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(chat): hold a built-in web page to the model's context window (#9283)

Thinh Lece7336a608ab
diff --git a/docs/src/pages/docs/desktop/web-search.mdx b/docs/src/pages/docs/desktop/web-search.mdx
index 2ef4eb578..9c027fee3 100644
--- a/docs/src/pages/docs/desktop/web-search.mdx
+++ b/docs/src/pages/docs/desktop/web-search.mdx
@@ -43,7 +43,10 @@ You can toggle web search for a chat from the input toolbar - the globe icon sho
A typical flow is `web_search` to find sources, then `web_fetch` to read a specific result in full.
`web_search` takes a `query` and an optional `count` (default 5, max 20); `web_fetch` takes an
-http(s) `url`. Fetched content is length-bounded so it doesn't flood the model's context.
+http(s) `url`. Fetched content is length-bounded so it doesn't flood the model's context: a page is
+cut to a fraction of the model's context window, and never past **Max tool output characters** in
+**Settings > MCP Servers** (40,000 by default). With that setting at `0` only the fetch's own
+40,000-character bound applies. A page that was cut ends with `[content truncated]`.
## Requirements
diff --git a/web-app/src/lib/__tests__/webSearchTool.test.ts b/web-app/src/lib/__tests__/webSearchTool.test.ts
new file mode 100644
index 000000000..0e69c9b37
--- /dev/null
+++ b/web-app/src/lib/__tests__/webSearchTool.test.ts
@@ -0,0 +1,219 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const h = vi.hoisted(() => ({
+ webFetch: vi.fn(),
+ mcp: {
+ settings: { maxToolOutputChars: 40000 } as { maxToolOutputChars?: number },
+ },
+}))
+
+vi.mock('@janhq/tauri-plugin-websearch-api', () => ({
+ webSearch: vi.fn(),
+ webFetch: h.webFetch,
+}))
+vi.mock('@/hooks/useWebSearchConfig', () => ({
+ useWebSearchConfig: {
+ getState: () => ({ apiKeys: {}, endpoints: {}, searchProvider: 'default' }),
+ },
+}))
+vi.mock('@/hooks/useMCPServers', () => ({
+ useMCPServers: { getState: () => h.mcp },
+}))
+
+import { executeWebTool, webOutputCap } from '../webSearchTool'
+import { parseWebFetchOutput } from '../toolPresentation'
+
+const page = (content: string, truncated = false) => ({
+ title: 'Trending',
+ url: 'https://github.com/trending',
+ content,
+ truncated,
+})
+const fetchText = async (maxOutputChars?: number) => {
+ const out = await executeWebTool(
+ 'web_fetch',
+ { url: 'https://github.com/trending' },
+ { maxOutputChars }
+ )
+ return out.content as string
+}
+
+beforeEach(() => {
+ h.webFetch.mockReset()
+ h.mcp.settings = { maxToolOutputChars: 40000 }
+})
+
+describe('web_fetch output is held to the same budget as an MCP result', () => {
+ // The page a 4,096-token window cannot hold (#9170).
+ it('is cut to the budget the model window affords', async () => {
+ h.webFetch.mockResolvedValue(page('x'.repeat(39000)))
+
+ const text = await fetchText(3600)
+
+ expect(text.length).toBeLessThanOrEqual(3600)
+ const parsed = parseWebFetchOutput(text)!
+ expect(parsed.title).toBe('Trending')
+ expect(parsed.url).toBe('https://github.com/trending')
+ expect(parsed.truncated).toBe(true)
+ expect(parsed.content.length).toBeGreaterThan(3000)
+ })
+
+ it('is cut to the "Max tool output characters" setting, which it used to ignore', async () => {
+ h.mcp.settings = { maxToolOutputChars: 10000 }
+ h.webFetch.mockResolvedValue(page('x'.repeat(28749)))
+
+ const text = await fetchText()
+
+ expect(text.length).toBeLessThanOrEqual(10000)
+ expect(parseWebFetchOutput(text)!.truncated).toBe(true)
+ })
+
+ it('follows the tighter of the two', async () => {
+ h.mcp.settings = { maxToolOutputChars: 5000 }
+ h.webFetch.mockResolvedValue(page('x'.repeat(20000)))
+
+ expect((await fetchText(3600)).length).toBeLessThanOrEqual(3600)
+ expect((await fetchText(30000)).length).toBeLessThanOrEqual(5000)
+ })
+
+ it('keeps a page that fits, with no marker', async () => {
+ h.webFetch.mockResolvedValue(page('short page'))
+
+ const text = await fetchText(3600)
+
+ expect(text).toBe(
+ 'Title: Trending\nURL: https://github.com/trending\n\nshort page'
+ )
+ })
+
+ it('marks a page the plugin already cut exactly once, and stays within the budget', async () => {
+ h.webFetch.mockResolvedValue(page('x'.repeat(3590), true))
+
+ const text = await fetchText(3600)
+
+ expect(text.length).toBeLessThanOrEqual(3600)
+ expect(text.match(/\[content truncated\]/g)).toHaveLength(1)
+ })
+
+ it('leaves the page whole when the setting is 0, as the setting promises', async () => {
+ h.mcp.settings = { maxToolOutputChars: 0 }
+ h.webFetch.mockResolvedValue(page('x'.repeat(39000)))
+
+ const parsed = parseWebFetchOutput(await fetchText(3600))!
+
+ expect(parsed.content).toHaveLength(39000)
+ expect(parsed.truncated).toBe(false)
+ })
+
+ it('does not split a character that takes two code units', async () => {
+ h.webFetch.mockResolvedValue(page('😀'.repeat(5000)))
+
+ const text = await fetchText(1000)
+
+ const body = parseWebFetchOutput(text)!.content
+ expect(body.length).toBeGreaterThan(0)
+ // A lone high surrogate at the end would be a broken character.
+ const last = body.charCodeAt(body.length - 1)
+ expect(last >= 0xd800 && last <= 0xdbff).toBe(false)
+ })
+
+ // The header comes from the page too (#9283): a title of 20,000 characters
+ // must not put the output past the budget on its own.
+ it('holds an oversized title and url to the budget as well', async () => {
+ h.webFetch.mockResolvedValue({
+ title: 'T'.repeat(20000),
+ url: `https://example.com/${'u'.repeat(20000)}`,
+ content: 'x'.repeat(5000),
+ truncated: false,
+ })
+
+ const text = await fetchText(3600)
+
+ expect(text.length).toBeLessThanOrEqual(3600)
+ const parsed = parseWebFetchOutput(text)!
+ expect(parsed.title!.length).toBeLessThanOrEqual(900)
+ // The page still gets the rest of the budget, and the result says it was cut.
+ expect(parsed.content.length).toBeGreaterThan(1500)
+ expect(parsed.truncated).toBe(true)
+ })
+
+ // A prefix of an address is a different address, and the source link is built
+ // from it, so an address that cannot be kept whole is left out.
+ it('leaves out a url that cannot be kept whole instead of cutting it', async () => {
+ const url = `https://example.com/${'u'.repeat(20000)}`
+ h.webFetch.mockResolvedValue({
+ title: 'Trending',
+ url,
+ content: 'x'.repeat(5000),
+ truncated: false,
+ })
+
+ const text = await fetchText(3600)
+
+ expect(parseWebFetchOutput(text)!.url).toBeUndefined()
+ expect(text).not.toContain('uuuuu')
+ })
+
+ it('keeps a long url whole when everything fits', async () => {
+ const url = `https://example.com/${'a'.repeat(300)}`
+ h.webFetch.mockResolvedValue({
+ title: 'T'.repeat(300),
+ url,
+ content: 'short page',
+ truncated: false,
+ })
+
+ const parsed = parseWebFetchOutput(await fetchText(1000))!
+
+ expect(parsed.url).toBe(url)
+ expect(parsed.title).toBe('T'.repeat(300))
+ expect(parsed.content).toBe('short page')
+ expect(parsed.truncated).toBe(false)
+ })
+
+ it('says the result was cut whenever the title or the url was', async () => {
+ h.webFetch.mockResolvedValue({
+ title: 'T'.repeat(5000),
+ url: 'https://example.com/a',
+ content: 'short page',
+ truncated: false,
+ })
+
+ const parsed = parseWebFetchOutput(await fetchText(1000))!
+
+ expect(parsed.title!.length).toBeLessThan(5000)
+ expect(parsed.truncated).toBe(true)
+ })
+
+ it('leaves a normal title and url untouched', async () => {
+ h.webFetch.mockResolvedValue(page('short page'))
+
+ expect(await fetchText(3600)).toContain(
+ 'Title: Trending\nURL: https://github.com/trending\n\n'
+ )
+ })
+
+ it('never exceeds a budget too small for the header, and still says it was cut', async () => {
+ h.webFetch.mockResolvedValue(page('x'.repeat(5000)))
+
+ const text = await fetchText(40)
+
+ expect(text.length).toBeLessThanOrEqual(40)
+ // The marker the page widget reads, so the cut is still reported to the user.
+ expect(parseWebFetchOutput(text)).toMatchObject({ truncated: true })
+ // Smaller than the marker itself: still inside the budget.
+ expect((await fetchText(10)).length).toBeLessThanOrEqual(10)
+ })
+})
+
+describe('webOutputCap', () => {
+ it('is the setting alone when the model reports no window', () => {
+ h.mcp.settings = { maxToolOutputChars: 12000 }
+ expect(webOutputCap(undefined)).toBe(12000)
+ })
+
+ it('is nothing when neither applies', () => {
+ h.mcp.settings = { maxToolOutputChars: 0 }
+ expect(webOutputCap(undefined)).toBeUndefined()
+ })
+})
diff --git a/web-app/src/lib/toolPresentation.ts b/web-app/src/lib/toolPresentation.ts
index ac6e3785e..d93c1eba8 100644
--- a/web-app/src/lib/toolPresentation.ts
+++ b/web-app/src/lib/toolPresentation.ts
@@ -228,7 +228,7 @@ export type WebFetchPage = {
truncated: boolean
}
-const TRUNCATION_MARKER = '\n\n[content truncated]'
+export const TRUNCATION_MARKER = '\n\n[content truncated]'
const FETCH_HEADER = /^Title: (.*)\nURL: (.*)\n\n([\s\S]*)$/
/**
diff --git a/web-app/src/lib/webSearchTool.ts b/web-app/src/lib/webSearchTool.ts
index 6b440dd84..44953ecc8 100644
--- a/web-app/src/lib/webSearchTool.ts
+++ b/web-app/src/lib/webSearchTool.ts
@@ -1,5 +1,7 @@
import { webSearch, webFetch } from '@janhq/tauri-plugin-websearch-api'
+import { useMCPServers } from '@/hooks/useMCPServers'
import { useWebSearchConfig } from '@/hooks/useWebSearchConfig'
+import { TRUNCATION_MARKER } from '@/lib/toolPresentation'
export const WEB_TOOL_NAMES = new Set(['web_search', 'web_fetch'])
@@ -41,13 +43,43 @@ function faviconFor(url: string): string | undefined {
type WebToolInput = { query?: unknown; count?: unknown; url?: unknown }
type WebToolResult = { content?: unknown; error?: string }
+/**
+ * The most characters a built-in web result may put into the conversation.
+ *
+ * A page enters history verbatim and stays there, so a page-sized one can
+ * exhaust a small model's window on its own. It is held to what an MCP result
+ * is held to: `contextCap`, the budget the model's window affords, and the
+ * user's "Max tool output characters" setting - the tighter of the two, and no
+ * cap at all when that setting is `0`, which means "keep results whole".
+ * Without either, the websearch plugin's own bound still applies.
+ */
+export function webOutputCap(contextCap?: number): number | undefined {
+ const configured = useMCPServers.getState().settings?.maxToolOutputChars
+ if (typeof configured !== 'number' || !Number.isFinite(configured)) {
+ return contextCap && contextCap > 0 ? contextCap : undefined
+ }
+ if (configured <= 0) return undefined
+ return contextCap && contextCap > 0
+ ? Math.min(contextCap, configured)
+ : configured
+}
+
+/** `text` cut to `max` characters, without splitting a surrogate pair. */
+function cutText(text: string, max: number): string {
+ if (max <= 0) return ''
+ const cut = text.slice(0, max)
+ const last = cut.charCodeAt(cut.length - 1)
+ return last >= 0xd800 && last <= 0xdbff ? cut.slice(0, -1) : cut
+}
+
/**
* Execute a native web tool via the websearch plugin and shape web_search
* output into the web-citation payload consumed by parseCitationsFromToolOutput.
*/
export async function executeWebTool(
toolName: string,
- input: WebToolInput
+ input: WebToolInput,
+ options: { maxOutputChars?: number } = {}
): Promise<WebToolResult> {
const { apiKeys, endpoints, searchProvider } = useWebSearchConfig.getState()
const apiKey = apiKeys[searchProvider] || undefined
@@ -74,10 +106,47 @@ export async function executeWebTool(
if (toolName === 'web_fetch') {
const url = typeof input?.url === 'string' ? input.url : ''
const page = await webFetch(url, apiKey, searchProvider, endpoint)
- const text = `Title: ${page.title}\nURL: ${page.url}\n\n${page.content}${
- page.truncated ? '\n\n[content truncated]' : ''
- }`
- return { content: text }
+ const cap = webOutputCap(options.maxOutputChars)
+ let title = page.title
+ let address = page.url
+ let content = page.content
+ let truncated = page.truncated
+ const render = () =>
+ `Title: ${title}\nURL: ${address}\n\n${content}${
+ truncated ? TRUNCATION_MARKER : ''
+ }`
+ const headerLength = () => `Title: ${title}\nURL: ${address}\n\n`.length
+
+ if (cap !== undefined && render().length > cap) {
+ // Over budget: cut the page, and say so - the model reads the marker.
+ truncated = true
+ if (cap - headerLength() - TRUNCATION_MARKER.length < cap / 2) {
+ // The title and url come from the page too, and here they would eat
+ // the budget. The title is cut; a url that long is left out, because
+ // a prefix of it is a different address, and a link built from it
+ // would point somewhere else.
+ const part = Math.floor(cap / 4)
+ title = cutText(title, part)
+ if (address.length > part) address = ''
+ }
+ content = cutText(
+ content,
+ cap - headerLength() - TRUNCATION_MARKER.length
+ )
+ }
+ const text = render()
+ // A budget too small for even the header and the marker: the cap still
+ // holds, and what is left says the page was cut - as the whole marker
+ // when it fits, which is the form `parseWebFetchOutput` recognises -
+ // rather than showing a fragment of a title or an address.
+ return {
+ content:
+ cap !== undefined && text.length > cap
+ ? cap >= TRUNCATION_MARKER.length
+ ? TRUNCATION_MARKER
+ : cutText(TRUNCATION_MARKER.trimStart(), cap)
+ : text,
+ }
}
return { error: `Unknown web tool '${toolName}'` }
} catch (e) {
diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsx
index 16e488915..580311891 100644
--- a/web-app/src/routes/threads/$threadId.tsx
+++ b/web-app/src/routes/threads/$threadId.tsx
@@ -714,12 +714,24 @@ function ThreadDetail() {
// not reported as the tool being slow.
useToolCallRuntime.getState().markRunning(toolCall.toolCallId)
+ // A tool result is injected into conversation history verbatim, so a
+ // page-sized one can exhaust the context on its own. This is the
+ // budget the window this model actually has affords; it is narrowed
+ // against the user's configured ceiling where the result is built.
+ const ctxLen = useModelProvider.getState().selectedModel?.settings
+ ?.ctx_len?.controller_props?.value
+ const maxOutputChars = deriveToolOutputCap(
+ typeof ctxLen === 'number' ? ctxLen : undefined
+ )
+
// Raced against Stop: a call that never returns (a runaway shell,
// a hung MCP server) must not hold the loop, and the thread, busy.
const result = await untilAborted<ToolRunResult>(
(async () => {
if (WEB_TOOL_NAMES.has(toolName)) {
- return await executeWebTool(toolName, toolCall.input)
+ return await executeWebTool(toolName, toolCall.input, {
+ maxOutputChars,
+ })
} else if (CHAT_AGENT_TOOL_NAMES.has(toolName)) {
// Chat's shell runs with the sandbox network closed: the
// default `allowNetwork = false` is the contract here, not an
@@ -749,20 +761,13 @@ function ThreadDetail() {
scope: projectId ? 'project' : 'thread',
})
} else if (mcpToolNames.has(toolName)) {
- // An MCP result is injected into conversation history
- // verbatim, so a page-sized one can exhaust the context on its
- // own. Give the backend a budget scaled to the window this
- // model actually has; it narrows that against the user's
- // configured ceiling. Cancellable, so Stop ends the call on
- // the backend as well as in this loop.
- const ctxLen = useModelProvider.getState().selectedModel
- ?.settings?.ctx_len?.controller_props?.value
+ // Give the backend the budget scaled to the window; it narrows
+ // that against the user's configured ceiling. Cancellable, so
+ // Stop ends the call on the backend as well as in this loop.
const call = serviceHub.mcp().callToolWithCancellation({
toolName,
arguments: toolCall.input,
- maxOutputChars: deriveToolOutputCap(
- typeof ctxLen === 'number' ? ctxLen : undefined
- ),
+ maxOutputChars,
})
const cancel = () => void call.cancel().catch(() => {})
stopSignal.addEventListener('abort', cancel, { once: true })
diff --git a/web-app/src/routes/threads/__tests__/$threadId.test.tsx b/web-app/src/routes/threads/__tests__/$threadId.test.tsx
index a9c89c03f..84283d0fa 100644
--- a/web-app/src/routes/threads/__tests__/$threadId.test.tsx
+++ b/web-app/src/routes/threads/__tests__/$threadId.test.tsx
@@ -453,6 +453,14 @@ vi.mock('@/utils/error', async (importOriginal) => ({
OUT_OF_CONTEXT_SIZE: 'OUT_OF_CONTEXT_SIZE',
}))
+// The built-in web tools run in the webview rather than through the service
+// hub, so a test can see what they were handed.
+const webTool = vi.hoisted(() => ({ executeWebTool: vi.fn() }))
+vi.mock('@/lib/webSearchTool', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/lib/webSearchTool')>()),
+ executeWebTool: webTool.executeWebTool,
+}))
+
// -----------------------------------------------------------------------------
// Import component AFTER mocks
// -----------------------------------------------------------------------------
@@ -1213,6 +1221,38 @@ describe('ThreadDetail route', () => {
}
})
+ // A page is a tool result like any other: held to the budget the window
+ // affords, not the 40,000 characters it used to be allowed (#9170).
+ it('hands a built-in web tool the budget of the active model context window', async () => {
+ webTool.executeWebTool.mockReset()
+ webTool.executeWebTool.mockResolvedValue({ content: 'page' })
+ renderComponent()
+
+ const onToolCall = (
+ h as { capturedOnToolCall: (arg: unknown) => Promise<void> }
+ ).capturedOnToolCall
+ await act(async () => {
+ await onToolCall({
+ toolCall: {
+ toolCallId: 'tcw',
+ toolName: 'web_fetch',
+ input: { url: 'https://example.com' },
+ },
+ })
+ })
+ await act(async () => {
+ await finishWithToolCalls()
+ })
+
+ expect(webTool.executeWebTool).toHaveBeenCalledTimes(1)
+ const [name, input, options] = webTool.executeWebTool.mock.calls[0]
+ expect(name).toBe('web_fetch')
+ expect(input).toEqual({ url: 'https://example.com' })
+ // 4096-token window in the harness: a fraction of it, not the whole thing.
+ expect(options.maxOutputChars).toBeGreaterThan(0)
+ expect(options.maxOutputChars).toBeLessThan(4096 * 3.5)
+ })
+
// A model can request several tools in one turn. They arrive together but
// are executed one at a time, which is what the queue display depends on.
describe('several tool calls in one turn', () => {