Files
heidi/app/api/chat/route.test.ts
CatoandCursor 25d45963c2 Heidi answers what you wrote last, Swiss German all the way through, and starting again is one tap (#146)
* fix(chat): Heidi answers the newest message, and starting again is one tap

- Render the model prompt ourselves: earlier turns marked as answered
  context, the newest message set apart. threadkit's flat transcript made
  «Pire» after three «Le Bilan» turns get a fourth «Le Bilan» sentence in
  4 of 6 live runs; none after.
- Heidi's past turns carry the dialect line she wrote; the draft route
  accepts it in history. Context capped at 20 turns on every surface.
- Prompt: answer only the newest message; a lone word asks about that word.
- decodeAnswer keeps mode 'answer' instead of collapsing it to 'understand'.
- One NewChatButton: phone toolbar above the chat, dock header icon, sidebar.
- Chats fit above the phone keyboard (interactive-widget + visualViewport).
- /chat gets a fresh key per request so the header's Chat link never
  re-renders the conversation just left; sidebar closes on Escape.

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(i18n): Swiss German first, and Heidi explains in it in every conversation

- Language menu, footer and settings share MENU_ORDER: dialect first.
- A saved conversation follows the page's locale on every message instead
  of the one it was created in (stored locale is the fallback).
- Suggestion labels come from a closed list and render via the dictionary;
  tones are translated; 'bridge' is no longer printed as a label.
- Prompt: every 'english' field is written in the explanation language.
- forReader strips translations of dialect suggestions for readers whose
  locale is the taught variety.
- lang on explanation text is the reader's locale, not 'en'.

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(i18n): a signed-in learner's language follows them to every device

Picking a language in the header, footer or settings saves it to the
account (new additive table `preferences`, migration 0006). Every sign-in
returns through /api/account/language, which puts the saved language into
the page the learner lands on. German stays the default; signed out,
nothing is stored.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(chat): the phone toolbar fits 320px in every language

«Nouvelle conversation» beside «Conversations» overflowed a 320px phone by
17px (layout audit, fr/chat). Both buttons now shrink to an ellipsis.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-30 07:13:08 -07:00

159 lines
6.4 KiB
TypeScript

import { test, describe } from "node:test";
import assert from "node:assert/strict";
import { POST, sanitise } from "./route.ts";
/**
* Streaming must not be a way around anything.
*
* The risk a second response shape creates is not that it breaks — it is that
* it becomes a second ROUTE in everything but name, with its own quietly
* divergent validation. That has already happened once in this file's history:
* `/api/chat` grew a private copy of the turn wiring that `respond.ts` existed
* to own, and the copies drifted.
*
* So the guards are asserted through BOTH shapes. Every one of these runs
* before the branch that decides between JSON and an event stream, and this is
* what keeps them there.
*
* No model is called in any of these: the checks reject first, and this
* deployment has no key configured anyway — which is itself one of the cases.
*
* One guard was REMOVED here rather than weakened, and the distinction
* matters: refusing a picture because no key was brought was not a guard, it
* was a wrong belief about free models. What replaced it is a stricter pair —
* a malformed picture is still refused, and a valid one is allowed through to
* a chain that decides for itself whether it can be read.
*/
function request(body: unknown) {
return new Request("http://localhost/api/chat", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
});
}
const BOTH = [
{ name: "blocking", extra: {} },
{ name: "streaming", extra: { stream: true } },
] as const;
describe("the guards hold in both response shapes", () => {
for (const { name, extra } of BOTH) {
test(`${name}: empty input is refused`, async () => {
const res = await POST(request({ input: " ", locale: "de", ...extra }));
assert.equal(res.status, 400);
});
test(`${name}: an over-long input is refused`, async () => {
// A streaming request that skipped this would let anyone post a novel
// and have it forwarded to a vendor a token at a time.
const res = await POST(request({ input: "a".repeat(2001), locale: "de", ...extra }));
assert.equal(res.status, 400);
});
test(`${name}: a MALFORMED picture is still refused`, async () => {
// The validation guard, which must survive the change below. A data URL
// of a type no vendor accepts is rejected here rather than forwarded and
// paid for.
const res = await POST(
request({
input: "Was heisst das?",
locale: "de",
images: ["data:text/html;base64,PGh0bWw+"],
...extra,
}),
);
assert.equal(res.status, 400);
});
test(`${name}: a VALID picture is no longer refused for lacking a key`, async () => {
/**
* This test used to assert the opposite, and the sentence above it read
* "only a brought key can see". That was never true of free models —
* `google/gemma-4-26b-a4b-it:free` was already in the chain this app
* installs — only of a chain with no vision routing, which ai-kit 1.11
* fixed for the whole fleet.
*
* So a picture is VALIDATED here and no longer REFUSED here. Whether one
* can be read is the chain's question and it answers for itself: a
* deployment with a sighted vendor keyed reads it, and one without says
* `blind` in its own words rather than this route guessing from the
* presence of a key.
*
* Asserted as "not 400", not as a specific success: this deployment has
* no key at all, so the turn lands on the unconfigured path pinned
* below. The point is only that the PICTURE is not what stopped it.
*/
const res = await POST(
request({
input: "Was heisst das?",
locale: "de",
images: ["data:image/png;base64,iVBORw0KGgo="],
...extra,
}),
);
assert.notEqual(res.status, 400);
});
}
test("unparseable JSON is refused before either shape is chosen", async () => {
const res = await POST(
new Request("http://localhost/api/chat", {
method: "POST",
headers: { "content-type": "application/json" },
body: "{not json",
}),
);
assert.equal(res.status, 400);
});
});
describe("the two shapes differ only in shape", () => {
/**
* With no model configured — which is this deployment — the blocking path
* answers 503 and the streaming path answers 200 and says so in an event.
*
* That asymmetry is deliberate and worth pinning. An event stream cannot
* report a status: by the time anything is written the headers have gone. So
* a stream's failures are IN the stream, and "the connection simply ended"
* must never be how a reader learns something went wrong.
*/
test("blocking says 503 in the status", async () => {
const res = await POST(request({ input: "Chunnsch du?", locale: "de" }));
assert.equal(res.status, 503);
assert.match(res.headers.get("content-type") ?? "", /application\/json/);
});
test("streaming says 200, then says unconfigured in an event", async () => {
const res = await POST(request({ input: "Chunnsch du?", locale: "de", stream: true }));
assert.equal(res.status, 200);
assert.match(res.headers.get("content-type") ?? "", /text\/event-stream/);
// `no-transform` and `x-accel-buffering: no` are what stop a proxy holding
// the whole answer back and delivering it in one piece — which looks
// exactly like streaming being broken.
assert.match(res.headers.get("cache-control") ?? "", /no-transform/);
assert.equal(res.headers.get("x-accel-buffering"), "no");
const body = await res.text();
assert.match(body, /^data: /m, "every frame is an SSE data line");
const frame = JSON.parse(body.split("data: ")[1].split("\n")[0]);
assert.deepEqual(frame, { type: "error", kind: "unconfigured" });
});
});
describe("the history the model is shown", () => {
test("Heidi's sendable line travels with her turn", () => {
const [, heidi] = sanitise([
{ authorId: "me", body: "Schreib mir einen Satz mit «Bilanz»." },
{ authorId: "heidi", body: "Hier ein kurzer Satz.", dialect: "I ha d Bilanz gmacht." },
]);
assert.equal(heidi.answer?.dialect, "I ha d Bilanz gmacht.");
});
test("a learner's turn cannot carry one", () => {
const [mine] = sanitise([{ authorId: "me", body: "Hoi", dialect: "invented" }]);
assert.equal(mine.answer, undefined);
});
});