Skip to content

perf(tui): cache and speed up @ file-reference completion - #808

Draft
alejandro-ao wants to merge 4 commits into
mainfrom
autocomplete-file-index
Draft

alejandro-ao wants to merge 4 commits into
mainfrom
autocomplete-file-index

Conversation

@alejandro-ao

@alejandro-ao alejandro-ao commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

@ file references in the TUI used to re-walk the entire workspace on every prompt text change. This PR makes the walk cheaper, caches it, and finishes the external-path behavior:

  • Replaces the Path.iterdir walk with an os.scandir walker that tracks relative paths as strings and detects symlink cycles per traversal branch.
  • Adds FileReferenceIndex, a stale-while-revalidate snapshot per workspace. The first request builds synchronously; later keystrokes filter cached entries and rebuild in a daemon thread when the TTL expires or a tool invalidates the index.
  • Passes the snapshot into build_completion_state lazily, so only an active workspace @ reference resolves it.
  • Adds home-relative completion for @~ and @~/..., normalizes home prefixes before parent-path handling, and escapes spaces so completion can descend into directories such as @~/Application\ Support/.
  • Preserves the selected completion across background refreshes, refreshes initially empty searches when a tool creates a matching file, and keeps the last good snapshot when a scan is incomplete or fails.
  • Preserves substring matching, ignored directories, ordering, the 50-item cap, directory slashes, and external ../ completion.

User experience

Measured on a 100,100-entry synthetic workspace:

Operation Before After
Each keystroke ~1.77 s full walk + filter ~2 ms cached filter
First @ ~1.77 s ~0.096 s one-time walk
Background refresh n/a off the UI thread

Typing @ no longer drops keystrokes or blocks the Textual event loop on large repositories. Background refreshes keep the current selection, failed or partial scans keep the previous suggestions, and zero-result searches update when a tool creates a matching file. Home-relative paths and paths containing spaces now complete and can be navigated further.

Issue

Closes #463.

Note: #473 also changes the file-reference walk (.gitignore filtering). This PR replaces _iter_file_reference_paths with scan_file_reference_entries; #473 will need a small rebase to apply its filtering in the new walker.

Manual validation

  1. Open a large workspace (or generate one with many files) and run tau.
  2. Type a prompt containing @ and keep typing a filename prefix.
  3. Confirm suggestions update smoothly without dropped keystrokes.
  4. Type @~/ and confirm home-relative suggestions appear.
  5. Type @~/Application into a home containing Application Support/ and confirm Tab inserts the escaped path and further completion works inside it.
  6. Type @new before new.py exists, then create the file with a tool; the suggestion should appear without another keystroke.
  7. Run uv run pytest, uv run ruff check ., uv run ruff format --check ., and uv run mypy.

Tests

  • Walker tests cover ordering, ignored directories, symlink loops, alias preservation, root scan errors, incomplete scans, cached-entry filtering, escaped spaced paths, and home-relative normalization.
  • Completion tests cover lazy entry sources, unrelated prompts, home completion, spaced paths, parent/duplicate-slash normalization, and selection preservation.
  • FileReferenceIndex tests cover bootstrap, TTL refresh, forced refresh, invalidation, mid-flight invalidation, incomplete/failed scans, non-blocking stale reads, and close behavior.
  • TUI app tests cover refreshing an initially empty @ search.
  • Full local suite: 2274 passed, 2 skipped.
  • Website checks, build, and tests also pass.

Replace the per-keystroke Path.iterdir walk with an os.scandir walker that
tracks relative paths directly and detects symlink cycles. Add a
FileReferenceIndex that serves the first snapshot synchronously, then keeps
later snapshots current with a TTL and a background refresh callback.

Preserve substring matching, ignored directories, ordering, the 50-item cap,
and external ../ completion. Existing completion tests keep exercising the
pure on-demand walk.
@alejandro-ao

Copy link
Copy Markdown
Collaborator Author

Review findings

Reviewed at 99bde4d42c487a227d3a85c32715ba5ccae296c7. I recommend addressing these before merging:

  1. [P2] Symlink aliases can hide the real directory's completions — autocomplete.py:383–387. The global inode set traverses only one path to a directory. With alias -> src and src/app.py, I reproduced @alias/app returning a match while @src/app returned none. Track ancestor inodes per traversal branch instead, preventing cycles while preserving distinct paths.

  2. [P2] A background refresh resets the selected completion — app.py:7992–8000. Rebuilding the state resets the selection to the first item. I selected @app2.py during a refresh; after it finished, Tab inserted @app1.py. Preserve the selected item when it still exists, and avoid reopening a dismissed picker.

  3. [P2] Unrelated @ text triggers a synchronous workspace scan — app.py:7957. The index is requested before checking the completion context. Shell commands, /model arguments, inactive mentions, and external @../ references therefore trigger an unnecessary first full scan on the UI thread. Request the snapshot lazily only when an active workspace file reference needs it.

  4. [P2] Tool completion does not update an open file search — app.py:6509–6510. Invalidation only marks the cache stale. If a tool creates a file while its @ prefix is already in the prompt, the suggestions stay unchanged without another edit, even after the TTL. Schedule a refresh for an active file search on invalidation.

  5. [P2] Invalidation during a scan can strand stale results — file_index.py:127–131. Requests made while a refresh is running receive stale entries; if the scan is invalidated, the worker then discards its result without retrying or notifying the UI. Schedule a replacement scan or notify the UI to request one, and test this interleaving.

  6. [P3] A failed refresh replaces the last good snapshot with empty results — file_index.py:122–134. A transient workspace access failure can clear populated suggestions and mark the empty snapshot fresh. Preserve the last successful snapshot and retry failures, including root scan errors currently swallowed by the walker.

Validation: uv run --locked pytest passed (2256 passed, 2 Windows/PowerShell skips); targeted completion tests, Ruff, formatting, and mypy passed. Ad-hoc reproductions confirmed the scenarios above.

Address review findings on the file-reference index:

- Track ancestor inodes per traversal branch so symlinked aliases keep their
  own completions while cycles still terminate.
- Preserve the selected completion across background rebuilds and do not
  reopen a closed picker.
- Resolve the cached snapshot lazily so shell paths, /model arguments, and
  external ../ references never trigger a workspace scan.
- Force a background refresh when a tool or terminal command finishes during
  an active workspace file search.
- Retry scans invalidated mid-flight, keep the last good snapshot on refresh
  failure, and propagate root scan errors so failures cannot publish an empty
  snapshot as fresh.
@alejandro-ao

Copy link
Copy Markdown
Collaborator Author

Addressed all six findings in b29b0bb1:

  1. Symlink aliases — the walker now tracks ancestor inodes per traversal branch, so alias/app.py and src/app.py both complete while cycles still terminate. Added a regression test.
  2. Selection reset — background rebuilds preserve the selected item by kind + display, and skip rebuilding when the picker is closed.
  3. Unrelated synchronous scans — file_entries accepts a callable; the TUI passes _completion_file_entries, so shell paths, /model arguments, and external ../ references never resolve the workspace index. Added tests for each case.
  4. Tool completion refresh — tool and terminal-command completion now invalidate and schedule a refresh when an active workspace @ search is in the prompt.
  5. Invalidation during a scan — a scan that sees a newer generation retries with that generation; repeated invalidation releases the refresh slot and notifies the UI. Added a mid-flight invalidation test.
  6. Failed refresh — failed scans keep the last good snapshot, stay stale for a later retry, and the walker now propagates root scan errors instead of publishing an empty snapshot as fresh. Added a regression test.

Local checks: uv run pytest (2266 passed, 2 skipped), Ruff lint/format, and mypy all pass. CI is green on the new commit.

Handle `@~` and `@~/...` in the same external-path completion branch as
`@../...`: expand the home directory, list one directory level, apply the
ignored-directory filter, preserve the `~/` prefix in the display, and cap
results at the existing limit. Home references do not need the workspace
index, so they remain outside the cached snapshot and avoid a workspace scan.
@alejandro-ao

Copy link
Copy Markdown
Collaborator Author

Follow-up review

Reviewed d39157e9cc88fb4c886931881eb70fe2065f84d2. The alias traversal, lazy lookup, selection preservation, and single-invalidation retry fixes work in the cases I tested. The following issues remain:

  1. [P2] Zero-result searches never update after refresh — app.py:8005–8007. The callback treats an empty result set as a dismissed picker. I typed @new before new.py existed; after a tool created the file, the refreshed index contained it but the suggestion remained absent until another keystroke. Track an active search separately from picker dismissal, and cover an initially empty search in a TUI test.

  2. [P2] Partial scan failures can still replace the last good snapshot — autocomplete.py:433–434,448–454. A missing root returns an empty result, and an inaccessible subdirectory is silently skipped; the index publishes either result as fresh. I reproduced losing src/app.py after a temporary permission failure on src/. Preserve affected cached entries or keep the snapshot stale when scans are incomplete.

  3. [P2] Home completion cannot navigate directories containing spaces — autocomplete.py:368–375. Tab inserts @~/Application Support/ unquoted; subsequent typing is treated as a separate token, so completion cannot descend into the directory. Support quoted or escaped file-reference tokens, with a test that completes through a spaced directory.

  4. [P3] Some home-relative paths resolve against the wrong directory — autocomplete.py:283–287,310–315. @~/.. is checked relative to the workspace, while @~//usr/bin/py can list /usr/bin but insert a path under $HOME. Normalize and resolve home-relative paths before generic parent-path handling.

The published TUI guide also does not yet document the new @~/ syntax.

Validation: uv run --locked pytest passed (2267 passed, 2 Windows/PowerShell skips); targeted completion and index tests, Ruff, formatting, and mypy passed. Ad-hoc TUI and filesystem reproductions confirmed the issues above.

Address the follow-up review:

- Escape spaces in file-reference displays and teach the tokenizer to treat
  backslash-escaped whitespace as part of the token, so completion can descend
  into directories such as Application Support.
- Normalize home-relative prefixes before generic parent-path handling, collapse
  duplicate slashes and dot segments, and resolve `@~/..` against the home tree
  instead of the workspace.
- Return scan completeness from the walker. Missing roots and unreadable nested
  directories now leave the index stale so the last good snapshot survives.
- Rebuild an active `@` search after a refresh even when it currently has zero
  results, instead of treating an empty result set as a dismissed picker.
- Document `@~/` and escaped spaced paths in the TUI guide.
@alejandro-ao

Copy link
Copy Markdown
Collaborator Author

Addressed all four follow-up findings plus the docs gap in 6cce2bd2:

  1. Zero-result searches — the refresh callback now keys off active_workspace_file_reference instead of the previous result count, so an initially empty @new updates when new.py appears. Added a TUI test.
  2. Partial scans — scan_file_reference_entries returns a completeness flag. Missing roots and unreadable nested directories leave the index stale, preserving the last good snapshot. Added scan and index tests.
  3. Spaced paths — file-reference displays escape spaces, and the tokenizer treats backslash-escaped whitespace as part of the token. @~/Application\ Support/ now completes through the directory; workspace paths behave the same. Added tests.
  4. Home path resolution — ~/ prefixes are normalized before generic .. handling, duplicate slashes and dot segments collapse, @~/.. resolves against the home tree, and @~//usr/bin/py stays under $HOME. Added tests.
  5. Docs — website/content/guides/tui.md now documents @~/ and escaped spaced paths.

Local: uv run pytest (2274 passed, 2 skipped), Ruff lint/format, mypy, and website check/format/build/test all pass. CI is green on the new commit.

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.

File references with @ are slow.

1 participant