Files
zeekayandHanzo Dev 41c39bf825 chat: a 402 is a paywall, chat is the default mode, a guest bearer survives a reload
Three defects that met at the same place: a new visitor's first message failed,
and nothing on screen said why.

1. A gateway 402 rendered as "Something went wrong on our side".

   Measured live: signed-in user, model `enso`, real message. The stored message
   was `{"type":"error","error":"An error occurred while processing the request:
   402 invalid API key"}` — prose. `Messages/Content/Error.tsx` dispatches on a
   CODE, so a paywall read as an outage to someone holding a credit card.

   The status was never lost upstream (langchain re-throws the OpenAI client's
   `APIError` untouched for a 402, so `err.status === 402` is right there); it was
   thrown away by the carriers. `server/utils/refusal.js` is now the ONE place
   that names a failure — the thrower's code wins, else the status names it — and
   both carriers use it: the agent run's error content part
   (`controllers/agents/client.js`) and `handleAbortError`, which used to pass a
   message through only when it happened to contain the substring `"type"`.
   `middleware/error.js#sendResponse` no longer answers every failure with 500.
   This is the rule `routes/ask.js#relayStatus` already applies to the answer
   engine, and the shape `controllers/agents/request.js` already answers with.

   Client side, `errorKey` now also reads an OpenAI-shaped nested body
   (`{error:{code}}`), and `insufficient_quota` renders the add-credit action
   instead of upstream's "set up your own API key" — there is no key to set on
   hanzo.chat; the money lives at billing.hanzo.ai. The generic fallback stays
   for failures that genuinely name nothing.

2. The mode selector opened on Search, which is sign-in gated.

   Search relays to cloud `/v1/ask` and needs a real principal, so an anonymous
   visitor's FIRST message was a 401 rendered as an inline error. Chat is the
   guest-scoped preview, and when even that is refused its submit path opens the
   login gate. It is also what the chips already say — `chat` is listed first.

3. The guest mint 429'd after a handful of page loads, then failed silently.

   The client DISCARDED a live guest bearer on every page load and minted a fresh
   one, so `guestTokenLimiter` was measuring page views rather than mint-spam —
   and behind Cloudflare one CF-Connecting-IP can be a whole office. The token
   already carries its own lifetime, so it is now reused for it (sessionStorage,
   not localStorage: a bearer must not outlive the visit on a shared browser). A
   visit costs one mint per expiry window instead of one per paint; the ceiling
   itself is unchanged, because the number was never the fix.

   And when the mint IS refused, say so. It used to pass in total silence —
   `Root` fell through to the marketing page, so a 429 on an auxiliary token read
   as a site with no composer and no explanation. `acquireGuest` now opens the
   ONE login gate with a new reason, `unavailable`, and `Root` mounts that gate
   alongside the landing. Because auth resolves before the shell paints, the gate
   picks up a reason that landed while it was unmounted; reading consumes it, so
   a dismissal is never undone by a remount.

Tests: api 2287 -> 2312 passing, client 1792 -> 1809 passing, 0 new failures
(pre-existing failures unchanged at 408 api / 503 client). Lint 893 -> 892
problems — one pre-existing prettier error fixed, none introduced.

Co-authored-by: Hanzo Dev <[email protected]>
2026-08-01 22:41:16 -07:00

142 lines
4.7 KiB
JavaScript

// errorHandler.js
const { logger } = require('@hanzochat/data-schemas');
const { CacheKeys, ViolationTypes } = require('@hanzochat/data-provider');
const { sendResponse } = require('~/server/middleware/error');
const { recordUsage } = require('~/server/services/Threads');
const { getConvo } = require('~/models/Conversation');
const getLogStores = require('~/cache/getLogStores');
/**
* @typedef {Object} ErrorHandlerContext
* @property {OpenAIClient} openai - The OpenAI client
* @property {string} run_id - The run ID
* @property {boolean} completedRun - Whether the run has completed
* @property {string} assistant_id - The assistant ID
* @property {string} conversationId - The conversation ID
* @property {string} parentMessageId - The parent message ID
* @property {string} responseMessageId - The response message ID
* @property {string} endpoint - The endpoint being used
* @property {string} cacheKey - The cache key for the current request
*/
/**
* @typedef {Object} ErrorHandlerDependencies
* @property {ServerRequest} req - The Express request object
* @property {Express.Response} res - The Express response object
* @property {() => ErrorHandlerContext} getContext - Function to get the current context
* @property {string} [originPath] - The origin path for the error handler
*/
/**
* Creates an error handler function with the given dependencies
* @param {ErrorHandlerDependencies} dependencies - The dependencies for the error handler
* @returns {(error: Error) => Promise<void>} The error handler function
*/
const createErrorHandler = ({ req, res, getContext, originPath = '/assistants/chat/' }) => {
const cache = getLogStores(CacheKeys.ABORT_KEYS);
/**
* Handles errors that occur during the chat process
* @param {Error} error - The error that occurred
* @returns {Promise<void>}
*/
return async (error) => {
const {
openai,
run_id,
endpoint,
cacheKey,
completedRun,
assistant_id,
conversationId,
parentMessageId,
responseMessageId,
} = getContext();
const defaultErrorMessage =
'The Assistant run failed to initialize. Try sending a message in a new conversation.';
const messageData = {
assistant_id,
conversationId,
parentMessageId,
sender: 'System',
user: req.user.id,
shouldSaveMessage: false,
messageId: responseMessageId,
endpoint,
};
if (error.message === 'Run cancelled') {
return res.end();
} else if (error.message === 'Request closed' && completedRun) {
return;
} else if (error.message === 'Request closed') {
logger.debug(`[${originPath}] Request aborted on close`);
} else if (/Files.*are invalid/.test(error.message)) {
const errorMessage = `Files are invalid, or may not have uploaded yet.${
endpoint === 'azureAssistants'
? " If using Azure OpenAI, files are only available in the region of the assistant's model at the time of upload."
: ''
}`;
return sendResponse(req, res, messageData, errorMessage);
} else if (error?.message?.includes('string too long')) {
return sendResponse(
req,
res,
messageData,
'Message too long. The Assistants API has a limit of 32,768 characters per message. Please shorten it and try again.',
);
} else if (error?.message?.includes(ViolationTypes.TOKEN_BALANCE)) {
return sendResponse(req, res, messageData, error.message, error.status);
} else {
logger.error(`[${originPath}]`, error);
}
if (!openai || !run_id) {
return sendResponse(req, res, messageData, defaultErrorMessage);
}
await new Promise((resolve) => setTimeout(resolve, 2000));
try {
const status = await cache.get(cacheKey);
if (status === 'cancelled') {
logger.debug(`[${originPath}] Run already cancelled`);
return res.end();
}
await cache.delete(cacheKey);
} catch (error) {
logger.error(`[${originPath}] Error cancelling run`, error);
}
await new Promise((resolve) => setTimeout(resolve, 2000));
let run;
try {
await recordUsage({
...run.usage,
model: run.model,
user: req.user.id,
conversationId,
});
} catch (error) {
logger.error(`[${originPath}] Error fetching or processing run`, error);
}
let finalEvent;
try {
finalEvent = {
final: true,
conversation: await getConvo(req.user.id, conversationId),
};
} catch (error) {
logger.error(`[${originPath}] Error finalizing error process`, error);
return sendResponse(req, res, messageData, 'The Assistant run failed');
}
return sendResponse(req, res, finalEvent);
};
};
module.exports = { createErrorHandler };