Skip to content

Commit 2a3e799

Browse files
authored
Merge pull request #596 from OpenCoven/fix/566-session-index-user-keys
fix: index every user message in the session search index
2 parents 69ea36c + aeb2929 commit 2a3e799

5 files changed

Lines changed: 244 additions & 32 deletions

File tree

‎scripts/tui-tests/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -178,7 +178,7 @@ lands on the main screen. No secrets or network access required.
178178
| `cases/29_tool_results_kept.sh` | Tool results after a tool turn | In Classic (`COVEN_CODE_UI` unset) and Next, `fake_anthropic.py` asks for a Bash call, the user approves it, and the model answers its result. Once the turn ends, single key presses (`x`, Backspace, as typing sends them) precede a follow-up prompt, whose request, read from the full `messages` the fake logs to a file of their own, must carry the call and, in the user message right after it, the tool result answering it; needs `python3` |
179179
| `cases/30_panic_restore.sh` | Panic restoration | The product has no known input that panics, so the tui crate's `panic_restore` example takes the terminal with the real `setup_terminal` and panics on request; `panic_restore_pty.py` runs it on a raw PTY, with `setup_terminal` for each renderer (Classic and Next; their event loops are not involved). Before the panic: raw termios (output processing off too), alternate screen, mouse capture, bracketed paste, hidden cursor and pushed keyboard flags. A main-thread panic restores every termios field and, before the panic message, turns output processing back on (the message's first line break arrives as CRLF), clears the title set at startup, pops the keyboard flags before leaving the alternate screen they were pushed on (each screen has its own keyboard stack, #410), leaves the alternate screen, turns mouse capture and bracketed paste off and shows the cursor, all once, so no pop is sent on the main screen; the message is printed and the exit status is 101. A worker-thread panic restores nothing and the probe keeps drawing; its later main-thread panic still restores. After a suspend and resume through the real `suspend_terminal`, which sets the terminal up again, a panic still restores, once: the panic hook is installed once per process (#417). With `COVEN_CODE_KEYBOARD_ENHANCEMENT=0` no flags are pushed and no pop is sent. The line containing "current behaviour" pins a detail that needs a decision, not endorses it (Unix; Windows has its own restore branch, which is not exercised): a worker-thread panic prints its message onto the live screen. Needs `python3` and the probe |
180180
| `cases/31_classic_daemon_glyph.sh` | Coven daemon glyph | In Classic (`COVEN_CODE_UI` unset), a fake daemon on `coven.sock` in a disposable `COVEN_HOME` answers every request. The footer shows `✦ coven` while it runs, turns to `○ coven` within 25 s of the fake stopping and its socket being removed, with no input, and back to `✦ coven` within 25 s of a fresh fake starting; needs `python3` |
181-
| `cases/32_one_runtime.sh` | One runtime per renderer (#408) | In Classic (`COVEN_CODE_UI` unset) and Next, `fake_anthropic.py` drives two real turns, an approved Bash call and then a text answer. Between them the window grows by 20 columns and 5 rows until the app draws a rule that wide, then goes back. There is one session file after the first turn, and after the second turn and the exit it is still that one file with that id; under the home and the project, the only session file (`sessions/*.json`) and session index (`sessions.db`) are that file and that index, which holds that one session. The fake saw three streamed requests, each carrying the one before it, its reply and the next user message, and the request of the second turn came on a TCP connection the first turn used (the fake numbers connections in a log of its own), so it came from the same HTTP connection pool. The saved session is the last request's conversation plus its answer, and every indexed message is that session's. A user message has no uuid, so the index keeps only the first one ever (current behaviour); the check uses the answers. The tool-result request inside the first turn is not checked on its own. Not shown: anything built but never used to send or save; clients that share one pool; and the other clients the process builds the same way in both renderers (the registry's Anthropic provider, the per-goal-turn wrapper, Agent sub-agents, memory extraction, which starts at 20 messages and which `fake_anthropic.py` answers and keeps out of its request logs, and the replacements made by `/refresh` and an in-session login); one store object, since the index is opened at every save; the scheduler and memory authority; relaunching the other renderer on the same session, `/resume` and `/clear`; any transport but the direct API-key one; needs `python3` |
181+
| `cases/32_one_runtime.sh` | One runtime per renderer (#408) | In Classic (`COVEN_CODE_UI` unset) and Next, `fake_anthropic.py` drives two real turns, an approved Bash call and then a text answer. Between them the window grows by 20 columns and 5 rows until the app draws a rule that wide, then goes back. There is one session file after the first turn, and after the second turn and the exit it is still that one file with that id; under the home and the project, the only session file (`sessions/*.json`) and session index (`sessions.db`) are that file and that index, which holds that one session. The fake saw three streamed requests, each carrying the one before it, its reply and the next user message, and the request of the second turn came on a TCP connection the first turn used (the fake numbers connections in a log of its own), so it came from the same HTTP connection pool. The saved session is the last request's conversation plus its answer, and every indexed message is that session's, the answer of each turn included. Each of the two user prompts is in the index exactly once, though the session was saved after each turn (#566). The tool-result request inside the first turn is not checked on its own. Not shown: anything built but never used to send or save; clients that share one pool; and the other clients the process builds the same way in both renderers (the registry's Anthropic provider, the per-goal-turn wrapper, Agent sub-agents, memory extraction, which starts at 20 messages and which `fake_anthropic.py` answers and keeps out of its request logs, and the replacements made by `/refresh` and an in-session login); one store object, since the index is opened at every save; the scheduler and memory authority; relaunching the other renderer on the same session, `/resume` and `/clear`; any transport but the direct API-key one; needs `python3` |
182182
| `cases/33_daemon_restart_unknown.sh` | Restarted Coven daemon (#412) | In Classic (`COVEN_CODE_UI` unset) and Next, with `daemonLedger` on, a fake daemon on `coven.sock` in a disposable `COVEN_HOME` answers health with its own pid and start time and logs every request. The session registers with it once. The fake is stopped and a second one, a new process, starts on the same path: within 30 s, with no input, Next's header reads `ledger unknown` instead of `ledger-registered`, and Classic's footer shows `◌ coven (unknown)` and its welcome line `unknown` instead of `online`. Across two more probes and one turn against `fake_anthropic.py`, the new daemon receives no registration. `/session resume <id>` then registers that session with it exactly once, and the state reads registered and online again (Classic's online glyph returns only once the new daemon has accepted the registration); needs `python3` |
183183
| `cases/34_command_error_clears.sh` | A command error leaves the status row (#529) | In Classic (`COVEN_CODE_UI` unset, before its first turn) and Next, a disposable `COVEN_HOME` holds a `coven.sock` that is a plain file, so every daemon request fails. `/coven sessions` puts `Error: Coven daemon offline. ...` on the status row; a following `/coven status` prints `Coven daemon: offline` and the earlier error is gone from the status row. No provider, nothing listens |
184184
| `cases/35_resume_short_session_id.sh` | Resuming an id that is not a UUID (#573) | In Classic (`COVEN_CODE_UI` unset) and Next, a fake `claude` answers one turn in a session started with `--session-id ab` and one started with `--session-id 日本語セッション` (byte 8 falls inside its third character). A fresh launch for each runs `/session resume ab` or `/session resume 日本語セッション`: each shows that session's transcript, the app is still running and nothing panicked; Next's status names the session (`Resumed session ab.`). No network or model |

‎scripts/tui-tests/cases/32_one_runtime.sh‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -206,15 +206,17 @@ if os.path.exists(db_path):
206206
else:
207207
indexed, owners, texts = None, None, []
208208
report("the session index holds one session, with that id", indexed == [first_id], indexed)
209-
# Current behaviour, not endorsed: the index keys a message by its uuid, and
210-
# a user message has none, so each is stored under the id "unknown", which
211-
# the whole index shares, and only the first one ever is kept. The answers
212-
# carry uuids, so they show both turns reached the index.
209+
# The answers carry uuids; the user messages have none and are keyed by
210+
# their session, role, text and repeat count (#566). The session was saved
211+
# after each turn, so a prompt indexed twice would show here.
213212
answers = [any(text.strip() == want for text in texts)
214213
for want in ("TOOL_RESULT_OK", "flood line\nflood line")]
215214
report("every indexed message belongs to that session, the answer of each turn included",
216215
owners == [first_id] and all(answers),
217216
"owners: %s; answers indexed: %s" % (owners, answers))
217+
prompts = [sum(text == want for text in texts) for want in (tool_prompt, text_prompt)]
218+
report("each user prompt is indexed once", prompts == [1, 1],
219+
"times indexed (tool prompt, text prompt): %s" % prompts)
218220
219221
requests = [line["messages"] for line in read_lines(messages_log)]
220222
streams = sorted((c for c in read_lines(connections_log) if c.get("stream")),

‎src-rust/crates/cli/src/main.rs‎

Lines changed: 8 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -3062,30 +3062,14 @@ async fn persist_interactive_session(
30623062
let db_path = claurst_core::config::Settings::config_dir().join("sessions.db");
30633063
if let Ok(store) = claurst_core::SqliteSessionStore::open(&db_path) {
30643064
let _ = store.save_session(&session.id, session.title.as_deref(), &session.model);
3065-
for msg in &session.messages {
3066-
if pending_uuid.is_some() && msg.uuid.as_deref() == pending_uuid {
3067-
continue;
3068-
}
3069-
let content_str = match &msg.content {
3070-
claurst_core::types::MessageContent::Text(t) => t.clone(),
3071-
claurst_core::types::MessageContent::Blocks(blocks) => blocks
3072-
.iter()
3073-
.filter_map(|b| {
3074-
if let claurst_core::types::ContentBlock::Text { text } = b {
3075-
Some(text.as_str())
3076-
} else {
3077-
None
3078-
}
3079-
})
3080-
.collect::<Vec<_>>()
3081-
.join(" "),
3082-
};
3083-
let role = match msg.role {
3084-
claurst_core::types::Role::User => "user",
3085-
claurst_core::types::Role::Assistant => "assistant",
3086-
};
3087-
let msg_id = msg.uuid.as_deref().unwrap_or("unknown");
3088-
let _ = store.save_message(&session.id, msg_id, role, &content_str, None);
3065+
if let Err(error) = store.index_messages(
3066+
&session.id,
3067+
session
3068+
.messages
3069+
.iter()
3070+
.filter(|msg| pending_uuid.is_none() || msg.uuid.as_deref() != pending_uuid),
3071+
) {
3072+
warn!(session_id = %session.id, %error, "Failed to index session for search");
30893073
}
30903074
}
30913075
}

‎src-rust/crates/cli/src/session_save_tests.rs‎

Lines changed: 100 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
11
use super::*;
22
use claurst_tui::notifications::{NotificationKind, NotificationQueue};
33

4-
#[test]
5-
fn session_save_failures_and_recovery_are_visible() {
4+
/// Runs one ignored worker test of this module in a child process whose
5+
/// config home is a fresh temporary directory, and checks that it finished.
6+
fn run_isolated_worker(worker: &str) {
67
let temp = tempfile::tempdir().unwrap();
78
let log = temp.path().join("stderr");
89
let mut child = std::process::Command::new(std::env::current_exe().unwrap())
910
.args([
1011
"--exact",
11-
"session_save_tests::session_save_worker",
12+
&format!("session_save_tests::{worker}"),
1213
"--ignored",
1314
"--nocapture",
1415
])
@@ -45,6 +46,16 @@ fn session_save_failures_and_recovery_are_visible() {
4546
assert_eq!(std::fs::read(temp.path().join("done")).unwrap(), b"checked");
4647
}
4748

49+
#[test]
50+
fn session_save_failures_and_recovery_are_visible() {
51+
run_isolated_worker("session_save_worker");
52+
}
53+
54+
#[test]
55+
fn session_index_keeps_every_user_message_once() {
56+
run_isolated_worker("session_index_worker");
57+
}
58+
4859
#[test]
4960
#[ignore = "isolated session save environment"]
5061
fn session_save_worker() {
@@ -137,3 +148,89 @@ fn session_save_worker() {
137148
});
138149
std::fs::write(home.join("done"), b"checked").unwrap();
139150
}
151+
152+
#[test]
153+
#[ignore = "isolated session save environment"]
154+
fn session_index_worker() {
155+
use claurst_core::types::Message;
156+
157+
let home = PathBuf::from(std::env::var_os("COVEN_CODE_HOME").unwrap());
158+
assert_eq!(Settings::config_dir(), home);
159+
let index_path = home.join("sessions.db");
160+
// An index written by an earlier build: its first user message ever was
161+
// stored under the id "unknown". That row is kept.
162+
{
163+
let index = claurst_core::SqliteSessionStore::open(&index_path).unwrap();
164+
index.save_session("legacy", None, "fixture-model").unwrap();
165+
index
166+
.save_message("legacy", "unknown", "user", "legacy-first-prompt", None)
167+
.unwrap();
168+
}
169+
let runtime = tokio::runtime::Builder::new_current_thread()
170+
.enable_all()
171+
.build()
172+
.unwrap();
173+
runtime.block_on(async {
174+
let mut notifications = NotificationQueue::new();
175+
let mut legacy = claurst_core::history::ConversationSession::new("fixture-model".into());
176+
legacy.id = "legacy".into();
177+
legacy.messages = vec![
178+
Message::user("legacy-first-prompt"),
179+
Message::user("legacy-second-prompt"),
180+
];
181+
let mut answer = Message::assistant("first-answer");
182+
answer.uuid = Some("answer-1".into());
183+
let mut first = claurst_core::history::ConversationSession::new("fixture-model".into());
184+
first.id = "first".into();
185+
first.messages = vec![
186+
Message::user("first-prompt-one"),
187+
answer,
188+
Message::user("first-prompt-two"),
189+
// The same text typed twice is two messages.
190+
Message::user("first-prompt-one"),
191+
];
192+
let mut second = claurst_core::history::ConversationSession::new("fixture-model".into());
193+
second.id = "second".into();
194+
second.messages = vec![Message::user("other-session-prompt")];
195+
// Every turn saves the whole session again.
196+
for session in [&legacy, &first, &first, &second, &second, &legacy] {
197+
assert!(persist_interactive_session(session, None, &mut notifications).await);
198+
}
199+
});
200+
201+
let index = claurst_core::SqliteSessionStore::open(&index_path).unwrap();
202+
for (text, session_id) in [
203+
("legacy-first-prompt", "legacy"),
204+
("legacy-second-prompt", "legacy"),
205+
("first-prompt-one", "first"),
206+
("first-prompt-two", "first"),
207+
("first-answer", "first"),
208+
("other-session-prompt", "second"),
209+
] {
210+
let found: Vec<_> = index
211+
.search_sessions(text)
212+
.unwrap()
213+
.into_iter()
214+
.map(|summary| summary.id)
215+
.collect();
216+
assert_eq!(found, [session_id], "search for {text}");
217+
}
218+
// `message_count` grows only when a row is inserted, so it counts rows.
219+
let mut counts: Vec<_> = index
220+
.list_sessions()
221+
.unwrap()
222+
.into_iter()
223+
.map(|summary| (summary.id, summary.message_count))
224+
.collect();
225+
counts.sort();
226+
assert_eq!(
227+
counts,
228+
[
229+
("first".to_owned(), 4),
230+
// The kept "unknown" row and one row per message.
231+
("legacy".to_owned(), 3),
232+
("second".to_owned(), 1)
233+
]
234+
);
235+
std::fs::write(home.join("done"), b"checked").unwrap();
236+
}

0 commit comments

Comments
 (0)