Skip to content

refactor: dead-code cleanup, Go 1.26 modernization, width-aware truncation, race testing - #667

Merged
edenreich merged 11 commits into
mainfrom
refactor/cleanup-deadcode-quickwins
Jun 27, 2026
Merged

edenreich merged 11 commits into
mainfrom
refactor/cleanup-deadcode-quickwins

Conversation

@edenreich

Copy link
Copy Markdown
Contributor

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).

build OK · 44 packages pass (0 failures) · golangci-lint 0 issues · go test -race ./... clean · deadcode 84 → 38 · net −1192 lines.

Commits

  • refactor: remove dead code — removed ~45 functions unreachable from main (deadcode-confirmed + per-symbol grep), including the entirely-unwired internal/services/middleware package (its ApprovalMiddleware was 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.SortFunc with cmp.Compare/time.Time.Compare (17), Run → RunE on root/version, dropped a hand-rolled min().
  • 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.TruncateText is now the single grapheme-safe truncator (via charmbracelet/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 from View every frame) rebuilt three lipgloss styles per frame; now cached and rebuilt only on theme change. Also replaced a time.Sleep inside a tea.Cmd with tea.Tick.
  • test: activate dormant event-publisher tests — agent_test_additions.go lacked the _test.go suffix, so its six Test* functions never ran. Renamed; they now run and pass, recovering coverage of publishToolExecutionCompleted.
  • ci: run tests with the race detector — added a test:race task and a CI step; the suite passes -race cleanly across all packages.

On "leaked goroutines"

None found. Verification showed the concurrency posture is sound (buffered hand-offs, guarded closes, honored ctx, Go 1.26 timer GC), so this PR invests in catching future races: go test -race ./... now runs in CI and passes clean, and govet's lostcancel analyzer (already enabled) is green.

Verified false positives (intentionally not changed)

  • Conditional model reassignment "loses state" — safe; all UI components use pointer receivers.
  • tea.KeyMsg "is a v1-ism" — it is a valid v2 interface implemented by KeyPressMsg.
  • agent.go tool 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).
  • A2A poller "double-close panic" / missing defer cancel() — already guarded.

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.
@edenreich
edenreich requested a review from a team as a code owner June 27, 2026 21:04
Comment thread internal/agent/agent_utils.go Resolved
Comment thread internal/formatting/formatting_test.go Resolved
Comment thread internal/ui/components/help_bar.go Resolved
@edenreich

Copy link
Copy Markdown
Contributor Author

@claude Can you review this?

@inference-gateway-maintainer

inference-gateway-maintainer Bot commented Jun 27, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @edenreich's task in 5m 33s —— View job


Review: dead-code cleanup, Go 1.26 modernization, truncation, race testing

Reviewed the full diff against origin/main (51 files, +206/-1407). This is a clean, well-disciplined PR - the "verified false positives" section is exactly the kind of rigor these audits need, and the high-risk pieces (sort-direction flips, truncation behavior, dead-code reachability) all hold up under scrutiny.

Note: go build / go test / golangci-lint required approval in my sandbox and didn't run, so my verification is static (diff reading + per-symbol grep). The CI step this PR adds (go test -race ./...) plus the existing build/test/lint cover the executable verification.

What I verified

Dead-code removal - safe. Grep-confirmed every removed exported symbol is unreferenced: FormatResponsiveCodeBlock, FormatMessage/Error/Enabled/Disabled, the services/middleware + services/chat packages, logger context/testing helpers, MergeMCP, ResolveEnvironmentVariables, ReleasePort, IsKnownAgent, GetChatEventListener, RegisterShortcut, the agent-package truncateString, the diffview builder methods, ScaleScreenToAPI, and the conversation title helpers. In container.go the RegisterShortcut wrapper is gone but shortcutRegistry.Register(...) is still called directly (container.go:455+), so the shortcuts import stays live - no dangling import.

Truncation fix - a real bug fix, not just cleanup. formatting.TruncateText (formatting.go:76-87) via ansi.StringWidth/ansi.Truncate is correct, and consolidating the three byte-based duplicates removes genuine latent bugs - notably conversation_view.go:~2503 previously did truncatedMsg[:availableWidth-3], which panics (slice bounds out of range) whenever availableWidth < 3. go.mod correctly promotes charmbracelet/x/ansi from indirect → direct.

Sort modernization - all directions correct. This is where conversions usually break; they don't here:

  • Descending (most-recent-first) in jsonl.go/memory.go/redis.go correctly swaps operands: b.UpdatedAt.Compare(a.UpdatedAt). ✔
  • Ascending in channel_manager.go (prune oldest) and scheduler/store.go keeps a,b order. ✔ The nil-Info case maps false→0 faithfully.
  • tree.go dirs-first-then-name and the keybinding multi-key comparators (registry.go) are behavior-equivalent.

help-bar caching - correct. refreshStyles (help_bar.go:85-98) keys the cache on accent+dim, which are the only inputs to the three styles; first render always rebuilds (zero-value "" ≠ real color). tea.Tick replacing the blocking time.Sleep in a tea.Cmd (chat.go:399) is the idiomatic fix.

Test activation. The rename adds the missing _test.go suffix and the six TestEventPublisher_* funcs are real. I also swept for the same bug elsewhere - no other Test* functions are stranded in non-_test.go files.

Minor / optional notes (none blocking)

  1. TruncateText width contract for 0 < maxLength < 3 (formatting.go:83-85): returns "..." (width 3), which exceeds the budget the doc comment promises ("fit within maxLength display columns"). This is pre-existing (the canonical function always did this) and no caller passes a width that small (smallest in the tree is 15), so it's cosmetic - flagging only for contract-correctness. Fix this →
  2. CI runs the suite twice (ci.yml): go test ./... then go test -race ./.... The race run supersedes the plain one; dropping the plain run roughly halves test wall-time, or keep both if you want the faster non-race signal first. Your call.
  3. MergeMCP removal is correct (dead), but it was the only mcp.yaml-over-base layering helper - worth a mental note in case that merge was planned-but-unwired rather than abandoned. Not something to change in this PR.
  4. The fromatting import-alias typo you flagged in your own review is already fixed in 91048aa. ✔

Verdict: LGTM. Mechanical changes are faithful, the truncation consolidation fixes a real panic path, and adding -race to CI is a good investment. The notes above are all optional.


  • Read the diff against origin/main
  • Review dead-code removal for correctness
  • Review the width-aware truncation fix
  • Review Go 1.26 modernization (slices/cmp)
  • Review help-bar caching + tea.Tick
  • Review test activation + race CI
  • Post review feedback
    · branch refactor/cleanup-deadcode-quickwins

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.
@edenreich
edenreich merged commit 7a97f3b into main Jun 27, 2026
1 check passed
@edenreich
edenreich deleted the refactor/cleanup-deadcode-quickwins branch June 27, 2026 21:47
inference-gateway-releaser Bot added a commit that referenced this pull request Jun 28, 2026
## [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)
@inference-gateway-releaser

Copy link
Copy Markdown
Contributor

🎉 This PR is included in version 0.125.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

@inference-gateway-releaser inference-gateway-releaser Bot added the released Shipped in a release label Jun 28, 2026
edenreich added a commit that referenced this pull request Sep 20, 2026
)

## 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`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

released Shipped in a release

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant