# UI + app audit — November 2026 Audit of `crates/ui` (~15k lines) and `crates/signed_app` (~23k lines) against soundness, panics/bounds, concurrency/async, input boundaries, and idiom categories, plus the standing ask to migrate duplicated elements into shared components. Every finding below was verified at its cited line before fixing; line numbers refer to the tree at audit time and have shifted since. All fixes are in the tree; the full gate (`cargo fmt --all`, `cargo check --workspace`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo test --workspace`) is green. ## Fixed findings ### A. Soundness and panics | ID | Severity | File | Finding and fix | |----|----------|------|-----------------| | A1 | High | `ui/src/theme/source/macos.rs` | `MacosSource` never unregistered its NSDistributedNotificationCenter, KVO, and NSWorkspace observers, so a dropped source left observers delivering into freed memory. Added `impl Drop` that removes both distributed names, the three defaults key paths, and the workspace-center registration; registrations are recorded in a `Watcher` enum during `install_watchers`. Also added the missing `// SAFETY:` on `msg_send![super(this), init]` and replaced the three "as above" comments with per-block justifications. | | A2 | Medium | `ui/src/theme/definition.rs` | `parse_hex` sliced `digits[i..i+1]` by byte length, panicking on non-char-boundary input such as `#éa` from a malformed omarchy theme. Added an `is_ascii` guard after `strip_prefix('#')`; `color()` already logs and falls back. | | A3 | Medium | `ui/src/components/input.rs` | IME-supplied reversed `range_utf16` produced `start > end` byte offsets and sliced out of order in `text_for_range` and the UTF-16/UTF-8 converters. Both helpers now order endpoints; `utf8_range_to_utf16` additionally floors each endpoint to a char boundary (`floor_to_char_boundary`). | | A4 | Medium | `ui/src/components/code.rs` | `CodeViewState::update_line` spliced `0..1` on an empty source, a documented panic. It now early-returns when the source is empty; the `# Panics` section is gone. No in-workspace callers existed, so early-return is safe. | | A5 | Medium | `ui/src/layout/resizable.rs` | A drag clamped `size.min(ceiling)` without honoring `floor`, so a window smaller than the other panes' mins rendered a pane below its floor; `set_pane_width` accepted negative persisted sizes. Fixed both: `size.min(ceiling.max(floor))` and `width.max(PANE_MIN_SIZE)`. | | A6 | High | `signed_app/src/repo/helpers.rs` | `render_diff_row` indexed `hunks[hunk].lines[line]` with a stale captured index. Absent indices render a blank row of `DIFF_ROW_HEIGHT` instead of panicking. | | A7 | High | `signed_app/src/pull_requests/mod.rs`, `signed_app/src/issues/mod.rs` | List rows indexed `pull_requests[pr_ix]` / `issues[issue_ix]` with indices captured at rebuild while the store is re-read each frame. Both now use `.get()` and render an empty row when the entry is gone. | | A8 | High | `signed_app/src/repo/dialogs/reset.rs` | The destructive remote reset detached its task and closed the dialog immediately; failures were invisible. It now uses the stored-progress pattern (busy gate, `DialogProgress.fail`, close only on success, `update_window` result logged instead of `.ok()`-swallowed). The same `.ok()` swallows in `create.rs` and `init.rs` now log. | ### B. Async and task hygiene | ID | Severity | File | Finding and fix | |----|----------|------|-----------------| | B1 | High | `ui/src/components/toast.rs`, `combobox.rs` | Timer/report handles accumulated in `Vec>` forever. Toasts now keep one `dismiss_task` and one `fade_task` slot (each new timer replaces the previous, which also fixes stale fade timers finishing the wrong toast); the combobox keeps a single `task` slot, latest report wins. | | B2 | Medium | `ui/src/components/tabs.rs` | `TabsMeasurements.strips` grew forever. `retain_tabs` prunes per-strip tab measurements to the keys rendered inline this frame, before paint re-records them. | | B3 | Medium | `repo/mod.rs`, `repo/files.rs`, `repo/history.rs`, `repo/commit_diff.rs`, `pull_requests/detail.rs`, `pull_requests/new.rs` (+ `new/source.rs`), `inbox/mod.rs` | Task vecs were never reaped. Each owner struct got a private `push_task` that retains unfinished tasks before pushing; every `tasks.push` site routes through it. `new/source.rs` sites were in the same category as the plan list and are covered. | | B4 | Medium | `repo/dialogs/grasp_servers.rs`, `settings/helpers.rs` | Remove buttons used an index captured at render, which desyncs after a prior removal (removing the wrong row or silently nothing). All three editors now capture the value and remove with `iter().position()` + `remove`. | | B5 | Medium | `pull_requests/dialogs/update.rs`, `issues/new_issue.rs` | Submit had no busy gate; a double-click published twice. Both dialogs hold a `DialogProgress`, `begin()` on submit, and disable the button while busy. The store publishes detached and reports through `last_error` (surfaced by the parent view's Alert), so the dialog closes after firing, as before. | | B6 | Medium | `ui/src/components/speech.rs` | (1) The mic stream loop discarded the dead-app `cx.update` error and kept spinning; this gpui's `AsyncApp::update` returns the value directly and panics on a dead app, ending the loop, so the loop was simplified instead. (2) A poisoned `Mutex` silently dropped all audio; it now recovers via `into_inner()` with a `log::warn!`. (3) `error_handler` only logged; stream errors are now sent as `Err(String)` over the same flume channel as samples and reported on the UI thread through the generation-guarded state, firing `SpeechEvent::Error`. | | B7 | Medium | `pull_requests/send_patch.rs`, `signed_state/src/repo.rs` | The panel closed immediately after firing the publish; failures were invisible until some other view read `last_error`. `RepoStore::open_pull_request` now returns its publish `Task>` (early failures as `Task::ready(Err)`, `last_error` still set; `open_pull_request_from_refs` pushes the task into the store's vec), and `SendPatchView::submit` awaits it: stays open with `submitting` set, `fail(message)` on error, closes on success. | ### C. Error surfacing | ID | Severity | File | Finding and fix | |----|----------|------|-----------------| | C1 | Medium | `inbox/mod.rs` | `Inbox::query` failures only logged. The app-level `Toasts` entity lives in `AppRoot` and is not addressable from the inbox entity, so the plan's stated fallback applies: an inline dismissible `Alert` bound to a new `error` field, cleared on the next successful refresh. | | C2 | Medium | `repo/dialogs/init.rs` | Branch-load failure only logged, rendering an empty dropdown. `load_branches` now calls `DialogProgress::fail` so `error_row` renders inside the dialog. | | C3 | Low | `repo/history.rs` | "Failed to load commits" conflated a load error with an empty list. The load records `error`, and the render shows an inline `Alert` with the message (dismiss clears it). | | C4 | Low | `repo/files.rs` | The traversal-guard rejection returned silently. It now inserts `FileContent::Failed("Cannot open file")` so the content pane renders the shared empty state; a comment documents that tree paths originate from git, so only crafted components are rejected (symlink escapes are accepted). | ## Shared infrastructure added to `crates/ui` (D) and migrations (E) - **D1** `layout/mod.rs` duplicated `h_flex`, `v_flex`, `StyledExt`, `focus_handle`, `focus_ring` from `components/common.rs`. The copies are deleted; `layout/mod.rs` re-exports the canonical ones so external `ui::layout::…` paths keep working. The one component-internal importer (`dialog.rs`) now imports from `components::common`. - **D2** New shared builders in `components/common.rs` and `empty_state.rs`: `floating_panel(cx, radius, panel, shadows)` (generic over `Styled`, so it slots into existing chains), `paint_highlighted_row` (mouse-move-driven rows), `wrapping_adjacent_selectable`, and `EmptyState::compact`. Each had 3+ verified call sites and no equivalent. - **D3** `ButtonVariant::chrome(cx)` returns a `ButtonChrome` (background, foreground, hover, pressed, and the three border states); `Button::render` consumes it. - **D4** `tabs.rs` gained `tab_label_color` and `apply_tab_chrome`, shared by `render_tab` and `render_group_tab`. - **D5** Theme tokens for recurring literals: `Theme::ui_font()`, `WINDOWS_CLOSE_*` moved into `colors.rs` (the only color-literal home), `CODE_LINE_HEIGHT` (diff line height), `CHANGE_BAR_WIDTH` (diff change bar), `RESIZE_HANDLE_WIDTH` (resize seam + panel gutter), `OVERLAY_ICON_SIZE` (window controls), `TOOLTIP_ANCHOR_GAP` (tooltip placement). - **E1** All eight floating-panel stacks (toast pill, overlay alert, popover, dialog, combobox popup, command palette, menu panel via `MenuChrome`, tooltip) render through `floating_panel`; `MenuChrome` shed its `surface`/`radius_overlay`/`shadow` fields. Command palette and dialog pass their dialog-elevation shadows to keep visuals identical. - **E2** Combobox and command-palette rows use `paint_highlighted_row`. Menu `row_shell` kept its hand-rolled three-way painting: its selected state uses ramp colors plus a destructive variant and a flyout distinction the shared helpers do not express; migrating it would have moved the code rather than deduplicated it. - **E3** Combobox, command palette, and `handle_menu_key` navigate via `wrapping_adjacent_selectable`. Note: menu `down`/`up` previously clamped at the ends; they now wrap, per the plan. - **E4** `dropdown_menu` consumes `ButtonVariant::chrome` for trigger colors and borders. - **E5** Combobox and command-palette popups render `uniform_list` sized `rows * row_height` capped at `POPUP_MAX_HEIGHT`, per the AGENTS.md convention. Scroll positions persist through `rows_scroll: UniformListScrollHandle` fields on both states. - **E6** Both "No matches" captions use `EmptyState::compact`. - **E7** `waveform_bars(levels, size, cx, bar_color)` replaces the duplicated bar geometry and reduce-motion height logic in `SpeechButton` and `SpeechWaveform`; the bar color is a closure because the waveform paints silent levels muted and the button does not. - **E8** Render-path caches: (1) `CodeViewState` caches per-line text and syntax roles (`CodeLineLayout`) rebuilt on `set_source`/`update_line`; selection-dependent highlight runs are still computed per visible row, since they cannot be derived at source-change time. (2) `InputState::shape_current_text` reuses the previous `ShapedText` while the text, wrap width, font, size, and color are unchanged (`ShapeCacheKey`, `RefCell` so the paint-phase caller needs no entity update); `ShapedLineEntry.line` is `Arc` to make the cache cloneable. - **E9** Nits: inlined the single-use border alias in `select.rs`; identicon patterns are cached per seed in a thread-local (PRNG no longer reruns each frame); tree indent depth is clamped at `TREE_MAX_DEPTH = 16` instead of `u32::MAX as f32`; segmented ids are `("segment", index)` so same-label segments cannot collide. ## App de-duplication (F) - **F1** `shared/widgets.rs` gained `centered_spinner` (five pure copies migrated; the `repo/mod.rs` variant that pairs a spinner with a status label stays inline — different shape), `scroll_overlay` (all seven scrollbar overlays), and `clone_row` (moved from `repo/helpers.rs`; `header.rs` imports it). `error_row` is the single inline-error convention (`new.rs`, `send_patch.rs`, `grasp_servers.rs` migrated); the two banner-level `Alert` uses remain Alerts. The inbox unread dot is `ui::status_dot::StatusDot`; the inbox-local `empty_state` and the hand-centered wrapper in `issues/mod.rs` are gone in favor of `shared::widgets::empty_state`; the issues detail "Loading…" pseudo-empty-state is `centered_spinner` (the PR detail equivalent was already a spinner). - **F2** File-level `+/−` counts in `commit_diff.rs` are `Badge`s (`Success`/`Danger`), matching the commit-row counts. - **F3** New `shared/event_list.rs`: `EventList` (toolbar + `uniform_list` + `scroll_overlay` + empty state), `EventRow` + `event_row`/`event_meta_row` (badge, title, author avatar, "opened", short id, age, click handler), `filter_toolbar` (the shared `px_4 border_b_1 bg(muted)` skeleton), and `ROW_HEIGHT = 73`. `issues/mod.rs` and `pull_requests/mod.rs` render through it; both headers build via `filter_toolbar`. The detail-view meta rows were inspected and left alone: they render state verbs, merged-at labels, and multi-author lines that do not match the row meta shape. - **F4** `commit_list` in `shared/event_list.rs` is the uniform commit-list scaffold (rows + optional per-row action + scrollbar overlay), migrated `repo/history.rs`, `pull_requests/detail.rs`, and `pull_requests/new.rs`. - **F5** `shared/progress.rs` gained `run_dialog_task` (close on success, fail on error) and `run_dialog_task_with` (explicit success/error sinks). Onboarding, passphrase, and create/init dialogs use them; `init.rs`/`create.rs` private `fail` wrappers are deleted in favor of direct `DialogProgress` calls. `identity/import.rs` keeps a thin `finish_import` because `ImportState` wraps `DialogProgress` rather than being one. - **F6** `announcement_display_name` (five hand-rolled copies in `repo/helpers.rs`, `repo/mod.rs` title, `explore/helpers.rs`, `pull_requests/helpers.rs` — whose `fork_display_name` is deleted — and `inbox/mod.rs`), `short_id` (`..8`, now also used by the history sync tooltip, which took 7), `snapshot_worktree` (the duplicated worktree snapshot + tree + paths block in `reload_worktree`/`catch_up_worktree`), `preferred_branch` (the announced → `main` → first fallback in `new/source.rs`), `track_event_participants` (the duplicated author/commenter/owner tracking in the two detail views). - **F7** Render-path clones: commit lists store `Arc>` (history also keeps `Arc`), assigned once per load and cloned per frame as an Arc; `RepositorySwitcher.entries` and its filtered `visible` rows are Arc'd. - **F8** The no-op `RepoItem::Patch` arm in `open_repo_item` collapsed into `_ => {}` with a comment; `RepoItem` keeps the variant. - **F9** `issues/mod.rs` `ISSUE_ROW_HEIGHT` and the PR `ROW_HEIGHT` unified into `event_list::ROW_HEIGHT`; `explore` `CARD_HEIGHT` decomposition documented. Per-dialog widths (440/520/500/480/420) are intentional — see report-only items. ## Tests and lints (G) - **G1** New regression tests: `theme::definition::tests` (`#éa` → `None`; `#abc`, `#aabbcc` resolve), `input.rs` (reversed UTF-16 ranges order instead of panic; off-boundary byte offsets floor; `floor_to_char_boundary` clamps), `resizable.rs` (sub-floor resize clamps to the floor; negative `set_pane_width` clamps to `PANE_MIN_SIZE`), `tests/tabs.rs` (`pinned=true` draws inline and selects; `closeable` close control reports the tab index). - **G2** Root `[workspace.lints.clippy]`: `all`, `perf`, `unwrap_used` — all `deny`, with `clippy.toml` `allow-unwrap-in-tests = true`; every crate opts in via `[lints] workspace = true`. `cargo clippy --workspace --all-targets -- -D warnings` is clean. Fixes en route: the two `series.last().unwrap()` loop invariants in `signed_core/src/pull_request.rs` now track the tail explicitly, and the four hardcoded relay parses in `signed_state/src/backend.rs` use `expect`. - **G4** Full gate green: `cargo fmt --all` (clean under `--check`), `cargo check --workspace`, `cargo clippy --workspace --all-targets -- -D warnings`, `cargo test --workspace` (all suites pass, including the panel/sizing/tabs suites that exercise `Theme::init` and the macOS Drop path). ## Report-only items (need a product call) - **Unlinked `inbox` module** (`signed_app/src/inbox`): `InboxView` has no reference from any navigation surface today — the module compiles but nothing opens it. Left in place per the plan. Note: this audit still hardened it (C1, B3), so enabling it later starts from sound ground. - **11 zero-consumer `crates/ui` components**: left in place as library stockpile; the components participate in the shared refactors above, so nothing dead was deleted. - **`DefaultHasher` in-session caveat** (`repo/helpers.rs` stable-hash helper): SipHash keys are not stable across process restarts, so anything persisted from it would change. Currently only used for in-session identity — safe today, do not persist its output. - **Per-dialog widths** (440/520/500/480/420): deliberate distinct sizes, left alone. - **`AnyThread` main-thread caveat** (`ui/src/theme/source/macos.rs:7`): theme reads use `AnyThread` accessors on the main thread by convention; nothing enforces it. ## Verified-clean inventory From the three audit passes, checked and deliberately unchanged: - macOS/Windows unsafe blocks outside `theme/source/macos.rs` (`window_controls.rs` caption-button cfg blocks, `windows.rs` theme reads): bounds-correct, correctly gated. - Speech audio path beyond B6: sink/generation guards, stop-timeout handling, and the recognizer handoff are generation-guarded; no unguarded shared state found. - Command construction (`EventBuilder` paths in `signed_state`): tag parsing uses `expect` on statically valid tags; no user-controlled panics found. - Deserialization paths: `Settings` serde falls back per-field with defaults; theme definitions log-and-fall back (hardened further by A2); announcement parsing drops malformed clone/relay/maintainer values (covered by existing tests). - Clean files across all passes: `layout/panel.rs`, `layout/shell.rs`, `layout/titlebar.rs`, `components/segmented.rs`, `components/slider.rs`, `components/switch.rs`, `components/toggle.rs`, `components/status_dot.rs`, `components/tooltip.rs`, `components/grain.rs`, `shared/tree.rs`, `shared/panels.rs`, `explore/helpers.rs`, `issues/helpers.rs` (post-F1), `titlebar/repository_switcher.rs` (post-F7), `settings/*` (post-G2). - Bounded-growth notes: `AnchorBoundsRegistry` (`common.rs`) never evicts but is bounded by live windows × element ids (documented in-code); `TabsMeasurements.strips` is keyed by window + strip id, now with per-strip tab pruning (B2).