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

112 lines
3.5 KiB
JavaScript

const crypto = require('crypto');
const { logger } = require('@hanzochat/data-schemas');
const { parseConvo } = require('@hanzochat/data-provider');
const { sendEvent, handleError, sanitizeMessageForTransmit } = require('@hanzochat/api');
const { saveMessage, getMessages } = require('~/models/Message');
const { getConvo } = require('~/models/Conversation');
/**
* Processes an error with provided options, saves the error message and sends a corresponding SSE response
* @async
* @param {object} req - The request.
* @param {object} res - The response.
* @param {object} options - The options for handling the error containing message properties.
* @param {object} options.user - The user ID.
* @param {string} options.sender - The sender of the message.
* @param {string} options.conversationId - The conversation ID.
* @param {string} options.messageId - The message ID.
* @param {string} options.parentMessageId - The parent message ID.
* @param {string} options.text - The error message.
* @param {boolean} options.shouldSaveMessage - [Optional] Whether the message should be saved. Default is true.
* @param {function} callback - [Optional] The callback function to be executed.
*/
const sendError = async (req, res, options, callback) => {
const {
user,
sender,
conversationId,
messageId,
parentMessageId,
text,
shouldSaveMessage,
...rest
} = options;
const errorMessage = {
sender,
messageId: messageId ?? crypto.randomUUID(),
conversationId,
parentMessageId,
unfinished: false,
error: true,
final: true,
text,
isCreatedByUser: false,
...rest,
};
if (callback && typeof callback === 'function') {
await callback();
}
if (shouldSaveMessage) {
await saveMessage(
req,
{ ...errorMessage, user },
{
context: 'api/server/utils/streamResponse.js - sendError',
},
);
}
if (!errorMessage.error) {
const requestMessage = { messageId: parentMessageId, conversationId };
let query = [],
convo = {};
try {
query = await getMessages(requestMessage);
convo = await getConvo(user, conversationId);
} catch (err) {
logger.error('[sendError] Error retrieving conversation data:', err);
convo = parseConvo(errorMessage);
}
return sendEvent(res, {
final: true,
requestMessage: sanitizeMessageForTransmit(query?.[0] ?? requestMessage),
responseMessage: errorMessage,
conversation: convo,
});
}
handleError(res, errorMessage);
};
/**
* Sends the response based on whether headers have been sent or not.
* @param {ServerRequest} req - The server response.
* @param {Express.Response} res - The server response.
* @param {Object} data - The data to be sent.
* @param {string} [errorMessage] - The error message, if any.
* @param {number} [status] - The status the thrower chose; 500 when it knew none.
* Answering every failure with 500 erases the only part of a refusal a client
* can act on — the defect `controllers/agents/request.js` already fixed for the
* agents path. A 402 is a paywall, not an outage.
*/
const sendResponse = (req, res, data, errorMessage, status) => {
if (!res.headersSent) {
if (errorMessage) {
return res.status(status ?? 500).json({ error: errorMessage });
}
return res.json(data);
}
if (errorMessage) {
return sendError(req, res, { ...data, text: errorMessage });
}
return sendEvent(res, data);
};
module.exports = {
sendError,
sendResponse,
};