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.

feat(chat): version branching for edited/regenerated messages

Akarshan Biswasfb90fc062bc3
diff --git a/web-app/src/containers/MessageItem.tsx b/web-app/src/containers/MessageItem.tsx
index 22fd97654..2d14877e7 100644
--- a/web-app/src/containers/MessageItem.tsx
+++ b/web-app/src/containers/MessageItem.tsx
@@ -27,6 +27,8 @@ import {
IconPaperclip,
IconArrowDown,
IconAlertTriangle,
+ IconChevronLeft,
+ IconChevronRight,
} from '@tabler/icons-react'
import { EditMessageDialog } from '@/containers/dialogs/EditMessageDialog'
import { DeleteMessageDialog } from '@/containers/dialogs/DeleteMessageDialog'
@@ -64,6 +66,8 @@ export type MessageItemProps = {
onRegenerate?: (messageId: string) => void
onEdit?: (messageId: string, newText: string) => void
onDelete?: (messageId: string) => void
+ versionInfo?: { index: number; count: number }
+ onSwitchVersion?: (messageId: string, dir: -1 | 1) => void
assistant?: { avatar?: React.ReactNode; name?: string }
showAssistant?: boolean
isAnimating?: boolean
@@ -85,6 +89,8 @@ export const MessageItem = memo(
onRegenerate,
onEdit,
onDelete,
+ versionInfo,
+ onSwitchVersion,
}: MessageItemProps) => {
const selectedModel = useModelProvider((state) => state.selectedModel)
const coloredUserBubble = useInterfaceSettings((s) => s.coloredUserBubble)
@@ -567,6 +573,33 @@ export const MessageItem = memo(
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [message.parts, isStreaming, isReasoningAtBottom, grounding])
+ const versionNav =
+ versionInfo && versionInfo.count > 1 && onSwitchVersion ? (
+ <div className="flex items-center gap-0.5 text-muted-foreground">
+ <button
+ type="button"
+ className="hover:text-foreground disabled:opacity-40"
+ disabled={versionInfo.index <= 1}
+ onClick={() => onSwitchVersion(message.id, -1)}
+ title="Previous version"
+ >
+ <IconChevronLeft size={14} />
+ </button>
+ <span className="tabular-nums">
+ {versionInfo.index}/{versionInfo.count}
+ </span>
+ <button
+ type="button"
+ className="hover:text-foreground disabled:opacity-40"
+ disabled={versionInfo.index >= versionInfo.count}
+ onClick={() => onSwitchVersion(message.id, 1)}
+ title="Next version"
+ >
+ <IconChevronRight size={14} />
+ </button>
+ </div>
+ ) : null
+
return (
<div
className={cn(
@@ -619,6 +652,7 @@ export const MessageItem = memo(
<span className="text-muted-foreground">
{formatDate(createdAt)}
</span>
+ {versionNav}
<CopyButton text={getFullTextContent()} />
{onEdit && status !== CHAT_STATUS.STREAMING &&
@@ -651,6 +685,7 @@ export const MessageItem = memo(
(isStreaming || hideActions) && 'hidden'
)}
>
+ {versionNav}
<CopyButton text={getFullTextContent()} />
{onEdit && !isStreaming && (
@@ -716,7 +751,9 @@ export const MessageItem = memo(
prevProps.isLastMessage === nextProps.isLastMessage &&
prevProps.status === nextProps.status &&
prevProps.showAssistant === nextProps.showAssistant &&
- prevProps.hideActions === nextProps.hideActions
+ prevProps.hideActions === nextProps.hideActions &&
+ prevProps.versionInfo?.index === nextProps.versionInfo?.index &&
+ prevProps.versionInfo?.count === nextProps.versionInfo?.count
)
}
)
diff --git a/web-app/src/lib/__tests__/message-branching.test.ts b/web-app/src/lib/__tests__/message-branching.test.ts
new file mode 100644
index 000000000..5c6b2c645
--- /dev/null
+++ b/web-app/src/lib/__tests__/message-branching.test.ts
@@ -0,0 +1,112 @@
+import { describe, it, expect } from 'vitest'
+import { ContentType, MessageStatus, type ThreadMessage } from '@janhq/core'
+import {
+ hasBranching,
+ getParentId,
+ getSiblings,
+ getVersionInfo,
+ pickActiveChild,
+ computeActivePath,
+ backfillParentIds,
+ makeSibling,
+ withActiveChild,
+} from '../message-branching'
+
+let clock = 1000
+function msg(
+ id: string,
+ role: 'user' | 'assistant',
+ text: string,
+ metadata?: Record<string, unknown>
+): ThreadMessage {
+ const t = ++clock
+ return {
+ id,
+ object: 'thread.message',
+ thread_id: 'thr',
+ role: role as ThreadMessage['role'],
+ content: [{ type: ContentType.Text, text: { value: text, annotations: [] } }],
+ status: MessageStatus.Ready,
+ created_at: t,
+ completed_at: t,
+ metadata,
+ }
+}
+
+const ids = (ms: ThreadMessage[]) => ms.map((m) => m.id)
+
+describe('message-branching', () => {
+ it('treats legacy un-branched threads as linear', () => {
+ const m = [msg('a', 'user', 'hi'), msg('b', 'assistant', 'yo')]
+ expect(hasBranching(m)).toBe(false)
+ expect(ids(computeActivePath(m))).toEqual(['a', 'b'])
+ expect(getVersionInfo(m, m[0])).toEqual({ index: 1, count: 1 })
+ })
+
+ it('backfills parent ids along a linear path, then is idempotent', () => {
+ const m = [msg('a', 'user', 'hi'), msg('b', 'assistant', 'yo')]
+ const filled = backfillParentIds(m)
+ expect(filled).toHaveLength(2)
+ expect(getParentId(filled[0])).toBeNull()
+ expect(getParentId(filled[1])).toBe('a')
+ expect(backfillParentIds(filled)).toEqual([])
+ })
+
+ it('makeSibling shares the parent and clears active/error state', () => {
+ const u = msg('a', 'user', 'orig', { parentId: null })
+ const sib = makeSibling(u, { id: 'a2', createdAt: 5000, text: 'edited' })
+ expect(getParentId(sib)).toBeNull()
+ expect(sib.id).toBe('a2')
+ expect(sib.content[0].text?.value).toBe('edited')
+ expect((sib.metadata as Record<string, unknown>).activeChildId).toBeUndefined()
+ })
+
+ it('newest sibling is active by default; activeChildId overrides', () => {
+ // root user a -> assistant b1 (v1) and b2 (v2, newer)
+ const a = msg('a', 'user', 'q', { parentId: null })
+ const b1 = msg('b1', 'assistant', 'first', { parentId: 'a' })
+ const b2 = msg('b2', 'assistant', 'second', { parentId: 'a' })
+ let m = [a, b1, b2]
+ expect(pickActiveChild(m, a)?.id).toBe('b2')
+ expect(ids(computeActivePath(m))).toEqual(['a', 'b2'])
+
+ // pin a's active child back to b1
+ m = [withActiveChild(a, 'b1'), b1, b2]
+ expect(pickActiveChild(m, m[0])?.id).toBe('b1')
+ expect(ids(computeActivePath(m))).toEqual(['a', 'b1'])
+ })
+
+ it('reconstructs a full downstream branch, not just the forked node', () => {
+ // a -> b1 -> c1 (branch 1); a -> b2 -> c2 (branch 2, newer)
+ const a = msg('a', 'user', 'q', { parentId: null })
+ const b1 = msg('b1', 'assistant', 'a1', { parentId: 'a' })
+ const c1 = msg('c1', 'user', 'follow1', { parentId: 'b1' })
+ const b2 = msg('b2', 'assistant', 'a2', { parentId: 'a' })
+ const c2 = msg('c2', 'user', 'follow2', { parentId: 'b2' })
+ const m = [a, b1, c1, b2, c2]
+ expect(ids(computeActivePath(m))).toEqual(['a', 'b2', 'c2'])
+ expect(ids(computeActivePath([withActiveChild(a, 'b1'), b1, c1, b2, c2]))).toEqual([
+ 'a',
+ 'b1',
+ 'c1',
+ ])
+ })
+
+ it('reports version index/count among siblings sorted by time', () => {
+ const a = msg('a', 'user', 'q', { parentId: null })
+ const b1 = msg('b1', 'assistant', 'a1', { parentId: 'a' })
+ const b2 = msg('b2', 'assistant', 'a2', { parentId: 'a' })
+ const m = [a, b1, b2]
+ expect(getSiblings(m, b1).map((x) => x.id)).toEqual(['b1', 'b2'])
+ expect(getVersionInfo(m, b1)).toEqual({ index: 1, count: 2 })
+ expect(getVersionInfo(m, b2)).toEqual({ index: 2, count: 2 })
+ })
+
+ it('selects the active root among sibling roots', () => {
+ const a1 = msg('a1', 'user', 'q1', { parentId: null })
+ const a2 = msg('a2', 'user', 'q2', { parentId: null })
+ const m = [a1, a2]
+ expect(ids(computeActivePath(m))).toEqual(['a2'])
+ expect(ids(computeActivePath(m, 'a1'))).toEqual(['a1'])
+ })
+})
diff --git a/web-app/src/lib/message-branching.ts b/web-app/src/lib/message-branching.ts
new file mode 100644
index 000000000..b9d7e0c9e
--- /dev/null
+++ b/web-app/src/lib/message-branching.ts
@@ -0,0 +1,166 @@
+import { ThreadMessage, ContentType, MessageStatus } from '@janhq/core'
+
+type ThreadContent = NonNullable<ThreadMessage['content']>[number]
+
+/**
+ * Message versioning model: a parent-pointer tree stored in `metadata`.
+ *
+ * - `metadata.parentId` links a message to its predecessor. Messages sharing a
+ * `parentId` (or both rootless) are sibling versions.
+ * - `metadata.activeChildId` selects which child branch is shown; absent ⇒ the
+ * newest sibling (by `created_at`) wins.
+ *
+ * The visible/sent conversation is the path from the active root down the active
+ * child at each node. Legacy threads carry no branching metadata and are treated
+ * as a single linear path until the first fork backfills parent links.
+ */
+
+const meta = (m: ThreadMessage) =>
+ (m.metadata ?? {}) as Record<string, unknown>
+
+// Raw link: `undefined` ⇒ legacy/unlinked, `null` ⇒ explicit root, string ⇒ parent.
+const rawParent = (m: ThreadMessage): string | null | undefined => {
+ const p = meta(m).parentId
+ if (p === null) return null
+ return typeof p === 'string' ? p : undefined
+}
+
+export const getParentId = (m: ThreadMessage): string | null => {
+ const p = rawParent(m)
+ return typeof p === 'string' ? p : null
+}
+
+export const getActiveChildId = (m: ThreadMessage): string | undefined => {
+ const c = meta(m).activeChildId
+ return typeof c === 'string' ? c : undefined
+}
+
+/** True once any message carries branching metadata. */
+export const hasBranching = (messages: ThreadMessage[]): boolean =>
+ messages.some(
+ (m) => meta(m).parentId !== undefined || meta(m).activeChildId !== undefined
+ )
+
+const byCreatedAt = (a: ThreadMessage, b: ThreadMessage) =>
+ (a.created_at ?? 0) - (b.created_at ?? 0)
+
+/** Sibling versions of `m` (same parent, or fellow roots), oldest → newest. */
+export const getSiblings = (
+ messages: ThreadMessage[],
+ m: ThreadMessage
+): ThreadMessage[] => {
+ const pid = rawParent(m)
+ // Legacy/unlinked messages have no version siblings.
+ if (pid === undefined) return [m]
+ return messages.filter((x) => rawParent(x) === pid).sort(byCreatedAt)
+}
+
+/** 1-based position of `m` among its versions and the total count. */
+export const getVersionInfo = (
+ messages: ThreadMessage[],
+ m: ThreadMessage
+): { index: number; count: number } => {
+ const siblings = getSiblings(messages, m)
+ const idx = siblings.findIndex((x) => x.id === m.id)
+ return { index: idx === -1 ? 1 : idx + 1, count: siblings.length }
+}
+
+const childrenOf = (
+ messages: ThreadMessage[],
+ parentId: string | null
+): ThreadMessage[] =>
+ messages.filter((x) => rawParent(x) === parentId).sort(byCreatedAt)
+
+/** The active child of `parent`: its `activeChildId` if still valid, else newest. */
+export const pickActiveChild = (
+ messages: ThreadMessage[],
+ parent: ThreadMessage
+): ThreadMessage | undefined => {
+ const children = childrenOf(messages, parent.id)
+ if (children.length === 0) return undefined
+ const activeId = getActiveChildId(parent)
+ const chosen = activeId && children.find((c) => c.id === activeId)
+ return chosen || children[children.length - 1]
+}
+
+/**
+ * The visible linear conversation. Legacy (un-branched) threads are returned
+ * unchanged; otherwise walk from the active root following the active child.
+ */
+export const computeActivePath = (
+ messages: ThreadMessage[],
+ activeRootId?: string
+): ThreadMessage[] => {
+ if (!hasBranching(messages)) return messages
+
+ const roots = childrenOf(messages, null)
+ if (roots.length === 0) return messages
+
+ const root =
+ (activeRootId && roots.find((r) => r.id === activeRootId)) ||
+ roots[roots.length - 1]
+
+ const path: ThreadMessage[] = []
+ let cur: ThreadMessage | undefined = root
+ const seen = new Set<string>()
+ while (cur && !seen.has(cur.id)) {
+ seen.add(cur.id)
+ path.push(cur)
+ cur = pickActiveChild(messages, cur)
+ }
+ return path
+}
+
+/** Return a copy of `m` with `parentId` set in metadata. */
+export const withParentId = (
+ m: ThreadMessage,
+ parentId: string | null
+): ThreadMessage => ({
+ ...m,
+ metadata: { ...(m.metadata ?? {}), parentId },
+})
+
+/** Return a copy of `m` with `activeChildId` set in metadata. */
+export const withActiveChild = (
+ m: ThreadMessage,
+ childId: string
+): ThreadMessage => ({
+ ...m,
+ metadata: { ...(m.metadata ?? {}), activeChildId: childId },
+})
+
+/**
+ * Assign `parentId` along a linear path so the tree is well-formed before the
+ * first fork. Returns only the messages that need a write (empty if already
+ * branched). `path` must be in conversation order.
+ */
+export const backfillParentIds = (path: ThreadMessage[]): ThreadMessage[] => {
+ if (path.some((m) => meta(m).parentId !== undefined)) return []
+ return path.map((m, i) => withParentId(m, i === 0 ? null : path[i - 1].id))
+}
+
+/**
+ * Build a new sibling version of `source`: fresh id/timestamp, same parent,
+ * no children, optional text override. Used for edit-user / edit-assistant forks.
+ */
+export const makeSibling = (
+ source: ThreadMessage,
+ opts: { id: string; createdAt: number; text?: string }
+): ThreadMessage => {
+ const content: ThreadContent[] =
+ opts.text !== undefined
+ ? [{ type: ContentType.Text, text: { value: opts.text, annotations: [] } }]
+ : source.content.map((c) => ({ ...c }))
+ const sourceMeta = { ...(source.metadata ?? {}) } as Record<string, unknown>
+ delete sourceMeta.activeChildId
+ delete sourceMeta.error
+ return {
+ ...source,
+ id: opts.id,
+ content,
+ status: MessageStatus.Ready,
+ created_at: opts.createdAt,
+ completed_at: opts.createdAt,
+ metadata: { ...sourceMeta, parentId: getParentId(source) },
+ }
+}
diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsx
index 19cea9b5a..785c4f2b9 100644
--- a/web-app/src/routes/threads/$threadId.tsx
+++ b/web-app/src/routes/threads/$threadId.tsx
@@ -33,11 +33,20 @@ import {
threadMessageIsEmpty,
} from '@/lib/messages'
import { newUserThreadContent } from '@/lib/completion'
+import {
+ computeActivePath,
+ backfillParentIds,
+ makeSibling,
+ withActiveChild,
+ getParentId,
+ getSiblings,
+ getVersionInfo,
+ hasBranching,
+} from '@/lib/message-branching'
import {
ThreadMessage,
MessageStatus,
ChatCompletionRole,
- ContentType,
} from '@janhq/core'
import {
createImageAttachment,
@@ -204,6 +213,9 @@ function ThreadDetail() {
message: UIMessage
text: string
} | null>(null)
+ // 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)
// Use the AI SDK chat hook
const {
@@ -274,6 +286,9 @@ function ThreadDetail() {
unknown
>
+ const parentForAssistant = pendingAssistantParentId.current
+ pendingAssistantParentId.current = null
+
const assistantMessage: ThreadMessage = {
type: 'text',
role: ChatCompletionRole.Assistant,
@@ -284,7 +299,10 @@ function ThreadDetail() {
status: MessageStatus.Ready,
created_at: Date.now(),
completed_at: Date.now(),
- metadata: messageMetadata,
+ metadata:
+ parentForAssistant != null
+ ? { ...messageMetadata, parentId: parentForAssistant }
+ : messageMetadata,
}
const existingMessages = useMessages.getState().getMessages(threadId)
@@ -293,9 +311,29 @@ function ThreadDetail() {
)
if (existingMessage) {
- updateMessage(assistantMessage)
+ // Preserve the existing branch link on re-runs of onFinish.
+ const existingParent = getParentId(existingMessage)
+ updateMessage(
+ existingParent != null
+ ? {
+ ...assistantMessage,
+ metadata: {
+ ...assistantMessage.metadata,
+ parentId: existingParent,
+ },
+ }
+ : assistantMessage
+ )
} else {
addMessage(assistantMessage)
+ // New generation becomes the active branch under its parent so
+ // version navigation lands on the latest reply by default.
+ if (parentForAssistant) {
+ const parent = existingMessages.find(
+ (m) => m.id === parentForAssistant
+ )
+ if (parent) updateMessage(withActiveChild(parent, assistantMessage.id))
+ }
}
for (const m of existingMessages) {
@@ -624,7 +662,14 @@ function ThreadDetail() {
}
useMessageErrors.getState().hydrate(hydrated)
- const uiMessages = convertThreadMessagesToUIMessages(messagesToSet)
+ const activeRootId = (
+ useThreads.getState().threads[threadId]?.metadata as
+ | Record<string, unknown>
+ | undefined
+ )?.activeRootId as string | undefined
+ const uiMessages = convertThreadMessagesToUIMessages(
+ computeActivePath(messagesToSet, activeRootId)
+ )
setChatMessages(uiMessages)
currentThread.current = threadId
}
@@ -809,12 +854,30 @@ function ThreadDetail() {
}
// Persist the final message to backend
- const userMessage = newUserThreadContent(
+ const baseUserMessage = newUserThreadContent(
threadId,
text,
processedAttachments,
messageId
)
+ // Once a thread has branches, link new turns into the active path so the
+ // assistant reply attaches to this message. Legacy threads stay linear.
+ const branchedMessages = useMessages.getState().getMessages(threadId)
+ let userMessage = baseUserMessage
+ if (hasBranching(branchedMessages)) {
+ const activeRootId = (
+ useThreads.getState().threads[threadId]?.metadata as
+ | Record<string, unknown>
+ | undefined
+ )?.activeRootId as string | undefined
+ const path = computeActivePath(branchedMessages, activeRootId)
+ const parentId = path.length ? path[path.length - 1].id : null
+ userMessage = {
+ ...baseUserMessage,
+ metadata: { ...(baseUserMessage.metadata ?? {}), parentId },
+ }
+ pendingAssistantParentId.current = messageId
+ }
addMessage(userMessage)
// Build parts for AI SDK (only images are sent as file parts)
@@ -949,128 +1012,164 @@ function ThreadDetail() {
]
)
- // Handle regenerate from any message (user or assistant)
- // - For user messages: keeps the user message, deletes all after, regenerates assistant response
- // - For assistant messages: finds the closest preceding user message, deletes from there
- const handleRegenerate = useCallback((messageId?: string) => {
- const hadBannerError =
- useAppState.getState().oomError != null ||
- useAppState.getState().backendError != null ||
- contextLimitError != null
- if (useAppState.getState().oomError) {
- useAppState.getState().setOomError(undefined)
- }
- if (useAppState.getState().backendError) {
- useAppState.getState().setBackendError(undefined)
- }
- if (contextLimitError) setContextLimitError(null)
- if (hadBannerError) stripBannerMetadata()
- // Cancel any in-flight title summarization before regenerating
- titleAbortRef.current?.abort()
- titleAbortRef.current = null
+ // Versioning helpers --------------------------------------------------------
- const currentLocalMessages = useMessages.getState().getMessages(threadId)
+ // Assign parentId along the current linear path the first time a thread forks,
+ // so siblings and subtrees are well-defined. Idempotent. Returns the store.
+ const ensureBranched = useCallback(() => {
+ const msgs = useMessages.getState().getMessages(threadId)
+ if (hasBranching(msgs)) return msgs
+ const filled = backfillParentIds(msgs)
+ filled.forEach((m) => updateMessage(m))
+ return useMessages.getState().getMessages(threadId)
+ }, [threadId, updateMessage])
- // If regenerating from a specific message, delete all messages after it
- if (messageId) {
- // Find the message in the current chat messages
- const messageIndex = currentLocalMessages.findIndex(
- (m) => m.id === messageId
- )
+ // Make `node` the active branch under its parent (or active root).
+ const setActiveBranch = useCallback(
+ (node: ThreadMessage) => {
+ const parentId = getParentId(node)
+ if (!parentId) {
+ const t = useThreads.getState().threads[threadId]
+ useThreads.getState().updateThread(threadId, {
+ metadata: {
+ ...((t?.metadata as Record<string, unknown> | undefined) ?? {}),
+ activeRootId: node.id,
+ },
+ })
+ return
+ }
+ const parent = useMessages
+ .getState()
+ .getMessages(threadId)
+ .find((m) => m.id === parentId)
+ if (parent) updateMessage(withActiveChild(parent, node.id))
+ },
+ [threadId, updateMessage]
+ )
- if (messageIndex !== -1) {
- const selectedMessage = currentLocalMessages[messageIndex]
-
- // If it's an assistant message, find the closest preceding user message
- let deleteFromIndex = messageIndex
- if (selectedMessage.role === 'assistant') {
- // Look backwards to find the closest user message
- for (let i = messageIndex - 1; i >= 0; i--) {
- if (currentLocalMessages[i].role === 'user') {
- deleteFromIndex = i
- break
- }
- }
- }
+ // Rebuild the rendered conversation from the active path in the store.
+ const syncActivePath = useCallback(() => {
+ const msgs = useMessages.getState().getMessages(threadId)
+ const activeRootId = (
+ useThreads.getState().threads[threadId]?.metadata as
+ | Record<string, unknown>
+ | undefined
+ )?.activeRootId as string | undefined
+ setChatMessages(
+ convertThreadMessagesToUIMessages(computeActivePath(msgs, activeRootId))
+ )
+ }, [threadId, setChatMessages])
+
+ // Switch the visible version of a message (the `< n/m >` control).
+ const handleSwitchVersion = useCallback(
+ (messageId: string, dir: -1 | 1) => {
+ const msgs = useMessages.getState().getMessages(threadId)
+ const target = msgs.find((m) => m.id === messageId)
+ if (!target) return
+ const siblings = getSiblings(msgs, target)
+ const idx = siblings.findIndex((m) => m.id === messageId)
+ const next = siblings[idx + dir]
+ if (!next) return
+ titleAbortRef.current?.abort()
+ titleAbortRef.current = null
+ setActiveBranch(next)
+ syncActivePath()
+ },
+ [threadId, setActiveBranch, syncActivePath]
+ )
- // Get all messages after the delete point
- const messagesToDelete = currentLocalMessages.slice(deleteFromIndex + 1)
+ // Resolve the user message that an assistant reply hangs off of.
+ const resolveAssistantParent = useCallback(
+ (messageId: string | undefined): string | null => {
+ const msgs = useMessages.getState().getMessages(threadId)
+ const activeRootId = (
+ useThreads.getState().threads[threadId]?.metadata as
+ | Record<string, unknown>
+ | undefined
+ )?.activeRootId as string | undefined
+ const path = computeActivePath(msgs, activeRootId)
+ const idx =
+ messageId == null
+ ? path.length - 1
+ : path.findIndex((m) => m.id === messageId)
+ if (idx === -1) return null
+ const sel = path[idx]
+ if (sel.role === 'user') return sel.id
+ for (let i = idx; i >= 0; i--) {
+ if (path[i].role === 'user') return path[i].id
+ }
+ return null
+ },
+ [threadId]
+ )
- // Delete from backend storage
- if (messagesToDelete.length > 0) {
- messagesToDelete.forEach((msg) => {
- deleteMessage(threadId, msg.id)
- })
- }
+ // Regenerate keeps the previous reply as a prior version (no deletion); the
+ // new reply arrives in onFinish as a sibling and becomes the active branch.
+ const handleRegenerate = useCallback(
+ (messageId?: string) => {
+ const hadBannerError =
+ useAppState.getState().oomError != null ||
+ useAppState.getState().backendError != null ||
+ contextLimitError != null
+ if (useAppState.getState().oomError) {
+ useAppState.getState().setOomError(undefined)
}
- }
+ if (useAppState.getState().backendError) {
+ useAppState.getState().setBackendError(undefined)
+ }
+ if (contextLimitError) setContextLimitError(null)
+ if (hadBannerError) stripBannerMetadata()
+ titleAbortRef.current?.abort()
+ titleAbortRef.current = null
- // Call the AI SDK regenerate function - it will handle truncating the UI messages
- // and generating a new response from the selected message
- regenerate(messageId ? { messageId } : undefined)
- }, [threadId, deleteMessage, regenerate, stripBannerMetadata, contextLimitError])
+ ensureBranched()
+ pendingAssistantParentId.current = resolveAssistantParent(messageId)
- // Handle edit message - updates the message and regenerates from it
+ regenerate(messageId ? { messageId } : undefined)
+ },
+ [
+ regenerate,
+ stripBannerMetadata,
+ contextLimitError,
+ ensureBranched,
+ resolveAssistantParent,
+ ]
+ )
+
+ // 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(
(messageId: string, newText: string) => {
- const currentLocalMessages = useMessages.getState().getMessages(threadId)
- const messageIndex = currentLocalMessages.findIndex(
- (m) => m.id === messageId
- )
+ const msgs = ensureBranched()
+ const target = msgs.find((m) => m.id === messageId)
+ if (!target) return
- if (messageIndex === -1) return
-
- const originalMessage = currentLocalMessages[messageIndex]
-
- const priorMeta = (originalMessage.metadata || {}) as Record<
- string,
- unknown
- >
- const cleanedMeta = { ...priorMeta }
- delete cleanedMeta.error
- const updatedMessage = {
- ...originalMessage,
- content: [
- {
- type: ContentType.Text,
- text: { value: newText, annotations: [] },
- },
- ],
- metadata: cleanedMeta,
- }
- updateMessage(updatedMessage)
useMessageErrors.getState().clearError(messageId)
+ titleAbortRef.current?.abort()
+ titleAbortRef.current = null
- // Update chat messages for UI
- const updatedChatMessages = chatMessages.map((msg) => {
- if (msg.id === messageId) {
- return {
- ...msg,
- parts: [{ type: 'text' as const, text: newText }],
- }
- }
- return msg
- })
- setChatMessages(updatedChatMessages)
-
- // Only regenerate if the edited message is from the user
- if (updatedMessage.role === 'assistant') return
-
- // Delete all messages after this one and regenerate
- const messagesToDelete = currentLocalMessages.slice(messageIndex + 1)
- messagesToDelete.forEach((msg) => {
- deleteMessage(threadId, msg.id)
+ const newId = generateId()
+ const sibling = makeSibling(target, {
+ id: newId,
+ createdAt: Date.now(),
+ text: newText,
})
-
- // Regenerate from the edited message
- regenerate({ messageId })
+ addMessage(sibling)
+ setActiveBranch(sibling)
+
+ if (target.role === 'user') {
+ pendingAssistantParentId.current = newId
+ syncActivePath()
+ regenerate({ messageId: newId })
+ } else {
+ syncActivePath()
+ }
},
[
- threadId,
- updateMessage,
- deleteMessage,
- chatMessages,
- setChatMessages,
+ ensureBranched,
+ addMessage,
+ setActiveBranch,
+ syncActivePath,
regenerate,
]
)
@@ -1330,6 +1429,17 @@ function ThreadDetail() {
[searchThreadModel, thread]
)
+ // Per-message version counts for the `< n/m >` navigation control.
+ const versionInfoById = useMemo(() => {
+ const map: Record<string, { index: number; count: number }> = {}
+ if (!localThreadMessages || !hasBranching(localThreadMessages)) return map
+ for (const m of localThreadMessages) {
+ const info = getVersionInfo(localThreadMessages, m)
+ if (info.count > 1) map[m.id] = info
+ }
+ return map
+ }, [localThreadMessages])
+
return (
<div className="flex flex-col h-[calc(100dvh-(env(safe-area-inset-bottom)+env(safe-area-inset-top)))]">
<HeaderPage>
@@ -1361,6 +1471,8 @@ function ThreadDetail() {
onRegenerate={handleRegenerate}
onEdit={handleEditMessage}
onDelete={handleDeleteMessage}
+ versionInfo={versionInfoById[message.id]}
+ onSwitchVersion={handleSwitchVersion}
isAnimating={!pendingContinueMessage}
hideActions={!!pendingContinueMessage}
/>
diff --git a/web-app/src/routes/threads/__tests__/$threadId.test.tsx b/web-app/src/routes/threads/__tests__/$threadId.test.tsx
index 152339b9e..212411014 100644
--- a/web-app/src/routes/threads/__tests__/$threadId.test.tsx
+++ b/web-app/src/routes/threads/__tests__/$threadId.test.tsx
@@ -197,9 +197,27 @@ vi.mock('@/containers/ChatInput', () => ({
}))
vi.mock('@/containers/MessageItem', () => ({
- MessageItem: ({ message, onRegenerate, onEdit, onDelete }: any) => (
+ MessageItem: ({
+ message,
+ onRegenerate,
+ onEdit,
+ onDelete,
+ versionInfo,
+ onSwitchVersion,
+ }: any) => (
<div data-testid={`message-${message.id}`} data-role={message.role}>
<span>{message.id}</span>
+ {versionInfo && (
+ <span data-testid={`version-${message.id}`}>
+ {versionInfo.index}/{versionInfo.count}
+ </span>
+ )}
+ <button
+ data-testid={`prev-${message.id}`}
+ onClick={() => onSwitchVersion?.(message.id, -1)}
+ >
+ prev
+ </button>
<button
data-testid={`regen-${message.id}`}
onClick={() => onRegenerate(message.id)}
@@ -480,28 +498,34 @@ describe('ThreadDetail route', () => {
expect(h.mockRegenerate).toHaveBeenCalledWith({ messageId: 'u1' })
})
- it('regenerate from an assistant message deletes msgs after preceding user', () => {
+ it('regenerate from an assistant message keeps the prior version (no delete)', () => {
h.chatState.messages = [
{ id: 'u1', role: 'user', parts: [{ type: 'text', text: 'hi' }] },
{ id: 'a1', role: 'assistant', parts: [{ type: 'text', text: 'hello' }] },
]
renderComponent()
screen.getByTestId('regen-a1').click()
- expect(h.messagesState.deleteMessage).toHaveBeenCalledWith('thread-1', 'a1')
+ // Versioning: the old reply is preserved, parent links are backfilled.
+ expect(h.messagesState.deleteMessage).not.toHaveBeenCalled()
+ expect(h.messagesState.updateMessage).toHaveBeenCalled()
expect(h.mockRegenerate).toHaveBeenCalledWith({ messageId: 'a1' })
})
- it('edit on a user message updates and regenerates', () => {
+ it('edit on a user message forks a new version and regenerates', () => {
h.chatState.messages = [
{ id: 'u1', role: 'user', parts: [{ type: 'text', text: 'hi' }] },
{ id: 'a1', role: 'assistant', parts: [{ type: 'text', text: 'hello' }] },
]
renderComponent()
screen.getByTestId('edit-u1').click()
+ // A new sibling version is added; the original branch is not deleted.
+ expect(h.messagesState.addMessage).toHaveBeenCalled()
expect(h.messagesState.updateMessage).toHaveBeenCalled()
expect(h.mockSetChatMessages).toHaveBeenCalled()
- expect(h.messagesState.deleteMessage).toHaveBeenCalledWith('thread-1', 'a1')
- expect(h.mockRegenerate).toHaveBeenCalledWith({ messageId: 'u1' })
+ expect(h.messagesState.deleteMessage).not.toHaveBeenCalled()
+ expect(h.mockRegenerate).toHaveBeenCalledWith(
+ expect.objectContaining({ messageId: expect.any(String) })
+ )
})
it('edit on an assistant message updates without regenerating', () => {
@@ -515,6 +539,46 @@ describe('ThreadDetail route', () => {
expect(h.mockRegenerate).not.toHaveBeenCalled()
})
+ it('shows a version chip and switches branches without regenerating', () => {
+ 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)
+ h.chatState.messages = [
+ { id: 'u1', role: 'user', parts: [{ type: 'text', text: 'hi' }] },
+ { id: 'a1b', role: 'assistant', parts: [{ type: 'text', text: 'v2' }] },
+ ]
+ renderComponent()
+ // The active (newest) reply shows as version 2 of 2.
+ expect(screen.getByTestId('version-a1b').textContent).toBe('2/2')
+ screen.getByTestId('prev-a1b').click()
+ // Switching pins the parent's active child and re-renders, no regeneration.
+ expect(h.messagesState.updateMessage).toHaveBeenCalled()
+ expect(h.mockSetChatMessages).toHaveBeenCalled()
+ expect(h.mockRegenerate).not.toHaveBeenCalled()
+ })
+
it('delete removes message from store and chat list', () => {
h.chatState.messages = [
{ id: 'u1', role: 'user', parts: [{ type: 'text', text: 'hi' }] },