feat(webui): show persisted fallback preset on replies (NAN-133)

This commit is contained in:
Xubin Ren committed 2026-09-20 15:16:35 +08:00
1 parent db675a43b6
commit 8d0430c761
43 files changed
+919 -95

No files matched your search

+36
View File
@@ -168,6 +168,42 @@ describe("webui API helpers", () => {
);
});
it.each([
null,
"backup",
[null],
[{ provider: "xai", model: "grok" }],
[{ provider: "xai", model: "grok", preset: "backup", fallback: "true" }],
])("rejects malformed response sources: %j", async (response_sources) => {
vi.mocked(fetch).mockResolvedValueOnce({
ok: true,
status: 200,
json: async () => ({
schemaVersion: 3,
projection: "events",
events: [{ event: "message", chat_id: "chat-1", text: "Reply", response_sources }],
}),
} as Response);
await expect(fetchWebuiThread("tok", "websocket:chat-1")).rejects.toThrow(
"Invalid WebUI thread event metadata",
);
});
it.each([
undefined,
[],
[{ provider: "xai", model: "grok", preset: "snapshot", fallback: true }],
[{ provider: "xai", model: "grok", preset: "legacy snapshot" }],
])("accepts optional recorded response sources: %j", async (response_sources) => {
const event = { event: "stream_end", chat_id: "chat-1", text: "Reply", response_sources };
vi.mocked(fetch).mockResolvedValueOnce({
ok: true,
status: 200,
json: async () => ({ schemaVersion: 3, projection: "events", events: [event] }),
} as Response);
await expect(fetchWebuiThread("tok", "websocket:chat-1")).resolves.toMatchObject({ events: [event] });
});
it("fetches deferred trace details with encoded session and ref", async () => {
await fetchWebuiThreadTraceDetail("tok", "websocket:chat-1", "9.tr-deadbeefdeadbeef");
@@ -15,6 +15,7 @@ describe("chat translation resources", () => {
for (const key of [
"chat.groups.all", "chat.groups.projects", "chat.newChat",
"chat.fallbackTitle", "chat.activity.running", "chat.rename", "chat.loading",
"message.fallbackResponse",
]) {
expect(i18n.exists(key), key).toBe(true);
expect(i18n.t(key), key).not.toBe(key);
+53
View File
@@ -97,6 +97,59 @@ const SLASH_COMMANDS: SlashCommand[] = [
];
describe("MessageBubble", () => {
it.each([false, undefined])("hides normal and legacy source badges (fallback: %s)", (fallback) => {
const message: UIMessage = { id: "primary", role: "assistant", content: "Hello", createdAt: 0,
isStreaming: true, responseSources: [{ provider: "openai_codex", model: "gpt", preset: "codex", fallback }] };
const { container, rerender } = render(<MessageBubble message={message} />);
expect(screen.queryByText("codex")).not.toBeInTheDocument();
expect(container.querySelector("[data-assistant-footer]")).toHaveAttribute("data-state", "reserved");
rerender(<MessageBubble message={{ ...message, isStreaming: false }} />);
expect(screen.queryByText("codex")).not.toBeInTheDocument();
});
it("shows only fallback provider logos and preset names while streaming and after completion", () => {
const message: UIMessage = { id: "actual", role: "assistant", content: "Hello", createdAt: 0,
isStreaming: true, responseSources: [
{ provider: "openai_codex", model: "gpt", preset: "codex", fallback: false },
{ provider: "xai", model: "grok-4.5", preset: "grok", fallback: true },
] };
const { container, rerender } = render(<MessageBubble message={message} />);
expect(screen.getByText("grok")).toBeVisible();
expect(screen.queryByText("codex")).not.toBeInTheDocument();
expect(screen.queryByText("grok-4.5")).not.toBeInTheDocument();
expect(container.querySelector("[data-assistant-footer]")).toHaveAttribute("data-state", "visible");
expect(container.querySelector("img")).toHaveAttribute("alt", "");
fireEvent.error(container.querySelector("img")!);
expect(screen.getByText("grok")).toBeVisible();
rerender(<MessageBubble message={{ ...message, isStreaming: false }} />);
expect(screen.getByText("grok")).toBeVisible();
rerender(<MessageBubble message={{ ...message, responseSources: undefined }} />);
expect(screen.queryByText("grok")).not.toBeInTheDocument();
});
it("explains fallback on focus and click, with the source directly after the timestamp", async () => {
await setAppLanguage("zh-CN");
const description = "本条回复已切换至备用模型,由 grok 回答。";
const { container } = render(<MessageBubble message={{
id: "fallback-info", role: "assistant", content: "你好", createdAt: 1,
responseSources: [{ provider: "xai", model: "grok", preset: "grok", fallback: true }],
}} />);
const trigger = screen.getByRole("button", { name: description });
const footer = container.querySelector("[data-assistant-footer]")!;
const sourceGroup = footer.querySelector("[data-message-timestamp]")!.nextElementSibling;
expect(sourceGroup).toContainElement(trigger);
expect(sourceGroup).not.toHaveClass("ml-auto");
fireEvent.focus(trigger);
expect(await screen.findByRole("tooltip")).toHaveTextContent(description);
fireEvent.blur(trigger);
fireEvent.click(trigger);
const popover = await screen.findByRole("dialog", { name: description });
expect(popover).toHaveTextContent(description);
expect(screen.queryByRole("tooltip")).not.toBeInTheDocument();
fireEvent.keyDown(popover, { key: "Escape" });
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
});
it("copies the localized compact reply instead of the stored English text", async () => {
await setAppLanguage("zh-CN");
const writeText = vi.fn().mockResolvedValue(undefined);
+11 -13
View File
@@ -37,16 +37,15 @@ describe("ModelPresetBadge setup tooltip", () => {
expect(onClick).toHaveBeenCalledTimes(1);
});
it.each(["openai-codex/gpt-5.5", "deepseek/deepseek-chat"])(
"keeps the localized setup prompt despite a stale fallback (%s)",
async (fallbackModelName) => {
it(
"keeps the localized setup prompt instead of an available preset",
async () => {
render(
<ModelPresetBadge
label="选择你的 AI"
modelDetail="claude-opus-4-5"
providerLabel="Anthropic"
modelPresets={presets}
fallbackModelName={fallbackModelName}
needsSetup
onClick={vi.fn()}
isHero={false}
@@ -62,8 +61,8 @@ describe("ModelPresetBadge setup tooltip", () => {
);
});
describe("ModelPresetBadge fallback tooltip", () => {
it("shows only the effective preset on hover and preserves the preset picker", async () => {
describe("ModelPresetBadge selected preset tooltip", () => {
it("shows the selected preset on hover and preserves the preset picker", async () => {
const user = userEvent.setup();
const onPresetChange = vi.fn();
const { container } = render(
@@ -73,18 +72,17 @@ describe("ModelPresetBadge fallback tooltip", () => {
modelDetail="glm-5"
provider="zhipu"
modelPresets={presets}
fallbackModelName="openai-codex/gpt-5.5"
onPresetChange={onPresetChange}
isHero={false}
/>,
);
const trigger = screen.getByRole("button", { name: "codex" });
const trigger = screen.getByRole("button", { name: "zhipu" });
expect(container.querySelector("[title]")).toBeNull();
await user.hover(trigger);
const tooltip = await screen.findByRole("tooltip");
expect(tooltip).toHaveTextContent("codex · openai-codex/gpt-5.5");
expect(tooltip).not.toHaveTextContent("zhipu");
expect(tooltip).toHaveTextContent("zhipu · glm-5");
expect(tooltip).not.toHaveTextContent("codex");
await user.click(trigger);
expect(await screen.findByRole("listbox")).toBeInTheDocument();
await waitFor(() => expect(screen.queryByRole("tooltip")).not.toBeInTheDocument());
@@ -96,16 +94,16 @@ describe("ModelPresetBadge fallback tooltip", () => {
render(
<ModelPresetBadge
label="zhipu"
modelDetail="glm-5"
modelPresets={presets}
fallbackModelName="openai-codex/gpt-5.5"
isHero
/>,
);
const trigger = screen.getByLabelText("codex");
const trigger = screen.getByLabelText("zhipu");
expect(trigger).toHaveAttribute("tabindex", "0");
fireEvent.focus(trigger);
expect(await screen.findByRole("tooltip")).toHaveTextContent(
"codex · openai-codex/gpt-5.5",
"zhipu · glm-5",
);
fireEvent.keyDown(trigger, { key: "Escape" });
await waitFor(() => expect(screen.queryByRole("tooltip")).not.toBeInTheDocument());
@@ -29,6 +29,7 @@ const SEMANTIC_MESSAGE_FIELDS = [
"reasoning",
"latencyMs",
"source",
"responseSources",
"turnId",
"turnPhase",
"turnSeq",
@@ -72,6 +73,27 @@ function normalizeProjection(messages: UIMessage[]): Array<Record<string, unknow
}
describe("canonical thread event projection", () => {
it.each(["message", "stream_end"] as const)("preserves recorded sources in %s replay", (event) => {
const source = { provider: "xai", model: "grok", preset: "saved backup", fallback: true };
const messages = projectThreadEvents([
{ event, chat_id: "chat", text: "Recovered", response_sources: [source] },
{ event: "turn_end", chat_id: "chat" },
{ event: "message", chat_id: "chat", text: "Legacy response" },
]);
expect(messages[0].responseSources).toEqual([source]);
expect(messages[1].responseSources).toBeUndefined();
});
it("clears unknown source metadata on a textless stream end", () => {
const source = { provider: "xai", model: "grok", preset: "backup", fallback: true };
const messages = projectThreadEvents([
{ event: "delta", chat_id: "chat", text: "Mixed answer", response_sources: [source] },
{ event: "stream_end", chat_id: "chat", response_sources: [] },
{ event: "turn_end", chat_id: "chat" },
]);
expect(messages[0].responseSources).toEqual([]);
});
it.each(cases)("projects persisted $name events", (fixtureCase) => {
const messages = projectThreadEvents(fixtureEvents(fixtureCase.transcript));
expect(normalizeProjection(messages)).toEqual(fixtureCase.expected);
+13 -14
View File
@@ -1086,7 +1086,7 @@ describe("ThreadShell", () => {
expect(screen.queryByRole("button", { name: "Choose your AI" })).not.toBeInTheDocument();
});
it("shows the effective fallback model in the composer badge", async () => {
it("keeps the selected composer preset and attributes only the reply to its actual source", async () => {
const client = makeClient();
render(wrap(
client,
@@ -1127,23 +1127,21 @@ describe("ThreadShell", () => {
});
});
const logo = await screen.findByTestId("composer-model-logo-deepseek");
const badge = logo.parentElement;
expect(badge).not.toBeNull();
expect(badge).toBe(configuredBadge);
expect(screen.queryByText("Default")).not.toBeInTheDocument();
expect(screen.getByText("deepseek-chat")).toBeInTheDocument();
expect(badge).toHaveAttribute("data-fallback", "true");
expect(badge).not.toHaveAttribute("title");
fireEvent.focus(screen.getByLabelText("deepseek-chat"));
expect(screen.getByTestId("composer-model-logo-openai_codex").parentElement).toBe(configuredBadge);
expect(screen.getByText("Default")).toBeInTheDocument();
expect(screen.queryByTestId("composer-model-logo-deepseek")).not.toBeInTheDocument();
expect(configuredBadge).not.toHaveAttribute("data-fallback");
fireEvent.focus(screen.getByLabelText("Default"));
expect(await screen.findByRole("tooltip")).toHaveTextContent(
"deepseek-chat · deepseek/deepseek-chat",
"Default · gpt-5.5 · OpenAI Codex",
);
expect(screen.getByRole("tooltip")).not.toHaveTextContent("Default");
fireEvent.blur(screen.getByLabelText("deepseek-chat"));
expect(logo).toBeInTheDocument();
fireEvent.blur(screen.getByLabelText("Default"));
act(() => {
client._emitChat("fallback-model", {
event: "message", chat_id: "fallback-model", text: "Reply from the actual provider",
response_sources: [{provider: "deepseek", model: "deepseek-chat", preset: "backup", fallback: true}],
});
client._emitChat("fallback-model", {
event: "turn_end",
chat_id: "fallback-model",
@@ -1156,6 +1154,7 @@ describe("ThreadShell", () => {
).not.toHaveAttribute("data-fallback");
});
expect(screen.getByText("Default")).toBeInTheDocument();
expect(await screen.findByText("backup")).toBeInTheDocument();
});
it.each([false, true])("hides unconfigured model details in setup tooltips (existing history: %s)", async (hasHistory) => {
+22
View File
@@ -17,6 +17,28 @@ function usage(days: Usage["days"]): Usage {
}
describe("Token usage card", () => {
it("uses the same plot box for stacked bars and the zero baseline, with dates outside", () => {
const days = Array.from({ length: 30 }, (_, index) => {
const date = `2026-09-${String(index + 1).padStart(2, "0")}`;
return { date, usage: day(date, index === 0 ? 30_000_000 : index === 1 ? 1 : 0) };
});
const { container } = render(<TokenUsageModelTrend days={days} modelDays={[
{ date: days[0].date, provider: "openai", model: "a", total_tokens: 20_000_000 },
{ date: days[0].date, provider: "xai", model: "b", total_tokens: 10_000_000 },
{ date: days[1].date, provider: "openai", model: "a", total_tokens: 1 },
]} />);
const plot = container.querySelector("[data-model-usage-plot]")!;
const bars = within(screen.getByRole("group", { name: "Model usage over time" })).getAllByRole("img");
expect(plot).toContainElement(bars[0]);
const baseline = container.querySelector('[data-model-usage-gridline="2"]')!;
expect(plot).toContainElement(baseline);
expect(baseline.parentElement).toHaveStyle({ top: "100%" });
expect(plot).not.toContainElement(screen.getByText("09-01"));
expect(bars[0].firstElementChild).toHaveStyle({ height: "100%" });
expect(bars[0].firstElementChild?.children).toHaveLength(2);
expect(bars[1].firstElementChild).toHaveStyle({ height: `${1 / 30_000_000 * 100}%` });
expect(bars[2].children).toHaveLength(0);
});
beforeEach(() => {
vi.useFakeTimers({ toFake: ["Date"] });
vi.setSystemTime(new Date("2026-09-09T12:00:00Z"));
+37
View File
@@ -43,6 +43,7 @@ const SEMANTIC_MESSAGE_FIELDS = [
"reasoning",
"latencyMs",
"source",
"responseSources",
"turnId",
"turnPhase",
"turnSeq",
@@ -201,6 +202,42 @@ async function flushStreamFrame() {
}
describe("useNanobotStream", () => {
it("keeps invocation snapshots across streaming, recovery segments, completion and reload", async () => {
const fake = fakeClient();
const a = { provider: "openai_codex", model: "gpt", preset: "writer", fallback: false };
const b = { provider: "xai", model: "grok", preset: "reviewer", fallback: true };
const { result, unmount } = renderHook(() => useNanobotStream("sources", EMPTY_MESSAGES), {
wrapper: wrap(fake.client),
});
act(() => fake.emit("sources", { event: "delta", chat_id: "sources", text: "First", response_sources: [a] }));
await flushStreamFrame();
expect(result.current.messages[0].responseSources).toEqual([a]);
act(() => {
fake.emit("sources", { event: "stream_end", chat_id: "sources", resuming: true, response_sources: [a] });
fake.emit("sources", { event: "delta", chat_id: "sources", text: "Recovered", response_sources: [b] });
fake.emit("sources", { event: "stream_end", chat_id: "sources", response_sources: [b] });
fake.emit("sources", { event: "turn_end", chat_id: "sources" });
});
expect(result.current.messages.map(m => m.responseSources)).toEqual([[a], [b]]);
const history = result.current.messages;
unmount();
const reloaded = renderHook(() => useNanobotStream("sources", history), { wrapper: wrap(fake.client) });
expect(reloaded.result.current.messages.map(m => m.responseSources)).toEqual([[a], [b]]);
});
it("honors complete and end-only sources and clears an ambiguous merged attribution", () => {
const fake = fakeClient();
const a = { provider: "openai", model: "shared-model", preset: "primary", fallback: false };
const b = { provider: "openai", model: "shared-model", preset: "backup", fallback: true };
const { result } = renderHook(() => useNanobotStream("sources", EMPTY_MESSAGES), { wrapper: wrap(fake.client) });
act(() => {
fake.emit("sources", { event: "message", chat_id: "sources", text: "Complete", response_sources: [b] });
fake.emit("sources", { event: "stream_end", chat_id: "sources", text: "Mixed", response_sources: [a, b], resuming: true, merge_next: true });
});
expect(result.current.messages.map(m => m.responseSources)).toEqual([[b], [a, b]]);
act(() => fake.emit("sources", { event: "stream_end", chat_id: "sources", response_sources: [] }));
expect(result.current.messages[1].responseSources).toEqual([]);
});
it.each(["succeeded", "cancelled"] as const)("updates one stable compaction row to %s", (phase) => {
const fake = fakeClient();
const { result } = renderHook(