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): stop persisting detached assistant replies in branched threads (#8376)

Akarshan Biswasd7c27c61c960
diff --git a/web-app/src/lib/__tests__/message-branching.test.ts b/web-app/src/lib/__tests__/message-branching.test.ts
index 5c6b2c645..78ab86dea 100644
--- a/web-app/src/lib/__tests__/message-branching.test.ts
+++ b/web-app/src/lib/__tests__/message-branching.test.ts
@@ -10,6 +10,7 @@ import {
backfillParentIds,
makeSibling,
withActiveChild,
+ repairDetachedAssistants,
} from '../message-branching'
let clock = 1000
@@ -109,4 +110,85 @@ describe('message-branching', () => {
expect(ids(computeActivePath(m))).toEqual(['a2'])
expect(ids(computeActivePath(m, 'a1'))).toEqual(['a1'])
})
+
+ describe('repairDetachedAssistants', () => {
+ it('re-parents a detached assistant to the preceding user turn', () => {
+ // u1 -> a1(BROKEN: parentId null) -> u2(-> a1); a1 is a phantom root that
+ // computeActivePath drops, so only u1 renders.
+ const u1 = msg('u1', 'user', 'hi', { parentId: null })
+ const a1 = msg('a1', 'assistant', 'reply', { parentId: null })
+ const u2 = msg('u2', 'user', 'again', { parentId: 'a1' })
+ const before = [u1, a1, u2]
+ // Broken: a1 is a second null-parent root, so computeActivePath picks it
+ // as the (newest) root and drops the real u1 turn from the path.
+ expect(ids(computeActivePath(before))).toEqual(['a1', 'u2'])
+
+ const repaired = repairDetachedAssistants(before)
+ expect(repaired).toHaveLength(1)
+ expect(repaired[0].id).toBe('a1')
+ expect(getParentId(repaired[0])).toBe('u1')
+
+ const fixed = before.map((m) => repaired.find((r) => r.id === m.id) ?? m)
+ expect(ids(computeActivePath(fixed))).toEqual(['u1', 'a1', 'u2'])
+ })
+
+ it('is a no-op on healthy branched threads', () => {
+ const u1 = msg('u1', 'user', 'hi', { parentId: null })
+ const a1 = msg('a1', 'assistant', 'reply', { parentId: 'u1' })
+ expect(repairDetachedAssistants([u1, a1])).toEqual([])
+ })
+
+ it('is a no-op on legacy un-branched threads', () => {
+ const m = [msg('a', 'user', 'hi'), msg('b', 'assistant', 'yo')]
+ expect(repairDetachedAssistants(m)).toEqual([])
+ })
+
+ it('leaves a detached assistant with no preceding user untouched', () => {
+ const a1 = msg('a1', 'assistant', 'orphan', { parentId: null })
+ const u1 = msg('u1', 'user', 'hi', { parentId: null })
+ expect(repairDetachedAssistants([a1, u1])).toEqual([])
+ })
+
+ it('repairs the real-world pattern: undefined-parent assistants with the next user mis-linked to the previous user', () => {
+ // Reproduces thread 03d08945: branched thread where assistant replies lost
+ // their parentId entirely (undefined) and each following user was linked to
+ // the PREVIOUS user, skipping the reply. Repair must re-parent the reply AND
+ // re-link the following user onto it so the whole tail rejoins the path.
+ const u1 = msg('u1', 'user', 'q1', { parentId: null })
+ const a1 = msg('a1', 'assistant', 'r1', { parentId: 'u1' })
+ const u2 = msg('u2', 'user', 'q2', { parentId: 'a1' })
+ const a2 = msg('a2', 'assistant', 'r2') // parentId missing (undefined)
+ const u3 = msg('u3', 'user', 'q3', { parentId: 'u2' }) // mis-linked to u2
+ const a3 = msg('a3', 'assistant', 'r3') // parentId missing (undefined)
+ const before = [u1, a1, u2, a2, u3, a3]
+ // Broken: a2 and a3 are dropped, only users survive after u2.
+ expect(ids(computeActivePath(before))).toEqual(['u1', 'a1', 'u2', 'u3'])
+
+ const repaired = repairDetachedAssistants(before)
+ const fixed = before.map((m) => repaired.find((r) => r.id === m.id) ?? m)
+ expect(ids(computeActivePath(fixed))).toEqual([
+ 'u1',
+ 'a1',
+ 'u2',
+ 'a2',
+ 'u3',
+ 'a3',
+ ])
+ // Idempotent: a second pass finds nothing to write.
+ expect(repairDetachedAssistants(fixed)).toEqual([])
+ })
+
+ it('repairs multiple detached assistants to their nearest user by created_at', () => {
+ const u1 = msg('u1', 'user', 'q1', { parentId: null })
+ const a1 = msg('a1', 'assistant', 'r1', { parentId: null })
+ const u2 = msg('u2', 'user', 'q2', { parentId: 'a1' })
+ const a2 = msg('a2', 'assistant', 'r2', { parentId: null })
+ const repaired = repairDetachedAssistants([u1, a1, u2, a2])
+ const parentOf = (id: string) =>
+ getParentId(repaired.find((r) => r.id === id)!)
+ expect(repaired.map((r) => r.id).sort()).toEqual(['a1', 'a2'])
+ expect(parentOf('a1')).toBe('u1')
+ expect(parentOf('a2')).toBe('u2')
+ })
+ })
})
diff --git a/web-app/src/lib/message-branching.ts b/web-app/src/lib/message-branching.ts
index b9d7e0c9e..d395d26b2 100644
--- a/web-app/src/lib/message-branching.ts
+++ b/web-app/src/lib/message-branching.ts
@@ -1,4 +1,9 @@
-import { ThreadMessage, ContentType, MessageStatus } from '@janhq/core'
+import {
+ ThreadMessage,
+ ContentType,
+ MessageStatus,
+ ChatCompletionRole,
+} from '@janhq/core'
type ThreadContent = NonNullable<ThreadMessage['content']>[number]
@@ -139,6 +144,65 @@ export const backfillParentIds = (path: ThreadMessage[]): ThreadMessage[] => {
return path.map((m, i) => withParentId(m, i === 0 ? null : path[i - 1].id))
}
+/**
+ * Repair threads corrupted on disk by the assistant-orphan bug (#8357 and its
+ * earlier variants): in a branched thread an assistant reply was persisted with
+ * a detached parent link -- either `parentId: null` or no `parentId` at all.
+ * `computeActivePath` then treats it as a phantom root / non-child and drops it,
+ * so the conversation renders as user messages in a row with the replies gone.
+ *
+ * The break compounds: because the reply is detached, the *following* user turn
+ * was linked to the previous user instead of to that reply, so the whole tail
+ * hangs off the wrong nodes. Repair each detached assistant by:
+ * 1. re-parenting it to the user turn it answers (nearest preceding user by
+ * `created_at`, mirroring `resolveAssistantParent`), and
+ * 2. re-linking the user turn that follows it (currently a child of that same
+ * user) onto the assistant, restoring the alternating chain so every later
+ * turn rejoins the active path.
+ * Genuine version forks are preserved: only detached assistants and the single
+ * user turn each one displaced are touched.
+ *
+ * Returns only the messages that need a write (empty when nothing is broken).
+ * Idempotent: once linked, an assistant has a string parent and is skipped.
+ * No-op on legacy (un-branched) threads -- without branching, `computeActivePath`
+ * returns messages unchanged, so a missing parent is harmless there.
+ */
+export const repairDetachedAssistants = (
+ messages: ThreadMessage[]
+): ThreadMessage[] => {
+ if (!hasBranching(messages)) return []
+ const ordered = [...messages].sort(byCreatedAt)
+ const writes = new Map<string, ThreadMessage>()
+ const parentOf = (m: ThreadMessage) => rawParent(writes.get(m.id) ?? m)
+
+ for (let i = 0; i < ordered.length; i++) {
+ const a = ordered[i]
+ if (a.role !== ChatCompletionRole.Assistant) continue
+ const p = parentOf(a)
+ if (p !== null && p !== undefined) continue
+
+ let user: ThreadMessage | undefined
+ for (let j = i - 1; j >= 0; j--) {
+ if (ordered[j].role === ChatCompletionRole.User) {
+ user = ordered[j]
+ break
+ }
+ }
+ if (!user) continue
+ writes.set(a.id, withParentId(writes.get(a.id) ?? a, user.id))
+
+ for (let j = i + 1; j < ordered.length; j++) {
+ const c = ordered[j]
+ if (c.role === ChatCompletionRole.User && parentOf(c) === user.id) {
+ writes.set(c.id, withParentId(writes.get(c.id) ?? c, a.id))
+ break
+ }
+ }
+ }
+
+ return [...writes.values()]
+}
+
/**
* 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/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsx
index f34dd65b8..c2bde1d63 100644
--- a/web-app/src/routes/threads/$threadId.tsx
+++ b/web-app/src/routes/threads/$threadId.tsx
@@ -42,6 +42,7 @@ import {
getSiblings,
getVersionInfo,
hasBranching,
+ repairDetachedAssistants,
} from '@/lib/message-branching'
import {
ThreadMessage,
@@ -313,9 +314,21 @@ function ThreadDetail() {
unknown
>
- const parentForAssistant = pendingAssistantParentId.current
+ let parentForAssistant = pendingAssistantParentId.current
pendingAssistantParentId.current = null
+ // 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
+ // answers. A null parentId would make computeActivePath treat the
+ // assistant as a phantom root and drop it from the visible path.
+ if (
+ parentForAssistant == null &&
+ hasBranching(useMessages.getState().getMessages(threadId))
+ ) {
+ parentForAssistant = resolveAssistantParent(undefined)
+ }
+
const assistantMessage: ThreadMessage = {
type: 'text',
role: ChatCompletionRole.Assistant,
@@ -690,6 +703,16 @@ function ThreadDetail() {
}
}
+ // Migrate threads corrupted by the pre-#8357 bug: assistant replies
+ // saved with parentId:null are phantom roots that computeActivePath
+ // drops. Re-parent them to the user turn they answer and persist.
+ const repaired = repairDetachedAssistants(messagesToSet)
+ if (repaired.length > 0) {
+ const byId = new Map(repaired.map((m) => [m.id, m]))
+ messagesToSet = messagesToSet.map((m) => byId.get(m.id) ?? m)
+ for (const m of repaired) updateMessage(m)
+ }
+
setMessages(threadId, messagesToSet)
const hydrated: Record<string, string> = {}
@@ -1031,27 +1054,34 @@ function ThreadDetail() {
}
}, [threadId, updateMessage])
+ // Dismiss any active thread-level banner error and strip its persisted
+ // metadata. The banner stands in for a failed last assistant turn (hidden by
+ // the render filter), so leaving it set would blank a healthy assistant on
+ // whatever branch we navigate to next.
+ const clearBannerErrors = useCallback(() => {
+ if (oomError) setOomError(undefined)
+ if (backendError) setBackendError(undefined)
+ if (contextLimitError) setContextLimitError(null)
+ if (oomError || backendError || contextLimitError) stripBannerMetadata()
+ }, [
+ oomError,
+ setOomError,
+ backendError,
+ setBackendError,
+ contextLimitError,
+ stripBannerMetadata,
+ ])
+
// Handle submit from ChatInput
const handleSubmit = useCallback(
async (
text: string,
files?: Array<{ type: string; mediaType: string; url: string }>
) => {
- if (oomError) setOomError(undefined)
- if (backendError) setBackendError(undefined)
- if (contextLimitError) setContextLimitError(null)
- if (oomError || backendError || contextLimitError) stripBannerMetadata()
+ clearBannerErrors()
await processAndSendMessage(text, files)
},
- [
- processAndSendMessage,
- oomError,
- setOomError,
- backendError,
- setBackendError,
- contextLimitError,
- stripBannerMetadata,
- ]
+ [processAndSendMessage, clearBannerErrors]
)
// Versioning helpers --------------------------------------------------------
@@ -1114,10 +1144,11 @@ function ThreadDetail() {
if (!next) return
titleAbortRef.current?.abort()
titleAbortRef.current = null
+ clearBannerErrors()
setActiveBranch(next)
syncActivePath()
},
- [threadId, setActiveBranch, syncActivePath]
+ [threadId, setActiveBranch, syncActivePath, clearBannerErrors]
)
// Resolve the user message that an assistant reply hangs off of.
diff --git a/web-app/src/routes/threads/__tests__/$threadId.test.tsx b/web-app/src/routes/threads/__tests__/$threadId.test.tsx
index 4c2b55f86..cd5e668d8 100644
--- a/web-app/src/routes/threads/__tests__/$threadId.test.tsx
+++ b/web-app/src/routes/threads/__tests__/$threadId.test.tsx
@@ -298,6 +298,8 @@ vi.mock('@/lib/messages', () => ({
msg.parts
.filter((p: any) => p.type === 'text')
.map((p: any) => ({ type: 'text', text: { value: p.text, annotations: [] } })),
+ uiMessageHasMeaningfulContent: (msg: any) =>
+ !!msg?.parts?.some((p: any) => p.type === 'text' && p.text?.trim()),
}))
vi.mock('@/lib/completion', () => ({
@@ -334,18 +336,21 @@ vi.mock('zustand/react/shallow', () => ({
}))
vi.mock('@/hooks/use-chat', () => ({
- useChat: (_args: any) => ({
- messages: h.chatState.messages,
- status: h.chatState.status,
- error: h.chatState.error,
- sendMessage: h.mockSendMessage,
- regenerate: h.mockRegenerate,
- setMessages: h.mockSetChatMessages,
- stop: h.mockStop,
- addToolOutput: h.mockAddToolOutput,
- updateRagToolsAvailability: h.mockUpdateRag,
- setContinueFromContent: h.mockSetContinueFromContent,
- }),
+ useChat: (_args: any) => {
+ ;(h as any).capturedOnFinish = _args?.onFinish
+ return {
+ messages: h.chatState.messages,
+ status: h.chatState.status,
+ error: h.chatState.error,
+ sendMessage: h.mockSendMessage,
+ regenerate: h.mockRegenerate,
+ setMessages: h.mockSetChatMessages,
+ stop: h.mockStop,
+ addToolOutput: h.mockAddToolOutput,
+ updateRagToolsAvailability: h.mockUpdateRag,
+ setContinueFromContent: h.mockSetContinueFromContent,
+ }
+ },
}))
vi.mock('@/hooks/useThreads', () => ({ useThreads: h.useThreadsMock }))
@@ -436,6 +441,8 @@ describe('ThreadDetail route', () => {
h.messageQueueState.dequeue = vi.fn(() => null)
h.messageQueueState.clearQueue = vi.fn()
h.agentModeState.agentThreads = {}
+ h.modelProviderState.selectedProvider = 'openai'
+ h.appStateState.oomError = undefined
sessionStorage.clear()
})
@@ -583,6 +590,99 @@ describe('ThreadDetail route', () => {
expect(h.mockRegenerate).not.toHaveBeenCalled()
})
+ it('clears an active banner error when switching versions so a healthy assistant is not hidden', () => {
+ // A prior turn left a router OOM banner active. Without clearing it on
+ // switch, the render filter blanks the last assistant of whatever branch we
+ // land on, leaving only user messages visible.
+ h.modelProviderState.selectedProvider = 'llamacpp'
+ h.appStateState.oomError = 'router crashed'
+ const branched = [
+ {
+ id: 'u1',
+ role: 'user',
+ created_at: 1,
+ content: [{ type: 'text', text: { value: 'hi', annotations: [] } }],
+ metadata: { parentId: null },
+ },
+ {
+ id: 'a1a',
+ role: 'assistant',
+ created_at: 2,
+ content: [{ type: 'text', text: { value: 'v1', annotations: [] } }],
+ metadata: { parentId: 'u1' },
+ },
+ {
+ id: 'a1b',
+ role: 'assistant',
+ created_at: 3,
+ content: [{ type: 'text', text: { value: 'v2', annotations: [] } }],
+ metadata: { parentId: 'u1' },
+ },
+ ]
+ h.messagesState.messages = { 'thread-1': branched }
+ h.messagesState.getMessages = vi.fn(() => branched)
+ // a1b is rendered mid-list (a trailing user turn keeps it off the
+ // last-message filter) so its version nav stays clickable.
+ h.chatState.messages = [
+ { id: 'u1', role: 'user', parts: [{ type: 'text', text: 'hi' }] },
+ { id: 'a1b', role: 'assistant', parts: [{ type: 'text', text: 'v2' }] },
+ { id: 'u2', role: 'user', parts: [{ type: 'text', text: 'more' }] },
+ ]
+ renderComponent()
+ screen.getByTestId('prev-a1b').click()
+ expect(h.appStateState.setOomError).toHaveBeenCalledWith(undefined)
+ expect(h.mockRegenerate).not.toHaveBeenCalled()
+ })
+
+ it('onFinish links a new assistant to the active user turn in a branched thread (never null parent)', () => {
+ // Regression for #8357: once a thread is branched, a lost pending-parent ref
+ // must not persist the assistant with parentId:null (which computeActivePath
+ // drops as a phantom root, leaving "user messages in a row").
+ const branched = [
+ {
+ id: 'u1',
+ role: 'user',
+ created_at: 1,
+ content: [{ type: 'text', text: { value: 'hi', annotations: [] } }],
+ metadata: { parentId: null },
+ },
+ {
+ id: 'a1',
+ role: 'assistant',
+ created_at: 2,
+ content: [{ type: 'text', text: { value: 'r1', annotations: [] } }],
+ metadata: { parentId: 'u1' },
+ },
+ {
+ id: 'u2',
+ role: 'user',
+ created_at: 3,
+ content: [{ type: 'text', text: { value: 'again', annotations: [] } }],
+ metadata: { parentId: 'a1' },
+ },
+ ]
+ h.messagesState.getMessages = vi.fn(() => branched)
+ renderComponent()
+
+ act(() => {
+ ;(h as any).capturedOnFinish({
+ message: {
+ id: 'a2',
+ role: 'assistant',
+ parts: [{ type: 'text', text: 'reply for u2' }],
+ metadata: {},
+ },
+ isAbort: false,
+ })
+ })
+
+ const added = h.messagesState.addMessage.mock.calls.map((c: any[]) => c[0])
+ const persisted = added.find((m: any) => m.id === 'a2')
+ expect(persisted).toBeTruthy()
+ expect(persisted.metadata.parentId).toBe('u2')
+ expect(persisted.metadata.parentId).not.toBeNull()
+ })
+
it('delete removes message from store and chat list', () => {
h.chatState.messages = [
{ id: 'u1', role: 'user', parts: [{ type: 'text', text: 'hi' }] },