Skip to content

armgit / jan

Public Imported from GitHub
0

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

fix(web-app): ask for 'auto' attachments when the inline budget is gone at send time (#9234)

Akarshan Biswasd364ac199e55
diff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsx
index cd2ef3f9a..98b9729bd 100644
--- a/web-app/src/containers/ChatInput.tsx
+++ b/web-app/src/containers/ChatInput.tsx
@@ -88,7 +88,6 @@ import { useAttachments } from '@/hooks/useAttachments'
import { toast } from 'sonner'
import { isPlatformTauri } from '@/lib/platform/utils'
import { shouldShowTokenCounter } from '@/lib/tokenCounterVisibility'
-import { useAttachmentIngestionPrompt } from '@/hooks/useAttachmentIngestionPrompt'
import {
NEW_THREAD_ATTACHMENT_KEY,
useChatAttachments,
@@ -102,7 +101,9 @@ import {
createVideoAttachment,
} from '@/types/attachment'
import {
+ applyIngestionChoices,
needsIngestionChoice,
+ promptIngestionChoices,
resolveAutoInlineBudget,
} from '@/lib/attachmentProcessing'
import { activePathTokens } from '@/lib/message-branching'
@@ -137,7 +138,10 @@ type ChatInputProps = {
files?: Array<{ type: 'file'; mediaType: string; url: string }>,
/** Document attachments, for surfaces that do not read them back out of
* the attachments store themselves. */
- documents?: Attachment[]
+ documents?: Attachment[],
+ /** What the user typed, before @path references were expanded into
+ * `text`, so a cancelled send can hand it back unchanged. */
+ draft?: string
) => void
onStop?: () => void
chatStatus?: ChatStatus
@@ -709,7 +713,8 @@ const ChatInput = memo(function ChatInput({
onSubmit(
effectivePrompt,
files.length > 0 ? files : undefined,
- documents.length > 0 ? documents : undefined
+ documents.length > 0 ? documents : undefined,
+ prompt
)
setPrompt('')
clearAttachmentsForThread(attachmentsKey)
@@ -726,6 +731,7 @@ const ChatInput = memo(function ChatInput({
const messagePayload = {
text: effectivePrompt,
+ draft: prompt,
files: [] as Array<{ type: string; mediaType: string; url: string }>,
}
@@ -899,8 +905,8 @@ const ChatInput = memo(function ChatInput({
// (processAttachmentsForSend inside processAndSendMessage), where
// 'auto' documents are routed by size when the model's window is known.
// Same conversation-aware budget as the send path (the active branch,
- // which is what gets sent), so 'auto' asks here exactly when send time
- // would have no budget to decide by.
+ // which is what gets sent). If the budget is gone by send time, the
+ // send path asks for the remaining 'auto' documents itself.
const hasInlineBudget =
(await resolveAutoInlineBudget(
selectedModel,
@@ -919,39 +925,26 @@ const ChatInput = memo(function ChatInput({
)
if (docsNeedingPrompt.length > 0) {
- const choices = new Map<string, 'inline' | 'embeddings'>()
- for (let i = 0; i < docsNeedingPrompt.length; i++) {
- const doc = docsNeedingPrompt[i]
- const choice = await useAttachmentIngestionPrompt
- .getState()
- .showPrompt(doc, i, docsNeedingPrompt.length)
-
- if (!choice) {
- // User cancelled — remove all pending docs
- setAttachmentsForThread(attachmentsKey, (prev) =>
- prev.filter(
- (att) =>
- !docsNeedingPrompt.some(
- (d) => d.path && att.path && d.path === att.path
- )
- )
- )
- return
- }
+ const choices = await promptIngestionChoices(docsNeedingPrompt)
- if (doc.path) {
- choices.set(doc.path, choice)
- }
+ if (!choices) {
+ // User cancelled — remove all pending docs
+ setAttachmentsForThread(attachmentsKey, (prev) =>
+ prev.filter(
+ (att) =>
+ !docsNeedingPrompt.some(
+ (d) => d.path && att.path && d.path === att.path
+ )
+ )
+ )
+ return
}
// Persist each document's chosen mode so processAttachmentsForSend
// can pick it up at send time.
if (choices.size > 0) {
setAttachmentsForThread(attachmentsKey, (prev) =>
- prev.map((att) => {
- const mode = att.path ? choices.get(att.path) : undefined
- return mode ? { ...att, parseMode: mode } : att
- })
+ applyIngestionChoices(prev, choices)
)
}
}
diff --git a/web-app/src/containers/__tests__/ChatInput.test.tsx b/web-app/src/containers/__tests__/ChatInput.test.tsx
index fb657d14e..c9010d270 100644
--- a/web-app/src/containers/__tests__/ChatInput.test.tsx
+++ b/web-app/src/containers/__tests__/ChatInput.test.tsx
@@ -398,7 +398,12 @@ describe('ChatInput', () => {
renderInput({ onSubmit })
fireEvent.keyDown(getTextarea(), { key: 'Enter' })
await waitFor(() =>
- expect(onSubmit).toHaveBeenCalledWith('hello world', undefined, undefined)
+ expect(onSubmit).toHaveBeenCalledWith(
+ 'hello world',
+ undefined,
+ undefined,
+ 'hello world'
+ )
)
expect(addToHistoryMock).toHaveBeenCalledWith('hello world')
expect(setPromptMock).toHaveBeenCalledWith('')
@@ -432,7 +437,12 @@ describe('ChatInput', () => {
) as HTMLButtonElement
fireEvent.click(btn)
await waitFor(() =>
- expect(onSubmit).toHaveBeenCalledWith('button submit', undefined, undefined)
+ expect(onSubmit).toHaveBeenCalledWith(
+ 'button submit',
+ undefined,
+ undefined,
+ 'button submit'
+ )
)
})
@@ -547,7 +557,8 @@ describe('ChatInput', () => {
url: 'data:image/png;base64,xxx',
}),
]),
- undefined
+ undefined,
+ 'with image'
)
)
expect(clearAttachmentsMock).toHaveBeenCalled()
@@ -562,9 +573,12 @@ describe('ChatInput', () => {
renderInput({ onSubmit })
fireEvent.keyDown(getTextarea(), { key: 'Enter' })
await waitFor(() =>
- expect(onSubmit).toHaveBeenCalledWith('read this', undefined, [
- expect.objectContaining({ name: 'spec.pdf', path: '/docs/spec.pdf' }),
- ])
+ expect(onSubmit).toHaveBeenCalledWith(
+ 'read this',
+ undefined,
+ [expect.objectContaining({ name: 'spec.pdf', path: '/docs/spec.pdf' })],
+ 'read this'
+ )
)
})
diff --git a/web-app/src/lib/__tests__/attachmentProcessing.test.ts b/web-app/src/lib/__tests__/attachmentProcessing.test.ts
index 7174b2f2f..6e68d23b3 100644
--- a/web-app/src/lib/__tests__/attachmentProcessing.test.ts
+++ b/web-app/src/lib/__tests__/attachmentProcessing.test.ts
@@ -1,11 +1,14 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import {
+ applyIngestionChoices,
needsIngestionChoice,
processAttachmentsForSend,
+ promptIngestionChoices,
resolveAutoInlineBudget,
type AttachmentProcessingResult,
} from '../attachmentProcessing'
import type { Attachment } from '@/types/attachment'
+import { useAttachmentIngestionPrompt } from '@/hooks/useAttachmentIngestionPrompt'
// Minimal mock for ServiceHub methods used by processAttachmentsForSend
const createMockServiceHub = (overrides: Record<string, unknown> = {}) => ({
@@ -331,6 +334,12 @@ describe('processAttachmentsForSend', () => {
expect(needsIngestionChoice(docAttachment(), 'auto', false)).toBe(true)
})
+ it('asks for a document recorded as auto when the budget is gone', () => {
+ expect(
+ needsIngestionChoice(docAttachment({ parseMode: 'auto' }), 'inline', false)
+ ).toBe(true)
+ })
+
it('never asks for explicit modes or already-routed documents', () => {
expect(needsIngestionChoice(docAttachment(), 'inline', false)).toBe(false)
expect(
@@ -341,4 +350,53 @@ describe('processAttachmentsForSend', () => {
).toBe(false)
})
})
+
+ describe('promptIngestionChoices', () => {
+ const answerNextPrompt = async (choice: 'inline' | 'embeddings' | undefined) => {
+ await vi.waitFor(() =>
+ expect(useAttachmentIngestionPrompt.getState().isModalOpen).toBe(true)
+ )
+ const state = useAttachmentIngestionPrompt.getState()
+ if (choice) state.choose(choice)
+ else state.cancel()
+ }
+
+ it('collects one choice per document, keyed by path', async () => {
+ const docs = [
+ docAttachment({ path: '/a.pdf' }),
+ docAttachment({ path: '/b.pdf' }),
+ ]
+ const pending = promptIngestionChoices(docs)
+ await answerNextPrompt('inline')
+ await answerNextPrompt('embeddings')
+ const choices = await pending
+ expect([...(choices ?? [])]).toEqual([
+ ['/a.pdf', 'inline'],
+ ['/b.pdf', 'embeddings'],
+ ])
+ })
+
+ it('is undefined as soon as the user cancels', async () => {
+ const pending = promptIngestionChoices([
+ docAttachment({ path: '/a.pdf' }),
+ docAttachment({ path: '/b.pdf' }),
+ ])
+ await answerNextPrompt(undefined)
+ await expect(pending).resolves.toBeUndefined()
+ expect(useAttachmentIngestionPrompt.getState().isModalOpen).toBe(false)
+ })
+
+ it('records each choice as the document parse mode', () => {
+ const docs = [
+ docAttachment({ path: '/a.pdf', parseMode: 'auto' }),
+ docAttachment({ path: '/b.pdf', parseMode: 'auto' }),
+ imageAttachment(),
+ ]
+ const applied = applyIngestionChoices(
+ docs,
+ new Map([['/a.pdf', 'inline' as const]])
+ )
+ expect(applied.map((a) => a.parseMode)).toEqual(['inline', 'auto', undefined])
+ })
+ })
})
diff --git a/web-app/src/lib/attachmentProcessing.ts b/web-app/src/lib/attachmentProcessing.ts
index adab14829..bb62ec58e 100644
--- a/web-app/src/lib/attachmentProcessing.ts
+++ b/web-app/src/lib/attachmentProcessing.ts
@@ -2,6 +2,7 @@ import { ServiceHub } from '@/services'
import { Attachment } from '@/types/attachment'
import { toast } from 'sonner'
import { estimateTokens } from '@/lib/context-manager'
+import { useAttachmentIngestionPrompt } from '@/hooks/useAttachmentIngestionPrompt'
import {
getLocalPropsExtension,
readCtxLen,
@@ -113,8 +114,10 @@ export const resolveAutoInlineBudget = async (
}
/**
- * Whether the user must pick inline vs embeddings for a document at attach
- * time. 'auto' only asks when there is no budget to decide by size.
+ * Whether the user must pick inline vs embeddings for a document. 'auto' only
+ * asks when there is no budget to decide by size. Checked at attach time and
+ * again at send time, since the budget can disappear in between (model
+ * switched or unloaded, conversation grown).
*/
export const needsIngestionChoice = (
doc: Attachment,
@@ -126,6 +129,38 @@ export const needsIngestionChoice = (
return preference === 'prompt' || (preference === 'auto' && !hasInlineBudget)
}
+export type IngestionChoice = 'inline' | 'embeddings'
+
+/**
+ * Asks the user, one document at a time, whether to inline or embed it.
+ * Resolves to each choice keyed by document path, or undefined as soon as the
+ * user cancels.
+ */
+export const promptIngestionChoices = async (
+ docs: Attachment[]
+): Promise<Map<string, IngestionChoice> | undefined> => {
+ const choices = new Map<string, IngestionChoice>()
+ for (let i = 0; i < docs.length; i++) {
+ const doc = docs[i]
+ const choice = await useAttachmentIngestionPrompt
+ .getState()
+ .showPrompt(doc, i, docs.length)
+ if (!choice) return undefined
+ if (doc.path) choices.set(doc.path, choice)
+ }
+ return choices
+}
+
+/** Records each choice as its document's parseMode, which send time honours. */
+export const applyIngestionChoices = (
+ attachments: Attachment[],
+ choices: Map<string, IngestionChoice>
+): Attachment[] =>
+ attachments.map((att) => {
+ const mode = att.path ? choices.get(att.path) : undefined
+ return mode ? { ...att, parseMode: mode } : att
+ })
+
export const processAttachmentsForSend = async (
options: AttachmentProcessingOptions
): Promise<AttachmentProcessingResult> => {
diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsx
index d4c650f08..78d2864f0 100644
--- a/web-app/src/routes/threads/$threadId.tsx
+++ b/web-app/src/routes/threads/$threadId.tsx
@@ -66,9 +66,13 @@ import {
NEW_THREAD_ATTACHMENT_KEY,
} from '@/hooks/useChatAttachments'
import {
+ applyIngestionChoices,
+ needsIngestionChoice,
processAttachmentsForSend,
+ promptIngestionChoices,
resolveAutoInlineBudget,
} from '@/lib/attachmentProcessing'
+import { usePrompt } from '@/hooks/usePrompt'
import { useAttachments } from '@/hooks/useAttachments'
import { PromptProgress } from '@/components/PromptProgress'
import { useToolAvailable } from '@/hooks/useToolAvailable'
@@ -189,6 +193,9 @@ function ThreadDetail() {
const clearAttachmentsForThread = useChatAttachments(
(state) => state.clearAttachments
)
+ const setAttachmentsForThread = useChatAttachments(
+ (state) => state.setAttachments
+ )
// Session data for tool call tracking
const getSessionData = useChatSessions((state) => state.getSessionData)
@@ -1015,7 +1022,8 @@ function ThreadDetail() {
const processAndSendMessage = useCallback(
async (
text: string,
- files?: Array<{ type: string; mediaType: string; url: string }>
+ files?: Array<{ type: string; mediaType: string; url: string }>,
+ draft: string = text
) => {
// Cancel any in-flight title summarization so it doesn't compete with this request
titleAbortRef.current?.abort()
@@ -1067,11 +1075,52 @@ function ThreadDetail() {
: storeMediaAttachments
// Combine media attachments with document attachments from the store
- const combinedAttachments = [
+ let combinedAttachments = [
...mediaAttachments,
...allAttachments.filter((a) => a.type === 'document'),
]
+ const projectId = thread?.metadata?.project?.id
+ const { parseMode: parsePreference, autoInlineContextRatio } =
+ useAttachments.getState()
+ const contextThreshold = combinedAttachments.some(
+ (a) => a.type === 'document' && !a.processed
+ )
+ ? await resolveAutoInlineBudget(
+ useModelProvider.getState().selectedModel,
+ selectedProvider,
+ autoInlineContextRatio,
+ estimateConversationTokens(chatMessagesRef.current)
+ )
+ : undefined
+ // The budget can be gone since attach time (model switched or unloaded,
+ // conversation grown), so 'auto' documents that would now silently
+ // fall back to embeddings are put to the user. Project files always
+ // embed, so there is nothing to ask.
+ const unrouted =
+ projectId || contextThreshold !== undefined
+ ? []
+ : combinedAttachments.filter(
+ (a) =>
+ a.type === 'document' &&
+ needsIngestionChoice(a, parsePreference, false)
+ )
+ if (unrouted.length > 0) {
+ const choices = await promptIngestionChoices(unrouted)
+ if (!choices) {
+ // ChatInput cleared the input on submit; hand the draft back so
+ // cancelling only cancels the send. `text` has @path references
+ // expanded, so restore what the user actually typed.
+ setAttachmentsForThread(attachmentsKey, allAttachments)
+ usePrompt.getState().setPrompt(draft)
+ return
+ }
+ combinedAttachments = applyIngestionChoices(
+ combinedAttachments,
+ choices
+ )
+ }
+
const messageId = generateId()
const hasDocuments = combinedAttachments.some(
(a) => a.type === 'document' && !a.processed
@@ -1104,15 +1153,12 @@ function ThreadDetail() {
// Process attachments (ingest images, parse/index documents)
let processedAttachments = combinedAttachments
- const projectId = thread?.metadata?.project?.id
if (combinedAttachments.length > 0) {
if (hasEmbeddingDocuments) {
useAppState.getState().setThreadEmbedding(threadId, true)
useAppState.getState().setThreadBusy(threadId, true)
}
try {
- const { parseMode: parsePreference, autoInlineContextRatio } =
- useAttachments.getState()
const result = await processAttachmentsForSend({
attachments: combinedAttachments,
threadId,
@@ -1120,12 +1166,7 @@ function ThreadDetail() {
serviceHub,
selectedProvider,
parsePreference,
- contextThreshold: await resolveAutoInlineBudget(
- useModelProvider.getState().selectedModel,
- selectedProvider,
- autoInlineContextRatio,
- estimateConversationTokens(chatMessagesRef.current)
- ),
+ contextThreshold,
})
processedAttachments = result.processedAttachments
@@ -1226,6 +1267,7 @@ function ThreadDetail() {
attachmentsKey,
setChatMessages,
clearAttachmentsForThread,
+ setAttachmentsForThread,
serviceHub,
selectedProvider,
]
@@ -1269,10 +1311,15 @@ function ThreadDetail() {
try {
const message = JSON.parse(storedMessage) as {
text: string
+ draft?: string
files?: Array<{ type: string; mediaType: string; url: string }>
}
- await processAndSendMessage(message.text, message.files)
+ await processAndSendMessage(
+ message.text,
+ message.files,
+ message.draft
+ )
} catch (error) {
console.error('Failed to parse initial message:', error)
}
@@ -1321,10 +1368,13 @@ function ThreadDetail() {
const handleSubmit = useCallback(
async (
text: string,
- files?: Array<{ type: string; mediaType: string; url: string }>
+ files?: Array<{ type: string; mediaType: string; url: string }>,
+ // This route reads documents back out of the attachments store.
+ _documents?: unknown,
+ draft?: string
) => {
clearBannerErrors()
- await processAndSendMessage(text, files)
+ await processAndSendMessage(text, files, draft)
},
[processAndSendMessage, clearBannerErrors]
)
diff --git a/web-app/src/routes/threads/__tests__/$threadId.test.tsx b/web-app/src/routes/threads/__tests__/$threadId.test.tsx
index a4e87f4d8..d62b9707a 100644
--- a/web-app/src/routes/threads/__tests__/$threadId.test.tsx
+++ b/web-app/src/routes/threads/__tests__/$threadId.test.tsx
@@ -98,6 +98,7 @@ const h = vi.hoisted(() => {
const attachmentsState: any = {
getAttachments: vi.fn(() => []),
clearAttachments: vi.fn(),
+ setAttachments: vi.fn(),
}
const useChatAttachmentsMock: any = (selector: any) => selector(attachmentsState)
useChatAttachmentsMock.getState = () => attachmentsState
@@ -201,6 +202,19 @@ vi.mock('@/containers/ChatInput', () => ({
>
send
</button>
+ <button
+ data-testid="chat-send-ref"
+ onClick={() =>
+ onSubmit(
+ 'summarise\n\n---\nReferenced file contents:\n\nbody',
+ undefined,
+ undefined,
+ 'summarise @notes.md'
+ )
+ }
+ >
+ send with reference
+ </button>
<button data-testid="chat-stop" onClick={() => onStop()}>
stop
</button>
@@ -325,6 +339,14 @@ vi.mock('@/lib/attachmentProcessing', () => ({
.fn()
.mockResolvedValue({ processedAttachments: [], hasEmbeddedDocuments: false }),
resolveAutoInlineBudget: vi.fn().mockResolvedValue(6144),
+ needsIngestionChoice: vi.fn(
+ (doc: any, pref: string) => (doc.parseMode ?? pref) === 'auto'
+ ),
+ promptIngestionChoices: vi.fn(),
+ applyIngestionChoices: (atts: any[], choices: Map<string, string>) =>
+ atts.map((a) =>
+ choices.has(a.path) ? { ...a, parseMode: choices.get(a.path) } : a
+ ),
}))
vi.mock('@/lib/thread-title-summarizer', () => ({
@@ -419,8 +441,10 @@ import { useToolCallRuntime } from '@/hooks/useToolCallRuntime'
import { useMessageErrors } from '@/stores/message-errors'
import {
processAttachmentsForSend,
+ promptIngestionChoices,
resolveAutoInlineBudget,
} from '@/lib/attachmentProcessing'
+import { usePrompt } from '@/hooks/usePrompt'
// The global setup mock is a shared object, so an overridden factory has to be
// put back or it leaks into every later test.
@@ -557,9 +581,91 @@ describe('ThreadDetail route', () => {
contextThreshold: 6144,
parsePreference: 'auto',
})
+ expect(promptIngestionChoices).not.toHaveBeenCalled()
h.attachmentsState.getAttachments = vi.fn(() => [])
})
+ describe('when the auto-inline budget is gone at send time', () => {
+ const sheet = {
+ name: 'sheet.xlsx',
+ type: 'document',
+ path: '/sheet.xlsx',
+ parseMode: 'auto',
+ }
+
+ beforeEach(() => {
+ // Cloud model, unloaded auto-fit model, or a conversation that has
+ // outgrown the window all resolve to no budget.
+ vi.mocked(resolveAutoInlineBudget).mockResolvedValueOnce(undefined)
+ h.attachmentsState.getAttachments = vi.fn(() => [sheet])
+ })
+
+ it('asks the user and sends the document the way they chose', async () => {
+ vi.mocked(promptIngestionChoices).mockResolvedValueOnce(
+ new Map([['/sheet.xlsx', 'inline']])
+ )
+ renderComponent()
+ await act(async () => {
+ screen.getByTestId('chat-send').click()
+ })
+ await waitFor(() => {
+ expect(processAttachmentsForSend).toHaveBeenCalled()
+ })
+ expect(promptIngestionChoices).toHaveBeenCalledWith([sheet])
+ expect(
+ vi.mocked(processAttachmentsForSend).mock.calls[0][0].attachments
+ ).toEqual([{ ...sheet, parseMode: 'inline' }])
+ h.attachmentsState.getAttachments = vi.fn(() => [])
+ })
+
+ it('cancelling keeps the draft and sends nothing', async () => {
+ vi.mocked(promptIngestionChoices).mockResolvedValueOnce(undefined)
+ renderComponent()
+ await act(async () => {
+ screen.getByTestId('chat-send').click()
+ })
+ await waitFor(() => {
+ expect(h.attachmentsState.setAttachments).toHaveBeenCalledWith(
+ 'thread-1',
+ [sheet]
+ )
+ })
+ expect(usePrompt.getState().prompt).toBe('hello world')
+ expect(processAttachmentsForSend).not.toHaveBeenCalled()
+ expect(h.mockSendMessage).not.toHaveBeenCalled()
+ expect(h.messagesState.addMessage).not.toHaveBeenCalled()
+ h.attachmentsState.getAttachments = vi.fn(() => [])
+ usePrompt.getState().resetPrompt()
+ })
+
+ it('cancelling restores the typed draft, not the expanded @references', async () => {
+ vi.mocked(promptIngestionChoices).mockResolvedValueOnce(undefined)
+ renderComponent()
+ await act(async () => {
+ screen.getByTestId('chat-send-ref').click()
+ })
+ await waitFor(() => {
+ expect(usePrompt.getState().prompt).toBe('summarise @notes.md')
+ })
+ expect(h.mockSendMessage).not.toHaveBeenCalled()
+ h.attachmentsState.getAttachments = vi.fn(() => [])
+ usePrompt.getState().resetPrompt()
+ })
+
+ it('does not ask for project threads, whose files always embed', async () => {
+ h.threadsState.threads['thread-1'].metadata = { project: { id: 'p1' } }
+ renderComponent()
+ await act(async () => {
+ screen.getByTestId('chat-send').click()
+ })
+ await waitFor(() => {
+ expect(processAttachmentsForSend).toHaveBeenCalled()
+ })
+ expect(promptIngestionChoices).not.toHaveBeenCalled()
+ h.attachmentsState.getAttachments = vi.fn(() => [])
+ })
+ })
+
it('invokes stop when ChatInput calls onStop', () => {
renderComponent()
screen.getByTestId('chat-stop').click()