Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(llm): carry provider error context beside the message
Elian Dorand51dace6c8d3
diff --git a/apps/client/src/services/llm_chat.spec.ts b/apps/client/src/services/llm_chat.spec.tsindex 878f99e9f8..9c2d5756de 100644--- a/apps/client/src/services/llm_chat.spec.ts+++ b/apps/client/src/services/llm_chat.spec.ts@@ -229,13 +229,20 @@ describe("streamChatCompletion", () => {expect(cb.onUsage).not.toHaveBeenCalled();});- it("forwards an error event to onError", async () => {- const chunks = [`data: ${JSON.stringify({ type: "error", error: "model failed" })}\n`];+ it("forwards an error event to onError, with the provider-call details when present", async () => {+ const errorDetails = { statusCode: 400, url: "https://api.test/v1", responseBody: "{}" };+ const chunks = [+ `data: ${JSON.stringify({ type: "error", error: "model failed" })}\n`,+ `data: ${JSON.stringify({ type: "error", error: "api failed", errorDetails })}\n`+ ];vi.stubGlobal("fetch", vi.fn(async () => makeStreamResponse(chunks)));const cb = makeCallbacks();await streamChatCompletion(messages, config, cb);- expect(cb.onError).toHaveBeenCalledWith("model failed");+ expect(cb.onError.mock.calls).toEqual([+ ["model failed", undefined],+ ["api failed", errorDetails]+ ]);});it("skips optional callbacks that are not provided", async () => {diff --git a/apps/client/src/services/llm_chat.ts b/apps/client/src/services/llm_chat.tsindex 62cd1d6019..fad8d4bd61 100644--- a/apps/client/src/services/llm_chat.ts+++ b/apps/client/src/services/llm_chat.ts@@ -1,4 +1,4 @@-import type { LlmChatConfig, LlmCitation, LlmMessage, LlmModelInfo,LlmUsage } from "@triliumnext/commons";+import type { LlmChatConfig, LlmCitation, LlmErrorDetails, LlmMessage, LlmModelInfo,LlmUsage } from "@triliumnext/commons";import server from "./server.js";@@ -52,7 +52,12 @@ export interface StreamCallbacks {onToolResult?: (toolCallId: string, toolName: string, result: string, isError?: boolean) => void;onCitation?: (citation: LlmCitation) => void;onUsage?: (usage: LlmUsage) => void;- onError: (error: string) => void;+ /**+ * @param error human-readable message.+ * @param details provider-call context (status, URL, response body), present only+ * for failures that reached a provider — never for connection/transport errors raised here.+ */+ onError: (error: string, details?: LlmErrorDetails) => void;onDone: () => void;}@@ -154,7 +159,7 @@ export async function streamChatCompletion(}break;case "error":- callbacks.onError(data.error);+ callbacks.onError(data.error, data.errorDetails);break;case "done":callbacks.onDone();diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 83b32f6997..52dca83559 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2349,6 +2349,8 @@"edit_index": "Edit {{index}} of {{total}}","result": "Result","error": "Error",+ "error_api": "API error (HTTP {{status}})",+ "error_show_details": "Show details","tool_error": "failed","total_tokens": "{{total}} tokens","tokens_detail": "{{prompt}} prompt + {{completion}} completion",diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.css b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.cssindex 12b57f8a04..cbc5c064bf 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.css+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.css@@ -185,6 +185,17 @@ body.background-effects.theme-supports-background-effects .llm-chat-message-useroverflow-wrap: anywhere;}+/* Endpoint + raw response body, revealed by the details toggle. Same treatment as the+ message above, minus the `<pre>` default margin. */+.llm-chat-error-details {+ margin: 0;+ font-family: var(--monospace-font-family, monospace);+ font-size: 0.85em;+ white-space: pre-wrap;+ overflow-wrap: anywhere;+ color: var(--muted-text-color);+}+.llm-chat-error-actions {margin-top: 0.75rem;}diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsxindex 4ad15df566..a1512d25f7 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatMessage.tsx@@ -10,6 +10,7 @@ import utils from "../../../services/utils.js";import { ExtendedAdmonition } from "../../react/Admonition.js";import Button from "../../react/Button.js";import { ReadOnlyTextContent } from "../text/ReadOnlyText.js";+import { formatErrorDetails } from "./chat_error.js";import { renderMarkdown } from "./chat_markdown.js";import { renderQuoteSourceLinks } from "./chat_quote.js";import { ExpandableCard, ExpandableSection } from "./ExpandableCard.js";@@ -159,17 +160,21 @@ function ChatMessage({ message, isStreaming, onRetry }: Props) {);}- // Render error messages as a "caution" extended admonition: the header names the- // failure so the (often long and technical) provider message reads as the detail- // rather than as the assistant's own prose.+ // Render error messages as a "caution" extended admonition: the header classifies the+ // failure (an HTTP status when the provider answered) so the message below it can be+ // just what went wrong, with the endpoint and raw response body folded into "details".if (isError) {+ const status = message.errorDetails?.statusCode;+ const details = formatErrorDetails(textContent, message.errorDetails);return (<div className="llm-chat-message-wrapper llm-chat-message-wrapper-assistant"><ExtendedAdmonitiontype="caution"icon="bx bx-error-circle"- title={t("llm_chat.error")}+ title={status ? t("llm_chat.error_api", { status }) : t("llm_chat.error")}className="llm-chat-error"+ detailsLabel={t("llm_chat.error_show_details")}+ details={details && <pre className="llm-chat-error-details">{details}</pre>}><div className="llm-chat-error-text">{textContent}</div>{onRetry && (diff --git a/apps/client/src/widgets/type_widgets/llm_chat/chat_error.spec.ts b/apps/client/src/widgets/type_widgets/llm_chat/chat_error.spec.tsnew file mode 100644index 0000000000..a2e2775ada--- /dev/null+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_error.spec.ts@@ -0,0 +1,65 @@+import { describe, expect, it } from "vitest";++import { formatErrorDetails } from "./chat_error.js";++/** The DeepSeek rejection that motivated the split: the body only restates the message. */+const DEEPSEEK_MESSAGE = "Failed to deserialize the JSON body into the target type: messages[1]: "+ + "unknown variant `image_url`, expected `text` at line 1 column 38345";+const DEEPSEEK_BODY = JSON.stringify({+ error: {+ message: DEEPSEEK_MESSAGE,+ type: "invalid_request_error",+ param: null,+ code: "invalid_request_error"+ }+});++describe("formatErrorDetails", () => {+ it("returns nothing when the failure carries no provider context", () => {+ expect(formatErrorDetails("Failed to connect to LLM stream: network down")).toBeUndefined();+ expect(formatErrorDetails("Timed out", {})).toBeUndefined();+ expect(formatErrorDetails("Timed out", { statusCode: 504 })).toBeUndefined();+ });++ it("drops a response body that only restates the message, keeping the endpoint", () => {+ const details = formatErrorDetails(DEEPSEEK_MESSAGE, {+ statusCode: 400,+ url: "https://api.deepseek.com/v1/chat/completions",+ responseBody: DEEPSEEK_BODY+ });+ expect(details).toBe("https://api.deepseek.com/v1/chat/completions");+ });++ it("recognises a restatement under either envelope shape, and a verbatim body", () => {+ const cases = [+ JSON.stringify({ error: { message: "Not Found" } }),+ JSON.stringify({ message: "Not Found" }),+ "Not Found"+ ];+ for (const responseBody of cases) {+ expect(formatErrorDetails("Not Found", { url: "https://api.test/v1", responseBody }))+ .toBe("https://api.test/v1");+ }+ });++ it("keeps a body that says more than the message", () => {+ const responseBody = JSON.stringify({ error: { message: "Router not found for POST /messages" } });+ expect(formatErrorDetails("Not Found", { url: "https://api.test/v1", responseBody }))+ .toBe(`https://api.test/v1\n\n${responseBody}`);+ });++ it("keeps an unparseable body, and a JSON body with no message field", () => {+ expect(formatErrorDetails("Bad gateway", { responseBody: "<html>502</html>" }))+ .toBe("<html>502</html>");+ expect(formatErrorDetails("Bad gateway", { responseBody: '{"code":"upstream_down"}' }))+ .toBe('{"code":"upstream_down"}');+ // A JSON scalar is still a parse success — it just carries no message to compare.+ expect(formatErrorDetails("Bad gateway", { responseBody: "42" })).toBe("42");+ });++ it("ignores an empty or whitespace-only body", () => {+ expect(formatErrorDetails("Boom", { url: "https://api.test/v1", responseBody: " " }))+ .toBe("https://api.test/v1");+ expect(formatErrorDetails("Boom", { responseBody: "" })).toBeUndefined();+ });+});diff --git a/apps/client/src/widgets/type_widgets/llm_chat/chat_error.ts b/apps/client/src/widgets/type_widgets/llm_chat/chat_error.tsnew file mode 100644index 0000000000..e5f4825929--- /dev/null+++ b/apps/client/src/widgets/type_widgets/llm_chat/chat_error.ts@@ -0,0 +1,59 @@+import type { LlmErrorDetails } from "@triliumnext/commons";++/**+ * Build the text shown behind an error card's "show details" toggle: the endpoint that+ * was called, followed by the provider's raw response body.+ *+ * The body is dropped when it only restates the message already on the card. Providers+ * routinely answer with `{"error":{"message":"…"}}` and the AI SDK lifts that same string+ * into `error.message`, so printing both would show the failure twice — which is the whole+ * reason the raw body lives down here rather than beside the message.+ *+ * Returns undefined when nothing is left to show, so the caller can omit the toggle.+ *+ * @param message the message displayed on the card, checked against the body for redundancy.+ * @param details the failed call's context, absent for failures that never reached a provider.+ */+export function formatErrorDetails(message: string, details?: LlmErrorDetails): string | undefined {+ if (!details) {+ return undefined;+ }++ const sections: string[] = [];+ if (details.url) {+ sections.push(details.url);+ }+ if (details.responseBody && !restatesMessage(details.responseBody, message)) {+ sections.push(details.responseBody);+ }+ return sections.length > 0 ? sections.join("\n\n") : undefined;+}++/**+ * Whether a raw response body carries nothing the message doesn't already say — either+ * because it *is* that text, or because it is a JSON envelope whose message field the+ * card already shows. Unparseable bodies (an HTML error page, a truncated payload) are+ * only redundant when the message quotes them verbatim.+ */+function restatesMessage(responseBody: string, message: string): boolean {+ const body = responseBody.trim();+ if (!body || message.includes(body)) {+ return true;+ }++ let parsed: unknown;+ try {+ parsed = JSON.parse(body);+ } catch {+ return false;+ }+ if (typeof parsed !== "object" || parsed === null) {+ return false;+ }++ const envelope = parsed as { message?: unknown; error?: { message?: unknown } };+ const reported = typeof envelope.error?.message === "string"+ ? envelope.error.message+ : typeof envelope.message === "string" ? envelope.message : undefined;+ return reported !== undefined && reported.length > 0 && message.includes(reported);+}diff --git a/apps/client/src/widgets/type_widgets/llm_chat/llm_chat_types.ts b/apps/client/src/widgets/type_widgets/llm_chat/llm_chat_types.tsindex f3cbc3a0ac..57e4ff4303 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/llm_chat_types.ts+++ b/apps/client/src/widgets/type_widgets/llm_chat/llm_chat_types.ts@@ -1,4 +1,4 @@-import type { LlmCitation, LlmUsage } from "@triliumnext/commons";+import type { LlmCitation, LlmErrorDetails, LlmUsage } from "@triliumnext/commons";export type MessageType = "message" | "error" | "thinking";@@ -140,6 +140,12 @@ export interface StoredMessage {citations?: LlmCitation[];/** Message type for special rendering. Defaults to "message" if omitted. */type?: MessageType;+ /**+ * For `type: "error"` messages, the failed provider call's context (HTTP status, URL,+ * raw response body). Drives the error card's title and its "show details" section.+ * Absent when the failure never reached a provider, and in chats saved before this existed.+ */+ errorDetails?: LlmErrorDetails;/** Token usage for this response */usage?: LlmUsage;/** User-created text highlights over this message's rendered prose. */diff --git a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.tsindex fddaf8e6fe..bcd4811f6f 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts+++ b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.ts@@ -798,14 +798,15 @@ export function useLlmChat(setLastPromptTokens(u.promptTokens);setLastCompletionTokens(u.completionTokens);},- onError: (errorMsg) => {- console.error("Chat error:", errorMsg);+ onError: (errorMsg, errorDetails) => {+ console.error("Chat error:", errorMsg, errorDetails);const errorMessage: StoredMessage = {id: randomString(),role: "assistant",content: errorMsg,createdAt: new Date().toISOString(),- type: "error"+ type: "error",+ ...(errorDetails ? { errorDetails } : {})};const finalMessages = [...conversation, errorMessage];setMessages(finalMessages);diff --git a/apps/server/src/routes/api/llm_chat.spec.ts b/apps/server/src/routes/api/llm_chat.spec.tsindex 33f32b29b1..8c68a08c88 100644--- a/apps/server/src/routes/api/llm_chat.spec.ts+++ b/apps/server/src/routes/api/llm_chat.spec.ts@@ -45,7 +45,10 @@ vi.mock("../../services/llm/index.js", () => {};});-vi.mock("../../services/llm/stream.js", () => ({+// Only the stream itself is faked; `formatStreamError` (used for the log line) is a pure+// function and stays real, so the logged text is asserted against the production format.+vi.mock("../../services/llm/stream.js", async (importOriginal) => ({+ ...await importOriginal<typeof import("../../services/llm/stream.js")>(),async *streamToChunks () { for (const c of state.chunks) yield c; }}));diff --git a/apps/server/src/routes/api/llm_chat.ts b/apps/server/src/routes/api/llm_chat.tsindex 841478818f..bca605b4db 100644--- a/apps/server/src/routes/api/llm_chat.ts+++ b/apps/server/src/routes/api/llm_chat.ts@@ -4,7 +4,7 @@ import type { Request, Response } from "express";import { generateChatTitle } from "../../services/llm/chat_title.js";import { getProvider, getProviderByType, getSelectedModel, hasConfiguredProviders, listProviderModels, type LlmProviderConfig } from "../../services/llm/index.js";-import { streamToChunks } from "../../services/llm/stream.js";+import { formatStreamError, streamToChunks } from "../../services/llm/stream.js";import { safeExtractMessageAndStackFromError } from "../../services/utils.js";interface ChatRequest {@@ -87,7 +87,10 @@ async function streamChat(req: Request, res: Response) {for await (const chunk of chunks) {if (chunk.type === "error") {- getLog().error(`LLM chat stream error (model ${modelDisplayName}): ${chunk.error}`);+ // The status/URL/response body travel beside the message for the UI's+ // benefit; the log gets them rejoined onto the one line it can show.+ const described = formatStreamError({ message: chunk.error, details: chunk.errorDetails });+ getLog().error(`LLM chat stream error (model ${modelDisplayName}): ${described}`);}res.write(`data: ${JSON.stringify(chunk)}\n\n`);// Flush immediately to ensure real-time streamingdiff --git a/apps/server/src/services/llm/stream.spec.ts b/apps/server/src/services/llm/stream.spec.tsindex e7797c0e9f..9c4376e3c5 100644--- a/apps/server/src/services/llm/stream.spec.ts+++ b/apps/server/src/services/llm/stream.spec.ts@@ -2,7 +2,7 @@ import type { LlmStreamChunk } from "@triliumnext/commons";import { APICallError } from "ai";import { describe, expect, it } from "vitest";-import { describeStreamError, type StreamOptions, streamToChunks } from "./stream.js";+import { describeStreamError, formatStreamError, type StreamOptions, streamToChunks } from "./stream.js";import type { ModelPricing, StreamResult } from "./types.js";type ErrorChunk = Extract<LlmStreamChunk, { type: "error" }>;@@ -92,17 +92,21 @@ describe("streamToChunks", () => {expect(chunks.some(c => c.type === "done")).toBe(false);});- it("includes HTTP status, URL and response body in the surfaced error", async () => {+ it("carries HTTP status, URL and response body beside the surfaced error", async () => {const chunks = await collect(fakeResult([{ type: "error", error: apiCallError() }],noOutputUsage()));const [error] = errorsOf(chunks);- // The previous implementation used String(error), losing all of this detail.- expect(error.error).toContain("HTTP 404");- expect(error.error).toContain("http://localhost:8080/messages");- expect(error.error).toContain("Router not found");+ // The message stays the failure alone — the context travels as data so the client+ // can title the card and collapse the noise instead of printing one long line.+ expect(error.error).toBe("Not Found");+ expect(error.errorDetails).toEqual({+ statusCode: 404,+ url: "http://localhost:8080/messages",+ responseBody: '{"message":"Router not found for request POST /messages"}'+ });});it("surfaces a usage rejection when no error part preceded it", async () => {@@ -326,12 +330,17 @@ describe("streamToChunks", () => {});describe("describeStreamError", () => {- it("expands an APICallError into status, URL and response body", () => {- const msg = describeStreamError(apiCallError());- expect(msg).toContain("AI_APICallError: Not Found");- expect(msg).toContain("HTTP 404");- expect(msg).toContain("URL http://localhost:8080/messages");- expect(msg).toContain('{"message":"Router not found for request POST /messages"}');+ it("splits an APICallError into its message and the call's context", () => {+ // The SDK's class name (AI_APICallError) is dropped: it names an internal, and the+ // status it stands for is reported as data instead.+ expect(describeStreamError(apiCallError())).toEqual({+ message: "Not Found",+ details: {+ statusCode: 404,+ url: "http://localhost:8080/messages",+ responseBody: '{"message":"Router not found for request POST /messages"}'+ }+ });});it("truncates an oversized response body", () => {@@ -342,12 +351,12 @@ describe("describeStreamError", () => {statusCode: 500,responseBody: "x".repeat(900)});- const msg = describeStreamError(err);- expect(msg).toContain("…");- expect(msg.length).toBeLessThan(900);+ const responseBody = describeStreamError(err).details?.responseBody ?? "";+ expect(responseBody.endsWith("…")).toBe(true);+ expect(responseBody.length).toBeLessThan(900);});- it("omits the detail suffix for an APICallError lacking status, url and body", () => {+ it("omits details entirely for an APICallError lacking status, url and body", () => {const err = new APICallError({message: "Opaque failure",url: "",@@ -355,15 +364,25 @@ describe("describeStreamError", () => {statusCode: undefined,responseBody: undefined});- // No status/url/body → no parenthesised detail, just name + message.- expect(describeStreamError(err)).toBe(`${err.name}: Opaque failure`);+ expect(describeStreamError(err)).toEqual({ message: "Opaque failure" });});- it("falls back to name and message for a plain Error", () => {- expect(describeStreamError(new TypeError("bad input"))).toBe("TypeError: bad input");+ it("falls back to name and message for a plain Error, and stringifies a non-Error", () => {+ expect(describeStreamError(new TypeError("bad input"))).toEqual({ message: "TypeError: bad input" });+ expect(describeStreamError("just a string")).toEqual({ message: "just a string" });+ });+});++describe("formatStreamError", () => {+ it("rejoins message and context onto the single line the log can show", () => {+ expect(formatStreamError(describeStreamError(apiCallError()))).toBe(+ "Not Found (HTTP 404, URL http://localhost:8080/messages, "+ + 'response: {"message":"Router not found for request POST /messages"})'+ );});- it("stringifies a non-Error value", () => {- expect(describeStreamError("just a string")).toBe("just a string");+ it("returns the bare message when there is no context to append", () => {+ expect(formatStreamError({ message: "TypeError: bad input" })).toBe("TypeError: bad input");+ expect(formatStreamError({ message: "Timed out", details: {} })).toBe("Timed out");});});diff --git a/apps/server/src/services/llm/stream.ts b/apps/server/src/services/llm/stream.tsindex 80e3890541..331c4931fc 100644--- a/apps/server/src/services/llm/stream.ts+++ b/apps/server/src/services/llm/stream.ts@@ -2,7 +2,7 @@* Shared streaming utilities for converting AI SDK streams to SSE chunks.*/-import type { LlmStreamChunk } from "@triliumnext/commons";+import type { LlmErrorDetails, LlmStreamChunk } from "@triliumnext/commons";import { APICallError, type LanguageModelUsage } from "ai";import type { ModelPricing, StreamResult } from "./types.js";@@ -52,37 +52,71 @@ export interface StreamOptions {pricing?: ModelPricing;}+/** Longest response body forwarded to the client; error bodies are normally tiny JSON payloads. */+const MAX_RESPONSE_BODY_LENGTH = 500;+/**- * Build a detailed, single-line description of an error coming out of the AI SDK.+ * Describe an error coming out of the AI SDK as a message plus its machine-readable+ * context.** AI SDK `APICallError`s carry the HTTP status, the URL that was called and the raw* response body. Surfacing those turns an opaque "Not Found" into something* actionable — e.g. a `404` against `http://localhost:8080/messages` immediately- * reveals a misconfigured provider base URL. Plain errors fall back to name + message.+ * reveals a misconfigured provider base URL. They are kept *beside* the message+ * rather than appended to it so the chat UI can title the failure and hide the noise+ * behind a details toggle; {@link formatStreamError} rejoins them for the log.+ *+ * The error's class name (`AI_APICallError`) is deliberately dropped: it names an SDK+ * internal, and the status it stands for is reported as `statusCode`. Plain errors keep+ * their name, which is the only classification they carry.*/-export function describeStreamError(error: unknown): string {+export function describeStreamError(error: unknown): { message: string; details?: LlmErrorDetails } {if (APICallError.isInstance(error)) {- const detail: string[] = [];+ const details: LlmErrorDetails = {};if (typeof error.statusCode === "number") {- detail.push(`HTTP ${error.statusCode}`);+ details.statusCode = error.statusCode;}if (error.url) {- detail.push(`URL ${error.url}`);+ details.url = error.url;}if (error.responseBody) {- // Response bodies for errors are normally tiny JSON payloads; cap defensively.- const body = error.responseBody.length > 500- ? `${error.responseBody.slice(0, 500)}…`+ details.responseBody = error.responseBody.length > MAX_RESPONSE_BODY_LENGTH+ ? `${error.responseBody.slice(0, MAX_RESPONSE_BODY_LENGTH)}…`: error.responseBody;- detail.push(`response: ${body}`);}- const suffix = detail.length > 0 ? ` (${detail.join(", ")})` : "";- return `${error.name}: ${error.message}${suffix}`;+ return {+ message: error.message,+ ...(Object.keys(details).length > 0 ? { details } : {})+ };}if (error instanceof Error) {- return `${error.name}: ${error.message}`;+ return { message: `${error.name}: ${error.message}` };}- return String(error);+ return { message: String(error) };+}++/**+ * Rejoin a described error into one line, for the server log — where a collapsible+ * details section isn't an option and the full context has to travel with the message.+ */+export function formatStreamError({ message, details }: { message: string; details?: LlmErrorDetails }): string {+ const parts: string[] = [];+ if (typeof details?.statusCode === "number") {+ parts.push(`HTTP ${details.statusCode}`);+ }+ if (details?.url) {+ parts.push(`URL ${details.url}`);+ }+ if (details?.responseBody) {+ parts.push(`response: ${details.responseBody}`);+ }+ return parts.length > 0 ? `${message} (${parts.join(", ")})` : message;+}++/** Package an error for the wire: the message on `error`, its context on `errorDetails`. */+function errorChunk(error: unknown): Extract<LlmStreamChunk, { type: "error" }> {+ const { message, details } = describeStreamError(error);+ return { type: "error", error: message, ...(details ? { errorDetails: details } : {}) };}/**@@ -157,7 +191,7 @@ export async function* streamToChunks(result: StreamResult, options: StreamOptiocase "error":errorEmitted = true;- yield { type: "error", error: describeStreamError(part.error) };+ yield errorChunk(part.error);break;}}@@ -174,7 +208,7 @@ export async function* streamToChunks(result: StreamResult, options: StreamOptiousage = await result.totalUsage;} catch (error) {if (!errorEmitted) {- yield { type: "error", error: describeStreamError(error) };+ yield errorChunk(error);}return;}@@ -197,7 +231,7 @@ export async function* streamToChunks(result: StreamResult, options: StreamOptioyield { type: "done" };} catch (error) {if (!errorEmitted) {- yield { type: "error", error: describeStreamError(error) };+ yield errorChunk(error);}}}diff --git a/packages/commons/src/lib/llm_api.ts b/packages/commons/src/lib/llm_api.tsindex cd988ea712..f0c6405fd0 100644--- a/packages/commons/src/lib/llm_api.ts+++ b/packages/commons/src/lib/llm_api.ts@@ -159,6 +159,25 @@ export interface LlmUsage {provider?: string;}+/**+ * Machine-readable context for a failed provider call, carried alongside the+ * human-readable error message of an `error` chunk.+ *+ * Kept as separate fields rather than pre-formatted into the message so the client+ * can title the failure ("API error (HTTP 400)"), collapse the noisy parts behind a+ * "show details" toggle, and drop a response body that only repeats the message.+ * Absent for failures that never reached a provider (connection errors, aborted+ * streams) and for chats saved before this field existed.+ */+export interface LlmErrorDetails {+ /** HTTP status returned by the provider. */+ statusCode?: number;+ /** Endpoint the failed request was sent to. */+ url?: string;+ /** Raw response body, truncated by the server to a display-safe length. */+ responseBody?: string;+}+/*** Stream chunk types for real-time SSE updates.* Defines the protocol between server and client.@@ -172,5 +191,5 @@ export type LlmStreamChunk =| { type: "tool_result"; toolCallId: string; toolName: string; result: string; isError?: boolean }| { type: "citation"; citation: LlmCitation }| { type: "usage"; usage: LlmUsage }- | { type: "error"; error: string }+ | { type: "error"; error: string; errorDetails?: LlmErrorDetails }| { type: "done" };