| 1 | use std::path::PathBuf; |
| 2 | |
| 3 | use anyhow::Result |
| 4 | use rusqlite::{Connection |
| 5 | use serde_json::Value |
| 6 | |
| 7 | pub type DbConn |
| 8 | |
| 9 | #[allow(dead_code)] |
| 10 | #[derive(Clone |
| 11 | pub struct Session |
| 12 | pub id: i64 |
| 13 | pub uuid: String |
| 14 | pub name: String |
| 15 | pub provider: String |
| 16 | pub model: String |
| 17 | pub mode: String |
| 18 | pub created_at: i64 |
| 19 | pub updated_at: i64 |
| 20 | } |
| 21 | |
| 22 | /// One todo in a session's task list. Mirrors opencode's `Todo.Info` shape: |
| 23 | /// per-session rows of `content`/`status`/`priority` kept in a stable order. |
| 24 | #[derive(Debug |
| 25 | pub struct TodoItem |
| 26 | pub content: String |
| 27 | pub status: String |
| 28 | pub priority: String |
| 29 | } |
| 30 | |
| 31 | /// One long-running goal per session. Mirrors opencode's `/goal` plugin shape |
| 32 | /// (`.opencode/goals.json`): the session works autonomously across multiple |
| 33 | /// turns until the goal is `complete`, `blocked`, `paused`, or `cleared`. |
| 34 | #[derive(Debug |
| 35 | pub struct Goal |
| 36 | pub goal_id: String |
| 37 | pub objective: String |
| 38 | /// `active`, `paused`, `blocked`, `usage_limited` or `complete`. |
| 39 | pub status: String |
| 40 | pub time_used_seconds: i64 |
| 41 | pub iteration_count: i64 |
| 42 | pub time_created: i64 |
| 43 | pub time_updated: i64 |
| 44 | } |
| 45 | |
| 46 | #[allow(dead_code)] |
| 47 | #[derive(Clone |
| 48 | pub struct StoredMessage |
| 49 | pub id: i64 |
| 50 | pub session_id: i64 |
| 51 | pub role: String |
| 52 | pub content: Option |
| 53 | pub tool_call_id: Option |
| 54 | pub name: Option |
| 55 | pub tool_calls: Option |
| 56 | /// Raw `reasoning_content` streamed by a reasoning model (DeepSeek-style). |
| 57 | /// Providers that support thinking mode REQUIRE it to be passed back on |
| 58 | /// the next request's assistant message; dropping it breaks the turn. |
| 59 | pub reasoning: Option |
| 60 | pub images: Option |
| 61 | /// JSON-serialized `LlmUsage` of the assistant call that produced this |
| 62 | /// message (None for old rows / non-assistant messages). |
| 63 | pub usage: Option |
| 64 | /// On a `compaction` role row: id of the first message kept verbatim |
| 65 | /// (everything before it was summarized into `content`). |
| 66 | pub cut_msg_id: Option |
| 67 | pub created_at: i64 |
| 68 | } |
| 69 | |
| 70 | pub fn default_db_path() |
| 71 | if let Ok |
| 72 | && !p.trim |
| 73 | { |
| 74 | return PathBuf::from |
| 75 | } |
| 76 | let home = |
| 77 | PathBuf::from( |
| 78 | } |
| 79 | |
| 80 | pub fn open(path |
| 81 | if let Some |
| 82 | std::fs::create_dir_all |
| 83 | } |
| 84 | let conn = |
| 85 | conn.execute_batch( |
| 86 | "PRAGMA journal_mode=WAL; |
| 87 | PRAGMA foreign_keys=ON; |
| 88 | CREATE TABLE IF NOT EXISTS sessions ( |
| 89 | id INTEGER PRIMARY KEY AUTOINCREMENT, |
| 90 | name TEXT NOT NULL DEFAULT '', |
| 91 | provider TEXT NOT NULL, |
| 92 | model TEXT NOT NULL, |
| 93 | uuid TEXT, |
| 94 | created_at INTEGER NOT NULL, |
| 95 | updated_at INTEGER NOT NULL |
| 96 | ); |
| 97 | CREATE TABLE IF NOT EXISTS messages ( |
| 98 | id INTEGER PRIMARY KEY AUTOINCREMENT, |
| 99 | session_id INTEGER NOT NULL REFERENCES sessions(id) ON DELETE CASCADE, |
| 100 | role TEXT NOT NULL, |
| 101 | content TEXT, |
| 102 | tool_call_id TEXT, |
| 103 | name TEXT, |
| 104 | tool_calls TEXT, |
| 105 | reasoning_content TEXT, |
| 106 | created_at INTEGER NOT NULL |
| 107 | ); |
| 108 | CREATE INDEX IF NOT EXISTS idx_messages_session ON messages(session_id, id); |
| 109 | CREATE TABLE IF NOT EXISTS provider_configs ( |
| 110 | provider TEXT PRIMARY KEY, |
| 111 | config TEXT NOT NULL, |
| 112 | updated_at INTEGER NOT NULL |
| 113 | ); |
| 114 | CREATE TABLE IF NOT EXISTS file_backups ( |
| 115 | id INTEGER PRIMARY KEY AUTOINCREMENT, |
| 116 | session_id INTEGER NOT NULL REFERENCES sessions(id) ON DELETE CASCADE, |
| 117 | path TEXT NOT NULL, |
| 118 | kind TEXT NOT NULL, |
| 119 | backup_path TEXT, |
| 120 | msg_before INTEGER NOT NULL, |
| 121 | created_at INTEGER NOT NULL |
| 122 | ); |
| 123 | CREATE TABLE IF NOT EXISTS settings ( |
| 124 | key TEXT PRIMARY KEY, |
| 125 | value TEXT NOT NULL, |
| 126 | updated_at INTEGER NOT NULL |
| 127 | ); |
| 128 | CREATE TABLE IF NOT EXISTS todos ( |
| 129 | session_id INTEGER NOT NULL REFERENCES sessions(id) ON DELETE CASCADE, |
| 130 | content TEXT NOT NULL, |
| 131 | status TEXT NOT NULL, |
| 132 | priority TEXT NOT NULL, |
| 133 | position INTEGER NOT NULL, |
| 134 | PRIMARY KEY (session_id, position) |
| 135 | ); |
| 136 | CREATE TABLE IF NOT EXISTS goals ( |
| 137 | session_id INTEGER PRIMARY KEY REFERENCES sessions(id) ON DELETE CASCADE, |
| 138 | goal_id TEXT NOT NULL, |
| 139 | objective TEXT NOT NULL, |
| 140 | status TEXT NOT NULL, |
| 141 | time_used_seconds INTEGER NOT NULL, |
| 142 | iteration_count INTEGER NOT NULL, |
| 143 | time_created INTEGER NOT NULL, |
| 144 | time_updated INTEGER NOT NULL |
| 145 | ); |
| 146 | CREATE TABLE IF NOT EXISTS command_usage ( |
| 147 | command TEXT PRIMARY KEY, |
| 148 | count INTEGER NOT NULL DEFAULT 0, |
| 149 | updated_at INTEGER NOT NULL |
| 150 | ); |
| 151 | ", |
| 152 | )?; |
| 153 | migrate_sessions(&conn)? |
| 154 | migrate_sessions_mode(&conn)? |
| 155 | migrate_messages_images(&conn)? |
| 156 | migrate_messages_cut_msg_id(&conn)? |
| 157 | migrate_sessions_source(&conn)? |
| 158 | migrate_messages_reasoning(&conn)? |
| 159 | migrate_messages_usage(&conn)? |
| 160 | Ok(conn) |
| 161 | } |
| 162 | |
| 163 | fn migrate_messages_usage(conn: |
| 164 | let has = |
| 165 | let mut stmt |
| 166 | let mut rows |
| 167 | let mut found |
| 168 | while let Some |
| 169 | if row.get:: |
| 170 | found = true; |
| 171 | break; |
| 172 | } |
| 173 | } |
| 174 | found |
| 175 | }; |
| 176 | if !has { |
| 177 | conn.execute("ALTER TABLE messages ADD COLUMN usage_json TEXT |
| 178 | } |
| 179 | Ok(()) |
| 180 | } |
| 181 | |
| 182 | fn migrate_messages_reasoning(conn: |
| 183 | let has = |
| 184 | let mut stmt |
| 185 | let mut rows |
| 186 | let mut found |
| 187 | while let Some |
| 188 | if row.get:: |
| 189 | found = true; |
| 190 | break; |
| 191 | } |
| 192 | } |
| 193 | found |
| 194 | }; |
| 195 | if !has { |
| 196 | conn.execute("ALTER TABLE messages ADD COLUMN reasoning_content TEXT |
| 197 | } |
| 198 | Ok(()) |
| 199 | } |
| 200 | |
| 201 | fn migrate_messages_cut_msg_id(conn: |
| 202 | let has = |
| 203 | let mut stmt |
| 204 | let mut rows |
| 205 | let mut found |
| 206 | while let Some |
| 207 | if row.get:: |
| 208 | found = true; |
| 209 | break; |
| 210 | } |
| 211 | } |
| 212 | found |
| 213 | }; |
| 214 | if !has { |
| 215 | conn.execute("ALTER TABLE messages ADD COLUMN cut_msg_id INTEGER |
| 216 | } |
| 217 | Ok(()) |
| 218 | } |
| 219 | |
| 220 | fn migrate_sessions_mode(conn: |
| 221 | let has = |
| 222 | let mut stmt |
| 223 | let mut rows |
| 224 | let mut found |
| 225 | while let Some |
| 226 | if row.get:: |
| 227 | found = true; |
| 228 | break; |
| 229 | } |
| 230 | } |
| 231 | found |
| 232 | }; |
| 233 | if !has { |
| 234 | conn.execute( |
| 235 | "ALTER TABLE sessions ADD COLUMN mode TEXT NOT NULL DEFAULT 'auto'", |
| 236 | [], |
| 237 | )?; |
| 238 | } |
| 239 | Ok(()) |
| 240 | } |
| 241 | |
| 242 | fn migrate_messages_images(conn: |
| 243 | let has = |
| 244 | let mut stmt |
| 245 | let mut rows |
| 246 | let mut found |
| 247 | while let Some |
| 248 | if row.get:: |
| 249 | found = true; |
| 250 | break; |
| 251 | } |
| 252 | } |
| 253 | found |
| 254 | }; |
| 255 | if !has { |
| 256 | conn.execute("ALTER TABLE messages ADD COLUMN images TEXT |
| 257 | } |
| 258 | Ok(()) |
| 259 | } |
| 260 | |
| 261 | fn migrate_sessions(conn: |
| 262 | let has_uuid = |
| 263 | let mut stmt |
| 264 | let mut rows |
| 265 | let mut found |
| 266 | while let Some |
| 267 | if row.get:: |
| 268 | found = true; |
| 269 | break; |
| 270 | } |
| 271 | } |
| 272 | found |
| 273 | }; |
| 274 | if !has_uuid { |
| 275 | conn.execute("ALTER TABLE sessions ADD COLUMN uuid TEXT |
| 276 | } |
| 277 | let tx = |
| 278 | { |
| 279 | let mut stmt |
| 280 | let ids: Vec |
| 281 | .query_map([], |r |
| 282 | .collect::<rusqlite:: |
| 283 | for id in ids |
| 284 | tx.execute( |
| 285 | "UPDATE sessions SET uuid=?2 WHERE id=?1", |
| 286 | params![id, |
| 287 | )?; |
| 288 | } |
| 289 | } |
| 290 | tx.commit()?; |
| 291 | conn.execute( |
| 292 | "CREATE UNIQUE INDEX IF NOT EXISTS idx_sessions_uuid ON sessions(uuid)", |
| 293 | [], |
| 294 | )?; |
| 295 | Ok(()) |
| 296 | } |
| 297 | |
| 298 | fn migrate_sessions_source(conn: |
| 299 | let has = |
| 300 | let mut stmt |
| 301 | let mut rows |
| 302 | let mut found |
| 303 | while let Some |
| 304 | if row.get:: |
| 305 | found = true; |
| 306 | break; |
| 307 | } |
| 308 | } |
| 309 | found |
| 310 | }; |
| 311 | if !has { |
| 312 | conn.execute("ALTER TABLE sessions ADD COLUMN source TEXT |
| 313 | } |
| 314 | conn.execute( |
| 315 | "CREATE INDEX IF NOT EXISTS idx_sessions_source ON sessions(source)", |
| 316 | [], |
| 317 | )?; |
| 318 | Ok(()) |
| 319 | } |
| 320 | |
| 321 | pub fn create_session( |
| 322 | conn: &Connection |
| 323 | provider: &str |
| 324 | model: &str |
| 325 | name: Option |
| 326 | ) -> Result<( |
| 327 | let now = |
| 328 | let name = |
| 329 | let uuid = |
| 330 | conn.execute( |
| 331 | "INSERT INTO sessions (name, provider, model, mode, uuid, created_at, updated_at) VALUES (?1, ?2, ?3, 'auto', ?4, ?5, ?5)", |
| 332 | params![name, |
| 333 | )?; |
| 334 | Ok((conn. |
| 335 | } |
| 336 | |
| 337 | fn map_session(r: |
| 338 | Ok(Session |
| 339 | id: r.get |
| 340 | uuid: r.get |
| 341 | name: r.get |
| 342 | provider: r.get |
| 343 | model: r.get |
| 344 | mode: r.get |
| 345 | created_at: r.get |
| 346 | updated_at: r.get |
| 347 | }) |
| 348 | } |
| 349 | |
| 350 | pub fn get_session(conn |
| 351 | let mut stmt |
| 352 | "SELECT id, uuid, name, provider, model, mode, created_at, updated_at FROM sessions WHERE id=?1", |
| 353 | )?; |
| 354 | let mut rows |
| 355 | if let Some |
| 356 | Ok(Some |
| 357 | } else { |
| 358 | Ok(None |
| 359 | } |
| 360 | } |
| 361 | |
| 362 | pub fn get_session_by_uuid(conn |
| 363 | let mut stmt |
| 364 | let mut rows |
| 365 | if let Some |
| 366 | Ok(Some |
| 367 | } else { |
| 368 | Ok(None |
| 369 | } |
| 370 | } |
| 371 | |
| 372 | pub fn get_session_by_ref(conn |
| 373 | if let Some |
| 374 | return Ok(Some |
| 375 | } |
| 376 | if let Ok |
| 377 | return get_session(conn, |
| 378 | } |
| 379 | Ok(None |
| 380 | } |
| 381 | |
| 382 | pub fn list_sessions(conn |
| 383 | let mut stmt |
| 384 | let rows = |
| 385 | let mut out |
| 386 | for row in rows |
| 387 | out.push(row |
| 388 | } |
| 389 | Ok(out) |
| 390 | } |
| 391 | |
| 392 | pub fn delete_session(conn |
| 393 | let n = |
| 394 | Ok(n) |
| 395 | } |
| 396 | |
| 397 | /// Delete every session except `keep_id`. Returns how many sessions were removed. |
| 398 | pub fn delete_sessions_except(conn |
| 399 | let n = |
| 400 | Ok(n) |
| 401 | } |
| 402 | |
| 403 | /// Wipe all messages (and file backups) for a session, leaving the session row. |
| 404 | /// |
| 405 | /// The most recent `user` and `assistant` messages are preserved so an |
| 406 | /// in-flight turn can finish: a tool like `delete_chats` clears history |
| 407 | /// mid-turn, and wiping the current prompt would leave the agent with an empty |
| 408 | /// conversation (the next LLM call fails with "Empty input messages"). |
| 409 | /// Returns how many messages were deleted. |
| 410 | pub fn clear_session_messages(conn |
| 411 | let _ = |
| 412 | "DELETE FROM file_backups WHERE session_id=?1", |
| 413 | params![session_id], |
| 414 | )?; |
| 415 | let mut keep |
| 416 | { |
| 417 | let mut stmt |
| 418 | conn.prepare("SELECT id, role FROM messages WHERE session_id=?1 ORDER BY id |
| 419 | let rows = |
| 420 | Ok((r. |
| 421 | })?; |
| 422 | let mut last_user |
| 423 | let mut last_assistant |
| 424 | for row in rows |
| 425 | let (id, |
| 426 | match role.as_str() |
| 427 | "user" => { |
| 428 | last_user = Some |
| 429 | last_assistant = None |
| 430 | } |
| 431 | "assistant" if last_user |
| 432 | _ => {} |
| 433 | } |
| 434 | } |
| 435 | if let Some |
| 436 | keep.push(id |
| 437 | } |
| 438 | if let Some |
| 439 | keep.push(id |
| 440 | } |
| 441 | } |
| 442 | let n = |
| 443 | conn.execute( |
| 444 | "DELETE FROM messages WHERE session_id=?1", |
| 445 | params![session_id], |
| 446 | )? |
| 447 | } else { |
| 448 | let sql = |
| 449 | "DELETE FROM messages WHERE session_id=?1 AND id NOT IN ({})", |
| 450 | vec!["?"; |
| 451 | ); |
| 452 | let mut stmt |
| 453 | let mut params |
| 454 | for id in & |
| 455 | params.push(Box |
| 456 | } |
| 457 | stmt.execute(rusqlite |
| 458 | params.iter().map |
| 459 | ))? |
| 460 | }; |
| 461 | touch_session(conn, session_id |
| 462 | Ok(n) |
| 463 | } |
| 464 | |
| 465 | /// Count sessions currently stored. |
| 466 | pub fn count_sessions(conn |
| 467 | let n: i64 |
| 468 | Ok(n |
| 469 | } |
| 470 | |
| 471 | pub fn update_session_model(conn |
| 472 | let now = |
| 473 | conn.execute( |
| 474 | "UPDATE sessions SET provider=?2, model=?3, updated_at=?4 WHERE id=?1", |
| 475 | params![id, |
| 476 | )?; |
| 477 | Ok(()) |
| 478 | } |
| 479 | |
| 480 | pub fn touch_session(conn |
| 481 | let now = |
| 482 | conn.execute( |
| 483 | "UPDATE sessions SET updated_at=?2 WHERE id=?1", |
| 484 | params![id, |
| 485 | )?; |
| 486 | Ok(()) |
| 487 | } |
| 488 | |
| 489 | pub fn set_session_name(conn |
| 490 | conn.execute("UPDATE sessions SET name=?2 WHERE id=?1 |
| 491 | Ok(()) |
| 492 | } |
| 493 | |
| 494 | /// The agent mode the session was last left in (one of mode::Mode::name()). |
| 495 | pub fn get_session_mode(conn |
| 496 | let m = |
| 497 | r.get(0) |
| 498 | })?; |
| 499 | Ok(m) |
| 500 | } |
| 501 | |
| 502 | pub fn set_session_mode(conn |
| 503 | let now = |
| 504 | conn.execute( |
| 505 | "UPDATE sessions SET mode=?2, updated_at=?3 WHERE id=?1", |
| 506 | params![id, |
| 507 | )?; |
| 508 | Ok(()) |
| 509 | } |
| 510 | |
| 511 | /// Replace the session's entire todo list (opencode semantics: delete all rows |
| 512 | /// for the session, then re-insert the new list in order). An empty list wipes |
| 513 | /// the todos. |
| 514 | pub fn set_todos(conn |
| 515 | let tx = |
| 516 | tx.execute("DELETE FROM todos WHERE session_id=?1 |
| 517 | for (pos, t |
| 518 | tx.execute( |
| 519 | "INSERT INTO todos (session_id, content, status, priority, position) VALUES (?1,?2,?3,?4,?5)", |
| 520 | params![session_id, |
| 521 | )?; |
| 522 | } |
| 523 | tx.commit()?; |
| 524 | Ok(()) |
| 525 | } |
| 526 | |
| 527 | /// The session's current todo list in list order. Empty when none were set. |
| 528 | pub fn get_todos(conn |
| 529 | let mut stmt |
| 530 | "SELECT content, status, priority FROM todos WHERE session_id=?1 ORDER BY position", |
| 531 | )?; |
| 532 | let rows = |
| 533 | Ok(TodoItem |
| 534 | content: r.get |
| 535 | status: r.get |
| 536 | priority: r.get |
| 537 | }) |
| 538 | })?; |
| 539 | let mut out |
| 540 | for row in rows |
| 541 | out.push(row |
| 542 | } |
| 543 | Ok(out) |
| 544 | } |
| 545 | |
| 546 | /// The session's current goal, or `None` when none is set. |
| 547 | pub fn get_goal(conn |
| 548 | let mut stmt |
| 549 | "SELECT goal_id, objective, status, time_used_seconds, iteration_count, time_created, time_updated |
| 550 | FROM goals WHERE session_id=?1", |
| 551 | )?; |
| 552 | let mut rows |
| 553 | Ok(Goal |
| 554 | goal_id: r.get |
| 555 | objective: r.get |
| 556 | status: r.get |
| 557 | time_used_seconds: r.get |
| 558 | iteration_count: r.get |
| 559 | time_created: r.get |
| 560 | time_updated: r.get |
| 561 | }) |
| 562 | })?; |
| 563 | match rows.next() |
| 564 | Some(row) |
| 565 | None => Ok |
| 566 | } |
| 567 | } |
| 568 | |
| 569 | /// Insert or replace the session's goal (one goal per session). |
| 570 | pub fn set_goal(conn |
| 571 | conn.execute( |
| 572 | "INSERT INTO goals (session_id, goal_id, objective, status, time_used_seconds, iteration_count, time_created, time_updated) |
| 573 | VALUES (?1,?2,?3,?4,?5,?6,?7,?8) |
| 574 | ON CONFLICT(session_id) DO UPDATE SET |
| 575 | goal_id=excluded.goal_id, |
| 576 | objective=excluded.objective, |
| 577 | status=excluded.status, |
| 578 | time_used_seconds=excluded.time_used_seconds, |
| 579 | iteration_count=excluded.iteration_count, |
| 580 | time_created=excluded.time_created, |
| 581 | time_updated=excluded.time_updated", |
| 582 | params![ |
| 583 | session_id, |
| 584 | goal.goal_id, |
| 585 | goal.objective, |
| 586 | goal.status, |
| 587 | goal.time_used_seconds, |
| 588 | goal.iteration_count, |
| 589 | goal.time_created, |
| 590 | goal.time_updated, |
| 591 | ], |
| 592 | )?; |
| 593 | Ok(()) |
| 594 | } |
| 595 | |
| 596 | /// Delete the session's goal. Returns true when a goal was actually removed. |
| 597 | pub fn clear_goal(conn |
| 598 | let n = |
| 599 | Ok(n |
| 600 | } |
| 601 | |
| 602 | /// Find an imported session by its source marker (e.g. `claude-code:/abs/path`). |
| 603 | pub fn get_session_by_source(conn |
| 604 | Ok(conn |
| 605 | .query_row( |
| 606 | "SELECT id FROM sessions WHERE source=?1", |
| 607 | params![source], |
| 608 | |r| r. |
| 609 | ) |
| 610 | .optional()?) |
| 611 | } |
| 612 | |
| 613 | pub fn set_session_source(conn |
| 614 | conn.execute( |
| 615 | "UPDATE sessions SET source=?2 WHERE id=?1", |
| 616 | params![id, |
| 617 | )?; |
| 618 | Ok(()) |
| 619 | } |
| 620 | |
| 621 | /// Delete every message (and file backup) for a session, keeping the row so an |
| 622 | /// imported session can be refreshed in place (uuid stays stable). |
| 623 | pub fn delete_all_messages(conn |
| 624 | let _ = |
| 625 | "DELETE FROM file_backups WHERE session_id=?1", |
| 626 | params![session_id], |
| 627 | )?; |
| 628 | conn.execute( |
| 629 | "DELETE FROM messages WHERE session_id=?1", |
| 630 | params![session_id], |
| 631 | )?; |
| 632 | Ok(()) |
| 633 | } |
| 634 | |
| 635 | pub fn update_session_meta( |
| 636 | conn: &Connection |
| 637 | id: i64 |
| 638 | name: &str |
| 639 | provider: &str |
| 640 | model: &str |
| 641 | ) -> Result<() |
| 642 | let now = |
| 643 | conn.execute( |
| 644 | "UPDATE sessions SET name=?2, provider=?3, model=?4, updated_at=?5 WHERE id=?1", |
| 645 | params![id, |
| 646 | )?; |
| 647 | Ok(()) |
| 648 | } |
| 649 | |
| 650 | #[allow(clippy:: |
| 651 | pub fn add_message( |
| 652 | conn: &Connection |
| 653 | session_id: i64 |
| 654 | role: &str |
| 655 | content: Option |
| 656 | tool_call_id: Option |
| 657 | name: Option |
| 658 | tool_calls: Option |
| 659 | images: Option |
| 660 | reasoning: Option |
| 661 | usage: Option |
| 662 | ) -> Result<i64 |
| 663 | let now = |
| 664 | conn.execute( |
| 665 | "INSERT INTO messages (session_id, role, content, tool_call_id, name, tool_calls, reasoning_content, images, usage_json, created_at) VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10)", |
| 666 | params![session_id, |
| 667 | )?; |
| 668 | Ok(conn. |
| 669 | } |
| 670 | |
| 671 | pub fn get_messages(conn |
| 672 | let mut stmt |
| 673 | "SELECT id, session_id, role, content, tool_call_id, name, tool_calls, reasoning_content, images, usage_json, cut_msg_id, created_at FROM messages WHERE session_id=?1 ORDER BY id", |
| 674 | )?; |
| 675 | let rows = |
| 676 | Ok(StoredMessage |
| 677 | id: r.get |
| 678 | session_id: r.get |
| 679 | role: r.get |
| 680 | content: r.get |
| 681 | tool_call_id: r.get |
| 682 | name: r.get |
| 683 | tool_calls: r.get |
| 684 | reasoning: r.get |
| 685 | images: r.get |
| 686 | usage: r.get |
| 687 | cut_msg_id: r.get |
| 688 | created_at: r.get |
| 689 | }) |
| 690 | })?; |
| 691 | let mut out |
| 692 | for row in rows |
| 693 | out.push(row |
| 694 | } |
| 695 | Ok(out) |
| 696 | } |
| 697 | |
| 698 | /// Insert a compaction marker: a `compaction` row whose `content` is the |
| 699 | /// structured summary and `cut_msg_id` the first message that stays verbatim. |
| 700 | pub fn add_compaction( |
| 701 | conn: &Connection |
| 702 | session_id: i64 |
| 703 | summary: &str |
| 704 | cut_msg_id: i64 |
| 705 | ) -> Result<i64 |
| 706 | let now = |
| 707 | conn.execute( |
| 708 | "INSERT INTO messages (session_id, role, content, tool_call_id, name, tool_calls, images, cut_msg_id, created_at) VALUES (?1,'compaction',?2,NULL,NULL,NULL,NULL,?3,?4)", |
| 709 | params![session_id, |
| 710 | )?; |
| 711 | Ok(conn. |
| 712 | } |
| 713 | |
| 714 | pub fn current_message_id(conn |
| 715 | let id: Option |
| 716 | .query_row( |
| 717 | "SELECT MAX(id) FROM messages WHERE session_id=?1", |
| 718 | params![session_id], |
| 719 | |r| r. |
| 720 | ) |
| 721 | .optional()?; |
| 722 | Ok(id. |
| 723 | } |
| 724 | |
| 725 | pub fn revert_messages( |
| 726 | conn: &Connection |
| 727 | session_id: i64 |
| 728 | upto_msg_id: i64 |
| 729 | ) -> Result<Vec |
| 730 | let all = |
| 731 | let deleted: Vec |
| 732 | let tx = |
| 733 | tx.execute( |
| 734 | "DELETE FROM messages WHERE session_id=?1 AND id>=?2", |
| 735 | params![session_id, |
| 736 | )?; |
| 737 | tx.commit()?; |
| 738 | Ok(deleted) |
| 739 | } |
| 740 | |
| 741 | pub fn copy_messages_up_to( |
| 742 | conn: &Connection |
| 743 | src_session: i64 |
| 744 | dst_session: i64 |
| 745 | upto_msg_id: i64 |
| 746 | ) -> Result<() |
| 747 | let msgs = |
| 748 | let tx = |
| 749 | for m in msgs |
| 750 | if m.id > |
| 751 | continue; |
| 752 | } |
| 753 | tx.execute( |
| 754 | "INSERT INTO messages (session_id, role, content, tool_call_id, name, tool_calls, images, cut_msg_id, created_at) VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9)", |
| 755 | params![ |
| 756 | dst_session, |
| 757 | m.role, |
| 758 | m.content, |
| 759 | m.tool_call_id, |
| 760 | m.name, |
| 761 | m.tool_calls, |
| 762 | m.images, |
| 763 | m.cut_msg_id, |
| 764 | m.created_at |
| 765 | ], |
| 766 | )?; |
| 767 | } |
| 768 | tx.commit()?; |
| 769 | Ok(()) |
| 770 | } |
| 771 | |
| 772 | pub fn record_file_backup( |
| 773 | conn: &Connection |
| 774 | session_id: i64 |
| 775 | path: &str |
| 776 | kind: &str |
| 777 | backup_path: Option |
| 778 | ) -> Result<() |
| 779 | let now = |
| 780 | let msg_before = |
| 781 | conn.execute( |
| 782 | "INSERT INTO file_backups (session_id, path, kind, backup_path, msg_before, created_at) VALUES (?1,?2,?3,?4,?5,?6)", |
| 783 | params![session_id, |
| 784 | )?; |
| 785 | Ok(()) |
| 786 | } |
| 787 | |
| 788 | pub fn restore_file_backups(conn |
| 789 | let mut stmt |
| 790 | "SELECT id, path, kind, backup_path FROM file_backups WHERE session_id=?1 AND msg_before>=?2 ORDER BY id DESC", |
| 791 | )?; |
| 792 | let rows = |
| 793 | Ok(( |
| 794 | r.get::<_ |
| 795 | r.get::<_ |
| 796 | r.get::<_ |
| 797 | )) |
| 798 | })?; |
| 799 | let mut affected |
| 800 | for row in rows |
| 801 | affected.push(row |
| 802 | } |
| 803 | let mut count |
| 804 | for (path, kind |
| 805 | match kind.as_str() |
| 806 | "created" => { |
| 807 | if std::fs |
| 808 | count += 1; |
| 809 | } |
| 810 | } |
| 811 | "before" | "deleted" |
| 812 | if let Some |
| 813 | && let Ok |
| 814 | && let Some |
| 815 | { |
| 816 | let _ = |
| 817 | if std::fs |
| 818 | count += 1; |
| 819 | } |
| 820 | } |
| 821 | } |
| 822 | _ => {} |
| 823 | } |
| 824 | } |
| 825 | conn.execute( |
| 826 | "DELETE FROM file_backups WHERE session_id=?1 AND msg_before>=?2", |
| 827 | params![session_id, |
| 828 | )?; |
| 829 | for (_, _ |
| 830 | if let Some |
| 831 | let _ = |
| 832 | } |
| 833 | } |
| 834 | Ok(count) |
| 835 | } |
| 836 | |
| 837 | pub fn backup_dir(session_id |
| 838 | let home = |
| 839 | std::path::PathBuf |
| 840 | .join(".wynba") |
| 841 | .join("backups") |
| 842 | .join(session_id.to_string |
| 843 | } |
| 844 | |
| 845 | use rusqlite::OptionalExtension |
| 846 | |
| 847 | pub fn set_provider_config(conn |
| 848 | let now = |
| 849 | let s = |
| 850 | conn.execute( |
| 851 | "INSERT INTO provider_configs (provider, config, updated_at) VALUES (?1, ?2, ?3) |
| 852 | ON CONFLICT(provider) DO UPDATE SET config=excluded.config, updated_at=excluded.updated_at", |
| 853 | params![provider, |
| 854 | )?; |
| 855 | Ok(()) |
| 856 | } |
| 857 | |
| 858 | pub fn get_provider_config(conn |
| 859 | let mut stmt |
| 860 | let mut rows |
| 861 | if let Some |
| 862 | Ok(serde_json:: |
| 863 | } else { |
| 864 | Ok(None |
| 865 | } |
| 866 | } |
| 867 | |
| 868 | pub fn delete_provider_config(conn |
| 869 | Ok(conn. |
| 870 | "DELETE FROM provider_configs WHERE provider=?1", |
| 871 | params![provider], |
| 872 | )?) |
| 873 | } |
| 874 | |
| 875 | pub fn list_provider_configs(conn |
| 876 | let mut stmt |
| 877 | let rows = |
| 878 | let provider: String |
| 879 | let config: String |
| 880 | Ok((provider, |
| 881 | })?; |
| 882 | let mut out |
| 883 | for row in rows |
| 884 | let (provider, |
| 885 | if let Ok |
| 886 | out.push((provider |
| 887 | } |
| 888 | } |
| 889 | Ok(out) |
| 890 | } |
| 891 | |
| 892 | pub fn set_setting(conn |
| 893 | let now = |
| 894 | conn.execute( |
| 895 | "INSERT INTO settings (key, value, updated_at) VALUES (?1, ?2, ?3) |
| 896 | ON CONFLICT(key) DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at", |
| 897 | params![key, |
| 898 | )?; |
| 899 | Ok(()) |
| 900 | } |
| 901 | |
| 902 | pub fn get_setting(conn |
| 903 | let mut stmt |
| 904 | let mut rows |
| 905 | match rows.next() |
| 906 | Some(row) |
| 907 | None => Ok |
| 908 | } |
| 909 | } |
| 910 | |
| 911 | /// Remember which provider `/connect` last set up. Fresh sessions resolve to |
| 912 | /// it (and its stored default model) unless overridden, so connecting a |
| 913 | /// provider "just works" on the next launch. An empty value clears the default. |
| 914 | pub fn set_default_provider(conn |
| 915 | set_setting(conn, " |
| 916 | } |
| 917 | |
| 918 | pub fn get_default_provider(conn |
| 919 | Ok(get_setting( |
| 920 | } |
| 921 | |
| 922 | /// Remember the model (and its provider) the user last switched to with |
| 923 | /// `/model`. Fresh sessions and new launches resolve to it, so a switch |
| 924 | /// outlives the session. `model` may be empty to clear the memory. |
| 925 | pub fn set_last_model(conn |
| 926 | if model.is_empty() |
| 927 | set_setting(conn, " |
| 928 | set_setting(conn, " |
| 929 | } else { |
| 930 | set_setting(conn, " |
| 931 | set_setting(conn, " |
| 932 | } |
| 933 | } |
| 934 | |
| 935 | /// The provider + model of the last `/model` switch, if any. |
| 936 | pub fn get_last_model(conn |
| 937 | let Some( |
| 938 | else { |
| 939 | return Ok(None |
| 940 | }; |
| 941 | let Some( |
| 942 | return Ok(None |
| 943 | }; |
| 944 | Ok(Some |
| 945 | } |
| 946 | |
| 947 | /// Record that a slash command was executed, bumping its usage counter. |
| 948 | /// `command` is the bare command name (e.g. "/model"). |
| 949 | pub fn record_command_usage(conn |
| 950 | let now = |
| 951 | conn.execute( |
| 952 | "INSERT INTO command_usage (command, count, updated_at) VALUES (?1, 1, ?2) |
| 953 | ON CONFLICT(command) DO UPDATE SET |
| 954 | count = count + 1, |
| 955 | updated_at = excluded.updated_at", |
| 956 | params![command, |
| 957 | )?; |
| 958 | Ok(()) |
| 959 | } |
| 960 | |
| 961 | /// How many times each command has been executed, keyed by command name. |
| 962 | /// Commands that were never run are simply absent from the map. |
| 963 | pub fn command_usage_counts(conn |
| 964 | let mut stmt |
| 965 | let rows = |
| 966 | let mut counts |
| 967 | for row in rows |
| 968 | let (cmd, |
| 969 | counts.insert(cmd |
| 970 | } |
| 971 | Ok(counts) |
| 972 | } |
| 973 | |
| 974 | #[cfg(test)] |
| 975 | mod tests { |
| 976 | use super::*; |
| 977 | |
| 978 | fn temp_db(name: |
| 979 | let path = |
| 980 | "wynba-db-test-{}-{name}.sqlite" |
| 981 | std::process::id |
| 982 | )); |
| 983 | let _ = |
| 984 | let conn = |
| 985 | (path, conn) |
| 986 | } |
| 987 | |
| 988 | #[test] |
| 989 | fn session_name_round_trips() { |
| 990 | let (path, |
| 991 | let (sid, |
| 992 | assert_eq!(get_session( |
| 993 | set_session_name(&conn, |
| 994 | assert_eq!( |
| 995 | get_session(&conn, |
| 996 | "my awesome session" |
| 997 | ); |
| 998 | let listed = |
| 999 | assert_eq!(listed[0 |
| 1000 | let _ = |
| 1001 | } |
| 1002 | |
| 1003 | #[test] |
| 1004 | fn sessions_default_to_auto_mode() { |
| 1005 | let (path, |
| 1006 | let (sid, |
| 1007 | assert_eq!(get_session_mode( |
| 1008 | assert_eq!(get_session( |
| 1009 | let _ = |
| 1010 | } |
| 1011 | |
| 1012 | #[test] |
| 1013 | fn mode_round_trips_and_is_persisted() { |
| 1014 | let (path, |
| 1015 | let (sid, |
| 1016 | set_session_mode(&conn, |
| 1017 | assert_eq!(get_session_mode( |
| 1018 | let session = |
| 1019 | assert_eq!(session. |
| 1020 | let listed = |
| 1021 | assert_eq!(listed[0 |
| 1022 | let _ = |
| 1023 | } |
| 1024 | |
| 1025 | #[test] |
| 1026 | fn mode_survives_reopen_after_migration() { |
| 1027 | let (path, |
| 1028 | let (sid, |
| 1029 | set_session_mode(&conn, |
| 1030 | drop(conn); |
| 1031 | // Reopening re-runs the migrations; mode must not be lost or reset. |
| 1032 | let conn = |
| 1033 | assert_eq!(get_session_mode( |
| 1034 | let _ = |
| 1035 | } |
| 1036 | |
| 1037 | #[test] |
| 1038 | fn default_provider_setting_round_trips_and_clears() { |
| 1039 | let (path, |
| 1040 | assert_eq!(get_default_provider( |
| 1041 | set_default_provider(&conn, |
| 1042 | assert_eq!(get_default_provider( |
| 1043 | // Clearing with an empty value is treated as "no default". |
| 1044 | set_default_provider(&conn, |
| 1045 | assert_eq!(get_default_provider( |
| 1046 | let _ = |
| 1047 | } |
| 1048 | |
| 1049 | #[test] |
| 1050 | fn todos_round_trip_in_list_order() { |
| 1051 | let (path, |
| 1052 | let (sid, |
| 1053 | let todos = |
| 1054 | TodoItem { |
| 1055 | content: "first". |
| 1056 | status: "in_progress". |
| 1057 | priority: "high". |
| 1058 | }, |
| 1059 | TodoItem { |
| 1060 | content: "second". |
| 1061 | status: "pending". |
| 1062 | priority: "low". |
| 1063 | }, |
| 1064 | ]; |
| 1065 | set_todos(&conn, |
| 1066 | assert_eq!(get_todos( |
| 1067 | let _ = |
| 1068 | } |
| 1069 | |
| 1070 | #[test] |
| 1071 | fn todos_are_per_session_and_replaced() { |
| 1072 | let (path, |
| 1073 | let (a, |
| 1074 | let (b, |
| 1075 | set_todos( |
| 1076 | &conn, |
| 1077 | a, |
| 1078 | &[TodoItem { |
| 1079 | content: "a". |
| 1080 | status: "pending". |
| 1081 | priority: "low". |
| 1082 | }], |
| 1083 | ) |
| 1084 | .unwrap(); |
| 1085 | set_todos( |
| 1086 | &conn, |
| 1087 | b, |
| 1088 | &[TodoItem { |
| 1089 | content: "b". |
| 1090 | status: "completed". |
| 1091 | priority: "medium". |
| 1092 | }], |
| 1093 | ) |
| 1094 | .unwrap(); |
| 1095 | assert_eq!(get_todos( |
| 1096 | assert_eq!(get_todos( |
| 1097 | // Updating replaces the list wholesale (opencode semantics). |
| 1098 | set_todos(&conn, |
| 1099 | assert!(get_todos( |
| 1100 | assert_eq!(get_todos( |
| 1101 | let _ = |
| 1102 | } |
| 1103 | |
| 1104 | #[test] |
| 1105 | fn todos_cascade_with_session_delete() { |
| 1106 | let (path, |
| 1107 | let (sid, |
| 1108 | set_todos( |
| 1109 | &conn, |
| 1110 | sid, |
| 1111 | &[TodoItem { |
| 1112 | content: "x". |
| 1113 | status: "pending". |
| 1114 | priority: "low". |
| 1115 | }], |
| 1116 | ) |
| 1117 | .unwrap(); |
| 1118 | delete_session(&conn, |
| 1119 | assert!(get_todos( |
| 1120 | let _ = |
| 1121 | } |
| 1122 | |
| 1123 | fn make_goal(objective: |
| 1124 | Goal { |
| 1125 | goal_id: "g-1". |
| 1126 | objective: objective.into |
| 1127 | status: "active". |
| 1128 | time_used_seconds: 0, |
| 1129 | iteration_count: 0, |
| 1130 | time_created: 1, |
| 1131 | time_updated: 1, |
| 1132 | } |
| 1133 | } |
| 1134 | |
| 1135 | #[test] |
| 1136 | fn goal_absent_by_default_and_clear_is_noop() { |
| 1137 | let (path, |
| 1138 | let (sid, |
| 1139 | assert!(get_goal( |
| 1140 | assert!(!clear_goal |
| 1141 | let _ = |
| 1142 | } |
| 1143 | |
| 1144 | #[test] |
| 1145 | fn goal_round_trips_with_all_fields() { |
| 1146 | let (path, |
| 1147 | let (sid, |
| 1148 | let goal = |
| 1149 | goal_id: "g-1". |
| 1150 | objective: "fix the login". |
| 1151 | status: "active". |
| 1152 | time_used_seconds: 125, |
| 1153 | iteration_count: 3, |
| 1154 | time_created: 10, |
| 1155 | time_updated: 20, |
| 1156 | }; |
| 1157 | set_goal(&conn, |
| 1158 | assert_eq!(get_goal( |
| 1159 | let _ = |
| 1160 | } |
| 1161 | |
| 1162 | #[test] |
| 1163 | fn goal_is_per_session_and_replaceable() { |
| 1164 | let (path, |
| 1165 | let (a, |
| 1166 | let (b, |
| 1167 | set_goal(&conn, |
| 1168 | set_goal(&conn, |
| 1169 | assert_eq!(get_goal( |
| 1170 | assert_eq!(get_goal( |
| 1171 | // Replace the existing goal in place (same session, no duplicate row). |
| 1172 | let updated = |
| 1173 | goal_id: "g-2". |
| 1174 | objective: "new objective". |
| 1175 | status: "paused". |
| 1176 | time_used_seconds: 60, |
| 1177 | iteration_count: 1, |
| 1178 | time_created: 1, |
| 1179 | time_updated: 99, |
| 1180 | }; |
| 1181 | set_goal(&conn, |
| 1182 | assert_eq!(get_goal( |
| 1183 | assert_eq!(get_goal( |
| 1184 | let _ = |
| 1185 | } |
| 1186 | |
| 1187 | #[test] |
| 1188 | fn goal_clear_removes_only_that_session() { |
| 1189 | let (path, |
| 1190 | let (a, |
| 1191 | let (b, |
| 1192 | set_goal(&conn, |
| 1193 | set_goal(&conn, |
| 1194 | assert!(clear_goal( |
| 1195 | assert!(get_goal( |
| 1196 | assert_eq!(get_goal( |
| 1197 | let _ = |
| 1198 | } |
| 1199 | |
| 1200 | #[test] |
| 1201 | fn goal_cascade_with_session_delete() { |
| 1202 | let (path, |
| 1203 | let (sid, |
| 1204 | set_goal(&conn, |
| 1205 | delete_session(&conn, |
| 1206 | assert!(get_goal( |
| 1207 | let _ = |
| 1208 | } |
| 1209 | |
| 1210 | #[test] |
| 1211 | fn command_usage_counts_and_increments() { |
| 1212 | let (path, |
| 1213 | assert!(command_usage_counts( |
| 1214 | |
| 1215 | record_command_usage(&conn, |
| 1216 | record_command_usage(&conn, |
| 1217 | record_command_usage(&conn, |
| 1218 | record_command_usage(&conn, |
| 1219 | |
| 1220 | let counts = |
| 1221 | assert_eq!(counts. |
| 1222 | assert_eq!(counts. |
| 1223 | assert_eq!(counts. |
| 1224 | let _ = |
| 1225 | } |
| 1226 | } |