Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(chat): add a separate, configurable image size limit (#9312)
James Dam1b06176d1ac4
diff --git a/e2e/README.md b/e2e/README.mdindex 004570977..1dca61d4a 100644--- a/e2e/README.md+++ b/e2e/README.md@@ -36,19 +36,27 @@ on the hosted runners — inside the virtual display for no reason.## What it covers-Four spec files, run in this order (see [Spec order](#spec-order-is-maintained-by-hand)):+Five spec files, run in this order (see [Spec order](#spec-order-is-maintained-by-hand)):| Spec | Covers ||---|---|| `smoke.e2e.ts` | The app boots, React mounts, the first-run wizard renders, and the data folder Rust resolves is inside the throwaway profile. || `chat.e2e.ts` | Configure a provider and a model through the real dialogs; send; stream a reply; a second turn; survive a webview reload; delete the thread and confirm it left disk. || `message-actions.e2e.ts` | Regenerate; switch between reply versions; edit a user message and re-run; delete a single message; stop a reply mid-stream; New Chat into a fresh thread. |+| `image-limit.e2e.ts` | Image/document defaults and disabled state; persisted image limit; oversized rejection and accepted images through paste, drop and the hidden file input; inline base64 parts received by the mock. || `cowork-channel.e2e.ts` | The absent half of the channel gate: no sidebar tab, no settings entry, and a bookmarked `/cowork`, `/artifacts` or `/settings/cowork` URL lands where the guard sends it. |+The image spec generates valid PNGs inside the webview and dispatches synthetic+`ClipboardEvent` / `DragEvent` events, plus assigns a generated `FileList` to the+hidden image input and dispatches `change`. These exercise the real intake+handlers, validation and send path. They do not exercise the OS clipboard,+OS drag-and-drop or native file picker, which the embedded driver cannot drive.+The tests share state in declaration order and use their own mock model id.+Those are the load-bearing items of the manual checklist's D section: if thechat loop and the actions on a message work, the product works. Much of D isstill manual — rename, the search dialog, `Delete All`, projects, switching-model mid-conversation, markdown/LaTeX/code-block rendering, image attachments,+model mid-conversation, markdown/LaTeX/code-block rendering, native image pickers,IME input, the token-speed readout.**Deliberately out of scope.** llama.cpp: a real local model means a@@ -590,8 +598,9 @@ and `chat.e2e.ts` configures a provider, which under an alphabetically sortedglob ran first and broke it.The order is pristine first, most-configured last — `smoke` → `chat` →-`message-actions` — and it is the reason `message-actions.e2e.ts` can assume a-provider has already been configured and the analytics panel already answered.+`message-actions` → `image-limit` → `cowork-channel` — and it is the reason+`message-actions.e2e.ts` can assume a provider has already been configured and+the analytics panel already answered.It leaks further than a shared profile would explain. The embedded providerspawns **one** app in the launcher's `onPrepare` and every spec file drives thatdiff --git a/e2e/helpers/mock-openai.ts b/e2e/helpers/mock-openai.tsindex 787f8c3c1..82751ce23 100644--- a/e2e/helpers/mock-openai.ts+++ b/e2e/helpers/mock-openai.ts@@ -1,4 +1,9 @@-import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'+import {+ createServer,+ type IncomingMessage,+ type Server,+ type ServerResponse,+} from 'node:http'import { AddressInfo } from 'node:net'/**@@ -68,6 +73,31 @@ export type MockOptions = {chunkDelayMs?: number}+/**+ * The typed content parts of one streaming completion's last user message, as+ * the server saw them on the wire.+ *+ * A plain-text turn has `content` as a string, which is reported as a single+ * `text` part so every entry has the same shape. Image URLs are summarised+ * rather than stored: a data URL for a 1.5MB image is 2MB of base64, which+ * nobody wants in an assertion diff.+ */+export type MockUserParts = {+ /** `type` of every content part, in order (`text`, `image_url`, ...). */+ partTypes: string[]+ /** One entry per `image_url` part. */+ imageParts: Array<{+ /** The URL starts with `data:image/`. */+ isDataImageUrl: boolean+ /** The URL contains `;base64,`, i.e. it is inline base64, not a link. */+ hasBase64Marker: boolean+ /** Length of the whole URL string, in characters. */+ urlLength: number+ decodedBytes: number+ isValidPngDataUrl: boolean+ }>+}+export type MockOpenAI = {/** Feed this to the Add Provider dialog verbatim. */baseUrl: string@@ -95,6 +125,15 @@ export type MockOpenAI = {* they fire on a schedule of their own.*/streamedPrompts: string[]+ /**+ * The typed content parts of the last user message of every *streaming*+ * completion, oldest first, index-aligned with `streamedPrompts`. Live.+ *+ * It exists for the same reason `streamedPrompts` does: whether an attached+ * image really went out as an inline base64 data URL is not observable in the+ * DOM, and the echo reply only ever repeats the text.+ */+ streamedUserParts: MockUserParts[]close: () => Promise<void>}@@ -125,6 +164,44 @@ function lastUserText(messages: ChatMessage[]): string {return ''}+/** Summarise the typed parts of the last user turn; see MockUserParts. */+function lastUserParts(messages: ChatMessage[]): MockUserParts {+ const lastUser = [...messages].reverse().find((m) => m.role === 'user')+ const content = lastUser?.content+ if (typeof content === 'string') {+ return { partTypes: ['text'], imageParts: [] }+ }+ const parts = Array.isArray(content) ? content : []+ const partTypes: string[] = []+ const imageParts: MockUserParts['imageParts'] = []+ for (const part of parts) {+ const p = (part ?? {}) as { type?: unknown; image_url?: unknown }+ partTypes.push(String(p.type))+ if (p.type !== 'image_url') continue+ // OpenAI's shape is { image_url: { url } }; tolerate a bare string too.+ const raw = p.image_url+ const url =+ typeof raw === 'string'+ ? raw+ : String((raw as { url?: unknown } | undefined)?.url ?? '')+ const payload = url.split(',')[1] ?? ''+ const decoded = Buffer.from(payload, 'base64')+ imageParts.push({+ decodedBytes: decoded.length,+ isValidPngDataUrl:+ url.startsWith('data:image/png;base64,') &&+ decoded.toString('base64') === payload &&+ decoded+ .subarray(0, 8)+ .equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])),+ isDataImageUrl: url.startsWith('data:image/'),+ hasBase64Marker: url.includes(';base64,'),+ urlLength: url.length,+ })+ }+ return { partTypes, imageParts }+}+function readBody(req: IncomingMessage): Promise<string> {return new Promise((resolve, reject) => {let body = ''@@ -176,7 +253,7 @@ async function streamCompletion(res.writeHead(200, {'Content-Type': 'text/event-stream','Cache-Control': 'no-cache',- Connection: 'keep-alive',+ 'Connection': 'keep-alive','Access-Control-Allow-Origin': '*',})@@ -224,7 +301,8 @@ async function handle(res: ServerResponse,modelId: string,chunkDelay: () => number,- streamedPrompts: string[]+ streamedPrompts: string[],+ streamedUserParts: MockUserParts[]) {const url = req.url ?? '/'@@ -292,6 +370,7 @@ async function handle(// Recorded before the reply is written, so a spec that counts requests sees// this one even if the stream it opens is aborted halfway through.streamedPrompts.push(prompt)+ streamedUserParts.push(lastUserParts(body.messages ?? []))await streamCompletion(res, MOCK_REPLY_PREFIX + prompt, modelId, chunkDelay)return}@@ -318,6 +397,7 @@ export function startMockOpenAI(): Promise<MockOpenAI> {const modelId = options.modelId ?? MOCK_MODEL_IDconst streamedPrompts: string[] = []+ const streamedUserParts: MockUserParts[] = []// Held in one place the handle also points at, so assigning to// `mock.chunkDelayMs` mid-spec changes the next chunk rather than only the// next server.@@ -329,7 +409,8 @@ export function startMockOpenAI(res,modelId,() => state.chunkDelayMs,- streamedPrompts+ streamedPrompts,+ streamedUserParts).catch((error) => {if (res.headersSent) {res.end()@@ -347,6 +428,7 @@ export function startMockOpenAI(baseUrl: `http://127.0.0.1:${port}/v1`,modelId,streamedPrompts,+ streamedUserParts,get chunkDelayMs() {return state.chunkDelayMs},diff --git a/e2e/specs/image-limit.e2e.ts b/e2e/specs/image-limit.e2e.tsnew file mode 100644index 000000000..3ea799fcc--- /dev/null+++ b/e2e/specs/image-limit.e2e.ts@@ -0,0 +1,624 @@+import { readFileSync } from 'node:fs'+import { join } from 'node:path'++import { browser, expect, $, $$ } from '@wdio/globals'++import {+ ASSISTANT_MESSAGES,+ sendPrompt,+ waitForStreamToFinish,+} from '../helpers/chat.js'+import { clickWhenReady } from '../helpers/interactions.js'+import {+ MOCK_REPLY_PREFIX,+ startMockOpenAI,+ type MockOpenAI,+} from '../helpers/mock-openai.js'+import { goto, waitForPath } from '../helpers/navigation.js'+import { janUserDataDir } from '../helpers/paths.js'+import {+ configureMockProvider,+ denyAnalyticsConsent,+ selectModel,+} from '../helpers/provider.js'++// The worker inherits this from the launcher; see wdio.conf.ts.+const testHome = process.env.JAN_E2E_HOME!++// Own provider and own model id: see the same note in message-actions.e2e.ts.+const PROVIDER_NAME = 'e2e-image-limit-provider'+const MODEL_ID = 'jan-e2e-image-limit'++// Titles come from web-app/src/locales/en/settings.json+// (settings:attachments.maxImage / maxFile). The settings rows carry no testid,+// so the row is found by its heading: h1 -> description wrapper -> row.+const IMAGE_ROW_INPUT =+ '//h1[normalize-space(.)="Max Image Size (MB)"]/../..//input'+const ATTACHMENTS_TOGGLE =+ '//h1[normalize-space(.)="Enable Attachments"]/../..//*[@role="switch"]'+const DOC_ROW_INPUT =+ '//h1[normalize-space(.)="Max Document Size (MB)"]/../..//input'++// Persisted key of useImageAttachmentConfig (constants/localStorage.ts). The+// zustand persist blob lands in the backend settings store, a flat string map+// at <jan_data>/settings.json, as a JSON string.+const IMAGE_SETTING_KEY = 'setting-image-attachments'++// Sizes. The PNGs are built in the page, so no fixture is committed.+// 700x750 RGB, stored deflate -> ~1.50 MiB (over a 1MB limit, under 2MB)+// 740x1150 RGB, stored deflate -> ~2.43 MiB (over a 2MB limit)+// 57x58 RGB -> ~9.9 KB (under everything)+const BIG = { width: 700, height: 750 }+const HUGE = { width: 740, height: 1150 }+const SMALL = { width: 57, height: 58 }++/**+ * Browser-side helpers, installed once on `window.__e2e` as a plain string.+ *+ * A string rather than a function passed to browser.execute(): tsx compiles+ * with keepNames, which wraps named functions in a `__name()` call that does+ * not exist in the webview, so a function with inner helpers would die with+ * "__name is not defined".+ *+ * make() builds a valid PNG with *stored* (uncompressed) deflate blocks and a+ * seeded LCG for pixels, so the bytes are deterministic and the file+ * is as large as asked regardless of the compressor.+ * paste() dispatches a ClipboardEvent('paste') on the composer carrying a+ * DataTransfer that holds the File (ChatInput.handlePaste).+ * drop() dispatches a DragEvent('drop') carrying the File on the composer's+ * drop zone (ChatInput.handleDrop).+ * input() puts the File on the hidden image <input type=file> and fires+ * `change` (ChatInput.handleFileChange). Needs the "+" menu open,+ * because the input is rendered inside the menu content.+ */+const PAGE_HELPERS = `+(function () {+ var files = {};+ var table = [];+ for (var n = 0; n < 256; n++) {+ var c = n;+ for (var k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;+ table[n] = c >>> 0;+ }+ function crc(bytes) {+ var c = 0xffffffff;+ for (var i = 0; i < bytes.length; i++) c = table[(c ^ bytes[i]) & 0xff] ^ (c >>> 8);+ return (c ^ 0xffffffff) >>> 0;+ }+ function u32(v) { return [(v >>> 24) & 255, (v >>> 16) & 255, (v >>> 8) & 255, v & 255]; }+ function chunk(type, data) {+ var body = new Uint8Array(4 + data.length);+ for (var i = 0; i < 4; i++) body[i] = type.charCodeAt(i);+ body.set(data, 4);+ var out = new Uint8Array(12 + data.length);+ out.set(u32(data.length), 0);+ out.set(body, 4);+ out.set(u32(crc(body)), 8 + data.length);+ return out;+ }+ function makePng(w, h, seed) {+ var stride = w * 3 + 1;+ var raw = new Uint8Array(stride * h);+ var s = seed >>> 0;+ for (var y = 0; y < h; y++) {+ for (var x = 1; x < stride; x++) {+ s = (Math.imul(s, 1664525) + 1013904223) >>> 0;+ raw[y * stride + x] = s >>> 24;+ }+ }+ var a = 1, b = 0;+ for (var i = 0; i < raw.length; i++) { a = (a + raw[i]) % 65521; b = (b + a) % 65521; }+ var blocks = Math.ceil(raw.length / 65535);+ var z = new Uint8Array(2 + raw.length + blocks * 5 + 4);+ var p = 0;+ z[p++] = 0x78; z[p++] = 0x01;+ for (var off = 0; off < raw.length; off += 65535) {+ var len = Math.min(65535, raw.length - off);+ z[p++] = off + len >= raw.length ? 1 : 0;+ z[p++] = len & 255; z[p++] = len >>> 8;+ z[p++] = ~len & 255; z[p++] = (~len >>> 8) & 255;+ z.set(raw.subarray(off, off + len), p);+ p += len;+ }+ z.set(u32(((b << 16) | a) >>> 0), p);+ var ihdr = new Uint8Array(13);+ ihdr.set(u32(w), 0); ihdr.set(u32(h), 4);+ ihdr[8] = 8; ihdr[9] = 2;+ var parts = [+ new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]),+ chunk('IHDR', ihdr), chunk('IDAT', z), chunk('IEND', new Uint8Array(0))+ ];+ return new Blob(parts, { type: 'image/png' });+ }+ function dataTransferFor(name) {+ var dt = new DataTransfer();+ dt.items.add(files[name]);+ return dt;+ }+ window.__e2e = {+ make: async function (name, w, h, seed) {+ files[name] = new File([makePng(w, h, seed)], name, { type: 'image/png' });+ var url = URL.createObjectURL(files[name]);+ try {+ var image = new Image();+ image.src = url;+ await image.decode();+ if (image.naturalWidth !== w || image.naturalHeight !== h) throw new Error('PNG dimensions differ');+ } finally { URL.revokeObjectURL(url); }+ return files[name].size;+ },+ paste: function (name) {+ var dt = dataTransferFor(name);+ var ev = new ClipboardEvent('paste', { clipboardData: dt, bubbles: true, cancelable: true });+ var seen = ev.clipboardData ? ev.clipboardData.items.length : -1;+ document.querySelector('[data-testid="chat-input"]').dispatchEvent(ev);+ return { itemsOnEvent: seen, defaultPrevented: ev.defaultPrevented };+ },+ drop: function (name) {+ var zone = document.querySelector('[data-drop-zone="true"]');+ if (!zone) return { zone: false, defaultPrevented: false };+ var ev = new DragEvent('drop', { dataTransfer: dataTransferFor(name), bubbles: true, cancelable: true });+ zone.dispatchEvent(ev);+ return { zone: true, defaultPrevented: ev.defaultPrevented };+ },+ input: function (name) {+ var el = document.querySelector('input[type="file"]:not([accept])');+ if (!el) return { found: false, assigned: 0 };+ el.files = dataTransferFor(name).files;+ var assigned = el.files.length;+ el.dispatchEvent(new Event('change', { bubbles: true }));+ return { found: true, assigned: assigned };+ }+ };+})();+`++/** Build a PNG in the page and keep it there under `name`; returns its size. */+async function makeImage(+ name: string,+ dims: { width: number; height: number },+ seed: number+): Promise<number> {+ return browser.execute(+ (n: string, w: number, h: number, s: number) =>+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ (window as any).__e2e.make(n, w, h, s) as number,+ name,+ dims.width,+ dims.height,+ seed+ )+}++async function pasteImage(name: string) {+ const result = await browser.execute(+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ (n: string) => (window as any).__e2e.paste(n),+ name+ )+ // Both facts matter: the event really carried the file, and ChatInput's+ // handler claimed it (it preventDefault()s synchronously for image items).+ expect(result.itemsOnEvent).toBe(1)+ expect(result.defaultPrevented).toBe(true)+}++async function dropImage(name: string) {+ const result = await browser.execute(+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ (n: string) => (window as any).__e2e.drop(n),+ name+ )+ // data-drop-zone is only rendered while the selected model can take images.+ expect(result.zone).toBe(true)+ expect(result.defaultPrevented).toBe(true)+}++/**+ * Open the composer's "+" menu and wait for "Add Images".+ *+ * Radix's trigger opens on pointerdown, which this driver never produces, so it+ * is the click-to-focus + Enter route used for the thread menu in chat.e2e.ts.+ * "Add Images" is only rendered for a vision model, so seeing it is also proof+ * the capability flag took.+ */+async function openPlusMenu() {+ const plus = await $('//button[.//*[contains(@class,"lucide-plus")]]')+ await plus.waitForExist({ timeout: 30_000 })+ await plus.click()+ await browser.keys('Enter')+ await $('//*[@role="menuitem"][contains(., "Add Images")]').waitForDisplayed({+ timeout: 15_000,+ timeoutMsg:+ 'the "+" menu never showed "Add Images": either the menu did not open or ' ++ 'the model has no vision capability.',+ })+}++async function inputImage(name: string) {+ await openPlusMenu()+ const result = await browser.execute(+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ (n: string) => (window as any).__e2e.input(n),+ name+ )+ expect(result).toEqual({ found: true, assigned: 1 })+ // Close the menu so it cannot sit between the spec and the composer.+ await browser.keys('Escape')+}++const errorBanner = (needle: string) =>+ `//*[contains(@class,"text-destructive")][contains(., "${needle}")]`+const chip = (name: string) => `img[alt="${name}"]`++/** Type into a settings number input and wait for the 500ms debounce to land. */+async function setLimitViaUi(inputXpath: string, value: number) {+ const input = await $(inputXpath)+ await input.waitForDisplayed({ timeout: 30_000 })+ await input.setValue(String(value))+ // The debounce commits to the store, which persists to settings.json: that+ // file is the settle signal, not a fixed sleep.+ await browser.waitUntil(() => persistedImageLimit() === value, {+ timeout: 15_000,+ timeoutMsg: `settings.json never recorded maxImageSizeMB=${value}`,+ })+ await browser.waitUntil(+ async () => (await input.getValue()) === String(value),+ {+ timeout: 10_000,+ timeoutMsg: `the input does not read ${value} after the debounce`,+ }+ )+}++function persistedImageLimit(): number | undefined {+ try {+ const file = join(janUserDataDir(testHome), 'settings.json')+ const store = JSON.parse(readFileSync(file, 'utf8')) as Record<+ string,+ string+ >+ const blob = store[IMAGE_SETTING_KEY]+ return blob ? JSON.parse(blob).state?.maxImageSizeMB : undefined+ } catch {+ return undefined+ }+}++async function openAttachmentsSettings(viaMenu: boolean) {+ if (viaMenu) {+ await clickWhenReady('a[href="/settings/attachments"]')+ await waitForPath('/settings/attachments')+ } else {+ await goto('/settings/attachments')+ }+ await $(IMAGE_ROW_INPUT).waitForDisplayed({ timeout: 30_000 })+ await $(DOC_ROW_INPUT).waitForDisplayed({ timeout: 30_000 })+}++describe('image size limit', () => {+ let mock: MockOpenAI+ let bigSize = 0++ before(async () => {+ mock = await startMockOpenAI({ modelId: MODEL_ID })++ await $('#root').waitForExist({ timeout: 60_000 })++ await configureMockProvider(mock, PROVIDER_NAME)+ await denyAnalyticsConsent({ required: false })++ // A model added by hand only gets `completion`, and every image intake path+ // in ChatInput is gated on the `vision` capability (hasMmproj). Turn it on+ // the way a user would: the pencil on the model row -> Vision -> Save. The+ // pencil has no testid, so it is found by its icon class; the switch has a+ // stable id.+ const pencil = await $(+ '//*[local-name()="svg" and contains(@class,"tabler-icon-pencil")]/..'+ )+ await pencil.waitForDisplayed({ timeout: 30_000 })+ await pencil.click()+ await clickWhenReady('#vision-capability')+ await expect($('#vision-capability')).toHaveAttribute(+ 'data-state',+ 'checked'+ )+ await clickWhenReady('//button[normalize-space(.)="Save Changes"]')+ await $('#vision-capability').waitForDisplayed({+ reverse: true,+ timeout: 15_000,+ })++ await browser.execute(PAGE_HELPERS)+ })++ after(async () => {+ try {+ // Restore the UI toggle after keeping documents off throughout intake.+ await openAttachmentsSettings(false)+ const toggle = await $(ATTACHMENTS_TOGGLE)+ if ((await toggle.getAttribute('data-state')) === 'unchecked')+ await toggle.click()+ await expect(toggle).toHaveAttribute('data-state', 'checked')+ } finally {+ if (mock) await mock.close()+ }+ })++ it('shows the defaults: 10MB images, 100MB documents, both in the Limits card', async () => {+ // From the provider page the settings menu is on screen, so this one goes+ // through the real navigation link.+ await openAttachmentsSettings(true)+ // RAG extension settings use webview localStorage, which can survive app+ // launches on macOS even when the backend profile is new. Establish the+ // toggle through the UI rather than assuming the previous run left it on.+ const toggle = await $(ATTACHMENTS_TOGGLE)+ if ((await toggle.getAttribute('data-state')) !== 'checked')+ await toggle.click()+ await expect(toggle).toHaveAttribute('data-state', 'checked')++ await expect($(IMAGE_ROW_INPUT)).toHaveValue('10')+ await expect($(DOC_ROW_INPUT)).toHaveValue('100')++ // Both limits share the Limits card, with images first.+ const rowsInLimitsCard = await browser.execute(() => {+ const card = Array.from(document.querySelectorAll('h1')).find(+ (h) => h.textContent?.trim() === 'Limits'+ )?.parentElement+ if (!card) return []+ return Array.from(card.querySelectorAll('h1'))+ .map((h) => h.textContent?.trim() ?? '')+ .filter((text) => text !== 'Limits')+ })+ expect(rowsInLimitsCard).toEqual([+ 'Max Image Size (MB)',+ 'Max Document Size (MB)',+ ])+ })++ it('disables only the document limit when Enable Attachments is off', async () => {+ const toggle = await $(ATTACHMENTS_TOGGLE)+ await expect(toggle).toHaveAttribute('data-state', 'checked')+ await expect(+ $(DOC_ROW_INPUT + '/ancestor::*[@aria-disabled="true"]')+ ).not.toBeExisting()+ await toggle.click()+ await expect(toggle).toHaveAttribute('data-state', 'unchecked')+ // disabledReason wraps the control; it does not set input.disabled.+ const disabledDocument = $(+ DOC_ROW_INPUT + '/ancestor::*[@aria-disabled="true"]'+ )+ await expect(disabledDocument).toHaveAttribute(+ 'title',+ 'Turn on Enable Attachments to change the document size limit.'+ )+ expect(+ (await disabledDocument.getCSSProperty('pointer-events')).value+ ).toBe('none')+ expect((await disabledDocument.getCSSProperty('opacity')).value).toBe(0.5)+ await expect(+ $(IMAGE_ROW_INPUT + '/ancestor::*[@aria-disabled="true"]')+ ).not.toBeExisting()+ await expect($(IMAGE_ROW_INPUT)).toBeEnabled()+ await expect($(DOC_ROW_INPUT + '/ancestor::*[@inert]/..')).toHaveAttribute(+ 'title',+ 'Turn on Enable Attachments to change the document size limit.'+ )+ await expect($(IMAGE_ROW_INPUT + '/ancestor::*[@inert]')).not.toBeExisting()+ const focus = await browser.execute(() => {+ const headings = Array.from(document.querySelectorAll('h1'))+ const documentInput = headings+ .find((h) => h.textContent?.trim() === 'Max Document Size (MB)')+ ?.parentElement?.parentElement?.querySelector('input')+ const imageInput = headings+ .find((h) => h.textContent?.trim() === 'Max Image Size (MB)')+ ?.parentElement?.parentElement?.querySelector('input')+ imageInput?.focus()+ const imageFocused = document.activeElement === imageInput+ documentInput?.focus()+ return {+ imageFocused,+ documentFocused: document.activeElement === documentInput,+ }+ })+ expect(focus).toEqual({ imageFocused: true, documentFocused: false })+ // Leave documents off: subsequent accepted images prove independence.+ })++ it('saves an image limit edit when navigating away before the debounce', async () => {+ // Dispatch the input and navigation in one webview task: the 500ms timer+ // cannot fire between them, regardless of WebDriver round-trip latency.+ await browser.execute(() => {+ const heading = Array.from(document.querySelectorAll('h1')).find(+ (h) => h.textContent?.trim() === 'Max Image Size (MB)'+ )+ const input =+ heading?.parentElement?.parentElement?.querySelector('input')+ const link = document.querySelector<HTMLAnchorElement>(+ 'a[href="/settings/general"]'+ )+ if (!input || !link)+ throw new Error('Missing image limit or settings navigation')+ // React tracks direct assignments; use the native setter and an input+ // event to deliver the same change as typing, then the real UI link.+ const setter = Object.getOwnPropertyDescriptor(+ HTMLInputElement.prototype,+ 'value'+ )!.set!+ setter.call(input, '2')+ input.dispatchEvent(new Event('input', { bubbles: true }))+ link.click()+ })+ await waitForPath('/settings/general')+ await browser.waitUntil(() => persistedImageLimit() === 2, {+ timeout: 15_000,+ timeoutMsg: 'leaving Settings before 500ms lost the pending image limit',+ })+ await openAttachmentsSettings(true)+ await expect($(IMAGE_ROW_INPUT)).toHaveValue('2')+ await expect($(DOC_ROW_INPUT)).toHaveValue('100')+ })++ it('persists a new image limit of 1MB set through the input', async () => {+ await setLimitViaUi(IMAGE_ROW_INPUT, 1)+ // Setting the image limit must not move the document limit.+ await expect($(DOC_ROW_INPUT)).toHaveValue('100')+ })++ it('rejects a 1.5MB image on paste, drop and the file input, with no chip', async () => {+ bigSize = await makeImage('oversized-paste.png', BIG, 1)+ await makeImage('oversized-drop.png', BIG, 1)+ await makeImage('oversized-input.png', BIG, 1)+ // Over 1MiB and under 2MiB, which is what the next steps lean on.+ expect(bigSize).toBeGreaterThan(1024 * 1024)+ expect(bigSize).toBeLessThan(2 * 1024 * 1024)++ await goto('/')+ await selectModel(MODEL_ID)++ for (const [deliver, name] of [+ [pasteImage, 'oversized-paste.png'],+ [dropImage, 'oversized-drop.png'],+ [inputImage, 'oversized-input.png'],+ ] as const) {+ await deliver(name)+ // Names differ per path, so each message is that path's own. The message+ // is set after validation and the chip would be added before it, so+ // waiting for the message first makes the "no chip" check below mean+ // something.+ await $(+ errorBanner(`File too large (max 1MB): ${name}`)+ ).waitForDisplayed({+ timeout: 30_000,+ timeoutMsg: `no "too large (max 1MB)" error for ${name}`,+ })+ await expect($(chip(name))).not.toBeExisting()+ }+ await expect($$('img[alt$=".png"]')).toBeElementsArrayOfSize(0)+ })++ it('accepts a 10KB image and sends it as exactly one base64 image part', async () => {+ const size = await makeImage('small-paste.png', SMALL, 2)+ expect(size).toBeGreaterThan(9 * 1024)+ expect(size).toBeLessThan(11 * 1024)++ await pasteImage('small-paste.png')+ await $(chip('small-paste.png')).waitForDisplayed({ timeout: 30_000 })+ // Accepting an image clears the previous rejection.+ await expect($(errorBanner('too large'))).not.toBeExisting()++ const before = mock.streamedUserParts.length+ await sendPrompt('describe the small picture')+ await expect($(ASSISTANT_MESSAGES)).toHaveText(+ expect.stringContaining(MOCK_REPLY_PREFIX + 'describe the small picture')+ )+ await waitForStreamToFinish()++ expect(mock.streamedUserParts.length).toBe(before + 1)+ const parts = mock.streamedUserParts[before]+ expect(parts.imageParts).toHaveLength(1)+ expect(parts.imageParts[0].isDataImageUrl).toBe(true)+ expect(parts.partTypes).toEqual(['text', 'image_url'])+ expect(parts.imageParts[0].decodedBytes).toBe(size)+ expect(parts.imageParts[0].isValidPngDataUrl).toBe(true)+ // ~10KB of PNG is ~13KB of base64: it is the image, not a stub.+ expect(parts.imageParts[0].urlLength).toBeGreaterThan(10_000)+ })++ it('accepts small images through drop and the file input as well', async () => {+ await makeImage('small-drop.png', SMALL, 3)+ await makeImage('small-input.png', SMALL, 4)++ await dropImage('small-drop.png')+ await $(chip('small-drop.png')).waitForDisplayed({ timeout: 30_000 })+ await inputImage('small-input.png')+ await $(chip('small-input.png')).waitForDisplayed({ timeout: 30_000 })++ const before = mock.streamedUserParts.length+ await sendPrompt('describe both pictures')+ await waitForStreamToFinish()+ await browser.waitUntil(+ () => mock.streamedUserParts.length === before + 1,+ {+ timeout: 30_000,+ timeoutMsg: 'the mock never saw the second image turn',+ }+ )+ const parts = mock.streamedUserParts[before]+ expect(parts.imageParts).toHaveLength(2)+ for (const image of parts.imageParts) {+ expect(image.isDataImageUrl).toBe(true)+ expect(image.hasBase64Marker).toBe(true)+ }+ })++ it('accepts the 1.5MB image once the limit is raised to 2MB', async () => {+ await openAttachmentsSettings(false)+ await setLimitViaUi(IMAGE_ROW_INPUT, 2)+ await expect($(DOC_ROW_INPUT)).toHaveValue('100')++ await goto('/')+ await selectModel(MODEL_ID)++ await makeImage('big-accepted.png', BIG, 1)+ await pasteImage('big-accepted.png')+ await $(chip('big-accepted.png')).waitForDisplayed({ timeout: 30_000 })+ await expect($(errorBanner('too large'))).not.toBeExisting()++ const before = mock.streamedUserParts.length+ await sendPrompt('describe the big picture')+ await waitForStreamToFinish()+ await browser.waitUntil(+ () => mock.streamedUserParts.length === before + 1,+ {+ timeout: 60_000,+ timeoutMsg: 'the mock never saw the big image turn',+ }+ )+ const parts = mock.streamedUserParts[before]+ expect(parts.imageParts).toHaveLength(1)+ expect(parts.imageParts[0].isDataImageUrl).toBe(true)+ expect(parts.imageParts[0].hasBase64Marker).toBe(true)+ // 1.5MiB of PNG is >2MB of base64 text: the whole image went out.+ expect(parts.imageParts[0].urlLength).toBeGreaterThan(1.5 * 1024 * 1024)+ })++ it('names the new limit when a 2.4MB image is rejected', async () => {+ await goto('/')+ await selectModel(MODEL_ID)++ const size = await makeImage('huge-paste.png', HUGE, 5)+ expect(size).toBeGreaterThan(2 * 1024 * 1024)++ await pasteImage('huge-paste.png')+ await $(+ errorBanner('too large (max 2MB): huge-paste.png')+ ).waitForDisplayed({+ timeout: 30_000,+ timeoutMsg: 'the rejection did not report the raised 2MB limit',+ })+ await expect($(chip('huge-paste.png'))).not.toBeExisting()+ })++ it('keeps the image limit across a webview reload, and the document limit unchanged', async () => {+ // Same reload recipe as chat.e2e.ts: from `/`, never from a deep path.+ await goto('/')+ await browser.refresh()+ await $('#root').waitForExist({ timeout: 60_000 })+ await $('[data-testid="model-selector-trigger"]').waitForDisplayed({+ timeout: 60_000,+ })++ await openAttachmentsSettings(false)++ // The store starts at the default and rehydrates asynchronously from the+ // backend, so wait for the value rather than reading it once. A limit that+ // did not persist would settle on 10 and fail here.+ const image = await $(IMAGE_ROW_INPUT)+ await browser.waitUntil(async () => (await image.getValue()) === '2', {+ timeout: 15_000,+ timeoutMsg: 'after a reload Max Image Size did not come back as 2',+ })+ await expect($(DOC_ROW_INPUT)).toHaveValue('100')+ expect(persistedImageLimit()).toBe(2)+ })+})diff --git a/e2e/wdio.conf.ts b/e2e/wdio.conf.tsindex a8a91e0ab..21eb75384 100644--- a/e2e/wdio.conf.ts+++ b/e2e/wdio.conf.ts@@ -258,7 +258,7 @@ export const config: WebdriverIO.Config = {// The cost is that this list is maintained by hand: a new spec that is not// added here does not run, and nothing reports its absence.//- // The order below is smoke -> chat -> message-actions -> cowork-channel,+ // The order below is smoke -> chat -> message-actions -> image-limit -> cowork-channel,// pristine first and most-configured last. message-actions.e2e.ts registers a// second provider and leaves two threads behind, so it has to come after// anything that cares what the profile holds. cowork-channel.e2e.ts writes@@ -269,6 +269,7 @@ export const config: WebdriverIO.Config = {'./specs/smoke.e2e.ts','./specs/chat.e2e.ts','./specs/message-actions.e2e.ts',+ './specs/image-limit.e2e.ts','./specs/cowork-channel.e2e.ts',],maxInstances: 1,diff --git a/web-app/src/constants/localStorage.ts b/web-app/src/constants/localStorage.tsindex 16e44c93b..6f75f74a0 100644--- a/web-app/src/constants/localStorage.ts+++ b/web-app/src/constants/localStorage.ts@@ -12,6 +12,7 @@ export const localStorageKey = {settingProxyConfig: 'setting-proxy-config',settingWebSearch: 'setting-web-search',settingCowork: 'setting-cowork',+ settingImageAttachments: 'setting-image-attachments',settingHardware: 'setting-hardware',settingVulkan: 'setting-vulkan',productAnalyticPrompt: 'productAnalyticPrompt',diff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsxindex 335c91074..334bf2fd1 100644--- a/web-app/src/containers/ChatInput.tsx+++ b/web-app/src/containers/ChatInput.tsx@@ -85,6 +85,7 @@ import {} from '@janhq/core'import { ExtensionManager } from '@/lib/extension'import { useAttachments } from '@/hooks/useAttachments'+import { useImageAttachmentConfig } from '@/hooks/useImageAttachmentConfig'import { toast } from 'sonner'import { isPlatformTauri } from '@/lib/platform/utils'import { shouldShowTokenCounter } from '@/lib/tokenCounterVisibility'@@ -515,6 +516,7 @@ const ChatInput = memo(function ChatInput({(s) => s.autoInlineContextRatio)const maxFileSizeMB = useAttachments((s) => s.maxFileSizeMB)+ const maxImageSizeMB = useImageAttachmentConfig((s) => s.maxImageSizeMB)// Derived: any document currently processing (ingestion in progress)// Same scope as the message queue: a surface writing attachments under its@@ -1225,7 +1227,7 @@ const ChatInput = memo(function ChatInput({}const processImageFiles = useCallback(async (files: File[]) => {- const maxSize = 10 * 1024 * 1024 // 10MB in bytes+ const maxSize = maxImageSizeMB * 1024 * 1024const oversizedFiles: string[] = []const invalidTypeFiles: string[] = []@@ -1402,7 +1404,7 @@ const ChatInput = memo(function ChatInput({const errors: string[] = []if (oversizedFiles.length > 0) {errors.push(- `File${oversizedFiles.length > 1 ? 's' : ''} too large (max 10MB): ${oversizedFiles.join(', ')}`+ `File${oversizedFiles.length > 1 ? 's' : ''} too large (max ${maxImageSizeMB}MB): ${oversizedFiles.join(', ')}`)}@@ -1421,7 +1423,7 @@ const ChatInput = memo(function ChatInput({} else {setMessage('')}- }, [attachmentsKey, currentThreadId, scopeKey, setAttachmentsForThread, serviceHub, setFileIngestProgress])+ }, [attachmentsKey, currentThreadId, scopeKey, setAttachmentsForThread, serviceHub, setFileIngestProgress, maxImageSizeMB])const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {const files = e.target.filesdiff --git a/web-app/src/containers/__tests__/ChatInput.test.tsx b/web-app/src/containers/__tests__/ChatInput.test.tsxindex e74671069..646eb28a2 100644--- a/web-app/src/containers/__tests__/ChatInput.test.tsx+++ b/web-app/src/containers/__tests__/ChatInput.test.tsx@@ -140,6 +140,16 @@ vi.mock('@/hooks/useAttachments', () => ({}),}))+// The real image-limit store runs against an in-memory backend so tests can+// set the configured limit the same way the settings page does.+vi.mock('@/lib/backendStorage', () => ({+ backendStorage: {+ getItem: async () => null,+ setItem: async () => {},+ removeItem: async () => {},+ },+}))+let attachmentsList: any[] = []/** Attachments stored under a specific scope key, for the scopeKey tests. */let attachmentsByKey: Record<string, any[]> = {}@@ -315,6 +325,7 @@ vi.mock('@/lib/platform/utils', () => ({// Import component AFTER all mocksimport ChatInput from '../ChatInput'+import { useImageAttachmentConfig } from '@/hooks/useImageAttachmentConfig'// Helpers -------------------------------------------------------------------@@ -338,6 +349,7 @@ const resetAll = () => {clearQueueMock.mockClear()for (const k of Object.keys(queueState)) delete queueState[k]getCurrentThreadMock.mockReturnValue(undefined)+ useImageAttachmentConfig.setState({ maxImageSizeMB: 10 })}const getTextarea = () =>@@ -735,4 +747,109 @@ describe('ChatInput', () => {expect(dimmed!.contains(screen.getByText('plan'))).toBe(false)})})++ describe('image size limit', () => {+ const MB = 1024 * 1024+ const imageFile = (name: string, bytes: number, type = 'image/png') => {+ const file = new File(['x'], name, { type })+ Object.defineProperty(file, 'size', { value: bytes })+ return file+ }+ const renderVision = () => {+ selectedModelOverride = {+ id: 'vision-model',+ capabilities: ['tools', 'vision'],+ provider: 'llamacpp',+ }+ return renderInput()+ }+ const pickFiles = (files: File[]) => {+ const input = document.querySelector(+ 'input[type="file"]:not([accept])'+ ) as HTMLInputElement+ fireEvent.change(input, { target: { files } })+ }+ // ChatInput always calls setAttachments with an updater; run it against an+ // empty list to see which images (if any) it would add.+ const attachedImages = () =>+ setAttachmentsMock.mock.calls.flatMap(([, updater]) =>+ typeof updater === 'function' ? updater([]) : updater+ )+ const attachedNames = () => (attachedImages().length > 0 ? 'attached' : 'none')++ beforeEach(() => {+ setAttachmentsMock.mockClear()+ })++ it('accepts an image under the default 10MB limit via the picker', async () => {+ renderVision()+ pickFiles([imageFile('ok.png', 9 * MB)])+ await waitFor(() => expect(attachedNames()).toBe('attached'))+ expect(screen.queryByText(/too large/)).not.toBeInTheDocument()+ })++ it('rejects an image over the default limit and reports 10MB', async () => {+ renderVision()+ pickFiles([imageFile('big.png', 11 * MB)])+ expect(+ await screen.findByText('File too large (max 10MB): big.png')+ ).toBeInTheDocument()+ expect(attachedNames()).toBe('none')+ })++ it('honors a raised limit and accepts a 20MB image', async () => {+ useImageAttachmentConfig.setState({ maxImageSizeMB: 25 })+ renderVision()+ pickFiles([imageFile('large.png', 20 * MB)])+ await waitFor(() => expect(attachedNames()).toBe('attached'))+ expect(screen.queryByText(/too large/)).not.toBeInTheDocument()+ })++ it('honors a lowered limit and builds the message from it', async () => {+ useImageAttachmentConfig.setState({ maxImageSizeMB: 2 })+ renderVision()+ pickFiles([imageFile('a.png', 3 * MB), imageFile('b.png', 4 * MB)])+ expect(+ await screen.findByText('Files too large (max 2MB): a.png, b.png')+ ).toBeInTheDocument()+ expect(attachedNames()).toBe('none')+ })++ it('applies the same limit to pasted images', async () => {+ useImageAttachmentConfig.setState({ maxImageSizeMB: 3 })+ renderVision()+ const file = imageFile('pasted.png', 5 * MB)+ fireEvent.paste(getTextarea(), {+ clipboardData: {+ items: [{ type: 'image/png', getAsFile: () => file }],+ },+ })+ expect(+ await screen.findByText('File too large (max 3MB): pasted.png')+ ).toBeInTheDocument()+ })++ it('applies the same limit to dropped images', async () => {+ useImageAttachmentConfig.setState({ maxImageSizeMB: 3 })+ // jsdom has no DataTransfer constructor; handleDrop builds one.+ class FakeDataTransfer {+ files: File[] = []+ items = { add: (f: File) => this.files.push(f) }+ }+ vi.stubGlobal('DataTransfer', FakeDataTransfer)+ try {+ renderVision()+ const dropZone = document.querySelector(+ '[data-drop-zone="true"]'+ ) as HTMLElement+ const file = imageFile('dropped.png', 5 * MB)+ fireEvent.drop(dropZone, { dataTransfer: { files: [file] } })+ expect(+ await screen.findByText('File too large (max 3MB): dropped.png')+ ).toBeInTheDocument()+ } finally {+ vi.unstubAllGlobals()+ }+ })+ })})diff --git a/web-app/src/hooks/__tests__/useImageAttachmentConfig.test.ts b/web-app/src/hooks/__tests__/useImageAttachmentConfig.test.tsnew file mode 100644index 000000000..1b9ff7c42--- /dev/null+++ b/web-app/src/hooks/__tests__/useImageAttachmentConfig.test.ts@@ -0,0 +1,138 @@+import { describe, it, expect, vi, beforeEach } from 'vitest'++// Real zustand persist, fake disk standing in for the backend settings store.+const disk = vi.hoisted(() => new Map<string, string>())+vi.mock('@/lib/backendStorage', () => ({+ backendStorage: {+ getItem: async (name: string) => disk.get(name) ?? null,+ setItem: async (name: string, value: string) => {+ disk.set(name, value)+ },+ removeItem: async (name: string) => {+ disk.delete(name)+ },+ },+}))+vi.mock('@/lib/extension', () => ({+ ExtensionManager: { getInstance: () => ({ get: () => undefined }) },+}))+vi.mock('@janhq/core', () => ({+ ExtensionTypeEnum: { RAG: 'rag' },+}))++import {+ useImageAttachmentConfig,+ clampImageSizeMB,+ DEFAULT_MAX_IMAGE_SIZE_MB,+ MIN_MAX_IMAGE_SIZE_MB,+ MAX_MAX_IMAGE_SIZE_MB,+} from '../useImageAttachmentConfig'+import { useAttachments } from '../useAttachments'+import { hydrateBackendStores } from '@/lib/hydrateStores'++describe('useImageAttachmentConfig', () => {+ beforeEach(() => {+ disk.clear()+ useImageAttachmentConfig.setState({+ maxImageSizeMB: DEFAULT_MAX_IMAGE_SIZE_MB,+ })+ })++ it('defaults to 10MB so behavior is unchanged', () => {+ expect(DEFAULT_MAX_IMAGE_SIZE_MB).toBe(10)+ expect(useImageAttachmentConfig.getState().maxImageSizeMB).toBe(10)+ })++ it('updates the limit', () => {+ useImageAttachmentConfig.getState().setMaxImageSizeMB(25)+ expect(useImageAttachmentConfig.getState().maxImageSizeMB).toBe(25)+ })++ it('clamps to the 1-100MB range and floors fractions', () => {+ const { setMaxImageSizeMB } = useImageAttachmentConfig.getState()+ setMaxImageSizeMB(0)+ expect(useImageAttachmentConfig.getState().maxImageSizeMB).toBe(+ MIN_MAX_IMAGE_SIZE_MB+ )+ setMaxImageSizeMB(500)+ expect(useImageAttachmentConfig.getState().maxImageSizeMB).toBe(+ MAX_MAX_IMAGE_SIZE_MB+ )+ setMaxImageSizeMB(12.9)+ expect(useImageAttachmentConfig.getState().maxImageSizeMB).toBe(12)+ })++ it('ignores non-numeric input', () => {+ useImageAttachmentConfig.getState().setMaxImageSizeMB(30)+ useImageAttachmentConfig.getState().setMaxImageSizeMB(NaN)+ expect(useImageAttachmentConfig.getState().maxImageSizeMB).toBe(30)+ expect(clampImageSizeMB('abc', 7)).toBe(7)+ })++ it('flushes the value to the backend store', async () => {+ useImageAttachmentConfig.getState().setMaxImageSizeMB(40)+ await vi.waitFor(() => {+ expect(+ JSON.parse(disk.get('setting-image-attachments') ?? '{}').state+ ).toEqual({ maxImageSizeMB: 40 })+ })+ })++ it('hydrates a saved value, surviving a restart', async () => {+ disk.set(+ 'setting-image-attachments',+ JSON.stringify({ state: { maxImageSizeMB: 50 }, version: 0 })+ )+ await useImageAttachmentConfig.persist.rehydrate()+ expect(useImageAttachmentConfig.getState().maxImageSizeMB).toBe(50)+ })++ it('keeps the default when nothing is saved', async () => {+ await useImageAttachmentConfig.persist.rehydrate()+ expect(useImageAttachmentConfig.getState().maxImageSizeMB).toBe(10)+ })++ it('sanitizes an out-of-range saved value instead of disabling the limit', async () => {+ disk.set(+ 'setting-image-attachments',+ JSON.stringify({ state: { maxImageSizeMB: 0 }, version: 0 })+ )+ await useImageAttachmentConfig.persist.rehydrate()+ expect(useImageAttachmentConfig.getState().maxImageSizeMB).toBe(1)+ // A record that is not a number falls back to the current value, so reset+ // it first: the assertion must not depend on the previous rehydrate.+ useImageAttachmentConfig.setState({ maxImageSizeMB: 10 })+ disk.set(+ 'setting-image-attachments',+ JSON.stringify({ state: { maxImageSizeMB: 'junk' }, version: 0 })+ )+ await useImageAttachmentConfig.persist.rehydrate()+ expect(useImageAttachmentConfig.getState().maxImageSizeMB).toBe(10)+ })++ it('is rehydrated by hydrateBackendStores', async () => {+ disk.set(+ 'setting-image-attachments',+ JSON.stringify({ state: { maxImageSizeMB: 33 }, version: 0 })+ )+ await hydrateBackendStores()+ expect(useImageAttachmentConfig.getState().maxImageSizeMB).toBe(33)+ })++ it('is independent of the document limit', () => {+ const docBefore = useAttachments.getState().maxFileSizeMB+ useImageAttachmentConfig.getState().setMaxImageSizeMB(60)+ expect(useAttachments.getState().maxFileSizeMB).toBe(docBefore)+ useAttachments.setState({ maxFileSizeMB: 150 })+ expect(useImageAttachmentConfig.getState().maxImageSizeMB).toBe(60)+ useAttachments.setState({ maxFileSizeMB: docBefore })+ })++ it('treats null and an empty string as non-numeric, not as 0', () => {+ useImageAttachmentConfig.setState({ maxImageSizeMB: 25 })+ useImageAttachmentConfig.getState().setMaxImageSizeMB(null as never)+ expect(useImageAttachmentConfig.getState().maxImageSizeMB).toBe(25)+ useImageAttachmentConfig.getState().setMaxImageSizeMB('' as never)+ expect(useImageAttachmentConfig.getState().maxImageSizeMB).toBe(25)+ })+})diff --git a/web-app/src/hooks/useImageAttachmentConfig.ts b/web-app/src/hooks/useImageAttachmentConfig.tsnew file mode 100644index 000000000..c37b51872--- /dev/null+++ b/web-app/src/hooks/useImageAttachmentConfig.ts@@ -0,0 +1,62 @@+import { create } from 'zustand'+import { persist, createJSONStorage } from 'zustand/middleware'+import { localStorageKey } from '@/constants/localStorage'+import { backendStorage } from '@/lib/backendStorage'++/** Default cap per image. Matches the previously hardcoded limit. */+export const DEFAULT_MAX_IMAGE_SIZE_MB = 10+export const MIN_MAX_IMAGE_SIZE_MB = 1+export const MAX_MAX_IMAGE_SIZE_MB = 100++/**+ * Coerce an arbitrary value to a whole number of MB within the allowed range.+ * Non-numeric input returns `fallback`.+ */+export const clampImageSizeMB = (+ value: unknown,+ fallback: number = DEFAULT_MAX_IMAGE_SIZE_MB+): number => {+ // null and '' coerce to 0, which would silently snap to the 1 MB floor.+ if (value === null || value === '') return fallback+ const num = typeof value === 'number' ? value : Number(value)+ if (!Number.isFinite(num)) return fallback+ return Math.max(+ MIN_MAX_IMAGE_SIZE_MB,+ Math.min(MAX_MAX_IMAGE_SIZE_MB, Math.floor(num))+ )+}++type ImageAttachmentConfigState = {+ /**+ * Maximum size of a single image attachment, in MB. Images are sent inline+ * as base64 data URLs, so this is independent of the document limit+ * (`max_file_size_mb` in the RAG extension). Providers and models may+ * enforce a lower limit of their own.+ */+ maxImageSizeMB: number+ setMaxImageSizeMB: (value: number) => void+}++export const useImageAttachmentConfig = create<ImageAttachmentConfigState>()(+ persist(+ (set, get) => ({+ maxImageSizeMB: DEFAULT_MAX_IMAGE_SIZE_MB,+ setMaxImageSizeMB: (value) =>+ set({ maxImageSizeMB: clampImageSizeMB(value, get().maxImageSizeMB) }),+ }),+ {+ name: localStorageKey.settingImageAttachments,+ storage: createJSONStorage(() => backendStorage),+ skipHydration: true,+ // A hand-edited or corrupt record must not disable the limit.+ merge: (persisted, current) => ({+ ...current,+ maxImageSizeMB: clampImageSizeMB(+ (persisted as Partial<ImageAttachmentConfigState> | undefined)+ ?.maxImageSizeMB,+ current.maxImageSizeMB+ ),+ }),+ }+ )+)diff --git a/web-app/src/lib/hydrateStores.ts b/web-app/src/lib/hydrateStores.tsindex 3df02cb15..3b4178c38 100644--- a/web-app/src/lib/hydrateStores.ts+++ b/web-app/src/lib/hydrateStores.ts@@ -23,6 +23,7 @@ import { useWebSearchConfig } from '@/hooks/useWebSearchConfig'import { useCoworkSessions } from '@/hooks/useCoworkSessions'import { useCoworkConfig } from '@/hooks/useCoworkConfig'import { useCoTDuration } from '@/hooks/useCoTDuration'+import { useImageAttachmentConfig } from '@/hooks/useImageAttachmentConfig'/*** Stores persisted through `backendStorage` set `skipHydration: true` so they@@ -57,6 +58,7 @@ const secondaryStores = [useCoworkSessions,useCoworkConfig,useCoTDuration,+ useImageAttachmentConfig,] as constexport async function hydrateBackendStores(): Promise<void> {diff --git a/web-app/src/locales/en/settings.json b/web-app/src/locales/en/settings.jsonindex 8a06d65a1..d9e7d5c91 100644--- a/web-app/src/locales/en/settings.json+++ b/web-app/src/locales/en/settings.json@@ -357,8 +357,11 @@"autoInlineThreshold": "Auto inline threshold","autoInlineThresholdDesc": "Fraction of the model context used as the cutoff for inlining parsed files on local models.","limitsTitle": "Limits",- "maxFile": "Max File Size (MB)",- "maxFileDesc": "Maximum size per file. Enforced at upload and processing time.",+ "maxFile": "Max Document Size (MB)",+ "maxFileDisabledReason": "Turn on Enable Attachments to change the document size limit.",+ "maxFileDesc": "Maximum size per document. Enforced at upload and processing time. Images have their own limit above.",+ "maxImage": "Max Image Size (MB)",+ "maxImageDesc": "Maximum size per image (JPEG or PNG). Your provider or model may enforce a lower limit.","retrievalTitle": "Retrieval","topK": "Top-K","topKDesc": "Maximum citations to return.",diff --git a/web-app/src/routes/settings/__tests__/attachments.test.tsx b/web-app/src/routes/settings/__tests__/attachments.test.tsxnew file mode 100644index 000000000..386acd710--- /dev/null+++ b/web-app/src/routes/settings/__tests__/attachments.test.tsx@@ -0,0 +1,190 @@+import '@testing-library/jest-dom/vitest'+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++vi.mock('@tanstack/react-router', () => ({+ createFileRoute: () => (options: unknown) => options,+}))+vi.mock('@/i18n/react-i18next-compat', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}))+vi.mock('@/containers/SettingsMenu', () => ({ default: () => null }))+vi.mock('@/containers/HeaderPage', () => ({+ default: ({ children }: any) => <div>{children}</div>,+}))+vi.mock('@/lib/backendStorage', () => ({+ backendStorage: {+ getItem: async () => null,+ setItem: async () => {},+ removeItem: async () => {},+ },+}))+vi.mock('@/lib/extension', () => ({+ ExtensionManager: { getInstance: () => ({ get: () => undefined }) },+}))+vi.mock('@janhq/core', () => ({ ExtensionTypeEnum: { RAG: 'rag' } }))+// Simple number input so the test can drive onChange directly.+vi.mock('@/containers/dynamicControllerSetting', () => ({+ DynamicControllerSetting: ({+ controllerProps,+ disabledReason,+ onChange,+ }: any) => (+ <input+ data-testid={`ctl-${controllerProps.max}`}+ data-disabled-reason={disabledReason}+ value={controllerProps.value}+ onChange={(e) => onChange(e.target.value)}+ />+ ),+}))++import { Route } from '../attachments'+import { useImageAttachmentConfig } from '@/hooks/useImageAttachmentConfig'+import { useAttachments } from '@/hooks/useAttachments'++const Page = (Route as unknown as { component: () => JSX.Element }).component++describe('Attachments settings: image size', () => {+ beforeEach(() => {+ vi.useFakeTimers()+ useImageAttachmentConfig.setState({ maxImageSizeMB: 10 })+ useAttachments.setState({+ settingsDefs: [+ {+ key: 'max_file_size_mb',+ titleKey: 'settings:attachments.maxFile',+ descriptionKey: 'settings:attachments.maxFileDesc',+ controllerType: 'input',+ controllerProps: { value: 100, type: 'number', min: 1, max: 200 },+ } as any,+ ],+ maxFileSizeMB: 100,+ enabled: true,+ })+ })++ afterEach(() => {+ cleanup()+ vi.useRealTimers()+ })++ it('shows the document and image limits as separate settings with the provider note', () => {+ render(<Page />)+ expect(+ screen.getByText('settings:attachments.maxFile')+ ).toBeInTheDocument()+ expect(+ screen.getByText('settings:attachments.maxImage')+ ).toBeInTheDocument()+ expect(+ screen.getByText('settings:attachments.maxImageDesc')+ ).toBeInTheDocument()+ expect(screen.getByTestId('ctl-100')).toHaveValue('10')+ expect(screen.getByTestId('ctl-200')).toHaveValue('100')+ })++ it('saves an image limit change without touching the document limit', () => {+ render(<Page />)+ fireEvent.change(screen.getByTestId('ctl-100'), { target: { value: '30' } })+ act(() => {+ vi.advanceTimersByTime(600)+ })+ expect(useImageAttachmentConfig.getState().maxImageSizeMB).toBe(30)+ expect(useAttachments.getState().maxFileSizeMB).toBe(100)+ })++ it.each([+ ['25', 25],+ ['999', 100],+ ['invalid', 10],+ ])('saves %s when leaving before the debounce expires', (value, expected) => {+ const page = render(<Page />)+ fireEvent.change(screen.getByTestId('ctl-100'), { target: { value: '20' } })+ act(() => {+ vi.advanceTimersByTime(100)+ })+ fireEvent.change(screen.getByTestId('ctl-100'), { target: { value } })+ expect(useImageAttachmentConfig.getState().maxImageSizeMB).toBe(10)++ page.unmount()++ expect(useImageAttachmentConfig.getState().maxImageSizeMB).toBe(expected)+ expect(useAttachments.getState().maxFileSizeMB).toBe(100)+ // An older scheduled edit must not overwrite the last value later.+ act(() => {+ vi.advanceTimersByTime(600)+ })+ expect(useImageAttachmentConfig.getState().maxImageSizeMB).toBe(expected)+ render(<Page />)+ expect(screen.getByTestId('ctl-100')).toHaveValue(String(expected))+ })++ it('clamps an out-of-range image limit to 100', () => {+ render(<Page />)+ fireEvent.change(screen.getByTestId('ctl-100'), { target: { value: '999' } })+ act(() => {+ vi.advanceTimersByTime(600)+ })+ expect(useImageAttachmentConfig.getState().maxImageSizeMB).toBe(100)+ })++ it('lists the image limit before the document limit', () => {+ render(<Page />)+ const image = screen.getByTestId('ctl-100')+ const document = screen.getByTestId('ctl-200')+ expect(+ image.compareDocumentPosition(document) &+ Node.DOCUMENT_POSITION_FOLLOWING+ ).toBeTruthy()+ })++ // The toggle governs documents only: images never check it, so only the+ // document limit is greyed out while it is off.+ it('disables only the document limit while attachments are off', () => {+ useAttachments.setState({ enabled: false })+ render(<Page />)+ expect(screen.getByTestId('ctl-200')).toHaveAttribute(+ 'data-disabled-reason',+ 'settings:attachments.maxFileDisabledReason'+ )+ expect(screen.getByTestId('ctl-100')).not.toHaveAttribute(+ 'data-disabled-reason'+ )+ })++ it('leaves both limits editable while attachments are on', () => {+ render(<Page />)+ expect(screen.getByTestId('ctl-200')).not.toHaveAttribute(+ 'data-disabled-reason'+ )+ expect(screen.getByTestId('ctl-100')).not.toHaveAttribute(+ 'data-disabled-reason'+ )+ })++ // pointer-events-none alone leaves a control reachable by keyboard, so the+ // document limit must be inert, not just styled, while attachments are off.+ it('makes only the document limit inert while attachments are off', () => {+ useAttachments.setState({ enabled: false })+ render(<Page />)+ expect(screen.getByTestId('ctl-200').closest('[inert]')).not.toBeNull()+ expect(screen.getByTestId('ctl-100').closest('[inert]')).toBeNull()+ })++ it('keeps both limits out of an inert subtree while attachments are on', () => {+ render(<Page />)+ expect(screen.getByTestId('ctl-200').closest('[inert]')).toBeNull()+ expect(screen.getByTestId('ctl-100').closest('[inert]')).toBeNull()+ })++ it('shows the reason as a tooltip on an element that still gets hover', () => {+ useAttachments.setState({ enabled: false })+ render(<Page />)+ const holder = screen+ .getByTestId('ctl-200')+ .closest('[title="settings:attachments.maxFileDisabledReason"]')+ expect(holder).not.toBeNull()+ expect(holder?.hasAttribute('inert')).toBe(false)+ })+})diff --git a/web-app/src/routes/settings/attachments.tsx b/web-app/src/routes/settings/attachments.tsxindex 0f6567f97..44fe109db 100644--- a/web-app/src/routes/settings/attachments.tsx+++ b/web-app/src/routes/settings/attachments.tsx@@ -8,6 +8,12 @@ import { useTranslation } from '@/i18n/react-i18next-compat'import { DynamicControllerSetting } from '@/containers/dynamicControllerSetting'import { useEffect, useState, useCallback, useRef } from 'react'import { useShallow } from 'zustand/react/shallow'+import {+ useImageAttachmentConfig,+ clampImageSizeMB,+ MIN_MAX_IMAGE_SIZE_MB,+ MAX_MAX_IMAGE_SIZE_MB,+} from '@/hooks/useImageAttachmentConfig'export const Route = createFileRoute('/settings/attachments')({component: AttachmentsSettings,@@ -41,6 +47,62 @@ function clampValue(return Math.max(min, Math.min(max, adjusted))}+// Image size limit lives outside the RAG extension (images are sent inline as+// base64, not retrieved), so it is rendered separately from the extension defs.+function ImageSizeSetting() {+ const { t } = useTranslation()+ const maxImageSizeMB = useImageAttachmentConfig((s) => s.maxImageSizeMB)+ const setMaxImageSizeMB = useImageAttachmentConfig((s) => s.setMaxImageSizeMB)+ const [local, setLocal] = useState<string | number | null>(null)+ const timerRef = useRef<ReturnType<typeof setTimeout>>(undefined)+ const pendingValueRef = useRef<number | undefined>(undefined)++ useEffect(+ () => () => {+ clearTimeout(timerRef.current)+ // Navigation can unmount this row before the debounce fires. Save the+ // latest edit without updating local state on the unmounted component.+ if (pendingValueRef.current !== undefined) {+ setMaxImageSizeMB(pendingValueRef.current)+ pendingValueRef.current = undefined+ }+ },+ [setMaxImageSizeMB]+ )++ const onChange = (val: unknown) => {+ clearTimeout(timerRef.current)+ setLocal(val as string | number)+ const validated = clampImageSizeMB(val, maxImageSizeMB)+ pendingValueRef.current = validated+ timerRef.current = setTimeout(() => {+ pendingValueRef.current = undefined+ setMaxImageSizeMB(validated)+ setLocal(validated)+ }, 500)+ }++ return (+ <CardItem+ title={t('settings:attachments.maxImage')}+ description={t('settings:attachments.maxImageDesc')}+ actions={+ <DynamicControllerSetting+ controllerType="input"+ controllerProps={{+ value: local ?? maxImageSizeMB,+ type: 'number',+ min: MIN_MAX_IMAGE_SIZE_MB,+ max: MAX_MAX_IMAGE_SIZE_MB,+ step: 1,+ }}+ onChange={onChange}+ />+ }+ />+ )+}+function AttachmentsSettings() {const { t } = useTranslation()const hookDefs = useAttachments((s) => s.settingsDefs)@@ -175,6 +237,106 @@ function AttachmentsSettings() {[sel])+ const renderDef = (d: SettingComponentProps) => {+ // The toggle governs documents only (images never check it), so only the+ // document size limit is greyed out while it is off.+ const disabledReason =+ d.key === 'max_file_size_mb' && !sel.enabled+ ? t('settings:attachments.maxFileDisabledReason')+ : undefined++ // Use local value if typing, else use store value+ const storeValue = (() => {+ switch (d.key) {+ case 'enabled':+ return sel.enabled+ case 'max_file_size_mb':+ return sel.maxFileSizeMB+ case 'retrieval_limit':+ return sel.retrievalLimit+ case 'retrieval_threshold':+ return sel.retrievalThreshold+ case 'chunk_size_chars':+ return sel.chunkSizeChars+ case 'overlap_chars':+ return sel.overlapChars+ case 'search_mode':+ return sel.searchMode+ case 'parse_mode':+ return sel.parseMode+ case 'auto_inline_context_ratio':+ return sel.autoInlineContextRatio+ default:+ return d?.controllerProps?.value+ }+ })()++ const currentValue =+ localValues[d.key] !== undefined+ ? localValues[d.key]+ : storeValue++ // Convert to DynamicControllerSetting compatible props+ const baseProps = d.controllerProps+ const normalizedValue: string | number | boolean = (() => {+ if (Array.isArray(currentValue)) {+ return currentValue.join(',')+ }+ return currentValue as string | number | boolean+ })()++ const props = {+ value: normalizedValue,+ placeholder:+ 'placeholder' in baseProps+ ? baseProps.placeholder+ : undefined,+ type: 'type' in baseProps ? baseProps.type : undefined,+ options:+ 'options' in baseProps ? baseProps.options : undefined,+ input_actions:+ 'inputActions' in baseProps+ ? baseProps.inputActions+ : undefined,+ rows: undefined,+ min: 'min' in baseProps ? baseProps.min : undefined,+ max: 'max' in baseProps ? baseProps.max : undefined,+ step: 'step' in baseProps ? baseProps.step : undefined,+ recommended:+ 'recommended' in baseProps+ ? baseProps.recommended+ : undefined,+ }++ const title = d.titleKey ? t(d.titleKey) : d.title+ const description = d.descriptionKey+ ? t(d.descriptionKey)+ : d.description++ return (+ <CardItem+ key={d.key}+ title={title}+ description={description}+ actions={+ // `inert` takes the control out of the tab order and ignores key+ // presses, which the shared wrapper's pointer-events-none does not.+ // The tooltip sits on an outer element so it still receives hover.+ <div title={disabledReason}>+ <div inert={disabledReason ? true : undefined}>+ <DynamicControllerSetting+ controllerType={d.controllerType}+ controllerProps={props}+ disabledReason={disabledReason}+ onChange={(val) => debouncedSet(d.key, val, d)}+ />+ </div>+ </div>+ }+ />+ )+ }+return (<div className="flex flex-col h-svh w-full"><HeaderPage>@@ -187,90 +349,11 @@ function AttachmentsSettings() {<div className="p-4 pt-0 w-full overflow-y-auto"><div className="flex flex-col justify-between gap-4 gap-y-3 w-full"><Card title={t('common:attachments') || 'Attachments'}>- {defs.map((d) => {- // Use local value if typing, else use store value- const storeValue = (() => {- switch (d.key) {- case 'enabled':- return sel.enabled- case 'max_file_size_mb':- return sel.maxFileSizeMB- case 'retrieval_limit':- return sel.retrievalLimit- case 'retrieval_threshold':- return sel.retrievalThreshold- case 'chunk_size_chars':- return sel.chunkSizeChars- case 'overlap_chars':- return sel.overlapChars- case 'search_mode':- return sel.searchMode- case 'parse_mode':- return sel.parseMode- case 'auto_inline_context_ratio':- return sel.autoInlineContextRatio- default:- return d?.controllerProps?.value- }- })()-- const currentValue =- localValues[d.key] !== undefined- ? localValues[d.key]- : storeValue-- // Convert to DynamicControllerSetting compatible props- const baseProps = d.controllerProps- const normalizedValue: string | number | boolean = (() => {- if (Array.isArray(currentValue)) {- return currentValue.join(',')- }- return currentValue as string | number | boolean- })()-- const props = {- value: normalizedValue,- placeholder:- 'placeholder' in baseProps- ? baseProps.placeholder- : undefined,- type: 'type' in baseProps ? baseProps.type : undefined,- options:- 'options' in baseProps ? baseProps.options : undefined,- input_actions:- 'inputActions' in baseProps- ? baseProps.inputActions- : undefined,- rows: undefined,- min: 'min' in baseProps ? baseProps.min : undefined,- max: 'max' in baseProps ? baseProps.max : undefined,- step: 'step' in baseProps ? baseProps.step : undefined,- recommended:- 'recommended' in baseProps- ? baseProps.recommended- : undefined,- }-- const title = d.titleKey ? t(d.titleKey) : d.title- const description = d.descriptionKey- ? t(d.descriptionKey)- : d.description-- return (- <CardItem- key={d.key}- title={title}- description={description}- actions={- <DynamicControllerSetting- controllerType={d.controllerType}- controllerProps={props}- onChange={(val) => debouncedSet(d.key, val, d)}- />- }- />- )- })}+ {defs.filter((d) => d.key !== 'max_file_size_mb').map(renderDef)}+ </Card>+ <Card title={t('settings:attachments.limitsTitle')}>+ <ImageSizeSetting />+ {defs.filter((d) => d.key === 'max_file_size_mb').map(renderDef)}</Card></div></div>