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: auto increase context size (#7609)

Louise2146cd5f7cf
diff --git a/web-app/src/containers/MessageItem.tsx b/web-app/src/containers/MessageItem.tsx
index e7e34f70f..0e0dc9723 100644
--- a/web-app/src/containers/MessageItem.tsx
+++ b/web-app/src/containers/MessageItem.tsx
@@ -48,6 +48,8 @@ export type MessageItemProps = {
onDelete?: (messageId: string) => void
assistant?: { avatar?: React.ReactNode; name?: string }
showAssistant?: boolean
+ isAnimating?: boolean
+ hideActions?: boolean
}
export const MessageItem = memo(
@@ -55,6 +57,8 @@ export const MessageItem = memo(
message,
isLastMessage,
status,
+ isAnimating,
+ hideActions,
reasoningContainerRef,
onRegenerate,
onEdit,
@@ -185,6 +189,7 @@ export const MessageItem = memo(
content={part.text}
isStreaming={isStreaming && isLastPart}
messageId={message.id}
+ isAnimating={isAnimating}
/>
</>
)}
@@ -345,7 +350,7 @@ export const MessageItem = memo(
})}
{/* Message actions for user messages */}
- {message.role === 'user' && (
+ {message.role === 'user' && !hideActions && (
<div className="flex items-center justify-end gap-1 text-muted-foreground text-xs mt-4">
<CopyButton text={getFullTextContent()} />
@@ -369,7 +374,7 @@ export const MessageItem = memo(
<div
className={cn(
'flex items-center gap-1',
- isStreaming && 'hidden'
+ (isStreaming || hideActions) && 'hidden'
)}
>
<CopyButton text={getFullTextContent()} />
@@ -434,7 +439,8 @@ export const MessageItem = memo(
prevProps.isFirstMessage === nextProps.isFirstMessage &&
prevProps.isLastMessage === nextProps.isLastMessage &&
prevProps.status === nextProps.status &&
- prevProps.showAssistant === nextProps.showAssistant
+ prevProps.showAssistant === nextProps.showAssistant &&
+ prevProps.hideActions === nextProps.hideActions
)
}
)
diff --git a/web-app/src/containers/RenderMarkdown.tsx b/web-app/src/containers/RenderMarkdown.tsx
index 1360bb291..6733947f1 100644
--- a/web-app/src/containers/RenderMarkdown.tsx
+++ b/web-app/src/containers/RenderMarkdown.tsx
@@ -21,6 +21,7 @@ interface MarkdownProps {
isUser?: boolean
isStreaming?: boolean
messageId?: string
+ isAnimating?: boolean
}
// Cache for normalized LaTeX content
@@ -85,6 +86,7 @@ function RenderMarkdownComponent({
isUser,
components,
messageId,
+ isAnimating
}: MarkdownProps) {
// Memoize the normalized content to avoid reprocessing on every render
@@ -101,7 +103,7 @@ function RenderMarkdownComponent({
)}
>
<Streamdown
- animate={true}
+ animate={isAnimating ?? true}
animationDuration={500}
linkSafety={{
enabled: false,
diff --git a/web-app/src/hooks/use-chat.ts b/web-app/src/hooks/use-chat.ts
index 53a2d249b..8a6632b23 100644
--- a/web-app/src/hooks/use-chat.ts
+++ b/web-app/src/hooks/use-chat.ts
@@ -126,6 +126,10 @@ export function useChat(
}
}, [mcpToolNames, ragToolNames])
+ const setContinueFromContent = useCallback((content: string) => {
+ transportRef.current?.setContinueFromContent(content)
+ }, [])
+
// Expose method to update RAG tools availability
const updateRagToolsAvailability = useCallback(
async (
@@ -147,5 +151,6 @@ export function useChat(
return {
...chatResult,
updateRagToolsAvailability,
+ setContinueFromContent,
}
}
diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.ts
index 169e07d81..7982db0b9 100644
--- a/web-app/src/lib/custom-chat-transport.ts
+++ b/web-app/src/lib/custom-chat-transport.ts
@@ -48,6 +48,38 @@ export type ServiceHub = {
}
}
+/**
+ * Wraps a UIMessageChunk stream so that when the first `text-start` chunk
+ * arrives, a `text-delta` carrying `prefixText` is immediately injected into
+ * the same text block. This makes the new message show the partial content
+ * right away while continuation tokens stream in after it.
+ */
+function prependTextDeltaToUIStream(
+ stream: ReadableStream<UIMessageChunk>,
+ prefixText: string
+): ReadableStream<UIMessageChunk> {
+ const reader = stream.getReader()
+ let prefixEmitted = false
+ return new ReadableStream<UIMessageChunk>({
+ async pull(controller) {
+ const { done, value } = await reader.read()
+ if (done) {
+ controller.close()
+ return
+ }
+ controller.enqueue(value)
+ if (!prefixEmitted && (value as { type: string }).type === 'text-start') {
+ prefixEmitted = true
+ const id = (value as { type: 'text-start'; id: string }).id
+ controller.enqueue({ type: 'text-delta', id, delta: prefixText } as UIMessageChunk)
+ }
+ },
+ cancel() {
+ reader.cancel()
+ },
+ })
+}
+
export class CustomChatTransport implements ChatTransport<UIMessage> {
public model: LanguageModel | null = null
private tools: Record<string, Tool> = {}
@@ -58,6 +90,7 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
private systemMessage?: string
private serviceHub: ServiceHub | null
private threadId?: string
+ private continueFromContent: string | null = null
constructor(systemMessage?: string, threadId?: string) {
this.systemMessage = systemMessage
@@ -213,6 +246,14 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
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.
+ */
+ setContinueFromContent(content: string) {
+ this.continueFromContent = content
+ }
+
async sendMessages(
options: {
chatId: string
@@ -258,10 +299,18 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
}
// Convert UI messages to model messages
- const modelMessages = convertToModelMessages(
+ const baseMessages = convertToModelMessages(
this.mapUserInlineAttachments(options.messages)
)
+ // 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 }]
+ : baseMessages
+
// Include tools only if we have tools loaded AND model supports them
const hasTools = Object.keys(this.tools).length > 0
const selectedModel = useModelProvider.getState().selectedModel
@@ -282,7 +331,7 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
let tokensPerSecond = 0
- return result.toUIMessageStream({
+ const uiStream = result.toUIMessageStream({
messageMetadata: ({ part }) => {
// Track stream start time on start
if (part.type === 'start' && !streamStartTime) {
@@ -320,6 +369,7 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
}
return {
+ finishReason: finishPart.finishReason,
usage: {
inputTokens: inputTokens,
outputTokens: outputTokens,
@@ -364,6 +414,13 @@ export class CustomChatTransport implements ChatTransport<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.
+ return continueContent
+ ? prependTextDeltaToUIStream(uiStream, continueContent)
+ : uiStream
}
async reconnectToStream(
diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsx
index dab38c110..71657b559 100644
--- a/web-app/src/routes/threads/$threadId.tsx
+++ b/web-app/src/routes/threads/$threadId.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useMemo, useRef } from 'react'
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { createFileRoute, useParams } from '@tanstack/react-router'
import { cn } from '@/lib/utils'
@@ -52,6 +52,7 @@ import { useToolApproval } from '@/hooks/useToolApproval'
import DropdownModelProvider from '@/containers/DropdownModelProvider'
import { ExtensionTypeEnum, VectorDBExtension } from '@janhq/core'
import { ExtensionManager } from '@/lib/extension'
+import { Shimmer } from '@/components/ai-elements/shimmer'
const CHAT_STATUS = {
STREAMING: 'streaming',
@@ -126,6 +127,18 @@ function ThreadDetail() {
threadRef.current = thread
}, [thread])
+ // Holds the partial assistant message while the model reloads after a
+ // context-limit hit, so the user sees it instead of a blank gap.
+ const [pendingContinueMessage, setPendingContinueMessage] =
+ useState<UIMessage | null>(null)
+ const [isAutoIncreasingContext, setIsAutoIncreasingContext] = useState(false)
+
+ // Refs so onFinish (captured in closure) always calls the latest callbacks
+ const handleContextSizeIncreaseRef = useRef<(() => void) | null>(null)
+ const setContinueFromContentRef = useRef<((content: string) => void) | null>(
+ null
+ )
+
// Use the AI SDK chat hook
const {
messages: chatMessages,
@@ -137,26 +150,47 @@ function ThreadDetail() {
stop,
addToolOutput,
updateRagToolsAvailability,
+ setContinueFromContent,
} = useChat({
sessionId: threadId,
sessionTitle: thread?.title,
systemMessage,
experimental_throttle: 50,
onFinish: ({ message, isAbort }) => {
- // Persist assistant message to backend (skip if aborted)
+ const msgMeta = message.metadata as Record<string, unknown> | undefined
+ const finishReason = msgMeta?.finishReason as string | undefined
+
+ // Context limit hit: send partial content as prefill so the model continues
+ // from where it stopped. The stream wrapper injects it as the first text-delta
+ // of the new message, so the user sees the partial text immediately.
+ if (!isAbort && finishReason === 'length') {
+ const partialText = message.parts
+ .filter((p) => p.type === 'text')
+ .map((p) => (p as { type: 'text'; text: string }).text)
+ .join('')
+ if (partialText) {
+ setContinueFromContentRef.current?.(partialText)
+ // Keep the partial message visible while the model reloads
+ setPendingContinueMessage(message)
+ }
+ handleContextSizeIncreaseRef.current?.()
+ return
+ }
+
+ if (!isAbort && message.parts.length) setPendingContinueMessage(null)
+
+ // Persist assistant message to backend (skip if aborted).
+ // For continuations, message.parts already contains partial + new content
+ // because the stream wrapper prepended the partial text as the first delta.
if (!isAbort && message.role === 'assistant') {
- // Extract content parts (including tool calls) as separate items in the content array
- // This preserves the natural ordering: text -> tool call -> text -> tool call, etc.
const contentParts = extractContentPartsFromUIMessage(message)
if (contentParts.length > 0) {
- // Extract metadata from the message (including usage and tokenSpeed)
const messageMetadata = (message.metadata || {}) as Record<
string,
unknown
>
- // Create assistant message with content parts (including tool calls) and metadata
const assistantMessage: ThreadMessage = {
type: 'text',
role: ChatCompletionRole.Assistant,
@@ -223,7 +257,6 @@ function ThreadDetail() {
// Route to the appropriate service based on tool name
if (ragToolNames.has(toolName)) {
-
result = await serviceHub.rag().callTool({
toolName,
arguments: toolCall.input,
@@ -699,8 +732,11 @@ function ThreadDetail() {
// Increase context length by 50%
const currentCtxLen =
- (model.settings?.ctx_len?.controller_props?.value as number) ?? 8192
- const newCtxLen = Math.round(Math.max(8192, currentCtxLen) * 1.5)
+ (model.settings?.ctx_len?.controller_props?.value as number) ?? 32768
+ const newCtxLen =
+ currentCtxLen < 32768
+ ? 32768
+ : Math.round(Math.max(32768, currentCtxLen) * 1.5)
const updatedModel = {
...model,
@@ -736,6 +772,32 @@ function ThreadDetail() {
handleRegenerate,
])
+ // Keep refs in sync so onFinish always calls the latest versions
+ handleContextSizeIncreaseRef.current = handleContextSizeIncrease
+ setContinueFromContentRef.current = setContinueFromContent
+
+ // Auto-trigger context size increase when the model reports a context limit error
+ useEffect(() => {
+ if (!error) return
+ const isContextError =
+ (error.message?.toLowerCase().includes('context') &&
+ (error.message?.toLowerCase().includes('size') ||
+ error.message?.toLowerCase().includes('length') ||
+ error.message?.toLowerCase().includes('limit'))) ||
+ error.message === OUT_OF_CONTEXT_SIZE
+ if (isContextError) {
+ setIsAutoIncreasingContext(true)
+ handleContextSizeIncrease()
+ }
+ }, [error]) // eslint-disable-line react-hooks/exhaustive-deps
+
+ // Clear once the new stream starts
+ useEffect(() => {
+ if (isAutoIncreasingContext && status === 'streaming') {
+ setIsAutoIncreasingContext(false)
+ }
+ }, [status]) // eslint-disable-line react-hooks/exhaustive-deps
+
const threadModel = useMemo(() => thread?.model, [thread])
return (
@@ -766,11 +828,35 @@ function ThreadDetail() {
onRegenerate={handleRegenerate}
onEdit={handleEditMessage}
onDelete={handleDeleteMessage}
+ isAnimating={!pendingContinueMessage}
+ hideActions={!!pendingContinueMessage}
/>
)
})}
- {status === CHAT_STATUS.SUBMITTED && <PromptProgress />}
- {error && (
+ {pendingContinueMessage && status === 'submitted' && (
+ <MessageItem
+ key={`continue-placeholder-${pendingContinueMessage.id}`}
+ message={pendingContinueMessage}
+ isFirstMessage={false}
+ isLastMessage={true}
+ status={status}
+ reasoningContainerRef={reasoningContainerRef}
+ onRegenerate={handleRegenerate}
+ onEdit={handleEditMessage}
+ onDelete={handleDeleteMessage}
+ hideActions
+ isAnimating={false}
+ />
+ )}
+ {(status === CHAT_STATUS.SUBMITTED || isAutoIncreasingContext) && (
+ <div className="flex flex-row items-center gap-2">
+ {(pendingContinueMessage || isAutoIncreasingContext) && (
+ <Shimmer duration={1}>Growing the Mind...</Shimmer>
+ )}
+ {status === CHAT_STATUS.SUBMITTED && <PromptProgress />}
+ </div>
+ )}
+ {error && !isAutoIncreasingContext && (
<div className="px-4 py-3 mx-4 my-2 rounded-lg border border-destructive/10 bg-destructive/10">
<div className="flex items-start gap-3">
<IconAlertCircle className="size-5 text-destructive shrink-0 mt-0.5" />
@@ -779,7 +865,10 @@ function ThreadDetail() {
Error generating response
</p>
<div className="table table-fixed w-full">
- <span className="text-sm text-muted-foreground table-cell align-middle" style={{wordWrap: "break-word"}}>
+ <span
+ className="text-sm text-muted-foreground table-cell align-middle"
+ style={{ wordWrap: 'break-word' }}
+ >
{error.message}
</span>
</div>