Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix(web-app): cloud output cap, truncated/empty replies, and spreadsheet attachments (#9230)

Akarshan Biswas063ebc9e6fc3
diff --git a/src-tauri/plugins/tauri-plugin-rag/src/parser.rs b/src-tauri/plugins/tauri-plugin-rag/src/parser.rs
index 330c30827..4bc543fc8 100644
--- a/src-tauri/plugins/tauri-plugin-rag/src/parser.rs
+++ b/src-tauri/plugins/tauri-plugin-rag/src/parser.rs
@@ -210,13 +210,105 @@ fn parse_csv(file_path: &str) -> Result<String, RagError> {
.flexible(true)
.from_path(file_path)
.map_err(|e| RagError::ParseError(e.to_string()))?;
- let mut out = String::new();
+ // Re-serialise through the csv writer so a cell holding the delimiter, a
+ // quote or a newline stays one cell instead of shifting the columns after it.
+ let mut wtr = csv_crate::WriterBuilder::new()
+ .flexible(true)
+ .from_writer(Vec::new());
for rec in rdr.records() {
let rec = rec.map_err(|e| RagError::ParseError(e.to_string()))?;
- out.push_str(&rec.iter().collect::<Vec<_>>().join(", "));
- out.push('\n');
+ wtr.write_record(&rec)
+ .map_err(|e| RagError::ParseError(e.to_string()))?;
+ }
+ let bytes = wtr
+ .into_inner()
+ .map_err(|e| RagError::ParseError(e.to_string()))?;
+ Ok(String::from_utf8_lossy(&bytes).into_owned())
+}
+
+const SECS_PER_DAY: i64 = 86_400;
+
+/// Largest serial Excel accepts (9999-12-31); anything past it is not a date.
+const MAX_EXCEL_SERIAL: f64 = 2_958_466.0;
+
+/// Renders a cell for the model. Date cells arrive as Excel serial numbers,
+/// which a model cannot read as dates, so they become ISO 8601 text.
+fn format_cell(cell: &DataType) -> String {
+ match cell {
+ DataType::DateTime(serial) => excel_serial_to_iso(*serial),
+ DataType::Duration(days) => excel_duration(*days),
+ other => other.to_string(),
}
- Ok(out)
+}
+
+/// Converts a 1900-system serial. calamine 0.23 already shifts 1904-system
+/// workbooks onto this system (`format_excel_f64_ref` adds 1462 days when
+/// xlsx `date1904`, xls record 0x0022 or the xlsb flag is set), and ods dates
+/// arrive as `DateTimeIso`, so no epoch detection is needed here.
+fn excel_serial_to_iso(serial: f64) -> String {
+ if !serial.is_finite() || !(0.0..MAX_EXCEL_SERIAL).contains(&serial) {
+ return serial.to_string();
+ }
+ let total_secs = (serial * SECS_PER_DAY as f64).round() as i64;
+ let serial_days = total_secs.div_euclid(SECS_PER_DAY);
+ let secs_of_day = total_secs.rem_euclid(SECS_PER_DAY);
+ let time = format!(
+ "{:02}:{:02}:{:02}",
+ secs_of_day / 3600,
+ secs_of_day % 3600 / 60,
+ secs_of_day % 60
+ );
+ // Serial 0 is Excel's "1900-01-00": the cell holds only a time of day.
+ if serial_days == 0 {
+ return time;
+ }
+ // Serial 60 is the 1900-02-29 Excel shows but no calendar has; spell it
+ // out so it does not collide with serial 59.
+ let date = if serial_days == 60 {
+ "1900-02-29".to_string()
+ } else {
+ excel_days_to_iso(serial_days)
+ };
+ if secs_of_day == 0 {
+ date
+ } else {
+ format!("{}T{}", date, time)
+ }
+}
+
+fn excel_days_to_iso(serial_days: i64) -> String {
+ // Excel counts a 1900-02-29 that never existed (serial 60), so serials
+ // before it are one day behind the 1899-12-30 epoch used for later ones.
+ let days_since_epoch = if serial_days < 60 { serial_days + 1 } else { serial_days };
+ // 1899-12-30 is 25569 days before 1970-01-01.
+ let (y, m, d) = civil_from_days(days_since_epoch - 25_569);
+ format!("{:04}-{:02}-{:02}", y, m, d)
+}
+
+/// Renders an Excel duration (fractional days) as elapsed `[h]:mm:ss`.
+fn excel_duration(days: f64) -> String {
+ if !days.is_finite() || days.abs() >= MAX_EXCEL_SERIAL {
+ return days.to_string();
+ }
+ let total_secs = (days * SECS_PER_DAY as f64).round() as i64;
+ let sign = if total_secs < 0 { "-" } else { "" };
+ let secs = total_secs.abs();
+ format!("{}{}:{:02}:{:02}", sign, secs / 3600, secs % 3600 / 60, secs % 60)
+}
+
+/// Proleptic Gregorian date for a day count relative to 1970-01-01
+/// (Howard Hinnant's civil_from_days), avoiding a date-library dependency.
+fn civil_from_days(z: i64) -> (i64, i64, i64) {
+ let z = z + 719_468;
+ let era = z.div_euclid(146_097);
+ let doe = z.rem_euclid(146_097);
+ let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
+ let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
+ let mp = (5 * doy + 2) / 153;
+ let d = doy - (153 * mp + 2) / 5 + 1;
+ let m = if mp < 10 { mp + 3 } else { mp - 9 };
+ let y = yoe + era * 400 + i64::from(m <= 2);
+ (y, m, d)
}
fn parse_spreadsheet(file_path: &str) -> Result<String, RagError> {
@@ -233,15 +325,7 @@ fn parse_spreadsheet(file_path: &str) -> Result<String, RagError> {
for row in range.rows() {
let cells = row
.iter()
- .map(|c| match c {
- DataType::Empty => "".to_string(),
- DataType::String(s) => s.to_string(),
- DataType::Float(f) => format!("{}", f),
- DataType::Int(i) => i.to_string(),
- DataType::Bool(b) => b.to_string(),
- DataType::DateTime(f) => format!("{}", f),
- other => other.to_string(),
- })
+ .map(format_cell)
.collect::<Vec<_>>()
.join("\t");
out.push_str(&cells);
@@ -349,3 +433,76 @@ fn read_text_auto(file_path: &str) -> Result<String, RagError> {
Ok(decoded.to_string())
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn date_only_serial_renders_as_iso_date() {
+ assert_eq!(format_cell(&DataType::DateTime(45123.0)), "2023-07-16");
+ }
+
+ #[test]
+ fn serial_with_time_renders_as_iso_datetime() {
+ assert_eq!(format_cell(&DataType::DateTime(45123.5)), "2023-07-16T12:00:00");
+ }
+
+ #[test]
+ fn time_only_serial_renders_as_time() {
+ assert_eq!(format_cell(&DataType::DateTime(0.75)), "18:00:00");
+ }
+
+ #[test]
+ fn serials_before_the_phantom_leap_day_are_not_shifted() {
+ assert_eq!(format_cell(&DataType::DateTime(1.0)), "1900-01-01");
+ assert_eq!(format_cell(&DataType::DateTime(59.0)), "1900-02-28");
+ assert_eq!(format_cell(&DataType::DateTime(61.0)), "1900-03-01");
+ }
+
+ #[test]
+ fn phantom_leap_day_renders_as_excel_shows_it() {
+ // Excel displays serial 60 as 1900-02-29; collapsing it onto 02-28
+ // would make two different cells read as the same date.
+ assert_eq!(format_cell(&DataType::DateTime(60.0)), "1900-02-29");
+ }
+
+ #[test]
+ fn seconds_round_instead_of_truncating() {
+ // 10:00:00 as a float is slightly below the exact value.
+ assert_eq!(
+ format_cell(&DataType::DateTime(44927.0 + 10.0 / 24.0)),
+ "2023-01-01T10:00:00"
+ );
+ }
+
+ #[test]
+ fn durations_render_as_elapsed_time() {
+ assert_eq!(format_cell(&DataType::Duration(1.5)), "36:00:00");
+ }
+
+ #[test]
+ fn iso_variants_pass_through() {
+ assert_eq!(
+ format_cell(&DataType::DateTimeIso("2024-02-29T08:15:00".into())),
+ "2024-02-29T08:15:00"
+ );
+ assert_eq!(format_cell(&DataType::DurationIso("PT1H".into())), "PT1H");
+ }
+
+ #[test]
+ fn csv_cells_with_delimiters_quotes_or_newlines_are_quoted() {
+ let path = std::env::temp_dir().join(format!(
+ "jan-rag-parse-csv-{}.csv",
+ std::process::id()
+ ));
+ fs::write(&path, "name,note\n\"Doe, Jane\",\"say \"\"hi\"\"\nthere\"\nplain,x\n")
+ .unwrap();
+ let out = parse_csv(path.to_str().unwrap());
+ let _ = fs::remove_file(&path);
+ assert_eq!(
+ out.unwrap(),
+ "name,note\n\"Doe, Jane\",\"say \"\"hi\"\"\nthere\"\nplain,x\n"
+ );
+ }
+}
diff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsx
index 58b63085c..cd2ef3f9a 100644
--- a/web-app/src/containers/ChatInput.tsx
+++ b/web-app/src/containers/ChatInput.tsx
@@ -101,6 +101,11 @@ import {
createAudioAttachment,
createVideoAttachment,
} from '@/types/attachment'
+import {
+ needsIngestionChoice,
+ resolveAutoInlineBudget,
+} from '@/lib/attachmentProcessing'
+import { activePathTokens } from '@/lib/message-branching'
import JanBrowserExtensionDialog from '@/containers/dialogs/JanBrowserExtensionDialog'
import { useJanBrowserExtension } from '@/hooks/useJanBrowserExtension'
import { useAgentMode } from '@/hooks/useAgentMode'
@@ -460,8 +465,12 @@ const ChatInput = memo(function ChatInput({
)
)
+ // Read when a document is attached, without rebuilding the attach
+ // callback on every message update.
+ const threadMessagesRef = useRef(threadMessages)
+ threadMessagesRef.current = threadMessages
+
const maxRows = 10
- const ATTACHMENT_AUTO_INLINE_FALLBACK_BYTES = 512 * 1024
const selectedModel = useModelProvider((state) => state.selectedModel)
const selectedProvider = useModelProvider((state) => state.selectedProvider)
@@ -532,6 +541,9 @@ const ChatInput = memo(function ChatInput({
const attachmentsEnabled = useAttachments((s) => s.enabled)
const parsePreference = useAttachments((s) => s.parseMode)
+ const autoInlineContextRatio = useAttachments(
+ (s) => s.autoInlineContextRatio
+ )
const maxFileSizeMB = useAttachments((s) => s.maxFileSizeMB)
// Derived: any document currently processing (ingestion in progress)
@@ -884,12 +896,27 @@ const ChatInput = memo(function ChatInput({
// Only collect the user's inline-vs-embeddings preference via the
// dialog. Actual ingestion is always deferred to send time
- // (processAttachmentsForSend inside processAndSendMessage).
- const docsNeedingPrompt = docs.filter((doc) => {
- if (doc.processed || doc.injectionMode) return false
- const preference = doc.parseMode ?? parsePreference
- return preference === 'prompt' || preference === 'auto'
- })
+ // (processAttachmentsForSend inside processAndSendMessage), where
+ // 'auto' documents are routed by size when the model's window is known.
+ // Same conversation-aware budget as the send path (the active branch,
+ // which is what gets sent), so 'auto' asks here exactly when send time
+ // would have no budget to decide by.
+ const hasInlineBudget =
+ (await resolveAutoInlineBudget(
+ selectedModel,
+ selectedProvider,
+ autoInlineContextRatio,
+ activePathTokens(
+ threadMessagesRef.current,
+ (
+ useThreads.getState().threads[currentThreadId ?? '']
+ ?.metadata as Record<string, unknown> | undefined
+ )?.activeRootId as string | undefined
+ )
+ )) !== undefined
+ const docsNeedingPrompt = docs.filter((doc) =>
+ needsIngestionChoice(doc, parsePreference, hasInlineBudget)
+ )
if (docsNeedingPrompt.length > 0) {
const choices = new Map<string, 'inline' | 'embeddings'>()
@@ -897,12 +924,7 @@ const ChatInput = memo(function ChatInput({
const doc = docsNeedingPrompt[i]
const choice = await useAttachmentIngestionPrompt
.getState()
- .showPrompt(
- doc,
- ATTACHMENT_AUTO_INLINE_FALLBACK_BYTES,
- i,
- docsNeedingPrompt.length
- )
+ .showPrompt(doc, i, docsNeedingPrompt.length)
if (!choice) {
// User cancelled — remove all pending docs
@@ -935,9 +957,12 @@ const ChatInput = memo(function ChatInput({
}
},
[
- ATTACHMENT_AUTO_INLINE_FALLBACK_BYTES,
attachmentsKey,
+ autoInlineContextRatio,
+ currentThreadId,
parsePreference,
+ selectedModel,
+ selectedProvider,
setAttachmentsForThread,
]
)
diff --git a/web-app/src/hooks/__tests__/useAttachmentIngestionPrompt.test.ts b/web-app/src/hooks/__tests__/useAttachmentIngestionPrompt.test.ts
index 6c6bf6e36..11e77a3cc 100644
--- a/web-app/src/hooks/__tests__/useAttachmentIngestionPrompt.test.ts
+++ b/web-app/src/hooks/__tests__/useAttachmentIngestionPrompt.test.ts
@@ -9,7 +9,6 @@ describe('useAttachmentIngestionPrompt', () => {
currentAttachment: null,
currentIndex: 0,
totalCount: 0,
- sizeThreshold: 0,
resolver: null,
})
})
@@ -26,14 +25,13 @@ describe('useAttachmentIngestionPrompt', () => {
// Don't await — it blocks until choose/cancel is called
const promise = useAttachmentIngestionPrompt
.getState()
- .showPrompt(attachment, 512_000, 0, 3)
+ .showPrompt(attachment, 0, 3)
const state = useAttachmentIngestionPrompt.getState()
expect(state.isModalOpen).toBe(true)
expect(state.currentAttachment).toEqual(attachment)
expect(state.currentIndex).toBe(0)
expect(state.totalCount).toBe(3)
- expect(state.sizeThreshold).toBe(512_000)
// Resolve it so the test doesn't hang
act(() => {
@@ -47,7 +45,7 @@ describe('useAttachmentIngestionPrompt', () => {
it('choose resolves the promise with the selected mode', async () => {
const promise = useAttachmentIngestionPrompt
.getState()
- .showPrompt({ name: 'doc.pdf', size: 100 }, 1000, 0, 1)
+ .showPrompt({ name: 'doc.pdf', size: 100 }, 0, 1)
act(() => {
useAttachmentIngestionPrompt.getState().choose('embeddings')
@@ -60,7 +58,7 @@ describe('useAttachmentIngestionPrompt', () => {
it('cancel resolves with undefined', async () => {
const promise = useAttachmentIngestionPrompt
.getState()
- .showPrompt({ name: 'doc.pdf', size: 100 }, 1000, 0, 1)
+ .showPrompt({ name: 'doc.pdf', size: 100 }, 0, 1)
act(() => {
useAttachmentIngestionPrompt.getState().cancel()
@@ -80,7 +78,7 @@ describe('useAttachmentIngestionPrompt', () => {
for (let i = 0; i < docs.length; i++) {
const promise = useAttachmentIngestionPrompt
.getState()
- .showPrompt(docs[i], 1000, i, docs.length)
+ .showPrompt(docs[i], i, docs.length)
expect(useAttachmentIngestionPrompt.getState().currentIndex).toBe(i)
expect(useAttachmentIngestionPrompt.getState().totalCount).toBe(
diff --git a/web-app/src/hooks/useAttachmentIngestionPrompt.ts b/web-app/src/hooks/useAttachmentIngestionPrompt.ts
index 669638126..618c36a38 100644
--- a/web-app/src/hooks/useAttachmentIngestionPrompt.ts
+++ b/web-app/src/hooks/useAttachmentIngestionPrompt.ts
@@ -8,11 +8,9 @@ type AttachmentIngestionState = {
currentAttachment: AttachmentSummary | null
currentIndex: number
totalCount: number
- sizeThreshold: number
resolver: ((choice: 'inline' | 'embeddings' | undefined) => void) | null
showPrompt: (
attachment: AttachmentSummary,
- sizeThreshold: number,
currentIndex: number,
totalCount: number
) => Promise<'inline' | 'embeddings' | undefined>
@@ -26,16 +24,14 @@ export const useAttachmentIngestionPrompt = create<AttachmentIngestionState>()(
currentAttachment: null,
currentIndex: 0,
totalCount: 0,
- sizeThreshold: 0,
resolver: null,
- showPrompt: async (attachment, sizeThreshold, currentIndex, totalCount) => {
+ showPrompt: async (attachment, currentIndex, totalCount) => {
return new Promise<'inline' | 'embeddings' | undefined>((resolve) => {
set({
isModalOpen: true,
currentAttachment: attachment,
currentIndex,
totalCount,
- sizeThreshold,
resolver: resolve,
})
})
diff --git a/web-app/src/lib/__tests__/attachmentProcessing.coverage.test.ts b/web-app/src/lib/__tests__/attachmentProcessing.coverage.test.ts
index e83e67fab..88db7ee9a 100644
--- a/web-app/src/lib/__tests__/attachmentProcessing.coverage.test.ts
+++ b/web-app/src/lib/__tests__/attachmentProcessing.coverage.test.ts
@@ -66,8 +66,8 @@ describe('processAttachmentsForSend - additional coverage', () => {
threadId,
serviceHub: hub as any,
parsePreference: 'auto',
- contextThreshold: 100,
- estimateTokens: vi.fn().mockResolvedValue(200),
+ // 'parsed text' is 4 estimated tokens.
+ contextThreshold: 3,
})
expect(result.processedAttachments[0].injectionMode).toBe('embeddings')
})
@@ -79,48 +79,52 @@ describe('processAttachmentsForSend - additional coverage', () => {
threadId,
serviceHub: hub as any,
parsePreference: 'auto',
- contextThreshold: 500,
- estimateTokens: vi.fn().mockResolvedValue(50),
+ contextThreshold: 4,
})
expect(result.processedAttachments[0].injectionMode).toBe('inline')
})
- it('auto mode without estimateTokens defaults to autoFallbackMode', async () => {
+ it('auto mode spends one budget across all documents in a send', async () => {
+ // Each 'parsed text' is 4 estimated tokens: two fit alone, not together.
const hub = createMockServiceHub()
const result = await processAttachmentsForSend({
- attachments: [{ name: 'doc.txt', type: 'document' as const, path: '/doc.txt' }],
+ attachments: [
+ { name: 'a.txt', type: 'document' as const, path: '/a.txt' },
+ { name: 'b.txt', type: 'document' as const, path: '/b.txt' },
+ ],
threadId,
serviceHub: hub as any,
parsePreference: 'auto',
- autoFallbackMode: 'inline',
+ contextThreshold: 6,
})
- // Without estimateTokens, uses autoFallbackMode
- expect(result.processedAttachments[0].injectionMode).toBe('inline')
+ expect(result.processedAttachments.map((a) => a.injectionMode)).toEqual([
+ 'inline',
+ 'embeddings',
+ ])
})
- it('prompt mode uses perFileChoices', async () => {
- const hub = createMockServiceHub()
- const choices = new Map([[ '/doc.txt', 'inline' as const ]])
+ it('auto mode without a context budget embeds without parsing', async () => {
+ const parseDocument = vi.fn().mockResolvedValue('parsed text')
+ const hub = { ...createMockServiceHub(), rag: () => ({ parseDocument }) }
const result = await processAttachmentsForSend({
attachments: [{ name: 'doc.txt', type: 'document' as const, path: '/doc.txt' }],
threadId,
serviceHub: hub as any,
- parsePreference: 'prompt',
- perFileChoices: choices,
+ parsePreference: 'auto',
})
- expect(result.processedAttachments[0].injectionMode).toBe('inline')
+ expect(result.processedAttachments[0].injectionMode).toBe('embeddings')
+ expect(parseDocument).not.toHaveBeenCalled()
})
- it('prompt mode defaults to autoFallbackMode when no perFileChoice', async () => {
+ it('prompt mode without a recorded choice falls back to embeddings', async () => {
const hub = createMockServiceHub()
const result = await processAttachmentsForSend({
attachments: [{ name: 'doc.txt', type: 'document' as const, path: '/doc.txt' }],
threadId,
serviceHub: hub as any,
parsePreference: 'prompt',
- autoFallbackMode: 'inline',
})
- expect(result.processedAttachments[0].injectionMode).toBe('inline')
+ expect(result.processedAttachments[0].injectionMode).toBe('embeddings')
})
it('skips already-processed inline documents', async () => {
@@ -145,26 +149,11 @@ describe('processAttachmentsForSend - additional coverage', () => {
serviceHub: hub as any,
parsePreference: 'auto',
contextThreshold: NaN,
- estimateTokens: vi.fn().mockResolvedValue(50),
})
// NaN threshold means no threshold -> defaults to embeddings
expect(result.processedAttachments[0].injectionMode).toBe('embeddings')
})
- it('handles non-positive token estimate', async () => {
- const hub = createMockServiceHub()
- const result = await processAttachmentsForSend({
- attachments: [{ name: 'doc.txt', type: 'document' as const, path: '/doc.txt' }],
- threadId,
- serviceHub: hub as any,
- parsePreference: 'auto',
- contextThreshold: 500,
- estimateTokens: vi.fn().mockResolvedValue(-1),
- })
- // Non-positive estimate -> defaults to embeddings
- expect(result.processedAttachments[0].injectionMode).toBe('embeddings')
- })
-
it('handles error as array', async () => {
const hub = {
uploads: () => ({
@@ -293,7 +282,7 @@ describe('processAttachmentsForSend - additional coverage', () => {
threadId,
serviceHub: hub as any,
parsePreference: 'auto',
- estimateTokens: vi.fn().mockResolvedValue(50),
+ contextThreshold: 500,
})
expect(result.processedAttachments[0].injectionMode).toBe('embeddings')
})
diff --git a/web-app/src/lib/__tests__/attachmentProcessing.test.ts b/web-app/src/lib/__tests__/attachmentProcessing.test.ts
index 24e8dc029..7174b2f2f 100644
--- a/web-app/src/lib/__tests__/attachmentProcessing.test.ts
+++ b/web-app/src/lib/__tests__/attachmentProcessing.test.ts
@@ -1,6 +1,8 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import {
+ needsIngestionChoice,
processAttachmentsForSend,
+ resolveAutoInlineBudget,
type AttachmentProcessingResult,
} from '../attachmentProcessing'
import type { Attachment } from '@/types/attachment'
@@ -24,6 +26,30 @@ const createMockServiceHub = (overrides: Record<string, unknown> = {}) => ({
}),
})
+const getModelPropsMock = vi.fn()
+let propsExtensionAvailable = true
+vi.mock('@/lib/llamacppRouterProps', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/lib/llamacppRouterProps')>()),
+ getLocalPropsExtension: (provider: string) =>
+ propsExtensionAvailable &&
+ (provider === 'llamacpp' || provider === 'mlx')
+ ? { getModelProps: getModelPropsMock }
+ : undefined,
+}))
+
+const modelWithCtx = (value: string | number): Model => ({
+ id: 'm1',
+ settings: {
+ ctx_len: {
+ key: 'ctx_len',
+ title: 'Context Size',
+ description: '',
+ controller_type: 'input',
+ controller_props: { value },
+ },
+ },
+})
+
const docAttachment = (overrides: Partial<Attachment> = {}): Attachment => ({
name: 'report.pdf',
type: 'document',
@@ -167,26 +193,6 @@ describe('processAttachmentsForSend', () => {
})
})
- describe('auto mode with perFileChoices', () => {
- it('respects per-file user choice for auto-mode documents', async () => {
- const hub = createMockServiceHub()
- const doc = docAttachment({ parseMode: 'auto' })
- const choices = new Map<string, 'inline' | 'embeddings'>([
- ['/tmp/report.pdf', 'inline'],
- ])
-
- const result = await processAttachmentsForSend({
- attachments: [doc],
- threadId,
- serviceHub: hub as any,
- parsePreference: 'auto',
- perFileChoices: choices,
- })
-
- expect(result.processedAttachments[0].injectionMode).toBe('inline')
- })
- })
-
describe('callbacks', () => {
it('calls updateAttachmentProcessing for each document', async () => {
const hub = createMockServiceHub()
@@ -252,4 +258,87 @@ describe('processAttachmentsForSend', () => {
expect(result.hasEmbeddedDocuments).toBe(true)
})
})
+
+ describe('resolveAutoInlineBudget', () => {
+ beforeEach(() => {
+ getModelPropsMock.mockReset()
+ propsExtensionAvailable = true
+ })
+
+ it('scales the configured ctx_len by the ratio', async () => {
+ await expect(
+ resolveAutoInlineBudget(modelWithCtx(8192), 'llamacpp', 0.75)
+ ).resolves.toBe(6144)
+ await expect(
+ resolveAutoInlineBudget(modelWithCtx('16384'), 'llamacpp', 0.5)
+ ).resolves.toBe(8192)
+ expect(getModelPropsMock).not.toHaveBeenCalled()
+ })
+
+ it('falls back to the launched window when ctx_len is left to auto-fit', async () => {
+ getModelPropsMock.mockResolvedValue({ nCtx: 4096 })
+ await expect(
+ resolveAutoInlineBudget(modelWithCtx(''), 'llamacpp', 0.75)
+ ).resolves.toBe(3072)
+ expect(getModelPropsMock).toHaveBeenCalledWith('m1')
+ })
+
+ it('leaves out what the conversation already uses', async () => {
+ await expect(
+ resolveAutoInlineBudget(modelWithCtx(8192), 'llamacpp', 0.75, 5000)
+ ).resolves.toBe(1144)
+ })
+
+ it('is undefined once the conversation has used up the budget', async () => {
+ await expect(
+ resolveAutoInlineBudget(modelWithCtx(8192), 'llamacpp', 0.75, 7000)
+ ).resolves.toBeUndefined()
+ })
+
+ it('is undefined when the local model is not loaded yet', async () => {
+ getModelPropsMock.mockRejectedValue(new Error('not loaded'))
+ await expect(
+ resolveAutoInlineBudget(modelWithCtx(''), 'llamacpp', 0.75)
+ ).resolves.toBeUndefined()
+ })
+
+ it('is undefined for cloud models, which report no context window', async () => {
+ await expect(
+ resolveAutoInlineBudget({ id: 'gpt' }, 'openai', 0.75)
+ ).resolves.toBeUndefined()
+ })
+
+ it('is undefined without a model or with a non-positive ratio', async () => {
+ await expect(
+ resolveAutoInlineBudget(undefined, 'llamacpp', 0.75)
+ ).resolves.toBeUndefined()
+ await expect(
+ resolveAutoInlineBudget(modelWithCtx(8192), 'llamacpp', 0)
+ ).resolves.toBeUndefined()
+ })
+ })
+
+ describe('needsIngestionChoice', () => {
+ it('asks in prompt mode regardless of the budget', () => {
+ expect(needsIngestionChoice(docAttachment(), 'prompt', true)).toBe(true)
+ })
+
+ it('decides auto mode by size when a budget is known', () => {
+ expect(needsIngestionChoice(docAttachment(), 'auto', true)).toBe(false)
+ })
+
+ it('asks in auto mode only when no budget is known', () => {
+ expect(needsIngestionChoice(docAttachment(), 'auto', false)).toBe(true)
+ })
+
+ it('never asks for explicit modes or already-routed documents', () => {
+ expect(needsIngestionChoice(docAttachment(), 'inline', false)).toBe(false)
+ expect(
+ needsIngestionChoice(docAttachment({ parseMode: 'embeddings' }), 'prompt', false)
+ ).toBe(false)
+ expect(
+ needsIngestionChoice(docAttachment({ injectionMode: 'inline' }), 'prompt', false)
+ ).toBe(false)
+ })
+ })
})
diff --git a/web-app/src/lib/__tests__/chatFinish.test.ts b/web-app/src/lib/__tests__/chatFinish.test.ts
new file mode 100644
index 000000000..e1abcc348
--- /dev/null
+++ b/web-app/src/lib/__tests__/chatFinish.test.ts
@@ -0,0 +1,133 @@
+import { describe, it, expect } from 'vitest'
+import type { UIMessage } from 'ai'
+import {
+ providerHasContextSetting,
+ isContextLimitStop,
+ isEmptyReply,
+ offersContextIncrease,
+} from '../chatFinish'
+
+const reply = (parts: UIMessage['parts']): UIMessage => ({
+ id: 'a1',
+ role: 'assistant',
+ parts,
+})
+
+describe('providerHasContextSetting', () => {
+ it('is true only for local engines that own a ctx_len setting', () => {
+ expect(providerHasContextSetting('llamacpp')).toBe(true)
+ expect(providerHasContextSetting('mlx')).toBe(true)
+ expect(providerHasContextSetting('anthropic')).toBe(false)
+ expect(providerHasContextSetting('openai')).toBe(false)
+ expect(providerHasContextSetting(undefined)).toBe(false)
+ })
+})
+
+describe('isContextLimitStop', () => {
+ const usage = { inputTokens: 30000, outputTokens: 1000 }
+
+ it('flags a llamacpp length stop near the configured ctx_len', () => {
+ expect(
+ isContextLimitStop({ provider: 'llamacpp', usage, ctxLen: 32768 })
+ ).toBe(true)
+ })
+
+ it('falls back to 32768 when a local model has no ctx_len', () => {
+ expect(
+ isContextLimitStop({ provider: 'mlx', usage, ctxLen: undefined })
+ ).toBe(true)
+ })
+
+ it('does not flag a local length stop far below ctx_len', () => {
+ expect(
+ isContextLimitStop({ provider: 'llamacpp', usage, ctxLen: 131072 })
+ ).toBe(false)
+ })
+
+ it('reads a string ctx_len the way the settings store keeps it', () => {
+ expect(
+ isContextLimitStop({ provider: 'llamacpp', usage, ctxLen: '131072' })
+ ).toBe(false)
+ })
+
+ it('uses the launched n_ctx when ctx_len is left to auto-fit', () => {
+ expect(
+ isContextLimitStop({
+ provider: 'llamacpp',
+ usage: { inputTokens: 3800, outputTokens: 200 },
+ ctxLen: '',
+ launchedCtxLen: 4096,
+ })
+ ).toBe(true)
+ })
+
+ it('never flags cloud providers, whose length stop is the output cap', () => {
+ expect(
+ isContextLimitStop({ provider: 'anthropic', usage, ctxLen: undefined })
+ ).toBe(false)
+ expect(
+ isContextLimitStop({ provider: 'openai', usage, ctxLen: 4096 })
+ ).toBe(false)
+ })
+})
+
+describe('isEmptyReply', () => {
+ const base = { isAbort: false, isError: false, finishReason: 'stop' }
+
+ it('is true for a finished assistant turn with no content', () => {
+ expect(isEmptyReply({ ...base, message: reply([]) })).toBe(true)
+ expect(
+ isEmptyReply({ ...base, message: reply([{ type: 'text', text: ' ' }]) })
+ ).toBe(true)
+ })
+
+ it('is false when the reply has text', () => {
+ expect(
+ isEmptyReply({ ...base, message: reply([{ type: 'text', text: 'hi' }]) })
+ ).toBe(false)
+ })
+
+ it('is false for aborted, errored and tool-call turns', () => {
+ const empty = reply([])
+ expect(isEmptyReply({ ...base, isAbort: true, message: empty })).toBe(false)
+ expect(isEmptyReply({ ...base, isError: true, message: empty })).toBe(false)
+ expect(
+ isEmptyReply({ ...base, finishReason: 'tool-calls', message: empty })
+ ).toBe(false)
+ })
+
+ it('is false for user messages', () => {
+ expect(
+ isEmptyReply({ ...base, message: { id: 'u', role: 'user', parts: [] } })
+ ).toBe(false)
+ })
+})
+
+describe('offersContextIncrease', () => {
+ const overflow = 'the request exceeds the available context size.'
+
+ it('offers the increase for local providers on a context error', () => {
+ expect(offersContextIncrease('llamacpp', overflow)).toBe(true)
+ expect(
+ offersContextIncrease(
+ 'mlx',
+ 'input length and `max_tokens` exceed context limit'
+ )
+ ).toBe(true)
+ })
+
+ it('never offers it for cloud providers, where ctx_len does nothing', () => {
+ expect(offersContextIncrease('anthropic', overflow)).toBe(false)
+ expect(
+ offersContextIncrease(
+ 'anthropic',
+ 'input length and `max_tokens` exceed context limit: 1 + 2 > 2'
+ )
+ ).toBe(false)
+ })
+
+ it('does not offer it for unrelated errors', () => {
+ expect(offersContextIncrease('llamacpp', 'connection refused')).toBe(false)
+ expect(offersContextIncrease('llamacpp', undefined)).toBe(false)
+ })
+})
diff --git a/web-app/src/lib/__tests__/context-manager.test.ts b/web-app/src/lib/__tests__/context-manager.test.ts
index 4318c1a48..6a75a1969 100644
--- a/web-app/src/lib/__tests__/context-manager.test.ts
+++ b/web-app/src/lib/__tests__/context-manager.test.ts
@@ -3,6 +3,7 @@ import type { UIMessage } from '@ai-sdk/react'
import {
estimateTokens,
estimateMessageTokens,
+ estimateConversationTokens,
trimMessages,
compactMessages,
deriveToolOutputCap,
@@ -39,6 +40,21 @@ describe('estimateTokens', () => {
})
})
+describe('estimateConversationTokens', () => {
+ it('sums every message, overhead included', () => {
+ const a = makeMessage('1', 'user', 'Hello world')
+ const b = makeMessage('2', 'assistant', 'Hi there')
+ expect(estimateConversationTokens([a, b])).toBe(
+ estimateMessageTokens(a) + estimateMessageTokens(b)
+ )
+ })
+
+ it('is 0 for an empty or missing conversation', () => {
+ expect(estimateConversationTokens([])).toBe(0)
+ expect(estimateConversationTokens(undefined)).toBe(0)
+ })
+})
+
describe('estimateMessageTokens', () => {
it('should estimate tokens for a simple text message', () => {
const msg = makeMessage('1', 'user', 'Hello world')
diff --git a/web-app/src/lib/__tests__/custom-chat-transport-prefix-stability.test.ts b/web-app/src/lib/__tests__/custom-chat-transport-prefix-stability.test.ts
index f26984fc3..897bf7516 100644
--- a/web-app/src/lib/__tests__/custom-chat-transport-prefix-stability.test.ts
+++ b/web-app/src/lib/__tests__/custom-chat-transport-prefix-stability.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it, vi, beforeEach } from 'vitest'
+import { describe, expect, it, vi, beforeEach, afterAll } from 'vitest'
import type { UIMessage } from '@ai-sdk/react'
import type * as ProviderCaps from '@/lib/providerCaps'
@@ -14,6 +14,7 @@ const h = vi.hoisted(() => ({
assistantParameters: null as Record<string, unknown> | null,
providerId: 'openai',
serviceHub: null as unknown,
+ predefinedRemote: false,
}))
const mcpService = {
@@ -125,7 +126,7 @@ vi.mock('@/lib/reasoningProviderOptions', () => ({
}))
vi.mock('@/lib/providerCaps', async (importOriginal) => ({
...(await importOriginal<typeof ProviderCaps>()),
- isPredefinedRemoteProvider: () => false,
+ isPredefinedRemoteProvider: () => h.predefinedRemote,
getProviderApiType: () => 'openai',
}))
vi.mock('../model-factory', () => ({
@@ -380,6 +381,42 @@ describe('CustomChatTransport assistant completion (continuation prefill)', () =
})
})
+// Anthropic falls back to the model's maximum max_tokens when no cap reaches
+// the SDK, and counts it against the context window (janhq/jan#9227).
+describe('CustomChatTransport output-token cap', () => {
+ beforeEach(() => {
+ streamTextCalls.length = 0
+ h.providerId = 'anthropic'
+ h.predefinedRemote = true
+ provider.provider = 'anthropic'
+ provider.settings = []
+ selectedModel.id = 'gpt'
+ h.getRelevantTools.mockReset()
+ h.getRelevantTools.mockResolvedValue([])
+ })
+
+ it('passes the assistant cap to streamText as maxOutputTokens for a predefined remote provider', async () => {
+ h.assistantParameters = { max_output_tokens: '4096' }
+ const transport = new CustomChatTransport('you are jan', 'thread-1')
+ await drain(await send(transport, [user('u1', 'hello')]))
+
+ expect(streamTextCalls[0].maxOutputTokens).toBe(4096)
+ expect(streamTextCalls[0]).not.toHaveProperty('maxTokens')
+ })
+
+ it('omits maxOutputTokens when the cap is 0 ("no cap") so the SDK does not reject it', async () => {
+ h.assistantParameters = { max_output_tokens: 0 }
+ const transport = new CustomChatTransport('you are jan', 'thread-1')
+ await drain(await send(transport, [user('u1', 'hello')]))
+
+ expect(streamTextCalls[0]).not.toHaveProperty('maxOutputTokens')
+ })
+
+ afterAll(() => {
+ h.predefinedRemote = false
+ })
+})
+
it('keeps a Cowork run on its chosen model when the viewed model changes between steps', async () => {
provider.provider = 'openai'
h.providerId = 'openai'
diff --git a/web-app/src/lib/__tests__/message-branching.test.ts b/web-app/src/lib/__tests__/message-branching.test.ts
index c5ac53041..ac4a36457 100644
--- a/web-app/src/lib/__tests__/message-branching.test.ts
+++ b/web-app/src/lib/__tests__/message-branching.test.ts
@@ -12,6 +12,7 @@ import {
withActiveChild,
repairDetachedAssistants,
planContinuation,
+ activePathTokens,
} from '../message-branching'
let clock = 1000
@@ -63,6 +64,17 @@ describe('message-branching', () => {
expect((sib.metadata as Record<string, unknown>).activeChildId).toBeUndefined()
})
+ it('activePathTokens counts only the visible branch', () => {
+ // b1 is a long inactive version; only a -> b2 is sent to the model.
+ const a = msg('a', 'user', 'q', { parentId: null })
+ const b1 = msg('b1', 'assistant', 'x'.repeat(3500), { parentId: 'a' })
+ const b2 = msg('b2', 'assistant', 'second', { parentId: 'a' })
+ const all = activePathTokens([a, b1, b2])
+ const visible = activePathTokens([a, b2])
+ expect(all).toBe(visible)
+ expect(activePathTokens(undefined)).toBe(0)
+ })
+
it('newest sibling is active by default; activeChildId overrides', () => {
// root user a -> assistant b1 (v1) and b2 (v2, newer)
const a = msg('a', 'user', 'q', { parentId: null })
diff --git a/web-app/src/lib/attachmentProcessing.ts b/web-app/src/lib/attachmentProcessing.ts
index 026f8e873..adab14829 100644
--- a/web-app/src/lib/attachmentProcessing.ts
+++ b/web-app/src/lib/attachmentProcessing.ts
@@ -1,6 +1,11 @@
import { ServiceHub } from '@/services'
import { Attachment } from '@/types/attachment'
import { toast } from 'sonner'
+import { estimateTokens } from '@/lib/context-manager'
+import {
+ getLocalPropsExtension,
+ readCtxLen,
+} from '@/lib/llamacppRouterProps'
type AttachmentProcessingStatus = 'processing' | 'done' | 'error' | 'clear_all'
@@ -15,11 +20,9 @@ type AttachmentProcessingOptions = {
projectId?: string
serviceHub: ServiceHub
selectedProvider?: string
+ /** Token budget under which an 'auto' document is inlined; see resolveAutoInlineBudget. */
contextThreshold?: number
- estimateTokens?: (text: string) => Promise<number | undefined>
parsePreference: 'auto' | 'inline' | 'embeddings' | 'prompt'
- autoFallbackMode?: 'inline' | 'embeddings'
- perFileChoices?: Map<string, 'inline' | 'embeddings'>
updateAttachmentProcessing?: (
name: string,
status: AttachmentProcessingStatus,
@@ -75,6 +78,54 @@ const formatAttachmentError = (err: unknown): string => {
return String(err)
}
+type ParsePreference = AttachmentProcessingOptions['parsePreference']
+
+/**
+ * Token budget an 'auto' document may use to be inlined: the model's context
+ * window times the user's auto-inline ratio. Only local models have a window
+ * the app knows (configured ctx_len, or the launched n_ctx when ctx_len is
+ * left to auto-fit and the model is already loaded). Cloud providers expose
+ * no context-window metadata, so they get undefined and the user is asked.
+ * `usedTokens` is what the conversation already occupies: a document that
+ * fits the bare window can still overflow it on top of a long thread.
+ */
+export const resolveAutoInlineBudget = async (
+ model: Model | null | undefined,
+ provider: string | undefined,
+ ratio: number | undefined,
+ usedTokens = 0
+): Promise<number | undefined> => {
+ if (!model || typeof ratio !== 'number' || !(ratio > 0)) return undefined
+ let ctxLen = readCtxLen(model.settings?.ctx_len?.controller_props?.value)
+ if (!ctxLen) {
+ try {
+ const props = await getLocalPropsExtension(provider)?.getModelProps?.(
+ model.id
+ )
+ ctxLen = readCtxLen(props?.nCtx)
+ } catch {
+ // Not loaded yet: the window is unknown until the router launches it.
+ }
+ }
+ if (!ctxLen) return undefined
+ const budget = Math.floor(ctxLen * ratio) - usedTokens
+ return budget > 0 ? budget : undefined
+}
+
+/**
+ * Whether the user must pick inline vs embeddings for a document at attach
+ * time. 'auto' only asks when there is no budget to decide by size.
+ */
+export const needsIngestionChoice = (
+ doc: Attachment,
+ parsePreference: ParsePreference,
+ hasInlineBudget: boolean
+): boolean => {
+ if (doc.processed || doc.injectionMode) return false
+ const preference = doc.parseMode ?? parsePreference
+ return preference === 'prompt' || (preference === 'auto' && !hasInlineBudget)
+}
+
export const processAttachmentsForSend = async (
options: AttachmentProcessingOptions
): Promise<AttachmentProcessingResult> => {
@@ -84,10 +135,7 @@ export const processAttachmentsForSend = async (
projectId,
serviceHub,
contextThreshold,
- estimateTokens,
parsePreference,
- autoFallbackMode,
- perFileChoices,
updateAttachmentProcessing,
onIngestProgress,
} = options
@@ -122,6 +170,9 @@ export const processAttachmentsForSend = async (
contextThreshold > 0
? contextThreshold
: undefined
+ // One budget for the whole send: each document that fits alone could still
+ // overflow the window together with the others inlined before it.
+ let remainingInlineBudget = effectiveContextThreshold ?? 0
const notifyUpdate = (
...args: Parameters<
NonNullable<AttachmentProcessingOptions['updateAttachmentProcessing']>
@@ -194,69 +245,35 @@ export const processAttachmentsForSend = async (
notifyUpdate(doc.name, 'processing')
const targetPreference = doc.parseMode ?? parsePreference
- let targetMode: 'inline' | 'embeddings' =
- targetPreference === 'inline' ? 'inline' : 'embeddings'
+ // Project files always use embeddings, never inline. 'prompt' documents
+ // carry the user's pick in parseMode, so reaching here means no pick
+ // was recorded and the safe default applies.
+ const decideBySize =
+ !projectId &&
+ targetPreference === 'auto' &&
+ effectiveContextThreshold !== undefined
+ const wantsInline =
+ !projectId && (targetPreference === 'inline' || decideBySize)
+ let targetMode: 'inline' | 'embeddings' = 'embeddings'
let parsedContent: string | undefined
- // Project files always use embeddings, never inline
- if (projectId) {
- targetMode = 'embeddings'
- }
-
- const canInline = !projectId && targetPreference !== 'embeddings' && !!doc.path
-
- if (canInline) {
+ if (wantsInline && doc.path) {
try {
parsedContent = await serviceHub
.rag()
- .parseDocument?.(doc.path!, doc.fileType)
+ .parseDocument?.(doc.path, doc.fileType)
} catch (err) {
console.warn(`Failed to parse ${doc.name} for inline use`, err)
}
}
- if (targetPreference === 'auto') {
- // Check if user made a per-file choice for this document
- const userChoice = perFileChoices?.get(doc.path || '')
- // Project files always use embeddings
- const effectiveMode = projectId ? 'embeddings' : (userChoice ?? autoFallbackMode ?? 'embeddings')
- targetMode = effectiveMode
-
- // Only do auto-detection if no user choice was made and not project file
- if (!projectId && !userChoice && parsedContent && estimateTokens) {
- const estimatedTokens = await estimateTokens(parsedContent)
- const tokenCount =
- typeof estimatedTokens === 'number' &&
- Number.isFinite(estimatedTokens) &&
- estimatedTokens > 0
- ? estimatedTokens
- : undefined
- if (!effectiveContextThreshold) {
- console.debug(
- `Attachment ${doc.name}: no context threshold available; defaulting to ${targetMode}`
- )
- } else if (typeof tokenCount === 'number') {
- targetMode =
- tokenCount <= effectiveContextThreshold ? 'inline' : 'embeddings'
- } else {
- console.debug(
- `Attachment ${doc.name}: token estimate unavailable or non-positive; defaulting to ${targetMode}`
- )
- }
- } else if (!projectId && !userChoice && !parsedContent) {
- console.debug(
- `Attachment ${doc.name}: parsed content unavailable for token estimation; defaulting to ${targetMode}`
- )
- } else if (!projectId && !userChoice) {
- console.debug(
- `Attachment ${doc.name}: token estimator unavailable; defaulting to ${targetMode}`
- )
- }
- } else if (targetPreference === 'prompt') {
- // Check if user made a per-file choice for this document
- const userChoice = perFileChoices?.get(doc.path || '')
- // Project files always use embeddings
- targetMode = projectId ? 'embeddings' : (userChoice ?? autoFallbackMode ?? 'embeddings')
+ if (parsedContent) {
+ const tokens = estimateTokens(parsedContent)
+ targetMode =
+ !decideBySize || tokens <= remainingInlineBudget
+ ? 'inline'
+ : 'embeddings'
+ if (targetMode === 'inline') remainingInlineBudget -= tokens
}
if (targetMode === 'inline' && parsedContent) {
diff --git a/web-app/src/lib/chatFinish.ts b/web-app/src/lib/chatFinish.ts
new file mode 100644
index 000000000..dacc7a496
--- /dev/null
+++ b/web-app/src/lib/chatFinish.ts
@@ -0,0 +1,79 @@
+import type { UIMessage } from 'ai'
+import { uiMessageHasMeaningfulContent } from '@/lib/messages'
+import { isContextOverflowMessage } from '@/utils/error'
+import { readCtxLen } from '@/lib/llamacppRouterProps'
+
+// Used when a local model has neither a ctx_len value nor a known launched n_ctx.
+const DEFAULT_CTX_LEN = 32768
+
+/**
+ * Only local engines read the per-model `ctx_len` setting; for cloud providers
+ * the context window is fixed server-side, so neither the context-limit
+ * heuristic nor the "Increase Context Size" action means anything there.
+ */
+export function providerHasContextSetting(provider: string | undefined): boolean {
+ return provider === 'llamacpp' || provider === 'mlx'
+}
+
+/**
+ * Whether a `finishReason === 'length'` stop means the local context window
+ * filled up (offer a bigger context) rather than the output-token cap being
+ * hit (keep the partial and offer Continue). Cloud providers always report
+ * the latter: their `ctx_len` is absent, so the fallback would misfire.
+ */
+export function isContextLimitStop({
+ provider,
+ usage,
+ ctxLen,
+ launchedCtxLen,
+}: {
+ provider: string | undefined
+ usage: { inputTokens?: number; outputTokens?: number } | undefined
+ ctxLen: unknown
+ /** n_ctx the model actually launched with; decides when ctx_len auto-fits. */
+ launchedCtxLen?: number
+}): boolean {
+ if (!providerHasContextSetting(provider)) return false
+ const limit =
+ readCtxLen(ctxLen) ?? readCtxLen(launchedCtxLen) ?? DEFAULT_CTX_LEN
+ const totalTokens = (usage?.inputTokens ?? 0) + (usage?.outputTokens ?? 0)
+ return totalTokens >= limit * 0.9
+}
+
+/**
+ * A completed assistant turn that produced nothing to show. Aborted and
+ * errored turns are excluded (the user stopped it, or the error banner already
+ * explains it), as are tool-call turns whose content arrives in a later step.
+ */
+export function isEmptyReply({
+ message,
+ isAbort,
+ isError,
+ finishReason,
+}: {
+ message: UIMessage
+ isAbort: boolean
+ isError: boolean
+ finishReason: string | undefined
+}): boolean {
+ if (isAbort || isError || message.role !== 'assistant') return false
+ if (finishReason === 'tool-calls') return false
+ return !uiMessageHasMeaningfulContent(message)
+}
+
+/**
+ * Show "Increase Context Size" only where raising ctx_len can help. The
+ * keyword fallback keeps llama-server wordings the strict matcher misses
+ * ("input (N tokens) is larger than the max context size").
+ */
+export function offersContextIncrease(
+ provider: string | undefined,
+ errorMessage: string | undefined
+): boolean {
+ if (!providerHasContextSetting(provider) || !errorMessage) return false
+ const lower = errorMessage.toLowerCase()
+ return (
+ isContextOverflowMessage(errorMessage) ||
+ (lower.includes('context') && /size|length|limit/.test(lower))
+ )
+}
diff --git a/web-app/src/lib/context-manager.ts b/web-app/src/lib/context-manager.ts
index 6c2110461..1f79e65ae 100644
--- a/web-app/src/lib/context-manager.ts
+++ b/web-app/src/lib/context-manager.ts
@@ -92,6 +92,16 @@ export function estimateMessageTokens(message: UIMessage): number {
return estimateTokens(text) + 4
}
+/** Tokens a whole conversation already occupies in the context window. */
+export function estimateConversationTokens(
+ messages: readonly UIMessage[] | undefined
+): number {
+ return (messages ?? []).reduce(
+ (sum, message) => sum + estimateMessageTokens(message),
+ 0
+ )
+}
+
export interface ContextManagerConfig {
maxContextTokens: number
maxOutputTokens: number
diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.ts
index 1545f8e4e..f1316b4aa 100644
--- a/web-app/src/lib/custom-chat-transport.ts
+++ b/web-app/src/lib/custom-chat-transport.ts
@@ -1397,6 +1397,11 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
...(inferenceParams ?? {}),
...reasoningParams,
}
+ // This only strips the raw-body injection. The output cap still reaches
+ // these providers through streamText's maxOutputTokens, which lets each
+ // SDK map it (Anthropic adds the thinking budget, OpenAI reasoning
+ // models need max_completion_tokens); a body max_tokens would clobber
+ // that. The context budget params are read client-side only.
if (isPredefinedRemoteProvider(effectiveProviderName)) {
for (const key of Object.keys(paramsSettings)) delete mergedParams[key]
}
@@ -1604,7 +1609,10 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
tools: shouldEnableTools ? this.tools : undefined,
toolChoice: shouldEnableTools ? 'auto' : undefined,
system: effectiveSystem,
- ...(maxOutputTokens !== undefined ? { maxTokens: maxOutputTokens } : {}),
+ // 0 means "no cap" in assistant params; the SDK rejects anything below 1.
+ ...(maxOutputTokens !== undefined && maxOutputTokens >= 1
+ ? { maxOutputTokens }
+ : {}),
...(reasoningProviderOptions
? { providerOptions: reasoningProviderOptions }
: {}),
diff --git a/web-app/src/lib/llamacppRouterProps.ts b/web-app/src/lib/llamacppRouterProps.ts
index 7a8466f38..6229b56da 100644
--- a/web-app/src/lib/llamacppRouterProps.ts
+++ b/web-app/src/lib/llamacppRouterProps.ts
@@ -44,3 +44,10 @@ export const getLocalPropsExtension = (
if (provider === 'mlx') return getMlxExtension()
return undefined
}
+
+/** A ctx_len setting or launched n_ctx as a positive token count. The settings
+ * store keeps ctx_len as a number or a string, and '' when left to auto-fit. */
+export const readCtxLen = (value: unknown): number | undefined => {
+ const n = typeof value === 'string' ? parseInt(value, 10) : value
+ return typeof n === 'number' && Number.isFinite(n) && n > 0 ? n : undefined
+}
diff --git a/web-app/src/lib/message-branching.ts b/web-app/src/lib/message-branching.ts
index 4a973eff6..3087bf2b9 100644
--- a/web-app/src/lib/message-branching.ts
+++ b/web-app/src/lib/message-branching.ts
@@ -5,6 +5,9 @@ import {
ChatCompletionRole,
} from '@janhq/core'
+import { estimateConversationTokens } from '@/lib/context-manager'
+import { convertThreadMessagesToUIMessages } from '@/lib/messages'
+
type ThreadContent = NonNullable<ThreadMessage['content']>[number]
/**
@@ -116,6 +119,20 @@ export const computeActivePath = (
return path
}
+/**
+ * Tokens the conversation the model will actually see already occupies. Only
+ * the active branch is sent, so inactive versions must not count.
+ */
+export const activePathTokens = (
+ messages: ThreadMessage[] | undefined,
+ activeRootId?: string
+): number =>
+ estimateConversationTokens(
+ convertThreadMessagesToUIMessages(
+ computeActivePath(messages ?? [], activeRootId)
+ )
+ )
+
/** Return a copy of `m` with `parentId` set in metadata. */
export const withParentId = (
m: ThreadMessage,
diff --git a/web-app/src/locales/en/model-errors.json b/web-app/src/locales/en/model-errors.json
index dc88ceb1b..63520f5d8 100644
--- a/web-app/src/locales/en/model-errors.json
+++ b/web-app/src/locales/en/model-errors.json
@@ -7,6 +7,7 @@
"lastRequestOverflowed": "Last request overflowed the context window.",
"contextOverflowDetail": "This request needed {{request}} tokens, but the model’s context window holds only {{context}}.",
"contextOverflowGeneric": "The request exceeds the available context size.",
+ "emptyReply": "The model finished without returning a reply. Try regenerating, or check the provider settings.",
"engine": {
"unknown": "The model engine reported an unexpected error.",
"MODEL_LOAD_FAILED": "The model could not be loaded.",
diff --git a/web-app/src/providers/__tests__/ExtensionProvider.test.tsx b/web-app/src/providers/__tests__/ExtensionProvider.test.tsx
index a4a933a6e..68766b2e2 100644
--- a/web-app/src/providers/__tests__/ExtensionProvider.test.tsx
+++ b/web-app/src/providers/__tests__/ExtensionProvider.test.tsx
@@ -1,5 +1,5 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
-import { render, screen, waitFor } from '@testing-library/react'
+import { render, screen, waitFor, cleanup } from '@testing-library/react'
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import '@testing-library/jest-dom'
@@ -61,6 +61,11 @@ describe('ExtensionProvider', () => {
})
afterEach(() => {
+ // Unmount first: restoreAllMocks strips h.emit's resolved value, and on a
+ // slow runner the app-ready effect can still be pending at this point, so
+ // emit('app-ready').catch would hit undefined. The global cleanup runs
+ // only after this hook.
+ cleanup()
vi.restoreAllMocks()
})
diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsx
index 7aa63df9e..d4c650f08 100644
--- a/web-app/src/routes/threads/$threadId.tsx
+++ b/web-app/src/routes/threads/$threadId.tsx
@@ -19,7 +19,10 @@ import { useChat } from '@/hooks/use-chat'
import { useModelProvider } from '@/hooks/useModelProvider'
import { engineSlotsIdle } from '@janhq/tauri-plugin-llamacpp-api'
import { useInterfaceSettings } from '@/hooks/useInterfaceSettings'
-import { deriveToolOutputCap } from '@/lib/context-manager'
+import {
+ deriveToolOutputCap,
+ estimateConversationTokens,
+} from '@/lib/context-manager'
import { renderInstructions } from '@/lib/instructionTemplate'
import {
Conversation,
@@ -62,16 +65,25 @@ import {
useChatAttachments,
NEW_THREAD_ATTACHMENT_KEY,
} from '@/hooks/useChatAttachments'
-import { processAttachmentsForSend } from '@/lib/attachmentProcessing'
+import {
+ processAttachmentsForSend,
+ resolveAutoInlineBudget,
+} from '@/lib/attachmentProcessing'
import { useAttachments } from '@/hooks/useAttachments'
import { PromptProgress } from '@/components/PromptProgress'
import { useToolAvailable } from '@/hooks/useToolAvailable'
import {
OUT_OF_CONTEXT_SIZE,
isContextOverflowMessage,
+ isLocalContextOverflowMessage,
parseContextOverflow,
} from '@/utils/error'
-import { useTranslation } from '@/i18n/react-i18next-compat'
+import { useTranslation, i18n } from '@/i18n/react-i18next-compat'
+import {
+ isContextLimitStop,
+ isEmptyReply,
+ offersContextIncrease,
+} from '@/lib/chatFinish'
import { Button } from '@/components/ui/button'
import { IconAlertCircle, IconRefresh, IconLoader2 } from '@tabler/icons-react'
import { useToolApproval } from '@/hooks/useToolApproval'
@@ -86,6 +98,10 @@ import { Shimmer } from '@/components/ai-elements/shimmer'
import { useMessageQueue } from '@/stores/message-queue-store'
import { generateThreadTitle } from '@/lib/thread-title-summarizer'
import { useAutoScroll } from '@/hooks/useAutoScroll'
+import {
+ getLocalPropsExtension,
+ readCtxLen,
+} from '@/lib/llamacppRouterProps'
const CHAT_STATUS = {
STREAMING: 'streaming',
@@ -237,7 +253,9 @@ function ThreadDetail() {
const { t } = useTranslation()
// llama-server's overflow string is raw English; localize it, interpolating
- // the parsed request/context token counts when available.
+ // the parsed request/context token counts when available. Any other wording
+ // is a provider's own error (Anthropic, OpenAI), which already says what to
+ // cut, so it is shown as is rather than hidden behind the generic text.
const contextBannerMessage = useMemo(() => {
const raw = contextLimitError?.message
if (!raw) return undefined
@@ -247,6 +265,7 @@ function ThreadDetail() {
request: info.requestTokens.toLocaleString(),
context: info.contextTokens.toLocaleString(),
})
+ if (!isLocalContextOverflowMessage(raw)) return raw
return t('model-errors:contextOverflowGeneric')
}, [contextLimitError, t])
@@ -281,6 +300,9 @@ function ThreadDetail() {
// Set before a generation when the resulting assistant message should be
// linked to a specific parent (versioning). Consumed once in onFinish.
const pendingAssistantParentId = useRef<string | null>(null)
+ // n_ctx the local model launched with. onFinish is synchronous, so it is
+ // fetched once streaming starts (the model is loaded by then).
+ const launchedCtxLenRef = useRef<number | undefined>(undefined)
// Holds the id of a stopped assistant message being resumed. Continuing must
// extend the turn in place, not fork a new version, so onFinish deletes this
// stale partial once the continued reply is persisted.
@@ -303,7 +325,7 @@ function ThreadDetail() {
sessionTitle: thread?.title,
systemMessage,
experimental_throttle: 50,
- onFinish: ({ message, isAbort }) => {
+ onFinish: ({ message, isAbort, isError }) => {
const msgMeta = message.metadata as Record<string, unknown> | undefined
const finishReason = msgMeta?.finishReason as string | undefined
// Consume once per generation so a skipped persist (error/empty) can't
@@ -315,16 +337,17 @@ function ThreadDetail() {
// from where it stopped. The stream wrapper injects it as the first text-delta
// of the new message, so the user sees the partial text immediately.
if (!isAbort && finishReason === 'length') {
- const selectedModelState = useModelProvider.getState().selectedModel
- const usage = msgMeta?.usage as
- | { inputTokens?: number; outputTokens?: number }
- | undefined
- const totalTokens =
- (usage?.inputTokens ?? 0) + (usage?.outputTokens ?? 0)
- const ctxLen =
- (selectedModelState?.settings?.ctx_len?.controller_props
- ?.value as number) ?? 32768
- const isContextLimit = totalTokens >= ctxLen * 0.9
+ const providerState = useModelProvider.getState()
+ const isContextLimit = isContextLimitStop({
+ provider: providerState.selectedProvider,
+ usage: msgMeta?.usage as
+ | { inputTokens?: number; outputTokens?: number }
+ | undefined,
+ ctxLen:
+ providerState.selectedModel?.settings?.ctx_len?.controller_props
+ ?.value,
+ launchedCtxLen: launchedCtxLenRef.current,
+ })
if (isContextLimit) {
// Stash the partial so the manual "Increase Context Size" button can
@@ -347,6 +370,22 @@ function ThreadDetail() {
if (!isAbort && message.parts.length) setPendingContinueMessage(null)
+ // Nothing would be persisted for an empty reply, so without this the
+ // turn silently vanishes and the user cannot tell it failed. The error
+ // goes on the user turn it answers (as the stream-error path does):
+ // that message is persisted, and the errorEntries effect below copies
+ // the error into its metadata.error, which hydration restores on reload.
+ if (isEmptyReply({ message, isAbort, isError, finishReason })) {
+ const userTurnId =
+ pendingAssistantParentId.current ?? resolveAssistantParent(undefined)
+ pendingAssistantParentId.current = null
+ if (userTurnId) {
+ useMessageErrors
+ .getState()
+ .setError(userTurnId, i18n.t('model-errors:emptyReply'))
+ }
+ }
+
// The turn ended before completion (user hit Stop, or the model hit its
// output-token cap). Persist the partial marked `stopped` so the UI can
// offer a "Continue" affordance, and stamp the live message so the button
@@ -781,6 +820,11 @@ function ThreadDetail() {
reset: resetReasoningScroll,
} = useAutoScroll()
+ // Read at send time without making the send callbacks depend on every
+ // streamed token.
+ const chatMessagesRef = useRef(chatMessages)
+ chatMessagesRef.current = chatMessages
+
const lastIsAssistant = useMemo(() => {
const last = chatMessages[chatMessages.length - 1]
return !!last && last.role === 'assistant'
@@ -792,6 +836,26 @@ function ThreadDetail() {
}
}, [status, resetReasoningScroll])
+ useEffect(() => {
+ if (status !== 'streaming') return
+ launchedCtxLenRef.current = undefined
+ const modelId = selectedModel?.id
+ const ext = getLocalPropsExtension(selectedProvider)
+ if (!modelId || !ext?.getModelProps) return
+ let cancelled = false
+ ext
+ .getModelProps(modelId)
+ .then((props) => {
+ if (!cancelled) launchedCtxLenRef.current = readCtxLen(props?.nCtx)
+ })
+ .catch(() => {
+ // Router unreachable: isContextLimitStop falls back to its default.
+ })
+ return () => {
+ cancelled = true
+ }
+ }, [status, selectedProvider, selectedModel?.id])
+
useEffect(() => {
if (status === 'streaming') {
scrollReasoningToBottom()
@@ -1047,7 +1111,8 @@ function ThreadDetail() {
useAppState.getState().setThreadBusy(threadId, true)
}
try {
- const parsePreference = useAttachments.getState().parseMode
+ const { parseMode: parsePreference, autoInlineContextRatio } =
+ useAttachments.getState()
const result = await processAttachmentsForSend({
attachments: combinedAttachments,
threadId,
@@ -1055,6 +1120,12 @@ function ThreadDetail() {
serviceHub,
selectedProvider,
parsePreference,
+ contextThreshold: await resolveAutoInlineBudget(
+ useModelProvider.getState().selectedModel,
+ selectedProvider,
+ autoInlineContextRatio,
+ estimateConversationTokens(chatMessagesRef.current)
+ ),
})
processedAttachments = result.processedAttachments
@@ -1843,20 +1914,10 @@ function ThreadDetail() {
<li>Use a smaller / more quantized model</li>
</ul>
)}
- {((error ?? contextLimitError)?.message
- ?.toLowerCase()
- .includes('context') &&
- ((error ?? contextLimitError)?.message
- ?.toLowerCase()
- .includes('size') ||
- (error ?? contextLimitError)?.message
- ?.toLowerCase()
- .includes('length') ||
- (error ?? contextLimitError)?.message
- ?.toLowerCase()
- .includes('limit'))) ||
- (error ?? contextLimitError)?.message ===
- OUT_OF_CONTEXT_SIZE ? (
+ {offersContextIncrease(
+ selectedProvider,
+ (error ?? contextLimitError)?.message
+ ) ? (
<Button
variant="outline"
size="sm"
@@ -1866,7 +1927,7 @@ function ThreadDetail() {
<IconAlertCircle className="size-4 mr-2" />
Increase Context Size
</Button>
- ) : (
+ ) : oomError || backendError ? (
<Button
variant="outline"
size="sm"
@@ -1874,9 +1935,9 @@ function ThreadDetail() {
onClick={() => handleRegenerate()}
>
<IconRefresh className="size-4 mr-2" />
- {oomError || backendError ? 'Reload' : 'Regenerate'}
+ Reload
</Button>
- )}
+ ) : null}
</div>
</div>
</div>
diff --git a/web-app/src/routes/threads/__tests__/$threadId.test.tsx b/web-app/src/routes/threads/__tests__/$threadId.test.tsx
index a7a98271c..a4e87f4d8 100644
--- a/web-app/src/routes/threads/__tests__/$threadId.test.tsx
+++ b/web-app/src/routes/threads/__tests__/$threadId.test.tsx
@@ -324,6 +324,7 @@ vi.mock('@/lib/attachmentProcessing', () => ({
processAttachmentsForSend: vi
.fn()
.mockResolvedValue({ processedAttachments: [], hasEmbeddedDocuments: false }),
+ resolveAutoInlineBudget: vi.fn().mockResolvedValue(6144),
}))
vi.mock('@/lib/thread-title-summarizer', () => ({
@@ -404,7 +405,8 @@ vi.mock('@/constants/chat', () => ({
SESSION_STORAGE_PREFIX: { INITIAL_MESSAGE: 'initial-message-' },
}))
-vi.mock('@/utils/error', () => ({
+vi.mock('@/utils/error', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/utils/error')>()),
OUT_OF_CONTEXT_SIZE: 'OUT_OF_CONTEXT_SIZE',
}))
@@ -414,6 +416,11 @@ vi.mock('@/utils/error', () => ({
import { Route } from '../$threadId'
import { getServiceHub } from '@/hooks/useServiceHub'
import { useToolCallRuntime } from '@/hooks/useToolCallRuntime'
+import { useMessageErrors } from '@/stores/message-errors'
+import {
+ processAttachmentsForSend,
+ resolveAutoInlineBudget,
+} from '@/lib/attachmentProcessing'
// The global setup mock is a shared object, so an overridden factory has to be
// put back or it leaks into every later test.
@@ -524,6 +531,35 @@ describe('ThreadDetail route', () => {
expect(h.messagesState.addMessage).toHaveBeenCalled()
})
+ it('passes the auto-inline budget when sending documents', async () => {
+ h.useAttachmentsState.autoInlineContextRatio = 0.75
+ // 35 chars -> 10 estimated tokens + 4 per-message overhead.
+ h.chatState.messages = [
+ { id: 'u0', role: 'user', parts: [{ type: 'text', text: 'x'.repeat(35) }] },
+ ]
+ h.attachmentsState.getAttachments = vi.fn(() => [
+ { name: 'sheet.xlsx', type: 'document', path: '/sheet.xlsx' },
+ ])
+ renderComponent()
+ await act(async () => {
+ screen.getByTestId('chat-send').click()
+ })
+ await waitFor(() => {
+ expect(processAttachmentsForSend).toHaveBeenCalled()
+ })
+ expect(resolveAutoInlineBudget).toHaveBeenCalledWith(
+ h.modelProviderState.selectedModel,
+ 'openai',
+ 0.75,
+ 14
+ )
+ expect(vi.mocked(processAttachmentsForSend).mock.calls[0][0]).toMatchObject({
+ contextThreshold: 6144,
+ parsePreference: 'auto',
+ })
+ h.attachmentsState.getAttachments = vi.fn(() => [])
+ })
+
it('invokes stop when ChatInput calls onStop', () => {
renderComponent()
screen.getByTestId('chat-stop').click()
@@ -714,6 +750,144 @@ describe('ThreadDetail route', () => {
expect(persisted.metadata.parentId).not.toBeNull()
})
+ describe('finishReason length (#9228)', () => {
+ const finishAtLength = () =>
+ (h as any).capturedOnFinish({
+ message: {
+ id: 'a-len',
+ role: 'assistant',
+ parts: [{ type: 'text', text: 'partial answer' }],
+ metadata: {
+ finishReason: 'length',
+ usage: { inputTokens: 30000, outputTokens: 4000 },
+ },
+ },
+ isAbort: false,
+ isError: false,
+ })
+
+ it('keeps a truncated cloud reply as stopped instead of a context banner', () => {
+ h.modelProviderState.selectedProvider = 'anthropic'
+ renderComponent()
+ act(() => {
+ finishAtLength()
+ })
+ const added = h.messagesState.addMessage.mock.calls.map((c: any[]) => c[0])
+ const persisted = added.find((m: any) => m.id === 'a-len')
+ expect(persisted).toBeTruthy()
+ expect(persisted.metadata.stopped).toBe(true)
+ expect(screen.queryByText('Increase Context Size')).toBeNull()
+ })
+
+ it('still offers Increase Context Size for a local model near ctx_len', () => {
+ h.modelProviderState.selectedProvider = 'llamacpp'
+ renderComponent()
+ act(() => {
+ finishAtLength()
+ })
+ expect(
+ h.messagesState.addMessage.mock.calls.some((c: any[]) => c[0].id === 'a-len')
+ ).toBe(false)
+ expect(screen.getByText('Increase Context Size')).toBeInTheDocument()
+ })
+ })
+
+ describe('empty replies (#9228)', () => {
+ beforeEach(() => {
+ useMessageErrors.getState().clearAll()
+ })
+
+ const finishEmpty = (extra: Record<string, unknown> = {}) =>
+ (h as any).capturedOnFinish({
+ message: {
+ id: 'a-empty',
+ role: 'assistant',
+ parts: [],
+ metadata: { finishReason: 'stop' },
+ },
+ isAbort: false,
+ isError: false,
+ ...extra,
+ })
+
+ it('pins the error on the user turn, which is persisted', () => {
+ // The empty assistant reply is never saved, so an error keyed to it
+ // would vanish on reload; the user message survives and is hydrated.
+ renderComponent()
+ act(() => {
+ finishEmpty()
+ })
+ const err = useMessageErrors.getState().errors['u1']
+ expect(err).toBeTruthy()
+ expect(err).not.toContain(':')
+ expect(useMessageErrors.getState().errors['a-empty']).toBeUndefined()
+ })
+
+ it('persists the empty-reply error into the user turn metadata', () => {
+ const u1 = {
+ id: 'u1',
+ role: 'user',
+ content: [{ type: 'text', text: { value: 'hi', annotations: [] } }],
+ metadata: {},
+ }
+ h.messagesState.messages = { 'thread-1': [u1] }
+ h.messagesState.getMessages = vi.fn(() => [u1])
+ renderComponent()
+ act(() => {
+ finishEmpty()
+ })
+ const persisted = h.messagesState.updateMessage.mock.calls
+ .map((c: any[]) => c[0])
+ .find((m: any) => m.id === 'u1' && m.metadata?.error)
+ expect(persisted?.metadata.error).toBe(
+ useMessageErrors.getState().errors['u1']
+ )
+ })
+
+ it('does not flag a reply the user stopped', () => {
+ renderComponent()
+ act(() => {
+ finishEmpty({ isAbort: true })
+ })
+ expect(useMessageErrors.getState().errors['a-empty']).toBeUndefined()
+ })
+ })
+
+ describe('context overflow banner (#9228)', () => {
+ it('does not offer a no-op Increase Context Size for a cloud overflow', () => {
+ h.modelProviderState.selectedProvider = 'anthropic'
+ h.chatState.status = 'error'
+ h.chatState.error = new Error(
+ 'input length and `max_tokens` exceed context limit: 188240 + 21333 > 200000'
+ )
+ h.chatState.messages = [
+ { id: 'u1', role: 'user', parts: [{ type: 'text', text: 'hi' }] },
+ ]
+ renderComponent()
+ expect(screen.getByText('Model ran out of context size')).toBeInTheDocument()
+ expect(screen.queryByText('Increase Context Size')).toBeNull()
+ // The provider's own text says what to cut; the generic string hid it.
+ expect(
+ screen.getByText(/188240 \+ 21333 > 200000/)
+ ).toBeInTheDocument()
+ // Regenerate would re-send the same oversized prompt.
+ expect(screen.queryByText('Regenerate')).toBeNull()
+ })
+
+ it('offers Increase Context Size for a llamacpp overflow', () => {
+ h.modelProviderState.selectedProvider = 'llamacpp'
+ h.chatState.status = 'error'
+ h.chatState.error = new Error(
+ 'request (518 tokens) exceeds the available context size (512 tokens)'
+ )
+ h.chatState.messages = [
+ { id: 'u1', role: 'user', parts: [{ type: 'text', text: 'hi' }] },
+ ]
+ renderComponent()
+ expect(screen.getByText('Increase Context Size')).toBeInTheDocument()
+ })
+ })
+
describe('tool-call approval requested early, execution stays in onFinish', () => {
const toolCall = (id: string) => ({
toolCall: { toolCallId: id, toolName: 'fetch', input: { url: 'x' } },
diff --git a/web-app/src/utils/__tests__/error.test.ts b/web-app/src/utils/__tests__/error.test.ts
index 287d18efe..6dd7e7ca0 100644
--- a/web-app/src/utils/__tests__/error.test.ts
+++ b/web-app/src/utils/__tests__/error.test.ts
@@ -2,6 +2,7 @@ import { describe, it, expect } from 'vitest'
import {
OUT_OF_CONTEXT_SIZE,
isContextOverflowMessage,
+ isLocalContextOverflowMessage,
parseContextOverflow,
} from '../error'
@@ -26,6 +27,45 @@ describe('error utilities', () => {
).toBe(true)
})
+ it('matches Anthropic overflow errors', () => {
+ expect(
+ isContextOverflowMessage('prompt is too long: 210000 tokens > 200000 maximum')
+ ).toBe(true)
+ expect(
+ isContextOverflowMessage(
+ 'input length and `max_tokens` exceed context limit: 188240 + 21333 > 200000, decrease input length or `max_tokens` and try again'
+ )
+ ).toBe(true)
+ })
+
+ it('tells llama-server wording apart from cloud provider wording', () => {
+ expect(isLocalContextOverflowMessage(OUT_OF_CONTEXT_SIZE)).toBe(true)
+ expect(
+ isLocalContextOverflowMessage(
+ 'request (518 tokens) exceeds the available context size (512 tokens)'
+ )
+ ).toBe(true)
+ expect(
+ isLocalContextOverflowMessage('prompt is too long: 210000 tokens > 200000 maximum')
+ ).toBe(false)
+ })
+
+ it('does not treat a 413 payload-size error as a context overflow', () => {
+ // A byte limit on the HTTP body (often images/files): regenerating the
+ // same request cannot help, so the provider text must stay visible.
+ expect(isContextOverflowMessage('request_too_large')).toBe(false)
+ expect(isContextOverflowMessage('Request exceeds the maximum size')).toBe(false)
+ })
+
+ it('matches OpenAI overflow errors', () => {
+ expect(
+ isContextOverflowMessage(
+ "This model's maximum context length is 128000 tokens. However, your messages resulted in 130000 tokens."
+ )
+ ).toBe(true)
+ expect(isContextOverflowMessage('context_length_exceeded')).toBe(true)
+ })
+
it('does not match unrelated errors', () => {
expect(isContextOverflowMessage('Could not establish connection')).toBe(false)
expect(isContextOverflowMessage('cuda error: out of memory')).toBe(false)
@@ -51,6 +91,20 @@ describe('error utilities', () => {
it('returns null when no token counts are present', () => {
expect(parseContextOverflow(OUT_OF_CONTEXT_SIZE)).toBeNull()
+ // Cloud messages use other layouts; never misread them as counts.
+ expect(
+ parseContextOverflow('prompt is too long: 210000 tokens > 200000 maximum')
+ ).toBeNull()
+ expect(
+ parseContextOverflow(
+ 'input length and `max_tokens` exceed context limit: 188240 + 21333 > 200000'
+ )
+ ).toBeNull()
+ expect(
+ parseContextOverflow(
+ "This model's maximum context length is 128000 tokens. However, your messages resulted in 130000 tokens."
+ )
+ ).toBeNull()
expect(parseContextOverflow('cuda error: out of memory')).toBeNull()
})
})
diff --git a/web-app/src/utils/error.ts b/web-app/src/utils/error.ts
index 30c548f1b..656cb4870 100644
--- a/web-app/src/utils/error.ts
+++ b/web-app/src/utils/error.ts
@@ -1,10 +1,34 @@
export const OUT_OF_CONTEXT_SIZE =
'the request exceeds the available context size.'
-// Matches OUT_OF_CONTEXT_SIZE and llama-server's verbose variant
-// ("request (N tokens) exceeds the available context size (M tokens)…").
+// Context-overflow wordings by source, so cloud overflows reach the same
+// context banner as local ones (the banner keeps a provider's own text):
+// llama-server: "request (N tokens) exceeds the available context size ..."
+// Anthropic: "prompt is too long: ...",
+// "input length and `max_tokens` exceed context limit: ..."
+// OpenAI: "This model's maximum context length is N tokens ...",
+// code context_length_exceeded
+// Anthropic's 413 request_too_large is deliberately absent: it is a byte limit
+// on the HTTP body (large images/files), not the token window, so it keeps the
+// provider's own message instead of the generic context banner.
+const LOCAL_CONTEXT_OVERFLOW = /exceeds the available context size/i
+
+const CONTEXT_OVERFLOW_PATTERNS = [
+ LOCAL_CONTEXT_OVERFLOW,
+ /prompt is too long/i,
+ /exceed context limit/i,
+ /context_length_exceeded/i,
+ /maximum context length/i,
+]
+
export function isContextOverflowMessage(message: string): boolean {
- return /exceeds the available context size/i.test(message)
+ return CONTEXT_OVERFLOW_PATTERNS.some((pattern) => pattern.test(message))
+}
+
+// llama-server's own wording, which the banner localizes; anything else that
+// matched isContextOverflowMessage came from a cloud provider.
+export function isLocalContextOverflowMessage(message: string): boolean {
+ return LOCAL_CONTEXT_OVERFLOW.test(message)
}
export interface ContextOverflowInfo {