Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(chat): restore 2-space formatting, carry dropped turns' attachments forward, test isLocalChatServer and verbatim preset paths
thinhlpgb3fab11f26c3
diff --git a/src-tauri/src/core/system/orphans.rs b/src-tauri/src/core/system/orphans.rsindex c55591898..79a7e78be 100644--- a/src-tauri/src/core/system/orphans.rs+++ b/src-tauri/src/core/system/orphans.rs@@ -402,6 +402,36 @@ mod tests {assert_eq!(victims, vec![200]);}+ #[test]+ fn verbatim_prefixed_preset_paths_match() {+ // 0.8.4 starts its router with `\\?\C:\...`, the form the sweep exists+ // to reap; `\\?\UNC\` is the same rule for a data folder on a share.+ for (pid, preset, data) in [+ (+ 200,+ "\\\\?\\C:\\Users\\u\\AppData\\Roaming\\Jan\\data\\llamacpp\\router.preset.ini",+ "C:\\Users\\u\\AppData\\Roaming\\Jan\\data",+ ),+ (+ 201,+ "\\\\?\\UNC\\srv\\share\\Jan\\data\\llamacpp\\router.preset.ini",+ "\\\\srv\\share\\Jan\\data",+ ),+ ] {+ let router = proc(+ pid,+ Some(4242),+ "llama-server.exe",+ &["llama-server.exe", "--models-preset", preset],+ );+ assert_eq!(+ orphaned_engine_pids(&[router], &PathBuf::from(data)),+ vec![pid],+ "{preset}"+ );+ }+ }+#[test]fn a_parent_cycle_from_pid_reuse_terminates() {// Windows never reparents and reuses pids: the router's dead parent'sdiff --git a/web-app/src/lib/__tests__/custom-chat-transport.test.ts b/web-app/src/lib/__tests__/custom-chat-transport.test.tsindex ae8d48d8d..1bf723fe4 100644--- a/web-app/src/lib/__tests__/custom-chat-transport.test.ts+++ b/web-app/src/lib/__tests__/custom-chat-transport.test.ts@@ -6,6 +6,7 @@ import {coalesceMessagesForAlternation,effectiveContextWindow,hasGenuineUserQuery,+ isLocalChatServer,extractContextInfoFromError,normalizeToolInputSchema,resolveOrphanToolCalls,@@ -14,6 +15,7 @@ import {unwrapRetryError,} from '../custom-chat-transport'import { encodeToolImageSentinel } from '../tool-image-sentinel'+import { encodeAudioSentinel } from '../audio-sentinel'const userMsg = (id: string, text: string): UIMessage =>({@@ -481,6 +483,39 @@ describe('coalesceMessagesForAlternation', () => {expect(out.map((m) => m.id)).toEqual(['u1', 'a1', 'u3'])})+ it("carries a dropped turn's attachments forward, but not its question", () => {+ const image = {+ type: 'file',+ mediaType: 'image/png',+ url: 'data:image/png;base64,AAA',+ } as unknown as UIMessage['parts'][number]+ const audio = { type: 'text', text: encodeAudioSentinel('wav', 'UklG') }+ const docs =+ '[ATTACHED_FILES]\n- file_id: f1, name: a.pdf\n[/ATTACHED_FILES]'+ const input: UIMessage[] = [+ {+ id: 'u1',+ role: 'user',+ parts: [+ { type: 'text', text: `failed question\n\n${docs}` },+ image,+ audio,+ ],+ } as UIMessage,+ assistantMsg('a1', []),+ userMsg('u2', 'what is in it?'),+ ]+ const out = coalesceMessagesForAlternation(input)+ expect(out).toHaveLength(1)+ expect(out[0].id).toBe('u2')+ expect(out[0].parts).toEqual([+ { type: 'text', text: docs },+ image,+ audio,+ { type: 'text', text: 'what is in it?' },+ ])+ })+it('keeps assistant messages with real content', () => {const input = [userMsg('u1', 'q'),@@ -814,3 +849,25 @@ describe('hasGenuineUserQuery', () => {).toBe(true)})})++describe('isLocalChatServer', () => {+ it.each([+ ['llamacpp', undefined],+ ['mlx', undefined],+ ['custom', 'http://localhost:11434/v1'],+ ['custom', 'http://127.0.0.1:8080/v1'],+ ['custom', 'http://[::1]:1234/v1'],+ ])('treats %s at %s as local (no retries)', (provider, baseUrl) => {+ expect(isLocalChatServer(provider, baseUrl)).toBe(true)+ })++ it.each([+ ['openai', 'https://api.openai.com/v1'],+ ['custom', 'http://192.168.1.5:1234/v1'],+ ['custom', 'https://localhost.example.com/v1'],+ ['custom', undefined],+ ['custom', 'not a url'],+ ])('treats %s at %s as hosted (SDK retries)', (provider, baseUrl) => {+ expect(isLocalChatServer(provider, baseUrl)).toBe(false)+ })+})diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.tsindex 7ee48c5de..065848d4d 100644--- a/web-app/src/lib/custom-chat-transport.ts+++ b/web-app/src/lib/custom-chat-transport.ts@@ -1,20 +1,20 @@import { type UIMessage } from '@ai-sdk/react'import {- convertToModelMessages,- streamText,- type ChatRequestOptions,- type ChatTransport,- type LanguageModel,- type UIMessageChunk,- type Tool,- type LanguageModelUsage,- jsonSchema,- InvalidToolInputError,+ convertToModelMessages,+ streamText,+ type ChatRequestOptions,+ type ChatTransport,+ type LanguageModel,+ type UIMessageChunk,+ type Tool,+ type LanguageModelUsage,+ jsonSchema,+ InvalidToolInputError,} from 'ai'import { repairToolArgs } from './toolCallRepair'import {- hasToolImageSentinel,- stripToolImageSentinels,+ hasToolImageSentinel,+ stripToolImageSentinels,} from './tool-image-sentinel'import { useServiceStore } from '@/hooks/useServiceHub'import { useToolAvailable } from '@/hooks/useToolAvailable'@@ -26,17 +26,17 @@ import { useAttachments } from '@/hooks/useAttachments'import { useMCPServers } from '@/hooks/useMCPServers'import { useWebSearchConfig } from '@/hooks/useWebSearchConfig'import {- WEB_SEARCH_DESCRIPTION,- WEB_SEARCH_INPUT_SCHEMA,- WEB_FETCH_DESCRIPTION,- WEB_FETCH_INPUT_SCHEMA,+ WEB_SEARCH_DESCRIPTION,+ WEB_SEARCH_INPUT_SCHEMA,+ WEB_FETCH_DESCRIPTION,+ WEB_FETCH_INPUT_SCHEMA,} from '@/lib/webSearchTool'import {- CHAT_AGENT_TOOL_NAMES,- getAgentToolSchemas,- memoryDigestNow,- refreshMemoryDigest,- sandboxEnforces,+ CHAT_AGENT_TOOL_NAMES,+ getAgentToolSchemas,+ memoryDigestNow,+ refreshMemoryDigest,+ sandboxEnforces,} from '@/lib/agentTools'import { useAppState, type ModelLoadProgress } from '@/hooks/useAppState'import { unloadLlamaModel, getLoadedModels } from '@janhq/tauri-plugin-llamacpp-api'@@ -44,69 +44,77 @@ import { engineFailure } from '@/lib/engineError'import { ExtensionManager } from '@/lib/extension'import { getLlamacppExtension } from '@/lib/llamacppRouterProps'import {- tokensForThinkingBudgetLevel,- isThinkingBudgetLevelKey,+ tokensForThinkingBudgetLevel,+ isThinkingBudgetLevelKey,} from '@/lib/thinkingBudget'import { buildReasoningProviderOptions } from '@/lib/reasoningProviderOptions'import {- ExtensionTypeEnum,- VectorDBExtension,- type MCPTool,+ ExtensionTypeEnum,+ VectorDBExtension,+ type MCPTool,} from '@janhq/core'import {- trimMessages,- compactMessages,- estimateTokens,- type ContextManagerConfig,+ trimMessages,+ compactMessages,+ estimateTokens,+ type ContextManagerConfig,} from './context-manager'import { mcpOrchestrator } from '@/lib/mcp-orchestrator'import { isRouterModelSelectable } from '@/lib/mcp-router-model-filter'-import { encodeAudioSentinel, parseAudioDataUrl } from '@/lib/audio-sentinel'-import { encodeVideoSentinel, parseVideoDataUrl } from '@/lib/video-sentinel'+import {+ encodeAudioSentinel,+ hasAudioSentinel,+ parseAudioDataUrl,+} from '@/lib/audio-sentinel'+import {+ encodeVideoSentinel,+ hasVideoSentinel,+ parseVideoDataUrl,+} from '@/lib/video-sentinel'import { isPredefinedRemoteProvider } from '@/lib/providerCaps'import { paramsSettings } from '@/lib/predefinedParams'import { CHAT_SLOT_ID } from '@/constants/models'import { createStepMetadata } from '@/lib/stepMetadata'export type TokenUsageCallback = (- usage: LanguageModelUsage,- messageId: string+ usage: LanguageModelUsage,+ messageId: string) => voidexport type StreamingTokenSpeedCallback = (- tokenCount: number,- elapsedMs: number+ tokenCount: number,+ elapsedMs: number) => voidexport type OnFinishCallback = (params: {- message: UIMessage- isAbort?: boolean+ message: UIMessage+ isAbort?: boolean}) => void/** Partial assistant output replayed as a prefill to resume a stopped turn. */export type ContinuationContent = { text?: string; reasoning?: string }export type ServiceHub = {- rag(): {- getTools(): Promise<- Array<{ name: string; description: string; inputSchema: unknown }>- >- }- mcp(): {- getTools(): Promise<MCPTool[]>- /** TauriMCPService only */- getToolsForServers?(serverNames: string[]): Promise<MCPTool[]>- /** TauriMCPService only */- getServerSummaries?(): Promise<- Array<{ name: string; capabilities: string[]; description: string }>- >- }+ rag(): {+ getTools(): Promise<+ Array<{ name: string; description: string; inputSchema: unknown }>+ >+ }+ mcp(): {+ getTools(): Promise<MCPTool[]>+ /** TauriMCPService only */+ getToolsForServers?(serverNames: string[]): Promise<MCPTool[]>+ /** TauriMCPService only */+ getServerSummaries?(): Promise<+ Array<{ name: string; capabilities: string[]; description: string }>+ >+ }}const SCHEMA_PRIMITIVE_TYPES = new Set([- 'string',- 'number',- 'integer',- 'boolean',- 'null',- 'array',- 'object',+ 'string',+ 'number',+ 'integer',+ 'boolean',+ 'null',+ 'array',+ 'object',])const SCHEMA_NODE_MAP_KEYS = new Set(['properties', 'patternProperties', 'definitions', '$defs'])@@ -118,20 +126,20 @@ const SCHEMA_NODE_LIST_KEYS = new Set(['anyOf', 'oneOf', 'allOf', 'prefixItems']// regenerating the preset and reloading the engine. Assistant `parameters`// override these in the merge.const MODEL_SAMPLING_SETTING_KEYS = [- 'temperature',- 'top_k',- 'top_p',- 'min_p',- 'repeat_last_n',- 'repeat_penalty',- 'presence_penalty',- 'frequency_penalty',+ 'temperature',+ 'top_k',+ 'top_p',+ 'min_p',+ 'repeat_last_n',+ 'repeat_penalty',+ 'presence_penalty',+ 'frequency_penalty',] as const/** Keys whose upstream handler throws on a negative value. */const NON_NEGATIVE_SAMPLING_KEYS = new Set<string>([- 'repeat_last_n',- 'dry_penalty_last_n',+ 'repeat_last_n',+ 'dry_penalty_last_n',])/**@@ -140,48 +148,48 @@ const NON_NEGATIVE_SAMPLING_KEYS = new Set<string>([* always forwarded.*/const UPSTREAM_SAMPLING_DEFAULTS: Record<string, number> = {- temperature: 0.8,- top_k: 40,- top_p: 0.95,- min_p: 0.05,- repeat_last_n: 64,- repeat_penalty: 1.0,+ temperature: 0.8,+ top_k: 40,+ top_p: 0.95,+ min_p: 0.05,+ repeat_last_n: 64,+ repeat_penalty: 1.0,}function extractModelSamplingDefaults(- model: Model | null | undefined+ model: Model | null | undefined): Record<string, unknown> {- if (!model?.settings) return {}- const out: Record<string, unknown> = {}- for (const key of MODEL_SAMPLING_SETTING_KEYS) {- const raw = model.settings[key]?.controller_props?.value- if (raw === undefined || raw === null || raw === '') continue- // Sidebar inputs are string-typed even when controller_props.type is- // 'number'; coerce so the request body matches the OpenAI schema.- let value: unknown = raw- if (typeof raw === 'string') {- const n = Number(raw)- if (!Number.isFinite(n)) continue- value = n- }- // The server rejects a negative window outright rather than clamping, so a- // value left over from the old "-1 = full context" UI would 400 every- // request. Dropping it lets the server's own default apply.- if (- NON_NEGATIVE_SAMPLING_KEYS.has(key) &&- typeof value === 'number' &&- value < 0- ) {- continue+ if (!model?.settings) return {}+ const out: Record<string, unknown> = {}+ for (const key of MODEL_SAMPLING_SETTING_KEYS) {+ const raw = model.settings[key]?.controller_props?.value+ if (raw === undefined || raw === null || raw === '') continue+ // Sidebar inputs are string-typed even when controller_props.type is+ // 'number'; coerce so the request body matches the OpenAI schema.+ let value: unknown = raw+ if (typeof raw === 'string') {+ const n = Number(raw)+ if (!Number.isFinite(n)) continue+ value = n+ }+ // The server rejects a negative window outright rather than clamping, so a+ // value left over from the old "-1 = full context" UI would 400 every+ // request. Dropping it lets the server's own default apply.+ if (+ NON_NEGATIVE_SAMPLING_KEYS.has(key) &&+ typeof value === 'number' &&+ value < 0+ ) {+ continue+ }+ // Forwarding a value equal to llama.cpp's default is not a no-op: it sets a+ // bit that suppresses the GGUF's own recommended sampling, so an+ // untouched-looking default would silently override what the model asked+ // for. Same rule preset.ts applies.+ if (UPSTREAM_SAMPLING_DEFAULTS[key] === value) continue+ out[key] = value}- // Forwarding a value equal to llama.cpp's default is not a no-op: it sets a- // bit that suppresses the GGUF's own recommended sampling, so an- // untouched-looking default would silently override what the model asked- // for. Same rule preset.ts applies.- if (UPSTREAM_SAMPLING_DEFAULTS[key] === value) continue- out[key] = value- }- return out+ return out}/**@@ -191,20 +199,20 @@ function extractModelSamplingDefaults(* and is dropped here.*/function extractModelTemplateKwargs(- model: Model | null | undefined+ model: Model | null | undefined): Record<string, boolean | number | string> {- const raw: unknown =- model?.settings?.chat_template_kwargs?.controller_props?.value- if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {}- const out: Record<string, boolean | number | string> = {}- for (const [key, value] of Object.entries(raw)) {- if (key === 'enable_thinking') continue- const t = typeof value- if (t === 'boolean' || t === 'number' || t === 'string') {- out[key] = value as boolean | number | string+ const raw: unknown =+ model?.settings?.chat_template_kwargs?.controller_props?.value+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {}+ const out: Record<string, boolean | number | string> = {}+ for (const [key, value] of Object.entries(raw)) {+ if (key === 'enable_thinking') continue+ const t = typeof value+ if (t === 'boolean' || t === 'number' || t === 'string') {+ out[key] = value as boolean | number | string+ }}- }- return out+ return out}/**@@ -216,43 +224,43 @@ function extractModelTemplateKwargs(* was picked in ChatInput.*/async function resolveThinkingBudgetTokens(- model: Model | null | undefined,- modelId: string | undefined+ model: Model | null | undefined,+ modelId: string | undefined): Promise<number | undefined> {- const rawLevel = model?.settings?.thinking_budget_tokens?.controller_props?.value- if (!isThinkingBudgetLevelKey(rawLevel)) return undefined- if (rawLevel === 'unlimited') return -1+ const rawLevel = model?.settings?.thinking_budget_tokens?.controller_props?.value+ if (!isThinkingBudgetLevelKey(rawLevel)) return undefined+ if (rawLevel === 'unlimited') return -1- let contextSize: number | undefined- if (modelId) {- try {- contextSize = (await getLlamacppExtension()?.getModelProps?.(modelId))?.nCtx- } catch {- // Model not loaded yet or router unreachable; fall through to configured/default.+ let contextSize: number | undefined+ if (modelId) {+ try {+ contextSize = (await getLlamacppExtension()?.getModelProps?.(modelId))?.nCtx+ } catch {+ // Model not loaded yet or router unreachable; fall through to configured/default.+ }}- }- if (!contextSize) {- const configured = model?.settings?.ctx_len?.controller_props?.value- contextSize =- typeof configured === 'number'- ? configured- : typeof configured === 'string' && configured !== ''- ? Number(configured)- : undefined- }- return tokensForThinkingBudgetLevel(rawLevel, contextSize || 8192)+ if (!contextSize) {+ const configured = model?.settings?.ctx_len?.controller_props?.value+ contextSize =+ typeof configured === 'number'+ ? configured+ : typeof configured === 'string' && configured !== ''+ ? Number(configured)+ : undefined+ }+ return tokensForThinkingBudgetLevel(rawLevel, contextSize || 8192)}export function effectiveContextWindow(- configuredContextTokens: number,- liveContextTokens: number | undefined,- contextShiftEnabled: boolean+ configuredContextTokens: number,+ liveContextTokens: number | undefined,+ contextShiftEnabled: boolean): number {- return contextShiftEnabled &&- typeof liveContextTokens === 'number' &&- liveContextTokens > 0- ? liveContextTokens- : configuredContextTokens+ return contextShiftEnabled &&+ typeof liveContextTokens === 'number' &&+ liveContextTokens > 0+ ? liveContextTokens+ : configuredContextTokens}@@ -265,89 +273,89 @@ export function effectiveContextWindow(* grammar generator sees a well-formed schema.*/function coerceSchemaNode(value: unknown): unknown {- if (typeof value === 'string' && SCHEMA_PRIMITIVE_TYPES.has(value)) {- return normalizeToolInputSchemaValue({ type: value })- }- return normalizeToolInputSchemaValue(value)+ if (typeof value === 'string' && SCHEMA_PRIMITIVE_TYPES.has(value)) {+ return normalizeToolInputSchemaValue({ type: value })+ }+ return normalizeToolInputSchemaValue(value)}function normalizeToolInputSchemaValue(value: unknown): unknown {- if (Array.isArray(value)) {- return value.map(normalizeToolInputSchemaValue)- }-- if (!value || typeof value !== 'object') {- return value- }-- const normalized = Object.fromEntries(- Object.entries(value as Record<string, unknown>).map(([key, childValue]) => {- // Schema-node containers: their direct children are sub-schemas, so a- // bare-string primitive type name should expand to `{ type: <name> }`.- if (- SCHEMA_NODE_MAP_KEYS.has(key) &&- childValue &&- typeof childValue === 'object' &&- !Array.isArray(childValue)- ) {- return [- key,- Object.fromEntries(- Object.entries(childValue as Record<string, unknown>).map(- ([propKey, propVal]) => [propKey, coerceSchemaNode(propVal)]- )- ),- ]- }- if (SCHEMA_NODE_LIST_KEYS.has(key) && Array.isArray(childValue)) {- return [key, childValue.map(coerceSchemaNode)]- }- if (key === 'items') {- if (Array.isArray(childValue)) return [key, childValue.map(coerceSchemaNode)]- return [key, coerceSchemaNode(childValue)]- }- return [key, normalizeToolInputSchemaValue(childValue)]- })- )-- const hasDescription = Object.prototype.hasOwnProperty.call(normalized, 'description')- const hasType = Object.prototype.hasOwnProperty.call(normalized, 'type')- const hasNestedSchemaKeywords =- Object.prototype.hasOwnProperty.call(normalized, 'properties') ||- Object.prototype.hasOwnProperty.call(normalized, 'items') ||- Object.prototype.hasOwnProperty.call(normalized, 'anyOf') ||- Object.prototype.hasOwnProperty.call(normalized, 'oneOf') ||- Object.prototype.hasOwnProperty.call(normalized, 'allOf') ||- Object.prototype.hasOwnProperty.call(normalized, '$ref')-- if (normalized.type === 'object' && !Object.prototype.hasOwnProperty.call(normalized, 'properties')) {- normalized.properties = {}- }-- if (hasDescription && !hasType && !hasNestedSchemaKeywords) {- normalized.type = 'string'- }-- // llama.cpp's json-schema-to-grammar emits PCRE `\d` for these formats,- // which GBNF rejects; the failed grammar silently disables tool-call JSON.- if (- typeof normalized.format === 'string' &&- LLAMACPP_BROKEN_STRING_FORMATS.has(normalized.format as string)- ) {- delete normalized.format- }-- // `pattern` is the same PCRE-to-GBNF trap as `format`: any pattern that- // uses `\d`, `\w`, or `\s` (extremely common in date/time/uuid regexes)- // fails GBNF compilation. The model still has `type` and `description`.- if (- typeof normalized.pattern === 'string' &&- PCRE_SHORTHAND.test(normalized.pattern as string)- ) {- delete normalized.pattern- }-- return normalized+ if (Array.isArray(value)) {+ return value.map(normalizeToolInputSchemaValue)+ }++ if (!value || typeof value !== 'object') {+ return value+ }++ const normalized = Object.fromEntries(+ Object.entries(value as Record<string, unknown>).map(([key, childValue]) => {+ // Schema-node containers: their direct children are sub-schemas, so a+ // bare-string primitive type name should expand to `{ type: <name> }`.+ if (+ SCHEMA_NODE_MAP_KEYS.has(key) &&+ childValue &&+ typeof childValue === 'object' &&+ !Array.isArray(childValue)+ ) {+ return [+ key,+ Object.fromEntries(+ Object.entries(childValue as Record<string, unknown>).map(+ ([propKey, propVal]) => [propKey, coerceSchemaNode(propVal)]+ )+ ),+ ]+ }+ if (SCHEMA_NODE_LIST_KEYS.has(key) && Array.isArray(childValue)) {+ return [key, childValue.map(coerceSchemaNode)]+ }+ if (key === 'items') {+ if (Array.isArray(childValue)) return [key, childValue.map(coerceSchemaNode)]+ return [key, coerceSchemaNode(childValue)]+ }+ return [key, normalizeToolInputSchemaValue(childValue)]+ })+ )++ const hasDescription = Object.prototype.hasOwnProperty.call(normalized, 'description')+ const hasType = Object.prototype.hasOwnProperty.call(normalized, 'type')+ const hasNestedSchemaKeywords =+ Object.prototype.hasOwnProperty.call(normalized, 'properties') ||+ Object.prototype.hasOwnProperty.call(normalized, 'items') ||+ Object.prototype.hasOwnProperty.call(normalized, 'anyOf') ||+ Object.prototype.hasOwnProperty.call(normalized, 'oneOf') ||+ Object.prototype.hasOwnProperty.call(normalized, 'allOf') ||+ Object.prototype.hasOwnProperty.call(normalized, '$ref')++ if (normalized.type === 'object' && !Object.prototype.hasOwnProperty.call(normalized, 'properties')) {+ normalized.properties = {}+ }++ if (hasDescription && !hasType && !hasNestedSchemaKeywords) {+ normalized.type = 'string'+ }++ // llama.cpp's json-schema-to-grammar emits PCRE `\d` for these formats,+ // which GBNF rejects; the failed grammar silently disables tool-call JSON.+ if (+ typeof normalized.format === 'string' &&+ LLAMACPP_BROKEN_STRING_FORMATS.has(normalized.format as string)+ ) {+ delete normalized.format+ }++ // `pattern` is the same PCRE-to-GBNF trap as `format`: any pattern that+ // uses `\d`, `\w`, or `\s` (extremely common in date/time/uuid regexes)+ // fails GBNF compilation. The model still has `type` and `description`.+ if (+ typeof normalized.pattern === 'string' &&+ PCRE_SHORTHAND.test(normalized.pattern as string)+ ) {+ delete normalized.pattern+ }++ return normalized}const LLAMACPP_BROKEN_STRING_FORMATS = new Set(['date', 'time', 'date-time'])@@ -360,17 +368,47 @@ const PCRE_SHORTHAND = /\\[dDwWsS]/* placeholder in the message list with empty parts.*/function isAssistantMessageEmpty(message: UIMessage): boolean {- if (message.role !== 'assistant') return false- const parts = Array.isArray(message.parts) ? message.parts : []- if (parts.length === 0) return true- return parts.every((part) => {- const type = (part as { type?: string }).type- if (type === 'text' || type === 'reasoning') {- const text = (part as { text?: string }).text- return typeof text !== 'string' || text.trim().length === 0+ if (message.role !== 'assistant') return false+ const parts = Array.isArray(message.parts) ? message.parts : []+ if (parts.length === 0) return true+ return parts.every((part) => {+ const type = (part as { type?: string }).type+ if (type === 'text' || type === 'reasoning') {+ const text = (part as { text?: string }).text+ return typeof text !== 'string' || text.trim().length === 0+ }+ return false+ })+}++/**+ * Parts of an unanswered user turn to keep when a newer user turn replaces it:+ * its attachments, but not its question. The UI still shows those attachments+ * in the earlier bubble, so a follow-up like "what is in it?" must still reach+ * the model with them. By this point images are `file` parts, audio and video+ * are sentinel-only text parts, and documents are an [ATTACHED_FILES] block+ * (plus any inlined contents) appended after the question text.+ */+function carryAttachmentsForward(+ dropped: UIMessage['parts'],+ kept: UIMessage['parts']+): UIMessage['parts'] {+ const attachments: UIMessage['parts'] = []+ for (const part of Array.isArray(dropped) ? dropped : []) {+ if (part.type === 'file') {+ attachments.push(part)+ } else if (part.type === 'text' && typeof part.text === 'string') {+ if (hasAudioSentinel(part.text) || hasVideoSentinel(part.text)) {+ attachments.push(part)+ continue+ }+ const filesAt = part.text.indexOf('[ATTACHED_FILES]')+ if (filesAt !== -1) {+ attachments.push({ ...part, text: part.text.slice(filesAt) })+ }+ }}- return false- })+ return [...attachments, ...(Array.isArray(kept) ? kept : [])]}/**@@ -387,8 +425,9 @@ function isAssistantMessageEmpty(message: UIMessage): boolean {** 1. Dropping assistant placeholders with no content (failed turns).* 2. Keeping only the last of any adjacent user messages. The earlier ones- * were never answered; merging them would resend a failed question inside- * the next one while the UI shows them as separate bubbles.+ * were never answered; merging their text would resend a failed question+ * inside the next one while the UI shows them as separate bubbles. Their+ * attachments are carried forward (see carryAttachmentsForward).** Adjacent assistant messages are intentionally left alone: the Anthropic* serial-tool-use wave-split in `sendMessages` deliberately produces them.@@ -418,95 +457,95 @@ function isAssistantMessageEmpty(message: UIMessage): boolean {* Returns null unless both fields are present and numeric.*/export function extractContextInfoFromError(- error: unknown+ error: unknown): { nPromptTokens: number; nCtx: number } | null {- if (!error || typeof error !== 'object') return null- const responseBody = (error as { responseBody?: unknown }).responseBody- if (typeof responseBody !== 'string' || responseBody.length === 0) return null- try {- const parsed = JSON.parse(responseBody) as {- error?: { n_prompt_tokens?: unknown; n_ctx?: unknown }+ if (!error || typeof error !== 'object') return null+ const responseBody = (error as { responseBody?: unknown }).responseBody+ if (typeof responseBody !== 'string' || responseBody.length === 0) return null+ try {+ const parsed = JSON.parse(responseBody) as {+ error?: { n_prompt_tokens?: unknown; n_ctx?: unknown }+ }+ const inner = parsed?.error+ if (!inner || typeof inner !== 'object') return null+ const nPromptTokens = (inner as Record<string, unknown>).n_prompt_tokens+ const nCtx = (inner as Record<string, unknown>).n_ctx+ if (typeof nPromptTokens !== 'number' || typeof nCtx !== 'number') return null+ return { nPromptTokens, nCtx }+ } catch {+ return null}- const inner = parsed?.error- if (!inner || typeof inner !== 'object') return null- const nPromptTokens = (inner as Record<string, unknown>).n_prompt_tokens- const nCtx = (inner as Record<string, unknown>).n_ctx- if (typeof nPromptTokens !== 'number' || typeof nCtx !== 'number') return null- return { nPromptTokens, nCtx }- } catch {- return null- }}export function unwrapRetryError(error: unknown): unknown {- if (!error || typeof error !== 'object') return error- const errors = (error as { errors?: unknown }).errors- if (Array.isArray(errors) && errors.length > 0) {- return errors[errors.length - 1] ?? error- }- return error+ if (!error || typeof error !== 'object') return error+ const errors = (error as { errors?: unknown }).errors+ if (Array.isArray(errors) && errors.length > 0) {+ return errors[errors.length - 1] ?? error+ }+ return error}const RETRY_PREFIX_RE = /^Failed after \d+ attempts\. Last error: /const RETRY_NONRETRYABLE_RE = /^Failed after \d+ attempts with non-retryable error: '(.+)'$/sexport function stripRetryErrorWrapper(message: string): string {- if (typeof message !== 'string') return message- const m = message.match(RETRY_NONRETRYABLE_RE)- if (m) return m[1]- return message.replace(RETRY_PREFIX_RE, '')+ if (typeof message !== 'string') return message+ const m = message.match(RETRY_NONRETRYABLE_RE)+ if (m) return m[1]+ return message.replace(RETRY_PREFIX_RE, '')}export function stripUnsupportedImageParts(- messages: UIMessage[],- modelSupportsVision: boolean+ messages: UIMessage[],+ modelSupportsVision: boolean): UIMessage[] {- if (modelSupportsVision) return messages- return messages.map((message) => {- if (!Array.isArray(message.parts) || message.parts.length === 0) {- return message- }- let touched = false- const nextParts = message.parts- .filter((part) => {- const type = (part as { type?: string }).type- if (type === 'image') {- touched = true- return false- }- if (type === 'file') {- const mediaType = (part as { mediaType?: string }).mediaType- if (typeof mediaType === 'string' && mediaType.startsWith('image/')) {- touched = true- return false- }- }- return true- })- .map((part) => {- // A tool image (see tool-image-sentinel.ts) would decode into an- // image_url part on the tool message; a text-only model rejects that.- const output = (part as { output?: unknown }).output- if (typeof output !== 'string' || !hasToolImageSentinel(output)) {- return part+ if (modelSupportsVision) return messages+ return messages.map((message) => {+ if (!Array.isArray(message.parts) || message.parts.length === 0) {+ return message}- touched = true- return {- ...part,- output: stripToolImageSentinels(output, TOOL_IMAGE_OMITTED),- } as typeof part- })- if (!touched) return message- return { ...message, parts: nextParts } as UIMessage- })+ let touched = false+ const nextParts = message.parts+ .filter((part) => {+ const type = (part as { type?: string }).type+ if (type === 'image') {+ touched = true+ return false+ }+ if (type === 'file') {+ const mediaType = (part as { mediaType?: string }).mediaType+ if (typeof mediaType === 'string' && mediaType.startsWith('image/')) {+ touched = true+ return false+ }+ }+ return true+ })+ .map((part) => {+ // A tool image (see tool-image-sentinel.ts) would decode into an+ // image_url part on the tool message; a text-only model rejects that.+ const output = (part as { output?: unknown }).output+ if (typeof output !== 'string' || !hasToolImageSentinel(output)) {+ return part+ }+ touched = true+ return {+ ...part,+ output: stripToolImageSentinels(output, TOOL_IMAGE_OMITTED),+ } as typeof part+ })+ if (!touched) return message+ return { ...message, parts: nextParts } as UIMessage+ })}const TOOL_IMAGE_OMITTED = ' (image omitted: the model has no vision)'const RESOLVED_TOOL_STATES = new Set([- 'output-available',- 'output-error',- 'output-denied',+ 'output-available',+ 'output-error',+ 'output-denied',])/**@@ -526,32 +565,32 @@ const RESOLVED_TOOL_STATES = new Set([* reasoning instead of dropping the whole turn.*/export function resolveOrphanToolCalls(messages: UIMessage[]): UIMessage[] {- return messages.map((message) => {- if (message.role !== 'assistant') return message- const parts = Array.isArray(message.parts) ? message.parts : []- if (parts.length === 0) return message-- let mutated = false- const nextParts = parts.map((part) => {- const type = (part as { type?: string }).type- if (typeof type !== 'string' || !type.startsWith('tool-')) return part- const state = (part as { state?: string }).state- if (typeof state === 'string' && RESOLVED_TOOL_STATES.has(state)) {- return part- }- mutated = true- return {- ...(part as object),- state: 'output-error',- errorText:- (part as { errorText?: string }).errorText ??- 'Tool call did not complete (interrupted by an earlier error).',- } as typeof part- })+ return messages.map((message) => {+ if (message.role !== 'assistant') return message+ const parts = Array.isArray(message.parts) ? message.parts : []+ if (parts.length === 0) return message++ let mutated = false+ const nextParts = parts.map((part) => {+ const type = (part as { type?: string }).type+ if (typeof type !== 'string' || !type.startsWith('tool-')) return part+ const state = (part as { state?: string }).state+ if (typeof state === 'string' && RESOLVED_TOOL_STATES.has(state)) {+ return part+ }+ mutated = true+ return {+ ...(part as object),+ state: 'output-error',+ errorText:+ (part as { errorText?: string }).errorText ??+ 'Tool call did not complete (interrupted by an earlier error).',+ } as typeof part+ })- if (!mutated) return message- return { ...message, parts: nextParts }- })+ if (!mutated) return message+ return { ...message, parts: nextParts }+ })}/**@@ -574,72 +613,75 @@ export function resolveOrphanToolCalls(messages: UIMessage[]): UIMessage[] {* parts, is returned unchanged.*/export function splitAssistantToolWaves(messages: UIMessage[]): UIMessage[] {- return messages.flatMap((message) => {- if (message.role !== 'assistant') return [message]-- const parts = Array.isArray(message.parts) ? message.parts : []- if (parts.length === 0) return [message]-- const isToolPart = (p: (typeof parts)[number]) =>- typeof p.type === 'string' && p.type.startsWith('tool-')-- const waves: (typeof parts)[] = []- let currentWave: typeof parts = []- let seenToolParts = false-- for (const part of parts) {- if (isToolPart(part)) {- seenToolParts = true- currentWave.push(part)- } else if (seenToolParts) {- waves.push(currentWave)- currentWave = [part]- seenToolParts = false- } else {- currentWave.push(part)- }- }- if (currentWave.length > 0) waves.push(currentWave)+ return messages.flatMap((message) => {+ if (message.role !== 'assistant') return [message]++ const parts = Array.isArray(message.parts) ? message.parts : []+ if (parts.length === 0) return [message]++ const isToolPart = (p: (typeof parts)[number]) =>+ typeof p.type === 'string' && p.type.startsWith('tool-')++ const waves: (typeof parts)[] = []+ let currentWave: typeof parts = []+ let seenToolParts = false++ for (const part of parts) {+ if (isToolPart(part)) {+ seenToolParts = true+ currentWave.push(part)+ } else if (seenToolParts) {+ waves.push(currentWave)+ currentWave = [part]+ seenToolParts = false+ } else {+ currentWave.push(part)+ }+ }+ if (currentWave.length > 0) waves.push(currentWave)- if (waves.length <= 1) return [message]+ if (waves.length <= 1) return [message]- return waves.map((waveParts, i) => ({- ...message,- id: `${message.id}_w${i}`,- parts: waveParts,- }))- })+ return waves.map((waveParts, i) => ({+ ...message,+ id: `${message.id}_w${i}`,+ parts: waveParts,+ }))+ })}export function coalesceMessagesForAlternation(- messages: UIMessage[]+ messages: UIMessage[]): UIMessage[] {- const filtered = messages.filter((m) => !isAssistantMessageEmpty(m))- if (filtered.length <= 1) return filtered-- const out: UIMessage[] = [filtered[0]]- for (let i = 1; i < filtered.length; i++) {- const prev = out[out.length - 1]- const cur = filtered[i]- // The earlier user turn was never answered; send only the newer one.- if (prev.role === 'user' && cur.role === 'user') {- out[out.length - 1] = cur- } else {- out.push(cur)+ const filtered = messages.filter((m) => !isAssistantMessageEmpty(m))+ if (filtered.length <= 1) return filtered++ const out: UIMessage[] = [filtered[0]]+ for (let i = 1; i < filtered.length; i++) {+ const prev = out[out.length - 1]+ const cur = filtered[i]+ if (prev.role === 'user' && cur.role === 'user') {+ out[out.length - 1] = {+ ...cur,+ parts: carryAttachmentsForward(prev.parts, cur.parts),+ }+ } else {+ out.push(cur)+ }}- }- return out+ return out}const LOCAL_ENGINE_PROVIDERS: Record<string, true> = {- llamacpp: true,- mlx: true,+ llamacpp: true,+ mlx: true,}const LOOPBACK_HOSTS: Record<string, true> = {- localhost: true,- '127.0.0.1': true,- '[::1]': true,+ localhost: true,+ '127.0.0.1': true,+ // URL.hostname keeps the brackets on IPv6 literals.+ '[::1]': true,}/**@@ -648,16 +690,16 @@ const LOOPBACK_HOSTS: Record<string, true> = {* whole prompt, so such requests are not retried.*/export function isLocalChatServer(- providerId: string,- baseUrl: string | undefined+ providerId: string,+ baseUrl: string | undefined): boolean {- if (LOCAL_ENGINE_PROVIDERS[providerId]) return true- if (!baseUrl) return false- try {- return !!LOOPBACK_HOSTS[new URL(baseUrl).hostname]- } catch {- return false- }+ if (LOCAL_ENGINE_PROVIDERS[providerId]) return true+ if (!baseUrl) return false+ try {+ return !!LOOPBACK_HOSTS[new URL(baseUrl).hostname]+ } catch {+ return false+ }}const TOOL_RESPONSE_ONLY = /^<tool_response>[\s\S]*<\/tool_response>$/@@ -670,23 +712,23 @@ const TOOL_RESPONSE_ONLY = /^<tool_response>[\s\S]*<\/tool_response>$/* eviction drops it. Guard the send so we fail with a clear message instead.*/export function hasGenuineUserQuery(messages: UIMessage[]): boolean {- return messages.some((m) => {- if (m.role !== 'user') return false- const text = (m.parts ?? [])- .map((p) => (p.type === 'text' ? (p.text ?? '') : ''))- .join('')- .trim()- return text.length > 0 && !TOOL_RESPONSE_ONLY.test(text)- })+ return messages.some((m) => {+ if (m.role !== 'user') return false+ const text = (m.parts ?? [])+ .map((p) => (p.type === 'text' ? (p.text ?? '') : ''))+ .join('')+ .trim()+ return text.length > 0 && !TOOL_RESPONSE_ONLY.test(text)+ })}type ToolInputSchema = Record<string, unknown>// Keep this behavior aligned with `normalize_openai_tool_parameters_schema` in Rust.export function normalizeToolInputSchema(- schema: ToolInputSchema+ schema: ToolInputSchema): ToolInputSchema {- return normalizeToolInputSchemaValue(schema) as ToolInputSchema+ return normalizeToolInputSchemaValue(schema) as ToolInputSchema}/** Text from the most recent user message (for MCP server routing). */@@ -705,43 +747,43 @@ type ChatTemplateKwargs = Record<string, boolean | number | string>* user-supplied value. The function is a no-op for non-llamacpp providers.*/export function buildLlamacppReasoningParams(- providerName: string | null | undefined,- reasoning: 'auto' | 'on' | 'off' | undefined,- userKwargs?: ChatTemplateKwargs | null+ providerName: string | null | undefined,+ reasoning: 'auto' | 'on' | 'off' | undefined,+ userKwargs?: ChatTemplateKwargs | null): { chat_template_kwargs?: ChatTemplateKwargs } {- if (providerName !== 'llamacpp') return {}- const kwargs: ChatTemplateKwargs = {}- if (userKwargs && typeof userKwargs === 'object') {- for (const [key, value] of Object.entries(userKwargs)) {- if (key === 'enable_thinking') continue- const t = typeof value- if (t === 'boolean' || t === 'number' || t === 'string') {- kwargs[key] = value- }+ if (providerName !== 'llamacpp') return {}+ const kwargs: ChatTemplateKwargs = {}+ if (userKwargs && typeof userKwargs === 'object') {+ for (const [key, value] of Object.entries(userKwargs)) {+ if (key === 'enable_thinking') continue+ const t = typeof value+ if (t === 'boolean' || t === 'number' || t === 'string') {+ kwargs[key] = value+ }+ }}- }- if (reasoning === 'on' || reasoning === 'off') {- kwargs.enable_thinking = reasoning === 'on'- }- if (Object.keys(kwargs).length === 0) return {}- return { chat_template_kwargs: kwargs }+ if (reasoning === 'on' || reasoning === 'off') {+ kwargs.enable_thinking = reasoning === 'on'+ }+ if (Object.keys(kwargs).length === 0) return {}+ return { chat_template_kwargs: kwargs }}function extractLatestUserText(messages: UIMessage[]): string {- for (let i = messages.length - 1; i >= 0; i--) {- const m = messages[i]- if (m.role !== 'user') continue- const parts = Array.isArray(m.parts) ? m.parts : []- const chunks: string[] = []- for (const p of parts) {- if (p.type === 'text' && typeof (p as { text?: string }).text === 'string') {- const t = (p as { text: string }).text.trim()- if (t) chunks.push(t)- }+ for (let i = messages.length - 1; i >= 0; i--) {+ const m = messages[i]+ if (m.role !== 'user') continue+ const parts = Array.isArray(m.parts) ? m.parts : []+ const chunks: string[] = []+ for (const p of parts) {+ if (p.type === 'text' && typeof (p as { text?: string }).text === 'string') {+ const t = (p as { text: string }).text.trim()+ if (t) chunks.push(t)+ }+ }+ if (chunks.length > 0) return chunks.join('\n')}- if (chunks.length > 0) return chunks.join('\n')- }- return ''+ return ''}/**@@ -751,1070 +793,1070 @@ function extractLatestUserText(messages: UIMessage[]): string {* makes the continuation look seamless instead of dropping the partial output.*/function prependContinuationToUIStream(- stream: ReadableStream<UIMessageChunk>,- prefix: ContinuationContent+ stream: ReadableStream<UIMessageChunk>,+ prefix: ContinuationContent): ReadableStream<UIMessageChunk> {- const reader = stream.getReader()- let reasoningEmitted = !prefix.reasoning- let textEmitted = !prefix.text- return new ReadableStream<UIMessageChunk>({- async pull(controller) {- try {- const { done, value } = await reader.read()- if (done) {- controller.close()- return- }- controller.enqueue(value)- const type = (value as { type: string }).type- if (!reasoningEmitted && type === 'reasoning-start') {- reasoningEmitted = true- const id = (value as { id: string }).id- controller.enqueue({- type: 'reasoning-delta',- id,- delta: prefix.reasoning,- } as UIMessageChunk)- }- if (!textEmitted && type === 'text-start') {- textEmitted = true- const id = (value as { id: string }).id- controller.enqueue({- type: 'text-delta',- id,- delta: prefix.text,- } as UIMessageChunk)- }- } catch (error) {- controller.error(error)- }- },- cancel() {- reader.cancel()- },- })+ const reader = stream.getReader()+ let reasoningEmitted = !prefix.reasoning+ let textEmitted = !prefix.text+ return new ReadableStream<UIMessageChunk>({+ async pull(controller) {+ try {+ const { done, value } = await reader.read()+ if (done) {+ controller.close()+ return+ }+ controller.enqueue(value)+ const type = (value as { type: string }).type+ if (!reasoningEmitted && type === 'reasoning-start') {+ reasoningEmitted = true+ const id = (value as { id: string }).id+ controller.enqueue({+ type: 'reasoning-delta',+ id,+ delta: prefix.reasoning,+ } as UIMessageChunk)+ }+ if (!textEmitted && type === 'text-start') {+ textEmitted = true+ const id = (value as { id: string }).id+ controller.enqueue({+ type: 'text-delta',+ id,+ delta: prefix.text,+ } as UIMessageChunk)+ }+ } catch (error) {+ controller.error(error)+ }+ },+ cancel() {+ reader.cancel()+ },+ })}export class CustomChatTransport implements ChatTransport<UIMessage> {- public model: LanguageModel | null = null- private routerModel: LanguageModel | null = null- private routerModelKey = ''- protected tools: Record<string, Tool> = {}- // Smart tool routing selects tools from the latest user message, which would- // change the tool set (and thus the cached prompt prefix) every turn. Freeze- // the routed set for the thread's lifetime so the prefix stays stable;- // re-route only when the connected servers or disabled-tool set changes.- private frozenRoutedTools: MCPTool[] | null = null- private frozenRoutedSig = ''- private onTokenUsage?: TokenUsageCallback- private hasDocuments = false- private modelSupportsTools = false- private ragFeatureAvailable = false- protected systemMessage?: string- protected serviceHub: ServiceHub | null- protected threadId?: string- private continueFromContent: ContinuationContent | null = null- /** Latest user message text — used by the MCP orchestrator for tool routing. */- private lastUserMessage = ''- /**- * Monotonic per-request token. The transport instance is reused across- * regenerate, so a superseded request's terminal onError/onFinish must not- * clear loading/stream state that the newer request has already set.- */- private streamGeneration = 0-- constructor(systemMessage?: string, threadId?: string) {- this.systemMessage = systemMessage- this.threadId = threadId- this.serviceHub = useServiceStore.getState().serviceHub- // Tools will be loaded when updateRagToolsAvailability is called with model capabilities- }-- protected getModelSelection(): { selectedProvider: string; selectedModel: Model | null } {- return useModelProvider.getState()- }-- setLastUserMessage(message: string): void {- this.lastUserMessage = message- }-- /**- * Whether this transport's load state and its `llamacpp-model-load-progress`- * events belong to a Cowork run. Cowork overrides the two writers below and- * this flag so the load card is fed from useCoworkRun's session mirror,- * keeping session ids out of useAppState's thread-keyed slots (which drive- * chat-thread active detection).- */- protected get streamRoutesToCowork(): boolean {- return false- }-- /** Route the model-loading flag. Base writes useAppState (global + thread). */- protected setLoadingModel(threadId: string, loading: boolean): void {- useAppState.getState().updateLoadingModel(loading)- useAppState.getState().updateThreadLoadingModel(threadId, loading)- }-- /** Route model-load progress. Base writes useAppState (global + thread). */- protected setModelLoadProgress(- threadId: string,- progress: ModelLoadProgress | undefined- ): void {- useAppState.getState().updateModelLoadProgress(progress)- useAppState.getState().updateThreadModelLoadProgress(threadId, progress)- }-- updateSystemMessage(systemMessage: string | undefined) {- this.systemMessage = systemMessage- }-- // Inference params follow the thread's assigned assistant so in-chat agent- // switches take effect immediately. A thread with no real assistant- // (model-only / "None") uses no assistant params — matching the switcher.- // Only off-thread (no threadId / thread not yet in store) do we fall back to- // the global current assistant.- private getActiveInferenceParams(): Record<string, unknown> {- const thread = this.threadId- ? useThreads.getState().threads[this.threadId]- : undefined- if (thread) {- const threadAssistant = thread.assistants?.[0]- return threadAssistant && threadAssistant.id !== 'model-only'- ? (threadAssistant.parameters ?? {})- : {}+ public model: LanguageModel | null = null+ private routerModel: LanguageModel | null = null+ private routerModelKey = ''+ protected tools: Record<string, Tool> = {}+ // Smart tool routing selects tools from the latest user message, which would+ // change the tool set (and thus the cached prompt prefix) every turn. Freeze+ // the routed set for the thread's lifetime so the prefix stays stable;+ // re-route only when the connected servers or disabled-tool set changes.+ private frozenRoutedTools: MCPTool[] | null = null+ private frozenRoutedSig = ''+ private onTokenUsage?: TokenUsageCallback+ private hasDocuments = false+ private modelSupportsTools = false+ private ragFeatureAvailable = false+ protected systemMessage?: string+ protected serviceHub: ServiceHub | null+ protected threadId?: string+ private continueFromContent: ContinuationContent | null = null+ /** Latest user message text — used by the MCP orchestrator for tool routing. */+ private lastUserMessage = ''+ /**+ * Monotonic per-request token. The transport instance is reused across+ * regenerate, so a superseded request's terminal onError/onFinish must not+ * clear loading/stream state that the newer request has already set.+ */+ private streamGeneration = 0++ constructor(systemMessage?: string, threadId?: string) {+ this.systemMessage = systemMessage+ this.threadId = threadId+ this.serviceHub = useServiceStore.getState().serviceHub+ // Tools will be loaded when updateRagToolsAvailability is called with model capabilities}- return useAssistant.getState().currentAssistant?.parameters ?? {}- }-- setOnTokenUsage(callback: TokenUsageCallback | undefined) {- this.onTokenUsage = callback- }-- /**- * Update RAG tools availability based on thread metadata and model capabilities- * @param hasDocuments - Whether the thread has documents attached- * @param modelSupportsTools - Whether the current model supports tool calling- * @param ragFeatureAvailable - Whether RAG features are available on the platform- */- async updateRagToolsAvailability(- hasDocuments: boolean,- modelSupportsTools: boolean,- ragFeatureAvailable: boolean- ) {- this.hasDocuments = hasDocuments- this.modelSupportsTools = modelSupportsTools- this.ragFeatureAvailable = ragFeatureAvailable-- // Update tools based on current state- await this.refreshTools()- }-- /**- * Refresh tools based on current state- * Reloads both RAG and MCP tools and merges them- * Filters out disabled tools based on thread settings- * @private- */- /**- * llama.cpp slot pin for this surface. Every surface shares slot 0 -- the one- * index guaranteed to exist -- and overrides only `thread_id`, which is what- * the engine parks and restores the slot's KV cache by. See CHAT_SLOT_ID.- */- protected slotParams(threadId?: string): Record<string, unknown> {- return { id_slot: CHAT_SLOT_ID, thread_id: threadId }- }-- /**- * The system turn for this surface. Whitespace-only prompts collapse to- * undefined so we don't send a useless system turn that some chat templates- * still wrap into special tokens.- */- protected buildSystemPrompt(messages: UIMessage[]): string | undefined {- const raw =- [- this.systemMessage,- this.buildMemorySystemInstruction(),- this.buildFilesSystemInstruction(messages),- this.buildWebSearchSystemInstruction(),- this.buildAgentToolsSystemInstruction(),- ]- .filter((s) => typeof s === 'string' && s.trim().length > 0)- .join('\n\n') || undefined- return typeof raw === 'string' && raw.trim().length > 0 ? raw : undefined- }-- /**- * Many chat templates (Qwen3.5+) reject a window with no genuine user query- * and throw a cryptic Jinja error. Fail early with a clear message when- * deletion/eviction has left no real user turn to respond to.- */- protected assertSendable(messages: UIMessage[]): void {- if (!hasGenuineUserQuery(messages)) {- throw new Error(- 'This conversation has no user message to respond to. Add a message, or regenerate from a turn that includes your question.'- )++ protected getModelSelection(): { selectedProvider: string; selectedModel: Model | null } {+ return useModelProvider.getState()}- }-- async refreshTools(abortSignal?: AbortSignal) {- // Resolve the memory digest before the prompt is built: the builder is- // sync, so it reads the snapshot this await guarantees. Error-safe and- // cached inside agentTools, so this is one IPC round-trip per store change.- await refreshMemoryDigest()- if (!this.serviceHub) {- this.tools = {}- return++ setLastUserMessage(message: string): void {+ this.lastUserMessage = message}- const toolsRecord: Record<string, Tool> = {}+ /**+ * Whether this transport's load state and its `llamacpp-model-load-progress`+ * events belong to a Cowork run. Cowork overrides the two writers below and+ * this flag so the load card is fed from useCoworkRun's session mirror,+ * keeping session ids out of useAppState's thread-keyed slots (which drive+ * chat-thread active detection).+ */+ protected get streamRoutesToCowork(): boolean {+ return false+ }++ /** Route the model-loading flag. Base writes useAppState (global + thread). */+ protected setLoadingModel(threadId: string, loading: boolean): void {+ useAppState.getState().updateLoadingModel(loading)+ useAppState.getState().updateThreadLoadingModel(threadId, loading)+ }- // Tool availability is global (shared across all chats).- const disabledToolKeys = useToolAvailable.getState().getDisabledTools()- const isToolDisabled = (serverName: string, toolName: string): boolean => {- const toolKey = `${serverName}::${toolName}`- return disabledToolKeys.includes(toolKey)+ /** Route model-load progress. Base writes useAppState (global + thread). */+ protected setModelLoadProgress(+ threadId: string,+ progress: ModelLoadProgress | undefined+ ): void {+ useAppState.getState().updateModelLoadProgress(progress)+ useAppState.getState().updateThreadModelLoadProgress(threadId, progress)}- const selectedModel = this.getModelSelection().selectedModel- const modelSupportsTools = selectedModel?.capabilities?.includes('tools') ?? this.modelSupportsTools+ updateSystemMessage(systemMessage: string | undefined) {+ this.systemMessage = systemMessage+ }- // Only load tools if model supports them- if (modelSupportsTools) {- let hasDocuments = this.hasDocuments- let ragFeatureAvailable = this.ragFeatureAvailable+ // Inference params follow the thread's assigned assistant so in-chat agent+ // switches take effect immediately. A thread with no real assistant+ // (model-only / "None") uses no assistant params — matching the switcher.+ // Only off-thread (no threadId / thread not yet in store) do we fall back to+ // the global current assistant.+ private getActiveInferenceParams(): Record<string, unknown> {+ const thread = this.threadId+ ? useThreads.getState().threads[this.threadId]+ : undefined+ if (thread) {+ const threadAssistant = thread.assistants?.[0]+ return threadAssistant && threadAssistant.id !== 'model-only'+ ? (threadAssistant.parameters ?? {})+ : {}+ }+ return useAssistant.getState().currentAssistant?.parameters ?? {}+ }- if (!hasDocuments && this.threadId) {- const thread = useThreads.getState().threads[this.threadId]- const hasThreadDocuments = Boolean(thread?.metadata?.hasDocuments)+ setOnTokenUsage(callback: TokenUsageCallback | undefined) {+ this.onTokenUsage = callback+ }- const projectId = thread?.metadata?.project?.id- if (projectId) {- try {- const ext = ExtensionManager.getInstance().get<VectorDBExtension>(- ExtensionTypeEnum.VectorDB+ /**+ * Update RAG tools availability based on thread metadata and model capabilities+ * @param hasDocuments - Whether the thread has documents attached+ * @param modelSupportsTools - Whether the current model supports tool calling+ * @param ragFeatureAvailable - Whether RAG features are available on the platform+ */+ async updateRagToolsAvailability(+ hasDocuments: boolean,+ modelSupportsTools: boolean,+ ragFeatureAvailable: boolean+ ) {+ this.hasDocuments = hasDocuments+ this.modelSupportsTools = modelSupportsTools+ this.ragFeatureAvailable = ragFeatureAvailable++ // Update tools based on current state+ await this.refreshTools()+ }++ /**+ * Refresh tools based on current state+ * Reloads both RAG and MCP tools and merges them+ * Filters out disabled tools based on thread settings+ * @private+ */+ /**+ * llama.cpp slot pin for this surface. Every surface shares slot 0 -- the one+ * index guaranteed to exist -- and overrides only `thread_id`, which is what+ * the engine parks and restores the slot's KV cache by. See CHAT_SLOT_ID.+ */+ protected slotParams(threadId?: string): Record<string, unknown> {+ return { id_slot: CHAT_SLOT_ID, thread_id: threadId }+ }++ /**+ * The system turn for this surface. Whitespace-only prompts collapse to+ * undefined so we don't send a useless system turn that some chat templates+ * still wrap into special tokens.+ */+ protected buildSystemPrompt(messages: UIMessage[]): string | undefined {+ const raw =+ [+ this.systemMessage,+ this.buildMemorySystemInstruction(),+ this.buildFilesSystemInstruction(messages),+ this.buildWebSearchSystemInstruction(),+ this.buildAgentToolsSystemInstruction(),+ ]+ .filter((s) => typeof s === 'string' && s.trim().length > 0)+ .join('\n\n') || undefined+ return typeof raw === 'string' && raw.trim().length > 0 ? raw : undefined+ }++ /**+ * Many chat templates (Qwen3.5+) reject a window with no genuine user query+ * and throw a cryptic Jinja error. Fail early with a clear message when+ * deletion/eviction has left no real user turn to respond to.+ */+ protected assertSendable(messages: UIMessage[]): void {+ if (!hasGenuineUserQuery(messages)) {+ throw new Error(+ 'This conversation has no user message to respond to. Add a message, or regenerate from a turn that includes your question.')- if (ext?.listAttachmentsForProject) {- const projectFiles = await ext.listAttachmentsForProject(projectId)- hasDocuments = hasThreadDocuments || projectFiles.length > 0- }- } catch (error) {- console.warn('Failed to check project files:', error)- hasDocuments = hasThreadDocuments- }- } else {- hasDocuments = hasThreadDocuments}- }+ }- if (!ragFeatureAvailable) {- ragFeatureAvailable = Boolean(useAttachments.getState().enabled)- }+ async refreshTools(abortSignal?: AbortSignal) {+ // Resolve the memory digest before the prompt is built: the builder is+ // sync, so it reads the snapshot this await guarantees. Error-safe and+ // cached inside agentTools, so this is one IPC round-trip per store change.+ await refreshMemoryDigest()+ if (!this.serviceHub) {+ this.tools = {}+ return+ }- // Load RAG tools if documents are available- if (hasDocuments && ragFeatureAvailable) {- try {- const ragTools = await this.serviceHub.rag().getTools()- if (Array.isArray(ragTools) && ragTools.length > 0) {- // Convert RAG tools to AI SDK format, filtering out disabled tools- ragTools.forEach((tool) => {- // RAG tools use MCPTool interface with server field- const serverName =- (tool as { server?: string }).server || 'unknown'- if (!isToolDisabled(serverName, tool.name)) {- toolsRecord[tool.name] = {- description: tool.description,- inputSchema: jsonSchema(- normalizeToolInputSchema(tool.inputSchema as Record<string, unknown>)- ),+ const toolsRecord: Record<string, Tool> = {}++ // Tool availability is global (shared across all chats).+ const disabledToolKeys = useToolAvailable.getState().getDisabledTools()+ const isToolDisabled = (serverName: string, toolName: string): boolean => {+ const toolKey = `${serverName}::${toolName}`+ return disabledToolKeys.includes(toolKey)+ }++ const selectedModel = this.getModelSelection().selectedModel+ const modelSupportsTools = selectedModel?.capabilities?.includes('tools') ?? this.modelSupportsTools++ // Only load tools if model supports them+ if (modelSupportsTools) {+ let hasDocuments = this.hasDocuments+ let ragFeatureAvailable = this.ragFeatureAvailable++ if (!hasDocuments && this.threadId) {+ const thread = useThreads.getState().threads[this.threadId]+ const hasThreadDocuments = Boolean(thread?.metadata?.hasDocuments)++ const projectId = thread?.metadata?.project?.id+ if (projectId) {+ try {+ const ext = ExtensionManager.getInstance().get<VectorDBExtension>(+ ExtensionTypeEnum.VectorDB+ )+ if (ext?.listAttachmentsForProject) {+ const projectFiles = await ext.listAttachmentsForProject(projectId)+ hasDocuments = hasThreadDocuments || projectFiles.length > 0+ }+ } catch (error) {+ console.warn('Failed to check project files:', error)+ hasDocuments = hasThreadDocuments+ }+ } else {+ hasDocuments = hasThreadDocuments+ }+ }++ if (!ragFeatureAvailable) {+ ragFeatureAvailable = Boolean(useAttachments.getState().enabled)+ }++ // Load RAG tools if documents are available+ if (hasDocuments && ragFeatureAvailable) {+ try {+ const ragTools = await this.serviceHub.rag().getTools()+ if (Array.isArray(ragTools) && ragTools.length > 0) {+ // Convert RAG tools to AI SDK format, filtering out disabled tools+ ragTools.forEach((tool) => {+ // RAG tools use MCPTool interface with server field+ const serverName =+ (tool as { server?: string }).server || 'unknown'+ if (!isToolDisabled(serverName, tool.name)) {+ toolsRecord[tool.name] = {+ description: tool.description,+ inputSchema: jsonSchema(+ normalizeToolInputSchema(tool.inputSchema as Record<string, unknown>)+ ),+ } as Tool+ }+ })+ }+ } catch (error) {+ console.warn('Failed to load RAG tools:', error)+ }+ }++ // Load MCP tools — route through the orchestrator when available so only+ // relevant servers are queried instead of all of them.+ try {+ const mcpService = this.serviceHub.mcp()+ let mcpTools: MCPTool[]+ const mcpSettings = useMCPServers.getState().settings+ const routingEnabled = mcpSettings.enableSmartToolRouting++ if (+ routingEnabled &&+ mcpService.getToolsForServers &&+ mcpService.getServerSummaries+ ) {+ const summaries = await mcpService.getServerSummaries!()+ const routedSig = JSON.stringify({+ servers: summaries.map((s) => s.name).sort(),+ disabled: [...disabledToolKeys].sort(),+ })+ if (this.frozenRoutedTools && this.frozenRoutedSig === routedSig) {+ mcpTools = this.frozenRoutedTools+ } else {+ const routerModel =+ mcpSettings.useLightweightRouterModel &&+ mcpSettings.routerModelProvider.trim() &&+ mcpSettings.routerModelId.trim()+ ? (await this.resolveRouterModel(mcpSettings)) ?? this.model+ : this.model+ mcpTools = await mcpOrchestrator.getRelevantTools(+ this.lastUserMessage,+ {+ getTools: () => mcpService.getTools(),+ getToolsForServers: (names) =>+ mcpService.getToolsForServers!(names),+ getServerSummaries: () => Promise.resolve(summaries),+ },+ disabledToolKeys,+ {+ routerModel,+ abortSignal,+ }+ )+ this.frozenRoutedTools = mcpTools+ this.frozenRoutedSig = routedSig+ }+ } else {+ mcpTools = await mcpService.getTools()+ }++ if (Array.isArray(mcpTools) && mcpTools.length > 0) {+ const seenBy = new Map<string, string>()+ mcpTools.forEach((tool) => {+ const serverName = tool.server || 'unknown'+ if (isToolDisabled(serverName, tool.name)) return+ const prevServer = seenBy.get(tool.name)+ if (prevServer && prevServer !== serverName) {+ console.warn(+ `[tools] MCP tool name collision: "${tool.name}" exposed by both "${prevServer}" and "${serverName}". Using "${serverName}".`+ )+ }+ seenBy.set(tool.name, serverName)+ toolsRecord[tool.name] = {+ description: tool.description,+ inputSchema: jsonSchema(+ normalizeToolInputSchema(tool.inputSchema as Record<string, unknown>)+ ),+ } as Tool+ })+ }+ } catch (error) {+ console.warn('Failed to load MCP tools:', error)+ }++ // Native web tools, provided by the websearch plugin (not an MCP server).+ // Advertised whenever the user has web search enabled.+ if (useWebSearchConfig.getState().webSearchEnabled) {+ toolsRecord['web_search'] = {+ description: WEB_SEARCH_DESCRIPTION,+ inputSchema: jsonSchema(WEB_SEARCH_INPUT_SCHEMA as Record<string, unknown>),} as Tool- }- })- }- } catch (error) {- console.warn('Failed to load RAG tools:', error)+ toolsRecord['web_fetch'] = {+ description: WEB_FETCH_DESCRIPTION,+ inputSchema: jsonSchema(WEB_FETCH_INPUT_SCHEMA as Record<string, unknown>),+ } as Tool+ }++ // The main chat offers exactly one built-in agent tool: the sandboxed+ // shell, with no network. The full toolset lives in Cowork. Schemas come+ // from Rust so they are never re-typed here, and `getAgentToolSchemas`+ // already withholds shell when no sandbox backend can confine it.+ try {+ for (const schema of await getAgentToolSchemas()) {+ if (!CHAT_AGENT_TOOL_NAMES.has(schema.function.name)) continue+ toolsRecord[schema.function.name] = {+ description: schema.function.description,+ inputSchema: jsonSchema(schema.function.parameters),+ } as Tool+ }+ } catch (error) {+ console.warn('Failed to load agent tools:', error)+ }}- }- // Load MCP tools — route through the orchestrator when available so only- // relevant servers are queried instead of all of them.- try {- const mcpService = this.serviceHub.mcp()- let mcpTools: MCPTool[]- const mcpSettings = useMCPServers.getState().settings- const routingEnabled = mcpSettings.enableSmartToolRouting+ this.tools = toolsRecord+ }- if (- routingEnabled &&- mcpService.getToolsForServers &&- mcpService.getServerSummaries- ) {- const summaries = await mcpService.getServerSummaries!()- const routedSig = JSON.stringify({- servers: summaries.map((s) => s.name).sort(),- disabled: [...disabledToolKeys].sort(),- })- if (this.frozenRoutedTools && this.frozenRoutedSig === routedSig) {- mcpTools = this.frozenRoutedTools- } else {- const routerModel =- mcpSettings.useLightweightRouterModel &&- mcpSettings.routerModelProvider.trim() &&- mcpSettings.routerModelId.trim()- ? (await this.resolveRouterModel(mcpSettings)) ?? this.model- : this.model- mcpTools = await mcpOrchestrator.getRelevantTools(- this.lastUserMessage,- {- getTools: () => mcpService.getTools(),- getToolsForServers: (names) =>- mcpService.getToolsForServers!(names),- getServerSummaries: () => Promise.resolve(summaries),- },- disabledToolKeys,- {- routerModel,- abortSignal,- }+ private async resolveRouterModel(settings: {+ useLightweightRouterModel: boolean+ routerModelProvider: string+ routerModelId: string+ }): Promise<LanguageModel | null> {+ if (!settings.useLightweightRouterModel) return null+ const providerName = settings.routerModelProvider.trim()+ const modelId = settings.routerModelId.trim()+ if (!providerName || !modelId) return null++ const key = `${providerName}::${modelId}`+ if (this.routerModel && this.routerModelKey === key) {+ return this.routerModel+ }++ const provider = useModelProvider.getState().getProviderByName(providerName)+ if (!provider) {+ console.warn(+ `[MCP] Router model provider '${providerName}' not found; using chat model for routing.`)- this.frozenRoutedTools = mcpTools- this.frozenRoutedSig = routedSig- }- } else {- mcpTools = await mcpService.getTools()+ return null}- if (Array.isArray(mcpTools) && mcpTools.length > 0) {- const seenBy = new Map<string, string>()- mcpTools.forEach((tool) => {- const serverName = tool.server || 'unknown'- if (isToolDisabled(serverName, tool.name)) return- const prevServer = seenBy.get(tool.name)- if (prevServer && prevServer !== serverName) {- console.warn(- `[tools] MCP tool name collision: "${tool.name}" exposed by both "${prevServer}" and "${serverName}". Using "${serverName}".`- )- }- seenBy.set(tool.name, serverName)- toolsRecord[tool.name] = {- description: tool.description,- inputSchema: jsonSchema(- normalizeToolInputSchema(tool.inputSchema as Record<string, unknown>)- ),- } as Tool- })+ const catalogModel = provider.models.find((m) => m.id === modelId)+ if (!catalogModel || !isRouterModelSelectable(provider, catalogModel)) {+ console.warn(+ `[MCP] Router model '${key}' is not allowed for routing (use a lightweight model with API access); using chat model for routing.`+ )+ return null}- } catch (error) {- console.warn('Failed to load MCP tools:', error)- }-- // Native web tools, provided by the websearch plugin (not an MCP server).- // Advertised whenever the user has web search enabled.- if (useWebSearchConfig.getState().webSearchEnabled) {- toolsRecord['web_search'] = {- description: WEB_SEARCH_DESCRIPTION,- inputSchema: jsonSchema(WEB_SEARCH_INPUT_SCHEMA as Record<string, unknown>),- } as Tool- toolsRecord['web_fetch'] = {- description: WEB_FETCH_DESCRIPTION,- inputSchema: jsonSchema(WEB_FETCH_INPUT_SCHEMA as Record<string, unknown>),- } as Tool- }-- // The main chat offers exactly one built-in agent tool: the sandboxed- // shell, with no network. The full toolset lives in Cowork. Schemas come- // from Rust so they are never re-typed here, and `getAgentToolSchemas`- // already withholds shell when no sandbox backend can confine it.- try {- for (const schema of await getAgentToolSchemas()) {- if (!CHAT_AGENT_TOOL_NAMES.has(schema.function.name)) continue- toolsRecord[schema.function.name] = {- description: schema.function.description,- inputSchema: jsonSchema(schema.function.parameters),- } as Tool++ try {+ const model = await ModelFactory.createModel(modelId, provider, {})+ this.routerModel = model+ this.routerModelKey = key+ return model+ } catch (error) {+ console.warn(+ `[MCP] Failed to create router model '${key}'; using chat model for routing.`,+ error+ )+ this.routerModel = null+ this.routerModelKey = ''+ return null}- } catch (error) {- console.warn('Failed to load agent tools:', error)- }}- this.tools = toolsRecord- }-- private async resolveRouterModel(settings: {- useLightweightRouterModel: boolean- routerModelProvider: string- routerModelId: string- }): Promise<LanguageModel | null> {- if (!settings.useLightweightRouterModel) return null- const providerName = settings.routerModelProvider.trim()- const modelId = settings.routerModelId.trim()- if (!providerName || !modelId) return null-- const key = `${providerName}::${modelId}`- if (this.routerModel && this.routerModelKey === key) {- return this.routerModel+ /**+ * Get current tools+ */+ getTools(): Record<string, Tool> {+ return this.tools}- const provider = useModelProvider.getState().getProviderByName(providerName)- if (!provider) {- console.warn(- `[MCP] Router model provider '${providerName}' not found; using chat model for routing.`- )- return null+ /**+ * Set partial assistant content to send as a prefill on the next request,+ * so the model continues generation from where it left off. Accepts a plain+ * text string, or structured content carrying reasoning so a turn stopped+ * mid-thinking resumes inside its reasoning block.+ */+ setContinueFromContent(content: string | ContinuationContent) {+ const normalized: ContinuationContent =+ typeof content === 'string' ? { text: content } : content+ this.continueFromContent =+ normalized.text || normalized.reasoning ? normalized : null}- const catalogModel = provider.models.find((m) => m.id === modelId)- if (!catalogModel || !isRouterModelSelectable(provider, catalogModel)) {- console.warn(- `[MCP] Router model '${key}' is not allowed for routing (use a lightweight model with API access); using chat model for routing.`- )- return null+ /**+ * Race model creation (which blocks on llama-server load, up to 600s)+ * against the request's abort signal. `invoke()` has no cancellation of+ * its own, so an abort during "Loading model..." would otherwise be+ * silently ignored until load either finishes or times out. On abort we+ * fire-and-forget an unload of the (possibly still-loading) model so the+ * router doesn't keep spawning/holding a llama-server nobody wants.+ */+ private createModelOrAbort(+ modelId: string,+ provider: ProviderObject,+ parameters: Record<string, unknown>,+ providerId: string,+ abortSignal: AbortSignal | undefined+ ): Promise<LanguageModel> {+ const modelPromise = ModelFactory.createModel(modelId, provider, parameters)+ if (!abortSignal) return modelPromise++ // Target lib is ES2021 here (see tsconfig.app.json), predating+ // Promise.withResolvers (ES2024), so the executor form is required.+ return new Promise<LanguageModel>((resolve, reject) => {+ const onAbort = () => {+ if (providerId === 'llamacpp') {+ // Call the plugin's unload command directly instead of through the+ // extension's `unload()` method: that method first looks up an+ // active *loaded* session and throws if none is found, but a+ // model aborted mid-load is still in the "loading" state (not+ // "loaded") and would never resolve to a session -- silently+ // skipping the unload and leaking the still-loading llama-server.+ // See https://github.com/janhq/jan/issues/8432.+ unloadLlamaModel(modelId).catch(() => {+ // Best-effort: model may not have started loading yet, or may+ // already have finished/failed on its own.+ })+ }+ const err = new Error('Aborted')+ err.name = 'AbortError'+ reject(err)+ }+ if (abortSignal.aborted) {+ onAbort()+ return+ }+ abortSignal.addEventListener('abort', onAbort, { once: true })+ modelPromise+ .then((model) => {+ abortSignal.removeEventListener('abort', onAbort)+ resolve(model)+ })+ .catch((error) => {+ abortSignal.removeEventListener('abort', onAbort)+ reject(error)+ })+ })}- try {- const model = await ModelFactory.createModel(modelId, provider, {})- this.routerModel = model- this.routerModelKey = key- return model- } catch (error) {- console.warn(- `[MCP] Failed to create router model '${key}'; using chat model for routing.`,- error- )- this.routerModel = null- this.routerModelKey = ''- return null- }- }-- /**- * Get current tools- */- getTools(): Record<string, Tool> {- return this.tools- }-- /**- * Set partial assistant content to send as a prefill on the next request,- * so the model continues generation from where it left off. Accepts a plain- * text string, or structured content carrying reasoning so a turn stopped- * mid-thinking resumes inside its reasoning block.- */- setContinueFromContent(content: string | ContinuationContent) {- const normalized: ContinuationContent =- typeof content === 'string' ? { text: content } : content- this.continueFromContent =- normalized.text || normalized.reasoning ? normalized : null- }-- /**- * Race model creation (which blocks on llama-server load, up to 600s)- * against the request's abort signal. `invoke()` has no cancellation of- * its own, so an abort during "Loading model..." would otherwise be- * silently ignored until load either finishes or times out. On abort we- * fire-and-forget an unload of the (possibly still-loading) model so the- * router doesn't keep spawning/holding a llama-server nobody wants.- */- private createModelOrAbort(- modelId: string,- provider: ProviderObject,- parameters: Record<string, unknown>,- providerId: string,- abortSignal: AbortSignal | undefined- ): Promise<LanguageModel> {- const modelPromise = ModelFactory.createModel(modelId, provider, parameters)- if (!abortSignal) return modelPromise-- // Target lib is ES2021 here (see tsconfig.app.json), predating- // Promise.withResolvers (ES2024), so the executor form is required.- return new Promise<LanguageModel>((resolve, reject) => {- const onAbort = () => {- if (providerId === 'llamacpp') {- // Call the plugin's unload command directly instead of through the- // extension's `unload()` method: that method first looks up an- // active *loaded* session and throws if none is found, but a- // model aborted mid-load is still in the "loading" state (not- // "loaded") and would never resolve to a session -- silently- // skipping the unload and leaking the still-loading llama-server.- // See https://github.com/janhq/jan/issues/8432.- unloadLlamaModel(modelId).catch(() => {- // Best-effort: model may not have started loading yet, or may- // already have finished/failed on its own.- })+ async sendMessages(+ options: {+ chatId: string+ messages: UIMessage[]+ abortSignal: AbortSignal | undefined+ } & {+ trigger: 'submit-message' | 'regenerate-message'+ messageId: string | undefined+ } & ChatRequestOptions+ ): Promise<ReadableStream<UIMessageChunk>> {+ const threadId = this.threadId ?? options.chatId+ const myGeneration = ++this.streamGeneration+ useAppState+ .getState()+ .setCurrentStreamThreadId(threadId, this.streamRoutesToCowork)+ // Capture the effective provider name early so the Anthropic serial+ // tool-use repair later uses the same value that was used to create the+ // model, even if the user switches provider mid-request.+ const { selectedModel, selectedProvider: providerId } = this.getModelSelection()+ const modelId = selectedModel?.id+ const effectiveProviderName = providerId+ const provider = useModelProvider.getState().getProviderByName(providerId)+ if (!this.serviceHub || !modelId || !provider) {+ throw new Error('ServiceHub not initialized or model/provider missing.')}- const err = new Error('Aborted')- err.name = 'AbortError'- reject(err)- }- if (abortSignal.aborted) {- onAbort()- return- }- abortSignal.addEventListener('abort', onAbort, { once: true })- modelPromise- .then((model) => {- abortSignal.removeEventListener('abort', onAbort)- resolve(model)- })- .catch((error) => {- abortSignal.removeEventListener('abort', onAbort)- reject(error)- })- })- }-- async sendMessages(- options: {- chatId: string- messages: UIMessage[]- abortSignal: AbortSignal | undefined- } & {- trigger: 'submit-message' | 'regenerate-message'- messageId: string | undefined- } & ChatRequestOptions- ): Promise<ReadableStream<UIMessageChunk>> {- const threadId = this.threadId ?? options.chatId- const myGeneration = ++this.streamGeneration- useAppState- .getState()- .setCurrentStreamThreadId(threadId, this.streamRoutesToCowork)- // Capture the effective provider name early so the Anthropic serial- // tool-use repair later uses the same value that was used to create the- // model, even if the user switches provider mid-request.- const { selectedModel, selectedProvider: providerId } = this.getModelSelection()- const modelId = selectedModel?.id- const effectiveProviderName = providerId- const provider = useModelProvider.getState().getProviderByName(providerId)- if (!this.serviceHub || !modelId || !provider) {- throw new Error('ServiceHub not initialized or model/provider missing.')- }- this.lastUserMessage = extractLatestUserText(options.messages)+ this.lastUserMessage = extractLatestUserText(options.messages)- try {- const updatedProvider = useModelProvider- .getState()- .getProviderByName(providerId)-- const inferenceParams = this.getActiveInferenceParams()-- const reasoningParams = buildLlamacppReasoningParams(- effectiveProviderName,- selectedModel?.settings?.reasoning?.controller_props?.value as- | 'auto'- | 'on'- | 'off'- | undefined,- extractModelTemplateKwargs(selectedModel)- )-- if (providerId === 'llamacpp') {try {- const loaded = await getLoadedModels()- if (!loaded.includes(modelId)) {- this.setLoadingModel(threadId, true)+ const updatedProvider = useModelProvider+ .getState()+ .getProviderByName(providerId)++ const inferenceParams = this.getActiveInferenceParams()++ const reasoningParams = buildLlamacppReasoningParams(+ effectiveProviderName,+ selectedModel?.settings?.reasoning?.controller_props?.value as+ | 'auto'+ | 'on'+ | 'off'+ | undefined,+ extractModelTemplateKwargs(selectedModel)+ )++ if (providerId === 'llamacpp') {+ try {+ const loaded = await getLoadedModels()+ if (!loaded.includes(modelId)) {+ this.setLoadingModel(threadId, true)+ this.setModelLoadProgress(threadId, undefined)+ }+ } catch {+ // Ignore probe failures; the router will still load on demand+ }+ }++ // Per-model sidebar sampling defaults flow through as request-body+ // overrides (router mode can't bake them into CLI args). Assistant+ // params still win — they're the explicit per-conversation override.+ const modelSamplingDefaults = extractModelSamplingDefaults(selectedModel)+ if (providerId === 'llamacpp') {+ const thinkingBudgetTokens = await resolveThinkingBudgetTokens(+ selectedModel,+ modelId+ )+ if (thinkingBudgetTokens !== undefined) {+ modelSamplingDefaults.thinking_budget_tokens = thinkingBudgetTokens+ }+ }++ // Create the model before refreshing tools so the MCP orchestrator can run+ // structured LLM routing when many servers are connected.+ const mergedParams: Record<string, unknown> = {+ ...modelSamplingDefaults,+ ...(inferenceParams ?? {}),+ ...reasoningParams,+ }+ if (isPredefinedRemoteProvider(effectiveProviderName)) {+ for (const key of Object.keys(paramsSettings)) delete mergedParams[key]+ }+ // Pin chat to slot 0 so llama-server reuses this thread's cached KV+ // prefix across turns. Cowork and background tasks share the same slot;+ // what keeps them from destroying this prefix is thread_id below.+ //+ // thread_id names whose cache that is, which is what lets the engine+ // park it when another thread takes the slot and pick it back up later,+ // including in a later session. It is stripped before the request+ // reaches llama.cpp.+ if (providerId === 'llamacpp') {+ Object.assign(mergedParams, this.slotParams(threadId))+ }+ this.model = await this.createModelOrAbort(+ modelId,+ updatedProvider ?? provider,+ mergedParams,+ providerId,+ options.abortSignal+ )+ this.setLoadingModel(threadId, false)this.setModelLoadProgress(threadId, undefined)- }- } catch {- // Ignore probe failures; the router will still load on demand- }- }-- // Per-model sidebar sampling defaults flow through as request-body- // overrides (router mode can't bake them into CLI args). Assistant- // params still win — they're the explicit per-conversation override.- const modelSamplingDefaults = extractModelSamplingDefaults(selectedModel)- if (providerId === 'llamacpp') {- const thinkingBudgetTokens = await resolveThinkingBudgetTokens(- selectedModel,- modelId- )- if (thinkingBudgetTokens !== undefined) {- modelSamplingDefaults.thinking_budget_tokens = thinkingBudgetTokens+ } catch (error) {+ this.setLoadingModel(threadId, false)+ this.setModelLoadProgress(threadId, undefined)+ console.error('Failed to create model:', error)+ // Preserve AbortError identity so callers/UI can tell a user-initiated+ // Stop from an actual model-load failure.+ if (error instanceof Error && error.name === 'AbortError') throw error+ throw engineFailure('model-errors:createModelFailed', error)}- }-- // Create the model before refreshing tools so the MCP orchestrator can run- // structured LLM routing when many servers are connected.- const mergedParams: Record<string, unknown> = {- ...modelSamplingDefaults,- ...(inferenceParams ?? {}),- ...reasoningParams,- }- if (isPredefinedRemoteProvider(effectiveProviderName)) {- for (const key of Object.keys(paramsSettings)) delete mergedParams[key]- }- // Pin chat to slot 0 so llama-server reuses this thread's cached KV- // prefix across turns. Cowork and background tasks share the same slot;- // what keeps them from destroying this prefix is thread_id below.- //- // thread_id names whose cache that is, which is what lets the engine- // park it when another thread takes the slot and pick it back up later,- // including in a later session. It is stripped before the request- // reaches llama.cpp.- if (providerId === 'llamacpp') {- Object.assign(mergedParams, this.slotParams(threadId))- }- this.model = await this.createModelOrAbort(- modelId,- updatedProvider ?? provider,- mergedParams,- providerId,- options.abortSignal- )- this.setLoadingModel(threadId, false)- this.setModelLoadProgress(threadId, undefined)- } catch (error) {- this.setLoadingModel(threadId, false)- this.setModelLoadProgress(threadId, undefined)- console.error('Failed to create model:', error)- // Preserve AbortError identity so callers/UI can tell a user-initiated- // Stop from an actual model-load failure.- if (error instanceof Error && error.name === 'AbortError') throw error- throw engineFailure('model-errors:createModelFailed', error)- }- await this.refreshTools(options.abortSignal)-- // Split assistant turns that place text after tool calls into separate- // messages. Required by the Claude API (tool_use / tool_result pairing) and- // it keeps the prompt prefix byte-identical across turns so llama.cpp reuses- // the KV cache. See `splitAssistantToolWaves`.- const messagesToConvert = splitAssistantToolWaves(options.messages)-- const inferenceParams = this.getActiveInferenceParams()--- const effectiveSystem = this.buildSystemPrompt(messagesToConvert)-- const maxOutputTokens: number | undefined = (() => {- const raw = inferenceParams.max_output_tokens ?? inferenceParams.max_tokens- if (raw === undefined || raw === null) return undefined- const n = typeof raw === 'number' ? raw : Number(raw)- return isNaN(n) ? undefined : n- })()-- const configuredContextTokens = (() => {- const raw = inferenceParams.max_context_tokens- return typeof raw === 'number' ? raw : (Number(raw) || 0)- })()- const contextShiftEnabled =- providerId === 'llamacpp' &&- provider.settings?.some(- (setting) =>- setting.key === 'ctx_shift' &&- setting.controller_props?.value === true- ) === true- let liveContextTokens: number | undefined- if (contextShiftEnabled) {- try {- liveContextTokens = (- await getLlamacppExtension()?.getModelProps?.(modelId)- )?.nCtx- } catch {- // The router has not loaded the model yet. Preserve the configured limit.- }- }- const maxContextTokens = effectiveContextWindow(- configuredContextTokens,- liveContextTokens,- contextShiftEnabled- )- const autoCompact =- inferenceParams.auto_compact === true ||- inferenceParams.auto_compact === 'true'-- let effectiveMessages = messagesToConvert- if (maxContextTokens > 0) {- const contextConfig: ContextManagerConfig = {- maxContextTokens,- maxOutputTokens: maxOutputTokens ?? 2048,- autoCompact: !!autoCompact,- }-- // Context Shift only shifts llama.cpp's KV cache after generation starts.- // Keep the submitted chat history under the live router context window first.- const systemPromptTokens = effectiveSystem- ? estimateTokens(effectiveSystem) + 4- : 0- if (autoCompact && !contextShiftEnabled && this.model) {- const compactResult = await compactMessages(- messagesToConvert,- contextConfig,- this.model,- systemPromptTokens- )- effectiveMessages = compactResult.messages- if (compactResult.trimmedCount > 0) {- console.debug(- `[context-manager] Compacted ${compactResult.trimmedCount} messages` +- (compactResult.compactedSummary ? ' with summary' : ' (trim fallback)')- )+ await this.refreshTools(options.abortSignal)++ // Split assistant turns that place text after tool calls into separate+ // messages. Required by the Claude API (tool_use / tool_result pairing) and+ // it keeps the prompt prefix byte-identical across turns so llama.cpp reuses+ // the KV cache. See `splitAssistantToolWaves`.+ const messagesToConvert = splitAssistantToolWaves(options.messages)++ const inferenceParams = this.getActiveInferenceParams()+++ const effectiveSystem = this.buildSystemPrompt(messagesToConvert)++ const maxOutputTokens: number | undefined = (() => {+ const raw = inferenceParams.max_output_tokens ?? inferenceParams.max_tokens+ if (raw === undefined || raw === null) return undefined+ const n = typeof raw === 'number' ? raw : Number(raw)+ return isNaN(n) ? undefined : n+ })()++ const configuredContextTokens = (() => {+ const raw = inferenceParams.max_context_tokens+ return typeof raw === 'number' ? raw : (Number(raw) || 0)+ })()+ const contextShiftEnabled =+ providerId === 'llamacpp' &&+ provider.settings?.some(+ (setting) =>+ setting.key === 'ctx_shift' &&+ setting.controller_props?.value === true+ ) === true+ let liveContextTokens: number | undefined+ if (contextShiftEnabled) {+ try {+ liveContextTokens = (+ await getLlamacppExtension()?.getModelProps?.(modelId)+ )?.nCtx+ } catch {+ // The router has not loaded the model yet. Preserve the configured limit.+ }}- } else {- const trimResult = trimMessages(- messagesToConvert,- contextConfig,- systemPromptTokens+ const maxContextTokens = effectiveContextWindow(+ configuredContextTokens,+ liveContextTokens,+ contextShiftEnabled)- effectiveMessages = trimResult.messages- if (trimResult.trimmedCount > 0) {- console.debug(- `[context-manager] Trimmed ${trimResult.trimmedCount} oldest messages to fit context budget`- )+ const autoCompact =+ inferenceParams.auto_compact === true ||+ inferenceParams.auto_compact === 'true'++ let effectiveMessages = messagesToConvert+ if (maxContextTokens > 0) {+ const contextConfig: ContextManagerConfig = {+ maxContextTokens,+ maxOutputTokens: maxOutputTokens ?? 2048,+ autoCompact: !!autoCompact,+ }++ // Context Shift only shifts llama.cpp's KV cache after generation starts.+ // Keep the submitted chat history under the live router context window first.+ const systemPromptTokens = effectiveSystem+ ? estimateTokens(effectiveSystem) + 4+ : 0+ if (autoCompact && !contextShiftEnabled && this.model) {+ const compactResult = await compactMessages(+ messagesToConvert,+ contextConfig,+ this.model,+ systemPromptTokens+ )+ effectiveMessages = compactResult.messages+ if (compactResult.trimmedCount > 0) {+ console.debug(+ `[context-manager] Compacted ${compactResult.trimmedCount} messages` ++ (compactResult.compactedSummary ? ' with summary' : ' (trim fallback)')+ )+ }+ } else {+ const trimResult = trimMessages(+ messagesToConvert,+ contextConfig,+ systemPromptTokens+ )+ effectiveMessages = trimResult.messages+ if (trimResult.trimmedCount > 0) {+ console.debug(+ `[context-manager] Trimmed ${trimResult.trimmedCount} oldest messages to fit context budget`+ )+ }+ }}- }- }- // Many chat templates (Qwen3.5+) reject a window with no genuine user query- // and throw a cryptic Jinja error. Fail early with a clear message when- // deletion/eviction has left no real user turn to respond to.- this.assertSendable(effectiveMessages)-- const modelSupportsVision =- selectedModel?.capabilities?.includes('vision') ?? false- const baseMessages = await convertToModelMessages(- coalesceMessagesForAlternation(- resolveOrphanToolCalls(- this.encodeVideoAttachments(- this.encodeAudioAttachments(- stripUnsupportedImageParts(- this.mapUserInlineAttachments(effectiveMessages),- modelSupportsVision- )+ // Many chat templates (Qwen3.5+) reject a window with no genuine user query+ // and throw a cryptic Jinja error. Fail early with a clear message when+ // deletion/eviction has left no real user turn to respond to.+ this.assertSendable(effectiveMessages)++ const modelSupportsVision =+ selectedModel?.capabilities?.includes('vision') ?? false+ const baseMessages = await convertToModelMessages(+ coalesceMessagesForAlternation(+ resolveOrphanToolCalls(+ this.encodeVideoAttachments(+ this.encodeAudioAttachments(+ stripUnsupportedImageParts(+ this.mapUserInlineAttachments(effectiveMessages),+ modelSupportsVision+ )+ )+ )+ ))- ))- )- )- // If continuing a truncated response, append the partial assistant content as a- // prefill so the model resumes from where it left off rather than regenerating.- const continueContent = this.continueFromContent- this.continueFromContent = null- const modelMessages = continueContent- ? [- ...baseMessages,- {- role: 'assistant' as const,- content: [- ...(continueContent.reasoning- ? [- {- type: 'reasoning' as const,- text: continueContent.reasoning,- },- ]- : []),- ...(continueContent.text- ? [{ type: 'text' as const, text: continueContent.text }]- : []),- ],- },- ]- : baseMessages-- // Include tools only if we have tools loaded AND model supports them- const hasTools = Object.keys(this.tools).length > 0- const modelSupportsTools = selectedModel?.capabilities?.includes('tools') ?? this.modelSupportsTools- const shouldEnableTools = hasTools && modelSupportsTools-- // Cloud providers take reasoning via the AI SDK's per-request- // providerOptions (native thinking config), not the raw body.- const reasoningProviderOptions = buildReasoningProviderOptions(- providerId,- selectedModel- )+ // If continuing a truncated response, append the partial assistant content as a+ // prefill so the model resumes from where it left off rather than regenerating.+ const continueContent = this.continueFromContent+ this.continueFromContent = null+ const modelMessages = continueContent+ ? [+ ...baseMessages,+ {+ role: 'assistant' as const,+ content: [+ ...(continueContent.reasoning+ ? [+ {+ type: 'reasoning' as const,+ text: continueContent.reasoning,+ },+ ]+ : []),+ ...(continueContent.text+ ? [{ type: 'text' as const, text: continueContent.text }]+ : []),+ ],+ },+ ]+ : baseMessages++ // Include tools only if we have tools loaded AND model supports them+ const hasTools = Object.keys(this.tools).length > 0+ const modelSupportsTools = selectedModel?.capabilities?.includes('tools') ?? this.modelSupportsTools+ const shouldEnableTools = hasTools && modelSupportsTools++ // Cloud providers take reasoning via the AI SDK's per-request+ // providerOptions (native thinking config), not the raw body.+ const reasoningProviderOptions = buildReasoningProviderOptions(+ providerId,+ selectedModel+ )- useAppState.getState().updatePromptProgress(undefined)- useAppState.getState().updateThreadPromptProgress(threadId, undefined)- useAppState.getState().updateLiveTokenStats(undefined)- useAppState.getState().updateThreadLiveTokenStats(threadId, undefined)-- const result = streamText({- model: this.model,- messages: modelMessages,- abortSignal: options.abortSignal,- // Hosted providers keep the SDK's two backoff retries for transient- // 429/5xx; local servers fail at once (see isLocalChatServer).- maxRetries: isLocalChatServer(providerId, provider.base_url) ? 0 : 2,- tools: shouldEnableTools ? this.tools : undefined,- toolChoice: shouldEnableTools ? 'auto' : undefined,- system: effectiveSystem,- ...(maxOutputTokens !== undefined ? { maxTokens: maxOutputTokens } : {}),- ...(reasoningProviderOptions- ? { providerOptions: reasoningProviderOptions }- : {}),- experimental_repairToolCall: async ({ toolCall, error }) => {- // Windows paths (`C:\Users\...`) contain invalid JSON escapes that make- // the SDK's argument parse fail. Re-escape lone backslashes and retry- // so the tool receives the intended path instead of looping on failure.- if (!InvalidToolInputError.isInstance(error)) return null- const repaired = repairToolArgs(toolCall.input)- if (!repaired) return null- return { ...toolCall, input: JSON.stringify(repaired) }- },- })+ useAppState.getState().updatePromptProgress(undefined)+ useAppState.getState().updateThreadPromptProgress(threadId, undefined)+ useAppState.getState().updateLiveTokenStats(undefined)+ useAppState.getState().updateThreadLiveTokenStats(threadId, undefined)++ const result = streamText({+ model: this.model,+ messages: modelMessages,+ abortSignal: options.abortSignal,+ // Hosted providers keep the SDK's two backoff retries for transient+ // 429/5xx; local servers fail at once (see isLocalChatServer).+ maxRetries: isLocalChatServer(providerId, provider.base_url) ? 0 : 2,+ tools: shouldEnableTools ? this.tools : undefined,+ toolChoice: shouldEnableTools ? 'auto' : undefined,+ system: effectiveSystem,+ ...(maxOutputTokens !== undefined ? { maxTokens: maxOutputTokens } : {}),+ ...(reasoningProviderOptions+ ? { providerOptions: reasoningProviderOptions }+ : {}),+ experimental_repairToolCall: async ({ toolCall, error }) => {+ // Windows paths (`C:\Users\...`) contain invalid JSON escapes that make+ // the SDK's argument parse fail. Re-escape lone backslashes and retry+ // so the tool receives the intended path instead of looping on failure.+ if (!InvalidToolInputError.isInstance(error)) return null+ const repaired = repairToolArgs(toolCall.input)+ if (!repaired) return null+ return { ...toolCall, input: JSON.stringify(repaired) }+ },+ })- const stepMetadata = createStepMetadata()-- const uiStream = result.toUIMessageStream({- // Usage and token speed, assembled by the one implementation every- // streaming surface shares (see `lib/stepMetadata`).- messageMetadata: ({ part }) => stepMetadata.onPart(part),- onError: (error) => {- // A superseded request (e.g. after Reload) must not clear loading/stream- // state the newer request already owns.- if (this.streamGeneration === myGeneration) {- useAppState.getState().updatePromptProgress(undefined)- useAppState.getState().updateThreadPromptProgress(threadId, undefined)- this.setLoadingModel(threadId, false)- useAppState.getState().updateLiveTokenStats(undefined)- useAppState.getState().updateThreadLiveTokenStats(threadId, undefined)- if (useAppState.getState().currentStreamThreadId === threadId) {- useAppState.getState().setCurrentStreamThreadId(undefined)- }- }- const unwrapped = unwrapRetryError(error)- const rawMessage = unwrapped == null- ? 'Unknown error'- : typeof unwrapped === 'string'- ? unwrapped- : unwrapped instanceof Error- ? unwrapped.message- : JSON.stringify(unwrapped)- const baseMessage = stripRetryErrorWrapper(rawMessage)-- const contextInfo = extractContextInfoFromError(unwrapped)- if (contextInfo) {- return `${baseMessage}\n\n(Used ${contextInfo.nPromptTokens.toLocaleString()} of ${contextInfo.nCtx.toLocaleString()} context tokens.)`- }- return baseMessage- },- onFinish: ({ responseMessage }) => {- if (this.streamGeneration === myGeneration) {- useAppState.getState().updatePromptProgress(undefined)- useAppState.getState().updateThreadPromptProgress(threadId, undefined)- this.setLoadingModel(threadId, false)- useAppState.getState().updateLiveTokenStats(undefined)- useAppState.getState().updateThreadLiveTokenStats(threadId, undefined)- if (useAppState.getState().currentStreamThreadId === threadId) {- useAppState.getState().setCurrentStreamThreadId(undefined)- }- }- if (responseMessage) {- const metadata = responseMessage.metadata as- | Record<string, unknown>- | undefined- const usage = metadata?.usage as LanguageModelUsage | undefined- if (usage) {- this.onTokenUsage?.(usage, responseMessage.id)- }- }- },- })+ const stepMetadata = createStepMetadata()++ const uiStream = result.toUIMessageStream({+ // Usage and token speed, assembled by the one implementation every+ // streaming surface shares (see `lib/stepMetadata`).+ messageMetadata: ({ part }) => stepMetadata.onPart(part),+ onError: (error) => {+ // A superseded request (e.g. after Reload) must not clear loading/stream+ // state the newer request already owns.+ if (this.streamGeneration === myGeneration) {+ useAppState.getState().updatePromptProgress(undefined)+ useAppState.getState().updateThreadPromptProgress(threadId, undefined)+ this.setLoadingModel(threadId, false)+ useAppState.getState().updateLiveTokenStats(undefined)+ useAppState.getState().updateThreadLiveTokenStats(threadId, undefined)+ if (useAppState.getState().currentStreamThreadId === threadId) {+ useAppState.getState().setCurrentStreamThreadId(undefined)+ }+ }+ const unwrapped = unwrapRetryError(error)+ const rawMessage = unwrapped == null+ ? 'Unknown error'+ : typeof unwrapped === 'string'+ ? unwrapped+ : unwrapped instanceof Error+ ? unwrapped.message+ : JSON.stringify(unwrapped)+ const baseMessage = stripRetryErrorWrapper(rawMessage)++ const contextInfo = extractContextInfoFromError(unwrapped)+ if (contextInfo) {+ return `${baseMessage}\n\n(Used ${contextInfo.nPromptTokens.toLocaleString()} of ${contextInfo.nCtx.toLocaleString()} context tokens.)`+ }+ return baseMessage+ },+ onFinish: ({ responseMessage }) => {+ if (this.streamGeneration === myGeneration) {+ useAppState.getState().updatePromptProgress(undefined)+ useAppState.getState().updateThreadPromptProgress(threadId, undefined)+ this.setLoadingModel(threadId, false)+ useAppState.getState().updateLiveTokenStats(undefined)+ useAppState.getState().updateThreadLiveTokenStats(threadId, undefined)+ if (useAppState.getState().currentStreamThreadId === threadId) {+ useAppState.getState().setCurrentStreamThreadId(undefined)+ }+ }+ if (responseMessage) {+ const metadata = responseMessage.metadata as+ | Record<string, unknown>+ | undefined+ const usage = metadata?.usage as LanguageModelUsage | undefined+ if (usage) {+ this.onTokenUsage?.(usage, responseMessage.id)+ }+ }+ },+ })- // When continuing a truncated response, inject the partial content as the- // very first text-delta so the new message immediately shows it and the- // user sees a seamless continuation rather than an empty box.- const finalStream = continueContent- ? prependContinuationToUIStream(uiStream, continueContent)- : uiStream-- return finalStream- }-- async reconnectToStream(- // eslint-disable-next-line @typescript-eslint/no-unused-vars- _options: {- chatId: string- } & ChatRequestOptions- ): Promise<ReadableStream<UIMessageChunk> | null> {- // This function normally handles reconnecting to a stream on the backend, e.g. /api/chat- // Since this project has no backend, we can't reconnect to a stream, so this is intentionally no-op.- return null- }-- // Replace audio `file` parts on user messages with sentinel-bearing `text`- // parts. The `@ai-sdk/openai-compatible` provider rejects non-image file- // parts in its converter; the matching fetch wrapper in model-factory.ts- // decodes these sentinels back into OpenAI `input_audio` content parts on- // the outgoing wire, which llama-server's chat-completions endpoint accepts.- encodeAudioAttachments(messages: UIMessage[]): UIMessage[] {- return messages.map((message) => {- if (message.role !== 'user' || !Array.isArray(message.parts)) return message- let touched = false- const nextParts = message.parts.map((part) => {- if (- part?.type === 'file' &&- typeof (part as { mediaType?: string }).mediaType === 'string' &&- (part as { mediaType: string }).mediaType.startsWith('audio/') &&- typeof (part as { url?: string }).url === 'string'- ) {- const parsed = parseAudioDataUrl((part as { url: string }).url)- if (!parsed) return part- touched = true- return { type: 'text' as const, text: encodeAudioSentinel(parsed.format, parsed.data) }- }- return part- })- if (!touched) return message- return { ...message, parts: nextParts } as UIMessage- })- }+ // When continuing a truncated response, inject the partial content as the+ // very first text-delta so the new message immediately shows it and the+ // user sees a seamless continuation rather than an empty box.+ const finalStream = continueContent+ ? prependContinuationToUIStream(uiStream, continueContent)+ : uiStream- // Replace video `file` parts on user messages with sentinel-bearing `text`- // parts, same mechanism as encodeAudioAttachments. The fetch wrapper in- // model-factory.ts decodes these into llama-server `input_video` content- // parts (frames decoded via the vision encoder + ffmpeg on the server).- encodeVideoAttachments(messages: UIMessage[]): UIMessage[] {- return messages.map((message) => {- if (message.role !== 'user' || !Array.isArray(message.parts)) return message- let touched = false- const nextParts = message.parts.map((part) => {- if (- part?.type === 'file' &&- typeof (part as { mediaType?: string }).mediaType === 'string' &&- (part as { mediaType: string }).mediaType.startsWith('video/') &&- typeof (part as { url?: string }).url === 'string'- ) {- const parsed = parseVideoDataUrl((part as { url: string }).url)- if (!parsed) return part- touched = true- return { type: 'text' as const, text: encodeVideoSentinel(parsed.data) }- }- return part- })- if (!touched) return message- return { ...message, parts: nextParts } as UIMessage- })- }-- /**- * [ATTACHED_FILES] blocks stay on the user message that carries them (see- * fileMetadata.ts injectFilesIntoPrompt) so the model reads file_ids in the- * turn they belong to. Only a static, file-independent instruction is added- * to the system prompt - it never varies per attachment, so it doesn't- * defeat prompt caching.- */- buildFilesSystemInstruction(messages: UIMessage[]): string {- const hasAttachedFiles = messages.some(- (message) =>- message.role === 'user' &&- Array.isArray(message.parts) &&- message.parts.some(- (part) =>- part?.type === 'text' &&- typeof (part as { text?: string }).text === 'string' &&- (part as { text: string }).text.includes('[ATTACHED_FILES]')- )- )- if (!hasAttachedFiles) return ''- return [- 'Some user messages contain an [ATTACHED_FILES] block listing files',- 'attached to that turn (file_id, name, type, size, chunk count, mode).',- 'Use the available retrieval tools with those file_ids when their',- 'contents are relevant to the request.',- ].join(' ')- }-- /**- * Static instruction teaching the model to use the native web tools and cite- * sources inline with [[cite:URL]] markers (rendered as favicon chips). Only- * added when web search is enabled so it doesn't affect prompt caching for- * users who keep it off.- */- buildWebSearchSystemInstruction(): string {- if (!useWebSearchConfig.getState().webSearchEnabled) return ''- return [- '# Web Access',- 'You can search the web with web_search and read pages with web_fetch.',- 'Use them whenever the request needs current, external, or verifiable',- 'information, then base your answer on what you find. When a statement',- 'relies on a web source, cite it inline immediately after that statement',- 'using the exact marker [[cite:URL]], where URL is the full source URL',- 'from a web_search result (for example: [[cite:https://example.com/page]]).',- 'Cite each distinct source you rely on; do not add a separate references',- 'or sources section.',- ].join(' ')- }-- /**- * Static instruction for the one built-in tool chat offers: the sandboxed- * shell. Empty when no sandbox backend enforces, because shell is then- * withheld too — stating limits for a tool that is not offered would only- * confuse the model, and an empty string keeps the prompt prefix stable.- */- /**- * A self-contained digest of the newest memory notes. Chat advertises no- * memory tools, so a catalog it cannot dereference would be useless; whole- * notes under a strict budget are what fit a conversation surface. Empty when- * no note fits, keeping the prompt prefix unchanged for users without memory.- */- buildMemorySystemInstruction(): string {- const digest = memoryDigestNow()- if (!digest) return ''- return [- '# Background Memory',- 'Notes the user previously chose to keep, from earlier conversations.',- 'They may be stale; prefer what this conversation itself establishes.',- '',- digest,- ].join('\n')- }-- buildAgentToolsSystemInstruction(): string {- if (!sandboxEnforces()) return ''- // Stating the limits up front is cheaper than letting the model discover- // them by having a command refused.- return [- '# Shell',- 'shell runs commands in an isolated scratch workspace under an OS',- 'sandbox: it starts there, can only write there, and cannot read files',- "in the user's home directory. The workspace belongs to this",- 'conversation alone and is deleted with it, so do not keep anything',- 'there that should last. It has no network access, so commands that',- 'download or upload will fail.',- ].join(' ')- }-- mapUserInlineAttachments(messages: UIMessage[]): UIMessage[] {- return messages.map((message) => {- if (message.role === 'user') {- const metadata = message.metadata as- | {- inline_file_contents?: Array<{ name?: string; content?: string }>- }- | undefined- const inlineFileContents = Array.isArray(metadata?.inline_file_contents)- ? metadata.inline_file_contents.filter((f) => f?.content)- : []- // Tool messages have content as array of ToolResultPart- if (inlineFileContents.length > 0) {- const buildInlineText = (base: string) => {- if (!inlineFileContents.length) return base- const formatted = inlineFileContents- .map((f) => `File: ${f.name || 'attachment'}\n${f.content ?? ''}`)- .join('\n\n')- return base ? `${base}\n\n${formatted}` : formatted- }-- if (message.parts.length > 0) {- const parts = message.parts.map((part) => {- if (part.type === 'text') {- return {- type: 'text' as const,- text: buildInlineText(part.text ?? ''),+ return finalStream+ }++ async reconnectToStream(+ // eslint-disable-next-line @typescript-eslint/no-unused-vars+ _options: {+ chatId: string+ } & ChatRequestOptions+ ): Promise<ReadableStream<UIMessageChunk> | null> {+ // This function normally handles reconnecting to a stream on the backend, e.g. /api/chat+ // Since this project has no backend, we can't reconnect to a stream, so this is intentionally no-op.+ return null+ }++ // Replace audio `file` parts on user messages with sentinel-bearing `text`+ // parts. The `@ai-sdk/openai-compatible` provider rejects non-image file+ // parts in its converter; the matching fetch wrapper in model-factory.ts+ // decodes these sentinels back into OpenAI `input_audio` content parts on+ // the outgoing wire, which llama-server's chat-completions endpoint accepts.+ encodeAudioAttachments(messages: UIMessage[]): UIMessage[] {+ return messages.map((message) => {+ if (message.role !== 'user' || !Array.isArray(message.parts)) return message+ let touched = false+ const nextParts = message.parts.map((part) => {+ if (+ part?.type === 'file' &&+ typeof (part as { mediaType?: string }).mediaType === 'string' &&+ (part as { mediaType: string }).mediaType.startsWith('audio/') &&+ typeof (part as { url?: string }).url === 'string'+ ) {+ const parsed = parseAudioDataUrl((part as { url: string }).url)+ if (!parsed) return part+ touched = true+ return { type: 'text' as const, text: encodeAudioSentinel(parsed.format, parsed.data) }}- }- return part+ return part})- message.parts = parts- }- }- }+ if (!touched) return message+ return { ...message, parts: nextParts } as UIMessage+ })+ }- return message- })- }+ // Replace video `file` parts on user messages with sentinel-bearing `text`+ // parts, same mechanism as encodeAudioAttachments. The fetch wrapper in+ // model-factory.ts decodes these into llama-server `input_video` content+ // parts (frames decoded via the vision encoder + ffmpeg on the server).+ encodeVideoAttachments(messages: UIMessage[]): UIMessage[] {+ return messages.map((message) => {+ if (message.role !== 'user' || !Array.isArray(message.parts)) return message+ let touched = false+ const nextParts = message.parts.map((part) => {+ if (+ part?.type === 'file' &&+ typeof (part as { mediaType?: string }).mediaType === 'string' &&+ (part as { mediaType: string }).mediaType.startsWith('video/') &&+ typeof (part as { url?: string }).url === 'string'+ ) {+ const parsed = parseVideoDataUrl((part as { url: string }).url)+ if (!parsed) return part+ touched = true+ return { type: 'text' as const, text: encodeVideoSentinel(parsed.data) }+ }+ return part+ })+ if (!touched) return message+ return { ...message, parts: nextParts } as UIMessage+ })+ }++ /**+ * [ATTACHED_FILES] blocks stay on the user message that carries them (see+ * fileMetadata.ts injectFilesIntoPrompt) so the model reads file_ids in the+ * turn they belong to. Only a static, file-independent instruction is added+ * to the system prompt - it never varies per attachment, so it doesn't+ * defeat prompt caching.+ */+ buildFilesSystemInstruction(messages: UIMessage[]): string {+ const hasAttachedFiles = messages.some(+ (message) =>+ message.role === 'user' &&+ Array.isArray(message.parts) &&+ message.parts.some(+ (part) =>+ part?.type === 'text' &&+ typeof (part as { text?: string }).text === 'string' &&+ (part as { text: string }).text.includes('[ATTACHED_FILES]')+ )+ )+ if (!hasAttachedFiles) return ''+ return [+ 'Some user messages contain an [ATTACHED_FILES] block listing files',+ 'attached to that turn (file_id, name, type, size, chunk count, mode).',+ 'Use the available retrieval tools with those file_ids when their',+ 'contents are relevant to the request.',+ ].join(' ')+ }++ /**+ * Static instruction teaching the model to use the native web tools and cite+ * sources inline with [[cite:URL]] markers (rendered as favicon chips). Only+ * added when web search is enabled so it doesn't affect prompt caching for+ * users who keep it off.+ */+ buildWebSearchSystemInstruction(): string {+ if (!useWebSearchConfig.getState().webSearchEnabled) return ''+ return [+ '# Web Access',+ 'You can search the web with web_search and read pages with web_fetch.',+ 'Use them whenever the request needs current, external, or verifiable',+ 'information, then base your answer on what you find. When a statement',+ 'relies on a web source, cite it inline immediately after that statement',+ 'using the exact marker [[cite:URL]], where URL is the full source URL',+ 'from a web_search result (for example: [[cite:https://example.com/page]]).',+ 'Cite each distinct source you rely on; do not add a separate references',+ 'or sources section.',+ ].join(' ')+ }++ /**+ * Static instruction for the one built-in tool chat offers: the sandboxed+ * shell. Empty when no sandbox backend enforces, because shell is then+ * withheld too — stating limits for a tool that is not offered would only+ * confuse the model, and an empty string keeps the prompt prefix stable.+ */+ /**+ * A self-contained digest of the newest memory notes. Chat advertises no+ * memory tools, so a catalog it cannot dereference would be useless; whole+ * notes under a strict budget are what fit a conversation surface. Empty when+ * no note fits, keeping the prompt prefix unchanged for users without memory.+ */+ buildMemorySystemInstruction(): string {+ const digest = memoryDigestNow()+ if (!digest) return ''+ return [+ '# Background Memory',+ 'Notes the user previously chose to keep, from earlier conversations.',+ 'They may be stale; prefer what this conversation itself establishes.',+ '',+ digest,+ ].join('\n')+ }++ buildAgentToolsSystemInstruction(): string {+ if (!sandboxEnforces()) return ''+ // Stating the limits up front is cheaper than letting the model discover+ // them by having a command refused.+ return [+ '# Shell',+ 'shell runs commands in an isolated scratch workspace under an OS',+ 'sandbox: it starts there, can only write there, and cannot read files',+ "in the user's home directory. The workspace belongs to this",+ 'conversation alone and is deleted with it, so do not keep anything',+ 'there that should last. It has no network access, so commands that',+ 'download or upload will fail.',+ ].join(' ')+ }++ mapUserInlineAttachments(messages: UIMessage[]): UIMessage[] {+ return messages.map((message) => {+ if (message.role === 'user') {+ const metadata = message.metadata as+ | {+ inline_file_contents?: Array<{ name?: string; content?: string }>+ }+ | undefined+ const inlineFileContents = Array.isArray(metadata?.inline_file_contents)+ ? metadata.inline_file_contents.filter((f) => f?.content)+ : []+ // Tool messages have content as array of ToolResultPart+ if (inlineFileContents.length > 0) {+ const buildInlineText = (base: string) => {+ if (!inlineFileContents.length) return base+ const formatted = inlineFileContents+ .map((f) => `File: ${f.name || 'attachment'}\n${f.content ?? ''}`)+ .join('\n\n')+ return base ? `${base}\n\n${formatted}` : formatted+ }++ if (message.parts.length > 0) {+ const parts = message.parts.map((part) => {+ if (part.type === 'text') {+ return {+ type: 'text' as const,+ text: buildInlineText(part.text ?? ''),+ }+ }+ return part+ })+ message.parts = parts+ }+ }+ }++ return message+ })+ }}