Spaces:
Running
Running
Sync from felladrin/MiniSearch@3f9f9de
Browse files- .env.example +3 -0
- changelog.md +11 -0
- client/components/AiResponse/ChatHeader.test.tsx +64 -0
- client/components/AiResponse/ChatHeader.tsx +5 -3
- client/components/AiResponse/ChatInterface.test.tsx +171 -0
- client/components/AiResponse/ChatInterface.tsx +65 -34
- client/components/AiResponse/MessageList.test.tsx +52 -1
- client/components/AiResponse/MessageList.tsx +23 -9
- client/hooks/useHistoryRestore.ts +5 -3
- client/modules/pubSub.throttle.test.ts +69 -0
- client/modules/pubSub.ts +73 -4
- client/modules/textGeneration.chatBudget.test.ts +1 -0
- client/modules/textGeneration.degradation.test.ts +5 -0
- client/modules/textGeneration.inference.test.ts +1 -0
- client/modules/textGeneration.responsePersistence.test.ts +111 -0
- client/modules/textGeneration.test.ts +1 -0
- client/modules/textGeneration.ts +10 -4
- client/modules/textGenerationWithHorde.test.ts +88 -3
- client/modules/textGenerationWithHorde.ts +27 -2
- client/modules/textGenerationWithInternalApi.test.ts +126 -2
- client/modules/textGenerationWithInternalApi.ts +117 -71
- client/modules/textGenerationWithOpenAi.test.ts +4 -2
- client/modules/textGenerationWithOpenAi.ts +25 -29
- client/modules/textGenerationWithWllama.test.ts +1 -1
- client/modules/textGenerationWithWllama.ts +3 -2
- docs/ai-integration.md +1 -1
- docs/api.md +5 -1
- docs/configuration.md +9 -6
- docs/failure-injection.md +2 -0
- docs/glossary.md +1 -1
- docs/overview.md +7 -7
- docs/ui-components.md +7 -6
.env.example
CHANGED
|
@@ -19,6 +19,9 @@ INTERNAL_OPENAI_COMPATIBLE_API_KEY=""
|
|
| 19 |
# The model for the internal OpenAI compatible API.
|
| 20 |
INTERNAL_OPENAI_COMPATIBLE_API_MODEL=""
|
| 21 |
|
|
|
|
|
|
|
|
|
|
| 22 |
# The name of the internal OpenAI compatible API, displayed in the UI.
|
| 23 |
INTERNAL_OPENAI_COMPATIBLE_API_NAME="Internal API"
|
| 24 |
|
|
|
|
| 19 |
# The model for the internal OpenAI compatible API.
|
| 20 |
INTERNAL_OPENAI_COMPATIBLE_API_MODEL=""
|
| 21 |
|
| 22 |
+
# The reasoning effort for the internal OpenAI compatible API, sent as `reasoning_effort` (e.g. "none", "low", "medium", "high"). Leave blank to use the API's default.
|
| 23 |
+
INTERNAL_OPENAI_COMPATIBLE_API_REASONING_EFFORT=""
|
| 24 |
+
|
| 25 |
# The name of the internal OpenAI compatible API, displayed in the UI.
|
| 26 |
INTERNAL_OPENAI_COMPATIBLE_API_NAME="Internal API"
|
| 27 |
|
changelog.md
CHANGED
|
@@ -2,8 +2,19 @@
|
|
| 2 |
|
| 3 |
Notable changes, grouped by date, most recent first.
|
| 4 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
## 2026-11-25
|
| 6 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
- Earlier chat turns no longer send their thinking back to the model. Stored answers keep their reasoning block, and every prompt built from the conversation was sending it again: wasted tokens, and older turns dropped from the context sooner because of it. The reasoning is now stripped where the prompt is built, for the continuation, the rolling summary and the follow-up question suggestions. The chat and the History still show it.
|
| 8 |
- Fetches triggered by the settings are cancelled when superseded and give up after 10 seconds. Typing a base URL or a Horde key used to fire one request per character, and the slowest answer won: an old server's model list could replace the correct one, a cleared field could show the old user again, and an endpoint that never answers left the model dropdown stuck or delayed the start of an AI response indefinitely. Clearing the base URL now clears the model list too.
|
| 9 |
- Follow-up question suggestions are now written from the question prompt alone. The prompt went out the way a chat answer does, behind the system prompt with the search results, which buried the instructions for the question under unrelated text; it now goes out on its own, like the related search query. A reply with no question in it also no longer leaves a blank entry in the list of earlier suggestions the next prompt asks the model not to repeat, which pushed a real one out of that list.
|
|
|
|
| 2 |
|
| 3 |
Notable changes, grouped by date, most recent first.
|
| 4 |
|
| 5 |
+
## 2026-11-26
|
| 6 |
+
|
| 7 |
+
- An AI Horde answer no longer fails because one of its two jobs did. With no model chosen, MiniSearch sends two jobs and uses whichever answers first, but a job that failed first, such as one whose worker crashed, ended the whole answer with "Generation failed" while the other job was about to finish. A failed job is now ignored as long as the other one is still running, and the answer fails only when both do. When both fail, a stop you pressed still ends it without a new attempt, and a job that could not run on the top models still sends the second round to any model.
|
| 8 |
+
- Stop now ends an answer from the instance's own AI right away. The request was never cancelled: pressing Stop only took effect when the next piece of text arrived, so a stalled answer kept going until the server gave up, and even after Stop the connection stayed open, so the server kept generating and counted the answer as streamed instead of abandoned. The same happened when the answer ended with an error. The request is now cancelled on Stop, even while nothing is arriving, and whenever the answer does not finish.
|
| 9 |
+
- A SearXNG that stops answering no longer holds a search until the client gives up. The request to SearXNG had no time limit, so a stalled instance kept a search waiting for up to 300 seconds, past the client's 30 second timeout, and the fallback providers were then skipped because the search's time had run out. The request, its retries and the waits between them are now canceled after 15 seconds when a fallback could still answer, leaving it the remaining 10, and after 25 seconds otherwise; each canceled request counts toward opening the SearXNG circuit. A failed SearXNG answer now also releases its connection right away, and a search whose every retry got a 500 says so in the log.
|
| 10 |
+
- A failed regeneration no longer loses the answer. Regenerate removed the answer from the chat before asking for a new one, and when the model errored it was gone, with the regenerate button, and the follow-up suggestion was cleared too, so the question had to be typed again; the only trace was a line in the logs. The previous answer and the follow-up suggestion now come back, a red notification says the regeneration failed, and the answer can be regenerated again.
|
| 11 |
+
|
| 12 |
## 2026-11-25
|
| 13 |
|
| 14 |
+
- Admins can now set the reasoning effort of the instance's own AI. The new `INTERNAL_OPENAI_COMPATIBLE_API_REASONING_EFFORT` variable is sent as `reasoning_effort` on every request to the internal OpenAI-compatible API, for every model in the list, so a reasoning model can be told to think less (or not at all) and answer faster. Left empty, nothing is sent and the API keeps its own default.
|
| 15 |
+
|
| 16 |
+
- Follow-up questions are now shown when the main AI answer came back empty. The first follow-up question and its answer used to be hidden for good, "Copy conversation" left them out, and they could not be regenerated. A last answer that came back empty now shows "No response" with its Re-generate button, instead of showing nothing to retry from.
|
| 17 |
+
- The AI answer is now saved to the history in full. Response updates are throttled to about 12 a second, and the save read the throttled channel right after the stream ended, before the write carrying the last tokens had run, so the stored answer could miss everything that arrived since the last publish — up to the whole answer, which with a reasoning model left a history row that restored as an unfinished thought. The save now takes the text the generation call returns, and the full answer is published before the generation state turns to completed, so the restored history row and the follow-up chat start from the complete answer. Restoring a saved answer publishes it the same way.
|
| 18 |
- Earlier chat turns no longer send their thinking back to the model. Stored answers keep their reasoning block, and every prompt built from the conversation was sending it again: wasted tokens, and older turns dropped from the context sooner because of it. The reasoning is now stripped where the prompt is built, for the continuation, the rolling summary and the follow-up question suggestions. The chat and the History still show it.
|
| 19 |
- Fetches triggered by the settings are cancelled when superseded and give up after 10 seconds. Typing a base URL or a Horde key used to fire one request per character, and the slowest answer won: an old server's model list could replace the correct one, a cleared field could show the old user again, and an endpoint that never answers left the model dropdown stuck or delayed the start of an AI response indefinitely. Clearing the base URL now clears the model list too.
|
| 20 |
- Follow-up question suggestions are now written from the question prompt alone. The prompt went out the way a chat answer does, behind the system prompt with the search results, which buried the instructions for the question under unrelated text; it now goes out on its own, like the related search query. A reply with no question in it also no longer leaves a blank entry in the list of earlier suggestions the next prompt asks the model not to repeat, which pushed a real one out of that list.
|
client/components/AiResponse/ChatHeader.test.tsx
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { MantineProvider } from "@mantine/core";
|
| 2 |
+
import { render, screen } from "@testing-library/react";
|
| 3 |
+
import { describe, expect, it, vi } from "vitest";
|
| 4 |
+
import type { ChatMessage } from "@/modules/types";
|
| 5 |
+
import ChatHeader from "./ChatHeader";
|
| 6 |
+
|
| 7 |
+
// Show the text the copy button would put on the clipboard.
|
| 8 |
+
vi.mock("./CopyIconButton", () => ({
|
| 9 |
+
default: ({ value }: { value: string }) => (
|
| 10 |
+
<pre data-testid="copied-conversation">{value}</pre>
|
| 11 |
+
),
|
| 12 |
+
}));
|
| 13 |
+
|
| 14 |
+
function renderChatHeader(messages: ChatMessage[], followUpStartIndex: number) {
|
| 15 |
+
return render(
|
| 16 |
+
<MantineProvider>
|
| 17 |
+
<ChatHeader messages={messages} followUpStartIndex={followUpStartIndex} />
|
| 18 |
+
</MantineProvider>,
|
| 19 |
+
);
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
describe("ChatHeader", () => {
|
| 23 |
+
it("copies the follow-ups that come after the main question and answer", () => {
|
| 24 |
+
renderChatHeader(
|
| 25 |
+
[
|
| 26 |
+
{ role: "user", content: "Main question" },
|
| 27 |
+
{ role: "assistant", content: "Main answer" },
|
| 28 |
+
{ role: "user", content: "Q1" },
|
| 29 |
+
{ role: "assistant", content: "A1" },
|
| 30 |
+
],
|
| 31 |
+
2,
|
| 32 |
+
);
|
| 33 |
+
|
| 34 |
+
expect(screen.getByTestId("copied-conversation").textContent).toBe(
|
| 35 |
+
"1. USER\n\nQ1\n\n2. ASSISTANT\n\nA1",
|
| 36 |
+
);
|
| 37 |
+
});
|
| 38 |
+
|
| 39 |
+
it("copies the first follow-up pair when there is no main question and answer", () => {
|
| 40 |
+
renderChatHeader(
|
| 41 |
+
[
|
| 42 |
+
{ role: "user", content: "Q1" },
|
| 43 |
+
{ role: "assistant", content: "A1" },
|
| 44 |
+
],
|
| 45 |
+
0,
|
| 46 |
+
);
|
| 47 |
+
|
| 48 |
+
expect(screen.getByTestId("copied-conversation").textContent).toBe(
|
| 49 |
+
"1. USER\n\nQ1\n\n2. ASSISTANT\n\nA1",
|
| 50 |
+
);
|
| 51 |
+
});
|
| 52 |
+
|
| 53 |
+
it("shows no copy button before the first follow-up", () => {
|
| 54 |
+
renderChatHeader(
|
| 55 |
+
[
|
| 56 |
+
{ role: "user", content: "Main question" },
|
| 57 |
+
{ role: "assistant", content: "Main answer" },
|
| 58 |
+
],
|
| 59 |
+
2,
|
| 60 |
+
);
|
| 61 |
+
|
| 62 |
+
expect(screen.queryByTestId("copied-conversation")).toBeNull();
|
| 63 |
+
});
|
| 64 |
+
});
|
client/components/AiResponse/ChatHeader.tsx
CHANGED
|
@@ -4,12 +4,14 @@ import CopyIconButton from "./CopyIconButton";
|
|
| 4 |
|
| 5 |
interface ChatHeaderProps {
|
| 6 |
messages: ChatMessage[];
|
|
|
|
|
|
|
| 7 |
}
|
| 8 |
|
| 9 |
-
function ChatHeader({ messages }: ChatHeaderProps) {
|
| 10 |
const getChatContent = () => {
|
| 11 |
return messages
|
| 12 |
-
.slice(
|
| 13 |
.map(
|
| 14 |
(msg, index) =>
|
| 15 |
`${index + 1}. ${msg.role?.toUpperCase()}\n\n${msg.content}`,
|
|
@@ -20,7 +22,7 @@ function ChatHeader({ messages }: ChatHeaderProps) {
|
|
| 20 |
return (
|
| 21 |
<Group justify="space-between">
|
| 22 |
<Text fw={500}>Follow-up questions</Text>
|
| 23 |
-
{messages.length >
|
| 24 |
<CopyIconButton
|
| 25 |
value={getChatContent()}
|
| 26 |
tooltipLabel="Copy conversation"
|
|
|
|
| 4 |
|
| 5 |
interface ChatHeaderProps {
|
| 6 |
messages: ChatMessage[];
|
| 7 |
+
/** Position of the first follow-up message: 2 after the main question and answer, 0 without them. */
|
| 8 |
+
followUpStartIndex: number;
|
| 9 |
}
|
| 10 |
|
| 11 |
+
function ChatHeader({ messages, followUpStartIndex }: ChatHeaderProps) {
|
| 12 |
const getChatContent = () => {
|
| 13 |
return messages
|
| 14 |
+
.slice(followUpStartIndex)
|
| 15 |
.map(
|
| 16 |
(msg, index) =>
|
| 17 |
`${index + 1}. ${msg.role?.toUpperCase()}\n\n${msg.content}`,
|
|
|
|
| 22 |
return (
|
| 23 |
<Group justify="space-between">
|
| 24 |
<Text fw={500}>Follow-up questions</Text>
|
| 25 |
+
{messages.length > followUpStartIndex && (
|
| 26 |
<CopyIconButton
|
| 27 |
value={getChatContent()}
|
| 28 |
tooltipLabel="Copy conversation"
|
client/components/AiResponse/ChatInterface.test.tsx
CHANGED
|
@@ -36,12 +36,17 @@ vi.mock("@/modules/notifications", () => ({
|
|
| 36 |
|
| 37 |
vi.mock("@/modules/logEntries", () => ({ addLogEntry: vi.fn() }));
|
| 38 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
vi.mock("./ChatHeader", () => ({ default: () => null }));
|
| 40 |
|
| 41 |
let sendMessage: (textToSend?: string) => Promise<void>;
|
| 42 |
let regenerateResponse: () => Promise<void>;
|
| 43 |
let messageListMessages: ChatMessage[] = [];
|
| 44 |
let messageListIsGenerating = false;
|
|
|
|
| 45 |
|
| 46 |
vi.mock("./ChatInputArea", () => ({
|
| 47 |
default: (props: { handleSend: (textToSend?: string) => Promise<void> }) => {
|
|
@@ -53,11 +58,13 @@ vi.mock("./ChatInputArea", () => ({
|
|
| 53 |
vi.mock("./MessageList", () => ({
|
| 54 |
default: (props: {
|
| 55 |
messages: ChatMessage[];
|
|
|
|
| 56 |
isGenerating: boolean;
|
| 57 |
onRegenerate: () => Promise<void>;
|
| 58 |
}) => {
|
| 59 |
regenerateResponse = props.onRegenerate;
|
| 60 |
messageListMessages = props.messages;
|
|
|
|
| 61 |
messageListIsGenerating = props.isGenerating;
|
| 62 |
return null;
|
| 63 |
},
|
|
@@ -69,6 +76,7 @@ const { generateFollowUpQuestion } = await import(
|
|
| 69 |
);
|
| 70 |
const { persistChatMessages } = await import("@/modules/chatHelpers");
|
| 71 |
const { addLogEntry } = await import("@/modules/logEntries");
|
|
|
|
| 72 |
|
| 73 |
/** A promise plus the handle to settle it, so a test can hold a call open. */
|
| 74 |
function deferred<T>() {
|
|
@@ -120,6 +128,7 @@ beforeEach(() => {
|
|
| 120 |
updateSuppressNextFollowUp(false);
|
| 121 |
messageListMessages = [];
|
| 122 |
messageListIsGenerating = false;
|
|
|
|
| 123 |
vi.mocked(generateChatResponse).mockResolvedValue("An answer.");
|
| 124 |
vi.mocked(generateFollowUpQuestion).mockResolvedValue("A question?");
|
| 125 |
});
|
|
@@ -738,6 +747,168 @@ describe("ChatInterface generation state", () => {
|
|
| 738 |
});
|
| 739 |
});
|
| 740 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 741 |
describe("ChatInterface previous follow-up questions", () => {
|
| 742 |
it("does not record an empty follow-up question", async () => {
|
| 743 |
vi.mocked(generateFollowUpQuestion)
|
|
|
|
| 36 |
|
| 37 |
vi.mock("@/modules/logEntries", () => ({ addLogEntry: vi.fn() }));
|
| 38 |
|
| 39 |
+
vi.mock("@mantine/notifications", () => ({
|
| 40 |
+
notifications: { show: vi.fn() },
|
| 41 |
+
}));
|
| 42 |
+
|
| 43 |
vi.mock("./ChatHeader", () => ({ default: () => null }));
|
| 44 |
|
| 45 |
let sendMessage: (textToSend?: string) => Promise<void>;
|
| 46 |
let regenerateResponse: () => Promise<void>;
|
| 47 |
let messageListMessages: ChatMessage[] = [];
|
| 48 |
let messageListIsGenerating = false;
|
| 49 |
+
let messageListFollowUpStartIndex: number | undefined;
|
| 50 |
|
| 51 |
vi.mock("./ChatInputArea", () => ({
|
| 52 |
default: (props: { handleSend: (textToSend?: string) => Promise<void> }) => {
|
|
|
|
| 58 |
vi.mock("./MessageList", () => ({
|
| 59 |
default: (props: {
|
| 60 |
messages: ChatMessage[];
|
| 61 |
+
followUpStartIndex: number;
|
| 62 |
isGenerating: boolean;
|
| 63 |
onRegenerate: () => Promise<void>;
|
| 64 |
}) => {
|
| 65 |
regenerateResponse = props.onRegenerate;
|
| 66 |
messageListMessages = props.messages;
|
| 67 |
+
messageListFollowUpStartIndex = props.followUpStartIndex;
|
| 68 |
messageListIsGenerating = props.isGenerating;
|
| 69 |
return null;
|
| 70 |
},
|
|
|
|
| 76 |
);
|
| 77 |
const { persistChatMessages } = await import("@/modules/chatHelpers");
|
| 78 |
const { addLogEntry } = await import("@/modules/logEntries");
|
| 79 |
+
const { notifications } = await import("@mantine/notifications");
|
| 80 |
|
| 81 |
/** A promise plus the handle to settle it, so a test can hold a call open. */
|
| 82 |
function deferred<T>() {
|
|
|
|
| 128 |
updateSuppressNextFollowUp(false);
|
| 129 |
messageListMessages = [];
|
| 130 |
messageListIsGenerating = false;
|
| 131 |
+
messageListFollowUpStartIndex = undefined;
|
| 132 |
vi.mocked(generateChatResponse).mockResolvedValue("An answer.");
|
| 133 |
vi.mocked(generateFollowUpQuestion).mockResolvedValue("A question?");
|
| 134 |
});
|
|
|
|
| 747 |
});
|
| 748 |
});
|
| 749 |
|
| 750 |
+
describe("ChatInterface follow-up start", () => {
|
| 751 |
+
const followUps: ChatMessage[] = [
|
| 752 |
+
{ role: "user", content: "Q1" },
|
| 753 |
+
{ role: "assistant", content: "A1" },
|
| 754 |
+
];
|
| 755 |
+
|
| 756 |
+
function renderWithoutMainAnswer() {
|
| 757 |
+
return render(
|
| 758 |
+
<MantineProvider>
|
| 759 |
+
<ChatInterface
|
| 760 |
+
initialQuery={initialQuery}
|
| 761 |
+
initialResponse=""
|
| 762 |
+
initialMessages={followUps}
|
| 763 |
+
suppressInitialFollowUp
|
| 764 |
+
/>
|
| 765 |
+
</MantineProvider>,
|
| 766 |
+
);
|
| 767 |
+
}
|
| 768 |
+
|
| 769 |
+
it("starts the follow-ups after the main question and answer", () => {
|
| 770 |
+
renderChatInterface();
|
| 771 |
+
|
| 772 |
+
expect(messageListMessages).toEqual([
|
| 773 |
+
{ role: "user", content: initialQuery },
|
| 774 |
+
{ role: "assistant", content: initialResponse },
|
| 775 |
+
]);
|
| 776 |
+
expect(messageListFollowUpStartIndex).toBe(2);
|
| 777 |
+
});
|
| 778 |
+
|
| 779 |
+
it("starts the follow-ups at the top when the main answer is empty", () => {
|
| 780 |
+
renderWithoutMainAnswer();
|
| 781 |
+
|
| 782 |
+
expect(messageListMessages).toEqual(followUps);
|
| 783 |
+
expect(messageListFollowUpStartIndex).toBe(0);
|
| 784 |
+
});
|
| 785 |
+
|
| 786 |
+
it("regenerates the first follow-up when the main answer is empty", async () => {
|
| 787 |
+
renderWithoutMainAnswer();
|
| 788 |
+
vi.mocked(generateChatResponse).mockResolvedValueOnce("A1 again");
|
| 789 |
+
|
| 790 |
+
await act(async () => {
|
| 791 |
+
await regenerateResponse();
|
| 792 |
+
});
|
| 793 |
+
|
| 794 |
+
expect(generateChatResponse).toHaveBeenCalledTimes(1);
|
| 795 |
+
expect(vi.mocked(generateChatResponse).mock.calls[0][0]).toEqual([
|
| 796 |
+
followUps[0],
|
| 797 |
+
]);
|
| 798 |
+
expect(messageListMessages.at(-1)).toEqual({
|
| 799 |
+
role: "assistant",
|
| 800 |
+
content: "A1 again",
|
| 801 |
+
});
|
| 802 |
+
});
|
| 803 |
+
});
|
| 804 |
+
|
| 805 |
+
describe("ChatInterface failed regeneration", () => {
|
| 806 |
+
const nextQuestion = "And how do I use it?";
|
| 807 |
+
|
| 808 |
+
async function sendThenFailRegenerate() {
|
| 809 |
+
vi.mocked(generateChatResponse)
|
| 810 |
+
.mockResolvedValueOnce("An answer.")
|
| 811 |
+
.mockRejectedValueOnce(new Error("model crashed"));
|
| 812 |
+
|
| 813 |
+
await act(async () => {
|
| 814 |
+
await sendMessage(nextQuestion);
|
| 815 |
+
});
|
| 816 |
+
await act(async () => {
|
| 817 |
+
await regenerateResponse();
|
| 818 |
+
});
|
| 819 |
+
}
|
| 820 |
+
|
| 821 |
+
it("keeps the previous answer so it can be regenerated again", async () => {
|
| 822 |
+
renderChatInterface();
|
| 823 |
+
await sendThenFailRegenerate();
|
| 824 |
+
|
| 825 |
+
expect(messageListMessages.at(-1)).toEqual({
|
| 826 |
+
role: "assistant",
|
| 827 |
+
content: "An answer.",
|
| 828 |
+
});
|
| 829 |
+
expect(messageListMessages).toHaveLength(4);
|
| 830 |
+
expect(getChatGenerationState().isGeneratingResponse).toBe(false);
|
| 831 |
+
|
| 832 |
+
vi.mocked(generateChatResponse).mockResolvedValueOnce("A second try.");
|
| 833 |
+
await act(async () => {
|
| 834 |
+
await regenerateResponse();
|
| 835 |
+
});
|
| 836 |
+
|
| 837 |
+
expect(generateChatResponse).toHaveBeenCalledTimes(3);
|
| 838 |
+
expect(messageListMessages.at(-1)?.content).toBe("A second try.");
|
| 839 |
+
});
|
| 840 |
+
|
| 841 |
+
it("shows one red notification and still logs the error", async () => {
|
| 842 |
+
renderChatInterface();
|
| 843 |
+
await sendThenFailRegenerate();
|
| 844 |
+
|
| 845 |
+
expect(notifications.show).toHaveBeenCalledTimes(1);
|
| 846 |
+
expect(notifications.show).toHaveBeenCalledWith(
|
| 847 |
+
expect.objectContaining({
|
| 848 |
+
color: "red",
|
| 849 |
+
message:
|
| 850 |
+
"Couldn't re-generate the response. The previous answer has been kept.",
|
| 851 |
+
}),
|
| 852 |
+
);
|
| 853 |
+
expect(addLogEntry).toHaveBeenCalledWith(
|
| 854 |
+
expect.stringContaining("Error re-generating response"),
|
| 855 |
+
);
|
| 856 |
+
});
|
| 857 |
+
|
| 858 |
+
it("brings back the follow-up question that was showing", async () => {
|
| 859 |
+
renderChatInterface();
|
| 860 |
+
await sendThenFailRegenerate();
|
| 861 |
+
|
| 862 |
+
expect(getFollowUpQuestion()).toBe("A question?");
|
| 863 |
+
});
|
| 864 |
+
|
| 865 |
+
it("writes nothing and shows no notification after unmounting", async () => {
|
| 866 |
+
const response = deferred<string>();
|
| 867 |
+
vi.mocked(generateChatResponse)
|
| 868 |
+
.mockResolvedValueOnce("An answer.")
|
| 869 |
+
.mockReturnValueOnce(response.promise);
|
| 870 |
+
|
| 871 |
+
const { unmount } = renderChatInterface();
|
| 872 |
+
await act(async () => {
|
| 873 |
+
await sendMessage(nextQuestion);
|
| 874 |
+
});
|
| 875 |
+
|
| 876 |
+
let regenerate: Promise<void> = Promise.resolve();
|
| 877 |
+
await act(async () => {
|
| 878 |
+
regenerate = regenerateResponse();
|
| 879 |
+
});
|
| 880 |
+
await act(async () => {
|
| 881 |
+
unmount();
|
| 882 |
+
});
|
| 883 |
+
updateFollowUpQuestion("A question from the next chat?");
|
| 884 |
+
|
| 885 |
+
await act(async () => {
|
| 886 |
+
response.reject(new Error("model crashed"));
|
| 887 |
+
await regenerate;
|
| 888 |
+
});
|
| 889 |
+
|
| 890 |
+
expect(notifications.show).not.toHaveBeenCalled();
|
| 891 |
+
expect(getFollowUpQuestion()).toBe("A question from the next chat?");
|
| 892 |
+
});
|
| 893 |
+
|
| 894 |
+
it("shows no notification when the regeneration succeeds", async () => {
|
| 895 |
+
vi.mocked(generateChatResponse)
|
| 896 |
+
.mockResolvedValueOnce("An answer.")
|
| 897 |
+
.mockResolvedValueOnce("A regenerated answer.");
|
| 898 |
+
|
| 899 |
+
renderChatInterface();
|
| 900 |
+
await act(async () => {
|
| 901 |
+
await sendMessage(nextQuestion);
|
| 902 |
+
});
|
| 903 |
+
await act(async () => {
|
| 904 |
+
await regenerateResponse();
|
| 905 |
+
});
|
| 906 |
+
|
| 907 |
+
expect(messageListMessages.at(-1)?.content).toBe("A regenerated answer.");
|
| 908 |
+
expect(notifications.show).not.toHaveBeenCalled();
|
| 909 |
+
});
|
| 910 |
+
});
|
| 911 |
+
|
| 912 |
describe("ChatInterface previous follow-up questions", () => {
|
| 913 |
it("does not record an empty follow-up question", async () => {
|
| 914 |
vi.mocked(generateFollowUpQuestion)
|
client/components/AiResponse/ChatInterface.tsx
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 1 |
import { Card, Stack } from "@mantine/core";
|
|
|
|
| 2 |
import { usePubSub } from "create-pubsub/react";
|
| 3 |
import {
|
| 4 |
type KeyboardEvent,
|
|
@@ -19,6 +20,7 @@ import {
|
|
| 19 |
chatInputPubSub,
|
| 20 |
followUpQuestionPubSub,
|
| 21 |
getChatGenerationState,
|
|
|
|
| 22 |
imageSearchResultsPubSub,
|
| 23 |
queryPubSub,
|
| 24 |
settingsPubSub,
|
|
@@ -38,25 +40,45 @@ interface ChatInterfaceProps {
|
|
| 38 |
suppressInitialFollowUp?: boolean;
|
| 39 |
}
|
| 40 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
export default function ChatInterface({
|
| 42 |
initialQuery,
|
| 43 |
initialResponse,
|
| 44 |
initialMessages,
|
| 45 |
suppressInitialFollowUp,
|
| 46 |
}: ChatInterfaceProps) {
|
| 47 |
-
const
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
]
|
| 57 |
-
: initialMessages || [];
|
| 58 |
-
|
| 59 |
-
const [messages, setMessages] = useState<ChatMessage[]>(initialMessagesArray);
|
| 60 |
const [input, setInput] = usePubSub(chatInputPubSub);
|
| 61 |
const [generationState, setGenerationState] = usePubSub(
|
| 62 |
chatGenerationStatePubSub,
|
|
@@ -172,25 +194,14 @@ export default function ChatInterface({
|
|
| 172 |
|
| 173 |
prevInitialMessagesRef.current = initialMessages;
|
| 174 |
|
| 175 |
-
const
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
...initialMessages,
|
| 184 |
-
]
|
| 185 |
-
: initialMessages || [];
|
| 186 |
-
|
| 187 |
-
if (newInitialMessagesArray.length > 0) {
|
| 188 |
-
setMessages(newInitialMessagesArray);
|
| 189 |
-
} else if (initialQuery && initialResponse) {
|
| 190 |
-
setMessages([
|
| 191 |
-
{ role: "user", content: initialQuery },
|
| 192 |
-
{ role: "assistant", content: initialResponse },
|
| 193 |
-
]);
|
| 194 |
}
|
| 195 |
}, [initialQuery, initialResponse, initialMessages]);
|
| 196 |
|
|
@@ -273,13 +284,18 @@ export default function ChatInterface({
|
|
| 273 |
const handleRegenerateResponse = useCallback(async () => {
|
| 274 |
if (
|
| 275 |
getChatGenerationState().isGeneratingResponse ||
|
| 276 |
-
|
|
|
|
| 277 |
messages[messages.length - 1].role !== "assistant"
|
| 278 |
)
|
| 279 |
return;
|
| 280 |
|
| 281 |
const history = messages.slice(0, -1);
|
| 282 |
const lastUser = history[history.length - 1];
|
|
|
|
|
|
|
|
|
|
|
|
|
| 283 |
|
| 284 |
setMessages(history);
|
| 285 |
setGenerationState({
|
|
@@ -313,6 +329,16 @@ export default function ChatInterface({
|
|
| 313 |
}
|
| 314 |
} catch (error) {
|
| 315 |
addLogEntry(`Error re-generating response: ${error}`);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 316 |
} finally {
|
| 317 |
if (isMountedRef.current) {
|
| 318 |
setGenerationState({
|
|
@@ -322,6 +348,7 @@ export default function ChatInterface({
|
|
| 322 |
}
|
| 323 |
}
|
| 324 |
}, [
|
|
|
|
| 325 |
messages,
|
| 326 |
regenerateFollowUpQuestion,
|
| 327 |
settings,
|
|
@@ -432,7 +459,10 @@ export default function ChatInterface({
|
|
| 432 |
return (
|
| 433 |
<Card withBorder shadow="sm" radius="md">
|
| 434 |
<Card.Section withBorder inheritPadding py="xs">
|
| 435 |
-
<ChatHeader
|
|
|
|
|
|
|
|
|
|
| 436 |
</Card.Section>
|
| 437 |
<Stack gap="md" pt="md">
|
| 438 |
<MessageList
|
|
@@ -441,6 +471,7 @@ export default function ChatInterface({
|
|
| 441 |
? [...messages, { role: "assistant", content: streamedResponse }]
|
| 442 |
: messages
|
| 443 |
}
|
|
|
|
| 444 |
onEditMessage={handleEditMessage}
|
| 445 |
onRegenerate={handleRegenerateResponse}
|
| 446 |
isGenerating={generationState.isGeneratingResponse}
|
|
|
|
| 1 |
import { Card, Stack } from "@mantine/core";
|
| 2 |
+
import { notifications } from "@mantine/notifications";
|
| 3 |
import { usePubSub } from "create-pubsub/react";
|
| 4 |
import {
|
| 5 |
type KeyboardEvent,
|
|
|
|
| 20 |
chatInputPubSub,
|
| 21 |
followUpQuestionPubSub,
|
| 22 |
getChatGenerationState,
|
| 23 |
+
getFollowUpQuestion,
|
| 24 |
imageSearchResultsPubSub,
|
| 25 |
queryPubSub,
|
| 26 |
settingsPubSub,
|
|
|
|
| 40 |
suppressInitialFollowUp?: boolean;
|
| 41 |
}
|
| 42 |
|
| 43 |
+
/**
|
| 44 |
+
* The messages the chat starts from, and where its follow-ups begin. The main
|
| 45 |
+
* question and answer lead the list only when the answer has text: after an
|
| 46 |
+
* empty main answer the follow-ups start at 0, so the first follow-up pair is
|
| 47 |
+
* not mistaken for them.
|
| 48 |
+
*/
|
| 49 |
+
function buildInitialConversation(
|
| 50 |
+
initialQuery: string | undefined,
|
| 51 |
+
initialResponse: string | undefined,
|
| 52 |
+
initialMessages: ChatMessage[] = [],
|
| 53 |
+
): { messages: ChatMessage[]; followUpStartIndex: number } {
|
| 54 |
+
if (initialQuery && initialResponse) {
|
| 55 |
+
return {
|
| 56 |
+
messages: [
|
| 57 |
+
{ role: "user", content: initialQuery },
|
| 58 |
+
{ role: "assistant", content: initialResponse },
|
| 59 |
+
...initialMessages,
|
| 60 |
+
],
|
| 61 |
+
followUpStartIndex: 2,
|
| 62 |
+
};
|
| 63 |
+
}
|
| 64 |
+
return { messages: initialMessages, followUpStartIndex: 0 };
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
export default function ChatInterface({
|
| 68 |
initialQuery,
|
| 69 |
initialResponse,
|
| 70 |
initialMessages,
|
| 71 |
suppressInitialFollowUp,
|
| 72 |
}: ChatInterfaceProps) {
|
| 73 |
+
const [initialConversation] = useState(() =>
|
| 74 |
+
buildInitialConversation(initialQuery, initialResponse, initialMessages),
|
| 75 |
+
);
|
| 76 |
+
const [messages, setMessages] = useState<ChatMessage[]>(
|
| 77 |
+
initialConversation.messages,
|
| 78 |
+
);
|
| 79 |
+
const [followUpStartIndex, setFollowUpStartIndex] = useState(
|
| 80 |
+
initialConversation.followUpStartIndex,
|
| 81 |
+
);
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
const [input, setInput] = usePubSub(chatInputPubSub);
|
| 83 |
const [generationState, setGenerationState] = usePubSub(
|
| 84 |
chatGenerationStatePubSub,
|
|
|
|
| 194 |
|
| 195 |
prevInitialMessagesRef.current = initialMessages;
|
| 196 |
|
| 197 |
+
const conversation = buildInitialConversation(
|
| 198 |
+
initialQuery,
|
| 199 |
+
initialResponse,
|
| 200 |
+
initialMessages,
|
| 201 |
+
);
|
| 202 |
+
if (conversation.messages.length > 0) {
|
| 203 |
+
setMessages(conversation.messages);
|
| 204 |
+
setFollowUpStartIndex(conversation.followUpStartIndex);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
}
|
| 206 |
}, [initialQuery, initialResponse, initialMessages]);
|
| 207 |
|
|
|
|
| 284 |
const handleRegenerateResponse = useCallback(async () => {
|
| 285 |
if (
|
| 286 |
getChatGenerationState().isGeneratingResponse ||
|
| 287 |
+
// There must be a follow-up question before the answer to regenerate.
|
| 288 |
+
messages.length - 1 <= followUpStartIndex ||
|
| 289 |
messages[messages.length - 1].role !== "assistant"
|
| 290 |
)
|
| 291 |
return;
|
| 292 |
|
| 293 |
const history = messages.slice(0, -1);
|
| 294 |
const lastUser = history[history.length - 1];
|
| 295 |
+
// Streaming needs the old answer off the list, so keep it and the
|
| 296 |
+
// follow-up that was showing to put back if the regeneration fails.
|
| 297 |
+
const previousAnswer = messages[messages.length - 1];
|
| 298 |
+
const previousFollowUpQuestion = getFollowUpQuestion();
|
| 299 |
|
| 300 |
setMessages(history);
|
| 301 |
setGenerationState({
|
|
|
|
| 329 |
}
|
| 330 |
} catch (error) {
|
| 331 |
addLogEntry(`Error re-generating response: ${error}`);
|
| 332 |
+
if (isMountedRef.current) {
|
| 333 |
+
setStreamedResponse("");
|
| 334 |
+
setMessages((prev) => [...prev, previousAnswer]);
|
| 335 |
+
setFollowUpQuestion(previousFollowUpQuestion);
|
| 336 |
+
notifications.show({
|
| 337 |
+
message:
|
| 338 |
+
"Couldn't re-generate the response. The previous answer has been kept.",
|
| 339 |
+
color: "red",
|
| 340 |
+
});
|
| 341 |
+
}
|
| 342 |
} finally {
|
| 343 |
if (isMountedRef.current) {
|
| 344 |
setGenerationState({
|
|
|
|
| 348 |
}
|
| 349 |
}
|
| 350 |
}, [
|
| 351 |
+
followUpStartIndex,
|
| 352 |
messages,
|
| 353 |
regenerateFollowUpQuestion,
|
| 354 |
settings,
|
|
|
|
| 459 |
return (
|
| 460 |
<Card withBorder shadow="sm" radius="md">
|
| 461 |
<Card.Section withBorder inheritPadding py="xs">
|
| 462 |
+
<ChatHeader
|
| 463 |
+
messages={messages}
|
| 464 |
+
followUpStartIndex={followUpStartIndex}
|
| 465 |
+
/>
|
| 466 |
</Card.Section>
|
| 467 |
<Stack gap="md" pt="md">
|
| 468 |
<MessageList
|
|
|
|
| 471 |
? [...messages, { role: "assistant", content: streamedResponse }]
|
| 472 |
: messages
|
| 473 |
}
|
| 474 |
+
followUpStartIndex={followUpStartIndex}
|
| 475 |
onEditMessage={handleEditMessage}
|
| 476 |
onRegenerate={handleRegenerateResponse}
|
| 477 |
isGenerating={generationState.isGeneratingResponse}
|
client/components/AiResponse/MessageList.test.tsx
CHANGED
|
@@ -11,6 +11,7 @@ vi.mock("@mantine/code-highlight", () => ({
|
|
| 11 |
|
| 12 |
function renderMessageList(props: {
|
| 13 |
messages: ChatMessage[];
|
|
|
|
| 14 |
onEditMessage?: (absoluteIndex: number) => void;
|
| 15 |
onRegenerate?: () => void;
|
| 16 |
isGenerating?: boolean;
|
|
@@ -19,6 +20,7 @@ function renderMessageList(props: {
|
|
| 19 |
<MantineProvider>
|
| 20 |
<MessageList
|
| 21 |
messages={props.messages}
|
|
|
|
| 22 |
onEditMessage={props.onEditMessage ?? vi.fn()}
|
| 23 |
onRegenerate={props.onRegenerate ?? vi.fn()}
|
| 24 |
isGenerating={props.isGenerating ?? false}
|
|
@@ -28,7 +30,7 @@ function renderMessageList(props: {
|
|
| 28 |
}
|
| 29 |
|
| 30 |
describe("MessageList", () => {
|
| 31 |
-
it("renders nothing when there are
|
| 32 |
const messages: ChatMessage[] = [
|
| 33 |
{ role: "user", content: "system instructions" },
|
| 34 |
{ role: "assistant", content: "Ok!" },
|
|
@@ -95,6 +97,55 @@ describe("MessageList", () => {
|
|
| 95 |
});
|
| 96 |
});
|
| 97 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
describe("unterminated reasoning", () => {
|
| 99 |
const messages: ChatMessage[] = [
|
| 100 |
{ role: "user", content: "system instructions" },
|
|
|
|
| 11 |
|
| 12 |
function renderMessageList(props: {
|
| 13 |
messages: ChatMessage[];
|
| 14 |
+
followUpStartIndex?: number;
|
| 15 |
onEditMessage?: (absoluteIndex: number) => void;
|
| 16 |
onRegenerate?: () => void;
|
| 17 |
isGenerating?: boolean;
|
|
|
|
| 20 |
<MantineProvider>
|
| 21 |
<MessageList
|
| 22 |
messages={props.messages}
|
| 23 |
+
followUpStartIndex={props.followUpStartIndex ?? 2}
|
| 24 |
onEditMessage={props.onEditMessage ?? vi.fn()}
|
| 25 |
onRegenerate={props.onRegenerate ?? vi.fn()}
|
| 26 |
isGenerating={props.isGenerating ?? false}
|
|
|
|
| 30 |
}
|
| 31 |
|
| 32 |
describe("MessageList", () => {
|
| 33 |
+
it("renders nothing when there are no follow-up messages", () => {
|
| 34 |
const messages: ChatMessage[] = [
|
| 35 |
{ role: "user", content: "system instructions" },
|
| 36 |
{ role: "assistant", content: "Ok!" },
|
|
|
|
| 97 |
});
|
| 98 |
});
|
| 99 |
|
| 100 |
+
describe("no main question and answer", () => {
|
| 101 |
+
// When the main answer came back empty, the follow-ups start at 0.
|
| 102 |
+
const messages: ChatMessage[] = [
|
| 103 |
+
{ role: "user", content: "Q1" },
|
| 104 |
+
{ role: "assistant", content: "A1" },
|
| 105 |
+
];
|
| 106 |
+
|
| 107 |
+
it("renders the first follow-up pair", () => {
|
| 108 |
+
renderMessageList({ messages, followUpStartIndex: 0 });
|
| 109 |
+
|
| 110 |
+
expect(screen.getByText("Q1")).toBeInTheDocument();
|
| 111 |
+
expect(screen.getByText("A1")).toBeInTheDocument();
|
| 112 |
+
});
|
| 113 |
+
|
| 114 |
+
it("edits the first follow-up question at position 0", () => {
|
| 115 |
+
const onEditMessage = vi.fn();
|
| 116 |
+
renderMessageList({ messages, followUpStartIndex: 0, onEditMessage });
|
| 117 |
+
|
| 118 |
+
fireEvent.click(screen.getByLabelText("Edit message"));
|
| 119 |
+
|
| 120 |
+
expect(onEditMessage).toHaveBeenCalledWith(0);
|
| 121 |
+
});
|
| 122 |
+
});
|
| 123 |
+
|
| 124 |
+
describe("an empty last answer", () => {
|
| 125 |
+
const messages: ChatMessage[] = [
|
| 126 |
+
{ role: "user", content: "system instructions" },
|
| 127 |
+
{ role: "assistant", content: "Ok!" },
|
| 128 |
+
{ role: "user", content: "Q1" },
|
| 129 |
+
{ role: "assistant", content: "" },
|
| 130 |
+
];
|
| 131 |
+
|
| 132 |
+
it("shows No response with a Re-generate button", () => {
|
| 133 |
+
const onRegenerate = vi.fn();
|
| 134 |
+
renderMessageList({ messages, onRegenerate });
|
| 135 |
+
|
| 136 |
+
expect(screen.getByText("No response")).toBeInTheDocument();
|
| 137 |
+
fireEvent.click(screen.getByLabelText("Re-generate response"));
|
| 138 |
+
expect(onRegenerate).toHaveBeenCalledTimes(1);
|
| 139 |
+
});
|
| 140 |
+
|
| 141 |
+
it("shows no bubble for it while the answer is being generated", () => {
|
| 142 |
+
renderMessageList({ messages, isGenerating: true });
|
| 143 |
+
|
| 144 |
+
expect(screen.queryByText("No response")).toBeNull();
|
| 145 |
+
expect(document.querySelectorAll(".mantine-Paper-root")).toHaveLength(1);
|
| 146 |
+
});
|
| 147 |
+
});
|
| 148 |
+
|
| 149 |
describe("unterminated reasoning", () => {
|
| 150 |
const messages: ChatMessage[] = [
|
| 151 |
{ role: "user", content: "system instructions" },
|
client/components/AiResponse/MessageList.tsx
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
import { ActionIcon, Group, Paper, Stack, Tooltip } from "@mantine/core";
|
| 2 |
import { IconPencil, IconRefresh } from "@tabler/icons-react";
|
| 3 |
import { memo } from "react";
|
| 4 |
import type { ChatMessage } from "@/modules/types";
|
|
@@ -6,6 +6,8 @@ import FormattedMarkdown from "./FormattedMarkdown";
|
|
| 6 |
|
| 7 |
interface MessageListProps {
|
| 8 |
messages: ChatMessage[];
|
|
|
|
|
|
|
| 9 |
onEditMessage: (absoluteIndex: number) => void;
|
| 10 |
onRegenerate: () => void;
|
| 11 |
isGenerating: boolean;
|
|
@@ -62,9 +64,15 @@ const Message = memo(
|
|
| 62 |
p="sm"
|
| 63 |
style={{ flex: 1, overflow: "auto" }}
|
| 64 |
>
|
| 65 |
-
|
| 66 |
-
{
|
| 67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
</Paper>
|
| 69 |
|
| 70 |
{canRegenerate && (
|
|
@@ -92,22 +100,28 @@ const Message = memo(
|
|
| 92 |
|
| 93 |
const MessageList = memo(function MessageList({
|
| 94 |
messages,
|
|
|
|
| 95 |
onEditMessage,
|
| 96 |
onRegenerate,
|
| 97 |
isGenerating,
|
| 98 |
}: MessageListProps) {
|
| 99 |
-
if (messages.length <=
|
| 100 |
|
| 101 |
return (
|
| 102 |
<Stack gap="md">
|
| 103 |
{messages.map((message, absoluteIndex) => {
|
| 104 |
// The index is the message's position in `messages`, which is what
|
| 105 |
-
// editing and regenerating act on.
|
| 106 |
-
//
|
| 107 |
-
//
|
| 108 |
-
if (absoluteIndex <
|
| 109 |
const isLastAssistant =
|
| 110 |
absoluteIndex === messages.length - 1 && message.role === "assistant";
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
return (
|
| 112 |
<Message
|
| 113 |
// biome-ignore lint/suspicious/noArrayIndexKey: a message's position in the chat is its identity
|
|
|
|
| 1 |
+
import { ActionIcon, Group, Paper, Stack, Text, Tooltip } from "@mantine/core";
|
| 2 |
import { IconPencil, IconRefresh } from "@tabler/icons-react";
|
| 3 |
import { memo } from "react";
|
| 4 |
import type { ChatMessage } from "@/modules/types";
|
|
|
|
| 6 |
|
| 7 |
interface MessageListProps {
|
| 8 |
messages: ChatMessage[];
|
| 9 |
+
/** Position of the first follow-up message: 2 after the main question and answer, 0 without them. */
|
| 10 |
+
followUpStartIndex: number;
|
| 11 |
onEditMessage: (absoluteIndex: number) => void;
|
| 12 |
onRegenerate: () => void;
|
| 13 |
isGenerating: boolean;
|
|
|
|
| 64 |
p="sm"
|
| 65 |
style={{ flex: 1, overflow: "auto" }}
|
| 66 |
>
|
| 67 |
+
{message.content.length > 0 ? (
|
| 68 |
+
<FormattedMarkdown isGenerating={isGenerating && isLastAssistant}>
|
| 69 |
+
{message.content}
|
| 70 |
+
</FormattedMarkdown>
|
| 71 |
+
) : (
|
| 72 |
+
<Text c="dimmed" fs="italic" size="sm">
|
| 73 |
+
No response
|
| 74 |
+
</Text>
|
| 75 |
+
)}
|
| 76 |
</Paper>
|
| 77 |
|
| 78 |
{canRegenerate && (
|
|
|
|
| 100 |
|
| 101 |
const MessageList = memo(function MessageList({
|
| 102 |
messages,
|
| 103 |
+
followUpStartIndex,
|
| 104 |
onEditMessage,
|
| 105 |
onRegenerate,
|
| 106 |
isGenerating,
|
| 107 |
}: MessageListProps) {
|
| 108 |
+
if (messages.length <= followUpStartIndex) return null;
|
| 109 |
|
| 110 |
return (
|
| 111 |
<Stack gap="md">
|
| 112 |
{messages.map((message, absoluteIndex) => {
|
| 113 |
// The index is the message's position in `messages`, which is what
|
| 114 |
+
// editing and regenerating act on. Messages before the follow-ups are
|
| 115 |
+
// shown above the chat, so they don't render here but keep their
|
| 116 |
+
// position.
|
| 117 |
+
if (absoluteIndex < followUpStartIndex) return null;
|
| 118 |
const isLastAssistant =
|
| 119 |
absoluteIndex === messages.length - 1 && message.role === "assistant";
|
| 120 |
+
// An empty message has nothing to show, except a finished last answer:
|
| 121 |
+
// it renders as "No response" so its Re-generate button has a row. A
|
| 122 |
+
// trailing empty answer while generating is the stream placeholder.
|
| 123 |
+
if (message.content.length === 0 && !(isLastAssistant && !isGenerating))
|
| 124 |
+
return null;
|
| 125 |
return (
|
| 126 |
<Message
|
| 127 |
// biome-ignore lint/suspicious/noArrayIndexKey: a message's position in the chat is its identity
|
client/hooks/useHistoryRestore.ts
CHANGED
|
@@ -20,7 +20,7 @@ import {
|
|
| 20 |
updateIsRestoringFromHistory,
|
| 21 |
updateLlmTextSearchResults,
|
| 22 |
updatePageContents,
|
| 23 |
-
|
| 24 |
updateSuppressNextFollowUp,
|
| 25 |
updateTextGenerationState,
|
| 26 |
updateTextSearchResults,
|
|
@@ -110,11 +110,13 @@ export function useHistoryRestore(
|
|
| 110 |
const savedResponse = await getLatestLlmResponseForEntry(entry);
|
| 111 |
if (savedResponse && savedResponse.trim().length > 0) {
|
| 112 |
updateSuppressNextFollowUp(true);
|
| 113 |
-
|
|
|
|
|
|
|
| 114 |
updateTextGenerationState("completed");
|
| 115 |
} else {
|
| 116 |
updateSuppressNextFollowUp(false);
|
| 117 |
-
|
| 118 |
updateTextGenerationState("idle");
|
| 119 |
}
|
| 120 |
|
|
|
|
| 20 |
updateIsRestoringFromHistory,
|
| 21 |
updateLlmTextSearchResults,
|
| 22 |
updatePageContents,
|
| 23 |
+
updateResponseImmediately,
|
| 24 |
updateSuppressNextFollowUp,
|
| 25 |
updateTextGenerationState,
|
| 26 |
updateTextSearchResults,
|
|
|
|
| 110 |
const savedResponse = await getLatestLlmResponseForEntry(entry);
|
| 111 |
if (savedResponse && savedResponse.trim().length > 0) {
|
| 112 |
updateSuppressNextFollowUp(true);
|
| 113 |
+
// The restore publishes the whole stored answer at once; a throttled
|
| 114 |
+
// write could be overwritten by whatever was queued before it.
|
| 115 |
+
updateResponseImmediately(savedResponse);
|
| 116 |
updateTextGenerationState("completed");
|
| 117 |
} else {
|
| 118 |
updateSuppressNextFollowUp(false);
|
| 119 |
+
updateResponseImmediately("");
|
| 120 |
updateTextGenerationState("idle");
|
| 121 |
}
|
| 122 |
|
client/modules/pubSub.throttle.test.ts
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
| 2 |
+
|
| 3 |
+
const throttleInterval = 1000 / 12;
|
| 4 |
+
|
| 5 |
+
// Each test gets its own copy of the module, so the throttle window opened by
|
| 6 |
+
// one test cannot decide whether the next test's first write is a leading one.
|
| 7 |
+
async function loadResponseChannel() {
|
| 8 |
+
vi.resetModules();
|
| 9 |
+
return await import("./pubSub");
|
| 10 |
+
}
|
| 11 |
+
|
| 12 |
+
describe("response publishing", () => {
|
| 13 |
+
beforeEach(() => {
|
| 14 |
+
vi.useFakeTimers();
|
| 15 |
+
});
|
| 16 |
+
|
| 17 |
+
afterEach(() => {
|
| 18 |
+
vi.useRealTimers();
|
| 19 |
+
});
|
| 20 |
+
|
| 21 |
+
it("publishes one leading and one trailing value per throttle window", async () => {
|
| 22 |
+
const { responsePubSub, updateResponse } = await loadResponseChannel();
|
| 23 |
+
const published: string[] = [];
|
| 24 |
+
const [, onResponseChange] = responsePubSub;
|
| 25 |
+
const unsubscribe = onResponseChange((value) => {
|
| 26 |
+
published.push(value);
|
| 27 |
+
});
|
| 28 |
+
|
| 29 |
+
updateResponse("Hello");
|
| 30 |
+
updateResponse("Hello world");
|
| 31 |
+
updateResponse("Hello world!!!");
|
| 32 |
+
|
| 33 |
+
expect(published).toEqual(["Hello"]);
|
| 34 |
+
|
| 35 |
+
vi.advanceTimersByTime(throttleInterval);
|
| 36 |
+
|
| 37 |
+
expect(published).toEqual(["Hello", "Hello world!!!"]);
|
| 38 |
+
|
| 39 |
+
unsubscribe();
|
| 40 |
+
});
|
| 41 |
+
|
| 42 |
+
it("publishes the final value immediately and drops the queued trailing write", async () => {
|
| 43 |
+
const {
|
| 44 |
+
getResponse,
|
| 45 |
+
responsePubSub,
|
| 46 |
+
updateResponse,
|
| 47 |
+
updateResponseImmediately,
|
| 48 |
+
} = await loadResponseChannel();
|
| 49 |
+
const published: string[] = [];
|
| 50 |
+
const [, onResponseChange] = responsePubSub;
|
| 51 |
+
const unsubscribe = onResponseChange((value) => {
|
| 52 |
+
published.push(value);
|
| 53 |
+
});
|
| 54 |
+
|
| 55 |
+
updateResponse("Hello");
|
| 56 |
+
updateResponse("Hello world, but truncated");
|
| 57 |
+
|
| 58 |
+
updateResponseImmediately("Hello world, the complete answer");
|
| 59 |
+
|
| 60 |
+
expect(getResponse()).toBe("Hello world, the complete answer");
|
| 61 |
+
|
| 62 |
+
vi.advanceTimersByTime(throttleInterval * 3);
|
| 63 |
+
|
| 64 |
+
expect(getResponse()).toBe("Hello world, the complete answer");
|
| 65 |
+
expect(published).toEqual(["Hello", "Hello world, the complete answer"]);
|
| 66 |
+
|
| 67 |
+
unsubscribe();
|
| 68 |
+
});
|
| 69 |
+
});
|
client/modules/pubSub.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
| 1 |
import { createPubSub } from "create-pubsub";
|
| 2 |
-
import throttle from "throttleit";
|
| 3 |
import { addLogEntry } from "./logEntries";
|
| 4 |
import * as safeStorage from "./safeStorage";
|
| 5 |
import {
|
|
@@ -133,7 +132,76 @@ export const [, , getQuery] = queryPubSub;
|
|
| 133 |
|
| 134 |
export const responsePubSub = createPubSub("");
|
| 135 |
|
| 136 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
export const [, , getResponse] = responsePubSub;
|
| 138 |
|
| 139 |
export const [updateSearchPromise, , getSearchPromise] = createPubSub<
|
|
@@ -146,7 +214,7 @@ export const textGenerationStatePubSub =
|
|
| 146 |
export const [updateTextGenerationState, , getTextGenerationState] =
|
| 147 |
textGenerationStatePubSub;
|
| 148 |
|
| 149 |
-
const [, listenToTextGenerationStateChanges] = textGenerationStatePubSub;
|
| 150 |
|
| 151 |
listenToTextGenerationStateChanges((textGenerationState) => {
|
| 152 |
addLogEntry(`Text generation state changed to '${textGenerationState}'`);
|
|
@@ -248,7 +316,8 @@ export const [, , getChatGenerationState] = chatGenerationStatePubSub;
|
|
| 248 |
|
| 249 |
export const followUpQuestionPubSub = createPubSub("");
|
| 250 |
|
| 251 |
-
export const [updateFollowUpQuestion] =
|
|
|
|
| 252 |
|
| 253 |
const conversationSummaryPubSub = createPubSub({
|
| 254 |
conversationId: "",
|
|
|
|
| 1 |
import { createPubSub } from "create-pubsub";
|
|
|
|
| 2 |
import { addLogEntry } from "./logEntries";
|
| 3 |
import * as safeStorage from "./safeStorage";
|
| 4 |
import {
|
|
|
|
| 132 |
|
| 133 |
export const responsePubSub = createPubSub("");
|
| 134 |
|
| 135 |
+
const responseThrottleInterval = 1000 / 12;
|
| 136 |
+
|
| 137 |
+
/**
|
| 138 |
+
* Throttles a publisher to one leading write plus at most one trailing write
|
| 139 |
+
* per interval, keeping the newest value. `publishNow` drops the trailing
|
| 140 |
+
* write, so a caller that already holds the final value can publish it without
|
| 141 |
+
* a queued stale write landing afterwards.
|
| 142 |
+
*/
|
| 143 |
+
function createThrottledPublisher<T>(
|
| 144 |
+
publish: (value: T) => void,
|
| 145 |
+
interval: number,
|
| 146 |
+
) {
|
| 147 |
+
let lastPublishTime = 0;
|
| 148 |
+
let timeoutId: ReturnType<typeof setTimeout> | undefined;
|
| 149 |
+
let pendingValue: T | undefined;
|
| 150 |
+
let hasPendingValue = false;
|
| 151 |
+
|
| 152 |
+
const cancelPending = () => {
|
| 153 |
+
if (timeoutId !== undefined) clearTimeout(timeoutId);
|
| 154 |
+
timeoutId = undefined;
|
| 155 |
+
pendingValue = undefined;
|
| 156 |
+
hasPendingValue = false;
|
| 157 |
+
};
|
| 158 |
+
|
| 159 |
+
const throttled = (value: T) => {
|
| 160 |
+
const now = Date.now();
|
| 161 |
+
const timeSinceLastPublish = now - lastPublishTime;
|
| 162 |
+
|
| 163 |
+
cancelPending();
|
| 164 |
+
|
| 165 |
+
if (timeSinceLastPublish >= interval) {
|
| 166 |
+
lastPublishTime = now;
|
| 167 |
+
publish(value);
|
| 168 |
+
return;
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
pendingValue = value;
|
| 172 |
+
hasPendingValue = true;
|
| 173 |
+
timeoutId = setTimeout(() => {
|
| 174 |
+
timeoutId = undefined;
|
| 175 |
+
if (!hasPendingValue) return;
|
| 176 |
+
const pending = pendingValue as T;
|
| 177 |
+
pendingValue = undefined;
|
| 178 |
+
hasPendingValue = false;
|
| 179 |
+
lastPublishTime = Date.now();
|
| 180 |
+
publish(pending);
|
| 181 |
+
}, interval - timeSinceLastPublish);
|
| 182 |
+
};
|
| 183 |
+
|
| 184 |
+
throttled.publishNow = (value: T) => {
|
| 185 |
+
cancelPending();
|
| 186 |
+
lastPublishTime = Date.now();
|
| 187 |
+
publish(value);
|
| 188 |
+
};
|
| 189 |
+
|
| 190 |
+
return throttled;
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
export const updateResponse = createThrottledPublisher(
|
| 194 |
+
responsePubSub[0],
|
| 195 |
+
responseThrottleInterval,
|
| 196 |
+
);
|
| 197 |
+
|
| 198 |
+
/**
|
| 199 |
+
* Publishes the final response without waiting for the throttle window and
|
| 200 |
+
* drops a trailing write still queued, so the UI and the chat mount read the
|
| 201 |
+
* complete answer instead of the last value that happened to be published.
|
| 202 |
+
*/
|
| 203 |
+
export const updateResponseImmediately = updateResponse.publishNow;
|
| 204 |
+
|
| 205 |
export const [, , getResponse] = responsePubSub;
|
| 206 |
|
| 207 |
export const [updateSearchPromise, , getSearchPromise] = createPubSub<
|
|
|
|
| 214 |
export const [updateTextGenerationState, , getTextGenerationState] =
|
| 215 |
textGenerationStatePubSub;
|
| 216 |
|
| 217 |
+
export const [, listenToTextGenerationStateChanges] = textGenerationStatePubSub;
|
| 218 |
|
| 219 |
listenToTextGenerationStateChanges((textGenerationState) => {
|
| 220 |
addLogEntry(`Text generation state changed to '${textGenerationState}'`);
|
|
|
|
| 316 |
|
| 317 |
export const followUpQuestionPubSub = createPubSub("");
|
| 318 |
|
| 319 |
+
export const [updateFollowUpQuestion, , getFollowUpQuestion] =
|
| 320 |
+
followUpQuestionPubSub;
|
| 321 |
|
| 322 |
const conversationSummaryPubSub = createPubSub({
|
| 323 |
conversationId: "",
|
client/modules/textGeneration.chatBudget.test.ts
CHANGED
|
@@ -23,6 +23,7 @@ vi.mock("./pubSub", () => ({
|
|
| 23 |
updateImageSearchState: vi.fn(),
|
| 24 |
updateLlmTextSearchResults: vi.fn(),
|
| 25 |
updateResponse: vi.fn(),
|
|
|
|
| 26 |
updateSearchPromise: vi.fn(),
|
| 27 |
updateTextGenerationState: vi.fn(),
|
| 28 |
updateTextSearchResults: vi.fn(),
|
|
|
|
| 23 |
updateImageSearchState: vi.fn(),
|
| 24 |
updateLlmTextSearchResults: vi.fn(),
|
| 25 |
updateResponse: vi.fn(),
|
| 26 |
+
updateResponseImmediately: vi.fn(),
|
| 27 |
updateSearchPromise: vi.fn(),
|
| 28 |
updateTextGenerationState: vi.fn(),
|
| 29 |
updateTextSearchResults: vi.fn(),
|
client/modules/textGeneration.degradation.test.ts
CHANGED
|
@@ -42,6 +42,7 @@ vi.mock("./pubSub", () => ({
|
|
| 42 |
getSettings: () => harness.state.settings,
|
| 43 |
getTextGenerationState: () => harness.state.textGenerationState,
|
| 44 |
listenToSettingsChanges: vi.fn(() => vi.fn()),
|
|
|
|
| 45 |
updateChatMessages: vi.fn(),
|
| 46 |
updateConversationSummary: vi.fn(),
|
| 47 |
updateImageSearchResults: vi.fn(),
|
|
@@ -56,6 +57,10 @@ vi.mock("./pubSub", () => ({
|
|
| 56 |
harness.state.response = value;
|
| 57 |
harness.onResponseUpdate.current(value);
|
| 58 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
updateSearchPromise: (promise: Promise<unknown>) => {
|
| 60 |
harness.state.searchPromise = promise;
|
| 61 |
},
|
|
|
|
| 42 |
getSettings: () => harness.state.settings,
|
| 43 |
getTextGenerationState: () => harness.state.textGenerationState,
|
| 44 |
listenToSettingsChanges: vi.fn(() => vi.fn()),
|
| 45 |
+
listenToTextGenerationStateChanges: vi.fn(() => vi.fn()),
|
| 46 |
updateChatMessages: vi.fn(),
|
| 47 |
updateConversationSummary: vi.fn(),
|
| 48 |
updateImageSearchResults: vi.fn(),
|
|
|
|
| 57 |
harness.state.response = value;
|
| 58 |
harness.onResponseUpdate.current(value);
|
| 59 |
},
|
| 60 |
+
updateResponseImmediately: (value: string) => {
|
| 61 |
+
harness.state.response = value;
|
| 62 |
+
harness.onResponseUpdate.current(value);
|
| 63 |
+
},
|
| 64 |
updateSearchPromise: (promise: Promise<unknown>) => {
|
| 65 |
harness.state.searchPromise = promise;
|
| 66 |
},
|
client/modules/textGeneration.inference.test.ts
CHANGED
|
@@ -20,6 +20,7 @@ vi.mock("./pubSub", () => ({
|
|
| 20 |
updateImageSearchState: vi.fn(),
|
| 21 |
updateLlmTextSearchResults: vi.fn(),
|
| 22 |
updateResponse: vi.fn(),
|
|
|
|
| 23 |
updateSearchPromise: vi.fn(),
|
| 24 |
updateTextGenerationState: vi.fn(),
|
| 25 |
updateTextSearchResults: vi.fn(),
|
|
|
|
| 20 |
updateImageSearchState: vi.fn(),
|
| 21 |
updateLlmTextSearchResults: vi.fn(),
|
| 22 |
updateResponse: vi.fn(),
|
| 23 |
+
updateResponseImmediately: vi.fn(),
|
| 24 |
updateSearchPromise: vi.fn(),
|
| 25 |
updateTextGenerationState: vi.fn(),
|
| 26 |
updateTextSearchResults: vi.fn(),
|
client/modules/textGeneration.responsePersistence.test.ts
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { beforeEach, describe, expect, it, vi } from "vitest";
|
| 2 |
+
|
| 3 |
+
const harness = vi.hoisted(() => ({
|
| 4 |
+
saved: [] as Array<{ query: string; response: string; model: string }>,
|
| 5 |
+
responseAtCompletion: { current: null as string | null },
|
| 6 |
+
}));
|
| 7 |
+
|
| 8 |
+
vi.mock("./history", () => ({
|
| 9 |
+
getCurrentSearchRunId: vi.fn(() => "run-1"),
|
| 10 |
+
saveLlmResponseForQuery: vi.fn(
|
| 11 |
+
(query: string, response: string, model: string) => {
|
| 12 |
+
harness.saved.push({ query, response, model });
|
| 13 |
+
return Promise.resolve();
|
| 14 |
+
},
|
| 15 |
+
),
|
| 16 |
+
updateSearchResults: vi.fn(() => Promise.resolve()),
|
| 17 |
+
}));
|
| 18 |
+
|
| 19 |
+
vi.mock("./logEntries", () => ({ addLogEntry: vi.fn() }));
|
| 20 |
+
|
| 21 |
+
vi.mock("./notifications", () => ({ showAiCompleteNotification: vi.fn() }));
|
| 22 |
+
|
| 23 |
+
vi.mock("./pageContent", () => ({
|
| 24 |
+
fetchPageContents: vi.fn(() => Promise.resolve({})),
|
| 25 |
+
}));
|
| 26 |
+
|
| 27 |
+
vi.mock("./search", () => ({
|
| 28 |
+
searchText: vi.fn(() =>
|
| 29 |
+
Promise.resolve({
|
| 30 |
+
results: [["Sky", "A snippet", "https://example.com/sky"]],
|
| 31 |
+
stale: false,
|
| 32 |
+
}),
|
| 33 |
+
),
|
| 34 |
+
searchImages: vi.fn(() => Promise.resolve({ results: [], stale: false })),
|
| 35 |
+
}));
|
| 36 |
+
|
| 37 |
+
vi.mock("./searchTokenHash", () => ({
|
| 38 |
+
getSearchTokenHash: vi.fn(() => Promise.resolve("mock-token")),
|
| 39 |
+
}));
|
| 40 |
+
|
| 41 |
+
import {
|
| 42 |
+
getResponse,
|
| 43 |
+
getSettings,
|
| 44 |
+
queryPubSub,
|
| 45 |
+
textGenerationStatePubSub,
|
| 46 |
+
updateSettings,
|
| 47 |
+
} from "./pubSub";
|
| 48 |
+
import { searchAndRespond } from "./textGeneration";
|
| 49 |
+
|
| 50 |
+
const throttleInterval = 1000 / 12;
|
| 51 |
+
|
| 52 |
+
const mockFetch = vi.fn();
|
| 53 |
+
vi.stubGlobal("fetch", mockFetch);
|
| 54 |
+
|
| 55 |
+
function sseStream(frames: string[]) {
|
| 56 |
+
const encoder = new TextEncoder();
|
| 57 |
+
return new Response(
|
| 58 |
+
new ReadableStream({
|
| 59 |
+
start(controller) {
|
| 60 |
+
for (const frame of frames) controller.enqueue(encoder.encode(frame));
|
| 61 |
+
controller.close();
|
| 62 |
+
},
|
| 63 |
+
}),
|
| 64 |
+
{ status: 200 },
|
| 65 |
+
);
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
function contentFrame(content: string) {
|
| 69 |
+
return `data: ${JSON.stringify({ choices: [{ delta: { content } }] })}\n`;
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
describe("response persistence", () => {
|
| 73 |
+
beforeEach(() => {
|
| 74 |
+
harness.saved.length = 0;
|
| 75 |
+
harness.responseAtCompletion.current = null;
|
| 76 |
+
mockFetch.mockReset();
|
| 77 |
+
queryPubSub[0]("why is the sky blue");
|
| 78 |
+
updateSettings({
|
| 79 |
+
...getSettings(),
|
| 80 |
+
inferenceType: "internal",
|
| 81 |
+
enableAiResponse: true,
|
| 82 |
+
enableTextSearch: true,
|
| 83 |
+
enableImageSearch: false,
|
| 84 |
+
enableNotificationOnAiComplete: false,
|
| 85 |
+
enablePageContentFetch: false,
|
| 86 |
+
});
|
| 87 |
+
});
|
| 88 |
+
|
| 89 |
+
it("saves the full answer when the last chunk lands inside the throttle window", async () => {
|
| 90 |
+
mockFetch.mockResolvedValue(
|
| 91 |
+
sseStream([contentFrame("Hello"), contentFrame(" world!!! done")]),
|
| 92 |
+
);
|
| 93 |
+
|
| 94 |
+
const unsubscribe = textGenerationStatePubSub[1]((state) => {
|
| 95 |
+
if (state === "completed") {
|
| 96 |
+
harness.responseAtCompletion.current = getResponse();
|
| 97 |
+
}
|
| 98 |
+
});
|
| 99 |
+
|
| 100 |
+
await searchAndRespond();
|
| 101 |
+
unsubscribe();
|
| 102 |
+
|
| 103 |
+
expect(harness.saved).toHaveLength(1);
|
| 104 |
+
expect(harness.saved[0].response).toBe("Hello world!!! done");
|
| 105 |
+
expect(harness.responseAtCompletion.current).toBe("Hello world!!! done");
|
| 106 |
+
|
| 107 |
+
await new Promise((resolve) => setTimeout(resolve, throttleInterval * 3));
|
| 108 |
+
|
| 109 |
+
expect(getResponse()).toBe("Hello world!!! done");
|
| 110 |
+
});
|
| 111 |
+
});
|
client/modules/textGeneration.test.ts
CHANGED
|
@@ -22,6 +22,7 @@ vi.mock("./pubSub", () => ({
|
|
| 22 |
getResponse: vi.fn(),
|
| 23 |
getQuery: vi.fn(),
|
| 24 |
updateResponse: vi.fn(),
|
|
|
|
| 25 |
updateSearchPromise: vi.fn(),
|
| 26 |
updateTextSearchResults: vi.fn(),
|
| 27 |
updateTextSearchState: vi.fn(),
|
|
|
|
| 22 |
getResponse: vi.fn(),
|
| 23 |
getQuery: vi.fn(),
|
| 24 |
updateResponse: vi.fn(),
|
| 25 |
+
updateResponseImmediately: vi.fn(),
|
| 26 |
updateSearchPromise: vi.fn(),
|
| 27 |
updateTextSearchResults: vi.fn(),
|
| 28 |
updateTextSearchState: vi.fn(),
|
client/modules/textGeneration.ts
CHANGED
|
@@ -12,7 +12,6 @@ import { fetchPageContents } from "./pageContent";
|
|
| 12 |
import {
|
| 13 |
getConversationSummary,
|
| 14 |
getQuery,
|
| 15 |
-
getResponse,
|
| 16 |
getSettings,
|
| 17 |
getTextGenerationState,
|
| 18 |
listenToSettingsChanges,
|
|
@@ -23,6 +22,7 @@ import {
|
|
| 23 |
updateLlmTextSearchResults,
|
| 24 |
updatePageContents,
|
| 25 |
updateResponse,
|
|
|
|
| 26 |
updateSearchPromise,
|
| 27 |
updateSuppressNextFollowUp,
|
| 28 |
updateTextGenerationState,
|
|
@@ -51,7 +51,7 @@ import type {
|
|
| 51 |
const SUMMARY_TOKEN_LIMIT = 800;
|
| 52 |
|
| 53 |
type InferenceStrategy = {
|
| 54 |
-
generateText: () => Promise<
|
| 55 |
generateChat: (
|
| 56 |
messages: ChatMessage[],
|
| 57 |
onUpdate: (partialResponse: string) => void,
|
|
@@ -280,12 +280,12 @@ export async function searchAndRespond() {
|
|
| 280 |
updateTextGenerationState("loadingModel");
|
| 281 |
}
|
| 282 |
const strategy = await getCurrentInferenceStrategy();
|
| 283 |
-
await strategy.generateText();
|
| 284 |
|
| 285 |
try {
|
| 286 |
await saveLlmResponseForQuery(
|
| 287 |
getQuery(),
|
| 288 |
-
|
| 289 |
getCurrentModelName(),
|
| 290 |
);
|
| 291 |
} catch (e) {
|
|
@@ -294,6 +294,12 @@ export async function searchAndRespond() {
|
|
| 294 |
);
|
| 295 |
}
|
| 296 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 297 |
updateTextGenerationState("completed");
|
| 298 |
|
| 299 |
if (settings.enableNotificationOnAiComplete) {
|
|
|
|
| 12 |
import {
|
| 13 |
getConversationSummary,
|
| 14 |
getQuery,
|
|
|
|
| 15 |
getSettings,
|
| 16 |
getTextGenerationState,
|
| 17 |
listenToSettingsChanges,
|
|
|
|
| 22 |
updateLlmTextSearchResults,
|
| 23 |
updatePageContents,
|
| 24 |
updateResponse,
|
| 25 |
+
updateResponseImmediately,
|
| 26 |
updateSearchPromise,
|
| 27 |
updateSuppressNextFollowUp,
|
| 28 |
updateTextGenerationState,
|
|
|
|
| 51 |
const SUMMARY_TOKEN_LIMIT = 800;
|
| 52 |
|
| 53 |
type InferenceStrategy = {
|
| 54 |
+
generateText: () => Promise<string>;
|
| 55 |
generateChat: (
|
| 56 |
messages: ChatMessage[],
|
| 57 |
onUpdate: (partialResponse: string) => void,
|
|
|
|
| 280 |
updateTextGenerationState("loadingModel");
|
| 281 |
}
|
| 282 |
const strategy = await getCurrentInferenceStrategy();
|
| 283 |
+
const finalResponse = await strategy.generateText();
|
| 284 |
|
| 285 |
try {
|
| 286 |
await saveLlmResponseForQuery(
|
| 287 |
getQuery(),
|
| 288 |
+
finalResponse,
|
| 289 |
getCurrentModelName(),
|
| 290 |
);
|
| 291 |
} catch (e) {
|
|
|
|
| 294 |
);
|
| 295 |
}
|
| 296 |
|
| 297 |
+
// The streaming writes are throttled, so the last chunk may still be
|
| 298 |
+
// queued here. Publishing the returned text unthrottled before the state
|
| 299 |
+
// flips to "completed" is what makes the mounted chat read the whole
|
| 300 |
+
// answer.
|
| 301 |
+
updateResponseImmediately(finalResponse);
|
| 302 |
+
|
| 303 |
updateTextGenerationState("completed");
|
| 304 |
|
| 305 |
if (settings.enableNotificationOnAiComplete) {
|
client/modules/textGenerationWithHorde.test.ts
CHANGED
|
@@ -78,7 +78,7 @@ describe("textGenerationWithHorde", () => {
|
|
| 78 |
}),
|
| 79 |
);
|
| 80 |
|
| 81 |
-
await generateTextWithHorde();
|
| 82 |
|
| 83 |
expect(canStartResponding).toHaveBeenCalled();
|
| 84 |
expect(vi.mocked(updateTextGenerationState).mock.calls).toEqual([
|
|
@@ -365,7 +365,7 @@ describe("textGenerationWithHorde", () => {
|
|
| 365 |
workers: Array<{ models: string[]; max_length: number }>;
|
| 366 |
monthStats?: Record<string, number>;
|
| 367 |
statsFails?: boolean;
|
| 368 |
-
statusResponder: (pollIndex: number) => unknown;
|
| 369 |
}) {
|
| 370 |
let idCounter = 0;
|
| 371 |
let pollCounter = 0;
|
|
@@ -385,7 +385,7 @@ describe("textGenerationWithHorde", () => {
|
|
| 385 |
if (init?.method === "DELETE") {
|
| 386 |
return jsonResponse({});
|
| 387 |
}
|
| 388 |
-
const reply = statusResponder(pollCounter++);
|
| 389 |
return reply instanceof Response ? reply : jsonResponse(reply);
|
| 390 |
},
|
| 391 |
);
|
|
@@ -539,6 +539,91 @@ describe("textGenerationWithHorde", () => {
|
|
| 539 |
expect(generationRequestBodies()).toHaveLength(2);
|
| 540 |
});
|
| 541 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 542 |
it("reuses the cached ranking for the next generation", async () => {
|
| 543 |
routeHordeFetch({
|
| 544 |
workers: [{ models: ["m-a"], max_length: 1024 }],
|
|
|
|
| 78 |
}),
|
| 79 |
);
|
| 80 |
|
| 81 |
+
await expect(generateTextWithHorde()).resolves.toBe("Hello world");
|
| 82 |
|
| 83 |
expect(canStartResponding).toHaveBeenCalled();
|
| 84 |
expect(vi.mocked(updateTextGenerationState).mock.calls).toEqual([
|
|
|
|
| 365 |
workers: Array<{ models: string[]; max_length: number }>;
|
| 366 |
monthStats?: Record<string, number>;
|
| 367 |
statsFails?: boolean;
|
| 368 |
+
statusResponder: (pollIndex: number, url: string) => unknown;
|
| 369 |
}) {
|
| 370 |
let idCounter = 0;
|
| 371 |
let pollCounter = 0;
|
|
|
|
| 385 |
if (init?.method === "DELETE") {
|
| 386 |
return jsonResponse({});
|
| 387 |
}
|
| 388 |
+
const reply = statusResponder(pollCounter++, url);
|
| 389 |
return reply instanceof Response ? reply : jsonResponse(reply);
|
| 390 |
},
|
| 391 |
);
|
|
|
|
| 539 |
expect(generationRequestBodies()).toHaveLength(2);
|
| 540 |
});
|
| 541 |
|
| 542 |
+
/** Answers each job's polls from its own script, by the job id in the URL. */
|
| 543 |
+
function perJobResponder(
|
| 544 |
+
scripts: Record<string, (jobPollIndex: number) => unknown>,
|
| 545 |
+
) {
|
| 546 |
+
const jobPolls: Record<string, number> = {};
|
| 547 |
+
return (_pollIndex: number, url: string) => {
|
| 548 |
+
const jobId = url.slice(url.lastIndexOf("/") + 1);
|
| 549 |
+
const jobPollIndex = jobPolls[jobId] ?? 0;
|
| 550 |
+
jobPolls[jobId] = jobPollIndex + 1;
|
| 551 |
+
return scripts[jobId](jobPollIndex);
|
| 552 |
+
};
|
| 553 |
+
}
|
| 554 |
+
|
| 555 |
+
const pendingResponse = { done: false, is_possible: true, generations: [] };
|
| 556 |
+
|
| 557 |
+
it("serves the healthy job when its sibling faults first", async () => {
|
| 558 |
+
routeHordeFetch({
|
| 559 |
+
workers: [{ models: ["m-a"], max_length: 1024 }],
|
| 560 |
+
monthStats: { "m-a": 10 },
|
| 561 |
+
statusResponder: perJobResponder({
|
| 562 |
+
"gen-1": () => ({ done: true, faulted: true }),
|
| 563 |
+
"gen-2": (poll) => (poll === 0 ? pendingResponse : doneResponse),
|
| 564 |
+
}),
|
| 565 |
+
});
|
| 566 |
+
|
| 567 |
+
const { generateTextWithHorde } = await import(
|
| 568 |
+
"./textGenerationWithHorde"
|
| 569 |
+
);
|
| 570 |
+
await expect(generateTextWithHorde()).resolves.toBe("Top model answer");
|
| 571 |
+
|
| 572 |
+
expect(updateResponse).toHaveBeenCalledWith("Top model answer");
|
| 573 |
+
expect(generationRequestBodies()).toHaveLength(2);
|
| 574 |
+
});
|
| 575 |
+
|
| 576 |
+
it("still retries with any model when one job faults and the other cannot take the job", async () => {
|
| 577 |
+
routeHordeFetch({
|
| 578 |
+
workers: [{ models: ["m-a"], max_length: 1024 }],
|
| 579 |
+
monthStats: { "m-a": 10 },
|
| 580 |
+
statusResponder: perJobResponder({
|
| 581 |
+
// The faulted job is first in submission order, so picking the
|
| 582 |
+
// first error would hide the "not possible" that the retry needs.
|
| 583 |
+
"gen-1": () => ({ done: true, faulted: true }),
|
| 584 |
+
"gen-2": () => ({ done: true, is_possible: false }),
|
| 585 |
+
"gen-3": () => doneResponse,
|
| 586 |
+
"gen-4": () => doneResponse,
|
| 587 |
+
}),
|
| 588 |
+
});
|
| 589 |
+
|
| 590 |
+
const { generateTextWithHorde } = await import(
|
| 591 |
+
"./textGenerationWithHorde"
|
| 592 |
+
);
|
| 593 |
+
await expect(generateTextWithHorde()).resolves.toBe("Top model answer");
|
| 594 |
+
|
| 595 |
+
expect(generationRequestBodies()).toHaveLength(4);
|
| 596 |
+
});
|
| 597 |
+
|
| 598 |
+
it("reports an interrupt during the race and submits no retry", async () => {
|
| 599 |
+
let interrupted = false;
|
| 600 |
+
vi.mocked(getTextGenerationState).mockImplementation(() =>
|
| 601 |
+
interrupted ? "interrupted" : "generating",
|
| 602 |
+
);
|
| 603 |
+
routeHordeFetch({
|
| 604 |
+
workers: [{ models: ["m-a"], max_length: 1024 }],
|
| 605 |
+
monthStats: { "m-a": 10 },
|
| 606 |
+
statusResponder: perJobResponder({
|
| 607 |
+
"gen-1": () => ({ done: true, is_possible: false }),
|
| 608 |
+
"gen-2": (poll) => {
|
| 609 |
+
// The user presses Stop while this job is still queued, after its
|
| 610 |
+
// sibling has already reported it cannot take the job.
|
| 611 |
+
if (poll >= 1) interrupted = true;
|
| 612 |
+
return pendingResponse;
|
| 613 |
+
},
|
| 614 |
+
}),
|
| 615 |
+
});
|
| 616 |
+
|
| 617 |
+
const { generateTextWithHorde } = await import(
|
| 618 |
+
"./textGenerationWithHorde"
|
| 619 |
+
);
|
| 620 |
+
await expect(generateTextWithHorde()).rejects.toThrow(
|
| 621 |
+
"Generation interrupted",
|
| 622 |
+
);
|
| 623 |
+
|
| 624 |
+
expect(generationRequestBodies()).toHaveLength(2);
|
| 625 |
+
});
|
| 626 |
+
|
| 627 |
it("reuses the cached ranking for the next generation", async () => {
|
| 628 |
routeHordeFetch({
|
| 629 |
workers: [{ models: ["m-a"], max_length: 1024 }],
|
client/modules/textGenerationWithHorde.ts
CHANGED
|
@@ -493,7 +493,7 @@ export async function generateTextWithHorde() {
|
|
| 493 |
// job is submitted shows the response card and its Stop button for the
|
| 494 |
// whole queue wait, which is what makes an interrupt possible at all.
|
| 495 |
updateTextGenerationState("generating");
|
| 496 |
-
await executeHordeGeneration(messages, (text) => {
|
| 497 |
updateResponse(text);
|
| 498 |
});
|
| 499 |
}
|
|
@@ -505,6 +505,25 @@ export async function generateChatWithHorde(
|
|
| 505 |
return await executeHordeGeneration(messages, onUpdate);
|
| 506 |
}
|
| 507 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 508 |
async function raceGenerations(
|
| 509 |
messages: ChatMessage[],
|
| 510 |
models: string[] | undefined,
|
|
@@ -554,7 +573,13 @@ async function raceGenerations(
|
|
| 554 |
).then((result: string) => ({ result, generationId: generation.id })),
|
| 555 |
);
|
| 556 |
|
| 557 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 558 |
|
| 559 |
await Promise.all(
|
| 560 |
generations
|
|
|
|
| 493 |
// job is submitted shows the response card and its Stop button for the
|
| 494 |
// whole queue wait, which is what makes an interrupt possible at all.
|
| 495 |
updateTextGenerationState("generating");
|
| 496 |
+
return await executeHordeGeneration(messages, (text) => {
|
| 497 |
updateResponse(text);
|
| 498 |
});
|
| 499 |
}
|
|
|
|
| 505 |
return await executeHordeGeneration(messages, onUpdate);
|
| 506 |
}
|
| 507 |
|
| 508 |
+
/**
|
| 509 |
+
* The error to report when every raced job failed. `AggregateError.errors` is
|
| 510 |
+
* in submission order, not failure order, so the choice goes by priority: an
|
| 511 |
+
* interrupt first, so a stop never turns into a retry, then "not possible",
|
| 512 |
+
* the original object `executeHordeGeneration` retries on, then the first.
|
| 513 |
+
*/
|
| 514 |
+
function pickRaceFailure(errors: unknown[]): unknown {
|
| 515 |
+
const withMessage = (message: string) =>
|
| 516 |
+
errors.find(
|
| 517 |
+
(error) =>
|
| 518 |
+
error instanceof ChatGenerationError && error.message === message,
|
| 519 |
+
);
|
| 520 |
+
return (
|
| 521 |
+
withMessage("Generation interrupted") ??
|
| 522 |
+
withMessage(GENERATION_NOT_POSSIBLE_MESSAGE) ??
|
| 523 |
+
errors[0]
|
| 524 |
+
);
|
| 525 |
+
}
|
| 526 |
+
|
| 527 |
async function raceGenerations(
|
| 528 |
messages: ChatMessage[],
|
| 529 |
models: string[] | undefined,
|
|
|
|
| 573 |
).then((result: string) => ({ result, generationId: generation.id })),
|
| 574 |
);
|
| 575 |
|
| 576 |
+
// The first job to answer wins; a job that fails is ignored while another
|
| 577 |
+
// is still running, so one crashed worker cannot sink a healthy sibling.
|
| 578 |
+
const winner = await Promise.any(statusPromises).catch((error: unknown) => {
|
| 579 |
+
throw error instanceof AggregateError
|
| 580 |
+
? pickRaceFailure(error.errors)
|
| 581 |
+
: error;
|
| 582 |
+
});
|
| 583 |
|
| 584 |
await Promise.all(
|
| 585 |
generations
|
client/modules/textGenerationWithInternalApi.test.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
| 2 |
import {
|
| 3 |
getQuery,
|
| 4 |
getTextGenerationState,
|
|
|
|
| 5 |
updateResponse,
|
| 6 |
updateTextGenerationState,
|
| 7 |
} from "./pubSub";
|
|
@@ -9,11 +10,12 @@ import {
|
|
| 9 |
ChatGenerationError,
|
| 10 |
canStartResponding,
|
| 11 |
} from "./textGenerationUtilities";
|
| 12 |
-
import type { ChatMessage } from "./types";
|
| 13 |
|
| 14 |
vi.mock("./pubSub", () => ({
|
| 15 |
getQuery: vi.fn().mockReturnValue("test query"),
|
| 16 |
getTextGenerationState: vi.fn().mockReturnValue("idle"),
|
|
|
|
| 17 |
updateResponse: vi.fn(),
|
| 18 |
updateTextGenerationState: vi.fn(),
|
| 19 |
}));
|
|
@@ -65,6 +67,47 @@ function streamResponse(chunks: Array<string | Uint8Array>, status = 200) {
|
|
| 65 |
return new Response(body, { status });
|
| 66 |
}
|
| 67 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
async function generateChatFromChunks(chunks: Array<string | Uint8Array>) {
|
| 69 |
const { generateChatWithInternalApi } = await import(
|
| 70 |
"./textGenerationWithInternalApi"
|
|
@@ -99,7 +142,7 @@ describe("textGenerationWithInternalApi", () => {
|
|
| 99 |
),
|
| 100 |
);
|
| 101 |
|
| 102 |
-
await generateTextWithInternalApi();
|
| 103 |
|
| 104 |
expect(canStartResponding).toHaveBeenCalled();
|
| 105 |
expect(updateTextGenerationState).toHaveBeenCalledWith(
|
|
@@ -257,4 +300,85 @@ describe("textGenerationWithInternalApi", () => {
|
|
| 257 |
expect(onUpdate).toHaveBeenCalledWith("Partial");
|
| 258 |
});
|
| 259 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 260 |
});
|
|
|
|
| 2 |
import {
|
| 3 |
getQuery,
|
| 4 |
getTextGenerationState,
|
| 5 |
+
listenToTextGenerationStateChanges,
|
| 6 |
updateResponse,
|
| 7 |
updateTextGenerationState,
|
| 8 |
} from "./pubSub";
|
|
|
|
| 10 |
ChatGenerationError,
|
| 11 |
canStartResponding,
|
| 12 |
} from "./textGenerationUtilities";
|
| 13 |
+
import type { ChatMessage, TextGenerationState } from "./types";
|
| 14 |
|
| 15 |
vi.mock("./pubSub", () => ({
|
| 16 |
getQuery: vi.fn().mockReturnValue("test query"),
|
| 17 |
getTextGenerationState: vi.fn().mockReturnValue("idle"),
|
| 18 |
+
listenToTextGenerationStateChanges: vi.fn(() => vi.fn()),
|
| 19 |
updateResponse: vi.fn(),
|
| 20 |
updateTextGenerationState: vi.fn(),
|
| 21 |
}));
|
|
|
|
| 67 |
return new Response(body, { status });
|
| 68 |
}
|
| 69 |
|
| 70 |
+
/**
|
| 71 |
+
* A response whose stream sends `chunks` and then stays open, as a stalled
|
| 72 |
+
* upstream does, with a spy on the stream's cancel.
|
| 73 |
+
*/
|
| 74 |
+
function openStreamResponse(chunks: string[]) {
|
| 75 |
+
const cancel = vi.fn();
|
| 76 |
+
const encoder = new TextEncoder();
|
| 77 |
+
const body = new ReadableStream({
|
| 78 |
+
start(controller) {
|
| 79 |
+
for (const chunk of chunks) controller.enqueue(encoder.encode(chunk));
|
| 80 |
+
},
|
| 81 |
+
cancel,
|
| 82 |
+
});
|
| 83 |
+
return { response: new Response(body), cancel };
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
/** A closed stream, with a spy on its cancel. */
|
| 87 |
+
function closedStreamResponse(chunks: string[]) {
|
| 88 |
+
const cancel = vi.fn();
|
| 89 |
+
const encoder = new TextEncoder();
|
| 90 |
+
const body = new ReadableStream({
|
| 91 |
+
start(controller) {
|
| 92 |
+
for (const chunk of chunks) controller.enqueue(encoder.encode(chunk));
|
| 93 |
+
controller.close();
|
| 94 |
+
},
|
| 95 |
+
cancel,
|
| 96 |
+
});
|
| 97 |
+
return { response: new Response(body), cancel };
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
/** The state listener the module registered last. */
|
| 101 |
+
function lastStateListener() {
|
| 102 |
+
const call = vi.mocked(listenToTextGenerationStateChanges).mock.calls.at(-1);
|
| 103 |
+
if (!call) throw new Error("no state listener was registered");
|
| 104 |
+
return call[0] as (state: TextGenerationState) => void;
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
function fetchSignal(): AbortSignal {
|
| 108 |
+
return mockFetch.mock.calls[0][1].signal;
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
async function generateChatFromChunks(chunks: Array<string | Uint8Array>) {
|
| 112 |
const { generateChatWithInternalApi } = await import(
|
| 113 |
"./textGenerationWithInternalApi"
|
|
|
|
| 142 |
),
|
| 143 |
);
|
| 144 |
|
| 145 |
+
await expect(generateTextWithInternalApi()).resolves.toBe("Hello");
|
| 146 |
|
| 147 |
expect(canStartResponding).toHaveBeenCalled();
|
| 148 |
expect(updateTextGenerationState).toHaveBeenCalledWith(
|
|
|
|
| 300 |
expect(onUpdate).toHaveBeenCalledWith("Partial");
|
| 301 |
});
|
| 302 |
});
|
| 303 |
+
|
| 304 |
+
describe("cancelling the stream", () => {
|
| 305 |
+
it("cancels the request when generation is interrupted mid-stream", async () => {
|
| 306 |
+
const { generateTextWithInternalApi } = await import(
|
| 307 |
+
"./textGenerationWithInternalApi"
|
| 308 |
+
);
|
| 309 |
+
const stream = openStreamResponse([
|
| 310 |
+
'data: {"choices":[{"delta":{"content":"partial"}}]}\n',
|
| 311 |
+
]);
|
| 312 |
+
mockFetch.mockResolvedValueOnce(stream.response);
|
| 313 |
+
vi.mocked(getTextGenerationState).mockReturnValue("interrupted");
|
| 314 |
+
|
| 315 |
+
await expect(generateTextWithInternalApi()).rejects.toThrow(
|
| 316 |
+
"Generation interrupted",
|
| 317 |
+
);
|
| 318 |
+
|
| 319 |
+
expect(fetchSignal().aborted).toBe(true);
|
| 320 |
+
expect(stream.cancel).toHaveBeenCalled();
|
| 321 |
+
});
|
| 322 |
+
|
| 323 |
+
it("cancels the request when the stream sends an error frame", async () => {
|
| 324 |
+
const { generateChatWithInternalApi } = await import(
|
| 325 |
+
"./textGenerationWithInternalApi"
|
| 326 |
+
);
|
| 327 |
+
const stream = openStreamResponse(['data: {"error":"boom"}\n']);
|
| 328 |
+
mockFetch.mockResolvedValueOnce(stream.response);
|
| 329 |
+
|
| 330 |
+
const error = await generateChatWithInternalApi(
|
| 331 |
+
[{ role: "user", content: "Hi" }],
|
| 332 |
+
vi.fn(),
|
| 333 |
+
).catch((caught: unknown) => caught);
|
| 334 |
+
|
| 335 |
+
expect(error).toBeInstanceOf(ChatGenerationError);
|
| 336 |
+
expect((error as Error).message).toBe("boom");
|
| 337 |
+
expect(fetchSignal().aborted).toBe(true);
|
| 338 |
+
expect(stream.cancel).toHaveBeenCalled();
|
| 339 |
+
});
|
| 340 |
+
|
| 341 |
+
it("stops a silent stream as soon as generation is interrupted", async () => {
|
| 342 |
+
const { generateChatWithInternalApi } = await import(
|
| 343 |
+
"./textGenerationWithInternalApi"
|
| 344 |
+
);
|
| 345 |
+
const stream = openStreamResponse([]);
|
| 346 |
+
mockFetch.mockResolvedValueOnce(stream.response);
|
| 347 |
+
|
| 348 |
+
const chat = generateChatWithInternalApi(
|
| 349 |
+
[{ role: "user", content: "Hi" }],
|
| 350 |
+
vi.fn(),
|
| 351 |
+
);
|
| 352 |
+
const outcome = expect(chat).rejects.toThrow(
|
| 353 |
+
"Chat generation interrupted",
|
| 354 |
+
);
|
| 355 |
+
await vi.waitFor(() => expect(mockFetch).toHaveBeenCalled());
|
| 356 |
+
// No chunk ever arrives, so only the state change can end the wait.
|
| 357 |
+
lastStateListener()("interrupted");
|
| 358 |
+
await outcome;
|
| 359 |
+
|
| 360 |
+
expect(fetchSignal().aborted).toBe(true);
|
| 361 |
+
expect(stream.cancel).toHaveBeenCalled();
|
| 362 |
+
});
|
| 363 |
+
|
| 364 |
+
it("leaves a finished request alone and stops listening", async () => {
|
| 365 |
+
const { generateChatWithInternalApi } = await import(
|
| 366 |
+
"./textGenerationWithInternalApi"
|
| 367 |
+
);
|
| 368 |
+
const stream = closedStreamResponse(
|
| 369 |
+
sseChunks(['{"choices":[{"delta":{"content":"Hello"}}]}']),
|
| 370 |
+
);
|
| 371 |
+
mockFetch.mockResolvedValueOnce(stream.response);
|
| 372 |
+
|
| 373 |
+
await expect(
|
| 374 |
+
generateChatWithInternalApi([{ role: "user", content: "Hi" }], vi.fn()),
|
| 375 |
+
).resolves.toBe("Hello");
|
| 376 |
+
|
| 377 |
+
expect(fetchSignal().aborted).toBe(false);
|
| 378 |
+
expect(stream.cancel).not.toHaveBeenCalled();
|
| 379 |
+
const stopListening = vi.mocked(listenToTextGenerationStateChanges).mock
|
| 380 |
+
.results[0].value;
|
| 381 |
+
expect(stopListening).toHaveBeenCalledTimes(1);
|
| 382 |
+
});
|
| 383 |
+
});
|
| 384 |
});
|
client/modules/textGenerationWithInternalApi.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
import {
|
| 2 |
getTextGenerationState,
|
|
|
|
| 3 |
updateResponse,
|
| 4 |
updateTextGenerationState,
|
| 5 |
} from "./pubSub";
|
|
@@ -26,98 +27,143 @@ export async function generateTextWithInternalApi() {
|
|
| 26 |
await getFormattedSearchResults(true),
|
| 27 |
);
|
| 28 |
|
| 29 |
-
const streamedMessage = await processStreamResponse(
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
| 33 |
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
|
| 38 |
-
|
| 39 |
-
|
|
|
|
|
|
|
| 40 |
|
| 41 |
updateResponse(streamedMessage);
|
|
|
|
|
|
|
| 42 |
}
|
| 43 |
|
| 44 |
export async function generateChatWithInternalApi(
|
| 45 |
messages: ChatMessage[],
|
| 46 |
onUpdate: (partialResponse: string) => void,
|
| 47 |
) {
|
| 48 |
-
return processStreamResponse(
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
}
|
| 55 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
async function processStreamResponse(
|
| 57 |
messages: ChatMessage[],
|
| 58 |
onChunk: (message: string) => void,
|
|
|
|
| 59 |
): Promise<string> {
|
| 60 |
-
const
|
| 61 |
-
const
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
method: "POST",
|
| 66 |
-
headers: {
|
| 67 |
-
"Content-Type": "application/json",
|
| 68 |
-
},
|
| 69 |
-
body: JSON.stringify({
|
| 70 |
-
...getDefaultChatCompletionCreateParamsStreaming(messages),
|
| 71 |
-
messages,
|
| 72 |
-
}),
|
| 73 |
-
});
|
| 74 |
-
|
| 75 |
-
if (!response.ok || !response.body) {
|
| 76 |
-
throw new Error(`HTTP error! status: ${response.status}`);
|
| 77 |
-
}
|
| 78 |
-
|
| 79 |
-
const reader = response.body.getReader();
|
| 80 |
-
const decoder = new TextDecoder("utf-8");
|
| 81 |
-
let streamedMessage = "";
|
| 82 |
-
let bufferedText = "";
|
| 83 |
-
|
| 84 |
-
const processLine = (line: string) => {
|
| 85 |
-
const data = line.replace(/^data: /, "").trim();
|
| 86 |
-
if (data === "" || data === "[DONE]") return;
|
| 87 |
-
|
| 88 |
-
let parsedLine: InternalApiStreamPayload;
|
| 89 |
-
try {
|
| 90 |
-
parsedLine = JSON.parse(data) as InternalApiStreamPayload;
|
| 91 |
-
} catch {
|
| 92 |
-
return;
|
| 93 |
}
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
}
|
| 98 |
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
}
|
| 104 |
-
};
|
| 105 |
-
|
| 106 |
-
while (true) {
|
| 107 |
-
const { done, value } = await reader.read();
|
| 108 |
-
if (done) break;
|
| 109 |
|
| 110 |
-
bufferedText += decoder.decode(
|
| 111 |
-
|
| 112 |
-
bufferedText = lines.pop() ?? "";
|
| 113 |
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
}
|
| 118 |
-
|
| 119 |
-
bufferedText += decoder.decode();
|
| 120 |
-
processLine(bufferedText);
|
| 121 |
-
|
| 122 |
-
return streamedMessage;
|
| 123 |
}
|
|
|
|
| 1 |
import {
|
| 2 |
getTextGenerationState,
|
| 3 |
+
listenToTextGenerationStateChanges,
|
| 4 |
updateResponse,
|
| 5 |
updateTextGenerationState,
|
| 6 |
} from "./pubSub";
|
|
|
|
| 27 |
await getFormattedSearchResults(true),
|
| 28 |
);
|
| 29 |
|
| 30 |
+
const streamedMessage = await processStreamResponse(
|
| 31 |
+
messages,
|
| 32 |
+
(message) => {
|
| 33 |
+
if (getTextGenerationState() === "interrupted") {
|
| 34 |
+
throw new ChatGenerationError("Generation interrupted");
|
| 35 |
+
}
|
| 36 |
|
| 37 |
+
if (getTextGenerationState() !== "generating") {
|
| 38 |
+
updateTextGenerationState("generating");
|
| 39 |
+
}
|
| 40 |
|
| 41 |
+
updateResponse(message);
|
| 42 |
+
},
|
| 43 |
+
"Generation interrupted",
|
| 44 |
+
);
|
| 45 |
|
| 46 |
updateResponse(streamedMessage);
|
| 47 |
+
|
| 48 |
+
return streamedMessage;
|
| 49 |
}
|
| 50 |
|
| 51 |
export async function generateChatWithInternalApi(
|
| 52 |
messages: ChatMessage[],
|
| 53 |
onUpdate: (partialResponse: string) => void,
|
| 54 |
) {
|
| 55 |
+
return processStreamResponse(
|
| 56 |
+
messages,
|
| 57 |
+
(message) => {
|
| 58 |
+
onUpdate(message);
|
| 59 |
+
if (getTextGenerationState() === "interrupted") {
|
| 60 |
+
throw new ChatGenerationError("Chat generation interrupted");
|
| 61 |
+
}
|
| 62 |
+
},
|
| 63 |
+
"Chat generation interrupted",
|
| 64 |
+
);
|
| 65 |
}
|
| 66 |
|
| 67 |
+
/**
|
| 68 |
+
* Streams one answer from the server's `/inference` endpoint. The request is
|
| 69 |
+
* cancelled whenever the answer does not finish: on Stop, which aborts it at
|
| 70 |
+
* once even while the stream is silent, and on any error thrown while reading.
|
| 71 |
+
* Cancelling closes the connection, which is how the server learns that the
|
| 72 |
+
* reader is gone and stops streaming the run.
|
| 73 |
+
*/
|
| 74 |
async function processStreamResponse(
|
| 75 |
messages: ChatMessage[],
|
| 76 |
onChunk: (message: string) => void,
|
| 77 |
+
interruptedMessage: string,
|
| 78 |
): Promise<string> {
|
| 79 |
+
const controller = new AbortController();
|
| 80 |
+
const { signal } = controller;
|
| 81 |
+
const stopListening = listenToTextGenerationStateChanges((state) => {
|
| 82 |
+
if (state === "interrupted") {
|
| 83 |
+
controller.abort(new ChatGenerationError(interruptedMessage));
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
}
|
| 85 |
+
});
|
| 86 |
+
let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
|
| 87 |
+
// The browser also errors the body when its fetch is aborted, but only a
|
| 88 |
+
// cancel ends a read that is already waiting on a silent stream everywhere.
|
| 89 |
+
const cancelReader = () => {
|
| 90 |
+
reader?.cancel(signal.reason).catch(() => {});
|
| 91 |
+
};
|
| 92 |
+
signal.addEventListener("abort", cancelReader, { once: true });
|
| 93 |
+
let completed = false;
|
| 94 |
+
|
| 95 |
+
try {
|
| 96 |
+
const inferenceUrl = new URL("/inference", self.location.origin);
|
| 97 |
+
const token = await getSearchTokenHash();
|
| 98 |
+
inferenceUrl.searchParams.set("token", token);
|
| 99 |
+
|
| 100 |
+
const response = await fetch(inferenceUrl.toString(), {
|
| 101 |
+
method: "POST",
|
| 102 |
+
headers: {
|
| 103 |
+
"Content-Type": "application/json",
|
| 104 |
+
},
|
| 105 |
+
body: JSON.stringify({
|
| 106 |
+
...getDefaultChatCompletionCreateParamsStreaming(messages),
|
| 107 |
+
messages,
|
| 108 |
+
}),
|
| 109 |
+
signal,
|
| 110 |
+
});
|
| 111 |
+
|
| 112 |
+
if (!response.ok || !response.body) {
|
| 113 |
+
throw new Error(`HTTP error! status: ${response.status}`);
|
| 114 |
}
|
| 115 |
|
| 116 |
+
reader = response.body.getReader();
|
| 117 |
+
const decoder = new TextDecoder("utf-8");
|
| 118 |
+
let streamedMessage = "";
|
| 119 |
+
let bufferedText = "";
|
| 120 |
+
|
| 121 |
+
const processLine = (line: string) => {
|
| 122 |
+
const data = line.replace(/^data: /, "").trim();
|
| 123 |
+
if (data === "" || data === "[DONE]") return;
|
| 124 |
+
|
| 125 |
+
let parsedLine: InternalApiStreamPayload;
|
| 126 |
+
try {
|
| 127 |
+
parsedLine = JSON.parse(data) as InternalApiStreamPayload;
|
| 128 |
+
} catch {
|
| 129 |
+
return;
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
if (typeof parsedLine?.error === "string") {
|
| 133 |
+
throw new ChatGenerationError(parsedLine.error);
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
const deltaContent = parsedLine?.choices?.[0]?.delta?.content;
|
| 137 |
+
if (typeof deltaContent === "string" && deltaContent !== "") {
|
| 138 |
+
streamedMessage += deltaContent;
|
| 139 |
+
onChunk(streamedMessage);
|
| 140 |
+
}
|
| 141 |
+
};
|
| 142 |
+
|
| 143 |
+
while (true) {
|
| 144 |
+
const { done, value } = await reader.read();
|
| 145 |
+
// A cancelled read resolves as done, so the abort is checked first.
|
| 146 |
+
signal.throwIfAborted();
|
| 147 |
+
if (done) break;
|
| 148 |
+
|
| 149 |
+
bufferedText += decoder.decode(value, { stream: true });
|
| 150 |
+
const lines = bufferedText.split("\n");
|
| 151 |
+
bufferedText = lines.pop() ?? "";
|
| 152 |
+
|
| 153 |
+
for (const line of lines) {
|
| 154 |
+
processLine(line);
|
| 155 |
+
}
|
| 156 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
|
| 158 |
+
bufferedText += decoder.decode();
|
| 159 |
+
processLine(bufferedText);
|
|
|
|
| 160 |
|
| 161 |
+
completed = true;
|
| 162 |
+
return streamedMessage;
|
| 163 |
+
} finally {
|
| 164 |
+
stopListening();
|
| 165 |
+
// Any way out but a finished stream cancels the request.
|
| 166 |
+
if (!completed) controller.abort();
|
| 167 |
+
signal.removeEventListener("abort", cancelReader);
|
| 168 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
}
|
client/modules/textGenerationWithOpenAi.test.ts
CHANGED
|
@@ -97,7 +97,7 @@ describe("textGenerationWithOpenAi", () => {
|
|
| 97 |
sseResponse([{ choices: [{ delta: { content: "Hello" } }] }]),
|
| 98 |
);
|
| 99 |
|
| 100 |
-
await generateTextWithOpenAi();
|
| 101 |
|
| 102 |
expect(canStartResponding).toHaveBeenCalled();
|
| 103 |
expect(updateTextGenerationState).toHaveBeenCalledWith(
|
|
@@ -119,7 +119,9 @@ describe("textGenerationWithOpenAi", () => {
|
|
| 119 |
]),
|
| 120 |
);
|
| 121 |
|
| 122 |
-
await generateTextWithOpenAi()
|
|
|
|
|
|
|
| 123 |
|
| 124 |
expect(updateResponse).toHaveBeenLastCalledWith(
|
| 125 |
"<think>Thinking...</think>\n\nHello",
|
|
|
|
| 97 |
sseResponse([{ choices: [{ delta: { content: "Hello" } }] }]),
|
| 98 |
);
|
| 99 |
|
| 100 |
+
await expect(generateTextWithOpenAi()).resolves.toBe("Hello");
|
| 101 |
|
| 102 |
expect(canStartResponding).toHaveBeenCalled();
|
| 103 |
expect(updateTextGenerationState).toHaveBeenCalledWith(
|
|
|
|
| 119 |
]),
|
| 120 |
);
|
| 121 |
|
| 122 |
+
await expect(generateTextWithOpenAi()).resolves.toBe(
|
| 123 |
+
"<think>Thinking...</think>\n\nHello",
|
| 124 |
+
);
|
| 125 |
|
| 126 |
expect(updateResponse).toHaveBeenLastCalledWith(
|
| 127 |
"<think>Thinking...</think>\n\nHello",
|
client/modules/textGenerationWithOpenAi.ts
CHANGED
|
@@ -36,6 +36,24 @@ interface StreamResult {
|
|
| 36 |
reasoningContent?: string;
|
| 37 |
}
|
| 38 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
async function createOpenAiStream({
|
| 40 |
messages,
|
| 41 |
onUpdate,
|
|
@@ -161,7 +179,7 @@ async function createOpenAiStream({
|
|
| 161 |
return tryNextModel();
|
| 162 |
}
|
| 163 |
|
| 164 |
-
export async function generateTextWithOpenAi() {
|
| 165 |
await canStartResponding();
|
| 166 |
updateTextGenerationState("preparingToGenerate");
|
| 167 |
|
|
@@ -170,7 +188,7 @@ export async function generateTextWithOpenAi() {
|
|
| 170 |
);
|
| 171 |
const settings = getSettings();
|
| 172 |
|
| 173 |
-
await createOpenAiStream({
|
| 174 |
messages,
|
| 175 |
onUpdate: (text, reasoningContent) => {
|
| 176 |
if (
|
|
@@ -180,19 +198,11 @@ export async function generateTextWithOpenAi() {
|
|
| 180 |
updateTextGenerationState("generating");
|
| 181 |
}
|
| 182 |
|
| 183 |
-
|
| 184 |
-
if (text && text.length > 0) {
|
| 185 |
-
updateResponse(
|
| 186 |
-
`${settings.reasoningStartMarker}${reasoningContent}${settings.reasoningEndMarker}\n\n${text}`,
|
| 187 |
-
);
|
| 188 |
-
} else {
|
| 189 |
-
updateResponse(`${settings.reasoningStartMarker}${reasoningContent}`);
|
| 190 |
-
}
|
| 191 |
-
} else {
|
| 192 |
-
updateResponse(text);
|
| 193 |
-
}
|
| 194 |
},
|
| 195 |
});
|
|
|
|
|
|
|
| 196 |
}
|
| 197 |
|
| 198 |
export async function generateChatWithOpenAi(
|
|
@@ -203,23 +213,9 @@ export async function generateChatWithOpenAi(
|
|
| 203 |
const result = await createOpenAiStream({
|
| 204 |
messages,
|
| 205 |
onUpdate: (text, reasoningContent) => {
|
| 206 |
-
|
| 207 |
-
if (text && text.length > 0) {
|
| 208 |
-
onUpdate(
|
| 209 |
-
`${settings.reasoningStartMarker}${reasoningContent}${settings.reasoningEndMarker}\n\n${text}`,
|
| 210 |
-
);
|
| 211 |
-
} else {
|
| 212 |
-
onUpdate(`${settings.reasoningStartMarker}${reasoningContent}`);
|
| 213 |
-
}
|
| 214 |
-
} else {
|
| 215 |
-
onUpdate(text);
|
| 216 |
-
}
|
| 217 |
},
|
| 218 |
});
|
| 219 |
|
| 220 |
-
|
| 221 |
-
return `${settings.reasoningStartMarker}${result.reasoningContent}${settings.reasoningEndMarker}\n\n${result.text}`;
|
| 222 |
-
}
|
| 223 |
-
|
| 224 |
-
return result.text;
|
| 225 |
}
|
|
|
|
| 36 |
reasoningContent?: string;
|
| 37 |
}
|
| 38 |
|
| 39 |
+
/**
|
| 40 |
+
* The text the response channel carries for a streamed answer: the reasoning
|
| 41 |
+
* block wrapped in its markers, followed by the answer once it arrives.
|
| 42 |
+
*/
|
| 43 |
+
function composeResponseText(
|
| 44 |
+
text: string,
|
| 45 |
+
reasoningContent: string | undefined,
|
| 46 |
+
settings: { reasoningStartMarker: string; reasoningEndMarker: string },
|
| 47 |
+
) {
|
| 48 |
+
if (!reasoningContent) return text;
|
| 49 |
+
|
| 50 |
+
const reasoning = `${settings.reasoningStartMarker}${reasoningContent}`;
|
| 51 |
+
|
| 52 |
+
if (!text) return reasoning;
|
| 53 |
+
|
| 54 |
+
return `${reasoning}${settings.reasoningEndMarker}\n\n${text}`;
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
async function createOpenAiStream({
|
| 58 |
messages,
|
| 59 |
onUpdate,
|
|
|
|
| 179 |
return tryNextModel();
|
| 180 |
}
|
| 181 |
|
| 182 |
+
export async function generateTextWithOpenAi(): Promise<string> {
|
| 183 |
await canStartResponding();
|
| 184 |
updateTextGenerationState("preparingToGenerate");
|
| 185 |
|
|
|
|
| 188 |
);
|
| 189 |
const settings = getSettings();
|
| 190 |
|
| 191 |
+
const result = await createOpenAiStream({
|
| 192 |
messages,
|
| 193 |
onUpdate: (text, reasoningContent) => {
|
| 194 |
if (
|
|
|
|
| 198 |
updateTextGenerationState("generating");
|
| 199 |
}
|
| 200 |
|
| 201 |
+
updateResponse(composeResponseText(text, reasoningContent, settings));
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
},
|
| 203 |
});
|
| 204 |
+
|
| 205 |
+
return composeResponseText(result.text, result.reasoningContent, settings);
|
| 206 |
}
|
| 207 |
|
| 208 |
export async function generateChatWithOpenAi(
|
|
|
|
| 213 |
const result = await createOpenAiStream({
|
| 214 |
messages,
|
| 215 |
onUpdate: (text, reasoningContent) => {
|
| 216 |
+
onUpdate(composeResponseText(text, reasoningContent, settings));
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
},
|
| 218 |
});
|
| 219 |
|
| 220 |
+
return composeResponseText(result.text, result.reasoningContent, settings);
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
}
|
client/modules/textGenerationWithWllama.test.ts
CHANGED
|
@@ -118,7 +118,7 @@ describe("generateTextWithWllama", () => {
|
|
| 118 |
{ loaded: 175 * megabyte, total: 250 * megabyte },
|
| 119 |
]);
|
| 120 |
|
| 121 |
-
await generateTextWithWllama();
|
| 122 |
|
| 123 |
expect(updateModelLoadingProgress).toHaveBeenCalledTimes(2);
|
| 124 |
expect(updateModelLoadingProgress).toHaveBeenLastCalledWith(70);
|
|
|
|
| 118 |
{ loaded: 175 * megabyte, total: 250 * megabyte },
|
| 119 |
]);
|
| 120 |
|
| 121 |
+
await expect(generateTextWithWllama()).resolves.toBe("Hello");
|
| 122 |
|
| 123 |
expect(updateModelLoadingProgress).toHaveBeenCalledTimes(2);
|
| 124 |
expect(updateModelLoadingProgress).toHaveBeenLastCalledWith(70);
|
client/modules/textGenerationWithWllama.ts
CHANGED
|
@@ -29,8 +29,8 @@ type ProgressCallback = ({
|
|
| 29 |
total: number;
|
| 30 |
}) => void;
|
| 31 |
|
| 32 |
-
export async function generateTextWithWllama(): Promise<
|
| 33 |
-
if (!getSettings().enableAiResponse) return;
|
| 34 |
|
| 35 |
try {
|
| 36 |
const response = await generateWithWllama({
|
|
@@ -46,6 +46,7 @@ export async function generateTextWithWllama(): Promise<void> {
|
|
| 46 |
shouldCheckCanRespond: true,
|
| 47 |
});
|
| 48 |
updateResponse(response);
|
|
|
|
| 49 |
} catch (error) {
|
| 50 |
addLogEntry(
|
| 51 |
`Text generation failed: ${
|
|
|
|
| 29 |
total: number;
|
| 30 |
}) => void;
|
| 31 |
|
| 32 |
+
export async function generateTextWithWllama(): Promise<string> {
|
| 33 |
+
if (!getSettings().enableAiResponse) return "";
|
| 34 |
|
| 35 |
try {
|
| 36 |
const response = await generateWithWllama({
|
|
|
|
| 46 |
shouldCheckCanRespond: true,
|
| 47 |
});
|
| 48 |
updateResponse(response);
|
| 49 |
+
return response;
|
| 50 |
} catch (error) {
|
| 51 |
addLogEntry(
|
| 52 |
`Text generation failed: ${
|
docs/ai-integration.md
CHANGED
|
@@ -144,7 +144,7 @@ Uses aihorde.net, a distributed volunteer GPU network.
|
|
| 144 |
{
|
| 145 |
inferenceType: 'horde',
|
| 146 |
hordeApiKey: '0000000000', // Default anonymous key; set your own for priority
|
| 147 |
-
hordeModel: '' // Optional; empty asks for the five most requested models this month and races two requests, using the first
|
| 148 |
}
|
| 149 |
```
|
| 150 |
|
|
|
|
| 144 |
{
|
| 145 |
inferenceType: 'horde',
|
| 146 |
hordeApiKey: '0000000000', // Default anonymous key; set your own for priority
|
| 147 |
+
hordeModel: '' // Optional; empty asks for the five most requested models this month and races two requests, using the first one that answers; one that fails is ignored while the other is still running
|
| 148 |
}
|
| 149 |
```
|
| 150 |
|
docs/api.md
CHANGED
|
@@ -194,7 +194,11 @@ failed: never while SearXNG answers, and never on an image search. It is
|
|
| 194 |
skipped when less than two seconds of the search's own 25-second deadline
|
| 195 |
remain, since an answer that late cannot reach the client before its 30-second
|
| 196 |
timeout, and that skip answers the `502` above and counts as a fallback that
|
| 197 |
-
failed.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
results, this endpoint responds `200` with `[]`, so the client shows the
|
| 199 |
"No results found" alert rather than the "Text search unavailable" one; only
|
| 200 |
when every provider tried fails, or none could be tried at all, does the
|
|
|
|
| 194 |
skipped when less than two seconds of the search's own 25-second deadline
|
| 195 |
remain, since an answer that late cannot reach the client before its 30-second
|
| 196 |
timeout, and that skip answers the `502` above and counts as a fallback that
|
| 197 |
+
failed. So that a stalled SearXNG cannot use up that deadline, the SearXNG
|
| 198 |
+
request, its retries and their backoff are canceled after 15 seconds when the
|
| 199 |
+
fallback could follow, which leaves it the last 10, and after the full 25
|
| 200 |
+
seconds otherwise; a canceled request counts as a SearXNG failure toward the
|
| 201 |
+
circuit breaker. If at least one provider answers with nothing usable and none returns
|
| 202 |
results, this endpoint responds `200` with `[]`, so the client shows the
|
| 203 |
"No results found" alert rather than the "Text search unavailable" one; only
|
| 204 |
when every provider tried fails, or none could be tried at all, does the
|
docs/configuration.md
CHANGED
|
@@ -51,12 +51,13 @@ value uses the corresponding default.
|
|
| 51 |
|
| 52 |
For self-hosted OpenAI-compatible APIs:
|
| 53 |
|
| 54 |
-
| Variable
|
| 55 |
-
| ----------------------------------------- | -------------- | ------------------------------------------------------------------ |
|
| 56 |
-
| `INTERNAL_OPENAI_COMPATIBLE_API_BASE_URL`
|
| 57 |
-
| `INTERNAL_OPENAI_COMPATIBLE_API_KEY`
|
| 58 |
-
| `INTERNAL_OPENAI_COMPATIBLE_API_MODEL`
|
| 59 |
-
| `
|
|
|
|
| 60 |
|
| 61 |
**Example:**
|
| 62 |
|
|
@@ -69,6 +70,8 @@ INTERNAL_OPENAI_COMPATIBLE_API_NAME="Company LLM"
|
|
| 69 |
|
| 70 |
`INTERNAL_OPENAI_COMPATIBLE_API_MODEL` takes several models, separated by commas, in order of preference (`"llama-3.1-8b,qwen-3-8b"`). When a model fails before sending the first token, the server moves to the next one, and after the last one it starts the list over once, up to 5 attempts in all. So a single model gets one retry. Left empty, each request picks a random model from the API's `/models` list, which includes every model the API serves.
|
| 71 |
|
|
|
|
|
|
|
| 72 |
### Default Behavior
|
| 73 |
|
| 74 |
| Variable | Default | Description |
|
|
|
|
| 51 |
|
| 52 |
For self-hosted OpenAI-compatible APIs:
|
| 53 |
|
| 54 |
+
| Variable | Default | Description |
|
| 55 |
+
| ------------------------------------------------- | -------------- | ------------------------------------------------------------------ |
|
| 56 |
+
| `INTERNAL_OPENAI_COMPATIBLE_API_BASE_URL` | `''` | Base URL of your API (e.g., `https://api.internal.company.com/v1`) |
|
| 57 |
+
| `INTERNAL_OPENAI_COMPATIBLE_API_KEY` | `''` | API key for authentication |
|
| 58 |
+
| `INTERNAL_OPENAI_COMPATIBLE_API_MODEL` | `''` | Model ID, or a comma-separated list (random model if empty) |
|
| 59 |
+
| `INTERNAL_OPENAI_COMPATIBLE_API_REASONING_EFFORT` | `''` | Sent as `reasoning_effort` on every request (API default if empty) |
|
| 60 |
+
| `INTERNAL_OPENAI_COMPATIBLE_API_NAME` | `Internal API` | Display name shown in UI |
|
| 61 |
|
| 62 |
**Example:**
|
| 63 |
|
|
|
|
| 70 |
|
| 71 |
`INTERNAL_OPENAI_COMPATIBLE_API_MODEL` takes several models, separated by commas, in order of preference (`"llama-3.1-8b,qwen-3-8b"`). When a model fails before sending the first token, the server moves to the next one, and after the last one it starts the list over once, up to 5 attempts in all. So a single model gets one retry. Left empty, each request picks a random model from the API's `/models` list, which includes every model the API serves.
|
| 72 |
|
| 73 |
+
`INTERNAL_OPENAI_COMPATIBLE_API_REASONING_EFFORT` sets the `reasoning_effort` field of every request to the API, for every model in the list. The value is passed through as written, because providers accept different values (`none`, `minimal`, `low`, `medium`, `high`, `xhigh`); one the API rejects fails the request, and the error shows in the server log. Left empty, the field is not sent and the API applies its own default.
|
| 74 |
+
|
| 75 |
### Default Behavior
|
| 76 |
|
| 77 |
| Variable | Default | Description |
|
docs/failure-injection.md
CHANGED
|
@@ -54,6 +54,7 @@ needed.
|
|
| 54 |
| Search returns nothing to the endpoint | HTTP 200 with `[]`, not an error | `server/searchEndpointServerHook.test.ts` › graceful degradation |
|
| 55 |
| Text search returns nothing to the client | Keyword-only query retried as a fallback | `client/modules/textGeneration.degradation.test.ts` |
|
| 56 |
| Keyword fallback also returns nothing | Text search state stays `completed` with the no-results alert | `client/modules/textGeneration.degradation.test.ts` |
|
|
|
|
| 57 |
| SearXNG is down on the client | Text search state becomes `failed`, keyword fallback does not fire | `client/modules/textGeneration.degradation.test.ts` |
|
| 58 |
| Client search fails after a previous search populated the LLM channel | The grounding channel is cleared, so the AI can't ground on the previous query's results; when image search is on and it answers, the channel is repopulated with the (image)-tagged titles and URLs instead | `client/modules/textGeneration.degradation.test.ts` |
|
| 59 |
| Text search fails and the image search answers | The answer waits for the image results and grounds on their (image)-tagged titles and URLs, and the failed-state alert says so | `client/modules/textGeneration.degradation.test.ts` › search degradation |
|
|
@@ -86,6 +87,7 @@ needed.
|
|
| 86 |
| `ChatInterface` unmounts while a follow-up question is in flight | Both generation flags are cleared and the orphaned completion writes nothing into the next mount | `client/components/AiResponse/ChatInterface.test.tsx` › leaves both generation flags off after unmounting mid-generation |
|
| 87 |
| A follow-up question generation rejects after a newer one started | The failed call blanks nothing, so the newer question still lands and the flag stays on until it does | `client/components/AiResponse/ChatInterface.test.tsx` › blanks nothing when an orphaned call rejects after a newer one started |
|
| 88 |
| `ChatInterface` unmounts while a regenerate is still awaiting its response | The orphaned regenerate leaves the next mount's response flag alone | `client/components/AiResponse/ChatInterface.test.tsx` › leaves the next mount's response flag alone when an orphaned regenerate settles |
|
|
|
|
| 89 |
| `ChatInterface` unmounts while a send is still awaiting its response | The orphaned send asks for no follow-up question and leaves the next mount's response flag alone | `client/components/AiResponse/ChatInterface.test.tsx` › starts no follow-up question for a send that settles after unmount, leaves the next mount's response flag alone when an orphaned send settles |
|
| 90 |
| The dictation model cannot load in the browser, or its download fails | While the on-device model is preferred, the local engine is abandoned for the browser's `SpeechRecognition` before the microphone opens, and the button hides when that is missing too | `client/modules/speechToText.test.ts` › falls back to the browser recognizer without opening the microphone when the model fails to load |
|
| 91 |
| The browser recognizer fails while the on-device model is off | The session fails outright; there is no reverse fallback, so the disabled model is never downloaded behind the user's back | `client/modules/speechToText.test.ts` › does not fall back to the wasm engine when the recognizer fails |
|
|
|
|
| 54 |
| Search returns nothing to the endpoint | HTTP 200 with `[]`, not an error | `server/searchEndpointServerHook.test.ts` › graceful degradation |
|
| 55 |
| Text search returns nothing to the client | Keyword-only query retried as a fallback | `client/modules/textGeneration.degradation.test.ts` |
|
| 56 |
| Keyword fallback also returns nothing | Text search state stays `completed` with the no-results alert | `client/modules/textGeneration.degradation.test.ts` |
|
| 57 |
+
| Stop on an internal-API answer, also while the stream is silent, or an error frame | The request is aborted and its stream cancelled, so the server stops streaming and counts the run abandoned | `client/modules/textGenerationWithInternalApi.test.ts` › cancelling the stream |
|
| 58 |
| SearXNG is down on the client | Text search state becomes `failed`, keyword fallback does not fire | `client/modules/textGeneration.degradation.test.ts` |
|
| 59 |
| Client search fails after a previous search populated the LLM channel | The grounding channel is cleared, so the AI can't ground on the previous query's results; when image search is on and it answers, the channel is repopulated with the (image)-tagged titles and URLs instead | `client/modules/textGeneration.degradation.test.ts` |
|
| 60 |
| Text search fails and the image search answers | The answer waits for the image results and grounds on their (image)-tagged titles and URLs, and the failed-state alert says so | `client/modules/textGeneration.degradation.test.ts` › search degradation |
|
|
|
|
| 87 |
| `ChatInterface` unmounts while a follow-up question is in flight | Both generation flags are cleared and the orphaned completion writes nothing into the next mount | `client/components/AiResponse/ChatInterface.test.tsx` › leaves both generation flags off after unmounting mid-generation |
|
| 88 |
| A follow-up question generation rejects after a newer one started | The failed call blanks nothing, so the newer question still lands and the flag stays on until it does | `client/components/AiResponse/ChatInterface.test.tsx` › blanks nothing when an orphaned call rejects after a newer one started |
|
| 89 |
| `ChatInterface` unmounts while a regenerate is still awaiting its response | The orphaned regenerate leaves the next mount's response flag alone | `client/components/AiResponse/ChatInterface.test.tsx` › leaves the next mount's response flag alone when an orphaned regenerate settles |
|
| 90 |
+
| A regenerate fails (model error, interrupted inference) | The previous answer and follow-up question come back with a red notification, the error is logged, and the answer can be regenerated again | `client/components/AiResponse/ChatInterface.test.tsx` › keeps the previous answer so it can be regenerated again |
|
| 91 |
| `ChatInterface` unmounts while a send is still awaiting its response | The orphaned send asks for no follow-up question and leaves the next mount's response flag alone | `client/components/AiResponse/ChatInterface.test.tsx` › starts no follow-up question for a send that settles after unmount, leaves the next mount's response flag alone when an orphaned send settles |
|
| 92 |
| The dictation model cannot load in the browser, or its download fails | While the on-device model is preferred, the local engine is abandoned for the browser's `SpeechRecognition` before the microphone opens, and the button hides when that is missing too | `client/modules/speechToText.test.ts` › falls back to the browser recognizer without opening the microphone when the model fails to load |
|
| 93 |
| The browser recognizer fails while the on-device model is off | The session fails outright; there is no reverse fallback, so the disabled model is never downloaded behind the user's back | `client/modules/speechToText.test.ts` › does not fall back to the wasm engine when the recognizer fails |
|
docs/glossary.md
CHANGED
|
@@ -30,7 +30,7 @@ Instead of a heavy state management library like Redux, MiniSearch uses a minima
|
|
| 30 |
- **Data Flow**: Components subscribe to "channels" (e.g., `queryPubSub`, `responsePubSub`)
|
| 31 |
- **Tuple Pattern**: Each channel is a 3-element tuple: `[update, subscribe, get]`
|
| 32 |
- **Persistence**: Some channels use `createLocalStoragePubSub` to automatically sync state with `localStorage`
|
| 33 |
-
- **Throttling**: UI-heavy updates like AI response streaming are throttled to ~12 updates/sec
|
| 34 |
|
| 35 |
### Reranker
|
| 36 |
|
|
|
|
| 30 |
- **Data Flow**: Components subscribe to "channels" (e.g., `queryPubSub`, `responsePubSub`)
|
| 31 |
- **Tuple Pattern**: Each channel is a 3-element tuple: `[update, subscribe, get]`
|
| 32 |
- **Persistence**: Some channels use `createLocalStoragePubSub` to automatically sync state with `localStorage`
|
| 33 |
+
- **Throttling**: UI-heavy updates like AI response streaming are throttled to ~12 updates/sec; the response channel keeps one trailing write and exposes an unthrottled final publish
|
| 34 |
|
| 35 |
### Reranker
|
| 36 |
|
docs/overview.md
CHANGED
|
@@ -107,7 +107,7 @@ The system executes two parallel flows when a user submits a query:
|
|
| 107 |
2. State machine transitions: `idle` -> `awaitingModelDownloadAllowance` -> `loadingModel` -> `awaitingSearchResults` -> `preparingToGenerate` -> `generating` -> `completed`/`failed`/`interrupted` (see Text Generation States below; `awaitingModelDownloadAllowance` and `loadingModel` only occur on the browser/Wllama path, while every backend transitions through `awaitingSearchResults` and then `preparingToGenerate`)
|
| 108 |
3. Search results are formatted and injected into system prompt via `{{searchResults}}` placeholder. With `enablePageContentFetch` on, the pages behind the top results are read through `/page-content` first and their excerpts are appended to each result (see `docs/page-content.md`)
|
| 109 |
4. LLM generates response with streaming tokens
|
| 110 |
-
5. Response updates throttled to ~12 updates/sec
|
| 111 |
6. Response saved to history database via `saveLlmResponseForQuery`
|
| 112 |
|
| 113 |
The `textGeneration` module orchestrates the entire search-to-response flow, managing search requests, LLM context preparation, and response streaming. Search results are optionally reranked in-process via ONNX Runtime before being passed to the LLM for response generation.
|
|
@@ -173,14 +173,14 @@ MiniSearch uses a PubSub-based architecture where state flows through independen
|
|
| 173 |
|
| 174 |
### Response Throttling
|
| 175 |
|
| 176 |
-
Streaming LLM output produces token-by-token state changes that would overwhelm React's rendering pipeline. Two channels
|
| 177 |
|
| 178 |
-
| Channel
|
| 179 |
-
| ------------------------ | ----------------- | ------------------------------------ |
|
| 180 |
-
| `responsePubSub`
|
| 181 |
-
| `
|
| 182 |
|
| 183 |
-
Callers write tokens directly to
|
| 184 |
|
| 185 |
### Side Effects
|
| 186 |
|
|
|
|
| 107 |
2. State machine transitions: `idle` -> `awaitingModelDownloadAllowance` -> `loadingModel` -> `awaitingSearchResults` -> `preparingToGenerate` -> `generating` -> `completed`/`failed`/`interrupted` (see Text Generation States below; `awaitingModelDownloadAllowance` and `loadingModel` only occur on the browser/Wllama path, while every backend transitions through `awaitingSearchResults` and then `preparingToGenerate`)
|
| 108 |
3. Search results are formatted and injected into system prompt via `{{searchResults}}` placeholder. With `enablePageContentFetch` on, the pages behind the top results are read through `/page-content` first and their excerpts are appended to each result (see `docs/page-content.md`)
|
| 109 |
4. LLM generates response with streaming tokens
|
| 110 |
+
5. Response updates throttled to ~12 updates/sec to prevent React render overload; the final answer is published unthrottled before the state turns to `completed` (see Response Throttling)
|
| 111 |
6. Response saved to history database via `saveLlmResponseForQuery`
|
| 112 |
|
| 113 |
The `textGeneration` module orchestrates the entire search-to-response flow, managing search requests, LLM context preparation, and response streaming. Search results are optionally reranked in-process via ONNX Runtime before being passed to the LLM for response generation.
|
|
|
|
| 173 |
|
| 174 |
### Response Throttling
|
| 175 |
|
| 176 |
+
Streaming LLM output produces token-by-token state changes that would overwhelm React's rendering pipeline. Two channels cap updates at ~12/sec (83ms):
|
| 177 |
|
| 178 |
+
| Channel | Throttle Interval | Purpose |
|
| 179 |
+
| ----------------------------------- | ----------------- | -------------------------------------------- |
|
| 180 |
+
| `responsePubSub` (`updateResponse`) | ~83ms (12/sec) | AI response text streaming |
|
| 181 |
+
| `ChatInterface` streamed response | ~83ms (12/sec) | Chat panel re-render while an answer streams |
|
| 182 |
|
| 183 |
+
`updateResponse` keeps at most one trailing write for the newest value; `updateResponseImmediately` drops that write and publishes the final answer at once. Callers write tokens directly to these exports without awareness of internal throttling.
|
| 184 |
|
| 185 |
### Side Effects
|
| 186 |
|
docs/ui-components.md
CHANGED
|
@@ -44,14 +44,15 @@ Channels using this pattern: `settingsPubSub`, `querySuggestionsPubSub`, `lastSe
|
|
| 44 |
|
| 45 |
### Throttling High-Frequency Updates
|
| 46 |
|
| 47 |
-
Streaming LLM output produces token-by-token state changes that would overwhelm React's rendering pipeline. Two channels
|
| 48 |
|
| 49 |
-
| Export
|
| 50 |
-
| ------------------------
|
| 51 |
-
| `updateResponse`
|
| 52 |
-
| `
|
|
|
|
| 53 |
|
| 54 |
-
Callers write streaming token output directly to these exports without awareness of internal throttling.
|
| 55 |
|
| 56 |
### Side Effects
|
| 57 |
|
|
|
|
| 44 |
|
| 45 |
### Throttling High-Frequency Updates
|
| 46 |
|
| 47 |
+
Streaming LLM output produces token-by-token state changes that would overwhelm React's rendering pipeline. Two channels cap subscriber notification rate to ~12 updates/sec (83ms interval):
|
| 48 |
|
| 49 |
+
| Export | Raw Updater | Throttle |
|
| 50 |
+
| ---------------------------------------- | ------------------- | ----------------------------------- |
|
| 51 |
+
| `updateResponse` | `responsePubSub[0]` | 1000 / 12 ms, plus a trailing write |
|
| 52 |
+
| `updateResponseImmediately` | `responsePubSub[0]` | none — drops the trailing write |
|
| 53 |
+
| `updateStreamedResponse` (ChatInterface) | local React state | `throttleit`, 1000 / 12 ms |
|
| 54 |
|
| 55 |
+
Callers write streaming token output directly to these exports without awareness of internal throttling; the generation flow publishes the final answer through `updateResponseImmediately`, so the last chunk is never lost.
|
| 56 |
|
| 57 |
### Side Effects
|
| 58 |
|