Skip to content

armgit / jan

Public Imported from GitHub
0

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

fix(chat): keep [ATTACHED_FILES] metadata on the attaching user message

Akarshan Biswas0c985cb7ebe0
diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.ts
index 9d8ef1cd5..22ee65460 100644
--- a/web-app/src/lib/custom-chat-transport.ts
+++ b/web-app/src/lib/custom-chat-transport.ts
@@ -43,7 +43,6 @@ 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 { extractFilesFromPrompt, type FileMetadata } from '@/lib/fileMetadata'
import { isPredefinedRemoteProvider, getProviderApiType } from '@/lib/providerCaps'
import { paramsSettings } from '@/lib/predefinedParams'
@@ -996,7 +995,7 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
// tool_use / tool_result pairing that the Claude API requires.
// See: https://platform.claude.com/docs/en/agents-and-tools/tool-use/implement-tool-use#parallel-tool-use
const effectiveApiType = getProviderApiType(provider)
- let messagesToConvert = (() => {
+ const messagesToConvert = (() => {
if (effectiveApiType !== 'anthropic') {
return options.messages
}
@@ -1044,14 +1043,11 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
const selectedModel = useModelProvider.getState().selectedModel
- const { messages: strippedMessages, files: attachedFiles } =
- this.extractFileMetadataForSystem(messagesToConvert)
- messagesToConvert = strippedMessages
- const filesAddendum = this.buildFilesSystemAddendum(attachedFiles)
- const rawSystem = filesAddendum
+ const filesInstruction = this.buildFilesSystemInstruction(messagesToConvert)
+ const rawSystem = filesInstruction
? this.systemMessage
- ? `${this.systemMessage}\n\n${filesAddendum}`
- : filesAddendum
+ ? `${this.systemMessage}\n\n${filesInstruction}`
+ : filesInstruction
: this.systemMessage
// Drop whitespace-only system prompts so we don't send a useless system
// turn that some chat templates still wrap into special tokens.
@@ -1378,69 +1374,31 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
}
/**
- * Map user messages to include inline attachments in the message parts
- * @param messages
- * @returns
+ * [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.
*/
- /**
- * Strip persisted [ATTACHED_FILES] blocks from user message text and return
- * the aggregated, deduped file metadata so it can be folded into the system
- * prompt instead of the user turn. The stored ThreadMessages are untouched
- * (UI still relies on the inline block for display); this only affects what
- * is sent to the model.
- */
- extractFileMetadataForSystem(
- messages: UIMessage[]
- ): { messages: UIMessage[]; files: FileMetadata[] } {
- const byId = new Map<string, FileMetadata>()
- const next = messages.map((message) => {
- if (message.role !== 'user' || !Array.isArray(message.parts)) return message
- let touched = false
- const parts = message.parts.map((part) => {
- if (
- part?.type === 'text' &&
- typeof (part as { text?: string }).text === 'string' &&
- (part as { text: string }).text.includes('[ATTACHED_FILES]')
- ) {
- const { files, cleanPrompt } = extractFilesFromPrompt(
- (part as { text: string }).text
- )
- if (files.length === 0) return part
- for (const f of files) {
- if (!byId.has(f.id)) byId.set(f.id, f)
- }
- touched = true
- return { ...part, text: cleanPrompt }
- }
- return part
- })
- if (!touched) return message
- return { ...message, parts } as UIMessage
- })
- return { messages: next, files: Array.from(byId.values()) }
- }
-
- /**
- * Format collected file metadata as a system-prompt addendum. The block is
- * stable / parseable so models can reference file_ids when invoking RAG tools.
- */
- buildFilesSystemAddendum(files: FileMetadata[]): string {
- if (files.length === 0) return ''
- const lines = files.map((f) => {
- const parts = [`file_id: ${f.id}`, `name: ${f.name}`]
- if (f.type) parts.push(`type: ${f.type}`)
- if (typeof f.size === 'number') parts.push(`size: ${f.size}`)
- if (typeof f.chunkCount === 'number') parts.push(`chunks: ${f.chunkCount}`)
- if (f.injectionMode) parts.push(`mode: ${f.injectionMode}`)
- return `- ${parts.join(', ')}`
- })
+ 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 [
- 'The user has attached the following files to this conversation.',
- 'Use the available retrieval tools with these file_ids when their contents are relevant.',
- '[ATTACHED_FILES]',
- ...lines,
- '[/ATTACHED_FILES]',
- ].join('\n')
+ '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(' ')
}
mapUserInlineAttachments(messages: UIMessage[]): UIMessage[] {