Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

Support branching off

Blue Mouse0b34e6be2b19
diff --git a/backend/apps/cloud/src/ai/ai-chat.service.ts b/backend/apps/cloud/src/ai/ai-chat.service.ts
index 0c87942c1..683a0c08f 100644
--- a/backend/apps/cloud/src/ai/ai-chat.service.ts
+++ b/backend/apps/cloud/src/ai/ai-chat.service.ts
@@ -163,16 +163,32 @@ export class AiChatService {
userId: string | null
messages: ChatMessage[]
name?: string
+ parentChatId?: string | null
}): Promise<AiChat> {
const chat = this.aiChatRepository.create({
project: { id: data.projectId },
user: data.userId ? { id: data.userId } : null,
messages: data.messages,
name: data.name || this.generateChatName(data.messages),
+ parentChatId: data.parentChatId ?? null,
})
return this.aiChatRepository.save(chat)
}
+ async findParentSummary(
+ parentChatId: string,
+ projectId: string,
+ ): Promise<{ id: string; name: string | null } | null> {
+ const parent = await this.aiChatRepository
+ .createQueryBuilder('chat')
+ .select(['chat.id', 'chat.name'])
+ .where('chat.id = :parentChatId', { parentChatId })
+ .andWhere('chat.projectId = :projectId', { projectId })
+ .getOne()
+ if (!parent) return null
+ return { id: parent.id, name: parent.name }
+ }
+
async update(
id: string,
data: { messages?: ChatMessage[]; name?: string },
diff --git a/backend/apps/cloud/src/ai/ai.controller.ts b/backend/apps/cloud/src/ai/ai.controller.ts
index b4e05a4b4..01165e327 100644
--- a/backend/apps/cloud/src/ai/ai.controller.ts
+++ b/backend/apps/cloud/src/ai/ai.controller.ts
@@ -563,12 +563,18 @@ export class AiController {
// Check if the current user is the owner of this chat
const isOwner = uid && chat.user?.id === uid
+ const parentChat = chat.parentChatId
+ ? await this.aiChatService.findParentSummary(chat.parentChatId, pid)
+ : null
+
return {
id: chat.id,
name: chat.name,
messages: chat.messages,
pinned: chat.pinned,
tags: chat.tags ?? [],
+ parentChatId: chat.parentChatId,
+ parentChat,
created: chat.created,
updated: chat.updated,
isOwner,
@@ -604,11 +610,23 @@ export class AiController {
: m,
)
+ let parentChatId: string | null = null
+ if (createChatDto.parentChatId) {
+ const parent = await this.aiChatService.findParentSummary(
+ createChatDto.parentChatId,
+ pid,
+ )
+ if (parent) {
+ parentChatId = parent.id
+ }
+ }
+
const chat = await this.aiChatService.create({
projectId: pid,
userId: uid,
messages: sanitisedCreateMessages,
name: createChatDto.name,
+ parentChatId,
})
await trackCustom(
@@ -644,6 +662,7 @@ export class AiController {
id: chat.id,
name: chat.name,
messages: chat.messages,
+ parentChatId: chat.parentChatId,
created: chat.created,
updated: chat.updated,
}
@@ -818,6 +837,7 @@ export class AiController {
userId: uid,
messages: sanitisedUpdateMessages || existingChat.messages,
name: updateChatDto.name,
+ parentChatId: existingChat.id,
})
this.logger.log(
diff --git a/backend/apps/cloud/src/ai/dto/chat.dto.ts b/backend/apps/cloud/src/ai/dto/chat.dto.ts
index c7ef48239..295de2351 100644
--- a/backend/apps/cloud/src/ai/dto/chat.dto.ts
+++ b/backend/apps/cloud/src/ai/dto/chat.dto.ts
@@ -137,6 +137,16 @@ export class CreateChatDto {
@IsString()
@MaxLength(MAX_CHAT_NAME_LENGTH)
name?: string
+
+ @ApiProperty({
+ required: false,
+ description:
+ 'ID of the chat this conversation was branched from. Must belong to the same project.',
+ })
+ @IsOptional()
+ @IsString()
+ @MaxLength(36)
+ parentChatId?: string
}
export class UpdateChatDto {
diff --git a/backend/apps/cloud/src/ai/entity/ai-chat.entity.ts b/backend/apps/cloud/src/ai/entity/ai-chat.entity.ts
index 6fbd2a267..f720d160d 100644
--- a/backend/apps/cloud/src/ai/entity/ai-chat.entity.ts
+++ b/backend/apps/cloud/src/ai/entity/ai-chat.entity.ts
@@ -56,6 +56,10 @@ export class AiChat {
@JoinColumn()
user: User | null
+ @ApiProperty({ required: false, nullable: true })
+ @Column('varchar', { name: 'parent_chat_id', length: 36, nullable: true })
+ parentChatId: string | null
+
@ApiProperty()
@CreateDateColumn()
created: Date
diff --git a/backend/migrations/mysql/2026_04_21_ai_chat_parent_chat.sql b/backend/migrations/mysql/2026_04_21_ai_chat_parent_chat.sql
new file mode 100644
index 000000000..e76ddc3fe
--- /dev/null
+++ b/backend/migrations/mysql/2026_04_21_ai_chat_parent_chat.sql
@@ -0,0 +1,4 @@
+ALTER TABLE `ai_chat`
+ ADD COLUMN `parent_chat_id` varchar(36) DEFAULT NULL;
+
+CREATE INDEX `idx_ai_chat_parent_chat_id` ON `ai_chat` (`parent_chat_id`);
diff --git a/web/app/pages/Project/tabs/AskAI/AskAIView.tsx b/web/app/pages/Project/tabs/AskAI/AskAIView.tsx
index 188e12f6f..3798d2e23 100644
--- a/web/app/pages/Project/tabs/AskAI/AskAIView.tsx
+++ b/web/app/pages/Project/tabs/AskAI/AskAIView.tsx
@@ -829,10 +829,12 @@ const AssistantMessage = ({
const UserMessage = ({
content,
onEdit,
+ onBranch,
isLoading,
}: {
content: string
onEdit?: (newContent: string) => void
+ onBranch?: () => void
isLoading?: boolean
}) => {
const { t } = useTranslation('common')
@@ -951,6 +953,18 @@ const UserMessage = ({
<PencilSimpleIcon className='h-4 w-4' />
</button>
) : null}
+ {onBranch ? (
+ <button
+ type='button'
+ onClick={onBranch}
+ disabled={isLoading}
+ className='flex h-7 w-7 items-center justify-center rounded-md text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600 disabled:cursor-not-allowed disabled:opacity-40 dark:hover:bg-slate-800 dark:hover:text-gray-200'
+ title={t('project.askAi.branchOff')}
+ aria-label={t('project.askAi.branchOff')}
+ >
+ <GitBranchIcon className='h-4 w-4' />
+ </button>
+ ) : null}
</div>
</div>
)
@@ -1100,6 +1114,8 @@ interface AIChat {
tags?: string[]
isOwner?: boolean
branched?: boolean
+ parentChatId?: string | null
+ parentChat?: { id: string; name: string | null } | null
created: string
updated: string
}
@@ -1698,6 +1714,13 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
const [currentChatId, setCurrentChatId] = useState<string | null>(null)
const [chatTitle, setChatTitle] = useState<string | null>(null)
+ const [parentChat, setParentChat] = useState<{
+ id: string
+ name: string | null
+ } | null>(null)
+ const [pendingBranchIndex, setPendingBranchIndex] = useState<number | null>(
+ null,
+ )
const [recentChats, setRecentChats] = useState<AIChatSummary[]>([])
const [allChats, setAllChats] = useState<AIChatSummary[]>([])
const [allChatsTotal, setAllChatsTotal] = useState(0)
@@ -1893,6 +1916,7 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
)
setCurrentChatId(chat.id)
setChatTitle(chat.name)
+ setParentChat(chat.parentChat ?? null)
} else if (loadChatFetcher.data.error) {
console.error('Failed to load chat:', loadChatFetcher.data.error)
const newParams = new URLSearchParams(searchParams)
@@ -1960,7 +1984,7 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
)
const createChatWithMessage = useCallback(
- (firstMessages: Message[]) => {
+ (firstMessages: Message[], opts: { parentChatId?: string | null } = {}) => {
const apiMessages = firstMessages
.filter((m) => m.content.trim().length > 0)
.map(serialiseMessageForApi)
@@ -1970,6 +1994,9 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
const formData = new FormData()
formData.append('intent', 'create-ai-chat')
formData.append('messages', JSON.stringify(apiMessages))
+ if (opts.parentChatId) {
+ formData.append('parentChatId', opts.parentChatId)
+ }
createChatFetcher.submit(formData, { method: 'POST' })
},
// eslint-disable-next-line react-hooks/exhaustive-deps
@@ -1998,6 +2025,11 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
setCurrentChatId(result.id)
currentChatIdRef.current = result.id
setChatTitle(result.name)
+ if (result.parentChat) {
+ setParentChat(result.parentChat)
+ } else if (!result.parentChatId) {
+ setParentChat(null)
+ }
const newParams = new URLSearchParams(searchParams)
newParams.set('chat', result.id)
setSearchParams(newParams, { replace: true })
@@ -2082,6 +2114,7 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
setCurrentChatId(null)
currentChatIdRef.current = null
setChatTitle(null)
+ setParentChat(null)
setStreamingMessage(null)
setFeedbackMap({})
pendingMessagesToSaveRef.current = null
@@ -2510,6 +2543,59 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
[isLoading, messages, runChatTurn, updateChatMessages],
)
+ const performBranch = useCallback(
+ async (index: number) => {
+ if (isLoading) return
+ if (index < 0 || index >= messages.length) return
+ if (messages[index]?.role !== 'user') return
+
+ const truncated = messages.slice(0, index + 1)
+ const sourceChatId = currentChatIdRef.current
+
+ setMessages(truncated)
+ setCurrentChatId(null)
+ currentChatIdRef.current = null
+ setChatTitle(null)
+ setFeedbackMap({})
+ pendingMessagesToSaveRef.current = null
+ setStreamingMessage(null)
+ setError(null)
+
+ const newParams = new URLSearchParams(searchParams)
+ newParams.delete('chat')
+ setSearchParams(newParams, { replace: true })
+
+ createChatWithMessage(truncated, {
+ parentChatId: sourceChatId ?? null,
+ })
+ await runChatTurn(truncated)
+ },
+ [
+ createChatWithMessage,
+ isLoading,
+ messages,
+ runChatTurn,
+ searchParams,
+ setSearchParams,
+ ],
+ )
+
+ const handleBranch = useCallback(
+ (index: number) => {
+ if (isLoading) return
+ if (index < 0 || index >= messages.length) return
+ if (messages[index]?.role !== 'user') return
+
+ const hasMessagesAfter = index < messages.length - 1
+ if (hasMessagesAfter) {
+ setPendingBranchIndex(index)
+ return
+ }
+ void performBranch(index)
+ },
+ [isLoading, messages, performBranch],
+ )
+
const handleRegenerate = useCallback(
async (assistantIndex: number) => {
if (isLoading) return
@@ -2737,15 +2823,38 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
>
<ArrowLeftIcon className='h-4 w-4' />
</button>
- <h2
- className='truncate text-sm font-semibold text-gray-800 dark:text-gray-100'
- title={chatTitle ?? undefined}
- >
- {chatTitle ||
- (currentChatId
- ? t('project.askAi.untitledChat')
- : t('project.askAi.newChat'))}
- </h2>
+ <div className='flex min-w-0 flex-col'>
+ <h2
+ className='truncate text-sm font-semibold text-gray-800 dark:text-gray-100'
+ title={chatTitle ?? undefined}
+ >
+ {chatTitle ||
+ (currentChatId
+ ? t('project.askAi.untitledChat')
+ : t('project.askAi.newChat'))}
+ </h2>
+ {parentChat ? (
+ <button
+ type='button'
+ onClick={() => {
+ const newParams = new URLSearchParams(searchParams)
+ newParams.set('chat', parentChat.id)
+ setSearchParams(newParams)
+ loadChatById(parentChat.id)
+ }}
+ className='flex max-w-full items-center gap-1 truncate text-left text-xs text-gray-500 transition-colors hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200'
+ title={parentChat.name ?? t('project.askAi.untitledChat')}
+ >
+ <GitBranchIcon className='h-3 w-3 shrink-0' />
+ <span className='truncate'>
+ {t('project.askAi.branchedFrom', {
+ name:
+ parentChat.name ?? t('project.askAi.untitledChat'),
+ })}
+ </span>
+ </button>
+ ) : null}
+ </div>
</div>
<div className='flex shrink-0 items-center gap-2'>
<button
@@ -2941,6 +3050,7 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
onEdit={(newContent) =>
handleEditUserMessage(idx, newContent)
}
+ onBranch={() => handleBranch(idx)}
/>
)
}
@@ -3128,6 +3238,22 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
closeText={t('common.cancel')}
submitType='danger'
/>
+
+ <Modal
+ isOpened={pendingBranchIndex !== null}
+ onClose={() => setPendingBranchIndex(null)}
+ onSubmit={() => {
+ if (pendingBranchIndex !== null) {
+ const idx = pendingBranchIndex
+ setPendingBranchIndex(null)
+ void performBranch(idx)
+ }
+ }}
+ title={t('project.askAi.branchOff')}
+ message={t('project.askAi.branchOffConfirm')}
+ submitText={t('project.askAi.branchOff')}
+ closeText={t('common.cancel')}
+ />
</div>
)
}
diff --git a/web/app/routes/projects.$id.tsx b/web/app/routes/projects.$id.tsx
index 6673560dc..150da68b1 100644
--- a/web/app/routes/projects.$id.tsx
+++ b/web/app/routes/projects.$id.tsx
@@ -1197,10 +1197,14 @@ export async function action({ request, params }: ActionFunctionArgs) {
case 'create-ai-chat': {
const messages = JSON.parse(formData.get('messages')?.toString() || '[]')
const name = formData.get('name')?.toString()
+ const parentChatId = formData.get('parentChatId')?.toString()
+
+ const body: Record<string, unknown> = { messages, name }
+ if (parentChatId) body.parentChatId = parentChatId
const result = await serverFetch(request, `ai/${projectId}/chats`, {
method: 'POST',
- body: { messages, name },
+ body,
})
if (result.error) {
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index 964d40c34..d5de04d23 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -2151,6 +2151,8 @@
"messageCopied": "Copied to clipboard",
"regenerate": "Regenerate response",
"branchOff": "Branch off",
+ "branchOffConfirm": "This will create a new conversation starting from this message. The current chat will not be modified.",
+ "branchedFrom": "Branched from {{name}}",
"editMessage": "Edit message",
"saveEdit": "Save",
"cancelEdit": "Cancel",