| 1 | //! Account-owned remote control for the active TUI session. |
| 2 | //! |
| 3 | //! This is deliberately a typed relay, not a remote shell. The control plane |
| 4 | //! may send prompts, approval decisions, and run-control requests for the exact |
| 5 | //! enrolled target. Provider credentials, paths, environment variables, and |
| 6 | //! arbitrary command strings never cross this boundary. |
| 7 | |
| 8 | use std::{ |
| 9 | collections::{BTreeMap, HashMap, HashSet}, |
| 10 | fs::File, |
| 11 | path::{Path, PathBuf}, |
| 12 | time::{Duration, Instant, SystemTime, UNIX_EPOCH}, |
| 13 | }; |
| 14 | |
| 15 | use reqwest::Url; |
| 16 | use reqwest::{Client, Method, StatusCode}; |
| 17 | use serde::{Deserialize, Serialize}; |
| 18 | use serde_json::{Value, json}; |
| 19 | use sha2::{Digest, Sha256}; |
| 20 | use tokio::sync::mpsc; |
| 21 | |
| 22 | use codewhale_models::{ContentBlock, Message}; |
| 23 | |
| 24 | use crate::runtime_chat_relay::{ |
| 25 | RuntimeChatControlScope, RuntimeChatProjection, RuntimeChatPrompt, RuntimeChatRelayHost, |
| 26 | }; |
| 27 | use codewhale_engine::{ |
| 28 | core::events::{Event as EngineEvent, TurnOutcomeStatus}, |
| 29 | git_status::normalize_observed_git_repo, |
| 30 | }; |
| 31 | |
| 32 | const PRODUCTION_CONTROL_PLANE: &str = "https://api.codewhale.net/"; |
| 33 | const ENROLLMENT_SECRET_SLOT: &str = "cwc-remote-control-enrollment-v1"; |
| 34 | /// Machine-stable device identity. It outlives individual enrollments so the |
| 35 | /// control plane can fold every folder enrolled from this terminal into one |
| 36 | /// computer instead of one row per `/rc`. |
| 37 | const DEVICE_IDENTITY_SECRET_SLOT: &str = "cwc-remote-control-device-v1"; |
| 38 | /// The only web origin whose session links the terminal will surface or open. |
| 39 | const APP_ORIGIN_HOST: &str = "app.codewhale.net"; |
| 40 | const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(25); |
| 41 | const SYNC_INTERVAL: Duration = Duration::from_millis(1_200); |
| 42 | const MAX_RESPONSE_BYTES: usize = 1024 * 1024; |
| 43 | const MAX_RUNS: usize = 64; |
| 44 | const MAX_COMMANDS: usize = 128; |
| 45 | const JS_MAX_SAFE_INTEGER: u64 = 9_007_199_254_740_991; |
| 46 | const MAX_RUNTIME_ENVELOPE_BYTES: usize = 128 * 1024; |
| 47 | const SNAPSHOT_ENVELOPE_BYTE_BUDGET: usize = 120 * 1024; |
| 48 | const MAX_SNAPSHOT_MESSAGES: usize = 64; |
| 49 | const MAX_SNAPSHOT_MESSAGE_CHARS: usize = 128 * 1024; |
| 50 | const MIN_TRUNCATED_MESSAGE_CHARS: usize = 32; |
| 51 | const MAX_REMOTE_ERROR_MESSAGE_BYTES: usize = 4 * 1024; |
| 52 | const RUNTIME_UPLOAD_RETRY_INTERVAL: Duration = Duration::from_millis(250); |
| 53 | const RUNTIME_UPLOAD_MAX_BACKOFF: Duration = Duration::from_secs(5); |
| 54 | const RUNTIME_CHAT_RELAY_PROTOCOL: &str = "codewhale.runtime-chat-relay.v1"; |
| 55 | const RUNTIME_CHAT_CATALOG_TIMESTAMP: &str = "1970-01-01T00:00:00Z"; |
| 56 | const CAPABILITIES: &[&str] = &["evidence-ledger", "fim", "git", "shell"]; |
| 57 | /// How long an aborted or failed relay keeps local input locked. Matches the |
| 58 | /// server-side runner lease expiry with margin; local input never returns |
| 59 | /// while the server could still consider a remote owner live. |
| 60 | const OWNERSHIP_LOCK_AFTER_FAILURE: Duration = Duration::from_secs(95); |
| 61 | /// Ceiling for draining unacknowledged runtime events during `/rc stop`. |
| 62 | /// Deliberately below `OWNERSHIP_LOCK_AFTER_FAILURE` so a failed drain still |
| 63 | /// resolves into the ownership-locked path before the lease question is moot. |
| 64 | const STOP_DRAIN_DEADLINE: Duration = Duration::from_secs(45); |
| 65 | const JOURNAL_SCHEMA_VERSION: u64 = 2; |
| 66 | const CLASSIC_SESSION_STATE_SCHEMA_VERSION: u64 = 3; |
| 67 | /// Hard bounds for the crash-recoverable unacknowledged-envelope journal. |
| 68 | const MAX_JOURNAL_EVENTS: usize = 256; |
| 69 | const MAX_JOURNAL_ENCODED_BYTES: usize = 4 * 1024 * 1024; |
| 70 | /// Capacity held back exclusively for integrity-critical envelopes (terminal |
| 71 | /// turn state, approvals, failures, resynchronization snapshots). Ordinary |
| 72 | /// deltas may never consume this headroom. |
| 73 | const JOURNAL_RESERVED_INTEGRITY_EVENTS: usize = 64; |
| 74 | const JOURNAL_RESERVED_INTEGRITY_BYTES: usize = 1024 * 1024; |
| 75 | /// A deferred (not yet handed to transport) delta envelope may grow to this |
| 76 | /// encoded size through coalescing before it is forced onto the wire. |
| 77 | const DELTA_COALESCE_BYTE_CAP: usize = 32 * 1024; |
| 78 | const JOURNAL_SETUP_ERROR: &str = "Remote control could not prepare its private delivery journal."; |
| 79 | const JOURNAL_UNTRUSTED_ERROR: &str = "The saved remote-control delivery journal could not be trusted; it was set aside. The account run may show an incomplete turn."; |
| 80 | const JOURNAL_LEGACY_SCOPE_ERROR: &str = "A saved legacy remote-control delivery journal is not bound to this workspace and cannot be replayed safely; it was preserved for explicit recovery."; |
| 81 | const CLASSIC_LEASE_SCOPE_ERROR: &str = "This saved session still owns an unfinished account turn in its original workspace; reconnect that workspace or create a new local session."; |
| 82 | const OWNER_LOST_ERROR: &str = "Remote control lost its local delivery transaction owner."; |
| 83 | |
| 84 | #[cfg(test)] |
| 85 | static TEST_JOURNAL_PERSIST_FAILURES: std::sync::Mutex<Vec<(PathBuf, usize)>> = |
| 86 | std::sync::Mutex::new(Vec::new()); |
| 87 | |
| 88 | #[cfg(test)] |
| 89 | fn inject_journal_persist_failures(path: &Path, count: usize) { |
| 90 | assert!(count > 0); |
| 91 | TEST_JOURNAL_PERSIST_FAILURES |
| 92 | .lock() |
| 93 | .unwrap_or_else(std::sync::PoisonError::into_inner) |
| 94 | .push((path.to_path_buf(), count)); |
| 95 | } |
| 96 | |
| 97 | #[cfg(test)] |
| 98 | fn take_journal_persist_failure(path: &Path) -> bool { |
| 99 | let mut failures = TEST_JOURNAL_PERSIST_FAILURES |
| 100 | .lock() |
| 101 | .unwrap_or_else(std::sync::PoisonError::into_inner); |
| 102 | let Some(index) = failures.iter().position(|(target, _)| target == path) else { |
| 103 | return false; |
| 104 | }; |
| 105 | if failures[index].1 > 1 { |
| 106 | failures[index].1 -= 1; |
| 107 | } else { |
| 108 | failures.remove(index); |
| 109 | } |
| 110 | true |
| 111 | } |
| 112 | |
| 113 | /// Envelopes whose loss would strand account-side truth: terminal turn state, |
| 114 | /// approval requests, failure records, and resynchronization snapshots. They |
| 115 | /// draw on reserved journal capacity, are never dropped silently, and gate |
| 116 | /// `/rc stop` until the server cursor covers them. |
| 117 | fn integrity_critical_event(event: &str) -> bool { |
| 118 | matches!( |
| 119 | event, |
| 120 | "turn.completed" |
| 121 | | "review.completed" |
| 122 | | "approval.required" |
| 123 | | "approval.resolved" |
| 124 | | "item.failed" |
| 125 | | "session.snapshot" |
| 126 | | "runtime.catalog" |
| 127 | ) |
| 128 | } |
| 129 | |
| 130 | fn runtime_envelope_event(envelope: &Value) -> Option<&str> { |
| 131 | envelope.get("event").and_then(Value::as_str) |
| 132 | } |
| 133 | |
| 134 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 135 | pub enum RemoteControlAction { |
| 136 | Start, |
| 137 | Stop, |
| 138 | } |
| 139 | |
| 140 | #[derive(Clone)] |
| 141 | pub struct RemoteStart { |
| 142 | pub workspace_label: String, |
| 143 | pub target_ref: String, |
| 144 | pub session_id: String, |
| 145 | pub runtime_version: String, |
| 146 | pub runtime_commit: String, |
| 147 | /// Directory that holds the crash-recoverable delivery journal. `None` |
| 148 | /// runs memory-only and is reserved for tests; production callers must |
| 149 | /// always provide a private directory under the Codewhale home. |
| 150 | pub journal_dir: Option<PathBuf>, |
| 151 | /// Observed `owner/name` from `git remote get-url origin`, when the folder |
| 152 | /// is a Git checkout. This is a display receipt, never a path or GitHub App |
| 153 | /// grant. |
| 154 | pub git_remote: Option<String>, |
| 155 | } |
| 156 | |
| 157 | #[derive(Debug, Clone)] |
| 158 | pub enum RemoteEvent { |
| 159 | Notice(String), |
| 160 | Connected { |
| 161 | account_ref: String, |
| 162 | runner_id: String, |
| 163 | target_ref: String, |
| 164 | attachment: RemoteAttachment, |
| 165 | links: RemoteLinks, |
| 166 | }, |
| 167 | Attachment { |
| 168 | account_ref: String, |
| 169 | target_ref: String, |
| 170 | attachment: RemoteAttachment, |
| 171 | links: RemoteLinks, |
| 172 | }, |
| 173 | RuntimeCursor { |
| 174 | run_id: String, |
| 175 | cursor: u64, |
| 176 | }, |
| 177 | Command { |
| 178 | run_id: String, |
| 179 | seq: u64, |
| 180 | command: RemoteCommand, |
| 181 | }, |
| 182 | RuntimeChatProjection(RuntimeChatProjection), |
| 183 | /// Internal handoff receipt: the connected worker has dropped its clone |
| 184 | /// of the old immutable Runtime Chat host, so the controller can safely |
| 185 | /// reopen the same durable scope with a freshly supplied provider config. |
| 186 | RuntimeChatHostReleased, |
| 187 | Failed(String), |
| 188 | /// The relay died before any server-confirmed lease existed — during |
| 189 | /// enrollment, device authorization, or the first connect. No lease can |
| 190 | /// still be live, so nothing is locked and `/rc` can retry immediately. |
| 191 | FailedPreLease(String), |
| 192 | Stopped, |
| 193 | OwnershipRestored { |
| 194 | approvals: Vec<PendingRemoteApproval>, |
| 195 | }, |
| 196 | } |
| 197 | |
| 198 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 199 | pub struct RemoteAttachment { |
| 200 | pub run_id: String, |
| 201 | pub workspace_id: String, |
| 202 | pub runtime_cursor: u64, |
| 203 | pub snapshot_present: bool, |
| 204 | pub runtime_chat_relay_protocol: String, |
| 205 | pub runtime_chat_relay_challenge: String, |
| 206 | } |
| 207 | |
| 208 | /// Web links the control plane advertises for the attached session. Both are |
| 209 | /// optional: an older control plane omits them and the terminal then simply |
| 210 | /// shows no link. Links are validated against the Codewhale app origin before |
| 211 | /// they are ever displayed or opened; the terminal never invents one. |
| 212 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 213 | pub struct RemoteLinks { |
| 214 | /// `https://app.codewhale.net/session?run=<runId>` for the live run. |
| 215 | pub run_url: Option<String>, |
| 216 | /// `https://app.codewhale.net/settings?section=workspaces` for this computer. |
| 217 | pub computer_url: Option<String>, |
| 218 | } |
| 219 | |
| 220 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 221 | struct RunnerConnection { |
| 222 | runner_id: String, |
| 223 | attachment: RemoteAttachment, |
| 224 | links: RemoteLinks, |
| 225 | } |
| 226 | |
| 227 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 228 | pub enum RemoteCommand { |
| 229 | Prompt { |
| 230 | turn_id: String, |
| 231 | prompt: String, |
| 232 | }, |
| 233 | RuntimeChatPrompt(Box<RuntimeChatPrompt>), |
| 234 | Approval { |
| 235 | gate: String, |
| 236 | approved: bool, |
| 237 | }, |
| 238 | Control { |
| 239 | action: RemoteControlRequest, |
| 240 | turn_id: Option<String>, |
| 241 | runtime_chat: Option<RuntimeChatControlScope>, |
| 242 | }, |
| 243 | } |
| 244 | |
| 245 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 246 | pub enum RemoteControlRequest { |
| 247 | Interrupt, |
| 248 | Cancel, |
| 249 | } |
| 250 | |
| 251 | enum RelayPhase { |
| 252 | /// Everything before the first server-confirmed lease: control-plane base |
| 253 | /// resolution, enrollment, device authorization, and the first connect. |
| 254 | Enrolling, |
| 255 | /// The server confirmed a lease (Connected was emitted). Any failure now |
| 256 | /// is a lost-after-lease disconnect and stays fail-closed. |
| 257 | Leased, |
| 258 | } |
| 259 | |
| 260 | impl RelayPhase { |
| 261 | fn lease_confirmed(&self) -> bool { |
| 262 | matches!(self, Self::Leased) |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | #[derive(Clone)] |
| 267 | enum WorkerCommand { |
| 268 | Upload { |
| 269 | run_id: String, |
| 270 | acknowledgements: Vec<CommandAcknowledgement>, |
| 271 | envelopes: Vec<Value>, |
| 272 | }, |
| 273 | ReleaseRuntimeChatHost, |
| 274 | InstallRuntimeChatHost(RuntimeChatRelayHost), |
| 275 | Stop, |
| 276 | } |
| 277 | |
| 278 | struct PendingRuntimeChatConfiguration { |
| 279 | config: codewhale_runtime::config::Config, |
| 280 | plugin_registry: std::sync::Arc<codewhale_plugins::PluginRegistry>, |
| 281 | private_root: PathBuf, |
| 282 | target_ref: String, |
| 283 | session_id: String, |
| 284 | } |
| 285 | |
| 286 | #[derive(Debug, Default)] |
| 287 | struct RuntimeTransportOutbox { |
| 288 | events: BTreeMap<(String, u64), Value>, |
| 289 | } |
| 290 | |
| 291 | /// One unacknowledged runtime envelope owned by the controller. |
| 292 | /// |
| 293 | /// `handed_off` records whether the envelope may already have reached the |
| 294 | /// server through the transport worker. Once true the envelope is immutable: |
| 295 | /// ambiguous retries must resend byte-identical JSON. |
| 296 | #[derive(Debug, Clone, PartialEq)] |
| 297 | struct PendingRuntimeEnvelope { |
| 298 | envelope: Value, |
| 299 | encoded_len: usize, |
| 300 | integrity: bool, |
| 301 | handed_off: bool, |
| 302 | } |
| 303 | |
| 304 | /// Crash-recoverable journal of unacknowledged runtime envelopes. |
| 305 | /// |
| 306 | /// The file name is hash-derived so nothing about the workspace or session |
| 307 | /// leaks through the path; the directory is private and the file owner-only. |
| 308 | /// Neither the path nor the contents are ever reported to the control plane |
| 309 | /// or written to logs. Acknowledged prefixes are compacted on every persist, |
| 310 | /// and a journal that cannot be verified fails closed at load time. |
| 311 | struct RuntimeEventJournal { |
| 312 | path: PathBuf, |
| 313 | scope_tag: String, |
| 314 | legacy_path: PathBuf, |
| 315 | legacy_unscoped_path: PathBuf, |
| 316 | active_index_path: PathBuf, |
| 317 | classic_lease: parking_lot::Mutex<Option<ClassicRunLease>>, |
| 318 | _classic_session_lock: ClassicSessionOwnerLock, |
| 319 | } |
| 320 | |
| 321 | #[derive(Debug)] |
| 322 | struct ClassicSessionOwnerLock { |
| 323 | _file: File, |
| 324 | } |
| 325 | |
| 326 | impl ClassicSessionOwnerLock { |
| 327 | fn acquire(path: &Path) -> Result<Self, String> { |
| 328 | let mut options = std::fs::OpenOptions::new(); |
| 329 | options.create(true).read(true).write(true); |
| 330 | #[cfg(unix)] |
| 331 | { |
| 332 | use std::os::unix::fs::OpenOptionsExt as _; |
| 333 | options.mode(0o600).custom_flags(libc::O_NOFOLLOW); |
| 334 | } |
| 335 | let file = options |
| 336 | .open(path) |
| 337 | .map_err(|_| JOURNAL_SETUP_ERROR.to_string())?; |
| 338 | #[cfg(unix)] |
| 339 | { |
| 340 | use std::os::fd::AsRawFd as _; |
| 341 | // SAFETY: `file` is open and live. |
| 342 | if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } != 0 { |
| 343 | return Err(CLASSIC_LEASE_SCOPE_ERROR.to_string()); |
| 344 | } |
| 345 | } |
| 346 | #[cfg(windows)] |
| 347 | { |
| 348 | use std::os::windows::io::AsRawHandle as _; |
| 349 | use windows_sys::Win32::Storage::FileSystem::LockFile; |
| 350 | // SAFETY: `file` is open and live. |
| 351 | if unsafe { LockFile(file.as_raw_handle() as _, 0, 0, u32::MAX, u32::MAX) } == 0 { |
| 352 | return Err(CLASSIC_LEASE_SCOPE_ERROR.to_string()); |
| 353 | } |
| 354 | } |
| 355 | Ok(Self { _file: file }) |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | impl Drop for ClassicSessionOwnerLock { |
| 360 | fn drop(&mut self) { |
| 361 | // close() alone does not release the lock while a descriptor |
| 362 | // duplicated into a child spawned between fork and exec still shares |
| 363 | // this open file description; unlocking first lets a same-process |
| 364 | // reopen proceed (#5735, #6698), as the relay and runtime store locks do. |
| 365 | #[cfg(unix)] |
| 366 | { |
| 367 | use std::os::fd::AsRawFd as _; |
| 368 | // SAFETY: Drop runs only while `_file` still owns this descriptor. |
| 369 | unsafe { |
| 370 | libc::flock(self._file.as_raw_fd(), libc::LOCK_UN); |
| 371 | } |
| 372 | } |
| 373 | #[cfg(windows)] |
| 374 | { |
| 375 | use std::os::windows::io::AsRawHandle as _; |
| 376 | use windows_sys::Win32::Storage::FileSystem::UnlockFile; |
| 377 | // SAFETY: Drop runs only while `_file` still owns this handle. |
| 378 | unsafe { |
| 379 | UnlockFile(self._file.as_raw_handle() as _, 0, 0, u32::MAX, u32::MAX); |
| 380 | } |
| 381 | } |
| 382 | } |
| 383 | } |
| 384 | |
| 385 | fn runtime_journal_scope_tag(target_ref: &str, session_id: &str) -> String { |
| 386 | let mut hasher = Sha256::new(); |
| 387 | hasher.update(b"cwc-remote-control-journal.v2\0"); |
| 388 | hasher.update(target_ref.as_bytes()); |
| 389 | hasher.update(b"\0"); |
| 390 | hasher.update(session_id.as_bytes()); |
| 391 | bytes_to_hex(&hasher.finalize())[..32].to_string() |
| 392 | } |
| 393 | |
| 394 | fn runtime_journal_session_tag(session_id: &str) -> String { |
| 395 | let mut hasher = Sha256::new(); |
| 396 | hasher.update(b"cwc-remote-control-journal\0"); |
| 397 | hasher.update(session_id.as_bytes()); |
| 398 | bytes_to_hex(&hasher.finalize())[..32].to_string() |
| 399 | } |
| 400 | |
| 401 | fn classic_recovery_turn_id(run_id: &str, lease_id: &str) -> String { |
| 402 | let mut hasher = Sha256::new(); |
| 403 | hasher.update(b"codewhale.classic-recovery-turn.v1\0"); |
| 404 | hasher.update(run_id.as_bytes()); |
| 405 | hasher.update(b"\0"); |
| 406 | hasher.update(lease_id.as_bytes()); |
| 407 | format!("turn_recovered_{}", &bytes_to_hex(&hasher.finalize())[..24]) |
| 408 | } |
| 409 | |
| 410 | impl RuntimeEventJournal { |
| 411 | fn open(dir: &Path, target_ref: &str, session_id: &str) -> Result<Self, String> { |
| 412 | let scope_tag = runtime_journal_scope_tag(target_ref, session_id); |
| 413 | let legacy_session_tag = runtime_journal_session_tag(session_id); |
| 414 | std::fs::create_dir_all(dir).map_err(|_| JOURNAL_SETUP_ERROR.to_string())?; |
| 415 | #[cfg(unix)] |
| 416 | // Journal files are written owner-only; the directory narrows to 0o700 |
| 417 | // where the filesystem stores modes. A mount that assigns modes itself |
| 418 | // (HarmonyOS hmdfs) refuses the call, and `tighten_mode` tolerates only |
| 419 | // that case — refusing here would disable the recoverable-turn journal |
| 420 | // on a platform where no directory can ever satisfy the chmod. |
| 421 | codewhale_config::private_directory::tighten_mode(dir, 0o700) |
| 422 | .map_err(|_| JOURNAL_SETUP_ERROR.to_string())?; |
| 423 | let legacy_path = dir.join(format!("journal_{legacy_session_tag}.json")); |
| 424 | let active_index_path = dir.join(format!("active_classic_{legacy_session_tag}.json")); |
| 425 | let classic_session_lock = |
| 426 | ClassicSessionOwnerLock::acquire(&active_index_path.with_extension("lock"))?; |
| 427 | if !active_index_path.exists() |
| 428 | && (legacy_path.exists() || legacy_path.with_extension("unscoped").exists()) |
| 429 | { |
| 430 | return Err(JOURNAL_LEGACY_SCOPE_ERROR.to_string()); |
| 431 | } |
| 432 | let journal = Self { |
| 433 | path: dir.join(format!("journal_{scope_tag}.json")), |
| 434 | scope_tag, |
| 435 | legacy_unscoped_path: legacy_path.with_extension("unscoped"), |
| 436 | legacy_path, |
| 437 | active_index_path, |
| 438 | classic_lease: parking_lot::Mutex::new(None), |
| 439 | _classic_session_lock: classic_session_lock, |
| 440 | }; |
| 441 | if journal.active_index_path.exists() { |
| 442 | let lease = journal.read_active_index()?; |
| 443 | *journal.classic_lease.lock() = lease; |
| 444 | } else { |
| 445 | journal.write_active_index(None)?; |
| 446 | } |
| 447 | Ok(journal) |
| 448 | } |
| 449 | |
| 450 | /// Loads every journaled envelope, or fails closed when the journal |
| 451 | /// cannot be trusted (corrupt, oversized, or written for another |
| 452 | /// session). A missing file is an ordinary empty journal. |
| 453 | fn load(&self) -> Result<HashMap<String, BTreeMap<u64, Value>>, String> { |
| 454 | let bytes = match std::fs::read(&self.path) { |
| 455 | Ok(bytes) => bytes, |
| 456 | Err(error) if error.kind() == std::io::ErrorKind::NotFound => { |
| 457 | if self.legacy_path.exists() || self.legacy_unscoped_path.exists() { |
| 458 | // Schema 1 authenticated only a session id. The same |
| 459 | // saved session can be opened from another target, so its |
| 460 | // envelopes cannot be relabelled into this v2 |
| 461 | // target+session scope without server-side ownership |
| 462 | // proof. Preserve it and fail closed. |
| 463 | return Err(JOURNAL_LEGACY_SCOPE_ERROR.to_string()); |
| 464 | } |
| 465 | return Ok(HashMap::new()); |
| 466 | } |
| 467 | Err(_) => return Err(JOURNAL_UNTRUSTED_ERROR.to_string()), |
| 468 | }; |
| 469 | if bytes.len() > MAX_JOURNAL_ENCODED_BYTES.saturating_mul(2) { |
| 470 | return Err(JOURNAL_UNTRUSTED_ERROR.to_string()); |
| 471 | } |
| 472 | let value: Value = |
| 473 | serde_json::from_slice(&bytes).map_err(|_| JOURNAL_UNTRUSTED_ERROR.to_string())?; |
| 474 | let identity_valid = value.get("schemaVersion").and_then(Value::as_u64) |
| 475 | == Some(JOURNAL_SCHEMA_VERSION) |
| 476 | && value.get("scope").and_then(Value::as_str) == Some(self.scope_tag.as_str()); |
| 477 | if !identity_valid { |
| 478 | return Err(JOURNAL_UNTRUSTED_ERROR.to_string()); |
| 479 | } |
| 480 | let runs = value |
| 481 | .get("runs") |
| 482 | .and_then(Value::as_object) |
| 483 | .ok_or_else(|| JOURNAL_UNTRUSTED_ERROR.to_string())?; |
| 484 | let mut restored: HashMap<String, BTreeMap<u64, Value>> = HashMap::new(); |
| 485 | let mut total_events = 0usize; |
| 486 | let mut total_bytes = 0usize; |
| 487 | for (run_id, envelopes) in runs { |
| 488 | if !valid_opaque_ref(run_id) { |
| 489 | return Err(JOURNAL_UNTRUSTED_ERROR.to_string()); |
| 490 | } |
| 491 | let envelopes = envelopes |
| 492 | .as_array() |
| 493 | .ok_or_else(|| JOURNAL_UNTRUSTED_ERROR.to_string())?; |
| 494 | let mut events = BTreeMap::new(); |
| 495 | for envelope in envelopes { |
| 496 | let seq = runtime_envelope_seq(envelope) |
| 497 | .ok_or_else(|| JOURNAL_UNTRUSTED_ERROR.to_string())?; |
| 498 | let encoded_len = serde_json::to_vec(envelope) |
| 499 | .map(|body| body.len()) |
| 500 | .unwrap_or(usize::MAX); |
| 501 | if encoded_len > MAX_RUNTIME_ENVELOPE_BYTES { |
| 502 | return Err(JOURNAL_UNTRUSTED_ERROR.to_string()); |
| 503 | } |
| 504 | total_events += 1; |
| 505 | total_bytes = total_bytes.saturating_add(encoded_len); |
| 506 | if total_events > MAX_JOURNAL_EVENTS || total_bytes > MAX_JOURNAL_ENCODED_BYTES { |
| 507 | return Err(JOURNAL_UNTRUSTED_ERROR.to_string()); |
| 508 | } |
| 509 | if events.insert(seq, envelope.clone()).is_some() { |
| 510 | return Err(JOURNAL_UNTRUSTED_ERROR.to_string()); |
| 511 | } |
| 512 | } |
| 513 | if !events.is_empty() { |
| 514 | restored.insert(run_id.clone(), events); |
| 515 | } |
| 516 | } |
| 517 | Ok(restored) |
| 518 | } |
| 519 | |
| 520 | /// Atomically replaces the journal with the current unacknowledged set. |
| 521 | /// An empty set removes the file entirely (prompt compaction). |
| 522 | fn persist( |
| 523 | &self, |
| 524 | pending: &HashMap<String, BTreeMap<u64, PendingRuntimeEnvelope>>, |
| 525 | ) -> Result<(), String> { |
| 526 | #[cfg(test)] |
| 527 | if take_journal_persist_failure(&self.path) { |
| 528 | return Err(JOURNAL_SETUP_ERROR.to_string()); |
| 529 | } |
| 530 | let classic_lease = self.classic_lease.lock().clone(); |
| 531 | if pending.values().all(BTreeMap::is_empty) && classic_lease.is_none() { |
| 532 | self.remove(); |
| 533 | return Ok(()); |
| 534 | } |
| 535 | let mut runs = serde_json::Map::new(); |
| 536 | for (run_id, events) in pending { |
| 537 | if events.is_empty() { |
| 538 | continue; |
| 539 | } |
| 540 | runs.insert( |
| 541 | run_id.clone(), |
| 542 | Value::Array( |
| 543 | events |
| 544 | .values() |
| 545 | .map(|entry| entry.envelope.clone()) |
| 546 | .collect(), |
| 547 | ), |
| 548 | ); |
| 549 | } |
| 550 | let body = serde_json::to_vec(&json!({ |
| 551 | "schemaVersion": JOURNAL_SCHEMA_VERSION, |
| 552 | "scope": self.scope_tag, |
| 553 | "runs": runs, |
| 554 | })) |
| 555 | .map_err(|_| JOURNAL_SETUP_ERROR.to_string())?; |
| 556 | codewhale_util::utils::write_atomic(&self.path, &body) |
| 557 | .map_err(|_| JOURNAL_SETUP_ERROR.to_string()) |
| 558 | } |
| 559 | |
| 560 | fn remove(&self) { |
| 561 | if self.classic_lease.lock().is_some() { |
| 562 | return; |
| 563 | } |
| 564 | let _ = std::fs::remove_file(&self.path); |
| 565 | let _ = std::fs::remove_file(self.path.with_extension("tmp")); |
| 566 | } |
| 567 | |
| 568 | /// Moves an untrusted journal aside so the failure is explicit and a |
| 569 | /// deliberate later `/rc` start can proceed from a clean slate. |
| 570 | fn quarantine_current(&self) { |
| 571 | let _ = std::fs::rename(&self.path, self.path.with_extension("corrupt")); |
| 572 | } |
| 573 | |
| 574 | fn quarantine_legacy(&self) { |
| 575 | if self.legacy_path.exists() { |
| 576 | let _ = std::fs::rename(&self.legacy_path, &self.legacy_unscoped_path); |
| 577 | } |
| 578 | } |
| 579 | |
| 580 | fn classic_lease(&self) -> Option<ClassicRunLease> { |
| 581 | self.classic_lease.lock().clone() |
| 582 | } |
| 583 | |
| 584 | fn read_active_index(&self) -> Result<Option<ClassicRunLease>, String> { |
| 585 | let bytes = std::fs::read(&self.active_index_path) |
| 586 | .map_err(|_| JOURNAL_UNTRUSTED_ERROR.to_string())?; |
| 587 | if bytes.len() > 2048 { |
| 588 | return Err(JOURNAL_UNTRUSTED_ERROR.to_string()); |
| 589 | } |
| 590 | let value: Value = |
| 591 | serde_json::from_slice(&bytes).map_err(|_| JOURNAL_UNTRUSTED_ERROR.to_string())?; |
| 592 | if value.get("schemaVersion").and_then(Value::as_u64) |
| 593 | != Some(CLASSIC_SESSION_STATE_SCHEMA_VERSION) |
| 594 | || value.get("scope").and_then(Value::as_str) != Some(self.scope_tag.as_str()) |
| 595 | { |
| 596 | return Err(CLASSIC_LEASE_SCOPE_ERROR.to_string()); |
| 597 | } |
| 598 | match value.get("lease") { |
| 599 | None | Some(Value::Null) => Ok(None), |
| 600 | Some(value) => { |
| 601 | let lease: ClassicRunLease = serde_json::from_value(value.clone()) |
| 602 | .map_err(|_| JOURNAL_UNTRUSTED_ERROR.to_string())?; |
| 603 | if !lease.valid() { |
| 604 | return Err(JOURNAL_UNTRUSTED_ERROR.to_string()); |
| 605 | } |
| 606 | Ok(Some(lease)) |
| 607 | } |
| 608 | } |
| 609 | } |
| 610 | |
| 611 | fn write_active_index(&self, lease: Option<&ClassicRunLease>) -> Result<(), String> { |
| 612 | #[cfg(test)] |
| 613 | if take_journal_persist_failure(&self.active_index_path) { |
| 614 | return Err(JOURNAL_SETUP_ERROR.to_string()); |
| 615 | } |
| 616 | let index = serde_json::to_vec(&json!({ |
| 617 | "schemaVersion": CLASSIC_SESSION_STATE_SCHEMA_VERSION, |
| 618 | "scope": self.scope_tag, |
| 619 | "lease": lease, |
| 620 | })) |
| 621 | .map_err(|_| JOURNAL_SETUP_ERROR.to_string())?; |
| 622 | codewhale_util::utils::write_atomic(&self.active_index_path, &index) |
| 623 | .map_err(|_| JOURNAL_SETUP_ERROR.to_string()) |
| 624 | } |
| 625 | |
| 626 | fn set_classic_lease( |
| 627 | &self, |
| 628 | lease: Option<ClassicRunLease>, |
| 629 | pending: &HashMap<String, BTreeMap<u64, PendingRuntimeEnvelope>>, |
| 630 | ) -> Result<(), String> { |
| 631 | let previous = self.classic_lease.lock().clone(); |
| 632 | let indexed = self.read_active_index()?; |
| 633 | if indexed != previous { |
| 634 | return Err(CLASSIC_LEASE_SCOPE_ERROR.to_string()); |
| 635 | } |
| 636 | *self.classic_lease.lock() = lease.clone(); |
| 637 | if let Err(error) = self.persist(pending) { |
| 638 | *self.classic_lease.lock() = previous; |
| 639 | return Err(error); |
| 640 | } |
| 641 | if let Err(error) = self.write_active_index(lease.as_ref()) { |
| 642 | *self.classic_lease.lock() = previous.clone(); |
| 643 | let journal_rollback = self.persist(pending); |
| 644 | let index_rollback = self.write_active_index(previous.as_ref()); |
| 645 | match (journal_rollback, index_rollback) { |
| 646 | (Ok(()), Ok(())) => return Err(error), |
| 647 | (Err(journal_err), Ok(())) => { |
| 648 | tracing::error!( |
| 649 | %journal_err, |
| 650 | %error, |
| 651 | "journal rollback failed; durable lease state may be inconsistent" |
| 652 | ); |
| 653 | return Err(format!( |
| 654 | "{error} Journal rollback also failed: {journal_err}" |
| 655 | )); |
| 656 | } |
| 657 | (Ok(()), Err(index_err)) => { |
| 658 | tracing::error!( |
| 659 | %index_err, |
| 660 | %error, |
| 661 | "active-index rollback failed; durable lease state may be inconsistent" |
| 662 | ); |
| 663 | return Err(format!( |
| 664 | "{error} Active-index rollback also failed: {index_err}" |
| 665 | )); |
| 666 | } |
| 667 | (Err(journal_err), Err(index_err)) => { |
| 668 | tracing::error!( |
| 669 | %journal_err, |
| 670 | %index_err, |
| 671 | %error, |
| 672 | "journal and active-index rollback failed; durable lease state may be inconsistent" |
| 673 | ); |
| 674 | return Err(format!( |
| 675 | "{error} Journal rollback ({journal_err}) and active-index rollback ({index_err}) also failed" |
| 676 | )); |
| 677 | } |
| 678 | } |
| 679 | } |
| 680 | Ok(()) |
| 681 | } |
| 682 | |
| 683 | /// Advances the canonical sequence floor for the active classic Work run. |
| 684 | /// |
| 685 | /// The target journal can compact an acknowledged prefix, so the |
| 686 | /// session-wide lease must retain the highest server/local sequence while |
| 687 | /// a provider turn is still active. Recovery uses this floor before it |
| 688 | /// synthesizes a terminal event and can therefore never reuse a sequence |
| 689 | /// the server already acknowledged. |
| 690 | fn advance_classic_seq_floor(&self, run_id: &str, seq: u64) -> Result<(), String> { |
| 691 | let Some(mut lease) = self.classic_lease.lock().clone() else { |
| 692 | return Ok(()); |
| 693 | }; |
| 694 | if lease.run_id != run_id || seq <= lease.seq_floor { |
| 695 | return Ok(()); |
| 696 | } |
| 697 | let indexed = self.read_active_index()?; |
| 698 | if indexed.as_ref() != self.classic_lease.lock().as_ref() { |
| 699 | return Err(CLASSIC_LEASE_SCOPE_ERROR.to_string()); |
| 700 | } |
| 701 | lease.seq_floor = seq; |
| 702 | self.write_active_index(Some(&lease))?; |
| 703 | *self.classic_lease.lock() = Some(lease); |
| 704 | Ok(()) |
| 705 | } |
| 706 | } |
| 707 | |
| 708 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 709 | enum RuntimePostOutcome { |
| 710 | Accepted(u64), |
| 711 | Retryable, |
| 712 | AccessTokenExpired, |
| 713 | } |
| 714 | |
| 715 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 716 | enum RuntimeFlushOutcome { |
| 717 | Idle, |
| 718 | Accepted { run_id: String, cursor: u64 }, |
| 719 | Retryable, |
| 720 | AccessTokenExpired, |
| 721 | } |
| 722 | |
| 723 | #[derive(Debug, Clone, Serialize)] |
| 724 | #[serde(rename_all = "camelCase")] |
| 725 | struct CommandAcknowledgement { |
| 726 | command_seq: u64, |
| 727 | command_type: String, |
| 728 | status: String, |
| 729 | #[serde(skip_serializing_if = "Option::is_none")] |
| 730 | turn_id: Option<String>, |
| 731 | #[serde(skip_serializing_if = "Option::is_none")] |
| 732 | error: Option<String>, |
| 733 | } |
| 734 | |
| 735 | #[derive(Clone, Deserialize, Serialize)] |
| 736 | #[serde(rename_all = "camelCase", deny_unknown_fields)] |
| 737 | struct PersistedEnrollment { |
| 738 | schema_version: u64, |
| 739 | control_plane_base: String, |
| 740 | runner_enrollment_id: String, |
| 741 | account_ref: String, |
| 742 | device_id: String, |
| 743 | target_ref: String, |
| 744 | target_grant_ref: String, |
| 745 | runtime_version: String, |
| 746 | runtime_commit: String, |
| 747 | bootstrap_secret: String, |
| 748 | } |
| 749 | |
| 750 | /// The machine-stable device identity persisted independently of any |
| 751 | /// enrollment. Enrollments are deleted and re-created when the target or |
| 752 | /// runtime changes; this record is only ever created once per keychain. |
| 753 | #[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] |
| 754 | #[serde(rename_all = "camelCase", deny_unknown_fields)] |
| 755 | struct PersistedDeviceIdentity { |
| 756 | schema_version: u64, |
| 757 | device_id: String, |
| 758 | } |
| 759 | |
| 760 | impl PersistedDeviceIdentity { |
| 761 | fn valid(&self) -> bool { |
| 762 | self.schema_version == 1 && valid_opaque_ref(&self.device_id) |
| 763 | } |
| 764 | } |
| 765 | |
| 766 | /// Pick the device id this terminal presents to the control plane. A valid |
| 767 | /// saved identity always wins; otherwise the device id of an existing |
| 768 | /// enrollment is adopted (so upgrading terminals keep their computer row); |
| 769 | /// otherwise a fresh id is minted. Returns the id and whether it must be |
| 770 | /// saved. |
| 771 | fn resolve_device_identity( |
| 772 | saved: Option<PersistedDeviceIdentity>, |
| 773 | enrollment_device_id: Option<&str>, |
| 774 | ) -> (String, bool) { |
| 775 | if let Some(saved) = saved.filter(PersistedDeviceIdentity::valid) { |
| 776 | return (saved.device_id, false); |
| 777 | } |
| 778 | if let Some(existing) = enrollment_device_id.filter(|value| valid_opaque_ref(value)) { |
| 779 | return (existing.to_string(), true); |
| 780 | } |
| 781 | (format!("device_{}", uuid::Uuid::new_v4().simple()), true) |
| 782 | } |
| 783 | |
| 784 | #[derive(Clone)] |
| 785 | struct LiveEnrollment { |
| 786 | persisted: PersistedEnrollment, |
| 787 | access_token: String, |
| 788 | } |
| 789 | |
| 790 | #[derive(Debug, Clone)] |
| 791 | struct ActiveRelayRun { |
| 792 | run_id: String, |
| 793 | turn_id: String, |
| 794 | } |
| 795 | |
| 796 | #[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] |
| 797 | #[serde(rename_all = "camelCase", deny_unknown_fields)] |
| 798 | struct ClassicRunLease { |
| 799 | run_id: String, |
| 800 | turn_id: Option<String>, |
| 801 | lease_id: String, |
| 802 | seq_floor: u64, |
| 803 | } |
| 804 | |
| 805 | impl ClassicRunLease { |
| 806 | fn valid(&self) -> bool { |
| 807 | valid_opaque_ref(&self.run_id) |
| 808 | && self.turn_id.as_deref().is_none_or(valid_opaque_ref) |
| 809 | && valid_opaque_ref(&self.lease_id) |
| 810 | && self.seq_floor <= JS_MAX_SAFE_INTEGER |
| 811 | } |
| 812 | } |
| 813 | |
| 814 | #[derive(Debug, Clone)] |
| 815 | pub struct PendingRemoteApproval { |
| 816 | pub tool_id: String, |
| 817 | } |
| 818 | |
| 819 | #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] |
| 820 | pub enum Status { |
| 821 | #[default] |
| 822 | Off, |
| 823 | Connecting, |
| 824 | Connected, |
| 825 | Stopping, |
| 826 | Failed, |
| 827 | } |
| 828 | |
| 829 | /// UI-thread owner for remote-control state and typed transport channels. |
| 830 | pub struct RemoteControlController { |
| 831 | status: Status, |
| 832 | status_detail: String, |
| 833 | account_ref: Option<String>, |
| 834 | target_ref: Option<String>, |
| 835 | links: RemoteLinks, |
| 836 | /// Latest server-confirmed run attachment. Kept separately from |
| 837 | /// `active_run`: an attachment can exist while the session is idle, and a |
| 838 | /// mid-turn `/rc` can bind the already-running local turn to it without |
| 839 | /// inventing a second prompt. |
| 840 | attached_run_id: Option<String>, |
| 841 | attached_workspace_id: Option<String>, |
| 842 | active_run: Option<ActiveRelayRun>, |
| 843 | /// A local dispatch that was already in flight when the web attachment |
| 844 | /// became ready, but whose typed `TurnStarted` event has not landed yet. |
| 845 | /// The first such event promotes this exact run into `active_run`. |
| 846 | pending_local_turn_run: Option<String>, |
| 847 | event_seq: HashMap<String, u64>, |
| 848 | uploaded_snapshots: HashSet<String>, |
| 849 | pending_runtime_events: HashMap<String, BTreeMap<u64, PendingRuntimeEnvelope>>, |
| 850 | pending_approvals: HashMap<String, PendingRemoteApproval>, |
| 851 | command_fingerprints: HashMap<(String, u64), String>, |
| 852 | worker_tx: Option<mpsc::UnboundedSender<WorkerCommand>>, |
| 853 | event_rx: Option<mpsc::UnboundedReceiver<RemoteEvent>>, |
| 854 | worker: Option<tokio::task::JoinHandle<()>>, |
| 855 | applying_remote_command: bool, |
| 856 | ownership_blocked_until: Option<Instant>, |
| 857 | journal: Option<RuntimeEventJournal>, |
| 858 | /// At most one deferred (unsent, still coalescible) delta seq per run. |
| 859 | deferred_delta: HashMap<String, u64>, |
| 860 | /// Runs whose deltas were shed under pressure; truth is restored with a |
| 861 | /// bounded snapshot at the next terminal boundary. |
| 862 | resync_required: HashSet<String>, |
| 863 | /// Runs that crossed their terminal boundary with `resync_required` set; |
| 864 | /// the UI drains these via `take_pending_resync`. |
| 865 | resync_ready: Vec<String>, |
| 866 | pending_event_count: usize, |
| 867 | pending_encoded_bytes: usize, |
| 868 | /// Separate native Runtime host for account Chat. It is configured by the |
| 869 | /// TUI composition root and never points at the current interactive turn. |
| 870 | runtime_chat: Option<RuntimeChatRelayHost>, |
| 871 | /// A same-scope reconnect may need the old immutable host long enough to |
| 872 | /// drain terminal/catalog rows behind the server cursor. New prompts stay |
| 873 | /// fail-closed while this fresh configuration waits for an acknowledged |
| 874 | /// boundary and a worker/controller host handoff. |
| 875 | pending_runtime_chat_configuration: Option<PendingRuntimeChatConfiguration>, |
| 876 | runtime_chat_refresh_release_requested: bool, |
| 877 | runtime_chat_attachment: Option<RemoteAttachment>, |
| 878 | uploaded_runtime_catalog_receipt: HashMap<String, String>, |
| 879 | } |
| 880 | |
| 881 | impl Default for RemoteControlController { |
| 882 | fn default() -> Self { |
| 883 | Self { |
| 884 | status: Status::Off, |
| 885 | status_detail: "off".to_string(), |
| 886 | account_ref: None, |
| 887 | target_ref: None, |
| 888 | links: RemoteLinks::default(), |
| 889 | attached_run_id: None, |
| 890 | attached_workspace_id: None, |
| 891 | active_run: None, |
| 892 | pending_local_turn_run: None, |
| 893 | event_seq: HashMap::new(), |
| 894 | uploaded_snapshots: HashSet::new(), |
| 895 | pending_runtime_events: HashMap::new(), |
| 896 | pending_approvals: HashMap::new(), |
| 897 | command_fingerprints: HashMap::new(), |
| 898 | worker_tx: None, |
| 899 | event_rx: None, |
| 900 | worker: None, |
| 901 | applying_remote_command: false, |
| 902 | ownership_blocked_until: None, |
| 903 | journal: None, |
| 904 | deferred_delta: HashMap::new(), |
| 905 | resync_required: HashSet::new(), |
| 906 | resync_ready: Vec::new(), |
| 907 | pending_event_count: 0, |
| 908 | pending_encoded_bytes: 0, |
| 909 | runtime_chat: None, |
| 910 | pending_runtime_chat_configuration: None, |
| 911 | runtime_chat_refresh_release_requested: false, |
| 912 | runtime_chat_attachment: None, |
| 913 | uploaded_runtime_catalog_receipt: HashMap::new(), |
| 914 | } |
| 915 | } |
| 916 | } |
| 917 | |
| 918 | fn blocking_owner_handle() -> Option<tokio::runtime::Handle> { |
| 919 | tokio::runtime::Handle::try_current() |
| 920 | .ok() |
| 921 | .filter(|handle| handle.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread) |
| 922 | } |
| 923 | |
| 924 | impl RemoteControlController { |
| 925 | async fn run_on_owner<T>( |
| 926 | &mut self, |
| 927 | work: impl FnOnce(&mut Self) -> T + Send + 'static, |
| 928 | ) -> Option<T> |
| 929 | where |
| 930 | T: Send + 'static, |
| 931 | { |
| 932 | let mut controller = std::mem::take(self); |
| 933 | let joined = tokio::task::spawn_blocking(move || { |
| 934 | let output = |
| 935 | std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| work(&mut controller))); |
| 936 | (controller, output) |
| 937 | }) |
| 938 | .await; |
| 939 | match joined { |
| 940 | Ok((controller, Ok(output))) => { |
| 941 | *self = controller; |
| 942 | Some(output) |
| 943 | } |
| 944 | Ok((controller, Err(payload))) => { |
| 945 | *self = controller; |
| 946 | std::panic::resume_unwind(payload) |
| 947 | } |
| 948 | Err(error) if error.is_panic() => std::panic::resume_unwind(error.into_panic()), |
| 949 | Err(_) => None, |
| 950 | } |
| 951 | } |
| 952 | |
| 953 | /// Acquires and validates the saved-session authority before any Runtime |
| 954 | /// Chat host/provider configuration is opened. |
| 955 | /// |
| 956 | /// The session-wide lifetime lock is intentionally acquired first. This |
| 957 | /// fixes the lock order across processes: a competing workspace cannot |
| 958 | /// make us release an existing Runtime store owner and only later discover |
| 959 | /// that the saved session is permanently bound elsewhere. |
| 960 | pub fn prepare_remote_control_session_journal( |
| 961 | &mut self, |
| 962 | dir: &Path, |
| 963 | target_ref: &str, |
| 964 | session_id: &str, |
| 965 | ) -> Result<(), String> { |
| 966 | let requested_scope = runtime_journal_scope_tag(target_ref, session_id); |
| 967 | let requested_session_path = dir.join(format!( |
| 968 | "active_classic_{}.json", |
| 969 | runtime_journal_session_tag(session_id) |
| 970 | )); |
| 971 | if let Some(current) = self.journal.as_ref() { |
| 972 | if current.active_index_path == requested_session_path { |
| 973 | if current.scope_tag != requested_scope { |
| 974 | return Err(CLASSIC_LEASE_SCOPE_ERROR.to_string()); |
| 975 | } |
| 976 | return Ok(()); |
| 977 | } |
| 978 | if self.has_active_run() || self.has_unacknowledged_integrity_events() { |
| 979 | return Err( |
| 980 | "The previous saved session still owns account delivery; reconnect it before opening another local session." |
| 981 | .to_string(), |
| 982 | ); |
| 983 | } |
| 984 | } |
| 985 | drop(self.journal.take()); |
| 986 | let journal = RuntimeEventJournal::open(dir, target_ref, session_id)?; |
| 987 | match journal.load() { |
| 988 | Ok(restored) => { |
| 989 | self.reset_pending_from(restored); |
| 990 | self.journal = Some(journal); |
| 991 | Ok(()) |
| 992 | } |
| 993 | Err(error) => { |
| 994 | if error == JOURNAL_LEGACY_SCOPE_ERROR { |
| 995 | journal.quarantine_legacy(); |
| 996 | } else { |
| 997 | journal.quarantine_current(); |
| 998 | } |
| 999 | Err(error) |
| 1000 | } |
| 1001 | } |
| 1002 | } |
| 1003 | |
| 1004 | pub async fn prepare_remote_control_session_journal_async( |
| 1005 | &mut self, |
| 1006 | dir: &Path, |
| 1007 | target_ref: &str, |
| 1008 | session_id: &str, |
| 1009 | ) -> Result<(), String> { |
| 1010 | let dir = dir.to_path_buf(); |
| 1011 | let target_ref = target_ref.to_string(); |
| 1012 | let session_id = session_id.to_string(); |
| 1013 | match self |
| 1014 | .run_on_owner(move |controller| { |
| 1015 | controller.prepare_remote_control_session_journal(&dir, &target_ref, &session_id) |
| 1016 | }) |
| 1017 | .await |
| 1018 | { |
| 1019 | Some(result) => result, |
| 1020 | None => Err(OWNER_LOST_ERROR.to_string()), |
| 1021 | } |
| 1022 | } |
| 1023 | |
| 1024 | pub async fn configure_runtime_chat_async( |
| 1025 | &mut self, |
| 1026 | config: codewhale_runtime::config::Config, |
| 1027 | plugin_registry: std::sync::Arc<codewhale_plugins::PluginRegistry>, |
| 1028 | private_root: PathBuf, |
| 1029 | target_ref: String, |
| 1030 | session_id: String, |
| 1031 | ) -> Result<(), String> { |
| 1032 | match self |
| 1033 | .run_on_owner(move |controller| { |
| 1034 | controller.configure_runtime_chat( |
| 1035 | config, |
| 1036 | plugin_registry, |
| 1037 | private_root, |
| 1038 | target_ref, |
| 1039 | session_id, |
| 1040 | ) |
| 1041 | }) |
| 1042 | .await |
| 1043 | { |
| 1044 | Some(result) => result, |
| 1045 | None => Err(OWNER_LOST_ERROR.to_string()), |
| 1046 | } |
| 1047 | } |
| 1048 | |
| 1049 | pub fn configure_runtime_chat( |
| 1050 | &mut self, |
| 1051 | config: codewhale_runtime::config::Config, |
| 1052 | plugin_registry: std::sync::Arc<codewhale_plugins::PluginRegistry>, |
| 1053 | private_root: PathBuf, |
| 1054 | target_ref: String, |
| 1055 | session_id: String, |
| 1056 | ) -> Result<(), String> { |
| 1057 | if matches!( |
| 1058 | self.status, |
| 1059 | Status::Connecting | Status::Connected | Status::Stopping |
| 1060 | ) { |
| 1061 | return Err("Remote control is already active.".to_string()); |
| 1062 | } |
| 1063 | let requested = PendingRuntimeChatConfiguration { |
| 1064 | config, |
| 1065 | plugin_registry, |
| 1066 | private_root, |
| 1067 | target_ref, |
| 1068 | session_id, |
| 1069 | }; |
| 1070 | if let Some(host) = self.runtime_chat.as_ref() { |
| 1071 | if host.scope_matches(&requested.target_ref, &requested.session_id) |
| 1072 | && (host.has_any_unsettled_turns() || self.has_unacknowledged_integrity_events()) |
| 1073 | { |
| 1074 | // Reuse the existing lifetime owner and durable manager only |
| 1075 | // while recovery still needs it. The fresh config is retained |
| 1076 | // separately and every new prompt is rejected until the |
| 1077 | // terminal/catalog backlog is server-acked and the connected |
| 1078 | // worker has explicitly dropped its clone. |
| 1079 | self.pending_runtime_chat_configuration = Some(requested); |
| 1080 | self.runtime_chat_refresh_release_requested = false; |
| 1081 | return Ok(()); |
| 1082 | } |
| 1083 | if host.has_any_unsettled_turns() { |
| 1084 | return Err( |
| 1085 | "An isolated Runtime Chat turn is still active; reconnect its original remote-control session before opening another." |
| 1086 | .to_string(), |
| 1087 | ); |
| 1088 | } |
| 1089 | } |
| 1090 | if self.has_unacknowledged_integrity_events() { |
| 1091 | return Err( |
| 1092 | "The current remote-control session still has unacknowledged terminal events; reconnect it before opening another session." |
| 1093 | .to_string(), |
| 1094 | ); |
| 1095 | } |
| 1096 | // A completed `/rc` session deliberately keeps its durable host until |
| 1097 | // the next start. Release that lifetime owner lock before reopening the |
| 1098 | // same account/session namespace with a fresh provider configuration. |
| 1099 | self.install_runtime_chat_configuration(requested) |
| 1100 | } |
| 1101 | |
| 1102 | fn install_runtime_chat_configuration( |
| 1103 | &mut self, |
| 1104 | requested: PendingRuntimeChatConfiguration, |
| 1105 | ) -> Result<(), String> { |
| 1106 | drop(self.runtime_chat.take()); |
| 1107 | let host = RuntimeChatRelayHost::open( |
| 1108 | requested.config, |
| 1109 | requested.plugin_registry, |
| 1110 | requested.private_root, |
| 1111 | requested.target_ref, |
| 1112 | requested.session_id, |
| 1113 | )?; |
| 1114 | self.runtime_chat = Some(host); |
| 1115 | self.pending_runtime_chat_configuration = None; |
| 1116 | self.runtime_chat_refresh_release_requested = false; |
| 1117 | self.uploaded_runtime_catalog_receipt.clear(); |
| 1118 | Ok(()) |
| 1119 | } |
| 1120 | |
| 1121 | fn schedule_runtime_chat_refresh_if_ready(&mut self) -> Result<(), String> { |
| 1122 | if self.pending_runtime_chat_configuration.is_none() |
| 1123 | || self.runtime_chat_refresh_release_requested |
| 1124 | || self.has_unacknowledged_integrity_events() |
| 1125 | || self |
| 1126 | .runtime_chat |
| 1127 | .as_ref() |
| 1128 | .is_some_and(RuntimeChatRelayHost::has_any_unsettled_turns) |
| 1129 | { |
| 1130 | return Ok(()); |
| 1131 | } |
| 1132 | if self.status != Status::Connected { |
| 1133 | return Ok(()); |
| 1134 | } |
| 1135 | let tx = self.worker_tx.as_ref().ok_or_else(|| { |
| 1136 | "Runtime Chat could not refresh its provider configuration safely.".to_string() |
| 1137 | })?; |
| 1138 | tx.send(WorkerCommand::ReleaseRuntimeChatHost) |
| 1139 | .map_err(|_| { |
| 1140 | "Runtime Chat could not refresh its provider configuration safely.".to_string() |
| 1141 | })?; |
| 1142 | self.runtime_chat_refresh_release_requested = true; |
| 1143 | self.status_detail = "refreshing the local Runtime model configuration".to_string(); |
| 1144 | Ok(()) |
| 1145 | } |
| 1146 | |
| 1147 | fn complete_runtime_chat_refresh(&mut self) -> Result<(), String> { |
| 1148 | if !self.runtime_chat_refresh_release_requested |
| 1149 | || self.has_unacknowledged_integrity_events() |
| 1150 | || self |
| 1151 | .runtime_chat |
| 1152 | .as_ref() |
| 1153 | .is_some_and(RuntimeChatRelayHost::has_any_unsettled_turns) |
| 1154 | { |
| 1155 | return Err("Runtime Chat received an invalid provider-refresh handoff.".to_string()); |
| 1156 | } |
| 1157 | let requested = self |
| 1158 | .pending_runtime_chat_configuration |
| 1159 | .take() |
| 1160 | .ok_or_else(|| { |
| 1161 | "Runtime Chat received an invalid provider-refresh handoff.".to_string() |
| 1162 | })?; |
| 1163 | // The worker has already removed its clone. Dropping the controller's |
| 1164 | // final old host now releases both the relay scope and native store |
| 1165 | // owner locks before the fresh immutable configuration is opened. |
| 1166 | drop(self.runtime_chat.take()); |
| 1167 | let host = RuntimeChatRelayHost::open( |
| 1168 | requested.config, |
| 1169 | requested.plugin_registry, |
| 1170 | requested.private_root, |
| 1171 | requested.target_ref, |
| 1172 | requested.session_id, |
| 1173 | )?; |
| 1174 | if let (Some(account_ref), Some(target_ref)) = |
| 1175 | (self.account_ref.as_deref(), self.target_ref.as_deref()) |
| 1176 | { |
| 1177 | host.bind_account(account_ref, target_ref)?; |
| 1178 | } |
| 1179 | if let Some(run_id) = self.attached_run_id.as_deref() { |
| 1180 | host.authorize_run(run_id)?; |
| 1181 | } |
| 1182 | self.runtime_chat = Some(host.clone()); |
| 1183 | self.runtime_chat_refresh_release_requested = false; |
| 1184 | self.uploaded_runtime_catalog_receipt.clear(); |
| 1185 | self.worker_tx |
| 1186 | .as_ref() |
| 1187 | .ok_or_else(|| { |
| 1188 | "Runtime Chat could not install its refreshed provider configuration.".to_string() |
| 1189 | })? |
| 1190 | .send(WorkerCommand::InstallRuntimeChatHost(host)) |
| 1191 | .map_err(|_| { |
| 1192 | "Runtime Chat could not install its refreshed provider configuration.".to_string() |
| 1193 | })?; |
| 1194 | if let Some(attachment) = self.runtime_chat_attachment.clone() { |
| 1195 | self.upload_runtime_chat_catalog(&attachment)?; |
| 1196 | } |
| 1197 | self.status_detail = "web mirror connected".to_string(); |
| 1198 | Ok(()) |
| 1199 | } |
| 1200 | |
| 1201 | pub fn start(&mut self, start: RemoteStart) -> Result<(), String> { |
| 1202 | let result = self.start_inner_on(start, None); |
| 1203 | if let Err(error) = &result { |
| 1204 | self.record_start_failure(error); |
| 1205 | } |
| 1206 | result |
| 1207 | } |
| 1208 | |
| 1209 | pub async fn start_async(&mut self, start: RemoteStart) -> Result<(), String> { |
| 1210 | let runtime = tokio::runtime::Handle::current(); |
| 1211 | let result = match self |
| 1212 | .run_on_owner(move |controller| controller.start_inner_on(start, Some(runtime))) |
| 1213 | .await |
| 1214 | { |
| 1215 | Some(result) => result, |
| 1216 | None => Err(OWNER_LOST_ERROR.to_string()), |
| 1217 | }; |
| 1218 | if let Err(error) = &result { |
| 1219 | self.record_start_failure(error); |
| 1220 | } |
| 1221 | result |
| 1222 | } |
| 1223 | |
| 1224 | pub fn record_start_failure(&mut self, error: &str) { |
| 1225 | if matches!(self.status, Status::Off | Status::Failed) |
| 1226 | && !self |
| 1227 | .ownership_blocked_until |
| 1228 | .is_some_and(|deadline| Instant::now() < deadline) |
| 1229 | { |
| 1230 | self.status = Status::Failed; |
| 1231 | self.status_detail = codewhale_config::persistence::redact_secrets(error); |
| 1232 | } |
| 1233 | } |
| 1234 | |
| 1235 | fn start_inner_on( |
| 1236 | &mut self, |
| 1237 | start: RemoteStart, |
| 1238 | runtime: Option<tokio::runtime::Handle>, |
| 1239 | ) -> Result<(), String> { |
| 1240 | if matches!( |
| 1241 | self.status, |
| 1242 | Status::Connecting | Status::Connected | Status::Stopping |
| 1243 | ) { |
| 1244 | return Err("Remote control is already active.".to_string()); |
| 1245 | } |
| 1246 | if self.status == Status::Failed |
| 1247 | && self |
| 1248 | .ownership_blocked_until |
| 1249 | .is_some_and(|deadline| Instant::now() < deadline) |
| 1250 | { |
| 1251 | return Err( |
| 1252 | "The previous remote lease may still be active; wait for ownership to return before reconnecting." |
| 1253 | .to_string(), |
| 1254 | ); |
| 1255 | } |
| 1256 | if self.active_run.is_some() || self.pending_local_turn_run.is_some() { |
| 1257 | return Err( |
| 1258 | "The local Work turn is still running; wait for its terminal receipt before reconnecting remote control." |
| 1259 | .to_string(), |
| 1260 | ); |
| 1261 | } |
| 1262 | if self.has_unacknowledged_integrity_events() |
| 1263 | && self |
| 1264 | .runtime_chat |
| 1265 | .as_ref() |
| 1266 | .is_none_or(|host| !host.scope_matches(&start.target_ref, &start.session_id)) |
| 1267 | { |
| 1268 | return Err( |
| 1269 | "The previous session still has unacknowledged terminal events; reconnect that exact session first." |
| 1270 | .to_string(), |
| 1271 | ); |
| 1272 | } |
| 1273 | if !valid_runtime_version(&start.runtime_version) |
| 1274 | || !valid_runtime_commit(&start.runtime_commit) |
| 1275 | || !valid_opaque_ref(&start.target_ref) |
| 1276 | || !valid_session_ref(&start.session_id) |
| 1277 | { |
| 1278 | return Err("This build or session does not have an enrollable identity.".to_string()); |
| 1279 | } |
| 1280 | if !self.pending_runtime_events.is_empty() |
| 1281 | && let Some(journal) = &self.journal |
| 1282 | { |
| 1283 | // A prior send-first fault is impossible now, but a disk failure |
| 1284 | // can leave a classic Work terminal retained only in live memory. |
| 1285 | // Repair that exact pending set before loading/replacing the same |
| 1286 | // session journal; never let reconnect clear the sole copy. |
| 1287 | journal.persist(&self.pending_runtime_events)?; |
| 1288 | } |
| 1289 | match &start.journal_dir { |
| 1290 | Some(dir) => self.prepare_remote_control_session_journal( |
| 1291 | dir, |
| 1292 | &start.target_ref, |
| 1293 | &start.session_id, |
| 1294 | )?, |
| 1295 | None => self.journal = None, |
| 1296 | } |
| 1297 | self.recover_classic_lease_before_worker()?; |
| 1298 | self.recover_runtime_chat_ownership_before_worker()?; |
| 1299 | let (worker_tx, worker_rx) = mpsc::unbounded_channel(); |
| 1300 | let (event_tx, event_rx) = mpsc::unbounded_channel(); |
| 1301 | self.stop_worker(); |
| 1302 | self.status = Status::Connecting; |
| 1303 | self.status_detail = "waiting for account authorization".to_string(); |
| 1304 | self.target_ref = Some(start.target_ref.clone()); |
| 1305 | self.attached_run_id = None; |
| 1306 | self.attached_workspace_id = None; |
| 1307 | self.runtime_chat_attachment = None; |
| 1308 | self.uploaded_runtime_catalog_receipt.clear(); |
| 1309 | self.active_run = None; |
| 1310 | self.pending_local_turn_run = None; |
| 1311 | self.worker_tx = Some(worker_tx); |
| 1312 | self.event_rx = Some(event_rx); |
| 1313 | let runtime_chat = self.runtime_chat.clone(); |
| 1314 | let runtime = runtime.unwrap_or_else(tokio::runtime::Handle::current); |
| 1315 | self.worker = Some(runtime.spawn(async move { |
| 1316 | let mut phase = RelayPhase::Enrolling; |
| 1317 | if let Err(error) = |
| 1318 | relay_worker(start, runtime_chat, worker_rx, event_tx.clone(), &mut phase).await |
| 1319 | { |
| 1320 | let _ = if phase.lease_confirmed() { |
| 1321 | event_tx.send(RemoteEvent::Failed(error)) |
| 1322 | } else { |
| 1323 | event_tx.send(RemoteEvent::FailedPreLease(error)) |
| 1324 | }; |
| 1325 | } |
| 1326 | })); |
| 1327 | Ok(()) |
| 1328 | } |
| 1329 | |
| 1330 | fn recover_runtime_chat_ownership_before_worker(&self) -> Result<(), String> { |
| 1331 | let Some(host) = &self.runtime_chat else { |
| 1332 | return Ok(()); |
| 1333 | }; |
| 1334 | if host.has_any_unsettled_turns() || self.has_unacknowledged_integrity_events() { |
| 1335 | // A prior process may have stopped either while native inference |
| 1336 | // was still running or after terminal projection was durable but |
| 1337 | // before CWC acknowledged its account-delivery envelope. Reclaim |
| 1338 | // the exclusive attached-run writer synchronously before worker |
| 1339 | // enrollment (and therefore before any autonomous provider work) |
| 1340 | // can begin. |
| 1341 | host.recover_inference_ownership_for_pending_delivery()?; |
| 1342 | } |
| 1343 | Ok(()) |
| 1344 | } |
| 1345 | |
| 1346 | fn recover_classic_lease_before_worker(&mut self) -> Result<(), String> { |
| 1347 | let Some(lease) = self |
| 1348 | .journal |
| 1349 | .as_ref() |
| 1350 | .and_then(RuntimeEventJournal::classic_lease) |
| 1351 | else { |
| 1352 | return Ok(()); |
| 1353 | }; |
| 1354 | self.event_seq |
| 1355 | .entry(lease.run_id.clone()) |
| 1356 | .and_modify(|known| *known = (*known).max(lease.seq_floor)) |
| 1357 | .or_insert(lease.seq_floor); |
| 1358 | let recovery_turn_id = lease |
| 1359 | .turn_id |
| 1360 | .clone() |
| 1361 | .unwrap_or_else(|| classic_recovery_turn_id(&lease.run_id, &lease.lease_id)); |
| 1362 | let already_terminal = |
| 1363 | self.pending_runtime_events |
| 1364 | .get(&lease.run_id) |
| 1365 | .is_some_and(|events| { |
| 1366 | events.iter().any(|(seq, entry)| { |
| 1367 | *seq > lease.seq_floor |
| 1368 | && runtime_envelope_event(&entry.envelope) == Some("turn.completed") |
| 1369 | && entry.envelope.get("turn_id").and_then(Value::as_str) |
| 1370 | == Some(recovery_turn_id.as_str()) |
| 1371 | }) |
| 1372 | }); |
| 1373 | if !already_terminal { |
| 1374 | let seq = self.next_runtime_seq(&lease.run_id); |
| 1375 | let envelope = runtime_envelope( |
| 1376 | seq, |
| 1377 | "turn.completed", |
| 1378 | Some(&recovery_turn_id), |
| 1379 | chrono::Utc::now().to_rfc3339(), |
| 1380 | json!({ |
| 1381 | "turn": { |
| 1382 | "status": "failed", |
| 1383 | "usage": {}, |
| 1384 | "error": "The local Runtime restarted before terminal delivery." |
| 1385 | } |
| 1386 | }), |
| 1387 | ); |
| 1388 | if !self.queue_runtime_envelope(&lease.run_id, envelope) { |
| 1389 | return Err( |
| 1390 | "Remote control could not recover its interrupted account turn.".to_string(), |
| 1391 | ); |
| 1392 | } |
| 1393 | } |
| 1394 | self.journal |
| 1395 | .as_ref() |
| 1396 | .ok_or_else(|| "Remote control lost its delivery journal during recovery.".to_string())? |
| 1397 | .set_classic_lease(None, &self.pending_runtime_events)?; |
| 1398 | Ok(()) |
| 1399 | } |
| 1400 | |
| 1401 | /// Why `/rc stop` must currently be refused, if any reason exists. |
| 1402 | /// |
| 1403 | /// Stopping is only safe once no remote turn is active and every |
| 1404 | /// integrity-critical envelope (terminal turn state, approvals, failures, |
| 1405 | /// resynchronization snapshots) is behind the server-confirmed cursor. |
| 1406 | pub fn stop_refusal(&self) -> Option<String> { |
| 1407 | if self.has_active_run() { |
| 1408 | return Some( |
| 1409 | "Finish or interrupt the active remote turn before stopping remote control." |
| 1410 | .to_string(), |
| 1411 | ); |
| 1412 | } |
| 1413 | if self |
| 1414 | .runtime_chat |
| 1415 | .as_ref() |
| 1416 | .is_some_and(RuntimeChatRelayHost::has_any_unsettled_turns) |
| 1417 | { |
| 1418 | return Some( |
| 1419 | "Finish or interrupt the active Runtime Chat turn before stopping remote control." |
| 1420 | .to_string(), |
| 1421 | ); |
| 1422 | } |
| 1423 | if self.has_unacknowledged_integrity_events() { |
| 1424 | return Some( |
| 1425 | "The server has not yet acknowledged this session's terminal or approval events; try /rc stop again in a moment." |
| 1426 | .to_string(), |
| 1427 | ); |
| 1428 | } |
| 1429 | None |
| 1430 | } |
| 1431 | |
| 1432 | fn has_unacknowledged_integrity_events(&self) -> bool { |
| 1433 | self.pending_runtime_events |
| 1434 | .values() |
| 1435 | .flat_map(BTreeMap::values) |
| 1436 | .any(|entry| entry.integrity) |
| 1437 | } |
| 1438 | |
| 1439 | pub fn runtime_chat_blocks_local_dispatch(&self) -> bool { |
| 1440 | self.has_durable_classic_lease() |
| 1441 | || self.pending_runtime_chat_configuration.is_some() |
| 1442 | || self.runtime_chat.as_ref().is_some_and(|host| { |
| 1443 | host.has_any_unsettled_turns() || self.has_unacknowledged_integrity_events() |
| 1444 | }) |
| 1445 | } |
| 1446 | |
| 1447 | pub async fn workspace_restore_guard( |
| 1448 | &self, |
| 1449 | workspace: &Path, |
| 1450 | ) -> Result<Option<tokio::sync::OwnedRwLockWriteGuard<()>>, String> { |
| 1451 | match self.runtime_chat.as_ref() { |
| 1452 | Some(host) => host.workspace_restore_guard(workspace).await.map(Some), |
| 1453 | None => Ok(None), |
| 1454 | } |
| 1455 | } |
| 1456 | |
| 1457 | #[cfg(any(test, feature = "test-support"))] |
| 1458 | pub fn block_runtime_chat_dispatch_for_tests(&mut self) { |
| 1459 | self.pending_runtime_chat_configuration = Some(PendingRuntimeChatConfiguration { |
| 1460 | config: codewhale_runtime::config::Config::default(), |
| 1461 | plugin_registry: std::sync::Arc::new(codewhale_plugins::PluginRegistry::empty( |
| 1462 | Path::new("."), |
| 1463 | )), |
| 1464 | private_root: PathBuf::from("runtime-chat-test-block"), |
| 1465 | target_ref: "target_test_block".to_string(), |
| 1466 | session_id: "session_test_block".to_string(), |
| 1467 | }); |
| 1468 | } |
| 1469 | |
| 1470 | fn attachment_switch_refusal(&self, next_run_id: &str) -> Option<String> { |
| 1471 | let current_run_id = self.attached_run_id.as_deref()?; |
| 1472 | if current_run_id == next_run_id { |
| 1473 | return None; |
| 1474 | } |
| 1475 | if self.has_active_run() { |
| 1476 | return Some( |
| 1477 | "Finish the active Work turn before attaching another account run.".to_string(), |
| 1478 | ); |
| 1479 | } |
| 1480 | let has_unacknowledged_terminal = self |
| 1481 | .pending_runtime_events |
| 1482 | .get(current_run_id) |
| 1483 | .is_some_and(|events| events.values().any(|entry| entry.integrity)); |
| 1484 | has_unacknowledged_terminal.then(|| { |
| 1485 | "The current Runtime Chat turn must be acknowledged before attaching another run." |
| 1486 | .to_string() |
| 1487 | }) |
| 1488 | } |
| 1489 | |
| 1490 | pub fn stop(&mut self) { |
| 1491 | match blocking_owner_handle() { |
| 1492 | Some(handle) => { |
| 1493 | tokio::task::block_in_place(|| handle.block_on(self.stop_async())); |
| 1494 | } |
| 1495 | None => self.stop_inner(), |
| 1496 | } |
| 1497 | } |
| 1498 | |
| 1499 | pub async fn stop_async(&mut self) { |
| 1500 | let _ = self.run_on_owner(Self::stop_inner).await; |
| 1501 | } |
| 1502 | |
| 1503 | fn stop_inner(&mut self) { |
| 1504 | if let Some(refusal) = self.stop_refusal() { |
| 1505 | self.status_detail = refusal; |
| 1506 | return; |
| 1507 | } |
| 1508 | if self.status == Status::Connecting { |
| 1509 | // The worker may have completed its server-side connect just before |
| 1510 | // the UI consumed RemoteEvent::Connected. Aborting it cannot prove |
| 1511 | // that no lease exists, so retain the ownership lock through the |
| 1512 | // server expiry instead of returning local input immediately. |
| 1513 | self.stop_worker(); |
| 1514 | self.status = Status::Failed; |
| 1515 | self.status_detail = |
| 1516 | "authorization cancelled; waiting for any server lease to expire safely" |
| 1517 | .to_string(); |
| 1518 | self.ownership_blocked_until = Some(Instant::now() + OWNERSHIP_LOCK_AFTER_FAILURE); |
| 1519 | } else if self.status == Status::Connected { |
| 1520 | // Hand every deferred delta to the transport first so the worker's |
| 1521 | // pre-heartbeat drain covers the complete unacknowledged set. |
| 1522 | self.hand_off_all_deferred(); |
| 1523 | let queued = self |
| 1524 | .worker_tx |
| 1525 | .as_ref() |
| 1526 | .is_some_and(|tx| tx.send(WorkerCommand::Stop).is_ok()); |
| 1527 | self.worker_tx = None; |
| 1528 | if queued { |
| 1529 | self.status = Status::Stopping; |
| 1530 | self.status_detail = "confirming the runner is offline".to_string(); |
| 1531 | } else { |
| 1532 | self.status = Status::Failed; |
| 1533 | self.status_detail = |
| 1534 | "waiting for the last server lease to expire safely".to_string(); |
| 1535 | self.ownership_blocked_until = Some(Instant::now() + OWNERSHIP_LOCK_AFTER_FAILURE); |
| 1536 | } |
| 1537 | } |
| 1538 | if self.status == Status::Failed && self.ownership_blocked_until.is_none() { |
| 1539 | // A pre-lease failure holds no lease; stopping is an ordinary |
| 1540 | // reset, not a drain confirmation. |
| 1541 | self.status = Status::Off; |
| 1542 | } |
| 1543 | if self.status == Status::Off { |
| 1544 | self.account_ref = None; |
| 1545 | self.links = RemoteLinks::default(); |
| 1546 | self.attached_run_id = None; |
| 1547 | self.attached_workspace_id = None; |
| 1548 | self.runtime_chat_attachment = None; |
| 1549 | self.active_run = None; |
| 1550 | self.pending_local_turn_run = None; |
| 1551 | self.pending_approvals.clear(); |
| 1552 | self.command_fingerprints.clear(); |
| 1553 | self.ownership_blocked_until = None; |
| 1554 | } |
| 1555 | } |
| 1556 | |
| 1557 | fn stop_worker(&mut self) { |
| 1558 | if let Some(worker) = self.worker.take() { |
| 1559 | worker.abort(); |
| 1560 | } |
| 1561 | if let Some(host) = &self.runtime_chat { |
| 1562 | // Projection claims are only an in-process handoff lease between |
| 1563 | // the worker and this controller. Aborting the worker or dropping |
| 1564 | // its receiver must make every unjournaled native event eligible |
| 1565 | // for replay on the same durable host. |
| 1566 | host.release_all_projection_claims(); |
| 1567 | } |
| 1568 | self.worker_tx = None; |
| 1569 | self.event_rx = None; |
| 1570 | self.runtime_chat_refresh_release_requested = false; |
| 1571 | } |
| 1572 | |
| 1573 | fn quarantine_rejected_authority(&mut self, error: String) -> RemoteEvent { |
| 1574 | // Once an attachment fails its account/run/catalog authority checks, |
| 1575 | // no later event from that worker can be trusted. In particular, the |
| 1576 | // classic Prompt and Approval command paths predate Runtime Chat and |
| 1577 | // must not keep consuming commands from a rejected re-enrollment. |
| 1578 | self.stop_worker(); |
| 1579 | self.status = Status::Failed; |
| 1580 | self.status_detail = error.clone(); |
| 1581 | self.ownership_blocked_until = Some(Instant::now() + OWNERSHIP_LOCK_AFTER_FAILURE); |
| 1582 | RemoteEvent::Failed(error) |
| 1583 | } |
| 1584 | |
| 1585 | fn has_pending_control_poll(&self) -> bool { |
| 1586 | !self.deferred_delta.is_empty() |
| 1587 | || self |
| 1588 | .event_rx |
| 1589 | .as_ref() |
| 1590 | .is_some_and(|events| !events.is_empty()) |
| 1591 | || (self.status == Status::Failed |
| 1592 | && self |
| 1593 | .ownership_blocked_until |
| 1594 | .is_some_and(|deadline| Instant::now() >= deadline)) |
| 1595 | } |
| 1596 | |
| 1597 | pub async fn try_next_event_async(&mut self) -> Option<RemoteEvent> { |
| 1598 | if !self.has_pending_control_poll() { |
| 1599 | return None; |
| 1600 | } |
| 1601 | self.run_on_owner(Self::try_next_event).await.flatten() |
| 1602 | } |
| 1603 | |
| 1604 | pub fn try_next_event(&mut self) -> Option<RemoteEvent> { |
| 1605 | // Coalescing ends at the next UI poll: hand any deferred delta to the |
| 1606 | // transport so live viewers never wait more than one tick. |
| 1607 | self.hand_off_all_deferred(); |
| 1608 | if self.status == Status::Failed |
| 1609 | && self |
| 1610 | .ownership_blocked_until |
| 1611 | .is_some_and(|deadline| Instant::now() >= deadline) |
| 1612 | { |
| 1613 | if self.has_active_run() |
| 1614 | || self.has_unacknowledged_integrity_events() |
| 1615 | || self |
| 1616 | .runtime_chat |
| 1617 | .as_ref() |
| 1618 | .is_some_and(RuntimeChatRelayHost::has_any_unsettled_turns) |
| 1619 | { |
| 1620 | // The server lease may have expired, but provider-backed work |
| 1621 | // still owns this private Runtime store. Keep the host/scope |
| 1622 | // lock and allow only a same-session reconnect to resume |
| 1623 | // projection/drain; never transition Off and reopen a second |
| 1624 | // manager over the active store. |
| 1625 | self.stop_worker(); |
| 1626 | self.status_detail = |
| 1627 | "this session still has unsettled or unacknowledged Runtime Chat work; reconnect it to drain" |
| 1628 | .to_string(); |
| 1629 | self.ownership_blocked_until = None; |
| 1630 | return None; |
| 1631 | } |
| 1632 | let approvals = self |
| 1633 | .pending_approvals |
| 1634 | .drain() |
| 1635 | .map(|(_, value)| value) |
| 1636 | .collect(); |
| 1637 | self.stop_worker(); |
| 1638 | self.status = Status::Off; |
| 1639 | self.status_detail = "off".to_string(); |
| 1640 | self.ownership_blocked_until = None; |
| 1641 | return Some(RemoteEvent::OwnershipRestored { approvals }); |
| 1642 | } |
| 1643 | let event = self.event_rx.as_mut()?.try_recv().ok()?; |
| 1644 | match &event { |
| 1645 | RemoteEvent::Connected { |
| 1646 | account_ref, |
| 1647 | target_ref, |
| 1648 | attachment, |
| 1649 | links, |
| 1650 | .. |
| 1651 | } => { |
| 1652 | if let Some(error) = self.attachment_switch_refusal(&attachment.run_id) { |
| 1653 | return Some(self.quarantine_rejected_authority(error)); |
| 1654 | } |
| 1655 | if let Some(host) = &self.runtime_chat |
| 1656 | && let Err(error) = host |
| 1657 | .bind_account(account_ref, target_ref) |
| 1658 | .and_then(|()| host.authorize_run(&attachment.run_id)) |
| 1659 | { |
| 1660 | return Some(self.quarantine_rejected_authority(error)); |
| 1661 | } |
| 1662 | self.apply_attachment(attachment); |
| 1663 | if self.pending_runtime_chat_configuration.is_none() |
| 1664 | && self.runtime_chat.is_some() |
| 1665 | && let Err(error) = self.upload_runtime_chat_catalog(attachment) |
| 1666 | { |
| 1667 | return Some(self.quarantine_rejected_authority(error)); |
| 1668 | } |
| 1669 | self.links = links.clone(); |
| 1670 | // Journal recovery may hold unacknowledged envelopes for runs |
| 1671 | // beyond this attachment; resend every pending run now. |
| 1672 | self.flush_all_pending(); |
| 1673 | self.status = Status::Connected; |
| 1674 | self.status_detail = "web mirror connected".to_string(); |
| 1675 | self.ownership_blocked_until = None; |
| 1676 | self.account_ref = Some(account_ref.clone()); |
| 1677 | self.target_ref = Some(target_ref.clone()); |
| 1678 | if let Err(error) = self.schedule_runtime_chat_refresh_if_ready() { |
| 1679 | return Some(self.quarantine_rejected_authority(error)); |
| 1680 | } |
| 1681 | } |
| 1682 | RemoteEvent::Attachment { |
| 1683 | account_ref, |
| 1684 | target_ref, |
| 1685 | attachment, |
| 1686 | links, |
| 1687 | } => { |
| 1688 | if let Some(error) = self.attachment_switch_refusal(&attachment.run_id) { |
| 1689 | return Some(self.quarantine_rejected_authority(error)); |
| 1690 | } |
| 1691 | if let Some(host) = &self.runtime_chat |
| 1692 | && let Err(error) = host |
| 1693 | .bind_account(account_ref, target_ref) |
| 1694 | .and_then(|()| host.authorize_run(&attachment.run_id)) |
| 1695 | { |
| 1696 | return Some(self.quarantine_rejected_authority(error)); |
| 1697 | } |
| 1698 | self.apply_attachment(attachment); |
| 1699 | if self.pending_runtime_chat_configuration.is_none() |
| 1700 | && self.runtime_chat.is_some() |
| 1701 | && let Err(error) = self.upload_runtime_chat_catalog(attachment) |
| 1702 | { |
| 1703 | return Some(self.quarantine_rejected_authority(error)); |
| 1704 | } |
| 1705 | self.links = links.clone(); |
| 1706 | self.account_ref = Some(account_ref.clone()); |
| 1707 | self.target_ref = Some(target_ref.clone()); |
| 1708 | if let Err(error) = self.schedule_runtime_chat_refresh_if_ready() { |
| 1709 | return Some(self.quarantine_rejected_authority(error)); |
| 1710 | } |
| 1711 | } |
| 1712 | RemoteEvent::RuntimeCursor { run_id, cursor } => { |
| 1713 | self.reconcile_runtime_cursor(run_id, *cursor); |
| 1714 | if let Err(error) = self.schedule_runtime_chat_refresh_if_ready() { |
| 1715 | return Some(self.quarantine_rejected_authority(error)); |
| 1716 | } |
| 1717 | } |
| 1718 | RemoteEvent::RuntimeChatHostReleased => { |
| 1719 | if let Err(error) = self.complete_runtime_chat_refresh() { |
| 1720 | return Some(self.quarantine_rejected_authority(error)); |
| 1721 | } |
| 1722 | } |
| 1723 | RemoteEvent::RuntimeChatProjection(projection) => { |
| 1724 | if let Err(error) = self.upload_runtime_chat_projection(projection) { |
| 1725 | if let Some(host) = &self.runtime_chat { |
| 1726 | host.release_projection( |
| 1727 | &projection.native_thread_id, |
| 1728 | projection.native_seq, |
| 1729 | ); |
| 1730 | } |
| 1731 | self.stop_worker(); |
| 1732 | self.status = Status::Failed; |
| 1733 | self.status_detail = error.clone(); |
| 1734 | self.ownership_blocked_until = |
| 1735 | Some(Instant::now() + OWNERSHIP_LOCK_AFTER_FAILURE); |
| 1736 | return Some(RemoteEvent::Failed(error)); |
| 1737 | } |
| 1738 | } |
| 1739 | RemoteEvent::FailedPreLease(reason) => { |
| 1740 | // No server-confirmed lease ever existed, so nothing is |
| 1741 | // locked: no reconnect blackout, no approval handoff to |
| 1742 | // undo, and `/rc` can retry immediately. |
| 1743 | self.status = Status::Failed; |
| 1744 | self.status_detail = reason.clone(); |
| 1745 | self.ownership_blocked_until = None; |
| 1746 | if !self.has_durable_classic_lease() { |
| 1747 | self.active_run = None; |
| 1748 | self.pending_local_turn_run = None; |
| 1749 | } |
| 1750 | } |
| 1751 | RemoteEvent::Failed(reason) => { |
| 1752 | self.status = Status::Failed; |
| 1753 | self.status_detail = |
| 1754 | format!("{reason}; waiting for the last server lease to expire safely"); |
| 1755 | self.ownership_blocked_until = Some(Instant::now() + OWNERSHIP_LOCK_AFTER_FAILURE); |
| 1756 | // Exact unacknowledged runtime envelopes remain owned by this |
| 1757 | // controller (and its journal). Keep any classic provider-turn |
| 1758 | // association live as well: the engine can still deliver its |
| 1759 | // exact terminal status/usage after the transport fails. |
| 1760 | } |
| 1761 | RemoteEvent::Stopped => { |
| 1762 | self.status = Status::Off; |
| 1763 | self.status_detail = "off".to_string(); |
| 1764 | self.active_run = None; |
| 1765 | self.pending_local_turn_run = None; |
| 1766 | self.attached_run_id = None; |
| 1767 | self.attached_workspace_id = None; |
| 1768 | self.runtime_chat_attachment = None; |
| 1769 | self.links = RemoteLinks::default(); |
| 1770 | self.ownership_blocked_until = None; |
| 1771 | // The worker only reports Stopped after draining through the |
| 1772 | // server-confirmed cursor and posting the offline heartbeat, |
| 1773 | // so an empty pending set means the journal is spent. |
| 1774 | if self.pending_runtime_events.values().all(BTreeMap::is_empty) |
| 1775 | && let Some(journal) = &self.journal |
| 1776 | { |
| 1777 | journal.remove(); |
| 1778 | } |
| 1779 | if !self.pending_approvals.is_empty() { |
| 1780 | let approvals = self |
| 1781 | .pending_approvals |
| 1782 | .drain() |
| 1783 | .map(|(_, value)| value) |
| 1784 | .collect(); |
| 1785 | return Some(RemoteEvent::OwnershipRestored { approvals }); |
| 1786 | } |
| 1787 | } |
| 1788 | RemoteEvent::Notice(_) |
| 1789 | | RemoteEvent::Command { .. } |
| 1790 | | RemoteEvent::OwnershipRestored { .. } => {} |
| 1791 | } |
| 1792 | Some(event) |
| 1793 | } |
| 1794 | |
| 1795 | /// The validated web link for the live session, once the control plane |
| 1796 | /// has advertised one. |
| 1797 | pub fn run_url(&self) -> Option<&str> { |
| 1798 | if matches!(self.status, Status::Connected | Status::Stopping) { |
| 1799 | self.links.run_url.as_deref() |
| 1800 | } else { |
| 1801 | None |
| 1802 | } |
| 1803 | } |
| 1804 | |
| 1805 | /// The validated web link for this computer's settings row, if advertised. |
| 1806 | pub fn computer_url(&self) -> Option<&str> { |
| 1807 | if matches!(self.status, Status::Connected | Status::Stopping) { |
| 1808 | self.links.computer_url.as_deref() |
| 1809 | } else { |
| 1810 | None |
| 1811 | } |
| 1812 | } |
| 1813 | |
| 1814 | /// One word for the posture bar's right slot, `None` while remote |
| 1815 | /// control is off so the bar paints nothing rather than "off". |
| 1816 | #[must_use] |
| 1817 | pub fn status_word(&self) -> Option<&'static str> { |
| 1818 | match self.status { |
| 1819 | Status::Off => None, |
| 1820 | Status::Connecting => Some("connecting"), |
| 1821 | Status::Connected => Some("connected"), |
| 1822 | Status::Stopping => Some("stopping"), |
| 1823 | Status::Failed => Some("failed"), |
| 1824 | } |
| 1825 | } |
| 1826 | |
| 1827 | #[must_use] |
| 1828 | pub fn status(&self) -> Status { |
| 1829 | self.status |
| 1830 | } |
| 1831 | |
| 1832 | /// Test-only: advertise a validated live session link without a control |
| 1833 | /// plane. Mirrors the shape the runner-lease parser installs (`Connected` |
| 1834 | /// plus validated links) so `/rc link`/`/rc open` routing can be exercised |
| 1835 | /// deterministically offline. |
| 1836 | #[cfg(any(test, feature = "test-support"))] |
| 1837 | pub fn install_live_link_for_test(&mut self, run_url: &str, computer_url: Option<&str>) { |
| 1838 | self.status = Status::Connected; |
| 1839 | self.status_detail = "test link".to_string(); |
| 1840 | self.links = RemoteLinks { |
| 1841 | run_url: Some(run_url.to_string()), |
| 1842 | computer_url: computer_url.map(str::to_string), |
| 1843 | }; |
| 1844 | } |
| 1845 | |
| 1846 | pub fn status_line(&self) -> String { |
| 1847 | match self.status { |
| 1848 | Status::Off => "Remote control: off".to_string(), |
| 1849 | Status::Connecting => format!("Remote control: connecting · {}", self.status_detail), |
| 1850 | Status::Connected => match self.links.run_url.as_deref() { |
| 1851 | Some(url) => format!( |
| 1852 | "Remote control: connected · account {} · {} · open {url}", |
| 1853 | self.account_ref.as_deref().unwrap_or("account"), |
| 1854 | self.status_detail |
| 1855 | ), |
| 1856 | None => format!( |
| 1857 | "Remote control: connected · account {} · {}", |
| 1858 | self.account_ref.as_deref().unwrap_or("account"), |
| 1859 | self.status_detail |
| 1860 | ), |
| 1861 | }, |
| 1862 | Status::Stopping => { |
| 1863 | "Remote control: stopping · confirming the runner is offline".to_string() |
| 1864 | } |
| 1865 | Status::Failed => { |
| 1866 | if self |
| 1867 | .ownership_blocked_until |
| 1868 | .is_some_and(|deadline| Instant::now() < deadline) |
| 1869 | { |
| 1870 | format!( |
| 1871 | "Remote control: lost after connecting · {} · reconnect waits for the server lease to drain", |
| 1872 | self.status_detail |
| 1873 | ) |
| 1874 | } else { |
| 1875 | format!( |
| 1876 | "Remote control: failed before connecting · {} · /rc to retry", |
| 1877 | self.status_detail |
| 1878 | ) |
| 1879 | } |
| 1880 | } |
| 1881 | } |
| 1882 | } |
| 1883 | |
| 1884 | /// Whether the web mirror can carry an approval decision right now. |
| 1885 | /// |
| 1886 | /// `Connecting` deliberately does not qualify: there is not yet an |
| 1887 | /// attachment/run cursor able to carry a typed approval, so the local |
| 1888 | /// card stays the only actionable surface until `Connected`. A |
| 1889 | /// transport failure also disqualifies — a dead relay cannot deliver a |
| 1890 | /// decision, and the local card remains the source of truth either way. |
| 1891 | /// |
| 1892 | /// Mirror semantics: this never gates *local* input. It only decides |
| 1893 | /// whether the approval card is *also* shared with the web. |
| 1894 | pub fn can_share_approval_with_web(&self) -> bool { |
| 1895 | let attached = match self.status { |
| 1896 | // A connection alone is not enough. Until a concrete typed turn |
| 1897 | // id is bound, `record_remote_approval` has nowhere safe to send |
| 1898 | // a decision, so the card stays local-only. |
| 1899 | Status::Connected | Status::Stopping => self.active_run.is_some(), |
| 1900 | Status::Off | Status::Connecting | Status::Failed => false, |
| 1901 | }; |
| 1902 | attached && !self.applying_remote_command |
| 1903 | } |
| 1904 | |
| 1905 | /// Record that the *local* surface answered an approval, so a late web |
| 1906 | /// decision for the same tool is acknowledged as "no longer pending" |
| 1907 | /// instead of double-answering the engine. First decision wins; the |
| 1908 | /// other surface is told. |
| 1909 | pub fn resolve_pending_approval(&mut self, tool_id: &str, approved: bool) -> bool { |
| 1910 | self.settle_pending_approval( |
| 1911 | tool_id, |
| 1912 | if approved { "approved" } else { "denied" }, |
| 1913 | "terminal", |
| 1914 | ) |
| 1915 | } |
| 1916 | |
| 1917 | /// The request's wait ended without a decision from any surface — its |
| 1918 | /// agent's work ended, or it was answered through another path. Retire |
| 1919 | /// the web's copy as `withdrawn`, never as a person's denial. |
| 1920 | pub fn withdraw_pending_approval(&mut self, tool_id: &str) -> bool { |
| 1921 | self.settle_pending_approval(tool_id, "withdrawn", "agent") |
| 1922 | } |
| 1923 | |
| 1924 | fn settle_pending_approval(&mut self, tool_id: &str, decision: &str, decided_by: &str) -> bool { |
| 1925 | let gate = projected_approval_id(tool_id); |
| 1926 | if self.pending_approvals.remove(&gate).is_none() { |
| 1927 | return false; |
| 1928 | } |
| 1929 | if let Some(active) = self.active_run.clone() { |
| 1930 | self.upload_envelope( |
| 1931 | &active.run_id, |
| 1932 | "approval.resolved", |
| 1933 | Some(&active.turn_id), |
| 1934 | json!({ |
| 1935 | "id": gate, |
| 1936 | "approval_id": gate, |
| 1937 | "decision": decision, |
| 1938 | "decided_by": decided_by, |
| 1939 | }), |
| 1940 | ); |
| 1941 | } |
| 1942 | true |
| 1943 | } |
| 1944 | |
| 1945 | pub fn set_applying_remote_command(&mut self, value: bool) { |
| 1946 | self.applying_remote_command = value; |
| 1947 | } |
| 1948 | |
| 1949 | /// Test-only: put the controller into the exact state a live connected |
| 1950 | /// mirror with an attached run would be in, without a relay worker. |
| 1951 | #[cfg(any(test, feature = "test-support"))] |
| 1952 | pub fn force_mirror_connected_for_tests(&mut self, run_id: &str, turn_id: &str) { |
| 1953 | self.status = Status::Connected; |
| 1954 | self.status_detail = "web mirror connected".to_string(); |
| 1955 | self.attached_run_id = Some(run_id.to_string()); |
| 1956 | self.active_run = Some(ActiveRelayRun { |
| 1957 | run_id: run_id.to_string(), |
| 1958 | turn_id: turn_id.to_string(), |
| 1959 | }); |
| 1960 | } |
| 1961 | |
| 1962 | #[cfg(any(test, feature = "test-support"))] |
| 1963 | pub fn queue_remote_event_for_tests(&mut self, event: RemoteEvent) { |
| 1964 | let (event_tx, event_rx) = mpsc::unbounded_channel(); |
| 1965 | event_tx.send(event).expect("test event receiver"); |
| 1966 | self.event_rx = Some(event_rx); |
| 1967 | if self.worker_tx.is_none() { |
| 1968 | let (worker_tx, _worker_rx) = mpsc::unbounded_channel(); |
| 1969 | self.worker_tx = Some(worker_tx); |
| 1970 | } |
| 1971 | } |
| 1972 | |
| 1973 | pub fn claim_command( |
| 1974 | &mut self, |
| 1975 | run_id: &str, |
| 1976 | seq: u64, |
| 1977 | command: &RemoteCommand, |
| 1978 | ) -> Result<bool, String> { |
| 1979 | if self.status != Status::Connected || self.attached_run_id.as_deref() != Some(run_id) { |
| 1980 | return Err( |
| 1981 | "The remote command does not belong to the current authorized attachment." |
| 1982 | .to_string(), |
| 1983 | ); |
| 1984 | } |
| 1985 | let fingerprint = command_fingerprint(command); |
| 1986 | let key = (run_id.to_string(), seq); |
| 1987 | if let Some(existing) = self.command_fingerprints.get(&key) { |
| 1988 | if existing == &fingerprint { |
| 1989 | // Runtime Chat's native operation key is idempotent. The UI |
| 1990 | // bridge deliberately re-enters that path for an exact replay |
| 1991 | // so a failed acknowledgement POST is issued again; admission |
| 1992 | // gates below describe *new* work and must not false-fail it. |
| 1993 | return Ok(false); |
| 1994 | } |
| 1995 | return Err( |
| 1996 | "The control plane reused a command sequence with different content.".to_string(), |
| 1997 | ); |
| 1998 | } |
| 1999 | if let RemoteCommand::RuntimeChatPrompt(prompt) = command |
| 2000 | && let Some(host) = &self.runtime_chat |
| 2001 | && host.is_exact_prompt_replay(prompt)? |
| 2002 | { |
| 2003 | // The controller's command-sequence cache is intentionally |
| 2004 | // process-local, while the native operation/turn binding is |
| 2005 | // durable. After a crash or deferred provider-config refresh, |
| 2006 | // recognize that durable exact replay before new-work gates and |
| 2007 | // reissue its acknowledgement through the idempotent host path. |
| 2008 | self.command_fingerprints.insert(key, fingerprint); |
| 2009 | return Ok(false); |
| 2010 | } |
| 2011 | match command { |
| 2012 | RemoteCommand::Prompt { .. } | RemoteCommand::RuntimeChatPrompt(_) |
| 2013 | if self.pending_runtime_chat_configuration.is_some() => |
| 2014 | { |
| 2015 | return Err( |
| 2016 | "Wait for Runtime Chat to finish refreshing its local model configuration." |
| 2017 | .to_string(), |
| 2018 | ); |
| 2019 | } |
| 2020 | RemoteCommand::RuntimeChatPrompt(_) if self.has_active_run() => { |
| 2021 | return Err("Finish the active Work turn before starting Runtime Chat.".to_string()); |
| 2022 | } |
| 2023 | RemoteCommand::RuntimeChatPrompt(_) if self.has_unacknowledged_integrity_events() => { |
| 2024 | return Err( |
| 2025 | "Wait for the current Runtime Chat catalog or terminal event to be acknowledged before starting another turn." |
| 2026 | .to_string(), |
| 2027 | ); |
| 2028 | } |
| 2029 | RemoteCommand::Prompt { .. } |
| 2030 | if self |
| 2031 | .runtime_chat |
| 2032 | .as_ref() |
| 2033 | .is_some_and(RuntimeChatRelayHost::has_any_unsettled_turns) |
| 2034 | || self |
| 2035 | .pending_runtime_events |
| 2036 | .get(run_id) |
| 2037 | .is_some_and(|events| events.values().any(|entry| entry.integrity)) => |
| 2038 | { |
| 2039 | return Err( |
| 2040 | "Finish and acknowledge the active Runtime Chat turn before starting Work." |
| 2041 | .to_string(), |
| 2042 | ); |
| 2043 | } |
| 2044 | _ => {} |
| 2045 | } |
| 2046 | self.command_fingerprints.insert(key, fingerprint); |
| 2047 | Ok(true) |
| 2048 | } |
| 2049 | |
| 2050 | pub fn activate_prompt(&mut self, run_id: &str, turn_id: &str) -> Result<(), String> { |
| 2051 | self.activate_prompt_with_lease_id(run_id, turn_id, String::new()) |
| 2052 | } |
| 2053 | |
| 2054 | pub async fn activate_prompt_async( |
| 2055 | &mut self, |
| 2056 | run_id: &str, |
| 2057 | turn_id: &str, |
| 2058 | ) -> Result<(), String> { |
| 2059 | let run_id = run_id.to_string(); |
| 2060 | let turn_id = turn_id.to_string(); |
| 2061 | match self |
| 2062 | .run_on_owner(move |controller| controller.activate_prompt(&run_id, &turn_id)) |
| 2063 | .await |
| 2064 | { |
| 2065 | Some(result) => result, |
| 2066 | None => Err(OWNER_LOST_ERROR.to_string()), |
| 2067 | } |
| 2068 | } |
| 2069 | |
| 2070 | fn activate_prompt_with_lease_id( |
| 2071 | &mut self, |
| 2072 | run_id: &str, |
| 2073 | turn_id: &str, |
| 2074 | lease_id: String, |
| 2075 | ) -> Result<(), String> { |
| 2076 | let active = ActiveRelayRun { |
| 2077 | run_id: run_id.to_string(), |
| 2078 | turn_id: turn_id.to_string(), |
| 2079 | }; |
| 2080 | self.begin_classic_lease(ClassicRunLease { |
| 2081 | run_id: active.run_id.clone(), |
| 2082 | turn_id: Some(active.turn_id.clone()), |
| 2083 | lease_id, |
| 2084 | seq_floor: self.runtime_seq_floor(&active.run_id), |
| 2085 | })?; |
| 2086 | self.active_run = Some(active); |
| 2087 | Ok(()) |
| 2088 | } |
| 2089 | |
| 2090 | fn promote_pending_local_turn(&mut self, run_id: &str, turn_id: &str) -> Result<(), String> { |
| 2091 | let lease_id = self |
| 2092 | .journal |
| 2093 | .as_ref() |
| 2094 | .and_then(RuntimeEventJournal::classic_lease) |
| 2095 | .filter(|lease| lease.run_id == run_id && lease.turn_id.is_none()) |
| 2096 | .map(|lease| lease.lease_id) |
| 2097 | .ok_or_else(|| { |
| 2098 | "Remote control lost its durable pre-dispatch lease generation.".to_string() |
| 2099 | })?; |
| 2100 | self.activate_prompt_with_lease_id(run_id, turn_id, lease_id) |
| 2101 | } |
| 2102 | |
| 2103 | #[cfg(test)] |
| 2104 | pub fn active_run_matches(&self, run_id: &str) -> bool { |
| 2105 | self.active_run |
| 2106 | .as_ref() |
| 2107 | .is_some_and(|active| active.run_id == run_id) |
| 2108 | || self.pending_local_turn_run.as_deref() == Some(run_id) |
| 2109 | } |
| 2110 | |
| 2111 | /// Legacy Work cancellation is exact-turn scoped. A delayed command for |
| 2112 | /// an older turn in the same run must never cancel the current provider |
| 2113 | /// lifecycle. |
| 2114 | pub fn active_turn_matches(&self, run_id: &str, turn_id: &str) -> bool { |
| 2115 | self.active_run |
| 2116 | .as_ref() |
| 2117 | .is_some_and(|active| active.run_id == run_id && active.turn_id == turn_id) |
| 2118 | || self |
| 2119 | .journal |
| 2120 | .as_ref() |
| 2121 | .and_then(RuntimeEventJournal::classic_lease) |
| 2122 | .is_some_and(|lease| { |
| 2123 | lease.run_id == run_id && lease.turn_id.as_deref() == Some(turn_id) |
| 2124 | }) |
| 2125 | } |
| 2126 | |
| 2127 | /// A remotely-owned turn must reach a terminal engine event before the |
| 2128 | /// user can release the relay lease. Dropping the worker earlier would |
| 2129 | /// discard the run binding and strand the control-plane ledger while the |
| 2130 | /// local engine continued producing results. |
| 2131 | pub fn has_active_run(&self) -> bool { |
| 2132 | self.active_run.is_some() |
| 2133 | || self.pending_local_turn_run.is_some() |
| 2134 | || self.has_durable_classic_lease() |
| 2135 | } |
| 2136 | |
| 2137 | fn has_durable_classic_lease(&self) -> bool { |
| 2138 | self.journal |
| 2139 | .as_ref() |
| 2140 | .and_then(RuntimeEventJournal::classic_lease) |
| 2141 | .is_some() |
| 2142 | } |
| 2143 | |
| 2144 | /// Bind the server-confirmed attachment to the local turn that was |
| 2145 | /// already running when `/rc` was invoked. |
| 2146 | /// |
| 2147 | /// With a typed runtime turn id the binding is immediate. During the |
| 2148 | /// narrow dispatch-before-`TurnStarted` window, the run is parked and the |
| 2149 | /// first typed start event completes the binding. Replays are idempotent: |
| 2150 | /// an existing binding is never replaced and no runtime envelope is |
| 2151 | /// emitted by this method itself. |
| 2152 | pub fn attach_current_local_turn(&mut self, turn_id: Option<&str>) -> bool { |
| 2153 | if self.status != Status::Connected || self.has_active_run() { |
| 2154 | return false; |
| 2155 | } |
| 2156 | let Some(run_id) = self.attached_run_id.clone() else { |
| 2157 | return false; |
| 2158 | }; |
| 2159 | match turn_id.map(str::trim).filter(|turn_id| !turn_id.is_empty()) { |
| 2160 | Some(turn_id) => { |
| 2161 | if self.activate_prompt(&run_id, turn_id).is_err() { |
| 2162 | return false; |
| 2163 | } |
| 2164 | } |
| 2165 | None => { |
| 2166 | if self |
| 2167 | .begin_classic_lease(ClassicRunLease { |
| 2168 | run_id: run_id.clone(), |
| 2169 | turn_id: None, |
| 2170 | lease_id: String::new(), |
| 2171 | seq_floor: self.runtime_seq_floor(&run_id), |
| 2172 | }) |
| 2173 | .is_err() |
| 2174 | { |
| 2175 | return false; |
| 2176 | } |
| 2177 | self.pending_local_turn_run = Some(run_id); |
| 2178 | } |
| 2179 | } |
| 2180 | true |
| 2181 | } |
| 2182 | |
| 2183 | pub async fn attach_current_local_turn_async(&mut self, turn_id: Option<&str>) -> bool { |
| 2184 | if self.status != Status::Connected |
| 2185 | || self.has_active_run() |
| 2186 | || self.attached_run_id.is_none() |
| 2187 | { |
| 2188 | return false; |
| 2189 | } |
| 2190 | let turn_id = turn_id.map(str::to_string); |
| 2191 | self.run_on_owner(move |controller| { |
| 2192 | controller.attach_current_local_turn(turn_id.as_deref()) |
| 2193 | }) |
| 2194 | .await |
| 2195 | .unwrap_or(false) |
| 2196 | } |
| 2197 | |
| 2198 | /// Release a dispatch-window binding when the local dispatcher becomes |
| 2199 | /// idle without ever producing a typed `TurnStarted`. The account-owned |
| 2200 | /// attachment remains connected and can accept a later web prompt; only |
| 2201 | /// the nonexistent turn lease is removed. |
| 2202 | pub fn release_unstarted_local_turn(&mut self) -> bool { |
| 2203 | if self.pending_local_turn_run.is_none() { |
| 2204 | return false; |
| 2205 | } |
| 2206 | if self.finish_classic_lease().is_err() { |
| 2207 | return false; |
| 2208 | } |
| 2209 | self.pending_local_turn_run = None; |
| 2210 | true |
| 2211 | } |
| 2212 | |
| 2213 | pub async fn release_unstarted_local_turn_async(&mut self) -> bool { |
| 2214 | if self.pending_local_turn_run.is_none() { |
| 2215 | return false; |
| 2216 | } |
| 2217 | self.run_on_owner(Self::release_unstarted_local_turn) |
| 2218 | .await |
| 2219 | .unwrap_or(false) |
| 2220 | } |
| 2221 | |
| 2222 | fn begin_classic_lease(&mut self, lease: ClassicRunLease) -> Result<(), String> { |
| 2223 | let mut lease = lease; |
| 2224 | lease.seq_floor = lease.seq_floor.max(self.runtime_seq_floor(&lease.run_id)); |
| 2225 | if let Some(previous) = self |
| 2226 | .journal |
| 2227 | .as_ref() |
| 2228 | .and_then(RuntimeEventJournal::classic_lease) |
| 2229 | .filter(|previous| previous.run_id == lease.run_id) |
| 2230 | { |
| 2231 | lease.seq_floor = lease.seq_floor.max(previous.seq_floor); |
| 2232 | } |
| 2233 | // A blank id always starts a fresh generation. The dispatch-window |
| 2234 | // promotion above is the only valid reuse and supplies its durable id |
| 2235 | // explicitly so a stale pre-dispatch lease cannot be inherited here. |
| 2236 | if lease.lease_id.is_empty() { |
| 2237 | lease.lease_id = format!("classic_lease_{}", uuid::Uuid::new_v4().simple()); |
| 2238 | } |
| 2239 | if !lease.valid() { |
| 2240 | return Err("The remote Work turn identity is invalid.".to_string()); |
| 2241 | } |
| 2242 | let Some(journal) = &self.journal else { |
| 2243 | #[cfg(test)] |
| 2244 | return Ok(()); |
| 2245 | #[cfg(not(test))] |
| 2246 | { |
| 2247 | self.status = Status::Failed; |
| 2248 | self.status_detail = |
| 2249 | "Remote control requires a durable account-delivery journal.".to_string(); |
| 2250 | return Err(self.status_detail.clone()); |
| 2251 | } |
| 2252 | }; |
| 2253 | if let Err(error) = journal.set_classic_lease(Some(lease), &self.pending_runtime_events) { |
| 2254 | self.status = Status::Failed; |
| 2255 | self.status_detail = error.clone(); |
| 2256 | self.ownership_blocked_until = Some(Instant::now() + OWNERSHIP_LOCK_AFTER_FAILURE); |
| 2257 | return Err(error); |
| 2258 | } |
| 2259 | Ok(()) |
| 2260 | } |
| 2261 | |
| 2262 | fn finish_classic_lease(&mut self) -> Result<(), String> { |
| 2263 | let Some(journal) = &self.journal else { |
| 2264 | #[cfg(test)] |
| 2265 | return Ok(()); |
| 2266 | #[cfg(not(test))] |
| 2267 | return Err("Remote control requires a durable account-delivery journal.".to_string()); |
| 2268 | }; |
| 2269 | if let Err(error) = journal.set_classic_lease(None, &self.pending_runtime_events) { |
| 2270 | self.status = Status::Failed; |
| 2271 | self.status_detail = error.clone(); |
| 2272 | self.ownership_blocked_until = Some(Instant::now() + OWNERSHIP_LOCK_AFTER_FAILURE); |
| 2273 | return Err(error); |
| 2274 | } |
| 2275 | Ok(()) |
| 2276 | } |
| 2277 | |
| 2278 | /// A remote prompt can fail during local route preparation before the |
| 2279 | /// engine owns a turn and therefore before it can emit `EngineEvent::Error`. |
| 2280 | /// That failure is still terminal for the account-owned run. |
| 2281 | pub fn fail_active_dispatch(&mut self, error: &str) { |
| 2282 | self.fail_active_run("dispatch_failed", error); |
| 2283 | } |
| 2284 | |
| 2285 | pub async fn fail_active_dispatch_async(&mut self, error: &str) { |
| 2286 | let error = error.to_string(); |
| 2287 | let _ = self |
| 2288 | .run_on_owner(move |controller| controller.fail_active_dispatch(&error)) |
| 2289 | .await; |
| 2290 | } |
| 2291 | |
| 2292 | fn apply_attachment(&mut self, attachment: &RemoteAttachment) { |
| 2293 | self.attached_run_id = Some(attachment.run_id.clone()); |
| 2294 | self.attached_workspace_id = Some(attachment.workspace_id.clone()); |
| 2295 | self.runtime_chat_attachment = Some(attachment.clone()); |
| 2296 | self.reconcile_runtime_cursor(&attachment.run_id, attachment.runtime_cursor); |
| 2297 | let local_cursor = self |
| 2298 | .pending_runtime_events |
| 2299 | .get(&attachment.run_id) |
| 2300 | .and_then(|events| events.last_key_value().map(|(seq, _)| *seq)) |
| 2301 | .unwrap_or(0); |
| 2302 | let cursor = self.event_seq.entry(attachment.run_id.clone()).or_insert(0); |
| 2303 | *cursor = (*cursor).max(attachment.runtime_cursor).max(local_cursor); |
| 2304 | self.flush_pending_runtime_events(&attachment.run_id); |
| 2305 | // `snapshot_present` is server history, not proof that this freshly |
| 2306 | // loaded TUI process has uploaded its current saved history. The local |
| 2307 | // marker below prevents ordinary same-process reconnect duplication. |
| 2308 | } |
| 2309 | |
| 2310 | fn upload_runtime_chat_catalog(&mut self, attachment: &RemoteAttachment) -> Result<(), String> { |
| 2311 | if self.pending_runtime_chat_configuration.is_some() { |
| 2312 | return Err( |
| 2313 | "Runtime Chat must refresh its local model configuration before advertising a catalog." |
| 2314 | .to_string(), |
| 2315 | ); |
| 2316 | } |
| 2317 | let host = self |
| 2318 | .runtime_chat |
| 2319 | .clone() |
| 2320 | .ok_or_else(|| "This Runtime cannot advertise an isolated Chat relay.".to_string())?; |
| 2321 | let payload = host.catalog(&attachment.runtime_chat_relay_challenge)?; |
| 2322 | let payload_fingerprint = RuntimeChatRelayHost::catalog_payload_fingerprint(&payload)?; |
| 2323 | let receipt_key = format!( |
| 2324 | "{}:{}", |
| 2325 | attachment.runtime_chat_relay_challenge, payload_fingerprint |
| 2326 | ); |
| 2327 | if self |
| 2328 | .uploaded_runtime_catalog_receipt |
| 2329 | .get(&attachment.run_id) |
| 2330 | .is_some_and(|receipt| receipt == &receipt_key) |
| 2331 | { |
| 2332 | return Ok(()); |
| 2333 | } |
| 2334 | let source_event_id = |
| 2335 | runtime_chat_catalog_source_event_id(&attachment.run_id, &payload_fingerprint); |
| 2336 | if self.pending_runtime_chat_catalog_matches(&attachment.run_id, &source_event_id) { |
| 2337 | self.uploaded_runtime_catalog_receipt |
| 2338 | .insert(attachment.run_id.clone(), receipt_key); |
| 2339 | return Ok(()); |
| 2340 | } |
| 2341 | // A local receipt proves only that the catalog was journaled, not that |
| 2342 | // the server cursor acknowledged it. After restart, resend the stable |
| 2343 | // semantic source id whenever no matching pending entry remains. CWC |
| 2344 | // deduplicates an exact replay and rejects conflicting reuse, while a |
| 2345 | // changed safe catalog gets a different payload fingerprint/source id. |
| 2346 | let seq = self.next_runtime_seq(&attachment.run_id); |
| 2347 | let envelope = runtime_chat_envelope( |
| 2348 | seq, |
| 2349 | "runtime.catalog", |
| 2350 | None, |
| 2351 | None, |
| 2352 | Some(&source_event_id), |
| 2353 | RUNTIME_CHAT_CATALOG_TIMESTAMP.to_string(), |
| 2354 | payload, |
| 2355 | ); |
| 2356 | if !self.queue_runtime_chat_envelope(&attachment.run_id, envelope) { |
| 2357 | return Err("Runtime Chat could not journal its challenge-bound catalog.".to_string()); |
| 2358 | } |
| 2359 | self.uploaded_runtime_catalog_receipt |
| 2360 | .insert(attachment.run_id.clone(), receipt_key); |
| 2361 | Ok(()) |
| 2362 | } |
| 2363 | |
| 2364 | fn pending_runtime_chat_catalog_matches(&self, run_id: &str, source_event_id: &str) -> bool { |
| 2365 | self.pending_runtime_events |
| 2366 | .get(run_id) |
| 2367 | .is_some_and(|events| { |
| 2368 | events.values().any(|event| { |
| 2369 | event.envelope.get("event").and_then(Value::as_str) == Some("runtime.catalog") |
| 2370 | && event |
| 2371 | .envelope |
| 2372 | .get("source_event_id") |
| 2373 | .and_then(Value::as_str) |
| 2374 | == Some(source_event_id) |
| 2375 | }) |
| 2376 | }) |
| 2377 | } |
| 2378 | |
| 2379 | fn upload_runtime_chat_projection( |
| 2380 | &mut self, |
| 2381 | projection: &RuntimeChatProjection, |
| 2382 | ) -> Result<(), String> { |
| 2383 | if self.attached_run_id.as_deref() != Some(projection.run_id.as_str()) { |
| 2384 | // A reconnect can change the single attached run after the worker |
| 2385 | // claimed an event from the previous run. Leave that durable |
| 2386 | // backlog with its rightful run instead of delivering it across |
| 2387 | // authority or poisoning the new attachment. |
| 2388 | self.runtime_chat |
| 2389 | .as_ref() |
| 2390 | .ok_or_else(|| "This Runtime Chat relay is not configured.".to_string())? |
| 2391 | .release_projection(&projection.native_thread_id, projection.native_seq); |
| 2392 | return Ok(()); |
| 2393 | } |
| 2394 | let seq = self.next_runtime_seq(&projection.run_id); |
| 2395 | let envelope = runtime_chat_envelope( |
| 2396 | seq, |
| 2397 | projection.event, |
| 2398 | Some(&projection.virtual_thread_id), |
| 2399 | Some(&projection.virtual_turn_id), |
| 2400 | Some(&projection.source_event_id), |
| 2401 | projection.timestamp.clone(), |
| 2402 | projection.payload.clone(), |
| 2403 | ); |
| 2404 | if !self.queue_runtime_chat_envelope(&projection.run_id, envelope) { |
| 2405 | return Err("Runtime Chat could not journal its native turn event.".to_string()); |
| 2406 | } |
| 2407 | self.runtime_chat |
| 2408 | .as_ref() |
| 2409 | .ok_or_else(|| "This Runtime Chat relay is not configured.".to_string())? |
| 2410 | .mark_projected( |
| 2411 | &projection.native_thread_id, |
| 2412 | projection.native_seq, |
| 2413 | &projection.virtual_turn_id, |
| 2414 | projection.event, |
| 2415 | ) |
| 2416 | } |
| 2417 | |
| 2418 | pub fn upload_snapshot(&mut self, run_id: &str, messages: &[Message]) { |
| 2419 | if self.uploaded_snapshots.contains(run_id) { |
| 2420 | return; |
| 2421 | } |
| 2422 | let seq = self.next_runtime_seq(run_id); |
| 2423 | let envelope = bounded_session_snapshot_envelope(seq, messages); |
| 2424 | if self.queue_runtime_envelope(run_id, envelope) { |
| 2425 | self.uploaded_snapshots.insert(run_id.to_string()); |
| 2426 | } |
| 2427 | } |
| 2428 | |
| 2429 | pub async fn upload_snapshot_async(&mut self, run_id: &str, messages: &[Message]) { |
| 2430 | if self.uploaded_snapshots.contains(run_id) { |
| 2431 | return; |
| 2432 | } |
| 2433 | let seq = self.next_runtime_seq(run_id); |
| 2434 | let envelope = bounded_session_snapshot_envelope(seq, messages); |
| 2435 | let target = run_id.to_string(); |
| 2436 | let queued_run = target.clone(); |
| 2437 | if let Some(true) = self |
| 2438 | .run_on_owner(move |controller| { |
| 2439 | controller.queue_runtime_envelope(&queued_run, envelope) |
| 2440 | }) |
| 2441 | .await |
| 2442 | { |
| 2443 | self.uploaded_snapshots.insert(target); |
| 2444 | } |
| 2445 | } |
| 2446 | |
| 2447 | pub fn acknowledge( |
| 2448 | &self, |
| 2449 | run_id: &str, |
| 2450 | seq: u64, |
| 2451 | command: &RemoteCommand, |
| 2452 | status: &str, |
| 2453 | error: Option<String>, |
| 2454 | ) { |
| 2455 | let Some(tx) = &self.worker_tx else { |
| 2456 | return; |
| 2457 | }; |
| 2458 | let _ = tx.send(WorkerCommand::Upload { |
| 2459 | run_id: run_id.to_string(), |
| 2460 | acknowledgements: vec![CommandAcknowledgement { |
| 2461 | command_seq: seq, |
| 2462 | command_type: command.kind().to_string(), |
| 2463 | status: status.to_string(), |
| 2464 | turn_id: command.turn_id().map(ToString::to_string), |
| 2465 | error: error.map(|value| value.chars().take(800).collect()), |
| 2466 | }], |
| 2467 | envelopes: Vec::new(), |
| 2468 | }); |
| 2469 | } |
| 2470 | |
| 2471 | pub async fn apply_runtime_chat_prompt( |
| 2472 | &self, |
| 2473 | command: &RuntimeChatPrompt, |
| 2474 | ) -> Result<(), String> { |
| 2475 | if self.status != Status::Connected |
| 2476 | || self.attached_run_id.as_deref() != Some(command.run_id.as_str()) |
| 2477 | || self.attached_workspace_id.as_deref() != Some(command.workspace.id.as_str()) |
| 2478 | || self.target_ref.as_deref() != Some(command.workspace.target_ref.as_str()) |
| 2479 | { |
| 2480 | return Err("The Runtime Chat command does not match the attached run.".to_string()); |
| 2481 | } |
| 2482 | let host = self |
| 2483 | .runtime_chat |
| 2484 | .clone() |
| 2485 | .ok_or_else(|| "This Runtime Chat relay is not configured.".to_string())?; |
| 2486 | if self.pending_runtime_chat_configuration.is_some() |
| 2487 | && !host.is_exact_prompt_replay(command)? |
| 2488 | { |
| 2489 | return Err("Runtime Chat is refreshing its local model configuration.".to_string()); |
| 2490 | } |
| 2491 | host.apply_prompt(command).await |
| 2492 | } |
| 2493 | |
| 2494 | pub async fn interrupt_runtime_chat( |
| 2495 | &self, |
| 2496 | run_id: &str, |
| 2497 | scope: &RuntimeChatControlScope, |
| 2498 | virtual_turn_id: &str, |
| 2499 | ) -> Result<(), String> { |
| 2500 | if self.status != Status::Connected || self.attached_run_id.as_deref() != Some(run_id) { |
| 2501 | return Err("The Runtime Chat interrupt does not match the attached run.".to_string()); |
| 2502 | } |
| 2503 | let host = self |
| 2504 | .runtime_chat |
| 2505 | .clone() |
| 2506 | .ok_or_else(|| "This Runtime Chat relay is not configured.".to_string())?; |
| 2507 | host.interrupt(run_id, scope, virtual_turn_id).await |
| 2508 | } |
| 2509 | |
| 2510 | pub fn record_remote_approval( |
| 2511 | &mut self, |
| 2512 | tool_id: &str, |
| 2513 | tool_name: &str, |
| 2514 | description: &str, |
| 2515 | _input: &Value, |
| 2516 | _approval_key: &str, |
| 2517 | _intent_summary: Option<&str>, |
| 2518 | ) -> String { |
| 2519 | let gate = projected_approval_id(tool_id); |
| 2520 | self.pending_approvals.insert( |
| 2521 | gate.clone(), |
| 2522 | PendingRemoteApproval { |
| 2523 | tool_id: tool_id.to_string(), |
| 2524 | }, |
| 2525 | ); |
| 2526 | if let Some(active) = self.active_run.clone() { |
| 2527 | self.upload_envelope( |
| 2528 | &active.run_id, |
| 2529 | "approval.required", |
| 2530 | Some(&active.turn_id), |
| 2531 | json!({ |
| 2532 | "id": gate, |
| 2533 | "approval_id": gate, |
| 2534 | "tool_name": tool_name, |
| 2535 | "description": description, |
| 2536 | }), |
| 2537 | ); |
| 2538 | } |
| 2539 | gate |
| 2540 | } |
| 2541 | |
| 2542 | pub fn pending_approval_tool_id(&self, gate: &str) -> Option<String> { |
| 2543 | self.pending_approvals |
| 2544 | .get(gate) |
| 2545 | .map(|approval| approval.tool_id.clone()) |
| 2546 | } |
| 2547 | |
| 2548 | pub fn take_pending_approval(&mut self, gate: &str) -> Option<String> { |
| 2549 | self.pending_approvals |
| 2550 | .remove(gate) |
| 2551 | .map(|approval| approval.tool_id) |
| 2552 | } |
| 2553 | |
| 2554 | pub fn observe_engine_event(&mut self, event: &EngineEvent) { |
| 2555 | // `/rc` can attach while the host is still preparing a turn. The |
| 2556 | // server run is known first; `TurnStarted` supplies the authoritative |
| 2557 | // runtime turn id later. Promote exactly once, before the ordinary |
| 2558 | // projection below observes the event. |
| 2559 | if let EngineEvent::TurnStarted { turn_id, .. } = event |
| 2560 | && self.active_run.is_none() |
| 2561 | && let Some(run_id) = self.pending_local_turn_run.take() |
| 2562 | && self.promote_pending_local_turn(&run_id, turn_id).is_err() |
| 2563 | { |
| 2564 | self.pending_local_turn_run = Some(run_id); |
| 2565 | return; |
| 2566 | } |
| 2567 | let Some(active) = self.active_run.clone() else { |
| 2568 | return; |
| 2569 | }; |
| 2570 | match event { |
| 2571 | EngineEvent::MessageDelta { content, .. } => { |
| 2572 | self.upload_delta(&active.run_id, &active.turn_id, content); |
| 2573 | } |
| 2574 | EngineEvent::ToolCallStarted { id, name, .. } => { |
| 2575 | self.upload_envelope( |
| 2576 | &active.run_id, |
| 2577 | "item.started", |
| 2578 | Some(&active.turn_id), |
| 2579 | json!({ "tool": { "id": id, "name": name, "input": {} } }), |
| 2580 | ); |
| 2581 | } |
| 2582 | EngineEvent::ToolCallComplete { id, result, .. } => { |
| 2583 | let (event_name, status) = if result.is_ok() { |
| 2584 | ("item.completed", "completed") |
| 2585 | } else { |
| 2586 | ("item.failed", "failed") |
| 2587 | }; |
| 2588 | self.upload_envelope( |
| 2589 | &active.run_id, |
| 2590 | event_name, |
| 2591 | Some(&active.turn_id), |
| 2592 | json!({ |
| 2593 | "item": { |
| 2594 | "id": id, |
| 2595 | "kind": "tool_call", |
| 2596 | "status": status, |
| 2597 | "summary": "", |
| 2598 | "detail": "", |
| 2599 | } |
| 2600 | }), |
| 2601 | ); |
| 2602 | } |
| 2603 | EngineEvent::TurnStarted { turn_id, route, .. } => { |
| 2604 | self.active_run = Some(ActiveRelayRun { |
| 2605 | run_id: active.run_id.clone(), |
| 2606 | turn_id: turn_id.clone(), |
| 2607 | }); |
| 2608 | self.upload_envelope( |
| 2609 | &active.run_id, |
| 2610 | "turn.started", |
| 2611 | Some(turn_id), |
| 2612 | json!({ |
| 2613 | "turn": { |
| 2614 | "model": route.as_ref().map(|value| value.model.as_str()).unwrap_or(""), |
| 2615 | "mode": "", |
| 2616 | } |
| 2617 | }), |
| 2618 | ); |
| 2619 | } |
| 2620 | EngineEvent::TurnComplete { usage, status, .. } => { |
| 2621 | let status = match status { |
| 2622 | TurnOutcomeStatus::Completed => "completed", |
| 2623 | TurnOutcomeStatus::Interrupted => "interrupted", |
| 2624 | TurnOutcomeStatus::Failed => "failed", |
| 2625 | }; |
| 2626 | let terminal_durable = self.upload_envelope( |
| 2627 | &active.run_id, |
| 2628 | "turn.completed", |
| 2629 | Some(&active.turn_id), |
| 2630 | json!({ "turn": { "status": status, "usage": usage } }), |
| 2631 | ); |
| 2632 | if terminal_durable && self.finish_classic_lease().is_ok() { |
| 2633 | if self.resync_required.remove(&active.run_id) { |
| 2634 | // Deltas were shed under pressure during this turn; the UI |
| 2635 | // must now upload a bounded current snapshot so account |
| 2636 | // truth is restored at the terminal boundary. |
| 2637 | self.resync_ready.push(active.run_id.clone()); |
| 2638 | } |
| 2639 | self.active_run = None; |
| 2640 | self.pending_local_turn_run = None; |
| 2641 | } |
| 2642 | } |
| 2643 | EngineEvent::Error { |
| 2644 | envelope, |
| 2645 | recoverable, |
| 2646 | } if !recoverable => { |
| 2647 | self.fail_active_run(&envelope.code, &envelope.message); |
| 2648 | } |
| 2649 | _ => {} |
| 2650 | } |
| 2651 | } |
| 2652 | |
| 2653 | fn fail_active_run(&mut self, code: &str, error: &str) { |
| 2654 | let Some(active) = self.active_run.clone() else { |
| 2655 | return; |
| 2656 | }; |
| 2657 | let message = bounded_remote_error_message(error); |
| 2658 | let item_id = projected_error_item_id(&active.run_id, &active.turn_id, code); |
| 2659 | let item_durable = self.upload_envelope( |
| 2660 | &active.run_id, |
| 2661 | "item.failed", |
| 2662 | Some(&active.turn_id), |
| 2663 | json!({ |
| 2664 | "item": { |
| 2665 | "id": item_id, |
| 2666 | "kind": "error", |
| 2667 | "status": "failed", |
| 2668 | "summary": message, |
| 2669 | "detail": message, |
| 2670 | } |
| 2671 | }), |
| 2672 | ); |
| 2673 | let terminal_durable = self.upload_envelope( |
| 2674 | &active.run_id, |
| 2675 | "turn.completed", |
| 2676 | Some(&active.turn_id), |
| 2677 | json!({ "turn": { "status": "failed", "usage": {} } }), |
| 2678 | ); |
| 2679 | if item_durable && terminal_durable && self.finish_classic_lease().is_ok() { |
| 2680 | self.active_run = None; |
| 2681 | self.pending_local_turn_run = None; |
| 2682 | } |
| 2683 | } |
| 2684 | |
| 2685 | fn upload_envelope( |
| 2686 | &mut self, |
| 2687 | run_id: &str, |
| 2688 | event: &str, |
| 2689 | turn_id: Option<&str>, |
| 2690 | payload: Value, |
| 2691 | ) -> bool { |
| 2692 | let prior_status = self.status; |
| 2693 | let prior_status_detail = self.status_detail.clone(); |
| 2694 | let prior_ownership_blocked_until = self.ownership_blocked_until; |
| 2695 | let seq = self.next_runtime_seq(run_id); |
| 2696 | let envelope = runtime_envelope( |
| 2697 | seq, |
| 2698 | event, |
| 2699 | turn_id, |
| 2700 | chrono::Utc::now().to_rfc3339(), |
| 2701 | payload, |
| 2702 | ); |
| 2703 | if self.queue_runtime_envelope(run_id, envelope) { |
| 2704 | return true; |
| 2705 | } |
| 2706 | if integrity_critical_event(event) |
| 2707 | && self |
| 2708 | .journal |
| 2709 | .as_ref() |
| 2710 | .is_some_and(|journal| journal.persist(&self.pending_runtime_events).is_ok()) |
| 2711 | { |
| 2712 | // Atomic replacement can fail transiently (sharing/AV/power-loss |
| 2713 | // boundary). The exact envelope is still retained in memory; |
| 2714 | // make one immediate durable retry before returning to UI code |
| 2715 | // that may clear an approval or terminal lease. Only after that |
| 2716 | // retry succeeds may transport handoff occur. |
| 2717 | if self.status == Status::Failed |
| 2718 | && self.status_detail |
| 2719 | == "Remote control could not durably journal its account event." |
| 2720 | { |
| 2721 | self.status = prior_status; |
| 2722 | self.status_detail = prior_status_detail; |
| 2723 | self.ownership_blocked_until = prior_ownership_blocked_until; |
| 2724 | } |
| 2725 | self.flush_pending_runtime_events(run_id); |
| 2726 | return true; |
| 2727 | } |
| 2728 | false |
| 2729 | } |
| 2730 | |
| 2731 | fn next_runtime_seq(&self, run_id: &str) -> u64 { |
| 2732 | let acknowledged = self.event_seq.get(run_id).copied().unwrap_or(0); |
| 2733 | let pending = self |
| 2734 | .pending_runtime_events |
| 2735 | .get(run_id) |
| 2736 | .and_then(|events| events.last_key_value().map(|(seq, _)| *seq)) |
| 2737 | .unwrap_or(0); |
| 2738 | acknowledged.max(pending).saturating_add(1) |
| 2739 | } |
| 2740 | |
| 2741 | fn runtime_seq_floor(&self, run_id: &str) -> u64 { |
| 2742 | self.next_runtime_seq(run_id).saturating_sub(1) |
| 2743 | } |
| 2744 | |
| 2745 | fn queue_runtime_envelope(&mut self, run_id: &str, envelope: Value) -> bool { |
| 2746 | // Per-run sequence order must reach the transport in order, so any |
| 2747 | // deferred delta is handed off before a later envelope is queued. |
| 2748 | // Persist the new sequence before transport handoff. This gives the |
| 2749 | // ordinary mirrored Work path the same crash boundary as Runtime Chat: |
| 2750 | // a send may be replayed after an ambiguous crash, but an accepted |
| 2751 | // terminal/approval/failure row is never send-first and then lost. |
| 2752 | self.hand_off_deferred(run_id); |
| 2753 | self.queue_runtime_envelope_inner(run_id, envelope, false, true, false) |
| 2754 | } |
| 2755 | |
| 2756 | fn queue_runtime_chat_envelope(&mut self, run_id: &str, envelope: Value) -> bool { |
| 2757 | // Native Chat advances its own durable event cursor only after this |
| 2758 | // account-delivery journal is durable. Persist before handing the |
| 2759 | // envelope to transport; a resend after an ambiguous send is safe via |
| 2760 | // the stable source_event_id contract. |
| 2761 | self.hand_off_deferred(run_id); |
| 2762 | self.queue_runtime_envelope_inner(run_id, envelope, false, true, true) |
| 2763 | } |
| 2764 | |
| 2765 | fn queue_runtime_envelope_inner( |
| 2766 | &mut self, |
| 2767 | run_id: &str, |
| 2768 | envelope: Value, |
| 2769 | defer: bool, |
| 2770 | require_durable_journal: bool, |
| 2771 | rollback_on_journal_failure: bool, |
| 2772 | ) -> bool { |
| 2773 | if require_durable_journal && self.journal.is_none() { |
| 2774 | self.status_detail = |
| 2775 | "Remote control requires a durable account-delivery journal.".to_string(); |
| 2776 | self.status = Status::Failed; |
| 2777 | self.ownership_blocked_until = Some(Instant::now() + OWNERSHIP_LOCK_AFTER_FAILURE); |
| 2778 | return false; |
| 2779 | } |
| 2780 | let Some(seq) = runtime_envelope_seq(&envelope) else { |
| 2781 | self.status_detail = "a local runtime event had no valid sequence".to_string(); |
| 2782 | return false; |
| 2783 | }; |
| 2784 | let encoded_len = serde_json::to_vec(&envelope) |
| 2785 | .map(|body| body.len()) |
| 2786 | .unwrap_or(usize::MAX); |
| 2787 | if encoded_len > MAX_RUNTIME_ENVELOPE_BYTES { |
| 2788 | self.status_detail = "a local runtime event exceeded the safe relay limit".to_string(); |
| 2789 | return false; |
| 2790 | } |
| 2791 | let integrity = runtime_envelope_event(&envelope).is_some_and(integrity_critical_event); |
| 2792 | let already_pending = self |
| 2793 | .pending_runtime_events |
| 2794 | .get(run_id) |
| 2795 | .and_then(|events| events.get(&seq)) |
| 2796 | .is_some(); |
| 2797 | let previous_event_seq = self.event_seq.get(run_id).copied(); |
| 2798 | if already_pending { |
| 2799 | let entry = self |
| 2800 | .pending_runtime_events |
| 2801 | .get(run_id) |
| 2802 | .and_then(|events| events.get(&seq)) |
| 2803 | .expect("checked above"); |
| 2804 | if entry.envelope != envelope { |
| 2805 | self.status_detail = |
| 2806 | "a local runtime sequence changed before acknowledgement".to_string(); |
| 2807 | return false; |
| 2808 | } |
| 2809 | } else { |
| 2810 | if !self.reserve_capacity(run_id, encoded_len, integrity) { |
| 2811 | return false; |
| 2812 | } |
| 2813 | self.pending_runtime_events |
| 2814 | .entry(run_id.to_string()) |
| 2815 | .or_default() |
| 2816 | .insert( |
| 2817 | seq, |
| 2818 | PendingRuntimeEnvelope { |
| 2819 | envelope: envelope.clone(), |
| 2820 | encoded_len, |
| 2821 | integrity, |
| 2822 | handed_off: false, |
| 2823 | }, |
| 2824 | ); |
| 2825 | self.pending_event_count += 1; |
| 2826 | self.pending_encoded_bytes = self.pending_encoded_bytes.saturating_add(encoded_len); |
| 2827 | } |
| 2828 | self.event_seq |
| 2829 | .entry(run_id.to_string()) |
| 2830 | .and_modify(|cursor| *cursor = (*cursor).max(seq)) |
| 2831 | .or_insert(seq); |
| 2832 | if require_durable_journal |
| 2833 | && self |
| 2834 | .journal |
| 2835 | .as_ref() |
| 2836 | .expect("checked above") |
| 2837 | .persist(&self.pending_runtime_events) |
| 2838 | .is_err() |
| 2839 | { |
| 2840 | if rollback_on_journal_failure && !already_pending { |
| 2841 | let remove_run = if let Some(events) = self.pending_runtime_events.get_mut(run_id) { |
| 2842 | events.remove(&seq); |
| 2843 | events.is_empty() |
| 2844 | } else { |
| 2845 | false |
| 2846 | }; |
| 2847 | if remove_run { |
| 2848 | self.pending_runtime_events.remove(run_id); |
| 2849 | } |
| 2850 | self.pending_event_count = self.pending_event_count.saturating_sub(1); |
| 2851 | self.pending_encoded_bytes = self.pending_encoded_bytes.saturating_sub(encoded_len); |
| 2852 | } |
| 2853 | if rollback_on_journal_failure { |
| 2854 | match previous_event_seq { |
| 2855 | Some(cursor) => { |
| 2856 | self.event_seq.insert(run_id.to_string(), cursor); |
| 2857 | } |
| 2858 | None => { |
| 2859 | self.event_seq.remove(run_id); |
| 2860 | } |
| 2861 | } |
| 2862 | } |
| 2863 | self.status_detail = |
| 2864 | "Remote control could not durably journal its account event.".to_string(); |
| 2865 | self.status = Status::Failed; |
| 2866 | self.ownership_blocked_until = Some(Instant::now() + OWNERSHIP_LOCK_AFTER_FAILURE); |
| 2867 | return false; |
| 2868 | } |
| 2869 | if defer { |
| 2870 | self.deferred_delta.insert(run_id.to_string(), seq); |
| 2871 | } else { |
| 2872 | if let Some(entry) = self |
| 2873 | .pending_runtime_events |
| 2874 | .get_mut(run_id) |
| 2875 | .and_then(|events| events.get_mut(&seq)) |
| 2876 | { |
| 2877 | entry.handed_off = true; |
| 2878 | } |
| 2879 | self.send_runtime_envelope(run_id, envelope); |
| 2880 | if !require_durable_journal { |
| 2881 | self.persist_journal(); |
| 2882 | } |
| 2883 | } |
| 2884 | true |
| 2885 | } |
| 2886 | |
| 2887 | /// Bounded-journal admission control. |
| 2888 | /// |
| 2889 | /// Integrity-critical envelopes may use the full budget, ordinary deltas |
| 2890 | /// only the unreserved share. A shed delta marks the run for terminal- |
| 2891 | /// boundary resynchronization; a shed integrity envelope can never happen |
| 2892 | /// silently — the relay fails closed and local input stays locked through |
| 2893 | /// the server lease expiry. |
| 2894 | fn reserve_capacity(&mut self, run_id: &str, encoded_len: usize, integrity: bool) -> bool { |
| 2895 | let (event_budget, byte_budget) = if integrity { |
| 2896 | (MAX_JOURNAL_EVENTS, MAX_JOURNAL_ENCODED_BYTES) |
| 2897 | } else { |
| 2898 | ( |
| 2899 | MAX_JOURNAL_EVENTS - JOURNAL_RESERVED_INTEGRITY_EVENTS, |
| 2900 | MAX_JOURNAL_ENCODED_BYTES - JOURNAL_RESERVED_INTEGRITY_BYTES, |
| 2901 | ) |
| 2902 | }; |
| 2903 | if self.pending_event_count < event_budget |
| 2904 | && self.pending_encoded_bytes.saturating_add(encoded_len) <= byte_budget |
| 2905 | { |
| 2906 | return true; |
| 2907 | } |
| 2908 | if integrity { |
| 2909 | self.status = Status::Failed; |
| 2910 | self.status_detail = |
| 2911 | "the runtime delivery buffer overflowed; waiting for the last server lease to expire safely" |
| 2912 | .to_string(); |
| 2913 | self.ownership_blocked_until = Some(Instant::now() + OWNERSHIP_LOCK_AFTER_FAILURE); |
| 2914 | } else { |
| 2915 | self.resync_required.insert(run_id.to_string()); |
| 2916 | } |
| 2917 | false |
| 2918 | } |
| 2919 | |
| 2920 | /// Streams a message delta, coalescing into the run's deferred envelope |
| 2921 | /// while that envelope has provably never been handed to the transport. |
| 2922 | fn upload_delta(&mut self, run_id: &str, turn_id: &str, content: &str) { |
| 2923 | if let Some(seq) = self.deferred_delta.get(run_id).copied() { |
| 2924 | if self.try_coalesce_delta(run_id, seq, turn_id, content) { |
| 2925 | return; |
| 2926 | } |
| 2927 | self.hand_off_deferred(run_id); |
| 2928 | } |
| 2929 | let seq = self.next_runtime_seq(run_id); |
| 2930 | let envelope = runtime_envelope( |
| 2931 | seq, |
| 2932 | "item.delta", |
| 2933 | Some(turn_id), |
| 2934 | chrono::Utc::now().to_rfc3339(), |
| 2935 | json!({ "kind": "agent_message", "delta": content }), |
| 2936 | ); |
| 2937 | self.queue_runtime_envelope_inner(run_id, envelope, true, false, false); |
| 2938 | } |
| 2939 | |
| 2940 | fn try_coalesce_delta(&mut self, run_id: &str, seq: u64, turn_id: &str, content: &str) -> bool { |
| 2941 | let Some(entry) = self |
| 2942 | .pending_runtime_events |
| 2943 | .get_mut(run_id) |
| 2944 | .and_then(|events| events.get_mut(&seq)) |
| 2945 | else { |
| 2946 | return false; |
| 2947 | }; |
| 2948 | if entry.handed_off |
| 2949 | || entry.envelope.get("turn_id").and_then(Value::as_str) != Some(turn_id) |
| 2950 | { |
| 2951 | return false; |
| 2952 | } |
| 2953 | let Some(existing) = entry |
| 2954 | .envelope |
| 2955 | .pointer("/payload/delta") |
| 2956 | .and_then(Value::as_str) |
| 2957 | else { |
| 2958 | return false; |
| 2959 | }; |
| 2960 | let merged = format!("{existing}{content}"); |
| 2961 | let mut candidate = entry.envelope.clone(); |
| 2962 | candidate["payload"]["delta"] = Value::String(merged); |
| 2963 | let encoded_len = serde_json::to_vec(&candidate) |
| 2964 | .map(|body| body.len()) |
| 2965 | .unwrap_or(usize::MAX); |
| 2966 | if encoded_len > DELTA_COALESCE_BYTE_CAP { |
| 2967 | return false; |
| 2968 | } |
| 2969 | let old_len = entry.encoded_len; |
| 2970 | entry.envelope = candidate; |
| 2971 | entry.encoded_len = encoded_len; |
| 2972 | self.pending_encoded_bytes = self |
| 2973 | .pending_encoded_bytes |
| 2974 | .saturating_sub(old_len) |
| 2975 | .saturating_add(encoded_len); |
| 2976 | true |
| 2977 | } |
| 2978 | |
| 2979 | /// Hands the run's deferred delta to the transport. From this point the |
| 2980 | /// envelope may have reached the server and becomes immutable. |
| 2981 | fn hand_off_deferred(&mut self, run_id: &str) { |
| 2982 | let Some(seq) = self.deferred_delta.get(run_id).copied() else { |
| 2983 | return; |
| 2984 | }; |
| 2985 | let Some(journal) = &self.journal else { |
| 2986 | self.status = Status::Failed; |
| 2987 | self.status_detail = |
| 2988 | "Remote control requires a durable account-delivery journal.".to_string(); |
| 2989 | self.ownership_blocked_until = Some(Instant::now() + OWNERSHIP_LOCK_AFTER_FAILURE); |
| 2990 | return; |
| 2991 | }; |
| 2992 | if journal.persist(&self.pending_runtime_events).is_err() { |
| 2993 | self.status = Status::Failed; |
| 2994 | self.status_detail = |
| 2995 | "Remote control could not durably journal its account event.".to_string(); |
| 2996 | self.ownership_blocked_until = Some(Instant::now() + OWNERSHIP_LOCK_AFTER_FAILURE); |
| 2997 | return; |
| 2998 | } |
| 2999 | self.deferred_delta.remove(run_id); |
| 3000 | let Some(envelope) = self |
| 3001 | .pending_runtime_events |
| 3002 | .get_mut(run_id) |
| 3003 | .and_then(|events| events.get_mut(&seq)) |
| 3004 | .map(|entry| { |
| 3005 | entry.handed_off = true; |
| 3006 | entry.envelope.clone() |
| 3007 | }) |
| 3008 | else { |
| 3009 | return; |
| 3010 | }; |
| 3011 | self.send_runtime_envelope(run_id, envelope); |
| 3012 | } |
| 3013 | |
| 3014 | fn hand_off_all_deferred(&mut self) { |
| 3015 | let runs: Vec<String> = self.deferred_delta.keys().cloned().collect(); |
| 3016 | for run_id in runs { |
| 3017 | self.hand_off_deferred(&run_id); |
| 3018 | } |
| 3019 | } |
| 3020 | |
| 3021 | /// The UI drains this after each engine event batch and answers with |
| 3022 | /// `upload_resync_snapshot` for the returned run. |
| 3023 | pub fn take_pending_resync(&mut self) -> Option<String> { |
| 3024 | self.resync_ready.pop() |
| 3025 | } |
| 3026 | |
| 3027 | /// Uploads a bounded current-history snapshot to repair account truth |
| 3028 | /// after deltas were shed under pressure. |
| 3029 | pub fn upload_resync_snapshot(&mut self, run_id: &str, messages: &[Message]) { |
| 3030 | let seq = self.next_runtime_seq(run_id); |
| 3031 | let envelope = bounded_session_snapshot_envelope(seq, messages); |
| 3032 | self.queue_runtime_envelope(run_id, envelope); |
| 3033 | } |
| 3034 | |
| 3035 | fn persist_journal(&mut self) { |
| 3036 | let Some(journal) = &self.journal else { |
| 3037 | return; |
| 3038 | }; |
| 3039 | if journal.persist(&self.pending_runtime_events).is_err() { |
| 3040 | // Crash durability is degraded, but nothing is lost silently: the |
| 3041 | // live relay keeps every envelope in memory and `/rc stop` still |
| 3042 | // requires the server-confirmed drain. |
| 3043 | self.status_detail = |
| 3044 | "the delivery journal could not be written; stop waits for server confirmation" |
| 3045 | .to_string(); |
| 3046 | } |
| 3047 | } |
| 3048 | |
| 3049 | /// Replaces the in-memory pending set from a verified journal load. |
| 3050 | fn reset_pending_from(&mut self, restored: HashMap<String, BTreeMap<u64, Value>>) { |
| 3051 | self.pending_runtime_events.clear(); |
| 3052 | self.deferred_delta.clear(); |
| 3053 | self.pending_event_count = 0; |
| 3054 | self.pending_encoded_bytes = 0; |
| 3055 | for (run_id, events) in restored { |
| 3056 | let mut pending = BTreeMap::new(); |
| 3057 | for (seq, envelope) in events { |
| 3058 | let encoded_len = serde_json::to_vec(&envelope) |
| 3059 | .map(|body| body.len()) |
| 3060 | .unwrap_or(usize::MAX); |
| 3061 | let integrity = |
| 3062 | runtime_envelope_event(&envelope).is_some_and(integrity_critical_event); |
| 3063 | self.pending_event_count += 1; |
| 3064 | self.pending_encoded_bytes = self.pending_encoded_bytes.saturating_add(encoded_len); |
| 3065 | pending.insert( |
| 3066 | seq, |
| 3067 | PendingRuntimeEnvelope { |
| 3068 | envelope, |
| 3069 | encoded_len, |
| 3070 | integrity, |
| 3071 | handed_off: false, |
| 3072 | }, |
| 3073 | ); |
| 3074 | } |
| 3075 | if let Some((top, _)) = pending.last_key_value() { |
| 3076 | let top = *top; |
| 3077 | self.event_seq |
| 3078 | .entry(run_id.clone()) |
| 3079 | .and_modify(|cursor| *cursor = (*cursor).max(top)) |
| 3080 | .or_insert(top); |
| 3081 | } |
| 3082 | if !pending.is_empty() { |
| 3083 | self.pending_runtime_events.insert(run_id, pending); |
| 3084 | } |
| 3085 | } |
| 3086 | } |
| 3087 | |
| 3088 | fn send_runtime_envelope(&self, run_id: &str, envelope: Value) { |
| 3089 | let Some(tx) = &self.worker_tx else { |
| 3090 | return; |
| 3091 | }; |
| 3092 | let _ = tx.send(WorkerCommand::Upload { |
| 3093 | run_id: run_id.to_string(), |
| 3094 | acknowledgements: Vec::new(), |
| 3095 | envelopes: vec![envelope], |
| 3096 | }); |
| 3097 | } |
| 3098 | |
| 3099 | fn flush_pending_runtime_events(&mut self, run_id: &str) { |
| 3100 | // A reconnect resend covers everything, deferred deltas included; |
| 3101 | // after this every envelope may have reached the server. |
| 3102 | self.deferred_delta.remove(run_id); |
| 3103 | let mut to_send = Vec::new(); |
| 3104 | if let Some(events) = self.pending_runtime_events.get_mut(run_id) { |
| 3105 | for entry in events.values_mut() { |
| 3106 | entry.handed_off = true; |
| 3107 | to_send.push(entry.envelope.clone()); |
| 3108 | } |
| 3109 | } |
| 3110 | if to_send.is_empty() { |
| 3111 | return; |
| 3112 | } |
| 3113 | for envelope in to_send { |
| 3114 | self.send_runtime_envelope(run_id, envelope); |
| 3115 | } |
| 3116 | self.persist_journal(); |
| 3117 | } |
| 3118 | |
| 3119 | fn flush_all_pending(&mut self) { |
| 3120 | let runs: Vec<String> = self.pending_runtime_events.keys().cloned().collect(); |
| 3121 | for run_id in runs { |
| 3122 | self.flush_pending_runtime_events(&run_id); |
| 3123 | } |
| 3124 | } |
| 3125 | |
| 3126 | fn reconcile_runtime_cursor(&mut self, run_id: &str, cursor: u64) { |
| 3127 | if cursor > JS_MAX_SAFE_INTEGER { |
| 3128 | self.status_detail = "the server returned an unsafe runtime cursor".to_string(); |
| 3129 | return; |
| 3130 | } |
| 3131 | let covered_classic_terminal = self |
| 3132 | .journal |
| 3133 | .as_ref() |
| 3134 | .and_then(RuntimeEventJournal::classic_lease) |
| 3135 | .filter(|lease| lease.run_id == run_id) |
| 3136 | .is_some_and(|lease| { |
| 3137 | let turn_id = lease |
| 3138 | .turn_id |
| 3139 | .clone() |
| 3140 | .unwrap_or_else(|| classic_recovery_turn_id(&lease.run_id, &lease.lease_id)); |
| 3141 | self.pending_runtime_events |
| 3142 | .get(run_id) |
| 3143 | .is_some_and(|events| { |
| 3144 | events.range(..=cursor).any(|(seq, entry)| { |
| 3145 | *seq > lease.seq_floor |
| 3146 | && runtime_envelope_event(&entry.envelope) == Some("turn.completed") |
| 3147 | && entry.envelope.get("turn_id").and_then(Value::as_str) |
| 3148 | == Some(turn_id.as_str()) |
| 3149 | }) |
| 3150 | }) |
| 3151 | }); |
| 3152 | let classic_state_result = if covered_classic_terminal { |
| 3153 | self.journal |
| 3154 | .as_ref() |
| 3155 | .expect("lease came from this journal") |
| 3156 | .set_classic_lease(None, &self.pending_runtime_events) |
| 3157 | } else if let Some(journal) = &self.journal { |
| 3158 | journal.advance_classic_seq_floor(run_id, cursor) |
| 3159 | } else { |
| 3160 | Ok(()) |
| 3161 | }; |
| 3162 | if let Err(error) = classic_state_result { |
| 3163 | // Never compact the only durable evidence of the run's sequence |
| 3164 | // history unless the canonical active lease first records the |
| 3165 | // acknowledged floor. A reconnect can retry this exact cursor. |
| 3166 | self.status = Status::Failed; |
| 3167 | self.status_detail = error; |
| 3168 | self.ownership_blocked_until = Some(Instant::now() + OWNERSHIP_LOCK_AFTER_FAILURE); |
| 3169 | return; |
| 3170 | } |
| 3171 | if covered_classic_terminal { |
| 3172 | self.active_run = None; |
| 3173 | self.pending_local_turn_run = None; |
| 3174 | } |
| 3175 | let mut empty = false; |
| 3176 | let mut retired_any = false; |
| 3177 | if let Some(events) = self.pending_runtime_events.get_mut(run_id) { |
| 3178 | let retired: Vec<u64> = events.range(..=cursor).map(|(seq, _)| *seq).collect(); |
| 3179 | for seq in retired { |
| 3180 | if let Some(entry) = events.remove(&seq) { |
| 3181 | retired_any = true; |
| 3182 | self.pending_event_count = self.pending_event_count.saturating_sub(1); |
| 3183 | self.pending_encoded_bytes = |
| 3184 | self.pending_encoded_bytes.saturating_sub(entry.encoded_len); |
| 3185 | } |
| 3186 | } |
| 3187 | empty = events.is_empty(); |
| 3188 | } |
| 3189 | if empty { |
| 3190 | self.pending_runtime_events.remove(run_id); |
| 3191 | } |
| 3192 | if self |
| 3193 | .deferred_delta |
| 3194 | .get(run_id) |
| 3195 | .is_some_and(|seq| *seq <= cursor) |
| 3196 | { |
| 3197 | self.deferred_delta.remove(run_id); |
| 3198 | } |
| 3199 | self.event_seq |
| 3200 | .entry(run_id.to_string()) |
| 3201 | .and_modify(|known| *known = (*known).max(cursor)) |
| 3202 | .or_insert(cursor); |
| 3203 | if retired_any { |
| 3204 | // Compact the acknowledged prefix out of the journal promptly. |
| 3205 | self.persist_journal(); |
| 3206 | } |
| 3207 | // Runtime Chat retains the exclusive provider-request lease through |
| 3208 | // local terminal projection *and* this server-confirmed cursor. Only |
| 3209 | // then may interactive/autonomous provider work resume for the |
| 3210 | // attached CWC run. Catalog/approval integrity rows conservatively |
| 3211 | // keep the same gate closed until their own acknowledgement as well. |
| 3212 | if !self.has_unacknowledged_integrity_events() |
| 3213 | && let Some(host) = &self.runtime_chat |
| 3214 | { |
| 3215 | host.release_inference_ownership_if_settled(); |
| 3216 | } |
| 3217 | } |
| 3218 | } |
| 3219 | |
| 3220 | impl Drop for RemoteControlController { |
| 3221 | fn drop(&mut self) { |
| 3222 | self.stop_worker(); |
| 3223 | } |
| 3224 | } |
| 3225 | |
| 3226 | impl RemoteCommand { |
| 3227 | fn kind(&self) -> &'static str { |
| 3228 | match self { |
| 3229 | Self::Prompt { .. } | Self::RuntimeChatPrompt(_) => "prompt.request", |
| 3230 | Self::Approval { .. } => "approval.decision", |
| 3231 | Self::Control { .. } => "run.control", |
| 3232 | } |
| 3233 | } |
| 3234 | |
| 3235 | fn turn_id(&self) -> Option<&str> { |
| 3236 | match self { |
| 3237 | Self::Prompt { turn_id, .. } => Some(turn_id), |
| 3238 | Self::RuntimeChatPrompt(prompt) => Some(&prompt.turn_id), |
| 3239 | Self::Control { turn_id, .. } => turn_id.as_deref(), |
| 3240 | Self::Approval { .. } => None, |
| 3241 | } |
| 3242 | } |
| 3243 | |
| 3244 | fn is_runtime_chat(&self) -> bool { |
| 3245 | matches!( |
| 3246 | self, |
| 3247 | Self::RuntimeChatPrompt(_) |
| 3248 | | Self::Control { |
| 3249 | runtime_chat: Some(_), |
| 3250 | .. |
| 3251 | } |
| 3252 | ) |
| 3253 | } |
| 3254 | } |
| 3255 | |
| 3256 | /// Opaque identity for the enrolled folder. It is a hash of the workspace |
| 3257 | /// path only: every session opened in the same folder shares one target, so |
| 3258 | /// the control plane sees one grant per folder rather than one per session |
| 3259 | /// (the session itself travels separately as `sessionRef`). |
| 3260 | pub fn target_ref(workspace: &Path) -> String { |
| 3261 | let mut hasher = Sha256::new(); |
| 3262 | hasher.update(b"codewhale-remote-target:v2\0"); |
| 3263 | hasher.update(workspace.to_string_lossy().as_bytes()); |
| 3264 | format!("target_{}", &bytes_to_hex(&hasher.finalize())[..32]) |
| 3265 | } |
| 3266 | |
| 3267 | /// Status-bar banner shown while the web owns this session. When the control |
| 3268 | /// plane advertised a session link the banner leads with it; otherwise it |
| 3269 | /// falls back to the opaque account and runner receipts. |
| 3270 | pub fn remote_control_banner(account_ref: &str, runner_id: &str, run_url: Option<&str>) -> String { |
| 3271 | match run_url { |
| 3272 | Some(url) => format!("WEB MIRROR · {url} · /rc stop"), |
| 3273 | None => format!("WEB MIRROR · account {account_ref} · runner {runner_id} · /rc stop"), |
| 3274 | } |
| 3275 | } |
| 3276 | |
| 3277 | /// Transcript note announcing where the live session can be followed. |
| 3278 | pub fn remote_control_link_notice(run_url: &str) -> String { |
| 3279 | format!( |
| 3280 | "Remote control is live at {run_url} — run /rc open to open it in your browser, or /rc link to print it. Both surfaces stay usable; one turn runs at a time." |
| 3281 | ) |
| 3282 | } |
| 3283 | |
| 3284 | fn runtime_envelope( |
| 3285 | seq: u64, |
| 3286 | event: &str, |
| 3287 | turn_id: Option<&str>, |
| 3288 | timestamp: String, |
| 3289 | payload: Value, |
| 3290 | ) -> Value { |
| 3291 | json!({ |
| 3292 | "schema_version": 1, |
| 3293 | "seq": seq, |
| 3294 | "event": event, |
| 3295 | "kind": event, |
| 3296 | "turn_id": turn_id, |
| 3297 | "timestamp": timestamp, |
| 3298 | "payload": payload, |
| 3299 | }) |
| 3300 | } |
| 3301 | |
| 3302 | fn runtime_chat_envelope( |
| 3303 | seq: u64, |
| 3304 | event: &str, |
| 3305 | thread_id: Option<&str>, |
| 3306 | turn_id: Option<&str>, |
| 3307 | source_event_id: Option<&str>, |
| 3308 | timestamp: String, |
| 3309 | payload: Value, |
| 3310 | ) -> Value { |
| 3311 | let mut envelope = json!({ |
| 3312 | "schema_version": 2, |
| 3313 | "seq": seq, |
| 3314 | "event": event, |
| 3315 | "kind": event, |
| 3316 | "timestamp": timestamp, |
| 3317 | "payload": payload, |
| 3318 | }); |
| 3319 | if let Some(thread_id) = thread_id { |
| 3320 | envelope["thread_id"] = json!(thread_id); |
| 3321 | } |
| 3322 | if let Some(turn_id) = turn_id { |
| 3323 | envelope["turn_id"] = json!(turn_id); |
| 3324 | } |
| 3325 | if let Some(source_event_id) = source_event_id { |
| 3326 | envelope["source_event_id"] = json!(source_event_id); |
| 3327 | } |
| 3328 | envelope |
| 3329 | } |
| 3330 | |
| 3331 | fn runtime_chat_catalog_source_event_id(run_id: &str, payload_fingerprint: &str) -> String { |
| 3332 | let mut hasher = Sha256::new(); |
| 3333 | hasher.update(b"codewhale.runtime-chat-catalog.v1\0"); |
| 3334 | hasher.update(run_id.as_bytes()); |
| 3335 | hasher.update(b"\0"); |
| 3336 | hasher.update(payload_fingerprint.as_bytes()); |
| 3337 | format!("catalog_{}", bytes_to_hex(&hasher.finalize())) |
| 3338 | } |
| 3339 | |
| 3340 | fn runtime_envelope_seq(envelope: &Value) -> Option<u64> { |
| 3341 | envelope |
| 3342 | .get("seq") |
| 3343 | .and_then(Value::as_u64) |
| 3344 | .filter(|seq| (1..=JS_MAX_SAFE_INTEGER).contains(seq)) |
| 3345 | } |
| 3346 | |
| 3347 | fn bounded_session_snapshot_envelope(seq: u64, messages: &[Message]) -> Value { |
| 3348 | let timestamp = chrono::Utc::now().to_rfc3339(); |
| 3349 | let candidates = messages |
| 3350 | .iter() |
| 3351 | .rev() |
| 3352 | .filter_map(project_session_message) |
| 3353 | .take(MAX_SNAPSHOT_MESSAGES) |
| 3354 | .collect::<Vec<_>>(); |
| 3355 | let mut kept = Vec::<Value>::new(); |
| 3356 | for (role, text) in candidates { |
| 3357 | let full = json!({ "role": role, "text": text }); |
| 3358 | kept.insert(0, full); |
| 3359 | if snapshot_envelope_len(seq, ×tamp, &kept) <= SNAPSHOT_ENVELOPE_BYTE_BUDGET { |
| 3360 | continue; |
| 3361 | } |
| 3362 | kept.remove(0); |
| 3363 | let max_chars = text.chars().count(); |
| 3364 | let mut low = 0usize; |
| 3365 | let mut high = max_chars; |
| 3366 | while low < high { |
| 3367 | let mid = low + (high - low).div_ceil(2); |
| 3368 | let prefix = unicode_prefix(&text, mid); |
| 3369 | kept.insert(0, json!({ "role": role, "text": prefix })); |
| 3370 | let fits = |
| 3371 | snapshot_envelope_len(seq, ×tamp, &kept) <= SNAPSHOT_ENVELOPE_BYTE_BUDGET; |
| 3372 | kept.remove(0); |
| 3373 | if fits { |
| 3374 | low = mid; |
| 3375 | } else { |
| 3376 | high = mid - 1; |
| 3377 | } |
| 3378 | } |
| 3379 | if low >= MIN_TRUNCATED_MESSAGE_CHARS || (kept.is_empty() && low > 0) { |
| 3380 | kept.insert( |
| 3381 | 0, |
| 3382 | json!({ "role": role, "text": unicode_prefix(&text, low) }), |
| 3383 | ); |
| 3384 | } |
| 3385 | break; |
| 3386 | } |
| 3387 | let envelope = runtime_envelope( |
| 3388 | seq, |
| 3389 | "session.snapshot", |
| 3390 | None, |
| 3391 | timestamp, |
| 3392 | json!({ "messages": kept }), |
| 3393 | ); |
| 3394 | debug_assert!( |
| 3395 | serde_json::to_vec(&envelope).is_ok_and(|body| body.len() <= SNAPSHOT_ENVELOPE_BYTE_BUDGET) |
| 3396 | ); |
| 3397 | envelope |
| 3398 | } |
| 3399 | |
| 3400 | fn project_session_message(message: &Message) -> Option<(String, String)> { |
| 3401 | let role = match message.role.as_str() { |
| 3402 | "user" => "user", |
| 3403 | "assistant" => "assistant", |
| 3404 | _ => return None, |
| 3405 | }; |
| 3406 | let text = message |
| 3407 | .content |
| 3408 | .iter() |
| 3409 | .filter_map(|block| match block { |
| 3410 | ContentBlock::Text { text, .. } => Some(text.as_str()), |
| 3411 | _ => None, |
| 3412 | }) |
| 3413 | .collect::<Vec<_>>() |
| 3414 | .join("\n"); |
| 3415 | if text.trim().is_empty() { |
| 3416 | return None; |
| 3417 | } |
| 3418 | Some(( |
| 3419 | role.to_string(), |
| 3420 | text.chars() |
| 3421 | .take(MAX_SNAPSHOT_MESSAGE_CHARS) |
| 3422 | .collect::<String>(), |
| 3423 | )) |
| 3424 | } |
| 3425 | |
| 3426 | fn snapshot_envelope_len(seq: u64, timestamp: &str, messages: &[Value]) -> usize { |
| 3427 | serde_json::to_vec(&runtime_envelope( |
| 3428 | seq, |
| 3429 | "session.snapshot", |
| 3430 | None, |
| 3431 | timestamp.to_string(), |
| 3432 | json!({ "messages": messages }), |
| 3433 | )) |
| 3434 | .map(|body| body.len()) |
| 3435 | .unwrap_or(usize::MAX) |
| 3436 | } |
| 3437 | |
| 3438 | fn unicode_prefix(value: &str, chars: usize) -> String { |
| 3439 | value.chars().take(chars).collect() |
| 3440 | } |
| 3441 | |
| 3442 | pub fn projected_approval_id(raw: &str) -> String { |
| 3443 | let mut hasher = Sha256::new(); |
| 3444 | hasher.update(b"local-runtime:approval\0"); |
| 3445 | hasher.update(raw.as_bytes()); |
| 3446 | format!("local_approval_{}", &bytes_to_hex(&hasher.finalize())[..24]) |
| 3447 | } |
| 3448 | |
| 3449 | fn projected_error_item_id(run_id: &str, turn_id: &str, code: &str) -> String { |
| 3450 | let mut hasher = Sha256::new(); |
| 3451 | hasher.update(b"local-runtime:error\0"); |
| 3452 | hasher.update(run_id.as_bytes()); |
| 3453 | hasher.update(b"\0"); |
| 3454 | hasher.update(turn_id.as_bytes()); |
| 3455 | hasher.update(b"\0"); |
| 3456 | hasher.update(code.as_bytes()); |
| 3457 | format!("local_item_{}", &bytes_to_hex(&hasher.finalize())[..24]) |
| 3458 | } |
| 3459 | |
| 3460 | fn bounded_remote_error_message(error: &str) -> String { |
| 3461 | let without_nul = error.replace('\0', " "); |
| 3462 | let redacted = codewhale_config::persistence::redact_secrets(&without_nul); |
| 3463 | let message = redacted.trim(); |
| 3464 | if message.is_empty() { |
| 3465 | return "The local model turn failed.".to_string(); |
| 3466 | } |
| 3467 | codewhale_util::utils::truncate_with_ellipsis(message, MAX_REMOTE_ERROR_MESSAGE_BYTES, "…") |
| 3468 | } |
| 3469 | |
| 3470 | fn command_fingerprint(command: &RemoteCommand) -> String { |
| 3471 | let canonical = format!("{command:?}"); |
| 3472 | bytes_to_hex(&Sha256::digest(canonical.as_bytes())) |
| 3473 | } |
| 3474 | |
| 3475 | fn bytes_to_hex(bytes: &[u8]) -> String { |
| 3476 | bytes.iter().map(|byte| format!("{byte:02x}")).collect() |
| 3477 | } |
| 3478 | |
| 3479 | async fn relay_worker( |
| 3480 | start: RemoteStart, |
| 3481 | mut runtime_chat: Option<RuntimeChatRelayHost>, |
| 3482 | mut worker_rx: mpsc::UnboundedReceiver<WorkerCommand>, |
| 3483 | event_tx: mpsc::UnboundedSender<RemoteEvent>, |
| 3484 | phase: &mut RelayPhase, |
| 3485 | ) -> Result<(), String> { |
| 3486 | let base = runner_control_plane_base()?; |
| 3487 | let client = codewhale_net::proxy::install_loopback_proxy( |
| 3488 | codewhale_release::tls::reqwest_client_builder(), |
| 3489 | ) |
| 3490 | .https_only(!cfg!(debug_assertions)) |
| 3491 | .redirect(reqwest::redirect::Policy::none()) |
| 3492 | .timeout(Duration::from_secs(20)) |
| 3493 | .build() |
| 3494 | .map_err(|_| "Remote control could not initialize secure networking.".to_string())?; |
| 3495 | |
| 3496 | let saved_enrollment = load_persisted_enrollment()?; |
| 3497 | // The device id is stable across enrollments: it is what lets the control |
| 3498 | // plane fold every folder enrolled from this terminal into one computer. |
| 3499 | let device_id = stable_device_id( |
| 3500 | saved_enrollment |
| 3501 | .as_ref() |
| 3502 | .map(|saved| saved.device_id.as_str()), |
| 3503 | )?; |
| 3504 | let mut enrollment = match saved_enrollment { |
| 3505 | Some(saved) if saved.matches(&start, &base) => { |
| 3506 | match refresh_enrollment(&client, saved).await { |
| 3507 | Ok(enrollment) => enrollment, |
| 3508 | Err(error) if error == "runner_enrollment_revoked" => { |
| 3509 | delete_persisted_enrollment(); |
| 3510 | enroll_device(&client, &base, &start, &device_id, &event_tx).await? |
| 3511 | } |
| 3512 | Err(error) => return Err(error), |
| 3513 | } |
| 3514 | } |
| 3515 | Some(_) => { |
| 3516 | delete_persisted_enrollment(); |
| 3517 | enroll_device(&client, &base, &start, &device_id, &event_tx).await? |
| 3518 | } |
| 3519 | None => enroll_device(&client, &base, &start, &device_id, &event_tx).await?, |
| 3520 | }; |
| 3521 | |
| 3522 | let connection = connect_runner(&client, &enrollment, &start).await?; |
| 3523 | // connect_runner answered with a server-confirmed attachment: a lease |
| 3524 | // exists from here on, and every later failure is a lost-after-lease |
| 3525 | // disconnect that must stay fail-closed. |
| 3526 | *phase = RelayPhase::Leased; |
| 3527 | let mut runner_id = connection.runner_id.clone(); |
| 3528 | event_tx |
| 3529 | .send(RemoteEvent::Connected { |
| 3530 | account_ref: enrollment.persisted.account_ref.clone(), |
| 3531 | runner_id: runner_id.clone(), |
| 3532 | target_ref: start.target_ref.clone(), |
| 3533 | attachment: connection.attachment, |
| 3534 | links: connection.links, |
| 3535 | }) |
| 3536 | .map_err(|_| "The terminal remote-control owner stopped.".to_string())?; |
| 3537 | let mut last_heartbeat = Instant::now() - HEARTBEAT_INTERVAL; |
| 3538 | let mut command_cursor: HashMap<String, u64> = HashMap::new(); |
| 3539 | let mut delivered: HashMap<(String, u64), String> = HashMap::new(); |
| 3540 | let mut runtime_outbox = RuntimeTransportOutbox::default(); |
| 3541 | let mut runtime_upload_tick = tokio::time::interval(RUNTIME_UPLOAD_RETRY_INTERVAL); |
| 3542 | runtime_upload_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); |
| 3543 | let mut runtime_chat_tick = tokio::time::interval(RUNTIME_UPLOAD_RETRY_INTERVAL); |
| 3544 | runtime_chat_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); |
| 3545 | // One deadline across loop iterations. Reconstructing `sleep(SYNC_INTERVAL)` |
| 3546 | // lets the 250ms Runtime Chat tick reset poll/heartbeat/token refresh. |
| 3547 | let mut sync_tick = |
| 3548 | tokio::time::interval_at(tokio::time::Instant::now() + SYNC_INTERVAL, SYNC_INTERVAL); |
| 3549 | sync_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); |
| 3550 | let mut runtime_retry_delay = RUNTIME_UPLOAD_RETRY_INTERVAL; |
| 3551 | let mut runtime_retry_not_before = Instant::now(); |
| 3552 | // One credential refresh per rejection streak (see |
| 3553 | // `RUNTIME_REFRESHED_CREDENTIAL_REFUSED`). |
| 3554 | let mut runtime_refreshed_since_accept = false; |
| 3555 | |
| 3556 | loop { |
| 3557 | tokio::select! { |
| 3558 | command = worker_rx.recv() => { |
| 3559 | match command { |
| 3560 | Some(WorkerCommand::Upload { run_id, acknowledgements, envelopes }) => { |
| 3561 | if !envelopes.is_empty() { |
| 3562 | if !acknowledgements.is_empty() || envelopes.len() != 1 { |
| 3563 | return Err("The local runtime queued an invalid event batch.".to_string()); |
| 3564 | } |
| 3565 | runtime_outbox.enqueue(&run_id, envelopes[0].clone())?; |
| 3566 | continue; |
| 3567 | } |
| 3568 | let body = Some(json!({ "acknowledgements": acknowledgements, "envelopes": envelopes })); |
| 3569 | let result = runner_request( |
| 3570 | &client, |
| 3571 | &enrollment, |
| 3572 | Method::POST, |
| 3573 | &["api", "local-runners", &runner_id, "runs", &run_id, "events"], |
| 3574 | &[], |
| 3575 | body.clone(), |
| 3576 | ) |
| 3577 | .await; |
| 3578 | if let Err(err) = result { |
| 3579 | if err == "runner_access_token_expired" { |
| 3580 | refresh_enrollment_and_reconnect( |
| 3581 | &client, |
| 3582 | &mut enrollment, |
| 3583 | &mut runner_id, |
| 3584 | &start, |
| 3585 | &event_tx, |
| 3586 | ) |
| 3587 | .await?; |
| 3588 | runner_request( |
| 3589 | &client, |
| 3590 | &enrollment, |
| 3591 | Method::POST, |
| 3592 | &["api", "local-runners", &runner_id, "runs", &run_id, "events"], |
| 3593 | &[], |
| 3594 | body, |
| 3595 | ) |
| 3596 | .await?; |
| 3597 | } else { |
| 3598 | return Err(err); |
| 3599 | } |
| 3600 | } |
| 3601 | } |
| 3602 | Some(WorkerCommand::ReleaseRuntimeChatHost) => { |
| 3603 | runtime_chat.take(); |
| 3604 | event_tx |
| 3605 | .send(RemoteEvent::RuntimeChatHostReleased) |
| 3606 | .map_err(|_| "The terminal remote-control owner stopped.".to_string())?; |
| 3607 | } |
| 3608 | Some(WorkerCommand::InstallRuntimeChatHost(host)) => { |
| 3609 | if runtime_chat.is_some() { |
| 3610 | return Err( |
| 3611 | "Runtime Chat received an invalid provider-refresh install." |
| 3612 | .to_string(), |
| 3613 | ); |
| 3614 | } |
| 3615 | runtime_chat = Some(host); |
| 3616 | } |
| 3617 | Some(WorkerCommand::Stop) | None => { |
| 3618 | // Do not return local input until the control plane has |
| 3619 | // durably released this lease. Every queued runtime |
| 3620 | // envelope must first drain behind the server-confirmed |
| 3621 | // cursor; only then may the offline heartbeat be |
| 3622 | // posted. If either cannot be confirmed, this worker |
| 3623 | // errors out and the UI keeps ownership locked through |
| 3624 | // the server-side lease expiry instead. |
| 3625 | drain_runtime_outbox_for_stop( |
| 3626 | &client, |
| 3627 | &mut enrollment, |
| 3628 | &mut runner_id, |
| 3629 | &start, |
| 3630 | &event_tx, |
| 3631 | &mut runtime_outbox, |
| 3632 | Instant::now() + STOP_DRAIN_DEADLINE, |
| 3633 | ) |
| 3634 | .await?; |
| 3635 | let hb = post_heartbeat(&client, &enrollment, &runner_id, &start, "offline").await; |
| 3636 | if let Err(err) = hb { |
| 3637 | if err == "runner_access_token_expired" { |
| 3638 | refresh_enrollment_and_reconnect( |
| 3639 | &client, |
| 3640 | &mut enrollment, |
| 3641 | &mut runner_id, |
| 3642 | &start, |
| 3643 | &event_tx, |
| 3644 | ) |
| 3645 | .await?; |
| 3646 | post_heartbeat(&client, &enrollment, &runner_id, &start, "offline").await?; |
| 3647 | } else { |
| 3648 | return Err(err); |
| 3649 | } |
| 3650 | } |
| 3651 | let _ = event_tx.send(RemoteEvent::Stopped); |
| 3652 | return Ok(()); |
| 3653 | } |
| 3654 | } |
| 3655 | } |
| 3656 | _ = runtime_upload_tick.tick(), if !runtime_outbox.events.is_empty() => { |
| 3657 | if Instant::now() < runtime_retry_not_before { |
| 3658 | continue; |
| 3659 | } |
| 3660 | match runtime_outbox |
| 3661 | .try_flush_one(&client, &enrollment, &runner_id) |
| 3662 | .await? |
| 3663 | { |
| 3664 | RuntimeFlushOutcome::Idle => { |
| 3665 | runtime_retry_delay = RUNTIME_UPLOAD_RETRY_INTERVAL; |
| 3666 | runtime_retry_not_before = Instant::now(); |
| 3667 | } |
| 3668 | RuntimeFlushOutcome::Retryable => { |
| 3669 | runtime_retry_not_before = Instant::now() + runtime_retry_delay; |
| 3670 | runtime_retry_delay = runtime_retry_delay |
| 3671 | .saturating_mul(2) |
| 3672 | .min(RUNTIME_UPLOAD_MAX_BACKOFF); |
| 3673 | } |
| 3674 | RuntimeFlushOutcome::Accepted { run_id, cursor } => { |
| 3675 | runtime_retry_delay = RUNTIME_UPLOAD_RETRY_INTERVAL; |
| 3676 | runtime_retry_not_before = Instant::now(); |
| 3677 | runtime_refreshed_since_accept = false; |
| 3678 | event_tx |
| 3679 | .send(RemoteEvent::RuntimeCursor { run_id, cursor }) |
| 3680 | .map_err(|_| "The terminal remote-control owner stopped.".to_string())?; |
| 3681 | } |
| 3682 | RuntimeFlushOutcome::AccessTokenExpired => { |
| 3683 | if std::mem::replace(&mut runtime_refreshed_since_accept, true) { |
| 3684 | return Err(RUNTIME_REFRESHED_CREDENTIAL_REFUSED.to_string()); |
| 3685 | } |
| 3686 | refresh_enrollment_and_reconnect( |
| 3687 | &client, |
| 3688 | &mut enrollment, |
| 3689 | &mut runner_id, |
| 3690 | &start, |
| 3691 | &event_tx, |
| 3692 | ) |
| 3693 | .await?; |
| 3694 | runtime_retry_delay = RUNTIME_UPLOAD_RETRY_INTERVAL; |
| 3695 | runtime_retry_not_before = Instant::now(); |
| 3696 | } |
| 3697 | } |
| 3698 | } |
| 3699 | _ = runtime_chat_tick.tick(), if runtime_chat.is_some() => { |
| 3700 | let host = runtime_chat.as_ref().expect("select guard requires Runtime Chat host"); |
| 3701 | for projection in host.pending_projections().await? { |
| 3702 | event_tx |
| 3703 | .send(RemoteEvent::RuntimeChatProjection(projection)) |
| 3704 | .map_err(|_| "The terminal remote-control owner stopped.".to_string())?; |
| 3705 | } |
| 3706 | } |
| 3707 | _ = sync_tick.tick() => { |
| 3708 | if enrollment_needs_refresh(&enrollment) { |
| 3709 | // Proactive refresh before expiry; reconnect to keep runner lease valid. |
| 3710 | match refresh_enrollment(&client, enrollment.persisted.clone()).await { |
| 3711 | Ok(new_enrollment) => { |
| 3712 | install_reconnected_enrollment( |
| 3713 | &mut enrollment, |
| 3714 | new_enrollment, |
| 3715 | &start, |
| 3716 | )?; |
| 3717 | reconnect_runner( |
| 3718 | &client, |
| 3719 | &enrollment, |
| 3720 | &mut runner_id, |
| 3721 | &start, |
| 3722 | &event_tx, |
| 3723 | ) |
| 3724 | .await?; |
| 3725 | } |
| 3726 | Err(err) if err == "runner_enrollment_revoked" => { |
| 3727 | delete_persisted_enrollment(); |
| 3728 | let device_id = enrollment.persisted.device_id.clone(); |
| 3729 | let candidate = |
| 3730 | enroll_device(&client, &base, &start, &device_id, &event_tx).await?; |
| 3731 | if let Err(error) = install_reconnected_enrollment( |
| 3732 | &mut enrollment, |
| 3733 | candidate, |
| 3734 | &start, |
| 3735 | ) { |
| 3736 | // enroll_device persists its candidate. Never retain a |
| 3737 | // credential for authority the live worker rejected. |
| 3738 | delete_persisted_enrollment(); |
| 3739 | return Err(error); |
| 3740 | } |
| 3741 | reconnect_runner( |
| 3742 | &client, |
| 3743 | &enrollment, |
| 3744 | &mut runner_id, |
| 3745 | &start, |
| 3746 | &event_tx, |
| 3747 | ) |
| 3748 | .await?; |
| 3749 | } |
| 3750 | Err(err) => return Err(err), |
| 3751 | } |
| 3752 | } |
| 3753 | if last_heartbeat.elapsed() >= HEARTBEAT_INTERVAL { |
| 3754 | let hb = post_heartbeat(&client, &enrollment, &runner_id, &start, "active").await; |
| 3755 | if let Err(err) = hb { |
| 3756 | if err == "runner_access_token_expired" { |
| 3757 | refresh_enrollment_and_reconnect( |
| 3758 | &client, |
| 3759 | &mut enrollment, |
| 3760 | &mut runner_id, |
| 3761 | &start, |
| 3762 | &event_tx, |
| 3763 | ) |
| 3764 | .await?; |
| 3765 | post_heartbeat(&client, &enrollment, &runner_id, &start, "active").await?; |
| 3766 | } else { |
| 3767 | return Err(err); |
| 3768 | } |
| 3769 | } |
| 3770 | last_heartbeat = Instant::now(); |
| 3771 | } |
| 3772 | let runs = match list_runs(&client, &enrollment, &runner_id).await { |
| 3773 | Ok(v) => v, |
| 3774 | Err(err) if err == "runner_access_token_expired" => { |
| 3775 | refresh_enrollment_and_reconnect( |
| 3776 | &client, |
| 3777 | &mut enrollment, |
| 3778 | &mut runner_id, |
| 3779 | &start, |
| 3780 | &event_tx, |
| 3781 | ) |
| 3782 | .await?; |
| 3783 | list_runs(&client, &enrollment, &runner_id).await? |
| 3784 | } |
| 3785 | Err(err) => return Err(err), |
| 3786 | }; |
| 3787 | for run_id in runs { |
| 3788 | let since = command_cursor.get(&run_id).copied().unwrap_or(0); |
| 3789 | let listed_commands = match list_commands( |
| 3790 | &client, |
| 3791 | &enrollment, |
| 3792 | &runner_id, |
| 3793 | &run_id, |
| 3794 | since, |
| 3795 | ) |
| 3796 | .await |
| 3797 | { |
| 3798 | Ok(v) => v, |
| 3799 | Err(err) if err == "runner_access_token_expired" => { |
| 3800 | refresh_enrollment_and_reconnect( |
| 3801 | &client, |
| 3802 | &mut enrollment, |
| 3803 | &mut runner_id, |
| 3804 | &start, |
| 3805 | &event_tx, |
| 3806 | ) |
| 3807 | .await?; |
| 3808 | list_commands(&client, &enrollment, &runner_id, &run_id, since).await? |
| 3809 | } |
| 3810 | Err(err) => return Err(err), |
| 3811 | }; |
| 3812 | for listed in listed_commands { |
| 3813 | let seq = listed.seq; |
| 3814 | if !listed.ack_status.is_empty() { |
| 3815 | if listed.ack_status == "accepted" { |
| 3816 | let rr = recover_run( |
| 3817 | &client, |
| 3818 | &enrollment, |
| 3819 | &runner_id, |
| 3820 | &run_id, |
| 3821 | "accepted command has no terminal acknowledgement after runner restart", |
| 3822 | ) |
| 3823 | .await; |
| 3824 | if let Err(err) = rr { |
| 3825 | if err == "runner_access_token_expired" { |
| 3826 | refresh_enrollment_and_reconnect( |
| 3827 | &client, |
| 3828 | &mut enrollment, |
| 3829 | &mut runner_id, |
| 3830 | &start, |
| 3831 | &event_tx, |
| 3832 | ) |
| 3833 | .await?; |
| 3834 | recover_run( |
| 3835 | &client, |
| 3836 | &enrollment, |
| 3837 | &runner_id, |
| 3838 | &run_id, |
| 3839 | "accepted command has no terminal acknowledgement after runner restart", |
| 3840 | ) |
| 3841 | .await?; |
| 3842 | } else { |
| 3843 | return Err(err); |
| 3844 | } |
| 3845 | } |
| 3846 | } |
| 3847 | command_cursor.insert(run_id.clone(), seq); |
| 3848 | continue; |
| 3849 | } |
| 3850 | let command = parse_remote_command(&listed.command, &run_id)?; |
| 3851 | let fingerprint = command_fingerprint(&command); |
| 3852 | let key = (run_id.clone(), seq); |
| 3853 | if let Some(existing) = delivered.get(&key) { |
| 3854 | if existing != &fingerprint { |
| 3855 | return Err("The control plane replayed a changed command sequence.".to_string()); |
| 3856 | } |
| 3857 | } else { |
| 3858 | delivered.insert(key, fingerprint); |
| 3859 | // Runtime Chat reports `applied` only after the |
| 3860 | // durable native thread manager has accepted the |
| 3861 | // exact operation key. Leaving the command |
| 3862 | // unacknowledged until then makes crash replay |
| 3863 | // naturally re-enter the idempotent native path. |
| 3864 | if !command.is_runtime_chat() { |
| 3865 | let up = upload_command_accepted( |
| 3866 | &client, |
| 3867 | &enrollment, |
| 3868 | &runner_id, |
| 3869 | &run_id, |
| 3870 | seq, |
| 3871 | &command, |
| 3872 | ) |
| 3873 | .await; |
| 3874 | if let Err(err) = up { |
| 3875 | if err == "runner_access_token_expired" { |
| 3876 | refresh_enrollment_and_reconnect( |
| 3877 | &client, |
| 3878 | &mut enrollment, |
| 3879 | &mut runner_id, |
| 3880 | &start, |
| 3881 | &event_tx, |
| 3882 | ) |
| 3883 | .await?; |
| 3884 | upload_command_accepted( |
| 3885 | &client, |
| 3886 | &enrollment, |
| 3887 | &runner_id, |
| 3888 | &run_id, |
| 3889 | seq, |
| 3890 | &command, |
| 3891 | ) |
| 3892 | .await?; |
| 3893 | } else { |
| 3894 | return Err(err); |
| 3895 | } |
| 3896 | } |
| 3897 | } |
| 3898 | event_tx.send(RemoteEvent::Command { |
| 3899 | run_id: run_id.clone(), |
| 3900 | seq, |
| 3901 | command, |
| 3902 | }).map_err(|_| "The terminal remote-control owner stopped.".to_string())?; |
| 3903 | } |
| 3904 | command_cursor.insert(run_id.clone(), seq.max(since)); |
| 3905 | } |
| 3906 | } |
| 3907 | } |
| 3908 | } |
| 3909 | } |
| 3910 | } |
| 3911 | |
| 3912 | impl RuntimeTransportOutbox { |
| 3913 | fn enqueue(&mut self, run_id: &str, envelope: Value) -> Result<(), String> { |
| 3914 | if !valid_opaque_ref(run_id) { |
| 3915 | return Err("The local runtime queued an invalid run id.".to_string()); |
| 3916 | } |
| 3917 | let seq = runtime_envelope_seq(&envelope) |
| 3918 | .ok_or_else(|| "The local runtime queued an invalid event sequence.".to_string())?; |
| 3919 | let encoded = serde_json::to_vec(&envelope) |
| 3920 | .map_err(|_| "The local runtime could not encode an event.".to_string())?; |
| 3921 | if encoded.len() > MAX_RUNTIME_ENVELOPE_BYTES { |
| 3922 | return Err("The local runtime queued an oversized event.".to_string()); |
| 3923 | } |
| 3924 | let key = (run_id.to_string(), seq); |
| 3925 | if let Some(existing) = self.events.get(&key) { |
| 3926 | if existing != &envelope { |
| 3927 | return Err( |
| 3928 | "The local runtime changed an unacknowledged event sequence.".to_string(), |
| 3929 | ); |
| 3930 | } |
| 3931 | return Ok(()); |
| 3932 | } |
| 3933 | self.events.insert(key, envelope); |
| 3934 | Ok(()) |
| 3935 | } |
| 3936 | |
| 3937 | async fn try_flush_one( |
| 3938 | &mut self, |
| 3939 | client: &Client, |
| 3940 | enrollment: &LiveEnrollment, |
| 3941 | runner_id: &str, |
| 3942 | ) -> Result<RuntimeFlushOutcome, String> { |
| 3943 | let Some(((run_id, seq), envelope)) = self |
| 3944 | .events |
| 3945 | .first_key_value() |
| 3946 | .map(|(key, value)| (key.clone(), value.clone())) |
| 3947 | else { |
| 3948 | return Ok(RuntimeFlushOutcome::Idle); |
| 3949 | }; |
| 3950 | match post_runtime_event(client, enrollment, runner_id, &run_id, seq, &envelope).await? { |
| 3951 | RuntimePostOutcome::Retryable => Ok(RuntimeFlushOutcome::Retryable), |
| 3952 | RuntimePostOutcome::AccessTokenExpired => Ok(RuntimeFlushOutcome::AccessTokenExpired), |
| 3953 | RuntimePostOutcome::Accepted(cursor) => { |
| 3954 | self.events.retain(|(pending_run, pending_seq), _| { |
| 3955 | pending_run != &run_id || *pending_seq > cursor |
| 3956 | }); |
| 3957 | Ok(RuntimeFlushOutcome::Accepted { run_id, cursor }) |
| 3958 | } |
| 3959 | } |
| 3960 | } |
| 3961 | } |
| 3962 | |
| 3963 | /// A runtime event refused (401/403) again right after a successful |
| 3964 | /// credential refresh is a terminal rejection, not an expired token: a |
| 3965 | /// revoked runner or a run this runner may not write. Refreshing again would |
| 3966 | /// loop at the upload retry interval forever. |
| 3967 | const RUNTIME_REFRESHED_CREDENTIAL_REFUSED: &str = "The remote-control server refused runtime events again with a freshly refreshed credential; stopping instead of retrying."; |
| 3968 | |
| 3969 | /// Flushes every queued runtime envelope through the server-confirmed cursor |
| 3970 | /// before a stop may be acknowledged. Emits `RuntimeCursor` events so the |
| 3971 | /// controller compacts its journal as acknowledgements land. Failing to drain |
| 3972 | /// by `deadline` is a hard error: the stop is *not* confirmed and the caller |
| 3973 | /// must leave ownership locked. |
| 3974 | #[allow(clippy::too_many_arguments)] |
| 3975 | async fn drain_runtime_outbox_for_stop( |
| 3976 | client: &Client, |
| 3977 | enrollment: &mut LiveEnrollment, |
| 3978 | runner_id: &mut String, |
| 3979 | start: &RemoteStart, |
| 3980 | event_tx: &mpsc::UnboundedSender<RemoteEvent>, |
| 3981 | outbox: &mut RuntimeTransportOutbox, |
| 3982 | deadline: Instant, |
| 3983 | ) -> Result<(), String> { |
| 3984 | let mut delay = RUNTIME_UPLOAD_RETRY_INTERVAL; |
| 3985 | let mut refreshed_since_accept = false; |
| 3986 | while !outbox.events.is_empty() { |
| 3987 | if Instant::now() >= deadline { |
| 3988 | return Err( |
| 3989 | "queued runtime events were not server-acknowledged in time; the stop was not confirmed" |
| 3990 | .to_string(), |
| 3991 | ); |
| 3992 | } |
| 3993 | match outbox.try_flush_one(client, enrollment, runner_id).await? { |
| 3994 | RuntimeFlushOutcome::Idle => break, |
| 3995 | RuntimeFlushOutcome::Accepted { run_id, cursor } => { |
| 3996 | delay = RUNTIME_UPLOAD_RETRY_INTERVAL; |
| 3997 | refreshed_since_accept = false; |
| 3998 | let _ = event_tx.send(RemoteEvent::RuntimeCursor { run_id, cursor }); |
| 3999 | } |
| 4000 | RuntimeFlushOutcome::Retryable => { |
| 4001 | tokio::time::sleep(delay).await; |
| 4002 | delay = delay.saturating_mul(2).min(RUNTIME_UPLOAD_MAX_BACKOFF); |
| 4003 | } |
| 4004 | RuntimeFlushOutcome::AccessTokenExpired => { |
| 4005 | if std::mem::replace(&mut refreshed_since_accept, true) { |
| 4006 | return Err(RUNTIME_REFRESHED_CREDENTIAL_REFUSED.to_string()); |
| 4007 | } |
| 4008 | refresh_enrollment_and_reconnect(client, enrollment, runner_id, start, event_tx) |
| 4009 | .await?; |
| 4010 | } |
| 4011 | } |
| 4012 | } |
| 4013 | Ok(()) |
| 4014 | } |
| 4015 | |
| 4016 | async fn post_runtime_event( |
| 4017 | client: &Client, |
| 4018 | enrollment: &LiveEnrollment, |
| 4019 | runner_id: &str, |
| 4020 | run_id: &str, |
| 4021 | seq: u64, |
| 4022 | envelope: &Value, |
| 4023 | ) -> Result<RuntimePostOutcome, String> { |
| 4024 | let url = control_plane_url( |
| 4025 | &enrollment.persisted.control_plane_base, |
| 4026 | &["api", "local-runners", runner_id, "runs", run_id, "events"], |
| 4027 | &[], |
| 4028 | )?; |
| 4029 | let response = match client |
| 4030 | .post(url) |
| 4031 | .bearer_auth(&enrollment.access_token) |
| 4032 | .json(&json!({ |
| 4033 | "acknowledgements": [], |
| 4034 | "envelopes": [envelope], |
| 4035 | })) |
| 4036 | .send() |
| 4037 | .await |
| 4038 | { |
| 4039 | Ok(response) => response, |
| 4040 | Err(_) => return Ok(RuntimePostOutcome::Retryable), |
| 4041 | }; |
| 4042 | let status = response.status(); |
| 4043 | if matches!(status, StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN) { |
| 4044 | return Ok(RuntimePostOutcome::AccessTokenExpired); |
| 4045 | } |
| 4046 | if matches!( |
| 4047 | status, |
| 4048 | StatusCode::REQUEST_TIMEOUT | StatusCode::TOO_EARLY | StatusCode::TOO_MANY_REQUESTS |
| 4049 | ) || status.is_server_error() |
| 4050 | { |
| 4051 | return Ok(RuntimePostOutcome::Retryable); |
| 4052 | } |
| 4053 | if !status.is_success() { |
| 4054 | return Err(format!( |
| 4055 | "The remote-control server rejected runtime event {seq} ({status})." |
| 4056 | )); |
| 4057 | } |
| 4058 | let value = match read_bounded_json(response).await { |
| 4059 | Ok(value) => value, |
| 4060 | Err(_) => return Ok(RuntimePostOutcome::Retryable), |
| 4061 | }; |
| 4062 | let Some(cursor) = value |
| 4063 | .get("cursor") |
| 4064 | .and_then(Value::as_u64) |
| 4065 | .filter(|cursor| *cursor >= seq && *cursor <= JS_MAX_SAFE_INTEGER) |
| 4066 | else { |
| 4067 | // A success without a durable cursor is indistinguishable from a lost |
| 4068 | // response. Retain and retry the exact same event body. |
| 4069 | return Ok(RuntimePostOutcome::Retryable); |
| 4070 | }; |
| 4071 | Ok(RuntimePostOutcome::Accepted(cursor)) |
| 4072 | } |
| 4073 | |
| 4074 | impl PersistedEnrollment { |
| 4075 | fn matches(&self, start: &RemoteStart, base: &str) -> bool { |
| 4076 | self.schema_version == 1 |
| 4077 | && self.control_plane_base == base |
| 4078 | && self.target_ref == start.target_ref |
| 4079 | && self.runtime_version == start.runtime_version |
| 4080 | && self.runtime_commit == start.runtime_commit |
| 4081 | && valid_opaque_ref(&self.runner_enrollment_id) |
| 4082 | && valid_opaque_ref(&self.account_ref) |
| 4083 | && valid_opaque_ref(&self.device_id) |
| 4084 | && valid_opaque_ref(&self.target_grant_ref) |
| 4085 | && valid_secret(&self.bootstrap_secret) |
| 4086 | } |
| 4087 | } |
| 4088 | |
| 4089 | async fn enroll_device( |
| 4090 | client: &Client, |
| 4091 | base: &str, |
| 4092 | start: &RemoteStart, |
| 4093 | device_id: &str, |
| 4094 | event_tx: &mpsc::UnboundedSender<RemoteEvent>, |
| 4095 | ) -> Result<LiveEnrollment, String> { |
| 4096 | let value = public_request( |
| 4097 | client, |
| 4098 | Method::POST, |
| 4099 | control_plane_url(base, &["api", "runner", "device", "start"], &[])?, |
| 4100 | json!({ |
| 4101 | "deviceId": device_id, |
| 4102 | "deviceLabel": "Codewhale terminal", |
| 4103 | "targetRef": start.target_ref, |
| 4104 | "targetLabel": start.workspace_label, |
| 4105 | "runtimeVersion": start.runtime_version, |
| 4106 | "runtimeCommit": start.runtime_commit, |
| 4107 | "capabilities": CAPABILITIES, |
| 4108 | }), |
| 4109 | ) |
| 4110 | .await?; |
| 4111 | let device_code = secret_field(&value, "deviceCode")?; |
| 4112 | let user_code = string_field(&value, "userCode")?; |
| 4113 | let verification_uri = string_field(&value, "verificationUriComplete")?; |
| 4114 | let interval = value |
| 4115 | .get("interval") |
| 4116 | .and_then(Value::as_u64) |
| 4117 | .filter(|value| (1..=30).contains(value)) |
| 4118 | .ok_or_else(|| { |
| 4119 | "Codewhale returned an invalid device authorization interval.".to_string() |
| 4120 | })?; |
| 4121 | let expires_in = value |
| 4122 | .get("expiresIn") |
| 4123 | .and_then(Value::as_u64) |
| 4124 | .filter(|value| (60..=1800).contains(value)) |
| 4125 | .ok_or_else(|| "Codewhale returned an invalid device authorization expiry.".to_string())?; |
| 4126 | validate_authorization_url(&verification_uri, &user_code)?; |
| 4127 | let _ = event_tx.send(RemoteEvent::Notice(format!( |
| 4128 | "Authorize this terminal at {verification_uri} (code {user_code})." |
| 4129 | ))); |
| 4130 | let _ = webbrowser::open(&verification_uri); |
| 4131 | let deadline = Instant::now() + Duration::from_secs(expires_in); |
| 4132 | loop { |
| 4133 | if Instant::now() >= deadline { |
| 4134 | return Err("Remote-control authorization expired; run /rc again.".to_string()); |
| 4135 | } |
| 4136 | tokio::time::sleep(Duration::from_secs(interval)).await; |
| 4137 | let response = client |
| 4138 | .post(control_plane_url( |
| 4139 | base, |
| 4140 | &["api", "runner", "device", "token"], |
| 4141 | &[], |
| 4142 | )?) |
| 4143 | .json(&json!({ "deviceCode": device_code })) |
| 4144 | .send() |
| 4145 | .await |
| 4146 | .map_err(|_| "Remote-control authorization could not reach Codewhale.".to_string())?; |
| 4147 | if response.status() == StatusCode::ACCEPTED { |
| 4148 | continue; |
| 4149 | } |
| 4150 | if !response.status().is_success() { |
| 4151 | return Err("Remote-control authorization was rejected.".to_string()); |
| 4152 | } |
| 4153 | let exchange = read_bounded_json(response).await?; |
| 4154 | let enrollment = enrollment_from_exchange(exchange, base, device_id, start)?; |
| 4155 | save_persisted_enrollment(&enrollment.persisted)?; |
| 4156 | return Ok(enrollment); |
| 4157 | } |
| 4158 | } |
| 4159 | |
| 4160 | fn enrollment_from_exchange( |
| 4161 | value: Value, |
| 4162 | base: &str, |
| 4163 | device_id: &str, |
| 4164 | start: &RemoteStart, |
| 4165 | ) -> Result<LiveEnrollment, String> { |
| 4166 | if value.get("status").and_then(Value::as_str) != Some("approved") { |
| 4167 | return Err("Codewhale returned an invalid runner credential.".to_string()); |
| 4168 | } |
| 4169 | let record = value |
| 4170 | .get("enrollment") |
| 4171 | .filter(|value| value.is_object()) |
| 4172 | .ok_or_else(|| "Codewhale returned an invalid runner credential.".to_string())?; |
| 4173 | let enrollment_id = opaque_field(record, "id")?; |
| 4174 | let account_ref = opaque_field(record, "userId")?; |
| 4175 | let returned_device = opaque_field(record, "deviceId")?; |
| 4176 | if returned_device != device_id |
| 4177 | || record.get("runtimeVersion").and_then(Value::as_str) |
| 4178 | != Some(start.runtime_version.as_str()) |
| 4179 | || record.get("runtimeCommit").and_then(Value::as_str) |
| 4180 | != Some(start.runtime_commit.as_str()) |
| 4181 | || !exact_capabilities(record.get("capabilities")) |
| 4182 | { |
| 4183 | return Err("The runner credential does not match this terminal.".to_string()); |
| 4184 | } |
| 4185 | let target_grant_ref = record |
| 4186 | .get("targetGrants") |
| 4187 | .and_then(Value::as_array) |
| 4188 | .and_then(|grants| { |
| 4189 | grants.iter().find(|grant| { |
| 4190 | grant.get("targetRef").and_then(Value::as_str) == Some(start.target_ref.as_str()) |
| 4191 | && grant |
| 4192 | .get("revokedAt") |
| 4193 | .and_then(Value::as_str) |
| 4194 | .unwrap_or_default() |
| 4195 | .is_empty() |
| 4196 | }) |
| 4197 | }) |
| 4198 | .and_then(|grant| grant.get("grantId")) |
| 4199 | .and_then(Value::as_str) |
| 4200 | .filter(|value| valid_opaque_ref(value)) |
| 4201 | .ok_or_else(|| "Codewhale returned no grant for this session.".to_string())? |
| 4202 | .to_string(); |
| 4203 | Ok(LiveEnrollment { |
| 4204 | persisted: PersistedEnrollment { |
| 4205 | schema_version: 1, |
| 4206 | control_plane_base: base.to_string(), |
| 4207 | runner_enrollment_id: enrollment_id, |
| 4208 | account_ref, |
| 4209 | device_id: returned_device, |
| 4210 | target_ref: start.target_ref.clone(), |
| 4211 | target_grant_ref, |
| 4212 | runtime_version: start.runtime_version.clone(), |
| 4213 | runtime_commit: start.runtime_commit.clone(), |
| 4214 | bootstrap_secret: secret_field(&value, "bootstrapSecret")?, |
| 4215 | }, |
| 4216 | access_token: access_token(&value)?, |
| 4217 | }) |
| 4218 | } |
| 4219 | |
| 4220 | async fn refresh_enrollment( |
| 4221 | client: &Client, |
| 4222 | persisted: PersistedEnrollment, |
| 4223 | ) -> Result<LiveEnrollment, String> { |
| 4224 | let url = control_plane_url( |
| 4225 | &persisted.control_plane_base, |
| 4226 | &["api", "runner", "enrollments", "token"], |
| 4227 | &[], |
| 4228 | )?; |
| 4229 | let response = client |
| 4230 | .post(url) |
| 4231 | .json(&json!({ |
| 4232 | "enrollmentId": persisted.runner_enrollment_id, |
| 4233 | "bootstrapSecret": persisted.bootstrap_secret, |
| 4234 | })) |
| 4235 | .send() |
| 4236 | .await |
| 4237 | .map_err(|_| "Remote-control credential refresh could not reach Codewhale.".to_string())?; |
| 4238 | if matches!( |
| 4239 | response.status(), |
| 4240 | StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN |
| 4241 | ) { |
| 4242 | return Err("runner_enrollment_revoked".to_string()); |
| 4243 | } |
| 4244 | if !response.status().is_success() { |
| 4245 | return Err("Remote-control credential refresh was rejected.".to_string()); |
| 4246 | } |
| 4247 | let value = read_bounded_json(response).await?; |
| 4248 | let record = value |
| 4249 | .get("enrollment") |
| 4250 | .filter(|value| value.is_object()) |
| 4251 | .ok_or_else(|| "Codewhale returned an invalid refreshed credential.".to_string())?; |
| 4252 | if record.get("id").and_then(Value::as_str) != Some(persisted.runner_enrollment_id.as_str()) |
| 4253 | || record.get("userId").and_then(Value::as_str) != Some(persisted.account_ref.as_str()) |
| 4254 | || record.get("deviceId").and_then(Value::as_str) != Some(persisted.device_id.as_str()) |
| 4255 | || record.get("runtimeVersion").and_then(Value::as_str) |
| 4256 | != Some(persisted.runtime_version.as_str()) |
| 4257 | || record.get("runtimeCommit").and_then(Value::as_str) |
| 4258 | != Some(persisted.runtime_commit.as_str()) |
| 4259 | || !exact_capabilities(record.get("capabilities")) |
| 4260 | { |
| 4261 | return Err("Codewhale returned a mismatched refreshed credential.".to_string()); |
| 4262 | } |
| 4263 | Ok(LiveEnrollment { |
| 4264 | persisted, |
| 4265 | access_token: access_token(&value)?, |
| 4266 | }) |
| 4267 | } |
| 4268 | |
| 4269 | async fn connect_runner( |
| 4270 | client: &Client, |
| 4271 | enrollment: &LiveEnrollment, |
| 4272 | start: &RemoteStart, |
| 4273 | ) -> Result<RunnerConnection, String> { |
| 4274 | let value = runner_request( |
| 4275 | client, |
| 4276 | enrollment, |
| 4277 | Method::POST, |
| 4278 | &["api", "local-runners", "connect"], |
| 4279 | &[], |
| 4280 | Some(connect_runner_body(enrollment, start)), |
| 4281 | ) |
| 4282 | .await?; |
| 4283 | parse_runner_connection(&value, enrollment, start) |
| 4284 | } |
| 4285 | |
| 4286 | fn connect_runner_body(enrollment: &LiveEnrollment, start: &RemoteStart) -> Value { |
| 4287 | let mut body = json!({ |
| 4288 | "deviceId": enrollment.persisted.device_id, |
| 4289 | "targetRef": start.target_ref, |
| 4290 | "displayLabel": start.workspace_label, |
| 4291 | "runtimeVersion": start.runtime_version, |
| 4292 | "runtimeCommit": start.runtime_commit, |
| 4293 | "capabilities": CAPABILITIES, |
| 4294 | "status": "active", |
| 4295 | // This is the only session attachment input. It is an opaque runtime |
| 4296 | // id, never a workspace path, prompt, environment, or credential. |
| 4297 | "sessionRef": start.session_id, |
| 4298 | "runtimeChatRelayProtocol": RUNTIME_CHAT_RELAY_PROTOCOL, |
| 4299 | }); |
| 4300 | if let Some(repo) = start |
| 4301 | .git_remote |
| 4302 | .as_deref() |
| 4303 | .and_then(normalize_observed_git_repo) |
| 4304 | { |
| 4305 | body["gitRemote"] = json!(repo); |
| 4306 | } |
| 4307 | body |
| 4308 | } |
| 4309 | |
| 4310 | fn parse_runner_connection( |
| 4311 | value: &Value, |
| 4312 | enrollment: &LiveEnrollment, |
| 4313 | start: &RemoteStart, |
| 4314 | ) -> Result<RunnerConnection, String> { |
| 4315 | let response = value |
| 4316 | .as_object() |
| 4317 | .filter(|record| { |
| 4318 | record.len() == 2 && record.contains_key("runner") && record.contains_key("attachment") |
| 4319 | }) |
| 4320 | .ok_or_else(|| "Codewhale returned an invalid runner attachment response.".to_string())?; |
| 4321 | let runner = response |
| 4322 | .get("runner") |
| 4323 | .and_then(Value::as_object) |
| 4324 | .ok_or_else(|| "Codewhale returned an invalid runner lease.".to_string())?; |
| 4325 | let runner_id = runner |
| 4326 | .get("id") |
| 4327 | .and_then(Value::as_str) |
| 4328 | .filter(|value| valid_opaque_ref(value)) |
| 4329 | .map(ToString::to_string) |
| 4330 | .ok_or_else(|| "Codewhale returned an invalid runner lease.".to_string())?; |
| 4331 | let runner_binding_matches = runner.get("userId").and_then(Value::as_str) |
| 4332 | == Some(enrollment.persisted.account_ref.as_str()) |
| 4333 | && runner.get("deviceId").and_then(Value::as_str) |
| 4334 | == Some(enrollment.persisted.device_id.as_str()) |
| 4335 | && runner.get("targetRef").and_then(Value::as_str) == Some(start.target_ref.as_str()) |
| 4336 | && runner.get("runtimeVersion").and_then(Value::as_str) |
| 4337 | == Some(start.runtime_version.as_str()) |
| 4338 | && runner.get("runtimeCommit").and_then(Value::as_str) |
| 4339 | == Some(start.runtime_commit.as_str()) |
| 4340 | && runner.get("controlPath").and_then(Value::as_str) == Some("outbound_relay") |
| 4341 | && runner.get("status").and_then(Value::as_str) == Some("active") |
| 4342 | && runner.get("active").and_then(Value::as_bool) == Some(true) |
| 4343 | && exact_capabilities(runner.get("capabilities")); |
| 4344 | if !runner_binding_matches { |
| 4345 | return Err("Codewhale returned a runner lease for a different session.".to_string()); |
| 4346 | } |
| 4347 | |
| 4348 | let attachment = response |
| 4349 | .get("attachment") |
| 4350 | .and_then(Value::as_object) |
| 4351 | .filter(|record| { |
| 4352 | record.len() == 6 |
| 4353 | && record.contains_key("runId") |
| 4354 | && record.contains_key("workspaceId") |
| 4355 | && record.contains_key("runtimeCursor") |
| 4356 | && record.contains_key("snapshotPresent") |
| 4357 | && record.contains_key("runtimeChatRelayProtocol") |
| 4358 | && record.contains_key("runtimeChatRelayChallenge") |
| 4359 | }) |
| 4360 | .ok_or_else(|| "Codewhale returned an invalid session attachment.".to_string())?; |
| 4361 | let run_id = attachment |
| 4362 | .get("runId") |
| 4363 | .and_then(Value::as_str) |
| 4364 | .filter(|value| valid_opaque_ref(value)) |
| 4365 | .map(ToString::to_string) |
| 4366 | .ok_or_else(|| "Codewhale returned an invalid attached run.".to_string())?; |
| 4367 | let workspace_id = attachment |
| 4368 | .get("workspaceId") |
| 4369 | .and_then(Value::as_str) |
| 4370 | .filter(|value| valid_opaque_ref(value)) |
| 4371 | .map(ToString::to_string) |
| 4372 | .ok_or_else(|| "Codewhale returned an invalid attached workspace.".to_string())?; |
| 4373 | let runtime_cursor = attachment |
| 4374 | .get("runtimeCursor") |
| 4375 | .and_then(Value::as_u64) |
| 4376 | .filter(|value| *value <= JS_MAX_SAFE_INTEGER) |
| 4377 | .ok_or_else(|| "Codewhale returned an invalid runtime event cursor.".to_string())?; |
| 4378 | let snapshot_present = attachment |
| 4379 | .get("snapshotPresent") |
| 4380 | .and_then(Value::as_bool) |
| 4381 | .ok_or_else(|| "Codewhale returned an invalid snapshot receipt.".to_string())?; |
| 4382 | let runtime_chat_relay_protocol = attachment |
| 4383 | .get("runtimeChatRelayProtocol") |
| 4384 | .and_then(Value::as_str) |
| 4385 | .filter(|value| *value == RUNTIME_CHAT_RELAY_PROTOCOL) |
| 4386 | .map(ToString::to_string) |
| 4387 | .ok_or_else(|| { |
| 4388 | "Codewhale returned an unsupported Runtime Chat relay protocol.".to_string() |
| 4389 | })?; |
| 4390 | let runtime_chat_relay_challenge = attachment |
| 4391 | .get("runtimeChatRelayChallenge") |
| 4392 | .and_then(Value::as_str) |
| 4393 | .filter(|value| { |
| 4394 | (32..=128).contains(&value.len()) |
| 4395 | && value |
| 4396 | .bytes() |
| 4397 | .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-')) |
| 4398 | }) |
| 4399 | .map(ToString::to_string) |
| 4400 | .ok_or_else(|| "Codewhale returned an invalid Runtime Chat relay challenge.".to_string())?; |
| 4401 | |
| 4402 | let links = parse_remote_links(runner, &run_id); |
| 4403 | |
| 4404 | Ok(RunnerConnection { |
| 4405 | runner_id, |
| 4406 | attachment: RemoteAttachment { |
| 4407 | run_id, |
| 4408 | workspace_id, |
| 4409 | runtime_cursor, |
| 4410 | snapshot_present, |
| 4411 | runtime_chat_relay_protocol, |
| 4412 | runtime_chat_relay_challenge, |
| 4413 | }, |
| 4414 | links, |
| 4415 | }) |
| 4416 | } |
| 4417 | |
| 4418 | /// Read the optional `runUrl` / `computerUrl` advertised on the runner lease. |
| 4419 | /// Absent fields yield `None`; present-but-invalid values are dropped (never |
| 4420 | /// displayed, never opened) rather than failing the attachment, because a |
| 4421 | /// link is a convenience receipt and not part of the ownership contract. |
| 4422 | fn parse_remote_links(runner: &serde_json::Map<String, Value>, run_id: &str) -> RemoteLinks { |
| 4423 | let run_url = runner |
| 4424 | .get("runUrl") |
| 4425 | .and_then(Value::as_str) |
| 4426 | .and_then(|value| validate_run_url(value, run_id)); |
| 4427 | let computer_url = runner |
| 4428 | .get("computerUrl") |
| 4429 | .and_then(Value::as_str) |
| 4430 | .and_then(validate_computer_url); |
| 4431 | RemoteLinks { |
| 4432 | run_url, |
| 4433 | computer_url, |
| 4434 | } |
| 4435 | } |
| 4436 | |
| 4437 | /// Parse a web link and accept it only on the Codewhale app origin (or, in |
| 4438 | /// debug builds only, a loopback development origin) with no credentials, |
| 4439 | /// port, or fragment — the same shape `validate_authorization_url` enforces. |
| 4440 | fn app_link_url(value: &str) -> Option<Url> { |
| 4441 | let trimmed = value.trim(); |
| 4442 | if trimmed.is_empty() || trimmed.len() > 2048 { |
| 4443 | return None; |
| 4444 | } |
| 4445 | let url = Url::parse(trimmed).ok()?; |
| 4446 | let production_origin = |
| 4447 | url.scheme() == "https" && url.host_str() == Some(APP_ORIGIN_HOST) && url.port().is_none(); |
| 4448 | let debug_loopback = cfg!(debug_assertions) |
| 4449 | && url.scheme() == "http" |
| 4450 | && matches!(url.host_str(), Some("127.0.0.1" | "localhost")); |
| 4451 | if !(production_origin || debug_loopback) |
| 4452 | || !url.username().is_empty() |
| 4453 | || url.password().is_some() |
| 4454 | || url.fragment().is_some() |
| 4455 | { |
| 4456 | return None; |
| 4457 | } |
| 4458 | Some(url) |
| 4459 | } |
| 4460 | |
| 4461 | /// `/session?run=<runId>` for exactly the attached run; anything else is |
| 4462 | /// dropped so the terminal can never send the user to a different session. |
| 4463 | fn validate_run_url(value: &str, run_id: &str) -> Option<String> { |
| 4464 | let url = app_link_url(value)?; |
| 4465 | let pairs = url.query_pairs().collect::<Vec<_>>(); |
| 4466 | if url.path() != "/session" || pairs.len() != 1 || pairs[0].0 != "run" || pairs[0].1 != run_id { |
| 4467 | return None; |
| 4468 | } |
| 4469 | Some(url.to_string()) |
| 4470 | } |
| 4471 | |
| 4472 | /// `/settings` (optionally `?section=…`) on the app origin. |
| 4473 | fn validate_computer_url(value: &str) -> Option<String> { |
| 4474 | let url = app_link_url(value)?; |
| 4475 | let pairs = url.query_pairs().collect::<Vec<_>>(); |
| 4476 | if url.path() != "/settings" |
| 4477 | || pairs.len() > 1 |
| 4478 | || pairs.iter().any(|(key, _)| *key != "section") |
| 4479 | { |
| 4480 | return None; |
| 4481 | } |
| 4482 | Some(url.to_string()) |
| 4483 | } |
| 4484 | |
| 4485 | async fn post_heartbeat( |
| 4486 | client: &Client, |
| 4487 | enrollment: &LiveEnrollment, |
| 4488 | runner_id: &str, |
| 4489 | start: &RemoteStart, |
| 4490 | status: &str, |
| 4491 | ) -> Result<(), String> { |
| 4492 | runner_request( |
| 4493 | client, |
| 4494 | enrollment, |
| 4495 | Method::POST, |
| 4496 | &["api", "local-runners", runner_id, "heartbeat"], |
| 4497 | &[], |
| 4498 | Some(json!({ |
| 4499 | "runtimeVersion": start.runtime_version, |
| 4500 | "runtimeCommit": start.runtime_commit, |
| 4501 | "capabilities": CAPABILITIES, |
| 4502 | "status": status, |
| 4503 | })), |
| 4504 | ) |
| 4505 | .await |
| 4506 | .map(|_| ()) |
| 4507 | } |
| 4508 | |
| 4509 | async fn list_runs( |
| 4510 | client: &Client, |
| 4511 | enrollment: &LiveEnrollment, |
| 4512 | runner_id: &str, |
| 4513 | ) -> Result<Vec<String>, String> { |
| 4514 | let value = runner_request( |
| 4515 | client, |
| 4516 | enrollment, |
| 4517 | Method::GET, |
| 4518 | &["api", "local-runners", runner_id, "runs"], |
| 4519 | &[], |
| 4520 | None, |
| 4521 | ) |
| 4522 | .await?; |
| 4523 | let runs = value |
| 4524 | .get("runs") |
| 4525 | .and_then(Value::as_array) |
| 4526 | .filter(|runs| runs.len() <= MAX_RUNS) |
| 4527 | .ok_or_else(|| "Codewhale returned an invalid runner run list.".to_string())?; |
| 4528 | runs.iter() |
| 4529 | .map(|run| { |
| 4530 | run.get("id") |
| 4531 | .and_then(Value::as_str) |
| 4532 | .filter(|value| valid_opaque_ref(value)) |
| 4533 | .map(ToString::to_string) |
| 4534 | .ok_or_else(|| "Codewhale returned an invalid runner run.".to_string()) |
| 4535 | }) |
| 4536 | .collect() |
| 4537 | } |
| 4538 | |
| 4539 | async fn list_commands( |
| 4540 | client: &Client, |
| 4541 | enrollment: &LiveEnrollment, |
| 4542 | runner_id: &str, |
| 4543 | run_id: &str, |
| 4544 | since: u64, |
| 4545 | ) -> Result<Vec<ListedCommand>, String> { |
| 4546 | let value = runner_request( |
| 4547 | client, |
| 4548 | enrollment, |
| 4549 | Method::GET, |
| 4550 | &[ |
| 4551 | "api", |
| 4552 | "local-runners", |
| 4553 | runner_id, |
| 4554 | "runs", |
| 4555 | run_id, |
| 4556 | "commands", |
| 4557 | ], |
| 4558 | &[ |
| 4559 | ("since_seq", since.to_string()), |
| 4560 | ("include_accepted", "1".to_string()), |
| 4561 | ], |
| 4562 | None, |
| 4563 | ) |
| 4564 | .await?; |
| 4565 | let commands = value |
| 4566 | .get("commands") |
| 4567 | .and_then(Value::as_array) |
| 4568 | .filter(|commands| commands.len() <= MAX_COMMANDS) |
| 4569 | .ok_or_else(|| "Codewhale returned an invalid command list.".to_string())?; |
| 4570 | commands |
| 4571 | .iter() |
| 4572 | .map(|item| { |
| 4573 | let seq = item |
| 4574 | .get("seq") |
| 4575 | .and_then(Value::as_u64) |
| 4576 | .filter(|value| *value > since) |
| 4577 | .ok_or_else(|| "Codewhale returned an invalid command sequence.".to_string())?; |
| 4578 | let command = item |
| 4579 | .get("command") |
| 4580 | .filter(|value| value.is_object()) |
| 4581 | .cloned() |
| 4582 | .ok_or_else(|| "Codewhale returned an invalid typed command.".to_string())?; |
| 4583 | Ok(ListedCommand { |
| 4584 | seq, |
| 4585 | command, |
| 4586 | ack_status: item |
| 4587 | .get("ackStatus") |
| 4588 | .and_then(Value::as_str) |
| 4589 | .unwrap_or_default() |
| 4590 | .to_string(), |
| 4591 | }) |
| 4592 | }) |
| 4593 | .collect() |
| 4594 | } |
| 4595 | |
| 4596 | struct ListedCommand { |
| 4597 | seq: u64, |
| 4598 | command: Value, |
| 4599 | ack_status: String, |
| 4600 | } |
| 4601 | |
| 4602 | async fn upload_command_accepted( |
| 4603 | client: &Client, |
| 4604 | enrollment: &LiveEnrollment, |
| 4605 | runner_id: &str, |
| 4606 | run_id: &str, |
| 4607 | seq: u64, |
| 4608 | command: &RemoteCommand, |
| 4609 | ) -> Result<(), String> { |
| 4610 | runner_request( |
| 4611 | client, |
| 4612 | enrollment, |
| 4613 | Method::POST, |
| 4614 | &["api", "local-runners", runner_id, "runs", run_id, "events"], |
| 4615 | &[], |
| 4616 | Some(json!({ |
| 4617 | "acknowledgements": [{ |
| 4618 | "commandSeq": seq, |
| 4619 | "commandType": command.kind(), |
| 4620 | "status": "accepted", |
| 4621 | "turnId": command.turn_id(), |
| 4622 | }], |
| 4623 | "envelopes": [], |
| 4624 | })), |
| 4625 | ) |
| 4626 | .await |
| 4627 | .map(|_| ()) |
| 4628 | } |
| 4629 | |
| 4630 | async fn recover_run( |
| 4631 | client: &Client, |
| 4632 | enrollment: &LiveEnrollment, |
| 4633 | runner_id: &str, |
| 4634 | run_id: &str, |
| 4635 | reason: &str, |
| 4636 | ) -> Result<(), String> { |
| 4637 | runner_request( |
| 4638 | client, |
| 4639 | enrollment, |
| 4640 | Method::POST, |
| 4641 | &[ |
| 4642 | "api", |
| 4643 | "local-runners", |
| 4644 | runner_id, |
| 4645 | "runs", |
| 4646 | run_id, |
| 4647 | "recovery", |
| 4648 | ], |
| 4649 | &[], |
| 4650 | Some(json!({ "reason": reason })), |
| 4651 | ) |
| 4652 | .await |
| 4653 | .map(|_| ()) |
| 4654 | } |
| 4655 | |
| 4656 | fn parse_remote_command(value: &Value, expected_run_id: &str) -> Result<RemoteCommand, String> { |
| 4657 | if value.get("runId").and_then(Value::as_str) != Some(expected_run_id) { |
| 4658 | return Err("A remote command targeted a different run.".to_string()); |
| 4659 | } |
| 4660 | match value.get("type").and_then(Value::as_str) { |
| 4661 | Some("prompt.request") => { |
| 4662 | let watch_fields = [ |
| 4663 | "watchEvent", |
| 4664 | "watch_event", |
| 4665 | "inputProvenance", |
| 4666 | "input_provenance", |
| 4667 | ]; |
| 4668 | if watch_fields.iter().any(|key| value.get(*key).is_some()) |
| 4669 | || value |
| 4670 | .get("metadata") |
| 4671 | .and_then(Value::as_object) |
| 4672 | .is_some_and(|metadata| { |
| 4673 | watch_fields.iter().any(|key| metadata.contains_key(*key)) |
| 4674 | }) |
| 4675 | { |
| 4676 | return Err("Automatic watch input is unsupported on this local coordinator; use the attested HTTP owner.".to_string()); |
| 4677 | } |
| 4678 | if value.get("structuredReview").is_some() && value.get("runtimeBindingId").is_none() { |
| 4679 | return Err( |
| 4680 | "A native review requires the authenticated Runtime binding.".to_string(), |
| 4681 | ); |
| 4682 | } |
| 4683 | if value.get("images").is_some() && value.get("runtimeBindingId").is_none() { |
| 4684 | return Err("Image input is unavailable for legacy remote Work; use native Runtime or Runtime Chat.".to_string()); |
| 4685 | } |
| 4686 | let exact_legacy_prompt = value.as_object().is_some_and(|record| { |
| 4687 | record.len() == 4 |
| 4688 | && ["type", "runId", "turnId", "prompt"] |
| 4689 | .iter() |
| 4690 | .all(|key| record.contains_key(*key)) |
| 4691 | }); |
| 4692 | if !exact_legacy_prompt { |
| 4693 | // A managed Chat prompt has a rich deny-unknown schema. Any |
| 4694 | // field beyond the exact legacy Work shape must satisfy that |
| 4695 | // schema in full; missing binding/version/route/tool fields can |
| 4696 | // never downgrade into the permissive Work parser. |
| 4697 | let prompt: RuntimeChatPrompt = |
| 4698 | serde_json::from_value(value.clone()).map_err(|_| { |
| 4699 | "Codewhale sent an invalid Runtime Chat prompt contract.".to_string() |
| 4700 | })?; |
| 4701 | prompt.validate_shape()?; |
| 4702 | if prompt.run_id != expected_run_id { |
| 4703 | return Err("A Runtime Chat prompt targeted a different run.".to_string()); |
| 4704 | } |
| 4705 | return Ok(RemoteCommand::RuntimeChatPrompt(Box::new(prompt))); |
| 4706 | } |
| 4707 | let turn_id = value |
| 4708 | .get("turnId") |
| 4709 | .and_then(Value::as_str) |
| 4710 | .filter(|value| valid_opaque_ref(value)) |
| 4711 | .ok_or_else(|| "A remote prompt had no valid turn id.".to_string())?; |
| 4712 | let prompt = value |
| 4713 | .get("prompt") |
| 4714 | .and_then(Value::as_str) |
| 4715 | .map(str::trim) |
| 4716 | .filter(|value| !value.is_empty() && value.len() <= 128 * 1024) |
| 4717 | .ok_or_else(|| "A remote prompt was empty or oversized.".to_string())?; |
| 4718 | Ok(RemoteCommand::Prompt { |
| 4719 | turn_id: turn_id.to_string(), |
| 4720 | prompt: prompt.to_string(), |
| 4721 | }) |
| 4722 | } |
| 4723 | Some("approval.decision") => { |
| 4724 | let exact_approval = value.as_object().is_some_and(|record| { |
| 4725 | record.len() == 4 |
| 4726 | && ["type", "runId", "gate", "decision"] |
| 4727 | .iter() |
| 4728 | .all(|key| record.contains_key(*key)) |
| 4729 | }); |
| 4730 | if !exact_approval { |
| 4731 | return Err("Codewhale sent an invalid approval contract.".to_string()); |
| 4732 | } |
| 4733 | let gate = value |
| 4734 | .get("gate") |
| 4735 | .and_then(Value::as_str) |
| 4736 | .filter(|value| valid_opaque_ref(value)) |
| 4737 | .ok_or_else(|| "A remote approval had no valid gate id.".to_string())?; |
| 4738 | let approved = match value.get("decision").and_then(Value::as_str) { |
| 4739 | Some("approved") => true, |
| 4740 | Some("denied") => false, |
| 4741 | _ => return Err("A remote approval had an invalid decision.".to_string()), |
| 4742 | }; |
| 4743 | Ok(RemoteCommand::Approval { |
| 4744 | gate: gate.to_string(), |
| 4745 | approved, |
| 4746 | }) |
| 4747 | } |
| 4748 | Some("run.control") => { |
| 4749 | let rich_runtime_control = |
| 4750 | value.get("runtimeBindingId").is_some() || value.get("runtimeThreadId").is_some(); |
| 4751 | if rich_runtime_control { |
| 4752 | let record = value |
| 4753 | .as_object() |
| 4754 | .filter(|record| { |
| 4755 | record.len() == 7 |
| 4756 | && record.contains_key("type") |
| 4757 | && record.contains_key("runId") |
| 4758 | && record.contains_key("action") |
| 4759 | && record.contains_key("reason") |
| 4760 | && record.contains_key("turnId") |
| 4761 | && record.contains_key("runtimeBindingId") |
| 4762 | && record.contains_key("runtimeThreadId") |
| 4763 | }) |
| 4764 | .ok_or_else(|| { |
| 4765 | "Codewhale sent an invalid Runtime Chat interrupt contract.".to_string() |
| 4766 | })?; |
| 4767 | if record.get("action").and_then(Value::as_str) != Some("interrupt") { |
| 4768 | return Err("Runtime Chat supports only an exact turn interrupt.".to_string()); |
| 4769 | } |
| 4770 | let reason = record |
| 4771 | .get("reason") |
| 4772 | .and_then(Value::as_str) |
| 4773 | .filter(|reason| { |
| 4774 | !reason.trim().is_empty() && reason.len() <= 800 && !reason.contains('\0') |
| 4775 | }) |
| 4776 | .ok_or_else(|| "A Runtime Chat interrupt reason is invalid.".to_string())?; |
| 4777 | let _ = reason; |
| 4778 | let turn_id = record |
| 4779 | .get("turnId") |
| 4780 | .and_then(Value::as_str) |
| 4781 | .ok_or_else(|| "A Runtime Chat interrupt turn is invalid.".to_string())? |
| 4782 | .to_string(); |
| 4783 | let scope = RuntimeChatControlScope { |
| 4784 | runtime_binding_id: record |
| 4785 | .get("runtimeBindingId") |
| 4786 | .and_then(Value::as_str) |
| 4787 | .ok_or_else(|| "A Runtime Chat interrupt binding is invalid.".to_string())? |
| 4788 | .to_string(), |
| 4789 | runtime_thread_id: record |
| 4790 | .get("runtimeThreadId") |
| 4791 | .and_then(Value::as_str) |
| 4792 | .ok_or_else(|| "A Runtime Chat interrupt thread is invalid.".to_string())? |
| 4793 | .to_string(), |
| 4794 | }; |
| 4795 | scope.validate_for_turn(&turn_id)?; |
| 4796 | return Ok(RemoteCommand::Control { |
| 4797 | action: RemoteControlRequest::Interrupt, |
| 4798 | turn_id: Some(turn_id), |
| 4799 | runtime_chat: Some(scope), |
| 4800 | }); |
| 4801 | } |
| 4802 | let exact_legacy_control = value.as_object().is_some_and(|record| { |
| 4803 | record.len() == 4 |
| 4804 | && ["type", "runId", "action", "turnId"] |
| 4805 | .iter() |
| 4806 | .all(|key| record.contains_key(*key)) |
| 4807 | }); |
| 4808 | if !exact_legacy_control { |
| 4809 | return Err("Codewhale sent an invalid run-control contract.".to_string()); |
| 4810 | } |
| 4811 | let action = match value.get("action").and_then(Value::as_str) { |
| 4812 | Some("interrupt") => RemoteControlRequest::Interrupt, |
| 4813 | Some("cancel") => RemoteControlRequest::Cancel, |
| 4814 | _ => return Err("A remote run-control command had an invalid action.".to_string()), |
| 4815 | }; |
| 4816 | let turn_id = value |
| 4817 | .get("turnId") |
| 4818 | .and_then(Value::as_str) |
| 4819 | .filter(|turn_id| valid_opaque_ref(turn_id)) |
| 4820 | .map(ToString::to_string) |
| 4821 | .ok_or_else(|| "A remote run-control command had an invalid turn.".to_string())?; |
| 4822 | Ok(RemoteCommand::Control { |
| 4823 | action, |
| 4824 | turn_id: Some(turn_id), |
| 4825 | runtime_chat: None, |
| 4826 | }) |
| 4827 | } |
| 4828 | _ => Err("Codewhale sent an unsupported remote command.".to_string()), |
| 4829 | } |
| 4830 | } |
| 4831 | |
| 4832 | async fn runner_request( |
| 4833 | client: &Client, |
| 4834 | enrollment: &LiveEnrollment, |
| 4835 | method: Method, |
| 4836 | segments: &[&str], |
| 4837 | query: &[(&str, String)], |
| 4838 | body: Option<Value>, |
| 4839 | ) -> Result<Value, String> { |
| 4840 | let url = control_plane_url(&enrollment.persisted.control_plane_base, segments, query)?; |
| 4841 | let mut request = client |
| 4842 | .request(method, url) |
| 4843 | .bearer_auth(&enrollment.access_token); |
| 4844 | if let Some(body) = body { |
| 4845 | request = request.json(&body); |
| 4846 | } |
| 4847 | let response = request |
| 4848 | .send() |
| 4849 | .await |
| 4850 | .map_err(|_| "Remote control lost its secure connection.".to_string())?; |
| 4851 | if matches!( |
| 4852 | response.status(), |
| 4853 | StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN |
| 4854 | ) { |
| 4855 | return Err("runner_access_token_expired".to_string()); |
| 4856 | } |
| 4857 | if !response.status().is_success() { |
| 4858 | let status = response.status(); |
| 4859 | let excerpt = rejection_excerpt(response).await; |
| 4860 | return Err(match excerpt { |
| 4861 | Some(reason) => { |
| 4862 | format!("The remote-control server rejected a request ({status}): {reason}.") |
| 4863 | } |
| 4864 | None => format!("The remote-control server rejected a request ({status})."), |
| 4865 | }); |
| 4866 | } |
| 4867 | let limit = if segments.last() == Some(&"commands") { |
| 4868 | codewhale_app_server_protocol::runtime::MAX_RUNTIME_IMAGE_BODY_BYTES |
| 4869 | } else { |
| 4870 | MAX_RESPONSE_BYTES |
| 4871 | }; |
| 4872 | read_bounded_json_with_limit(response, limit).await |
| 4873 | } |
| 4874 | |
| 4875 | async fn public_request( |
| 4876 | client: &Client, |
| 4877 | method: Method, |
| 4878 | url: Url, |
| 4879 | body: Value, |
| 4880 | ) -> Result<Value, String> { |
| 4881 | let response = client |
| 4882 | .request(method, url) |
| 4883 | .json(&body) |
| 4884 | .send() |
| 4885 | .await |
| 4886 | .map_err(|_| "Remote control could not reach Codewhale.".to_string())?; |
| 4887 | if !response.status().is_success() { |
| 4888 | let status = response.status(); |
| 4889 | let excerpt = rejection_excerpt(response).await; |
| 4890 | return Err(match excerpt { |
| 4891 | Some(reason) => { |
| 4892 | format!("Codewhale rejected remote-control enrollment ({status}): {reason}.") |
| 4893 | } |
| 4894 | None => format!("Codewhale rejected remote-control enrollment ({status})."), |
| 4895 | }); |
| 4896 | } |
| 4897 | read_bounded_json(response).await |
| 4898 | } |
| 4899 | |
| 4900 | /// Bounded error-body read: at most MAX_RESPONSE_BYTES, so a misbehaving |
| 4901 | /// control plane cannot force an unbounded in-memory read through the |
| 4902 | /// rejection-excerpt path. |
| 4903 | async fn rejection_excerpt(response: reqwest::Response) -> Option<String> { |
| 4904 | let status = response.status(); |
| 4905 | if response |
| 4906 | .content_length() |
| 4907 | .is_some_and(|length| length > MAX_RESPONSE_BYTES as u64) |
| 4908 | { |
| 4909 | return None; |
| 4910 | } |
| 4911 | let mut body = Vec::new(); |
| 4912 | let mut response = response; |
| 4913 | while let Some(chunk) = response.chunk().await.ok()? { |
| 4914 | body.extend_from_slice(&chunk); |
| 4915 | if body.len() > MAX_RESPONSE_BYTES { |
| 4916 | return None; |
| 4917 | } |
| 4918 | } |
| 4919 | sanitized_rejection_excerpt(&body, status) |
| 4920 | } |
| 4921 | |
| 4922 | fn sanitized_rejection_excerpt(body: &[u8], status: StatusCode) -> Option<String> { |
| 4923 | let parsed: Value = serde_json::from_slice(body).ok()?; |
| 4924 | match ( |
| 4925 | status, |
| 4926 | parsed |
| 4927 | .get("code") |
| 4928 | .or_else(|| parsed.pointer("/details/code")) |
| 4929 | .and_then(Value::as_str), |
| 4930 | ) { |
| 4931 | (StatusCode::SERVICE_UNAVAILABLE, Some("runner_runtime_identity_unavailable")) => { |
| 4932 | Some("Remote control is temporarily unavailable because this service has not been configured for a Codewhale build. Try again later".to_string()) |
| 4933 | } |
| 4934 | (StatusCode::UNPROCESSABLE_ENTITY, Some("runner_runtime_identity_unsupported")) => { |
| 4935 | Some("This Codewhale build is not accepted by the remote-control service. Check your installed version or contact the service administrator".to_string()) |
| 4936 | } |
| 4937 | _ => None, |
| 4938 | } |
| 4939 | } |
| 4940 | |
| 4941 | async fn read_bounded_json(response: reqwest::Response) -> Result<Value, String> { |
| 4942 | read_bounded_json_with_limit(response, MAX_RESPONSE_BYTES).await |
| 4943 | } |
| 4944 | |
| 4945 | async fn read_bounded_json_with_limit( |
| 4946 | mut response: reqwest::Response, |
| 4947 | limit: usize, |
| 4948 | ) -> Result<Value, String> { |
| 4949 | if response |
| 4950 | .content_length() |
| 4951 | .is_some_and(|length| length > limit as u64) |
| 4952 | { |
| 4953 | return Err("Codewhale returned an oversized remote-control response.".to_string()); |
| 4954 | } |
| 4955 | let mut bytes = Vec::new(); |
| 4956 | while let Some(chunk) = response |
| 4957 | .chunk() |
| 4958 | .await |
| 4959 | .map_err(|_| "Codewhale returned an unreadable response.".to_string())? |
| 4960 | { |
| 4961 | if bytes.len().saturating_add(chunk.len()) > limit { |
| 4962 | return Err("Codewhale returned an oversized remote-control response.".to_string()); |
| 4963 | } |
| 4964 | bytes.extend_from_slice(&chunk); |
| 4965 | } |
| 4966 | serde_json::from_slice(&bytes) |
| 4967 | .map_err(|_| "Codewhale returned an invalid remote-control response.".to_string()) |
| 4968 | } |
| 4969 | |
| 4970 | fn runner_control_plane_base() -> Result<String, String> { |
| 4971 | if cfg!(debug_assertions) |
| 4972 | && let Ok(value) = std::env::var("CWC_RUNNER_CONTROL_PLANE_BASE") |
| 4973 | { |
| 4974 | let parsed = |
| 4975 | Url::parse(&value).map_err(|_| "The runner control plane is invalid.".to_string())?; |
| 4976 | let loopback = parsed.scheme() == "http" |
| 4977 | && matches!(parsed.host_str(), Some("127.0.0.1" | "localhost")) |
| 4978 | && parsed.path() == "/" |
| 4979 | && parsed.query().is_none() |
| 4980 | && parsed.fragment().is_none(); |
| 4981 | if loopback { |
| 4982 | return Ok(parsed.to_string()); |
| 4983 | } |
| 4984 | return Err( |
| 4985 | "Debug remote control only accepts an explicit loopback control plane.".to_string(), |
| 4986 | ); |
| 4987 | } |
| 4988 | Ok(PRODUCTION_CONTROL_PLANE.to_string()) |
| 4989 | } |
| 4990 | |
| 4991 | fn control_plane_url( |
| 4992 | base: &str, |
| 4993 | segments: &[&str], |
| 4994 | query: &[(&str, String)], |
| 4995 | ) -> Result<Url, String> { |
| 4996 | let mut url = |
| 4997 | Url::parse(base).map_err(|_| "The runner control plane is invalid.".to_string())?; |
| 4998 | { |
| 4999 | let mut path = url |
| 5000 | .path_segments_mut() |
| 5001 | .map_err(|_| "The runner control plane is invalid.".to_string())?; |
| 5002 | path.pop_if_empty(); |
| 5003 | for segment in segments { |
| 5004 | path.push(segment); |
| 5005 | } |
| 5006 | } |
| 5007 | if !query.is_empty() { |
| 5008 | let mut pairs = url.query_pairs_mut(); |
| 5009 | for (key, value) in query { |
| 5010 | pairs.append_pair(key, value); |
| 5011 | } |
| 5012 | } |
| 5013 | Ok(url) |
| 5014 | } |
| 5015 | |
| 5016 | fn load_persisted_enrollment() -> Result<Option<PersistedEnrollment>, String> { |
| 5017 | let Some(raw) = remote_control_secrets() |
| 5018 | .get(ENROLLMENT_SECRET_SLOT) |
| 5019 | .map_err(|error| format!("Could not read the saved remote-control enrollment: {error}"))? |
| 5020 | else { |
| 5021 | return Ok(None); |
| 5022 | }; |
| 5023 | serde_json::from_str(&raw) |
| 5024 | .map(Some) |
| 5025 | .map_err(|_| "The saved remote-control enrollment is invalid.".to_string()) |
| 5026 | } |
| 5027 | |
| 5028 | fn save_persisted_enrollment(enrollment: &PersistedEnrollment) -> Result<(), String> { |
| 5029 | let raw = serde_json::to_string(enrollment) |
| 5030 | .map_err(|_| "Could not encode the remote-control enrollment.".to_string())?; |
| 5031 | remote_control_secrets() |
| 5032 | .set(ENROLLMENT_SECRET_SLOT, &raw) |
| 5033 | .map_err(|error| format!("Could not securely save the remote-control enrollment: {error}")) |
| 5034 | } |
| 5035 | |
| 5036 | fn load_persisted_device_identity() -> Result<Option<PersistedDeviceIdentity>, String> { |
| 5037 | let Some(raw) = remote_control_secrets() |
| 5038 | .get(DEVICE_IDENTITY_SECRET_SLOT) |
| 5039 | .map_err(|error| format!("Could not read the saved remote-control device id: {error}"))? |
| 5040 | else { |
| 5041 | return Ok(None); |
| 5042 | }; |
| 5043 | // An unreadable identity is replaced rather than fatal: the worst case is |
| 5044 | // one extra computer row, never a lost session. |
| 5045 | Ok(serde_json::from_str(&raw).ok()) |
| 5046 | } |
| 5047 | |
| 5048 | fn save_persisted_device_identity(identity: &PersistedDeviceIdentity) -> Result<(), String> { |
| 5049 | let raw = serde_json::to_string(identity) |
| 5050 | .map_err(|_| "Could not encode the remote-control device id.".to_string())?; |
| 5051 | remote_control_secrets() |
| 5052 | .set(DEVICE_IDENTITY_SECRET_SLOT, &raw) |
| 5053 | .map_err(|error| format!("Could not securely save the remote-control device id: {error}")) |
| 5054 | } |
| 5055 | |
| 5056 | /// Load (or mint and persist) the machine-stable device id. |
| 5057 | fn stable_device_id(enrollment_device_id: Option<&str>) -> Result<String, String> { |
| 5058 | let saved = load_persisted_device_identity()?; |
| 5059 | let (device_id, needs_save) = resolve_device_identity(saved, enrollment_device_id); |
| 5060 | if needs_save { |
| 5061 | save_persisted_device_identity(&PersistedDeviceIdentity { |
| 5062 | schema_version: 1, |
| 5063 | device_id: device_id.clone(), |
| 5064 | })?; |
| 5065 | } |
| 5066 | Ok(device_id) |
| 5067 | } |
| 5068 | |
| 5069 | fn delete_persisted_enrollment() { |
| 5070 | if let Err(error) = remote_control_secrets().delete(ENROLLMENT_SECRET_SLOT) { |
| 5071 | tracing::warn!("could not delete revoked remote-control enrollment: {error}"); |
| 5072 | } |
| 5073 | } |
| 5074 | |
| 5075 | /// Remote-control enrollment/device receipts deliberately use Codewhale's |
| 5076 | /// permission-bounded file store even when the operator chose the OS keyring |
| 5077 | /// for model-provider credentials. This keeps `/rc` and desktop dogfood from |
| 5078 | /// triggering a Keychain access dialog while preserving provider credential |
| 5079 | /// custody and its explicit backend selection unchanged. |
| 5080 | fn remote_control_secrets() -> codewhale_secrets::Secrets { |
| 5081 | codewhale_secrets::Secrets::file_backed() |
| 5082 | } |
| 5083 | |
| 5084 | fn install_reconnected_enrollment( |
| 5085 | current: &mut LiveEnrollment, |
| 5086 | candidate: LiveEnrollment, |
| 5087 | start: &RemoteStart, |
| 5088 | ) -> Result<(), String> { |
| 5089 | if candidate.persisted.account_ref != current.persisted.account_ref |
| 5090 | || candidate.persisted.target_ref != current.persisted.target_ref |
| 5091 | || candidate.persisted.target_ref != start.target_ref |
| 5092 | || candidate.persisted.device_id != current.persisted.device_id |
| 5093 | { |
| 5094 | return Err( |
| 5095 | "Remote control stopped because re-authorization selected a different account or folder. Start a new local session to switch authority." |
| 5096 | .to_string(), |
| 5097 | ); |
| 5098 | } |
| 5099 | *current = candidate; |
| 5100 | Ok(()) |
| 5101 | } |
| 5102 | |
| 5103 | async fn refresh_enrollment_and_reconnect( |
| 5104 | client: &Client, |
| 5105 | enrollment: &mut LiveEnrollment, |
| 5106 | runner_id: &mut String, |
| 5107 | start: &RemoteStart, |
| 5108 | event_tx: &mpsc::UnboundedSender<RemoteEvent>, |
| 5109 | ) -> Result<(), String> { |
| 5110 | let base = enrollment.persisted.control_plane_base.clone(); |
| 5111 | match refresh_enrollment(client, enrollment.persisted.clone()).await { |
| 5112 | Ok(new_enrollment) => { |
| 5113 | install_reconnected_enrollment(enrollment, new_enrollment, start)?; |
| 5114 | reconnect_runner(client, enrollment, runner_id, start, event_tx).await |
| 5115 | } |
| 5116 | Err(err) if err == "runner_enrollment_revoked" => { |
| 5117 | delete_persisted_enrollment(); |
| 5118 | let device_id = enrollment.persisted.device_id.clone(); |
| 5119 | let candidate = enroll_device(client, &base, start, &device_id, event_tx).await?; |
| 5120 | if let Err(error) = install_reconnected_enrollment(enrollment, candidate, start) { |
| 5121 | delete_persisted_enrollment(); |
| 5122 | return Err(error); |
| 5123 | } |
| 5124 | reconnect_runner(client, enrollment, runner_id, start, event_tx).await |
| 5125 | } |
| 5126 | Err(err) => Err(err), |
| 5127 | } |
| 5128 | } |
| 5129 | |
| 5130 | async fn reconnect_runner( |
| 5131 | client: &Client, |
| 5132 | enrollment: &LiveEnrollment, |
| 5133 | runner_id: &mut String, |
| 5134 | start: &RemoteStart, |
| 5135 | event_tx: &mpsc::UnboundedSender<RemoteEvent>, |
| 5136 | ) -> Result<(), String> { |
| 5137 | let connection = connect_runner(client, enrollment, start).await?; |
| 5138 | *runner_id = connection.runner_id; |
| 5139 | event_tx |
| 5140 | .send(RemoteEvent::Attachment { |
| 5141 | account_ref: enrollment.persisted.account_ref.clone(), |
| 5142 | target_ref: enrollment.persisted.target_ref.clone(), |
| 5143 | attachment: connection.attachment, |
| 5144 | links: connection.links, |
| 5145 | }) |
| 5146 | .map_err(|_| "The terminal remote-control owner stopped.".to_string()) |
| 5147 | } |
| 5148 | |
| 5149 | fn enrollment_needs_refresh(enrollment: &LiveEnrollment) -> bool { |
| 5150 | jwt_expiry(&enrollment.access_token) |
| 5151 | .is_none_or(|expiry| expiry <= epoch_seconds().saturating_add(60)) |
| 5152 | } |
| 5153 | |
| 5154 | fn jwt_expiry(token: &str) -> Option<u64> { |
| 5155 | use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD}; |
| 5156 | let payload = URL_SAFE_NO_PAD.decode(token.split('.').nth(1)?).ok()?; |
| 5157 | serde_json::from_slice::<Value>(&payload) |
| 5158 | .ok()? |
| 5159 | .get("exp")? |
| 5160 | .as_u64() |
| 5161 | } |
| 5162 | |
| 5163 | fn access_token(value: &Value) -> Result<String, String> { |
| 5164 | let token = value |
| 5165 | .get("credential") |
| 5166 | .and_then(|value| value.get("accessToken")) |
| 5167 | .and_then(Value::as_str) |
| 5168 | .filter(|value| { |
| 5169 | (64..=8192).contains(&value.len()) && !value.chars().any(char::is_whitespace) |
| 5170 | }) |
| 5171 | .ok_or_else(|| "Codewhale returned an invalid runner access token.".to_string())? |
| 5172 | .to_string(); |
| 5173 | if jwt_expiry(&token).is_none_or(|expiry| expiry <= epoch_seconds()) { |
| 5174 | return Err("Codewhale returned an expired runner access token.".to_string()); |
| 5175 | } |
| 5176 | Ok(token) |
| 5177 | } |
| 5178 | |
| 5179 | fn exact_capabilities(value: Option<&Value>) -> bool { |
| 5180 | let Some(items) = value.and_then(Value::as_array) else { |
| 5181 | return false; |
| 5182 | }; |
| 5183 | let mut actual = items.iter().filter_map(Value::as_str).collect::<Vec<_>>(); |
| 5184 | actual.sort_unstable(); |
| 5185 | actual == CAPABILITIES |
| 5186 | } |
| 5187 | |
| 5188 | fn validate_authorization_url(value: &str, user_code: &str) -> Result<(), String> { |
| 5189 | let url = Url::parse(value) |
| 5190 | .map_err(|_| "Codewhale returned an invalid authorization URL.".to_string())?; |
| 5191 | let pairs = url.query_pairs().collect::<Vec<_>>(); |
| 5192 | if url.scheme() != "https" |
| 5193 | || url.host_str() != Some("app.codewhale.net") |
| 5194 | || url.path() != "/runner/authorize" |
| 5195 | || url.port().is_some() |
| 5196 | || !url.username().is_empty() |
| 5197 | || url.password().is_some() |
| 5198 | || url.fragment().is_some() |
| 5199 | || pairs.len() != 1 |
| 5200 | || pairs[0].0 != "user_code" |
| 5201 | || pairs[0].1 != user_code |
| 5202 | { |
| 5203 | return Err("Codewhale returned an invalid authorization URL.".to_string()); |
| 5204 | } |
| 5205 | Ok(()) |
| 5206 | } |
| 5207 | |
| 5208 | fn string_field(value: &Value, field: &str) -> Result<String, String> { |
| 5209 | value |
| 5210 | .get(field) |
| 5211 | .and_then(Value::as_str) |
| 5212 | .map(str::trim) |
| 5213 | .filter(|value| !value.is_empty() && value.len() <= 2048) |
| 5214 | .map(ToString::to_string) |
| 5215 | .ok_or_else(|| format!("Codewhale returned an invalid {field}.")) |
| 5216 | } |
| 5217 | |
| 5218 | fn secret_field(value: &Value, field: &str) -> Result<String, String> { |
| 5219 | value |
| 5220 | .get(field) |
| 5221 | .and_then(Value::as_str) |
| 5222 | .filter(|value| valid_secret(value)) |
| 5223 | .map(ToString::to_string) |
| 5224 | .ok_or_else(|| format!("Codewhale returned an invalid {field}.")) |
| 5225 | } |
| 5226 | |
| 5227 | fn opaque_field(value: &Value, field: &str) -> Result<String, String> { |
| 5228 | value |
| 5229 | .get(field) |
| 5230 | .and_then(Value::as_str) |
| 5231 | .filter(|value| valid_opaque_ref(value)) |
| 5232 | .map(ToString::to_string) |
| 5233 | .ok_or_else(|| format!("Codewhale returned an invalid {field}.")) |
| 5234 | } |
| 5235 | |
| 5236 | fn valid_opaque_ref(value: &str) -> bool { |
| 5237 | (3..=160).contains(&value.len()) |
| 5238 | && value |
| 5239 | .bytes() |
| 5240 | .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.')) |
| 5241 | } |
| 5242 | |
| 5243 | fn valid_session_ref(value: &str) -> bool { |
| 5244 | (1..=160).contains(&value.len()) |
| 5245 | && value |
| 5246 | .bytes() |
| 5247 | .next() |
| 5248 | .is_some_and(|byte| byte.is_ascii_alphanumeric()) |
| 5249 | && value.bytes().all(|byte| { |
| 5250 | byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.' | b':' | b'@') |
| 5251 | }) |
| 5252 | && !value.contains("..") |
| 5253 | } |
| 5254 | |
| 5255 | fn valid_secret(value: &str) -> bool { |
| 5256 | (32..=8192).contains(&value.len()) && !value.chars().any(char::is_whitespace) |
| 5257 | } |
| 5258 | |
| 5259 | fn valid_runtime_version(value: &str) -> bool { |
| 5260 | semver::Version::parse(value).is_ok() && value.len() <= 64 |
| 5261 | } |
| 5262 | |
| 5263 | fn valid_runtime_commit(value: &str) -> bool { |
| 5264 | value.len() == 40 && value.bytes().all(|byte| byte.is_ascii_hexdigit()) |
| 5265 | } |
| 5266 | |
| 5267 | fn epoch_seconds() -> u64 { |
| 5268 | SystemTime::now() |
| 5269 | .duration_since(UNIX_EPOCH) |
| 5270 | .unwrap_or_default() |
| 5271 | .as_secs() |
| 5272 | } |
| 5273 | |
| 5274 | #[cfg(test)] |
| 5275 | mod tests { |
| 5276 | use super::*; |
| 5277 | use codewhale_models::Role; |
| 5278 | use std::sync::{ |
| 5279 | Arc, Mutex, |
| 5280 | atomic::{AtomicUsize, Ordering}, |
| 5281 | }; |
| 5282 | use wiremock::{ |
| 5283 | Mock, MockServer, Request, Respond, ResponseTemplate, |
| 5284 | matchers::{body_json, method, path, query_param}, |
| 5285 | }; |
| 5286 | |
| 5287 | #[derive(Clone, Default)] |
| 5288 | struct AmbiguousRuntimeResponder { |
| 5289 | bodies: Arc<Mutex<Vec<Value>>>, |
| 5290 | } |
| 5291 | |
| 5292 | #[derive(Clone, Default)] |
| 5293 | struct ControlPollCounter { |
| 5294 | hits: Arc<AtomicUsize>, |
| 5295 | } |
| 5296 | |
| 5297 | impl Respond for ControlPollCounter { |
| 5298 | fn respond(&self, _request: &Request) -> ResponseTemplate { |
| 5299 | self.hits.fetch_add(1, Ordering::SeqCst); |
| 5300 | ResponseTemplate::new(200).set_body_json(json!({ "runs": [] })) |
| 5301 | } |
| 5302 | } |
| 5303 | |
| 5304 | impl Respond for AmbiguousRuntimeResponder { |
| 5305 | fn respond(&self, request: &Request) -> ResponseTemplate { |
| 5306 | let body: Value = serde_json::from_slice(&request.body).expect("runtime request JSON"); |
| 5307 | let mut bodies = self.bodies.lock().expect("runtime request bodies"); |
| 5308 | bodies.push(body); |
| 5309 | if bodies.len() == 1 { |
| 5310 | // Model a committed request whose response was truncated in |
| 5311 | // transit. The client must keep the exact body and retry. |
| 5312 | ResponseTemplate::new(200).set_body_raw("{", "application/json") |
| 5313 | } else { |
| 5314 | ResponseTemplate::new(200).set_body_json(json!({ |
| 5315 | "accepted": [], |
| 5316 | "count": 0, |
| 5317 | "cursor": 1 |
| 5318 | })) |
| 5319 | } |
| 5320 | } |
| 5321 | } |
| 5322 | |
| 5323 | fn text_message(role: &str, text: impl Into<String>) -> Message { |
| 5324 | Message { |
| 5325 | role: Role::from(role), |
| 5326 | content: vec![ContentBlock::Text { |
| 5327 | text: text.into(), |
| 5328 | cache_control: None, |
| 5329 | }], |
| 5330 | } |
| 5331 | } |
| 5332 | |
| 5333 | fn fixture_start() -> RemoteStart { |
| 5334 | RemoteStart { |
| 5335 | workspace_label: "private-project".to_string(), |
| 5336 | target_ref: "target_fixture".to_string(), |
| 5337 | session_id: "session:fixture@01".to_string(), |
| 5338 | runtime_version: "0.9.6".to_string(), |
| 5339 | runtime_commit: "a".repeat(40), |
| 5340 | journal_dir: None, |
| 5341 | git_remote: None, |
| 5342 | } |
| 5343 | } |
| 5344 | |
| 5345 | fn fixture_enrollment(base: &str) -> LiveEnrollment { |
| 5346 | LiveEnrollment { |
| 5347 | persisted: PersistedEnrollment { |
| 5348 | schema_version: 1, |
| 5349 | control_plane_base: base.to_string(), |
| 5350 | runner_enrollment_id: "enrollment_fixture".to_string(), |
| 5351 | account_ref: "account_fixture".to_string(), |
| 5352 | device_id: "device_fixture".to_string(), |
| 5353 | target_ref: "target_fixture".to_string(), |
| 5354 | target_grant_ref: "grant_fixture".to_string(), |
| 5355 | runtime_version: "0.9.6".to_string(), |
| 5356 | runtime_commit: "a".repeat(40), |
| 5357 | bootstrap_secret: "b".repeat(43), |
| 5358 | }, |
| 5359 | access_token: "fixture-runner-access-token".to_string(), |
| 5360 | } |
| 5361 | } |
| 5362 | |
| 5363 | fn fixture_connection_response() -> Value { |
| 5364 | json!({ |
| 5365 | "runner": { |
| 5366 | "id": "runner_fixture", |
| 5367 | "userId": "account_fixture", |
| 5368 | "deviceId": "device_fixture", |
| 5369 | "targetRef": "target_fixture", |
| 5370 | "displayLabel": "private-project", |
| 5371 | "runtimeVersion": "0.9.6", |
| 5372 | "runtimeCommit": "a".repeat(40), |
| 5373 | "capabilities": CAPABILITIES, |
| 5374 | "controlPath": "outbound_relay", |
| 5375 | "status": "active", |
| 5376 | "active": true, |
| 5377 | "capacity": 1, |
| 5378 | "lastHeartbeatAt": "2026-08-08T12:00:00.000Z", |
| 5379 | "expiresAt": "2026-08-08T12:01:30.000Z", |
| 5380 | "revokedAt": "", |
| 5381 | "createdAt": "2026-08-08T12:00:00.000Z", |
| 5382 | "updatedAt": "2026-08-08T12:00:00.000Z" |
| 5383 | }, |
| 5384 | "attachment": { |
| 5385 | "runId": "run_fixture", |
| 5386 | "workspaceId": "workspace_fixture", |
| 5387 | "runtimeCursor": 41, |
| 5388 | "snapshotPresent": false, |
| 5389 | "runtimeChatRelayProtocol": RUNTIME_CHAT_RELAY_PROTOCOL, |
| 5390 | "runtimeChatRelayChallenge": "a".repeat(32) |
| 5391 | } |
| 5392 | }) |
| 5393 | } |
| 5394 | |
| 5395 | #[test] |
| 5396 | fn observed_git_repo_is_owner_name_not_a_path() { |
| 5397 | assert_eq!( |
| 5398 | normalize_observed_git_repo("git@github.com:codewhale-hq/CodeWhale.git").as_deref(), |
| 5399 | Some("codewhale-hq/CodeWhale") |
| 5400 | ); |
| 5401 | assert_eq!( |
| 5402 | normalize_observed_git_repo("https://github.com/Hmbown/cwc.git").as_deref(), |
| 5403 | Some("Hmbown/cwc") |
| 5404 | ); |
| 5405 | assert_eq!( |
| 5406 | normalize_observed_git_repo("/Volumes/WorkSSD/project/codewhale"), |
| 5407 | None |
| 5408 | ); |
| 5409 | for private_or_untrusted in [ |
| 5410 | "file:///Users/alice/PrivateProject.git", |
| 5411 | "https://internal.example/acme/secret-repo.git", |
| 5412 | "https://alice:password@github.com/acme/repo.git", |
| 5413 | "https://github.com/acme/repo.git?token=secret", |
| 5414 | "ssh://git@github.com/acme/repo.git", |
| 5415 | "acme/secret-repo", |
| 5416 | ] { |
| 5417 | assert_eq!( |
| 5418 | normalize_observed_git_repo(private_or_untrusted), |
| 5419 | None, |
| 5420 | "untrusted git identity must not cross: {private_or_untrusted}" |
| 5421 | ); |
| 5422 | } |
| 5423 | } |
| 5424 | |
| 5425 | #[test] |
| 5426 | fn connect_body_can_carry_an_observed_repo_without_a_path() { |
| 5427 | let enrollment = fixture_enrollment("https://api.codewhale.net/"); |
| 5428 | let mut start = fixture_start(); |
| 5429 | start.git_remote = Some("git@github.com:codewhale-hq/CodeWhale.git".to_string()); |
| 5430 | let body = connect_runner_body(&enrollment, &start); |
| 5431 | assert_eq!(body["gitRemote"], "codewhale-hq/CodeWhale"); |
| 5432 | assert!(body.get("workspacePath").is_none()); |
| 5433 | assert!(body.get("path").is_none()); |
| 5434 | } |
| 5435 | |
| 5436 | #[test] |
| 5437 | fn live_worker_rejects_reenrollment_authority_switch_before_assignment() { |
| 5438 | let start = fixture_start(); |
| 5439 | let mut current = fixture_enrollment("https://api.codewhale.net/"); |
| 5440 | let original_access_token = current.access_token.clone(); |
| 5441 | let mut other_account = current.clone(); |
| 5442 | other_account.persisted.account_ref = "account_other".to_string(); |
| 5443 | other_account.access_token = "other-account-access-token".to_string(); |
| 5444 | let error = install_reconnected_enrollment(&mut current, other_account, &start) |
| 5445 | .expect_err("a live worker must never change tenant authority"); |
| 5446 | assert!(error.contains("different account or folder")); |
| 5447 | assert_eq!(current.persisted.account_ref, "account_fixture"); |
| 5448 | assert_eq!(current.persisted.target_ref, "target_fixture"); |
| 5449 | assert_eq!(current.access_token, original_access_token); |
| 5450 | |
| 5451 | let mut other_target = current.clone(); |
| 5452 | other_target.persisted.target_ref = "target_other".to_string(); |
| 5453 | assert!(install_reconnected_enrollment(&mut current, other_target, &start).is_err()); |
| 5454 | assert_eq!(current.persisted.target_ref, "target_fixture"); |
| 5455 | |
| 5456 | let mut refreshed = current.clone(); |
| 5457 | refreshed.access_token = "same-authority-refreshed-access-token".to_string(); |
| 5458 | install_reconnected_enrollment(&mut current, refreshed, &start).unwrap(); |
| 5459 | assert_eq!( |
| 5460 | current.access_token, |
| 5461 | "same-authority-refreshed-access-token" |
| 5462 | ); |
| 5463 | } |
| 5464 | |
| 5465 | #[test] |
| 5466 | fn target_identity_is_stable_without_exposing_the_path() { |
| 5467 | let target = target_ref(Path::new("/Users/alice/private/project")); |
| 5468 | assert!(target.starts_with("target_")); |
| 5469 | assert_eq!(target.len(), 39); |
| 5470 | assert!(!target.contains("alice")); |
| 5471 | // Every session opened in the same folder shares one target, so the |
| 5472 | // control plane keeps one grant per folder rather than one per `/rc`. |
| 5473 | assert_eq!( |
| 5474 | target, |
| 5475 | target_ref(Path::new("/Users/alice/private/project")) |
| 5476 | ); |
| 5477 | assert_ne!(target, target_ref(Path::new("/Users/alice/private/other"))); |
| 5478 | } |
| 5479 | |
| 5480 | #[test] |
| 5481 | fn runtime_chat_same_session_reconfigure_releases_then_reacquires_owner_lock() { |
| 5482 | let root = tempfile::tempdir().unwrap(); |
| 5483 | let registry = Arc::new(codewhale_plugins::PluginRegistry::empty(root.path())); |
| 5484 | let mut controller = RemoteControlController::default(); |
| 5485 | let old_config = { |
| 5486 | let __cw_config_init_0_0 = Some("ollama".to_string()); |
| 5487 | let __cw_config_init_0_1 = Some("old-safe-model".to_string()); |
| 5488 | let mut __cw_config_init_0_value: codewhale_runtime::config::Config = |
| 5489 | codewhale_runtime::config::Config::default(); |
| 5490 | __cw_config_init_0_value.provider = __cw_config_init_0_0; |
| 5491 | __cw_config_init_0_value.default_text_model = __cw_config_init_0_1; |
| 5492 | __cw_config_init_0_value |
| 5493 | }; |
| 5494 | controller |
| 5495 | .configure_runtime_chat( |
| 5496 | old_config, |
| 5497 | Arc::clone(®istry), |
| 5498 | root.path().join("runtime-chat"), |
| 5499 | "target_fixture".to_string(), |
| 5500 | "session_fixture".to_string(), |
| 5501 | ) |
| 5502 | .unwrap(); |
| 5503 | assert_eq!( |
| 5504 | controller |
| 5505 | .runtime_chat |
| 5506 | .as_ref() |
| 5507 | .unwrap() |
| 5508 | .configured_default_model_for_tests(), |
| 5509 | "old-safe-model" |
| 5510 | ); |
| 5511 | |
| 5512 | let mut competing = RemoteControlController::default(); |
| 5513 | assert!( |
| 5514 | competing |
| 5515 | .configure_runtime_chat( |
| 5516 | codewhale_runtime::config::Config::default(), |
| 5517 | Arc::clone(®istry), |
| 5518 | root.path().join("runtime-chat"), |
| 5519 | "target_fixture".to_string(), |
| 5520 | "session_fixture".to_string(), |
| 5521 | ) |
| 5522 | .is_err() |
| 5523 | ); |
| 5524 | |
| 5525 | let new_config = { |
| 5526 | let __cw_config_init_1_0 = Some("ollama".to_string()); |
| 5527 | let __cw_config_init_1_1 = Some("new-safe-model".to_string()); |
| 5528 | let mut __cw_config_init_1_value: codewhale_runtime::config::Config = |
| 5529 | codewhale_runtime::config::Config::default(); |
| 5530 | __cw_config_init_1_value.provider = __cw_config_init_1_0; |
| 5531 | __cw_config_init_1_value.default_text_model = __cw_config_init_1_1; |
| 5532 | __cw_config_init_1_value |
| 5533 | }; |
| 5534 | controller |
| 5535 | .configure_runtime_chat( |
| 5536 | new_config, |
| 5537 | Arc::clone(®istry), |
| 5538 | root.path().join("runtime-chat"), |
| 5539 | "target_fixture".to_string(), |
| 5540 | "session_fixture".to_string(), |
| 5541 | ) |
| 5542 | .unwrap(); |
| 5543 | assert_eq!( |
| 5544 | controller |
| 5545 | .runtime_chat |
| 5546 | .as_ref() |
| 5547 | .unwrap() |
| 5548 | .configured_default_model_for_tests(), |
| 5549 | "new-safe-model", |
| 5550 | "a settled same-scope restart must refresh immutable provider configuration" |
| 5551 | ); |
| 5552 | drop(controller); |
| 5553 | competing |
| 5554 | .configure_runtime_chat( |
| 5555 | codewhale_runtime::config::Config::default(), |
| 5556 | registry, |
| 5557 | root.path().join("runtime-chat"), |
| 5558 | "target_fixture".to_string(), |
| 5559 | "session_fixture".to_string(), |
| 5560 | ) |
| 5561 | .unwrap(); |
| 5562 | } |
| 5563 | |
| 5564 | #[test] |
| 5565 | fn runtime_chat_backlog_refreshes_immutable_config_before_new_catalog_or_prompt() { |
| 5566 | let root = tempfile::tempdir().unwrap(); |
| 5567 | let registry = Arc::new(codewhale_plugins::PluginRegistry::empty(root.path())); |
| 5568 | let mut controller = RemoteControlController::default(); |
| 5569 | let old_config = { |
| 5570 | let __cw_config_init_2_0 = Some("ollama".to_string()); |
| 5571 | let __cw_config_init_2_1 = Some("old-safe-model".to_string()); |
| 5572 | let mut __cw_config_init_2_value: codewhale_runtime::config::Config = |
| 5573 | codewhale_runtime::config::Config::default(); |
| 5574 | __cw_config_init_2_value.provider = __cw_config_init_2_0; |
| 5575 | __cw_config_init_2_value.default_text_model = __cw_config_init_2_1; |
| 5576 | __cw_config_init_2_value |
| 5577 | }; |
| 5578 | controller |
| 5579 | .configure_runtime_chat( |
| 5580 | old_config, |
| 5581 | Arc::clone(®istry), |
| 5582 | root.path().join("runtime-chat"), |
| 5583 | "target-1".to_string(), |
| 5584 | "session-1".to_string(), |
| 5585 | ) |
| 5586 | .unwrap(); |
| 5587 | controller |
| 5588 | .runtime_chat |
| 5589 | .as_ref() |
| 5590 | .unwrap() |
| 5591 | .bind_account("account-1", "target-1") |
| 5592 | .unwrap(); |
| 5593 | controller.journal = Some( |
| 5594 | RuntimeEventJournal::open(root.path(), "target-1", "session-1") |
| 5595 | .expect("runtime chat delivery journal"), |
| 5596 | ); |
| 5597 | |
| 5598 | let pending_seq = controller.next_runtime_seq("run-1"); |
| 5599 | assert!(controller.queue_runtime_chat_envelope( |
| 5600 | "run-1", |
| 5601 | runtime_chat_envelope( |
| 5602 | pending_seq, |
| 5603 | "runtime.catalog", |
| 5604 | None, |
| 5605 | None, |
| 5606 | Some("catalog_old_fixture"), |
| 5607 | RUNTIME_CHAT_CATALOG_TIMESTAMP.to_string(), |
| 5608 | json!({ "old": true }), |
| 5609 | ), |
| 5610 | )); |
| 5611 | let new_config = { |
| 5612 | let __cw_config_init_3_0 = Some("ollama".to_string()); |
| 5613 | let __cw_config_init_3_1 = Some("new-safe-model".to_string()); |
| 5614 | let mut __cw_config_init_3_value: codewhale_runtime::config::Config = |
| 5615 | codewhale_runtime::config::Config::default(); |
| 5616 | __cw_config_init_3_value.provider = __cw_config_init_3_0; |
| 5617 | __cw_config_init_3_value.default_text_model = __cw_config_init_3_1; |
| 5618 | __cw_config_init_3_value |
| 5619 | }; |
| 5620 | controller |
| 5621 | .configure_runtime_chat( |
| 5622 | new_config, |
| 5623 | Arc::clone(®istry), |
| 5624 | root.path().join("runtime-chat"), |
| 5625 | "target-1".to_string(), |
| 5626 | "session-1".to_string(), |
| 5627 | ) |
| 5628 | .unwrap(); |
| 5629 | assert!(controller.pending_runtime_chat_configuration.is_some()); |
| 5630 | assert_eq!( |
| 5631 | controller |
| 5632 | .runtime_chat |
| 5633 | .as_ref() |
| 5634 | .unwrap() |
| 5635 | .configured_default_model_for_tests(), |
| 5636 | "old-safe-model", |
| 5637 | "the old host remains only as the durable backlog owner" |
| 5638 | ); |
| 5639 | |
| 5640 | let (worker_tx, mut worker_rx) = mpsc::unbounded_channel(); |
| 5641 | let (event_tx, event_rx) = mpsc::unbounded_channel(); |
| 5642 | controller.worker_tx = Some(worker_tx); |
| 5643 | controller.event_rx = Some(event_rx); |
| 5644 | controller.status = Status::Connected; |
| 5645 | controller.account_ref = Some("account-1".to_string()); |
| 5646 | controller.target_ref = Some("target-1".to_string()); |
| 5647 | controller.attached_run_id = Some("run-1".to_string()); |
| 5648 | controller.attached_workspace_id = Some("workspace-1".to_string()); |
| 5649 | controller.runtime_chat_attachment = Some(RemoteAttachment { |
| 5650 | run_id: "run-1".to_string(), |
| 5651 | workspace_id: "workspace-1".to_string(), |
| 5652 | runtime_cursor: pending_seq, |
| 5653 | snapshot_present: false, |
| 5654 | runtime_chat_relay_protocol: RUNTIME_CHAT_RELAY_PROTOCOL.to_string(), |
| 5655 | runtime_chat_relay_challenge: "c".repeat(32), |
| 5656 | }); |
| 5657 | let command = parse_remote_command(&runtime_chat_prompt_fixture(), "run-1").unwrap(); |
| 5658 | assert!( |
| 5659 | controller.claim_command("run-1", 1, &command).is_err(), |
| 5660 | "no newly configured prompt may reach the stale host while backlog drains" |
| 5661 | ); |
| 5662 | |
| 5663 | event_tx |
| 5664 | .send(RemoteEvent::RuntimeCursor { |
| 5665 | run_id: "run-1".to_string(), |
| 5666 | cursor: pending_seq, |
| 5667 | }) |
| 5668 | .unwrap(); |
| 5669 | assert!(matches!( |
| 5670 | controller.try_next_event(), |
| 5671 | Some(RemoteEvent::RuntimeCursor { .. }) |
| 5672 | )); |
| 5673 | assert!(matches!( |
| 5674 | worker_rx.try_recv().unwrap(), |
| 5675 | WorkerCommand::ReleaseRuntimeChatHost |
| 5676 | )); |
| 5677 | |
| 5678 | event_tx.send(RemoteEvent::RuntimeChatHostReleased).unwrap(); |
| 5679 | assert!(matches!( |
| 5680 | controller.try_next_event(), |
| 5681 | Some(RemoteEvent::RuntimeChatHostReleased) |
| 5682 | )); |
| 5683 | assert_eq!( |
| 5684 | controller |
| 5685 | .runtime_chat |
| 5686 | .as_ref() |
| 5687 | .unwrap() |
| 5688 | .configured_default_model_for_tests(), |
| 5689 | "new-safe-model" |
| 5690 | ); |
| 5691 | assert!(matches!( |
| 5692 | worker_rx.try_recv().unwrap(), |
| 5693 | WorkerCommand::InstallRuntimeChatHost(_) |
| 5694 | )); |
| 5695 | let WorkerCommand::Upload { envelopes, .. } = worker_rx.try_recv().unwrap() else { |
| 5696 | panic!("the refreshed host must upload a new challenge-bound catalog"); |
| 5697 | }; |
| 5698 | assert_eq!(envelopes.len(), 1); |
| 5699 | assert_eq!(envelopes[0]["event"], "runtime.catalog"); |
| 5700 | let serialized = envelopes[0].to_string(); |
| 5701 | assert!(serialized.contains("new-safe-model")); |
| 5702 | assert!(!serialized.contains("old-safe-model")); |
| 5703 | assert!(controller.pending_runtime_chat_configuration.is_none()); |
| 5704 | } |
| 5705 | |
| 5706 | #[tokio::test] |
| 5707 | async fn runtime_chat_provider_ownership_releases_only_after_terminal_server_cursor() { |
| 5708 | let root = tempfile::tempdir().unwrap(); |
| 5709 | let mut controller = RemoteControlController::default(); |
| 5710 | controller |
| 5711 | .configure_runtime_chat( |
| 5712 | codewhale_runtime::config::Config::default(), |
| 5713 | Arc::new(codewhale_plugins::PluginRegistry::empty(root.path())), |
| 5714 | root.path().join("runtime-chat"), |
| 5715 | "target_fixture".to_string(), |
| 5716 | "session_fixture".to_string(), |
| 5717 | ) |
| 5718 | .unwrap(); |
| 5719 | let host = controller.runtime_chat.as_ref().unwrap().clone(); |
| 5720 | controller.journal = Some( |
| 5721 | RuntimeEventJournal::open(root.path(), "target_fixture", "session_fixture") |
| 5722 | .expect("runtime chat delivery journal"), |
| 5723 | ); |
| 5724 | host.bind_account("account_fixture", "target_fixture") |
| 5725 | .unwrap(); |
| 5726 | let native_thread_id = "thr_terminal_gate_fixture"; |
| 5727 | let virtual_thread_id = format!("local_thread_{}", "a".repeat(24)); |
| 5728 | let virtual_turn_id = format!("local_turn_{}", "b".repeat(24)); |
| 5729 | host.install_unsettled_turn_for_tests( |
| 5730 | "run_fixture", |
| 5731 | native_thread_id, |
| 5732 | &virtual_thread_id, |
| 5733 | &virtual_turn_id, |
| 5734 | ) |
| 5735 | .await |
| 5736 | .unwrap(); |
| 5737 | host.acquire_inference_ownership_for_tests().await; |
| 5738 | assert!(host.inference_ownership_is_held_for_tests()); |
| 5739 | |
| 5740 | let seq = controller.next_runtime_seq("run_fixture"); |
| 5741 | assert!(controller.queue_runtime_chat_envelope( |
| 5742 | "run_fixture", |
| 5743 | runtime_chat_envelope( |
| 5744 | seq, |
| 5745 | "turn.completed", |
| 5746 | Some(&virtual_thread_id), |
| 5747 | Some(&virtual_turn_id), |
| 5748 | Some("native_event_terminal_gate_fixture"), |
| 5749 | "2026-08-23T00:00:00Z".to_string(), |
| 5750 | json!({ "status": "completed" }), |
| 5751 | ), |
| 5752 | )); |
| 5753 | host.mark_projected(native_thread_id, 1, &virtual_turn_id, "turn.completed") |
| 5754 | .unwrap(); |
| 5755 | assert!(!host.has_any_unsettled_turns()); |
| 5756 | controller.reconcile_runtime_cursor("run_fixture", seq.saturating_sub(1)); |
| 5757 | assert!( |
| 5758 | host.inference_ownership_is_held_for_tests(), |
| 5759 | "local terminal projection is not a server acknowledgement" |
| 5760 | ); |
| 5761 | controller.reconcile_runtime_cursor("run_fixture", seq); |
| 5762 | assert!( |
| 5763 | !host.inference_ownership_is_held_for_tests(), |
| 5764 | "the accepted server cursor releases attached-run provider ownership" |
| 5765 | ); |
| 5766 | } |
| 5767 | |
| 5768 | #[tokio::test] |
| 5769 | async fn restart_rehydrates_runtime_chat_ownership_until_terminal_cursor() { |
| 5770 | let root = tempfile::tempdir().unwrap(); |
| 5771 | let runtime_root = root.path().join("runtime-chat"); |
| 5772 | let journal_root = root.path().join("journal"); |
| 5773 | std::fs::create_dir_all(&journal_root).unwrap(); |
| 5774 | let terminal_seq; |
| 5775 | { |
| 5776 | let mut first = RemoteControlController::default(); |
| 5777 | first |
| 5778 | .configure_runtime_chat( |
| 5779 | codewhale_runtime::config::Config::default(), |
| 5780 | Arc::new(codewhale_plugins::PluginRegistry::empty(root.path())), |
| 5781 | runtime_root.clone(), |
| 5782 | "target_fixture".to_string(), |
| 5783 | "session_fixture".to_string(), |
| 5784 | ) |
| 5785 | .unwrap(); |
| 5786 | first.journal = Some( |
| 5787 | RuntimeEventJournal::open(&journal_root, "target_fixture", "session_fixture") |
| 5788 | .unwrap(), |
| 5789 | ); |
| 5790 | let host = first.runtime_chat.as_ref().unwrap().clone(); |
| 5791 | host.bind_account("account_fixture", "target_fixture") |
| 5792 | .unwrap(); |
| 5793 | let native_thread_id = "thr_restart_terminal_gate"; |
| 5794 | let virtual_thread_id = format!("local_thread_{}", "c".repeat(24)); |
| 5795 | let virtual_turn_id = format!("local_turn_{}", "d".repeat(24)); |
| 5796 | host.install_unsettled_turn_for_tests( |
| 5797 | "run_fixture", |
| 5798 | native_thread_id, |
| 5799 | &virtual_thread_id, |
| 5800 | &virtual_turn_id, |
| 5801 | ) |
| 5802 | .await |
| 5803 | .unwrap(); |
| 5804 | host.acquire_inference_ownership_for_tests().await; |
| 5805 | terminal_seq = first.next_runtime_seq("run_fixture"); |
| 5806 | assert!(first.queue_runtime_chat_envelope( |
| 5807 | "run_fixture", |
| 5808 | runtime_chat_envelope( |
| 5809 | terminal_seq, |
| 5810 | "turn.completed", |
| 5811 | Some(&virtual_thread_id), |
| 5812 | Some(&virtual_turn_id), |
| 5813 | Some("native_event_restart_terminal_gate"), |
| 5814 | "2026-08-23T00:00:00Z".to_string(), |
| 5815 | json!({ "turn": { "status": "completed" } }), |
| 5816 | ), |
| 5817 | )); |
| 5818 | host.mark_projected(native_thread_id, 1, &virtual_turn_id, "turn.completed") |
| 5819 | .unwrap(); |
| 5820 | assert!(!host.has_any_unsettled_turns()); |
| 5821 | } |
| 5822 | |
| 5823 | let mut reopened = RemoteControlController::default(); |
| 5824 | reopened |
| 5825 | .configure_runtime_chat( |
| 5826 | codewhale_runtime::config::Config::default(), |
| 5827 | Arc::new(codewhale_plugins::PluginRegistry::empty(root.path())), |
| 5828 | runtime_root, |
| 5829 | "target_fixture".to_string(), |
| 5830 | "session_fixture".to_string(), |
| 5831 | ) |
| 5832 | .unwrap(); |
| 5833 | let journal = |
| 5834 | RuntimeEventJournal::open(&journal_root, "target_fixture", "session_fixture").unwrap(); |
| 5835 | reopened.reset_pending_from(journal.load().unwrap()); |
| 5836 | reopened.journal = Some(journal); |
| 5837 | reopened |
| 5838 | .recover_runtime_chat_ownership_before_worker() |
| 5839 | .unwrap(); |
| 5840 | |
| 5841 | let mut participant = tokio::spawn(async { |
| 5842 | codewhale_engine::client::acquire_remote_control_inference_participant().await |
| 5843 | }); |
| 5844 | assert!( |
| 5845 | tokio::time::timeout(Duration::from_millis(40), &mut participant) |
| 5846 | .await |
| 5847 | .is_err(), |
| 5848 | "restart recovery must retain the provider writer before CWC cursor ack" |
| 5849 | ); |
| 5850 | reopened.reconcile_runtime_cursor("run_fixture", terminal_seq); |
| 5851 | let permit = tokio::time::timeout(Duration::from_secs(1), participant) |
| 5852 | .await |
| 5853 | .expect("participant resumes after cursor") |
| 5854 | .expect("participant task"); |
| 5855 | drop(permit); |
| 5856 | } |
| 5857 | |
| 5858 | #[tokio::test] |
| 5859 | async fn restart_reclaims_unsettled_runtime_chat_before_worker_or_fails_closed() { |
| 5860 | let root = tempfile::tempdir().unwrap(); |
| 5861 | let runtime_root = root.path().join("runtime-chat"); |
| 5862 | let native_thread_id = "thr_restart_unsettled_gate"; |
| 5863 | let virtual_thread_id = format!("local_thread_{}", "e".repeat(24)); |
| 5864 | let virtual_turn_id = format!("local_turn_{}", "f".repeat(24)); |
| 5865 | { |
| 5866 | let mut first = RemoteControlController::default(); |
| 5867 | first |
| 5868 | .configure_runtime_chat( |
| 5869 | codewhale_runtime::config::Config::default(), |
| 5870 | Arc::new(codewhale_plugins::PluginRegistry::empty(root.path())), |
| 5871 | runtime_root.clone(), |
| 5872 | "target_fixture".to_string(), |
| 5873 | "session_fixture".to_string(), |
| 5874 | ) |
| 5875 | .unwrap(); |
| 5876 | let host = first.runtime_chat.as_ref().unwrap(); |
| 5877 | host.bind_account("account_fixture", "target_fixture") |
| 5878 | .unwrap(); |
| 5879 | host.install_unsettled_turn_for_tests( |
| 5880 | "run_fixture", |
| 5881 | native_thread_id, |
| 5882 | &virtual_thread_id, |
| 5883 | &virtual_turn_id, |
| 5884 | ) |
| 5885 | .await |
| 5886 | .unwrap(); |
| 5887 | } |
| 5888 | |
| 5889 | let mut reopened = RemoteControlController::default(); |
| 5890 | reopened |
| 5891 | .configure_runtime_chat( |
| 5892 | codewhale_runtime::config::Config::default(), |
| 5893 | Arc::new(codewhale_plugins::PluginRegistry::empty(root.path())), |
| 5894 | runtime_root, |
| 5895 | "target_fixture".to_string(), |
| 5896 | "session_fixture".to_string(), |
| 5897 | ) |
| 5898 | .unwrap(); |
| 5899 | let host = reopened.runtime_chat.as_ref().unwrap().clone(); |
| 5900 | assert!(host.has_any_unsettled_turns()); |
| 5901 | |
| 5902 | let participant = |
| 5903 | codewhale_engine::client::acquire_remote_control_inference_participant().await; |
| 5904 | let error = reopened |
| 5905 | .recover_runtime_chat_ownership_before_worker() |
| 5906 | .unwrap_err(); |
| 5907 | assert!(error.contains("active local turn"), "{error}"); |
| 5908 | assert!(!host.inference_ownership_is_held_for_tests()); |
| 5909 | drop(participant); |
| 5910 | |
| 5911 | reopened |
| 5912 | .recover_runtime_chat_ownership_before_worker() |
| 5913 | .unwrap(); |
| 5914 | let mut blocked = tokio::spawn(async { |
| 5915 | codewhale_engine::client::acquire_remote_control_inference_participant().await |
| 5916 | }); |
| 5917 | assert!( |
| 5918 | tokio::time::timeout(Duration::from_millis(40), &mut blocked) |
| 5919 | .await |
| 5920 | .is_err(), |
| 5921 | "an unsettled recovered turn must own the gate before Connected" |
| 5922 | ); |
| 5923 | host.mark_projected(native_thread_id, 1, &virtual_turn_id, "turn.completed") |
| 5924 | .unwrap(); |
| 5925 | host.release_inference_ownership_if_settled(); |
| 5926 | let permit = tokio::time::timeout(Duration::from_secs(1), blocked) |
| 5927 | .await |
| 5928 | .expect("participant resumes after durable terminal settlement") |
| 5929 | .expect("participant task"); |
| 5930 | drop(permit); |
| 5931 | } |
| 5932 | |
| 5933 | #[tokio::test(flavor = "current_thread")] |
| 5934 | async fn actual_start_reclaims_runtime_chat_writer_before_worker_spawn() { |
| 5935 | let root = tempfile::tempdir().unwrap(); |
| 5936 | let runtime_root = root.path().join("runtime-chat"); |
| 5937 | let journal_root = root.path().join("journal"); |
| 5938 | let native_thread_id = "thr_actual_start_unsettled"; |
| 5939 | let virtual_thread_id = format!("local_thread_{}", "c".repeat(24)); |
| 5940 | let virtual_turn_id = format!("local_turn_{}", "d".repeat(24)); |
| 5941 | { |
| 5942 | let mut first = RemoteControlController::default(); |
| 5943 | first |
| 5944 | .prepare_remote_control_session_journal( |
| 5945 | &journal_root, |
| 5946 | "target_fixture", |
| 5947 | "session_fixture", |
| 5948 | ) |
| 5949 | .unwrap(); |
| 5950 | first |
| 5951 | .configure_runtime_chat( |
| 5952 | codewhale_runtime::config::Config::default(), |
| 5953 | Arc::new(codewhale_plugins::PluginRegistry::empty(root.path())), |
| 5954 | runtime_root.clone(), |
| 5955 | "target_fixture".to_string(), |
| 5956 | "session_fixture".to_string(), |
| 5957 | ) |
| 5958 | .unwrap(); |
| 5959 | first |
| 5960 | .runtime_chat |
| 5961 | .as_ref() |
| 5962 | .unwrap() |
| 5963 | .bind_account("account_fixture", "target_fixture") |
| 5964 | .unwrap(); |
| 5965 | first |
| 5966 | .runtime_chat |
| 5967 | .as_ref() |
| 5968 | .unwrap() |
| 5969 | .install_unsettled_turn_for_tests( |
| 5970 | "run_fixture", |
| 5971 | native_thread_id, |
| 5972 | &virtual_thread_id, |
| 5973 | &virtual_turn_id, |
| 5974 | ) |
| 5975 | .await |
| 5976 | .unwrap(); |
| 5977 | } |
| 5978 | |
| 5979 | let mut reopened = RemoteControlController::default(); |
| 5980 | reopened |
| 5981 | .prepare_remote_control_session_journal( |
| 5982 | &journal_root, |
| 5983 | "target_fixture", |
| 5984 | "session_fixture", |
| 5985 | ) |
| 5986 | .unwrap(); |
| 5987 | reopened |
| 5988 | .configure_runtime_chat( |
| 5989 | codewhale_runtime::config::Config::default(), |
| 5990 | Arc::new(codewhale_plugins::PluginRegistry::empty(root.path())), |
| 5991 | runtime_root, |
| 5992 | "target_fixture".to_string(), |
| 5993 | "session_fixture".to_string(), |
| 5994 | ) |
| 5995 | .unwrap(); |
| 5996 | let host = reopened.runtime_chat.as_ref().unwrap().clone(); |
| 5997 | let start = RemoteStart { |
| 5998 | session_id: "session_fixture".to_string(), |
| 5999 | journal_dir: Some(journal_root), |
| 6000 | ..fixture_start() |
| 6001 | }; |
| 6002 | |
| 6003 | let participant = |
| 6004 | codewhale_engine::client::acquire_remote_control_inference_participant().await; |
| 6005 | let error = reopened.start(start.clone()).unwrap_err(); |
| 6006 | assert!(error.contains("active local turn"), "{error}"); |
| 6007 | assert!(reopened.worker.is_none()); |
| 6008 | assert_eq!(reopened.status, Status::Failed); |
| 6009 | assert!(reopened.status_line().contains(&error)); |
| 6010 | drop(participant); |
| 6011 | |
| 6012 | reopened.start(start).unwrap(); |
| 6013 | assert!(host.inference_ownership_is_held_for_tests()); |
| 6014 | assert_eq!(reopened.status, Status::Connecting); |
| 6015 | assert!(reopened.worker.is_some()); |
| 6016 | // This current-thread test has not yielded since spawning the worker, |
| 6017 | // so abort it before enrollment can perform any network I/O. |
| 6018 | reopened.stop_worker(); |
| 6019 | host.mark_projected(native_thread_id, 1, &virtual_turn_id, "turn.completed") |
| 6020 | .unwrap(); |
| 6021 | host.release_inference_ownership_if_settled(); |
| 6022 | assert!(!host.inference_ownership_is_held_for_tests()); |
| 6023 | } |
| 6024 | |
| 6025 | #[test] |
| 6026 | fn aborting_a_relay_worker_releases_unjournaled_projection_claims() { |
| 6027 | let root = tempfile::tempdir().unwrap(); |
| 6028 | let mut controller = RemoteControlController::default(); |
| 6029 | controller |
| 6030 | .configure_runtime_chat( |
| 6031 | codewhale_runtime::config::Config::default(), |
| 6032 | Arc::new(codewhale_plugins::PluginRegistry::empty(root.path())), |
| 6033 | root.path().join("runtime-chat"), |
| 6034 | "target_fixture".to_string(), |
| 6035 | "session_fixture".to_string(), |
| 6036 | ) |
| 6037 | .unwrap(); |
| 6038 | let host = controller.runtime_chat.as_ref().unwrap().clone(); |
| 6039 | host.install_projection_claim_for_tests("thr_claimed", 7); |
| 6040 | assert!(host.projection_is_claimed_for_tests("thr_claimed", 7)); |
| 6041 | |
| 6042 | controller.stop_worker(); |
| 6043 | |
| 6044 | assert!(!host.projection_is_claimed_for_tests("thr_claimed", 7)); |
| 6045 | } |
| 6046 | |
| 6047 | #[tokio::test] |
| 6048 | async fn idle_runtime_chat_ticks_cannot_starve_the_control_poll() { |
| 6049 | if !cfg!(debug_assertions) { |
| 6050 | return; |
| 6051 | } |
| 6052 | let _env = codewhale_engine::test_support::lock_test_env(); |
| 6053 | let secrets_root = tempfile::tempdir().expect("isolated remote-control secrets"); |
| 6054 | let _codewhale_home = |
| 6055 | codewhale_engine::test_support::EnvVarGuard::set("CODEWHALE_HOME", secrets_root.path()); |
| 6056 | let server = MockServer::start().await; |
| 6057 | let plane = format!("{}/", server.uri().trim_end_matches('/')); |
| 6058 | let _control_plane = codewhale_engine::test_support::EnvVarGuard::set( |
| 6059 | "CWC_RUNNER_CONTROL_PLANE_BASE", |
| 6060 | &plane, |
| 6061 | ); |
| 6062 | let base = runner_control_plane_base().expect("loopback control plane"); |
| 6063 | save_persisted_enrollment(&fixture_enrollment(&base).persisted) |
| 6064 | .expect("persist matching enrollment"); |
| 6065 | |
| 6066 | let access_token = codewhale_engine::test_support::future_test_jwt(&"a".repeat(40)); |
| 6067 | Mock::given(method("POST")) |
| 6068 | .and(path("/api/runner/enrollments/token")) |
| 6069 | .respond_with(ResponseTemplate::new(200).set_body_json(json!({ |
| 6070 | "enrollment": { |
| 6071 | "id": "enrollment_fixture", |
| 6072 | "userId": "account_fixture", |
| 6073 | "deviceId": "device_fixture", |
| 6074 | "runtimeVersion": "0.9.6", |
| 6075 | "runtimeCommit": "a".repeat(40), |
| 6076 | "capabilities": CAPABILITIES, |
| 6077 | }, |
| 6078 | "credential": { "accessToken": access_token }, |
| 6079 | }))) |
| 6080 | .mount(&server) |
| 6081 | .await; |
| 6082 | Mock::given(method("POST")) |
| 6083 | .and(path("/api/local-runners/connect")) |
| 6084 | .respond_with(ResponseTemplate::new(200).set_body_json(fixture_connection_response())) |
| 6085 | .mount(&server) |
| 6086 | .await; |
| 6087 | Mock::given(method("POST")) |
| 6088 | .and(path("/api/local-runners/runner_fixture/heartbeat")) |
| 6089 | .respond_with(ResponseTemplate::new(200).set_body_json(json!({}))) |
| 6090 | .mount(&server) |
| 6091 | .await; |
| 6092 | let polls = ControlPollCounter::default(); |
| 6093 | Mock::given(method("GET")) |
| 6094 | .and(path("/api/local-runners/runner_fixture/runs")) |
| 6095 | .respond_with(polls.clone()) |
| 6096 | .mount(&server) |
| 6097 | .await; |
| 6098 | |
| 6099 | let runtime_root = tempfile::tempdir().expect("idle Runtime Chat host"); |
| 6100 | let host = RuntimeChatRelayHost::open( |
| 6101 | codewhale_runtime::config::Config::default(), |
| 6102 | Arc::new(codewhale_plugins::PluginRegistry::empty( |
| 6103 | runtime_root.path(), |
| 6104 | )), |
| 6105 | runtime_root.path().to_path_buf(), |
| 6106 | "target_fixture".to_string(), |
| 6107 | "session_fixture".to_string(), |
| 6108 | ) |
| 6109 | .expect("open idle Runtime Chat host"); |
| 6110 | let start = fixture_start(); |
| 6111 | let (_worker_tx, worker_rx) = mpsc::unbounded_channel(); |
| 6112 | let (event_tx, mut event_rx) = mpsc::unbounded_channel(); |
| 6113 | let worker = tokio::spawn(async move { |
| 6114 | let mut phase = RelayPhase::Enrolling; |
| 6115 | relay_worker(start, Some(host), worker_rx, event_tx, &mut phase).await |
| 6116 | }); |
| 6117 | |
| 6118 | tokio::time::timeout(Duration::from_secs(5), async { |
| 6119 | loop { |
| 6120 | match event_rx.recv().await { |
| 6121 | Some(RemoteEvent::Connected { .. }) => break, |
| 6122 | Some(RemoteEvent::Notice(_)) => {} |
| 6123 | Some(RemoteEvent::Failed(error)) => { |
| 6124 | panic!("relay worker failed before attach: {error}"); |
| 6125 | } |
| 6126 | Some(RemoteEvent::FailedPreLease(error)) => { |
| 6127 | panic!("relay worker failed before attach: {error}"); |
| 6128 | } |
| 6129 | Some(_) => panic!("relay worker emitted an unexpected event before attach"), |
| 6130 | None => panic!("relay worker stopped before attach"), |
| 6131 | } |
| 6132 | } |
| 6133 | }) |
| 6134 | .await |
| 6135 | .expect("relay worker should attach"); |
| 6136 | |
| 6137 | tokio::time::sleep(RUNTIME_UPLOAD_RETRY_INTERVAL.saturating_mul(2)).await; |
| 6138 | assert_eq!( |
| 6139 | polls.hits.load(Ordering::SeqCst), |
| 6140 | 0, |
| 6141 | "the first control poll must still wait SYNC_INTERVAL while idle chat ticks fire" |
| 6142 | ); |
| 6143 | tokio::time::sleep(SYNC_INTERVAL).await; |
| 6144 | assert!( |
| 6145 | polls.hits.load(Ordering::SeqCst) >= 1, |
| 6146 | "idle Runtime Chat ticks must not reset the control poll" |
| 6147 | ); |
| 6148 | worker.abort(); |
| 6149 | let _ = worker.await; |
| 6150 | } |
| 6151 | |
| 6152 | #[tokio::test] |
| 6153 | async fn preattachment_failure_cannot_release_a_recovered_unsettled_turn() { |
| 6154 | let root = tempfile::tempdir().unwrap(); |
| 6155 | let registry = Arc::new(codewhale_plugins::PluginRegistry::empty(root.path())); |
| 6156 | let mut controller = RemoteControlController::default(); |
| 6157 | controller |
| 6158 | .configure_runtime_chat( |
| 6159 | codewhale_runtime::config::Config::default(), |
| 6160 | Arc::clone(®istry), |
| 6161 | root.path().join("runtime-chat"), |
| 6162 | "target_fixture".to_string(), |
| 6163 | "session_fixture".to_string(), |
| 6164 | ) |
| 6165 | .unwrap(); |
| 6166 | let host = controller.runtime_chat.as_ref().unwrap(); |
| 6167 | host.bind_account("account_fixture", "target_fixture") |
| 6168 | .unwrap(); |
| 6169 | host.install_unsettled_turn_for_tests( |
| 6170 | "run_old", |
| 6171 | "thr_recovered", |
| 6172 | &format!("local_thread_{}", "a".repeat(24)), |
| 6173 | &format!("local_turn_{}", "b".repeat(24)), |
| 6174 | ) |
| 6175 | .await |
| 6176 | .unwrap(); |
| 6177 | let retained_model = host.configured_default_model_for_tests(); |
| 6178 | controller |
| 6179 | .configure_runtime_chat( |
| 6180 | { |
| 6181 | let __cw_config_init_4_0 = Some("ollama".to_string()); |
| 6182 | let __cw_config_init_4_1 = Some("must-not-replace-live-host".to_string()); |
| 6183 | let mut __cw_config_init_4_value: codewhale_runtime::config::Config = |
| 6184 | codewhale_runtime::config::Config::default(); |
| 6185 | __cw_config_init_4_value.provider = __cw_config_init_4_0; |
| 6186 | __cw_config_init_4_value.default_text_model = __cw_config_init_4_1; |
| 6187 | __cw_config_init_4_value |
| 6188 | }, |
| 6189 | Arc::clone(®istry), |
| 6190 | root.path().join("runtime-chat"), |
| 6191 | "target_fixture".to_string(), |
| 6192 | "session_fixture".to_string(), |
| 6193 | ) |
| 6194 | .unwrap(); |
| 6195 | assert_eq!( |
| 6196 | controller |
| 6197 | .runtime_chat |
| 6198 | .as_ref() |
| 6199 | .unwrap() |
| 6200 | .configured_default_model_for_tests(), |
| 6201 | retained_model, |
| 6202 | "an unsettled same-scope turn must retain its lifetime manager" |
| 6203 | ); |
| 6204 | controller.status = Status::Failed; |
| 6205 | controller.ownership_blocked_until = Some(Instant::now() - Duration::from_millis(1)); |
| 6206 | |
| 6207 | assert!(controller.try_next_event().is_none()); |
| 6208 | assert_eq!(controller.status, Status::Failed); |
| 6209 | assert!(controller.runtime_chat.is_some()); |
| 6210 | assert!( |
| 6211 | controller |
| 6212 | .configure_runtime_chat( |
| 6213 | codewhale_runtime::config::Config::default(), |
| 6214 | registry, |
| 6215 | root.path().join("runtime-chat"), |
| 6216 | "target_other".to_string(), |
| 6217 | "session_other".to_string(), |
| 6218 | ) |
| 6219 | .is_err() |
| 6220 | ); |
| 6221 | } |
| 6222 | |
| 6223 | #[test] |
| 6224 | fn runtime_chat_reenrollment_rejects_attachment_from_a_different_account() { |
| 6225 | let root = tempfile::tempdir().unwrap(); |
| 6226 | let registry = Arc::new(codewhale_plugins::PluginRegistry::empty(root.path())); |
| 6227 | let (mut controller, _worker_rx, event_tx, _journal_root) = wired_controller(); |
| 6228 | controller |
| 6229 | .configure_runtime_chat( |
| 6230 | codewhale_runtime::config::Config::default(), |
| 6231 | registry, |
| 6232 | root.path().join("runtime-chat"), |
| 6233 | "target_fixture".to_string(), |
| 6234 | "session_fixture".to_string(), |
| 6235 | ) |
| 6236 | .unwrap(); |
| 6237 | controller |
| 6238 | .runtime_chat |
| 6239 | .as_ref() |
| 6240 | .unwrap() |
| 6241 | .bind_account("account_a", "target_fixture") |
| 6242 | .unwrap(); |
| 6243 | controller.account_ref = Some("account_a".to_string()); |
| 6244 | controller.target_ref = Some("target_fixture".to_string()); |
| 6245 | controller.attached_run_id = Some("run_account_a".to_string()); |
| 6246 | |
| 6247 | event_tx |
| 6248 | .send(RemoteEvent::Attachment { |
| 6249 | account_ref: "account_b".to_string(), |
| 6250 | target_ref: "target_fixture".to_string(), |
| 6251 | attachment: RemoteAttachment { |
| 6252 | run_id: "run_account_b".to_string(), |
| 6253 | workspace_id: "workspace_account_b".to_string(), |
| 6254 | runtime_cursor: 0, |
| 6255 | snapshot_present: false, |
| 6256 | runtime_chat_relay_protocol: RUNTIME_CHAT_RELAY_PROTOCOL.to_string(), |
| 6257 | runtime_chat_relay_challenge: "b".repeat(32), |
| 6258 | }, |
| 6259 | links: RemoteLinks::default(), |
| 6260 | }) |
| 6261 | .unwrap(); |
| 6262 | |
| 6263 | let event = controller.try_next_event().unwrap(); |
| 6264 | let RemoteEvent::Failed(error) = event else { |
| 6265 | panic!("an account-switch attachment must fail closed"); |
| 6266 | }; |
| 6267 | assert!(error.contains("belongs to another account"), "{error}"); |
| 6268 | assert_eq!(controller.account_ref.as_deref(), Some("account_a")); |
| 6269 | assert_eq!(controller.attached_run_id.as_deref(), Some("run_account_a")); |
| 6270 | assert_eq!(controller.status, Status::Failed); |
| 6271 | assert!(controller.worker_tx.is_none()); |
| 6272 | assert!(controller.event_rx.is_none()); |
| 6273 | for command in [ |
| 6274 | RemoteCommand::Prompt { |
| 6275 | turn_id: "turn_rejected".to_string(), |
| 6276 | prompt: "must not execute".to_string(), |
| 6277 | }, |
| 6278 | RemoteCommand::Approval { |
| 6279 | gate: "local_approval_rejected".to_string(), |
| 6280 | approved: true, |
| 6281 | }, |
| 6282 | ] { |
| 6283 | assert!( |
| 6284 | controller |
| 6285 | .claim_command("run_account_b", 1, &command) |
| 6286 | .is_err(), |
| 6287 | "rejected account command must not be claimable: {command:?}" |
| 6288 | ); |
| 6289 | } |
| 6290 | } |
| 6291 | |
| 6292 | #[tokio::test] |
| 6293 | async fn connect_request_opts_into_runtime_chat_without_exposing_local_state() { |
| 6294 | let server = MockServer::start().await; |
| 6295 | let enrollment = fixture_enrollment(&format!("{}/", server.uri())); |
| 6296 | let start = fixture_start(); |
| 6297 | let expected = json!({ |
| 6298 | "deviceId": "device_fixture", |
| 6299 | "targetRef": "target_fixture", |
| 6300 | "displayLabel": "private-project", |
| 6301 | "runtimeVersion": "0.9.6", |
| 6302 | "runtimeCommit": "a".repeat(40), |
| 6303 | "capabilities": CAPABILITIES, |
| 6304 | "status": "active", |
| 6305 | "sessionRef": "session:fixture@01", |
| 6306 | "runtimeChatRelayProtocol": RUNTIME_CHAT_RELAY_PROTOCOL |
| 6307 | }); |
| 6308 | assert_eq!(connect_runner_body(&enrollment, &start), expected); |
| 6309 | for forbidden in [ |
| 6310 | "sessionId", |
| 6311 | "workspacePath", |
| 6312 | "path", |
| 6313 | "prompt", |
| 6314 | "environment", |
| 6315 | "env", |
| 6316 | "token", |
| 6317 | "credential", |
| 6318 | ] { |
| 6319 | assert!(expected.get(forbidden).is_none(), "leaked {forbidden}"); |
| 6320 | } |
| 6321 | Mock::given(method("POST")) |
| 6322 | .and(path("/api/local-runners/connect")) |
| 6323 | .and(body_json(expected)) |
| 6324 | .respond_with(ResponseTemplate::new(200).set_body_json(fixture_connection_response())) |
| 6325 | .expect(1) |
| 6326 | .mount(&server) |
| 6327 | .await; |
| 6328 | let client = codewhale_release::tls::reqwest_client_builder() |
| 6329 | .redirect(reqwest::redirect::Policy::none()) |
| 6330 | .build() |
| 6331 | .expect("fixture client"); |
| 6332 | |
| 6333 | let connection = connect_runner(&client, &enrollment, &start) |
| 6334 | .await |
| 6335 | .expect("strict runner attachment"); |
| 6336 | |
| 6337 | assert_eq!(connection.runner_id, "runner_fixture"); |
| 6338 | assert_eq!(connection.attachment.run_id, "run_fixture"); |
| 6339 | assert_eq!(connection.attachment.runtime_cursor, 41); |
| 6340 | assert!(!connection.attachment.snapshot_present); |
| 6341 | assert_eq!( |
| 6342 | connection.attachment.runtime_chat_relay_protocol, |
| 6343 | RUNTIME_CHAT_RELAY_PROTOCOL |
| 6344 | ); |
| 6345 | assert_eq!( |
| 6346 | connection.attachment.runtime_chat_relay_challenge, |
| 6347 | "a".repeat(32) |
| 6348 | ); |
| 6349 | } |
| 6350 | |
| 6351 | #[test] |
| 6352 | fn connection_without_links_yields_no_urls() { |
| 6353 | let enrollment = fixture_enrollment("https://api.codewhale.net/"); |
| 6354 | let start = fixture_start(); |
| 6355 | let connection = |
| 6356 | parse_runner_connection(&fixture_connection_response(), &enrollment, &start) |
| 6357 | .expect("legacy lease without links still attaches"); |
| 6358 | assert_eq!(connection.links, RemoteLinks::default()); |
| 6359 | assert!(connection.links.run_url.is_none()); |
| 6360 | assert!(connection.links.computer_url.is_none()); |
| 6361 | } |
| 6362 | |
| 6363 | #[test] |
| 6364 | fn connection_links_are_parsed_from_the_runner_lease() { |
| 6365 | let enrollment = fixture_enrollment("https://api.codewhale.net/"); |
| 6366 | let start = fixture_start(); |
| 6367 | let mut value = fixture_connection_response(); |
| 6368 | value["runner"]["runUrl"] = json!("https://app.codewhale.net/session?run=run_fixture"); |
| 6369 | value["runner"]["computerUrl"] = |
| 6370 | json!("https://app.codewhale.net/settings?section=workspaces"); |
| 6371 | let connection = parse_runner_connection(&value, &enrollment, &start) |
| 6372 | .expect("lease with links attaches"); |
| 6373 | assert_eq!( |
| 6374 | connection.links.run_url.as_deref(), |
| 6375 | Some("https://app.codewhale.net/session?run=run_fixture") |
| 6376 | ); |
| 6377 | assert_eq!( |
| 6378 | connection.links.computer_url.as_deref(), |
| 6379 | Some("https://app.codewhale.net/settings?section=workspaces") |
| 6380 | ); |
| 6381 | } |
| 6382 | |
| 6383 | #[test] |
| 6384 | fn connection_links_off_origin_or_for_another_run_are_dropped_not_fatal() { |
| 6385 | let enrollment = fixture_enrollment("https://api.codewhale.net/"); |
| 6386 | let start = fixture_start(); |
| 6387 | for spoofed in [ |
| 6388 | "http://app.codewhale.net/session?run=run_fixture", |
| 6389 | "https://app.codewhale.net.evil.example/session?run=run_fixture", |
| 6390 | "https://evil.example/session?run=run_fixture", |
| 6391 | "https://user:pw@app.codewhale.net/session?run=run_fixture", |
| 6392 | "https://app.codewhale.net:8443/session?run=run_fixture", |
| 6393 | "https://app.codewhale.net/session?run=run_fixture#token=abc", |
| 6394 | "https://app.codewhale.net/session?run=run_other", |
| 6395 | "https://app.codewhale.net/session?run=run_fixture&next=https://evil.example", |
| 6396 | "https://app.codewhale.net/logout?run=run_fixture", |
| 6397 | "", |
| 6398 | "not a url", |
| 6399 | ] { |
| 6400 | let mut value = fixture_connection_response(); |
| 6401 | value["runner"]["runUrl"] = json!(spoofed); |
| 6402 | value["runner"]["computerUrl"] = json!(spoofed); |
| 6403 | let connection = parse_runner_connection(&value, &enrollment, &start) |
| 6404 | .expect("a bad link must not break the attachment"); |
| 6405 | assert!( |
| 6406 | connection.links.run_url.is_none(), |
| 6407 | "run link accepted: {spoofed}" |
| 6408 | ); |
| 6409 | assert!( |
| 6410 | connection.links.computer_url.is_none(), |
| 6411 | "computer link accepted: {spoofed}" |
| 6412 | ); |
| 6413 | } |
| 6414 | // A non-string value is treated as absent. |
| 6415 | let mut value = fixture_connection_response(); |
| 6416 | value["runner"]["runUrl"] = json!(42); |
| 6417 | let connection = parse_runner_connection(&value, &enrollment, &start).unwrap(); |
| 6418 | assert!(connection.links.run_url.is_none()); |
| 6419 | } |
| 6420 | |
| 6421 | #[test] |
| 6422 | fn banner_leads_with_the_session_link_when_present() { |
| 6423 | let with_link = remote_control_banner( |
| 6424 | "account_fixture", |
| 6425 | "runner_fixture", |
| 6426 | Some("https://app.codewhale.net/session?run=run_fixture"), |
| 6427 | ); |
| 6428 | assert_eq!( |
| 6429 | with_link, |
| 6430 | "WEB MIRROR · https://app.codewhale.net/session?run=run_fixture · /rc stop" |
| 6431 | ); |
| 6432 | let without_link = remote_control_banner("account_fixture", "runner_fixture", None); |
| 6433 | assert_eq!( |
| 6434 | without_link, |
| 6435 | "WEB MIRROR · account account_fixture · runner runner_fixture · /rc stop" |
| 6436 | ); |
| 6437 | let notice = |
| 6438 | remote_control_link_notice("https://app.codewhale.net/session?run=run_fixture"); |
| 6439 | assert!(notice.starts_with( |
| 6440 | "Remote control is live at https://app.codewhale.net/session?run=run_fixture" |
| 6441 | )); |
| 6442 | assert!(notice.contains("/rc open")); |
| 6443 | assert!(notice.contains("/rc link")); |
| 6444 | } |
| 6445 | |
| 6446 | #[test] |
| 6447 | fn controller_exposes_links_only_while_connected() { |
| 6448 | let mut controller = RemoteControlController::default(); |
| 6449 | assert!(controller.run_url().is_none()); |
| 6450 | let (worker_tx, _worker_rx) = mpsc::unbounded_channel(); |
| 6451 | let (event_tx, event_rx) = mpsc::unbounded_channel(); |
| 6452 | controller.worker_tx = Some(worker_tx); |
| 6453 | controller.event_rx = Some(event_rx); |
| 6454 | event_tx |
| 6455 | .send(RemoteEvent::Connected { |
| 6456 | account_ref: "account_fixture".to_string(), |
| 6457 | runner_id: "runner_fixture".to_string(), |
| 6458 | target_ref: "target_fixture".to_string(), |
| 6459 | attachment: RemoteAttachment { |
| 6460 | run_id: "run_fixture".to_string(), |
| 6461 | workspace_id: "workspace_fixture".to_string(), |
| 6462 | runtime_cursor: 0, |
| 6463 | snapshot_present: false, |
| 6464 | runtime_chat_relay_protocol: RUNTIME_CHAT_RELAY_PROTOCOL.to_string(), |
| 6465 | runtime_chat_relay_challenge: "a".repeat(32), |
| 6466 | }, |
| 6467 | links: RemoteLinks { |
| 6468 | run_url: Some("https://app.codewhale.net/session?run=run_fixture".to_string()), |
| 6469 | computer_url: Some( |
| 6470 | "https://app.codewhale.net/settings?section=workspaces".to_string(), |
| 6471 | ), |
| 6472 | }, |
| 6473 | }) |
| 6474 | .unwrap(); |
| 6475 | controller.try_next_event().unwrap(); |
| 6476 | assert_eq!( |
| 6477 | controller.run_url(), |
| 6478 | Some("https://app.codewhale.net/session?run=run_fixture") |
| 6479 | ); |
| 6480 | assert_eq!( |
| 6481 | controller.computer_url(), |
| 6482 | Some("https://app.codewhale.net/settings?section=workspaces") |
| 6483 | ); |
| 6484 | assert!( |
| 6485 | controller |
| 6486 | .status_line() |
| 6487 | .contains("open https://app.codewhale.net/session?run=run_fixture") |
| 6488 | ); |
| 6489 | |
| 6490 | event_tx.send(RemoteEvent::Stopped).unwrap(); |
| 6491 | controller.try_next_event().unwrap(); |
| 6492 | assert!(controller.run_url().is_none()); |
| 6493 | assert!(controller.computer_url().is_none()); |
| 6494 | } |
| 6495 | |
| 6496 | #[test] |
| 6497 | fn connecting_never_blocks_local_prompts_and_shares_approvals_only_once_attached() { |
| 6498 | let mut controller = RemoteControlController::default(); |
| 6499 | controller.status = Status::Connecting; |
| 6500 | controller.status_detail = "waiting for account authorization".to_string(); |
| 6501 | // Mirror semantics: there is no local-input gate at all. The only |
| 6502 | // shared-decision surface is the approval card, and only once a |
| 6503 | // typed turn is bound. |
| 6504 | assert!( |
| 6505 | !controller.can_share_approval_with_web(), |
| 6506 | "without a confirmed run cursor the web cannot receive an approval" |
| 6507 | ); |
| 6508 | |
| 6509 | controller.status = Status::Connected; |
| 6510 | controller.attached_run_id = Some("run_fixture".to_string()); |
| 6511 | assert!( |
| 6512 | !controller.can_share_approval_with_web(), |
| 6513 | "a connected idle session has no typed turn to receive approvals" |
| 6514 | ); |
| 6515 | assert!(controller.attach_current_local_turn(Some("turn_fixture"))); |
| 6516 | assert!(controller.can_share_approval_with_web()); |
| 6517 | } |
| 6518 | |
| 6519 | #[test] |
| 6520 | fn persisted_device_identity_survives_a_reload_and_outlives_enrollments() { |
| 6521 | let (minted, needs_save) = resolve_device_identity(None, None); |
| 6522 | assert!(needs_save); |
| 6523 | assert!(minted.starts_with("device_")); |
| 6524 | assert!(valid_opaque_ref(&minted)); |
| 6525 | |
| 6526 | let identity = PersistedDeviceIdentity { |
| 6527 | schema_version: 1, |
| 6528 | device_id: minted.clone(), |
| 6529 | }; |
| 6530 | let raw = serde_json::to_string(&identity).expect("encode device identity"); |
| 6531 | let reloaded: PersistedDeviceIdentity = |
| 6532 | serde_json::from_str(&raw).expect("decode device identity"); |
| 6533 | assert_eq!(reloaded, identity); |
| 6534 | |
| 6535 | // A saved identity wins over any enrollment's id and needs no re-save. |
| 6536 | let (resolved, needs_save) = |
| 6537 | resolve_device_identity(Some(reloaded.clone()), Some("device_enrolled")); |
| 6538 | assert_eq!(resolved, minted); |
| 6539 | assert!(!needs_save); |
| 6540 | |
| 6541 | // Without a saved identity, an existing enrollment's device id is |
| 6542 | // adopted (upgrading terminals keep their computer row) and persisted. |
| 6543 | let (adopted, needs_save) = resolve_device_identity(None, Some("device_enrolled")); |
| 6544 | assert_eq!(adopted, "device_enrolled"); |
| 6545 | assert!(needs_save); |
| 6546 | |
| 6547 | // An unreadable identity is replaced, never fatal. |
| 6548 | let broken = PersistedDeviceIdentity { |
| 6549 | schema_version: 2, |
| 6550 | device_id: "x".to_string(), |
| 6551 | }; |
| 6552 | let (replaced, needs_save) = resolve_device_identity(Some(broken), None); |
| 6553 | assert_ne!(replaced, "x"); |
| 6554 | assert!(needs_save); |
| 6555 | assert!(serde_json::from_str::<PersistedDeviceIdentity>("{\"deviceId\":\"a\"}").is_err()); |
| 6556 | } |
| 6557 | |
| 6558 | #[test] |
| 6559 | fn remote_control_receipts_never_select_the_system_keychain() { |
| 6560 | assert!( |
| 6561 | remote_control_secrets() |
| 6562 | .backend_name() |
| 6563 | .starts_with("file-based"), |
| 6564 | "/rc enrollment must not trigger an OS keychain prompt" |
| 6565 | ); |
| 6566 | } |
| 6567 | |
| 6568 | #[test] |
| 6569 | fn attachment_response_validation_fails_closed() { |
| 6570 | let enrollment = fixture_enrollment("https://api.codewhale.net/"); |
| 6571 | let start = fixture_start(); |
| 6572 | let valid = fixture_connection_response(); |
| 6573 | assert!(parse_runner_connection(&valid, &enrollment, &start).is_ok()); |
| 6574 | |
| 6575 | let mut missing = valid.clone(); |
| 6576 | missing.as_object_mut().unwrap().remove("attachment"); |
| 6577 | assert!(parse_runner_connection(&missing, &enrollment, &start).is_err()); |
| 6578 | |
| 6579 | let mut oversized_cursor = valid.clone(); |
| 6580 | oversized_cursor["attachment"]["runtimeCursor"] = json!(JS_MAX_SAFE_INTEGER + 1); |
| 6581 | assert!(parse_runner_connection(&oversized_cursor, &enrollment, &start).is_err()); |
| 6582 | |
| 6583 | let mut false_receipt = valid.clone(); |
| 6584 | false_receipt["attachment"]["snapshotPresent"] = json!("false"); |
| 6585 | assert!(parse_runner_connection(&false_receipt, &enrollment, &start).is_err()); |
| 6586 | |
| 6587 | let mut extra_authority = valid.clone(); |
| 6588 | extra_authority["attachment"]["workspacePath"] = json!("/private/project"); |
| 6589 | assert!(parse_runner_connection(&extra_authority, &enrollment, &start).is_err()); |
| 6590 | |
| 6591 | let mut wrong_protocol = valid.clone(); |
| 6592 | wrong_protocol["attachment"]["runtimeChatRelayProtocol"] = json!("legacy"); |
| 6593 | assert!(parse_runner_connection(&wrong_protocol, &enrollment, &start).is_err()); |
| 6594 | |
| 6595 | let mut invalid_challenge = valid.clone(); |
| 6596 | invalid_challenge["attachment"]["runtimeChatRelayChallenge"] = json!("too-short"); |
| 6597 | assert!(parse_runner_connection(&invalid_challenge, &enrollment, &start).is_err()); |
| 6598 | |
| 6599 | let mut wrong_control_path = valid; |
| 6600 | wrong_control_path["runner"]["controlPath"] = json!("direct_native"); |
| 6601 | assert!(parse_runner_connection(&wrong_control_path, &enrollment, &start).is_err()); |
| 6602 | } |
| 6603 | |
| 6604 | #[test] |
| 6605 | fn attachment_cursor_seeds_the_first_runtime_event_sequence() { |
| 6606 | let (mut controller, mut worker_rx, event_tx, _journal_root) = wired_controller(); |
| 6607 | event_tx |
| 6608 | .send(RemoteEvent::Connected { |
| 6609 | account_ref: "account_fixture".to_string(), |
| 6610 | runner_id: "runner_fixture".to_string(), |
| 6611 | target_ref: "target_fixture".to_string(), |
| 6612 | attachment: RemoteAttachment { |
| 6613 | run_id: "run_fixture".to_string(), |
| 6614 | workspace_id: "workspace_fixture".to_string(), |
| 6615 | runtime_cursor: 41, |
| 6616 | snapshot_present: false, |
| 6617 | runtime_chat_relay_protocol: RUNTIME_CHAT_RELAY_PROTOCOL.to_string(), |
| 6618 | runtime_chat_relay_challenge: "a".repeat(32), |
| 6619 | }, |
| 6620 | links: RemoteLinks::default(), |
| 6621 | }) |
| 6622 | .unwrap(); |
| 6623 | |
| 6624 | assert!(matches!( |
| 6625 | controller.try_next_event(), |
| 6626 | Some(RemoteEvent::Connected { .. }) |
| 6627 | )); |
| 6628 | controller.upload_snapshot("run_fixture", &[]); |
| 6629 | |
| 6630 | let WorkerCommand::Upload { envelopes, .. } = worker_rx.try_recv().unwrap() else { |
| 6631 | panic!("expected snapshot upload"); |
| 6632 | }; |
| 6633 | assert_eq!(envelopes.len(), 1); |
| 6634 | assert_eq!(envelopes[0]["event"], "session.snapshot"); |
| 6635 | assert_eq!(envelopes[0]["seq"], 42); |
| 6636 | } |
| 6637 | |
| 6638 | #[test] |
| 6639 | fn connected_attachment_adopts_the_existing_turn_and_streams_typed_state_once() { |
| 6640 | let (mut controller, mut worker_rx, event_tx, _journal_root) = wired_controller(); |
| 6641 | event_tx |
| 6642 | .send(RemoteEvent::Connected { |
| 6643 | account_ref: "account_fixture".to_string(), |
| 6644 | runner_id: "runner_fixture".to_string(), |
| 6645 | target_ref: "target_fixture".to_string(), |
| 6646 | attachment: RemoteAttachment { |
| 6647 | run_id: "run_fixture".to_string(), |
| 6648 | workspace_id: "workspace_fixture".to_string(), |
| 6649 | runtime_cursor: 11, |
| 6650 | snapshot_present: false, |
| 6651 | runtime_chat_relay_protocol: RUNTIME_CHAT_RELAY_PROTOCOL.to_string(), |
| 6652 | runtime_chat_relay_challenge: "a".repeat(32), |
| 6653 | }, |
| 6654 | links: RemoteLinks::default(), |
| 6655 | }) |
| 6656 | .unwrap(); |
| 6657 | assert!(matches!( |
| 6658 | controller.try_next_event(), |
| 6659 | Some(RemoteEvent::Connected { .. }) |
| 6660 | )); |
| 6661 | assert!( |
| 6662 | !controller.can_share_approval_with_web(), |
| 6663 | "a connected attachment without a bound typed turn keeps approvals local" |
| 6664 | ); |
| 6665 | assert!(controller.attach_current_local_turn(Some("turn_existing"))); |
| 6666 | assert!( |
| 6667 | controller.can_share_approval_with_web(), |
| 6668 | "the bound active turn can carry typed approvals to the web" |
| 6669 | ); |
| 6670 | assert!(controller.has_active_run()); |
| 6671 | assert!(controller.active_run_matches("run_fixture")); |
| 6672 | assert!( |
| 6673 | !controller.attach_current_local_turn(Some("turn_duplicate")), |
| 6674 | "replaying the attachment must not replace or duplicate the turn" |
| 6675 | ); |
| 6676 | |
| 6677 | controller.observe_engine_event(&EngineEvent::MessageDelta { |
| 6678 | index: 0, |
| 6679 | content: "existing turn output".to_string(), |
| 6680 | }); |
| 6681 | controller.observe_engine_event(&EngineEvent::ToolCallStarted { |
| 6682 | model_call: None, |
| 6683 | id: "tool_existing".to_string(), |
| 6684 | name: "shell".to_string(), |
| 6685 | input: json!({ "never": "relayed" }), |
| 6686 | }); |
| 6687 | let gate = controller.record_remote_approval( |
| 6688 | "tool_existing", |
| 6689 | "shell", |
| 6690 | "approve bounded fixture", |
| 6691 | &json!({ "credential": "must-not-cross" }), |
| 6692 | "approval-key", |
| 6693 | None, |
| 6694 | ); |
| 6695 | |
| 6696 | let mut envelopes = Vec::new(); |
| 6697 | for _ in 0..3 { |
| 6698 | let WorkerCommand::Upload { |
| 6699 | envelopes: batch, .. |
| 6700 | } = worker_rx.try_recv().expect("typed active-turn upload") |
| 6701 | else { |
| 6702 | panic!("active-turn state must use the runtime envelope channel"); |
| 6703 | }; |
| 6704 | envelopes.extend(batch); |
| 6705 | } |
| 6706 | assert_eq!( |
| 6707 | envelopes |
| 6708 | .iter() |
| 6709 | .map(|event| event["event"].as_str().unwrap()) |
| 6710 | .collect::<Vec<_>>(), |
| 6711 | vec!["item.delta", "item.started", "approval.required"] |
| 6712 | ); |
| 6713 | assert!( |
| 6714 | envelopes |
| 6715 | .iter() |
| 6716 | .all(|event| event["turn_id"] == "turn_existing") |
| 6717 | ); |
| 6718 | assert_eq!( |
| 6719 | envelopes[2]["payload"]["approval_id"].as_str(), |
| 6720 | Some(gate.as_str()) |
| 6721 | ); |
| 6722 | let projected = serde_json::to_string(&envelopes).unwrap(); |
| 6723 | assert!(!projected.contains("must-not-cross")); |
| 6724 | assert!(!projected.contains("approval-key")); |
| 6725 | assert!(worker_rx.try_recv().is_err()); |
| 6726 | } |
| 6727 | |
| 6728 | #[test] |
| 6729 | fn dispatch_window_attachment_promotes_on_typed_start_and_reconnect_is_idempotent() { |
| 6730 | let (mut controller, mut worker_rx, event_tx, _journal_root) = wired_controller(); |
| 6731 | let attachment = RemoteAttachment { |
| 6732 | run_id: "run_fixture".to_string(), |
| 6733 | workspace_id: "workspace_fixture".to_string(), |
| 6734 | runtime_cursor: 3, |
| 6735 | snapshot_present: false, |
| 6736 | runtime_chat_relay_protocol: RUNTIME_CHAT_RELAY_PROTOCOL.to_string(), |
| 6737 | runtime_chat_relay_challenge: "a".repeat(32), |
| 6738 | }; |
| 6739 | event_tx |
| 6740 | .send(RemoteEvent::Connected { |
| 6741 | account_ref: "account_fixture".to_string(), |
| 6742 | runner_id: "runner_fixture".to_string(), |
| 6743 | target_ref: "target_fixture".to_string(), |
| 6744 | attachment: attachment.clone(), |
| 6745 | links: RemoteLinks::default(), |
| 6746 | }) |
| 6747 | .unwrap(); |
| 6748 | controller.try_next_event().unwrap(); |
| 6749 | |
| 6750 | assert!(controller.attach_current_local_turn(None)); |
| 6751 | let pending_lease = controller |
| 6752 | .journal |
| 6753 | .as_ref() |
| 6754 | .and_then(RuntimeEventJournal::classic_lease) |
| 6755 | .expect("dispatch-window lease is durable"); |
| 6756 | assert!(pending_lease.turn_id.is_none()); |
| 6757 | assert!( |
| 6758 | controller.has_active_run(), |
| 6759 | "the dispatch window gates stop" |
| 6760 | ); |
| 6761 | assert!(controller.active_run_matches("run_fixture")); |
| 6762 | assert!( |
| 6763 | !controller.can_share_approval_with_web(), |
| 6764 | "a pending dispatch has no typed turn id, so approvals stay local" |
| 6765 | ); |
| 6766 | assert!(worker_rx.try_recv().is_err()); |
| 6767 | |
| 6768 | controller.observe_engine_event(&EngineEvent::TurnStarted { |
| 6769 | previous_source: None, |
| 6770 | turn_id: "turn_started_later".to_string(), |
| 6771 | created_at: chrono::Utc::now(), |
| 6772 | route: None, |
| 6773 | submission_id: None, |
| 6774 | }); |
| 6775 | let WorkerCommand::Upload { envelopes, .. } = |
| 6776 | worker_rx.try_recv().expect("one typed turn start") |
| 6777 | else { |
| 6778 | panic!("turn start must use the runtime envelope channel"); |
| 6779 | }; |
| 6780 | assert_eq!(envelopes.len(), 1); |
| 6781 | assert_eq!(envelopes[0]["seq"], 4); |
| 6782 | assert_eq!(envelopes[0]["event"], "turn.started"); |
| 6783 | assert_eq!(envelopes[0]["turn_id"], "turn_started_later"); |
| 6784 | let promoted_lease = controller |
| 6785 | .journal |
| 6786 | .as_ref() |
| 6787 | .and_then(RuntimeEventJournal::classic_lease) |
| 6788 | .expect("typed start keeps the durable lease"); |
| 6789 | assert_eq!( |
| 6790 | promoted_lease.turn_id.as_deref(), |
| 6791 | Some("turn_started_later") |
| 6792 | ); |
| 6793 | assert_eq!( |
| 6794 | promoted_lease.lease_id, pending_lease.lease_id, |
| 6795 | "typed start promotes the same dispatch generation" |
| 6796 | ); |
| 6797 | let started_envelope = envelopes[0].clone(); |
| 6798 | assert!( |
| 6799 | controller.can_share_approval_with_web(), |
| 6800 | "typed TurnStarted promotes the dispatch into a web-owned active turn" |
| 6801 | ); |
| 6802 | |
| 6803 | event_tx |
| 6804 | .send(RemoteEvent::Attachment { |
| 6805 | account_ref: "account_fixture".to_string(), |
| 6806 | target_ref: "target_fixture".to_string(), |
| 6807 | attachment, |
| 6808 | links: RemoteLinks::default(), |
| 6809 | }) |
| 6810 | .unwrap(); |
| 6811 | controller.try_next_event().unwrap(); |
| 6812 | assert!( |
| 6813 | !controller.attach_current_local_turn(Some("turn_replayed")), |
| 6814 | "a reconnect must not rebind the live turn" |
| 6815 | ); |
| 6816 | let WorkerCommand::Upload { envelopes, .. } = worker_rx |
| 6817 | .try_recv() |
| 6818 | .expect("the unacknowledged start is replayed unchanged") |
| 6819 | else { |
| 6820 | panic!("runtime replay must use the envelope channel"); |
| 6821 | }; |
| 6822 | assert_eq!( |
| 6823 | envelopes, |
| 6824 | vec![started_envelope], |
| 6825 | "retry safety preserves the original sequence and payload" |
| 6826 | ); |
| 6827 | assert!(worker_rx.try_recv().is_err()); |
| 6828 | |
| 6829 | controller.observe_engine_event(&turn_complete_event()); |
| 6830 | let WorkerCommand::Upload { envelopes, .. } = |
| 6831 | worker_rx.try_recv().expect("one terminal receipt") |
| 6832 | else { |
| 6833 | panic!("turn completion must use the runtime envelope channel"); |
| 6834 | }; |
| 6835 | assert_eq!(envelopes.len(), 1); |
| 6836 | assert_eq!(envelopes[0]["seq"], 5); |
| 6837 | assert_eq!(envelopes[0]["event"], "turn.completed"); |
| 6838 | assert_eq!(envelopes[0]["turn_id"], "turn_started_later"); |
| 6839 | assert!(!controller.has_active_run()); |
| 6840 | assert!(worker_rx.try_recv().is_err()); |
| 6841 | } |
| 6842 | |
| 6843 | #[test] |
| 6844 | fn dispatch_window_that_ends_before_typed_start_returns_to_idle_attachment() { |
| 6845 | let (mut controller, mut worker_rx, event_tx, _journal_root) = wired_controller(); |
| 6846 | event_tx |
| 6847 | .send(RemoteEvent::Connected { |
| 6848 | account_ref: "account_fixture".to_string(), |
| 6849 | runner_id: "runner_fixture".to_string(), |
| 6850 | target_ref: "target_fixture".to_string(), |
| 6851 | attachment: RemoteAttachment { |
| 6852 | run_id: "run_fixture".to_string(), |
| 6853 | workspace_id: "workspace_fixture".to_string(), |
| 6854 | runtime_cursor: 8, |
| 6855 | snapshot_present: false, |
| 6856 | runtime_chat_relay_protocol: RUNTIME_CHAT_RELAY_PROTOCOL.to_string(), |
| 6857 | runtime_chat_relay_challenge: "a".repeat(32), |
| 6858 | }, |
| 6859 | links: RemoteLinks::default(), |
| 6860 | }) |
| 6861 | .unwrap(); |
| 6862 | controller.try_next_event().unwrap(); |
| 6863 | |
| 6864 | assert!(controller.attach_current_local_turn(None)); |
| 6865 | assert!(controller.has_active_run()); |
| 6866 | assert!(controller.release_unstarted_local_turn()); |
| 6867 | assert!(!controller.has_active_run()); |
| 6868 | assert!(!controller.can_share_approval_with_web()); |
| 6869 | assert!( |
| 6870 | !controller.release_unstarted_local_turn(), |
| 6871 | "reconciling the same idle boundary is idempotent" |
| 6872 | ); |
| 6873 | assert!(worker_rx.try_recv().is_err()); |
| 6874 | } |
| 6875 | |
| 6876 | #[test] |
| 6877 | fn fresh_controller_refreshes_old_server_snapshot_then_deduplicates_reconnects() { |
| 6878 | let (mut controller, mut worker_rx, event_tx, _journal_root) = wired_controller(); |
| 6879 | event_tx |
| 6880 | .send(RemoteEvent::Connected { |
| 6881 | account_ref: "account_fixture".to_string(), |
| 6882 | runner_id: "runner_fixture".to_string(), |
| 6883 | target_ref: "target_fixture".to_string(), |
| 6884 | attachment: RemoteAttachment { |
| 6885 | run_id: "run_fixture".to_string(), |
| 6886 | workspace_id: "workspace_fixture".to_string(), |
| 6887 | runtime_cursor: 7, |
| 6888 | snapshot_present: true, |
| 6889 | runtime_chat_relay_protocol: RUNTIME_CHAT_RELAY_PROTOCOL.to_string(), |
| 6890 | runtime_chat_relay_challenge: "a".repeat(32), |
| 6891 | }, |
| 6892 | links: RemoteLinks::default(), |
| 6893 | }) |
| 6894 | .unwrap(); |
| 6895 | controller.try_next_event().unwrap(); |
| 6896 | |
| 6897 | controller.upload_snapshot("run_fixture", &[]); |
| 6898 | let WorkerCommand::Upload { envelopes, .. } = worker_rx.try_recv().unwrap() else { |
| 6899 | panic!("fresh controller must refresh saved history"); |
| 6900 | }; |
| 6901 | assert_eq!(envelopes[0]["seq"], 8); |
| 6902 | |
| 6903 | event_tx |
| 6904 | .send(RemoteEvent::Attachment { |
| 6905 | account_ref: "account_fixture".to_string(), |
| 6906 | target_ref: "target_fixture".to_string(), |
| 6907 | attachment: RemoteAttachment { |
| 6908 | run_id: "run_fixture".to_string(), |
| 6909 | workspace_id: "workspace_fixture".to_string(), |
| 6910 | runtime_cursor: 7, |
| 6911 | snapshot_present: false, |
| 6912 | runtime_chat_relay_protocol: RUNTIME_CHAT_RELAY_PROTOCOL.to_string(), |
| 6913 | runtime_chat_relay_challenge: "a".repeat(32), |
| 6914 | }, |
| 6915 | links: RemoteLinks::default(), |
| 6916 | }) |
| 6917 | .unwrap(); |
| 6918 | controller.try_next_event().unwrap(); |
| 6919 | controller.upload_snapshot("run_fixture", &[]); |
| 6920 | let WorkerCommand::Upload { envelopes, .. } = worker_rx.try_recv().unwrap() else { |
| 6921 | panic!("unacknowledged snapshot must be retried"); |
| 6922 | }; |
| 6923 | assert_eq!(envelopes[0]["seq"], 8); |
| 6924 | controller.upload_snapshot("run_fixture", &[]); |
| 6925 | assert!(worker_rx.try_recv().is_err()); |
| 6926 | |
| 6927 | event_tx |
| 6928 | .send(RemoteEvent::Attachment { |
| 6929 | account_ref: "account_fixture".to_string(), |
| 6930 | target_ref: "target_fixture".to_string(), |
| 6931 | attachment: RemoteAttachment { |
| 6932 | run_id: "run_fixture".to_string(), |
| 6933 | workspace_id: "workspace_fixture".to_string(), |
| 6934 | runtime_cursor: 8, |
| 6935 | snapshot_present: true, |
| 6936 | runtime_chat_relay_protocol: RUNTIME_CHAT_RELAY_PROTOCOL.to_string(), |
| 6937 | runtime_chat_relay_challenge: "a".repeat(32), |
| 6938 | }, |
| 6939 | links: RemoteLinks::default(), |
| 6940 | }) |
| 6941 | .unwrap(); |
| 6942 | controller.try_next_event().unwrap(); |
| 6943 | controller.upload_snapshot("run_fixture", &[]); |
| 6944 | assert!(worker_rx.try_recv().is_err()); |
| 6945 | } |
| 6946 | |
| 6947 | #[test] |
| 6948 | fn reconnect_cursor_retires_only_the_acknowledged_prefix() { |
| 6949 | let (mut controller, mut worker_rx, event_tx, _journal_root) = wired_controller(); |
| 6950 | controller.event_seq.insert("run_fixture".to_string(), 6); |
| 6951 | controller.upload_envelope( |
| 6952 | "run_fixture", |
| 6953 | "item.delta", |
| 6954 | None, |
| 6955 | json!({ "delta": "seven" }), |
| 6956 | ); |
| 6957 | controller.upload_envelope( |
| 6958 | "run_fixture", |
| 6959 | "item.delta", |
| 6960 | None, |
| 6961 | json!({ "delta": "eight" }), |
| 6962 | ); |
| 6963 | worker_rx.try_recv().unwrap(); |
| 6964 | worker_rx.try_recv().unwrap(); |
| 6965 | |
| 6966 | event_tx |
| 6967 | .send(RemoteEvent::Attachment { |
| 6968 | account_ref: "account_fixture".to_string(), |
| 6969 | target_ref: "target_fixture".to_string(), |
| 6970 | attachment: RemoteAttachment { |
| 6971 | run_id: "run_fixture".to_string(), |
| 6972 | workspace_id: "workspace_fixture".to_string(), |
| 6973 | runtime_cursor: 7, |
| 6974 | snapshot_present: false, |
| 6975 | runtime_chat_relay_protocol: RUNTIME_CHAT_RELAY_PROTOCOL.to_string(), |
| 6976 | runtime_chat_relay_challenge: "a".repeat(32), |
| 6977 | }, |
| 6978 | links: RemoteLinks::default(), |
| 6979 | }) |
| 6980 | .unwrap(); |
| 6981 | controller.try_next_event().unwrap(); |
| 6982 | |
| 6983 | let WorkerCommand::Upload { envelopes, .. } = worker_rx.try_recv().unwrap() else { |
| 6984 | panic!("seq 8 must remain pending"); |
| 6985 | }; |
| 6986 | assert_eq!(envelopes.len(), 1); |
| 6987 | assert_eq!(envelopes[0]["seq"], 8); |
| 6988 | assert_eq!( |
| 6989 | controller |
| 6990 | .pending_runtime_events |
| 6991 | .get("run_fixture") |
| 6992 | .unwrap() |
| 6993 | .keys() |
| 6994 | .copied() |
| 6995 | .collect::<Vec<_>>(), |
| 6996 | vec![8] |
| 6997 | ); |
| 6998 | |
| 6999 | event_tx |
| 7000 | .send(RemoteEvent::Attachment { |
| 7001 | account_ref: "account_fixture".to_string(), |
| 7002 | target_ref: "target_fixture".to_string(), |
| 7003 | attachment: RemoteAttachment { |
| 7004 | run_id: "run_fixture".to_string(), |
| 7005 | workspace_id: "workspace_fixture".to_string(), |
| 7006 | runtime_cursor: 6, |
| 7007 | snapshot_present: false, |
| 7008 | runtime_chat_relay_protocol: RUNTIME_CHAT_RELAY_PROTOCOL.to_string(), |
| 7009 | runtime_chat_relay_challenge: "a".repeat(32), |
| 7010 | }, |
| 7011 | links: RemoteLinks::default(), |
| 7012 | }) |
| 7013 | .unwrap(); |
| 7014 | controller.try_next_event().unwrap(); |
| 7015 | let WorkerCommand::Upload { envelopes, .. } = worker_rx.try_recv().unwrap() else { |
| 7016 | panic!("older cursor cannot discard seq 8"); |
| 7017 | }; |
| 7018 | assert_eq!(envelopes[0]["seq"], 8); |
| 7019 | |
| 7020 | event_tx |
| 7021 | .send(RemoteEvent::RuntimeCursor { |
| 7022 | run_id: "run_fixture".to_string(), |
| 7023 | cursor: 8, |
| 7024 | }) |
| 7025 | .unwrap(); |
| 7026 | controller.try_next_event().unwrap(); |
| 7027 | assert!( |
| 7028 | !controller |
| 7029 | .pending_runtime_events |
| 7030 | .contains_key("run_fixture") |
| 7031 | ); |
| 7032 | } |
| 7033 | |
| 7034 | #[tokio::test] |
| 7035 | async fn ambiguous_success_retries_the_identical_runtime_event_until_cursor_acceptance() { |
| 7036 | let server = MockServer::start().await; |
| 7037 | let responder = AmbiguousRuntimeResponder::default(); |
| 7038 | Mock::given(method("POST")) |
| 7039 | .and(path( |
| 7040 | "/api/local-runners/runner_fixture/runs/run_fixture/events", |
| 7041 | )) |
| 7042 | .respond_with(responder.clone()) |
| 7043 | .expect(2) |
| 7044 | .mount(&server) |
| 7045 | .await; |
| 7046 | let enrollment = fixture_enrollment(&format!("{}/", server.uri())); |
| 7047 | let client = codewhale_release::tls::reqwest_client_builder() |
| 7048 | .redirect(reqwest::redirect::Policy::none()) |
| 7049 | .build() |
| 7050 | .expect("fixture client"); |
| 7051 | let envelope = runtime_envelope( |
| 7052 | 1, |
| 7053 | "item.delta", |
| 7054 | None, |
| 7055 | "2026-08-08T12:00:00Z".to_string(), |
| 7056 | json!({ "delta": "exact body" }), |
| 7057 | ); |
| 7058 | let mut outbox = RuntimeTransportOutbox::default(); |
| 7059 | outbox |
| 7060 | .enqueue("run_fixture", envelope) |
| 7061 | .expect("queue runtime event"); |
| 7062 | |
| 7063 | assert_eq!( |
| 7064 | outbox |
| 7065 | .try_flush_one(&client, &enrollment, "runner_fixture") |
| 7066 | .await |
| 7067 | .unwrap(), |
| 7068 | RuntimeFlushOutcome::Retryable |
| 7069 | ); |
| 7070 | assert_eq!(outbox.events.len(), 1); |
| 7071 | assert_eq!( |
| 7072 | outbox |
| 7073 | .try_flush_one(&client, &enrollment, "runner_fixture") |
| 7074 | .await |
| 7075 | .unwrap(), |
| 7076 | RuntimeFlushOutcome::Accepted { |
| 7077 | run_id: "run_fixture".to_string(), |
| 7078 | cursor: 1, |
| 7079 | } |
| 7080 | ); |
| 7081 | assert!(outbox.events.is_empty()); |
| 7082 | let bodies = responder.bodies.lock().unwrap(); |
| 7083 | assert_eq!(bodies.len(), 2); |
| 7084 | assert_eq!(bodies[0], bodies[1]); |
| 7085 | } |
| 7086 | |
| 7087 | #[test] |
| 7088 | fn snapshot_envelope_is_unicode_safe_and_keeps_newest_history() { |
| 7089 | let messages = (0..80) |
| 7090 | .map(|index| { |
| 7091 | let marker = format!("message-{index:02}-"); |
| 7092 | text_message( |
| 7093 | if index % 2 == 0 { "user" } else { "assistant" }, |
| 7094 | marker + &"🫧\"\\\n".repeat(1_500), |
| 7095 | ) |
| 7096 | }) |
| 7097 | .collect::<Vec<_>>(); |
| 7098 | |
| 7099 | let envelope = bounded_session_snapshot_envelope(1, &messages); |
| 7100 | let encoded = serde_json::to_vec(&envelope).unwrap(); |
| 7101 | let retained = envelope["payload"]["messages"].as_array().unwrap(); |
| 7102 | |
| 7103 | assert!(encoded.len() <= SNAPSHOT_ENVELOPE_BYTE_BUDGET); |
| 7104 | assert!(encoded.len() < MAX_RUNTIME_ENVELOPE_BYTES); |
| 7105 | assert!(!retained.is_empty()); |
| 7106 | assert!(retained.len() <= MAX_SNAPSHOT_MESSAGES); |
| 7107 | assert!( |
| 7108 | retained.last().unwrap()["text"] |
| 7109 | .as_str() |
| 7110 | .unwrap() |
| 7111 | .starts_with("message-79-") |
| 7112 | ); |
| 7113 | for message in retained { |
| 7114 | let text = message["text"].as_str().unwrap(); |
| 7115 | assert!(!text.contains('\u{FFFD}')); |
| 7116 | assert!(text.is_char_boundary(text.len())); |
| 7117 | } |
| 7118 | } |
| 7119 | |
| 7120 | #[test] |
| 7121 | fn snapshot_truncation_pins_the_exact_encoded_byte_boundary() { |
| 7122 | let source = "🫧\"\\\n".repeat(40_000); |
| 7123 | let message = text_message("assistant", source); |
| 7124 | let envelope = bounded_session_snapshot_envelope(9, std::slice::from_ref(&message)); |
| 7125 | let encoded = serde_json::to_vec(&envelope).unwrap(); |
| 7126 | assert!(encoded.len() <= SNAPSHOT_ENVELOPE_BYTE_BUDGET); |
| 7127 | |
| 7128 | let retained = envelope["payload"]["messages"][0]["text"].as_str().unwrap(); |
| 7129 | let projected = project_session_message(&message).unwrap().1; |
| 7130 | let retained_chars = retained.chars().count(); |
| 7131 | let next = projected.chars().nth(retained_chars).unwrap(); |
| 7132 | let mut one_more = retained.to_string(); |
| 7133 | one_more.push(next); |
| 7134 | let timestamp = envelope["timestamp"].as_str().unwrap(); |
| 7135 | let expanded = vec![json!({ "role": "assistant", "text": one_more })]; |
| 7136 | assert!( |
| 7137 | snapshot_envelope_len(9, timestamp, &expanded) > SNAPSHOT_ENVELOPE_BYTE_BUDGET, |
| 7138 | "one more Unicode scalar must cross the chosen encoded boundary" |
| 7139 | ); |
| 7140 | } |
| 7141 | |
| 7142 | #[test] |
| 7143 | fn fatal_engine_error_projects_failure_and_releases_the_remote_run() { |
| 7144 | let (mut controller, mut worker_rx, _event_tx, _journal_root) = wired_controller(); |
| 7145 | controller |
| 7146 | .activate_prompt("run_fixture", "turn_fixture") |
| 7147 | .unwrap(); |
| 7148 | let secret = "sk-runtime-secret-that-must-not-cross-the-relay"; |
| 7149 | let message = format!( |
| 7150 | "DeepSeek API key: {secret}\n{}", |
| 7151 | "🫧".repeat(MAX_REMOTE_ERROR_MESSAGE_BYTES) |
| 7152 | ); |
| 7153 | |
| 7154 | controller.observe_engine_event(&EngineEvent::Error { |
| 7155 | envelope: codewhale_error_taxonomy::ErrorEnvelope::new( |
| 7156 | codewhale_error_taxonomy::ErrorCategory::Authentication, |
| 7157 | codewhale_error_taxonomy::ErrorSeverity::Critical, |
| 7158 | false, |
| 7159 | "llm_auth_error", |
| 7160 | message, |
| 7161 | ), |
| 7162 | recoverable: false, |
| 7163 | }); |
| 7164 | |
| 7165 | assert!(!controller.has_active_run()); |
| 7166 | let WorkerCommand::Upload { |
| 7167 | envelopes: failed, .. |
| 7168 | } = worker_rx.try_recv().expect("fatal item upload") |
| 7169 | else { |
| 7170 | panic!("fatal error must upload an item.failed envelope"); |
| 7171 | }; |
| 7172 | let WorkerCommand::Upload { |
| 7173 | envelopes: completed, |
| 7174 | .. |
| 7175 | } = worker_rx.try_recv().expect("fatal turn upload") |
| 7176 | else { |
| 7177 | panic!("fatal error must upload a terminal turn envelope"); |
| 7178 | }; |
| 7179 | assert_eq!(failed.len(), 1); |
| 7180 | assert_eq!(failed[0]["seq"], 1); |
| 7181 | assert_eq!(failed[0]["event"], "item.failed"); |
| 7182 | assert_eq!(failed[0]["turn_id"], "turn_fixture"); |
| 7183 | assert_eq!(failed[0]["payload"]["item"]["kind"], "error"); |
| 7184 | assert_eq!(failed[0]["payload"]["item"]["status"], "failed"); |
| 7185 | let projected = failed[0]["payload"]["item"]["detail"] |
| 7186 | .as_str() |
| 7187 | .expect("bounded error detail"); |
| 7188 | assert!(projected.len() <= MAX_REMOTE_ERROR_MESSAGE_BYTES); |
| 7189 | assert!(projected.is_char_boundary(projected.len())); |
| 7190 | assert!(!projected.contains(secret)); |
| 7191 | assert!(projected.contains("[redacted]")); |
| 7192 | |
| 7193 | assert_eq!(completed.len(), 1); |
| 7194 | assert_eq!(completed[0]["seq"], 2); |
| 7195 | assert_eq!(completed[0]["event"], "turn.completed"); |
| 7196 | assert_eq!(completed[0]["turn_id"], "turn_fixture"); |
| 7197 | assert_eq!(completed[0]["payload"]["turn"]["status"], "failed"); |
| 7198 | assert_eq!( |
| 7199 | controller.pending_runtime_events["run_fixture"] |
| 7200 | .keys() |
| 7201 | .copied() |
| 7202 | .collect::<Vec<_>>(), |
| 7203 | vec![1, 2] |
| 7204 | ); |
| 7205 | assert!(worker_rx.try_recv().is_err()); |
| 7206 | } |
| 7207 | |
| 7208 | #[test] |
| 7209 | fn recoverable_engine_error_stays_nonterminal_for_provider_fallback() { |
| 7210 | let mut controller = RemoteControlController::default(); |
| 7211 | let (worker_tx, mut worker_rx) = mpsc::unbounded_channel(); |
| 7212 | controller.worker_tx = Some(worker_tx); |
| 7213 | controller |
| 7214 | .activate_prompt("run_fixture", "turn_fixture") |
| 7215 | .unwrap(); |
| 7216 | |
| 7217 | controller.observe_engine_event(&EngineEvent::Error { |
| 7218 | envelope: codewhale_error_taxonomy::ErrorEnvelope::network( |
| 7219 | "temporary provider connection failure", |
| 7220 | ), |
| 7221 | recoverable: true, |
| 7222 | }); |
| 7223 | |
| 7224 | assert!(controller.active_run_matches("run_fixture")); |
| 7225 | assert!(controller.pending_runtime_events.is_empty()); |
| 7226 | assert!(worker_rx.try_recv().is_err()); |
| 7227 | } |
| 7228 | |
| 7229 | #[test] |
| 7230 | fn terminal_pre_dispatch_error_uses_the_same_failure_projection() { |
| 7231 | let (mut controller, mut worker_rx, _event_tx, _journal_root) = wired_controller(); |
| 7232 | controller |
| 7233 | .activate_prompt("run_fixture", "turn_fixture") |
| 7234 | .unwrap(); |
| 7235 | |
| 7236 | controller.fail_active_dispatch( |
| 7237 | "DeepSeek API key: sk-preflight-secret-that-must-not-cross-the-relay", |
| 7238 | ); |
| 7239 | |
| 7240 | assert!(!controller.has_active_run()); |
| 7241 | let WorkerCommand::Upload { envelopes, .. } = |
| 7242 | worker_rx.try_recv().expect("pre-dispatch item upload") |
| 7243 | else { |
| 7244 | panic!("pre-dispatch error must upload item.failed"); |
| 7245 | }; |
| 7246 | assert_eq!(envelopes[0]["event"], "item.failed"); |
| 7247 | assert!(!envelopes[0].to_string().contains("sk-preflight-secret")); |
| 7248 | let WorkerCommand::Upload { envelopes, .. } = |
| 7249 | worker_rx.try_recv().expect("pre-dispatch turn upload") |
| 7250 | else { |
| 7251 | panic!("pre-dispatch error must upload turn.completed"); |
| 7252 | }; |
| 7253 | assert_eq!(envelopes[0]["event"], "turn.completed"); |
| 7254 | assert_eq!(envelopes[0]["payload"]["turn"]["status"], "failed"); |
| 7255 | assert!(worker_rx.try_recv().is_err()); |
| 7256 | } |
| 7257 | |
| 7258 | #[test] |
| 7259 | fn typed_command_parser_rejects_shell_and_cross_run_content() { |
| 7260 | let prompt = parse_remote_command( |
| 7261 | &json!({ |
| 7262 | "type": "prompt.request", |
| 7263 | "runId": "run-1", |
| 7264 | "turnId": "turn-1", |
| 7265 | "prompt": "Continue", |
| 7266 | }), |
| 7267 | "run-1", |
| 7268 | ) |
| 7269 | .unwrap(); |
| 7270 | assert_eq!( |
| 7271 | prompt, |
| 7272 | RemoteCommand::Prompt { |
| 7273 | turn_id: "turn-1".to_string(), |
| 7274 | prompt: "Continue".to_string(), |
| 7275 | } |
| 7276 | ); |
| 7277 | for field in [ |
| 7278 | "watchEvent", |
| 7279 | "watch_event", |
| 7280 | "inputProvenance", |
| 7281 | "input_provenance", |
| 7282 | ] { |
| 7283 | let mut value = |
| 7284 | json!({"type":"prompt.request","runId":"run-1","turnId":"turn-1","prompt":"watch"}); |
| 7285 | value[field] = json!({"version":1}); |
| 7286 | assert!(parse_remote_command(&value, "run-1").is_err()); |
| 7287 | let mut nested = json!({"type":"prompt.request","runId":"run-1","turnId":"turn-1","prompt":"watch","metadata":{}}); |
| 7288 | nested["metadata"][field] = json!({"version":1}); |
| 7289 | assert!(parse_remote_command(&nested, "run-1").is_err()); |
| 7290 | } |
| 7291 | assert!( |
| 7292 | parse_remote_command( |
| 7293 | &json!({ |
| 7294 | "type": "shell", |
| 7295 | "runId": "run-1", |
| 7296 | "command": "rm -rf /", |
| 7297 | }), |
| 7298 | "run-1" |
| 7299 | ) |
| 7300 | .is_err() |
| 7301 | ); |
| 7302 | assert!( |
| 7303 | parse_remote_command( |
| 7304 | &json!({ |
| 7305 | "type": "prompt.request", |
| 7306 | "runId": "run-other", |
| 7307 | "turnId": "turn-1", |
| 7308 | "prompt": "Continue", |
| 7309 | }), |
| 7310 | "run-1" |
| 7311 | ) |
| 7312 | .is_err() |
| 7313 | ); |
| 7314 | } |
| 7315 | |
| 7316 | fn runtime_chat_prompt_fixture() -> Value { |
| 7317 | json!({ |
| 7318 | "type": "prompt.request", |
| 7319 | "runId": "run-1", |
| 7320 | "turnId": format!("local_turn_{}", "b".repeat(24)), |
| 7321 | "operationKey": "operation-1", |
| 7322 | "runtimeBindingId": "binding-1", |
| 7323 | "runtimeThreadId": format!("local_thread_{}", "a".repeat(24)), |
| 7324 | "prompt": "Hello from account Chat", |
| 7325 | "systemPrompt": "Answer directly.", |
| 7326 | "model": "model-1", |
| 7327 | "modelProvider": "ollama", |
| 7328 | "modelProviderId": "ollama", |
| 7329 | "reasoningEffort": "high", |
| 7330 | "allowedTools": [], |
| 7331 | "mode": "chat", |
| 7332 | "requestedMode": "chat", |
| 7333 | "workspace": { |
| 7334 | "id": "workspace-1", |
| 7335 | "targetRef": "target-1" |
| 7336 | } |
| 7337 | }) |
| 7338 | } |
| 7339 | |
| 7340 | #[test] |
| 7341 | fn runtime_chat_parser_requires_exact_route_tools_mode_and_interrupt_scope() { |
| 7342 | let command = parse_remote_command(&runtime_chat_prompt_fixture(), "run-1").unwrap(); |
| 7343 | assert!(matches!(command, RemoteCommand::RuntimeChatPrompt(_))); |
| 7344 | |
| 7345 | for mutation in [ |
| 7346 | ("allowedTools", json!(["bash"])), |
| 7347 | ("mode", json!("work")), |
| 7348 | ("requestedMode", json!("operate")), |
| 7349 | ("modelProvider", json!("https://provider.invalid")), |
| 7350 | ] { |
| 7351 | let mut value = runtime_chat_prompt_fixture(); |
| 7352 | value[mutation.0] = mutation.1; |
| 7353 | assert!(parse_remote_command(&value, "run-1").is_err()); |
| 7354 | } |
| 7355 | let mut unknown = runtime_chat_prompt_fixture(); |
| 7356 | unknown["workspacePath"] = json!("/private/workspace"); |
| 7357 | assert!(parse_remote_command(&unknown, "run-1").is_err()); |
| 7358 | let mut missing_markers = runtime_chat_prompt_fixture(); |
| 7359 | let record = missing_markers.as_object_mut().unwrap(); |
| 7360 | record.remove("operationKey"); |
| 7361 | record.remove("runtimeBindingId"); |
| 7362 | record.remove("runtimeThreadId"); |
| 7363 | assert!( |
| 7364 | parse_remote_command(&missing_markers, "run-1").is_err(), |
| 7365 | "a rich Chat-shaped payload cannot downgrade into a legacy Work prompt" |
| 7366 | ); |
| 7367 | |
| 7368 | let interrupt = json!({ |
| 7369 | "type": "run.control", |
| 7370 | "runId": "run-1", |
| 7371 | "action": "interrupt", |
| 7372 | "reason": "Stop this turn", |
| 7373 | "turnId": format!("local_turn_{}", "b".repeat(24)), |
| 7374 | "runtimeBindingId": "binding-1", |
| 7375 | "runtimeThreadId": format!("local_thread_{}", "a".repeat(24)) |
| 7376 | }); |
| 7377 | assert!(matches!( |
| 7378 | parse_remote_command(&interrupt, "run-1").unwrap(), |
| 7379 | RemoteCommand::Control { |
| 7380 | runtime_chat: Some(_), |
| 7381 | .. |
| 7382 | } |
| 7383 | )); |
| 7384 | let mut drifted = interrupt; |
| 7385 | drifted["runtimeThreadId"] = json!(format!("local_thread_{}", "F".repeat(24))); |
| 7386 | assert!(parse_remote_command(&drifted, "run-1").is_err()); |
| 7387 | } |
| 7388 | |
| 7389 | #[test] |
| 7390 | fn legacy_control_requires_and_matches_the_exact_active_turn() { |
| 7391 | assert!( |
| 7392 | parse_remote_command( |
| 7393 | &json!({ |
| 7394 | "type": "run.control", |
| 7395 | "runId": "run-1", |
| 7396 | "action": "interrupt" |
| 7397 | }), |
| 7398 | "run-1" |
| 7399 | ) |
| 7400 | .is_err(), |
| 7401 | "run-only cancellation can target a newer turn in the same run" |
| 7402 | ); |
| 7403 | assert!( |
| 7404 | parse_remote_command( |
| 7405 | &json!({ |
| 7406 | "type": "run.control", |
| 7407 | "runId": "run-1", |
| 7408 | "action": "interrupt", |
| 7409 | "turnId": "../../stale" |
| 7410 | }), |
| 7411 | "run-1" |
| 7412 | ) |
| 7413 | .is_err() |
| 7414 | ); |
| 7415 | let parsed = parse_remote_command( |
| 7416 | &json!({ |
| 7417 | "type": "run.control", |
| 7418 | "runId": "run-1", |
| 7419 | "action": "interrupt", |
| 7420 | "turnId": "turn-current" |
| 7421 | }), |
| 7422 | "run-1", |
| 7423 | ) |
| 7424 | .unwrap(); |
| 7425 | assert!(matches!( |
| 7426 | parsed, |
| 7427 | RemoteCommand::Control { |
| 7428 | turn_id: Some(ref turn_id), |
| 7429 | runtime_chat: None, |
| 7430 | .. |
| 7431 | } if turn_id == "turn-current" |
| 7432 | )); |
| 7433 | |
| 7434 | let mut controller = RemoteControlController::default(); |
| 7435 | controller.activate_prompt("run-1", "turn-current").unwrap(); |
| 7436 | assert!(controller.active_turn_matches("run-1", "turn-current")); |
| 7437 | assert!(!controller.active_turn_matches("run-1", "turn-stale")); |
| 7438 | assert!(!controller.active_turn_matches("run-other", "turn-current")); |
| 7439 | } |
| 7440 | |
| 7441 | #[test] |
| 7442 | fn runtime_chat_semantic_envelope_carries_stable_native_source_id() { |
| 7443 | let source_event_id = format!("native_event_{}", "a".repeat(64)); |
| 7444 | let semantic = runtime_chat_envelope( |
| 7445 | 9, |
| 7446 | "item.delta", |
| 7447 | Some("local_thread_fixture"), |
| 7448 | Some("local_turn_fixture"), |
| 7449 | Some(&source_event_id), |
| 7450 | "2026-08-23T00:00:00Z".to_string(), |
| 7451 | json!({ "delta": "hello" }), |
| 7452 | ); |
| 7453 | assert_eq!(semantic["schema_version"], 2); |
| 7454 | assert_eq!(semantic["source_event_id"], source_event_id); |
| 7455 | |
| 7456 | let catalog_payload = json!({ |
| 7457 | "schemaVersion": 2, |
| 7458 | "challenge": "a".repeat(32), |
| 7459 | "providers": [{ "id": "safe", "models": [{ "id": "model-1" }] }] |
| 7460 | }); |
| 7461 | let fingerprint = |
| 7462 | RuntimeChatRelayHost::catalog_payload_fingerprint(&catalog_payload).unwrap(); |
| 7463 | let catalog_source_id = runtime_chat_catalog_source_event_id("run_fixture", &fingerprint); |
| 7464 | let catalog = runtime_chat_envelope( |
| 7465 | 1, |
| 7466 | "runtime.catalog", |
| 7467 | None, |
| 7468 | None, |
| 7469 | Some(&catalog_source_id), |
| 7470 | RUNTIME_CHAT_CATALOG_TIMESTAMP.to_string(), |
| 7471 | catalog_payload.clone(), |
| 7472 | ); |
| 7473 | let replay = runtime_chat_envelope( |
| 7474 | 99, |
| 7475 | "runtime.catalog", |
| 7476 | None, |
| 7477 | None, |
| 7478 | Some(&catalog_source_id), |
| 7479 | RUNTIME_CHAT_CATALOG_TIMESTAMP.to_string(), |
| 7480 | catalog_payload, |
| 7481 | ); |
| 7482 | assert_eq!(catalog["source_event_id"], catalog_source_id); |
| 7483 | let mut catalog_semantic = catalog; |
| 7484 | let mut replay_semantic = replay; |
| 7485 | catalog_semantic.as_object_mut().unwrap().remove("seq"); |
| 7486 | replay_semantic.as_object_mut().unwrap().remove("seq"); |
| 7487 | assert_eq!(catalog_semantic, replay_semantic); |
| 7488 | |
| 7489 | let changed_fingerprint = RuntimeChatRelayHost::catalog_payload_fingerprint( |
| 7490 | &json!({ "schemaVersion": 2, "challenge": "a".repeat(32), "providers": [] }), |
| 7491 | ) |
| 7492 | .unwrap(); |
| 7493 | assert_ne!( |
| 7494 | runtime_chat_catalog_source_event_id("run_fixture", &changed_fingerprint), |
| 7495 | catalog_source_id |
| 7496 | ); |
| 7497 | } |
| 7498 | |
| 7499 | #[test] |
| 7500 | fn approval_projection_matches_control_plane_namespace() { |
| 7501 | assert_eq!(projected_approval_id("tool-call-1").len(), 39); |
| 7502 | assert!(projected_approval_id("tool-call-1").starts_with("local_approval_")); |
| 7503 | assert_ne!( |
| 7504 | projected_approval_id("tool-call-1"), |
| 7505 | projected_approval_id("tool-call-2") |
| 7506 | ); |
| 7507 | } |
| 7508 | |
| 7509 | #[test] |
| 7510 | fn authorization_url_is_exact_and_cannot_redirect_or_add_parameters() { |
| 7511 | assert!( |
| 7512 | validate_authorization_url( |
| 7513 | "https://app.codewhale.net/runner/authorize?user_code=ABCD-EFGH-JKLM", |
| 7514 | "ABCD-EFGH-JKLM", |
| 7515 | ) |
| 7516 | .is_ok() |
| 7517 | ); |
| 7518 | for spoofed in [ |
| 7519 | "http://app.codewhale.net/runner/authorize?user_code=ABCD-EFGH-JKLM", |
| 7520 | "https://app.codewhale.net.evil.example/runner/authorize?user_code=ABCD-EFGH-JKLM", |
| 7521 | "https://app.codewhale.net/runner/authorize?user_code=ABCD-EFGH-JKLM&next=https://evil.example", |
| 7522 | "https://app.codewhale.net/runner/authorize?user_code=WRONG-CODE", |
| 7523 | ] { |
| 7524 | assert!(validate_authorization_url(spoofed, "ABCD-EFGH-JKLM").is_err()); |
| 7525 | } |
| 7526 | } |
| 7527 | |
| 7528 | #[test] |
| 7529 | fn command_sequences_are_content_bound_and_replay_safe() { |
| 7530 | let mut controller = RemoteControlController::default(); |
| 7531 | controller.status = Status::Connected; |
| 7532 | controller.attached_run_id = Some("run-1".to_string()); |
| 7533 | let prompt = RemoteCommand::Prompt { |
| 7534 | turn_id: "turn-1".to_string(), |
| 7535 | prompt: "Continue".to_string(), |
| 7536 | }; |
| 7537 | assert_eq!(controller.claim_command("run-1", 1, &prompt), Ok(true)); |
| 7538 | assert_eq!(controller.claim_command("run-1", 1, &prompt), Ok(false)); |
| 7539 | assert!( |
| 7540 | controller |
| 7541 | .claim_command( |
| 7542 | "run-1", |
| 7543 | 1, |
| 7544 | &RemoteCommand::Prompt { |
| 7545 | turn_id: "turn-1".to_string(), |
| 7546 | prompt: "Changed".to_string(), |
| 7547 | }, |
| 7548 | ) |
| 7549 | .is_err() |
| 7550 | ); |
| 7551 | } |
| 7552 | |
| 7553 | #[tokio::test] |
| 7554 | async fn durable_runtime_chat_replay_bypasses_only_new_work_recovery_gates() { |
| 7555 | let root = tempfile::tempdir().unwrap(); |
| 7556 | let runtime_root = root.path().join("runtime-chat"); |
| 7557 | let command = parse_remote_command(&runtime_chat_prompt_fixture(), "run-1").unwrap(); |
| 7558 | let RemoteCommand::RuntimeChatPrompt(prompt) = &command else { |
| 7559 | panic!("fixture must parse as Runtime Chat"); |
| 7560 | }; |
| 7561 | { |
| 7562 | let mut first = RemoteControlController::default(); |
| 7563 | first |
| 7564 | .configure_runtime_chat( |
| 7565 | codewhale_runtime::config::Config::default(), |
| 7566 | Arc::new(codewhale_plugins::PluginRegistry::empty(root.path())), |
| 7567 | runtime_root.clone(), |
| 7568 | "target-1".to_string(), |
| 7569 | "session_fixture".to_string(), |
| 7570 | ) |
| 7571 | .unwrap(); |
| 7572 | let host = first.runtime_chat.as_ref().unwrap(); |
| 7573 | host.bind_account("account_fixture", "target-1").unwrap(); |
| 7574 | host.install_prompt_replay_for_tests(prompt, true) |
| 7575 | .await |
| 7576 | .unwrap(); |
| 7577 | } |
| 7578 | |
| 7579 | let mut controller = RemoteControlController::default(); |
| 7580 | controller |
| 7581 | .configure_runtime_chat( |
| 7582 | codewhale_runtime::config::Config::default(), |
| 7583 | Arc::new(codewhale_plugins::PluginRegistry::empty(root.path())), |
| 7584 | runtime_root.clone(), |
| 7585 | "target-1".to_string(), |
| 7586 | "session_fixture".to_string(), |
| 7587 | ) |
| 7588 | .unwrap(); |
| 7589 | controller |
| 7590 | .runtime_chat |
| 7591 | .as_ref() |
| 7592 | .unwrap() |
| 7593 | .bind_account("account_fixture", "target-1") |
| 7594 | .unwrap(); |
| 7595 | controller |
| 7596 | .runtime_chat |
| 7597 | .as_ref() |
| 7598 | .unwrap() |
| 7599 | .authorize_run("run-1") |
| 7600 | .unwrap(); |
| 7601 | let envelope = runtime_chat_envelope( |
| 7602 | 9, |
| 7603 | "turn.completed", |
| 7604 | Some(&prompt.runtime_thread_id), |
| 7605 | Some(&prompt.turn_id), |
| 7606 | Some("native_event_exact_replay_gate"), |
| 7607 | "2026-08-23T00:00:00Z".to_string(), |
| 7608 | json!({ "turn": { "status": "completed" } }), |
| 7609 | ); |
| 7610 | controller.pending_runtime_events.insert( |
| 7611 | "run-1".to_string(), |
| 7612 | BTreeMap::from([( |
| 7613 | 9, |
| 7614 | PendingRuntimeEnvelope { |
| 7615 | encoded_len: serde_json::to_vec(&envelope).unwrap().len(), |
| 7616 | envelope, |
| 7617 | integrity: true, |
| 7618 | handed_off: true, |
| 7619 | }, |
| 7620 | )]), |
| 7621 | ); |
| 7622 | let changed_config = { |
| 7623 | let __cw_config_init_5_0 = Some("changed-after-restart".to_string()); |
| 7624 | let mut __cw_config_init_5_value: codewhale_runtime::config::Config = |
| 7625 | codewhale_runtime::config::Config::default(); |
| 7626 | __cw_config_init_5_value.default_text_model = __cw_config_init_5_0; |
| 7627 | __cw_config_init_5_value |
| 7628 | }; |
| 7629 | controller |
| 7630 | .configure_runtime_chat( |
| 7631 | changed_config, |
| 7632 | Arc::new(codewhale_plugins::PluginRegistry::empty(root.path())), |
| 7633 | runtime_root, |
| 7634 | "target-1".to_string(), |
| 7635 | "session_fixture".to_string(), |
| 7636 | ) |
| 7637 | .unwrap(); |
| 7638 | assert!(controller.pending_runtime_chat_configuration.is_some()); |
| 7639 | controller.status = Status::Connected; |
| 7640 | controller.attached_run_id = Some("run-1".to_string()); |
| 7641 | controller.attached_workspace_id = Some(prompt.workspace.id.clone()); |
| 7642 | controller.target_ref = Some(prompt.workspace.target_ref.clone()); |
| 7643 | |
| 7644 | assert_eq!(controller.claim_command("run-1", 17, &command), Ok(false)); |
| 7645 | controller.apply_runtime_chat_prompt(prompt).await.unwrap(); |
| 7646 | let mut changed = runtime_chat_prompt_fixture(); |
| 7647 | changed["prompt"] = json!("changed replay body"); |
| 7648 | let changed = parse_remote_command(&changed, "run-1").unwrap(); |
| 7649 | assert!(controller.claim_command("run-1", 17, &changed).is_err()); |
| 7650 | } |
| 7651 | |
| 7652 | #[tokio::test] |
| 7653 | async fn pre_lease_failure_never_locks_and_allows_immediate_retry() { |
| 7654 | let (mut controller, _worker_rx, event_tx, _journal_root) = wired_controller(); |
| 7655 | let mut invalid_start = fixture_start(); |
| 7656 | invalid_start.runtime_commit.clear(); |
| 7657 | let error = controller.start(invalid_start).unwrap_err(); |
| 7658 | assert!(error.contains("enrollable identity"), "{error}"); |
| 7659 | assert_eq!(controller.status, Status::Failed); |
| 7660 | assert!(controller.status_line().contains(&error)); |
| 7661 | assert!(controller.ownership_blocked_until.is_none()); |
| 7662 | controller.status = Status::Connecting; |
| 7663 | controller.status_detail = "connecting fixture".to_string(); |
| 7664 | assert!(controller.start(fixture_start()).is_err()); |
| 7665 | assert_eq!(controller.status, Status::Connecting); |
| 7666 | assert_eq!(controller.status_detail, "connecting fixture"); |
| 7667 | event_tx |
| 7668 | .send(RemoteEvent::FailedPreLease( |
| 7669 | "Codewhale rejected remote-control enrollment (403): client version not accepted." |
| 7670 | .to_string(), |
| 7671 | )) |
| 7672 | .unwrap(); |
| 7673 | assert!(matches!( |
| 7674 | controller.try_next_event(), |
| 7675 | Some(RemoteEvent::FailedPreLease(_)) |
| 7676 | )); |
| 7677 | assert_eq!(controller.status, Status::Failed); |
| 7678 | assert!( |
| 7679 | controller.ownership_blocked_until.is_none(), |
| 7680 | "a rejection before any lease must never start the reconnect blackout" |
| 7681 | ); |
| 7682 | let line = controller.status_line(); |
| 7683 | assert!(line.contains("failed before connecting"), "{line}"); |
| 7684 | assert!(line.contains("/rc to retry"), "{line}"); |
| 7685 | assert!( |
| 7686 | line.contains("403"), |
| 7687 | "the sanitized HTTP status must surface: {line}" |
| 7688 | ); |
| 7689 | assert!(line.contains("client version not accepted"), "{line}"); |
| 7690 | |
| 7691 | // Stopping after a pre-lease failure is an ordinary reset (no lease |
| 7692 | // to drain, no blackout to honor). |
| 7693 | controller.stop(); |
| 7694 | assert_eq!(controller.status, Status::Off); |
| 7695 | |
| 7696 | // Immediate retry is allowed — no lease drain wait. |
| 7697 | let result = controller.start(RemoteStart { |
| 7698 | workspace_label: "fixture".to_string(), |
| 7699 | target_ref: "target_fixture".to_string(), |
| 7700 | session_id: "session_fixture".to_string(), |
| 7701 | runtime_version: "0.9.1".to_string(), |
| 7702 | runtime_commit: "a".repeat(40), |
| 7703 | journal_dir: None, |
| 7704 | git_remote: None, |
| 7705 | }); |
| 7706 | assert!(result.is_ok(), "{result:?}"); |
| 7707 | } |
| 7708 | |
| 7709 | #[test] |
| 7710 | fn sanitized_rejection_excerpt_reads_only_bounded_error_fields() { |
| 7711 | assert_eq!( |
| 7712 | sanitized_rejection_excerpt(br#"{"error":"RunnerEnrollmentError","details":{"code":"runner_runtime_identity_unavailable"},"message":"private server detail"}"#, StatusCode::SERVICE_UNAVAILABLE).as_deref(), |
| 7713 | Some("Remote control is temporarily unavailable because this service has not been configured for a Codewhale build. Try again later") |
| 7714 | ); |
| 7715 | assert_eq!( |
| 7716 | sanitized_rejection_excerpt(br#"{"error":"RunnerEnrollmentError","details":{"code":"runner_runtime_identity_unsupported"}}"#, StatusCode::UNPROCESSABLE_ENTITY).as_deref(), |
| 7717 | Some("This Codewhale build is not accepted by the remote-control service. Check your installed version or contact the service administrator") |
| 7718 | ); |
| 7719 | assert_eq!( |
| 7720 | sanitized_rejection_excerpt( |
| 7721 | br#"{"code":"runner_runtime_identity_unavailable"}"#, |
| 7722 | StatusCode::SERVICE_UNAVAILABLE |
| 7723 | ) |
| 7724 | .as_deref(), |
| 7725 | Some( |
| 7726 | "Remote control is temporarily unavailable because this service has not been configured for a Codewhale build. Try again later" |
| 7727 | ) |
| 7728 | ); |
| 7729 | for body in [ |
| 7730 | br#"{"error":"opaque-synthetic-value"}"#.as_slice(), |
| 7731 | br#"{"message":"https://example.test/?token=synthetic"}"#, |
| 7732 | br#"{"title":"bad\u0000opaque"}"#, |
| 7733 | br#"{"details":{"code":"runner_runtime_identity_unavailable"}}"#, |
| 7734 | b"<html>403</html>", |
| 7735 | b"{\"error\":\"bad\0opaque\"}", |
| 7736 | ] { |
| 7737 | assert_eq!( |
| 7738 | sanitized_rejection_excerpt(body, StatusCode::BAD_REQUEST), |
| 7739 | None |
| 7740 | ); |
| 7741 | } |
| 7742 | let long = format!("{{\"error\":\"{}\"}}", "x".repeat(400)); |
| 7743 | assert_eq!( |
| 7744 | sanitized_rejection_excerpt(long.as_bytes(), StatusCode::BAD_REQUEST), |
| 7745 | None |
| 7746 | ); |
| 7747 | } |
| 7748 | |
| 7749 | #[tokio::test] |
| 7750 | async fn enrollment_rejection_carries_a_sanitized_actionable_reason() { |
| 7751 | let server = MockServer::start().await; |
| 7752 | Mock::given(method("POST")) |
| 7753 | .and(path("/oauth/device")) |
| 7754 | .respond_with(ResponseTemplate::new(403).set_body_json(json!({ |
| 7755 | "error": "client version not accepted", |
| 7756 | "documentation": "https://example.test/docs" |
| 7757 | }))) |
| 7758 | .mount(&server) |
| 7759 | .await; |
| 7760 | let client = codewhale_release::tls::reqwest_client_builder() |
| 7761 | .https_only(false) |
| 7762 | .redirect(reqwest::redirect::Policy::none()) |
| 7763 | .timeout(Duration::from_secs(5)) |
| 7764 | .build() |
| 7765 | .expect("test client"); |
| 7766 | let error = public_request( |
| 7767 | &client, |
| 7768 | Method::POST, |
| 7769 | Url::parse(&format!( |
| 7770 | "{}/oauth/device", |
| 7771 | server.uri().trim_end_matches('/') |
| 7772 | )) |
| 7773 | .expect("server url"), |
| 7774 | json!({ "audience": "codewhale-runner" }), |
| 7775 | ) |
| 7776 | .await |
| 7777 | .expect_err("403 must fail"); |
| 7778 | assert!(error.contains("403"), "{error}"); |
| 7779 | assert!(!error.contains("client version not accepted"), "{error}"); |
| 7780 | assert!(!error.contains("example.test"), "{error}"); |
| 7781 | Mock::given(method("POST")) |
| 7782 | .and(path("/oauth/known")) |
| 7783 | .respond_with(ResponseTemplate::new(503).set_body_json(json!({ |
| 7784 | "code": "runner_runtime_identity_unavailable", |
| 7785 | "message": "opaque-synthetic-value" |
| 7786 | }))) |
| 7787 | .mount(&server) |
| 7788 | .await; |
| 7789 | let known = public_request( |
| 7790 | &client, |
| 7791 | Method::POST, |
| 7792 | Url::parse(&format!( |
| 7793 | "{}/oauth/known", |
| 7794 | server.uri().trim_end_matches('/') |
| 7795 | )) |
| 7796 | .expect("server url"), |
| 7797 | json!({ "audience": "codewhale-runner" }), |
| 7798 | ) |
| 7799 | .await |
| 7800 | .expect_err("503 must fail"); |
| 7801 | assert!(known.contains("temporarily unavailable"), "{known}"); |
| 7802 | assert!(!known.contains("opaque-synthetic-value"), "{known}"); |
| 7803 | } |
| 7804 | |
| 7805 | #[tokio::test] |
| 7806 | async fn failed_relay_keeps_reconnect_blocked_until_lease_expiry() { |
| 7807 | let mut controller = RemoteControlController::default(); |
| 7808 | controller.status = Status::Failed; |
| 7809 | controller.ownership_blocked_until = Some(Instant::now() + Duration::from_secs(90)); |
| 7810 | controller.status_detail = "fixture transport failure".to_string(); |
| 7811 | let deadline = controller.ownership_blocked_until; |
| 7812 | // Mirror semantics: local input is never locked, but reconnecting |
| 7813 | // while the server lease may still be live is refused — the web must |
| 7814 | // not see two runners for the same session. |
| 7815 | let start = RemoteStart { |
| 7816 | workspace_label: "fixture".to_string(), |
| 7817 | target_ref: "target_fixture".to_string(), |
| 7818 | session_id: "session_fixture".to_string(), |
| 7819 | runtime_version: "0.9.1".to_string(), |
| 7820 | runtime_commit: "a".repeat(40), |
| 7821 | journal_dir: None, |
| 7822 | git_remote: None, |
| 7823 | }; |
| 7824 | assert!(controller.start(start.clone()).is_err()); |
| 7825 | assert_eq!(controller.ownership_blocked_until, deadline); |
| 7826 | assert_eq!(controller.status_detail, "fixture transport failure"); |
| 7827 | // The web cannot answer shared approvals while the relay is failed. |
| 7828 | assert!(!controller.can_share_approval_with_web()); |
| 7829 | controller.ownership_blocked_until = Some(Instant::now() - Duration::from_secs(1)); |
| 7830 | assert!(controller.start(start).is_ok()); |
| 7831 | } |
| 7832 | |
| 7833 | #[test] |
| 7834 | fn stop_after_lease_expiry_preserves_pending_approvals_for_restoration() { |
| 7835 | let mut controller = RemoteControlController::default(); |
| 7836 | controller.status = Status::Failed; |
| 7837 | controller.ownership_blocked_until = Some(Instant::now() - Duration::from_secs(1)); |
| 7838 | controller.pending_approvals.insert( |
| 7839 | "approval_fixture".to_string(), |
| 7840 | PendingRemoteApproval { |
| 7841 | tool_id: "tool_fixture".to_string(), |
| 7842 | }, |
| 7843 | ); |
| 7844 | |
| 7845 | controller.stop(); |
| 7846 | assert_eq!(controller.status, Status::Failed); |
| 7847 | assert_eq!(controller.pending_approvals.len(), 1); |
| 7848 | |
| 7849 | let event = controller.try_next_event(); |
| 7850 | assert!(matches!( |
| 7851 | event, |
| 7852 | Some(RemoteEvent::OwnershipRestored { approvals }) |
| 7853 | if approvals.len() == 1 && approvals[0].tool_id == "tool_fixture" |
| 7854 | )); |
| 7855 | assert_eq!(controller.status, Status::Off); |
| 7856 | assert!(controller.pending_approvals.is_empty()); |
| 7857 | } |
| 7858 | |
| 7859 | #[test] |
| 7860 | fn cancelling_a_connect_keeps_reconnect_blocked_until_lease_drain() { |
| 7861 | let mut controller = RemoteControlController::default(); |
| 7862 | controller.status = Status::Connecting; |
| 7863 | controller.stop(); |
| 7864 | |
| 7865 | assert_eq!(controller.status, Status::Failed); |
| 7866 | // Mirror semantics: nothing about a cancelled connect locks local |
| 7867 | // input; reconnect stays blocked until the possible lease drains. |
| 7868 | let result = controller.start(RemoteStart { |
| 7869 | workspace_label: "fixture".to_string(), |
| 7870 | target_ref: "target_fixture".to_string(), |
| 7871 | session_id: "session_fixture".to_string(), |
| 7872 | runtime_version: "0.9.1".to_string(), |
| 7873 | runtime_commit: "a".repeat(40), |
| 7874 | journal_dir: None, |
| 7875 | git_remote: None, |
| 7876 | }); |
| 7877 | assert!(result.is_err()); |
| 7878 | assert!(result.unwrap_err().contains("previous remote lease")); |
| 7879 | } |
| 7880 | |
| 7881 | #[test] |
| 7882 | fn failed_worker_retains_snapshot_marker_and_exact_unacked_event() { |
| 7883 | let (mut controller, mut worker_rx, event_tx, _journal_root) = wired_controller(); |
| 7884 | controller.status = Status::Connected; |
| 7885 | controller.upload_snapshot("run-1", &[]); |
| 7886 | let WorkerCommand::Upload { envelopes, .. } = worker_rx.try_recv().unwrap() else { |
| 7887 | panic!("snapshot queued"); |
| 7888 | }; |
| 7889 | let exact = envelopes[0].clone(); |
| 7890 | event_tx |
| 7891 | .send(RemoteEvent::Failed("fixture disconnect".to_string())) |
| 7892 | .unwrap(); |
| 7893 | |
| 7894 | assert!(matches!( |
| 7895 | controller.try_next_event(), |
| 7896 | Some(RemoteEvent::Failed(_)) |
| 7897 | )); |
| 7898 | assert!(controller.uploaded_snapshots.contains("run-1")); |
| 7899 | assert_eq!( |
| 7900 | controller.pending_runtime_events["run-1"] |
| 7901 | .values() |
| 7902 | .next() |
| 7903 | .map(|entry| &entry.envelope), |
| 7904 | Some(&exact) |
| 7905 | ); |
| 7906 | // Fail-closed: the web can no longer answer shared approvals, and |
| 7907 | // reconnecting waits out the possible server lease. |
| 7908 | assert!(!controller.can_share_approval_with_web()); |
| 7909 | assert!(controller.ownership_blocked_until.is_some()); |
| 7910 | } |
| 7911 | |
| 7912 | #[tokio::test] |
| 7913 | async fn cwc_runner_wire_contract_preserves_pending_and_recovery_commands() { |
| 7914 | let server = MockServer::start().await; |
| 7915 | Mock::given(method("GET")) |
| 7916 | .and(path("/api/local-runners/runner-1/runs/run-1/commands")) |
| 7917 | .and(query_param("since_seq", "0")) |
| 7918 | .and(query_param("include_accepted", "1")) |
| 7919 | .respond_with(ResponseTemplate::new(200).set_body_json(json!({ |
| 7920 | "commands": [{ |
| 7921 | "seq": 1, |
| 7922 | "deliveryStatus": "pending", |
| 7923 | "ackStatus": "", |
| 7924 | "command": { |
| 7925 | "type": "prompt.request", |
| 7926 | "runId": "run-1", |
| 7927 | "turnId": "turn-1", |
| 7928 | "prompt": "Continue from the web." |
| 7929 | } |
| 7930 | }, { |
| 7931 | "seq": 2, |
| 7932 | "deliveryStatus": "acknowledged", |
| 7933 | "ackStatus": "accepted", |
| 7934 | "command": { |
| 7935 | "type": "run.control", |
| 7936 | "runId": "run-1", |
| 7937 | "action": "interrupt" |
| 7938 | } |
| 7939 | }] |
| 7940 | }))) |
| 7941 | .expect(1) |
| 7942 | .mount(&server) |
| 7943 | .await; |
| 7944 | Mock::given(method("POST")) |
| 7945 | .and(path("/api/local-runners/runner-1/runs/run-1/events")) |
| 7946 | .and(body_json(json!({ |
| 7947 | "acknowledgements": [{ |
| 7948 | "commandSeq": 1, |
| 7949 | "commandType": "prompt.request", |
| 7950 | "status": "accepted", |
| 7951 | "turnId": "turn-1" |
| 7952 | }], |
| 7953 | "envelopes": [] |
| 7954 | }))) |
| 7955 | .respond_with(ResponseTemplate::new(200).set_body_json(json!({ |
| 7956 | "accepted": [], |
| 7957 | "count": 1, |
| 7958 | "cursor": 0 |
| 7959 | }))) |
| 7960 | .expect(1) |
| 7961 | .mount(&server) |
| 7962 | .await; |
| 7963 | |
| 7964 | let enrollment = LiveEnrollment { |
| 7965 | persisted: PersistedEnrollment { |
| 7966 | schema_version: 1, |
| 7967 | control_plane_base: format!("{}/", server.uri()), |
| 7968 | runner_enrollment_id: "enrollment-1".to_string(), |
| 7969 | account_ref: "account-1".to_string(), |
| 7970 | device_id: "device-1".to_string(), |
| 7971 | target_ref: "target-1".to_string(), |
| 7972 | target_grant_ref: "grant-1".to_string(), |
| 7973 | runtime_version: "0.9.1".to_string(), |
| 7974 | runtime_commit: "a".repeat(40), |
| 7975 | bootstrap_secret: "b".repeat(43), |
| 7976 | }, |
| 7977 | access_token: "fixture-runner-access-token".to_string(), |
| 7978 | }; |
| 7979 | let client = codewhale_release::tls::reqwest_client_builder() |
| 7980 | .redirect(reqwest::redirect::Policy::none()) |
| 7981 | .build() |
| 7982 | .expect("fixture client"); |
| 7983 | |
| 7984 | let listed = list_commands(&client, &enrollment, "runner-1", "run-1", 0) |
| 7985 | .await |
| 7986 | .expect("CWC command list"); |
| 7987 | assert_eq!(listed.len(), 2); |
| 7988 | assert_eq!(listed[0].ack_status, ""); |
| 7989 | assert_eq!(listed[1].ack_status, "accepted"); |
| 7990 | let prompt = |
| 7991 | parse_remote_command(&listed[0].command, "run-1").expect("typed prompt command"); |
| 7992 | upload_command_accepted( |
| 7993 | &client, |
| 7994 | &enrollment, |
| 7995 | "runner-1", |
| 7996 | "run-1", |
| 7997 | listed[0].seq, |
| 7998 | &prompt, |
| 7999 | ) |
| 8000 | .await |
| 8001 | .expect("durable accepted acknowledgement"); |
| 8002 | } |
| 8003 | |
| 8004 | fn wired_controller() -> ( |
| 8005 | RemoteControlController, |
| 8006 | mpsc::UnboundedReceiver<WorkerCommand>, |
| 8007 | mpsc::UnboundedSender<RemoteEvent>, |
| 8008 | tempfile::TempDir, |
| 8009 | ) { |
| 8010 | let mut controller = RemoteControlController::default(); |
| 8011 | let (worker_tx, worker_rx) = mpsc::unbounded_channel(); |
| 8012 | let (event_tx, event_rx) = mpsc::unbounded_channel(); |
| 8013 | let journal_root = tempfile::tempdir().expect("wired controller journal root"); |
| 8014 | controller.journal = Some( |
| 8015 | RuntimeEventJournal::open( |
| 8016 | journal_root.path(), |
| 8017 | "target_wired_fixture", |
| 8018 | "session_wired_fixture", |
| 8019 | ) |
| 8020 | .expect("wired controller journal"), |
| 8021 | ); |
| 8022 | controller.worker_tx = Some(worker_tx); |
| 8023 | controller.event_rx = Some(event_rx); |
| 8024 | (controller, worker_rx, event_tx, journal_root) |
| 8025 | } |
| 8026 | |
| 8027 | fn turn_complete_event() -> EngineEvent { |
| 8028 | EngineEvent::TurnComplete { |
| 8029 | source_accounting: false, |
| 8030 | |
| 8031 | turn_id: None, |
| 8032 | submission_id: None, |
| 8033 | compaction_id: None, |
| 8034 | usage: codewhale_models::Usage::default(), |
| 8035 | parent_route_usage: codewhale_models::Usage::default(), |
| 8036 | routed_usage_dropped_records: 0, |
| 8037 | status: TurnOutcomeStatus::Completed, |
| 8038 | error: None, |
| 8039 | tool_catalog: None, |
| 8040 | base_url: None, |
| 8041 | } |
| 8042 | } |
| 8043 | |
| 8044 | #[test] |
| 8045 | fn stop_refusal_holds_until_terminal_event_is_acknowledged() { |
| 8046 | let (mut controller, mut worker_rx, event_tx, _journal_root) = wired_controller(); |
| 8047 | controller |
| 8048 | .activate_prompt("run_fixture", "turn_fixture") |
| 8049 | .unwrap(); |
| 8050 | let refusal = controller.stop_refusal().expect("active turn blocks stop"); |
| 8051 | assert!(refusal.contains("active remote turn"), "{refusal}"); |
| 8052 | |
| 8053 | controller.observe_engine_event(&turn_complete_event()); |
| 8054 | assert!( |
| 8055 | !controller.has_active_run(), |
| 8056 | "the terminal event releases the run binding" |
| 8057 | ); |
| 8058 | let refusal = controller |
| 8059 | .stop_refusal() |
| 8060 | .expect("a queued but unacknowledged terminal event must still block stop"); |
| 8061 | assert!(refusal.contains("acknowledged"), "{refusal}"); |
| 8062 | let WorkerCommand::Upload { envelopes, .. } = worker_rx.try_recv().unwrap() else { |
| 8063 | panic!("the terminal envelope must be handed to the transport"); |
| 8064 | }; |
| 8065 | assert_eq!(envelopes[0]["event"], "turn.completed"); |
| 8066 | let seq = envelopes[0]["seq"].as_u64().expect("terminal seq"); |
| 8067 | |
| 8068 | event_tx |
| 8069 | .send(RemoteEvent::RuntimeCursor { |
| 8070 | run_id: "run_fixture".to_string(), |
| 8071 | cursor: seq, |
| 8072 | }) |
| 8073 | .unwrap(); |
| 8074 | controller.try_next_event().unwrap(); |
| 8075 | assert_eq!( |
| 8076 | controller.stop_refusal(), |
| 8077 | None, |
| 8078 | "a server-acknowledged terminal event unblocks stop" |
| 8079 | ); |
| 8080 | } |
| 8081 | |
| 8082 | #[test] |
| 8083 | fn different_run_attachment_is_quarantined_during_active_classic_work() { |
| 8084 | let (mut controller, _worker_rx, event_tx, _journal_root) = wired_controller(); |
| 8085 | let attachment = |run_id: &str| RemoteAttachment { |
| 8086 | run_id: run_id.to_string(), |
| 8087 | workspace_id: "workspace_fixture".to_string(), |
| 8088 | runtime_cursor: 0, |
| 8089 | snapshot_present: false, |
| 8090 | runtime_chat_relay_protocol: RUNTIME_CHAT_RELAY_PROTOCOL.to_string(), |
| 8091 | runtime_chat_relay_challenge: "a".repeat(32), |
| 8092 | }; |
| 8093 | event_tx |
| 8094 | .send(RemoteEvent::Connected { |
| 8095 | account_ref: "account_fixture".to_string(), |
| 8096 | runner_id: "runner_fixture".to_string(), |
| 8097 | target_ref: "target_wired_fixture".to_string(), |
| 8098 | attachment: attachment("run_a"), |
| 8099 | links: RemoteLinks::default(), |
| 8100 | }) |
| 8101 | .unwrap(); |
| 8102 | controller.try_next_event().unwrap(); |
| 8103 | controller.activate_prompt("run_a", "turn_a").unwrap(); |
| 8104 | |
| 8105 | event_tx |
| 8106 | .send(RemoteEvent::Attachment { |
| 8107 | account_ref: "account_fixture".to_string(), |
| 8108 | target_ref: "target_wired_fixture".to_string(), |
| 8109 | attachment: attachment("run_b"), |
| 8110 | links: RemoteLinks::default(), |
| 8111 | }) |
| 8112 | .unwrap(); |
| 8113 | let rejected = controller |
| 8114 | .try_next_event() |
| 8115 | .expect("rejected attachment event"); |
| 8116 | assert!(matches!(rejected, RemoteEvent::Failed(_))); |
| 8117 | assert_eq!(controller.attached_run_id.as_deref(), Some("run_a")); |
| 8118 | assert!(controller.active_turn_matches("run_a", "turn_a")); |
| 8119 | assert_eq!(controller.status, Status::Failed); |
| 8120 | assert!( |
| 8121 | controller.worker_tx.is_none(), |
| 8122 | "rejected authority is quarantined" |
| 8123 | ); |
| 8124 | assert!( |
| 8125 | controller |
| 8126 | .claim_command( |
| 8127 | "run_b", |
| 8128 | 1, |
| 8129 | &RemoteCommand::Prompt { |
| 8130 | turn_id: "turn_b".to_string(), |
| 8131 | prompt: "must not run".to_string(), |
| 8132 | }, |
| 8133 | ) |
| 8134 | .is_err(), |
| 8135 | "no command from the rejected run may execute" |
| 8136 | ); |
| 8137 | } |
| 8138 | |
| 8139 | #[test] |
| 8140 | fn failed_stop_stays_fail_closed_with_no_dual_ownership() { |
| 8141 | let (mut controller, _worker_rx, event_tx, _journal_root) = wired_controller(); |
| 8142 | controller.status = Status::Connected; |
| 8143 | controller.stop(); |
| 8144 | assert_eq!(controller.status, Status::Stopping); |
| 8145 | assert!( |
| 8146 | !controller.can_share_approval_with_web(), |
| 8147 | "stopping must close the shared-decision channel before confirmation" |
| 8148 | ); |
| 8149 | |
| 8150 | // The worker could not confirm the drain or the offline heartbeat. |
| 8151 | event_tx |
| 8152 | .send(RemoteEvent::Failed( |
| 8153 | "the offline heartbeat could not be delivered".to_string(), |
| 8154 | )) |
| 8155 | .unwrap(); |
| 8156 | let event = controller.try_next_event().unwrap(); |
| 8157 | assert!(matches!(event, RemoteEvent::Failed(_))); |
| 8158 | assert!( |
| 8159 | !controller.can_share_approval_with_web(), |
| 8160 | "an unconfirmed stop must stay fail-closed through the lease expiry" |
| 8161 | ); |
| 8162 | assert!(controller.ownership_blocked_until.is_some()); |
| 8163 | assert!( |
| 8164 | controller.status_line().contains("lost after connecting"), |
| 8165 | "{}", |
| 8166 | controller.status_line() |
| 8167 | ); |
| 8168 | assert!( |
| 8169 | controller.try_next_event().is_none(), |
| 8170 | "ownership must not be restored while the lease could still be live" |
| 8171 | ); |
| 8172 | } |
| 8173 | |
| 8174 | #[tokio::test] |
| 8175 | async fn stop_drain_flushes_runtime_outbox_with_byte_identical_retries() { |
| 8176 | let server = MockServer::start().await; |
| 8177 | let responder = AmbiguousRuntimeResponder::default(); |
| 8178 | Mock::given(method("POST")) |
| 8179 | .and(path( |
| 8180 | "/api/local-runners/runner_fixture/runs/run_fixture/events", |
| 8181 | )) |
| 8182 | .respond_with(responder.clone()) |
| 8183 | .expect(2) |
| 8184 | .mount(&server) |
| 8185 | .await; |
| 8186 | let mut enrollment = fixture_enrollment(&format!("{}/", server.uri())); |
| 8187 | let mut runner_id = "runner_fixture".to_string(); |
| 8188 | let client = codewhale_release::tls::reqwest_client_builder() |
| 8189 | .redirect(reqwest::redirect::Policy::none()) |
| 8190 | .build() |
| 8191 | .expect("fixture client"); |
| 8192 | let (event_tx, mut event_rx) = mpsc::unbounded_channel(); |
| 8193 | let mut outbox = RuntimeTransportOutbox::default(); |
| 8194 | outbox |
| 8195 | .enqueue( |
| 8196 | "run_fixture", |
| 8197 | runtime_envelope( |
| 8198 | 1, |
| 8199 | "turn.completed", |
| 8200 | Some("turn_fixture"), |
| 8201 | "2026-08-08T12:00:00Z".to_string(), |
| 8202 | json!({ "turn": { "status": "completed", "usage": {} } }), |
| 8203 | ), |
| 8204 | ) |
| 8205 | .expect("queue terminal envelope"); |
| 8206 | |
| 8207 | drain_runtime_outbox_for_stop( |
| 8208 | &client, |
| 8209 | &mut enrollment, |
| 8210 | &mut runner_id, |
| 8211 | &fixture_start(), |
| 8212 | &event_tx, |
| 8213 | &mut outbox, |
| 8214 | Instant::now() + Duration::from_secs(10), |
| 8215 | ) |
| 8216 | .await |
| 8217 | .expect("the drain must complete before stop is confirmed"); |
| 8218 | |
| 8219 | assert!(outbox.events.is_empty(), "the outbox must drain fully"); |
| 8220 | let RemoteEvent::RuntimeCursor { run_id, cursor } = event_rx |
| 8221 | .try_recv() |
| 8222 | .expect("cursor event for journal compaction") |
| 8223 | else { |
| 8224 | panic!("drain must surface the server cursor"); |
| 8225 | }; |
| 8226 | assert_eq!(run_id, "run_fixture"); |
| 8227 | assert_eq!(cursor, 1); |
| 8228 | let bodies = responder.bodies.lock().unwrap(); |
| 8229 | assert_eq!(bodies.len(), 2, "ambiguous response must be retried"); |
| 8230 | assert_eq!(bodies[0], bodies[1], "retries must be byte-identical"); |
| 8231 | } |
| 8232 | |
| 8233 | #[tokio::test] |
| 8234 | async fn stop_drain_stops_when_a_fresh_credential_is_refused_again() { |
| 8235 | let _env = codewhale_engine::test_support::lock_test_env(); |
| 8236 | let secrets_root = tempfile::tempdir().expect("isolated remote-control secrets"); |
| 8237 | let _codewhale_home = |
| 8238 | codewhale_engine::test_support::EnvVarGuard::set("CODEWHALE_HOME", secrets_root.path()); |
| 8239 | let server = MockServer::start().await; |
| 8240 | // A terminal refusal: the runner may not write this run, and a new |
| 8241 | // access token does not change that. |
| 8242 | Mock::given(method("POST")) |
| 8243 | .and(path( |
| 8244 | "/api/local-runners/runner_fixture/runs/run_fixture/events", |
| 8245 | )) |
| 8246 | .respond_with(ResponseTemplate::new(403)) |
| 8247 | .expect(2) |
| 8248 | .mount(&server) |
| 8249 | .await; |
| 8250 | let access_token = codewhale_engine::test_support::future_test_jwt(&"a".repeat(40)); |
| 8251 | Mock::given(method("POST")) |
| 8252 | .and(path("/api/runner/enrollments/token")) |
| 8253 | .respond_with(ResponseTemplate::new(200).set_body_json(json!({ |
| 8254 | "enrollment": { |
| 8255 | "id": "enrollment_fixture", |
| 8256 | "userId": "account_fixture", |
| 8257 | "deviceId": "device_fixture", |
| 8258 | "runtimeVersion": "0.9.6", |
| 8259 | "runtimeCommit": "a".repeat(40), |
| 8260 | "capabilities": CAPABILITIES, |
| 8261 | }, |
| 8262 | "credential": { "accessToken": access_token }, |
| 8263 | }))) |
| 8264 | .expect(1) |
| 8265 | .mount(&server) |
| 8266 | .await; |
| 8267 | Mock::given(method("POST")) |
| 8268 | .and(path("/api/local-runners/connect")) |
| 8269 | .respond_with(ResponseTemplate::new(200).set_body_json(fixture_connection_response())) |
| 8270 | .mount(&server) |
| 8271 | .await; |
| 8272 | let mut enrollment = fixture_enrollment(&format!("{}/", server.uri())); |
| 8273 | let mut runner_id = "runner_fixture".to_string(); |
| 8274 | let client = codewhale_release::tls::reqwest_client_builder() |
| 8275 | .redirect(reqwest::redirect::Policy::none()) |
| 8276 | .build() |
| 8277 | .expect("fixture client"); |
| 8278 | let (event_tx, _event_rx) = mpsc::unbounded_channel(); |
| 8279 | let mut outbox = RuntimeTransportOutbox::default(); |
| 8280 | outbox |
| 8281 | .enqueue( |
| 8282 | "run_fixture", |
| 8283 | runtime_envelope( |
| 8284 | 1, |
| 8285 | "turn.completed", |
| 8286 | Some("turn_fixture"), |
| 8287 | "2026-08-08T12:00:00Z".to_string(), |
| 8288 | json!({ "turn": { "status": "completed", "usage": {} } }), |
| 8289 | ), |
| 8290 | ) |
| 8291 | .expect("queue terminal envelope"); |
| 8292 | |
| 8293 | let error = drain_runtime_outbox_for_stop( |
| 8294 | &client, |
| 8295 | &mut enrollment, |
| 8296 | &mut runner_id, |
| 8297 | &fixture_start(), |
| 8298 | &event_tx, |
| 8299 | &mut outbox, |
| 8300 | Instant::now() + Duration::from_secs(5), |
| 8301 | ) |
| 8302 | .await |
| 8303 | .expect_err("a refusal that survives a refresh must end the drain"); |
| 8304 | assert_eq!(error, RUNTIME_REFRESHED_CREDENTIAL_REFUSED); |
| 8305 | assert!( |
| 8306 | !outbox.events.is_empty(), |
| 8307 | "the refused envelope stays queued for a later, authorized resend" |
| 8308 | ); |
| 8309 | } |
| 8310 | |
| 8311 | #[tokio::test] |
| 8312 | async fn stop_drain_deadline_failure_refuses_to_confirm_stop() { |
| 8313 | let server = MockServer::start().await; |
| 8314 | Mock::given(method("POST")) |
| 8315 | .and(path( |
| 8316 | "/api/local-runners/runner_fixture/runs/run_fixture/events", |
| 8317 | )) |
| 8318 | .respond_with(ResponseTemplate::new(500)) |
| 8319 | .mount(&server) |
| 8320 | .await; |
| 8321 | let mut enrollment = fixture_enrollment(&format!("{}/", server.uri())); |
| 8322 | let mut runner_id = "runner_fixture".to_string(); |
| 8323 | let client = codewhale_release::tls::reqwest_client_builder() |
| 8324 | .redirect(reqwest::redirect::Policy::none()) |
| 8325 | .build() |
| 8326 | .expect("fixture client"); |
| 8327 | let (event_tx, _event_rx) = mpsc::unbounded_channel(); |
| 8328 | let mut outbox = RuntimeTransportOutbox::default(); |
| 8329 | outbox |
| 8330 | .enqueue( |
| 8331 | "run_fixture", |
| 8332 | runtime_envelope( |
| 8333 | 1, |
| 8334 | "turn.completed", |
| 8335 | Some("turn_fixture"), |
| 8336 | "2026-08-08T12:00:00Z".to_string(), |
| 8337 | json!({ "turn": { "status": "completed", "usage": {} } }), |
| 8338 | ), |
| 8339 | ) |
| 8340 | .expect("queue terminal envelope"); |
| 8341 | |
| 8342 | let error = drain_runtime_outbox_for_stop( |
| 8343 | &client, |
| 8344 | &mut enrollment, |
| 8345 | &mut runner_id, |
| 8346 | &fixture_start(), |
| 8347 | &event_tx, |
| 8348 | &mut outbox, |
| 8349 | Instant::now() + Duration::from_millis(700), |
| 8350 | ) |
| 8351 | .await |
| 8352 | .expect_err("an undrained outbox must fail the stop"); |
| 8353 | assert!(error.contains("not confirmed"), "{error}"); |
| 8354 | assert!( |
| 8355 | !outbox.events.is_empty(), |
| 8356 | "the exact unacknowledged envelope must be retained for the reconnect resend" |
| 8357 | ); |
| 8358 | } |
| 8359 | |
| 8360 | #[test] |
| 8361 | fn journal_roundtrip_restores_unacknowledged_envelopes_byte_identically() { |
| 8362 | let dir = tempfile::tempdir().expect("journal tempdir"); |
| 8363 | let journal = |
| 8364 | RuntimeEventJournal::open(dir.path(), "target:fixture@01", "session:fixture@01") |
| 8365 | .expect("journal setup"); |
| 8366 | assert!(journal.load().expect("missing file is empty").is_empty()); |
| 8367 | |
| 8368 | let delta = runtime_envelope( |
| 8369 | 1, |
| 8370 | "item.delta", |
| 8371 | Some("turn_fixture"), |
| 8372 | "2026-08-08T12:00:00Z".to_string(), |
| 8373 | json!({ "kind": "agent_message", "delta": "exact 🫧 body" }), |
| 8374 | ); |
| 8375 | let terminal = runtime_envelope( |
| 8376 | 2, |
| 8377 | "turn.completed", |
| 8378 | Some("turn_fixture"), |
| 8379 | "2026-08-08T12:00:01Z".to_string(), |
| 8380 | json!({ "turn": { "status": "completed", "usage": {} } }), |
| 8381 | ); |
| 8382 | let mut pending: HashMap<String, BTreeMap<u64, PendingRuntimeEnvelope>> = HashMap::new(); |
| 8383 | let mut events = BTreeMap::new(); |
| 8384 | for envelope in [delta.clone(), terminal.clone()] { |
| 8385 | let seq = runtime_envelope_seq(&envelope).unwrap(); |
| 8386 | let encoded_len = serde_json::to_vec(&envelope).unwrap().len(); |
| 8387 | let integrity = runtime_envelope_event(&envelope).is_some_and(integrity_critical_event); |
| 8388 | events.insert( |
| 8389 | seq, |
| 8390 | PendingRuntimeEnvelope { |
| 8391 | envelope, |
| 8392 | encoded_len, |
| 8393 | integrity, |
| 8394 | handed_off: true, |
| 8395 | }, |
| 8396 | ); |
| 8397 | } |
| 8398 | pending.insert("run_fixture".to_string(), events); |
| 8399 | journal.persist(&pending).expect("atomic persist"); |
| 8400 | drop(journal); |
| 8401 | |
| 8402 | let reopened = |
| 8403 | RuntimeEventJournal::open(dir.path(), "target:fixture@01", "session:fixture@01") |
| 8404 | .expect("journal reopen"); |
| 8405 | let restored = reopened.load().expect("verified load"); |
| 8406 | let events = restored.get("run_fixture").expect("restored run"); |
| 8407 | assert_eq!(events.len(), 2); |
| 8408 | assert_eq!( |
| 8409 | serde_json::to_vec(&events[&1]).unwrap(), |
| 8410 | serde_json::to_vec(&delta).unwrap(), |
| 8411 | "a restored envelope must re-serialize byte-identically for ambiguous retries" |
| 8412 | ); |
| 8413 | assert_eq!( |
| 8414 | serde_json::to_vec(&events[&2]).unwrap(), |
| 8415 | serde_json::to_vec(&terminal).unwrap() |
| 8416 | ); |
| 8417 | |
| 8418 | // Compaction: an empty pending set removes the file entirely. |
| 8419 | pending.get_mut("run_fixture").unwrap().clear(); |
| 8420 | reopened.persist(&pending).expect("compacting persist"); |
| 8421 | assert!(!reopened.path.exists(), "acknowledged journals are deleted"); |
| 8422 | } |
| 8423 | |
| 8424 | #[test] |
| 8425 | fn legacy_session_only_journal_is_preserved_and_repeated_starts_fail_closed() { |
| 8426 | let dir = tempfile::tempdir().expect("journal tempdir"); |
| 8427 | let session_id = "session_legacy_shared"; |
| 8428 | let journal_a = RuntimeEventJournal::open(dir.path(), "target_a", session_id).unwrap(); |
| 8429 | let mut hasher = Sha256::new(); |
| 8430 | hasher.update(b"cwc-remote-control-journal\0"); |
| 8431 | hasher.update(session_id.as_bytes()); |
| 8432 | let session_tag = bytes_to_hex(&hasher.finalize())[..32].to_string(); |
| 8433 | assert_eq!( |
| 8434 | journal_a.legacy_path, |
| 8435 | dir.path().join(format!("journal_{session_tag}.json")) |
| 8436 | ); |
| 8437 | let envelope = runtime_envelope( |
| 8438 | 1, |
| 8439 | "turn.completed", |
| 8440 | Some("turn_legacy"), |
| 8441 | "2026-08-08T12:00:00Z".to_string(), |
| 8442 | json!({ "turn": { "status": "completed" } }), |
| 8443 | ); |
| 8444 | codewhale_util::utils::write_atomic( |
| 8445 | &journal_a.legacy_path, |
| 8446 | &serde_json::to_vec(&json!({ |
| 8447 | "schemaVersion": 1, |
| 8448 | "session": session_tag, |
| 8449 | "runs": { "run_legacy": [envelope] }, |
| 8450 | })) |
| 8451 | .unwrap(), |
| 8452 | ) |
| 8453 | .unwrap(); |
| 8454 | |
| 8455 | assert_eq!(journal_a.load().unwrap_err(), JOURNAL_LEGACY_SCOPE_ERROR); |
| 8456 | journal_a.quarantine_legacy(); |
| 8457 | let unscoped_path = journal_a.legacy_unscoped_path.clone(); |
| 8458 | assert!(unscoped_path.exists()); |
| 8459 | assert!(!journal_a.path.exists()); |
| 8460 | drop(journal_a); |
| 8461 | |
| 8462 | let retry_a = RuntimeEventJournal::open(dir.path(), "target_a", session_id).unwrap(); |
| 8463 | assert_eq!(retry_a.load().unwrap_err(), JOURNAL_LEGACY_SCOPE_ERROR); |
| 8464 | drop(retry_a); |
| 8465 | assert_eq!( |
| 8466 | RuntimeEventJournal::open(dir.path(), "target_b", session_id) |
| 8467 | .err() |
| 8468 | .expect("the legacy session remains permanently bound to target A"), |
| 8469 | CLASSIC_LEASE_SCOPE_ERROR |
| 8470 | ); |
| 8471 | assert!(unscoped_path.exists()); |
| 8472 | } |
| 8473 | |
| 8474 | #[test] |
| 8475 | fn corrupt_v2_quarantine_never_moves_an_unrelated_legacy_journal() { |
| 8476 | let dir = tempfile::tempdir().expect("journal tempdir"); |
| 8477 | let journal = RuntimeEventJournal::open(dir.path(), "target_b", "session_shared").unwrap(); |
| 8478 | codewhale_util::utils::write_atomic( |
| 8479 | &journal.legacy_path, |
| 8480 | b"legacy target A recovery material", |
| 8481 | ) |
| 8482 | .unwrap(); |
| 8483 | codewhale_util::utils::write_atomic(&journal.path, b"{not-json").unwrap(); |
| 8484 | assert_eq!(journal.load().unwrap_err(), JOURNAL_UNTRUSTED_ERROR); |
| 8485 | journal.quarantine_current(); |
| 8486 | assert!(journal.legacy_path.exists()); |
| 8487 | assert!(!journal.legacy_unscoped_path.exists()); |
| 8488 | assert!(journal.path.with_extension("corrupt").exists()); |
| 8489 | } |
| 8490 | |
| 8491 | #[test] |
| 8492 | fn runtime_chat_projection_is_not_handed_off_before_durable_journal_write() { |
| 8493 | let dir = tempfile::tempdir().expect("journal tempdir"); |
| 8494 | let journal = |
| 8495 | RuntimeEventJournal::open(dir.path(), "target:fixture@01", "session:fixture@01") |
| 8496 | .expect("journal setup"); |
| 8497 | let journal_path = journal.path.clone(); |
| 8498 | let mut controller = RemoteControlController::default(); |
| 8499 | let (worker_tx, mut worker_rx) = mpsc::unbounded_channel(); |
| 8500 | controller.worker_tx = Some(worker_tx); |
| 8501 | controller.journal = Some(journal); |
| 8502 | let envelope = runtime_chat_envelope( |
| 8503 | 1, |
| 8504 | "turn.completed", |
| 8505 | Some("local_thread_aaaaaaaaaaaaaaaaaaaaaaaa"), |
| 8506 | Some("local_turn_bbbbbbbbbbbbbbbbbbbbbbbb"), |
| 8507 | Some("native_event_fixture"), |
| 8508 | RUNTIME_CHAT_CATALOG_TIMESTAMP.to_string(), |
| 8509 | json!({ "turn": { "status": "completed" } }), |
| 8510 | ); |
| 8511 | |
| 8512 | inject_journal_persist_failures(&journal_path, 1); |
| 8513 | assert!( |
| 8514 | !controller.queue_runtime_chat_envelope("run_fixture", envelope.clone()), |
| 8515 | "a failed durable append must reject native cursor advancement" |
| 8516 | ); |
| 8517 | assert!(controller.pending_runtime_events.is_empty()); |
| 8518 | assert!(!controller.event_seq.contains_key("run_fixture")); |
| 8519 | assert!(worker_rx.try_recv().is_err()); |
| 8520 | |
| 8521 | assert!(controller.queue_runtime_chat_envelope("run_fixture", envelope)); |
| 8522 | assert!(journal_path.exists()); |
| 8523 | let WorkerCommand::Upload { envelopes, .. } = worker_rx.try_recv().unwrap() else { |
| 8524 | panic!("durable retry must hand off the exact projection"); |
| 8525 | }; |
| 8526 | assert_eq!(envelopes[0]["seq"], 1); |
| 8527 | } |
| 8528 | |
| 8529 | #[test] |
| 8530 | fn classic_terminal_journal_failure_stays_retained_and_fail_closed_until_cursor() { |
| 8531 | let (mut controller, mut worker_rx, _event_tx, _journal_root) = wired_controller(); |
| 8532 | controller.status = Status::Connected; |
| 8533 | controller |
| 8534 | .activate_prompt("run_fixture", "turn_fixture") |
| 8535 | .unwrap(); |
| 8536 | let journal_path = controller.journal.as_ref().unwrap().path.clone(); |
| 8537 | inject_journal_persist_failures(&journal_path, 2); |
| 8538 | |
| 8539 | controller.observe_engine_event(&turn_complete_event()); |
| 8540 | assert_eq!(controller.status, Status::Failed); |
| 8541 | assert!(worker_rx.try_recv().is_err(), "failed append must not send"); |
| 8542 | assert!( |
| 8543 | controller.has_unacknowledged_integrity_events(), |
| 8544 | "classic terminal must remain retryable in memory" |
| 8545 | ); |
| 8546 | assert!(controller.stop_refusal().is_some()); |
| 8547 | controller.ownership_blocked_until = Some(Instant::now() - Duration::from_millis(1)); |
| 8548 | assert!(controller.try_next_event().is_none()); |
| 8549 | assert_eq!( |
| 8550 | controller.status, |
| 8551 | Status::Failed, |
| 8552 | "lease expiry cannot discard an unacknowledged classic terminal" |
| 8553 | ); |
| 8554 | |
| 8555 | controller |
| 8556 | .journal |
| 8557 | .as_ref() |
| 8558 | .unwrap() |
| 8559 | .persist(&controller.pending_runtime_events) |
| 8560 | .expect("repair durable journal"); |
| 8561 | let (worker_tx, mut repaired_worker_rx) = mpsc::unbounded_channel(); |
| 8562 | controller.worker_tx = Some(worker_tx); |
| 8563 | controller.flush_pending_runtime_events("run_fixture"); |
| 8564 | let WorkerCommand::Upload { envelopes, .. } = repaired_worker_rx.try_recv().unwrap() else { |
| 8565 | panic!("repaired terminal must be handed off"); |
| 8566 | }; |
| 8567 | let seq = runtime_envelope_seq(&envelopes[0]).unwrap(); |
| 8568 | controller.reconcile_runtime_cursor("run_fixture", seq); |
| 8569 | assert!(!controller.has_unacknowledged_integrity_events()); |
| 8570 | } |
| 8571 | |
| 8572 | #[test] |
| 8573 | fn classic_worker_failure_retains_live_turn_until_exact_terminal_is_durable() { |
| 8574 | let (mut controller, _worker_rx, event_tx, _journal_root) = wired_controller(); |
| 8575 | controller.status = Status::Connected; |
| 8576 | controller |
| 8577 | .activate_prompt("run_fixture", "turn_fixture") |
| 8578 | .unwrap(); |
| 8579 | event_tx |
| 8580 | .send(RemoteEvent::Failed("fixture transport loss".to_string())) |
| 8581 | .unwrap(); |
| 8582 | assert!(matches!( |
| 8583 | controller.try_next_event(), |
| 8584 | Some(RemoteEvent::Failed(_)) |
| 8585 | )); |
| 8586 | assert!(controller.has_active_run()); |
| 8587 | assert!(controller.has_durable_classic_lease()); |
| 8588 | |
| 8589 | controller.ownership_blocked_until = Some(Instant::now() - Duration::from_millis(1)); |
| 8590 | assert!(controller.try_next_event().is_none()); |
| 8591 | assert_eq!(controller.status, Status::Failed); |
| 8592 | assert!(controller.has_active_run()); |
| 8593 | assert!(controller.start(fixture_start()).is_err()); |
| 8594 | |
| 8595 | let usage = codewhale_models::Usage { |
| 8596 | input_tokens: 17, |
| 8597 | output_tokens: 5, |
| 8598 | ..codewhale_models::Usage::default() |
| 8599 | }; |
| 8600 | controller.observe_engine_event(&EngineEvent::TurnComplete { |
| 8601 | source_accounting: false, |
| 8602 | |
| 8603 | turn_id: None, |
| 8604 | submission_id: None, |
| 8605 | compaction_id: None, |
| 8606 | usage: usage.clone(), |
| 8607 | parent_route_usage: usage.clone(), |
| 8608 | routed_usage_dropped_records: 0, |
| 8609 | status: TurnOutcomeStatus::Completed, |
| 8610 | error: None, |
| 8611 | tool_catalog: None, |
| 8612 | base_url: None, |
| 8613 | }); |
| 8614 | assert!(!controller.has_active_run()); |
| 8615 | assert!(!controller.has_durable_classic_lease()); |
| 8616 | let terminals: Vec<&PendingRuntimeEnvelope> = |
| 8617 | controller.pending_runtime_events["run_fixture"] |
| 8618 | .values() |
| 8619 | .filter(|entry| runtime_envelope_event(&entry.envelope) == Some("turn.completed")) |
| 8620 | .collect(); |
| 8621 | assert_eq!(terminals.len(), 1); |
| 8622 | assert_eq!( |
| 8623 | terminals[0].envelope["payload"]["turn"]["usage"], |
| 8624 | serde_json::to_value(usage).unwrap() |
| 8625 | ); |
| 8626 | } |
| 8627 | |
| 8628 | #[test] |
| 8629 | fn classic_recovery_uses_persisted_seq_floor_and_ignores_older_terminal() { |
| 8630 | let root = tempfile::tempdir().unwrap(); |
| 8631 | let old_terminal = runtime_envelope( |
| 8632 | 40, |
| 8633 | "turn.completed", |
| 8634 | Some("turn_floor_fixture"), |
| 8635 | "2026-08-08T12:00:00Z".to_string(), |
| 8636 | json!({ "turn": { "status": "completed", "usage": {} } }), |
| 8637 | ); |
| 8638 | { |
| 8639 | let mut first = RemoteControlController::default(); |
| 8640 | first.journal = Some( |
| 8641 | RuntimeEventJournal::open(root.path(), "target_floor", "session_floor").unwrap(), |
| 8642 | ); |
| 8643 | first.reset_pending_from(HashMap::from([( |
| 8644 | "run_floor".to_string(), |
| 8645 | BTreeMap::from([(40, old_terminal.clone())]), |
| 8646 | )])); |
| 8647 | first.event_seq.insert("run_floor".to_string(), 41); |
| 8648 | first |
| 8649 | .activate_prompt("run_floor", "turn_floor_fixture") |
| 8650 | .unwrap(); |
| 8651 | assert_eq!( |
| 8652 | first |
| 8653 | .journal |
| 8654 | .as_ref() |
| 8655 | .unwrap() |
| 8656 | .classic_lease() |
| 8657 | .unwrap() |
| 8658 | .seq_floor, |
| 8659 | 41 |
| 8660 | ); |
| 8661 | } |
| 8662 | |
| 8663 | let mut reopened = RemoteControlController::default(); |
| 8664 | let journal = |
| 8665 | RuntimeEventJournal::open(root.path(), "target_floor", "session_floor").unwrap(); |
| 8666 | reopened.reset_pending_from(journal.load().unwrap()); |
| 8667 | reopened.journal = Some(journal); |
| 8668 | reopened.recover_classic_lease_before_worker().unwrap(); |
| 8669 | |
| 8670 | let events = &reopened.pending_runtime_events["run_floor"]; |
| 8671 | assert!(events.contains_key(&40)); |
| 8672 | let recovered = events.get(&42).expect("recovery follows the durable floor"); |
| 8673 | assert_eq!( |
| 8674 | runtime_envelope_event(&recovered.envelope), |
| 8675 | Some("turn.completed") |
| 8676 | ); |
| 8677 | assert_eq!(recovered.envelope["turn_id"], "turn_floor_fixture"); |
| 8678 | assert_eq!(recovered.envelope["payload"]["turn"]["status"], "failed"); |
| 8679 | assert!(!reopened.has_durable_classic_lease()); |
| 8680 | } |
| 8681 | |
| 8682 | #[test] |
| 8683 | fn blank_predispatch_lease_id_always_starts_a_fresh_generation() { |
| 8684 | let root = tempfile::tempdir().unwrap(); |
| 8685 | let mut controller = RemoteControlController::default(); |
| 8686 | controller.journal = Some( |
| 8687 | RuntimeEventJournal::open(root.path(), "target_generation", "session_generation") |
| 8688 | .unwrap(), |
| 8689 | ); |
| 8690 | controller |
| 8691 | .begin_classic_lease(ClassicRunLease { |
| 8692 | run_id: "run_generation".to_string(), |
| 8693 | turn_id: None, |
| 8694 | lease_id: String::new(), |
| 8695 | seq_floor: 0, |
| 8696 | }) |
| 8697 | .unwrap(); |
| 8698 | let stale_lease = controller |
| 8699 | .journal |
| 8700 | .as_ref() |
| 8701 | .and_then(RuntimeEventJournal::classic_lease) |
| 8702 | .unwrap(); |
| 8703 | |
| 8704 | controller |
| 8705 | .begin_classic_lease(ClassicRunLease { |
| 8706 | run_id: "run_generation".to_string(), |
| 8707 | turn_id: None, |
| 8708 | lease_id: String::new(), |
| 8709 | seq_floor: 0, |
| 8710 | }) |
| 8711 | .unwrap(); |
| 8712 | let fresh_lease = controller |
| 8713 | .journal |
| 8714 | .as_ref() |
| 8715 | .and_then(RuntimeEventJournal::classic_lease) |
| 8716 | .unwrap(); |
| 8717 | |
| 8718 | assert_ne!( |
| 8719 | fresh_lease.lease_id, stale_lease.lease_id, |
| 8720 | "a stale empty-turn lease cannot define the next recovery identity" |
| 8721 | ); |
| 8722 | } |
| 8723 | |
| 8724 | #[test] |
| 8725 | fn separate_predispatch_crashes_on_one_run_get_distinct_recovery_turn_ids() { |
| 8726 | let root = tempfile::tempdir().unwrap(); |
| 8727 | let first_recovery_turn; |
| 8728 | { |
| 8729 | let mut first = RemoteControlController::default(); |
| 8730 | first.journal = Some( |
| 8731 | RuntimeEventJournal::open(root.path(), "target_generation", "session_generation") |
| 8732 | .unwrap(), |
| 8733 | ); |
| 8734 | first |
| 8735 | .begin_classic_lease(ClassicRunLease { |
| 8736 | run_id: "run_generation".to_string(), |
| 8737 | turn_id: None, |
| 8738 | lease_id: String::new(), |
| 8739 | seq_floor: 0, |
| 8740 | }) |
| 8741 | .unwrap(); |
| 8742 | } |
| 8743 | { |
| 8744 | let mut recovered = RemoteControlController::default(); |
| 8745 | let journal = |
| 8746 | RuntimeEventJournal::open(root.path(), "target_generation", "session_generation") |
| 8747 | .unwrap(); |
| 8748 | recovered.reset_pending_from(journal.load().unwrap()); |
| 8749 | recovered.journal = Some(journal); |
| 8750 | recovered.recover_classic_lease_before_worker().unwrap(); |
| 8751 | first_recovery_turn = |
| 8752 | recovered.pending_runtime_events["run_generation"][&1].envelope["turn_id"] |
| 8753 | .as_str() |
| 8754 | .unwrap() |
| 8755 | .to_string(); |
| 8756 | recovered.reconcile_runtime_cursor("run_generation", 1); |
| 8757 | recovered |
| 8758 | .begin_classic_lease(ClassicRunLease { |
| 8759 | run_id: "run_generation".to_string(), |
| 8760 | turn_id: None, |
| 8761 | lease_id: String::new(), |
| 8762 | seq_floor: recovered.runtime_seq_floor("run_generation"), |
| 8763 | }) |
| 8764 | .unwrap(); |
| 8765 | } |
| 8766 | let mut recovered_again = RemoteControlController::default(); |
| 8767 | let journal = |
| 8768 | RuntimeEventJournal::open(root.path(), "target_generation", "session_generation") |
| 8769 | .unwrap(); |
| 8770 | recovered_again.reset_pending_from(journal.load().unwrap()); |
| 8771 | recovered_again.journal = Some(journal); |
| 8772 | recovered_again |
| 8773 | .recover_classic_lease_before_worker() |
| 8774 | .unwrap(); |
| 8775 | let second_recovery_turn = recovered_again.pending_runtime_events["run_generation"][&2] |
| 8776 | .envelope["turn_id"] |
| 8777 | .as_str() |
| 8778 | .unwrap(); |
| 8779 | assert_ne!(first_recovery_turn, second_recovery_turn); |
| 8780 | } |
| 8781 | |
| 8782 | /// #6698: a process spawned between fork and exec while a journal is open |
| 8783 | /// holds a duplicate of the lock descriptor. Dropping the journal must |
| 8784 | /// still release the session lock, or the next same-process reopen fails |
| 8785 | /// with the unfinished-account-turn error. |
| 8786 | #[cfg(unix)] |
| 8787 | #[test] |
| 8788 | fn classic_session_lock_releases_while_a_duplicated_descriptor_survives() { |
| 8789 | let root = tempfile::tempdir().unwrap(); |
| 8790 | let path = root.path().join("active_classic_fixture.lock"); |
| 8791 | let lock = ClassicSessionOwnerLock::acquire(&path).unwrap(); |
| 8792 | let inherited = lock._file.try_clone().unwrap(); |
| 8793 | drop(lock); |
| 8794 | let reopened = ClassicSessionOwnerLock::acquire(&path) |
| 8795 | .expect("dropping the owner releases the lock despite a surviving duplicate"); |
| 8796 | drop(reopened); |
| 8797 | drop(inherited); |
| 8798 | } |
| 8799 | |
| 8800 | #[test] |
| 8801 | fn classic_terminal_cursor_repairs_failed_canonical_clear_before_compaction() { |
| 8802 | let (mut controller, _worker_rx, _event_tx, journal_root) = wired_controller(); |
| 8803 | controller.status = Status::Connected; |
| 8804 | controller |
| 8805 | .activate_prompt("run_fixture", "turn_fixture") |
| 8806 | .unwrap(); |
| 8807 | let state_path = controller |
| 8808 | .journal |
| 8809 | .as_ref() |
| 8810 | .unwrap() |
| 8811 | .active_index_path |
| 8812 | .clone(); |
| 8813 | inject_journal_persist_failures(&state_path, 1); |
| 8814 | |
| 8815 | controller.observe_engine_event(&turn_complete_event()); |
| 8816 | assert!(controller.has_durable_classic_lease()); |
| 8817 | assert!(controller.has_active_run()); |
| 8818 | let terminal_seq = *controller.pending_runtime_events["run_fixture"] |
| 8819 | .last_key_value() |
| 8820 | .unwrap() |
| 8821 | .0; |
| 8822 | controller.reconcile_runtime_cursor("run_fixture", terminal_seq); |
| 8823 | assert!(!controller.has_durable_classic_lease()); |
| 8824 | assert!(!controller.has_active_run()); |
| 8825 | assert!(controller.pending_runtime_events.is_empty()); |
| 8826 | drop(controller); |
| 8827 | |
| 8828 | let journal = RuntimeEventJournal::open( |
| 8829 | journal_root.path(), |
| 8830 | "target_wired_fixture", |
| 8831 | "session_wired_fixture", |
| 8832 | ) |
| 8833 | .unwrap(); |
| 8834 | assert!(journal.classic_lease().is_none()); |
| 8835 | assert!(journal.load().unwrap().is_empty()); |
| 8836 | } |
| 8837 | |
| 8838 | #[test] |
| 8839 | fn classic_lease_persist_failure_does_not_advance_active_index_and_surfaces_rollback_failure() { |
| 8840 | let (mut controller, _worker_rx, _event_tx, journal_root) = wired_controller(); |
| 8841 | controller.status = Status::Connected; |
| 8842 | let journal_path = controller.journal.as_ref().unwrap().path.clone(); |
| 8843 | let active_index_path = controller |
| 8844 | .journal |
| 8845 | .as_ref() |
| 8846 | .unwrap() |
| 8847 | .active_index_path |
| 8848 | .clone(); |
| 8849 | inject_journal_persist_failures(&journal_path, 1); |
| 8850 | inject_journal_persist_failures(&active_index_path, 1); |
| 8851 | |
| 8852 | let err = controller |
| 8853 | .begin_classic_lease(ClassicRunLease { |
| 8854 | run_id: "run_fixture".to_string(), |
| 8855 | turn_id: Some("turn_fixture".to_string()), |
| 8856 | lease_id: String::new(), |
| 8857 | seq_floor: 0, |
| 8858 | }) |
| 8859 | .unwrap_err(); |
| 8860 | assert_eq!(err, JOURNAL_SETUP_ERROR); |
| 8861 | assert_eq!(controller.status, Status::Failed); |
| 8862 | assert!(!controller.has_durable_classic_lease()); |
| 8863 | assert!( |
| 8864 | !take_journal_persist_failure(&journal_path), |
| 8865 | "journal persist must fail before active_index is touched" |
| 8866 | ); |
| 8867 | assert!( |
| 8868 | take_journal_persist_failure(&active_index_path), |
| 8869 | "active_index write must not be attempted after persist fails" |
| 8870 | ); |
| 8871 | assert!( |
| 8872 | controller |
| 8873 | .journal |
| 8874 | .as_ref() |
| 8875 | .unwrap() |
| 8876 | .read_active_index() |
| 8877 | .unwrap() |
| 8878 | .is_none() |
| 8879 | ); |
| 8880 | drop(controller); |
| 8881 | |
| 8882 | let reopened = RuntimeEventJournal::open( |
| 8883 | journal_root.path(), |
| 8884 | "target_wired_fixture", |
| 8885 | "session_wired_fixture", |
| 8886 | ) |
| 8887 | .unwrap(); |
| 8888 | assert!(reopened.classic_lease().is_none()); |
| 8889 | } |
| 8890 | |
| 8891 | #[test] |
| 8892 | fn classic_lease_active_index_rollback_failure_is_surfaced_in_status_detail() { |
| 8893 | let (mut controller, _worker_rx, _event_tx, _journal_root) = wired_controller(); |
| 8894 | controller.status = Status::Connected; |
| 8895 | controller |
| 8896 | .activate_prompt("run_fixture", "turn_fixture") |
| 8897 | .unwrap(); |
| 8898 | let active_index_path = controller |
| 8899 | .journal |
| 8900 | .as_ref() |
| 8901 | .unwrap() |
| 8902 | .active_index_path |
| 8903 | .clone(); |
| 8904 | inject_journal_persist_failures(&active_index_path, 2); |
| 8905 | |
| 8906 | let err = controller.finish_classic_lease().unwrap_err(); |
| 8907 | assert_eq!(controller.status, Status::Failed); |
| 8908 | assert_eq!(controller.status_detail, err); |
| 8909 | assert!( |
| 8910 | controller.status_detail.contains("rollback"), |
| 8911 | "status_detail must surface rollback failure: {}", |
| 8912 | controller.status_detail |
| 8913 | ); |
| 8914 | assert!(controller.has_durable_classic_lease()); |
| 8915 | } |
| 8916 | |
| 8917 | #[test] |
| 8918 | fn classic_lease_active_index_failure_rolls_back_persisted_journal() { |
| 8919 | let (mut controller, _worker_rx, _event_tx, journal_root) = wired_controller(); |
| 8920 | controller.status = Status::Connected; |
| 8921 | controller |
| 8922 | .activate_prompt("run_fixture", "turn_fixture") |
| 8923 | .unwrap(); |
| 8924 | let active_index_path = controller |
| 8925 | .journal |
| 8926 | .as_ref() |
| 8927 | .unwrap() |
| 8928 | .active_index_path |
| 8929 | .clone(); |
| 8930 | inject_journal_persist_failures(&active_index_path, 1); |
| 8931 | |
| 8932 | let err = controller.finish_classic_lease().unwrap_err(); |
| 8933 | assert_eq!(err, JOURNAL_SETUP_ERROR); |
| 8934 | assert_eq!(controller.status, Status::Failed); |
| 8935 | assert!(controller.has_durable_classic_lease()); |
| 8936 | drop(controller); |
| 8937 | |
| 8938 | let reopened = RuntimeEventJournal::open( |
| 8939 | journal_root.path(), |
| 8940 | "target_wired_fixture", |
| 8941 | "session_wired_fixture", |
| 8942 | ) |
| 8943 | .unwrap(); |
| 8944 | assert_eq!( |
| 8945 | reopened |
| 8946 | .classic_lease() |
| 8947 | .as_ref() |
| 8948 | .map(|lease| lease.run_id.as_str()), |
| 8949 | Some("run_fixture"), |
| 8950 | "on-disk journal must be rolled back to previous lease when active_index write fails" |
| 8951 | ); |
| 8952 | assert_eq!( |
| 8953 | reopened |
| 8954 | .read_active_index() |
| 8955 | .unwrap() |
| 8956 | .as_ref() |
| 8957 | .map(|lease| lease.run_id.as_str()), |
| 8958 | Some("run_fixture") |
| 8959 | ); |
| 8960 | } |
| 8961 | |
| 8962 | #[test] |
| 8963 | fn saved_session_is_permanently_bound_to_its_first_remote_target() { |
| 8964 | let dir = tempfile::tempdir().expect("journal tempdir"); |
| 8965 | let first = RuntimeEventJournal::open(dir.path(), "target_a", "session_shared") |
| 8966 | .expect("first target journal"); |
| 8967 | assert_eq!( |
| 8968 | RuntimeEventJournal::open(dir.path(), "target_b", "session_shared") |
| 8969 | .err() |
| 8970 | .expect("a second target must fail closed"), |
| 8971 | CLASSIC_LEASE_SCOPE_ERROR |
| 8972 | ); |
| 8973 | |
| 8974 | let pending_for = |run_id: &str, marker: &str| { |
| 8975 | let envelope = runtime_envelope( |
| 8976 | 1, |
| 8977 | "turn.completed", |
| 8978 | None, |
| 8979 | "2026-08-08T12:00:00Z".to_string(), |
| 8980 | json!({ "turn": { "status": "completed" }, "marker": marker }), |
| 8981 | ); |
| 8982 | let encoded_len = serde_json::to_vec(&envelope).unwrap().len(); |
| 8983 | HashMap::from([( |
| 8984 | run_id.to_string(), |
| 8985 | BTreeMap::from([( |
| 8986 | 1, |
| 8987 | PendingRuntimeEnvelope { |
| 8988 | envelope, |
| 8989 | encoded_len, |
| 8990 | integrity: true, |
| 8991 | handed_off: true, |
| 8992 | }, |
| 8993 | )]), |
| 8994 | )]) |
| 8995 | }; |
| 8996 | first.persist(&pending_for("run_a", "a")).unwrap(); |
| 8997 | assert_eq!( |
| 8998 | first.load().unwrap().keys().collect::<Vec<_>>(), |
| 8999 | vec!["run_a"] |
| 9000 | ); |
| 9001 | drop(first); |
| 9002 | assert_eq!( |
| 9003 | RuntimeEventJournal::open(dir.path(), "target_b", "session_shared") |
| 9004 | .err() |
| 9005 | .expect("the permanent target binding must fail closed"), |
| 9006 | CLASSIC_LEASE_SCOPE_ERROR, |
| 9007 | "the target binding survives terminal settlement and process restart" |
| 9008 | ); |
| 9009 | RuntimeEventJournal::open(dir.path(), "target_a", "session_shared") |
| 9010 | .expect("the original target can reopen its saved session"); |
| 9011 | } |
| 9012 | |
| 9013 | #[cfg(unix)] |
| 9014 | #[test] |
| 9015 | fn journal_directory_and_file_are_owner_only() { |
| 9016 | use std::os::unix::fs::PermissionsExt; |
| 9017 | let base = tempfile::tempdir().expect("journal tempdir"); |
| 9018 | let dir = base.path().join("journal"); |
| 9019 | let journal = RuntimeEventJournal::open(&dir, "target:fixture@01", "session:fixture@01") |
| 9020 | .expect("journal setup"); |
| 9021 | let mut pending: HashMap<String, BTreeMap<u64, PendingRuntimeEnvelope>> = HashMap::new(); |
| 9022 | let envelope = runtime_envelope( |
| 9023 | 1, |
| 9024 | "turn.completed", |
| 9025 | None, |
| 9026 | "2026-08-08T12:00:00Z".to_string(), |
| 9027 | json!({ "turn": { "status": "completed", "usage": {} } }), |
| 9028 | ); |
| 9029 | let encoded_len = serde_json::to_vec(&envelope).unwrap().len(); |
| 9030 | pending.insert( |
| 9031 | "run_fixture".to_string(), |
| 9032 | BTreeMap::from([( |
| 9033 | 1, |
| 9034 | PendingRuntimeEnvelope { |
| 9035 | envelope, |
| 9036 | encoded_len, |
| 9037 | integrity: true, |
| 9038 | handed_off: true, |
| 9039 | }, |
| 9040 | )]), |
| 9041 | ); |
| 9042 | journal.persist(&pending).expect("atomic persist"); |
| 9043 | let dir_mode = std::fs::metadata(&dir).unwrap().permissions().mode() & 0o777; |
| 9044 | assert_eq!(dir_mode, 0o700, "journal directory must be private"); |
| 9045 | let file_mode = std::fs::metadata(&journal.path) |
| 9046 | .unwrap() |
| 9047 | .permissions() |
| 9048 | .mode() |
| 9049 | & 0o777; |
| 9050 | assert_eq!(file_mode, 0o600, "journal file must be owner-only"); |
| 9051 | } |
| 9052 | |
| 9053 | #[test] |
| 9054 | fn corrupt_journal_fails_closed_and_start_quarantines_it() { |
| 9055 | let dir = tempfile::tempdir().expect("journal tempdir"); |
| 9056 | let probe = RuntimeEventJournal::open(dir.path(), "target_fixture", "session:fixture@01") |
| 9057 | .expect("journal setup"); |
| 9058 | std::fs::write(&probe.path, b"{ not json").expect("plant corrupt journal"); |
| 9059 | let corrupt_path = probe.path.clone(); |
| 9060 | drop(probe); |
| 9061 | |
| 9062 | let mut controller = RemoteControlController::default(); |
| 9063 | let error = controller |
| 9064 | .start(RemoteStart { |
| 9065 | journal_dir: Some(dir.path().to_path_buf()), |
| 9066 | ..fixture_start() |
| 9067 | }) |
| 9068 | .expect_err("a corrupt journal must fail closed"); |
| 9069 | assert_eq!(error, JOURNAL_UNTRUSTED_ERROR); |
| 9070 | assert_eq!(controller.status, Status::Failed); |
| 9071 | assert!(controller.status_line().contains(&error)); |
| 9072 | assert!(controller.worker.is_none(), "no relay may start"); |
| 9073 | assert!( |
| 9074 | !corrupt_path.exists(), |
| 9075 | "the untrusted journal must not stay in place" |
| 9076 | ); |
| 9077 | assert!( |
| 9078 | corrupt_path.with_extension("corrupt").exists(), |
| 9079 | "the untrusted journal is quarantined, not silently discarded" |
| 9080 | ); |
| 9081 | |
| 9082 | // A mismatched session tag is equally untrusted. |
| 9083 | let other = |
| 9084 | RuntimeEventJournal::open(dir.path(), "target:fixture@01", "session:fixture@02") |
| 9085 | .expect("journal setup"); |
| 9086 | std::fs::write( |
| 9087 | &other.path, |
| 9088 | serde_json::to_vec(&json!({ |
| 9089 | "schemaVersion": JOURNAL_SCHEMA_VERSION, |
| 9090 | "scope": "00000000000000000000000000000000", |
| 9091 | "runs": {}, |
| 9092 | })) |
| 9093 | .unwrap(), |
| 9094 | ) |
| 9095 | .expect("plant mismatched journal"); |
| 9096 | assert_eq!(other.load().unwrap_err(), JOURNAL_UNTRUSTED_ERROR); |
| 9097 | } |
| 9098 | |
| 9099 | #[test] |
| 9100 | fn start_recovers_journaled_envelopes_and_resends_on_connect() { |
| 9101 | let dir = tempfile::tempdir().expect("journal tempdir"); |
| 9102 | { |
| 9103 | let journal = |
| 9104 | RuntimeEventJournal::open(dir.path(), "target:fixture@01", "session:fixture@01") |
| 9105 | .expect("journal setup"); |
| 9106 | let envelope = runtime_envelope( |
| 9107 | 3, |
| 9108 | "turn.completed", |
| 9109 | Some("turn_fixture"), |
| 9110 | "2026-08-08T12:00:00Z".to_string(), |
| 9111 | json!({ "turn": { "status": "completed", "usage": {} } }), |
| 9112 | ); |
| 9113 | let encoded_len = serde_json::to_vec(&envelope).unwrap().len(); |
| 9114 | let pending = HashMap::from([( |
| 9115 | "run_fixture".to_string(), |
| 9116 | BTreeMap::from([( |
| 9117 | 3, |
| 9118 | PendingRuntimeEnvelope { |
| 9119 | envelope, |
| 9120 | encoded_len, |
| 9121 | integrity: true, |
| 9122 | handed_off: true, |
| 9123 | }, |
| 9124 | )]), |
| 9125 | )]); |
| 9126 | journal |
| 9127 | .persist(&pending) |
| 9128 | .expect("previous process persisted"); |
| 9129 | } |
| 9130 | |
| 9131 | let mut controller = RemoteControlController::default(); |
| 9132 | let journal = |
| 9133 | RuntimeEventJournal::open(dir.path(), "target:fixture@01", "session:fixture@01") |
| 9134 | .expect("journal setup"); |
| 9135 | controller.reset_pending_from(journal.load().expect("clean recovery")); |
| 9136 | controller.journal = Some(journal); |
| 9137 | assert!( |
| 9138 | controller.has_unacknowledged_integrity_events(), |
| 9139 | "recovered terminal state must gate /rc stop until acknowledged" |
| 9140 | ); |
| 9141 | assert!(controller.stop_refusal().is_some()); |
| 9142 | |
| 9143 | let (worker_tx, mut worker_rx) = mpsc::unbounded_channel(); |
| 9144 | let (event_tx, event_rx) = mpsc::unbounded_channel(); |
| 9145 | controller.worker_tx = Some(worker_tx); |
| 9146 | controller.event_rx = Some(event_rx); |
| 9147 | event_tx |
| 9148 | .send(RemoteEvent::Connected { |
| 9149 | account_ref: "account_fixture".to_string(), |
| 9150 | runner_id: "runner_fixture".to_string(), |
| 9151 | target_ref: "target_fixture".to_string(), |
| 9152 | attachment: RemoteAttachment { |
| 9153 | run_id: "run_other".to_string(), |
| 9154 | workspace_id: "workspace_fixture".to_string(), |
| 9155 | runtime_cursor: 0, |
| 9156 | snapshot_present: false, |
| 9157 | runtime_chat_relay_protocol: RUNTIME_CHAT_RELAY_PROTOCOL.to_string(), |
| 9158 | runtime_chat_relay_challenge: "a".repeat(32), |
| 9159 | }, |
| 9160 | links: RemoteLinks::default(), |
| 9161 | }) |
| 9162 | .unwrap(); |
| 9163 | controller.try_next_event().unwrap(); |
| 9164 | let WorkerCommand::Upload { envelopes, .. } = worker_rx.try_recv().unwrap() else { |
| 9165 | panic!("recovered envelopes must resend on connect"); |
| 9166 | }; |
| 9167 | assert_eq!(envelopes[0]["seq"], 3); |
| 9168 | assert_eq!(envelopes[0]["event"], "turn.completed"); |
| 9169 | } |
| 9170 | |
| 9171 | #[test] |
| 9172 | fn delta_pressure_sheds_to_resync_and_preserves_integrity_capacity() { |
| 9173 | let (mut controller, _worker_rx, _event_tx, _journal_root) = wired_controller(); |
| 9174 | let delta_budget = MAX_JOURNAL_EVENTS - JOURNAL_RESERVED_INTEGRITY_EVENTS; |
| 9175 | for index in 0..delta_budget { |
| 9176 | assert!( |
| 9177 | controller.queue_runtime_envelope( |
| 9178 | "run_fixture", |
| 9179 | runtime_envelope( |
| 9180 | (index + 1) as u64, |
| 9181 | "item.delta", |
| 9182 | Some("turn_fixture"), |
| 9183 | "2026-08-08T12:00:00Z".to_string(), |
| 9184 | json!({ "kind": "agent_message", "delta": index.to_string() }), |
| 9185 | ), |
| 9186 | ), |
| 9187 | "delta {index} fits the unreserved budget" |
| 9188 | ); |
| 9189 | } |
| 9190 | assert_eq!(controller.pending_event_count, delta_budget); |
| 9191 | |
| 9192 | let shed_seq = (delta_budget + 1) as u64; |
| 9193 | assert!( |
| 9194 | !controller.queue_runtime_envelope( |
| 9195 | "run_fixture", |
| 9196 | runtime_envelope( |
| 9197 | shed_seq, |
| 9198 | "item.delta", |
| 9199 | Some("turn_fixture"), |
| 9200 | "2026-08-08T12:00:00Z".to_string(), |
| 9201 | json!({ "kind": "agent_message", "delta": "over budget" }), |
| 9202 | ), |
| 9203 | ), |
| 9204 | "a delta beyond the unreserved budget is shed" |
| 9205 | ); |
| 9206 | assert_eq!(controller.pending_event_count, delta_budget); |
| 9207 | assert!(controller.resync_required.contains("run_fixture")); |
| 9208 | assert_ne!( |
| 9209 | controller.status, |
| 9210 | Status::Failed, |
| 9211 | "delta pressure is ordinary and must not fail the relay" |
| 9212 | ); |
| 9213 | |
| 9214 | // Reserved capacity keeps the terminal boundary deliverable, and the |
| 9215 | // terminal boundary schedules the resynchronization snapshot. |
| 9216 | controller |
| 9217 | .activate_prompt("run_fixture", "turn_fixture") |
| 9218 | .unwrap(); |
| 9219 | controller.observe_engine_event(&turn_complete_event()); |
| 9220 | assert!( |
| 9221 | controller.has_unacknowledged_integrity_events(), |
| 9222 | "the terminal envelope must use the reserved capacity" |
| 9223 | ); |
| 9224 | assert_eq!( |
| 9225 | controller.take_pending_resync().as_deref(), |
| 9226 | Some("run_fixture"), |
| 9227 | "the shed run resynchronizes at its terminal boundary" |
| 9228 | ); |
| 9229 | controller.upload_resync_snapshot("run_fixture", &[]); |
| 9230 | assert!( |
| 9231 | controller |
| 9232 | .pending_runtime_events |
| 9233 | .get("run_fixture") |
| 9234 | .is_some_and(|events| events.values().any(|entry| runtime_envelope_event( |
| 9235 | &entry.envelope |
| 9236 | ) == Some("session.snapshot"))), |
| 9237 | "the bounded snapshot restores account truth" |
| 9238 | ); |
| 9239 | } |
| 9240 | |
| 9241 | #[test] |
| 9242 | fn integrity_overflow_fails_closed_without_restoring_input() { |
| 9243 | let (mut controller, _worker_rx, _event_tx, _journal_root) = wired_controller(); |
| 9244 | controller.status = Status::Connected; |
| 9245 | for index in 0..MAX_JOURNAL_EVENTS { |
| 9246 | assert!(controller.queue_runtime_envelope( |
| 9247 | "run_fixture", |
| 9248 | runtime_envelope( |
| 9249 | (index + 1) as u64, |
| 9250 | "item.failed", |
| 9251 | Some("turn_fixture"), |
| 9252 | "2026-08-08T12:00:00Z".to_string(), |
| 9253 | json!({ "item": { "id": index.to_string(), "kind": "error" } }), |
| 9254 | ), |
| 9255 | )); |
| 9256 | } |
| 9257 | |
| 9258 | assert!(!controller.queue_runtime_envelope( |
| 9259 | "run_fixture", |
| 9260 | runtime_envelope( |
| 9261 | (MAX_JOURNAL_EVENTS + 1) as u64, |
| 9262 | "turn.completed", |
| 9263 | Some("turn_fixture"), |
| 9264 | "2026-08-08T12:00:00Z".to_string(), |
| 9265 | json!({ "turn": { "status": "failed", "usage": {} } }), |
| 9266 | ), |
| 9267 | )); |
| 9268 | assert_eq!( |
| 9269 | controller.status, |
| 9270 | Status::Failed, |
| 9271 | "losing integrity state can never be silent" |
| 9272 | ); |
| 9273 | assert!( |
| 9274 | !controller.can_share_approval_with_web(), |
| 9275 | "a failed-closed relay keeps the shared-decision channel closed" |
| 9276 | ); |
| 9277 | } |
| 9278 | |
| 9279 | #[test] |
| 9280 | fn message_deltas_coalesce_until_a_handoff_boundary() { |
| 9281 | let (mut controller, mut worker_rx, _event_tx, _journal_root) = wired_controller(); |
| 9282 | controller |
| 9283 | .activate_prompt("run_fixture", "turn_fixture") |
| 9284 | .unwrap(); |
| 9285 | controller.observe_engine_event(&EngineEvent::MessageDelta { |
| 9286 | index: 0, |
| 9287 | content: "Hello ".to_string(), |
| 9288 | }); |
| 9289 | controller.observe_engine_event(&EngineEvent::MessageDelta { |
| 9290 | index: 0, |
| 9291 | content: "world".to_string(), |
| 9292 | }); |
| 9293 | assert!( |
| 9294 | worker_rx.try_recv().is_err(), |
| 9295 | "deferred deltas coalesce before any transport handoff" |
| 9296 | ); |
| 9297 | let events = controller |
| 9298 | .pending_runtime_events |
| 9299 | .get("run_fixture") |
| 9300 | .unwrap(); |
| 9301 | assert_eq!(events.len(), 1, "both deltas share one envelope"); |
| 9302 | assert_eq!( |
| 9303 | events.values().next().unwrap().envelope["payload"]["delta"], |
| 9304 | "Hello world" |
| 9305 | ); |
| 9306 | |
| 9307 | controller.observe_engine_event(&EngineEvent::ToolCallStarted { |
| 9308 | model_call: None, |
| 9309 | id: "tool_fixture".to_string(), |
| 9310 | name: "shell".to_string(), |
| 9311 | input: json!({}), |
| 9312 | }); |
| 9313 | let WorkerCommand::Upload { envelopes, .. } = worker_rx.try_recv().unwrap() else { |
| 9314 | panic!("the coalesced delta must hand off before a later event"); |
| 9315 | }; |
| 9316 | assert_eq!(envelopes[0]["event"], "item.delta"); |
| 9317 | assert_eq!(envelopes[0]["payload"]["delta"], "Hello world"); |
| 9318 | let WorkerCommand::Upload { envelopes, .. } = worker_rx.try_recv().unwrap() else { |
| 9319 | panic!("the tool event follows the coalesced delta"); |
| 9320 | }; |
| 9321 | assert_eq!(envelopes[0]["event"], "item.started"); |
| 9322 | |
| 9323 | // Once handed off an envelope is immutable; new deltas open a fresh |
| 9324 | // envelope that flushes on the next UI poll. |
| 9325 | controller.observe_engine_event(&EngineEvent::MessageDelta { |
| 9326 | index: 0, |
| 9327 | content: "again".to_string(), |
| 9328 | }); |
| 9329 | assert!(worker_rx.try_recv().is_err()); |
| 9330 | assert!(controller.try_next_event().is_none()); |
| 9331 | let WorkerCommand::Upload { envelopes, .. } = worker_rx.try_recv().unwrap() else { |
| 9332 | panic!("the UI poll hands the deferred delta to the transport"); |
| 9333 | }; |
| 9334 | assert_eq!(envelopes[0]["payload"]["delta"], "again"); |
| 9335 | } |
| 9336 | #[test] |
| 9337 | fn runtime_image_legacy_work_never_downgrades_to_text() { |
| 9338 | let image = codewhale_engine::image_attach::test_support::runtime_image_fixture(1); |
| 9339 | let command = json!({"type":"prompt.request","runId":"run_fixture","turnId":"turn_fixture","prompt":"look","images":[image]}); |
| 9340 | assert!( |
| 9341 | parse_remote_command(&command, "run_fixture") |
| 9342 | .unwrap_err() |
| 9343 | .contains("legacy remote Work") |
| 9344 | ); |
| 9345 | let mut text = command; |
| 9346 | text.as_object_mut().unwrap().remove("images"); |
| 9347 | assert!(matches!( |
| 9348 | parse_remote_command(&text, "run_fixture").unwrap(), |
| 9349 | RemoteCommand::Prompt { .. } |
| 9350 | )); |
| 9351 | } |
| 9352 | |
| 9353 | #[tokio::test] |
| 9354 | async fn runtime_image_command_response_has_bounded_larger_budget() { |
| 9355 | use axum::{Router, routing::get}; |
| 9356 | let payload = serde_json::to_string( |
| 9357 | &json!({"commands":[],"fixture": "x".repeat(MAX_RESPONSE_BYTES + 1)}), |
| 9358 | ) |
| 9359 | .unwrap(); |
| 9360 | let app = Router::new().route( |
| 9361 | "/", |
| 9362 | get(move || { |
| 9363 | let payload = payload.clone(); |
| 9364 | async move { payload } |
| 9365 | }), |
| 9366 | ); |
| 9367 | let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 9368 | let addr = listener.local_addr().unwrap(); |
| 9369 | let server = tokio::spawn(async move { |
| 9370 | axum::serve(listener, app).await.unwrap(); |
| 9371 | }); |
| 9372 | let client = codewhale_release::tls::reqwest_client(); |
| 9373 | let url = format!("http://{addr}/"); |
| 9374 | assert!( |
| 9375 | read_bounded_json(client.get(&url).send().await.unwrap()) |
| 9376 | .await |
| 9377 | .is_err() |
| 9378 | ); |
| 9379 | let parsed = read_bounded_json_with_limit( |
| 9380 | client.get(&url).send().await.unwrap(), |
| 9381 | codewhale_app_server_protocol::runtime::MAX_RUNTIME_IMAGE_BODY_BYTES, |
| 9382 | ) |
| 9383 | .await |
| 9384 | .unwrap(); |
| 9385 | assert_eq!( |
| 9386 | parsed["fixture"].as_str().unwrap().len(), |
| 9387 | MAX_RESPONSE_BYTES + 1 |
| 9388 | ); |
| 9389 | server.abort(); |
| 9390 | } |
| 9391 | } |
| 9392 |