Skip to content

Improve cmd j search keyword match - #15170

Merged
AmethystLiang merged 2 commits into
mainfrom
improve-cmd-j-search-keyword-match
Aug 17, 2026
Merged

AmethystLiang merged 2 commits into
mainfrom
improve-cmd-j-search-keyword-match

Conversation

@AmethystLiang

@AmethystLiang AmethystLiang commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 17 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1572 $\color{#cf222e}{\Huge{\mathbf{−}}}$​696 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​876
Prod 35 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​3218 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1130 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​2088

ELI5

What Changed

Why

Linked Issue

Fixes #

Visual Proof

Testing

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

AI Disclosure

Review

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Ensure no issues in: Security, Cross-platoform support (Linux, Windows, Mac), Remote SSH, Mobile, general backwards compatibility, performance

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

Author

  • X / Twitter: @your_handle

Replaces the single-match-per-field scoring with a comprehensive matcher that:
- Validates token coverage across multiple query keywords
- Normalizes Unicode text consistently across all sections
- Classifies matches by quality for cross-section leadership
- Supports evidence-based matching with hidden supporting fields
- Includes typo matching for letter-only words
- Performance-gated against a synthetic corpus of 800+ candidates

Result structure now carries match ranges per field (not per row), quality class, and document rank so sections can compare relative strength. This enables worktree/open-tab/intent section ordering based on match intent rather than hardcoded defaults.
Instead of clearing selection when the deferred query commits,
intelligently select the next available item using the standard
selection logic. Also remove unnecessary array index from React
key generation to prevent spurious re-renders.
@AmethystLiang
AmethystLiang merged commit 2aebcfe into main Aug 17, 2026
46 checks passed
@coderabbitai

coderabbitai Bot commented Aug 17, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The palette now uses shared normalized documents for worktrees, tabs, browser pages, simulator tabs, and Cmd+J results. Matching supports multiple query tokens, Unicode normalization, evidence fields, ranked quality classes, and multiple highlight ranges. Section ordering uses shared document ranks. Worktree creation requires an eligible context and either task-URL intent or explicit user selection. Tests cover matching, ranking, evidence, token limits, normalization, performance, and activation behavior.

Merge Risk: 🟡 Moderate · up to c4790

This PR substantially changes search matching across Cmd+J, board search, tabs, and worktrees. The current behavior can hide valid results, show rows matched only by text users cannot see, make the Create action appear selected while Enter does nothing, and add avoidable work during typing or while search is closed. These correctness and responsiveness issues should be fixed or explicitly accepted before merge.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description contains the template headings but leaves the required explanation, linked issue, visual proof, testing details, and checklist incomplete. Complete the ELI5, What Changed, Why, Linked Issue, Visual Proof, Testing, AI Disclosure, Notes, and checklist sections.
Docstring Coverage ⚠️ Warning Docstring coverage is 22.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main change: improving Cmd+J search keyword matching.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 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: 13

🧹 Nitpick comments (8)
src/renderer/src/lib/workspace-tab-palette-results.ts (1)

80-104: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Consider caching the resolved worktree labels on the entry.

baseResult calls resolveWorktreeDisplayName and resolveWorktreeBranchLabel for every entry on every search call. buildSearchableWorkspaceTabs already resolves the same two values per worktree at build time (lines 185-186 of src/renderer/src/lib/workspace-tab-palette-search.ts). Storing them on SearchableWorkspaceTab removes the repeated basename/branchName work from the keystroke path, and keeps one source for the label used in the document and in the row.

src/renderer/src/lib/browser-palette-search.ts (2)

181-192: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Build the base result after the match check.

Lines 183-184 run for every entry, including entries that the matcher rejects at line 186. baseResult calls resolveWorktreeDisplayName, resolveWorktreeBranchLabel, and formatBrowserPaletteUrl, and browserPaletteSecondaryTexts parses the URL again. Move both calls below the continue so the discarded rows cost only the document match.

♻️ Proposed refactor
   const results: BrowserPaletteSearchResult[] = []
   for (const entry of entries) {
-    const base = baseResult(entry)
-    const secondaryTexts = browserPaletteSecondaryTexts(entry.page)
     const match = matchPaletteTabDocument(entry.document, prepared)
     if (!match) {
       continue
     }
+    const base = baseResult(entry)
+    const secondaryTexts = browserPaletteSecondaryTexts(entry.page)
     results.push({
       ...base,
       secondaryText:
         match.secondary !== null ? secondaryTexts[match.secondary.index] : base.secondaryText,

104-105: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

The comment does not describe the code.

The comment states that the workspace label is conditional. Line 105 passes args.workspace.label ?? '' unconditionally. Restate the reason for the empty-string default, or remove the comment.

src/renderer/src/lib/palette-match/palette-match-core.test.ts (1)

93-99: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Avoid depending on object key order in the assertion.

Object.values(mapNormalizedRange(...)) produces the slice arguments from property enumeration order. The assertion then breaks if mapNormalizedRange ever returns the fields in another order, or adds a field. Read the fields by name instead.

♻️ Proposed refactor
   it('maps supplementary-plane characters back correctly', () => {
     const text = normalizePaletteText('🚀 Launch')
     const index = text.normalized.indexOf('launch')
-    expect(text.original.slice(...Object.values(mapNormalizedRange(text, index, index + 6)))).toBe(
-      'Launch'
-    )
+    const range = mapNormalizedRange(text, index, index + 6)
+    expect(text.original.slice(range.start, range.end)).toBe('Launch')
   })
src/renderer/src/lib/worktree-palette-multi-keyword.test.ts (1)

12-17: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Type extra against the searchWorktrees options parameter.

Record<string, unknown> accepts any key. A misspelled option such as evidencePolicy would then be dropped silently, and the affected test would pass while asserting default behavior. Derive the type from the function signature so the compiler catches this.

♻️ Proposed refactor
-function search(query: string, extra: Record<string, unknown> = {}): PaletteSearchResult[] {
+function search(
+  query: string,
+  extra: Parameters<typeof searchWorktrees>[3] = {}
+): PaletteSearchResult[] {
   return searchWorktrees(CMD_J_FIXTURE_WORKTREES, query, CMD_J_FIXTURE_REPO_MAP, {
     workspacePortsByWorktreeId: CMD_J_FIXTURE_PORTS,
     ...extra
   })
 }
src/renderer/src/lib/workspace-tab-palette-search.test.ts (1)

545-547: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Align paneKey with the record key.

Set paneKey: 'terminal-agent:leaf-a' in makeAgentEntry; the index uses the record key, but the fixture currently contains inconsistent pane identifiers.

src/renderer/src/lib/simulator-palette-search.test.ts (1)

69-83: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Share simulator document construction with the test fixtures.

buildSearchableSimulatorTabs, makeEntry, and the oversized-query fixture duplicate the simulator document mapping. Export a focused builder from simulator-palette-search.ts and use it in all three paths. Pass a separate synthetic tab to the oversized-query fixture so its throwing tab getter remains untouched.

src/renderer/src/lib/worktree-palette-create-action.test.ts (1)

78-102: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add coverage for a create-only result list.

The tests cover an empty selectableItemIds and lists that mix Create with real rows. The uncovered case is the one users hit most: a typed name that matches nothing, where listEntries contains only the Create row. Pin the current contract so the interaction with cmdk auto-selection stays visible.

💚 Proposed test
it('returns no selection when create is the only row and auto-select is off', () => {
  expect(
    getNextWorktreePaletteSelection({
      currentSelectedItemId: '',
      queryChanged: true,
      selectableItemIds: [CREATE_WORKTREE_ITEM_ID],
      showCreateAction: true
    })
  ).toBe('')
})

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 49039c03-4fd2-466b-956f-cd58ff2d41e9

📥 Commits

Reviewing files that changed from the base of the PR and between 0bedeea and c479052.

📒 Files selected for processing (52)
  • src/renderer/src/components/WorktreeJumpPalette.recent-tabs.test.tsx
  • src/renderer/src/components/WorktreeJumpPalette.tsx
  • src/renderer/src/components/cmd-j/palette-project-results.ts
  • src/renderer/src/components/cmd-j/palette-query-tokens.test.ts
  • src/renderer/src/components/cmd-j/palette-query-tokens.ts
  • src/renderer/src/components/cmd-j/palette-results.test.ts
  • src/renderer/src/components/cmd-j/palette-results.ts
  • src/renderer/src/components/sidebar/workspace-kanban-search.ts
  • src/renderer/src/components/tab-bar/open-tab-search.test.ts
  • src/renderer/src/components/tab-bar/open-tab-search.ts
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/lib/browser-palette-page-entries.ts
  • src/renderer/src/lib/browser-palette-search.test.ts
  • src/renderer/src/lib/browser-palette-search.ts
  • src/renderer/src/lib/cmd-j-evaluation-fixture.ts
  • src/renderer/src/lib/cmd-j-match-relevance.test.ts
  • src/renderer/src/lib/cmd-j-match-relevance.ts
  • src/renderer/src/lib/cmd-j-section-leadership.test.ts
  • src/renderer/src/lib/cmd-j-section-leadership.ts
  • src/renderer/src/lib/palette-match/evidence-composer.ts
  • src/renderer/src/lib/palette-match/indexed-field.ts
  • src/renderer/src/lib/palette-match/match-document.ts
  • src/renderer/src/lib/palette-match/match-field.ts
  • src/renderer/src/lib/palette-match/match-quality.ts
  • src/renderer/src/lib/palette-match/normalized-text.ts
  • src/renderer/src/lib/palette-match/palette-document.ts
  • src/renderer/src/lib/palette-match/palette-match-budget.ts
  • src/renderer/src/lib/palette-match/palette-match-core.test.ts
  • src/renderer/src/lib/palette-match/palette-match-performance.test.ts
  • src/renderer/src/lib/palette-match/palette-query.ts
  • src/renderer/src/lib/palette-match/tab-document.ts
  • src/renderer/src/lib/palette-match/tab-match.ts
  • src/renderer/src/lib/palette-match/text-segments.ts
  • src/renderer/src/lib/palette-match/typo-distance.ts
  • src/renderer/src/lib/simulator-palette-search.test.ts
  • src/renderer/src/lib/simulator-palette-search.ts
  • src/renderer/src/lib/workspace-tab-agent-snippet-match.ts
  • src/renderer/src/lib/workspace-tab-palette-activation.test.ts
  • src/renderer/src/lib/workspace-tab-palette-results.ts
  • src/renderer/src/lib/workspace-tab-palette-search.test.ts
  • src/renderer/src/lib/workspace-tab-palette-search.ts
  • src/renderer/src/lib/worktree-palette-create-action.test.ts
  • src/renderer/src/lib/worktree-palette-create-action.ts
  • src/renderer/src/lib/worktree-palette-document.ts
  • src/renderer/src/lib/worktree-palette-evidence.ts
  • src/renderer/src/lib/worktree-palette-multi-keyword.test.ts
  • src/renderer/src/lib/worktree-palette-review-match.test.ts
  • src/renderer/src/lib/worktree-palette-search.test.ts
  • src/renderer/src/lib/worktree-palette-search.ts
  • src/renderer/src/lib/worktree-palette-task-url-match.test.ts
  • src/renderer/src/lib/worktree-palette-task-url-match.ts
  • src/renderer/src/lib/worktree-palette-task-url-result.ts
💤 Files with no reviewable changes (2)
  • src/renderer/src/lib/cmd-j-match-relevance.ts
  • src/renderer/src/lib/cmd-j-match-relevance.test.ts

Included review availability: Your plan includes up to 10 reviews per rolling hour; 7 remain after this review.

Comment on lines +32 to +34
for (const result of searchWorktrees(args.worktrees, args.query, args.repoMap, {
evidencePolicy: 'board'
})) {

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.

🚀 Performance & Scalability | 🟠 Major | ⚡ Quick win

Avoid rebuilding board search documents on every query.

The board search path rebuilds and normalizes a document for every worktree on each query update, even though callers are expected to reuse documents across keystrokes. This makes typing cost scale with the full worktree corpus and duplicates the document work already avoided in Cmd+J. Build board documents once per worktree/repository input set and pass them to searchWorktreeDocuments.

📍 Affects 2 files
  • src/renderer/src/components/sidebar/workspace-kanban-search.ts#L32-L34 (this comment)
  • src/renderer/src/lib/worktree-palette-search.ts#L153-L193

Comment on lines +35 to 37
if (result.matchedFields.length) {
matched.add(result.worktreeId)
}

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Recover the previous allowlist to compare accepted fields.
git log -1 --format=%H -- src/renderer/src/components/sidebar/workspace-kanban-search.ts
git show HEAD~1:src/renderer/src/components/sidebar/workspace-kanban-search.ts 2>/dev/null | rg -n -C6 'BOARD_MATCHED_FIELDS' || echo 'previous revision not available'

# Check whether the kanban card renders the repository name.
fd -t f -e tsx -e ts . src/renderer/src/components/sidebar --exec rg -ln 'Kanban' {} \
  | xargs -r rg -nP -C4 'displayName|repoName|RepoBadge'

Repository: stablyai/orca

Length of output: 29130


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- candidate files ---'
fd -t f -e ts -e tsx . src/renderer/src/components/sidebar | rg 'workspace-kanban|WorkspaceKanban'

printf '%s\n' '--- search implementation outline ---'
ast-grep outline src/renderer/src/components/sidebar/workspace-kanban-search.ts

printf '%s\n' '--- search implementation ---'
cat -n src/renderer/src/components/sidebar/workspace-kanban-search.ts

printf '%s\n' '--- references to search and document builder ---'
rg -n -C5 'matchWorkspaceBoardWorktrees|buildWorktreePaletteDocument|evidencePolicy|matchedFields|BOARD_MATCHED_FIELDS' src/renderer/src/components/sidebar src/renderer/src | head -n 500

printf '%s\n' '--- kanban render symbols ---'
rg -n -C5 'repo|repository|displayName|branch|WorkspaceKanban' src/renderer/src/components/sidebar/WorkspaceKanban*.tsx src/renderer/src/components/sidebar/workspace-kanban*.tsx 2>/dev/null | head -n 500

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- worktree palette document ---'
wc -l src/renderer/src/lib/worktree-palette-document.ts
cat -n src/renderer/src/lib/worktree-palette-document.ts | sed -n '1,180p'

printf '%s\n' '--- worktree palette search ---'
cat -n src/renderer/src/lib/worktree-palette-search.ts | sed -n '1,230p'

printf '%s\n' '--- kanban card ---'
wc -l src/renderer/src/components/sidebar/WorkspaceKanbanCard.tsx
ast-grep outline src/renderer/src/components/sidebar/WorkspaceKanbanCard.tsx
cat -n src/renderer/src/components/sidebar/WorkspaceKanbanCard.tsx | sed -n '1,260p'

printf '%s\n' '--- board search tests ---'
cat -n src/renderer/src/components/sidebar/workspace-kanban-search.test.ts | sed -n '1,125p'

printf '%s\n' '--- focused card display references ---'
rg -n -C3 'repoMap|repo\.|displayName|branch|baseBranch|comment|WorktreeKanban' \
  src/renderer/src/components/sidebar/WorkspaceKanbanCard.tsx \
  src/renderer/src/components/sidebar/WorkspaceKanbanStatusLane.tsx \
  src/renderer/src/components/sidebar/WorkspaceKanbanLaneCardList.tsx \
  src/renderer/src/components/sidebar/WorkspaceKanbanLaneGrid.tsx

Repository: stablyai/orca

Length of output: 31071


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- WorktreeCard candidates ---'
fd -t f -e ts -e tsx . src/renderer/src/components/sidebar | rg '(^|/)WorktreeCard'

printf '%s\n' '--- WorktreeCard display implementation ---'
for f in $(fd -t f -e ts -e tsx . src/renderer/src/components/sidebar | rg '(^|/)WorktreeCard'); do
  echo "--- $f ---"
  wc -l "$f"
  ast-grep outline "$f"
  rg -n -C5 'repo|displayName|branch|host|mode|detailed|comment' "$f" | head -n 300
done

printf '%s\n' '--- allowlist references ---'
rg -n -C5 'BOARD_MATCHED_FIELDS|matchedFields\.length|matchedFields' src/renderer/src | head -n 300

printf '%s\n' '--- file history metadata ---'
git rev-parse --verify HEAD
git rev-parse --verify HEAD^ 2>/dev/null || true
git log --oneline -8 -- src/renderer/src/components/sidebar/workspace-kanban-search.ts
git log --all --oneline -12 -- src/renderer/src/components/sidebar/workspace-kanban-search.ts

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- WorktreeCard.tsx outline and key sections ---'
ast-grep outline src/renderer/src/components/sidebar/WorktreeCard.tsx
wc -l src/renderer/src/components/sidebar/WorktreeCard.tsx
rg -n -C8 'function WorktreeCard|export default|repo\.displayName|displayName|hideRepoBadge|repoBadge|RepoBadge|branch|WorktreeTitleInlineRename|experimentalNewWorktreeCardStyle|flushSurface' \
  src/renderer/src/components/sidebar/WorktreeCard.tsx | head -n 500

printf '%s\n' '--- direct JSX around repository and title rendering ---'
rg -n 'repo|displayName|hideRepoBadge|RepoBadge|WorktreeTitleInlineRename' src/renderer/src/components/sidebar/WorktreeCard.tsx

printf '%s\n' '--- exact file history ---'
git rev-parse --verify HEAD
git rev-parse --verify HEAD^ 2>/dev/null || true
git log --oneline -8 -- src/renderer/src/components/sidebar/workspace-kanban-search.ts || true
git log --all --oneline -12 -- src/renderer/src/components/sidebar/workspace-kanban-search.ts || true
git show HEAD:src/renderer/src/components/sidebar/workspace-kanban-search.ts | sed -n '1,80p'
if git rev-parse --verify HEAD^ >/dev/null 2>&1; then
  git show HEAD^:src/renderer/src/components/sidebar/workspace-kanban-search.ts 2>&1 | sed -n '1,100p'
fi

Repository: stablyai/orca

Length of output: 7204


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- card surface candidates ---'
fd -t f -e ts -e tsx . src/renderer/src/components/sidebar | rg 'worktree-card-(surface|model)|WorktreeCardSurface'

printf '%s\n' '--- card surface repository rendering ---'
for f in $(fd -t f -e ts -e tsx . src/renderer/src/components/sidebar | rg 'worktree-card-(surface|model)|WorktreeCardSurface'); do
  echo "--- $f ---"
  wc -l "$f"
  ast-grep outline "$f"
  rg -n -C6 'repo|displayName|hideRepoBadge|Repo|branch|title|badge' "$f" | head -n 500
done

printf '%s\n' '--- pre-change implementation ---'
git show 95cd71c7ca317aab896260891c08d2fa7911fdb6^:src/renderer/src/components/sidebar/workspace-kanban-search.ts 2>&1 | sed -n '1,100p'

printf '%s\n' '--- changed implementation diff summary ---'
git diff --stat 95cd71c7ca317aab896260891c08d2fa7911fdb6^ 95cd71c7ca317aab896260891c08d2fa7911fdb6 -- src/renderer/src/components/sidebar/workspace-kanban-search.ts
git diff 95cd71c7ca317aab896260891c08d2fa7911fdb6^ 95cd71c7ca317aab8962608911fdb6 -- src/renderer/src/components/sidebar/workspace-kanban-search.ts 2>/dev/null || true

Repository: stablyai/orca

Length of output: 9950


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- parent content definition and imports ---'
rg -n -C8 'WorktreeCardParentContent|parent-card-content|ParentContent' src/renderer/src/components/sidebar src/renderer/src/components | head -n 300

printf '%s\n' '--- card surface imports ---'
sed -n '1,55p' src/renderer/src/components/sidebar/worktree-card-surface.tsx

printf '%s\n' '--- board card property configuration ---'
rg -n -C8 'WorkspaceKanban|worktreeCardProperties|cardProperties|COMPACT_WORKTREE_CARD_PROPERTIES|hideRepoBadge|newCardStyle' \
  src/renderer/src/components/sidebar/WorkspaceKanban*.tsx \
  src/renderer/src/components/sidebar/workspace-kanban*.ts \
  src/renderer/src/components/sidebar/use-workspace-kanban*.ts \
  src/renderer/src/components/sidebar/worktree-card*.ts \
  src/renderer/src/components/sidebar/worktree-card*.tsx 2>/dev/null | head -n 500

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -eu

for f in \
  src/renderer/src/components/sidebar/worktree-card-parent-content.tsx \
  src/renderer/src/components/sidebar/worktree-card-header.tsx \
  src/renderer/src/components/sidebar/worktree-card-meta-row.tsx \
  src/renderer/src/components/sidebar/worktree-card-presentation.tsx
do
  echo "--- $f ---"
  wc -l "$f"
  cat -n "$f" | sed -n '1,260p'
done

printf '%s\n' '--- board card props ---'
cat -n src/renderer/src/components/sidebar/WorkspaceKanbanLaneCardList.tsx | sed -n '80,125p'
cat -n src/renderer/src/components/sidebar/WorkspaceKanbanCard.tsx | sed -n '1,78p'

Repository: stablyai/orca

Length of output: 38674


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- task URL matcher ---'
wc -l src/renderer/src/lib/worktree-palette-task-url-match.ts
ast-grep outline src/renderer/src/lib/worktree-palette-task-url-match.ts
cat -n src/renderer/src/lib/worktree-palette-task-url-match.ts | sed -n '1,260p'

printf '%s\n' '--- task URL tests ---'
rg -n -C10 'matchWorktreePaletteTaskUrl|matchedFields.*(issue|pr)|parseCmdJTaskSourceUrl|github.com/.*/(issues|pull)' \
  src/renderer/src/lib/worktree-palette-task-url-match.test.ts \
  src/renderer/src/lib/worktree-palette-search.test.ts | head -n 500

printf '%s\n' '--- task URL call path ---'
cat -n src/renderer/src/lib/worktree-palette-search.ts | sed -n '145,212p'

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -eu

python3 - <<'PY'
from pathlib import Path
import re

search = Path("src/renderer/src/lib/worktree-palette-search.ts").read_text()
board = Path("src/renderer/src/components/sidebar/workspace-kanban-search.ts").read_text()
old = """'displayName',
  'branch',
  'repo',
  'comment'"""
task_tests = Path("src/renderer/src/lib/worktree-palette-task-url-match.test.ts").read_text()

assert "evidencePolicy: 'board'" in board
assert "if (result.matchedFields.length)" in board

# The task-URL branch returns before document matching and has no evidence-policy guard.
task_branch = re.search(
    r"if \(taskSourceUrl\) \{(?P<body>.*?)\n\s*continue\n\s*\}",
    search,
    re.S,
)
assert task_branch, "task-source URL branch not found"
assert "matchWorktreePaletteTaskUrl" in task_branch.group("body")
assert "evidencePolicy" not in task_branch.group("body")

# The task matcher tests pin palette-only result labels for URL matches.
assert "matchedFields: ['issue']" in task_tests
assert "matchedFields: ['pr']" in task_tests

# Model the exact gate difference for a task URL result.
matched_fields = ["issue"]
old_allowlist = {"displayName", "branch", "repo", "comment"}
old_accepts = bool(set(matched_fields) & old_allowlist)
new_accepts = bool(matched_fields)
assert not old_accepts and new_accepts

print("board policy task-URL bypass: reproduced")
print("task URL result: matchedFields=['issue']")
print("old allowlist accepts: False")
print("new non-empty check accepts: True")
PY

Repository: stablyai/orca

Length of output: 296


Preserve the board field allowlist for task-URL matches.

evidencePolicy: 'board' does not apply to the taskSourceUrl branch. That branch returns matchedFields: ['issue'] or ['pr'], and the new non-empty check admits these palette-only matches. Retain the board allowlist for this path or make task-URL matching honor the board policy. Add a regression test.

Comment on lines 109 to 111
function isNameOnlyMatch(result: EngineResult): boolean {
return result.worktreeRange !== null || result.repoRange !== null
return result.worktreeRanges.length > 0 || result.repoRanges.length > 0
}

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 | 🟠 Major | ⚡ Quick win

isNameOnlyMatch no longer detects "name only" under multi-field matching.

The predicate returns true whenever the worktree or repository field has a range. With the previous single-match-per-row engine, a worktree range implied the row matched on the worktree name alone. The shared matcher now reports ranges for every field a token landed on, so a row that matches the title and the worktree name at the same time carries both range arrays. Line 157 then filters that row out of the omnibox, and a query such as a title word plus a worktree word returns nothing.

Require the visible identity fields to be empty before treating the row as name-only.

🐛 Proposed fix
 function isNameOnlyMatch(result: EngineResult): boolean {
-  return result.worktreeRanges.length > 0 || result.repoRanges.length > 0
+  if (result.titleRanges.length > 0 || result.secondaryRanges.length > 0) {
+    return false
+  }
+  return result.worktreeRanges.length > 0 || result.repoRanges.length > 0
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
function isNameOnlyMatch(result: EngineResult): boolean {
return result.worktreeRange !== null || result.repoRange !== null
return result.worktreeRanges.length > 0 || result.repoRanges.length > 0
}
function isNameOnlyMatch(result: EngineResult): boolean {
if (result.titleRanges.length > 0 || result.secondaryRanges.length > 0) {
return false
}
return result.worktreeRanges.length > 0 || result.repoRanges.length > 0
}

Comment on lines +1089 to 1112
const worktreeDocuments = useMemo(
() =>
searchWorktrees(
sortedWorktrees,
paletteSearchQuery,
repoMap,
prCache,
issueCache,
getWorkspacePortsByWorktreeId(workspacePortScan),
checksReviewByWorktree
// Archived workspaces are never searchable, so normalizing them is waste.
buildWorktreePaletteDocuments(
allWorktrees.filter((worktree) => !worktree.isArchived),
{
repoMap,
prCache,
issueCache,
workspacePortsByWorktreeId: getWorkspacePortsByWorktreeId(workspacePortScan),
checksReviewByWorktree,
hostLabelByWorktreeId
}
),
[
sortedWorktrees,
paletteSearchQuery,
allWorktrees,
repoMap,
prCache,
issueCache,
workspacePortScan,
checksReviewByWorktree
checksReviewByWorktree,
hostLabelByWorktreeId
]
)

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.

🚀 Performance & Scalability | 🟠 Major | ⚡ Quick win

Gate worktreeDocuments on paletteStatusInputsActive.

Every other expensive index in this component skips work while the palette is closed but mounted. browserSortedWorktrees states the rule at Lines 1012-1015, and browserPageEntries, simulatorTabEntries, and workspaceTabEntries all follow it. This memo does not. allWorktrees changes on app-wide worktree mutations, so each change re-normalizes and re-tokenizes the name, branch, repository, comment, and all evidence text for every worktree while the palette is not visible.

Add the same early return.

⚡ Proposed gate matching the existing pattern
+const EMPTY_WORKTREE_DOCUMENTS: ReadonlyMap<string, PaletteDocument> = new Map()
   const worktreeDocuments = useMemo(
     () =>
+      !paletteStatusInputsActive
+        ? EMPTY_WORKTREE_DOCUMENTS
+        : // Archived workspaces are never searchable, so normalizing them is waste.
+          buildWorktreePaletteDocuments(
-      // Archived workspaces are never searchable, so normalizing them is waste.
-      buildWorktreePaletteDocuments(
         allWorktrees.filter((worktree) => !worktree.isArchived),
         {
           repoMap,
           prCache,
           issueCache,
           workspacePortsByWorktreeId: getWorkspacePortsByWorktreeId(workspacePortScan),
           checksReviewByWorktree,
           hostLabelByWorktreeId
         }
       ),
     [
+      paletteStatusInputsActive,
       allWorktrees,
       repoMap,
       prCache,
       issueCache,
       workspacePortScan,
       checksReviewByWorktree,
       hostLabelByWorktreeId
     ]
   )
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const worktreeDocuments = useMemo(
() =>
searchWorktrees(
sortedWorktrees,
paletteSearchQuery,
repoMap,
prCache,
issueCache,
getWorkspacePortsByWorktreeId(workspacePortScan),
checksReviewByWorktree
// Archived workspaces are never searchable, so normalizing them is waste.
buildWorktreePaletteDocuments(
allWorktrees.filter((worktree) => !worktree.isArchived),
{
repoMap,
prCache,
issueCache,
workspacePortsByWorktreeId: getWorkspacePortsByWorktreeId(workspacePortScan),
checksReviewByWorktree,
hostLabelByWorktreeId
}
),
[
sortedWorktrees,
paletteSearchQuery,
allWorktrees,
repoMap,
prCache,
issueCache,
workspacePortScan,
checksReviewByWorktree
checksReviewByWorktree,
hostLabelByWorktreeId
]
)
const worktreeDocuments = useMemo(
() =>
!paletteStatusInputsActive
? EMPTY_WORKTREE_DOCUMENTS
: // Archived workspaces are never searchable, so normalizing them is waste.
buildWorktreePaletteDocuments(
allWorktrees.filter((worktree) => !worktree.isArchived),
{
repoMap,
prCache,
issueCache,
workspacePortsByWorktreeId: getWorkspacePortsByWorktreeId(workspacePortScan),
checksReviewByWorktree,
hostLabelByWorktreeId
}
),
[
paletteStatusInputsActive,
allWorktrees,
repoMap,
prCache,
issueCache,
workspacePortScan,
checksReviewByWorktree,
hostLabelByWorktreeId
]
)

Comment on lines +2646 to +2653
if (
!isWorktreePaletteCreateActivationAllowed({
hasTaskUrlIntent: taskSourceUrl !== null,
selectionMovedByUser: selectionMovedByUserRef.current
})
) {
return
}

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 | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Confirm cmdk auto-selects the first item when the controlled value is empty,
# and check for a test covering Enter on a create-only result list.
fd -t f 'Command.tsx' src/renderer/src/components/ui --exec rg -nP -C5 'value|onValueChange|shouldFilter' {}
rg -nP -C5 'CREATE_WORKTREE_ITEM_ID' --type=ts --type=tsx -g '*.test.*'

Repository: stablyai/orca

Length of output: 183


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- candidate files ---'
fd -t f -i 'Command.tsx|WorktreeJumpPalette.tsx' src/renderer/src
printf '%s\n' '--- Command primitives and selection props ---'
fd -t f 'Command.tsx' src/renderer/src/components/ui --exec sed -n '1,240p' {}
printf '%s\n' '--- palette symbols and handlers ---'
rg -n -C8 'isWorktreePaletteCreateActivationAllowed|getNextWorktreePaletteSelection|handleCreateWorktree|selectionMovedByUser|CREATE_WORKTREE_ITEM_ID|onKeyDown|onSelect' src/renderer/src/components/WorktreeJumpPalette.tsx
printf '%s\n' '--- related tests ---'
rg -n -C6 'CREATE_WORKTREE_ITEM_ID|handleCreateWorktree|selectionMovedByUser|WorktreeJumpPalette' --glob '*.{test,spec}.{ts,tsx,js,jsx}' .

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- command primitive ---'
cat -n src/renderer/src/components/ui/command.tsx | sed -n '1,260p'
printf '%s\n' '--- create-action implementation ---'
fd -t f -i 'worktree-palette-create-action' src/renderer/src --exec sh -c 'cat -n "$1"' sh {}
printf '%s\n' '--- exact create row rendering ---'
sed -n '3060,3110p' src/renderer/src/components/WorktreeJumpPalette.tsx
printf '%s\n' '--- relevant tests only ---'
rg -l 'getNextWorktreePaletteSelection|isWorktreePaletteCreateActivationAllowed|selectionMovedByUser|CREATE_WORKTREE_ITEM_ID' src/renderer/src --glob '*.{test,spec}.{ts,tsx}' |
  while IFS= read -r file; do
    echo "--- $file"
    rg -n -C5 'getNextWorktreePaletteSelection|isWorktreePaletteCreateActivationAllowed|selectionMovedByUser|CREATE_WORKTREE_ITEM_ID' "$file"
  done

Repository: stablyai/orca

Length of output: 35749


🏁 Script executed:

#!/bin/bash
set -e
python3 - <<'PY'
from pathlib import Path
import re

palette = Path("src/renderer/src/components/WorktreeJumpPalette.tsx").read_text()
action = Path("src/renderer/src/lib/worktree-palette-create-action.ts").read_text()

assert "autoSelectCreateAction: taskSourceUrl !== null" in palette
assert "const defaultSelectableId =" in action
assert "selectableItemIds.find((id) => id !== CREATE_WORKTREE_ITEM_ID)" in action
assert "(showCreateAction && autoSelectCreateAction ? CREATE_WORKTREE_ITEM_ID : '')" in action
assert "selectionMovedByUser: selectionMovedByUserRef.current" in palette
assert "onSelect={handleCreateWorktree}" in palette

# Evaluate the relevant pure selection branch for a free-text, create-only list.
show_create = True
auto_select_create = False
selectable_ids = ["__create_worktree__"]
default_id = next((x for x in selectable_ids if x != "__create_worktree__"), None)
fallback_id = default_id or ("__create_worktree__" if show_create and auto_select_create else "")
print({
    "free_text_auto_select_create_action": auto_select_create,
    "create_only_selectable_ids": selectable_ids,
    "controlled_selection_after_query_change": fallback_id,
    "create_activation_with_no_navigation": False,
    "create_row_on_select": True,
})
PY
printf '%s\n' '--- package version ---'
rg -n '"cmdk"|cmdk@' package.json package-lock.json pnpm-lock.yaml yarn.lock 2>/dev/null || true
printf '%s\n' '--- create-row component behavior ---'
rg -n -C12 'function PaletteCreateWorktreeRow|const PaletteCreateWorktreeRow|onSelect' src/renderer/src/components --glob '*.tsx' | head -160

Repository: stablyai/orca

Length of output: 15661


🌐 Web query:

cmdk GitHub source controlled value empty auto-select first item Enter onSelect

💡 Result:

In the cmdk library, the Command component is designed to auto-select the first item by default, which is intended as an accessibility feature [1][2]. There is no official API (such as a selectFirstItem={false} prop) to disable this behavior [1][2]. For developers who need to control or suppress this auto-selection, particularly in controlled modes or dynamic lists, the following strategies are commonly used: 1. Controlled Mode: You can pass a value and onValueChange to the Command component to manage the selection state externally [3][4]. By controlling the value state, you determine exactly which item is selected at any given time [3][5]. When your data changes, you can programmatically update the state to match your desired behavior (e.g., setting it to undefined or the ID of a specific item) [4][6]. 2. Using a "Hidden" Item: A known community workaround involves adding a dummy or "hidden" Command.Item to the list with a unique value [1][2]. If this item is rendered, it will be automatically selected by cmdk because it occupies the first position, effectively preventing the "real" first item from being selected by default [1][2]. 3. Default Value Workaround: If you simply want to prevent the auto-selection without removing it entirely, some users have reported success by setting the value prop to a non-existent value (other than undefined) upon initial load [1][2]. Regarding the Enter key behavior, cmdk is hardcoded to trigger the onSelect handler of the currently selected item when the Enter key is pressed [3][7]. If you need to avoid triggering onSelect when pressing Enter (for example, in a complex form or a nested dialog), the library currently does not provide a configuration prop to disable this behavior [7][8]. As a result, developers typically implement workarounds by intercepting keyboard events at a higher level or by ensuring the Command component is only active when Enter key triggers are desired [8].

Citations:


Allow Enter to create from a create-only result.

When a non-empty free-text query has no real matches, cmdk auto-selects the visible Create row. Enter calls handleCreateWorktree, but the guard rejects it because no navigation key or click set selectionMovedByUserRef. The row appears selected, but Enter silently does nothing. Treat Enter on Create as an explicit gesture, or suppress the visual selection until the user moves to the row. Add a regression test for this path.

Comment on lines +92 to +95
function percentile95(samples: number[]): number {
const sorted = [...samples].sort((a, b) => a - b)
return sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * 0.95))]
}

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

percentile95 returns the maximum for both sample sizes used here.

With 5 samples, Math.floor(5 * 0.95) is 4, which is the last index. With 10 samples, Math.floor(10 * 0.95) is 9, which is again the last index. Both assertions therefore compare the slowest run against a threshold named coldBuildP95Ms / warmMatchP95Ms. A single scheduling stall on a shared CI runner then fails the suite.

Either raise the sample count so a 95th percentile excludes outliers, or assert on the median and rename the helper to match what it computes.

♻️ Proposed change
-function percentile95(samples: number[]): number {
-  const sorted = [...samples].sort((a, b) => a - b)
-  return sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * 0.95))]
-}
+// Sample counts here are too small for a true p95, so assert on the median run.
+function medianMs(samples: number[]): number {
+  const sorted = [...samples].sort((a, b) => a - b)
+  return sorted[Math.floor(sorted.length / 2)]
+}

Comment on lines +85 to +95
for (const secondary of dedupeSecondaryTexts(input.title, input.secondaryTexts)) {
fields.push({
id: paletteTabSecondaryFieldId(secondary.index),
profile: 'path',
text: secondary.text
})
}

for (const [index, alias] of (input.typeAliases ?? []).entries()) {
fields.push({ id: paletteTabAliasFieldId(index), profile: 'exact-alias', text: alias })
}

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 | 🟠 Major | 🏗️ Heavy lift

Do not combine non-rendered secondary or alias alternatives.

matchPaletteDocument can assign separate tokens to different secondary texts or aliases. matchPaletteTabDocument returns only the first matching value of each type, and workspace-tab-palette-results.ts:106-148 renders only that value. A row can then match a query token that the user cannot see in the result.

Require all tokens in an alternative group to use one renderable value, or return and render every contributing value.

Comment on lines +37 to +56
function coverAllTokens(text: string, tokens: readonly PaletteQueryToken[]): MatchRange[] | null {
// Why the cheap path first: this tier runs over long agent text for every row the
// structured matcher rejected, so full folding is reserved for strings that need it.
const lowered = text.toLowerCase()
const folded = lowered.length === text.length ? null : normalizePaletteText(text)
const haystack = folded ? folded.normalized : lowered
const ranges: MatchRange[] = []
for (const token of tokens) {
if (token.isPunctuationOnly) {
return null
}
const index = haystack.indexOf(token.text)
if (index === -1) {
return null
}
const end = index + token.text.length
ranges.push(folded ? mapNormalizedRange(folded, index, end) : { start: index, end })
}
return mergeMatchRanges(ranges)
}

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Inspect palette text normalization and query token production.
fd -t f 'normalized-text.ts' src/renderer/src/lib/palette-match --exec cat -n
fd -t f 'palette-query.ts' src/renderer/src/lib/palette-match --exec cat -n

Repository: stablyai/orca

Length of output: 8426


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- target implementation ---'
cat -n src/renderer/src/lib/workspace-tab-agent-snippet-match.ts | sed -n '1,130p'

printf '%s\n' '--- normalization and matcher references ---'
rg -n -C 3 "normalizePaletteText|coverAllTokens|structured|agent snippet|snippet" src/renderer/src/lib src/renderer/src -g '*.{ts,tsx}' | head -n 400

printf '%s\n' '--- related tests ---'
fd -t f -e ts -e tsx . | rg 'palette|workspace-tab-agent|snippet|normalized-text' | sort

Repository: stablyai/orca

Length of output: 42861


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- indexed-field implementation ---'
cat -n src/renderer/src/lib/palette-match/indexed-field.ts | sed -n '1,190p'

printf '%s\n' '--- matching pipeline ---'
cat -n src/renderer/src/lib/palette-match/match-field.ts | sed -n '1,240p'
cat -n src/renderer/src/lib/palette-match/match-document.ts | sed -n '1,220p'
cat -n src/renderer/src/lib/palette-match/palette-match-core.test.ts | sed -n '1,260p'

printf '%s\n' '--- normalization-focused tests and references ---'
rg -n -C 4 "normalizePaletteText|NFC|whitespace|diacritic|accent|NBSP|\\u00a0|Café|cafe" src/renderer/src/lib src/renderer/src/components -g '*.{ts,tsx}'

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -eu

node - <<'JS'
const ASCII_FAST_PATH = /^[\t\n\v\f\r -~]*$/
const ASCII_CONTROL_SPACE = /[\t\n\v\f\r]/g
const COMBINING_MARK = /\p{M}/u
const UNICODE_SPACE = /\s/u

function isCombiningMark(codePoint) {
  return COMBINING_MARK.test(String.fromCodePoint(codePoint))
}
function foldChunk(chunk) {
  if (UNICODE_SPACE.test(chunk) && chunk.trim() === '') return ' '
  return chunk.normalize('NFC').toLowerCase()
}
function normalizePaletteText(original) {
  if (ASCII_FAST_PATH.test(original)) {
    return { original, normalized: original.toLowerCase().replace(ASCII_CONTROL_SPACE, ' '), starts: null, ends: null }
  }
  let normalized = ''
  let identity = true
  let index = 0
  while (index < original.length) {
    const codePoint = original.codePointAt(index)
    let end = index + (codePoint > 0xffff ? 2 : 1)
    while (end < original.length) {
      const next = original.codePointAt(end)
      if (!isCombiningMark(next)) break
      end += next > 0xffff ? 2 : 1
    }
    const folded = foldChunk(original.slice(index, end))
    if (folded.length !== end - index) identity = false
    normalized += folded
    index = end
  }
  return { original, normalized, changed: !identity }
}
function cheapHaystack(text) {
  const lowered = text.toLowerCase()
  return lowered.length === text.length ? lowered : normalizePaletteText(text).normalized
}
for (const [text, token] of [
  ['Café server', 'cafe'],
  ['Café server', 'café'],
  ['alpha\u00a0beta', 'alpha beta'],
  ['alpha\u2003beta', 'alpha beta'],
  ['e\u0301clair', 'éclair'],
  ['ABC', 'abc'],
]) {
  const normalized = normalizePaletteText(text).normalized
  const cheap = cheapHaystack(text)
  console.log(JSON.stringify({text, token, normalized, cheap, normalizedMatch: normalized.includes(token), cheapMatch: cheap.includes(token), length: [...text].length, codeUnits: text.length}))
}
JS

Repository: stablyai/orca

Length of output: 1054


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- exact structured matching path ---'
cat -n src/renderer/src/lib/palette-match/indexed-field.ts | sed -n '1,175p'
cat -n src/renderer/src/lib/palette-match/match-field.ts | sed -n '1,220p'
cat -n src/renderer/src/lib/palette-match/match-document.ts | sed -n '1,180p'
cat -n src/renderer/src/lib/palette-match/text-segments.ts | sed -n '1,220p'
cat -n src/renderer/src/lib/palette-match/palette-query.ts | sed -n '74,110p'

printf '%s\n' '--- direct tests for normalized text ---'
rg -l "normalizePaletteText|normalized-text" src/renderer/src -g '*.{ts,tsx}' | sort | while read -r file; do
  echo "### $file"
  rg -n -C 5 "normalizePaletteText|normalized-text" "$file"
done

Repository: stablyai/orca

Length of output: 38426


🏁 Script executed:

#!/bin/bash
set -eu

node - <<'JS'
const ASCII_FAST_PATH = /^[\t\n\v\f\r -~]*$/
const ASCII_CONTROL_SPACE = /[\t\n\v\f\r]/g
const COMBINING_MARK = /\p{M}/u
const UNICODE_SPACE = /\s/u

function isCombiningMark(codePoint) {
  return COMBINING_MARK.test(String.fromCodePoint(codePoint))
}
function foldChunk(chunk) {
  if (UNICODE_SPACE.test(chunk) && chunk.trim() === '') return ' '
  return chunk.normalize('NFC').toLowerCase()
}
function normalizePaletteText(original) {
  if (ASCII_FAST_PATH.test(original)) {
    return original.toLowerCase().replace(ASCII_CONTROL_SPACE, ' ')
  }
  let normalized = ''
  let index = 0
  while (index < original.length) {
    const codePoint = original.codePointAt(index)
    let end = index + (codePoint > 0xffff ? 2 : 1)
    while (end < original.length) {
      const next = original.codePointAt(end)
      if (!isCombiningMark(next)) break
      end += next > 0xffff ? 2 : 1
    }
    normalized += foldChunk(original.slice(index, end))
    index = end
  }
  return normalized
}

const diffs = []
for (let cp = 0; cp <= 0x10ffff; cp += 1) {
  if (cp >= 0xd800 && cp <= 0xdfff) continue
  const text = String.fromCodePoint(cp)
  const lowered = text.toLowerCase()
  if (lowered.length !== text.length) continue
  const normalized = normalizePaletteText(text)
  if (normalized !== lowered) {
    diffs.push({
      cp: `U+${cp.toString(16).toUpperCase().padStart(4, '0')}`,
      text,
      lowered,
      normalized,
      lowerLength: lowered.length
    })
    if (diffs.length >= 20) break
  }
}
console.log(JSON.stringify(diffs, null, 2))
JS

Repository: stablyai/orca

Length of output: 2380


Normalize agent snippets before token search. NFC can change text without changing its UTF-16 length. The query token क़ matches क़ in normalized fields, but this path misses it. Use normalizePaletteText(text).normalized and mapNormalizedRange; hoist the query-only punctuation check outside coverAllTokens.

Comment on lines +46 to +53
export const WORKTREE_PALETTE_SELECTION_MOVE_KEYS: ReadonlySet<string> = new Set([
'ArrowDown',
'ArrowUp',
'Home',
'End',
'PageDown',
'PageUp'
])

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check the Command wrapper and any keybinding layer for non-arrow selection movement.
fd -t f 'command.tsx' src/renderer/src/components/ui --exec rg -nP -C6 'ArrowDown|ArrowUp|ctrlKey|metaKey|"n"|"p"|"j"|"k"' {}
rg -nP -C4 'vimBindings|loop:\s*true' --type=tsx

Repository: stablyai/orca

Length of output: 183


🏁 Script executed:

#!/bin/bash
set -u

echo '--- candidate files ---'
fd -t f . src/renderer/src/components/ui src/renderer/src | rg '(^|/)(command\.tsx|worktree-palette-create-action\.ts)$'

echo '--- command wrapper navigation handlers ---'
while IFS= read -r file; do
  echo "### $file"
  rg -n -C8 'ArrowDown|ArrowUp|PageDown|PageUp|Home|End|ctrlKey|metaKey|vim|keybind|onKeyDown|loop' "$file" || true
done < <(fd -t f 'command.tsx' src/renderer/src/components/ui src/renderer/src)

echo '--- renderer keybinding/navigation references ---'
rg -n -C5 'vimBindings|loop:\s*true|Ctrl\+?[npjk]|ctrlKey|metaKey|ArrowDown|ArrowUp|PageDown|PageUp' src/renderer/src -g '*.ts' -g '*.tsx' || true

echo '--- target action and package versions ---'
cat -n src/renderer/src/lib/worktree-palette-create-action.ts | sed -n '1,140p'
rg -n '"(cmdk|`@radix-ui`|shadcn)"|cmdk@|packageManager' package.json pnpm-lock.yaml yarn.lock package-lock.json 2>/dev/null || true

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -u
log=/tmp/coderabbit-shell-logs/shell-output-ALNV0N

echo '--- resolved candidate paths ---'
sed -n '1,40p' "$log"

echo '--- exact command wrapper files ---'
fd -t f -g 'command.tsx' src/renderer/src/components/ui src/renderer/src

echo '--- exact target file ---'
cat -n src/renderer/src/lib/worktree-palette-create-action.ts | sed -n '1,140p'

echo '--- command wrapper source ---'
while IFS= read -r file; do
  echo "### $file"
  cat -n "$file"
done < <(fd -t f -g 'command.tsx' src/renderer/src/components/ui src/renderer/src)

echo '--- focused keybinding declarations and cmdk usage ---'
rg -n -C5 'vimBindings|loop\s*[:=]|onKeyDown|Command(Input|List|Item)?|cmdk|useCommandState' \
  src/renderer/src/lib src/renderer/src/components/ui src/renderer/src/components \
  -g '*.ts' -g '*.tsx' \
  | rg -v '(^|/)[^:]+\.test\.[tj]sx?:|node_modules' \
  | head -n 500

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -u

echo '--- Command wrapper ---'
cat -n src/renderer/src/components/ui/command.tsx | sed -n '1,260p'

echo '--- worktree palette references ---'
rg -n -C6 'WORKTREE_PALETTE_SELECTION_MOVE_KEYS|selectionMovedByUser|isWorktreePaletteCreateActivationAllowed|getNextWorktreePaletteSelection|CREATE_WORKTREE_ITEM_ID' \
  src/renderer/src -g '*.ts' -g '*.tsx' \
  | head -n 500

echo '--- palette-specific keyboard handlers ---'
rg -l 'worktree.*palette|Worktree.*Palette|WORKTREE_PALETTE' src/renderer/src -g '*.ts' -g '*.tsx' \
  | while IFS= read -r file; do
      echo "### $file"
      rg -n -C12 'onKeyDown|onKeyUp|event\.key|key ===|key\.to|selectionMovedByUser|Command' "$file" || true
    done

echo '--- literal alternate navigation bindings in renderer source ---'
rg -n -C4 'Ctrl\+[npjk]|Control\+[npjk]|ctrlKey.*[npj k]|key\s*===\s*['"'"'"'"'"']?[npj k]['"'"'"'"'"']?|key\s*===\s*['"'"'"'"'"'](n|p|j|k)['"'"'"'"'"']' \
  src/renderer/src -g '*.ts' -g '*.tsx' \
  | head -n 300

Repository: stablyai/orca

Length of output: 50370


🌐 Web query:

cmdk GitHub source keyboard navigation Ctrl+n Ctrl+p Ctrl+j Ctrl+k ArrowDown onKeyDown

💡 Result:

The cmdk library includes built-in keyboard navigation support, which is active by default and can be customized via the Command component [1][2]. Keyboard Shortcuts: - Navigation: ArrowDown (next), ArrowUp (previous), Home (first item), End (last item) [1][2]. - Vim-style (enabled by default): Ctrl+N and Ctrl+J move down; Ctrl+P and Ctrl+K move up [1][2]. - Selection: Enter triggers the onSelect action for the selected item [1][2]. - Grouping: Alt+ArrowDown jumps to the first item in the next group, and Alt+ArrowUp jumps to the first in the previous group [1][2]. Customization and onKeyDown: - The Vim-style bindings can be disabled by setting the vimBindings={false} prop on the Command component [2]. - You can override or extend keyboard behavior by using the onKeyDown prop on the Command component [3][4]. Because cmdk handles internal navigation via this same event, calling event.preventDefault within your custom onKeyDown handler will prevent the default cmdk action for that key [3][4]. - If you need to keep default input behavior (like Home/End moving the cursor in the input field) while preventing them from triggering list navigation, you can use event.stopPropagation inside the onKeyDown handler of the Command.Input component [4]. Implementation Note: cmdk does not automatically listen for the global ⌘K toggle shortcut; you must implement that listener yourself in your application to control the context [5][6]. The library internals check for IME composition (isComposing or keyCode 229) to ensure key bindings do not interfere with text input [7].

Citations:


🏁 Script executed:

#!/bin/bash
set -u

echo '--- declared cmdk version ---'
rg -n -C2 '"cmdk"' package.json pnpm-lock.yaml yarn.lock package-lock.json 2>/dev/null || true

echo '--- vimBindings and selection-key usage in the checked-in source ---'
rg -n -C6 'vimBindings|WORKTREE_PALETTE_SELECTION_MOVE_KEYS|onKeyDownCapture' \
  src/renderer/src/components/ui/command.tsx \
  src/renderer/src/components/WorktreeJumpPalette.tsx \
  src/renderer/src/lib/worktree-palette-create-action.ts

echo '--- cmdk upstream keyboard implementation ---'
python3 - <<'PY'
import urllib.request

url = 'https://raw.githubusercontent.com/pacocoursey/cmdk/main/cmdk/src/index.tsx'
try:
    text = urllib.request.urlopen(url, timeout=10).read().decode()
except Exception as exc:
    print(f'fetch failed: {exc}')
    raise SystemExit(0)

lines = text.splitlines()
needles = ('vimBindings', 'ArrowDown', 'ArrowUp', 'Ctrl', "'n'", "'p'", "'j'", "'k'")
for i, line in enumerate(lines):
    if any(needle in line for needle in needles):
        start = max(0, i - 8)
        end = min(len(lines), i + 12)
        print(f'--- lines {start + 1}-{end} ---')
        print('\n'.join(f'{n + 1}: {lines[n]}' for n in range(start, end)))
PY

Repository: stablyai/orca

Length of output: 4248


Handle cmdk’s Vim-style navigation keys. cmdk maps Ctrl+N/Ctrl+J to next and Ctrl+P/Ctrl+K to previous by default, but this capture only recognizes event.key values for arrows and paging. Track these modifier-key combinations, or set vimBindings={false}; otherwise Enter cannot activate Create after Vim-style navigation.

Comment on lines +36 to +43
export function buildWorktreeCommentEvidence(comment: string): PaletteComposedEvidence | null {
return composePaletteEvidence({
id: 'comment',
kind: 'comment',
accessibilityLabel: 'Workspace comment',
parts: [{ key: 'text', text: comment, profile: '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.

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Supporting-kind accessibility labels are declared twice and never translated. Both modules own their own copy of the English label for each PaletteSupportingKind, and both bake the string into the search result. The label reaches the DOM as aria-label in src/renderer/src/components/WorktreeJumpPalette.tsx (Line 3208), so screen-reader users read English while the adjacent visible chip label is translated through translate(). The two copies must also stay in sync by hand when a kind is added.

  • src/renderer/src/lib/worktree-palette-evidence.ts#L36-L43: stop passing literal accessibilityLabel values into composePaletteEvidence; emit only the kind and let the render layer resolve the label.
  • src/renderer/src/lib/worktree-palette-task-url-result.ts#L3-L11: delete ACCESSIBILITY_LABELS and resolve the label from the shared, translated map keyed by PaletteSupportingKind, next to getPaletteSupportingTextLabel in WorktreeJumpPalette.tsx.
📍 Affects 2 files
  • src/renderer/src/lib/worktree-palette-evidence.ts#L36-L43 (this comment)
  • src/renderer/src/lib/worktree-palette-task-url-result.ts#L3-L11

brennanb2025 pushed a commit that referenced this pull request Aug 17, 2026
…5170)

#15170 replaced the palette result model (singular matchedField/ranges ->
plural arrays, options-object search signature), which is the same surface
this PR's jump-palette change occupied. Took main's rewritten palette
wholesale and re-applied only what is load-bearing here:

- deleteActiveWorkspaceAction again passes expectedHostId, or a colliding
  id deletes whichever row wins first-wins. This is delete routing, the
  core of the PR, and taking main's side silently reverted it.
- Dropped cmd-j/worktree-palette-item-id.* — orphaned by the rewrite.
  Palette item ids are bare again, which is main's own behaviour, so
  collision disambiguation there is deferred, not regressed.
brennanb2025 pushed a commit that referenced this pull request Aug 17, 2026
#15170 replaced PaletteSearchResult while this PR was open. Re-applied the
host qualification on top of the new model instead of taking either side:
results carry worktreeHostId again, and the board filter keys its matched
set on host identity rather than the bare id.

Known gap, documented in the board test rather than deleted: searchWorktrees
resolves evidence through a `documents` map keyed by BARE worktree id, so two
same-id host rows collapse before this code sees them. Closing that belongs
with the palette work.
brennanb2025 pushed a commit that referenced this pull request Aug 17, 2026
…ld model

The palette collision test asserted two host-qualified rows, which #15170's
rewrite made unreachable: item ids are bare again and worktreeMap is id-keyed.

Rewritten to assert what holds — activation always names a host — and to pin
the defect it exposes: two same-id rows render on ONE command value, so React
sees duplicate keys and a click on the first row activates the second row's
host. That reproduces on main, so it is pre-existing, not from this PR. Pinned
rather than deleted so fixing it must update this test.
brennanb2025 added a commit that referenced this pull request Aug 17, 2026
…ows selectable (STA-4343) (#15013)

* fix(workspaces): host-qualified workspace deletion (STA-4343, STA-4448)

Squashed integration of PR #14606 + the codex review-loop output, replayed
onto current main. Granular history preserved on brennanb2025/sta-4343-review-full.

Fixes the regression from #13413: a workspace id is repoId::path with no host
component, so the same repo at the same path on two hosts published one id for
two workspaces, and deletion routed by that id landed on whichever host routing
preferred - usually the ACTIVE one, not the row the user confirmed.

- removeWorktree takes a REQUIRED host-qualified WorktreeRemovalTarget; omitting
  the host is a type error. All destructive callers migrated.
- Projections dedup on (host, id), so two hosts render as two selectable rows
  while the createWorktree/fetchWorktrees race duplicate still collapses.
- Ephemeral VM cleanup is host-scoped. It matched on bare workspaceId, so the
  host-scoped delete path destroyed the SURVIVING host's VM and its unpushed
  filesystem - a leak fix that had become data destruction.
- Selection, keyboard routing, lineage grouping and Space rows carry host
  identity end to end; fixing the executor dedupe alone would have turned
  one-row intent into deleting both hosts.

Files split to stay under max-lines rather than raising any cap.

* refactor: split files that crossed max-lines

The review-loop commits used --no-verify, so the pre-commit hook never
enforced the caps. Extracted cohesive units rather than raising any limit:
renderer teardown, delete-with-toast, pinned-group rows, host-scope helpers,
workspace-kind predicates, filter actions, kanban drag selection, the
renderer removal result type, and the native-chat persistence tests.

* refactor(workspaces): extract cleanup deletion-phase selector

Clears the last max-lines violation and the import-type side effect the
changed-code gate flagged.

* refactor(sidebar): track the delete-dialog extraction modules

* fix(workspaces): preserve host identity across remaining surfaces

* fix(sidebar): re-carry host through the rewritten palette result model

#15170 replaced PaletteSearchResult while this PR was open. Re-applied the
host qualification on top of the new model instead of taking either side:
results carry worktreeHostId again, and the board filter keys its matched
set on host identity rather than the bare id.

Known gap, documented in the board test rather than deleted: searchWorktrees
resolves evidence through a `documents` map keyed by BARE worktree id, so two
same-id host rows collapse before this code sees them. Closing that belongs
with the palette work.

* test(cmd-j): pin the palette collision gap instead of asserting the old model

The palette collision test asserted two host-qualified rows, which #15170's
rewrite made unreachable: item ids are bare again and worktreeMap is id-keyed.

Rewritten to assert what holds — activation always names a host — and to pin
the defect it exposes: two same-id rows render on ONE command value, so React
sees duplicate keys and a click on the first row activates the second row's
host. That reproduces on main, so it is pre-existing, not from this PR. Pinned
rather than deleted so fixing it must update this test.

---------

Co-authored-by: QA <qa@local>
nwparker added a commit that referenced this pull request Aug 18, 2026
Same #15133/#15170 collision as the retention test: the hoisted
useOpenTabSearch mock builds workspace tab entries with no document, so
retention re-matching throws on document.fields.
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 21, 2026
* Implement multi-keyword palette matching with evidence-based ranking

Replaces the single-match-per-field scoring with a comprehensive matcher that:
- Validates token coverage across multiple query keywords
- Normalizes Unicode text consistently across all sections
- Classifies matches by quality for cross-section leadership
- Supports evidence-based matching with hidden supporting fields
- Includes typo matching for letter-only words
- Performance-gated against a synthetic corpus of 800+ candidates

Result structure now carries match ranges per field (not per row), quality class, and document rank so sections can compare relative strength. This enables worktree/open-tab/intent section ordering based on match intent rather than hardcoded defaults.

* Improve cmd-j palette selection after deferred query commits

Instead of clearing selection when the deferred query commits,
intelligently select the next available item using the standard
selection logic. Also remove unnecessary array index from React
key generation to prevent spurious re-renders.
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 21, 2026
…ows selectable (STA-4343) (stablyai#15013)

* fix(workspaces): host-qualified workspace deletion (STA-4343, STA-4448)

Squashed integration of PR stablyai#14606 + the codex review-loop output, replayed
onto current main. Granular history preserved on brennanb2025/sta-4343-review-full.

Fixes the regression from stablyai#13413: a workspace id is repoId::path with no host
component, so the same repo at the same path on two hosts published one id for
two workspaces, and deletion routed by that id landed on whichever host routing
preferred - usually the ACTIVE one, not the row the user confirmed.

- removeWorktree takes a REQUIRED host-qualified WorktreeRemovalTarget; omitting
  the host is a type error. All destructive callers migrated.
- Projections dedup on (host, id), so two hosts render as two selectable rows
  while the createWorktree/fetchWorktrees race duplicate still collapses.
- Ephemeral VM cleanup is host-scoped. It matched on bare workspaceId, so the
  host-scoped delete path destroyed the SURVIVING host's VM and its unpushed
  filesystem - a leak fix that had become data destruction.
- Selection, keyboard routing, lineage grouping and Space rows carry host
  identity end to end; fixing the executor dedupe alone would have turned
  one-row intent into deleting both hosts.

Files split to stay under max-lines rather than raising any cap.

* refactor: split files that crossed max-lines

The review-loop commits used --no-verify, so the pre-commit hook never
enforced the caps. Extracted cohesive units rather than raising any limit:
renderer teardown, delete-with-toast, pinned-group rows, host-scope helpers,
workspace-kind predicates, filter actions, kanban drag selection, the
renderer removal result type, and the native-chat persistence tests.

* refactor(workspaces): extract cleanup deletion-phase selector

Clears the last max-lines violation and the import-type side effect the
changed-code gate flagged.

* refactor(sidebar): track the delete-dialog extraction modules

* fix(workspaces): preserve host identity across remaining surfaces

* fix(sidebar): re-carry host through the rewritten palette result model

stablyai#15170 replaced PaletteSearchResult while this PR was open. Re-applied the
host qualification on top of the new model instead of taking either side:
results carry worktreeHostId again, and the board filter keys its matched
set on host identity rather than the bare id.

Known gap, documented in the board test rather than deleted: searchWorktrees
resolves evidence through a `documents` map keyed by BARE worktree id, so two
same-id host rows collapse before this code sees them. Closing that belongs
with the palette work.

* test(cmd-j): pin the palette collision gap instead of asserting the old model

The palette collision test asserted two host-qualified rows, which stablyai#15170's
rewrite made unreachable: item ids are bare again and worktreeMap is id-keyed.

Rewritten to assert what holds — activation always names a host — and to pin
the defect it exposes: two same-id rows render on ONE command value, so React
sees duplicate keys and a click on the first row activates the second row's
host. That reproduces on main, so it is pre-existing, not from this PR. Pinned
rather than deleted so fixing it must update this test.

---------

Co-authored-by: QA <qa@local>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* Implement multi-keyword palette matching with evidence-based ranking

Replaces the single-match-per-field scoring with a comprehensive matcher that:
- Validates token coverage across multiple query keywords
- Normalizes Unicode text consistently across all sections
- Classifies matches by quality for cross-section leadership
- Supports evidence-based matching with hidden supporting fields
- Includes typo matching for letter-only words
- Performance-gated against a synthetic corpus of 800+ candidates

Result structure now carries match ranges per field (not per row), quality class, and document rank so sections can compare relative strength. This enables worktree/open-tab/intent section ordering based on match intent rather than hardcoded defaults.

* Improve cmd-j palette selection after deferred query commits

Instead of clearing selection when the deferred query commits,
intelligently select the next available item using the standard
selection logic. Also remove unnecessary array index from React
key generation to prevent spurious re-renders.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…ows selectable (STA-4343) (stablyai#15013)

* fix(workspaces): host-qualified workspace deletion (STA-4343, STA-4448)

Squashed integration of PR stablyai#14606 + the codex review-loop output, replayed
onto current main. Granular history preserved on brennanb2025/sta-4343-review-full.

Fixes the regression from stablyai#13413: a workspace id is repoId::path with no host
component, so the same repo at the same path on two hosts published one id for
two workspaces, and deletion routed by that id landed on whichever host routing
preferred - usually the ACTIVE one, not the row the user confirmed.

- removeWorktree takes a REQUIRED host-qualified WorktreeRemovalTarget; omitting
  the host is a type error. All destructive callers migrated.
- Projections dedup on (host, id), so two hosts render as two selectable rows
  while the createWorktree/fetchWorktrees race duplicate still collapses.
- Ephemeral VM cleanup is host-scoped. It matched on bare workspaceId, so the
  host-scoped delete path destroyed the SURVIVING host's VM and its unpushed
  filesystem - a leak fix that had become data destruction.
- Selection, keyboard routing, lineage grouping and Space rows carry host
  identity end to end; fixing the executor dedupe alone would have turned
  one-row intent into deleting both hosts.

Files split to stay under max-lines rather than raising any cap.

* refactor: split files that crossed max-lines

The review-loop commits used --no-verify, so the pre-commit hook never
enforced the caps. Extracted cohesive units rather than raising any limit:
renderer teardown, delete-with-toast, pinned-group rows, host-scope helpers,
workspace-kind predicates, filter actions, kanban drag selection, the
renderer removal result type, and the native-chat persistence tests.

* refactor(workspaces): extract cleanup deletion-phase selector

Clears the last max-lines violation and the import-type side effect the
changed-code gate flagged.

* refactor(sidebar): track the delete-dialog extraction modules

* fix(workspaces): preserve host identity across remaining surfaces

* fix(sidebar): re-carry host through the rewritten palette result model

stablyai#15170 replaced PaletteSearchResult while this PR was open. Re-applied the
host qualification on top of the new model instead of taking either side:
results carry worktreeHostId again, and the board filter keys its matched
set on host identity rather than the bare id.

Known gap, documented in the board test rather than deleted: searchWorktrees
resolves evidence through a `documents` map keyed by BARE worktree id, so two
same-id host rows collapse before this code sees them. Closing that belongs
with the palette work.

* test(cmd-j): pin the palette collision gap instead of asserting the old model

The palette collision test asserted two host-qualified rows, which stablyai#15170's
rewrite made unreachable: item ids are bare again and worktreeMap is id-keyed.

Rewritten to assert what holds — activation always names a host — and to pin
the defect it exposes: two same-id rows render on ONE command value, so React
sees duplicate keys and a click on the first row activates the second row's
host. That reproduces on main, so it is pre-existing, not from this PR. Pinned
rather than deleted so fixing it must update this test.

---------

Co-authored-by: QA <qa@local>
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.

1 participant