Skip to content

feat(tui): find in session - #64870

Open
neriousy wants to merge 6 commits into
devfrom
session-search
Open

neriousy wants to merge 6 commits into
devfrom
session-search

Conversation

@neriousy

@neriousy neriousy commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

Issue for this PR

Closes #4714

Type of change

  • Bug fix
  • New feature
  • Refactor / code improvement
  • Documentation

What does this PR do?

adds find in session to the tui. it works like the desktop app's find bar:

  • open with <leader>f (also super+f) or /find. a one-line bar shows up above the prompt
  • plain, case-insensitive text, incremental. a counter shows 3/12, or 0/0 when nothing matches
  • enter/↓ next, shift+enter/↑ previous (wraps around), esc closes and clears the highlights
  • searches prompts and assistant text in the loaded messages. no reasoning, tool output or older history. same as desktop
  • a new query jumps to the first match. the current match is scrolled to the middle of the view
  • the current match uses a solid color, other matches a softer one

how it works:

  • matches are counted on the message source (find.ts), so the counter also covers rows that aren't mounted yet. a jump mounts every row first (ensureAllRows), like timeline jumps do
  • markdown is highlighted in the chunk callback that session links already use: each block maps the matches inside its own source onto its rendered chunks through OpenTUI's per-chunk source ranges. concealed markers like ** are handled, and fenced code blocks get the callback too. tables are counted but not painted for now
  • user prompts are split into spans
  • once the block with the current match renders, it reports its offset, and offsetRow turns that into the exact wrapped row to scroll to
  • the bar pushes a find keymap mode only while its field has focus, so the prompt keeps enter/esc/arrows if you click back into it
  • new find theme token (find.background.match, find.background.current, find.text.current). it's optional and falls back to background.raised.max and the focused primary action colors, so existing themes need no changes
  • session links now match blocks by what they rendered instead of by callback identity, since find wraps their callback

behind the session-find tui experiment (experimental: { "session-find": true } or the Experiments dialog)

How did you verify your code works?

  • test/session-find.test.tsx: unit tests for matching, concealed markdown mapping, chunk painting and wrapped rows, plus an app test that opens find with <leader>f, types, checks the highlights in a prompt, bold markdown and a code block, moves with enter/↑ (wrapping to 4/4) and closes with esc. passes 10/10 with --rerun-each 10, and fails fast if highlighting is turned off
  • full tui suite passes, bun run check passes
  • drove it by hand with termctrl against real sessions at 120 and 60 cols: case-insensitive matches, matches inside **bold**, /find, 0/0, wrap-around, esc clearing everything and focus going back to the prompt

Screenshots / recordings

no screenshots yet. the ones I took show private session content, I'll add ones from a fixture session

Checklist

  • I have tested my changes locally
  • I have not included unrelated changes in this PR

Added by the opencode bot (AI-generated).

Public API: adds the session.find keybind, the experimental session-find key and an optional find theme token group (backwards compatible)

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Works as described. With the session-find experiment on, I drove the TUI with the simulated model: /find opens the bar, the counter goes 1/4 → 2/4, and matches are highlighted in the prompt, bold markdown, plain text and a fenced code block. The base has none of this. test/session-find.test.tsx and the group-view test pass (10/10), and tsc passes for packages/tui and packages/theme.

Public API: all additions, backwards compatible. They are the session.find keybind (<leader>f,super+f), the experimental["session-find"] config key, an optional find theme token group (find.text.current, find.background.match, find.background.current, falling back to existing tokens), and ResolvedThemeTokens.find. Existing themes and configs keep working.

Two things are worth fixing, both inline. First, the markdown chunk-callback override runs even when the experiment is off. Second, paint walks the whole markdown tree before checking whether a search is active.

Before

After


function paint(block: CodeRenderable, chunks: TextChunk[], context: ChunkRenderContext) {
const pattern = ctx.find.pattern()
const start = markdown && sourceStart(markdown, part().text, block)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sourceStart walks the whole markdown tree and runs indexOf per block before the !pattern check. So every chunk callback of every prose block pays for it, even with find closed or the experiment off. While a long reply streams, that is roughly quadratic in the number of blocks. Returning early on !pattern before computing start avoids it.

// oxlint-disable-next-line no-restricted-globals -- OpenTUI has no public option for the markdown chunk callback.
links = Reflect.get(renderable, "_linkifyMarkdownChunks")
// oxlint-disable-next-line no-restricted-globals -- OpenTUI has no public option for the markdown chunk callback.
Reflect.set(renderable, "_linkifyMarkdownChunks", prose)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This replaces OpenTUI's private _linkifyMarkdownChunks on every assistant text part, whatever the session-find setting; only the command checks it. Per packages/tui/AGENTS.md, experiment behavior should be gated by its config key. Could this ref (and FindText) be a no-op unless the experiment is on? Then users who haven't opted in never run code that depends on the private field.

@neriousy

Copy link
Copy Markdown
Member Author

thanks, fixed both in 91987ac

  • paint now bails before sourceStart: prose returns right after the links callback when there's no query, and paint only walks the tree when the part actually has matches
  • the find ref is only installed when session-find is on. TextPart remounts its markdown when the experiment flips, so already rendered parts pick it up. with it off, no private field is touched
  • FindText doesn't touch OpenTUI internals, with no query it renders the same plain text as before, so I left it as is

the unit (linux) failure was core's video-generation.test.ts timing out (waits for a job to finish and cancels a running one) and then turbo segfaulting, nothing in this PR touches core. new run is going

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both earlier points are addressed. prose/paint now return early when no search is active or the part has no matches, before walking the tree. Find's markdown hook is only installed when session-find is on. The tests and tsc still pass, and find works as before when I drove it (2/4, highlights in the prompt, markdown and the code block). The public API is unchanged since the last review: all additions, backwards compatible. Nothing new to flag.

Before

After

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both earlier points (the early return before the tree walk, and gating the markdown hook on the experiment) were fixed in the previous push. This commit makes find take the prompt's place. I found nothing new worth flagging. The updated test passes, tsc passes, and I drove it with the simulated model: the find field replaces the prompt with a 2/4 counter and the key hints, and highlights still appear in the prompt, the markdown and the code block. The public API is unchanged since the last review: all additions, backwards compatible.

Before

After

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both earlier points are addressed. The private _linkifyMarkdownChunks override is replaced by OpenTUI 0.9's public inlineHook/inlineHookFilter. The hook is installed whatever the experiment setting again, but with no search active it only checks for matches and returns the session links' spans as they are. code/prose return early when the part has no matches.

One new problem in the inline-hook rewrite: prose blocks can mark the wrong match as current (inline). Driving it with the simulated model, a reply with **banana** and then a table cell banana shows both highlighted as the current match at "2 of 5". The tests (16 pass across the find, session-link, reasoning-body and plugin-markdown tests) and tsc pass. The PR's own test misses this because its table cell text doesn't repeat any earlier block.

The public API is unchanged since the last review: all additions, backwards compatible.

Before

After

const linked = links ? links(spans, context) : spans
const matches = findRanges(part().text, ctx.find.pattern())
if (matches.length === 0) return linked
const start = part().text.indexOf(context.source)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

indexOf(context.source) returns the first copy of the block's source anywhere in the part. A table cell or short paragraph whose text also appears earlier gets numbered from the wrong place. With The **banana** is yellow… followed by a table cell banana, the cell resolves to the first paragraph's offset. At "2 of 5" both the paragraph match and the cell are painted as current (see the screenshot). Searching from the end of the previous block, as sourceStart does for code, or using a source offset from OpenTUI if the hook context has one, would fix it. Relatedly, matching on the linked text rather than the source means a session link label (or an ID it hides) can shift first + index the same way.

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The doubled current highlight is fixed: with a table cell that repeats earlier text, only one match is painted as current now. I checked by driving it with the simulated model (**banana**, then a table cell banana, then a code block, at "2 of 5"), and with a link whose URL contains the query. The updated find test and tsc pass. The earlier points were already addressed. The public API is unchanged since the last review: all additions, backwards compatible. Nothing new to flag.

Before

After

@levontumanyan

Copy link
Copy Markdown

Thanks for working on this — really nice, clean implementation! I tested it both with an agent (full packages/tui + packages/theme suites, typecheck, and automated fixture probes) and manually against real sessions. Everything in the test suite passes and core flows (/find, <leader>f, draft preservation, wrap-around, narrow terminals, blockquotes/lists/tables) work great.

Here are 2 bugs and 5 smaller code/efficiency findings from testing, with repros, suggested fixes, and criticality/usefulness ratings:

Bugs

1. Code fence language tags cause off-by-one / ghost matches

  • Criticality: 7/10 · Usefulness to patch: 9/10
  • Why: findMatches() in find.ts counts occurrences on raw markdown part.text (which includes fence headers like ```typescript / ```jsonc), while shown() in find-view.tsx indexes matches against CodeRenderable.content (which excludes the fence header).
  • Repro:
    1. Have an assistant message containing:
      ```typescript
      const x = 1
      ```
      
      We use typescript here.
    2. Open Find and search typescript (also reproduces on real sessions searching jsonc, bash, ts, etc. whenever a fenced block uses that language).
    3. Counter shows Find · 1 of 2. On 1 of 2, We use typescript here. is highlighted as current (shifted by 1); pressing Enter to 2 of 2 clears the current highlight, leaving nothing highlighted.
  • Suggested fix: Count matches in find.ts against visible/rendered text rather than raw markdown (e.g., extracting visible text from marked tokens — skipping fence info strings and markdown delimiters — so findMatches() and shown() stay 1:1).

2. Concealed markdown syntax causes counter/highlight mismatches

  • Criticality: 5/10 · Usefulness to patch: 7/10
  • Why: Same raw-source vs. rendered-text mismatch as feat: compact and other improvements #1.
  • Repro:
    1. On a message containing Look at **foo**bar here. (or any **bold** text):
    2. Searching ** reports matches (e.g., 1 of 2) with nothing highlighted on screen.
    3. Searching foobar reports No matches even though foobar is visibly rendered.
  • Suggested fix: Resolved automatically by the same visible-text extraction suggested in feat: compact and other improvements #1.

Code & Efficiency Findings

1. Quadratic .reduce() array copies in displayRanges() and shown()

  • Criticality: 3/10 · Usefulness to patch: 8/10
  • Detail: Prefix sums use reduce((result, x) => [...result, ...], [0]), which is $O(N^2)$ on syntax-highlighted code blocks with many chunks.
  • Suggested fix: Use a running let offset = 0 with .map() for an $O(N)$ single pass.

2. Repeated shown(pattern) scans per CodeRenderable

  • Criticality: 4/10 · Usefulness to patch: 7/10
  • Detail: code() in find-view.tsx calls shown(pattern) (scanning every block and table cell in the part) once per CodeRenderable, making parts with multiple code blocks $O(\text{blocks}^2)$ per keystroke/step.
  • Suggested fix: Compute shown(pattern) once per refresh pass (or memoize by (pattern, markdown.blocks)) and share the offsets across code blocks in the part.

3. Table matches in long messages scroll to the part top instead of the table

  • Criticality: 4/10 · Usefulness to patch: 7/10
  • Detail: markCurrent() only calls ctx.find.located(...) for TextRenderable, falling back to anchor.node.y (top of the part) for TextTableRenderable. A table far down in a long message won't scroll into view.
  • Suggested fix: Allow ctx.find.located to accept a Renderable (using offsetRow for TextBufferRenderable and node.y directly for TextTableRenderable).

4. Newly streamed fenced code blocks aren't highlighted while Find is open

  • Criticality: 4/10 · Usefulness to patch: 6/10
  • Detail: useFindHighlight's effect tracks [ctx.find.pattern, current] but not part().text, so if a streaming assistant message appends a new code block while Find is open, refresh(markdown) won't attach onChunks = code until the query or current match changes.
  • Suggested fix: Include part().text (gated on ctx.find.pattern()) in the effect dependencies so refresh(markdown) picks up newly mounted CodeRenderables.

5. No keystroke debounce on very long sessions

  • Criticality: 3/10 · Usefulness to patch: 5/10
  • Detail: Every keystroke (including 1-char queries like a/e) synchronously scans all loaded rows and triggers rerunInlineHook on every matching markdown part.
  • Suggested fix: Keep input state immediate, and lightly debounce updating findActivePattern (~50–80ms) for large sessions or short queries.

@levontumanyan

Copy link
Copy Markdown

One quick follow-up question on searchable message types in findParts:

Right now Find searches user prompts and assistant text (matching desktop), and skips shell (!) messages and compaction summaries.

  • Skipping shell command output makes sense to me (similar to skipping tool output to avoid noise).
  • What do you think about including compaction summaries? In long compacted sessions they seem like a nice thing to find, unless you feel strongly about keeping parity with desktop and leaving them out.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FEATURE]: TUI - Search for and find string in session buffer

2 participants