| 1 | use std::collections::HashMap; |
| 2 | use std::path::PathBuf; |
| 3 | |
| 4 | use axum::Json; |
| 5 | use axum::extract::{Path, Query, State}; |
| 6 | use axum::http::StatusCode; |
| 7 | use serde::{Deserialize, Serialize}; |
| 8 | use serde_json::{Value, json}; |
| 9 | |
| 10 | use codewhale_engine::runtime_threads::{ |
| 11 | RuntimeTurnStatus, manager::CreateThreadRequest, manager::RuntimeThreadManager, |
| 12 | manager::ThreadDetail, manager::ThreadListFilter, |
| 13 | }; |
| 14 | use codewhale_engine::session_manager::{ |
| 15 | SavedSession, SessionListFilter, SessionManager, SessionMetadata, SessionMutator, |
| 16 | create_saved_session_with_id_and_mode, |
| 17 | }; |
| 18 | use codewhale_engine::session_peek::{DEFAULT_PEEK_ENTRIES, SessionPeek, build_peek}; |
| 19 | use codewhale_engine::session_projection::{ |
| 20 | SessionQuery, SessionSortMode, SessionSummary, project_sessions, |
| 21 | }; |
| 22 | use codewhale_models::{Message, Role}; |
| 23 | |
| 24 | use super::{ApiError, RuntimeApiState, map_thread_err, truncate_text}; |
| 25 | |
| 26 | #[derive(Debug, Serialize)] |
| 27 | pub(super) struct SessionsResponse { |
| 28 | sessions: Vec<SessionMetadata>, |
| 29 | } |
| 30 | |
| 31 | #[derive(Debug, Serialize)] |
| 32 | pub(super) struct SessionDetailResponse { |
| 33 | pub(super) metadata: SessionMetadata, |
| 34 | pub(super) messages: Vec<Value>, |
| 35 | pub(super) system_prompt: Option<String>, |
| 36 | /// Turns that ended `Failed`, with the redacted reason the transcript |
| 37 | /// showed. Absent when none did. |
| 38 | #[serde(skip_serializing_if = "Vec::is_empty")] |
| 39 | pub(super) turn_outcomes: Vec<codewhale_engine::session_manager::SavedTurnOutcome>, |
| 40 | } |
| 41 | |
| 42 | #[derive(Debug, Deserialize)] |
| 43 | pub(super) struct CreateSessionRequest { |
| 44 | thread_id: String, |
| 45 | title: Option<String>, |
| 46 | } |
| 47 | |
| 48 | #[derive(Debug, Serialize)] |
| 49 | pub(super) struct CreateSessionResponse { |
| 50 | session_id: String, |
| 51 | thread_id: String, |
| 52 | message_count: usize, |
| 53 | title: String, |
| 54 | } |
| 55 | |
| 56 | #[derive(Debug, Deserialize)] |
| 57 | pub(crate) struct ResumeSessionRequest { |
| 58 | pub(crate) model: Option<String>, |
| 59 | pub(crate) mode: Option<String>, |
| 60 | } |
| 61 | |
| 62 | #[derive(Debug, Serialize)] |
| 63 | pub(crate) struct ResumeSessionResponse { |
| 64 | pub(crate) thread_id: String, |
| 65 | pub(crate) session_id: String, |
| 66 | pub(crate) message_count: usize, |
| 67 | pub(crate) summary: String, |
| 68 | } |
| 69 | |
| 70 | #[derive(Debug, Deserialize)] |
| 71 | pub(super) struct SessionsQuery { |
| 72 | limit: Option<usize>, |
| 73 | search: Option<String>, |
| 74 | /// Include archived sessions. Same name and meaning as the `/v1/threads` |
| 75 | /// query pair, so a client does not need two mental models (#4397). |
| 76 | #[serde(default)] |
| 77 | include_archived: Option<bool>, |
| 78 | /// Return archived sessions only. Overrides `include_archived`. |
| 79 | #[serde(default)] |
| 80 | archived_only: Option<bool>, |
| 81 | /// Restrict to sessions recorded against this workspace. Absent means |
| 82 | /// every workspace, matching the historical behaviour of this route. |
| 83 | #[serde(default)] |
| 84 | workspace: Option<PathBuf>, |
| 85 | /// `recent` (default), `name`, or `size`. |
| 86 | #[serde(default)] |
| 87 | sort: Option<String>, |
| 88 | } |
| 89 | |
| 90 | /// `PATCH /v1/sessions/{id}` body. Both fields are optional; omitting one |
| 91 | /// leaves it untouched. |
| 92 | #[derive(Debug, Deserialize)] |
| 93 | pub(super) struct PatchSessionRequest { |
| 94 | #[serde(default)] |
| 95 | title: Option<String>, |
| 96 | #[serde(default)] |
| 97 | archived: Option<bool>, |
| 98 | } |
| 99 | |
| 100 | /// Lifecycle receipt for a session mutation. |
| 101 | /// |
| 102 | /// Deliberately shaped like the thread patch receipt: the caller gets the |
| 103 | /// resulting record plus an explicit `changes` map of what actually moved, so |
| 104 | /// a no-op patch is distinguishable from an applied one without diffing. |
| 105 | #[derive(Debug, Serialize)] |
| 106 | pub(super) struct PatchSessionResponse { |
| 107 | session: SessionMetadata, |
| 108 | changes: HashMap<String, Value>, |
| 109 | } |
| 110 | |
| 111 | #[derive(Debug, Deserialize)] |
| 112 | pub(crate) struct SaveSessionRequest { |
| 113 | /// Thread ID to save as a session. If omitted, saves the most recently |
| 114 | /// active thread. |
| 115 | #[serde(default)] |
| 116 | pub(crate) thread_id: Option<String>, |
| 117 | /// If provided, update the existing session with this ID instead of |
| 118 | /// creating a new one. This matches TUI's `build_session_snapshot` |
| 119 | /// behavior where it updates the current session in-place. |
| 120 | #[serde(default)] |
| 121 | pub(crate) session_id: Option<String>, |
| 122 | } |
| 123 | |
| 124 | #[derive(Debug, Serialize)] |
| 125 | pub(crate) struct SaveSessionResponse { |
| 126 | pub(crate) session_id: String, |
| 127 | pub(super) session: SessionDetailResponse, |
| 128 | } |
| 129 | |
| 130 | /// Turn a `SessionsQuery` into the shared projection query. |
| 131 | /// |
| 132 | /// The whole point of routing through [`SessionQuery`] is that the API's |
| 133 | /// filter/sort/search semantics are the *same code* the TUI picker and the |
| 134 | /// sidebar rail run, not a parallel reimplementation that drifts. |
| 135 | fn projection_query(query: &SessionsQuery) -> SessionQuery { |
| 136 | let mut projected = SessionQuery::default() |
| 137 | .with_filter(SessionListFilter::from_query( |
| 138 | query.include_archived, |
| 139 | query.archived_only, |
| 140 | )) |
| 141 | .with_sort( |
| 142 | query |
| 143 | .sort |
| 144 | .as_deref() |
| 145 | .map_or(SessionSortMode::Recent, SessionSortMode::from_str_or_recent), |
| 146 | ) |
| 147 | .with_search(query.search.clone().unwrap_or_default()) |
| 148 | .with_limit(query.limit.unwrap_or(50).clamp(1, 500)); |
| 149 | if let Some(workspace) = query.workspace.as_deref() { |
| 150 | projected = projected.scoped_to(workspace); |
| 151 | } |
| 152 | projected |
| 153 | } |
| 154 | |
| 155 | pub(super) async fn list_sessions( |
| 156 | State(state): State<RuntimeApiState>, |
| 157 | Query(query): Query<SessionsQuery>, |
| 158 | ) -> Result<Json<SessionsResponse>, ApiError> { |
| 159 | let projection = projection_query(&query); |
| 160 | tokio::task::spawn_blocking(move || { |
| 161 | let manager = SessionManager::new(state.sessions_dir) |
| 162 | .map_err(|e| ApiError::internal(format!("Failed to open sessions dir: {e}")))?; |
| 163 | let all = manager.list_sessions().map_err(map_session_list_err)?; |
| 164 | // This route keeps returning full `SessionMetadata` for compatibility; |
| 165 | // `/v1/sessions/summary` is the projected shape. Membership *and* order |
| 166 | // come from the shared projection so the two routes never disagree. |
| 167 | let sessions: Vec<SessionMetadata> = project_sessions(&all, &projection, None) |
| 168 | .into_iter() |
| 169 | .filter_map(|summary| all.iter().find(|m| m.id == summary.id).cloned()) |
| 170 | .collect(); |
| 171 | Ok::<_, ApiError>(SessionsResponse { sessions }) |
| 172 | }) |
| 173 | .await |
| 174 | .map_err(|_| ApiError::internal("session listing failed"))? |
| 175 | .map(Json) |
| 176 | } |
| 177 | |
| 178 | /// `GET /v1/sessions/summary` — the projected row shape. |
| 179 | /// |
| 180 | /// Field-compatible with `/v1/threads/summary` so the embedded dashboard can |
| 181 | /// render a saved session and a live thread with one row renderer, which is |
| 182 | /// what "one projection" means in practice rather than as an aspiration. |
| 183 | pub(super) async fn list_sessions_summary( |
| 184 | State(state): State<RuntimeApiState>, |
| 185 | Query(query): Query<SessionsQuery>, |
| 186 | ) -> Result<Json<Vec<SessionSummary>>, ApiError> { |
| 187 | let projection = projection_query(&query); |
| 188 | tokio::task::spawn_blocking(move || { |
| 189 | let manager = SessionManager::new(state.sessions_dir) |
| 190 | .map_err(|e| ApiError::internal(format!("Failed to open sessions dir: {e}")))?; |
| 191 | let all = manager.list_sessions().map_err(map_session_list_err)?; |
| 192 | Ok::<_, ApiError>(project_sessions(&all, &projection, None)) |
| 193 | }) |
| 194 | .await |
| 195 | .map_err(|_| ApiError::internal("session summary listing failed"))? |
| 196 | .map(Json) |
| 197 | } |
| 198 | |
| 199 | /// `PATCH /v1/sessions/{id}` — rename and/or archive a saved session. |
| 200 | /// |
| 201 | /// Both mutations go through the manager's single writers |
| 202 | /// (`rename_session`, `set_session_archived`), which is what keeps the web |
| 203 | /// dashboard, the TUI picker, and `/sessions archive` from producing three |
| 204 | /// different notions of the same lifecycle state. |
| 205 | pub(super) async fn patch_session( |
| 206 | State(state): State<RuntimeApiState>, |
| 207 | Path(id): Path<String>, |
| 208 | Json(req): Json<PatchSessionRequest>, |
| 209 | ) -> Result<Json<PatchSessionResponse>, ApiError> { |
| 210 | if req.title.is_none() && req.archived.is_none() { |
| 211 | return Err(ApiError::bad_request( |
| 212 | "PATCH /v1/sessions/{id} requires at least one of `title` or `archived`", |
| 213 | )); |
| 214 | } |
| 215 | // The single writers hold the session's live lease across their load and |
| 216 | // save; taking it may retry with short sleeps. Keep all of it off the |
| 217 | // async worker (#6149). |
| 218 | tokio::task::spawn_blocking(move || patch_session_blocking(state.sessions_dir, &id, &req)) |
| 219 | .await |
| 220 | .map_err(|_| ApiError::internal("session update failed"))? |
| 221 | .map(Json) |
| 222 | } |
| 223 | |
| 224 | fn patch_session_blocking( |
| 225 | sessions_dir: PathBuf, |
| 226 | id: &str, |
| 227 | req: &PatchSessionRequest, |
| 228 | ) -> Result<PatchSessionResponse, ApiError> { |
| 229 | let manager = SessionManager::new(sessions_dir) |
| 230 | .map_err(|e| ApiError::internal(format!("Failed to open sessions dir: {e}")))?; |
| 231 | |
| 232 | let before = manager |
| 233 | .load_session(id) |
| 234 | .map_err(|e| map_session_err(id, e, "read"))? |
| 235 | .metadata; |
| 236 | let mut metadata = before.clone(); |
| 237 | let mut changes: HashMap<String, Value> = HashMap::new(); |
| 238 | |
| 239 | if let Some(title) = req.title.as_deref() { |
| 240 | // Validate the title before touching the store so a rejected title |
| 241 | // reports *why* it was rejected rather than the generic "invalid |
| 242 | // session id" that `map_session_err` produces for `InvalidInput`. |
| 243 | codewhale_engine::session_manager::normalize_session_title(title) |
| 244 | .map_err(|e| ApiError::bad_request(e.to_string()))?; |
| 245 | metadata = manager |
| 246 | .rename_session(id, title, SessionMutator::External) |
| 247 | .map_err(|e| map_session_err(id, e, "rename"))?; |
| 248 | if metadata.title != before.title { |
| 249 | changes.insert("title".to_string(), json!(metadata.title)); |
| 250 | } |
| 251 | } |
| 252 | if let Some(archived) = req.archived { |
| 253 | metadata = manager |
| 254 | .set_session_archived(id, archived, SessionMutator::External) |
| 255 | .map_err(|e| map_session_err(id, e, "archive"))?; |
| 256 | if metadata.archived != before.archived { |
| 257 | changes.insert("archived".to_string(), json!(metadata.archived)); |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | Ok(PatchSessionResponse { |
| 262 | session: metadata, |
| 263 | changes, |
| 264 | }) |
| 265 | } |
| 266 | |
| 267 | /// Hold `id`'s live lease across an external load and save, refusing (409) |
| 268 | /// as rename, archive and delete do when an interactive session holds the |
| 269 | /// document open — its next autosave would revert the write — and rejecting |
| 270 | /// a malformed id (400). A released liveness probe cannot protect the write |
| 271 | /// that follows it (#6144). Taking the lease may retry with short sleeps, so |
| 272 | /// it runs off the async worker; drop the lease only after the save. |
| 273 | async fn reserve_external_session_write( |
| 274 | state: &RuntimeApiState, |
| 275 | id: &str, |
| 276 | action: &'static str, |
| 277 | ) -> Result<codewhale_engine::session_manager::SessionLease, ApiError> { |
| 278 | reserve_session_write(&state.sessions_dir, id, action).await |
| 279 | } |
| 280 | |
| 281 | async fn reserve_session_write( |
| 282 | sessions_dir: &std::path::Path, |
| 283 | id: &str, |
| 284 | action: &'static str, |
| 285 | ) -> Result<codewhale_engine::session_manager::SessionLease, ApiError> { |
| 286 | let sessions_dir = sessions_dir.to_path_buf(); |
| 287 | let id = id.to_string(); |
| 288 | tokio::task::spawn_blocking(move || { |
| 289 | SessionManager::new(sessions_dir) |
| 290 | .map_err(|e| ApiError::internal(format!("Failed to open sessions dir: {e}")))? |
| 291 | .reserve_session_for_external_write(&id) |
| 292 | .map_err(|e| map_session_err(&id, e, action)) |
| 293 | }) |
| 294 | .await |
| 295 | .map_err(|_| ApiError::internal("session lease reservation failed"))? |
| 296 | } |
| 297 | |
| 298 | /// `GET /v1/sessions/{id}` query options. |
| 299 | #[derive(Debug, Deserialize, Default)] |
| 300 | pub(super) struct SessionDetailQuery { |
| 301 | /// When true, return a bounded, redacted [`SessionPeek`] instead of the |
| 302 | /// full transcript. The dashboard always asks for this: shipping a |
| 303 | /// multi-megabyte transcript to a browser in order to show twelve lines is |
| 304 | /// both wasteful and a needless place to re-emit secrets. |
| 305 | #[serde(default)] |
| 306 | peek: Option<bool>, |
| 307 | /// Entry budget for the peek: [`DEFAULT_PEEK_ENTRIES`] when omitted, clamped |
| 308 | /// to `MAX_PEEK_ENTRIES`. |
| 309 | #[serde(default)] |
| 310 | entries: Option<usize>, |
| 311 | } |
| 312 | |
| 313 | /// Either the full session or a bounded peek, chosen by `?peek=true`. |
| 314 | #[derive(Debug, Serialize)] |
| 315 | #[serde(untagged)] |
| 316 | pub(super) enum SessionDetailOrPeek { |
| 317 | Peek(Box<SessionPeek>), |
| 318 | Detail(Box<SessionDetailResponse>), |
| 319 | } |
| 320 | |
| 321 | pub(super) async fn get_session( |
| 322 | State(state): State<RuntimeApiState>, |
| 323 | Path(id): Path<String>, |
| 324 | Query(query): Query<SessionDetailQuery>, |
| 325 | ) -> Result<Json<SessionDetailOrPeek>, ApiError> { |
| 326 | let manager = SessionManager::new(state.sessions_dir.clone()) |
| 327 | .map_err(|e| ApiError::internal(format!("Failed to open sessions dir: {e}")))?; |
| 328 | let session = manager |
| 329 | .load_session(&id) |
| 330 | .map_err(|e| map_session_err(&id, e, "read"))?; |
| 331 | |
| 332 | if query.peek.unwrap_or(false) { |
| 333 | let entries = query.entries.unwrap_or(DEFAULT_PEEK_ENTRIES); |
| 334 | return Ok(Json(SessionDetailOrPeek::Peek(Box::new(build_peek( |
| 335 | &session, entries, |
| 336 | ))))); |
| 337 | } |
| 338 | Ok(Json(SessionDetailOrPeek::Detail(Box::new( |
| 339 | session_to_detail(session), |
| 340 | )))) |
| 341 | } |
| 342 | |
| 343 | /// `POST /v1/sessions/{id}/resume-thread` — open a saved session as a live |
| 344 | /// thread. |
| 345 | /// |
| 346 | /// Idempotent for a conversation that is already open: when an active thread |
| 347 | /// already holds this session (and its checkpoint still describes the file), |
| 348 | /// that thread is returned with `200 OK` instead of minting a second one with |
| 349 | /// `201 Created`. Minting unconditionally is what made "continue this |
| 350 | /// conversation" grow the rail by a row per visit. |
| 351 | /// |
| 352 | /// `req.model` / `req.mode` apply only when a thread is created. An open thread |
| 353 | /// keeps the route it was opened with — a caller that needs a different route |
| 354 | /// is creating a conversation, not resuming one. |
| 355 | /// |
| 356 | /// `message_count` reports the *saved session's* count. A reused thread may hold |
| 357 | /// more than that: it keeps the turns it ran after the session's last save. |
| 358 | pub(super) async fn resume_session_thread( |
| 359 | State(state): State<RuntimeApiState>, |
| 360 | Path(id): Path<String>, |
| 361 | Json(req): Json<ResumeSessionRequest>, |
| 362 | ) -> Result<(StatusCode, Json<ResumeSessionResponse>), ApiError> { |
| 363 | tokio::spawn(async move { |
| 364 | resume_session_in_runtime( |
| 365 | &state.runtime_threads, |
| 366 | &state.sessions_dir, |
| 367 | &id, |
| 368 | req, |
| 369 | ( |
| 370 | state.config_path.as_deref(), |
| 371 | state.config_profile.as_deref(), |
| 372 | ), |
| 373 | None, |
| 374 | ) |
| 375 | .await |
| 376 | }) |
| 377 | .await |
| 378 | .map_err(|error| ApiError::internal(format!("Saved session resume task failed: {error}")))? |
| 379 | } |
| 380 | |
| 381 | pub(crate) async fn resume_session_in_runtime( |
| 382 | runtime: &std::sync::Arc<RuntimeThreadManager>, |
| 383 | sessions_dir: &std::path::Path, |
| 384 | id: &str, |
| 385 | req: ResumeSessionRequest, |
| 386 | config_source: (Option<&std::path::Path>, Option<&str>), |
| 387 | allow_shell: Option<bool>, |
| 388 | ) -> Result<(StatusCode, Json<ResumeSessionResponse>), ApiError> { |
| 389 | let _checkpoint_admission = runtime.session_checkpoint_guard().await; |
| 390 | let manager = SessionManager::new(sessions_dir.to_path_buf()) |
| 391 | .map_err(|e| ApiError::internal(format!("Failed to open sessions dir: {e}")))?; |
| 392 | let session = manager |
| 393 | .resume_session(id) |
| 394 | .map_err(|e| map_session_err(id, e, "read"))? |
| 395 | .session; |
| 396 | |
| 397 | if runtime.is_acp_host() |
| 398 | && session |
| 399 | .metadata |
| 400 | .runtime_store |
| 401 | .as_ref() |
| 402 | .is_some_and(|binding| *binding != runtime.session_store_binding()) |
| 403 | { |
| 404 | return Err(ApiError::conflict( |
| 405 | "This saved conversation belongs to another Runtime store; secure owner attachment is not qualified, so ACP will not copy its history", |
| 406 | )); |
| 407 | } |
| 408 | |
| 409 | // Validate imported image bytes before allocating a Runtime thread. This |
| 410 | // retains local history's existing bounds; invalid content cannot leave an |
| 411 | // empty session, and no path or remote image reference is dereferenced. |
| 412 | for message in session |
| 413 | .messages |
| 414 | .iter() |
| 415 | .filter(|message| message.role == Role::User) |
| 416 | { |
| 417 | codewhale_engine::image_attach::runtime_images_from_blocks(&message.content).map_err( |
| 418 | |error| ApiError::bad_request(format!("Cannot restore session image: {error}")), |
| 419 | )?; |
| 420 | } |
| 421 | |
| 422 | // The conversation may already be open. Answer with the thread that holds |
| 423 | // it rather than adding a second row for the same history (see |
| 424 | // `RuntimeThreadManager::thread_holding_session`). |
| 425 | if let Some(existing) = runtime.thread_holding_session(id, &session) { |
| 426 | let thread_id = existing.id; |
| 427 | let message_count = session.messages.len(); |
| 428 | let summary = format!( |
| 429 | "Session '{}' is already open in thread {thread_id} ({message_count} messages)", |
| 430 | session.metadata.title |
| 431 | ); |
| 432 | return Ok(( |
| 433 | StatusCode::OK, |
| 434 | Json(ResumeSessionResponse { |
| 435 | thread_id, |
| 436 | session_id: id.to_string(), |
| 437 | message_count, |
| 438 | summary, |
| 439 | }), |
| 440 | )); |
| 441 | } |
| 442 | |
| 443 | let model = req.model.unwrap_or_else(|| session.metadata.model.clone()); |
| 444 | let mode = req.mode.unwrap_or_else(|| { |
| 445 | session |
| 446 | .metadata |
| 447 | .mode |
| 448 | .clone() |
| 449 | .filter(|mode| codewhale_runtime::runtime_policy::parse_runtime_mode(mode).is_some()) |
| 450 | .unwrap_or_else(|| "agent".to_string()) |
| 451 | }); |
| 452 | |
| 453 | let thread = runtime |
| 454 | .create_thread_with_shell_policy( |
| 455 | CreateThreadRequest { |
| 456 | model: Some(model), |
| 457 | model_provider: Some(session.metadata.model_provider.clone()), |
| 458 | model_provider_id: session.metadata.model_provider_id.clone(), |
| 459 | workspace: Some(session.metadata.workspace.clone()), |
| 460 | mode: Some(mode), |
| 461 | allow_shell, |
| 462 | trust_mode: None, |
| 463 | auto_approve: None, |
| 464 | archived: false, |
| 465 | system_prompt: session.system_prompt.clone(), |
| 466 | task_id: None, |
| 467 | ..Default::default() |
| 468 | }, |
| 469 | config_source.0, |
| 470 | config_source.1, |
| 471 | ) |
| 472 | .await |
| 473 | .map_err(|err| map_resume_thread_create_err(&session.metadata.id, err))?; |
| 474 | |
| 475 | let msg_count = session.messages.len(); |
| 476 | runtime |
| 477 | .seed_thread_from_saved_session(&thread.id, &session) |
| 478 | .await |
| 479 | .map_err(|e| ApiError::internal(format!("Failed to seed thread history: {e}")))?; |
| 480 | |
| 481 | let trimmed_title = session.metadata.title.trim(); |
| 482 | if !trimmed_title.is_empty() |
| 483 | && !matches!( |
| 484 | trimmed_title.to_ascii_lowercase().as_str(), |
| 485 | "untitled" | "new session" | "new chat" |
| 486 | ) |
| 487 | { |
| 488 | let _ = runtime |
| 489 | .update_thread_under_history_guard( |
| 490 | &thread.id, |
| 491 | codewhale_engine::runtime_threads::manager::UpdateThreadRequest { |
| 492 | title: Some(trimmed_title.to_string()), |
| 493 | ..Default::default() |
| 494 | }, |
| 495 | config_source.0, |
| 496 | config_source.1, |
| 497 | ) |
| 498 | .await; |
| 499 | } |
| 500 | |
| 501 | let summary = format!( |
| 502 | "Resumed session '{}' ({} messages) into thread {}", |
| 503 | session.metadata.title, msg_count, thread.id |
| 504 | ); |
| 505 | |
| 506 | Ok(( |
| 507 | StatusCode::CREATED, |
| 508 | Json(ResumeSessionResponse { |
| 509 | thread_id: thread.id, |
| 510 | session_id: id.to_string(), |
| 511 | message_count: msg_count, |
| 512 | summary, |
| 513 | }), |
| 514 | )) |
| 515 | } |
| 516 | |
| 517 | pub(super) async fn create_session_from_thread( |
| 518 | State(state): State<RuntimeApiState>, |
| 519 | Json(req): Json<CreateSessionRequest>, |
| 520 | ) -> Result<(StatusCode, Json<CreateSessionResponse>), ApiError> { |
| 521 | let _checkpoint_admission = state.runtime_threads.session_checkpoint_guard().await; |
| 522 | let thread_id = req.thread_id.trim(); |
| 523 | if thread_id.is_empty() { |
| 524 | return Err(ApiError::bad_request("thread_id is required")); |
| 525 | } |
| 526 | |
| 527 | let detail = state |
| 528 | .runtime_threads |
| 529 | .get_thread_detail(thread_id) |
| 530 | .await |
| 531 | .map_err(map_thread_err)?; |
| 532 | |
| 533 | if thread_detail_has_live_work(&detail) { |
| 534 | return Err(ApiError { |
| 535 | status: StatusCode::CONFLICT, |
| 536 | message: format!( |
| 537 | "Thread {thread_id} has a queued or active turn; wait for completion before saving as a session" |
| 538 | ), |
| 539 | code: None, |
| 540 | }); |
| 541 | } |
| 542 | |
| 543 | let manager = SessionManager::new(state.sessions_dir.clone()) |
| 544 | .map_err(|e| ApiError::internal(format!("Failed to open sessions dir: {e}")))?; |
| 545 | // Export is idempotent (#6144). Every POST used to mint a fresh document |
| 546 | // and rebind the thread to it, so each re-export left the previous |
| 547 | // document unreferenced, and a crash between the save and the bind below |
| 548 | // left the new one unreferenced too. Export writes only the document id |
| 549 | // derived from the thread — the one its engine already writes artifacts |
| 550 | // under — so a re-export or a retry after such a crash updates and binds |
| 551 | // the document it already wrote. |
| 552 | // |
| 553 | // The document the thread is currently bound to is deliberately *not* |
| 554 | // the target: a thread opened with `resume-thread` is bound to the |
| 555 | // original saved session, often a TUI conversation, and rewriting it from |
| 556 | // this thread's lossier projection would drop its images, tool work and |
| 557 | // system prompt. Export leaves that document untouched. |
| 558 | let session_handle = codewhale_engine::runtime_threads::thread_session_id(&detail.thread.id); |
| 559 | let _lease = reserve_external_session_write(&state, &session_handle, "export").await?; |
| 560 | let existing = match manager.load_session(&session_handle) { |
| 561 | Ok(existing) => Some(existing), |
| 562 | Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, |
| 563 | Err(error) => return Err(map_session_err(&session_handle, error, "read")), |
| 564 | }; |
| 565 | let control_owner = codewhale_engine::session_manager::SessionWriteOwner::control(); |
| 566 | let captured_source = if let Some(existing) = existing.as_ref() { |
| 567 | existing |
| 568 | .write_receipt |
| 569 | .as_ref() |
| 570 | .ok_or_else(|| ApiError::conflict("Export target source was not admitted"))? |
| 571 | .capture(control_owner) |
| 572 | } else { |
| 573 | manager |
| 574 | .expect_absent_session(&session_handle) |
| 575 | .and_then(|source| source.capture(control_owner)) |
| 576 | } |
| 577 | .map_err(|error| ApiError::conflict(error.to_string()))?; |
| 578 | let messages = |
| 579 | messages_from_thread_detail(&state.runtime_threads, &detail).map_err(|error| { |
| 580 | ApiError::internal(format!("Failed to reconstruct thread history: {error}")) |
| 581 | })?; |
| 582 | if messages.is_empty() { |
| 583 | return Err(ApiError::bad_request(format!( |
| 584 | "Thread {thread_id} has no user or assistant messages to save" |
| 585 | ))); |
| 586 | } |
| 587 | |
| 588 | let total_tokens = total_tokens_from_thread_detail(&detail); |
| 589 | let created = existing.is_none(); |
| 590 | let mut session = match existing { |
| 591 | Some(existing) => { |
| 592 | let mut updated = codewhale_engine::session_manager::update_session( |
| 593 | existing, |
| 594 | &messages, |
| 595 | total_tokens, |
| 596 | None, |
| 597 | ); |
| 598 | updated.metadata.model = detail.thread.model.clone(); |
| 599 | updated.metadata.mode = Some(detail.thread.mode.clone()); |
| 600 | updated |
| 601 | } |
| 602 | None => create_saved_session_with_id_and_mode( |
| 603 | session_handle.clone(), |
| 604 | &messages, |
| 605 | &detail.thread.model, |
| 606 | &detail.thread.workspace, |
| 607 | total_tokens, |
| 608 | None, |
| 609 | Some(&detail.thread.mode), |
| 610 | ), |
| 611 | }; |
| 612 | { |
| 613 | let config = state.runtime_threads.read_config(); |
| 614 | stamp_session_provider_from_thread(&config, &detail, &mut session.metadata).map_err( |
| 615 | |reason| { |
| 616 | ApiError::bad_request(format!( |
| 617 | "Thread {thread_id} provider route is unavailable; session export will not fall back: {reason}" |
| 618 | )) |
| 619 | }, |
| 620 | )?; |
| 621 | } |
| 622 | session.system_prompt = detail.thread.system_prompt.clone(); |
| 623 | |
| 624 | if let Some(title) = |
| 625 | session_title_override(req.title.as_deref(), detail.thread.title.as_deref()) |
| 626 | { |
| 627 | session.metadata.title = title; |
| 628 | session.metadata.title_is_custom = true; |
| 629 | } |
| 630 | let title = session.metadata.title.clone(); |
| 631 | let message_count = session.metadata.message_count; |
| 632 | |
| 633 | session.write_receipt = Some(captured_source); |
| 634 | persist_thread_cost(&state.runtime_threads, thread_id, &mut session).await?; |
| 635 | |
| 636 | let publication = manager |
| 637 | .publish_session(&session) |
| 638 | .map_err(|error| map_session_err(&session.metadata.id, error, "save"))?; |
| 639 | session.adopt_publication(&publication); |
| 640 | |
| 641 | // Link the session to the thread so that `ensure_engine_loaded` can |
| 642 | // restore the full message history from the session file. |
| 643 | state |
| 644 | .runtime_threads |
| 645 | .set_thread_session_checkpoint(&detail.thread.id, &session) |
| 646 | .await |
| 647 | .map_err(|e| { |
| 648 | ApiError::internal(format!( |
| 649 | "Session was saved but its Runtime checkpoint could not be bound: {e}" |
| 650 | )) |
| 651 | })?; |
| 652 | |
| 653 | Ok(( |
| 654 | if created { |
| 655 | StatusCode::CREATED |
| 656 | } else { |
| 657 | StatusCode::OK |
| 658 | }, |
| 659 | Json(CreateSessionResponse { |
| 660 | session_id: session_handle, |
| 661 | thread_id: detail.thread.id, |
| 662 | message_count, |
| 663 | title, |
| 664 | }), |
| 665 | )) |
| 666 | } |
| 667 | |
| 668 | pub(super) fn stamp_session_provider_from_thread( |
| 669 | config: &codewhale_runtime::config::Config, |
| 670 | detail: &ThreadDetail, |
| 671 | metadata: &mut codewhale_engine::session_manager::SessionMetadata, |
| 672 | ) -> Result<(), String> { |
| 673 | let thread_has_route = detail |
| 674 | .thread |
| 675 | .model_provider |
| 676 | .as_deref() |
| 677 | .is_some_and(|provider| !provider.trim().is_empty()) |
| 678 | || detail.thread.model_provider_id.is_some(); |
| 679 | let provider_identity = if thread_has_route { |
| 680 | config.resolve_persisted_provider_identity( |
| 681 | detail.thread.model_provider.as_deref(), |
| 682 | detail.thread.model_provider_id.as_deref(), |
| 683 | )? |
| 684 | } else if let Some(turn) = detail.turns.iter().rev().find(|turn| { |
| 685 | turn.effective_provider |
| 686 | .as_deref() |
| 687 | .is_some_and(|provider| !provider.trim().is_empty()) |
| 688 | || turn.effective_provider_id.is_some() |
| 689 | }) { |
| 690 | config.resolve_persisted_provider_identity( |
| 691 | turn.effective_provider.as_deref(), |
| 692 | turn.effective_provider_id.as_deref(), |
| 693 | )? |
| 694 | } else { |
| 695 | let key = config |
| 696 | .provider |
| 697 | .as_deref() |
| 698 | .unwrap_or(codewhale_config::ProviderKind::Deepseek.as_str()); |
| 699 | config.resolve_provider_identity(key)? |
| 700 | }; |
| 701 | metadata.set_model_provider_route( |
| 702 | provider_identity.provider.as_str(), |
| 703 | provider_identity.persisted_id(), |
| 704 | ); |
| 705 | Ok(()) |
| 706 | } |
| 707 | |
| 708 | /// Whether a thread still has work in flight, for the routes that must not |
| 709 | /// read a half-written conversation. |
| 710 | /// |
| 711 | /// The turn is the authority, and an item is not. `monitor_turn` assigns a |
| 712 | /// turn's terminal status only after every item write for that turn, and crash |
| 713 | /// recovery normalizes a turn a dead process left live; the item list, by |
| 714 | /// contrast, is a projection that can outlive the turn which produced it (a |
| 715 | /// reasoning segment whose completion frame a retried stream never sent). |
| 716 | /// Reading items here made one such row — permanently `in_progress` inside a |
| 717 | /// turn that had completed — refuse every later save of that thread's session, |
| 718 | /// with a 409 that named an "active turn" which did not exist. |
| 719 | /// |
| 720 | /// Items are still repaired, just not here: `get_thread_detail` closes a |
| 721 | /// terminal turn's leftovers in the snapshot it already holds. |
| 722 | pub(super) fn thread_detail_has_live_work(detail: &ThreadDetail) -> bool { |
| 723 | detail.turns.iter().any(|turn| { |
| 724 | matches!( |
| 725 | turn.status, |
| 726 | RuntimeTurnStatus::Queued | RuntimeTurnStatus::InProgress |
| 727 | ) |
| 728 | }) |
| 729 | } |
| 730 | |
| 731 | pub(super) fn messages_from_thread_detail( |
| 732 | runtime: &RuntimeThreadManager, |
| 733 | detail: &ThreadDetail, |
| 734 | ) -> anyhow::Result<Vec<Message>> { |
| 735 | let mut items_by_turn = HashMap::new(); |
| 736 | for item in &detail.items { |
| 737 | items_by_turn |
| 738 | .entry(item.turn_id.clone()) |
| 739 | .or_insert_with(Vec::new) |
| 740 | .push(item.clone()); |
| 741 | } |
| 742 | runtime.history_from_records(&detail.turns, &items_by_turn) |
| 743 | } |
| 744 | |
| 745 | async fn persist_thread_cost( |
| 746 | runtime: &std::sync::Arc<RuntimeThreadManager>, |
| 747 | thread_id: &str, |
| 748 | session: &mut codewhale_engine::session_manager::SavedSession, |
| 749 | ) -> Result<(), ApiError> { |
| 750 | session.metadata.cost = runtime |
| 751 | .project_session_cost_for_thread(thread_id, &session.metadata.cost) |
| 752 | .await |
| 753 | .map_err(|error| { |
| 754 | ApiError::internal(format!( |
| 755 | "Failed to reconcile thread source accounting: {error}" |
| 756 | )) |
| 757 | })?; |
| 758 | Ok(()) |
| 759 | } |
| 760 | |
| 761 | /// `PUT /v1/sessions` — save a thread's current engine state as a session. |
| 762 | /// |
| 763 | /// Unlike `POST /v1/sessions` (which reconstructs messages from stored turn |
| 764 | /// items), this endpoint asks the engine for its live session snapshot so |
| 765 | /// token counts and message ordering are authoritative. |
| 766 | /// |
| 767 | /// `session_id` names the document to write. Omitted, the thread's bound |
| 768 | /// document is updated, or, for a thread bound to none, a document is created |
| 769 | /// under the thread's own conversation id — see |
| 770 | /// [`codewhale_engine::core::ops::SessionSnapshot::session_id`]. |
| 771 | pub(super) async fn save_current_session( |
| 772 | State(state): State<RuntimeApiState>, |
| 773 | Json(req): Json<SaveSessionRequest>, |
| 774 | ) -> Result<Json<SaveSessionResponse>, ApiError> { |
| 775 | save_session_in_runtime(&state.runtime_threads, &state.sessions_dir, req).await |
| 776 | } |
| 777 | |
| 778 | pub(crate) async fn save_session_in_runtime( |
| 779 | runtime: &std::sync::Arc<RuntimeThreadManager>, |
| 780 | sessions_dir: &std::path::Path, |
| 781 | req: SaveSessionRequest, |
| 782 | ) -> Result<Json<SaveSessionResponse>, ApiError> { |
| 783 | let _checkpoint_admission = runtime.session_checkpoint_guard().await; |
| 784 | // Find the thread to save. |
| 785 | let thread_id = match req.thread_id { |
| 786 | Some(id) => id, |
| 787 | None => { |
| 788 | // Find the most recently updated thread. |
| 789 | let threads = runtime |
| 790 | .list_threads(ThreadListFilter::IncludeArchived, Some(100)) |
| 791 | .await |
| 792 | .map_err(map_thread_err)?; |
| 793 | threads |
| 794 | .into_iter() |
| 795 | .max_by_key(|t| t.updated_at) |
| 796 | .map(|t| t.id) |
| 797 | .ok_or_else(|| ApiError::bad_request("No threads to save"))? |
| 798 | } |
| 799 | }; |
| 800 | |
| 801 | let detail = runtime |
| 802 | .get_thread_detail(&thread_id) |
| 803 | .await |
| 804 | .map_err(map_thread_err)?; |
| 805 | if thread_detail_has_live_work(&detail) { |
| 806 | return Err(ApiError { |
| 807 | status: StatusCode::CONFLICT, |
| 808 | message: format!( |
| 809 | "Thread {thread_id} has a queued or active turn; wait for completion before saving the session" |
| 810 | ), |
| 811 | code: None, |
| 812 | }); |
| 813 | } |
| 814 | |
| 815 | let manager = SessionManager::new(sessions_dir.to_path_buf()) |
| 816 | .map_err(|e| ApiError::internal(format!("Failed to open sessions dir: {e}")))?; |
| 817 | |
| 818 | // A document another thread is bound to is that thread's conversation. |
| 819 | // Rebinding this thread onto it would leave the other thread's checkpoint |
| 820 | // describing a document it no longer owns (#6144). A thread already bound |
| 821 | // to the same document (a legacy shared link) keeps saving to it. |
| 822 | if let Some(requested) = req.session_id.as_deref() { |
| 823 | let own = runtime |
| 824 | .get_thread(&thread_id) |
| 825 | .await |
| 826 | .map_err(map_thread_err)?; |
| 827 | if own.session_id.as_deref() != Some(requested) |
| 828 | && let Some(other) = runtime.thread_bound_to_session(requested, &thread_id) |
| 829 | { |
| 830 | return Err(ApiError { |
| 831 | status: StatusCode::CONFLICT, |
| 832 | message: format!( |
| 833 | "Session '{requested}' belongs to thread {other}; save this thread without a session_id, or into its own session" |
| 834 | ), |
| 835 | code: None, |
| 836 | }); |
| 837 | } |
| 838 | } |
| 839 | // Which document this save writes. A named `session_id` wins. With none, |
| 840 | // the thread's own document answers it: the one it is bound to (a |
| 841 | // `resume-thread` from document X runs bound to X, and saving it must |
| 842 | // update X, not start a second copy under another name), else a new |
| 843 | // document under the engine's conversation id, which for a Runtime thread |
| 844 | // is the thread's own id (see `ensure_engine_loaded`) and so cannot |
| 845 | // collide with another thread's document. Snapshot ownership does not |
| 846 | // depend on this binding: a thread owns the restore points recorded on |
| 847 | // its turns. |
| 848 | let document_id = req |
| 849 | .session_id |
| 850 | .clone() |
| 851 | .or_else(|| detail.thread.session_id.clone()) |
| 852 | .unwrap_or_else(|| codewhale_engine::runtime_threads::thread_session_id(&thread_id)); |
| 853 | let _lease = reserve_session_write(sessions_dir, &document_id, "save").await?; |
| 854 | let existing = match manager.load_session_snapshot(&document_id) { |
| 855 | Ok(session) => Some(session), |
| 856 | Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, |
| 857 | Err(error) => return Err(map_session_err(&document_id, error, "read")), |
| 858 | }; |
| 859 | let captured_source = if detail.thread.session_id.as_deref() == Some(document_id.as_str()) { |
| 860 | let captured_runtime = std::sync::Arc::clone(runtime); |
| 861 | let id = thread_id.clone(); |
| 862 | codewhale_engine::runtime_threads::manager::history::history_owner_work(move || { |
| 863 | captured_runtime.saved_session_publication_source(&id) |
| 864 | }).await.map_err(|error| ApiError::conflict(error.to_string()))? |
| 865 | } else if let Some(existing) = existing.as_ref() { |
| 866 | existing.write_receipt.clone() |
| 867 | } else { |
| 868 | Some(manager.expect_absent_session(&document_id).map_err(|error| ApiError::conflict(error.to_string()))?) |
| 869 | }.ok_or_else(|| ApiError::conflict("This Runtime history has no admitted full-document publication source; reopen its saved session before saving"))?; |
| 870 | |
| 871 | let captured_source = captured_source |
| 872 | .capture(codewhale_engine::session_manager::SessionWriteOwner::control()) |
| 873 | .map_err(|error| ApiError::conflict(error.to_string()))?; |
| 874 | // Get the engine handle (loads the thread into an engine if needed), |
| 875 | // then request a session snapshot. This reuses the same code path as |
| 876 | // TUI's `build_session_snapshot`: the engine holds the authoritative |
| 877 | // messages and token usage, so we don't need to reconstruct from turns. |
| 878 | let engine = runtime |
| 879 | .get_engine(&thread_id) |
| 880 | .await |
| 881 | .map_err(|e| ApiError::internal(format!("Failed to get engine for thread: {e}")))?; |
| 882 | |
| 883 | let snapshot = engine |
| 884 | .get_session_snapshot() |
| 885 | .await |
| 886 | .map_err(|e| ApiError::internal(format!("Failed to get session snapshot: {e}")))?; |
| 887 | |
| 888 | if snapshot.session_id != detail.thread.id || snapshot.workspace != detail.thread.workspace { |
| 889 | return Err(ApiError::conflict( |
| 890 | "Engine snapshot source changed before session publication", |
| 891 | )); |
| 892 | } |
| 893 | |
| 894 | // Build or update the session, mirroring TUI's `build_session_snapshot`. |
| 895 | // Only `io::ErrorKind::NotFound` falls back to creating a new session; |
| 896 | // other I/O errors (e.g. PermissionDenied) are propagated so callers |
| 897 | // don't silently overwrite a corrupt or inaccessible session file. |
| 898 | let mut session = match existing { |
| 899 | Some(existing) => { |
| 900 | let mut updated = codewhale_engine::session_manager::update_session( |
| 901 | existing, |
| 902 | &snapshot.messages, |
| 903 | snapshot.total_tokens, |
| 904 | snapshot.system_prompt.as_ref(), |
| 905 | ); |
| 906 | updated.metadata.model = snapshot.model.clone(); |
| 907 | updated.metadata.set_model_provider_route( |
| 908 | &snapshot.model_provider, |
| 909 | snapshot.model_provider_id.as_deref(), |
| 910 | ); |
| 911 | updated.metadata.mode = Some(snapshot.mode.clone()); |
| 912 | updated |
| 913 | } |
| 914 | None => { |
| 915 | let mut session = |
| 916 | codewhale_engine::session_manager::create_saved_session_with_id_and_mode( |
| 917 | document_id.clone(), |
| 918 | &snapshot.messages, |
| 919 | &snapshot.model, |
| 920 | &snapshot.workspace, |
| 921 | snapshot.total_tokens, |
| 922 | snapshot.system_prompt.as_ref(), |
| 923 | Some(snapshot.mode.as_str()), |
| 924 | ); |
| 925 | session.metadata.set_model_provider_route( |
| 926 | &snapshot.model_provider, |
| 927 | snapshot.model_provider_id.as_deref(), |
| 928 | ); |
| 929 | session |
| 930 | } |
| 931 | }; |
| 932 | session.write_receipt = Some(captured_source); |
| 933 | |
| 934 | persist_thread_cost(runtime, &thread_id, &mut session).await?; |
| 935 | |
| 936 | if runtime.is_acp_host() { |
| 937 | session.metadata.runtime_store = Some(runtime.session_store_binding()); |
| 938 | } |
| 939 | |
| 940 | // Save the session. |
| 941 | let publication = manager |
| 942 | .publish_session(&session) |
| 943 | .map_err(|error| map_session_err(&session.metadata.id, error, "save"))?; |
| 944 | session.adopt_publication(&publication); |
| 945 | |
| 946 | // Link the session to the thread so that `ensure_engine_loaded` can |
| 947 | // restore the full message history (including thinking/tool blocks) |
| 948 | // from the session file instead of reconstructing from turns. |
| 949 | let session_handle = session.metadata.id.clone(); |
| 950 | runtime |
| 951 | .set_thread_session_checkpoint(&thread_id, &session) |
| 952 | .await |
| 953 | .map_err(|e| { |
| 954 | ApiError::internal(format!( |
| 955 | "Session was saved but its Runtime checkpoint could not be bound: {e}" |
| 956 | )) |
| 957 | })?; |
| 958 | |
| 959 | Ok(Json(SaveSessionResponse { |
| 960 | session_id: session_handle, |
| 961 | session: session_to_detail(session), |
| 962 | })) |
| 963 | } |
| 964 | |
| 965 | fn total_tokens_from_thread_detail(detail: &ThreadDetail) -> u64 { |
| 966 | detail |
| 967 | .turns |
| 968 | .iter() |
| 969 | .filter_map(|turn| turn.usage.as_ref()) |
| 970 | .map(|usage| u64::from(usage.input_tokens) + u64::from(usage.output_tokens)) |
| 971 | .sum() |
| 972 | } |
| 973 | |
| 974 | fn session_title_override(requested: Option<&str>, thread_title: Option<&str>) -> Option<String> { |
| 975 | requested |
| 976 | .and_then(nonempty_title) |
| 977 | .or_else(|| thread_title.and_then(nonempty_title)) |
| 978 | } |
| 979 | |
| 980 | fn nonempty_title(title: &str) -> Option<String> { |
| 981 | let trimmed = title.trim(); |
| 982 | if trimmed.is_empty() { |
| 983 | None |
| 984 | } else { |
| 985 | Some(truncate_text(trimmed, 50)) |
| 986 | } |
| 987 | } |
| 988 | |
| 989 | pub(super) async fn delete_session( |
| 990 | State(state): State<RuntimeApiState>, |
| 991 | Path(id): Path<String>, |
| 992 | ) -> Result<StatusCode, ApiError> { |
| 993 | // Deletion validates the id (400), refuses an unknown one (404) before |
| 994 | // creating any lease file, and holds the session's live lease, refusing |
| 995 | // (409) a document an interactive session holds open: its next autosave, |
| 996 | // in whichever process holds it, would undo the delete. Taking the lease |
| 997 | // may retry with short sleeps, so all of it runs off the async worker. |
| 998 | tokio::task::spawn_blocking(move || { |
| 999 | let manager = SessionManager::new(state.sessions_dir.clone()) |
| 1000 | .map_err(|e| ApiError::internal(format!("Failed to open sessions dir: {e}")))?; |
| 1001 | manager |
| 1002 | .delete_session(&id) |
| 1003 | .map_err(|e| map_session_err(&id, e, "delete"))?; |
| 1004 | // Threads bound to the document keep their turns; drop the dead link |
| 1005 | // so they load from those instead of failing (#6144). |
| 1006 | if let Err(error) = state.runtime_threads.unbind_session_threads(&id) { |
| 1007 | tracing::warn!(session_id = %id, %error, "deleted session's threads were not unbound"); |
| 1008 | } |
| 1009 | Ok::<_, ApiError>(StatusCode::NO_CONTENT) |
| 1010 | }) |
| 1011 | .await |
| 1012 | .map_err(|_| ApiError::internal("session delete failed"))? |
| 1013 | } |
| 1014 | |
| 1015 | /// `GET /v1/sessions/repair`: what the last session-store repair did (#6144). |
| 1016 | /// `null` when none has completed. |
| 1017 | pub(super) async fn get_session_repair( |
| 1018 | State(state): State<RuntimeApiState>, |
| 1019 | ) -> Json<Option<codewhale_engine::session_reconcile::ReconcileSummary>> { |
| 1020 | Json(codewhale_engine::session_reconcile::last_run( |
| 1021 | &state.sessions_dir, |
| 1022 | )) |
| 1023 | } |
| 1024 | |
| 1025 | pub(super) fn session_to_detail(session: SavedSession) -> SessionDetailResponse { |
| 1026 | let messages: Vec<Value> = session |
| 1027 | .messages |
| 1028 | .iter() |
| 1029 | .map(|msg| { |
| 1030 | let content_blocks: Vec<Value> = msg |
| 1031 | .content |
| 1032 | .iter() |
| 1033 | .map(|block| match block { |
| 1034 | codewhale_models::ContentBlock::Text { text, .. } => { |
| 1035 | json!({ "type": "text", "text": text }) |
| 1036 | } |
| 1037 | codewhale_models::ContentBlock::Thinking { thinking, .. } => { |
| 1038 | json!({ "type": "thinking", "text": thinking }) |
| 1039 | } |
| 1040 | codewhale_models::ContentBlock::ToolUse { |
| 1041 | id, |
| 1042 | name, |
| 1043 | input, |
| 1044 | caller, ..} => { |
| 1045 | let mut obj = |
| 1046 | json!({ "type": "tool_use", "id": id, "name": name, "input": input }); |
| 1047 | if let Some(caller) = caller { |
| 1048 | obj["caller"] = json!(caller); |
| 1049 | } |
| 1050 | obj |
| 1051 | } |
| 1052 | codewhale_models::ContentBlock::ToolResult { |
| 1053 | tool_use_id, |
| 1054 | content, |
| 1055 | is_error, |
| 1056 | content_blocks, |
| 1057 | .. |
| 1058 | } => { |
| 1059 | let mut obj = json!({ "type": "tool_result", "tool_use_id": tool_use_id }); |
| 1060 | if let Some(cbs) = content_blocks { |
| 1061 | obj["content_blocks"] = json!(cbs); |
| 1062 | if !content.is_empty() { |
| 1063 | obj["content"] = json!(content); |
| 1064 | } |
| 1065 | } else { |
| 1066 | obj["content"] = json!(content); |
| 1067 | } |
| 1068 | if let Some(e) = is_error { |
| 1069 | obj["is_error"] = json!(e); |
| 1070 | } |
| 1071 | obj |
| 1072 | } |
| 1073 | codewhale_models::ContentBlock::ServerToolUse { |
| 1074 | id, name, input, .. |
| 1075 | } => { |
| 1076 | json!({ "type": "tool_use", "id": id, "name": name, "input": input }) |
| 1077 | } |
| 1078 | codewhale_models::ContentBlock::ToolSearchToolResult { |
| 1079 | tool_use_id, |
| 1080 | content, |
| 1081 | } => { |
| 1082 | json!({ "type": "tool_result", "tool_use_id": tool_use_id, "content": content }) |
| 1083 | } |
| 1084 | codewhale_models::ContentBlock::CodeExecutionToolResult { |
| 1085 | tool_use_id, |
| 1086 | content, |
| 1087 | } |
| 1088 | | codewhale_models::ContentBlock::WebSearchToolResult { |
| 1089 | tool_use_id, |
| 1090 | content, |
| 1091 | .. |
| 1092 | } |
| 1093 | | codewhale_models::ContentBlock::WebFetchToolResult { |
| 1094 | tool_use_id, |
| 1095 | content, |
| 1096 | .. |
| 1097 | } => { |
| 1098 | json!({ "type": "tool_result", "tool_use_id": tool_use_id, "content": content }) |
| 1099 | } |
| 1100 | codewhale_models::ContentBlock::WebSearchCall { .. } |
| 1101 | | codewhale_models::ContentBlock::ServerToolCalls { .. } |
| 1102 | | codewhale_models::ContentBlock::File { .. } |
| 1103 | | codewhale_models::ContentBlock::ImageUrl { .. } => Value::Null, |
| 1104 | }) |
| 1105 | .collect(); |
| 1106 | json!({ |
| 1107 | "role": msg.role, |
| 1108 | "content": content_blocks, |
| 1109 | }) |
| 1110 | }) |
| 1111 | .collect(); |
| 1112 | SessionDetailResponse { |
| 1113 | metadata: session.metadata, |
| 1114 | messages, |
| 1115 | system_prompt: session.system_prompt, |
| 1116 | turn_outcomes: session.turn_outcomes, |
| 1117 | } |
| 1118 | } |
| 1119 | |
| 1120 | fn map_session_list_err(err: std::io::Error) -> ApiError { |
| 1121 | if err.kind() == std::io::ErrorKind::FileTooLarge { |
| 1122 | map_session_err("catalog", err, "list") |
| 1123 | } else { |
| 1124 | ApiError::internal(format!("Failed to list sessions: {err}")) |
| 1125 | } |
| 1126 | } |
| 1127 | |
| 1128 | pub(super) fn map_session_err(id: &str, err: std::io::Error, action: &str) -> ApiError { |
| 1129 | match err.kind() { |
| 1130 | std::io::ErrorKind::NotFound => ApiError::not_found(format!("Session '{id}' not found")), |
| 1131 | std::io::ErrorKind::FileTooLarge => ApiError { |
| 1132 | code: Some("session_metadata_too_large"), |
| 1133 | ..ApiError::payload_too_large(format!("Failed to {action} session '{id}': {err}")) |
| 1134 | }, |
| 1135 | std::io::ErrorKind::InvalidData => { |
| 1136 | ApiError::bad_request(format!("Failed to parse session '{id}': {err}")) |
| 1137 | } |
| 1138 | std::io::ErrorKind::InvalidInput => { |
| 1139 | ApiError::bad_request(format!("Invalid session id '{id}'")) |
| 1140 | } |
| 1141 | // The session is open in an interactive Codewhale session, which holds |
| 1142 | // the authoritative copy in memory. Fail closed with a typed conflict |
| 1143 | // rather than write something its next autosave would revert. |
| 1144 | std::io::ErrorKind::ResourceBusy => ApiError { |
| 1145 | status: StatusCode::CONFLICT, |
| 1146 | message: err.to_string(), |
| 1147 | code: None, |
| 1148 | }, |
| 1149 | _ => ApiError::internal(format!("Failed to {action} session '{id}': {err}")), |
| 1150 | } |
| 1151 | } |
| 1152 | |
| 1153 | fn map_resume_thread_create_err(session_id: &str, err: anyhow::Error) -> ApiError { |
| 1154 | let reason = err.to_string(); |
| 1155 | let message = format!("Failed to create thread: {reason}"); |
| 1156 | if reason.starts_with("saved session has an empty provider identity") |
| 1157 | || reason.starts_with("saved session requires custom provider") |
| 1158 | || reason.starts_with("persisted provider route requires exact custom provider") |
| 1159 | || reason.starts_with("legacy session records only the generic `custom` provider kind") |
| 1160 | || reason.starts_with("legacy `provider = \"custom\"`") |
| 1161 | { |
| 1162 | ApiError::bad_request(format!( |
| 1163 | "{message}. {}", |
| 1164 | codewhale_engine::session_export::export_recovery_hint(session_id) |
| 1165 | )) |
| 1166 | } else { |
| 1167 | // Thread-store writes, event persistence, and other runtime failures |
| 1168 | // are server-side faults; never disguise them as a client config error. |
| 1169 | ApiError::internal(message) |
| 1170 | } |
| 1171 | } |
| 1172 | |
| 1173 | #[cfg(test)] |
| 1174 | mod session_query_tests { |
| 1175 | use super::*; |
| 1176 | |
| 1177 | fn query( |
| 1178 | include_archived: Option<bool>, |
| 1179 | archived_only: Option<bool>, |
| 1180 | sort: Option<&str>, |
| 1181 | workspace: Option<&str>, |
| 1182 | limit: Option<usize>, |
| 1183 | ) -> SessionsQuery { |
| 1184 | SessionsQuery { |
| 1185 | limit, |
| 1186 | search: Some("whale".to_string()), |
| 1187 | include_archived, |
| 1188 | archived_only, |
| 1189 | workspace: workspace.map(PathBuf::from), |
| 1190 | sort: sort.map(str::to_string), |
| 1191 | } |
| 1192 | } |
| 1193 | |
| 1194 | #[test] |
| 1195 | fn archive_params_resolve_like_the_threads_routes() { |
| 1196 | assert_eq!( |
| 1197 | projection_query(&query(None, None, None, None, None)).filter, |
| 1198 | SessionListFilter::ActiveOnly |
| 1199 | ); |
| 1200 | assert_eq!( |
| 1201 | projection_query(&query(Some(true), None, None, None, None)).filter, |
| 1202 | SessionListFilter::IncludeArchived |
| 1203 | ); |
| 1204 | assert_eq!( |
| 1205 | projection_query(&query(Some(true), Some(true), None, None, None)).filter, |
| 1206 | SessionListFilter::ArchivedOnly |
| 1207 | ); |
| 1208 | } |
| 1209 | |
| 1210 | #[test] |
| 1211 | fn sort_and_workspace_scope_flow_through_and_bad_sorts_fall_back() { |
| 1212 | let projected = projection_query(&query(None, None, Some("name"), Some("/repo"), Some(9))); |
| 1213 | assert_eq!(projected.sort, SessionSortMode::Name); |
| 1214 | // `Path` in this module is `axum::extract::Path`; spell out the std one. |
| 1215 | assert_eq!( |
| 1216 | projected.workspace_scope.as_deref(), |
| 1217 | Some(std::path::Path::new("/repo")) |
| 1218 | ); |
| 1219 | assert_eq!(projected.limit, 9); |
| 1220 | assert_eq!(projected.search, "whale"); |
| 1221 | |
| 1222 | // An unknown sort must not fail the request — a stale client should |
| 1223 | // still get a listing, just in the default order. |
| 1224 | assert_eq!( |
| 1225 | projection_query(&query(None, None, Some("nonsense"), None, None)).sort, |
| 1226 | SessionSortMode::Recent |
| 1227 | ); |
| 1228 | } |
| 1229 | |
| 1230 | #[test] |
| 1231 | fn limit_is_clamped_at_both_ends() { |
| 1232 | assert_eq!( |
| 1233 | projection_query(&query(None, None, None, None, Some(0))).limit, |
| 1234 | 1 |
| 1235 | ); |
| 1236 | assert_eq!( |
| 1237 | projection_query(&query(None, None, None, None, Some(10_000))).limit, |
| 1238 | 500 |
| 1239 | ); |
| 1240 | // Absent limit keeps the historical page size. |
| 1241 | assert_eq!( |
| 1242 | projection_query(&query(None, None, None, None, None)).limit, |
| 1243 | 50 |
| 1244 | ); |
| 1245 | } |
| 1246 | |
| 1247 | #[test] |
| 1248 | fn absent_workspace_means_every_workspace() { |
| 1249 | assert!( |
| 1250 | projection_query(&query(None, None, None, None, None)) |
| 1251 | .workspace_scope |
| 1252 | .is_none(), |
| 1253 | "the API must not silently scope to the runtime's own CWD" |
| 1254 | ); |
| 1255 | } |
| 1256 | } |
| 1257 | |
| 1258 | #[cfg(test)] |
| 1259 | mod resume_thread_error_tests { |
| 1260 | use super::*; |
| 1261 | |
| 1262 | #[test] |
| 1263 | fn provider_config_errors_are_client_errors_but_storage_errors_stay_internal() { |
| 1264 | let provider = map_resume_thread_create_err( |
| 1265 | "session-1", |
| 1266 | anyhow::anyhow!( |
| 1267 | "saved session requires custom provider 'lm-studio', but `[providers.lm-studio]` is missing" |
| 1268 | ), |
| 1269 | ); |
| 1270 | assert_eq!(provider.status, StatusCode::BAD_REQUEST); |
| 1271 | |
| 1272 | let storage = map_resume_thread_create_err( |
| 1273 | "session-1", |
| 1274 | anyhow::anyhow!("Failed to save runtime thread: permission denied"), |
| 1275 | ); |
| 1276 | assert_eq!(storage.status, StatusCode::INTERNAL_SERVER_ERROR); |
| 1277 | } |
| 1278 | } |
| 1279 | |
| 1280 | // --------------------------------------------------------------------------- |
| 1281 | // Session artifacts (#6163): the oversized tool outputs a session recorded as |
| 1282 | // `ArtifactRecord`s live under `sessions/<id>/artifacts/`. These routes list |
| 1283 | // the records a saved session carries and read one artifact through the same |
| 1284 | // confined opener the workspace file routes use. Nothing is copied anywhere. |
| 1285 | // --------------------------------------------------------------------------- |
| 1286 | |
| 1287 | #[derive(Debug, Serialize)] |
| 1288 | pub(super) struct SessionArtifactSummary { |
| 1289 | id: String, |
| 1290 | session_id: String, |
| 1291 | #[serde(skip_serializing_if = "Option::is_none")] |
| 1292 | content_type: Option<String>, |
| 1293 | kind: codewhale_runtime::artifacts::ArtifactKind, |
| 1294 | tool_call_id: String, |
| 1295 | tool_name: String, |
| 1296 | created_at: chrono::DateTime<chrono::Utc>, |
| 1297 | byte_size: u64, |
| 1298 | preview: String, |
| 1299 | /// Session-relative storage path with `/` separators. |
| 1300 | path: String, |
| 1301 | } |
| 1302 | |
| 1303 | #[derive(Debug, Serialize)] |
| 1304 | pub(super) struct SessionArtifactsResponse { |
| 1305 | session_id: String, |
| 1306 | artifacts: Vec<SessionArtifactSummary>, |
| 1307 | } |
| 1308 | |
| 1309 | #[derive(Deserialize)] |
| 1310 | #[serde(deny_unknown_fields)] |
| 1311 | pub(super) struct SessionArtifactReadQuery { |
| 1312 | offset: Option<usize>, |
| 1313 | limit: Option<usize>, |
| 1314 | } |
| 1315 | |
| 1316 | #[derive(Debug, Serialize)] |
| 1317 | pub(super) struct SessionArtifactReadResponse { |
| 1318 | artifact: SessionArtifactSummary, |
| 1319 | size: u64, |
| 1320 | revision: String, |
| 1321 | offset: usize, |
| 1322 | bytes: usize, |
| 1323 | truncated: bool, |
| 1324 | encoding: &'static str, |
| 1325 | content: String, |
| 1326 | } |
| 1327 | |
| 1328 | fn artifact_summary( |
| 1329 | record: &codewhale_runtime::artifacts::ArtifactRecord, |
| 1330 | ) -> SessionArtifactSummary { |
| 1331 | SessionArtifactSummary { |
| 1332 | id: record.id.clone(), |
| 1333 | session_id: record.session_id.clone(), |
| 1334 | content_type: None, |
| 1335 | kind: record.kind.clone(), |
| 1336 | tool_call_id: record.tool_call_id.clone(), |
| 1337 | tool_name: record.tool_name.clone(), |
| 1338 | created_at: record.created_at, |
| 1339 | byte_size: record.byte_size, |
| 1340 | preview: record.preview.clone(), |
| 1341 | path: codewhale_runtime::artifacts::format_artifact_relative_path(&record.storage_path), |
| 1342 | } |
| 1343 | } |
| 1344 | |
| 1345 | pub(super) async fn list_session_artifacts( |
| 1346 | State(state): State<RuntimeApiState>, |
| 1347 | Path(id): Path<String>, |
| 1348 | ) -> Result<Json<SessionArtifactsResponse>, ApiError> { |
| 1349 | let manager = SessionManager::new(state.sessions_dir.clone()) |
| 1350 | .map_err(|e| ApiError::internal(format!("Failed to open sessions dir: {e}")))?; |
| 1351 | let session = manager |
| 1352 | .load_session(&id) |
| 1353 | .map_err(|e| map_session_err(&id, e, "read"))?; |
| 1354 | Ok(Json(SessionArtifactsResponse { |
| 1355 | session_id: session.metadata.id.clone(), |
| 1356 | artifacts: session.artifacts.iter().map(artifact_summary).collect(), |
| 1357 | })) |
| 1358 | } |
| 1359 | |
| 1360 | pub(super) async fn read_session_artifact( |
| 1361 | State(state): State<RuntimeApiState>, |
| 1362 | Path((id, artifact_id)): Path<(String, String)>, |
| 1363 | Query(query): Query<SessionArtifactReadQuery>, |
| 1364 | ) -> Result<Json<SessionArtifactReadResponse>, ApiError> { |
| 1365 | let (offset, limit) = super::workspace::parse_read_window(query.offset, query.limit)?; |
| 1366 | tokio::task::spawn_blocking(move || { |
| 1367 | read_session_artifact_window(&state.sessions_dir, &id, &artifact_id, offset, limit) |
| 1368 | }) |
| 1369 | .await |
| 1370 | .map_err(|_| ApiError::internal("session artifact read failed"))? |
| 1371 | .map(Json) |
| 1372 | } |
| 1373 | |
| 1374 | fn read_session_artifact_window( |
| 1375 | sessions_dir: &std::path::Path, |
| 1376 | id: &str, |
| 1377 | artifact_id: &str, |
| 1378 | offset: usize, |
| 1379 | limit: usize, |
| 1380 | ) -> Result<SessionArtifactReadResponse, ApiError> { |
| 1381 | let resolved = resolve_session_artifact( |
| 1382 | sessions_dir, |
| 1383 | id, |
| 1384 | artifact_id, |
| 1385 | ArtifactAuthority::SavedSession, |
| 1386 | )?; |
| 1387 | let summary = resolved |
| 1388 | .summary |
| 1389 | .ok_or_else(|| ApiError::internal("saved-session artifact has no summary"))?; |
| 1390 | let read = resolved.read; |
| 1391 | let (window, truncated) = super::workspace::read_window(&read.bytes, offset, limit); |
| 1392 | let (encoding, content) = super::workspace::encode_window(window); |
| 1393 | Ok(SessionArtifactReadResponse { |
| 1394 | artifact: summary, |
| 1395 | size: read.size, |
| 1396 | revision: read.revision, |
| 1397 | offset: offset.min(read.bytes.len()), |
| 1398 | bytes: window.len(), |
| 1399 | truncated, |
| 1400 | encoding, |
| 1401 | content, |
| 1402 | }) |
| 1403 | } |
| 1404 | |
| 1405 | /// Who vouches that `artifact_id` belongs to session `id`. |
| 1406 | pub(super) enum ArtifactAuthority<'a> { |
| 1407 | /// The SavedSession JSON's `artifacts` index. |
| 1408 | SavedSession, |
| 1409 | /// A runtime turn's recorded reference. A Runtime engine runs under its |
| 1410 | /// thread's own id (#6621), which has no SavedSession index, so the turn |
| 1411 | /// record is the ownership proof: the bytes must sit at `path` and, when `revision` is |
| 1412 | /// known, hash to it. |
| 1413 | TurnRef { |
| 1414 | path: &'a str, |
| 1415 | revision: Option<&'a str>, |
| 1416 | }, |
| 1417 | } |
| 1418 | |
| 1419 | /// One session artifact's bytes, read through the confined opener. |
| 1420 | pub(super) struct ResolvedSessionArtifact { |
| 1421 | /// The index or manifest record; `None` for a turn-ref read of a |
| 1422 | /// non-image artifact, whose caller already holds the reference. |
| 1423 | pub(super) summary: Option<SessionArtifactSummary>, |
| 1424 | pub(super) read: super::workspace::ConfinedFileBytes, |
| 1425 | } |
| 1426 | |
| 1427 | /// The one resolver behind both session-artifact reads: the session route |
| 1428 | /// (SavedSession authority) and the turn route (turn-ref authority). Both |
| 1429 | /// get the same session-id validation, confinement, image-manifest checks |
| 1430 | /// and integrity checks. |
| 1431 | pub(super) fn resolve_session_artifact( |
| 1432 | sessions_dir: &std::path::Path, |
| 1433 | id: &str, |
| 1434 | artifact_id: &str, |
| 1435 | authority: ArtifactAuthority<'_>, |
| 1436 | ) -> Result<ResolvedSessionArtifact, ApiError> { |
| 1437 | if !codewhale_runtime::artifacts::is_valid_session_id(id) { |
| 1438 | return Err(ApiError::bad_request("invalid session id")); |
| 1439 | } |
| 1440 | // The reserved image namespace always requires its immutable manifest, |
| 1441 | // even if a later SavedSession index also mentions that handle. |
| 1442 | let image_handle = artifact_id.strip_prefix("art_image_").is_some_and(|hash| { |
| 1443 | hash.len() == 64 |
| 1444 | && hash |
| 1445 | .bytes() |
| 1446 | .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()) |
| 1447 | }); |
| 1448 | let (summary, relative_path, evidence) = if image_handle { |
| 1449 | let (summary, evidence) = image_evidence_summary(sessions_dir, id, artifact_id)?; |
| 1450 | let path = summary.path.clone(); |
| 1451 | (Some(summary), path, Some(evidence)) |
| 1452 | } else { |
| 1453 | match &authority { |
| 1454 | ArtifactAuthority::SavedSession => { |
| 1455 | let summary = saved_session_summary(sessions_dir, id, artifact_id)?; |
| 1456 | let path = summary.path.clone(); |
| 1457 | (Some(summary), path, None) |
| 1458 | } |
| 1459 | ArtifactAuthority::TurnRef { path, .. } => { |
| 1460 | let relative = PathBuf::from(path); |
| 1461 | if relative.is_absolute() || !codewhale_util::files::path_is_confined(&relative) { |
| 1462 | return Err(ApiError::forbidden( |
| 1463 | "artifact reference is not confined to its session", |
| 1464 | )); |
| 1465 | } |
| 1466 | (None, (*path).to_string(), None) |
| 1467 | } |
| 1468 | } |
| 1469 | }; |
| 1470 | let relative = PathBuf::from(id).join(&relative_path); |
| 1471 | let opened = super::workspace::open_confined_file_resolved(sessions_dir, &relative, false) |
| 1472 | .and_then(|file| super::workspace::read_confined_bytes(&file)); |
| 1473 | let read = match (opened, &authority) { |
| 1474 | (Ok(read), _) => read, |
| 1475 | // A turn recorded these bytes; their absence means the session |
| 1476 | // directory was pruned since. |
| 1477 | (Err(error), ArtifactAuthority::TurnRef { .. }) |
| 1478 | if error.status == StatusCode::NOT_FOUND => |
| 1479 | { |
| 1480 | return Err(ApiError::gone( |
| 1481 | "this artifact's bytes are no longer stored (its session was pruned)", |
| 1482 | )); |
| 1483 | } |
| 1484 | (Err(error), _) => return Err(error), |
| 1485 | }; |
| 1486 | if let Some(evidence) = evidence |
| 1487 | && (read.size != evidence.size_bytes |
| 1488 | || read.revision != evidence.digest |
| 1489 | || codewhale_engine::image_attach::sniff_media_type(&read.bytes) |
| 1490 | != Some(evidence.content_type.as_str()) |
| 1491 | || codewhale_engine::image_attach::decode_and_guard_image(&read.bytes).is_err()) |
| 1492 | { |
| 1493 | return Err(ApiError::bad_request( |
| 1494 | "image evidence integrity check failed", |
| 1495 | )); |
| 1496 | } |
| 1497 | if let ArtifactAuthority::TurnRef { |
| 1498 | revision: Some(expected), |
| 1499 | .. |
| 1500 | } = authority |
| 1501 | && read.revision != expected |
| 1502 | { |
| 1503 | return Err(ApiError::conflict(format!( |
| 1504 | "artifact bytes changed since the turn recorded them; current revision is {}", |
| 1505 | read.revision |
| 1506 | ))); |
| 1507 | } |
| 1508 | Ok(ResolvedSessionArtifact { summary, read }) |
| 1509 | } |
| 1510 | |
| 1511 | fn saved_session_summary( |
| 1512 | sessions_dir: &std::path::Path, |
| 1513 | id: &str, |
| 1514 | artifact_id: &str, |
| 1515 | ) -> Result<SessionArtifactSummary, ApiError> { |
| 1516 | let manager = SessionManager::new(sessions_dir.to_path_buf()) |
| 1517 | .map_err(|e| ApiError::internal(format!("Failed to open sessions dir: {e}")))?; |
| 1518 | let record = match manager.load_session_snapshot(id) { |
| 1519 | Ok(session) if session.metadata.id == id => session |
| 1520 | .artifacts |
| 1521 | .into_iter() |
| 1522 | .find(|record| record.id == artifact_id), |
| 1523 | Ok(_) => return Err(ApiError::forbidden("artifact session owner does not match")), |
| 1524 | Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, |
| 1525 | Err(error) => return Err(map_session_err(id, error, "read")), |
| 1526 | }; |
| 1527 | let record = record.ok_or_else(|| ApiError::not_found("artifact not found"))?; |
| 1528 | if record.storage_path.is_absolute() |
| 1529 | || !codewhale_util::files::path_is_confined(&record.storage_path) |
| 1530 | || (!record.session_id.is_empty() && record.session_id != id) |
| 1531 | { |
| 1532 | return Err(ApiError::forbidden( |
| 1533 | "artifact record is not confined to its session", |
| 1534 | )); |
| 1535 | } |
| 1536 | let mut summary = artifact_summary(&record); |
| 1537 | summary.session_id = id.to_owned(); |
| 1538 | Ok(summary) |
| 1539 | } |
| 1540 | |
| 1541 | /// Fresh Engine sessions can publish immutable observations before a |
| 1542 | /// SavedSession JSON exists. Only the exact owned image manifest grants |
| 1543 | /// access; arbitrary relative paths and other evidence are not a fallback. |
| 1544 | fn image_evidence_summary( |
| 1545 | sessions_dir: &std::path::Path, |
| 1546 | id: &str, |
| 1547 | artifact_id: &str, |
| 1548 | ) -> Result< |
| 1549 | ( |
| 1550 | SessionArtifactSummary, |
| 1551 | codewhale_engine::tools::large_output_router::EvidenceArtifact, |
| 1552 | ), |
| 1553 | ApiError, |
| 1554 | > { |
| 1555 | let relative = PathBuf::from(id).join( |
| 1556 | codewhale_engine::tools::large_output_router::evidence_metadata_relative_path(artifact_id), |
| 1557 | ); |
| 1558 | let file = super::workspace::open_confined_file_resolved(sessions_dir, &relative, false)?; |
| 1559 | let evidence = codewhale_engine::tools::large_output_router::read_evidence_metadata_file(&file) |
| 1560 | .map_err(|error| super::workspace::map_fs_error(error, "evidence metadata"))?; |
| 1561 | let expected_path = PathBuf::from(codewhale_runtime::artifacts::ARTIFACTS_DIR_NAME) |
| 1562 | .join(format!("{artifact_id}.image")); |
| 1563 | if evidence.origin_session != id |
| 1564 | || evidence.handle != artifact_id |
| 1565 | || evidence.storage_path != expected_path |
| 1566 | || evidence.generation != 1 |
| 1567 | || evidence.encoding != "binary" |
| 1568 | || evidence.call_id.is_empty() |
| 1569 | { |
| 1570 | return Err(ApiError::forbidden( |
| 1571 | "image evidence owner or path does not match", |
| 1572 | )); |
| 1573 | } |
| 1574 | if evidence.redacted |
| 1575 | || codewhale_engine::tools::large_output_router::evidence_is_expired( |
| 1576 | &evidence, |
| 1577 | codewhale_engine::tools::large_output_router::unix_millis_now(), |
| 1578 | ) |
| 1579 | { |
| 1580 | return Err(ApiError::forbidden("image evidence is no longer available")); |
| 1581 | } |
| 1582 | if evidence.size_bytes > codewhale_engine::image_attach::MAX_IMAGE_BYTES as u64 |
| 1583 | || !matches!( |
| 1584 | evidence.content_type.as_str(), |
| 1585 | "image/png" | "image/jpeg" | "image/gif" | "image/webp" |
| 1586 | ) |
| 1587 | { |
| 1588 | return Err(ApiError::bad_request("invalid image evidence")); |
| 1589 | } |
| 1590 | let created_at = i64::try_from(evidence.created_at_unix_ms) |
| 1591 | .ok() |
| 1592 | .and_then(chrono::DateTime::from_timestamp_millis) |
| 1593 | .ok_or_else(|| ApiError::bad_request("invalid evidence timestamp"))?; |
| 1594 | let summary = SessionArtifactSummary { |
| 1595 | id: artifact_id.to_owned(), |
| 1596 | session_id: id.to_owned(), |
| 1597 | content_type: Some(evidence.content_type.clone()), |
| 1598 | kind: codewhale_runtime::artifacts::ArtifactKind::ToolOutput, |
| 1599 | tool_call_id: evidence.call_id.clone(), |
| 1600 | tool_name: evidence.tool_name.clone(), |
| 1601 | created_at, |
| 1602 | byte_size: evidence.size_bytes, |
| 1603 | preview: String::new(), |
| 1604 | path: codewhale_runtime::artifacts::format_artifact_relative_path(&evidence.storage_path), |
| 1605 | }; |
| 1606 | Ok((summary, evidence)) |
| 1607 | } |
| 1608 | |
| 1609 | #[cfg(test)] |
| 1610 | mod tool_media_artifact_tests { |
| 1611 | use super::*; |
| 1612 | use base64::Engine as _; |
| 1613 | use codewhale_engine::tools::large_output_router::{ |
| 1614 | EvidenceArtifact, EvidenceRetentionState, evidence_metadata_relative_path, unix_millis_now, |
| 1615 | }; |
| 1616 | |
| 1617 | fn fixture(root: &std::path::Path) -> EvidenceArtifact { |
| 1618 | let id = format!("art_image_{}", "a".repeat(64)); |
| 1619 | let relative = PathBuf::from("artifacts").join(format!("{id}.image")); |
| 1620 | let mut bytes = std::io::Cursor::new(Vec::new()); |
| 1621 | image::DynamicImage::new_rgba8(2, 1) |
| 1622 | .write_to(&mut bytes, image::ImageFormat::Png) |
| 1623 | .unwrap(); |
| 1624 | let bytes = bytes.into_inner(); |
| 1625 | let now = unix_millis_now(); |
| 1626 | let evidence = EvidenceArtifact { |
| 1627 | handle: id, |
| 1628 | digest: codewhale_runtime::hashing::sha256_hex(&bytes), |
| 1629 | size_bytes: bytes.len() as u64, |
| 1630 | content_type: "image/png".into(), |
| 1631 | tool_name: "screenshot".into(), |
| 1632 | call_id: "image-call".into(), |
| 1633 | origin_session: "media_owner".into(), |
| 1634 | generation: 1, |
| 1635 | redacted: false, |
| 1636 | encoding: "binary".into(), |
| 1637 | retention_state: EvidenceRetentionState::Live, |
| 1638 | created_at_unix_ms: now, |
| 1639 | retain_until_unix_ms: now + 60_000, |
| 1640 | storage_path: relative, |
| 1641 | }; |
| 1642 | std::fs::create_dir_all(root.join("media_owner/artifacts")).unwrap(); |
| 1643 | std::fs::write(root.join("media_owner").join(&evidence.storage_path), bytes).unwrap(); |
| 1644 | save_manifest(root, &evidence); |
| 1645 | evidence |
| 1646 | } |
| 1647 | |
| 1648 | fn save_manifest(root: &std::path::Path, evidence: &EvidenceArtifact) { |
| 1649 | std::fs::write( |
| 1650 | root.join("media_owner") |
| 1651 | .join(evidence_metadata_relative_path(&evidence.handle)), |
| 1652 | serde_json::to_vec(evidence).unwrap(), |
| 1653 | ) |
| 1654 | .unwrap(); |
| 1655 | } |
| 1656 | |
| 1657 | fn decode(response: &SessionArtifactReadResponse) -> Vec<u8> { |
| 1658 | if response.encoding == "base64" { |
| 1659 | base64::engine::general_purpose::STANDARD |
| 1660 | .decode(&response.content) |
| 1661 | .unwrap() |
| 1662 | } else { |
| 1663 | response.content.as_bytes().to_vec() |
| 1664 | } |
| 1665 | } |
| 1666 | |
| 1667 | #[test] |
| 1668 | fn tool_media_artifact_reads_without_saved_session_and_retains_window_revision() { |
| 1669 | let temp = tempfile::tempdir().unwrap(); |
| 1670 | let evidence = fixture(temp.path()); |
| 1671 | assert!(!temp.path().join("media_owner.json").exists()); |
| 1672 | let first = |
| 1673 | read_session_artifact_window(temp.path(), "media_owner", &evidence.handle, 0, 7) |
| 1674 | .unwrap(); |
| 1675 | let rest = |
| 1676 | read_session_artifact_window(temp.path(), "media_owner", &evidence.handle, 7, 1024) |
| 1677 | .unwrap(); |
| 1678 | assert_eq!(first.artifact.session_id, "media_owner"); |
| 1679 | assert_eq!(first.artifact.tool_call_id, "image-call"); |
| 1680 | assert_eq!(first.artifact.content_type.as_deref(), Some("image/png")); |
| 1681 | assert_eq!(first.revision, rest.revision); |
| 1682 | assert!(first.truncated); |
| 1683 | assert!(!rest.truncated); |
| 1684 | let mut bytes = decode(&first); |
| 1685 | bytes.extend(decode(&rest)); |
| 1686 | assert_eq!( |
| 1687 | codewhale_runtime::hashing::sha256_hex(&bytes), |
| 1688 | evidence.digest |
| 1689 | ); |
| 1690 | assert_eq!( |
| 1691 | read_session_artifact_window(temp.path(), "other_owner", &evidence.handle, 0, 1024) |
| 1692 | .unwrap_err() |
| 1693 | .status, |
| 1694 | StatusCode::NOT_FOUND |
| 1695 | ); |
| 1696 | assert_eq!( |
| 1697 | read_session_artifact_window(temp.path(), "../media_owner", &evidence.handle, 0, 1024) |
| 1698 | .unwrap_err() |
| 1699 | .status, |
| 1700 | StatusCode::BAD_REQUEST |
| 1701 | ); |
| 1702 | } |
| 1703 | |
| 1704 | #[test] |
| 1705 | fn tool_media_artifact_rejects_wrong_owner_expiry_spoofed_mime_and_changed_bytes() { |
| 1706 | let temp = tempfile::tempdir().unwrap(); |
| 1707 | let evidence = fixture(temp.path()); |
| 1708 | let mut owner = evidence.clone(); |
| 1709 | owner.origin_session = "foreign".into(); |
| 1710 | let mut handle = evidence.clone(); |
| 1711 | handle.handle = "forged".into(); |
| 1712 | let mut path = evidence.clone(); |
| 1713 | path.storage_path = PathBuf::from("../outside.png"); |
| 1714 | let mut generation = evidence.clone(); |
| 1715 | generation.generation = 2; |
| 1716 | for invalid in [owner, handle, path, generation] { |
| 1717 | save_manifest(temp.path(), &invalid); |
| 1718 | assert_eq!( |
| 1719 | read_session_artifact_window(temp.path(), "media_owner", &evidence.handle, 0, 1024) |
| 1720 | .unwrap_err() |
| 1721 | .status, |
| 1722 | StatusCode::FORBIDDEN |
| 1723 | ); |
| 1724 | } |
| 1725 | let mut expired = evidence.clone(); |
| 1726 | expired.retain_until_unix_ms = 0; |
| 1727 | save_manifest(temp.path(), &expired); |
| 1728 | assert_eq!( |
| 1729 | read_session_artifact_window(temp.path(), "media_owner", &evidence.handle, 0, 1024) |
| 1730 | .unwrap_err() |
| 1731 | .status, |
| 1732 | StatusCode::FORBIDDEN |
| 1733 | ); |
| 1734 | let mut redacted = evidence.clone(); |
| 1735 | redacted.redacted = true; |
| 1736 | save_manifest(temp.path(), &redacted); |
| 1737 | assert_eq!( |
| 1738 | read_session_artifact_window(temp.path(), "media_owner", &evidence.handle, 0, 1024) |
| 1739 | .unwrap_err() |
| 1740 | .status, |
| 1741 | StatusCode::FORBIDDEN |
| 1742 | ); |
| 1743 | let mut mime = evidence.clone(); |
| 1744 | mime.content_type = "image/jpeg".into(); |
| 1745 | save_manifest(temp.path(), &mime); |
| 1746 | assert_eq!( |
| 1747 | read_session_artifact_window(temp.path(), "media_owner", &evidence.handle, 0, 1024) |
| 1748 | .unwrap_err() |
| 1749 | .status, |
| 1750 | StatusCode::BAD_REQUEST |
| 1751 | ); |
| 1752 | save_manifest(temp.path(), &evidence); |
| 1753 | std::fs::write( |
| 1754 | temp.path().join("media_owner").join(&evidence.storage_path), |
| 1755 | b"changed", |
| 1756 | ) |
| 1757 | .unwrap(); |
| 1758 | assert_eq!( |
| 1759 | read_session_artifact_window(temp.path(), "media_owner", &evidence.handle, 0, 1024) |
| 1760 | .unwrap_err() |
| 1761 | .status, |
| 1762 | StatusCode::BAD_REQUEST |
| 1763 | ); |
| 1764 | } |
| 1765 | |
| 1766 | #[cfg(unix)] |
| 1767 | #[test] |
| 1768 | fn tool_media_artifact_rejects_manifest_and_payload_symlinks() { |
| 1769 | use std::os::unix::fs::symlink; |
| 1770 | let temp = tempfile::tempdir().unwrap(); |
| 1771 | let evidence = fixture(temp.path()); |
| 1772 | let manifest = temp |
| 1773 | .path() |
| 1774 | .join("media_owner") |
| 1775 | .join(evidence_metadata_relative_path(&evidence.handle)); |
| 1776 | let outside = temp.path().join("outside.json"); |
| 1777 | std::fs::rename(&manifest, &outside).unwrap(); |
| 1778 | symlink(&outside, &manifest).unwrap(); |
| 1779 | assert!( |
| 1780 | read_session_artifact_window(temp.path(), "media_owner", &evidence.handle, 0, 1024) |
| 1781 | .is_err() |
| 1782 | ); |
| 1783 | std::fs::remove_file(&manifest).unwrap(); |
| 1784 | save_manifest(temp.path(), &evidence); |
| 1785 | let payload = temp.path().join("media_owner").join(&evidence.storage_path); |
| 1786 | let outside = temp.path().join("outside.png"); |
| 1787 | std::fs::rename(&payload, &outside).unwrap(); |
| 1788 | symlink(&outside, &payload).unwrap(); |
| 1789 | assert!( |
| 1790 | read_session_artifact_window(temp.path(), "media_owner", &evidence.handle, 0, 1024) |
| 1791 | .is_err() |
| 1792 | ); |
| 1793 | } |
| 1794 | } |
| 1795 | |
| 1796 | /// Trusted transport creation uses the same lease/checkpoint writer before |
| 1797 | /// the first provider call. Ordinary HTTP export still rejects empty history. |
| 1798 | pub(crate) async fn initialize_empty_session( |
| 1799 | runtime: &std::sync::Arc<RuntimeThreadManager>, |
| 1800 | sessions_dir: &std::path::Path, |
| 1801 | thread_id: &str, |
| 1802 | session_id: &str, |
| 1803 | ) -> Result<(), ApiError> { |
| 1804 | let _checkpoint_admission = runtime.session_checkpoint_guard().await; |
| 1805 | let detail = runtime |
| 1806 | .get_thread_detail(thread_id) |
| 1807 | .await |
| 1808 | .map_err(map_thread_err)?; |
| 1809 | if thread_detail_has_live_work(&detail) |
| 1810 | || !detail.turns.is_empty() |
| 1811 | || detail.thread.session_id.is_some() |
| 1812 | { |
| 1813 | return Err(ApiError::conflict( |
| 1814 | "Initial ACP checkpoint requires a new idle, unbound thread", |
| 1815 | )); |
| 1816 | } |
| 1817 | let _lease = reserve_session_write(sessions_dir, session_id, "initialize").await?; |
| 1818 | let manager = SessionManager::new(sessions_dir.to_path_buf()) |
| 1819 | .map_err(|error| ApiError::internal(error.to_string()))?; |
| 1820 | match manager.load_session(session_id) { |
| 1821 | Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} |
| 1822 | Ok(_) => { |
| 1823 | return Err(ApiError::conflict( |
| 1824 | "Initial session identity already exists", |
| 1825 | )); |
| 1826 | } |
| 1827 | Err(error) => return Err(map_session_err(session_id, error, "read")), |
| 1828 | } |
| 1829 | let source = manager |
| 1830 | .expect_absent_session(session_id) |
| 1831 | .and_then(|source| { |
| 1832 | source.capture(codewhale_engine::session_manager::SessionWriteOwner::control()) |
| 1833 | }) |
| 1834 | .map_err(|error| ApiError::conflict(error.to_string()))?; |
| 1835 | let mut session = create_saved_session_with_id_and_mode( |
| 1836 | session_id.to_string(), |
| 1837 | &[], |
| 1838 | &detail.thread.model, |
| 1839 | &detail.thread.workspace, |
| 1840 | 0, |
| 1841 | None, |
| 1842 | Some(&detail.thread.mode), |
| 1843 | ); |
| 1844 | stamp_session_provider_from_thread(&runtime.read_config(), &detail, &mut session.metadata) |
| 1845 | .map_err(ApiError::bad_request)?; |
| 1846 | session.metadata.runtime_store = Some(runtime.session_store_binding()); |
| 1847 | session.write_receipt = Some(source); |
| 1848 | let publication = manager |
| 1849 | .publish_session(&session) |
| 1850 | .map_err(|error| map_session_err(session_id, error, "initialize"))?; |
| 1851 | session.adopt_publication(&publication); |
| 1852 | runtime |
| 1853 | .set_thread_session_checkpoint(thread_id, &session) |
| 1854 | .await |
| 1855 | .map_err(|error| { |
| 1856 | ApiError::internal(format!( |
| 1857 | "Initial session was saved but checkpoint binding failed: {error}" |
| 1858 | )) |
| 1859 | })?; |
| 1860 | Ok(()) |
| 1861 | } |
| 1862 |