Skip to content

feat(terminal): inline path completion for the web terminal - #548

Merged
iamwhatever merged 1 commit into
mainfrom
feat/terminal-path-completion
Jul 27, 2026
Merged

iamwhatever merged 1 commit into
mainfrom
feat/terminal-path-completion

Conversation

@dwu96

@dwu96 dwu96 commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor
Screen.Recording.2026-07-26.at.11.18.20.PM.mov

What

Inline path completion for the built-in web terminal. Typing a path — or a bare argument to a path command — opens a menu anchored at the cursor; arrows select, Tab extends to the common prefix, Enter inserts, Escape dismisses.

Why this is built rather than reused

kiro-cli ships exactly this menu, and it does not reach our terminal. That menu is a native always-on-top window positioned via the macOS Accessibility API against a real terminal window; xterm.js is a canvas with no OS-level text caret to anchor to, and KiroCrew is not in kiro-cli's integration list. The one part that is genuinely native is the part we don't need — our whole UI is already in a webview and xterm hands us the cursor cell directly.

How

The word being completed is read back from xterm's screen buffer, not mirrored from keystrokes. A keystroke mirror drifts the moment the shell edits the line itself, which it does constantly: zsh's own Tab completion, autosuggestions, Ctrl-R, paste, vi mode. Reading buffer.active cannot drift because it is what the user sees.

Prompt boundaries come from shell integration when it exists. OSC 133;B (VS Code / WezTerm / starship) and OSC 697 NewCmd/EndPrompt (kiro-cli, Fig lineage) both mark where the editable region starts; either handler records the column. Without a marker we fall back to matching the last prompt terminator (❯ ➜ » $ % #) before the word — a heuristic, but a wrong answer only mis-identifies the command name, which at worst suppresses a menu that would have been offered.

Two independent triggers, both deliberately narrow. A word that already looks like a path (/, ./, ../, ~) triggers whatever the command is; a bare word triggers only for a known path command (46 of them, cd/ls/cat/vim/…). Flags, $vars and command substitutions never trigger, and neither does the command name itself while it is being typed.

Names match as case-insensitive substrings, ranked by match offset, so a long directory is reachable by its distinctive middle — termi finds KiroCrew-terminal-completion without retyping from the start — while a true prefix still leads. The matched span is emphasised in the menu, because a non-prefix hit is otherwise illegible. A fragment starting with a dot is matched as a prefix instead: the dot is what unhides entries, so treating it as a substring would drag in every foo.bar and defeat the filter it just switched on.

Accepting a directory appends /, which re-triggers the menu on its contents, so a path is walked without leaving the keyboard. Once the word ends in a slash a ↪ ./ row leads the list, so the level just chosen is reachable rather than only its children. Accepting a file ends the word and does not re-open.

Keys the menu claims are cancelled at the DOM level. Returning false from xterm's custom key handler only stops xterm's own processing — it returns early from _keyDown without calling cancel(), so the browser default still runs. Left alone, Tab moved focus out of the terminal onto the page's skip link, and Enter went on to fire keypress, which xterm turns into a CR and sends to the PTY — the shell executed the line instead of the menu completing it. Ctrl/Meta/Alt combinations are always passed through, so Ctrl-C interrupts even with the menu open.

Backend

One route, POST /api/terminal/complete, which scandirs a directory and returns entries plus the match offset.

It requires an existing terminal session id, and that is what keeps it from being a general filesystem-enumeration endpoint: the caller already owns a live PTY in this gateway — an interactive shell with the gateway user's full filesystem access — so the route grants nothing that session's own ls does not. Paths therefore resolve exactly as the shell would, without a root restriction. The existing _is_enabled gate and SEL audit logging apply.

The session cwd is probed directly with a 0.4 s memo rather than reused from the title poller's last_cwd. That poller refreshes on a 1 s cadence, which is long enough for a completion issued right after a cd to resolve against the previous directory. The memo also keeps a held-down key from spawning an lsof per keystroke (macOS has no /proc).

Out of scope

No per-CLI subcommand/flag specs, no history mode, no fuzzy (subsequence) matching, no mouse selection — the menu is pointer-events: none so it never steals the terminal's own selection and drag. Words containing spaces produce no completions rather than wrong ones: quoting and backslash escapes are not interpreted. git, docker, kubectl and friends need to know which argument is a path, which is what a spec tree solves; until then they work by typing ./.

POSIX only, following the PTY backend.

Testing

  • test/test_terminal_handler.py — 125 pass, 5 skipped. New coverage for word splitting, directory resolution (relative / absolute / ~ / ..), substring matching and offset ranking, the dot-prefix rule, hidden-entry gating, folders_only narrowing, truncation, the cwd memo TTL, and the route's auth / disabled / malformed-body / oversized-word / unknown-session paths.
  • website/src/test/terminalCompletion.test.ts — 31 pass. Pure trigger/tokenising logic: cursor at a word boundary, prompt-marker versus heuristic, pipelines and &&, sudo/env wrappers, flags and expansions, common prefix, insertion keystrokes.
  • website/src/test/TerminalCompletion.test.tsx — 23 pass. Full trigger → fetch → render → keys path, including a regression test that every claimed key is defaultPrevented, that Ctrl-C is not, that accepting a directory re-opens on the next level, that accepting a file does not, and that a mid-name match is emphasised and replaces the typed fragment.
  • Existing terminal-adjacent suites re-run green (CliPanel.fontRefit, RunInTerminalBtn, RunInTerminalBtn.security, App.terminalEnabledFlag).
  • flake8, isort, mypy, tsc, eslint clean; npm run build passes.

Not verified

Visual behaviour was exercised by hand on macOS with zsh + kiro-cli's OSC 697 integration (the four bugs above were all found that way). The OSC 133 path and the no-marker heuristic have unit coverage but were not driven through a real bash/fish session end to end.

@github-actions github-actions Bot added the readiness: checking Automated validation is still running label Jul 27, 2026
@github-actions

github-actions Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Design Review (Fable 5) — ✅ PASS

Advisory design-level review of 445c24bca528aeca34d5d6d081d8aa5f0b9d12bd — updated in place on each push; does not block merge.

Design-Verdict: PASS

A real UX gap closed with a sound shape: screen-buffer truth over keystroke mirroring, session-scoped authority on the backend, and refuse-over-guess everywhere ambiguity exists.

[DESIGN-REVIEWED] 445c24b

@github-actions

github-actions Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Arbiter — ✅ no blocking findings

Arbiter found no unresolved long-term items that require action before merging 445c24bca528aeca34d5d6d081d8aa5f0b9d12bd.

Second-order review for 445c24bca528aeca34d5d6d081d8aa5f0b9d12bd; this comment is updated in place on each push.

Review details

Both line-level reviewers (Opus 5 and GPT 5.6) reported no findings for this commit, and the design review passed with no CONCERNS listed — so there are no sub-threshold findings to arbitrate.

Arbiter-Verdict: PASS

No sub-threshold finding meets the long-term-impact bar.

Both line-level reviews (Opus 5, GPT 5.6) recorded "No findings" for commit 445c24bc, and the design review recorded a PASS verdict with no CONCERNS. With an empty findings set there is nothing eligible for escalation or for follow-up tracking under this arbiter's mandate, which judges only already-raised findings and does not re-review the diff.

[ARBITER-REVIEWED] 445c24b

False positive or not applicable? A repository writer can comment:
/ai-review override arbiter 445c24bca528aeca34d5d6d081d8aa5f0b9d12bd: <one-sentence reason>

For a broader accepted-risk deferral, apply defer-longterm and explain why.

@github-actions

github-actions Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

GPT 5.6 Review — ✅ no blocking findings

GPT 5.6 completed its review of 445c24bca528aeca34d5d6d081d8aa5f0b9d12bd and found no blocking issues.

This comment is updated in place on each push.

Review details

No findings.
[GPT-REVIEWED] 445c24b

False positive or not applicable? A repository writer can comment:
/ai-review override gpt 445c24bca528aeca34d5d6d081d8aa5f0b9d12bd: <one-sentence reason>

@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention and removed readiness: checking Automated validation is still running labels Jul 27, 2026
@dwu96
dwu96 force-pushed the feat/terminal-path-completion branch from 4103e82 to 45c3c52 Compare July 27, 2026 06:48
@github-actions github-actions Bot added readiness: checking Automated validation is still running and removed readiness: action required A blocking check or review needs attention labels Jul 27, 2026
@dwu96

dwu96 commented Jul 27, 2026

Copy link
Copy Markdown
Contributor Author

Round 1 — all 11 GPT 5.6 findings + both Design Review concerns addressed

Pushed as 45c3c528 (single commit, amended). Nothing was dismissed as a false positive.

HIGH

1. Raw filenames enable terminal command injection (TerminalCompletion.tsx)

Correct and the most serious of the three. touch $'evil\nrm -rf x' creates a legal directory entry whose name contains a newline; accepting it typed that newline into the PTY and the shell executed the second line.

Two layers, because they solve different problems. Control characters are refused, not escaped — there is no escape that makes CR/LF safe to type — filtered where the listing enters the component so such a name is never offered, never highlighted, and never feeds Tab's common prefix, with a second check in accept as defence in depth. Everything else is backslash-escaped inside buildInsertion, which is the single choke point both insertion paths already went through, so the Tab common-prefix path you called out is covered by construction rather than by a second call site that could be forgotten. The escape set is an allowlist (\p{L}\p{N}_@%+:,./-, i.e. shlex.quote's safe set minus = for zsh equals-expansion), so a metacharacter this version has not anticipated is escaped by default.

Backslashes rather than quotes, deliberately: the escaped name stays one shell word with nothing left open, so the echo still tokenises as a single word and accepting a directory can re-trigger on its contents. Wrapping in quotes would put the cursor inside a quoted region that finding #10's fix then (correctly) refuses to complete, dead-ending the walk-into-directory flow the trailing / exists for.

2. Completion bypasses the sensitive-path keystone (terminal.py)

Correct — is_sensitive_path() is used in six places in _shared.py and the new scandir skipped it. New _vetted_completion_dir() runs os.path.realpath() first, then the sensitive-path test on the canonical form. The order is the point: a benign-named symlink, or a symlinked parent component, whose target lands in the governance trust-root would pass a name-based check and then be enumerated through the link. The gate lives inside _list_completions so any future caller inherits it, and is also evaluated in the route so the audit reason can be distinguished. A realpath failure refuses rather than proceeds. Refusal returns the identical empty-listing shape as the unknown-cwd branch, so the client needs no special case and the response does not disclose whether the path exists.

3. Successful enumeration is not SEL-audited (terminal.py)

Correct, and the spec states it as a blocking rule. terminal.complete is now emitted for every outcome — feature_disabled, invalid_body, token_too_long, unknown_session, no_cwd, sensitive_path, listed.

The payload is deliberately coarse: a fixed reason word and nothing else. This route fires per keystroke behind a 70 ms debounce, and the word, prefix, resolved directory and entry names are all user filesystem contents — logging them would turn the audit trail into a transcript of the user's typing and disk layout, which is a worse outcome than the coarse event. Flagging the volume tradeoff explicitly since it is a consequence of the rule rather than of this feature: one audit event per completion request.

MEDIUM

4. Stale suggestions survive edits and failures. Fixed both halves. .catch now closes the menu unless the rejection is our own abort (closing on abort would kill the superseding request already in flight). Enter and Tab re-read the live word with the same reader that opened the menu and compare against Suggestions.token; on a mismatch the menu closes and the key is returned to the shell untouched rather than swallowed — Enter submits exactly the visible line, Tab runs the shell's own completion. The abort never types on the user's behalf and never eats a keystroke.

5. Mid-word completion corrupts the command. Fixed. The module docstring claimed this was out of scope but nothing enforced it; new atWordEnd suppresses when the character right of the cursor is not whitespace. Same restriction kiro-cli applies internally.

6. translateToString row versus cursorX cell coordinate. Fixed by suppression, not by mapping — a deliberate call. A correct mapping needs the logical line reassembled across continuation rows, a cell-width prefix sum to convert cursorX to a string index, and the reverse mapping to anchor the menu column: a second coordinate system inside a V1 whose only current failure mode is a silently wrong path. Instead the reader bails on isWrapped, and scans getCell(x).getWidth() up to the cursor, bailing on any 2 (wide glyph) or 0 (its spacer). Cells after the cursor are not scanned, so a CJK argument later on the line does not disable completion for the word being typed.

7. Menu opens while a foreground program owns the PTY. Fixed via the alternate-screen guard rather than the process-group check you suggested — this is the one place I deviated. Design Review independently called the alt-buffer bail-out "a one-line fix [that] closes the whole failure class", and it covers vim/less/htop. Honest remaining gap: a REPL on the normal screen is not covered, and >>> happens to satisfy our prompt-terminator heuristic. Full foreground-process-group detection means reading the PTY's controlling process group per keystroke and is deferred rather than dismissed.

8. No IME guard. Fixed. Keys with isComposing or keyCode === 229 pass through, plus any Enter within 60 ms of a compositionend observed on term.textarea — browsers disagree on whether the committing Enter is flagged as composing, and some only report the boundary.

9. Unbounded retention and wrong executor. Fixed both. Candidates are now pulled lazily from a generator into heapq.nsmallest(limit, …) against the same ranking key, so only limit entries are ever alive regardless of directory size. A second cap, _COMPLETE_MAX_SCAN = 20000, bounds how many entries are examined — retention alone still walked a million-entry directory while holding a pool thread. truncated is truthful for both caps. The listing moved to discovery_executor(); subprocess_executor() is shared with PTY teardown (os.close on a wedged master fd) and a slow scan must not be able to starve it. _session_cwd_cached stays on subprocess_executor() — it genuinely shells out to lsof.

10. Quoted and escaped words. Fixed. New isPlainWord rejects a word containing a quote or backslash, rejects a quote between the command start and the word, and rejects when the whitespace ending the previous word was preceded by an odd number of backslashes (cd My\ D). The scan is bounded by the command start so an apostrophe in the prompt (~/it's » ) cannot disable the whole line. cd My\\ D — escaped backslash, real break — still completes.

11. Spec not updated. Fixed. POST /api/terminal/complete is documented in the Terminal paragraph of docs/system-specs/modules/learn-cron-dashboard.md, in the surrounding continuous-prose style, covering the request/response contract, status codes, the substring/offset matching and the dot-prefix exception, both caps, the sensitive-path gate, the SEL reason vocabulary, the cwd memo, the authority model, and the client-side suppression rules.

Design Review

Both items are covered above (alt-buffer guard → #7, spec → #11). The third, advisory, item is also done: CliPanel.tsx now carries a comment at the mount site naming the constraint that this component claims xterm's single attachCustomKeyEventHandler slot and which keys it reserves, so a future terminal feature does not shadow it unknowingly.

Verification

  • test/test_terminal_handler.py — 139 passed, 5 skipped (pre-existing: 1 real-host Windows, 4 need Linux /proc). New: sensitive directory refused directly and via a benign-named symlink; canonicalisation and realpath-failure cases; retention cap preserving ranking; scan cap setting truncated and not setting it when the directory fits; newline/ESC filenames excluded; SEL asserted on successful listing with the payload proven free of both the typed word and the directory path; SEL on sensitive_path / no_cwd / unknown_session; and an assertion that the listing uses discovery_executor and never subprocess_executor.
  • Frontend — 124 passed across the two owned suites plus the existing terminal-adjacent ones (CliPanel.fontRefit, RunInTerminalBtn, RunInTerminalBtn.security, App.terminalEnabledFlag). The two completion suites went 76 → 90 tests: alternate-buffer suppression (never opens, and closes an open menu), mid-word, wrapped row, wide cell, quoted and escaped words, control-character filenames, escaping on both the Enter and Tab paths, stale-word abort, and IME pass-through including the post-composition window.
  • flake8, isort, mypy, tsc, eslint clean; npm run build passes.

One scope note

The 400/413 client-validation branches are audited too (invalid_body, token_too_long), so "every outcome emits SEL" holds literally rather than only for access outcomes. Say the word if you would rather keep malformed-request noise out of the audit log.

@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention and removed readiness: checking Automated validation is still running labels Jul 27, 2026
@dwu96
dwu96 force-pushed the feat/terminal-path-completion branch from 45c3c52 to d90f059 Compare July 27, 2026 06:59
@dwu96

dwu96 commented Jul 27, 2026

Copy link
Copy Markdown
Contributor Author

Round 1b — d90f059b: fixed the Inclusive Language failure. Two added lines used "master fd" for the PTY file descriptor (one comment in terminal.py, one sentence in the spec). The existing code carries the POSIX field name master_fd with # wokeignore:rule=master pragmas, and the round-1 comment had the pragma on the wrong line; rather than add a pragma for prose I rephrased both to describe the behaviour instead ("an os.close that can wedge in the kernel"), which is clearer anyway since the point is the blocking close, not the fd. No functional change; 139 backend tests still pass.

@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Jul 27, 2026
@dwu96
dwu96 force-pushed the feat/terminal-path-completion branch from d90f059 to 523ef16 Compare July 27, 2026 07:43
@github-actions github-actions Bot added readiness: checking Automated validation is still running and removed readiness: action required A blocking check or review needs attention labels Jul 27, 2026
@dwu96

dwu96 commented Jul 27, 2026

Copy link
Copy Markdown
Contributor Author

Round 2 — all 3 HIGH + 10 MEDIUM addressed

Pushed as 523ef169 (still one commit). Nothing dismissed as a false positive. Two of these were regressions introduced by round 1's own fixes, which is worth calling out.

HIGH

1. Sensitive child entries bypass the gate. Correct, and my round-1 fix was the cause of the false confidence: it vetted the directory only, so completing inside ~/.kiro/crew still stat'd and returned leaves like security_policy.json. New _entry_is_sensitive(canonical_dir, entry) runs inside the scandir loop after the cheap name filters and before entry.is_dir(), so a rejected entry is never stat'd. Any OSError/ValueError counts as sensitive — over-refusal is the safe direction for a read gate. The per-entry cost is kept off the syscall path: with an already-canonical parent, a non-symlink entry needs no re-resolution, so only symlinked children pay for a second resolve.

2. Path resolution blocks the event loop. Correct — expanduser does a synchronous NSS lookup for ~someuser, and realpath touches the filesystem. New _resolve_vet_and_list does resolve + vet + list on a single discovery_executor() hop and returns (lexical_dir, allowed, entries, truncated); the coroutine no longer calls either inline. One hop rather than three, so a keystroke costs one thread handoff. _list_completions remains as a vetting wrapper over _list_vetted_completions so it stays the safe entry point for direct callers. The sensitive_path SEL reason and the null-dir response shape are unchanged. The new test records the thread each function ran on, asserts neither is the loop thread, asserts the order, and asserts discovery_executor was consulted exactly once.

3. Leading hyphens remain executable options. Correct, and the sharpest finding in this round — escaping cannot fix it, since \-c is still an option to the target program. buildInsertion now prefixes ./ when the replacement starts with -, and only when the word has no directory part (sub/-x cannot parse as an option anyway). Both insertion paths go through that one function, so the guard cannot be bypassed. Because ./ means the replacement no longer extends the typed word, the erase-and-retype branch takes over naturally: selecting -c:!sh evil from evil erases 4 and retypes ./-c:\!sh\ evil.

MEDIUM

4. isPlainWord rejects the backslashes shellEscape produces. This is a regression round 1 introduced, and the most user-visible item here: after accepting my dir/ the on-screen word is my\ dir/, which isPlainWord rejected, so completion refused to continue — dead-ending precisely the walk-into-directory flow the trailing / exists for. Fixed by unescaping rather than rejecting, which took three coordinated changes: extractToken no longer breaks at whitespace preceded by an odd number of backslashes (without this the tokeniser split before escaping was ever consulted, so unescaping alone would not have helped); isPlainWord accepts backslashes, still rejects quote characters, and newly rejects a word ending in a lone backslash as an unfinished escape; and new unescapeWord decodes the word for the request. readWord now returns both forms.

That decouples on-screen length from decoded length, so buildInsertion's contract changed: it takes the word as the terminal shows it (escapes intact), splits the last path segment itself, and measures both the extend-check and the erase count against that escaped text. Every pre-existing buildInsertion expectation still holds. Contract note: token in the request is now the dequoted literal path, not the raw shell word — the route docstring and the module spec are updated to say so.

5. Cached cwd survives command submission. Correct — the 0.4 s memo reintroduced, in a smaller window, the exact bug it was added to prevent. The WS binary-write branch now clears sess.cwd_probe when the written bytes contain CR/LF, so cd invalidates on submission rather than up to 400 ms later. A non-submitting keystroke leaves the memo intact, otherwise every character would force a fresh lsof on macOS. Verified end-to-end over a real PTY, with a ping round-trip as the ordering barrier.

6. close() leaves the debounce timer armed — cleared and nulled, so Escape followed by an edit no longer reopens the menu despite the dismissal.

7. term.textarea is null on first mount. Correct: the child effect runs before the parent's term.open(), so the IME grace listener was never attached at all and fix F of round 1 was dead code on first mount. Now attaches immediately when the textarea exists and otherwise on the first term.onRender.

8. Surrogate filenames. Both halves. Server: the filter is extended to \ud800-\udfff and renamed _UNSAFE_NAME_RE, since it no longer describes only controls. Client: isSafeName now tests [\p{Cc}\p{Cs}]. A well-formed pair is a supplementary code point rather than Cs, so emoji and rare-CJK names still complete — asserted explicitly.

9. commonPrefix compares UTF-16 code units — now compares code points, so names differing inside a supplementary character can no longer yield a lone surrogate.

10. erase counts code units — now code points, with a comment recording that one DEL erases one character from the shell's line editor while String.length counts UTF-16 units. The old count sent two DELs for one supplementary character and ate the character before the word.

11. Combining-character cells. Fixed by suppression, not remapping, and stated as a choice: readWord already refused non-single-width cells and now also refuses a cell whose getChars() is longer than one code unit. A correct cell→offset mapping means rebuilding the row cell by cell and re-deriving every column index — disproportionate for a rare row, where refusing costs that row its menu and never mistypes a path.

12. folders_only coercion. bool() replaced by an isinstance(..., bool) check alongside the existing type validation; the 400 message names folders_only?: boolean. Parametrised over "false", "true", "0", 0, 1, null, [] → 400, and real booleans plus the omitted default → 200 with the expected split.

13. Manual fetch violates the React Query rule. Verified against website/AGENTS.md:90 and complied rather than argued. useQuery with key ['terminal-completions', sessionId, token, foldersOnly], enabled, staleTime: 0, gcTime: 0, retry: false, and the query's signal passed to fetch — a key change drops the superseded query and aborts its signal, and gcTime: 0 keeps a keystroke-rate filesystem read from ever being served from memory, since stale entries reappearing is a correctness bug rather than a perf win. The debounce now only sets a request object whose identity is preserved when unchanged, so a bare cursor move does not churn the key. An arriving listing is turned into menu state rather than derived, so the open menu does not blink out on every keystroke, and that effect re-checks the dismissal because React Query — unlike the old abort — can still deliver a reply after Escape closed the menu.

Verification

  • Backend: 156 passed, 6 skipped (5 pre-existing platform guards, plus a macOS-unwritable surrogate-filename test whose code path is covered on every platform by a synthetic-scandir test).
  • Frontend: 151 passed across the two owned suites (68 + 49) plus the four existing terminal-adjacent ones.
  • flake8, isort, mypy, tsc, eslint clean; npm run build passes; Inclusive Language pre-checked against the added lines this time rather than after the fact.
  • Spec updated again for the changed token semantics, the surrogate filter, the combining-cell suppression, and the fact that backslash-escaped words are now handled rather than refused.

Remaining known gap, unchanged from round 1

Foreground-process-group detection is still not implemented. The alternate-screen guard covers vim/less/htop; a REPL on the normal screen is not covered, and >>> happens to satisfy the prompt-terminator heuristic. Deferred, not dismissed.

@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running and removed readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention labels Jul 27, 2026
@github-actions

github-actions Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Opus 5 Review — ✅ no blocking findings

Reviewed 445c24bca528aeca34d5d6d081d8aa5f0b9d12bd — this comment is updated in place on each push.

No findings.

Verdict recorded via the action's structured output for commit 445c24bca528aeca34d5d6d081d8aa5f0b9d12bd.

False positive or not applicable? A repository writer can comment:
/ai-review override fable 445c24bca528aeca34d5d6d081d8aa5f0b9d12bd: <one-sentence reason>

@dwu96
dwu96 force-pushed the feat/terminal-path-completion branch from cf08548 to 03b9c11 Compare July 27, 2026 18:13
@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Jul 27, 2026
@dwu96
dwu96 force-pushed the feat/terminal-path-completion branch from 9273bad to 74ea1f5 Compare July 27, 2026 19:45
@dwu96

dwu96 commented Jul 27, 2026

Copy link
Copy Markdown
Contributor Author

Round 6 — 74ea1f5c

BLOCKING — filesystem read bypasses the hooks.py chokepoint

The rule is real. docs/system-specs/modules/security.md, Security Rules for Development → Backend #1: "Never read sensitive paths — all file reads must go through hooks.py which enforces is_sensitive_path()". The code satisfied the rule’s intent — it called is_sensitive_path() directly, the exact predicate the rule names, after realpath — but not its mechanism, and the mechanism is the point of naming a chokepoint: it is what makes the property auditable across the codebase rather than re-derived per call site.

_vetted_completion_dir now delegates to hooks.validate_file_path(), which is that pair (realpath(expanduser(...)) → is_sensitive_path) behind one name. No semantic change; the reimplementation is gone.

Worth noting the precedent this lands on: hooks.safe_read_file already layers an O_NOFOLLOW open over the same check to close the same TOCTOU window for single-file reads. Round 3’s descriptor pinning is that pattern applied to a directory read, so the pairing here now mirrors the established one instead of inventing a parallel structure — validate_file_path decides which path is allowed, _open_vetted_dir binds the answer to the inode that will be read.

Per-entry gate unchanged, deliberately. _entry_is_sensitive still calls is_sensitive_path on the joined child path rather than routing each entry through validate_file_path. That wrapper adds a realpath per call, and this runs per entry at keystroke rate — up to the 20k scan cap. The parent is already canonical by then, so for a non-symlink child the extra resolution buys the same verdict for a syscall, and is_sensitive_path internally builds both resolved and lexical candidate forms, so a symlinked child whose target is protected is still refused through the link. The chokepoint governs the read; the per-entry filter is a second, cheaper layer on top of it.

Tests: 165 passed, 6 skipped. New case asserts _vetted_completion_dir actually calls validate_file_path and honours its refusal, so a future edit cannot quietly re-inline the check. The existing sensitive-path tests were rewired through a _sensitive() helper that forces the verdict at both layers — the directory gate now lives in hooks, so a test patching only terminal.is_sensitive_path would have exercised half the guard and passed regardless.

flake8, isort, mypy clean; npm run build passes. Spec updated to name the chokepoint. Frontend untouched this round (125 passed on the previous commit).

On the shape of this loop

This is round 6, and rounds 3 and 6 are the same code under two framings — round 3 asked for descriptor pinning (implemented), round 6 asked for the same call site to route through hooks. Both were worth doing. But if a round 7 returns to this function again, I would rather have a human decide than keep re-litigating it, since the substantive vulnerabilities in this area were closed in rounds 1–3 and what remains is convention placement.

@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Jul 27, 2026
@dwu96
dwu96 force-pushed the feat/terminal-path-completion branch from 74ea1f5 to 3e082b3 Compare July 27, 2026 20:02
@dwu96

dwu96 commented Jul 27, 2026

Copy link
Copy Markdown
Contributor Author

Round 7 — 3e082b3e

BLOCKING — Tab can shorten a case-insensitive match

Real, and a nice catch: it falls out of the interaction between two features rather than being visible in either. Matching is case-insensitive server-side, so cd doc matches Docs and DoConfig; commonPrefix compares the names as they are, giving Do — two characters, one fewer than the user typed. The old guard was common !== s.prefix, which is true for Do, so Tab replaced doc with Do and silently ate a character.

New extendsWord(common, prefix) gates that branch: a candidate must be at least as long as the typed word and agree with it case-insensitively. A non-extending candidate falls through to the existing behaviour of committing the highlighted entry, which is the useful thing to do when there is no shared extension to offer.

One case deliberately kept as an insert rather than a no-op: an equal-length candidate that differs only in case (Doc for doc). That is not a shortening — it corrects the word to the name that actually exists on disk, which is the same reason buildInsertion already erases-and-retypes on a case mismatch.

Seven unit tests: shorter-than-typed rejected, genuine extension accepted, case-only correction accepted, identical rejected, divergent candidate rejected, empty candidate rejected, and any candidate accepted when nothing is typed yet.

Publish readiness signal

Failed alongside PR Readiness with 8 readiness check(s) still pending — it is the downstream label publisher for the readiness aggregate and exits non-zero while the aggregate is undecided. Not a code result; it clears when the blocking review does.

Verification

Frontend 132 passed (82 unit + 50 component), tsc and eslint clean, npm run build passes. Backend untouched this round (165 passed on the previous commit).

@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Jul 27, 2026
The web terminal had no completion menu of its own. kiro-cli's autocomplete does
not reach it: that menu is a native always-on-top window positioned via the
macOS Accessibility API against a real terminal window, and xterm.js is a canvas
with no OS-level text caret to anchor to.

Build the equivalent natively instead. The menu is a positioned React element
inside the terminal pane, driven from xterm's own screen buffer rather than a
keystroke mirror, so it cannot drift out of sync with the shell's line editor
(zsh tab completion, autosuggestions, Ctrl-R, paste and vi mode all rewrite the
line behind our back). Prompt boundaries come from OSC 133 `B` or OSC 697
`NewCmd`/`EndPrompt` when the user's shell integration emits them, and from a
prompt-terminator heuristic otherwise.

Scope is paths only: directories for `cd`/`mkdir`-style commands, directories
plus files elsewhere, arrow keys to select, Tab to extend to the common prefix,
Enter to insert, Escape to dismiss. Accepting a directory appends `/`, which
re-triggers the menu so a path can be walked without leaving the keyboard; a
row that confirms the directory as typed leads the list once the word ends in a
slash, so the level just chosen is reachable rather than only its children.
Accepting a file ends the word and does not re-open. No per-CLI subcommand
specs, history mode or fuzzy matching.

Names are matched as case-insensitive substrings, not prefixes, so a long
directory is reachable by its distinctive middle (`termi` finds
`KiroCrew-terminal-completion`) without retyping from the start. Results rank by
match offset, so a true prefix still leads, and the matched span is emphasised
in the menu — a non-prefix hit is illegible otherwise. Accepting such an entry
erases the typed fragment and retypes the name, since it cannot be extended in
place. A fragment starting with a dot is matched as a prefix instead: the dot is
what unhides entries, so searching for it as a substring would drag in every
`foo.bar` and defeat the filter it just switched on.

Nothing filesystem-derived is typed raw. A directory entry may legally contain a
newline — `touch $'evil\nrm -rf x'` creates one — and typing it would submit the
second line to the shell as a command, so names carrying a control character are
refused at both the listing and the insertion end rather than sanitised, since no
escape makes CR/LF safe to type. Everything else is backslash-escaped through the
single choke point both insertion paths already share, against an allowlist, so a
metacharacter this version has not thought of is escaped by default. Backslashes
rather than quotes keep the result one shell word with nothing left open, so the
echo still tokenises as one word and walking into a directory still works.

The menu produces nothing rather than something plausible but wrong wherever the
row cannot be reasoned about: on the alternate screen buffer, because vim/less/
htop sweep the cursor over arbitrary text where a redrawn `> cd ./src` satisfies
the prompt heuristic and an open menu would then steal Escape/Enter/Tab/arrows
from the TUI; on a wrapped row or one with a non-single-width cell at or before
the cursor, because `translateToString` returns one physical row while `cursorX`
counts cells and the two coordinate systems agree only otherwise; mid-word, where
the chosen name would be inserted in front of the surviving suffix; and for words
the whitespace-only tokeniser cannot parse (`cd "My D`, `cd My\ D`). Enter and
Tab re-read the live word before acting and hand the key back to the shell
untouched if it no longer matches what the suggestions were computed for, and a
failed request closes the menu instead of leaving stale entries acceptable. Keys
committing an IME composition are passed through, since swallowing that Enter
would accept a path instead of the composed text.

Keys the menu claims are cancelled at the DOM level. Returning false from
xterm's custom key handler only stops xterm's own processing — it returns early
from _keyDown without calling cancel(), so Tab would still move focus out of
the terminal and Enter would still reach the PTY as a CR through the following
keypress event, executing the line instead of completing it. Ctrl/Meta/Alt
combinations are passed through untouched, so Ctrl-C always interrupts.

Backend adds POST /api/terminal/complete. It requires an existing live PTY
session id, and that is what keeps it from being a general filesystem-
enumeration endpoint: the caller already owns an interactive shell with the
gateway user's filesystem access, so the route grants nothing that session's own
`ls` does not. Within that model the target directory is still canonicalised with
realpath and refused through `is_sensitive_path()` before any scan —
canonicalisation first, because a benign-named symlink whose target lands in the
governance trust-root would otherwise pass a name check and be enumerated through
the link. Every outcome including success emits a `terminal.complete` SEL event
carrying only a fixed reason word: the route fires per keystroke, and logging the
word, prefix, directory or entry names would turn the audit trail into a
transcript of the user's typing and disk layout. Candidates are pulled lazily
into a bounded heap and the scan itself is capped, so neither a huge directory
nor a pathological one can occupy a pool thread; the listing runs on
discovery_executor rather than the subprocess_executor shared with PTY teardown.
The session cwd is probed directly with a 0.4 s memo rather than reused from the
title poller, whose 1 s cadence would resolve a completion issued right after a
`cd` against the previous directory.

POSIX only, following the PTY backend.
@dwu96
dwu96 force-pushed the feat/terminal-path-completion branch from 3e082b3 to 445c24b Compare July 27, 2026 20:17
@dwu96

dwu96 commented Jul 27, 2026

Copy link
Copy Markdown
Contributor Author

Round 8 — 445c24bc

BLOCKING — bare colon filenames remain remote rsync targets

Real. rsync/scp read host:path as a remote target, so a local file named attacker.example:drop turns rsync secret.txt <completion> into an upload off the machine. Escaping does not help — host\:path is still a remote target to rsync, because the reinterpretation happens in the program, after the shell has already split the word. : is also legitimately in shellEscape's safe set, which is correct for the shell and irrelevant here.

Rather than add a third one-off condition, I generalised the guard. OPTION_LEAD = /^[-+]/ is now NOT_A_PLAIN_PATH = /^[-+]|:/, documented as a class: a bare filename that some program would read as something other than a local path. Both members are the same failure mode —

  • leading -/+ → an option to whatever runs next (vim -c:!sh evil, vim +:!id);
  • : in a name with no directory part → a remote host:path target.

The reasoning is written down in one place, so a future variant lands there instead of becoming round 9. The guard still applies only when the word has no directory part, since sub/a:b is already unambiguously a path, and still lives inside buildInsertion, the single choke point Enter and Tab's common prefix both pass through.

Three tests: a colon-bearing bare name guarded on the Enter path, guarded on Tab's common prefix, and a colon-named file inside a directory left alone.

Note on this loop

This is the third consecutive round on the same class (- in round 4, + in round 4b, : here), each found by enumerating another program's argument syntax. The generalisation above is my attempt to stop that enumeration from driving the round count. If a round 9 produces a fourth member of the same class, I would suggest a human decides whether the class is adequately covered rather than continuing to append characters — the mitigation is uniform and the residual is "some program somewhere reads some other character specially".

Verification

Frontend 135 passed (85 unit + 50 component), tsc and eslint clean, npm run build passes. Backend untouched (165 passed). Spec updated to describe the class rather than list two characters.

@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: passed Eligible automated validation passed for the current revision and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Jul 27, 2026
@iamwhatever
iamwhatever merged commit fc85714 into main Jul 27, 2026
42 checks passed
@iamwhatever
iamwhatever deleted the feat/terminal-path-completion branch July 27, 2026 22:38
@github-actions github-actions Bot removed the readiness: passed Eligible automated validation passed for the current revision label Jul 27, 2026
encomjp pushed a commit to encomjp/kirocrew-customapi that referenced this pull request Aug 22, 2026
…otdev#548)

The web terminal had no completion menu of its own. kiro-cli's autocomplete does
not reach it: that menu is a native always-on-top window positioned via the
macOS Accessibility API against a real terminal window, and xterm.js is a canvas
with no OS-level text caret to anchor to.

Build the equivalent natively instead. The menu is a positioned React element
inside the terminal pane, driven from xterm's own screen buffer rather than a
keystroke mirror, so it cannot drift out of sync with the shell's line editor
(zsh tab completion, autosuggestions, Ctrl-R, paste and vi mode all rewrite the
line behind our back). Prompt boundaries come from OSC 133 `B` or OSC 697
`NewCmd`/`EndPrompt` when the user's shell integration emits them, and from a
prompt-terminator heuristic otherwise.

Scope is paths only: directories for `cd`/`mkdir`-style commands, directories
plus files elsewhere, arrow keys to select, Tab to extend to the common prefix,
Enter to insert, Escape to dismiss. Accepting a directory appends `/`, which
re-triggers the menu so a path can be walked without leaving the keyboard; a
row that confirms the directory as typed leads the list once the word ends in a
slash, so the level just chosen is reachable rather than only its children.
Accepting a file ends the word and does not re-open. No per-CLI subcommand
specs, history mode or fuzzy matching.

Names are matched as case-insensitive substrings, not prefixes, so a long
directory is reachable by its distinctive middle (`termi` finds
`KiroCrew-terminal-completion`) without retyping from the start. Results rank by
match offset, so a true prefix still leads, and the matched span is emphasised
in the menu — a non-prefix hit is illegible otherwise. Accepting such an entry
erases the typed fragment and retypes the name, since it cannot be extended in
place. A fragment starting with a dot is matched as a prefix instead: the dot is
what unhides entries, so searching for it as a substring would drag in every
`foo.bar` and defeat the filter it just switched on.

Nothing filesystem-derived is typed raw. A directory entry may legally contain a
newline — `touch $'evil\nrm -rf x'` creates one — and typing it would submit the
second line to the shell as a command, so names carrying a control character are
refused at both the listing and the insertion end rather than sanitised, since no
escape makes CR/LF safe to type. Everything else is backslash-escaped through the
single choke point both insertion paths already share, against an allowlist, so a
metacharacter this version has not thought of is escaped by default. Backslashes
rather than quotes keep the result one shell word with nothing left open, so the
echo still tokenises as one word and walking into a directory still works.

The menu produces nothing rather than something plausible but wrong wherever the
row cannot be reasoned about: on the alternate screen buffer, because vim/less/
htop sweep the cursor over arbitrary text where a redrawn `> cd ./src` satisfies
the prompt heuristic and an open menu would then steal Escape/Enter/Tab/arrows
from the TUI; on a wrapped row or one with a non-single-width cell at or before
the cursor, because `translateToString` returns one physical row while `cursorX`
counts cells and the two coordinate systems agree only otherwise; mid-word, where
the chosen name would be inserted in front of the surviving suffix; and for words
the whitespace-only tokeniser cannot parse (`cd "My D`, `cd My\ D`). Enter and
Tab re-read the live word before acting and hand the key back to the shell
untouched if it no longer matches what the suggestions were computed for, and a
failed request closes the menu instead of leaving stale entries acceptable. Keys
committing an IME composition are passed through, since swallowing that Enter
would accept a path instead of the composed text.

Keys the menu claims are cancelled at the DOM level. Returning false from
xterm's custom key handler only stops xterm's own processing — it returns early
from _keyDown without calling cancel(), so Tab would still move focus out of
the terminal and Enter would still reach the PTY as a CR through the following
keypress event, executing the line instead of completing it. Ctrl/Meta/Alt
combinations are passed through untouched, so Ctrl-C always interrupts.

Backend adds POST /api/terminal/complete. It requires an existing live PTY
session id, and that is what keeps it from being a general filesystem-
enumeration endpoint: the caller already owns an interactive shell with the
gateway user's filesystem access, so the route grants nothing that session's own
`ls` does not. Within that model the target directory is still canonicalised with
realpath and refused through `is_sensitive_path()` before any scan —
canonicalisation first, because a benign-named symlink whose target lands in the
governance trust-root would otherwise pass a name check and be enumerated through
the link. Every outcome including success emits a `terminal.complete` SEL event
carrying only a fixed reason word: the route fires per keystroke, and logging the
word, prefix, directory or entry names would turn the audit trail into a
transcript of the user's typing and disk layout. Candidates are pulled lazily
into a bounded heap and the scan itself is capped, so neither a huge directory
nor a pathological one can occupy a pool thread; the listing runs on
discovery_executor rather than the subprocess_executor shared with PTY teardown.
The session cwd is probed directly with a 0.4 s memo rather than reused from the
title poller, whose 1 s cadence would resolve a completion issued right after a
`cd` against the previous directory.

POSIX only, following the PTY backend.
@bolichen97

Copy link
Copy Markdown
Contributor

Open PR relationship audit

This is a consolidated, point-in-time code-level audit note. It compares complete merge-base diffs and current/merged code; it does not treat a shared topic as duplication or partial coverage as completion.

Relationship findings

  • PR #7203 is PARTIALLY_COVERED relative to this PR. Coverage is explicitly incomplete; this finding is not a completion or closure claim. Recommended action for PR #7203: KEEP. Only the mechanism and the Enter half landed in PR #548; the Tab half this PR adds has no coverage anywhere, so nothing here justifies closure. Files: website/src/components/TerminalCompletion.tsx.

No PR, Issue, label, branch, or review state was changed by the relationship-note portion of this audit.

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.

3 participants