Skip to content

Refactor interfaces, fix context propagation, and reduce delays - #666

Merged
edenreich merged 3 commits into
mainfrom
refactor/segregate-interfaces-fix-context
Jun 27, 2026
Merged

edenreich merged 3 commits into
mainfrom
refactor/segregate-interfaces-fix-context

Conversation

@edenreich

Copy link
Copy Markdown
Contributor

Segregates ConversationRepository and StateManager into focused sub-interfaces (MessageRepository, TokenUsageRepository, ViewManager, etc.) for better dependency management. Fixes context propagation in agent tool calls by passing the request-scoped context instead of context.Background(), adds error logging for state machine transitions, and reduces agent processing delays from 100ms to 20ms for improved responsiveness. Cleans up unused migration count variables in storage backends.

@edenreich
edenreich requested a review from a team as a code owner June 27, 2026 19:24
Comment thread internal/infra/storage/postgres.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 6m 17s —— View job


Code Review

I read the full diff against origin/main, verified method-set equivalence for both segregated interfaces, built the project, and ran the affected test packages. Overall this is a clean, well-scoped refactor. Build passes, all touched packages' tests pass. A few notes below, none blocking.

  • Read the full diff against origin/main
  • Review interface segregation (interfaces.go)
  • Review context propagation fix (agent.go)
  • Review state-machine error logging
  • Review timing/delay reductions
  • Review storage cleanup (postgres.go / sqlite.go)
  • Verify build & method-set equivalence
  • Post review

✅ Strengths

  • Interface segregation is correct and safe. I flattened both composed interfaces and diffed the method sets against origin/main: ConversationRepository (19 methods) and StateManager (68 methods) are identical before/after - no method dropped, added, or duplicated. Because the composed interfaces keep their original names, all existing implementations and the committed counterfeiter fakes (FakeConversationRepository, FakeStateManager) still satisfy them with no regeneration needed. The "new code should depend on the narrower sub-interfaces" doc comments are a nice touch.
  • Error logging on state transitions (agent_event_driven.go, agent_streaming.go) is a real observability win - silently swallowing Transition() errors with _ = hid genuine failures.
  • Storage cleanup (postgres.go:95, sqlite.go:68) removes a confusing _ = appliedCount no-op block. Confirmed the time import is still used elsewhere in both files, so no unused-import breakage.

🔍 Findings

1. Stale doc comment in completing.go (nit)
The inline Debug log was updated to 20ms, but the struct doc at internal/agent/states/completing.go:16 still reads "Performs a final 100ms queue check". Worth syncing to avoid drift.
Fix this →

2. activate_app.go 300ms→50ms - the one delay that touches an external system (worth validating)
internal/agent/tools/activate_app.go:89 sleeps after ActivateApp() and before verifying with GetFrontmostApp(). Unlike the other reductions (internal goroutine settle windows), this one waits on the macOS window server, where focus switches are async and latency is less predictable. If 50ms is too short, the check at line 92 fails and the tool returns the weaker "Attempted to activate" result (line 105) instead of the confirmed "is now in focus" (line 93). Both still return Success: true, so it's not a hard failure - just a degraded confirmation signal to the LLM. Recommend validating on real hardware; a larger margin here (e.g. 100-150ms) may be safer than the internal 20ms values.

3. The context-propagation fix is correct hygiene but currently behaviorally inert (FYI, not a bug)
Passing ctx instead of context.Background() at agent.go:790 and agent.go:875 is the right thing to do. However, all three ShouldRequireApproval implementations in internal/services/approval_policy.go (Standard/Permissive/Strict) ignore the ctx parameter - the agent mode is resolved via stateManager.GetAgentMode(), not from context values. So this changes no observable behavior today; it's good future-proofing (cancellation/tracing/values) rather than a fix for a live bug. Flagging only so the "Fixes context propagation" framing isn't mistaken for a behavioral change.

4. 3 of the 5 reduced timing constants are unused (pre-existing dead code)
In internal/constants/timing.go, only AgentIterationDelay (used in agent_streaming.go:30) and AgentToolExecutionDelay (used in agent.go) are actually referenced. AgentParallelToolsDelay, AgentConversationSaveDelay, and CompletionCheckDelay have no references anywhere, so reducing their values is a no-op. This predates the PR, but since you're touching these exact lines, a follow-up could delete the three dead constants. The behaviorally meaningful reductions are the two used constants plus the hardcoded sleeps in completing.go, bash.go, and a2a_task.go.

5. bash.go 100ms→20ms before background-detach (minor, confirm intent)
internal/agent/tools/bash.go:295 sleeps before DetachToBackground, which reads as a window to capture early stdout before handing the process off. 20ms is fine for the common case; just confirm it still captures enough startup output for commands that emit a quick line and exit right around the detach boundary.

Notes

  • The empty ```suggestion review comment on postgres.go looks like an accidental/empty submission - no action needed unless it was meant to convey something.
  • No mock regeneration required, but if future code starts depending on the narrow sub-interfaces in tests, you may eventually want dedicated counterfeiter fakes for them (the composed fakes already satisfy them today, so this is optional).

Verification

go build ./...                 ✅ passes
go test ./internal/agent/...   ✅ ok (agent, states, tools)
     ./internal/infra/storage/... ✅ ok (storage, migrations)
     ./internal/domain/...        ✅ ok
     ./internal/constants/...     ✅ (no test files)

Nice incremental refactor - the interface split and error logging are clear wins. My only substantive ask is to eyeball the activate_app.go 50ms on real macOS; everything else is nits/FYI.
· refactor/segregate-interfaces-fix-context

…ay, dead timing constants

- Fix stale doc comment in completing.go: update '100ms' to '20ms' to
  match the actual sleep duration in the code
- Bump activate_app.go delay from 50ms to 150ms: the macOS window server
  focus switch is async and less predictable than internal goroutine
  settle windows; 50ms risked degrading the confirmation signal to the
  weaker 'Attempted to activate' result instead of confirmed 'is now in
  focus'
- Remove 3 unused timing constants from timing.go:
  AgentParallelToolsDelay, AgentConversationSaveDelay, and
  CompletionCheckDelay had zero references anywhere in the codebase
@edenreich

Copy link
Copy Markdown
Contributor Author

Addressed review findings from @inference-gateway-maintainer[bot]:

1. Stale doc comment in completing.go (Finding #1) ✅ Fixed
Updated the struct doc comment from "Performs a final 100ms queue check" to "20ms" to match the actual time.Sleep(20 * time.Millisecond) in the code.

2. activate_app.go 300ms→50ms delay (Finding #2) ✅ Fixed
Bumped from 50ms to 150ms. The reviewer was right that this is the one delay that touches an external system (macOS window server) where focus switches are async and less predictable. 50ms risked degrading the confirmation signal to the weaker "Attempted to activate" result. 150ms provides a safer margin while still being more responsive than the original 300ms.

3. Dead timing constants (Finding #4) ✅ Fixed
Removed the 3 unused constants: AgentParallelToolsDelay, AgentConversationSaveDelay, and CompletionCheckDelay — confirmed zero references anywhere in the codebase via grep. Cleaned up gofmt alignment for the remaining constants.

4. Context propagation (Finding #3) — No action needed (FYI)
Agreed this is correct hygiene/future-proofing rather than a behavioral fix. The PR description's "Fixes context propagation" framing is accurate for the code change itself; the fact that current ShouldRequireApproval implementations don't yet use ctx values doesn't diminish the value of passing it correctly.

5. bash.go 100ms→20ms (Finding #5) — No action needed
Reviewed the detach flow: the 20ms sleep before DetachToBackground is sufficient for the common case of capturing early stdout. The wg.Wait() goroutine ensures all pipe readers have finished before detach proceeds, and outputBuffer already accumulates output regardless of timing. 20ms is fine here.

All tests pass, pre-commit hooks pass (lint, format, mocks, etc.). Ready for re-review.

@edenreich

Copy link
Copy Markdown
Contributor Author

@claude Check the changes. Is it ready for merge?

@inference-gateway-maintainer

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

Copy link
Copy Markdown
Contributor

Claude finished @edenreich's task in 6m 25s —— View job


Merge Readiness Check

  • Read the full diff against origin/main
  • Verify the 3 review findings were addressed (doc comment, activate_app delay, dead constants)
  • Verify interface segregation correctness (method-set equivalence)
  • Build the project
  • Run affected test packages
  • Post merge-readiness verdict

✅ Ready for merge

I re-checked the latest state of the branch (HEAD 951477c) against origin/main. All three actionable findings from the previous review are correctly addressed, the interface refactor is provably behavior-preserving, and build + vet + tests are green.

Review findings - all resolved

# Finding Status
1 Stale 100ms doc comment in completing.go ✅ Updated to 20ms (matches the time.Sleep(20 * time.Millisecond))
2 activate_app.go delay too aggressive for the macOS window server ✅ Set to 150ms (a safer margin than the 50ms I flagged, still faster than the original 300ms)
4 3 dead timing constants ✅ Removed AgentParallelToolsDelay, AgentConversationSaveDelay, CompletionCheckDelay - confirmed zero references remain; the two live constants (AgentIterationDelay, AgentToolExecutionDelay) are still used

Findings #3 (context propagation - correct hygiene, behaviorally inert today) and #5 (bash.go 20ms detach window) were FYI-only and need no change.

Interface segregation - verified pure refactor

I went beyond a visual diff and compared the flattened, reflection-derived method sets of the composed interfaces on this branch vs. origin/main (via a throwaway worktree). They are byte-for-byte identical:

ConversationRepository:  19 methods  →  19 methods   (diff: identical)
StateManager:            68 methods  →  68 methods   (diff: identical)

No method added, dropped, renamed, or signature-changed - so all existing implementations and the committed counterfeiter fakes (FakeConversationRepository, FakeStateManager) still satisfy the interfaces with no regeneration needed.

Extra safety checks

  • a2a_task.go 100ms→20ms: safe. ResultChan is a buffered channel (cap 1) (a2a_task.go:253), so the send before the sleep never blocks and the result cannot be lost regardless of the delay - the sleep is only a grace window.
  • Storage cleanup (postgres.go / sqlite.go): the dead _ = appliedCount blocks are gone; ApplyMigrations's error is still propagated and the time import remains used.
  • State-machine error logging compiles cleanly (logger wired in both files).

Verification

go build ./...                                 ✅ passes
go vet   ./internal/agent/... storage/... ...  ✅ passes
go test  ./internal/agent/...                  ✅ ok (agent, states, tools)
         ./internal/infra/storage/...          ✅ ok (storage, migrations)
         ./internal/domain/...                 ✅ ok
gofmt    internal/constants/timing.go          ✅ aligned correctly

One non-blocking note

The activate_app.go 150ms can only be definitively validated on real macOS hardware (CI here is Linux). Even if it ever proves slightly short, the consequence is only a degraded confirmation message ("Attempted to activate" vs "is now in focus") - both still return Success: true, so it is not a hard failure. 150ms is a sensible conservative choice.

Verdict: No blocking issues. This is a clean, well-scoped, behavior-preserving refactor with real observability and responsiveness wins. 👍 Ready to merge.
· refactor/segregate-interfaces-fix-context

@edenreich
edenreich merged commit 1a93ff8 into main Jun 27, 2026
1 check passed
@edenreich
edenreich deleted the refactor/segregate-interfaces-fix-context branch June 27, 2026 20:01
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
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