Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(chat): keep the reply of a turn that fills the local context instead of dropping it (#9393)
Thinh Le9a24144804e2
diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsxindex c5bdc1624..631e5f959 100644--- a/web-app/src/routes/threads/$threadId.tsx+++ b/web-app/src/routes/threads/$threadId.tsx@@ -160,7 +160,7 @@ const continueReplaceIds = new Map<string, string>()// "Increase Context Size" button to resume from.const pendingContinuations = new Map<string,- { message: UIMessage; text: string }+ { message: UIMessage; content: { text: string; reasoning: string } }>()// The n_ctx the thread's local model launched with, read by isContextLimitStop.const launchedCtxLens = new Map<string, number | undefined>()@@ -168,6 +168,17 @@ const launchedCtxLens = new Map<string, number | undefined>()// cancels it.const titleAborts = new Map<string, AbortController>()+// The text and reasoning a reply generated so far: what a resume replays as+// the assistant prefill, so a thinking model keeps its reasoning.+const partialOf = (message: UIMessage) => {+ const collect = (type: 'text' | 'reasoning') =>+ message.parts+ .filter((p) => p.type === type)+ .map((p) => (p as { text: string }).text)+ .join('')+ return { text: collect('text'), reasoning: collect('reasoning') }+}+const takeFrom = <V,>(map: Map<string, V>, threadId: string) => {const value = map.get(threadId)map.delete(threadId)@@ -535,13 +546,10 @@ function ThreadDetail() {if (isContextLimit) {// Stash the partial so the manual "Increase Context Size" button can// resume from here. Surface the standard banner with the manual- // button — auto-increase was removed; the user explicitly opts in.- const partialText = message.parts- .filter((p) => p.type === 'text')- .map((p) => (p as { type: 'text'; text: string }).text)- .join('')- if (partialText) {- pendingContinuations.set(threadId, { message, text: partialText })+ // button - auto-increase was removed; the user explicitly opts in.+ const content = partialOf(message)+ if (content.text || content.reasoning) {+ pendingContinuations.set(threadId, { message, content })}// Stamped on the thread's own messages, so a thread that finished in// the background shows the banner when the user returns to it.@@ -549,10 +557,11 @@ function ThreadDetail() {if (openThreadIdRef.current === threadId) {setContextLimitError(new Error(OUT_OF_CONTEXT_SIZE))}- return+ // Falls through to store the partial as a stopped reply: returning+ // here dropped everything the model had generated.}- // Non-context-limit length truncation: fall through and persist the- // partial marked as stopped so the "Continue" button can resume it.+ // Any other length stop is the output-token cap: the partial is stored+ // as stopped so the "Continue" button can resume it.}if (!isAbort && message.parts.length) clearPendingContinue(threadId)@@ -1908,13 +1917,7 @@ function ThreadDetail() {(messageId: string) => {const msg = chatMessages.find((m) => m.id === messageId)if (!msg) return- const collect = (type: 'text' | 'reasoning') =>- msg.parts- .filter((p) => p.type === type)- .map((p) => (p as { text: string }).text)- .join('')- const text = collect('text')- const reasoning = collect('reasoning')+ const { text, reasoning } = partialOf(msg)if (!text && !reasoning) returnsetContinueFromContent({ text, reasoning })continueReplaceIds.set(threadId, messageId)@@ -1982,6 +1985,21 @@ function ThreadDetail() {const handleContextSizeIncrease = useCallback(async () => {if (!selectedModel) return+ // The reply this click resumes if the turn that stopped is not in+ // pendingContinuations (a restart empties it): the stored partial, marked+ // `stopped`, that hydration restored. Read before the awaits below, while+ // the open thread is still this one.+ const lastMessage = chatMessagesRef.current.at(-1)+ const stoppedPartial =+ lastMessage?.role === 'assistant' &&+ (lastMessage.metadata as { stopped?: boolean } | undefined)?.stopped+ ? { message: lastMessage, content: partialOf(lastMessage) }+ : undefined+ const storedPartial =+ stoppedPartial?.content.text || stoppedPartial?.content.reasoning+ ? stoppedPartial+ : undefined+const updateProvider = useModelProvider.getState().updateProviderconst provider = getProviderByName(selectedProvider)if (!provider) return@@ -2058,21 +2076,27 @@ function ThreadDetail() {await serviceHub.models().stopModel(selectedModel.id)}- // Consume any pending partial captured at the `finishReason === 'length'`- // event so the regenerate resumes from where the stream stopped, and the- // "Growing the Mind…" shimmer renders while the model reloads.+ // Resume from the partial the reply stopped at: the one captured at the+ // `finishReason === 'length'` event, or, when none was (the Map is empty+ // after an application restart), the stored reply read above. The+ // regenerate then continues it, and the "Growing the Mind…" shimmer renders+ // while the model reloads.// The prefill goes on this thread's own transport: the user may have// opened another thread while the model reloaded.- const pending = takeFrom(pendingContinuations, threadId)+ const pending =+ takeFrom(pendingContinuations, threadId) ?? storedPartialif (pending) {useChatSessions.getState()- .sessions[threadId]?.transport.setContinueFromContent(pending.text)+ .sessions[threadId]?.transport.setContinueFromContent(pending.content)setPendingContinue({ threadId, message: pending.message })+ // The partial is stored (see onFinish), so the resumed reply replaces it+ // in place rather than forking a second version of the same answer.+ continueReplaceIds.set(threadId, pending.message.id)}setTimeout(() => {- handleRegenerate()+ handleRegenerate(pending?.message.id)}, 1000)}, [selectedModel,@@ -2254,12 +2278,15 @@ function ThreadDetail() {{chatMessages.map((message, index) => {const isLastMessage = index === chatMessages.length - 1const isFirstMessage = index === 0- // A banner error stands in for the failed assistant turn:- // regenerate/reload restarts it from scratch, so hide the- // partial (tool calls, "Worked for Ns") and show only the banner.+ // An out-of-memory or backend error stands in for the failed+ // assistant turn: regenerate/reload restarts it from scratch, so+ // hide the partial (tool calls, "Worked for Ns") and show only+ // the banner. A context-limit stop keeps its partial: that text+ // was generated and stored, and the banner only offers a bigger+ // context to resume it.if (isLastMessage &&- hasBannerError &&+ (oomError || backendError) &&message.role === 'assistant')return nulldiff --git a/web-app/src/routes/threads/__tests__/$threadId.test.tsx b/web-app/src/routes/threads/__tests__/$threadId.test.tsxindex da6f7b34c..b814d1c64 100644--- a/web-app/src/routes/threads/__tests__/$threadId.test.tsx+++ b/web-app/src/routes/threads/__tests__/$threadId.test.tsx@@ -1056,17 +1056,132 @@ describe('ThreadDetail route', () => {expect(screen.queryByText('Increase Context Size')).toBeNull()})- it('still offers Increase Context Size for a local model near ctx_len', () => {+ // A reply that fills a local model's context was generated; dropping it left+ // the user with only their own message and a banner.+ it('keeps the partial reply of a local model near ctx_len, with the banner', () => {h.modelProviderState.selectedProvider = 'llamacpp'renderComponent()act(() => {finishAtLength()})- expect(- h.messagesState.addMessage.mock.calls.some((c: any[]) => c[0].id === 'a-len')- ).toBe(false)+ const added = h.messagesState.addMessage.mock.calls.map((c: any[]) => c[0])+ const persisted = added.find((m: any) => m.id === 'a-len')+ expect(persisted).toBeTruthy()+ expect(persisted.metadata.stopped).toBe(true)expect(screen.getByText('Increase Context Size')).toBeInTheDocument()})++ // Clicks Increase Context Size and lets its delayed regenerate fire. Returns+ // what the click replayed to the thread's transport as the assistant prefill.+ const increaseContext = async () => {+ const setContinueFromContent = vi.fn()+ h.chatSessionsState.sessions = {+ 'thread-1': {+ transport: { getTurnModelSelection: () => null, setContinueFromContent },+ },+ }+ const realModels = hub.models as () => Record<string, unknown>+ hub.models = () => ({+ ...realModels(),+ updateModelSettings: vi.fn().mockResolvedValue(undefined),+ })+ vi.useFakeTimers()+ try {+ await act(async () => {+ screen.getByText('Increase Context Size').click()+ })+ await act(async () => {+ vi.advanceTimersByTime(1000)+ })+ } finally {+ vi.clearAllTimers()+ vi.useRealTimers()+ hub.models = realModels+ h.chatSessionsState.sessions = {}+ }+ return setContinueFromContent+ }++ // The saved partial is in memory only; after a restart the stopped reply is+ // what hydration restored. Increase Context Size resumes it in place instead+ // of regenerating from scratch and keeping the partial as another version,+ // and replays its reasoning with its text.+ it('resumes the stored partial in place after an application restart', async () => {+ h.modelProviderState.selectedProvider = 'llamacpp'+ h.chatState.status = 'error'+ h.chatState.error = new Error(+ 'request (518 tokens) exceeds the available context size (512 tokens)'+ )+ h.chatState.messages = [+ { id: 'u1', role: 'user', parts: [{ type: 'text', text: 'q' }] },+ {+ id: 'a-len',+ role: 'assistant',+ parts: [+ { type: 'reasoning', text: 'thinking' },+ { type: 'text', text: 'partial answer' },+ ],+ metadata: { stopped: true, parentId: 'u1' },+ },+ ]+ const stored = [+ { id: 'u1', role: 'user', thread_id: 'thread-1', content: [], metadata: { parentId: null } },+ { id: 'a-len', role: 'assistant', thread_id: 'thread-1', content: [], metadata: { stopped: true, parentId: 'u1' } },+ ]+ h.messagesState.getMessages = vi.fn(() => stored)+ renderComponent()+ const onFinish = (h as any).capturedOnFinish++ const prefill = await increaseContext()+ expect(h.mockRegenerate).toHaveBeenCalledWith({ messageId: 'a-len' })+ expect(prefill).toHaveBeenCalledWith({+ text: 'partial answer',+ reasoning: 'thinking',+ })++ act(() => {+ onFinish({+ message: {+ id: 'a-new',+ role: 'assistant',+ parts: [{ type: 'text', text: 'partial answer, done' }],+ metadata: {},+ },+ isAbort: false,+ isError: false,+ })+ })+ expect(h.messagesState.deleteMessage).toHaveBeenCalledWith('thread-1', 'a-len')+ })++ // A thinking model can fill the context while still reasoning: there is no+ // text yet, but the reasoning is what to resume from.+ it('resumes a reply that filled the context while still reasoning', async () => {+ h.modelProviderState.selectedProvider = 'llamacpp'+ renderComponent()+ act(() => {+ ;(h as any).capturedOnFinish({+ message: {+ id: 'a-len',+ role: 'assistant',+ parts: [{ type: 'reasoning', text: 'still thinking' }],+ metadata: {+ finishReason: 'length',+ usage: { inputTokens: 30000, outputTokens: 4000 },+ },+ },+ isAbort: false,+ isError: false,+ })+ })++ const prefill = await increaseContext()+ expect(h.mockRegenerate).toHaveBeenCalledWith({ messageId: 'a-len' })+ expect(prefill).toHaveBeenCalledWith({+ text: '',+ reasoning: 'still thinking',+ })+ })})// #9311: a turn keeps running after the user opens another thread, and its