From 081b1c27b243893bb585e8052ee5ad67712dd1bd Mon Sep 17 00:00:00 2001 From: Michael Ledin Date: Tue, 24 Nov 2026 17:37:35 +0300 Subject: [PATCH 1/8] fix(hosts): read OpenCode 2.4 replies from session_part rows OpenCode 2.4 writes each part as its own session_part row and leaves the assistant payload's content empty, so the reply list showed nothing for new sessions and lost the newest replies on resumed ones. Decide the source per reply: text in session_message.data.content wins, and a reply without visible text falls back to its text parts in ordinal order. The part table is checked once per read and its statement reused per message; a database without the table still reads the payload alone. --- crates/plannotator-tui-hosts/src/opencode.rs | 62 ++++++++- .../plannotator-tui-hosts/tests/opencode.rs | 118 ++++++++++++++++++ 2 files changed, 177 insertions(+), 3 deletions(-) diff --git a/crates/plannotator-tui-hosts/src/opencode.rs b/crates/plannotator-tui-hosts/src/opencode.rs index 29f952b3..5ffdf15d 100644 --- a/crates/plannotator-tui-hosts/src/opencode.rs +++ b/crates/plannotator-tui-hosts/src/opencode.rs @@ -18,6 +18,11 @@ //! assistant, `text` for a user). Other channels use `opencode-.db` next to it //! (`packages/cli/src/server-process.ts`). A v1 session and a v2 session can therefore both //! match one directory; the newest wins, whichever schema and file it lives in. +//! +//! `OpenCode` 2.4 (migration `20261029002625_session_part`) writes each part as its own +//! `session_part` row (`message_id`, `session_id`, `ordinal`, `type`, `data`) and leaves the +//! assistant payload's `content` empty. The text of such a reply is its `text` parts in +//! `ordinal` order. A reply keeps whichever format carries its text; the two are never mixed. use std::path::Path; @@ -198,9 +203,25 @@ fn messages_v1(db: &Path, session_id: &str, n: usize) -> Result, Ho Ok(messages) } -/// `OpenCode` 2: one `session_message` row per message; the payload carries the text directly. +/// `OpenCode` 2: one `session_message` row per message; the payload carries the text directly, +/// or, since 2.4 writes each part as its own row, in the message's `session_part` rows. fn messages_v2(db: &Path, session_id: &str, n: usize) -> Result, HostError> { let connection = open_read_only(db, WHAT)?; + // The part table arrived in 2.4; a database written before it has none, and the message + // payload is then the only source. Checked once, the prepared statement serves every row. + let mut parts = if has_table(&connection, "session_part")? { + Some( + connection + .prepare( + "SELECT data FROM session_part \ + WHERE session_id = ?1 AND message_id = ?2 AND type = 'text' \ + ORDER BY ordinal ASC", + ) + .map_err(|e| sql_error(WHAT, &e))?, + ) + } else { + None + }; let mut statement = connection .prepare( "SELECT id, type, data, time_created FROM session_message \ @@ -227,7 +248,7 @@ fn messages_v2(db: &Path, session_id: &str, n: usize) -> Result, Ho let Ok(json) = serde_json::from_str::(&data) else { continue }; let (role, text) = match kind.as_str() { "assistant" => { - let parts: Vec<&str> = json + let blocks: Vec<&str> = json .get("content") .and_then(serde_json::Value::as_array) .map(|items| { @@ -239,7 +260,18 @@ fn messages_v2(db: &Path, session_id: &str, n: usize) -> Result, Ho .collect() }) .unwrap_or_default(); - (Role::Assistant, parts.join("\n\n")) + let payload = blocks.join("\n\n"); + // The format is decided per reply: text in the payload wins, and only a reply + // without visible text falls back to its parts. Never both, never repeated. + let text = if payload.trim().is_empty() { + match parts_for_message(&mut parts, session_id, &id)? { + Some(text) => text, + None => payload, + } + } else { + payload + }; + (Role::Assistant, text) } "user" => (Role::Human, json.get("text").and_then(|t| t.as_str()).unwrap_or_default().to_owned()), _ => continue, @@ -263,6 +295,30 @@ fn messages_v2(db: &Path, session_id: &str, n: usize) -> Result, Ho Ok(messages) } +/// The part reader for one session: a statement prepared once and reused per message id. +type PartStatement<'connection> = rusqlite::Statement<'connection>; + +/// The visible text of a reply's `session_part` rows, joined in `ordinal` order, or `None` when +/// the reply has no visible text there. Tool calls, reasoning and injected parts are not text. +fn parts_for_message( + statement: &mut Option>, + session_id: &str, + message_id: &str, +) -> Result, HostError> { + let Some(statement) = statement.as_mut() else { return Ok(None) }; + let rows = statement + .query_map(params![session_id, message_id], |row| row.get::<_, String>(0)) + .map_err(|e| sql_error(WHAT, &e))?; + let mut parts = Vec::new(); + for row in rows { + let data = row.map_err(|e| sql_error(WHAT, &e))?; + if let Some(text) = part_text(&data) { + parts.push(text); + } + } + Ok((!parts.is_empty()).then(|| parts.join("\n\n"))) +} + /// How many of `messages` are assistant replies: `n` counts those, not prompts. fn replies(messages: &[Message]) -> usize { messages.iter().filter(|message| message.role == Role::Assistant).count() diff --git a/crates/plannotator-tui-hosts/tests/opencode.rs b/crates/plannotator-tui-hosts/tests/opencode.rs index 43337e81..b0b44866 100644 --- a/crates/plannotator-tui-hosts/tests/opencode.rs +++ b/crates/plannotator-tui-hosts/tests/opencode.rs @@ -31,6 +31,15 @@ CREATE TABLE session_message (id TEXT PRIMARY KEY, session_id TEXT NOT NULL, typ CREATE UNIQUE INDEX session_message_session_seq_idx ON session_message (session_id, seq); "; +/// `OpenCode` 2.4 split a message's payload: one `session_part` row per part, ordered by +/// `ordinal`. `packages/core/src/session/sql.ts`, migration `20261029002625_session_part`. +const SCHEMA_V2_PARTS: &str = " +CREATE TABLE session_part (message_id TEXT NOT NULL, session_id TEXT NOT NULL, ordinal INTEGER NOT NULL, + type TEXT NOT NULL, call_id TEXT, time_created INTEGER NOT NULL, time_updated INTEGER NOT NULL, + data TEXT NOT NULL, CONSTRAINT session_part_pk PRIMARY KEY(message_id, ordinal)); +CREATE INDEX session_part_session_message_idx ON session_part (session_id, message_id, ordinal); +"; + /// Current `OpenCode` writes this table alongside the legacy message/part tables while the /// session row remains in `session`. const CURRENT_SESSION_MESSAGE: &str = " @@ -136,6 +145,115 @@ fn an_opencode2_session_in_the_same_database_wins_when_it_is_newer() { std::fs::remove_dir_all(&dir).expect("cleanup"); } +fn part_v2(c: &Connection, message: &str, session: &str, ordinal: i64, kind: &str, data: &str) { + c.execute( + "INSERT INTO session_part (message_id, session_id, ordinal, type, time_created, time_updated, data) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?5, ?6)", + params![message, session, ordinal, kind, ordinal + 1, data], + ) + .expect("session_part"); +} + +/// A `OpenCode` 2.4 session whose replies are split between the message payload and +/// `session_part` rows, as after the part-table migration: one reply in each format, one in +/// both, a reasoning-only turn, and a prompt between them. +fn populate_v2_parts(db: &Path) -> Connection { + let c = Connection::open(db).expect("create"); + c.pragma_update(None, "journal_mode", "WAL").expect("wal"); + c.execute_batch(SCHEMA_V2).expect("schema v2"); + c.execute_batch(SCHEMA_V2_PARTS).expect("schema v2 parts"); + session_v2(&c, "ses2_mixed", "/work/app", None, 7000, None); + message_v2( + &c, + "msg2_q1", + "ses2_mixed", + 1, + "user", + r#"{"text":"mixed question","files":[],"time":{"created":70001}}"#, + ); + message_v2( + &c, + "msg2_legacy", + "ses2_mixed", + 2, + "assistant", + r#"{"content":[{"type":"text","text":"legacy reply"}],"time":{"created":70002}}"#, + ); + message_v2(&c, "msg2_parts", "ses2_mixed", 3, "assistant", r#"{"content":[],"time":{"created":70003}}"#); + message_v2( + &c, + "msg2_both", + "ses2_mixed", + 4, + "assistant", + r#"{"content":[{"type":"text","text":"both reply"}],"time":{"created":70004}}"#, + ); + message_v2( + &c, + "msg2_q2", + "ses2_mixed", + 5, + "user", + r#"{"text":"follow-up question","files":[],"time":{"created":70005}}"#, + ); + message_v2( + &c, + "msg2_reasoning", + "ses2_mixed", + 6, + "assistant", + r#"{"content":[{"type":"reasoning","text":"thinking"}],"time":{"created":70006}}"#, + ); + // Written out of order on purpose: only `ordinal` decides how the reply reads. + part_v2(&c, "msg2_parts", "ses2_mixed", 3, "text", r#"{"type":"text","text":"part two"}"#); + part_v2(&c, "msg2_parts", "ses2_mixed", 1, "tool", r#"{"type":"tool","name":"read"}"#); + part_v2(&c, "msg2_parts", "ses2_mixed", 0, "text", r#"{"type":"text","text":"part one"}"#); + part_v2(&c, "msg2_parts", "ses2_mixed", 2, "text", r#"{"type":"text","text":" "}"#); + part_v2( + &c, + "msg2_parts", + "ses2_mixed", + 4, + "text", + r#"{"type":"text","text":"injected","synthetic":true}"#, + ); + part_v2(&c, "msg2_both", "ses2_mixed", 0, "text", r#"{"type":"text","text":"part duplicate"}"#); + part_v2(&c, "msg2_reasoning", "ses2_mixed", 0, "tool", r#"{"type":"tool","name":"read"}"#); + c +} + +#[test] +fn replies_survive_the_part_table_once_each_in_order_and_under_the_limit() { + let dir = temp_dir("v2parts"); + let db = dir.join("opencode.db"); + let writer = populate_v2_parts(&db); + let messages = opencode::messages_for_session(&db, "ses2_mixed", Schema::V2, 25).expect("messages"); + let texts: Vec<&str> = messages.iter().map(|m| m.text.as_str()).collect(); + assert_eq!( + texts, + ["follow-up question", "both reply", "part one\n\npart two", "legacy reply", "mixed question"] + ); + // A reply stored in both formats is one entry: the payload wins, its parts are not repeated. + assert_eq!(messages.iter().filter(|m| m.id == "msg2_both").count(), 1); + assert!(messages.iter().all(|m| !m.text.contains("part duplicate"))); + let parts = messages.iter().find(|m| m.id == "msg2_parts").expect("parts reply"); + assert_eq!(parts.role, Role::Assistant); + assert_eq!(parts.at.as_deref(), Some("1970-01-01T00:01:10.003Z")); + assert_eq!(messages[1].id, "msg2_both"); + assert_eq!(messages[1].role, Role::Assistant); + assert_eq!(messages[1].at.as_deref(), Some("1970-01-01T00:01:10.004Z")); + assert_eq!(messages[0].role, Role::Human); + assert_eq!(messages[3].at.as_deref(), Some("1970-01-01T00:01:10.002Z")); + // Only the reasoning turn is invisible, so a limit of two replies still reaches the parts + // reply; a limit of one stops at the newest reply and keeps the prompt after it. + let one = opencode::messages_for_session(&db, "ses2_mixed", Schema::V2, 1).expect("one"); + assert_eq!(one.iter().map(|m| m.id.as_str()).collect::>(), ["msg2_q2", "msg2_both"]); + let two = opencode::messages_for_session(&db, "ses2_mixed", Schema::V2, 2).expect("two"); + assert_eq!(two.iter().map(|m| m.id.as_str()).collect::>(), ["msg2_q2", "msg2_both", "msg2_parts"]); + drop(writer); + std::fs::remove_dir_all(&dir).expect("cleanup"); +} + #[test] fn a_database_without_the_v2_tables_still_reads_v1() { let dir = temp_dir("v1only"); From d94a9c16a043bd8043bd0d37000aad2349e5d04e Mon Sep 17 00:00:00 2001 From: Michael Ledin Date: Tue, 24 Nov 2026 17:57:38 +0300 Subject: [PATCH 2/8] refactor(hosts): split the OpenCode reader and report part read errors A part row that will not parse was silently dropped, so a reply could vanish without a word. The part reader now fails with the operation, session, message and database path, while a message payload that will not parse stays skipped as before: it was never selected for its parts, and one bad row must not hide the session. The module outgrew one file, so it splits by responsibility: session picking, the two message readers, the 2.4 part reader, and the shared payload rules that decide what counts as reply text for every source. The public surface is unchanged. The mixed fixture test asserted order, dedup, identity and the limit at once, so a failure named none of them. Each invariant now has its own test, and the fixtures moved to a shared module. The part fixture also covers an ignored part and a reasoning part beside a text part. --- crates/plannotator-tui-hosts/src/opencode.rs | 363 ------------------ .../src/opencode/messages.rs | 165 ++++++++ .../plannotator-tui-hosts/src/opencode/mod.rs | 153 ++++++++ .../src/opencode/parts.rs | 81 ++++ .../src/opencode/payload.rs | 27 ++ .../{opencode.rs => opencode/fixture.rs} | 349 ++++++----------- .../tests/opencode/main.rs | 12 + .../tests/opencode/parts.rs | 135 +++++++ .../tests/opencode/session.rs | 80 ++++ .../tests/opencode/v1.rs | 48 +++ .../tests/opencode/v2.rs | 50 +++ 11 files changed, 861 insertions(+), 602 deletions(-) delete mode 100644 crates/plannotator-tui-hosts/src/opencode.rs create mode 100644 crates/plannotator-tui-hosts/src/opencode/messages.rs create mode 100644 crates/plannotator-tui-hosts/src/opencode/mod.rs create mode 100644 crates/plannotator-tui-hosts/src/opencode/parts.rs create mode 100644 crates/plannotator-tui-hosts/src/opencode/payload.rs rename crates/plannotator-tui-hosts/tests/{opencode.rs => opencode/fixture.rs} (53%) create mode 100644 crates/plannotator-tui-hosts/tests/opencode/main.rs create mode 100644 crates/plannotator-tui-hosts/tests/opencode/parts.rs create mode 100644 crates/plannotator-tui-hosts/tests/opencode/session.rs create mode 100644 crates/plannotator-tui-hosts/tests/opencode/v1.rs create mode 100644 crates/plannotator-tui-hosts/tests/opencode/v2.rs diff --git a/crates/plannotator-tui-hosts/src/opencode.rs b/crates/plannotator-tui-hosts/src/opencode.rs deleted file mode 100644 index 5ffdf15d..00000000 --- a/crates/plannotator-tui-hosts/src/opencode.rs +++ /dev/null @@ -1,363 +0,0 @@ -//! `OpenCode`: sessions, messages and parts live in `SQLite` (`opencode.db` under the XDG data -//! dir), one row per message and one per part, with the payload as JSON in `data`. -//! -//! Verified against opencode 1.18 source (`packages/core/src/database/database.ts`, -//! `packages/core/src/global.ts`, `packages/opencode/src/session/message-v2.ts`): -//! -//! - the database is `$OPENCODE_DB`, else `/opencode/opencode.db`, where the xdg -//! data dir is `$XDG_DATA_HOME` or `~/.local/share` on every platform; -//! - `session.directory` is where `OpenCode` was started; child sessions (subagents) carry a -//! `parent_id`; archived sessions carry `time_archived`; -//! - a message's text is its `part` rows of type `text`, in id order; parts flagged -//! `synthetic` or `ignored` are injected context, not something the user or model wrote. -//! -//! `OpenCode` 2 (the `opencode2` binary, `anomalyco/opencode` branch `beta`) shares the data -//! directory and, on the standard channels, the same `opencode.db`, but writes to new tables: -//! `session_v2` (same columns this reader needs) and `session_message` (`type` column is the -//! role, `seq` is the order, `data` holds the payload: `content[].type == "text"` for an -//! assistant, `text` for a user). Other channels use `opencode-.db` next to it -//! (`packages/cli/src/server-process.ts`). A v1 session and a v2 session can therefore both -//! match one directory; the newest wins, whichever schema and file it lives in. -//! -//! `OpenCode` 2.4 (migration `20261029002625_session_part`) writes each part as its own -//! `session_part` row (`message_id`, `session_id`, `ordinal`, `type`, `data`) and leaves the -//! assistant payload's `content` empty. The text of such a reply is its `text` parts in -//! `ordinal` order. A reply keeps whichever format carries its text; the two are never mixed. - -use std::path::Path; - -use rusqlite::params; - -use crate::sqlite::{open_read_only, sql_error}; -use crate::{HostError, Message, Role}; - -/// The database relative to `OpenCode`'s data directory. -pub const DB_FILE: &str = "opencode.db"; -/// The data directory relative to the XDG data home. -pub const DATA_DIR: &str = "opencode"; - -const WHAT: &str = "OpenCode"; - -/// Which table family a session lives in. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Schema { - /// `OpenCode` 1: `session`, `message`, `part`. - V1, - /// `OpenCode` 2: `session_v2`, `session_message`. - V2, -} - -/// A session picked for a directory, with what is needed to compare picks across files. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Found { - pub id: String, - pub schema: Schema, - /// `time_updated`, Unix milliseconds. - pub updated: i64, -} - -/// The newest top-level, unarchived session started in `cwd`, across both schemas. When none -/// was started exactly there, the newest one started in an ancestor of `cwd` (`OpenCode` -/// records the directory it was launched from; the pane may have moved since). -pub fn find_session(db: &Path, cwd: &Path) -> Result { - let connection = open_read_only(db, WHAT)?; - let cwd = normalize(&cwd.to_string_lossy()); - let mut exact: Option = None; - let mut ancestor: Option = None; - for (schema, table) in [(Schema::V2, "session_v2"), (Schema::V1, "session")] { - if !has_table(&connection, table)? { - continue; - } - let mut statement = connection - .prepare(&format!( - "SELECT id, directory, time_updated FROM {table} \ - WHERE parent_id IS NULL AND time_archived IS NULL" - )) - .map_err(|e| sql_error(WHAT, &e))?; - let rows = statement - .query_map([], |row| { - Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?, row.get::<_, i64>(2)?)) - }) - .map_err(|e| sql_error(WHAT, &e))?; - for row in rows { - let (id, directory, updated) = row.map_err(|e| sql_error(WHAT, &e))?; - let directory = normalize(&directory); - let found = Found { id, schema, updated }; - if directory == cwd { - newer(&mut exact, found); - } else if is_ancestor(&directory, &cwd) { - newer(&mut ancestor, found); - } - } - } - exact - .or(ancestor) - .ok_or_else(|| HostError::NoTranscript(format!("no OpenCode session for {cwd} in {}", db.display()))) -} - -/// Which schema holds `session_id`, for sessions addressed by id rather than found by cwd. -pub fn schema_of(db: &Path, session_id: &str) -> Result { - crate::validate_session_id(session_id)?; - let connection = open_read_only(db, WHAT)?; - for (schema, table) in [(Schema::V2, "session_v2"), (Schema::V1, "session")] { - if !has_table(&connection, table)? { - continue; - } - let count: i64 = connection - .query_row(&format!("SELECT count(*) FROM {table} WHERE id = ?1"), params![session_id], |r| { - r.get(0) - }) - .map_err(|e| sql_error(WHAT, &e))?; - if count > 0 { - return Ok(schema); - } - } - Err(HostError::NoMessages(format!("no OpenCode session {session_id} in {}", db.display()))) -} - -fn newer(slot: &mut Option, candidate: Found) { - if slot.as_ref().is_none_or(|current| candidate.updated > current.updated) { - *slot = Some(candidate); - } -} - -fn has_table(connection: &rusqlite::Connection, name: &str) -> Result { - connection - .query_row( - "SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name = ?1", - params![name], - |row| row.get::<_, i64>(0), - ) - .map(|n| n > 0) - .map_err(|e| sql_error(WHAT, &e)) -} - -/// The user and assistant messages of `session_id` that carry text, newest first, through the -/// `n`th newest assistant reply. -pub fn messages_for_session( - db: &Path, - session_id: &str, - schema: Schema, - n: usize, -) -> Result, HostError> { - crate::validate_session_id(session_id)?; - match schema { - Schema::V1 => messages_v1(db, session_id, n), - Schema::V2 => messages_v2(db, session_id, n), - } -} - -fn messages_v1(db: &Path, session_id: &str, n: usize) -> Result, HostError> { - let connection = open_read_only(db, WHAT)?; - // One indexed pass: every text part of the session, grouped by message, newest message - // first and parts in creation order within it. - let mut statement = connection - .prepare( - "SELECT m.id, m.data, p.data FROM message m \ - JOIN part p ON p.message_id = m.id \ - WHERE m.session_id = ?1 AND json_extract(p.data, '$.type') = 'text' \ - ORDER BY m.time_created DESC, m.id DESC, p.time_created ASC, p.id ASC", - ) - .map_err(|e| sql_error(WHAT, &e))?; - let rows = statement - .query_map(params![session_id], |row| { - Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?, row.get::<_, String>(2)?)) - }) - .map_err(|e| sql_error(WHAT, &e))?; - - let mut messages: Vec = Vec::new(); - let mut current: Option<(String, Role, Option, Vec)> = None; - let flush = |current: &mut Option<(String, Role, Option, Vec)>, - out: &mut Vec| { - if let Some((id, role, at, parts)) = current.take() - && !parts.is_empty() - { - out.push(Message { id, role, text: parts.join("\n\n"), at }); - } - }; - for row in rows { - let (id, message_data, part_data) = row.map_err(|e| sql_error(WHAT, &e))?; - if current.as_ref().is_none_or(|c| c.0 != id) { - flush(&mut current, &mut messages); - if replies(&messages) >= n { - break; - } - let Some((role, at)) = message_meta(&message_data) else { continue }; - current = Some((id, role, at, Vec::new())); - } - if let Some((_, _, _, parts)) = current.as_mut() - && let Some(text) = part_text(&part_data) - { - parts.push(text); - } - } - if replies(&messages) < n { - flush(&mut current, &mut messages); - } - if messages.is_empty() { - return Err(HostError::NoMessages(format!( - "no messages for OpenCode session {session_id} in {}", - db.display() - ))); - } - Ok(messages) -} - -/// `OpenCode` 2: one `session_message` row per message; the payload carries the text directly, -/// or, since 2.4 writes each part as its own row, in the message's `session_part` rows. -fn messages_v2(db: &Path, session_id: &str, n: usize) -> Result, HostError> { - let connection = open_read_only(db, WHAT)?; - // The part table arrived in 2.4; a database written before it has none, and the message - // payload is then the only source. Checked once, the prepared statement serves every row. - let mut parts = if has_table(&connection, "session_part")? { - Some( - connection - .prepare( - "SELECT data FROM session_part \ - WHERE session_id = ?1 AND message_id = ?2 AND type = 'text' \ - ORDER BY ordinal ASC", - ) - .map_err(|e| sql_error(WHAT, &e))?, - ) - } else { - None - }; - let mut statement = connection - .prepare( - "SELECT id, type, data, time_created FROM session_message \ - WHERE session_id = ?1 AND type IN ('user', 'assistant') \ - ORDER BY seq DESC", - ) - .map_err(|e| sql_error(WHAT, &e))?; - let rows = statement - .query_map(params![session_id], |row| { - Ok(( - row.get::<_, String>(0)?, - row.get::<_, String>(1)?, - row.get::<_, String>(2)?, - row.get::<_, i64>(3)?, - )) - }) - .map_err(|e| sql_error(WHAT, &e))?; - let mut messages = Vec::new(); - for row in rows { - if replies(&messages) >= n { - break; - } - let (id, kind, data, created) = row.map_err(|e| sql_error(WHAT, &e))?; - let Ok(json) = serde_json::from_str::(&data) else { continue }; - let (role, text) = match kind.as_str() { - "assistant" => { - let blocks: Vec<&str> = json - .get("content") - .and_then(serde_json::Value::as_array) - .map(|items| { - items - .iter() - .filter(|item| item.get("type").and_then(|t| t.as_str()) == Some("text")) - .filter_map(|item| item.get("text").and_then(|t| t.as_str())) - .filter(|t| !t.trim().is_empty()) - .collect() - }) - .unwrap_or_default(); - let payload = blocks.join("\n\n"); - // The format is decided per reply: text in the payload wins, and only a reply - // without visible text falls back to its parts. Never both, never repeated. - let text = if payload.trim().is_empty() { - match parts_for_message(&mut parts, session_id, &id)? { - Some(text) => text, - None => payload, - } - } else { - payload - }; - (Role::Assistant, text) - } - "user" => (Role::Human, json.get("text").and_then(|t| t.as_str()).unwrap_or_default().to_owned()), - _ => continue, - }; - if text.trim().is_empty() { - continue; - } - let at = json - .pointer("/time/created") - .and_then(serde_json::Value::as_u64) - .or_else(|| u64::try_from(created).ok()) - .map(crate::time::iso_from_unix_ms); - messages.push(Message { id, role, text, at }); - } - if messages.is_empty() { - return Err(HostError::NoMessages(format!( - "no messages for OpenCode session {session_id} in {}", - db.display() - ))); - } - Ok(messages) -} - -/// The part reader for one session: a statement prepared once and reused per message id. -type PartStatement<'connection> = rusqlite::Statement<'connection>; - -/// The visible text of a reply's `session_part` rows, joined in `ordinal` order, or `None` when -/// the reply has no visible text there. Tool calls, reasoning and injected parts are not text. -fn parts_for_message( - statement: &mut Option>, - session_id: &str, - message_id: &str, -) -> Result, HostError> { - let Some(statement) = statement.as_mut() else { return Ok(None) }; - let rows = statement - .query_map(params![session_id, message_id], |row| row.get::<_, String>(0)) - .map_err(|e| sql_error(WHAT, &e))?; - let mut parts = Vec::new(); - for row in rows { - let data = row.map_err(|e| sql_error(WHAT, &e))?; - if let Some(text) = part_text(&data) { - parts.push(text); - } - } - Ok((!parts.is_empty()).then(|| parts.join("\n\n"))) -} - -/// How many of `messages` are assistant replies: `n` counts those, not prompts. -fn replies(messages: &[Message]) -> usize { - messages.iter().filter(|message| message.role == Role::Assistant).count() -} - -/// Role and creation time from a `message.data` payload; `None` for roles we do not render. -fn message_meta(data: &str) -> Option<(Role, Option)> { - let json: serde_json::Value = serde_json::from_str(data).ok()?; - let role = match json.get("role").and_then(|r| r.as_str())? { - "assistant" => Role::Assistant, - "user" => Role::Human, - _ => return None, - }; - let at = - json.pointer("/time/created").and_then(serde_json::Value::as_u64).map(crate::time::iso_from_unix_ms); - Some((role, at)) -} - -/// The text of a `part.data` payload when it is real text: type `text`, not `synthetic` -/// (injected by `OpenCode`), not `ignored`, not empty. -fn part_text(data: &str) -> Option { - let json: serde_json::Value = serde_json::from_str(data).ok()?; - if json.get("type").and_then(|t| t.as_str()) != Some("text") { - return None; - } - let flagged = |key: &str| json.get(key).and_then(serde_json::Value::as_bool).unwrap_or(false); - if flagged("synthetic") || flagged("ignored") { - return None; - } - let text = json.get("text").and_then(|t| t.as_str())?; - (!text.trim().is_empty()).then(|| text.to_owned()) -} - -/// Paths compare without a trailing separator; Windows drive letters case-insensitively. -fn normalize(path: &str) -> String { - let trimmed = path.trim_end_matches(['/', '\\']); - if cfg!(windows) { trimmed.replace('\\', "/").to_ascii_lowercase() } else { trimmed.to_owned() } -} - -fn is_ancestor(directory: &str, cwd: &str) -> bool { - !directory.is_empty() && cwd.starts_with(directory) && cwd.as_bytes().get(directory.len()) == Some(&b'/') -} diff --git a/crates/plannotator-tui-hosts/src/opencode/messages.rs b/crates/plannotator-tui-hosts/src/opencode/messages.rs new file mode 100644 index 00000000..5172c12c --- /dev/null +++ b/crates/plannotator-tui-hosts/src/opencode/messages.rs @@ -0,0 +1,165 @@ +//! The message readers: `OpenCode` 1 (`message` + `part`) and `OpenCode` 2 (`session_message`, +//! whose payload may hold the text or, since 2.4, leave it to `session_part` rows). + +use std::path::Path; + +use rusqlite::params; +use serde_json::Value; + +use super::parts::Parts; +use super::payload::{json_text, part_text}; +use super::{WHAT, replies}; +use crate::sqlite::{open_read_only, sql_error}; +use crate::{HostError, Message, Role}; + +/// The user and assistant messages of `session_id` that carry text, newest first, through the +/// `n`th newest assistant reply. +pub fn messages_for_session( + db: &Path, + session_id: &str, + schema: super::Schema, + n: usize, +) -> Result, HostError> { + crate::validate_session_id(session_id)?; + match schema { + super::Schema::V1 => messages_v1(db, session_id, n), + super::Schema::V2 => messages_v2(db, session_id, n), + } +} + +fn messages_v1(db: &Path, session_id: &str, n: usize) -> Result, HostError> { + let connection = open_read_only(db, WHAT)?; + // One indexed pass: every text part of the session, grouped by message, newest message + // first and parts in creation order within it. + let mut statement = connection + .prepare( + "SELECT m.id, m.data, p.data FROM message m \ + JOIN part p ON p.message_id = m.id \ + WHERE m.session_id = ?1 AND json_extract(p.data, '$.type') = 'text' \ + ORDER BY m.time_created DESC, m.id DESC, p.time_created ASC, p.id ASC", + ) + .map_err(|e| sql_error(WHAT, &e))?; + let rows = statement + .query_map(params![session_id], |row| { + Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?, row.get::<_, String>(2)?)) + }) + .map_err(|e| sql_error(WHAT, &e))?; + + let mut messages: Vec = Vec::new(); + let mut current: Option<(String, Role, Option, Vec)> = None; + let flush = |current: &mut Option<(String, Role, Option, Vec)>, + out: &mut Vec| { + if let Some((id, role, at, parts)) = current.take() + && !parts.is_empty() + { + out.push(Message { id, role, text: parts.join("\n\n"), at }); + } + }; + for row in rows { + let (id, message_data, part_data) = row.map_err(|e| sql_error(WHAT, &e))?; + if current.as_ref().is_none_or(|c| c.0 != id) { + flush(&mut current, &mut messages); + if replies(&messages) >= n { + break; + } + let Some((role, at)) = message_meta(&message_data) else { continue }; + current = Some((id, role, at, Vec::new())); + } + if let Some((_, _, _, parts)) = current.as_mut() + && let Some(text) = part_text(&part_data) + { + parts.push(text); + } + } + if replies(&messages) < n { + flush(&mut current, &mut messages); + } + empty_is_an_error(messages, db, session_id) +} + +/// `OpenCode` 2: one `session_message` row per message; the payload carries the text directly, +/// or, since 2.4 writes each part as its own row, in the message's `session_part` rows. +fn messages_v2(db: &Path, session_id: &str, n: usize) -> Result, HostError> { + let connection = open_read_only(db, WHAT)?; + // The part table arrived in 2.4; a database written before it has none, and the message + // payload is then the only source. Prepared once, the reader serves every row. + let mut parts = Parts::new(&connection, db, session_id)?; + let mut statement = connection + .prepare( + "SELECT id, type, data, time_created FROM session_message \ + WHERE session_id = ?1 AND type IN ('user', 'assistant') \ + ORDER BY seq DESC", + ) + .map_err(|e| sql_error(WHAT, &e))?; + let rows = statement + .query_map(params![session_id], |row| { + Ok(( + row.get::<_, String>(0)?, + row.get::<_, String>(1)?, + row.get::<_, String>(2)?, + row.get::<_, i64>(3)?, + )) + }) + .map_err(|e| sql_error(WHAT, &e))?; + let mut messages = Vec::new(); + for row in rows { + if replies(&messages) >= n { + break; + } + let (id, kind, data, created) = row.map_err(|e| sql_error(WHAT, &e))?; + // A message payload that will not parse is skipped, as it always has been: it was not + // selected for its parts, and one bad row must not hide the rest of the session. + let Ok(json) = serde_json::from_str::(&data) else { continue }; + let (role, text) = match kind.as_str() { + "assistant" => (Role::Assistant, assistant_text(&json, &id, &mut parts)?), + "user" => (Role::Human, json.get("text").and_then(Value::as_str).unwrap_or_default().to_owned()), + _ => continue, + }; + if text.trim().is_empty() { + continue; + } + let at = json + .pointer("/time/created") + .and_then(Value::as_u64) + .or_else(|| u64::try_from(created).ok()) + .map(crate::time::iso_from_unix_ms); + messages.push(Message { id, role, text, at }); + } + empty_is_an_error(messages, db, session_id) +} + +/// A v2 assistant reply's text. The format is decided per reply: text in the payload wins, and +/// only a reply without visible text falls back to its parts. Never both, never repeated. +fn assistant_text(json: &Value, id: &str, parts: &mut Parts<'_>) -> Result { + let payload = json + .get("content") + .and_then(Value::as_array) + .map(|items| items.iter().filter_map(json_text).collect::>().join("\n\n")) + .unwrap_or_default(); + if !payload.trim().is_empty() { + return Ok(payload); + } + Ok(parts.text_for(id)?.unwrap_or(payload)) +} + +fn empty_is_an_error(messages: Vec, db: &Path, session_id: &str) -> Result, HostError> { + if messages.is_empty() { + return Err(HostError::NoMessages(format!( + "no messages for OpenCode session {session_id} in {}", + db.display() + ))); + } + Ok(messages) +} + +/// Role and creation time from a `message.data` payload; `None` for roles we do not render. +fn message_meta(data: &str) -> Option<(Role, Option)> { + let json: Value = serde_json::from_str(data).ok()?; + let role = match json.get("role").and_then(|r| r.as_str())? { + "assistant" => Role::Assistant, + "user" => Role::Human, + _ => return None, + }; + let at = json.pointer("/time/created").and_then(Value::as_u64).map(crate::time::iso_from_unix_ms); + Some((role, at)) +} diff --git a/crates/plannotator-tui-hosts/src/opencode/mod.rs b/crates/plannotator-tui-hosts/src/opencode/mod.rs new file mode 100644 index 00000000..ab6e489d --- /dev/null +++ b/crates/plannotator-tui-hosts/src/opencode/mod.rs @@ -0,0 +1,153 @@ +//! `OpenCode`: sessions, messages and parts live in `SQLite` (`opencode.db` under the XDG data +//! dir), one row per message and one per part, with the payload as JSON in `data`. +//! +//! Verified against opencode 1.18 source (`packages/core/src/database/database.ts`, +//! `packages/core/src/global.ts`, `packages/opencode/src/session/message-v2.ts`): +//! +//! - the database is `$OPENCODE_DB`, else `/opencode/opencode.db`, where the xdg +//! data dir is `$XDG_DATA_HOME` or `~/.local/share` on every platform; +//! - `session.directory` is where `OpenCode` was started; child sessions (subagents) carry a +//! `parent_id`; archived sessions carry `time_archived`; +//! - a message's text is its `part` rows of type `text`, in id order; parts flagged +//! `synthetic` or `ignored` are injected context, not something the user or model wrote. +//! +//! `OpenCode` 2 (the `opencode2` binary, `anomalyco/opencode` branch `beta`) shares the data +//! directory and, on the standard channels, the same `opencode.db`, but writes to new tables: +//! `session_v2` (same columns this reader needs) and `session_message` (`type` column is the +//! role, `seq` is the order, `data` holds the payload: `content[].type == "text"` for an +//! assistant, `text` for a user). Other channels use `opencode-.db` next to it +//! (`packages/cli/src/server-process.ts`). A v1 session and a v2 session can therefore both +//! match one directory; the newest wins, whichever schema and file it lives in. +//! +//! `OpenCode` 2.4 (migration `20261029002625_session_part`) writes each part as its own +//! `session_part` row (`message_id`, `session_id`, `ordinal`, `type`, `data`) and leaves the +//! assistant payload's `content` empty. The text of such a reply is its `text` parts in +//! `ordinal` order. A reply keeps whichever format carries its text; the two are never mixed. + +mod messages; +mod parts; +mod payload; + +use std::path::Path; + +use rusqlite::params; + +use crate::sqlite::{open_read_only, sql_error}; +use crate::{HostError, Role}; +pub use messages::messages_for_session; + +/// The database relative to `OpenCode`'s data directory. +pub const DB_FILE: &str = "opencode.db"; +/// The data directory relative to the XDG data home. +pub const DATA_DIR: &str = "opencode"; + +const WHAT: &str = "OpenCode"; + +/// Which table family a session lives in. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Schema { + /// `OpenCode` 1: `session`, `message`, `part`. + V1, + /// `OpenCode` 2: `session_v2`, `session_message`. + V2, +} + +/// A session picked for a directory, with what is needed to compare picks across files. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Found { + pub id: String, + pub schema: Schema, + /// `time_updated`, Unix milliseconds. + pub updated: i64, +} + +/// The newest top-level, unarchived session started in `cwd`, across both schemas. When none +/// was started exactly there, the newest one started in an ancestor of `cwd` (`OpenCode` +/// records the directory it was launched from; the pane may have moved since). +pub fn find_session(db: &Path, cwd: &Path) -> Result { + let connection = open_read_only(db, WHAT)?; + let cwd = normalize(&cwd.to_string_lossy()); + let mut exact: Option = None; + let mut ancestor: Option = None; + for (schema, table) in [(Schema::V2, "session_v2"), (Schema::V1, "session")] { + if !has_table(&connection, table)? { + continue; + } + let mut statement = connection + .prepare(&format!( + "SELECT id, directory, time_updated FROM {table} \ + WHERE parent_id IS NULL AND time_archived IS NULL" + )) + .map_err(|e| sql_error(WHAT, &e))?; + let rows = statement + .query_map([], |row| { + Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?, row.get::<_, i64>(2)?)) + }) + .map_err(|e| sql_error(WHAT, &e))?; + for row in rows { + let (id, directory, updated) = row.map_err(|e| sql_error(WHAT, &e))?; + let directory = normalize(&directory); + let found = Found { id, schema, updated }; + if directory == cwd { + newer(&mut exact, found); + } else if is_ancestor(&directory, &cwd) { + newer(&mut ancestor, found); + } + } + } + exact + .or(ancestor) + .ok_or_else(|| HostError::NoTranscript(format!("no OpenCode session for {cwd} in {}", db.display()))) +} + +/// Which schema holds `session_id`, for sessions addressed by id rather than found by cwd. +pub fn schema_of(db: &Path, session_id: &str) -> Result { + crate::validate_session_id(session_id)?; + let connection = open_read_only(db, WHAT)?; + for (schema, table) in [(Schema::V2, "session_v2"), (Schema::V1, "session")] { + if !has_table(&connection, table)? { + continue; + } + let count: i64 = connection + .query_row(&format!("SELECT count(*) FROM {table} WHERE id = ?1"), params![session_id], |r| { + r.get(0) + }) + .map_err(|e| sql_error(WHAT, &e))?; + if count > 0 { + return Ok(schema); + } + } + Err(HostError::NoMessages(format!("no OpenCode session {session_id} in {}", db.display()))) +} + +fn newer(slot: &mut Option, candidate: Found) { + if slot.as_ref().is_none_or(|current| candidate.updated > current.updated) { + *slot = Some(candidate); + } +} + +fn has_table(connection: &rusqlite::Connection, name: &str) -> Result { + connection + .query_row( + "SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name = ?1", + params![name], + |row| row.get::<_, i64>(0), + ) + .map(|n| n > 0) + .map_err(|e| sql_error(WHAT, &e)) +} + +/// How many of `messages` are assistant replies: `n` counts those, not prompts. +fn replies(messages: &[crate::Message]) -> usize { + messages.iter().filter(|message| message.role == Role::Assistant).count() +} + +/// Paths compare without a trailing separator; Windows drive letters case-insensitively. +fn normalize(path: &str) -> String { + let trimmed = path.trim_end_matches(['/', '\\']); + if cfg!(windows) { trimmed.replace('\\', "/").to_ascii_lowercase() } else { trimmed.to_owned() } +} + +fn is_ancestor(directory: &str, cwd: &str) -> bool { + !directory.is_empty() && cwd.starts_with(directory) && cwd.as_bytes().get(directory.len()) == Some(&b'/') +} diff --git a/crates/plannotator-tui-hosts/src/opencode/parts.rs b/crates/plannotator-tui-hosts/src/opencode/parts.rs new file mode 100644 index 00000000..98be5853 --- /dev/null +++ b/crates/plannotator-tui-hosts/src/opencode/parts.rs @@ -0,0 +1,81 @@ +//! The `OpenCode` 2.4 part reader: the `session_part` statement is prepared once per read and +//! reused per message id, and a failure names the message it was reading. + +use std::path::Path; + +use rusqlite::{Connection, Statement, params}; +use serde_json::Value; + +use super::payload::{injected, json_text}; +use crate::HostError; + +/// Reads the text parts of one reply at a time, or nothing when the database predates the +/// part table. Owned names keep the borrow on the connection alone. +pub(super) struct Parts<'connection> { + statement: Option>, + database: String, + session_id: String, +} + +impl<'connection> Parts<'connection> { + /// Prepare the reader for `session_id`, or a reader that yields nothing when the database + /// has no part table (written before `OpenCode` 2.4). + pub(super) fn new( + connection: &'connection Connection, + database: &Path, + session_id: &str, + ) -> Result { + let session_id = session_id.to_owned(); + let database = database.display().to_string(); + let statement = if super::has_table(connection, "session_part")? { + Some( + connection + .prepare( + "SELECT data FROM session_part \ + WHERE session_id = ?1 AND message_id = ?2 AND type = 'text' \ + ORDER BY ordinal ASC", + ) + .map_err(|e| part_error(&session_id, &database, None, &e))?, + ) + } else { + None + }; + Ok(Self { statement, database, session_id }) + } + + /// The visible text of `message_id`'s parts, joined in `ordinal` order, or `None` when it + /// has no visible text there. A part row that will not parse is an error: it was selected + /// for this reply, so silence would drop text the user is owed. + pub(super) fn text_for(&mut self, message_id: &str) -> Result, HostError> { + let Self { statement, database, session_id } = self; + let Some(statement) = statement.as_mut() else { return Ok(None) }; + let rows = statement + .query_map(params![session_id.as_str(), message_id], |row| row.get::<_, String>(0)) + .map_err(|e| part_error(session_id, database, Some(message_id), &e))?; + let mut texts = Vec::new(); + for row in rows { + let data = row.map_err(|e| part_error(session_id, database, Some(message_id), &e))?; + let json: Value = serde_json::from_str(&data) + .map_err(|e| part_error(session_id, database, Some(message_id), &e))?; + if let Some(text) = json_text(&json) + && !injected(&json) + { + texts.push(text.to_owned()); + } + } + Ok((!texts.is_empty()).then(|| texts.join("\n\n"))) + } +} + +/// A part read failure: names the operation, the session and message, and the database. +fn part_error( + session_id: &str, + database: &str, + message_id: Option<&str>, + err: &impl std::fmt::Display, +) -> HostError { + let reply = message_id.map(|id| format!(" message {id}")).unwrap_or_default(); + HostError::NoTranscript(format!( + "reading the text parts of OpenCode session {session_id}{reply} in {database}: {err}" + )) +} diff --git a/crates/plannotator-tui-hosts/src/opencode/payload.rs b/crates/plannotator-tui-hosts/src/opencode/payload.rs new file mode 100644 index 00000000..683d9065 --- /dev/null +++ b/crates/plannotator-tui-hosts/src/opencode/payload.rs @@ -0,0 +1,27 @@ +//! Text out of an `OpenCode` `data` payload. One set of rules decides what is reply text, +//! whether the block came from an `OpenCode` 1 `part` row, an `OpenCode` 2 message payload or a +//! 2.4 `session_part` row: type `text`, not blank, not injected context. + +use serde_json::Value; + +/// The text of a JSON block that is real reply text: type `text` and not blank. +pub(super) fn json_text(json: &Value) -> Option<&str> { + if json.get("type").and_then(Value::as_str) != Some("text") { + return None; + } + json.get("text").and_then(Value::as_str).filter(|text| !text.trim().is_empty()) +} + +/// Is the block injected context rather than something the user or the model wrote? +pub(super) fn injected(json: &Value) -> bool { + let flagged = |key: &str| json.get(key).and_then(Value::as_bool).unwrap_or(false); + flagged("synthetic") || flagged("ignored") +} + +/// The text of an `OpenCode` 1 `part.data` payload when it is real text. A row that will not +/// parse is not text; the 1.x reader has always skipped those rather than failed. +pub(super) fn part_text(data: &str) -> Option { + let json: Value = serde_json::from_str(data).ok()?; + let text = json_text(&json)?; + (!injected(&json)).then(|| text.to_owned()) +} diff --git a/crates/plannotator-tui-hosts/tests/opencode.rs b/crates/plannotator-tui-hosts/tests/opencode/fixture.rs similarity index 53% rename from crates/plannotator-tui-hosts/tests/opencode.rs rename to crates/plannotator-tui-hosts/tests/opencode/fixture.rs index b0b44866..f7747f58 100644 --- a/crates/plannotator-tui-hosts/tests/opencode.rs +++ b/crates/plannotator-tui-hosts/tests/opencode/fixture.rs @@ -1,14 +1,11 @@ -//! `OpenCode` messages out of a generated `opencode.db` (the 1.18 schema subset), read-only. - -#![allow(clippy::expect_used, clippy::indexing_slicing, clippy::panic, reason = "tests assert by panicking")] +//! The generated databases the tests read: the `OpenCode` 1 schema subset, the `OpenCode` 2 +//! tables, and the 2.4 `session_part` table, with one mixed session each. use std::path::{Path, PathBuf}; -use plannotator_tui_hosts::opencode::{Found, Schema}; -use plannotator_tui_hosts::{HostError, Role, opencode}; use rusqlite::{Connection, params}; -const SCHEMA: &str = " +pub(crate) const SCHEMA: &str = " CREATE TABLE session (id TEXT PRIMARY KEY, project_id TEXT NOT NULL, parent_id TEXT, slug TEXT NOT NULL, directory TEXT NOT NULL, title TEXT NOT NULL, version TEXT NOT NULL, time_created INTEGER NOT NULL, time_updated INTEGER NOT NULL, time_archived INTEGER); @@ -22,7 +19,7 @@ CREATE INDEX part_message_id_id_idx ON part (message_id, id); /// The `OpenCode` 2 tables (`packages/core/src/session/sql.ts` on the `beta` branch), the columns /// this reader touches. -const SCHEMA_V2: &str = " +pub(crate) const SCHEMA_V2: &str = " CREATE TABLE session_v2 (id TEXT PRIMARY KEY, project_id TEXT NOT NULL, workspace_id TEXT, parent_id TEXT, slug TEXT NOT NULL, directory TEXT NOT NULL, title TEXT, version TEXT NOT NULL, time_created INTEGER NOT NULL, time_updated INTEGER NOT NULL, time_archived INTEGER); @@ -33,7 +30,7 @@ CREATE UNIQUE INDEX session_message_session_seq_idx ON session_message (session_ /// `OpenCode` 2.4 split a message's payload: one `session_part` row per part, ordered by /// `ordinal`. `packages/core/src/session/sql.ts`, migration `20261029002625_session_part`. -const SCHEMA_V2_PARTS: &str = " +pub(crate) const SCHEMA_V2_PARTS: &str = " CREATE TABLE session_part (message_id TEXT NOT NULL, session_id TEXT NOT NULL, ordinal INTEGER NOT NULL, type TEXT NOT NULL, call_id TEXT, time_created INTEGER NOT NULL, time_updated INTEGER NOT NULL, data TEXT NOT NULL, CONSTRAINT session_part_pk PRIMARY KEY(message_id, ordinal)); @@ -42,39 +39,83 @@ CREATE INDEX session_part_session_message_idx ON session_part (session_id, messa /// Current `OpenCode` writes this table alongside the legacy message/part tables while the /// session row remains in `session`. -const CURRENT_SESSION_MESSAGE: &str = " +pub(crate) const CURRENT_SESSION_MESSAGE: &str = " CREATE TABLE session_message (id TEXT PRIMARY KEY, session_id TEXT NOT NULL, type TEXT NOT NULL, seq INTEGER NOT NULL, time_created INTEGER NOT NULL, time_updated INTEGER NOT NULL, data TEXT NOT NULL); "; -fn session_v2( - c: &Connection, - id: &str, - dir: &str, - parent: Option<&str>, - updated: i64, - archived: Option, -) { - c.execute( - "INSERT INTO session_v2 (id, project_id, parent_id, slug, directory, version, time_created, time_updated, time_archived) \ - VALUES (?1, 'p', ?2, ?1, ?3, '0.0.0-beta', ?4, ?4, ?5)", - params![id, parent, dir, updated, archived], - ) - .expect("session_v2"); +/// A generated database in its own temp directory, removed when the test ends. Declare it +/// before the writer connection so the connection closes first. +pub(crate) struct Db { + dir: PathBuf, + pub(crate) path: PathBuf, } -fn message_v2(c: &Connection, id: &str, session: &str, seq: i64, kind: &str, data: &str) { - c.execute( - "INSERT INTO session_message (id, session_id, type, seq, time_created, time_updated, data) VALUES (?1, ?2, ?3, ?4, ?5, ?5, ?6)", - params![id, session, kind, seq, seq * 10, data], - ) - .expect("session_message"); +impl Db { + /// A fresh directory named for `tag`; paths are unique per test, not just per process. + pub(crate) fn new(tag: &str) -> Self { + let dir = std::env::temp_dir().join(format!("plannotator-tui-opencode-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("temp dir"); + Self { path: dir.join("opencode.db"), dir } + } + + /// The database path, for messages that must name the file. + pub(crate) fn file(&self) -> &Path { + &self.path + } +} + +impl Drop for Db { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.dir); + } +} + +/// Create the 1.x database at `db` and fill it with the shared `OpenCode` 1 fixture. +pub(crate) fn populate(db: &Path) -> Connection { + let c = open(db); + c.execute_batch(SCHEMA).expect("schema"); + session(&c, "ses_main", "/work/app", None, 1000, None); + session(&c, "ses_older", "/work/app", None, 900, None); + session(&c, "ses_child", "/work/app", Some("ses_main"), 2000, None); + session(&c, "ses_archived", "/work/app", None, 3000, Some(3000)); + session(&c, "ses_other", "/work/other", None, 5000, None); + session(&c, "ses_root", "/work", None, 100, None); + + message(&c, "msg_1", "ses_main", 10, "user"); + part(&c, "prt_1a", "msg_1", 10, r#"{"type":"text","text":"first question"}"#); + part( + &c, + "prt_1b", + "msg_1", + 11, + r#"{"type":"text","text":"injected","synthetic":true}"#, + ); + message(&c, "msg_2", "ses_main", 20, "assistant"); + part(&c, "prt_2a", "msg_2", 20, r#"{"type":"step-start"}"#); + part(&c, "prt_2b", "msg_2", 21, r#"{"type":"reasoning","text":"**thinking**"}"#); + part(&c, "prt_2c", "msg_2", 22, r#"{"type":"text","text":"oldest reply, part one"}"#); + part(&c, "prt_2d", "msg_2", 23, r#"{"type":"tool","tool":"read","state":{"status":"completed"}}"#); + part(&c, "prt_2e", "msg_2", 24, r#"{"type":"text","text":"oldest reply, part two"}"#); + part(&c, "prt_2f", "msg_2", 25, r#"{"type":"step-finish"}"#); + message(&c, "msg_3", "ses_main", 30, "assistant"); // aborted: no text at all + part(&c, "prt_3a", "msg_3", 30, r#"{"type":"step-start"}"#); + message(&c, "msg_4", "ses_main", 40, "user"); + part(&c, "prt_4a", "msg_4", 40, r#"{"type":"text","text":"ignored draft","ignored":true}"#); + part(&c, "prt_4b", "msg_4", 41, r#"{"type":"text","text":"second question"}"#); + message(&c, "msg_5", "ses_main", 50, "assistant"); + part(&c, "prt_5a", "msg_5", 50, r#"{"type":"text","text":" "}"#); + part(&c, "prt_5b", "msg_5", 51, r#"{"type":"text","text":"newest reply"}"#); + message(&c, "msg_x", "ses_other", 60, "assistant"); + part(&c, "prt_xa", "msg_x", 60, r#"{"type":"text","text":"other project"}"#); + c } -/// A database `OpenCode` 2 has written to: the v1 tables with an older session for `/work/app` -/// (as after the v1 migration) plus the v2 tables with a newer session for the same directory. -fn populate_v2(db: &Path) -> Connection { +/// Add the 2.x tables and a session whose replies live in the message payload: one reply with +/// reasoning and two text blocks, and a reasoning-only turn that has no visible text. +pub(crate) fn populate_v2(db: &Path) -> Connection { let c = populate(db); c.execute_batch(SCHEMA_V2).expect("schema v2"); session_v2(&c, "ses2_new", "/work/app", None, 5000, None); @@ -116,50 +157,11 @@ fn populate_v2(db: &Path) -> Connection { c } -#[test] -fn an_opencode2_session_in_the_same_database_wins_when_it_is_newer() { - let dir = temp_dir("v2"); - let db = dir.join("opencode.db"); - let writer = populate_v2(&db); - let found = opencode::find_session(&db, Path::new("/work/app")).expect("found"); - assert_eq!(found, Found { id: "ses2_new".to_owned(), schema: Schema::V2, updated: 5000 }); - // The v1 session is still the answer for a directory only v1 knows. - assert_eq!(opencode::find_session(&db, Path::new("/work/other")).expect("v1 only").schema, Schema::V1); - assert_eq!(opencode::schema_of(&db, "ses2_new").expect("v2"), Schema::V2); - assert_eq!(opencode::schema_of(&db, "ses_main").expect("v1"), Schema::V1); - assert!(matches!(opencode::schema_of(&db, "ses_nope"), Err(HostError::NoMessages(_)))); - - let messages = opencode::messages_for_session(&db, "ses2_new", Schema::V2, 25).expect("messages"); - let texts: Vec<&str> = messages.iter().map(|m| m.text.as_str()).collect(); - assert_eq!( - texts, - ["OPENCODE2_V2_SESSION_SELECTED\n\nDone.", "reply with exactly OPENCODE2_V2_SESSION_SELECTED"] - ); - assert_eq!(messages[0].role, Role::Assistant); - assert_eq!(messages[0].id, "msg2_3"); - assert_eq!(messages[0].at.as_deref(), Some("1970-01-01T00:00:50.002Z")); - assert_eq!(messages[1].role, Role::Human); - // n counts messages with text: the reasoning-only turn and the switch rows take no slot. - assert_eq!(opencode::messages_for_session(&db, "ses2_new", Schema::V2, 1).expect("one").len(), 1); - drop(writer); - std::fs::remove_dir_all(&dir).expect("cleanup"); -} - -fn part_v2(c: &Connection, message: &str, session: &str, ordinal: i64, kind: &str, data: &str) { - c.execute( - "INSERT INTO session_part (message_id, session_id, ordinal, type, time_created, time_updated, data) \ - VALUES (?1, ?2, ?3, ?4, ?5, ?5, ?6)", - params![message, session, ordinal, kind, ordinal + 1, data], - ) - .expect("session_part"); -} - /// A `OpenCode` 2.4 session whose replies are split between the message payload and /// `session_part` rows, as after the part-table migration: one reply in each format, one in /// both, a reasoning-only turn, and a prompt between them. -fn populate_v2_parts(db: &Path) -> Connection { - let c = Connection::open(db).expect("create"); - c.pragma_update(None, "journal_mode", "WAL").expect("wal"); +pub(crate) fn populate_v2_parts(db: &Path) -> Connection { + let c = open(db); c.execute_batch(SCHEMA_V2).expect("schema v2"); c.execute_batch(SCHEMA_V2_PARTS).expect("schema v2 parts"); session_v2(&c, "ses2_mixed", "/work/app", None, 7000, None); @@ -204,7 +206,8 @@ fn populate_v2_parts(db: &Path) -> Connection { "assistant", r#"{"content":[{"type":"reasoning","text":"thinking"}],"time":{"created":70006}}"#, ); - // Written out of order on purpose: only `ordinal` decides how the reply reads. + // Written out of order on purpose: only `ordinal` decides how the reply reads. Tool calls, + // reasoning, blank, injected and ignored parts are not reply text. part_v2(&c, "msg2_parts", "ses2_mixed", 3, "text", r#"{"type":"text","text":"part two"}"#); part_v2(&c, "msg2_parts", "ses2_mixed", 1, "tool", r#"{"type":"tool","name":"read"}"#); part_v2(&c, "msg2_parts", "ses2_mixed", 0, "text", r#"{"type":"text","text":"part one"}"#); @@ -217,77 +220,17 @@ fn populate_v2_parts(db: &Path) -> Connection { "text", r#"{"type":"text","text":"injected","synthetic":true}"#, ); + part_v2(&c, "msg2_parts", "ses2_mixed", 5, "text", r#"{"type":"text","text":"draft","ignored":true}"#); + part_v2(&c, "msg2_parts", "ses2_mixed", 6, "reasoning", r#"{"type":"reasoning","text":"thinking"}"#); part_v2(&c, "msg2_both", "ses2_mixed", 0, "text", r#"{"type":"text","text":"part duplicate"}"#); part_v2(&c, "msg2_reasoning", "ses2_mixed", 0, "tool", r#"{"type":"tool","name":"read"}"#); c } -#[test] -fn replies_survive_the_part_table_once_each_in_order_and_under_the_limit() { - let dir = temp_dir("v2parts"); - let db = dir.join("opencode.db"); - let writer = populate_v2_parts(&db); - let messages = opencode::messages_for_session(&db, "ses2_mixed", Schema::V2, 25).expect("messages"); - let texts: Vec<&str> = messages.iter().map(|m| m.text.as_str()).collect(); - assert_eq!( - texts, - ["follow-up question", "both reply", "part one\n\npart two", "legacy reply", "mixed question"] - ); - // A reply stored in both formats is one entry: the payload wins, its parts are not repeated. - assert_eq!(messages.iter().filter(|m| m.id == "msg2_both").count(), 1); - assert!(messages.iter().all(|m| !m.text.contains("part duplicate"))); - let parts = messages.iter().find(|m| m.id == "msg2_parts").expect("parts reply"); - assert_eq!(parts.role, Role::Assistant); - assert_eq!(parts.at.as_deref(), Some("1970-01-01T00:01:10.003Z")); - assert_eq!(messages[1].id, "msg2_both"); - assert_eq!(messages[1].role, Role::Assistant); - assert_eq!(messages[1].at.as_deref(), Some("1970-01-01T00:01:10.004Z")); - assert_eq!(messages[0].role, Role::Human); - assert_eq!(messages[3].at.as_deref(), Some("1970-01-01T00:01:10.002Z")); - // Only the reasoning turn is invisible, so a limit of two replies still reaches the parts - // reply; a limit of one stops at the newest reply and keeps the prompt after it. - let one = opencode::messages_for_session(&db, "ses2_mixed", Schema::V2, 1).expect("one"); - assert_eq!(one.iter().map(|m| m.id.as_str()).collect::>(), ["msg2_q2", "msg2_both"]); - let two = opencode::messages_for_session(&db, "ses2_mixed", Schema::V2, 2).expect("two"); - assert_eq!(two.iter().map(|m| m.id.as_str()).collect::>(), ["msg2_q2", "msg2_both", "msg2_parts"]); - drop(writer); - std::fs::remove_dir_all(&dir).expect("cleanup"); -} - -#[test] -fn a_database_without_the_v2_tables_still_reads_v1() { - let dir = temp_dir("v1only"); - let db = dir.join("opencode.db"); - let writer = populate(&db); - assert_eq!(opencode::find_session(&db, Path::new("/work/app")).expect("v1").schema, Schema::V1); - drop(writer); - std::fs::remove_dir_all(&dir).expect("cleanup"); -} - -#[test] -fn current_schema_keeps_exact_ids_on_the_session_message_compatibility_path() { - let dir = temp_dir("current"); - let db = dir.join("opencode.db"); - let writer = populate(&db); - writer.execute_batch(CURRENT_SESSION_MESSAGE).expect("current session_message table"); - writer - .execute( - "INSERT INTO session_message (id, session_id, type, seq, time_created, time_updated, data) VALUES ('current-only', 'ses_main', 'assistant', 1, 60, 60, '{\"content\":[{\"type\":\"text\",\"text\":\"duplicate current row\"}]}')", - [], - ) - .expect("current row"); - assert_eq!(opencode::schema_of(&db, "ses_main").expect("schema"), Schema::V1); - let messages = opencode::messages_for_session(&db, "ses_main", Schema::V1, 1).expect("messages"); - assert_eq!(messages[0].text, "newest reply"); - drop(writer); - std::fs::remove_dir_all(&dir).expect("cleanup"); -} - -fn temp_dir(tag: &str) -> PathBuf { - let dir = std::env::temp_dir().join(format!("plannotator-tui-opencode-{tag}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).expect("temp dir"); - dir +fn open(db: &Path) -> Connection { + let c = Connection::open(db).expect("create"); + c.pragma_update(None, "journal_mode", "WAL").expect("wal"); + c } fn session(c: &Connection, id: &str, dir: &str, parent: Option<&str>, updated: i64, archived: Option) { @@ -317,107 +260,35 @@ fn part(c: &Connection, id: &str, message: &str, created: i64, data: &str) { .expect("part"); } -/// One project with a main session, a newer child (subagent) session and a newer archived -/// session; another project elsewhere. The main session's messages exercise every skip rule. -fn populate(db: &Path) -> Connection { - let c = Connection::open(db).expect("create"); - c.pragma_update(None, "journal_mode", "WAL").expect("wal"); - c.execute_batch(SCHEMA).expect("schema"); - session(&c, "ses_main", "/work/app", None, 1000, None); - session(&c, "ses_older", "/work/app", None, 900, None); - session(&c, "ses_child", "/work/app", Some("ses_main"), 2000, None); - session(&c, "ses_archived", "/work/app", None, 3000, Some(3000)); - session(&c, "ses_other", "/work/other", None, 5000, None); - session(&c, "ses_root", "/work", None, 100, None); - - message(&c, "msg_1", "ses_main", 10, "user"); - part(&c, "prt_1a", "msg_1", 10, r#"{"type":"text","text":"first question"}"#); - part( - &c, - "prt_1b", - "msg_1", - 11, - r#"{"type":"text","text":"injected","synthetic":true}"#, - ); - message(&c, "msg_2", "ses_main", 20, "assistant"); - part(&c, "prt_2a", "msg_2", 20, r#"{"type":"step-start"}"#); - part(&c, "prt_2b", "msg_2", 21, r#"{"type":"reasoning","text":"**thinking**"}"#); - part(&c, "prt_2c", "msg_2", 22, r#"{"type":"text","text":"oldest reply, part one"}"#); - part(&c, "prt_2d", "msg_2", 23, r#"{"type":"tool","tool":"read","state":{"status":"completed"}}"#); - part(&c, "prt_2e", "msg_2", 24, r#"{"type":"text","text":"oldest reply, part two"}"#); - part(&c, "prt_2f", "msg_2", 25, r#"{"type":"step-finish"}"#); - message(&c, "msg_3", "ses_main", 30, "assistant"); // aborted: no text at all - part(&c, "prt_3a", "msg_3", 30, r#"{"type":"step-start"}"#); - message(&c, "msg_4", "ses_main", 40, "user"); - part(&c, "prt_4a", "msg_4", 40, r#"{"type":"text","text":"ignored draft","ignored":true}"#); - part(&c, "prt_4b", "msg_4", 41, r#"{"type":"text","text":"second question"}"#); - message(&c, "msg_5", "ses_main", 50, "assistant"); - part(&c, "prt_5a", "msg_5", 50, r#"{"type":"text","text":" "}"#); - part(&c, "prt_5b", "msg_5", 51, r#"{"type":"text","text":"newest reply"}"#); - message(&c, "msg_x", "ses_other", 60, "assistant"); - part(&c, "prt_xa", "msg_x", 60, r#"{"type":"text","text":"other project"}"#); - c -} - -#[test] -fn newest_session_for_the_directory_skips_children_and_archived_ones() { - let dir = temp_dir("find"); - let db = dir.join("opencode.db"); - let writer = populate(&db); - assert_eq!(opencode::find_session(&db, Path::new("/work/app")).expect("exact").id, "ses_main"); - assert_eq!(opencode::find_session(&db, Path::new("/work/app/")).expect("trailing slash").id, "ses_main"); - // Started in an ancestor: the newest session there, never a sibling project. - assert_eq!(opencode::find_session(&db, Path::new("/work/app/src/deep")).expect("nested").id, "ses_main"); - assert_eq!(opencode::find_session(&db, Path::new("/work/tools")).expect("root").id, "ses_root"); - assert_eq!(opencode::find_session(&db, Path::new("/work/other")).expect("other").id, "ses_other"); - match opencode::find_session(&db, Path::new("/elsewhere")) { - Err(HostError::NoTranscript(msg)) => assert!(msg.contains("/elsewhere"), "{msg}"), - other => panic!("expected NoTranscript, got {other:?}"), - } - drop(writer); - std::fs::remove_dir_all(&dir).expect("cleanup"); +fn session_v2( + c: &Connection, + id: &str, + dir: &str, + parent: Option<&str>, + updated: i64, + archived: Option, +) { + c.execute( + "INSERT INTO session_v2 (id, project_id, parent_id, slug, directory, version, time_created, time_updated, time_archived) \ + VALUES (?1, 'p', ?2, ?1, ?3, '0.0.0-beta', ?4, ?4, ?5)", + params![id, parent, dir, updated, archived], + ) + .expect("session_v2"); } -#[test] -fn text_parts_join_in_order_and_injected_or_empty_ones_are_skipped() { - let dir = temp_dir("read"); - let db = dir.join("opencode.db"); - let writer = populate(&db); - let messages = opencode::messages_for_session(&db, "ses_main", Schema::V1, 25).expect("messages"); - let texts: Vec<&str> = messages.iter().map(|m| m.text.as_str()).collect(); - assert_eq!( - texts, - [ - "newest reply", - "second question", - "oldest reply, part one\n\noldest reply, part two", - "first question" - ] - ); - assert_eq!(messages[0].role, Role::Assistant); - assert_eq!(messages[0].id, "msg_5"); - assert_eq!(messages[0].at.as_deref(), Some("1970-01-01T00:00:00.050Z")); - assert_eq!(messages[1].role, Role::Human); - // n counts replies with text; the prompt between them and the aborted assistant turn - // do not consume a slot. - let two = opencode::messages_for_session(&db, "ses_main", Schema::V1, 2).expect("two"); - assert_eq!(two.iter().map(|m| m.id.as_str()).collect::>(), ["msg_5", "msg_4", "msg_2"]); - match opencode::messages_for_session(&db, "ses_empty", Schema::V1, 25) { - Err(HostError::NoMessages(msg)) => assert!(msg.contains("ses_empty"), "{msg}"), - other => panic!("expected NoMessages, got {other:?}"), - } - drop(writer); - std::fs::remove_dir_all(&dir).expect("cleanup"); +pub(crate) fn message_v2(c: &Connection, id: &str, session: &str, seq: i64, kind: &str, data: &str) { + c.execute( + "INSERT INTO session_message (id, session_id, type, seq, time_created, time_updated, data) VALUES (?1, ?2, ?3, ?4, ?5, ?5, ?6)", + params![id, session, kind, seq, seq * 10, data], + ) + .expect("session_message"); } -#[test] -fn a_missing_database_is_reported_not_created() { - let dir = temp_dir("missing"); - let db = dir.join("opencode.db"); - match opencode::find_session(&db, Path::new("/work/app")) { - Err(HostError::NoTranscript(msg)) => assert!(msg.contains("no OpenCode database"), "{msg}"), - other => panic!("expected NoTranscript, got {other:?}"), - } - assert!(!db.exists(), "a read must not create the database"); - std::fs::remove_dir_all(&dir).expect("cleanup"); +pub(crate) fn part_v2(c: &Connection, message: &str, session: &str, ordinal: i64, kind: &str, data: &str) { + c.execute( + "INSERT INTO session_part (message_id, session_id, ordinal, type, time_created, time_updated, data) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?5, ?6)", + params![message, session, ordinal, kind, ordinal + 1, data], + ) + .expect("session_part"); } diff --git a/crates/plannotator-tui-hosts/tests/opencode/main.rs b/crates/plannotator-tui-hosts/tests/opencode/main.rs new file mode 100644 index 00000000..c37085ce --- /dev/null +++ b/crates/plannotator-tui-hosts/tests/opencode/main.rs @@ -0,0 +1,12 @@ +//! `OpenCode` messages out of a generated `opencode.db` (the 1.18 schema subset), read-only. +//! +//! Fixtures and helpers live in `fixture`; each other module holds the tests for one +//! invariant, so a failure names the rule it broke. + +#![allow(clippy::expect_used, clippy::indexing_slicing, clippy::panic, reason = "tests assert by panicking")] + +mod fixture; +mod parts; +mod session; +mod v1; +mod v2; diff --git a/crates/plannotator-tui-hosts/tests/opencode/parts.rs b/crates/plannotator-tui-hosts/tests/opencode/parts.rs new file mode 100644 index 00000000..bb938321 --- /dev/null +++ b/crates/plannotator-tui-hosts/tests/opencode/parts.rs @@ -0,0 +1,135 @@ +//! `OpenCode` 2.4 (`session_part` rows): a reply without payload text reads its visible parts +//! in `ordinal` order, and a part that cannot be read is an error naming what was being read. + +use plannotator_tui_hosts::opencode::Schema; +use plannotator_tui_hosts::{HostError, Role, opencode}; + +use super::fixture::{Db, message_v2, part_v2, populate_v2_parts}; + +#[test] +fn a_reply_read_from_its_parts_joins_the_visible_ones_in_ordinal_order() { + let db = Db::new("parts-order"); + let _writer = populate_v2_parts(db.file()); + let messages = opencode::messages_for_session(db.file(), "ses2_mixed", Schema::V2, 25).expect("messages"); + let parts = messages.iter().find(|m| m.id == "msg2_parts").expect("parts reply"); + assert_eq!(parts.text, "part one\n\npart two"); + assert_eq!(parts.role, Role::Assistant); + assert_eq!(parts.at.as_deref(), Some("1970-01-01T00:01:10.003Z")); +} + +#[test] +fn injected_ignored_and_reasoning_parts_are_not_reply_text() { + let db = Db::new("parts-skipped"); + let writer = populate_v2_parts(db.file()); + message_v2( + &writer, + "msg2_only_noise", + "ses2_mixed", + 7, + "assistant", + r#"{"content":[],"time":{"created":70007}}"#, + ); + part_v2( + &writer, + "msg2_only_noise", + "ses2_mixed", + 0, + "reasoning", + r#"{"type":"reasoning","text":"thinking"}"#, + ); + part_v2( + &writer, + "msg2_only_noise", + "ses2_mixed", + 1, + "text", + r#"{"type":"text","text":"injected","synthetic":true}"#, + ); + part_v2( + &writer, + "msg2_only_noise", + "ses2_mixed", + 2, + "text", + r#"{"type":"text","text":"draft","ignored":true}"#, + ); + let messages = opencode::messages_for_session(db.file(), "ses2_mixed", Schema::V2, 25).expect("messages"); + assert!( + messages.iter().all(|m| m.id != "msg2_only_noise"), + "a reply with only reasoning, injected and ignored parts has no text" + ); +} + +#[test] +fn a_reply_stored_in_both_formats_is_listed_once_from_its_payload() { + let db = Db::new("parts-both"); + let _writer = populate_v2_parts(db.file()); + let messages = opencode::messages_for_session(db.file(), "ses2_mixed", Schema::V2, 25).expect("messages"); + let both: Vec<&str> = messages.iter().filter(|m| m.id == "msg2_both").map(|m| m.text.as_str()).collect(); + assert_eq!(both, ["both reply"]); + assert!(messages.iter().all(|m| !m.text.contains("part duplicate"))); +} + +#[test] +fn a_mixed_session_lists_prompts_and_replies_newest_first() { + let db = Db::new("parts-order-all"); + let _writer = populate_v2_parts(db.file()); + let messages = opencode::messages_for_session(db.file(), "ses2_mixed", Schema::V2, 25).expect("messages"); + let ids: Vec<&str> = messages.iter().map(|m| m.id.as_str()).collect(); + let texts: Vec<&str> = messages.iter().map(|m| m.text.as_str()).collect(); + let roles: Vec = messages.iter().map(|m| m.role).collect(); + let times: Vec> = messages.iter().map(|m| m.at.as_deref()).collect(); + assert_eq!(ids, ["msg2_q2", "msg2_both", "msg2_parts", "msg2_legacy", "msg2_q1"]); + assert_eq!( + texts, + ["follow-up question", "both reply", "part one\n\npart two", "legacy reply", "mixed question"] + ); + assert_eq!(roles, [Role::Human, Role::Assistant, Role::Assistant, Role::Assistant, Role::Human]); + assert_eq!( + times, + [ + Some("1970-01-01T00:01:10.005Z"), + Some("1970-01-01T00:01:10.004Z"), + Some("1970-01-01T00:01:10.003Z"), + Some("1970-01-01T00:01:10.002Z"), + Some("1970-01-01T00:01:10.001Z"), + ] + ); +} + +#[test] +fn the_reply_limit_counts_replies_that_have_visible_text() { + let db = Db::new("parts-limit"); + let _writer = populate_v2_parts(db.file()); + // Only the reasoning turn is invisible, so a limit of two replies still reaches the parts + // reply; a limit of one stops at the newest reply and keeps the prompt after it. + let one = opencode::messages_for_session(db.file(), "ses2_mixed", Schema::V2, 1).expect("one"); + assert_eq!(one.iter().map(|m| m.id.as_str()).collect::>(), ["msg2_q2", "msg2_both"]); + let two = opencode::messages_for_session(db.file(), "ses2_mixed", Schema::V2, 2).expect("two"); + assert_eq!(two.iter().map(|m| m.id.as_str()).collect::>(), ["msg2_q2", "msg2_both", "msg2_parts"]); +} + +#[test] +fn malformed_part_json_is_an_error_naming_the_message_session_and_database() { + let db = Db::new("parts-bad"); + let writer = populate_v2_parts(db.file()); + message_v2( + &writer, + "msg2_broken", + "ses2_mixed", + 7, + "assistant", + r#"{"content":[],"time":{"created":70007}}"#, + ); + part_v2(&writer, "msg2_broken", "ses2_mixed", 0, "text", "{not json"); + let path = db.file().display().to_string(); + match opencode::messages_for_session(db.file(), "ses2_mixed", Schema::V2, 25) { + Err(HostError::NoTranscript(msg)) => { + assert!(msg.contains("msg2_broken"), "{msg}"); + assert!(msg.contains("ses2_mixed"), "{msg}"); + assert!(msg.contains(&path), "{msg}"); + assert!(msg.contains("text parts"), "{msg}"); + } + other => panic!("expected a part read error, got {other:?}"), + } +} diff --git a/crates/plannotator-tui-hosts/tests/opencode/session.rs b/crates/plannotator-tui-hosts/tests/opencode/session.rs new file mode 100644 index 00000000..e53a3102 --- /dev/null +++ b/crates/plannotator-tui-hosts/tests/opencode/session.rs @@ -0,0 +1,80 @@ +//! Picking a session: the newest top-level unarchived one for a directory, across schemas. + +use std::path::Path; + +use plannotator_tui_hosts::opencode::{Found, Schema}; +use plannotator_tui_hosts::{HostError, opencode}; + +use super::fixture::{CURRENT_SESSION_MESSAGE, Db, populate, populate_v2}; + +#[test] +fn newest_session_for_the_directory_skips_children_and_archived_ones() { + let db = Db::new("find"); + let _writer = populate(db.file()); + assert_eq!(opencode::find_session(db.file(), Path::new("/work/app")).expect("exact").id, "ses_main"); + assert_eq!( + opencode::find_session(db.file(), Path::new("/work/app/")).expect("trailing slash").id, + "ses_main" + ); + // Started in an ancestor: the newest session there, never a sibling project. + assert_eq!( + opencode::find_session(db.file(), Path::new("/work/app/src/deep")).expect("nested").id, + "ses_main" + ); + assert_eq!(opencode::find_session(db.file(), Path::new("/work/tools")).expect("root").id, "ses_root"); + assert_eq!(opencode::find_session(db.file(), Path::new("/work/other")).expect("other").id, "ses_other"); + match opencode::find_session(db.file(), Path::new("/elsewhere")) { + Err(HostError::NoTranscript(msg)) => assert!(msg.contains("/elsewhere"), "{msg}"), + other => panic!("expected NoTranscript, got {other:?}"), + } +} + +#[test] +fn an_opencode2_session_in_the_same_database_wins_when_it_is_newer() { + let db = Db::new("v2-wins"); + let _writer = populate_v2(db.file()); + let found = opencode::find_session(db.file(), Path::new("/work/app")).expect("found"); + assert_eq!(found, Found { id: "ses2_new".to_owned(), schema: Schema::V2, updated: 5000 }); + // The v1 session is still the answer for a directory only v1 knows. + assert_eq!( + opencode::find_session(db.file(), Path::new("/work/other")).expect("v1 only").schema, + Schema::V1 + ); + assert_eq!(opencode::schema_of(db.file(), "ses2_new").expect("v2"), Schema::V2); + assert_eq!(opencode::schema_of(db.file(), "ses_main").expect("v1"), Schema::V1); + assert!(matches!(opencode::schema_of(db.file(), "ses_nope"), Err(HostError::NoMessages(_)))); +} + +#[test] +fn a_database_without_the_v2_tables_still_reads_v1() { + let db = Db::new("v1only"); + let _writer = populate(db.file()); + assert_eq!(opencode::find_session(db.file(), Path::new("/work/app")).expect("v1").schema, Schema::V1); +} + +#[test] +fn current_schema_keeps_exact_ids_on_the_session_message_compatibility_path() { + let db = Db::new("current"); + let writer = populate(db.file()); + writer.execute_batch(CURRENT_SESSION_MESSAGE).expect("current session_message table"); + writer + .execute( + "INSERT INTO session_message (id, session_id, type, seq, time_created, time_updated, data) VALUES ('current-only', 'ses_main', 'assistant', 1, 60, 60, '{\"content\":[{\"type\":\"text\",\"text\":\"duplicate current row\"}]}')", + [], + ) + .expect("current row"); + assert_eq!(opencode::schema_of(db.file(), "ses_main").expect("schema"), Schema::V1); + let messages = opencode::messages_for_session(db.file(), "ses_main", Schema::V1, 1).expect("messages"); + assert_eq!(messages[0].text, "newest reply"); +} + +#[test] +fn a_missing_database_is_reported_not_created() { + let db = Db::new("missing"); + let path = db.file().to_path_buf(); + match opencode::find_session(&path, Path::new("/work/app")) { + Err(HostError::NoTranscript(msg)) => assert!(msg.contains("no OpenCode database"), "{msg}"), + other => panic!("expected NoTranscript, got {other:?}"), + } + assert!(!path.exists(), "a read must not create the database"); +} diff --git a/crates/plannotator-tui-hosts/tests/opencode/v1.rs b/crates/plannotator-tui-hosts/tests/opencode/v1.rs new file mode 100644 index 00000000..e78883c2 --- /dev/null +++ b/crates/plannotator-tui-hosts/tests/opencode/v1.rs @@ -0,0 +1,48 @@ +//! `OpenCode` 1 (`message` + `part` rows): text parts join in creation order, and only real +//! text is reply text. + +use plannotator_tui_hosts::opencode::Schema; +use plannotator_tui_hosts::{HostError, Role, opencode}; + +use super::fixture::{Db, populate}; + +#[test] +fn text_parts_join_in_order_and_injected_or_empty_ones_are_skipped() { + let db = Db::new("v1-read"); + let _writer = populate(db.file()); + let messages = opencode::messages_for_session(db.file(), "ses_main", Schema::V1, 25).expect("messages"); + let texts: Vec<&str> = messages.iter().map(|m| m.text.as_str()).collect(); + assert_eq!( + texts, + [ + "newest reply", + "second question", + "oldest reply, part one\n\noldest reply, part two", + "first question" + ] + ); + assert_eq!(messages[0].role, Role::Assistant); + assert_eq!(messages[0].id, "msg_5"); + assert_eq!(messages[0].at.as_deref(), Some("1970-01-01T00:00:00.050Z")); + assert_eq!(messages[1].role, Role::Human); +} + +#[test] +fn the_v1_reply_limit_counts_replies_with_text() { + let db = Db::new("v1-limit"); + let _writer = populate(db.file()); + // n counts replies with text; the prompt between them and the aborted assistant turn + // do not consume a slot. + let two = opencode::messages_for_session(db.file(), "ses_main", Schema::V1, 2).expect("two"); + assert_eq!(two.iter().map(|m| m.id.as_str()).collect::>(), ["msg_5", "msg_4", "msg_2"]); +} + +#[test] +fn a_v1_session_without_text_is_reported_by_id() { + let db = Db::new("v1-empty"); + let _writer = populate(db.file()); + match opencode::messages_for_session(db.file(), "ses_empty", Schema::V1, 25) { + Err(HostError::NoMessages(msg)) => assert!(msg.contains("ses_empty"), "{msg}"), + other => panic!("expected NoMessages, got {other:?}"), + } +} diff --git a/crates/plannotator-tui-hosts/tests/opencode/v2.rs b/crates/plannotator-tui-hosts/tests/opencode/v2.rs new file mode 100644 index 00000000..91c099c3 --- /dev/null +++ b/crates/plannotator-tui-hosts/tests/opencode/v2.rs @@ -0,0 +1,50 @@ +//! `OpenCode` 2 (`session_message` payload only, as before 2.4): the payload's text blocks are +//! the reply, and a database without the part table keeps the old tolerance. + +use plannotator_tui_hosts::opencode::Schema; +use plannotator_tui_hosts::{Role, opencode}; + +use super::fixture::{Db, message_v2, populate_v2}; + +#[test] +fn payload_text_blocks_join_in_order_and_reasoning_is_not_reply_text() { + let db = Db::new("v2-payload"); + let _writer = populate_v2(db.file()); + let messages = opencode::messages_for_session(db.file(), "ses2_new", Schema::V2, 25).expect("messages"); + let texts: Vec<&str> = messages.iter().map(|m| m.text.as_str()).collect(); + assert_eq!( + texts, + ["OPENCODE2_V2_SESSION_SELECTED\n\nDone.", "reply with exactly OPENCODE2_V2_SESSION_SELECTED"] + ); + assert_eq!(messages[0].role, Role::Assistant); + assert_eq!(messages[0].id, "msg2_3"); + assert_eq!(messages[0].at.as_deref(), Some("1970-01-01T00:00:50.002Z")); + assert_eq!(messages[1].role, Role::Human); +} + +#[test] +fn the_v2_reply_limit_counts_replies_with_payload_text() { + let db = Db::new("v2-payload-limit"); + let _writer = populate_v2(db.file()); + // A limit of one stops at the newest reply: the reasoning-only turn and the switch rows + // take no slot, so the next reply is not reached. + let one = opencode::messages_for_session(db.file(), "ses2_new", Schema::V2, 1).expect("one"); + assert_eq!(one.iter().map(|m| m.id.as_str()).collect::>(), ["msg2_3"]); + let two = opencode::messages_for_session(db.file(), "ses2_new", Schema::V2, 2).expect("two"); + assert_eq!(two.iter().map(|m| m.id.as_str()).collect::>(), ["msg2_3", "msg2_1"]); +} + +#[test] +fn a_malformed_v2_message_payload_is_skipped_rather_than_failing_the_read() { + let db = Db::new("v2-bad-payload"); + let writer = populate_v2(db.file()); + message_v2(&writer, "msg2_bad", "ses2_new", 6, "assistant", "{not json"); + // No part table here: the payload is the only source, and one unreadable row does not + // hide the rest of the session. + let messages = opencode::messages_for_session(db.file(), "ses2_new", Schema::V2, 25).expect("messages"); + assert_eq!( + messages.iter().map(|m| m.id.as_str()).collect::>(), + ["msg2_3", "msg2_1"], + "the malformed row is skipped, the readable ones stay" + ); +} From 0959909cabb7bd8c5b65f5bbeda3707226122a70 Mon Sep 17 00:00:00 2001 From: Michael Ledin Date: Wed, 25 Nov 2026 16:25:25 +0300 Subject: [PATCH 3/8] docs: describe the OpenCode 2.4 reply history fix --- docs/opencode-2.4-history-design.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 docs/opencode-2.4-history-design.md diff --git a/docs/opencode-2.4-history-design.md b/docs/opencode-2.4-history-design.md new file mode 100644 index 00000000..8f129182 --- /dev/null +++ b/docs/opencode-2.4-history-design.md @@ -0,0 +1,21 @@ +# Restore the reply picker for OpenCode 2.4 + +## Problem + +Herdr's `annotate.last` calls `plannotator-tui herdr last`. The OpenCode V2 reader in `crates/plannotator-tui-hosts/src/opencode.rs` reads assistant text only from `session_message.data.content[]`. In observed OpenCode 2.4.0/2.4.1 sessions, `content` is empty and completed replies have text rows in `session_part`. A resumed session can contain both formats, so the picker can silently fall back to older replies. A new session can instead report that there are no assistant messages. + +## Proposed change + +Keep the existing session resolution and the `session_message` scan in descending `seq` order. In `messages_v2`: + +1. Check once whether `session_part` exists. If it does, prepare a reusable read-only statement: `SELECT data FROM session_part WHERE message_id = ?1 AND session_id = ?2 AND type = 'text' ORDER BY ordinal ASC`. The primary key starts with `message_id`, so the query does not need a session-wide scan or a new index. +2. For each assistant message, extract visible inline text exactly as today. If that produces no nonblank text and the parts statement is available, run it for that message and extract `data.text` using the existing `part_text` helper. Join qualifying parts with the existing paragraph separator (`\n\n`). Choose one source per message; do not concatenate them and risk duplicate replies. +3. Leave user prompts, message IDs, timestamps, ordering and the reply limit unchanged. Blank, ignored, synthetic, reasoning-only and tool-only parts do not count as replies. Preserve normal SQL error reporting; an absent optional table is the expected legacy case, not an error. + +Detect the format by available text and tables rather than `session_v2.version`: resumed sessions can retain their original version while storing new replies as parts. Do not modify the OpenCode database or change Herdr shortcuts, delivery or the V1 reader. + +## Verification + +Add a synthetic mixed-history fixture in `crates/plannotator-tui-hosts/tests/opencode.rs`: an older inline reply; a newer multipart reply with empty inline content; a reply seeded in both formats; a user prompt; and a more recent assistant row with only non-displayable parts. Insert multipart rows out of order. Assert that the reader returns the new reply first, assembles its parts in ordinal order, emits the dual-format reply once, preserves prompt/ID/timestamp behavior and applies the limit to visible assistant replies. Keep the existing V1 and V2-without-`session_part` tests. + +Run `cargo test -p plannotator-tui-hosts --test opencode`. Then compare `plannotator-tui last --host opencode --session-id --print` with the newest visible reply in a known affected session, without sharing its contents. Finally, try `Ctrl+B`, then `Shift+O` in the focused OpenCode pane with the patched binary actually used by the Herdr plugin; the Homebrew binary is a separate installation. From e7a9a92f1746205bb20d32f8910462880148aeef Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Wed, 25 Nov 2026 11:50:32 -0500 Subject: [PATCH 4/8] docs(spec): point the OpenCode path comparison link at opencode/mod.rs --- docs/spec-windows-full.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/spec-windows-full.md b/docs/spec-windows-full.md index ad5d1b56..4bf01034 100644 --- a/docs/spec-windows-full.md +++ b/docs/spec-windows-full.md @@ -82,7 +82,7 @@ The application already contains the Windows-specific path behavior required by ([`locate.rs`](../crates/plannotator-tui/src/last/locate.rs#L71-L78), [`locate.rs`](../crates/plannotator-tui/src/last/locate.rs#L180-L193)). - OpenCode path comparisons convert backslashes to slashes and compare case-insensitively on - Windows ([`opencode.rs`](../crates/plannotator-tui-hosts/src/opencode.rs#L291-L299)). Copilot + Windows ([`opencode/mod.rs`](../crates/plannotator-tui-hosts/src/opencode/mod.rs#L145-L153)). Copilot and Droid directory matching also tolerate Windows separators and case ([`copilot.rs`](../crates/plannotator-tui-hosts/src/copilot.rs#L160-L163), [`droid.rs`](../crates/plannotator-tui-hosts/src/droid.rs#L28-L37)). From 637da0220b2b5918a99d7a1dda5dddcd98891a6d Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Wed, 25 Nov 2026 11:50:32 -0500 Subject: [PATCH 5/8] docs(hosts): drop the claim that the OpenCode 1 reader skips unparsable parts Its query filters with json_extract, which fails the read on a malformed part row. --- crates/plannotator-tui-hosts/src/opencode/payload.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/plannotator-tui-hosts/src/opencode/payload.rs b/crates/plannotator-tui-hosts/src/opencode/payload.rs index 683d9065..09f98b0d 100644 --- a/crates/plannotator-tui-hosts/src/opencode/payload.rs +++ b/crates/plannotator-tui-hosts/src/opencode/payload.rs @@ -18,8 +18,7 @@ pub(super) fn injected(json: &Value) -> bool { flagged("synthetic") || flagged("ignored") } -/// The text of an `OpenCode` 1 `part.data` payload when it is real text. A row that will not -/// parse is not text; the 1.x reader has always skipped those rather than failed. +/// The text of an `OpenCode` 1 `part.data` payload when it is real text. pub(super) fn part_text(data: &str) -> Option { let json: Value = serde_json::from_str(data).ok()?; let text = json_text(&json)?; From 948263287150b43ce9f26e952ea2657c1c9aec59 Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Wed, 25 Nov 2026 11:52:25 -0500 Subject: [PATCH 6/8] fix(hosts): prepare the OpenCode part query on first use A session whose replies all carry payload text no longer depends on the session_part columns, so a later change to that table cannot break it. --- .../src/opencode/messages.rs | 3 +- .../src/opencode/parts.rs | 67 +++++++++---------- .../tests/opencode/parts.rs | 29 ++++++++ 3 files changed, 64 insertions(+), 35 deletions(-) diff --git a/crates/plannotator-tui-hosts/src/opencode/messages.rs b/crates/plannotator-tui-hosts/src/opencode/messages.rs index 5172c12c..c8334cf3 100644 --- a/crates/plannotator-tui-hosts/src/opencode/messages.rs +++ b/crates/plannotator-tui-hosts/src/opencode/messages.rs @@ -82,7 +82,8 @@ fn messages_v1(db: &Path, session_id: &str, n: usize) -> Result, Ho fn messages_v2(db: &Path, session_id: &str, n: usize) -> Result, HostError> { let connection = open_read_only(db, WHAT)?; // The part table arrived in 2.4; a database written before it has none, and the message - // payload is then the only source. Prepared once, the reader serves every row. + // payload is then the only source. The part query is prepared on the first reply without + // payload text and then serves every such reply. let mut parts = Parts::new(&connection, db, session_id)?; let mut statement = connection .prepare( diff --git a/crates/plannotator-tui-hosts/src/opencode/parts.rs b/crates/plannotator-tui-hosts/src/opencode/parts.rs index 98be5853..58edfcf0 100644 --- a/crates/plannotator-tui-hosts/src/opencode/parts.rs +++ b/crates/plannotator-tui-hosts/src/opencode/parts.rs @@ -1,5 +1,5 @@ -//! The `OpenCode` 2.4 part reader: the `session_part` statement is prepared once per read and -//! reused per message id, and a failure names the message it was reading. +//! The `OpenCode` 2.4 part reader: the `session_part` statement is prepared on the first reply +//! that needs it and reused per message id, and a failure names the message it was reading. use std::path::Path; @@ -9,54 +9,59 @@ use serde_json::Value; use super::payload::{injected, json_text}; use crate::HostError; +const QUERY: &str = "SELECT data FROM session_part \ + WHERE session_id = ?1 AND message_id = ?2 AND type = 'text' \ + ORDER BY ordinal ASC"; + /// Reads the text parts of one reply at a time, or nothing when the database predates the /// part table. Owned names keep the borrow on the connection alone. pub(super) struct Parts<'connection> { + connection: &'connection Connection, + /// Whether the database has a part table (written by `OpenCode` 2.4 or later). + table: bool, + /// Prepared on first use, so a session whose replies are all inline never depends on the + /// part table's columns. statement: Option>, database: String, session_id: String, } impl<'connection> Parts<'connection> { - /// Prepare the reader for `session_id`, or a reader that yields nothing when the database - /// has no part table (written before `OpenCode` 2.4). + /// A reader for `session_id`, which yields nothing when the database has no part table. pub(super) fn new( connection: &'connection Connection, database: &Path, session_id: &str, ) -> Result { - let session_id = session_id.to_owned(); - let database = database.display().to_string(); - let statement = if super::has_table(connection, "session_part")? { - Some( - connection - .prepare( - "SELECT data FROM session_part \ - WHERE session_id = ?1 AND message_id = ?2 AND type = 'text' \ - ORDER BY ordinal ASC", - ) - .map_err(|e| part_error(&session_id, &database, None, &e))?, - ) - } else { - None - }; - Ok(Self { statement, database, session_id }) + Ok(Self { + connection, + table: super::has_table(connection, "session_part")?, + statement: None, + database: database.display().to_string(), + session_id: session_id.to_owned(), + }) } /// The visible text of `message_id`'s parts, joined in `ordinal` order, or `None` when it /// has no visible text there. A part row that will not parse is an error: it was selected /// for this reply, so silence would drop text the user is owed. pub(super) fn text_for(&mut self, message_id: &str) -> Result, HostError> { - let Self { statement, database, session_id } = self; - let Some(statement) = statement.as_mut() else { return Ok(None) }; + let Self { connection, table, statement, database, session_id } = self; + if !*table { + return Ok(None); + } + let error = |e: &dyn std::fmt::Display| part_error(session_id, database, message_id, e); + let statement = match statement { + Some(statement) => statement, + None => statement.insert(connection.prepare(QUERY).map_err(|e| error(&e))?), + }; let rows = statement .query_map(params![session_id.as_str(), message_id], |row| row.get::<_, String>(0)) - .map_err(|e| part_error(session_id, database, Some(message_id), &e))?; + .map_err(|e| error(&e))?; let mut texts = Vec::new(); for row in rows { - let data = row.map_err(|e| part_error(session_id, database, Some(message_id), &e))?; - let json: Value = serde_json::from_str(&data) - .map_err(|e| part_error(session_id, database, Some(message_id), &e))?; + let data = row.map_err(|e| error(&e))?; + let json: Value = serde_json::from_str(&data).map_err(|e| error(&e))?; if let Some(text) = json_text(&json) && !injected(&json) { @@ -68,14 +73,8 @@ impl<'connection> Parts<'connection> { } /// A part read failure: names the operation, the session and message, and the database. -fn part_error( - session_id: &str, - database: &str, - message_id: Option<&str>, - err: &impl std::fmt::Display, -) -> HostError { - let reply = message_id.map(|id| format!(" message {id}")).unwrap_or_default(); +fn part_error(session_id: &str, database: &str, message_id: &str, err: &dyn std::fmt::Display) -> HostError { HostError::NoTranscript(format!( - "reading the text parts of OpenCode session {session_id}{reply} in {database}: {err}" + "reading the text parts of OpenCode session {session_id} message {message_id} in {database}: {err}" )) } diff --git a/crates/plannotator-tui-hosts/tests/opencode/parts.rs b/crates/plannotator-tui-hosts/tests/opencode/parts.rs index bb938321..2a92a84c 100644 --- a/crates/plannotator-tui-hosts/tests/opencode/parts.rs +++ b/crates/plannotator-tui-hosts/tests/opencode/parts.rs @@ -133,3 +133,32 @@ fn malformed_part_json_is_an_error_naming_the_message_session_and_database() { other => panic!("expected a part read error, got {other:?}"), } } + +#[test] +fn replies_with_payload_text_read_even_when_the_part_table_has_other_columns() { + let db = Db::new("parts-other-columns"); + let writer = populate_v2_parts(db.file()); + // A later `OpenCode` could reshape the part table; a session that never needs it still reads. + writer + .execute_batch( + "DROP TABLE session_part; + CREATE TABLE session_part (message_id TEXT NOT NULL, position INTEGER NOT NULL, + payload TEXT NOT NULL, PRIMARY KEY (message_id, position));", + ) + .expect("reshaped part table"); + message_v2(&writer, "msg2_i1", "ses2_inline", 1, "user", r#"{"text":"inline question"}"#); + message_v2( + &writer, + "msg2_i2", + "ses2_inline", + 2, + "assistant", + r#"{"content":[{"type":"text","text":"inline reply"}],"time":{"created":70010}}"#, + ); + let messages = + opencode::messages_for_session(db.file(), "ses2_inline", Schema::V2, 25).expect("messages"); + assert_eq!( + messages.iter().map(|m| m.text.as_str()).collect::>(), + ["inline reply", "inline question"] + ); +} From c5fa3be8a6d18e5547dbb2c9f45ca9cbc8cf3c3b Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Wed, 25 Nov 2026 11:52:51 -0500 Subject: [PATCH 7/8] docs: record the OpenCode 2.4 part rows in decisions instead of a design doc --- docs/decisions.md | 21 +++++++++++++++++++-- docs/opencode-2.4-history-design.md | 21 --------------------- 2 files changed, 19 insertions(+), 23 deletions(-) delete mode 100644 docs/opencode-2.4-history-design.md diff --git a/docs/decisions.md b/docs/decisions.md index ac5edd3e..bf48cb5e 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -371,14 +371,31 @@ branch `beta`, `packages/cli`) keeps the same data directory and, on the standar `time_updated`, `time_archived`) and `session_message` (`type` is the role, `seq` the order, `data` the payload; an assistant's text is `content[].type == "text"`, a user's is `text`; `synthetic`, `system`, `skill`, `shell`, `compaction` and the `*-switched` rows are not -rendered). There is no `part` table. Other channels use `opencode-.db` beside it -(`packages/cli/src/server-process.ts`). After the v1 migration both table families hold data, +rendered). This version has no part table; 2.4 adds one (below). Other channels use +`opencode-.db` beside it (`packages/cli/src/server-process.ts`). After the v1 migration both table families hold data, so the reader now considers every `opencode*.db` in the data dir and both schemas, and picks the newest top-level unarchived session for the cwd across all of them; a `--session-id` is looked up in whichever table holds it. Verified against the `beta` source (`packages/core/src/session/sql.ts`, `packages/schema/src/session-message.ts`, `packages/util/src/global-roots.ts`) and a mixed-schema fixture reproducing the report. +**OpenCode 2.4** (2026-11-25, plannotator-tui#209, #203). OpenCode 2.4 (migration +`20261029002625_session_part`) writes each part of an assistant message as its own +`session_part` row (`message_id`, `session_id`, `ordinal`, `type`, `data`) and leaves +`session_message.data.content` empty, so the reader found no recent replies. A session +resumed under 2.4 holds both shapes. A reply's text is its inline `content[]` text when it has +any, else its `text` parts in `ordinal` order, so no reply is listed twice; `reasoning`, +`tool` and `step` parts, and parts flagged `synthetic` or `ignored`, are not reply text. The +shape is decided per reply, not by `session_v2.version`, which a resumed session keeps. +OpenCode's own reader (`withParts` in `packages/core/src/session/history.ts`) shows the parts +and then any inline content; both exist only when an older build wrote to a message 2.4 had +split. A database without `session_part` reads as before, and the part query is prepared on +the first reply that needs it, so a session whose replies are all inline never depends on that +table's columns. A part row that will not parse fails the read and names the session, message +and database: it was selected for that reply, so skipping it would drop text silently. +Verified against the `dev` source (the migration, `packages/core/src/session/sql.ts`, +`history.ts`, `projector.ts`) and a synthetic 2.4 database. + **Command Code** (2026-10-27, plannotator-tui#106). Command Code writes pi's session format: a `session` header with the `cwd`, then `id`/`parentId` entries (`message`, `session_info`, `model_change`, ...), so it is pi's reader over another layout, diff --git a/docs/opencode-2.4-history-design.md b/docs/opencode-2.4-history-design.md deleted file mode 100644 index 8f129182..00000000 --- a/docs/opencode-2.4-history-design.md +++ /dev/null @@ -1,21 +0,0 @@ -# Restore the reply picker for OpenCode 2.4 - -## Problem - -Herdr's `annotate.last` calls `plannotator-tui herdr last`. The OpenCode V2 reader in `crates/plannotator-tui-hosts/src/opencode.rs` reads assistant text only from `session_message.data.content[]`. In observed OpenCode 2.4.0/2.4.1 sessions, `content` is empty and completed replies have text rows in `session_part`. A resumed session can contain both formats, so the picker can silently fall back to older replies. A new session can instead report that there are no assistant messages. - -## Proposed change - -Keep the existing session resolution and the `session_message` scan in descending `seq` order. In `messages_v2`: - -1. Check once whether `session_part` exists. If it does, prepare a reusable read-only statement: `SELECT data FROM session_part WHERE message_id = ?1 AND session_id = ?2 AND type = 'text' ORDER BY ordinal ASC`. The primary key starts with `message_id`, so the query does not need a session-wide scan or a new index. -2. For each assistant message, extract visible inline text exactly as today. If that produces no nonblank text and the parts statement is available, run it for that message and extract `data.text` using the existing `part_text` helper. Join qualifying parts with the existing paragraph separator (`\n\n`). Choose one source per message; do not concatenate them and risk duplicate replies. -3. Leave user prompts, message IDs, timestamps, ordering and the reply limit unchanged. Blank, ignored, synthetic, reasoning-only and tool-only parts do not count as replies. Preserve normal SQL error reporting; an absent optional table is the expected legacy case, not an error. - -Detect the format by available text and tables rather than `session_v2.version`: resumed sessions can retain their original version while storing new replies as parts. Do not modify the OpenCode database or change Herdr shortcuts, delivery or the V1 reader. - -## Verification - -Add a synthetic mixed-history fixture in `crates/plannotator-tui-hosts/tests/opencode.rs`: an older inline reply; a newer multipart reply with empty inline content; a reply seeded in both formats; a user prompt; and a more recent assistant row with only non-displayable parts. Insert multipart rows out of order. Assert that the reader returns the new reply first, assembles its parts in ordinal order, emits the dual-format reply once, preserves prompt/ID/timestamp behavior and applies the limit to visible assistant replies. Keep the existing V1 and V2-without-`session_part` tests. - -Run `cargo test -p plannotator-tui-hosts --test opencode`. Then compare `plannotator-tui last --host opencode --session-id --print` with the newest visible reply in a known affected session, without sharing its contents. Finally, try `Ctrl+B`, then `Shift+O` in the focused OpenCode pane with the patched binary actually used by the Herdr plugin; the Homebrew binary is a separate installation. From 521c047a7faf9bef74ab66fca37fb63c10a2b1cd Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Wed, 25 Nov 2026 11:52:51 -0500 Subject: [PATCH 8/8] docs(hosts): state the OpenCode 2.4 reply rule in the reader's module comment --- crates/plannotator-tui-hosts/src/opencode/mod.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/plannotator-tui-hosts/src/opencode/mod.rs b/crates/plannotator-tui-hosts/src/opencode/mod.rs index ab6e489d..5c96c39a 100644 --- a/crates/plannotator-tui-hosts/src/opencode/mod.rs +++ b/crates/plannotator-tui-hosts/src/opencode/mod.rs @@ -21,8 +21,9 @@ //! //! `OpenCode` 2.4 (migration `20261029002625_session_part`) writes each part as its own //! `session_part` row (`message_id`, `session_id`, `ordinal`, `type`, `data`) and leaves the -//! assistant payload's `content` empty. The text of such a reply is its `text` parts in -//! `ordinal` order. A reply keeps whichever format carries its text; the two are never mixed. +//! assistant payload's `content` empty. A reply's text is its payload text when it has any, +//! else its `text` parts in `ordinal` order; one source per reply, so none is listed twice +//! (`docs/decisions.md`, decision 14). mod messages; mod parts;