Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(voice): send the latest Agent reply as realtime start context (#2206)

Call Whitea501284bdac5
diff --git a/docs/voice-realtime-prototype.md b/docs/voice-realtime-prototype.md
index 60017fdbb..7a3af6cdc 100644
--- a/docs/voice-realtime-prototype.md
+++ b/docs/voice-realtime-prototype.md
@@ -12,3 +12,21 @@ The preview is transient editor state; only the server-cleaned final result is
committed to the draft. Provider credentials remain server-side. Handshake,
transport, protocol, timeout, and upstream failures activate the existing HTTP
recording fallback without changing legacy or dictation endpoint contracts.
+
+## Reply context
+
+When dictation starts in an existing chat, `start` may also carry `reply`: the
+full body of the chat's latest Agent `result`, without Avibe's generated
+footer. The cloud extracts recognition hotwords from it; the browser neither
+extracts nor truncates it, and never logs it. The reply is read once, when
+dictation starts and before the microphone opens. A result row arrives whole, so during a running
+Turn the previous reply is used. The field is omitted when the reply is empty
+or longer than 200,000 characters. It is also omitted when the transcript
+window does not reach the live tail. The Workbench home, the new-session sheet,
+and Show Page dictation have no latest reply and never send it.
+
+The `start` schema is strict, so an unknown field closes the socket. The
+browser therefore sends `reply` only when the cloud token that opened the
+socket declares `realtime_reply_context`. avibe.bot returns `capabilities` with
+`POST /api/v1/instances/{id}/user-token`. `GET /api/cloud/token` relays it as a
+bounded list of strings. A backend that predates the field declares none.
diff --git a/tests/test_remote_access_vibe_cloud.py b/tests/test_remote_access_vibe_cloud.py
index 61d3c2cb8..11f7dc59d 100644
--- a/tests/test_remote_access_vibe_cloud.py
+++ b/tests/test_remote_access_vibe_cloud.py
@@ -3048,6 +3048,36 @@ def test_cloud_token_for_request_mints_for_authorized_remote_asr(
}
+ ("declared", "relayed"),
+ (
+ (["realtime_reply_context", 7, None, {"x": 1}], ["realtime_reply_context"]),
+ ("realtime_reply_context", []),
+ (None, []),
+ ([f"feature_{index}" for index in range(40)], [f"feature_{index}" for index in range(32)]),
+ ),
+)
+def test_cloud_token_relays_only_bounded_string_capabilities(
+ monkeypatch,
+ declared,
+ relayed,
+) -> None:
+ """The browser gates optional realtime protocol fields on these values, so
+ a malformed or missing backend field must never enable one."""
+ config = _cloud_broker_config()
+ monkeypatch.setattr(remote_access, "current_authorization_revision", lambda *a, **k: 1)
+ cookie = _session_cookie(config, role="editor")
+ minted = {"access_token": "ct_xyz", "expires_in": 43200}
+ if declared is not None:
+ minted["capabilities"] = declared
+ monkeypatch.setattr(remote_access, "_json_request", lambda *a, **k: minted)
+
+ token = remote_access.cloud_token_for_request(config, cookie)
+
+ assert token is not None
+ assert token["capabilities"] == relayed
+
+
def test_cloud_token_for_request_rejects_non_asr_scope(monkeypatch) -> None:
config = _cloud_broker_config()
monkeypatch.setattr(remote_access, "current_authorization_revision", lambda *a, **k: 1)
diff --git a/ui/src/components/workbench/ChatPage.hydration.test.tsx b/ui/src/components/workbench/ChatPage.hydration.test.tsx
index 2528d8f8d..8d283d7b5 100644
--- a/ui/src/components/workbench/ChatPage.hydration.test.tsx
+++ b/ui/src/components/workbench/ChatPage.hydration.test.tsx
@@ -600,6 +600,58 @@ describe('ChatPage transcript hydration', () => {
}
});
+ it.each(['live tail', 'search history'])(
+ 'offers the latest Agent reply body as dictation context from the %s',
+ async (view) => {
+ const prompt = { ...projectedMessage('prompt', 'deploy it'), projection: undefined };
+ const olderReply = {
+ ...prompt, id: 'older-reply', author: 'agent', type: 'result', source: 'agent', text: 'Older reply',
+ delivered_at: '2026-08-15T00:00:02Z',
+ };
+ const reply = {
+ ...olderReply,
+ id: 'latest-reply',
+ text: 'Run make release on prod-7.\n\n✅ 12s · 3k tokens',
+ content: { result_footer: '✅ 12s · 3k tokens' },
+ delivered_at: '2026-08-15T00:00:03Z',
+ };
+ mocks.api.getSession.mockResolvedValue({ id: 'session-new' });
+ mocks.api.getSessionBootstrap.mockResolvedValue({
+ ...bootstrapPayload('session-new'),
+ messages: [prompt, olderReply, reply],
+ });
+ // The searched window holds an old reply, not the chat's latest one.
+ mocks.api.listSessionMessages.mockResolvedValue({
+ messages: [
+ { ...projectedMessage('historical-prompt', 'historical prompt'), projection: undefined },
+ { ...olderReply, id: 'historical-reply', text: 'historical reply' },
+ ],
+ next_after_id: 'historical-reply',
+ });
+ render(
+ <MemoryRouter initialEntries={['/chat/session-new']}>
+ <SessionSwitcher sessionId="session-new" search="?msg=historical-prompt" label="read history" />
+ <Routes><Route path="/chat/:sessionId" element={<ChatPage />} /></Routes>
+ </MemoryRouter>,
+ );
+ await screen.findByText('Run make release on prod-7.');
+ if (view === 'search history') {
+ act(() => screen.getByRole('button', { name: 'read history' }).click());
+ await screen.findByText('historical prompt');
+ } else {
+ // A later prompt starts a Turn; the committed reply stays the context.
+ act(() => mocks.events?.onMessageNew({
+ ...prompt, id: 'next-prompt', text: 'and then?', delivered_at: '2026-08-15T00:00:04Z',
+ }));
+ await screen.findByText('and then?');
+ }
+
+ expect(mocks.composer?.readLatestAgentReply?.()).toBe(
+ view === 'live tail' ? 'Run make release on prod-7.' : undefined,
+ );
+ },
+ );
+
it('keeps the loading view when SSE Session-row recovery beats transcript bootstrap', async () => {
render(
<MemoryRouter initialEntries={['/chat/session-new']}>
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index 232f707f6..d08fde3b0 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -592,6 +592,21 @@ export const ChatPage: React.FC = () => {
const [historicalWindow, setHistoricalWindow] = useState(false);
const historicalWindowRef = useRef(false);
historicalWindowRef.current = historicalWindow;
+ // Realtime dictation context: the body of the latest Agent reply in this chat,
+ // without Avibe's generated footer. A result row is persisted whole, so a
+ // running Turn still reads the previous reply. A window detached from the live
+ // tail may not hold the latest reply, so it offers none.
+ const readLatestAgentReply = useCallback((): string | undefined => {
+ if (historicalWindowRef.current) return undefined;
+ const rows = messagesRef.current;
+ for (let index = rows.length - 1; index >= 0; index -= 1) {
+ const row = rows[index];
+ if (row.author === 'agent' && row.type === 'result') {
+ return resultFooterParts(row).body || undefined;
+ }
+ }
+ return undefined;
+ }, []);
const oldestLoadedIdRef = useRef<string | null>(null);
const newestLoadedIdRef = useRef<string | null>(null);
// Owned here but driven by the Transcript scroller (which reads/writes it in
@@ -3030,6 +3045,7 @@ export const ChatPage: React.FC = () => {
{(writable || readOnlyReason !== null) && <Compose
key={sessionId}
composerRef={composerRef}
+ readLatestAgentReply={readLatestAgentReply}
onSend={(text, attachments, references) => sendMessage(text, attachments, undefined, references)}
onStop={stopMessage}
busy={working}
@@ -3504,6 +3520,7 @@ export const QueueStrip: React.FC<{
interface ComposeProps {
composerRef: React.Ref<ComposerHandle>;
+ readLatestAgentReply: ComposerProps['readLatestAgentReply'];
onSend: (text: string, attachments?: ComposerAttachment[], references?: MentionReference[]) => void;
onStop: () => void;
busy: boolean;
@@ -3518,7 +3535,7 @@ interface ComposeProps {
readOnlyReason: SessionReadOnlyReason | null;
}
-const Compose: React.FC<ComposeProps> = ({ composerRef, onSend, onStop, busy, sessionId, initialDraft, onDraftChange, onSearchAgents, onSearchSessions, readOnlyReason }) => {
+const Compose: React.FC<ComposeProps> = ({ composerRef, readLatestAgentReply, onSend, onStop, busy, sessionId, initialDraft, onDraftChange, onSearchAgents, onSearchSessions, readOnlyReason }) => {
const { t } = useTranslation();
const readOnly = readOnlyReason !== null;
return (
@@ -3540,6 +3557,7 @@ const Compose: React.FC<ComposeProps> = ({ composerRef, onSend, onStop, busy, se
onDraftChange={onDraftChange}
onSearchAgents={onSearchAgents}
onSearchSessions={onSearchSessions}
+ readLatestAgentReply={readLatestAgentReply}
// Read-only archived session: reuse the composer's own disabled +
// placeholder props rather than swapping in a notice bar. ``busy`` is NOT
// reliably false here — archive commits before the controller turn is
diff --git a/ui/src/components/workbench/Composer.shortcut.test.tsx b/ui/src/components/workbench/Composer.shortcut.test.tsx
index cf1ba66bd..eed10f109 100644
--- a/ui/src/components/workbench/Composer.shortcut.test.tsx
+++ b/ui/src/components/workbench/Composer.shortcut.test.tsx
@@ -23,6 +23,7 @@ const voiceMocks = vi.hoisted(() => ({
realtimeAbort: vi.fn(),
realtimeFinish: vi.fn(),
realtimeStart: vi.fn(),
+ realtimeOptions: [] as Array<{ reply?: string }>,
}));
vi.hoisted(() => {
Range.prototype.getBoundingClientRect = () => new DOMRect();
@@ -55,6 +56,10 @@ vi.mock('../../lib/voiceRecording', async (importOriginal) => ({
vi.mock('../../lib/voiceRealtime', async (importOriginal) => ({
...await importOriginal<typeof import('../../lib/voiceRealtime')>(),
VoiceRealtimeSession: class {
+ constructor(options: { reply?: string }) {
+ voiceMocks.realtimeOptions.push(options);
+ }
+
start = voiceMocks.realtimeStart;
finish = voiceMocks.realtimeFinish;
abort = voiceMocks.realtimeAbort;
@@ -83,6 +88,7 @@ type ComposerTestState = {
initialDraft?: string;
mentions?: boolean;
onSend?: (text: string) => void;
+ readLatestAgentReply?: () => string | undefined;
shortcutStartEnabled?: boolean;
};
@@ -118,6 +124,7 @@ const ComposerShortcutHarness = ({
initialDraft={state.initialDraft}
onSearchAgents={state.mentions ? async () => [] : undefined}
onSearchSessions={state.mentions ? async () => [] : undefined}
+ readLatestAgentReply={state.readLatestAgentReply}
/>
</>
);
@@ -150,6 +157,7 @@ beforeEach(() => {
voiceMocks.realtimeAbort.mockReset();
voiceMocks.realtimeFinish.mockReset();
voiceMocks.realtimeStart.mockReset().mockReturnValue(new Promise(() => undefined));
+ voiceMocks.realtimeOptions = [];
voiceMocks.getUserMedia.mockResolvedValue({
getTracks: () => [{ stop: vi.fn() }],
});
@@ -374,4 +382,17 @@ describe('Composer voice shortcut', () => {
fireEvent.keyDown(window, { code: 'Escape', key: 'Escape' });
expect(voiceMocks.abort).toHaveBeenCalledOnce();
});
+
+ it('gives realtime recognition the chat reply present when dictation starts', async () => {
+ let latestReply = 'Run make release on prod-7.';
+ renderComposer('reply-context-session', { readLatestAgentReply: () => latestReply });
+ const mic = await screen.findByRole('button', { name: en.chat.compose.voice });
+ await act(async () => undefined);
+
+ fireEvent.click(mic);
+ latestReply = 'A reply that arrived after dictation started';
+ await waitFor(() => expect(voiceMocks.realtimeOptions).toHaveLength(1));
+
+ expect(voiceMocks.realtimeOptions[0].reply).toBe('Run make release on prod-7.');
+ });
});
diff --git a/ui/src/components/workbench/Composer.tsx b/ui/src/components/workbench/Composer.tsx
index 0e1318f22..eb7e2908e 100644
--- a/ui/src/components/workbench/Composer.tsx
+++ b/ui/src/components/workbench/Composer.tsx
@@ -419,6 +419,9 @@ export interface ComposerProps {
* unset keeps the plain textarea (e.g. the Workbench home). */
onSearchAgents?: (query: string) => Promise<AgentSearchResult[]>;
onSearchSessions?: (query: string) => Promise<SessionSearchResult[]>;
+ /** The chat's latest Agent reply, read once when dictation starts and sent to
+ * realtime recognition as context. Surfaces without one leave it unset. */
+ readLatestAgentReply?: () => string | undefined;
}
export interface ComposerHandle {
@@ -463,6 +466,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
autoFocus = false,
onSearchAgents,
onSearchSessions,
+ readLatestAgentReply,
}, ref) {
const { t } = useTranslation();
const { voiceInput: voiceInputShortcut } = useActionShortcuts();
@@ -1065,6 +1069,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
return;
}
const insertion = capturedInsertion ?? captureVoiceInsertion();
+ const reply = readLatestAgentReply?.();
recordingStartRef.current = true;
setRecordingStarting(true);
let stream: MediaStream | null = null;
@@ -1107,6 +1112,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
session.realtime = new VoiceRealtimeSession({
before: insertion.before,
after: insertion.after,
+ reply,
signal: abortController.signal,
onPreview: (preview) => {
if (recordingSessionRef.current !== session || unmountedRef.current) return;
diff --git a/ui/src/lib/avibeFetch.test.ts b/ui/src/lib/avibeFetch.test.ts
index 627f21d10..2121529ed 100644
--- a/ui/src/lib/avibeFetch.test.ts
+++ b/ui/src/lib/avibeFetch.test.ts
@@ -153,4 +153,30 @@ describe('avibeFetch', () => {
{ phase: 'response', attempt: 2, status: 200, elapsedMs: expect.any(Number) },
]);
});
+
+ it.each([
+ ['keeps only string capabilities', ['realtime_reply_context', 7, null], ['realtime_reply_context']],
+ ['treats a missing field as no capabilities', undefined, []],
+ ['treats a non-array field as no capabilities', 'realtime_reply_context', []],
+ ])('%s of the token that opened a WebSocket', async (_case, capabilities, expected) => {
+ const { apiFetch, openAvibeWebSocket } = await loadModules();
+ apiFetch.mockReset();
+ apiFetch.mockResolvedValueOnce(Response.json({
+ token: 'tok',
+ base_url: 'https://example.test',
+ expires_at: Math.floor(Date.now() / 1000) + 3600,
+ ...(capabilities === undefined ? {} : { capabilities }),
+ }));
+ const opened: Array<[string, string]> = [];
+ vi.stubGlobal('WebSocket', class {
+ constructor(url: string, protocol: string) {
+ opened.push([url, protocol]);
+ }
+ });
+
+ const connection = await openAvibeWebSocket('/api/cloud/voice/realtime', 'avibe-asr-v1');
+
+ expect(opened).toEqual([['wss://example.test/api/cloud/voice/realtime', 'avibe-asr-v1.tok']]);
+ expect(connection.capabilities).toEqual(expected);
+ });
});
diff --git a/ui/src/lib/avibeFetch.ts b/ui/src/lib/avibeFetch.ts
index a6ef306a2..ae23603a6 100644
--- a/ui/src/lib/avibeFetch.ts
+++ b/ui/src/lib/avibeFetch.ts
@@ -15,10 +15,23 @@
import { apiFetch } from './apiFetch';
import { onPageReactivated } from './pageActivity';
-export type CloudToken = { token: string; baseUrl: string; expiresAt: number };
+export type CloudToken = {
+ token: string;
+ baseUrl: string;
+ expiresAt: number;
+ /** Optional cloud features avibe.bot declared when it minted this token. */
+ capabilities: readonly string[];
+};
export type AvibeWebSocket = WebSocket;
+export type AvibeWebSocketConnection = {
+ socket: AvibeWebSocket;
+ /** Capabilities of the token this socket authenticated with, so a caller
+ * gates optional protocol fields on the backend that will parse them. */
+ capabilities: readonly string[];
+};
+
export type AvibeFetchAttemptEvent =
| { phase: 'started'; attempt: number }
| { phase: 'response'; attempt: number; status: number; elapsedMs: number };
@@ -102,7 +115,7 @@ const mint = (): Promise<CloudToken | null> => {
return null;
}
const data = (await res.json().catch(() => null)) as
- | { token?: unknown; base_url?: unknown; expires_at?: unknown }
+ | { token?: unknown; base_url?: unknown; expires_at?: unknown; capabilities?: unknown }
| null;
if (
!data ||
@@ -113,7 +126,15 @@ const mint = (): Promise<CloudToken | null> => {
current = null;
return null;
}
- current = { token: data.token, baseUrl: data.base_url, expiresAt: data.expires_at };
+ current = {
+ token: data.token,
+ baseUrl: data.base_url,
+ expiresAt: data.expires_at,
+ // Older local servers omit the field: no optional cloud features.
+ capabilities: Array.isArray(data.capabilities)
+ ? data.capabilities.filter((value): value is string => typeof value === 'string')
+ : [],
+ };
scheduleRefresh(current);
bindActivityListeners();
return current;
@@ -132,7 +153,7 @@ export const openAvibeWebSocket = async (
path: string,
subprotocol: string,
signal?: AbortSignal,
-): Promise<AvibeWebSocket> => {
+): Promise<AvibeWebSocketConnection> => {
let token: CloudToken | null;
try {
token = await waitForSignal(ensureToken(), signal);
@@ -153,7 +174,7 @@ export const openAvibeWebSocket = async (
else signal.addEventListener('abort', abort, { once: true });
socket.addEventListener('close', () => signal.removeEventListener('abort', abort), { once: true });
}
- return socket;
+ return { socket, capabilities: token.capabilities };
};
const waitForSignal = <Value>(promise: Promise<Value>, signal?: AbortSignal): Promise<Value> => {
diff --git a/ui/src/lib/voiceRealtime.test.ts b/ui/src/lib/voiceRealtime.test.ts
index 309f48610..74a9fab8e 100644
--- a/ui/src/lib/voiceRealtime.test.ts
+++ b/ui/src/lib/voiceRealtime.test.ts
@@ -52,6 +52,12 @@ class FakeSocket {
}
}
+const connect = (socket: FakeSocket, capabilities: string[] = []) =>
+ async () => ({ socket: socket as unknown as WebSocket, capabilities });
+
+const startFrame = (socket: FakeSocket): Record<string, unknown> =>
+ JSON.parse(socket.sent.find((frame) => JSON.parse(frame).type === 'start') ?? 'null');
+
afterEach(() => {
vi.useRealTimers();
vi.unstubAllGlobals();
@@ -82,7 +88,7 @@ describe('voice realtime client protocol', () => {
const session = new VoiceRealtimeSession({
before: '',
after: '',
- openSocket: async () => socket as unknown as WebSocket,
+ openSocket: connect(socket),
});
const start = session.start();
expect(session.sendPcm(new Int16Array([1]))).toBe(true);
@@ -101,7 +107,7 @@ describe('voice realtime client protocol', () => {
const session = new VoiceRealtimeSession({
before: '',
after: '',
- openSocket: async () => socket as unknown as WebSocket,
+ openSocket: connect(socket),
});
const start = session.start();
socket.open();
@@ -120,7 +126,7 @@ describe('voice realtime client protocol', () => {
const session = new VoiceRealtimeSession({
before: '',
after: '',
- openSocket: async () => socket as unknown as WebSocket,
+ openSocket: connect(socket),
});
const start = session.start();
await Promise.resolve();
@@ -140,7 +146,7 @@ describe('voice realtime client protocol', () => {
before: '',
after: '',
onError,
- openSocket: async () => socket as unknown as WebSocket,
+ openSocket: connect(socket),
});
const start = session.start();
socket.open();
@@ -158,7 +164,7 @@ describe('voice realtime client protocol', () => {
const session = new VoiceRealtimeSession({
before: '',
after: '',
- openSocket: async () => socket as unknown as WebSocket,
+ openSocket: connect(socket),
});
const start = session.start();
await Promise.resolve();
@@ -176,7 +182,7 @@ describe('voice realtime client protocol', () => {
const session = new VoiceRealtimeSession({
before: '',
after: '',
- openSocket: async () => socket as unknown as WebSocket,
+ openSocket: connect(socket),
});
const start = session.start();
await Promise.resolve();
@@ -190,4 +196,47 @@ describe('voice realtime client protocol', () => {
await expectation;
expect(socket.readyState).toBe(3);
});
+
+ it.each([
+ ['a backend that declares reply context', ['realtime_reply_context'], 'Deploy notes: run make release.', true],
+ ['a backend without the capability', [], 'Deploy notes: run make release.', false],
+ ['an empty reply', ['realtime_reply_context'], ' ', false],
+ ['a reply over the client cap', ['realtime_reply_context'], 'x'.repeat(200_001), false],
+ ])('sends the latest Agent reply in start only for %s', async (_case, capabilities, reply, included) => {
+ vi.stubGlobal('WebSocket', { OPEN: 1 });
+ const socket = new FakeSocket();
+ const session = new VoiceRealtimeSession({
+ before: '前文',
+ after: '后文',
+ reply,
+ openSocket: connect(socket, capabilities),
+ });
+ const start = session.start();
+ socket.open();
+ await start;
+
+ expect(startFrame(socket)).toEqual({
+ type: 'start',
+ before: '前文',
+ after: '后文',
+ ...(included ? { reply } : {}),
+ });
+ });
+
+ it('sends a reply at the client cap in full', async () => {
+ vi.stubGlobal('WebSocket', { OPEN: 1 });
+ const socket = new FakeSocket();
+ const reply = 'x'.repeat(200_000);
+ const session = new VoiceRealtimeSession({
+ before: '',
+ after: '',
+ reply,
+ openSocket: connect(socket, ['realtime_reply_context']),
+ });
+ const start = session.start();
+ socket.open();
+ await start;
+
+ expect(startFrame(socket).reply).toBe(reply);
+ });
});
diff --git a/ui/src/lib/voiceRealtime.ts b/ui/src/lib/voiceRealtime.ts
index b70b8a004..da6fd327e 100644
--- a/ui/src/lib/voiceRealtime.ts
+++ b/ui/src/lib/voiceRealtime.ts
@@ -2,6 +2,7 @@ import {
CloudUnavailableError,
openAvibeWebSocket,
type AvibeWebSocket,
+ type AvibeWebSocketConnection,
} from './avibeFetch';
export const VOICE_REALTIME_PATH = '/api/cloud/voice/realtime';
@@ -9,6 +10,12 @@ export const VOICE_REALTIME_PROTOCOL = 'avibe-asr-v1';
export const VOICE_REALTIME_HANDSHAKE_TIMEOUT_MS = 8_000;
export const VOICE_REALTIME_FINISH_TIMEOUT_MS = 20_000;
const MAX_PENDING_AUDIO_FRAMES = 128;
+// avibe.bot declares this on the user token when its strict `start` schema
+// accepts `reply`; any older backend would close the socket on the field.
+const REPLY_CONTEXT_CAPABILITY = 'realtime_reply_context';
+// Upper bound for the reply sent with `start`. Longer replies are omitted, not
+// truncated: the backend extracts hotwords from the whole text.
+const MAX_REPLY_CHARS = 200_000;
export type VoiceRealtimePreview = { text: string; stash: string };
export type VoiceRealtimeFinal = { text: string; cleanup: 'success' | 'fallback' };
@@ -17,12 +24,14 @@ export type VoiceRealtimeOptions = {
before: string;
after: string;
language?: string;
+ /** Full text of the latest Agent reply; recognition context only. Never log it. */
+ reply?: string;
signal?: AbortSignal;
openSocket?: (
path: string,
protocol: string,
signal?: AbortSignal,
- ) => Promise<AvibeWebSocket>;
+ ) => Promise<AvibeWebSocketConnection>;
onReady?: () => void;
onPreview?: (preview: VoiceRealtimePreview) => void;
onError?: (error: Error) => void;
@@ -129,12 +138,16 @@ export class VoiceRealtimeSession {
}
private async connect(): Promise<void> {
- const socket = await this.openSocket(
+ const { socket, capabilities } = await this.openSocket(
VOICE_REALTIME_PATH,
VOICE_REALTIME_PROTOCOL,
this.options.signal,
);
this.socket = socket;
+ const reply = this.options.reply;
+ const sendReply = capabilities.includes(REPLY_CONTEXT_CAPABILITY)
+ && !!reply?.trim()
+ && reply.length <= MAX_REPLY_CHARS;
let openReject: ((error: unknown) => void) | null = null;
let readyReject: ((error: unknown) => void) | null = null;
let openListener: ((event: unknown) => void) | null = null;
@@ -194,6 +207,7 @@ export class VoiceRealtimeSession {
before: this.options.before,
after: this.options.after,
...(this.options.language ? { language: this.options.language } : {}),
+ ...(sendReply ? { reply } : {}),
}));
await waitWithTimeout(readyPromise, VOICE_REALTIME_HANDSHAKE_TIMEOUT_MS);
while (this.pendingAudio.length > 0 && this.socket?.readyState === WebSocket.OPEN) {
diff --git a/vibe/remote_access.py b/vibe/remote_access.py
index ab500c446..d6662ff28 100644
--- a/vibe/remote_access.py
+++ b/vibe/remote_access.py
@@ -1858,8 +1858,9 @@ def cloud_token_for_request(
) -> dict[str, Any] | None:
"""Mint a short-lived, subject-bound Cloud ASR token for a remote editor.
- Returns ``{base_url, token, expires_at, scope}`` for the frontend, or ``None``
- when the request is not an eligible remote ASR request or the mint fails.
+ Returns ``{base_url, token, expires_at, scope, capabilities}`` for the
+ frontend, or ``None`` when the request is not an eligible remote ASR request
+ or the mint fails.
This deliberately does not reuse ``can_chat``: that capability authorizes a
local Agent turn and must remain false for every remote caller. New Cloud
@@ -1902,9 +1903,27 @@ def cloud_token_for_authorization(
"token": str(minted["access_token"]),
"expires_at": int(time.time()) + int(minted.get("expires_in", 0) or 0),
"scope": scope,
+ "capabilities": _cloud_token_capabilities(minted.get("capabilities")),
}
+# Bound on the backend-declared optional features relayed to the browser.
+_MAX_CLOUD_TOKEN_CAPABILITIES = 32
+
+
+def _cloud_token_capabilities(value: Any) -> list[str]:
+ """Relay the optional cloud features avibe.bot declared for this token.
+
+ The browser gates optional protocol fields on them (for example
+ ``realtime_reply_context`` for the realtime voice ``start`` frame), so only
+ a bounded list of strings passes; a backend that predates the field yields
+ no capabilities.
+ """
+ if not isinstance(value, list):
+ return []
+ return [item for item in value if isinstance(item, str)][:_MAX_CLOUD_TOKEN_CAPABILITIES]
+
+
def _resource_acl_sync_configured(config: V2Config | None) -> bool:
if config is None:
return False