Repository navigation
feat(gateway): hermetic mock gateway with INFER_GATEWAY_MOCK mode, scenario e2e harness, streaming fixes - #817
Merged
Merged
Conversation
…flag race Three latent bugs surfaced by the new hermetic e2e harness (#815): - A failed GenerateContentStream (or stream timeout) transitioned the state machine to Error from the streaming goroutine without waking the event loop, leaving the loop blocked forever: the chat event channel never closed and both agent goroutines leaked. The transition now nudges the loop with a MessageReceivedEvent so it observes the terminal state. - Cancelling the context passed to RunWithStream aborted the HTTP stream but nothing closed the session cancel channel, parking the state machine in StreamingLLM indefinitely (this also affected non-interactive chat on gateway timeout). context.AfterFunc now propagates ctx cancellation to sessionCancel, which is idempotent via sync.Once. - Usage was only captured inside the per-choice loop, so the OpenAI-style final usage chunk (include_usage: true, choices: []) was silently dropped and token stats fell back to the tokenizer polyfill. Usage is now read before iterating choices. - Registry.SetReadToolUsed raced under parallel tool execution (several Read calls in one assistant turn); the flag is now an atomic.Bool.
…ence-gateway Adds internal/mockgateway, a stateless stand-in for the inference-gateway API surface the CLI consumes (GET /v1/models, POST /v1/chat/completions in both sync JSON and SSE streaming form, GET /v1/health). A scenario is selected by regex against the first user message; the turn within a scenario is derived from the assistant-message count already in the request, so the server needs no session state and is race-safe. - internal/mockgateway: handler, YAML scenario schema (strict decode), embedded built-in library of 13 scenarios (text, parallel tool calls, search, sequential tools, approval-blocked write, bash allow/block, 429-retry, hard 500, malformed SSE, slow stream, usage, reasoning), self-tests round-tripping frames through the SDK types - tests/mockgateway: standalone mock-gateway binary (-port, -scenarios) for manual runs and future terminal-automation harnesses; first stdout line is the readiness protocol - tests/integration: in-process e2e driving the real container, real SDK client and real SSE parsing through RunWithStream and Run - fragment accumulation, parallel tool dispatch, multi-turn loops, retry, hard errors, malformed frames, cancel mid-stream, usage capture - tests/e2e (build tag e2e): the built infer binary as a subprocess - headless JSON output contract, termination after two no-tool turns, parallel reads, write blocked without approver, bash allow-list gate, agent_error + non-zero exit, piped chat streaming - Taskfile: test:e2e and build:mockgateway targets
4 tasks done
…options resolveViperEnvironmentVariables built viper keys from the raw mapstructure tag, so fields tagged with options (e.g. "debug,omitempty") looked up gateway.debug,omitempty and their env overrides (INFER_GATEWAY_DEBUG, INFER_GATEWAY_OCI) never resolved. Strip tag options before building the key.
Interactive chat sends one growing conversation, so first-user-message routing pinned the whole session to whatever the first prompt matched and the assistant-count step never reset: every later prompt answered with the fallback. Anchor scenario matching on the latest user message that is not an injected <system-reminder> and count steps as the assistant messages after it. Each chat prompt starts its scenario at turn 0; the headless loop's automated-check reminder still never re-routes a run.
…rocess One env var for hermetic local runs: the container serves the scenario library from internal/mockgateway on an ephemeral localhost port, rewrites gateway.url to it and forces gateway.run off. infer chat lands in the model selection view with the mock model and every scenario works interactively; no real gateway, LLM, or API key involved.
Same directory the real gateway binary is downloaded to, instead of littering the repo root.
…paste functionality
Contributor
|
🎉 This PR is included in version 0.141.0 🎉 The release is available on: Your semantic-release bot 📦🚀 |
This was referenced Jul 10, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #815.
What
A hermetic end-to-end test harness for the agent: a mock inference-gateway that serves the exact API surface the CLI consumes, selecting canned scenarios via regex on the user prompt — no real LLM, no API key, deterministic and fast (the full binary e2e suite runs in ~6s). Plus a zero-config way to use it:
One env var: the container serves the embedded scenario library in-process on an ephemeral localhost port, rewrites
gateway.urlto it and forcesgateway.runoff. Chat lands in the model-selection view with the mock model; every scenario works interactively. Same forinfer agent -m openai/gpt-4o "...".Design (stateless by construction)
Every request carries the full message history, so the mock needs no session state:
<system-reminder>— each interactive chat prompt re-routes to its scenario, while the headless loop's automated-check reminder never re-routes a run.turns[step], so every new prompt restarts its scenario at turn 0; past the end, afallbackturn is served, which lets the headless "two consecutive no-tool-call turns" termination happen naturally.CreateChatCompletionResponse/...StreamResponse) for wire fidelity; the only mutable state is the error-injection counter and request recording. Zero new dependencies.Pieces
internal/mockgatewayhttp.Handler:/v1/models,/v1/chat/completions(sync JSON + SSE),/v1/health; YAML scenario schema (strict decode); embedded library of 13 scenarios;Requests()recording for assertionsconfig/internal/containergateway.mock(INFER_GATEWAY_MOCK): boots the mock in-process and points the SDK client at ittests/mockgatewaymock-gatewaybinary (-port,-scenarios) for custom scenario files and the future tmux TUI harness; first stdout line is the readiness protocoltests/integrationRunWithStream/Run— fragment accumulation, parallel tool dispatch, multi-turn loops, retry, hard errors, malformed frames, cancel mid-stream, usage capture. Runs in plaingo test ./...tests/e2e(-tags e2e)inferbinary as a subprocess: headless JSON output contract, termination rule, parallel reads, write blocked without approver, bash allow-list gate,agent_error+ non-zero exit, piped-chat streaming, one-env-var mock modeTaskfile/ CItask test:e2e,task build:mockgateway; newe2eCI jobStreaming tool-call arguments are deliberately emitted in ≥2 fragments per call so the CLI's index-keyed accumulator is always exercised; content chunks split on runes (UTF-8-safe).
Bugs the harness caught immediately (fixed here)
GenerateContentStream(or stream timeout) transitioned the state machine toErrorfrom the streaming goroutine without waking the event loop — the chat event channel never closed. Fixed with an event nudge after the transition.RunWithStreamaborted the HTTP stream but nothing closed the session cancel channel, parking the machine inStreamingLLMforever (also hit non-interactive chat on gateway timeout). Fixed withcontext.AfterFunc(sessionCtx, sc.Cancel).stream_options.include_usage,choices: []) was discarded and stats fell back to the tokenizer polyfill. Fixed by hoisting the capture.Registry.SetReadToolUsedraced under parallel tool execution (e.g. fourReadcalls in one turn). Now anatomic.Bool.INFER_*env vars dead for optioned mapstructure tags:resolveViperEnvironmentVariablesbuilt viper keys from the raw tag, so fields taggeddebug,omitemptylooked upgateway.debug,omitempty—INFER_GATEWAY_DEBUG/INFER_GATEWAY_OCInever resolved. Tag options are stripped before building the key.Try it
Prompts that trigger scenarios (
internal/mockgateway/scenarios.yamlis the reference):say hello,please search for TODO,run the echo command,explore the project structure,create a file named blocked.txt(approval prompt),stream slowly,think step by step,report your usage;please execute the Read tool 4 times in parallelreadsa.txt–d.txtfrom the cwd. Anything else answers with the fallback (Done.).Custom scenario files use the standalone binary:
task build:mockgateway && .infer/bin/mock-gateway -port 0 -scenarios my.yaml+INFER_GATEWAY_URL.Out of scope
TUI automation (tmux screen-capture harness) — follow-up in #818; the mock gateway here is its prerequisite.