Skip to content

fix(file-explorer): sort numbered file names naturally across every listing surface - #11576

Merged
brennanb2025 merged 7 commits into
mainfrom
brennanb2025/sta-2950-file-explorer-natural-sort
Aug 6, 2026
Merged

brennanb2025 merged 7 commits into
mainfrom
brennanb2025/sta-2950-file-explorer-natural-sort

Conversation

@brennanb2025

Copy link
Copy Markdown
Contributor

Summary

Fixes #11426 (Linear STA-2950). The File Explorer sorted names lexicographically, so numbered files listed 100, 200 before 99. Every directory-listing funnel now sorts directories-first in natural (numeric-aware) name order via one shared comparator: local fs:readDir, the SSH short-circuits (re-sorted locally so an older remote relay can't leak lexicographic order), the relay's own handler, the remote-runtime RPC / paired-web routes (re-sorted at the renderer choke point), the SSH folder browser and runtime server dir pickers, the name-filtered view, Source Control directory nodes, and the mobile file explorer.

ELI5: computers sort text character-by-character, so "100" comes before "99" (because "1" < "9") — like shelving "Chapter 100" before "Chapter 99". This teaches Orca's file lists to read whole numbers inside names the way Finder and Explorer do, so 9, 99, 100 shelve in the order you'd expect.

Live before/after (real dev app, right-sidebar File Explorer):

Before — lexicographic (1, 100, 2, 200, 409, 41, 410, 9, 99):

sta-2950-before-lexicographic.png

After — natural (1, 2, 9, 41, 99, 100, 200, 409, 410), re-verified on the final build:

sta-2950-after-natural-final.png

Screenshots

See before/after above.

Testing

  • pnpm lint
  • pnpm typecheck
  • pnpm test — targeted instead: affected desktop suites (182 files / 1699 passed, incl. new ordering tests at the relay, SSH fs:readDir handler branch, renderer choke point, source-control tree, shared helper) plus mobile/src/files/file-tree.test.ts (8 passed, mobile vitest config). A reviewer's broader sweep of src/main+relay+shared hit only two known local-environment artifacts (GIT_CONFIG env leak; load-dependent timeout), both green when re-run isolated.
  • pnpm build — left to CI.
  • Added or updated high-quality tests that would catch regressions: ordering pinned at every funnel that previously sorted independently, including a handler-level SSH-branch test and a choke-point test that feeds a deliberately out-of-order backend payload.

AI Review Report

Adversarial review loop: 4 rounds with a fresh reviewer each round; round 4 came back clean (zero blocker/major).

  • Round 1 (1 blocker, 1 major, 3 minor): both readDir funnels short-circuited to the SSH filesystem provider before the patched sort, and the relay still compared lexicographically — fixed by re-sorting locally after the provider returns plus fixing the relay; added the code-unit tie-break (numeric collation ties 2 vs 02, which would otherwise fall back to readdir order); pinned the collator locale to 'en' so every host produces one order; patched the SSH folder browser and runtime dir pickers that would have disagreed with the Explorer.
  • Round 2 (1 major, 2 minor): the mobile file explorer re-sorted host results with bare localeCompare, undoing the host's order — fixed with the shared comparator + mobile test.
  • Round 3 (2 major, 2 minor): remote-runtime RPC and paired-web routes returned the host's order verbatim — fixed at the renderer choke point every desktop route converges on; added the missing call-site tests; routed Source Control path compares through the tie-breaking comparator.
  • Round 4: clean. Its minor notes (dead export, locale-pinned test oracle) are applied.

Cross-platform: explicitly reviewed for macOS/Linux/Windows — the comparator is pure JS with no path-separator or shell assumptions; verified / terminates ICU numeric runs so digits never merge across path segments; SSH, WSL (routes through main's patched local readdir), remote-runtime, paired-web, relay version-skew (older remote sends lexicographic order → local re-sort corrects it), and mobile (Hermes ships Intl on RN 0.83 for both platforms; Metro already watches src/shared) were each traced. Performance review (perf skill): pass-with-notes — numeric collation costs ~5x bare localeCompare (~5ms extra on a 10,000-entry directory; invisible at realistic sizes), the hoisted collator avoids a 68x naive form, re-sorting an already-sorted SSH response is near-free (V8 adaptive sort, n−1 comparisons), and one collator instance was deduped.

Security Audit

No input handling, command execution, auth, secrets, or dependency changes. The comparator is pure string comparison; no user input reaches Intl.Collator options. IPC surface unchanged (same handlers, same payload shapes — only result ordering). The relay change affects ordering only, not path resolution or authorization; resolveAuthorizedPath checks are untouched and still precede every local readdir.

Notes

  • Trade-offs: (1) Source Control changed-files ordering becomes locale-independent ('en'-pinned) — for locales whose collation differs from English (sv/cs/da) the list can reorder relative to the old OS-locale behavior; accepted for cross-host consistency and repo precedent (skill-freshness pins 'en'). (2) Zero-padded numeric ties (2 vs 02) now order deterministically by code units instead of readdir order.
  • Hermes on-device numeric collation is unverified (tests run under Node/V8); Hermes ships Intl on RN 0.83 and mobile already uses numeric: true collation in three modules, so risk is bounded — a device spot-check of the Files panel with 9/99/100-style names would close it.
  • Follow-up candidates (not this PR): the quick-open file list is still code-unit sorted, so its 20k-result truncation boundary is chosen in a different order than the Explorer displays; CombinedDiffViewer's flat view still sorts by bare localeCompare while its tree view now uses the shared collator; three mobile modules use the slow per-call localeCompare(x, undefined, {numeric:true}) form that the new shared module makes a one-line fix each.

The File Explorer compared names with bare localeCompare, so numbered
files listed 100, 200 before 99. Hoist the numeric collator Source
Control file rows already use (#10850) into src/shared and apply it to
the local and runtime directory listings, the name-filtered view, and
Source Control directory nodes, which were inconsistent with the file
rows one line below (#11426).
Adversarial-review round 1 rework:
- Both readDir funnels short-circuited to the SSH filesystem provider
  before the patched sort, so SSH workspaces kept lexicographic order;
  re-sort locally after the provider returns (the remote relay may be an
  older build), and fix the relay's own comparator for relay-native
  consumers.
- sortDirEntries (shared, unit-tested) owns the directories-first +
  natural-order listing contract used by every funnel.
- compareFileNames breaks numeric-collation ties ('2' vs '02') by code
  units so sibling order stays total instead of readdir order, and pins
  the collator locale to 'en' so every host produces one order.
- The SSH folder browser and runtime server dir picker now match the
  Explorer they browse into.
- Ordering pinned by tests at the relay, source-control tree, and shared
  helper.
Mobile re-sorted host readDir results with bare localeCompare, undoing
the host funnel's natural order (round-2 review). Reuse the shared
comparator and pin the order in the mobile suite.
…ining ties

Round-3 review: the remote-runtime RPC and paired-web routes return the
host's order verbatim, so re-sort in readFileExplorerDirectory where
every desktop route converges; pin the SSH funnel with a handler-level
test; and route Source Control path compares through compareFileNames so
numeric-collation ties share one total order with the Explorer.
Comment thread src/main/ipc/ssh-browse.ts Resolved
Comment thread src/shared/file-name-sort.ts Resolved
@greptile-apps

greptile-apps Bot commented Jul 30, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR centralises all file-explorer sort logic into a new src/shared/file-name-sort.ts module that wraps an Intl.Collator('en', { numeric: true }) singleton, replacing nine independent inline sort comparators that previously used bare localeCompare. Every directory-listing surface now sorts directories-first in numeric-aware natural order.

  • New shared comparator (file-name-sort.ts): hoisted collator avoids per-comparison ICU construction; compareFileNames adds a code-unit tie-break so zero-padded names (2 vs 02) are deterministically ordered; sortDirEntries is the canonical directories-first sort contract used at every call-site.
  • Quick-open heap refactor (quick-open-search.ts): replaces a O(N·K) sorted-insertion scheme with a O(N log K) max-heap; compareRankedResult now breaks score ties by natural path order before falling back to inputIndex.
  • Re-sort at renderer choke-point (file-explorer-directory-listing.ts, runtime-server-directory-browser.ts): remote-runtime and paired-web routes are now re-sorted locally so an older relay cannot leak lexicographic ordering to the UI.

Confidence Score: 5/5

Safe to merge — the change is a well-scoped sort-algorithm replacement with no effect on IPC shapes, auth, or data integrity.

All nine previously independent sort comparators now delegate to a single, well-tested shared module. The max-heap in quick-open-search is correct (total-order comparator, proper sift-up/sift-down, max at root), and the shared Intl.Collator singleton is correctly hoisted. Re-sorting at every funnel closes the version-skew gap for older relays.

Files Needing Attention: No files require special attention. The mobile import path crossing package boundaries warrants a device spot-check on the Files panel, as noted in the PR.

Important Files Changed

Filename Overview
src/shared/file-name-sort.ts New shared module: hoisted Intl.Collator singleton, compareFileNames with code-unit tie-break, sortDirEntries with directories-first contract. Well-commented, tested, and correctly structured.
src/renderer/src/components/quick-open-search.ts Replaces sorted-insertion with a correct max-heap for O(N log K) top-N selection; compareRankedResult gains natural-path tie-breaker; finalizeResults sorts heap output ascending for best-first display. Implementation is correct.
src/main/ipc/filesystem.ts SSH provider branch now re-sorts via sortDirEntries; local readdir branch replaces inline comparator. Both paths consistently produce directories-first natural order.
src/relay/fs-handler.ts Inline sort replaced by sortDirEntries. Relay now produces natural order; test updated to pin exact numeric ordering.
src/renderer/src/components/right-sidebar/file-explorer-directory-listing.ts Renderer choke-point re-sorts backend results; paired-web and remote-runtime routes now produce consistent order even when the host relay is an older build.
src/renderer/src/components/right-sidebar/source-control-tree.ts Directory name sort upgraded from bare localeCompare to compareFileNames; removes now-unused sourceControlPathCollator import. Tree and flat-list now agree on numeric order.
src/renderer/src/components/right-sidebar/source-control-file-filter.ts Adds filterAndSortSourceControlPathEntries (spread copy + compareFileNames sort); original filterSourceControlPathEntries left intact. Non-mutating by design.
mobile/src/files/file-tree.ts compareDirectoryEntries switches from bare localeCompare to compareFileNames, bringing mobile ordering in line with desktop.
src/renderer/src/runtime/runtime-server-directory-browser.ts browseRuntimeServerDirectory now re-sorts the RPC result before returning, ensuring natural order regardless of host runtime version.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[Directory listing requested] --> B{Route type}
    B -->|Local fs:readDir| C[Node.js readdir]
    B -->|SSH connectionId| D[SSH filesystem provider]
    B -->|Remote-runtime RPC| E[callRuntimeRpc]
    B -->|Relay handler| F[FsHandler readDir]
    B -->|SSH folder browser| G[runBrowseCommand]
    B -->|Mobile file tree| H[flattenDirectoryCache]
    C --> SORT1[sortDirEntries]
    D --> SORT2[sortDirEntries re-sort locally]
    E --> SORT3[sortDirEntries renderer choke-point]
    F --> SORT4[sortDirEntries relay-side]
    G --> SORT5[sortDirEntries in-place]
    H --> SORT6[compareFileNames]
    SORT1 --> OUT[Directories-first natural numeric order]
    SORT2 --> OUT
    SORT3 --> OUT
    SORT4 --> OUT
    SORT5 --> OUT
    SORT6 --> OUT
    subgraph shared [src/shared/file-name-sort.ts]
        SC[fileNameCollator Intl.Collator en+numeric]
        SC --> CF[compareFileNames + code-unit tie-break]
        CF --> SDE[sortDirEntries dirs-first contract]
    end
Loading

Reviews (2): Last reviewed commit: "fix(file-listings): cover remaining natu..." | Re-trigger Greptile

@coderabbitai

coderabbitai Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@brennanb2025, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 34 seconds

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 886ead80-f96c-48e3-b7f3-7eb8851a9537

📥 Commits

Reviewing files that changed from the base of the PR and between b54563e and 197a9ad.

📒 Files selected for processing (9)
  • src/renderer/src/components/quick-open-search.test.ts
  • src/renderer/src/components/quick-open-search.ts
  • src/renderer/src/components/right-sidebar/SourceControl.tsx
  • src/renderer/src/components/right-sidebar/source-control-file-filter.test.ts
  • src/renderer/src/components/right-sidebar/source-control-file-filter.ts
  • src/renderer/src/runtime/runtime-server-directory-browser.test.ts
  • src/renderer/src/runtime/runtime-server-directory-browser.ts
  • src/shared/quick-open-directory-reader.test.ts
  • src/shared/quick-open-directory-reader.ts
📝 Walkthrough

Walkthrough

Adds shared natural filename comparison with deterministic tie-breaking and directory-first sorting. The helper is applied to local and remote filesystem listings, SSH browsing, runtime directory reads, mobile file trees, renderer explorer projections, and source-control trees and status entries. Tests cover numeric filename ordering, embedded numeric segments, directory grouping, remote filesystem responses, explorer listings, and source-control tree flattening.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the main change: natural sorting of numbered file names across file-explorer listings.
Description check ✅ Passed The description includes the required sections, screenshots, testing, AI review, security audit, and notes, and is mostly complete.
Linked Issues check ✅ Passed The PR addresses #11426 by switching file-list sorting to a shared numeric-aware comparator across the File Explorer and related listing surfaces.
Out of Scope Changes check ✅ Passed No unrelated changes stand out; the added helper, tests, and broadened sorting coverage all support the stated file-list ordering fix.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai 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.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 6b460ae3-1360-4d39-82d6-1e4def10c6ec

📥 Commits

Reviewing files that changed from the base of the PR and between ab665a3 and b54563e.

📒 Files selected for processing (18)
  • mobile/src/files/file-tree.test.ts
  • mobile/src/files/file-tree.ts
  • src/main/ipc/filesystem.test.ts
  • src/main/ipc/filesystem.ts
  • src/main/ipc/ssh-browse.ts
  • src/main/runtime/orca-runtime-files.ts
  • src/main/runtime/orca-runtime.ts
  • src/relay/fs-handler.test.ts
  • src/relay/fs-handler.ts
  • src/renderer/src/components/right-sidebar/file-explorer-directory-listing.test.ts
  • src/renderer/src/components/right-sidebar/file-explorer-directory-listing.ts
  • src/renderer/src/components/right-sidebar/file-explorer-name-filter-projection.ts
  • src/renderer/src/components/right-sidebar/source-control-status-sort.test.ts
  • src/renderer/src/components/right-sidebar/source-control-status-sort.ts
  • src/renderer/src/components/right-sidebar/source-control-tree.test.ts
  • src/renderer/src/components/right-sidebar/source-control-tree.ts
  • src/shared/file-name-sort.test.ts
  • src/shared/file-name-sort.ts

Comment on lines +7 to +10
vi.mock('./file-explorer-operation-owner', () => ({
getFileExplorerOperationOwner: () => ({ kind: 'local' }),
getFileExplorerOperationRoute: () => ({ settings: null, connectionId: null }),
getFileExplorerOwnerUnresolvedMessage: () => 'unresolved'

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Make the route mock match the test’s stated coverage.

The mocks always return { kind: 'local' }, so this test never exercises the remote-runtime or paired-web routes named on Line 16. Parameterize the route mock for those owners, or rename the test to avoid implying coverage it does not provide.

Also applies to: 16-16

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Mandatory merge-blocker recovery is complete at final HEAD 197a9ad84d8e8f83ba7f2121a4a8edf593d2aed5 (fast-forward pushed as 197a9ad84d). The first fresh same-model/xhigh review found material Quick Open and remote-runtime picker gaps; those plus the flat Source Control omission were fixed, the next fresh review returned CLEAN, and a final fresh gpt-5.6-sol/xhigh reviewer explicitly returned CLEAN for this exact committed HEAD across local, SSH/relay/version-skew, remote-runtime, folder workspaces, Source Control, Quick Open, and mobile.

Validation:

  • Tests/build: 196 focused desktop tests passed (1 skipped), 8 mobile file-tree tests passed, node/web/mobile typechecks passed, relay artifacts built, changed-code quality and max-lines ratchet passed, and git diff --check passed.
  • Perf: bounded Quick Open heap measured about 31 ms at the real 20,001-path cap and 153–156 ms at synthetic 100k, versus about 557 ms for the prior full sort.
  • Electron: isolated final-branch instance identity verified; visible local folder-workspace File Explorer + Quick Open and real SSH File Explorer + Quick Open + flat Source Control + remote folder picker all rendered 9, 99, 100 naturally. Renderer console: 0 errors.
  • SSH: Ubuntu 22.04 ARM64 throwaway Docker target, real demo-project cloned from a local bundle after GitHub auth blocked the preferred clone, relay built/deployed/handshook, and remote backing checks showed only the intentional numbered-fixture commit with no extra test branches/worktrees/folders.
  • Mobile: iPhone 17e loaded the exact branch Metro bundle without redbox, paired through the normal LAN flow to the isolated desktop, desktop backing state confirmed one connected device, and the real mobile Files surface visibly rendered folders 9, 99, 100 followed by files 9, 99, 100.
  • CI: final head has 42 successful checks and one expected path-gated E2E skip; the sole first-attempt failure was the out-of-diff terminal-fit-restore.test.ts 1 ms timing assertion (14999 vs 15000), which passed locally 9/9 and passed on the one bounded failed-job rerun. PR mergeability is CLEAN.

Evidence (uploaded without committing):

  • SSH File Explorer: SSH File Explorer
  • SSH Quick Open: SSH Quick Open
  • SSH Source Control: SSH Source Control
  • SSH remote picker: SSH remote picker
  • Local folder File Explorer: Local folder File Explorer
  • Local folder Quick Open: Local folder Quick Open
  • iOS Files: iOS Files

Cleanup completed for the isolated Electron profile/process, mobile credential/device/helper/Metro, SSH target/container/relay/temp keys, and local fixtures. No approval, merge, auto-merge, issue close, force-push, or check-bypass action was taken; the PR remains open and auto-merge remains unset.

@brennanb2025
brennanb2025 merged commit 6df8997 into main Aug 6, 2026
82 of 84 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…isting surface (stablyai#11576)

* fix(file-explorer): sort numbered file names naturally

The File Explorer compared names with bare localeCompare, so numbered
files listed 100, 200 before 99. Hoist the numeric collator Source
Control file rows already use (stablyai#10850) into src/shared and apply it to
the local and runtime directory listings, the name-filtered view, and
Source Control directory nodes, which were inconsistent with the file
rows one line below (stablyai#11426).

* fix(file-explorer): natural sort on SSH funnels, relay, and pickers

Adversarial-review round 1 rework:
- Both readDir funnels short-circuited to the SSH filesystem provider
  before the patched sort, so SSH workspaces kept lexicographic order;
  re-sort locally after the provider returns (the remote relay may be an
  older build), and fix the relay's own comparator for relay-native
  consumers.
- sortDirEntries (shared, unit-tested) owns the directories-first +
  natural-order listing contract used by every funnel.
- compareFileNames breaks numeric-collation ties ('2' vs '02') by code
  units so sibling order stays total instead of readdir order, and pins
  the collator locale to 'en' so every host produces one order.
- The SSH folder browser and runtime server dir picker now match the
  Explorer they browse into.
- Ordering pinned by tests at the relay, source-control tree, and shared
  helper.

* fix(mobile): natural sort in the mobile file explorer

Mobile re-sorted host readDir results with bare localeCompare, undoing
the host funnel's natural order (round-2 review). Reuse the shared
comparator and pin the order in the mobile suite.

* fix(file-explorer): natural sort at the renderer choke point and remaining ties

Round-3 review: the remote-runtime RPC and paired-web routes return the
host's order verbatim, so re-sort in readFileExplorerDirectory where
every desktop route converges; pin the SSH funnel with a handler-level
test; and route Source Control path compares through compareFileNames so
numeric-collation ties share one total order with the Explorer.

* docs(file-name-sort): state the real perf baseline in the hoist comment

* refactor(source-control): drop the dead collator export; pin the test oracle locale

* fix(file-listings): cover remaining natural-sort surfaces
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.

[Bug]: File Explorer sorts names lexicographically — numbered files list 100, 200 before 1, 2, 3

1 participant