Skip to content

The agent that grows with you

fix(desktop): restore branching in session tiles

embwl0xeb0b136e91fe
diff --git a/apps/desktop/src/app/chat/session-tile-actions.ts b/apps/desktop/src/app/chat/session-tile-actions.ts
index 22aac1d5100..5907a52196a 100644
--- a/apps/desktop/src/app/chat/session-tile-actions.ts
+++ b/apps/desktop/src/app/chat/session-tile-actions.ts
@@ -741,8 +741,16 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, stored
[update]
)
+ const branchInNewChat = useCallback(
+ (messageId: string) =>
+ sessionTileDelegate()?.branchSessionAtMessage(storedIdRef.current, runtimeIdRef.current, messageId) ??
+ Promise.resolve(false),
+ []
+ )
+
return useMemo(
() => ({
+ branchInNewChat,
cancelRun,
dismissError,
editMessage,
@@ -754,6 +762,7 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, stored
submitText
}),
[
+ branchInNewChat,
cancelRun,
dismissError,
editMessage,
diff --git a/apps/desktop/src/app/chat/session-tile-attachments.test.tsx b/apps/desktop/src/app/chat/session-tile-attachments.test.tsx
index d8a790aafaf..4ad4f82a84f 100644
--- a/apps/desktop/src/app/chat/session-tile-attachments.test.tsx
+++ b/apps/desktop/src/app/chat/session-tile-attachments.test.tsx
@@ -85,6 +85,7 @@ function installDelegate(): void {
setSessionTileDelegate({
archiveSession: vi.fn(async () => undefined),
branchSession: vi.fn(async () => undefined),
+ branchSessionAtMessage: vi.fn(async () => true),
deleteSession: vi.fn(async () => undefined),
executeSlash: vi.fn(async () => undefined),
interruptSession: vi.fn(async () => undefined),
diff --git a/apps/desktop/src/app/chat/session-tile.tsx b/apps/desktop/src/app/chat/session-tile.tsx
index e46140d936c..8dbe9a1e3e1 100644
--- a/apps/desktop/src/app/chat/session-tile.tsx
+++ b/apps/desktop/src/app/chat/session-tile.tsx
@@ -407,6 +407,7 @@ function TileChat({
onAttachDroppedItems={composer.attachDroppedItems}
onAttachImageBlob={composer.attachImageBlob}
onAttachPastedText={composer.attachPastedText}
+ onBranchInNewChat={actions.branchInNewChat}
onCancel={actions.cancelRun}
onDeleteSelectedSession={noop}
onDismissError={actions.dismissError}
diff --git a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts
index a5cb68ff0c8..bbd6fc89dc9 100644
--- a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts
+++ b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts
@@ -46,22 +46,24 @@ const row = (over: Partial<SessionInfo>): SessionInfo =>
function renderTile(
requestGateway: ReturnType<typeof vi.fn>,
- refs?: {
+ options: {
+ branchLoadedSession?: ReturnType<typeof vi.fn>
runtimeIdByStoredSessionIdRef?: { current: Map<string, string> }
sessionStateByRuntimeIdRef?: { current: Map<string, unknown> }
updateSessionState?: ReturnType<typeof vi.fn>
- }
+ } = {}
) {
renderHook(() =>
useSessionTileDelegate({
archiveSession: vi.fn(async () => undefined),
+ branchLoadedSession: (options.branchLoadedSession ?? vi.fn(async () => false)) as never,
branchStoredSession: vi.fn(async () => undefined),
executeSlashCommand: vi.fn(async () => undefined) as never,
removeSession: vi.fn(async () => undefined),
requestGateway: requestGateway as never,
- runtimeIdByStoredSessionIdRef: (refs?.runtimeIdByStoredSessionIdRef ?? { current: new Map() }) as never,
- sessionStateByRuntimeIdRef: (refs?.sessionStateByRuntimeIdRef ?? { current: new Map() }) as never,
- updateSessionState: (refs?.updateSessionState ?? vi.fn()) as never
+ runtimeIdByStoredSessionIdRef: (options.runtimeIdByStoredSessionIdRef ?? { current: new Map() }) as never,
+ sessionStateByRuntimeIdRef: (options.sessionStateByRuntimeIdRef ?? { current: new Map() }) as never,
+ updateSessionState: (options.updateSessionState ?? vi.fn()) as never
})
)
}
@@ -575,6 +577,32 @@ describe('useSessionTileDelegate resumeTile', () => {
const runtimeId = await sessionTileDelegate()!.resumeTile('stored-c')
expect(runtimeId).toBe('runtime-fresh')
})
+
+ it('branches a tile from the live message array that rendered the clicked action', async () => {
+ const messages = [
+ { id: 'q1', role: 'user' as const, parts: [{ type: 'text' as const, text: 'question one' }] },
+ { id: 'a1', role: 'assistant' as const, parts: [{ type: 'text' as const, text: 'answer one' }] },
+ { id: 'q2', role: 'user' as const, parts: [{ type: 'text' as const, text: 'question two' }] }
+ ]
+
+ const state = { ...createClientSessionState('stored-x', messages), cwd: '/repo' }
+ const branchLoadedSession = vi.fn(async () => true)
+
+ renderTile(vi.fn(), {
+ branchLoadedSession,
+ sessionStateByRuntimeIdRef: { current: new Map([['runtime-x', state]]) }
+ })
+
+ await expect(sessionTileDelegate()!.branchSessionAtMessage('stored-x', 'runtime-x', 'a1')).resolves.toBe(true)
+ expect(branchLoadedSession).toHaveBeenCalledWith({
+ busy: false,
+ cwd: '/repo',
+ messageId: 'a1',
+ messages,
+ runtimeId: 'runtime-x',
+ storedSessionId: 'stored-x'
+ })
+ })
})
describe('useSessionTileDelegate retireBusyClaim', () => {
diff --git a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts
index b6d8ae894e2..f8b00411399 100644
--- a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts
+++ b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts
@@ -35,6 +35,7 @@ import type { SessionResumeResult } from '@/types/hermes'
import type { usePromptActions } from '../../session/hooks/use-prompt-actions'
import { singleFlightSessionResume } from '../../session/hooks/use-prompt-actions/single-flight-resume'
import { markSessionRecentlyInterrupted, withSessionNotFoundResume } from '../../session/hooks/use-prompt-actions/utils'
+import type { useSessionActions } from '../../session/hooks/use-session-actions'
import {
chatMessageArraysEquivalent,
preserveLocalPendingTurnMessages,
@@ -119,6 +120,7 @@ function mergeTileTranscript(
interface SessionTileDelegateParams {
archiveSession: (storedSessionId: string) => Promise<unknown>
+ branchLoadedSession: ReturnType<typeof useSessionActions>['branchLoadedSession']
branchStoredSession: (storedSessionId: string) => Promise<unknown>
executeSlashCommand: ReturnType<typeof usePromptActions>['executeSlashCommand']
removeSession: (storedSessionId: string) => Promise<unknown>
@@ -137,6 +139,7 @@ interface SessionTileDelegateParams {
*/
export function useSessionTileDelegate({
archiveSession,
+ branchLoadedSession,
branchStoredSession,
executeSlashCommand,
removeSession,
@@ -205,6 +208,18 @@ export function useSessionTileDelegate({
branchSession: async storedSessionId => {
await branchStoredSession(storedSessionId)
},
+ branchSessionAtMessage: async (storedSessionId, runtimeId, messageId) => {
+ const state = sessionStateByRuntimeIdRef.current.get(runtimeId)
+
+ return await branchLoadedSession({
+ busy: state?.busy ?? false,
+ cwd: state?.cwd,
+ messageId,
+ messages: state?.messages ?? [],
+ runtimeId,
+ storedSessionId
+ })
+ },
deleteSession: async storedSessionId => {
await removeSession(storedSessionId)
},
@@ -536,6 +551,7 @@ export function useSessionTileDelegate({
})
}, [
archiveSession,
+ branchLoadedSession,
branchStoredSession,
executeSlashCommand,
removeSession,
diff --git a/apps/desktop/src/app/contrib/wiring.tsx b/apps/desktop/src/app/contrib/wiring.tsx
index 80faffc7744..169dee315b1 100644
--- a/apps/desktop/src/app/contrib/wiring.tsx
+++ b/apps/desktop/src/app/contrib/wiring.tsx
@@ -562,6 +562,7 @@ export function ContribWiring({ children }: { children: ReactNode }) {
const {
archiveSession,
branchCurrentSession,
+ branchLoadedSession,
branchStoredSession,
createBackendSessionForSend,
openNewSessionTile,
@@ -793,6 +794,7 @@ export function ContribWiring({ children }: { children: ReactNode }) {
// the tile TAB menu needs, without touching the primary view).
useSessionTileDelegate({
archiveSession,
+ branchLoadedSession,
branchStoredSession,
executeSlashCommand,
removeSession,
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx b/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx
index ec2cfbffa9a..b6a233737f2 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx
@@ -2601,6 +2601,7 @@ function BranchHarness({
activeSessionId = null,
navigate = vi.fn(),
onCurrentReady,
+ onLoadedReady,
onReady,
onStateUpdate,
onRefs,
@@ -2610,6 +2611,7 @@ function BranchHarness({
activeSessionId?: string | null
navigate?: ReturnType<typeof vi.fn>
onCurrentReady?: (branchCurrentSession: (messageId?: string) => Promise<boolean>) => void
+ onLoadedReady?: (branchLoadedSession: ReturnType<typeof useSessionActions>['branchLoadedSession']) => void
onReady: (branchStoredSession: (storedSessionId: string, sessionProfile?: string | null) => Promise<boolean>) => void
onStateUpdate?: (sessionId: string, state: ClientSessionState) => void
onRefs?: (refs: {
@@ -2653,7 +2655,15 @@ function BranchHarness({
useEffect(() => {
onReady(actions.branchStoredSession)
onCurrentReady?.(actions.branchCurrentSession)
- }, [actions.branchCurrentSession, actions.branchStoredSession, onCurrentReady, onReady])
+ onLoadedReady?.(actions.branchLoadedSession)
+ }, [
+ actions.branchCurrentSession,
+ actions.branchLoadedSession,
+ actions.branchStoredSession,
+ onCurrentReady,
+ onLoadedReady,
+ onReady
+ ])
return null
}
@@ -3093,6 +3103,50 @@ describe('branchStoredSession desktop source tagging', () => {
expect(requestGateway).not.toHaveBeenCalledWith('session.branch', expect.anything())
})
+ it('branches a loaded tile transcript through the clicked message', async () => {
+ const requestGateway = vi.fn(async (method: string) => {
+ if (method === 'session.branch') {
+ return { session_id: 'branch-runtime', stored_session_id: 'branch-stored' } as never
+ }
+
+ return {} as never
+ })
+
+ const messages = [
+ { id: 'q1', role: 'user' as const, parts: [{ type: 'text' as const, text: 'question one' }] },
+ { id: 'a1', role: 'assistant' as const, parts: [{ type: 'text' as const, text: 'answer one' }] },
+ { id: 'q2', role: 'user' as const, parts: [{ type: 'text' as const, text: 'question two' }] },
+ { id: 'a2', role: 'assistant' as const, parts: [{ type: 'text' as const, text: 'answer two' }] }
+ ]
+
+ setSessions([storedSession({ id: 'tile-stored', message_count: messages.length })])
+ let branchLoadedSession: ReturnType<typeof useSessionActions>['branchLoadedSession'] | null = null
+ render(
+ <BranchHarness
+ onLoadedReady={branch => (branchLoadedSession = branch)}
+ onReady={() => undefined}
+ requestGateway={requestGateway}
+ />
+ )
+ await waitFor(() => expect(branchLoadedSession).not.toBeNull())
+
+ await expect(
+ branchLoadedSession!({
+ busy: false,
+ cwd: '/repo',
+ messageId: 'a1',
+ messages,
+ runtimeId: 'tile-runtime',
+ storedSessionId: 'tile-stored'
+ })
+ ).resolves.toBe(true)
+
+ expect(requestGateway).toHaveBeenCalledWith('session.branch', {
+ session_id: 'tile-runtime',
+ count: 2
+ })
+ })
+
// #67603: right-clicking a session outside the paginated sidebar window is a
// cache miss. Resolve its owning profile (cache → active → cross-profile) and
// swap to it before asking the backend to copy the transcript, so the fork is
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
index c4f3c03d9c6..5218d06db6b 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
@@ -230,6 +230,16 @@ interface SessionActionsOptions {
) => ClientSessionState
}
+export interface BranchLoadedSessionOptions {
+ busy: boolean
+ contextDrift?: () => null | string
+ cwd?: string
+ messageId?: string
+ messages: ChatMessage[]
+ runtimeId: null | string
+ storedSessionId: null | string
+}
+
const branchMessagesFingerprint = (messages: BranchMessage[]): string =>
JSON.stringify(messages.map(({ content, role }) => [role, content]))
@@ -2905,16 +2915,26 @@ export function useSessionActions({
]
)
- // Branch the open chat — optionally from a specific message — off its live transcript.
- const branchCurrentSession = useCallback(
- async (messageId?: string): Promise<boolean> => {
- if (!activeSessionIdRef.current) {
+ // Branch a session whose live transcript is already loaded in this renderer.
+ // Both the main chat and session tiles use this path so a clicked message id
+ // is resolved against the exact message array that rendered the action bar.
+ const branchLoadedSession = useCallback(
+ async ({
+ busy,
+ contextDrift,
+ cwd,
+ messageId,
+ messages,
+ runtimeId,
+ storedSessionId
+ }: BranchLoadedSessionOptions) => {
+ if (!runtimeId) {
notify({ kind: 'warning', title: copy.nothingToBranch, message: copy.branchNeedsChat })
return false
}
- if (busyRef.current) {
+ if (busy) {
notify({ kind: 'warning', title: copy.sessionBusy, message: copy.branchStopCurrent })
return false
@@ -2952,18 +2972,10 @@ export function useSessionActions({
}
}
- const drift = sessionContextDrift({
- startRouteToken: startingRouteToken,
- nowRouteToken: getRouteToken(),
- startSelectedStoredId: storedSessionId,
- nowSelectedStoredId: selectedStoredSessionIdRef.current
- })
-
- const runtimeChanged = activeSessionIdRef.current !== startingActiveSessionId
- const selectionChanged = selectedStoredSessionIdRef.current !== storedSessionId
+ const drift = contextDrift?.()
- if (drift || runtimeChanged || selectionChanged) {
- console.warn('[branch-drift-abort]', drift ?? 'runtime-or-selection-changed', {
+ if (drift) {
+ console.warn('[branch-drift-abort]', drift, {
phase: 'transcript-hydration'
})
@@ -2980,20 +2992,54 @@ export function useSessionActions({
clearNotifications()
- // The open chat's owning profile, NOT the picker's / launch profile —
- // /profile only retargets new chats, so a branch of an existing thread
- // must stay on that thread's backend (cache hit for an open session).
return forkBranch(
branchMessages,
- startingActiveSessionId,
+ runtimeId,
storedSessionId,
- startingCwd,
+ cwd?.trim(),
profile,
messageId ? branchMessages.length : undefined,
ownerRoute
)
},
- [activeSessionIdRef, busyRef, copy, forkBranch, getRouteToken, selectedStoredSessionIdRef]
+ [copy, forkBranch]
+ )
+
+ // Branch the open chat — optionally from a specific message — off its live transcript.
+ const branchCurrentSession = useCallback(
+ (messageId?: string): Promise<boolean> => {
+ const runtimeId = activeSessionIdRef.current
+ const storedSessionId = selectedStoredSessionIdRef.current
+ const routeToken = getRouteToken()
+
+ return branchLoadedSession({
+ busy: busyRef.current,
+ contextDrift: () => {
+ const drift = sessionContextDrift({
+ startRouteToken: routeToken,
+ nowRouteToken: getRouteToken(),
+ startSelectedStoredId: storedSessionId,
+ nowSelectedStoredId: selectedStoredSessionIdRef.current
+ })
+
+ if (drift) {
+ return drift
+ }
+
+ if (activeSessionIdRef.current !== runtimeId) {
+ return 'runtime-changed'
+ }
+
+ return selectedStoredSessionIdRef.current === storedSessionId ? null : 'selection-changed'
+ },
+ cwd: $currentCwd.get(),
+ messageId,
+ messages: $messages.get(),
+ runtimeId,
+ storedSessionId
+ })
+ },
+ [activeSessionIdRef, branchLoadedSession, busyRef, getRouteToken, selectedStoredSessionIdRef]
)
// Branch any listed session, not just the open one. Reads the target's stored
@@ -3360,6 +3406,7 @@ export function useSessionActions({
return {
archiveSession,
branchCurrentSession,
+ branchLoadedSession,
branchStoredSession,
closeSettings,
createBackendSessionForSend,
diff --git a/apps/desktop/src/store/session-states.ts b/apps/desktop/src/store/session-states.ts
index 2f11712a310..6ec953cdcdc 100644
--- a/apps/desktop/src/store/session-states.ts
+++ b/apps/desktop/src/store/session-states.ts
@@ -2270,6 +2270,8 @@ export interface SessionTileDelegate {
archiveSession(storedSessionId: string): Promise<void>
/** Branch a stored session into a new chat (the sidebar's branch). */
branchSession(storedSessionId: string): Promise<void>
+ /** Branch a tile's live transcript through the clicked message. */
+ branchSessionAtMessage(storedSessionId: string, runtimeId: string, messageId: string): Promise<boolean>
/** Delete a stored session (the sidebar's delete, incl. tile cleanup). */
deleteSession(storedSessionId: string): Promise<void>
/** Run a slash command against a tile's session (app-level effects — e.g.