Repository navigation
refactor: dead-code cleanup, Go 1.26 modernization, width-aware truncation, race testing - #667
Conversation
Remove functions, types and files unreachable from main, confirmed via the
deadcode tool plus per-symbol grep. Build, golangci-lint (0 issues) and the
full test suite stay green; deadcode drops 84 -> 39 (the remainder are
test-only or interface/registry-dispatched false positives).
Notable removals:
- internal/services/middleware: whole package was never imported; its
ApprovalMiddleware was only exercised by its own tests and is superseded by
the agent approval flow (config.ResolveApprovalDelivery + requestToolApproval).
- internal/logger/{context,testing}.go: vestigial context/test helpers, no callers.
- internal/services/chat.go: unused StreamingChatService wrapper.
- formatting: FormatMessage/FormatError/FormatEnabled/FormatDisabled/
FormatResponsiveCodeBlock and the now-orphaned MessageType.
- ui/styles: dead diff-line color helpers and the unused CommonStyles.
- diffview: unused fluent-builder setters (defaults remain wired).
- config: IsKnownAgent, MergeMCP, ResolveEnvironmentVariables, ReleasePort.
- misc: domain title predicates, display registry getters, container
GetChatEventListener/RegisterShortcut, coordinate_scaler ScaleScreenToAPI,
keys IsKeyOrPrintable.
- Replace sort.Strings/sort.Ints with slices.Sort (19 sites) and sort.Slice/sort.SliceStable with slices.SortFunc/SortStableFunc using cmp.Compare (and time.Time.Compare for time-keyed comparators) (17 sites). - Convert the root and version commands from Run to RunE so errors propagate. - Drop the hand-rolled min() in renderer_test.go for the Go 1.21+ builtin. Behaviour-preserving; build, golangci-lint (0 issues) and the full test suite stay green.
The byte-based truncators (formatting.TruncateText and three duplicates) measured length with len() and sliced with s[:n], which over-counts width for multibyte runes and splits emoji/CJK graphemes mid-codepoint, producing mojibake in message previews, conversation titles and task rows. Make formatting.TruncateText the single width-aware truncator using charmbracelet/x/ansi (StringWidth + grapheme-safe Truncate), then route every duplicate through it and delete the copies: - agent_utils.truncateString (free func) + its test - task_management_view.truncateString + its now-unused stripAnsi helper - conversation_selection_view.truncateString - the inline len()/byte-slice in conversation_view Adds a table-driven TestTruncateText covering ASCII edges plus emoji/CJK width and grapheme-boundary invariants. Promotes charmbracelet/x/ansi to a direct dep.
HelpBar.Render (called from View every frame) rebuilt three lipgloss styles on each render. Cache them and rebuild only when the active theme colours change, so the steady-state render allocates nothing - per lipgloss-v2 guidance not to build NewStyle chains inside View. Also replace a time.Sleep inside a tea.Cmd in chat.go with tea.Tick - the idiomatic, cancellable way to defer a message (the sleep blocked a goroutine for 500ms rather than the UI, but tea.Tick is the correct primitive).
agent_test_additions.go held Test* functions but, lacking the _test.go suffix, was compiled into the package build rather than the test binary, so `go test` never ran them. Rename it to _test.go; the six TestEventPublisher_PublishToolExecutionCompleted sub-tests now run and pass, recovering real coverage of publishToolExecutionCompleted.
Add a `test:race` task (go test -race ./...) and a CI step that runs it. The race detector is the best safeguard for this event-driven, goroutine-heavy codebase against future data races; the current suite passes it cleanly across all packages.
|
@claude Can you review this? |
|
Claude finished @edenreich's task in 5m 33s —— View job Review: dead-code cleanup, Go 1.26 modernization, truncation, race testingReviewed the full diff against
What I verifiedDead-code removal - safe. Grep-confirmed every removed exported symbol is unreferenced: Truncation fix - a real bug fix, not just cleanup. Sort modernization - all directions correct. This is where conversions usually break; they don't here:
help-bar caching - correct. Test activation. The rename adds the missing Minor / optional notes (none blocking)
Verdict: LGTM. Mechanical changes are faithful, the truncation consolidation fixes a real panic path, and adding
|
For 0 < maxLength < 3 the function returned "..." (width 3), exceeding the column budget its doc promises. Return min(maxLength) dots instead so the result never exceeds maxLength. No caller passes a width that small today, so this is a contract-correctness fix. Adds maxLength 1 and 2 test cases.
The test job ran `go test ./...` then `go test -race ./...` sequentially; the race run is a superset, so the plain run only added wall-clock time. Keep the race run. The Taskfile still exposes both `test` and `test:race` for local use.
## [0.125.0](v0.124.1...v0.125.0) (2026-06-28) ### 🚀 Features * **reminders:** configurable reminders on a shared hook-point catalog ([#675](#675)) ([179cad1](179cad1)), closes [#270](#270) [#669](#669) [#270](#270) [#525](#525) [#270](#270) * **channels:** retain inbound voice/audio recordings with bounded cleanup ([#671](#671)) ([8fd29ce](8fd29ce)) * **hooks:** run configured shell commands at agent hook points ([#676](#676)) ([990f2c0](990f2c0)), closes [#270](#270) [#675](#675) [#675](#675) [#270](#270) [#675](#675) [#675](#675) [#669](#669) [#270](#270) ### 🐛 Bug Fixes * **agent:** keep the internal completion check out of channel replies ([#672](#672)) ([96b166c](96b166c)) * **docs:** replace em dashes with hyphens for consistency in SKILL.md and configuration-reference.md ([1c9196d](1c9196d)) ### ♻️ Code Refactoring * dead-code cleanup, Go 1.26 modernization, width-aware truncation, race testing ([#667](#667)) ([7a97f3b](7a97f3b)) * interfaces, fix context propagation, and reduce delays ([#666](#666)) ([1a93ff8](1a93ff8)) ### 📚 Documentation * **skills:** add charm v2 skills (bubbletea, lipgloss, bubbles) ([#664](#664)) ([c7242c7](c7242c7)), closes [#657](#657) [#663](#663) * **skills:** add Go skills adapted from spf13/go-skills ([#665](#665)) ([971ac23](971ac23)) * **skills:** add go-concurrency skill ([#663](#663)) ([c77ac33](c77ac33)), closes [#657](#657) ### ✅ Tests * relax TestSessionID_Age_Recent upper bound to tolerate slow CI ([#673](#673)) ([9cfe203](9cfe203)), closes [#671](#671)
|
🎉 This PR is included in version 0.125.0 🎉 The release is available on: Your semantic-release bot 📦🚀 |
) ## The crash `infer chat` panics and tears down the TUI the moment `/` is typed: ``` strings: negative Repeat count strings.Repeat(...) tui/autocomplete.(*AutocompleteImpl).renderItems(..., 0x3, 0x1c, 0xb3) autocomplete.go:981 ``` ## Root cause — bytes used as display columns `formatting.TruncateText` cuts to **display columns** (`ansi.StringWidth` / `ansi.Truncate`), but `renderItems` padded the result with `len()` — **bytes**: ```go description := formatting.TruncateText(cmd.Description, descWidth) paddedDescription := description + strings.Repeat(" ", descWidth-len(description)) ``` One multibyte rune in a description long enough to be truncated pushes `len()` past the column budget and the count goes negative. Reproduced with the exact values from the trace: at a 214-column terminal `descWidth = 214 - 28 - 7 = 179` (the `0xb3`). The `motion-graphics` skill description truncated to 179 columns is **181 bytes** → `strings.Repeat(" ", -2)`. ## Why it surfaced now The code was correct until the contract changed under it: | when | what | | --- | --- | | 2026-06-27 | #667 flips `TruncateText` from `len(text) <= maxLength` (bytes) to `ansi.StringWidth` (columns) — this caller was not touched, and its padding silently became wrong | | 2026-07-31 | #973 wires the skills catalog into the autocomplete list, so skill descriptions reach this renderer | | 2026-09-16 | `inference-gateway/skills#132` adds `motion-graphics` — the only one of 25 catalog entries with a non-ASCII description (`—` U+2014, `→` U+2192) | Before #667 `len(truncated) <= maxLength` was guaranteed, so the subtraction could never go negative. Nothing in the CLI changed in September; the catalog data did. ## The fix One helper beside the function whose contract caused it, so truncation and padding always happen in the same unit: ```go func PadText(text string, width int) string { text = TruncateText(text, width) return text + strings.Repeat(" ", max(0, width-ansi.StringWidth(text))) } ``` - `autocomplete.go` — both columns route through `PadText`; `calculateMaxShortcutWidth` measures with `ansi.StringWidth` instead of `len`. - `task_management_view.go` — the two separators now use the `getSeparatorWidth()` guard that already existed for exactly this case (`strings.Repeat("─", t.width-4)` panics below 4 columns, and `t.width` is 0 until the first `WindowSizeMsg`). One copy had no guard; the other inlined a duplicate of it, now deleted. `lipgloss.NewStyle().Width(n)` was considered and rejected — it *wraps* overflow instead of truncating, which would turn one table row into several. ## Tests - `TestPadText` — table-driven, asserts `ansi.StringWidth(got) == width` and valid UTF-8 across narrow-multibyte, wide-rune and ASCII inputs. - `TestAutocomplete_RenderMultibyteDescription` — feeds the real failing shape at 214/60/20 columns and asserts the rows stay column-aligned. Verified the regression test earns its keep: reverting just the two pad lines makes it panic with the identical `strings: negative Repeat count`; restoring the fix passes. ## Checks - `task precommit:run` — 0 issues - `go test ./internal/presentation/... ./internal/platform/...` — green ## Notes No docs ticket: bug fix, no public surface change. No cross-repo impact — the trigger data lives in `inference-gateway/skills`, but nothing there needs changing. Found during the sweep, left for separate PRs: - `task_management_view.go:1116-1152` pads with `%-38s` (rune count) against a column budget — misalignment only, no panic. - `agent/infrastructure/formatter.go:258` still does a raw `text[:maxLength-3]` byte slice and emits invalid UTF-8 on multibyte input; its own test documents this at `formatter_units_test.go:86`.
Codebase audit and refactor across five themes — quick wins, dead-code cleanup, charm-framework usage, a real truncation bug, and testability. Findings were produced by exploration agents and then independently verified against the source and the repo's own tooling before any change; most of the raw high-severity findings turned out to be false positives and were deliberately dropped (see below).
buildOK · 44 packages pass (0 failures) ·golangci-lint0 issues ·go test -race ./...clean ·deadcode84 → 38 · net −1192 lines.Commits
refactor: remove dead code— removed ~45 functions unreachable frommain(deadcode-confirmed + per-symbol grep), including the entirely-unwiredinternal/services/middlewarepackage (itsApprovalMiddlewarewas only exercised by its own tests; superseded by the real approval flow) and the vestigial logger context/test helpers.refactor: modernize to Go 1.26 stdlib—sort.Strings/Ints→slices.Sort(19),sort.Slice→slices.SortFuncwithcmp.Compare/time.Time.Compare(17),Run→RunEon root/version, dropped a hand-rolledmin().fix: width-aware text truncation— byte-based truncators (len()+s[:n]) split emoji/CJK graphemes and over-count width, producing mojibake in message previews, conversation titles and task rows.formatting.TruncateTextis now the single grapheme-safe truncator (viacharmbracelet/x/ansi); the three duplicates were deleted. Adds a table-driven test with emoji/CJK width and grapheme invariants.refactor: cache help-bar lipgloss styles; use tea.Tick—HelpBar.Render(called fromViewevery frame) rebuilt three lipgloss styles per frame; now cached and rebuilt only on theme change. Also replaced atime.Sleepinside atea.Cmdwithtea.Tick.test: activate dormant event-publisher tests—agent_test_additions.golacked the_test.gosuffix, so its sixTest*functions never ran. Renamed; they now run and pass, recovering coverage ofpublishToolExecutionCompleted.ci: run tests with the race detector— added atest:racetask and a CI step; the suite passes-racecleanly across all packages.On "leaked goroutines"
None found. Verification showed the concurrency posture is sound (buffered hand-offs, guarded
closes, honoredctx, Go 1.26 timer GC), so this PR invests in catching future races:go test -race ./...now runs in CI and passes clean, andgovet'slostcancelanalyzer (already enabled) is green.Verified false positives (intentionally not changed)
tea.KeyMsg"is a v1-ism" — it is a valid v2 interface implemented byKeyPressMsg.agent.gotool goroutine "leaks on cancel" — it sends to a buffered channel; no leak.time.After"leaks timers" — moot on Go 1.26 (GC'd since 1.23).defer cancel()— already guarded.