Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/services/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,7 @@ pub mod process;
pub mod provider_auth;
pub mod provider_probe;
pub mod relaunch;
pub mod session_search;
pub mod settings;
pub mod shell_env;
pub mod store;
Expand Down
380 changes: 380 additions & 0 deletions crates/services/src/session_search.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,380 @@
//! Lazy full-text search over persisted session event logs.
//!
//! The index is deliberately in-memory: each session is parsed only when its
//! JSONL file's length or modification time changes. This keeps the append-only
//! persistence format authoritative and avoids a second on-disk database.

use std::collections::{HashMap, HashSet};
use std::fs;
use std::time::SystemTime;

use agent::ItemContent;
use tcode_core::project::SessionMeta;
use tcode_core::session::{EntryContent, StoredEvent, Timeline};

use crate::store::SessionStore;

/// One final, folded timeline entry that contributes to content search.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SearchableEntry {
pub entry_id: String,
pub turn: usize,
pub text: String,
}

/// A content match suitable for presentation by a session picker.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionSearchHit {
pub session_id: String,
pub session_title: String,
pub entry_id: String,
pub turn: usize,
pub snippet: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct FileFingerprint {
len: u64,
modified: Option<SystemTime>,
}

#[derive(Debug, Clone)]
struct CachedSession {
fingerprint: FileFingerprint,
entries: Vec<SearchableEntry>,
}

/// Incremental, file-freshness-based content index for one [`SessionStore`].
pub struct SessionSearch {
store: SessionStore,
cache: HashMap<String, CachedSession>,
}

impl SessionSearch {
pub fn new(store: SessionStore) -> Self {
Self {
store,
cache: HashMap::new(),
}
}

/// Search sessions in the supplied order, returning at most `limit` hits.
/// Empty and whitespace-only queries intentionally return no content hits.
pub fn search(
&mut self,
sessions: &[SessionMeta],
query: &str,
limit: usize,
) -> Vec<SessionSearchHit> {
let query = query.trim();
if query.is_empty() || limit == 0 {
return Vec::new();
}

let live_ids: HashSet<&str> = sessions.iter().map(|meta| meta.id.as_str()).collect();
self.cache.retain(|id, _| live_ids.contains(id.as_str()));

let mut hits = Vec::new();
for meta in sessions {
self.refresh(meta);
let Some(cached) = self.cache.get(&meta.id) else {
continue;
};
for entry in &cached.entries {
let Some(snippet) = match_snippet(&entry.text, query, 140) else {
continue;
};
hits.push(SessionSearchHit {
session_id: meta.id.clone(),
session_title: meta.title.clone(),
entry_id: entry.entry_id.clone(),
turn: entry.turn,
snippet,
});
if hits.len() == limit {
return hits;
}
}
}
hits
}

fn refresh(&mut self, meta: &SessionMeta) {
let path = self.store.root().join(format!("{}.jsonl", meta.id));
let fingerprint = match fs::metadata(path) {
Ok(metadata) => FileFingerprint {
len: metadata.len(),
modified: metadata.modified().ok(),
},
Err(error) if error.kind() == std::io::ErrorKind::NotFound => FileFingerprint {
len: 0,
modified: None,
},
Err(error) => {
log::warn!("cannot inspect session log {}: {error}", meta.id);
return;
}
};
if self
.cache
.get(&meta.id)
.is_some_and(|cached| cached.fingerprint == fingerprint)
{
return;
}
let entries = extract_searchable_entries(&self.store.read_events(&meta.id));
self.cache.insert(
meta.id.clone(),
CachedSession {
fingerprint,
entries,
},
);
}
}

/// Fold persisted events and extract the final searchable representation.
///
/// Folding first deduplicates streaming deltas and item lifecycle updates, so
/// callers index what the chat ultimately displays rather than every wire event.
pub fn extract_searchable_entries(events: &[StoredEvent]) -> Vec<SearchableEntry> {
let timeline = Timeline::fold_events(events.iter().cloned());
let mut entries = Vec::new();
for entry in timeline
.entries
.iter()
.chain(timeline.children.values().flatten())
{
let text = match &entry.content {
EntryContent::Item(content) => searchable_item_text(content),
EntryContent::Steer {
text, attachments, ..
} => Some(join_parts(
std::iter::once(text.as_str()).chain(attachments.iter().map(String::as_str)),
)),
_ => None,
};
if let Some(text) = text.filter(|text| !text.trim().is_empty()) {
entries.push(SearchableEntry {
entry_id: entry.id.clone(),
turn: entry.turn,
text,
});
}
}
entries.sort_by_key(|entry| entry.turn);
entries
}

fn searchable_item_text(content: &ItemContent) -> Option<String> {
match content {
ItemContent::UserMessage {
text, attachments, ..
} => Some(join_parts(
std::iter::once(text.as_str()).chain(attachments.iter().map(String::as_str)),
)),
ItemContent::AssistantMessage { text } => Some(text.clone()),
ItemContent::CommandExecution { command, .. } => Some(command.clone()),
ItemContent::FileChange { changes, .. } => Some(join_parts(
changes.iter().map(|change| change.path.as_str()),
)),
ItemContent::ToolCall { name, input, .. } => {
Some(format!("{name} {}", compact_json(input)))
}
ItemContent::Subagent {
agent_type,
description,
summary,
..
} => Some(join_parts(
[agent_type.as_str(), description.as_str()]
.into_iter()
.chain(summary.iter().map(String::as_str)),
)),
ItemContent::WebSearch { query } => Some(query.clone()),
ItemContent::Other {
provider_kind,
summary,
} => Some(format!("{provider_kind} {summary}")),
ItemContent::Reasoning { .. } => None,
}
}

fn compact_json(value: &serde_json::Value) -> String {
serde_json::to_string(value).unwrap_or_default()
}

fn join_parts<'a>(parts: impl Iterator<Item = &'a str>) -> String {
parts
.filter(|part| !part.is_empty())
.collect::<Vec<_>>()
.join(" ")
}

/// Return a compact, whitespace-normalized snippet for a case-insensitive hit.
pub fn match_snippet(text: &str, query: &str, max_chars: usize) -> Option<String> {
let normalized = text.split_whitespace().collect::<Vec<_>>().join(" ");
let query = query.trim().to_lowercase();
if normalized.is_empty() || query.is_empty() {
return None;
}
let (match_start, match_end) = case_insensitive_range(&normalized, &query)?;
let chars: Vec<char> = normalized.chars().collect();
let start_char = normalized[..match_start].chars().count();
let end_char = normalized[..match_end].chars().count();
if chars.len() <= max_chars {
return Some(normalized);
}

let match_len = end_char.saturating_sub(start_char);
let context = max_chars.saturating_sub(match_len);
let mut start = start_char.saturating_sub(context / 2);
let end = (start + max_chars).min(chars.len());
start = end.saturating_sub(max_chars);
let mut snippet: String = chars[start..end].iter().collect();
if start > 0 {
snippet.insert(0, '…');
}
if end < chars.len() {
snippet.push('…');
}
Some(snippet)
}

fn case_insensitive_range(text: &str, lower_query: &str) -> Option<(usize, usize)> {
for (start, _) in text.char_indices() {
let suffix = &text[start..];
if !suffix.to_lowercase().starts_with(lower_query) {
continue;
}
let mut folded_len = 0;
let mut end = start;
for ch in suffix.chars() {
folded_len += ch.to_lowercase().map(char::len_utf8).sum::<usize>();
end += ch.len_utf8();
if folded_len >= lower_query.len() {
return Some((start, end));
}
}
}
None
}

#[cfg(test)]
mod tests {
use std::path::PathBuf;

use agent::{AgentEvent, ItemStatus, ProviderKind, ThreadItem};
use serde_json::json;
use tcode_core::project::SessionMeta;

use super::*;

fn completed(id: &str, content: ItemContent) -> StoredEvent {
AgentEvent::ItemCompleted(ThreadItem {
id: id.into(),
parent_item_id: None,
content,
})
.into()
}

#[test]
fn extracts_user_and_assistant_messages() {
let entries = extract_searchable_entries(&[
completed(
"user",
ItemContent::UserMessage {
text: "Where is auth.rs?".into(),
context_len: None,
attachments: Vec::new(),
},
),
completed(
"assistant",
ItemContent::AssistantMessage {
text: "It is under crates/runtime.".into(),
},
),
]);
assert_eq!(entries.len(), 2);
assert_eq!(entries[0].text, "Where is auth.rs?");
assert_eq!(entries[1].text, "It is under crates/runtime.");
}

#[test]
fn extracts_tool_titles_paths_and_commands() {
let entries = extract_searchable_entries(&[
completed(
"command",
ItemContent::CommandExecution {
command: "rg auth.rs crates".into(),
output: "large output is deliberately not indexed".into(),
exit_code: Some(0),
status: ItemStatus::Completed,
},
),
completed(
"tool",
ItemContent::ToolCall {
name: "read_file".into(),
input: json!({"path": "src/auth.rs"}),
output: None,
status: ItemStatus::Completed,
},
),
]);
assert_eq!(entries[0].text, "rg auth.rs crates");
assert!(entries[1].text.contains("read_file"));
assert!(entries[1].text.contains("src/auth.rs"));
}

#[test]
fn query_matching_is_case_insensitive_and_generates_a_bounded_snippet() {
let text = format!("{} AUTH.rs {}", "before ".repeat(20), "after ".repeat(20));
let snippet = match_snippet(&text, "auth.RS", 60).expect("match");
assert!(snippet.contains("AUTH.rs"));
assert!(snippet.chars().count() <= 62); // up to two ellipses
assert!(match_snippet(&text, "missing", 60).is_none());
}

#[test]
fn searches_a_fixture_session_log_to_a_session_and_turn() {
let root = std::env::temp_dir().join(format!(
"tcode-session-search-test-{}",
uuid::Uuid::new_v4()
));
let store = SessionStore::open_at(root.clone()).expect("store");
let mut meta = SessionMeta::new(ProviderKind::Codex, PathBuf::from("/project"), None);
meta.title = "Authentication cleanup".into();
store
.append_event(
&meta.id,
1,
&AgentEvent::TurnStarted {
turn_id: "turn-1".into(),
},
)
.unwrap();
store
.append_event(
&meta.id,
2,
&completed(
"assistant",
ItemContent::AssistantMessage {
text: "I updated crates/runtime/src/auth.rs".into(),
},
)
.event,
)
.unwrap();

let hits = SessionSearch::new(store).search(&[meta.clone()], "auth.rs", 10);
assert_eq!(hits.len(), 1);
assert_eq!(hits[0].session_id, meta.id);
assert_eq!(hits[0].turn, 0);
assert!(hits[0].snippet.contains("auth.rs"));
let _ = fs::remove_dir_all(root);
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/services/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,7 @@ pub mod process;
pub mod provider_auth;
pub mod provider_probe;
pub mod relaunch;
pub mod session_search;
pub mod settings;
pub mod shell_env;
pub mod store;
Expand Down
380 changes: 380 additions & 0 deletions crates/services/src/session_search.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,380 @@
//! Lazy full-text search over persisted session event logs.
//!
//! The index is deliberately in-memory: each session is parsed only when its
//! JSONL file's length or modification time changes. This keeps the append-only
//! persistence format authoritative and avoids a second on-disk database.

use std::collections::{HashMap, HashSet};
use std::fs;
use std::time::SystemTime;

use agent::ItemContent;
use tcode_core::project::SessionMeta;
use tcode_core::session::{EntryContent, StoredEvent, Timeline};

use crate::store::SessionStore;

/// One final, folded timeline entry that contributes to content search.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SearchableEntry {
pub entry_id: String,
pub turn: usize,
pub text: String,
}

/// A content match suitable for presentation by a session picker.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionSearchHit {
pub session_id: String,
pub session_title: String,
pub entry_id: String,
pub turn: usize,
pub snippet: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct FileFingerprint {
len: u64,
modified: Option<SystemTime>,
}

#[derive(Debug, Clone)]
struct CachedSession {
fingerprint: FileFingerprint,
entries: Vec<SearchableEntry>,
}

/// Incremental, file-freshness-based content index for one [`SessionStore`].
pub struct SessionSearch {
store: SessionStore,
cache: HashMap<String, CachedSession>,
}

impl SessionSearch {
pub fn new(store: SessionStore) -> Self {
Self {
store,
cache: HashMap::new(),
}
}

/// Search sessions in the supplied order, returning at most `limit` hits.
/// Empty and whitespace-only queries intentionally return no content hits.
pub fn search(
&mut self,
sessions: &[SessionMeta],
query: &str,
limit: usize,
) -> Vec<SessionSearchHit> {
let query = query.trim();
if query.is_empty() || limit == 0 {
return Vec::new();
}

let live_ids: HashSet<&str> = sessions.iter().map(|meta| meta.id.as_str()).collect();
self.cache.retain(|id, _| live_ids.contains(id.as_str()));

let mut hits = Vec::new();
for meta in sessions {
self.refresh(meta);
let Some(cached) = self.cache.get(&meta.id) else {
continue;
};
for entry in &cached.entries {
let Some(snippet) = match_snippet(&entry.text, query, 140) else {
continue;
};
hits.push(SessionSearchHit {
session_id: meta.id.clone(),
session_title: meta.title.clone(),
entry_id: entry.entry_id.clone(),
turn: entry.turn,
snippet,
});
if hits.len() == limit {
return hits;
}
}
}
hits
}

fn refresh(&mut self, meta: &SessionMeta) {
let path = self.store.root().join(format!("{}.jsonl", meta.id));
let fingerprint = match fs::metadata(path) {
Ok(metadata) => FileFingerprint {
len: metadata.len(),
modified: metadata.modified().ok(),
},
Err(error) if error.kind() == std::io::ErrorKind::NotFound => FileFingerprint {
len: 0,
modified: None,
},
Err(error) => {
log::warn!("cannot inspect session log {}: {error}", meta.id);
return;
}
};
if self
.cache
.get(&meta.id)
.is_some_and(|cached| cached.fingerprint == fingerprint)
{
return;
}
let entries = extract_searchable_entries(&self.store.read_events(&meta.id));
self.cache.insert(
meta.id.clone(),
CachedSession {
fingerprint,
entries,
},
);
}
}

/// Fold persisted events and extract the final searchable representation.
///
/// Folding first deduplicates streaming deltas and item lifecycle updates, so
/// callers index what the chat ultimately displays rather than every wire event.
pub fn extract_searchable_entries(events: &[StoredEvent]) -> Vec<SearchableEntry> {
let timeline = Timeline::fold_events(events.iter().cloned());
let mut entries = Vec::new();
for entry in timeline
.entries
.iter()
.chain(timeline.children.values().flatten())
{
let text = match &entry.content {
EntryContent::Item(content) => searchable_item_text(content),
EntryContent::Steer {
text, attachments, ..
} => Some(join_parts(
std::iter::once(text.as_str()).chain(attachments.iter().map(String::as_str)),
)),
_ => None,
};
if let Some(text) = text.filter(|text| !text.trim().is_empty()) {
entries.push(SearchableEntry {
entry_id: entry.id.clone(),
turn: entry.turn,
text,
});
}
}
entries.sort_by_key(|entry| entry.turn);
entries
}

fn searchable_item_text(content: &ItemContent) -> Option<String> {
match content {
ItemContent::UserMessage {
text, attachments, ..
} => Some(join_parts(
std::iter::once(text.as_str()).chain(attachments.iter().map(String::as_str)),
)),
ItemContent::AssistantMessage { text } => Some(text.clone()),
ItemContent::CommandExecution { command, .. } => Some(command.clone()),
ItemContent::FileChange { changes, .. } => Some(join_parts(
changes.iter().map(|change| change.path.as_str()),
)),
ItemContent::ToolCall { name, input, .. } => {
Some(format!("{name} {}", compact_json(input)))
}
ItemContent::Subagent {
agent_type,
description,
summary,
..
} => Some(join_parts(
[agent_type.as_str(), description.as_str()]
.into_iter()
.chain(summary.iter().map(String::as_str)),
)),
ItemContent::WebSearch { query } => Some(query.clone()),
ItemContent::Other {
provider_kind,
summary,
} => Some(format!("{provider_kind} {summary}")),
ItemContent::Reasoning { .. } => None,
}
}

fn compact_json(value: &serde_json::Value) -> String {
serde_json::to_string(value).unwrap_or_default()
}

fn join_parts<'a>(parts: impl Iterator<Item = &'a str>) -> String {
parts
.filter(|part| !part.is_empty())
.collect::<Vec<_>>()
.join(" ")
}

/// Return a compact, whitespace-normalized snippet for a case-insensitive hit.
pub fn match_snippet(text: &str, query: &str, max_chars: usize) -> Option<String> {
let normalized = text.split_whitespace().collect::<Vec<_>>().join(" ");
let query = query.trim().to_lowercase();
if normalized.is_empty() || query.is_empty() {
return None;
}
let (match_start, match_end) = case_insensitive_range(&normalized, &query)?;
let chars: Vec<char> = normalized.chars().collect();
let start_char = normalized[..match_start].chars().count();
let end_char = normalized[..match_end].chars().count();
if chars.len() <= max_chars {
return Some(normalized);
}

let match_len = end_char.saturating_sub(start_char);
let context = max_chars.saturating_sub(match_len);
let mut start = start_char.saturating_sub(context / 2);
let end = (start + max_chars).min(chars.len());
start = end.saturating_sub(max_chars);
let mut snippet: String = chars[start..end].iter().collect();
if start > 0 {
snippet.insert(0, '…');
}
if end < chars.len() {
snippet.push('…');
}
Some(snippet)
}

fn case_insensitive_range(text: &str, lower_query: &str) -> Option<(usize, usize)> {
for (start, _) in text.char_indices() {
let suffix = &text[start..];
if !suffix.to_lowercase().starts_with(lower_query) {
continue;
}
let mut folded_len = 0;
let mut end = start;
for ch in suffix.chars() {
folded_len += ch.to_lowercase().map(char::len_utf8).sum::<usize>();
end += ch.len_utf8();
if folded_len >= lower_query.len() {
return Some((start, end));
}
}
}
None
}

#[cfg(test)]
mod tests {
use std::path::PathBuf;

use agent::{AgentEvent, ItemStatus, ProviderKind, ThreadItem};
use serde_json::json;
use tcode_core::project::SessionMeta;

use super::*;

fn completed(id: &str, content: ItemContent) -> StoredEvent {
AgentEvent::ItemCompleted(ThreadItem {
id: id.into(),
parent_item_id: None,
content,
})
.into()
}

#[test]
fn extracts_user_and_assistant_messages() {
let entries = extract_searchable_entries(&[
completed(
"user",
ItemContent::UserMessage {
text: "Where is auth.rs?".into(),
context_len: None,
attachments: Vec::new(),
},
),
completed(
"assistant",
ItemContent::AssistantMessage {
text: "It is under crates/runtime.".into(),
},
),
]);
assert_eq!(entries.len(), 2);
assert_eq!(entries[0].text, "Where is auth.rs?");
assert_eq!(entries[1].text, "It is under crates/runtime.");
}

#[test]
fn extracts_tool_titles_paths_and_commands() {
let entries = extract_searchable_entries(&[
completed(
"command",
ItemContent::CommandExecution {
command: "rg auth.rs crates".into(),
output: "large output is deliberately not indexed".into(),
exit_code: Some(0),
status: ItemStatus::Completed,
},
),
completed(
"tool",
ItemContent::ToolCall {
name: "read_file".into(),
input: json!({"path": "src/auth.rs"}),
output: None,
status: ItemStatus::Completed,
},
),
]);
assert_eq!(entries[0].text, "rg auth.rs crates");
assert!(entries[1].text.contains("read_file"));
assert!(entries[1].text.contains("src/auth.rs"));
}

#[test]
fn query_matching_is_case_insensitive_and_generates_a_bounded_snippet() {
let text = format!("{} AUTH.rs {}", "before ".repeat(20), "after ".repeat(20));
let snippet = match_snippet(&text, "auth.RS", 60).expect("match");
assert!(snippet.contains("AUTH.rs"));
assert!(snippet.chars().count() <= 62); // up to two ellipses
assert!(match_snippet(&text, "missing", 60).is_none());
}

#[test]
fn searches_a_fixture_session_log_to_a_session_and_turn() {
let root = std::env::temp_dir().join(format!(
"tcode-session-search-test-{}",
uuid::Uuid::new_v4()
));
let store = SessionStore::open_at(root.clone()).expect("store");
let mut meta = SessionMeta::new(ProviderKind::Codex, PathBuf::from("/project"), None);
meta.title = "Authentication cleanup".into();
store
.append_event(
&meta.id,
1,
&AgentEvent::TurnStarted {
turn_id: "turn-1".into(),
},
)
.unwrap();
store
.append_event(
&meta.id,
2,
&completed(
"assistant",
ItemContent::AssistantMessage {
text: "I updated crates/runtime/src/auth.rs".into(),
},
)
.event,
)
.unwrap();

let hits = SessionSearch::new(store).search(&[meta.clone()], "auth.rs", 10);
assert_eq!(hits.len(), 1);
assert_eq!(hits[0].session_id, meta.id);
assert_eq!(hits[0].turn, 0);
assert!(hits[0].snippet.contains("auth.rs"));
let _ = fs::remove_dir_all(root);
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/services/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,7 @@ pub mod process;
pub mod provider_auth;
pub mod provider_probe;
pub mod relaunch;
pub mod session_search;
pub mod settings;
pub mod shell_env;
pub mod store;
Expand Down
380 changes: 380 additions & 0 deletions crates/services/src/session_search.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,380 @@
//! Lazy full-text search over persisted session event logs.
//!
//! The index is deliberately in-memory: each session is parsed only when its
//! JSONL file's length or modification time changes. This keeps the append-only
//! persistence format authoritative and avoids a second on-disk database.

use std::collections::{HashMap, HashSet};
use std::fs;
use std::time::SystemTime;

use agent::ItemContent;
use tcode_core::project::SessionMeta;
use tcode_core::session::{EntryContent, StoredEvent, Timeline};

use crate::store::SessionStore;

/// One final, folded timeline entry that contributes to content search.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SearchableEntry {
pub entry_id: String,
pub turn: usize,
pub text: String,
}

/// A content match suitable for presentation by a session picker.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionSearchHit {
pub session_id: String,
pub session_title: String,
pub entry_id: String,
pub turn: usize,
pub snippet: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct FileFingerprint {
len: u64,
modified: Option<SystemTime>,
}

#[derive(Debug, Clone)]
struct CachedSession {
fingerprint: FileFingerprint,
entries: Vec<SearchableEntry>,
}

/// Incremental, file-freshness-based content index for one [`SessionStore`].
pub struct SessionSearch {
store: SessionStore,
cache: HashMap<String, CachedSession>,
}

impl SessionSearch {
pub fn new(store: SessionStore) -> Self {
Self {
store,
cache: HashMap::new(),
}
}

/// Search sessions in the supplied order, returning at most `limit` hits.
/// Empty and whitespace-only queries intentionally return no content hits.
pub fn search(
&mut self,
sessions: &[SessionMeta],
query: &str,
limit: usize,
) -> Vec<SessionSearchHit> {
let query = query.trim();
if query.is_empty() || limit == 0 {
return Vec::new();
}

let live_ids: HashSet<&str> = sessions.iter().map(|meta| meta.id.as_str()).collect();
self.cache.retain(|id, _| live_ids.contains(id.as_str()));

let mut hits = Vec::new();
for meta in sessions {
self.refresh(meta);
let Some(cached) = self.cache.get(&meta.id) else {
continue;
};
for entry in &cached.entries {
let Some(snippet) = match_snippet(&entry.text, query, 140) else {
continue;
};
hits.push(SessionSearchHit {
session_id: meta.id.clone(),
session_title: meta.title.clone(),
entry_id: entry.entry_id.clone(),
turn: entry.turn,
snippet,
});
if hits.len() == limit {
return hits;
}
}
}
hits
}

fn refresh(&mut self, meta: &SessionMeta) {
let path = self.store.root().join(format!("{}.jsonl", meta.id));
let fingerprint = match fs::metadata(path) {
Ok(metadata) => FileFingerprint {
len: metadata.len(),
modified: metadata.modified().ok(),
},
Err(error) if error.kind() == std::io::ErrorKind::NotFound => FileFingerprint {
len: 0,
modified: None,
},
Err(error) => {
log::warn!("cannot inspect session log {}: {error}", meta.id);
return;
}
};
if self
.cache
.get(&meta.id)
.is_some_and(|cached| cached.fingerprint == fingerprint)
{
return;
}
let entries = extract_searchable_entries(&self.store.read_events(&meta.id));
self.cache.insert(
meta.id.clone(),
CachedSession {
fingerprint,
entries,
},
);
}
}

/// Fold persisted events and extract the final searchable representation.
///
/// Folding first deduplicates streaming deltas and item lifecycle updates, so
/// callers index what the chat ultimately displays rather than every wire event.
pub fn extract_searchable_entries(events: &[StoredEvent]) -> Vec<SearchableEntry> {
let timeline = Timeline::fold_events(events.iter().cloned());
let mut entries = Vec::new();
for entry in timeline
.entries
.iter()
.chain(timeline.children.values().flatten())
{
let text = match &entry.content {
EntryContent::Item(content) => searchable_item_text(content),
EntryContent::Steer {
text, attachments, ..
} => Some(join_parts(
std::iter::once(text.as_str()).chain(attachments.iter().map(String::as_str)),
)),
_ => None,
};
if let Some(text) = text.filter(|text| !text.trim().is_empty()) {
entries.push(SearchableEntry {
entry_id: entry.id.clone(),
turn: entry.turn,
text,
});
}
}
entries.sort_by_key(|entry| entry.turn);
entries
}

fn searchable_item_text(content: &ItemContent) -> Option<String> {
match content {
ItemContent::UserMessage {
text, attachments, ..
} => Some(join_parts(
std::iter::once(text.as_str()).chain(attachments.iter().map(String::as_str)),
)),
ItemContent::AssistantMessage { text } => Some(text.clone()),
ItemContent::CommandExecution { command, .. } => Some(command.clone()),
ItemContent::FileChange { changes, .. } => Some(join_parts(
changes.iter().map(|change| change.path.as_str()),
)),
ItemContent::ToolCall { name, input, .. } => {
Some(format!("{name} {}", compact_json(input)))
}
ItemContent::Subagent {
agent_type,
description,
summary,
..
} => Some(join_parts(
[agent_type.as_str(), description.as_str()]
.into_iter()
.chain(summary.iter().map(String::as_str)),
)),
ItemContent::WebSearch { query } => Some(query.clone()),
ItemContent::Other {
provider_kind,
summary,
} => Some(format!("{provider_kind} {summary}")),
ItemContent::Reasoning { .. } => None,
}
}

fn compact_json(value: &serde_json::Value) -> String {
serde_json::to_string(value).unwrap_or_default()
}

fn join_parts<'a>(parts: impl Iterator<Item = &'a str>) -> String {
parts
.filter(|part| !part.is_empty())
.collect::<Vec<_>>()
.join(" ")
}

/// Return a compact, whitespace-normalized snippet for a case-insensitive hit.
pub fn match_snippet(text: &str, query: &str, max_chars: usize) -> Option<String> {
let normalized = text.split_whitespace().collect::<Vec<_>>().join(" ");
let query = query.trim().to_lowercase();
if normalized.is_empty() || query.is_empty() {
return None;
}
let (match_start, match_end) = case_insensitive_range(&normalized, &query)?;
let chars: Vec<char> = normalized.chars().collect();
let start_char = normalized[..match_start].chars().count();
let end_char = normalized[..match_end].chars().count();
if chars.len() <= max_chars {
return Some(normalized);
}

let match_len = end_char.saturating_sub(start_char);
let context = max_chars.saturating_sub(match_len);
let mut start = start_char.saturating_sub(context / 2);
let end = (start + max_chars).min(chars.len());
start = end.saturating_sub(max_chars);
let mut snippet: String = chars[start..end].iter().collect();
if start > 0 {
snippet.insert(0, '…');
}
if end < chars.len() {
snippet.push('…');
}
Some(snippet)
}

fn case_insensitive_range(text: &str, lower_query: &str) -> Option<(usize, usize)> {
for (start, _) in text.char_indices() {
let suffix = &text[start..];
if !suffix.to_lowercase().starts_with(lower_query) {
continue;
}
let mut folded_len = 0;
let mut end = start;
for ch in suffix.chars() {
folded_len += ch.to_lowercase().map(char::len_utf8).sum::<usize>();
end += ch.len_utf8();
if folded_len >= lower_query.len() {
return Some((start, end));
}
}
}
None
}

#[cfg(test)]
mod tests {
use std::path::PathBuf;

use agent::{AgentEvent, ItemStatus, ProviderKind, ThreadItem};
use serde_json::json;
use tcode_core::project::SessionMeta;

use super::*;

fn completed(id: &str, content: ItemContent) -> StoredEvent {
AgentEvent::ItemCompleted(ThreadItem {
id: id.into(),
parent_item_id: None,
content,
})
.into()
}

#[test]
fn extracts_user_and_assistant_messages() {
let entries = extract_searchable_entries(&[
completed(
"user",
ItemContent::UserMessage {
text: "Where is auth.rs?".into(),
context_len: None,
attachments: Vec::new(),
},
),
completed(
"assistant",
ItemContent::AssistantMessage {
text: "It is under crates/runtime.".into(),
},
),
]);
assert_eq!(entries.len(), 2);
assert_eq!(entries[0].text, "Where is auth.rs?");
assert_eq!(entries[1].text, "It is under crates/runtime.");
}

#[test]
fn extracts_tool_titles_paths_and_commands() {
let entries = extract_searchable_entries(&[
completed(
"command",
ItemContent::CommandExecution {
command: "rg auth.rs crates".into(),
output: "large output is deliberately not indexed".into(),
exit_code: Some(0),
status: ItemStatus::Completed,
},
),
completed(
"tool",
ItemContent::ToolCall {
name: "read_file".into(),
input: json!({"path": "src/auth.rs"}),
output: None,
status: ItemStatus::Completed,
},
),
]);
assert_eq!(entries[0].text, "rg auth.rs crates");
assert!(entries[1].text.contains("read_file"));
assert!(entries[1].text.contains("src/auth.rs"));
}

#[test]
fn query_matching_is_case_insensitive_and_generates_a_bounded_snippet() {
let text = format!("{} AUTH.rs {}", "before ".repeat(20), "after ".repeat(20));
let snippet = match_snippet(&text, "auth.RS", 60).expect("match");
assert!(snippet.contains("AUTH.rs"));
assert!(snippet.chars().count() <= 62); // up to two ellipses
assert!(match_snippet(&text, "missing", 60).is_none());
}

#[test]
fn searches_a_fixture_session_log_to_a_session_and_turn() {
let root = std::env::temp_dir().join(format!(
"tcode-session-search-test-{}",
uuid::Uuid::new_v4()
));
let store = SessionStore::open_at(root.clone()).expect("store");
let mut meta = SessionMeta::new(ProviderKind::Codex, PathBuf::from("/project"), None);
meta.title = "Authentication cleanup".into();
store
.append_event(
&meta.id,
1,
&AgentEvent::TurnStarted {
turn_id: "turn-1".into(),
},
)
.unwrap();
store
.append_event(
&meta.id,
2,
&completed(
"assistant",
ItemContent::AssistantMessage {
text: "I updated crates/runtime/src/auth.rs".into(),
},
)
.event,
)
.unwrap();

let hits = SessionSearch::new(store).search(&[meta.clone()], "auth.rs", 10);
assert_eq!(hits.len(), 1);
assert_eq!(hits[0].session_id, meta.id);
assert_eq!(hits[0].turn, 0);
assert!(hits[0].snippet.contains("auth.rs"));
let _ = fs::remove_dir_all(root);
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/services/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,7 @@ pub mod process;
pub mod provider_auth;
pub mod provider_probe;
pub mod relaunch;
pub mod session_search;
pub mod settings;
pub mod shell_env;
pub mod store;
Expand Down
380 changes: 380 additions & 0 deletions crates/services/src/session_search.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,380 @@
//! Lazy full-text search over persisted session event logs.
//!
//! The index is deliberately in-memory: each session is parsed only when its
//! JSONL file's length or modification time changes. This keeps the append-only
//! persistence format authoritative and avoids a second on-disk database.

use std::collections::{HashMap, HashSet};
use std::fs;
use std::time::SystemTime;

use agent::ItemContent;
use tcode_core::project::SessionMeta;
use tcode_core::session::{EntryContent, StoredEvent, Timeline};

use crate::store::SessionStore;

/// One final, folded timeline entry that contributes to content search.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SearchableEntry {
pub entry_id: String,
pub turn: usize,
pub text: String,
}

/// A content match suitable for presentation by a session picker.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionSearchHit {
pub session_id: String,
pub session_title: String,
pub entry_id: String,
pub turn: usize,
pub snippet: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct FileFingerprint {
len: u64,
modified: Option<SystemTime>,
}

#[derive(Debug, Clone)]
struct CachedSession {
fingerprint: FileFingerprint,
entries: Vec<SearchableEntry>,
}

/// Incremental, file-freshness-based content index for one [`SessionStore`].
pub struct SessionSearch {
store: SessionStore,
cache: HashMap<String, CachedSession>,
}

impl SessionSearch {
pub fn new(store: SessionStore) -> Self {
Self {
store,
cache: HashMap::new(),
}
}

/// Search sessions in the supplied order, returning at most `limit` hits.
/// Empty and whitespace-only queries intentionally return no content hits.
pub fn search(
&mut self,
sessions: &[SessionMeta],
query: &str,
limit: usize,
) -> Vec<SessionSearchHit> {
let query = query.trim();
if query.is_empty() || limit == 0 {
return Vec::new();
}

let live_ids: HashSet<&str> = sessions.iter().map(|meta| meta.id.as_str()).collect();
self.cache.retain(|id, _| live_ids.contains(id.as_str()));

let mut hits = Vec::new();
for meta in sessions {
self.refresh(meta);
let Some(cached) = self.cache.get(&meta.id) else {
continue;
};
for entry in &cached.entries {
let Some(snippet) = match_snippet(&entry.text, query, 140) else {
continue;
};
hits.push(SessionSearchHit {
session_id: meta.id.clone(),
session_title: meta.title.clone(),
entry_id: entry.entry_id.clone(),
turn: entry.turn,
snippet,
});
if hits.len() == limit {
return hits;
}
}
}
hits
}

fn refresh(&mut self, meta: &SessionMeta) {
let path = self.store.root().join(format!("{}.jsonl", meta.id));
let fingerprint = match fs::metadata(path) {
Ok(metadata) => FileFingerprint {
len: metadata.len(),
modified: metadata.modified().ok(),
},
Err(error) if error.kind() == std::io::ErrorKind::NotFound => FileFingerprint {
len: 0,
modified: None,
},
Err(error) => {
log::warn!("cannot inspect session log {}: {error}", meta.id);
return;
}
};
if self
.cache
.get(&meta.id)
.is_some_and(|cached| cached.fingerprint == fingerprint)
{
return;
}
let entries = extract_searchable_entries(&self.store.read_events(&meta.id));
self.cache.insert(
meta.id.clone(),
CachedSession {
fingerprint,
entries,
},
);
}
}

/// Fold persisted events and extract the final searchable representation.
///
/// Folding first deduplicates streaming deltas and item lifecycle updates, so
/// callers index what the chat ultimately displays rather than every wire event.
pub fn extract_searchable_entries(events: &[StoredEvent]) -> Vec<SearchableEntry> {
let timeline = Timeline::fold_events(events.iter().cloned());
let mut entries = Vec::new();
for entry in timeline
.entries
.iter()
.chain(timeline.children.values().flatten())
{
let text = match &entry.content {
EntryContent::Item(content) => searchable_item_text(content),
EntryContent::Steer {
text, attachments, ..
} => Some(join_parts(
std::iter::once(text.as_str()).chain(attachments.iter().map(String::as_str)),
)),
_ => None,
};
if let Some(text) = text.filter(|text| !text.trim().is_empty()) {
entries.push(SearchableEntry {
entry_id: entry.id.clone(),
turn: entry.turn,
text,
});
}
}
entries.sort_by_key(|entry| entry.turn);
entries
}

fn searchable_item_text(content: &ItemContent) -> Option<String> {
match content {
ItemContent::UserMessage {
text, attachments, ..
} => Some(join_parts(
std::iter::once(text.as_str()).chain(attachments.iter().map(String::as_str)),
)),
ItemContent::AssistantMessage { text } => Some(text.clone()),
ItemContent::CommandExecution { command, .. } => Some(command.clone()),
ItemContent::FileChange { changes, .. } => Some(join_parts(
changes.iter().map(|change| change.path.as_str()),
)),
ItemContent::ToolCall { name, input, .. } => {
Some(format!("{name} {}", compact_json(input)))
}
ItemContent::Subagent {
agent_type,
description,
summary,
..
} => Some(join_parts(
[agent_type.as_str(), description.as_str()]
.into_iter()
.chain(summary.iter().map(String::as_str)),
)),
ItemContent::WebSearch { query } => Some(query.clone()),
ItemContent::Other {
provider_kind,
summary,
} => Some(format!("{provider_kind} {summary}")),
ItemContent::Reasoning { .. } => None,
}
}

fn compact_json(value: &serde_json::Value) -> String {
serde_json::to_string(value).unwrap_or_default()
}

fn join_parts<'a>(parts: impl Iterator<Item = &'a str>) -> String {
parts
.filter(|part| !part.is_empty())
.collect::<Vec<_>>()
.join(" ")
}

/// Return a compact, whitespace-normalized snippet for a case-insensitive hit.
pub fn match_snippet(text: &str, query: &str, max_chars: usize) -> Option<String> {
let normalized = text.split_whitespace().collect::<Vec<_>>().join(" ");
let query = query.trim().to_lowercase();
if normalized.is_empty() || query.is_empty() {
return None;
}
let (match_start, match_end) = case_insensitive_range(&normalized, &query)?;
let chars: Vec<char> = normalized.chars().collect();
let start_char = normalized[..match_start].chars().count();
let end_char = normalized[..match_end].chars().count();
if chars.len() <= max_chars {
return Some(normalized);
}

let match_len = end_char.saturating_sub(start_char);
let context = max_chars.saturating_sub(match_len);
let mut start = start_char.saturating_sub(context / 2);
let end = (start + max_chars).min(chars.len());
start = end.saturating_sub(max_chars);
let mut snippet: String = chars[start..end].iter().collect();
if start > 0 {
snippet.insert(0, '…');
}
if end < chars.len() {
snippet.push('…');
}
Some(snippet)
}

fn case_insensitive_range(text: &str, lower_query: &str) -> Option<(usize, usize)> {
for (start, _) in text.char_indices() {
let suffix = &text[start..];
if !suffix.to_lowercase().starts_with(lower_query) {
continue;
}
let mut folded_len = 0;
let mut end = start;
for ch in suffix.chars() {
folded_len += ch.to_lowercase().map(char::len_utf8).sum::<usize>();
end += ch.len_utf8();
if folded_len >= lower_query.len() {
return Some((start, end));
}
}
}
None
}

#[cfg(test)]
mod tests {
use std::path::PathBuf;

use agent::{AgentEvent, ItemStatus, ProviderKind, ThreadItem};
use serde_json::json;
use tcode_core::project::SessionMeta;

use super::*;

fn completed(id: &str, content: ItemContent) -> StoredEvent {
AgentEvent::ItemCompleted(ThreadItem {
id: id.into(),
parent_item_id: None,
content,
})
.into()
}

#[test]
fn extracts_user_and_assistant_messages() {
let entries = extract_searchable_entries(&[
completed(
"user",
ItemContent::UserMessage {
text: "Where is auth.rs?".into(),
context_len: None,
attachments: Vec::new(),
},
),
completed(
"assistant",
ItemContent::AssistantMessage {
text: "It is under crates/runtime.".into(),
},
),
]);
assert_eq!(entries.len(), 2);
assert_eq!(entries[0].text, "Where is auth.rs?");
assert_eq!(entries[1].text, "It is under crates/runtime.");
}

#[test]
fn extracts_tool_titles_paths_and_commands() {
let entries = extract_searchable_entries(&[
completed(
"command",
ItemContent::CommandExecution {
command: "rg auth.rs crates".into(),
output: "large output is deliberately not indexed".into(),
exit_code: Some(0),
status: ItemStatus::Completed,
},
),
completed(
"tool",
ItemContent::ToolCall {
name: "read_file".into(),
input: json!({"path": "src/auth.rs"}),
output: None,
status: ItemStatus::Completed,
},
),
]);
assert_eq!(entries[0].text, "rg auth.rs crates");
assert!(entries[1].text.contains("read_file"));
assert!(entries[1].text.contains("src/auth.rs"));
}

#[test]
fn query_matching_is_case_insensitive_and_generates_a_bounded_snippet() {
let text = format!("{} AUTH.rs {}", "before ".repeat(20), "after ".repeat(20));
let snippet = match_snippet(&text, "auth.RS", 60).expect("match");
assert!(snippet.contains("AUTH.rs"));
assert!(snippet.chars().count() <= 62); // up to two ellipses
assert!(match_snippet(&text, "missing", 60).is_none());
}

#[test]
fn searches_a_fixture_session_log_to_a_session_and_turn() {
let root = std::env::temp_dir().join(format!(
"tcode-session-search-test-{}",
uuid::Uuid::new_v4()
));
let store = SessionStore::open_at(root.clone()).expect("store");
let mut meta = SessionMeta::new(ProviderKind::Codex, PathBuf::from("/project"), None);
meta.title = "Authentication cleanup".into();
store
.append_event(
&meta.id,
1,
&AgentEvent::TurnStarted {
turn_id: "turn-1".into(),
},
)
.unwrap();
store
.append_event(
&meta.id,
2,
&completed(
"assistant",
ItemContent::AssistantMessage {
text: "I updated crates/runtime/src/auth.rs".into(),
},
)
.event,
)
.unwrap();

let hits = SessionSearch::new(store).search(&[meta.clone()], "auth.rs", 10);
assert_eq!(hits.len(), 1);
assert_eq!(hits[0].session_id, meta.id);
assert_eq!(hits[0].turn, 0);
assert!(hits[0].snippet.contains("auth.rs"));
let _ = fs::remove_dir_all(root);
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/services/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,7 @@ pub mod process;
pub mod provider_auth;
pub mod provider_probe;
pub mod relaunch;
pub mod session_search;
pub mod settings;
pub mod shell_env;
pub mod store;
Expand Down
380 changes: 380 additions & 0 deletions crates/services/src/session_search.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,380 @@
//! Lazy full-text search over persisted session event logs.
//!
//! The index is deliberately in-memory: each session is parsed only when its
//! JSONL file's length or modification time changes. This keeps the append-only
//! persistence format authoritative and avoids a second on-disk database.

use std::collections::{HashMap, HashSet};
use std::fs;
use std::time::SystemTime;

use agent::ItemContent;
use tcode_core::project::SessionMeta;
use tcode_core::session::{EntryContent, StoredEvent, Timeline};

use crate::store::SessionStore;

/// One final, folded timeline entry that contributes to content search.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SearchableEntry {
pub entry_id: String,
pub turn: usize,
pub text: String,
}

/// A content match suitable for presentation by a session picker.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionSearchHit {
pub session_id: String,
pub session_title: String,
pub entry_id: String,
pub turn: usize,
pub snippet: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct FileFingerprint {
len: u64,
modified: Option<SystemTime>,
}

#[derive(Debug, Clone)]
struct CachedSession {
fingerprint: FileFingerprint,
entries: Vec<SearchableEntry>,
}

/// Incremental, file-freshness-based content index for one [`SessionStore`].
pub struct SessionSearch {
store: SessionStore,
cache: HashMap<String, CachedSession>,
}

impl SessionSearch {
pub fn new(store: SessionStore) -> Self {
Self {
store,
cache: HashMap::new(),
}
}

/// Search sessions in the supplied order, returning at most `limit` hits.
/// Empty and whitespace-only queries intentionally return no content hits.
pub fn search(
&mut self,
sessions: &[SessionMeta],
query: &str,
limit: usize,
) -> Vec<SessionSearchHit> {
let query = query.trim();
if query.is_empty() || limit == 0 {
return Vec::new();
}

let live_ids: HashSet<&str> = sessions.iter().map(|meta| meta.id.as_str()).collect();
self.cache.retain(|id, _| live_ids.contains(id.as_str()));

let mut hits = Vec::new();
for meta in sessions {
self.refresh(meta);
let Some(cached) = self.cache.get(&meta.id) else {
continue;
};
for entry in &cached.entries {
let Some(snippet) = match_snippet(&entry.text, query, 140) else {
continue;
};
hits.push(SessionSearchHit {
session_id: meta.id.clone(),
session_title: meta.title.clone(),
entry_id: entry.entry_id.clone(),
turn: entry.turn,
snippet,
});
if hits.len() == limit {
return hits;
}
}
}
hits
}

fn refresh(&mut self, meta: &SessionMeta) {
let path = self.store.root().join(format!("{}.jsonl", meta.id));
let fingerprint = match fs::metadata(path) {
Ok(metadata) => FileFingerprint {
len: metadata.len(),
modified: metadata.modified().ok(),
},
Err(error) if error.kind() == std::io::ErrorKind::NotFound => FileFingerprint {
len: 0,
modified: None,
},
Err(error) => {
log::warn!("cannot inspect session log {}: {error}", meta.id);
return;
}
};
if self
.cache
.get(&meta.id)
.is_some_and(|cached| cached.fingerprint == fingerprint)
{
return;
}
let entries = extract_searchable_entries(&self.store.read_events(&meta.id));
self.cache.insert(
meta.id.clone(),
CachedSession {
fingerprint,
entries,
},
);
}
}

/// Fold persisted events and extract the final searchable representation.
///
/// Folding first deduplicates streaming deltas and item lifecycle updates, so
/// callers index what the chat ultimately displays rather than every wire event.
pub fn extract_searchable_entries(events: &[StoredEvent]) -> Vec<SearchableEntry> {
let timeline = Timeline::fold_events(events.iter().cloned());
let mut entries = Vec::new();
for entry in timeline
.entries
.iter()
.chain(timeline.children.values().flatten())
{
let text = match &entry.content {
EntryContent::Item(content) => searchable_item_text(content),
EntryContent::Steer {
text, attachments, ..
} => Some(join_parts(
std::iter::once(text.as_str()).chain(attachments.iter().map(String::as_str)),
)),
_ => None,
};
if let Some(text) = text.filter(|text| !text.trim().is_empty()) {
entries.push(SearchableEntry {
entry_id: entry.id.clone(),
turn: entry.turn,
text,
});
}
}
entries.sort_by_key(|entry| entry.turn);
entries
}

fn searchable_item_text(content: &ItemContent) -> Option<String> {
match content {
ItemContent::UserMessage {
text, attachments, ..
} => Some(join_parts(
std::iter::once(text.as_str()).chain(attachments.iter().map(String::as_str)),
)),
ItemContent::AssistantMessage { text } => Some(text.clone()),
ItemContent::CommandExecution { command, .. } => Some(command.clone()),
ItemContent::FileChange { changes, .. } => Some(join_parts(
changes.iter().map(|change| change.path.as_str()),
)),
ItemContent::ToolCall { name, input, .. } => {
Some(format!("{name} {}", compact_json(input)))
}
ItemContent::Subagent {
agent_type,
description,
summary,
..
} => Some(join_parts(
[agent_type.as_str(), description.as_str()]
.into_iter()
.chain(summary.iter().map(String::as_str)),
)),
ItemContent::WebSearch { query } => Some(query.clone()),
ItemContent::Other {
provider_kind,
summary,
} => Some(format!("{provider_kind} {summary}")),
ItemContent::Reasoning { .. } => None,
}
}

fn compact_json(value: &serde_json::Value) -> String {
serde_json::to_string(value).unwrap_or_default()
}

fn join_parts<'a>(parts: impl Iterator<Item = &'a str>) -> String {
parts
.filter(|part| !part.is_empty())
.collect::<Vec<_>>()
.join(" ")
}

/// Return a compact, whitespace-normalized snippet for a case-insensitive hit.
pub fn match_snippet(text: &str, query: &str, max_chars: usize) -> Option<String> {
let normalized = text.split_whitespace().collect::<Vec<_>>().join(" ");
let query = query.trim().to_lowercase();
if normalized.is_empty() || query.is_empty() {
return None;
}
let (match_start, match_end) = case_insensitive_range(&normalized, &query)?;
let chars: Vec<char> = normalized.chars().collect();
let start_char = normalized[..match_start].chars().count();
let end_char = normalized[..match_end].chars().count();
if chars.len() <= max_chars {
return Some(normalized);
}

let match_len = end_char.saturating_sub(start_char);
let context = max_chars.saturating_sub(match_len);
let mut start = start_char.saturating_sub(context / 2);
let end = (start + max_chars).min(chars.len());
start = end.saturating_sub(max_chars);
let mut snippet: String = chars[start..end].iter().collect();
if start > 0 {
snippet.insert(0, '…');
}
if end < chars.len() {
snippet.push('…');
}
Some(snippet)
}

fn case_insensitive_range(text: &str, lower_query: &str) -> Option<(usize, usize)> {
for (start, _) in text.char_indices() {
let suffix = &text[start..];
if !suffix.to_lowercase().starts_with(lower_query) {
continue;
}
let mut folded_len = 0;
let mut end = start;
for ch in suffix.chars() {
folded_len += ch.to_lowercase().map(char::len_utf8).sum::<usize>();
end += ch.len_utf8();
if folded_len >= lower_query.len() {
return Some((start, end));
}
}
}
None
}

#[cfg(test)]
mod tests {
use std::path::PathBuf;

use agent::{AgentEvent, ItemStatus, ProviderKind, ThreadItem};
use serde_json::json;
use tcode_core::project::SessionMeta;

use super::*;

fn completed(id: &str, content: ItemContent) -> StoredEvent {
AgentEvent::ItemCompleted(ThreadItem {
id: id.into(),
parent_item_id: None,
content,
})
.into()
}

#[test]
fn extracts_user_and_assistant_messages() {
let entries = extract_searchable_entries(&[
completed(
"user",
ItemContent::UserMessage {
text: "Where is auth.rs?".into(),
context_len: None,
attachments: Vec::new(),
},
),
completed(
"assistant",
ItemContent::AssistantMessage {
text: "It is under crates/runtime.".into(),
},
),
]);
assert_eq!(entries.len(), 2);
assert_eq!(entries[0].text, "Where is auth.rs?");
assert_eq!(entries[1].text, "It is under crates/runtime.");
}

#[test]
fn extracts_tool_titles_paths_and_commands() {
let entries = extract_searchable_entries(&[
completed(
"command",
ItemContent::CommandExecution {
command: "rg auth.rs crates".into(),
output: "large output is deliberately not indexed".into(),
exit_code: Some(0),
status: ItemStatus::Completed,
},
),
completed(
"tool",
ItemContent::ToolCall {
name: "read_file".into(),
input: json!({"path": "src/auth.rs"}),
output: None,
status: ItemStatus::Completed,
},
),
]);
assert_eq!(entries[0].text, "rg auth.rs crates");
assert!(entries[1].text.contains("read_file"));
assert!(entries[1].text.contains("src/auth.rs"));
}

#[test]
fn query_matching_is_case_insensitive_and_generates_a_bounded_snippet() {
let text = format!("{} AUTH.rs {}", "before ".repeat(20), "after ".repeat(20));
let snippet = match_snippet(&text, "auth.RS", 60).expect("match");
assert!(snippet.contains("AUTH.rs"));
assert!(snippet.chars().count() <= 62); // up to two ellipses
assert!(match_snippet(&text, "missing", 60).is_none());
}

#[test]
fn searches_a_fixture_session_log_to_a_session_and_turn() {
let root = std::env::temp_dir().join(format!(
"tcode-session-search-test-{}",
uuid::Uuid::new_v4()
));
let store = SessionStore::open_at(root.clone()).expect("store");
let mut meta = SessionMeta::new(ProviderKind::Codex, PathBuf::from("/project"), None);
meta.title = "Authentication cleanup".into();
store
.append_event(
&meta.id,
1,
&AgentEvent::TurnStarted {
turn_id: "turn-1".into(),
},
)
.unwrap();
store
.append_event(
&meta.id,
2,
&completed(
"assistant",
ItemContent::AssistantMessage {
text: "I updated crates/runtime/src/auth.rs".into(),
},
)
.event,
)
.unwrap();

let hits = SessionSearch::new(store).search(&[meta.clone()], "auth.rs", 10);
assert_eq!(hits.len(), 1);
assert_eq!(hits[0].session_id, meta.id);
assert_eq!(hits[0].turn, 0);
assert!(hits[0].snippet.contains("auth.rs"));
let _ = fs::remove_dir_all(root);
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/services/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,7 @@ pub mod process;
pub mod provider_auth;
pub mod provider_probe;
pub mod relaunch;
pub mod session_search;
pub mod settings;
pub mod shell_env;
pub mod store;
Expand Down
380 changes: 380 additions & 0 deletions crates/services/src/session_search.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,380 @@
//! Lazy full-text search over persisted session event logs.
//!
//! The index is deliberately in-memory: each session is parsed only when its
//! JSONL file's length or modification time changes. This keeps the append-only
//! persistence format authoritative and avoids a second on-disk database.

use std::collections::{HashMap, HashSet};
use std::fs;
use std::time::SystemTime;

use agent::ItemContent;
use tcode_core::project::SessionMeta;
use tcode_core::session::{EntryContent, StoredEvent, Timeline};

use crate::store::SessionStore;

/// One final, folded timeline entry that contributes to content search.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SearchableEntry {
pub entry_id: String,
pub turn: usize,
pub text: String,
}

/// A content match suitable for presentation by a session picker.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionSearchHit {
pub session_id: String,
pub session_title: String,
pub entry_id: String,
pub turn: usize,
pub snippet: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct FileFingerprint {
len: u64,
modified: Option<SystemTime>,
}

#[derive(Debug, Clone)]
struct CachedSession {
fingerprint: FileFingerprint,
entries: Vec<SearchableEntry>,
}

/// Incremental, file-freshness-based content index for one [`SessionStore`].
pub struct SessionSearch {
store: SessionStore,
cache: HashMap<String, CachedSession>,
}

impl SessionSearch {
pub fn new(store: SessionStore) -> Self {
Self {
store,
cache: HashMap::new(),
}
}

/// Search sessions in the supplied order, returning at most `limit` hits.
/// Empty and whitespace-only queries intentionally return no content hits.
pub fn search(
&mut self,
sessions: &[SessionMeta],
query: &str,
limit: usize,
) -> Vec<SessionSearchHit> {
let query = query.trim();
if query.is_empty() || limit == 0 {
return Vec::new();
}

let live_ids: HashSet<&str> = sessions.iter().map(|meta| meta.id.as_str()).collect();
self.cache.retain(|id, _| live_ids.contains(id.as_str()));

let mut hits = Vec::new();
for meta in sessions {
self.refresh(meta);
let Some(cached) = self.cache.get(&meta.id) else {
continue;
};
for entry in &cached.entries {
let Some(snippet) = match_snippet(&entry.text, query, 140) else {
continue;
};
hits.push(SessionSearchHit {
session_id: meta.id.clone(),
session_title: meta.title.clone(),
entry_id: entry.entry_id.clone(),
turn: entry.turn,
snippet,
});
if hits.len() == limit {
return hits;
}
}
}
hits
}

fn refresh(&mut self, meta: &SessionMeta) {
let path = self.store.root().join(format!("{}.jsonl", meta.id));
let fingerprint = match fs::metadata(path) {
Ok(metadata) => FileFingerprint {
len: metadata.len(),
modified: metadata.modified().ok(),
},
Err(error) if error.kind() == std::io::ErrorKind::NotFound => FileFingerprint {
len: 0,
modified: None,
},
Err(error) => {
log::warn!("cannot inspect session log {}: {error}", meta.id);
return;
}
};
if self
.cache
.get(&meta.id)
.is_some_and(|cached| cached.fingerprint == fingerprint)
{
return;
}
let entries = extract_searchable_entries(&self.store.read_events(&meta.id));
self.cache.insert(
meta.id.clone(),
CachedSession {
fingerprint,
entries,
},
);
}
}

/// Fold persisted events and extract the final searchable representation.
///
/// Folding first deduplicates streaming deltas and item lifecycle updates, so
/// callers index what the chat ultimately displays rather than every wire event.
pub fn extract_searchable_entries(events: &[StoredEvent]) -> Vec<SearchableEntry> {
let timeline = Timeline::fold_events(events.iter().cloned());
let mut entries = Vec::new();
for entry in timeline
.entries
.iter()
.chain(timeline.children.values().flatten())
{
let text = match &entry.content {
EntryContent::Item(content) => searchable_item_text(content),
EntryContent::Steer {
text, attachments, ..
} => Some(join_parts(
std::iter::once(text.as_str()).chain(attachments.iter().map(String::as_str)),
)),
_ => None,
};
if let Some(text) = text.filter(|text| !text.trim().is_empty()) {
entries.push(SearchableEntry {
entry_id: entry.id.clone(),
turn: entry.turn,
text,
});
}
}
entries.sort_by_key(|entry| entry.turn);
entries
}

fn searchable_item_text(content: &ItemContent) -> Option<String> {
match content {
ItemContent::UserMessage {
text, attachments, ..
} => Some(join_parts(
std::iter::once(text.as_str()).chain(attachments.iter().map(String::as_str)),
)),
ItemContent::AssistantMessage { text } => Some(text.clone()),
ItemContent::CommandExecution { command, .. } => Some(command.clone()),
ItemContent::FileChange { changes, .. } => Some(join_parts(
changes.iter().map(|change| change.path.as_str()),
)),
ItemContent::ToolCall { name, input, .. } => {
Some(format!("{name} {}", compact_json(input)))
}
ItemContent::Subagent {
agent_type,
description,
summary,
..
} => Some(join_parts(
[agent_type.as_str(), description.as_str()]
.into_iter()
.chain(summary.iter().map(String::as_str)),
)),
ItemContent::WebSearch { query } => Some(query.clone()),
ItemContent::Other {
provider_kind,
summary,
} => Some(format!("{provider_kind} {summary}")),
ItemContent::Reasoning { .. } => None,
}
}

fn compact_json(value: &serde_json::Value) -> String {
serde_json::to_string(value).unwrap_or_default()
}

fn join_parts<'a>(parts: impl Iterator<Item = &'a str>) -> String {
parts
.filter(|part| !part.is_empty())
.collect::<Vec<_>>()
.join(" ")
}

/// Return a compact, whitespace-normalized snippet for a case-insensitive hit.
pub fn match_snippet(text: &str, query: &str, max_chars: usize) -> Option<String> {
let normalized = text.split_whitespace().collect::<Vec<_>>().join(" ");
let query = query.trim().to_lowercase();
if normalized.is_empty() || query.is_empty() {
return None;
}
let (match_start, match_end) = case_insensitive_range(&normalized, &query)?;
let chars: Vec<char> = normalized.chars().collect();
let start_char = normalized[..match_start].chars().count();
let end_char = normalized[..match_end].chars().count();
if chars.len() <= max_chars {
return Some(normalized);
}

let match_len = end_char.saturating_sub(start_char);
let context = max_chars.saturating_sub(match_len);
let mut start = start_char.saturating_sub(context / 2);
let end = (start + max_chars).min(chars.len());
start = end.saturating_sub(max_chars);
let mut snippet: String = chars[start..end].iter().collect();
if start > 0 {
snippet.insert(0, '…');
}
if end < chars.len() {
snippet.push('…');
}
Some(snippet)
}

fn case_insensitive_range(text: &str, lower_query: &str) -> Option<(usize, usize)> {
for (start, _) in text.char_indices() {
let suffix = &text[start..];
if !suffix.to_lowercase().starts_with(lower_query) {
continue;
}
let mut folded_len = 0;
let mut end = start;
for ch in suffix.chars() {
folded_len += ch.to_lowercase().map(char::len_utf8).sum::<usize>();
end += ch.len_utf8();
if folded_len >= lower_query.len() {
return Some((start, end));
}
}
}
None
}

#[cfg(test)]
mod tests {
use std::path::PathBuf;

use agent::{AgentEvent, ItemStatus, ProviderKind, ThreadItem};
use serde_json::json;
use tcode_core::project::SessionMeta;

use super::*;

fn completed(id: &str, content: ItemContent) -> StoredEvent {
AgentEvent::ItemCompleted(ThreadItem {
id: id.into(),
parent_item_id: None,
content,
})
.into()
}

#[test]
fn extracts_user_and_assistant_messages() {
let entries = extract_searchable_entries(&[
completed(
"user",
ItemContent::UserMessage {
text: "Where is auth.rs?".into(),
context_len: None,
attachments: Vec::new(),
},
),
completed(
"assistant",
ItemContent::AssistantMessage {
text: "It is under crates/runtime.".into(),
},
),
]);
assert_eq!(entries.len(), 2);
assert_eq!(entries[0].text, "Where is auth.rs?");
assert_eq!(entries[1].text, "It is under crates/runtime.");
}

#[test]
fn extracts_tool_titles_paths_and_commands() {
let entries = extract_searchable_entries(&[
completed(
"command",
ItemContent::CommandExecution {
command: "rg auth.rs crates".into(),
output: "large output is deliberately not indexed".into(),
exit_code: Some(0),
status: ItemStatus::Completed,
},
),
completed(
"tool",
ItemContent::ToolCall {
name: "read_file".into(),
input: json!({"path": "src/auth.rs"}),
output: None,
status: ItemStatus::Completed,
},
),
]);
assert_eq!(entries[0].text, "rg auth.rs crates");
assert!(entries[1].text.contains("read_file"));
assert!(entries[1].text.contains("src/auth.rs"));
}

#[test]
fn query_matching_is_case_insensitive_and_generates_a_bounded_snippet() {
let text = format!("{} AUTH.rs {}", "before ".repeat(20), "after ".repeat(20));
let snippet = match_snippet(&text, "auth.RS", 60).expect("match");
assert!(snippet.contains("AUTH.rs"));
assert!(snippet.chars().count() <= 62); // up to two ellipses
assert!(match_snippet(&text, "missing", 60).is_none());
}

#[test]
fn searches_a_fixture_session_log_to_a_session_and_turn() {
let root = std::env::temp_dir().join(format!(
"tcode-session-search-test-{}",
uuid::Uuid::new_v4()
));
let store = SessionStore::open_at(root.clone()).expect("store");
let mut meta = SessionMeta::new(ProviderKind::Codex, PathBuf::from("/project"), None);
meta.title = "Authentication cleanup".into();
store
.append_event(
&meta.id,
1,
&AgentEvent::TurnStarted {
turn_id: "turn-1".into(),
},
)
.unwrap();
store
.append_event(
&meta.id,
2,
&completed(
"assistant",
ItemContent::AssistantMessage {
text: "I updated crates/runtime/src/auth.rs".into(),
},
)
.event,
)
.unwrap();

let hits = SessionSearch::new(store).search(&[meta.clone()], "auth.rs", 10);
assert_eq!(hits.len(), 1);
assert_eq!(hits[0].session_id, meta.id);
assert_eq!(hits[0].turn, 0);
assert!(hits[0].snippet.contains("auth.rs"));
let _ = fs::remove_dir_all(root);
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/services/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,7 @@ pub mod process;
pub mod provider_auth;
pub mod provider_probe;
pub mod relaunch;
pub mod session_search;
pub mod settings;
pub mod shell_env;
pub mod store;
Expand Down
380 changes: 380 additions & 0 deletions crates/services/src/session_search.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,380 @@
//! Lazy full-text search over persisted session event logs.
//!
//! The index is deliberately in-memory: each session is parsed only when its
//! JSONL file's length or modification time changes. This keeps the append-only
//! persistence format authoritative and avoids a second on-disk database.

use std::collections::{HashMap, HashSet};
use std::fs;
use std::time::SystemTime;

use agent::ItemContent;
use tcode_core::project::SessionMeta;
use tcode_core::session::{EntryContent, StoredEvent, Timeline};

use crate::store::SessionStore;

/// One final, folded timeline entry that contributes to content search.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SearchableEntry {
pub entry_id: String,
pub turn: usize,
pub text: String,
}

/// A content match suitable for presentation by a session picker.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionSearchHit {
pub session_id: String,
pub session_title: String,
pub entry_id: String,
pub turn: usize,
pub snippet: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct FileFingerprint {
len: u64,
modified: Option<SystemTime>,
}

#[derive(Debug, Clone)]
struct CachedSession {
fingerprint: FileFingerprint,
entries: Vec<SearchableEntry>,
}

/// Incremental, file-freshness-based content index for one [`SessionStore`].
pub struct SessionSearch {
store: SessionStore,
cache: HashMap<String, CachedSession>,
}

impl SessionSearch {
pub fn new(store: SessionStore) -> Self {
Self {
store,
cache: HashMap::new(),
}
}

/// Search sessions in the supplied order, returning at most `limit` hits.
/// Empty and whitespace-only queries intentionally return no content hits.
pub fn search(
&mut self,
sessions: &[SessionMeta],
query: &str,
limit: usize,
) -> Vec<SessionSearchHit> {
let query = query.trim();
if query.is_empty() || limit == 0 {
return Vec::new();
}

let live_ids: HashSet<&str> = sessions.iter().map(|meta| meta.id.as_str()).collect();
self.cache.retain(|id, _| live_ids.contains(id.as_str()));

let mut hits = Vec::new();
for meta in sessions {
self.refresh(meta);
let Some(cached) = self.cache.get(&meta.id) else {
continue;
};
for entry in &cached.entries {
let Some(snippet) = match_snippet(&entry.text, query, 140) else {
continue;
};
hits.push(SessionSearchHit {
session_id: meta.id.clone(),
session_title: meta.title.clone(),
entry_id: entry.entry_id.clone(),
turn: entry.turn,
snippet,
});
if hits.len() == limit {
return hits;
}
}
}
hits
}

fn refresh(&mut self, meta: &SessionMeta) {
let path = self.store.root().join(format!("{}.jsonl", meta.id));
let fingerprint = match fs::metadata(path) {
Ok(metadata) => FileFingerprint {
len: metadata.len(),
modified: metadata.modified().ok(),
},
Err(error) if error.kind() == std::io::ErrorKind::NotFound => FileFingerprint {
len: 0,
modified: None,
},
Err(error) => {
log::warn!("cannot inspect session log {}: {error}", meta.id);
return;
}
};
if self
.cache
.get(&meta.id)
.is_some_and(|cached| cached.fingerprint == fingerprint)
{
return;
}
let entries = extract_searchable_entries(&self.store.read_events(&meta.id));
self.cache.insert(
meta.id.clone(),
CachedSession {
fingerprint,
entries,
},
);
}
}

/// Fold persisted events and extract the final searchable representation.
///
/// Folding first deduplicates streaming deltas and item lifecycle updates, so
/// callers index what the chat ultimately displays rather than every wire event.
pub fn extract_searchable_entries(events: &[StoredEvent]) -> Vec<SearchableEntry> {
let timeline = Timeline::fold_events(events.iter().cloned());
let mut entries = Vec::new();
for entry in timeline
.entries
.iter()
.chain(timeline.children.values().flatten())
{
let text = match &entry.content {
EntryContent::Item(content) => searchable_item_text(content),
EntryContent::Steer {
text, attachments, ..
} => Some(join_parts(
std::iter::once(text.as_str()).chain(attachments.iter().map(String::as_str)),
)),
_ => None,
};
if let Some(text) = text.filter(|text| !text.trim().is_empty()) {
entries.push(SearchableEntry {
entry_id: entry.id.clone(),
turn: entry.turn,
text,
});
}
}
entries.sort_by_key(|entry| entry.turn);
entries
}

fn searchable_item_text(content: &ItemContent) -> Option<String> {
match content {
ItemContent::UserMessage {
text, attachments, ..
} => Some(join_parts(
std::iter::once(text.as_str()).chain(attachments.iter().map(String::as_str)),
)),
ItemContent::AssistantMessage { text } => Some(text.clone()),
ItemContent::CommandExecution { command, .. } => Some(command.clone()),
ItemContent::FileChange { changes, .. } => Some(join_parts(
changes.iter().map(|change| change.path.as_str()),
)),
ItemContent::ToolCall { name, input, .. } => {
Some(format!("{name} {}", compact_json(input)))
}
ItemContent::Subagent {
agent_type,
description,
summary,
..
} => Some(join_parts(
[agent_type.as_str(), description.as_str()]
.into_iter()
.chain(summary.iter().map(String::as_str)),
)),
ItemContent::WebSearch { query } => Some(query.clone()),
ItemContent::Other {
provider_kind,
summary,
} => Some(format!("{provider_kind} {summary}")),
ItemContent::Reasoning { .. } => None,
}
}

fn compact_json(value: &serde_json::Value) -> String {
serde_json::to_string(value).unwrap_or_default()
}

fn join_parts<'a>(parts: impl Iterator<Item = &'a str>) -> String {
parts
.filter(|part| !part.is_empty())
.collect::<Vec<_>>()
.join(" ")
}

/// Return a compact, whitespace-normalized snippet for a case-insensitive hit.
pub fn match_snippet(text: &str, query: &str, max_chars: usize) -> Option<String> {
let normalized = text.split_whitespace().collect::<Vec<_>>().join(" ");
let query = query.trim().to_lowercase();
if normalized.is_empty() || query.is_empty() {
return None;
}
let (match_start, match_end) = case_insensitive_range(&normalized, &query)?;
let chars: Vec<char> = normalized.chars().collect();
let start_char = normalized[..match_start].chars().count();
let end_char = normalized[..match_end].chars().count();
if chars.len() <= max_chars {
return Some(normalized);
}

let match_len = end_char.saturating_sub(start_char);
let context = max_chars.saturating_sub(match_len);
let mut start = start_char.saturating_sub(context / 2);
let end = (start + max_chars).min(chars.len());
start = end.saturating_sub(max_chars);
let mut snippet: String = chars[start..end].iter().collect();
if start > 0 {
snippet.insert(0, '…');
}
if end < chars.len() {
snippet.push('…');
}
Some(snippet)
}

fn case_insensitive_range(text: &str, lower_query: &str) -> Option<(usize, usize)> {
for (start, _) in text.char_indices() {
let suffix = &text[start..];
if !suffix.to_lowercase().starts_with(lower_query) {
continue;
}
let mut folded_len = 0;
let mut end = start;
for ch in suffix.chars() {
folded_len += ch.to_lowercase().map(char::len_utf8).sum::<usize>();
end += ch.len_utf8();
if folded_len >= lower_query.len() {
return Some((start, end));
}
}
}
None
}

#[cfg(test)]
mod tests {
use std::path::PathBuf;

use agent::{AgentEvent, ItemStatus, ProviderKind, ThreadItem};
use serde_json::json;
use tcode_core::project::SessionMeta;

use super::*;

fn completed(id: &str, content: ItemContent) -> StoredEvent {
AgentEvent::ItemCompleted(ThreadItem {
id: id.into(),
parent_item_id: None,
content,
})
.into()
}

#[test]
fn extracts_user_and_assistant_messages() {
let entries = extract_searchable_entries(&[
completed(
"user",
ItemContent::UserMessage {
text: "Where is auth.rs?".into(),
context_len: None,
attachments: Vec::new(),
},
),
completed(
"assistant",
ItemContent::AssistantMessage {
text: "It is under crates/runtime.".into(),
},
),
]);
assert_eq!(entries.len(), 2);
assert_eq!(entries[0].text, "Where is auth.rs?");
assert_eq!(entries[1].text, "It is under crates/runtime.");
}

#[test]
fn extracts_tool_titles_paths_and_commands() {
let entries = extract_searchable_entries(&[
completed(
"command",
ItemContent::CommandExecution {
command: "rg auth.rs crates".into(),
output: "large output is deliberately not indexed".into(),
exit_code: Some(0),
status: ItemStatus::Completed,
},
),
completed(
"tool",
ItemContent::ToolCall {
name: "read_file".into(),
input: json!({"path": "src/auth.rs"}),
output: None,
status: ItemStatus::Completed,
},
),
]);
assert_eq!(entries[0].text, "rg auth.rs crates");
assert!(entries[1].text.contains("read_file"));
assert!(entries[1].text.contains("src/auth.rs"));
}

#[test]
fn query_matching_is_case_insensitive_and_generates_a_bounded_snippet() {
let text = format!("{} AUTH.rs {}", "before ".repeat(20), "after ".repeat(20));
let snippet = match_snippet(&text, "auth.RS", 60).expect("match");
assert!(snippet.contains("AUTH.rs"));
assert!(snippet.chars().count() <= 62); // up to two ellipses
assert!(match_snippet(&text, "missing", 60).is_none());
}

#[test]
fn searches_a_fixture_session_log_to_a_session_and_turn() {
let root = std::env::temp_dir().join(format!(
"tcode-session-search-test-{}",
uuid::Uuid::new_v4()
));
let store = SessionStore::open_at(root.clone()).expect("store");
let mut meta = SessionMeta::new(ProviderKind::Codex, PathBuf::from("/project"), None);
meta.title = "Authentication cleanup".into();
store
.append_event(
&meta.id,
1,
&AgentEvent::TurnStarted {
turn_id: "turn-1".into(),
},
)
.unwrap();
store
.append_event(
&meta.id,
2,
&completed(
"assistant",
ItemContent::AssistantMessage {
text: "I updated crates/runtime/src/auth.rs".into(),
},
)
.event,
)
.unwrap();

let hits = SessionSearch::new(store).search(&[meta.clone()], "auth.rs", 10);
assert_eq!(hits.len(), 1);
assert_eq!(hits[0].session_id, meta.id);
assert_eq!(hits[0].turn, 0);
assert!(hits[0].snippet.contains("auth.rs"));
let _ = fs::remove_dir_all(root);
}
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/services/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,7 @@ pub mod process;
pub mod provider_auth;
pub mod provider_probe;
pub mod relaunch;
pub mod session_search;
pub mod settings;
pub mod shell_env;
pub mod store;
Expand Down
380 changes: 380 additions & 0 deletions crates/services/src/session_search.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,380 @@
//! Lazy full-text search over persisted session event logs.
//!
//! The index is deliberately in-memory: each session is parsed only when its
//! JSONL file's length or modification time changes. This keeps the append-only
//! persistence format authoritative and avoids a second on-disk database.

use std::collections::{HashMap, HashSet};
use std::fs;
use std::time::SystemTime;

use agent::ItemContent;
use tcode_core::project::SessionMeta;
use tcode_core::session::{EntryContent, StoredEvent, Timeline};

use crate::store::SessionStore;

/// One final, folded timeline entry that contributes to content search.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SearchableEntry {
pub entry_id: String,
pub turn: usize,
pub text: String,
}

/// A content match suitable for presentation by a session picker.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionSearchHit {
pub session_id: String,
pub session_title: String,
pub entry_id: String,
pub turn: usize,
pub snippet: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct FileFingerprint {
len: u64,
modified: Option<SystemTime>,
}

#[derive(Debug, Clone)]
struct CachedSession {
fingerprint: FileFingerprint,
entries: Vec<SearchableEntry>,
}

/// Incremental, file-freshness-based content index for one [`SessionStore`].
pub struct SessionSearch {
store: SessionStore,
cache: HashMap<String, CachedSession>,
}

impl SessionSearch {
pub fn new(store: SessionStore) -> Self {
Self {
store,
cache: HashMap::new(),
}
}

/// Search sessions in the supplied order, returning at most `limit` hits.
/// Empty and whitespace-only queries intentionally return no content hits.
pub fn search(
&mut self,
sessions: &[SessionMeta],
query: &str,
limit: usize,
) -> Vec<SessionSearchHit> {
let query = query.trim();
if query.is_empty() || limit == 0 {
return Vec::new();
}

let live_ids: HashSet<&str> = sessions.iter().map(|meta| meta.id.as_str()).collect();
self.cache.retain(|id, _| live_ids.contains(id.as_str()));

let mut hits = Vec::new();
for meta in sessions {
self.refresh(meta);
let Some(cached) = self.cache.get(&meta.id) else {
continue;
};
for entry in &cached.entries {
let Some(snippet) = match_snippet(&entry.text, query, 140) else {
continue;
};
hits.push(SessionSearchHit {
session_id: meta.id.clone(),
session_title: meta.title.clone(),
entry_id: entry.entry_id.clone(),
turn: entry.turn,
snippet,
});
if hits.len() == limit {
return hits;
}
}
}
hits
}

fn refresh(&mut self, meta: &SessionMeta) {
let path = self.store.root().join(format!("{}.jsonl", meta.id));
let fingerprint = match fs::metadata(path) {
Ok(metadata) => FileFingerprint {
len: metadata.len(),
modified: metadata.modified().ok(),
},
Err(error) if error.kind() == std::io::ErrorKind::NotFound => FileFingerprint {
len: 0,
modified: None,
},
Err(error) => {
log::warn!("cannot inspect session log {}: {error}", meta.id);
return;
}
};
if self
.cache
.get(&meta.id)
.is_some_and(|cached| cached.fingerprint == fingerprint)
{
return;
}
let entries = extract_searchable_entries(&self.store.read_events(&meta.id));
self.cache.insert(
meta.id.clone(),
CachedSession {
fingerprint,
entries,
},
);
}
}

/// Fold persisted events and extract the final searchable representation.
///
/// Folding first deduplicates streaming deltas and item lifecycle updates, so
/// callers index what the chat ultimately displays rather than every wire event.
pub fn extract_searchable_entries(events: &[StoredEvent]) -> Vec<SearchableEntry> {
let timeline = Timeline::fold_events(events.iter().cloned());
let mut entries = Vec::new();
for entry in timeline
.entries
.iter()
.chain(timeline.children.values().flatten())
{
let text = match &entry.content {
EntryContent::Item(content) => searchable_item_text(content),
EntryContent::Steer {
text, attachments, ..
} => Some(join_parts(
std::iter::once(text.as_str()).chain(attachments.iter().map(String::as_str)),
)),
_ => None,
};
if let Some(text) = text.filter(|text| !text.trim().is_empty()) {
entries.push(SearchableEntry {
entry_id: entry.id.clone(),
turn: entry.turn,
text,
});
}
}
entries.sort_by_key(|entry| entry.turn);
entries
}

fn searchable_item_text(content: &ItemContent) -> Option<String> {
match content {
ItemContent::UserMessage {
text, attachments, ..
} => Some(join_parts(
std::iter::once(text.as_str()).chain(attachments.iter().map(String::as_str)),
)),
ItemContent::AssistantMessage { text } => Some(text.clone()),
ItemContent::CommandExecution { command, .. } => Some(command.clone()),
ItemContent::FileChange { changes, .. } => Some(join_parts(
changes.iter().map(|change| change.path.as_str()),
)),
ItemContent::ToolCall { name, input, .. } => {
Some(format!("{name} {}", compact_json(input)))
}
ItemContent::Subagent {
agent_type,
description,
summary,
..
} => Some(join_parts(
[agent_type.as_str(), description.as_str()]
.into_iter()
.chain(summary.iter().map(String::as_str)),
)),
ItemContent::WebSearch { query } => Some(query.clone()),
ItemContent::Other {
provider_kind,
summary,
} => Some(format!("{provider_kind} {summary}")),
ItemContent::Reasoning { .. } => None,
}
}

fn compact_json(value: &serde_json::Value) -> String {
serde_json::to_string(value).unwrap_or_default()
}

fn join_parts<'a>(parts: impl Iterator<Item = &'a str>) -> String {
parts
.filter(|part| !part.is_empty())
.collect::<Vec<_>>()
.join(" ")
}

/// Return a compact, whitespace-normalized snippet for a case-insensitive hit.
pub fn match_snippet(text: &str, query: &str, max_chars: usize) -> Option<String> {
let normalized = text.split_whitespace().collect::<Vec<_>>().join(" ");
let query = query.trim().to_lowercase();
if normalized.is_empty() || query.is_empty() {
return None;
}
let (match_start, match_end) = case_insensitive_range(&normalized, &query)?;
let chars: Vec<char> = normalized.chars().collect();
let start_char = normalized[..match_start].chars().count();
let end_char = normalized[..match_end].chars().count();
if chars.len() <= max_chars {
return Some(normalized);
}

let match_len = end_char.saturating_sub(start_char);
let context = max_chars.saturating_sub(match_len);
let mut start = start_char.saturating_sub(context / 2);
let end = (start + max_chars).min(chars.len());
start = end.saturating_sub(max_chars);
let mut snippet: String = chars[start..end].iter().collect();
if start > 0 {
snippet.insert(0, '…');
}
if end < chars.len() {
snippet.push('…');
}
Some(snippet)
}

fn case_insensitive_range(text: &str, lower_query: &str) -> Option<(usize, usize)> {
for (start, _) in text.char_indices() {
let suffix = &text[start..];
if !suffix.to_lowercase().starts_with(lower_query) {
continue;
}
let mut folded_len = 0;
let mut end = start;
for ch in suffix.chars() {
folded_len += ch.to_lowercase().map(char::len_utf8).sum::<usize>();
end += ch.len_utf8();
if folded_len >= lower_query.len() {
return Some((start, end));
}
}
}
None
}

#[cfg(test)]
mod tests {
use std::path::PathBuf;

use agent::{AgentEvent, ItemStatus, ProviderKind, ThreadItem};
use serde_json::json;
use tcode_core::project::SessionMeta;

use super::*;

fn completed(id: &str, content: ItemContent) -> StoredEvent {
AgentEvent::ItemCompleted(ThreadItem {
id: id.into(),
parent_item_id: None,
content,
})
.into()
}

#[test]
fn extracts_user_and_assistant_messages() {
let entries = extract_searchable_entries(&[
completed(
"user",
ItemContent::UserMessage {
text: "Where is auth.rs?".into(),
context_len: None,
attachments: Vec::new(),
},
),
completed(
"assistant",
ItemContent::AssistantMessage {
text: "It is under crates/runtime.".into(),
},
),
]);
assert_eq!(entries.len(), 2);
assert_eq!(entries[0].text, "Where is auth.rs?");
assert_eq!(entries[1].text, "It is under crates/runtime.");
}

#[test]
fn extracts_tool_titles_paths_and_commands() {
let entries = extract_searchable_entries(&[
completed(
"command",
ItemContent::CommandExecution {
command: "rg auth.rs crates".into(),
output: "large output is deliberately not indexed".into(),
exit_code: Some(0),
status: ItemStatus::Completed,
},
),
completed(
"tool",
ItemContent::ToolCall {
name: "read_file".into(),
input: json!({"path": "src/auth.rs"}),
output: None,
status: ItemStatus::Completed,
},
),
]);
assert_eq!(entries[0].text, "rg auth.rs crates");
assert!(entries[1].text.contains("read_file"));
assert!(entries[1].text.contains("src/auth.rs"));
}

#[test]
fn query_matching_is_case_insensitive_and_generates_a_bounded_snippet() {
let text = format!("{} AUTH.rs {}", "before ".repeat(20), "after ".repeat(20));
let snippet = match_snippet(&text, "auth.RS", 60).expect("match");
assert!(snippet.contains("AUTH.rs"));
assert!(snippet.chars().count() <= 62); // up to two ellipses
assert!(match_snippet(&text, "missing", 60).is_none());
}

#[test]
fn searches_a_fixture_session_log_to_a_session_and_turn() {
let root = std::env::temp_dir().join(format!(
"tcode-session-search-test-{}",
uuid::Uuid::new_v4()
));
let store = SessionStore::open_at(root.clone()).expect("store");
let mut meta = SessionMeta::new(ProviderKind::Codex, PathBuf::from("/project"), None);
meta.title = "Authentication cleanup".into();
store
.append_event(
&meta.id,
1,
&AgentEvent::TurnStarted {
turn_id: "turn-1".into(),
},
)
.unwrap();
store
.append_event(
&meta.id,
2,
&completed(
"assistant",
ItemContent::AssistantMessage {
text: "I updated crates/runtime/src/auth.rs".into(),
},
)
.event,
)
.unwrap();

let hits = SessionSearch::new(store).search(&[meta.clone()], "auth.rs", 10);
assert_eq!(hits.len(), 1);
assert_eq!(hits[0].session_id, meta.id);
assert_eq!(hits[0].turn, 0);
assert!(hits[0].snippet.contains("auth.rs"));
let _ = fs::remove_dir_all(root);
}
}
Loading