Skip to content

Add VoiceClaw realtime brain gateway - #70938

Merged
steipete merged 3 commits into
openclaw:mainfrom
yagudaev:michael/nan-656-add-direct-real-time-brain-mode-for-voiceclaw
Apr 24, 2026
Merged

steipete merged 3 commits into
openclaw:mainfrom
yagudaev:michael/nan-656-add-direct-real-time-brain-mode-for-voiceclaw

Conversation

@yagudaev

Copy link
Copy Markdown
Contributor

Summary

  • Add a /voiceclaw/realtime Gateway WebSocket path for VoiceClaw-compatible clients to connect directly to Gemini Live.
  • Route async ask_brain tool calls into OpenClaw with isolated VoiceClaw session namespaces, auth checks, reconnect handling, and tool cancellation handling.
  • Document the isolated realtime-brain OpenClaw runtime setup and add Gateway upgrade/handshake coverage.

Test plan

  • pnpm check:changed
  • pnpm build
  • Claude Code review via cc; addressed blocking/medium findings

Linear: NAN-656

@greptile-apps

greptile-apps Bot commented Apr 24, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds a /voiceclaw/realtime WebSocket gateway that proxies audio sessions to Gemini Live and routes ask_brain tool calls into the OpenClaw agent runtime. The overall architecture (preauth budget, handshake timeout, rate limiting, reconnect/resumption, watchdog, session isolation) is solid. Two correctness issues are worth addressing before merge.

  • session.ended never delivered (session.ts): cleanup() is only invoked from the ws.on(\"close\") handler, so ws.readyState is always CLOSED at that point and the guard readyState === WebSocket.OPEN is never true — clients never receive session summary data.
  • Partial tool-call cancellation corrupts counter (gemini-live.ts): pendingToolCalls is reset to 0 unconditionally on any toolCallCancellation message, even if only a subset of IDs are cancelled, potentially triggering premature watchdog resets and session rotation.

Confidence Score: 4/5

Safe to merge after fixing the two P1 issues; the rest of the implementation is well-structured.

Two P1 findings: session.ended is unreachable dead code (clients never receive session summaries), and partial tool-call cancellation resets pendingToolCalls to 0 prematurely, which can trigger incorrect watchdog resets and session rotation. Both are in the new code path only and do not break existing functionality, but they produce wrong behavior for the new feature.

src/gateway/voiceclaw-realtime/session.ts (session.ended delivery), src/gateway/voiceclaw-realtime/gemini-live.ts (toolCallCancellation counter and API key URL exposure)

Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/gateway/voiceclaw-realtime/session.ts
Line: 326-348

Comment:
**`session.ended` is dead code — never delivered to the client**

`cleanup()` is triggered exclusively from `this.ws.on("close", ...)`. When that event fires the WebSocket `readyState` is already `WebSocket.CLOSED` (3), so the guard `this.ws.readyState === WebSocket.OPEN` is always false and the `session.ended` event is never sent. Clients expecting session summary data (duration, turn count) will never receive it.

The message needs to be sent *before* the connection closes — e.g. from a `disconnect()` method the adapter calls on its own, or emitted by `handleAdapterEvent` when it receives a terminal upstream event, with `cleanup()` only used for resource teardown.

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: src/gateway/voiceclaw-realtime/gemini-live.ts
Line: 314-327

Comment:
**`pendingToolCalls` reset to 0 on partial cancellation**

`this.pendingToolCalls = 0` is applied unconditionally regardless of how many IDs appear in the cancellation message. If Gemini ever sends a partial cancellation (a subset of in-flight call IDs), `pendingToolCalls` becomes 0 while `pendingToolCallIds` still contains the uncancelled IDs. This inconsistency means `resetWatchdog()` and the `rotateAfterToolCalls` deferred-rotation check (in `sendToolResult`) can fire prematurely, triggering a session rotation while tool calls are still genuinely in flight.

Using `this.pendingToolCallIds.size` as the counter, or decrementing only by `ids.length`, keeps both fields consistent.

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: src/gateway/voiceclaw-realtime/gemini-live.ts
Line: 491-495

Comment:
**Client WebSocket left open after all reconnect attempts exhaust**

After all `MAX_RECONNECT_ATTEMPTS` fail, the adapter sends `{ type: "error", code: 502 }` but neither the adapter nor the session closes the client-facing WebSocket. The session appears alive but the Gemini upstream is gone; any subsequent audio or tool results from the client will be silently dropped (`sendUpstream` skips when `upstream` is null). Clients that don't immediately `close()` on receiving an error event will leak an open connection.

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "Add VoiceClaw realtime brain gateway (NA..." | Re-trigger Greptile

Comment on lines +326 to +348
private async cleanup(): Promise<void> {
if (this.closed) {
return;
}
this.clearHandshakeTimer();
this.releasePreauthBudget();
for (const controller of this.inFlightTools.values()) {
controller.abort();
}
this.inFlightTools.clear();
const transcript = this.adapter?.getTranscript() ?? [];
this.adapter?.disconnect();
this.adapter = null;
if (transcript.length > 0 && this.ws.readyState === WebSocket.OPEN) {
this.send({
type: "session.ended",
summary: "Real-time brain session ended.",
durationSec: Math.round((Date.now() - this.startedAt) / 1000),
turnCount: transcript.filter((entry) => entry.role === "user").length,
});
}
this.closed = true;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 session.ended is dead code — never delivered to the client

cleanup() is triggered exclusively from this.ws.on("close", ...). When that event fires the WebSocket readyState is already WebSocket.CLOSED (3), so the guard this.ws.readyState === WebSocket.OPEN is always false and the session.ended event is never sent. Clients expecting session summary data (duration, turn count) will never receive it.

The message needs to be sent before the connection closes — e.g. from a disconnect() method the adapter calls on its own, or emitted by handleAdapterEvent when it receives a terminal upstream event, with cleanup() only used for resource teardown.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/gateway/voiceclaw-realtime/session.ts
Line: 326-348

Comment:
**`session.ended` is dead code — never delivered to the client**

`cleanup()` is triggered exclusively from `this.ws.on("close", ...)`. When that event fires the WebSocket `readyState` is already `WebSocket.CLOSED` (3), so the guard `this.ws.readyState === WebSocket.OPEN` is always false and the `session.ended` event is never sent. Clients expecting session summary data (duration, turn count) will never receive it.

The message needs to be sent *before* the connection closes — e.g. from a `disconnect()` method the adapter calls on its own, or emitted by `handleAdapterEvent` when it receives a terminal upstream event, with `cleanup()` only used for resource teardown.

How can I resolve this? If you propose a fix, please make it concise.

Comment on lines +314 to +327
const cancellation = asRecord(msg.toolCallCancellation);
if (cancellation) {
const ids = Array.isArray(cancellation.ids)
? cancellation.ids.filter((id): id is string => typeof id === "string")
: [];
this.pendingToolCalls = 0;
for (const id of ids) {
this.pendingToolCallIds.delete(id);
}
if (ids.length > 0) {
this.sendToClient?.({ type: "tool.cancelled", callIds: ids });
}
this.resetWatchdog();
return;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 pendingToolCalls reset to 0 on partial cancellation

this.pendingToolCalls = 0 is applied unconditionally regardless of how many IDs appear in the cancellation message. If Gemini ever sends a partial cancellation (a subset of in-flight call IDs), pendingToolCalls becomes 0 while pendingToolCallIds still contains the uncancelled IDs. This inconsistency means resetWatchdog() and the rotateAfterToolCalls deferred-rotation check (in sendToolResult) can fire prematurely, triggering a session rotation while tool calls are still genuinely in flight.

Using this.pendingToolCallIds.size as the counter, or decrementing only by ids.length, keeps both fields consistent.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/gateway/voiceclaw-realtime/gemini-live.ts
Line: 314-327

Comment:
**`pendingToolCalls` reset to 0 on partial cancellation**

`this.pendingToolCalls = 0` is applied unconditionally regardless of how many IDs appear in the cancellation message. If Gemini ever sends a partial cancellation (a subset of in-flight call IDs), `pendingToolCalls` becomes 0 while `pendingToolCallIds` still contains the uncancelled IDs. This inconsistency means `resetWatchdog()` and the `rotateAfterToolCalls` deferred-rotation check (in `sendToolResult`) can fire prematurely, triggering a session rotation while tool calls are still genuinely in flight.

Using `this.pendingToolCallIds.size` as the counter, or decrementing only by `ids.length`, keeps both fields consistent.

How can I resolve this? If you propose a fix, please make it concise.

Comment on lines +491 to +495
}
}
}
this.isReconnecting = false;
this.sendToClient?.({ type: "error", message: "Gemini Live reconnect failed", code: 502 });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Client WebSocket left open after all reconnect attempts exhaust

After all MAX_RECONNECT_ATTEMPTS fail, the adapter sends { type: "error", code: 502 } but neither the adapter nor the session closes the client-facing WebSocket. The session appears alive but the Gemini upstream is gone; any subsequent audio or tool results from the client will be silently dropped (sendUpstream skips when upstream is null). Clients that don't immediately close() on receiving an error event will leak an open connection.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/gateway/voiceclaw-realtime/gemini-live.ts
Line: 491-495

Comment:
**Client WebSocket left open after all reconnect attempts exhaust**

After all `MAX_RECONNECT_ATTEMPTS` fail, the adapter sends `{ type: "error", code: 502 }` but neither the adapter nor the session closes the client-facing WebSocket. The session appears alive but the Gemini upstream is gone; any subsequent audio or tool results from the client will be silently dropped (`sendUpstream` skips when `upstream` is null). Clients that don't immediately `close()` on receiving an error event will leak an open connection.

How can I resolve this? If you propose a fix, please make it concise.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d1f29963ed

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".


export { VOICECLAW_REALTIME_PATH };

const wss = new WebSocketServer({ noServer: true });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Set pre-auth frame limits on VoiceClaw upgrade server

The VoiceClaw upgrader creates a dedicated WebSocketServer without maxPayload, so /voiceclaw/realtime uses the ws default frame limit instead of the gateway’s hardened pre-auth limit (MAX_PREAUTH_PAYLOAD_BYTES). Because auth happens after upgrade (in session.config), unauthenticated clients can push much larger frames than intended and consume memory/CPU before any auth gate applies. This should use the same pre-auth payload cap as the main gateway WS path.

Useful? React with 👍 / 👎.

Comment on lines +330 to +333
if (asRecord(msg.goAway)) {
if (this.pendingToolCalls > 0 || !this.currentlyResumable) {
this.rotateAfterToolCalls = true;
return;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reconnect immediately when deferred goAway becomes resumable

When goAway is received while currentlyResumable is false, this path sets rotateAfterToolCalls and returns, but there is no follow-up reconnect when a later sessionResumptionUpdate flips resumable to true. In that sequence (with no tool calls in flight), the adapter never rotates and then treats socket close as a hard error instead of resuming. Trigger reconnect once resumability is restored if rotateAfterToolCalls is already set and no tool calls are pending.

Useful? React with 👍 / 👎.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime size: XL labels Apr 24, 2026
@yagudaev
yagudaev force-pushed the michael/nan-656-add-direct-real-time-brain-mode-for-voiceclaw branch 2 times, most recently from e87d70c to bf4cea2 Compare April 24, 2026 05:06

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: bf4cea210d

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +479 to +483
for (let attempt = 1; attempt <= MAX_RECONNECT_ATTEMPTS; attempt += 1) {
try {
await this.openUpstream();
this.isReconnecting = false;
this.sendToClient?.({ type: "session.rotated", sessionId: `gemini-resumed-${Date.now()}` });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Stop reconnect attempts after session disconnect

When the client WebSocket closes, disconnect() sets this.disconnected = true, but an already-running reconnect() loop still executes openUpstream() and can establish a new Gemini socket after the session is gone. In that case the adapter keeps an orphan upstream connection (and potentially burns provider resources) because sendToClient is already null and nothing closes the newly opened socket. Re-check this.disconnected before each reconnect attempt (and immediately after openUpstream() resolves) to abort and tear down cleanly.

Useful? React with 👍 / 👎.

Comment on lines +319 to +321
this.pendingToolCalls = 0;
for (const id of ids) {
this.pendingToolCallIds.delete(id);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep pending tool-call state consistent on cancellations

This handler unconditionally sets pendingToolCalls to 0 for any toolCallCancellation, even though it only removes the IDs that were actually cancelled from pendingToolCallIds. If Gemini cancels only a subset of calls, the adapter now believes all tool calls are done, which can restart watchdog/reconnect flows too early and mis-handle later results for still-active calls. Update the counter based on cancelled IDs (or derive from the set) instead of zeroing it globally.

Useful? React with 👍 / 👎.

@yagudaev
yagudaev force-pushed the michael/nan-656-add-direct-real-time-brain-mode-for-voiceclaw branch 2 times, most recently from f53320e to edd7f8c Compare April 24, 2026 18:42
@steipete

Copy link
Copy Markdown
Contributor

Codex maintainer review: keep open, but not merge-ready yet.

The direction is plausible if we want an explicitly VoiceClaw-compatible gateway endpoint, but the latest diff still has two behavior blockers:

  • src/gateway/voiceclaw-realtime/session.ts: session.ended is still effectively unreachable. cleanup() runs from the WebSocket close handler, then send() drops the event because the client socket is no longer open. Emit the terminal summary before closing the client socket, or add an explicit session-close path that sends session.ended first and leaves cleanup() for resource teardown. Please add a test that a client actually receives session.ended before close.
  • src/gateway/voiceclaw-realtime/gemini-live.ts: terminal upstream failures can leave the client WebSocket open. After reconnect attempts exhaust, or after a non-reconnectable Gemini close, the adapter sends an error but the session stays alive and later client audio/tool frames are silently dropped. The session should close the client-facing socket after a terminal upstream error, with coverage.

The earlier partial tool-call cancellation concern looks addressed in edd7f8c by tracking pendingToolCallIds / async tool IDs instead of blindly resetting the counter.

CI is also red on check-additional-boundaries: lint:tmp:no-raw-channel-fetch reports extensions/elevenlabs/tts.ts:74. Current main passes that local check, so this branch likely needs a rebase/fix rather than a waiver.

After those changes: rerun the focused src/gateway/voiceclaw-realtime/*.test.ts coverage plus pnpm check:changed / pnpm build.

@steipete
steipete force-pushed the michael/nan-656-add-direct-real-time-brain-mode-for-voiceclaw branch from edd7f8c to 40e79d2 Compare April 24, 2026 19:57
@steipete
steipete merged commit c997a9f into openclaw:main Apr 24, 2026
65 checks passed
@steipete

Copy link
Copy Markdown
Contributor

Landed via squash after rebasing onto current main.

  • Maintainer fixup: src/gateway/voiceclaw-realtime/session.ts now treats terminal adapter errors as terminal client-session errors: send the error, emit session.ended while the WebSocket is still open, then close the client-facing socket. Added lifecycle coverage in src/gateway/voiceclaw-realtime/session.test.ts.
  • Removed the local-only package.json helper that assumed a sibling ../voiceclaw checkout; docs keep the generic startup path.
  • Added the changelog entry.

Local proof:

  • pnpm test src/gateway/voiceclaw-realtime/session.test.ts src/gateway/voiceclaw-realtime/gemini-live.test.ts src/gateway/voiceclaw-realtime/tool-runtime.test.ts src/gateway/voiceclaw-realtime/upgrade.test.ts
  • pnpm run lint:tmp:no-raw-channel-fetch
  • pnpm check
  • pnpm build
  • pnpm test src/agents/codex-native-web-search.test.ts (rerun of unrelated full-sweep timeout; passed)

CI on 40e79d21bbb65a75357ac0afdfec3f6d001d5531 went green, including check-additional-boundaries.

  • Source fixup SHA: 40e79d21bbb65a75357ac0afdfec3f6d001d5531
  • Merge commit: c997a9f9788e0a96e8eab05e7ae94959e76cdb4a

Thanks @yagudaev!

Angfr95 pushed a commit to Angfr95/openclaw that referenced this pull request Apr 25, 2026
Adds the VoiceClaw-compatible realtime brain WebSocket endpoint backed by Gemini Live, with owner-auth gating, async OpenClaw tool handoff, docs, and lifecycle tests.

Maintainer fixup: terminal upstream errors now send the error, emit session.ended while the client socket is still open, then close the client-facing socket.

Co-authored-by: Michael Yagudaev <[email protected]>
GONZO304 pushed a commit to GONZO304/openclaw that referenced this pull request Apr 28, 2026
Adds the VoiceClaw-compatible realtime brain WebSocket endpoint backed by Gemini Live, with owner-auth gating, async OpenClaw tool handoff, docs, and lifecycle tests.

Maintainer fixup: terminal upstream errors now send the error, emit session.ended while the client socket is still open, then close the client-facing socket.

Co-authored-by: Michael Yagudaev <[email protected]>
ogt-redknie pushed a commit to ogt-redknie/OPENX that referenced this pull request May 2, 2026
Adds the VoiceClaw-compatible realtime brain WebSocket endpoint backed by Gemini Live, with owner-auth gating, async OpenClaw tool handoff, docs, and lifecycle tests.

Maintainer fixup: terminal upstream errors now send the error, emit session.ended while the client socket is still open, then close the client-facing socket.

Co-authored-by: Michael Yagudaev <[email protected]>
globalcaos pushed a commit to globalcaos/tinkerclaw that referenced this pull request May 13, 2026
Adds the VoiceClaw-compatible realtime brain WebSocket endpoint backed by Gemini Live, with owner-auth gating, async OpenClaw tool handoff, docs, and lifecycle tests.

Maintainer fixup: terminal upstream errors now send the error, emit session.ended while the client socket is still open, then close the client-facing socket.

Co-authored-by: Michael Yagudaev <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request May 24, 2026
Adds the VoiceClaw-compatible realtime brain WebSocket endpoint backed by Gemini Live, with owner-auth gating, async OpenClaw tool handoff, docs, and lifecycle tests.

Maintainer fixup: terminal upstream errors now send the error, emit session.ended while the client socket is still open, then close the client-facing socket.

Co-authored-by: Michael Yagudaev <[email protected]>
jameslcowan pushed a commit to jameslcowan/openclaw that referenced this pull request Jun 2, 2026
Adds the VoiceClaw-compatible realtime brain WebSocket endpoint backed by Gemini Live, with owner-auth gating, async OpenClaw tool handoff, docs, and lifecycle tests.

Maintainer fixup: terminal upstream errors now send the error, emit session.ended while the client socket is still open, then close the client-facing socket.

Co-authored-by: Michael Yagudaev <[email protected]>
sablehead pushed a commit to sablehead/openclaw that referenced this pull request Jun 10, 2026
Adds the VoiceClaw-compatible realtime brain WebSocket endpoint backed by Gemini Live, with owner-auth gating, async OpenClaw tool handoff, docs, and lifecycle tests.

Maintainer fixup: terminal upstream errors now send the error, emit session.ended while the client socket is still open, then close the client-facing socket.

Co-authored-by: Michael Yagudaev <[email protected]>
vixco pushed a commit to vixco/openclaw that referenced this pull request Aug 16, 2026
Adds the VoiceClaw-compatible realtime brain WebSocket endpoint backed by Gemini Live, with owner-auth gating, async OpenClaw tool handoff, docs, and lifecycle tests.

Maintainer fixup: terminal upstream errors now send the error, emit session.ended while the client socket is still open, then close the client-facing socket.

Co-authored-by: Michael Yagudaev <[email protected]>
Heetisk pushed a commit to Heetisk/openclaw that referenced this pull request Sep 28, 2026
Adds the VoiceClaw-compatible realtime brain WebSocket endpoint backed by Gemini Live, with owner-auth gating, async OpenClaw tool handoff, docs, and lifecycle tests.

Maintainer fixup: terminal upstream errors now send the error, emit session.ended while the client socket is still open, then close the client-facing socket.

Co-authored-by: Michael Yagudaev <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation gateway Gateway runtime size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants