Skip to content

A spy satellite simulator in your browser, except the data is real. Live open source spatial intelligence on a photorealistic 3D globe.

Merge main into PR #621 (ChatGPT OAuth for Realtime voice)

Sameh Khamisfb1596d2f106
diff --cc CHANGELOG.md
index 25415f601,64232fa29..76046f4b3
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -1,15 -1,97 +1,105 @@@
# Changelog
+ - Vector tile sources take their allowed tile origin from the configured
+ `tileJsonUrl`, so repointing only that URL at a mirror loads tiles from the
+ mirror or fails visibly instead of silently using OpenFreeMap. Thanks to
+ [daikaginza](https://github.com/daikaginza) (#935).
+
+ - MCP setup examples use the app's default port, `4173`. Thanks to
+ [Huanyi Xie](https://github.com/xiehuanyi) (#934) and
+ [shirunjies8-png](https://github.com/shirunjies8-png) (#959) for the same fix.
+
+ - Voice revisits numbered analyst records through current layer snapshots and
+ preserves resolved pin coordinates. Requested analyst lists and rankings can
+ speak returned items alongside the exact count and coverage caveats. Failed
+ actions settle the voice card without reviving cancelled turns. Coverage
+ benchmarks reject invalid calls before accepting semantic matches.
+
+ - Street Level is included in the voice layer manifest for visibility toggles;
+ imagery is not exposed as countable analyst records.
+
+ - Voice debug logs omit complete tool-result bodies and serialized function
+ outputs by default, including location queries and generated spoken replies.
+ `GEV_VOICE_LOG_CONTENT=1` retains them for explicit content debugging.
+
+ - Unqualified Alps searches use the bundled European range for navigation
+ and annotations instead of a same-named peak returned by a geocoder.
+ Coordinates, supplied presets and geographically qualified place names
+ keep their precedence; annotation proximity and containment guards remain.
+ - Contacts analyst follow-ups retain the snapshot's distance ranking rather
+ than switching to the camera. Requested radii and explicit scopes remain
+ authoritative, and a request for a list still requires an analyst query.
+ Analyst speech names stale or degraded feeds and withholds authoritative
+ counts when unavailable. The existing NOTES disclosure preserves complete,
+ deduplicated coverage and source caveats, including crowded results.
+ - The voice card shows analyst counts ("At least 250,000 aircraft …") with
+ their scope, feed window and caveats, and marks partial answers. Analyst
+ speech uses the same deterministic headline, preserves lower bounds and says
+ when an answer is partial. Follow-ups retain unanswered-layer coverage, and
+ keep the original scope label when they narrow a remembered result.
+ Contacts-window answers read one immutable panel snapshot, mark a 20,000-row
+ layer cap as a lower bound, and commit that displayed cohort only after
+ cancellation checks pass. Concurrent analyst calls from one model response
+ remain independent; a stopped or replaced user turn still cancels them.
+ - Voice answers are shorter and fill slow work instead of going silent. Slow
+ or multi-step requests may open with one short spoken plan; instant ones
+ just happen. Tool results carry a code-built `say` line and a `display`
+ card: sources and notes stay on screen, a caveat is spoken only when it
+ changes the answer, and "at least" and partial answers are always said. A card above the mic shows captions, the plan's steps and the
+ result. When a tool that reports steps (layers, place lookups, outlines,
+ nearest-aircraft) is still running after 1.5 s its current step is spoken
+ once; others say "still working" once after 8 s. A soft
+ tick plays in push-to-talk. Holding Space while the assistant talks cuts it
+ off. Each turn writes latency and speech figures to the debug log
+ (`node scripts/voice-turn-spans.mjs`). Captions of what you say are
+ counted in the voice cost meter; the debug log leaves out what was said
+ unless `GEV_VOICE_LOG_CONTENT=1`.
+ - Point and ask: hold Space with the cursor on an aircraft, ship or spot on
+ the map and say "what's that", "track that one" or "how many flights
+ around here". A reticle marks the point and the voice card shows what
+ "this" meant. In open mic it works when you have just moved the cursor
+ there. "The second one" picks from the last numbered list. Asking about
+ "the last one" resolves to the last of the five rows actually shown, and
+ referent-only tracking calls are accepted while empty targets are rejected.
+ Asking about
+ bare ground up close gives the assistant a small crop of the map around the
+ point. A slow render gets one bounded second frame request, while hidden,
+ stale, moved-camera, invalid and oversized captures still fail closed.
+
## [Unreleased]
+- Add an experimental ChatGPT/Codex OAuth option for cloud voice in Provider
+ Settings. API-key voice remains the default. Local sign-in can start from
+ the auth button and reports completion, failure, timeout, or expired
+ credentials. OAuth credentials stay on the server; local routes require
+ loopback access and same-site requests. OAuth sessions retain usage data
+ and show unknown cost. The auth button keeps keyboard focus after a mode
+ change, and pending sign-in does not discard text in the key fields.
+
+ - Stdio servers from one install share a panel key so a page read from one
+ process can make requests through another. Concurrent malformed-key repairs
+ now select one winner; unavailable storage or a busy repair retains the
+ logged per-process fallback. Thanks to [Jibran Tahir](https://github.com/jibraaan)
+ for #958, [MarvinNL046](https://github.com/MarvinNL046) for the report and
+ proposed diagnosis in #927, and [kvnloo](https://github.com/kvnloo) for identifying
+ the repair race. Windows/Claude Desktop Cowork confirmation remains outstanding.
+
+ - Street Level: a street-level imagery layer modelled on the iD editor's photo
+ overlay, with Mapillary as its first provider (free client token, CC BY-SA 4.0
+ imagery). One right-rail panel holds a chip per provider, shared 360°/flat and
+ captured-since filters, and an embedded viewer with EXPAND, FIT/FILL and
+ FOLLOW (Google 3D only). Coverage lines and image cones are drawn from orbit
+ down to a single street; on Google 3D they sit on the bare earth, refined
+ against the rendered mesh near the camera, so trees and buildings hide them.
+ Share links carry the provider switches, the filters and the panel's collapsed
+ state. A server proxy caches Mapillary coverage tiles (24 h, 1 GiB on disk),
+ refuses cross-site requests, rate-limits per IP and backs off when Mapillary
+ rejects the token or rate-limits.
+
+ - The CCTV and Street Level panels are portable: drag the header to float the
+ panel, resize it from any edge or corner, and double-click the header to dock
+ it again. The position persists across reloads.
+
- Add Norway's road cameras from Statens vegvesen as a CCTV pack. The camera
list is one keyless GeoJSON request to the agency's OGC API view of its
DATEX 3.1 CCTV table, so no DATEX account is needed. Every working camera
diff --cc README.md
index c6b9cfb1e,5a4ab8b24..fc9c177ae
--- a/README.md
+++ b/README.md
@@@ -249,9 -243,9 +249,9 @@@ Click **GEV MIC**, grant the microphone
- **🎯 Entity Q&A.** Click any plane, ship, or datacenter and ask _"what's this?"_ It answers using the object's live telemetry.
- **👁️ Visual grounding.** At street level, it reads a viewport screenshot to identify legible signage and building names, and is instructed never to hallucinate labels.
- **🎬 Cinematic framing.** _"Show me the planes overhead"_ pulls the camera back, angles it, and frames the live traffic like a director.
-- **🔒 Honest and secure.** The agent only confirms actions that succeeded. Your `OPENAI_API_KEY` never touches the browser; the client only gets a short-lived session token.
+- **🔒 Honest and secure.** The agent only confirms actions that succeeded. Your `OPENAI_API_KEY` never touches the browser; the client only gets a short-lived session token. If you choose **USE CHATGPT OAUTH** in Provider Settings, the local server uses that sign-in only to mint the same kind of short-lived Realtime credential, and refuses the OAuth path for non-loopback clients.
- Twenty-nine tools, four jobs — the commands below come straight from the product's voice test suite and tool playbook:
+ Thirty tools, four jobs — the commands below come straight from the product's voice test suite and tool playbook:
**🎥 Direct it** — drone-operator camera verbs:
diff --cc docs/CURRENT-STATE.md
index f7de72983,e216fab72..fd746ae12
--- a/docs/CURRENT-STATE.md
+++ b/docs/CURRENT-STATE.md
@@@ -3877,9 -4035,9 +4035,9 @@@ and unreachable upstream (502/504) sepa
`GEV MIC` button (bottom UI) starts an OpenAI Realtime session over WebRTC:
-- **Token flow**: browser fetches a short-lived client secret from `/api/realtime/token`; the Vite middleware holds `OPENAI_API_KEY` and posts the full session config (instructions, tool schemas, VAD, truncation) to `api.openai.com/v1/realtime/client_secrets`. SDP exchange goes directly to `api.openai.com/v1/realtime/calls` with the ephemeral token.
+- **Token flow**: browser fetches a short-lived client secret from `/api/realtime/token`; the Vite middleware uses `OPENAI_API_KEY` by default, or the signed-in local ChatGPT/Codex OAuth access token when OAuth was explicitly selected in Provider Settings, and posts the full session config (instructions, tool schemas, VAD, truncation) to `api.openai.com/v1/realtime/client_secrets`. Both long-lived credentials stay server-side; OAuth minting is loopback-only. SDP exchange goes directly to `api.openai.com/v1/realtime/calls` with the ephemeral token.
- **Session defaults** (env-tunable): model `gpt-realtime-2` (or `gpt-realtime-2.1-mini` when the MINI tier is selected — see the model-tier entry below), voice `marin`, reasoning effort `low`, semantic VAD with low eagerness, no response interruption, context window truncated to ~3,000 post-instruction tokens with 0.5 retention ratio — the conversational window stays short because map state is fetched live per turn.
- - **Twenty-nine tools** (argument schemas in `src/voice/actionSchemas.js`, served with their descriptions by `server/providers/openai/tools.js`, executed client-side in `src/voice/gevActions.js`): `fly_to_location`, `select_nearest_aircraft`, `adjust_camera_zoom`, `zoom_to_globe`, `set_layer_visibility`, `show_data_layers_menu`, `set_panel_open`, `set_visual_style`, `get_entity_context`, `get_current_view_state`, `set_hud`, `set_detection`, `set_map_stack`, `set_post_processing`, `control_scene`, `control_cctv`, `set_context_mode`, `control_cockpit`, `control_radio`, `track_entity`, `stop_tracking`, `frame_overhead`, `annotate_map`, `clear_annotations`, `move_camera`, `fly_route`, `analyst_query`, `next_iss_pass`, and `next_satellite_pass`.
+ - **Thirty tools** (argument schemas in `src/voice/actionSchemas.js`, served with their descriptions by `server/providers/openai/tools.js`, executed client-side in `src/voice/gevActions.js`): `fly_to_location`, `select_nearest_aircraft`, `adjust_camera_zoom`, `zoom_to_globe`, `set_layer_visibility`, `show_data_layers_menu`, `set_panel_open`, `set_visual_style`, `get_entity_context`, `get_current_view_state`, `set_hud`, `set_cyber_sonar`, `set_detection`, `set_map_stack`, `set_post_processing`, `control_scene`, `control_cctv`, `set_context_mode`, `control_cockpit`, `control_radio`, `track_entity`, `stop_tracking`, `frame_overhead`, `annotate_map`, `clear_annotations`, `move_camera`, `fly_route`, `analyst_query`, `next_iss_pass`, and `next_satellite_pass`.
> **Reading `npm test` totals:** the count depends on the Node major. The two
> GC-bracketed allocation microbenchmarks (`src/data/focusAllocations.test.mjs`
diff --cc scripts/format-scope.json
index 0d9530871,693263205..6b5c9b544
--- a/scripts/format-scope.json
+++ b/scripts/format-scope.json
@@@ -36,10 -36,9 +36,13 @@@
"src/main.js",
"docs/APPLICATION.md",
"scripts/qa-application.mjs",
+ "scripts/qa-voice-auth.mjs",
+ "scripts/qa-voice-auth-focus.mjs",
+ "src/codexOauthRealtime.test.mjs",
+ "src/voice/cloudVoiceAuth.test.mjs",
+ "scripts/qa-panel-resize.mjs",
+ "scripts/qa-panelDrag.mjs",
+ "src/tooling/panelResizeQa.test.mjs",
"scripts/qa-terrain-429.mjs",
"src/app/application.js",
"src/app/application.test.mjs",
diff --cc scripts/package-boundaries.json
index 4f7ca8ca6,2a188b4b0..23f9f52ed
--- a/scripts/package-boundaries.json
+++ b/scripts/package-boundaries.json
@@@ -1881,9 -1960,16 +1962,17 @@@
"src/voice/commands.js",
"src/voice/control.js",
"src/voice/gevActions.js",
+ "src/voice/speech.js",
+ "src/voice/earcon.js",
+ "src/voice/narration.js",
+ "src/voice/turnMetrics.js",
+ "src/voice/speechLint.js",
+ "src/voice/voiceCard.js",
+ "src/voice/voiceCardPresentation.js",
+ "src/voice/resultDisplay.js",
"src/voice/gevRealtime.js",
"src/voice/layerSummary.js",
+ "src/voice/cloudVoiceAuth.js",
"src/voice/realtimeBackend.js",
"src/voice/realtimeController.js",
"src/voice/voiceCost.js",
diff --cc server/providers/openai/realtime.js
index 588f43c77,b99f6c51f..6823c918d
--- a/server/providers/openai/realtime.js
+++ b/server/providers/openai/realtime.js
@@@ -314,10 -149,11 +324,15 @@@ function createRealtimeTokenHandler(
// case where a bogus ?tier= was silently downgraded to standard.
res.setHeader('X-GEV-Voice-Tier', tier);
res.setHeader('X-GEV-Voice-Model', model);
+ res.setHeader(
+ 'X-GEV-Voice-Auth',
+ authMode === 'oauth' ? 'codex-oauth' : 'env',
+ );
+ // Captions are billed separately; the client meters them with this id.
+ res.setHeader(
+ 'X-GEV-Voice-Transcribe-Model',
+ transcription.transcription ? transcribeModel : 'off',
+ );
if (requestedTier && !isKnownVoiceTier(requestedTier)) {
res.setHeader('X-GEV-Voice-Tier-Fallback', '1');
}
diff --cc src/setupDoctor.test.mjs
index aa825f126,761a2def9..59d4cbde1
--- a/src/setupDoctor.test.mjs
+++ b/src/setupDoctor.test.mjs
@@@ -219,20 -265,20 +265,27 @@@ test('doctor describes the credential l
OPENSKY_CLIENT_ID: { configured: false },
OPENSKY_CLIENT_SECRET: { configured: false },
LL2_API_TOKEN: { configured: true, source: 'environment' },
+ MAPILLARY_CLIENT_TOKEN: { configured: false },
};
const capabilities = buildCapabilitySummary(credentials);
- assert.match(capabilities.map, /Google Photorealistic 3D Tiles through Cesium ion/);
+ assert.match(
+ capabilities.map,
+ /Google Photorealistic 3D Tiles through Cesium ion/,
+ );
assert.match(capabilities.map, /Bing and world-terrain stacks/);
assert.equal(capabilities.voice, 'available');
+ assert.equal(
+ buildCapabilitySummary({
+ ...credentials,
+ OPENAI_API_KEY: { configured: false },
+ }).voice,
+ 'ChatGPT/Codex OAuth can be selected at runtime',
+ );
assert.match(capabilities.missions, /token allowance/);
- assert.equal(capabilities.flights, 'OpenSky keyless anonymous access (rate-limited)');
+ assert.equal(
+ capabilities.flights,
+ 'OpenSky keyless anonymous access (rate-limited)',
+ );
const report = formatSetupReport({
ready: true,
diff --cc src/tooling/localServices.test.mjs
index f6f78f6b6,9e5034e8c..075f8c837
--- a/src/tooling/localServices.test.mjs
+++ b/src/tooling/localServices.test.mjs
@@@ -197,386 -199,30 +200,410 @@@ test('Realtime handler preserves tools
assert.equal(sent[0].session.instructions, sent[2].session.instructions);
});
+test('Realtime handler keeps API key as default and uses OAuth only when requested', async (t) => {
+ env(t, 'GEV_RATELIMIT_OPENAI_PER_MIN', undefined);
+ let oauthReads = 0;
+ const authorizations = [];
+ const routes = install(
+ openAiRealtimeProxy({
+ realtime: {
+ resolveApiKey: () => 'fixture-api-key',
+ resolveOAuthAccessToken: () => {
+ oauthReads += 1;
+ return 'fixture-oauth-token';
+ },
+ fetchImpl: async (_url, options) => {
+ authorizations.push(options.headers.Authorization);
+ return Response.json({ value: 'fixture-ephemeral' });
+ },
+ },
+ }),
+ );
+ const token = routes.get('/api/realtime/token');
+
+ const apiResponse = await request(token);
+ assert.equal(apiResponse.status, 200);
+ assert.equal(apiResponse.headers['x-gev-voice-auth'], 'env');
+ assert.equal(oauthReads, 0, 'default cloud voice does not read OAuth');
+ assert.equal(authorizations.at(-1), 'Bearer fixture-api-key');
+
+ const oauthResponse = await request(token, { url: '/?auth=oauth' });
+ assert.equal(oauthResponse.status, 200);
+ assert.equal(oauthResponse.headers['x-gev-voice-auth'], 'codex-oauth');
+ assert.equal(oauthReads, 1);
+ assert.equal(authorizations.at(-1), 'Bearer fixture-oauth-token');
+});
+
+test('a Codex OAuth pin refuses API-key minting without silently switching modes', async (t) => {
+ env(t, 'GEV_RATELIMIT_OPENAI_PER_MIN', undefined);
+ const authorizations = [];
+ const routes = install(
+ openAiRealtimeProxy({
+ realtime: {
+ environment: { GEV_PREFER_CODEX_OAUTH: 'true' },
+ resolveApiKey: () => assert.fail('pinned OAuth cannot read an API key'),
+ resolveOAuthAccessToken: () => 'fixture-oauth-token',
+ fetchImpl: async (_url, options) => {
+ authorizations.push(options.headers.Authorization);
+ return Response.json({ value: 'fixture-ephemeral' });
+ },
+ },
+ }),
+ );
+ const token = routes.get('/api/realtime/token');
+ const refused = await request(token);
+ assert.equal(refused.status, 503);
+ assert.equal(refused.json().code, 'CODEX_OAUTH_REQUIRED');
+ assert.equal(authorizations.length, 0);
+ assert.equal((await request(token, { url: '/?auth=oauth' })).status, 200);
+ assert.deepEqual(authorizations, ['Bearer fixture-oauth-token']);
+});
+
+test('OAuth status and token minting never expose local OAuth to remote clients', async () => {
+ let oauthReads = 0;
+ const routes = install(
+ openAiRealtimeProxy({
+ realtime: {
+ resolveOAuthAccessToken: () => {
+ oauthReads += 1;
+ return 'must-not-be-read-remotely';
+ },
+ fetchImpl: () =>
+ assert.fail('remote OAuth request must not reach OpenAI'),
+ },
+ }),
+ );
+ const remote = { remoteAddress: '192.168.1.20' };
+ assert.equal(
+ (await request(routes.get('/api/realtime/oauth-status'), remote)).status,
+ 403,
+ );
+ assert.equal(
+ (
+ await request(routes.get('/api/realtime/token'), {
+ ...remote,
+ url: '/?auth=oauth',
+ })
+ ).status,
+ 403,
+ );
+ assert.equal(oauthReads, 0);
+});
+
+test('OAuth status reports local sign-in availability without returning the token', async () => {
+ const routes = install(
+ openAiRealtimeProxy({
+ realtime: { resolveOAuthAccessToken: () => 'fixture-oauth-secret' },
+ }),
+ );
+ const response = await request(routes.get('/api/realtime/oauth-status'));
+ assert.equal(response.status, 200);
+ assert.deepEqual(response.json(), { available: true });
+ assert.equal(response.body.includes('fixture-oauth-secret'), false);
+});
+
+test('OAuth status and token minting report expired sign-in as re-auth required', async () => {
+ const expired = () => {
+ const error = new Error('ChatGPT sign-in has expired.');
+ error.code = 'CODEX_OAUTH_REAUTH_REQUIRED';
+ throw error;
+ };
+ const routes = install(
+ openAiRealtimeProxy({
+ realtime: {
+ resolveOAuthAccessToken: expired,
+ fetchImpl: () => assert.fail('expired OAuth must not reach OpenAI'),
+ },
+ }),
+ );
+
+ const status = await request(routes.get('/api/realtime/oauth-status'));
+ assert.equal(status.status, 200);
+ assert.deepEqual(status.json(), {
+ available: false,
+ error: 'ChatGPT sign-in has expired.',
+ code: 'CODEX_OAUTH_REAUTH_REQUIRED',
+ reauthRequired: true,
+ });
+
+ const token = await request(routes.get('/api/realtime/token'), {
+ url: '/?auth=oauth',
+ });
+ assert.equal(token.status, 503);
+ assert.equal(token.json().code, 'CODEX_OAUTH_REAUTH_REQUIRED');
+});
+
+test('OAuth login endpoint shares pending attempts and never exposes credentials', async (t) => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ let starts = 0;
+ let spawnReady;
+ let exit;
+ const plugin = openAiRealtimeProxy({
+ realtime: {
+ resolveOAuthAccessToken: () => {
+ throw new Error('not signed in');
+ },
+ startOAuthLogin: async () => {
+ starts += 1;
+ await new Promise((resolve) => {
+ spawnReady = resolve;
+ });
+ return {
+ completion: new Promise((resolve) => {
+ exit = resolve;
+ }),
+ cancel() {},
+ };
+ },
+ },
+ });
+ t.after(plugin.closeBundle);
+ const routes = install(plugin);
+ const handler = routes.get('/api/realtime/oauth-login');
+
+ const firstRequest = request(handler, { method: 'POST' });
+ const concurrent = await request(handler, { method: 'POST' });
+ assert.equal(concurrent.status, 202);
+ assert.equal(concurrent.json().started, false);
+ assert.equal(starts, 1, 'reserve the attempt before awaiting spawn');
+ spawnReady();
+ const started = await firstRequest;
+ assert.equal(started.status, 202);
+ assert.deepEqual(started.json(), {
+ available: false,
+ started: true,
+ pending: true,
+ });
+ assert.equal(starts, 1);
+
+ t.mock.timers.tick(31_000);
+ const duplicate = await request(handler, { method: 'POST' });
+ assert.equal(duplicate.status, 202);
+ assert.equal(duplicate.json().pending, true);
+ assert.equal(starts, 1, 'rapid retries must not spawn another login');
+
+ const remote = await request(handler, {
+ method: 'POST',
+ remoteAddress: '192.168.1.20',
+ });
+ assert.equal(remote.status, 403);
+ assert.equal(starts, 1);
+
+ const crossOrigin = await request(handler, {
+ method: 'POST',
+ origin: 'https://example.com',
+ });
+ assert.equal(crossOrigin.status, 403);
+ assert.equal(starts, 1);
+
+ exit({ exitCode: 1 });
+ await Promise.resolve();
+ const failed = await request(routes.get('/api/realtime/oauth-status'));
+ assert.equal(failed.json().loginFailed, true);
+ assert.equal(failed.json().code, 'CODEX_OAUTH_LOGIN_FAILED');
+});
+
+test('OAuth status follows process completion, permits retry, and checks credential storage', async (t) => {
+ let token = null;
+ let exit;
+ let starts = 0;
+ const plugin = openAiRealtimeProxy({
+ realtime: {
+ resolveOAuthAccessToken: () => token,
+ startOAuthLogin: async () => {
+ starts += 1;
+ return {
+ completion: new Promise((resolve) => {
+ exit = resolve;
+ }),
+ cancel() {},
+ };
+ },
+ },
+ });
+ t.after(plugin.closeBundle);
+ const routes = install(plugin);
+ const launch = () =>
+ request(routes.get('/api/realtime/oauth-login'), { method: 'POST' });
+ const status = () => request(routes.get('/api/realtime/oauth-status'));
+ await launch();
+ exit({ exitCode: 0 });
+ await Promise.resolve();
+ assert.equal(
+ (await status()).json().code,
+ 'CODEX_OAUTH_STORAGE_UNAVAILABLE',
+ 'exit success alone is not usable sign-in',
+ );
+ await launch();
+ assert.equal(starts, 2, 'failed attempts can be retried immediately');
+ token = 'fixture-private-token';
+ exit({ exitCode: 0 });
+ await Promise.resolve();
+ const ready = await status();
+ assert.deepEqual(ready.json(), { available: true });
+ assert.equal(ready.body.includes(token), false);
+});
+
+test('OAuth login timeout and server shutdown cancel the owned process', async () => {
+ let timeout;
+ let cancelled = 0;
+ let cleared = 0;
+ const plugin = openAiRealtimeProxy({
+ realtime: {
+ resolveOAuthAccessToken: () => null,
+ startOAuthLogin: async () => ({
+ completion: new Promise(() => {}),
+ cancel() {
+ cancelled += 1;
+ },
+ }),
+ setTimer(callback, duration) {
+ timeout = callback;
+ assert.equal(duration, 120_000);
+ return 1;
+ },
+ clearTimer() {
+ cleared += 1;
+ },
+ },
+ });
+ const routes = install(plugin);
+ const launch = () =>
+ request(routes.get('/api/realtime/oauth-login'), { method: 'POST' });
+ await launch();
+ timeout();
+ assert.equal(cancelled, 1);
+ const status = await request(routes.get('/api/realtime/oauth-status'));
+ assert.equal(status.json().code, 'CODEX_OAUTH_LOGIN_TIMEOUT');
+ await launch();
+ plugin.closeBundle();
+ plugin.closeBundle();
+ assert.equal(cancelled, 2, 'shutdown is idempotent');
+ assert.equal(cleared, 2);
+});
+
+test('OAuth launch errors are safe and cross-origin status requests cannot read credentials', async () => {
+ let reads = 0;
+ const routes = install(
+ openAiRealtimeProxy({
+ realtime: {
+ resolveOAuthAccessToken() {
+ reads += 1;
+ return null;
+ },
+ startOAuthLogin: async () => {
+ throw new Error('private-token-fixture');
+ },
+ },
+ }),
+ );
+ const remote = await request(routes.get('/api/realtime/oauth-status'), {
+ origin: 'https://example.com',
+ });
+ assert.equal(remote.status, 403);
+ assert.equal(reads, 0);
+ const failed = await request(routes.get('/api/realtime/oauth-login'), {
+ method: 'POST',
+ });
+ assert.equal(failed.status, 503);
+ assert.equal(failed.json().code, 'CODEX_OAUTH_LOGIN_FAILED');
+ assert.equal(failed.body.includes('private-token-fixture'), false);
+});
+
+test('a login that spawns after timeout is cancelled and cannot replace a retry', async (t) => {
+ let timeout;
+ let releaseSpawn;
+ let cancelled = 0;
+ let launches = 0;
+ const plugin = openAiRealtimeProxy({
+ realtime: {
+ resolveOAuthAccessToken: () => null,
+ startOAuthLogin: async () => {
+ launches += 1;
+ if (launches === 1)
+ await new Promise((resolve) => {
+ releaseSpawn = resolve;
+ });
+ return {
+ completion: new Promise(() => {}),
+ cancel() {
+ cancelled += 1;
+ },
+ };
+ },
+ setTimer(callback) {
+ timeout = callback;
+ return 1;
+ },
+ clearTimer() {},
+ },
+ });
+ t.after(plugin.closeBundle);
+ const routes = install(plugin);
+ const launch = () =>
+ request(routes.get('/api/realtime/oauth-login'), { method: 'POST' });
+ const first = launch();
+ timeout();
+ await launch();
+ releaseSpawn();
+ await first;
+ assert.equal(launches, 2);
+ assert.equal(cancelled, 1, 'late process must not become an orphan');
+ const status = (
+ await request(routes.get('/api/realtime/oauth-status'))
+ ).json();
+ assert.equal(status.pending, true);
+ assert.equal(
+ status.loginFailed,
+ undefined,
+ 'the older attempt cannot fail the retry',
+ );
+});
+
+test('OAuth login endpoint selects an existing local sign-in without launching Codex', async () => {
+ const handler = install(
+ openAiRealtimeProxy({
+ realtime: {
+ resolveOAuthAccessToken: () => 'fixture-existing-secret',
+ startOAuthLogin: () =>
+ assert.fail('existing auth must not launch login'),
+ },
+ }),
+ ).get('/api/realtime/oauth-login');
+ const response = await request(handler, { method: 'POST' });
+ assert.equal(response.status, 200);
+ assert.deepEqual(response.json(), {
+ available: true,
+ started: false,
+ pending: false,
+ });
+ assert.equal(response.body.includes('fixture-existing-secret'), false);
+});
+
+ test('caption transcription is on by default, reported to the client meter, and can be turned off', async (t) => {
+ env(t, 'OPENAI_API_KEY', 'fixture-upstream-secret');
+ env(t, 'GEV_RATELIMIT_OPENAI_PER_MIN', undefined);
+ const sent = [];
+ t.mock.method(globalThis, 'fetch', async (url, options) => {
+ sent.push(JSON.parse(options.body));
+ return Response.json({ value: 'fixture-ephemeral' });
+ });
+ for (const [setting, expected] of [
+ [undefined, 'gpt-4o-mini-transcribe'],
+ ['off', 'off'],
+ ]) {
+ env(t, 'OPENAI_REALTIME_TRANSCRIBE_MODEL', setting);
+ const response = await request(
+ install(openAiRealtimeProxy()).get('/api/realtime/token'),
+ );
+ assert.equal(response.headers['x-gev-voice-transcribe-model'], expected);
+ assert.equal(
+ sent.at(-1).session.audio.input.transcription?.model ?? 'off',
+ expected,
+ );
+ }
+ });
+
test('Realtime sessions carry supplied tools, and the standalone voice adds the catalog queries', async (t) => {
env(t, 'OPENAI_API_KEY', 'fixture-upstream-secret');
env(t, 'GEV_RATELIMIT_OPENAI_PER_MIN', undefined);
diff --cc src/voice/realtimeController.js
index 999297c27,923af56d6..7cc9c8d69
--- a/src/voice/realtimeController.js
+++ b/src/voice/realtimeController.js
@@@ -239,10 -374,8 +374,11 @@@ export class GevRealtimeController exte
status: this.status,
connection: this.connectionDiagnostics(),
});
- if (this.dc && this.responseActive) this.costTracker.markIncomplete();
+ if (this.dc && this.responseActive) {
+ this.costTracker.markIncomplete();
+ this.syncCostUi();
+ }
+ this._metrics.flush('stop');
this._connection.closeTransport();
this.stopVoiceVisualizer();
this._connection.releaseMedia();
diff --cc src/voice/realtimeCost.js
index 0de89065c,9691dccad..0d48a7701
--- a/src/voice/realtimeCost.js
+++ b/src/voice/realtimeCost.js
@@@ -17,9 -17,7 +18,10 @@@ export class RealtimeCost
Object.assign(this, { readUi, readStatus }, operations);
this.voiceTier = readStoredVoiceTier();
this.voiceLimits = readStoredVoiceLimits();
+ this.cloudVoiceAuth = readStoredCloudVoiceAuthMode();
+ this.sessionCloudVoiceAuth = null;
+ this.oauthUsage = { responses: 0, input: 0, output: 0 };
+ this.transcribeModel = null;
this.costTracker = createVoiceCostTracker({
tier: this.voiceTier,
limits: this.voiceLimits,
@@@ -155,16 -138,28 +157,37 @@@
*/
recordUsage(usage) {
if (!usage) return null;
+ if (this.sessionCloudVoiceAuth === 'oauth') {
+ const count = (value) =>
+ Number.isFinite(value) && value > 0 ? value : 0;
+ this.oauthUsage.responses += 1;
+ this.oauthUsage.input += count(usage.input_tokens);
+ this.oauthUsage.output += count(usage.output_tokens);
+ this.syncCostUi();
+ return { ...this.oauthUsage, costKnown: false };
+ }
- const state = this.costTracker.record(usage);
+ return this.applyCost(this.costTracker.record(usage));
+ }
+
+ /**
+ * Meter one input transcription (voice-card captions). It is billed apart
+ * from responses, so it is priced with the transcription model the server
+ * reported and folded into the same total, warning and cap.
+ */
+ recordTranscriptionUsage(usage) {
+ if (!usage) return null;
+ return this.applyCost(
+ this.costTracker.recordUsd(
+ estimateTranscriptionCostUsd(usage, this.transcribeModel),
+ ),
+ );
+ }
+
+ bindTranscriptionModel(model) {
+ this.transcribeModel = model && model !== 'off' ? model : null;
+ }
+
+ applyCost(state) {
this.syncCostUi();
if (state.warnCrossed) {
// Exactly one line — the latch in the tracker guarantees it.