Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(chat): add Continue button to resume stopped turns in place
Akarshan Biswase4e35ab45552
diff --git a/web-app/src/containers/MessageItem.tsx b/web-app/src/containers/MessageItem.tsxindex 74c29c0bd..93b0ebba5 100644--- a/web-app/src/containers/MessageItem.tsx+++ b/web-app/src/containers/MessageItem.tsx@@ -18,12 +18,14 @@ import {ToolOutput,} from '@/components/ai-elements/tool'import { CopyButton } from './CopyButton'+import { useTranslation } from '@/i18n/react-i18next-compat'import { formatDate } from '@/utils/formatDate'import { useModelProvider } from '@/hooks/useModelProvider'import { useInterfaceSettings } from '@/hooks/useInterfaceSettings'import { useMessageErrors } from '@/stores/message-errors'import {IconRefresh,+ IconPlayerPlay,IconPaperclip,IconArrowDown,IconAlertTriangle,@@ -70,6 +72,7 @@ export type MessageItemProps = {onReasoningScroll?: () => voidonReasoningScrollToBottom?: () => voidonRegenerate?: (messageId: string) => void+ onContinue?: (messageId: string) => voidonEdit?: (messageId: string, newText: string) => voidonDelete?: (messageId: string) => voidversionInfo?: { index: number; count: number }@@ -93,11 +96,13 @@ export const MessageItem = memo(onReasoningScroll,onReasoningScrollToBottom,onRegenerate,+ onContinue,onEdit,onDelete,versionInfo,onSwitchVersion,}: MessageItemProps) => {+ const { t } = useTranslation()const selectedModel = useModelProvider((state) => state.selectedModel)const coloredUserBubble = useInterfaceSettings((s) => s.coloredUserBubble)const metadata = message.metadata as Record<string, unknown> | undefined@@ -113,6 +118,12 @@ export const MessageItem = memo(onRegenerate?.(message.id)}, [onRegenerate, message.id])+ const handleContinue = useCallback(() => {+ onContinue?.(message.id)+ }, [onContinue, message.id])++ const isStopped = metadata?.stopped === true+const handleEdit = useCallback((newText: string) => {onEdit?.(message.id, newText)@@ -838,12 +849,27 @@ export const MessageItem = memo(<DeleteMessageDialog onDelete={handleDelete} />)}+ {selectedModel &&+ onContinue &&+ !isStreaming &&+ isLastMessage &&+ isStopped && (+ <Button+ variant="ghost"+ size="icon-xs"+ onClick={handleContinue}+ title={t('chat:actions.continue')}+ >+ <IconPlayerPlay size={16} />+ </Button>+ )}+{selectedModel && onRegenerate && !isStreaming && isLastMessage && (<Buttonvariant="ghost"size="icon-xs"onClick={handleRegenerate}- title="Regenerate response"+ title={t('chat:actions.regenerate')}><IconRefresh size={16} /></Button>diff --git a/web-app/src/containers/__tests__/MessageItem.test.tsx b/web-app/src/containers/__tests__/MessageItem.test.tsxindex ce3955161..b9cae20df 100644--- a/web-app/src/containers/__tests__/MessageItem.test.tsx+++ b/web-app/src/containers/__tests__/MessageItem.test.tsx@@ -4,6 +4,10 @@ import '@testing-library/jest-dom'// ---- Module mocks ----------------------------------------------------------+vi.mock('@/i18n/react-i18next-compat', () => ({+ useTranslation: () => ({ t: (k: string) => k }),+}))+const selectedModelRef = vi.hoisted(() => ({ current: { id: 'm1' } as any }))vi.mock('@/hooks/useModelProvider', () => ({useModelProvider: (selector: any) =>@@ -182,7 +186,7 @@ describe('MessageItem', () => {onRegenerate={onRegenerate}/>)- const regenBtn = screen.getByTitle('Regenerate response')+ const regenBtn = screen.getByTitle('chat:actions.regenerate')fireEvent.click(regenBtn)expect(onRegenerate).toHaveBeenCalledWith('msg-1')})@@ -198,7 +202,53 @@ describe('MessageItem', () => {onRegenerate={onRegenerate}/>)- expect(screen.queryByTitle('Regenerate response')).not.toBeInTheDocument()+ expect(screen.queryByTitle('chat:actions.regenerate')).not.toBeInTheDocument()+ })++ it('shows Continue button on a stopped last assistant message', () => {+ const onContinue = vi.fn()+ render(+ <MessageItem+ message={+ makeMsg({ metadata: { createdAt: new Date(), stopped: true } }) as any+ }+ isFirstMessage+ isLastMessage+ status={'ready' as any}+ onContinue={onContinue}+ />+ )+ const btn = screen.getByTitle('chat:actions.continue')+ fireEvent.click(btn)+ expect(onContinue).toHaveBeenCalledWith('msg-1')+ })++ it('hides Continue button when the turn finished normally', () => {+ render(+ <MessageItem+ message={makeMsg() as any}+ isFirstMessage+ isLastMessage+ status={'ready' as any}+ onContinue={vi.fn()}+ />+ )+ expect(screen.queryByTitle('chat:actions.continue')).not.toBeInTheDocument()+ })++ it('hides Continue button on a stopped message that is not last', () => {+ render(+ <MessageItem+ message={+ makeMsg({ metadata: { createdAt: new Date(), stopped: true } }) as any+ }+ isFirstMessage+ isLastMessage={false}+ status={'ready' as any}+ onContinue={vi.fn()}+ />+ )+ expect(screen.queryByTitle('chat:actions.continue')).not.toBeInTheDocument()})it('fires onEdit when edit dialog saves', () => {@@ -529,6 +579,6 @@ describe('MessageItem', () => {onRegenerate={onRegenerate}/>)- expect(screen.queryByTitle('Regenerate response')).not.toBeInTheDocument()+ expect(screen.queryByTitle('chat:actions.regenerate')).not.toBeInTheDocument()})})diff --git a/web-app/src/hooks/use-chat.ts b/web-app/src/hooks/use-chat.tsindex 3928adbc0..7edaed320 100644--- a/web-app/src/hooks/use-chat.ts+++ b/web-app/src/hooks/use-chat.ts@@ -1,5 +1,6 @@import {CustomChatTransport,+ type ContinuationContent,} from '@/lib/custom-chat-transport'import {Chat,@@ -115,9 +116,12 @@ export function useChat(}}, [mcpToolNames, ragToolNames])- const setContinueFromContent = useCallback((content: string) => {- transportRef.current?.setContinueFromContent(content)- }, [])+ const setContinueFromContent = useCallback(+ (content: string | ContinuationContent) => {+ transportRef.current?.setContinueFromContent(content)+ },+ []+ )// Expose method to update RAG tools availabilityconst updateRagToolsAvailability = useCallback(diff --git a/web-app/src/lib/__tests__/custom-chat-transport-prefix-stability.test.ts b/web-app/src/lib/__tests__/custom-chat-transport-prefix-stability.test.tsindex c0b4bd3a2..f89f6f54c 100644--- a/web-app/src/lib/__tests__/custom-chat-transport-prefix-stability.test.ts+++ b/web-app/src/lib/__tests__/custom-chat-transport-prefix-stability.test.ts@@ -237,7 +237,21 @@ describe('CustomChatTransport assistant completion (continuation prefill)', () =}>const last = messages[messages.length - 1]expect(last.role).toBe('assistant')- expect(last.content).toBe('Roses are red,')+ expect(last.content).toEqual([{ type: 'text', text: 'Roses are red,' }])+ })++ it('prefills reasoning so a turn stopped mid-thinking resumes inside <think>', async () => {+ const transport = new CustomChatTransport('you are jan', 'thread-1')+ transport.setContinueFromContent({ reasoning: 'let me think', text: '' })+ await drain(await send(transport, history))++ const messages = streamTextCalls[0].messages as Array<{+ role: string+ content: unknown+ }>+ const last = messages[messages.length - 1]+ expect(last.role).toBe('assistant')+ expect(last.content).toEqual([{ type: 'reasoning', text: 'let me think' }])})it('leaves the cached prefix byte-identical (prefill only appends)', async () => {diff --git a/web-app/src/lib/__tests__/message-branching.test.ts b/web-app/src/lib/__tests__/message-branching.test.tsindex 78ab86dea..c5ac53041 100644--- a/web-app/src/lib/__tests__/message-branching.test.ts+++ b/web-app/src/lib/__tests__/message-branching.test.ts@@ -11,6 +11,7 @@ import {makeSibling,withActiveChild,repairDetachedAssistants,+ planContinuation,} from '../message-branching'let clock = 1000@@ -191,4 +192,57 @@ describe('message-branching', () => {expect(parentOf('a2')).toBe('u2')})})++ describe('planContinuation', () => {+ it('inherits the stopped partial parent and marks it for deletion', () => {+ const u = msg('u1', 'user', 'q', { parentId: null })+ const partial = msg('a1', 'assistant', 'half', {+ parentId: 'u1',+ stopped: true,+ })+ const plan = planContinuation([u, partial], 'a2', 'a1', null)+ expect(plan).toEqual({ parentId: 'u1', deletePartialId: 'a1' })+ })++ it('applying the plan leaves the parent with a single child (no fork)', () => {+ const u = msg('u1', 'user', 'q', { parentId: null })+ const partial = msg('a1', 'assistant', 'half', {+ parentId: 'u1',+ stopped: true,+ })+ const reply = msg('a2', 'assistant', 'half and rest', { parentId: 'u1' })+ const plan = planContinuation([u, partial], reply.id, 'a1', null)++ let messages = [u, partial, reply]+ messages = messages.map((m) =>+ m.id === plan.parentId ? withActiveChild(m, reply.id) : m+ )+ if (plan.deletePartialId) {+ messages = messages.filter((m) => m.id !== plan.deletePartialId)+ }++ expect(getSiblings(messages, reply)).toHaveLength(1)+ expect(getVersionInfo(messages, reply)).toEqual({ index: 1, count: 1 })+ expect(ids(computeActivePath(messages))).toEqual(['u1', 'a2'])+ })++ it('falls back to the pending parent when no partial is targeted', () => {+ const u = msg('u1', 'user', 'q', { parentId: null })+ const plan = planContinuation([u], 'a2', null, 'u1')+ expect(plan).toEqual({ parentId: 'u1', deletePartialId: null })+ })++ it('does not delete when the partial id is stale (not found)', () => {+ const u = msg('u1', 'user', 'q', { parentId: null })+ const plan = planContinuation([u], 'a2', 'gone', 'u1')+ expect(plan).toEqual({ parentId: 'u1', deletePartialId: null })+ })++ it('does not delete when the reply reuses the partial id', () => {+ const u = msg('u1', 'user', 'q', { parentId: null })+ const partial = msg('a1', 'assistant', 'half', { parentId: 'u1' })+ const plan = planContinuation([u, partial], 'a1', 'a1', null)+ expect(plan).toEqual({ parentId: 'u1', deletePartialId: null })+ })+ })})diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.tsindex cadc3e082..7a0440a89 100644--- a/web-app/src/lib/custom-chat-transport.ts+++ b/web-app/src/lib/custom-chat-transport.ts@@ -59,6 +59,8 @@ export type OnFinishCallback = (params: {message: UIMessageisAbort?: 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<@@ -661,17 +663,18 @@ function extractLatestUserText(messages: UIMessage[]): string {}/**- * 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.+ * Wraps a UIMessageChunk stream so the partial content of a resumed turn is+ * injected back into the new message right away: `reasoning` into the first+ * `reasoning-start` block and `text` into the first `text-start` block. This+ * makes the continuation look seamless instead of dropping the partial output.*/-function prependTextDeltaToUIStream(+function prependContinuationToUIStream(stream: ReadableStream<UIMessageChunk>,- prefixText: string+ prefix: ContinuationContent): ReadableStream<UIMessageChunk> {const reader = stream.getReader()- let prefixEmitted = false+ let reasoningEmitted = !prefix.reasoning+ let textEmitted = !prefix.textreturn new ReadableStream<UIMessageChunk>({async pull(controller) {try {@@ -681,10 +684,24 @@ function prependTextDeltaToUIStream(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)+ 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)@@ -714,7 +731,7 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {private systemMessage?: stringprivate serviceHub: ServiceHub | nullprivate threadId?: string- private continueFromContent: string | null = null+ private continueFromContent: ContinuationContent | null = null/** Latest user message text — used by the MCP orchestrator for tool routing. */private lastUserMessage = ''/**@@ -993,10 +1010,15 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {/*** Set partial assistant content to send as a prefill on the next request,- * so the model continues generation from where it left off.+ * 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) {- this.continueFromContent = content+ setContinueFromContent(content: string | ContinuationContent) {+ const normalized: ContinuationContent =+ typeof content === 'string' ? { text: content } : content+ this.continueFromContent =+ normalized.text || normalized.reasoning ? normalized : null}async sendMessages(@@ -1222,7 +1244,25 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {const continueContent = this.continueFromContentthis.continueFromContent = nullconst modelMessages = continueContent- ? [...baseMessages, { role: 'assistant' as const, content: 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@@ -1389,7 +1429,7 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {// 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- ? prependTextDeltaToUIStream(uiStream, continueContent)+ ? prependContinuationToUIStream(uiStream, continueContent): uiStreamreturn finalStreamdiff --git a/web-app/src/lib/message-branching.ts b/web-app/src/lib/message-branching.tsindex d395d26b2..4a973eff6 100644--- a/web-app/src/lib/message-branching.ts+++ b/web-app/src/lib/message-branching.ts@@ -203,6 +203,32 @@ export const repairDetachedAssistants = (return [...writes.values()]}+export type ContinuationPlan = {+ parentId: string | null+ deletePartialId: string | null+}++/**+ * Resume a stopped assistant turn in place. The continued reply inherits the+ * stale partial's parent, and that partial is dropped, so the reply replaces it+ * rather than forking a sibling version. Falls back to `fallbackParentId` when+ * no partial is targeted or its id is stale.+ */+export const planContinuation = (+ messages: ThreadMessage[],+ replyId: string,+ partialId: string | null | undefined,+ fallbackParentId: string | null+): ContinuationPlan => {+ const partial = partialId+ ? messages.find((m) => m.id === partialId)+ : undefined+ const parentId = (partial ? getParentId(partial) : null) ?? fallbackParentId+ const deletePartialId =+ partial && partial.id !== replyId ? partial.id : null+ return { parentId, deletePartialId }+}+/*** Build a new sibling version of `source`: fresh id/timestamp, same parent,* no children, optional text override. Used for edit-user / edit-assistant forks.diff --git a/web-app/src/locales/en/chat.json b/web-app/src/locales/en/chat.jsonindex 4a5b099c1..80cd672b8 100644--- a/web-app/src/locales/en/chat.json+++ b/web-app/src/locales/en/chat.json@@ -12,5 +12,9 @@"embeddings": {"title": "Preparing your documents","description": "Indexing the attached files so they can be searched and cited. This may take a moment for large documents."+ },+ "actions": {+ "regenerate": "Regenerate response",+ "continue": "Continue generating"}}\ No newline at end of filediff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsxindex ac7a2e9a1..9b1ae6f8e 100644--- a/web-app/src/routes/threads/$threadId.tsx+++ b/web-app/src/routes/threads/$threadId.tsx@@ -44,6 +44,7 @@ import {getVersionInfo,hasBranching,repairDetachedAssistants,+ planContinuation,} from '@/lib/message-branching'import {ThreadMessage,@@ -241,6 +242,9 @@ function ThreadDetail() {const setContinueFromContentRef = useRef<((content: string) => void) | null>(null)+ const setChatMessagesRef = useRef<+ ((updater: (prev: UIMessage[]) => UIMessage[]) => void) | null+ >(null)// Holds the partial assistant output captured when the model stops with// `finishReason === 'length'`. Consumed by `handleContextSizeIncrease` so// the manual "Increase Context Size" button resumes from where the stream@@ -252,6 +256,10 @@ function ThreadDetail() {// Set before a generation when the resulting assistant message should be// linked to a specific parent (versioning). Consumed once in onFinish.const pendingAssistantParentId = useRef<string | null>(null)+ // Holds the id of a stopped assistant message being resumed. Continuing must+ // extend the turn in place, not fork a new version, so onFinish deletes this+ // stale partial once the continued reply is persisted.+ const continueReplaceIdRef = useRef<string | null>(null)// Use the AI SDK chat hookconst {@@ -273,6 +281,10 @@ function ThreadDetail() {onFinish: ({ message, isAbort }) => {const msgMeta = message.metadata as Record<string, unknown> | undefinedconst finishReason = msgMeta?.finishReason as string | undefined+ // Consume once per generation so a skipped persist (error/empty) can't+ // leak the replace target into a later, unrelated turn.+ const continueReplaceId = continueReplaceIdRef.current+ continueReplaceIdRef.current = null// 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@@ -302,29 +314,62 @@ function ThreadDetail() {}stampContextErrorOnThread(threadId)setContextLimitError(new Error(OUT_OF_CONTEXT_SIZE))+ return}- return+ // Non-context-limit length truncation: fall through and persist the+ // partial marked as stopped so the "Continue" button can resume it.}if (!isAbort && message.parts.length) setPendingContinueMessage(null)+ // The turn ended before completion (user hit Stop, or the model hit its+ // output-token cap). Persist the partial marked `stopped` so the UI can+ // offer a "Continue" affordance, and stamp the live message so the button+ // appears without waiting for a reload.+ const isStoppedTurn = isAbort || finishReason === 'length'+// 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' &&uiMessageHasMeaningfulContent(message)) {const contentParts = extractContentPartsFromUIMessage(message)- const messageMetadata = (message.metadata || {}) as Record<- string,- unknown- >+ const messageMetadata = {+ ...((message.metadata || {}) as Record<string, unknown>),+ ...(isStoppedTurn ? { stopped: true } : {}),+ }++ if (isStoppedTurn) {+ setChatMessagesRef.current?.((prev) =>+ prev.map((m) =>+ m.id === message.id+ ? {+ ...m,+ metadata: {+ ...(m.metadata as Record<string, unknown> | undefined),+ stopped: true,+ },+ }+ : m+ )+ )+ }- let parentForAssistant = pendingAssistantParentId.current+ // A continuation resumes a stopped turn: the stale partial is deleted+ // below so the continued reply takes its place instead of forking a new+ // version. Inherit the partial's parent so the branch link holds.+ const continuation = planContinuation(+ useMessages.getState().getMessages(threadId),+ message.id,+ continueReplaceId,+ pendingAssistantParentId.current+ )pendingAssistantParentId.current = null+ let parentForAssistant = continuation.parentId+// Never persist a detached assistant in a branched thread: if the// pending link was lost (e.g. a multi-step turn consumed the ref before// this reply finished), fall back to the user message this reply@@ -384,6 +429,13 @@ function ThreadDetail() {}}+ // Drop the stale partial so the resumed turn replaces it in place+ // rather than appearing as a separate version of the same reply.+ if (continuation.deletePartialId) {+ deleteMessage(threadId, continuation.deletePartialId)+ useMessageErrors.getState().clearError(continuation.deletePartialId)+ }+for (const m of existingMessages) {const meta = m.metadata as Record<string, unknown> | undefinedif (meta?.error) {@@ -1253,6 +1305,29 @@ function ThreadDetail() {])+ // Resume a turn that was stopped before it finished: replay the partial text+ // as an assistant prefill so the model continues from where it left off. The+ // transport re-emits the partial as the first delta, so the regenerated+ // message reconstitutes partial + new content and the KV cache is reused.+ const handleContinue = useCallback(+ (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')+ if (!text && !reasoning) return+ setContinueFromContent({ text, reasoning })+ continueReplaceIdRef.current = messageId+ handleRegenerate(messageId)+ },+ [chatMessages, setContinueFromContent, handleRegenerate]+ )+// Editing forks a new sibling version (the original + its subtree are kept).// User edits regenerate a reply for the new branch; assistant edits don't.const handleEditMessage = useCallback(@@ -1411,6 +1486,7 @@ function ThreadDetail() {// Keep refs in sync so onFinish always calls the latest versionshandleContextSizeIncreaseRef.current = handleContextSizeIncreasesetContinueFromContentRef.current = setContinueFromContent+ setChatMessagesRef.current = setChatMessagesuseEffect(() => {if (@@ -1595,6 +1671,7 @@ function ThreadDetail() {onReasoningScroll={handleReasoningScroll}onReasoningScrollToBottom={forceScrollReasoningToBottom}onRegenerate={handleRegenerate}+ onContinue={handleContinue}onEdit={handleEditMessage}onDelete={handleDeleteMessage}versionInfo={versionInfoById[message.id]}