Files
synchronicity/docs/command-palette-and-search.md
Greg ShuflinandClaude Opus 5.5 f3fab6f234 android: every list filter matches by text_match
Music, Comics, the PDF and podcast libraries, Pictures, Video, Humans
(name and subtitle) and the timezone picker each filtered with
contains(ignoreCase = true), which folds case and nothing else. They call
the lib's textMatches instead, so on Android as everywhere else 'cafe'
finds 'Café' and an uppercase letter demands its case.

The search design doc's Android section no longer describes Kotlin
matching as its own substring test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 03:18:56 -08:00

38 KiB
Raw Permalink Blame History

Command Palette and Search

Status: Proposed — a plan to iterate on, not a record of work done. Date: 2026-08-05

1. The question this answers

TODO.md asked: what if all searching in every agent was routed through the command palette — i.e. no agent has its own independent search facility, but agents can customize the command palette as per their unique needs? And, as a follow-on: does this imply the command palette should change its name?

The answer is no, not all of it — but a large, well-defined part of it, and the parts that stay per-agent should share machinery rather than each being hand-rolled. The rest of this document says which is which and how to build both.

2. Current state (as surveyed 2026-08-05)

Worth writing down, because the amount of existing search is much smaller than "every agent has its own rudimentary search" suggests.

The palette (rust/gui-app/src/components/command_palette.rs) is a shell: Ctrl-P, a TextInput, a text_match substring filter over a Vec<Command>, and two placeholder entries ("Switch", "Exit Synchronicity"). run_selected is a TODO that only dismisses. It rolls its own backdrop rather than using components::modal. It exists only in gui-app — there is no Android or TUI equivalent.

Real local search is in one agent, not many. Documents has it in three front-ends — agents/documents/mod.rs (debounced TextInput + type/date filter dropdowns + active-filter chips), DocumentsScreen.kt, and the TUI's / key — all funnelling into DocumentStore::search_document_items_page.

Everything else:

Agent Desktop Android Notes
Documents real real keyset-paginated, store-backed
Notes placeholder (notes/search_bar.rs — its own doc comment says "no wired-up behavior") real, but a client-side title filter over the sidebar list
Podcasts podcasts/search.rs (461 lines) PodcastSearchScreen.kt external directory search, not local content — different category, see §4
Music, Pictures, Comics, Humans, Jobs, Code, Video, QR none none TextInputs in pictures.rs/human.rs are edit fields, not search

The store layer is thinner than the UI implies. There is no FTS5 anywhere in the workspace. search_document_items matches with json_extract(CAST(p.value AS TEXT), '$.value') LIKE ? against the title property only. Note bodies, extracted PDF text, music metadata, and human records are not searchable at all. SearchParams is document-store-shaped (document_types, date_filter, only_roots, include_derived).

The practical consequence: there is almost nothing to tear out. This plan is mostly about what to build, not what to consolidate.

3. The core distinction

The palette is ephemeral. A filter is persistent.

  • The palette opens over the app, you act, it dismisses. It carries no state between invocations.
  • A filter is bound to a view you are living inside. You set it, then scroll, expand a tree node, open something, come back — and it is still applied.

A modal overlay is structurally wrong for durable state. Routing filtering through the palette means building "palette writes a filter into the underlying view, then closes", at which point the palette is an alternate input method for a filter bar that still has to exist — indirection added, no widget removed. Note that none of the apps with strong palettes deleted their in-context filtering: Obsidian has a quick switcher and a persistent Search pane in the left drawer; VS Code has Ctrl-P and an Explorer filter box and a search panel.

So: two features, not one.

Separating these is what makes the rest of the plan fall out.

  1. Run a command — "Import a file", "Sync now", "Toggle dark mode". → Palette.
  2. Jump to a known object — "open that note", "open that PDF". Transient; you type, press Enter, it's gone. → Palette (§6).
  3. Filter the view you're in — narrow a list/tree/grid in place, and keep it narrowed. → Per-agent, shared component (§7).
  4. Query something remote — the podcast directory. Network latency, results are not local objects, and the terminal action is "subscribe", not "open". → Stays an agent-specific flow. The palette may launch it ("Podcasts: find a show…") but must not host it: mixing network-latency rows into an otherwise-instant list makes the whole palette feel broken.

4.1 The instant-feedback invariant

Case 4 is a specific instance of a project-wide rule that holds everywhere in Synchronicity, not just here:

Kicking off any operation that takes a human-noticeable amount of time to complete must (a) return control to the UI instantly, and (b) create a background job that is visible somewhere in the UI. Anywhere this is not the case is a UI bug.

The machinery already exists: lib::jobs (run_as_job / run_as_job_async), first-class Jobs per ADR 0011, and a Jobs screen on desktop, Android, and the TUI. What this document adds is the recognition that search is a place where the rule is easy to violate by accident, because a search box invites a query per keystroke and a query can cross a network or a disk.

Two distinct violations to avoid, since they need different fixes:

  • Long, user-initiated operations (a podcast directory query, an import triggered from the palette) → these become tracked Jobs. The palette's role ends at starting one; it dismisses immediately and the Jobs UI carries the result.
  • Short-but-not-instant incremental queries (a per-keystroke SQLite lookup) → these do not become Jobs. A job per keystroke would turn the Jobs screen into noise. They get debouncing, async execution off the UI thread, and stale-response rejection instead (§6.6).

The dividing line is whether the user thinks of it as "a thing I started" or "the UI keeping up with my typing". Only the former becomes a Job.

"Not a Job" does not mean "not visible". The two clauses of the invariant come apart for incremental queries: clause (a) still binds absolutely, while clause (b) is satisfied in place rather than on the Jobs screen. If an incremental query runs longer than a second or two, the view it belongs to still owes the user a state, and there are three of them:

State Obligation
Running an unobtrusive in-place indicator (spinner in the field's trailing edge, or a muted "searching…" row) — never a blocking modal, never a layout shift
Settled results replace the indicator; zero results must be distinguishable from not-done-yet, since an empty list reads as a wrong answer rather than a slow one
Wedged / failed a visible, non-modal error state with a retry affordance — a query that silently never returns is the worst outcome of the three, and is what "some kind of UI for indicating it got wedged" has to prevent

Priority ordering between the two clauses is not symmetric. Never introducing user-visible latency — above all in the typing path — is the hard constraint; the status affordance is the softer, secondary obligation. A view that shows perfect progress state but drops keystrokes has failed worse than one that shows nothing but stays responsive. Concretely: the input field's own render path must never touch the store, and no query may be awaited on the thread that handles key events.

5. Architecture: one engine, two presentations

The model is Telescope's, not Obsidian's. Telescope is not a search widget — it is a picker abstraction (a source of items + row rendering + actions) plus a fuzzy matcher plus a presentation. find_files, buffers, and live_grep are the same machinery with different sources.

What we want is Telescope's source abstraction driving two presentations:

┌──────────────────────────────────────────────────────────┐
│ Layer 3a: Overlay presentation   │ 3b: Inline presentation│
│ (CommandPalette)                 │ (FilterBar)            │
│ - renders its own uniform rows   │ - renders ONLY the     │
│ - owns selection, Enter, Esc     │   input chrome         │
│ - dismisses on action            │ - hands surviving ids  │
│                                  │   back to the agent,   │
│                                  │   which renders        │
├──────────────────────────────────┴────────────────────────┤
│ Layer 2: Source ("picker")                                │
│   items() -> Vec<Item>; Item { id, haystack, subtitle,    │
│   icon, action }.  Per-agent parameterization lives here. │
├───────────────────────────────────────────────────────────┤
│ Layer 1: Matcher                                          │
│   (query, haystack) -> Option<(score, Vec<match_range>)>  │
│   Pure. No gpui. Unit-testable. Shared by all front-ends. │
└───────────────────────────────────────────────────────────┘

The asymmetry at layer 3 is the important part. In the overlay, the component owns rendering — rows are uniform by design. Inline, it cannot: Pictures renders a thumbnail grid, Humans a table, Notes a tree. So the inline component owns the input, the debounce, and the match state, and returns results; the agent draws.

Consequence: the reusable widget is thin. It is a text field, a clear button, a debounce, and a match-state struct. The value concentrates in layers 1 and 2 — which is good, because those are platform-independent and Android gets them for free across the FFI.

5.1 Two regimes, and why conflating them breaks the design

Client-side fuzzy matching assumes the full candidate list is in memory.

  • Regime A — bounded, in-memory. Notebooks, albums, humans, jobs, podcast subscriptions, the agent list itself. Fuzzy-rank client-side. This is where the shared component earns its keep and where most of the wins are.
  • Regime B — unbounded, store-backed, paginated. Documents today (and music tracks eventually). search_document_items_page fetches LIMIT + 1 and derives a keyset cursor; you cannot fuzzy-rank a list you have not loaded, and pushing fuzzy scoring into SQL stops it being fuzzy.

Regime B shares the input chrome and the placement convention with regime A, but not the matcher. Documents' existing filter bar keeps its current semantics (substring, ordered by created_at DESC); it adopts the shared component only for the input, clear button, and debounce. Do not attempt one matcher for both. What the two regimes do share is the rule for what a character matches (§7.1): regime B's SQL calls text_match as a function, so a title search and a fuzzy pick disagree only about gaps and typos, never about whether e finds é.

Facets are the exception that does cross the boundary (§10.2). A facet is a predicate over a field rather than a text match, so one declaration can be evaluated as an in-memory predicate in regime A or compiled to a SQL WHERE fragment in regime B. Free-text matching is regime-split; structured filtering is not.

Where a set is bounded today but might not be tomorrow (music tracks, pictures), start in regime A and treat the move to B as a known future migration rather than designing for it up front.

6. Feature A — the Command Palette

6.1 Scope

Hosts commands and jump-to-object, in one widget, disambiguated by a mode prefix rather than by being two separate widgets (VS Code's model: Ctrl-P is quick-open, typing > switches to commands).

Prefix Mode Example
(none) Jump to object quarterly → the note "Quarterly review"
> Commands >import → "Documents: Import files…"
@ Jump to agent @pod → Podcasts

Rationale for one widget: jump-to-object was explicitly wanted in the palette. Splitting into an Obsidian-style palette/quick-switcher pair means two hotkeys and two mental models for what is one question ("what do I want to get to?").

6.2 Naming

TODO.md asked whether the name should change. Keep it. The code module stays components::command_palette; the user-facing name stays "Command Palette". The mode-prefix design means commands are the default-ish framing and object-jumping is a mode within it, so the name stays defensible — and it matches what Ctrl-P is called in Obsidian, which is the app whose conventions we are otherwise following.

6.3 Keybindings

Ctrl-P opens the palette. Retain the existing global binding.

Ctrl-K is deliberately NOT used for the palette. Ctrl-K's "search/command" meaning is a web-app convention (Slack's quick switcher → Linear's command menu → the cmdk library → GitHub/Notion/Discord), roughly 2014 onward, and is weak outside the browser — VS Code uses Ctrl-K as a chord prefix, and most native desktop apps do not use it for search at all. Meanwhile Ctrl-K has two much older live meanings: kill-line (Emacs → readline → macOS text fields), and insert hyperlink (Word → Google Docs → Slack composer → essentially every markdown editor, including Obsidian).

Ctrl-K is therefore reserved for insert-link in the Notes agent's editor key context (agents/notes/editor.rs), matching Obsidian. It is currently unbound anywhere in gui-app. gpui key contexts would technically allow both, but a binding that means different things depending on focus is fine for six months and quietly annoying forever.

Per-source direct bindings (Telescope's <leader>+letter model) are a later addition, made nearly free by layer 2: a shortcut can open the palette pre-scoped to a single source. Not in the first pass.

6.4 Desktop implementation

Work against the existing command_palette.rs, which mostly needs its guts replaced:

  1. Replace Vec<Command> with Vec<PaletteSource> — see §6.4.1 for why this is a plain struct rather than a trait object. A source supplies items for one mode and knows how to run one. First sources:
    • AgentSource — from AgentRegistry::get_agents(); action emits the existing agent_sidebar::View::Agent(id). This finally gives the placeholder "Switch" command a real implementation.
    • CommandSource — a static list of app-level actions (zoom, settings, import, quit), each carrying a gpui action to dispatch.
    • NoteSource — notes by title, action opens the note in the Notes agent.
    • DocumentSource — regime B; see §6.6 for the async caveat.
  2. Make run_selected actually dispatch. Today it only emits PaletteEvent::Dismiss. It needs to emit the item's action and dismiss, which means PaletteEvent grows a Navigate(View) variant (or the item carries a boxed gpui action the palette dispatches on the window).
  3. Parse the mode prefix in matches(), and show the active mode as a chip to the left of the input so the user can see which list they are in.
  4. Swap the hand-rolled backdrop for components::modal if that component fits; otherwise leave as-is and note why.
  5. Match highlighting — bold the matched character ranges returned by layer 1. This is most of the perceived quality of a fuzzy finder.
  6. Scrolling / cap. The current list renders every match into a non-scrolling column. Cap displayed results (~50) and make the list overflow_y_scroll — remembering the min_h(px(0.)) rule from CLAUDE.md for every level of the flex chain.
  7. Sizing — all dimensions from sizing::{font, icon, control, layout}. DIALOG_WIDTH already applies.

6.4.1 Why sources are a struct, not dyn or an enum

The instinct to reach for Box<dyn PaletteSource> assumes the source set is open. It is not: AgentId is a closed 15-variant uniffi enum and AgentRegistry::default() is a hardcoded vec![] of AgentMetadata with &'static str fields (rust/lib/src/agents/mod.rs). Agents are compiled in, not registered at runtime.

But source-count is the wrong axis anyway — sources are not 1:1 with agents (CommandSource is not an agent; Documents may want more than one). The deciding question is whether a source owns state.

Default: stateless sources, so plain functions.

pub struct PaletteSource {
    mode: Mode,                                   // prefix: none / `>` / `@`
    label: &'static str,
    items: fn(&CommandPalette, &App) -> Vec<PaletteItem>,
}

A fn pointer, not a closure — no allocation, no vtable, no enum boilerplate, and Vec<PaletteSource> is just data. Whatever a source needs it reaches through &CommandPalette and cx; the palette holds the AgentRegistry the way AgentSidebar already does. Adding a source is one vec![] entry.

Escalate to an enum if a source needs its own state — a cached candidate list, a pending Task, a §6.6 generation counter. Note that most of that state arguably belongs to the palette rather than the source, since it coordinates across sources; a per-source generation counter is really the palette's record of what it last asked. An enum beats dyn on every axis that matters here: exhaustive match makes the compiler find every site when a variant is added, no allocation, and no object-safety constraints on method signatures. The cost is a match arm per method, and there would be roughly three methods.

dyn does not earn its place even under the guest-agent future described in §6.4.2 — see there for why.

An item's action must be data, not a closure. The tempting shape is Box<dyn gpui::Action>, since that is what window.dispatch_action takes. Use an intent enum instead:

pub enum PaletteAction {
    Navigate(AgentId),
    OpenDocument(DocumentID),
    RunCommand(CommandId),
}

The palette translates a PaletteAction into a gpui dispatch at the moment it runs one, so the boxing is confined to that single call site and never appears in PaletteItem. This is the better design on its own merits — loggable, testable without a window, and serializable across the FFI so Android can share one command list rather than re-declaring it — and it is also the one choice here that the §6.4.2 future genuinely depends on.

6.4.2 Guest agents: what this design must not foreclose

A far-future desideratum for Synchronicity is agents written in something other than Rust, executing inside a host-provided VM — the mental model being a browser's JS engine running a page-scoped webapp. This is not near-term, carries a large amount of unrelated planning, and nothing in this document should be built for it. The goal is only to avoid gratuitously foreclosing it.

The good news is that it barely constrains anything here:

  • It does not argue for dyn. A guest cannot hand the host a Rust trait object; its contributions cross a serialization boundary. From the host's side every guest is identical — a single GuestSource { agent: GuestAgentId } that dispatches into the runtime and receives serialized items. That is one variant, not N, so §6.4.1's conclusion is unchanged.
  • It does argue for actions-as-data, per §6.4.1. This is the single load- bearing constraint: a guest can emit a PaletteAction as a message; it can never produce a Rust closure or a gpui type.

Two properties the near-term design already has for unrelated reasons happen to be the ones a guest would need, so they are worth not regressing:

  • §6.6's async sources with per-source pending/wedged state is the shape an untrusted guest requires — the host asks for items, time-bounds the answer, and degrades gracefully when one source misbehaves, rather than letting a source push into the palette.
  • Deriving the source list from AgentRegistry (already the case for AgentSource) rather than hand-listing sources in gui-app means guest- contributed sources would surface in both front-ends without either being touched.

Explicitly not doing now: any trait, serialization layer, VM abstraction, or indirection introduced for guest agents. The bar for anything in this section is that it is independently correct today; all three points above clear it.

6.4.3 PaletteAction as the seed of a general intent vocabulary

The natural generalization of §6.4.1's actions-as-data is an intent system: a serializable vocabulary of user-level "what should happen" defined once in lib, whose interpretation is per-modality — the GUI swaps a pane, Android pushes a NavHost route, the TUI switches a screen, the CLI prints.

There is more existing support for this than is obvious. "Take me to X" is already expressed three mutually incompatible ways:

Modality Today
gui-app agent_sidebar::View { Home, Agent(AgentId) }, a gpui event
Android @Serializable data class AgentRoute(val agentId: String) — MainActivity.kt notes that uniffi enums are not @Serializable, so AgentId is stringified into the route and re-parsed
syn-daemon DaemonCommand, which already includes Search { query }

Android's stringify-and-reparse is a live papercut that an intent type in lib would erase. Fixing it is out of scope here, but it is evidence the idea pays.

Two constraints if this is ever pursued:

  • Do not merge with DaemonCommand. It resembles an intent enum but is an RPC protocol — versioned by commit hash (ADR 0005), with variants carrying query parameters (sort, limit, only_roots). "Perform this operation with these arguments" is not "the user wants this to happen"; merging drags protocol-versioning constraints into UI code and pagination parameters into a user-level vocabulary. Keep them adjacent and distinct.
  • Interpretation must be partial. A modality has to be able to decline an intent — "scan a QR code" has no desktop meaning, "zoom the UI" has no CLI meaning. If every front-end must exhaustively match, stub arms accumulate and adding a GUI-only affordance becomes a five-file change. Design the not-applicable-here answer in from the start.

Process: grow it bottom-up, do not design it top-down. PaletteAction lives in lib and is uniffi-exported from day one, but stays small (navigate to agent, open document, run command). If it later absorbs deep links, guest-agent contributions (§6.4.2), and the triplication above, it earns the name Intent then. Renaming later is trivial; a premature god-enum every front-end must satisfy is not.

6.5 Android implementation

Command palettes are keyboard-first and largely absent from phones. Where they exist (Obsidian mobile), they are demoted from a hotkey to a button and presented as a full-screen modal: input pinned at top, keyboard up immediately, list filling the rest.

  • Presentation: full-screen. Do not port the centered desktop dialog — the soft keyboard takes roughly half the screen, so an overlay is full-screen whether designed that way or not.
  • Entry point: an app-bar search action on the main scaffold, not a hidden gesture. A dedicated PaletteRoute in the root NavHost, consistent with ADR 0008's type-safe @Serializable routes.
  • Priority: lower than the desktop palette and lower than Feature B on Android. The phone gets more value from good in-place filtering than from a command list. Ship it second.

6.6 The async problem to decide before building

Sources divide into synchronous (agent list, static commands) and store-backed (notes, documents). A palette that blocks the UI thread on a SQLite query per keystroke will feel bad, and one that renders results out of order will feel broken.

This is §4.1's invariant applied to the palette, and it falls on the "UI keeping up with my typing" side of the line — so the answer is not a Job per keystroke.

Decide up front: sources return results asynchronously, the palette renders sync sources instantly and fills in async ones as they land, and each async query carries a generation counter so a stale response is dropped rather than overwriting a newer one. Documents' existing debounce-then-query pattern in agents/documents/mod.rs is the reference.

The invariant does bind hard in one place here: the palette must open and accept typing instantly, before any source has produced anything. A source that needs to load its candidate list (every note title, say) cannot block the first frame. Sources therefore need a "not ready yet" state that the palette renders as an unobtrusive pending affordance rather than an empty list — an empty list reads as "no matches", which is a wrong answer, not a slow one.

Because the palette fans out across several sources, §4.1's three states are tracked per source, not per palette: a slow or wedged DocumentSource must not blank out the instant results AgentSource already returned. The palette renders partial results as they land, with the pending/failed indicator scoped to the section it belongs to.

Any palette action that starts something long — an import, a sync, a podcast directory query — dismisses the palette immediately and hands off to a Job per §4.1. The palette never waits for its own commands to finish.

7. Feature B — the shared filter component

7.1 Desktop

A new components::filter_bar (layer 3b) plus a matcher module (layer 1).

// Layer 1 — pure, testable, no gpui.
pub struct Match { pub score: i32, pub ranges: Vec<Range<usize>> }
pub fn fuzzy_match(query: &str, haystack: &str) -> Option<Match>;

// Layer 3b — owns the input, debounce, and match state only.
pub struct FilterBar { input: Entity<TextInput>, /* … */ }
impl FilterBar {
    pub fn query(&self, cx: &App) -> &str;
    /// Rank `items` against the current query. Empty query = identity.
    pub fn apply<'a, T>(&self, items: &'a [T], key: impl Fn(&T) -> &str, cx: &App)
        -> Vec<(&'a T, Option<Match>)>;
}

The agent renders the surviving items itself, using Match::ranges to bold matched characters. FilterBar emits a change event so the agent can re-render or re-query.

Status: FilterBar does not exist yet. The PDF agent's library screen carries its own header search field (a TextInput plus a substring filter in apply_filter), which is what FilterBar should absorb when it lands — it is a caller-in-waiting, not a second design.

The matcher is rust/lib's text_match and fuzzy::rank. Every match a user types follows one per-character rule, stated in text_match's module docs: a plain character finds its accented and cased variants, a marked or uppercase one demands exactly that — Unicode's asymmetric search. text_match::Query is the substring matcher, and its find_all returns the ranges Match::ranges above stands for; fuzzy::rank is the typo-tolerant one, frizbee's scoring run over text_match::folded text.

An earlier version of this section said not to write the matcher by hand and to take nucleo. That stopped holding once matching had to work in every script. No Rust crate does asymmetric matching per character (ICU4C's StringSearch does; ICU4X has no string search), and nucleo folds only Latin accents, decides per query word rather than per character, has no typo tolerance, and has not released since 2024. What is taken from crates is every Unicode fact — ICU4X's decomposition, case folding and general category — and the fuzzy scoring; the hand-written part is the comparison.

Placement convention (this is the part that answers "where do I put the search bar and is it the same everywhere"): top of the content pane, right of the view's title, max width 500px — the rule components/screen_header.rs now holds, as header_search (at SEARCH_MAX_WIDTH, 420) plus the shared header_search_clear. Write it into CLAUDE.md next to the existing tabs/TabRow rule so the question stops recurring.

Adoption order (all regime A unless noted):

  1. Notes — replace the dead NotesSearchBar placeholder. Filters the notebook/note tree in the sidebar. Highest value, and it deletes dead code.
    • Partly done: NotesSearchBar is no longer dead — it emits its query and HierarchicalSidebar::set_filter narrows the tree to the matches and the collections around them, the shape Documents already had. What is still missing is the component: the sidebar calls text_match itself, so FilterBar remains unwritten and this is a caller-in-waiting like the PDF library, not a second design.
  2. Jobs, Humans, Podcast subscriptions — flat lists, trivial adoption, good proof the abstraction generalizes.
  3. Music, Pictures, Comics — grids and library views; confirms the "agent renders, component matches" split survives non-list layouts.
  4. Documents — regime B. Adopts the input chrome and placement only, keeping its SQL substring semantics and pagination. Its type/date chips are not left as-is: they are the prototype the general facet mechanism (§10.2) is extracted from, so this step is where facets get designed against a real existing consumer rather than speculatively.

Facets attach to FilterBar alongside the query, and are declared rather than hand-rolled per agent:

// A closed, enumerable set of choices over one field — not an expression tree.
pub struct Facet { field: FieldId, label: &'static str, choices: Vec<Choice> }

Common facets (date range, document type) live in lib so every agent and front-end shares them; agent-specific ones are registered by their agent. Each facet must be evaluable both as an in-memory predicate and as a SQL fragment, or be explicitly declared regime-specific — see §10.2 for the constraints.

7.2 Android

The Android idiom is Material 3's SearchBar: it sits inline and collapsed in the layout and expands into a full-screen search surface over the same content, then collapses back — exactly what Gmail, Notion, and Slack do. DockedSearchBar is the large-window variant that expands to a dropdown instead.

The Compose BOM is pinned at 2024.09.00 (android/gradle/libs.versions.toml), i.e. Material3 1.3.x — SearchBar exists there on the older query/onQueryChange/active/onActiveChange API, not the newer inputField/expanded one. Write against what is pinned; a BOM bump is out of scope for this work.

  • Wrap it once as a shared SynSearchBar composable so placement, clear button, and empty-state text are uniform, then adopt per agent in the same order as §7.1. NoteSearchBar.kt becomes the first caller and loses its bespoke BasicTextField chrome.
    • Partly done (ui/SearchBar.kt): SynSearchBar exists and Notes and the PDF library both call it — but it is NoteSearchBar.kt's bespoke BasicTextField chrome promoted into ui/, not yet Material 3's SearchBar. Callers get uniform chrome and a shared clear button today, and the expand-to-full-screen swap stays a one-file change here. Each caller filters with the lib's textMatches and highlights with textMatchRanges (ffi::text_match), so Android matches by text_match's rule; nothing fuzzy yet.
  • Fuzzy matching must not be reimplemented in Kotlin. Layer 1 lives in rust/lib and is exposed over uniffi, so both front-ends rank identically. This is the main reason the matcher is specified as pure and platform-free.
  • The persistent bar's expanded state will look much like the ephemeral palette. That is fine. The distinction that matters is what Enter does — the palette dismisses and acts; the filter bar collapses and the filter stays applied.

8. Explicitly out of scope

Deferred, but recorded because they shape whether this design holds up:

  • FTS5 / content search. Note bodies and extracted PDF text are not searchable today. Both features above work on titles and in-memory lists, so neither is blocked — but a palette that implies "find anything I have" and then only matches titles will disappoint. Adding a SQLite FTS5 virtual table (word-aware matching, BM25 ranking, snippet() for excerpts) is the natural follow-on, and it slots in under layer 2 without disturbing layers 1 or 3.
  • A cross-agent search(query, scopes) -> Vec<SearchHit> API in rust/lib. Layer 2's per-agent sources are the desktop-side stand-in. If the palette's source list grows past ~6 sources, promote it into lib so the TUI and Android share it rather than each maintaining a source list.
  • Ensemble-wide search ("which of my nodes has this?"). Retrofitting this into eleven independent per-agent search bars is impossible; retrofitting it into a lib-level searcher is natural. Not needed now — but it is the strongest long-run argument for the layer-2-in-lib promotion above, and a reason not to let per-agent sources calcify.
  • TUI. The TUI has its own /-to-search idiom in documents_screen.rs that already works. It can adopt layer 1 opportunistically; it is not part of this plan.

9. Suggested sequencing

Each step is independently shippable and independently revertible.

  1. Add the fuzzy matcher (layer 1) as a rust/lib module + uniffi export, with tests. No UI change.
  2. Build components::filter_bar and adopt it in Notes on desktop, deleting the NotesSearchBar placeholder. One real consumer proves the API before it has five.
  3. Rework the palette's internals to sources (layer 2), with AgentSource and CommandSource only — synchronous, so the async design in §6.6 is not on the critical path. Ship match highlighting, grouping (§10.1), and scrolling here.
  4. Add the async source machinery + NoteSource/DocumentSource, and usage persistence for the empty-query recency list (§10.4).
  5. Extract facets (§10.2) from Documents' existing type/date chips, and adopt FilterBar there — the regime-B consumer, with a debounce policy per §10.3. Deliberately after steps 2–4 so facets are generalized from a working implementation rather than designed up front.
  6. Android: shared SynSearchBar, adopted in Notes and Documents.
  7. Android: the full-screen palette.
  8. Write the placement convention into CLAUDE.md.

10. Resolved questions

10.1 Current-agent results are prioritized, not scoped

The palette always searches globally — every source stays reachable at all times — but the active agent's results are surfaced first.

Implement this as grouping, not score bias: render labeled sections with the current agent's first, rather than boosting its items inside one flat ranked list. A score bonus produces the case where a clearly better match from another agent sits below a mediocre local one with nothing on screen explaining why; a section header makes the ordering self-explaining. Grouping composes with §6.1's mode prefixes — the prefix selects the mode, grouping orders within it.

Still open: the palette's command language. §6.1's three prefixes are a starting point, not a settled grammar. Deliberately left unresolved — it is the part of the design most likely to change after a week of real use, and it is cheap to change, being pure parsing over a source list that exists regardless.

10.2 Filters generalize into per-agent facets

The Documents type/date chips become a general facet mechanism, not a Documents-specific one: common facets (date range, document type) declared once in lib, agent-specific facets registered by their agent.

This generalizes better than the fuzzy matcher does, and it is worth being clear why: a facet is a predicate over a field, not a text match. The same declaration can therefore be evaluated as an in-memory predicate (regime A) or compiled to a SQL WHERE fragment (regime B) — it crosses the §5.1 boundary that fuzzy matching explicitly cannot.

Two constraints that follow:

  • A facet must be expressible in both backends, or be explicitly declared regime-specific. This is the main thing to check when adding one.
  • Facet values stay enumerable and shallow — a small closed set of choices rendered as chips. The failure mode is drifting into a query-builder DSL with nested boolean expressions; that is a different and much larger feature.

10.3 FilterBar owns the debounce mechanism; the agent sets the policy

FilterBar owns it — there is no benefit to the agent doing so. But it must not be unconditional, for a reason unrelated to ownership: regime A should not debounce at all. Matching a few hundred in-memory items is sub-millisecond, so a debounce there adds perceptible input lag in exchange for nothing, making the common case worse to serve the uncommon one.

So: the constructor takes an Option<Duration>, defaulting to None. Only store-backed views (regime B) pass a value, because the right interval is a property of the query's cost — which the agent knows and the component cannot.

10.4 The palette does not remember its query; it remembers usage

Open with an empty query, but show recency when empty. Do not restore the previous query or mode.

This is where the field converged independently:

App Behavior
Obsidian Palette opens empty with a recently-used commands section on top; quick switcher lists recent files. Never restores the query.
VS Code Same shape — Ctrl-Shift-P opens empty with a "recently used" group, Ctrl-P lists recent editors. Deliberately does not restore.
Telescope Opens fresh; :Telescope resume restores the last picker as a separate, explicitly invoked command.
Launcher-class tools (Alfred et al.) Expose query retention as a preference — but these carry hundreds of preferences.

The reframe that settles it: the memory a user actually wants is not "my last query", it is "the things I use". A restored stale query is mostly an annoyance, since it must be cleared before typing anything new. Persisting usage — recent and frequent items surfaced when the query is empty — delivers the benefit without the cost.

If resume is wanted later, add it Telescope's way: a separate binding, not a mode, and not a setting. Deliberately not a global settings option — a preference here is a way of not deciding, and this question has a strong default. The settings infrastructure exists if that turns out to be wrong.