World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
Word chat request refusals from their stable error code (#931)
Maya Kid2fa272cb8562
diff --git a/web/src/api.ts b/web/src/api.tsindex 7b633841..9a64171a 100644--- a/web/src/api.ts+++ b/web/src/api.ts@@ -13,6 +13,26 @@ export class ApiError extends Error {}}+/** 服务端拒绝时回的正文 */+type Refusal = { error?: string; code?: string; detail?: string };++/** 一次拒绝给人看的那句话。+ *+ * 有 code 就查 i18n,没有(或这一条还没进表)就退回服务端的英文原句——+ * 服务端永远说英文,因为界面语言在客户端(docs/decisions/0004)。+ * **普通请求与对话流共用这一处**:对话流从前只读 `error`,于是明明有译文的+ * `no_chat_model` 在中文界面上也是一句英文 */+function refusalMessage(body: Refusal, fallback: string): string {+ let message = body.error || fallback;+ // code 来自网络,不是字面量——这一处 cast 换来 err 表本身的全量类型检查+ const worded = body.code+ ? (S.err as Record<string, string | undefined>)[body.code]+ : undefined;+ if (worded) message = worded;+ if (body.detail) message = S.errDetail(message, body.detail);+ return message;+}+async function request<T>(path: string, init?: RequestInit): Promise<T> {const res = await fetch(path, {credentials: "include",@@ -23,25 +43,13 @@ async function request<T>(path: string, init?: RequestInit): Promise<T> {...init,});if (!res.ok) {- // 措辞在这一个收口点定:22 个文件里的 toast.error(e.message) 一处都不用改。- // 有 code 就查 i18n,没有(或这一条还没进表)就退回服务端的英文原句——- // 服务端永远说英文,因为界面语言在客户端(docs/decisions/0004)+ // 措辞在这一个收口点定:22 个文件里的 toast.error(e.message) 一处都不用改let message = res.statusText;let code: string | undefined;try {- const body = (await res.json()) as {- error?: string;- code?: string;- detail?: string;- };- if (body.error) message = body.error;+ const body = (await res.json()) as Refusal;code = body.code;- // code 来自网络,不是字面量——这一处 cast 换来 err 表本身的全量类型检查- const worded = code- ? (S.err as Record<string, string | undefined>)[code]- : undefined;- if (worded) message = worded;- if (body.detail) message = S.errDetail(message, body.detail);+ message = refusalMessage(body, message);} catch {// 非 JSON 响应体,保留 statusText}@@ -2707,8 +2715,7 @@ function consumeChatStream(if (!res.ok || !res.body) {let message = res.statusText;try {- const body = (await res.json()) as { error?: string };- if (body.error) message = body.error;+ message = refusalMessage((await res.json()) as Refusal, message);} catch { /* keep the HTTP status */ }fail(message);return;diff --git a/web/src/chatStream.test.ts b/web/src/chatStream.test.tsindex 033b7a9e..8bba3876 100644--- a/web/src/chatStream.test.ts+++ b/web/src/chatStream.test.ts@@ -1,6 +1,13 @@import { afterEach, describe, expect, it, vi } from "vitest";import { reattachChat, streamChat, type ChatHandlers } from "./api";-vi.mock("./i18n", () => ({ S: { ask: { streamInterrupted: "Stream interrupted" } }, lang: "en" }));+vi.mock("./i18n", () => ({+ S: {+ ask: { streamInterrupted: "Stream interrupted" },+ err: { no_chat_model: "Worded: configure a chat model" },+ errDetail: (message: string, detail: string) => `${message} (${detail})`,+ },+ lang: "en",+}));afterEach(() => vi.unstubAllGlobals());const encoder = new TextEncoder();@@ -26,6 +33,34 @@ async function replay(text: string, attach = false, bytewise = false) {return events;}+/** The chat request is refused before any stream opens */+async function refuse(status: number, body: unknown) {+ const events: [string, unknown][] = [];+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(JSON.stringify(body), { status })));+ streamChat("kb", { message: "hello" }, {+ onConversation: vi.fn(), onSources: vi.fn(), onStep: vi.fn(), onDelta: vi.fn(),+ onDone: () => events.push(["done", null]), onError: (v) => events.push(["error", v]),+ });+ await vi.waitFor(() => expect(events).toHaveLength(1));+ return events;+}++describe("a refused chat request", () => {+ it("is worded from its stable code, like every other request", async () => {+ expect(await refuse(422, { error: "Chat model not configured. Go to Settings → Models.", code: "no_chat_model" }))+ .toEqual([["error", "Worded: configure a chat model"]]);+ });+ it("keeps the server's sentence when there is no code to word it by", async () => {+ expect(await refuse(404, { error: "Not found" })).toEqual([["error", "Not found"]]);+ expect(await refuse(422, { error: "Not in the table yet", code: "unlisted_code" }))+ .toEqual([["error", "Not in the table yet"]]);+ });+ it("keeps the server's detail beside the wording", async () => {+ expect(await refuse(422, { error: "x", code: "no_chat_model", detail: "no endpoint" }))+ .toEqual([["error", "Worded: configure a chat model (no endpoint)"]]);+ });+});+describe("application chat terminal outcomes", () => {it.each(["\n", "\r\n", "\r"])("reads %j line endings once, including split UTF-8", async (nl) => {const text = 'event: delta\ndata: {"text":"中文🙂"}\n\nevent: done\ndata: {}\n\n'.replaceAll("\n", nl);