Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,10 @@
- Apply current full Autopilot settings at each new scheduled window. Disabling between windows restores ordinary saved model selection even if unchanged; other runtime inputs remain frozen.
- Queue pending-operation uncertainty before removing a disconnected provider, persisting outside registry/provider locks. Connection loss never implies rollback or a confirmed terminal resident set.

## Unreleased — console chat request budget

- Refuse oversized chat requests locally with guidance to reduce images or conversation length. Check the full UTF-8 request and optional encrypted envelope before sending, retain the user's message and images, and apply the same check on retry. Existing per-file and image-count limits remain unchanged.

## Unreleased — canceled queue waiters

- Stop canceled waiters held by a scheduling pass from returning as queued demand and occupying slots needed by fresh requests. Drop completed entries during queue pop and stale cleanup while preserving live FIFO order, timeout notifications, and reservation cleanup.
Expand Down
106 changes: 106 additions & 0 deletions console-ui/src/hooks/useChatStream.request-budget.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import { act, cleanup, renderHook, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { useChatStream } from "./useChatStream";
import { useStore } from "@/lib/store";
import { useToastStore } from "./useToast";
import { setEncryptionEnabled } from "@/lib/encryption";

vi.mock("@/lib/google-analytics", () => ({ trackEvent: vi.fn() }));

beforeEach(() => {
localStorage.clear();
setEncryptionEnabled(false);
useStore.setState({ chats: [], activeChatId: null, selectedModel: "fixture-vision-model", models: [], useMyMachine: false });
useToastStore.setState({ toasts: [] });
vi.stubGlobal("fetch", vi.fn(async () => new Response("data: [DONE]\n\n", { headers: { "content-type": "text/event-stream" } })));
});

afterEach(() => {
cleanup();
vi.unstubAllGlobals();
vi.restoreAllMocks();
useStore.setState({ chats: [], activeChatId: null });
useToastStore.setState({ toasts: [] });
});

describe("chat send and retry budget lifecycle", () => {
it("retains user images and text when send and retry are refused locally", async () => {
const data = `data:image/jpeg;base64,${Buffer.alloc(7 * 1024 * 1024).toString("base64")}`;
const images = [data, data];
const text = "describe my images";
const { result } = renderHook(() => useChatStream());
await act(async () => { await result.current.handleSend(text, images); });
const messages = useStore.getState().chats[0].messages;
expect(messages[0].content).toBe(text);
expect(messages[0].images).toEqual(images);
expect(messages[1].error).toBe(true);
expect(messages[1].streaming).toBe(false);
expect(messages[1].content).toMatch(/too large/i);
expect(result.current.isStreaming).toBe(false);
expect(fetch).not.toHaveBeenCalled();
expect(useToastStore.getState().toasts).toHaveLength(1);

act(() => result.current.handleRetry(messages[1].id));
await waitFor(() => expect(result.current.isStreaming).toBe(false));
const retried = useStore.getState().chats[0].messages;
expect(retried).toHaveLength(2);
expect(retried[0].content).toBe(text);
expect(retried[0].images).toEqual(images);
expect(retried[1].error).toBe(true);
expect(retried[1].streaming).toBe(false);
expect(retried[1].content).toMatch(/too large/i);
expect(useToastStore.getState().toasts).toHaveLength(2);
expect(fetch).not.toHaveBeenCalled();
});

it("keeps newest-image history pruning and permits a valid send", async () => {
const chatId = useStore.getState().createChat();
const oldImage = `data:image/jpeg;base64,${Buffer.alloc(10 * 1024 * 1024).toString("base64")}`;
useStore.getState().addMessage(chatId, { id: "old", role: "user", content: "old image", images: [oldImage], timestamp: 0 });
const currentImage = "data:image/png;base64,AQID";
const { result } = renderHook(() => useChatStream());
await act(async () => { await result.current.handleSend("new image", [currentImage]); });
expect(fetch).toHaveBeenCalledTimes(1);
const [, init] = vi.mocked(fetch).mock.calls[0];
const sent = JSON.parse(init?.body as string);
expect(sent.messages[0].role).toBe("system");
expect(sent.messages[1]).toEqual({ role: "user", content: "old image" });
expect(JSON.stringify(sent)).not.toContain(oldImage);
expect(JSON.stringify(sent)).toContain(currentImage);
expect(useStore.getState().chats[0].messages[0].images).toEqual([oldImage]);
expect(result.current.isStreaming).toBe(false);
expect(useToastStore.getState().toasts).toHaveLength(0);
});

it("rechecks current encryption and model settings with pruned retry history", async () => {
const chatId = useStore.getState().createChat();
const oldImage = "data:image/png;base64,AQID";
useStore.getState().addMessage(chatId, { id: "old", role: "user", content: "old image", images: [oldImage], timestamp: 0 });
const currentImage = `data:image/jpeg;base64,${Buffer.alloc(10 * 1024 * 1024).toString("base64")}`;
const { result } = renderHook(() => useChatStream());
await act(async () => { await result.current.handleSend("new image", [currentImage]); });
const assistantId = useStore.getState().chats[0].messages[2].id;
expect(fetch).toHaveBeenCalledTimes(1);

vi.mocked(fetch).mockClear();
setEncryptionEnabled(true);
act(() => result.current.handleRetry(assistantId));
await waitFor(() => expect(result.current.isStreaming).toBe(false));
expect(fetch).not.toHaveBeenCalled();
expect(useStore.getState().chats[0].messages[2].content).toMatch(/too large/i);
expect(useStore.getState().chats[0].messages[1].images).toEqual([currentImage]);

setEncryptionEnabled(false);
useStore.setState({ selectedModel: "current-retry-model" });
act(() => result.current.handleRetry(assistantId));
await waitFor(() => expect(result.current.isStreaming).toBe(false));
expect(fetch).toHaveBeenCalledTimes(1);
const sent = JSON.parse(vi.mocked(fetch).mock.calls[0][1]?.body as string);
expect(sent.model).toBe("current-retry-model");
expect(sent.messages[0].role).toBe("system");
expect(sent.messages[1]).toEqual({ role: "user", content: "old image" });
expect(JSON.stringify(sent)).not.toContain(oldImage);
expect(JSON.stringify(sent)).toContain(currentImage);
expect(useStore.getState().chats[0].messages[2].error).toBe(false);
});
});
8 changes: 4 additions & 4 deletions console-ui/src/lib/chat-messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ import { buildApiContent } from "./image-upload";
* content parts (text-only turns stay plain strings). Shared by the send and
* retry paths so the transformation lives in one place.
*
* The coordinator caps plaintext inference bodies at 64 MiB. One UI turn may
* carry four 10 MB images (~53 MiB after base64), so resending multiple image
* turns from live chat history would breach that cap. Older images remain in
* the visible chat state, but only the newest image turn is sent upstream.
* Only the newest image turn is sent upstream; older images remain visible
* in chat state. Even one image turn can exceed the coordinator's 16 MiB body
* cap after base64 and optional sealing. streamChat checks the complete
* serialized request and sealed envelope before sending.
*
* NOTE: `m.images` is undefined for turns restored from persistence (images are
* stripped from localStorage to protect the quota — see store.ts `partialize`),
Expand Down
34 changes: 34 additions & 0 deletions console-ui/src/lib/chat/request-budget.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { describe, expect, it } from "vitest";
import { sealRawRequest } from "../encryption";
import nacl from "tweetnacl";
import { assertChatRequestBudget, ChatRequestTooLargeError } from "./request-budget";

const LIMIT = 16 * 1024 * 1024;

describe("chat request byte budget", () => {
it("accepts the exact plaintext cap and refuses one additional UTF-8 byte", () => {
expect(() => assertChatRequestBudget("a".repeat(LIMIT))).not.toThrow();
expect(() => assertChatRequestBudget("a".repeat(LIMIT + 1))).toThrow(ChatRequestTooLargeError);
});

it("counts multibyte text rather than UTF-16 code units", () => {
expect(() => assertChatRequestBudget("雪".repeat(Math.floor(LIMIT / 3) + 1))).toThrow(ChatRequestTooLargeError);
});

it("uses only a lower bound before sealing, leaving metadata to the final check", () => {
// This ciphertext alone fits exactly, although its envelope cannot fit.
const largestCiphertextOnlyBody = 3 * (LIMIT / 4) - 24 - 16;
expect(() => assertChatRequestBudget("a".repeat(largestCiphertextOnlyBody), true)).not.toThrow();
expect(() => assertChatRequestBudget("a".repeat(largestCiphertextOnlyBody + 1), true)).toThrow(ChatRequestTooLargeError);
});

it.each([0, 1, 2])("matches real NaCl/base64 padding for remainder %i", (remainder) => {
const body = new TextEncoder().encode("雪".repeat(5) + "a".repeat(remainder));
const key = nacl.box.keyPair();
const sealed = sealRawRequest(body, { kid: '"雪\\key', publicKey: key.publicKey });
const envelope = JSON.parse(sealed.envelopeJson);
expect(envelope.ciphertext.length).toBe(4 * Math.ceil((body.byteLength + 24 + 16) / 3));
expect(envelope.ciphertext.length).toBeLessThan(new TextEncoder().encode(sealed.envelopeJson).byteLength);
expect(() => assertChatRequestBudget(sealed.envelopeJson)).not.toThrow();
});
});
26 changes: 26 additions & 0 deletions console-ui/src/lib/chat/request-budget.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import nacl from "tweetnacl";

// Matches the coordinator's plaintext and sender-sealed transport body caps.
// Later coordinator rewrites still have their own authoritative size checks.
export const MAX_CHAT_REQUEST_BYTES = 16 * 1024 * 1024;

export class ChatRequestTooLargeError extends Error {
constructor() {
super("This message is too large to send. Use fewer or smaller images, shorten the conversation, or start a new chat.");
this.name = "ChatRequestTooLargeError";
}
}

/** Check serialized UTF-8 bytes, including the full history and request options. */
export function assertChatRequestBudget(body: string, willSeal = false): void {
const bytes = new TextEncoder().encode(body).byteLength;
if (bytes > MAX_CHAT_REQUEST_BYTES) throw new ChatRequestTooLargeError();

// A proven lower bound before fetching a key or allocating ciphertext:
// base64(nonce || authenticated ciphertext), excluding all envelope metadata.
// A fitting lower bound still requires a check of the actual sealed envelope.
const ciphertextBytes = bytes + nacl.box.nonceLength + nacl.box.overheadLength;
if (willSeal && 4 * Math.ceil(ciphertextBytes / 3) > MAX_CHAT_REQUEST_BYTES) {
throw new ChatRequestTooLargeError();
}
}
Loading
Loading