fix(voice): address review of typed AI chat

Typed chat sessions no longer end on the voice inactivity timeout, and a
failed or stopped reply keeps the conversation: Stop cancels only the
reply in progress, and map actions that already ran stay in the model's
context. Each upstream request and map action gets its own deadline, old
tool results shrink instead of the history overflowing, and step limits,
a missing or rejected key, the OAuth lock and throttling each get their
own message.

- Server: OpenAI chat is off under GEV_PREFER_CODEX_OAUTH; chat throttles
  default to the provider's throttle; replies carry API_KEY_MISSING,
  API_KEY_REJECTED, CODEX_OAUTH_REQUIRED and RATE_LIMITED codes; upstream
  Retry-After passes through, and a rejected key (Gemini's invalid-key 400
  included) cools down for a minute
- Pinokio forwards the chat throttle settings
- UI: the reply reveal publishes only the message list; the border orbit
  runs only while busy; layers attach with a button or Enter; the log is
  aria-busy while a reply types out; auto-scroll respects a reader who
  scrolled up; Escape closes the attach menu; the chat gear says Settings;
  a note says chat bills the OpenAI key when voice uses ChatGPT sign-in
- Layout does less work while panel height animates; unused blurs removed
- Gemini voice start ends chat; the voice preview clears on every new
  session
- Tests for the route gates, client limits, attachments and the fixes
This commit is contained in:
manjunath22466 committed 2026-11-03 22:01:08 +05:30
1 parent 11cd0142ac
commit da8b0dd8cd
49 files changed
+2121 -160

No files matched your search

+74 -8
View File
@@ -1,5 +1,9 @@
import { readRequestBody } from './request.js';
import { clientKey, makeCostRateLimiter } from './rate-limit.js';
import {
clientKey,
makeCostRateLimiter,
resolvePerMinuteCap,
} from './rate-limit.js';
import { waitForSignal } from '../../../src/sources/requestDeadline.js';
import { readResponseJsonCapped } from '../../../src/sources/httpBody.js';
import { isGeminiRequestOriginAllowed } from '../gemini/request.js';
@@ -7,6 +11,29 @@ import { parseUsage } from './textTools.js';
const MAX_BYTES = 512 * 1024;
const FAILURE = 'Could not connect. Try again.';
// A rejected key is not retried upstream for this long, unless the key changes.
const REJECTED_KEY_COOLDOWN_MS = 60_000;
// Gemini answers an invalid key with 400 and this reason, not 401 or 403.
const KEY_REJECTED_REASON = 'API_KEY_INVALID';
async function rejectsKey(response, signal) {
if ([401, 403].includes(response.status)) return true;
if (response.status !== 400) return false;
try {
const body = await readResponseJsonCapped(response, 16 * 1024, signal);
return JSON.stringify(body).includes(KEY_REJECTED_REASON);
} catch {
return false;
}
}
// Pass through only a delay in whole seconds, capped at an hour.
function upstreamRetryAfter(response) {
const value = String(response.headers?.get?.('retry-after') ?? '').trim();
if (!/^\d{1,6}$/.test(value)) return null;
return String(Math.min(Math.max(Number(value), 1), 3600));
}
export function createTextChatHandler({
provider,
prepare,
@@ -16,21 +43,32 @@ export function createTextChatHandler({
resolveHost = () => process.env.HOST,
resolveAllowedHosts = () => process.env.GEV_ALLOWED_HOSTS,
resolveRateLimit = () =>
process.env[`GEV_RATELIMIT_${provider.toUpperCase()}_CHAT_PER_MIN`] ?? '60',
process.env[`GEV_RATELIMIT_${provider.toUpperCase()}_CHAT_PER_MIN`],
// An unset chat throttle follows the provider's own cost throttle.
resolveProviderRateLimit = () => undefined,
providerPerMin = 30,
// Returns { error, code } when the route must refuse before any key is used.
refuse = () => null,
now = Date.now,
timeoutMs = 60000,
} = {}) {
let limiter;
let rejected = null;
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, value) => {
const reply = (status, value, code) => {
if (req.aborted || res.destroyed || res.writableEnded) return;
res.statusCode = status;
if (status >= 400) res.setHeader('Connection', 'close');
res.end(
JSON.stringify(typeof value === 'string' ? { error: value } : value),
JSON.stringify(
typeof value === 'string'
? { error: value, ...(code ? { code } : {}) }
: value,
),
);
};
if (req.method !== 'POST') {
@@ -52,13 +90,32 @@ export function createTextChatHandler({
!isGeminiRequestOriginAllowed(req, resolveHost(), resolveAllowedHosts())
)
return reply(403, FAILURE);
const refusal = refuse();
if (refusal) return reply(503, refusal.error, refusal.code);
const apiKey = String(resolveApiKey() || '').trim();
if (!apiKey) return reply(503, 'Add an API key in Provider Settings');
if (!apiKey)
return reply(
503,
'Add an API key in Provider Settings',
'API_KEY_MISSING',
);
if (rejected && (rejected.key !== apiKey || now() >= rejected.until))
rejected = null;
if (rejected) {
res.setHeader(
'Retry-After',
String(Math.max(1, Math.ceil((rejected.until - now()) / 1000))),
);
return reply(502, FAILURE, 'API_KEY_REJECTED');
}
if (limiter === undefined)
limiter = makeCostRateLimiter(resolveRateLimit(), 60);
limiter = makeCostRateLimiter(
resolveRateLimit(),
resolvePerMinuteCap(resolveProviderRateLimit(), providerPerMin),
);
if (limiter && !limiter(clientKey(req))) {
res.setHeader('Retry-After', '60');
return reply(429, FAILURE);
return reply(429, FAILURE, 'RATE_LIMITED');
}
if (
!/^application\/json(?:\s*;|$)/i.test(req.headers['content-type'] || '')
@@ -99,10 +156,19 @@ export function createTextChatHandler({
if (response.redirected || (response.url && response.url !== endpoint))
throw new Error('Unexpected destination');
if (!response.ok) {
if (await rejectsKey(response, lifetime.signal)) {
void response.body?.cancel().catch(() => {});
rejected = { key: apiKey, until: now() + REJECTED_KEY_COOLDOWN_MS };
return reply(502, FAILURE, 'API_KEY_REJECTED');
}
void response.body?.cancel().catch(() => {});
if (![429, 503].includes(response.status)) return reply(502, FAILURE);
const retryAfter = upstreamRetryAfter(response);
if (retryAfter) res.setHeader('Retry-After', retryAfter);
return reply(
[429, 503].includes(response.status) ? response.status : 502,
response.status,
FAILURE,
response.status === 429 ? 'RATE_LIMITED' : undefined,
);
}
const data = await readResponseJsonCapped(
+6
View File
@@ -4,6 +4,9 @@ import { textInstructions } from '../common/textInstructions.js';
import { GEV_REALTIME_TOOLS } from '../openai/tools.js';
import { normalizeGeminiModel } from './config.js';
// The Gemini token route's throttle default (GEV_RATELIMIT_GEMINI_PER_MIN).
export const GEMINI_DEFAULT_PER_MIN = 30;
const object = (value) =>
value && typeof value === 'object' && !Array.isArray(value);
const keys = (value, allowed) =>
@@ -80,12 +83,15 @@ export function createGeminiChatHandler({
resolveChatModel = () =>
process.env.GEMINI_CHAT_MODEL || 'gemini-3.5-flash-lite',
resolveApiKey = () => process.env.GEMINI_API_KEY,
resolveProviderRateLimit = () => process.env.GEV_RATELIMIT_GEMINI_PER_MIN,
...options
} = {}) {
return createTextChatHandler({
...options,
provider: 'gemini',
resolveApiKey,
resolveProviderRateLimit,
providerPerMin: GEMINI_DEFAULT_PER_MIN,
prepare(input) {
const model = normalizeGeminiModel(resolveChatModel());
if (!model || /live|audio|tts/i.test(model)) return { errorStatus: 503 };
+17
View File
@@ -1,4 +1,6 @@
import { createTextChatHandler } from '../common/textChat.js';
import { preferCodexOAuth } from './codex-auth.js';
import { OPENAI_DEFAULT_PER_MIN } from './rate-limit.js';
import { invalidCalls } from '../common/textTools.js';
import { textInstructions } from '../common/textInstructions.js';
import { GEV_REALTIME_TOOLS } from './tools.js';
@@ -66,12 +68,27 @@ export function createOpenAiChatHandler({
tools = GEV_REALTIME_TOOLS,
resolveApiKey = () => process.env.OPENAI_API_KEY,
resolveChatModel = () => process.env.OPENAI_CHAT_MODEL || 'gpt-4.1-mini',
resolveProviderRateLimit = () => process.env.GEV_RATELIMIT_OPENAI_PER_MIN,
environment = process.env,
...options
} = {}) {
return createTextChatHandler({
...options,
provider: 'openai',
resolveApiKey,
resolveProviderRateLimit,
providerPerMin: OPENAI_DEFAULT_PER_MIN,
// Chat can only bill the API key, which this operator lock forbids.
refuse() {
let error =
'ChatGPT OAuth is required by GEV_PREFER_CODEX_OAUTH, and typed OpenAI chat needs an API key.';
try {
if (!preferCodexOAuth(environment)) return null;
} catch (invalid) {
error = invalid.message;
}
return { error, code: 'CODEX_OAUTH_REQUIRED' };
},
prepare(input) {
const model = String(resolveChatModel()).trim();
if (