Local-first, zero-token interactive session search plugin for OpenCode: indexes local SQLite session history, previews matching messages, tools, and files as you type, and opens matching conversations from the TUI or OpenCode Desktop.
| OpenCode Desktop | OpenCode TUI |
|---|---|
![]() |
![]() |
| View full size | View full size |
Note: Previews were rendered in headless Chromium via Playwright from the plugin's actual Desktop (dist/gui-experimental.cjs) and TUI (src/tui.ts) UI code using synthetic fixture data and a simulated host frame, rather than captured from a live OpenCode window or terminal.
Replaces OpenCode Desktop's built-in session search. The titlebar, vertical-tabs (Search), Home session search, and built-in Search sessions dialog route into this plugin's Search interface.
Now available in OpenCode Desktop as well as the TUI. Search local conversation history in a persistent Search side panel (side-by-side at 640px and wider, or list-to-matches with a Back button in narrow panels), sort sessions by recency, relevance (auto-selected while typing unless manually overridden), creation time, title, context size, or total tokens, hide the current session with Hide this session, preview matching messages and file/tool details, and open matching sessions without a model turn. Press Ctrl+Shift+F to open or focus the panel, or Ctrl+Alt+F to toggle it. When no session is active, search opens in a fallback dialog.
In the CLI/TUI, search is an additional tool rather than a replacement. Open it with /search or the command palette. The built-in /sessions picker remains available.
One global OpenCode V2 plugin entry loads the server RPC bridge, TUI, and Desktop integration together. Both interfaces search the same local session history; see Installation for setup.
This project started as a small local CLI script wired to a custom /search command. It queried OpenCode's SQLite database and printed matching session IDs into the chat, which worked as a quick prototype but had two limitations in daily use:
- Every search ran through an LLM turn: Because custom markdown commands send their output to the model, searching past sessions took several seconds and used prompt and completion tokens just to look up an old conversation.
- Results were static text: Getting a list of session IDs in the chat still meant copying an ID or opening
/sessionsto actually switch to the session.
opencode-local-search makes session search a native part of the terminal interface:
- Zero-token local SQLite indexing: Queries OpenCode's local SQLite database directly inside the TUI using the runtime's built-in driver (
bun:sqliteornode:sqlite) without making an LLM request. - Live split-pane preview: Filter across your past work on every keystroke on the left while inspecting highlighted message snippets, tools used, and files touched on the right.
- Jump to the exact message: Pressing
Enteropens the selected session and scrolls the transcript straight to the message that matched instead of the bottom of the conversation.
| Feature | Details |
|---|---|
| Local-first, zero-token execution | Queries your local OpenCode SQLite database directly inside the TUI with zero LLM token usage, zero server tools, and zero cloud dependencies |
| Zero external npm dependencies | Uses the SQLite driver built into OpenCode's runtime (bun:sqlite or node:sqlite) and a built-in bounded Levenshtein matcher, requiring no native C++ addons |
| Dual-schema support (OpenCode V2 + V1) | Automatically detects and indexes both the OpenCode V2 schema (session_v2 and session_message) and the V1 schema (session, message, and part) |
Interactive /search TUI modal |
Wide (80% default, configurable via dialogWidth) split-pane popup with colored filter pills (^p scope, ^g role, ^t date, ^r mode, ^o sort, ^l refresh), live session list on the left, and highlighted message/tool/file snippet cards on the right |
| Session-level multi-term AND ranking | Searching auth cookie finds sessions where both terms appear anywhere across the session title, user prompts, assistant replies, tool calls, or file paths, ranking single-message co-occurrences higher |
| Multi-mode session sorting | Sort results by Recently updated, Relevance, Newest created, Oldest created, Title A-Z, Latest context size, or Total tokens used (src/sort.ts) |
| Typo-tolerant fuzzy & regex search | Supports "exact phrase", /regex/i (re:), explicit ~fuzzy terms, and automatic bounded Levenshtein fallback when a multi-word query has a typo |
| Auto-scroll to matched message | Pressing Enter (or clicking any snippet card in the preview pane) opens the session and automatically scrolls the transcript to the exact matched message |
| OpenCode Desktop search | Persistent Search side panel backed by SearchRpc.query, with a fallback dialog when no session is active, centered loading spinner, scope/query/sort controls, snippets, and session navigation |
Install with OpenCode's native plugin CLI. OpenCode downloads the package from npm (or GitHub) into its own cache automatically and adds one entry to ~/.config/opencode/opencode.jsonc that loads the server RPC bridge, /search TUI popup, and Desktop panel together:
opencode plugin add @nandoblanco/opencode-local-search
# Auto-update on startup and every 24 hours:
opencode plugin add @nandoblanco/opencode-local-search@latest
# Or install directly from GitHub:
opencode plugin add github:nandoblanco/opencode-local-searchAdd @nandoblanco/opencode-local-search to "plugins" in the global ~/.config/opencode/opencode.jsonc (or project ./opencode.jsonc / ./.opencode/opencode.jsonc). OpenCode fetches the npm package automatically and loads the server RPC bridge, TUI, and Desktop parts from this single entry (no manual npm install or separate cli.json entry is required):
{
"plugins": [
{
"package": "@nandoblanco/opencode-local-search",
"options": {
"dialogWidth": "80%"
}
}
]
}Run the package CLI once via npx to register the plugin in ~/.config/opencode/opencode.jsonc:
npx @nandoblanco/opencode-local-search install
# Or directly from GitHub:
npx github:nandoblanco/opencode-local-search installFor development, use Node.js 26.4 or newer to meet the OpenTUI dependency's declared minimum. Clone this repository, run npm ci and npm run build to build the Desktop bundle, then reference the directory in opencode.jsonc (or place the directory inside ~/.config/opencode/plugins/ or .opencode/plugins/). TUI-only use does not need the GUI build. The root overrides pin patched glob and minimatch versions for this repository's development dependencies; they do not alter the OpenCode host application's dependencies:
{
"plugins": ["file:///path/to/opencode-local-search"]
}- Interactive
/searchpopup: Run/searchto open the popup, or/search <query>(for example/search playwrightor/search file:tui.ts) to open with your search pre-filled. - Command palette: Press
Ctrl+Pand selectSearch session history.... - Custom keybind: Bind
session.history.searchin~/.config/opencode/cli.json:
{
"keybinds": {
"session.history.search": "ctrl+f"
}
}Run /search [query] or press Ctrl+Shift+F (Cmd+Shift+F on macOS) to open and focus the persistent Search side panel. Ctrl+Alt+F (Cmd+Option+F) toggles it. Without an active session, these commands open a dialog. The plugin also intercepts the built-in titlebar, vertical-tab (Search), and home-session search entry points.
Desktop requests use a 16 ms debounce, a centered loading spinner overlay, and a sequence counter to discard stale responses. They call SearchRpc.query on the server, which loads and caches the SQLite session index on demand and returns up to 60 session results with message snippets, token/context metadata, and file/tool details. The TUI continues to query SQLite locally. Exact-message scrolling in the TUI uses the render-tree traversal described below; Desktop uses its own session navigation path.
Type filters inline in the search bar or toggle them with keyboard shortcuts and clickable filter pills.
| Syntax | Description | Example |
|---|---|---|
term1 term2 |
Session-level AND across title, messages, tools, and files (single-message hits rank higher) | auth cookie |
"exact phrase" |
Exact substring phrase match | "session_message" |
~term |
Typo-tolerant fuzzy match (bounded Levenshtein distance) | ~playwrigth |
/pattern/i or re:pattern |
Regular expression match | /error\s+\d+/i |
role:user / role:assistant / role:shell |
Filter by message author (from:user, from:ai also work) |
role:user backup |
scope:project / scope:all |
Filter to current workspace directory or all workspaces | scope:project |
date:today / date:yesterday / date:7d / date:30d |
Relative date filter | date:7d migration |
date:YYYY-MM or date:YYYY-MM-DD..YYYY-MM-DD |
Month or date range filter | date:2026-10 |
file:<path> |
Filter sessions that read or modified a matching file path | file:tui.ts |
tool:<name> |
Filter sessions that invoked a matching tool | tool:edit |
in:title / in:message / in:tool / in:file |
Restrict search to a specific entry type | in:title plugin |
| Key | Action |
|---|---|
Enter |
Open the selected session and auto-scroll to the active matched snippet |
Up / Down or Ctrl+N / Ctrl+K |
Move selection up or down (or cycle matching snippets when the Preview pane is focused; j/k also work in List and Preview panes) |
PageUp / PageDown or Ctrl+U / Ctrl+D |
Jump 6 sessions up/down (or scroll the Preview pane by 8 lines when focused) |
Tab / Shift+Tab |
Switch focus between Search Input, Session List, and Preview Pane (/ returns to Search Input) |
Ctrl+P |
Toggle project scope pill (scope:all <-> scope:project) |
Ctrl+G |
Cycle role filter pill (all -> user -> assistant -> shell) |
Ctrl+T |
Cycle date filter pill (all -> today -> yesterday -> 7d -> 30d) |
Ctrl+R |
Cycle search mode pill (smart -> fuzzy -> regex) |
Ctrl+O |
Cycle session sort order (updated -> relevance -> newest -> oldest -> title -> context -> tokens) |
Ctrl+L |
Force refresh the SQLite session index |
Esc |
Close popup |
opencode-local-search has zero runtime npm dependencies and requires no compiled C++ addons. When the popup opens, openReadOnlyDb() detects the active JavaScript runtime (Bun vs. Node.js) and dynamically imports the built-in SQLite driver (bun:sqlite or node:sqlite) in read-only mode.
resolveDbPath() locates the OpenCode database in this order:
- Explicit
customPathargument (used by tests or custom callers) OPENCODE_DB_PATHenvironment variable$XDG_DATA_HOME/opencode/opencode.db~/.local/share/opencode/opencode.db(macOS, Linux, Windows)%LOCALAPPDATA%/opencode/opencode.db(Windows fallback)
Once loaded, loadSessionIndex() keeps the parsed SessionIndex in memory (INDEX_TTL_MS = 2000) and performs incremental SQLite delta updates (WHERE time_updated > cachedMaxUpdated) so only newly modified sessions are re-read from session_v2 and session_message. Typing in the search bar filters in sub-millisecond time (Ctrl+L or Desktop Refresh forces a full re-index).
At index time, loadSessionIndex() inspects sqlite_master to support both OpenCode database generations automatically:
- OpenCode V2 (
session_v2+session_message):- Inspects
PRAGMA table_info(session_v2)to resolve workspace directory columns (directoryorCOALESCE(workspace_directory, root_directory, '')) and exclude archived sessions (WHERE time_archived IS NULL). - Loads the 800 most recently updated sessions and uses a window function (
ROW_NUMBER() OVER (PARTITION BY m.session_id ORDER BY m.time_created DESC)) to pull up to the latest 250 messages per session (LIMIT 30000, with a plainORDER BYfallback if window functions are unavailable).
- Inspects
- OpenCode V1 Fallback (
session+message+part):- Automatically falls back to joining
partandmessage(json_extract(m.data, '$.role')) ifsession_v2is not present.
- Automatically falls back to joining
- Structured entry extraction:
- The indexer splits each message JSON payload into three
SearchEntrykinds:message: User prompt text and assistant reply text partstool: Tool invocations ([toolName] key: value · ...viastringifyToolInput()) and shell commands plus terminal output ($ command\noutput)filepath: Attached user files, patch file lists, and file paths extracted from tool arguments (path,filePath,file,file_path,targetFile,workdir,directory,filesviaextractFilePathsFromInput())
- The indexer splits each message JSON payload into three
parseSearchQuery() tokenizes raw input with /(\/[^/]+\/[gimsuy]*|[a-zA-Z]+:"[^"]+"|"[^"]+"|\S+)/g, separating inline filter tokens (role:, scope:, date:, file:, tool:, in:, re:, ~fuzzy) from search terms and quoted phrases.
When filtering sessions, searchSessionIndex() enforces session-level multi-term AND matching: every required term in terms and fuzzyTerms must appear somewhere in the session, even if one term is in the session title, another is in a user prompt, and a third is in an edited file path. searchSessionIndex() scores matching sessions with fixed weights:
| Signal | Score Contribution | Notes |
|---|---|---|
| Title regex match | +120 |
When searching in regex mode (/pattern/i or re:) |
| Title exact substring match | +90 |
Per query term matched in session.title |
| Title fuzzy match | +65 - (distance * 10) |
Explicit ~term (+55 - distance * 10 in fuzzy mode) |
| Entry exact match | +35 * entryMatchedTerms |
Per message, tool call, or file path entry (+50 / +35 in regex mode) |
| Entry fuzzy match | +20 * entryMatchedTerms |
When matched via bounded Levenshtein distance |
| Single-message co-occurrence bonus | +45 |
Added when a single message contains all query terms |
Active file: / tool: target bonus |
+25 |
Added when an entry directly matches the active file: or tool: filter |
| Recency boost | max(0, 15 - recencyDays * 0.4) |
Breaks ties in favor of recently updated sessions |
src/search.ts implements a bounded Levenshtein dynamic programming matcher (editDistanceBounded(a, b, maxDist)) for typo tolerance:
- Uses two rolling row arrays (
prevandcurr) and aborts immediately if length difference exceedsmaxDistor if the minimum value in the current DP row exceedsmaxDist. - Allows edit distance
<= 1for short words (3 to 5 characters) and<= 2for longer words (6+ characters), pre-filtering candidate tokens by a shared 2-character prefix or length withinmaxDist. - Automatic Smart Fallback: In default
smartmode, if a multi-word query fails the strict session-level AND check because one word has a typo (for example,playwrigth),searchSessionIndex()automatically retries the missing term throughfindFuzzyWordMatch()(+30title /+22entry) and tags the resulting snippet as[FUZZY].
When you press Enter on a session (or click a specific snippet card in the right preview pane), the plugin navigates to that session (context.ui.router.navigate({ type: "session", sessionID })) and runs scrollToMatchedMessage() to scroll the transcript to the matched message:
- Message store sync: Triggers
context.data.session.message.sync(sessionId)and polls the live@opentuirender tree every 60ms (up to 25 attempts) while the session view mounts. - Viewport discovery: Traverses
context.renderer.rootto find the largest visibleScrollBoxRenderablerepresenting the conversation transcript. - Three-tier node resolution:
- Tier 1 (Exact ID): Matches a render node whose
idequals or contains the targetmessageId. - Tier 2 (Tiered text needles + chronological ratio): Walks
scrollBox.contentand comparesextractRenderableText(node)against progressively broader normalized snippet needles. If multiple nodes match the same text, it computes the message's chronological index ratio (msgIdx / (liveMessages.length - 1)) and picks the candidate whose vertical position (relY) is closest toratio. - Tier 3 (Collapsed tool fallback): If the match was inside a collapsed tool call output, falls back after 6 attempts to scrolling to
topChildren[Math.round(ratio * (topChildren.length - 1))].
- Tier 1 (Exact ID): Matches a render node whose
- Viewport positioning & scroll lock: Scrolls the matched node to 22% from the top of the viewport (
scrollBox.scrollBy({ x: 0, y: dy })), setsscrollBox._hasManualScroll = trueso OpenCode's auto-scroll-to-bottom does not snap back, and re-applies the offset after 120ms to settle layout reflows.
- Wide modal layout (
applyDialogWidth&dialog.set):- Calls
context.ui.dialog.show(...)followed bycontext.ui.dialog.set({ size: "xlarge", centered: true })so the dialog opens wide without being reset to default width. - Inside
onMountandref,applyDialogWidth()walks upward fromrootRefto the outerabsolute-positioned dialog container and setswidth: "80%"(or your configureddialogWidth),maxWidth: "80%", andminWidth: 72.
- Calls
- Interactive filter pills & inline badge sync:
- Renders clickable
Pillcomponents beneath the search input forscope:<all|project>(^p),role:<role>(^g),date:<range>(^t), andmode:<mode>(^r), plus live indicator badges whenfile:<path>,tool:<name>, or regex syntax errors are active in the query string.
- Renders clickable
- Split-pane session list & selectable snippet cards:
- Splits the main body into a 44%-width left session list (session title, match kind badge, relative age, and 1-line snippet preview) and a 56%-width right preview pane (session metadata header, files touched chips, and individual matched snippet cards).
- Focusing the right preview pane (
Tab) lets you cycle through individual snippet cards inside the selected session withUp/Downand pressEnter(or click a card directly) to jump straight to that specific message.
src/server.ts registers SearchRpc.query, implemented by executeSearchQuery(), for Desktop clients. It loads the read-only SQLite index and runs the same query parser and ranking functions as the TUI. The server registers zero LLM agent tools and adds 0 schema tokens to model context. src/rpc.ts exports the shared contract; src/gui.tsx and src/gui.css build to dist/gui-experimental.cjs with npm run build.
Every operation in opencode-local-search uses zero LLM tokens:
| Operation | Token Cost | Why |
|---|---|---|
Opening /search & indexing SQLite (loadSessionIndex) |
0 tokens | Queries ~/.local/share/opencode/opencode.db directly in read-only mode via bun:sqlite or node:sqlite |
| Live filtering, fuzzy matching & snippet preview | 0 tokens | Runs synchronously in memory (searchSessionIndex) inside the TUI process on every keystroke |
Jumping to a matched session & message (Enter) |
0 tokens | Navigates via context.ui.router.navigate() and scrolls the local @opentui transcript tree directly |
Server plugin entrypoint (src/server.ts) |
0 schema tokens | Registers no LLM tools or system prompts |
| Desktop queries and session navigation | 0 tokens | Uses the server RPC bridge and Desktop layout API without a model turn |
Configure the package in the global ~/.config/opencode/opencode.jsonc for all interfaces. dialogWidth controls the TUI popup only; Desktop uses its panel or dialog layout:
{
"plugins": [
{
"package": "@nandoblanco/opencode-local-search",
"options": {
"dialogWidth": "80%"
}
}
]
}| Option | Env Variable | Default | Description |
|---|---|---|---|
dialogWidth |
OPENCODE_SESSION_SEARCH_DIALOG_WIDTH |
"80%" |
Width of the centered /search TUI modal ("80%" or column count like 120; also respects OPENCODE_DIALOG_WIDTH) |
| (db path) | OPENCODE_DB_PATH |
~/.local/share/opencode/opencode.db |
Override path to the OpenCode SQLite database |
MIT

