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.

refactor(voice): isolate gemini live provider core

manjunath10916227cb2c
diff --cc .env.example
index d54ccf255,2fc23f721..4ca005da8
--- a/.env.example
+++ b/.env.example
@@@ -95,6 -83,6 +83,12 @@@ OPENAI_REALTIME_TRANSCRIBE_MODEL=gpt-4o
# keep them while debugging; delete the log when you are done.
GEV_VOICE_LOG_CONTENT=
OPENAI_HUD_SUMMARY_MODEL=gpt-5-nano
++# Optional: Gemini Live voice, selected in the GEV MIC provider chooser.
++# Server-only key. Do not prefix with VITE_. Provider Settings can save it.
++GEMINI_API_KEY=
++GEMINI_LIVE_MODEL=gemini-3.8-live
++# Token starts per IP per minute; 0 disables the throttle, not provider quotas.
++# GEV_RATELIMIT_GEMINI_PER_MIN=30
# Per-IP rate limit for the OpenAI cost endpoints
# (/api/realtime/token + /api/openai/hud-summary), in requests per minute.
# DEFAULTS TO 30, the value the Pinokio build also ships. That clears ordinary
diff --cc README.md
index 847abf535,55cf47189..3b005c8dc
--- a/README.md
+++ b/README.md
@@@ -309,6 -309,6 +309,10 @@@ _Why cockpit mode exists: you're ridin
## 🎙️ Talk to It
++The standalone app offers **OpenAI** and **Gemini** in the GEV MIC provider chooser. OpenAI is the initial default; your choice is saved in this browser. To use Gemini, add `GEMINI_API_KEY` in Provider Settings or your local `.env` file, then select Gemini. `GEMINI_LIVE_MODEL` defaults to `gemini-3.8-live`. The permanent key stays on the local server, which issues a constrained, single-use session credential.
++
++Changing provider ends the current conversation. If voice is on, the new provider starts with the same open-mic or push-to-talk mode; a held Space key is not carried over. Gemini uses the same map actions and captions, but has no OpenAI cost meter or MINI tier. When Gemini reports that its session has expired, start voice again for a new conversation. The provider chooser does not change the OpenAI-backed AI HUD summary.
++
> Voice can use an **OpenAI API key** or, on the same machine, an opt-in signed-in **ChatGPT/Codex OAuth** session. The API-key path remains the default. Selecting ChatGPT OAuth in Provider Settings reuses an existing local sign-in or starts the Codex browser sign-in flow and selects OAuth when it completes. The OpenAI key still drives the **AI HUD summary**: a terse, five-word intelligence-style readout of the current view that regenerates as you move.
The OAuth option is experimental. OpenAI documents ChatGPT plan usage for the [Responses API](https://developers.openai.com/siwc/token-sharing-open-source/models-and-inference); a supported third-party Realtime contract for reusing Codex tokens has not been confirmed. A successful token mint does not establish billing or support terms.
diff --cc changelog.d/872-gemini-live-voice.md
index 000000000,000000000..519e4d37b
new file mode 100644
--- /dev/null
+++ b/changelog.d/872-gemini-live-voice.md
@@@ -1,0 -1,0 +1,4 @@@
++- Add optional Gemini Live voice to the standalone app, with a provider chooser,
++ server-held API key, microphone streaming, shared map actions and captions.
++ Switching providers ends the old conversation and preserves the input mode
++ (Manjunath, #872).
diff --cc docs/CURRENT-STATE.md
index 3af1f8633,045d6e26b..90d68d390
--- a/docs/CURRENT-STATE.md
+++ b/docs/CURRENT-STATE.md
@@@ -662,7 -618,7 +618,9 @@@ Reference feed construction is exporte
Source factories have dedicated `layers/<family>/source` exports. ALPR and earthquake record normalization and CCTV source policy no longer pull rendering into source consumers. Catalog construction and voice feed reads use their focused owners; compatibility entries remain available. Settings filesystem hardening lives under `server/standalone/`. Import-direction checks complement export ownership checks; source behavior, settings policy and rendering are unchanged.
--Voice controls bind to a protocol-independent session factory. The default WebRTC adapter preserves the existing Realtime connection, push-to-talk, cost controls and radio handoff. Session subscriptions expose state, transcript, action call/progress/result, interruption, completion and turn-metrics events; stopping or replacing a session cancels pending actions. Alternate adapters can use the same controls and action runner.
++Voice controls bind to a protocol-independent session factory. The default WebRTC adapter preserves the existing Realtime connection, push-to-talk, cost controls and radio handoff. Session subscriptions expose state, transcript, action call/progress/result, interruption, completion and turn-metrics events; stopping or replacing a session cancels pending actions. An active session's normal Stop publishes one idle transition, including adapters that emit their own terminal state; a restart triggered by that transition keeps ownership of its new startup state. Alternate adapters can use the same controls and action runner.
++
++The standalone app offers OpenAI and Gemini Live through an explicit provider chooser. Gemini keeps its permanent API key on the local server and mints a short-lived, single-use credential with server-owned instructions and the standalone action catalog. Its native WebSocket adapter supports open microphone and push-to-talk input, streaming audio, captions and the existing action runner. Switching providers ends the old conversation and releases its microphone and connection; only the input mode carries over. Gemini uses bounded shutdown draining and explicit manual restart, without automatic reconnection or a promise of uninterrupted session duration. Hosts that do not opt into the provider facade retain their existing default or custom adapter.
Voice action argument schemas have one portable owner under `src/voice/actionSchemas.js`. The Realtime provider builds 30 tools using separate description-only metadata. Description customization cannot replace argument types, enum values or required fields.
diff --cc scripts/package-boundaries.json
index 78f855a48,264f58440..ca5dc0c7f
--- a/scripts/package-boundaries.json
+++ b/scripts/package-boundaries.json
@@@ -1440,11 -1629,11 +1629,19 @@@
"src/voice/earcon.js",
"src/voice/pointerContext.js",
"src/voice/pointerReticle.js",
+ "src/i18n/index.js",
+ "src/i18n/locale.js",
+ "src/i18n/locales/es.json",
+ "src/i18n/locales/ru.json",
- "src/ui/statusText.js"
++ "src/ui/statusText.js",
++ "src/voice/providerCommands.js",
+ "src/voice/providerCapabilities.js",
- "src/voice/providerIntent.js",
- "src/voice/providerIntentFragments.js",
- "src/voice/userTurnIntent.js",
- "src/voice/toolExecutionPolicy.js"
++ "src/voice/geminiSession.js",
++ "src/voice/geminiAudio.js",
++ "src/voice/geminiCaptureWorklet.js",
++ "src/sources/httpBody.js",
++ "src/sources/requestDeadline.js",
++ "src/i18n/marker.js"
],
"external": []
},
@@@ -2289,12 -2496,8 +2504,13 @@@
"src/app/layers/airQuality.js",
"src/layers/airQuality/index.js",
"src/layers/airQuality/model.js",
- "src/layers/airQuality/source.js"
+ "src/layers/airQuality/source.js",
- "src/ui/statusText.js"
++ "src/ui/statusText.js",
++ "src/voice/providerCommands.js",
++ "src/voice/providerCapabilities.js",
++ "src/voice/geminiSession.js",
++ "src/voice/geminiAudio.js",
++ "src/voice/geminiCaptureWorklet.js"
],
"external": [
"hls.js",
@@@ -3124,7 -3377,15 +3390,16 @@@
"src/voice/referents.js",
"src/voice/layerManifest.js",
"src/voice/speech.js",
- "src/voice/pointerReticle.js"
+ "src/cityPois.js",
+ "src/ui/layerNames.js",
+ "src/ui/unitLabels.js",
+ "src/voice/pointerReticle.js",
+ "src/i18n/index.js",
+ "src/i18n/locale.js",
+ "src/i18n/locales/es.json",
+ "src/i18n/locales/ru.json",
- "src/ui/statusText.js"
++ "src/ui/statusText.js",
++ "src/voice/providerCapabilities.js"
],
"external": []
},
diff --cc scripts/track-regression.mjs
index 756daccfc,756daccfc..5ba1bc2b0
--- a/scripts/track-regression.mjs
+++ b/scripts/track-regression.mjs
@@@ -657,6 -657,6 +657,7 @@@ async function main()
// SHARE LINK V2 — real reload restores the same logical plane.
// ============================================================
console.log('\nShare Link v2 — tracked aircraft survives a full reload');
++ await evalPage(() => window.__godsEyeView.styleManager.initialRestorePromise);
const shareTracked = await evalPage(() => (
window.__godsEyeView.dataManager.layers
.get('flights').module.trackById('aaa001', { origin: 'user' })
diff --cc server/providers/common/request.js
index 93bbbaa85,93bbbaa85..3a45bdd30
--- a/server/providers/common/request.js
+++ b/server/providers/common/request.js
@@@ -14,16 -14,16 +14,34 @@@ async function readRequestBodyCapped(re
return Buffer.concat(chunks);
}
--function readRequestBody(req, maxBytes = 1024 * 1024) {
++/** Optional cancellation discards buffered data while the request drains. */
++function readRequestBody(req, maxBytes = 1024 * 1024, signal) {
return new Promise((resolve, reject) => {
let total = 0;
let bodyTooLarge = false;
++ let settled = false;
const chunks = [];
-- req.on('data', (chunk) => {
++ const stopReading = () => {
++ if (!signal) return;
++ req.off('data', data);
++ req.off('end', end);
++ signal.removeEventListener('abort', abort);
++ };
++ const fail = (error) => {
++ if (signal) {
++ if (settled) return;
++ settled = true;
++ chunks.length = 0;
++ signal.removeEventListener('abort', abort);
++ }
++ reject(error);
++ };
++ const abort = () => fail(signal.reason);
++ const data = (chunk) => {
// Keep draining after the cap without retaining more bytes. Destroying
// the request also destroys its socket, so the handler cannot deliver
// the fixed error response it constructs for BODY_TOO_LARGE.
-- if (bodyTooLarge) return;
++ if (bodyTooLarge || settled) return;
total += chunk.length;
if (total > maxBytes) {
// Same marker readRequestBodyCapped sets, so a caller can tell an
@@@ -32,15 -32,15 +50,42 @@@
chunks.length = 0;
const error = new Error(`Request body exceeds ${maxBytes} bytes`);
error.code = 'BODY_TOO_LARGE';
-- reject(error);
++ fail(error);
return;
}
chunks.push(chunk);
-- });
-- req.on('end', () => {
++ };
++ const end = () => {
++ if (settled) {
++ stopReading();
++ return;
++ }
if (!bodyTooLarge) resolve(Buffer.concat(chunks).toString('utf8'));
-- });
-- req.on('error', reject);
++ if (signal) {
++ settled = true;
++ chunks.length = 0;
++ stopReading();
++ }
++ };
++ const close = () => {
++ fail(
++ new DOMException('Request closed before its body ended', 'AbortError'),
++ );
++ stopReading();
++ req.off('error', fail);
++ req.off('close', close);
++ };
++ if (signal) {
++ // Abort/overflow release retained bytes but keep draining. Retain an
++ // error handler until close, including a late error after end/abort.
++ req.on('close', close);
++ signal.addEventListener('abort', abort, { once: true });
++ if (signal.aborted) abort();
++ }
++ req.on('data', data);
++ req.on('end', end);
++ req.on('error', fail);
++ if (signal && req.destroyed) close();
});
}
diff --cc server/providers/common/request.test.mjs
index 000000000,000000000..0360e6a04
new file mode 100644
--- /dev/null
+++ b/server/providers/common/request.test.mjs
@@@ -1,0 -1,0 +1,137 @@@
++import test from 'node:test';
++import assert from 'node:assert/strict';
++import { EventEmitter, getEventListeners } from 'node:events';
++import { readRequestBody } from './request.js';
++
++function fixture() {
++ const req = new EventEmitter();
++ req.pause = () => assert.fail('The reader must keep draining');
++ req.destroy = () =>
++ assert.fail('The reader must preserve the response socket');
++ const owner = new AbortController();
++ return { req, owner };
++}
++
++function finish(req, owner) {
++ assert.doesNotThrow(() => req.emit('error', new Error('late stream error')));
++ req.emit('end');
++ assert.doesNotThrow(() => req.emit('error', new Error('error before close')));
++ req.emit('close');
++ for (const event of ['data', 'end', 'error', 'close'])
++ assert.equal(req.listenerCount(event), 0, event);
++ assert.equal(getEventListeners(owner.signal, 'abort').length, 0);
++}
++
++test('default and cancellable readers preserve byte caps and UTF-8 across chunks', async () => {
++ for (const useSignal of [false, true]) {
++ for (const text of ['', 'hello', 'é']) {
++ const { req, owner } = fixture();
++ const bytes = Buffer.from(text);
++ const body = readRequestBody(
++ req,
++ bytes.length,
++ useSignal ? owner.signal : undefined,
++ );
++ for (const byte of bytes) req.emit('data', Buffer.from([byte]));
++ req.emit('end');
++ assert.equal(await body, text);
++ if (useSignal) finish(req, owner);
++ }
++ }
++});
++
++test('default overflow rejects before end and drains without pausing or destroying', async () => {
++ const { req } = fixture();
++ const rejection = assert.rejects(readRequestBody(req, 2), {
++ code: 'BODY_TOO_LARGE',
++ });
++ req.emit('data', Buffer.from('é'));
++ req.emit('data', Buffer.from('!'));
++ await rejection;
++ req.emit('data', Buffer.alloc(4096));
++ assert.doesNotThrow(() => req.emit('error', new Error('late')));
++ req.emit('end');
++});
++
++test('partial abort settles before end, discards late data and guards errors until close', async () => {
++ const { req, owner } = fixture();
++ const reason = new Error('request deadline');
++ const rejection = assert.rejects(
++ readRequestBody(req, 1024, owner.signal),
++ (error) => error === reason,
++ );
++ req.emit('data', Buffer.from('partial'));
++ owner.abort(reason);
++ await rejection;
++ assert.equal(getEventListeners(owner.signal, 'abort').length, 0);
++ req.emit('data', Buffer.alloc(4096));
++ finish(req, owner);
++});
++
++test('already-aborted and already-closed requests settle and release their listeners', async () => {
++ for (const closed of [false, true]) {
++ const { req, owner } = fixture();
++ if (closed) req.destroyed = true;
++ else owner.abort();
++ await assert.rejects(readRequestBody(req, 1024, owner.signal), {
++ name: 'AbortError',
++ });
++ if (!closed) finish(req, owner);
++ for (const event of ['data', 'end', 'error', 'close'])
++ assert.equal(req.listenerCount(event), 0);
++ assert.equal(getEventListeners(owner.signal, 'abort').length, 0);
++ }
++});
++
++test('overflow keeps its first failure through later abort and stream errors', async () => {
++ const { req, owner } = fixture();
++ const rejection = assert.rejects(readRequestBody(req, 2, owner.signal), {
++ code: 'BODY_TOO_LARGE',
++ });
++ req.emit('data', Buffer.from('é!'));
++ await rejection;
++ owner.abort(new Error('later deadline'));
++ req.emit('data', Buffer.alloc(4096));
++ finish(req, owner);
++});
++
++test('early close and request error reject once; successful end wins over later abort', async () => {
++ for (const event of ['close', 'error', 'end']) {
++ const { req, owner } = fixture();
++ const reason = new Error('request failed');
++ const body = readRequestBody(req, 32, owner.signal);
++ const observed =
++ event === 'end'
++ ? body.then((value) => assert.equal(value, 'ok'))
++ : assert.rejects(
++ body,
++ event === 'close'
++ ? { name: 'AbortError' }
++ : (error) => error === reason,
++ );
++ req.emit('data', Buffer.from('ok'));
++ req.emit(event, reason);
++ owner.abort(new Error('later abort'));
++ await observed;
++ if (event !== 'close') finish(req, owner);
++ assert.equal(getEventListeners(owner.signal, 'abort').length, 0);
++ }
++});
++
++test('a prior data observer can abort synchronously without retaining or resolving that chunk', async () => {
++ const { req, owner } = fixture();
++ const reason = new Error('observer stopped request');
++ const external = () => owner.abort(reason);
++ req.on('data', external);
++ const rejection = assert.rejects(
++ readRequestBody(req, 1024, owner.signal),
++ (error) => error === reason,
++ );
++ req.emit('data', Buffer.from('must be discarded'));
++ await rejection;
++ req.emit('end');
++ req.emit('close');
++ assert.deepEqual(req.listeners('data'), [external]);
++ assert.equal(getEventListeners(owner.signal, 'abort').length, 0);
++ req.off('data', external);
++});
diff --cc server/providers/gemini/config.js
index b15455cab,000000000..4fa438d15
mode 100644,000000..100644
--- a/server/providers/gemini/config.js
+++ b/server/providers/gemini/config.js
@@@ -1,54 -1,0 +1,53 @@@
+import { realtimeInstructions } from '../openai/instructions.js';
+import { GEV_REALTIME_TOOLS } from '../openai/tools.js';
+
+export const GEMINI_LIVE_MODEL_DEFAULT = 'gemini-3.8-live';
+export const GEMINI_TOKEN_ENDPOINT =
+ 'https://generativelanguage.googleapis.com/v1beta/auth_tokens';
+export const GEMINI_LIVE_WEBSOCKET_URL =
+ 'wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContentConstrained';
+
+export function normalizeGeminiModel(value) {
+ const model = String(value ?? GEMINI_LIVE_MODEL_DEFAULT)
+ .trim()
+ .replace(/^models\//, '');
+ return /^gemini-[a-z0-9][a-z0-9.-]{0,119}$/.test(model) ? model : null;
+}
+
+/** REST BidiGenerateContentSetup fields, excluding its model resource name. */
+export function createGeminiLiveConfig(
+ annotationGuidance,
+ inputMode = 'open-mic',
+ tools = GEV_REALTIME_TOOLS,
- capabilities,
+) {
+ if (!['open-mic', 'push-to-talk'].includes(inputMode))
+ throw new Error('Invalid Gemini input mode');
+ const config = {
+ generationConfig: { responseModalities: ['AUDIO'] },
+ systemInstruction: {
- parts: [{ text: realtimeInstructions(annotationGuidance, capabilities) }],
++ parts: [{ text: realtimeInstructions(annotationGuidance) }],
+ },
+ tools: [
+ {
+ functionDeclarations: tools.map(
+ ({ name, description, parameters }) => ({
+ name,
+ description,
+ // GEV's canonical schemas are JSON Schema, not Google's Schema.
+ parametersJsonSchema: structuredClone(parameters),
+ // App actions must finish before the model confirms their result.
+ behavior: 'BLOCKING',
+ }),
+ ),
+ },
+ ],
+ inputAudioTranscription: {},
+ outputAudioTranscription: {},
+ contextWindowCompression: { slidingWindow: {} },
+ };
+ if (inputMode === 'push-to-talk')
+ config.realtimeInputConfig = {
+ automaticActivityDetection: { disabled: true },
+ };
+ return config;
+}
diff --cc server/providers/gemini/realtime.js
index db3a95b72,000000000..dbbdba345
mode 100644,000000..100644
--- a/server/providers/gemini/realtime.js
+++ b/server/providers/gemini/realtime.js
@@@ -1,180 -1,0 +1,208 @@@
++import { waitForSignal } from '../../../src/sources/requestDeadline.js';
+import { clientKey, makeCostRateLimiter } from '../common/rate-limit.js';
+import { readResponseJsonCapped } from '../../../src/sources/httpBody.js';
+import {
+ GEMINI_TOKEN_ENDPOINT,
+ GEMINI_LIVE_WEBSOCKET_URL,
+ GEMINI_LIVE_MODEL_DEFAULT,
+ createGeminiLiveConfig,
+ normalizeGeminiModel,
+} from './config.js';
+import {
+ isGeminiRequestOriginAllowed,
+ readGeminiTokenRequest,
+} from './request.js';
+
+const UPSTREAM_RESPONSE_BYTES = 32 * 1024;
+const MINT_FAILURE = 'Gemini voice could not connect. Try again.';
+
+export function createGeminiTokenHandler({
+ annotationGuidance,
- providerDropdown = false,
+ tools,
+ fetchImpl = (...args) => fetch(...args),
+ resolveApiKey = () => process.env.GEMINI_API_KEY,
+ resolveModel = () =>
+ process.env.GEMINI_LIVE_MODEL || GEMINI_LIVE_MODEL_DEFAULT,
+ resolveHost = () => process.env.HOST,
+ resolveAllowedHosts = () => process.env.GEV_ALLOWED_HOSTS,
+ resolveRateLimit = () => process.env.GEV_RATELIMIT_GEMINI_PER_MIN ?? '30',
+ now = Date.now,
+ timeoutMs = 15_000,
+} = {}) {
+ let limiter;
+ return async (req, res) => {
++ if (req.aborted || res.destroyed || res.writableEnded) return;
+ res.setHeader('Cache-Control', 'no-store');
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
+ res.setHeader('X-Content-Type-Options', 'nosniff');
+ const reply = (status, errorOrPayload) => {
+ if (res.destroyed || res.writableEnded) return;
+ res.statusCode = status;
+ if (status >= 400) res.setHeader('Connection', 'close');
+ res.end(
+ JSON.stringify(
+ typeof errorOrPayload === 'string'
+ ? { error: errorOrPayload }
+ : errorOrPayload,
+ ),
+ );
+ };
+ if (req.method !== 'POST') {
+ res.setHeader('Allow', 'POST');
+ return reply(405, 'Method not allowed');
+ }
- if (
- !isGeminiRequestOriginAllowed(req, resolveHost(), resolveAllowedHosts())
- )
- return reply(403, 'Gemini voice requires a same-origin app request');
- const apiKey = String(resolveApiKey() || '').trim();
- if (!apiKey) return reply(503, 'Add a Gemini API key in Provider Settings');
- const model = normalizeGeminiModel(resolveModel());
- if (!model)
- return reply(503, 'The Gemini Live model configuration is invalid');
- if (limiter === undefined)
- limiter = makeCostRateLimiter(resolveRateLimit(), 30);
- if (limiter && !limiter(clientKey(req))) {
- res.setHeader('Retry-After', '60');
- return reply(
- 429,
- 'Gemini voice is starting too often. Try again shortly.',
- );
++ let apiKey;
++ let model;
++ try {
++ if (
++ !isGeminiRequestOriginAllowed(req, resolveHost(), resolveAllowedHosts())
++ )
++ return reply(403, 'Gemini voice requires a same-origin app request');
++ apiKey = String(resolveApiKey() || '').trim();
++ if (!apiKey)
++ return reply(503, 'Add a Gemini API key in Provider Settings');
++ model = normalizeGeminiModel(resolveModel());
++ if (!model)
++ return reply(503, 'The Gemini Live model configuration is invalid');
++ if (limiter === undefined)
++ limiter = makeCostRateLimiter(resolveRateLimit(), 30);
++ if (limiter && !limiter(clientKey(req))) {
++ res.setHeader('Retry-After', '60');
++ return reply(
++ 429,
++ 'Gemini voice is starting too often. Try again shortly.',
++ );
++ }
++ } catch {
++ // Connect does not observe the handler's returned promise. A synchronous
++ // configuration resolver must fail with a bounded, fixed response.
++ return reply(503, MINT_FAILURE);
+ }
+
+ const lifetime = new AbortController();
+ let disconnected = false;
+ const disconnect = () => {
+ disconnected = true;
+ lifetime.abort(new DOMException('Request closed', 'AbortError'));
+ };
+ const responseClosed = () => {
+ if (!res.writableEnded) disconnect();
+ };
+ req.once('aborted', disconnect);
+ res.once('close', responseClosed);
+ const deadline = setTimeout(() => {
+ lifetime.abort(
+ new DOMException('Token request timed out', 'TimeoutError'),
+ );
+ }, timeoutMs);
+ deadline.unref?.();
++ let acquiredResponse;
+ try {
+ const inputMode = await readGeminiTokenRequest(req, lifetime.signal);
+ lifetime.signal.throwIfAborted();
+ const config = createGeminiLiveConfig(
+ annotationGuidance,
+ inputMode,
+ tools,
- { providerDropdown },
+ );
+ const issuedAt = now();
+ // REST uses bidiGenerateContentSetup. liveConnectConstraints is the SDK
+ // input shape, converted before transport. With no fieldMask the complete
+ // setup is locked to this server-owned configuration.
+ const request = {
+ uses: 1,
+ expireTime: new Date(issuedAt + 30 * 60_000).toISOString(),
+ newSessionExpireTime: new Date(issuedAt + 60_000).toISOString(),
+ bidiGenerateContentSetup: { model: `models/${model}`, ...config },
+ };
- const response = await fetchImpl(GEMINI_TOKEN_ENDPOINT, {
- method: 'POST',
- redirect: 'error',
- signal: lifetime.signal,
- headers: {
- 'x-goog-api-key': apiKey,
- 'Content-Type': 'application/json',
++ const acquisition = Promise.resolve(
++ fetchImpl(GEMINI_TOKEN_ENDPOINT, {
++ method: 'POST',
++ redirect: 'error',
++ signal: lifetime.signal,
++ headers: {
++ 'x-goog-api-key': apiKey,
++ 'Content-Type': 'application/json',
++ },
++ body: JSON.stringify(request),
++ }),
++ );
++ // A fetch implementation can ignore abort. Bound this caller's wait and
++ // discard a response that arrives after timeout/disconnection.
++ void acquisition.then(
++ (late) => {
++ acquiredResponse = late;
++ if (lifetime.signal.aborted) void late.body?.cancel().catch(() => {});
+ },
- body: JSON.stringify(request),
- });
++ () => {},
++ );
++ const response = await waitForSignal(acquisition, lifetime.signal);
+ lifetime.signal.throwIfAborted();
+ if (
+ response.redirected ||
+ (response.url && response.url !== GEMINI_TOKEN_ENDPOINT)
- )
++ ) {
++ void response.body?.cancel().catch(() => {});
+ throw new Error('Unexpected token response destination');
++ }
+ if (!response.ok) {
+ // Never forward upstream bodies, headers or exception messages.
+ void response.body?.cancel().catch(() => {});
+ if (response.status === 429) {
+ res.setHeader('Retry-After', '60');
+ return reply(429, 'Gemini quota is unavailable. Try again later.');
+ }
+ if (response.status === 401 || response.status === 403)
+ return reply(
+ 503,
+ 'Gemini access was refused. Check the API key and model access.',
+ );
+ if (response.status === 400 || response.status === 404)
+ return reply(
+ 502,
+ 'Gemini Live is unavailable for the configured model.',
+ );
+ return reply(502, MINT_FAILURE);
+ }
+ const data = await readResponseJsonCapped(
+ response,
+ UPSTREAM_RESPONSE_BYTES,
+ lifetime.signal,
+ );
+ lifetime.signal.throwIfAborted();
+ if (
+ !data ||
+ Array.isArray(data) ||
+ typeof data !== 'object' ||
+ typeof data.name !== 'string' ||
+ data.name.length > 8192 ||
+ !/^auth_tokens\/[A-Za-z0-9._~+/=-]+$/.test(data.name) ||
+ data.name.includes(apiKey)
+ )
+ throw new Error('Invalid ephemeral token');
+ reply(200, {
+ token: data.name,
+ model,
+ config,
+ websocketUrl: GEMINI_LIVE_WEBSOCKET_URL,
+ });
+ } catch (error) {
+ if (disconnected || req.aborted) return;
+ if (error?.code === 'BODY_TOO_LARGE')
+ return reply(413, 'Token request is too large');
+ if (error?.code === 'BAD_CONTENT_TYPE')
+ return reply(415, 'Use an empty JSON token request');
+ if (error?.code === 'BAD_BODY')
+ return reply(400, 'Use an empty JSON token request');
+ reply(lifetime.signal.aborted ? 504 : 502, MINT_FAILURE);
+ } finally {
++ // Abort can happen after acquisition resolves but before this handler
++ // resumes and passes ownership to the body reader.
++ if (lifetime.signal.aborted)
++ void acquiredResponse?.body?.cancel().catch(() => {});
+ clearTimeout(deadline);
+ req.off('aborted', disconnect);
+ res.off('close', responseClosed);
+ }
+ };
+}
diff --cc server/providers/gemini/request.js
index 6ce807e24,000000000..0ce54d5ab
mode 100644,000000..100644
--- a/server/providers/gemini/request.js
+++ b/server/providers/gemini/request.js
@@@ -1,117 -1,0 +1,93 @@@
++import { readRequestBody } from '../common/request.js';
+import { admitSameSiteRequest } from '../../../src/localRequestGate.mjs';
+import {
+ isAllowedHost,
+ resolveAllowedHosts,
+} from '../../../build/allowedHosts.js';
+
+/** Use the app's Host and request policies, with a required browser Origin. */
+export function isGeminiRequestOriginAllowed(
+ req,
+ configuredHost = '',
+ configuredAllowedHosts,
+) {
+ const host = req.headers?.host;
+ const origin = req.headers?.origin;
+ if (
+ typeof host !== 'string' ||
+ typeof origin !== 'string' ||
+ !host ||
+ /[\s/?#@\\]/.test(host)
+ )
+ return false;
+ const protocol = req.socket?.encrypted ? 'https:' : 'http:';
+ if (
+ !admitSameSiteRequest({
+ hostHeader: host,
+ protocol,
+ origin,
+ secFetchSite: req.headers?.['sec-fetch-site'],
+ proxyHeaders: req.headers || {},
+ }).ok
+ )
+ return false;
+ const boundHost = String(configuredHost || '')
+ .trim()
+ .toLowerCase();
+ if (
+ !isAllowedHost(host, resolveAllowedHosts(configuredAllowedHosts), [
+ boundHost,
+ ])
+ )
+ return false;
+ try {
+ const authority = new URL(`${protocol}//${host}`);
+ const source = new URL(origin);
+ return (
+ source.origin === authority.origin &&
+ source.username === '' &&
+ source.password === '' &&
+ source.pathname === '/' &&
+ source.search === '' &&
+ source.hash === ''
+ );
+ } catch {
+ return false;
+ }
+}
+
+/** Admit only the existing input gesture; callers cannot supply model/setup. */
+export async function readGeminiTokenRequest(req, signal, maxBytes = 1024) {
+ const declared = Number(req.headers?.['content-length']);
+ const fail = (code) =>
+ Object.assign(new Error('Invalid token request'), { code });
- if (Number.isFinite(declared) && declared > maxBytes)
- throw fail('BODY_TOO_LARGE');
- const body = await new Promise((resolve, reject) => {
- let total = 0;
- const chunks = [];
- const cleanup = () => {
- req.off('data', data);
- req.off('end', end);
- req.off('error', error);
- signal.removeEventListener('abort', abort);
- };
- const error = (reason) => {
- cleanup();
- req.pause();
- reject(reason);
- };
- const abort = () => error(signal.reason);
- const data = (chunk) => {
- total += chunk.length;
- if (total > maxBytes) return error(fail('BODY_TOO_LARGE'));
- chunks.push(chunk);
- };
- const end = () => {
- cleanup();
- resolve(Buffer.concat(chunks).toString('utf8'));
- };
- req.on('data', data);
- req.once('end', end);
- req.once('error', error);
- signal.addEventListener('abort', abort, { once: true });
- if (signal.aborted) abort();
- });
++ const body = await readRequestBody(
++ req,
++ maxBytes,
++ Number.isFinite(declared) && declared > maxBytes
++ ? AbortSignal.abort(fail('BODY_TOO_LARGE'))
++ : signal,
++ );
+ if (!body.trim()) return 'open-mic';
+ if (
+ !/^application\/json(?:\s*;|$)/i.test(req.headers?.['content-type'] || '')
+ )
+ throw fail('BAD_CONTENT_TYPE');
+ let parsed;
+ try {
+ parsed = JSON.parse(body);
+ } catch {
+ throw fail('BAD_BODY');
+ }
+ if (!parsed || Array.isArray(parsed) || typeof parsed !== 'object')
+ throw fail('BAD_BODY');
+ const keys = Object.keys(parsed);
+ if (!keys.length) return 'open-mic';
+ if (
+ keys.length === 1 &&
+ keys[0] === 'inputMode' &&
+ parsed.inputMode === 'push-to-talk'
+ )
+ return 'push-to-talk';
+ throw fail('BAD_BODY');
+}
diff --cc server/providers/local.js
index 816df3e40,854b77f33..5d39c3a01
--- a/server/providers/local.js
+++ b/server/providers/local.js
@@@ -31,9 -30,9 +31,9 @@@ import { windProxy } from './wind.js'
/**
* Construct the local provider plugins in their established order.
-- * `realtime` configures the voice session token endpoint.
++ * `realtime` configures OpenAI; `gemini` explicitly opts into Gemini Live.
*/
--function localProviderPlugins({ realtime } = {}) {
++function localProviderPlugins({ realtime, gemini } = {}) {
return [
openSkyProxy(),
celestrakProxy(),
@@@ -56,7 -55,6 +56,7 @@@
aisLiveProxy(),
trackBackfillProxies(),
openAiRealtimeProxy({ realtime }),
- geminiLiveProxy({ realtime }),
++ ...(gemini ? [geminiLiveProxy({ realtime: gemini })] : []),
googlePlacesContextProxy(),
windProxy(),
weatherProxy(),
diff --cc server/standalone/vite.config.js
index 3a1b4cf2a,03a935092..ffe5124ce
--- a/server/standalone/vite.config.js
+++ b/server/standalone/vite.config.js
@@@ -15,13 -16,12 +16,13 @@@ export default defineConfig(({ command
for (const [key, value] of Object.entries(loaded)) {
if (process.env[key] === undefined) process.env[key] = value;
}
++ const tools = standaloneVoiceTools();
return createBrowserViteConfig({
plugins: [
- ...localProviderPlugins({
- realtime: { tools: standaloneVoiceTools(), providerDropdown: true },
- }),
- ...localProviderPlugins({ realtime: { tools: standaloneVoiceTools() } }),
++ ...localProviderPlugins({ realtime: { tools }, gemini: { tools } }),
localMcpPlugin(),
apiNotFoundPlugin(),
+ unwatchedRuntimeDirsPlugin(),
],
googleApiKey: process.env.GOOGLE_MAPS_API_KEY,
cesiumToken: process.env.CESIUM_ION_TOKEN,
diff --cc src/geminiComposition.test.mjs
index 000000000,000000000..1dcd7f1c4
new file mode 100644
--- /dev/null
+++ b/src/geminiComposition.test.mjs
@@@ -1,0 -1,0 +1,115 @@@
++import test from 'node:test';
++import assert from 'node:assert/strict';
++import { EventEmitter } from 'node:events';
++import { PassThrough } from 'node:stream';
++import { localProviderPlugins } from '../server/providers/local.js';
++import { standaloneVoiceTools } from '../server/standalone/voiceTools.js';
++import {
++ KEY_SETUP_KEYS,
++ keySetupStatus,
++ validateKeySetupUpdates,
++ upsertDotenvValues,
++} from './keySetupCore.mjs';
++
++test('local hosts opt into Gemini explicitly and retain the default plugin order', (t) => {
++ t.mock.method(globalThis, 'fetch', () => {
++ throw Error('construction must not fetch');
++ });
++ const defaults = localProviderPlugins().map((plugin) => plugin.name);
++ assert.ok(!defaults.includes('gemini-live-proxy'));
++ const enabled = localProviderPlugins({ gemini: {} }).map(
++ (plugin) => plugin.name,
++ );
++ assert.equal(
++ enabled.filter((name) => name === 'gemini-live-proxy').length,
++ 1,
++ );
++ assert.deepEqual(
++ enabled.filter((name) => name !== 'gemini-live-proxy'),
++ defaults,
++ );
++});
++
++for (const hook of ['configureServer', 'configurePreviewServer']) {
++ test(`opted-in ${hook} locks the standalone catalog into the Gemini token`, async () => {
++ const tools = standaloneVoiceTools();
++ const calls = [];
++ const plugin = localProviderPlugins({
++ gemini: {
++ tools,
++ resolveApiKey: () => 'fixture-key',
++ resolveModel: () => 'gemini-3.8-live',
++ resolveHost: () => '',
++ resolveAllowedHosts: () => '',
++ resolveRateLimit: () => '0',
++ fetchImpl: async (url, options) => {
++ calls.push({ url, options });
++ return Response.json({ name: 'auth_tokens/fixture' });
++ },
++ },
++ }).find((entry) => entry.name === 'gemini-live-proxy');
++ let handler;
++ plugin[hook]({
++ middlewares: {
++ use(route, value) {
++ assert.equal(route, '/api/gemini/token');
++ handler = value;
++ },
++ },
++ });
++ const req = new PassThrough();
++ req.method = 'POST';
++ req.headers = {
++ host: 'localhost:5173',
++ origin: 'http://localhost:5173',
++ 'content-type': 'application/json',
++ };
++ req.socket = { remoteAddress: '127.0.0.1' };
++ const res = new EventEmitter();
++ res.setHeader = () => {};
++ res.end = (body) => {
++ res.body = JSON.parse(body);
++ res.writableEnded = true;
++ };
++ req.end('{}');
++ await handler(req, res);
++ assert.equal(res.statusCode, 200);
++ assert.equal(calls.length, 1);
++ const locked = JSON.parse(calls[0].options.body).bidiGenerateContentSetup
++ .tools[0].functionDeclarations;
++ assert.deepEqual(
++ locked.map(({ name }) => name),
++ tools.map(({ name }) => name),
++ );
++ assert.deepEqual(
++ locked.map(({ parametersJsonSchema }) => parametersJsonSchema),
++ tools.map(({ parameters }) => parameters),
++ );
++ assert.ok(locked.every(({ behavior }) => behavior === 'BLOCKING'));
++ assert.deepEqual(res.body.config.tools[0].functionDeclarations, locked);
++ assert.ok(!JSON.stringify(res.body).includes('fixture-key'));
++ });
++}
++
++test('Gemini key setup uses the existing server-only status and save contract', () => {
++ const entry = KEY_SETUP_KEYS.find(({ id }) => id === 'gemini');
++ assert.deepEqual(entry.envVars, ['GEMINI_API_KEY']);
++ assert.ok(!entry.clientExposed);
++ assert.equal(
++ keySetupStatus({}).keys.find(({ id }) => id === 'gemini').set,
++ false,
++ );
++ const env = { GEMINI_API_KEY: 'fixture-private-key' };
++ const status = keySetupStatus(env);
++ assert.equal(status.keys.find(({ id }) => id === 'gemini').set, true);
++ assert.ok(!JSON.stringify(status).includes(env.GEMINI_API_KEY));
++ assert.equal(validateKeySetupUpdates(env).ok, true);
++ assert.match(
++ upsertDotenvValues('GEMINI_API_KEY=old\n', env),
++ /^GEMINI_API_KEY=fixture-private-key\n$/,
++ );
++ assert.equal(
++ validateKeySetupUpdates({ VITE_GEMINI_API_KEY: 'fixture-private-key' }).ok,
++ false,
++ );
++});
diff --cc src/geminiServer.test.mjs
index f7630fe23,000000000..b9addf3f9
mode 100644,000000..100644
--- a/src/geminiServer.test.mjs
+++ b/src/geminiServer.test.mjs
@@@ -1,793 -1,0 +1,1031 @@@
- import test from 'node:test';
- import assert from 'node:assert/strict';
- import http from 'node:http';
- import { once } from 'node:events';
+import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { createServer, preview } from 'vite';
+import { hostCheckPlugin, resolveAllowedHosts } from '../build/allowedHosts.js';
++import { standaloneVoiceTools } from '../server/standalone/voiceTools.js';
++import test from 'node:test';
++import assert from 'node:assert/strict';
++import http from 'node:http';
++import { EventEmitter, once } from 'node:events';
++import { PassThrough } from 'node:stream';
+import { geminiLiveProxy } from '../server/providers/gemini.js';
+import { createGeminiTokenHandler } from '../server/providers/gemini/realtime.js';
+import {
+ GEMINI_TOKEN_ENDPOINT,
+ GEMINI_LIVE_WEBSOCKET_URL,
+ createGeminiLiveConfig,
+} from '../server/providers/gemini/config.js';
+import { GEV_REALTIME_TOOLS } from '../server/providers/openai/tools.js';
- import { standaloneVoiceTools } from '../server/standalone/voiceTools.js';
+import { PROXY_SIGNALS } from './localRequestGate.mjs';
+
+const API_KEY = 'private-gemini-test-key-never-return';
+const TOKEN = 'auth_tokens/short-lived-test';
+const ISSUED_AT = Date.parse('2026-09-29T12:00:00Z');
+
+async function fixture(t, options = {}) {
+ const calls = [];
+ const handler = createGeminiTokenHandler({
+ resolveApiKey: () => API_KEY,
+ resolveModel: () => 'gemini-3.8-live',
+ resolveHost: () => '',
+ resolveAllowedHosts: () => '',
+ resolveRateLimit: () => '0',
+ now: () => ISSUED_AT,
+ fetchImpl: async (...args) => {
+ calls.push(args);
+ return Response.json({
+ name: TOKEN,
+ privateDebug: API_KEY,
+ upstreamUrl: GEMINI_TOKEN_ENDPOINT,
+ });
+ },
+ ...options,
+ });
+ const server = http.createServer((req, res) => void handler(req, res));
+ server.listen(0, '127.0.0.1');
+ await once(server, 'listening');
+ const origin = `http://127.0.0.1:${server.address().port}`;
+ t.after(async () => {
+ server.closeAllConnections();
+ await new Promise((resolve) => server.close(resolve));
+ });
+ const send = (overrides = {}) => {
+ const { headers, ...rest } = overrides;
+ return fetch(origin, {
+ method: 'POST',
+ body: '{}',
+ ...rest,
+ headers: {
+ Origin: origin,
+ 'Content-Type': 'application/json',
+ ...headers,
+ },
+ });
+ };
+ const sendRaw = (overrides = {}) =>
+ new Promise((resolve, reject) => {
+ const { headers, body = '{}', ...rest } = overrides;
+ const req = http.request(
+ origin,
+ {
+ method: 'POST',
+ ...rest,
+ headers: {
+ Origin: origin,
+ 'Content-Type': 'application/json',
+ ...headers,
+ },
+ },
+ (res) => {
+ const chunks = [];
+ res.on('data', (chunk) => chunks.push(chunk));
+ res.on('end', () =>
+ resolve(
+ new Response(Buffer.concat(chunks), {
+ status: res.statusCode,
+ headers: res.headers,
+ }),
+ ),
+ );
+ res.on('error', reject);
+ },
+ );
+ req.on('error', reject);
+ req.end(body);
+ });
+ return { calls, origin, send, sendRaw };
+}
+
+test('dev and preview install the same bounded Gemini token endpoint', () => {
+ for (const hook of ['configureServer', 'configurePreviewServer']) {
+ const installed = [];
+ geminiLiveProxy()[hook]({
+ middlewares: { use: (...args) => installed.push(args) },
+ });
+ assert.equal(installed.length, 1);
+ assert.equal(installed[0][0], '/api/gemini/token');
+ assert.equal(typeof installed[0][1], 'function');
+ }
+});
+
++test('mounted token handler completes synchronous resolver failures without exposing details', async (t) => {
++ for (const resolver of [
++ 'resolveHost',
++ 'resolveAllowedHosts',
++ 'resolveApiKey',
++ 'resolveModel',
++ 'resolveRateLimit',
++ null,
++ ]) {
++ await t.test(resolver || 'healthy control', async () => {
++ const req = Object.assign(new PassThrough(), {
++ method: 'POST',
++ headers: {
++ host: '127.0.0.1',
++ origin: 'http://127.0.0.1',
++ 'content-type': 'application/json',
++ },
++ socket: { remoteAddress: '127.0.0.1' },
++ });
++ const writes = [];
++ const headers = new Map();
++ const res = Object.assign(new EventEmitter(), {
++ setHeader: (name, value) => headers.set(name.toLowerCase(), value),
++ end(body) {
++ this.writableEnded = true;
++ writes.push(JSON.parse(body));
++ },
++ });
++ let calls = 0;
++ let handler;
++ geminiLiveProxy({
++ realtime: {
++ resolveHost: () => '',
++ resolveAllowedHosts: () => '',
++ resolveApiKey: () => API_KEY,
++ resolveModel: () => 'gemini-3.8-live',
++ resolveRateLimit: () => '0',
++ fetchImpl: async () => {
++ calls++;
++ return Response.json({ name: TOKEN });
++ },
++ ...(resolver && {
++ [resolver]: () => {
++ throw new Error(`Synthetic resolver failure: ${API_KEY}`);
++ },
++ }),
++ },
++ }).configureServer({
++ middlewares: {
++ use(_path, installed) {
++ handler = installed;
++ },
++ },
++ });
++ const pending = handler(req, res);
++ req.end('{}');
++ await assert.doesNotReject(pending);
++ assert.equal(writes.length, 1);
++ assert.equal(res.statusCode, resolver ? 503 : 200);
++ assert.equal(calls, resolver ? 0 : 1);
++ assert.equal(headers.get('cache-control'), 'no-store');
++ if (resolver) {
++ assert.deepEqual(writes[0], {
++ error: 'Gemini voice could not connect. Try again.',
++ });
++ assert.equal(headers.get('connection'), 'close');
++ } else assert.equal(writes[0].token, TOKEN);
++ assert.equal(req.listenerCount('aborted'), 0);
++ assert.equal(req.listenerCount('data'), 0);
++ assert.equal(req.listenerCount('end'), 0);
++ assert.equal(res.listenerCount('close'), 0);
++ req.destroy();
++ });
++ }
++});
++
+test('mint locks canonical action schemas and server instructions with no permanent credential in browser data', async (t) => {
+ const f = await fixture(t, {
+ annotationGuidance: 'Keep existing annotations.',
+ });
+ const response = await f.send();
+ assert.equal(response.status, 200);
+ assert.equal(response.headers.get('cache-control'), 'no-store');
+ assert.equal(response.headers.get('x-content-type-options'), 'nosniff');
+ const data = await response.json();
+ assert.deepEqual(Object.keys(data).sort(), [
+ 'config',
+ 'model',
+ 'token',
+ 'websocketUrl',
+ ]);
+ assert.equal(data.token, TOKEN);
+ assert.equal(data.model, 'gemini-3.8-live');
+ assert.equal(data.websocketUrl, GEMINI_LIVE_WEBSOCKET_URL);
+ assert.equal(new URL(data.websocketUrl).search, '');
+ assert.equal(JSON.stringify(data).includes(API_KEY), false);
+ assert.deepEqual(data.config.generationConfig, {
+ responseModalities: ['AUDIO'],
+ });
+ assert.match(
+ data.config.systemInstruction.parts[0].text,
+ /Keep existing annotations\./,
+ );
+ assert.deepEqual(data.config.inputAudioTranscription, {});
+ assert.deepEqual(data.config.outputAudioTranscription, {});
+ assert.equal(
+ data.config.realtimeInputConfig?.automaticActivityDetection?.disabled,
+ undefined,
+ );
+ const functions = data.config.tools[0].functionDeclarations;
+ assert.deepEqual(
+ functions.map((tool) => tool.name),
+ GEV_REALTIME_TOOLS.map((tool) => tool.name),
+ );
+ for (let i = 0; i < functions.length; i++) {
+ assert.equal(functions[i].behavior, 'BLOCKING');
+ assert.deepEqual(
+ functions[i].parametersJsonSchema,
+ GEV_REALTIME_TOOLS[i].parameters,
+ );
+ assert.equal(functions[i].parameters, undefined);
+ }
+ const [url, init] = f.calls[0];
+ assert.equal(url, GEMINI_TOKEN_ENDPOINT);
+ assert.equal(init.redirect, 'error');
+ assert.equal(init.headers['x-goog-api-key'], API_KEY);
+ const request = JSON.parse(init.body);
+ assert.equal(request.uses, 1);
+ assert.equal(Date.parse(request.expireTime) - ISSUED_AT, 30 * 60_000);
+ assert.equal(Date.parse(request.newSessionExpireTime) - ISSUED_AT, 60_000);
+ assert.equal(request.fieldMask, undefined);
+ assert.equal(request.liveConnectConstraints, undefined);
+ assert.deepEqual(request.bidiGenerateContentSetup, {
+ model: 'models/gemini-3.8-live',
+ ...data.config,
+ });
+});
+
- test('standalone mints lock the full voice query catalog in both credential and browser setup', async (t) => {
- const tools = standaloneVoiceTools();
- const declarations = tools.map(({ name, description, parameters }) => ({
- name,
- description,
- parametersJsonSchema: parameters,
- behavior: 'BLOCKING',
- }));
- for (const name of ['search_places', 'get_weather', 'get_wind', 'plan_route'])
- assert.ok(
- tools.some((tool) => tool.name === name),
- name,
- );
- assert.ok(tools.length > GEV_REALTIME_TOOLS.length);
- for (const inputMode of ['open-mic', 'push-to-talk']) {
- const f = await fixture(t, { tools });
- const response = await f.send({
- body: JSON.stringify(inputMode === 'open-mic' ? {} : { inputMode }),
- });
- assert.equal(response.status, 200);
- const data = await response.json();
- assert.deepEqual(data.config.tools, [
- { functionDeclarations: declarations },
- ]);
- const request = JSON.parse(f.calls[0][1].body);
- assert.deepEqual(request.bidiGenerateContentSetup, {
- model: 'models/gemini-3.8-live',
- ...data.config,
- });
- assert.equal(request.fieldMask, undefined);
- assert.equal(JSON.stringify(data).includes(API_KEY), false);
- }
- });
-
- test('Gemini endpoint instructions advertise only the server-owned provider chooser', async (t) => {
- for (const options of [
- {},
- { providerDropdown: false },
- { providerDropdown: true },
- ]) {
- const f = await fixture(t, options);
- const response = await f.send();
- assert.equal(response.status, 200);
- const data = await response.json();
- const instructions = data.config.systemInstruction.parts[0].text;
- assert.match(instructions, /I can’t switch voice providers directly/);
- if (options.providerDropdown === true)
- assert.match(
- instructions,
- /Hover over the Voice panel and use the provider dropdown/,
- );
- else assert.doesNotMatch(instructions, /hover|provider dropdown/i);
- const upstream = JSON.parse(f.calls[0][1].body);
- assert.equal(
- upstream.bidiGenerateContentSetup.systemInstruction.parts[0].text,
- instructions,
- );
- }
- });
-
- test('browser token requests cannot enable provider chooser guidance', async (t) => {
++test('browser token requests cannot override server capabilities', async (t) => {
+ for (const body of [
+ { providerDropdown: true },
+ { inputMode: 'push-to-talk', providerDropdown: true },
+ { capabilities: { providerDropdown: true } },
+ ]) {
+ const f = await fixture(t);
+ assert.equal((await f.send({ body: JSON.stringify(body) })).status, 400);
+ assert.equal(f.calls.length, 0);
+ }
+});
+
+test('missing key and malformed model fail without an upstream request', async (t) => {
+ const missing = await fixture(t, { resolveApiKey: () => '' });
+ assert.equal((await missing.send()).status, 503);
+ assert.equal(missing.calls.length, 0);
+ for (const model of [
+ '',
+ 'models/../../secrets',
+ 'https://attacker.example/model',
+ 'gemini-live?key=private',
+ 'x'.repeat(150),
+ ]) {
+ const f = await fixture(t, { resolveModel: () => model });
+ const response = await f.send();
+ assert.equal(response.status, 503);
+ assert.equal(f.calls.length, 0);
+ assert.equal((await response.text()).includes(model || API_KEY), false);
+ }
+ const valid = await fixture(t, {
+ resolveModel: () =>
+ ' models/gemini-2.5-flash-native-audio-preview-12-2025 ',
+ });
+ assert.equal(
+ (await (await valid.send()).json()).model,
+ 'gemini-2.5-flash-native-audio-preview-12-2025',
+ );
+});
+
+test('only the PTT gesture selects manual activity in the complete locked setup', async (t) => {
+ const f = await fixture(t);
+ const ordinary = await (await f.send()).json();
+ const response = await f.send({
+ body: JSON.stringify({ inputMode: 'push-to-talk' }),
+ });
+ assert.equal(response.status, 200);
+ const manual = await response.json();
+ assert.deepEqual(manual.config.realtimeInputConfig, {
+ automaticActivityDetection: { disabled: true },
+ });
+ const { realtimeInputConfig, ...shared } = manual.config;
+ assert.equal(JSON.stringify(shared), JSON.stringify(ordinary.config));
+ assert.equal(
+ JSON.stringify(createGeminiLiveConfig(undefined, 'open-mic')),
+ JSON.stringify(ordinary.config),
+ );
+ assert.throws(
+ () => createGeminiLiveConfig(undefined, 'unknown'),
+ /input mode/,
+ );
+ const locked = JSON.parse(f.calls[1][1].body);
+ assert.deepEqual(locked.bidiGenerateContentSetup, {
+ model: 'models/gemini-3.8-live',
+ ...manual.config,
+ });
+ assert.equal(locked.fieldMask, undefined);
+ assert.equal(locked.uses, 1);
+ assert.equal(Date.parse(locked.newSessionExpireTime) - ISSUED_AT, 60_000);
+ assert.equal(Date.parse(locked.expireTime) - ISSUED_AT, 30 * 60_000);
+ assert.equal(JSON.stringify(manual).includes(API_KEY), false);
+});
+
+test('other methods, missing/cross origins, hostile hosts and cross-site metadata cannot mint', async (t) => {
+ const f = await fixture(t);
+ for (const method of ['GET', 'OPTIONS', 'PUT', 'DELETE']) {
+ const response = await f.send({ method, body: undefined });
+ assert.equal(response.status, 405);
+ assert.equal(response.headers.get('allow'), 'POST');
+ }
+ for (const headers of [
+ { Origin: '' },
+ { Origin: 'null' },
+ { Origin: 'https://attacker.example' },
+ { Origin: `${f.origin}/path` },
+ { Origin: `${f.origin}?key=secret` },
+ { Origin: f.origin.replace('http:', 'https:') },
+ { Host: 'attacker.example', Origin: 'http://attacker.example' },
+ { Host: '[email protected]', Origin: 'http://attacker.example' },
+ { 'Sec-Fetch-Site': 'cross-site' },
+ ]) {
+ assert.equal((await f.sendRaw({ headers })).status, 403);
+ }
+ assert.equal(f.calls.length, 0);
+ assert.equal((await f.send()).status, 200);
+});
+
+test('same-origin local and explicitly bound hosts work without trusting forwarded authority', async (t) => {
+ const f = await fixture(t, { resolveHost: () => 'demo.example' });
+ assert.equal(
+ (
+ await f.sendRaw({
+ headers: {
+ Host: 'demo.example:4173',
+ Origin: 'http://demo.example:4173',
+ },
+ })
+ ).status,
+ 200,
+ );
+ assert.equal(
+ (
+ await f.sendRaw({
+ headers: { Host: 'gev.local:4173', Origin: 'http://gev.local:4173' },
+ })
+ ).status,
+ 403,
+ );
+ assert.equal(
+ (
+ await f.send({
+ headers: {
+ Origin: 'https://demo.example',
+ 'X-Forwarded-Host': 'demo.example',
+ 'X-Forwarded-Proto': 'https',
+ },
+ })
+ ).status,
+ 403,
+ );
+});
+
+test('forwarded requests cannot mint or consume the real socket peer rate cap', async (t) => {
+ const f = await fixture(t, { resolveRateLimit: () => '1' });
+ assert.equal(
+ (await f.send({ headers: { 'X-Forwarded-For': '10.1.1.1' } })).status,
+ 403,
+ );
+ assert.equal(
+ (await f.send({ headers: { 'X-Forwarded-For': '10.1.1.2' } })).status,
+ 403,
+ );
+ assert.equal((await f.send()).status, 200);
+ const response = await f.send();
+ assert.equal(response.status, 429);
+ assert.equal(response.headers.get('retry-after'), '60');
+ assert.equal(f.calls.length, 1);
+});
+
+test('all shared proxy signals and same-site cross-origin metadata fail before minting', async (t) => {
+ const f = await fixture(t, { resolveRateLimit: () => '1' });
+ for (const header of PROXY_SIGNALS) {
+ assert.equal(
+ (await f.sendRaw({ headers: { [header]: 'untrusted' } })).status,
+ 403,
+ header,
+ );
+ }
+ assert.equal(
+ (await f.sendRaw({ headers: { 'Sec-Fetch-Site': 'same-site' } })).status,
+ 403,
+ );
+ assert.equal(f.calls.length, 0);
+ assert.equal(
+ (await f.sendRaw({ headers: { 'Sec-Fetch-Site': 'same-origin' } })).status,
+ 200,
+ );
+ assert.equal((await f.send()).status, 429);
+ assert.equal(f.calls.length, 1);
+});
+
+test('LAN binding, exact configured hosts, IPs, and localhost subdomains follow the app host policy', async (t) => {
+ const f = await fixture(t, {
+ resolveHost: () => '0.0.0.0',
+ resolveAllowedHosts: () => 'gev.local, demo.example',
+ });
+ for (const host of [
+ 'gev.local:4173',
+ 'demo.example:4173',
+ '192.168.1.20:4173',
+ '[::1]:4173',
+ 'demo.localhost:4173',
+ ]) {
+ assert.equal(
+ (await f.sendRaw({ headers: { Host: host, Origin: `http://${host}` } }))
+ .status,
+ 200,
+ host,
+ );
+ }
+ for (const host of ['arbitrary.local:4173', 'child.demo.example:4173']) {
+ assert.equal(
+ (await f.sendRaw({ headers: { Host: host, Origin: `http://${host}` } }))
+ .status,
+ 403,
+ host,
+ );
+ }
+ assert.equal(f.calls.length, 5);
+});
+
+test('unset, blank, malformed and negative rate limits keep the 30-per-minute cap', async (t) => {
+ for (const value of [undefined, '', ' ', '3O', 'Infinity', '-1']) {
+ await t.test(String(value), async (t) => {
+ const f = await fixture(t, { resolveRateLimit: () => value });
+ for (let index = 0; index < 30; index++)
+ assert.equal((await f.send()).status, 200, `request ${index + 1}`);
+ const response = await f.send();
+ assert.equal(response.status, 429);
+ assert.equal(response.headers.get('retry-after'), '60');
+ assert.equal(f.calls.length, 30);
+ });
+ }
+});
+
+test('a positive fraction applies a real cap and only explicit zero disables it', async (t) => {
+ const fractional = await fixture(t, { resolveRateLimit: () => '0.5' });
+ assert.equal((await fractional.send()).status, 200);
+ assert.equal((await fractional.send()).status, 429);
+ assert.equal(fractional.calls.length, 1);
+ const unlimited = await fixture(t, { resolveRateLimit: () => '0' });
+ for (let index = 0; index < 31; index++)
+ assert.equal((await unlimited.send()).status, 200);
+ assert.equal(unlimited.calls.length, 31);
+});
+
- test('real Vite dev and preview reject hostile hosts before the Gemini middleware', async (t) => {
- for (const mode of ['dev', 'preview']) {
- await t.test(mode, async (t) => {
- const root = await mkdtemp(path.join(tmpdir(), 'gev-gemini-vite-test-'));
- await mkdir(path.join(root, 'dist'));
- await writeFile(path.join(root, 'index.html'), '<p>isolated fixture</p>');
- await writeFile(
- path.join(root, 'dist/index.html'),
- '<p>isolated fixture</p>',
- );
- let credentialReads = 0;
- let upstreamCalls = 0;
- const allowedHosts = resolveAllowedHosts('gev.local');
- const config = {
- configFile: false,
- envFile: false,
- root,
- logLevel: 'silent',
- publicDir: false,
- optimizeDeps: { noDiscovery: true, include: [] },
- // Deliberately put the provider first: enforce: pre must order the gate.
- plugins: [
- geminiLiveProxy({
- realtime: {
- resolveApiKey: () => {
- credentialReads++;
- return '';
- },
- resolveHost: () => '127.0.0.1',
- resolveAllowedHosts: () => 'gev.local',
- fetchImpl: async () => {
- upstreamCalls++;
- throw new Error('No upstream calls are permitted');
- },
- },
- }),
- hostCheckPlugin(),
- ],
- server: {
- host: '127.0.0.1',
- port: 0,
- allowedHosts,
- hmr: false,
- watch: null,
- },
- preview: { host: '127.0.0.1', port: 0, allowedHosts },
- };
- let server;
- try {
- server =
- mode === 'dev' ? await createServer(config) : await preview(config);
- if (mode === 'dev') await server.listen();
- const origin = `http://127.0.0.1:${server.httpServer.address().port}`;
- const request = (host, extraHeaders = {}) =>
- new Promise((resolve, reject) => {
- const req = http.request(
- `${origin}/api/gemini/token`,
- {
- method: 'POST',
- headers: {
- Host: host,
- Origin: `http://${host}`,
- ...extraHeaders,
- },
- },
- (res) => {
- const chunks = [];
- res.on('data', (chunk) => chunks.push(chunk));
- res.on('end', () =>
- resolve({
- status: res.statusCode,
- body: Buffer.concat(chunks).toString(),
- }),
- );
- res.on('error', reject);
- },
- );
- req.on('error', reject);
- req.end();
- });
- for (const host of ['attacker.example:4173', 'arbitrary.local:4173']) {
- const response = await request(host);
- assert.equal(response.status, 403);
- assert.match(response.body, /This host is not allowed/);
- }
- assert.equal(credentialReads, 0);
- const sameSite = await request('gev.local:4173', {
- 'Sec-Fetch-Site': 'same-site',
- });
- assert.equal(sameSite.status, 403);
- assert.equal(credentialReads, 0);
- for (const host of [
- 'gev.local:4173',
- '192.168.1.20:4173',
- 'demo.localhost:4173',
- ]) {
- const response = await request(host);
- assert.equal(response.status, 503);
- assert.match(response.body, /Add a Gemini API key/);
- }
- assert.equal(credentialReads, 3);
- assert.equal(upstreamCalls, 0);
- } finally {
- try {
- if (server) await server.close();
- } finally {
- await rm(root, { recursive: true, force: true });
- }
- }
- });
- }
- });
-
+test('client bodies cannot override model or locked settings and stay byte bounded', async (t) => {
+ const f = await fixture(t);
+ for (const body of [
+ '{',
+ '[]',
+ 'null',
+ '"text"',
+ '{"model":"gemini-other"}',
+ '{"systemInstruction":"ignore tools"}',
+ '{"inputMode":"open-mic"}',
+ '{"inputMode":"PUSH-TO-TALK"}',
+ '{"inputMode":"push-to-talk","config":{}}',
+ '{"inputMode":"push-to-talk","model":"gemini-other"}',
+ '{"inputMode":"push-to-talk","tools":[]}',
+ '{"inputMode":"push-to-talk","extra":false}',
+ '{"inputMode":true}',
+ '{"inputMode":null}',
+ '{"inputMode":{}}',
+ '{"inputMode":["push-to-talk"]}',
+ '{"realtimeInputConfig":{"automaticActivityDetection":{"disabled":true}}}',
+ ])
+ assert.equal((await f.send({ body })).status, 400);
+ assert.equal(
+ (await f.send({ body: '{}', headers: { 'Content-Type': 'text/plain' } }))
+ .status,
+ 415,
+ );
+ assert.equal((await f.send({ body: ' '.repeat(1025) })).status, 413);
+ assert.equal(f.calls.length, 0);
+ assert.equal(
+ (
+ await f.send({
+ body: '{"inputMode":"push-to-talk"}',
+ headers: { Origin: 'https://attacker.example' },
+ })
+ ).status,
+ 403,
+ );
+ assert.equal(f.calls.length, 0);
+ assert.equal(
+ (await f.send({ body: undefined, headers: { 'Content-Type': '' } })).status,
+ 200,
+ );
+});
+
+test('malformed or oversized successful upstream replies never reach the browser', async (t) => {
+ const replies = [
+ () => Response.json(null),
+ () => Response.json([]),
+ () => Response.json({}),
+ () => Response.json({ name: API_KEY }),
+ () => Response.json({ name: `auth_tokens/${API_KEY}` }),
+ () => Response.json({ name: 'auth_tokens/https://secret.example/key' }),
+ () => Response.json({ name: `auth_tokens/${'x'.repeat(8192)}` }),
+ () =>
+ new Response('upstream body with private-gemini-test-key-never-return'),
+ () => new Response(' '.repeat(32 * 1024 + 1)),
+ () =>
+ new Response('{}', {
+ headers: { 'Content-Length': String(32 * 1024 + 1) },
+ }),
+ ];
+ for (const makeResponse of replies) {
+ const f = await fixture(t, { fetchImpl: async () => makeResponse() });
+ const response = await f.send();
+ assert.equal(response.status, 502);
+ const body = await response.text();
+ assert.equal(body.includes(API_KEY), false);
+ assert.equal(body.includes('upstream'), false);
+ assert.equal(body.includes('secret.example'), false);
+ }
+});
+
+test('upstream refusals and network exceptions are normalized and never log secrets', async (t) => {
+ const leaked = `${API_KEY} https://generativelanguage.googleapis.com/v1beta/auth_tokens?key=${API_KEY}`;
+ const logs = [];
+ const originalWarn = console.warn;
+ console.warn = (...args) => logs.push(args.join(' '));
+ t.after(() => {
+ console.warn = originalWarn;
+ });
+ for (const [status, expected] of [
+ [400, 502],
+ [401, 503],
+ [403, 503],
+ [404, 502],
+ [429, 429],
+ [500, 502],
+ [302, 502],
+ ]) {
+ const f = await fixture(t, {
+ fetchImpl: async () => new Response(leaked, { status }),
+ });
+ const response = await f.send();
+ assert.equal(response.status, expected);
+ assert.equal((await response.text()).includes(API_KEY), false);
+ }
+ const failed = await fixture(t, {
+ fetchImpl: async () => {
+ throw new Error(leaked);
+ },
+ });
+ assert.equal((await failed.send()).status, 502);
+ const redirected = await fixture(t, {
+ fetchImpl: async () => {
+ const response = Response.json({ name: TOKEN });
+ Object.defineProperty(response, 'url', {
+ value: 'https://attacker.example/token',
+ });
+ return response;
+ },
+ });
+ assert.equal((await redirected.send()).status, 502);
+ assert.equal(logs.join(' ').includes(API_KEY), false);
+});
+
+test('a stalled mint is aborted at the deadline without forwarding error details', async (t) => {
+ let cancelled = false;
+ const f = await fixture(t, {
+ timeoutMs: 30,
+ fetchImpl: (_url, { signal }) =>
+ new Promise((_resolve, reject) => {
+ signal.addEventListener(
+ 'abort',
+ () => {
+ cancelled = true;
+ reject(signal.reason);
+ },
+ { once: true },
+ );
+ }),
+ });
+ const response = await f.send();
+ assert.equal(response.status, 504);
+ assert.equal(cancelled, true);
+ assert.deepEqual(await response.json(), {
+ error: 'Gemini voice could not connect. Try again.',
+ });
+});
+
+test('request disconnect cancels its pending mint and cannot publish a late token', async (t) => {
+ let started;
+ let cancelled;
+ let release;
+ const ready = new Promise((resolve) => {
+ started = resolve;
+ });
+ const aborted = new Promise((resolve) => {
+ cancelled = resolve;
+ });
+ const f = await fixture(t, {
+ fetchImpl: (_url, { signal }) => {
+ signal.addEventListener('abort', cancelled, { once: true });
+ started();
+ return new Promise((resolve) => {
+ release = resolve;
+ });
+ },
+ });
+ const req = http.request(f.origin, {
+ method: 'POST',
+ headers: { Origin: f.origin },
+ });
+ req.on('error', () => {});
+ req.end();
+ await ready;
+ req.destroy();
+ await aborted;
+ release(Response.json({ name: TOKEN }));
+ await new Promise((resolve) => setImmediate(resolve));
+});
+
++test('disconnect at mint resolution settles without publishing and discards the response body', async () => {
++ for (const timing of ['before-resolution', 'after-resolution', 'connected']) {
++ const req = Object.assign(new PassThrough(), {
++ method: 'POST',
++ headers: {
++ host: '127.0.0.1',
++ origin: 'http://127.0.0.1',
++ 'content-type': 'application/json',
++ },
++ socket: { remoteAddress: '127.0.0.1' },
++ });
++ const writes = [];
++ const res = Object.assign(new EventEmitter(), {
++ setHeader() {},
++ end(body) {
++ this.writableEnded = true;
++ writes.push(body);
++ },
++ });
++ let started;
++ let release;
++ let cancelled = 0;
++ const ready = new Promise((resolve) => {
++ started = resolve;
++ });
++ const handler = createGeminiTokenHandler({
++ resolveApiKey: () => API_KEY,
++ resolveModel: () => 'gemini-3.8-live',
++ resolveHost: () => '',
++ resolveAllowedHosts: () => '',
++ resolveRateLimit: () => '0',
++ fetchImpl: () =>
++ new Promise((resolve) => {
++ release = resolve;
++ started();
++ }),
++ });
++ const pending = handler(req, res);
++ req.end('{}');
++ await ready;
++ const disconnect = () => {
++ req.aborted = true;
++ req.emit('aborted');
++ };
++ if (timing === 'before-resolution') {
++ disconnect();
++ await pending;
++ }
++ release(
++ new Response(
++ new ReadableStream({
++ start(controller) {
++ controller.enqueue(
++ new TextEncoder().encode(JSON.stringify({ name: TOKEN })),
++ );
++ if (timing === 'connected') controller.close();
++ },
++ cancel() {
++ cancelled++;
++ },
++ }),
++ ),
++ );
++ if (timing === 'after-resolution') queueMicrotask(disconnect);
++ await pending;
++ await new Promise((resolve) => setImmediate(resolve));
++ if (timing === 'connected') {
++ assert.equal(res.statusCode, 200);
++ assert.equal(writes.length, 1);
++ assert.equal(JSON.parse(writes[0]).token, TOKEN);
++ assert.equal(cancelled, 0);
++ } else {
++ assert.equal(writes.length, 0, timing);
++ assert.equal(cancelled, 1, timing);
++ }
++ assert.equal(req.listenerCount('aborted'), 0, timing);
++ assert.equal(res.listenerCount('close'), 0, timing);
++ }
++});
++
+test('timeout also bounds a stalled upstream response body', async (t) => {
+ let cancelled = false;
+ const f = await fixture(t, {
+ timeoutMs: 30,
+ fetchImpl: async () =>
+ new Response(
+ new ReadableStream({
+ cancel() {
+ cancelled = true;
+ },
+ }),
+ ),
+ });
+ assert.equal((await f.send()).status, 504);
+ assert.equal(cancelled, true);
+});
+
+test('chunked client uploads are capped without starting a mint', async (t) => {
+ const f = await fixture(t);
+ const response = await f.sendRaw({
+ body: ' '.repeat(1025),
+ headers: { 'Transfer-Encoding': 'chunked' },
+ });
+ assert.equal(response.status, 413);
+ assert.equal(f.calls.length, 0);
+});
+
+test('a partial token request cannot hold the handler beyond its deadline', async (t) => {
+ const f = await fixture(t, { timeoutMs: 30 });
+ const response = await new Promise((resolve, reject) => {
+ const req = http.request(
+ f.origin,
+ {
+ method: 'POST',
+ headers: {
+ Origin: f.origin,
+ 'Content-Type': 'application/json',
+ 'Transfer-Encoding': 'chunked',
+ },
+ },
+ resolve,
+ );
+ req.on('error', reject);
+ t.after(() => req.destroy());
+ req.write('{');
+ });
+ assert.equal(response.statusCode, 504);
- response.resume();
++ const chunks = [];
++ response.on('data', (chunk) => chunks.push(chunk));
+ await once(response, 'end');
++ assert.deepEqual(JSON.parse(Buffer.concat(chunks)), {
++ error: 'Gemini voice could not connect. Try again.',
++ });
+ assert.equal(f.calls.length, 0);
+});
++
++test(
++ 'deadline responds before an abort-ignoring mint settles and cancels its late body',
++ { timeout: 2000 },
++ async (t) => {
++ let release;
++ let signal;
++ let cancelled = false;
++ const f = await fixture(t, {
++ timeoutMs: 30,
++ fetchImpl: (_url, options) => {
++ signal = options.signal;
++ return new Promise((resolve) => {
++ release = resolve;
++ });
++ },
++ });
++ const response = await f.send();
++ assert.equal(response.status, 504);
++ assert.equal(signal.aborted, true);
++ assert.deepEqual(await response.json(), {
++ error: 'Gemini voice could not connect. Try again.',
++ });
++ release(
++ new Response(
++ new ReadableStream({
++ start(controller) {
++ controller.enqueue(
++ new TextEncoder().encode(JSON.stringify({ name: TOKEN })),
++ );
++ },
++ cancel() {
++ cancelled = true;
++ },
++ }),
++ ),
++ );
++ await new Promise((resolve) => setImmediate(resolve));
++ assert.equal(cancelled, true);
++ },
++);
++
++test('wrong-destination and redirected successful responses discard their bodies', async (t) => {
++ for (const property of ['url', 'redirected']) {
++ let cancelled = false;
++ const f = await fixture(t, {
++ fetchImpl: async () => {
++ const response = new Response(
++ new ReadableStream({
++ cancel() {
++ cancelled = true;
++ },
++ }),
++ );
++ Object.defineProperty(response, property, {
++ value: property === 'url' ? 'https://attacker.example/token' : true,
++ });
++ return response;
++ },
++ });
++ const response = await f.send();
++ assert.equal(response.status, 502);
++ assert.deepEqual(await response.json(), {
++ error: 'Gemini voice could not connect. Try again.',
++ });
++ assert.equal(cancelled, true);
++ }
++});
++
++test(
++ 'a chunked overflow delivers fixed 413 while its upload is still open',
++ { timeout: 2000 },
++ async (t) => {
++ const f = await fixture(t);
++ const response = await new Promise((resolve, reject) => {
++ const req = http.request(
++ f.origin,
++ {
++ method: 'POST',
++ headers: {
++ Origin: f.origin,
++ 'Content-Type': 'application/json',
++ 'Transfer-Encoding': 'chunked',
++ },
++ },
++ resolve,
++ );
++ req.on('error', reject);
++ t.after(() => req.destroy());
++ req.write(' '.repeat(1024));
++ req.write(' ');
++ });
++ assert.equal(response.statusCode, 413);
++ const chunks = [];
++ response.on('data', (chunk) => chunks.push(chunk));
++ await once(response, 'end');
++ assert.deepEqual(JSON.parse(Buffer.concat(chunks)), {
++ error: 'Token request is too large',
++ });
++ assert.equal(f.calls.length, 0);
++ assert.equal((await f.send({ body: ' '.repeat(1024) })).status, 200);
++ },
++);
++
++test('standalone mints lock the full voice query catalog in both credential and browser setup', async (t) => {
++ const tools = standaloneVoiceTools();
++ const declarations = tools.map(({ name, description, parameters }) => ({
++ name,
++ description,
++ parametersJsonSchema: parameters,
++ behavior: 'BLOCKING',
++ }));
++ for (const name of ['search_places', 'get_weather', 'get_wind', 'plan_route'])
++ assert.ok(
++ tools.some((tool) => tool.name === name),
++ name,
++ );
++ assert.ok(tools.length > GEV_REALTIME_TOOLS.length);
++ for (const inputMode of ['open-mic', 'push-to-talk']) {
++ const f = await fixture(t, { tools });
++ const response = await f.send({
++ body: JSON.stringify(inputMode === 'open-mic' ? {} : { inputMode }),
++ });
++ assert.equal(response.status, 200);
++ const data = await response.json();
++ assert.deepEqual(data.config.tools, [
++ { functionDeclarations: declarations },
++ ]);
++ const request = JSON.parse(f.calls[0][1].body);
++ assert.deepEqual(request.bidiGenerateContentSetup, {
++ model: 'models/gemini-3.8-live',
++ ...data.config,
++ });
++ assert.equal(request.fieldMask, undefined);
++ assert.equal(JSON.stringify(data).includes(API_KEY), false);
++ }
++});
++
++test('real Vite dev and preview reject hostile hosts before the Gemini middleware', async (t) => {
++ for (const mode of ['dev', 'preview']) {
++ await t.test(mode, async (t) => {
++ const root = await mkdtemp(path.join(tmpdir(), 'gev-gemini-vite-test-'));
++ await mkdir(path.join(root, 'dist'));
++ await writeFile(path.join(root, 'index.html'), '<p>isolated fixture</p>');
++ await writeFile(
++ path.join(root, 'dist/index.html'),
++ '<p>isolated fixture</p>',
++ );
++ let credentialReads = 0;
++ let upstreamCalls = 0;
++ const allowedHosts = resolveAllowedHosts('gev.local');
++ const config = {
++ configFile: false,
++ envFile: false,
++ root,
++ logLevel: 'silent',
++ publicDir: false,
++ optimizeDeps: { noDiscovery: true, include: [] },
++ // Deliberately put the provider first: enforce: pre must order the gate.
++ plugins: [
++ geminiLiveProxy({
++ realtime: {
++ resolveApiKey: () => {
++ credentialReads++;
++ return '';
++ },
++ resolveHost: () => '127.0.0.1',
++ resolveAllowedHosts: () => 'gev.local',
++ fetchImpl: async () => {
++ upstreamCalls++;
++ throw new Error('No upstream calls are permitted');
++ },
++ },
++ }),
++ hostCheckPlugin(),
++ ],
++ server: {
++ host: '127.0.0.1',
++ port: 0,
++ allowedHosts,
++ hmr: false,
++ watch: null,
++ },
++ preview: { host: '127.0.0.1', port: 0, allowedHosts },
++ };
++ let server;
++ try {
++ server =
++ mode === 'dev' ? await createServer(config) : await preview(config);
++ if (mode === 'dev') await server.listen();
++ const origin = `http://127.0.0.1:${server.httpServer.address().port}`;
++ const request = (host, extraHeaders = {}) =>
++ new Promise((resolve, reject) => {
++ const req = http.request(
++ `${origin}/api/gemini/token`,
++ {
++ method: 'POST',
++ headers: {
++ Host: host,
++ Origin: `http://${host}`,
++ ...extraHeaders,
++ },
++ },
++ (res) => {
++ const chunks = [];
++ res.on('data', (chunk) => chunks.push(chunk));
++ res.on('end', () =>
++ resolve({
++ status: res.statusCode,
++ body: Buffer.concat(chunks).toString(),
++ }),
++ );
++ res.on('error', reject);
++ },
++ );
++ req.on('error', reject);
++ req.end();
++ });
++ for (const host of ['attacker.example:4173', 'arbitrary.local:4173']) {
++ const response = await request(host);
++ assert.equal(response.status, 403);
++ assert.match(response.body, /This host is not allowed/);
++ }
++ assert.equal(credentialReads, 0);
++ const sameSite = await request('gev.local:4173', {
++ 'Sec-Fetch-Site': 'same-site',
++ });
++ assert.equal(sameSite.status, 403);
++ assert.equal(credentialReads, 0);
++ for (const host of [
++ 'gev.local:4173',
++ '192.168.1.20:4173',
++ 'demo.localhost:4173',
++ ]) {
++ const response = await request(host);
++ assert.equal(response.status, 503);
++ assert.match(response.body, /Add a Gemini API key/);
++ }
++ assert.equal(credentialReads, 3);
++ assert.equal(upstreamCalls, 0);
++ } finally {
++ try {
++ if (server) await server.close();
++ } finally {
++ await rm(root, { recursive: true, force: true });
++ }
++ }
++ });
++ }
++});
diff --cc src/i18n/locales/es.json
index 000000000,f93f42070..973239213
mode 000000,100644..100644
--- a/src/i18n/locales/es.json
+++ b/src/i18n/locales/es.json
@@@ -1,0 -1,2894 +1,2945 @@@
+ {
+ "NO PLACE LEFT BEHIND": "NINGÚN RINCÓN SIN VIGILAR",
+ "Initializing photorealistic world...": "Inicializando el mundo fotorrealista...",
+ "Configuring viewer...": "Configurando el visor...",
+ "Google 3D Tiles unavailable ({detail}). Loading the keyless globe...": "Google 3D Tiles no disponibles ({detail}). Cargando el globo sin clave...",
+ "Flying to Austin, TX...": "Volando a Austin, TX...",
+ "Restoring shared view...": "Restaurando la vista compartida...",
+ "LOADING LIVE DATA": "CARGANDO DATOS EN VIVO",
+ "LOAD COMPLETE": "CARGA COMPLETA",
+ "LOAD FAILED": "CARGA FALLIDA",
+ "LOAD CANCELLED": "CARGA CANCELADA",
+ "syncing road network": "sincronizando la red vial",
+ "retrying in {seconds}s": "reintento en {seconds} s",
+ "retry pending": "reintento pendiente",
+ "Clear selected data layers": "Limpiar las capas de datos seleccionadas",
+ "Turn off all selected data layers": "Desactivar todas las capas de datos seleccionadas",
+ "Copy share link": "Copiar enlace para compartir",
+ "Reset to full globe view": "Restablecer la vista del globo completo",
+ "DATA LAYERS": "CAPAS DE DATOS",
+ "Collapse panel": "Contraer panel",
+ "Navigation, voice, and visual preset controls": "Controles de navegación, voz y preajustes visuales",
+ "Globe actions": "Acciones del globo",
+ "Reset camera and return to full globe view": "Restablecer la cámara y volver a la vista del globo completo",
+ "loading frames": "cargando fotogramas",
+ "Language: {language}": "Idioma: {language}",
+ "Change the interface language": "Cambiar el idioma de la interfaz",
+ "Interface language": "Idioma de la interfaz",
+ "Search languages": "Buscar idioma",
+ "No matching languages": "No hay idiomas que coincidan",
+ "Loading Google 3D Tiles...": "Cargando Google 3D Tiles...",
+ "Loading the keyless globe...": "Cargando el globo sin clave...",
+ "Initializing systems...": "Inicializando sistemas...",
+ "LIVE DATA OFF": "DATOS EN VIVO DESACTIVADOS",
+ "MAPPED SITES LOADED": "SITIOS MAPEADOS CARGADOS",
+ "RETRYING MAPPED SITES": "REINTENTANDO SITIOS MAPEADOS",
+ "FETCHING MAPPED SITES": "OBTENIENDO SITIOS MAPEADOS",
+ "TURNING OFF LIVE DATA": "DESACTIVANDO DATOS EN VIVO",
+ "REFRESHING LIVE DATA": "ACTUALIZANDO DATOS",
+ "Close data attribution": "Cerrar la atribución de datos",
+ "Aircraft cockpit view": "Vista de cabina de la aeronave",
+ "EXIT COCKPIT": "SALIR DE CABINA",
+ "GROUND SPEED": "VEL. SUELO",
+ "ALTITUDE": "ALTITUD",
+ "CONTACT": "CONTACTO",
+ "CONTACTS · 250 KM": "CONTACTOS · 250 KM",
+ "LIVE SIGNALS": "SEÑALES EN VIVO",
+ "OBSERVED / MAPPED PINGS": "PINGS OBSERVADOS / MAPEADOS",
+ "CURRENT": "ACTUAL",
+ "READY": "LISTA",
+ "ACTIVE STYLE": "ESTILO ACTUAL",
+ "Return UI controls": "Volver a mostrar los controles de la interfaz",
+ "EXIT CLEAN VIEW": "SALIR DE VISTA LIMPIA",
+ "Expand Visual Presets": "Expandir Preajustes visuales",
+ "VISUAL PRESETS": "PREAJUSTES",
+ "Pin visual presets": "Fijar Preajustes visuales",
+ "Keep visual presets open": "Mantener abiertos los Preajustes visuales",
+ "Show the globe without a visual filter.": "Muestra el globo sin filtro visual.",
+ "Normal": "Normal",
+ "Emulate a green phosphor CRT with scanlines and screen curvature.": "Emula un CRT de fósforo verde con líneas de barrido y curvatura de pantalla.",
+ "CRT": "CRT",
+ "Simulate night-vision goggles with green intensification and a tube vignette.": "Simula unas gafas de visión nocturna con intensificación verde y viñeta de tubo.",
+ "NVG": "NVG",
+ "Simulate FLIR-style thermal contrast. Turn up Ironbow for color.": "Simula un contraste térmico estilo FLIR. Sube Ironbow para tener color.",
+ "FLIR": "FLIR",
+ "Apply bright cel-shaded color and illustrated outlines.": "Aplica un color brillante de cel-shading y contornos ilustrados.",
+ "Anime": "Anime",
+ "Apply high-contrast monochrome film-noir grading.": "Aplica una gradación monocroma de alto contraste estilo film noir.",
+ "Noir": "Noir",
+ "Add a cold, snowy whiteout treatment to the scene.": "Añade a la escena un tratamiento frío de ventisca blanca.",
+ "Snow": "Nieve",
+ "MAP SOURCE": "FUENTE DEL MAPA",
+ "Map source": "Fuente del mapa",
+ "Style": "Estilo",
+ "DISPLAY": "VISUALIZACIÓN",
+ "Intelligence HUD (H)": "HUD de inteligencia (H)",
+ "Layout": "Disposición",
+ "HUD layout": "Disposición del HUD",
+ "Tactical": "Táctica",
+ "Operator": "De operador",
+ "Minimal": "Mínima",
+ "Detection Overlay (D)": "Superposición de detección (D)",
+ "Detection overlay": "Superposición de detección",
+ "DETECT": "DETECTAR",
+ "Density": "Densidad",
+ "Detection label density": "Densidad de etiquetas de detección",
+ "Allocation": "Asignación",
+ "Detection label allocation": "Asignación de etiquetas de detección",
+ "Elastic": "Elástica",
+ "Weighted": "Ponderada",
+ "Fade": "Desvanecimiento",
+ "Detection fade distance": "Distancia de desvanecimiento de detección",
+ "World-overlay fade distance outside the keyhole as a percentage of its radius": "Distancia de desvanecimiento de la superposición del mundo fuera del ojo de cerradura, como porcentaje de su radio",
+ "Outside": "Exterior",
+ "Detection opacity outside the keyhole": "Opacidad de detección fuera del ojo de cerradura",
+ "World-overlay label and card opacity beyond the fade distance": "Opacidad de etiquetas y tarjetas de la superposición del mundo más allá de la distancia de desvanecimiento",
+ "PARAMETERS": "PARÁMETROS",
+ "3D aircraft — flat icons zoomed out, 3D models up close": "Aeronaves 3D — iconos planos de lejos, modelos 3D de cerca",
+ "Models": "Modelos",
+ "3D model coverage": "Cobertura de modelos 3D",
+ "Proximity": "Proximidad",
+ "All": "Todos",
+ "Scope — the circular viewport mask": "Mirilla — la máscara circular del visor",
+ "Scope": "Mirilla",
+ "Feather": "Difuminado",
+ "Scope edge feather as a percentage of the keyhole radius": "Difuminado del borde de la mirilla como porcentaje del radio del ojo de cerradura",
+ "Celestial ring — reveal the full globe": "Anillo celestial — muestra el globo completo",
+ "Celestial": "Cielo",
+ "Hide UI chrome": "Ocultar los elementos de la interfaz",
+ "Clean UI": "Interfaz limpia",
+ "Bloom / Glow": "Resplandor",
+ "Bloom": "Resplandor",
+ "Sharpening": "Nitidez",
+ "Sharpen": "Nitidez",
+ "LOCATION": "UBICACIÓN",
+ "Pin location tray": "Fijar bandeja de ubicación",
+ "Keep location tray open": "Mantener abierta la bandeja de ubicación",
+ "📍 Location: --": "📍 Ubicación: --",
+ "Landmark: --": "Punto de interés: --",
+ "Search any location": "Buscar un lugar",
+ "Search any location...": "Buscar un lugar…",
+ "LEVEL": "NIVEL",
+ "Estimated destination direction": "Dirección estimada del destino",
+ "DEST ---°": "DEST ---°",
+ "OPTICAL PLANE · 01": "PLANO ÓPTICO · 01",
+ "VISOR LOCK · ACTIVE": "BLOQUEO DE VISERA · ACTIVO",
+ "FIRST PERSON": "PRIMERA PERSONA",
+ "LIVE TRACK · COURSE ALIGNED": "RASTREO EN VIVO · RUMBO ALINEADO",
+ "Cockpit vision style": "Estilo de visión de la cabina",
+ "Current aircraft heading": "Rumbo actual de la aeronave",
+ "GROUND SPEED · KTS": "VEL. SUELO · KN",
+ "ALTITUDE · FT": "ALTITUD · FT",
+ "PREV": "ANT.",
+ "Previous cockpit vision style": "Estilo de visión de cabina anterior",
+ "Previous vision style": "Estilo de visión anterior",
+ "Current cockpit vision style: NORMAL. Activate for next style.": "Estilo de visión de cabina actual: NORMAL. Actívalo para pasar al siguiente estilo.",
+ "Current style: NORMAL — click for next": "Estilo actual: NORMAL — haz clic para el siguiente",
+ "NEXT": "SIG.",
+ "Next cockpit vision style": "Siguiente estilo de visión de cabina",
+ "Next vision style": "Siguiente estilo de visión",
+ "View switcher": "Selector de vistas",
+ "Reset cockpit to full globe view": "Restablecer la cabina a la vista de globo completo",
+ "Exit cockpit and return to full globe view": "Salir de la cabina y volver a la vista de globo completo",
+ "RESET": "RESTABLECER",
+ "Exit cockpit view": "Salir de la vista de cabina",
+ "Estimated flight plan": "Plan de vuelo estimado",
+ "ESTIMATED FLIGHT PLAN": "PLAN DE VUELO ESTIMADO",
+ "ROUTE DATA UNAVAILABLE": "DATOS DE RUTA NO DISPONIBLES",
+ "FROM": "DESDE",
+ "TO": "HACIA",
+ "UNKNOWN": "DESCONOCIDO",
+ "Cockpit briefing carousel": "Carrusel de información de la cabina",
+ "Cockpit briefing controls": "Controles de información de la cabina",
+ "Previous briefing page": "Página de información anterior",
+ "Next briefing page": "Página de información siguiente",
+ "Cycle briefing pages automatically every 9 seconds (Signals → News → Local). Pauses while you hover or focus the panel. Live signal data refreshes continuously either way.": "Cambia las páginas de información automáticamente cada 9 segundos (Señales → Noticias → Local). Se pausa mientras pasas el cursor por el panel o lo enfocas. Los datos de señales en vivo se actualizan continuamente de todos modos.",
+ "Collapse cockpit briefing panel": "Contraer el panel de información de la cabina",
+ "Collapse briefing panel": "Contraer el panel de información",
+ "Live signals": "Señales en vivo",
+ "Latest regional news": "Últimas noticias regionales",
+ "Location-based information": "Información basada en la ubicación",
+ "ACQUIRING REGIONAL NEWS": "OBTENIENDO NOTICIAS DE ZONA",
+ "RESOLVING REGION": "DETERMINANDO REGIÓN",
+ "TEMP": "TEMP.",
+ "WIND": "VIENTO",
+ "SKY": "CIELO",
+ "PRECIP": "PRECIP.",
+ "SOURCE-BACKED EVENTS · NO SYNTHETIC NEWS": "EVENTOS CON FUENTE · SIN NOTICIAS SINTÉTICAS",
+ "Show Live Signals": "Mostrar Señales en vivo",
+ "Show Regional News": "Mostrar noticias de zona",
+ "Show Local Info": "Mostrar Información local",
+ "Contact cockpit summary": "Resumen de contacto de la cabina",
+ "Contact navigation": "Navegación de contactos",
+ "Previous — prior visited contact in the 250 km window": "Anterior — contacto ya visitado en la ventana de 250 km",
+ "Next — nearest unvisited contact in the 250 km window": "Siguiente — contacto sin visitar más cercano en la ventana de 250 km",
+ "Collapse Contact panel": "Contraer el panel de contacto",
+ "Collapse contact panel": "Contraer el panel de contacto",
+ "CONTEXT ONLY": "SOLO CONTEXTO",
+ "Nearby cohort counts": "Recuento de grupos cercanos",
+ "NEAREST OBSERVED / MAPPED": "MÁS CERCANO OBSERVADO / MAPEADO",
+ "NO AVAILABLE EXAMPLE": "SIN EJEMPLO DISPONIBLE",
+ "AVAILABLE INPUTS ONLY · NOT AN ALL-CLEAR": "SOLO DATOS DISPONIBLES · NO IMPLICA TODO DESPEJADO",
+ "Enable cockpit weather effects": "Activar los efectos climáticos de la cabina",
+ "CONTEXT": "CONTEXTO",
+ "Expand panel": "Expandir panel",
+ "Context mode": "Modo de contexto",
+ "CONTACTS": "CONTACTOS",
+ "Cycles the nearest contacts of whatever type you select — planes, vessels, installations. Satellites track independently.": "Recorre los contactos más cercanos del tipo que elijas — aeronaves, buques, instalaciones. Los satélites se rastrean por separado.",
+ "SPACE MISSIONS": "MISIONES ESPACIALES",
+ "SELECT CONTEXT": "SELECCIONAR CONTEXTO",
+ "Contact Context actions": "Acciones de contexto de contacto",
+ "COCKPIT": "CABINA",
+ "SEARCH NEARBY SITES": "BUSCAR SITIOS CERCANOS",
+ "Reclassify tracked contact as TR-3B": "Reclasificar el contacto rastreado como TR-3B",
+ "Reclassify as TR-3B": "Reclasificar como TR-3B",
+ "CONTACTS CONTEXT OFF": "CONTEXTO DE CONTACTOS DESACTIVADO",
+ "SELECT CONTACTS TO LOAD OBSERVED / MAPPED PROXIMITY": "SELECCIONA CONTACTOS PARA CARGAR LA PROXIMIDAD OBSERVADA / MAPEADA",
+ "Available Space Missions": "Misiones espaciales disponibles",
+ "AVAILABLE MISSIONS": "MISIONES DISPONIBLES",
+ "SELECT A MISSION TO INSPECT": "SELECCIONA UNA MISIÓN PARA INSPECCIONAR",
+ "LOADING 30-DAY MISSION INDEX": "CARGANDO ÍNDICE DE MISIONES DE 30 DÍAS",
+ "Open compact Radio controls": "Abrir los controles compactos de Radio",
+ "Compact Radio controls": "Controles compactos de Radio",
+ "RADIO": "RADIO",
+ "RADIO READY": "RADIO LISTA",
+ "Open detailed Radio controls": "Abrir los controles detallados de Radio",
+ "Close compact Radio controls": "Cerrar los controles compactos de Radio",
+ "ENABLE": "ACTIVAR",
+ "Previous filtered radio station": "Emisora de radio filtrada anterior",
+ "Previous station": "Emisora anterior",
+ "Play selected radio station": "Reproducir la emisora de radio seleccionada",
+ "Play": "Reproducir",
+ "Next filtered radio station": "Siguiente emisora de radio filtrada",
+ "Next station": "Siguiente emisora",
+ "VOLUME": "VOLUMEN",
+ "Compact Radio volume": "Volumen de la Radio compacta",
+ "Cockpit display and Radio controls": "Controles de visualización y Radio de la cabina",
+ "Expand Cockpit display options": "Expandir las opciones de visualización de la cabina",
+ "Cockpit display options": "Opciones de visualización de la cabina",
+ "Expand Cockpit Radio controls": "Expandir los controles de Radio de la cabina",
+ "Cockpit compact Radio controls": "Controles compactos de Radio de la cabina",
+ "Cockpit Radio volume": "Volumen de la Radio de la cabina",
+ "Expand {name}": "Expandir {name}",
+ "Collapse {name}": "Contraer {name}",
+ "panel": "panel",
+ "Collapse Radio": "Contraer Radio",
+ "Collapse Radio section": "Contraer la sección de Radio",
+ "Searched location": "Ubicación buscada",
+ "Disable cockpit weather effects": "Desactivar los efectos climáticos de la cabina",
+ "ON": "ACTIVO",
+ "OFF": "INACTIVO",
+ "Restore real aircraft": "Restaurar la aeronave real",
+ "Night vision": "Visión nocturna",
+ "Thermal": "Térmica",
+ "Current cockpit vision style: {style}. Activate for next style.": "Estilo de visión de cabina actual: {style}. Actívalo para pasar al siguiente estilo.",
+ "Current style: {style} — click for next": "Estilo actual: {style} — haz clic para el siguiente",
+ "TRACK ACQUIRED": "RASTREO ADQUIRIDO",
+ "{label} · COURSE {heading}°": "{label} · RUMBO {heading}°",
+ "Select flight {title}": "Seleccionar el vuelo {title}",
+ "CONTEXT STANDBY": "CONTEXTO EN ESPERA",
+ "ENABLE GLOBAL CONTEXT FOR PROXIMITY PINGS": "ACTIVAR CONTEXTO GLOBAL PARA PINGS DE PROXIMIDAD",
+ "CONTACT LOST · {subject}": "CONTACTO PERDIDO · {subject}",
+ "SUBJECT LEFT ITS FEED · READOUT HOLDING LAST KNOWN": "EL OBJETIVO SALIÓ DE SU FUENTE · LA LECTURA CONSERVA EL ÚLTIMO DATO CONOCIDO",
+ "MILITARY FLIGHT": "VUELO MILITAR",
+ "COMMERCIAL FLIGHT": "VUELO COMERCIAL",
+ "{aircraftClass} · CURRENT": "{aircraftClass} · ACTUAL",
+ "{aircraftClass} · {distance}": "{aircraftClass} · {distance}",
+ "DISTANCE UNKNOWN": "DISTANCIA DESCONOCIDA",
+ "{count} INPUTS UNKNOWN": {
+ "one": "{count} DATO DESCONOCIDO",
+ "many": "{count} DE DATOS DESCONOCIDOS",
+ "other": "{count} DATOS DESCONOCIDOS"
+ },
+ "SOURCE STATUS UNAVAILABLE": "ESTADO DE FUENTE NO DISPONIBLE",
+ "AIRCRAFT": "AERONAVE",
+ "MILITARY": "MILITAR",
+ "COMMERCIAL": "COMERCIAL",
+ "ACQUIRING SURFACE": "OBTENIENDO SUPERFICIE",
+ "SURFACE FALLBACK": "RESPALDO DE SUPERFICIE",
+ "STALE FEED": "FUENTE DESACTUALIZADA",
+ "LIVE TRACK": "RASTREO EN VIVO",
+ "{aircraftClass} · {feedState} · COURSE ALIGNED": "{aircraftClass} · {feedState} · RUMBO ALINEADO",
+ "ARROW · ESTIMATED DIRECTION": "FLECHA · DIRECCIÓN ESTIMADA",
+ "DEST {bearing}": "DEST {bearing}",
+ "CONTACT LOST · LAST KNOWN READOUT · NOT AN ALL-CLEAR": "CONTACTO PERDIDO · ÚLTIMA LECTURA CONOCIDA · NO IMPLICA TODO DESPEJADO",
+ "{count} INPUTS UNKNOWN · NOT AN ALL-CLEAR": {
+ "one": "{count} DATO DESCONOCIDO · NO IMPLICA TODO DESPEJADO",
+ "many": "{count} DE DATOS DESCONOCIDOS · NO IMPLICA TODO DESPEJADO",
+ "other": "{count} DATOS DESCONOCIDOS · NO IMPLICA TODO DESPEJADO"
+ },
+ "AVAILABLE INPUTS CURRENT · NOT AN ALL-CLEAR": "DATOS DISPONIBLES ACTUALIZADOS · NO IMPLICA TODO DESPEJADO",
+ "{cohort} · {contact}": "{cohort} · {contact}",
+ "{cohort}, Unavailable": "{cohort}, no disponible",
+ "BRG —": "BRG —",
+ "AHEAD": "AL FRENTE",
+ "{side} {angle}": "{side} {angle}",
+ "L": "I",
+ "R": "D",
+ "Expand Contact panel": "Expandir el panel de contacto",
+ "Expand contact panel": "Expandir el panel de contacto",
+ "Expand cockpit briefing panel": "Expandir el panel de información de la cabina",
+ "Expand briefing panel": "Expandir el panel de información",
+ "CYCLE ON": "CICLO: SÍ",
+ "CYCLE OFF": "CICLO: NO",
+ "Stop automatic page cycling. Previous, Next, and the SIG/NEWS/LOCAL tabs stay available.": "Detén el cambio automático de páginas. Anterior, Siguiente y las pestañas SIG/NOTICIAS/LOCAL siguen disponibles.",
+ "REGIONAL NEWS": "NOTICIAS DE ZONA",
+ "LOCAL INFO": "INFORMACIÓN LOCAL",
+ "LATEST LOCATION-MATCHED REPORTING": "ÚLTIMOS INFORMES SEGÚN UBICACIÓN",
+ "PLACE / CONDITIONS / POSITION": "LUGAR / CLIMA / POSICIÓN",
+ "POSITION UNAVAILABLE": "POSICIÓN NO DISPONIBLE",
+ "REGIONAL NEWS UNAVAILABLE": "NOTICIAS DE ZONA NO DISPONIBLES",
+ "REGION UNAVAILABLE": "REGIÓN NO DISPONIBLE",
+ "NO RECENT LOCATION MATCHES": "SIN COINCIDENCIAS RECIENTES DE UBICACIÓN",
+ "SOURCE": "FUENTE",
+ "{domain} · {age}": "{domain} · {age}",
+ "{source} · LOCATION QUERY": "{source} · CONSULTA POR UBICACIÓN",
+ "TIME UNKNOWN": "HORA DESCONOCIDA",
+ "{count}M AGO": "HACE {count} MIN",
+ "{count}H AGO": "HACE {count} H",
+ "{count}D AGO": "HACE {count} D",
+ "DIR UNKNOWN": "DIR DESCONOCIDA",
+ "CLOUD {pct}%": "NUBES {pct}%",
+ "CLOUD UNKNOWN": "NUBES DESCONOCIDAS",
+ "Panel layout updated — positions reset to new defaults": "Disposición de paneles actualizada — posiciones restablecidas a los nuevos valores predeterminados",
+ "Link copied!": "¡Enlace copiado!",
+ "Copy failed": "No se pudo copiar",
+ "Location not found": "Ubicación no encontrada",
+ "Search failed": "No se pudo completar la búsqueda",
+ "Fly to a POI first": "Ve primero a un punto de interés",
+ "Clearing selected data layers": "Limpiando las capas de datos seleccionadas",
+ "Selected data layers could not be cleared": "No se pudieron limpiar las capas de datos seleccionadas",
+ "ACQUIRING": "OBTENIENDO",
+ "entity": "entidad",
+ "SHARED {subject}": "{subject} COMPARTIDO",
+ "Shared {subject} follow expired": "El seguimiento de {subject} compartido ha caducado",
+ "Shared {subject} could not be restored — feed unavailable": "No se pudo restaurar {subject} compartido — fuente no disponible",
+ "Shared {subject} is unavailable": "{subject} compartido no está disponible",
+ "Context": "Contexto",
+ "Space Missions": "Misiones espaciales",
+ "{mode} could not start because another layer did not stop cleanly": "{mode} no pudo iniciarse porque otra capa no se detuvo correctamente",
+ "Contacts could not complete the requested transition; try again": "Contactos no pudo completar la transición solicitada; inténtalo de nuevo",
+ "Space Missions could not complete the requested transition; try again": "Misiones espaciales no pudo completar la transición solicitada; inténtalo de nuevo",
+ "Nearby installations could not be refreshed; try again": "No se pudieron actualizar las instalaciones cercanas; inténtalo de nuevo",
+ "Context could not restore every layer; try again": "Contexto no pudo restaurar todas las capas; inténtalo de nuevo",
+ "Zoom in to search mapped installations": "Acércate para buscar instalaciones mapeadas",
+ "Nearby installations refreshed": "Instalaciones cercanas actualizadas",
+ "That layer is unavailable in the current Context mode": "Esa capa no está disponible en el modo de contexto actual",
+ "start": "iniciarse",
+ "stop": "detenerse",
+ "{layerId} could not {action} cleanly": "{layerId} no pudo {action} correctamente",
+ "Radio could not {action} cleanly": "Radio no pudo {action} correctamente",
+ "camera grid ready": "cuadrícula de cámaras lista",
+ "CCTV calibration saved": "Calibración de CCTV guardada",
+ "CCTV calibration reset": "Calibración de CCTV restablecida",
+ "CCTV layer unavailable": "Capa de CCTV no disponible",
+ "MAP": "MAPA",
+ "CONTACTS — nearest planes · vessels · sites": "CONTACTOS — aeronaves · buques · sitios más cercanos",
+ "SPACE MISSIONS — launches & orbital assets": "MISIONES ESPACIALES — lanzamientos y activos orbitales",
+ "Space Missions cancellation could not restore the previous layer state": "La cancelación de Misiones espaciales no pudo restaurar el estado previo de las capas",
+ "Collapse Cockpit display options": "Contraer las opciones de visualización de la cabina",
+ "Collapse Cockpit Radio controls": "Contraer los controles de Radio de la cabina",
+ "SYNC": "SINCR.",
+ "{category} BAND": "BANDA {category}",
+ "NO STATIONS": "SIN EMISORAS",
+ "{name}, station {index} of {total}": "{name}, emisora {index} de {total}",
+ "No station available": "Sin emisoras disponibles",
+ "OFF AIR": "FUERA DEL AIRE",
+ "STATION UNAVAILABLE": "EMISORA NO DISPONIBLE",
+ "Pause": "Pausar",
+ "Resume": "Reanudar",
+ "selected": "seleccionada",
+ "nearest": "más cercana",
+ "{action} {target} radio station": "{action} la emisora de radio {target}",
+ "RADIO STATE UNCERTAIN": "ESTADO DE RADIO SIN CONFIRMAR",
+ "SYNCING DIRECTORY": "SINCRONIZANDO DIRECTORIO",
+ "SYNCING": "SINCRONIZANDO",
+ "station": "emisora",
+ "Ready": "Listo",
+ "VIEWSHED ON": "ÁREA VISIBLE ACTIVADA",
+ "FRAME · LOADING": "FOTOGRAMA · CARGANDO",
+ "FRAME · UNAVAILABLE": "FOTOGRAMA · NO DISPONIBLE",
+ "CAL · EDITED (UNSAVED)": "CAL · EDITADA (SIN GUARDAR)",
+ "CAL · {badge}": "CAL · {badge}",
+ "CALIBRATED": "CALIBRADA",
+ "CURATED": "CURADA",
+ "RAW PRIOR": "ESTIMACIÓN INICIAL",
+ "MONITOR": "MONITOR",
+ "{city} · HDG {heading} · FOV {fov} · RANGE {range}m · {projection}{calBadge} · {provider}{status}": "{city} · HDG {heading} · FOV {fov} · RANGE {range} m · {projection}{calBadge} · {provider}{status}",
+ "{count} cameras loaded · click a camera to activate": {
+ "one": "{count} cámara cargada · haz clic en una cámara para activarla",
+ "many": "{count} de cámaras cargadas · haz clic en una cámara para activarla",
+ "other": "{count} cámaras cargadas · haz clic en una cámara para activarla"
+ },
+ "{count} cameras loaded · enable CCTV to activate": {
+ "one": "{count} cámara cargada · activa CCTV para activarla",
+ "many": "{count} de cámaras cargadas · activa CCTV para activarlas",
+ "other": "{count} cámaras cargadas · activa CCTV para activarlas"
+ },
+ "No summary available.": "No hay resumen disponible.",
+ "Celestial ring — available in Normal style": "Anillo celestial — disponible en el estilo Normal",
+ "Detection overlay: {mode}": "Superposición de detección: {mode}",
+ "Detection overlay: off": "Superposición de detección: desactivada",
+ "SPARSE": "DISPERSA",
+ "BALANCED": "EQUILIBRADA",
+ "DENSE": "DENSO",
+ "Resetting to full globe view": "Restableciendo la vista de globo completo",
+ "Resetting cockpit to full globe view": "Restableciendo la cabina a la vista de globo completo",
+ "ORBIT": "ÓRBITA",
+ "SUMMARY": "RESUMEN",
+ "Awaiting telemetry...": "Esperando telemetría...",
+ "REC": "REC",
+ "Scope edge feather": "Difuminado del borde de la mirilla",
+ "Bloom intensity": "Intensidad del resplandor",
+ "Sharpen intensity": "Intensidad de la nitidez",
+ "Search location by name or coordinates": "Buscar ubicación por nombre o coordenadas",
+ "Expand LOCATION": "Expandir UBICACIÓN",
+ "UNAVAILABLE": "NO DISPONIBLE",
+ "Live Flights": "Vuelos en vivo",
+ "Earthquakes (24h)": "Terremotos (24 h)",
+ "No selected data layers": "No hay capas de datos seleccionadas",
+ "Cleared {count} data layers": {
+ "one": "Se limpió {count} capa de datos",
+ "many": "Se limpiaron {count} de capas de datos",
+ "other": "Se limpiaron {count} capas de datos"
+ },
+ "{count} data layers could not be cleared": {
+ "one": "No se pudo limpiar {count} capa de datos",
+ "many": "No se pudieron limpiar {count} de capas de datos",
+ "other": "No se pudieron limpiar {count} capas de datos"
+ },
+ "Visible map targets": "Objetivos visibles en el mapa",
+ "CCTV": "CCTV",
+ "SOURCE · UNKNOWN": "FUENTE · DESCONOCIDA",
+ "Enable CCTV to load camera intersections": "Activa CCTV para cargar intersecciones con cámaras",
+ "CCTV OFF": "CCTV DESACTIVADO",
+ "NEAREST": "MÁS CERCANA",
+ "CCTV camera": "Cámara CCTV",
+ "FOCUS": "ENFOCAR",
+ "COVERAGE OFF": "COBERTURA DESACTIVADA",
+ "AUTO HOP OFF": "SALTO AUTO: NO",
+ "PROJECTION ON": "PROYECCIÓN ACTIVADA",
+ "CALIBRATION": "CALIBRACIÓN",
+ "ADJUST": "AJUSTAR",
+ "Drag the camera in the world: rings rotate, arrows move, handles set range/FOV": "Arrastra la cámara en el mundo: los anillos la giran, las flechas la mueven, los tiradores ajustan alcance/FOV",
+ "Camera pose — click a value to type": "Pose de la cámara — clic en un valor para escribirlo",
+ "Heading (compass °) — click to type": "Rumbo (° brújula) — clic para escribir",
+ "Pitch (° up/down) — click to type": "Inclinación (° arriba/abajo) — clic para escribir",
+ "Horizontal FOV (°) — click to type": "FOV horizontal (°) — clic para escribir",
+ "Range / monitor-plane distance (m) — click to type": "Alcance / distancia al plano del monitor (m) — clic para escribir",
+ "Mount height above ground (m) — click to type": "Altura de montaje sobre el suelo (m) — clic para escribir",
+ "North offset from catalog position (m) — click to type": "Desplazamiento al norte desde la posición del catálogo (m) — clic para escribir",
+ "East offset from catalog position (m) — click to type": "Desplazamiento al este desde la posición del catálogo (m) — clic para escribir",
+ "SAVE CAL": "GUARDAR CAL",
+ "RESET CAL": "RESTABLECER CAL",
+ "SCENE SUMMARY": "RESUMEN DE ESCENA",
+ "Enable CCTV to start camera-linked intelligence summaries.": "Activa CCTV para iniciar resúmenes de inteligencia vinculados a cámaras.",
+ "Internet radio and local SDR": "Radio por Internet y SDR local",
+ "Expand Radio": "Expandir Radio",
+ "Expand Radio section": "Expandir la sección de Radio",
+ "STATION TAG": "ETIQUETA DE EMISORA",
+ "Filter stations by station tag": "Filtrar emisoras por etiqueta de emisora",
+ "NO STATION SELECTED": "NINGUNA EMISORA SELECCIONADA",
+ "Enable Radio, then choose a globe marker or use next.": "Activa Radio y elige un marcador del globo o pulsa SIG.",
+ "DIRECTORY BAND": "BANDA DEL DIRECTORIO",
+ "DRAG TO TUNE": "ARRASTRA PARA SINTONIZAR",
+ "ALL · DRAG THE NEEDLE": "TODAS · ARRASTRA LA AGUJA",
+ "SNAPS TO AVAILABLE STATIONS": "SE AJUSTA A EMISORAS DISPONIBLES",
+ "Radio playback": "Reproducción de Radio",
+ "Previous filtered station": "Emisora filtrada anterior",
+ "PLAY": "ESCUCHAR",
+ "Play selected station": "Reproducir la emisora seleccionada",
+ "Next filtered station": "Siguiente emisora filtrada",
+ "STOP": "DETENER",
+ "Stop radio playback": "Detener la reproducción de Radio",
+ "Radio volume": "Volumen de Radio",
+ "Radio off": "Radio desactivada",
+ "STATION SITE": "SITIO DE LA EMISORA",
+ "Audio connects directly to the broadcaster after you press play. Your IP is visible to that broadcaster.": "El audio se conecta directamente con la emisora después de pulsar ESCUCHAR. Tu IP es visible para esa emisora.",
+ "LOADING": "CARGANDO",
+ "DEGRADED": "DEGRADADO",
+ "STALE": "DESACTUALIZADO",
+ "FALLBACK": "RESPALDO",
+ "PARTIAL": "PARCIAL",
+ "UNCERTAIN": "INCIERTO",
+ "ENABLING": "ACTIVANDO",
+ "DISABLING": "APAGANDO",
+ "Military Flights": "Vuelos militares",
+ "Satellites": "Satélites",
+ "Space Missions (30d)": "Misiones espaciales (30 d)",
+ "Street Traffic": "Tráfico urbano",
+ "Radio": "Radio",
+ "Bikeshare": "Bicicletas compartidas",
+ "Live AIS Vessels": "Buques AIS en vivo",
+ "Mapped Installations": "Instalaciones mapeadas",
+ "Global Context": "Contexto global",
+ "Datacenters": "Centros de datos",
+ "Dams": "Presas",
+ "Submarine Cables": "Cables submarinos",
+ "FIRMS Active Fires": "Incendios activos FIRMS",
+ "just now": "hace un momento",
+ "{count}s ago": "hace {count} s",
+ "{count}m ago": "hace {count} min",
+ "{count}h ago": "hace {count} h",
+ "never": "sin actualizar",
+ "loading...": "cargando...",
+ "UNCERTAIN · {source} · lifecycle state requires reconciliation": "INCIERTO · {source} · el estado del ciclo de vida requiere reconciliación",
+ "{state} · {source}": "{state} · {source}",
+ "{state} · {source} · {detail} · retry {seconds}s": "{state} · {source} · {detail} · reintento en {seconds}s",
+ "{state} · {source} · {detail}": "{state} · {source} · {detail}",
+ "{state} · {source} · {ago}": "{state} · {source} · {ago}",
+ "{state} · {source} · {ago} · retrying in {seconds}s": "{state} · {source} · {ago} · reintentando en {seconds}s",
+ "{source} · {loadingLabel}": "{source} · {loadingLabel}",
+ "{source} · {ago}": "{source} · {ago}",
+ "{accepted} of {raw} records accepted": "{accepted} de {raw} registros aceptados",
+ "incomplete snapshot": "instantánea incompleta",
+ "{state} · {source} · {detail} · {ago}": "{state} · {source} · {detail} · {ago}",
+ "{name}: {state}": "{name}: {state}",
+ "Type unknown": "Tipo desconocido",
+ "Reg unknown": "Matrícula desconocida",
+ "Operator unknown": "Operador desconocido",
+ "Alt unknown": "Altitud desconocida",
+ "FISHING": "PESCA",
+ "TOWING": "REMOLQUE",
+ "DREDGER": "DRAGA",
+ "DIVE OPS": "BUCEO",
+ "SAILING": "VELERO",
+ "PLEASURE": "RECREO",
+ "PILOT": "PRÁCTICO",
+ "SAR": "SAR",
+ "TUG": "REMOLCADOR",
+ "PORT TENDER": "AUXILIAR DE PUERTO",
+ "ANTI-POLLUTION": "ANTICONTAMINACIÓN",
+ "LAW ENFORCE": "POLICÍA",
+ "MEDICAL": "MÉDICO",
+ "HIGH-SPEED": "ALTA VELOCIDAD",
+ "PASSENGER": "PASAJEROS",
+ "CARGO": "CARGA",
+ "TANKER": "PETROLERO",
+ "OTHER": "OTRO",
+ "VESSEL": "BUQUE",
+ "POS: LIVE": "POS: EN VIVO",
+ "POS: {time}Z": "POS: {time}Z",
+ "AIS: --": "AIS: --",
+ "AIS: {name}": "AIS: {name}",
+ "{type} SPD: {speed} HDG: {heading}": "{type} SPD: {speed} HDG: {heading}",
+ "awaiting first AIS position…": "esperando la primera posición AIS…",
+ "CCTV ON": "CCTV ACTIVADO",
+ "COVERAGE ON": "COBERTURA ACTIVADA",
+ "AUTO HOP ON": "SALTO AUTO: SÍ",
+ "PROJECTION OFF": "PROYECCIÓN DESACTIVADA",
+ "ADJUST ON": "AJUSTE ACTIVADO",
+ "{count} CAMERAS STANDING BY · NO CAMERA SELECTED · CLICK A CAMERA TO ACTIVATE": "{count} CÁMARAS EN ESPERA · NINGUNA CÁMARA SELECCIONADA · CLIC EN UNA CÁMARA PARA ACTIVARLA",
+ "No cameras available in catalog.": "No hay cámaras disponibles en el catálogo.",
+ "{city} CCTV": "CCTV de {city}",
+ "HDG {value}°": "HDG {value}°",
+ "HDG {value}° (ESTIMATED)": "HDG {value}° (ESTIMADO)",
+ "FOV {value}°": "FOV {value}°",
+ "COVERAGE {value}km²": "COBERTURA {value} KM²",
+ "OVERLAP {count} cams": "SOLAPE {count} cám.",
+ "ISOLATED VIEW": "VISTA AISLADA",
+ "PROJ MONITOR": "PROY MONITOR",
+ "PROJ OFF": "PROY DESACT",
+ "VIEWSHED": "ÁREA VISIBLE",
+ "CAL {value}": "CAL {value}",
+ "SRC {value}": "SRC {value}",
+ "{value} CONTEXT": "CONTEXTO {value}",
+ "News": "Noticias",
+ "Talk": "Radio hablada",
+ "Weather / Emergency": "Clima / Emergencias",
+ "Public Safety": "Seguridad pública",
+ "Aviation / Marine": "Aviación / Marina",
+ "Traffic / Transit": "Tráfico / Transporte",
+ "Music": "Música",
+ "Other": "Otros",
+ "NO STATION AVAILABLE": "NINGUNA EMISORA DISPONIBLE",
+ "DISABLE": "DESACTIVAR",
+ "RECONCILE": "RECONCILIAR",
+ "Enable Radio": "Activar Radio",
+ "Disable Radio": "Desactivar Radio",
+ "Reconcile Radio — lifecycle uncertain": "Reconciliar Radio — ciclo de vida incierto",
+ "Loading station directory…": "Cargando el directorio de emisoras…",
+ "Directory metadata only": "Solo metadatos del directorio",
+ "Choose a globe marker or use next.": "Elige un marcador del globo o pulsa SIG.",
+ "TAGS · {tags}": "ETIQUETAS · {tags}",
+ "Ready — playback starts only from your action": "Preparada: la reproducción empieza cuando pulses ESCUCHAR",
+ "Connecting directly to broadcaster…": "Conectando directamente con la emisora…",
+ "Buffering broadcaster stream…": "Almacenando en búfer el flujo de la emisora…",
+ "Playing {station}": "Reproduciendo {station}",
+ "Paused {station}": "{station} en pausa",
+ "Broadcaster stream unavailable": "Flujo de la emisora no disponible",
+ " · degraded directory": " · directorio degradado",
+ " · stale directory": " · directorio desactualizado",
+ " · stale/degraded directory": " · directorio desactualizado/degradado",
+ " · outside current filter": " · fuera del filtro actual",
+ " · muted during voice interaction": " · silenciado durante la interacción de voz",
+ " · restoring volume after voice": " · restaurando el volumen tras la voz",
+ " · static indicates no broadcaster audio": " · la estática indica que no hay audio de la emisora",
+ " · tuning static until broadcaster starts": " · estática de sintonía hasta que la emisora comience",
+ "Station unavailable after directory refresh — choose another channel": "Emisora no disponible tras actualizar el directorio — elige otro canal",
+ "Radio is enabling…": "Activando Radio…",
+ "Radio is disabling…": "Desactivando Radio…",
+ "Radio lifecycle is uncertain — use Enable or Disable to reconcile": "El ciclo de vida de Radio es incierto — usa Activar o Desactivar para reconciliar",
+ "LAUNCH SITE": "LUGAR DE LANZAMIENTO",
+ "LAUNCH SITE · {site}": "LUGAR DE LANZAMIENTO · {site}",
+ "SELECTED SPACE MISSION": "MISIÓN ESPACIAL SELECCIONADA",
+ "Show all missions": "Mostrar todas las misiones",
+ "Deselect mission": "Deseleccionar misión",
+ "MISSION": "MISIÓN",
+ "STATUS · ": "ESTADO · ",
+ "LAUNCH SITE · ": "LUGAR DE LANZAMIENTO · ",
+ "LAUNCH TIME · ": "HORA DE LANZAMIENTO · ",
+ "ORBIT · ": "ÓRBITA · ",
+ "ASCENT PATH · ": "TRAYECTORIA DE ASCENSO · ",
+ "CURRENT DISTANCE FROM EARTH · ": "DISTANCIA ACTUAL A LA TIERRA · ",
+ "SATELLITE SPEED · ": "VELOCIDAD DEL SATÉLITE · ",
+ "PAYLOAD": "CARGA ÚTIL",
+ "NAME": "NOMBRE",
+ "TYPE": "TIPO",
+ "DESTINATION": "DESTINO",
+ "STAGE / RE-ENTRY / RECOVERY": "ETAPA / REENTRADA / RECUPERACIÓN",
+ "STAGE": "ETAPA",
+ "STATUS": "ESTADO",
+ "FINAL POSITION": "POSICIÓN FINAL",
+ "Previous mission": "Misión anterior",
+ "Next mission": "Misión siguiente",
+ "SHOW ALL / DESELECT": "MOSTRAR TODAS / DESELECCIONAR",
+ "NO MISSIONS AVAILABLE IN THE CURRENT 30-DAY WINDOW": "SIN MISIONES DISPONIBLES EN LA VENTANA ACTUAL DE 30 DÍAS",
+ "{count} / 30D": "{count} / 30 D",
+ "DATE UNAVAILABLE": "FECHA NO DISPONIBLE",
+ "UNSPECIFIED OPERATOR": "OPERADOR NO ESPECIFICADO",
+ "Select {mission}": "Seleccionar {mission}",
+ "+{count} additional payload records": "+{count} registros de carga útil adicionales",
+ "PAYLOAD DATA UNAVAILABLE": "DATOS DE CARGA ÚTIL NO DISPONIBLES",
+ "NO STAGE RE-ENTRY / RECOVERY DATA": "SIN DATOS DE REENTRADA / RECUPERACIÓN DE ETAPA",
+ "UNSPECIFIED": "NO ESPECIFICADO",
+ "FLIGHT {count}": "VUELO {count}",
+ "REUSED": "REUTILIZADO",
+ "{value} KM DOWNRANGE": "{value} KM DE TRAYECTORIA",
+ "PLANNED · ": "PLANIFICADA · ",
+ "SUPPLIED TRAJECTORY POINTS": "PUNTOS DE TRAYECTORIA SUMINISTRADOS",
+ "RECONSTRUCTED ESTIMATE": "ESTIMACIÓN RECONSTRUIDA",
+ "{value} KM": "{value} KM",
+ "{value} KM/S": "{value} KM/S",
+ "REPLAY ASCENT": "REPETIR ASCENSO",
+ "Replay the estimated ascent with a following camera": "Reproduce el ascenso estimado con una cámara de seguimiento",
+ "Pause replay": "Pausar repetición",
+ "Resume replay": "Reanudar repetición",
+ "Cancel replay": "Cancelar repetición",
+ "REPLAY SPEED": "VELOCIDAD DE REPETICIÓN",
+ "Replay speed multiplier": "Multiplicador de velocidad de repetición",
+ "T−{time} · {mission}": "T−{time} · {mission}",
+ "LAUNCH STANDBY": "EN ESPERA DE LANZAMIENTO",
+ "LIFTOFF · {mission}": "DESPEGUE · {mission}",
+ "ASCENT REPLAY · {mission}": "REPETICIÓN DEL ASCENSO · {mission}",
+ "ASCENT ESTIMATE · {mission}": "ESTIMACIÓN DEL ASCENSO · {mission}",
+ "STAGE RE-ENTRY / RECOVERY · {mission}": "REENTRADA / RECUPERACIÓN DE ETAPA · {mission}",
+ "ORBIT REPLAY · {mission}": "REPETICIÓN EN ÓRBITA · {mission}",
+ "PAUSED · {title}": "EN PAUSA · {title}",
+ "T minus {seconds}": "T menos {seconds}",
+ "Preparing launch site": "Preparando el lugar de lanzamiento",
+ "Liftoff": "Despegue",
+ "Ascent replay": "Repetición del ascenso",
+ "Orbit replay": "Repetición en órbita",
+ ", paused": ", en pausa",
+ "DENSE ···": "DENSO ···",
+ "DENSE ✕": "DENSO ✕",
+ "Add the full Starlink broadband shell (thousands of extra points)": "Añade la capa completa de banda ancha de Starlink (miles de puntos extra)",
+ "Loading the Starlink shell…": "Cargando la capa de Starlink…",
+ "Starlink {detail} — click to retry": "Starlink {detail} — clic para reintentar",
+ "load failed": "carga fallida",
+ "Showing the full Starlink shell — click for the core catalog only": "Mostrando la capa completa de Starlink — clic para ver solo el catálogo principal",
+ "STATION": "ESTACIÓN",
+ "Crewed stations and their visiting vehicles": "Estaciones tripuladas y sus vehículos de visita",
+ "NAV": "NAV",
+ "GNSS navigation — GPS, GLONASS, Galileo": "Navegación GNSS — GPS, GLONASS, Galileo",
+ "GEO": "GEO",
+ "Geostationary belt — comms and weather, fixed over the equator": "Cinturón geoestacionario — comunicaciones y meteorología, fijos sobre el ecuador",
+ "VISUAL": "VISUAL",
+ "Brightest naked-eye objects — CelesTrak visual group": "Objetos más brillantes a simple vista — grupo visual de CelesTrak",
+ "COMMS": "TELECOM",
+ "Broadband constellation shell — shown only in DENSE mode": "Capa de constelación de banda ancha — visible solo en modo DENSO",
+ "refreshing...": "actualizando...",
+ "KEY REQUIRED": "CLAVE REQUERIDA",
+ "STALE · cached {age}": "DESACTUALIZADO · en caché hace {age}",
+ "LIVE · updated {age}": "EN VIVO · actualizado {age}",
+ "<1m ago": "hace <1 min",
+ "FIRE · {frp} MW": "INCENDIO · {frp} MW",
+ "▲ {frp} MW": "▲ {frp} MW",
+ "FIRE": "INCENDIO",
+ "FIRES": "INCENDIOS",
+ "{value} conf": "confianza {value}",
+ "{value} ago": "hace {value}",
+ "max {value} MW": "máx {value} MW",
+ "new {value}": "nueva hace {value}",
+ "NIGHT": "NOCHE",
+ "sensor n/a": "sensor n/d",
+ "Focus fire detection {title}, {details}": "Enfocar la detección de incendio {title}, {details}",
+ "SIMULATED — traffic service unreachable": "SIMULADO — servicio de tráfico inaccesible",
+ "SIMULATED — add TomTom key for live": "SIMULADO — añade una clave de TomTom para datos en vivo",
+ "syncing {count} city feeds...": "sincronizando {count} fuentes de ciudades...",
+ "scanning nearby systems...": "escaneando sistemas cercanos...",
+ "🚲 {bikes} avail · {docks} docks · {capacity} cap": "🚲 {bikes} disp · {docks} anclajes · {capacity} cap",
+ "⚠️ Not installed": "⚠️ No instalada",
+ "⚠️ Not renting": "⚠️ No alquila",
+ "⚠️ Not returning": "⚠️ No admite devoluciones",
+ "Station": "Estación",
+ "Station {id}": "Estación {id}",
+ "MAPPED INSTALLATION": "INSTALACIÓN MAPEADA",
+ "loading mapped installation context": "cargando contexto de instalaciones mapeadas",
+ "Overpass rate-limited": "Overpass con límite de peticiones",
+ "Overpass timed out": "Overpass agotó el tiempo de espera",
+ "Overpass could not complete the query": "Overpass no pudo completar la consulta",
+ "Overpass temporarily unavailable": "Overpass temporalmente no disponible",
+ "Retrying mapped sites…": "Reintentando sitios mapeados…",
+ "Fetching mapped sites…": "Obteniendo sitios mapeados…",
+ "{reason} — retrying in {seconds}s": "{reason} — reintentando en {seconds}s",
+ "{reason} — retry pending": "{reason} — reintento pendiente",
+ "Showing cached mapped sites": "Mostrando sitios mapeados en caché",
+ "Mapped sites not loaded": "Sitios mapeados sin cargar",
+ "Mapped sites loaded": "Sitios mapeados cargados",
+ "CONTEXT READY": "CONTEXTO LISTO",
+ "GLOBAL CONTEXT OFF": "CONTEXTO GLOBAL DESACTIVADO",
+ "SELECT A FLIGHT, VESSEL, OR MAPPED INSTALLATION": "SELECCIONA UN VUELO, BUQUE U INSTALACIÓN MAPEADA",
+ "ENABLE TO LOAD OBSERVED / MAPPED PROXIMITY": "ACTIVA PARA CARGAR PROXIMIDAD OBSERVADA / MAPEADA",
+ "Global Context navigation": "Navegación del Contexto global",
+ "PREVIOUS": "ANT.",
+ "Open-source mapped/observed context. Missing broadcasts, unloaded map areas, or unmapped sites are not evidence of absence.": "Contexto mapeado/observado de fuentes abiertas. Las transmisiones ausentes, las zonas del mapa sin cargar o los sitios sin mapear no son evidencia de ausencia.",
+ "Unavailable": "No disponible",
+ "Focus {label}": "Enfocar {label}",
+ "Flights": "Vuelos",
+ "Military flights": "Vuelos militares",
+ "AIS vessels": "Buques AIS",
+ "Mapped installations": "Instalaciones mapeadas",
+ "CURRENT VIEWPORT ONLY": "SOLO LA VISTA ACTUAL",
+ "BRG {value}°": "BRG {value}°",
+ "CRS {value}°": "CRS {value}°",
+ "feed unavailable": "fuente no disponible",
+ "feed stale": "fuente desactualizada",
+ "observed or mapped nearby context": "contexto cercano observado o mapeado",
+ "no observed or mapped objects in current feeds": "sin objetos observados o mapeados en las fuentes actuales",
+ "CONDITIONS UNKNOWN": "CONDICIONES DESCONOCIDAS",
+ "CLEAR": "DESPEJADO",
+ "PARTLY CLOUDY": "PARCIALMENTE NUBLADO",
+ "OVERCAST": "CUBIERTO",
+ "FOG": "NIEBLA",
+ "DRIZZLE": "LLOVIZNA",
+ "RAIN": "LLUVIA",
+ "SNOW": "NIEVE",
+ "RAIN SHOWERS": "CHUBASCOS",
+ "SNOW SHOWERS": "CHUBASCOS DE NIEVE",
+ "THUNDERSTORM": "TORMENTA",
+ "MIXED CONDITIONS": "CONDICIONES MIXTAS",
+ "TAB PREVIEWS · ENTER / SPACE SELECTS": "TAB VISTA PREVIA · ENTER / SPACE SELECCIONA",
+ "awaiting usable AIS positions…": "esperando posiciones AIS utilizables…",
+ "awaiting first AIS message…": "esperando el primer mensaje AIS…",
+ "EST. DOWNRANGE": "DIST. ESTIMADA",
+ "MISSION CONTROL · FIRST LAUNCH": "CENTRO DE MANDO · PRIMER INICIO",
+ "Choose your first view": "Elige tu primera vista",
+ "LIVE CONTACTS": "CONTACTOS EN VIVO",
+ "Don't show this again": "No volver a mostrar",
+ "POWER UP": "ENCENDER",
+ "GROUND STATION · PROVIDER SETTINGS": "ESTACIÓN TERRENA · AJUSTES DE PROVEEDORES",
+ "Power up the globe": "Enciende el globo",
+ "SAVE KEYS": "GUARDAR CLAVES",
+ "Saving…": "Guardando…",
+ "It feels like a forbidden cockpit—then you realize the sources are public and the data is real.": "Parece una cabina prohibida—hasta que descubres que las fuentes son públicas y los datos son reales.",
+ "Aircraft, vessels and nearby intelligence": "Aeronaves, buques e inteligencia cercana",
+ "Launches, spacecraft and orbital context": "Lanzamientos, naves y contexto orbital",
+ "EXPLORE MANUALLY": "EXPLORAR MANUALMENTE",
+ "Begin with a clean globe": "Empieza con un globo limpio",
+ "ESC to dismiss": "ESC para cerrar",
+ "Tip: the GEV MIC button in the dock lets you talk to the map.": "Consejo: el botón GEV MIC del dock te permite hablar con el mapa.",
+ "Close key setup": "Cerrar la configuración de claves",
+ "The globe already flies keyless. Every key below switches on another real feed — paste one and it's saved into this app's local configuration, then the server restarts itself. Server-side keys stay on this machine; Google Maps and Cesium ion run in the browser and must be provider-restricted. Keys you configured elsewhere are shown but never touched.": "El globo ya funciona sin claves. Cada clave de abajo activa otra fuente real — pega una y queda guardada en la configuración local de esta app, y luego el servidor se reinicia solo. Las claves del servidor se quedan en esta máquina; Google Maps y Cesium ion funcionan en el navegador y sus claves deben restringirse en la consola del proveedor. Las claves que configuraste en otro lugar se muestran, pero nunca se modifican.",
+ "ESC to close": "ESC para cerrar",
+ "The Google Maps key buys the photorealistic planet — everything else stacks on top.": "La clave de Google Maps activa el planeta fotorrealista; todo lo demás se superpone.",
+ "SCENES": "ESCENAS",
+ "Scene recipe": "Receta de escena",
+ "NEW": "NUEVA",
+ "DEL": "BORRAR",
+ "CAPTURE SHOT": "CAPTURAR PLANO",
+ "UPDATE SHOT": "ACTUALIZAR PLANO",
+ "START": "INICIAR",
+ "EXPORT PRESETS": "EXPORTAR PREAJUSTES",
+ "IMPORT": "IMPORTAR",
+ "RUN LOG": "REGISTRO DE EJECUCIÓN",
+ "Starting live contacts…": "Iniciando contactos en vivo…",
+ "Opening space missions…": "Abriendo misiones espaciales…",
+ "Scanning active events…": "Escaneando eventos activos…",
+ "Working…": "Trabajando…",
+ "Could not open that mission{detail}. Retry or explore manually.": "No se pudo abrir esa misión{detail}. Reintenta o explora manualmente.",
+ "This browser is blocking storage, so that could not be saved.": "Este navegador bloquea el almacenamiento, así que no se pudo guardar.",
+ "Live earthquakes and active fires, from USGS and NASA": "Terremotos en vivo e incendios activos, de USGS y NASA",
+ "ENVIRONMENTAL": "MEDIO AMBIENTE",
+ "EARTH WATCH": "VIGILANCIA TERRESTRE",
+ "ACTIVE EVENTS": "EVENTOS ACTIVOS",
+ "POWER UP · {count} KEYS WAITING": {
+ "one": "ENCENDER · {count} CLAVE EN ESPERA",
+ "many": "ENCENDER · {count} DE CLAVES EN ESPERA",
+ "other": "ENCENDER · {count} CLAVES EN ESPERA"
+ },
+ "POWERED UP": "ENCENDIDO",
+ "Save failed ({status}).": "Error al guardar ({status}).",
+ "Save failed: {detail}": "Error al guardar: {detail}",
+ "Paste at least one key first.": "Pega al menos una clave primero.",
+ "Saved to {store}. Restarting — this page reloads itself.": "Guardado en {store}. Reiniciando — esta página se recarga sola.",
+ "Removed from {store}. Restarting — this page reloads itself.": "Eliminado de {store}. Reiniciando — esta página se recarga sola.",
+ "your app configuration": "tu configuración de la app",
+ "your local .env": "tu .env local",
+ "Remove this key from your saved configuration?": "¿Eliminar esta clave de tu configuración guardada?",
+ "This map stack": "Este conjunto de mapas",
+ "{label} is unavailable": "{label} no está disponible",
+ "{label} unavailable: {hint}": "{label} no disponible: {hint}",
+ "Global Flights Radar": "Radar global de vuelos",
+ "Orbital Watch": "Vigilancia orbital",
+ "Thermal Threat Board": "Panel de amenazas térmicas",
+ "City Overload": "Sobrecarga urbana",
+ "Omniscience Pullback": "Alejamiento omnisciente",
+ "CONNECTING": "CONECTANDO",
+ "ERROR": "ERROR",
+ "Session ended — cost cap {cost}": "Sesión finalizada — límite de costo {cost}",
+ "VOICE STANDBY": "VOZ EN ESPERA",
+ "VOICE ACTIVE": "VOZ ACTIVA",
+ "VOICE UNAVAILABLE": "VOZ NO DISPONIBLE",
+ "WebRTC microphone support unavailable": "Este navegador no admite micrófono WebRTC",
+ "Requesting microphone": "Solicitando micrófono",
+ "Hold Space to talk": "Mantén Space y habla",
+ "Release Space to send": "Suelta Space para enviar",
+ "Ask or command": "Pregunta o ordena",
+ "Voice off": "Voz desactivada",
+ "Running command": "Ejecutando comando",
+ "Radio did not start": "La radio no se inició",
+ "Hold Space to speak · tap Space to activate focused controls": "Mantén pulsado Space para hablar · pulsa Space brevemente para activar el control enfocado",
+ "Voice session could not be started.": "No se pudo iniciar la sesión de voz.",
+ "VOICE SYSTEM ERROR": "ERROR DEL SISTEMA DE VOZ",
+ "DISMISS": "CERRAR",
+ "Check microphone permission and network access, then try again.": "Revisa el permiso del micrófono y el acceso a la red, y vuelve a intentarlo.",
+ "AI AGENT": "AGENTE DE IA",
+ "VOICE CONTROL": "CONTROL DE VOZ",
+ "{tier} applies next session": "{tier} desde la próxima sesión",
+ "Voice model tier — applies next session": "Nivel del modelo de voz — se aplica en la próxima sesión",
+ "Estimated session cost": "Costo estimado de la sesión",
+ "Voice control — activate to toggle voice; hold Space to speak": "Control de voz — púlsalo para activar o desactivar la voz; mantén pulsado Space para hablar",
+ "Cannot capture shot: camera not ready": "No se puede capturar el plano: la cámara no está lista",
+ "Shot {n}": "Plano {n}",
+ "Captured: {scene} / {shot}": "Capturado: {scene} / {shot}",
+ "Select a shot first": "Selecciona primero un plano",
+ "Updated: {scene} / {shot}": "Actualizado: {scene} / {shot}",
+ "Delete shot \"{shot}\"?": "¿Eliminar el plano \"{shot}\"?",
+ "Loaded: {scene} / {shot}": "Cargado: {scene} / {shot}",
+ "Camera unavailable — exit cockpit first": "Cámara no disponible — sal primero de la cabina",
+ "No shots to run": "No hay planos para ejecutar",
+ "Running {index}/{total}: {scene} / {shot}": "Ejecutando {index}/{total}: {scene} / {shot}",
+ "Scene run complete": "Ejecución de escenas completada",
+ "Error: {message}": "Error: {message}",
+ "Could not exit {mode} — scene layers may be refused": "No se pudo salir de {mode} — las capas de la escena pueden rechazarse",
+ "REMOVE": "ELIMINAR",
+ "Remove {title} from this app's saved keys": "Elimina {title} de las claves guardadas de esta app",
+ "Needs {envVars} — add it in Provider Settings": "Necesita {envVars} — se añade en Ajustes de proveedores",
+ "Places context + Street View fallback; optional separate key": "Contexto de Places + respaldo de Street View; clave separada opcional",
+ "Live ships, worldwide": "Buques en vivo, en todo el mundo",
+ "Live active-fire detections": "Detecciones de incendios activos en vivo",
+ "Real live traffic (keyless runs a simulation)": "Tráfico real en vivo (sin clave se usa una simulación)",
+ "Bing imagery map stacks + world terrain": "Imágenes de Bing + terreno mundial",
+ "More flight-polling credits (anonymous works without)": "Más créditos de consulta de vuelos (sin clave funciona el modo anónimo)",
+ "Public space-missions access needs no key. Leave blank for standard use; paid tokens only raise request limits.": "El acceso público a misiones espaciales no necesita clave. Déjalo en blanco para el uso estándar; los tokens de pago solo aumentan los límites de solicitudes.",
+ "Optional paid token — public access works without one": "Token opcional de pago — el acceso público funciona sin él",
+ "Scene action failed": "La acción de escena falló",
+ "Project exported": "Proyecto exportado",
+ "Next session: {pendingId} — this session stays on {modelId}": "Sesión siguiente: {pendingId} — esta sesión sigue en {modelId}",
+ "Voice model: {pendingId} — click to switch to {target}; applies next session": "Modelo de voz: {pendingId} — haz clic para cambiar a {target}; se aplica en la próxima sesión",
+ "Estimated session cost on {modelId} — {responses} response(s). Warns at {warn}, ends the session at {cap}.": "Costo de sesión estimado en {modelId} — {responses} respuesta(s). Avisa a {warn} y cierra la sesión a {cap}.",
+ "Street-level imagery and coverage in the Street Level layer. Free: register an app in the Mapillary developer dashboard and paste its Client Token": "Imágenes y cobertura a nivel de calle en la capa \"A pie de calle\". Gratis: registra una app en el panel de desarrolladores de Mapillary y pega su token de cliente (Client Token)",
+ "Voice control — API key or ChatGPT OAuth": "Control de voz — clave de API u OAuth de ChatGPT",
+ "WITHIN {km} KM": "A MENOS DE {km} KM",
+ "Syncing flow · Roads: {source}": "Sincronizando flujo · Vías: {source}",
+ "LIVE · Roads: {source} · Roads without flow hidden": "EN VIVO · Vías: {source} · Vías sin flujo ocultas",
+ "LIVE · Roads: {source} · No flow roads in view": "EN VIVO · Vías: {source} · Sin vías con flujo a la vista",
+ "LIVE · Roads: {source} · Flow {percent}%": "EN VIVO · Vías: {source} · Flujo {percent}%",
+ "SIMULATED · Roads: {source} · Flow {percent}%": "SIMULADO · Vías: {source} · Flujo {percent}%",
+ "Syncing flow · Roads: OpenStreetMap · Flow: TomTom · Unmatched: simulated": "Sincronizando flujo · Vías: OpenStreetMap · Flujo: TomTom · Sin coincidencia: simulado",
+ "LIVE · Roads: OpenStreetMap · Flow: TomTom · {percent}% cov · Unmatched: simulated": "EN VIVO · Vías: OpenStreetMap · Flujo: TomTom · {percent}% cob. · Sin coincidencia: simulado",
+ "LIVE · Roads: OpenStreetMap · Flow: TomTom · {percent}% cov": "EN VIVO · Vías: OpenStreetMap · Flujo: TomTom · {percent}% cob.",
+ "SIMULATED · Roads: OpenStreetMap · Flow: TomTom (no matches)": "SIMULADO · Vías: OpenStreetMap · Flujo: TomTom (sin coincidencias)",
+ "Data source unavailable": "Fuente de datos no disponible",
+ "Saturation": "Saturación",
+ "Edge Thickness": "Grosor de bordes",
+ "Contrast": "Contraste",
+ "Grain": "Grano",
+ "Vignette": "Viñeta",
+ "Pixelation": "Pixelado",
+ "Distortion": "Distorsión",
+ "Instability": "Inestabilidad",
+ "Wind": "Viento",
+ "Gain": "Ganancia",
+ "Scanlines": "Líneas de barrido",
+ "Sensitivity": "Sensibilidad",
+ "WHOT/BHOT": "WHOT/BHOT",
+ "Ironbow": "Ironbow",
+ "Pick a shape, then click the map.": "Elige una forma y haz clic en el mapa.",
+ "Enter to place the pin, Esc to cancel.": "Enter para colocar el marcador, Esc para cancelar.",
+ "Click where the pin goes.": "Haz clic donde quieras colocar el marcador.",
+ "Click {count} more points.": {
+ "one": "Haz clic en {count} punto más.",
+ "many": "Haz clic en {count} de puntos más.",
+ "other": "Haz clic en {count} puntos más."
+ },
+ "Those points are in a line — move one off it to enclose an area.": "Esos puntos están en línea: mueve uno fuera de ella para cerrar un área.",
+ "That line has no length — click somewhere further away.": "Esa línea no tiene longitud: haz clic más lejos.",
+ " · {max}-point limit reached": " · límite de {max} puntos alcanzado",
+ "{measure} · double-click or Enter to finish, Backspace undoes, Esc cancels.{full}": "{measure} · doble clic o Enter para terminar, Backspace deshace, Esc cancela.{full}",
+ "That point is off the globe — click on the world.": "Ese punto está fuera del globo: haz clic sobre el mundo.",
+ "That shape could not be placed.": "No se pudo colocar esa forma.",
+ "Board cleared.": "Tablero borrado.",
+ "Draw on the world — click vertices, double-click or Enter to finish, Esc to cancel": "Dibuja sobre el mundo: haz clic en los vértices, doble clic o Enter para terminar, Esc para cancelar",
+ "Draw": "Dibujo",
+ "Shape": "Forma",
+ "Shape to draw": "Forma a dibujar",
+ "Area": "Área",
+ "Line": "Línea",
+ "Pin": "Marcador",
+ "Label (optional)": "Etiqueta (opcional)",
+ "Label for the drawn shape": "Etiqueta de la forma dibujada",
+ "Colour of the drawn shape": "Color de la forma dibujada",
+ "Primary": "Principal",
+ "Amber": "Ámbar",
+ "Cyan": "Cian",
+ "Green": "Verde",
+ "Red": "Rojo",
+ "Clear": "Borrar",
+ "Remove every mark from the board": "Quitar todas las marcas del tablero",
+ "Point the camera at the globe for street-level coverage": "Apunta la cámara al globo para ver la cobertura a pie de calle",
+ "No street-level imagery providers configured": "No hay proveedores de imágenes a pie de calle configurados",
+ "Selected": "Seleccionada",
+ "Live Vessels": "Buques en vivo",
+ "Bike Share": "Bicis compartidas",
+ "Cameras": "Cámaras",
+ "Street Level": "A pie de calle",
+ "Mapped ALPR Cameras": "Cámaras ALPR mapeadas",
+ "Data Centers": "Centros de datos",
+ "Active Fires": "Incendios activos",
+ "Street Level could not start": "No se pudo iniciar A pie de calle",
+ "Street Level toggle failed": "No se pudo activar o desactivar la capa A pie de calle",
+ "Street-level image": "Imagen a pie de calle",
+ "SHRINK": "REDUCIR",
+ "EXPAND": "AMPLIAR",
+ "Shrink": "Reducir",
+ "Expand": "Ampliar",
+ "ANY DATE": "CUALQUIER FECHA",
+ "LAST 10 YEARS": "ÚLTIMOS 10 AÑOS",
+ "LAST 5 YEARS": "ÚLTIMOS 5 AÑOS",
+ "LAST 3 YEARS": "ÚLTIMOS 3 AÑOS",
+ "LAST 2 YEARS": "ÚLTIMOS 2 AÑOS",
+ "LAST YEAR": "ÚLTIMO AÑO",
+ "LAST 6 MONTHS": "ÚLTIMOS 6 MESES",
+ "LAST 3 MONTHS": "ÚLTIMOS 3 MESES",
+ "LAST MONTH": "ÚLTIMO MES",
+ "LAST {count} DAYS": {
+ "one": "ÚLTIMO {count} DÍA",
+ "many": "ÚLTIMOS {count} DE DÍAS",
+ "other": "ÚLTIMOS {count} DÍAS"
+ },
+ "{window} · SINCE {date}": "{window} · DESDE {date}",
+ "Turn Street Level off": "Desactivar A pie de calle",
+ "Turn Street Level on": "Activar A pie de calle",
+ "KEY REJECTED": "CLAVE RECHAZADA",
+ "{name} imagery on": "Imágenes de {name} activadas",
+ "{name} imagery off": "Imágenes de {name} desactivadas",
+ "Image by {creator}": "Imagen de {creator}",
+ "zoom in to see KartaView coverage": "acércate para ver la cobertura de KartaView",
+ "no KartaView photos in view": "no hay fotos de KartaView a la vista",
+ "{names}: by upload date": "{names}: por fecha de subida",
+ "{n} streets in view · click a line for its nearest photo": {
+ "one": "{n} calle a la vista · haz clic en una línea para su foto más cercana",
+ "many": "{n} calles a la vista · haz clic en una línea para su foto más cercana",
+ "other": "{n} calles a la vista · haz clic en una línea para su foto más cercana"
+ },
+ "Camera follows view: move the globe camera wherever the street-level view looks": "La cámara sigue la vista: mueve la cámara del globo hacia donde mira la vista a pie de calle",
+ "Camera follow needs the Google 3D map: choose Google 3D under MAP SOURCE": "Seguir con la cámara requiere el mapa Google 3D: elige Google 3D en FUENTE DEL MAPA",
+ "Switch a provider on to draw its coverage.": "Activa un proveedor para dibujar su cobertura.",
+ "Loading this sequence…": "Cargando esta secuencia…",
+ "{n} images in this sequence · Esc clears": {
+ "one": "{n} imagen en esta secuencia · Esc quita la selección",
+ "many": "{n} de imágenes en esta secuencia · Esc quita la selección",
+ "other": "{n} imágenes en esta secuencia · Esc quita la selección"
+ },
+ "{n} sequences in view · click a line for its photos": {
+ "one": "{n} secuencia a la vista · haz clic en una línea para ver sus fotos",
+ "many": "{n} de secuencias a la vista · haz clic en una línea para ver sus fotos",
+ "other": "{n} secuencias a la vista · haz clic en una línea para ver sus fotos"
+ },
+ "STREET LEVEL": "A PIE DE CALLE",
+ "Expand the street-level view (Esc shrinks it)": "Ampliar la vista a pie de calle (Esc la reduce)",
+ "Image fit": "Ajuste de la imagen",
+ "FIT": "AJUSTAR",
+ "Fit: show the whole photo, with dark bars where its shape differs from the frame": "Ajustar: muestra la foto entera, con barras oscuras donde su forma no coincide con el marco",
+ "FILL": "RELLENAR",
+ "Fill: fill the frame edge to edge, cropping the photo": "Rellenar: llena el marco de borde a borde, recortando la foto",
+ "Camera follows view": "La cámara sigue la vista",
+ "FOLLOW": "SEGUIR",
+ "Close the image and deselect it on the map": "Cerrar la imagen y quitar la selección en el mapa",
+ "Close the street-level image": "Cerrar la imagen a pie de calle",
+ "Street-level viewer": "Visor a pie de calle",
+ "Open this image on the provider's site": "Abrir esta imagen en el sitio del proveedor",
+ "Imagery providers": "Proveedores de imágenes",
+ "PROVIDERS": "PROVEEDORES",
+ "Imagery filters": "Filtros de imágenes",
+ "IMAGERY": "IMÁGENES",
+ "Panorama filter": "Filtro de panoramas",
+ "ALL": "TODAS",
+ "FLAT": "PLANAS",
+ "SINCE": "DESDE",
+ "Coverage colours": "Colores de cobertura",
+ "That shape already has {count} points — finish it or press Backspace.": "Esa forma ya tiene {count} puntos — termínala o pulsa Backspace.",
+ "Could not place the shape: {error}": "No se pudo colocar la forma: {error}",
+ "{owner} is using the pointer — close it first.": "Puntero en uso: {owner}. Ciérralo primero.",
+ "{label} · Detailed outline unavailable": "{label} · Contorno detallado no disponible",
+ "Witness source": "Fuente de testigo",
+ "{provider} · EMBEDDED SOURCE": "{provider} · FUENTE INSERTADA",
+ "OPEN ORIGINAL ↗": "ABRIR ORIGINAL ↗",
+ "{provider} media: {source}": "Contenido de {provider}: {source}",
+ "{provider} · PROVIDER CONTROLS": "{provider} · CONTROLES DEL PROVEEDOR",
+ "YOUTUBE {state} · OPEN ORIGINAL": "YOUTUBE {state} · ABRIR ORIGINAL",
+ "Facebook player API did not initialize.": "La API del reproductor de Facebook no se inicializó.",
+ "Facebook player API could not load.": "No se pudo cargar la API del reproductor de Facebook.",
+ "Facebook player API timed out.": "La API del reproductor de Facebook agotó el tiempo de espera.",
+ "X embed API did not initialize.": "La API de inserción de X no se inicializó.",
+ "X embed could not load.": "No se pudo cargar la inserción de X.",
+ "X embed timed out.": "La inserción de X agotó el tiempo de espera.",
+ "TIMEOUT": "TIEMPO AGOTADO",
+ "BLOCKED": "BLOQUEADO",
+ "Facebook embed unavailable. The post may be private, removed, region-restricted, or blocked.": "Inserción de Facebook no disponible. La publicación puede ser privada, haber sido eliminada, estar restringida por región o estar bloqueada.",
+ "Preloading {provider} media": "Precargando contenido de {provider}",
+ "LOADING X POST…": "CARGANDO PUBLICACIÓN DE X…",
+ "The X post is unavailable or cannot be embedded.": "La publicación de X no está disponible o no se puede insertar.",
+ "X POST · PROVIDER CONTROLS": "PUBLICACIÓN DE X · CONTROLES DEL PROVEEDOR",
+ "{reason} OPEN ORIGINAL.": "{reason} ABRE EL ORIGINAL.",
+ "X embed unavailable": "Inserción de X no disponible",
+ "FACEBOOK · PROVIDER CONTROLS": "FACEBOOK · CONTROLES DEL PROVEEDOR",
+ "Facebook embed unavailable": "Inserción de Facebook no disponible",
+ "AUTOPLAY BLOCKED · USE PROVIDER CONTROLS": "REPRODUCCIÓN AUTOMÁTICA BLOQUEADA · USA LOS CONTROLES DEL PROVEEDOR",
+ "Embedded {provider} media for {source}": "Contenido de {provider} insertado para {source}",
+ "witness source": "fuente de testigo",
+ "Rasuwagadhi witness": "Testigo de Rasuwagadhi",
+ "Open original source for {source}; capture time unverified": "Abrir la fuente original de {source}; hora de captura sin verificar",
+ "Historical reference and post-event image divider": "Divisor entre la imagen de referencia histórica y la posterior al evento",
+ "A historical reference {before} percent, B post-event {after} percent": "A, referencia histórica, {before} por ciento; B, posterior al evento, {after} por ciento",
+ "■ RELEASE CAMERA": "■ LIBERAR CÁMARA",
+ "Seek Nepal scene clock": "Desplazarse por el reloj de la escena de Nepal",
+ "NEPAL SCENE CLOCK": "RELOJ DE LA ESCENA DE NEPAL",
+ "… PLAYING SHOT": "… REPRODUCIENDO PLANO",
+ "▶ PLAY SHOT": "▶ REPRODUCIR PLANO",
+ "Ⅱ PAUSE": "Ⅱ PAUSA",
+ "↺ REPLAY CINEMATIC": "↺ REPETIR CINEMÁTICA",
+ "↺ REPLAY": "↺ REPETIR",
+ "… PLAYING SCENE": "… REPRODUCIENDO ESCENA",
+ "Continue {scene} from next shot": "Continuar {scene} desde el siguiente plano",
+ "current scene": "la escena actual",
+ "Replay the full reconstruction": "Repetir la reconstrucción completa",
+ "SCENE SHOT": "PLANO DE ESCENA",
+ "TIME UNVERIFIED": "HORA SIN VERIFICAR",
+ "{count} SOURCES": {
+ "one": "{count} FUENTE",
+ "many": "{count} DE FUENTES",
+ "other": "{count} FUENTES"
+ },
+ "OUTSIDE IMAGERY SWIPE": "FUERA DE LA COMPARACIÓN DE IMÁGENES",
+ "{scene} / AUTHORED SHOT": "{scene} / PLANO DISEÑADO",
+ "NEPAL FLOOD INCIDENT": "INCIDENTE DE INUNDACIÓN EN NEPAL",
+ "Play {shot}": "Reproducir {shot}",
+ "current scene shot": "el plano actual de la escena",
+ "Play reconstruction": "Reproducir la reconstrucción",
+ "Load previous scene shot": "Cargar el plano anterior de la escena",
+ "Load next scene shot": "Cargar el siguiente plano de la escena",
+ "SCHEMATIC CORRIDOR, NOT MODELED ARRIVAL TIME.": "CORREDOR ESQUEMÁTICO; NO ES UN TIEMPO DE LLEGADA MODELADO.",
+ "Rasuwa · 26 Aug 2026": "Rasuwa · 26 ago 2026",
+ "Event reconstruction": "Reconstrucción del evento",
+ "INITIATION": "INICIO",
+ "DAMMING": "REPRESAMIENTO",
+ "SECONDARY FAILURE": "ROTURA SECUNDARIA",
+ "BORDER ARRIVAL": "LLEGADA A LA FRONTERA",
+ "PROPAGATION": "PROPAGACIÓN",
+ "DOWNSTREAM PASSAGE": "PASO AGUAS ABAJO",
+ "CONSEQUENCE": "SECUELAS",
+ "DOWNSTREAM CONSEQUENCE": "SECUELAS AGUAS ABAJO",
+ "EVIDENCE": "EVIDENCIA",
+ "{count} GEOLOCATED SOURCE-MAP PLACEMENTS": {
+ "one": "{count} UBICACIÓN GEOLOCALIZADA EN EL MAPA DE FUENTES",
+ "many": "{count} DE UBICACIONES GEOLOCALIZADAS EN EL MAPA DE FUENTES",
+ "other": "{count} UBICACIONES GEOLOCALIZADAS EN EL MAPA DE FUENTES"
+ },
+ "NO PREVIEW": "SIN VISTA PREVIA",
+ "SOURCE LINK": "ENLACE DE LA FUENTE",
+ "{publisher} / OPEN": "{publisher} / ABRIR",
+ "Bhote Koshi flood reconstruction controls": "Controles de la reconstrucción de la inundación del Bhote Koshi",
+ "EVENT RECONSTRUCTION · 26 AUG 2026": "RECONSTRUCCIÓN DEL EVENTO · 26 AGO 2026",
+ "BHOTE KOSHI OUTBURST FLOOD": "INUNDACIÓN POR DESBORDE DEL BHOTE KOSHI",
+ "Close event layer": "Cerrar la capa del evento",
+ "OBSERVED IMAGERY": "IMÁGENES OBSERVADAS",
+ "SCHEMATIC CORRIDOR": "CORREDOR ESQUEMÁTICO",
+ "2021 HISTORICAL REFERENCE / 2026 POST-EVENT": "REF. HISTÓRICA 2021 / POSTERIOR AL EVENTO 2026",
+ "Historical reference and post-event image split": "División entre la imagen de referencia histórica y la posterior al evento",
+ "RECONSTRUCTION CLOCK": "RELOJ DE LA RECONSTRUCCIÓN",
+ "Schematic downstream progression": "Avance esquemático aguas abajo",
+ "Story beat navigation": "Navegación por momentos del relato",
+ "Previous story beat": "Momento anterior del relato",
+ "CAUSE": "CAUSA",
+ "CAPTURE TIME UNVERIFIED": "HORA DE CAPTURA SIN VERIFICAR",
+ "Next story beat": "Siguiente momento del relato",
+ "▶ PLAY": "▶ REPRODUCIR",
+ "Play the next shot and continue through this scene": "Reproducir el siguiente plano y continuar con esta escena",
+ "▶ PLAY SCENE": "▶ REPRODUCIR ESCENA",
+ "◉ CINEMATIC": "◉ CINEMÁTICA",
+ "↺ FULL STORY": "↺ HISTORIA COMPLETA",
+ "↗ OPEN ORIGINAL": "↗ ABRIR ORIGINAL",
+ "⌖ LOWER GORGE": "⌖ GARGANTA INFERIOR",
+ "FIELD REPORTS · {count}": "INFORMES DE CAMPO · {count}",
+ "GEOLOCATIONS · {credit}": "GEOLOCALIZACIONES · {credit}",
+ "↗ OPEN PUBLIC MAP": "↗ ABRIR MAPA PÚBLICO",
+ "Clouds are preserved from the source imagery.": "Las nubes provienen de las imágenes de origen.",
+ "Show the Nepal context callout without a border or country fill": "Muestra la etiqueta de contexto de Nepal sin frontera ni relleno del país",
+ "Introduce Nepal, draw its border, then reveal the Bhote Koshi incident": "Presenta Nepal, dibuja su frontera y luego revela el incidente del Bhote Koshi",
+ "CITIES": "CIUDADES",
+ "Keep the regional incident context and introduce nearby city labels": "Mantiene el contexto regional del incidente y presenta las etiquetas de las ciudades cercanas",
+ "PLACES": "LUGARES",
+ "Introduce the reconstruction scene key places from trigger to downstream": "Presenta los lugares clave de la escena de reconstrucción, desde el desencadenante hasta aguas abajo",
+ "PATH": "RECORRIDO",
+ "Animate the sourced cyan river-centerline route to Trishuli Bazaar": "Anima la ruta cian documentada por el eje del río hasta Trishuli Bazaar",
+ "OVERVIEW": "VISTA GENERAL",
+ "Keep the completed flood path and location labels visible": "Mantiene visibles el recorrido completo de la inundación y las etiquetas de lugares",
+ "RECORD": "REGISTRO",
+ "Reveal the trigger record while making a slow camera approach": "Revela el registro del desencadenante con una aproximación lenta de la cámara",
+ "BHOTE KOSHI FLOOD INCIDENT": "INCIDENTE DE INUNDACIÓN DEL BHOTE KOSHI",
+ "NEPAL · 26 AUG 2026": "NEPAL · 26 AGO 2026",
+ "USGS INITIAL REPORT": "INFORME INICIAL DEL USGS",
+ "26 AUG 2026 · 08:37 NPT": "26 AGO 2026 · 08:37 NPT",
+ "28.2710° N · 85.5150° E": "28,2710° N · 85,5150° E",
+ "INITIAL M4.4 · RECLASSIFIED M5.2 LANDSLIDE": "INICIAL M4,4 · RECLASIFICADO COMO DESLIZAMIENTO M5,2",
+ "USGS EVENT us7000tbwb · OPEN SOURCE": "EVENTO USGS us7000tbwb · ABRIR FUENTE",
+ "flight": "vuelo",
+ "military flight": "vuelo militar",
+ "satellite": "satélite",
+ "VOICE AUTH · CHATGPT OAUTH": "AUTENTICACIÓN DE VOZ · OAUTH DE CHATGPT",
+ "VOICE AUTH · API KEY": "AUTENTICACIÓN DE VOZ · CLAVE DE API",
+ "USE API KEY": "USAR CLAVE DE API",
+ "USE CHATGPT OAUTH": "USAR OAUTH DE CHATGPT",
+ "Use OPENAI_API_KEY for the next cloud voice session": "Usar OPENAI_API_KEY en la próxima sesión de voz en la nube",
+ "Use the signed-in local ChatGPT/Codex OAuth session for the next cloud voice session": "Usar la sesión OAuth local de ChatGPT/Codex ya iniciada en la próxima sesión de voz en la nube",
+ "Metered — a billing-enabled account": "De pago por uso — una cuenta con facturación activada",
+ "Free key — register, paste, done": "Clave gratuita — regístrate, pégala y listo",
+ "browser-side": "en el navegador",
+ "This key runs in the browser by design — restrict it at the provider (see SECURITY.md)": "Esta clave funciona en el navegador por diseño — restríngela en el proveedor (consulta SECURITY.md)",
+ "configured externally": "configurada externamente",
+ "Supplied by your environment, Keychain, or launcher — change it where it was set": "Proporcionada por tu entorno, Keychain o el lanzador — cámbiala donde se definió",
+ "MANAGE ↗": "GESTIONAR ↗",
+ "GET KEY ↗": "OBTENER CLAVE ↗",
+ "{envVar} saved — paste to replace": "{envVar} guardada — pega otra para reemplazarla",
+ "paste {envVar}": "pega {envVar}",
+ "Project keys: {status}": "Claves del proyecto: {status}",
+ "Mapped camera locations": "Ubicaciones de cámaras mapeadas",
+ "SHOW NEAREST": "MOSTRAR LA MÁS CERCANA",
+ "Stop following the current object before navigating to a camera": "Deja de seguir el objeto actual antes de ir a una cámara",
+ "Move to the nearest loaded camera and show its details": "Ir a la cámara cargada más cercana y mostrar sus detalles",
+ "Camera badges": "Iconos de cámaras",
+ "Cyan cameras turn coral when selected. Wedges illustrate mapped direction, not measured coverage. Nearby cameras may be outside the screen.": "Las cámaras cian se vuelven coral al seleccionarlas. Las cuñas ilustran la dirección mapeada, no la cobertura medida. Las cámaras cercanas pueden estar fuera de la pantalla.",
+ "{count} nearby · {onScreen} on screen": {
+ "one": "{count} cercana · {onScreen} en pantalla",
+ "many": "{count} de cámaras cercanas · {onScreen} en pantalla",
+ "other": "{count} cercanas · {onScreen} en pantalla"
+ },
+ "{count} nearby": {
+ "one": "{count} cercana",
+ "many": "{count} de cámaras cercanas",
+ "other": "{count} cercanas"
+ },
+ "retrying mapped ALPR cameras": "reintentando cámaras ALPR mapeadas",
+ "loading mapped ALPR cameras": "cargando cámaras ALPR mapeadas",
+ "No ALPR data for this area — US and Canada only": "Sin datos ALPR para esta zona — solo EE. UU. y Canadá",
+ "Zoom in to load mapped cameras": "Acércate para cargar las cámaras mapeadas",
+ "Showing cached locations": "Mostrando ubicaciones en caché",
+ "Coverage limited — zoom in": "Cobertura limitada: acércate",
+ "No ALPR data for this area": "Sin datos ALPR para esta zona",
+ "None on screen — nearby cameras are outside the view": "Ninguna en pantalla — las cámaras cercanas están fuera de la vista",
+ "ALPR camera": "Cámara ALPR",
+ "OpenStreetMap · community mapped": "OpenStreetMap · mapeado por la comunidad",
+ "Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "Atlántico y Pacífico Norte oriental/central; no es una cobertura mundial de ciclones.",
+ "Potential tropical cyclone": "Posible ciclón tropical",
+ "Hurricane": "Huracán",
+ "Tropical storm": "Tormenta tropical",
+ "Tropical depression": "Depresión tropical",
+ "Subtropical storm": "Tormenta subtropical",
+ "Subtropical depression": "Depresión subtropical",
+ "Track and cone match this advisory": "La trayectoria y el cono coinciden con este aviso",
+ "Track/cone awaiting advisory {number}": "Trayectoria/cono a la espera del aviso {number}",
+ "Track/cone unavailable": "Trayectoria/cono no disponible",
+ "Cached advisory · stale source": "Aviso en caché · fuente desactualizada",
+ "Loading advisories…": "Cargando avisos…",
+ "{count} active storms": {
+ "one": "{count} ciclón activo",
+ "many": "{count} de ciclones activos",
+ "other": "{count} ciclones activos"
+ },
+ "Position as of {time}": "Posición a las {time}",
+ "Maximum sustained wind: {wind} · Pressure: {pressure}": "Viento máximo sostenido: {wind} · Presión: {pressure}",
+ "{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · Aviso {number} · emitido {time}",
+ "No active NHC/CPHC systems": "Sin sistemas activos del NHC/CPHC",
+ "Advisories unavailable": "Avisos no disponibles",
+ "Cyclones · NHC / CPHC": "Ciclones · NHC / CPHC",
+ "Atlantic · E/C Pacific": "Atlántico · Pacífico E/C",
+ "{storms} · {name} selected": "{storms} · {name} seleccionado",
+ "Official advisory ↗": "Aviso oficial ↗",
+ "Active NHC and CPHC cyclone advisories": "Avisos de ciclones activos del NHC y el CPHC",
+ "Wind unavailable": "Viento no disponible",
+ "Advisory center / forecast track": "Centro del ciclón según el aviso / trayectoria pronosticada",
+ "Center-track uncertainty cone": "Cono de incertidumbre de la trayectoria del centro",
+ "Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "Selecciona un ciclón en el mapa, o elige uno en la lista para seleccionarlo y mover la cámara. Haz clic en un espacio vacío del mapa para borrar la selección. Contexto de avisos NOAA NHC/CPHC. El cono describe la incertidumbre de la trayectoria pronosticada del centro, no el tamaño del ciclón ni toda el área de peligro. Las etiquetas de los puntos de pronóstico son horas de anticipación de la fuente, no horas calculadas a partir de la emisión del aviso. La geometría sigue la superficie; la altura no es altitud meteorológica. Consulta el aviso oficial.",
+ "Directions": "Indicaciones",
+ "{mode} — reroute for {modeLower}": "{mode} — recalcular la ruta {modeLower}",
+ "CLICK MAP": "CLIC EN EL MAPA",
+ "SET A": "FIJAR A",
+ "Click a spot on the globe to place A (click again to cancel)": "Haz clic en un punto del globo para colocar A (vuelve a hacer clic para cancelar)",
+ "Then click the globe to place the start": "Luego haz clic en el globo para colocar el inicio",
+ "SET B": "FIJAR B",
+ "Click a spot on the globe to place B (click again to cancel)": "Haz clic en un punto del globo para colocar B (vuelve a hacer clic para cancelar)",
+ "Then click the globe to place the destination": "Luego haz clic en el globo para colocar el destino",
+ "Swap A and B": "Intercambiar A y B",
+ "FLY ···": "VOLAR ···",
+ "FLYING": "VOLANDO",
+ "FLY": "VOLAR",
+ "Fly the camera along the route": "Volar con la cámara a lo largo de la ruta",
+ "Place A and B first": "Coloca primero A y B",
+ "Remove the route and both markers": "Eliminar la ruta y ambos marcadores",
+ "press Escape twice to leave Draw": "pulsa Esc dos veces para salir de Dibujo",
+ "{name} is active — turn {name} off, then set {endpoint}": "{name} está activo — desactiva {name} y luego fija {endpoint}",
+ "{name} is active — {leave}, then set {endpoint}": "{name} está activo — {leave} y luego fija {endpoint}",
+ "Only the first {count} turns of this route are shown": "Solo se muestran los primeros {count} giros de esta ruta",
+ "Turn-by-turn directions": "Indicaciones paso a paso",
+ "OSM routing": "Rutas de OSM",
+ "DRIVE": "COCHE",
+ "Drive": "En coche",
+ "Another map tool is using clicks — close it, then SET A again": "Otra herramienta del mapa está usando los clics — ciérrala y vuelve a pulsar FIJAR A",
+ "WALK": "A PIE",
+ "Walk": "A pie",
+ "Routing…": "Calculando ruta…",
+ "BIKE": "BICI",
+ "Bike": "En bici",
+ "No route found": "No se encontró ninguna ruta",
+ "{distance} · {duration} · {mode} · first {count} turns": "{distance} · {duration} · {mode} · primeros {count} giros",
+ "{distance} · {duration} · {mode}": "{distance} · {duration} · {mode}",
+ "Click the globe to place {endpoint}": "Haz clic en el globo para colocar {endpoint}",
+ "SET B, then click the globe": "Pulsa FIJAR B y luego haz clic en el globo",
+ "SET A, then click the globe": "Pulsa FIJAR A y luego haz clic en el globo",
+ "Step {step} of {total} · then {leg}": "Paso {step} de {total} · luego {leg}",
+ "Step {step} of {total}": "Paso {step} de {total}",
+ "Then: {instruction}": "Luego: {instruction}",
+ "No route found between A and B": "No se encontró ninguna ruta entre A y B",
+ "Routing failed: {error}": "Falló el cálculo de la ruta: {error}",
+ "Routing timed out": "El cálculo de la ruta agotó el tiempo de espera",
+ "Routing unavailable — no response from the routing service": "Rutas no disponibles — sin respuesta del servicio de rutas",
+ "Routing unavailable": "Rutas no disponibles",
+ "Fire · FRP {frp} MW": "Incendio · FRP {frp} MW",
+ "Not contained or unknown": "Sin contener o desconocido",
+ "Under 50% contained": "Contenido por debajo del 50%",
+ "50–99% contained": "Contenido al 50–99%",
+ "Fully contained": "Totalmente contenido",
+ "Colour shows reported containment. Perimeters are simplified to about 100 m.": "El color indica la contención notificada. Los perímetros se simplifican a unos 100 m.",
+ "MORE DETAIL · 30 m": "MÁS DETALLE · 30 m",
+ "Sentinel-2 and Landsat via HLS, 30 m, every 2–6 days": "Sentinel‑2 y Landsat vía HLS, 30 m, cada 2–6 días",
+ "DAILY OVERVIEW · 250 m": "VISTA GENERAL DIARIA · 250 m",
+ "VIIRS daily mosaic, 250 m, follows broad changes; little detail under 25 km": "Mosaico diario de VIIRS, 250 m, sigue los cambios amplios; poco detalle por debajo de 25 km",
+ "Catalog truncated · a newer clear day may exist": "Catálogo truncado · puede existir un día despejado más reciente",
+ "{label} catalog unavailable · {detail}": "Catálogo de {label} no disponible · {detail}",
+ "Daily overview for today may still be empty until the pass": "La vista general diaria de hoy puede seguir vacía hasta el paso del satélite",
+ "Sentinel-2": "Sentinel‑2",
+ "Landsat 8/9": "Landsat 8/9",
+ "Daily overview": "Vista general diaria",
+ "No frame within {gap} min of {time}": "Sin fotograma a ±{gap} min de {time}",
+ "No frame within {gap} h of {time}": "Sin fotograma a ±{gap} h de {time}",
+ "{hours}h {minutes}m ago": "hace {hours} h {minutes} min",
+ "{minutes}m ago": "hace {minutes} min",
+ "{state} · {time} · {lag}": "{state} · {time} · {lag}",
+ "Observed": "Observado",
+ "History": "Historial",
+ "Observation unavailable": "Observación no disponible",
+ "Waiting for observation": "Esperando observación",
+ "{detail} · synced": "{detail} · sincr.",
+ "{detail} · nearest": "{detail} · más cercano",
+ "RADAR REFLECTIVITY · dBZ": "REFLECTIVIDAD DE RADAR · dBZ",
+ "LIGHTNING DENSITY · 15 min accumulation": "DENSIDAD DE RAYOS · acumulación de 15 min",
+ "GLOBAL INFRARED · hourly": "INFRARROJO GLOBAL · cada hora",
+ "GOES INFRARED · ~5 min": "INFRARROJO GOES · ~5 min",
+ "{state}: {time}": "{state}: {time}",
+ "Latest observation": "Última observación",
+ "frame {index}/{total}": "fotograma {index}/{total}",
+ "loading": "cargando",
+ "Observation: unavailable": "Observación: no disponible",
+ "Contiguous US · gaps ≠ no rain": "EE. UU. contiguos · huecos ≠ sin lluvia",
+ "Americas + Pacific · not individual strikes": "América + Pacífico · no son rayos individuales",
+ "Color: strikes/km²/min ×10³": "Color: rayos/km²/min ×10³",
+ "60°S–60°N · typically 2–3 h delayed": "60°S–60°N · normalmente con 2–3 h de retraso",
+ "North America · infrared imagery": "Norteamérica · imágenes infrarrojas",
+ "Reduced motion · history playback unavailable": "Movimiento reducido · reproducción del historial no disponible",
+ "Reduced motion · manual history available": "Movimiento reducido · puedes recorrer el historial a mano",
+ "Rain radar · US": "Radar de lluvia · EE. UU.",
+ "Lightning density · 15 min": "Densidad de rayos · 15 min",
+ "Satellite clouds": "Nubes por satélite",
+ "Americas + Pacific": "América + Pacífico",
+ "Global · 60°S–60°N": "Global · 60°S–60°N",
+ "North America": "Norteamérica",
+ "Source observations delayed": "Observaciones de la fuente con retraso",
+ "Stale source": "Fuente desactualizada",
+ "Loading next frame…": "Cargando el siguiente fotograma…",
+ "Map center outside coverage": "Centro del mapa fuera de cobertura",
+ "strikes/km²/min ×10³": "rayos/km²/min ×10³",
+ "N. America": "Norteamérica",
+ "Global": "Global",
+ "Hourly global mosaic; usually 2–3 hours delayed": "Mosaico global horario; normalmente con 2–3 horas de retraso",
+ "GOES regional clouds; approximately 5-minute updates": "Nubes regionales de GOES; actualizaciones cada 5 minutos aproximadamente",
+ "Clouds only": "Solo nubes",
+ "Full": "Completa",
+ "Soft": "Suave",
+ "Vivid": "Intensa",
+ "Image opacity; does not alter the observed values": "Opacidad de la imagen; no altera los valores observados",
+ "View US radar": "Ver radar de EE. UU.",
+ "View Americas & Pacific": "Ver América y Pacífico",
+ "View coverage": "Ver cobertura",
+ "{value} strikes/km²/min ×10³ (15-minute density)": "{value} rayos/km²/min ×10³ (densidad de 15 minutos)",
+ "{value} dBZ radar reflectivity": "{value} dBZ de reflectividad de radar",
+ "STALE · cached source metadata": "DESACTUALIZADO · metadatos de la fuente en caché",
+ "Map center is outside source coverage": "El centro del mapa está fuera de la cobertura de la fuente",
+ "NOAA/NWS 15-minute lightning density derived from Vaisala NLDN/GLD360. Coverage 110°E across the Pacific/Americas to 0°, 25°S–80°N. Not a live strike count, global coverage or a safety warning.": "Densidad de rayos de 15 minutos de NOAA/NWS derivada de Vaisala NLDN/GLD360. Cobertura desde 110°E, a través del Pacífico/América, hasta 0°, 25°S–80°N. No es un recuento de rayos en vivo, ni una cobertura global, ni un aviso de seguridad.",
+ "NOAA MRMS radar echoes indicate precipitation patterns, not rain rate, a storm warning or a future forecast. Native source approximately 1 km; display is limited to level 6. Frames use exact advertised observation times.": "Los ecos de radar NOAA MRMS indican patrones de precipitación, no la intensidad de lluvia, ni un aviso de tormenta, ni un pronóstico futuro. Fuente nativa de aproximadamente 1 km; la visualización se limita al nivel 6. Los fotogramas usan las horas de observación exactas anunciadas.",
+ "GOES-19/18 longwave infrared Band 14 regional; NESDIS global longwave mosaic. Clouds only dims everything but bright, cold cloud tops; a brightness filter, not a cloud mask. Coverage and freshness differ by region.": "Infrarrojo de onda larga GOES-19/18, banda 14, regional; mosaico global de onda larga de NESDIS. Solo nubes atenúa todo excepto las cimas de nubes brillantes y frías; un filtro de brillo, no una máscara de nubes. La cobertura y la actualidad varían según la región.",
+ "REGION": "REGIÓN",
+ "IMAGE": "IMAGEN",
+ "OPACITY": "OPACIDAD",
+ "Forecast · does not follow history": "Pronóstico · no sigue el historial",
+ "Wind motion": "Movimiento del viento",
+ "Wind speed": "Velocidad del viento",
+ "Sea-level pressure": "Presión a nivel del mar",
+ "Air temperature · 2 m": "Temperatura del aire · 2 m",
+ "Global · 1° grid": "Global · cuadrícula de 1°",
+ "{model} forecast · {time}": "Pronóstico {model} · {time}",
+ "Loading forecast": "Cargando pronóstico",
+ "Preparing flow": "Preparando flujo",
+ "Selected field unavailable": "Campo seleccionado no disponible",
+ "Cached forecast · stale": "Pronóstico en caché · desactualizado",
+ "ECMWF IFS surface forecast": "Pronóstico de superficie ECMWF IFS",
+ "NOAA GFS surface forecast": "Pronóstico de superficie NOAA GFS",
+ "Reduced motion": "Movimiento reducido",
+ "Pause visual flow; forecast time does not advance with animation": "Pausa el flujo visual; la hora del pronóstico no avanza con la animación",
+ "None": "Ninguno",
+ "Speed": "Velocidad",
+ "Pressure": "Presión",
+ "Temperature": "Temperatura",
+ "Wind trails with no field shading": "Trazas de viento sin sombreado del campo",
+ "How hard the surface wind is blowing": "Con qué fuerza sopla el viento en superficie",
+ "Sea-level air pressure: broad highs and lows": "Presión del aire a nivel del mar: altas y bajas amplias",
+ "Air temperature two meters above the surface": "Temperatura del aire a dos metros sobre la superficie",
+ "Wind speed units": "Unidades de velocidad del viento",
+ "Read wind at map center": "Leer el viento en el centro del mapa",
+ "Read the forecast at the center of the map without changing selection": "Leer el pronóstico en el centro del mapa sin cambiar la selección",
+ "{model} forecast · {field} ({unit})": "Pronóstico {model} · {field} ({unit})",
+ "Valid: {time}": "Válido: {time}",
+ "preparing": "preparando",
+ "Issued: {time}": "Emitido: {time}",
+ "Selected field unavailable · wind remains visible": "Campo seleccionado no disponible · el viento sigue visible",
+ "{error} · wind remains visible": "{error} · el viento sigue visible",
+ "Surface wind at 10 m. Approximately 1° global grid. Curves follow the 10 m wind field, lifted 12 km for visibility; display height is not weather altitude. View lighting is for readability. Animation shows flow through one fixed forecast; it does not advance time. Color fields drape the globe basemap or the active photorealistic 3D Tiles.": "Viento en superficie a 10 m. Cuadrícula global de aproximadamente 1°. Las curvas siguen el campo de viento a 10 m, elevadas 12 km para que sean visibles; la altura mostrada no es altitud meteorológica. La iluminación de la vista es para facilitar la lectura. La animación muestra el flujo de un único pronóstico fijo; no avanza el tiempo. Los campos de color cubren el mapa base del globo o las 3D Tiles fotorrealistas activas.",
+ "MODEL": "MODELO",
+ "FIELD": "CAMPO",
+ "UNITS": "UNIDADES",
+ "MOTION": "MOVIMIENTO",
+ "Forecast": "Pronóstico",
+ "Interpolated model forecast on an approximately 1° grid. Broad weather patterns, not a street-level measurement.": "Pronóstico de modelo interpolado en una cuadrícula de aproximadamente 1°. Patrones meteorológicos generales, no una medición a pie de calle.",
+ "No surface reading": "Sin lectura en superficie",
+ "Aim the map center at Earth": "Apunta el centro del mapa a la Tierra",
+ " · calm": " · calma",
+ " from {direction}": " del {direction}",
+ "WIND AT {coordinates}": "VIENTO EN {coordinates}",
+ "{model} · valid {time}": "{model} · válido {time}",
+ "Focusing {label}": "Enfocando {label}",
+ "Source": "Fuente",
+ "Could not leave scene: {scene}": "No se pudo salir de la escena: {scene}",
+ "Seeked: {scene} / {shot}": "Saltado a: {scene} / {shot}",
+ "Scene transition limit reached — load a shot to reset": "Límite de transiciones de escena alcanzado — carga un plano para restablecer",
+ "Export failed: {error}": "La exportación falló: {error}",
+ "Imported {file}": "Importado: {file}",
+ "Import failed: {error}": "La importación falló: {error}",
+ "Import failed (could not read JSON file)": "La importación falló (no se pudo leer el archivo JSON)",
+ "Layers refused: {layers}": "Capas rechazadas: {layers}",
+ "Scene {n}": "Escena {n}",
+ "Cannot update {scene}: shot inventory changed": "No se puede actualizar {scene}: el inventario de planos cambió",
+ "Cannot update {scene}: evidence beats changed": "No se puede actualizar {scene}: los momentos de evidencia cambiaron",
+ "Cannot update {scene}: shot bindings are incomplete": "No se puede actualizar {scene}: los vínculos de los planos están incompletos",
+ "Updated {count} shots: {scene}": {
+ "one": "{count} plano actualizado: {scene}",
+ "many": "{count} de planos actualizados: {scene}",
+ "other": "{count} planos actualizados: {scene}"
+ },
+ "Appended {count} shots: {scene}": {
+ "one": "{count} plano añadido: {scene}",
+ "many": "{count} de planos añadidos: {scene}",
+ "other": "{count} planos añadidos: {scene}"
+ },
+ "Select a feature or use Tab and Enter to choose an action.": "Selecciona un elemento o usa Tab y Enter para elegir una acción.",
+ "Selected feature: {feature}. Choose an action.": "Elemento seleccionado: {feature}. Elige una acción.",
+ "Action complete": "Acción completada",
+ "Action unavailable or cancelled": "Acción no disponible o cancelada",
+ "Scene actions": "Acciones de escena",
+ "Bhote Koshi Evidence Sequence": "Secuencia de evidencia del Bhote Koshi",
+ "Nepal Flood Incident": "Incidente de inundación en Nepal",
+ "{count} scenes": {
+ "one": "{count} escena",
+ "many": "{count} de escenas",
+ "other": "{count} escenas"
+ },
+ "{count} shots": {
+ "one": "{count} plano",
+ "many": "{count} de planos",
+ "other": "{count} planos"
+ },
+ "{count} data packs": {
+ "one": "{count} paquete de datos",
+ "many": "{count} de paquetes de datos",
+ "other": "{count} paquetes de datos"
+ },
+ "{scene} / {pack}: {status}. File: {path}. {attribution} · {license}": "{scene} / {pack}: {status}. Archivo: {path}. {attribution} · {license}",
+ "Unavailable layers: {layers}": "Capas no disponibles: {layers}",
+ "{bytes} bundled bytes verified. Files stay in memory for this session. Reimport the bundle after reloading the app.": "{bytes} bytes empaquetados verificados. Los archivos permanecen en memoria durante esta sesión. Vuelve a importar el paquete después de recargar la app.",
+ "Review scene import": "Revisar la importación de escena",
+ "Nothing is loaded or changed until you apply this file.": "No se carga ni se cambia nada hasta que apliques este archivo.",
+ "Ready to import": "Listo para importar",
+ "Apply replaces the current project. Export your current project first if you want to keep both.": "Aplicar reemplaza el proyecto actual. Exporta primero tu proyecto actual si quieres conservar ambos.",
+ "Apply import": "Aplicar importación",
+ "Import was not applied. The current project may have changed.": "La importación no se aplicó. Es posible que el proyecto actual haya cambiado.",
+ "Select a scene and shot first": "Selecciona primero una escena y un plano",
+ "Edit scene details": "Editar los detalles de la escena",
+ "Camera positions use degrees and meters above the ellipsoid. Drafts are validated before they replace your saved scene.": "Las posiciones de cámara usan grados y metros sobre el elipsoide. Los borradores se validan antes de reemplazar tu escena guardada.",
+ "Anchors and data packs": "Anclas y paquetes de datos",
+ "Shot camera, timing, packs and actions": "Cámara, tiempos, paquetes y acciones del plano",
+ "New anchor ID": "ID del ancla nueva",
+ "Capture camera as anchor": "Capturar la cámara como ancla",
+ "Anchor added to draft": "Ancla añadida al borrador",
+ "Set move start to current camera": "Fijar el inicio del movimiento en la cámara actual",
+ "Move added to draft; destination remains the shot camera": "Movimiento añadido al borrador; el destino sigue siendo la cámara del plano",
+ "Use ordinary flight": "Usar vuelo normal",
+ "Invalid shot JSON": "JSON de plano no válido",
+ "Apply details": "Aplicar detalles",
+ "Select a scene first": "Selecciona primero una escena",
+ "Share selected scene": "Compartir la escena seleccionada",
+ "Scene JSON preserves authored settings and attribution. It does not include asset files. Bundles include only pack files you choose here or previously imported bundle files.": "El JSON de escena conserva los ajustes definidos por el autor y la atribución. No incluye archivos de recursos. Los paquetes de escena solo incluyen los archivos de paquetes de datos que elijas aquí o los que se importaron antes.",
+ "Download scene JSON": "Descargar JSON de escena",
+ "Choose data-pack files": "Elegir archivos de paquete de datos",
+ "Or choose a data-pack folder": "O elige una carpeta de paquete de datos",
+ "Download asset bundle": "Descargar paquete de recursos",
+ "Asset bundle downloaded": "Paquete de recursos descargado",
+ "Could not complete this action. Check the file, references and selected assets.": "No se pudo completar esta acción. Revisa el archivo, las referencias y los recursos seleccionados.",
+ "RTL-SDR sample stream stopped": "Flujo de muestras RTL-SDR detenido",
+ "Switching to {mode}…": "Cambiando a {mode}…",
+ "Browser audio is suspended; select FM again to resume it": "El audio del navegador está suspendido; selecciona FM de nuevo para reanudarlo",
+ "RTL-SDR gain change failed": "No se pudo cambiar la ganancia del RTL-SDR",
+ "Tuned to {mhz} MHz FM": "Sintonizado en {mhz} MHz FM",
+ "FM signal found at {mhz} MHz": "Señal FM encontrada en {mhz} MHz",
+ "No FM signal found": "No se encontró ninguna señal FM",
+ "Seek stopped": "Búsqueda detenida",
+ "Browser location is unavailable": "La ubicación del navegador no está disponible",
+ "Receiver location was not granted": "No se concedió permiso para la ubicación del receptor",
+ "RTL-SDR disconnected": "RTL-SDR desconectado",
+ "No RTL-SDR device selected": "No hay ningún dispositivo RTL-SDR seleccionado",
+ "WebUSB requires desktop Chrome or Edge on localhost/HTTPS": "WebUSB requiere Chrome o Edge de escritorio en localhost/HTTPS",
+ "RTL-SDR access failed; close other SDR apps and check USB permissions": "No se pudo acceder al RTL-SDR; cierra otras apps de SDR y revisa los permisos USB",
+ "RTL-SDR connection failed": "La conexión con el RTL-SDR falló",
+ "Receiving 1090 MHz ADS-B": "Recibiendo ADS-B en 1090 MHz",
+ "Receiving broadcast FM": "Recibiendo FM de radiodifusión",
+ "Connect an RTL-SDR to begin.": "Conecta un RTL-SDR para empezar.",
+ "WebUSB is unavailable in this browser": "WebUSB no está disponible en este navegador",
+ "SDR decoder worker failed": "Falló el proceso del decodificador SDR",
+ "WebUSB requires desktop Chrome or Edge": "WebUSB requiere Chrome o Edge de escritorio",
+ "Waiting for an RTL-SDR device…": "Esperando un dispositivo RTL-SDR…",
+ "Browser audio is suspended; press Connect again to resume it": "El audio del navegador está suspendido; pulsa Conectar de nuevo para reanudarlo",
+ "Return map to straight-down view": "Volver el mapa a la vista cenital",
+ "Tilt map to oblique view": "Inclinar el mapa a una vista oblicua",
+ "Reset map to north up. Current heading {heading} degrees": "Orientar el mapa al norte. Rumbo actual: {heading} grados",
+ "HDG": "HDG",
+ "PITCH": "INCL.",
+ "FOV": "FOV",
+ "RANGE": "RANGE",
+ "HGT": "ALT.",
+ "{value} KM/H": "{value} KM/H",
+ "NORMAL": "NORMAL",
+ "ANIME": "ANIME",
+ "NOIR": "NOIR",
+ "Rendered globe frames per second · toggle with `": "Fotogramas por segundo renderizados del globo · alterna con `",
+ "Utilities": "Utilidades",
+ "Other layers": "Otras capas",
+ "Movement": "Movimiento",
+ "Infrastructure": "Infraestructura",
+ "Events": "Eventos",
+ "Weather": "Clima",
+ "LOCATED": "UBICADO",
+ "LOCATE": "UBICAR",
+ "IDLE": "EN ESPERA",
+ "TUNING": "SINTONIZANDO",
+ "STREAMING": "RECIBIENDO",
+ "UNSUPPORTED": "NO COMPATIBLE",
+ "waiting for IQ": "esperando IQ",
+ "{count} messages": {
+ "one": "{count} mensaje",
+ "many": "{count} de mensajes",
+ "other": "{count} mensajes"
+ },
+ "DSP {count} blocks": {
+ "one": "DSP {count} bloque",
+ "many": "DSP {count} de bloques",
+ "other": "DSP {count} bloques"
+ },
+ "DSP waiting": "DSP en espera",
+ "{level} dBFS audio": "audio {level} dBFS",
+ "audio signal --": "señal de audio --",
+ "audio {state}": "audio {state}",
+ "{count} HEARD": {
+ "one": "CAPTADAS: {count}",
+ "many": "CAPTADAS: {count}",
+ "other": "CAPTADAS: {count}"
+ },
+ "DISCONNECT": "DESCONECTAR",
+ "CONNECT": "CONECTAR",
+ "LOCATING…": "UBICANDO…",
+ "Drag to resize · double-click the header to snap back": "Arrastra para cambiar el tamaño · doble clic en el encabezado para restaurarlo",
+ "CH {index} / {total}": "CANAL {index} / {total}",
+ "Station unavailable after directory refresh": "Emisora no disponible tras actualizar el directorio",
+ "Clear reading": "Borrar lectura",
+ "Earlier observation": "Observación anterior",
+ "Observed history": "Historial observado",
+ "Later observation": "Observación posterior",
+ "Latest": "Último",
+ "Newest frame per product": "Fotograma más reciente por producto",
+ "Replay observed history": "Reproducir el historial observado",
+ "S on another day replaces it · × unpins": "S en otro día lo reemplaza · × quita la fijación",
+ "← → preview · S shows the focused day": "← → vista previa · S muestra el día enfocado",
+ "Recent imagery": "Imágenes recientes",
+ "ZOOM IN": "ACERCAR",
+ "Fly in until the view fits the 1,000 km limit": "Acércate hasta que la vista quepa en el límite de 1000 km",
+ "Imagery days, newest first · arrows move, S or A and B pin": "Días de imágenes, el más reciente primero · las flechas mueven, S o A y B fijan",
+ "On the map": "En el mapa",
+ "Mode": "Modo",
+ "Imagery on Esri · Google 3D returns when cleared": "Imágenes sobre Esri · BORRAR restaura Google 3D",
+ "Imagery opacity": "Opacidad de las imágenes",
+ "SWAP": "INVERTIR",
+ "VS BASEMAP": "VS MAPA BASE",
+ "Trade the two sides of the divider": "Intercambiar los dos lados del divisor",
+ "A / B": "A / B",
+ "Newest low-cloud day for this box · scene cloud, not box cloud": "Día más reciente con pocas nubes para este recuadro · nubes de la escena, no del recuadro",
+ "Newest day covering this box · cloudier than 20%": "Día más reciente que cubre este recuadro · más de un 20% de nubes",
+ "SELECT BOX": "SELECCIONAR",
+ "Drag a box on the map (Esc cancels)": "Arrastra un recuadro en el mapa (Esc cancela)",
+ "Newest day with imagery for this box · partial coverage": "Día más reciente con imágenes para este recuadro · cobertura parcial",
+ "USE VIEW": "USAR VISTA",
+ "Use the current view as the box": "Usar la vista actual como recuadro",
+ "Newest daily overview for this box": "Vista general diaria más reciente para este recuadro",
+ "Forget the box and its images": "Olvidar el recuadro y sus imágenes",
+ "newest clear day": "día despejado más reciente",
+ "newest day (cloudy)": "día más reciente (nublado)",
+ "newest day (partial coverage)": "día más reciente (cobertura parcial)",
+ "START HERE": "EMPIEZA AQUÍ",
+ "newest overview": "vista general más reciente",
+ "No imagery": "Sin imágenes",
+ "Checking": "Comprobando",
+ "Loading": "Cargando",
+ "PREVIEW": "VISTA PREVIA",
+ "Newest day with imagery for this box": "Día más reciente con imágenes para este recuadro",
+ "SHOW": "MOSTRAR",
+ "Pin {day} as {slot}": "Fijar {day} como {slot}",
+ "Show {day}": "Mostrar {day}",
+ "pinned {slot}": "fijado en {slot}",
+ "shown": "mostrado",
+ "preview": "vista previa",
+ "start here": "empieza aquí",
+ "No box": "Sin recuadro",
+ "Searching": "Buscando",
+ "Every day is empty here": "Todos los días están vacíos aquí",
+ "Sources off": "Fuentes desactivadas",
+ "VS": "VS",
+ "Not set": "Sin definir",
+ "Basemap": "Mapa base",
+ "Source off": "Fuente desactivada",
+ "Unpin {slot}": "Quitar {slot}",
+ "Unpin the image": "Quitar la imagen fijada",
+ "EXPORT {slot}": "EXP. {slot}",
+ "EXPORT": "EXPORTAR",
+ "Download {slot} as a PNG": "Descargar {slot} como PNG",
+ "Download the image as a PNG": "Descargar la imagen como PNG",
+ "Box {width} × {height} km": "Recuadro de {width} × {height} km",
+ "no imagery": "sin imágenes",
+ "Acquired {time}": "Adquirida {time}",
+ "cloud unknown": "nubosidad desconocida",
+ "Coverage {coverage}": "Cobertura {coverage}",
+ "unknown": "desconocida",
+ "START HERE · {reason}": "EMPIEZA AQUÍ · {reason}",
+ "Daily overview shows little detail in a box this small": "La vista general diaria muestra poco detalle en un recuadro tan pequeño",
+ "{percent}% cloud": "{percent}% de nubes",
+ "Imagery: NASA GIBS and Worldview · HLS (Sentinel-2, Landsat 8/9) and VIIRS": "Imágenes: NASA GIBS y Worldview · HLS (Sentinel‑2, Landsat 8/9) y VIIRS",
+ "{min}–{max}% cloud": "{min}–{max}% de nubes",
+ "Details": "Detalles",
+ "Times, coverage, sources": "Horas, cobertura, fuentes",
+ "HIDE EMPTY DAYS": "OCULTAR DÍAS VACÍOS",
+ "SHOW EMPTY DAYS · {count}": "MOSTRAR DÍAS VACÍOS · {count}",
+ "Days the probe found empty in this box": "Días que el sondeo encontró vacíos en este recuadro",
+ "NO BOX": "SIN RECUADRO",
+ "image": "imagen",
+ "BASEMAP": "MAPA BASE",
+ "The basemap": "El mapa base",
+ "basemap": "mapa base",
+ "SEARCHING": "BUSCANDO",
+ "{count} DAYS": {
+ "one": "{count} DÍA",
+ "many": "{count} DE DÍAS",
+ "other": "{count} DÍAS"
+ },
+ "Recent imagery against the basemap divider": "Divisor de imágenes recientes frente al mapa base",
+ "Recent imagery A and B divider": "Divisor A y B de imágenes recientes",
+ "{before} {left} percent, {after} {right} percent": "{before} {left} por ciento, {after} {right} por ciento",
+ "Zoom in or draw a smaller box": "Acércate o dibuja un recuadro más pequeño",
+ "Select a box or use the view": "Selecciona un recuadro o usa la vista",
+ "Searching the last 30 days": "Buscando en los últimos 30 días",
+ "No days to show for this box": "No hay días que mostrar para este recuadro",
+ "Drag the divider · SWAP trades sides": "Arrastra el divisor · INVERTIR cambia los lados",
+ "Export failed · {error}": "La exportación falló · {error}",
+ "← → preview · A or B pins the focused day": "← → vista previa · A o B fija el día enfocado",
+ "← → preview the other side · A or B pins it": "← → vista previa del otro lado · A o B lo fija",
+ "LOAD": "CARGAR",
+ "No shots yet. Use CAPTURE SHOT to save current look.": "Aún no hay planos. Usa CAPTURAR PLANO para guardar el aspecto actual.",
+ "Double-click to rename": "Doble clic para cambiar el nombre",
+ "Shot name": "Nombre del plano",
+ "RETRYING ALPR CAMERAS": "REINTENTANDO CÁMARAS ALPR",
+ "FETCHING ALPR CAMERAS": "OBTENIENDO CÁMARAS ALPR",
+ "OVERPASS TEMPORARILY UNAVAILABLE": "OVERPASS TEMPORALMENTE NO DISPONIBLE",
+ "Weather data by Open-Meteo.com": "Datos meteorológicos de Open-Meteo.com",
+ "ESC EXIT": "ESC SALIR",
+ "C TOGGLE": "C ALTERNAR",
+ "SIG": "SIG",
+ "NEWS": "NOTICIAS",
+ "LOCAL": "LOCAL",
+ "Cockpit briefing pages": "Páginas de información de la cabina",
+ "MM": "MM",
+ "KTS": "KN",
+ "FT": "FT",
+ "FLT": "FLT",
+ "MIL": "MIL",
+ "SITE": "SITIOS",
+ "WX": "WX",
+ "DIRECTORY: RADIO BROWSER": "DIRECTORIO: RADIO BROWSER",
+ "Use your location for faster ADS-B position decoding": "Usa tu ubicación para decodificar más rápido las posiciones ADS-B",
+ "CHANGE DEVICE": "CAMBIAR",
+ "Choose a different RTL-SDR or receiver channel": "Elige otro RTL-SDR u otro canal del receptor",
+ "TUNE": "SINTONIZAR",
+ "◀ SEEK": "◀ BUSCAR",
+ "SEEK ▶": "BUSCAR ▶",
+ "Local RTL-SDR receiver": "Receptor RTL-SDR local",
+ "RTL-SDR receiver mode": "Modo del receptor RTL-SDR",
+ "Seek broadcast FM stations": "Buscar emisoras de FM",
+ "Tune available internet radio stations": "Sintonizar las emisoras de radio por Internet disponibles",
+ "Local SDR volume": "Volumen del SDR local",
+ "GAIN": "GANANCIA",
+ "FM MHZ": "FM MHZ",
+ "AUTO": "AUTO",
+ "Chrome/Edge · WebUSB · one local tuner shared by FM and the Local ADS-B layer.": "Chrome/Edge · WebUSB · un sintonizador local compartido entre FM y la capa ADS-B local.",
+ "RTL-SDR tuner gain for the current mode": "Ganancia del sintonizador RTL-SDR para el modo actual",
+ "WEATHER": "CLIMA",
+ "Active weather products": "Productos meteorológicos activos",
+ "RECENT IMAGERY": "IMÁGENES RECIENTES",
+ "Imagery days in the box": "Días de imágenes en el recuadro",
+ "MSG/S": "MSG/S",
+ "HEARD": "CAPTADAS",
+ "POSITIONED": "POSICIONADAS",
+ "SDR VOL": "VOL. SDR",
+ "LOCAL RTL-SDR": "RTL-SDR LOCAL",
+ "Cyber sonar contact scanner": "Escáner de contactos del sonar Ciber",
+ "Sonar ring count": "Número de anillos del sonar",
+ "Sonar ring range": "Alcance de los anillos del sonar",
+ "Sonar intensity": "Intensidad del sonar",
+ "Cyber contact and label opacity": "Opacidad de contactos y etiquetas Ciber",
+ "Minimum opacity for map dots, icons, models, brackets, and labels between sonar passes": "Opacidad mínima de puntos, iconos, modelos, corchetes y etiquetas del mapa entre pasadas del sonar",
+ "Sonar sector width": "Ancho del sector del sonar",
+ "Rings": "Anillos",
+ "Range": "Alcance",
+ "Power": "Potencia",
+ "Opacity": "Opacidad",
+ "Sector": "Sector",
+ "Cyber": "Ciber",
+ "Sonar": "Sonar",
+ "Turn Street Level on or off": "Activar o desactivar A pie de calle",
+ "Toggle straight-down and tilted map views": "Alternar entre la vista cenital y la vista inclinada del mapa",
+ "Reset map to north up": "Orientar el mapa al norte",
+ "Reset map bearing to north": "Restablecer la orientación del mapa al norte",
+ "Rain radar": "Radar de lluvia",
+ "Lightning density": "Densidad de rayos",
+ "LATEST · newest per product": "ÚLTIMO · más reciente por producto",
+ "Forecast · valid {valid} · issued {issued}": "Pronóstico · válido {valid} · emitido {issued}",
+ "{detail} · Does not follow history": "{detail} · No sigue el historial",
+ "Forecast · valid {valid}": "Pronóstico · válido {valid}",
+ "{time} · {minutes} min ago": "{time} · hace {minutes} min",
+ "Active weather": "Capas meteorológicas activas",
+ "MINI": "MINI",
+ "STD": "STD",
+ "standard": "estándar",
+ "mini": "mini",
+ "COST UNKNOWN": "COSTO DESCONOCIDO",
+ "ChatGPT OAuth session: {responses} response(s), {input} input and {output} output tokens, {captions} caption transcription(s) reported.": "Sesión OAuth de ChatGPT (datos informados): {responses} respuesta(s), {input} tokens de entrada y {output} de salida, {captions} transcripción(es) de subtítulos.",
+ "USD cost and the API spend cap are unavailable for this auth mode.": "El costo en USD y el límite de gasto de la API no están disponibles con este modo de autenticación.",
+ "Usage is incomplete because a response was still in flight when the session ended.": "El uso está incompleto porque una respuesta seguía en curso cuando terminó la sesión.",
+ "Toggle voice control": "Alternar el control de voz",
+ "Activate to toggle voice": "Pulsa para activar o desactivar la voz",
+ "Voice active": "Voz activa",
+ "Voice could not be started.": "No se pudo iniciar la voz.",
+ "degraded": "degradado",
+ "stale": "desactualizado",
+ "partial": "parcial",
+ "fallback": "respaldo",
+ "unavailable": "no disponible",
+ "{label} on": "{label}: activado",
+ "{label} off": "{label}: desactivado",
+ "Frame aircraft": "Encuadrar aeronaves",
+ "Frame military aircraft": "Encuadrar aeronaves militares",
+ "Frame ships": "Encuadrar buques",
+ "Frame satellites": "Encuadrar satélites",
+ "Frame contacts": "Encuadrar contactos",
+ "{count} aircraft in frame": {
+ "one": "{count} aeronave en el encuadre",
+ "many": "{count} de aeronaves en el encuadre",
+ "other": "{count} aeronaves en el encuadre"
+ },
+ "{count} military aircraft in frame": {
+ "one": "{count} aeronave militar en el encuadre",
+ "many": "{count} de aeronaves militares en el encuadre",
+ "other": "{count} aeronaves militares en el encuadre"
+ },
+ "{count} ships in frame": {
+ "one": "{count} buque en el encuadre",
+ "many": "{count} de buques en el encuadre",
+ "other": "{count} buques en el encuadre"
+ },
+ "{count} satellites in frame": {
+ "one": "{count} satélite en el encuadre",
+ "many": "{count} de satélites en el encuadre",
+ "other": "{count} satélites en el encuadre"
+ },
+ "{count} contacts in frame": {
+ "one": "{count} contacto en el encuadre",
+ "many": "{count} de contactos en el encuadre",
+ "other": "{count} contactos en el encuadre"
+ },
+ "Nearest military aircraft": "Aeronaves militares más cercanas",
+ "Nearest ships": "Buques más cercanos",
+ "Nearest satellites": "Satélites más cercanos",
+ "Nearest aircraft": "Aeronaves más cercanas",
+ "{first} and {second}": "{first} y {second}",
+ "Camera range {range}": "Alcance de la cámara {range}",
+ "Within {radius} of the view": "En un radio de {radius} desde la vista",
+ "Labels on": "Etiquetas activadas",
+ "Framing uses the nearest 80 loaded contacts": "El encuadre usa los 80 contactos cargados más cercanos",
+ "{distance} from {location}": "A {distance} de {location}",
+ "Altitude {altitude}": "Altitud {altitude}",
+ "{origin} to {destination}": "De {origin} a {destination}",
+ "from {origin}": "desde {origin}",
+ "to {destination}": "a {destination}",
+ "Registration {registration}": "Matrícula {registration}",
+ "Route {route}": "Ruta {route}",
+ "View state": "Estado de la vista",
+ "Marked {count} places": {
+ "one": "{count} lugar marcado",
+ "many": "{count} de lugares marcados",
+ "other": "{count} lugares marcados"
+ },
+ "Nothing marked": "Nada marcado",
+ "Not found: {places}": "No encontrado: {places}",
+ "Tracing outlines": "Trazando contornos",
+ "Mark the map": "Marcar el mapa",
+ "Mark {targets} +{more}": "Marcar {targets} +{more}",
+ "Mark {targets}": "Marcar: {targets}",
+ "Fly to {place}": "Volar a {place}",
+ "Nearest aircraft to {place}": "Aeronave más cercana a {place}",
+ "Read the view": "Consultar la vista",
+ "Check view state": "Comprobar el estado de la vista",
+ "Frame {target}": "Encuadrar {target}",
+ "Finding places": "Buscando lugares",
+ "Tracing outline": "Trazando contorno",
+ "Looking up place": "Buscando lugar",
+ "Flying": "Volando",
+ "Turning on layer": "Activando capa",
+ "Loading aircraft": "Cargando aeronaves",
+ "Picking nearest": "Eligiendo la más cercana",
+ "Working": "Procesando",
+ "{value} feet": "{value} pies",
+ "nominal": "nominal",
+ "Source: {label}": "Fuente: {label}",
+ "N": "N",
+ "NNE": "NNE",
+ "NE": "NE",
+ "ENE": "ENE",
+ "E": "E",
+ "ESE": "ESE",
+ "SE": "SE",
+ "SSE": "SSE",
+ "S": "S",
+ "SSW": "SSO",
+ "SW": "SO",
+ "WSW": "OSO",
+ "W": "O",
+ "WNW": "ONO",
+ "NW": "NO",
+ "NNW": "NNO",
+ "Local ADS-B": "ADS-B local",
+ "Transit": "Transporte público",
+ "Recent Imagery": "Imágenes recientes",
+ "Fire Perimeters": "Perímetros de incendios",
+ "Cyclone advisories": "Avisos de ciclones",
+ "EDIT DETAILS": "EDITAR DETALLES",
+ "SHARE SCENE": "COMPARTIR ESCENA",
+ "ON/OFF": "ENC./APAG.",
+ "Voice assistant": "Asistente de voz",
+ "VOICE": "VOZ",
+ "Dismiss voice card": "Cerrar la tarjeta de voz",
+ "YOU": "TÚ",
+ "THIS": "ESTO",
+ "HERE": "AQUÍ",
+ "Plan": "Plan",
+ "Referenced items": "Elementos citados",
+ "NOTES & SOURCES": "NOTAS Y FUENTES",
+ "ΔN": "ΔN",
+ "ΔE": "ΔE",
+ "action|CLEAR": "BORRAR",
+ "ALPR Cameras": "Cámaras ALPR",
+ "Military aircraft": "Aeronaves militares",
+ "Vessels": "Buques",
+ "CCTV + Street View fallback": "CCTV + respaldo de Street View",
+ "OpenStreetMap + optional Google Maps Places": "OpenStreetMap + Google Maps Places opcional",
+ "GFS / ECMWF IFS · FORECAST": "GFS / ECMWF IFS · PRONÓSTICO",
+ "NOAA nowCOAST · OBSERVED": "NOAA nowCOAST · OBSERVADO",
+ "NASA FIRMS · LIVE": "NASA FIRMS · EN VIVO",
+ "data source|Local": "Datos locales",
+ "overview": "vista general",
+ "{percent}% scene cloud": "{percent}% de nubes en la escena",
+ "{min}–{max}% scene cloud": "{min}–{max}% de nubes en la escena",
+ "Sentinel-2 via HLS": "Sentinel‑2 vía HLS",
+ "Landsat 8/9 via HLS": "Landsat 8/9 vía HLS",
+ "coverage|full": "completa",
+ "coverage|partial": "parcial",
+ "m": "m",
+ "km/h": "km/h",
+ "m/s": "m/s",
+ "mph": "mph",
+ "hPa": "hPa",
+ "kt": "kn",
+ "km": "km",
+ "h": "h",
+ "min": "min",
+ "s": "s",
+ "direction|left": "a la izquierda",
+ "direction|right": "a la derecha",
+ "direction|slightly left": "ligeramente a la izquierda",
+ "direction|slightly right": "ligeramente a la derecha",
+ "direction|sharply left": "bruscamente a la izquierda",
+ "direction|sharply right": "bruscamente a la derecha",
+ "direction|straight": "recto",
+ "direction|around": "en sentido contrario",
+ "ordinal|{number}st": "{number}.ª",
+ "ordinal|{number}nd": "{number}.ª",
+ "ordinal|{number}rd": "{number}.ª",
+ "ordinal|{number}th": "{number}.ª",
+ "Head out on {road}": "Sal por {road}",
+ "Head out": "Inicia el recorrido",
+ "Arrive at your destination": "Has llegado a tu destino",
+ "Arrive at your destination, on the left": "Tu destino está a la izquierda",
+ "Arrive at your destination, on the right": "Tu destino está a la derecha",
+ "Make a U-turn": "Da la vuelta",
+ "Make a U-turn onto {road}": "Da la vuelta hacia {road}",
+ "Continue straight": "Sigue recto",
+ "Continue straight onto {road}": "Sigue recto por {road}",
+ "Turn {direction}": "Gira {direction}",
+ "Turn {direction} onto {road}": "Gira {direction} hacia {road}",
+ "maneuver|Turn": "Gira",
+ "Turn onto {road}": "Gira hacia {road}",
+ "Continue {direction}": "Sigue {direction}",
+ "Continue {direction} onto {road}": "Sigue {direction} por {road}",
+ "maneuver|Continue": "Continúa",
+ "Continue onto {road}": "Continúa por {road}",
+ "At the end of the road, turn {direction}": "Al final de la vía, gira {direction}",
+ "At the end of the road, turn {direction} onto {road}": "Al final de la vía, gira {direction} hacia {road}",
+ "At the end of the road, continue": "Al final de la vía, continúa",
+ "At the end of the road, continue onto {road}": "Al final de la vía, continúa por {road}",
+ "Keep {direction} at the fork": "En la bifurcación, mantente {direction}",
+ "Keep {direction} at the fork onto {road}": "En la bifurcación, mantente {direction} hacia {road}",
+ "Continue at the fork": "En la bifurcación, continúa",
+ "Continue at the fork onto {road}": "En la bifurcación, continúa por {road}",
+ "Merge {direction}": "Incorpórate {direction}",
+ "Merge {direction} onto {road}": "Incorpórate {direction} a {road}",
+ "maneuver|Merge": "Incorpórate",
+ "Merge onto {road}": "Incorpórate a {road}",
+ "Take the ramp on the {direction}": "Toma la rampa {direction}",
+ "Take the ramp on the {direction} onto {road}": "Toma la rampa {direction} hacia {road}",
+ "Take the ramp": "Toma la rampa",
+ "Take the ramp onto {road}": "Toma la rampa hacia {road}",
+ "Take the exit on the {direction}": "Toma la salida {direction}",
+ "Take the exit on the {direction} onto {road}": "Toma la salida {direction} hacia {road}",
+ "Take the exit": "Toma la salida",
+ "Take the exit onto {road}": "Toma la salida hacia {road}",
+ "At the roundabout, take the {exit} exit": "En la rotonda, toma la {exit} salida",
+ "At the roundabout, take the {exit} exit onto {road}": "En la rotonda, toma la {exit} salida hacia {road}",
+ "Enter the roundabout": "Entra en la rotonda",
+ "Enter the roundabout onto {road}": "Entra en la rotonda hacia {road}",
+ "At the roundabout, turn {direction}": "En la rotonda, gira {direction}",
+ "At the roundabout, turn {direction} onto {road}": "En la rotonda, gira {direction} hacia {road}",
+ "At the roundabout, continue": "En la rotonda, continúa",
+ "At the roundabout, continue onto {road}": "En la rotonda, continúa por {road}",
+ "Exit the roundabout": "Sal de la rotonda",
+ "Exit the roundabout onto {road}": "Sal de la rotonda hacia {road}",
+ "Use the {direction} lane": "Toma el carril {direction}",
+ "Use the {direction} lane onto {road}": "Toma el carril {direction} hacia {road}",
+ "voice|OFF": "APAG.",
+ "voice|CONNECTING": "CONEX…",
+ "voice|LISTENING": "OYENDO",
+ "voice|EXECUTING": "ACCIÓN",
+ "voice|ERROR": "ERROR",
+ "MIC": "MIC",
+ "WORKING": "EN CURSO",
+ "DONE": "HECHO",
+ "Outline traced": "Contorno trazado",
+ "Outline unavailable": "Contorno no disponible",
+ "in progress": "en curso",
+ "done": "hecho",
+ "failed": "fallido",
+ "cancelled": "cancelado",
+ "view band|STREET": "CALLE",
+ "view band|CITY": "CIUDAD",
+ "view band|METRO": "METRÓPOLI",
+ "view band|REGIONAL": "REGIÓN",
+ "view band|GLOBAL": "GLOBAL",
+ "NEAR {poi} ({city}) {distance}": "CERCA DE {poi} ({city}) {distance}",
+ "SECTOR {lat} {lon}": "SECTOR {lat} {lon}",
+ "ARCTIC": "ÁRTICO",
+ "ANTARCTIC": "ANTÁRTICO",
+ "NORTH AMERICA": "NORTEAMÉRICA",
+ "SOUTH AMERICA": "SUDAMÉRICA",
+ "EUROPE": "EUROPA",
+ "AFRICA": "ÁFRICA",
+ "ASIA": "ASIA",
+ "OCEANIA": "OCEANÍA",
+ "NORTHERN OCEANIC GRID": "CUADRÍCULA OCEÁNICA NORTE",
+ "SOUTHERN OCEANIC GRID": "CUADRÍCULA OCEÁNICA SUR",
+ "N/A": "N/D",
+ "{label} · {radius} AIR/SEA WINDOW": "{label} · VENTANA AIRE/MAR {radius}",
+ "{scope} · INSTALLATIONS {coverage}": "{scope} · INSTALACIONES: {coverage}",
+ "{source} · LOCATION QUERY · RECENT": "{source} · CONSULTA POR UBICACIÓN · RECIENTE",
+ "ft": "ft",
+ "kts": "kn",
+ "PAUSE": "PAUSA",
+ "RESUME": "REANUDAR",
+ "dB": "dB",
+ "radio|NEWS": "NOTICIAS",
+ "radio|TALK": "RADIO HABLADA",
+ "radio|WEATHER": "CLIMA",
+ "radio|SAFETY": "SEGURIDAD",
+ "radio|AIR / SEA": "AIRE / MAR",
+ "radio|TRANSIT": "TRANSPORTE",
+ "radio|MUSIC": "MÚSICA",
+ "radio|OTHER": "OTROS",
+ "SNAPSHOT": "INSTANTÁNEA",
+ "LIVE": "EN VIVO",
+ "UPSTREAM": "ORIGEN",
+ "SYNTHETIC": "SINTÉTICO",
+ "CONFIGURED": "CONFIGURADO",
+ "SEED": "CATÁLOGO",
+ "Live HLS connected": "HLS en vivo conectado",
+ "Live HLS unavailable": "HLS en vivo no disponible",
+ "No stream URL configured": "No hay URL de transmisión configurada",
+ "Live stream connected": "Transmisión en vivo conectada",
+ "Snapshot feed connected": "Fuente de instantáneas conectada",
+ "Media fetch failed": "Error al obtener el contenido multimedia",
+ "Upstream snapshot active": "Instantánea de origen activa",
+ "Fallback Street View frame": "Fotograma de respaldo de Street View",
+ "Upstream unavailable": "Origen no disponible",
+ "No source configured": "No hay fuente configurada",
+ "Upstream HTTP {status}": "Origen: HTTP {status}",
+ "Unexpected media type {type}": "Tipo de contenido inesperado: {type}",
+ "Configured source": "Fuente configurada",
+ "Synthetic fallback": "Respaldo sintético",
+ "Cancel": "Cancelar",
+ "Choose files": "Elegir archivos",
+ "No file chosen": "Ningún archivo seleccionado",
+ "{count} files selected": {
+ "one": "{count} archivo seleccionado",
+ "many": "{count} de archivos seleccionados",
+ "other": "{count} archivos seleccionados"
+ },
+ "Rasuwagadhi witness video": "Video del testigo de Rasuwagadhi",
+ "Bhote Koshi valley footage": "Imágenes del valle del Bhote Koshi",
+ "Flood footage": "Imágenes de la inundación",
+ "Compilation and casualty claims": "Recopilación y afirmaciones sobre víctimas",
+ "SOURCE GEOCONFIRMED · WORLD-PINNED": "FUENTE GEOCONFIRMADA · FIJADA EN EL MAPA",
+ "SOURCE CREDITED · LOCATION UNRESOLVED": "AUTORÍA INDICADA · UBICACIÓN SIN DETERMINAR",
+ "REFERENCE ONLY · CLAIMS UNVERIFIED": "SOLO REFERENCIA · AFIRMACIONES SIN VERIFICAR",
+ "SOURCE GEOCONFIRMED": "FUENTE GEOCONFIRMADA",
+ "2021 historical reference versus 2026 post-event imagery; changes are cumulative and include the July 2025 Rasuwagadhi flood. Schematic downstream progression, not modeled arrival time; not an official hazard model.": "Referencia histórica de 2021 frente a imágenes posteriores al evento de 2026; los cambios son acumulativos e incluyen la inundación de Rasuwagadhi de julio de 2025. Avance esquemático aguas abajo, no un tiempo de llegada modelado; no es un modelo oficial de peligro.",
+ "Immediate collapse viewpoint": "Punto de vista junto al colapso",
+ "Collapse viewpoint": "Vista del colapso",
+ "Debris-dammed lake": "Lago represado por escombros",
+ "Dammed lake": "Lago represado",
+ "Second landslide": "Segundo deslizamiento",
+ "Gyirong border gate": "Paso fronterizo de Gyirong",
+ "Border gate": "Paso fronterizo",
+ "Timure evidence cluster": "Grupo de evidencias de Timure",
+ "Mailung / Upper Trishuli bridge": "Mailung / puente de Upper Trishuli",
+ "Dandagaun viewpoint restaurant": "Restaurante mirador de Dandagaun",
+ "Dandagaun viewpoint": "Mirador de Dandagaun",
+ "Bidur - Trishuli bridge": "Puente Bidur - Trishuli",
+ "Bidur bridge": "Puente de Bidur",
+ "Devighat / Taadi Khola Bridge": "Devighat / puente de Taadi Khola",
+ "Devighat bridge": "Puente de Devighat",
+ "Global Incident Context": "Contexto global del incidente",
+ "Nepal-Focused Globe Rotation": "Rotación del globo hacia Nepal",
+ "Bhote Koshi Regional Approach": "Aproximación regional al Bhote Koshi",
+ "Bhote Koshi Nearby Cities": "Ciudades cercanas al Bhote Koshi",
+ "Bhote Koshi Incident Corridor": "Corredor del incidente del Bhote Koshi",
+ "Bhote Koshi Flood Path": "Trayectoria de la inundación del Bhote Koshi",
+ "Bhote Koshi Corridor Overview": "Vista general del corredor del Bhote Koshi",
+ "Bhote Koshi Upper Valley": "Valle alto del Bhote Koshi",
+ "Upper Valley Collapse": "Colapso en el valle alto",
+ "Debris-Dammed Lake": "Lago represado por escombros",
+ "Nepal-China Border Gate": "Paso fronterizo Nepal-China",
+ "Timure Evidence Cluster": "Grupo de evidencias de Timure",
+ "Syabru Besi Passage": "Paso por Syabru Besi",
+ "Bidur / Trishuli Consequence": "Consecuencias en Bidur / Trishuli",
+ "Final view": "Vista final",
+ "{year} HISTORICAL REFERENCE": "REFERENCIA HISTÓRICA {year}",
+ "{year} POST-EVENT": "POSTERIOR AL EVENTO {year}",
+ "Esri map unavailable · no swipe": "Mapa Esri no disponible · sin comparación",
+ "Swipe needs a globe map": "La comparación necesita un mapa de globo",
+ "Imagery stays on Esri · CLEAR to use Google 3D": "Las imágenes siguen en Esri · BORRAR para usar Google 3D",
+ "Box and images cleared": "Recuadro e imágenes borrados",
+ "Box is {size} wide · limit {limit}": "El recuadro mide {size} de ancho · límite {limit}",
+ "View is {size} wide · limit {limit}": "La vista mide {size} de ancho · límite {limit}",
+ "Frame unavailable; previous observation retained": "Fotograma no disponible; se mantiene la observación anterior",
+ "Weather imagery unavailable": "Imágenes meteorológicas no disponibles",
+ "Weather source unavailable; previous observation retained": "Fuente meteorológica no disponible; se mantiene la observación anterior",
+ "Weather unavailable": "Clima no disponible",
+ "Weather tiles unavailable · previous frame retained": "Teselas meteorológicas no disponibles · se mantiene el fotograma anterior",
+ "Some weather tiles unavailable": "Algunas teselas meteorológicas no disponibles",
+ "Hidden by this map source · choose a globe map": "Oculto con esta fuente del mapa · elige un mapa de globo",
+ "Wind source unavailable": "Fuente de viento no disponible",
+ "Globe imagery unavailable": "Imágenes del globo no disponibles",
+ "Globe field image unavailable": "Imagen del campo en el globo no disponible",
+ "status chip|UNAVAILABLE": "NO DISP.",
+ "Uses registered content or linked media. Those external files are not included in a scene bundle. Their original notices still apply.": "Contiene referencias a contenido registrado o medios vinculados. Esos archivos externos no se incluyen en un paquete de escena. Sus avisos originales siguen vigentes.",
+ "{state} {layers}": "{state}: {layers}",
+ "Selected Space Mission": "Misión espacial seleccionada",
+ "{duration}s + {hold}s": "{duration} s + {hold} s",
+ "Configured Source": "Fuente configurada",
+ "subject": "objetivo",
+ "{value}m": "{value} m",
+ "Google 3D tiles unavailable — check the key's API restrictions, quota, or network": "Teselas de Google 3D no disponibles: revisa las restricciones de API de la clave, la cuota o la red",
+ "Needs {envVars} — add it in Provider Settings — or a Cesium ion token for the ion-hosted route": "Necesita {envVars} — se añade en Ajustes de proveedores — o un token de Cesium ion para la ruta alojada en ion",
+ "Comparison in use by another scene": "La comparación está en uso por otra escena",
+ "A location reading needs a loaded forecast and the Earth at the center of the view.": "Una lectura en un punto necesita un pronóstico cargado y la Tierra en el centro de la vista.",
+ "{mode} {band} {locality} | {region} | ALT {alt} | WINDOW {window} | SUN {sun}° | ONA {ona}° | {zone}": "{mode} · {band} · {locality} | {region} | ALT {alt} | VENTANA {window} | SOL {sun}° | ONA {ona}° | {zone}",
+ "light {source} to use your {name} key": "activa {source} para usar tu clave de {name}",
+ "light {source}": "activa {source}",
+ ", or ": ", o ",
+ "{requirement}, or {offer}": "{requirement}, o {offer}",
+ "The photorealistic 3D planet, place search + Street View": "El planeta 3D fotorrealista, búsqueda de lugares + Street View",
+ "{name} needs the Google 3D map: choose it under MAP SOURCE": "{name} requiere el mapa Google 3D: elígelo en FUENTE DEL MAPA",
+ "zoom in to a street to open {name}": "acércate a una calle para abrir {name}",
+ "Google Street View": "Google Street View",
+ "GOOGLE STREET VIEW": "GOOGLE STREET VIEW",
+ "Google refused GOOGLE_MAPS_API_KEY for Street View — check that the Maps JavaScript API is enabled for it and this site is an allowed referrer": "Google rechazó GOOGLE_MAPS_API_KEY para Street View — comprueba que la clave tenga habilitada la API Maps JavaScript y que este sitio figure entre sus referentes HTTP (sitios web) permitidos",
+ "Street View did not answer — check the network, and that the Maps JavaScript API is enabled for GOOGLE_MAPS_API_KEY": "Street View no respondió — comprueba la red y que la API Maps JavaScript esté habilitada para GOOGLE_MAPS_API_KEY",
+ "click a street to open Street View": "haz clic en una calle para abrir Street View",
+ " or ": " o ",
+ "OPEN {labels}": "ABRIR {labels}",
+ "Open {names} at the centre of the view": "Abrir {names} en el centro de la vista",
+ "Zoom in to a street to open {names} here": "Acércate a una calle para abrir {names} aquí",
+ "radio tag|All": "Todas",
+ "Alternative": "Alternativa",
+ "Ambient": "Ambient",
+ "Blues": "Blues",
+ "Classical": "Clásica",
+ "Country": "Country",
+ "Dance": "Dance",
+ "Electronic": "Electrónica",
+ "Folk": "Folk",
+ "Funk": "Funk",
+ "Hip-Hop": "Hip-Hop",
+ "House": "House",
+ "Indie": "Indie",
+ "Jazz": "Jazz",
+ "Latin": "Latina",
+ "Metal": "Metal",
+ "Oldies": "Clásicos de siempre",
+ "Pop": "Pop",
+ "Punk": "Punk",
+ "R&B": "R&B",
+ "Reggae": "Reggae",
+ "Rock": "Rock",
+ "Soul": "Soul",
+ "Techno": "Techno",
+ "Trance": "Trance",
+ "World": "Músicas del mundo",
+ "{speed}KT": "{speed} KN",
+ "{heading}DEG": "{heading}°",
+ "At least {count}": "Al menos {count}",
+ "Named areas ({n})": "Zonas con nombre ({n})",
+ "{distance} FLIGHT / VESSEL WINDOW": "VENTANA DE VUELOS / BUQUES DE {distance}",
+ "mapped matches within {km} km of the subject": "coincidencias mapeadas a menos de {km} km del objetivo",
+ "none mapped within {km} km; not a complete 250 km survey": "ninguna mapeada a menos de {km} km; no es un barrido completo de 250 km",
+ "mapped matches from the loaded viewport": "coincidencias mapeadas en la vista cargada",
+ "viewport feed is not a complete 250 km survey": "los datos de la vista no son un barrido completo de 250 km",
+ "lane direction|left": "izquierdo",
+ "lane direction|right": "derecho",
+ "lane direction|slightly left": "izquierdo",
+ "lane direction|slightly right": "derecho",
+ "lane direction|sharply left": "del extremo izquierdo",
+ "lane direction|sharply right": "del extremo derecho",
+ "lane direction|straight": "central",
+ "{value}°N": "{value}°N",
+ "{value}°S": "{value}°S",
+ "{value}°E": "{value}°E",
+ "{value}°W": "{value}°O",
+ "fork direction|left": "a la izquierda",
+ "fork direction|right": "a la derecha",
+ "fork direction|slightly left": "ligeramente a la izquierda",
+ "fork direction|slightly right": "ligeramente a la derecha",
+ "fork direction|sharply left": "bruscamente a la izquierda",
+ "fork direction|sharply right": "bruscamente a la derecha",
+ "fork direction|straight": "recto",
+ "installation class|AIRFIELD": "AERÓDROMO",
+ "installation class|NAVAL BASE": "BASE NAVAL",
+ "installation class|RANGE": "CAMPO DE TIRO",
+ "installation class|MILITARY LAND": "TERRENO MILITAR",
+ "installation class|BASE": "BASE",
+ "installation class|PLACES CANDIDATE": "DE GOOGLE PLACES",
+ "installation class|INSTALLATION": "INSTALACIÓN",
+ "fire confidence|high": "alta",
+ "fire confidence|nominal": "nominal",
+ "fire confidence|low": "baja",
+ "age|<1h": "<1 h",
+ "age|{count}h": "{count} h",
+ "age|{count}d": "{count} d",
+ "General emergency": "Emergencia general",
+ "Unlawful interference": "Interferencia ilícita",
+ "Radio failure": "Fallo de radio",
+ "Downed aircraft": "Aeronave siniestrada",
+ "Minimum fuel": "Combustible mínimo",
+ "Lifeguard (medical priority)": "Lifeguard (prioridad médica)",
+ "That file is not valid JSON.": "Ese archivo no es un JSON válido.",
+ "That JSON file is not GeoJSON.": "Ese archivo JSON no es GeoJSON.",
+ "That FeatureCollection has no features list.": "Esa FeatureCollection no tiene lista de features.",
+ "Every GeoJSON feature must have type Feature.": "Cada elemento GeoJSON debe tener el tipo Feature.",
+ "That GeoJSON has invalid geometries.": "Ese GeoJSON tiene geometrías no válidas.",
+ "That GeoJSON contains an unsupported geometry.": "Ese GeoJSON contiene una geometría no admitida.",
+ "That GeoJSON has invalid coordinates.": "Ese GeoJSON tiene coordenadas no válidas.",
+ "That file creates more than {limit} map objects (the limit).": "Ese archivo crea más de {limit} objetos en el mapa (el límite).",
+ "That file has more than {limit} style definitions and image links after cleanup (the limit).": "Tras la limpieza, ese archivo tiene más de {limit} definiciones de estilo y enlaces a imágenes (el límite).",
+ "That file has more than {limit} features (the limit).": "Ese archivo tiene más de {limit} elementos (el límite).",
+ "That file has more than {limit} points (the limit) across {features} features.": "Ese archivo tiene más de {limit} puntos (el límite) en {features} elementos.",
+ "That file has more than {limit} points (the limit).": "Ese archivo tiene más de {limit} puntos (el límite).",
+ "That KMZ unpacks to more than the import limit.": "Al descomprimirse, ese KMZ supera el límite de importación.",
+ "That KMZ is damaged and could not be unpacked.": "Ese KMZ está dañado y no se pudo descomprimir.",
+ "That KMZ is not a readable zip archive.": "Ese KMZ no es un archivo zip legible.",
+ "That KMZ uses a zip format this import does not read.": "Ese KMZ usa un formato zip que esta importación no lee.",
+ "That KMZ is encrypted.": "Ese KMZ está cifrado.",
+ "That KMZ uses a compression method this import does not read.": "Ese KMZ usa un método de compresión que esta importación no lee.",
+ "That KML has invalid geometry bounds.": "Ese KML tiene límites de geometría no válidos.",
+ "That KML has invalid coordinates.": "Ese KML tiene coordenadas no válidas.",
+ "That GPX file has no <gpx> document.": "Ese archivo GPX no tiene documento <gpx>.",
+ "That {format} file is not valid XML.": "Ese archivo {format} no es un XML válido.",
+ "That file has an unreadable image or exceeds the 16-megapixel image limit.": "Ese archivo tiene una imagen ilegible o supera el límite de imagen de 16 megapíxeles.",
+ "That KML could not be read.": "No se pudo leer ese KML.",
+ "That file has invalid point coordinates.": "Ese archivo tiene coordenadas de puntos no válidas.",
+ "Ground heights are not available for that file. Try again when the map has loaded.": "Las alturas del terreno no están disponibles para ese archivo. Vuelve a intentarlo cuando el mapa haya cargado.",
+ "That file took too long to read.": "La lectura de ese archivo tardó demasiado.",
+ "Nothing to import.": "No hay nada que importar.",
+ "That file is larger than {size} MiB.": "Ese archivo pesa más de {size} MiB.",
+ "Only GeoJSON, KML, KMZ and GPX files can be imported.": "Solo se pueden importar archivos GeoJSON, KML, KMZ y GPX.",
+ "That file has nothing to draw.": "Ese archivo no tiene nada que dibujar.",
+ "That KMZ holds no KML document.": "Ese KMZ no contiene ningún documento KML.",
+ "That {format} file could not be read.": "No se pudo leer ese archivo {format}.",
+ "That file has {count} map objects; the limit is {limit}.": "Ese archivo tiene {count} objetos en el mapa; el límite es {limit}.",
+ "Ground heights could not be read. Try that file again.": "No se pudieron leer las alturas del terreno. Vuelve a intentarlo con ese archivo.",
+ "That file has invalid point graphics.": "Ese archivo tiene gráficos de puntos no válidos.",
+ "Low-accuracy score < 2%": "Índice de baja precisión < 2%",
+ "Low-accuracy score 2–10%": "Índice de baja precisión 2–10%",
+ "Low-accuracy score > 10%": "Índice de baja precisión > 10%",
+ "GNSS integrity source unavailable": "Fuente de integridad GNSS no disponible",
+ "Regional sample · 250 nm radius · cells from visited views over 30 min": "Muestra regional · radio de 250 NM · celdas de las vistas visitadas en 30 min",
+ "Retrying automatically at {time} UTC": "Reintento automático a las {time} UTC",
+ "Retrying automatically after provider cooldown": "Reintento automático tras la pausa del proveedor",
+ "Updates automatically after pan or zoom and once a minute. The public feed covers a 250-nautical-mile circle around the view centre; zooming out does not make it a worldwide snapshot. Blank cells are outside sampled coverage or have insufficient observations.": "Se actualiza automáticamente al desplazar o hacer zoom y una vez por minuto. El feed público cubre un círculo de 250 millas náuticas alrededor del centro de la vista; alejarte no lo convierte en una instantánea mundial. Las celdas vacías están fuera de la cobertura muestreada o no tienen observaciones suficientes.",
+ "Low-accuracy score = 100 × max(0, bad − 1) / total: one aircraft is discounted, so this is not the raw share. Cells need {aircraft} aircraft over {minutes} minutes. Navigation-integrity anomalies are not a detection of jamming or spoofing.": "Índice de baja precisión = 100 × max(0, malas − 1) / total: se descuenta una aeronave, así que no es la proporción bruta. Cada celda necesita {aircraft} aeronaves en {minutes} minutos. Las anomalías de integridad de navegación no son una detección de interferencias ni de suplantación.",
+ "SQUAWK {code} · {status}": "SQUAWK {code} · {status}",
+ "ADS-B PRIORITY · {status}": "ADS-B PRIORIDAD · {status}",
+ "ADS-B EMERGENCY · {status}": "ADS-B EMERGENCIA · {status}",
+ "{aircraftClass} · {emergency} · {feedState}": "{aircraftClass} · {emergency} · {feedState}",
+ "Ground heights could not be refreshed. Try the file again when the map has loaded.": "No se pudieron actualizar las alturas del terreno. Vuelve a intentarlo con el archivo cuando el mapa haya cargado.",
+ "{count} map objects": {
+ "one": "{count} objeto en el mapa",
+ "many": "{count} de objetos en el mapa",
+ "other": "{count} objetos en el mapa"
+ },
+ ", drawn with its own styles": ", dibujado con sus propios estilos",
+ "Hide {name}": "Ocultar {name}",
+ "Show {name}": "Mostrar {name}",
+ "Fly to {name}": "Volar a {name}",
+ "Remove {name}": "Quitar {name}",
+ "At most {count} files at once — remove one first.": "Como máximo {count} archivos a la vez: quita uno primero.",
+ "Reading {name}…": "Leyendo {name}…",
+ "That file could not be read.": "No se pudo leer ese archivo.",
+ "Added {count} files.": {
+ "one": "Se añadió {count} archivo.",
+ "many": "Se añadieron {count} de archivos.",
+ "other": "Se añadieron {count} archivos."
+ },
+ "{count} files could not be added ({name}: {error})": {
+ "one": "No se pudo añadir {count} archivo ({name}: {error})",
+ "many": "No se pudieron añadir {count} de archivos ({name}: {error})",
+ "other": "No se pudieron añadir {count} archivos ({name}: {error})"
+ },
+ "Some KML content was left out.": "Se omitió parte del contenido KML.",
+ "GNSS Integrity": "Integridad GNSS",
+ "Show your own GeoJSON, KML, KMZ or GPX files on the globe (or drop them onto it). File bytes stay on this device; overlays can appear in map screenshots shared with voice.": "Muestra en el globo tus propios archivos GeoJSON, KML, KMZ o GPX (o suéltalos sobre él). Los archivos no salen de este dispositivo; las capas pueden aparecer en capturas del mapa compartidas con la voz.",
+ "Import": "Importar",
+ "Choose GeoJSON, KML, KMZ or GPX files": "Elige archivos GeoJSON, KML, KMZ o GPX",
+ "Imported files": "Archivos importados",
+ "DOCKED · {name}": "ACOPLE · {name}",
+ "DOCKED · {name} · +{extra}": "ACOPLE · {name} · +{extra}",
+ "loading coverage...": "cargando cobertura...",
+ "live feed unavailable": "fuente en vivo no disponible",
+ "GBFS fetch error": "error al obtener datos GBFS",
+ "Open the Street Level panel to view imagery": "Abre el panel \"A pie de calle\" para ver las imágenes",
+ "Image could not be opened": "No se pudo abrir la imagen",
+ "Mapillary rejected MAPILLARY_CLIENT_TOKEN — replace it in Provider Settings": "Mapillary rechazó MAPILLARY_CLIENT_TOKEN — sustitúyelo en Ajustes de proveedores",
+ "Coverage requests are being rate-limited — they resume on their own": "Las peticiones de cobertura están limitadas por frecuencia — se reanudan solas",
+ "No street-level imagery within {radius} m of that point": "No hay imágenes a pie de calle a menos de {radius} m de ese punto",
+ "No street-level imagery within {radius} m of the view centre": "No hay imágenes a pie de calle a menos de {radius} m del centro de la vista",
+ "Aim the middle of the view at a street to look for imagery there": "Apunta el centro de la vista a una calle para buscar imágenes allí",
+ "Street View has no imagery for this place": "Street View no tiene imágenes de este lugar",
+ "GOOGLE_MAPS_API_KEY is not set": "GOOGLE_MAPS_API_KEY no está configurada",
+ "The Google Maps JavaScript API could not load": "No se pudo cargar la API de Maps JavaScript de Google",
+ "Weather request timed out": "La petición del clima agotó el tiempo de espera",
+ "Malformed weather manifest": "Manifiesto del clima mal formado",
+ "Weather HTTP {status}": "Clima: HTTP {status}",
+ "Weather image HTTP {status}": "Imagen del clima: HTTP {status}",
+ "Weather prefetch unavailable": "Precarga del clima no disponible",
+ "Infrared decode failed": "Falló la decodificación del infrarrojo",
+ "rate limited": "límite de peticiones superado",
+ "routing service is rate limited": "el servicio de rutas superó el límite de peticiones",
+ "route leg too long": "tramo de la ruta demasiado largo",
+ "route too long": "ruta demasiado larga",
+ "Routing is rate limited — try again in a moment": "Se alcanzó el límite de peticiones de rutas — inténtalo de nuevo en un momento",
+ "{error} — try again in a moment": "{error} — inténtalo de nuevo en un momento",
+ "Routing unavailable (HTTP {status})": "Rutas no disponibles (HTTP {status})",
+ "CelesTrak unreachable": "CelesTrak inaccesible",
+ "KartaView is rate-limiting requests — they resume on their own": "KartaView está limitando las peticiones — se reanudan solas",
+ "KartaView’s photos here are archived and cannot be shown": "Las fotos de KartaView de aquí están archivadas y no se pueden mostrar",
+ "KartaView did not filter this area in time — move the map to ask again": "KartaView no filtró esta zona a tiempo — mueve el mapa para pedirlo de nuevo",
+ "None of KartaView’s photos here pass the imagery filter": "Ninguna foto de KartaView de aquí pasa el filtro de imágenes",
+ "KartaView did not answer in time — try again": "KartaView no respondió a tiempo — inténtalo de nuevo",
+ "KartaView could not be reached — check the network": "No se pudo conectar con KartaView — comprueba la red",
+ "KartaView sent an answer that could not be read": "KartaView envió una respuesta que no se pudo leer",
+ "KartaView is rate-limiting requests": "KartaView está limitando las peticiones",
+ "KartaView is rate-limiting requests — try again in a moment": "KartaView está limitando las peticiones — inténtalo de nuevo en un momento",
+ "KartaView sent too much data": "KartaView envió demasiados datos",
+ "KartaView has no such photo": "KartaView no tiene esa foto",
+ "The KartaView photo could not be loaded": "No se pudo cargar la foto de KartaView",
+ "KartaView has no position for this photo": "KartaView no tiene la posición de esta foto",
+ "Map tiles temporarily unavailable": "Teselas del mapa temporalmente no disponibles",
+ "Mapped names temporarily unavailable": "Nombres mapeados temporalmente no disponibles",
+ "No mapped sites in view": "No hay sitios mapeados a la vista",
+ "No mapped sites within {km} km of the contact": "No hay sitios mapeados a menos de {km} km del contacto",
+ "{count} mapped sites in view": {
+ "one": "{count} sitio mapeado a la vista",
+ "many": "{count} de sitios mapeados a la vista",
+ "other": "{count} sitios mapeados a la vista"
+ },
+ "{count} mapped sites within {km} km of the contact": {
+ "one": "{count} sitio mapeado a menos de {km} km del contacto",
+ "many": "{count} de sitios mapeados a menos de {km} km del contacto",
+ "other": "{count} sitios mapeados a menos de {km} km del contacto"
+ },
+ "Too many mapped sites in view to list them all": "Hay demasiados sitios mapeados a la vista para listarlos todos",
+ "Installation context unavailable": "Contexto de instalaciones no disponible",
+ "Focus vessel {name}, MMSI {mmsi}": "Enfocar el buque {name}, MMSI {mmsi}",
+ "Open the USGS initial report for the 26 August 2026 Nepal landslide": "Abrir el informe inicial del USGS sobre el deslizamiento del 26 de agosto de 2026 en Nepal",
+ "YouTube source": "Fuente de YouTube",
+ "Facebook source": "Fuente de Facebook",
+ "Military airfield": "Aeródromo militar",
+ "Naval base": "Base naval",
+ "Firing range": "Campo de tiro",
+ "Military land": "Terreno militar",
+ "Mapped installation": "Instalación mapeada",
+ "Military area": "Zona militar",
+ "SIMULATED — {reason}": "SIMULADO — {reason}",
+ "TomTom key unavailable": "Clave de TomTom no disponible",
+ "TomTom daily budget reached": "Se alcanzó el límite diario de TomTom",
+ "TomTom upstream unreachable": "Servidor de TomTom inaccesible",
+ "TomTom flow unavailable": "Flujo de TomTom no disponible",
+ "API key rejected — check AISSTREAM_API_KEY": "Clave de API rechazada — revisa AISSTREAM_API_KEY",
+ "feed silent {seconds}s — no AIS data": "fuente en silencio {seconds} s — sin datos AIS",
+ "feed silent — no AIS data": "fuente en silencio — sin datos AIS",
+ "feed down — retrying slowly (attempt {attempt})": "fuente caída — reintentando despacio (intento {attempt})",
+ "feed down — retrying slowly": "fuente caída — reintentando despacio",
+ "reconnecting to feed… (attempt {attempt})": "reconectando con la fuente… (intento {attempt})",
+ "reconnecting to feed…": "reconectando con la fuente…",
+ "AISSTREAM_API_KEY not set": "AISSTREAM_API_KEY no está configurada",
+ "live feed unsupported": "fuente en vivo no compatible",
+ "connecting to feed…": "conectando con la fuente…",
+ "feed disconnected": "fuente desconectada",
+ "feed down": "fuente caída",
+ "feed idle": "fuente inactiva",
+ "AIS live load failed": "Falló la carga de AIS en vivo",
+ "age|{count}m": "{count} min",
+ "{acres} ac": {
+ "one": "{acres} acre",
+ "many": "{acres} de acres",
+ "other": "{acres} acres"
+ },
+ "{percent}% contained": "contenido al {percent}%",
+ "containment unknown": "contención desconocida",
+ "{cause} cause": "causa: {cause}",
+ "{personnel} personnel": {
+ "one": "{personnel} efectivo",
+ "many": "{personnel} de efectivos",
+ "other": "{personnel} efectivos"
+ },
+ "{county} County": "condado de {county}",
+ "{cost} to date": "{cost} hasta la fecha",
+ "discovered {age} ago": "detectado hace {age}",
+ "updated {age} ago": "actualizado hace {age}",
+ "part of {complex}": "parte de {complex}",
+ "InciWeb ↗ · click card to open": "InciWeb ↗ · haz clic en la tarjeta para abrir",
+ "FIRE · {name}": "INCENDIO · {name}",
+ "Unnamed incident": "Sin nombre",
+ "Open {title} on InciWeb": "Abrir {title} en InciWeb",
+ "Vehicle {vehicle}": "Vehículo {vehicle}",
+ "Bus": "Autobús",
+ "Tram": "Tranvía",
+ "Subway": "Metro",
+ "Train": "Tren",
+ "Ferry": "Ferri",
+ "Transit vehicle": "Vehículo de transporte público",
+ "No recent fix": "Sin posición reciente",
+ "Waiting for update": "Esperando actualización",
+ "Moving": "En movimiento",
+ "reported {speed} km/h": "velocidad notificada: {speed} km/h",
+ "reported hdg {heading}°": "rumbo notificado: {heading}°",
+ "Last report: stopped at stop {stop}": "Último informe: detenido en la parada {stop}",
+ "Last report: arriving at stop {stop}": "Último informe: llegando a la parada {stop}",
+ "Last report: next stop {stop}": "Último informe: próxima parada {stop}",
+ "occupancy|empty": "vacío",
+ "occupancy|many seats available": "muchos asientos libres",
+ "occupancy|few seats available": "pocos asientos libres",
+ "occupancy|standing room only": "solo de pie",
+ "occupancy|crushed standing room only": "abarrotado, solo de pie",
+ "occupancy|full": "lleno",
+ "occupancy|not accepting passengers": "no admite pasajeros",
+ "occupancy|not boardable": "no se puede subir",
+ "Shown at street level · depth not in the feed": "Se muestra a nivel de calle · la fuente no indica la profundidad",
+ "Reported {seconds} s ago": "Notificado hace {seconds} s",
+ "Reported {minutes} min ago": "Notificado hace {minutes} min",
+ "{reported} (feed time)": "{reported} (hora de la fuente)",
+ "shown {seconds} s behind": "se muestra con {seconds} s de retraso",
+ "Available trail: {minutes} min": "Rastro disponible: {minutes} min",
+ "Available trail: {minutes} min (limited)": "Rastro disponible: {minutes} min (limitado)",
+ "UNAVAILABLE · {source} · Roads unavailable": "NO DISPONIBLE · {source} · Vías no disponibles",
+ "Roads: {source}": "Vías: {source}",
+ "TomTom roads unavailable while the traffic service is unreachable": "Vías de TomTom no disponibles mientras el servicio de tráfico esté inaccesible",
+ "Hybrid unavailable while the traffic service is unreachable": "Modo híbrido no disponible mientras el servicio de tráfico esté inaccesible",
+ "TomTom roads need a TomTom key": "Las vías de TomTom necesitan una clave de TomTom",
+ "Hybrid needs a TomTom key": "El modo híbrido necesita una clave de TomTom",
+ "Local surface still loading": "La superficie bajo las vías aún se está cargando",
+ "Partial coverage": "Cobertura parcial",
+ "Detailed roads unavailable": "Vías detalladas no disponibles",
+ "Reduced detail coverage": "Cobertura con menos detalle",
+ "OpenFreeMap tiles rate-limited": "Teselas de OpenFreeMap con límite de peticiones",
+ "OpenFreeMap tiles timed out": "Las teselas de OpenFreeMap agotaron el tiempo de espera",
+ "OpenFreeMap tiles unavailable": "Teselas de OpenFreeMap no disponibles",
+ "Heard by your receiver": "Captado por tu receptor",
+ "browser SDR": "SDR del navegador",
+ "decoder feed": "fuente del decodificador",
+ "Your RTL-SDR receiver and decoder feed": "Tu receptor RTL-SDR y la fuente del decodificador",
+ "Your decoder feed": "Tu fuente del decodificador",
+ "Your RTL-SDR receiver": "Tu receptor RTL-SDR",
+ "NO CALLSIGN": "SIN INDICATIVO",
+ "ALT {altitude} FT · GS {speed} KT · TRK {track}": "ALT {altitude} FT · VEL. SUELO {speed} KN · TRK {track}",
+ "V/S {rate}": "VEL. VERT. {rate}",
+ "V/S {rate} FPM": "VEL. VERT. {rate} FT/MIN",
+ "POSITION {age}": "POSICIÓN {age}",
+ "POSITION {seconds} S AGO": "POSICIÓN HACE {seconds} S",
+ "{count} MSGS": {
+ "one": "{count} MENSAJE",
+ "many": "{count} DE MENSAJES",
+ "other": "{count} MENSAJES"
+ },
+ "installation class|BARRACKS": "CUARTEL",
+ "installation class|TRAINING AREA": "ZONA DE INSTRUCCIÓN",
+ "Seeking up…": "Buscando hacia arriba…",
+ "Seeking down…": "Buscando hacia abajo…",
+ "Scanning {mhz} MHz…": "Escaneando {mhz} MHz…",
+ "Found {mhz} MHz · {snr} dB": "Encontrado {mhz} MHz · {snr} dB",
+ "Broadcaster stream is unavailable or blocked by the browser.": "El flujo de la emisora no está disponible o el navegador lo ha bloqueado.",
+ "Playback requires a direct click or tap.": "La reproducción requiere un clic o un toque directo.",
+ "Broadcaster stream could not be started.": "No se pudo iniciar el flujo de la emisora.",
+ "Directory refresh degraded; showing the previous station catalog.": "La actualización del directorio fue parcial; se muestra el catálogo de emisoras anterior.",
+ "Radio directory coverage is degraded.": "El directorio de radio funciona con interrupciones.",
+ "Directory refresh failed; showing the previous station catalog.": "La actualización del directorio falló; se muestra el catálogo de emisoras anterior.",
+ "Radio directory is temporarily unavailable.": "El directorio de radio no está disponible temporalmente.",
+ "Decoder feeds: {feeds}": "Fuentes del decodificador: {feeds}",
+ " · read while Local ADS-B is on": " · se leen mientras ADS-B local está activo",
+ "idle": "en espera",
+ "running": "activo",
+ "suspended": "suspendido",
+ "closed": "cerrado",
+ "Local FM stopped: internet radio started": "FM local detenida: se inició la radio por Internet",
+ "ALPR cameras": "cámaras ALPR",
+ "OVERPASS RATE-LIMITED": "OVERPASS CON LÍMITE DE PETICIONES",
+ "OVERPASS TIMED OUT": "OVERPASS AGOTÓ EL TIEMPO DE ESPERA",
+ "OVERPASS COULD NOT COMPLETE THE QUERY": "OVERPASS NO PUDO COMPLETAR LA CONSULTA",
+ "MAP TILES TEMPORARILY UNAVAILABLE": "TESELAS DEL MAPA TEMPORALMENTE NO DISPONIBLES",
+ "MAPPED NAMES TEMPORARILY UNAVAILABLE": "NOMBRES MAPEADOS TEMPORALMENTE NO DISPONIBLES",
+ "Shared flight follow expired": "El seguimiento del vuelo compartido ha caducado",
+ "Shared military flight follow expired": "El seguimiento del vuelo militar compartido ha caducado",
+ "Shared satellite follow expired": "El seguimiento del satélite compartido ha caducado",
+ "Shared flight could not be restored — feed unavailable": "No se pudo restaurar el vuelo compartido — fuente no disponible",
+ "Shared military flight could not be restored — feed unavailable": "No se pudo restaurar el vuelo militar compartido — fuente no disponible",
+ "Shared satellite could not be restored — feed unavailable": "No se pudo restaurar el satélite compartido — fuente no disponible",
+ "Shared flight is unavailable": "El vuelo compartido no está disponible",
+ "Shared military flight is unavailable": "El vuelo militar compartido no está disponible",
+ "Shared satellite is unavailable": "El satélite compartido no está disponible",
+ "Scene not saved — browser storage unavailable": "Escena no guardada — almacenamiento del navegador no disponible",
+ "Scene not saved — existing saved project could not be read. Export edits or import a valid file.": "Escena no guardada — no se pudo leer el proyecto guardado. Exporta los cambios o importa un archivo válido.",
+ "Saved project could not be read; storage preserved. Import a valid file to resume saving.": "No se pudo leer el proyecto guardado; el almacenamiento se conserva. Importa un archivo válido para volver a guardar.",
+ "Scene not saved — {reason}": "Escena no guardada — {reason}",
+ "Stopped": "Detenido",
+ "Stopped (Esc)": "Detenido (Esc)",
+ "Camera ownership changed": "Cambió el control de la cámara",
+ "Scene layer turned off": "Capa de la escena desactivada",
+ "Seeking scene clock": "Desplazando el reloj de la escena",
+ "Importing project": "Importando proyecto",
+ "Camera move interrupted": "Movimiento de cámara interrumpido",
+ "Scene media timed out": "El contenido multimedia de la escena agotó el tiempo de espera",
+ "Space Missions isolates replay data. Exit the mode to enable {layer}.": "El modo Misiones espaciales aísla los datos de repetición. Sal del modo para activar {layer}.",
+ "Tilted view": "Vista inclinada",
+ "Straight-down view": "Vista cenital",
+ "North up": "Norte arriba",
+ "Exit cockpit to fly to a camera": "Sal de la cabina para volar a una cámara",
+ "Exit cockpit to fly to a location": "Sal de la cabina para volar a una ubicación",
+ "Exit cockpit to fly to a photo": "Sal de la cabina para volar a una foto",
+ "Exit cockpit to fly to a shared view": "Sal de la cabina para volar a una vista compartida",
+ "Exit cockpit to fly to a target": "Sal de la cabina para volar a un objetivo",
+ "Exit cockpit to fly to a vessel": "Sal de la cabina para volar a un buque",
+ "Exit cockpit to fly to a fire": "Sal de la cabina para volar a un incendio",
+ "Exit cockpit to fly to a route": "Sal de la cabina para volar a una ruta",
+ "Exit cockpit to fly to a file": "Sal de la cabina para volar a un archivo",
+ "Exit cockpit to fly to a scene": "Sal de la cabina para volar a una escena",
+ "Go to expanded Radio section": "Ir a la sección de Radio expandida",
+ "Expand Radio section in Context": "Expandir la sección de Radio en Contexto",
+ "Double-click the header to snap the panel back": "Haz doble clic en el encabezado para devolver el panel a su sitio",
+ "New scene name": "Nombre de la nueva escena",
+ "Delete scene \"{scene}\" and all shots?": "¿Eliminar la escena \"{scene}\" y todos sus planos?",
+ "Detailed outline unavailable": "Contorno detallado no disponible",
+ "Provider Settings does not answer proxied requests": "Ajustes de proveedores no responde a peticiones a través de un proxy",
+ "Provider Settings is disabled while sharing is enabled": "El panel \"Ajustes de proveedores\" está desactivado mientras el uso compartido esté activado",
+ "Provider Settings answers only the machine running the server": "Ajustes de proveedores solo responde al equipo que ejecuta el servidor",
+ "Provider Settings answers only local hostnames": "Ajustes de proveedores solo responde a nombres de host locales",
+ "Provider Settings requires an exact local Origin": "Ajustes de proveedores requiere un Origin local exacto",
+ "Unrecognized Origin refused": "Origin no reconocido: petición rechazada",
+ "Cross-origin requests are refused": "Se rechazan las peticiones de otro origen",
+ "Content-Type must be application/json": "Content-Type debe ser application/json",
+ "Method not allowed": "Método no permitido",
+ "Request too large": "Petición demasiado grande",
+ "Invalid JSON": "JSON no válido",
+ "Body must be a JSON object of {ENV_VAR: value}": "El cuerpo debe ser un objeto JSON de {ENV_VAR: value}",
+ "No keys provided": "No se envió ninguna clave",
+ "At most {limit} keys per save": "Como máximo {limit} claves por guardado",
+ "Unknown key: {name}": "Clave desconocida: {name}",
+ "{name} must be a string": "{name}: el valor debe ser una cadena de texto",
+ "{name} is empty": "{name}: el valor está vacío",
+ "{name} is longer than any real key ({limit} max)": "{name}: el valor es más largo que cualquier clave real (máximo {limit})",
+ "{name} may only contain printable characters with no spaces": "{name}: solo se admiten caracteres imprimibles, sin espacios",
+ "{name} contains a character that is not valid in a key (#, quotes, $, \\, or backtick)": "{name}: hay un carácter no válido en una clave (#, comillas, $, \\ o acento grave)",
+ "{name} is configured outside Provider Settings and can only be changed where it was set": "{name} se configuró fuera de Ajustes de proveedores y solo se puede cambiar donde se definió",
+ "The key was not saved: could not restrict the credential file to your account; nothing was saved": "La clave no se guardó: no se pudo restringir el archivo de credenciales a tu cuenta; no se guardó nada",
+ "The key was not saved: the existing configuration could not be read, so nothing was changed": "La clave no se guardó: no se pudo leer la configuración existente, así que no se cambió nada",
+ "Could not write the {store} store": "No se pudo escribir en el almacén {store}",
+ "Could not check ChatGPT sign-in. Try again.": "No se pudo comprobar el inicio de sesión de ChatGPT. Inténtalo de nuevo.",
+ "Cloud voice will use OPENAI_API_KEY on the next session.": "La voz en la nube usará OPENAI_API_KEY en la próxima sesión.",
+ "Checking local ChatGPT OAuth sign-in…": "Comprobando el inicio de sesión OAuth local de ChatGPT…",
+ "Could not check ChatGPT sign-in.": "No se pudo comprobar el inicio de sesión de ChatGPT.",
+ "ChatGPT OAuth selected for cloud voice. Your API key stays saved and available.": "OAuth de ChatGPT seleccionado para la voz en la nube. Tu clave de API sigue guardada y disponible.",
+ "ChatGPT sign-in expired. Opening sign-in again…": "El inicio de sesión de ChatGPT caducó. Abriéndolo de nuevo…",
+ "Opening ChatGPT sign-in in your browser…": "Abriendo el inicio de sesión de ChatGPT en tu navegador…",
+ "Could not start ChatGPT sign-in on this machine.": "No se pudo abrir el inicio de sesión de ChatGPT en este equipo.",
+ "Finish ChatGPT sign-in in the browser. Waiting for it to complete…": "Termina de iniciar sesión en ChatGPT en el navegador. Esperando a que se complete…",
+ "ChatGPT sign-in timed out. Click {button} to try again.": "Se agotó el tiempo para iniciar sesión en ChatGPT. Haz clic en \"{button}\" para intentarlo de nuevo.",
+ "ChatGPT sign-in complete. OAuth will be used for the next cloud voice session.": "Sesión de ChatGPT iniciada. Se usará OAuth en la próxima sesión de voz en la nube.",
+ "OAuth check failed: {detail}": "Error al comprobar OAuth: {detail}",
+ "unsaved CCTV calibration": "la calibración de CCTV sin guardar",
+ "the open cockpit": "la cabina abierta",
+ "Switching language reloads the page. This will be lost: {items}. Switch anyway?": "Cambiar de idioma recarga la página. Se perderá lo siguiente: {items}. ¿Cambiar de todos modos?",
+ "Wind upstream unavailable": "Origen de datos de viento no disponible",
+ "WebUSB needs desktop Chrome or Edge": "WebUSB requiere Chrome o Edge de escritorio",
+ "connect a receiver in Radio": "conecta un receptor en Radio",
+ "receiver is in FM mode": "el receptor está en modo FM",
+ "Cyclone advisories unavailable": "Avisos de ciclones no disponibles",
+ "Cyclone data unavailable": "Datos de ciclones no disponibles",
+ "Drag to size the box": "Arrastra para dar tamaño al recuadro",
+ "Press on the ground, not the sky": "Pulsa sobre el suelo, no sobre el cielo",
+ "Point the camera at the ground to use the view": "Apunta la cámara al suelo para usar la vista",
+ "That point cannot anchor a box": "Ese punto no puede anclar un recuadro",
+ "Box edges must be finite": "Coordenadas del recuadro no válidas",
+ "Longitudes must be within ±180°": "Las longitudes deben estar dentro de ±180°",
+ "Select one side of the dateline": "No cruces la línea de cambio de fecha",
+ "Box must enclose an area": "El recuadro debe abarcar un área",
+ "Imagery stops at ±{limit}° latitude": "Las imágenes llegan hasta ±{limit}° de latitud",
+ "{owner} is using the pointer — close it first": "Puntero en uso: {owner}. Ciérralo primero",
+ "OpenSky OAuth client missing/invalid": "Cliente OAuth de OpenSky ausente o no válido",
+ "OpenSky OAuth rejected credentials": "OpenSky OAuth rechazó las credenciales",
+ "OpenSky username/password rejected": "OpenSky rechazó el usuario o la contraseña",
+ "OpenSky auth missing": "Falta la autenticación de OpenSky",
+ "OpenSky auth required": "OpenSky requiere autenticación",
+ "OpenSky auth invalid": "Autenticación de OpenSky no válida",
+ "OpenSky auth failed": "Falló la autenticación de OpenSky",
+ "Source snapshot {minutes} min old": "La instantánea de la fuente tiene {minutes} min",
+ "{source} rate limited (anonymous)": "{source}: límite de peticiones (anónimo)",
+ "{source} rate limited": "{source}: límite de peticiones",
+ "{source} HTTP {status}": "{source}: HTTP {status}",
+ "{source} network error": "{source}: error de red",
+ "Malformed {source} aircraft rows": "{source}: filas de aeronaves mal formadas",
+ "Malformed {source} response": "{source}: respuesta mal formada",
+ "Source snapshot time unavailable": "Hora de la instantánea de la fuente no disponible",
+ "Live data unavailable": "Datos en vivo no disponibles",
+ "{n} aircraft": {
+ "one": "{n} aeronave",
+ "many": "{n} de aeronaves",
+ "other": "{n} aeronaves"
+ },
+ "{n} military aircraft": {
+ "one": "{n} aeronave militar",
+ "many": "{n} de aeronaves militares",
+ "other": "{n} aeronaves militares"
+ },
+ "{n} ships": {
+ "one": "{n} buque",
+ "many": "{n} de buques",
+ "other": "{n} buques"
+ },
+ "{n} satellites": {
+ "one": "{n} satélite",
+ "many": "{n} de satélites",
+ "other": "{n} satélites"
+ },
+ "{n} launches": {
+ "one": "{n} lanzamiento",
+ "many": "{n} de lanzamientos",
+ "other": "{n} lanzamientos"
+ },
+ "{n} earthquakes": {
+ "one": "{n} terremoto",
+ "many": "{n} de terremotos",
+ "other": "{n} terremotos"
+ },
+ "{n} fires": {
+ "one": "{n} incendio",
+ "many": "{n} de incendios",
+ "other": "{n} incendios"
+ },
+ "{n} fire perimeters": {
+ "one": "{n} perímetro de incendio",
+ "many": "{n} de perímetros de incendio",
+ "other": "{n} perímetros de incendio"
+ },
+ "{n} cyclones": {
+ "one": "{n} ciclón",
+ "many": "{n} de ciclones",
+ "other": "{n} ciclones"
+ },
+ "{n} buses": {
+ "one": "{n} autobús",
+ "many": "{n} de autobuses",
+ "other": "{n} autobuses"
+ },
+ "{n} bike share": {
+ "one": "{n} estación de bicicletas compartidas",
+ "many": "{n} de estaciones de bicicletas compartidas",
+ "other": "{n} estaciones de bicicletas compartidas"
+ },
+ "{n} flock cameras": {
+ "one": "{n} cámara ALPR",
+ "many": "{n} de cámaras ALPR",
+ "other": "{n} cámaras ALPR"
+ },
+ "{n} military bases": {
+ "one": "{n} base militar",
+ "many": "{n} de bases militares",
+ "other": "{n} bases militares"
+ },
+ "{n} datacenters": {
+ "one": "{n} centro de datos",
+ "many": "{n} de centros de datos",
+ "other": "{n} centros de datos"
+ },
+ "{n} dams": {
+ "one": "{n} presa",
+ "many": "{n} de presas",
+ "other": "{n} presas"
+ },
+ "{n} results": {
+ "one": "{n} resultado",
+ "many": "{n} de resultados",
+ "other": "{n} resultados"
+ },
+ "anywhere in the loaded data": "en todos los datos cargados",
+ "in view": "a la vista",
+ "within {radius} of the view centre": "en un radio de {radius} del centro de la vista",
+ "within {radius} of {place} (Contacts window)": "en un radio de {radius} de {place} (ventana de Contactos)",
+ "within {radius} of {place}": "en un radio de {radius} de {place}",
+ "within {radius}": "en un radio de {radius}",
+ "over {region}": "en {region}",
+ "At least {items}": "Al menos {items}",
+ "{items} {scope}": "{items} {scope}",
+ "last 24 h": "últimas 24 h",
+ "past 30 d and upcoming": "últimos 30 d y próximos",
+ "the flights layer loads by viewport": "la capa de vuelos se carga según la vista",
+ "distance is ground distance, not overhead": "la distancia es sobre el terreno hasta el punto subsatélite, no hasta el satélite",
+ "the count is a lower bound because at least one layer reached its retained limit.": "el recuento es un mínimo porque al menos una capa alcanzó su límite de retención.",
+ "{label} loading": "{label}: cargando",
+ "{label} error": "{label}: error",
+ "counted the first {returned} loaded records": "se contaron los primeros {returned} registros cargados",
+ "counted {returned} of {total} loaded records": "se contaron {returned} de {total} registros cargados",
+ "{layers} just turned on — still loading, counts will rise": "{layers}: recién activado — aún se está cargando, los recuentos subirán",
+ "Contacts panel snapshot at {time} — the same retained cohort supplies the card, speech, and follow-up memory": "Instantánea del panel Contactos ({time}) — el mismo conjunto retenido alimenta la tarjeta, la voz y la memoria de seguimiento",
+ "Contacts panel snapshot — the same retained cohort supplies the card, speech, and follow-up memory": "Instantánea del panel Contactos — el mismo conjunto retenido alimenta la tarjeta, la voz y la memoria de seguimiento",
+ "Not answered: {layers}": "Sin respuesta: {layers}",
+ "The flights layer is not enabled": "La capa de vuelos no está activada",
+ "The military layer is not enabled": "La capa de vuelos militares no está activada",
+ "The satellites layer is not enabled": "La capa de satélites no está activada",
+ "The ais-live-vessels layer is not enabled": "La capa de buques AIS no está activada",
+ "Could not enable the requested layer": "No se pudo activar la capa solicitada",
+ "Could not disable the requested layer": "No se pudo desactivar la capa solicitada",
+ "Radio layer unavailable": "La capa de radio no está disponible",
+ "Camera navigation is unavailable in the current view": "La navegación de la cámara no está disponible en la vista actual",
+ "Camera navigation policy unavailable": "La política de navegación de la cámara no está disponible",
+ "Nearest-aircraft selection supports Flights or Military Flights only": "La selección de la aeronave más cercana solo funciona con vuelos o vuelos militares",
+ "Nearest-aircraft selection needs a preset, place name, or latitude and longitude": "Para seleccionar la aeronave más cercana se necesita un preajuste, un nombre de lugar o la latitud y la longitud",
+ "Could not arrive at the requested place": "No se pudo llegar al lugar solicitado",
+ "The nearest airborne aircraft could not be selected": "No se pudo seleccionar la aeronave en vuelo más cercana",
+ "No flights within {radius} of the current view": "No hay vuelos en un radio de {radius} de la vista actual",
+ "No military within {radius} of the current view": "No hay vuelos militares en un radio de {radius} de la vista actual",
+ "No satellites within {radius} of the current view": "No hay satélites en un radio de {radius} de la vista actual",
+ "No vessels within {radius} of the current view": "No hay buques en un radio de {radius} de la vista actual",
+ "{layer} is enabled on the {source} feed, but no airborne aircraft is loaded in the {place} view yet": "La capa {layer} está activada con la fuente {source}, pero aún no hay aeronaves en vuelo cargadas en la vista de {place}",
+ "{layer} is enabled, but no airborne aircraft is loaded in the {place} view yet": "La capa {layer} está activada, pero aún no hay aeronaves en vuelo cargadas en la vista de {place}",
+ "{layer} is enabled, but its aircraft feed is unavailable": "La capa {layer} está activada, pero su fuente de aeronaves no está disponible",
+ "{layer} is enabled, but its destination refresh did not complete": "La capa {layer} está activada, pero la actualización en el destino no terminó",
+ "{layer} is enabled, but {source} is unavailable": "La capa {layer} está activada, pero {source} no está disponible",
+ "Could not arrive at {place}": "No se pudo llegar a {place}",
+ "{name} is no longer loaded": "{name} ya no está cargado",
+ "Unknown target layer: {target}": "Capa de destino desconocida: {target}",
+ "Layer": "Capa",
+ "there": "allí",
+ "Frame flights": "Encuadrar aeronaves",
+ "Frame military": "Encuadrar aeronaves militares",
+ "Frame vessels": "Encuadrar buques",
+ "Fly to Location": "Volar al lugar",
+ "Nearest aircraft to Here": "Aeronave más cercana aquí",
+ "Estimate is incomplete — a response was still in flight when the session ended, so its usage was never reported.": "La estimación está incompleta: una respuesta seguía en curso cuando terminó la sesión, así que su uso nunca se informó.",
+ "STANDARD": "ESTÁNDAR",
+ "vehicle motion|Stopped": "Detenido",
+ "ACQUIRING FRAME": "OBTENIENDO FOTOGRAMA",
+ "Camera source temporarily unavailable": "Fuente de cámaras no disponible temporalmente",
+ "Perimeter source unavailable": "Fuente de perímetros no disponible",
+ "Imagery catalog unavailable": "Catálogo de imágenes no disponible",
+ "Earthquake source unavailable": "Fuente de terremotos no disponible",
+ "TeleGeography load failed": "Falló la carga de TeleGeography",
+ "Wind request timed out": "La petición del viento agotó el tiempo de espera",
+ "Malformed wind manifest": "Manifiesto del viento mal formado",
+ "Malformed wind grid": "Malla del viento mal formada",
+ "Unknown wind model": "Modelo de viento desconocido",
+ "Unknown weather overlay": "Capa de clima desconocida",
+ "Temperature field unavailable": "Campo de temperatura no disponible",
+ "Mean sea level pressure field unavailable": "Campo de presión a nivel del mar no disponible",
+ "KartaView answered HTTP {status}": "KartaView respondió HTTP {status}",
+ "KartaView refused the request (code {code})": "KartaView rechazó la petición (código {code})",
+ "Stopped by voice": "Detenido por voz",
+ "drawings on the map": "los dibujos del mapa",
+ "imported map files": "los archivos importados en el mapa",
+ "the active voice session": "la sesión de voz activa",
+ "Light aircraft": "Avioneta",
+ "Glider": "Planeador",
+ "Turboprop": "Turbohélice",
+ "Airliner": "Avión comercial",
+ "Widebody": "Avión de fuselaje ancho",
+ "Four-engine jet": "Reactor cuatrimotor",
+ "Helicopter": "Helicóptero",
+ "Fast jet": "Avión de alto rendimiento",
+ "Business jet": "Reactor ejecutivo",
+ "Drone": "Dron",
+ "fire cause|Human": "humana",
+ "fire cause|Natural": "natural",
+ "fire cause|Undetermined": "indeterminada",
+ "fire cause|Unknown": "desconocida",
+ "fire behavior|Minimal": "actividad mínima",
+ "fire behavior|Moderate": "actividad moderada",
+ "fire behavior|Active": "actividad alta",
+ "fire behavior|Extreme": "actividad extrema",
+ "Type {level} Incident": "incidente de tipo {level}",
+ "${amount}K": "{amount} mil $",
+ "${amount}M": "{amount} M$",
+ "${amount}B": "{amount} mil M$",
+ "{speed} kn": "{speed} kn",
+ "1090 MHz": "1090 MHz",
+ "978 MHz UAT": "978 MHz UAT",
+ "feed status|live": "en vivo",
+ "feed status|stale": "desactualizada",
+ "feed status|unreachable": "inaccesible",
+ "feed status|invalid": "no válida",
+ "Vector tile metadata unavailable": "Metadatos de teselas vectoriales no disponibles",
+ "Vector tiles unavailable": "Teselas vectoriales no disponibles",
+ "Vector tiles unavailable (HTTP {status})": "Teselas vectoriales no disponibles (HTTP {status})",
+ "Vector tile request timed out": "Las teselas vectoriales agotaron el tiempo de espera",
+ "Zoom in for vector tile coverage": "Acércate para cargar las teselas vectoriales",
+ "Camera coverage unavailable": "Cobertura de cámaras no disponible",
+ "Hybrid": "Híbrido",
+ "TomTom roads only, each with its live flow": "Solo vías de TomTom, cada una con su flujo en vivo",
+ "TomTom roads only, each with its live flow (needs a TomTom key)": "Solo vías de TomTom, cada una con su flujo en vivo (necesita una clave de TomTom)",
+ "OpenStreetMap roads, with TomTom flow matched when available": "Vías de OpenStreetMap, con el flujo de TomTom emparejado cuando está disponible",
+ "TomTom roads first; OpenStreetMap fills the rest, simulated": "Primero las vías de TomTom; OpenStreetMap completa el resto con flujo simulado",
+ "TomTom roads first; OpenStreetMap fills the rest, simulated (needs a TomTom key)": "Primero las vías de TomTom; OpenStreetMap completa el resto con flujo simulado (necesita una clave de TomTom)",
+ "Austin": "Austin",
+ "San Francisco": "San Francisco",
+ "New York": "Nueva York",
+ "Tokyo": "Tokio",
+ "London": "Londres",
+ "Paris": "París",
+ "Dubai": "Dubái",
+ "Washington DC": "Washington D. C.",
+ "Tallinn": "Tallin",
+ "Los Angeles": "Los Ángeles",
+ "Data attribution": "Atribución de datos",
+ "Data provided by:": "Datos proporcionados por:",
+ "Exit cockpit to view weather coverage": "Sal de la cabina para ver la cobertura de la capa meteorológica",
+ "Exit cockpit to fly to a cyclone": "Sal de la cabina para volar a un ciclón",
+ "the title of scene {scene} is empty or longer than {max} characters": "el título de la escena {scene} está vacío o supera los {max} caracteres",
+ "the title of shot {shot} in scene {scene} is empty or longer than {max} characters": "el título del plano {shot} de la escena {scene} está vacío o supera los {max} caracteres",
+ "the project is larger than 5 MiB": "el proyecto pesa más de 5 MiB",
+ "the project has too many shots": "el proyecto tiene demasiados planos",
+ "the scene data failed validation": "los datos de la escena no superaron la validación",
+ "Layer on": "Capa: activada",
+ "Layer off": "Capa: desactivada",
+ "Zoom in": "Acercar",
+ "Zoom out": "Alejar",
+ "Zoom out to globe": "Alejar hasta el globo",
+ "Open data layers": "Abrir las capas de datos",
+ "Open or close a panel": "Abrir o cerrar un panel",
+ "Change context mode": "Cambiar el modo de contexto",
+ "Control cockpit": "Controlar la cabina",
+ "Change visual style": "Cambiar el estilo visual",
+ "Adjust HUD": "Ajustar el HUD",
+ "Adjust cyber sonar": "Ajustar el sonar Ciber",
+ "Adjust detection overlay": "Ajustar la superposición de detección",
+ "Change map stack": "Cambiar el conjunto de mapas",
+ "Adjust post-processing": "Ajustar el posprocesado",
+ "Control scene": "Controlar la escena",
+ "Control CCTV": "Controlar las cámaras CCTV",
+ "Control radio": "Controlar la radio",
+ "Track contact": "Rastrear el contacto",
+ "Stop tracking": "Detener el rastreo",
+ "Clear marks": "Borrar las marcas",
+ "Move camera": "Mover la cámara",
+ "Fly route": "Recorrer la ruta",
+ "Analyst query": "Consulta analítica",
+ "Next ISS pass": "Próximo paso de la EEI",
+ "Next satellite pass": "Próximo paso del satélite",
+ "Action": "Acción",
+ "The photo could not be loaded": "No se pudo cargar la foto",
+ "{name} photo. ← and → step along the sequence. On a 360° photo, drag or use Shift+← →, ↑ ↓ to look around, and + − to zoom": "Foto de {name}. ← y → avanzan por la secuencia. En una foto de 360°, arrastra o usa Mayús+← →, ↑ ↓ para mirar alrededor, y + − para hacer zoom",
+ "{name} street-level photo": "Foto a pie de calle de {name}",
+ "Previous photo in this sequence (←)": "Foto anterior de la secuencia (←)",
+ "Next photo in this sequence (→)": "Foto siguiente de la secuencia (→)",
+ "The Panoramax photo could not be loaded": "No se pudo cargar la foto de Panoramax",
+ "Panoramax is busy — coverage resumes on its own": "Panoramax está saturado — la cobertura se reanuda sola",
+ "no Panoramax photos in view": "no hay fotos de Panoramax a la vista",
+ "no Panoramax photos here match the filters": "aquí no hay fotos de Panoramax que cumplan los filtros",
+ "Panoramax sent a map tile that could not be read": "Panoramax envió una tesela del mapa que no se pudo leer",
+ "This Panoramax photo is no longer available": "Esta foto de Panoramax ya no está disponible",
+ "zoom in to see Panoramax coverage": "acércate para ver la cobertura de Panoramax",
+ "Panoramax did not answer in time — try again": "Panoramax no respondió a tiempo — inténtalo de nuevo",
+ "Panoramax could not be reached — check the connection": "No se pudo conectar con Panoramax — comprueba la conexión",
+ "Panoramax sent too much data": "Panoramax envió demasiados datos",
+ "Panoramax is busy": "Panoramax está saturado",
+ "Panoramax sent an unreadable answer": "Panoramax envió una respuesta que no se pudo leer",
+ "Apply the full cloud brightness key; 100% filter strength": "Aplica el filtro de brillo de nubes completo; intensidad del filtro 100%",
+ "Show the complete infrared image; 0% filter strength": "Muestra la imagen infrarroja completa; intensidad del filtro 0%",
+ "FILTER": "FILTRO",
+ "Cloud filter strength": "Intensidad del filtro de nubes",
+ "Panoramax answered HTTP {status}": "Panoramax respondió HTTP {status}",
+ "Highest air-quality readings in view": "Lecturas de calidad del aire más altas a la vista",
+ "Low": "Baja",
+ "Moderate": "Moderada",
+ "High": "Alta",
+ "Very High": "Muy alta",
+ "Air quality": "Calidad del aire",
+ "{n} sequences in view · click a line for its nearest photo": {
+ "one": "{n} secuencia a la vista · haz clic en una línea para su foto más cercana",
+ "many": "{n} secuencias a la vista · haz clic en una línea para su foto más cercana",
+ "other": "{n} secuencias a la vista · haz clic en una línea para su foto más cercana"
+ },
+ "FOV {value}° (DATASHEET)": "FOV {value}° (FICHA TÉCNICA)",
+ "SPEC FOV {span}° (CAPABILITY)": "FOV DE FICHA {span}° (CAPACIDAD)",
+ "{spec} · SPECS: CCTV-DATABASE.COM": "{spec} · ESPECIFICACIONES: CCTV-DATABASE.COM",
+ "Canada only · ECCC AQHI network": "Solo Canadá · red AQHI de ECCC",
+ "{count} stations reporting": {
+ "one": "{count} estación con datos",
+ "many": "{count} de estaciones con datos",
+ "other": "{count} estaciones con datos"
+ },
+ "No readings available": "No hay lecturas disponibles",
+ "No current readings": "Sin lecturas actuales",
+ "Low health risk": "Riesgo bajo para la salud",
+ "Moderate health risk": "Riesgo moderado para la salud",
+ "High health risk": "Riesgo alto para la salud",
+ "Very High health risk": "Riesgo muy alto para la salud",
+ "Air quality request failed": "Falló la petición de calidad del aire",
+ "ECCC request timed out": "La petición a ECCC agotó el tiempo de espera",
+ "Malformed AQHI station response": "Respuesta de estaciones AQHI mal formada",
+ "Malformed AQHI observation response": "Respuesta de observaciones AQHI mal formada",
+ "No AQHI stations available": "No hay estaciones AQHI disponibles",
+ "{n} air quality": {
+ "one": "{n} estación de calidad del aire",
+ "many": "{n} de estaciones de calidad del aire",
+ "other": "{n} estaciones de calidad del aire"
+ },
+ "GNSS feed rate limited (HTTP 429)": "Fuente GNSS: límite de peticiones superado (HTTP 429)",
+ "GNSS feed unavailable (HTTP {status})": "Fuente GNSS no disponible (HTTP {status})",
+ "GNSS snapshot needs a view anchor": "La instantánea GNSS necesita un punto de referencia de la vista",
+ "Malformed GNSS integrity snapshot": "Instantánea de integridad GNSS mal formada",
+ "GNSS integrity snapshot has no observation time": "La instantánea de integridad GNSS no tiene hora de observación",
+ "{feed} feed unavailable": "Fuente {feed} no disponible",
+ "Loading {feeds}": "Cargando {feeds}",
+ "{count} CelesTrak groups unavailable": {
+ "one": "{count} grupo de CelesTrak no disponible",
+ "many": "{count} de grupos de CelesTrak no disponibles",
+ "other": "{count} grupos de CelesTrak no disponibles"
+ },
+ "Malformed launch snapshot": "Instantánea de lanzamientos mal formada",
+ "Malformed perimeter snapshot": "Instantánea de perímetros mal formada",
+ "Overpass returned an incomplete camera response": "Overpass devolvió una respuesta de cámaras incompleta",
+ "Fly below {km} km to a covered region": "Desciende por debajo de {km} km sobre una región con cobertura",
+ "No feed here yet · {n} regions available": {
+ "one": "Aún no hay fuente aquí · {n} región disponible",
+ "many": "Aún no hay fuente aquí · {n} de regiones disponibles",
+ "other": "Aún no hay fuente aquí · {n} regiones disponibles"
+ },
+ "Wind speed field unavailable": "Campo de velocidad del viento no disponible",
+ "Decoder feeds": "Fuentes del decodificador",
+ "WebUSB + decoder feeds": "WebUSB + fuentes del decodificador",
+ "opening receiver": "abriendo el receptor",
+ "checking decoder feeds": "comprobando las fuentes del decodificador",
+ "listening": "escuchando",
+ "USB error": "error de USB",
+ "{count} heard": {
+ "one": "{count} aeronave captada",
+ "many": "{count} de aeronaves captadas",
+ "other": "{count} aeronaves captadas"
+ },
+ "{rate} msg/s": "{rate} msg/s",
+ "USB {rate} msg/s": "USB {rate} msg/s",
+ "{count} feeds live": {
+ "one": "{count} fuente en vivo",
+ "many": "{count} de fuentes en vivo",
+ "other": "{count} fuentes en vivo"
+ },
+ "feeds {names} stale": {
+ "one": "fuente {names} desactualizada",
+ "many": "fuentes {names} desactualizadas",
+ "other": "fuentes {names} desactualizadas"
+ },
+ "feeds {names} unreachable": {
+ "one": "fuente {names} inaccesible",
+ "many": "fuentes {names} inaccesibles",
+ "other": "fuentes {names} inaccesibles"
+ },
+ "feeds {names} invalid": {
+ "one": "fuente {names} no válida",
+ "many": "fuentes {names} no válidas",
+ "other": "fuentes {names} no válidas"
+ },
+ "unsaved provider keys": "las claves de proveedores sin guardar",
+ "Exit cockpit to fly to an aircraft": "Sal de la cabina para volar a una aeronave",
+ "Exit cockpit to fly to a satellite": "Sal de la cabina para volar a un satélite",
+ "Exit cockpit to frame contacts": "Sal de la cabina para encuadrar contactos",
+ "{feed} {count} ({seconds}s old)": "{feed} {count} (hace {seconds} s)",
+ "entry {n}": "n.º {n}",
+ "Upstream response too large": "Respuesta del origen demasiado grande",
+ "Included in bundle": "Incluido en el paquete",
+ "Missing bundle file — reimport its bundle": "Falta el archivo en el paquete — vuelve a importar su paquete",
+ "Source configured; file checked when loaded": "Fuente configurada; el archivo se comprobará al cargarlo",
+ "Source unavailable": "Fuente no disponible",
+ "Coverage tile failed": "No se pudo cargar la tesela de cobertura",
+ "Unknown": "Desconocido",
+ "USB work abandoned after a stalled transfer": "Trabajo USB cancelado tras una transferencia bloqueada",
+ "SDR decoder did not start; receiver stopped": "El decodificador SDR no arrancó; receptor detenido",
+ "SDR decoder stopped responding; receiver stopped": "El decodificador SDR dejó de responder; receptor detenido",
- "SDR decoder fell behind; receiver stopped": "El decodificador SDR se quedó atrás; receptor detenido"
++ "SDR decoder fell behind; receiver stopped": "El decodificador SDR se quedó atrás; receptor detenido",
++ "Gemini returned an oversized audio chunk": "Gemini devolvió un fragmento de audio demasiado grande",
++ "Gemini returned an unsupported audio format": "Gemini devolvió un formato de audio no compatible",
++ "Gemini returned an invalid audio sample rate": "Gemini devolvió una frecuencia de muestreo de audio no válida",
++ "Gemini returned incomplete PCM audio": "Gemini devolvió audio PCM incompleto",
++ "This browser does not support Gemini microphone audio": "Este navegador no admite audio del micrófono para Gemini",
++ "Microphone audio processing failed": "Falló el procesamiento del audio del micrófono",
++ "Gemini audio playback fell behind. Reconnect to continue.": "La reproducción de audio de Gemini se ha retrasado. Vuelve a conectar para continuar.",
++ "Gemini token response did not include an ephemeral credential": "La respuesta de Gemini no incluyó una credencial temporal",
++ "Invalid Gemini connection endpoint": "El destino de conexión de Gemini no es válido",
++ "Voice command context is too large": "El contexto del comando de voz es demasiado grande",
++ "Gemini reliable transport exceeded its queue limit. Start voice again.": "La cola de envío fiable de Gemini superó su límite. Vuelve a iniciar la voz.",
++ "Gemini reliable transport did not drain. Start voice again.": "La cola de envío fiable de Gemini no se vació. Vuelve a iniciar la voz.",
++ "Gemini token request failed (HTTP {status})": "Falló la solicitud de credencial de Gemini (HTTP {status})",
++ "Gemini token response did not include a valid model": "La respuesta de Gemini no incluyó un modelo válido",
++ "Gemini token response did not include session settings": "La respuesta de Gemini no incluyó la configuración de la sesión",
++ "Gemini session settings do not match the input mode": "La configuración de la sesión de Gemini no coincide con el modo de entrada",
++ "Gemini could not submit this input. Start voice again.": "Gemini no pudo enviar esta entrada. Vuelve a iniciar la voz.",
++ "Connecting to Gemini": "Conectando con Gemini",
++ "Gemini returned an oversized message": "Gemini devolvió un mensaje demasiado grande",
++ "Gemini Live connection failed. Check network access, then start voice again.": "Falló la conexión con Gemini Live. Comprueba el acceso a la red y vuelve a iniciar la voz.",
++ "Gemini Live connection ended. Start voice again for a new conversation.": "La conexión con Gemini Live terminó. Vuelve a iniciar la voz para una nueva conversación.",
++ "Gemini Live could not start. Start voice again to request a fresh session.": "Gemini Live no pudo iniciarse. Vuelve a iniciar la voz para solicitar una nueva sesión.",
++ "Start voice again for a fresh token and a new conversation.": "Vuelve a iniciar la voz para obtener una credencial nueva y comenzar otra conversación.",
++ "Start voice again to request a fresh session credential.": "Vuelve a iniciar la voz para solicitar una nueva credencial de sesión.",
++ "Microphone permission was denied. Allow microphone access and try again.": "Se denegó el permiso del micrófono. Permite el acceso al micrófono e inténtalo de nuevo.",
++ "Gemini connection timed out. Try again.": "Se agotó el tiempo de conexión con Gemini. Inténtalo de nuevo.",
++ "Gemini voice could not start": "No se pudo iniciar la voz de Gemini",
++ "Gemini did not finish the interrupted reply. Start voice again.": "Gemini no terminó la respuesta interrumpida. Vuelve a iniciar la voz.",
++ "Gemini session expiring; finishing the current reply": "La sesión de Gemini va a caducar; terminando la respuesta actual",
++ "Gemini rejected the voice session. Start voice again to request a fresh session.": "Gemini rechazó la sesión de voz. Vuelve a iniciar la voz para solicitar una nueva sesión.",
++ "Start voice again for a fresh session credential. If it repeats, check Gemini model and API access.": "Vuelve a iniciar la voz para obtener una nueva credencial de sesión. Si se repite, comprueba el modelo de Gemini y el acceso a la API.",
++ "Gemini action history is full. Start voice again for a fresh session.": "El historial de acciones de Gemini está lleno. Vuelve a iniciar la voz para una nueva sesión.",
++ "Gemini requested too many simultaneous actions": "Gemini solicitó demasiadas acciones simultáneas",
++ "Voice text command is too long": "El comando de voz escrito es demasiado largo",
++ "Gemini voice is not connected": "La voz de Gemini no está conectada",
++ "Gemini interrupted input exceeded its buffer or wait limit. Start voice again.": "La entrada interrumpida de Gemini superó el límite de búfer o de espera. Vuelve a iniciar la voz.",
++ "Gemini Live connection is expiring. Start voice again for a new conversation.": "La conexión con Gemini Live va a caducar. Vuelve a iniciar la voz para una nueva conversación.",
++ "Gemini voice sessions have a time limit. When a session expires, start voice again for a new conversation.": "Las sesiones de voz de Gemini tienen un límite de tiempo. Cuando caduque la sesión, vuelve a iniciar la voz para una nueva conversación.",
++ "Gemini Live voice control": "Control por voz con Gemini Live",
++ "Voice provider": "Proveedor de voz",
++ "Changing provider reconnects voice if it is on.": "Cambiar de proveedor vuelve a conectar la voz si está activada.",
++ "Gemini voice could not connect. Try again.": "No se pudo conectar la voz de Gemini. Inténtalo de nuevo.",
++ "Gemini voice requires a same-origin app request": "La voz de Gemini requiere una solicitud del mismo origen que la aplicación",
++ "Add a Gemini API key in Provider Settings": "Añade una clave de API de Gemini en los ajustes de proveedores",
++ "The Gemini Live model configuration is invalid": "La configuración del modelo de Gemini Live no es válida",
++ "Gemini voice is starting too often. Try again shortly.": "La voz de Gemini se está iniciando con demasiada frecuencia. Vuelve a intentarlo en breve.",
++ "Gemini quota is unavailable. Try again later.": "La cuota de Gemini no está disponible. Inténtalo más tarde.",
++ "Gemini access was refused. Check the API key and model access.": "Se denegó el acceso a Gemini. Comprueba la clave de API y el acceso al modelo.",
++ "Gemini Live is unavailable for the configured model.": "Gemini Live no está disponible para el modelo configurado.",
++ "Token request is too large": "La solicitud de credencial es demasiado grande",
++ "Use an empty JSON token request": "Usa una solicitud de credencial con un objeto JSON vacío"
+ }
diff --cc src/i18n/locales/ru.json
index 000000000,6a58ab901..f3a1d9537
mode 000000,100644..100644
--- a/src/i18n/locales/ru.json
+++ b/src/i18n/locales/ru.json
@@@ -1,0 -1,2961 +1,3012 @@@
+ {
+ "Flying to Austin, TX...": "Перелёт в Остин, Техас...",
+ "Restoring shared view...": "Восстановление общего вида...",
+ "Initializing systems...": "Инициализация систем...",
+ "Configuring viewer...": "Настройка просмотрщика...",
+ "Loading Google 3D Tiles...": "Загрузка Google 3D Tiles...",
+ "Loading the keyless globe...": "Загрузка глобуса без ключа...",
+ "Google 3D Tiles unavailable ({detail}). Loading the keyless globe...": "Google 3D Tiles недоступны ({detail}). Загрузка глобуса без ключа...",
+ "Close data attribution": "Закрыть атрибуцию данных",
+ "observed or mapped nearby context": "наблюдаемая или картографическая обстановка",
+ "no observed or mapped objects in current feeds": "нет наблюдаемых или картографированных объектов в текущих потоках",
+ "feed unavailable": "поток данных недоступен",
+ "feed stale": "поток данных устарел",
+ "Brightest naked-eye objects — CelesTrak visual group": "Самые яркие объекты невооружённым глазом — визуальная группа CelesTrak",
+ "COMMS": "СВЯЗЬ",
+ "Broadband constellation shell — shown only in DENSE mode": "Оболочка широкополосной группировки — только в режиме ПЛОТНО",
+ "STATION": "СТАНЦИЯ",
+ "Crewed stations and their visiting vehicles": "Пилотируемые станции и прибывающие к ним корабли",
+ "NAV": "NAV",
+ "GNSS navigation — GPS, GLONASS, Galileo": "Навигация GNSS — GPS, ГЛОНАСС, Galileo",
+ "GEO": "GEO",
+ "Geostationary belt — comms and weather, fixed over the equator": "Геостационарный пояс — связь и погода, неподвижно над экватором",
+ "VISUAL": "ВИДИМЫЕ",
+ "FISHING": "РЫБОЛОВНОЕ",
+ "TOWING": "БУКСИРОВКА",
+ "DREDGER": "ЗЕМСНАРЯД",
+ "DIVE OPS": "ВОДОЛАЗНОЕ",
+ "MILITARY": "ВОЕННОЕ",
+ "SAILING": "ПАРУСНИК",
+ "PLEASURE": "ПРОГУЛОЧНОЕ",
+ "PILOT": "ЛОЦМАН",
+ "SAR": "СПАСАТЕЛЬНОЕ",
+ "TUG": "БУКСИР",
+ "PORT TENDER": "ПОРТОВОЕ",
+ "ANTI-POLLUTION": "НЕФТЕСБОРЩИК",
+ "LAW ENFORCE": "ПАТРУЛЬНОЕ",
+ "MEDICAL": "МЕДИЦИНСКОЕ",
+ "HIGH-SPEED": "СКОРОСТНОЕ",
+ "PASSENGER": "ПАССАЖИРСКОЕ",
+ "CARGO": "ГРУЗОВОЕ",
+ "TANKER": "ТАНКЕР",
+ "OTHER": "ДРУГОЕ",
+ "Starting live contacts…": "Запуск контактов в реальном времени…",
+ "Opening space missions…": "Открытие космических миссий…",
+ "Scanning active events…": "Сканирование активных событий…",
+ "Live earthquakes and active fires, from USGS and NASA": "Землетрясения и активные пожары в реальном времени от USGS и NASA",
+ "It feels like a forbidden cockpit—then you realize the sources are public and the data is real.": "Будто вы в запретной кабине — а потом понимаете: источники открыты, а данные настоящие.",
+ "ENVIRONMENTAL": "ПРИРОДА",
+ "EARTH WATCH": "ДОЗОР ЗЕМЛИ",
+ "ACTIVE EVENTS": "АКТИВНЫЕ СОБЫТИЯ",
+ "Working…": "Работаем…",
+ "Could not open that mission{detail}. Retry or explore manually.": "Не удалось открыть эту миссию{detail}. Повторите попытку или исследуйте вручную.",
+ "This browser is blocking storage, so that could not be saved.": "Браузер блокирует хранилище, поэтому сохранить не удалось.",
+ "SUMMARY": "СВОДКА",
+ "Awaiting telemetry...": "Ожидание телеметрии...",
+ "REC": "REC",
+ "REMOVE": "УДАЛИТЬ",
+ "Remove {title} from this app's saved keys": "Удалить {title} из сохранённых ключей этого приложения",
+ "POWER UP · {count} KEYS WAITING": {
+ "one": "ЗАПУСК · {count} КЛЮЧ В ОЖИДАНИИ",
+ "few": "ЗАПУСК · {count} КЛЮЧА В ОЖИДАНИИ",
+ "many": "ЗАПУСК · {count} КЛЮЧЕЙ В ОЖИДАНИИ",
+ "other": "ЗАПУСК · {count} КЛЮЧА В ОЖИДАНИИ"
+ },
+ "POWERED UP": "ЗАПУЩЕНО",
+ "your app configuration": "ваша конфигурация приложения",
+ "your local .env": "ваш локальный .env",
+ "Saving…": "Сохранение…",
+ "Save failed ({status}).": "Не удалось сохранить ({status}).",
+ "Save failed: {detail}": "Не удалось сохранить: {detail}",
+ "Paste at least one key first.": "Сначала вставьте хотя бы один ключ.",
+ "Saved to {store}. Restarting — this page reloads itself.": "Сохранено: {store}. Перезапуск — страница перезагрузится сама.",
+ "Remove this key from your saved configuration?": "Удалить этот ключ из сохранённой конфигурации?",
+ "Removed from {store}. Restarting — this page reloads itself.": "Удалено: {store}. Перезапуск — страница перезагрузится сама.",
+ "More flight-polling credits (anonymous works without)": "Повышенный лимит запросов рейсов (анонимно работает и без ключа)",
+ "Street-level imagery and coverage in the Street Level layer. Free: register an app in the Mapillary developer dashboard and paste its Client Token": "Уличные снимки и покрытие в слое «Уличные снимки». Бесплатно: зарегистрируйте приложение в панели разработчика Mapillary и вставьте его клиентский токен (Client Token).",
+ "Public space-missions access needs no key. Leave blank for standard use; paid tokens only raise request limits.": "Общедоступные данные космических миссий не требуют ключа. Для обычного использования оставьте поле пустым; платные токены только повышают лимиты запросов.",
+ "Optional paid token — public access works without one": "Необязательный платный токен — публичный доступ работает без него",
+ "Places context + Street View fallback; optional separate key": "Контекст Places + резерв: Просмотр улиц; отдельный ключ — по желанию",
+ "Voice control — API key or ChatGPT OAuth": "Голосовое управление — ключ API или ChatGPT OAuth",
+ "Live ships, worldwide": "Суда в реальном времени по всему миру",
+ "Live active-fire detections": "Обнаружение активных пожаров в реальном времени",
+ "Real live traffic (keyless runs a simulation)": "Настоящие пробки в реальном времени (без ключа — симуляция)",
+ "Bing imagery map stacks + world terrain": "Снимки Bing + рельеф мира",
+ "Global Context navigation": "Навигация глобального контекста",
+ "Previous — prior visited contact in the 250 km window": "Назад — предыдущий посещённый контакт в радиусе 250 км",
+ "PREVIOUS": "ПРЕД.",
+ "FOCUS": "ФОКУС",
+ "Next — nearest unvisited contact in the 250 km window": "Далее — ближайший непосещённый контакт в радиусе 250 км",
+ "NEXT": "СЛЕД.",
+ "Open-source mapped/observed context. Missing broadcasts, unloaded map areas, or unmapped sites are not evidence of absence.": "Контекст из открытых источников. Отсутствие трансляций, незагруженные области карты или неотмеченные объекты — не доказательство отсутствия.",
+ "CONTEXT READY": "КОНТЕКСТ ГОТОВ",
+ "GLOBAL CONTEXT OFF": "ГЛОБАЛЬНЫЙ КОНТЕКСТ ВЫКЛ.",
+ "SELECT A FLIGHT, VESSEL, OR MAPPED INSTALLATION": "ВЫБЕРИТЕ РЕЙС, СУДНО ИЛИ ОБЪЕКТ НА КАРТЕ",
+ "ENABLE TO LOAD OBSERVED / MAPPED PROXIMITY": "ВКЛЮЧИТЕ ДЛЯ ЗАГРУЗКИ НАБЛЮДАЕМОГО / КАРТОГРАФИРОВАННОГО ОКРУЖЕНИЯ",
+ "Unavailable": "Недоступно",
+ "Focus {label}": "Фокус на {label}",
+ "HDG {value}°": "КУРС {value}°",
+ "BRG {value}°": "ПЕЛ. {value}°",
+ "BRG —": "ПЕЛ. —",
+ "CRS {value}°": "ПУТЬ {value}°",
+ "Military flights": "Военные рейсы",
+ "AIS vessels": "Суда AIS",
+ "Mapped installations": "Картографированные объекты",
+ "CURRENT VIEWPORT ONLY": "ТОЛЬКО ТЕКУЩАЯ ОБЛАСТЬ ОБЗОРА",
+ "WITHIN {km} KM": "В РАДИУСЕ {km} КМ",
+ "Flights": "Рейсы",
+ "syncing {count} city feeds...": "синхронизация городских потоков: {count}...",
+ "scanning nearby systems...": "поиск ближайших систем...",
+ "Station {id}": "Станция {id}",
+ "Station": "Станция",
+ "🚲 {bikes} avail · {docks} docks · {capacity} cap": "🚲 доступно {bikes} · своб. мест {docks} · вмест. {capacity}",
+ "⚠️ Not installed": "⚠️ Не установлена",
+ "⚠️ Not renting": "⚠️ Не выдаёт",
+ "⚠️ Not returning": "⚠️ Не принимает",
+ "HDG {value}° (ESTIMATED)": "КУРС {value}° (ОЦЕНКА)",
+ "{count} CAMERAS STANDING BY · NO CAMERA SELECTED · CLICK A CAMERA TO ACTIVATE": "КАМЕР В ГОТОВНОСТИ: {count} · КАМЕРА НЕ ВЫБРАНА · НАЖМИТЕ КАМЕРУ ДЛЯ АКТИВАЦИИ",
+ "No cameras available in catalog.": "В каталоге нет доступных камер.",
+ "{city} CCTV": "CCTV: {city}",
+ "FOV {value}°": "ОБЗОР {value}°",
+ "COVERAGE {value}km²": "ОХВАТ {value} КМ²",
+ "OVERLAP {count} cams": "ПЕРЕКРЫТИЕ {count} кам.",
+ "ISOLATED VIEW": "ИЗОЛИРОВАННЫЙ ВИД",
+ "PROJ MONITOR": "ПРОЕКЦ. МОНИТОР",
+ "PROJ OFF": "ПРОЕКЦ. ВЫКЛ.",
+ "VIEWSHED": "ЗОНА ВИДИМОСТИ",
+ "CAL {value}": "КАЛИБР. {value}",
+ "SRC {value}": "ИСТ. {value}",
+ "{value} CONTEXT": "КОНТЕКСТ {value}",
+ "Focus fire detection {title}, {details}": "Фокус на очаге пожара {title}, {details}",
+ "{value} conf": "увер.: {value}",
+ "{value} ago": "{value} назад",
+ "sensor n/a": "сенсор н/д",
+ "FIRE · {frp} MW": "ПОЖАР · {frp} МВт",
+ "NIGHT": "НОЧЬ",
+ "▲ {frp} MW": "▲ {frp} МВт",
+ "FIRE": "ПОЖАР",
+ "FIRES": "ПОЖ.",
+ "max {value} MW": "макс. {value} МВт",
+ "new {value}": "последний {value}",
+ "just now": "только что",
+ "<1m ago": "<1 мин назад",
+ "{count}m ago": "{count} мин назад",
+ "{count}h ago": "{count} ч назад",
+ "STALE · cached {age}": "УСТАРЕЛ · кэш {age}",
+ "STALE": "УСТАРЕЛ",
+ "refreshing...": "обновление...",
+ "loading...": "загрузка...",
+ "KEY REQUIRED": "ТРЕБУЕТСЯ КЛЮЧ",
+ "LIVE · updated {age}": "ОНЛАЙН · обновлено {age}",
+ "Retrying mapped sites…": "Повторный запрос объектов…",
+ "Fetching mapped sites…": "Загрузка объектов…",
+ "Zoom in to search mapped installations": "Приблизьте, чтобы искать картографированные объекты",
+ "Showing cached mapped sites": "Показаны объекты из кэша",
+ "Mapped sites not loaded": "Объекты не загружены",
+ "Mapped sites loaded": "Объекты загружены",
+ "Overpass rate-limited": "Overpass: превышен лимит запросов",
+ "Overpass timed out": "Overpass: истекло время ожидания",
+ "Overpass could not complete the query": "Overpass не смог завершить запрос",
+ "Overpass temporarily unavailable": "Overpass временно недоступен",
+ "loading mapped installation context": "загрузка контекста объектов",
+ "{reason} — retrying in {seconds}s": "{reason} — повтор через {seconds} с",
+ "{reason} — retry pending": "{reason} — ожидается повтор",
+ "MAPPED INSTALLATION": "КАРТОГРАФИРОВАННЫЙ ОБЪЕКТ",
+ "LAUNCH SITE · {site}": "МЕСТО ПУСКА · {site}",
+ "LAUNCH SITE": "МЕСТО ПУСКА",
+ "T−{time} · {mission}": "T−{time} · {mission}",
+ "LAUNCH STANDBY": "ОЖИДАНИЕ ПУСКА",
+ "LIFTOFF · {mission}": "СТАРТ · {mission}",
+ "ASCENT REPLAY · {mission}": "ПОВТОР ВЫВЕДЕНИЯ · {mission}",
+ "ASCENT ESTIMATE · {mission}": "РАСЧЁТНОЕ ВЫВЕДЕНИЕ · {mission}",
+ "STAGE RE-ENTRY / RECOVERY · {mission}": "ВХОД В АТМОСФЕРУ / ВОЗВРАТ СТУПЕНИ · {mission}",
+ "ORBIT REPLAY · {mission}": "ПОВТОР ОРБИТЫ · {mission}",
+ "PAUSED · {title}": "ПАУЗА · {title}",
+ "UNSPECIFIED": "НЕ УКАЗАНО",
+ "UNAVAILABLE": "НЕДОСТУПНО",
+ "+{count} additional payload records": "+{count} доп. записи о полезной нагрузке",
+ "PAYLOAD DATA UNAVAILABLE": "ДАННЫЕ ПОЛЕЗНОЙ НАГРУЗКИ НЕДОСТУПНЫ",
+ "{value} KM DOWNRANGE": "{value} КМ ПО ТРАССЕ",
+ "POSITION UNAVAILABLE": "ПОЗИЦИЯ НЕДОСТУПНА",
+ "FLIGHT {count}": "ПОЛЁТ {count}",
+ "REUSED": "ЛЕТАВШАЯ",
+ "NO STAGE RE-ENTRY / RECOVERY DATA": "НЕТ ДАННЫХ О ВХОДЕ В АТМОСФЕРУ / ВОЗВРАТЕ СТУПЕНИ",
+ "{count} / 30D": "{count} / 30 ДН.",
+ "NO MISSIONS AVAILABLE IN THE CURRENT 30-DAY WINDOW": "НЕТ МИССИЙ В ТЕКУЩЕМ 30-ДНЕВНОМ ОКНЕ",
+ "DATE UNAVAILABLE": "ДАТА НЕДОСТУПНА",
+ "UNSPECIFIED OPERATOR": "ОПЕРАТОР НЕ УКАЗАН",
+ "Select {mission}": "Выбрать {mission}",
+ "{value} KM": "{value} КМ",
+ "{value} KM/S": "{value} КМ/С",
+ "SELECTED SPACE MISSION": "ВЫБРАННАЯ КОСМИЧЕСКАЯ МИССИЯ",
+ "Show all missions": "Показать все миссии",
+ "Deselect mission": "Снять выбор миссии",
+ "MISSION": "МИССИЯ",
+ "STATUS · ": "СТАТУС · ",
+ "LAUNCH SITE · ": "МЕСТО ПУСКА · ",
+ "LAUNCH TIME · ": "ВРЕМЯ ПУСКА · ",
+ "ORBIT · ": "ОРБИТА · ",
+ "ASCENT PATH · ": "ТРАЕКТОРИЯ ВЫВЕДЕНИЯ · ",
+ "CURRENT DISTANCE FROM EARTH · ": "ТЕКУЩЕЕ РАССТОЯНИЕ ОТ ЗЕМЛИ · ",
+ "SATELLITE SPEED · ": "СКОРОСТЬ СПУТНИКА · ",
+ "PAYLOAD": "ПОЛЕЗНАЯ НАГРУЗКА",
+ "NAME": "НАЗВАНИЕ",
+ "TYPE": "ТИП",
+ "DESTINATION": "ПУНКТ НАЗНАЧЕНИЯ",
+ "STAGE / RE-ENTRY / RECOVERY": "СТУПЕНЬ / ВХОД В АТМОСФЕРУ / ВОЗВРАТ",
+ "STAGE": "СТУПЕНЬ",
+ "STATUS": "СТАТУС",
+ "FINAL POSITION": "КОНЕЧНОЕ ПОЛОЖЕНИЕ",
+ "REPLAY SPEED": "СКОРОСТЬ ПОВТОРА",
+ "Replay speed multiplier": "Множитель скорости повтора",
+ "REPLAY ASCENT": "ПОВТОРИТЬ ВЫВЕДЕНИЕ",
+ "Previous mission": "Предыдущая миссия",
+ "PREV": "ПРЕД.",
+ "Next mission": "Следующая миссия",
+ "SHOW ALL / DESELECT": "ПОКАЗАТЬ ВСЕ / СНЯТЬ ВЫБОР",
+ "Pause replay": "Приостановить повтор",
+ "Cancel replay": "Отменить повтор",
+ "EST. DOWNRANGE": "РАСЧЁТ ПО ТРАССЕ",
+ "PLANNED · ": "ПЛАН · ",
+ "SUPPLIED TRAJECTORY POINTS": "ПРЕДОСТАВЛЕННЫЕ ТОЧКИ ТРАЕКТОРИИ",
+ "RECONSTRUCTED ESTIMATE": "РЕКОНСТРУИРОВАННАЯ ОЦЕНКА",
+ "Replay the estimated ascent with a following camera": "Повторить расчётное выведение с камерой сопровождения",
+ "Resume replay": "Возобновить повтор",
+ "T minus {seconds}": "T минус {seconds}",
+ "Preparing launch site": "Подготовка стартовой площадки",
+ "Liftoff": "Старт",
+ "Ascent replay": "Повтор выведения",
+ "Orbit replay": "Повтор: орбита",
+ ", paused": ", пауза",
+ "Alt unknown": "Высота неизвестна",
+ "Type unknown": "Тип неизвестен",
+ "Reg unknown": "Рег. номер неизвестен",
+ "Operator unknown": "Оператор неизвестен",
+ "All": "Все",
+ "News": "Новости",
+ "Talk": "Разговорное",
+ "Weather / Emergency": "Погода / ЧС",
+ "Public Safety": "Общественная безопасность",
+ "Aviation / Marine": "Авиация / Море",
+ "Traffic / Transit": "Трафик / Транспорт",
+ "Music": "Музыка",
+ "Other": "Другое",
+ "Add the full Starlink broadband shell (thousands of extra points)": "Добавить полную широкополосную оболочку Starlink (тысячи дополнительных точек)",
+ "Loading the Starlink shell…": "Загрузка оболочки Starlink…",
+ "Starlink {detail} — click to retry": "Starlink: {detail} — нажмите, чтобы повторить",
+ "load failed": "ошибка загрузки",
+ "Showing the full Starlink shell — click for the core catalog only": "Показана полная оболочка Starlink — нажмите, чтобы оставить только основной каталог",
+ "DENSE ···": "ПЛОТНО ···",
+ "DENSE ✕": "ПЛОТНО ✕",
+ "DENSE": "ПЛОТНЫЙ",
+ "Syncing flow · Roads: {source}": "Синхронизация потока · Дороги: {source}",
+ "LIVE · Roads: {source} · Roads without flow hidden": "ОНЛАЙН · Дороги: {source} · Дороги без потока скрыты",
+ "LIVE · Roads: {source} · No flow roads in view": "ОНЛАЙН · Дороги: {source} · В кадре нет дорог с потоком",
+ "LIVE · Roads: {source} · Flow {percent}%": "ОНЛАЙН · Дороги: {source} · Поток {percent}%",
+ "SIMULATED · Roads: {source} · Flow {percent}%": "СИМУЛЯЦИЯ · Дороги: {source} · Поток {percent}%",
+ "Syncing flow · Roads: OpenStreetMap · Flow: TomTom · Unmatched: simulated": "Синхронизация потока · Дороги: OpenStreetMap · Поток: TomTom · Без совпадений: симуляция",
+ "LIVE · Roads: OpenStreetMap · Flow: TomTom · {percent}% cov · Unmatched: simulated": "ОНЛАЙН · Дороги: OpenStreetMap · Поток: TomTom · охват {percent}% · Без совпадений: симуляция",
+ "LIVE · Roads: OpenStreetMap · Flow: TomTom · {percent}% cov": "ОНЛАЙН · Дороги: OpenStreetMap · Поток: TomTom · охват {percent}%",
+ "SIMULATED · Roads: OpenStreetMap · Flow: TomTom (no matches)": "СИМУЛЯЦИЯ · Дороги: OpenStreetMap · Поток: TomTom (нет совпадений)",
+ "SIMULATED — traffic service unreachable": "СИМУЛЯЦИЯ — сервис трафика недоступен",
+ "SIMULATED — add TomTom key for live": "СИМУЛЯЦИЯ — добавьте ключ TomTom для режима онлайн",
+ "POS: LIVE": "ПОЗ: ОНЛАЙН",
+ "POS: {time}Z": "ПОЗ: {time}Z",
+ "AIS: {name}": "AIS: {name}",
+ "{type} SPD: {speed} HDG: {heading}": "{type} СКОР: {speed} КУРС: {heading}",
+ "VESSEL": "СУДНО",
+ "AIS: --": "AIS: --",
+ "awaiting first AIS position…": "ожидание первой позиции AIS…",
+ "awaiting usable AIS positions…": "ожидание пригодных позиций AIS…",
+ "awaiting first AIS message…": "ожидание первого сообщения AIS…",
+ "{label} unavailable: {hint}": "{label}: недоступно — {hint}",
+ "Needs {envVars} — add it in Provider Settings": "Нужен {envVars} — добавьте его в «Настройках провайдеров»",
+ "{label} is unavailable": "{label}: недоступно",
+ "This map stack": "Этот набор карт",
+ "Updated: {scene} / {shot}": "Обновлено: {scene} / {shot}",
+ "Camera unavailable — exit cockpit first": "Камера недоступна — сначала выйдите из кабины",
+ "No shots to run": "Нет кадров для воспроизведения",
+ "Error: {message}": "Ошибка: {message}",
+ "Project exported": "Проект экспортирован",
+ "Ready": "Готово",
+ "Could not exit {mode} — scene layers may be refused": "Не удалось выйти из режима {mode} — слои сцены могут быть отклонены",
+ "Loaded: {scene} / {shot}": "Загружено: {scene} / {shot}",
+ "Global Flights Radar": "Глобальный радар рейсов",
+ "Orbital Watch": "Орбитальный дозор",
+ "Thermal Threat Board": "Панель тепловых угроз",
+ "City Overload": "Перегрузка города",
+ "Omniscience Pullback": "Отъезд к всевидению",
+ "Cannot capture shot: camera not ready": "Не удалось сделать кадр: камера не готова",
+ "Shot {n}": "Кадр {n}",
+ "Captured: {scene} / {shot}": "Снято: {scene} / {shot}",
+ "Select a shot first": "Сначала выберите кадр",
+ "Running {index}/{total}: {scene} / {shot}": "Воспроизведение {index}/{total}: {scene} / {shot}",
+ "Scene run complete": "Воспроизведение сцены завершено",
+ "CCTV layer unavailable": "Слой CCTV недоступен",
+ "Link copied!": "Ссылка скопирована!",
+ "Copy failed": "Не удалось скопировать",
+ "VISUAL PRESETS": "ПРЕСЕТЫ",
+ "LOCATION": "МЕСТО",
+ "DISPLAY": "ЭКРАН",
+ "CONTACT": "КОНТАКТ",
+ "CONTACTS — nearest planes · vessels · sites": "КОНТАКТЫ — ближайшие самолёты · суда · объекты",
+ "SPACE MISSIONS — launches & orbital assets": "КОСМИЧЕСКИЕ МИССИИ — пуски и орбитальные аппараты",
+ "LIVE SIGNALS": "СИГНАЛЫ ОНЛАЙН",
+ "MAP SOURCE": "ИСТОЧНИК КАРТЫ",
+ "Map source": "Источник карты",
+ "CCTV calibration saved": "Калибровка CCTV сохранена",
+ "ADJUST ON": "НАСТРОЙКА ВКЛ",
+ "ADJUST": "НАСТРОЙКА",
+ "CCTV calibration reset": "Калибровка CCTV сброшена",
+ "FRAME · UNAVAILABLE": "КАДР · НЕДОСТУПЕН",
+ "SOURCE · UNKNOWN": "ИСТОЧНИК · НЕИЗВЕСТЕН",
+ "FRAME · LOADING": "КАДР · ЗАГРУЗКА",
+ "VIEWSHED ON": "ВИДИМОСТЬ ВКЛ",
+ "COVERAGE ON": "ОХВАТ ВКЛ",
+ "COVERAGE OFF": "ОХВАТ ВЫКЛ",
+ "RAW PRIOR": "ИСХОДНАЯ ОЦЕНКА",
+ "AUTO HOP ON": "АВТОСМЕНА ВКЛ",
+ "AUTO HOP OFF": "АВТОСМЕНА ВЫКЛ",
+ "PROJECTION ON": "ПРОЕКЦИЯ ВКЛ",
+ "PROJECTION OFF": "ПРОЕКЦИЯ ВЫКЛ",
+ "CAL · EDITED (UNSAVED)": "КАЛИБР. · ИЗМЕНЕНО (НЕ СОХР.)",
+ "CAL · {badge}": "КАЛИБР. · {badge}",
+ "MONITOR": "МОНИТОР",
+ "OFF": "ВЫКЛ",
+ "{city} · HDG {heading} · FOV {fov} · RANGE {range}m · {projection}{calBadge} · {provider}{status}": "{city} · КУРС {heading} · ОБЗОР {fov} · ДАЛЬН. {range} м · {projection}{calBadge} · {provider}{status}",
+ "{count} cameras loaded · click a camera to activate": {
+ "one": "Загружена {count} камера · щёлкните по камере, чтобы активировать",
+ "few": "Загружено {count} камеры · щёлкните по камере, чтобы активировать",
+ "many": "Загружено {count} камер · щёлкните по камере, чтобы активировать",
+ "other": "Загружено {count} камеры · щёлкните по камере, чтобы активировать"
+ },
+ "{count} cameras loaded · enable CCTV to activate": {
+ "one": "Загружена {count} камера · включите CCTV, чтобы активировать",
+ "few": "Загружено {count} камеры · включите CCTV, чтобы активировать",
+ "many": "Загружено {count} камер · включите CCTV, чтобы активировать",
+ "other": "Загружено {count} камеры · включите CCTV, чтобы активировать"
+ },
+ "Enable CCTV to load camera intersections": "Включите CCTV, чтобы загрузить камеры на перекрёстках",
+ "Enable CCTV to start camera-linked intelligence summaries.": "Включите CCTV, чтобы запускать сводки по камерам.",
+ "No summary available.": "Сводка недоступна.",
+ "loading frames": "загрузка кадров",
+ "camera grid ready": "сетка камер готова",
+ "CCTV ON": "CCTV ВКЛ",
+ "CCTV OFF": "CCTV ВЫКЛ",
+ "CALIBRATED": "ОТКАЛИБРОВАНО",
+ "CURATED": "ВЫВЕРЕНО",
+ "Clearing selected data layers": "Очистка выбранных слоёв данных",
+ "Clear selected data layers": "Очистить выбранные слои данных",
+ "CONDITIONS UNKNOWN": "УСЛОВИЯ НЕИЗВЕСТНЫ",
+ "CLEAR": "ЯСНО",
+ "PARTLY CLOUDY": "ПЕРЕМЕННАЯ ОБЛАЧНОСТЬ",
+ "OVERCAST": "ПАСМУРНО",
+ "ACQUIRING REGIONAL NEWS": "ЗАГРУЗКА РЕГИОНАЛЬНЫХ НОВОСТЕЙ",
+ "REGIONAL NEWS UNAVAILABLE": "РЕГИОНАЛЬНЫЕ НОВОСТИ НЕДОСТУПНЫ",
+ "RESOLVING REGION": "ОПРЕДЕЛЕНИЕ РЕГИОНА",
+ "REGION UNAVAILABLE": "РЕГИОН НЕДОСТУПЕН",
+ "FOG": "ТУМАН",
+ "NO RECENT LOCATION MATCHES": "НЕТ СВЕЖИХ СОВПАДЕНИЙ ПО МЕСТУ",
+ "DRIZZLE": "МОРОСЬ",
+ "RAIN": "ДОЖДЬ",
+ "{domain} · {age}": "{domain} · {age}",
+ "SOURCE": "ИСТОЧНИК",
+ "SNOW": "СНЕГ",
+ "RAIN SHOWERS": "ЛИВНИ",
+ "SNOW SHOWERS": "ЛИВНЕВЫЙ СНЕГ",
+ "THUNDERSTORM": "ГРОЗА",
+ "CLOUD {pct}%": "ОБЛАЧНОСТЬ {pct}%",
+ "CLOUD UNKNOWN": "ОБЛАЧНОСТЬ НЕИЗВЕСТНА",
+ "MIXED CONDITIONS": "СМЕШАННЫЕ УСЛОВИЯ",
+ "{source} · LOCATION QUERY": "{source} · ЗАПРОС ПО МЕСТУ",
+ "REGIONAL NEWS": "НОВОСТИ РЕГИОНА",
+ "CYCLE ON": "АВТО: ВКЛ",
+ "CYCLE OFF": "АВТО: ВЫКЛ",
+ "Stop automatic page cycling. Previous, Next, and the SIG/NEWS/LOCAL tabs stay available.": "Остановить автоматическое листание страниц. Кнопки ПРЕД./СЛЕД. и вкладки СИГН./НОВОСТИ/МЕСТН. остаются доступны.",
+ "Cycle briefing pages automatically every 9 seconds (Signals → News → Local). Pauses while you hover or focus the panel. Live signal data refreshes continuously either way.": "Автоматически листать страницы брифинга каждые 9 секунд (Сигналы → Новости → Местное). При наведении или фокусе на панели листание приостанавливается. Данные сигналов в реальном времени в любом случае обновляются непрерывно.",
+ "{cohort}, Unavailable": "{cohort}, недоступно",
+ "AHEAD": "ПО КУРСУ",
+ "{side} {angle}": "{side} {angle}",
+ "L": "Л",
+ "R": "П",
+ "{count} INPUTS UNKNOWN · NOT AN ALL-CLEAR": {
+ "one": "{count} ИСТОЧНИК ДАННЫХ НЕИЗВЕСТЕН · ОТСУТСТВИЕ УГРОЗ НЕ ПОДТВЕРЖДЕНО",
+ "few": "{count} ИСТОЧНИКА ДАННЫХ НЕИЗВЕСТНЫ · ОТСУТСТВИЕ УГРОЗ НЕ ПОДТВЕРЖДЕНО",
+ "many": "{count} ИСТОЧНИКОВ ДАННЫХ НЕИЗВЕСТНО · ОТСУТСТВИЕ УГРОЗ НЕ ПОДТВЕРЖДЕНО",
+ "other": "{count} ИСТОЧНИКА ДАННЫХ НЕИЗВЕСТНО · ОТСУТСТВИЕ УГРОЗ НЕ ПОДТВЕРЖДЕНО"
+ },
+ "AVAILABLE INPUTS CURRENT · NOT AN ALL-CLEAR": "ДОСТУПНЫЕ ДАННЫЕ АКТУАЛЬНЫ · ОТСУТСТВИЕ УГРОЗ НЕ ПОДТВЕРЖДЕНО",
+ "CONTEXT STANDBY": "КОНТЕКСТ В ОЖИДАНИИ",
+ "ENABLE GLOBAL CONTEXT FOR PROXIMITY PINGS": "ВКЛЮЧИТЕ ГЛОБАЛЬНЫЙ КОНТЕКСТ ДЛЯ ПИНГОВ ПОБЛИЗОСТИ",
+ "CONTACT LOST · LAST KNOWN READOUT · NOT AN ALL-CLEAR": "КОНТАКТ ПОТЕРЯН · ПОСЛЕДНИЕ ИЗВЕСТНЫЕ ДАННЫЕ · ОТСУТСТВИЕ УГРОЗ НЕ ПОДТВЕРЖДЕНО",
+ "CONTACT LOST · {subject}": "КОНТАКТ ПОТЕРЯН · {subject}",
+ "SUBJECT LEFT ITS FEED · READOUT HOLDING LAST KNOWN": "ОБЪЕКТ ВЫПАЛ ИЗ ПОТОКА · ПОКАЗАНЫ ПОСЛЕДНИЕ ДАННЫЕ",
+ "{cohort} · {contact}": "{cohort} · {contact}",
+ "NO AVAILABLE EXAMPLE": "НЕТ ДОСТУПНОГО ПРИМЕРА",
+ "ACQUIRING SURFACE": "ЗАХВАТ ПОВЕРХНОСТИ",
+ "SURFACE FALLBACK": "РЕЗЕРВНАЯ ПОВЕРХНОСТЬ",
+ "STALE FEED": "ПОТОК УСТАРЕЛ",
+ "LIVE TRACK": "ТРЕК ОНЛАЙН",
+ "{aircraftClass} · {feedState} · COURSE ALIGNED": "{aircraftClass} · {feedState} · КУРС СОВМЕЩЁН",
+ "COMMERCIAL": "ГРАЖДАНСКИЙ",
+ "UNKNOWN": "НЕИЗВЕСТНО",
+ "ARROW · ESTIMATED DIRECTION": "СТРЕЛКА · РАСЧЁТНОЕ НАПРАВЛЕНИЕ",
+ "ROUTE DATA UNAVAILABLE": "ДАННЫЕ МАРШРУТА НЕДОСТУПНЫ",
+ "DEST {bearing}": "НАЗН. {bearing}",
+ "Disable cockpit weather effects": "Выключить погодные эффекты кабины",
+ "Enable cockpit weather effects": "Включить погодные эффекты кабины",
+ "ON": "ВКЛ",
+ "Night vision": "Ночное видение",
+ "Thermal": "Тепловизор",
+ "Anime": "Аниме",
+ "Noir": "Нуар",
+ "Snow": "Снег",
+ "Current cockpit vision style: {style}. Activate for next style.": "Текущий стиль обзора кабины: {style}. Активируйте, чтобы переключить на следующий.",
+ "Current style: {style} — click for next": "Текущий стиль: {style} — нажмите для следующего",
+ "AIRCRAFT": "САМОЛЁТ",
+ "Expand Contact panel": "Развернуть панель контактов",
+ "Collapse Contact panel": "Свернуть панель контактов",
+ "Expand contact panel": "Развернуть панель контактов",
+ "Collapse contact panel": "Свернуть панель контактов",
+ "Collapse cockpit briefing panel": "Свернуть панель брифинга кабины",
+ "Expand cockpit briefing panel": "Развернуть панель брифинга кабины",
+ "Collapse briefing panel": "Свернуть панель брифинга",
+ "Expand briefing panel": "Развернуть панель брифинга",
+ "OBSERVED / MAPPED PINGS": "НАБЛЮДАЕМЫЕ / НАНЕСЁННЫЕ ПИНГИ",
+ "SOURCE-BACKED EVENTS · NO SYNTHETIC NEWS": "СОБЫТИЯ ИЗ ИСТОЧНИКОВ · БЕЗ ВЫМЫСЛА",
+ "LATEST LOCATION-MATCHED REPORTING": "СВЕЖИЕ НОВОСТИ ПО МЕСТУ",
+ "LOCAL INFO": "МЕСТНЫЕ ДАННЫЕ",
+ "PLACE / CONDITIONS / POSITION": "МЕСТО / ПОГОДА / КООРД.",
+ "TIME UNKNOWN": "ВРЕМЯ НЕИЗВЕСТНО",
+ "{count}M AGO": "{count} МИН НАЗАД",
+ "{count}H AGO": "{count} Ч НАЗАД",
+ "{count}D AGO": "{count} ДН. НАЗАД",
+ "DIR UNKNOWN": "НАПР. НЕИЗВЕСТНО",
+ "{aircraftClass} · CURRENT": "{aircraftClass} · ТЕКУЩИЙ",
+ "MILITARY FLIGHT": "ВОЕННЫЙ РЕЙС",
+ "COMMERCIAL FLIGHT": "ГРАЖДАНСКИЙ РЕЙС",
+ "{aircraftClass} · {distance}": "{aircraftClass} · {distance}",
+ "DISTANCE UNKNOWN": "ДИСТАНЦИЯ НЕИЗВЕСТНА",
+ "{count} INPUTS UNKNOWN": {
+ "one": "{count} ИСТОЧНИК ДАННЫХ НЕИЗВЕСТЕН",
+ "few": "{count} ИСТОЧНИКА ДАННЫХ НЕИЗВЕСТНЫ",
+ "many": "{count} ИСТОЧНИКОВ ДАННЫХ НЕИЗВЕСТНО",
+ "other": "{count} ИСТОЧНИКА ДАННЫХ НЕИЗВЕСТНО"
+ },
+ "SOURCE STATUS UNAVAILABLE": "СТАТУС ИСТОЧНИКА НЕДОСТУПЕН",
+ "Select flight {title}": "Выбрать рейс {title}",
+ "TRACK ACQUIRED": "ЦЕЛЬ ЗАХВАЧЕНА",
+ "{label} · COURSE {heading}°": "{label} · КУРС {heading}°",
+ "Restore real aircraft": "Вернуть реальный самолёт",
+ "Reclassify as TR-3B": "Переклассифицировать как TR-3B",
+ "No selected data layers": "Нет выбранных слоёв данных",
+ "{count} data layers could not be cleared": {
+ "one": "Не удалось очистить {count} слой данных",
+ "few": "Не удалось очистить {count} слоя данных",
+ "many": "Не удалось очистить {count} слоёв данных",
+ "other": "Не удалось очистить {count} слоя данных"
+ },
+ "Cleared {count} data layers": {
+ "one": "Очищен {count} слой данных",
+ "few": "Очищено {count} слоя данных",
+ "many": "Очищено {count} слоёв данных",
+ "other": "Очищено {count} слоя данных"
+ },
+ "Selected data layers could not be cleared": "Не удалось очистить выбранные слои данных",
+ "Context could not restore every layer; try again": "Контекст: не удалось восстановить все слои; попробуйте снова",
+ "Nearby installations refreshed": "Ближайшие объекты обновлены",
+ "Nearby installations could not be refreshed; try again": "Не удалось обновить ближайшие объекты; попробуйте снова",
+ "Contacts could not complete the requested transition; try again": "Не удалось переключить режим «Контакты»; попробуйте снова",
+ "Space Missions could not complete the requested transition; try again": "Не удалось переключить режим «Космические миссии»; попробуйте снова",
+ "{layerId} could not {action} cleanly": "Не удалось корректно {action} слой {layerId}",
+ "start": "запустить",
+ "stop": "остановить",
+ "Space Missions cancellation could not restore the previous layer state": "Не удалось восстановить прежнее состояние слоёв после отмены космических миссий",
+ "That layer is unavailable in the current Context mode": "Этот слой недоступен в текущем режиме контекста",
+ "{mode} could not start because another layer did not stop cleanly": "Не удалось запустить режим «{mode}»: другой слой не остановился корректно",
+ "Space Missions": "Космические миссии",
+ "Context": "Контекст",
+ "LOADING": "ЗАГРУЗКА",
+ "DEGRADED": "ПЕРЕБОИ",
+ "PARTIAL": "ЧАСТИЧНО",
+ "FALLBACK": "РЕЗЕРВ",
+ "Live Flights": "Рейсы онлайн",
+ "Military Flights": "Военные рейсы",
+ "Earthquakes (24h)": "Землетрясения (24 ч)",
+ "Satellites": "Спутники",
+ "Space Missions (30d)": "Космические миссии (30 дн.)",
+ "Street Traffic": "Дорожный трафик",
+ "CCTV": "CCTV",
+ "Radio": "Радио",
+ "Bikeshare": "Велошеринг",
+ "Live AIS Vessels": "Суда AIS онлайн",
+ "Mapped Installations": "Объекты на карте",
+ "Global Context": "Глобальный контекст",
+ "Datacenters": "Дата-центры",
+ "Dams": "Плотины",
+ "Submarine Cables": "Подводные кабели",
+ "FIRMS Active Fires": "Активные пожары FIRMS",
+ "ENABLING": "ВКЛЮЧЕНИЕ",
+ "DISABLING": "ВЫКЛЮЧЕНИЕ",
+ "{state} · {source}": "{state} · {source}",
+ "UNCERTAIN · {source} · lifecycle state requires reconciliation": "НЕОПРЕД. · {source} · требуется сверка состояния",
+ "{state} · {source} · {detail} · retry {seconds}s": "{state} · {source} · {detail} · повтор через {seconds} с",
+ "{state} · {source} · {detail}": "{state} · {source} · {detail}",
+ "never": "не обновлялось",
+ "{source} · {loadingLabel}": "{source} · {loadingLabel}",
+ "{accepted} of {raw} records accepted": "принято записей: {accepted} из {raw}",
+ "incomplete snapshot": "неполный снимок",
+ "{state} · {source} · {detail} · {ago}": "{state} · {source} · {detail} · {ago}",
+ "{state} · {source} · {ago} · retrying in {seconds}s": "{state} · {source} · {ago} · повтор через {seconds} с",
+ "{state} · {source} · {ago}": "{state} · {source} · {ago}",
+ "{source} · {ago}": "{source} · {ago}",
+ "UNCERTAIN": "НЕОПРЕД.",
+ "Data source unavailable": "Источник данных недоступен",
+ "{name}: {state}": "{name}: {state}",
+ "{count}s ago": "{count} с назад",
+ "📍 Location: --": "📍 Место: --",
+ "Landmark: --": "Ориентир: --",
+ "Searched location": "Найденное место",
+ "ORBIT": "ОРБИТА",
+ "Fly to a POI first": "Сначала перелетите к точке интереса",
+ "Reset to full globe view": "Сбросить к виду всего глобуса",
+ "Reset cockpit to full globe view": "Сбросить кабину к виду всего глобуса",
+ "Resetting to full globe view": "Сброс к виду всего глобуса",
+ "Resetting cockpit to full globe view": "Сброс кабины к виду всего глобуса",
+ "Location not found": "Место не найдено",
+ "Search failed": "Не удалось выполнить поиск",
+ "MAP": "КАРТА",
+ "panel": "панель",
+ "Expand {name}": "Развернуть {name}",
+ "Collapse {name}": "Свернуть {name}",
+ "Expand Radio": "Развернуть радио",
+ "Collapse Radio": "Свернуть радио",
+ "Expand Radio section": "Развернуть раздел радио",
+ "Collapse Radio section": "Свернуть раздел радио",
+ "Panel layout updated — positions reset to new defaults": "Макет панелей обновлён — позиции сброшены к новым значениям по умолчанию",
+ "NO STATIONS": "НЕТ СТАНЦИЙ",
+ "NO STATION AVAILABLE": "НЕТ ДОСТУПНЫХ СТАНЦИЙ",
+ "{name}, station {index} of {total}": "{name}, станция {index} из {total}",
+ "No station available": "Нет доступной станции",
+ "OFF AIR": "НЕ В ЭФИРЕ",
+ "STATION UNAVAILABLE": "СТАНЦИЯ НЕДОСТУПНА",
+ "Radio could not {action} cleanly": "Не удалось корректно {action} радио",
+ "Collapse Cockpit display options": "Свернуть параметры экрана кабины",
+ "Expand Cockpit display options": "Развернуть параметры экрана кабины",
+ "Collapse Cockpit Radio controls": "Свернуть управление радио кабины",
+ "Expand Cockpit Radio controls": "Развернуть управление радио кабины",
+ "Close compact Radio controls": "Закрыть компактное управление радио",
+ "Open compact Radio controls": "Открыть компактное управление радио",
+ "DIRECTORY BAND": "ДИАПАЗОН КАТАЛОГА",
+ "{category} BAND": "ДИАПАЗОН {category}",
+ "NO STATION SELECTED": "СТАНЦИЯ НЕ ВЫБРАНА",
+ "Directory metadata only": "Только метаданные каталога",
+ "Loading station directory…": "Загрузка каталога станций…",
+ "Choose a globe marker or use next.": "Выберите маркер на глобусе или нажмите «След.».",
+ "TAGS · {tags}": "ТЕГИ · {tags}",
+ "Pause": "Приостановить",
+ "Resume": "Продолжить",
+ "Play": "Воспроизвести",
+ "selected": "выбранную",
+ "nearest": "ближайшую",
+ "{action} {target} radio station": "{action} {target} радиостанцию",
+ "RADIO STATE UNCERTAIN": "СОСТОЯНИЕ РАДИО НЕОПРЕДЕЛЁННО",
+ "SYNCING DIRECTORY": "СИНХРОНИЗАЦИЯ КАТАЛОГА",
+ "RADIO READY": "РАДИО ГОТОВО",
+ "SYNCING": "СИНХРОНИЗАЦИЯ",
+ "READY": "ГОТОВО",
+ "station": "станция",
+ " · stale/degraded directory": " · каталог устарел/с перебоями",
+ " · degraded directory": " · каталог с перебоями",
+ " · stale directory": " · каталог устарел",
+ " · outside current filter": " · вне текущего фильтра",
+ "Ready — playback starts only from your action": "Готово — воспроизведение начнётся только по вашей команде",
+ "Radio off": "Радио выключено",
+ "Connecting directly to broadcaster…": "Прямое подключение к вещателю…",
+ "Buffering broadcaster stream…": "Буферизация потока вещателя…",
+ "Playing {station}": "Играет {station}",
+ "Paused {station}": "{station} на паузе",
+ "Broadcaster stream unavailable": "Поток вещателя недоступен",
+ " · muted during voice interaction": " · приглушено во время голосовой сессии",
+ " · restoring volume after voice": " · восстановление громкости после голосовой сессии",
+ " · static indicates no broadcaster audio": " · шум означает отсутствие аудио вещателя",
+ " · tuning static until broadcaster starts": " · шум настройки, пока не начнётся вещание",
+ "Station unavailable after directory refresh — choose another channel": "Станция недоступна после обновления каталога — выберите другой канал",
+ "Radio is enabling…": "Радио включается…",
+ "Radio is disabling…": "Радио выключается…",
+ "Radio lifecycle is uncertain — use Enable or Disable to reconcile": "Состояние радио не определено — нажмите «Включить» или «Выключить» для сверки",
+ "SYNC": "СИНХР.",
+ "RECONCILE": "СВЕРИТЬ",
+ "DISABLE": "ВЫКЛЮЧИТЬ",
+ "ENABLE": "ВКЛЮЧИТЬ",
+ "Reconcile Radio — lifecycle uncertain": "Сверить радио — состояние не определено",
+ "Disable Radio": "Выключить радио",
+ "Enable Radio": "Включить радио",
+ "Scene action failed": "Не удалось выполнить действие со сценой",
+ "Delete shot \"{shot}\"?": "Удалить кадр «{shot}»?",
+ "ACQUIRING": "ЗАХВАТ",
+ "SHARED {subject}": "ПО ССЫЛКЕ: {subject}",
+ "entity": "объект",
+ "Shared {subject} follow expired": "Срок отслеживания {subject} по ссылке истёк",
+ "Shared {subject} could not be restored — feed unavailable": "Не удалось восстановить {subject} по ссылке — поток данных недоступен",
+ "Shared {subject} is unavailable": "{subject} по ссылке недоступен",
+ "LOADING LIVE DATA": "ЗАГРУЗКА ОНЛАЙН-ДАННЫХ",
+ "LOAD COMPLETE": "ЗАГРУЗКА ЗАВЕРШЕНА",
+ "LOAD CANCELLED": "ЗАГРУЗКА ОТМЕНЕНА",
+ "LOAD FAILED": "ОШИБКА ЗАГРУЗКИ",
+ "LIVE DATA OFF": "ОНЛАЙН-ДАННЫЕ ВЫКЛ.",
+ "MAPPED SITES LOADED": "ОБЪЕКТЫ ЗАГРУЖЕНЫ",
+ "RETRYING MAPPED SITES": "ПОВТОРНАЯ ЗАГРУЗКА ОБЪЕКТОВ",
+ "FETCHING MAPPED SITES": "ЗАГРУЗКА ОБЪЕКТОВ",
+ "TURNING OFF LIVE DATA": "ОТКЛЮЧЕНИЕ ОНЛАЙН-ДАННЫХ",
+ "REFRESHING LIVE DATA": "ОБНОВЛЕНИЕ ОНЛАЙН-ДАННЫХ",
+ "syncing road network": "синхронизация дорожной сети",
+ "retrying in {seconds}s": "повтор через {seconds} с",
+ "retry pending": "повтор ожидается",
+ "Contact cockpit summary": "Сводка по контакту в кабине",
+ "Cockpit briefing carousel": "Карусель брифингов кабины",
+ "Cockpit display and Radio controls": "Управление экраном и радио кабины",
+ "Previous cockpit vision style": "Предыдущий стиль обзора кабины",
+ "Previous vision style": "Предыдущий стиль обзора",
+ "Current cockpit vision style: NORMAL. Activate for next style.": "Текущий стиль обзора кабины: ОБЫЧНЫЙ. Активируйте для следующего стиля.",
+ "Current style: NORMAL — click for next": "Текущий стиль: ОБЫЧНЫЙ — нажмите для следующего",
+ "Next cockpit vision style": "Следующий стиль обзора кабины",
+ "Next vision style": "Следующий стиль обзора",
+ "Previous briefing page": "Предыдущая страница брифинга",
+ "Next briefing page": "Следующая страница брифинга",
+ "Show Live Signals": "Показать сигналы в реальном времени",
+ "Show Regional News": "Показать региональные новости",
+ "Show Local Info": "Показать местную информацию",
+ "Previous filtered radio station": "Предыдущая отфильтрованная радиостанция",
+ "Play selected radio station": "Воспроизвести выбранную радиостанцию",
+ "Next filtered radio station": "Следующая отфильтрованная радиостанция",
+ "Exit cockpit and return to full globe view": "Выйти из кабины и вернуться к виду всего глобуса",
+ "Exit cockpit view": "Выйти из кабины",
+ "Estimated destination direction": "Расчётное направление на пункт назначения",
+ "OPTICAL PLANE · 01": "ОПТИЧЕСКАЯ ПЛОСКОСТЬ · 01",
+ "VISOR LOCK · ACTIVE": "БЛОКИРОВКА ВИЗОРА · АКТИВНА",
+ "Cockpit vision style": "Стиль обзора кабины",
+ "Current aircraft heading": "Текущий курс самолёта",
+ "Nearby cohort counts": "Счётчики контактов поблизости",
+ "Cockpit display options": "Параметры экрана кабины",
+ "Cockpit compact Radio controls": "Компактное управление радио кабины",
+ "Cockpit Radio volume": "Громкость радио кабины",
+ "Contact navigation": "Навигация по контактам",
+ "Cockpit briefing controls": "Управление брифингом кабины",
+ "View switcher": "Переключатель вида",
+ "Aircraft cockpit view": "Вид кабины самолёта",
+ "Estimated flight plan": "Расчётный план полёта",
+ "Live signals": "Сигналы в реальном времени",
+ "Latest regional news": "Последние региональные новости",
+ "Location-based information": "Информация по текущему месту",
+ "LEVEL": "ГОРИЗОНТ",
+ "DEST ---°": "НАЗН. ---°",
+ "CURRENT": "ТЕКУЩИЙ",
+ "NEAREST OBSERVED / MAPPED": "БЛИЖАЙШИЕ НАБЛЮДАЕМЫЕ / НА КАРТЕ",
+ "GROUND SPEED · KTS": "ПУТЕВАЯ СКОРОСТЬ · УЗ",
+ "ALTITUDE · FT": "ВЫСОТА · ФТ",
+ "FIRST PERSON": "ОТ ПЕРВОГО ЛИЦА",
+ "LIVE TRACK · COURSE ALIGNED": "ТРЕК ОНЛАЙН · КУРС СОВМЕЩЁН",
+ "GROUND SPEED": "ПУТЕВАЯ СКОРОСТЬ",
+ "ALTITUDE": "ВЫСОТА",
+ "CONTEXT ONLY": "ТОЛЬКО КОНТЕКСТ",
+ "AVAILABLE INPUTS ONLY · NOT AN ALL-CLEAR": "ТОЛЬКО ДОСТУПНЫЕ ДАННЫЕ · ОТСУТСТВИЕ УГРОЗ НЕ ПОДТВЕРЖДЕНО",
+ "ESTIMATED FLIGHT PLAN": "РАСЧЁТНЫЙ ПЛАН ПОЛЁТА",
+ "FROM": "ОТКУДА",
+ "TO": "КУДА",
+ "TEMP": "ТЕМП.",
+ "WIND": "ВЕТЕР",
+ "SKY": "НЕБО",
+ "PRECIP": "ОСАДКИ",
+ "RADIO": "РАДИО",
+ "VOLUME": "ГРОМКОСТЬ",
+ "RESET": "СБРОС",
+ "EXIT COCKPIT": "ВЫЙТИ ИЗ КАБИНЫ",
+ "CONTACTS · 250 KM": "КОНТАКТЫ · 250 КМ",
+ "Expand Visual Presets": "Развернуть визуальные пресеты",
+ "Pin visual presets": "Закрепить визуальные пресеты",
+ "Keep visual presets open": "Держать визуальные пресеты открытыми",
+ "Show the globe without a visual filter.": "Показывает глобус без визуального фильтра.",
+ "Emulate a green phosphor CRT with scanlines and screen curvature.": "Имитирует CRT-экран с зелёным люминофором, строками развёртки и кривизной экрана.",
+ "Simulate night-vision goggles with green intensification and a tube vignette.": "Имитирует приборы ночного видения с зелёным усилением изображения и виньеткой трубки.",
+ "Simulate FLIR-style thermal contrast. Turn up Ironbow for color.": "Имитирует тепловой контраст в стиле FLIR. Для цвета увеличьте Ironbow.",
+ "Apply bright cel-shaded color and illustrated outlines.": "Применяет яркие cel-shading-цвета и рисованные контуры.",
+ "Apply high-contrast monochrome film-noir grading.": "Применяет высококонтрастную монохромную цветокоррекцию в стиле нуар.",
+ "Add a cold, snowy whiteout treatment to the scene.": "Добавляет в сцену холодный снежный эффект «белой мглы».",
+ "Expand LOCATION": "Развернуть панель «Место»",
+ "Collapse panel": "Свернуть панель",
+ "Pin location tray": "Закрепить панель места",
+ "Keep location tray open": "Держать панель места открытой",
+ "Search any location": "Поиск любого места",
+ "Navigation, voice, and visual preset controls": "Управление навигацией, голосом и визуальными пресетами",
+ "Language: {language}": "Язык: {language}",
+ "Change the interface language": "Сменить язык интерфейса",
+ "Interface language": "Язык интерфейса",
+ "Search languages": "Поиск языка",
+ "No matching languages": "Подходящих языков нет",
+ "Search location by name or coordinates": "Поиск места по названию или координатам",
+ "Search any location...": "Поиск любого места...",
+ "Normal": "Обычный",
+ "CRT": "CRT",
+ "NVG": "NVG",
+ "FLIR": "FLIR",
+ "Style": "Стиль",
+ "STATION SITE": "САЙТ СТАНЦИИ",
+ "Open detailed Radio controls": "Открыть подробное управление радио",
+ "Previous station": "Предыдущая станция",
+ "Next station": "Следующая станция",
+ "Expand panel": "Развернуть панель",
+ "CONTACTS": "КОНТАКТЫ",
+ "Cycles the nearest contacts of whatever type you select — planes, vessels, installations. Satellites track independently.": "Перебирает ближайшие контакты выбранного типа — самолёты, суда, объекты. Спутники отслеживаются отдельно.",
+ "SEARCH NEARBY SITES": "ПОИСК ОБЪЕКТОВ РЯДОМ",
+ "Reclassify tracked contact as TR-3B": "Переклассифицировать отслеживаемый контакт как TR-3B",
+ "Previous filtered station": "Предыдущая отфильтрованная станция",
+ "PLAY": "ПУСК",
+ "Play selected station": "Воспроизвести выбранную станцию",
+ "Next filtered station": "Следующая отфильтрованная станция",
+ "STOP": "СТОП",
+ "Stop radio playback": "Остановить воспроизведение радио",
+ "Compact Radio controls": "Компактное управление радио",
+ "Context mode": "Режим контекста",
+ "Contact Context actions": "Действия контекста контакта",
+ "Available Space Missions": "Доступные космические миссии",
+ "LOADING 30-DAY MISSION INDEX": "ЗАГРУЗКА ИНДЕКСА МИССИЙ ЗА 30 ДНЕЙ",
+ "Radio playback": "Воспроизведение радио",
+ "Compact Radio volume": "Громкость компактного радио",
+ "Radio volume": "Громкость радио",
+ "STATION TAG": "ТЕГ СТАНЦИИ",
+ "DRAG TO TUNE": "ТЯНИТЕ ДЛЯ НАСТРОЙКИ",
+ "TAB PREVIEWS · ENTER / SPACE SELECTS": "TAB — ПРОСМОТР · ENTER / SPACE — ВЫБОР",
+ "Audio connects directly to the broadcaster after you press play. Your IP is visible to that broadcaster.": "После нажатия «Пуск» звук идёт напрямую от вещателя, и ему виден ваш IP-адрес.",
+ "Internet radio and local SDR": "Интернет-радио и локальный SDR",
+ "Filter stations by station tag": "Фильтровать станции по тегу",
+ "CONTEXT": "КОНТЕКСТ",
+ "SPACE MISSIONS": "КОСМИЧЕСКИЕ МИССИИ",
+ "COCKPIT": "КАБИНА",
+ "SELECT CONTACTS TO LOAD OBSERVED / MAPPED PROXIMITY": "ВЫБЕРИТЕ КОНТАКТЫ, ЧТОБЫ ЗАГРУЗИТЬ НАБЛЮДАЕМОЕ / КАРТОГРАФИРОВАННОЕ ОКРУЖЕНИЕ",
+ "SELECT A MISSION TO INSPECT": "ВЫБЕРИТЕ МИССИЮ ДЛЯ ПРОСМОТРА",
+ "Enable Radio, then choose a globe marker or use next.": "Включите радио, затем выберите маркер на глобусе или переключите на следующую станцию.",
+ "ALL · DRAG THE NEEDLE": "ВСЕ · ТЯНИТЕ СТРЕЛКУ",
+ "SNAPS TO AVAILABLE STATIONS": "ПРИВЯЗКА К ДОСТУПНЫМ СТАНЦИЯМ",
+ "SELECT CONTEXT": "ВЫБЕРИТЕ КОНТЕКСТ",
+ "CONTACTS CONTEXT OFF": "КОНТЕКСТ КОНТАКТОВ ВЫКЛЮЧЕН",
+ "AVAILABLE MISSIONS": "ДОСТУПНЫЕ МИССИИ",
+ "Intelligence HUD (H)": "HUD разведки (H)",
+ "Detection Overlay (D)": "Слой детекции (D)",
+ "Detection overlay": "Слой детекции",
+ "Elastic": "Гибкое",
+ "Weighted": "Взвешенное",
+ "3D aircraft — flat icons zoomed out, 3D models up close": "3D-самолёты — издалека плоские иконки, вблизи 3D-модели",
+ "Proximity": "Вблизи",
+ "Scope — the circular viewport mask": "Прицел — круглая маска области просмотра",
+ "Hide UI chrome": "Скрыть элементы интерфейса",
+ "Bloom / Glow": "Bloom / свечение",
+ "Sharpening": "Повышение резкости",
+ "EXIT CLEAN VIEW": "ВЫЙТИ ИЗ ЧИСТОГО ВИДА",
+ "Return UI controls": "Вернуть управление интерфейсом",
+ "Detection label allocation": "Размещение меток детекции",
+ "3D model coverage": "Охват 3D-моделей",
+ "Detection label density": "Плотность меток детекции",
+ "Detection fade distance": "Дистанция затухания детекции",
+ "World-overlay fade distance outside the keyhole as a percentage of its radius": "Дистанция затухания мирового слоя за пределами маски в процентах от её радиуса",
+ "Detection opacity outside the keyhole": "Непрозрачность детекции за пределами маски",
+ "World-overlay label and card opacity beyond the fade distance": "Непрозрачность меток и карточек мирового слоя за пределами дистанции затухания",
+ "Scope edge feather": "Растушёвка края прицела",
+ "Scope edge feather as a percentage of the keyhole radius": "Растушёвка края прицела в процентах от радиуса маски",
+ "Bloom intensity": "Интенсивность bloom",
+ "Sharpen intensity": "Интенсивность резкости",
+ "Density": "Плотность",
+ "Fade": "Затухание",
+ "Outside": "Снаружи",
+ "Tactical": "Тактический",
+ "Operator": "Операторский",
+ "Minimal": "Минимальный",
+ "HUD layout": "Макет HUD",
+ "Layout": "Макет",
+ "Allocation": "Размещение",
+ "PARAMETERS": "ПАРАМЕТРЫ",
+ "Models": "Модели",
+ "Scope": "Прицел",
+ "Feather": "Растушёвка",
+ "Celestial": "Небо",
+ "Clean UI": "Чистый интерфейс",
+ "Bloom": "Свечение",
+ "Sharpen": "Резкость",
+ "Initializing photorealistic world...": "Инициализация фотореалистичного мира...",
+ "NEAREST": "БЛИЖАЙШАЯ",
+ "Drag the camera in the world: rings rotate, arrows move, handles set range/FOV": "Перетащите камеру в мире: кольца вращают, стрелки перемещают, маркеры задают дальность и угол обзора",
+ "Heading (compass °) — click to type": "Курс (° по компасу) — нажмите для ввода",
+ "Pitch (° up/down) — click to type": "Тангаж (° вверх/вниз) — нажмите для ввода",
+ "Horizontal FOV (°) — click to type": "Горизонтальный угол обзора (°) — нажмите для ввода",
+ "Range / monitor-plane distance (m) — click to type": "Дальность / расстояние до плоскости монитора (м) — нажмите для ввода",
+ "Mount height above ground (m) — click to type": "Высота крепления над землёй (м) — нажмите для ввода",
+ "North offset from catalog position (m) — click to type": "Смещение на север от позиции каталога (м) — нажмите для ввода",
+ "East offset from catalog position (m) — click to type": "Смещение на восток от позиции каталога (м) — нажмите для ввода",
+ "SAVE CAL": "СОХРАНИТЬ КАЛИБР.",
+ "RESET CAL": "СБРОСИТЬ КАЛИБР.",
+ "NEW": "НОВАЯ",
+ "DEL": "УДАЛ.",
+ "CAPTURE SHOT": "СДЕЛАТЬ КАДР",
+ "UPDATE SHOT": "ОБНОВИТЬ КАДР",
+ "START": "СТАРТ",
+ "EXPORT PRESETS": "ЭКСПОРТ ПРЕСЕТОВ",
+ "IMPORT": "ИМПОРТ",
+ "RUN LOG": "ЖУРНАЛ ЗАПУСКОВ",
+ "CALIBRATION": "КАЛИБРОВКА",
+ "Camera pose — click a value to type": "Поза камеры — щёлкните по значению, чтобы ввести",
+ "SCENE SUMMARY": "СВОДКА ПО СЦЕНЕ",
+ "CCTV camera": "Камера CCTV",
+ "Scene recipe": "Рецепт сцены",
+ "DATA LAYERS": "СЛОИ ДАННЫХ",
+ "SCENES": "СЦЕНЫ",
+ "Close key setup": "Закрыть настройку ключей",
+ "SAVE KEYS": "СОХРАНИТЬ КЛЮЧИ",
+ "Power up the globe": "Подключите потоки данных",
+ "The globe already flies keyless. Every key below switches on another real feed — paste one and it's saved into this app's local configuration, then the server restarts itself. Server-side keys stay on this machine; Google Maps and Cesium ion run in the browser and must be provider-restricted. Keys you configured elsewhere are shown but never touched.": "Глобус уже работает без ключей. Каждый ключ ниже включает ещё один поток данных в реальном времени — вставьте ключ, и он сохранится в локальной конфигурации приложения, после чего сервер перезапустится сам. Серверные ключи остаются на этом компьютере; Google Maps и Cesium ion работают в браузере, поэтому их ключи нужно ограничить на стороне провайдера. Ключи, настроенные в другом месте, видны здесь, но изменить их нельзя.",
+ "The Google Maps key buys the photorealistic planet — everything else stacks on top.": "Ключ Google Maps открывает фотореалистичную планету — остальное накладывается поверх.",
+ "POWER UP": "ЗАПУСК",
+ "GROUND STATION · PROVIDER SETTINGS": "НАЗЕМНАЯ СТАНЦИЯ · НАСТРОЙКИ ПРОВАЙДЕРОВ",
+ "ESC to close": "ESC — закрыть",
+ "Turn off all selected data layers": "Выключить все выбранные слои данных",
+ "Copy share link": "Скопировать ссылку",
+ "Reset camera and return to full globe view": "Сбросить камеру и вернуть полный вид глобуса",
+ "Visible map targets": "Видимые цели на карте",
+ "Globe actions": "Действия с глобусом",
+ "NO PLACE LEFT BEHIND": "НИ ОДНА ТОЧКА НЕ ОСТАНЕТСЯ ПОЗАДИ",
+ "ACTIVE STYLE": "АКТИВНЫЙ СТИЛЬ",
+ "Choose your first view": "Выберите первый вид",
+ "Tip: the GEV MIC button in the dock lets you talk to the map.": "Совет: кнопка «МИК» в доке позволяет говорить с картой.",
+ "Aircraft, vessels and nearby intelligence": "Самолёты, суда и разведданные поблизости",
+ "Launches, spacecraft and orbital context": "Пуски, космические аппараты и орбитальный контекст",
+ "Begin with a clean globe": "Начните с чистого глобуса",
+ "MISSION CONTROL · FIRST LAUNCH": "ЦЕНТР УПРАВЛЕНИЯ · ПЕРВЫЙ ЗАПУСК",
+ "Don't show this again": "Больше не показывать",
+ "ESC to dismiss": "ESC — скрыть",
+ "LIVE CONTACTS": "КОНТАКТЫ ОНЛАЙН",
+ "EXPLORE MANUALLY": "ИЗУЧИТЬ ВРУЧНУЮ",
+ "Celestial ring — reveal the full globe": "Небесное кольцо — показать весь глобус",
+ "Celestial ring — available in Normal style": "Небесное кольцо — доступно в стиле «Обычный»",
+ "Detection overlay: {mode}": "Слой детекции: {mode}",
+ "Detection overlay: off": "Слой детекции: выкл.",
+ "SPARSE": "РЕДКО",
+ "BALANCED": "УМЕРЕННО",
+ "DETECT": "ДЕТЕКЦИЯ",
+ "AI AGENT": "ИИ-АГЕНТ",
+ "Voice model tier — applies next session": "Уровень голосовой модели — вступит в силу со следующей сессии",
+ "Estimated session cost": "Оценочная стоимость сессии",
+ "Voice control — activate to toggle voice; hold Space to speak": "Голосовое управление — активируйте, чтобы включить или выключить голос; удерживайте Space, чтобы говорить",
+ "VOICE STANDBY": "ГОЛОС В ОЖИДАНИИ",
+ "VOICE CONTROL": "ГОЛОСОВОЕ УПРАВЛЕНИЕ",
+ "Hold Space to speak · tap Space to activate focused controls": "Удерживайте Space, чтобы говорить · нажатие Space активирует элемент в фокусе",
+ "VOICE SYSTEM ERROR": "ОШИБКА ГОЛОСОВОЙ СИСТЕМЫ",
+ "DISMISS": "СКРЫТЬ",
+ "Check microphone permission and network access, then try again.": "Проверьте разрешение на микрофон и доступ к сети, затем попробуйте снова.",
+ "Release Space to send": "Отпустите Space для отправки",
+ "Hold Space to talk": "Держите Space и говорите",
+ "Ask or command": "Спросите или дайте команду",
+ "WebRTC microphone support unavailable": "Поддержка микрофона WebRTC недоступна",
+ "Requesting microphone": "Запрос доступа к микрофону",
+ "Voice off": "Голос выключен",
+ "VOICE UNAVAILABLE": "ГОЛОС НЕДОСТУПЕН",
+ "VOICE ACTIVE": "ГОЛОС АКТИВЕН",
+ "Voice session could not be started.": "Не удалось запустить голосовую сессию.",
+ "CONNECTING": "ПОДКЛЮЧЕНИЕ",
+ "ERROR": "ОШИБКА",
+ "{tier} applies next session": "{tier} — со следующей сессии",
+ "Session ended — cost cap {cost}": "Сессия завершена — лимит стоимости {cost}",
+ "Next session: {pendingId} — this session stays on {modelId}": "Следующая сессия: {pendingId} — текущая остаётся на {modelId}",
+ "Voice model: {pendingId} — click to switch to {target}; applies next session": "Голосовая модель: {pendingId} — нажмите, чтобы переключиться на {target}; вступит в силу со следующей сессии",
+ "Estimated session cost on {modelId} — {responses} response(s). Warns at {warn}, ends the session at {cap}.": "Оценочная стоимость сессии на {modelId} — ответов: {responses}. Предупреждение при {warn}, завершение сессии при {cap}.",
+ "Radio did not start": "Не удалось запустить радио",
+ "Running command": "Выполнение команды",
+ "Saturation": "Насыщенность",
+ "Edge Thickness": "Толщина контуров",
+ "Contrast": "Контраст",
+ "Grain": "Зерно",
+ "Vignette": "Виньетка",
+ "Pixelation": "Пикселизация",
+ "Distortion": "Искажение",
+ "Instability": "Нестабильность",
+ "Wind": "Ветер",
+ "Gain": "Усиление",
+ "Scanlines": "Строки развёртки",
+ "Sensitivity": "Чувствительность",
+ "WHOT/BHOT": "WHOT/BHOT",
+ "Ironbow": "Ironbow",
+ "Pick a shape, then click the map.": "Выберите фигуру и щёлкните по карте.",
+ "Enter to place the pin, Esc to cancel.": "Enter — поставить метку, Esc — отменить.",
+ "Click where the pin goes.": "Щёлкните там, где нужно поставить метку.",
+ "Click {count} more points.": {
+ "one": "Отметьте ещё {count} точку.",
+ "few": "Отметьте ещё {count} точки.",
+ "many": "Отметьте ещё {count} точек.",
+ "other": "Отметьте ещё {count} точки."
+ },
+ "Those points are in a line — move one off it to enclose an area.": "Точки лежат на одной линии — сдвиньте одну из них, чтобы образовалась замкнутая область.",
+ "That line has no length — click somewhere further away.": "У линии нет длины — щёлкните дальше.",
+ " · {max}-point limit reached": " · достигнут лимит точек: {max}",
+ "{measure} · double-click or Enter to finish, Backspace undoes, Esc cancels.{full}": "{measure} · двойной щелчок или Enter — завершить, Backspace — отменить точку, Esc — отменить.{full}",
+ "That point is off the globe — click on the world.": "Эта точка вне глобуса — щёлкните по Земле.",
+ "That shape could not be placed.": "Не удалось разместить фигуру.",
+ "Board cleared.": "Доска очищена.",
+ "Draw on the world — click vertices, double-click or Enter to finish, Esc to cancel": "Рисовать на карте мира — щёлкайте по вершинам, двойной щелчок или Enter — завершить, Esc — отменить",
+ "Draw": "Рисование",
+ "Shape": "Фигура",
+ "Shape to draw": "Фигура для рисования",
+ "Area": "Зона",
+ "Line": "Линия",
+ "Pin": "Метка",
+ "Label (optional)": "Подпись (необязательно)",
+ "Label for the drawn shape": "Подпись нарисованной фигуры",
+ "Colour of the drawn shape": "Цвет нарисованной фигуры",
+ "Primary": "Основной",
+ "Amber": "Янтарный",
+ "Cyan": "Голубой",
+ "Green": "Зелёный",
+ "Red": "Красный",
+ "Clear": "Очистить",
+ "Remove every mark from the board": "Убрать все пометки с доски",
+ "Point the camera at the globe for street-level coverage": "Наведите камеру на глобус, чтобы увидеть покрытие уличных снимков",
+ "No street-level imagery providers configured": "Источники уличных снимков не настроены",
+ "Selected": "Выбрано",
+ "Live Vessels": "Суда онлайн",
+ "Bike Share": "Прокат велосипедов",
+ "Cameras": "Камеры",
+ "Street Level": "Уличные снимки",
+ "Mapped ALPR Cameras": "Камеры ALPR на карте",
+ "Data Centers": "Дата-центры",
+ "Active Fires": "Активные пожары",
+ "Street Level could not start": "Не удалось запустить «Уличные снимки»",
+ "Street Level toggle failed": "Не удалось переключить «Уличные снимки»",
+ "Street-level image": "Уличный снимок",
+ "SHRINK": "СВЕРНУТЬ",
+ "EXPAND": "РАЗВЕРНУТЬ",
+ "Shrink": "Свернуть",
+ "Expand": "Развернуть",
+ "ANY DATE": "ЛЮБАЯ ДАТА",
+ "LAST 10 YEARS": "ЗА 10 ЛЕТ",
+ "LAST 5 YEARS": "ЗА 5 ЛЕТ",
+ "LAST 3 YEARS": "ЗА 3 ГОДА",
+ "LAST 2 YEARS": "ЗА 2 ГОДА",
+ "LAST YEAR": "ЗА ГОД",
+ "LAST 6 MONTHS": "ЗА 6 МЕСЯЦЕВ",
+ "LAST 3 MONTHS": "ЗА 3 МЕСЯЦА",
+ "LAST MONTH": "ЗА МЕСЯЦ",
+ "LAST {count} DAYS": {
+ "one": "ЗА {count} ДЕНЬ",
+ "few": "ЗА {count} ДНЯ",
+ "many": "ЗА {count} ДНЕЙ",
+ "other": "ЗА {count} ДНЯ"
+ },
+ "{window} · SINCE {date}": "{window} · С {date}",
+ "Turn Street Level off": "Выключить «Уличные снимки»",
+ "Turn Street Level on": "Включить «Уличные снимки»",
+ "KEY REJECTED": "КЛЮЧ ОТКЛОНЁН",
+ "{name} imagery on": "Снимки {name} включены",
+ "{name} imagery off": "Снимки {name} выключены",
+ "Image by {creator}": "Автор снимка: {creator}",
+ "zoom in to see KartaView coverage": "приблизьтесь, чтобы увидеть покрытие KartaView",
+ "no KartaView photos in view": "фотографий KartaView в зоне видимости нет",
+ "{names}: by upload date": "{names}: по дате загрузки",
+ "{n} streets in view · click a line for its nearest photo": {
+ "one": "{n} улица в кадре · щёлкните линию, чтобы открыть ближайшую фотографию",
+ "few": "{n} улицы в кадре · щёлкните линию, чтобы открыть ближайшую фотографию",
+ "many": "{n} улиц в кадре · щёлкните линию, чтобы открыть ближайшую фотографию",
+ "other": "{n} улицы в кадре · щёлкните линию, чтобы открыть ближайшую фотографию"
+ },
+ "Camera follows view: move the globe camera wherever the street-level view looks": "Камера следует за видом: камера глобуса поворачивается туда, куда смотрит уличный снимок",
+ "Camera follow needs the Google 3D map: choose Google 3D under MAP SOURCE": "Слежению камеры нужна карта Google 3D: выберите Google 3D в разделе «ИСТОЧНИК КАРТЫ»",
+ "Switch a provider on to draw its coverage.": "Включите источник, чтобы показать его покрытие.",
+ "Loading this sequence…": "Загрузка последовательности…",
+ "{n} images in this sequence · Esc clears": {
+ "one": "{n} снимок в последовательности · Esc — сбросить",
+ "few": "{n} снимка в последовательности · Esc — сбросить",
+ "many": "{n} снимков в последовательности · Esc — сбросить",
+ "other": "{n} снимка в последовательности · Esc — сбросить"
+ },
+ "{n} sequences in view · click a line for its photos": {
+ "one": "{n} последовательность в кадре · щёлкните по линии, чтобы открыть снимки",
+ "few": "{n} последовательности в кадре · щёлкните по линии, чтобы открыть снимки",
+ "many": "{n} последовательностей в кадре · щёлкните по линии, чтобы открыть снимки",
+ "other": "{n} последовательности в кадре · щёлкните по линии, чтобы открыть снимки"
+ },
+ "STREET LEVEL": "УЛИЧНЫЕ СНИМКИ",
+ "Expand the street-level view (Esc shrinks it)": "Развернуть уличный снимок (Esc сворачивает)",
+ "Image fit": "Масштаб снимка",
+ "FIT": "ВПИСАТЬ",
+ "Fit: show the whole photo, with dark bars where its shape differs from the frame": "Вписать: показать снимок целиком, с тёмными полосами там, где его форма не совпадает с рамкой",
+ "FILL": "ЗАПОЛНИТЬ",
+ "Fill: fill the frame edge to edge, cropping the photo": "Заполнить: заполнить рамку целиком, обрезав края снимка",
+ "Camera follows view": "Камера следует за видом",
+ "FOLLOW": "СЛЕДИТЬ",
+ "Close the image and deselect it on the map": "Закрыть снимок и снять выделение на карте",
+ "Close the street-level image": "Закрыть уличный снимок",
+ "Street-level viewer": "Просмотр уличных снимков",
+ "Open this image on the provider's site": "Открыть снимок на сайте источника",
+ "Imagery providers": "Источники снимков",
+ "PROVIDERS": "ИСТОЧНИКИ",
+ "Imagery filters": "Фильтры снимков",
+ "IMAGERY": "СНИМКИ",
+ "Panorama filter": "Фильтр панорам",
+ "ALL": "ВСЕ",
+ "FLAT": "ПЛОСКИЕ",
+ "SINCE": "С ДАТЫ",
+ "Coverage colours": "Цвета покрытия",
+ "That shape already has {count} points — finish it or press Backspace.": "В этой фигуре уже точек: {count} — завершите её или нажмите Backspace.",
+ "Could not place the shape: {error}": "Не удалось разместить фигуру: {error}",
+ "{owner} is using the pointer — close it first.": "Указатель занят: «{owner}». Закройте его.",
+ "{label} · Detailed outline unavailable": "{label} · Подробный контур недоступен",
+ "Witness source": "Свидетельство очевидца",
+ "{provider} · EMBEDDED SOURCE": "{provider} · ВСТРОЕННЫЙ ИСТОЧНИК",
+ "OPEN ORIGINAL ↗": "ОТКРЫТЬ ОРИГИНАЛ ↗",
+ "{provider} media: {source}": "Медиа {provider}: {source}",
+ "{provider} · PROVIDER CONTROLS": "{provider} · ВСТРОЕННЫЙ ПЛЕЕР",
+ "YOUTUBE {state} · OPEN ORIGINAL": "YOUTUBE {state} · ОТКРЫТЬ ОРИГИНАЛ",
+ "Facebook player API did not initialize.": "API плеера Facebook не инициализировался.",
+ "Facebook player API could not load.": "Не удалось загрузить API плеера Facebook.",
+ "Facebook player API timed out.": "Истекло время ожидания API плеера Facebook.",
+ "X embed API did not initialize.": "API встраивания X не инициализировался.",
+ "X embed could not load.": "Не удалось загрузить встраивание X.",
+ "X embed timed out.": "Истекло время ожидания встраивания X.",
+ "TIMEOUT": "ТАЙМАУТ",
+ "BLOCKED": "ЗАБЛОКИРОВАНО",
+ "Facebook embed unavailable. The post may be private, removed, region-restricted, or blocked.": "Встраивание Facebook недоступно. Публикация может быть закрытой, удалённой, ограниченной по региону или заблокированной.",
+ "Preloading {provider} media": "Предзагрузка медиа {provider}",
+ "LOADING X POST…": "ЗАГРУЗКА ПОСТА X…",
+ "The X post is unavailable or cannot be embedded.": "Пост X недоступен или не может быть встроен.",
+ "X POST · PROVIDER CONTROLS": "ПОСТ X · ВСТРОЕННЫЙ ВИДЖЕТ",
+ "{reason} OPEN ORIGINAL.": "{reason} ОТКРОЙТЕ ОРИГИНАЛ.",
+ "X embed unavailable": "Встраивание X недоступно",
+ "FACEBOOK · PROVIDER CONTROLS": "FACEBOOK · ВСТРОЕННЫЙ ПЛЕЕР",
+ "Facebook embed unavailable": "Встраивание Facebook недоступно",
+ "AUTOPLAY BLOCKED · USE PROVIDER CONTROLS": "АВТОВОСПРОИЗВЕДЕНИЕ ЗАБЛОКИРОВАНО · ЗАПУСТИТЕ В ПЛЕЕРЕ",
+ "Embedded {provider} media for {source}": "Встроенное медиа {provider}: {source}",
+ "witness source": "свидетельство очевидца",
+ "Rasuwagadhi witness": "Очевидец в Rasuwagadhi",
+ "Open original source for {source}; capture time unverified": "Открыть оригинал: {source}; время съёмки не подтверждено",
+ "Historical reference and post-event image divider": "Разделитель исторического снимка и снимка после события",
+ "A historical reference {before} percent, B post-event {after} percent": "A — исторический снимок: {before}%, B — после события: {after}%",
+ "■ RELEASE CAMERA": "■ ОСВОБОДИТЬ КАМЕРУ",
+ "Seek Nepal scene clock": "Перемотка времени сцены в Непале",
+ "NEPAL SCENE CLOCK": "ВРЕМЯ СЦЕНЫ В НЕПАЛЕ",
+ "… PLAYING SHOT": "… ИДЁТ КАДР",
+ "▶ PLAY SHOT": "▶ ПУСК КАДРА",
+ "Ⅱ PAUSE": "Ⅱ ПАУЗА",
+ "↺ REPLAY CINEMATIC": "↺ ПОВТОРИТЬ КИНОРЕЖИМ",
+ "↺ REPLAY": "↺ ПОВТОРИТЬ",
+ "… PLAYING SCENE": "… ИДЁТ СЦЕНА",
+ "Continue {scene} from next shot": "Продолжить со следующего кадра: {scene}",
+ "current scene": "текущая сцена",
+ "Replay the full reconstruction": "Повторить всю реконструкцию",
+ "SCENE SHOT": "КАДР СЦЕНЫ",
+ "TIME UNVERIFIED": "ВРЕМЯ НЕ ПОДТВЕРЖДЕНО",
+ "{count} SOURCES": {
+ "one": "{count} ИСТОЧНИК",
+ "few": "{count} ИСТОЧНИКА",
+ "many": "{count} ИСТОЧНИКОВ",
+ "other": "{count} ИСТОЧНИКА"
+ },
+ "OUTSIDE IMAGERY SWIPE": "ВНЕ СРАВНЕНИЯ СНИМКОВ",
+ "{scene} / AUTHORED SHOT": "{scene} / АВТОРСКИЙ КАДР",
+ "NEPAL FLOOD INCIDENT": "НАВОДНЕНИЕ В НЕПАЛЕ",
+ "Play {shot}": "Воспроизвести: {shot}",
+ "current scene shot": "текущий кадр сцены",
+ "Play reconstruction": "Воспроизвести реконструкцию",
+ "Load previous scene shot": "Загрузить предыдущий кадр сцены",
+ "Load next scene shot": "Загрузить следующий кадр сцены",
+ "SCHEMATIC CORRIDOR, NOT MODELED ARRIVAL TIME.": "СХЕМАТИЧЕСКИЙ КОРИДОР, А НЕ МОДЕЛЬ ВРЕМЕНИ ДОБЕГАНИЯ ПАВОДКА.",
+ "Rasuwa · 26 Aug 2026": "Rasuwa · 26 авг. 2026",
+ "Event reconstruction": "Реконструкция события",
+ "INITIATION": "ЗАРОЖДЕНИЕ",
+ "DAMMING": "ЗАПРУДА",
+ "SECONDARY FAILURE": "ВТОРИЧНЫЙ ПРОРЫВ",
+ "BORDER ARRIVAL": "ДОСТИЖЕНИЕ ГРАНИЦЫ",
+ "PROPAGATION": "РАСПРОСТРАНЕНИЕ",
+ "DOWNSTREAM PASSAGE": "ПРОХОЖДЕНИЕ ВНИЗ ПО ТЕЧЕНИЮ",
+ "CONSEQUENCE": "ПОСЛЕДСТВИЯ",
+ "DOWNSTREAM CONSEQUENCE": "ПОСЛЕДСТВИЯ НИЖЕ ПО ТЕЧЕНИЮ",
+ "EVIDENCE": "СВИДЕТЕЛЬСТВА",
+ "{count} GEOLOCATED SOURCE-MAP PLACEMENTS": {
+ "one": "{count} ГЕОПРИВЯЗАННАЯ МЕТКА НА КАРТЕ ИСТОЧНИКОВ",
+ "few": "{count} ГЕОПРИВЯЗАННЫЕ МЕТКИ НА КАРТЕ ИСТОЧНИКОВ",
+ "many": "{count} ГЕОПРИВЯЗАННЫХ МЕТОК НА КАРТЕ ИСТОЧНИКОВ",
+ "other": "{count} ГЕОПРИВЯЗАННОЙ МЕТКИ НА КАРТЕ ИСТОЧНИКОВ"
+ },
+ "NO PREVIEW": "НЕТ ПРЕДПРОСМОТРА",
+ "SOURCE LINK": "ССЫЛКА НА ИСТОЧНИК",
+ "{publisher} / OPEN": "{publisher} / ОТКРЫТЬ",
+ "Bhote Koshi flood reconstruction controls": "Управление реконструкцией наводнения на Bhote Koshi",
+ "EVENT RECONSTRUCTION · 26 AUG 2026": "РЕКОНСТРУКЦИЯ СОБЫТИЯ · 26 АВГ. 2026",
+ "BHOTE KOSHI OUTBURST FLOOD": "ПРОРЫВНОЙ ПАВОДОК НА BHOTE KOSHI",
+ "Close event layer": "Закрыть слой события",
+ "OBSERVED IMAGERY": "ФАКТИЧЕСКИЕ СНИМКИ",
+ "SCHEMATIC CORRIDOR": "СХЕМАТИЧЕСКИЙ КОРИДОР",
+ "2021 HISTORICAL REFERENCE / 2026 POST-EVENT": "2021 ИСТОРИЧЕСКИЙ СНИМОК / 2026 ПОСЛЕ СОБЫТИЯ",
+ "Historical reference and post-event image split": "Сравнение исторического снимка и снимка после события",
+ "RECONSTRUCTION CLOCK": "ВРЕМЯ РЕКОНСТРУКЦИИ",
+ "Schematic downstream progression": "Схематическое продвижение вниз по течению",
+ "Story beat navigation": "Навигация по этапам сюжета",
+ "Previous story beat": "Предыдущий этап сюжета",
+ "CAUSE": "ПРИЧИНА",
+ "CAPTURE TIME UNVERIFIED": "ВРЕМЯ СЪЁМКИ НЕ ПОДТВЕРЖДЕНО",
+ "Next story beat": "Следующий этап сюжета",
+ "▶ PLAY": "▶ ПУСК",
+ "Play the next shot and continue through this scene": "Воспроизвести следующий кадр и продолжить эту сцену",
+ "▶ PLAY SCENE": "▶ ПУСК СЦЕНЫ",
+ "◉ CINEMATIC": "◉ КИНОРЕЖИМ",
+ "↺ FULL STORY": "↺ ВСЯ ИСТОРИЯ",
+ "↗ OPEN ORIGINAL": "↗ ОРИГИНАЛ",
+ "⌖ LOWER GORGE": "⌖ НИЖНЕЕ УЩЕЛЬЕ",
+ "FIELD REPORTS · {count}": "СООБЩЕНИЯ С МЕСТА · {count}",
+ "GEOLOCATIONS · {credit}": "ГЕОЛОКАЦИИ · {credit}",
+ "↗ OPEN PUBLIC MAP": "↗ ОТКРЫТЬ ПУБЛИЧНУЮ КАРТУ",
+ "Clouds are preserved from the source imagery.": "Облака оставлены такими, как на исходных снимках.",
+ "Show the Nepal context callout without a border or country fill": "Показать выноску с контекстом Непала без границы и заливки страны",
+ "Introduce Nepal, draw its border, then reveal the Bhote Koshi incident": "Представить Непал, нарисовать его границу, затем показать инцидент на Bhote Koshi",
+ "CITIES": "ГОРОДА",
+ "Keep the regional incident context and introduce nearby city labels": "Сохранить региональный контекст инцидента и добавить подписи ближайших городов",
+ "PLACES": "МЕСТА",
+ "Introduce the reconstruction scene key places from trigger to downstream": "Показать ключевые места сцены реконструкции — от источника события до низовья",
+ "PATH": "ПУТЬ",
+ "Animate the sourced cyan river-centerline route to Trishuli Bazaar": "Анимировать голубой маршрут по оси реки до Trishuli Bazaar по данным источников",
+ "OVERVIEW": "ОБЗОР",
+ "Keep the completed flood path and location labels visible": "Оставить на экране весь путь паводка и подписи мест",
+ "RECORD": "ЗАПИСЬ",
+ "Reveal the trigger record while making a slow camera approach": "Показать запись о первопричине при медленном приближении камеры",
+ "BHOTE KOSHI FLOOD INCIDENT": "НАВОДНЕНИЕ НА BHOTE KOSHI",
+ "NEPAL · 26 AUG 2026": "НЕПАЛ · 26 АВГ. 2026",
+ "USGS INITIAL REPORT": "ПЕРВИЧНОЕ СООБЩЕНИЕ USGS",
+ "26 AUG 2026 · 08:37 NPT": "26 АВГ. 2026 · 08:37 NPT",
+ "28.2710° N · 85.5150° E": "28,2710° С. Ш. · 85,5150° В. Д.",
+ "INITIAL M4.4 · RECLASSIFIED M5.2 LANDSLIDE": "ПЕРВОНАЧАЛЬНО M4,4 · ПЕРЕКЛАССИФИЦИРОВАНО: ОПОЛЗЕНЬ M5,2",
+ "USGS EVENT us7000tbwb · OPEN SOURCE": "СОБЫТИЕ USGS us7000tbwb · ОТКРЫТЬ ИСТОЧНИК",
+ "flight": "рейс",
+ "military flight": "военный рейс",
+ "satellite": "спутник",
+ "VOICE AUTH · CHATGPT OAUTH": "ГОЛОС: АВТОРИЗАЦИЯ · CHATGPT OAUTH",
+ "VOICE AUTH · API KEY": "ГОЛОС: КЛЮЧ API",
+ "USE API KEY": "ИСПОЛЬЗОВАТЬ КЛЮЧ API",
+ "USE CHATGPT OAUTH": "ИСПОЛЬЗОВАТЬ CHATGPT OAUTH",
+ "Use OPENAI_API_KEY for the next cloud voice session": "Использовать OPENAI_API_KEY для следующей облачной голосовой сессии",
+ "Use the signed-in local ChatGPT/Codex OAuth session for the next cloud voice session": "Использовать локальную OAuth-сессию ChatGPT/Codex, в которую выполнен вход, для следующей облачной голосовой сессии",
+ "Metered — a billing-enabled account": "Платный — нужен аккаунт с включённой оплатой",
+ "Free key — register, paste, done": "Бесплатный ключ — зарегистрируйтесь, вставьте, готово",
+ "browser-side": "в браузере",
+ "This key runs in the browser by design — restrict it at the provider (see SECURITY.md)": "Этот ключ по задумке работает в браузере — ограничьте его у провайдера (см. SECURITY.md)",
+ "configured externally": "задан извне",
+ "Supplied by your environment, Keychain, or launcher — change it where it was set": "Задан окружением, Keychain или лаунчером — меняйте его там, где он задан",
+ "MANAGE ↗": "УПРАВЛЯТЬ ↗",
+ "GET KEY ↗": "ПОЛУЧИТЬ КЛЮЧ ↗",
+ "{envVar} saved — paste to replace": "{envVar} сохранён — вставьте, чтобы заменить",
+ "paste {envVar}": "вставьте {envVar}",
+ "Project keys: {status}": "Ключи проекта: {status}",
+ "Mapped camera locations": "Расположение камер на карте",
+ "SHOW NEAREST": "ПОКАЗАТЬ БЛИЖАЙШУЮ",
+ "Stop following the current object before navigating to a camera": "Прекратите следовать за текущим объектом, прежде чем переходить к камере",
+ "Move to the nearest loaded camera and show its details": "Перейти к ближайшей загруженной камере и показать её данные",
+ "Camera badges": "Значки камер",
+ "Cyan cameras turn coral when selected. Wedges illustrate mapped direction, not measured coverage. Nearby cameras may be outside the screen.": "Голубые камеры при выборе становятся коралловыми. Секторы показывают направление по карте, а не измеренное покрытие. Ближайшие камеры могут быть за пределами экрана.",
+ "{count} nearby · {onScreen} on screen": {
+ "one": "{count} рядом · {onScreen} видно",
+ "few": "{count} рядом · {onScreen} видно",
+ "many": "{count} рядом · {onScreen} видно",
+ "other": "{count} рядом · {onScreen} видно"
+ },
+ "{count} nearby": {
+ "one": "рядом: {count}",
+ "few": "рядом: {count}",
+ "many": "рядом: {count}",
+ "other": "рядом: {count}"
+ },
+ "retrying mapped ALPR cameras": "повторная загрузка камер ALPR",
+ "loading mapped ALPR cameras": "загрузка камер ALPR",
+ "No ALPR data for this area — US and Canada only": "Нет данных ALPR для этой области — только США и Канада",
+ "Zoom in to load mapped cameras": "Приблизьте карту, чтобы загрузить камеры",
+ "Showing cached locations": "Показаны места из кэша",
+ "Coverage limited — zoom in": "Покрытие ограничено — приблизьте карту",
+ "No ALPR data for this area": "Нет данных ALPR для этой области",
+ "None on screen — nearby cameras are outside the view": "На экране нет — ближайшие камеры вне поля зрения",
+ "ALPR camera": "Камера ALPR",
+ "OpenStreetMap · community mapped": "OpenStreetMap · данные сообщества",
+ "Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.": "Атлантика и восточная/центральная часть северного Тихого океана; покрытие циклонов не глобальное.",
+ "Potential tropical cyclone": "Потенциальный тропический циклон",
+ "Hurricane": "Ураган",
+ "Tropical storm": "Тропический шторм",
+ "Tropical depression": "Тропическая депрессия",
+ "Subtropical storm": "Субтропический шторм",
+ "Subtropical depression": "Субтропическая депрессия",
+ "Track and cone match this advisory": "Трек и конус соответствуют этой сводке",
+ "Track/cone awaiting advisory {number}": "Трек и конус появятся со сводкой № {number}",
+ "Track/cone unavailable": "Трек/конус недоступны",
+ "Cached advisory · stale source": "Сводка из кэша · источник устарел",
+ "Loading advisories…": "Загрузка сводок…",
+ "{count} active storms": {
+ "one": "{count} активный шторм",
+ "few": "{count} активных шторма",
+ "many": "{count} активных штормов",
+ "other": "{count} активного шторма"
+ },
+ "Position as of {time}": "Положение на {time}",
+ "Maximum sustained wind: {wind} · Pressure: {pressure}": "Макс. устойчивый ветер: {wind} · Давление: {pressure}",
+ "{name} · {classification} · Advisory {number} · issued {time}": "{name} · {classification} · Сводка № {number} · выпущена {time}",
+ "No active NHC/CPHC systems": "Нет активных систем NHC/CPHC",
+ "Advisories unavailable": "Сводки недоступны",
+ "Cyclones · NHC / CPHC": "Циклоны · NHC / CPHC",
+ "Atlantic · E/C Pacific": "Атлантика · вост./центр. Тихий океан",
+ "{storms} · {name} selected": "{storms} · выбран {name}",
+ "Official advisory ↗": "Официальная сводка ↗",
+ "Active NHC and CPHC cyclone advisories": "Действующие сводки NHC и CPHC о циклонах",
+ "Wind unavailable": "Ветер: нет данных",
+ "Advisory center / forecast track": "Центр циклона по сводке / прогнозный трек",
+ "Center-track uncertainty cone": "Конус неопределённости трека центра",
+ "Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.": "Выберите шторм на карте или в списке, чтобы выделить его и переместить к нему камеру. Щёлкните по пустому месту карты, чтобы снять выделение. Контекст сводок NOAA NHC/CPHC. Конус описывает неопределённость прогнозного трека центра, а не размер шторма или всю зону опасности. Подписи прогнозных точек — заблаговременность источника в часах, а не время, рассчитанное от выпуска сводки. Геометрия следует поверхности; высота не отражает высоту погодных явлений. Сверяйтесь с официальной сводкой.",
+ "Directions": "Маршруты",
+ "{mode} — reroute for {modeLower}": "{mode} — перестроить маршрут: {modeLower}",
+ "CLICK MAP": "ЩЁЛКНИТЕ ПО КАРТЕ",
+ "SET A": "ЗАДАТЬ A",
+ "Click a spot on the globe to place A (click again to cancel)": "Щёлкните по точке на глобусе, чтобы поставить A (повторный щелчок — отмена)",
+ "Then click the globe to place the start": "Затем щёлкните по глобусу, чтобы поставить начало",
+ "SET B": "ЗАДАТЬ B",
+ "Click a spot on the globe to place B (click again to cancel)": "Щёлкните по точке на глобусе, чтобы поставить B (повторный щелчок — отмена)",
+ "Then click the globe to place the destination": "Затем щёлкните по глобусу, чтобы поставить пункт назначения",
+ "Swap A and B": "Поменять A и B местами",
+ "FLY ···": "ПОЛЁТ ···",
+ "FLYING": "В ПОЛЁТЕ",
+ "FLY": "ПОЛЁТ",
+ "Fly the camera along the route": "Пролететь камерой по маршруту",
+ "Place A and B first": "Сначала поставьте A и B",
+ "Remove the route and both markers": "Удалить маршрут и обе метки",
+ "press Escape twice to leave Draw": "дважды нажмите Esc, чтобы выйти из режима «Рисование»",
+ "{name} is active — turn {name} off, then set {endpoint}": "Активно: {name} — выключите {name}, затем задайте {endpoint}",
+ "{name} is active — {leave}, then set {endpoint}": "Активно: {name} — {leave}, затем задайте {endpoint}",
+ "Only the first {count} turns of this route are shown": "Показаны только первые повороты маршрута: {count}",
+ "Turn-by-turn directions": "Пошаговые указания",
+ "OSM routing": "Маршрутизация OSM",
+ "DRIVE": "АВТО",
+ "Drive": "На машине",
+ "Another map tool is using clicks — close it, then SET A again": "Щелчки перехватывает другой инструмент карты — закройте его и снова нажмите «ЗАДАТЬ A»",
+ "WALK": "ПЕШКОМ",
+ "Walk": "Пешком",
+ "Routing…": "Построение маршрута…",
+ "BIKE": "ВЕЛО",
+ "Bike": "На велосипеде",
+ "No route found": "Маршрут не найден",
+ "{distance} · {duration} · {mode} · first {count} turns": "{distance} · {duration} · {mode} · первые повороты: {count}",
+ "{distance} · {duration} · {mode}": "{distance} · {duration} · {mode}",
+ "Click the globe to place {endpoint}": "Щёлкните по глобусу, чтобы поставить {endpoint}",
+ "SET B, then click the globe": "Нажмите «ЗАДАТЬ B», затем щёлкните по глобусу",
+ "SET A, then click the globe": "Нажмите «ЗАДАТЬ A», затем щёлкните по глобусу",
+ "Step {step} of {total} · then {leg}": "Шаг {step} из {total} · затем {leg}",
+ "Step {step} of {total}": "Шаг {step} из {total}",
+ "Then: {instruction}": "Затем: {instruction}",
+ "No route found between A and B": "Маршрут между A и B не найден",
+ "Routing failed: {error}": "Не удалось построить маршрут: {error}",
+ "Routing timed out": "Истекло время построения маршрута",
+ "Routing unavailable — no response from the routing service": "Построение маршрута недоступно — сервис маршрутизации не отвечает",
+ "Routing unavailable": "Построение маршрута недоступно",
+ "Fire · FRP {frp} MW": "Пожар · FRP {frp} МВт",
+ "Not contained or unknown": "Не локализован или неизвестно",
+ "Under 50% contained": "Локализован менее чем на 50%",
+ "50–99% contained": "Локализован на 50–99%",
+ "Fully contained": "Полностью локализован",
+ "Colour shows reported containment. Perimeters are simplified to about 100 m.": "Цвет показывает заявленную степень локализации. Контуры упрощены примерно до 100 м.",
+ "MORE DETAIL · 30 m": "БОЛЬШЕ ДЕТАЛЕЙ · 30 м",
+ "Sentinel-2 and Landsat via HLS, 30 m, every 2–6 days": "Sentinel‑2 и Landsat через HLS, 30 м, каждые 2–6 дней",
+ "DAILY OVERVIEW · 250 m": "ЕЖЕДНЕВНЫЙ ОБЗОР · 250 м",
+ "VIIRS daily mosaic, 250 m, follows broad changes; little detail under 25 km": "Ежедневная мозаика VIIRS, 250 м, показывает крупные изменения; мало деталей в масштабе менее 25 км",
+ "Catalog truncated · a newer clear day may exist": "Каталог усечён · возможно, есть более поздний ясный день",
+ "{label} catalog unavailable · {detail}": "Каталог {label} недоступен · {detail}",
+ "Daily overview for today may still be empty until the pass": "Ежедневный обзор за сегодня может оставаться пустым до пролёта спутника",
+ "Sentinel-2": "Sentinel‑2",
+ "Landsat 8/9": "Landsat 8/9",
+ "Daily overview": "Ежедневный обзор",
+ "No frame within {gap} min of {time}": "Нет кадра в пределах {gap} мин от {time}",
+ "No frame within {gap} h of {time}": "Нет кадра в пределах {gap} ч от {time}",
+ "{hours}h {minutes}m ago": "{hours} ч {minutes} мин назад",
+ "{minutes}m ago": "{minutes} мин назад",
+ "{state} · {time} · {lag}": "{state} · {time} · {lag}",
+ "Observed": "Наблюдение",
+ "History": "История",
+ "Observation unavailable": "Наблюдение недоступно",
+ "Waiting for observation": "Ожидание наблюдения",
+ "{detail} · synced": "{detail} · синхр.",
+ "{detail} · nearest": "{detail} · ближайший",
+ "RADAR REFLECTIVITY · dBZ": "РАДИОЛОК. ОТРАЖАЕМОСТЬ · dBZ",
+ "LIGHTNING DENSITY · 15 min accumulation": "ПЛОТНОСТЬ МОЛНИЙ · накопление за 15 мин",
+ "GLOBAL INFRARED · hourly": "ГЛОБАЛЬНЫЙ ИК · ежечасно",
+ "GOES INFRARED · ~5 min": "GOES ИК · ~5 мин",
+ "{state}: {time}": "{state}: {time}",
+ "Latest observation": "Последнее наблюдение",
+ "frame {index}/{total}": "кадр {index}/{total}",
+ "loading": "загрузка",
+ "Observation: unavailable": "Наблюдение: недоступно",
+ "Contiguous US · gaps ≠ no rain": "Континентальные США · пробелы ≠ нет дождя",
+ "Americas + Pacific · not individual strikes": "Америка + Тихий океан · не отдельные разряды",
+ "Color: strikes/km²/min ×10³": "Цвет: разрядов/км²/мин ×10³",
+ "60°S–60°N · typically 2–3 h delayed": "60° ю. ш.–60° с. ш. · обычно задержка 2–3 ч",
+ "North America · infrared imagery": "Северная Америка · ИК-снимки",
+ "Reduced motion · history playback unavailable": "Уменьшение движения · воспроизведение истории недоступно",
+ "Reduced motion · manual history available": "Уменьшение движения · историю можно листать вручную",
+ "Rain radar · US": "Радар осадков · США",
+ "Lightning density · 15 min": "Плотность молний · 15 мин",
+ "Satellite clouds": "Спутниковая облачность",
+ "Americas + Pacific": "Америка + Тихий океан",
+ "Global · 60°S–60°N": "Глобально · 60° ю. ш.–60° с. ш.",
+ "North America": "Северная Америка",
+ "Source observations delayed": "Наблюдения источника задерживаются",
+ "Stale source": "Источник устарел",
+ "Loading next frame…": "Загрузка следующего кадра…",
+ "Map center outside coverage": "Центр карты вне зоны покрытия",
+ "strikes/km²/min ×10³": "разрядов/км²/мин ×10³",
+ "N. America": "Сев. Америка",
+ "Global": "Глобально",
+ "Hourly global mosaic; usually 2–3 hours delayed": "Ежечасная глобальная мозаика; обычно с задержкой 2–3 ч",
+ "GOES regional clouds; approximately 5-minute updates": "Региональная облачность GOES; обновление примерно каждые 5 мин",
+ "Clouds only": "Только облака",
+ "Full": "Полный",
+ "Soft": "Мягко",
+ "Vivid": "Ярко",
+ "Image opacity; does not alter the observed values": "Непрозрачность изображения; не меняет наблюдаемые значения",
+ "View US radar": "Показать радар США",
+ "View Americas & Pacific": "Показать Америку и Тихий океан",
+ "View coverage": "Показать зону покрытия",
+ "{value} strikes/km²/min ×10³ (15-minute density)": "{value} разрядов/км²/мин ×10³ (плотность за 15 мин)",
+ "{value} dBZ radar reflectivity": "Радиолокационная отражаемость: {value} dBZ",
+ "STALE · cached source metadata": "УСТАРЕЛ · метаданные источника из кэша",
+ "Map center is outside source coverage": "Центр карты вне зоны покрытия источника",
+ "NOAA/NWS 15-minute lightning density derived from Vaisala NLDN/GLD360. Coverage 110°E across the Pacific/Americas to 0°, 25°S–80°N. Not a live strike count, global coverage or a safety warning.": "15-минутная плотность молний NOAA/NWS на основе Vaisala NLDN/GLD360. Покрытие — от 110° в. д. через Тихий океан и Америку до 0°, 25° ю. ш.–80° с. ш. Это не подсчёт разрядов в реальном времени, не глобальное покрытие и не предупреждение об опасности.",
+ "NOAA MRMS radar echoes indicate precipitation patterns, not rain rate, a storm warning or a future forecast. Native source approximately 1 km; display is limited to level 6. Frames use exact advertised observation times.": "Радиолокационные эхосигналы NOAA MRMS показывают картину осадков, а не их интенсивность, штормовое предупреждение или прогноз. Исходное разрешение около 1 км; отображение ограничено уровнем 6. Для кадров используется точное заявленное время наблюдений.",
+ "GOES-19/18 longwave infrared Band 14 regional; NESDIS global longwave mosaic. Clouds only dims everything but bright, cold cloud tops; a brightness filter, not a cloud mask. Coverage and freshness differ by region.": "Региональный длинноволновый ИК-канал 14 GOES-19/18; глобальная длинноволновая мозаика NESDIS. Режим «Только облака» затемняет всё, кроме ярких холодных вершин облаков; это фильтр яркости, а не маска облачности. Покрытие и актуальность различаются по регионам.",
+ "REGION": "РЕГИОН",
+ "IMAGE": "СНИМОК",
+ "OPACITY": "НЕПРОЗР.",
+ "Forecast · does not follow history": "Прогноз · не следует за историей",
+ "Wind motion": "Движение ветра",
+ "Wind speed": "Скорость ветра",
+ "Sea-level pressure": "Давление на уровне моря",
+ "Air temperature · 2 m": "Температура воздуха · 2 м",
+ "Global · 1° grid": "Глобально · сетка 1°",
+ "{model} forecast · {time}": "Прогноз {model} · {time}",
+ "Loading forecast": "Загрузка прогноза",
+ "Preparing flow": "Подготовка анимации ветра",
+ "Selected field unavailable": "Выбранное поле недоступно",
+ "Cached forecast · stale": "Прогноз из кэша · устарел",
+ "ECMWF IFS surface forecast": "Приземный прогноз ECMWF IFS",
+ "NOAA GFS surface forecast": "Приземный прогноз NOAA GFS",
+ "Reduced motion": "Уменьшение движения",
+ "Pause visual flow; forecast time does not advance with animation": "Приостановить визуальный поток; время прогноза не сдвигается с анимацией",
+ "None": "Нет",
+ "Speed": "Скорость",
+ "Pressure": "Давление",
+ "Temperature": "Температура",
+ "Wind trails with no field shading": "Следы ветра без заливки поля",
+ "How hard the surface wind is blowing": "Насколько сильно дует приземный ветер",
+ "Sea-level air pressure: broad highs and lows": "Давление на уровне моря: крупные области высокого и низкого давления",
+ "Air temperature two meters above the surface": "Температура воздуха в двух метрах над поверхностью",
+ "Wind speed units": "Единицы скорости ветра",
+ "Read wind at map center": "Узнать ветер в центре карты",
+ "Read the forecast at the center of the map without changing selection": "Получить прогноз в центре карты, не меняя выбор",
+ "{model} forecast · {field} ({unit})": "Прогноз {model} · {field} ({unit})",
+ "Valid: {time}": "Действует на: {time}",
+ "preparing": "подготовка",
+ "Issued: {time}": "Выпущен: {time}",
+ "Selected field unavailable · wind remains visible": "Выбранное поле недоступно · ветер остаётся видимым",
+ "{error} · wind remains visible": "{error} · ветер остаётся видимым",
+ "Surface wind at 10 m. Approximately 1° global grid. Curves follow the 10 m wind field, lifted 12 km for visibility; display height is not weather altitude. View lighting is for readability. Animation shows flow through one fixed forecast; it does not advance time. Color fields drape the globe basemap or the active photorealistic 3D Tiles.": "Приземный ветер на высоте 10 м. Глобальная сетка около 1°. Линии следуют полю ветра на 10 м и подняты на 12 км для наглядности; высота отображения не является высотой погодных явлений. Освещение вида — для удобства чтения. Анимация показывает поток в одном фиксированном прогнозе и не сдвигает время. Цветовые поля накладываются на подложку глобуса или на активные фотореалистичные 3D Tiles.",
+ "MODEL": "МОДЕЛЬ",
+ "FIELD": "ПОЛЕ",
+ "UNITS": "ЕДИНИЦЫ",
+ "MOTION": "ДВИЖЕНИЕ",
+ "Forecast": "Прогноз",
+ "Interpolated model forecast on an approximately 1° grid. Broad weather patterns, not a street-level measurement.": "Интерполированный модельный прогноз на сетке около 1°. Общая погодная обстановка, а не измерение на уровне улицы.",
+ "No surface reading": "Нет приземных данных",
+ "Aim the map center at Earth": "Наведите центр карты на Землю",
+ " · calm": " · штиль",
+ " from {direction}": " с {direction}",
+ "WIND AT {coordinates}": "ВЕТЕР В ТОЧКЕ {coordinates}",
+ "{model} · valid {time}": "{model} · на {time}",
+ "Focusing {label}": "Фокусировка: {label}",
+ "Source": "Источник",
+ "Could not leave scene: {scene}": "Не удалось выйти из сцены: {scene}",
+ "Seeked: {scene} / {shot}": "Перемотано: {scene} / {shot}",
+ "Scene transition limit reached — load a shot to reset": "Достигнут лимит переходов сцены — загрузите кадр, чтобы сбросить счётчик",
+ "Export failed: {error}": "Ошибка экспорта: {error}",
+ "Imported {file}": "Импортировано: {file}",
+ "Import failed: {error}": "Ошибка импорта: {error}",
+ "Import failed (could not read JSON file)": "Ошибка импорта (не удалось прочитать файл JSON)",
+ "Layers refused: {layers}": "Слои отклонены: {layers}",
+ "Scene {n}": "Сцена {n}",
+ "Cannot update {scene}: shot inventory changed": "Не удалось обновить {scene}: изменился состав кадров",
+ "Cannot update {scene}: evidence beats changed": "Не удалось обновить {scene}: изменились этапы свидетельств",
+ "Cannot update {scene}: shot bindings are incomplete": "Не удалось обновить {scene}: привязки кадров неполные",
+ "Updated {count} shots: {scene}": {
+ "one": "Обновлён {count} кадр: {scene}",
+ "few": "Обновлено {count} кадра: {scene}",
+ "many": "Обновлено {count} кадров: {scene}",
+ "other": "Обновлено {count} кадра: {scene}"
+ },
+ "Appended {count} shots: {scene}": {
+ "one": "Добавлен {count} кадр: {scene}",
+ "few": "Добавлено {count} кадра: {scene}",
+ "many": "Добавлено {count} кадров: {scene}",
+ "other": "Добавлено {count} кадра: {scene}"
+ },
+ "Select a feature or use Tab and Enter to choose an action.": "Выберите объект на карте или используйте Tab и Enter, чтобы выбрать действие.",
+ "Selected feature: {feature}. Choose an action.": "Выбран объект: {feature}. Выберите действие.",
+ "Action complete": "Действие выполнено",
+ "Action unavailable or cancelled": "Действие недоступно или отменено",
+ "Scene actions": "Действия сцены",
+ "Bhote Koshi Evidence Sequence": "Последовательность свидетельств: Bhote Koshi",
+ "Nepal Flood Incident": "Наводнение в Непале",
+ "{count} scenes": {
+ "one": "{count} сцена",
+ "few": "{count} сцены",
+ "many": "{count} сцен",
+ "other": "{count} сцены"
+ },
+ "{count} shots": {
+ "one": "{count} кадр",
+ "few": "{count} кадра",
+ "many": "{count} кадров",
+ "other": "{count} кадра"
+ },
+ "{count} data packs": {
+ "one": "{count} пакет данных",
+ "few": "{count} пакета данных",
+ "many": "{count} пакетов данных",
+ "other": "{count} пакета данных"
+ },
+ "{scene} / {pack}: {status}. File: {path}. {attribution} · {license}": "{scene} / {pack}: {status}. Файл: {path}. {attribution} · {license}",
+ "Unavailable layers: {layers}": "Недоступные слои: {layers}",
+ "{bytes} bundled bytes verified. Files stay in memory for this session. Reimport the bundle after reloading the app.": "Проверено байт в архиве: {bytes}. Файлы хранятся в памяти только в этом сеансе. После перезагрузки приложения импортируйте архив снова.",
+ "Review scene import": "Проверка импорта сцены",
+ "Nothing is loaded or changed until you apply this file.": "Ничего не загружается и не меняется, пока вы не примените этот файл.",
+ "Ready to import": "Готово к импорту",
+ "Apply replaces the current project. Export your current project first if you want to keep both.": "Применение заменит текущий проект. Чтобы не потерять его, сначала экспортируйте текущий проект.",
+ "Apply import": "Применить импорт",
+ "Import was not applied. The current project may have changed.": "Импорт не применён. Возможно, текущий проект изменился.",
+ "Select a scene and shot first": "Сначала выберите сцену и кадр",
+ "Edit scene details": "Изменить параметры сцены",
+ "Camera positions use degrees and meters above the ellipsoid. Drafts are validated before they replace your saved scene.": "Положения камеры задаются в градусах и метрах над эллипсоидом. Перед заменой сохранённой сцены черновик проверяется.",
+ "Anchors and data packs": "Якоря и пакеты данных",
+ "Shot camera, timing, packs and actions": "Камера кадра, тайминг, пакеты и действия",
+ "New anchor ID": "ID нового якоря",
+ "Capture camera as anchor": "Сохранить камеру как якорь",
+ "Anchor added to draft": "Якорь добавлен в черновик",
+ "Set move start to current camera": "Начало перелёта — текущая камера",
+ "Move added to draft; destination remains the shot camera": "Перелёт добавлен в черновик; конечной точкой остаётся камера кадра",
+ "Use ordinary flight": "Использовать обычный перелёт",
+ "Invalid shot JSON": "Некорректный JSON кадра",
+ "Apply details": "Применить параметры",
+ "Select a scene first": "Сначала выберите сцену",
+ "Share selected scene": "Поделиться выбранной сценой",
+ "Scene JSON preserves authored settings and attribution. It does not include asset files. Bundles include only pack files you choose here or previously imported bundle files.": "JSON сцены сохраняет авторские настройки и атрибуцию, но не содержит файлов ресурсов. Архив включает только файлы пакетов, выбранные здесь, или файлы ранее импортированных архивов.",
+ "Download scene JSON": "Скачать JSON сцены",
+ "Choose data-pack files": "Выберите файлы пакетов данных",
+ "Or choose a data-pack folder": "Или выберите папку пакета данных",
+ "Download asset bundle": "Скачать архив ресурсов",
+ "Asset bundle downloaded": "Архив ресурсов скачан",
+ "Could not complete this action. Check the file, references and selected assets.": "Не удалось выполнить действие. Проверьте файл, ссылки и выбранные ресурсы.",
+ "RTL-SDR sample stream stopped": "Поток выборок RTL-SDR остановлен",
+ "Switching to {mode}…": "Переключение на {mode}…",
+ "Browser audio is suspended; select FM again to resume it": "Звук в браузере приостановлен; выберите FM ещё раз, чтобы возобновить его",
+ "RTL-SDR gain change failed": "Не удалось изменить усиление RTL-SDR",
+ "Tuned to {mhz} MHz FM": "Настроено на FM {mhz} МГц",
+ "FM signal found at {mhz} MHz": "Найден FM-сигнал на {mhz} МГц",
+ "No FM signal found": "FM-сигнал не найден",
+ "Seek stopped": "Поиск остановлен",
+ "Browser location is unavailable": "Местоположение браузера недоступно",
+ "Receiver location was not granted": "Доступ к местоположению приёмника не предоставлен",
+ "RTL-SDR disconnected": "RTL-SDR отключён",
+ "No RTL-SDR device selected": "Устройство RTL-SDR не выбрано",
+ "WebUSB requires desktop Chrome or Edge on localhost/HTTPS": "Для WebUSB нужен настольный Chrome или Edge на localhost/HTTPS",
+ "RTL-SDR access failed; close other SDR apps and check USB permissions": "Нет доступа к RTL-SDR; закройте другие SDR-приложения и проверьте разрешения USB",
+ "RTL-SDR connection failed": "Не удалось подключить RTL-SDR",
+ "Receiving 1090 MHz ADS-B": "Приём ADS-B на 1090 МГц",
+ "Receiving broadcast FM": "Приём FM-вещания",
+ "Connect an RTL-SDR to begin.": "Подключите RTL-SDR, чтобы начать.",
+ "WebUSB is unavailable in this browser": "WebUSB недоступен в этом браузере",
+ "SDR decoder worker failed": "Сбой обработчика декодера SDR",
+ "WebUSB requires desktop Chrome or Edge": "Для WebUSB нужен настольный Chrome или Edge",
+ "Waiting for an RTL-SDR device…": "Ожидание устройства RTL-SDR…",
+ "Browser audio is suspended; press Connect again to resume it": "Звук в браузере приостановлен; нажмите «Подключить» ещё раз, чтобы возобновить его",
+ "Return map to straight-down view": "Вернуть карту к виду сверху",
+ "Tilt map to oblique view": "Наклонить карту в перспективный вид",
+ "Reset map to north up. Current heading {heading} degrees": "Повернуть карту севером вверх. Текущий курс: {heading}°",
+ "HDG": "КУРС",
+ "PITCH": "ТАНГАЖ",
+ "FOV": "ОБЗОР",
+ "RANGE": "ДАЛЬН.",
+ "HGT": "ВЫС.",
+ "{value} KM/H": "{value} КМ/Ч",
+ "NORMAL": "ОБЫЧНЫЙ",
+ "ANIME": "АНИМЕ",
+ "NOIR": "НУАР",
+ "Rendered globe frames per second · toggle with `": "Кадров глобуса в секунду · переключение клавишей `",
+ "Utilities": "Инструменты",
+ "Other layers": "Другие слои",
+ "Movement": "Движение",
+ "Infrastructure": "Инфраструктура",
+ "Events": "События",
+ "Weather": "Погода",
+ "LOCATED": "ОПРЕДЕЛЕНА",
+ "LOCATE": "ГЕОПОЗИЦИЯ",
+ "IDLE": "ОЖИДАНИЕ",
+ "TUNING": "НАСТРОЙКА",
+ "STREAMING": "ПРИЁМ",
+ "UNSUPPORTED": "НЕ ПОДДЕРЖ.",
+ "waiting for IQ": "ожидание IQ",
+ "{count} messages": {
+ "one": "{count} сообщение",
+ "few": "{count} сообщения",
+ "many": "{count} сообщений",
+ "other": "{count} сообщения"
+ },
+ "DSP {count} blocks": {
+ "one": "DSP {count} блок",
+ "few": "DSP {count} блока",
+ "many": "DSP {count} блоков",
+ "other": "DSP {count} блока"
+ },
+ "DSP waiting": "DSP ожидает",
+ "{level} dBFS audio": "аудио {level} dBFS",
+ "audio signal --": "аудиосигнал --",
+ "audio {state}": "аудио: {state}",
+ "{count} HEARD": {
+ "one": "СЛЫШНО: {count}",
+ "few": "СЛЫШНО: {count}",
+ "many": "СЛЫШНО: {count}",
+ "other": "СЛЫШНО: {count}"
+ },
+ "DISCONNECT": "ОТКЛЮЧИТЬ",
+ "CONNECT": "ПОДКЛЮЧИТЬ",
+ "LOCATING…": "ОПРЕДЕЛЯЮ…",
+ "Drag to resize · double-click the header to snap back": "Перетащите, чтобы изменить размер · двойной щелчок по заголовку — вернуть на место",
+ "CH {index} / {total}": "КАН. {index} / {total}",
+ "Station unavailable after directory refresh": "Станция недоступна после обновления каталога",
+ "Clear reading": "Очистить показания",
+ "Earlier observation": "Более раннее наблюдение",
+ "Observed history": "История наблюдений",
+ "Later observation": "Более позднее наблюдение",
+ "Latest": "Последние",
+ "Newest frame per product": "Самый свежий кадр каждого продукта",
+ "Replay observed history": "Воспроизвести историю наблюдений",
+ "S on another day replaces it · × unpins": "S в другой день заменяет его · × открепляет",
+ "← → preview · S shows the focused day": "← → просмотр · S показывает выбранный день",
+ "Recent imagery": "Свежие снимки",
+ "ZOOM IN": "ПРИБЛИЗИТЬ",
+ "Fly in until the view fits the 1,000 km limit": "Приблизьтесь, пока вид не уложится в предел 1000 км",
+ "Imagery days, newest first · arrows move, S or A and B pin": "Дни со снимками, сначала новые · стрелки — перемещение, S или A и B — закрепить",
+ "On the map": "На карте",
+ "Mode": "Режим",
+ "Imagery on Esri · Google 3D returns when cleared": "Подложка: Esri · сброс вернёт Google 3D",
+ "Imagery opacity": "Непрозрачность снимков",
+ "SWAP": "ПОМЕНЯТЬ",
+ "VS BASEMAP": "С ПОДЛОЖКОЙ",
+ "Trade the two sides of the divider": "Поменять местами стороны разделителя",
+ "A / B": "A / B",
+ "Newest low-cloud day for this box · scene cloud, not box cloud": "Самый свежий малооблачный день для этой области · облачность всей сцены, а не области",
+ "Newest day covering this box · cloudier than 20%": "Самый свежий день с покрытием этой области · облачность выше 20%",
+ "SELECT BOX": "ВЫДЕЛИТЬ",
+ "Drag a box on the map (Esc cancels)": "Выделите область на карте (Esc — отмена)",
+ "Newest day with imagery for this box · partial coverage": "Самый свежий день со снимками этой области · частичное покрытие",
+ "USE VIEW": "ПО ВИДУ",
+ "Use the current view as the box": "Использовать текущий вид как область",
+ "Newest daily overview for this box": "Самый свежий ежедневный обзор для этой области",
+ "Forget the box and its images": "Сбросить область и её снимки",
+ "newest clear day": "самый свежий ясный день",
+ "newest day (cloudy)": "самый свежий день (облачно)",
+ "newest day (partial coverage)": "самый свежий день (частичное покрытие)",
+ "START HERE": "НАЧНИТЕ ЗДЕСЬ",
+ "newest overview": "самый свежий обзор",
+ "No imagery": "Нет снимков",
+ "Checking": "Проверка",
+ "Loading": "Загрузка",
+ "PREVIEW": "ПРОСМОТР",
+ "Newest day with imagery for this box": "Самый свежий день со снимками этой области",
+ "SHOW": "ПОКАЗАТЬ",
+ "Pin {day} as {slot}": "Закрепить {day} как {slot}",
+ "Show {day}": "Показать {day}",
+ "pinned {slot}": "закреплено как {slot}",
+ "shown": "показано",
+ "preview": "просмотр",
+ "start here": "начните здесь",
+ "No box": "Нет области",
+ "Searching": "Поиск",
+ "Every day is empty here": "Здесь все дни пустые",
+ "Sources off": "Источники выключены",
+ "VS": "СРАВН.",
+ "Not set": "Не задано",
+ "Basemap": "Подложка",
+ "Source off": "Источник выключен",
+ "Unpin {slot}": "Открепить {slot}",
+ "Unpin the image": "Открепить снимок",
+ "EXPORT {slot}": "ЭКСП. {slot}",
+ "EXPORT": "ЭКСПОРТ",
+ "Download {slot} as a PNG": "Скачать {slot} в PNG",
+ "Download the image as a PNG": "Скачать снимок в PNG",
+ "Box {width} × {height} km": "Область {width} × {height} км",
+ "no imagery": "нет снимков",
+ "Acquired {time}": "Снято {time}",
+ "cloud unknown": "облачность неизвестна",
+ "Coverage {coverage}": "Покрытие {coverage}",
+ "unknown": "неизвестно",
+ "START HERE · {reason}": "НАЧНИТЕ ЗДЕСЬ · {reason}",
+ "Daily overview shows little detail in a box this small": "В такой маленькой области ежедневный обзор почти не показывает деталей",
+ "{percent}% cloud": "облачность {percent}%",
+ "Imagery: NASA GIBS and Worldview · HLS (Sentinel-2, Landsat 8/9) and VIIRS": "Снимки: NASA GIBS и Worldview · HLS (Sentinel‑2, Landsat 8/9) и VIIRS",
+ "{min}–{max}% cloud": "облачность {min}–{max}%",
+ "Details": "Подробности",
+ "Times, coverage, sources": "Время, покрытие, источники",
+ "HIDE EMPTY DAYS": "СКРЫТЬ ПУСТЫЕ ДНИ",
+ "SHOW EMPTY DAYS · {count}": "ПОКАЗАТЬ ПУСТЫЕ ДНИ · {count}",
+ "Days the probe found empty in this box": "Дни, в которые проверка не нашла снимков в этой области",
+ "NO BOX": "НЕТ ОБЛАСТИ",
+ "image": "снимок",
+ "BASEMAP": "ПОДЛОЖКА",
+ "The basemap": "Подложка",
+ "basemap": "подложка",
+ "SEARCHING": "ПОИСК",
+ "{count} DAYS": {
+ "one": "{count} ДЕНЬ",
+ "few": "{count} ДНЯ",
+ "many": "{count} ДНЕЙ",
+ "other": "{count} ДНЯ"
+ },
+ "Recent imagery against the basemap divider": "Разделитель: свежие снимки и подложка",
+ "Recent imagery A and B divider": "Разделитель свежих снимков A и B",
+ "{before} {left} percent, {after} {right} percent": "{before}: {left}%, {after}: {right}%",
+ "Zoom in or draw a smaller box": "Приблизьте карту или выделите область поменьше",
+ "Select a box or use the view": "Выделите область или используйте текущий вид",
+ "Searching the last 30 days": "Поиск за последние 30 дней",
+ "No days to show for this box": "Для этой области нечего показать",
+ "Drag the divider · SWAP trades sides": "Тяните разделитель · «ПОМЕНЯТЬ» — смена сторон",
+ "Export failed · {error}": "Ошибка экспорта · {error}",
+ "← → preview · A or B pins the focused day": "← → просмотр · A или B закрепляет выбранный день",
+ "← → preview the other side · A or B pins it": "← → просмотр другой стороны · A или B закрепляет её",
+ "LOAD": "ЗАГРУЗИТЬ",
+ "No shots yet. Use CAPTURE SHOT to save current look.": "Кадров пока нет. Нажмите «СДЕЛАТЬ КАДР», чтобы сохранить текущий вид.",
+ "Double-click to rename": "Дважды щёлкните, чтобы переименовать",
+ "Shot name": "Название кадра",
+ "RETRYING ALPR CAMERAS": "ПОВТОРНАЯ ЗАГРУЗКА КАМЕР ALPR",
+ "FETCHING ALPR CAMERAS": "ЗАГРУЗКА КАМЕР ALPR",
+ "OVERPASS TEMPORARILY UNAVAILABLE": "OVERPASS ВРЕМЕННО НЕДОСТУПЕН",
+ "Weather data by Open-Meteo.com": "Данные о погоде: Open-Meteo.com",
+ "ESC EXIT": "ESC ВЫХОД",
+ "C TOGGLE": "C ПЕРЕКЛ.",
+ "SIG": "СИГН.",
+ "NEWS": "НОВОСТИ",
+ "LOCAL": "МЕСТН.",
+ "Cockpit briefing pages": "Страницы брифинга кабины",
+ "MM": "ММ",
+ "KTS": "УЗ",
+ "FT": "ФТ",
+ "FLT": "РЕЙСЫ",
+ "MIL": "ВОЕН.",
+ "SITE": "ОБЪЕКТЫ",
+ "WX": "ПОГОДА",
+ "DIRECTORY: RADIO BROWSER": "КАТАЛОГ: RADIO BROWSER",
+ "Use your location for faster ADS-B position decoding": "Использовать ваше местоположение для ускорения декодирования позиций ADS-B",
+ "CHANGE DEVICE": "СМЕНИТЬ",
+ "Choose a different RTL-SDR or receiver channel": "Выбрать другой RTL-SDR или канал приёмника",
+ "TUNE": "НАСТРОИТЬ",
+ "◀ SEEK": "◀ ПОИСК",
+ "SEEK ▶": "ПОИСК ▶",
+ "Local RTL-SDR receiver": "Локальный приёмник RTL-SDR",
+ "RTL-SDR receiver mode": "Режим приёмника RTL-SDR",
+ "Seek broadcast FM stations": "Поиск FM-радиостанций",
+ "Tune available internet radio stations": "Настройка на доступные интернет-радиостанции",
+ "Local SDR volume": "Громкость локального SDR",
+ "GAIN": "УСИЛЕНИЕ",
+ "FM MHZ": "FM МГЦ",
+ "AUTO": "АВТО",
+ "Chrome/Edge · WebUSB · one local tuner shared by FM and the Local ADS-B layer.": "Chrome/Edge · WebUSB · один локальный тюнер для FM и слоя «Локальный ADS-B».",
+ "RTL-SDR tuner gain for the current mode": "Усиление тюнера RTL-SDR для текущего режима",
+ "WEATHER": "ПОГОДА",
+ "Active weather products": "Активные погодные продукты",
+ "RECENT IMAGERY": "СВЕЖИЕ СНИМКИ",
+ "Imagery days in the box": "Дни со снимками в области",
+ "MSG/S": "СООБЩ./С",
+ "HEARD": "СЛЫШНО",
+ "POSITIONED": "С КООРД.",
+ "SDR VOL": "ГРОМК. SDR",
+ "LOCAL RTL-SDR": "ЛОКАЛЬНЫЙ RTL-SDR",
+ "Cyber sonar contact scanner": "Кибер-сонар: сканер контактов",
+ "Sonar ring count": "Число колец сонара",
+ "Sonar ring range": "Дальность колец сонара",
+ "Sonar intensity": "Интенсивность сонара",
+ "Cyber contact and label opacity": "Непрозрачность контактов и подписей в режиме «Кибер»",
+ "Minimum opacity for map dots, icons, models, brackets, and labels between sonar passes": "Минимальная непрозрачность точек, значков, моделей, рамок и подписей на карте между проходами сонара",
+ "Sonar sector width": "Ширина сектора сонара",
+ "Rings": "Кольца",
+ "Range": "Дальность",
+ "Power": "Мощность",
+ "Opacity": "Непрозрачность",
+ "Sector": "Сектор",
+ "Cyber": "Кибер",
+ "Sonar": "Сонар",
+ "Turn Street Level on or off": "Включить или выключить «Уличные снимки»",
+ "Toggle straight-down and tilted map views": "Переключить вид карты: сверху или с наклоном",
+ "Reset map to north up": "Повернуть карту севером вверх",
+ "Reset map bearing to north": "Сбросить азимут карты на север",
+ "Rain radar": "Радар осадков",
+ "Lightning density": "Плотность молний",
+ "LATEST · newest per product": "ПОСЛЕДНИЕ · самые свежие по каждому продукту",
+ "Forecast · valid {valid} · issued {issued}": "Прогноз · действует на {valid} · выпущен {issued}",
+ "{detail} · Does not follow history": "{detail} · не следует за историей",
+ "Forecast · valid {valid}": "Прогноз · действует на {valid}",
+ "{time} · {minutes} min ago": "{time} · {minutes} мин назад",
+ "Active weather": "Активные погодные слои",
+ "MINI": "МИНИ",
+ "STD": "СТД",
+ "standard": "стандартную",
+ "mini": "мини",
+ "COST UNKNOWN": "СТОИМОСТЬ НЕИЗВЕСТНА",
+ "ChatGPT OAuth session: {responses} response(s), {input} input and {output} output tokens, {captions} caption transcription(s) reported.": "Сессия ChatGPT OAuth: ответов — {responses}, входных токенов — {input}, выходных токенов — {output}, транскрипций субтитров — {captions}.",
+ "USD cost and the API spend cap are unavailable for this auth mode.": "Стоимость в USD и лимит расходов API недоступны в этом режиме авторизации.",
+ "Usage is incomplete because a response was still in flight when the session ended.": "Данные об использовании неполные: к моменту завершения сессии один из ответов ещё не был получен.",
+ "Toggle voice control": "Включить или выключить голосовое управление",
+ "Activate to toggle voice": "Активируйте, чтобы включить или выключить голос",
+ "Voice active": "Голос активен",
+ "Voice could not be started.": "Не удалось запустить голос.",
+ "degraded": "с перебоями",
+ "stale": "устарел",
+ "partial": "частично",
+ "fallback": "резерв",
+ "unavailable": "недоступен",
+ "{label} on": "{label}: вкл.",
+ "{label} off": "{label}: выкл.",
+ "Frame aircraft": "Показать самолёты в кадре",
+ "Frame military aircraft": "Показать военные самолёты в кадре",
+ "Frame ships": "Показать суда в кадре",
+ "Frame satellites": "Показать спутники в кадре",
+ "Frame contacts": "Показать контакты в кадре",
+ "{count} aircraft in frame": {
+ "one": "{count} самолёт в кадре",
+ "few": "{count} самолёта в кадре",
+ "many": "{count} самолётов в кадре",
+ "other": "{count} самолёта в кадре"
+ },
+ "{count} military aircraft in frame": {
+ "one": "{count} военный самолёт в кадре",
+ "few": "{count} военных самолёта в кадре",
+ "many": "{count} военных самолётов в кадре",
+ "other": "{count} военного самолёта в кадре"
+ },
+ "{count} ships in frame": {
+ "one": "{count} судно в кадре",
+ "few": "{count} судна в кадре",
+ "many": "{count} судов в кадре",
+ "other": "{count} судна в кадре"
+ },
+ "{count} satellites in frame": {
+ "one": "{count} спутник в кадре",
+ "few": "{count} спутника в кадре",
+ "many": "{count} спутников в кадре",
+ "other": "{count} спутника в кадре"
+ },
+ "{count} contacts in frame": {
+ "one": "{count} контакт в кадре",
+ "few": "{count} контакта в кадре",
+ "many": "{count} контактов в кадре",
+ "other": "{count} контакта в кадре"
+ },
+ "Nearest military aircraft": "Ближайшие военные самолёты",
+ "Nearest ships": "Ближайшие суда",
+ "Nearest satellites": "Ближайшие спутники",
+ "Nearest aircraft": "Ближайшие самолёты",
+ "{first} and {second}": "{first} и {second}",
+ "Camera range {range}": "Дальность камеры: {range}",
+ "Within {radius} of the view": "В радиусе {radius} от вида",
+ "Labels on": "Подписи включены",
+ "Framing uses the nearest 80 loaded contacts": "В кадр берутся 80 ближайших загруженных контактов",
+ "{distance} from {location}": "{location}: {distance}",
+ "Altitude {altitude}": "Высота {altitude}",
+ "{origin} to {destination}": "{origin} → {destination}",
+ "from {origin}": "откуда: {origin}",
+ "to {destination}": "куда: {destination}",
+ "Registration {registration}": "Регистрационный номер: {registration}",
+ "Route {route}": "Маршрут {route}",
+ "View state": "Состояние вида",
+ "Marked {count} places": {
+ "one": "Отмечено {count} место",
+ "few": "Отмечено {count} места",
+ "many": "Отмечено {count} мест",
+ "other": "Отмечено {count} места"
+ },
+ "Nothing marked": "Ничего не отмечено",
+ "Not found: {places}": "Не найдено: {places}",
+ "Tracing outlines": "Построение контуров",
+ "Mark the map": "Отметить на карте",
+ "Mark {targets} +{more}": "Отметить {targets} +{more}",
+ "Mark {targets}": "Отметить {targets}",
+ "Fly to {place}": "Перелёт: {place}",
+ "Nearest aircraft to {place}": "Ближайший самолёт: {place}",
+ "Read the view": "Осмотреть видимую область",
+ "Check view state": "Проверить состояние вида",
+ "Frame {target}": "Показать в кадре: {target}",
+ "Finding places": "Поиск мест",
+ "Tracing outline": "Построение контура",
+ "Looking up place": "Поиск места",
+ "Flying": "Перелёт",
+ "Turning on layer": "Включение слоя",
+ "Loading aircraft": "Загрузка самолётов",
+ "Picking nearest": "Выбор ближайших",
+ "Working": "Выполняется",
+ "{value} feet": "{value} фт",
+ "nominal": "в норме",
+ "Source: {label}": "Источник: {label}",
+ "N": "С",
+ "NNE": "ССВ",
+ "NE": "СВ",
+ "ENE": "ВСВ",
+ "E": "В",
+ "ESE": "ВЮВ",
+ "SE": "ЮВ",
+ "SSE": "ЮЮВ",
+ "S": "Ю",
+ "SSW": "ЮЮЗ",
+ "SW": "ЮЗ",
+ "WSW": "ЗЮЗ",
+ "W": "З",
+ "WNW": "ЗСЗ",
+ "NW": "СЗ",
+ "NNW": "ССЗ",
+ "Local ADS-B": "Локальный ADS-B",
+ "Transit": "Общественный транспорт",
+ "Recent Imagery": "Свежие снимки",
+ "Fire Perimeters": "Контуры пожаров",
+ "Cyclone advisories": "Сводки о циклонах",
+ "EDIT DETAILS": "ИЗМЕНИТЬ ПАРАМЕТРЫ",
+ "SHARE SCENE": "ПОДЕЛИТЬСЯ СЦЕНОЙ",
+ "ON/OFF": "ВКЛ/ВЫКЛ",
+ "Voice assistant": "Голосовой ассистент",
+ "VOICE": "ГОЛОС",
+ "Dismiss voice card": "Закрыть карточку голоса",
+ "YOU": "ВЫ",
+ "THIS": "ЭТО",
+ "HERE": "ЗДЕСЬ",
+ "Plan": "План",
+ "Referenced items": "Упомянутые объекты",
+ "NOTES & SOURCES": "ЗАМЕТКИ И ИСТОЧНИКИ",
+ "ΔN": "ΔС",
+ "ΔE": "ΔВ",
+ "action|CLEAR": "СБРОСИТЬ",
+ "ALPR Cameras": "Камеры ALPR",
+ "Military aircraft": "Военные самолёты",
+ "Vessels": "Суда",
+ "CCTV + Street View fallback": "CCTV + резерв: Просмотр улиц",
+ "OpenStreetMap + optional Google Maps Places": "OpenStreetMap + Google Maps Places (опц.)",
+ "GFS / ECMWF IFS · FORECAST": "GFS / ECMWF IFS · ПРОГНОЗ",
+ "NOAA nowCOAST · OBSERVED": "NOAA nowCOAST · НАБЛЮДЕНИЕ",
+ "NASA FIRMS · LIVE": "NASA FIRMS · ОНЛАЙН",
+ "data source|Local": "Локальные данные",
+ "overview": "обзор",
+ "{percent}% scene cloud": "облачность сцены {percent}%",
+ "{min}–{max}% scene cloud": "облачность сцены {min}–{max}%",
+ "Sentinel-2 via HLS": "Sentinel‑2 через HLS",
+ "Landsat 8/9 via HLS": "Landsat 8/9 через HLS",
+ "coverage|full": "полное",
+ "coverage|partial": "частичное",
+ "m": "м",
+ "km/h": "км/ч",
+ "m/s": "м/с",
+ "mph": "миль/ч",
+ "hPa": "гПа",
+ "kt": "уз",
+ "km": "км",
+ "h": "ч",
+ "min": "мин",
+ "s": "с",
+ "direction|left": "налево",
+ "direction|right": "направо",
+ "direction|slightly left": "плавно налево",
+ "direction|slightly right": "плавно направо",
+ "direction|sharply left": "резко налево",
+ "direction|sharply right": "резко направо",
+ "direction|straight": "прямо",
+ "direction|around": "в обратную сторону",
+ "ordinal|{number}st": "{number}-й",
+ "ordinal|{number}nd": "{number}-й",
+ "ordinal|{number}rd": "{number}-й",
+ "ordinal|{number}th": "{number}-й",
+ "Head out on {road}": "Начните движение по {road}",
+ "Head out": "Начните движение",
+ "Arrive at your destination": "Вы прибыли в пункт назначения",
+ "Arrive at your destination, on the left": "Пункт назначения слева",
+ "Arrive at your destination, on the right": "Пункт назначения справа",
+ "Make a U-turn": "Развернитесь",
+ "Make a U-turn onto {road}": "Развернитесь на {road}",
+ "Continue straight": "Продолжайте прямо",
+ "Continue straight onto {road}": "Продолжайте движение прямо по {road}",
+ "Turn {direction}": "Поверните {direction}",
+ "Turn {direction} onto {road}": "Поверните {direction} на {road}",
+ "maneuver|Turn": "Поверните",
+ "Turn onto {road}": "Поверните на {road}",
+ "Continue {direction}": "Продолжайте движение {direction}",
+ "Continue {direction} onto {road}": "Продолжайте движение {direction} по {road}",
+ "maneuver|Continue": "Продолжайте движение",
+ "Continue onto {road}": "Продолжайте движение по {road}",
+ "At the end of the road, turn {direction}": "В конце дороги поверните {direction}",
+ "At the end of the road, turn {direction} onto {road}": "В конце дороги поверните {direction} на {road}",
+ "At the end of the road, continue": "В конце дороги продолжайте движение",
+ "At the end of the road, continue onto {road}": "В конце дороги продолжайте движение по {road}",
+ "Keep {direction} at the fork": "На развилке держитесь {direction}",
+ "Keep {direction} at the fork onto {road}": "На развилке держитесь {direction}, чтобы выехать на {road}",
+ "Continue at the fork": "На развилке продолжайте движение",
+ "Continue at the fork onto {road}": "На развилке продолжайте движение по {road}",
+ "Merge {direction}": "Перестройтесь {direction}",
+ "Merge {direction} onto {road}": "Перестройтесь {direction} на {road}",
+ "maneuver|Merge": "Перестройтесь",
+ "Merge onto {road}": "Въезжайте на {road}",
+ "Take the ramp on the {direction}": "Въезжайте на съезд {direction}",
+ "Take the ramp on the {direction} onto {road}": "Въезжайте по съезду {direction} на {road}",
+ "Take the ramp": "Въезжайте на съезд",
+ "Take the ramp onto {road}": "Въезжайте по съезду на {road}",
+ "Take the exit on the {direction}": "Сверните на съезд {direction}",
+ "Take the exit on the {direction} onto {road}": "Сверните на съезд {direction} на {road}",
+ "Take the exit": "Сверните на съезд",
+ "Take the exit onto {road}": "Сверните на съезд на {road}",
+ "At the roundabout, take the {exit} exit": "На кольце сверните на {exit} съезд",
+ "At the roundabout, take the {exit} exit onto {road}": "На кольце сверните на {exit} съезд на {road}",
+ "Enter the roundabout": "Въезжайте на кольцо",
+ "Enter the roundabout onto {road}": "Въезжайте на кольцо, выезд на {road}",
+ "At the roundabout, turn {direction}": "На кольце поверните {direction}",
+ "At the roundabout, turn {direction} onto {road}": "На кольце поверните {direction} на {road}",
+ "At the roundabout, continue": "На кольце продолжайте движение",
+ "At the roundabout, continue onto {road}": "На кольце продолжайте движение по {road}",
+ "Exit the roundabout": "Съезжайте с кольца",
+ "Exit the roundabout onto {road}": "Съезжайте с кольца на {road}",
+ "Use the {direction} lane": "Займите {direction} полосу",
+ "Use the {direction} lane onto {road}": "Займите {direction} полосу, чтобы выехать на {road}",
+ "voice|OFF": "ВЫКЛ",
+ "voice|CONNECTING": "СВЯЗЬ…",
+ "voice|LISTENING": "СЛУШАЮ",
+ "voice|EXECUTING": "ДЕЛАЮ",
+ "voice|ERROR": "ОШИБКА",
+ "MIC": "МИК",
+ "WORKING": "В РАБОТЕ",
+ "DONE": "ГОТОВО",
+ "Outline traced": "Контур построен",
+ "Outline unavailable": "Контур недоступен",
+ "in progress": "выполняется",
+ "done": "готово",
+ "failed": "ошибка",
+ "cancelled": "отменено",
+ "view band|STREET": "УЛИЦА",
+ "view band|CITY": "ГОРОД",
+ "view band|METRO": "АГЛОМЕРАЦИЯ",
+ "view band|REGIONAL": "РЕГИОН",
+ "view band|GLOBAL": "ПЛАНЕТА",
+ "NEAR {poi} ({city}) {distance}": "РЯДОМ: {poi} ({city}) {distance}",
+ "SECTOR {lat} {lon}": "СЕКТОР {lat} {lon}",
+ "ARCTIC": "АРКТИКА",
+ "ANTARCTIC": "АНТАРКТИКА",
+ "NORTH AMERICA": "СЕВЕРНАЯ АМЕРИКА",
+ "SOUTH AMERICA": "ЮЖНАЯ АМЕРИКА",
+ "EUROPE": "ЕВРОПА",
+ "AFRICA": "АФРИКА",
+ "ASIA": "АЗИЯ",
+ "OCEANIA": "ОКЕАНИЯ",
+ "NORTHERN OCEANIC GRID": "СЕВЕРНАЯ ОКЕАНСКАЯ СЕТКА",
+ "SOUTHERN OCEANIC GRID": "ЮЖНАЯ ОКЕАНСКАЯ СЕТКА",
+ "N/A": "Н/Д",
+ "{label} · {radius} AIR/SEA WINDOW": "{label} · ОКНО ВОЗДУХ/МОРЕ {radius}",
+ "{scope} · INSTALLATIONS {coverage}": "{scope} · ОБЪЕКТЫ: {coverage}",
+ "{source} · LOCATION QUERY · RECENT": "{source} · ЗАПРОС ПО МЕСТУ · НЕДАВНИЕ",
+ "ft": "фт",
+ "kts": "уз",
+ "PAUSE": "ПАУЗА",
+ "RESUME": "ПРОДОЛЖ.",
+ "dB": "дБ",
+ "radio|NEWS": "НОВОСТИ",
+ "radio|TALK": "ТОК-РАДИО",
+ "radio|WEATHER": "ПОГОДА",
+ "radio|SAFETY": "БЕЗОПАСНОСТЬ",
+ "radio|AIR / SEA": "АВИА / МОРЕ",
+ "radio|TRANSIT": "ТРАНСПОРТ",
+ "radio|MUSIC": "МУЗЫКА",
+ "radio|OTHER": "ДРУГОЕ",
+ "SNAPSHOT": "СНИМОК",
+ "LIVE": "ОНЛАЙН",
+ "UPSTREAM": "ИСТОЧНИК",
+ "SYNTHETIC": "СИМУЛЯЦИЯ",
+ "CONFIGURED": "НАСТРОЕН",
+ "SEED": "КАТАЛОГ",
+ "Live HLS connected": "Поток HLS подключён",
+ "Live HLS unavailable": "Поток HLS недоступен",
+ "No stream URL configured": "URL потока не настроен",
+ "Live stream connected": "Прямой поток подключён",
+ "Snapshot feed connected": "Поток снимков подключён",
+ "Media fetch failed": "Не удалось получить медиа",
+ "Upstream snapshot active": "Снимок с источника активен",
+ "Fallback Street View frame": "Резервный кадр из Просмотра улиц",
+ "Upstream unavailable": "Источник недоступен",
+ "No source configured": "Источник не настроен",
+ "Upstream HTTP {status}": "Источник: HTTP {status}",
+ "Unexpected media type {type}": "Неожиданный тип медиа: {type}",
+ "Configured source": "Настроенный источник",
+ "Synthetic fallback": "Синтетический резерв",
+ "Cancel": "Отмена",
+ "Choose files": "Выбрать файлы",
+ "No file chosen": "Файлы не выбраны",
+ "{count} files selected": {
+ "one": "Выбрано файлов: {count}",
+ "few": "Выбрано файлов: {count}",
+ "many": "Выбрано файлов: {count}",
+ "other": "Выбрано файлов: {count}"
+ },
+ "Rasuwagadhi witness video": "Видео очевидца в Rasuwagadhi",
+ "Bhote Koshi valley footage": "Съёмка долины Bhote Koshi",
+ "Flood footage": "Съёмка паводка",
+ "Compilation and casualty claims": "Подборка видео и сообщения о жертвах",
+ "SOURCE GEOCONFIRMED · WORLD-PINNED": "МЕСТО СЪЁМКИ ПОДТВЕРЖДЕНО · ОТМЕЧЕНО НА КАРТЕ",
+ "SOURCE CREDITED · LOCATION UNRESOLVED": "АВТОР УКАЗАН · МЕСТО НЕ УСТАНОВЛЕНО",
+ "REFERENCE ONLY · CLAIMS UNVERIFIED": "ТОЛЬКО ДЛЯ СПРАВКИ · ЗАЯВЛЕНИЯ НЕ ПРОВЕРЕНЫ",
+ "SOURCE GEOCONFIRMED": "МЕСТО СЪЁМКИ ПОДТВЕРЖДЕНО",
+ "2021 historical reference versus 2026 post-event imagery; changes are cumulative and include the July 2025 Rasuwagadhi flood. Schematic downstream progression, not modeled arrival time; not an official hazard model.": "Исторический снимок 2021 года в сравнении со снимками 2026 года после события; изменения показаны суммарно за весь период и включают паводок в Rasuwagadhi в июле 2025 года. Схематическое продвижение вниз по течению, а не смоделированное время добегания паводка; не официальная модель опасности.",
+ "Immediate collapse viewpoint": "Точка обзора у места обрушения",
+ "Collapse viewpoint": "Вид на обрушение",
+ "Debris-dammed lake": "Озеро, запруженное обломками",
+ "Dammed lake": "Запрудное озеро",
+ "Second landslide": "Второй оползень",
+ "Gyirong border gate": "Погранпереход Gyirong",
+ "Border gate": "Погранпереход",
+ "Timure evidence cluster": "Группа свидетельств у Timure",
+ "Mailung / Upper Trishuli bridge": "Mailung / мост Upper Trishuli",
+ "Dandagaun viewpoint restaurant": "Ресторан со смотровой площадкой, Dandagaun",
+ "Dandagaun viewpoint": "Смотровая площадка Dandagaun",
+ "Bidur - Trishuli bridge": "Мост Bidur — Trishuli",
+ "Bidur bridge": "Мост Bidur",
+ "Devighat / Taadi Khola Bridge": "Devighat / мост Taadi Khola",
+ "Devighat bridge": "Мост Devighat",
+ "Global Incident Context": "Глобальный контекст инцидента",
+ "Nepal-Focused Globe Rotation": "Поворот глобуса к Непалу",
+ "Bhote Koshi Regional Approach": "Подлёт к региону Bhote Koshi",
+ "Bhote Koshi Nearby Cities": "Города рядом с Bhote Koshi",
+ "Bhote Koshi Incident Corridor": "Коридор инцидента на Bhote Koshi",
+ "Bhote Koshi Flood Path": "Путь паводка на Bhote Koshi",
+ "Bhote Koshi Corridor Overview": "Обзор коридора Bhote Koshi",
+ "Bhote Koshi Upper Valley": "Верхняя долина Bhote Koshi",
+ "Upper Valley Collapse": "Обрушение в верхней долине",
+ "Debris-Dammed Lake": "Озеро, запруженное обломками",
+ "Nepal-China Border Gate": "Погранпереход Непал — Китай",
+ "Timure Evidence Cluster": "Группа свидетельств у Timure",
+ "Syabru Besi Passage": "Прохождение через Syabru Besi",
+ "Bidur / Trishuli Consequence": "Последствия в Bidur / Trishuli",
+ "Final view": "Финальный вид",
+ "{year} HISTORICAL REFERENCE": "{year} ИСТОРИЧЕСКИЙ СНИМОК",
+ "{year} POST-EVENT": "{year} ПОСЛЕ СОБЫТИЯ",
+ "Esri map unavailable · no swipe": "Карта Esri недоступна · без сравнения",
+ "Swipe needs a globe map": "Для сравнения нужна карта-глобус",
+ "Imagery stays on Esri · CLEAR to use Google 3D": "Снимки остаются на Esri · «СБРОСИТЬ», чтобы вернуть Google 3D",
+ "Box and images cleared": "Область и снимки сброшены",
+ "Box is {size} wide · limit {limit}": "Область шириной {size} · предел {limit}",
+ "View is {size} wide · limit {limit}": "Вид шириной {size} · предел {limit}",
+ "Frame unavailable; previous observation retained": "Кадр недоступен; показано предыдущее наблюдение",
+ "Weather imagery unavailable": "Погодные снимки недоступны",
+ "Weather source unavailable; previous observation retained": "Источник погоды недоступен; показано предыдущее наблюдение",
+ "Weather unavailable": "Погода недоступна",
+ "Weather tiles unavailable · previous frame retained": "Погодные тайлы недоступны · показан предыдущий кадр",
+ "Some weather tiles unavailable": "Часть погодных тайлов недоступна",
+ "Hidden by this map source · choose a globe map": "Скрыто этим источником карты · выберите глобус",
+ "Wind source unavailable": "Источник ветра недоступен",
+ "Globe imagery unavailable": "Снимки глобуса недоступны",
+ "Globe field image unavailable": "Изображение поля на глобусе недоступно",
+ "status chip|UNAVAILABLE": "НЕДОСТ.",
+ "Uses registered content or linked media. Those external files are not included in a scene bundle. Their original notices still apply.": "Используется зарегистрированный контент или связанные медиафайлы. Эти внешние файлы не входят в архив сцены. Их исходные условия использования по-прежнему действуют.",
+ "{state} {layers}": "{state}: {layers}",
+ "Selected Space Mission": "Выбранная космическая миссия",
+ "{duration}s + {hold}s": "{duration} с + {hold} с",
+ "Configured Source": "Настроенный источник",
+ "subject": "объект",
+ "{value}m": "{value} м",
+ "Google 3D tiles unavailable — check the key's API restrictions, quota, or network": "Тайлы Google 3D недоступны — проверьте ограничения API ключа, квоту или сеть",
+ "Needs {envVars} — add it in Provider Settings — or a Cesium ion token for the ion-hosted route": "Нужен {envVars} — добавьте его в «Настройках провайдеров» — или токен Cesium ion для варианта через ion",
+ "Comparison in use by another scene": "Сравнение занято другой сценой",
+ "A location reading needs a loaded forecast and the Earth at the center of the view.": "Чтобы получить данные в точке, загрузите прогноз и поместите Землю в центр экрана.",
+ "{mode} {band} {locality} | {region} | ALT {alt} | WINDOW {window} | SUN {sun}° | ONA {ona}° | {zone}": "{mode} · {band} · {locality} | {region} | ALT {alt} | ОКНО {window} | SUN {sun}° | ONA {ona}° | {zone}",
+ "light {source} to use your {name} key": "включите {source}, чтобы использовать свой ключ {name}",
+ "light {source}": "включите {source}",
+ ", or ": ", или ",
+ "{requirement}, or {offer}": "{requirement}, или {offer}",
+ "The photorealistic 3D planet, place search + Street View": "Фотореалистичная 3D-планета, поиск мест + Просмотр улиц",
+ "{name} needs the Google 3D map: choose it under MAP SOURCE": "{name}: нужна карта Google 3D — выберите её в разделе «ИСТОЧНИК КАРТЫ»",
+ "zoom in to a street to open {name}": "приблизьтесь к улице, чтобы открыть {name}",
+ "Google Street View": "Google Просмотр улиц",
+ "GOOGLE STREET VIEW": "GOOGLE ПРОСМОТР УЛИЦ",
+ "Google refused GOOGLE_MAPS_API_KEY for Street View — check that the Maps JavaScript API is enabled for it and this site is an allowed referrer": "Google отклонил GOOGLE_MAPS_API_KEY для Просмотра улиц — проверьте, что для ключа включён Maps JavaScript API, а адрес этого сайта есть в списке разрешённых (HTTP referrer)",
+ "Street View did not answer — check the network, and that the Maps JavaScript API is enabled for GOOGLE_MAPS_API_KEY": "Просмотр улиц не ответил — проверьте сеть и что для GOOGLE_MAPS_API_KEY включён Maps JavaScript API",
+ "click a street to open Street View": "щёлкните по улице, чтобы открыть Просмотр улиц",
+ " or ": " или ",
+ "OPEN {labels}": "ОТКРЫТЬ {labels}",
+ "Open {names} at the centre of the view": "Открыть {names} в центре вида",
+ "Zoom in to a street to open {names} here": "Приблизьтесь к улице, чтобы открыть здесь {names}",
+ "radio tag|All": "Все",
+ "Alternative": "Альтернатива",
+ "Ambient": "Эмбиент",
+ "Blues": "Блюз",
+ "Classical": "Классика",
+ "Country": "Кантри",
+ "Dance": "Танцевальная",
+ "Electronic": "Электроника",
+ "Folk": "Фолк",
+ "Funk": "Фанк",
+ "Hip-Hop": "Хип-хоп",
+ "House": "Хаус",
+ "Indie": "Инди",
+ "Jazz": "Джаз",
+ "Latin": "Латиноамериканская",
+ "Metal": "Метал",
+ "Oldies": "Ретро",
+ "Pop": "Поп",
+ "Punk": "Панк",
+ "R&B": "R&B",
+ "Reggae": "Регги",
+ "Rock": "Рок",
+ "Soul": "Соул",
+ "Techno": "Техно",
+ "Trance": "Транс",
+ "World": "Музыка мира",
+ "{speed}KT": "{speed} УЗ",
+ "{heading}DEG": "{heading}°",
+ "At least {count}": "Не менее {count}",
+ "Named areas ({n})": "Именованные зоны ({n})",
+ "{distance} FLIGHT / VESSEL WINDOW": "РАДИУС РЕЙСОВ / СУДОВ {distance}",
+ "mapped matches within {km} km of the subject": "совпадения на карте в радиусе {km} км от объекта",
+ "none mapped within {km} km; not a complete 250 km survey": "на карте нет в радиусе {km} км; это не полный обзор 250 км",
+ "mapped matches from the loaded viewport": "совпадения на карте в загруженной области",
+ "viewport feed is not a complete 250 km survey": "данные видимой области — не полный обзор 250 км",
+ "fork direction|left": "левее",
+ "fork direction|right": "правее",
+ "fork direction|slightly left": "чуть левее",
+ "fork direction|slightly right": "чуть правее",
+ "fork direction|sharply left": "левее",
+ "fork direction|sharply right": "правее",
+ "fork direction|straight": "прямо",
+ "lane direction|left": "левую",
+ "lane direction|right": "правую",
+ "lane direction|slightly left": "левую",
+ "lane direction|slightly right": "правую",
+ "lane direction|sharply left": "крайнюю левую",
+ "lane direction|sharply right": "крайнюю правую",
+ "lane direction|straight": "среднюю",
+ "{value}°N": "{value}° с. ш.",
+ "{value}°S": "{value}° ю. ш.",
+ "{value}°E": "{value}° в. д.",
+ "{value}°W": "{value}° з. д.",
+ "installation class|AIRFIELD": "АЭРОДРОМ",
+ "installation class|NAVAL BASE": "ВОЕННО-МОРСКАЯ БАЗА",
+ "installation class|RANGE": "ПОЛИГОН",
+ "installation class|MILITARY LAND": "ВОЕННАЯ ТЕРРИТОРИЯ",
+ "installation class|BASE": "БАЗА",
+ "installation class|PLACES CANDIDATE": "ИЗ GOOGLE PLACES",
+ "installation class|INSTALLATION": "ОБЪЕКТ",
+ "fire confidence|high": "высокая",
+ "fire confidence|nominal": "средняя",
+ "fire confidence|low": "низкая",
+ "age|<1h": "<1 ч",
+ "age|{count}h": "{count} ч",
+ "age|{count}d": "{count} д",
+ "General emergency": "Общая авария",
+ "Unlawful interference": "Незаконное вмешательство",
+ "Radio failure": "Отказ радиосвязи",
+ "Downed aircraft": "Вынужденная посадка",
+ "Minimum fuel": "Минимум топлива",
+ "Lifeguard (medical priority)": "Санитарный рейс (медицинский приоритет)",
+ "That file is not valid JSON.": "Этот файл — некорректный JSON.",
+ "That JSON file is not GeoJSON.": "Этот файл JSON не является GeoJSON.",
+ "That FeatureCollection has no features list.": "В этой FeatureCollection нет списка features.",
+ "Every GeoJSON feature must have type Feature.": "У каждого объекта GeoJSON должен быть тип Feature.",
+ "That GeoJSON has invalid geometries.": "В этом GeoJSON некорректные геометрии.",
+ "That GeoJSON contains an unsupported geometry.": "В этом GeoJSON есть неподдерживаемая геометрия.",
+ "That GeoJSON has invalid coordinates.": "В этом GeoJSON некорректные координаты.",
+ "That file creates more than {limit} map objects (the limit).": "Файл создаёт больше объектов на карте, чем позволяет лимит: {limit}.",
+ "That file has more than {limit} style definitions and image links after cleanup (the limit).": "После очистки в файле больше стилей и ссылок на изображения, чем позволяет лимит: {limit}.",
+ "That file has more than {limit} features (the limit).": "В файле больше объектов, чем позволяет лимит: {limit}.",
+ "That file has more than {limit} points (the limit) across {features} features.": "В файле больше точек, чем позволяет лимит: {limit} (объектов: {features}).",
+ "That file has more than {limit} points (the limit).": "В файле больше точек, чем позволяет лимит: {limit}.",
+ "That KMZ unpacks to more than the import limit.": "После распаковки этот KMZ превышает лимит импорта.",
+ "That KMZ is damaged and could not be unpacked.": "Этот KMZ повреждён, распаковать его не удалось.",
+ "That KMZ is not a readable zip archive.": "Этот KMZ — не читаемый zip-архив.",
+ "That KMZ uses a zip format this import does not read.": "Этот KMZ использует формат zip, который импорт не читает.",
+ "That KMZ is encrypted.": "Этот KMZ зашифрован.",
+ "That KMZ uses a compression method this import does not read.": "Этот KMZ использует метод сжатия, который импорт не читает.",
+ "That KML has invalid geometry bounds.": "В этом KML некорректные границы геометрии.",
+ "That KML has invalid coordinates.": "В этом KML некорректные координаты.",
+ "That GPX file has no <gpx> document.": "В этом файле GPX нет документа <gpx>.",
+ "That {format} file is not valid XML.": "Этот файл {format} — некорректный XML.",
+ "That file has an unreadable image or exceeds the 16-megapixel image limit.": "В файле есть нечитаемое изображение или изображение больше лимита в 16 мегапикселей.",
+ "That KML could not be read.": "Не удалось прочитать этот KML.",
+ "That file has invalid point coordinates.": "В файле некорректные координаты точек.",
+ "Ground heights are not available for that file. Try again when the map has loaded.": "Высоты рельефа для этого файла недоступны. Попробуйте ещё раз, когда карта загрузится.",
+ "That file took too long to read.": "Файл читался слишком долго.",
+ "Nothing to import.": "Нечего импортировать.",
+ "That file is larger than {size} MiB.": "Файл больше {size} МиБ.",
+ "Only GeoJSON, KML, KMZ and GPX files can be imported.": "Импортировать можно только файлы GeoJSON, KML, KMZ и GPX.",
+ "That file has nothing to draw.": "В файле нечего показать на карте.",
+ "That KMZ holds no KML document.": "В этом KMZ нет документа KML.",
+ "That {format} file could not be read.": "Не удалось прочитать этот файл {format}.",
+ "That file has {count} map objects; the limit is {limit}.": "Объектов на карте в файле: {count}; лимит: {limit}.",
+ "Ground heights could not be read. Try that file again.": "Не удалось получить высоты рельефа. Попробуйте импортировать файл ещё раз.",
+ "That file has invalid point graphics.": "В файле некорректное оформление точек.",
+ "Low-accuracy score < 2%": "Доля неточных < 2%",
+ "Low-accuracy score 2–10%": "Доля неточных 2–10%",
+ "Low-accuracy score > 10%": "Доля неточных > 10%",
+ "GNSS integrity source unavailable": "Источник целостности GNSS недоступен",
+ "Regional sample · 250 nm radius · cells from visited views over 30 min": "Региональная выборка · радиус 250 мор. миль · ячейки из просмотренных видов за 30 мин",
+ "Retrying automatically at {time} UTC": "Автоматический повтор в {time} UTC",
+ "Retrying automatically after provider cooldown": "Автоматический повтор после паузы провайдера",
+ "Updates automatically after pan or zoom and once a minute. The public feed covers a 250-nautical-mile circle around the view centre; zooming out does not make it a worldwide snapshot. Blank cells are outside sampled coverage or have insufficient observations.": "Обновляется автоматически после сдвига или масштабирования карты и раз в минуту. Публичный поток данных охватывает круг радиусом 250 морских миль вокруг центра вида; при отдалении карта не становится снимком всего мира. Пустые ячейки — вне охвата выборки или с недостаточным числом наблюдений.",
+ "Low-accuracy score = 100 × max(0, bad − 1) / total: one aircraft is discounted, so this is not the raw share. Cells need {aircraft} aircraft over {minutes} minutes. Navigation-integrity anomalies are not a detection of jamming or spoofing.": "Доля неточных = 100 × max(0, неточные − 1) / всего: один самолёт не учитывается, поэтому это не прямая доля. Для ячейки нужно самолётов: {aircraft} за {minutes} мин. Аномалии целостности навигации — не обнаружение глушения или подмены сигнала.",
+ "SQUAWK {code} · {status}": "СКВОК {code} · {status}",
+ "ADS-B PRIORITY · {status}": "ADS-B ПРИОРИТЕТ · {status}",
+ "ADS-B EMERGENCY · {status}": "ADS-B АВАРИЯ · {status}",
+ "{aircraftClass} · {emergency} · {feedState}": "{aircraftClass} · {emergency} · {feedState}",
+ "Ground heights could not be refreshed. Try the file again when the map has loaded.": "Не удалось обновить высоты рельефа. Попробуйте импортировать файл ещё раз, когда карта загрузится.",
+ "{count} map objects": {
+ "one": "{count} объект на карте",
+ "few": "{count} объекта на карте",
+ "many": "{count} объектов на карте",
+ "other": "{count} объекта на карте"
+ },
+ ", drawn with its own styles": ", со своими стилями",
+ "Hide {name}": "Скрыть: {name}",
+ "Show {name}": "Показать: {name}",
+ "Fly to {name}": "Перелёт: {name}",
+ "Remove {name}": "Удалить: {name}",
+ "At most {count} files at once — remove one first.": "Не больше {count} файлов одновременно — сначала удалите один.",
+ "Reading {name}…": "Чтение: {name}…",
+ "That file could not be read.": "Не удалось прочитать этот файл.",
+ "Added {count} files.": {
+ "one": "Добавлен {count} файл.",
+ "few": "Добавлено {count} файла.",
+ "many": "Добавлено {count} файлов.",
+ "other": "Добавлено {count} файла."
+ },
+ "{count} files could not be added ({name}: {error})": {
+ "one": "Не удалось добавить {count} файл ({name}: {error})",
+ "few": "Не удалось добавить {count} файла ({name}: {error})",
+ "many": "Не удалось добавить {count} файлов ({name}: {error})",
+ "other": "Не удалось добавить {count} файла ({name}: {error})"
+ },
+ "Some KML content was left out.": "Часть содержимого KML пропущена.",
+ "GNSS Integrity": "Целостность GNSS",
+ "Show your own GeoJSON, KML, KMZ or GPX files on the globe (or drop them onto it). File bytes stay on this device; overlays can appear in map screenshots shared with voice.": "Показать на глобусе свои файлы GeoJSON, KML, KMZ или GPX (или перетащите их на глобус). Содержимое файлов остаётся на этом устройстве; наложения могут попасть в снимки карты, которые передаются голосовому ассистенту.",
+ "Import": "Импорт",
+ "Choose GeoJSON, KML, KMZ or GPX files": "Выберите файлы GeoJSON, KML, KMZ или GPX",
+ "Imported files": "Импортированные файлы",
+ "DOCKED · {name}": "СТЫКОВКА · {name}",
+ "DOCKED · {name} · +{extra}": "СТЫКОВКА · {name} · +{extra}",
+ "loading coverage...": "загрузка покрытия...",
+ "live feed unavailable": "поток в реальном времени недоступен",
+ "GBFS fetch error": "ошибка загрузки GBFS",
+ "Open the Street Level panel to view imagery": "Откройте панель «Уличные снимки», чтобы их посмотреть",
+ "Image could not be opened": "Не удалось открыть снимок",
+ "Mapillary rejected MAPILLARY_CLIENT_TOKEN — replace it in Provider Settings": "Mapillary отклонил MAPILLARY_CLIENT_TOKEN — замените его в «Настройках провайдеров»",
+ "Coverage requests are being rate-limited — they resume on their own": "Запросы покрытия ограничены по частоте — они возобновятся сами",
+ "No street-level imagery within {radius} m of that point": "В радиусе {radius} м от этой точки уличных снимков нет",
+ "No street-level imagery within {radius} m of the view centre": "В радиусе {radius} м от центра вида уличных снимков нет",
+ "Aim the middle of the view at a street to look for imagery there": "Наведите центр вида на улицу, чтобы поискать там снимки",
+ "Street View has no imagery for this place": "В Просмотре улиц нет снимков этого места",
+ "GOOGLE_MAPS_API_KEY is not set": "GOOGLE_MAPS_API_KEY не задан",
+ "The Google Maps JavaScript API could not load": "Не удалось загрузить Google Maps JavaScript API",
+ "Weather request timed out": "Истекло время ожидания запроса погоды",
+ "Malformed weather manifest": "Некорректный манифест погоды",
+ "Weather HTTP {status}": "Погода: HTTP {status}",
+ "Weather image HTTP {status}": "Снимок погоды: HTTP {status}",
+ "Weather prefetch unavailable": "Предзагрузка погоды недоступна",
+ "Infrared decode failed": "Не удалось декодировать инфракрасный снимок",
+ "rate limited": "превышен лимит запросов",
+ "routing service is rate limited": "сервис маршрутизации превысил лимит запросов",
+ "route leg too long": "участок маршрута слишком длинный",
+ "route too long": "маршрут слишком длинный",
+ "Routing is rate limited — try again in a moment": "Построение маршрута: превышен лимит запросов — попробуйте ещё раз чуть позже",
+ "{error} — try again in a moment": "{error} — попробуйте ещё раз чуть позже",
+ "Routing unavailable (HTTP {status})": "Построение маршрута недоступно (HTTP {status})",
+ "CelesTrak unreachable": "CelesTrak недоступен",
+ "KartaView is rate-limiting requests — they resume on their own": "KartaView ограничивает частоту запросов — они возобновятся сами",
+ "KartaView’s photos here are archived and cannot be shown": "Фотографии KartaView здесь в архиве, показать их нельзя",
+ "KartaView did not filter this area in time — move the map to ask again": "KartaView не успел отфильтровать эту область — сдвиньте карту, чтобы запросить снова",
+ "None of KartaView’s photos here pass the imagery filter": "Ни одна фотография KartaView здесь не проходит фильтр снимков",
+ "KartaView did not answer in time — try again": "KartaView не ответил вовремя — попробуйте снова",
+ "KartaView could not be reached — check the network": "Не удалось связаться с KartaView — проверьте сеть",
+ "KartaView sent an answer that could not be read": "KartaView прислал ответ, который не удалось прочитать",
+ "KartaView is rate-limiting requests": "KartaView ограничивает частоту запросов",
+ "KartaView is rate-limiting requests — try again in a moment": "KartaView ограничивает частоту запросов — попробуйте ещё раз чуть позже",
+ "KartaView sent too much data": "KartaView прислал слишком много данных",
+ "KartaView has no such photo": "У KartaView нет такой фотографии",
+ "The KartaView photo could not be loaded": "Не удалось загрузить фотографию KartaView",
+ "KartaView has no position for this photo": "У KartaView нет координат этой фотографии",
+ "Map tiles temporarily unavailable": "Тайлы карты временно недоступны",
+ "Mapped names temporarily unavailable": "Названия объектов временно недоступны",
+ "No mapped sites in view": "В кадре нет объектов",
+ "No mapped sites within {km} km of the contact": "Нет объектов в радиусе {km} км от контакта",
+ "{count} mapped sites in view": {
+ "one": "{count} объект в кадре",
+ "few": "{count} объекта в кадре",
+ "many": "{count} объектов в кадре",
+ "other": "{count} объекта в кадре"
+ },
+ "{count} mapped sites within {km} km of the contact": {
+ "one": "{count} объект в радиусе {km} км от контакта",
+ "few": "{count} объекта в радиусе {km} км от контакта",
+ "many": "{count} объектов в радиусе {km} км от контакта",
+ "other": "{count} объекта в радиусе {km} км от контакта"
+ },
+ "Too many mapped sites in view to list them all": "В кадре слишком много объектов, чтобы перечислить все",
+ "Installation context unavailable": "Контекст объектов недоступен",
+ "Focus vessel {name}, MMSI {mmsi}": "Фокус на судне {name}, MMSI {mmsi}",
+ "Open the USGS initial report for the 26 August 2026 Nepal landslide": "Открыть первичное сообщение USGS об оползне в Непале 26 августа 2026 года",
+ "YouTube source": "Источник YouTube",
+ "Facebook source": "Источник Facebook",
+ "Military airfield": "Военный аэродром",
+ "Naval base": "Военно-морская база",
+ "Firing range": "Стрельбище",
+ "Military land": "Военная территория",
+ "Mapped installation": "Объект на карте",
+ "Military area": "Военная зона",
+ "SIMULATED — {reason}": "СИМУЛЯЦИЯ — {reason}",
+ "TomTom key unavailable": "Ключ TomTom недоступен",
+ "TomTom daily budget reached": "Исчерпан дневной лимит TomTom",
+ "TomTom upstream unreachable": "Сервер TomTom не отвечает",
+ "TomTom flow unavailable": "Поток TomTom недоступен",
+ "API key rejected — check AISSTREAM_API_KEY": "Ключ API отклонён — проверьте AISSTREAM_API_KEY",
+ "feed silent {seconds}s — no AIS data": "нет данных AIS от потока {seconds} с",
+ "feed silent — no AIS data": "нет данных AIS от потока",
+ "feed down — retrying slowly (attempt {attempt})": "поток недоступен — повторяем реже (попытка {attempt})",
+ "feed down — retrying slowly": "поток недоступен — повторяем реже",
+ "reconnecting to feed… (attempt {attempt})": "переподключение к потоку… (попытка {attempt})",
+ "reconnecting to feed…": "переподключение к потоку…",
+ "AISSTREAM_API_KEY not set": "AISSTREAM_API_KEY не задан",
+ "live feed unsupported": "поток в реальном времени не поддерживается",
+ "connecting to feed…": "подключение к потоку…",
+ "feed disconnected": "поток отключён",
+ "feed down": "поток недоступен",
+ "feed idle": "поток простаивает",
+ "AIS live load failed": "Не удалось загрузить AIS в реальном времени",
+ "age|{count}m": "{count} мин",
+ "{acres} ac": {
+ "one": "{acres} акр",
+ "few": "{acres} акра",
+ "many": "{acres} акров",
+ "other": "{acres} акра"
+ },
+ "{percent}% contained": "локализован на {percent}%",
+ "containment unknown": "локализация неизвестна",
+ "{cause} cause": "причина: {cause}",
+ "{personnel} personnel": {
+ "one": "{personnel} человек",
+ "few": "{personnel} человека",
+ "many": "{personnel} человек",
+ "other": "{personnel} человека"
+ },
+ "{county} County": "округ {county}",
+ "{cost} to date": "{cost} на сегодня",
+ "discovered {age} ago": "обнаружен {age} назад",
+ "updated {age} ago": "обновлён {age} назад",
+ "part of {complex}": "входит в {complex}",
+ "InciWeb ↗ · click card to open": "InciWeb ↗ · нажмите на карточку, чтобы открыть",
+ "FIRE · {name}": "ПОЖАР · {name}",
+ "Unnamed incident": "Без названия",
+ "Open {title} on InciWeb": "Открыть {title} в InciWeb",
+ "Vehicle {vehicle}": "Борт {vehicle}",
+ "Bus": "Автобус",
+ "Tram": "Трамвай",
+ "Subway": "Метро",
+ "Train": "Поезд",
+ "Ferry": "Паром",
+ "Transit vehicle": "Общественный транспорт",
+ "No recent fix": "Нет свежих координат",
+ "Waiting for update": "Ожидание обновления",
+ "Moving": "В движении",
+ "reported {speed} km/h": "по отчёту {speed} км/ч",
+ "reported hdg {heading}°": "по отчёту курс {heading}°",
+ "Last report: stopped at stop {stop}": "Последний отчёт: стоит на остановке {stop}",
+ "Last report: arriving at stop {stop}": "Последний отчёт: прибывает на остановку {stop}",
+ "Last report: next stop {stop}": "Последний отчёт: следующая остановка {stop}",
+ "occupancy|empty": "пусто",
+ "occupancy|many seats available": "много свободных мест",
+ "occupancy|few seats available": "мало свободных мест",
+ "occupancy|standing room only": "только стоячие места",
+ "occupancy|crushed standing room only": "переполнен, только стоя",
+ "occupancy|full": "мест нет",
+ "occupancy|not accepting passengers": "посадки нет",
+ "occupancy|not boardable": "посадка невозможна",
+ "Shown at street level · depth not in the feed": "Показан на уровне улицы · глубины в потоке нет",
+ "Reported {seconds} s ago": "Отчёт {seconds} с назад",
+ "Reported {minutes} min ago": "Отчёт {minutes} мин назад",
+ "{reported} (feed time)": "{reported} (время потока)",
+ "shown {seconds} s behind": "показ отстаёт на {seconds} с",
+ "Available trail: {minutes} min": "Доступный след: {minutes} мин",
+ "Available trail: {minutes} min (limited)": "Доступный след: {minutes} мин (ограничен)",
+ "UNAVAILABLE · {source} · Roads unavailable": "НЕДОСТУПНО · {source} · Дороги недоступны",
+ "Roads: {source}": "Дороги: {source}",
+ "TomTom roads unavailable while the traffic service is unreachable": "Дороги TomTom недоступны, пока сервис трафика не отвечает",
+ "Hybrid unavailable while the traffic service is unreachable": "Гибридный режим недоступен, пока сервис трафика не отвечает",
+ "TomTom roads need a TomTom key": "Для дорог TomTom нужен ключ TomTom",
+ "Hybrid needs a TomTom key": "Для гибридного режима нужен ключ TomTom",
+ "Local surface still loading": "Поверхность под дорогами ещё загружается",
+ "Partial coverage": "Частичное покрытие",
+ "Detailed roads unavailable": "Нет детальных данных о дорогах",
+ "Reduced detail coverage": "Покрытие с меньшей детализацией",
+ "OpenFreeMap tiles rate-limited": "Тайлы OpenFreeMap: превышен лимит запросов",
+ "OpenFreeMap tiles timed out": "Тайлы OpenFreeMap: истекло время ожидания",
+ "OpenFreeMap tiles unavailable": "Тайлы OpenFreeMap недоступны",
+ "Heard by your receiver": "Принято вашим приёмником",
+ "browser SDR": "SDR в браузере",
+ "decoder feed": "поток декодера",
+ "Your RTL-SDR receiver and decoder feed": "Ваш приёмник RTL-SDR и поток декодера",
+ "Your decoder feed": "Ваш поток декодера",
+ "Your RTL-SDR receiver": "Ваш приёмник RTL-SDR",
+ "NO CALLSIGN": "БЕЗ ПОЗЫВНОГО",
+ "ALT {altitude} FT · GS {speed} KT · TRK {track}": "ВЫС. {altitude} ФТ · ПУТ. СКОР. {speed} УЗ · ПУТЬ {track}",
+ "V/S {rate}": "ВЕРТ. СКОР. {rate}",
+ "V/S {rate} FPM": "ВЕРТ. СКОР. {rate} ФТ/МИН",
+ "POSITION {age}": "ПОЗИЦИЯ {age}",
+ "POSITION {seconds} S AGO": "ПОЗИЦИЯ {seconds} С НАЗАД",
+ "{count} MSGS": {
+ "one": "{count} СООБЩЕНИЕ",
+ "few": "{count} СООБЩЕНИЯ",
+ "many": "{count} СООБЩЕНИЙ",
+ "other": "{count} СООБЩЕНИЯ"
+ },
+ "installation class|BARRACKS": "КАЗАРМЫ",
+ "installation class|TRAINING AREA": "УЧЕБНЫЙ ПОЛИГОН",
+ "Seeking up…": "Поиск вверх…",
+ "Seeking down…": "Поиск вниз…",
+ "Scanning {mhz} MHz…": "Сканирование {mhz} МГц…",
+ "Found {mhz} MHz · {snr} dB": "Найдено {mhz} МГц · {snr} дБ",
+ "Broadcaster stream is unavailable or blocked by the browser.": "Поток вещателя недоступен или заблокирован браузером.",
+ "Playback requires a direct click or tap.": "Чтобы начать воспроизведение, нажмите «Пуск».",
+ "Broadcaster stream could not be started.": "Не удалось запустить поток вещателя.",
+ "Directory refresh degraded; showing the previous station catalog.": "Обновление каталога прошло с перебоями; показан предыдущий каталог станций.",
+ "Radio directory coverage is degraded.": "Каталог радиостанций работает с перебоями.",
+ "Directory refresh failed; showing the previous station catalog.": "Не удалось обновить каталог; показан предыдущий каталог станций.",
+ "Radio directory is temporarily unavailable.": "Каталог радиостанций временно недоступен.",
+ "Decoder feeds: {feeds}": "Потоки декодера: {feeds}",
+ " · read while Local ADS-B is on": " · читаются при включённом слое «Локальный ADS-B»",
+ "idle": "ожидание",
+ "running": "работает",
+ "suspended": "приостановлено",
+ "closed": "закрыто",
+ "Local FM stopped: internet radio started": "Локальный FM остановлен: запущено интернет-радио",
+ "ALPR cameras": "камеры ALPR",
+ "OVERPASS RATE-LIMITED": "OVERPASS: ПРЕВЫШЕН ЛИМИТ ЗАПРОСОВ",
+ "OVERPASS TIMED OUT": "OVERPASS: ИСТЕКЛО ВРЕМЯ ОЖИДАНИЯ",
+ "OVERPASS COULD NOT COMPLETE THE QUERY": "OVERPASS: НЕ УДАЛОСЬ ЗАВЕРШИТЬ ЗАПРОС",
+ "MAP TILES TEMPORARILY UNAVAILABLE": "ТАЙЛЫ КАРТЫ ВРЕМЕННО НЕДОСТУПНЫ",
+ "MAPPED NAMES TEMPORARILY UNAVAILABLE": "НАЗВАНИЯ ОБЪЕКТОВ ВРЕМЕННО НЕДОСТУПНЫ",
+ "Shared flight follow expired": "Срок отслеживания рейса по ссылке истёк",
+ "Shared military flight follow expired": "Срок отслеживания военного рейса по ссылке истёк",
+ "Shared satellite follow expired": "Срок отслеживания спутника по ссылке истёк",
+ "Shared flight could not be restored — feed unavailable": "Не удалось восстановить рейс по ссылке — поток данных недоступен",
+ "Shared military flight could not be restored — feed unavailable": "Не удалось восстановить военный рейс по ссылке — поток данных недоступен",
+ "Shared satellite could not be restored — feed unavailable": "Не удалось восстановить спутник по ссылке — поток данных недоступен",
+ "Shared flight is unavailable": "Рейс по ссылке недоступен",
+ "Shared military flight is unavailable": "Военный рейс по ссылке недоступен",
+ "Shared satellite is unavailable": "Спутник по ссылке недоступен",
+ "Scene not saved — browser storage unavailable": "Сцена не сохранена — хранилище браузера недоступно",
+ "Scene not saved — existing saved project could not be read. Export edits or import a valid file.": "Сцена не сохранена — не удалось прочитать сохранённый проект. Экспортируйте правки или импортируйте корректный файл.",
+ "Saved project could not be read; storage preserved. Import a valid file to resume saving.": "Не удалось прочитать сохранённый проект; хранилище не тронуто. Импортируйте корректный файл, чтобы снова сохранять.",
+ "Scene not saved — {reason}": "Сцена не сохранена — {reason}",
+ "Stopped": "Остановлено",
+ "Stopped (Esc)": "Остановлено (Esc)",
+ "Camera ownership changed": "Управление камерой перехвачено",
+ "Scene layer turned off": "Слой сцены выключен",
+ "Seeking scene clock": "Перемотка сцены",
+ "Importing project": "Импорт проекта",
+ "Camera move interrupted": "Перелёт камеры прерван",
+ "Scene media timed out": "Истекло время ожидания медиа сцены",
+ "Space Missions isolates replay data. Exit the mode to enable {layer}.": "Режим «Космические миссии» изолирует данные воспроизведения. Выйдите из режима, чтобы включить слой «{layer}».",
+ "Tilted view": "Вид с наклоном",
+ "Straight-down view": "Вид сверху",
+ "North up": "Север вверху",
+ "Exit cockpit to fly to a camera": "Выйдите из кабины, чтобы перелететь к камере",
+ "Exit cockpit to fly to a location": "Выйдите из кабины, чтобы перелететь к месту",
+ "Exit cockpit to fly to a photo": "Выйдите из кабины, чтобы перелететь к фото",
+ "Exit cockpit to fly to a shared view": "Выйдите из кабины, чтобы перелететь к виду по ссылке",
+ "Exit cockpit to fly to a target": "Выйдите из кабины, чтобы перелететь к цели",
+ "Exit cockpit to fly to a vessel": "Выйдите из кабины, чтобы перелететь к судну",
+ "Exit cockpit to fly to a fire": "Выйдите из кабины, чтобы перелететь к пожару",
+ "Exit cockpit to fly to a route": "Выйдите из кабины, чтобы перелететь к маршруту",
+ "Exit cockpit to fly to a file": "Выйдите из кабины, чтобы перелететь к файлу",
+ "Exit cockpit to fly to a scene": "Выйдите из кабины, чтобы перелететь к сцене",
+ "Go to expanded Radio section": "Перейти к развёрнутому разделу радио",
+ "Expand Radio section in Context": "Развернуть раздел «Радио» в панели «Контекст»",
+ "Double-click the header to snap the panel back": "Двойной щелчок по заголовку — вернуть панель на место",
+ "New scene name": "Название новой сцены",
+ "Delete scene \"{scene}\" and all shots?": "Удалить сцену «{scene}» и все кадры?",
+ "Detailed outline unavailable": "Подробный контур недоступен",
+ "Provider Settings does not answer proxied requests": "«Настройки провайдеров» не отвечают на запросы через прокси",
+ "Provider Settings is disabled while sharing is enabled": "«Настройки провайдеров» отключены, пока включён общий доступ",
+ "Provider Settings answers only the machine running the server": "«Настройки провайдеров» отвечают только компьютеру, на котором запущен сервер",
+ "Provider Settings answers only local hostnames": "«Настройки провайдеров» отвечают только на локальные имена хостов",
+ "Provider Settings requires an exact local Origin": "«Настройкам провайдеров» нужен точный локальный Origin",
+ "Unrecognized Origin refused": "Нераспознанный Origin отклонён",
+ "Cross-origin requests are refused": "Запросы с другого источника отклоняются",
+ "Content-Type must be application/json": "Content-Type должен быть application/json",
+ "Method not allowed": "Метод не разрешён",
+ "Request too large": "Слишком большой запрос",
+ "Invalid JSON": "Некорректный JSON",
+ "Body must be a JSON object of {ENV_VAR: value}": "Тело запроса должно быть JSON-объектом вида {ENV_VAR: value}",
+ "No keys provided": "Ключи не переданы",
+ "At most {limit} keys per save": "Ключей за одно сохранение — не больше {limit}",
+ "Unknown key: {name}": "Неизвестный ключ: {name}",
+ "{name} must be a string": "{name}: значение должно быть строкой",
+ "{name} is empty": "{name}: пустое значение",
+ "{name} is longer than any real key ({limit} max)": "{name}: значение длиннее любого настоящего ключа (максимум {limit})",
+ "{name} may only contain printable characters with no spaces": "{name}: допустимы только печатные символы без пробелов",
+ "{name} contains a character that is not valid in a key (#, quotes, $, \\, or backtick)": "{name}: недопустимый для ключа символ (#, кавычки, $, \\ или обратный апостроф)",
+ "{name} is configured outside Provider Settings and can only be changed where it was set": "{name}: задан вне «Настроек провайдеров», изменить его можно только там, где его задали",
+ "The key was not saved: could not restrict the credential file to your account; nothing was saved": "Ключ не сохранён: не удалось закрыть файл учётных данных от всех, кроме вашей учётной записи; ничего не сохранено",
+ "The key was not saved: the existing configuration could not be read, so nothing was changed": "Ключ не сохранён: не удалось прочитать текущую конфигурацию, поэтому ничего не изменено",
+ "Could not write the {store} store": "Не удалось записать хранилище {store}",
+ "Could not check ChatGPT sign-in. Try again.": "Не удалось проверить вход в ChatGPT. Попробуйте ещё раз.",
+ "Cloud voice will use OPENAI_API_KEY on the next session.": "Следующая облачная голосовая сессия будет использовать OPENAI_API_KEY.",
+ "Checking local ChatGPT OAuth sign-in…": "Проверка локального входа в ChatGPT через OAuth…",
+ "Could not check ChatGPT sign-in.": "Не удалось проверить вход в ChatGPT.",
+ "ChatGPT OAuth selected for cloud voice. Your API key stays saved and available.": "Для облачного голоса выбран ChatGPT OAuth. Ваш ключ API остаётся сохранённым и доступным.",
+ "ChatGPT sign-in expired. Opening sign-in again…": "Сеанс ChatGPT истёк. Открываем вход заново…",
+ "Opening ChatGPT sign-in in your browser…": "Открываем вход в ChatGPT в браузере…",
+ "Could not start ChatGPT sign-in on this machine.": "Не удалось начать вход в ChatGPT на этом компьютере.",
+ "Finish ChatGPT sign-in in the browser. Waiting for it to complete…": "Завершите вход в ChatGPT в браузере. Ожидание завершения…",
+ "ChatGPT sign-in timed out. Click {button} to try again.": "Время на вход в ChatGPT истекло. Нажмите «{button}», чтобы попробовать ещё раз.",
+ "ChatGPT sign-in complete. OAuth will be used for the next cloud voice session.": "Вход в ChatGPT выполнен. В следующей облачной голосовой сессии будет использоваться OAuth.",
+ "OAuth check failed: {detail}": "Не удалось проверить OAuth: {detail}",
+ "unsaved CCTV calibration": "несохранённая калибровка CCTV",
+ "the open cockpit": "открытая кабина",
+ "Switching language reloads the page. This will be lost: {items}. Switch anyway?": "Смена языка перезагрузит страницу. Будет потеряно: {items}. Всё равно сменить язык?",
+ "Wind upstream unavailable": "Источник данных о ветре недоступен",
+ "WebUSB needs desktop Chrome or Edge": "Для WebUSB нужен настольный Chrome или Edge",
+ "connect a receiver in Radio": "подключите приёмник в разделе «Радио»",
+ "receiver is in FM mode": "приёмник в режиме FM",
+ "Cyclone advisories unavailable": "Сводки о циклонах недоступны",
+ "Cyclone data unavailable": "Данные о циклонах недоступны",
+ "Drag to size the box": "Потяните, чтобы задать размер области",
+ "Press on the ground, not the sky": "Нажмите на землю, а не на небо",
+ "Point the camera at the ground to use the view": "Наведите камеру на землю, чтобы использовать вид",
+ "That point cannot anchor a box": "От этой точки нельзя построить область",
+ "Box edges must be finite": "Некорректные координаты области",
+ "Longitudes must be within ±180°": "Долгота должна быть в пределах ±180°",
+ "Select one side of the dateline": "Не пересекайте линию перемены дат",
+ "Box must enclose an area": "Область должна иметь площадь",
+ "Imagery stops at ±{limit}° latitude": "Снимки есть только до ±{limit}° широты",
+ "{owner} is using the pointer — close it first": "Указатель занят: «{owner}». Закройте его",
+ "OpenSky OAuth client missing/invalid": "Клиент OAuth OpenSky отсутствует или недействителен",
+ "OpenSky OAuth rejected credentials": "OpenSky OAuth отклонил учётные данные",
+ "OpenSky username/password rejected": "OpenSky отклонил имя пользователя или пароль",
+ "OpenSky auth missing": "Нет данных для входа в OpenSky",
+ "OpenSky auth required": "OpenSky требует входа",
+ "OpenSky auth invalid": "Неверные данные для входа в OpenSky",
+ "OpenSky auth failed": "Не удалось войти в OpenSky",
+ "Source snapshot {minutes} min old": "Возраст снимка источника: {minutes} мин",
+ "{source} rate limited (anonymous)": "{source}: лимит запросов (анонимно)",
+ "{source} rate limited": "{source}: лимит запросов",
+ "{source} HTTP {status}": "{source}: HTTP {status}",
+ "{source} network error": "{source}: ошибка сети",
+ "Malformed {source} aircraft rows": "{source}: некорректные записи о самолётах",
+ "Malformed {source} response": "{source}: некорректный ответ",
+ "Source snapshot time unavailable": "Время снимка источника неизвестно",
+ "Live data unavailable": "Данные в реальном времени недоступны",
+ "{n} aircraft": {
+ "one": "{n} самолёт",
+ "few": "{n} самолёта",
+ "many": "{n} самолётов",
+ "other": "{n} самолёта"
+ },
+ "{n} military aircraft": {
+ "one": "{n} военный самолёт",
+ "few": "{n} военных самолёта",
+ "many": "{n} военных самолётов",
+ "other": "{n} военного самолёта"
+ },
+ "{n} ships": {
+ "one": "{n} судно",
+ "few": "{n} судна",
+ "many": "{n} судов",
+ "other": "{n} судна"
+ },
+ "{n} satellites": {
+ "one": "{n} спутник",
+ "few": "{n} спутника",
+ "many": "{n} спутников",
+ "other": "{n} спутника"
+ },
+ "{n} launches": {
+ "one": "{n} пуск",
+ "few": "{n} пуска",
+ "many": "{n} пусков",
+ "other": "{n} пуска"
+ },
+ "{n} earthquakes": {
+ "one": "{n} землетрясение",
+ "few": "{n} землетрясения",
+ "many": "{n} землетрясений",
+ "other": "{n} землетрясения"
+ },
+ "{n} fires": {
+ "one": "{n} пожар",
+ "few": "{n} пожара",
+ "many": "{n} пожаров",
+ "other": "{n} пожара"
+ },
+ "{n} fire perimeters": {
+ "one": "{n} контур пожара",
+ "few": "{n} контура пожаров",
+ "many": "{n} контуров пожаров",
+ "other": "{n} контура пожаров"
+ },
+ "{n} cyclones": {
+ "one": "{n} циклон",
+ "few": "{n} циклона",
+ "many": "{n} циклонов",
+ "other": "{n} циклона"
+ },
+ "{n} buses": {
+ "one": "{n} автобус",
+ "few": "{n} автобуса",
+ "many": "{n} автобусов",
+ "other": "{n} автобуса"
+ },
+ "{n} bike share": {
+ "one": "{n} станция проката велосипедов",
+ "few": "{n} станции проката велосипедов",
+ "many": "{n} станций проката велосипедов",
+ "other": "{n} станции проката велосипедов"
+ },
+ "{n} flock cameras": {
+ "one": "{n} камера ALPR",
+ "few": "{n} камеры ALPR",
+ "many": "{n} камер ALPR",
+ "other": "{n} камеры ALPR"
+ },
+ "{n} military bases": {
+ "one": "{n} военная база",
+ "few": "{n} военные базы",
+ "many": "{n} военных баз",
+ "other": "{n} военной базы"
+ },
+ "{n} datacenters": {
+ "one": "{n} дата-центр",
+ "few": "{n} дата-центра",
+ "many": "{n} дата-центров",
+ "other": "{n} дата-центра"
+ },
+ "{n} dams": {
+ "one": "{n} плотина",
+ "few": "{n} плотины",
+ "many": "{n} плотин",
+ "other": "{n} плотины"
+ },
+ "{n} results": {
+ "one": "{n} результат",
+ "few": "{n} результата",
+ "many": "{n} результатов",
+ "other": "{n} результата"
+ },
+ "anywhere in the loaded data": "во всех загруженных данных",
+ "in view": "в кадре",
+ "within {radius} of the view centre": "в радиусе {radius} от центра вида",
+ "within {radius} of {place} (Contacts window)": "в радиусе {radius} — {place} (окно «Контактов»)",
+ "within {radius} of {place}": "в радиусе {radius} — {place}",
+ "within {radius}": "в радиусе {radius}",
+ "over {region}": "в регионе {region}",
+ "At least {items}": "{items} или больше",
+ "{items} {scope}": "{items} {scope}",
+ "last 24 h": "за последние 24 ч",
+ "past 30 d and upcoming": "за последние 30 дн. и предстоящие",
+ "the flights layer loads by viewport": "слой рейсов загружается по области вида",
+ "distance is ground distance, not overhead": "расстояние — по поверхности земли до подспутниковой точки, а не до самого аппарата",
+ "the count is a lower bound because at least one layer reached its retained limit.": "это нижняя граница: хотя бы один слой достиг предела хранимых записей.",
+ "{label} loading": "{label}: загрузка",
+ "{label} error": "{label}: ошибка",
+ "counted the first {returned} loaded records": "учтены только первые загруженные записи: {returned}",
+ "counted {returned} of {total} loaded records": "учтено загруженных записей: {returned} из {total}",
+ "{layers} just turned on — still loading, counts will rise": "{layers}: только что включено — данные ещё загружаются, значения вырастут",
+ "Contacts panel snapshot at {time} — the same retained cohort supplies the card, speech, and follow-up memory": "Снимок панели «Контакты» ({time}) — та же сохранённая выборка используется для карточки, речи и памяти уточняющих вопросов",
+ "Contacts panel snapshot — the same retained cohort supplies the card, speech, and follow-up memory": "Снимок панели «Контакты» — та же сохранённая выборка используется для карточки, речи и памяти уточняющих вопросов",
+ "Not answered: {layers}": "Нет ответа: {layers}",
+ "The flights layer is not enabled": "Слой рейсов не включён",
+ "The military layer is not enabled": "Слой военных рейсов не включён",
+ "The satellites layer is not enabled": "Слой спутников не включён",
+ "The ais-live-vessels layer is not enabled": "Слой судов AIS не включён",
+ "Could not enable the requested layer": "Не удалось включить запрошенный слой",
+ "Could not disable the requested layer": "Не удалось выключить запрошенный слой",
+ "Radio layer unavailable": "Слой радио недоступен",
+ "Camera navigation is unavailable in the current view": "Управление камерой недоступно в текущем виде",
+ "Camera navigation policy unavailable": "Правила навигации камеры недоступны",
+ "Nearest-aircraft selection supports Flights or Military Flights only": "Выбор ближайшего самолёта работает только для рейсов и военных рейсов",
+ "Nearest-aircraft selection needs a preset, place name, or latitude and longitude": "Для выбора ближайшего самолёта нужен пресет, название места или широта и долгота",
+ "Could not arrive at the requested place": "Не удалось долететь до запрошенного места",
+ "The nearest airborne aircraft could not be selected": "Не удалось выбрать ближайший самолёт в воздухе",
+ "No flights within {radius} of the current view": "В радиусе {radius} от текущего вида нет рейсов",
+ "No military within {radius} of the current view": "В радиусе {radius} от текущего вида нет военных рейсов",
+ "No satellites within {radius} of the current view": "В радиусе {radius} от текущего вида нет спутников",
+ "No vessels within {radius} of the current view": "В радиусе {radius} от текущего вида нет судов",
+ "{layer} is enabled on the {source} feed, but no airborne aircraft is loaded in the {place} view yet": "{layer}: включено (поток {source}), но в виде «{place}» пока не загружено ни одного самолёта в воздухе",
+ "{layer} is enabled, but no airborne aircraft is loaded in the {place} view yet": "{layer}: включено, но в виде «{place}» пока не загружено ни одного самолёта в воздухе",
+ "{layer} is enabled, but its aircraft feed is unavailable": "{layer}: включено, но поток данных о самолётах недоступен",
+ "{layer} is enabled, but its destination refresh did not complete": "{layer}: включено, но обновление в точке назначения не завершилось",
+ "{layer} is enabled, but {source} is unavailable": "{layer}: включено, но источник {source} недоступен",
+ "Could not arrive at {place}": "Не удалось долететь: {place}",
+ "{name} is no longer loaded": "{name}: объект больше не загружен",
+ "Unknown target layer: {target}": "Неизвестный слой цели: {target}",
+ "Layer": "Слой",
+ "there": "там",
+ "Frame flights": "Показать самолёты в кадре",
+ "Frame military": "Показать военные самолёты в кадре",
+ "Frame vessels": "Показать суда в кадре",
+ "Fly to Location": "Перелёт к месту",
+ "Nearest aircraft to Here": "Ближайший самолёт здесь",
+ "Estimate is incomplete — a response was still in flight when the session ended, so its usage was never reported.": "Оценка неполная: к моменту завершения сессии один из ответов ещё не был получен, поэтому его использование не учтено.",
+ "STANDARD": "СТАНДАРТ",
+ "vehicle motion|Stopped": "Стоит",
+ "ACQUIRING FRAME": "ПОЛУЧЕНИЕ КАДРА",
+ "Camera source temporarily unavailable": "Источник камер временно недоступен",
+ "Perimeter source unavailable": "Источник контуров пожаров недоступен",
+ "Imagery catalog unavailable": "Каталог снимков недоступен",
+ "Earthquake source unavailable": "Источник данных о землетрясениях недоступен",
+ "TeleGeography load failed": "Не удалось загрузить данные TeleGeography",
+ "Wind request timed out": "Истекло время ожидания запроса ветра",
+ "Malformed wind manifest": "Некорректный манифест ветра",
+ "Malformed wind grid": "Некорректная сетка ветра",
+ "Unknown wind model": "Неизвестная модель ветра",
+ "Unknown weather overlay": "Неизвестный погодный слой",
+ "Temperature field unavailable": "Поле температуры недоступно",
+ "Mean sea level pressure field unavailable": "Поле давления на уровне моря недоступно",
+ "KartaView answered HTTP {status}": "KartaView ответил: HTTP {status}",
+ "KartaView refused the request (code {code})": "KartaView отклонил запрос (код {code})",
+ "Stopped by voice": "Остановлено голосовой командой",
+ "drawings on the map": "рисунки на карте",
+ "imported map files": "импортированные файлы на карте",
+ "the active voice session": "активная голосовая сессия",
+ "Light aircraft": "Лёгкий самолёт",
+ "Glider": "Планёр",
+ "Turboprop": "Турбовинтовой самолёт",
+ "Airliner": "Авиалайнер",
+ "Widebody": "Широкофюзеляжный самолёт",
+ "Four-engine jet": "Четырёхмоторный реактивный самолёт",
+ "Helicopter": "Вертолёт",
+ "Fast jet": "Высокоманёвренный самолёт",
+ "Business jet": "Бизнес-джет",
+ "Drone": "Беспилотник",
+ "fire cause|Human": "деятельность человека",
+ "fire cause|Natural": "природная",
+ "fire cause|Undetermined": "не установлена",
+ "fire cause|Unknown": "неизвестна",
+ "fire behavior|Minimal": "минимальная активность",
+ "fire behavior|Moderate": "умеренная активность",
+ "fire behavior|Active": "высокая активность",
+ "fire behavior|Extreme": "экстремальная активность",
+ "Type {level} Incident": "инцидент {level}-го типа",
+ "${amount}K": "{amount} тыс. $",
+ "${amount}M": "{amount} млн $",
+ "${amount}B": "{amount} млрд $",
+ "{speed} kn": "{speed} уз",
+ "1090 MHz": "1090 МГц",
+ "978 MHz UAT": "978 МГц UAT",
+ "feed status|live": "онлайн",
+ "feed status|stale": "устарел",
+ "feed status|unreachable": "недоступен",
+ "feed status|invalid": "некорректный",
+ "Vector tile metadata unavailable": "Метаданные векторных тайлов недоступны",
+ "Vector tiles unavailable": "Векторные тайлы недоступны",
+ "Vector tiles unavailable (HTTP {status})": "Векторные тайлы недоступны (HTTP {status})",
+ "Vector tile request timed out": "Векторные тайлы: истекло время ожидания",
+ "Zoom in for vector tile coverage": "Приблизьте карту, чтобы загрузить векторные тайлы",
+ "Camera coverage unavailable": "Покрытие камер недоступно",
+ "Hybrid": "Гибрид",
+ "TomTom roads only, each with its live flow": "Только дороги TomTom, у каждой — свой поток онлайн",
+ "TomTom roads only, each with its live flow (needs a TomTom key)": "Только дороги TomTom, у каждой — свой поток онлайн (нужен ключ TomTom)",
+ "OpenStreetMap roads, with TomTom flow matched when available": "Дороги OpenStreetMap; поток TomTom сопоставляется, где он есть",
+ "TomTom roads first; OpenStreetMap fills the rest, simulated": "Сначала дороги TomTom; остальное дополняет OpenStreetMap с симуляцией потока",
+ "TomTom roads first; OpenStreetMap fills the rest, simulated (needs a TomTom key)": "Сначала дороги TomTom; остальное дополняет OpenStreetMap с симуляцией потока (нужен ключ TomTom)",
+ "Austin": "Остин",
+ "San Francisco": "Сан-Франциско",
+ "New York": "Нью-Йорк",
+ "Tokyo": "Токио",
+ "London": "Лондон",
+ "Paris": "Париж",
+ "Dubai": "Дубай",
+ "Washington DC": "Вашингтон",
+ "Tallinn": "Таллин",
+ "Los Angeles": "Лос-Анджелес",
+ "Data attribution": "Источники данных",
+ "Data provided by:": "Данные предоставлены:",
+ "Exit cockpit to view weather coverage": "Выйдите из кабины, чтобы показать зону покрытия погодного слоя",
+ "Exit cockpit to fly to a cyclone": "Выйдите из кабины, чтобы перелететь к циклону",
+ "the title of scene {scene} is empty or longer than {max} characters": "название сцены {scene} пустое или длиннее {max} символов",
+ "the title of shot {shot} in scene {scene} is empty or longer than {max} characters": "название кадра {shot} в сцене {scene} пустое или длиннее {max} символов",
+ "the project is larger than 5 MiB": "проект больше 5 МиБ",
+ "the project has too many shots": "в проекте слишком много кадров",
+ "the scene data failed validation": "данные сцены не прошли проверку",
+ "Layer on": "Слой: вкл.",
+ "Layer off": "Слой: выкл.",
+ "Zoom in": "Приблизить",
+ "Zoom out": "Отдалить",
+ "Zoom out to globe": "Отдалить до глобуса",
+ "Open data layers": "Открыть слои данных",
+ "Open or close a panel": "Открыть или закрыть панель",
+ "Change context mode": "Сменить режим контекста",
+ "Control cockpit": "Управлять кабиной",
+ "Change visual style": "Сменить визуальный стиль",
+ "Adjust HUD": "Настроить HUD",
+ "Adjust cyber sonar": "Настроить кибер-сонар",
+ "Adjust detection overlay": "Настроить слой детекции",
+ "Change map stack": "Сменить набор карт",
+ "Adjust post-processing": "Настроить постобработку",
+ "Control scene": "Управлять сценой",
+ "Control CCTV": "Управлять камерами CCTV",
+ "Control radio": "Управлять радио",
+ "Track contact": "Отслеживать контакт",
+ "Stop tracking": "Остановить отслеживание",
+ "Clear marks": "Убрать отметки",
+ "Move camera": "Переместить камеру",
+ "Fly route": "Пролететь по маршруту",
+ "Analyst query": "Аналитический запрос",
+ "Next ISS pass": "Следующий пролёт МКС",
+ "Next satellite pass": "Следующий пролёт спутника",
+ "Action": "Действие",
+ "The photo could not be loaded": "Не удалось загрузить фотографию",
+ "{name} photo. ← and → step along the sequence. On a 360° photo, drag or use Shift+← →, ↑ ↓ to look around, and + − to zoom": "Фотография {name}. ← и → листают съёмку. На 360°-фотографии перетаскивайте или используйте Shift+← →, ↑ ↓ для обзора, + − для масштаба",
+ "{name} street-level photo": "Уличная фотография {name}",
+ "Previous photo in this sequence (←)": "Предыдущая фотография съёмки (←)",
+ "Next photo in this sequence (→)": "Следующая фотография съёмки (→)",
+ "The Panoramax photo could not be loaded": "Не удалось загрузить фотографию Panoramax",
+ "Panoramax is busy — coverage resumes on its own": "Panoramax перегружен — покрытие загрузится само",
+ "no Panoramax photos in view": "фотографий Panoramax в зоне видимости нет",
+ "no Panoramax photos here match the filters": "здесь нет фотографий Panoramax, подходящих под фильтры",
+ "Panoramax sent a map tile that could not be read": "Panoramax прислал тайл карты, который не удалось прочитать",
+ "This Panoramax photo is no longer available": "Эта фотография Panoramax больше недоступна",
+ "zoom in to see Panoramax coverage": "приблизьтесь, чтобы увидеть покрытие Panoramax",
+ "Panoramax did not answer in time — try again": "Panoramax не ответил вовремя — попробуйте снова",
+ "Panoramax could not be reached — check the connection": "Не удалось связаться с Panoramax — проверьте подключение",
+ "Panoramax sent too much data": "Panoramax прислал слишком много данных",
+ "Panoramax is busy": "Panoramax перегружен",
+ "Panoramax sent an unreadable answer": "Panoramax прислал ответ, который не удалось прочитать",
+ "Apply the full cloud brightness key; 100% filter strength": "Применить полный фильтр яркости облаков; сила фильтра 100%",
+ "Show the complete infrared image; 0% filter strength": "Показать полное ИК-изображение; сила фильтра 0%",
+ "FILTER": "ФИЛЬТР",
+ "Cloud filter strength": "Сила фильтра облаков",
+ "Panoramax answered HTTP {status}": "Panoramax ответил: HTTP {status}",
+ "Highest air-quality readings in view": "Наивысшие показатели качества воздуха в поле зрения",
+ "Low": "Низкий",
+ "Moderate": "Умеренный",
+ "High": "Высокий",
+ "Very High": "Очень высокий",
+ "Air quality": "Качество воздуха",
+ "{n} sequences in view · click a line for its nearest photo": {
+ "one": "{n} съёмка в кадре · щёлкните линию, чтобы открыть ближайшую фотографию",
+ "few": "{n} съёмки в кадре · щёлкните линию, чтобы открыть ближайшую фотографию",
+ "many": "{n} съёмок в кадре · щёлкните линию, чтобы открыть ближайшую фотографию",
+ "other": "{n} съёмки в кадре · щёлкните линию, чтобы открыть ближайшую фотографию"
+ },
+ "FOV {value}° (DATASHEET)": "ОБЗОР {value}° (ПО ПАСПОРТУ)",
+ "SPEC FOV {span}° (CAPABILITY)": "ОБЗОР ПО ПАСПОРТУ {span}° (ВОЗМОЖНОСТИ)",
+ "{spec} · SPECS: CCTV-DATABASE.COM": "{spec} · ХАРАКТЕРИСТИКИ: CCTV-DATABASE.COM",
+ "Canada only · ECCC AQHI network": "Только Канада · сеть AQHI ECCC",
+ "{count} stations reporting": {
+ "one": "{count} станция передаёт данные",
+ "few": "{count} станции передают данные",
+ "many": "{count} станций передают данные",
+ "other": "{count} станции передают данные"
+ },
+ "No readings available": "Нет доступных показаний",
+ "No current readings": "Нет актуальных показаний",
+ "Low health risk": "Низкий риск для здоровья",
+ "Moderate health risk": "Умеренный риск для здоровья",
+ "High health risk": "Высокий риск для здоровья",
+ "Very High health risk": "Очень высокий риск для здоровья",
+ "Air quality request failed": "Не удалось запросить данные о качестве воздуха",
+ "ECCC request timed out": "Истекло время ожидания запроса к ECCC",
+ "Malformed AQHI station response": "Некорректный ответ со станциями AQHI",
+ "Malformed AQHI observation response": "Некорректный ответ с наблюдениями AQHI",
+ "No AQHI stations available": "Нет доступных станций AQHI",
+ "{n} air quality": {
+ "one": "{n} станция качества воздуха",
+ "few": "{n} станции качества воздуха",
+ "many": "{n} станций качества воздуха",
+ "other": "{n} станции качества воздуха"
+ },
+ "GNSS feed rate limited (HTTP 429)": "Поток GNSS: превышен лимит запросов (HTTP 429)",
+ "GNSS feed unavailable (HTTP {status})": "Поток GNSS недоступен (HTTP {status})",
+ "GNSS snapshot needs a view anchor": "Для снимка GNSS нужна опорная точка вида",
+ "Malformed GNSS integrity snapshot": "Некорректный снимок целостности GNSS",
+ "GNSS integrity snapshot has no observation time": "В снимке целостности GNSS нет времени наблюдения",
+ "{feed} feed unavailable": "Поток {feed} недоступен",
+ "Loading {feeds}": "Загрузка: {feeds}",
+ "{count} CelesTrak groups unavailable": {
+ "one": "{count} группа CelesTrak недоступна",
+ "few": "{count} группы CelesTrak недоступны",
+ "many": "{count} групп CelesTrak недоступны",
+ "other": "{count} группы CelesTrak недоступны"
+ },
+ "Malformed launch snapshot": "Некорректный снимок запусков",
+ "Malformed perimeter snapshot": "Некорректный снимок периметров",
+ "Overpass returned an incomplete camera response": "Overpass вернул неполный ответ о камерах",
+ "Fly below {km} km to a covered region": "Опуститесь ниже {km} км над регионом с покрытием",
+ "No feed here yet · {n} regions available": {
+ "one": "Здесь пока нет потока данных · доступен {n} регион",
+ "few": "Здесь пока нет потока данных · доступно {n} региона",
+ "many": "Здесь пока нет потока данных · доступно {n} регионов",
+ "other": "Здесь пока нет потока данных · доступно {n} региона"
+ },
+ "Wind speed field unavailable": "Поле скорости ветра недоступно",
+ "Decoder feeds": "Потоки декодера",
+ "WebUSB + decoder feeds": "WebUSB + потоки декодера",
+ "opening receiver": "открытие приёмника",
+ "checking decoder feeds": "проверка потоков декодера",
+ "listening": "приём",
+ "USB error": "ошибка USB",
+ "{count} heard": {
+ "one": "слышно бортов: {count}",
+ "few": "слышно бортов: {count}",
+ "many": "слышно бортов: {count}",
+ "other": "слышно бортов: {count}"
+ },
+ "{rate} msg/s": "{rate} сообщ./с",
+ "USB {rate} msg/s": "USB {rate} сообщ./с",
+ "{count} feeds live": {
+ "one": "{count} поток онлайн",
+ "few": "{count} потока онлайн",
+ "many": "{count} потоков онлайн",
+ "other": "{count} потока онлайн"
+ },
+ "feeds {names} stale": {
+ "one": "поток {names} устарел",
+ "few": "потоки {names} устарели",
+ "many": "потоки {names} устарели",
+ "other": "потоки {names} устарели"
+ },
+ "feeds {names} unreachable": {
+ "one": "поток {names} недоступен",
+ "few": "потоки {names} недоступны",
+ "many": "потоки {names} недоступны",
+ "other": "потоки {names} недоступны"
+ },
+ "feeds {names} invalid": {
+ "one": "поток {names} некорректен",
+ "few": "потоки {names} некорректны",
+ "many": "потоки {names} некорректны",
+ "other": "потоки {names} некорректны"
+ },
+ "unsaved provider keys": "несохранённые ключи провайдеров",
+ "Exit cockpit to fly to an aircraft": "Выйдите из кабины, чтобы перелететь к самолёту",
+ "Exit cockpit to fly to a satellite": "Выйдите из кабины, чтобы перелететь к спутнику",
+ "Exit cockpit to frame contacts": "Выйдите из кабины, чтобы показать контакты в кадре",
+ "{feed} {count} ({seconds}s old)": "{feed} {count} ({seconds} с назад)",
+ "entry {n}": "№ {n}",
+ "Upstream response too large": "Слишком большой ответ источника",
+ "Included in bundle": "Входит в архив",
+ "Missing bundle file — reimport its bundle": "Файла нет в архиве — импортируйте этот архив снова",
+ "Source configured; file checked when loaded": "Источник настроен; файл будет проверен при загрузке",
+ "Source unavailable": "Источник недоступен",
+ "Coverage tile failed": "Не удалось загрузить тайл покрытия",
+ "Unknown": "Неизвестно",
+ "USB work abandoned after a stalled transfer": "Работа с USB прервана: передача данных зависла",
+ "SDR decoder did not start; receiver stopped": "Декодер SDR не запустился; приёмник остановлен",
+ "SDR decoder stopped responding; receiver stopped": "Декодер SDR перестал отвечать; приёмник остановлен",
- "SDR decoder fell behind; receiver stopped": "Декодер SDR не успевает; приёмник остановлен"
++ "SDR decoder fell behind; receiver stopped": "Декодер SDR не успевает; приёмник остановлен",
++ "Gemini returned an oversized audio chunk": "Gemini вернул слишком большой фрагмент аудио",
++ "Gemini returned an unsupported audio format": "Gemini вернул неподдерживаемый формат аудио",
++ "Gemini returned an invalid audio sample rate": "Gemini вернул недопустимую частоту дискретизации аудио",
++ "Gemini returned incomplete PCM audio": "Gemini вернул неполные аудиоданные PCM",
++ "This browser does not support Gemini microphone audio": "Этот браузер не поддерживает звук с микрофона для Gemini",
++ "Microphone audio processing failed": "Не удалось обработать звук с микрофона",
++ "Gemini audio playback fell behind. Reconnect to continue.": "Воспроизведение звука Gemini отстаёт. Подключитесь заново, чтобы продолжить.",
++ "Gemini token response did not include an ephemeral credential": "В ответе Gemini нет временных учётных данных",
++ "Invalid Gemini connection endpoint": "Недопустимый адрес подключения к Gemini",
++ "Voice command context is too large": "Контекст голосовой команды слишком велик",
++ "Gemini reliable transport exceeded its queue limit. Start voice again.": "Очередь надёжной передачи Gemini превысила лимит. Запустите голосовой режим заново.",
++ "Gemini reliable transport did not drain. Start voice again.": "Очередь надёжной передачи Gemini не освободилась. Запустите голосовой режим заново.",
++ "Gemini token request failed (HTTP {status})": "Не удалось запросить токен Gemini (HTTP {status})",
++ "Gemini token response did not include a valid model": "В ответе Gemini нет допустимой модели",
++ "Gemini token response did not include session settings": "В ответе Gemini нет настроек сеанса",
++ "Gemini session settings do not match the input mode": "Настройки сеанса Gemini не соответствуют режиму ввода",
++ "Gemini could not submit this input. Start voice again.": "Gemini не удалось отправить эти данные. Запустите голосовой режим заново.",
++ "Connecting to Gemini": "Подключение к Gemini",
++ "Gemini returned an oversized message": "Gemini вернул слишком большое сообщение",
++ "Gemini Live connection failed. Check network access, then start voice again.": "Не удалось подключиться к Gemini Live. Проверьте доступ к сети и запустите голосовой режим заново.",
++ "Gemini Live connection ended. Start voice again for a new conversation.": "Соединение с Gemini Live завершено. Запустите голосовой режим заново для нового разговора.",
++ "Gemini Live could not start. Start voice again to request a fresh session.": "Не удалось запустить Gemini Live. Запустите голосовой режим заново, чтобы запросить новый сеанс.",
++ "Start voice again for a fresh token and a new conversation.": "Запустите голосовой режим заново, чтобы получить новый токен и начать новый разговор.",
++ "Start voice again to request a fresh session credential.": "Запустите голосовой режим заново, чтобы запросить новые учётные данные сеанса.",
++ "Microphone permission was denied. Allow microphone access and try again.": "Доступ к микрофону запрещён. Разрешите доступ и повторите попытку.",
++ "Gemini connection timed out. Try again.": "Время ожидания подключения к Gemini истекло. Повторите попытку.",
++ "Gemini voice could not start": "Не удалось запустить голосовой режим Gemini",
++ "Gemini did not finish the interrupted reply. Start voice again.": "Gemini не завершил прерванный ответ. Запустите голосовой режим заново.",
++ "Gemini session expiring; finishing the current reply": "Сеанс Gemini истекает; завершается текущий ответ",
++ "Gemini rejected the voice session. Start voice again to request a fresh session.": "Gemini отклонил голосовой сеанс. Запустите голосовой режим заново, чтобы запросить новый сеанс.",
++ "Start voice again for a fresh session credential. If it repeats, check Gemini model and API access.": "Запустите голосовой режим заново для получения новых учётных данных. Если ошибка повторится, проверьте модель Gemini и доступ к API.",
++ "Gemini action history is full. Start voice again for a fresh session.": "История действий Gemini заполнена. Запустите голосовой режим заново для нового сеанса.",
++ "Gemini requested too many simultaneous actions": "Gemini запросил слишком много одновременных действий",
++ "Voice text command is too long": "Текст голосовой команды слишком длинный",
++ "Gemini voice is not connected": "Голосовой режим Gemini не подключён",
++ "Gemini interrupted input exceeded its buffer or wait limit. Start voice again.": "Прерванный ввод Gemini превысил лимит буфера или ожидания. Запустите голосовой режим заново.",
++ "Gemini Live connection is expiring. Start voice again for a new conversation.": "Соединение с Gemini Live истекает. Запустите голосовой режим заново для нового разговора.",
++ "Gemini voice sessions have a time limit. When a session expires, start voice again for a new conversation.": "Время голосовых сеансов Gemini ограничено. Когда сеанс истечёт, запустите голосовой режим заново для нового разговора.",
++ "Gemini Live voice control": "Голосовое управление через Gemini Live",
++ "Voice provider": "Поставщик голосового сервиса",
++ "Changing provider reconnects voice if it is on.": "Смена поставщика переподключает голосовой режим, если он включён.",
++ "Gemini voice could not connect. Try again.": "Не удалось подключить голосовой режим Gemini. Повторите попытку.",
++ "Gemini voice requires a same-origin app request": "Голосовой режим Gemini требует запрос из того же источника, что и приложение",
++ "Add a Gemini API key in Provider Settings": "Добавьте ключ API Gemini в настройках поставщиков",
++ "The Gemini Live model configuration is invalid": "Недопустимая конфигурация модели Gemini Live",
++ "Gemini voice is starting too often. Try again shortly.": "Голосовой режим Gemini запускается слишком часто. Повторите попытку чуть позже.",
++ "Gemini quota is unavailable. Try again later.": "Квота Gemini недоступна. Повторите попытку позже.",
++ "Gemini access was refused. Check the API key and model access.": "Доступ к Gemini запрещён. Проверьте ключ API и доступ к модели.",
++ "Gemini Live is unavailable for the configured model.": "Gemini Live недоступен для выбранной модели.",
++ "Token request is too large": "Запрос токена слишком велик",
++ "Use an empty JSON token request": "Используйте запрос токена с пустым объектом JSON"
+ }
diff --cc src/keySetupCore.mjs
index 1446cc621,10bbe32a5..d8ccc048d
--- a/src/keySetupCore.mjs
+++ b/src/keySetupCore.mjs
@@@ -17,7 -19,7 +19,7 @@@ import { hasProxySignals } from './loca
/** Longest accepted key/token value. Real provider keys are all far shorter. */
export const KEY_SETUP_VALUE_LIMIT = 512;
- /** Most env vars accepted in one save; enough for the complete registry. */
-/** Most env vars accepted in one save. The registry defines ten. */
++/** Most env vars accepted in one save. */
export const KEY_SETUP_UPDATE_LIMIT = 16;
/** Header line written above keys the panel appends to a .env file. */
@@@ -60,18 -65,10 +65,18 @@@ export const KEY_SETUP_KEYS = Object.fr
envVars: Object.freeze(['OPENAI_API_KEY']),
tier: 'metered',
}),
+ Object.freeze({
+ id: 'gemini',
- title: 'GEMINI VOICE',
- unlocks: 'Voice control — free tier depends on model and project quotas',
++ title: 'GEMINI', // i18n-ignore: provider product name
++ unlocks: msg('Gemini Live voice control'),
+ getUrl: 'https://aistudio.google.com/apikey',
+ envVars: Object.freeze(['GEMINI_API_KEY']),
- tier: 'free',
++ tier: 'metered',
+ }),
Object.freeze({
id: 'aisstream',
- title: 'AISSTREAM',
- unlocks: 'Live ships, worldwide',
+ title: 'AISSTREAM', // i18n-ignore: provider product name
+ unlocks: msg('Live ships, worldwide'),
getUrl: 'https://aisstream.io',
envVars: Object.freeze(['AISSTREAM_API_KEY']),
tier: 'free',
diff --cc src/standalone/tools.js
index 5d5abd263,fb127d598..eec4d0796
--- a/src/standalone/tools.js
+++ b/src/standalone/tools.js
@@@ -17,10 -17,6 +17,10 @@@ export function createStandaloneTools(o
},
},
...options,
- voice: { toolCatalog: loadToolCatalog, ...options?.voice },
+ voice: {
- toolCatalog: loadToolCatalog,
+ supportedProviders: ['openai', 'gemini'],
++ toolCatalog: loadToolCatalog,
+ ...options?.voice,
+ },
});
}
diff --cc src/testSupport/geminiIntegrationFixture.mjs
index 000000000,000000000..ad84dcce6
new file mode 100644
--- /dev/null
+++ b/src/testSupport/geminiIntegrationFixture.mjs
@@@ -1,0 -1,0 +1,364 @@@
++import assert from 'node:assert/strict';
++import { createVoiceSession } from '../voice/session.js';
++import { createGevActionRunner } from '../voice/gevActions.js';
++import { createGeminiSession } from '../voice/geminiSession.js';
++import { createNarrationScheduler } from '../voice/narration.js';
++
++export const turnOfEventLoop = () =>
++ new Promise((resolve) => setImmediate(resolve));
++
++function deferred() {
++ let resolve;
++ const promise = new Promise((done) => {
++ resolve = done;
++ });
++ return { promise, resolve };
++}
++
++function ownedClock() {
++ let now = 0;
++ let nextId = 0;
++ const timers = new Map();
++ return {
++ timers,
++ now: () => now,
++ setTimer(fn, delay = 0) {
++ const id = ++nextId;
++ timers.set(id, { fn, at: now + Math.max(0, delay) });
++ return id;
++ },
++ clearTimer: (id) => timers.delete(id),
++ advance(ms) {
++ const until = now + ms;
++ let callbacks = 0;
++ for (;;) {
++ const due = [...timers]
++ .filter(([, timer]) => timer.at <= until)
++ .sort((a, b) => a[1].at - b[1].at || a[0] - b[0])[0];
++ if (!due) break;
++ assert.ok(
++ ++callbacks <= 1000,
++ 'fixture timer queue must remain bounded',
++ );
++ timers.delete(due[0]);
++ now = due[1].at;
++ due[1].fn();
++ }
++ now = until;
++ },
++ };
++}
++
++/**
++ * Real common session -> real Gemini adapter -> real action runner.
++ * Only devices, transport, passive UI and wall-clock facilities are fakes.
++ * The optional result gate delays return AFTER the actual action commits.
++ */
++export function nativeIntegrationFixture(t) {
++ const clock = ownedClock();
++ const events = [];
++ const sockets = [];
++ const tracks = [];
++ const audios = [];
++ const requests = [];
++ const runnerCalls = [];
++ const runnerJobs = [];
++ const resultGates = new Map();
++ const acquisitions = { microphone: 0, audio: 0, token: 0, socket: 0 };
++ const state = { height: 1000, renders: 0, zooms: [], earconStarts: 0 };
++ const position = { x: 6379137, y: 0, z: 0 };
++ const viewer = {
++ clock: { onTick: { addEventListener: () => () => {} } },
++ camera: {
++ positionWC: position,
++ positionCartographic: { height: state.height },
++ moveEnd: { addEventListener() {} },
++ cancelFlight() {},
++ zoomIn(metres) {
++ position.x -= metres;
++ state.height -= metres;
++ this.positionCartographic.height = state.height;
++ state.zooms.push({ direction: 'in', metres });
++ },
++ zoomOut(metres) {
++ position.x += metres;
++ state.height += metres;
++ this.positionCartographic.height = state.height;
++ state.zooms.push({ direction: 'out', metres });
++ },
++ },
++ scene: {
++ canvas: {
++ clientWidth: 800,
++ clientHeight: 600,
++ addEventListener() {},
++ removeEventListener() {},
++ },
++ requestRender() {
++ state.renders++;
++ },
++ },
++ };
++ const dataManager = { layers: new Map() };
++ const actualRunner = createGevActionRunner({
++ viewer,
++ dataManager,
++ styleManager: {},
++ });
++ const runner = (name, args, options) => {
++ runnerCalls.push({ name, args, options });
++ const job = (async () => {
++ // No fake action result: the camera and envelope come from production.
++ const result = await actualRunner(name, args, options);
++ const gate = resultGates.get(options.callId);
++ if (gate) {
++ gate.entered.resolve(result);
++ await gate.release.promise;
++ }
++ return result;
++ })();
++ runnerJobs.push(job);
++ return job;
++ };
++ class Socket {
++ constructor(url) {
++ acquisitions.socket++;
++ this.url = url;
++ this.readyState = 0;
++ this.bufferedAmount = 0;
++ this.sent = [];
++ sockets.push(this);
++ queueMicrotask(() => {
++ if (this.closed) return;
++ this.readyState = 1;
++ this.onopen?.();
++ });
++ }
++ send(raw) {
++ assert.equal(
++ this.readyState,
++ 1,
++ 'sending requires the owned open socket',
++ );
++ const message = JSON.parse(raw);
++ this.sent.push(message);
++ if (message.setup)
++ queueMicrotask(() => this.message({ setupComplete: {} }));
++ }
++ message(message) {
++ this.onmessage?.({ data: JSON.stringify(message) });
++ }
++ close() {
++ this.closed = true;
++ this.readyState = 3;
++ }
++ }
++ const session = createVoiceSession({
++ runner,
++ createAdapter: (hooks) =>
++ createGeminiSession({
++ ...hooks,
++ ui: { root: { remove() {} } },
++ dataManager,
++ now: clock.now,
++ setTimer: clock.setTimer,
++ clearTimer: clock.clearTimer,
++ WebSocketClass: Socket,
++ getUserMedia: async () => {
++ acquisitions.microphone++;
++ const track = {
++ enabled: true,
++ readyState: 'live',
++ stopCalls: 0,
++ stop() {
++ this.stopCalls++;
++ this.readyState = 'ended';
++ },
++ };
++ tracks.push(track);
++ return { getTracks: () => [track], getAudioTracks: () => [track] };
++ },
++ fetchImpl: async (url, init) => {
++ acquisitions.token++;
++ requests.push({ url, init });
++ const manual = JSON.parse(init.body).inputMode === 'push-to-talk';
++ return Response.json({
++ token: 'auth_tokens/fixture-not-a-credential',
++ model: 'gemini-3.8-live',
++ websocketUrl:
++ 'wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContentConstrained',
++ config: {
++ generationConfig: { responseModalities: ['AUDIO'] },
++ ...(manual
++ ? {
++ realtimeInputConfig: {
++ automaticActivityDetection: { disabled: true },
++ },
++ }
++ : {}),
++ },
++ });
++ },
++ createInput: ({ readStream, operations }) => ({
++ ...operations,
++ setMicrophoneEnabled(enabled) {
++ for (const track of readStream()?.getAudioTracks() || [])
++ track.enabled = enabled;
++ },
++ updateVoiceButtonLabel() {},
++ setVoiceSpeaker() {},
++ startVoiceVisualizer() {},
++ startAssistantVoiceVisualizer() {},
++ cancelPushToTalkHold() {},
++ stopVoiceVisualizer() {},
++ detachBindings() {},
++ bindPushToTalkShortcut() {},
++ resetSession() {
++ this.pushToTalkMode =
++ this.pushToTalkKeyHeld =
++ this.spaceKeyHeld =
++ false;
++ },
++ }),
++ createAudio: (callbacks) => {
++ acquisitions.audio++;
++ const audio = {
++ pending: false,
++ closed: false,
++ outputStream: {},
++ async initialize() {},
++ connectMicrophone(stream, enabled, metadata) {
++ this.stream = stream;
++ this.setMicrophoneEnabled(enabled, metadata);
++ },
++ setMicrophoneEnabled(enabled, metadata) {
++ this.enabled = enabled;
++ this.metadata = metadata;
++ },
++ play() {
++ this.pending = true;
++ },
++ clearPlayback() {
++ this.pending = false;
++ },
++ drain() {
++ this.pending = false;
++ callbacks.onDrain();
++ },
++ diagnostics: () => ({ outputChunks: 0 }),
++ async close() {
++ this.closed = true;
++ this.pending = false;
++ return true;
++ },
++ };
++ audios.push(audio);
++ return audio;
++ },
++ createNarration: (options) =>
++ createNarrationScheduler({
++ ...options,
++ now: clock.now,
++ setTimer: clock.setTimer,
++ clearTimer: clock.clearTimer,
++ }),
++ createProgressEarcon: () => ({
++ available: () => true,
++ start() {
++ state.earconStarts++;
++ },
++ stop() {},
++ dispose() {},
++ }),
++ captureViewport: async () => null,
++ }),
++ });
++ session.subscribe((event) => events.push(event));
++ const controller = session.adapter.controller;
++ t.after(async () => {
++ session.destroy();
++ for (const gate of resultGates.values()) gate.release.resolve();
++ await Promise.allSettled(runnerJobs);
++ actualRunner.dispose();
++ assert.equal(clock.timers.size, 0, 'fixture must leave no owned timer');
++ assert.ok(audios.every((audio) => audio.closed));
++ assert.ok(tracks.every((track) => track.readyState === 'ended'));
++ assert.ok(sockets.every((socket) => socket.closed));
++ });
++ return {
++ session,
++ controller,
++ state,
++ events,
++ sockets,
++ tracks,
++ audios,
++ requests,
++ acquisitions,
++ runnerCalls,
++ clock,
++ holdResult(callId) {
++ const gate = { entered: deferred(), release: deferred() };
++ resultGates.set(callId, gate);
++ return { ready: gate.entered.promise, release: gate.release.resolve };
++ },
++ async start() {
++ await session.start();
++ assert.equal(session.state, 'listening');
++ assert.equal(controller.getDiagnostics().connected, true);
++ return sockets.at(-1);
++ },
++ activity(socket = sockets.at(-1)) {
++ socket.message({ voiceActivity: { type: 'ACTIVITY_START' } });
++ socket.message({ voiceActivity: { type: 'ACTIVITY_END' } });
++ },
++ tool(callId, socket = sockets.at(-1)) {
++ socket.message({
++ toolCall: {
++ functionCalls: [
++ {
++ id: callId,
++ name: 'adjust_camera_zoom',
++ args: { direction: 'in', amount: 'little' },
++ },
++ ],
++ },
++ });
++ // A deterministic settlement boundary, not a fake action dispatcher.
++ return controller.toolQueue;
++ },
++ outputs(socket = sockets.at(-1)) {
++ return socket.sent.flatMap(
++ (message) => message.toolResponse?.functionResponses || [],
++ );
++ },
++ complete(socket = sockets.at(-1)) {
++ socket.message({ serverContent: { turnComplete: true } });
++ },
++ };
++}
++
++export function assertSuccessfulZoom(h, socket, callId, beforeHeight) {
++ assert.equal(h.state.height, beforeHeight * 0.75);
++ assert.ok(h.state.renders > 0);
++ const calls = h.events.filter(
++ (event) => event.type === 'action-call' && event.callId === callId,
++ );
++ const results = h.events.filter(
++ (event) => event.type === 'action-result' && event.callId === callId,
++ );
++ assert.equal(calls.length, 1);
++ assert.equal(results.length, 1);
++ assert.equal(calls[0].name, 'adjust_camera_zoom');
++ assert.deepEqual(calls[0].arguments, { direction: 'in', amount: 'little' });
++ assert.equal(results[0].result.ok, true);
++ assert.equal(results[0].result.action, 'adjust_camera_zoom');
++ assert.equal(results[0].result.beforeHeightM, Math.round(beforeHeight));
++ assert.equal(results[0].result.afterHeightM, Math.round(h.state.height));
++ const outputs = h.outputs(socket).filter((output) => output.id === callId);
++ assert.equal(outputs.length, 1);
++ assert.equal(outputs[0].name, 'adjust_camera_zoom');
++ assert.equal(outputs[0].response.ok, true);
++ assert.equal(outputs[0].response.action, 'adjust_camera_zoom');
++ assert.equal(outputs[0].response.afterHeightM, Math.round(h.state.height));
++}
diff --cc src/testSupport/geminiNativeHarness.mjs
index 7ecc06969,000000000..fab535027
mode 100644,000000..100644
--- a/src/testSupport/geminiNativeHarness.mjs
+++ b/src/testSupport/geminiNativeHarness.mjs
@@@ -1,254 -1,0 +1,251 @@@
- import { GeminiSessionController } from './geminiSession.js';
- import { createNarrationScheduler } from './narration.js';
++import { GeminiSessionController } from '../voice/geminiSession.js';
++import { createNarrationScheduler } from '../voice/narration.js';
+
+const endpoint =
+ 'wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContentConstrained';
+const credential = {
+ token: 'auth_tokens/test',
+ model: 'gemini-3.8-live',
+ websocketUrl: endpoint,
+ config: { generationConfig: { responseModalities: ['AUDIO'] } },
+};
+const manualCredential = {
+ ...credential,
+ config: {
+ ...credential.config,
+ realtimeInputConfig: { automaticActivityDetection: { disabled: true } },
+ },
+};
+const tick = () => new Promise((resolve) => setImmediate(resolve));
+function deferred() {
+ let resolve;
+ const promise = new Promise((done) => {
+ resolve = done;
+ });
+ return { promise, resolve };
+}
+function harness(overrides = {}) {
+ const { autoSetup = true, ...controllerOverrides } = overrides;
+ const events = [];
+ const sockets = [];
+ const media = [];
+ const tracks = [];
+ const captures = [];
+ const calls = [];
+ const requests = [];
+ const state = { playing: 0, ducked: false, stopped: 0 };
+ let clock = 0;
+ let nextTimer = 0;
+ const timers = new Map();
+ const earcon = { playing: false, starts: 0, disposals: 0 };
+ const advance = (ms) => {
+ const target = clock + ms;
+ for (;;) {
+ const due = [...timers]
+ .filter(([, timer]) => timer.at <= target)
+ .sort((a, b) => a[1].at - b[1].at)[0];
+ if (!due) break;
+ timers.delete(due[0]);
+ clock = due[1].at;
+ due[1].fn();
+ }
+ clock = target;
+ };
+ let radioControl;
+ const radio = {
+ setVoiceDucked(value) {
+ state.ducked = value;
+ },
+ pause() {},
+ subscribePlaybackControls(callback) {
+ radioControl = callback;
+ return () => {
+ radioControl = null;
+ };
+ },
+ async playForVoice() {
+ state.playing++;
+ return true;
+ },
+ stopPlayback() {
+ state.stopped++;
+ },
+ };
+ class Socket {
+ constructor(url) {
+ this.url = url;
+ this.readyState = 0;
+ this.bufferedAmount = 0;
+ this.sent = [];
+ sockets.push(this);
+ queueMicrotask(() => {
+ this.readyState = 1;
+ this.onopen?.();
+ });
+ }
+ send(raw) {
+ const value = JSON.parse(raw);
+ this.sent.push(value);
+ if (value.setup && autoSetup)
+ queueMicrotask(() => this.message({ setupComplete: {} }));
+ }
+ message(value) {
+ this.onmessage?.({ data: JSON.stringify(value) });
+ }
+ error() {
+ this.onerror?.();
+ }
+ remoteClose() {
+ this.readyState = 3;
+ this.onclose?.();
+ }
+ close() {
+ this.readyState = 3;
+ this.closed = true;
+ }
+ }
+ const makeStream = () => {
+ const track = {
+ enabled: true,
+ readyState: 'live',
+ stop() {
+ this.readyState = 'ended';
+ },
+ };
+ tracks.push(track);
+ return { getTracks: () => [track], getAudioTracks: () => [track] };
+ };
+ const c = new GeminiSessionController({
+ emit: (event) => events.push(event),
+ runAction: async (name, args, options) => {
+ calls.push({ name, args, options });
+ return { ok: true, action: name };
+ },
+ ui: { root: { remove() {} } },
+ radioLayer: radio,
+ now: () => clock,
- prefixNow: () => clock,
+ setTimer: (fn, ms) => {
+ const id = ++nextTimer;
+ timers.set(id, { fn, at: clock + ms });
+ return id;
+ },
+ clearTimer: (id) => timers.delete(id),
+ WebSocketClass: Socket,
+ fetchImpl: async (_url, init) => {
+ requests.push(init);
- return {
- ok: true,
- json: async () =>
- JSON.parse(init.body).inputMode === 'push-to-talk'
- ? manualCredential
- : credential,
- };
++ return Response.json(
++ JSON.parse(init.body).inputMode === 'push-to-talk'
++ ? manualCredential
++ : credential,
++ );
+ },
+ getUserMedia: async () => makeStream(),
+ createInput: ({ readStream, operations }) => ({
+ ...operations,
+ setMicrophoneEnabled(enabled) {
+ for (const track of readStream()?.getAudioTracks() || [])
+ track.enabled = enabled;
+ },
+ updateVoiceButtonLabel() {},
+ setVoiceSpeaker() {},
+ startVoiceVisualizer() {},
+ startAssistantVoiceVisualizer() {},
+ cancelPushToTalkHold() {},
+ stopVoiceVisualizer() {},
+ detachBindings() {},
+ bindPushToTalkShortcut() {},
+ resetSession() {
+ this.pushToTalkMode = false;
+ this.pushToTalkKeyHeld = false;
+ this.spaceKeyHeld = false;
+ },
+ }),
+ createNarration: (options) =>
+ createNarrationScheduler({
+ ...options,
+ now: () => clock,
+ setTimer: (fn, ms) => {
+ const id = ++nextTimer;
+ timers.set(id, { fn, at: clock + ms });
+ return id;
+ },
+ clearTimer: (id) => timers.delete(id),
+ }),
+ createProgressEarcon: ({ isMicrophoneMuted }) => ({
+ available: isMicrophoneMuted,
+ start() {
+ earcon.playing = true;
+ earcon.starts++;
+ },
+ stop() {
+ earcon.playing = false;
+ },
+ dispose() {
+ this.stop();
+ earcon.disposals++;
+ },
+ }),
+ createAudio: (callbacks) => {
+ const audio = {
+ callbacks,
+ pending: false,
+ closed: false,
+ played: [],
+ async initialize() {},
+ connectMicrophone(stream, enabled, metadata) {
+ media.push({ stream, enabled });
+ this.connected = true;
+ this.setMicrophoneEnabled(enabled, metadata);
+ },
+ setMicrophoneEnabled(value, metadata) {
+ if (!this.connected) return;
+ if (value && !this.enabled) {
+ this.metadata = metadata;
+ callbacks.onAudioStart(metadata);
+ }
+ if (!value && this.enabled) callbacks.onAudioEnd(this.metadata);
+ this.enabled = value;
+ },
+ play(data, mime) {
+ this.pending = true;
+ this.played.push({ data, mime });
+ },
+ drain() {
+ this.pending = false;
+ callbacks.onDrain();
+ },
+ clearPlayback() {
+ this.pending = false;
+ this.cleared = true;
+ },
+ diagnostics() {
+ return { outputChunks: this.played.length };
+ },
+ close() {
+ this.closed = true;
+ },
+ };
+ captures.push(audio);
+ return audio;
+ },
+ ...controllerOverrides,
+ });
+ return {
+ c,
+ sockets,
+ tracks,
+ makeStream,
+ events,
+ media,
+ captures,
+ calls,
+ requests,
+ state,
+ advance,
+ timers,
+ earcon,
+ radioControl: (value) => radioControl?.(value),
+ };
+}
+
+export { harness, tick, deferred };
diff --cc src/tooling/viteBuild.test.mjs
index 86a9afb63,9e38a0295..e1eb1aecd
--- a/src/tooling/viteBuild.test.mjs
+++ b/src/tooling/viteBuild.test.mjs
@@@ -88,14 -88,16 +88,27 @@@ test('root config retains existing name
for (const [name, value] of Object.entries(providers))
assert.equal(compatibility[name], value, name);
const config = standaloneConfig({ mode: 'test' });
++ const standaloneProviders = config.plugins
++ .slice(3, -5)
++ .map((plugin) => plugin.name);
++ assert.equal(
++ standaloneProviders.filter((name) => name === 'gemini-live-proxy').length,
++ 1,
++ );
++ assert.equal(
++ standaloneProviders.indexOf('gemini-live-proxy'),
++ standaloneProviders.indexOf('openai-realtime-proxy') + 1,
++ );
assert.deepEqual(
- config.plugins.slice(3, -4).map((plugin) => plugin.name),
- config.plugins.slice(3, -5).map((plugin) => plugin.name),
++ standaloneProviders.filter((name) => name !== 'gemini-live-proxy'),
providers.localProviderPlugins().map((plugin) => plugin.name),
);
- assert.equal(config.plugins.at(-5).name, 'gev-key-setup');
+ assert.equal(config.plugins.at(-6).name, 'gev-key-setup');
// The local MCP route follows every provider and precedes the API fallback.
- assert.equal(config.plugins.at(-4).name, 'local-mcp');
- assert.equal(config.plugins.at(-3).name, 'api-not-found');
+ assert.equal(config.plugins.at(-5).name, 'local-mcp');
+ assert.equal(config.plugins.at(-4).name, 'api-not-found');
+ // Config-only, so it sits after the provider slice rather than in it.
+ assert.equal(config.plugins.at(-3).name, 'gev-unwatched-runtime-dirs');
assert.equal(config.plugins.at(-2).name, 'embed-framing');
assert.equal(config.plugins.at(-1).name, 'panel-build');
});
diff --cc src/ui/styles/voice-cost.css
index dd0c33050,128811e3b..b43f40168
--- a/src/ui/styles/voice-cost.css
+++ b/src/ui/styles/voice-cost.css
@@@ -83,87 -83,60 +83,152 @@@
display: none;
}
- #command-dock #gev-voice-control[data-provider] {
+ /* The heading row is only as wide as the voice column: the cost cluster
+ keeps its size and a long state (ПОДКЛЮЧЕНИЕ, CONECTANDO) ends in an
+ ellipsis. Dropping the kicker returns its gap to the state label; the
+ negative margin reaches over the gutter beside the mic ring, which has
+ curved away at heading height. */
+ html:not([lang='en']) #command-dock .gev-voice-heading {
+ gap: 0.2rem;
+ margin-left: -0.6rem;
+ }
+
+ html:not([lang='en']) #command-dock .gev-voice-heading > .gev-voice-kicker {
+ display: none;
+ }
+
+ html:not([lang='en']) #command-dock .gev-voice-heading > #gev-voice-status {
+ flex: 0 1 auto;
+ min-width: 0;
+ overflow: hidden;
+ letter-spacing: 0;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ html:not([lang='en']) #command-dock .gev-voice-cost {
+ gap: 0.16rem;
+ padding-left: 0.1rem;
+ }
+
+ html:not([lang='en']) #command-dock .gev-voice-tier-btn {
+ min-width: 0;
+ padding: 0 0.2rem;
+ }
+
+ html:not([lang='en']) #command-dock .gev-voice-cost-value {
+ letter-spacing: 0;
+ }
+
+ /* Live hints and the tier switch ("СТАНДАРТ — со следующей сессии") run
+ longer: a second line from the spare space under the readout, with no
+ tracking so the tier line does not need a third. */
+ html:not([lang='en'])
+ #command-dock
+ #gev-voice-control:is(
+ [data-status='connecting'],
+ [data-status='listening'],
+ [data-status='executing']
+ )
+ #gev-voice-detail {
+ display: -webkit-box;
+ -webkit-box-orient: vertical;
+ -webkit-line-clamp: 2;
+ line-clamp: 2;
+ line-height: 1.15;
+ letter-spacing: 0;
+ white-space: normal;
+ overflow-wrap: anywhere;
+ }
++
++#gev-voice-control[data-provider-choice='true'] {
+ --gev-provider-lift: 0px;
+}
+
+/* Provider choice belongs to the existing voice control, not a separate panel. */
+.gev-voice-provider-field {
+ position: absolute;
+ bottom: calc(100% + var(--gev-provider-lift, 0px));
+ z-index: 9;
+ left: 0;
+ right: 0;
+ display: grid;
+ gap: 4px;
+ padding: 8px 6px;
+ border: 1px solid var(--glass-border);
+ border-radius: 8px;
+ background: var(--bg-panel, #09121b);
+ color: var(--text-secondary);
+ font-family: var(--font-mono);
+ font-size: 0.5rem;
+ opacity: 0;
+ pointer-events: none;
+}
+.gev-voice-provider-field[hidden] {
+ display: none;
+}
+.gev-voice-provider-field select {
+ min-width: 0;
+ width: 100%;
+ min-height: 30px;
+ color: var(--text-primary);
+ background: #09121b;
+ border: 1px solid var(--glass-border);
+ border-radius: 4px;
+ font: inherit;
+ font-size: 0.65rem;
+}
+#gev-voice-control:hover .gev-voice-provider-field,
+#gev-voice-control:focus-within .gev-voice-provider-field {
+ opacity: 1;
+ pointer-events: auto;
+}
- #command-dock #gev-voice-control[data-provider] .gev-voice-help-tray,
- #command-dock #gev-voice-control[data-provider] .gev-voice-card,
- #command-dock #gev-voice-control[data-provider] .gev-voice-error-tray {
++#command-dock
++ #gev-voice-control[data-provider-choice='true']
++ .gev-voice-help-tray,
++#command-dock #gev-voice-control[data-provider-choice='true'] .gev-voice-card,
++#command-dock
++ #gev-voice-control[data-provider-choice='true']
++ .gev-voice-error-tray {
+ bottom: calc(100% + 4.8rem + var(--gev-provider-lift));
+}
- #command-dock.dock-has-pinned-tray #gev-voice-control[data-provider] {
++#command-dock.dock-has-pinned-tray
++ #gev-voice-control[data-provider-choice='true'] {
+ --gev-provider-lift: calc(1.7rem + var(--dock-pinned-stack-height));
+}
+/* Pinned trays separate the chooser from its hover owner. Keep it reachable
+ across that gap without requiring keyboard focus to hold it open. */
+#command-dock.dock-has-pinned-tray .gev-voice-provider-field {
+ opacity: 1;
+ pointer-events: auto;
+}
+@media (max-width: 900px) {
+ /* The attribution clearance also creates a gap for mouse users in a
+ narrow window, so the raised chooser must not depend on root hover. */
+ .gev-voice-provider-field {
+ opacity: 1;
+ pointer-events: auto;
+ }
- #command-dock #gev-voice-control[data-provider] {
++ #command-dock #gev-voice-control[data-provider-choice='true'] {
+ --gev-provider-lift: 3rem;
+ }
- #command-dock.dock-has-pinned-tray #gev-voice-control[data-provider] {
++ #command-dock.dock-has-pinned-tray
++ #gev-voice-control[data-provider-choice='true'] {
+ --gev-provider-lift: calc(3.5rem + var(--dock-pinned-stack-height));
+ }
+}
+@media (max-width: 720px) {
- #command-dock #gev-voice-control[data-provider] {
++ #command-dock #gev-voice-control[data-provider-choice='true'] {
+ --gev-provider-lift: calc(2vh + 2.5rem);
+ }
- #command-dock.dock-has-pinned-tray #gev-voice-control[data-provider] {
++ #command-dock.dock-has-pinned-tray
++ #gev-voice-control[data-provider-choice='true'] {
+ --gev-provider-lift: calc(2vh + 3rem + var(--dock-pinned-stack-height));
+ }
+}
+@media (hover: none) {
+ .gev-voice-provider-field {
+ opacity: 1;
+ pointer-events: auto;
+ }
+}
diff --cc src/voice/commands.js
index fe77ddcf0,cc059852b..c5f92b209
--- a/src/voice/commands.js
+++ b/src/voice/commands.js
@@@ -1,27 -1,10 +1,18 @@@
import { createVoiceCommands as bindVoiceCommands } from './sessionCommands.js';
import { createRealtimeSession } from './realtimeSession.js';
+import { createGeminiSession } from './geminiSession.js';
+import { createProviderCommands } from './providerCommands.js';
- import { supportedVoiceProviders } from './providerCapabilities.js';
- /** Standalone provider selection; embedders may still supply their own adapter. */
- export function createVoiceCommands(options) {
- if (options.createSession) return bindVoiceCommands(options);
- const factories = {
- openai: createRealtimeSession,
- gemini: createGeminiSession,
- };
- const supportedProviders = supportedVoiceProviders(
- options.supportedProviders,
- factories,
- );
- return createProviderCommands(
- { ...options, supportedProviders },
- {
+ /** Default composition; callers may supply another session adapter factory. */
-export function createVoiceCommands(options) {
++export function createVoiceCommands(options = {}) {
++ // Generic hosts retain the existing default; standalone opts in explicitly.
++ if (!options.createSession && options.supportedProviders !== undefined)
++ return createProviderCommands(options, {
+ bind: bindVoiceCommands,
- factories: Object.fromEntries(
- supportedProviders.map((name) => [name, factories[name]]),
- ),
- },
- );
++ factories: { openai: createRealtimeSession, gemini: createGeminiSession },
++ });
+ return bindVoiceCommands({
+ createSession: createRealtimeSession,
+ ...options,
+ });
}
diff --cc src/voice/control.js
index 7739624de,e729a5cb1..c77197412
--- a/src/voice/control.js
+++ b/src/voice/control.js
@@@ -11,24 -39,17 +39,21 @@@ export function createVoiceControl({ re
root.dataset.status = 'idle';
root.dataset.speaker = 'idle';
root.innerHTML = `
+ <label id="gev-voice-provider-field" class="gev-voice-provider-field" hidden>
- <span>VOICE PROVIDER</span>
- <select id="gev-voice-provider" aria-label="Voice provider" title="Changing provider reconnects voice if it is on">
- <option value="openai">OpenAI</option>
- <option value="gemini">Gemini</option>
- </select>
++ <span>${t('Voice provider')}</span>
++ <select id="gev-voice-provider" aria-label="${t('Voice provider')}" title="${t('Changing provider reconnects voice if it is on.')}"></select>
+ </label>
<div class="gev-voice-heading">
- <div class="gev-voice-kicker">AI AGENT</div>
- <div id="gev-voice-status">OFF</div>
+ <div class="gev-voice-kicker">${t('AI AGENT')}</div>
+ <div id="gev-voice-status">${voiceStatusLabel('idle')}</div>
<div class="gev-voice-cost">
- <button id="gev-voice-tier" class="gev-voice-tier-btn" type="button" aria-pressed="false" title="Voice model tier — applies next session">STD</button>
- <span id="gev-voice-cost-value" class="gev-voice-cost-value" data-level="ok" title="Estimated session cost">~$0.00</span>
+ <button id="gev-voice-tier" class="gev-voice-tier-btn" type="button" aria-pressed="false" title="${t('Voice model tier — applies next session')}">${t('STD')}</button>
+ <span id="gev-voice-cost-value" class="gev-voice-cost-value" data-level="ok" title="${t('Estimated session cost')}">~$0.00</span>
</div>
</div>
- <button id="gev-voice-button" type="button" aria-label="Voice control — activate to toggle voice; hold Space to speak" aria-describedby="gev-voice-help">
+ <button id="gev-voice-button" type="button" aria-label="${t('Voice control — activate to toggle voice; hold Space to speak')}" aria-describedby="gev-voice-help">
<span class="gev-mic-orbit"><img src="/mic.svg" alt="" /></span>
- <span class="gev-mic-label">ON/OFF</span>
+ <span class="gev-mic-label">${t('ON/OFF')}</span>
</button>
<div class="gev-voice-visualizer" aria-hidden="true">
${Array.from({ length: 15 }, (_, index) => `<span style="--bar:${index}"></span>`).join('')}
@@@ -90,9 -110,6 +114,8 @@@
}
return {
root,
+ providerField: root.querySelector('#gev-voice-provider-field'),
+ providerSelect: root.querySelector('#gev-voice-provider'),
- errorHint: root.querySelector('.gev-voice-error-hint'),
button: root.querySelector('#gev-voice-button'),
buttonLabel: root.querySelector('.gev-mic-label'),
status: root.querySelector('#gev-voice-status'),
diff --cc src/voice/geminiAcquisition.test.mjs
index 000000000,000000000..1b80d6cd6
new file mode 100644
--- /dev/null
+++ b/src/voice/geminiAcquisition.test.mjs
@@@ -1,0 -1,0 +1,142 @@@
++import test from 'node:test';
++import assert from 'node:assert/strict';
++import {
++ harness,
++ deferred,
++ tick,
++} from '../testSupport/geminiNativeHarness.mjs';
++
++function unreadResponse(bytes = null) {
++ const state = { reads: 0, cancelled: 0 };
++ const response = new Response(
++ new ReadableStream(
++ {
++ pull(controller) {
++ state.reads++;
++ if (bytes) controller.enqueue(bytes);
++ },
++ cancel() {
++ state.cancelled++;
++ },
++ },
++ { highWaterMark: 0 },
++ ),
++ );
++ return { response, state };
++}
++
++test('already aborted token request does not acquire or read a response', async (t) => {
++ let fetches = 0;
++ const h = harness({
++ fetchImpl: () => {
++ fetches++;
++ throw Error('must not fetch');
++ },
++ });
++ t.after(() => h.c.stop());
++ const abort = new AbortController();
++ abort.abort();
++ await assert.rejects(h.c.requestToken(abort.signal), { name: 'AbortError' });
++ assert.equal(fetches, 0);
++});
++
++for (const phase of [
++ 'before response',
++ 'between resolution and continuation',
++]) {
++ test(`aborted token acquisition closes the unread body ${phase}`, async (t) => {
++ const gate = deferred();
++ const h = harness({ fetchImpl: () => gate.promise });
++ t.after(() => h.c.stop());
++ const abort = new AbortController();
++ const { response, state } = unreadResponse();
++ const result = assert.rejects(h.c.requestToken(abort.signal), {
++ name: 'AbortError',
++ });
++ if (phase === 'before response') abort.abort();
++ gate.resolve(response);
++ if (phase !== 'before response') queueMicrotask(() => abort.abort());
++ await result;
++ await tick();
++ assert.deepEqual(state, { reads: 0, cancelled: 1 });
++ });
++}
++
++test('token body cap cancels a native response stream', async (t) => {
++ const { response, state } = unreadResponse(new Uint8Array(256 * 1024 + 1));
++ const h = harness({ fetchImpl: async () => response });
++ t.after(() => h.c.stop());
++ await assert.rejects(
++ h.c.requestToken(new AbortController().signal),
++ /too large|exceed|limit/i,
++ );
++ assert.equal(state.cancelled, 1);
++ assert.equal(state.reads, 1);
++});
++
++test('token body read ends promptly on caller abort and releases the reader', async (t) => {
++ const { response, state } = unreadResponse();
++ const h = harness({ fetchImpl: async () => response });
++ t.after(() => h.c.stop());
++ const abort = new AbortController();
++ const result = assert.rejects(h.c.requestToken(abort.signal), {
++ name: 'AbortError',
++ });
++ await tick();
++ assert.equal(state.reads, 1);
++ abort.abort();
++ await result;
++ assert.equal(state.cancelled, 1);
++ assert.equal(response.body.locked, false);
++});
++
++test('permission grant resolved just before Stop releases its tracks and preserves a fresh start', async (t) => {
++ const gate = deferred();
++ const h = harness({ getUserMedia: () => gate.promise });
++ t.after(() => h.c.stop());
++ const stream = h.makeStream();
++ const start = h.c.start();
++ gate.resolve(stream);
++ queueMicrotask(() => h.c.stop());
++ await start;
++ await tick();
++ assert.equal(h.tracks[0].readyState, 'ended');
++ assert.equal(h.requests.length, 0);
++ assert.equal(h.sockets.length, 0);
++ assert.equal(h.captures[0].closed, true);
++ h.c.getUserMedia = async () => h.makeStream();
++ await h.c.start();
++ assert.equal(h.c.status, 'listening');
++ assert.equal(h.tracks[1].readyState, 'live');
++ assert.equal(h.captures[1].closed, false);
++});
++
++test('late audio initialization cannot connect a retired microphone or close successor audio', async (t) => {
++ const gate = deferred();
++ const h = harness();
++ t.after(() => h.c.stop());
++ const createAudio = h.c.createAudio;
++ let first = true;
++ h.c.createAudio = (options) => {
++ const audio = createAudio(options);
++ if (first) {
++ first = false;
++ audio.initialize = () => gate.promise;
++ audio.connectMicrophone = () =>
++ assert.fail('retired initialization must not connect');
++ }
++ return audio;
++ };
++ const oldStart = h.c.start();
++ await tick();
++ h.c.stop();
++ await h.c.start();
++ gate.resolve();
++ await oldStart;
++ await tick();
++ assert.equal(h.c.status, 'listening');
++ assert.equal(h.captures[0].closed, true);
++ assert.equal(h.captures[1].closed, false);
++ assert.equal(h.tracks[0].readyState, 'ended');
++ assert.equal(h.tracks[1].readyState, 'live');
++});
diff --cc src/voice/geminiAudio.js
index 86f903316,000000000..3074923e5
mode 100644,000000..100644
--- a/src/voice/geminiAudio.js
+++ b/src/voice/geminiAudio.js
@@@ -1,375 -1,0 +1,380 @@@
++import { msg } from '../i18n/marker.js';
+const MAX_AUDIO_BYTES = 2 * 1024 * 1024;
+const MAX_QUEUED_SECONDS = 60;
+const MAX_QUEUED_SOURCES = 256;
+const PTT_WINDOW_SAMPLES = 160; // 10 ms at the worklet's fixed 16 kHz.
+const PTT_ENERGY_FLOOR = 0.002;
+const PTT_PRE_ROLL_BYTES = 16000 * 2 * 0.4;
+
+/** Admit manual input only after sustained energy; not an utterance detector. */
+function pttCapture(captureId) {
+ return {
+ captureId,
+ admitted: false,
+ buffers: [],
+ bytes: 0,
+ samples: 0,
+ energy: 0,
+ aboveFloor: 0,
+ voicedWindows: 0,
+ };
+}
+
+function hasPttEnergy(state, pcm) {
+ for (let index = 0; index + 1 < pcm.byteLength; index += 2) {
+ const sample = pcm.getInt16(index, true) / 32768;
+ state.energy += sample * sample;
+ if (Math.abs(sample) >= PTT_ENERGY_FLOOR) state.aboveFloor++;
+ if (++state.samples !== PTT_WINDOW_SAMPLES) continue;
+ // Requiring occupancy as well as RMS rejects isolated high-peak key clicks.
+ const voiced =
+ state.energy / state.samples >= PTT_ENERGY_FLOOR ** 2 &&
+ state.aboveFloor >= PTT_WINDOW_SAMPLES / 8;
+ state.voicedWindows = voiced ? state.voicedWindows + 1 : 0;
+ state.samples = state.energy = state.aboveFloor = 0;
+ if (state.voicedWindows >= 2) return true;
+ }
+ return false;
+}
+
+export function pcmBytesToBase64(buffer) {
+ const bytes = new Uint8Array(buffer);
+ let binary = '';
+ for (let offset = 0; offset < bytes.length; offset += 8192) {
+ binary += String.fromCharCode(...bytes.subarray(offset, offset + 8192));
+ }
+ return btoa(binary);
+}
+
+export function decodeGeminiPcm(data, mimeType = 'audio/pcm;rate=24000') {
+ if (
+ typeof data !== 'string' ||
+ data.length > 4 * Math.ceil(MAX_AUDIO_BYTES / 3)
+ )
- throw new Error('Gemini returned an oversized audio chunk');
++ throw new Error(msg('Gemini returned an oversized audio chunk'));
+ const match = /^audio\/pcm(?:;rate=(\d+))?$/.exec(mimeType);
- if (!match) throw new Error('Gemini returned an unsupported audio format');
++ if (!match)
++ throw new Error(msg('Gemini returned an unsupported audio format'));
+ const sampleRate = Number(match[1] || 24000);
+ if (!Number.isInteger(sampleRate) || sampleRate < 8000 || sampleRate > 96000)
- throw new Error('Gemini returned an invalid audio sample rate');
++ throw new Error(msg('Gemini returned an invalid audio sample rate'));
+ const binary = atob(data);
+ if (binary.length > MAX_AUDIO_BYTES)
- throw new Error('Gemini returned an oversized audio chunk');
++ throw new Error(msg('Gemini returned an oversized audio chunk'));
+ if (!binary.length || binary.length % 2)
- throw new Error('Gemini returned incomplete PCM audio');
++ throw new Error(msg('Gemini returned incomplete PCM audio'));
+ const bytes = new Uint8Array(binary.length);
+ for (let index = 0; index < binary.length; index++)
+ bytes[index] = binary.charCodeAt(index);
+ const view = new DataView(bytes.buffer);
+ const samples = new Float32Array(bytes.length / 2);
+ for (let index = 0; index < samples.length; index++)
+ samples[index] = view.getInt16(index * 2, true) / 32768;
+ return { samples, sampleRate };
+}
+
+/** Own capture and playback independently from the Live protocol. */
+export function createGeminiAudio({
+ pushToTalk = false,
+ onAudioStart,
+ onAudio,
+ onAudioEnd,
+ onAudioDiscard,
+ onDrain,
+ onError,
+ AudioContextClass = globalThis.AudioContext || globalThis.webkitAudioContext,
+ AudioWorkletNodeClass = globalThis.AudioWorkletNode,
+} = {}) {
+ if (!AudioContextClass || !AudioWorkletNodeClass)
- throw new Error('This browser does not support Gemini microphone audio');
++ throw new Error(
++ msg('This browser does not support Gemini microphone audio'),
++ );
+ let captureContext;
+ let playbackContext;
+ let output;
+ let meter;
+ let resumed;
+ const closeContext = (context) => {
+ try {
+ return Promise.resolve(context?.close());
+ } catch (error) {
+ return Promise.reject(error);
+ }
+ };
+ try {
+ // Capture at the device rate; the worklet explicitly resamples to 16 kHz.
+ captureContext = new AudioContextClass();
+ playbackContext = new AudioContextClass({ sampleRate: 24000 });
+ // Resume both synchronously within the mic gesture, before any awaits.
+ const resume = (context) => {
+ try {
+ return Promise.resolve(context.resume());
+ } catch (error) {
+ return Promise.reject(error);
+ }
+ };
+ resumed = Promise.all([resume(captureContext), resume(playbackContext)]);
+ // Permission may remain pending before initialize observes this failure.
+ void resumed.catch(() => {});
+ output = playbackContext.createGain();
+ meter = playbackContext.createMediaStreamDestination();
+ output.connect(playbackContext.destination);
+ output.connect(meter);
+ } catch (error) {
+ output?.disconnect();
+ meter?.disconnect();
+ meter?.stream.getTracks?.().forEach((track) => track.stop());
+ void Promise.allSettled([
+ closeContext(captureContext),
+ closeContext(playbackContext),
+ ]);
+ throw error;
+ }
+ let closed = false;
+ let closeResult;
+ let capture = null;
+ let microphone = null;
+ let mute = null;
+ let nextTime = 0;
+ let inputChunks = 0;
+ let inputPeak = 0;
+ let nonSilentInputChunks = 0;
+ let outputChunks = 0;
+ let outputSamples = 0;
+ let completedOutputSamples = 0;
+ let discardedOutputSamples = 0;
+ let pendingPtt = null;
+ let latestPttCaptureId = 0;
+ let suppressedPttCaptures = 0;
+ let admittedPttCaptures = 0;
+ const sources = new Map();
+
+ const emitAudio = (buffer, metadata) =>
+ onAudio?.(
+ { data: pcmBytesToBase64(buffer), mimeType: 'audio/pcm;rate=16000' },
+ metadata,
+ );
+
+ function clearPlayback() {
+ const oldSources = [...sources];
+ sources.clear();
+ nextTime = playbackContext.currentTime;
+ for (const [source, sampleCount] of oldSources) {
+ discardedOutputSamples += sampleCount;
+ source.onended = null;
+ try {
+ source.stop();
+ } catch {
+ /* Already ended. */
+ }
+ source.disconnect();
+ }
+ }
+
+ return {
+ outputStream: meter.stream,
+ get pending() {
+ return sources.size > 0;
+ },
+ async initialize(signal) {
+ try {
+ await Promise.all([
+ resumed,
+ captureContext.audioWorklet.addModule(
+ new URL('./geminiCaptureWorklet.js', import.meta.url),
+ ),
+ ]);
+ signal?.throwIfAborted();
+ if (closed) throw new DOMException('Voice stopped', 'AbortError');
+ } catch (error) {
+ await this.close();
+ throw error;
+ }
+ },
+ connectMicrophone(stream, enabled, metadata) {
+ if (closed) throw new DOMException('Voice stopped', 'AbortError');
+ capture = new AudioWorkletNodeClass(
+ captureContext,
+ 'gev-gemini-capture',
+ {
+ numberOfInputs: 1,
+ numberOfOutputs: 1,
+ outputChannelCount: [1],
+ },
+ );
+ capture.port.onmessage = ({ data }) => {
+ if (closed) return;
+ // Capture ownership is transport metadata, never part of Live audio.
+ if (!Number.isSafeInteger(data?.captureId) || data.captureId <= 0)
+ return;
+ const metadata = { captureId: data.captureId };
+ try {
+ if (data?.type === 'audio' && data.buffer instanceof ArrayBuffer) {
+ inputChunks++;
+ const pcm = new DataView(data.buffer);
+ let peak = 0;
+ for (let index = 0; index + 1 < pcm.byteLength; index += 2)
+ peak = Math.max(
+ peak,
+ Math.abs(pcm.getInt16(index, true)) / 32768,
+ );
+ inputPeak = Math.max(inputPeak, peak);
+ if (peak >= 0.01) nonSilentInputChunks++;
+ if (!pushToTalk) emitAudio(data.buffer, metadata);
+ else {
+ const state = pendingPtt;
+ if (state?.captureId !== data.captureId) return;
+ if (state.admitted) emitAudio(data.buffer, metadata);
+ else {
+ state.buffers.push(data.buffer);
+ state.bytes += data.buffer.byteLength;
+ if (hasPttEnergy(state, pcm)) {
+ state.admitted = true;
+ admittedPttCaptures++;
+ // Context and activityStart are gated together with PCM.
+ onAudioStart?.(metadata);
+ for (const buffer of state.buffers) {
+ if (closed || pendingPtt !== state) break;
+ emitAudio(buffer, metadata);
+ }
+ state.buffers = [];
+ state.bytes = 0;
+ } else {
+ while (state.bytes > PTT_PRE_ROLL_BYTES) {
+ state.bytes -= state.buffers.shift().byteLength;
+ }
+ }
+ }
+ }
+ } else if (data?.type === 'start') {
+ if (!pushToTalk) onAudioStart?.(metadata);
+ else if (data.captureId > latestPttCaptureId) {
+ latestPttCaptureId = data.captureId;
+ pendingPtt = pttCapture(data.captureId);
+ }
+ } else if (data?.type === 'end') {
+ if (!pushToTalk) onAudioEnd?.(metadata);
+ else if (pendingPtt?.captureId === data.captureId) {
+ const admitted = pendingPtt.admitted;
+ pendingPtt = null;
+ if (admitted) onAudioEnd?.(metadata);
+ else {
+ suppressedPttCaptures++;
+ onAudioDiscard?.(metadata);
+ }
+ }
+ }
+ } catch (error) {
+ onError?.(error);
+ }
+ };
+ capture.onprocessorerror = () => {
- if (!closed) onError?.(new Error('Microphone audio processing failed'));
++ if (!closed)
++ onError?.(new Error(msg('Microphone audio processing failed')));
+ };
+ microphone = captureContext.createMediaStreamSource(stream);
+ mute = captureContext.createGain();
+ mute.gain.value = 0;
+ capture.port.postMessage({
+ enabled: Boolean(enabled),
+ captureId: metadata?.captureId,
+ });
+ microphone.connect(capture);
+ capture.connect(mute);
+ mute.connect(captureContext.destination);
+ },
+ setMicrophoneEnabled(enabled, metadata) {
+ if (closed) return;
+ capture?.port.postMessage({
+ enabled: Boolean(enabled),
+ captureId: metadata?.captureId,
+ });
+ },
+ play(data, mimeType) {
+ if (closed) return;
+ // Tiny chunks can exhaust source nodes long before the duration limit.
+ if (sources.size >= MAX_QUEUED_SOURCES)
+ throw new Error(
- 'Gemini audio playback fell behind. Reconnect to continue.',
++ msg('Gemini audio playback fell behind. Reconnect to continue.'),
+ );
+ const { samples, sampleRate } = decodeGeminiPcm(data, mimeType);
+ const start = Math.max(playbackContext.currentTime + 0.02, nextTime);
+ if (
+ start + samples.length / sampleRate - playbackContext.currentTime >
+ MAX_QUEUED_SECONDS
+ )
+ throw new Error(
- 'Gemini audio playback fell behind. Reconnect to continue.',
++ msg('Gemini audio playback fell behind. Reconnect to continue.'),
+ );
+ const buffer = playbackContext.createBuffer(
+ 1,
+ samples.length,
+ sampleRate,
+ );
+ buffer.copyToChannel(samples, 0);
+ const source = playbackContext.createBufferSource();
+ source.buffer = buffer;
+ source.connect(output);
+ sources.set(source, samples.length);
+ source.onended = () => {
+ if (!sources.delete(source)) return;
+ completedOutputSamples += samples.length;
+ source.disconnect();
+ if (!closed && !sources.size) onDrain?.();
+ };
+ nextTime = start + buffer.duration;
+ outputChunks++;
+ outputSamples += samples.length;
+ source.start(start);
+ },
+ clearPlayback,
+ diagnostics() {
+ return {
+ inputChunks,
+ inputPeak,
+ nonSilentInputChunks,
+ outputChunks,
+ outputSamples,
+ completedOutputSamples,
+ discardedOutputSamples,
+ queuedSeconds: Math.max(0, nextTime - playbackContext.currentTime),
+ contextState:
+ captureContext.state === playbackContext.state
+ ? captureContext.state
+ : 'suspended',
+ captureContextState: captureContext.state,
+ playbackContextState: playbackContext.state,
+ captureSampleRate: captureContext.sampleRate,
+ playbackSampleRate: playbackContext.sampleRate,
+ inputSampleRate: 16000,
+ suppressedPttCaptures,
+ admittedPttCaptures,
+ pttBufferedBytes: pendingPtt?.bytes || 0,
+ };
+ },
+ close() {
+ if (closed) return closeResult;
+ closed = true;
+ pendingPtt = null;
+ clearPlayback();
+ if (capture) {
+ capture.port.onmessage = null;
+ capture.onprocessorerror = null;
+ capture.port.close();
+ capture.disconnect();
+ }
+ microphone?.disconnect();
+ mute?.disconnect();
+ output.disconnect();
+ meter.disconnect();
+ meter.stream.getTracks?.().forEach((track) => track.stop());
+ closeResult = Promise.allSettled([
+ closeContext(captureContext),
+ closeContext(playbackContext),
+ ]).then((results) =>
+ results.every((result) => result.status === 'fulfilled'),
+ );
+ return closeResult;
+ },
+ };
+}
diff --cc src/voice/geminiAudio.test.mjs
index 06c08fb4f,000000000..5ba719b32
mode 100644,000000..100644
--- a/src/voice/geminiAudio.test.mjs
+++ b/src/voice/geminiAudio.test.mjs
@@@ -1,1483 -1,0 +1,1134 @@@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import vm from 'node:vm';
- import { harness as sessionHarness, tick } from './geminiNativeHarness.mjs';
+import {
+ createGeminiAudio,
+ decodeGeminiPcm,
+ pcmBytesToBase64,
+} from './geminiAudio.js';
+
+test('PCM decoding preserves little-endian signed samples and rejects malformed audio', () => {
+ const data = new Uint8Array([0, 128, 0, 0, 255, 127]);
+ const decoded = decodeGeminiPcm(pcmBytesToBase64(data.buffer));
+ assert.equal(decoded.sampleRate, 24000);
+ assert.deepEqual([...decoded.samples], [-1, 0, 32767 / 32768]);
+ assert.throws(() => decodeGeminiPcm('AA=='), /incomplete/);
+ assert.throws(() => decodeGeminiPcm('AAAA', 'audio/mp3'), /unsupported/);
+ assert.throws(
+ () => decodeGeminiPcm('AAAA', 'audio/pcm;rate=1'),
+ /sample rate/,
+ );
+});
+
+test('PCM decoding accepts both rate endpoints and the exact decoded chunk limit', () => {
+ for (const rate of [8000, 96000]) {
+ const decoded = decodeGeminiPcm('AAA=', `audio/pcm;rate=${rate}`);
+ assert.equal(decoded.sampleRate, rate);
+ assert.deepEqual([...decoded.samples], [0]);
+ }
+ const limit = 2 * 1024 * 1024;
+ const maximum = decodeGeminiPcm(
+ pcmBytesToBase64(new ArrayBuffer(limit)),
+ 'audio/pcm;rate=96000',
+ );
+ assert.equal(maximum.samples.length, limit / 2);
+ for (const size of [limit + 1, limit + 2])
+ assert.throws(
+ () => decodeGeminiPcm(pcmBytesToBase64(new ArrayBuffer(size))),
+ /oversized audio chunk/,
+ );
+});
+
+function createCaptureHarness(sampleRate = 16000) {
+ let Processor;
+ const messages = [];
+ vm.runInNewContext(
+ fs.readFileSync(
+ new URL('./geminiCaptureWorklet.js', import.meta.url),
+ 'utf8',
+ ),
+ {
+ sampleRate,
+ AudioWorkletProcessor: class {
+ constructor() {
+ this.port = { postMessage: (message) => messages.push(message) };
+ }
+ },
+ registerProcessor: (_name, Class) => {
+ Processor = Class;
+ },
+ },
+ );
+ return { capture: new Processor(), messages };
+}
+
+test('worklet orders start, bounded PCM and the final partial chunk before end', () => {
+ const { capture, messages } = createCaptureHarness();
+ capture.process([[new Float32Array([-1, 0, 1])]]);
+ assert.equal(messages.length, 0);
+ capture.port.onmessage({ data: { enabled: true, captureId: 1 } });
+ capture.process([[new Float32Array([-1, 0, 1])]]);
+ capture.port.onmessage({ data: { enabled: false, captureId: 1 } });
+ assert.deepEqual(
+ messages.map((message) => message.type),
+ ['start', 'audio', 'end'],
+ );
+ const view = new DataView(messages[1].buffer);
+ assert.deepEqual(
+ [view.getInt16(0, true), view.getInt16(2, true), view.getInt16(4, true)],
+ [-32768, 0, 32767],
+ );
+ capture.process([[new Float32Array(2048)]]);
+ assert.equal(messages.length, 3);
+});
+
+test('worklet serializes rapid re-holds and ignores repeated enable or release', () => {
+ const { capture, messages } = createCaptureHarness();
+ let captureId = 0;
+ let gate = false;
+ const enable = (enabled) => {
+ if (enabled && !gate) captureId++;
+ gate = enabled;
+ capture.port.onmessage({ data: { enabled, captureId } });
+ };
+ enable(false);
+ enable(true);
+ enable(true);
+ capture.process([[new Float32Array(1025).fill(0.5)]]);
+ enable(false);
+ enable(false);
+ capture.process([[new Float32Array(2048).fill(1)]]);
+ enable(true);
+ capture.process([[new Float32Array([0.25])]]);
+ enable(false);
+ assert.deepEqual(
+ messages.map((message) => message.type),
+ ['start', 'audio', 'audio', 'end', 'start', 'audio', 'end'],
+ );
+ assert.deepEqual(
+ messages
+ .filter((message) => message.type === 'audio')
+ .map((message) => message.buffer.byteLength),
+ [2048, 2, 2],
+ );
+ assert.equal(new DataView(messages[5].buffer).getInt16(0, true), 8192);
+ assert.deepEqual(
+ messages.map((message) => message.captureId),
+ [1, 1, 1, 1, 2, 2, 2],
+ );
+ enable(true);
+ enable(false);
+ assert.deepEqual(
+ messages.slice(-2).map((message) => message.type),
+ ['start', 'end'],
+ );
+ assert.equal(capture.length, 0);
+ assert.equal(capture.enabled, false);
+});
+
+function createPlaybackHarness() {
+ const sources = [];
+ const buffers = [];
+ let drains = 0;
+ let context;
+ const contexts = [];
+ const node = () => ({
+ connect() {},
+ disconnect() {
+ this.disconnected = true;
+ },
+ gain: { value: 1 },
+ });
+ class Context {
+ constructor(options) {
+ context = this;
+ contexts.push(this);
+ this.options = options;
+ this.currentTime = 0;
+ this.sampleRate = options?.sampleRate ?? 48000;
+ this.state = 'running';
+ this.destination = {};
+ this.audioWorklet = { addModule: async () => {} };
+ }
+ async resume() {}
+ async close() {
+ this.state = 'closed';
+ }
+ createGain() {
+ return node();
+ }
+ createMediaStreamDestination() {
+ return { ...node(), stream: {} };
+ }
+ createBuffer(_channels, length, rate) {
+ const buffer = { duration: length / rate, copyToChannel() {} };
+ buffers.push(buffer);
+ return buffer;
+ }
+ createBufferSource() {
+ const source = {
+ ...node(),
+ start(at) {
+ this.at = at;
+ },
+ stop() {
+ this.stopped = true;
+ },
+ };
+ sources.push(source);
+ return source;
+ }
+ }
+ const audio = createGeminiAudio({
+ AudioContextClass: Context,
+ AudioWorkletNodeClass: class {},
+ onDrain: () => {
+ drains++;
+ },
+ });
+ return {
+ audio,
+ sources,
+ buffers,
+ contexts,
+ get drains() {
+ return drains;
+ },
+ get context() {
+ return context;
+ },
+ };
+}
+
+function outputDiagnostics(audio) {
+ const { outputSamples, completedOutputSamples, discardedOutputSamples } =
+ audio.diagnostics();
+ return { outputSamples, completedOutputSamples, discardedOutputSamples };
+}
+
+test('pending sources are capped before decoding or allocating and natural completion frees a slot', async (t) => {
+ const playback = createPlaybackHarness();
+ const { audio, sources, buffers } = playback;
+ t.after(() => audio.close());
+ const decode = t.mock.method(globalThis, 'atob', globalThis.atob);
+ await audio.initialize();
+ for (let index = 0; index < 256; index++)
+ audio.play('AAA=', 'audio/pcm;rate=96000');
+ assert.equal(audio.pending, true);
+ assert.ok(audio.diagnostics().queuedSeconds < 0.023);
+ assert.equal(decode.mock.calls.length, 256);
+ assert.equal(buffers.length, 256);
+ assert.equal(sources.length, 256);
+ const before = audio.diagnostics();
+ assert.throws(
+ () => audio.play('AAA=', 'audio/pcm;rate=96000'),
+ /Gemini audio playback fell behind\. Reconnect to continue\./,
+ );
+ assert.equal(decode.mock.calls.length, 256);
+ assert.equal(buffers.length, 256);
+ assert.equal(sources.length, 256);
+ assert.deepEqual(audio.diagnostics(), before);
+
+ const ended = sources[0].onended;
+ ended();
+ assert.equal(sources[0].disconnected, true);
+ assert.equal(playback.drains, 0);
+ audio.play('AAA=', 'audio/pcm;rate=96000');
+ assert.equal(decode.mock.calls.length, 257);
+ assert.equal(buffers.length, 257);
+ assert.equal(sources.length, 257);
+ ended();
+ assert.equal(audio.diagnostics().completedOutputSamples, 1);
+ assert.throws(() => audio.play('AAA='), /playback fell behind/);
+ assert.equal(decode.mock.calls.length, 257);
+});
+
+test('clearing and closing a full queue release every source and ignore late completion', async (t) => {
+ const playback = createPlaybackHarness();
+ const { audio, sources, buffers } = playback;
+ t.after(() => audio.close());
+ const decode = t.mock.method(globalThis, 'atob', globalThis.atob);
+ await audio.initialize();
+ for (let index = 0; index < 256; index++) audio.play('AAA=');
+ const staleEnded = sources.map((source) => source.onended);
+ audio.clearPlayback();
+ assert.equal(audio.pending, false);
+ assert.equal(audio.diagnostics().queuedSeconds, 0);
+ for (const source of sources) {
+ assert.equal(source.stopped, true);
+ assert.equal(source.disconnected, true);
+ assert.equal(source.onended, null);
+ }
+ for (let index = 0; index < 256; index++) audio.play('AAA=');
+ for (const ended of staleEnded) ended();
+ assert.equal(audio.pending, true);
+ assert.throws(() => audio.play('AAA='), /playback fell behind/);
+ assert.equal(decode.mock.calls.length, 512);
+ assert.equal(buffers.length, 512);
+ assert.equal(sources.length, 512);
+ const lateEnded = sources.slice(256).map((source) => source.onended);
+ await audio.close();
+ for (const source of sources) {
+ assert.equal(source.stopped, true);
+ assert.equal(source.disconnected, true);
+ assert.equal(source.onended, null);
+ }
+ for (const ended of [...staleEnded, ...lateEnded]) ended();
+ audio.play('not base64');
+ assert.equal(decode.mock.calls.length, 512);
+ assert.equal(buffers.length, 512);
+ assert.equal(sources.length, 512);
+ assert.equal(audio.pending, false);
+ assert.equal(playback.drains, 0);
+ assert.equal(playback.context.state, 'closed');
+ assert.deepEqual(outputDiagnostics(audio), {
+ outputSamples: 512,
+ completedOutputSamples: 0,
+ discardedOutputSamples: 512,
+ });
+});
+
+test('the duration limit still rejects long chunks below the source cap', async (t) => {
+ const playback = createPlaybackHarness();
+ const { audio, sources, buffers } = playback;
+ t.after(() => audio.close());
+ await audio.initialize();
+ const second = pcmBytesToBase64(new ArrayBuffer(16000));
+ for (let index = 0; index < 59; index++)
+ audio.play(second, 'audio/pcm;rate=8000');
+ assert.ok(Math.abs(audio.diagnostics().queuedSeconds - 59.02) < 1e-9);
+ assert.throws(
+ () => audio.play(second, 'audio/pcm;rate=8000'),
+ /playback fell behind/,
+ );
+ assert.equal(buffers.length, 59);
+ assert.equal(sources.length, 59);
+});
+
+test('audio playback records completed samples only as sources naturally end', async () => {
+ const playback = createPlaybackHarness();
+ const { audio, sources } = playback;
+ await audio.initialize();
+ audio.play('AAA=');
+ audio.play('AAA=');
+ assert.ok(sources[1].at > sources[0].at);
+ assert.deepEqual(outputDiagnostics(audio), {
+ outputSamples: 2,
+ completedOutputSamples: 0,
+ discardedOutputSamples: 0,
+ });
+ sources[0].onended();
+ assert.equal(playback.drains, 0);
+ assert.equal(audio.diagnostics().completedOutputSamples, 1);
+ sources[1].onended();
+ assert.equal(playback.drains, 1);
+ assert.equal(audio.pending, false);
+ assert.deepEqual(outputDiagnostics(audio), {
+ outputSamples: 2,
+ completedOutputSamples: 2,
+ discardedOutputSamples: 0,
+ });
+ await audio.close();
+ assert.equal(playback.context.state, 'closed');
+ assert.deepEqual(outputDiagnostics(audio), {
+ outputSamples: 2,
+ completedOutputSamples: 2,
+ discardedOutputSamples: 0,
+ });
+});
+
+test('interruption records queued samples as discarded and rejects stale ended callbacks', async () => {
+ const playback = createPlaybackHarness();
+ const { audio, sources } = playback;
+ await audio.initialize();
+ audio.play('AAA=');
+ audio.play(pcmBytesToBase64(new ArrayBuffer(4)));
+ sources[0].onended();
+ const staleEnded = sources[1].onended;
+ audio.clearPlayback();
+ assert.equal(sources[1].stopped, true);
+ assert.equal(sources[1].onended, null);
+ assert.equal(audio.pending, false);
+ assert.equal(audio.diagnostics().queuedSeconds, 0);
+ staleEnded();
+ audio.clearPlayback();
+ assert.equal(playback.drains, 0);
+ assert.deepEqual(outputDiagnostics(audio), {
+ outputSamples: 3,
+ completedOutputSamples: 1,
+ discardedOutputSamples: 2,
+ });
+ await audio.close();
+ assert.deepEqual(outputDiagnostics(audio), {
+ outputSamples: 3,
+ completedOutputSamples: 1,
+ discardedOutputSamples: 2,
+ });
+});
+
+test('closing queued playback cannot count stopped sources as completed audio', async () => {
+ const playback = createPlaybackHarness();
+ const { audio, sources } = playback;
+ await audio.initialize();
+ audio.play('AAA=');
+ audio.play(pcmBytesToBase64(new ArrayBuffer(4)));
+ const staleEnded = sources.map((source) => source.onended);
+ await audio.close();
+ for (const source of sources) {
+ assert.equal(source.stopped, true);
+ assert.equal(source.onended, null);
+ }
+ for (const ended of staleEnded) ended();
+ audio.play('AAA=');
+ await audio.close();
+ assert.equal(audio.pending, false);
+ assert.equal(playback.drains, 0);
+ assert.equal(audio.diagnostics().contextState, 'closed');
+ assert.equal(audio.diagnostics().queuedSeconds, 0);
+ assert.deepEqual(outputDiagnostics(audio), {
+ outputSamples: 3,
+ completedOutputSamples: 0,
+ discardedOutputSamples: 3,
+ });
+});
+
+test('capture diagnostics distinguish speech energy from silence without retaining audio', async () => {
+ let capture;
+ const emitted = [];
+ const order = [];
+ const identities = [];
+ const gates = [];
+ const node = () => ({ connect() {}, disconnect() {}, gain: { value: 1 } });
+ class Context {
+ constructor() {
+ this.currentTime = 0;
+ this.sampleRate = 16000;
+ this.state = 'running';
+ this.destination = {};
+ this.audioWorklet = { addModule: async () => {} };
+ }
+ async resume() {}
+ async close() {
+ this.state = 'closed';
+ }
+ createGain() {
+ return node();
+ }
+ createMediaStreamDestination() {
+ return { ...node(), stream: { getTracks: () => [] } };
+ }
+ createMediaStreamSource() {
+ return node();
+ }
+ }
+ class Worklet {
+ constructor() {
+ capture = this;
+ Object.assign(this, node());
+ this.port = {
+ postMessage(message) {
+ gates.push(message);
+ },
+ close() {},
+ };
+ }
+ }
+ const audio = createGeminiAudio({
+ AudioContextClass: Context,
+ AudioWorkletNodeClass: Worklet,
+ onAudioStart: (metadata) => {
+ identities.push(metadata.captureId);
+ order.push('start');
+ },
+ onAudio: (chunk, metadata) => {
+ identities.push(metadata.captureId);
+ emitted.push(chunk);
+ order.push('audio');
+ },
+ onAudioEnd: (metadata) => {
+ identities.push(metadata.captureId);
+ order.push('end');
+ },
+ });
+ await audio.initialize();
+ audio.connectMicrophone({}, true, { captureId: 11 });
+ const deliver = capture.port.onmessage;
+ deliver({ data: { type: 'start', captureId: 11 } });
+ capture.port.onmessage({
+ data: { type: 'audio', captureId: 11, buffer: new ArrayBuffer(4) },
+ });
+ const spoken = new ArrayBuffer(4);
+ new DataView(spoken).setInt16(0, 16384, true);
+ capture.port.onmessage({
+ data: { type: 'audio', captureId: 11, buffer: spoken },
+ });
+ deliver({ data: { type: 'end', captureId: 11 } });
+ assert.deepEqual(order, ['start', 'audio', 'audio', 'end']);
+ assert.deepEqual(identities, [11, 11, 11, 11]);
+ assert.deepEqual(gates, [{ enabled: true, captureId: 11 }]);
+ // Gate D does not relabel delayed B port messages.
+ audio.setMicrophoneEnabled(false, { captureId: 11 });
+ audio.setMicrophoneEnabled(true, { captureId: 12 });
+ deliver({ data: { type: 'start', captureId: 11 } });
+ deliver({ data: { type: 'audio', captureId: 11, buffer: spoken } });
+ deliver({ data: { type: 'end', captureId: 11 } });
+ assert.deepEqual(identities.slice(-3), [11, 11, 11]);
+ const count = order.length;
+ for (const captureId of [undefined, null, 0, -1, 1.5, '12', Infinity]) {
+ deliver({ data: { type: 'start', captureId } });
+ deliver({ data: { type: 'audio', captureId, buffer: spoken } });
+ deliver({ data: { type: 'end', captureId } });
+ }
+ assert.equal(order.length, count);
+ assert.equal(audio.diagnostics().inputChunks, 3);
+ assert.equal(audio.diagnostics().nonSilentInputChunks, 2);
+ assert.equal(audio.diagnostics().inputPeak, 0.5);
+ assert.equal(emitted.length, 3);
+ assert.equal(emitted[1].mimeType, 'audio/pcm;rate=16000');
+ assert.deepEqual(Object.keys(emitted[1]).sort(), ['data', 'mimeType']);
+ assert.equal(await audio.close(), true);
+ assert.equal(audio.diagnostics().contextState, 'closed');
+ deliver({ data: { type: 'start', captureId: 11 } });
+ deliver({ data: { type: 'audio', captureId: 11, buffer: spoken } });
+ deliver({ data: { type: 'end', captureId: 11 } });
+ assert.deepEqual(order, [
+ 'start',
+ 'audio',
+ 'audio',
+ 'end',
+ 'start',
+ 'audio',
+ 'end',
+ ]);
+});
+
+test('worklet rejects missing identity and stale release without changing the active capture', () => {
+ const { capture, messages } = createCaptureHarness();
+ for (const captureId of [undefined, null, 0, -1, 1.5, '1', Infinity])
+ capture.port.onmessage({ data: { enabled: true, captureId } });
+ capture.process([[new Float32Array([0.5])]]);
+ assert.equal(messages.length, 0);
+ capture.port.onmessage({ data: { enabled: true, captureId: 20 } });
+ capture.process([[new Float32Array([0.5])]]);
+ capture.port.onmessage({ data: { enabled: true, captureId: 21 } });
+ capture.port.onmessage({ data: { enabled: false, captureId: 19 } });
+ assert.equal(messages.length, 1);
+ capture.port.onmessage({ data: { enabled: false, captureId: 20 } });
+ assert.deepEqual(
+ messages.map((message) => [message.type, message.captureId]),
+ [
+ ['start', 20],
+ ['audio', 20],
+ ['end', 20],
+ ],
+ );
+ capture.port.onmessage({ data: { enabled: true, captureId: 21 } });
+ capture.port.onmessage({ data: { enabled: false, captureId: 20 } });
+ capture.process([[new Float32Array([0.25])]]);
+ capture.port.onmessage({ data: { enabled: false, captureId: 21 } });
+ assert.deepEqual(
+ messages.slice(3).map((message) => [message.type, message.captureId]),
+ [
+ ['start', 21],
+ ['audio', 21],
+ ['end', 21],
+ ],
+ );
+});
+
+function capturedPcm(messages, captureId) {
+ const samples = [];
+ for (const message of messages) {
+ if (message.type !== 'audio' || message.captureId !== captureId) continue;
+ const view = new DataView(message.buffer);
+ for (let index = 0; index < view.byteLength; index += 2)
+ samples.push(view.getInt16(index, true));
+ }
+ return samples;
+}
+
+function captureSignal(rate, signal, blockSizes = [128]) {
+ const harness = createCaptureHarness(rate);
+ harness.capture.port.onmessage({ data: { enabled: true, captureId: 1 } });
+ let block = 0;
+ for (let offset = 0; offset < signal.length;) {
+ const size = blockSizes[block++ % blockSizes.length];
+ harness.capture.process([[signal.subarray(offset, offset + size)]]);
+ offset += size;
+ }
+ harness.capture.port.onmessage({ data: { enabled: false, captureId: 1 } });
+ return { ...harness, pcm: capturedPcm(harness.messages, 1) };
+}
+
+for (const rate of [44100, 48000, 96000]) {
+ test(`worklet resamples ${rate} Hz to bounded 16 kHz PCM independently of block boundaries`, () => {
+ const signal = Float32Array.from(
+ { length: rate },
+ (_, index) => 0.5 * Math.sin((2 * Math.PI * 1000 * index) / rate),
+ );
+ const fragmented = captureSignal(rate, signal, [1, 127, 257, 3, 128]);
+ const contiguous = captureSignal(rate, signal, [rate]);
+ assert.equal(fragmented.pcm.length, 16000);
+ assert.deepEqual(fragmented.pcm, contiguous.pcm);
+ assert.deepEqual(
+ fragmented.messages.map((message) => message.type).slice(0, 2),
+ ['start', 'audio'],
+ );
+ assert.equal(fragmented.messages.at(-1).type, 'end');
+ assert.ok(fragmented.messages.every((message) => message.captureId === 1));
+ assert.ok(
+ fragmented.messages
+ .filter((message) => message.type === 'audio')
+ .every((message) => message.buffer.byteLength <= 2048),
+ );
+ const rms = Math.sqrt(
+ fragmented.pcm
+ .slice(256)
+ .reduce((total, sample) => total + (sample / 32768) ** 2, 0) /
+ (fragmented.pcm.length - 256),
+ );
+ assert.ok(
+ Math.abs(rms - Math.SQRT1_2 * 0.5) < 0.01,
+ `speech-band RMS ${rms}`,
+ );
+ // Check the actual waveform against its expected frequency and causal
+ // filter delay, rather than accepting any signal with the same energy.
+ const error = Math.sqrt(
+ fragmented.pcm.slice(256).reduce((total, sample, index) => {
+ const time = (index + 257) / 16000 - 32.5 / rate;
+ const expected = 0.5 * Math.sin(2 * Math.PI * 1000 * time);
+ return total + (sample / 32768 - expected) ** 2;
+ }, 0) /
+ (fragmented.pcm.length - 256),
+ );
+ assert.ok(error < 0.005, `resampled waveform error ${error}`);
+ });
+}
+
+for (const rate of [44100, 48000]) {
+ test(`worklet suppresses 12 kHz aliasing from a ${rate} Hz microphone`, () => {
+ const signal = Float32Array.from(
+ { length: rate },
+ (_, index) => 0.5 * Math.sin((2 * Math.PI * 12000 * index) / rate),
+ );
+ const { pcm } = captureSignal(rate, signal);
+ const rms = Math.sqrt(
+ pcm
+ .slice(256)
+ .reduce((total, sample) => total + (sample / 32768) ** 2, 0) /
+ (pcm.length - 256),
+ );
+ assert.ok(rms < 0.005, `out-of-band RMS ${rms}`);
+ });
+}
+
+test('resampler release flushes only owned PCM and clears phase/history before a successor', () => {
+ const { capture, messages } = createCaptureHarness(44100);
+ const gate = (enabled, captureId) =>
+ capture.port.onmessage({ data: { enabled, captureId } });
+ gate(true, 10);
+ capture.process([[new Float32Array(442).fill(1)]]);
+ gate(false, 9); // A stale release cannot clear the active filter or phase.
+ capture.process([[new Float32Array(441).fill(1)]]);
+ gate(false, 10);
+ assert.equal(
+ capturedPcm(messages, 10).length,
+ Math.floor((883 * 16000) / 44100),
+ );
+ gate(true, 11);
+ gate(false, 10);
+ capture.process([[new Float32Array(441)]]);
+ gate(false, 11);
+ const successor = capturedPcm(messages, 11);
+ assert.equal(successor.length, 160);
+ assert.ok(successor.every((sample) => sample === 0));
+ assert.deepEqual(
+ messages.slice(-3).map((message) => [message.type, message.captureId]),
+ [
+ ['start', 11],
+ ['audio', 11],
+ ['end', 11],
+ ],
+ );
+ // A sub-output-sample hold has no residual PCM or phase to transfer.
+ gate(true, 12);
+ capture.process([[new Float32Array([1])]]);
+ gate(false, 12);
+ gate(true, 13);
+ capture.process([[new Float32Array(441)]]);
+ gate(false, 13);
+ assert.deepEqual(capturedPcm(messages, 13), successor);
+ assert.deepEqual(
+ messages
+ .filter((message) => message.captureId === 12)
+ .map((message) => message.type),
+ ['start', 'end'],
+ );
+});
+
+function createContextLifecycleHarness({
+ resumeFailure,
+ moduleFailure = false,
+ closeFailure,
+ constructorFailure,
+ actualPlaybackRate = 24000,
+} = {}) {
+ const contexts = [];
+ const worklets = [];
+ const events = [];
+ let stoppedTracks = 0;
+ const node = (context) => ({
+ context,
+ gain: { value: 1 },
+ connections: [],
+ connect(target) {
+ this.connections.push(target);
+ },
+ disconnect() {
+ this.disconnected = true;
+ },
+ });
+ class Context {
+ constructor(options) {
+ const index = contexts.length;
+ if (constructorFailure === index)
+ throw new Error('context creation failed');
+ this.index = index;
+ this.options = options;
+ this.sampleRate = index === 0 ? 44100 : actualPlaybackRate;
+ this.currentTime = index === 0 ? 99 : 7;
+ this.state = 'suspended';
+ this.destination = { context: this };
+ this.nodes = [];
+ this.closeCalls = 0;
+ this.audioWorklet = {
+ addModule: async () => {
+ events.push(`module:${index}`);
+ if (moduleFailure) throw new Error('module failed');
+ },
+ };
+ contexts.push(this);
+ }
+ resume() {
+ events.push(`resume:${this.index}`);
+ if (resumeFailure === this.index) throw new Error('resume failed');
+ this.state = 'running';
+ return Promise.resolve();
+ }
+ close() {
+ this.closeCalls++;
+ events.push(`close:${this.index}`);
+ if (closeFailure === this.index) throw new Error('close failed');
+ this.state = 'closed';
+ return Promise.resolve();
+ }
+ createGain() {
+ const result = node(this);
+ this.nodes.push(result);
+ return result;
+ }
+ createMediaStreamDestination() {
+ const result = {
+ ...node(this),
+ stream: {
+ getTracks: () => [
+ {
+ stop: () => {
+ stoppedTracks++;
+ },
+ },
+ ],
+ },
+ };
+ this.nodes.push(result);
+ return result;
+ }
+ createMediaStreamSource() {
+ const result = node(this);
+ this.nodes.push(result);
+ return result;
+ }
+ createBuffer(_channels, length, rate) {
+ return {
+ context: this,
+ rate,
+ duration: length / rate,
+ copyToChannel() {},
+ };
+ }
+ createBufferSource() {
+ const result = {
+ ...node(this),
+ start(at) {
+ this.at = at;
+ },
+ stop() {
+ this.stopped = true;
+ },
+ };
+ this.nodes.push(result);
+ return result;
+ }
+ }
+ class Worklet {
+ constructor(context) {
+ Object.assign(this, node(context));
+ this.gates = [];
+ this.port = {
+ postMessage: (message) => this.gates.push(message),
+ close: () => {
+ this.portClosed = true;
+ },
+ };
+ worklets.push(this);
+ }
+ }
+ return {
+ contexts,
+ worklets,
+ events,
+ create: (callbacks = {}) =>
+ createGeminiAudio({
+ AudioContextClass: Context,
+ AudioWorkletNodeClass: Worklet,
+ ...callbacks,
+ }),
+ get stoppedTracks() {
+ return stoppedTracks;
+ },
+ };
+}
+
+test('capture uses the device context while playback owns its clock, stream and actual rate diagnostics', async () => {
+ const harness = createContextLifecycleHarness({ actualPlaybackRate: 48000 });
+ const chunks = [];
+ const errors = [];
+ const audio = harness.create({
+ onAudio: (chunk) => chunks.push(chunk),
+ onError: (error) => errors.push(error),
+ });
+ assert.deepEqual(harness.events, ['resume:0', 'resume:1']);
+ assert.equal(harness.contexts[0].options, undefined);
+ assert.deepEqual(harness.contexts[1].options, { sampleRate: 24000 });
+ await audio.initialize();
+ assert.deepEqual(harness.events, ['resume:0', 'resume:1', 'module:0']);
+ audio.connectMicrophone({}, true, { captureId: 5 });
+ const capture = harness.worklets[0];
+ assert.equal(capture.context, harness.contexts[0]);
+ assert.deepEqual(capture.gates, [{ enabled: true, captureId: 5 }]);
+ const staleError = capture.onprocessorerror;
+ capture.port.onmessage({
+ data: { type: 'audio', captureId: 5, buffer: new ArrayBuffer(4) },
+ });
+ assert.equal(chunks[0].mimeType, 'audio/pcm;rate=16000');
+ audio.play('AAA=');
+ const source = harness.contexts[1].nodes.find((item) => item.buffer);
+ assert.equal(source.context, harness.contexts[1]);
+ assert.equal(source.buffer.context, harness.contexts[1]);
+ assert.equal(source.buffer.rate, 24000);
+ assert.equal(source.at, 7.02);
+ assert.ok(audio.diagnostics().queuedSeconds < 0.021);
+ assert.equal(audio.diagnostics().captureSampleRate, 44100);
+ assert.equal(audio.diagnostics().playbackSampleRate, 48000);
+ assert.equal(audio.diagnostics().inputSampleRate, 16000);
+ assert.equal(audio.diagnostics().contextState, 'running');
+ harness.contexts[0].state = 'suspended';
+ assert.equal(audio.diagnostics().contextState, 'suspended');
+ const closing = audio.close();
+ assert.equal(audio.close(), closing);
+ assert.equal(await closing, true);
+ assert.ok(
+ harness.contexts.every(
+ (context) => context.state === 'closed' && context.closeCalls === 1,
+ ),
+ );
+ assert.equal(harness.stoppedTracks, 1);
+ assert.equal(capture.portClosed, true);
+ assert.equal(capture.disconnected, true);
+ assert.equal(capture.onprocessorerror, null);
+ assert.equal(source.stopped, true);
+ staleError();
+ audio.setMicrophoneEnabled(true, { captureId: 6 });
+ assert.equal(capture.gates.length, 1);
+ assert.deepEqual(errors, []);
+});
+
+for (const resumeFailure of [0, 1]) {
+ test(`resume failure in context ${resumeFailure} releases both contexts`, async () => {
+ const harness = createContextLifecycleHarness({ resumeFailure });
+ const audio = harness.create();
+ assert.deepEqual(harness.events, ['resume:0', 'resume:1']);
+ await assert.rejects(audio.initialize(), /resume failed/);
+ assert.ok(
+ harness.contexts.every(
+ (context) => context.state === 'closed' && context.closeCalls === 1,
+ ),
+ );
+ assert.equal(harness.stoppedTracks, 1);
+ assert.equal(await audio.close(), true);
+ });
+}
+
+test('module failure and aborted initialization release both capture and playback', async () => {
+ for (const moduleFailure of [true, false]) {
+ const harness = createContextLifecycleHarness({ moduleFailure });
+ const audio = harness.create();
+ const signal = moduleFailure ? undefined : AbortSignal.abort();
+ await assert.rejects(
+ audio.initialize(signal),
+ moduleFailure ? /module failed/ : { name: 'AbortError' },
+ );
+ assert.ok(
+ harness.contexts.every(
+ (context) => context.state === 'closed' && context.closeCalls === 1,
+ ),
+ );
+ assert.equal(harness.stoppedTracks, 1);
+ }
+});
+
+for (const closeFailure of [0, 1]) {
+ test(`context ${closeFailure} close failure does not prevent closing the other context`, async () => {
+ const harness = createContextLifecycleHarness({ closeFailure });
+ const audio = harness.create();
+ await audio.initialize();
+ const closing = audio.close();
+ assert.equal(audio.close(), closing);
+ assert.equal(await closing, false);
+ assert.ok(harness.contexts.every((context) => context.closeCalls === 1));
+ assert.equal(harness.contexts[1 - closeFailure].state, 'closed');
+ assert.equal(harness.stoppedTracks, 1);
+ });
+}
+
+test('partial context construction failure closes the previously acquired capture context', async () => {
+ const harness = createContextLifecycleHarness({ constructorFailure: 1 });
+ assert.throws(() => harness.create(), /context creation failed/);
+ assert.equal(harness.contexts.length, 1);
+ assert.equal(harness.contexts[0].closeCalls, 1);
+ assert.equal(harness.contexts[0].state, 'closed');
+});
+
+function admissionHarness({ pushToTalk = true, callbacks = {} } = {}) {
+ const events = [];
+ const worklets = [];
+ const node = () => ({ connect() {}, disconnect() {}, gain: { value: 1 } });
+ class Context {
+ constructor() {
+ this.sampleRate = 16000;
+ this.currentTime = 0;
+ this.state = 'running';
+ this.destination = {};
+ this.audioWorklet = { addModule: async () => {} };
+ }
+ async resume() {}
+ async close() {
+ this.state = 'closed';
+ }
+ createGain() {
+ return node();
+ }
+ createMediaStreamDestination() {
+ return { ...node(), stream: { getTracks: () => [] } };
+ }
+ createMediaStreamSource() {
+ return node();
+ }
+ createBuffer(_channels, samples, rate) {
+ return { duration: samples / rate, copyToChannel() {} };
+ }
+ createBufferSource() {
+ return { ...node(), start() {}, stop() {} };
+ }
+ }
+ class Worklet {
+ constructor() {
+ Object.assign(this, node());
+ worklets.push(this);
+ const { capture, messages } = createCaptureHarness();
+ this.processor = capture;
+ this.flush = () => {
+ for (const data of messages.splice(0)) {
+ // MessagePort structured cloning moves VM buffers into this realm.
+ if (data.buffer)
+ data.buffer = new Uint8Array(data.buffer).slice().buffer;
+ this.port.onmessage?.({ data });
+ }
+ };
+ this.port = {
+ postMessage: (data) => {
+ capture.port.onmessage({ data });
+ this.flush();
+ },
+ close() {},
+ };
+ }
+ feed(samples) {
+ this.processor.process([[samples]]);
+ this.flush();
+ }
+ }
+ const createAudio = (options) =>
+ createGeminiAudio({
+ ...options,
+ AudioContextClass: Context,
+ AudioWorkletNodeClass: Worklet,
+ });
+ const audio = createAudio({
+ pushToTalk,
+ onAudioStart: (metadata) => {
+ events.push({ type: 'start', ...metadata });
+ callbacks.onAudioStart?.(metadata);
+ },
+ onAudio: (chunk, metadata) => {
+ events.push({ type: 'audio', ...metadata, chunk });
+ callbacks.onAudio?.(chunk, metadata);
+ },
+ onAudioEnd: (metadata) => {
+ events.push({ type: 'end', ...metadata });
+ callbacks.onAudioEnd?.(metadata);
+ },
+ onAudioDiscard: (metadata) => {
+ events.push({ type: 'discard', ...metadata });
+ callbacks.onAudioDiscard?.(metadata);
+ },
+ onError: (error) => {
+ throw error;
+ },
+ });
+ return { audio, events, worklets, createAudio };
+}
+function tone(length, amplitude = 0.04) {
+ return Float32Array.from(
+ { length },
+ (_, i) => amplitude * Math.sin((i * 2 * Math.PI * 220) / 16000),
+ );
+}
+function emittedPcm(events) {
+ return events
+ .filter((e) => e.type === 'audio')
+ .flatMap((e) => {
+ const bytes = Uint8Array.from(atob(e.chunk.data), (c) => c.charCodeAt(0));
+ const view = new DataView(bytes.buffer);
+ return Array.from({ length: bytes.length / 2 }, (_, i) =>
+ view.getInt16(i * 2, true),
+ );
+ });
+}
+
+test('PTT admission suppresses zero and near-silent captures without protocol callbacks', async (t) => {
+ const h = admissionHarness();
+ t.after(() => h.audio.close());
+ await h.audio.initialize();
+ h.audio.connectMicrophone({}, true, { captureId: 1 });
+ h.worklets[0].feed(new Float32Array(1024));
+ h.worklets[0].feed(tone(320, 0.00018));
+ h.audio.setMicrophoneEnabled(false, { captureId: 1 });
+ assert.deepEqual(h.events, [{ type: 'discard', captureId: 1 }]);
+ assert.equal(h.audio.diagnostics().suppressedPttCaptures, 1);
+ assert.equal(h.audio.diagnostics().pttBufferedBytes, 0);
+});
+
+test('PTT admission rejects isolated high-peak clicks across packet boundaries', async (t) => {
+ const h = admissionHarness();
+ t.after(() => h.audio.close());
+ await h.audio.initialize();
+ h.audio.connectMicrophone({}, true, { captureId: 1 });
+ const click = new Float32Array(1024);
+ click[159] = 1;
+ click[160] = -1;
+ h.worklets[0].feed(click);
+ h.audio.setMicrophoneEnabled(false, { captureId: 1 });
+ assert.deepEqual(
+ h.events.map((e) => e.type),
+ ['discard'],
+ );
+});
+
+test('PTT admission preserves quiet short speech and final partial release in exact order', async (t) => {
+ const h = admissionHarness();
+ t.after(() => h.audio.close());
+ await h.audio.initialize();
+ h.audio.connectMicrophone({}, true, { captureId: 1 });
+ const prefix = new Float32Array(73);
+ const speech = tone(640, 0.005);
+ const tail = new Float32Array(57);
+ h.worklets[0].feed(prefix);
+ h.worklets[0].feed(speech);
+ h.worklets[0].feed(tail);
+ assert.equal(h.events.length, 0, 'worklet still owns its incomplete packet');
+ h.audio.setMicrophoneEnabled(false, { captureId: 1 });
+ assert.deepEqual(
+ h.events.map((e) => e.type),
+ ['start', 'audio', 'end'],
+ );
+ const expected = [...prefix, ...speech, ...tail].map(
+ (v) => Math.round(v * (v < 0 ? 32768 : 32767)) || 0,
+ );
+ assert.deepEqual(emittedPcm(h.events), expected);
+});
+
+test('PTT admission bounds a long silent preroll and never regates voiced tails', async (t) => {
+ const h = admissionHarness();
+ t.after(() => h.audio.close());
+ await h.audio.initialize();
+ h.audio.connectMicrophone({}, true, { captureId: 1 });
+ for (let i = 0; i < 200; i++) {
+ h.worklets[0].feed(new Float32Array(1024));
+ assert.ok(h.audio.diagnostics().pttBufferedBytes <= 12800);
+ }
+ assert.equal(h.events.length, 0);
+ h.worklets[0].feed(tone(1024));
+ h.worklets[0].feed(new Float32Array(1024));
+ h.audio.setMicrophoneEnabled(false, { captureId: 1 });
+ assert.equal(h.events[0].type, 'start');
+ assert.equal(h.events.at(-1).type, 'end');
+ assert.equal(h.events.filter((e) => e.type === 'start').length, 1);
+ const pcm = emittedPcm(h.events);
+ assert.ok(pcm.length <= 9 * 1024);
+ assert.deepEqual(pcm.slice(-1024), new Array(1024).fill(0));
+ assert.equal(h.audio.diagnostics().admittedPttCaptures, 1);
+});
+
+test('PTT admission isolates repeated holds, stale identities and close callbacks', async (t) => {
+ const h = admissionHarness();
+ t.after(() => h.audio.close());
+ await h.audio.initialize();
+ h.audio.connectMicrophone({}, true, { captureId: 1 });
+ h.worklets[0].feed(tone(160));
+ h.audio.setMicrophoneEnabled(false, { captureId: 1 });
+ h.audio.setMicrophoneEnabled(true, { captureId: 2 });
+ const deliver = h.worklets[0].port.onmessage;
+ deliver({
+ data: { type: 'audio', captureId: 1, buffer: new ArrayBuffer(2048) },
+ });
+ deliver({ data: { type: 'end', captureId: 1 } });
+ h.worklets[0].feed(tone(160));
+ h.audio.setMicrophoneEnabled(false, { captureId: 2 });
+ assert.deepEqual(
+ h.events.map((e) => e.type),
+ ['discard', 'discard'],
+ );
+ h.audio.setMicrophoneEnabled(true, { captureId: 3 });
+ h.worklets[0].feed(new Float32Array(1024));
+ await h.audio.close();
+ deliver({ data: { type: 'audio', captureId: 3, buffer: tone(1024).buffer } });
+ deliver({ data: { type: 'end', captureId: 3 } });
+ assert.equal(h.events.length, 2);
+ assert.equal(h.audio.diagnostics().pttBufferedBytes, 0);
+});
+
+test('PTT admission leaves open-mic start, silence, PCM and end unchanged', async (t) => {
+ const h = admissionHarness({ pushToTalk: false });
+ t.after(() => h.audio.close());
+ await h.audio.initialize();
+ h.audio.connectMicrophone({}, true, { captureId: 1 });
+ h.worklets[0].feed(new Float32Array(1024));
+ h.audio.setMicrophoneEnabled(false, { captureId: 1 });
+ assert.deepEqual(
+ h.events.map((e) => e.type),
+ ['start', 'audio', 'end'],
+ );
+ assert.deepEqual(emittedPcm(h.events), new Array(1024).fill(0));
+});
-
- async function realAdapterSession(t, overrides = {}) {
- const a = admissionHarness();
- await a.audio.close(); // Only the controller-owned adapter remains live below.
- const h = sessionHarness({ createAudio: a.createAudio, ...overrides });
- t.after(() => h.c.stop());
- await h.c.start({ pushToTalk: true });
- return { ...h, worklet: a.worklets[0] };
- }
-
- test('silent PTT actual-controller integration sends no activity/context/PCM and releases pending state', async (t) => {
- const h = await realAdapterSession(t);
- const ws = h.sockets[0];
- const before = ws.sent.length;
- h.c.input.pushToTalkKeyHeld = true;
- h.c.input.setMicrophoneEnabled(true);
- h.worklet.feed(new Float32Array(1024));
- h.c.input.pushToTalkKeyHeld = false;
- h.c.input.setMicrophoneEnabled(false);
- assert.equal(ws.sent.length, before);
- assert.equal(h.c.userTurnPending, false);
- assert.equal(h.c.replyPending, false);
- assert.equal(h.c.forwardedActivityOpen, false);
- assert.equal(h.c.audio.diagnostics().suppressedPttCaptures, 1);
- assert.equal(h.c.status, 'listening');
- });
-
- test('silent PTT during native playback retains local interruption without creating a successor', async (t) => {
- const h = await realAdapterSession(t);
- const ws = h.sockets[0];
- ws.message({
- serverContent: {
- modelTurn: {
- parts: [
- { inlineData: { data: 'AAA=', mimeType: 'audio/pcm;rate=24000' } },
- ],
- },
- },
- });
- assert.equal(h.c.audio.pending, true);
- const before = ws.sent.length;
- assert.equal(h.c.input.bargeIn(), true);
- h.c.input.pushToTalkKeyHeld = true;
- h.c.input.setMicrophoneEnabled(true);
- h.worklet.feed(new Float32Array(1024));
- h.c.input.pushToTalkKeyHeld = false;
- h.c.input.setMicrophoneEnabled(false);
- assert.equal(ws.sent.length, before);
- assert.equal(h.c.audio.pending, false);
- assert.equal(h.c.userTurnPending, false);
- ws.message({ serverContent: { turnComplete: true } });
- h.advance(5001);
- await tick();
- assert.equal(h.c.retiredReplyPending, false);
- assert.equal(h.c.status, 'listening');
- assert.equal(h.timers.size, 0);
- });
-
- test('voiced PTT actual-controller integration submits one ordered activity and recovers after silence', async (t) => {
- const h = await realAdapterSession(t);
- const ws = h.sockets[0];
- for (const [samples, admitted] of [
- [new Float32Array(640), false],
- [tone(640, 0.005), true],
- ]) {
- h.c.input.pushToTalkKeyHeld = true;
- h.c.input.setMicrophoneEnabled(true);
- h.worklet.feed(samples);
- h.c.input.pushToTalkKeyHeld = false;
- h.c.input.setMicrophoneEnabled(false);
- if (!admitted) assert.equal(h.c.userTurnPending, false);
- }
- const frames = ws.sent
- .filter((m) => m.realtimeInput)
- .map((m) => Object.keys(m.realtimeInput)[0]);
- assert.deepEqual(frames, ['activityStart', 'audio', 'activityEnd']);
- assert.equal(h.c.replyPending, true);
- ws.message({
- toolCall: {
- functionCalls: [
- {
- id: 'after-silent',
- name: 'adjust_camera_zoom',
- args: { direction: 'out', amount: 'little' },
- },
- ],
- },
- });
- await h.c.toolQueue;
- assert.equal(h.calls.length, 1);
- ws.message({ serverContent: { turnComplete: true } });
- assert.equal(h.c.userTurnPending, false);
- });
-
- test('silent PTT discard cannot clear a newer typed request', async (t) => {
- const h = await realAdapterSession(t);
- h.c.input.pushToTalkKeyHeld = true;
- h.c.input.setMicrophoneEnabled(true);
- h.worklet.feed(new Float32Array(1024));
- h.c.sendTextCommand('zoom out a little');
- const typed = h.c.readTypedTurnInput();
- h.c.input.pushToTalkKeyHeld = false;
- h.c.input.setMicrophoneEnabled(false);
- assert.equal(h.c.userTurnPending, true);
- assert.equal(h.c.readTypedTurnInput(), typed);
- assert.equal(h.c.replyPending, true);
- });
-
- // A physical hold alone cannot retire a provider tool request: without admitted
- // speech there is no native activity boundary to cancel that request.
- test('silent physical PTT preserves old tool completion without a retired-boundary timeout', async (t) => {
- const h = await realAdapterSession(t),
- ws = h.sockets[0];
- h.c.input.pushToTalkKeyHeld = true;
- h.c.input.setMicrophoneEnabled(true);
- h.worklet.feed(tone(640, 0.005));
- h.c.input.pushToTalkKeyHeld = false;
- h.c.input.setMicrophoneEnabled(false);
- const before = ws.sent.length,
- turn = h.c.turn;
- assert.equal(h.c.input.bargeIn(), true);
- h.c.input.pushToTalkKeyHeld = true;
- h.c.input.setMicrophoneEnabled(true);
- h.worklet.feed(new Float32Array(1024));
- h.c.input.pushToTalkKeyHeld = false;
- h.c.input.setMicrophoneEnabled(false);
- ws.message({
- toolCall: {
- functionCalls: [
- {
- id: 'after-empty-hold',
- name: 'adjust_camera_zoom',
- args: { direction: 'out', amount: 'little' },
- },
- ],
- },
- });
- await h.c.toolQueue;
- assert.equal(h.c.turn, turn);
- assert.equal(h.calls.length, 1);
- assert.equal(ws.sent.slice(before).filter((m) => m.toolResponse).length, 1);
- assert.equal(
- ws.sent.slice(before).some((m) => m.realtimeInput || m.clientContent),
- false,
- );
- h.advance(5001);
- await tick();
- assert.equal(h.c.status, 'listening');
- assert.equal(h.c.retiredReplyPending, false);
- ws.message({ serverContent: { turnComplete: true } });
- assert.equal(h.c.replyPending, false);
- assert.equal(h.timers.size, 0);
- });
-
- test('silent physical PTT does not supersede an earlier typed request', async (t) => {
- const h = await realAdapterSession(t);
- h.c.sendTextCommand('zoom out a little');
- const typed = h.c.readTypedTurnInput(),
- turn = h.c.turn;
- h.c.input.bargeIn();
- h.c.input.pushToTalkKeyHeld = true;
- h.c.input.setMicrophoneEnabled(true);
- h.worklet.feed(new Float32Array(640));
- h.c.input.pushToTalkKeyHeld = false;
- h.c.input.setMicrophoneEnabled(false);
- assert.equal(h.c.turn, turn);
- assert.equal(h.c.readTypedTurnInput(), typed);
- assert.equal(h.c.userTurnPending, true);
- assert.equal(h.c.replyPending, true);
- h.advance(5001);
- await tick();
- assert.equal(h.c.status, 'listening');
- });
-
- test('admitted physical PTT retires older input only at sustained energy', async (t) => {
- const h = await realAdapterSession(t),
- ws = h.sockets[0];
- h.c.sendTextCommand('zoom out a little');
- const turn = h.c.turn;
- h.c.input.bargeIn();
- h.c.input.pushToTalkKeyHeld = true;
- h.c.input.setMicrophoneEnabled(true);
- h.worklet.feed(new Float32Array(1024));
- assert.equal(h.c.turn, turn);
- h.worklet.feed(tone(1024, 0.005));
- assert.equal(h.c.turn, turn + 1);
- assert.equal(h.c.readTypedTurnInput(), undefined);
- assert.equal(h.c.retiredReplyPending, true);
- h.c.input.pushToTalkKeyHeld = false;
- h.c.input.setMicrophoneEnabled(false);
- assert.equal(ws.sent.filter((m) => m.realtimeInput?.activityStart).length, 1);
- ws.message({ serverContent: { interrupted: true, turnComplete: true } });
- assert.equal(h.c.retiredReplyPending, false);
- });
-
- test('rejected admitted PTT start fails closed instead of stranding a pending turn', async (t) => {
- const h = await realAdapterSession(t),
- ws = h.sockets[0];
- h.c.input.pushToTalkKeyHeld = true;
- h.c.input.setMicrophoneEnabled(true);
- ws.readyState = 0;
- h.worklet.feed(tone(1024, 0.005));
- await tick();
- assert.equal(h.c.status, 'error');
- assert.equal(h.c.userTurnPending, false);
- assert.equal(h.c.replyPending, false);
- assert.equal(ws.closed, true);
- });
-
- test('a silent physical hold cannot replace the current tool pointer; admitted released speech uses its owned snapshot', async (t) => {
- const { createPointerTracker } = await import('./pointerContext.js');
- let clock = 0;
- const pointer = createPointerTracker({
- element: { clientWidth: 1000, clientHeight: 500, addEventListener() {} },
- pick: (x, y) => ({ ground: { lat: x / 10, lon: y / 10, heightM: 0 } }),
- now: () => clock,
- setTimer: () => 0,
- clearTimer() {},
- });
- const h = await realAdapterSession(t, { pointer });
- pointer.moveTo(100, 100);
- const old = pointer.beginTurn('text');
- pointer.moveTo(200, 200);
- h.c.input.holdPointer();
- h.c.input.beginPointerTurn('keydown');
- h.c.input.pushToTalkKeyHeld = true;
- h.c.input.setMicrophoneEnabled(true);
- assert.equal(pointer.activeSnapshot(), old);
- h.worklet.feed(new Float32Array(640));
- h.c.input.pushToTalkKeyHeld = false;
- h.c.input.setMicrophoneEnabled(false);
- h.c.input.releasePointerHold();
- assert.equal(pointer.activeSnapshot(), old);
- pointer.moveTo(300, 250);
- h.c.input.holdPointer();
- h.c.input.beginPointerTurn('keydown');
- h.c.input.pushToTalkKeyHeld = true;
- h.c.input.setMicrophoneEnabled(true);
- h.worklet.feed(tone(640, 0.005));
- h.c.input.pushToTalkKeyHeld = false;
- h.c.input.releasePointerHold();
- h.c.input.setMicrophoneEnabled(false);
- assert.deepEqual(pointer.activeSnapshot().screenPx, { x: 300, y: 250 });
- const contexts = h.sockets[0].sent.filter((m) => m.clientContent);
- assert.equal(contexts.length, 1);
- assert.match(contexts[0].clientContent.turns[0].parts[0].text, /30/);
- });
-
- test('a typed reply completes while its superseded silent PTT hold is still open', async (t) => {
- const h = await realAdapterSession(t),
- ws = h.sockets[0];
- h.c.input.pushToTalkKeyHeld = true;
- h.c.input.setMicrophoneEnabled(true);
- h.worklet.feed(new Float32Array(640));
- h.c.sendTextCommand('zoom out a little');
- ws.message({ serverContent: { turnComplete: true } });
- assert.equal(h.events.filter((e) => e.type === 'completion').length, 1);
- h.c.input.pushToTalkKeyHeld = false;
- h.c.input.setMicrophoneEnabled(false);
- assert.equal(h.events.filter((e) => e.type === 'completion').length, 1);
- assert.equal(h.c.pendingCompletionStatus, null);
- });
-
- test('typed voice-off completion is not held behind a superseded silent capture', async (t) => {
- const h = await realAdapterSession(t),
- ws = h.sockets[0];
- h.c.input.pushToTalkKeyHeld = true;
- h.c.input.setMicrophoneEnabled(true);
- h.worklet.feed(new Float32Array(640));
- h.c.sendTextCommand('turn voice off');
- h.c.stopAfterReply = true;
- h.c.postToolOutput = true;
- ws.message({ serverContent: { turnComplete: true } });
- assert.equal(h.c.status, 'idle');
- assert.equal(ws.closed, true);
- });
-
- test('silent PTT release waits for asynchronous discard before presentation or Radio handoff', async (t) => {
- const h = await realAdapterSession(t),
- ws = h.sockets[0];
- h.c.input.pushToTalkKeyHeld = true;
- h.c.input.setMicrophoneEnabled(true);
- h.worklet.feed(new Float32Array(640));
- const deliver = h.worklet.port.onmessage,
- queued = [];
- h.worklet.port.onmessage = (e) => queued.push(e);
- h.c.input.pushToTalkKeyHeld = false;
- h.c.input.setMicrophoneEnabled(false);
- let handoffs = 0;
- h.c.radio.startPendingRadioHandoff = async () => {
- handoffs++;
- };
- h.c.radio.pendingRadioPlaybackResult = {
- ok: true,
- radioPlaybackRequested: true,
- };
- h.c.postToolOutput = true;
- ws.message({ serverContent: { turnComplete: true } });
- assert.equal(h.events.filter((e) => e.type === 'completion').length, 0);
- assert.equal(handoffs, 0);
- for (const e of queued) deliver(e);
- assert.equal(h.events.filter((e) => e.type === 'completion').length, 1);
- assert.equal(handoffs, 0);
- assert.equal(h.c.radio.pendingRadioPlaybackResult, null);
- });
-
- test('expiry cannot admit a voiced partial worklet tail or replace its pointer', async (t) => {
- const h = await realAdapterSession(t),
- ws = h.sockets[0];
- h.c.sendTextCommand('zoom out a little');
- h.c.input.pushToTalkKeyHeld = true;
- h.c.input.setMicrophoneEnabled(true);
- h.worklet.feed(tone(320, 0.005));
- const before = ws.sent.length;
- ws.message({ goAway: { timeLeft: '10s' } });
- assert.equal(ws.sent.length, before);
- assert.equal(h.c.forwardedActivityOpen, false);
- assert.equal(h.c.captureOwner.settled, true);
- assert.equal(h.c.captureOwner.admitted, false);
- });
-
- test('suppressed old native PCM is not reported as spoken after a silent claim', async (t) => {
- const h = await realAdapterSession(t),
- ws = h.sockets[0];
- h.c.sendTextCommand('zoom out a little');
- h.c.input.bargeIn();
- h.c.input.pushToTalkKeyHeld = true;
- h.c.input.setMicrophoneEnabled(true);
- h.worklet.feed(new Float32Array(640));
- h.c.input.pushToTalkKeyHeld = false;
- h.c.input.setMicrophoneEnabled(false);
- ws.message({
- serverContent: {
- modelTurn: {
- parts: [
- { inlineData: { data: 'AAA=', mimeType: 'audio/pcm;rate=24000' } },
- ],
- },
- },
- });
- assert.equal(h.c.audio.diagnostics().outputChunks, 0);
- assert.equal(h.c.modelSpoke, false);
- ws.message({ serverContent: { turnComplete: true } });
- assert.equal(
- h.events.filter((e) => e.type === 'completion').at(-1).spoken,
- false,
- );
- });
diff --cc src/voice/geminiAutomaticVad.test.mjs
index ae3849a2b,000000000..1a6f8af61
mode 100644,000000..100644
--- a/src/voice/geminiAutomaticVad.test.mjs
+++ b/src/voice/geminiAutomaticVad.test.mjs
@@@ -1,783 -1,0 +1,791 @@@
+// Native automatic activity, reply ownership and expiry lifecycle regressions.
+import test from 'node:test';
+import assert from 'node:assert/strict';
- import { harness, tick, deferred } from './geminiNativeHarness.mjs';
++import {
++ harness,
++ tick,
++ deferred,
++} from '../testSupport/geminiNativeHarness.mjs';
+const vad = (ws, type) => ws.message({ voiceActivity: { type } });
+const onset = (ws) => {
+ vad(ws, 'ACTIVITY_START');
+ vad(ws, 'ACTIVITY_END');
+};
+const split = (ws) => {
+ onset(ws);
+ onset(ws);
+};
+const audio = {
+ serverContent: {
+ modelTurn: {
+ parts: [
+ { inlineData: { data: 'AAAA', mimeType: 'audio/pcm;rate=24000' } },
+ ],
+ },
+ },
+};
+const done = (ws) => ws.message({ serverContent: { turnComplete: true } });
+const tools = (ws, id) =>
+ ws.message({
+ toolCall: {
+ functionCalls: [
+ {
+ id,
+ name: 'adjust_camera_zoom',
+ args: { direction: 'out', amount: 'little' },
+ },
+ ],
+ },
+ });
+const responses = (ws) =>
+ ws.sent.flatMap((m) => m.toolResponse?.functionResponses || []);
+function close(h) {
+ h.c.stop();
+ assert.equal(h.timers.size, 0, 'owned timers released');
+}
+test('N1 VAD-only split admits the first real answer and completes after playback', async () => {
+ const h = harness();
+ try {
+ await h.c.start();
+ const ws = h.sockets[0];
+ split(ws);
+ ws.message(audio);
+ ws.message({ serverContent: { outputTranscription: { text: 'Answer' } } });
+ done(ws);
+ assert.equal(h.captures[0].played.length, 1);
+ h.captures[0].drain();
+ assert.equal(
+ h.events.findLast((e) => e.type === 'completion')?.status,
+ 'completed',
+ );
+ assert.equal(h.c.retiredReplyPending, false);
+ } finally {
+ close(h);
+ }
+});
+test('N2 VAD-only split does not arm a nonexistent reply timeout', async () => {
+ const h = harness();
+ try {
+ await h.c.start();
+ split(h.sockets[0]);
+ h.advance(5001);
+ assert.equal(h.c.status, 'listening');
+ assert.equal(h.c.retiredReplyPending, false);
+ assert.equal(h.c.retiredBoundaryWait, null);
+ } finally {
+ close(h);
+ }
+});
+test('N3 server interruption before output still fences until ordered turnComplete', async () => {
+ const h = harness();
+ try {
+ await h.c.start();
+ const ws = h.sockets[0];
+ split(ws);
+ ws.message({ serverContent: { interrupted: true } });
+ assert.equal(h.c.retiredReplyPending, true);
+ ws.message(audio);
+ tools(ws, 'retired-before-boundary');
+ await h.c.toolQueue;
+ assert.equal(h.captures[0].played.length, 0);
+ assert.equal(h.calls.length, 0);
+ assert.equal(responses(ws).length, 0);
+ ws.message({
+ serverContent: { ...audio.serverContent, turnComplete: true },
+ });
+ assert.equal(
+ h.captures[0].played.length,
+ 0,
+ 'coalesced retired content is discarded',
+ );
+ ws.message(audio);
+ assert.equal(h.captures[0].played.length, 1);
+ done(ws);
+ h.captures[0].drain();
+ assert.equal(
+ h.events.findLast((e) => e.type === 'completion')?.status,
+ 'completed',
+ );
+ } finally {
+ close(h);
+ }
+});
+test('N4 generationComplete is server evidence and next onset retires it', async () => {
+ const h = harness();
+ try {
+ await h.c.start();
+ const ws = h.sockets[0];
+ onset(ws);
+ ws.message({ serverContent: { generationComplete: true } });
+ onset(ws);
+ assert.equal(h.c.retiredReplyPending, true);
+ assert.ok(h.c.retiredBoundaryWait);
+ ws.message(audio);
+ tools(ws, 'old-generation');
+ await h.c.toolQueue;
+ assert.equal(h.captures[0].played.length, 0);
+ assert.equal(h.calls.length, 0);
+ done(ws);
+ assert.equal(h.c.retiredReplyPending, false);
+ } finally {
+ close(h);
+ }
+});
+test('N5 goAway during VAD-only activity waits for actual reply and playback', async () => {
+ const h = harness();
+ try {
+ await h.c.start();
+ const ws = h.sockets[0];
+ split(ws);
+ ws.message({ goAway: { timeLeft: '30s' } });
+ assert.equal(h.c.isActive(), true);
+ assert.ok(h.c.goAway);
+ assert.equal(ws.closed, undefined);
+ h.advance(5001);
+ assert.equal(h.c.isActive(), true);
+ ws.message(audio);
+ done(ws);
+ assert.equal(
+ h.c.isActive(),
+ true,
+ 'pending actual PCM drains before expiry',
+ );
+ h.captures[0].drain();
+ assert.equal(h.c.status, 'error');
+ assert.equal(ws.closed, true);
+ } finally {
+ close(h);
+ }
+});
+test('N6 first server tool after VAD-only split executes exactly once', async () => {
+ const h = harness();
+ try {
+ await h.c.start();
+ const ws = h.sockets[0];
+ split(ws);
+ tools(ws, 'new-generation');
+ await h.c.toolQueue;
+ assert.equal(h.calls.length, 1);
+ assert.equal(
+ responses(ws).filter((x) => x.id === 'new-generation').length,
+ 1,
+ );
+ assert.equal(responses(ws).at(-1).response.ok, true);
+ tools(ws, 'new-generation');
+ await h.c.toolQueue;
+ assert.equal(h.calls.length, 1);
+ assert.equal(
+ responses(ws).filter((x) => x.id === 'new-generation').length,
+ 1,
+ );
+ } finally {
+ close(h);
+ }
+});
+test('C1 actual old audio followed by onset fences late audio and tool until boundary', async () => {
+ const h = harness();
+ try {
+ await h.c.start();
+ const ws = h.sockets[0];
+ ws.message(audio);
+ onset(ws);
+ assert.equal(h.c.retiredReplyPending, true);
+ ws.message(audio);
+ tools(ws, 'late-old');
+ await h.c.toolQueue;
+ assert.equal(h.captures[0].played.length, 1);
+ assert.equal(h.calls.length, 0);
+ ws.message({ serverContent: { interrupted: true } });
+ ws.message(audio);
+ assert.equal(h.captures[0].played.length, 1);
+ done(ws);
+ ws.message(audio);
+ assert.equal(h.captures[0].played.length, 2);
+ } finally {
+ close(h);
+ }
+});
+test('C2 first server tool in flight is aborted and never answered after new onset', async () => {
+ const gate = deferred(),
+ entered = [];
+ const h = harness({
+ runAction: async (_n, _a, o) => {
+ entered.push(o);
+ await gate.promise;
+ return { ok: true };
+ },
+ });
+ try {
+ await h.c.start();
+ const ws = h.sockets[0];
+ onset(ws);
+ tools(ws, 'old-running');
+ await tick();
+ assert.equal(entered.length, 1);
+ onset(ws);
+ assert.equal(entered[0].signal.aborted, true);
+ gate.resolve();
+ await h.c.toolQueue;
+ assert.equal(responses(ws).filter((x) => x.id === 'old-running').length, 0);
+ assert.equal(h.c.retiredReplyPending, true);
+ } finally {
+ gate.resolve();
+ close(h);
+ }
+});
+test('C5 typed request before first server output still retires on next onset', async () => {
+ const h = harness();
+ try {
+ await h.c.start();
+ const ws = h.sockets[0];
+ assert.equal(h.c.sendTextCommand('Zoom in'), true);
+ onset(ws);
+ assert.equal(h.c.retiredReplyPending, true);
+ ws.message(audio);
+ tools(ws, 'late-typed');
+ await h.c.toolQueue;
+ assert.equal(h.captures[0].played.length, 0);
+ assert.equal(h.calls.length, 0);
+ } finally {
+ close(h);
+ }
+});
+test('N7 old retired boundary preserves the newer automatic owner for goAway', async () => {
+ const h = harness();
+ try {
+ await h.c.start();
+ const ws = h.sockets[0];
+ onset(ws);
+ const oldOwner = h.c.automaticActivityOwner;
+ ws.message(audio);
+ onset(ws);
+ const successor = h.c.automaticActivityOwner;
+ assert.notEqual(successor, oldOwner);
+ assert.equal(h.c.retiredAutomaticActivityOwner, oldOwner);
+ ws.message({ serverContent: { interrupted: true, turnComplete: true } });
+ assert.equal(h.c.automaticActivityOwner, successor);
+ assert.equal(h.c.automaticTurnOpen, true);
+ ws.message({ goAway: { timeLeft: '30s' } });
+ assert.equal(h.c.isActive(), true);
+ ws.message(audio);
+ done(ws);
+ h.captures[0].drain();
+ assert.equal(h.c.status, 'error');
+ } finally {
+ close(h);
+ }
+});
+test('N8 old automatic owner with no successor is cleared by its retired boundary', async () => {
+ const h = harness();
+ try {
+ await h.c.start();
+ const ws = h.sockets[0];
+ onset(ws);
+ const owner = h.c.automaticActivityOwner;
+ ws.message(audio);
+ ws.message({ serverContent: { interrupted: true } });
+ assert.equal(h.c.retiredAutomaticActivityOwner, owner);
+ done(ws);
+ assert.equal(h.c.automaticTurnOpen, false);
+ assert.equal(h.c.automaticActivityOwner, null);
+ assert.equal(h.c.retiredAutomaticActivityOwner, null);
+ ws.message({ goAway: { timeLeft: '30s' } });
+ assert.equal(h.c.isActive(), false, 'no invented successor wait');
+ } finally {
+ close(h);
+ }
+});
+test('N9 coalesced old completion and new VAD preserves the new owner', async () => {
+ const h = harness();
+ try {
+ await h.c.start();
+ const ws = h.sockets[0];
+ onset(ws);
+ ws.message(audio);
+ vad(ws, 'ACTIVITY_END');
+ ws.message({
+ voiceActivity: { type: 'ACTIVITY_START' },
+ serverContent: { interrupted: true, turnComplete: true },
+ });
+ assert.equal(h.c.automaticTurnOpen, true);
+ assert.ok(h.c.automaticActivityOwner);
+ assert.equal(h.c.retiredAutomaticActivityOwner, null);
+ ws.message({ goAway: { timeLeft: '30s' } });
+ assert.equal(h.c.isActive(), true);
+ } finally {
+ close(h);
+ }
+});
+test('N10 stop, restart and destroy release automatic owner identities and timers', async () => {
+ const h = harness();
+ try {
+ await h.c.start();
+ onset(h.sockets[0]);
+ const first = h.c.automaticActivityOwner;
+ h.c.stop();
+ assert.equal(h.c.automaticTurnOpen, false);
+ assert.equal(h.c.automaticActivityOwner, null);
+ assert.equal(h.c.retiredAutomaticActivityOwner, null);
+ assert.equal(h.c.automaticActivitySequence, 0);
+ await h.c.start();
+ onset(h.sockets[1]);
+ assert.notEqual(h.c.automaticActivityOwner, first);
+ assert.notEqual(h.c.automaticActivityOwner.epoch, first.epoch);
+ h.c.stop({ removeUi: true });
+ assert.equal(h.c.disposed, true);
+ assert.equal(h.c.automaticTurnOpen, false);
+ assert.equal(h.c.automaticActivityOwner, null);
+ assert.equal(h.c.retiredAutomaticActivityOwner, null);
+ assert.equal(h.timers.size, 0);
+ } finally {
+ close(h);
+ }
+});
+test('N11 deferred typed ownership counts discarded open-mic PCM without queuing or replay', async () => {
+ const h = harness();
+ try {
+ await h.c.start();
+ const ws = h.sockets[0];
+ ws.message(audio);
+ assert.equal(h.c.sendTextCommand('Zoom in'), true);
+ assert.equal(h.c.sendTextCommand('Zoom out'), true);
+ assert.equal(h.c.deferredInput.kind, 'user-text');
+ const before = ws.sent.filter((x) => x.realtimeInput?.audio).length;
+ const metadata = { captureId: h.c.captureOwner.captureId };
+ h.captures[0].callbacks.onAudio(
+ { data: 'AAAA', mimeType: 'audio/pcm;rate=16000' },
+ metadata,
+ );
+ assert.equal(ws.sent.filter((x) => x.realtimeInput?.audio).length, before);
+ assert.equal(
+ h.c.deferredInput.messages.some((x) => x.realtimeInput?.audio),
+ false,
+ );
+ assert.equal(h.c.getDiagnostics().droppedAudioChunks, 1);
+ assert.deepEqual(h.c.getDiagnostics().deferredAudioDrops, {
+ nonPttOwner: 1,
+ closedActivity: 0,
+ });
+ ws.message({ serverContent: { interrupted: true, turnComplete: true } });
+ done(ws);
+ assert.equal(
+ ws.sent.filter((x) => x.realtimeInput?.audio).length,
+ before,
+ 'no wrong-owner PCM replay after boundaries',
+ );
+ } finally {
+ close(h);
+ }
+});
+test('N12 goAway before old completion still waits for the newer automatic owner', async () => {
+ const h = harness();
+ try {
+ await h.c.start();
+ const ws = h.sockets[0];
+ onset(ws);
+ ws.message(audio);
+ onset(ws);
+ const successor = h.c.automaticActivityOwner;
+ ws.message({ goAway: { timeLeft: '30s' } });
+ assert.equal(h.c.isActive(), true);
+ ws.message({ serverContent: { interrupted: true, turnComplete: true } });
+ assert.equal(h.c.automaticActivityOwner, successor);
+ assert.equal(
+ h.c.isActive(),
+ true,
+ 'old boundary during goAway cannot end successor wait',
+ );
+ ws.message(audio);
+ done(ws);
+ h.captures[0].drain();
+ assert.equal(h.c.status, 'error');
+ } finally {
+ close(h);
+ }
+});
+for (const interruptedBeforeExpiry of [false, true])
+ test(`N13 no successor clears retired ownership with goAway ${interruptedBeforeExpiry ? 'after interruption' : 'before interruption'}`, async () => {
+ const h = harness();
+ try {
+ await h.c.start();
+ const ws = h.sockets[0];
+ onset(ws);
+ ws.message(audio);
+ if (interruptedBeforeExpiry)
+ ws.message({ serverContent: { interrupted: true } });
+ ws.message({ goAway: { timeLeft: '30s' } });
+ assert.equal(h.c.isActive(), true);
+ ws.message({ serverContent: { interrupted: true, turnComplete: true } });
+ assert.equal(h.c.automaticTurnOpen, false);
+ assert.equal(h.c.automaticActivityOwner, null);
+ assert.equal(
+ h.c.isActive(),
+ false,
+ 'no successor finishes at its actual boundary',
+ );
+ } finally {
+ close(h);
+ }
+ });
+test('N14 native interruption during goAway aborts pending old tool and suppresses late response', async () => {
+ const gate = deferred(),
+ entered = [];
+ const h = harness({
+ runAction: async (_n, _a, o) => {
+ entered.push(o);
+ await gate.promise;
+ return { ok: true };
+ },
+ });
+ try {
+ await h.c.start();
+ const ws = h.sockets[0];
+ onset(ws);
+ tools(ws, 'expiring-old-tool');
+ await tick();
+ assert.equal(entered.length, 1);
+ ws.message({ goAway: { timeLeft: '30s' } });
+ assert.equal(h.c.isActive(), true);
+ ws.message({ serverContent: { interrupted: true, turnComplete: true } });
+ assert.equal(entered[0].signal.aborted, true);
+ gate.resolve();
+ await h.c.toolQueue;
+ assert.equal(
+ responses(ws).filter((x) => x.id === 'expiring-old-tool').length,
+ 0,
+ );
+ assert.equal(h.c.isActive(), false);
+ } finally {
+ gate.resolve();
+ close(h);
+ }
+});
+test('N15 goAway still refuses local PTT and typed replacement without reopening microphone', async () => {
+ const h = harness();
+ try {
+ await h.c.start();
+ const ws = h.sockets[0];
+ onset(ws);
+ ws.message(audio);
+ ws.message({ goAway: { timeLeft: '30s' } });
+ const turn = h.c.turn,
+ sent = ws.sent.length;
+ assert.equal(h.c.bargeIn(), false);
+ assert.equal(h.c.sendTextCommand('Zoom out'), false);
+ h.c.interrupt('push-to-talk');
+ assert.equal(h.c.turn, turn);
+ assert.equal(ws.sent.length, sent);
+ assert.equal(
+ h.tracks.every((t) => !t.enabled),
+ true,
+ );
+ ws.message({ serverContent: { interrupted: true, turnComplete: true } });
+ assert.equal(h.c.isActive(), false);
+ assert.equal(
+ h.tracks.every((t) => t.readyState === 'ended'),
+ true,
+ );
+ } finally {
+ close(h);
+ }
+});
+
+test('T-F1a PTT successor PCM survives retired boundary and a second input fences its late output', async () => {
+ const h = harness();
+ try {
+ await h.c.start({ pushToTalk: true });
+ const ws = h.sockets[0],
+ a = h.captures[0];
+ ws.message(audio);
+ h.c.input.pushToTalkKeyHeld = true;
+ assert.equal(h.c.input.bargeIn(), true);
+ h.c.input.setMicrophoneEnabled(true);
+ a.callbacks.onAudio(
+ { data: 'AAAB', mimeType: 'audio/pcm;rate=16000' },
+ a.metadata,
+ );
+ h.c.input.setMicrophoneEnabled(false);
+ assert.equal(h.c.replyPending, true);
+ ws.message({ serverContent: { interrupted: true, turnComplete: true } });
+ assert.equal(
+ h.c.replyPending,
+ true,
+ 'old boundary cannot clear submitted successor',
+ );
+ assert.equal(h.c.sendTextCommand('Zoom out second request'), true);
- assert.ok(h.c.readTypedTurnInput());
++ assert.ok(h.c.currentTypedInput());
+ const played = a.played.length;
+ ws.message(audio);
+ tools(ws, 'late-ptt-predecessor');
+ await h.c.toolQueue;
+ assert.equal(a.played.length, played);
- assert.equal(h.calls.length, 0, 'no old tool under newer typed userTurn');
++ assert.equal(
++ h.calls.length,
++ 0,
++ 'no old tool under newer local typed input',
++ );
+ done(ws);
+ tools(ws, 'current-typed');
+ await h.c.toolQueue;
+ assert.equal(h.calls.length, 1);
- assert.deepEqual(
- h.calls[0].options.userTurn,
- h.c.readTypedTurnInput(),
- 'actual runner receives current typed input',
- );
++ assert.equal(h.calls[0].options.userTurn, undefined);
++ assert.equal(h.calls[0].options.isCurrent(), true);
++ assert.equal(h.c.currentTypedInput().text, 'Zoom out second request');
+ } finally {
+ close(h);
+ }
+});
+for (const expiryBeforeBoundary of [false, true])
+ test(`T-F1b VAD then submitted text survives goAway ${expiryBeforeBoundary ? 'before' : 'after'} retired boundary`, async () => {
+ const h = harness();
+ try {
+ await h.c.start();
+ const ws = h.sockets[0];
+ ws.message(audio);
+ onset(ws);
+ assert.equal(h.c.sendTextCommand('Zoom out successor'), true);
- const typed = h.c.readTypedTurnInput();
++ const typed = h.c.currentTypedInput();
+ assert.ok(typed);
+ assert.equal(h.c.replyPending, true);
+ if (expiryBeforeBoundary) ws.message({ goAway: { timeLeft: '30s' } });
+ ws.message({ serverContent: { interrupted: true, turnComplete: true } });
+ assert.equal(h.c.replyPending, true);
+ if (!expiryBeforeBoundary) ws.message({ goAway: { timeLeft: '30s' } });
+ assert.equal(h.c.isActive(), true, 'submitted text must finish');
+ tools(ws, 'valid-successor');
+ await h.c.toolQueue;
+ assert.equal(h.calls.length, 1);
- assert.deepEqual(h.calls[0].options.userTurn, typed);
++ assert.equal(h.calls[0].options.userTurn, undefined);
++ assert.equal(h.calls[0].options.isCurrent(), true);
++ assert.equal(h.c.currentTypedInput(), typed);
+ ws.message(audio);
+ done(ws);
+ assert.equal(h.c.isActive(), true);
+ h.captures[0].drain();
+ assert.equal(h.c.isActive(), false);
+ } finally {
+ close(h);
+ }
+ });
+for (const repeat of [false, true])
+ test(`T-F2 forwarded A superseded by deferred B cannot run after goAway${repeat ? ' shortened twice' : ''}`, async () => {
+ const h = harness();
+ try {
+ await h.c.start();
+ const ws = h.sockets[0];
+ ws.message(audio);
+ assert.equal(h.c.sendTextCommand('Zoom out A'), true);
+ assert.equal(h.c.replyPending, true);
+ assert.equal(h.c.sendTextCommand('Zoom out B'), true);
+ assert.equal(h.c.deferredInput.kind, 'user-text');
- assert.ok(h.c.readTypedTurnInput());
++ assert.ok(h.c.currentTypedInput());
+ onset(ws);
+ assert.equal(h.c.automaticTurnOpen, true);
+ ws.message({ goAway: { timeLeft: '30s' } });
+ assert.equal(h.c.deferredInput, null);
+ if (repeat) {
+ ws.message({ goAway: { timeLeft: '20s' } });
+ ws.message({ goAway: { timeLeft: '10s' } });
+ }
+ assert.equal(h.c.goAway.supersededSuccessor, true);
+ assert.equal(h.c.isActive(), true);
+ ws.message({ serverContent: { interrupted: true, turnComplete: true } });
+ tools(ws, 'superseded-A');
+ await h.c.toolQueue;
+ assert.equal(h.calls.length, 0, 'A cannot run with dropped B authority');
+ assert.equal(
+ h.c.isActive(),
+ false,
+ 'ordered boundary closes superseded forwarded predecessor',
+ );
+ } finally {
+ close(h);
+ }
+ });
+test('T-F3 VAD-only no-generation expiry waits to bounded native deadline and releases resources', async () => {
+ const h = harness();
+ try {
+ await h.c.start();
+ onset(h.sockets[0]);
+ h.sockets[0].message({ goAway: { timeLeft: '30s' } });
+ h.advance(29999);
+ assert.equal(h.c.isActive(), true);
+ h.advance(1);
+ assert.equal(h.c.isActive(), false);
+ assert.equal(h.timers.size, 0);
+ assert.equal(
+ h.tracks.every((t) => t.readyState === 'ended'),
+ true,
+ );
+ } finally {
+ close(h);
+ }
+});
+test('T-C1 coalesced new START and natural old completion preserve newer automatic activity', async () => {
+ const h = harness();
+ try {
+ await h.c.start();
+ const ws = h.sockets[0];
+ onset(ws);
+ ws.message(audio);
+ ws.message({
+ voiceActivity: { type: 'ACTIVITY_START' },
+ serverContent: { turnComplete: true },
+ });
+ assert.equal(h.c.retiredReplyPending, false);
+ assert.equal(h.c.automaticTurnOpen, true);
+ ws.message({ goAway: { timeLeft: '30s' } });
+ assert.equal(h.c.isActive(), true);
+ } finally {
+ close(h);
+ }
+});
+test('T-C2 generationComplete alone followed by natural completion emits completion with no retirement timer', async () => {
+ const h = harness();
+ try {
+ await h.c.start();
+ const ws = h.sockets[0];
+ onset(ws);
+ ws.message({ serverContent: { generationComplete: true } });
+ assert.equal(h.c.replyPending, true);
+ done(ws);
+ assert.equal(
+ h.events.findLast((e) => e.type === 'completion')?.status,
+ 'completed',
+ );
+ assert.equal(h.c.replyPending, false);
+ assert.equal(h.c.automaticTurnOpen, false);
+ assert.equal(h.c.retiredBoundaryWait, null);
+ assert.equal(h.timers.size, 0);
+ } finally {
+ close(h);
+ }
+});
+
+test('T-C3 silent PTT terminal completion emits spoken false without fabricated audio', async () => {
+ const h = harness();
+ try {
+ await h.c.start({ pushToTalk: true });
+ const ws = h.sockets[0],
+ a = h.captures[0];
+ h.c.input.setMicrophoneEnabled(true);
+ a.callbacks.onAudio(
+ { data: 'AAAB', mimeType: 'audio/pcm;rate=16000' },
+ a.metadata,
+ );
+ h.c.input.setMicrophoneEnabled(false);
+ assert.equal(h.c.userTurnPending, true);
+ ws.message({ serverContent: { generationComplete: true } });
+ done(ws);
+ const event = h.events.findLast((e) => e.type === 'completion');
+ assert.equal(event.status, 'completed');
+ assert.equal(event.spoken, false);
+ assert.equal(a.played.length, 0);
+ assert.equal(h.c.userTurnPending, false);
+ } finally {
+ close(h);
+ }
+});
+test('T-C4 silent terminal boundary waits for pending tool and native follow-up completion', async () => {
+ const gate = deferred(),
+ entered = [];
+ const h = harness({
+ runAction: async (_n, _a, o) => {
+ entered.push(o);
+ await gate.promise;
+ return { ok: true };
+ },
+ });
+ try {
+ await h.c.start();
+ const ws = h.sockets[0];
+ onset(ws);
+ tools(ws, 'pending-terminal-tool');
+ await tick();
+ assert.equal(entered.length, 1);
+ done(ws);
+ assert.equal(
+ h.events.some((e) => e.type === 'completion'),
+ false,
+ );
+ assert.equal(h.c.userTurnPending, false);
+ gate.resolve();
+ await h.c.toolQueue;
+ h.c.finishPlayback();
+ assert.equal(
+ h.events.some((e) => e.type === 'completion'),
+ false,
+ );
+ assert.equal(h.c.replyPending, true, 'tool result awaits native follow-up');
+ done(ws);
+ assert.equal(
+ h.events.findLast((e) => e.type === 'completion')?.status,
+ 'completed',
+ );
+ } finally {
+ gate.resolve();
+ close(h);
+ }
+});
+test('T-C5 terminal boundary with queued PCM waits for drain and preserves real spoken state', async () => {
+ const h = harness();
+ try {
+ await h.c.start();
+ const ws = h.sockets[0];
+ onset(ws);
+ ws.message(audio);
+ ws.message({ serverContent: { generationComplete: true } });
+ done(ws);
+ assert.equal(
+ h.events.some((e) => e.type === 'completion'),
+ false,
+ );
+ h.captures[0].drain();
+ const event = h.events.findLast((e) => e.type === 'completion');
+ assert.equal(event.status, 'completed');
+ assert.equal(event.spoken, true);
+ } finally {
+ close(h);
+ }
+});
+test('T-C6 old retired terminal boundary cannot clear successor userTurnPending', async () => {
+ const h = harness();
+ try {
+ await h.c.start();
+ const ws = h.sockets[0];
+ ws.message(audio);
+ assert.equal(h.c.sendTextCommand('Zoom out successor'), true);
+ assert.equal(h.c.userTurnPending, true);
+ done(ws);
+ assert.equal(h.c.userTurnPending, true);
+ assert.equal(
+ h.events.some((e) => e.type === 'completion'),
+ false,
+ );
+ } finally {
+ close(h);
+ }
+});
+test('T-C7 reentrant silent completion observer keeps new input pending', async () => {
+ const h = harness();
+ try {
+ await h.c.start();
+ const ws = h.sockets[0];
+ const emit = h.c.emit.bind(h.c);
+ h.c.emit = (event) => {
+ emit(event);
+ if (event.type === 'completion')
+ h.c.sendTextCommand('Zoom out reentrant');
+ };
+ onset(ws);
+ ws.message({ serverContent: { generationComplete: true } });
+ done(ws);
+ assert.equal(h.events.filter((e) => e.type === 'completion').length, 1);
+ assert.equal(h.c.replyPending, true);
+ assert.equal(h.c.userTurnPending, true);
- assert.ok(h.c.readTypedTurnInput());
++ assert.ok(h.c.currentTypedInput());
+ assert.equal(h.c.modelComplete, false);
+ } finally {
+ close(h);
+ }
+});
diff --cc src/voice/geminiDeferredInput.test.mjs
index 000000000,000000000..e22c32e3d
new file mode 100644
--- /dev/null
+++ b/src/voice/geminiDeferredInput.test.mjs
@@@ -1,0 -1,0 +1,285 @@@
++import test from 'node:test';
++import assert from 'node:assert/strict';
++import {
++ nativeIntegrationFixture,
++ assertSuccessfulZoom,
++} from '../testSupport/geminiIntegrationFixture.mjs';
++
++const options = { concurrency: false, timeout: 5000 };
++const OLD_PCM = 'BAAFAA==';
++const TEXT = 'Zoom in for the owned typed successor';
++
++function exposeCapture(h) {
++ const createAudio = h.controller.createAudio;
++ h.controller.createAudio = (callbacks) => {
++ const audio = createAudio(callbacks);
++ audio.captureCallbacks = callbacks;
++ return audio;
++ };
++}
++
++async function startManual(h) {
++ await h.session.start({ pushToTalk: true });
++ assert.equal(h.session.state, 'listening');
++ assert.equal(h.controller.input.pushToTalkMode, true);
++ assert.equal(Boolean(h.controller.input.pushToTalkKeyHeld), false);
++ return h.sockets.at(-1);
++}
++
++// Explicit fake worklet callbacks retain the native physical-capture path;
++// this helper does not populate controller queues or ownership fields itself.
++function speakAndRelease(h, data) {
++ const c = h.controller;
++ const audio = h.audios.at(-1);
++ c.input.pushToTalkKeyHeld = true;
++ c.input.setMicrophoneEnabled(true);
++ const metadata = audio.metadata;
++ assert.ok(Number.isSafeInteger(metadata?.captureId));
++ audio.captureCallbacks.onAudioStart(metadata);
++ audio.captureCallbacks.onAudio(
++ { data, mimeType: 'audio/pcm;rate=16000' },
++ metadata,
++ );
++ c.input.pushToTalkKeyHeld = false;
++ c.input.setMicrophoneEnabled(false);
++ audio.captureCallbacks.onAudioEnd(metadata);
++ return metadata;
++}
++
++async function prepareDeferredPtt(h) {
++ exposeCapture(h);
++ const socket = await startManual(h);
++ speakAndRelease(h, 'AAABAA=='); // A is submitted and awaits its reply.
++ speakAndRelease(h, 'AgADAA=='); // B is submitted, retiring A.
++ const wireBeforeC = socket.sent.length;
++ const metadata = speakAndRelease(h, OLD_PCM); // C waits behind A's boundary.
++ const owner = h.controller.deferredInput;
++ assert.equal(owner?.kind, 'push-to-talk');
++ assert.equal(owner.captureId, metadata.captureId);
++ assert.equal(
++ socket.sent.length,
++ wireBeforeC,
++ 'C must still be wholly deferred',
++ );
++ assert.deepEqual(
++ owner.messages.map((message) =>
++ message.realtimeInput?.activityStart
++ ? 'start'
++ : message.realtimeInput?.audio
++ ? 'audio'
++ : message.realtimeInput?.activityEnd
++ ? 'end'
++ : 'other',
++ ),
++ ['start', 'audio', 'end'],
++ );
++ return { socket, owner, metadata };
++}
++
++async function assertHealthySuccessor(h, socket, callId) {
++ const beforeHeight = h.state.height;
++ await h.tool(callId, socket);
++ assertSuccessfulZoom(h, socket, callId, beforeHeight);
++ assert.equal(h.controller.pendingTools, 0);
++ h.complete(socket); // Native post-tool response boundary, with no output PCM.
++ assert.equal(h.controller.narration.state().tools, 0);
++ assert.equal(h.session.state, 'listening');
++}
++
++for (const mode of ['typed replacement', 'Stop', 'Stop+restart']) {
++ test(
++ `F04-5 deferred PTT flush loses its owner on ${mode}`,
++ options,
++ async (t) => {
++ const h = nativeIntegrationFixture(t);
++ const { socket: oldSocket, owner } = await prepareDeferredPtt(h);
++ const oldAudio = h.audios.at(-1);
++ let observed = 0;
++ let sentAtObserverReturn;
++ let restart;
++ let stateAtObserverReturn;
++ const unsubscribe = h.session.subscribe((event) => {
++ if (
++ event.type !== 'transcript' ||
++ event.role !== 'user' ||
++ event.text !== '' ||
++ observed
++ )
++ return;
++ observed++;
++ if (mode === 'typed replacement') {
++ assert.equal(h.session.sendText(TEXT), true);
++ } else {
++ h.session.stop();
++ if (mode === 'Stop+restart')
++ restart = h.session.start({ pushToTalk: true });
++ }
++ sentAtObserverReturn = oldSocket.sent.length;
++ stateAtObserverReturn = {
++ epoch: h.controller.epoch,
++ turn: h.controller.turn,
++ replyPending: h.controller.replyPending,
++ forwardedActivityOpen: h.controller.forwardedActivityOpen,
++ };
++ });
++ t.after(unsubscribe);
++
++ h.complete(oldSocket); // A's boundary starts flushing C. C's start emits.
++ assert.equal(
++ observed,
++ 1,
++ 'must enter the actual flush/onset observer boundary',
++ );
++ assert.ok(
++ stateAtObserverReturn,
++ 'observer must complete its replacement action',
++ );
++ assert.deepEqual(
++ oldSocket.sent.slice(sentAtObserverReturn),
++ [],
++ 'retired C must send neither queued PCM nor an extra end after the observer returns',
++ );
++ assert.deepEqual(
++ {
++ epoch: h.controller.epoch,
++ turn: h.controller.turn,
++ replyPending: h.controller.replyPending,
++ forwardedActivityOpen: h.controller.forwardedActivityOpen,
++ },
++ stateAtObserverReturn,
++ 'old flush must not write successor state',
++ );
++ assert.equal(h.controller.deferredInput, null);
++ assert.equal(
++ h.controller.typedIntent?.text ?? null,
++ mode === 'typed replacement' ? TEXT : null,
++ );
++
++ let successorSocket;
++ if (mode === 'typed replacement') {
++ assert.equal(h.controller.epoch, owner.epoch);
++ assert.notEqual(h.controller.turn, owner.turn);
++ assert.equal(
++ oldSocket.sent.some(
++ (message) => message.realtimeInput?.audio?.data === OLD_PCM,
++ ),
++ false,
++ );
++ const typedIndex = oldSocket.sent.findIndex((message) =>
++ message.clientContent?.turns?.some((turn) =>
++ turn.parts?.some((part) => part.text === TEXT),
++ ),
++ );
++ assert.ok(
++ typedIndex >= 0,
++ 'owned replacement must actually reach transport',
++ );
++ // The replacement legitimately closes the already-forwarded C start once.
++ assert.ok(oldSocket.sent[typedIndex - 1]?.realtimeInput?.activityEnd);
++ h.complete(oldSocket); // B's remaining retired boundary, deliberately separate.
++ assert.equal(h.controller.retiredReplyPending, false);
++ assert.equal(h.controller.replyPending, true);
++ successorSocket = oldSocket;
++ } else {
++ assert.equal(oldAudio.closed, true);
++ assert.equal(oldSocket.closed, true);
++ if (!restart) restart = h.session.start({ pushToTalk: true });
++ await restart;
++ successorSocket = h.sockets.at(-1);
++ assert.notEqual(successorSocket, oldSocket);
++ assert.equal(
++ successorSocket.sent.some((message) => message.realtimeInput?.audio),
++ false,
++ );
++ assert.equal(
++ successorSocket.sent.some(
++ (message) => message.realtimeInput?.activityEnd,
++ ),
++ false,
++ );
++ assert.equal(h.session.sendText(TEXT), true);
++ }
++ await assertHealthySuccessor(
++ h,
++ successorSocket,
++ `healthy-after-deferred-${mode}`,
++ );
++ },
++ );
++}
++
++test(
++ 'F04-5 deferred typed onSent cannot resurrect replyPending after Stop+restart',
++ options,
++ async (t) => {
++ const h = nativeIntegrationFixture(t);
++ const oldSocket = await h.start();
++ assert.equal(h.session.sendText('A'), true);
++ assert.equal(h.session.sendText('B'), true);
++ assert.equal(h.session.sendText('C deferred text'), true);
++ assert.equal(h.controller.deferredInput?.kind, 'user-text');
++ let restart;
++ let observed = 0;
++ const unsubscribe = h.session.subscribe((event) => {
++ if (
++ event.type !== 'transcript' ||
++ event.role !== 'user' ||
++ event.text !== 'C deferred text'
++ )
++ return;
++ observed++;
++ h.session.stop();
++ restart = h.session.start();
++ });
++ t.after(unsubscribe);
++ h.complete(oldSocket);
++ assert.equal(observed, 1);
++ assert.equal(
++ h.controller.replyPending,
++ false,
++ 'old onSent wrapper must not resurrect a stopped reply',
++ );
++ await restart;
++ assert.equal(h.controller.replyPending, false);
++ const socket = h.sockets.at(-1);
++ assert.equal(
++ socket.sent.length,
++ 1,
++ 'replacement connection should contain setup only',
++ );
++ assert.equal(h.session.sendText(TEXT), true);
++ await assertHealthySuccessor(h, socket, 'healthy-after-deferred-text');
++ },
++);
++
++test(
++ 'F04-5 ordinary deferred PTT flush preserves start, PCM and end exactly once',
++ options,
++ async (t) => {
++ const h = nativeIntegrationFixture(t);
++ const { socket } = await prepareDeferredPtt(h);
++ const before = socket.sent.length;
++ h.complete(socket);
++ assert.deepEqual(
++ socket.sent
++ .slice(before)
++ .map((message) =>
++ message.realtimeInput?.activityStart
++ ? 'start'
++ : message.realtimeInput?.audio?.data === OLD_PCM
++ ? 'audio'
++ : message.realtimeInput?.activityEnd
++ ? 'end'
++ : 'other',
++ ),
++ ['start', 'audio', 'end'],
++ );
++ assert.equal(h.controller.deferredInput, null);
++ assert.equal(h.controller.replyPending, true);
++ assert.equal(h.controller.retiredReplyPending, true);
++ h.complete(socket); // B's boundary; C remains the owned submitted input.
++ assert.equal(h.controller.retiredReplyPending, false);
++ assert.equal(h.controller.replyPending, true);
++ await assertHealthySuccessor(h, socket, 'healthy-ordinary-deferred');
++ },
++);
diff --cc src/voice/geminiIntegration.test.mjs
index 000000000,000000000..44c87b341
new file mode 100644
--- /dev/null
+++ b/src/voice/geminiIntegration.test.mjs
@@@ -1,0 -1,0 +1,287 @@@
++import test from 'node:test';
++import assert from 'node:assert/strict';
++import {
++ nativeIntegrationFixture,
++ assertSuccessfulZoom,
++ turnOfEventLoop,
++} from '../testSupport/geminiIntegrationFixture.mjs';
++
++const options = { concurrency: false, timeout: 5000 };
++const resultFor = (h, id) =>
++ h.events.filter(
++ (event) => event.type === 'action-result' && event.callId === id,
++ );
++const callFor = (h, id) =>
++ h.events.filter(
++ (event) => event.type === 'action-call' && event.callId === id,
++ );
++
++test(
++ 'native tool reaches actual common session and camera runner without a caption',
++ options,
++ async (t) => {
++ const h = nativeIntegrationFixture(t);
++ const ws = await h.start();
++ h.activity(ws); // Native activity is input framing, not transcript admission.
++ await h.tool('ordinary', ws);
++ assertSuccessfulZoom(h, ws, 'ordinary', 1000);
++ assert.equal(h.runnerCalls.length, 1);
++ assert.equal(h.runnerCalls[0].options.callId, 'ordinary');
++ assert.equal(h.runnerCalls[0].options.signal.aborted, false);
++ assert.equal(h.runnerCalls[0].options.isCurrent(), true);
++ h.complete(ws);
++ assert.equal(h.controller.narration.state().tools, 0);
++ assert.equal(h.controller.narration.state().pendingTimers, 0);
++ },
++);
++
++for (const cancellation of ['stop', 'native interruption']) {
++ test(
++ `${cancellation} discards a stale completed action result; successor changes camera once`,
++ options,
++ async (t) => {
++ const h = nativeIntegrationFixture(t);
++ const oldSocket = await h.start();
++ h.activity(oldSocket);
++ const gate = h.holdResult('old');
++ const oldDispatch = h.tool('old', oldSocket);
++ const committedResult = await gate.ready;
++ assert.equal(committedResult.ok, true);
++ assert.equal(
++ h.state.height,
++ 750,
++ 'the legitimate first action committed before cancellation',
++ );
++ assert.equal(callFor(h, 'old').length, 1);
++ assert.deepEqual(resultFor(h, 'old'), []);
++ assert.deepEqual(h.outputs(oldSocket), []);
++
++ if (cancellation === 'stop') h.session.stop();
++ else
++ oldSocket.message({
++ serverContent: { interrupted: true, turnComplete: true },
++ });
++ assert.equal(h.runnerCalls[0].options.signal.aborted, true);
++ assert.equal(h.runnerCalls[0].options.isCurrent(), false);
++ await oldDispatch; // Cancellation must settle before the held result returns.
++ gate.release();
++ await turnOfEventLoop();
++ assert.equal(
++ h.state.height,
++ 750,
++ 'settling a cancelled result adds no camera mutation',
++ );
++ assert.equal(h.state.zooms.length, 1);
++ assert.deepEqual(resultFor(h, 'old'), []);
++ assert.deepEqual(h.outputs(oldSocket), []);
++ if (cancellation === 'native interruption')
++ assert.ok(h.events.some((event) => event.type === 'interruption'));
++
++ const successorSocket =
++ cancellation === 'stop' ? await h.start() : oldSocket;
++ h.activity(successorSocket);
++ await h.tool('successor', successorSocket);
++ assertSuccessfulZoom(h, successorSocket, 'successor', 750);
++ assert.equal(h.state.zooms.length, 2);
++ assert.equal(h.runnerCalls.length, 2);
++ assert.equal(
++ h.outputs(successorSocket).some((output) => output.id === 'old'),
++ false,
++ );
++ h.complete(successorSocket);
++ },
++ );
++}
++
++for (const phase of ['common connecting', 'adapter connecting']) {
++ test(
++ `Stop from ${phase} observer prevents acquisition and permits fresh Start`,
++ options,
++ async (t) => {
++ const h = nativeIntegrationFixture(t);
++ let stopped = false;
++ const remove = h.session.subscribe((event) => {
++ const matchingDetail =
++ phase === 'common connecting'
++ ? event.detail === undefined
++ : typeof event.detail === 'string' && event.detail.length > 0;
++ if (
++ !stopped &&
++ event.type === 'state' &&
++ event.state === 'connecting' &&
++ matchingDetail
++ ) {
++ stopped = true;
++ h.session.stop();
++ }
++ });
++ await h.session.start();
++ remove();
++ assert.equal(
++ stopped,
++ true,
++ 'the chosen production observer boundary was exercised',
++ );
++ assert.deepEqual(h.acquisitions, {
++ microphone: 0,
++ audio: 0,
++ token: 0,
++ socket: 0,
++ });
++ assert.equal(h.session.state, 'idle');
++ assert.equal(h.controller.narration.state().tools, 0);
++ assert.equal(h.controller.narration.state().pendingTimers, 0);
++ assert.equal(h.clock.timers.size, 0);
++ const ws = await h.start();
++ h.activity(ws);
++ await h.tool('fresh-after-start-cancel', ws);
++ assertSuccessfulZoom(h, ws, 'fresh-after-start-cancel', 1000);
++ h.complete(ws);
++ },
++ );
++}
++
++test(
++ 'Stop from common action-call observer prevents runner and leaves no unhandled rejection',
++ options,
++ async (t) => {
++ const h = nativeIntegrationFixture(t);
++ const ws = await h.start();
++ const remove = h.session.subscribe((event) => {
++ if (event.type === 'action-call' && event.callId === 'cancel-at-call')
++ h.session.stop();
++ });
++ h.activity(ws);
++ await h.tool('cancel-at-call', ws);
++ // Do not install a swallowing process rejection listener. node:test records
++ // an unhandled rejection as a failure; these checkpoints let it surface here.
++ await turnOfEventLoop();
++ await turnOfEventLoop();
++ remove();
++ assert.equal(callFor(h, 'cancel-at-call').length, 1);
++ assert.deepEqual(resultFor(h, 'cancel-at-call'), []);
++ assert.equal(h.runnerCalls.length, 0);
++ assert.equal(h.state.height, 1000);
++ assert.deepEqual(h.outputs(ws), []);
++ assert.equal(h.controller.narration.state().tools, 0);
++ assert.equal(h.controller.narration.state().pendingTimers, 0);
++ assert.equal(h.clock.timers.size, 0);
++ const successor = await h.start();
++ h.activity(successor);
++ await h.tool('after-call-cancel', successor);
++ assertSuccessfulZoom(h, successor, 'after-call-cancel', 1000);
++ h.complete(successor);
++ },
++);
++
++test(
++ 'Stop from executing observer cannot recreate narration or dispatch the runner',
++ options,
++ async (t) => {
++ const h = nativeIntegrationFixture(t);
++ const ws = await h.start();
++ let stopped = false;
++ const remove = h.session.subscribe((event) => {
++ if (!stopped && event.type === 'state' && event.state === 'executing') {
++ stopped = true;
++ h.session.stop();
++ }
++ });
++ h.activity(ws);
++ await h.tool('cancel-at-executing', ws);
++ remove();
++ assert.equal(stopped, true);
++ assert.equal(h.runnerCalls.length, 0);
++ assert.deepEqual(callFor(h, 'cancel-at-executing'), []);
++ assert.deepEqual(resultFor(h, 'cancel-at-executing'), []);
++ assert.equal(h.state.height, 1000);
++ assert.deepEqual(h.outputs(ws), []);
++ assert.equal(h.controller.narration.state().tools, 0);
++ assert.equal(h.controller.narration.state().pendingTimers, 0);
++ assert.equal(h.clock.timers.size, 0);
++ assert.equal(ws.closed, true);
++ assert.ok(h.audios.every((audio) => audio.closed));
++ assert.ok(h.tracks.every((track) => track.readyState === 'ended'));
++ const before = {
++ events: h.events.length,
++ wire: ws.sent.length,
++ earcon: h.state.earconStarts,
++ };
++ h.clock.advance(60_000);
++ assert.deepEqual(
++ {
++ events: h.events.length,
++ wire: ws.sent.length,
++ earcon: h.state.earconStarts,
++ },
++ before,
++ );
++ const successor = await h.start();
++ h.activity(successor);
++ await h.tool('after-executing-cancel', successor);
++ assertSuccessfulZoom(h, successor, 'after-executing-cancel', 1000);
++ h.complete(successor);
++ },
++);
++
++test(
++ 'native idle observer restart remains connecting and public Stop cancels its pending permission',
++ options,
++ async (t) => {
++ const h = nativeIntegrationFixture(t);
++ await h.start();
++ let grant;
++ const permission = new Promise((resolve) => {
++ grant = resolve;
++ });
++ h.controller.getUserMedia = () => permission;
++ const states = [];
++ let restarted = false;
++ let startup;
++ const remove = h.session.subscribe((event) => {
++ if (event.type === 'state') states.push(event.state);
++ if (!restarted && event.type === 'state' && event.state === 'idle') {
++ restarted = true;
++ startup = h.session.start();
++ }
++ });
++ h.session.stop();
++ remove();
++ assert.equal(restarted, true);
++ assert.equal(states.filter((state) => state === 'idle').length, 1);
++ assert.equal(h.session.state, 'connecting');
++ assert.equal(h.controller.status, 'connecting');
++ assert.equal(
++ h.session.isActive(),
++ true,
++ 'the common button/facade must offer Stop',
++ );
++ h.session.stop();
++ assert.equal(h.session.state, 'idle');
++ assert.equal(h.controller.status, 'idle');
++ const lateTrack = {
++ readyState: 'live',
++ stopCalls: 0,
++ stop() {
++ this.stopCalls++;
++ this.readyState = 'ended';
++ },
++ };
++ h.tracks.push(lateTrack);
++ grant({ getTracks: () => [lateTrack], getAudioTracks: () => [lateTrack] });
++ await startup;
++ await turnOfEventLoop();
++ assert.equal(lateTrack.stopCalls, 1);
++ assert.equal(
++ h.requests.length,
++ 1,
++ 'cancelled restart must not mint another token',
++ );
++ assert.equal(
++ h.sockets.length,
++ 1,
++ 'cancelled restart must not open another socket',
++ );
++ assert.equal(h.session.state, 'idle');
++ },
++);
diff --cc src/voice/geminiNativeCaptionEvents.test.mjs
index 000000000,000000000..0157ee8fc
new file mode 100644
--- /dev/null
+++ b/src/voice/geminiNativeCaptionEvents.test.mjs
@@@ -1,0 -1,0 +1,85 @@@
++import test from 'node:test';
++import assert from 'node:assert/strict';
++import { harness } from '../testSupport/geminiNativeHarness.mjs';
++
++const caption = (socket, text) =>
++ socket.message({ serverContent: { inputTranscription: { text } } });
++const userEvents = (events) =>
++ events.filter(
++ (event) => event.type === 'transcript' && event.role === 'user',
++ );
++
++test('native caption events preserve received advisory segments without granting tool authority', async () => {
++ const h = harness();
++ try {
++ await h.c.start();
++ const ws = h.sockets[0];
++ const start = h.events.length;
++ for (const text of ['little. ', 'Zoom in a ']) caption(ws, text);
++ const received = userEvents(h.events.slice(start));
++ assert.deepEqual(
++ received.map((event) => event.text),
++ ['little. ', 'Zoom in a '],
++ );
++ assert.equal(
++ received.every(
++ (event) =>
++ event.delta === true &&
++ event.final === false &&
++ event.attribution === 'unverified' &&
++ event.responseId === null,
++ ),
++ true,
++ );
++ assert.equal(h.c.currentTypedInput(), null);
++ ws.message({
++ toolCall: {
++ functionCalls: [
++ {
++ id: 'ordinary-native',
++ name: 'get_current_view_state',
++ args: {},
++ },
++ ],
++ },
++ });
++ await h.c.toolQueue;
++ assert.equal(h.calls.length, 1);
++ assert.equal(h.calls[0].options.userTurn, undefined);
++ assert.equal(h.calls[0].options.isCurrent(), true);
++ ws.message({ serverContent: { turnComplete: true } });
++ assert.equal(
++ userEvents(h.events.slice(start)).some((event) => event.final),
++ false,
++ );
++ } finally {
++ h.c.stop();
++ }
++ assert.equal(h.timers.size, 0);
++});
++
++test('native old socket captions cannot enter a restarted controller event stream', async () => {
++ const h = harness();
++ try {
++ await h.c.start();
++ const old = h.sockets[0];
++ caption(old, 'old partial');
++ h.c.stop();
++ await h.c.start();
++ const start = h.events.length;
++ const current = h.sockets[1];
++ caption(current, 'Zoom ');
++ caption(old, 'stale old socket');
++ caption(current, 'in a little.');
++ current.message({ serverContent: { turnComplete: true } });
++ assert.deepEqual(
++ userEvents(h.events.slice(start)).map((event) => event.text),
++ ['Zoom ', 'in a little.'],
++ );
++ assert.equal(h.tracks[0].readyState, 'ended');
++ assert.equal(h.captures[0].closed, true);
++ } finally {
++ h.c.stop();
++ }
++ assert.equal(h.timers.size, 0);
++});
diff --cc src/voice/geminiNativeOwnership.test.mjs
index afc8e3f84,000000000..043ebbe31
mode 100644,000000..100644
--- a/src/voice/geminiNativeOwnership.test.mjs
+++ b/src/voice/geminiNativeOwnership.test.mjs
@@@ -1,524 -1,0 +1,667 @@@
+import test from 'node:test';
+import assert from 'node:assert/strict';
- import { harness, tick, deferred } from './geminiNativeHarness.mjs';
- import { readVoiceUserTurnText } from './userTurnIntent.js';
++import {
++ harness,
++ tick,
++ deferred,
++} from '../testSupport/geminiNativeHarness.mjs';
+import { withToolCatalog } from './gevRealtime.js';
+
+const audioContent = (data) => ({
+ modelTurn: {
+ parts: [{ inlineData: { data, mimeType: 'audio/pcm;rate=24000' } }],
+ },
+});
+const request = (ws, id, name = 'get_current_view_state', args = {}) =>
+ ws.message({ toolCall: { functionCalls: [{ id, name, args }] } });
+const responses = (ws) =>
+ ws.sent.flatMap((m) => m.toolResponse?.functionResponses || []);
+const onset = (ws) => {
+ ws.message({ voiceActivity: { type: 'ACTIVITY_START' } });
+ ws.message({ voiceActivity: { type: 'ACTIVITY_END' } });
+};
+const caption = (ws, text) =>
+ ws.message({ serverContent: { inputTranscription: { text } } });
+
+for (const [id, name, args] of [
+ ['H01', 'get_entity_context', {}],
+ ['H02', 'control_radio', { action: 'status' }],
+]) {
+ test(`${id} native: cancelling a current ${name} query preserves unrelated Radio preflight`, async () => {
+ const ready = deferred(),
+ query = deferred(),
+ executions = [];
+ const h = harness({
+ runAction: (name, args, options) => {
+ executions.push({ name, args, options });
+ return args.action === 'play'
+ ? Promise.resolve({
+ ok: true,
+ action: 'control_radio',
+ radioAction: 'play',
+ radioPlaybackRequested: true,
+ })
+ : query.promise;
+ },
+ });
+ h.c.radio.radioLayer.playForVoice = () => ready.promise;
+ try {
+ await h.c.start();
+ h.c.sendTextCommand('Play radio');
+ const ws = h.sockets[0];
+ request(ws, 'owner', 'control_radio', { action: 'play' });
+ await h.c.toolQueue;
+ ws.message({
+ serverContent: { ...audioContent('confirmation'), turnComplete: true },
+ });
+ h.captures[0].drain();
+ assert.equal(h.c.radio.radioHandoffInFlight, true);
+ request(ws, 'query', name, args);
+ await tick();
+ assert.equal(
+ executions.length,
+ 2,
+ 'current native query may start after provider completion',
+ );
+ const epoch = h.c.radio.radioHandoffEpoch;
+ const pending = h.c.radio.pendingRadioPlaybackResult;
+ const attempt = h.c.radio.radioHandoffAttemptId;
+ const ownerCurrent = executions[0].options.isCurrent();
+ ws.message({ toolCallCancellation: { ids: ['unknown', 'query'] } });
+ await h.c.toolQueue;
+ assert.equal(executions[1].options.signal.aborted, true);
+ assert.equal(executions[1].options.isCurrent(), false);
+ assert.equal(h.c.radio.radioHandoffEpoch, epoch);
+ assert.equal(executions[0].options.signal.aborted, false);
+ assert.equal(executions[0].options.isCurrent(), ownerCurrent);
+ assert.equal(h.c.radio.pendingRadioPlaybackResult, pending);
+ assert.equal(h.c.radio.radioHandoffAttemptId, attempt);
+ assert.equal(h.c.radio.radioHandoffInFlight, true);
+ assert.equal(h.state.stopped, 0);
+ assert.equal(h.c.pendingTools, 0);
+ assert.deepEqual(
+ responses(ws).map((r) => r.id),
+ ['owner'],
+ );
+ assert.equal(responses(ws)[0].response.ok, true);
+ query.resolve({ ok: true });
+ ready.resolve(true);
+ await tick();
+ assert.equal(h.c.status, 'idle');
+ assert.equal(h.state.ducked, false);
+ assert.deepEqual(
+ responses(ws).map((r) => r.id),
+ ['owner'],
+ );
+ } finally {
+ h.c.stop();
+ }
+ assert.equal(h.timers.size, 0);
+ });
+}
+
+for (const [id, prior] of [
+ ['H03', 'playing'],
+ ['H04', 'before-first-output'],
+]) {
+ test(`${id} native: PTT fences ${prior} reply and recovers the new call after its boundary`, async () => {
+ const h = harness();
+ try {
+ await h.c.start({ pushToTalk: true });
+ const ws = h.sockets[0],
+ audio = h.captures[0];
+ if (prior === 'playing')
+ ws.message({ serverContent: audioContent('old') });
+ else {
+ h.c.input.setMicrophoneEnabled(true);
+ audio.callbacks.onAudio(
+ { data: 'AAAB', mimeType: 'audio/pcm;rate=16000' },
+ audio.metadata,
+ );
+ h.c.input.setMicrophoneEnabled(false);
+ }
+ h.c.input.pushToTalkKeyHeld = true;
+ assert.equal(h.c.input.bargeIn(), true);
+ h.c.input.setMicrophoneEnabled(true);
+ h.c.input.setMicrophoneEnabled(false);
+ const turn = h.c.turn,
+ played = audio.played.length,
+ firstEvent = h.events.length;
+ ws.message({
+ serverContent: {
+ ...audioContent('late-old'),
+ outputTranscription: { text: 'retired output' },
+ inputTranscription: { text: 'new request' },
+ },
+ });
+ request(ws, 'retired-call', 'fly_to_location', { query: 'old target' });
+ await h.c.toolQueue;
+ assert.equal(audio.played.length, played);
+ assert.equal(audio.pending, false);
+ assert.equal(h.calls.length, 0);
+ assert.equal(
+ h.events.slice(firstEvent).some((e) => e.role === 'assistant'),
+ false,
+ );
+ assert.equal(
+ h.events
+ .slice(firstEvent)
+ .some((e) => e.role === 'user' && e.text === 'new request'),
+ true,
+ );
+ ws.message({ serverContent: { interrupted: true } });
+ assert.equal(h.c.turn, turn);
+ ws.message({ serverContent: audioContent('after-interrupted') });
+ assert.equal(
+ audio.played.length,
+ played,
+ 'interrupted alone cannot release the fence',
+ );
+ ws.message({
+ serverContent: {
+ ...audioContent('boundary-old'),
+ outputTranscription: { text: 'still retired' },
+ turnComplete: true,
+ },
+ });
+ assert.equal(
+ audio.played.length,
+ played,
+ 'coalesced old boundary output is discarded',
+ );
+ assert.equal(
+ h.events.slice(firstEvent).some((e) => e.type === 'completion'),
+ false,
+ );
+ caption(ws, 'unrelated advisory words');
+ ws.message({
+ toolCall: {
+ functionCalls: [
+ {
+ id: 'retired-call',
+ name: 'fly_to_location',
+ args: { query: 'replayed old target' },
+ },
+ {
+ id: 'new-call',
+ name: 'fly_to_location',
+ args: { query: 'new target' },
+ },
+ ],
+ },
+ });
+ await h.c.toolQueue;
+ assert.deepEqual(
+ h.calls.map((c) => c.args.query),
+ ['new target'],
+ );
+ assert.equal(h.calls[0].options.userTurn, undefined);
+ ws.message({
+ serverContent: {
+ ...audioContent('new'),
+ outputTranscription: { text: 'new reply' },
+ turnComplete: true,
+ },
+ });
+ assert.equal(audio.played.at(-1).data, 'new');
+ audio.drain();
+ assert.equal(
+ h.events.findLast((e) => e.type === 'completion').status,
+ 'completed',
+ );
+ } finally {
+ h.c.stop();
+ }
+ assert.equal(h.timers.size, 0);
+ });
+}
+
- test('H05 native: typed token survives audio drain for same-turn tools and revokes on new input', async () => {
++test('H05 native: local typed presentation survives audio drain and new input revokes old call ownership', async () => {
+ const h = harness();
+ try {
+ await h.c.start();
+ const ws = h.sockets[0],
+ audio = h.captures[0];
+ h.c.sendTextCommand('Show the current view');
- const response = h.events.findLast((e) => e.type === 'response-start');
++ const response = h.c.currentTypedInput();
++ assert.equal(response.text, 'Show the current view');
+ assert.equal(
- readVoiceUserTurnText(response.userTurn),
- 'Show the current view',
++ h.events.findLast((e) => e.type === 'transcript' && e.role === 'user')
++ .text,
++ response.text,
+ );
+ request(ws, 'first');
+ await h.c.toolQueue;
- assert.equal(h.calls[0].options.userTurn, response.userTurn);
- assert.equal(h.calls[0].options.responseId, response.responseId);
++ assert.equal(h.calls[0].options.userTurn, undefined);
++ assert.equal(h.calls[0].options.isCurrent(), true);
+ ws.message({
+ serverContent: {
+ ...audioContent('confirmation'),
+ outputTranscription: { text: 'Here is the current view' },
+ turnComplete: true,
+ },
+ });
+ assert.equal(
+ h.events.some((e) => e.type === 'completion'),
+ false,
+ );
+ assert.equal(
+ h.events.findLast((e) => e.role === 'assistant').responseId,
+ response.responseId,
+ );
+ audio.drain();
+ const completion = h.events.findLast((e) => e.type === 'completion');
+ assert.equal(completion.responseId, response.responseId);
+ assert.equal(completion.spoken, true);
+ assert.equal(completion.audioDrained, true);
- assert.equal(
- readVoiceUserTurnText(response.userTurn),
- 'Show the current view',
- );
++ assert.equal(h.c.currentTypedInput(), response);
++ assert.equal(response.text, 'Show the current view');
+ request(ws, 'same-turn');
+ await h.c.toolQueue;
- assert.equal(h.calls[1].options.userTurn, response.userTurn);
++ assert.equal(h.calls[1].options.userTurn, undefined);
++ assert.equal(h.c.currentTypedInput(), response);
+ h.c.sendTextCommand('New request');
- assert.equal(readVoiceUserTurnText(response.userTurn), undefined);
++ assert.notEqual(h.c.currentTypedInput(), response);
++ assert.equal(h.c.currentTypedInput().text, 'New request');
++ assert.equal(h.calls[0].options.isCurrent(), false);
++ assert.equal(h.calls[1].options.isCurrent(), false);
+ } finally {
+ h.c.stop();
+ }
+ assert.equal(h.timers.size, 0);
+});
+
+test('H08 native: replacing pending runner work cannot underflow tool counts or block successor', async () => {
+ const gate = deferred(),
+ executions = [];
+ const h = harness({
+ runAction: (name, args, options) => {
+ executions.push({ name, args, options });
+ return options.callId === 'old'
+ ? gate.promise
+ : Promise.resolve({ ok: true });
+ },
+ });
+ try {
+ await h.c.start();
+ const ws = h.sockets[0];
+ onset(ws);
+ request(ws, 'old');
+ await tick();
+ const oldWork = h.c.toolQueue;
+ assert.equal(h.c.pendingTools, 1);
+ ws.message({ voiceActivity: { type: 'ACTIVITY_START' } });
+ assert.equal(h.c.pendingTools, 0);
+ await oldWork;
+ assert.equal(h.c.pendingTools, 0);
+ assert.equal(executions[0].options.signal.aborted, true);
+ assert.equal(executions[0].options.isCurrent(), false);
+ ws.message({ voiceActivity: { type: 'ACTIVITY_END' } });
+ ws.message({ serverContent: { interrupted: true, turnComplete: true } });
+ request(ws, 'fresh');
+ await h.c.toolQueue;
+ assert.equal(executions.at(-1).options.callId, 'fresh');
+ assert.equal(h.c.pendingTools, 0);
+ gate.resolve({ ok: true });
+ await tick();
+ assert.equal(h.c.pendingTools, 0);
+ assert.deepEqual(
+ responses(ws).map((r) => r.id),
+ ['fresh'],
+ );
+ ws.message({
+ serverContent: { ...audioContent('fresh reply'), turnComplete: true },
+ });
+ h.captures[0].drain();
+ assert.equal(
+ h.events.findLast((e) => e.type === 'completion').status,
+ 'completed',
+ );
+ } finally {
+ h.c.stop();
+ }
+ assert.equal(h.timers.size, 0);
+});
+
+test('H10 native: held speech dispatches without caption authority and new text revokes its call', async () => {
+ const gate = deferred(),
+ executions = [];
+ const h = harness({
+ runAction: (name, args, options) => {
+ executions.push({ name, args, options });
+ return gate.promise;
+ },
+ });
+ try {
+ await h.c.start({ pushToTalk: true });
+ const ws = h.sockets[0],
+ audio = h.captures[0];
+ h.c.input.bargeIn();
+ h.c.input.setMicrophoneEnabled(true);
+ audio.callbacks.onAudio(
+ { data: 'AA==', mimeType: 'audio/pcm;rate=16000' },
+ audio.metadata,
+ );
+ h.c.input.setMicrophoneEnabled(false);
+ caption(ws, 'Show the current view');
- const response = h.events.findLast((e) => e.type === 'response-start');
- assert.equal(response.userTurn, undefined);
++ assert.equal(h.c.currentTypedInput(), null);
++ assert.equal(
++ h.events.findLast((e) => e.type === 'transcript' && e.role === 'user')
++ .text,
++ 'Show the current view',
++ );
+ request(ws, 'held');
+ await tick();
+ const oldWork = h.c.toolQueue;
+ assert.equal(executions.length, 1);
+ assert.equal(executions[0].options.userTurn, undefined);
- assert.equal(executions[0].options.responseId, response.responseId);
++ assert.equal(executions[0].options.isCurrent(), true);
+ h.c.sendTextCommand('new intent');
+ await oldWork;
+ assert.equal(executions[0].options.signal.aborted, true);
+ assert.equal(executions[0].options.isCurrent(), false);
+ gate.resolve({ ok: true });
+ await tick();
+ assert.equal(
+ responses(ws).some((r) => r.id === 'held'),
+ false,
+ );
+ } finally {
+ h.c.stop();
+ }
+ assert.equal(h.timers.size, 0);
+});
+
+for (const [id, restart] of [
+ ['H11', false],
+ ['H12', true],
+]) {
+ test(`${id} native: pending tool cannot revive voice after Stop${restart ? '/restart' : ''}`, async () => {
+ const gate = deferred(),
+ mutations = [],
+ executions = [];
+ const h = harness({
+ runAction: async (name, args, options) => {
+ executions.push(options);
+ await gate.promise;
+ if (options.isCurrent()) mutations.push(name);
+ return { ok: true };
+ },
+ });
+ try {
+ await h.c.start();
+ const ws = h.sockets[0];
+ onset(ws);
+ request(ws, 'old');
+ await tick();
+ const pending = h.c.toolQueue;
+ assert.equal(h.c.pendingTools, 1);
+ h.c.stop();
+ const boundary = h.events.length;
+ const successor = restart ? h.c.start() : null;
+ await pending;
+ assert.equal(
+ h.events
+ .slice(boundary)
+ .some((e) => e.type === 'state' && e.state === 'listening'),
+ false,
+ );
+ assert.equal(executions[0].signal.aborted, true);
+ assert.equal(executions[0].isCurrent(), false);
+ assert.equal(h.c.pendingTools, 0);
+ if (successor) await successor;
+ const laterBoundary = h.events.length;
+ gate.resolve();
+ caption(ws, 'late old speech');
+ await tick();
+ assert.deepEqual(mutations, []);
+ assert.equal(
+ h.events.slice(laterBoundary).some((e) => e.type === 'state'),
+ false,
+ );
+ assert.equal(responses(ws).length, 0);
+ } finally {
+ h.c.stop();
+ }
+ assert.equal(h.timers.size, 0);
+ });
+}
+
+for (const [id, boundary] of [
+ ['H14', 'interrupted'],
+ ['H15', 'natural'],
+]) {
+ test(`${id} native: shared runner zoom executes promptly after ${boundary} retired boundary`, async () => {
+ const mutations = [],
+ observed = [];
+ const guarded = withToolCatalog(
+ async (name, args) => {
+ mutations.push({ name, args });
+ return { ok: true };
+ },
+ async () => null,
+ );
+ const h = harness({
+ runAction: (name, args, options) => {
+ observed.push(options);
+ return guarded(name, args, options);
+ },
+ });
+ try {
+ await h.c.start();
+ const ws = h.sockets[0];
+ ws.message({ serverContent: audioContent('old reply') });
+ ws.message({ voiceActivity: { type: 'ACTIVITY_START' } });
+ ws.message({
+ serverContent: {
+ ...(boundary === 'interrupted' ? { interrupted: true } : {}),
+ turnComplete: true,
+ },
+ });
+ ws.message({ voiceActivity: { type: 'ACTIVITY_END' } });
+ caption(ws, 'zoom in');
+ request(ws, 'zoom', 'adjust_camera_zoom', { direction: 'in' });
+ await tick();
+ assert.equal(
+ mutations.length,
+ 1,
+ 'native action executes without a transcript wait',
+ );
+ assert.equal(observed[0].userTurn, undefined);
+ assert.equal(h.c.pendingTools, 0);
+ assert.equal(
+ responses(ws).some((r) => r.response.voiceIntentUnverified),
+ false,
+ );
+ } finally {
+ h.c.stop();
+ }
+ assert.equal(h.timers.size, 0);
+ });
+}
+
+for (const [id, exit] of [
+ ['H18', 'stop'],
+ ['H19', 'replacement'],
+]) {
+ test(`${id} native: ${exit} prevents queued camera dispatch and late captions cannot revive it`, async () => {
+ const mutations = [],
+ observed = [];
+ const guarded = withToolCatalog(
+ async (name) => {
+ mutations.push(name);
+ return { ok: true };
+ },
+ async () => null,
+ );
+ const h = harness({
+ runAction: (name, args, options) => {
+ observed.push(name);
+ return guarded(name, args, options);
+ },
+ });
+ try {
+ await h.c.start();
+ const ws = h.sockets[0];
+ onset(ws);
+ request(ws, 'queued-old', 'adjust_camera_zoom', { direction: 'in' });
+ const oldWork = h.c.toolQueue;
+ assert.equal(h.c.pendingTools, 1);
+ if (exit === 'stop') h.c.stop();
- else h.c.sendTextCommand('switch voice provider to Gemini');
++ else h.c.sendTextCommand('Show the whole globe');
+ caption(ws, 'zoom in');
+ await oldWork;
+ assert.deepEqual(mutations, []);
+ assert.deepEqual(observed, []);
+ assert.equal(h.c.pendingTools, 0);
+ if (exit === 'replacement') {
+ ws.message({
+ serverContent: { interrupted: true, turnComplete: true },
+ });
- request(ws, 'typed-provider-camera', 'zoom_to_globe');
++ request(ws, 'fresh-camera', 'zoom_to_globe');
+ await h.c.toolQueue;
- assert.deepEqual(mutations, []);
- assert.deepEqual(observed, []);
- assert.equal(
- responses(ws).at(-1).response.providerRequestBlocked,
- true,
- );
++ assert.deepEqual(mutations, ['zoom_to_globe']);
++ assert.deepEqual(observed, ['zoom_to_globe']);
++ assert.equal(responses(ws).at(-1).response.ok, true);
+ }
+ } finally {
+ h.c.stop();
+ }
+ assert.equal(h.timers.size, 0);
+ });
+}
++
++for (const settlement of ['queued', 'running']) {
++ test(`native: cancelled ${settlement} tool settles a completed provider turn`, async () => {
++ const result = deferred();
++ let executions = 0;
++ const h = harness({
++ runAction: () => {
++ executions++;
++ return result.promise;
++ },
++ });
++ try {
++ await h.c.start();
++ h.c.sendTextCommand('Read current view');
++ const ws = h.sockets[0];
++ request(ws, 'cancelled-query');
++ if (settlement === 'running') await tick();
++ ws.message({ toolCallCancellation: { ids: ['cancelled-query'] } });
++ ws.message({ serverContent: { turnComplete: true } });
++ await h.c.toolQueue;
++ assert.equal(h.c.pendingTools, 0);
++ assert.equal(executions, settlement === 'queued' ? 0 : 1);
++ assert.deepEqual(responses(ws), []);
++ assert.equal(
++ h.events.filter((event) => event.type === 'completion').length,
++ 1,
++ );
++ assert.equal(h.c.pendingCompletionStatus, null);
++ result.resolve({ ok: true });
++ await tick();
++ h.captures[0].drain();
++ assert.equal(
++ h.events.filter((event) => event.type === 'completion').length,
++ 1,
++ );
++ assert.deepEqual(responses(ws), []);
++ } finally {
++ result.resolve({ ok: true });
++ h.c.stop();
++ }
++ assert.equal(h.timers.size, 0);
++ });
++}
++
++for (const order of ['before', 'after']) {
++ test(`native: cancelling queued output ${order} turnComplete emits one completion`, async () => {
++ const h = harness();
++ try {
++ await h.c.start();
++ h.c.sendTextCommand('Read current view');
++ const ws = h.sockets[0];
++ ws.bufferedAmount = 1e9;
++ request(ws, 'queued-output');
++ await h.c.toolQueue;
++ assert.equal(h.c.pendingTools, 0);
++ assert.equal(h.c.controlQueue.length, 1);
++ assert.equal(responses(ws).length, 0);
++ if (order === 'after')
++ ws.message({ serverContent: { turnComplete: true } });
++ ws.message({ toolCallCancellation: { ids: ['queued-output'] } });
++ if (order === 'before')
++ ws.message({ serverContent: { turnComplete: true } });
++ assert.equal(h.c.controlQueue.length, 0);
++ assert.equal(h.c.controlTimer, null);
++ assert.equal(h.c.pendingCompletionStatus, null);
++ assert.equal(h.events.filter((e) => e.type === 'completion').length, 1);
++ ws.bufferedAmount = 0;
++ h.advance(1000);
++ h.captures[0].drain();
++ assert.deepEqual(responses(ws), []);
++ assert.equal(h.events.filter((e) => e.type === 'completion').length, 1);
++ } finally {
++ h.c.stop();
++ }
++ assert.equal(h.timers.size, 0);
++ });
++}
++
++for (const successor of ['input', 'stop']) {
++ test(`native: queued-output cancellation completion fences reentrant ${successor}`, async () => {
++ let h;
++ let successorTurn;
++ h = harness({
++ emit: (event) => {
++ h.events.push(event);
++ if (event.type !== 'completion') return;
++ h.sockets[0].bufferedAmount = 0;
++ if (successor === 'stop') h.c.stop();
++ else {
++ h.c.sendTextCommand('Show the whole globe');
++ successorTurn = h.c.turn;
++ }
++ },
++ });
++ try {
++ await h.c.start();
++ h.c.sendTextCommand('Read current view');
++ const ws = h.sockets[0];
++ ws.bufferedAmount = 1e9;
++ request(ws, 'queued-output');
++ await h.c.toolQueue;
++ ws.message({ serverContent: { turnComplete: true } });
++ const callCount = h.calls.length;
++ ws.message({
++ toolCallCancellation: { ids: ['queued-output'] },
++ serverContent: {
++ outputTranscription: { text: 'Retired packet caption' },
++ turnComplete: true,
++ },
++ toolCall: {
++ functionCalls: [
++ { id: 'retired-tool', name: 'get_current_view_state', args: {} },
++ ],
++ },
++ });
++ await h.c.toolQueue;
++ assert.equal(h.events.filter((e) => e.type === 'completion').length, 1);
++ assert.equal(h.calls.length, callCount);
++ assert.deepEqual(responses(ws), []);
++ assert.ok(
++ !h.events.some((e) =>
++ JSON.stringify(e).includes('Retired packet caption'),
++ ),
++ );
++ if (successor === 'input') {
++ assert.equal(h.c.turn, successorTurn);
++ assert.equal(h.c.modelComplete, false);
++ assert.equal(h.c.replyPending, true);
++ } else assert.equal(h.c.isActive(), false);
++ } finally {
++ h.c.stop();
++ }
++ assert.equal(h.timers.size, 0);
++ });
++}
diff --cc src/voice/geminiNativeRadio.test.mjs
index 1f18c3fbc,000000000..38ba8ff79
mode 100644,000000..100644
--- a/src/voice/geminiNativeRadio.test.mjs
+++ b/src/voice/geminiNativeRadio.test.mjs
@@@ -1,1049 -1,0 +1,734 @@@
+// Native ownership replacements for historical Radio regression cases.
+// Real Gemini controller, action runner, DataLayerManager and RealtimeRadio consumers.
+import test from 'node:test';
+import assert from 'node:assert/strict';
- import { harness, tick, deferred } from './geminiNativeHarness.mjs';
++import {
++ harness,
++ tick,
++ deferred,
++} from '../testSupport/geminiNativeHarness.mjs';
+import { createGevActionRunner } from './gevActions.js';
+import { createVoiceSession } from './session.js';
+import { DataLayerManager } from '../data/manager.js';
+
+const viewerFixture = () => ({
+ clock: { onTick: { addEventListener: () => () => {} } },
+ camera: { moveEnd: { addEventListener() {} } },
+ scene: { canvas: { addEventListener() {}, removeEventListener() {} } },
+});
+const request = (ws, id, name, args = {}) =>
+ ws.message({ toolCall: { functionCalls: [{ id, name, args }] } });
+const responses = (ws) =>
+ ws.sent.flatMap((frame) => frame.toolResponse?.functionResponses || []);
+const responseFor = (ws, id) =>
+ responses(ws).findLast((response) => response.id === id)?.response;
+const speechTurn = (ws) => {
+ ws.message({ voiceActivity: { type: 'ACTIVITY_START' } });
+ ws.message({ voiceActivity: { type: 'ACTIVITY_END' } });
+};
+function drainRadioReply(h) {
+ h.sockets.at(-1).message({
+ serverContent: {
+ modelTurn: { parts: [{ inlineData: { data: 'AAAA' } }] },
+ turnComplete: true,
+ },
+ });
+ h.captures.at(-1).drain();
+}
+
+function radioSiblingFixture() {
+ const viewer = viewerFixture();
+ const manager = new DataLayerManager(viewer);
+ const lookupEntered = deferred();
+ const lookupReleased = deferred();
+ const state = {
+ stationCount: 2,
+ selected: { id: 'existing-station', name: 'Existing Station' },
+ audioState: 'stopped',
+ };
+ const trace = { stops: 0, pauses: 0, selections: 0, options: new Map() };
+ const radio = {
+ async init() {},
+ async enable() {},
+ async disable() {},
+ async update() {},
+ getStats: () => ({ count: 2 }),
+ getUIState: () => ({ ...state }),
+ setVoiceDucked() {},
+ pause({ origin } = {}) {
+ if (origin === 'voice') trace.pauses++;
+ state.audioState = 'paused';
+ return true;
+ },
+ stopPlayback() {
+ trace.stops++;
+ state.audioState = 'stopped';
+ return true;
+ },
+ selectRequestedStation() {
+ trace.selections++;
+ state.selected = { id: 'late-station', name: 'Late Station' };
+ return state.selected;
+ },
+ subscribePlaybackControls: () => () => {},
+ };
+ manager.register(
+ Object.assign(radio, {
+ id: 'radio',
+ name: 'Radio',
+ updateInterval: -1,
+ }),
+ );
+ const runner = createGevActionRunner({
+ viewer,
+ dataManager: manager,
+ placeSearch: {
+ async geocode(_query, { signal }) {
+ trace.lookupSignal = signal;
+ lookupEntered.resolve();
+ // Deliberately ignore abort: production currentness must still prevent
+ // this late service completion from committing a station selection.
+ await lookupReleased.promise;
+ return { place: { lat: 10, lng: 20, label: 'Deferred Place' } };
+ },
+ },
+ });
+ const h = harness({
+ dataManager: manager,
+ radioLayer: radio,
+ runAction(name, args, options) {
+ trace.options.set(options.callId, options);
+ return runner(name, args, options);
+ },
+ });
+ return {
+ h,
+ manager,
+ runner,
+ radio,
+ trace,
+ state,
+ lookupEntered,
+ lookupReleased,
+ };
+}
+
+for (const action of ['select', 'play']) {
+ for (const stronger of ['stop', 'pause', 'disable', 'off']) {
+ test(`native same-turn Radio ${stronger} preempts deferred ${action} without cancelling a query sibling`, async () => {
+ const f = radioSiblingFixture();
+ const { h, trace, state } = f;
+ try {
+ await f.manager.setEnabled('radio', true);
+ await h.c.start();
+ const ws = h.sockets[0];
+ speechTurn(ws);
+ const turn = h.c.turn;
+ request(ws, 'slow-selection', 'control_radio', {
+ action,
+ locationQuery: 'Deferred Place',
+ });
+ await f.lookupEntered.promise;
+ request(ws, 'query-sibling', 'control_radio', { action: 'status' });
+ request(
+ ws,
+ 'stronger-radio',
+ stronger === 'off' ? 'set_layer_visibility' : 'control_radio',
+ stronger === 'off'
+ ? { layerId: 'radio', enabled: false }
+ : { action: stronger },
+ );
+ await tick();
+ assert.equal(
+ responseFor(ws, 'stronger-radio')?.ok,
+ true,
+ 'stronger control must finish before lookup release',
+ );
+ assert.equal(trace.lookupSignal.aborted, true);
+ await h.c.toolQueue;
+ assert.equal(
+ h.c.turn,
+ turn,
+ 'sibling control cannot invent a new turn',
+ );
+ assert.equal(trace.selections, 0);
+ assert.equal(state.selected.id, 'existing-station');
+ assert.equal(responseFor(ws, 'slow-selection').ok, false);
+ assert.match(responseFor(ws, 'slow-selection').error, /cancelled/);
+ assert.equal(
+ responseFor(ws, 'slow-selection').enabled,
+ !['disable', 'off'].includes(stronger),
+ );
+ assert.equal(responseFor(ws, 'query-sibling').ok, true);
+ assert.equal(trace.options.get('query-sibling').signal.aborted, false);
+ assert.equal(
+ responseFor(ws, 'stronger-radio').enabled,
+ !['disable', 'off'].includes(stronger),
+ );
+ assert.equal(trace.stops, stronger === 'stop' ? 1 : 0);
+ assert.equal(trace.pauses, stronger === 'pause' ? 1 : 0);
+ f.lookupReleased.resolve();
+ await tick();
+ assert.equal(trace.selections, 0, 'late lookup cannot commit');
+ assert.equal(h.c.pendingTools, 0);
+ assert.equal(h.c.tools.size, 0);
+ assert.equal(h.c.radio.radioToolHandoffReservations.size, 0);
+ for (const id of ['slow-selection', 'query-sibling', 'stronger-radio'])
+ assert.equal(responses(ws).filter((r) => r.id === id).length, 1);
+ } finally {
+ f.lookupReleased.resolve();
+ h.c.stop();
+ f.runner.dispose();
+ await f.manager.setEnabled('radio', false);
+ }
+ assert.equal(h.timers.size, 0);
+ });
+ }
+}
+
- for (const guard of [
- 'malformed',
- 'replay',
- 'invalid-arguments',
- 'provider-veto',
- ]) {
++for (const guard of ['malformed', 'replay', 'invalid-arguments']) {
+ test(`native stronger Radio ${guard} cannot revoke a same-turn lookup`, async () => {
+ const f = radioSiblingFixture();
+ const { h, trace } = f;
+ try {
+ await f.manager.setEnabled('radio', true);
+ await h.c.start();
+ const ws = h.sockets[0];
+ if (guard === 'replay') {
+ request(ws, 'stronger-radio', 'control_radio', { action: 'stop' });
+ await h.c.toolQueue;
+ }
+ speechTurn(ws);
+ if (guard === 'replay')
+ ws.message({
+ serverContent: { interrupted: true, turnComplete: true },
+ });
+ request(ws, 'slow-selection', 'control_radio', {
+ action: 'select',
+ locationQuery: 'Deferred Place',
+ });
+ await f.lookupEntered.promise;
+ const stops = trace.stops;
+ const handoffEpoch = h.c.radio.radioHandoffEpoch;
- if (guard === 'provider-veto')
- request(ws, 'provider-setter', 'set_voice_provider', {
- provider: 'openai',
- });
+ request(
+ ws,
+ guard === 'malformed' ? '\n' : 'stronger-radio',
+ 'control_radio',
+ {
+ action: 'stop',
+ ...(guard === 'invalid-arguments'
+ ? { latitude: 91, longitude: 0 }
+ : {}),
+ },
+ );
+ await tick();
+ assert.equal(trace.lookupSignal.aborted, false);
+ assert.equal(trace.stops, stops);
+ assert.equal(h.c.radio.radioHandoffEpoch, handoffEpoch);
+ assert.equal(h.c.radio.radioToolHandoffReservations.size, 0);
- if (guard === 'provider-veto') {
- assert.equal(
- responseFor(ws, 'stronger-radio').providerRequestBlocked,
- true,
- );
- assert.equal(trace.options.has('stronger-radio'), false);
- }
+ if (guard === 'invalid-arguments') {
+ assert.equal(responseFor(ws, 'stronger-radio').ok, false);
+ assert.match(responseFor(ws, 'stronger-radio').error, /coordinates/);
+ }
+ f.lookupReleased.resolve();
+ await h.c.toolQueue;
+ assert.equal(
+ trace.selections,
+ 1,
+ 'older eligible work retains authority',
+ );
+ assert.equal(responseFor(ws, 'slow-selection').ok, true);
+ assert.equal(h.c.pendingTools, 0);
+ assert.equal(h.c.tools.size, 0);
+ } finally {
+ f.lookupReleased.resolve();
+ h.c.stop();
+ f.runner.dispose();
+ await f.manager.setEnabled('radio', false);
+ }
+ assert.equal(h.timers.size, 0);
+ });
+}
+
+test('native failed Stop releases its reservation and lets the older selection finish', async () => {
+ const f = radioSiblingFixture();
+ const { h, trace } = f;
+ const stopReleased = deferred();
+ f.radio.stopPlayback = () => stopReleased.promise;
+ try {
+ await f.manager.setEnabled('radio', true);
+ await h.c.start();
+ const ws = h.sockets[0];
+ speechTurn(ws);
+ request(ws, 'slow-selection', 'control_radio', {
+ action: 'select',
+ locationQuery: 'Deferred Place',
+ });
+ await f.lookupEntered.promise;
+ request(ws, 'failed-stop', 'control_radio', { action: 'stop' });
+ await tick();
+ assert.equal(h.c.radio.radioToolHandoffReservations.size, 1);
+ assert.equal(
+ trace.lookupSignal.aborted,
+ false,
+ 'provisional Stop cannot revoke work',
+ );
+ assert.equal(h.c.pendingTools, 2);
+ stopReleased.resolve(false);
+ await tick();
+ assert.equal(responseFor(ws, 'failed-stop').ok, false);
+ assert.match(responseFor(ws, 'failed-stop').error, /could not be stopped/);
+ assert.equal(h.c.radio.radioToolHandoffReservations.size, 0);
+ assert.equal(trace.lookupSignal.aborted, false);
+ f.lookupReleased.resolve();
+ await h.c.toolQueue;
+ assert.equal(responseFor(ws, 'slow-selection').ok, true);
+ assert.equal(trace.selections, 1);
+ assert.equal(f.state.selected.id, 'late-station');
+ assert.equal(h.c.pendingTools, 0);
+ } finally {
+ stopReleased.resolve(false);
+ f.lookupReleased.resolve();
+ h.c.stop();
+ f.runner.dispose();
+ await f.manager.setEnabled('radio', false);
+ }
+ assert.equal(h.timers.size, 0);
+});
+
+test('native pending Stop preserves selection completed before its own successful settlement', async () => {
+ const f = radioSiblingFixture();
+ const { h } = f;
+ const stopReleased = deferred();
+ f.radio.stopPlayback = () => stopReleased.promise;
+ try {
+ await f.manager.setEnabled('radio', true);
+ await h.c.start();
+ const ws = h.sockets[0];
+ speechTurn(ws);
+ request(ws, 'slow-selection', 'control_radio', {
+ action: 'select',
+ locationQuery: 'Deferred Place',
+ });
+ await f.lookupEntered.promise;
+ request(ws, 'pending-stop', 'control_radio', { action: 'stop' });
+ await tick();
+ f.lookupReleased.resolve();
+ await tick();
+ assert.equal(responseFor(ws, 'slow-selection').ok, true);
+ assert.equal(f.state.selected.id, 'late-station');
+ assert.equal(h.c.radio.radioToolHandoffReservations.size, 1);
+ assert.ok(h.c.radio.pendingRadioPlaybackResult);
+ stopReleased.resolve(true);
+ await h.c.toolQueue;
+ assert.equal(responseFor(ws, 'pending-stop').ok, true);
+ assert.equal(responseFor(ws, 'pending-stop').stationId, 'late-station');
+ assert.equal(f.state.selected.id, 'late-station');
+ assert.equal(h.c.radio.pendingRadioPlaybackResult, null);
+ assert.equal(h.c.pendingTools, 0);
+ } finally {
+ stopReleased.resolve(false);
+ f.lookupReleased.resolve();
+ h.c.stop();
+ f.runner.dispose();
+ await f.manager.setEnabled('radio', false);
+ }
+ assert.equal(h.timers.size, 0);
+});
+
+for (const restart of [false, true]) {
+ test(`native Stop${restart ? '/restart' : ''} retires concurrent stronger Radio work without late output or count underflow`, async () => {
+ const f = radioSiblingFixture();
+ const { h } = f;
+ const stopReleased = deferred();
+ f.radio.stopPlayback = () => stopReleased.promise;
+ try {
+ await f.manager.setEnabled('radio', true);
+ await h.c.start();
+ const ws = h.sockets[0];
+ speechTurn(ws);
+ request(ws, 'slow-selection', 'control_radio', {
+ action: 'select',
+ locationQuery: 'Deferred Place',
+ });
+ await f.lookupEntered.promise;
+ request(ws, 'pending-stop', 'control_radio', { action: 'stop' });
+ await tick();
+ const oldDrain = h.c.toolQueue;
+ const stopOptions = f.trace.options.get('pending-stop');
+ assert.equal(h.c.pendingTools, 2);
+ h.c.stop();
+ assert.equal(stopOptions.signal.aborted, true);
+ assert.equal(f.trace.lookupSignal.aborted, true);
+ if (restart) {
+ await h.c.start();
+ request(h.sockets[1], 'new-query', 'control_radio', {
+ action: 'status',
+ });
+ await h.c.toolQueue;
+ assert.equal(responseFor(h.sockets[1], 'new-query').ok, true);
+ }
+ stopReleased.resolve(true);
+ f.lookupReleased.resolve();
+ await oldDrain;
+ await tick();
+ assert.equal(responseFor(ws, 'pending-stop'), undefined);
+ assert.equal(responseFor(ws, 'slow-selection'), undefined);
+ assert.equal(f.trace.selections, 0);
+ assert.equal(h.c.pendingTools, 0);
+ assert.equal(h.c.tools.size, 0);
+ assert.equal(h.c.radio.radioToolHandoffReservations.size, 0);
+ assert.equal(h.c.isActive(), restart);
+ } finally {
+ stopReleased.resolve(false);
+ f.lookupReleased.resolve();
+ h.c.stop();
+ f.runner.dispose();
+ await f.manager.setEnabled('radio', false);
+ }
+ assert.equal(h.timers.size, 0);
+ });
+}
+
+for (const phase of ['prepared', 'preflight']) {
+ test(`native same-turn Stop revokes only voice-owned ${phase} playback and preserves completed station`, async () => {
+ const f = radioSiblingFixture();
+ const { h } = f;
+ const ready = deferred();
+ const stopped = [];
+ let preflight;
+ f.radio.playForVoice = () => ready.promise;
+ f.radio.stopPlayback = (options) => {
+ stopped.push(options);
+ return true;
+ };
+ try {
+ await f.manager.setEnabled('radio', true);
+ await h.c.start();
+ const ws = h.sockets[0];
+ speechTurn(ws);
+ request(ws, 'prepared-play', 'control_radio', { action: 'play' });
+ await h.c.toolQueue;
+ assert.equal(
+ responseFor(ws, 'prepared-play').radioPlaybackRequested,
+ true,
+ );
+ if (phase === 'preflight')
+ preflight = h.c.radio.startPendingRadioHandoff();
+ const attemptId = h.c.radio.radioHandoffAttemptId;
+ request(ws, 'stronger-stop', 'control_radio', { action: 'stop' });
+ await h.c.toolQueue;
+ assert.equal(responseFor(ws, 'stronger-stop').ok, true);
+ assert.equal(f.state.selected.id, 'existing-station');
+ assert.equal(h.c.radio.pendingRadioPlaybackResult, null);
+ assert.equal(h.c.radio.radioHandoffInFlight, false);
+ const cleanups = stopped.filter((o) => o.origin === 'voice-cleanup');
+ assert.deepEqual(
+ cleanups,
+ phase === 'preflight' ? [{ origin: 'voice-cleanup', attemptId }] : [],
+ );
+ ready.resolve(true);
+ await preflight;
+ await tick();
+ assert.equal(
+ h.c.isActive(),
+ true,
+ 'late old readiness cannot stop voice',
+ );
+ assert.equal(h.c.radio.radioToolHandoffReservations.size, 0);
+ assert.equal(h.c.pendingTools, 0);
+ } finally {
+ ready.resolve(false);
+ h.c.stop();
+ await preflight;
+ f.runner.dispose();
+ await f.manager.setEnabled('radio', false);
+ }
+ assert.equal(h.timers.size, 0);
+ });
+}
+
- let historicalId = 35;
- for (const providerDropdown of [false, true]) {
- for (const segments of [
- ['use', 'Foo', 'as', 'my', 'voi', 'ce provider'],
- ['use Claude'],
- ['switch to Gemini'],
- ]) {
- for (const tool of [
- { name: 'control_radio', args: { action: 'stop' } },
- { name: 'control_radio', args: { action: 'disable' } },
- {
- name: 'set_layer_visibility',
- args: { layerId: 'radio', enabled: false },
- },
- ]) {
- const id = `H${historicalId++}`;
- test(`${id} native setter quarantine: chooser=${providerDropdown} ${JSON.stringify(segments)} ${tool.name}/${tool.args.action || 'off'} leaves unrelated Radio preflight intact`, async () => {
- const mutations = [];
- const runner = createGevActionRunner({
- viewer: viewerFixture(),
- styleManager: {
- setStyle: (...args) => mutations.push(['style', ...args]),
- },
- dataManager: {
- isEnabled: () => true,
- setEnabled: (...args) => mutations.push(['visibility', ...args]),
- },
- radioLayer: {
- stopPlayback: (...args) => mutations.push(['stop', ...args]),
- },
- });
- let runnerCalls = 0;
- const h = harness({
- providerDropdown: () => providerDropdown,
- runAction: (...args) => {
- runnerCalls++;
- return runner(...args);
- },
- });
- const trace = {
- reservations: 0,
- registered: 0,
- toolStarted: 0,
- pauses: 0,
- };
- const playbackReady = deferred();
- let preflight;
- try {
- const pause = h.c.radio.pauseRadioForVoice.bind(h.c.radio);
- h.c.radio.pauseRadioForVoice = (...args) => {
- trace.pauses++;
- return pause(...args);
- };
- await h.c.start();
- const ws = h.sockets[0];
- speechTurn(ws);
- for (const text of segments)
- ws.message({ serverContent: { inputTranscription: { text } } });
- assert.equal(trace.pauses, 1);
- h.c.radio.radioLayer.playForVoice = () => playbackReady.promise;
- const prepared = {
- ok: true,
- action: 'control_radio',
- radioAction: 'play',
- radioPlaybackRequested: true,
- };
- h.c.radio.setPendingPlayback(prepared);
- preflight = h.c.radio.startPendingRadioHandoff();
- const handoffEpoch = h.c.radio.radioHandoffEpoch;
- const attemptId = h.c.radio.radioHandoffAttemptId;
- assert.equal(h.c.radio.radioHandoffInFlight, true);
- for (const [method, counter] of [
- ['reserveRadioToolHandoff', 'reservations'],
- ['registerTool', 'registered'],
- ]) {
- const original = h.c.radio[method].bind(h.c.radio);
- h.c.radio[method] = (...args) => {
- trace[counter]++;
- return original(...args);
- };
- }
- const started = h.c.narration.toolStarted.bind(h.c.narration);
- h.c.narration.toolStarted = (...args) => {
- trace.toolStarted++;
- return started(...args);
- };
- // The ordinary sibling is first: batch inspection must quarantine it
- // before any runner, reservation or Radio registration can begin.
- ws.message({
- toolCall: {
- functionCalls: [
- { id: 'refused-radio', ...tool },
- {
- id: 'native-setter',
- name: 'set_voice_provider',
- args: { provider: 'openai' },
- },
- ],
- },
- });
- await h.c.toolQueue;
- for (const callId of ['refused-radio', 'native-setter']) {
- const result = responseFor(ws, callId);
- assert.equal(result.providerRequestBlocked, true);
- assert.equal(result.providerDropdown, providerDropdown);
- assert.match(
- result.say,
- providerDropdown ? /dropdown/ : /switch voice providers directly/,
- );
- }
- request(ws, 'later-radio', tool.name, tool.args);
- await h.c.toolQueue;
- assert.equal(
- responseFor(ws, 'later-radio').providerRequestBlocked,
- true,
- );
- assert.deepEqual(trace, {
- reservations: 0,
- registered: 0,
- toolStarted: 0,
- pauses: 1,
- });
- assert.equal(h.c.radio.radioToolHandoffReservations.size, 0);
- assert.equal(h.c.radio.activeRadioToolControllers.size, 0);
- assert.equal(h.c.pendingTools, 0);
- assert.equal(h.c.tools.size, 0);
- assert.equal(runnerCalls, 0);
- assert.deepEqual(mutations, []);
- assert.equal(h.c.radio.pendingRadioPlaybackResult, null);
- assert.equal(h.c.radio.radioHandoffInFlight, true);
- assert.equal(h.c.radio.radioHandoffInFlightResult, prepared);
- assert.equal(h.c.radio.radioHandoffEpoch, handoffEpoch);
- assert.equal(h.c.radio.radioHandoffAttemptId, attemptId);
- assert.equal(h.state.stopped, 0);
- assert.equal(h.c.stopAfterReply, false);
- h.c.sendTextCommand('Set visual style to night vision');
- ws.message({
- serverContent: { interrupted: true, turnComplete: true },
- });
- request(ws, 'fresh-style', 'set_visual_style', {
- style: 'night vision',
- });
- await h.c.toolQueue;
- assert.equal(runnerCalls, 1);
- assert.equal(mutations.length, 1);
- assert.equal(h.c.pendingTools, 0);
- } finally {
- h.c.stop();
- playbackReady.resolve(false);
- await preflight;
- runner.dispose();
- }
- assert.equal(h.timers.size, 0);
- });
- }
- }
- }
-
- for (const [index, phase] of ['initializing', 'committed'].entries()) {
- test(`H${53 + index} native late setter: ${phase} manager work retains commit truth and quarantines later sibling`, async () => {
++for (const phase of ['prepared', 'preflight', 'settling']) {
++ test(`native Radio cancellation: ${phase} preserves selection truth and prevents stale speaker transfer`, async () => {
+ const viewer = viewerFixture();
+ const manager = new DataLayerManager(viewer);
- const initEntered = deferred();
- const initReleased = deferred();
- const committed = deferred();
- const settlement = deferred();
- const calls = [];
- const events = [];
- manager.register({
- id: 'rocket-launches',
- name: 'Missions',
- updateInterval: -1,
- async init() {
- calls.push('init');
- initEntered.resolve();
- if (phase === 'initializing') await initReleased.promise;
++ const prepared = deferred();
++ const settleResult = deferred();
++ const playbackReady = deferred();
++ let playCalls = 0;
++ let stopCalls = 0;
++ let selections = 0;
++ let activeOptions;
++ const state = {
++ stationCount: 2,
++ selected: null,
++ audioState: 'stopped',
++ voiceDucked: false,
++ };
++ const radio = {
++ async init() {},
++ async enable() {},
++ async disable() {},
++ async update() {},
++ getStats: () => ({ count: 2 }),
++ getUIState: () => ({ ...state }),
++ setVoiceDucked(value) {
++ state.voiceDucked = value;
+ },
- async enable() {
- calls.push('enable');
++ pause() {
++ state.audioState = 'paused';
+ },
- async disable() {
- calls.push('disable');
++ subscribePlaybackControls() {
++ return () => {};
+ },
- async update() {},
- getStats: () => ({ count: 0 }),
- });
- const unsubscribe = manager.subscribe((event) => {
- events.push(event);
- if (event.type === 'visibility' && event.enabled) committed.resolve();
- });
- const runner = createGevActionRunner({
- viewer,
- dataManager: manager,
- styleManager: {
- _waitForContextLayerSettlement: () => settlement.promise,
++ selectRequestedStation(_criteria, options) {
++ assert.equal(options.autoplay, false);
++ selections++;
++ state.selected = { id: 'station-1', name: 'Station One' };
++ return state.selected;
++ },
++ playForVoice() {
++ playCalls++;
++ return playbackReady.promise;
+ },
++ stopPlayback() {
++ stopCalls++;
++ state.audioState = 'stopped';
++ },
++ };
++ manager.register({
++ id: 'radio',
++ name: 'Radio',
++ updateInterval: -1,
++ ...radio,
+ });
++ const runner = createGevActionRunner({ viewer, dataManager: manager });
+ let h;
- let activeOptions;
- let runnerCalls = 0;
++ let preflight;
+ const session = createVoiceSession({
- runner: (name, args, options) => {
- runnerCalls++;
++ runner: async (name, args, options) => {
+ activeOptions = options;
- return runner(name, args, options);
++ const result = await runner(name, args, options);
++ prepared.resolve(result);
++ if (phase === 'settling') await settleResult.promise;
++ return result;
+ },
+ createAdapter: (shared) => {
- h = harness({ ...shared, dataManager: manager });
++ h = harness({ ...shared, dataManager: manager, radioLayer: radio });
+ return {
+ start: (settings) => h.c.start(settings),
+ stop: (settings) => h.c.stop(settings),
+ sendText: (text) => h.c.sendTextCommand(text),
+ sendMapEvent: (event) => h.c.notifyMapEvent(event),
+ };
+ },
+ });
+ try {
+ await session.start();
+ const ws = h.sockets[0];
- speechTurn(ws);
- ws.message({
- serverContent: { inputTranscription: { text: 'use foo as my voi' } },
- });
- request(ws, 'inflight-layer', 'set_layer_visibility', {
- layerId: 'rocket-launches',
- enabled: true,
- });
- await initEntered.promise;
- if (phase === 'committed') await committed.promise;
- assert.equal(activeOptions.signal.aborted, false);
- assert.equal(
- activeOptions.userTurn,
- undefined,
- 'captions never become runner authority',
- );
- ws.message({
- serverContent: { inputTranscription: { text: 'ce provider' } },
- });
- request(ws, 'native-setter', 'set_voice_provider', {
- provider: 'openai',
- });
- request(ws, 'denied-sibling', 'set_layer_visibility', {
- layerId: 'rocket-launches',
- enabled: false,
++ assert.equal(session.sendText('Select Station One on Radio'), true);
++ request(ws, 'prepared-radio', 'control_radio', {
++ action: 'select',
++ stationQuery: 'Station One',
+ });
- assert.equal(
- activeOptions.signal.aborted,
- false,
- 'late setter cannot retroactively revoke already-started work',
- );
- initReleased.resolve();
- settlement.resolve();
++ const actual = await prepared.promise;
++ assert.equal(actual.ok, true);
++ assert.equal(actual.radioPlaybackRequested, true);
++ assert.equal(actual.stationId, 'station-1');
++ assert.equal(manager.isEnabled('radio'), true);
++ if (phase !== 'settling') {
++ await h.c.toolQueue;
++ assert.ok(h.c.radio.pendingRadioPlaybackResult);
++ }
++ if (phase === 'preflight') {
++ preflight = h.c.radio.startPendingRadioHandoff();
++ assert.equal(h.c.radio.radioHandoffInFlight, true);
++ assert.equal(playCalls, 1);
++ }
++ // Native call ownership revokes only this deferred playback. No caption
++ // parsing or caption-driven provider policy participates in cancellation.
++ ws.message({ toolCallCancellation: { ids: ['prepared-radio'] } });
++ if (phase === 'settling')
++ assert.equal(activeOptions.signal.aborted, true);
++ settleResult.resolve();
+ await h.c.toolQueue;
- const result = responseFor(ws, 'inflight-layer');
- assert.equal(result.ok, true);
- assert.equal(result.providerRequestBlocked, undefined);
- assert.equal(result.enabled, true);
- assert.equal(manager.isEnabled('rocket-launches'), true);
- assert.equal(calls.includes('enable'), true);
- assert.equal(
- events.some((event) => event.type === 'visibility' && event.enabled),
- true,
- );
++ assert.equal(h.c.radio.pendingRadioPlaybackResult, null);
++ assert.equal(h.c.radio.radioHandoffInFlight, false);
++ assert.equal(manager.isEnabled('radio'), true);
++ assert.equal(state.selected.id, 'station-1');
++ assert.equal(selections, 1);
++ const modelResult = responseFor(ws, 'prepared-radio');
++ if (phase === 'settling')
++ assert.equal(
++ modelResult,
++ undefined,
++ 'cancelled active call never sends a late result',
++ );
++ else {
++ assert.equal(modelResult.ok, true);
++ assert.equal(modelResult.stationId, 'station-1');
++ }
++ const stopsAfterCancellation = stopCalls;
++ assert.equal(stopsAfterCancellation, phase === 'preflight' ? 1 : 0);
++ drainRadioReply(h);
++ playbackReady.resolve(true);
++ await preflight;
++ await tick();
+ assert.equal(
- responseFor(ws, 'native-setter').providerRequestBlocked,
- true,
++ playCalls,
++ phase === 'preflight' ? 1 : 0,
++ 'drain cannot revive cancelled playback',
+ );
++ assert.equal(h.c.isActive(), true, 'late readiness cannot stop voice');
++ assert.equal(h.c.radio.radioHandoffInFlight, false);
++ assert.equal(h.c.pendingTools, 0);
++ assert.equal(h.c.tools.size, 0);
++ assert.equal(session.sendText('Play radio'), true);
++ request(ws, 'fresh-radio', 'control_radio', { action: 'play' });
++ await h.c.toolQueue;
++ assert.ok(h.c.radio.pendingRadioPlaybackResult);
++ drainRadioReply(h);
++ await tick();
++ assert.equal(playCalls, phase === 'preflight' ? 2 : 1);
+ assert.equal(
- responseFor(ws, 'denied-sibling').providerRequestBlocked,
- true,
++ h.c.isActive(),
++ false,
++ 'fresh typed Radio handoff alone ends voice',
+ );
- assert.equal(runnerCalls, 1);
- session.sendText('Hide missions');
- ws.message({ serverContent: { interrupted: true, turnComplete: true } });
- request(ws, 'fresh-missions', 'set_layer_visibility', {
- layerId: 'rocket-launches',
- enabled: false,
- });
- await h.c.toolQueue;
- assert.equal(responseFor(ws, 'fresh-missions').ok, true);
- assert.equal(manager.isEnabled('rocket-launches'), false);
- assert.equal(runnerCalls, 2);
- assert.equal(h.c.tools.size, 0);
- assert.equal(h.c.pendingTools, 0);
+ } finally {
- initReleased.resolve();
- settlement.resolve();
++ settleResult.resolve();
++ playbackReady.resolve(false);
+ session.destroy();
++ await preflight;
+ runner.dispose();
- unsubscribe();
- await manager.setEnabled('rocket-launches', false);
++ await manager.setEnabled('radio', false);
+ }
+ assert.equal(h.timers.size, 0);
+ });
+}
+
- for (const [chooserIndex, providerDropdown] of [false, true].entries()) {
- for (const [phaseIndex, phase] of [
- 'prepared',
- 'preflight',
- 'settling',
- ].entries()) {
- test(`H${55 + chooserIndex * 3 + phaseIndex} native Radio cancellation: ${phase} chooser=${providerDropdown} preserves selection truth and prevents stale speaker transfer`, async () => {
- const viewer = viewerFixture();
- const manager = new DataLayerManager(viewer);
- const prepared = deferred();
- const settleResult = deferred();
- const playbackReady = deferred();
- let playCalls = 0;
- let stopCalls = 0;
- let selections = 0;
- let activeOptions;
- const state = {
- stationCount: 2,
- selected: null,
- audioState: 'stopped',
- voiceDucked: false,
- };
- const radio = {
- async init() {},
- async enable() {},
- async disable() {},
- async update() {},
- getStats: () => ({ count: 2 }),
- getUIState: () => ({ ...state }),
- setVoiceDucked(value) {
- state.voiceDucked = value;
- },
- pause() {
- state.audioState = 'paused';
- },
- subscribePlaybackControls() {
- return () => {};
- },
- selectRequestedStation(_criteria, options) {
- assert.equal(options.autoplay, false);
- selections++;
- state.selected = { id: 'station-1', name: 'Station One' };
- return state.selected;
- },
- playForVoice() {
- playCalls++;
- return playbackReady.promise;
- },
- stopPlayback() {
- stopCalls++;
- state.audioState = 'stopped';
- },
- };
- manager.register({
- id: 'radio',
- name: 'Radio',
- updateInterval: -1,
- ...radio,
- });
- const runner = createGevActionRunner({ viewer, dataManager: manager });
- let h;
- let preflight;
- const session = createVoiceSession({
- providerDropdown: () => providerDropdown,
- runner: async (name, args, options) => {
- activeOptions = options;
- const result = await runner(name, args, options);
- prepared.resolve(result);
- if (phase === 'settling') await settleResult.promise;
- return result;
- },
- createAdapter: (shared) => {
- h = harness({ ...shared, dataManager: manager, radioLayer: radio });
- return {
- start: (settings) => h.c.start(settings),
- stop: (settings) => h.c.stop(settings),
- sendText: (text) => h.c.sendTextCommand(text),
- sendMapEvent: (event) => h.c.notifyMapEvent(event),
- };
- },
- });
- try {
- await session.start();
- const ws = h.sockets[0];
- assert.equal(session.sendText('Select Station One on Radio'), true);
- request(ws, 'prepared-radio', 'control_radio', {
- action: 'select',
- stationQuery: 'Station One',
- });
- const actual = await prepared.promise;
- assert.equal(actual.ok, true);
- assert.equal(actual.radioPlaybackRequested, true);
- assert.equal(actual.stationId, 'station-1');
- assert.equal(manager.isEnabled('radio'), true);
- if (phase !== 'settling') {
- await h.c.toolQueue;
- assert.ok(h.c.radio.pendingRadioPlaybackResult);
- }
- if (phase === 'preflight') {
- preflight = h.c.radio.startPendingRadioHandoff();
- assert.equal(h.c.radio.radioHandoffInFlight, true);
- assert.equal(playCalls, 1);
- }
- // Native call ownership revokes only this deferred playback. No caption
- // parsing or caption-driven provider policy participates in cancellation.
- ws.message({ toolCallCancellation: { ids: ['prepared-radio'] } });
- if (phase === 'settling')
- assert.equal(activeOptions.signal.aborted, true);
- settleResult.resolve();
- await h.c.toolQueue;
- assert.equal(h.c.radio.pendingRadioPlaybackResult, null);
- assert.equal(h.c.radio.radioHandoffInFlight, false);
- assert.equal(manager.isEnabled('radio'), true);
- assert.equal(state.selected.id, 'station-1');
- assert.equal(selections, 1);
- const modelResult = responseFor(ws, 'prepared-radio');
- if (phase === 'settling')
- assert.equal(
- modelResult,
- undefined,
- 'cancelled active call never sends a late result',
- );
- else {
- assert.equal(modelResult.ok, true);
- assert.equal(modelResult.stationId, 'station-1');
- }
- const stopsAfterCancellation = stopCalls;
- assert.equal(stopsAfterCancellation, phase === 'preflight' ? 1 : 0);
- drainRadioReply(h);
- playbackReady.resolve(true);
- await preflight;
- await tick();
- assert.equal(
- playCalls,
- phase === 'preflight' ? 1 : 0,
- 'drain cannot revive cancelled playback',
- );
- assert.equal(h.c.isActive(), true, 'late readiness cannot stop voice');
- assert.equal(h.c.radio.radioHandoffInFlight, false);
- assert.equal(h.c.pendingTools, 0);
- assert.equal(h.c.tools.size, 0);
- assert.equal(session.sendText('Play radio'), true);
- request(ws, 'fresh-radio', 'control_radio', { action: 'play' });
- await h.c.toolQueue;
- assert.ok(h.c.radio.pendingRadioPlaybackResult);
- drainRadioReply(h);
- await tick();
- assert.equal(playCalls, phase === 'preflight' ? 2 : 1);
- assert.equal(
- h.c.isActive(),
- false,
- 'fresh typed Radio handoff alone ends voice',
- );
- } finally {
- settleResult.resolve();
- playbackReady.resolve(false);
- session.destroy();
- await preflight;
- runner.dispose();
- await manager.setEnabled('radio', false);
- }
- assert.equal(h.timers.size, 0);
- });
- }
- }
-
+// A stronger Radio control skips the ordered queue. An older Radio call still
+// queued behind a slow sibling must not start after that control succeeded,
+// while a failed control or a later call in the same turn keeps its order.
+for (const [label, ids, stopOk, expectPending] of [
+ [
+ 'older queued select is revoked by a later successful stop',
+ ['slow', 'sel', 'stop'],
+ true,
+ false,
+ ],
+ [
+ 'a failed stop leaves the older queued select current',
+ ['slow', 'sel', 'stop'],
+ false,
+ true,
+ ],
+ [
+ 'a select after the stop in the same turn still runs',
+ ['slow', 'stop', 'sel'],
+ true,
+ true,
+ ],
+]) {
+ test(`stronger Radio ordering: ${label}`, async () => {
+ const viewer = viewerFixture();
+ const manager = new DataLayerManager(viewer);
+ const state = {
+ stationCount: 2,
+ selected: { id: 'existing', name: 'Existing' },
+ audioState: 'stopped',
+ };
+ const radio = {
+ id: 'radio',
+ name: 'Radio',
+ updateInterval: -1,
+ async init() {},
+ async enable() {},
+ async disable() {},
+ async update() {},
+ getStats: () => ({ count: 2 }),
+ getUIState: () => ({ ...state }),
+ setVoiceDucked() {},
+ pause() {
+ state.audioState = 'paused';
+ return true;
+ },
+ stopPlayback() {
+ state.audioState = 'stopped';
+ return stopOk;
+ },
+ selectRequestedStation() {
+ state.selected = { id: 'late', name: 'Late' };
+ return state.selected;
+ },
+ async playForVoice() {
+ return true;
+ },
+ subscribePlaybackControls: () => () => {},
+ };
+ manager.register(radio);
+ const runner = createGevActionRunner({
+ viewer,
+ dataManager: manager,
+ placeSearch: {
+ async geocode() {
+ return { place: { lat: 10, lng: 20, label: 'Place' } };
+ },
+ },
+ });
+ const slow = deferred();
+ const h = harness({
+ dataManager: manager,
+ radioLayer: radio,
+ async runAction(name, args, options) {
+ if (name === 'slow_sibling') {
+ await slow.promise;
+ return { ok: true, action: 'slow_sibling' };
+ }
+ if (name === 'control_radio' && args.action === 'stop' && !stopOk)
+ return {
+ ok: false,
+ action: 'control_radio',
+ error: 'Radio stop failed',
+ };
+ return runner(name, args, options);
+ },
+ });
+ const calls = {
+ slow: { id: 'slow', name: 'slow_sibling', args: {} },
+ sel: {
+ id: 'sel',
+ name: 'control_radio',
+ args: { action: 'select', locationQuery: 'Place' },
+ },
+ stop: { id: 'stop', name: 'control_radio', args: { action: 'stop' } },
+ };
+ try {
+ await manager.setEnabled('radio', true);
+ await h.c.start();
+ const ws = h.sockets[0];
+ speechTurn(ws);
+ ws.message({ toolCall: { functionCalls: ids.map((id) => calls[id]) } });
+ await tick();
+ assert.equal(
+ responseFor(ws, 'stop')?.ok,
+ stopOk,
+ 'stop settles without waiting',
+ );
+ slow.resolve();
+ await h.c.toolQueue;
+ await tick();
+ assert.equal(
+ Boolean(h.c.radio.pendingRadioPlaybackResult),
+ expectPending,
+ );
+ assert.equal(responseFor(ws, 'sel')?.ok, expectPending);
+ } finally {
+ slow.resolve();
+ h.c.stop();
+ runner.dispose();
+ await manager.setEnabled('radio', false);
+ }
+ assert.equal(h.timers.size, 0);
+ });
+}
diff --cc src/voice/geminiNativeRecovery.test.mjs
index 2871ea0c5,000000000..10d23a609
mode 100644,000000..100644
--- a/src/voice/geminiNativeRecovery.test.mjs
+++ b/src/voice/geminiNativeRecovery.test.mjs
@@@ -1,601 -1,0 +1,280 @@@
+import test from 'node:test';
+import assert from 'node:assert/strict';
- import { harness, tick, deferred } from './geminiNativeHarness.mjs';
- import { createGevActionRunner } from './gevActions.js';
+import {
- initialVoiceCardState,
- reduceVoiceCard,
- voiceCardView,
- } from './voiceCardPresentation.js';
- import { readVoiceUserTurnText } from './userTurnIntent.js';
++ harness,
++ tick,
++ deferred,
++} from '../testSupport/geminiNativeHarness.mjs';
++import { createGevActionRunner } from './gevActions.js';
+
+const tool = (ws, id) =>
+ ws.message({
+ toolCall: {
+ functionCalls: [
+ {
+ id,
+ name: 'adjust_camera_zoom',
+ args: { direction: 'in', amount: 'little' },
+ },
+ ],
+ },
+ });
+const caption = (ws, text) =>
+ ws.message({ serverContent: { inputTranscription: { text } } });
+const onset = (ws) => {
+ ws.message({ voiceActivity: { type: 'ACTIVITY_START' } });
+ ws.message({ voiceActivity: { type: 'ACTIVITY_END' } });
+};
+const complete = (ws) => ws.message({ serverContent: { turnComplete: true } });
+const oldAudio = {
+ serverContent: {
+ modelTurn: {
+ parts: [
+ {
+ inlineData: {
+ data: 'AAAA',
+ mimeType: 'audio/pcm;rate=24000',
+ },
+ },
+ ],
+ },
+ },
+};
+const outputs = (ws) =>
+ ws.sent.flatMap((m) => m.toolResponse?.functionResponses || []);
+
+// Socket/media are deterministic. Mutations use the production action runner.
+function fixture({ holdFirst = false } = {}) {
+ const state = { height: 1000, renders: 0, providerWrites: [], panels: [] };
+ const position = { x: 6379137, y: 0, z: 0 };
+ const viewer = {
+ clock: { onTick: { addEventListener: () => () => {} } },
+ camera: {
+ positionWC: position,
+ positionCartographic: { height: 1000 },
+ moveEnd: { addEventListener() {} },
+ cancelFlight() {},
+ zoomIn(n) {
+ position.x -= n;
+ state.height -= n;
+ this.positionCartographic.height = state.height;
+ },
+ zoomOut(n) {
+ position.x += n;
+ state.height += n;
+ this.positionCartographic.height = state.height;
+ },
+ },
+ scene: {
+ canvas: {
+ clientWidth: 800,
+ clientHeight: 600,
+ addEventListener() {},
+ removeEventListener() {},
+ },
+ requestRender() {
+ state.renders++;
+ },
+ },
+ };
+ const runner = createGevActionRunner({
+ viewer,
+ dataManager: { layers: new Map() },
+ styleManager: {
+ setVoiceProvider: (p) => state.providerWrites.push(p),
+ setPanelCollapsed: (...args) => state.panels.push(args),
+ },
+ });
+ const entered = [];
+ const gate = deferred();
+ const h = harness({
+ runAction: async (name, args, options) => {
+ entered.push({ name, args, options });
+ if (holdFirst && entered.length === 1) await gate.promise;
+ if (!options.isCurrent())
+ return { ok: false, action: name, changed: false };
+ return runner(name, args, options);
+ },
+ });
+ return {
+ ...h,
+ state,
+ entered,
+ gate,
+ close() {
+ gate.resolve();
+ h.c.stop();
+ runner.dispose();
+ assert.equal(h.timers.size, 0);
+ assert.deepEqual(state.providerWrites, []);
+ assert.deepEqual(state.panels, []);
+ },
+ };
+}
+
+for (const [id, order] of [
+ ['H20', 'before-boundary'],
+ ['H21', 'after-boundary'],
+]) {
+ test(`native replacement ${id}: ${order} tool respects retired output and next onset recovers`, async () => {
+ const h = fixture();
+ try {
+ await h.c.start();
+ const ws = h.sockets[0];
+ ws.message(oldAudio);
+ onset(ws);
+ caption(ws, 'zoom in');
+ if (order === 'before-boundary') {
+ tool(ws, 'ambiguous-before');
+ await tick();
+ assert.equal(h.state.height, 1000);
+ assert.equal(h.entered.length, 0);
+ assert.equal(outputs(ws).length, 0);
+ }
+ ws.message({ serverContent: { interrupted: true, turnComplete: true } });
+ if (order === 'after-boundary') {
+ tool(ws, 'native-after');
+ await h.c.toolQueue;
+ assert.equal(h.state.height, 750);
+ assert.equal(h.entered.length, 1);
+ assert.equal(outputs(ws).at(-1).response.ok, true);
+ complete(ws);
+ }
+ onset(ws);
+ caption(ws, 'zoom in');
+ tool(ws, 'fresh-clean-onset');
+ await h.c.toolQueue;
+ assert.equal(h.state.height, order === 'before-boundary' ? 750 : 562.5);
+ assert.equal(h.entered.length, order === 'before-boundary' ? 1 : 2);
+ assert.equal(h.entered.at(-1).options.userTurn, undefined);
+ assert.equal(h.c.pendingTools, 0);
+ assert.equal(
+ outputs(ws).some((o) => o.id === 'ambiguous-before'),
+ false,
+ );
+ assert.equal(
+ outputs(ws).find((o) => o.id === 'fresh-clean-onset').response.ok,
+ true,
+ );
+ } finally {
+ h.close();
+ }
+ });
+}
+
+test('native replacement H30: ordinary tools run promptly and late caption fragments cannot strand siblings', async () => {
+ const h = fixture();
+ try {
+ await h.c.start();
+ const ws = h.sockets[0];
+ onset(ws);
+ caption(ws, 'switch to');
+ tool(ws, 'ordinary-before-caption-resolution');
+ await tick();
+ await h.c.toolQueue;
+ assert.equal(h.state.height, 750);
+ assert.equal(h.c.pendingTools, 0);
+ h.advance(1499);
+ caption(ws, 'Austin');
+ h.advance(5000);
+ tool(ws, 'released-sibling');
+ await h.c.toolQueue;
+ assert.equal(h.state.height, 562.5);
+ assert.equal(h.entered.length, 2);
+ assert.equal(
+ h.entered.every((c) => c.options.userTurn === undefined),
+ true,
+ );
+ assert.equal(outputs(ws).length, 2);
+ assert.equal(
+ outputs(ws).every((o) => o.response.ok),
+ true,
+ );
+ assert.equal(h.c.pendingTools, 0);
+ assert.equal(h.c.status, 'listening');
+ } finally {
+ h.close();
+ }
+});
+
+for (const [id, exit] of [
+ ['H32', 'stop'],
+ ['H33', 'restart'],
+ ['H34', 'new-input'],
+]) {
+ test(`native replacement ${id}: ${exit} retires owned in-flight work and late callbacks`, async () => {
+ const h = fixture({ holdFirst: true });
+ try {
+ await h.c.start();
+ let ws = h.sockets[0];
+ onset(ws);
+ caption(ws, 'switch to');
+ tool(ws, 'old-owned-action');
+ await tick();
+ assert.equal(h.entered.length, 1);
+ assert.equal(h.c.pendingTools, 1);
+ assert.equal(h.state.height, 1000);
+ const oldWork = h.c.toolQueue;
+ const oldMessage = ws.onmessage;
+ const oldOwner = h.entered[0].options;
+ if (exit === 'new-input') h.c.sendTextCommand('zoom out');
+ else h.c.stop();
+ assert.equal(oldOwner.signal.aborted, true);
+ assert.equal(oldOwner.isCurrent(), false);
+ if (exit === 'restart') {
+ await h.c.start();
+ ws = h.sockets.at(-1);
+ }
+ if (exit !== 'new-input')
+ oldMessage({
+ data: JSON.stringify({
+ toolCall: {
+ functionCalls: [
+ {
+ id: 'late-old-call',
+ name: 'adjust_camera_zoom',
+ args: { direction: 'in' },
+ },
+ ],
+ },
+ }),
+ });
+ caption(ws, 'Gemini');
+ h.advance(1500);
+ h.gate.resolve();
+ await oldWork;
+ await tick();
+ assert.equal(h.state.height, 1000);
+ assert.equal(h.c.pendingTools, 0);
+ assert.equal(
+ outputs(ws).some(
+ (o) => o.id === 'old-owned-action' || o.id === 'late-old-call',
+ ),
+ false,
+ );
+ if (exit === 'stop') {
+ assert.equal(h.c.status, 'idle');
+ assert.equal(h.c.isActive(), false);
+ } else {
+ if (exit === 'new-input') {
+ ws.message({
+ serverContent: { interrupted: true, turnComplete: true },
+ });
+ } else h.c.sendTextCommand('zoom out');
+ tool(ws, 'fresh-after-retirement');
+ await h.c.toolQueue;
+ assert.equal(h.state.height, 750);
+ assert.equal(h.entered.length, 2);
+ assert.equal(
+ outputs(ws).find((o) => o.id === 'fresh-after-retirement').response
+ .ok,
+ true,
+ );
+ assert.equal(h.c.pendingTools, 0);
+ assert.equal(h.c.isActive(), true);
+ }
+ } finally {
+ h.close();
+ }
+ });
+}
-
- function captionFixture() {
- let card = initialVoiceCardState();
- const events = [];
- const h = harness({
- emit(event) {
- events.push(event);
- card = reduceVoiceCard(card, event);
- },
- });
- return {
- ...h,
- events,
- view: () => voiceCardView(card),
- close() {
- h.c.stop();
- assert.equal(h.timers.size, 0);
- },
- };
- }
-
- const startSpeech = (ws) =>
- ws.message({ voiceActivity: { type: 'ACTIVITY_START' } });
- const endSpeech = (ws) =>
- ws.message({ voiceActivity: { type: 'ACTIVITY_END' } });
- const speak = (ws, text) =>
- ws.message({
- serverContent: {
- outputTranscription: { text },
- modelTurn: {
- parts: [
- {
- inlineData: {
- data: 'AAAA',
- mimeType: 'audio/pcm;rate=24000',
- },
- },
- ],
- },
- },
- });
- const zoom = (ws, id) =>
- ws.message({
- toolCall: {
- functionCalls: [
- {
- id,
- name: 'adjust_camera_zoom',
- args: { direction: 'in', amount: 'little' },
- },
- ],
- },
- });
-
- test('native captions: interrupted request cannot overwrite fragmented successor preview at completion', async () => {
- const h = captionFixture();
- try {
- await h.c.start();
- const ws = h.sockets[0];
- startSpeech(ws);
- caption(ws, 'Can you explain the data layers in GEV?');
- endSpeech(ws);
- speak(ws, 'The app has several data layers.');
-
- startSpeech(ws);
- ws.message({ serverContent: { interrupted: true } });
- complete(ws);
- assert.equal(h.view().user.text, '…');
- assert.equal(h.view().assistant.text, '');
-
- for (const text of ['Zoom ', 'in ', 'a little.']) caption(ws, text);
- endSpeech(ws);
- assert.equal(h.view().user.text, 'Zoom in a little.');
- zoom(ws, 'successor-zoom');
- await h.c.toolQueue;
- assert.equal(h.calls.length, 1);
- assert.deepEqual(h.calls[0].args, { direction: 'in', amount: 'little' });
- assert.equal(h.calls[0].options.userTurn, undefined);
- assert.equal(
- ws.sent.some((m) =>
- m.toolResponse?.functionResponses?.some(
- (call) => call.id === 'successor-zoom' && call.response.ok,
- ),
- ),
- true,
- );
- speak(ws, 'Zooming in ');
- speak(ws, 'slightly.');
- complete(ws);
- h.captures[0].drain();
- assert.equal(h.view().user.text, 'Zoom in a little.');
- assert.equal(h.view().assistant.text, 'Zooming in slightly.');
- assert.equal(
- h.events.some(
- (e) => e.type === 'transcript' && e.role === 'user' && e.final,
- ),
- false,
- );
- assert.equal(
- h.events.some(
- (e) =>
- e.type === 'transcript' &&
- e.role === 'assistant' &&
- e.final &&
- e.text === 'Zooming in slightly.',
- ),
- true,
- );
- const segments = h.events.filter((e) => e.type === 'user-input-segment');
- assert.deepEqual(
- segments.map((e) => e.text),
- ['Can you explain the data layers in GEV?', 'Zoom ', 'in ', 'a little.'],
- );
- assert.equal(
- segments.every(
- (e) => e.inputId === null && e.inputScope === 'unattributed-segment',
- ),
- true,
- );
- const captions = h.events.filter(
- (e) => e.type === 'transcript' && e.role === 'user',
- );
- assert.equal(
- captions.every(
- (e) =>
- e.delta === true &&
- e.final === false &&
- e.attribution === 'unverified' &&
- e.responseId === null,
- ),
- true,
- );
- } finally {
- h.close();
- }
- });
-
- test('native captions: duplicate activity and interrupted acknowledgments preserve received fragments', async () => {
- const h = captionFixture();
- try {
- await h.c.start();
- const ws = h.sockets[0];
- speak(ws, 'Old reply');
- startSpeech(ws);
- caption(ws, 'Zoom ');
- startSpeech(ws);
- ws.message({ serverContent: { interrupted: true } });
- ws.message({ serverContent: { interrupted: true } });
- assert.equal(h.view().user.text, 'Zoom');
- caption(ws, 'in ');
- complete(ws);
- caption(ws, 'a little.');
- endSpeech(ws);
- assert.equal(h.view().user.text, 'Zoom in a little.');
- complete(ws);
- assert.equal(h.view().user.text, 'Zoom in a little.');
- } finally {
- h.close();
- }
- });
-
- test('native captions: no new caption means successor completion cannot replay old request', async () => {
- const h = captionFixture();
- try {
- await h.c.start();
- const ws = h.sockets[0];
- caption(ws, 'Explain the data layers.');
- speak(ws, 'Several layers are available.');
- startSpeech(ws);
- ws.message({ serverContent: { interrupted: true } });
- complete(ws);
- zoom(ws, 'uncaptioned-successor');
- await h.c.toolQueue;
- complete(ws);
- assert.equal(h.calls.length, 1);
- assert.equal(h.calls[0].options.userTurn, undefined);
- assert.equal(h.view().user.text, '…');
- } finally {
- h.close();
- }
- });
-
- test('native captions: advisory arrival order is displayed without synthesizing final speech ownership', async () => {
- const h = captionFixture();
- try {
- await h.c.start();
- const ws = h.sockets[0];
- // Captions have no input id: presentation does not guess their semantic order.
- caption(ws, 'little. ');
- caption(ws, 'Zoom in a ');
- assert.equal(h.view().user.text, 'little. Zoom in a');
- complete(ws);
- assert.equal(h.view().user.text, 'little. Zoom in a');
- assert.equal(
- h.events.some((e) => e.type === 'user-input-final'),
- false,
- );
- assert.equal(
- h.events.some((e) => e.type === 'response-start'),
- false,
- );
- assert.equal(
- h.events.some((e) => e.role === 'user' && e.final),
- false,
- );
- } finally {
- h.close();
- }
- });
-
- test('native captions: local PTT and typed boundaries clear preview without changing typed authority', async () => {
- const h = captionFixture();
- try {
- await h.c.start();
- const ws = h.sockets[0];
- caption(ws, 'Older speech.');
- assert.equal(h.c.bargeIn(), true);
- assert.equal(h.view().user.text, '…');
- caption(ws, 'Zoom ');
- caption(ws, 'in a little.');
- assert.equal(h.view().user.text, 'Zoom in a little.');
- complete(ws);
- assert.equal(h.view().user.text, 'Zoom in a little.');
-
- assert.equal(h.c.sendTextCommand('Zoom in a little.'), true);
- assert.equal(h.view().user.text, '…');
- caption(ws, 'unrelated advisory speech');
- zoom(ws, 'typed-zoom');
- await h.c.toolQueue;
- assert.equal(h.calls.length, 1);
- assert.equal(
- readVoiceUserTurnText(h.calls[0].options.userTurn),
- 'Zoom in a little.',
- );
- complete(ws);
- assert.equal(h.view().user.text, 'unrelated advisory speech');
- } finally {
- h.close();
- }
- });
-
- test('native captions: Stop and restart do not retain old display fragments or accept old socket captions', async () => {
- const h = captionFixture();
- try {
- await h.c.start();
- const old = h.sockets[0];
- caption(old, 'Old partial ');
- h.c.stop();
- assert.equal(h.view().visible, false);
- await h.c.start();
- const ws = h.sockets[1];
- caption(ws, 'Zoom ');
- caption(old, 'stale caption');
- caption(ws, 'in a little.');
- complete(ws);
- assert.equal(h.view().user.text, 'Zoom in a little.');
- assert.equal(h.tracks[0].readyState, 'ended');
- assert.equal(h.captures[0].closed, true);
- } finally {
- h.close();
- }
- });
-
- for (const split of [false, true]) {
- test(`native captions: server-only interruption retains ${split ? 'a leading fragment alongside its successor' : 'a complete pre-marker caption'} as recent speech`, async () => {
- const h = captionFixture();
- try {
- await h.c.start();
- const ws = h.sockets[0];
- speak(ws, 'An earlier assistant reply.');
- caption(ws, split ? 'Zoom ' : 'Zoom in a little.');
- ws.message({ serverContent: { interrupted: true } });
- assert.equal(h.view().user.text, '…');
- assert.equal(h.view().recentSpeech.text, split ? 'Zoom' : 'Zoom in a little.');
- assert.equal(h.view().recentSpeech.visible, true);
- ws.message({ serverContent: { interrupted: true } });
- assert.equal(h.view().recentSpeech.text, split ? 'Zoom' : 'Zoom in a little.');
- if (split) caption(ws, 'in a little.');
- complete(ws);
- zoom(ws, 'server-only-caption');
- await h.c.toolQueue;
- speak(ws, 'Zooming in slightly.');
- complete(ws);
- h.captures[0].drain();
- assert.equal(h.view().recentSpeech.text, split ? 'Zoom' : 'Zoom in a little.');
- assert.equal(h.view().user.text, split ? 'in a little.' : '…');
- assert.equal(h.view().assistant.text, 'Zooming in slightly.');
- assert.equal(h.calls[0].options.userTurn, undefined);
- assert.equal(h.events.some((e) => e.role === 'user' && e.final), false);
- } finally {
- h.close();
- }
- });
- }
-
- for (const boundary of ['native-onset', 'push-to-talk', 'typed', 'stop']) {
- test(`native captions: ${boundary} clears recent speech retained by a server-only acknowledgment`, async () => {
- const h = captionFixture();
- try {
- await h.c.start();
- const ws = h.sockets[0];
- speak(ws, 'Old response');
- caption(ws, 'Earlier advisory speech');
- ws.message({ serverContent: { interrupted: true } });
- assert.equal(h.view().recentSpeech.visible, true);
- // The native onset must clear presentation even while retirement is
- // already pending and therefore does not emit another interruption.
- if (boundary === 'native-onset') startSpeech(ws);
- else if (boundary === 'push-to-talk') h.c.bargeIn();
- else if (boundary === 'typed') h.c.sendTextCommand('Zoom in a little.');
- else h.c.stop();
- assert.equal(h.view().recentSpeech.visible, false);
- assert.equal(h.view().recentSpeech.text, '');
- assert.equal(h.view().user.text, '…');
- } finally {
- h.close();
- }
- });
- }
diff --cc src/voice/geminiPacketOwnership.test.mjs
index 000000000,000000000..4188cf7be
new file mode 100644
--- /dev/null
+++ b/src/voice/geminiPacketOwnership.test.mjs
@@@ -1,0 -1,0 +1,529 @@@
++import test from 'node:test';
++import assert from 'node:assert/strict';
++import {
++ nativeIntegrationFixture,
++ assertSuccessfulZoom,
++ turnOfEventLoop,
++} from '../testSupport/geminiIntegrationFixture.mjs';
++
++const options = { concurrency: false, timeout: 5000 };
++const OLD_TEXT = 'Old packet caption.';
++const OLD_PCM = 'AAABAA==';
++const POST_TOOL_PCM = 'AgADAA==';
++const OLD_CALL = 'old-coalesced-call';
++
++function coalescedPacket(callId = OLD_CALL) {
++ return {
++ serverContent: {
++ outputTranscription: { text: OLD_TEXT },
++ modelTurn: {
++ parts: [
++ { inlineData: { data: OLD_PCM, mimeType: 'audio/pcm;rate=24000' } },
++ ],
++ },
++ turnComplete: true,
++ },
++ toolCall: {
++ functionCalls: [
++ {
++ id: callId,
++ name: 'adjust_camera_zoom',
++ args: { direction: 'in', amount: 'little' },
++ },
++ ],
++ },
++ };
++}
++
++// Local test observations wrap only injected device fakes and the actual
++// scheduler methods, delegating unchanged. No frozen fixture file is modified.
++function observePacketEffects(h) {
++ const played = [];
++ const narration = { audible: 0, toolStarted: 0, toolFinished: 0 };
++ const createAudio = h.controller.createAudio;
++ h.controller.createAudio = (callbacks) => {
++ const audio = createAudio(callbacks);
++ const play = audio.play.bind(audio);
++ audio.play = (data, mimeType) => {
++ played.push({ audio, data, mimeType });
++ return play(data, mimeType);
++ };
++ return audio;
++ };
++ for (const method of Object.keys(narration)) {
++ const invoke = h.controller.narration[method].bind(h.controller.narration);
++ h.controller.narration[method] = (...args) => {
++ narration[method]++;
++ return invoke(...args);
++ };
++ }
++ return { played, narration };
++}
++
++function packetState(h) {
++ const c = h.controller;
++ return {
++ epoch: c.epoch,
++ inputGeneration: c.inputGeneration,
++ turn: c.turn,
++ completedTurns: c.completedTurns,
++ pendingTools: c.pendingTools,
++ modelComplete: c.modelComplete,
++ pendingCompletionStatus: c.pendingCompletionStatus,
++ postToolOutput: c.postToolOutput,
++ modelSpoke: c.modelSpoke,
++ assistant: c.transcripts.assistant,
++ replyPending: c.replyPending,
++ retiredReplyPending: c.retiredReplyPending,
++ typedText: c.typedIntent?.text ?? null,
++ typedResponseId: c.typedIntent?.responseId ?? null,
++ narrationTools: c.narration.state().tools,
++ narrationTimers: c.narration.state().pendingTimers,
++ ownedTimers: h.clock.timers.size,
++ };
++}
++
++const completions = (h) =>
++ h.events.filter((event) => event.type === 'completion');
++const toolEvents = (h, callId) =>
++ h.events.filter(
++ (event) =>
++ ['action-call', 'action-result', 'progress'].includes(event.type) &&
++ event.callId === callId,
++ );
++
++function assertOldRemainderAbsent(h, observed) {
++ assert.equal(h.state.height, 1000);
++ assert.deepEqual(h.state.zooms, []);
++ assert.deepEqual(h.runnerCalls, []);
++ assert.deepEqual(toolEvents(h, OLD_CALL), []);
++ assert.deepEqual(observed.played, []);
++ assert.deepEqual(observed.narration, {
++ audible: 0,
++ toolStarted: 0,
++ toolFinished: 0,
++ });
++ assert.deepEqual(completions(h), []);
++ assert.equal(h.controller.completedTurns, 0);
++ assert.equal(h.controller.pendingTools, 0);
++ assert.equal(
++ h.events.filter(
++ (event) =>
++ event.type === 'transcript' &&
++ event.role === 'assistant' &&
++ event.final &&
++ event.text === OLD_TEXT,
++ ).length,
++ 0,
++ );
++ for (const socket of h.sockets)
++ assert.equal(
++ h.outputs(socket).some((output) => output.id === OLD_CALL),
++ false,
++ );
++}
++
++for (const mode of ['Stop', 'Stop then Start', 'typed successor']) {
++ test(
++ `assistant transcript observer ${mode} fences the rest of a coalesced native packet`,
++ options,
++ async (t) => {
++ const h = nativeIntegrationFixture(t);
++ const observed = observePacketEffects(h);
++ const oldSocket = await h.start();
++ const oldAudio = h.audios[0];
++ h.activity(oldSocket);
++ const before = packetState(h);
++ let reached = false;
++ let restart;
++ let typedAccepted;
++ let afterObserver;
++ const remove = h.session.subscribe((event) => {
++ if (
++ reached ||
++ event.type !== 'transcript' ||
++ event.role !== 'assistant' ||
++ event.final ||
++ event.text !== OLD_TEXT
++ )
++ return;
++ reached = true;
++ if (mode === 'typed successor') {
++ typedAccepted = h.session.sendText('Zoom in for the typed successor');
++ } else {
++ h.session.stop();
++ if (mode === 'Stop then Start') restart = h.session.start();
++ }
++ afterObserver = packetState(h);
++ });
++ oldSocket.message(coalescedPacket());
++ remove();
++ assert.equal(
++ reached,
++ true,
++ 'the actual common transcript observer ran synchronously',
++ );
++ // A retired reply may consume its own received terminal, but cannot
++ // complete or overwrite the successor. Stop/restart permits no old writes.
++ const afterPacketExpected =
++ mode === 'typed successor'
++ ? {
++ ...afterObserver,
++ retiredReplyPending: false,
++ ownedTimers: afterObserver.ownedTimers - 1,
++ }
++ : afterObserver;
++ assert.deepEqual(packetState(h), afterPacketExpected);
++ await h.controller.toolQueue;
++ await turnOfEventLoop();
++ if (restart) await restart;
++ assertOldRemainderAbsent(h, observed);
++
++ let successorSocket;
++ if (mode === 'typed successor') {
++ assert.equal(typedAccepted, true);
++ assert.equal(
++ h.controller.epoch,
++ before.epoch,
++ 'typed replacement shares the socket epoch',
++ );
++ assert.ok(h.controller.inputGeneration > before.inputGeneration);
++ assert.ok(h.controller.turn > before.turn);
++ assert.deepEqual(packetState(h), afterPacketExpected);
++ assert.equal(
++ h.controller.typedIntent.text,
++ 'Zoom in for the typed successor',
++ );
++ assert.equal(h.controller.replyPending, true);
++ assert.equal(h.controller.retiredReplyPending, false);
++ assert.equal(oldAudio.closed, false);
++ const typedMessages = oldSocket.sent.filter((message) =>
++ message.clientContent?.turns?.some((turn) =>
++ turn.parts?.some(
++ (part) => part.text === 'Zoom in for the typed successor',
++ ),
++ ),
++ );
++ assert.equal(typedMessages.length, 1);
++ // The received packet already carried the old terminal. No extra
++ // provider boundary may be invented before testing the actual successor.
++ assert.equal(h.controller.retiredBoundaryWait, null);
++ assert.equal(h.controller.cancelledCalls.has(OLD_CALL), true);
++ assert.equal(h.controller.replyPending, true);
++ assert.equal(h.controller.completedTurns, 0);
++ assert.deepEqual(completions(h), []);
++ successorSocket = oldSocket;
++ } else {
++ assert.equal(oldSocket.closed, true);
++ assert.equal(oldAudio.closed, true);
++ assert.equal(h.controller.narration.state().tools, 0);
++ assert.equal(h.controller.narration.state().pendingTimers, 0);
++ assert.equal(h.clock.timers.size, 0);
++ if (mode === 'Stop') {
++ assert.equal(h.session.state, 'idle');
++ successorSocket = await h.start();
++ } else {
++ assert.equal(h.session.state, 'listening');
++ assert.equal(h.sockets.length, 2);
++ assert.equal(h.audios.length, 2);
++ assert.notEqual(h.audios[1], oldAudio);
++ assert.equal(h.audios[1].closed, false);
++ assert.equal(h.audios[1].pending, false);
++ successorSocket = h.sockets[1];
++ }
++ h.activity(successorSocket);
++ }
++ await h.tool('owned-after-packet-cancel', successorSocket);
++ assertSuccessfulZoom(
++ h,
++ successorSocket,
++ 'owned-after-packet-cancel',
++ 1000,
++ );
++ assert.equal(h.state.zooms.length, 1);
++ assert.equal(h.runnerCalls.length, 1);
++ assert.equal(
++ h.outputs(successorSocket).some((output) => output.id === OLD_CALL),
++ false,
++ );
++ h.complete(successorSocket);
++ assert.equal(completions(h).length, 1);
++ assert.equal(h.controller.narration.state().tools, 0);
++ assert.equal(h.controller.narration.state().pendingTimers, 0);
++ },
++ );
++}
++
++test(
++ 'ordinary coalesced packet plays and executes once, then completes only after its post-tool reply',
++ options,
++ async (t) => {
++ const h = nativeIntegrationFixture(t);
++ const observed = observePacketEffects(h);
++ const ws = await h.start();
++ h.activity(ws);
++ ws.message(coalescedPacket('ordinary-coalesced'));
++ assert.equal(
++ h.controller.completedTurns,
++ 1,
++ 'first generation terminal is counted once',
++ );
++ assert.equal(h.controller.pendingTools, 1);
++ assert.deepEqual(
++ observed.played.map(({ data }) => data),
++ [OLD_PCM],
++ );
++ assert.equal(observed.played[0].audio, h.audios[0]);
++ assert.deepEqual(completions(h), [], 'tool and playback are still pending');
++ await h.controller.toolQueue;
++ assertSuccessfulZoom(h, ws, 'ordinary-coalesced', 1000);
++ assert.equal(h.controller.pendingTools, 0);
++ assert.equal(observed.narration.toolStarted, 1);
++ assert.equal(observed.narration.toolFinished, 1);
++ assert.equal(h.controller.narration.state().tools, 0);
++ h.audios[0].drain();
++ assert.equal(
++ h.controller.modelComplete,
++ false,
++ 'function response waits for the post-tool generation',
++ );
++ assert.equal(h.controller.completedTurns, 1);
++ assert.deepEqual(
++ completions(h),
++ [],
++ 'draining first-generation PCM cannot finish the tool reply',
++ );
++
++ // The accepted contract has two generations: the function response prompts
++ // a fresh model reply. This boundary is intentional, not a stale-packet fix.
++ ws.message({
++ serverContent: {
++ outputTranscription: { text: 'The requested zoom is complete.' },
++ modelTurn: {
++ parts: [
++ {
++ inlineData: {
++ data: POST_TOOL_PCM,
++ mimeType: 'audio/pcm;rate=24000',
++ },
++ },
++ ],
++ },
++ turnComplete: true,
++ },
++ });
++ assert.equal(h.controller.completedTurns, 2);
++ assert.deepEqual(
++ observed.played.map(({ data }) => data),
++ [OLD_PCM, POST_TOOL_PCM],
++ );
++ assert.deepEqual(
++ completions(h),
++ [],
++ 'post-tool playback must drain before completion',
++ );
++ h.audios[0].drain();
++ assert.equal(completions(h).length, 1);
++ assert.equal(completions(h)[0].status, 'completed');
++ assert.equal(completions(h)[0].spoken, true);
++ assert.equal(completions(h)[0].audioDrained, true);
++ assert.equal(h.controller.pendingCompletionStatus, null);
++ assert.equal(h.controller.narration.state().tools, 0);
++ assert.equal(h.controller.narration.state().pendingTimers, 0);
++ assert.equal(h.clock.timers.size, 0);
++ assert.equal(observed.narration.audible, 2);
++ assert.equal(h.runnerCalls.length, 1);
++ assert.equal(h.state.zooms.length, 1);
++ assert.equal(h.outputs(ws).length, 1);
++ h.audios[0].drain();
++ assert.equal(
++ completions(h).length,
++ 1,
++ 'a duplicate device drain cannot complete twice',
++ );
++ },
++);
++
++// Real native message-type fields are separate packets here; no extra old
++// completion is inserted before the accepted successor.
++const BOUNDARY_OLD = 'Prior reply caption.';
++const BOUNDARY_NEXT = 'Zoom in for the typed successor';
++const boundaryZoomCall = (id) => ({
++ toolCall: {
++ functionCalls: [
++ {
++ id,
++ name: 'adjust_camera_zoom',
++ args: { direction: 'in', amount: 'little' },
++ },
++ ],
++ },
++});
++function boundarySnapshot(h) {
++ const c = h.controller;
++ return {
++ retiredReplyPending: c.retiredReplyPending,
++ retiredBoundaryWait: Boolean(c.retiredBoundaryWait),
++ replyPending: c.replyPending,
++ typedText: c.typedIntent?.text ?? null,
++ completions: h.events.filter((event) => event.type === 'completion').length,
++ };
++}
++
++for (const mode of [
++ 'partial assistant transcript',
++ 'input transcript',
++ 'interruption event',
++ 'listening event',
++ 'final assistant transcript control',
++]) {
++ test(
++ `received native terminal preserves typed successor after ${mode}`,
++ { concurrency: false, timeout: 5000 },
++ async (t) => {
++ const h = nativeIntegrationFixture(t);
++ const ws = await h.start();
++ h.activity(ws);
++ let oldDispatch, gate;
++ const interruptionMode =
++ mode === 'interruption event' || mode === 'listening event';
++ if (interruptionMode) {
++ h.session.sendText('Prior zoom request');
++ gate = h.holdResult('already-committed-old-tool');
++ oldDispatch = h.tool('already-committed-old-tool', ws);
++ await gate.ready;
++ } else if (mode === 'input transcript') {
++ ws.message({
++ serverContent: {
++ outputTranscription: { text: 'Previously emitted output' },
++ },
++ });
++ }
++ let entered = 0,
++ accepted;
++ const remove = h.session.subscribe((event) => {
++ if (entered) return;
++ const matches =
++ mode === 'interruption event'
++ ? event.type === 'interruption' && event.reason === 'user-speech'
++ : mode === 'listening event'
++ ? event.type === 'state' && event.state === 'listening'
++ : mode === 'input transcript'
++ ? event.type === 'transcript' &&
++ event.role === 'user' &&
++ event.text === 'Old input caption'
++ : event.type === 'transcript' &&
++ event.role === 'assistant' &&
++ event.text === BOUNDARY_OLD &&
++ event.final ===
++ (mode === 'final assistant transcript control');
++ if (!matches) return;
++ entered++;
++ accepted = h.session.sendText(BOUNDARY_NEXT);
++ });
++ if (interruptionMode)
++ ws.message({
++ serverContent: { interrupted: true, turnComplete: true },
++ });
++ else
++ ws.message({
++ serverContent: {
++ ...(mode === 'input transcript'
++ ? { inputTranscription: { text: 'Old input caption' } }
++ : {}),
++ outputTranscription: { text: BOUNDARY_OLD },
++ turnComplete: true,
++ },
++ });
++ remove();
++ if (oldDispatch) {
++ await oldDispatch;
++ gate.release();
++ }
++ await turnOfEventLoop();
++ const afterPacket = boundarySnapshot(h);
++ const beforeSuccessorHeight = h.state.height;
++ // No extra synthetic old boundary. This is the next reply to the accepted text.
++ ws.message({
++ serverContent: {
++ outputTranscription: { text: 'Handling your new zoom.' },
++ },
++ });
++ ws.message(boundaryZoomCall('typed-successor-call'));
++ await h.controller.toolQueue;
++ await turnOfEventLoop();
++ ws.message({ serverContent: { turnComplete: true } });
++ const afterSuccessor = boundarySnapshot(h);
++ assert.equal(entered, 1);
++ assert.equal(accepted, true);
++ assert.equal(
++ afterPacket.retiredReplyPending,
++ false,
++ 'received old terminal must settle its retirement',
++ );
++ assert.equal(afterPacket.retiredBoundaryWait, false);
++ assert.equal(afterPacket.typedText, BOUNDARY_NEXT);
++ assert.equal(
++ h.runnerCalls.filter((x) => x.options.callId === 'typed-successor-call')
++ .length,
++ 1,
++ 'accepted typed successor must reach the actual runner',
++ );
++ assert.equal(h.state.height, beforeSuccessorHeight * 0.75);
++ assert.equal(afterSuccessor.completions, 1);
++ assert.equal(afterSuccessor.replyPending, false);
++ assert.equal(
++ h.controller.cancelledCalls.has('typed-successor-call'),
++ false,
++ );
++ },
++ );
++}
++
++for (const terminalAlreadyApplied of [false, true]) {
++ test(
++ `typed reentry retains a genuinely pending boundary when terminal already applied is ${terminalAlreadyApplied}`,
++ options,
++ async (t) => {
++ const h = nativeIntegrationFixture(t);
++ const ws = await h.start();
++ h.activity(ws);
++ let entered = false;
++ const remove = h.session.subscribe((event) => {
++ if (
++ entered ||
++ event.type !== 'transcript' ||
++ event.role !== 'assistant' ||
++ event.text !== 'Boundary control' ||
++ event.final !== terminalAlreadyApplied
++ )
++ return;
++ entered = true;
++ assert.equal(h.session.sendText('First typed replacement'), true);
++ if (terminalAlreadyApplied)
++ assert.equal(h.session.sendText('Second typed replacement'), true);
++ });
++ ws.message({
++ serverContent: {
++ outputTranscription: { text: 'Boundary control' },
++ ...(terminalAlreadyApplied ? { turnComplete: true } : {}),
++ },
++ });
++ remove();
++ assert.equal(entered, true);
++ // With no old terminal received, or when that terminal was consumed
++ // before the observer, a real predecessor boundary is still outstanding.
++ assert.equal(h.controller.retiredReplyPending, true);
++ assert.ok(h.controller.retiredBoundaryWait);
++ assert.equal(completions(h).length, 0);
++ assert.equal(h.runnerCalls.length, 0);
++ ws.message({ serverContent: { turnComplete: true } });
++ assert.equal(h.controller.retiredReplyPending, false);
++ assert.equal(h.controller.retiredBoundaryWait, null);
++ await h.tool('after-real-pending-boundary', ws);
++ assertSuccessfulZoom(h, ws, 'after-real-pending-boundary', 1000);
++ h.complete(ws);
++ assert.equal(completions(h).length, 1);
++ },
++ );
++}
diff --cc src/voice/geminiSession.js
index 5b25ce6f5,000000000..a44347ec8
mode 100644,000000..100644
--- a/src/voice/geminiSession.js
+++ b/src/voice/geminiSession.js
@@@ -1,2336 -1,0 +1,2452 @@@
++import { t, translateKnown } from '../i18n/index.js';
++import { msg } from '../i18n/marker.js';
+import { createGeminiAudio } from './geminiAudio.js';
+import { RealtimeInput } from './realtimeInput.js';
+import { RealtimeRadio } from './realtimeRadio.js';
+import { captureViewportImage } from './realtimeViewport.js';
+import { createNarrationScheduler } from './narration.js';
+import { createEarcon } from './earcon.js';
+import { narrationLabel } from './speech.js';
- import {
- createVoiceUserTurnTracker,
- readVoiceUserTurnInputKind,
- } from './userTurnIntent.js';
- import {
- readVoiceRequestRestriction,
- voiceRequestRestrictionResult,
- } from './providerIntent.js';
- import {
- classifyVoiceTool,
- projectVoiceToolResultForModel,
- shouldStopVoiceAfterToolResult,
- reconcileRadioToolResult,
- toolResultGuidance,
- } from './toolExecutionPolicy.js';
++import { waitForSignal } from '../sources/requestDeadline.js';
++import { readResponseJsonCapped } from '../sources/httpBody.js';
++import { readLayerLifecycleSummary } from './layerSummary.js';
+import {
+ POINTER_OPEN_MIC_RECENT_MS,
+ pointerChip,
+ pointerContextItem,
+} from './pointerContext.js';
+import {
+ hasStructuredViewIdentity,
+ shouldSendViewportImage,
++ shouldStopVoiceAfterRadioTool,
++ responseInstructionForToolResult,
+} from './realtimeProtocol.js';
+
+const SOCKET_PATH =
+ /^\/ws\/google\.ai\.generativelanguage\.v1(?:alpha|beta)\.GenerativeService\.BidiGenerateContentConstrained$/;
+const MAX_BUFFERED_BYTES = 256 * 1024;
+const MAX_CONTROL_BYTES = 1024 * 1024;
+const MAX_CONTROL_MESSAGES = 64;
+const CONTROL_PRESSURE_TIMEOUT_MS = 5_000;
+const CONTROL_POLL_MS = 25;
+const MAX_GO_AWAY_MS = 10 * 60 * 1000;
+const MAX_MESSAGE_LENGTH = 3 * 1024 * 1024;
+const MAX_TOOL_CALLS = 16;
+const MAX_SEEN_CALLS = 256;
+const MAX_CALL_ID_LENGTH = 1024;
+const MAX_MAP_EVENTS = 16;
+const MAX_MAP_CONTEXT_LENGTH = 16000;
+
+/** Only an ephemeral token can be attached to the fixed Google Live endpoint. */
+export function geminiSocketUrl({ token, websocketUrl }) {
+ if (
+ typeof token !== 'string' ||
+ !token.startsWith('auth_tokens/') ||
+ token.length > 8192
+ )
+ throw new Error(
- 'Gemini token response did not include an ephemeral credential',
++ msg('Gemini token response did not include an ephemeral credential'),
+ );
+ let url;
+ try {
+ url = new URL(websocketUrl);
+ } catch {
- throw new Error('Invalid Gemini connection endpoint');
++ throw new Error(msg('Invalid Gemini connection endpoint'));
+ }
+ if (
+ url.protocol !== 'wss:' ||
+ url.hostname !== 'generativelanguage.googleapis.com' ||
+ url.port ||
+ url.username ||
+ url.password ||
+ url.search ||
+ url.hash ||
+ !SOCKET_PATH.test(url.pathname)
+ )
- throw new Error('Invalid Gemini connection endpoint');
++ throw new Error(msg('Invalid Gemini connection endpoint'));
+ url.searchParams.set('access_token', token);
+ return url.href;
+}
+
++// Known local-server failures are translated; unexpected diagnostics stay intact.
++function tokenErrorMessage(error) {
++ switch (error) {
++ case msg('Gemini voice could not connect. Try again.'):
++ case msg('Gemini voice requires a same-origin app request'):
++ case msg('Add a Gemini API key in Provider Settings'):
++ case msg('The Gemini Live model configuration is invalid'):
++ case msg('Gemini voice is starting too often. Try again shortly.'):
++ case msg('Gemini quota is unavailable. Try again later.'):
++ case msg('Gemini access was refused. Check the API key and model access.'):
++ case msg('Gemini Live is unavailable for the configured model.'):
++ case msg('Token request is too large'):
++ case msg('Use an empty JSON token request'):
++ case msg('Method not allowed'):
++ return t(error);
++ default:
++ return error;
++ }
++}
++
+function validCallId(id) {
+ return (
+ typeof id === 'string' &&
+ id.length > 0 &&
+ id.length <= MAX_CALL_ID_LENGTH &&
+ id.trim().length > 0 &&
+ !/[\u0000-\u001f\u007f]/u.test(id)
+ );
+}
+
+function cancelled() {
+ return new DOMException('Voice operation cancelled', 'AbortError');
+}
+
- function awaitWithSignal(promise, signal) {
- return new Promise((resolve, reject) => {
- const abort = () => reject(signal.reason || cancelled());
- signal.addEventListener('abort', abort, { once: true });
- if (signal.aborted) abort();
- Promise.resolve(promise)
- .then(resolve, reject)
- .finally(() => signal.removeEventListener('abort', abort));
- });
++// Match the existing OpenAI/Radio classification; transport ownership stays local.
++function classifyGeminiTool(name, args = {}) {
++ const radioControl = name === 'control_radio';
++ const radioVisibility =
++ name === 'set_layer_visibility' && args.layerId === 'radio';
++ const radioAction = radioControl
++ ? String(args.action || '').toLowerCase()
++ : null;
++ const authorityDomain =
++ radioVisibility || ['enable', 'disable'].includes(radioAction)
++ ? 'visibility'
++ : radioAction === 'status'
++ ? 'query'
++ : radioControl
++ ? 'playback'
++ : null;
++ const stronger =
++ (radioControl && ['disable', 'pause', 'stop'].includes(radioAction)) ||
++ (radioVisibility && args.enabled === false);
++ return {
++ radioControl,
++ radioVisibility,
++ authorityDomain,
++ stronger,
++ abortScope:
++ radioAction === 'disable' || radioVisibility ? 'all' : 'playback',
++ };
+}
+
+/** Gemini owns its socket/media; the common session owns action authorization. */
+export class GeminiSessionController {
+ constructor({
+ emit,
+ runAction,
+ signal,
+ ui,
+ radioLayer = null,
+ dataManager = null,
- providerDropdown = () => false,
+ pointer = null,
+ tokenEndpoint = '/api/gemini/token',
+ startupTimeoutMs = 30_000,
+ inputBoundaryTimeoutMs = 5_000,
+ fetchImpl = (...args) => fetch(...args),
+ WebSocketClass = globalThis.WebSocket,
+ getUserMedia = (settings) => navigator.mediaDevices.getUserMedia(settings),
+ createAudio = createGeminiAudio,
+ createInput = (settings) => new RealtimeInput(settings),
+ createNarration = createNarrationScheduler,
+ createProgressEarcon = createEarcon,
+ captureViewport = captureViewportImage,
+ now = () => Date.now(),
+ setTimer = setTimeout,
+ clearTimer = clearTimeout,
+ }) {
+ Object.assign(this, {
+ emit,
+ runAction,
+ signal,
+ ui,
+ tokenEndpoint,
+ startupTimeoutMs,
+ inputBoundaryTimeoutMs,
+ fetchImpl,
+ WebSocketClass,
+ getUserMedia,
+ createAudio,
+ captureViewport,
+ pointer,
+ radioLayer,
+ dataManager,
- providerDropdown,
+ now,
+ // Browser timer functions reject the controller as their receiver.
+ setTimer: (...args) => setTimer(...args),
+ clearTimer: (...args) => clearTimer(...args),
+ });
+ this.status = 'idle';
+ this.model = null;
+ this.epoch = 0;
+ this.turn = 0;
+ this.inputGeneration = 0;
+ this.turnAbort = new AbortController();
+ this.disposed = false;
+ this.socket = null;
+ this.channel = null;
+ this.stream = null;
+ this.audio = null;
+ this.abort = null;
+ this.tools = new Map();
+ this.radioPlaybackCalls = new WeakMap();
+ this.seenCalls = new Set();
+ this.cancelledCalls = new Set();
+ this.toolQueue = Promise.resolve();
+ this.pendingTools = 0;
+ this.modelComplete = false;
+ this.pendingCompletionStatus = null;
+ this.postToolOutput = false;
+ this.stopAfterReply = false;
+ this.modelSpoke = false;
+ this.transcripts = { assistant: '' };
+ this.pendingMapEvents = [];
+ this.userTurnPending = false;
+ // Live output has no response ID. A locally retired reply keeps ownership
+ // of incoming output until its ordered server turnComplete boundary.
+ this.replyPending = false;
+ this.automaticTurnOpen = false;
+ this.automaticActivityOwner = null;
+ this.retiredAutomaticActivityOwner = null;
+ this.automaticActivitySequence = 0;
+ this.retiredReplyPending = false;
+ this.deferredInput = null;
+ this.retiredBoundaryWait = null;
+ this.forwardedActivityOpen = false;
+ this.forwardedCaptureId = null;
- this.manualInputKind = null;
+ this.captureGeneration = 0;
+ this.captureEnabled = false;
+ this.pttPlaybackSuppressed = false;
+ this.microphoneRequested = false;
+ this.captureOwner = null;
+ this.userActivityOpen = false;
+ this.pointerSentKey = null;
+ this.pointerAnnounced = null;
+ this.pendingPointerContext = null;
- this.userTurns = createVoiceUserTurnTracker({ setTimer, clearTimer });
+ this.typedIntent = null;
- this.providerQuarantine = null;
+ this.toolSequence = 0;
+ this.radioStrongerCommit = null;
+ this.intentSequence = 0;
+ this.intentItemId = null;
+ this.intentResponseId = null;
+ this.intentCaptureId = null;
+ this.controlQueue = [];
+ this.controlBytes = 0;
+ this.controlTimer = null;
+ this.goAway = null;
+ this.droppedAudioChunks = 0;
+ this.deferredAudioDrops = { nonPttOwner: 0, closedActivity: 0 };
+ this.droppedImages = 0;
+ this.lastClose = null;
+ this.lastError = null;
+ this.completedTurns = 0;
+ this.lastAudio = null;
+ this.lastViewportAt = -Infinity;
+ this.input = createInput({
+ readUi: () => ui,
+ readStream: () => this.stream,
+ readStatus: () => this.status,
+ operations: {
+ isActive: () => this.isActive(),
+ start: (settings) => this.start(settings),
+ setStatus: (...args) => this.setStatus(...args),
+ pauseRadioForVoice: () => this.radio.pauseRadioForVoice(),
+ bargeIn: () => this.claimPttPlayback(),
+ holdPointer: () => {
+ this.heldPointerSnapshot = this.pointer?.hold('keydown');
+ },
+ releasePointerHold: () => this.pointer?.releaseHold(),
+ beginPointerTurn: (at) =>
+ this.input.pushToTalkMode && at === 'keydown'
+ ? this.heldPointerSnapshot
+ : this.beginPointerTurn(at),
+ mayClaimSpeaker: () => this.radio.mayVoiceClaimSpeaker(),
+ },
+ });
+ const setMicrophoneEnabled = this.input.setMicrophoneEnabled.bind(
+ this.input,
+ );
+ this.applyMicrophoneEnabled = (enabled) => {
+ enabled = Boolean(enabled) && !this.goAway;
+ setMicrophoneEnabled(enabled);
+ if (enabled && !this.captureEnabled) {
+ // The physical gate owns this generation, independently of tool turns.
+ this.captureOwner = {
+ captureId: ++this.captureGeneration,
+ context: null,
+ snapshot: this.heldPointerSnapshot,
+ retired: false,
+ admitted: false,
+ settled: false,
+ };
+ }
+ this.captureEnabled = enabled;
+ const metadata = this.captureOwner
+ ? { captureId: this.captureOwner.captureId }
+ : null;
+ this.audio?.setMicrophoneEnabled(enabled, metadata);
+ if (enabled && this.channel?.readyState === 'open') {
+ if (this.input.pushToTalkMode) this.radio.cancelRadioHandoff();
+ else this.noteUserActivity();
+ }
+ };
+ this.input.setMicrophoneEnabled = (enabled) => {
+ this.microphoneRequested = Boolean(enabled) && !this.goAway;
+ this.applyMicrophoneEnabled(this.microphoneRequested);
+ };
+ this.radio = new RealtimeRadio({
+ readRadioLayer: () => radioLayer,
+ readDataManager: () => dataManager,
+ readChannel: () => this.channel,
+ readUserTurnPending: () => this.userTurnPending,
+ readSessionId: () => `gemini-${this.epoch}`,
+ operations: {
+ abortTools: () => this.abortTools(),
+ isActive: () => this.isActive(),
+ stop: (settings) => this.stop(settings),
- readVoiceResumeSettings: () => ({
- pushToTalk: Boolean(this.input.pushToTalkMode),
- }),
- resumeVoice: (settings) => this.start(settings),
- notifyVoiceSuspended: ({ reason }) =>
- this.emit({ type: 'voice-suspended', reason }),
+ setStatus: (...args) => this.setStatus(...args),
+ // The shared Radio owner already surfaces a failed start in the UI.
+ queueResponseCreate: () => {},
+ debugLog: () => {},
+ },
+ });
+ this.earcon = createProgressEarcon({
+ isMicrophoneMuted: () =>
+ Boolean(
+ this.isActive() &&
+ this.channel?.readyState === 'open' &&
+ this.input.pushToTalkMode &&
+ !this.input.pushToTalkKeyHeld &&
+ this.stream &&
+ this.stream.getAudioTracks().every((track) => !track.enabled) &&
+ !this.audio?.pending &&
+ this.radio.mayVoiceClaimSpeaker(),
+ ),
+ });
+ this.narration = createNarration({
+ // Live clientContent interrupts generation, even with turnComplete:false.
+ // Reuse shared progress timing and muted-PTT earcons without injecting a
+ // second conversation turn. The model's own preamble supplies speech.
+ speak: () => false,
+ earcon: this.earcon,
+ canSpeak: () => false,
+ });
+ this.radio.observe();
+ this.lifetimeAbort = () => this.stop({ removeUi: true });
+ signal?.addEventListener('abort', this.lifetimeAbort, { once: true });
+ }
+
+ get spaceKeyHeld() {
+ return this.input.spaceKeyHeld;
+ }
+ isActive() {
+ return !['idle', 'error'].includes(this.status);
+ }
+ owns(epoch) {
+ return (
+ !this.disposed && epoch === this.epoch && !this.abort?.signal.aborted
+ );
+ }
+
+ setStatus(status, detail, recovery) {
+ this.status = status;
+ if (status === 'listening' && this.input.pushToTalkMode)
+ detail = this.input.pushToTalkKeyHeld
- ? 'Release Space to send'
- : 'Hold Space to talk';
- const event = { type: 'state', state: status, detail };
- if (recovery) event.recovery = recovery;
++ ? msg('Release Space to send')
++ : msg('Hold Space to talk');
++ const event = {
++ type: 'state',
++ state: status,
++ detail: translateKnown(detail),
++ };
++ if (recovery) event.recovery = translateKnown(recovery);
+ this.emit(event);
+ this.input.updateVoiceButtonLabel();
+ if (['idle', 'connecting', 'error'].includes(status))
+ this.input.setVoiceSpeaker('idle');
+ }
+
+ send(
+ message,
+ {
+ beforeSetup = false,
+ captureId = null,
+ onSent = null,
+ durable = false,
+ } = {},
+ ) {
+ if (
+ this.socket?.readyState !== 1 ||
+ (!beforeSetup && this.channel?.readyState !== 'open')
+ )
+ return false;
+ const body = JSON.stringify(message);
+ const bytes = new TextEncoder().encode(body).byteLength;
+ if (bytes > MAX_MESSAGE_LENGTH)
- throw new Error('Voice command context is too large');
++ throw new Error(msg('Voice command context is too large'));
+ const optional = Boolean(
+ message.realtimeInput?.audio || message.realtimeInput?.video,
+ );
+ if (optional) {
+ this.pruneControls();
+ if (
+ this.goAway ||
+ this.controlQueue.length ||
+ this.socket.bufferedAmount + bytes > MAX_BUFFERED_BYTES
+ ) {
+ if (message.realtimeInput.audio) this.droppedAudioChunks++;
+ else this.droppedImages++;
+ return false;
+ }
+ this.socket.send(body);
+ onSent?.();
+ return true;
+ }
+ this.pruneControls();
+ const entry = {
+ epoch: this.epoch,
+ turn: this.turn,
+ captureId,
+ durable,
+ message,
+ body,
+ bytes,
+ onSent,
+ deadline: this.now() + CONTROL_PRESSURE_TIMEOUT_MS,
+ };
+ if (!this.controlQueue.length && this.canSendControl(entry)) {
+ this.writeControl(entry);
+ return true;
+ }
+ if (
+ bytes > MAX_CONTROL_BYTES ||
+ this.controlBytes + bytes > MAX_CONTROL_BYTES ||
+ this.controlQueue.length >= MAX_CONTROL_MESSAGES
+ )
+ throw new Error(
- 'Gemini reliable transport exceeded its queue limit. Start voice again.',
++ msg(
++ 'Gemini reliable transport exceeded its queue limit. Start voice again.',
++ ),
+ );
+ this.controlQueue.push(entry);
+ this.controlBytes += bytes;
+ this.scheduleControls();
+ return true;
+ }
+
+ controlCurrent(entry) {
+ if (!this.owns(entry.epoch)) return false;
+ if (entry.durable) return true;
+ const input = entry.message.realtimeInput;
+ if (
+ entry.message.toolResponse?.functionResponses?.some((call) =>
+ this.cancelledCalls.has(call.id),
+ )
+ )
+ return false;
+ if (input?.activityEnd)
+ return (
+ (this.forwardedActivityOpen &&
+ this.forwardedCaptureId === entry.captureId) ||
+ (this.acceptsCapture({ captureId: entry.captureId }) &&
+ this.controlQueue.some(
+ (pending) =>
+ pending.message.realtimeInput?.activityStart &&
+ pending.captureId === entry.captureId &&
+ this.controlCurrent(pending),
+ ))
+ );
+ if (entry.captureId !== null)
+ return this.acceptsCapture({ captureId: entry.captureId });
+ return entry.turn === this.turn;
+ }
+
+ pruneControls() {
+ this.controlQueue = this.controlQueue.filter((entry) =>
+ this.controlCurrent(entry),
+ );
+ this.controlBytes = this.controlQueue.reduce(
+ (total, entry) => total + entry.bytes,
+ 0,
+ );
+ if (!this.controlQueue.length) {
+ if (this.controlTimer !== null) this.clearTimer(this.controlTimer);
+ this.controlTimer = null;
+ }
+ }
+
+ canSendControl(entry) {
+ return (
+ entry.bytes <= MAX_CONTROL_BYTES &&
+ (this.socket.bufferedAmount === 0 ||
+ this.socket.bufferedAmount + entry.bytes <= MAX_BUFFERED_BYTES)
+ );
+ }
+
+ writeControl(entry) {
+ this.socket.send(entry.body);
+ if (!this.controlCurrent(entry)) return;
+ const input = entry.message.realtimeInput;
+ // Only markers actually written to the socket own its physical activity.
+ if (input?.activityStart) {
+ this.forwardedActivityOpen = true;
+ this.forwardedCaptureId = entry.captureId;
+ this.beginSpeechIntent(entry.captureId);
+ if (!this.controlCurrent(entry)) return;
+ }
+ if (input?.activityEnd) {
+ this.forwardedActivityOpen = false;
+ this.forwardedCaptureId = null;
+ if (this.intentCaptureId === entry.captureId) this.bindSpeechIntent();
+ }
+ entry.onSent?.();
+ }
+
+ scheduleControls() {
+ if (this.controlTimer !== null || !this.controlQueue.length) return;
+ const epoch = this.epoch;
+ this.controlTimer = this.setTimer(
+ () => {
- this.controlTimer = null;
+ if (!this.owns(epoch)) return;
++ this.controlTimer = null;
+ try {
+ this.flushControls();
+ } catch (error) {
+ this.fail(error);
+ }
+ },
+ Math.min(
+ CONTROL_POLL_MS,
+ Math.max(0, this.controlQueue[0].deadline - this.now()),
+ ),
+ );
+ this.controlTimer?.unref?.();
+ }
+
+ flushControls() {
+ this.pruneControls();
+ while (this.controlQueue.length) {
+ const entry = this.controlQueue[0];
+ if (this.now() >= entry.deadline)
+ throw new Error(
- 'Gemini reliable transport did not drain. Start voice again.',
++ msg('Gemini reliable transport did not drain. Start voice again.'),
+ );
+ if (!this.canSendControl(entry)) break;
+ this.controlQueue.shift();
+ this.controlBytes -= entry.bytes;
+ if (this.controlCurrent(entry)) this.writeControl(entry);
+ }
+ this.scheduleControls();
+ if (!this.controlQueue.length) this.finishPlayback();
+ }
+
+ clearControls() {
+ if (this.controlTimer !== null) this.clearTimer(this.controlTimer);
+ this.controlTimer = null;
+ this.controlQueue = [];
+ this.controlBytes = 0;
+ }
+
+ async requestToken(signal, pushToTalk = false) {
- const response = await this.fetchImpl(this.tokenEndpoint, {
- method: 'POST',
- cache: 'no-store',
- redirect: 'error',
- signal,
- headers: { 'Content-Type': 'application/json' },
- body: pushToTalk ? '{"inputMode":"push-to-talk"}' : '{}',
- });
- const data = await response.json().catch(() => null);
+ signal.throwIfAborted();
- if (!response.ok)
- throw new Error(
- typeof data?.error === 'string'
- ? data.error
- : `Gemini token request failed (HTTP ${response.status})`,
- );
- if (
- typeof data?.model !== 'string' ||
- !/^gemini-[a-z0-9.-]+$/.test(data.model)
- )
- throw new Error('Gemini token response did not include a valid model');
- if (
- !data.config ||
- typeof data.config !== 'object' ||
- Array.isArray(data.config)
- )
- throw new Error('Gemini token response did not include session settings');
- const manual =
- data.config.realtimeInputConfig?.automaticActivityDetection?.disabled;
- if (pushToTalk ? manual !== true : manual !== undefined && manual !== false)
- throw new Error('Gemini session settings do not match the input mode');
- const url = geminiSocketUrl(data);
- return { ...data, url };
++ let acquiredResponse;
++ const acquisition = Promise.resolve(
++ this.fetchImpl(this.tokenEndpoint, {
++ method: 'POST',
++ cache: 'no-store',
++ redirect: 'error',
++ signal,
++ headers: { 'Content-Type': 'application/json' },
++ body: pushToTalk ? '{"inputMode":"push-to-talk"}' : '{}',
++ }),
++ );
++ void acquisition.then(
++ (response) => {
++ acquiredResponse = response;
++ if (signal.aborted) void response.body?.cancel().catch(() => {});
++ },
++ () => {},
++ );
++ try {
++ const response = await waitForSignal(acquisition, signal);
++ signal.throwIfAborted();
++ const data = await readResponseJsonCapped(response, 256 * 1024, signal);
++ signal.throwIfAborted();
++ if (!response.ok)
++ throw new Error(
++ typeof data?.error === 'string'
++ ? tokenErrorMessage(data.error)
++ : t('Gemini token request failed (HTTP {status})', {
++ status: response.status,
++ }),
++ );
++ if (
++ typeof data?.model !== 'string' ||
++ !/^gemini-[a-z0-9.-]+$/.test(data.model)
++ )
++ throw new Error(
++ msg('Gemini token response did not include a valid model'),
++ );
++ if (
++ !data.config ||
++ typeof data.config !== 'object' ||
++ Array.isArray(data.config)
++ )
++ throw new Error(
++ msg('Gemini token response did not include session settings'),
++ );
++ const manual =
++ data.config.realtimeInputConfig?.automaticActivityDetection?.disabled;
++ if (
++ pushToTalk ? manual !== true : manual !== undefined && manual !== false
++ )
++ throw new Error(
++ msg('Gemini session settings do not match the input mode'),
++ );
++ const url = geminiSocketUrl(data);
++ return { ...data, url };
++ } finally {
++ if (signal.aborted) void acquiredResponse?.body?.cancel().catch(() => {});
++ }
+ }
+
+ async start({ pushToTalk = false } = {}) {
+ if (this.disposed || this.isActive() || this.signal?.aborted) return;
+ const held = pushToTalk && this.input.pushToTalkKeyHeld;
+ const spaceHeld = this.input.spaceKeyHeld;
+ this.stop({ preserveStatus: true });
+ this.input.pushToTalkMode = pushToTalk;
+ this.input.pushToTalkKeyHeld = held;
+ this.input.spaceKeyHeld = spaceHeld;
+ this.abort = new AbortController();
+ const epoch = this.epoch;
+ const permissionSignal = AbortSignal.any([
+ this.abort.signal,
+ ...(this.signal ? [this.signal] : []),
+ ]);
+ let signal = permissionSignal;
+ this.lastError = null;
+ this.lastAudio = null;
+ this.completedTurns = 0;
- this.setStatus('connecting', 'Requesting microphone');
- this.radio.pauseRadioForVoice();
+ let acquiredStream = null;
+ let releasedStream = null;
+ const releaseStream = (stream) => {
+ if (!stream || stream === releasedStream) return;
+ releasedStream = stream;
+ stream.getTracks().forEach((track) => track.stop());
+ };
+ try {
++ this.setStatus('connecting', msg('Requesting microphone'));
++ if (!this.owns(epoch)) return;
++ signal.throwIfAborted();
++ this.radio.pauseRadioForVoice();
++ if (!this.owns(epoch)) return;
+ // The worklet serializes start, PCM and flushed end notifications. A
+ // keydown must not send a new start ahead of the previous queued end.
+ let activityCaptureId = null;
+ const audio = this.createAudio({
+ pushToTalk,
+ onAudioStart: (metadata) => {
+ if (
+ !this.owns(epoch) ||
+ this.goAway ||
+ !this.acceptsCapture(metadata)
+ )
+ return;
+ if (!pushToTalk || activityCaptureId === metadata.captureId) return;
+ this.captureOwner.admitted = true;
+ if (
+ !this.interrupt('push-to-talk', {
+ keepPlayback: !this.pttPlaybackSuppressed,
+ })
+ )
+ return;
+ if (!this.owns(epoch) || !this.acceptsCapture(metadata)) return;
+ const activityGeneration = this.inputGeneration;
+ const activityCurrent = () =>
+ this.owns(epoch) &&
+ this.inputGeneration === activityGeneration &&
+ this.acceptsCapture(metadata);
+ this.beginPointerTurn(
+ 'speech_start',
+ this.captureOwner.snapshot,
+ activityCurrent,
+ );
+ if (!activityCurrent()) return;
+ const context = this.pendingPointerContext;
+ this.captureOwner.context = context;
+ if (!this.sendPointerContext(context, metadata)) {
+ if (this.owns(epoch))
+ this.fail(
+ new Error(
- 'Gemini could not submit this input. Start voice again.',
++ msg('Gemini could not submit this input. Start voice again.'),
+ ),
+ );
+ return;
+ }
+ if (!activityCurrent()) return;
+ const accepted = this.sendUserInput(
+ { realtimeInput: { activityStart: {} } },
+ metadata,
+ );
+ if (!activityCurrent()) return;
+ // Quiet context and an empty hold have no response to retire later.
+ if (accepted) activityCaptureId = metadata.captureId;
+ else if (this.owns(epoch))
+ this.fail(
+ new Error(
- 'Gemini could not submit this input. Start voice again.',
++ msg('Gemini could not submit this input. Start voice again.'),
+ ),
+ );
+ },
+ onAudio: (chunk, metadata) => {
+ if (!this.owns(epoch) || !this.acceptsCapture(metadata)) return;
+ if (!pushToTalk || activityCaptureId === metadata.captureId) {
+ const sent = this.sendUserInput(
+ {
+ realtimeInput: { audio: chunk },
+ },
+ metadata,
+ );
+ if (sent && pushToTalk) this.replyPending = true;
+ }
+ },
+ onAudioEnd: (metadata) => {
+ if (!this.owns(epoch) || !this.validCaptureMetadata(metadata)) return;
+ if (pushToTalk) {
+ if (this.captureOwner?.captureId === metadata.captureId)
+ this.captureOwner.settled = true;
+ if (activityCaptureId !== metadata.captureId) {
+ this.finishPlayback();
+ return;
+ }
+ this.sendUserInput(
+ { realtimeInput: { activityEnd: {} } },
+ metadata,
+ );
+ if (this.acceptsCapture(metadata)) this.narration.userTurnEnded();
+ activityCaptureId = null;
+ } else if (this.acceptsCapture(metadata)) {
+ this.send({ realtimeInput: { audioStreamEnd: true } });
+ }
+ },
+ onAudioDiscard: (metadata) => {
+ if (
+ !this.owns(epoch) ||
+ !pushToTalk ||
+ !this.validCaptureMetadata(metadata) ||
+ this.captureOwner?.captureId !== metadata.captureId
+ )
+ return;
+ this.captureOwner.settled = true;
+ if (!this.acceptsCapture(metadata)) {
+ // New typed input owns completion; its retired capture cannot
+ // revoke that request or leave its presentation waiting.
+ this.finishPlayback();
+ return;
+ }
+ if (
+ activityCaptureId === metadata.captureId ||
+ this.forwardedCaptureId === metadata.captureId ||
+ this.deferredInput?.captureId === metadata.captureId
+ )
+ return;
+ // No provider turn was submitted or retired. Keep an older request's
+ // tool/completion ownership; the physical claim still revokes Radio.
+ this.radio.cancelRadioHandoff();
+ if (!this.audio?.pending) this.input.setVoiceSpeaker('idle');
+ this.finishPlayback();
+ },
+ onDrain: () => {
+ if (this.owns(epoch)) {
+ this.narration.quiet();
+ this.finishPlayback();
+ }
+ },
+ onError: (error) => {
+ if (this.owns(epoch)) this.fail(error);
+ },
+ });
++ if (!this.owns(epoch) || signal.aborted) {
++ void Promise.resolve(audio.close()).catch(() => {});
++ return;
++ }
+ this.audio = audio;
+ // Invoke resume in the initiating gesture, but do not mint the short-lived
+ // admission credential while an uncancellable permission prompt is open.
+ const initialized = Promise.resolve(audio.initialize(permissionSignal));
+ void initialized.catch(() => {});
++ if (!this.owns(epoch)) return;
++ signal.throwIfAborted();
+ const mediaRequest = Promise.resolve(
+ this.getUserMedia({
+ audio: {
+ echoCancellation: true,
+ noiseSuppression: true,
+ autoGainControl: true,
+ channelCount: 1,
+ },
+ }),
+ );
+ // Permission prompts cannot be cancelled. A later grant still belongs
+ // to this attempt and must release its own tracks after stop/timeout.
+ void mediaRequest.then(
+ (stream) => {
+ if (!this.owns(epoch) || signal.aborted) releaseStream(stream);
+ },
+ () => {},
+ );
- acquiredStream = await awaitWithSignal(mediaRequest, signal);
++ acquiredStream = await waitForSignal(mediaRequest, signal);
+ if (!this.owns(epoch)) {
+ releaseStream(acquiredStream);
+ return;
+ }
+ signal.throwIfAborted();
+ this.stream = acquiredStream;
+ acquiredStream.getAudioTracks().forEach((track) => {
+ track.enabled = false;
+ });
+ signal = AbortSignal.any([
+ permissionSignal,
+ AbortSignal.timeout(this.startupTimeoutMs),
+ ]);
- this.setStatus('connecting', 'Connecting to Gemini');
- const [, credential] = await awaitWithSignal(
- Promise.all([initialized, this.requestToken(signal, pushToTalk)]),
- signal,
- );
++ this.setStatus('connecting', msg('Connecting to Gemini'));
++ if (!this.owns(epoch)) return;
++ signal.throwIfAborted();
++ const startup = Promise.all([
++ initialized,
++ this.requestToken(signal, pushToTalk),
++ ]);
++ void startup.catch(() => {});
++ const [, credential] = await waitForSignal(startup, signal);
+ if (!this.owns(epoch)) return;
+ this.model = credential.model;
+ await this.connect(credential, epoch, signal);
+ if (!this.owns(epoch)) return;
+ signal.throwIfAborted();
+ const enabled =
+ !this.input.pushToTalkMode || this.input.pushToTalkKeyHeld;
+ this.input.setMicrophoneEnabled(enabled);
+ audio.connectMicrophone(
+ acquiredStream,
+ enabled,
+ this.captureOwner ? { captureId: this.captureOwner.captureId } : null,
+ );
+ this.input.startVoiceVisualizer(acquiredStream);
+ this.input.startAssistantVoiceVisualizer(audio.outputStream);
- this.setStatus('listening', 'Ask or command');
++ this.setStatus('listening', msg('Ask or command'));
+ } catch (error) {
+ if (acquiredStream && acquiredStream !== this.stream)
+ releaseStream(acquiredStream);
+ if (this.owns(epoch)) this.fail(error);
+ }
+ }
+
+ connect(credential, epoch, signal) {
+ return new Promise((resolve, reject) => {
++ signal.throwIfAborted();
++ if (!this.owns(epoch)) return reject(cancelled());
+ const socket = new this.WebSocketClass(credential.url);
+ socket.binaryType = 'arraybuffer';
+ this.socket = socket;
+ const channel = { readyState: 'connecting' };
+ this.channel = channel;
+ let connected = false;
+ const current = () => this.owns(epoch) && this.socket === socket;
+ const abort = () => {
+ signal.removeEventListener('abort', abort);
- reject(cancelled());
++ reject(signal.reason || cancelled());
+ };
+ signal.addEventListener('abort', abort, { once: true });
+ socket.onopen = () => {
+ if (!current()) return;
+ try {
+ this.send(
+ {
+ setup: {
+ ...credential.config,
+ model: `models/${credential.model}`,
+ },
+ },
+ { beforeSetup: true },
+ );
+ } catch (error) {
+ reject(error);
+ }
+ };
+ socket.onmessage = ({ data }) => {
+ if (!current()) return;
+ try {
+ const text =
+ typeof data === 'string' ? data : new TextDecoder().decode(data);
+ if (text.length > MAX_MESSAGE_LENGTH)
- throw new Error('Gemini returned an oversized message');
++ throw new Error(msg('Gemini returned an oversized message'));
+ const message = JSON.parse(text);
+ if (message.setupComplete) {
+ if (connected) return;
+ connected = true;
+ channel.readyState = 'open';
+ signal.removeEventListener('abort', abort);
+ resolve();
+ }
+ this.handleMessage(message, epoch);
+ } catch (error) {
+ if (!connected) reject(error);
- else this.fail(error);
++ else if (current()) this.fail(error);
+ }
+ };
+ socket.onerror = () => {
+ const error = new Error(
- 'Gemini Live connection failed. Check network access, then start voice again.',
++ msg(
++ 'Gemini Live connection failed. Check network access, then start voice again.',
++ ),
+ );
+ if (!current()) return;
+ if (!connected) reject(error);
+ else this.fail(error);
+ };
+ socket.onclose = (event) => {
+ if (!current()) return;
+ const code =
+ Number.isInteger(event?.code) &&
+ event.code >= 1000 &&
+ event.code <= 4999
+ ? event.code
+ : null;
+ this.lastClose = {
+ code,
+ category:
+ code === 1000
+ ? 'normal'
+ : code === 1008
+ ? 'policy'
+ : code === 1011
+ ? 'server'
+ : 'connection',
+ };
+ const error = new Error(
+ connected
- ? 'Gemini Live connection ended. Start voice again for a new conversation.'
- : 'Gemini Live could not start. Start voice again to request a fresh session.',
++ ? msg(
++ 'Gemini Live connection ended. Start voice again for a new conversation.',
++ )
++ : msg(
++ 'Gemini Live could not start. Start voice again to request a fresh session.',
++ ),
+ );
+ error.recovery = connected
- ? 'Start voice again for a fresh token and a new conversation.'
- : 'Start voice again to request a fresh session credential.';
++ ? msg('Start voice again for a fresh token and a new conversation.')
++ : msg('Start voice again to request a fresh session credential.');
+ if (!connected) reject(error);
+ else this.fail(error);
+ };
+ });
+ }
+
+ fail(error, recovery = error?.recovery) {
+ const detail =
+ error?.name === 'NotAllowedError'
- ? 'Microphone permission was denied. Allow microphone access and try again.'
++ ? msg(
++ 'Microphone permission was denied. Allow microphone access and try again.',
++ )
+ : error?.name === 'TimeoutError'
- ? 'Gemini connection timed out. Try again.'
- : error?.message || 'Gemini voice could not start';
++ ? msg('Gemini connection timed out. Try again.')
++ : error?.message || msg('Gemini voice could not start');
+ this.lastError = detail;
+ this.stop({ preserveStatus: true });
+ this.setStatus('error', detail, recovery);
+ }
+
+ abortTools() {
+ const resources = this.turnAbort;
+ const tools = [...this.tools.values()];
+ this.turnAbort = new AbortController();
+ this.turn++;
+ this.typedIntent = null;
- this.providerQuarantine = null;
+ this.radioStrongerCommit = null;
+ this.pruneControls();
+ this.tools.clear();
+ this.radio?.clearTools();
+ this.pendingTools = 0;
+ this.toolQueue = Promise.resolve();
+ this.narration?.cancel();
+ resources.abort();
+ for (const entry of tools) entry.abort();
+ }
+
+ noteUserActivity() {
+ this.narration?.cancel();
+ this.modelSpoke = false;
+ this.userTurnPending = true;
+ this.radio.cancelRadioHandoff();
+ }
+
+ /** A physical hold silences playback; only admitted speech retires a turn. */
+ claimPttPlayback() {
+ if (
+ this.channel?.readyState !== 'open' ||
+ this.goAway ||
+ !this.radio.mayVoiceClaimSpeaker()
+ )
+ return false;
+ this.pttPlaybackSuppressed = true;
+ this.audio?.clearPlayback();
+ this.input.setVoiceSpeaker('user');
+ return true;
+ }
+
+ /** A claimed Space hold stops local playback before its audio reaches Live. */
+ bargeIn() {
+ if (
+ this.channel?.readyState !== 'open' ||
+ this.goAway ||
+ !this.radio.mayVoiceClaimSpeaker()
+ )
+ return false;
+ return this.interrupt('push-to-talk');
+ }
+
+ interrupt(
+ reason = 'user-speech',
+ {
+ keepPlayback = false,
+ preserveAdvisoryCaption = false,
+ serverInterrupted = false,
+ } = {},
+ ) {
+ if (this.goAway && !serverInterrupted) return false;
+ const epoch = this.epoch;
+ const generation = ++this.inputGeneration;
+ const channel = this.channel;
+ const owned = () =>
+ this.owns(epoch) &&
+ this.inputGeneration === generation &&
+ this.channel === channel;
+ this.pttPlaybackSuppressed = false;
- if (['push-to-talk', 'user-text'].includes(reason))
- this.manualInputKind = reason;
+ // Arm only for an outstanding reply: an idle hold/first text command has
+ // no old boundary to wait for. This also covers generation before the
+ // first output packet, because input submission marks replyPending.
+ const deferred = this.deferredInput;
+ const deferInput =
+ deferred || (this.retiredReplyPending && this.replyPending);
+ if (this.replyPending) {
+ if (!this.retiredReplyPending)
+ this.retiredAutomaticActivityOwner = this.automaticActivityOwner;
+ this.retiredReplyPending = true;
+ }
+ this.replyPending = false;
+ if (['push-to-talk', 'user-text'].includes(reason)) {
+ this.automaticTurnOpen = false;
+ this.automaticActivityOwner = null;
+ }
+ this.clearDeferredInput();
+ this.abortTools();
+ if (!owned()) return false;
- this.userTurns.invalidate();
- if (!owned()) return false;
+ this.intentItemId = null;
+ this.intentResponseId = null;
+ this.intentCaptureId = null;
- this.emit({ type: 'user-turn-start' });
- if (!owned()) return false;
+ if (deferInput) {
+ // Only one successor may reach Live before the previous boundary. A
+ // newer local turn replaces unsent input and waits to interrupt that
+ // successor, rather than creating indistinguishable overlapping replies.
+ const owner = {
+ epoch: this.epoch,
+ turn: this.turn,
+ messages: [],
+ bytes: 0,
+ activityOpen: false,
+ kind: reason,
+ context: null,
+ deadline:
+ deferred?.deadline ||
+ this.retiredBoundaryWait?.deadline ||
+ this.now() + this.inputBoundaryTimeoutMs,
+ };
+ this.clearRetiredBoundaryWait();
+ this.deferredInput = owner;
+ owner.timer = this.setTimer(
+ () => {
+ if (this.deferredInput === owner && this.owns(owner.epoch))
+ this.fail(
+ new Error(
- 'Gemini did not finish the interrupted reply. Start voice again.',
++ msg(
++ 'Gemini did not finish the interrupted reply. Start voice again.',
++ ),
+ ),
+ );
+ },
+ Math.max(0, owner.deadline - this.now()),
+ );
+ owner.timer.unref?.();
+ } else this.boundRetiredReply();
+ this.noteUserActivity();
+ if (!owned()) return false;
+ if (!keepPlayback) this.audio?.clearPlayback();
+ if (!owned()) return false;
+ this.modelComplete = false;
+ this.pendingCompletionStatus = null;
+ this.postToolOutput = false;
+ this.stopAfterReply = false;
+ this.transcripts.assistant = '';
+ this.emit({
+ type: 'interruption',
+ reason,
+ ...(preserveAdvisoryCaption ? { preserveAdvisoryCaption: true } : {}),
+ });
+ if (!owned()) return false;
+ this.input.setVoiceSpeaker(this.goAway ? 'idle' : 'user');
+ if (!owned()) return false;
+ this.setStatus(
+ 'listening',
+ this.goAway
- ? 'Gemini session expiring; finishing the current reply'
- : 'Ask or command',
++ ? msg('Gemini session expiring; finishing the current reply')
++ : msg('Ask or command'),
+ );
+ return owned();
+ }
+
++ discardRetiredReply(message, epoch) {
++ if (!this.owns(epoch) || !this.retiredReplyPending) return false;
++ const content = message.serverContent;
++ // Retired output proves the old reply is still running; only silence
++ // after it counts toward the first retirement's recovery bound.
++ if (
++ this.retiredBoundaryWait?.extendable &&
++ !content?.turnComplete &&
++ (content?.modelTurn ||
++ content?.outputTranscription ||
++ content?.generationComplete ||
++ message.toolCall)
++ ) {
++ this.clearRetiredBoundaryWait();
++ this.boundRetiredReply();
++ }
++ const retiredIds = (message.toolCall?.functionCalls || [])
++ .map((call) => call?.id)
++ .filter(validCallId);
++ this.rememberCallIds(retiredIds);
++ for (const id of retiredIds) this.cancelledCalls.add(id);
++ // Gemini documents interrupted -> turnComplete. Discard all retired
++ // output, including content coalesced with either marker. A natural
++ // completion racing the local claim also closes the old reply safely.
++ if (content?.turnComplete) {
++ this.clearRetiredBoundaryWait();
++ this.retiredReplyPending = false;
++ if (
++ this.typedIntent?.retiredAutomaticPredecessor ===
++ this.retiredAutomaticActivityOwner
++ )
++ this.typedIntent.retiredAutomaticPredecessor = null;
++ // A true replyPending now belongs to a successor submitted while
++ // this older reply was retired. Its boundary cannot revoke that input.
++ if (this.automaticActivityOwner === this.retiredAutomaticActivityOwner) {
++ this.automaticTurnOpen = false;
++ this.automaticActivityOwner = null;
++ }
++ this.retiredAutomaticActivityOwner = null;
++ if (this.goAway) {
++ this.clearDeferredInput();
++ if (
++ this.goAway.supersededSuccessor ||
++ (!this.replyPending &&
++ !this.automaticTurnOpen &&
++ !this.pendingTools &&
++ !this.audio?.pending &&
++ !this.controlQueue.length)
++ )
++ this.finishGoAway();
++ } else this.flushDeferredInput();
++ }
++ return true;
++ }
++
+ handleMessage(message, epoch = this.epoch) {
+ if (!this.owns(epoch)) return;
++ const initialGeneration = this.inputGeneration;
++ const initialTurn = this.turn;
++ const initialCurrent = () =>
++ this.owns(epoch) &&
++ this.inputGeneration === initialGeneration &&
++ this.turn === initialTurn;
+ if (this.goAway && this.now() >= this.goAway.deadline) {
+ this.finishGoAway();
+ return;
+ }
+ if (message.error) {
+ this.fail(
+ new Error(
- 'Gemini rejected the voice session. Start voice again to request a fresh session.',
++ msg(
++ 'Gemini rejected the voice session. Start voice again to request a fresh session.',
++ ),
++ ),
++ msg(
++ 'Start voice again for a fresh session credential. If it repeats, check Gemini model and API access.',
+ ),
- 'Start voice again for a fresh session credential. If it repeats, check Gemini model and API access.',
+ );
+ return;
+ }
+ if (message.goAway) {
+ this.beginGoAway(message.goAway.timeLeft, epoch);
- if (!this.owns(epoch)) return;
++ if (!initialCurrent()) return;
+ }
++ let prunedCancelledControls = false;
+ for (const id of message.toolCallCancellation?.ids || []) {
+ const action = this.tools.get(id);
+ const results = [
+ this.radio.pendingRadioPlaybackResult,
+ this.radio.radioHandoffInFlightResult,
+ ].filter((result) => {
+ const owner = result && this.radioPlaybackCalls.get(result);
+ return (
+ owner?.id === id && owner.epoch === epoch && owner.turn === this.turn
+ );
+ });
+ const queuedResponse = this.controlQueue.some((entry) =>
+ entry.message.toolResponse?.functionResponses?.some(
+ (call) => call.id === id,
+ ),
+ );
+ // A queued response still owns transport work until it reaches the wire.
+ if (!action && !results.length && !queuedResponse) continue;
+ this.cancelledCalls.add(id);
+ action?.abort();
++ if (!initialCurrent()) return;
+ for (const result of results) this.radio.cancelPlaybackResult(result);
++ if (!initialCurrent()) return;
++ const queuedControls = this.controlQueue.length;
+ this.pruneControls();
++ prunedCancelledControls ||= this.controlQueue.length < queuedControls;
++ }
++ if (prunedCancelledControls) {
++ // Removing the last queued response can release an already complete turn.
++ this.finishPlayback();
++ // Completion observers may stop this session or accept a successor input.
++ if (!initialCurrent()) return;
+ }
+ const content = message.serverContent;
++ let receivedReplyPending = this.replyPending || this.retiredReplyPending;
++ const settleFencedBoundary = () => {
++ // Preserve this packet's old terminal without publishing its caption,
++ // audio or tools into the new input. A terminal already processed below
++ // must never be reused to close a successor retired by a final observer.
++ if (receivedReplyPending && content?.turnComplete)
++ this.discardRetiredReply(message, epoch);
++ };
+ // A server acknowledgment of a local interruption belongs to the retired
+ // reply; it must not revoke the successor's pointer, timing or turn token.
+ if (content?.interrupted) {
+ const newAutomaticActivity =
+ !this.input.pushToTalkMode &&
+ !this.goAway &&
+ message.voiceActivity?.type === 'ACTIVITY_START' &&
+ !this.userActivityOpen;
+ const predecessor = this.typedIntent?.automaticPredecessor;
+ if (
+ !this.retiredReplyPending &&
+ !newAutomaticActivity &&
+ predecessor?.epoch === epoch &&
- this.readTypedTurnInput()
++ this.currentTypedInput()
+ ) {
+ // Automatic VAD may not have produced output before text superseded
+ // it. This specific local predecessor owns one interruption boundary;
+ // the acknowledgment is not another user input. Do not infer this
+ // from output silence alone, or wait for a boundary until it arrives.
+ this.retiredAutomaticActivityOwner = predecessor;
+ this.typedIntent.retiredAutomaticPredecessor = predecessor;
+ this.typedIntent.automaticPredecessor = null;
+ } else if (!this.retiredReplyPending) {
+ if (
+ !this.interrupt('user-speech', {
+ preserveAdvisoryCaption: true,
+ serverInterrupted: true,
+ })
- )
++ ) {
++ settleFencedBoundary();
+ return;
++ }
+ }
+ this.retiredReplyPending = true;
++ receivedReplyPending = true;
+ this.boundRetiredReply();
+ }
+ // Manual PTT owns its onset locally. Automatic speech takes one snapshot
+ // per activity, regardless of duplicate/late transcription notifications.
+ if (!this.input.pushToTalkMode && !this.goAway) {
+ if (
+ message.voiceActivity?.type === 'ACTIVITY_START' &&
+ !this.userActivityOpen
+ ) {
+ this.userActivityOpen = true;
+ const typedPredecessor = this.typedIntent?.retiredAutomaticPredecessor;
+ if (
+ this.retiredReplyPending &&
+ typedPredecessor &&
+ typedPredecessor === this.retiredAutomaticActivityOwner &&
- this.readTypedTurnInput()
++ this.currentTypedInput()
+ ) {
+ // This precise wait still belongs to the automatic predecessor, not
+ // the submitted text. New speech revokes that text without inventing
+ // a second retirement/deferred input or renewing the existing bound.
+ this.replyPending = false;
+ if (!this.interrupt()) return;
+ } else if (!this.retiredReplyPending && !this.interrupt()) return;
+ // Local activity ownership is only for expiry liveness, not tools.
+ // Assign after retiring observed output so its boundary cannot clear
+ // a newer detected activity that has not received a reply yet.
+ this.automaticActivityOwner = {
+ epoch,
+ sequence: ++this.automaticActivitySequence,
+ };
+ this.automaticTurnOpen = true;
+ const activityGeneration = this.inputGeneration;
+ const activityCurrent = () =>
+ this.owns(epoch) && this.inputGeneration === activityGeneration;
+ this.beginSpeechIntent(null);
+ if (!activityCurrent()) return;
+ this.beginPointerTurn('speech_start', undefined, activityCurrent);
+ if (!activityCurrent()) return;
+ const context = this.pendingPointerContext;
+ if (
+ context &&
+ this.send({
+ realtimeInput: { text: JSON.stringify(context.item) },
+ }) &&
+ activityCurrent()
+ )
+ this.consumePointerContext(context);
+ } else if (
+ message.voiceActivity?.type === 'ACTIVITY_END' &&
+ this.userActivityOpen
+ ) {
+ this.userActivityOpen = false;
+ this.bindSpeechIntent();
+ this.narration.userTurnEnded();
+ }
+ }
++ // Native activity above may intentionally advance the local input. From
++ // here, observers must not let the rest of this packet reach a successor.
++ const messageGeneration = this.inputGeneration;
++ const messageTurn = this.turn;
++ const messageCurrent = () =>
++ this.owns(epoch) &&
++ this.inputGeneration === messageGeneration &&
++ this.turn === messageTurn;
+ // Native Live captions are unordered advisory segments. Never attach them
+ // to a command token or use them to grant/revoke a tool's lifetime.
+ if (content?.inputTranscription?.text) {
- this.emit({
- type: 'user-input-segment',
- inputKind: 'speech',
- inputId: null,
- inputScope: 'unattributed-segment',
- text: content.inputTranscription.text,
- });
+ this.transcript('user', content.inputTranscription);
- }
- if (this.retiredReplyPending) {
- // Retired output proves the old reply is still running; only silence
- // after it counts toward the first retirement's recovery bound.
- if (
- this.retiredBoundaryWait?.extendable &&
- !content?.turnComplete &&
- (content?.modelTurn ||
- content?.outputTranscription ||
- content?.generationComplete ||
- message.toolCall)
- ) {
- this.clearRetiredBoundaryWait();
- this.boundRetiredReply();
- }
- const retiredIds = (message.toolCall?.functionCalls || [])
- .map((call) => call?.id)
- .filter(validCallId);
- this.rememberCallIds(retiredIds);
- for (const id of retiredIds) this.cancelledCalls.add(id);
- // Gemini documents interrupted -> turnComplete. Discard all retired
- // output, including content coalesced with either marker. A natural
- // completion racing the local claim also closes the old reply safely.
- if (content?.turnComplete) {
- this.clearRetiredBoundaryWait();
- this.retiredReplyPending = false;
- if (
- this.typedIntent?.retiredAutomaticPredecessor ===
- this.retiredAutomaticActivityOwner
- )
- this.typedIntent.retiredAutomaticPredecessor = null;
- // A true replyPending now belongs to a successor submitted while
- // this older reply was retired. Its boundary cannot revoke that input.
- if (
- this.automaticActivityOwner === this.retiredAutomaticActivityOwner
- ) {
- this.automaticTurnOpen = false;
- this.automaticActivityOwner = null;
- }
- this.retiredAutomaticActivityOwner = null;
- if (this.goAway) {
- this.clearDeferredInput();
- if (
- this.goAway.supersededSuccessor ||
- (!this.replyPending &&
- !this.automaticTurnOpen &&
- !this.pendingTools &&
- !this.audio?.pending &&
- !this.controlQueue.length)
- )
- this.finishGoAway();
- } else this.flushDeferredInput();
++ if (!messageCurrent()) {
++ settleFencedBoundary();
++ return;
+ }
- return;
+ }
++ if (this.discardRetiredReply(message, epoch)) return;
+ if (
+ content?.modelTurn ||
+ content?.outputTranscription ||
+ content?.generationComplete ||
+ message.toolCall
+ ) {
+ // Once successor output is observed, an unattributed later interruption
+ // cannot still claim the unobserved automatic predecessor's boundary.
+ if (this.typedIntent) {
+ this.typedIntent.automaticPredecessor = null;
+ this.typedIntent.retiredAutomaticPredecessor = null;
+ }
+ this.replyPending = true;
++ receivedReplyPending = true;
+ }
+ if (content?.outputTranscription?.text) {
+ this.userTurnPending = false;
+ this.postToolOutput = true;
+ this.transcript('assistant', content.outputTranscription);
++ if (!messageCurrent()) {
++ settleFencedBoundary();
++ return;
++ }
+ }
+ for (const part of (content?.interrupted
+ ? []
+ : content?.modelTurn?.parts) || []) {
+ if (part.thought) continue;
+ if (part.inlineData?.data) {
+ this.userTurnPending = false;
+ this.modelComplete = false;
+ this.postToolOutput = true;
+ if (!this.pttPlaybackSuppressed) {
+ this.input.setVoiceSpeaker('ai');
++ if (!messageCurrent()) {
++ settleFencedBoundary();
++ return;
++ }
+ this.audio?.play(part.inlineData.data, part.inlineData.mimeType);
++ if (!messageCurrent()) {
++ settleFencedBoundary();
++ return;
++ }
+ this.modelSpoke = true;
+ this.narration.audible();
+ }
+ }
+ }
+ if (message.toolCall?.functionCalls?.length)
+ this.enqueueTools(message.toolCall.functionCalls, epoch);
+ if (content?.turnComplete) {
+ if (this.typedIntent) {
+ this.typedIntent.automaticPredecessor = null;
+ this.typedIntent.retiredAutomaticPredecessor = null;
+ }
+ this.pttPlaybackSuppressed = false;
+ // A native terminal boundary also completes a silent user turn. Output,
+ // pending tools and queued controls still gate presentation completion.
+ this.userTurnPending = false;
+ this.replyPending = false;
+ this.automaticTurnOpen = false;
+ this.automaticActivityOwner = null;
+ this.retiredAutomaticActivityOwner = null;
+ this.modelComplete = true;
+ this.pendingCompletionStatus = content.interrupted
+ ? 'interrupted'
+ : 'completed';
+ this.completedTurns++;
+ // Native input captions have no response identity. A model completion
+ // cannot finalize them or join speech from either side of an interruption.
+ if (this.transcripts.assistant) {
+ this.emit({
+ type: 'transcript',
+ role: 'assistant',
+ text: this.transcripts.assistant,
+ final: true,
+ responseId: this.intentResponseId,
+ });
++ if (!messageCurrent()) return;
+ this.transcripts.assistant = '';
+ }
+ this.finishPlayback();
+ }
+ }
+
+ transcript(role, value) {
+ if (role === 'assistant')
+ this.transcripts.assistant = (
+ this.transcripts.assistant + value.text
+ ).slice(-16000);
+ this.emit({
+ type: 'transcript',
+ role,
+ text: value.text,
+ final: false,
+ responseId: role === 'user' ? null : this.intentResponseId,
+ ...(role === 'user' ? { attribution: 'unverified', delta: true } : {}),
+ });
+ }
+
+ rememberCallIds(ids) {
+ const freshIds = new Set(ids.filter((id) => !this.seenCalls.has(id)));
+ // Forgetting an old ID would let its replay acquire a new turn's authority.
+ // Reserve the entire batch before changing policy or queuing any action.
+ if (this.seenCalls.size + freshIds.size > MAX_SEEN_CALLS)
+ throw new Error(
- 'Gemini action history is full. Start voice again for a fresh session.',
++ msg(
++ 'Gemini action history is full. Start voice again for a fresh session.',
++ ),
+ );
+ for (const id of freshIds) this.seenCalls.add(id);
+ }
+
+ enqueueTools(calls, epoch) {
+ if (
+ calls.length > MAX_TOOL_CALLS ||
+ this.pendingTools + calls.length > MAX_TOOL_CALLS
+ )
- throw new Error('Gemini requested too many simultaneous actions');
++ throw new Error(msg('Gemini requested too many simultaneous actions'));
+ const turn = this.turn;
+ this.userTurnPending = false;
+ this.modelComplete = false;
- // Only accepted, new calls may affect turn policy. Malformed or replayed
- // setter calls must not quarantine an otherwise unrelated current turn.
++ // Admit each valid native call ID once per connection.
+ const batchIds = new Set();
+ const acceptedCalls = calls.filter((call) => {
+ if (
+ !validCallId(call?.id) ||
+ typeof call.name !== 'string' ||
+ this.seenCalls.has(call.id) ||
+ batchIds.has(call.id)
+ )
+ return false;
+ batchIds.add(call.id);
+ return true;
+ });
+ this.rememberCallIds(acceptedCalls.map((call) => call.id));
- // The model's own setter call marks a provider request without trusting
- // captions. Refuse every not-yet-started tool for the rest of this turn.
- if (acceptedCalls.some((call) => call.name === 'set_voice_provider'))
- this.providerQuarantine = { epoch, turn };
+ for (const call of acceptedCalls) {
+ this.pendingTools++;
+ const action = new AbortController();
+ action.call = { id: call.id, name: call.name };
+ action.sequence = ++this.toolSequence;
+ this.tools.set(call.id, action);
+ const priorTools = this.toolQueue;
+ const args =
+ call.args && typeof call.args === 'object' && !Array.isArray(call.args)
+ ? call.args
+ : {};
+ // Stronger Radio controls must reach their shared reservation/result
+ // owner while an older selection is awaiting a service. Keep ordinary
+ // siblings ordered, and retain every in-flight call in the drain promise.
- // executeTool still checks currentness and provider policy before any
++ // executeTool still checks currentness before any
+ // reservation; only a successful stronger result revokes older work.
- const { stronger } = classifyVoiceTool(call.name, args);
++ const { stronger } = classifyGeminiTool(call.name, args);
+ const execution = (stronger ? Promise.resolve() : priorTools)
+ .then(async () => {
+ if (!this.owns(epoch) || turn !== this.turn) return;
+ if (this.cancelledCalls.has(call.id)) {
+ if (this.tools.get(call.id) === action) this.tools.delete(call.id);
+ this.pendingTools--;
- if (!this.pendingTools)
- this.setStatus('listening', 'Ask or command');
++ if (!this.pendingTools) {
++ this.setStatus('listening', msg('Ask or command'));
++ if (this.owns(epoch) && turn === this.turn) this.finishPlayback();
++ }
+ return;
+ }
+ await this.executeTool(call, epoch, turn, action);
+ })
+ .catch((error) => {
+ if (this.owns(epoch) && turn === this.turn) this.fail(error);
+ });
+ this.toolQueue = stronger
+ ? Promise.all([priorTools, execution]).then(() => {})
+ : execution;
+ }
+ }
+
+ async executeTool(call, epoch, turn, action) {
+ const args =
+ call.args && typeof call.args === 'object' && !Array.isArray(call.args)
+ ? call.args
+ : {};
- // The deadline bounds this call. Deferred work it leaves behind (for
- // example an outline) belongs to the turn, so detach it on settlement.
+ const deadline = AbortSignal.timeout(45_000);
+ const expire = () => action.abort(deadline.reason);
+ deadline.addEventListener('abort', expire, { once: true });
+ const toolSignal = AbortSignal.any([action.signal, this.turnAbort.signal]);
- const responseId = this.intentResponseId;
- // The current socket/turn/call owns native tool dispatch. Only first-party
- // typed text has independently known request content; speech captions do not.
- const userTurn = this.readTypedTurnInput(turn);
- const restriction =
- call.name === 'set_voice_provider' || this.providerQuarantined(turn)
- ? { kind: 'provider' }
- : readVoiceRequestRestriction(userTurn);
- const inputRestricted = Boolean(restriction);
+ const {
+ radioControl,
+ radioVisibility,
- radioAction,
+ authorityDomain: authority,
+ stronger,
+ abortScope,
- } = classifyVoiceTool(call.name, args);
- const reservation =
- stronger && !inputRestricted
- ? this.radio.reserveRadioToolHandoff({ abortScope })
- : null;
- const handoffEpoch = this.radio.radioHandoffEpoch;
++ } = classifyGeminiTool(call.name, args);
++ let reservation = null;
++ let handoffEpoch = this.radio.radioHandoffEpoch;
+ const current = () =>
+ this.owns(epoch) && this.turn === turn && !toolSignal.aborted;
+ const actionCurrent = () =>
+ current() &&
+ !this.radioSuperseded(action, authority, epoch, turn) &&
+ (authority !== 'playback' ||
+ handoffEpoch === this.radio.radioHandoffEpoch);
- if (authority && !inputRestricted)
- this.radio.registerTool(action, {
- responseId: String(turn),
- authorityDomain: authority,
- });
- if (!inputRestricted) {
- this.setStatus('executing', 'Running command');
++ let result;
++ try {
++ if (!actionCurrent()) throw cancelled();
++ if (stronger)
++ reservation = this.radio.reserveRadioToolHandoff({ abortScope });
++ handoffEpoch = this.radio.radioHandoffEpoch;
++ if (!actionCurrent()) throw cancelled();
++ if (authority)
++ this.radio.registerTool(action, {
++ responseId: String(turn),
++ authorityDomain: authority,
++ });
++ this.setStatus('executing', msg('Running command'));
++ // A common state observer may synchronously stop/replace the session.
++ if (!actionCurrent()) throw cancelled();
+ this.radio.pauseRadioForVoice();
++ if (!actionCurrent()) throw cancelled();
+ if (this.modelSpoke) this.narration.preamble();
+ this.narration.toolStarted(call.id, {
+ name: call.name,
+ label: narrationLabel(call.name, args),
+ narrate: !radioControl && !radioVisibility,
+ });
- }
- let result;
- try {
+ if (!actionCurrent()) throw cancelled();
- if (inputRestricted) {
- result = voiceRequestRestrictionResult(call.name, restriction, {
- providerDropdown: this.providerDropdown() === true,
- });
- } else {
- result = await awaitWithSignal(
- this.runAction(call.name, args, {
- signal: toolSignal,
- callId: call.id,
- userTurn,
- responseId,
- progress: (update) => {
- if (actionCurrent()) this.narration.progress(call.id, update);
- },
- isCurrent: actionCurrent,
- }),
- toolSignal,
- );
- }
++ const execution = Promise.resolve(
++ this.runAction(call.name, args, {
++ signal: toolSignal,
++ callId: call.id,
++ progress: (update) => {
++ if (actionCurrent()) this.narration.progress(call.id, update);
++ },
++ isCurrent: actionCurrent,
++ }),
++ );
++ // action-call observers can abort before waitForSignal receives the
++ // already-started operation; retain its rejection handler in that case.
++ void execution.catch(() => {});
++ result = await waitForSignal(execution, toolSignal);
+ if (!actionCurrent()) throw cancelled();
+ if (result?.ok && result.radioPlaybackRequested) {
- // A runner may reuse an envelope; handoff identity belongs to this call.
+ const playbackResult = { ...result };
+ this.radioPlaybackCalls.set(playbackResult, {
+ id: call.id,
+ epoch,
+ turn,
- userTurn,
+ });
+ this.radio.setPendingPlayback(playbackResult);
+ }
+ if (
+ result?.action === 'get_entity_context' &&
+ shouldSendViewportImage(result.scene?.basemap?.viewScale) &&
+ !hasStructuredViewIdentity(result) &&
+ this.now() - this.lastViewportAt >= 1000
+ ) {
- const image = await this.captureViewport();
- if (current() && image?.startsWith('data:image/jpeg;base64,')) {
++ const capture = Promise.resolve(this.captureViewport());
++ void capture.catch(() => {});
++ const image = await waitForSignal(capture, toolSignal);
++ if (actionCurrent() && image?.startsWith('data:image/jpeg;base64,')) {
+ this.lastViewportAt = this.now();
+ this.send({
+ realtimeInput: {
+ video: {
+ mimeType: 'image/jpeg',
+ data: image.slice(image.indexOf(',') + 1),
+ },
+ },
+ });
+ }
+ }
+ } catch (error) {
+ result = {
+ ok: false,
+ tool: call.name,
+ ...(radioVisibility ? { layerId: 'radio' } : {}),
+ error:
+ error?.name === 'AbortError'
+ ? 'Action cancelled by a newer request'
+ : error?.message || 'GEV command failed',
+ };
+ } finally {
+ deadline.removeEventListener('abort', expire);
+ if (this.tools.get(call.id) === action) this.tools.delete(call.id);
- if (!inputRestricted) {
- this.radio.releaseTool(action);
- if (this.owns(epoch) && turn === this.turn)
- this.narration.toolFinished(call.id);
- }
++ this.radio.releaseTool(action);
++ if (this.owns(epoch) && turn === this.turn)
++ this.narration.toolFinished(call.id);
+ }
+ if (!this.owns(epoch) || turn !== this.turn) return;
+ this.pendingTools--;
- if (reservation) {
++ // Successful stronger ownership commits before the result is serialized.
++ // A failed reservation stays held until after its failure reaches transport.
++ if (reservation && result?.ok) {
+ this.radio.settleRadioToolHandoffReservation(reservation, {
- commit: Boolean(result?.ok),
++ commit: true,
+ responseId: String(turn),
+ });
- if (result?.ok) this.noteRadioStrongerCommit(action, abortScope, turn);
++ reservation = null;
++ this.noteRadioStrongerCommit(action, abortScope, turn);
+ }
++ if (!this.owns(epoch) || turn !== this.turn) return;
+ const playbackObsolete =
+ authority === 'playback' && handoffEpoch !== this.radio.radioHandoffEpoch;
- result = reconcileRadioToolResult(result, {
- dataManager: this.dataManager,
- radioLayer: this.radioLayer,
- suppressPlayback: playbackObsolete,
- });
++ if (radioControl || radioVisibility) {
++ const state = this.radioLayer?.getUIState?.() || {};
++ const lifecycle = readLayerLifecycleSummary(this.dataManager, 'radio', {
++ fallbackEnabled: state.enabled ?? result?.enabled,
++ });
++ result = {
++ ...result,
++ ...lifecycle,
++ audioState: state.audioState || result?.audioState || 'stopped',
++ ...(result?.radioAction === 'pause' && lifecycle.enabled === false
++ ? { changed: false }
++ : {}),
++ ...(playbackObsolete && result?.ok && result.radioPlaybackRequested
++ ? { radioPlaybackRequested: false, radioPlaybackSuppressed: true }
++ : {}),
++ };
++ }
+ if (
+ !this.cancelledCalls.has(call.id) &&
- shouldStopVoiceAfterToolResult(result)
++ shouldStopVoiceAfterRadioTool(result) &&
++ !result.radioPlaybackRequested &&
++ !result.radioPlaybackSuppressed
+ )
+ this.stopAfterReply = true;
- // A server cancellation already discarded this call; do not revive it.
++ // Native call cancellation suppresses its output, without canceling siblings.
+ if (!this.cancelledCalls.has(call.id)) {
+ this.postToolOutput = false;
+ this.modelComplete = false;
+ this.replyPending = true;
+ const mapSnapshot = [...this.pendingMapEvents];
+ const mapEvents = mapSnapshot.map((text) => JSON.parse(text));
- const response = projectVoiceToolResultForModel({
++ const response = {
+ ...(result ?? { ok: false, error: 'Command returned no result' }),
- responseGuidance: toolResultGuidance(result),
- });
++ responseGuidance: responseInstructionForToolResult(result),
++ };
+ this.send(
+ {
+ toolResponse: {
+ functionResponses: [
+ {
+ id: call.id,
+ name: call.name,
+ response: mapEvents.length
+ ? { ...response, mapEvents }
+ : response,
+ },
+ ],
+ },
+ },
+ { onSent: () => this.consumeMapEvents(mapSnapshot) },
+ );
+ }
- if (!this.pendingTools) this.setStatus('listening', 'Ask or command');
++ if (!this.owns(epoch) || turn !== this.turn) return;
++ if (reservation)
++ this.radio.settleRadioToolHandoffReservation(reservation, {
++ commit: false,
++ responseId: String(turn),
++ });
++ if (this.owns(epoch) && turn === this.turn && !this.pendingTools) {
++ this.setStatus('listening', msg('Ask or command'));
++ if (this.owns(epoch) && turn === this.turn) this.finishPlayback();
++ }
+ }
+
+ finishPlayback() {
+ if (this.goAway && this.now() >= this.goAway.deadline) {
+ this.finishGoAway();
+ return;
+ }
+ if (
+ !this.isActive() ||
+ !this.modelComplete ||
+ this.userTurnPending ||
+ this.pendingTools ||
+ (this.input.pushToTalkMode &&
+ this.captureOwner &&
+ !this.captureOwner.retired &&
+ !this.captureOwner.admitted &&
+ !this.captureOwner.settled) ||
+ this.audio?.pending ||
+ this.controlQueue.length
+ )
+ return;
+ const completionStatus = this.pendingCompletionStatus;
+ this.pendingCompletionStatus = null;
+ this.narration.cancel();
+ if (completionStatus) {
+ const responseId = this.intentResponseId;
+ const completionEpoch = this.epoch;
+ const completionTurn = this.turn;
+ this.emit({
+ type: 'completion',
+ status: completionStatus,
+ responseId,
+ spoken: Boolean(this.modelSpoke),
+ audioDrained: true,
+ });
+ // Observers may synchronously accept new input or replace the session.
+ // Old completion must not clear its metadata or overwrite its status.
+ if (this.epoch !== completionEpoch || this.turn !== completionTurn)
+ return;
- // Provider completion is not a new first-party input boundary. Keep a
- // typed request's authority for later tools in this same local turn.
- if (!this.readTypedTurnInput())
- this.userTurns.completeResponse(responseId);
++ // Caption completion does not create an input or tool authority boundary.
+ this.clearSettledSpeechIntent();
+ }
+ // A completion observer may replace this provider immediately. Do not let
+ // the retired session update UI or start delayed Radio work afterward.
+ if (!this.isActive()) return;
+ this.input.setVoiceSpeaker('idle');
- this.setStatus('listening', 'Ask or command');
++ this.setStatus('listening', msg('Ask or command'));
+ if (this.stopAfterReply && this.postToolOutput) {
+ this.stop({ preserveRadioPlayback: true });
+ return;
+ }
+ if (this.goAway) {
+ this.finishGoAway();
+ return;
+ }
+ if (this.postToolOutput && this.radio.pendingRadioPlaybackResult)
+ void this.radio.startPendingRadioHandoff();
+ }
+
+ sendTextCommand(text) {
+ const clean = String(text || '').trim();
+ if (!clean || this.goAway) return false;
- if (clean.length > 16000) throw new Error('Voice text command is too long');
++ if (clean.length > 16000)
++ throw new Error(msg('Voice text command is too long'));
+ if (this.channel?.readyState !== 'open')
- throw new Error('Gemini voice is not connected');
++ throw new Error(msg('Gemini voice is not connected'));
+ if (this.input.pushToTalkMode && this.captureOwner)
+ this.captureOwner.retired = true;
+ const automaticPredecessor =
+ this.automaticTurnOpen &&
+ !this.replyPending &&
+ !this.retiredReplyPending &&
+ !this.deferredInput
+ ? this.automaticActivityOwner
+ : null;
+ if (!this.interrupt('user-text')) return false;
+ const epoch = this.epoch;
+ const turn = this.turn;
+ const generation = this.inputGeneration;
+ const owned = () =>
+ this.owns(epoch) &&
+ this.turn === turn &&
+ this.inputGeneration === generation;
+ // Typed intent supersedes the held speech even if its worklet end is late.
+ // Close the forwarded manual activity before submitting the new text.
+ if (this.input.pushToTalkMode && this.forwardedActivityOpen)
+ this.send(
+ { realtimeInput: { activityEnd: {} } },
+ { captureId: this.forwardedCaptureId },
+ );
+ if (!owned()) return false;
- this.userTurns.text(clean);
- if (!owned()) return false;
+ const typedIntent = {
+ epoch: this.epoch,
+ turn: this.turn,
++ text: clean,
+ responseId: `gemini-response-${this.epoch}-${++this.intentSequence}`,
+ automaticPredecessor,
+ retiredAutomaticPredecessor: null,
+ };
- // Bind the accepted text now, rather than whatever input happens to be
- // current when reliable transport or a retired reply eventually drains.
- this.userTurns.expectResponse();
- this.userTurns.bindResponse(typedIntent.responseId);
++ // Keep local presentation ownership while reliable transport drains.
+ this.typedIntent = typedIntent;
+ this.beginPointerTurn('text', undefined, owned);
+ if (!owned()) return false;
+ const context = this.pendingPointerContext;
+ const mapSnapshot = [...this.pendingMapEvents];
+ const parts = context ? [{ text: JSON.stringify(context.item) }] : [];
+ if (this.pendingMapEvents.length)
+ parts.push({
+ text: JSON.stringify({
+ type: 'map_events',
+ events: mapSnapshot.map((value) => JSON.parse(value)),
+ }),
+ });
+ parts.push({ text: clean });
+ const sent = this.sendUserInput(
+ {
+ clientContent: { turns: [{ role: 'user', parts }], turnComplete: true },
+ },
+ undefined,
+ {
+ onSent: () => {
+ if (!owned() || this.typedIntent !== typedIntent) return;
+ this.replyPending = true;
+ this.bindTextIntent(typedIntent);
+ if (!owned() || this.typedIntent !== typedIntent) return;
+ this.consumePointerContext(context);
+ this.consumeMapEvents(mapSnapshot);
+ },
+ },
+ );
+ if (sent && owned()) {
+ this.narration.userTurnEnded();
+ }
+ return sent && owned();
+ }
+
+ consumeMapEvents(snapshot) {
+ // Queue acceptance is not delivery. A cancelled envelope retains passive
+ // context for the next genuine turn, and new events cannot be erased.
+ if (snapshot.every((text, index) => this.pendingMapEvents[index] === text))
+ this.pendingMapEvents.splice(0, snapshot.length);
+ }
+
+ validCaptureMetadata(metadata) {
+ return Number.isSafeInteger(metadata?.captureId) && metadata.captureId > 0;
+ }
+
+ acceptsCapture(metadata) {
+ return (
+ this.validCaptureMetadata(metadata) &&
+ metadata.captureId === this.captureOwner?.captureId &&
+ !this.captureOwner.retired
+ );
+ }
+
+ sendUserInput(message, metadata, { onSent = null } = {}) {
+ const owner = this.deferredInput;
+ const input = message.realtimeInput;
+ const captureContext = message.clientContent?.turnComplete === false;
+ // A superseded start cannot read the current pointer or acquire its queue.
+ // Only an end for the actually forwarded old activity may close that wire.
+ if (
+ captureContext ||
+ input?.activityStart ||
+ input?.activityEnd ||
+ input?.audio
+ ) {
+ if (!this.validCaptureMetadata(metadata)) return false;
+ if (!this.acceptsCapture(metadata)) {
+ return input?.activityEnd &&
+ this.forwardedActivityOpen &&
+ this.forwardedCaptureId === metadata.captureId
+ ? this.send(message, { captureId: metadata.captureId, onSent })
+ : false;
+ }
+ }
+ if (
+ input?.activityEnd &&
+ !this.forwardedActivityOpen &&
+ !this.controlQueue.some(
+ (entry) =>
+ entry.captureId === metadata?.captureId &&
+ entry.message.realtimeInput?.activityStart,
+ ) &&
+ !owner?.activityOpen
+ )
+ return true;
+ if (!owner)
+ return this.send(message, {
+ captureId: metadata?.captureId ?? null,
+ onSent,
+ });
+ if (!this.owns(owner.epoch) || owner.turn !== this.turn) return false;
+ // Worklet callbacks keep the previous end ahead of the new start. After
+ // replacing unsent input, that old end/PCM has no new gesture to belong to.
+ if (input?.activityEnd && !owner.activityOpen)
+ return this.forwardedActivityOpen
+ ? this.send(message, { captureId: this.forwardedCaptureId, onSent })
+ : true;
+ if (
+ input?.audio &&
+ (!owner.activityOpen || owner.kind !== 'push-to-talk')
+ ) {
+ // These frames cannot be replayed under the deferred explicit owner.
+ // Preserve that discard policy while making the loss observable.
+ this.droppedAudioChunks++;
+ this.deferredAudioDrops[
+ owner.kind !== 'push-to-talk' ? 'nonPttOwner' : 'closedActivity'
+ ]++;
+ return true;
+ }
+ const bytes = new TextEncoder().encode(JSON.stringify(message)).byteLength;
+ if (
+ owner.bytes + bytes > MAX_BUFFERED_BYTES ||
+ this.now() >= owner.deadline
+ ) {
+ this.fail(
+ new Error(
- 'Gemini interrupted input exceeded its buffer or wait limit. Start voice again.',
++ msg(
++ 'Gemini interrupted input exceeded its buffer or wait limit. Start voice again.',
++ ),
+ ),
+ );
+ return false;
+ }
+ if (input?.activityStart) {
+ owner.activityOpen = true;
+ owner.captureId = metadata?.captureId;
+ }
+ if (input?.activityEnd) owner.activityOpen = false;
+ owner.messages.push(message);
+ if (onSent) {
+ owner.onSent ||= new Map();
+ owner.onSent.set(message, onSent);
+ }
+ owner.bytes += bytes;
+ return true;
+ }
+
+ clearDeferredInput() {
+ if (this.deferredInput) this.clearTimer(this.deferredInput.timer);
+ this.deferredInput = null;
+ }
+
+ clearRetiredBoundaryWait() {
+ if (this.retiredBoundaryWait)
+ this.clearTimer(this.retiredBoundaryWait.timer);
+ this.retiredBoundaryWait = null;
+ }
+
+ waitForRetiredBoundary(owner) {
+ this.clearRetiredBoundaryWait();
+ const wait = { epoch: owner.epoch, deadline: owner.deadline };
+ this.retiredBoundaryWait = wait;
+ wait.timer = this.setTimer(
+ () => {
+ if (
+ this.retiredBoundaryWait === wait &&
+ this.owns(wait.epoch) &&
+ this.retiredReplyPending
+ )
+ this.fail(
+ new Error(
- 'Gemini did not finish the interrupted reply. Start voice again.',
++ msg(
++ 'Gemini did not finish the interrupted reply. Start voice again.',
++ ),
+ ),
+ );
+ },
+ Math.max(0, wait.deadline - this.now()),
+ );
+ wait.timer.unref?.();
+ }
+
+ // A first retirement has no deferred owner, yet everything Live sends is
+ // discarded until the old boundary. Never leave that wait unbounded.
+ boundRetiredReply() {
+ if (
+ !this.retiredReplyPending ||
+ this.deferredInput ||
+ this.retiredBoundaryWait
+ )
+ return;
+ this.waitForRetiredBoundary({
+ epoch: this.epoch,
+ deadline: this.now() + this.inputBoundaryTimeoutMs,
+ });
+ this.retiredBoundaryWait.extendable = true;
+ }
+
+ flushDeferredInput() {
+ const owner = this.deferredInput;
+ if (!owner) return;
+ this.clearDeferredInput();
- if (!this.owns(owner.epoch) || owner.turn !== this.turn) return;
++ const generation = this.inputGeneration;
++ const current = () =>
++ this.owns(owner.epoch) &&
++ owner.turn === this.turn &&
++ generation === this.inputGeneration;
++ if (!current()) return;
+ if (this.now() >= owner.deadline) {
+ this.fail(
+ new Error(
- 'Gemini did not finish the interrupted reply. Start voice again.',
++ msg(
++ 'Gemini did not finish the interrupted reply. Start voice again.',
++ ),
+ ),
+ );
+ return;
+ }
+ // The already submitted successor is now the one being retired. Send the
+ // newest start/text immediately to trigger its own provider boundary.
+ this.retiredReplyPending = true;
+ // The forwarded predecessor here is explicit PTT/text, not a later VAD
+ // activity that may have arrived while its boundary was pending.
+ this.retiredAutomaticActivityOwner = null;
+ // Flushing (even an empty capture queue) must not remove the absolute
+ // recovery bound while the forwarded predecessor still owns output.
+ this.waitForRetiredBoundary(owner);
+ this.replyPending = false;
+ for (const message of owner.messages) {
++ if (!current()) return;
+ const onSent = owner.onSent?.get(message);
- if (
- !this.send(message, {
- captureId: owner.captureId ?? null,
- onSent: () => {
- onSent?.();
- if (
- (message.clientContent &&
- message.clientContent.turnComplete !== false) ||
- message.realtimeInput?.audio ||
- message.realtimeInput?.text
- )
- this.replyPending = true;
- },
- })
- )
- continue;
++ this.send(message, {
++ captureId: owner.captureId ?? null,
++ onSent: () => {
++ if (!current()) return;
++ onSent?.();
++ if (!current()) return;
++ if (
++ (message.clientContent &&
++ message.clientContent.turnComplete !== false) ||
++ message.realtimeInput?.audio ||
++ message.realtimeInput?.text
++ )
++ this.replyPending = true;
++ },
++ });
++ if (!current()) return;
+ }
- if (owner.context && !this.controlQueue.length)
++ if (current() && owner.context && !this.controlQueue.length)
+ this.consumePointerContext(owner.context);
+ }
+
+ /** Use the common pointer owner; held speech context precedes audio quietly. */
+ beginPointerTurn(at, capturedSnapshot = undefined, isCurrent = () => true) {
+ if (!this.pointer || !isCurrent()) return null;
+ // The delayed manual speech notification still refers to the released hold.
+ if (
+ capturedSnapshot === undefined &&
+ at === 'speech_start' &&
+ this.input.pushToTalkMode &&
+ !this.pointer.isHeld?.()
+ )
+ return this.pointer.activeSnapshot?.() || null;
+ const gesture =
+ at === 'keydown' || (at === 'speech_start' && this.input.pushToTalkMode);
+ let snapshot = null;
+ try {
+ snapshot = this.pointer.beginTurn(
+ at,
+ capturedSnapshot !== undefined
+ ? { capturedSnapshot }
+ : gesture
+ ? {}
+ : { recentMs: POINTER_OPEN_MIC_RECENT_MS },
+ );
+ } catch {
+ snapshot = null;
+ }
+ if (!isCurrent()) return null;
+ const chip = pointerChip(snapshot);
+ this.pointerAnnounced = gesture && chip ? snapshot : null;
+ this.emit({
+ type: 'pointer',
+ pointer:
+ gesture && chip ? { ...chip, screenPx: snapshot.screenPx } : null,
+ });
+ if (!isCurrent()) return null;
+ const item = !chip
+ ? this.pointerSentKey && this.pointerSentKey !== 'none'
+ ? { type: 'pointer_context', at, target: 'none' }
+ : null
+ : gesture
+ ? pointerContextItem(snapshot)
+ : {
+ type: 'pointer_context',
+ at,
+ pointing: snapshot.entity?.kind || 'ground',
+ };
+ const { at: _at, ...identity } = item || {};
+ const key = chip ? JSON.stringify(identity) : 'none';
+ this.pendingPointerContext =
+ item && key !== this.pointerSentKey ? { item, key } : null;
+ return snapshot;
+ }
+
+ /** Reveal an implicit referent only after the shared action runner uses it. */
+ announcePointer() {
+ const snapshot = this.pointer?.activeSnapshot?.() || null;
+ const chip = pointerChip(snapshot);
+ if (!chip || snapshot === this.pointerAnnounced) return false;
+ this.pointerAnnounced = snapshot;
+ this.emit({
+ type: 'pointer',
+ pointer: { ...chip, screenPx: snapshot.screenPx },
+ });
+ return true;
+ }
+
+ /** Pointing accompanies speech without asking Live to answer the context. */
+ sendPointerContext(context, metadata) {
+ if (!context) return true;
+ const message = {
+ clientContent: {
+ turns: [
+ { role: 'user', parts: [{ text: JSON.stringify(context.item) }] },
+ ],
+ turnComplete: false,
+ },
+ };
+ // Context has the same physical owner and queue as its PTT start/PCM/end.
+ const deferred = Boolean(this.deferredInput);
+ const accepted = this.sendUserInput(message, metadata, {
+ onSent: () => this.consumePointerContext(context),
+ });
+ if (accepted && deferred) this.consumePointerContext(context);
+ return accepted;
+ }
+
+ consumePointerContext(context) {
+ if (!context) return;
+ if (this.deferredInput) {
+ this.deferredInput.context = context;
+ if (this.pendingPointerContext === context)
+ this.pendingPointerContext = null;
+ return;
+ }
+ this.pointerSentKey = context.key;
+ if (this.pendingPointerContext === context)
+ this.pendingPointerContext = null;
+ }
+
+ // Any clientContent message can interrupt Live generation, including one
+ // with turnComplete:false. Passive map results wait for an explicit turn
+ // or a tool response; they must never cut off spoken output or start speech.
+ notifyMapEvent(event) {
+ if (this.goAway || this.channel?.readyState !== 'open') return false;
+ let text;
+ try {
+ text = JSON.stringify(event);
+ } catch {
+ return false;
+ }
+ if (!text || text.length > MAX_MAP_CONTEXT_LENGTH) return false;
+ this.pendingMapEvents.push(text);
+ while (
+ this.pendingMapEvents.length > MAX_MAP_EVENTS ||
+ this.pendingMapEvents.reduce((sum, value) => sum + value.length, 0) >
+ MAX_MAP_CONTEXT_LENGTH
+ )
+ this.pendingMapEvents.shift();
+ return true;
+ }
+
+ beginSpeechIntent(captureId) {
- if (this.retiredReplyPending && this.readTypedTurnInput()) return;
++ if (this.retiredReplyPending && this.currentTypedInput()) return;
+ // Local onset labels serve timing/UI only. They do not assert native
+ // transcript ownership or mint a completed-speech authorization token.
+ this.clearSettledSpeechIntent();
+ // interrupt() revokes old input when a new local turn actually starts.
+ // Onsets racing a retired reply must not erase its typed successor.
+ this.intentItemId = `gemini-input-${this.epoch}-${++this.intentSequence}`;
+ this.intentResponseId = null;
+ this.intentCaptureId = captureId;
+ // A physical speech onset clears display-only recent captions, including
+ // when retirement already fenced the reply and no second interrupt runs.
- const epoch = this.epoch;
- const turn = this.turn;
- const generation = this.inputGeneration;
- this.emit({ type: 'user-caption-reset' });
- if (
- !this.owns(epoch) ||
- this.turn !== turn ||
- this.inputGeneration !== generation
- )
- return;
- this.emit({ type: 'user-turn-start' });
++ this.emit({ type: 'transcript', role: 'user', text: '', final: false });
+ }
+
+ bindSpeechIntent() {
+ if (!this.intentItemId || this.intentResponseId) return;
+ this.intentResponseId = `gemini-response-${this.epoch}-${this.intentSequence}`;
- this.emitIntentResponse();
+ }
+
- readTypedTurnInput(turn = this.turn) {
- const intent = this.typedIntent;
- if (!intent || intent.epoch !== this.epoch || intent.turn !== turn) return;
- const input = this.userTurns.forResponse(intent.responseId);
- return readVoiceUserTurnInputKind(input) === 'typed' ? input : undefined;
++ currentTypedInput(turn = this.turn) {
++ const input = this.typedIntent;
++ return input?.epoch === this.epoch && input.turn === turn ? input : null;
+ }
+
+ // Stronger Radio controls skip the ordered queue. An older Radio call still
+ // waiting behind a sibling must not start after a successful stronger
+ // result has revoked it; later calls in the same turn remain the model's.
+ noteRadioStrongerCommit(action, abortScope, turn) {
+ let commit = this.radioStrongerCommit;
+ if (commit?.epoch !== this.epoch || commit.turn !== turn)
+ commit = this.radioStrongerCommit = {
+ epoch: this.epoch,
+ turn,
+ all: 0,
+ playback: 0,
+ };
+ const scope = abortScope === 'all' ? 'all' : 'playback';
+ commit[scope] = Math.max(commit[scope], action.sequence);
+ }
+
+ radioSuperseded(action, authority, epoch, turn) {
+ const commit = this.radioStrongerCommit;
+ // Read-only status queries stay current, as for the shared sibling abort.
+ if (
+ !authority ||
+ authority === 'query' ||
+ commit?.epoch !== epoch ||
+ commit.turn !== turn
+ )
+ return false;
+ return (
+ action.sequence < commit.all ||
+ (authority === 'playback' && action.sequence < commit.playback)
+ );
+ }
+
- providerQuarantined(turn = this.turn) {
- const quarantine = this.providerQuarantine;
- return Boolean(
- quarantine && quarantine.epoch === this.epoch && quarantine.turn === turn,
- );
- }
-
+ bindTextIntent(intent) {
+ if (
+ intent !== this.typedIntent ||
+ intent.epoch !== this.epoch ||
+ intent.turn !== this.turn
+ )
+ return;
+ this.clearSettledSpeechIntent();
+ this.intentResponseId = intent.responseId;
- this.emitIntentResponse();
- }
-
- emitIntentResponse() {
- if (this.intentResponseId)
- this.emit({
- type: 'response-start',
- responseId: this.intentResponseId,
- userTurn: this.userTurns.forResponse(this.intentResponseId),
- });
++ this.emit({
++ type: 'transcript',
++ role: 'user',
++ text: intent.text,
++ final: true,
++ });
+ }
+
+ clearSettledSpeechIntent() {
+ this.intentResponseId = null;
+ this.intentItemId = null;
+ this.intentCaptureId = null;
+ }
+
+ beginGoAway(timeLeft, epoch) {
+ const duration =
+ typeof timeLeft === 'string' &&
+ /^(?:\d{1,6})(?:\.\d{1,9})?s$/.test(timeLeft)
+ ? Number(timeLeft.slice(0, -1)) * 1000
+ : 0;
+ const milliseconds = Math.min(
+ MAX_GO_AWAY_MS,
+ Number.isFinite(duration) ? duration : 0,
+ );
+ const deadline = this.now() + milliseconds;
+ if (this.goAway && this.goAway.deadline <= deadline) return;
+ const supersededSuccessor =
+ Boolean(this.deferredInput) || Boolean(this.goAway?.supersededSuccessor);
+ if (this.goAway) this.clearTimer(this.goAway.timer);
+ const owner = {
+ epoch,
+ turn: this.turn,
+ deadline,
+ timer: null,
+ // Dropping the newest unsent input must not make its superseded,
+ // already forwarded predecessor current at the retired boundary.
+ supersededSuccessor,
+ };
+ this.goAway = owner;
+ this.clearDeferredInput();
+ owner.timer = this.setTimer(() => {
+ if (this.goAway === owner && this.owns(epoch)) this.finishGoAway();
+ }, milliseconds);
+ owner.timer?.unref?.();
+ this.input.setMicrophoneEnabled(false);
+ this.radio.cancelRadioHandoff();
+ this.setStatus(
+ this.status,
- 'Gemini session expiring; finishing the current reply',
++ msg('Gemini session expiring; finishing the current reply'),
+ );
+ if (
+ milliseconds === 0 ||
+ (!this.replyPending &&
+ !this.automaticTurnOpen &&
+ !this.pendingTools &&
+ !this.audio?.pending &&
+ !this.controlQueue.length)
+ )
+ this.finishGoAway();
+ else this.finishPlayback();
+ }
+
+ finishGoAway() {
+ if (!this.goAway) return;
+ this.fail(
+ new Error(
- 'Gemini Live connection is expiring. Start voice again for a new conversation.',
++ msg(
++ 'Gemini Live connection is expiring. Start voice again for a new conversation.',
++ ),
+ ),
- 'Start voice again for a fresh token and a new conversation.',
++ msg('Start voice again for a fresh token and a new conversation.'),
+ );
+ }
+
+ getDiagnostics() {
+ return {
+ provider: 'gemini',
+ status: this.status,
+ model: this.model,
+ connected: this.channel?.readyState === 'open',
+ microphoneActive: Boolean(
+ this.stream
+ ?.getAudioTracks()
+ .some((track) => track.enabled && track.readyState !== 'ended'),
+ ),
+ pendingTools: this.pendingTools,
+ narration: this.narration.state(),
+ completedTurns: this.completedTurns,
+ audio: this.audio?.diagnostics() || this.lastAudio,
+ error: this.lastError,
+ close: this.lastClose,
+ droppedAudioChunks: this.droppedAudioChunks,
+ deferredAudioDrops: { ...this.deferredAudioDrops },
+ droppedImages: this.droppedImages,
+ queuedControls: this.controlQueue.length,
+ expiring: Boolean(this.goAway),
+ };
+ }
+
+ stop({
+ removeUi = false,
+ preserveStatus = false,
+ preserveRadioPlayback = false,
+ } = {}) {
+ if (this.disposed) return;
+ this.epoch++;
+ this.inputGeneration++;
- this.userTurns.reset();
+ this.clearSettledSpeechIntent();
+ this.clearControls();
+ if (this.goAway) this.clearTimer(this.goAway.timer);
+ this.goAway = null;
+ this.abort?.abort();
+ this.abort = null;
+ this.abortTools();
+ this.earcon.dispose();
+ this.radio.invalidateHandoff();
+ this.radio.stopHandoff({ preserveRadioPlayback });
+ this.radio.clearPendingPlayback();
+ if (this.channel) this.channel.readyState = 'closed';
+ this.channel = null;
+ const socket = this.socket;
+ this.socket = null;
+ if (socket) {
+ socket.onopen = socket.onmessage = socket.onerror = socket.onclose = null;
+ socket.close();
+ }
+ if (this.audio) {
+ const lastAudio = {
+ ...this.audio.diagnostics(),
+ queuedSeconds: 0,
+ resourcesReleased: true,
+ contextState: 'closing',
+ };
+ this.lastAudio = lastAudio;
+ void Promise.resolve(this.audio.close()).then(
+ (closed) => {
+ lastAudio.contextState = closed === false ? 'close-failed' : 'closed';
+ },
+ () => {
+ lastAudio.contextState = 'close-failed';
+ },
+ );
+ }
+ this.audio = null;
+ this.stream?.getTracks().forEach((track) => track.stop());
+ this.stream = null;
+ this.input.cancelPushToTalkHold();
+ this.input.stopVoiceVisualizer();
+ this.pointer?.clear({ keepHold: this.input.pushToTalkKeyHeld });
+ if (!this.input.pushToTalkKeyHeld) this.heldPointerSnapshot = undefined;
+ this.input.resetSession();
+ this.radio.setRadioVoiceDucking(false);
+ this.modelComplete = false;
+ this.pendingCompletionStatus = null;
+ this.postToolOutput = false;
+ this.modelSpoke = false;
+ this.stopAfterReply = false;
+ this.seenCalls.clear();
+ this.cancelledCalls.clear();
+ this.pendingMapEvents = [];
+ this.userTurnPending = false;
+ this.replyPending = false;
+ this.automaticTurnOpen = false;
+ this.automaticActivityOwner = null;
+ this.retiredAutomaticActivityOwner = null;
+ this.automaticActivitySequence = 0;
+ this.retiredReplyPending = false;
+ this.clearDeferredInput();
+ this.clearRetiredBoundaryWait();
+ this.forwardedActivityOpen = false;
+ this.forwardedCaptureId = null;
- this.manualInputKind = null;
+ this.captureEnabled = false;
+ this.pttPlaybackSuppressed = false;
+ this.microphoneRequested = false;
+ this.captureOwner = null;
+ this.userActivityOpen = false;
+ this.pointerSentKey = null;
+ this.pointerAnnounced = null;
+ this.pendingPointerContext = null;
+ this.transcripts = { assistant: '' };
+ if (removeUi) {
+ this.disposed = true;
+ this.status = 'idle';
+ this.input.detachBindings();
+ this.radio.detachObservers();
+ this.signal?.removeEventListener('abort', this.lifetimeAbort);
+ this.ui?.root?.remove();
+ this.emit({ type: 'disposed' });
- } else if (!preserveStatus) this.setStatus('idle', 'Voice off');
++ } else if (!preserveStatus) this.setStatus('idle', msg('Voice off'));
+ }
+}
+
+export function createGeminiSession(options) {
+ const controller = new GeminiSessionController(options);
+ return {
+ controller,
+ capabilities: {
+ costControls: false,
+ pushToTalk: true,
- advisoryLimit:
++ advisoryLimit: t(
+ 'Gemini voice sessions have a time limit. When a session expires, start voice again for a new conversation.',
++ ),
+ },
+ start: (settings) => controller.start(settings),
+ getStartOptions: () => ({
+ pushToTalk: Boolean(controller.input.pushToTalkMode),
+ }),
+ stop: (settings) => controller.stop(settings),
+ sendText: (text) => controller.sendTextCommand(text),
+ sendMapEvent: (event) => controller.notifyMapEvent(event),
+ ignoreButtonClick: () => Boolean(controller.spaceKeyHeld),
+ bindControls: () => controller.input.bindPushToTalkShortcut(),
+ };
+}
diff --cc src/voice/geminiSession.test.mjs
index 7eb87ec27,000000000..e916dd6f6
mode 100644,000000..100644
--- a/src/voice/geminiSession.test.mjs
+++ b/src/voice/geminiSession.test.mjs
@@@ -1,5222 -1,0 +1,3203 @@@
+import test from 'node:test';
+import assert from 'node:assert/strict';
- import { GeminiSessionController, geminiSocketUrl } from './geminiSession.js';
- import { createNarrationScheduler } from './narration.js';
++import { geminiSocketUrl } from './geminiSession.js';
+import { createVoiceSession } from './session.js';
+import { createPointerTracker } from './pointerContext.js';
- import { readVoiceUserTurnText } from './userTurnIntent.js';
+import { withToolCatalog } from './gevRealtime.js';
- import { createGevActionRunner } from './gevActions.js';
- import { VOICE_TOOL_FAILURE_TEXT_LIMIT } from './toolExecutionPolicy.js';
- import { DataLayerManager } from '../data/manager.js';
++import {
++ harness,
++ tick,
++ deferred,
++} from '../testSupport/geminiNativeHarness.mjs';
+
+const endpoint =
+ 'wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContentConstrained';
++
+const credential = {
+ token: 'auth_tokens/test',
+ model: 'gemini-3.8-live',
+ websocketUrl: endpoint,
+ config: { generationConfig: { responseModalities: ['AUDIO'] } },
+};
++
+const manualCredential = {
+ ...credential,
+ config: {
+ ...credential.config,
+ realtimeInputConfig: { automaticActivityDetection: { disabled: true } },
+ },
+};
- const tick = () => new Promise((resolve) => setImmediate(resolve));
- function deferred() {
- let resolve;
- const promise = new Promise((done) => {
- resolve = done;
- });
- return { promise, resolve };
- }
- function harness(overrides = {}) {
- const { autoSetup = true, ...controllerOverrides } = overrides;
- const events = [];
- const sockets = [];
- const media = [];
- const tracks = [];
- const captures = [];
- const calls = [];
- const requests = [];
- const state = { playing: 0, ducked: false, stopped: 0 };
- let clock = 0;
- let nextTimer = 0;
- const timers = new Map();
- const earcon = { playing: false, starts: 0, disposals: 0 };
- const advance = (ms) => {
- const target = clock + ms;
- for (;;) {
- const due = [...timers]
- .filter(([, timer]) => timer.at <= target)
- .sort((a, b) => a[1].at - b[1].at)[0];
- if (!due) break;
- timers.delete(due[0]);
- clock = due[1].at;
- due[1].fn();
- }
- clock = target;
- };
- let radioControl;
- const radio = {
- setVoiceDucked(value) {
- state.ducked = value;
- },
- pause() {},
- subscribePlaybackControls(callback) {
- radioControl = callback;
- return () => {
- radioControl = null;
- };
- },
- async playForVoice() {
- state.playing++;
- return true;
- },
- stopPlayback() {
- state.stopped++;
- },
- };
- class Socket {
- constructor(url) {
- this.url = url;
- this.readyState = 0;
- this.bufferedAmount = 0;
- this.sent = [];
- sockets.push(this);
- queueMicrotask(() => {
- this.readyState = 1;
- this.onopen?.();
- });
- }
- send(raw) {
- const value = JSON.parse(raw);
- this.sent.push(value);
- if (value.setup && autoSetup)
- queueMicrotask(() => this.message({ setupComplete: {} }));
- }
- message(value) {
- this.onmessage?.({ data: JSON.stringify(value) });
- }
- error() {
- this.onerror?.();
- }
- remoteClose() {
- this.readyState = 3;
- this.onclose?.();
- }
- close() {
- this.readyState = 3;
- this.closed = true;
- }
- }
- const makeStream = () => {
- const track = {
- enabled: true,
- readyState: 'live',
- stop() {
- this.readyState = 'ended';
- },
- };
- tracks.push(track);
- return { getTracks: () => [track], getAudioTracks: () => [track] };
- };
- const c = new GeminiSessionController({
- emit: (event) => events.push(event),
- runAction: async (name, args, options) => {
- calls.push({ name, args, options });
- return { ok: true, action: name };
- },
- ui: { root: { remove() {} } },
- radioLayer: radio,
- now: () => clock,
- prefixNow: () => clock,
- setTimer: (fn, ms) => {
- const id = ++nextTimer;
- timers.set(id, { fn, at: clock + ms });
- return id;
- },
- clearTimer: (id) => timers.delete(id),
- WebSocketClass: Socket,
- fetchImpl: async (_url, init) => {
- requests.push(init);
- return {
- ok: true,
- json: async () =>
- JSON.parse(init.body).inputMode === 'push-to-talk'
- ? manualCredential
- : credential,
- };
- },
- getUserMedia: async () => makeStream(),
- createInput: ({ readStream, operations }) => ({
- ...operations,
- setMicrophoneEnabled(enabled) {
- for (const track of readStream()?.getAudioTracks() || [])
- track.enabled = enabled;
- },
- updateVoiceButtonLabel() {},
- setVoiceSpeaker() {},
- startVoiceVisualizer() {},
- startAssistantVoiceVisualizer() {},
- cancelPushToTalkHold() {},
- stopVoiceVisualizer() {},
- detachBindings() {},
- bindPushToTalkShortcut() {},
- resetSession() {
- this.pushToTalkMode = false;
- this.pushToTalkKeyHeld = false;
- this.spaceKeyHeld = false;
- },
- }),
- createNarration: (options) =>
- createNarrationScheduler({
- ...options,
- now: () => clock,
- setTimer: (fn, ms) => {
- const id = ++nextTimer;
- timers.set(id, { fn, at: clock + ms });
- return id;
- },
- clearTimer: (id) => timers.delete(id),
- }),
- createProgressEarcon: ({ isMicrophoneMuted }) => ({
- available: isMicrophoneMuted,
- start() {
- earcon.playing = true;
- earcon.starts++;
- },
- stop() {
- earcon.playing = false;
- },
- dispose() {
- this.stop();
- earcon.disposals++;
- },
- }),
- createAudio: (callbacks) => {
- const audio = {
- callbacks,
- pending: false,
- closed: false,
- played: [],
- async initialize() {},
- connectMicrophone(stream, enabled, metadata) {
- media.push({ stream, enabled });
- this.connected = true;
- this.setMicrophoneEnabled(enabled, metadata);
- },
- setMicrophoneEnabled(value, metadata) {
- if (!this.connected) return;
- if (value && !this.enabled) {
- this.metadata = metadata;
- callbacks.onAudioStart(metadata);
- }
- if (!value && this.enabled) callbacks.onAudioEnd(this.metadata);
- this.enabled = value;
- },
- play(data, mime) {
- this.pending = true;
- this.played.push({ data, mime });
- },
- drain() {
- this.pending = false;
- callbacks.onDrain();
- },
- clearPlayback() {
- this.pending = false;
- this.cleared = true;
- },
- diagnostics() {
- return { outputChunks: this.played.length };
- },
- close() {
- this.closed = true;
- },
- };
- captures.push(audio);
- return audio;
- },
- ...controllerOverrides,
- });
- return {
- c,
- sockets,
- tracks,
- makeStream,
- events,
- media,
- captures,
- calls,
- requests,
- state,
- advance,
- timers,
- earcon,
- radioControl: (value) => radioControl?.(value),
- };
- }
+
+test('ephemeral credentials are sent only to the fixed constrained Google endpoint', () => {
+ const url = new URL(geminiSocketUrl(credential));
+ assert.equal(url.searchParams.get('access_token'), credential.token);
+ for (const websocketUrl of [
+ endpoint + '?key=foo',
+ endpoint.replace('googleapis.com', 'example.com'),
+ endpoint.replace('wss:', 'ws:'),
+ endpoint.replace('Constrained', ''),
+ endpoint.replace('wss://', 'wss://user@'),
+ ])
+ assert.throws(
+ () => geminiSocketUrl({ ...credential, websocketUrl }),
+ /endpoint/,
+ );
+ assert.throws(
+ () =>
+ geminiSocketUrl({ ...credential, token: 'AIza-not-an-ephemeral-token' }),
+ /ephemeral/,
+ );
+});
+
+test('PTT locks manual activity and serializes cold and repeated held turns', async () => {
+ const h = harness();
+ h.c.input.pushToTalkKeyHeld = true;
+ h.c.input.spaceKeyHeld = true;
+ await h.c.start({ pushToTalk: true });
+ assert.equal(h.requests[0].body, '{"inputMode":"push-to-talk"}');
+ const ws = h.sockets[0];
+ assert.deepEqual(ws.sent[0].setup.realtimeInputConfig, {
+ automaticActivityDetection: { disabled: true },
+ });
+ const audio = h.captures[0];
+ const pcm = { data: 'AAABAA==', mimeType: 'audio/pcm;rate=16000' };
+ audio.callbacks.onAudioStart(audio.metadata); // A duplicate notification cannot reopen.
+ audio.callbacks.onAudio(pcm, audio.metadata);
+ h.c.input.setMicrophoneEnabled(false);
+ audio.callbacks.onAudioEnd(audio.metadata);
+ audio.callbacks.onAudio(pcm, audio.metadata); // Unbracketed/stale PCM is not forwarded.
+ assert.equal(h.tracks[0].enabled, false);
+ h.c.input.setMicrophoneEnabled(true);
+ audio.callbacks.onAudio(pcm, audio.metadata);
+ h.c.input.setMicrophoneEnabled(false);
+ assert.deepEqual(ws.sent.slice(1), [
+ { realtimeInput: { activityStart: {} } },
+ { realtimeInput: { audio: pcm } },
+ { realtimeInput: { activityEnd: {} } },
+ { realtimeInput: { activityStart: {} } },
+ { realtimeInput: { audio: pcm } },
+ { realtimeInput: { activityEnd: {} } },
+ ]);
+ assert.equal(h.c.status, 'listening');
+ assert.equal(h.c.input.pushToTalkMode, true);
+ assert.equal(h.tracks[0].enabled, false);
+ h.c.stop();
+});
+
+test('ordinary microphone keeps its default setup and automatic stream-end message', async () => {
+ const h = harness();
+ await h.c.start();
+ assert.equal(h.requests[0].body, '{}');
+ assert.deepEqual(h.sockets[0].sent, [
+ { setup: { ...credential.config, model: 'models/gemini-3.8-live' } },
+ ]);
+ h.c.input.setMicrophoneEnabled(false);
+ assert.deepEqual(h.sockets[0].sent.at(-1), {
+ realtimeInput: { audioStreamEnd: true },
+ });
+ h.c.stop();
+});
+
+for (const phase of ['token', 'setup', 'microphone']) {
+ test(`PTT release during ${phase} startup stays muted until a later hold`, async () => {
+ const pending = deferred();
+ const h = harness({
+ ...(phase === 'token' ? { fetchImpl: () => pending.promise } : {}),
+ ...(phase === 'setup' ? { autoSetup: false } : {}),
+ ...(phase === 'microphone'
+ ? { getUserMedia: () => pending.promise }
+ : {}),
+ });
+ h.c.input.pushToTalkKeyHeld = true;
+ h.c.input.spaceKeyHeld = true;
+ const start = h.c.start({ pushToTalk: true });
+ await tick();
+ assert.equal(h.media.length, 0);
+ assert.equal(
+ h.sockets[0]?.sent.filter((value) => value.realtimeInput).length || 0,
+ 0,
+ );
+ h.c.input.pushToTalkKeyHeld = false;
+ h.c.input.spaceKeyHeld = false;
+ h.c.input.setMicrophoneEnabled(false);
- if (phase === 'token')
- pending.resolve({ ok: true, json: async () => manualCredential });
++ if (phase === 'token') pending.resolve(Response.json(manualCredential));
+ else if (phase === 'setup') h.sockets[0].message({ setupComplete: {} });
+ else pending.resolve(h.makeStream());
+ await start;
+ assert.equal(h.c.status, 'listening');
+ assert.equal(h.tracks[0].enabled, false);
+ assert.equal(h.media[0].enabled, false);
+ assert.equal(
+ h.sockets[0].sent.length,
+ 1,
+ 'no phantom activity for a released gesture',
+ );
+ h.c.input.pushToTalkKeyHeld = true;
+ h.c.input.setMicrophoneEnabled(true);
+ assert.deepEqual(h.sockets[0].sent.at(-1), {
+ realtimeInput: { activityStart: {} },
+ });
+ h.c.input.setMicrophoneEnabled(false);
+ assert.deepEqual(h.sockets[0].sent.at(-1), {
+ realtimeInput: { activityEnd: {} },
+ });
+ h.c.stop();
+ });
+}
+
+test('a token config that disagrees with the gesture fails before socket creation and releases consented microphone', async () => {
+ for (const [pushToTalk, supplied] of [
+ [true, credential],
+ [false, manualCredential],
+ ]) {
+ const h = harness({
- fetchImpl: async () => ({ ok: true, json: async () => supplied }),
++ fetchImpl: async () => Response.json(supplied),
+ });
+ await h.c.start({ pushToTalk });
+ assert.equal(h.c.status, 'error');
+ assert.match(h.c.lastError, /input mode/);
+ assert.equal(h.sockets.length, 0);
+ assert.equal(h.tracks[0].readyState, 'ended');
+ assert.equal(h.captures[0].closed, true);
+ }
+});
+
+test('old PTT callbacks cannot send to a stopped or replacement session', async () => {
+ const h = harness();
+ h.c.input.pushToTalkKeyHeld = true;
+ await h.c.start({ pushToTalk: true });
+ const old = h.captures[0].callbacks;
+ const socket = h.sockets[0];
+ h.c.stop();
+ const oldCount = socket.sent.length;
+ await h.c.start();
+ const replacementCount = h.sockets[1].sent.length;
+ old.onAudioStart(h.captures[0].metadata);
+ old.onAudio(
+ { data: 'AAAA', mimeType: 'audio/pcm;rate=16000' },
+ h.captures[0].metadata,
+ );
+ old.onAudioEnd(h.captures[0].metadata);
+ assert.equal(socket.sent.length, oldCount);
+ assert.equal(h.sockets[1].sent.length, replacementCount);
+ assert.equal(h.c.status, 'listening');
+ assert.equal(h.tracks[0].readyState, 'ended');
+ assert.equal(h.tracks[1].enabled, true);
+ h.c.stop({ removeUi: true });
+ const latest = h.captures[1].callbacks;
+ latest.onAudioStart(h.captures[1].metadata);
+ latest.onAudioEnd(h.captures[1].metadata);
+ assert.equal(h.sockets[1].sent.length, replacementCount);
+});
+
+test('session waits for setup, captures PCM, plays all parts, emits transcripts and releases every resource', async () => {
+ const h = harness();
+ await h.c.start();
+ assert.equal(h.c.status, 'listening');
+ assert.equal(h.media.length, 1);
+ const ws = h.sockets[0];
+ assert.equal(ws.sent[0].setup.model, 'models/gemini-3.8-live');
+ h.captures[0].callbacks.onAudio(
+ {
+ data: 'AAAA',
+ mimeType: 'audio/pcm;rate=16000',
+ },
+ h.captures[0].metadata,
+ );
+ assert.equal(ws.sent.at(-1).realtimeInput.audio.data, 'AAAA');
+ ws.message({
+ serverContent: {
+ inputTranscription: { text: 'Hello' },
+ outputTranscription: { text: 'Hi' },
+ modelTurn: {
+ parts: [
+ { inlineData: { data: 'AAAA', mimeType: 'audio/pcm;rate=24000' } },
+ { inlineData: { data: 'AQAB', mimeType: 'audio/pcm;rate=24000' } },
+ ],
+ },
+ turnComplete: true,
+ },
+ });
+ assert.equal(h.captures[0].played.length, 2);
+ assert.equal(
+ h.events.some((event) => event.type === 'completion'),
+ false,
+ 'server turn completion waits for queued audio to drain',
+ );
+ assert.ok(
+ h.events.some(
+ (event) =>
+ event.type === 'transcript' &&
+ event.role === 'assistant' &&
+ event.final &&
+ event.text === 'Hi',
+ ),
+ );
+ assert.equal(h.c.getDiagnostics().completedTurns, 1);
+ h.captures[0].drain();
+ assert.equal(
+ h.events.some(
+ (event) => event.type === 'completion' && event.status === 'completed',
+ ),
+ true,
+ );
+ h.c.stop();
+ assert.equal(h.tracks[0].readyState, 'ended');
+ assert.equal(ws.closed, true);
+ assert.equal(h.captures[0].closed, true);
+ assert.equal(h.state.ducked, false);
+ assert.equal(h.c.status, 'idle');
+});
+
+test('goAway deadline tears down pending work and an explicit restart creates a fresh conversation', async () => {
+ const pending = deferred();
+ let issued = 0;
+ let pendingOptions;
+ const h = harness({
- fetchImpl: async () => ({
- ok: true,
- json: async () => ({
++ fetchImpl: async () =>
++ Response.json({
+ ...credential,
+ token: `auth_tokens/session-${++issued}`,
+ }),
- }),
+ runAction: async (name, _args, options) => {
+ if (name === 'control_radio')
+ return {
+ ok: true,
+ action: 'control_radio',
+ radioAction: 'play',
+ radioPlaybackRequested: true,
+ };
+ pendingOptions = options;
+ return pending.promise;
+ },
+ });
+ await h.c.start();
+ establishToolInput(h);
+ const oldSocket = h.sockets[0];
+ const oldAudio = h.captures[0];
+ const oldCallbacks = oldAudio.callbacks;
+ oldSocket.message({
+ toolCall: {
+ functionCalls: [
+ { id: 'radio', name: 'control_radio', args: { action: 'play' } },
+ { id: 'pending', name: 'get_current_view_state', args: {} },
+ ],
+ },
+ });
+ await tick();
+ await tick();
+ assert.ok(h.c.radio.pendingRadioPlaybackResult);
+ assert.equal(h.c.pendingTools, 1);
+ oldSocket.message({
+ serverContent: {
+ modelTurn: { parts: [{ inlineData: { data: 'AAAA' } }] },
+ },
+ });
+ assert.equal(oldAudio.played.length, 1);
+ let sentBeforeExpiry = oldSocket.sent.length;
+
+ oldSocket.message({ goAway: { timeLeft: '5s' } });
+ sentBeforeExpiry = oldSocket.sent.length; // Microphone stream-end is a reliable lifecycle marker.
+ assert.equal(h.c.status, 'executing');
+ assert.equal(pendingOptions.signal.aborted, false);
+ assert.equal(h.c.sendTextCommand('Do not admit a new turn'), false);
+ h.advance(5000);
+ assert.equal(h.c.status, 'error');
+ assert.equal(
+ h.c.lastError,
+ 'Gemini Live connection is expiring. Start voice again for a new conversation.',
+ );
+ assert.equal(
+ h.events.at(-1).recovery,
+ 'Start voice again for a fresh token and a new conversation.',
+ );
+ assert.equal(oldSocket.closed, true);
+ assert.equal(oldAudio.closed, true);
+ assert.equal(h.tracks[0].readyState, 'ended');
+ assert.equal(h.c.pendingTools, 0);
+ assert.equal(h.c.radio.pendingRadioPlaybackResult, null);
+ assert.equal(pendingOptions.signal.aborted, true);
+
+ oldCallbacks.onAudioStart(h.captures[0].metadata);
+ oldCallbacks.onAudio(
+ { data: 'AQAB', mimeType: 'audio/pcm;rate=16000' },
+ h.captures[0].metadata,
+ );
+ oldCallbacks.onAudioEnd(h.captures[0].metadata);
+ oldCallbacks.onDrain();
+ oldCallbacks.onError(new Error('late retired audio'));
+ oldSocket.message({ serverContent: { turnComplete: true } });
+ oldSocket.error();
+ oldSocket.remoteClose();
+ pending.resolve({ ok: true });
+ await tick();
+ await tick();
+ assert.equal(oldSocket.sent.length, sentBeforeExpiry);
+ assert.equal(oldAudio.played.length, 1);
+ assert.equal(
+ oldSocket.sent.filter((entry) => entry.toolResponse).length,
+ 1,
+ 'only the completed Radio result was sent before expiry',
+ );
+ assert.equal(h.state.playing, 0);
+
+ await h.c.start();
+ assert.equal(issued, 2);
+ assert.equal(h.sockets.length, 2);
+ assert.equal(
+ new URL(h.sockets[1].url).searchParams.get('access_token'),
+ 'auth_tokens/session-2',
+ );
+ assert.equal(h.c.status, 'listening');
+ assert.equal(h.c.completedTurns, 0);
+ assert.equal(h.captures[1].played.length, 0);
+ assert.equal(h.tracks[1].readyState, 'live');
+ h.c.stop();
+});
+
+test('pre-setup rejection or close releases startup and asks for a fresh session', async () => {
+ for (const terminal of ['rejected', 'closed']) {
+ const h = harness({ autoSetup: false });
+ const start = h.c.start();
+ await tick();
+ if (terminal === 'rejected')
+ h.sockets[0].message({ error: { message: 'credential rejected' } });
+ else h.sockets[0].remoteClose();
+ await start;
+ assert.equal(h.c.status, 'error', terminal);
+ assert.equal(h.tracks[0].readyState, 'ended', terminal);
+ assert.equal(h.captures[0].closed, true, terminal);
+ assert.equal(h.sockets[0].closed, true, terminal);
+ assert.match(h.c.lastError, /Start voice again/, terminal);
+ assert.match(h.events.at(-1).recovery, /fresh session/, terminal);
+ assert.equal(h.sockets.length, 1, 'no automatic retry');
+ }
+});
+
+test('network close after setup releases media and starts no replacement', async () => {
+ const h = harness();
+ await h.c.start();
+ h.sockets[0].remoteClose();
+ assert.equal(h.c.status, 'error');
+ assert.equal(
+ h.c.lastError,
+ 'Gemini Live connection ended. Start voice again for a new conversation.',
+ );
+ assert.equal(h.tracks[0].readyState, 'ended');
+ assert.equal(h.captures[0].closed, true);
+ assert.equal(h.sockets.length, 1);
+ assert.doesNotMatch(h.events.at(-1).recovery, /microphone|API key/i);
+});
+
+test('OFF during unresolved setup blocks late setup, error and close callbacks', async () => {
+ const h = harness({ autoSetup: false });
+ const start = h.c.start();
+ await tick();
+ const socket = h.sockets[0];
+ h.c.stop();
+ const eventCount = h.events.length;
+ socket.message({ setupComplete: {} });
+ socket.message({ error: { message: 'late rejection' } });
+ socket.error();
+ socket.remoteClose();
+ await start;
+ assert.equal(h.c.status, 'idle');
+ assert.equal(h.tracks[0].readyState, 'ended');
+ assert.equal(h.captures[0].closed, true);
+ assert.equal(h.events.length, eventCount);
+});
+
+test('a disposed pending microphone is stopped and cannot update the replacement UI', async () => {
+ const microphone = deferred();
+ const h = harness({ getUserMedia: () => microphone.promise });
+ const start = h.c.start();
+ await tick();
+ h.c.stop({ removeUi: true });
+ const eventCount = h.events.length;
+ microphone.resolve(h.makeStream());
+ await start;
+ assert.equal(h.tracks[0].readyState, 'ended');
+ assert.equal(h.events.length, eventCount);
+ assert.equal(h.media.length, 0);
+});
+
+test('late token rejection after stop cannot replace a successor state', async () => {
+ const response = deferred();
+ const h = harness({ fetchImpl: () => response.promise });
+ const start = h.c.start();
+ h.c.stop({ removeUi: true });
+ const count = h.events.length;
- response.resolve({
- ok: false,
- status: 503,
- json: async () => ({ error: 'late rejection' }),
- });
++ response.resolve(Response.json({ error: 'late rejection' }, { status: 503 }));
+ await start;
+ assert.equal(h.events.length, count);
+ assert.equal(h.sockets.length, 0);
+});
+
+test('tool cancellation covers queued calls and interrupted results never return to the socket', async () => {
+ const first = deferred();
+ const names = [];
+ const h = harness({
+ runAction: async (name) => {
+ names.push(name);
+ return first.promise;
+ },
+ });
+ await h.c.start();
+ establishToolInput(h);
+ const ws = h.sockets[0];
+ ws.message({
+ toolCall: {
+ functionCalls: [
+ { id: 'a', name: 'one', args: {} },
+ { id: 'b', name: 'two', args: {} },
+ ],
+ },
+ });
+ await tick();
+ ws.message({ toolCallCancellation: { ids: ['b'] } });
+ first.resolve({ ok: true });
+ await h.c.toolQueue;
+ assert.deepEqual(names, ['one']);
+ assert.equal(h.c.pendingTools, 0);
+ assert.equal(ws.sent.filter((entry) => entry.toolResponse).length, 1);
+ const second = deferred();
+ h.c.runAction = () => second.promise;
+ ws.message({
+ toolCall: { functionCalls: [{ id: 'c', name: 'three', args: {} }] },
+ });
+ await tick();
+ ws.message({ serverContent: { interrupted: true } });
+ second.resolve({ ok: true });
+ await tick();
+ assert.equal(ws.sent.filter((entry) => entry.toolResponse).length, 1);
+ assert.equal(h.captures[0].cleared, true);
+ h.c.stop();
+});
+
+test('wire voiceActivity.type start aborts pending work and discards old playback', async () => {
+ const pending = deferred();
+ let signal;
+ const h = harness({
+ runAction: (_name, _args, options) => {
+ signal = options.signal;
+ return pending.promise;
+ },
+ });
+ await h.c.start();
+ establishToolInput(h);
+ const ws = h.sockets[0];
+ ws.message({
+ serverContent: { modelTurn: { parts: [{ inlineData: { data: 'AAAA' } }] } },
+ });
+ ws.message({
+ toolCall: {
+ functionCalls: [
+ { id: 'old', name: 'fly_to_location', args: { query: 'Austin' } },
+ ],
+ },
+ });
+ await tick();
+ const turn = h.c.turn;
+ assert.equal(signal.aborted, false);
+ assert.equal(h.captures[0].pending, true);
+ ws.message({
+ voiceActivity: { type: 'ACTIVITY_START', audioOffset: '5.240s' },
+ });
+ assert.equal(signal.aborted, true);
+ assert.ok(h.c.turn > turn);
+ assert.equal(h.c.pendingTools, 0);
+ assert.equal(h.captures[0].cleared, true);
+ assert.equal(h.c.status, 'listening');
+ pending.resolve({ ok: true });
+ await tick();
+ assert.equal(
+ ws.sent.some((entry) => entry.toolResponse),
+ false,
+ );
+ h.c.stop();
+});
+
+test('unknown or malformed voice activity cannot revoke the current turn', async () => {
+ const h = harness();
+ await h.c.start();
+ const turn = h.c.turn;
+ for (const voiceActivity of [
+ null,
+ {},
+ { type: 'TYPE_UNSPECIFIED' },
+ { type: 'unknown' },
+ { type: 1 },
+ ]) {
+ h.sockets[0].message({ voiceActivity });
+ assert.equal(h.c.turn, turn);
+ assert.equal(h.c.status, 'listening');
+ assert.equal(h.c.narration.state().pendingTimers, 0);
+ }
+ h.c.stop();
+});
+
+for (const pushToTalk of [false, true]) {
+ test(`wire voiceActivity.type end respects ${pushToTalk ? 'manual' : 'automatic'} turn ownership`, async () => {
+ const h = harness();
+ await h.c.start({ pushToTalk });
+ if (!pushToTalk)
+ h.sockets[0].message({ voiceActivity: { type: 'ACTIVITY_START' } });
+ h.c.narration.cancel();
+ h.sockets[0].message({
+ voiceActivity: { type: 'ACTIVITY_END', audioOffset: '9.080s' },
+ });
+ assert.equal(h.c.narration.state().pendingTimers, pushToTalk ? 0 : 1);
+ assert.equal(h.c.status, 'listening');
+ h.c.stop();
+ assert.equal(h.timers.size, 0);
+ });
+}
+
+test('radio handoff waits for a post-tool reply and actual playback drain', async () => {
+ const h = harness({
+ runAction: async () => ({
+ ok: true,
+ action: 'control_radio',
+ radioAction: 'play',
+ radioPlaybackRequested: true,
+ }),
+ });
+ await h.c.start();
+ establishToolInput(h);
+ const ws = h.sockets[0];
+ ws.message({
+ toolCall: {
+ functionCalls: [
+ { id: 'radio', name: 'control_radio', args: { action: 'play' } },
+ ],
+ },
+ });
+ await h.c.toolQueue;
+ ws.message({ serverContent: { turnComplete: true } });
+ assert.equal(
+ h.state.playing,
+ 0,
+ 'the tool turn alone must not release Radio',
+ );
+ ws.message({
+ serverContent: {
+ modelTurn: {
+ parts: [
+ { inlineData: { data: 'AAAA', mimeType: 'audio/pcm;rate=24000' } },
+ ],
+ },
+ turnComplete: true,
+ },
+ });
+ assert.equal(
+ h.state.playing,
+ 0,
+ 'queued assistant audio still owns the speaker',
+ );
+ h.captures[0].drain();
+ await tick();
+ assert.equal(h.state.playing, 1);
+ assert.equal(h.state.ducked, false);
+ assert.equal(h.c.status, 'idle');
+});
+
+test('explicit Radio stop cancels a handoff while confirmation is playing', async () => {
+ const h = harness({
+ runAction: async () => ({
+ ok: true,
+ action: 'control_radio',
+ radioPlaybackRequested: true,
+ }),
+ });
+ await h.c.start();
+ establishToolInput(h);
+ const ws = h.sockets[0];
+ ws.message({
+ toolCall: {
+ functionCalls: [
+ { id: 'r', name: 'control_radio', args: { action: 'play' } },
+ ],
+ },
+ });
+ await h.c.toolQueue;
+ ws.message({
+ serverContent: {
+ modelTurn: { parts: [{ inlineData: { data: 'AAAA' } }] },
+ turnComplete: true,
+ },
+ });
+ h.radioControl({ action: 'stop', origin: 'user' });
+ h.captures[0].drain();
+ await tick();
+ assert.equal(h.state.playing, 0);
+ assert.equal(h.c.status, 'listening');
+ h.c.stop();
+});
+
+test('eligible entity context sends a bounded fresh image before its function result', async () => {
+ const h = harness({
+ runAction: async () => ({
+ ok: true,
+ action: 'get_entity_context',
+ scene: { basemap: { viewScale: 'local' } },
+ }),
+ captureViewport: async () => 'data:image/jpeg;base64,aW1hZ2U=',
+ });
+ await h.c.start();
+ establishToolInput(h);
+ h.sockets[0].message({
+ toolCall: {
+ functionCalls: [{ id: 'view', name: 'get_entity_context', args: {} }],
+ },
+ });
+ await h.c.toolQueue;
+ const sent = h.sockets[0].sent;
+ const imageIndex = sent.findIndex((entry) => entry.realtimeInput?.video);
+ assert.ok(imageIndex > 0);
+ assert.ok(imageIndex < sent.findIndex((entry) => entry.toolResponse));
+ h.c.stop();
+});
+
+test('socket pressure drops PCM without failing the active session and delivery recovers', async () => {
+ const h = harness();
+ await h.c.start();
+ const ws = h.sockets[0],
+ audio = h.captures[0],
+ before = ws.sent.length;
+ ws.bufferedAmount = 300000;
+ audio.callbacks.onAudio(
+ { data: 'AA==', mimeType: 'audio/pcm;rate=16000' },
+ audio.metadata,
+ );
+ assert.equal(ws.sent.length, before);
+ assert.equal(h.c.getDiagnostics().droppedAudioChunks, 1);
+ assert.equal(h.c.status, 'listening');
+ assert.equal(h.tracks[0].readyState, 'live');
+ ws.bufferedAmount = 0;
+ audio.callbacks.onAudio(
+ { data: 'AQ==', mimeType: 'audio/pcm;rate=16000' },
+ audio.metadata,
+ );
+ assert.equal(ws.sent.at(-1).realtimeInput.audio.data, 'AQ==');
+ h.c.stop();
+});
+
+test('passive map context never interrupts spoken output and is delivered at the next explicit turn', async () => {
+ const h = harness();
+ await h.c.start();
+ const ws = h.sockets[0];
+ ws.message({
+ serverContent: { modelTurn: { parts: [{ inlineData: { data: 'AAAA' } }] } },
+ });
+ const before = ws.sent.length;
+ const event = {
+ type: 'map_annotation_outline',
+ label: 'Austin',
+ status: 'resolved',
+ };
+ assert.equal(h.c.notifyMapEvent(event), true);
+ event.label = 'changed after enqueue';
+ assert.equal(
+ ws.sent.length,
+ before,
+ 'passive context sends no clientContent while speech is active',
+ );
+ assert.equal(h.captures[0].pending, true);
+ h.c.sendTextCommand('What did you outline?');
+ const parts = ws.sent.at(-1).clientContent.turns[0].parts;
+ assert.equal(JSON.parse(parts[0].text).events[0].label, 'Austin');
+ assert.equal(parts[1].text, 'What did you outline?');
+ assert.equal(h.c.pendingMapEvents.length, 0);
+ for (let i = 0; i < 30; i++) h.c.notifyMapEvent({ index: i });
+ assert.equal(h.c.pendingMapEvents.length, 16);
+ assert.equal(h.c.notifyMapEvent({ text: 'x'.repeat(16000) }), false);
+ h.c.stop();
+ assert.equal(h.c.pendingMapEvents.length, 0);
+});
+
+test('passive context joins the next tool response and survives a failed explicit send', async () => {
+ const h = harness();
+ await h.c.start();
+ h.c.notifyMapEvent({ type: 'map_annotation_outline', label: 'London' });
+ h.sockets[0].readyState = 0;
+ assert.equal(h.c.sendTextCommand('Continue'), false);
+ assert.equal(h.c.pendingMapEvents.length, 1);
+ h.sockets[0].readyState = 1;
+ h.sockets[0].message({ voiceActivity: { type: 'ACTIVITY_START' } });
+ h.sockets[0].message({ voiceActivity: { type: 'ACTIVITY_END' } });
+ h.sockets[0].message({
+ serverContent: { inputTranscription: { text: 'Continue' } },
+ });
+ h.sockets[0].message({
+ toolCall: {
+ functionCalls: [{ id: 'context', name: 'get_entity_context', args: {} }],
+ },
+ });
+ await h.c.toolQueue;
+ assert.equal(
+ h.sockets[0].sent.at(-1).toolResponse.functionResponses[0].response
+ .mapEvents[0].label,
+ 'London',
+ );
+ assert.equal(h.c.pendingMapEvents.length, 0);
+ h.c.stop();
+});
+
+test('a delayed permission prompt does not mint a token or consume the network deadline', async () => {
+ const microphone = deferred();
+ const h = harness({
+ startupTimeoutMs: 40,
+ getUserMedia: () => microphone.promise,
+ });
+ const start = h.c.start();
+ await new Promise((resolve) => setTimeout(resolve, 80));
+ assert.equal(h.c.status, 'connecting');
+ assert.equal(h.requests.length, 0);
+ assert.equal(h.sockets.length, 0);
+ microphone.resolve(h.makeStream());
+ await start;
+ assert.equal(h.c.status, 'listening');
+ assert.equal(h.requests.length, 1);
+ h.c.stop();
+});
+
+test('Stop during a permission prompt releases a late grant without touching the successor', async () => {
+ const microphone = deferred();
+ const h = harness({ getUserMedia: () => microphone.promise });
+ const start = h.c.start();
+ await tick();
+ h.c.stop();
+ await start;
+ const lateStream = h.makeStream();
+ h.c.getUserMedia = async () => h.makeStream();
+ await h.c.start();
+ microphone.resolve(lateStream);
+ await tick();
+ assert.equal(h.tracks[0].readyState, 'ended');
+ assert.equal(h.tracks[1].readyState, 'live');
+ assert.equal(h.c.status, 'listening');
+ h.c.stop();
+});
+
+test('stalled audio initialization also obeys the startup deadline', async () => {
+ const initialization = deferred();
+ const h = harness({ startupTimeoutMs: 40 });
+ const createAudio = h.c.createAudio;
+ h.c.createAudio = (callbacks) => {
+ const audio = createAudio(callbacks);
+ audio.initialize = () => initialization.promise;
+ return audio;
+ };
+ await Promise.all([
+ h.c.start(),
+ new Promise((resolve) => setTimeout(resolve, 80)),
+ ]);
+ assert.equal(h.c.status, 'error');
+ assert.equal(h.captures[0].closed, true);
+ assert.equal(h.sockets.length, 0);
+ initialization.resolve();
+ await tick();
+ assert.equal(h.c.status, 'error');
+});
+
+for (const activity of [
+ 'activity-start',
+ 'push-to-talk',
+ 'interrupted',
+ 'user-text',
+]) {
+ test(`new ${activity} revokes a pending Radio preflight after the old spoken turn ended`, async () => {
+ const ready = deferred();
+ const h = harness({
+ runAction: async () => ({
+ ok: true,
+ action: 'control_radio',
+ radioPlaybackRequested: true,
+ }),
+ });
+ h.c.radio.radioLayer.playForVoice = () => ready.promise;
+ await h.c.start();
+ establishToolInput(h);
+ const ws = h.sockets[0];
+ ws.message({
+ toolCall: {
+ functionCalls: [
+ { id: 'radio', name: 'control_radio', args: { action: 'play' } },
+ ],
+ },
+ });
+ await h.c.toolQueue;
+ ws.message({
+ serverContent: {
+ modelTurn: { parts: [{ inlineData: { data: 'AAAA' } }] },
+ turnComplete: true,
+ },
+ });
+ h.captures[0].drain();
+ assert.equal(h.c.radio.radioHandoffInFlight, true);
+ if (activity === 'activity-start')
+ ws.message({
+ voiceActivity: {
+ type: 'ACTIVITY_START',
+ audioOffset: '12s',
+ },
+ });
+ else if (activity === 'interrupted')
+ ws.message({ serverContent: { interrupted: true } });
+ else if (activity === 'user-text') h.c.sendTextCommand('Actually stop');
+ else h.c.input.setMicrophoneEnabled(true);
+ ready.resolve(true);
+ await tick();
+ assert.equal(h.c.status, 'listening');
+ assert.equal(h.c.stream.getTracks()[0].readyState, 'live');
+ assert.equal(h.state.ducked, true);
+ assert.ok(h.state.stopped > 0);
+ h.c.stop();
+ });
+}
+
+test('uncorrelated late transcription preserves its own successful Radio action and preflight', async () => {
+ const tool = deferred();
+ const ready = deferred();
+ const h = harness({ runAction: () => tool.promise });
+ h.c.radio.radioLayer.playForVoice = () => ready.promise;
+ await h.c.start();
+ establishToolInput(h);
+ const ws = h.sockets[0];
+ ws.message({
+ toolCall: {
+ functionCalls: [
+ {
+ id: 'radio-late-transcript',
+ name: 'control_radio',
+ args: { action: 'play' },
+ },
+ ],
+ },
+ });
+ await tick();
+ const handoffEpoch = h.c.radio.radioHandoffEpoch;
+ ws.message({
+ serverContent: {
+ inputTranscription: { text: 'Play the radio' },
+ interimInputTranscription: { text: 'Play the radio' },
+ },
+ });
+ assert.equal(h.c.radio.radioHandoffEpoch, handoffEpoch);
+ tool.resolve({
+ ok: true,
+ action: 'control_radio',
+ radioPlaybackRequested: true,
+ });
+ await h.c.toolQueue;
+ const response = ws.sent.find((message) => message.toolResponse).toolResponse
+ .functionResponses[0].response;
+ assert.equal(response.ok, true);
+ assert.equal(response.radioPlaybackRequested, true);
+ ws.message({
+ serverContent: {
+ modelTurn: { parts: [{ inlineData: { data: 'AAAA' } }] },
+ turnComplete: true,
+ },
+ });
+ h.captures[0].drain();
+ assert.equal(h.c.radio.radioHandoffInFlight, true);
+ ws.message({ serverContent: { inputTranscription: { text: ' please' } } });
+ assert.equal(h.c.radio.radioHandoffInFlight, true);
+ ready.resolve(true);
+ await tick();
+ assert.equal(h.c.status, 'idle');
+ assert.equal(h.state.ducked, false);
+});
+
+function radioPlaybackResult() {
+ return {
+ ok: true,
+ action: 'control_radio',
+ radioAction: 'play',
+ radioPlaybackRequested: true,
+ };
+}
+
+function establishToolInput(h, text = 'Run the requested action') {
+ assert.equal(h.c.sendTextCommand(text), true);
+}
+
+function requestTool(
+ ws,
+ id,
+ name = 'control_radio',
+ args = { action: 'play' },
+) {
+ ws.message({ toolCall: { functionCalls: [{ id, name, args }] } });
+}
+
+function drainRadioReply(h) {
+ h.sockets[0].message({
+ serverContent: {
+ modelTurn: { parts: [{ inlineData: { data: 'AAAA' } }] },
+ turnComplete: true,
+ },
+ });
+ h.captures[0].drain();
+}
+
- for (const query of [
- { name: 'get_entity_context', args: {} },
- { name: 'control_radio', args: { action: 'status' } },
- ]) {
- for (const phase of ['active', 'prepared', 'preflight']) {
- test(
- `cancelling ${query.name} ${query.args.action || ''} preserves another Radio owner in ${phase}`,
- {
- skip:
- phase === 'preflight'
- ? 'replace-native: H01, H02; equivalent native regression tests replace caption ownership assumptions'
- : false,
- },
- async () => {
- const tool = deferred();
- const queryWork = deferred();
- const ready = deferred();
- const executions = [];
- const h = harness({
- runAction: (name, args, options) => {
- executions.push({ name, args, options });
- return args.action === 'play' ? tool.promise : queryWork.promise;
- },
- });
- h.c.radio.radioLayer.playForVoice = () => ready.promise;
- await h.c.start();
- establishToolInput(h);
- const ws = h.sockets[0];
- requestTool(ws, 'owner');
- await tick();
- if (phase !== 'active') {
- tool.resolve(radioPlaybackResult());
- await h.c.toolQueue;
- if (phase === 'preflight') drainRadioReply(h);
- }
- requestTool(ws, 'query', query.name, query.args);
- await tick();
- const epoch = h.c.radio.radioHandoffEpoch;
- const pending = h.c.radio.pendingRadioPlaybackResult;
- const attempt = h.c.radio.radioHandoffAttemptId;
- const ownerWasCurrent = executions[0].options.isCurrent();
- ws.message({ toolCallCancellation: { ids: ['unknown', 'query'] } });
- assert.equal(h.c.radio.radioHandoffEpoch, epoch);
- assert.equal(executions[0].options.signal.aborted, false);
- assert.equal(executions[0].options.isCurrent(), ownerWasCurrent);
- assert.equal(h.c.radio.pendingRadioPlaybackResult, pending);
- assert.equal(h.c.radio.radioHandoffAttemptId, attempt);
- assert.equal(h.state.stopped, 0);
- if (phase === 'active') tool.resolve(radioPlaybackResult());
- await h.c.toolQueue;
- assert.equal(
- executions.length,
- phase === 'prepared' ? 2 : 1,
- 'cancelled queued and post-completion unowned queries never start',
- );
- assert.equal(h.c.pendingTools, 0);
- const responses = ws.sent.flatMap(
- (message) => message.toolResponse?.functionResponses || [],
- );
- assert.deepEqual(
- responses.map((response) => response.id),
- phase === 'preflight' ? ['owner', 'query'] : ['owner'],
- );
- assert.equal(responses[0].response.ok, true);
- if (phase !== 'preflight') drainRadioReply(h);
- assert.equal(h.c.radio.radioHandoffInFlight, true);
- ready.resolve(true);
- queryWork.resolve({ ok: true });
- await tick();
- assert.equal(h.c.status, 'idle');
- assert.equal(h.state.ducked, false);
- },
- );
- }
- }
-
+test('cancelling one queued Radio call preserves active and queued same-feature siblings', async () => {
+ const first = deferred();
+ const executions = [];
+ const h = harness({
+ runAction: (name, args, options) => {
+ executions.push({ args, options });
+ return args.station === 'first' ? first.promise : radioPlaybackResult();
+ },
+ });
+ await h.c.start();
+ establishToolInput(h);
+ const ws = h.sockets[0];
+ for (const station of ['first', 'cancelled', 'last'])
+ requestTool(ws, station, 'control_radio', { action: 'select', station });
+ await tick();
+ const epoch = h.c.radio.radioHandoffEpoch;
+ ws.message({ toolCallCancellation: { ids: ['cancelled'] } });
+ assert.equal(h.c.radio.radioHandoffEpoch, epoch);
+ assert.equal(executions[0].options.isCurrent(), true);
+ first.resolve(radioPlaybackResult());
+ await h.c.toolQueue;
+ assert.deepEqual(
+ executions.map((entry) => entry.args.station),
+ ['first', 'last'],
+ );
+ assert.ok(executions.every((entry) => !entry.options.signal.aborted));
+ assert.equal(h.c.pendingTools, 0);
+ const newer = h.c.radio.pendingRadioPlaybackResult;
+ ws.message({ toolCallCancellation: { ids: ['first', 'unknown'] } });
+ assert.equal(h.c.radio.pendingRadioPlaybackResult, newer);
+ assert.equal(h.c.radio.radioHandoffEpoch, epoch);
+ h.c.stop();
+});
+
+test('matching active Radio cancellation aborts its work and permits its sibling to finish', async () => {
+ const first = deferred();
+ const executions = [];
+ const h = harness({
+ runAction: (name, args, options) => {
+ executions.push(options);
+ return args.action === 'play' ? first.promise : radioPlaybackResult();
+ },
+ });
+ await h.c.start();
+ establishToolInput(h);
+ const ws = h.sockets[0];
+ requestTool(ws, 'old');
+ requestTool(ws, 'new', 'control_radio', { action: 'select' });
+ await tick();
+ const epoch = h.c.radio.radioHandoffEpoch;
+ ws.message({ toolCallCancellation: { ids: ['old'] } });
+ assert.equal(executions[0].signal.aborted, true);
+ assert.equal(executions[0].isCurrent(), false);
+ await h.c.toolQueue;
+ const pending = h.c.radio.pendingRadioPlaybackResult;
+ assert.ok(pending);
+ assert.equal(executions[1].isCurrent(), true);
+ assert.equal(h.c.radio.radioHandoffEpoch, epoch);
+ first.resolve(radioPlaybackResult());
+ await tick();
+ assert.equal(h.c.radio.pendingRadioPlaybackResult, pending);
+ assert.deepEqual(
+ ws.sent
+ .flatMap((m) => m.toolResponse?.functionResponses || [])
+ .map((r) => r.id),
+ ['new'],
+ );
+ h.c.stop();
+});
+
+test('matching prepared cancellation preserves a stronger sibling reservation and signal', async () => {
+ const stronger = deferred();
+ let strongerOptions;
+ const h = harness({
+ runAction: (name, args, options) => {
+ if (args.action === 'stop') {
+ strongerOptions = options;
+ return stronger.promise;
+ }
+ return radioPlaybackResult();
+ },
+ });
+ await h.c.start();
+ establishToolInput(h);
+ const ws = h.sockets[0];
+ requestTool(ws, 'play');
+ await h.c.toolQueue;
+ requestTool(ws, 'stop', 'control_radio', { action: 'stop' });
+ await tick();
+ const reservations = [...h.c.radio.radioToolHandoffReservations.keys()];
+ assert.equal(reservations.length, 1);
+ const epoch = h.c.radio.radioHandoffEpoch;
+ ws.message({ toolCallCancellation: { ids: ['play', 'unknown'] } });
+ assert.equal(h.c.radio.pendingRadioPlaybackResult, null);
+ assert.equal(strongerOptions.signal.aborted, false);
+ assert.deepEqual(
+ [...h.c.radio.radioToolHandoffReservations.keys()],
+ reservations,
+ );
+ assert.equal(h.c.radio.radioHandoffEpoch, epoch);
+ stronger.resolve({ ok: false, error: 'Refused fixture stop' });
+ await h.c.toolQueue;
+ assert.equal(h.c.radio.radioToolHandoffReservations.size, 0);
+ drainRadioReply(h);
+ await tick();
+ assert.equal(h.state.playing, 0);
+ assert.equal(h.c.status, 'listening');
+ h.c.stop();
+});
+
+test('cancelled stronger call releases only its reservation and retains prepared playback', async () => {
+ const stronger = deferred();
+ const h = harness({
+ runAction: (name, args) =>
+ args.action === 'stop' ? stronger.promise : radioPlaybackResult(),
+ });
+ await h.c.start();
+ establishToolInput(h);
+ const ws = h.sockets[0];
+ requestTool(ws, 'play');
+ await h.c.toolQueue;
+ const prepared = h.c.radio.pendingRadioPlaybackResult;
+ requestTool(ws, 'stop', 'control_radio', { action: 'stop' });
+ await tick();
+ const separateReservation = h.c.radio.reserveRadioToolHandoff();
+ ws.message({ toolCallCancellation: { ids: ['stop'] } });
+ await h.c.toolQueue;
+ assert.equal(h.c.radio.pendingRadioPlaybackResult, prepared);
+ assert.deepEqual(
+ [...h.c.radio.radioToolHandoffReservations.keys()],
+ [separateReservation],
+ );
+ stronger.resolve({ ok: true, action: 'control_radio' });
+ await tick();
+ assert.equal(h.c.radio.pendingRadioPlaybackResult, prepared);
+ h.c.radio.settleRadioToolHandoffReservation(separateReservation);
+ drainRadioReply(h);
+ await tick();
+ assert.equal(h.state.playing, 1);
+ assert.equal(h.c.status, 'idle');
+});
+
+test('matching preflight cancellation and late completion cannot revoke a newer reused-result handoff', async () => {
+ const sharedResult = radioPlaybackResult();
+ const starts = [];
+ const stops = [];
+ let playingAttempt = null;
+ const h = harness({ runAction: () => sharedResult });
+ h.c.radio.radioLayer.playForVoice = ({ attemptId }) => {
+ const ready = deferred();
+ starts.push({ attemptId, ready });
+ playingAttempt = attemptId;
+ return ready.promise;
+ };
+ h.c.radio.radioLayer.stopPlayback = ({ attemptId }) => {
+ stops.push(attemptId);
+ if (playingAttempt === attemptId) playingAttempt = null;
+ };
+ await h.c.start();
+ establishToolInput(h);
+ const ws = h.sockets[0];
+ requestTool(ws, 'old');
+ await h.c.toolQueue;
+ drainRadioReply(h);
+ const oldResult = h.c.radio.radioHandoffInFlightResult;
+ establishToolInput(h, 'Play the radio again');
+ requestTool(ws, 'new');
+ await h.c.toolQueue;
+ const newerResult = h.c.radio.pendingRadioPlaybackResult;
+ assert.notEqual(oldResult, newerResult);
+ assert.notEqual(newerResult, sharedResult);
+ const epoch = h.c.radio.radioHandoffEpoch;
+ ws.message({ toolCallCancellation: { ids: ['old'] } });
+ assert.equal(h.c.radio.radioHandoffEpoch, epoch);
+ assert.equal(h.c.radio.pendingRadioPlaybackResult, newerResult);
+ assert.equal(h.c.radio.radioHandoffInFlight, false);
+ assert.deepEqual(stops, [starts[0].attemptId]);
+ drainRadioReply(h);
+ assert.equal(starts.length, 2);
+ const newerAttempt = starts[1].attemptId;
+ starts[0].ready.resolve(true);
+ await tick();
+ assert.equal(h.c.status, 'listening');
+ assert.equal(h.c.radio.radioHandoffAttemptId, newerAttempt);
+ assert.equal(playingAttempt, newerAttempt);
+ assert.ok(stops.every((id) => id === starts[0].attemptId));
+ ws.message({ toolCallCancellation: { ids: ['old', 'unknown'] } });
+ assert.equal(h.c.radio.radioHandoffAttemptId, newerAttempt);
+ starts[1].ready.resolve(true);
+ await tick();
+ assert.equal(h.c.status, 'idle');
+ assert.equal(playingAttempt, newerAttempt);
+});
+
+test('cancelled preflight rejection cannot emit a stale Radio failure correction', async () => {
+ let rejectReady;
+ const ready = new Promise((_, reject) => {
+ rejectReady = reject;
+ });
+ const corrections = [];
+ const h = harness({ runAction: () => radioPlaybackResult() });
+ h.c.radio.radioLayer.playForVoice = () => ready;
+ h.c.radio.queueResponseCreate = (text) => corrections.push(text);
+ await h.c.start();
+ establishToolInput(h);
+ const ws = h.sockets[0];
+ requestTool(ws, 'old');
+ await h.c.toolQueue;
+ drainRadioReply(h);
+ ws.message({ toolCallCancellation: { ids: ['old'] } });
+ rejectReady(new Error('late obsolete stream rejection'));
+ await tick();
+ assert.deepEqual(corrections, []);
+ assert.equal(h.c.status, 'listening');
+ h.c.stop();
+});
+
+test('completed query and unknown cancellation IDs are inert and cannot poison future calls', async () => {
+ const executions = [];
+ const h = harness({
+ runAction: (name, args) => {
+ executions.push(args.action);
+ return args.action === 'status'
+ ? { ok: true, action: name }
+ : radioPlaybackResult();
+ },
+ });
+ await h.c.start();
+ establishToolInput(h);
+ const ws = h.sockets[0];
+ requestTool(ws, 'query', 'control_radio', { action: 'status' });
+ await h.c.toolQueue;
+ requestTool(ws, 'owner');
+ await h.c.toolQueue;
+ const prepared = h.c.radio.pendingRadioPlaybackResult;
+ const epoch = h.c.radio.radioHandoffEpoch;
+ ws.message({ toolCallCancellation: { ids: ['query', 'future'] } });
+ assert.equal(h.c.radio.pendingRadioPlaybackResult, prepared);
+ assert.equal(h.c.radio.radioHandoffEpoch, epoch);
+ requestTool(ws, 'future', 'control_radio', { action: 'select' });
+ await h.c.toolQueue;
+ assert.deepEqual(executions, ['status', 'play', 'select']);
+ h.c.stop();
+});
+
+for (const replacement of ['user-activity', 'stop']) {
+ test(`${replacement} still revokes all prepared and preflight Radio ownership`, async () => {
+ const ready = deferred();
+ const h = harness({ runAction: () => radioPlaybackResult() });
+ h.c.radio.radioLayer.playForVoice = () => ready.promise;
+ await h.c.start();
+ establishToolInput(h);
+ const ws = h.sockets[0];
+ requestTool(ws, 'old');
+ await h.c.toolQueue;
+ drainRadioReply(h);
+ h.c.radio.setPendingPlayback(radioPlaybackResult());
+ assert.ok(h.c.radio.pendingRadioPlaybackResult);
+ assert.equal(h.c.radio.radioHandoffInFlight, true);
+ if (replacement === 'user-activity') h.c.noteUserActivity();
+ else h.c.stop();
+ assert.equal(h.c.radio.pendingRadioPlaybackResult, null);
+ assert.equal(h.c.radio.radioHandoffInFlight, false);
+ assert.equal(h.c.radio.radioToolHandoffReservations.size, 0);
+ assert.ok(h.state.stopped > 0);
+ ready.resolve(true);
+ await tick();
+ assert.equal(h.c.status, replacement === 'stop' ? 'idle' : 'listening');
+ if (replacement === 'user-activity') {
+ assert.equal(h.c.stream.getTracks()[0].readyState, 'live');
+ h.c.stop();
+ }
+ });
+}
+
+test('successful stronger Radio stop still invalidates the prepared group', async () => {
+ const h = harness({
+ runAction: (name, args) =>
+ args.action === 'stop'
+ ? { ok: true, action: name, radioAction: 'stop' }
+ : radioPlaybackResult(),
+ });
+ await h.c.start();
+ establishToolInput(h);
+ const ws = h.sockets[0];
+ requestTool(ws, 'play');
+ await h.c.toolQueue;
+ const epoch = h.c.radio.radioHandoffEpoch;
+ requestTool(ws, 'stop', 'control_radio', { action: 'stop' });
+ await h.c.toolQueue;
+ assert.equal(h.c.radio.pendingRadioPlaybackResult, null);
+ assert.ok(h.c.radio.radioHandoffEpoch > epoch);
+ drainRadioReply(h);
+ await tick();
+ assert.equal(h.state.playing, 0);
+ assert.equal(h.c.status, 'listening');
+ h.c.stop();
+});
+
+test('slow Gemini tools reuse shared progress timing without injecting a conversation turn', async () => {
+ const pending = deferred();
+ let options;
+ const h = harness({
+ runAction: (_name, _args, next) => {
+ options = next;
+ next.progress({ step: 'search', label: 'Austin' });
+ return pending.promise;
+ },
+ });
+ await h.c.start({ pushToTalk: true });
+ h.c.sendTextCommand('Fly to Austin');
+ const ws = h.sockets[0];
+ requestTool(ws, 'flight', 'fly_to_location', { query: 'Austin' });
+ await tick();
+ assert.equal(
+ options.callId,
+ 'flight',
+ 'shared card and narration use one call identity',
+ );
+ assert.equal(h.c.narration.state().tools, 1);
+ h.advance(699);
+ assert.equal(h.earcon.playing, false);
+ h.advance(1);
+ assert.equal(h.earcon.playing, true);
+ h.advance(7500);
+ assert.equal(
+ ws.sent.length,
+ 2,
+ 'progress never sends clientContent or an early tool response',
+ );
+ assert.equal(h.c.narration.state().stepLines, 0);
+ assert.equal(h.c.narration.state().stillSpoken, false);
+ pending.resolve({ ok: true, action: 'fly_to_location' });
+ await h.c.toolQueue;
+ assert.equal(ws.sent.at(-1).toolResponse.functionResponses[0].id, 'flight');
+ assert.equal(h.c.narration.state().tools, 0);
+ h.advance(3000);
+ assert.equal(h.earcon.playing, false, 'reply grace bounds the final earcon');
+ assert.equal(h.timers.size, 0);
+ h.c.stop();
+});
+
+test('fast Gemini tools retract pending progress and Radio tools do not schedule lines', async () => {
+ for (const name of ['fly_to_location', 'control_radio']) {
+ const h = harness();
+ await h.c.start({ pushToTalk: true });
+ h.c.sendTextCommand('Run command');
+ requestTool(
+ h.sockets[0],
+ 'fast',
+ name,
+ name === 'control_radio' ? { action: 'status' } : {},
+ );
+ await h.c.toolQueue;
+ h.advance(20000);
+ assert.equal(h.earcon.starts, 0);
+ assert.equal(h.timers.size, 0);
+ assert.equal(
+ h.sockets[0].sent.filter((message) => message.clientContent).length,
+ 1,
+ );
+ h.c.stop();
+ }
+});
+
+test('Gemini model preamble and playback take priority over the working earcon', async () => {
+ const pending = deferred();
+ const h = harness({ runAction: () => pending.promise });
+ await h.c.start({ pushToTalk: true });
+ h.c.sendTextCommand('Fly to Austin');
+ const ws = h.sockets[0];
+ ws.message({
+ serverContent: { modelTurn: { parts: [{ inlineData: { data: 'AAAA' } }] } },
+ });
+ requestTool(ws, 'slow', 'fly_to_location', { query: 'Austin' });
+ await tick();
+ assert.equal(h.c.narration.state().preambleSpoken, true);
+ h.advance(1500);
+ assert.equal(h.earcon.starts, 0, 'queued model audio owns the speaker');
+ h.captures[0].drain();
+ h.advance(700);
+ assert.equal(h.earcon.playing, true);
+ ws.message({
+ serverContent: { modelTurn: { parts: [{ inlineData: { data: 'AAAA' } }] } },
+ });
+ assert.equal(
+ h.earcon.playing,
+ false,
+ 'new model audio immediately stops the tone',
+ );
+ h.c.stop();
+ pending.resolve({ ok: true });
+ await tick();
+});
+
+test('PTT release starts shared progress timing and a new hold cancels it', async () => {
+ const pending = deferred();
+ let options;
+ const h = harness({
+ runAction: (_name, _args, next) => {
+ options = next;
+ return pending.promise;
+ },
+ });
+ h.c.input.pushToTalkKeyHeld = true;
+ await h.c.start({ pushToTalk: true });
+ assert.equal(h.timers.size, 0);
+ h.c.input.pushToTalkKeyHeld = false;
+ h.c.input.setMicrophoneEnabled(false);
+ h.sockets[0].message({
+ serverContent: { inputTranscription: { text: 'fly to Austin' } },
+ });
+ requestTool(h.sockets[0], 'held', 'fly_to_location', { query: 'Austin' });
+ await tick();
+ h.advance(700);
+ assert.equal(h.earcon.playing, true);
+ h.c.input.pushToTalkKeyHeld = true;
+ assert.equal(h.c.input.mayClaimSpeaker(), true);
+ assert.equal(h.c.input.bargeIn(), true);
+ h.c.input.setMicrophoneEnabled(true);
+ assert.equal(h.earcon.playing, false);
+ assert.ok(h.c.retiredBoundaryWait, 'interruption retains its recovery bound');
+ assert.deepEqual([...h.timers.keys()], [h.c.retiredBoundaryWait.timer]);
+ assert.equal(options.signal.aborted, true);
+ assert.equal(h.captures[0].cleared, true);
+ assert.equal(h.c.narration.state().preambleSpoken, false);
+ pending.resolve({ ok: true });
+ await tick();
+ assert.equal(
+ h.sockets[0].sent.some((message) => message.toolResponse),
+ false,
+ );
+ h.c.stop();
+});
+
+test('open microphone and Radio speaker ownership suppress Gemini earcons', async () => {
+ for (const mode of ['open-mic', 'held-ptt', 'radio']) {
+ const pending = deferred();
+ const h = harness({ runAction: () => pending.promise });
+ await h.c.start({ pushToTalk: mode !== 'open-mic' });
+ h.c.sendTextCommand('Fly to Austin');
+ requestTool(h.sockets[0], 'slow', 'fly_to_location', { query: 'Austin' });
+ await tick();
+ if (mode === 'held-ptt') h.c.input.pushToTalkKeyHeld = true;
+ if (mode === 'radio') {
+ h.c.radio.setPendingPlayback(radioPlaybackResult());
+ assert.equal(h.c.input.mayClaimSpeaker(), false);
+ assert.equal(
+ h.c.input.bargeIn(),
+ false,
+ 'a hold cannot steal a Radio handoff',
+ );
+ assert.equal(h.c.pendingTools, 1);
+ }
+ h.advance(20000);
+ assert.equal(h.earcon.starts, 0, mode);
+ h.c.stop();
+ pending.resolve({ ok: true });
+ await tick();
+ }
+});
+
+test('Gemini progress is bounded and all terminal paths release narration ownership', async () => {
+ for (const end of ['stop', 'goAway', 'destroy', 'interruption']) {
+ const pending = deferred();
+ const h = harness({ runAction: () => pending.promise });
+ await h.c.start({ pushToTalk: true });
+ h.c.sendTextCommand('Fly to Austin');
+ const ws = h.sockets[0];
+ requestTool(ws, 'slow', 'fly_to_location', { query: 'Austin' });
+ await tick();
+ h.advance(700);
+ assert.equal(h.earcon.playing, true);
+ h.advance(15000);
+ assert.equal(
+ h.earcon.playing,
+ false,
+ 'working tone never runs beyond the shared limit',
+ );
+ const disposals = h.earcon.disposals;
+ if (end === 'goAway') ws.message({ goAway: { timeLeft: '0s' } });
+ else if (end === 'interruption')
+ ws.message({ serverContent: { interrupted: true } });
+ else h.c.stop({ removeUi: end === 'destroy' });
+ assert.equal(h.c.narration.state().tools, 0, end);
+ const retirementTimer = h.c.retiredBoundaryWait?.timer;
+ assert.deepEqual(
+ [...h.timers.keys()],
+ end === 'interruption' ? [retirementTimer] : [],
+ 'only the interrupted reply recovery timer may remain',
+ );
+ if (end === 'interruption') assert.ok(h.c.retiredBoundaryWait);
+ assert.equal(h.earcon.playing, false, end);
+ if (end !== 'interruption')
+ assert.equal(h.earcon.disposals, disposals + 1, end);
+ pending.resolve({ ok: true });
+ await tick();
+ h.advance(20000);
+ assert.equal(
+ ws.sent.some((message) => message.toolResponse),
+ false,
+ end,
+ );
+ assert.equal(h.timers.size, 0, end);
+ h.c.stop();
+ }
+});
+
+test('late tool and audio callbacks cannot change a successor Gemini narrator', async () => {
+ const first = deferred();
+ const second = deferred();
+ const options = [];
+ const h = harness({
+ runAction: (_name, _args, next) => {
+ options.push(next);
+ return options.length === 1 ? first.promise : second.promise;
+ },
+ });
+ await h.c.start({ pushToTalk: true });
+ h.c.sendTextCommand('Fly to Austin');
+ requestTool(h.sockets[0], 'reused', 'fly_to_location', { query: 'Austin' });
+ await tick();
+ const oldAudio = h.captures[0].callbacks;
+ h.c.stop();
+ await h.c.start({ pushToTalk: true });
+ h.c.sendTextCommand('Fly to Tokyo');
+ requestTool(h.sockets[1], 'reused', 'fly_to_location', { query: 'Tokyo' });
+ await tick();
+ const before = h.c.narration.state();
+ options[0].progress({ step: 'fly', label: 'Austin' });
+ oldAudio.onAudioEnd(h.captures[0].metadata);
+ oldAudio.onDrain();
+ first.resolve({ ok: true });
+ await tick();
+ assert.deepEqual(h.c.narration.state(), before);
+ assert.equal(h.c.pendingTools, 1);
+ h.advance(700);
+ assert.equal(h.earcon.playing, true);
+ second.resolve({ ok: true });
+ await h.c.toolQueue;
+ assert.equal(h.c.narration.state().tools, 0);
+ h.c.stop();
+ assert.equal(h.timers.size, 0);
+});
+
+test('Gemini tool progress reaches the shared card event contract with its call id', async () => {
+ const pending = deferred();
+ const events = [];
+ let options;
+ let h;
+ const session = createVoiceSession({
+ runner: (_name, _args, next) => {
+ options = next;
+ next.progress({ step: 'search', label: 'Austin' });
+ return pending.promise;
+ },
+ createAdapter: (shared) => {
+ h = harness(shared);
+ return {
+ start: (settings) => h.c.start(settings),
+ stop: (settings) => h.c.stop(settings),
+ sendText: (text) => h.c.sendTextCommand(text),
+ sendMapEvent: (event) => h.c.notifyMapEvent(event),
+ };
+ },
+ });
+ session.subscribe((event) => events.push(event));
+ await session.start({ pushToTalk: true });
+ establishToolInput(h);
+ requestTool(h.sockets[0], 'shared-call', 'fly_to_location', {
+ query: 'Austin',
+ });
+ await tick();
+ assert.equal(
+ events.find((event) => event.type === 'action-call').callId,
+ 'shared-call',
+ );
+ assert.deepEqual(
+ events.find((event) => event.type === 'progress'),
+ {
+ type: 'progress',
+ name: 'fly_to_location',
+ callId: 'shared-call',
+ step: 'search',
+ label: 'Austin',
+ },
+ );
+ pending.resolve({ ok: true, action: 'fly_to_location' });
+ await h.c.toolQueue;
+ assert.equal(
+ events.find((event) => event.type === 'action-result').callId,
+ 'shared-call',
+ );
+ session.stop();
+ const progressCount = events.filter(
+ (event) => event.type === 'progress',
+ ).length;
+ options.progress({ step: 'fly', label: 'Stale Austin' });
+ assert.equal(
+ events.filter((event) => event.type === 'progress').length,
+ progressCount,
+ );
+ assert.equal(h.timers.size, 0);
+ session.destroy();
+});
+
+function pointerHarness() {
+ let clock = 1000;
+ const pointer = createPointerTracker({
+ element: {
+ clientWidth: 1000,
+ clientHeight: 500,
+ addEventListener() {},
+ },
+ now: () => clock,
+ setTimer: () => 1,
+ clearTimer() {},
+ pick: (x) => ({
+ entity: {
+ layerId: 'flights',
+ id: String(x),
+ label: `Aircraft ${x}`,
+ kind: 'aircraft',
+ lat: 30,
+ lon: -97,
+ },
+ }),
+ });
+ return {
+ pointer,
+ advance: (ms) => {
+ clock += ms;
+ },
+ };
+}
+
+const replyAudio = (data) => ({
+ modelTurn: {
+ parts: [{ inlineData: { data, mimeType: 'audio/pcm;rate=24000' } }],
+ },
+});
+
+test('B48 pointer: a cold held PTT turn freezes keydown and sends quiet context before activity', async () => {
+ const { pointer } = pointerHarness();
+ const h = harness({ pointer });
+ pointer.moveTo(300, 200);
+ h.c.input.holdPointer();
+ pointer.moveTo(700, 200);
+ h.c.input.pushToTalkKeyHeld = true;
+ h.c.input.spaceKeyHeld = true;
+ await h.c.start({ pushToTalk: true });
+ assert.equal(pointer.activeSnapshot().entity.id, '300');
+ assert.deepEqual(
+ h.events.filter((event) => event.type === 'pointer').at(-1).pointer,
+ {
+ kind: 'this',
+ label: 'Aircraft 300',
+ screenPx: { x: 300, y: 200 },
+ },
+ );
+ const start = h.sockets[0].sent.find(
+ (value) => value.realtimeInput?.activityStart,
+ );
+ const context = h.sockets[0].sent.find((value) => value.clientContent);
+ assert.equal(
+ JSON.parse(context.clientContent.turns[0].parts[0].text).target.label,
+ 'Aircraft 300',
+ );
+ assert.equal(context.clientContent.turns[0].role, 'user');
+ assert.equal(context.clientContent.turnComplete, false);
+ assert.deepEqual(start, { realtimeInput: { activityStart: {} } });
+ assert.equal(
+ h.sockets[0].sent.indexOf(context) < h.sockets[0].sent.indexOf(start),
+ true,
+ );
+ assert.equal(
+ h.c.replyPending,
+ false,
+ 'context and an empty hold request no reply',
+ );
+ assert.equal(
+ h.sockets[0].sent.some(
+ (value) => value.clientContent?.turnComplete === true,
+ ),
+ false,
+ );
+ h.c.input.releasePointerHold();
+ h.c.input.setMicrophoneEnabled(false);
+ // A delayed server onset must not replace the released gesture's referent.
+ h.sockets[0].message({ voiceActivity: { type: 'ACTIVITY_START' } });
+ assert.equal(pointer.activeSnapshot().entity.id, '300');
+ h.sockets[0].message({
+ serverContent: { inputTranscription: { text: 'what is this' } },
+ });
+ h.sockets[0].message({
+ toolCall: {
+ functionCalls: [
+ {
+ id: 'pointed',
+ name: 'get_entity_context',
+ args: { scope: 'pointer' },
+ },
+ ],
+ },
+ });
+ await h.c.toolQueue;
+ assert.equal(h.calls[0].args.scope, 'pointer');
+ assert.equal(pointer.activeSnapshot().entity.id, '300');
+ h.c.stop();
+ assert.equal(pointer.activeSnapshot(), null);
+ pointer.destroy();
+});
+
+test('B48 pointer: text uses recent availability, clears stale context and sends one turn', async () => {
+ const { pointer, advance } = pointerHarness();
+ const h = harness({ pointer });
+ await h.c.start();
+ pointer.moveTo(400, 200);
+ h.c.sendTextCommand('what is this?');
+ assert.equal(pointer.activeSnapshot().entity.id, '400');
+ let parts = h.sockets[0].sent.at(-1).clientContent.turns[0].parts;
+ assert.deepEqual(JSON.parse(parts[0].text), {
+ type: 'pointer_context',
+ at: 'text',
+ pointing: 'aircraft',
+ });
+ assert.equal(parts.at(-1).text, 'what is this?');
+ assert.equal(
+ h.sockets[0].sent.filter((value) => value.clientContent).length,
+ 1,
+ );
+ assert.equal(
+ h.events.filter((event) => event.type === 'pointer').at(-1).pointer,
+ null,
+ );
+ h.c.runAction = async () => {
+ assert.equal(pointer.activeSnapshot().entity.id, '400');
+ assert.equal(h.c.announcePointer(), true);
+ assert.equal(h.c.announcePointer(), false);
+ return { ok: true };
+ };
+ h.sockets[0].message({
+ toolCall: {
+ functionCalls: [
+ {
+ id: 'implicit-pointer',
+ name: 'get_entity_context',
+ args: { scope: 'pointer' },
+ },
+ ],
+ },
+ });
+ await h.c.toolQueue;
+ assert.equal(
+ h.events.filter((event) => event.type === 'pointer').at(-1).pointer.label,
+ 'Aircraft 400',
+ );
+ h.sockets[0].message({ serverContent: { turnComplete: true } });
+ advance(5001);
+ h.c.sendTextCommand('what is here?');
+ assert.equal(pointer.activeSnapshot(), null);
+ parts = h.sockets[0].sent.at(-1).clientContent.turns[0].parts;
+ assert.deepEqual(JSON.parse(parts[0].text), {
+ type: 'pointer_context',
+ at: 'text',
+ target: 'none',
+ });
+ assert.equal(parts.at(-1).text, 'what is here?');
+ h.c.stop();
+ pointer.destroy();
+});
+
+test('B48 pointer: automatic speech snapshots once per onset and late input transcript keeps it', async () => {
+ const { pointer } = pointerHarness();
+ const h = harness({ pointer });
+ await h.c.start();
+ pointer.moveTo(450, 200);
+ const ws = h.sockets[0];
+ ws.message({ voiceActivity: { type: 'ACTIVITY_START' } });
+ const turn = h.c.turn;
+ assert.equal(pointer.activeSnapshot().entity.id, '450');
+ assert.deepEqual(JSON.parse(ws.sent.at(-1).realtimeInput.text), {
+ type: 'pointer_context',
+ at: 'speech_start',
+ pointing: 'aircraft',
+ });
+ pointer.moveTo(750, 200);
+ ws.message({ voiceActivity: { type: 'ACTIVITY_START' } });
+ ws.message({
+ serverContent: { inputTranscription: { text: 'what is this?' } },
+ });
+ assert.equal(
+ h.c.turn,
+ turn,
+ 'duplicate onset does not revoke the current turn',
+ );
+ assert.equal(pointer.activeSnapshot().entity.id, '450');
+ assert.equal(
+ ws.sent.some((value) => value.clientContent),
+ false,
+ );
+ ws.message({ voiceActivity: { type: 'ACTIVITY_END' } });
+ ws.message({ serverContent: { turnComplete: true } });
+ ws.message({ voiceActivity: { type: 'ACTIVITY_START' } });
+ assert.equal(pointer.activeSnapshot().entity.id, '750');
+ h.c.stop();
+ pointer.destroy();
+});
+
- for (const route of ['push-to-talk', 'user-text']) {
- for (const prior of ['playing', 'before-first-output']) {
- test(
- `B48 fence: ${route} retires ${prior} output through the server boundary`,
- {
- skip:
- route === 'push-to-talk'
- ? 'replace-native: H03, H04; equivalent native regression tests replace caption ownership assumptions'
- : false,
- },
- async () => {
- const h = harness();
- await h.c.start({ pushToTalk: route === 'push-to-talk' });
- const ws = h.sockets[0];
- const audio = h.captures[0];
- if (prior === 'playing')
- ws.message({ serverContent: replyAudio('old') });
- else if (route === 'user-text') h.c.sendTextCommand('first request');
- else {
- h.c.input.setMicrophoneEnabled(true);
- audio.callbacks.onAudio(
- {
- data: 'AAAB',
- mimeType: 'audio/pcm;rate=16000',
- },
- audio.metadata,
- );
- h.c.input.setMicrophoneEnabled(false);
- }
- if (route === 'user-text') h.c.sendTextCommand('new request');
- else {
- h.c.input.pushToTalkKeyHeld = true;
- assert.equal(h.c.input.bargeIn(), true);
- h.c.input.setMicrophoneEnabled(true);
- h.c.input.setMicrophoneEnabled(false);
- }
- const turn = h.c.turn;
- const played = audio.played.length;
- const eventCount = h.events.length;
- ws.message({
- serverContent: {
- ...replyAudio('late-old'),
- outputTranscription: { text: 'retired output' },
- inputTranscription: { text: 'new request' },
- },
- });
- ws.message({
- toolCall: {
- functionCalls: [
- {
- id: 'retired-call',
- name: 'fly_to_location',
- args: { query: 'old target' },
- },
- ],
- },
- });
- await tick();
- assert.equal(
- audio.played.length,
- played,
- 'late old audio cannot requeue after the local interruption',
- );
- assert.equal(audio.pending, false);
- assert.equal(
- h.calls.length,
- 0,
- 'late old call cannot acquire the newer local turn',
- );
- assert.equal(
- h.events
- .slice(eventCount)
- .some((event) => event.role === 'assistant'),
- false,
- );
- assert.equal(
- h.events
- .slice(eventCount)
- .some(
- (event) => event.role === 'user' && event.text === 'new request',
- ),
- true,
- );
- ws.message({ serverContent: { interrupted: true } });
- assert.equal(
- h.c.turn,
- turn,
- 'the acknowledgment cannot cancel successor ownership',
- );
- ws.message({ serverContent: replyAudio('after-interrupted') });
- assert.equal(
- audio.played.length,
- played,
- 'interrupted alone is not the completed boundary',
- );
- ws.message({
- serverContent: {
- ...replyAudio('boundary-old'),
- outputTranscription: { text: 'still retired' },
- turnComplete: true,
- },
- });
- assert.equal(
- audio.played.length,
- played,
- 'coalesced retired boundary content is also discarded',
- );
- assert.equal(
- h.events
- .slice(eventCount)
- .some((event) => event.type === 'completion'),
- false,
- );
- if (route === 'push-to-talk')
- ws.message({
- serverContent: {
- inputTranscription: { text: 'fly to new target' },
- },
- });
- ws.message({
- toolCall: {
- functionCalls: [
- {
- id: 'retired-call',
- name: 'fly_to_location',
- args: { query: 'replayed old target' },
- },
- {
- id: 'new-call',
- name: 'fly_to_location',
- args: { query: 'new target' },
- },
- ],
- },
- });
- if (route === 'push-to-talk') {
- await tick();
- h.advance(5_000);
- }
- await h.c.toolQueue;
- assert.deepEqual(
- h.calls.map((call) => call.args.query),
- route === 'user-text' ? ['new target'] : [],
- );
- ws.message({
- serverContent: {
- ...replyAudio('new'),
- outputTranscription: { text: 'new reply' },
- turnComplete: true,
- },
- });
- assert.equal(audio.played.at(-1).data, 'new');
- audio.drain();
- assert.equal(
- h.events.filter((event) => event.type === 'completion').at(-1).status,
- 'completed',
- );
- h.c.stop();
- },
- );
- }
- }
-
+for (const route of ['push-to-talk', 'user-text']) {
+ for (const idle of ['first', 'completed']) {
+ test(`B48 fence: ${route} permits the ${idle} idle reply without an interruption marker`, async () => {
+ const h = harness();
+ await h.c.start({ pushToTalk: route === 'push-to-talk' });
+ const ws = h.sockets[0];
+ const audio = h.captures[0];
+ if (idle === 'completed') {
+ ws.message({
+ serverContent: { ...replyAudio('previous'), turnComplete: true },
+ });
+ audio.drain();
+ }
+ if (route === 'user-text') h.c.sendTextCommand('first live request');
+ else {
+ h.c.input.bargeIn();
+ h.c.input.setMicrophoneEnabled(true);
+ h.c.input.setMicrophoneEnabled(false);
+ ws.message({
+ serverContent: { inputTranscription: { text: 'what is in view' } },
+ });
+ }
+ ws.message({
+ toolCall: {
+ functionCalls: [
+ { id: 'valid-first-call', name: 'get_entity_context', args: {} },
+ ],
+ },
+ });
+ await h.c.toolQueue;
+ ws.message({
+ serverContent: { ...replyAudio('legitimate'), turnComplete: true },
+ });
+ assert.equal(h.calls.length, 1);
+ assert.equal(audio.played.at(-1).data, 'legitimate');
+ h.c.stop();
+ });
+ }
+}
+
+test('B48 fence: an empty PTT hold creates no retired boundary for the next command', async () => {
+ const h = harness();
+ await h.c.start({ pushToTalk: true });
+ h.c.input.bargeIn();
+ h.c.input.setMicrophoneEnabled(true);
+ h.c.input.setMicrophoneEnabled(false);
+ h.c.input.bargeIn();
+ h.c.input.setMicrophoneEnabled(true);
+ h.captures[0].callbacks.onAudio(
+ {
+ data: 'AAAA',
+ mimeType: 'audio/pcm;rate=16000',
+ },
+ h.captures[0].metadata,
+ );
+ h.c.input.setMicrophoneEnabled(false);
+ h.sockets[0].message({
+ serverContent: { ...replyAudio('first-real'), turnComplete: true },
+ });
+ assert.equal(h.captures[0].played.at(-1).data, 'first-real');
+ h.c.stop();
+});
+
+test('B48 fence: a coalesced interrupted boundary keeps successor speech and its pointer', async () => {
+ const { pointer } = pointerHarness();
+ const h = harness({ pointer });
+ await h.c.start();
+ const ws = h.sockets[0];
+ ws.message({ serverContent: replyAudio('old') });
+ pointer.moveTo(600, 200);
+ ws.message({ voiceActivity: { type: 'ACTIVITY_START' } });
+ const turn = h.c.turn;
+ ws.message({
+ voiceActivity: { type: 'ACTIVITY_START' },
+ serverContent: {
+ ...replyAudio('boundary-old'),
+ interrupted: true,
+ turnComplete: true,
+ inputTranscription: { text: 'new pointed question' },
+ outputTranscription: { text: 'old answer' },
+ },
+ });
+ assert.equal(h.c.turn, turn);
+ assert.equal(pointer.activeSnapshot().entity.id, '600');
+ assert.equal(h.captures[0].played.length, 1);
+ assert.equal(
+ h.events.some((event) => event.type === 'completion'),
+ false,
+ );
+ assert.equal(
+ h.events.some(
+ (event) => event.role === 'user' && event.text === 'new pointed question',
+ ),
+ true,
+ );
+ ws.message({ voiceActivity: { type: 'ACTIVITY_END' } });
+ ws.message({
+ serverContent: { ...replyAudio('successor'), turnComplete: true },
+ });
+ assert.equal(h.captures[0].played.at(-1).data, 'successor');
+ h.c.stop();
+ pointer.destroy();
+});
+
+for (const route of ['push-to-talk', 'user-text']) {
+ test(`B48 queue: rapid ${route} keeps only the latest pointer/input and serializes reply boundaries`, async () => {
+ const { pointer } = pointerHarness();
+ const h = harness({ pointer });
+ await h.c.start({ pushToTalk: true });
+ const ws = h.sockets[0];
+ const audio = h.captures[0];
+ ws.message({ serverContent: replyAudio('old') });
+ const submit = (x) => {
+ pointer.moveTo(x, 200);
+ if (route === 'user-text') return h.c.sendTextCommand(`request ${x}`);
+ h.c.input.holdPointer();
+ h.c.input.bargeIn();
+ h.c.input.beginPointerTurn('keydown');
+ h.c.input.setMicrophoneEnabled(true);
+ audio.callbacks.onAudio(
+ {
+ data: String(x),
+ mimeType: 'audio/pcm;rate=16000',
+ },
+ audio.metadata,
+ );
+ h.c.input.releasePointerHold();
+ h.c.input.setMicrophoneEnabled(false);
+ };
+ submit(300); // This start/command must reach the provider to cause interruption.
+ const sentFirst = ws.sent.length;
+ submit(500);
+ submit(700); // Newer intent replaces the still-unsent second turn.
+ assert.equal(
+ ws.sent.length,
+ sentFirst,
+ 'later input waits without opening another server generation',
+ );
+ assert.equal(pointer.activeSnapshot().entity.id, '700');
+ const latestTurn = h.c.turn;
+ ws.message({ serverContent: { interrupted: true, turnComplete: true } });
+ const flushed = ws.sent.slice(sentFirst);
+ if (route === 'user-text') {
+ assert.equal(flushed.length, 1);
+ assert.equal(
+ flushed[0].clientContent.turns[0].parts.at(-1).text,
+ 'request 700',
+ );
+ } else {
+ assert.deepEqual(
+ flushed.map((value) =>
+ value.clientContent ? ['context'] : Object.keys(value.realtimeInput),
+ ),
+ [['context'], ['activityStart'], ['audio'], ['activityEnd']],
+ );
+ assert.equal(
+ JSON.parse(flushed[0].clientContent.turns[0].parts[0].text).target
+ .label,
+ 'Aircraft 700',
+ );
+ assert.equal(flushed[0].clientContent.turnComplete, false);
+ assert.equal(flushed[2].realtimeInput.audio.data, '700');
+ }
+ ws.message({
+ serverContent: {
+ ...replyAudio('first-successor-retired'),
+ outputTranscription: { text: 'stale second answer' },
+ },
+ });
+ ws.message({
+ toolCall: {
+ functionCalls: [
+ {
+ id: 'queued-old-call',
+ name: 'fly_to_location',
+ args: { query: 'stale' },
+ },
+ ],
+ },
+ });
+ assert.equal(audio.played.length, 1);
+ ws.message({ serverContent: { interrupted: true, turnComplete: true } });
+ assert.equal(h.c.turn, latestTurn);
+ ws.message({
+ serverContent: { inputTranscription: { text: 'what is this' } },
+ });
+ ws.message({
+ toolCall: {
+ functionCalls: [
+ {
+ id: 'latest-call',
+ name: 'get_entity_context',
+ args: { scope: 'pointer' },
+ },
+ ],
+ },
+ });
+ if (route === 'push-to-talk') {
+ await tick();
+ h.advance(5_000);
+ }
+ await h.c.toolQueue;
+ assert.equal(h.calls.length, 1);
+ assert.equal(pointer.activeSnapshot().entity.id, '700');
+ ws.message({
+ serverContent: { ...replyAudio('latest'), turnComplete: true },
+ });
+ assert.equal(audio.played.at(-1).data, 'latest');
+ h.c.stop();
+ pointer.destroy();
+ });
+}
+
+test('B48 queue: wait timeout fails closed and Stop releases queued input without replay', async () => {
+ for (const exit of ['timeout', 'stop']) {
+ const h = harness({ inputBoundaryTimeoutMs: 10 });
+ await h.c.start();
+ const ws = h.sockets[0];
+ ws.message({ serverContent: replyAudio('old') });
+ h.c.sendTextCommand('sent successor');
+ h.c.sendTextCommand('queued latest');
+ const sent = ws.sent.length;
+ if (exit === 'stop') h.c.stop();
+ else h.advance(25);
+ assert.equal(ws.closed, true);
+ assert.equal(h.tracks[0].readyState, 'ended');
+ assert.equal(h.c.status, exit === 'stop' ? 'idle' : 'error');
+ assert.equal(h.c.deferredInput, null);
+ ws.message({ serverContent: { interrupted: true, turnComplete: true } });
+ assert.equal(
+ ws.sent.length,
+ sent,
+ 'released queue cannot replay on a late boundary',
+ );
+ h.c.stop();
+ }
+});
+
+test('B48 queue: 256 KiB input bound fails closed without flushing partial queued speech', async () => {
+ const h = harness();
+ await h.c.start({ pushToTalk: true });
+ const ws = h.sockets[0];
+ ws.message({ serverContent: replyAudio('old') });
+ h.c.input.bargeIn();
+ h.c.input.setMicrophoneEnabled(true);
+ h.captures[0].callbacks.onAudio(
+ {
+ data: 'first',
+ mimeType: 'audio/pcm;rate=16000',
+ },
+ h.captures[0].metadata,
+ );
+ h.c.input.setMicrophoneEnabled(false);
+ h.c.input.bargeIn();
+ h.c.input.setMicrophoneEnabled(true);
+ const sent = ws.sent.length;
+ h.captures[0].callbacks.onAudio(
+ {
+ data: 'A'.repeat(256 * 1024),
+ mimeType: 'audio/pcm;rate=16000',
+ },
+ h.captures[0].metadata,
+ );
+ assert.equal(h.c.status, 'error');
+ assert.equal(h.tracks[0].readyState, 'ended');
+ assert.equal(ws.closed, true);
+ assert.equal(h.c.deferredInput, null);
+ assert.equal(ws.sent.length, sent);
+ h.c.stop();
+});
+
+test('B48 fence: duplicate automatic activity end cannot retire an idle next command', async () => {
+ const h = harness();
+ await h.c.start();
+ const ws = h.sockets[0];
+ ws.message({ voiceActivity: { type: 'ACTIVITY_START' } });
+ ws.message({ voiceActivity: { type: 'ACTIVITY_END' } });
+ ws.message({
+ serverContent: { ...replyAudio('finished'), turnComplete: true },
+ });
+ h.captures[0].drain();
+ ws.message({ voiceActivity: { type: 'ACTIVITY_END' } });
+ h.c.sendTextCommand('new idle turn');
+ ws.message({
+ serverContent: { ...replyAudio('new idle answer'), turnComplete: true },
+ });
+ assert.equal(h.captures[0].played.at(-1).data, 'new idle answer');
+ h.c.stop();
+});
+
+test('B48 queue: a boundary before deferred PTT worklet start still fences the submitted successor', async () => {
+ const h = harness();
+ await h.c.start({ pushToTalk: true });
+ const ws = h.sockets[0];
+ ws.message({ serverContent: replyAudio('old') });
+ h.c.sendTextCommand('first successor');
+ h.c.input.bargeIn(); // Audio-start callback is deliberately delayed.
+ ws.message({ serverContent: { interrupted: true, turnComplete: true } });
+ ws.message({ serverContent: replyAudio('first-successor-stale') });
+ assert.equal(h.captures[0].played.length, 1);
+ h.c.input.setMicrophoneEnabled(true);
+ h.captures[0].callbacks.onAudio(
+ {
+ data: 'latest',
+ mimeType: 'audio/pcm;rate=16000',
+ },
+ h.captures[0].metadata,
+ );
+ h.c.input.setMicrophoneEnabled(false);
+ ws.message({ serverContent: { interrupted: true, turnComplete: true } });
+ ws.message({
+ serverContent: { ...replyAudio('latest'), turnComplete: true },
+ });
+ assert.equal(h.captures[0].played.at(-1).data, 'latest');
+ h.c.stop();
+});
+
+for (const latest of ['push-to-talk', 'user-text']) {
+ test(`B48 queue: ${latest} can replace the other unsent input mode without stale pointer context`, async () => {
+ const { pointer, advance } = pointerHarness();
+ const h = harness({ pointer });
+ await h.c.start({ pushToTalk: true });
+ const ws = h.sockets[0];
+ const audio = h.captures[0];
+ ws.message({ serverContent: replyAudio('old') });
+ pointer.moveTo(300, 200);
+ h.c.sendTextCommand('first successor');
+ const speak = (x) => {
+ pointer.moveTo(x, 200);
+ h.c.input.holdPointer();
+ h.c.input.bargeIn();
+ h.c.input.beginPointerTurn('keydown');
+ h.c.input.setMicrophoneEnabled(true);
+ audio.callbacks.onAudio(
+ {
+ data: String(x),
+ mimeType: 'audio/pcm;rate=16000',
+ },
+ audio.metadata,
+ );
+ h.c.input.releasePointerHold();
+ h.c.input.setMicrophoneEnabled(false);
+ };
+ if (latest === 'push-to-talk') {
+ pointer.moveTo(500, 200);
+ h.c.sendTextCommand('discard queued text');
+ speak(700);
+ } else {
+ speak(500);
+ advance(5001);
+ h.c.sendTextCommand('latest text without pointer');
+ }
+ const sent = ws.sent.length;
+ ws.message({ serverContent: { turnComplete: true } }); // Natural completion races the claim.
+ const frames = ws.sent.slice(sent);
+ if (latest === 'push-to-talk') {
+ assert.equal(
+ frames.some((message) => message.clientContent?.turnComplete === true),
+ false,
+ );
+ assert.equal(frames[0].clientContent.turnComplete, false);
+ assert.deepEqual(frames[1], { realtimeInput: { activityStart: {} } });
+ assert.equal(
+ JSON.parse(frames[0].clientContent.turns[0].parts[0].text).target.label,
+ 'Aircraft 700',
+ );
+ } else {
+ assert.equal(frames.length, 1);
+ assert.deepEqual(
+ JSON.parse(frames[0].clientContent.turns[0].parts[0].text),
+ { type: 'pointer_context', at: 'text', target: 'none' },
+ );
+ assert.equal(pointer.activeSnapshot(), null);
+ }
+ ws.message({ serverContent: { interrupted: true, turnComplete: true } });
+ ws.message({
+ serverContent: { ...replyAudio('latest'), turnComplete: true },
+ });
+ assert.equal(audio.played.at(-1).data, 'latest');
+ h.c.stop();
+ pointer.destroy();
+ });
+}
+
+test('R51: typed override closes forwarded PTT before its queued text and suppresses the old flush', async () => {
+ const h = harness();
+ await h.c.start({ pushToTalk: true });
+ const ws = h.sockets[0];
+ const audio = h.captures[0];
+ ws.message({ serverContent: replyAudio('retired A') });
+ h.c.input.bargeIn();
+ h.c.input.setMicrophoneEnabled(true);
+ audio.callbacks.onAudio(
+ {
+ data: 'spoken B',
+ mimeType: 'audio/pcm;rate=16000',
+ },
+ audio.metadata,
+ );
+ const before = ws.sent.length;
+ h.c.sendTextCommand('latest typed C');
+ assert.equal(
+ ws.sent.at(-1).realtimeInput?.activityEnd !== undefined,
+ true,
+ 'the forwarded speech must end when typed intent supersedes it',
+ );
+ assert.equal(ws.sent.length, before + 1);
+ audio.callbacks.onAudio(
+ {
+ data: 'retired buffered B',
+ mimeType: 'audio/pcm;rate=16000',
+ },
+ audio.metadata,
+ );
+ h.c.input.setMicrophoneEnabled(false);
+ assert.equal(
+ ws.sent.length,
+ before + 1,
+ 'late old PCM/end cannot extend or duplicate closed activity',
+ );
+ ws.message({ serverContent: { interrupted: true, turnComplete: true } });
+ const flushed = ws.sent.slice(before);
+ assert.equal(flushed.length, 2);
+ assert.equal(flushed[0].realtimeInput?.activityEnd !== undefined, true);
+ assert.equal(
+ flushed[1].clientContent.turns[0].parts.at(-1).text,
+ 'latest typed C',
+ );
+ h.c.stop();
+});
+
+test('R51: a delayed old worklet start cannot reclaim a typed turn; a fresh hold still works', async () => {
+ const h = harness();
+ await h.c.start({ pushToTalk: true });
+ const ws = h.sockets[0];
+ const audio = h.captures[0];
+ h.c.sendTextCommand('current text');
+ const before = ws.sent.length;
+ // This is the prior gesture's callback, delayed until after typed intent.
+ audio.callbacks.onAudioStart(audio.metadata);
+ audio.callbacks.onAudio(
+ {
+ data: 'old gesture',
+ mimeType: 'audio/pcm;rate=16000',
+ },
+ audio.metadata,
+ );
+ audio.callbacks.onAudioEnd(audio.metadata);
+ assert.equal(ws.sent.length, before);
+ ws.message({
+ serverContent: { ...replyAudio('text completed'), turnComplete: true },
+ });
+ audio.drain();
+ h.c.input.bargeIn();
+ h.c.input.setMicrophoneEnabled(true);
+ audio.callbacks.onAudio(
+ {
+ data: 'fresh hold',
+ mimeType: 'audio/pcm;rate=16000',
+ },
+ audio.metadata,
+ );
+ h.c.input.setMicrophoneEnabled(false);
+ const frames = ws.sent.slice(before);
+ assert.equal(frames[0].realtimeInput.activityStart !== undefined, true);
+ assert.equal(frames[1].realtimeInput.audio.data, 'fresh hold');
+ assert.equal(frames[2].realtimeInput.activityEnd !== undefined, true);
+ h.c.stop();
+});
+
+test('R51: replaced unsent PTT contributes no unmatched end to the forwarded stream', async () => {
+ const h = harness();
+ await h.c.start({ pushToTalk: true });
+ const ws = h.sockets[0];
+ const audio = h.captures[0];
+ ws.message({ serverContent: replyAudio('retired A') });
+ h.c.sendTextCommand('submitted B');
+ h.c.input.bargeIn();
+ h.c.input.setMicrophoneEnabled(true);
+ audio.callbacks.onAudio(
+ {
+ data: 'unsent C',
+ mimeType: 'audio/pcm;rate=16000',
+ },
+ audio.metadata,
+ );
+ h.c.sendTextCommand('newest typed D');
+ const before = ws.sent.length;
+ h.c.input.setMicrophoneEnabled(false);
+ assert.equal(ws.sent.length, before);
+ ws.message({ serverContent: { interrupted: true, turnComplete: true } });
+ const flushed = ws.sent.slice(before);
+ assert.equal(flushed.length, 1);
+ assert.equal(
+ flushed[0].clientContent.turns[0].parts.at(-1).text,
+ 'newest typed D',
+ );
+ h.c.stop();
+});
+
+test('R51-2: FIFO old capture messages stay retired after typed replacement and a fresh claim', async () => {
+ const { pointer } = pointerHarness();
+ const h = harness({ pointer });
+ await h.c.start({ pushToTalk: true });
+ const ws = h.sockets[0];
+ const audio = h.captures[0];
+ // Delay only the worklet message port; gate/gesture callbacks still run now.
+ const port = [];
+ const callbacks = audio.callbacks;
+ const enable = audio.setMicrophoneEnabled.bind(audio);
+ audio.setMicrophoneEnabled = (value, metadata) => {
+ if (value && !audio.enabled)
+ port.push(() => callbacks.onAudioStart(metadata));
+ if (!value && audio.enabled) {
+ const ending = audio.metadata;
+ port.push(() => callbacks.onAudioEnd(ending));
+ }
+ audio.enabled = value;
+ if (value) audio.metadata = metadata;
+ };
+ ws.message({ serverContent: replyAudio('outstanding A') });
+ const claim = (x) => {
+ pointer.moveTo(x, 200);
+ h.c.input.holdPointer();
+ h.c.input.bargeIn();
+ h.c.input.beginPointerTurn('keydown');
+ h.c.input.setMicrophoneEnabled(true);
+ return audio.metadata;
+ };
+ const b = claim(300);
+ port.push(() =>
+ callbacks.onAudio(
+ { data: 'retired B', mimeType: 'audio/pcm;rate=16000' },
+ b,
+ ),
+ );
+ h.c.sendTextCommand('typed C');
+ h.c.input.releasePointerHold();
+ h.c.input.setMicrophoneEnabled(false);
+ const d = claim(700);
+ port.push(() =>
+ callbacks.onAudio(
+ { data: 'current D', mimeType: 'audio/pcm;rate=16000' },
+ d,
+ ),
+ );
+ h.c.input.releasePointerHold();
+ h.c.input.setMicrophoneEnabled(false);
+ const before = ws.sent.length;
+ // Allowed port FIFO: start B / PCM B / end B / start D / PCM D / end D.
+ for (const deliver of port) deliver();
+ assert.equal(ws.sent.length, before);
+ const queued = h.c.deferredInput.messages;
+ assert.deepEqual(
+ queued.map((message) =>
+ message.clientContent
+ ? 'context'
+ : message.realtimeInput.audio?.data ||
+ (message.realtimeInput.activityStart ? 'start' : 'end'),
+ ),
+ ['context', 'start', 'current D', 'end'],
+ );
+ assert.equal(
+ JSON.parse(queued[0].clientContent.turns[0].parts[0].text).target.label,
+ 'Aircraft 700',
+ );
+ ws.message({ serverContent: { interrupted: true, turnComplete: true } });
+ assert.deepEqual(ws.sent.slice(before), queued);
+ assert.equal(JSON.stringify(ws.sent).includes('captureId'), false);
+ audio.setMicrophoneEnabled = enable;
+ h.c.stop();
+});
+
+test('R51-2: a normal release keeps its delayed final PCM and end, without relabelling duplicate gates or tool aborts', async () => {
+ const h = harness();
+ h.c.input.pushToTalkKeyHeld = true;
+ await h.c.start({ pushToTalk: true });
+ const audio = h.captures[0];
+ const metadata = audio.metadata;
+ const ws = h.sockets[0];
+ h.c.input.setMicrophoneEnabled(true);
+ assert.equal(audio.metadata.captureId, metadata.captureId);
+ h.c.abortTools(); // Radio cleanup is not a new physical capture.
+ const end = audio.callbacks.onAudioEnd;
+ let released;
+ audio.callbacks.onAudioEnd = (identity) => {
+ released = identity;
+ };
+ h.c.input.setMicrophoneEnabled(false);
+ assert.equal(released.captureId, metadata.captureId);
+ const before = ws.sent.length;
+ audio.callbacks.onAudio(
+ { data: 'released tail', mimeType: 'audio/pcm;rate=16000' },
+ metadata,
+ );
+ end(released);
+ assert.deepEqual(ws.sent.slice(before), [
+ {
+ realtimeInput: {
+ audio: { data: 'released tail', mimeType: 'audio/pcm;rate=16000' },
+ },
+ },
+ { realtimeInput: { activityEnd: {} } },
+ ]);
+ audio.callbacks.onAudioEnd = end;
+ h.c.stop();
+});
+
+test('R51-2: a forwarded old capture closes once before fresh FIFO start and cannot close the new activity', async () => {
+ const h = harness();
+ await h.c.start({ pushToTalk: true });
+ const audio = h.captures[0];
+ const ws = h.sockets[0];
+ h.c.input.bargeIn();
+ h.c.input.setMicrophoneEnabled(true);
+ const b = audio.metadata;
+ audio.callbacks.onAudio(
+ { data: 'forwarded B', mimeType: 'audio/pcm;rate=16000' },
+ b,
+ );
+ const start = audio.callbacks.onAudioStart;
+ const end = audio.callbacks.onAudioEnd;
+ const port = [];
+ audio.callbacks.onAudioStart = (identity) => port.push(() => start(identity));
+ audio.callbacks.onAudioEnd = (identity) => port.push(() => end(identity));
+ h.c.input.setMicrophoneEnabled(false);
+ h.c.input.bargeIn();
+ h.c.input.setMicrophoneEnabled(true);
+ const d = audio.metadata;
+ const before = ws.sent.length;
+ for (const deliver of port) deliver(); // end B, start D in port FIFO.
+ assert.deepEqual(ws.sent.slice(before), [
+ { realtimeInput: { activityEnd: {} } },
+ { realtimeInput: { activityStart: {} } },
+ ]);
+ assert.equal(h.c.forwardedCaptureId, d.captureId);
+ end(b); // A duplicate old end cannot close D.
+ assert.equal(ws.sent.length, before + 2);
+ assert.equal(h.c.forwardedActivityOpen, true);
+ audio.callbacks.onAudio(
+ { data: 'current D', mimeType: 'audio/pcm;rate=16000' },
+ d,
+ );
+ audio.callbacks.onAudioStart = start;
+ audio.callbacks.onAudioEnd = end;
+ h.c.input.setMicrophoneEnabled(false);
+ assert.equal(ws.sent.at(-1).realtimeInput.activityEnd !== undefined, true);
+ assert.equal(h.c.forwardedActivityOpen, false);
+ h.c.stop();
+});
+
+test('R51-2: absent metadata fails closed and Stop/error restart never reuse capture identity', async () => {
+ const h = harness();
+ let previous = 0;
+ let old;
+ let oldMetadata;
+ for (const terminate of ['stop', 'error', 'stop']) {
+ h.c.input.pushToTalkKeyHeld = true;
+ await h.c.start({ pushToTalk: true });
+ const audio = h.captures.at(-1);
+ const ws = h.sockets.at(-1);
+ assert.ok(audio.metadata.captureId > previous);
+ previous = audio.metadata.captureId;
+ const before = ws.sent.length;
+ for (const captureId of [undefined, null, 0, -1, 1.5, '1', Infinity]) {
+ const metadata = captureId === undefined ? undefined : { captureId };
+ audio.callbacks.onAudioStart(metadata);
+ audio.callbacks.onAudio(
+ { data: 'must reject', mimeType: 'audio/pcm;rate=16000' },
+ metadata,
+ );
+ audio.callbacks.onAudioEnd(metadata);
+ }
+ if (old) {
+ old.onAudioStart(oldMetadata);
+ old.onAudio(
+ { data: 'old epoch', mimeType: 'audio/pcm;rate=16000' },
+ oldMetadata,
+ );
+ old.onAudioEnd(oldMetadata);
+ }
+ assert.equal(ws.sent.length, before);
+ assert.equal(h.c.forwardedActivityOpen, true);
+ old = audio.callbacks;
+ oldMetadata = audio.metadata;
+ if (terminate === 'error') h.c.fail(new Error('capture failed'));
+ else h.c.stop();
+ assert.equal(h.c.captureOwner, null);
+ assert.equal(h.c.captureEnabled, false);
+ assert.equal(h.c.forwardedCaptureId, null);
+ }
+});
+
+for (const queued of ['empty', 'text']) {
+ test(`R52: ${queued} flush keeps the original retirement wait bound`, async () => {
+ const h = harness({ inputBoundaryTimeoutMs: 40 });
+ await h.c.start({ pushToTalk: true });
+ const ws = h.sockets[0];
+ ws.message({ serverContent: replyAudio('old') });
+ h.c.sendTextCommand('first submitted successor');
+ if (queued === 'empty') h.c.input.bargeIn();
+ else h.c.sendTextCommand('newest queued text');
+ // A physical empty hold no longer submits/retires a successor. The first
+ // submitted text still owns the reply when the old native boundary arrives.
+ if (queued === 'empty') {
+ assert.equal(h.c.deferredInput, null);
+ ws.message({ serverContent: { interrupted: true, turnComplete: true } });
+ assert.equal(h.c.retiredReplyPending, false);
+ assert.equal(h.c.replyPending, true);
+ h.advance(60);
+ assert.equal(h.c.status, 'listening');
+ assert.equal(ws.closed, undefined);
+ h.c.stop();
+ return;
+ }
+ const deadline = h.c.deferredInput.deadline;
+ ws.message({ serverContent: { interrupted: true, turnComplete: true } });
+ assert.equal(h.c.deferredInput, null);
+ assert.equal(h.c.retiredReplyPending, true);
+ h.advance(deadline + 20);
+ assert.equal(
+ h.c.status,
+ 'error',
+ 'missing genuine boundary cannot leave voice waiting indefinitely',
+ );
+ assert.equal(ws.closed, true);
+ assert.equal(h.tracks[0].readyState, 'ended');
+ h.c.stop();
+ });
+}
+
+test('R52: replacement cannot extend a flushed retirement deadline and Stop cancels it', async () => {
+ for (const exit of ['timeout', 'stop', 'boundary']) {
+ const h = harness({ inputBoundaryTimeoutMs: 60 });
+ await h.c.start();
+ const ws = h.sockets[0];
+ ws.message({ serverContent: replyAudio('old') });
+ h.c.sendTextCommand('first successor');
+ h.c.sendTextCommand('queued successor');
+ const deadline = h.c.deferredInput.deadline;
+ ws.message({ serverContent: { interrupted: true, turnComplete: true } });
+ h.advance(15);
+ h.c.sendTextCommand('replacement while successor retired');
+ assert.equal(h.c.deferredInput.deadline, deadline);
+ if (exit === 'stop') h.c.stop();
+ if (exit === 'boundary') {
+ ws.message({ serverContent: { interrupted: true, turnComplete: true } });
+ ws.message({ serverContent: { interrupted: true, turnComplete: true } });
+ ws.message({
+ serverContent: { ...replyAudio('latest'), turnComplete: true },
+ });
+ h.captures[0].drain();
+ }
+ h.advance(deadline + 20);
+ assert.equal(
+ h.c.status,
+ exit === 'timeout' ? 'error' : exit === 'stop' ? 'idle' : 'listening',
+ );
+ assert.equal(Boolean(ws.closed), exit !== 'boundary');
+ h.c.stop();
+ }
+});
+
+test('PTT pointer context is quiet, ordered once, and only PCM creates a pending reply', async () => {
+ const { pointer } = pointerHarness();
+ const h = harness({ pointer });
+ pointer.moveTo(300, 200);
+ h.c.input.holdPointer();
+ h.c.input.pushToTalkKeyHeld = true;
+ h.c.input.spaceKeyHeld = true;
+ await h.c.start({ pushToTalk: true });
+ const ws = h.sockets[0],
+ audio = h.captures[0];
+ const [context, start] = ws.sent.slice(1);
+ assert.deepEqual(Object.keys(context), ['clientContent']);
+ assert.equal(context.clientContent.turnComplete, false);
+ assert.equal(context.clientContent.turns.length, 1);
+ assert.equal(context.clientContent.turns[0].role, 'user');
+ assert.equal(
+ JSON.parse(context.clientContent.turns[0].parts[0].text).target.label,
+ 'Aircraft 300',
+ );
+ assert.deepEqual(start, { realtimeInput: { activityStart: {} } });
+ assert.equal(h.c.replyPending, false);
+ assert.equal(audio.played.length, 0);
+ assert.equal(h.calls.length, 0);
+ audio.callbacks.onAudioStart(audio.metadata);
+ assert.equal(
+ ws.sent.length,
+ 3,
+ 'duplicate start does not resend quiet context',
+ );
+ audio.callbacks.onAudio(
+ { data: 'AAABAA==', mimeType: 'audio/pcm;rate=16000' },
+ audio.metadata,
+ );
+ assert.equal(h.c.replyPending, true);
+ assert.equal(
+ ws.sent.some((message) => message.realtimeInput?.text),
+ false,
+ );
+ h.c.stop();
+ pointer.destroy();
+});
+
+test('PTT pointer context rejected by the channel fails closed without opening activity', async () => {
+ const { pointer } = pointerHarness();
+ const h = harness({ pointer });
+ await h.c.start({ pushToTalk: true });
+ pointer.moveTo(300, 200);
+ h.c.input.holdPointer();
+ const ws = h.sockets[0],
+ before = ws.sent.length;
+ h.c.channel.readyState = 'connecting';
+ // The adapter emits one admitted start, not a retryable channel-open event.
+ h.c.input.setMicrophoneEnabled(true);
+ assert.equal(ws.sent.length, before);
+ assert.equal(h.c.forwardedActivityOpen, false);
+ assert.equal(h.c.pointerSentKey, null);
+ assert.equal(h.c.captureOwner, null);
+ assert.equal(h.c.userTurnPending, false);
+ assert.equal(h.c.status, 'error');
+ assert.equal(ws.closed, true);
+ assert.equal(h.tracks[0].readyState, 'ended');
+ h.c.stop();
+ pointer.destroy();
+});
+
+test('quiet pointer context rejects stale or absent capture metadata without touching the new pointer', async () => {
+ const { pointer } = pointerHarness();
+ const h = harness({ pointer });
+ await h.c.start({ pushToTalk: true });
+ pointer.moveTo(300, 200);
+ h.c.input.holdPointer();
+ h.c.input.setMicrophoneEnabled(true);
+ const old = h.captures[0].metadata,
+ context = h.c.captureOwner.context;
+ h.c.input.setMicrophoneEnabled(false);
+ pointer.moveTo(700, 200);
+ h.c.input.holdPointer();
+ h.c.input.setMicrophoneEnabled(true);
+ const before = h.sockets[0].sent.length,
+ key = h.c.pointerSentKey;
+ assert.equal(h.c.sendPointerContext(context, old), false);
+ assert.equal(h.c.sendPointerContext(context), false);
+ assert.equal(h.c.sendPointerContext(context, { captureId: 0 }), false);
+ assert.equal(h.sockets[0].sent.length, before);
+ assert.equal(h.c.pointerSentKey, key);
+ assert.equal(pointer.activeSnapshot().entity.id, '700');
+ h.c.stop();
+ pointer.destroy();
+});
+
+test('replacing a deferred quiet PTT context preserves its deadline and only flushes the latest owner', async () => {
+ const { pointer } = pointerHarness();
+ const h = harness({ pointer });
+ await h.c.start({ pushToTalk: true });
+ const ws = h.sockets[0],
+ audio = h.captures[0];
+ ws.message({ serverContent: replyAudio('old A') });
+ const claim = (x, pcm) => {
+ pointer.moveTo(x, 200);
+ h.c.input.holdPointer();
+ h.c.input.bargeIn();
+ h.c.input.beginPointerTurn('keydown');
+ h.c.input.setMicrophoneEnabled(true);
+ if (pcm)
+ audio.callbacks.onAudio(
+ { data: pcm, mimeType: 'audio/pcm;rate=16000' },
+ audio.metadata,
+ );
+ h.c.input.releasePointerHold();
+ h.c.input.setMicrophoneEnabled(false);
+ };
+ claim(300, 'submitted B');
+ claim(500);
+ const deadline = h.c.deferredInput.deadline;
+ const sent = ws.sent.length;
+ claim(700);
+ assert.equal(h.c.deferredInput.deadline, deadline);
+ assert.equal(h.c.deferredInput.kind, 'push-to-talk');
+ assert.equal(h.c.deferredInput.captureId, h.c.captureOwner.captureId);
+ assert.equal(h.c.deferredInput.messages.length, 3);
+ assert.equal(
+ JSON.parse(
+ h.c.deferredInput.messages[0].clientContent.turns[0].parts[0].text,
+ ).target.label,
+ 'Aircraft 700',
+ );
+ assert.equal(
+ JSON.stringify(h.c.deferredInput.messages).includes('Aircraft 500'),
+ false,
+ );
+ assert.equal(ws.sent.length, sent);
+ // The genuine retired boundary may coalesce content; it must discard it
+ // while releasing only the latest quiet context and its activity markers.
+ ws.message({
+ serverContent: {
+ ...replyAudio('retired coalesced A'),
+ interrupted: true,
+ turnComplete: true,
+ },
+ });
+ const flushed = ws.sent.slice(sent);
+ assert.equal(flushed.length, 3);
+ assert.equal(flushed[0].clientContent.turnComplete, false);
+ assert.deepEqual(flushed[1], { realtimeInput: { activityStart: {} } });
+ assert.deepEqual(flushed[2], { realtimeInput: { activityEnd: {} } });
+ assert.equal(audio.played.at(-1).data, 'old A');
+ assert.equal(
+ h.c.replyPending,
+ false,
+ 'flushed context without PCM asks for no reply',
+ );
+ assert.equal(h.c.retiredBoundaryWait.deadline, deadline);
+ assert.equal(h.c.retiredReplyPending, true);
+ assert.equal(h.c.pointerSentKey, h.c.captureOwner.context.key);
+ h.c.stop();
+ pointer.destroy();
+});
+
+test('projected PCM bytes and optional viewport frames drop while reliable tool results wait', async () => {
+ const h = harness({
+ captureViewport: async () => 'data:image/jpeg;base64,aW1hZ2U=',
+ });
+ await h.c.start();
+ establishToolInput(h);
+ const ws = h.sockets[0],
+ audio = h.captures[0],
+ before = ws.sent.length;
+ ws.bufferedAmount = 262140;
+ audio.callbacks.onAudio(
+ { data: 'AA==', mimeType: 'audio/pcm;rate=16000' },
+ audio.metadata,
+ );
+ ws.message({
+ toolCall: {
+ functionCalls: [
+ { id: 'image-pressure', name: 'get_entity_context', args: {} },
+ ],
+ },
+ });
+ h.c.runAction = async () => ({
+ ok: true,
+ action: 'get_entity_context',
+ scene: { basemap: { viewScale: 'local' } },
+ });
+ await h.c.toolQueue;
+ assert.equal(h.c.status, 'listening');
+ assert.equal(h.c.getDiagnostics().droppedAudioChunks, 1);
+ assert.equal(h.c.getDiagnostics().droppedImages, 1);
+ assert.equal(ws.sent.length, before);
+ assert.equal(h.c.controlQueue.length, 1);
+ ws.bufferedAmount = 0;
+ h.advance(25);
+ assert.equal(
+ ws.sent.at(-1).toolResponse.functionResponses[0].id,
+ 'image-pressure',
+ );
+ assert.match(
+ ws.sent.at(-1).toolResponse.functionResponses[0].response.responseGuidance,
+ /briefly|request|read|view/i,
+ );
+ assert.equal(h.c.controlQueue.length, 0);
+ h.c.stop();
+});
+
+test('congested PTT markers remain ordered and forwarding flags commit only at wire delivery', async () => {
+ const h = harness();
+ await h.c.start({ pushToTalk: true });
+ const ws = h.sockets[0],
+ audio = h.captures[0],
+ before = ws.sent.length;
+ ws.bufferedAmount = 300000;
+ h.c.input.setMicrophoneEnabled(true);
+ const capture = audio.metadata;
+ audio.callbacks.onAudio(
+ { data: 'discarded PCM', mimeType: 'audio/pcm;rate=16000' },
+ capture,
+ );
+ h.c.input.setMicrophoneEnabled(false);
+ assert.equal(h.c.forwardedActivityOpen, false);
+ assert.equal(h.c.controlQueue.length, 2);
+ assert.equal(ws.sent.length, before);
+ assert.equal(h.c.replyPending, false);
+ ws.bufferedAmount = 0;
+ h.advance(25);
+ assert.deepEqual(ws.sent.slice(before), [
+ { realtimeInput: { activityStart: {} } },
+ { realtimeInput: { activityEnd: {} } },
+ ]);
+ assert.equal(h.c.forwardedActivityOpen, false);
+ h.c.stop();
+});
+
+test('saturation then typed override and a fresh hold cannot flush retired pointer or capture markers', async () => {
+ const { pointer } = pointerHarness();
+ const h = harness({ pointer });
+ await h.c.start({ pushToTalk: true });
+ const ws = h.sockets[0],
+ audio = h.captures[0],
+ before = ws.sent.length;
+ ws.bufferedAmount = 300000;
+ pointer.moveTo(300, 200);
+ h.c.input.holdPointer();
+ h.c.input.bargeIn();
+ h.c.input.setMicrophoneEnabled(true);
+ const old = audio.metadata;
+ h.c.input.setMicrophoneEnabled(false);
+ h.c.sendTextCommand('unsent typed override');
+ assert.equal(
+ h.c.replyPending,
+ false,
+ 'queued text creates no phantom retired reply',
+ );
+ pointer.moveTo(700, 200);
+ h.c.input.holdPointer();
+ h.c.input.bargeIn();
+ h.c.input.setMicrophoneEnabled(true);
+ h.c.input.setMicrophoneEnabled(false);
+ audio.callbacks.onAudioStart(old);
+ audio.callbacks.onAudioEnd(old);
+ assert.equal(
+ h.c.pointerSentKey,
+ null,
+ 'queued context is not consumed before wire delivery',
+ );
+ ws.bufferedAmount = 0;
+ h.advance(25);
+ const frames = ws.sent.slice(before);
+ assert.equal(JSON.stringify(frames).includes('Aircraft 300'), false);
+ assert.equal(JSON.stringify(frames).includes('unsent typed override'), false);
+ assert.equal(
+ JSON.parse(frames[0].clientContent.turns[0].parts[0].text).target.label,
+ 'Aircraft 700',
+ );
+ assert.deepEqual(frames.slice(1), [
+ { realtimeInput: { activityStart: {} } },
+ { realtimeInput: { activityEnd: {} } },
+ ]);
+ assert.equal(h.c.forwardedActivityOpen, false);
+ h.c.stop();
+ pointer.destroy();
+});
+
+for (const cancellation of ['new-turn', 'server-call']) {
+ test(`a queued tool response is revoked by ${cancellation} before pressure clears`, async () => {
+ const h = harness();
+ await h.c.start();
+ const ws = h.sockets[0],
+ before = ws.sent.length;
+ ws.bufferedAmount = 300000;
+ ws.message({
+ toolCall: {
+ functionCalls: [
+ { id: 'queued-old', name: 'get_current_view_state', args: {} },
+ ],
+ },
+ });
+ await h.c.toolQueue;
+ assert.equal(h.c.controlQueue.length, 1);
+ if (cancellation === 'new-turn') h.c.sendTextCommand('new owned input');
+ else ws.message({ toolCallCancellation: { ids: ['queued-old'] } });
+ ws.bufferedAmount = 0;
+ h.advance(25);
+ assert.equal(
+ ws.sent.slice(before).some((frame) => frame.toolResponse),
+ false,
+ );
+ h.c.stop();
+ });
+}
+
+test('reliable pressure has an absolute deadline and Stop releases its poll without successor effects', async () => {
+ for (const mode of ['deadline', 'stop']) {
+ const h = harness();
+ await h.c.start();
+ const ws = h.sockets[0];
+ ws.bufferedAmount = 300000;
+ h.c.send({ realtimeInput: { text: 'reliable authored context' } });
+ h.advance(4975);
+ assert.equal(h.c.status, 'listening');
+ if (mode === 'stop') {
+ h.c.stop();
+ await h.c.start();
+ }
+ h.advance(25);
+ assert.equal(h.c.status, mode === 'deadline' ? 'error' : 'listening');
+ assert.equal(h.c.controlQueue.length, 0);
+ assert.equal(h.timers.size, 0);
+ h.c.stop();
+ }
+});
+
+test('reliable queue is byte and message bounded without partially sending oversized frames', async () => {
+ for (const kind of ['bytes', 'messages']) {
+ const h = harness();
+ await h.c.start();
+ const ws = h.sockets[0],
+ before = ws.sent.length;
+ ws.bufferedAmount = 300000;
+ if (kind === 'bytes') {
+ assert.throws(
+ () => h.c.send({ realtimeInput: { text: 'x'.repeat(1024 * 1024) } }),
+ /queue limit/,
+ );
+ } else {
+ for (let i = 0; i < 64; i++)
+ assert.equal(h.c.send({ realtimeInput: { text: String(i) } }), true);
+ assert.throws(
+ () => h.c.send({ realtimeInput: { text: 'overflow' } }),
+ /queue limit/,
+ );
+ }
+ assert.equal(ws.sent.length, before);
+ h.c.stop();
+ assert.equal(h.timers.size, 0);
+ }
+});
+
+test('goAway permits the current tool/reply/audio drain and denies successor input', async () => {
+ const tool = deferred();
+ const h = harness({ runAction: () => tool.promise });
+ await h.c.start();
+ const ws = h.sockets[0],
+ audio = h.captures[0];
+ h.c.sendTextCommand('read the view');
+ ws.message({
+ toolCall: {
+ functionCalls: [{ id: 'current', name: 'get_entity_context', args: {} }],
+ },
+ });
+ await tick();
+ ws.message({ goAway: { timeLeft: '5s' } });
+ assert.equal(h.c.goAway.deadline, 5000);
+ assert.equal(h.tracks[0].enabled, false);
+ assert.equal(h.c.sendTextCommand('successor is disallowed'), false);
+ assert.equal(h.c.bargeIn(), false);
+ h.c.input.setMicrophoneEnabled(true);
+ assert.equal(h.tracks[0].enabled, false);
+ tool.resolve({ ok: true, action: 'get_entity_context' });
+ await h.c.toolQueue;
+ assert.equal(ws.sent.at(-1).toolResponse.functionResponses[0].id, 'current');
+ ws.message({
+ serverContent: {
+ ...replyAudio('accepted reply'),
+ outputTranscription: { text: 'Current result' },
+ turnComplete: true,
+ },
+ });
+ assert.equal(h.c.isActive(), true);
+ assert.equal(audio.pending, true);
+ audio.drain();
+ assert.equal(h.c.status, 'error');
+ assert.equal(ws.closed, true);
+ assert.equal(h.timers.size, 0);
+ assert.equal(
+ h.events.findLast((event) => event.type === 'completion').audioDrained,
+ true,
+ );
+ h.c.stop();
+});
+
+test('goAway chooses the earliest bounded deadline and Stop cancels it for a fresh epoch', async () => {
+ const h = harness();
+ await h.c.start();
+ const ws = h.sockets[0];
+ ws.message({ serverContent: replyAudio('playing') });
+ ws.message({ goAway: { timeLeft: '1.250s' } });
+ h.advance(250);
+ ws.message({ goAway: { timeLeft: '500s' } });
+ assert.equal(h.c.goAway.deadline, 1250);
+ ws.message({ goAway: { timeLeft: '0.5s' } });
+ assert.equal(h.c.goAway.deadline, 750);
+ h.c.stop();
+ await h.c.start();
+ h.advance(1000);
+ assert.equal(h.c.status, 'listening');
+ assert.equal(h.sockets.length, 2);
+ assert.equal(h.c.goAway, null);
+ h.c.stop();
+});
+
+for (const duration of ['bad', '-1s', 'Infinitys', '10000000s', null]) {
+ test(`malformed goAway timeLeft ${duration} closes safely without an unbounded timer`, async () => {
+ const h = harness();
+ await h.c.start();
+ h.sockets[0].message({ serverContent: replyAudio('playing') });
+ h.sockets[0].message({ goAway: { timeLeft: duration } });
+ assert.equal(h.c.status, 'error');
+ assert.equal(h.timers.size, 0);
+ });
+}
+
+test('close diagnostics preserve bounded code/category but never provider reason or credential text', async () => {
+ const h = harness();
+ await h.c.start();
+ h.sockets[0].onclose({
+ code: 1008,
+ reason: 'auth_tokens/private-secret user-private-text',
+ });
+ assert.deepEqual(h.c.getDiagnostics().close, {
+ code: 1008,
+ category: 'policy',
+ });
+ assert.doesNotMatch(
+ JSON.stringify(h.c.getDiagnostics()),
+ /private-secret|user-private-text/,
+ );
+ await h.c.start();
+ h.sockets[1].onclose({ code: Infinity, reason: 'private' });
+ assert.deepEqual(h.c.getDiagnostics().close, {
+ code: null,
+ category: 'connection',
+ });
+ h.c.stop();
+});
+
- test(
- 'typed input grants an authentic correlated user turn and only audio drain completes spoken confirmation',
- {
- skip: 'replace-native: H05; equivalent native regression tests replace caption ownership assumptions',
- },
- async () => {
- const h = harness();
- await h.c.start();
- const ws = h.sockets[0],
- audio = h.captures[0];
- h.c.sendTextCommand('Show the current view');
- const response = h.events.findLast(
- (event) => event.type === 'response-start',
- );
- assert.equal(
- readVoiceUserTurnText(response.userTurn),
- 'Show the current view',
- );
- ws.message({
- toolCall: {
- functionCalls: [
- {
- id: 'provider',
- name: 'get_current_view_state',
- args: {},
- },
- ],
- },
- });
- await h.c.toolQueue;
- assert.equal(h.calls[0].options.userTurn, response.userTurn);
- assert.equal(h.calls[0].options.responseId, response.responseId);
- ws.message({
- serverContent: {
- ...replyAudio('confirmation'),
- outputTranscription: { text: 'Here is the current view' },
- turnComplete: true,
- },
- });
- assert.equal(
- h.events.some((event) => event.type === 'completion'),
- false,
- );
- assert.equal(
- h.events.findLast((event) => event.role === 'assistant').responseId,
- response.responseId,
- );
- audio.drain();
- const completion = h.events.findLast(
- (event) => event.type === 'completion',
- );
- assert.equal(completion.responseId, response.responseId);
- assert.equal(completion.spoken, true);
- assert.equal(completion.audioDrained, true);
- assert.equal(readVoiceUserTurnText(response.userTurn), undefined);
- h.c.stop();
- },
- );
-
- test(
- 'one native finalized speech segment authorizes its known current item',
- {
- skip: 'retired-by-decision: H06; captions no longer authorize or quarantine native calls (2026-10-15 contract)',
- },
- async () => {
- const h = harness();
- await h.c.start();
- const ws = h.sockets[0];
- ws.message({
- serverContent: {
- inputTranscription: { text: 'uncorrelated earlier speech' },
- },
- });
- ws.message({
- toolCall: {
- functionCalls: [
- { id: 'unowned', name: 'get_current_view_state', args: {} },
- ],
- },
- });
- await h.c.toolQueue;
- assert.deepEqual(h.calls, []);
- assert.equal(
- ws.sent.at(-1).toolResponse.functionResponses[0].response
- .voiceIntentUnverified,
- true,
- );
- ws.message({ serverContent: { turnComplete: true } });
- ws.message({ voiceActivity: { type: 'ACTIVITY_START' } });
- ws.message({
- serverContent: {
- interimInputTranscription: { text: 'partial untrusted' },
- },
- });
- ws.message({ voiceActivity: { type: 'ACTIVITY_END' } });
- ws.message({
- serverContent: { inputTranscription: { text: 'Show the current view' } },
- });
- const response = h.events.findLast(
- (event) => event.type === 'response-start',
- );
- assert.equal(
- readVoiceUserTurnText(response.userTurn),
- 'Show the current view',
- );
- ws.message({
- toolCall: {
- functionCalls: [
- { id: 'authorized', name: 'get_current_view_state', args: {} },
- ],
- },
- });
- await h.c.toolQueue;
- assert.equal(h.calls.at(-1).options.userTurn, response.userTurn);
- h.c.stop();
- assert.equal(readVoiceUserTurnText(response.userTurn), undefined);
- },
- );
-
- test(
- 'a Gemini speech tool waits for the correlated final transcript',
- {
- skip: 'retired-by-decision: H07; captions no longer authorize or quarantine native calls (2026-10-15 contract)',
- },
- async () => {
- const h = harness();
- await h.c.start();
- const ws = h.sockets[0];
- ws.message({ voiceActivity: { type: 'ACTIVITY_START' } });
- ws.message({ voiceActivity: { type: 'ACTIVITY_END' } });
- ws.message({
- toolCall: {
- functionCalls: [
- { id: 'deferred-provider', name: 'get_current_view_state', args: {} },
- ],
- },
- });
- await tick();
- assert.deepEqual(h.calls, []);
- ws.message({
- serverContent: {
- inputTranscription: { text: 'Show the current view' },
- },
- });
- await h.c.toolQueue;
- assert.equal(
- readVoiceUserTurnText(h.calls[0].options.userTurn),
- 'Show the current view',
- );
- h.c.stop();
- },
- );
-
- test(
- 'a newer Gemini turn cannot underflow a transcript-waiting tool count',
- {
- skip: 'replace-native: H08; equivalent native regression tests replace caption ownership assumptions',
- },
- async () => {
- const h = harness();
- await h.c.start();
- const ws = h.sockets[0];
- ws.message({ voiceActivity: { type: 'ACTIVITY_START' } });
- ws.message({ voiceActivity: { type: 'ACTIVITY_END' } });
- ws.message({
- toolCall: {
- functionCalls: [
- { id: 'retired-waiter', name: 'get_current_view_state', args: {} },
- ],
- },
- });
- await tick();
- const retiredTool = h.c.toolQueue;
- assert.equal(h.c.pendingTools, 1);
-
- ws.message({ voiceActivity: { type: 'ACTIVITY_START' } });
- assert.equal(h.c.pendingTools, 0);
- await retiredTool;
- assert.equal(h.c.pendingTools, 0);
- assert.deepEqual(h.calls, []);
-
- ws.message({ voiceActivity: { type: 'ACTIVITY_END' } });
- ws.message({ serverContent: { interrupted: true, turnComplete: true } });
- ws.message({ voiceActivity: { type: 'ACTIVITY_START' } });
- ws.message({ voiceActivity: { type: 'ACTIVITY_END' } });
- ws.message({
- serverContent: { inputTranscription: { text: 'what is in view' } },
- });
- ws.message({
- toolCall: {
- functionCalls: [
- { id: 'fresh-action', name: 'get_current_view_state', args: {} },
- ],
- },
- });
- await h.c.toolQueue;
- assert.equal(h.calls.length, 1);
- assert.equal(h.calls[0].name, 'get_current_view_state');
- assert.equal(h.c.pendingTools, 0);
- ws.message({
- serverContent: { ...replyAudio('fresh reply'), turnComplete: true },
- });
- h.captures[0].drain();
- assert.equal(
- h.events.findLast((event) => event.type === 'completion').status,
- 'completed',
- );
- h.c.stop();
- },
- );
-
- test(
- 'overlapping native speech with uncorrelated late transcripts cannot authorize a read tool',
- {
- skip: 'retired-by-decision: H09; captions no longer authorize or quarantine native calls (2026-10-15 contract)',
- },
- async () => {
- const h = harness();
- await h.c.start();
- const ws = h.sockets[0];
- ws.message({ serverContent: replyAudio('previous reply') });
- ws.message({ voiceActivity: { type: 'ACTIVITY_START' } });
- ws.message({ voiceActivity: { type: 'ACTIVITY_END' } });
- ws.message({
- serverContent: { inputTranscription: { text: 'switch to OpenAI' } },
- });
- ws.message({ serverContent: { interrupted: true, turnComplete: true } });
- ws.message({
- toolCall: {
- functionCalls: [
- {
- id: 'ambiguous-setting',
- name: 'get_current_view_state',
- args: { provider: 'openai' },
- },
- ],
- },
- });
- await tick();
- h.advance(5000);
- await h.c.toolQueue;
- assert.deepEqual(h.calls, []);
- assert.equal(
- ws.sent.some(
- (message) =>
- message.toolResponse?.functionResponses?.[0]?.response
- ?.voiceIntentUnverified === true,
- ),
- true,
- );
- h.c.stop();
- },
- );
-
+test('goAway never flushes an unsent successor at the retired response boundary', async () => {
+ const h = harness();
+ await h.c.start();
+ const ws = h.sockets[0];
+ ws.message({ serverContent: replyAudio('retired previous') });
+ h.c.sendTextCommand('already forwarded successor');
+ h.c.sendTextCommand('unsent newest successor');
+ assert.ok(h.c.deferredInput);
+ const before = ws.sent.length;
+ ws.message({ goAway: { timeLeft: '5s' } });
+ ws.message({ serverContent: { interrupted: true, turnComplete: true } });
+ assert.equal(
+ ws.sent.slice(before).some((message) => message.clientContent),
+ false,
+ );
+ assert.equal(h.c.status, 'error');
+ assert.equal(h.c.deferredInput, null);
+ assert.equal(h.timers.size, 0);
+ h.c.stop();
+});
+
+test('permission rejection opens no token/socket and initialized audio is released', async () => {
+ const h = harness({
+ getUserMedia: async () => {
+ throw new DOMException('not allowed', 'NotAllowedError');
+ },
+ });
+ await h.c.start();
+ assert.equal(h.c.status, 'error');
+ assert.equal(h.requests.length, 0);
+ assert.equal(h.sockets.length, 0);
+ assert.equal(h.captures[0].closed, true);
+ assert.match(h.c.lastError, /permission was denied/);
+});
+
+test('consented microphone stays muted through the network phase and its deadline releases tracks', async () => {
+ const pending = deferred();
+ const h = harness({ startupTimeoutMs: 20, fetchImpl: () => pending.promise });
+ const start = h.c.start();
+ await tick();
+ assert.equal(h.tracks[0].enabled, false);
+ await Promise.all([start, new Promise((resolve) => setTimeout(resolve, 40))]);
+ assert.equal(h.c.status, 'error');
+ assert.equal(h.tracks[0].readyState, 'ended');
+ assert.equal(h.captures[0].closed, true);
- pending.resolve({ ok: true, json: async () => credential });
++ pending.resolve(Response.json(credential));
+ await tick();
+ assert.equal(h.sockets.length, 0);
+ h.c.stop();
+});
+
+test('valid huge goAway duration is clamped to a bounded timer', async () => {
+ const h = harness();
+ await h.c.start();
+ h.sockets[0].message({ serverContent: replyAudio('playing') });
+ h.sockets[0].message({ goAway: { timeLeft: '999999s' } });
+ assert.equal(h.c.goAway.deadline, 600000);
+ h.c.stop();
+ assert.equal(h.timers.size, 0);
+});
+
- test(
- 'held speech passes authentic first final input and invalidation revokes it',
- {
- skip: 'replace-native: H10; equivalent native regression tests replace caption ownership assumptions',
- },
- async () => {
- const h = harness();
- await h.c.start({ pushToTalk: true });
- const ws = h.sockets[0],
- audio = h.captures[0];
- h.c.input.bargeIn();
- h.c.input.setMicrophoneEnabled(true);
- audio.callbacks.onAudio(
- { data: 'AA==', mimeType: 'audio/pcm;rate=16000' },
- audio.metadata,
- );
- h.c.input.setMicrophoneEnabled(false);
- ws.message({
- serverContent: { inputTranscription: { text: 'Show the current view' } },
- });
- const response = h.events.findLast(
- (event) => event.type === 'response-start',
- );
- assert.equal(
- readVoiceUserTurnText(response.userTurn),
- 'Show the current view',
- );
- ws.message({
- toolCall: {
- functionCalls: [
- {
- id: 'held-setting',
- name: 'get_current_view_state',
- args: {},
- },
- ],
- },
- });
- await h.c.toolQueue;
- assert.equal(h.calls[0].options.userTurn, response.userTurn);
- h.c.sendTextCommand('new intent');
- assert.equal(readVoiceUserTurnText(response.userTurn), undefined);
- h.c.stop();
- },
- );
-
+test('cancelling a pressure-queued response retains passive map context for the next owned text', async () => {
+ const h = harness();
+ await h.c.start();
+ const ws = h.sockets[0];
+ h.c.notifyMapEvent({ type: 'map_annotation_outline', label: 'Austin' });
+ ws.bufferedAmount = 300000;
+ ws.message({
+ toolCall: {
+ functionCalls: [
+ { id: 'old-map-envelope', name: 'get_current_view_state', args: {} },
+ ],
+ },
+ });
+ await h.c.toolQueue;
+ assert.equal(
+ h.c.pendingMapEvents.length,
+ 1,
+ 'unsent data remains owned by the context queue',
+ );
+ ws.message({ toolCallCancellation: { ids: ['old-map-envelope'] } });
+ h.c.sendTextCommand('use the map context');
+ ws.bufferedAmount = 0;
+ h.advance(25);
+ const frame = ws.sent.at(-1);
+ assert.equal(
+ JSON.parse(frame.clientContent.turns[0].parts[0].text).events[0].label,
+ 'Austin',
+ );
+ assert.equal(h.c.pendingMapEvents.length, 0);
+ h.c.stop();
+});
+
+test('an expired goAway deadline rejects late output before the timer callback can run', async () => {
+ let now = 0;
+ const h = harness({ now: () => now });
+ await h.c.start();
+ const ws = h.sockets[0];
+ h.c.sendTextCommand('current request');
+ ws.message({ serverContent: replyAudio('initial output') });
+ ws.message({ goAway: { timeLeft: '1s' } });
+ now = 1000;
+ ws.message({
+ serverContent: { ...replyAudio('too late'), turnComplete: true },
+ });
+ assert.equal(h.c.status, 'error');
+ assert.equal(h.captures[0].played.length, 1);
+ assert.equal(
+ h.events.some((event) => event.type === 'completion'),
+ false,
+ );
+ assert.equal(h.timers.size, 0);
+});
+
- for (const restart of [false, true]) {
- test(
- `a transcript-waiting tool cannot revive voice after Stop${restart ? '/restart' : ''}`,
- {
- skip: 'replace-native: H11, H12; equivalent native regression tests replace caption ownership assumptions',
- },
- async () => {
- const h = harness();
- await h.c.start();
- const ws = h.sockets[0];
- ws.message({ voiceActivity: { type: 'ACTIVITY_START' } });
- ws.message({ voiceActivity: { type: 'ACTIVITY_END' } });
- ws.message({
- toolCall: {
- functionCalls: [
- { id: 'stopped-waiter', name: 'get_current_view_state', args: {} },
- ],
- },
- });
- await tick();
- const pending = h.c.toolQueue;
- assert.equal(h.c.pendingTools, 1);
- h.c.stop();
- const boundary = h.events.length;
- const successor = restart ? h.c.start() : null;
- await pending;
- assert.equal(
- h.events
- .slice(boundary)
- .some(
- (event) => event.type === 'state' && event.state === 'listening',
- ),
- false,
- );
- assert.deepEqual(h.calls, []);
- assert.equal(h.c.pendingTools, 0);
- if (successor) await successor;
- h.c.stop();
- },
- );
- }
-
- // Sameh runtime regressions exercise the socket adapter and the production
- // provider-intent guard before an action runner can mutate camera state.
- function samehPolicyHarness(overrides = {}) {
++function guardedNativeHarness(overrides = {}) {
+ const mutations = [];
+ const observed = [];
+ const guarded = withToolCatalog(
+ async (name, args, options) => {
+ mutations.push({ name, args, options });
+ return { ok: true, action: name };
+ },
+ async () => null,
+ );
+ const h = harness({
+ ...overrides,
+ runAction: async (name, args, options) => {
+ observed.push({ name, args, options });
+ return guarded(name, args, options);
+ },
+ });
+ return { ...h, mutations, observed };
+}
+
- test(
- 'punctuated finalized provider segments block actual synchronous app actions after the target arrives',
- {
- skip: 'retired-by-decision: H13; captions no longer authorize or quarantine native calls (2026-10-15 contract)',
- },
- async () => {
- const mutations = [];
- const viewer = {
- clock: { onTick: { addEventListener: () => () => {} } },
- camera: { moveEnd: { addEventListener() {} } },
- scene: { canvas: { addEventListener() {}, removeEventListener() {} } },
- };
- const runner = createGevActionRunner({
- viewer,
- styleManager: {
- setStyle: (...args) => mutations.push(['style', ...args]),
- setPanelCollapsed: (...args) => mutations.push(['panel', ...args]),
- },
- });
- const h = harness({ runAction: runner });
- try {
- await h.c.start();
- const ws = h.sockets[0];
- ws.message({ voiceActivity: { type: 'ACTIVITY_START' } });
- ws.message({ voiceActivity: { type: 'ACTIVITY_END' } });
- ws.message({
- serverContent: { inputTranscription: { text: 'Switch to.' } },
- });
- ws.message({
- serverContent: { inputTranscription: { text: 'Gemini.' } },
- });
- ws.message({
- toolCall: {
- functionCalls: [
- {
- id: 'punctuated-style',
- name: 'set_visual_style',
- args: { style: 'night vision' },
- },
- {
- id: 'punctuated-panel',
- name: 'set_panel_open',
- args: { panelId: 'radio-panel', open: true },
- },
- ],
- },
- });
- await tick();
- await h.c.toolQueue;
- assert.deepEqual(mutations, []);
- const outputs = ws.sent.flatMap(
- (frame) => frame.toolResponse?.functionResponses || [],
- );
- assert.equal(outputs.length, 2);
- assert.equal(
- outputs.every((call) => call.response.providerRequestBlocked === true),
- true,
- );
- } finally {
- h.c.stop();
- runner.dispose();
- }
- assert.equal(h.timers.size, 0);
- },
- );
-
- for (const boundary of ['interrupted', 'natural']) {
- test(
- `Sameh P0-1: spoken zoom after ${boundary} retired reply boundary executes promptly`,
- {
- skip: 'replace-native: H14, H15; equivalent native regression tests replace caption ownership assumptions',
- },
- async () => {
- const h = samehPolicyHarness();
- try {
- await h.c.start();
- const ws = h.sockets[0];
- ws.message({ serverContent: replyAudio('old reply') });
- ws.message({ voiceActivity: { type: 'ACTIVITY_START' } });
- ws.message({
- serverContent: {
- ...(boundary === 'interrupted' ? { interrupted: true } : {}),
- turnComplete: true,
- },
- });
- ws.message({ voiceActivity: { type: 'ACTIVITY_END' } });
- ws.message({
- serverContent: { inputTranscription: { text: 'zoom in' } },
- });
- requestTool(ws, 'current-zoom', 'adjust_camera_zoom', {
- direction: 'in',
- });
- await tick();
- assert.equal(
- h.mutations.length,
- 1,
- 'a current command must not await a missing transcript for five seconds',
- );
- assert.equal(
- readVoiceUserTurnText(h.observed[0].options.userTurn),
- 'zoom in',
- );
- assert.equal(h.c.pendingTools, 0);
- assert.equal(
- ws.sent.some(
- (m) =>
- m.toolResponse?.functionResponses?.[0]?.response
- ?.voiceIntentUnverified,
- ),
- false,
- );
- } finally {
- h.c.stop();
- }
- assert.equal(h.timers.size, 0);
- },
- );
- }
-
- test(
- 'Sameh P1-1: finalized provider fragments quarantine every sibling camera call',
- {
- skip: 'retired-by-decision: H16; captions no longer authorize or quarantine native calls (2026-10-15 contract)',
- },
- async () => {
- const h = samehPolicyHarness();
- try {
- await h.c.start();
- const ws = h.sockets[0];
- ws.message({ voiceActivity: { type: 'ACTIVITY_START' } });
- ws.message({ voiceActivity: { type: 'ACTIVITY_END' } });
- ws.message({
- serverContent: {
- inputTranscription: { text: 'switch voice provider' },
- },
- });
- const response = h.events.findLast(
- (event) => event.type === 'response-start',
- );
- requestTool(ws, 'first-camera', 'adjust_camera_zoom', {
- direction: 'in',
- });
- await tick();
- ws.message({
- serverContent: { inputTranscription: { text: 'to Gemini' } },
- });
- requestTool(ws, 'sibling-camera', 'adjust_camera_zoom', {
- direction: 'out',
- });
- await tick();
- h.advance(5000);
- await h.c.toolQueue;
- assert.deepEqual(
- h.mutations,
- [],
- 'native segments must not remove provider-intent policy from a sibling',
- );
- assert.equal(
- readVoiceUserTurnText(response.userTurn),
- 'switch voice provider to Gemini',
- );
- assert.equal(
- h.c.userTurns.forResponse(response.responseId),
- response.userTurn,
- );
- assert.deepEqual(
- h.observed,
- [],
- 'provider requests refuse before action preparation',
- );
- assert.equal(
- ws.sent.filter(
- (m) =>
- m.toolResponse?.functionResponses?.[0]?.response
- ?.providerRequestBlocked,
- ).length,
- 2,
- );
- } finally {
- h.c.stop();
- }
- assert.equal(h.timers.size, 0);
- },
- );
-
+for (const stage of ['deferred', 'flushed']) {
+ test(`Sameh P3-1: ${stage} retirement deadline uses the injected clock and releases timers`, async () => {
+ const h = harness({ inputBoundaryTimeoutMs: 60 });
+ try {
+ await h.c.start();
+ const ws = h.sockets[0];
+ ws.message({ serverContent: replyAudio('old') });
+ h.c.sendTextCommand('first successor');
+ h.c.sendTextCommand('queued successor');
+ assert.equal(h.c.deferredInput.deadline, 60);
+ h.advance(15);
+ h.c.sendTextCommand('replacement');
+ assert.equal(h.c.deferredInput.deadline, 60);
+ if (stage === 'flushed') {
+ ws.message({
+ serverContent: { interrupted: true, turnComplete: true },
+ });
+ assert.equal(h.c.retiredBoundaryWait.deadline, 60);
+ }
+ h.advance(44);
+ assert.notEqual(h.c.status, 'error');
+ h.advance(1);
+ assert.equal(h.c.status, 'error');
+ assert.equal(ws.closed, true);
+ assert.equal(h.timers.size, 0);
+ } finally {
+ h.c.stop();
+ }
+ });
+}
+
+for (const exit of ['stop', 'boundary']) {
+ test(`Sameh P3-1: ${exit} clears an injected retirement deadline before replacement`, async () => {
+ const h = harness({ inputBoundaryTimeoutMs: 60 });
+ try {
+ await h.c.start();
+ const ws = h.sockets[0];
+ ws.message({ serverContent: replyAudio('old') });
+ h.c.sendTextCommand('first successor');
+ h.c.sendTextCommand('queued successor');
+ const deadline = h.c.deferredInput.deadline;
+ h.advance(15);
+ h.c.sendTextCommand('newest successor');
+ assert.equal(h.c.deferredInput.deadline, deadline);
+ ws.message({ serverContent: { interrupted: true, turnComplete: true } });
+ assert.equal(h.c.retiredBoundaryWait.deadline, deadline);
+ assert.equal(
+ [...h.timers.values()].some((timer) => timer.at === 60),
+ true,
+ 'retirement wait must belong to the injected timer registry',
+ );
+ if (exit === 'stop') h.c.stop();
+ else {
+ ws.message({
+ serverContent: { interrupted: true, turnComplete: true },
+ });
+ ws.message({ serverContent: { turnComplete: true } });
+ }
+ assert.equal(
+ [...h.timers.values()].some((timer) => timer.at === 60),
+ false,
+ );
+ h.advance(100);
+ assert.equal(h.c.status, exit === 'stop' ? 'idle' : 'listening');
+ assert.equal(Boolean(ws.closed), exit === 'stop');
+ } finally {
+ h.c.stop();
+ }
+ });
+}
+
- test(
- 'Sameh P1-1: a late finalized segment updates both queued siblings before dispatch',
- {
- skip: 'retired-by-decision: H17; captions no longer authorize or quarantine native calls (2026-10-15 contract)',
- },
- async () => {
- const h = samehPolicyHarness();
- try {
- await h.c.start();
- const ws = h.sockets[0];
- ws.message({ voiceActivity: { type: 'ACTIVITY_START' } });
- ws.message({ voiceActivity: { type: 'ACTIVITY_END' } });
- ws.message({
- serverContent: { inputTranscription: { text: 'switch voice' } },
- });
- const response = h.events.findLast(
- (event) => event.type === 'response-start',
- );
- ws.message({
- toolCall: {
- functionCalls: [
- {
- id: 'queued-zoom-one',
- name: 'adjust_camera_zoom',
- args: { direction: 'in' },
- },
- { id: 'queued-zoom-two', name: 'zoom_to_globe', args: {} },
- ],
- },
- });
- // Both calls already exist; this provider segment arrives before their
- // serialized action dispatch and must update the authentic current token.
- ws.message({
- serverContent: { inputTranscription: { text: 'provider to Gemini' } },
- });
- await h.c.toolQueue;
- assert.deepEqual(h.mutations, []);
- assert.deepEqual(
- h.observed,
- [],
- 'provider requests refuse before action preparation',
- );
- assert.equal(
- h.c.userTurns.forResponse(response.responseId),
- response.userTurn,
- );
- assert.equal(
- readVoiceUserTurnText(response.userTurn),
- 'switch voice provider to Gemini',
- );
- assert.equal(
- ws.sent.filter(
- (m) =>
- m.toolResponse?.functionResponses?.[0]?.response
- ?.providerRequestBlocked,
- ).length,
- 2,
- );
- } finally {
- h.c.stop();
- }
- assert.equal(h.timers.size, 0);
- },
- );
-
- for (const exit of ['stop', 'replacement']) {
- test(
- `Sameh P1-1: ${exit} prevents queued fragments from reviving the old command`,
- {
- skip: 'replace-native: H18, H19; equivalent native regression tests replace caption ownership assumptions',
- },
- async () => {
- const h = samehPolicyHarness();
- try {
- await h.c.start();
- const ws = h.sockets[0];
- ws.message({ voiceActivity: { type: 'ACTIVITY_START' } });
- ws.message({ voiceActivity: { type: 'ACTIVITY_END' } });
- requestTool(ws, 'old-waiting-camera', 'adjust_camera_zoom', {
- direction: 'in',
- });
- await tick();
- const oldWork = h.c.toolQueue;
- if (exit === 'stop') h.c.stop();
- else h.c.sendTextCommand('switch voice provider to Gemini');
- ws.message({
- serverContent: { inputTranscription: { text: 'zoom in' } },
- });
- await oldWork;
- assert.deepEqual(h.mutations, []);
- assert.deepEqual(h.observed, []);
- assert.equal(h.c.pendingTools, 0);
- if (exit === 'replacement') {
- ws.message({
- serverContent: { interrupted: true, turnComplete: true },
- });
- requestTool(ws, 'current-provider-camera', 'zoom_to_globe', {});
- await h.c.toolQueue;
- assert.deepEqual(h.mutations, []);
- assert.equal(
- ws.sent.at(-1).toolResponse.functionResponses[0].response
- .providerRequestBlocked,
- true,
- );
- }
- } finally {
- h.c.stop();
- }
- assert.equal(h.timers.size, 0);
- },
- );
- }
-
- for (const toolOrder of ['before-boundary', 'after-boundary']) {
- test(
- `Sameh P0-1 ordering: unattributed early caption and tool ${toolOrder} fail closed and a new onset recovers`,
- {
- skip: 'replace-native: H20, H21; equivalent native regression tests replace caption ownership assumptions',
- },
- async () => {
- const h = samehPolicyHarness();
- try {
- await h.c.start();
- const ws = h.sockets[0];
- ws.message({ serverContent: replyAudio('old assistant reply') });
- ws.message({ voiceActivity: { type: 'ACTIVITY_START' } });
- ws.message({ voiceActivity: { type: 'ACTIVITY_END' } });
- ws.message({
- serverContent: { inputTranscription: { text: 'zoom in' } },
- });
- if (toolOrder === 'before-boundary')
- requestTool(
- ws,
- 'current-before-old-completion',
- 'adjust_camera_zoom',
- {
- direction: 'in',
- },
- );
- ws.message({
- serverContent: { interrupted: true, turnComplete: true },
- });
- if (toolOrder === 'after-boundary')
- requestTool(
- ws,
- 'current-after-old-completion',
- 'adjust_camera_zoom',
- {
- direction: 'in',
- },
- );
- await tick();
- // Input captions and tool calls have no turn ID. This ambiguous early
- // ordering cannot safely recover the original command from the wire.
- assert.deepEqual(h.mutations, []);
- assert.deepEqual(h.observed, []);
- assert.equal(h.c.pendingTools, 0);
- if (toolOrder === 'after-boundary')
- assert.equal(
- ws.sent.at(-1).toolResponse.functionResponses[0].response
- .voiceIntentUnverified,
- true,
- );
- ws.message({ voiceActivity: { type: 'ACTIVITY_START' } });
- if (h.c.retiredReplyPending)
- ws.message({
- serverContent: { interrupted: true, turnComplete: true },
- });
- ws.message({ voiceActivity: { type: 'ACTIVITY_END' } });
- ws.message({
- serverContent: { inputTranscription: { text: 'zoom in' } },
- });
- requestTool(ws, 'fresh-clean-onset', 'adjust_camera_zoom', {
- direction: 'in',
- });
- await h.c.toolQueue;
- assert.equal(h.mutations.length, 1);
- assert.equal(
- readVoiceUserTurnText(h.observed[0].options.userTurn),
- 'zoom in',
- );
- } finally {
- h.c.stop();
- }
- assert.equal(h.timers.size, 0);
- },
- );
- }
-
- for (const firstSegment of ['switch voice provider', 'switch voice']) {
- test(
- `Sameh P1-1 ordering: provider fragment ${firstSegment} before old completion cannot authorize a suffix camera call`,
- {
- skip: 'retired-by-decision: H22, H23; captions no longer authorize or quarantine native calls (2026-10-15 contract)',
- },
- async () => {
- const h = samehPolicyHarness();
- try {
- await h.c.start();
- const ws = h.sockets[0];
- ws.message({ serverContent: replyAudio('old assistant reply') });
- ws.message({ voiceActivity: { type: 'ACTIVITY_START' } });
- ws.message({ voiceActivity: { type: 'ACTIVITY_END' } });
- ws.message({
- serverContent: { inputTranscription: { text: firstSegment } },
- });
- requestTool(ws, 'ambiguous-before-boundary', 'adjust_camera_zoom', {
- direction: 'in',
- });
- ws.message({
- serverContent: { interrupted: true, turnComplete: true },
- });
- ws.message({
- serverContent: {
- inputTranscription: {
- text:
- firstSegment === 'switch voice'
- ? 'provider to Gemini'
- : 'to Gemini',
- },
- },
- });
- requestTool(ws, 'suffix-camera-one', 'adjust_camera_zoom', {
- direction: 'in',
- });
- requestTool(ws, 'suffix-camera-two', 'zoom_to_globe', {});
- await tick();
- h.advance(5000);
- await h.c.toolQueue;
- assert.deepEqual(
- h.mutations,
- [],
- 'discarding the prefix must not turn the suffix into an unrelated camera request',
- );
- assert.equal(h.c.pendingTools, 0);
- } finally {
- h.c.stop();
- }
- assert.equal(h.timers.size, 0);
- },
- );
- }
-
- test('Sameh projection: Gemini sends useful bounded failure prose as data without altering the local result', async () => {
- const failure = Object.freeze({
- ok: false,
- action: 'get_current_view_state',
- error:
- 'Map search failed: no matching place. token=private-test-secret. Retry with a city name.',
- say: 'Map search failed. ' + 'Choose a more specific city. '.repeat(80),
- retryable: true,
- changed: false,
- });
- const h = harness({ runAction: async () => failure });
- try {
- await h.c.start();
- establishToolInput(h, 'What is in view?');
- const ws = h.sockets[0];
- requestTool(ws, 'failed-place-query', 'get_current_view_state', {});
- await h.c.toolQueue;
- const output = ws.sent.at(-1).toolResponse.functionResponses[0].response;
- assert.equal(output.ok, false);
- assert.equal(output.changed, false);
- assert.equal(output.retryable, true);
- assert.match(output.error, /Map search failed: no matching place/);
- assert.match(output.error, /Retry with a city name/);
- assert.doesNotMatch(output.error, /private-test-secret/);
- assert.ok(output.say.length <= VOICE_TOOL_FAILURE_TEXT_LIMIT);
- assert.match(output.say, /Map search failed/);
- assert.match(failure.error, /private-test-secret/);
- assert.ok(failure.say.length > VOICE_TOOL_FAILURE_TEXT_LIMIT);
- assert.equal(h.c.status, 'listening');
- } finally {
- h.c.stop();
- }
- assert.equal(h.timers.size, 0);
- });
-
- // Selective C3 port: a clean current onset is essential here. An early caption
- // behind an old response boundary would pass by P0 quarantine alone.
- for (const segments of [
- ['use', 'foo', 'bar', 'baz', 'as', 'my', 'voice', 'provider'],
- ['use', 'Foo', 'as', 'my', 'voi', 'ce provider'],
- ['please', ', use foo', 'as my voice provider'],
- ['use', 'x'.repeat(41), 'as', 'my', 'voi', 'ce provider'],
- ['use', 'Claude'],
- ['use', ' '.repeat(10000) + 'foo', 'as my voice provider'],
- ]) {
- test(
- `selective C3: attributed ${JSON.stringify(segments)} refuses sibling actions with manual guidance`,
- {
- skip: 'retired-by-decision: H24, H25, H26, H27, H28, H29; captions no longer authorize or quarantine native calls (2026-10-15 contract)',
- },
- async () => {
- const h = samehPolicyHarness();
- try {
- await h.c.start();
- const ws = h.sockets[0];
- ws.message({ voiceActivity: { type: 'ACTIVITY_START' } });
- ws.message({ voiceActivity: { type: 'ACTIVITY_END' } });
- assert.equal(h.c.intentAmbiguous, false);
- for (const text of segments)
- ws.message({ serverContent: { inputTranscription: { text } } });
- requestTool(ws, 'joined-one', 'adjust_camera_zoom', {
- direction: 'in',
- });
- requestTool(ws, 'joined-two', 'zoom_to_globe', {});
- await h.c.toolQueue;
- assert.deepEqual(h.mutations, []);
- const outputs = ws.sent.flatMap(
- (m) => m.toolResponse?.functionResponses || [],
- );
- assert.equal(outputs.length, 2);
- for (const output of outputs) {
- assert.equal(output.response.providerRequestBlocked, true);
- assert.match(output.response.say, /switch voice providers directly/);
- assert.equal(output.response.voiceIntentUnverified, undefined);
- }
- } finally {
- h.c.stop();
- }
- assert.equal(h.timers.size, 0);
- },
- );
- }
-
+for (const segments of [
+ ['set', 'voice', 'volume', 'to', '50'],
+ ['set', 'voice', 'speed', 'to', 'fast'],
+ ['set', 'provider', 'to', 'bing maps'],
+ ['"use foo', 'as my voice provider"'],
+ ['use foo as my voice provider', 'and zoom out'],
+ ['do not', 'use foo as my voice provider'],
+ ['use', 'foo'],
+]) {
- test(`selective C3: attributed ordinary ${JSON.stringify(segments)} releases tools`, async () => {
- const h = samehPolicyHarness();
++ test(`native advisory caption text ${JSON.stringify(segments)} releases tools`, async () => {
++ const h = guardedNativeHarness();
+ try {
+ await h.c.start();
+ const ws = h.sockets[0];
+ ws.message({ voiceActivity: { type: 'ACTIVITY_START' } });
+ ws.message({ voiceActivity: { type: 'ACTIVITY_END' } });
+ for (const text of segments)
+ ws.message({ serverContent: { inputTranscription: { text } } });
+ requestTool(ws, 'ordinary-port', 'zoom_to_globe', {});
+ await h.c.toolQueue;
+ assert.equal(h.mutations.length, 1);
+ } finally {
+ h.c.stop();
+ }
+ assert.equal(h.timers.size, 0);
+ });
+}
-
- test(
- 'selective C3: ordinary resolution before expiry releases later siblings without a stale timeout',
- {
- skip: 'replace-native: H30; equivalent native regression tests replace caption ownership assumptions',
- },
- async () => {
- const h = samehPolicyHarness();
- try {
- await h.c.start();
- const ws = h.sockets[0];
- ws.message({ voiceActivity: { type: 'ACTIVITY_START' } });
- ws.message({ voiceActivity: { type: 'ACTIVITY_END' } });
- ws.message({
- serverContent: { inputTranscription: { text: 'switch to' } },
- });
- requestTool(ws, 'held-ordinary', 'zoom_to_globe', {});
- await tick();
- assert.equal(h.c.pendingTools, 1);
- h.advance(1499);
- ws.message({ serverContent: { inputTranscription: { text: 'Austin' } } });
- await h.c.toolQueue;
- assert.equal(h.mutations.length, 1);
- h.advance(5000);
- requestTool(ws, 'released-sibling', 'zoom_to_globe', {});
- await h.c.toolQueue;
- assert.equal(h.mutations.length, 2);
- } finally {
- h.c.stop();
- }
- assert.equal(h.timers.size, 0);
- },
- );
-
- test(
- 'selective C3: exact 1500ms expiry refuses late completed fragments and every sibling',
- {
- skip: 'retired-by-decision: H31; captions no longer authorize or quarantine native calls (2026-10-15 contract)',
- },
- async () => {
- const h = samehPolicyHarness();
- try {
- await h.c.start();
- const ws = h.sockets[0];
- ws.message({ voiceActivity: { type: 'ACTIVITY_START' } });
- ws.message({ voiceActivity: { type: 'ACTIVITY_END' } });
- ws.message({
- serverContent: { inputTranscription: { text: 'switch to' } },
- });
- requestTool(ws, 'expiry-one', 'zoom_to_globe', {});
- await tick();
- h.advance(1499);
- assert.equal(h.c.pendingTools, 1);
- h.advance(1);
- ws.message({ serverContent: { inputTranscription: { text: 'Gemini' } } });
- requestTool(ws, 'expiry-two', 'zoom_to_globe', {});
- await h.c.toolQueue;
- assert.deepEqual(h.mutations, []);
- const outputs = ws.sent.flatMap(
- (m) => m.toolResponse?.functionResponses || [],
- );
- assert.equal(outputs.length, 2);
- for (const output of outputs) {
- assert.equal(output.response.voiceIntentUnverified, true);
- assert.match(output.response.error, /incomplete/);
- }
- } finally {
- h.c.stop();
- }
- assert.equal(h.timers.size, 0);
- },
- );
-
- for (const exit of ['stop', 'restart', 'new-input']) {
- test(
- `selective C3: ${exit} retires joined fragment state and late callbacks`,
- {
- skip: 'replace-native: H32, H33, H34; equivalent native regression tests replace caption ownership assumptions',
- },
- async () => {
- const h = samehPolicyHarness();
- try {
- await h.c.start();
- let ws = h.sockets[0];
- ws.message({ voiceActivity: { type: 'ACTIVITY_START' } });
- ws.message({ voiceActivity: { type: 'ACTIVITY_END' } });
- ws.message({
- serverContent: { inputTranscription: { text: 'switch to' } },
- });
- requestTool(ws, 'old-port-hold', 'zoom_to_globe', {});
- await tick();
- const oldWork = h.c.toolQueue;
- if (exit === 'new-input') h.c.sendTextCommand('zoom out');
- else h.c.stop();
- ws.message({
- serverContent: { inputTranscription: { text: 'Gemini' } },
- });
- h.advance(1500);
- await oldWork;
- assert.deepEqual(h.mutations, []);
- if (exit === 'restart') {
- await h.c.start();
- ws = h.sockets.at(-1);
- h.c.sendTextCommand('zoom out');
- } else if (exit === 'new-input') {
- ws.message({
- serverContent: { interrupted: true, turnComplete: true },
- });
- }
- if (exit !== 'stop') {
- requestTool(ws, 'fresh-after-port', 'zoom_to_globe', {});
- await h.c.toolQueue;
- assert.equal(h.mutations.length, 1);
- }
- } finally {
- h.c.stop();
- }
- assert.equal(h.timers.size, 0);
- },
- );
- }
-
- for (const providerDropdown of [false, true]) {
- for (const segments of [
- ['use', 'Foo', 'as', 'my', 'voi', 'ce provider'],
- ['use Claude'],
- ['switch to Gemini'],
- ]) {
- for (const tool of [
- { name: 'control_radio', args: { action: 'stop' } },
- { name: 'control_radio', args: { action: 'disable' } },
- {
- name: 'set_layer_visibility',
- args: { layerId: 'radio', enabled: false },
- },
- ]) {
- test(
- `C3 Radio refusal: chooser=${providerDropdown} ${JSON.stringify(segments)} ${tool.name}/${tool.args.action || 'off'} leaves no setter preparation`,
- {
- skip: 'replace-native: H35, H36, H37, H38, H39, H40, H41, H42, H43, H44, H45, H46, H47, H48, H49, H50, H51, H52; equivalent native regression tests replace caption ownership assumptions',
- },
- async () => {
- const mutations = [];
- const viewer = {
- clock: { onTick: { addEventListener: () => () => {} } },
- camera: { moveEnd: { addEventListener() {} } },
- scene: {
- canvas: { addEventListener() {}, removeEventListener() {} },
- },
- };
- const runner = createGevActionRunner({
- viewer,
- styleManager: {
- setStyle: (...args) => mutations.push(['style', ...args]),
- },
- dataManager: {
- isEnabled: () => true,
- setEnabled: (...args) => mutations.push(['visibility', ...args]),
- },
- radioLayer: {
- stopPlayback: (...args) => mutations.push(['stop', ...args]),
- },
- });
- let runnerCalls = 0;
- const h = harness({
- providerDropdown: () => providerDropdown,
- runAction: (...args) => {
- runnerCalls++;
- return runner(...args);
- },
- });
- const trace = {
- reservations: 0,
- registered: 0,
- toolStarted: 0,
- pauses: 0,
- };
- const playbackReady = deferred();
- let preflight;
- try {
- const pause = h.c.radio.pauseRadioForVoice.bind(h.c.radio);
- h.c.radio.pauseRadioForVoice = (...args) => {
- trace.pauses++;
- return pause(...args);
- };
- await h.c.start();
- const ws = h.sockets[0];
- ws.message({ voiceActivity: { type: 'ACTIVITY_START' } });
- ws.message({ voiceActivity: { type: 'ACTIVITY_END' } });
- for (const text of segments)
- ws.message({ serverContent: { inputTranscription: { text } } });
- assert.equal(h.c.intentAmbiguous, false);
- assert.equal(
- trace.pauses,
- 1,
- 'normal voice startup already paused Radio',
- );
- h.c.radio.radioLayer.playForVoice = () => playbackReady.promise;
- const prepared = radioPlaybackResult();
- h.c.radio.setPendingPlayback(prepared);
- preflight = h.c.radio.startPendingRadioHandoff();
- const handoffEpoch = h.c.radio.radioHandoffEpoch;
- const attemptId = h.c.radio.radioHandoffAttemptId;
- assert.equal(h.c.radio.radioHandoffInFlight, true);
- const reserve = h.c.radio.reserveRadioToolHandoff.bind(h.c.radio);
- h.c.radio.reserveRadioToolHandoff = (...args) => {
- trace.reservations++;
- return reserve(...args);
- };
- const register = h.c.radio.registerTool.bind(h.c.radio);
- h.c.radio.registerTool = (...args) => {
- trace.registered++;
- return register(...args);
- };
- const started = h.c.narration.toolStarted.bind(h.c.narration);
- h.c.narration.toolStarted = (...args) => {
- trace.toolStarted++;
- return started(...args);
- };
- requestTool(ws, 'refused-radio', tool.name, tool.args);
- await h.c.toolQueue;
- const response =
- ws.sent.at(-1).toolResponse.functionResponses[0].response;
- console.log(
- 'C3 Radio trace',
- JSON.stringify({
- providerDropdown,
- segments,
- tool,
- trace,
- runnerCalls,
- reservationsLeft: h.c.radio.radioToolHandoffReservations.size,
- activeToolsLeft: h.c.radio.activeRadioToolControllers.size,
- response,
- }),
- );
- assert.equal(response.providerRequestBlocked, true);
- assert.equal(response.providerDropdown, providerDropdown);
- assert.match(
- response.say,
- providerDropdown ? /dropdown/ : /switch voice providers directly/,
- );
- assert.deepEqual(trace, {
- reservations: 0,
- registered: 0,
- toolStarted: 0,
- pauses: 1,
- });
- assert.equal(h.c.radio.radioToolHandoffReservations.size, 0);
- assert.equal(h.c.radio.activeRadioToolControllers.size, 0);
- assert.equal(h.c.pendingTools, 0);
- assert.equal(h.c.tools.size, 0);
- assert.equal(runnerCalls, 0);
- assert.deepEqual(mutations, []);
- assert.equal(h.c.radio.pendingRadioPlaybackResult, null);
- assert.equal(h.c.radio.radioHandoffInFlight, true);
- assert.equal(h.c.radio.radioHandoffInFlightResult, prepared);
- assert.equal(h.c.radio.radioHandoffEpoch, handoffEpoch);
- assert.equal(h.c.radio.radioHandoffAttemptId, attemptId);
- assert.equal(
- h.state.stopped,
- 0,
- 'a refused setter must not freeze the existing preflight',
- );
- assert.equal(h.c.stopAfterReply, false);
- h.c.sendTextCommand('Set visual style to night vision');
- ws.message({
- serverContent: { interrupted: true, turnComplete: true },
- });
- requestTool(ws, 'next-ordinary-style', 'set_visual_style', {
- style: 'night vision',
- });
- await h.c.toolQueue;
- assert.equal(runnerCalls, 1);
- assert.equal(mutations.length, 1);
- assert.equal(h.c.pendingTools, 0);
- } finally {
- h.c.stop();
- playbackReady.resolve(false);
- await preflight;
- runner.dispose();
- }
- assert.equal(h.timers.size, 0);
- },
- );
- }
- }
- }
-
- for (const phase of ['initializing', 'committed']) {
- test(
- `C3 joined policy: a late fused provider request during ${phase} preserves actual manager commit truth`,
- {
- skip: 'replace-native: H53, H54; equivalent native regression tests replace caption ownership assumptions',
- },
- async () => {
- const viewer = {
- clock: { onTick: { addEventListener: () => () => {} } },
- camera: { moveEnd: { addEventListener() {} } },
- scene: { canvas: { addEventListener() {}, removeEventListener() {} } },
- };
- const manager = new DataLayerManager(viewer);
- const initEntered = deferred();
- const initReleased = deferred();
- const committed = deferred();
- const settlement = deferred();
- const calls = [];
- const events = [];
- manager.register({
- id: 'rocket-launches',
- name: 'Missions',
- updateInterval: -1,
- async init() {
- calls.push('init');
- initEntered.resolve();
- if (phase === 'initializing') await initReleased.promise;
- },
- async enable() {
- calls.push('enable');
- },
- async disable() {
- calls.push('disable');
- },
- async update() {},
- getStats: () => ({ count: 0 }),
- });
- const unsubscribe = manager.subscribe((event) => {
- events.push(event);
- if (event.type === 'visibility' && event.enabled) committed.resolve();
- });
- const runner = createGevActionRunner({
- viewer,
- dataManager: manager,
- styleManager: {
- _waitForContextLayerSettlement: () => settlement.promise,
- },
- });
- let options;
- let h;
- const sharedEvents = [];
- const session = createVoiceSession({
- runner: (name, args, context) => {
- options = context;
- return runner(name, args, context);
- },
- createAdapter: (shared) => {
- h = harness({ ...shared, dataManager: manager });
- return {
- start: (settings) => h.c.start(settings),
- stop: (settings) => h.c.stop(settings),
- sendText: (text) => h.c.sendTextCommand(text),
- sendMapEvent: (event) => h.c.notifyMapEvent(event),
- };
- },
- });
- session.subscribe((event) => sharedEvents.push(event));
- try {
- await session.start();
- const ws = h.sockets[0];
- ws.message({ voiceActivity: { type: 'ACTIVITY_START' } });
- ws.message({ voiceActivity: { type: 'ACTIVITY_END' } });
- ws.message({
- serverContent: { inputTranscription: { text: 'use foo as my voi' } },
- });
- const response = sharedEvents.findLast(
- (event) => event.type === 'response-start',
- );
- requestTool(ws, 'inflight-layer', 'set_layer_visibility', {
- layerId: 'rocket-launches',
- enabled: true,
- });
- await initEntered.promise;
- if (phase === 'committed') await committed.promise;
- assert.equal(options.signal.aborted, false);
- ws.message({
- serverContent: { inputTranscription: { text: 'ce provider' } },
- });
- assert.equal(
- readVoiceUserTurnText(response.userTurn),
- 'use foo as my voi ce provider',
- );
- const policySignalAborted = options.signal.aborted;
- initReleased.resolve();
- settlement.resolve();
- await h.c.toolQueue;
- const result =
- ws.sent.at(-1).toolResponse.functionResponses[0].response;
- console.log(
- 'C3 late joined trace',
- JSON.stringify({
- phase,
- policySignalAborted,
- enabled: manager.isEnabled('rocket-launches'),
- calls,
- result,
- }),
- );
- assert.equal(
- policySignalAborted,
- true,
- 'joined restrictions must revoke the cooperative runner signal',
- );
- if (phase === 'initializing') {
- assert.equal(result.providerRequestBlocked, true);
- assert.equal(result.ok, false);
- assert.equal(manager.isEnabled('rocket-launches'), false);
- assert.equal(calls.includes('enable'), false);
- assert.equal(
- events.some(
- (event) => event.type === 'visibility' && event.enabled,
- ),
- false,
- );
- } else {
- assert.equal(result.ok, true);
- assert.equal(result.providerRequestBlocked, undefined);
- assert.equal(result.enabled, true);
- assert.equal(manager.isEnabled('rocket-launches'), true);
- }
- requestTool(ws, 'denied-sibling', 'set_layer_visibility', {
- layerId: 'rocket-launches',
- enabled: false,
- });
- await h.c.toolQueue;
- assert.equal(
- ws.sent.at(-1).toolResponse.functionResponses[0].response
- .providerRequestBlocked,
- true,
- );
- assert.equal(
- manager.isEnabled('rocket-launches'),
- phase === 'committed',
- );
- h.c.sendTextCommand('Show missions');
- ws.message({
- serverContent: { interrupted: true, turnComplete: true },
- });
- requestTool(ws, 'fresh-missions', 'set_layer_visibility', {
- layerId: 'rocket-launches',
- enabled: true,
- });
- await h.c.toolQueue;
- assert.equal(
- ws.sent.at(-1).toolResponse.functionResponses[0].response.ok,
- true,
- );
- assert.equal(manager.isEnabled('rocket-launches'), true);
- assert.equal(h.c.tools.size, 0);
- assert.equal(h.c.pendingTools, 0);
- } finally {
- initReleased.resolve();
- settlement.resolve();
- session.destroy();
- runner.dispose();
- unsubscribe();
- await manager.setEnabled('rocket-launches', false);
- }
- assert.equal(h.timers.size, 0);
- },
- );
- }
-
- for (const providerDropdown of [false, true]) {
- for (const phase of ['prepared', 'preflight', 'settling']) {
- test(
- `C3 deferred Radio policy: late same-token fused request cancels ${phase} speaker transfer chooser=${providerDropdown} without erasing preparation`,
- {
- skip: 'replace-native: H55, H56, H57, H58, H59, H60; equivalent native regression tests replace caption ownership assumptions',
- },
- async () => {
- const viewer = {
- clock: { onTick: { addEventListener: () => () => {} } },
- camera: { moveEnd: { addEventListener() {} } },
- scene: {
- canvas: { addEventListener() {}, removeEventListener() {} },
- },
- };
- const manager = new DataLayerManager(viewer);
- const prepared = deferred();
- const settleResult = deferred();
- const playbackReady = deferred();
- let playCalls = 0;
- let stopCalls = 0;
- let selections = 0;
- const state = {
- stationCount: 2,
- selected: null,
- audioState: 'stopped',
- voiceDucked: false,
- };
- const radio = {
- async init() {},
- async enable() {},
- async disable() {},
- async update() {},
- getStats: () => ({ count: 2 }),
- getUIState: () => ({ ...state }),
- setVoiceDucked(value) {
- state.voiceDucked = value;
- },
- pause() {
- state.audioState = 'paused';
- },
- subscribePlaybackControls() {
- return () => {};
- },
- selectRequestedStation(_criteria, options) {
- assert.equal(options.autoplay, false);
- selections++;
- state.selected = { id: 'station-1', name: 'Station One' };
- return state.selected;
- },
- playForVoice() {
- playCalls++;
- return playbackReady.promise;
- },
- stopPlayback() {
- stopCalls++;
- state.audioState = 'stopped';
- },
- };
- manager.register({
- id: 'radio',
- name: 'Radio',
- updateInterval: -1,
- ...radio,
- });
- const runner = createGevActionRunner({ viewer, dataManager: manager });
- let h;
- let preflight;
- const session = createVoiceSession({
- providerDropdown: () => providerDropdown,
- runner: async (...args) => {
- const result = await runner(...args);
- prepared.resolve(result);
- if (phase === 'settling') await settleResult.promise;
- return result;
- },
- createAdapter: (shared) => {
- h = harness({ ...shared, dataManager: manager, radioLayer: radio });
- return {
- start: (settings) => h.c.start(settings),
- stop: (settings) => h.c.stop(settings),
- sendText: (text) => h.c.sendTextCommand(text),
- sendMapEvent: (event) => h.c.notifyMapEvent(event),
- };
- },
- });
- try {
- await session.start();
- const ws = h.sockets[0];
- ws.message({ voiceActivity: { type: 'ACTIVITY_START' } });
- ws.message({ voiceActivity: { type: 'ACTIVITY_END' } });
- ws.message({
- serverContent: {
- inputTranscription: { text: 'use foo as my voi' },
- },
- });
- requestTool(ws, 'prepared-radio-policy', 'control_radio', {
- action: 'select',
- stationQuery: 'Station One',
- });
- const actual = await prepared.promise;
- assert.equal(actual.ok, true);
- assert.equal(actual.radioPlaybackRequested, true);
- assert.equal(actual.stationId, 'station-1');
- assert.equal(manager.isEnabled('radio'), true);
- if (phase !== 'settling') {
- await h.c.toolQueue;
- assert.ok(h.c.radio.pendingRadioPlaybackResult);
- }
- if (phase === 'preflight') {
- preflight = h.c.radio.startPendingRadioHandoff();
- assert.equal(h.c.radio.radioHandoffInFlight, true);
- assert.equal(playCalls, 1);
- }
- ws.message({
- serverContent: { inputTranscription: { text: 'ce provider' } },
- });
- settleResult.resolve();
- await h.c.toolQueue;
- const result = ws.sent.findLast((frame) => frame.toolResponse)
- ?.toolResponse.functionResponses[0].response;
- console.log(
- 'C3 deferred Radio trace',
- JSON.stringify({
- phase,
- playCalls,
- stopCalls,
- pending: Boolean(h.c.radio.pendingRadioPlaybackResult),
- inFlight: h.c.radio.radioHandoffInFlight,
- enabled: manager.isEnabled('radio'),
- stationId: state.selected?.id,
- result,
- }),
- );
- const pendingAfterRestriction = h.c.radio.pendingRadioPlaybackResult;
- const inFlightAfterRestriction = h.c.radio.radioHandoffInFlight;
- const stopsAfterRestriction = stopCalls;
- drainRadioReply(h);
- playbackReady.resolve(true);
- await preflight;
- await tick();
- console.log(
- 'C3 deferred Radio drain',
- JSON.stringify({
- phase,
- playCalls,
- stopCalls,
- active: h.c.isActive(),
- }),
- );
- assert.equal(
- pendingAfterRestriction,
- null,
- 'provider request cancels only its deferred playback',
- );
- assert.equal(inFlightAfterRestriction, false);
- assert.equal(
- result.ok,
- true,
- 'station selection and layer initialization really completed',
- );
- assert.equal(result.stationId, 'station-1');
- if (phase === 'settling') {
- assert.equal(result.radioPlaybackRequested, false);
- assert.equal(result.radioPlaybackSuppressed, true);
- assert.equal(result.radioPlaybackPolicyBlocked, true);
- assert.equal(result.providerDropdown, providerDropdown);
- assert.match(
- result.responseGuidance,
- providerDropdown ? /dropdown/ : /managed by this app/,
- );
- assert.match(result.responseGuidance, /provider/);
- assert.doesNotMatch(
- result.responseGuidance,
- /stopped as requested/,
- );
- assert.notEqual(result.changed, false);
- }
- assert.equal(manager.isEnabled('radio'), true);
- assert.equal(selections, 1);
- assert.equal(stopsAfterRestriction, phase === 'preflight' ? 1 : 0);
- assert.equal(
- playCalls,
- phase === 'preflight' ? 1 : 0,
- 'confirmation/drain cannot revive policy-cancelled playback',
- );
- assert.equal(
- h.c.isActive(),
- true,
- 'cancelled handoff cannot end voice after late readiness',
- );
- assert.equal(h.c.radio.radioHandoffInFlight, false);
- assert.equal(h.c.pendingTools, 0);
- assert.equal(h.c.tools.size, 0);
- assert.equal(session.sendText('Play radio'), true);
- requestTool(ws, 'fresh-radio-policy', 'control_radio', {
- action: 'play',
- });
- await h.c.toolQueue;
- assert.ok(
- h.c.radio.pendingRadioPlaybackResult,
- 'a new authentic turn may prepare Radio again',
- );
- drainRadioReply(h);
- await tick();
- assert.equal(playCalls, phase === 'preflight' ? 2 : 1);
- assert.equal(
- h.c.isActive(),
- false,
- 'only the fresh authorized Radio handoff ends voice',
- );
- } finally {
- settleResult.resolve();
- playbackReady.resolve(false);
- session.destroy();
- await preflight;
- runner.dispose();
- await manager.setEnabled('radio', false);
- }
- assert.equal(h.timers.size, 0);
- },
- );
- }
- }
diff --cc src/voice/gevRealtime.js
index 4c15f9879,58efacad3..8364a5723
--- a/src/voice/gevRealtime.js
+++ b/src/voice/gevRealtime.js
@@@ -80,11 -61,10 +61,8 @@@ export function initGevVoiceCommands(op
});
deixis.imageFrame = () => commands.retainedImageFrame?.() || null;
deixis.onPointerUsed = () => commands.announcePointer?.();
- commands.session?.signal?.addEventListener(
- 'abort',
- () => pointer?.destroy(),
- { once: true },
- );
+ const lifetime = commands.signal ?? commands.session?.signal;
++ lifetime?.addEventListener('abort', () => pointer?.destroy(), { once: true });
+ if (lifetime?.aborted) pointer?.destroy();
- else
- lifetime?.addEventListener('abort', () => pointer?.destroy(), {
- once: true,
- });
return commands;
}
diff --cc src/voice/pointerContext.js
index 9dac543c7,d54c0bd64..19ea6771b
--- a/src/voice/pointerContext.js
+++ b/src/voice/pointerContext.js
@@@ -330,17 -330,10 +330,17 @@@ export function createPointerTracker(
* (open mic only when it moved recently: `recentMs`). The result becomes
* the turn's referent (null when stale).
*/
- beginTurn(at, { recentMs = POINTER_FRESH_MS } = {}) {
+ beginTurn(at, { recentMs = POINTER_FRESH_MS, capturedSnapshot } = {}) {
++ // Delayed admitted audio keeps its capture's pointer without replacing a
++ // newer physical hold. Undefined preserves existing caller behavior.
++ if (capturedSnapshot !== undefined) {
++ const snapshot = destroyed ? { fresh: false, at } : capturedSnapshot;
++ active = snapshot?.fresh ? snapshot : null;
++ return snapshot;
++ }
const reuse =
at !== 'text' && held && now() - held.heldAt <= POINTER_HOLD_MS;
- // A delayed worklet admission may arrive after Space release. The
- // provider owns this previously captured, local gesture snapshot.
- const snapshot =
- capturedSnapshot !== undefined
- ? capturedSnapshot
- : reuse
- ? held.snapshot
- : capture(at, { recentMs });
+ const snapshot = reuse ? held.snapshot : capture(at, { recentMs });
if (!reuse && at !== 'text') held = null;
active = snapshot?.fresh ? snapshot : null;
return snapshot;
diff --cc src/voice/pointerContext.test.mjs
index 3ee9012d4,1d4f2e1fe..6c40cc0e9
--- a/src/voice/pointerContext.test.mjs
+++ b/src/voice/pointerContext.test.mjs
@@@ -151,6 -151,6 +151,51 @@@ test('destroy removes listeners and ign
assert.equal(h.tracker.capture('keydown').fresh, false);
});
++test('delayed speech uses its released capture without replacing a newer physical hold', () => {
++ const h = harness();
++ h.move(700, 250);
++ const capturedA = h.tracker.hold();
++ h.tracker.releaseHold();
++ h.move(200, 100);
++ h.tracker.beginTurn('speech_start', { capturedSnapshot: capturedA });
++ assert.equal(h.tracker.activeSnapshot(), capturedA);
++ const heldB = h.tracker.hold();
++ h.tracker.beginTurn('speech_start', { capturedSnapshot: capturedA });
++ assert.equal(h.tracker.activeSnapshot(), capturedA);
++ assert.equal(h.tracker.isHeld(), true);
++ assert.equal(h.tracker.beginTurn('speech_start'), heldB);
++ h.tracker.destroy();
++});
++
++test('explicit stale captures clear the referent while a silent hold leaves it alone', () => {
++ const h = harness();
++ h.move(700, 250);
++ const current = h.tracker.beginTurn('text');
++ h.move(200, 100);
++ h.tracker.hold();
++ h.tracker.releaseHold();
++ assert.equal(h.tracker.activeSnapshot(), current);
++ for (const capturedSnapshot of [null, { fresh: false, at: 'keydown' }]) {
++ h.tracker.beginTurn('text');
++ h.tracker.beginTurn('speech_start', { capturedSnapshot });
++ assert.equal(h.tracker.activeSnapshot(), null);
++ }
++ h.tracker.destroy();
++});
++
++test('a capture arriving after destruction cannot restore an active referent', () => {
++ const h = harness();
++ h.move(700, 250);
++ const capturedSnapshot = h.tracker.hold();
++ assert.equal(capturedSnapshot.fresh, true);
++ h.tracker.destroy();
++ const result = h.tracker.beginTurn('speech_start', { capturedSnapshot });
++ assert.equal(result.fresh, false);
++ assert.equal(h.tracker.activeSnapshot(), null);
++ assert.equal(h.tracker.isHeld(), false);
++ assert.equal(h.tracker.beginTurn('speech_start').fresh, false);
++});
++
test('format: the model item is compact inert JSON; labels are bounded data', () => {
const snapshot = buildPointerSnapshot({
at: 'speech_start',
diff --cc src/voice/providerCapabilities.js
index 563a5028a,000000000..128785cc8
mode 100644,000000..100644
--- a/src/voice/providerCapabilities.js
+++ b/src/voice/providerCapabilities.js
@@@ -1,33 -1,0 +1,21 @@@
- export const VOICE_PROVIDER_GUIDANCE =
- 'I can’t switch voice providers directly. Hover over the Voice panel and use the provider dropdown.';
- export const HOST_VOICE_PROVIDER_GUIDANCE =
- 'I can’t switch voice providers directly. Provider selection is managed by this app.';
-
- /** Host construction decides which controls exist; tool text cannot add one. */
- export function voiceProviderGuidance({ providerDropdown = false } = {}) {
- return providerDropdown === true
- ? VOICE_PROVIDER_GUIDANCE
- : HOST_VOICE_PROVIDER_GUIDANCE;
- }
-
+export const VOICE_PROVIDERS = Object.freeze({
- openai: Object.freeze({ label: 'OpenAI' }),
- gemini: Object.freeze({ label: 'Gemini' }),
++ openai: Object.freeze({ label: 'OpenAI' }), // i18n-ignore: provider product name
++ gemini: Object.freeze({ label: 'Gemini' }), // i18n-ignore: provider product name
+});
+
+/** Optional providers require an explicit host opt-in and an available factory. */
+export function supportedVoiceProviders(
+ requested = ['openai'],
+ factories = {},
+) {
+ if (!Array.isArray(requested))
+ throw new TypeError('supportedProviders must be an array');
+ const selected = [...new Set(requested)].filter(
+ (name) =>
+ Object.hasOwn(VOICE_PROVIDERS, name) &&
+ typeof factories[name] === 'function',
+ );
+ if (!selected.length)
+ throw new Error('No supported voice provider is configured');
+ return Object.freeze(selected);
+}
diff --cc src/voice/providerCommands.js
index 7e56d5136,000000000..86855e3bc
mode 100644,000000..100644
--- a/src/voice/providerCommands.js
+++ b/src/voice/providerCommands.js
@@@ -1,154 -1,0 +1,161 @@@
+import { supportedVoiceProviders } from './providerCapabilities.js';
+
+const STORAGE_KEY = 'gev.voice.provider';
+
+export function readVoiceProvider(storage, supported = ['openai', 'gemini']) {
+ let saved;
+ try {
+ saved = (storage ?? globalThis.localStorage)?.getItem(STORAGE_KEY);
+ } catch {
+ /* Storage is optional. */
+ }
+ return supported.includes(saved)
+ ? saved
+ : supported.includes('openai')
+ ? 'openai'
+ : supported[0];
+}
+
+/** Keep one public controller identity while replacing each provider's lifetime. */
+export function createProviderCommands(options, { bind, factories, storage }) {
+ const supportedProviders = supportedVoiceProviders(
+ options.supportedProviders ?? Object.keys(factories),
+ factories,
+ );
+ window.__gevVoiceCommands?.stop?.({ removeUi: true });
+ let provider = readVoiceProvider(storage, supportedProviders);
+ let current;
+ let disposed = false;
+ const lifetime = new AbortController();
+ let mountGeneration = 0;
+ let voiceEnabled = false;
+ const stored = () => {
+ try {
+ return storage ?? globalThis.localStorage;
+ } catch {
+ return null;
+ }
+ };
+ const stop = (settings = {}) => {
+ if (disposed) return;
+ voiceEnabled = false;
+ if (settings.removeUi) {
+ disposed = true;
+ options.signal?.removeEventListener('abort', destroy);
+ }
+ try {
+ current?.session.stop(settings);
+ } finally {
+ if (settings.removeUi) {
+ lifetime.abort();
+ options.runner.dispose?.();
+ }
+ }
+ };
+ const destroy = () => stop({ removeUi: true });
+ const selectProvider = (next) => {
+ if (disposed || !supportedProviders.includes(next) || next === provider)
+ return false;
+ const resume = voiceEnabled && current.session.isActive();
+ // Carry the input mode, never a held key, microphone or conversation.
+ const pushToTalk = Boolean(
+ current.session.adapter.getStartOptions?.().pushToTalk,
+ );
++ const generation = ++mountGeneration;
++ voiceEnabled = false;
+ current.session.destroy();
++ // Disposal suppresses the retired adapter's idle event. Clear the shared
++ // conversation explicitly before the new mount can use these owners.
++ if (disposed || generation !== mountGeneration) return false;
++ options.pointer?.clear();
++ options.referents?.clear();
++ options.runner.resetConversation?.();
++ if (disposed || generation !== mountGeneration) return false;
+ provider = next;
+ try {
+ stored()?.setItem(STORAGE_KEY, provider);
+ } catch {
+ /* Storage is optional. */
+ }
+ mount();
- if (resume && !disposed) void current.session.start({ pushToTalk });
++ if (resume && !disposed && provider === next)
++ void current.session.start({ pushToTalk });
+ globalThis.document?.getElementById('gev-voice-provider')?.focus();
+ return true;
+ };
+
+ const handleSessionEvent = (event) => {
+ if (event?.type === 'state' && event.state === 'connecting')
+ voiceEnabled = true;
- if (
- event?.type === 'stop' ||
- (event?.type === 'state' && ['idle', 'error'].includes(event.state))
- ) {
++ if (event?.type === 'state' && ['idle', 'error'].includes(event.state)) {
+ voiceEnabled = false;
+ }
+ // The host still observes the mounted provider's neutral session events.
+ options.onSessionEvent?.(event);
+ };
+
+ const sendTextCommand = (text) => {
+ if (disposed) return false;
+ return current.session.sendText(text);
+ };
+
+ const api = {
+ // The shared action surface is independent of an active voice connection.
+ runner: options.runner,
+ supportedProviders,
+ signal: lifetime.signal,
+ get provider() {
+ return provider;
+ },
+ get session() {
+ return current?.session;
+ },
+ get status() {
+ return current?.status ?? current?.session.state ?? 'idle';
+ },
+ get state() {
+ return current?.session.state ?? 'idle';
+ },
+ get disposed() {
+ return disposed;
+ },
+ start: (settings) => !disposed && current.session.start(settings),
+ stop,
+ destroy,
+ isActive: () => !disposed && current.session.isActive(),
+ sendTextCommand,
+ sendText: sendTextCommand,
+ notifyMapEvent: (event) => !disposed && current.session.sendMapEvent(event),
+ };
+ // Existing diagnostic and controller accessors continue to reflect the active provider.
+ const facade = new Proxy(api, {
+ get(target, name, receiver) {
+ if (Reflect.has(target, name)) return Reflect.get(target, name, receiver);
+ const value = current?.[name];
+ return typeof value === 'function' ? value.bind(current) : value;
+ },
+ });
+ function mount() {
+ voiceEnabled = false;
+ const generation = ++mountGeneration;
+ current = bind({
+ ...options,
+ signal: lifetime.signal,
+ resetExisting: false,
+ disposeRunner: false,
+ provider,
+ supportedProviders,
+ onProviderChange: selectProvider,
+ onSessionEvent: (event) => {
+ if (!disposed && generation === mountGeneration)
+ handleSessionEvent(event);
+ },
+ createSession: factories[provider],
+ });
+ window.__gevVoiceCommands = facade;
+ }
+ mount();
+ options.signal?.addEventListener('abort', destroy, { once: true });
+ if (options.signal?.aborted) destroy();
+ return facade;
+}
diff --cc src/voice/providerCommands.test.mjs
index fcffb57a6,000000000..74d99699b
mode 100644,000000..100644
--- a/src/voice/providerCommands.test.mjs
+++ b/src/voice/providerCommands.test.mjs
@@@ -1,817 -1,0 +1,888 @@@
++// Imports intentionally target the candidate, never the immutable reference.
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {
+ createProviderCommands,
+ readVoiceProvider,
+} from './providerCommands.js';
- import { createVoiceCommands as bind } from './sessionCommands.js';
++import { createVoiceCommands as bindVoiceCommands } from './sessionCommands.js';
++import { createVoiceCommands as createCommands } from './commands.js';
++import { createGevActionRunner } from './gevActions.js';
++import { createPointerTracker } from './pointerContext.js';
++import { createReferentRegistry } from './referents.js';
++import { describeUnsavedWork, t as translate } from '../i18n/index.js';
+
- function element(properties = {}) {
- const target = new EventTarget();
- Object.assign(target, properties);
- target.attributes = {};
- target.setAttribute = (name, value) => {
- target.attributes[name] = String(value);
- };
- target.getAttribute = (name) => target.attributes[name] ?? null;
- target.focus = () => {
- target.focused = true;
- };
- return target;
++const PROVIDER_KEY = 'gev.voice.provider';
++const settle = () => new Promise((resolve) => setImmediate(resolve));
++
++function deferred() {
++ let resolve;
++ let reject;
++ const promise = new Promise((yes, no) => {
++ resolve = yes;
++ reject = no;
++ });
++ return { promise, resolve, reject };
+}
+
- function control() {
- const button = element();
- button.setAttribute = () => {};
- const select = element();
- select.options = [];
- select.ownerDocument = { createElement: () => ({}) };
- select.replaceChildren = (...options) => {
- select.options = options;
- };
- const view = {
- root: {
- dataset: {},
- remove() {
- this.removed = true;
- },
- },
- button,
- providerSelect: select,
- providerField: {
- remove() {
- this.removed = true;
++// Listener counts observe the actual binder's registrations/removals.
++class Element extends EventTarget {
++ listeners = new Map();
++ attributes = new Map();
++ addEventListener(type, handler, options) {
++ if (!this.listeners.has(type)) this.listeners.set(type, new Set());
++ this.listeners.get(type).add(handler);
++ super.addEventListener(type, handler, options);
++ }
++ removeEventListener(type, handler, options) {
++ this.listeners.get(type)?.delete(handler);
++ super.removeEventListener(type, handler, options);
++ }
++ listenerCount(type) {
++ return this.listeners.get(type)?.size || 0;
++ }
++ setAttribute(name, value) {
++ this.attributes.set(name, String(value));
++ }
++ focus() {
++ this.focusCount = (this.focusCount || 0) + 1;
++ }
++}
++
++for (const custom of [false, true]) {
++ test(`public composition preserves the ${custom ? 'custom adapter' : 'default OpenAI adapter'} path`, async (t) => {
++ const prior = globalThis.window;
++ globalThis.window = new EventTarget();
++ let controls;
++ t.after(() => {
++ controls?.session.destroy();
++ globalThis.window = prior;
++ });
++ const ui = {
++ root: { dataset: {}, remove() {} },
++ button: new Element(),
++ status: {},
++ detail: {},
++ providerField: {},
++ };
++ let defaultCreated = 0;
++ let customCreated = 0;
++ const options = {
++ runner: async () => ({ ok: true }),
++ createControl: () => ui,
++ createController: ({ onSessionEvent }) => {
++ defaultCreated++;
++ return {
++ ui,
++ start({ pushToTalk }) {
++ this.pushToTalkMode = pushToTalk;
++ onSessionEvent({ type: 'state', state: 'listening' });
++ },
++ stop() {},
++ syncCostUi() {},
++ bindPushToTalkShortcut() {},
++ sendTextCommand: (text) => `default:${text}`,
++ };
+ },
- },
- status: {},
- detail: {},
- tierButton: {},
- costValue: {},
- helpDetail: {},
- };
- return view;
++ };
++ if (custom) {
++ options.supportedProviders = ['gemini'];
++ options.createSession = ({ emit }) => {
++ customCreated++;
++ return {
++ capabilities: { pushToTalk: false },
++ start() {
++ emit({ type: 'state', state: 'listening' });
++ },
++ stop() {},
++ sendText: (text) => `custom:${text}`,
++ sendMapEvent: () => true,
++ };
++ };
++ }
++ controls = createCommands(options);
++ await controls.session.start({ pushToTalk: true });
++ assert.equal(defaultCreated, custom ? 0 : 1);
++ assert.equal(customCreated, custom ? 1 : 0);
++ assert.equal(
++ controls.session.sendText('test'),
++ `${custom ? 'custom' : 'default'}:test`,
++ );
++ assert.equal(ui.providerField.hidden, true);
++ assert.equal(ui.root.dataset.providerChoice, 'false');
++ if (!custom)
++ assert.deepEqual(controls.session.adapter.getStartOptions(), {
++ pushToTalk: true,
++ });
++ });
+}
- function setup(
++
++/** Real facade -> real binder -> real common session and real action runner.
++ * Adapters and passive UI/viewer boundaries are fixtures. Wrappers only count
++ * calls to real pointer/referent/conversation cleanup; they do not replace it.
++ */
++function compositionFixture(
+ t,
+ {
- value = null,
- runner = async () => ({ ok: true }),
- deferredStart,
- startGate,
- startOptionsAvailable = true,
- storedValues = new Map(),
+ supportedProviders = ['openai', 'gemini'],
+ factoryProviders = ['openai', 'gemini'],
++ savedProvider = null,
++ storageDenied = false,
++ gateStarts = () => false,
++ onSessionEvent = () => {},
+ } = {},
+) {
- const prior = globalThis.window;
- const priorDocument = globalThis.document;
- globalThis.window = new EventTarget();
++ const original = new Map(
++ ['window', 'document'].map((key) => [
++ key,
++ Object.getOwnPropertyDescriptor(globalThis, key),
++ ]),
++ );
+ const lifetime = new AbortController();
- let controls;
- t.after(() => {
- controls?.destroy();
- globalThis.window = prior;
- globalThis.document = priorDocument;
- });
- let clock = 1000;
- const timers = new Map();
- let timerSequence = 0;
- const hooks = {};
- const starts = [];
- const stops = [];
- const claims = [];
- const releases = [];
- const localOutputBegins = [];
- const localOutputEnds = [];
- const localOutputLifecycle = [];
+ const views = [];
++ const instances = [];
++ const mounts = [];
++ const events = [];
++ const order = [];
++ const annotations = new Set();
++ const storageWrites = [];
++ const counters = { pointer: 0, referents: 0, conversation: 0, dispose: 0 };
++ const state = { height: 1000, zooms: 0, renders: 0 };
++ let facade;
++ let pointer;
++ globalThis.window = new EventTarget();
+ globalThis.document = {
+ getElementById: (id) =>
+ id === 'gev-voice-provider' ? views.at(-1)?.providerSelect : null,
+ };
- const sourceEvents = [];
- const sessionEvents = [];
- const sentTexts = [];
- const mountedControls = [];
- const instances = [];
- const values = storedValues;
- const storageWrites = [];
- if (value != null) values.set('gev.voice.provider', value);
- const storage = {
- getItem: (key) => {
- return values.get(key) ?? null;
++ t.after(async () => {
++ try {
++ facade?.destroy();
++ pointer?.destroy();
++ for (const instance of instances)
++ for (const gate of instance.gates) gate.resolve();
++ await Promise.allSettled(instances.flatMap((instance) => instance.jobs));
++ } finally {
++ for (const [key, descriptor] of original) {
++ if (descriptor) Object.defineProperty(globalThis, key, descriptor);
++ else delete globalThis[key];
++ }
++ }
++ });
++
++ const canvas = new EventTarget();
++ Object.assign(canvas, { clientWidth: 800, clientHeight: 600 });
++ const position = { x: 6379137, y: 0, z: 0 };
++ const viewer = {
++ clock: { onTick: { addEventListener: () => () => {} } },
++ camera: {
++ positionWC: position,
++ positionCartographic: { height: state.height },
++ moveEnd: { addEventListener() {} },
++ cancelFlight() {},
++ zoomIn(metres) {
++ position.x -= metres;
++ state.height -= metres;
++ this.positionCartographic.height = state.height;
++ state.zooms++;
++ },
++ zoomOut(metres) {
++ position.x += metres;
++ state.height += metres;
++ this.positionCartographic.height = state.height;
++ state.zooms++;
++ },
+ },
- setItem: (key, next) => {
- storageWrites.push([key, next]);
- values.set(key, next);
++ scene: {
++ canvas,
++ requestRender() {
++ state.renders++;
++ },
+ },
+ };
++ const dataManager = { layers: new Map() };
++ pointer = createPointerTracker({ element: null, now: () => 1000 });
++ const referents = createReferentRegistry();
++ const runner = createGevActionRunner({
++ viewer,
++ dataManager,
++ styleManager: {},
++ deixis: { pointer, referents },
++ });
++ for (const [object, method, counter] of [
++ [pointer, 'clear', 'pointer'],
++ [referents, 'clear', 'referents'],
++ [runner, 'resetConversation', 'conversation'],
++ [runner, 'dispose', 'dispose'],
++ ]) {
++ const originalMethod = object[method];
++ object[method] = (...args) => {
++ counters[counter]++;
++ order.push(counter);
++ return originalMethod.apply(object, args);
++ };
++ }
++
+ const factories = Object.fromEntries(
+ factoryProviders.map((provider) => [
+ provider,
- (h) => {
- hooks[provider] = h;
- let startGeneration = 0;
++ (hooks) => {
++ const id = instances.length;
++ let generation = 0;
+ const instance = {
++ id,
+ provider,
- id: instances.length,
- hooks: h,
- startSettings: [],
- stopSettings: [],
++ hooks,
+ starts: [],
- input: { pushToTalkMode: false, pushToTalkKeyHeld: false },
++ stops: [],
++ jobs: [],
++ gates: [],
++ acquired: 0,
+ microphoneEnabled: false,
++ bound: 0,
++ input: { pushToTalk: false, held: false },
++ texts: [],
++ mapEvents: [],
+ };
+ instances.push(instance);
++ order.push(`factory:${id}`);
+ const adapter = {
++ identity: `${provider}:${id}`,
+ capabilities: {
- costControls: provider === 'openai',
+ pushToTalk: true,
++ costControls: provider === 'openai',
++ },
++ controller: {
++ providerDiagnostic() {
++ return this.session.adapter.identity;
++ },
+ },
- start: (settings = {}) => {
- const generation = ++startGeneration;
- starts.push(provider);
- instance.startSettings.push({ ...settings });
- instance.input.pushToTalkMode = Boolean(settings.pushToTalk);
- h.emit({ type: 'state', state: 'connecting', detail: provider });
- const promise = (async () => {
- const gate =
- startGate?.(instance) ??
- (provider === 'openai' ? deferredStart : null);
- if (gate) await gate;
- // Real adapters own a startup generation and suppress work after
- // stop/disposal. Model that contract, not an impossible late emit.
- if (generation !== startGeneration || h.signal.aborted) return;
++ start(settings = {}) {
++ const attempt = ++generation;
++ instance.starts.push({ ...settings });
++ instance.input.pushToTalk = Boolean(settings.pushToTalk);
++ hooks.emit({
++ type: 'state',
++ state: 'connecting',
++ detail: `adapter:${provider}`,
++ });
++ const job = (async () => {
++ if (attempt !== generation || hooks.signal.aborted) return;
++ if (gateStarts(instance)) {
++ const gate = deferred();
++ instance.gates.push(gate);
++ await gate.promise;
++ }
++ // Adapters own cancellation of their asynchronous acquisition.
++ if (attempt !== generation || hooks.signal.aborted) return;
++ instance.acquired++;
+ instance.microphoneEnabled =
- !instance.input.pushToTalkMode ||
- instance.input.pushToTalkKeyHeld;
- h.emit({ type: 'state', state: 'listening', detail: provider });
++ !instance.input.pushToTalk || instance.input.held;
++ hooks.emit({
++ type: 'state',
++ state: 'listening',
++ detail: provider,
++ });
+ })();
- instance.starts.push(promise);
- return promise;
++ instance.jobs.push(job);
++ return job;
+ },
- stop: (settings = {}) => {
- startGeneration++;
- stops.push(provider);
- instance.stopSettings.push({ ...settings });
- instance.input.pushToTalkMode = false;
- instance.input.pushToTalkKeyHeld = false;
++ stop(settings = {}) {
++ generation++;
++ instance.stops.push({ ...settings });
++ order.push(`stop:${id}`);
++ instance.input.pushToTalk = instance.input.held = false;
+ instance.microphoneEnabled = false;
+ },
- sendText: (text) => {
- sentTexts.push({ provider, text });
- return provider + ':' + text;
- },
- sendMapEvent: () => true,
- claimLocalProviderCommand: () => {
- claims.push(provider);
- return true;
++ getStartOptions: () => ({ pushToTalk: instance.input.pushToTalk }),
++ bindControls() {
++ instance.bound++;
+ },
- releaseLocalProviderCommand: () => {
- releases.push(provider);
- localOutputLifecycle.push(`${provider}:release`);
++ sendText(text) {
++ instance.texts.push(text);
++ return `${provider}:${text}`;
+ },
- beginLocalOutput: () => {
- localOutputBegins.push(provider);
- localOutputLifecycle.push(`${provider}:begin`);
++ sendMapEvent(event) {
++ instance.mapEvents.push(event);
+ return true;
+ },
- endLocalOutput: () => {
- localOutputEnds.push(provider);
- localOutputLifecycle.push(`${provider}:end`);
- },
+ };
- if (startOptionsAvailable)
- adapter.getStartOptions = () => ({
- pushToTalk: instance.input.pushToTalkMode,
- });
+ instance.adapter = adapter;
+ return adapter;
+ },
+ ]),
+ );
- controls = createProviderCommands(
++
++ function createControl() {
++ const id = views.length;
++ order.push(`control:${id}`);
++ const providerSelect = new Element();
++ providerSelect.ownerDocument = { createElement: () => ({}) };
++ providerSelect.replaceChildren = (...options) => {
++ providerSelect.options = options;
++ };
++ const view = {
++ root: {
++ dataset: {},
++ classList: { remove() {} },
++ removeCount: 0,
++ remove() {
++ this.removeCount++;
++ order.push(`remove:${id}`);
++ },
++ },
++ button: new Element(),
++ providerSelect,
++ providerField: {},
++ status: {},
++ detail: {},
++ errorDetail: {},
++ tierButton: {},
++ costValue: {},
++ helpDetail: {},
++ card: {},
++ };
++ views.push(view);
++ return view;
++ }
++ function passiveView() {
++ return {
++ events: [],
++ outlines: [],
++ destroyed: 0,
++ handle(event) {
++ this.events.push(event);
++ },
++ outline(event) {
++ this.outlines.push(event);
++ },
++ destroy() {
++ this.destroyed++;
++ },
++ };
++ }
++
++ facade = createProviderCommands(
+ {
+ runner,
- supportedProviders,
++ pointer,
++ referents,
++ dataManager,
+ signal: lifetime.signal,
- createControl: () => {
- const view = control();
- views.push(view);
- return view;
++ supportedProviders,
++ createControl,
++ createCard() {
++ const card = passiveView();
++ views.at(-1).cardView = card;
++ return card;
+ },
- createCard: () => ({
- enabled: true,
- setEnabled(value) {
- this.enabled = value;
++ createReticle() {
++ const reticle = passiveView();
++ views.at(-1).reticle = reticle;
++ return reticle;
++ },
++ annotations: {
++ onOutlineEvent(callback) {
++ annotations.add(callback);
++ return () => annotations.delete(callback);
+ },
- handle() {},
- destroy() {},
- }),
++ },
++ onSessionEvent(event) {
++ events.push(event);
++ onSessionEvent(event, facade);
++ },
+ },
+ {
- bind: (options) => {
- sourceEvents.push(options.onSessionEvent);
- const onSessionEvent = options.onSessionEvent;
- const mounted = bind({
- ...options,
- onSessionEvent: (event) => {
- sessionEvents.push(event);
- onSessionEvent(event);
- },
- });
- mountedControls.push(mounted);
- return mounted;
- },
+ factories,
- storage,
- now: () => clock,
- setTimer: (callback, delay) => {
- const id = ++timerSequence;
- timers.set(id, { callback, deadline: clock + delay });
- return id;
++ storage: {
++ getItem() {
++ if (storageDenied) throw Error('Storage denied');
++ return savedProvider;
++ },
++ setItem(key, value) {
++ if (storageDenied) throw Error('Storage denied');
++ storageWrites.push([key, value]);
++ savedProvider = value;
++ },
++ },
++ bind(options) {
++ // Keep the real callback so stale-event suppression tests exercise the
++ // facade's mount generation as well as the common session's disposal.
++ const mount = { options, callback: options.onSessionEvent };
++ mounts.push(mount);
++ mount.controls = bindVoiceCommands(options);
++ return mount.controls;
+ },
- clearTimer: (id) => timers.delete(id),
+ },
+ );
+ return {
- controls,
- hooks,
- starts,
- stops,
- claims,
- releases,
- localOutputBegins,
- localOutputEnds,
- localOutputLifecycle,
- views,
- sourceEvents,
- sessionEvents,
- sentTexts,
- mountedControls,
++ facade,
++ runner,
++ pointer,
++ referents,
++ lifetime,
+ instances,
++ views,
++ mounts,
++ events,
++ order,
++ annotations,
++ counters,
+ storageWrites,
- lifetime,
- stored: () => values.get('gev.voice.provider') ?? null,
- storedValue: (key) => values.get(key) ?? null,
- timers,
- setClock: (value) => {
- clock = value;
- },
- selectProvider: (next) => {
- const before = controls.provider;
- const select = views.at(-1)?.providerSelect;
- if (!select) return false;
- select.value = next;
++ state,
++ select(provider) {
++ const select = views.at(-1).providerSelect;
++ select.value = provider;
+ select.dispatchEvent(new Event('change'));
- return controls.provider !== before;
+ },
- expireTimers: () => {
- clock += 30000;
- for (const [id, { callback, deadline }] of [...timers])
- if (clock >= deadline) {
- timers.delete(id);
- callback();
- }
- },
- advanceTime: (milliseconds) => {
- clock += milliseconds;
- for (const [id, { callback, deadline }] of [...timers])
- if (clock >= deadline) {
- timers.delete(id);
- callback();
- }
++ seedConversation() {
++ pointer.beginTurn('text', {
++ capturedSnapshot: { fresh: true, at: 'text' },
++ });
++ referents.recordResult('frame_overhead', {
++ ok: true,
++ display: { title: 'One aircraft' },
++ referents: [
++ { n: 1, id: 'aaa111', label: 'Fixture', layerId: 'flights' },
++ ],
++ });
++ assert.ok(pointer.activeSnapshot());
++ assert.equal(referents.list().length, 1);
+ },
+ };
+}
+
- function deferred() {
- let resolve;
- let reject;
- const promise = new Promise((done, fail) => {
- resolve = done;
- reject = fail;
- });
- return { promise, resolve, reject };
- }
-
- async function settleStarts(instance) {
- await Promise.allSettled(instance.starts);
- await Promise.resolve(); // Let createVoiceSession publish any caught failure.
- }
-
- test('provider preference defaults to OpenAI and ignores invalid or unavailable storage', () => {
- assert.equal(readVoiceProvider({ getItem: () => 'gemini' }), 'gemini');
- for (const value of [null, '', 'other', 'GEMINI']) {
- assert.equal(readVoiceProvider({ getItem: () => value }), 'openai');
- }
++test('provider preference uses only the supplied host capability list', () => {
++ const stored = (value) => ({ getItem: () => value });
++ assert.equal(readVoiceProvider(stored('gemini'), ['openai']), 'openai');
++ assert.equal(readVoiceProvider(stored('openai'), ['gemini']), 'gemini');
+ assert.equal(
- readVoiceProvider({
- getItem() {
- throw new Error('denied');
- },
- }),
++ readVoiceProvider(stored('unknown'), ['gemini', 'openai']),
+ 'openai',
+ );
- });
-
- test('selector stops the active provider, persists the choice, and keeps one public facade', async (t) => {
- const f = setup(t);
- const original = f.controls;
- await original.start();
- assert.equal(original.status, 'listening');
- assert.equal(f.views[0].tierButton.hidden, false);
- f.views[0].providerSelect.value = 'gemini';
- f.views[0].providerSelect.dispatchEvent(new Event('change'));
- assert.equal(window.__gevVoiceCommands, original);
- assert.equal(original.provider, 'gemini');
- assert.equal(f.stored(), 'gemini');
- assert.equal(f.views[0].root.removed, true);
- assert.equal(f.views[1].tierButton.hidden, true);
- assert.deepEqual(f.starts, ['openai', 'gemini']);
- assert.deepEqual(f.instances[1].startSettings, [{ pushToTalk: false }]);
- assert.equal(original.sendTextCommand('hello'), 'gemini:hello');
- assert.equal(original.status, 'listening');
- assert.deepEqual(f.stops, ['openai']);
- f.views[0].providerSelect.value = 'openai';
- f.views[0].providerSelect.dispatchEvent(new Event('change'));
+ assert.equal(
- original.provider,
++ readVoiceProvider(stored('gemini'), ['openai', 'gemini']),
++ 'gemini',
++ );
++ assert.equal(
++ readVoiceProvider(
++ {
++ getItem() {
++ throw Error('denied');
++ },
++ },
++ ['gemini'],
++ ),
+ 'gemini',
- 'old selector listener was released',
+ );
+});
+
- test('the shared action runner keeps its identity and remains callable across provider switches', async (t) => {
- const calls = [];
- const result = { ok: true, hudVariant: 'minimal' };
- const runner = async (...args) => {
- calls.push(args);
- return result;
- };
- const f = setup(t, { runner });
- const args = { variant: 'minimal' };
- const options = { signal: new AbortController().signal };
- for (const provider of ['openai', 'gemini', 'openai']) {
- f.selectProvider(provider);
- assert.equal(f.controls.runner, runner);
- assert.equal(window.__gevVoiceCommands.runner, runner);
++for (const scenario of [
++ {
++ title: 'OpenAI-only host ignores saved Gemini',
++ requested: ['openai'],
++ saved: 'gemini',
++ expected: ['openai'],
++ provider: 'openai',
++ },
++ {
++ title: 'Gemini-only host falls back from saved OpenAI',
++ requested: ['gemini'],
++ saved: 'openai',
++ expected: ['gemini'],
++ provider: 'gemini',
++ },
++ {
++ title: 'dual host restores Gemini',
++ requested: ['openai', 'gemini'],
++ saved: 'gemini',
++ expected: ['openai', 'gemini'],
++ provider: 'gemini',
++ },
++ {
++ title: 'unknown, duplicate and unavailable factories are excluded',
++ requested: ['unknown', 'gemini', 'openai', 'gemini'],
++ factories: ['gemini'],
++ saved: 'openai',
++ expected: ['gemini'],
++ provider: 'gemini',
++ },
++]) {
++ test(scenario.title, (t) => {
++ const f = compositionFixture(t, {
++ supportedProviders: scenario.requested,
++ factoryProviders: scenario.factories,
++ savedProvider: scenario.saved,
++ });
++ assert.deepEqual(f.facade.supportedProviders, scenario.expected);
++ assert.equal(Object.isFrozen(f.facade.supportedProviders), true);
++ assert.equal(f.facade.provider, scenario.provider);
++ assert.deepEqual(
++ f.views[0].providerSelect.options.map((option) => option.value),
++ scenario.expected,
++ );
+ assert.equal(
- await f.controls.runner('set_hud_variant', args, options),
- result,
++ f.views[0].providerField.hidden,
++ scenario.expected.length === 1,
+ );
- assert.equal(f.controls.status, 'idle');
- }
- assert.deepEqual(
- calls,
- Array.from({ length: 3 }, () => ['set_hud_variant', args, options]),
- );
- assert.deepEqual(
- f.starts,
- [],
- 'direct map actions do not start a voice connection',
- );
- });
-
- test('switch during tool execution aborts old work without disturbing the new session', async (t) => {
- let resolve;
- let actionSignal;
- const pending = new Promise((done) => {
- resolve = done;
- });
- const f = setup(t, {
- runner: async (_name, _args, options) => {
- actionSignal = options.signal;
- return pending;
- },
- });
- await f.controls.start();
- const oldAction = f.hooks.openai.runAction('fly_to_location', {});
- f.selectProvider('gemini');
- assert.equal(actionSignal.aborted, true);
- assert.deepEqual(f.starts, ['openai', 'gemini']);
- resolve({ ok: true });
- await assert.rejects(oldAction, { name: 'AbortError' });
- assert.equal(f.controls.status, 'listening');
- assert.equal(f.controls.provider, 'gemini');
- });
-
- test('provider swaps retain the shared runner and facade lifetime until final teardown', async (t) => {
- let disposed = false;
- let disposals = 0;
- let resets = 0;
- const runner = async () => {
+ assert.equal(
- disposed,
- false,
- 'replacement must not permanently dispose the runner',
++ f.views[0].root.dataset.providerChoice,
++ String(scenario.expected.length > 1),
+ );
- return { ok: true };
- };
- runner.resetConversation = () => resets++;
- runner.dispose = () => {
- disposed = true;
- disposals++;
- };
- const f = setup(t, { runner });
- const lifetime = f.controls.signal;
- let lifetimeAborts = 0;
- lifetime.addEventListener('abort', () => lifetimeAborts++);
- await f.controls.start();
- for (const provider of ['gemini', 'openai']) {
- const outgoing = f.controls.session.signal;
- f.selectProvider(provider);
- assert.equal(outgoing.aborted, true);
- assert.equal(f.controls.signal, lifetime);
- assert.equal(lifetime.aborted, false);
- assert.equal(disposals, 0);
- assert.equal(f.controls.status, 'listening');
- assert.deepEqual(await f.hooks[provider].runAction('zoom_to_globe', {}), {
- ok: true,
- });
- }
- assert.equal(resets, 2, 'each retired adapter forgets conversation state');
- f.controls.destroy();
- f.controls.destroy();
- f.controls.stop({ removeUi: true });
- f.lifetime.abort();
- assert.equal(lifetime.aborted, true);
- assert.equal(lifetimeAborts, 1);
- assert.equal(disposals, 1);
- });
-
- test('late startup cannot revive a replaced provider; app teardown removes the latest controls', async (t) => {
- let resolve;
- const pending = new Promise((done) => {
- resolve = done;
++ assert.equal(f.instances.length, 1);
++ assert.equal(
++ f.instances[0].starts.length,
++ 0,
++ 'discovery must not start a provider',
++ );
++ assert.equal(f.facade.state, 'idle');
+ });
- const f = setup(t, { deferredStart: pending });
- const first = f.controls.start();
- f.selectProvider('gemini');
- assert.deepEqual(f.starts, ['openai', 'gemini']);
- resolve();
- await first;
- assert.equal(f.controls.status, 'listening');
- assert.equal(f.views[1].detail.textContent, 'gemini');
- f.lifetime.abort();
- assert.equal(f.controls.disposed, true);
- assert.equal(f.views[1].root.removed, true);
- assert.equal(f.selectProvider('openai'), false);
- assert.equal(f.controls.start(), false);
- assert.equal(f.controls.sendTextCommand('late'), false);
- });
++}
+
- test('restored Gemini choice retains the action runner without creating duplicate lifetimes', async (t) => {
- const result = { ok: true, hudVariant: 'tactical' };
- const runner = async (name) => {
- assert.equal(name, 'get_current_view_state');
- return result;
++test('invalid or empty host support fails before mounting a control', () => {
++ let mounts = 0;
++ const dependencies = {
++ bind() {
++ mounts++;
++ },
++ factories: { openai() {} },
+ };
- const f = setup(t, { value: 'gemini', runner });
- assert.equal(f.controls.provider, 'gemini');
- assert.equal(f.controls.runner, runner);
- assert.equal(await f.controls.runner('get_current_view_state'), result);
- assert.equal(f.selectProvider('gemini'), false);
- assert.equal(f.selectProvider('unrecognized'), false);
- assert.equal(f.views.length, 1);
- assert.deepEqual(f.starts, []);
++ assert.throws(
++ () =>
++ createProviderCommands({ supportedProviders: 'gemini' }, dependencies),
++ /must be an array/,
++ );
++ assert.throws(
++ () =>
++ createProviderCommands(
++ { supportedProviders: ['gemini', 'unknown'] },
++ dependencies,
++ ),
++ /No supported voice provider/,
++ );
++ assert.equal(mounts, 0);
+});
+
- for (const provider of ['openai', 'gemini']) {
- test(`${provider} sends clear provider requests to the active model without changing provider state`, async (t) => {
- const f = setup(t, { value: provider });
- await f.controls.start();
- const session = f.controls.session;
- const starts = [...f.starts];
- const stops = [...f.stops];
- const mountedViews = f.views.length;
- const requests = [
- provider === 'openai' ? 'Switch to Gemini' : 'Switch to OpenAI',
- `Switch to ${provider}`,
- 'Select a voice provider',
- 'Use another-provider as my voice provider',
- ];
-
- for (const text of requests)
- assert.equal(f.controls.sendTextCommand(text), `${provider}:${text}`);
-
- assert.deepEqual(
- f.sentTexts,
- requests.map((text) => ({ provider, text })),
++test('active switch keeps PTT mode, retires the held key, and disposes before mounting', async (t) => {
++ const f = compositionFixture(t);
++ const firstSession = f.facade.session;
++ const outerSignal = f.facade.signal;
++ const first = f.instances[0];
++ // PTT controls can activate the adapter directly; the facade must learn
++ // activity from its common events, not only from facade.start().
++ first.input.held = true;
++ await first.adapter.start({ pushToTalk: true });
++ assert.equal(first.microphoneEnabled, true);
++ assert.equal(f.facade.isActive(), true);
++ f.seedConversation();
++ const before = { ...f.counters };
++ f.select('gemini');
++ await settle();
++ const second = f.instances[1];
++ assert.equal(window.__gevVoiceCommands, f.facade);
++ assert.equal(f.facade.runner, f.runner);
++ assert.equal(f.facade.signal, outerSignal);
++ assert.equal(outerSignal.aborted, false);
++ assert.equal(firstSession.disposed, true);
++ assert.equal(first.hooks.signal.aborted, true);
++ assert.deepEqual(first.stops, [{ removeUi: true }]);
++ assert.equal(first.input.held, false);
++ assert.equal(first.microphoneEnabled, false);
++ assert.deepEqual(second.starts, [{ pushToTalk: true }]);
++ assert.equal(second.input.held, false);
++ assert.equal(
++ second.microphoneEnabled,
++ false,
++ 'a held key must never migrate to the new adapter',
++ );
++ assert.equal(f.facade.state, 'listening');
++ assert.ok(f.order.indexOf('stop:0') < f.order.indexOf('control:1'));
++ assert.ok(f.order.indexOf('remove:0') < f.order.indexOf('control:1'));
++ assert.ok(f.order.indexOf('stop:0') < f.order.indexOf('factory:1'));
++ assert.equal(f.views[0].button.listenerCount('click'), 0);
++ assert.equal(f.views[0].providerSelect.listenerCount('change'), 0);
++ assert.equal(f.views[1].providerSelect.listenerCount('change'), 1);
++ assert.equal(f.views[1].providerSelect.focusCount, 1);
++ assert.equal(f.views[1].tierButton.hidden, true);
++ assert.equal(f.views[1].costValue.hidden, true);
++ assert.equal(f.facade.providerDiagnostic(), 'gemini:1');
++ assert.equal(f.pointer.activeSnapshot(), null);
++ assert.deepEqual(f.referents.list(), []);
++ for (const key of ['pointer', 'referents', 'conversation'])
++ assert.equal(
++ f.counters[key],
++ before[key] + 1,
++ `one explicit replacement reset: ${key}`,
+ );
- assert.equal(f.controls.provider, provider);
- assert.equal(f.controls.session, session);
- assert.deepEqual(f.storageWrites, []);
- assert.deepEqual(f.starts, starts);
- assert.deepEqual(f.stops, stops);
- assert.equal(f.views.length, mountedViews);
- assert.deepEqual(f.claims, []);
- assert.deepEqual(f.releases, []);
- assert.equal(f.controls.session.adapter.acknowledgeLocalCommand, undefined);
- assert.deepEqual(f.localOutputBegins, []);
- assert.deepEqual(f.localOutputEnds, []);
- });
-
- test(`${provider} leaves spoken provider requests with the provider response already in progress`, async (t) => {
- const f = setup(t, { value: provider });
- await f.controls.start();
- const session = f.controls.session;
- const events = [
- {
- type: 'user-input-final',
- inputKind: 'speech',
- inputScope: 'utterance',
- inputId: 'provider-request',
- text: provider === 'openai' ? 'Switch to Gemini' : 'Switch to OpenAI',
- },
- {
- type: 'user-input-final',
- inputKind: 'speech',
- inputScope: 'segment',
- inputId: 'provider-request',
- text: ' actually keep the current provider',
- },
- ];
-
- for (const event of events) f.hooks[provider].emit(event);
- await Promise.resolve();
-
- assert.equal(f.controls.provider, provider);
- assert.equal(f.controls.session, session);
- assert.deepEqual(f.sentTexts, []);
- assert.deepEqual(f.storageWrites, []);
- assert.deepEqual(f.starts, [provider]);
- assert.deepEqual(f.stops, []);
- assert.equal(f.views.length, 1);
- assert.deepEqual(f.claims, []);
- assert.deepEqual(f.releases, []);
- assert.equal(f.controls.session.adapter.acknowledgeLocalCommand, undefined);
- assert.deepEqual(f.localOutputBegins, []);
- assert.deepEqual(f.localOutputEnds, []);
++ assert.equal(
++ f.counters.dispose,
++ 0,
++ 'provider replacement keeps the page runner',
++ );
++ assert.deepEqual(f.storageWrites, [[PROVIDER_KEY, 'gemini']]);
++ assert.equal(f.facade.sendTextCommand('hello'), 'gemini:hello');
++ assert.deepEqual(first.texts, []);
++ assert.deepEqual(second.texts, ['hello']);
++ const result = await f.facade.runner('adjust_camera_zoom', {
++ direction: 'in',
++ amount: 'little',
+ });
- }
++ assert.equal(
++ result.ok,
++ true,
++ 'the actual shared action runner remains usable after switching',
++ );
++ assert.equal(f.state.zooms, 1);
++});
+
- for (const provider of ['openai', 'gemini']) {
- test(`${provider} button activation resumes exactly once after a selector change`, async (t) => {
- const f = setup(t, { value: provider });
- const successor = provider === 'openai' ? 'gemini' : 'openai';
- f.views[0].button.dispatchEvent(new Event('click'));
- assert.equal(f.controls.state, 'listening');
- assert.deepEqual(f.instances[0].startSettings, [{ pushToTalk: false }]);
- f.views[0].providerSelect.value = successor;
- f.views[0].providerSelect.dispatchEvent(new Event('change'));
- assert.equal(f.controls.provider, successor);
- assert.equal(f.views[1].providerSelect.focused, true);
- assert.equal(f.controls.state, 'listening');
- assert.deepEqual(f.starts, [provider, successor]);
- assert.deepEqual(f.instances[1].startSettings, [{ pushToTalk: false }]);
- await f.controls.start();
- assert.deepEqual(
- f.starts,
- [provider, successor],
- 'an already active successor is not started twice',
++for (const initialState of ['idle', 'error']) {
++ test(`${initialState} selection never autostarts; manual start still works`, async (t) => {
++ const f = compositionFixture(t, { storageDenied: true });
++ if (initialState === 'error') {
++ await f.facade.start({ pushToTalk: true });
++ f.instances[0].adapter.stop({ preserveStatus: true });
++ f.instances[0].hooks.emit({
++ type: 'state',
++ state: 'error',
++ detail: 'Fixture failure',
++ });
++ }
++ f.select('gemini');
++ await settle();
++ assert.equal(
++ f.facade.provider,
++ 'gemini',
++ 'denied storage cannot block a supported selection',
++ );
++ assert.equal(f.facade.state, 'idle');
++ assert.deepEqual(f.instances[1].starts, []);
++ f.select('gemini');
++ f.select('unknown');
++ assert.equal(
++ f.instances.length,
++ 2,
++ 'same and unsupported selections cannot remount',
+ );
++ assert.equal(f.facade.provider, 'gemini');
++ await f.facade.start({ pushToTalk: false });
++ assert.deepEqual(f.instances[1].starts, [{ pushToTalk: false }]);
++ assert.equal(f.instances[1].microphoneEnabled, true);
+ });
+}
+
- for (const route of [
- 'public-stop',
- 'session-stop',
- 'button-stop',
- 'preserve-status',
- 'session-preserve-status',
- ]) {
- test(`provider selection stays OFF after ${route}, even if a stale active state arrives`, async (t) => {
- const f = setup(t, {});
- await f.controls.start();
- if (route === 'public-stop') f.controls.stop();
- if (route === 'session-stop') f.controls.session.stop();
- if (route === 'button-stop')
- f.views[0].button.dispatchEvent(new Event('click'));
- if (route === 'preserve-status') f.controls.stop({ preserveStatus: true });
- if (route === 'session-preserve-status')
- f.controls.session.stop({ preserveStatus: true });
- // A stopped adapter may still have a queued presentation event. It must
- // not re-create the user's ON intent without a new connecting transition.
- f.hooks.openai.emit({
- type: 'state',
- state: 'listening',
- detail: 'late display state',
- });
- f.hooks.openai.emit({
- type: 'transcript',
- role: 'user',
- text: 'Show flights over London',
- final: true,
++for (const outcome of ['resolve', 'reject']) {
++ test(`retired startup ${outcome} and stale events cannot affect the current mount`, async (t) => {
++ const f = compositionFixture(t, {
++ gateStarts: (instance) => instance.id === 0,
+ });
- f.selectProvider('gemini');
- assert.equal(f.controls.provider, 'gemini');
- assert.equal(f.controls.state, 'idle');
- assert.deepEqual(f.starts, ['openai']);
- assert.deepEqual(f.instances[1].startSettings, []);
++ const oldStart = f.facade.start({ pushToTalk: false });
++ const old = f.instances[0];
++ assert.equal(f.facade.state, 'connecting');
++ f.select('gemini');
++ await settle();
++ assert.equal(f.facade.state, 'listening');
++ const current = f.instances[1];
++ const eventCount = f.events.length;
++ const currentStops = current.stops.length;
++ const currentCardCount = f.views[1].cardView.events.length;
++ old.gates[0][outcome](new Error('Late retired startup failure'));
++ await oldStart;
++ for (const state of ['idle', 'error', 'connecting']) {
++ old.hooks.emit({ type: 'state', state, detail: 'retired adapter' });
++ f.mounts[0].callback({
++ type: 'state',
++ state,
++ detail: 'retired forward callback',
++ });
++ }
++ assert.equal(f.events.length, eventCount);
++ assert.equal(f.views[1].cardView.events.length, currentCardCount);
++ assert.equal(f.facade.state, 'listening');
++ assert.equal(old.acquired, 0);
++ assert.equal(current.stops.length, currentStops);
++ assert.equal(current.starts.length, 1);
++ f.facade.stop();
++ f.mounts[0].callback({ type: 'state', state: 'connecting' });
++ f.select('openai');
++ assert.deepEqual(
++ f.instances[2].starts,
++ [],
++ 'a retired connecting callback cannot revive voice intent',
++ );
++ assert.equal(f.facade.state, 'idle');
+ });
+}
+
- test('a rejected old connect cannot stop the automatically connecting successor', async (t) => {
- const oldGate = deferred();
- const nextGate = deferred();
- const f = setup(t, {
- startGate: ({ id }) => (id === 0 ? oldGate.promise : nextGate.promise),
++test('Stop during replacement startup defeats late settlement and further automatic resume', async (t) => {
++ const f = compositionFixture(t, {
++ gateStarts: (instance) => instance.id === 1,
+ });
- const first = f.controls.start();
- assert.equal(f.controls.state, 'connecting');
- f.selectProvider('gemini');
- assert.deepEqual(f.starts, ['openai', 'gemini']);
- assert.equal(f.controls.state, 'connecting');
- oldGate.reject(new Error('retired connect failed'));
- await first;
- assert.equal(f.controls.provider, 'gemini');
- assert.equal(f.controls.state, 'connecting');
- assert.deepEqual(f.instances[1].stopSettings, []);
- nextGate.resolve();
- await settleStarts(f.instances[1]);
- assert.equal(f.controls.state, 'listening');
- });
-
- test('rapid active switches start each replacement once and only the newest mount can finish', async (t) => {
- const gates = [deferred(), deferred(), deferred()];
- const f = setup(t, { startGate: ({ id }) => gates[id].promise });
- const first = f.controls.start();
- f.selectProvider('gemini');
- f.selectProvider('openai');
- assert.equal(f.controls.provider, 'openai');
- assert.equal(f.controls.state, 'connecting');
- assert.deepEqual(f.starts, ['openai', 'gemini', 'openai']);
- assert.equal(f.instances[0].hooks.signal.aborted, true);
- assert.equal(f.instances[1].hooks.signal.aborted, true);
- assert.equal(f.instances[2].hooks.signal.aborted, false);
- gates[1].resolve();
- gates[0].resolve();
- await first;
- await settleStarts(f.instances[1]);
- for (const instance of f.instances.slice(0, 2)) {
- instance.hooks.emit({ type: 'state', state: 'error', detail: 'retired' });
- instance.hooks.emit({ type: 'state', state: 'listening' });
- }
- assert.equal(f.controls.state, 'connecting');
- gates[2].resolve();
- await settleStarts(f.instances[2]);
- assert.equal(f.controls.state, 'listening');
- assert.equal(f.controls.session.signal, f.instances[2].hooks.signal);
- assert.deepEqual(
- f.instances.map((instance) => instance.startSettings.length),
- [1, 1, 1],
++ await f.facade.start();
++ f.select('gemini');
++ const replacement = f.instances[1];
++ assert.equal(f.facade.state, 'connecting');
++ f.facade.stop();
++ replacement.gates[0].resolve();
++ await Promise.all(replacement.jobs);
++ assert.equal(replacement.acquired, 0);
++ assert.equal(f.facade.state, 'idle');
++ f.select('openai');
++ assert.deepEqual(f.instances[2].starts, []);
++ await f.facade.start();
++ assert.equal(
++ f.facade.state,
++ 'listening',
++ 'a later explicit start remains healthy',
+ );
+});
+
- for (const route of [
- 'public-stop',
- 'session-stop',
- 'button-stop',
- 'destroy',
- 'parent-abort',
- ]) {
- test(`${route} defeats an automatic successor startup that has not settled`, async (t) => {
- const nextGate = deferred();
- const f = setup(t, {
- startGate: ({ provider }) =>
- provider === 'gemini' ? nextGate.promise : null,
- });
- await f.controls.start();
- f.selectProvider('gemini');
- assert.deepEqual(f.starts, ['openai', 'gemini']);
- assert.equal(f.controls.state, 'connecting');
- if (route === 'public-stop') f.controls.stop();
- if (route === 'session-stop') f.controls.session.stop();
- if (route === 'button-stop')
- f.views[1].button.dispatchEvent(new Event('click'));
- if (route === 'destroy') f.controls.destroy();
- if (route === 'parent-abort') f.lifetime.abort();
- nextGate.resolve();
- await settleStarts(f.instances[1]);
- assert.equal(f.controls.state, 'idle');
- assert.equal(f.instances[1].microphoneEnabled, false);
- assert.equal(f.instances[1].stopSettings.length, 1);
- assert.deepEqual(f.starts, ['openai', 'gemini']);
- if (route === 'destroy' || route === 'parent-abort') {
- assert.equal(f.controls.disposed, true);
- assert.equal(f.views[1].root.removed, true);
- } else {
- f.selectProvider('openai');
- assert.equal(f.controls.state, 'idle');
- assert.deepEqual(f.starts, ['openai', 'gemini']);
++for (const emitsIdle of [false, true]) {
++ test(`Stop and error clear pointer/referents/conversation once: adapter emitsIdle=${emitsIdle}`, async (t) => {
++ const f = compositionFixture(t);
++ if (emitsIdle) {
++ const instance = f.instances[0];
++ const originalStop = instance.adapter.stop;
++ instance.adapter.stop = function (settings = {}) {
++ originalStop.call(this, settings);
++ if (!settings.preserveStatus && !settings.removeUi)
++ instance.hooks.emit({ type: 'state', state: 'idle' });
++ };
++ }
++ for (const end of ['stop', 'error']) {
++ await f.facade.start();
++ f.seedConversation();
++ const before = { ...f.counters };
++ const generation = f.referents.generation();
++ if (end === 'stop') f.facade.stop();
++ else {
++ f.instances[0].adapter.stop({ preserveStatus: true });
++ f.instances[0].hooks.emit({
++ type: 'state',
++ state: 'error',
++ detail: 'Fixture failure',
++ });
++ }
++ assert.equal(f.pointer.activeSnapshot(), null);
++ assert.deepEqual(f.referents.list(), []);
++ assert.equal(f.referents.generation(), generation + 1);
++ for (const key of ['pointer', 'referents', 'conversation'])
++ assert.equal(f.counters[key], before[key] + 1, `${end}: ${key}`);
+ }
+ });
+}
+
- test('failed automatic startup keeps the selected provider in error without fallback or retries', async (t) => {
- const nextGate = deferred();
- const f = setup(t, {
- startGate: ({ provider }) =>
- provider === 'gemini' ? nextGate.promise : null,
++test('outer destruction disposes the runner once and removes each provider binding', async (t) => {
++ const priorUnsaved = describeUnsavedWork();
++ const f = compositionFixture(t);
++ await f.facade.start();
++ f.select('gemini');
++ await settle();
++ assert.equal(f.annotations.size, 1);
++ assert.ok(
++ describeUnsavedWork().includes(translate('the active voice session')),
++ );
++ const oldCardEvents = f.views[0].cardView.events.length;
++ for (const callback of f.annotations) callback({ id: 'fixture-outline' });
++ assert.equal(f.views[0].cardView.outlines.length, 0);
++ assert.equal(f.views[1].cardView.outlines.length, 1);
++ assert.equal(f.instances[1].mapEvents.length, 1);
++ f.facade.destroy();
++ f.facade.destroy();
++ f.facade.stop({ removeUi: true });
++ f.lifetime.abort();
++ assert.equal(f.counters.dispose, 1);
++ assert.equal(f.facade.signal.aborted, true);
++ assert.equal(f.facade.disposed, true);
++ assert.equal(f.annotations.size, 0);
++ assert.deepEqual(describeUnsavedWork(), priorUnsaved);
++ const finalEvents = f.events.length;
++ const starts = f.instances.map((instance) => instance.starts.length);
++ for (const [index, view] of f.views.entries()) {
++ assert.equal(view.root.removeCount, 1);
++ assert.equal(view.cardView.destroyed, 1);
++ assert.equal(view.reticle.destroyed, 1);
++ assert.equal(view.button.listenerCount('click'), 0);
++ assert.equal(view.providerSelect.listenerCount('change'), 0);
++ assert.equal(f.instances[index].hooks.signal.aborted, true);
++ view.button.dispatchEvent(new Event('click'));
++ view.providerSelect.value = 'openai';
++ view.providerSelect.dispatchEvent(new Event('change'));
++ f.instances[index].hooks.emit({ type: 'state', state: 'connecting' });
++ f.mounts[index].callback({ type: 'state', state: 'connecting' });
++ }
++ assert.equal(f.events.length, finalEvents);
++ assert.equal(f.views[0].cardView.events.length, oldCardEvents);
++ assert.deepEqual(
++ f.instances.map((instance) => instance.starts.length),
++ starts,
++ );
++ assert.equal(f.instances.length, 2);
++ assert.equal(f.facade.start(), false);
++ assert.equal(f.facade.sendText('after destroy'), false);
++ assert.equal(f.facade.notifyMapEvent({}), false);
++ const result = await f.facade.runner('adjust_camera_zoom', {
++ direction: 'in',
++ amount: 'little',
+ });
- await f.controls.start();
- f.selectProvider('gemini');
- assert.equal(f.controls.state, 'connecting');
- nextGate.reject(new Error('Microphone permission denied'));
- await settleStarts(f.instances[1]);
- assert.equal(f.controls.provider, 'gemini');
- assert.equal(f.stored(), 'gemini');
- assert.equal(f.controls.state, 'error');
- assert.equal(f.views[1].detail.textContent, 'Microphone permission denied');
- assert.equal(f.instances[0].hooks.signal.aborted, true);
- assert.deepEqual(f.instances[1].stopSettings, [{ preserveStatus: true }]);
- assert.deepEqual(f.starts, ['openai', 'gemini']);
- f.selectProvider('openai');
- assert.equal(f.controls.state, 'idle', 'failure cleared the resume intent');
- assert.deepEqual(f.starts, ['openai', 'gemini']);
++ assert.equal(result.cancelled, true);
++ assert.equal(
++ f.state.zooms,
++ 0,
++ 'the actual runner cannot move the camera after outer disposal',
++ );
+});
+
- for (const provider of ['openai', 'gemini']) {
- for (const pushToTalk of [false, true]) {
- test(`${provider} direct adapter activation preserves ${pushToTalk ? 'PTT' : 'open-mic'} mode without transferring a held key`, async (t) => {
- const f = setup(t, { value: provider });
- const original = f.instances[0];
- original.input.pushToTalkKeyHeld = pushToTalk;
- // Native PTT starts the controller rather than facade.start(). The
- // adapter emits connecting, then the common session observes its state.
- await original.adapter.start({ pushToTalk });
- assert.equal(f.controls.state, 'listening');
- f.selectProvider(provider === 'openai' ? 'gemini' : 'openai');
- const successor = f.instances[1];
- assert.equal(f.controls.state, 'listening');
- assert.deepEqual(successor.startSettings, [{ pushToTalk }]);
- assert.equal(
- original.input.pushToTalkMode,
- false,
- 'retirement resets the old input after its settings were captured',
- );
- assert.equal(successor.input.pushToTalkKeyHeld, false);
++for (const action of ['stop', 'destroy']) {
++ for (const phase of ['common', 'adapter']) {
++ test(`${action} from replacement ${phase} connecting observer prevents resume`, async (t) => {
++ let intercepted = 0;
++ const f = compositionFixture(t, {
++ onSessionEvent(event, facade) {
++ if (
++ facade?.provider !== 'gemini' ||
++ event.type !== 'state' ||
++ event.state !== 'connecting'
++ )
++ return;
++ const matching =
++ phase === 'common'
++ ? event.detail === undefined
++ : event.detail === 'adapter:gemini';
++ if (matching && intercepted++ === 0) facade[action]();
++ },
++ });
++ await f.facade.start({ pushToTalk: true });
++ f.select('gemini');
++ await settle();
++ const replacement = f.instances[1];
++ assert.equal(intercepted, 1);
++ assert.equal(replacement.starts.length, phase === 'common' ? 0 : 1);
++ assert.equal(replacement.acquired, 0);
++ assert.equal(replacement.microphoneEnabled, false);
++ assert.equal(f.facade.isActive(), false);
++ assert.equal(f.facade.state, 'idle');
+ assert.equal(
- successor.microphoneEnabled,
- !pushToTalk,
- 'PTT waits muted for a new physical hold',
++ f.events.filter(
++ (event) => event.state === 'listening' && event.detail === 'gemini',
++ ).length,
++ 0,
+ );
++ assert.equal(f.facade.disposed, action === 'destroy');
++ assert.equal(f.counters.dispose, action === 'destroy' ? 1 : 0);
++ if (action === 'stop') {
++ f.select('openai');
++ assert.deepEqual(
++ f.instances[2].starts,
++ [],
++ 'Stop cleared the intent to resume',
++ );
++ await f.facade.start({ pushToTalk: false });
++ assert.equal(f.facade.state, 'listening');
++ } else {
++ f.select('openai');
++ assert.equal(f.instances.length, 2);
++ assert.equal(f.facade.start(), false);
++ }
+ });
+ }
+}
-
- test('an adapter without resume options still resumes an active session in open-mic mode', async (t) => {
- const f = setup(t, { startOptionsAvailable: false });
- await f.controls.start();
- f.selectProvider('gemini');
- assert.equal(f.controls.state, 'listening');
- assert.deepEqual(f.instances[1].startSettings, [{ pushToTalk: false }]);
- });
-
- test('the public facade exposes no provider-mutation method', (t) => {
- const f = setup(t);
- assert.equal(f.controls.setProvider, undefined);
- assert.equal(f.controls.requestProviderChange, undefined);
- assert.equal(f.controls.provider, 'openai');
- assert.deepEqual(f.starts, []);
- assert.deepEqual(f.storageWrites, []);
- });
-
- test('supported factories determine restoration, facade selection and actual selector options', async (t) => {
- for (const config of [
- { supportedProviders: ['openai'], value: 'gemini', expected: 'openai' },
- { supportedProviders: ['gemini'], value: 'openai', expected: 'gemini' },
- {
- supportedProviders: ['gemini', 'openai'],
- factoryProviders: ['openai'],
- value: 'gemini',
- expected: 'openai',
- },
- { supportedProviders: ['unknown', 'gemini', 'gemini'], expected: 'gemini' },
- ]) {
- await t.test(JSON.stringify(config), async (t) => {
- const f = setup(t, config);
- assert.equal(f.controls.provider, config.expected);
- assert.deepEqual(f.controls.supportedProviders, [config.expected]);
- assert.deepEqual(
- f.views[0].providerSelect.options.map(({ value }) => value),
- [config.expected],
- );
- assert.equal(f.instances.length, 1);
- assert.equal(f.instances[0].provider, config.expected);
- const unsupported = config.expected === 'openai' ? 'gemini' : 'openai';
- assert.equal(f.selectProvider(unsupported), false);
- assert.deepEqual(f.storageWrites, []);
- await f.controls.start();
- assert.deepEqual(f.starts, [config.expected]);
- });
- }
- });
-
- test('a host without an available supported factory fails before mounting controls', (t) => {
- assert.throws(
- () =>
- setup(t, {
- supportedProviders: ['gemini'],
- factoryProviders: ['openai'],
- }),
- /No supported voice provider/,
- );
- });
diff --cc src/voice/realtimeRadio.js
index ae8e75193,b4cd1dfa6..4c5212d6e
--- a/src/voice/realtimeRadio.js
+++ b/src/voice/realtimeRadio.js
@@@ -324,25 -266,6 +268,25 @@@ export class RealtimeRadio
}
}
+ /** Revoke one call's prepared/preflight result, preserving other owners. */
+ cancelPlaybackResult(result) {
+ if (!result) return;
+ if (this.pendingRadioPlaybackResult === result) {
+ this.pendingRadioPlaybackResult = null;
+ this.radioHandoffDeferredByReservation = false;
+ }
+ if (this.radioHandoffInFlightResult !== result) return;
+ const attemptId = this.radioHandoffAttemptId;
+ const shouldStopPlayback = this.radioHandoffInFlight;
+ this.radioHandoffInFlightResult = null;
+ this.radioHandoffInFlight = false;
+ this.radioHandoffAttemptId = null;
- // Do not advance the group epoch or release another tool's reservation.
- // Late preflight completion remains bound to its own attempt ID.
++ // Keep the group epoch and sibling reservations; release ownership before
++ // Stop can synchronously notify playback observers.
+ if (shouldStopPlayback)
+ this.radioLayer?.stopPlayback?.({ origin: 'voice-cleanup', attemptId });
+ }
+
/** Invalidate delayed Radio work inside the requested authority scope. */
abortRadioSiblingTools({ responseId = null, scope = 'all' } = {}) {
for (const [controller, metadata] of this.activeRadioToolControllers) {
diff --cc src/voice/realtimeRadio.test.mjs
index 000000000,000000000..4e29325ee
new file mode 100644
--- /dev/null
+++ b/src/voice/realtimeRadio.test.mjs
@@@ -1,0 -1,0 +1,120 @@@
++import test from 'node:test';
++import assert from 'node:assert/strict';
++import { GevRealtimeController } from './realtimeController.js';
++
++const tick = () => new Promise((resolve) => setImmediate(resolve));
++const playback = (id) => ({
++ ok: true,
++ action: 'control_radio',
++ radioAction: 'play',
++ radioPlaybackRequested: true,
++ id,
++});
++
++function fixture(t) {
++ const attempts = [],
++ stopped = [],
++ corrections = [],
++ states = [];
++ const controller = new GevRealtimeController({
++ ui: {
++ root: {
++ dataset: {},
++ classList: { remove() {} },
++ querySelectorAll: () => [],
++ remove() {},
++ },
++ status: {},
++ detail: {},
++ errorDetail: {},
++ },
++ runner: async () => ({ ok: false }),
++ debugSink: null,
++ onSessionEvent: (event) => states.push(event),
++ radioLayer: {
++ setVoiceDucked() {},
++ playForVoice: ({ attemptId }) =>
++ new Promise((resolve, reject) =>
++ attempts.push({ attemptId, resolve, reject }),
++ ),
++ stopPlayback: (options) => stopped.push(options),
++ },
++ });
++ controller.queueResponseCreate = (message) => corrections.push(message);
++ controller.dc = { readyState: 'open', send() {}, close() {} };
++ t.after(() => controller.stop({ removeUi: true }));
++ return { controller, attempts, stopped, corrections, states };
++}
++
++test('default OpenAI reservation silences rejected frozen preflight and resumes retained result after failure', async (t) => {
++ const h = fixture(t),
++ c = h.controller;
++ const a = playback('A');
++ c.pendingRadioPlaybackResult = a;
++ const pending = c.startPendingRadioHandoff();
++ const reservation = c.reserveRadioToolHandoff();
++ assert.equal(c.pendingRadioPlaybackResult, a);
++ assert.equal(c.radioHandoffInFlight, false);
++ h.attempts[0].reject(new Error('obsolete frozen preflight'));
++ await pending;
++ assert.deepEqual(h.corrections, []);
++ assert.equal(
++ h.states.some((event) => event.detail === 'Radio did not start'),
++ false,
++ );
++ c.settleRadioToolHandoffReservation(reservation, { commit: false });
++ await tick();
++ assert.equal(h.attempts.length, 2);
++ assert.equal(c.radioHandoffInFlightResult, a);
++ assert.notEqual(h.attempts[0].attemptId, h.attempts[1].attemptId);
++ h.attempts[1].reject(new Error('current preflight failed'));
++ await tick();
++ assert.equal(h.corrections.length, 1);
++ assert.equal(c.status, 'listening');
++});
++
++test('default OpenAI group cancellation silences rejected preflight without blocking the next failure correction', async (t) => {
++ const h = fixture(t),
++ c = h.controller;
++ c.pendingRadioPlaybackResult = playback('A');
++ const old = c.startPendingRadioHandoff();
++ c.cancelRadioHandoff();
++ h.attempts[0].reject(new Error('cancelled preflight'));
++ await old;
++ assert.deepEqual(h.corrections, []);
++ c.pendingRadioPlaybackResult = playback('B');
++ const current = c.startPendingRadioHandoff();
++ h.attempts[1].resolve(false);
++ await current;
++ assert.equal(h.corrections.length, 1);
++});
++
++test('per-result cancellation retains sibling result and epoch and ignores late failure or duplicate cancellation', async (t) => {
++ const h = fixture(t),
++ c = h.controller;
++ const a = playback('A'),
++ b = playback('B');
++ c.pendingRadioPlaybackResult = a;
++ const old = c.startPendingRadioHandoff();
++ const siblingEpoch = c.radioHandoffEpoch;
++ c.pendingRadioPlaybackResult = b;
++ c._radio.cancelPlaybackResult(a);
++ c._radio.cancelPlaybackResult(a);
++ c._radio.cancelPlaybackResult(playback('unknown'));
++ assert.equal(c.radioHandoffEpoch, siblingEpoch);
++ assert.equal(c.pendingRadioPlaybackResult, b);
++ assert.equal(h.stopped.length, 1);
++ h.attempts[0].reject(new Error('late cancelled preflight'));
++ await old;
++ assert.deepEqual(h.corrections, []);
++ const current = c.startPendingRadioHandoff();
++ const reservation = c.reserveRadioToolHandoff();
++ c._radio.cancelPlaybackResult(b);
++ assert.equal(c._radio.radioToolHandoffReservations.has(reservation), true);
++ h.attempts[1].resolve(false);
++ await current;
++ assert.deepEqual(h.corrections, []);
++ c.settleRadioToolHandoffReservation(reservation, { commit: false });
++ await tick();
++ assert.equal(h.attempts.length, 2, 'a cancelled result cannot be resumed');
++});
diff --cc src/voice/realtimeSession.js
index c6e709be5,0220961f8..0d9eca872
--- a/src/voice/realtimeSession.js
+++ b/src/voice/realtimeSession.js
@@@ -14,14 -14,8 +14,9 @@@ export function createRealtimeSession(
});
return {
controller,
- capabilities: {
- costControls: true,
- pushToTalk: true,
- advisoryLimit:
- 'OpenAI voice sessions have a time limit. When a session expires, start voice again for a new conversation.',
- },
+ capabilities: { costControls: true, pushToTalk: true },
start: (settings) => controller.start(settings),
+ getStartOptions: () => ({ pushToTalk: Boolean(controller.pushToTalkMode) }),
stop: (settings) => controller.stop(settings),
sendText: (text) => controller.sendTextCommand(text),
sendMapEvent: (event) => controller.notifyMapEvent(event),
diff --cc src/voice/session.js
index 7d7293147,f55b7657e..21400f04c
--- a/src/voice/session.js
+++ b/src/voice/session.js
@@@ -168,8 -147,8 +147,9 @@@ export function createVoiceSession({ cr
},
async start(options) {
if (disposed || !['idle', 'error'].includes(state)) return;
-- emit({ type: 'state', state: 'connecting' });
const attempt = ++startAttempt;
++ emit({ type: 'state', state: 'connecting' });
++ if (disposed || attempt !== startAttempt) return;
try {
await adapter.start(options);
} catch (error) {
@@@ -185,19 -164,13 +165,18 @@@
stop(options = {}) {
if (options.removeUi) return dispose();
if (disposed) return;
-- startAttempt++;
++ const attempt = ++startAttempt;
cancelActions();
try {
adapter.stop(options);
} finally {
- if (options.preserveStatus)
- emit({ type: 'stop', preserveStatus: true });
- else
- emit({
- type: 'state',
- state: 'idle',
- detail: 'Voice off',
- });
- if (!options.preserveStatus)
++ if (
++ !options.preserveStatus &&
++ !disposed &&
++ attempt === startAttempt &&
++ state !== 'idle'
++ )
+ emit({ type: 'state', state: 'idle', detail: 'Voice off' });
}
},
sendText: (text) => !disposed && adapter.sendText(text),
diff --cc src/voice/session.test.mjs
index e061e96c4,9bd016f20..8e4d37385
--- a/src/voice/session.test.mjs
+++ b/src/voice/session.test.mjs
@@@ -6,9 -6,9 +6,10 @@@ import
voiceCardView,
} from './voiceCardPresentation.js';
import { createVoiceSession } from './session.js';
++import { createRealtimeSession } from './realtimeSession.js';
import { realtimeSessionEvent } from './realtimeEvents.js';
import { createVoiceCommands } from './sessionCommands.js';
- import { VoiceCardControls } from './voiceCard.js';
+ import { describeUnsavedWork } from '../i18n/index.js';
function deferred() {
let resolve;
@@@ -434,123 -441,3 +442,189 @@@ test('a late rejection cannot settle a
);
f.session.destroy();
});
+
- test('a supplied adapter retains cost controls without a provider selector', () => {
- const previous = globalThis.window;
- globalThis.window = new EventTarget();
- const button = new EventTarget();
- button.setAttribute = () => {};
- const ui = {
- root: { dataset: {}, remove() {} },
- button,
- status: {},
- detail: {},
- providerField: { hidden: true, remove() {} },
- providerSelect: new EventTarget(),
- tierButton: { hidden: true },
- costValue: { hidden: true },
- };
- let controls;
- try {
- controls = createVoiceCommands({
- runner: async () => ({ ok: true }),
- createControl: () => ui,
- createSession: () => ({
- capabilities: { costControls: true, pushToTalk: true },
- start() {},
- stop() {},
- sendText() {},
- sendMapEvent() {},
- }),
- });
- assert.equal(ui.providerField.hidden, true);
- assert.equal(ui.tierButton.hidden, false);
- assert.equal(ui.costValue.hidden, false);
- } finally {
- controls?.session.destroy();
- globalThis.window = previous;
- }
- });
-
- test('session stamps host controls instead of accepting a tool caller capability claim', async () => {
- for (const available of [false, true]) {
- let hooks;
- let received;
- const session = createVoiceSession({
- providerDropdown: () => available,
- runner: async (_name, _args, options) => {
- received = options;
- return { ok: true };
++function startReentrancyFixture() {
++ let starts = 0;
++ let stops = 0;
++ const settings = [];
++ const session = createVoiceSession({
++ runner: async () => ({ ok: true }),
++ createAdapter: ({ emit }) => ({
++ async start(options) {
++ starts++;
++ settings.push(options);
++ emit({ type: 'state', state: 'listening' });
+ },
- createAdapter(value) {
- hooks = value;
- return {
- start() {
- hooks.emit({ type: 'state', state: 'listening' });
- },
- stop() {},
- sendText() {},
- sendMapEvent() {},
- };
++ stop() {
++ stops++;
+ },
++ sendText() {},
++ sendMapEvent() {},
++ }),
++ });
++ return { session, settings, starts: () => starts, stops: () => stops };
++}
++
++for (const action of ['stop', 'destroy']) {
++ test(`initial connecting observer ${action} prevents adapter acquisition`, async () => {
++ const f = startReentrancyFixture();
++ const unsubscribe = f.session.subscribe((event) => {
++ if (event.type === 'state' && event.state === 'connecting') {
++ unsubscribe();
++ f.session[action]();
++ }
+ });
- await session.start();
- await hooks.runAction(
- 'get_current_view_state',
- {},
- { providerDropdown: !available },
++ await f.session.start();
++ assert.equal(
++ f.starts(),
++ 0,
++ 'cancelled attempt must not call adapter.start',
+ );
- assert.equal(received.providerDropdown, available);
- session.destroy();
- }
- });
++ assert.equal(f.stops(), 1);
++ assert.equal(f.session.state, 'idle');
++ if (action === 'stop') {
++ await f.session.start();
++ assert.equal(f.starts(), 1, 'later explicit Start remains usable');
++ assert.equal(f.session.state, 'listening');
++ }
++ f.session.destroy();
++ });
++}
+
- test('provider policy revokes resources while preserving committed results and suppressing progress', async () => {
- const gate = deferred();
- const policy = new AbortController();
- let received;
- const events = [];
- const f = fixture(async (_name, _args, options) => {
- received = options;
- await gate.promise;
- options.progress({ step: 'late', label: 'late' });
- return { ok: true, changed: true, action: 'committed' };
++test('preserveStatus Stop still prevents adapter acquisition', async () => {
++ const f = startReentrancyFixture();
++ const unsubscribe = f.session.subscribe((event) => {
++ if (event.type === 'state' && event.state === 'connecting') {
++ unsubscribe();
++ f.session.stop({ preserveStatus: true });
++ }
+ });
- f.session.subscribe((event) => events.push(event));
+ await f.session.start();
- const pending = f.hooks.runAction(
- 'committed',
- {},
- { providerPolicySignal: policy.signal },
- );
- policy.abort();
- assert.equal(received.signal.aborted, true);
- assert.equal(received.isCurrent(), false);
- gate.resolve();
- assert.equal((await pending).changed, true);
++ assert.equal(f.starts(), 0);
+ assert.equal(
- events.some((e) => e.type === 'progress'),
- false,
++ f.session.state,
++ 'connecting',
++ 'preserved state is not ownership',
+ );
++ f.session.stop();
++ await f.session.start();
++ assert.equal(f.starts(), 1);
+ f.session.destroy();
+});
+
- test('Stop still revokes a committed result while provider policy signal exists', async () => {
- const gate = deferred();
- const policy = new AbortController();
- const f = fixture(async () => {
- await gate.promise;
- return { ok: true, changed: true };
++test('Stop and explicit reentrant successor start acquire only for the successor', async () => {
++ const f = startReentrancyFixture();
++ let successor;
++ const unsubscribe = f.session.subscribe((event) => {
++ if (event.type === 'state' && event.state === 'connecting') {
++ unsubscribe();
++ f.session.stop();
++ successor = f.session.start();
++ }
+ });
+ await f.session.start();
- const pending = f.hooks.runAction(
- 'committed',
- {},
- { providerPolicySignal: policy.signal },
- );
- policy.abort();
++ await successor;
++ assert.equal(f.starts(), 1);
++ assert.equal(f.session.state, 'listening');
++ f.session.destroy();
++});
++
++test('ordinary start forwards caller settings once and remains stoppable', async () => {
++ const f = startReentrancyFixture();
++ const settings = { pushToTalk: true };
++ await f.session.start(settings);
++ assert.equal(f.settings.length, 1);
++ assert.equal(f.settings[0], settings);
++ assert.equal(f.starts(), 1);
++ assert.equal(f.session.state, 'listening');
+ f.session.stop();
- gate.resolve();
- await assert.rejects(pending, { name: 'AbortError' });
++ assert.equal(f.session.state, 'idle');
+ f.session.destroy();
+});
++
++for (const emitsIdle of [false, true]) {
++ for (const outcome of ['normal', 'preserveStatus', 'throw']) {
++ test(`stop preserves custom adapter contract: emitsIdle=${emitsIdle}, ${outcome}`, async (t) => {
++ let adapter;
++ const calls = [];
++ const events = [];
++ const failure = new Error('Controlled stop failure');
++ const session = createVoiceSession({
++ runner: async () => ({}),
++ createAdapter: ({ emit }) =>
++ (adapter = {
++ async start() {
++ emit({ type: 'state', state: 'listening' });
++ },
++ stop(settings = {}) {
++ calls.push({ receiver: this, settings });
++ if (settings.removeUi) return;
++ if (emitsIdle && !settings.preserveStatus)
++ emit({ type: 'state', state: 'idle' });
++ if (outcome === 'throw') throw failure;
++ return 'adapter-only return';
++ },
++ sendText() {},
++ sendMapEvent() {},
++ }),
++ });
++ t.after(() => session.destroy());
++ session.subscribe((event) => events.push(event));
++ await session.start();
++ events.length = 0;
++ const settings =
++ outcome === 'preserveStatus' ? { preserveStatus: true } : {};
++ if (outcome === 'throw')
++ assert.throws(
++ () => session.stop(settings),
++ (error) => error === failure,
++ );
++ else assert.equal(session.stop(settings), undefined);
++ assert.equal(calls[0].receiver, adapter);
++ assert.equal(calls[0].settings, settings);
++ assert.equal(
++ session.state,
++ outcome === 'preserveStatus' ? 'listening' : 'idle',
++ );
++ assert.equal(
++ events.filter(
++ (event) => event.type === 'state' && event.state === 'idle',
++ ).length,
++ outcome === 'preserveStatus' ? 0 : 1,
++ );
++ });
++ }
++}
++
++test('actual default OpenAI adapter stop publishes one common idle', (t) => {
++ const events = [];
++ const ui = {
++ root: {
++ dataset: {},
++ querySelectorAll: () => [],
++ classList: { remove() {} },
++ remove() {},
++ },
++ status: {},
++ detail: {},
++ };
++ const runner = async () => ({});
++ const session = createVoiceSession({
++ runner,
++ createAdapter: (hooks) =>
++ createRealtimeSession({ ...hooks, runner, ui, debugSink() {} }),
++ });
++ t.after(() => session.destroy());
++ session.subscribe((event) => events.push(event));
++ // Exercise the real stop path without acquiring microphone/WebRTC resources.
++ session.adapter.controller.setStatus('listening', 'Controlled active state');
++ events.length = 0;
++ session.stop();
++ assert.equal(
++ events.filter((event) => event.type === 'state' && event.state === 'idle')
++ .length,
++ 1,
++ );
++ assert.equal(session.state, 'idle');
++ assert.equal(session.adapter.controller.status, 'idle');
++});
diff --cc src/voice/sessionCommands.js
index e4c183fbd,05bbcc501..9431555df
--- a/src/voice/sessionCommands.js
+++ b/src/voice/sessionCommands.js
@@@ -2,9 -2,7 +2,8 @@@ import { createVoiceControl, voiceStatu
import { createVoiceSession } from './session.js';
import { VoiceCardControls } from './voiceCard.js';
import { PointerReticle } from './pointerReticle.js';
-
- const DEFAULT_ERROR_HINT =
- 'Check microphone permission and network access, then try again.';
++import { VOICE_PROVIDERS } from './providerCapabilities.js';
+ import { msg, registerUnsavedWork, t } from '../i18n/index.js';
function createDefaultReticle(pointer) {
const element = pointer?.element;
@@@ -27,37 -25,15 +26,21 @@@ export function createVoiceCommands(
signal,
debugSink,
createControl = createVoiceControl,
+ resetExisting = true,
++ disposeRunner = true,
+ provider,
+ supportedProviders,
+ onProviderChange,
+ onSessionEvent,
- disposeRunner = true,
createCard = (options) => new VoiceCardControls(options),
pointer = null,
referents = null,
createReticle = createDefaultReticle,
}) {
- window.__gevVoiceCommands?.stop?.({ removeUi: true });
+ if (resetExisting) window.__gevVoiceCommands?.stop?.({ removeUi: true });
const ui = createControl({ reset: true });
- const hasProviderChoice = () =>
- new Set(
- Array.from(ui.providerSelect?.options || [], (option) =>
- option.disabled ? null : option.value,
- ).filter(Boolean),
- ).size > 1;
const session = createVoiceSession({
runner,
- providerDropdown: () =>
- Boolean(
- onProviderChange &&
- ui.providerSelect &&
- !ui.providerSelect.disabled &&
- !ui.providerSelect.hidden &&
- ui.providerField &&
- hasProviderChoice() &&
- !ui.providerField.hidden,
- ),
signal,
createAdapter: (hooks) =>
createSession({
@@@ -74,27 -50,6 +57,34 @@@
});
const adapter = session.adapter;
const capabilities = adapter.capabilities || {};
+ const providerHandler = () => onProviderChange?.(ui.providerSelect.value);
+ if (ui.providerSelect && onProviderChange) {
+ if (supportedProviders && ui.providerSelect.replaceChildren) {
+ const doc = ui.providerSelect.ownerDocument;
+ ui.providerSelect.replaceChildren(
+ ...supportedProviders.map((name) => {
+ const option = doc.createElement('option');
+ option.value = name;
- option.textContent = name === 'openai' ? 'OpenAI' : 'Gemini';
++ option.textContent = VOICE_PROVIDERS[name].label;
+ return option;
+ }),
+ );
+ }
+ ui.providerSelect.value = provider;
- if (capabilities.advisoryLimit)
- ui.providerSelect.title = `Changing provider reconnects voice if it is on. ${capabilities.advisoryLimit}`;
- ui.root.dataset.provider = provider;
++ ui.providerSelect.title = [
++ t('Changing provider reconnects voice if it is on.'),
++ capabilities.advisoryLimit,
++ ]
++ .filter(Boolean)
++ .join(' ');
+ ui.providerSelect.addEventListener('change', providerHandler);
++ ui.root.dataset.provider = provider;
+ }
- if (ui.providerField)
- ui.providerField.hidden = !onProviderChange || !hasProviderChoice();
++ const hasProviderChoice = Boolean(
++ onProviderChange && supportedProviders?.length > 1,
++ );
++ if (ui.providerField) ui.providerField.hidden = !hasProviderChoice;
++ ui.root.dataset.providerChoice = String(hasProviderChoice);
if (ui.tierButton) ui.tierButton.hidden = !capabilities.costControls;
if (ui.costValue) ui.costValue.hidden = !capabilities.costControls;
if (!capabilities.pushToTalk) {
@@@ -104,15 -60,17 +95,18 @@@
// Retain the existing controller's inspection surface for browser tools.
const controls = adapter.controller || session;
controls.session = session;
+ controls.ui = ui;
const updateStatus = session.subscribe((event) => {
- onSessionEvent?.(event);
if (event.type !== 'state') return;
ui.root.dataset.status = event.state;
- ui.status.textContent =
- event.state === 'idle' ? 'OFF' : event.state.toUpperCase();
+ // States are machine values; only the label is translated.
+ ui.status.textContent = voiceStatusLabel(event.state);
+ // The portable session reports 'Voice off' in English: show the idle
+ // label instead. Other details are provider messages, shown as they come.
+ const idle = event.state === 'idle';
+ const detail = event.detail === 'Voice off' ? '' : event.detail;
ui.detail.textContent =
- event.detail || (event.state === 'idle' ? 'Voice off' : 'Voice active');
+ detail || (idle ? t('Voice off') : t('Voice active'));
ui.button.setAttribute('aria-pressed', String(session.isActive()));
if (ui.errorDetail)
ui.errorDetail.textContent =
@@@ -148,6 -101,6 +137,10 @@@
});
controls.pointer = pointer;
controls.referents = referents;
++ // Forward last: a host observer may synchronously replace or stop this mount.
++ const forwardEvents = onSessionEvent
++ ? session.subscribe(onSessionEvent)
++ : null;
const annotationUnsubscribe = annotations?.onOutlineEvent?.((event) => {
card?.outline(event);
session.sendMapEvent({ type: 'map_annotation_outline', ...event });
@@@ -158,40 -115,34 +155,26 @@@
else void session.start({ pushToTalk: false });
};
ui.button.addEventListener('click', buttonHandler);
-- session.signal.addEventListener(
-- 'abort',
-- () => {
-- ui.button.removeEventListener('click', buttonHandler);
- ui.providerSelect?.removeEventListener('change', providerHandler);
- unregisterUnsavedWork();
-- annotationUnsubscribe?.();
-- updateStatus();
-- updateCard?.();
-- updatePointer();
-- reticle?.destroy();
-- card?.destroy();
- pointer?.clear();
- referents?.clear();
- runner.resetConversation?.();
- if (disposeRunner) runner.dispose?.();
- runner.dispose?.();
-- ui.root.remove();
-- },
-- { once: true },
-- );
-- if (session.disposed) {
++ let cleaned = false;
++ const cleanup = () => {
++ if (cleaned) return;
++ cleaned = true;
ui.button.removeEventListener('click', buttonHandler);
+ ui.providerSelect?.removeEventListener('change', providerHandler);
+ unregisterUnsavedWork();
annotationUnsubscribe?.();
updateStatus();
updateCard?.();
updatePointer();
++ forwardEvents?.();
reticle?.destroy();
card?.destroy();
- pointer?.clear();
- referents?.clear();
- runner.resetConversation?.();
- runner.dispose?.();
+ if (disposeRunner) runner.dispose?.();
ui.root.remove();
-- } else adapter.bindControls?.();
++ };
++ session.signal.addEventListener('abort', cleanup, { once: true });
++ if (session.disposed) cleanup();
++ else adapter.bindControls?.();
window.__gevVoiceCommands = controls;
return controls;
}