Files
CatoandClaude 4315aed00e Voice symptom check-in and first-run path (#118)
Say or type what is wrong; it is redacted in the browser, read into a
structured symptom by the shared model chain, floored by deterministic
red-flag rules (en+de, with negation), triaged and saved to the local file
with one button. Adds the symptom item kind, Today/Records/Ask entry points,
a first-run path (sample report link, one primary button on empty screens),
delete confirmation, and removes the stray floating Ask pill.

Co-authored-by: Claude <noreply@anthropic.com>
2026-12-04 11:28:51 +01:00

221 lines
8.9 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { REPLIES_INSTRUCTION, RICH_ANSWERS_INSTRUCTION } from "@bitbaum/chatkit";
import { describe, expect, it } from "vitest";
import { AskRequestSchema, SYMPTOM_HISTORY, askFile, buildAskMessages } from "./ask";
import { buildFileContext, CONTEXT_MAX_CHARS } from "./file-context";
import { parseItem } from "./health-item";
import { parseReport } from "./report";
function vendor(content: string) {
const seen: {
url: string;
body: { messages: { role: string; content: string }[] };
auth: string | null;
}[] = [];
const impl: typeof fetch = async (input, init) => {
seen.push({
url: String(input),
body: JSON.parse(String(init?.body ?? "{}")),
auth: new Headers(init?.headers).get("authorization"),
});
return Response.json({ choices: [{ message: { role: "assistant", content } }] });
};
return { impl, seen };
}
const ask = (over: Record<string, unknown> = {}) =>
AskRequestSchema.parse({
messages: [{ role: "user", content: "What stands out?" }],
context: "REPORT: Blood test",
locale: "de",
...over,
});
const report = parseReport({
title: "Blood test",
collected: "2026-10-01",
provider: "Labor X",
summary: "One value is low.",
results: [
{
name: "Hämoglobin",
analyte: "Hemoglobin",
value: "118",
unit: "g/L",
low: 120,
high: 160,
flag: "normal",
},
{ name: "Ferritin", value: "40", unit: "µg/L", low: 15, high: 150, flag: "normal" },
],
})!;
const medicine = parseItem({
id: "i_1",
createdAt: "2026-10-01T00:00:00Z",
kind: "medication",
name: "Metformin",
dose: "500 mg",
schedule: "morning",
})!;
describe("the file as text", () => {
it("lists values with their range and what the numbers say, medicines and appointments too", () => {
const text = buildFileContext([report], [medicine]);
expect(text).toContain("REPORT: Blood test (2026-10-01), Labor X");
expect(text).toContain("- Hemoglobin: 118 g/L (range 120–160) [LOW]");
expect(text).toContain("[LOW]");
expect(text).toContain("- Metformin, 500 mg, morning");
});
it("is bounded, and says when it was cut", () => {
const big = Array.from({ length: 12 }, (_, i) =>
parseReport({
title: `Report ${i}`,
collected: `2026-01-${String(i + 1).padStart(2, "0")}`,
results: [],
})!,
);
const text = buildFileContext(big, []);
expect(text).toContain("Report 11");
expect(text).not.toContain("Report 0\n");
expect(text).toContain("only the newest part");
expect(buildFileContext([], []).length).toBeLessThan(CONTEXT_MAX_CHARS);
});
});
describe("AskRequestSchema", () => {
it("must end on a question from the person", () => {
expect(
AskRequestSchema.safeParse({ messages: [{ role: "assistant", content: "Hi" }] }).success,
).toBe(false);
expect(AskRequestSchema.safeParse({ messages: [] }).success).toBe(false);
});
});
describe("buildAskMessages", () => {
it("puts the file in tags, asks for the reader's language and keeps the rules", () => {
const [system, user] = buildAskMessages(ask());
expect(system!.content).toContain("<file>\nREPORT: Blood test\n</file>");
expect(system!.content).toContain(
"Reply in the language the person writes in; if that is unclear, in German.",
);
expect(system!.content).toContain("never a diagnosis");
expect(system!.content).toContain("Answer ONLY from the file");
expect(user).toEqual({ role: "user", content: "What stands out?" });
});
it("without a file, answers in general terms and says a report would let it read the person's own", () => {
const [system, user] = buildAskMessages(ask({ context: "" }));
const text = system!.content as string;
expect(text).toContain("No report has been shared");
// French answers to a sore knee opened with "I can't see your report"
// (live, 2026-11-01): the fact is for result questions only.
expect(text).toContain("that matters only when they ask about a result of theirs");
expect(text).toContain("never a diagnosis");
expect(text).not.toContain("<file>");
expect(text).not.toContain("Answer ONLY from the file");
expect(text).toContain(
"Reply in the language the person writes in; if that is unclear, in German.",
);
expect(user).toEqual({ role: "user", content: "What stands out?" });
});
it("without a file, asks about a symptom before answering, and uses the answers", () => {
const text = buildAskMessages(ask({ context: "" }))[0]!.content as string;
expect(text).toContain(SYMPTOM_HISTORY);
expect(SYMPTOM_HISTORY).toMatch(/ASK for them in this answer/);
expect(SYMPTOM_HISTORY).toMatch(/Always ask when they invite you to/);
expect(SYMPTOM_HISTORY).toMatch(/never a medicine/);
// The one-tap replies under a question answer it, in the person's words.
expect(SYMPTOM_HISTORY).toMatch(/suggested replies are short answers to your FIRST question/);
// A symptom is not a result: no "I have not seen your report".
expect(text).toContain("When they describe a symptom, do not mention a report at all.");
// Both modes: no medicine by name, not even one sold without a prescription.
expect(text).toContain("never name a medicine, painkiller, cream or supplement");
expect(buildAskMessages(ask())[0]!.content as string).toContain("never name a medicine");
// With a file, a symptom is not "the file does not contain it": it gets the same history.
const withFile = buildAskMessages(ask())[0]!.content as string;
expect(withFile).toContain(SYMPTOM_HISTORY);
expect(withFile).toMatch(/is not a question about the file/);
});
it("puts the caller's scene after the rules, before the file", () => {
const text = buildAskMessages(
ask({ scene: "## The room\nYou are Diplodoctor, in a group chat." }),
)[0]!.content as string;
expect(text).toContain(
"Reply in the language the person writes in; if that is unclear, in German.\n\n## The room\nYou are Diplodoctor, in a group chat.",
);
expect(text.indexOf("## The room")).toBeLessThan(text.indexOf("<file>\nREPORT"));
expect(AskRequestSchema.safeParse({ ...ask(), scene: "x".repeat(1_001) }).success).toBe(false);
});
it("asks for the fleet's visual answers, then the one-tap replies", () => {
const system = buildAskMessages(ask())[0]!.content as string;
expect(system).toContain(RICH_ANSWERS_INSTRUCTION);
expect(system).toContain(REPLIES_INSTRUCTION);
expect(system.indexOf(RICH_ANSWERS_INSTRUCTION)).toBeLessThan(
system.indexOf(REPLIES_INSTRUCTION),
);
});
});
describe("askFile", () => {
it("calls nobody when no model is available", async () => {
const { impl, seen } = vendor("x");
expect(await askFile(ask(), { env: {}, fetchImpl: impl })).toEqual({
ok: false,
error: "not_configured",
});
expect(seen).toEqual([]);
});
it("answers from the shared chain, and from the reader's own key when given", async () => {
const shared = vendor("Your ferritin is in range.");
const a = await askFile(ask(), { env: { GROQ_API_KEY: "shared" }, fetchImpl: shared.impl });
expect(a).toMatchObject({ ok: true, text: "Your ferritin is in range.", ownModel: false });
expect(shared.seen[0]!.auth).toBe("Bearer shared");
expect(shared.seen[0]!.body.messages[0]!.content).toContain("<file>");
const own = vendor("ok");
const b = await askFile(
ask({ byok: { vendor: "mistral", apiKey: "reader-key", model: "mistral-large-latest" } }),
{ env: { GROQ_API_KEY: "shared" }, fetchImpl: own.impl },
);
expect(b).toMatchObject({ ok: true, ownModel: true });
expect(own.seen[0]!.auth).toBe("Bearer reader-key");
});
it("takes the replies block out of the answer and returns the replies as data", async () => {
const { impl } = vendor(
'Your ferritin is in range.\n\n```quick_replies\n["What should I ask my doctor?", "Show the range"]\n```',
);
const out = await askFile(ask(), { env: { GROQ_API_KEY: "shared" }, fetchImpl: impl });
expect(out).toEqual({
ok: true,
text: "Your ferritin is in range.",
replies: ["What should I ask my doctor?", "Show the range"],
servedBy: expect.any(String),
ownModel: false,
});
});
it("answers with no replies when the model wrote none", async () => {
const { impl } = vendor("Nothing in the file says.");
const out = await askFile(ask(), { env: { GROQ_API_KEY: "shared" }, fetchImpl: impl });
expect(out).toMatchObject({ ok: true, text: "Nothing in the file says.", replies: [] });
});
it("refuses an own-model config outside the closed vendor list", async () => {
const { impl, seen } = vendor("x");
const out = await askFile(
ask({ byok: { vendor: "https://evil.example", apiKey: "k", model: "m" } }),
{
env: { GROQ_API_KEY: "shared" },
fetchImpl: impl,
},
);
expect(out).toEqual({ ok: false, error: "bad_own_model" });
expect(seen).toEqual([]);
});
});