18 KiB
18 KiB
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<Task<()>> 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<Resampler> 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<Result<(), Error>> (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.rsduplicatedh_flex,v_flex,StyledExt,focus_handle,focus_ringfromcomponents/common.rs. The copies are deleted;layout/mod.rsre-exports the canonical ones so externalui::layout::…paths keep working. The one component-internal importer (dialog.rs) now imports fromcomponents::common. - D2 New shared builders in
components/common.rsandempty_state.rs:floating_panel(cx, radius, panel, shadows)(generic overStyled, so it slots into existing chains),paint_highlighted_row(mouse-move-driven rows),wrapping_adjacent_selectable, andEmptyState::compact. Each had 3+ verified call sites and no equivalent. - D3
ButtonVariant::chrome(cx)returns aButtonChrome(background, foreground, hover, pressed, and the three border states);Button::renderconsumes it. - D4
tabs.rsgainedtab_label_colorandapply_tab_chrome, shared byrender_tabandrender_group_tab. - D5 Theme tokens for recurring literals:
Theme::ui_font(),WINDOWS_CLOSE_*moved intocolors.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 throughfloating_panel;MenuChromeshed itssurface/radius_overlay/shadowfields. Command palette and dialog pass their dialog-elevation shadows to keep visuals identical. - E2 Combobox and command-palette rows use
paint_highlighted_row. Menurow_shellkept 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_keynavigate viawrapping_adjacent_selectable. Note: menudown/uppreviously clamped at the ends; they now wrap, per the plan. - E4
dropdown_menuconsumesButtonVariant::chromefor trigger colors and borders. - E5 Combobox and command-palette popups render
uniform_listsizedrows * row_heightcapped atPOPUP_MAX_HEIGHT, per the AGENTS.md convention. Scroll positions persist throughrows_scroll: UniformListScrollHandlefields 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 inSpeechButtonandSpeechWaveform; the bar color is a closure because the waveform paints silent levels muted and the button does not. - E8 Render-path caches: (1)
CodeViewStatecaches per-line text and syntax roles (CodeLineLayout) rebuilt onset_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_textreuses the previousShapedTextwhile the text, wrap width, font, size, and color are unchanged (ShapeCacheKey,RefCellso the paint-phase caller needs no entity update);ShapedLineEntry.lineisArc<WrappedLine>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 atTREE_MAX_DEPTH = 16instead ofu32::MAX as f32; segmented ids are("segment", index)so same-label segments cannot collide.
App de-duplication (F)
- F1
shared/widgets.rsgainedcentered_spinner(five pure copies migrated; therepo/mod.rsvariant that pairs a spinner with a status label stays inline — different shape),scroll_overlay(all seven scrollbar overlays), andclone_row(moved fromrepo/helpers.rs;header.rsimports it).error_rowis the single inline-error convention (new.rs,send_patch.rs,grasp_servers.rsmigrated); the two banner-levelAlertuses remain Alerts. The inbox unread dot isui::status_dot::StatusDot; the inbox-localempty_stateand the hand-centered wrapper inissues/mod.rsare gone in favor ofshared::widgets::empty_state; the issues detail "Loading…" pseudo-empty-state iscentered_spinner(the PR detail equivalent was already a spinner). - F2 File-level
+/−counts incommit_diff.rsareBadges (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 sharedpx_4 border_b_1 bg(muted)skeleton), andROW_HEIGHT = 73.issues/mod.rsandpull_requests/mod.rsrender through it; both headers build viafilter_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_listinshared/event_list.rsis the uniform commit-list scaffold (rows + optional per-row action + scrollbar overlay), migratedrepo/history.rs,pull_requests/detail.rs, andpull_requests/new.rs. - F5
shared/progress.rsgainedrun_dialog_task(close on success, fail on error) andrun_dialog_task_with(explicit success/error sinks). Onboarding, passphrase, and create/init dialogs use them;init.rs/create.rsprivatefailwrappers are deleted in favor of directDialogProgresscalls.identity/import.rskeeps a thinfinish_importbecauseImportStatewrapsDialogProgressrather than being one. - F6
announcement_display_name(five hand-rolled copies inrepo/helpers.rs,repo/mod.rstitle,explore/helpers.rs,pull_requests/helpers.rs— whosefork_display_nameis deleted — andinbox/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 inreload_worktree/catch_up_worktree),preferred_branch(the announced →main→ first fallback innew/source.rs),track_event_participants(the duplicated author/commenter/owner tracking in the two detail views). - F7 Render-path clones: commit lists store
Arc<Vec<FileCommit>>(history also keepsArc<CommitList>), assigned once per load and cloned per frame as an Arc;RepositorySwitcher.entriesand its filteredvisiblerows are Arc'd. - F8 The no-op
RepoItem::Patcharm inopen_repo_itemcollapsed into_ => {}with a comment;RepoItemkeeps the variant. - F9
issues/mod.rsISSUE_ROW_HEIGHTand the PRROW_HEIGHTunified intoevent_list::ROW_HEIGHT;exploreCARD_HEIGHTdecomposition 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,#aabbccresolve),input.rs(reversed UTF-16 ranges order instead of panic; off-boundary byte offsets floor;floor_to_char_boundaryclamps),resizable.rs(sub-floor resize clamps to the floor; negativeset_pane_widthclamps toPANE_MIN_SIZE),tests/tabs.rs(pinned=truedraws inline and selects;closeableclose control reports the tab index). - G2 Root
[workspace.lints.clippy]:all,perf,unwrap_used— alldeny, withclippy.tomlallow-unwrap-in-tests = true; every crate opts in via[lints] workspace = true.cargo clippy --workspace --all-targets -- -D warningsis clean. Fixes en route: the twoseries.last().unwrap()loop invariants insigned_core/src/pull_request.rsnow track the tail explicitly, and the four hardcoded relay parses insigned_state/src/backend.rsuseexpect. - 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 exerciseTheme::initand the macOS Drop path).
Report-only items (need a product call)
- Unlinked
inboxmodule (signed_app/src/inbox):InboxViewhas 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/uicomponents: left in place as library stockpile; the components participate in the shared refactors above, so nothing dead was deleted. DefaultHasherin-session caveat (repo/helpers.rsstable-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.
AnyThreadmain-thread caveat (ui/src/theme/source/macos.rs:7): theme reads useAnyThreadaccessors 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.rscaption-button cfg blocks,windows.rstheme 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 (
EventBuilderpaths insigned_state): tag parsing usesexpecton statically valid tags; no user-controlled panics found. - Deserialization paths:
Settingsserde 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.stripsis keyed by window + strip id, now with per-strip tab pruning (B2).