AIStudio2API icon indicating copy to clipboard operation
AIStudio2API copied to clipboard

Gemini SSE heartbeat ("\n") breaks google.golang.org/genai streaming (+ suggestion to add Antigravity CLI setup)

Open CyberMst opened this issue 2 weeks ago • 2 comments

Transparency note: This issue report was drafted with the assistance of an LLM after auditing the codebase, investigating the failure logs, reproducing the bug deterministically in a Go integration test, and verifying the fix on a locally compiled Linux binary in a real long-context Antigravity CLI (agy) session.

This issue covers two related items from running Antigravity CLI (agy) against AIStudio2API's Gemini SSE endpoint:

  1. Bug Report & Fix: Why geminiHeartbeat = "\n" causes intermittent iterateResponseStream: invalid stream chunk + HTTP 499 failures in google.golang.org/genai clients, and the one-line fix ("\n\n").
  2. Feature / Docs Suggestion: Adding Antigravity CLI (agy) to Connect → Clients (web/src/access/clients.ts) and the README client examples.

1. Bug: geminiHeartbeat = "\n" breaks google.golang.org/genai SSE streaming after odd keepalives

Summary

When using Gemini SSE streaming (POST /v1beta/models/{model}:streamGenerateContent?alt=sse) with clients built on the official Go SDK googleapis/go-genai — such as Antigravity CLI (agy) configured with a custom Gemini API endpoint — long-context or slow-thinking requests intermittently abort mid-stream with:

iterateResponseStream: invalid stream chunk: \ndata: {"candidates":[...]}

(Note: terminal/TUI error banners may collapse the newline after chunk:, displaying invalid stream chunk: data: {"candidates":...}.)

At the exact moment the next upstream event arrives, AIStudio2API logs HTTP 499 context canceled because the client immediately closes the response body upon rejecting the chunk.

Root Cause

In internal/api/keepalive.go:

const (
	sseHeartbeat       = ": ping\n\n"
	anthropicHeartbeat = "event: ping\ndata: {\"type\":\"ping\"}\n\n"
	geminiHeartbeat    = "\n"
)

For POST .../models/{model}:streamGenerateContent?alt=sse:

  1. handleGeminiGenerate (internal/api/gemini.go) calls startChatChoices (internal/api/chat_choices.go), which waits up to streamHeartbeatInterval (10s, internal/api/generate.go) in awaitStreamStart before returning if no upstream event has arrived yet.
  2. streamGemini then calls openGeminiStream(w, r), which calls openStream(w, geminiHeartbeat), writing HTTP 200 SSE headers and starting a 10s keepalive timer (streamKeepalive).
  3. Unlike sseHeartbeat and anthropicHeartbeat (both terminated with \n\n), geminiHeartbeat writes a single "\n".

Meanwhile, googleapis/go-genai (api_client.go) parses SSE streams using bufio.Scanner with custom scan():

  1. scan() splits frames on "\n\n" (or "\r\n\r\n"), not on single "\n" lines (bytes.Index(data, []byte("\n\n"))).
  2. iterateResponseStream() skips empty tokens (if len(line) == 0 { continue }).
  3. Otherwise, it runs prefix, data, _ := bytes.Cut(line, []byte(":")) and switches on string(prefix):
    • case "data": unmarshals the JSON chunk.
    • default: attempts error JSON unmarshaling (respWithError) and otherwise aborts with fmt.Errorf("iterateResponseStream: invalid stream chunk: %s:%s", string(prefix), string(data)). (This is also why : ping\n\n cannot be used for Gemini — go-genai rejects : comment lines with invalid stream chunk: : ping.)

Because every data chunk from writeSSE (internal/api/errors.go) ends with "\n\n", scan() leaves an empty buffer after each valid chunk. Once idle heartbeats begin firing every 10s:

  • 0 heartbeats (< 10s idle after openStream): buffer stays clean; works normally.
  • Even number of heartbeats (2, 4, ... → "\n\n", "\n\n\n\n"): pairs of "\n" form "\n\n", which scan() emits as empty tokens (len(line) == 0) and skips cleanly.
  • Odd number of heartbeats (1, 3, 5, ... → "\n", "\n\n\n"): one unpaired "\n" stays buffered and gets prepended to the very next writeSSE frame ("data: {...}\n\n"):
    • Wire bytes since the previous "\n\n" delimiter: "\ndata: {...}\n\n"
    • scan() returns token: "\ndata: {...}"
    • bytes.Cut yields prefix = "\ndata" (!= "data"), falling into default: and aborting the stream.

Observed Behavior & Logs (Real Session)

This occurred repeatedly in longer-context conversations (e.g., 63k–242k prompt tokens) regardless of WAA backend (observed identically with both SpiderMonkey and Camoufox, since the bug is in the HTTP SSE keepalive layer):

  1. Slow initial response (Wait=21.066s before first chunk): 18:54:21 request starts → after 10s (~18:54:31), awaitStreamStart times out and openGeminiStream opens the SSE stream with a 10s timer → at ~18:54:41 (+10s), 1 "\n" heartbeat fires → at 18:54:43 (21.066s), upstream headers arrive and the first thought chunk is written ("\ndata: {...}\n\n"):

    499 gemini-4-hydrogen Playground 21.12 s context canceled
    18:54:21 Request started
    18:54:21 Waiting for upstream response
    18:54:21 Upstream call | Channel=playground | Mode=stream | RPC=GenerateContent
    18:54:36 Request preparation waiting | waited=15s | current=Waiting for upstream response headers
    18:54:43 Request preparation ended | Wait=21.066s | WAA=16ms | Response headers=21.05s
    18:54:43 Request canceled
    

    Client error: iterateResponseStream: invalid stream chunk on the first thought chunk.

  2. Mid-stream pause (pause=33.39s before tool_call): Initial reasoning events streamed normally (ending around 19:51:58, resetting streamKeepalive's timer). During the subsequent 33.39s pause before tool_call, 3 "\n" heartbeats (+10s, +20s, +30s) fired ("\n\n\n"). The first two paired into "\n\n", and the 3rd "\n" corrupted the write_file functionCall chunk at 19:52:32:

    499 gemini-4-hydrogen Playground 53.67 s Tool calls 1 context canceled
    19:51:38 Request started
    19:51:38 Waiting for upstream response
    19:51:38 Upstream call | Channel=playground | Mode=stream | RPC=GenerateContent
    19:52:13 Event stream paused | Model=gemini-4-hydrogen | waited=15s | recent_events=reasoning | reasoning=5 | Bodies=0 | Network bytes=3310 | recent_network=15.002s
    19:52:32 Event stream resumed | Model=gemini-4-hydrogen | pause=33.39s | current_event=tool_call
    19:52:32 Request canceled
    

    Client error: iterateResponseStream: invalid stream chunk on the write_file functionCall chunk.

Notes on Reproduction

  • In live AI Studio usage: It is difficult to reproduce deterministically on demand because it depends on upstream latency/pauses landing on an odd multiple of streamHeartbeatInterval (10s) — specifically 10–20s, 30–40s, 50–60s between writes (or 20–30s, 40–50s before the first chunk when awaitStreamStart takes the first 10s), whereas even multiples (20–30s mid-stream, etc.) accidentally succeed due to \n pairing.
  • In a controlled Go test: It reproduces 100% deterministically by wiring api.NewHandler over httptest.NewServer with a mock aistudio.Service and calling Models.GenerateContentStream from google.golang.org/genai:
    • 21s delay before the first event (awaitStreamStart 10s + 1 heartbeat): fails with iterateResponseStream: invalid stream chunk: \ndata: ... (chunks=0).
    • 11s pause between EventReasoning and EventToolCall (1 heartbeat): fails with iterateResponseStream: invalid stream chunk: \ndata: ... (chunks=1).
    • 21s pause between EventReasoning and EventToolCall (2 heartbeats = "\n\n"): succeeds (chunks=3, err=<nil>).

Suggested Fix

In internal/api/keepalive.go, change geminiHeartbeat from "\n" to "\n\n" so every heartbeat emits a complete empty SSE frame delimiter:

const (
	sseHeartbeat       = ": ping\n\n"
	anthropicHeartbeat = "event: ping\ndata: {\"type\":\"ping\"}\n\n"
	geminiHeartbeat    = "\n\n"
)

(Note: streamKeepalive already serializes beat() and Write() with writer.mu, nonstreamKeepalive (keepaliveWriter) only affects non-SSE JSON responses, and alt != "sse" JSON array streaming does not use geminiHeartbeat. Adding a unit test in internal/api/ covering openGeminiStream (alt=sse) with odd heartbeats would also prevent regressions.)

Verification & Compatibility

  • Why \n\n is safe for all Gemini SSE clients: Under the WHATWG SSE specification (used by JS @google/genai via eventsource-parser, Python google-genai, EventSource, and curl), blank lines with an empty event data buffer are a spec-compliant no-op and dispatch no event. In go-genai, each "\n\n" heartbeat is immediately consumed as an empty token and skipped (len(line) == 0), leaving the scanner buffer completely clean before the next writeSSE frame (or geminiStream.fail error frame).
  • Test & real-world verification:
    1. Re-ran the google.golang.org/genai Go integration test above with geminiHeartbeat = "\n\n": all three timing scenarios (21s initial delay, 11s pause, 21s pause) passed with err=<nil>.
    2. Ran the existing Go test suite (go test -mod=readonly -trimpath -vet=off -tags netgo,osusergo ./cmd/... ./internal/...) with Zig + SpiderMonkey/libwebp static libraries: all packages passed.
    3. Compiled a static Linux amd64 binary with the fix and tested it on the exact same long-context Antigravity CLI conversation that previously failed repeatedly — streaming and tool calls completed cleanly with no invalid stream chunk or 499 context canceled.

2. Suggestion: Add Antigravity CLI (agy) to Connect > Clients & Client Docs

Since AIStudio2API already provides guided agent setup both in the Web UI (Connect → Clients in web/src/components/AccessPanel.vue / web/src/access/clients.ts) and in README.md / README_en.md (Client Configuration Example), it would be great to add Antigravity CLI (agy) alongside Claude Code, Codex, OpenCode, pi, omp, etc.

Unlike the Antigravity desktop IDE, the standalone Antigravity CLI (agy) officially supports authenticating with a Gemini API key and pointing GOOGLE_GEMINI_BASE_URL to a custom Gemini-compatible endpoint, as documented in the official Antigravity CLI install guide:

  • https://antigravity.google/docs/install/?tab=cli

Per that guide, connecting agy to AIStudio2API takes two steps:

  1. Enable Gemini API-key mode in ~/.gemini/antigravity-cli/settings.json:
    {
      "modelProvider": "gemini"
    }
    
  2. Set GEMINI_API_KEY (PROXY_API_KEY from .env) and GOOGLE_GEMINI_BASE_URL (the service root http://127.0.0.1:2048 / input.origin without /v1beta, matching the existing Gemini base URL in AccessPanel.vue and README_en.md) and start agy:
    export GEMINI_API_KEY="<PROXY_API_KEY>"
    export GOOGLE_GEMINI_BASE_URL="http://127.0.0.1:2048"
    agy
    
    (Plus $env:... PowerShell syntax on Windows.)

Suggested placement

  • Web UI (web/src/access/clients.ts + web/src/locales/*.ts): Add an entry under group: 'agent' with protocols: ['gemini'], shell: true, and noModel: true, using:
    1. access.step.configFile for ~/.gemini/antigravity-cli/settings.json ({"modelProvider": "gemini"}), and
    2. envStep (access.step.envRun) setting GEMINI_API_KEY and GOOGLE_GEMINI_BASE_URL (input.origin) and launching agy. (Optionally note MODEL_MAPPING if model aliases are needed.)
  • Documentation (README.md / README_en.md): Add the same short snippet under Client Configuration Example with a reference to https://antigravity.google/docs/install/?tab=cli so users know they can use agy directly with AIStudio2API via custom API key + endpoint.

CyberMst avatar Nov 15 '26 15:11 CyberMst

fixed in v0.3.10, heartbeat is now an empty frame so genai skips it, and agy setup is added to the access page and README.

Mag1cFall avatar Nov 16 '26 08:11 Mag1cFall

Thank you for resolving the streaming issue and adding Antigravity CLI to Connect → Clients and the documentation.

One small note regarding the Antigravity CLI link used for Homepage in Connect → Clients and in the README (README.md / README_en.md): it currently points to https://antigravity.google/docs/install?tab=cli, which was included in the issue only as a reference for API-key authentication rather than the repository, product page, or CLI installation overview.

For those links, one of the following would be a better fit (especially the GitHub repository for consistency with the other agent links like Claude Code and Codex, keeping /docs/install/?tab=cli only if linking specifically to the API-key auth instructions):

  • GitHub repository: https://github.com/google-antigravity/antigravity-cli
  • Product page: https://antigravity.google/product/antigravity-cli
  • CLI installation / getting-started docs: https://antigravity.google/docs/getting-started/?tab=cli

CyberMst avatar Nov 16 '26 15:11 CyberMst