Skip to content

The agent that grows with you

fix(desktop): branch long sessions without renderer transcript load

Benjamin Brumbaugh44812b5e90a0
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 56bfdeb3565..b4030694098 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
@@ -261,14 +261,14 @@ describe('desktop branch creation idempotency', () => {
expect(requestGateway).toHaveBeenCalledWith(
'session.create',
expect.objectContaining({
- messages: [
- { content: 'question', role: 'user' },
- { content: 'answer', role: 'assistant' }
- ],
+ copy_parent_history: true,
+ omit_messages: true,
parent_session_id: 'parent',
source: 'desktop'
})
)
+ expect(requestGateway.mock.calls[0]?.[1]).not.toHaveProperty('messages')
+ expect(getAllSessionMessages).not.toHaveBeenCalled()
expect($sessions.get().filter(session => session.id === 'stored-branch')).toHaveLength(1)
})
@@ -2100,10 +2100,7 @@ describe('branchStoredSession desktop source tagging', () => {
expect(ambientRequest).not.toHaveBeenCalledWith('session.create', expect.anything())
})
- // The parent transcript read must land on the owning backend too: reading it
- // from the ambient socket returns nothing for a foreign-owned parent, which
- // aborts the branch as "nothing to branch" before any create is attempted.
- it('reads a connection-tagged parent transcript from its owning connection', async () => {
+ it('does not materialize a connection-tagged parent transcript in the renderer', async () => {
const ambientRequest = vi.fn(async () => ({}) as never)
vi.mocked(requestGatewayForAgent).mockImplementation((async (
@@ -2121,25 +2118,26 @@ describe('branchStoredSession desktop source tagging', () => {
setSessions([
storedSession({ connection_id: 'pandora', id: 'stored-parent', message_count: 1, profile: 'default' })
])
- vi.mocked(getAllSessionMessages).mockResolvedValue({
- messages: [{ content: 'branch me', role: 'user', timestamp: 1 }],
- session_id: 'stored-parent'
- } as never)
-
let branchStoredSession: ((storedSessionId: string) => Promise<boolean>) | null = null
render(<BranchHarness onReady={branch => (branchStoredSession = branch)} requestGateway={ambientRequest} />)
await waitFor(() => expect(branchStoredSession).not.toBeNull())
await expect(branchStoredSession!('stored-parent')).resolves.toBe(true)
- expect(getAllSessionMessages).toHaveBeenCalledWith('stored-parent', {
- connectionId: 'pandora',
- profile: 'default'
- })
+ expect(requestGatewayForAgent).toHaveBeenCalledWith(
+ 'pandora',
+ 'default',
+ 'session.create',
+ expect.objectContaining({
+ copy_parent_history: true,
+ omit_messages: true,
+ parent_session_id: 'stored-parent',
+ source: 'desktop'
+ })
+ )
+ expect(getAllSessionMessages).not.toHaveBeenCalled()
})
-
- // The create landing on the right backend is only half the job: the sidebar
- // row must be TAGGED with that owner too. An untagged optimistic row inherits
+ // The row must be TAGGED with that owner too. An untagged optimistic row inherits
// the ambient profile, so every later owner lookup (resume/hydrate/prompt)
// routes to the wrong backend and the chat pane spins forever on a session
// that backend never had.
@@ -2255,12 +2253,13 @@ describe('branchStoredSession desktop source tagging', () => {
expect(requestGateway).toHaveBeenCalledWith('session.branch', {
session_id: 'live-parent',
- count: 2
+ count: 2,
+ omit_messages: true
})
- expect(branchParams).toEqual({ session_id: 'live-parent', count: 2 })
+ expect(branchParams).toEqual({ session_id: 'live-parent', count: 2, omit_messages: true })
})
- it('hydrates the complete persisted display transcript before branching a compacted live chat', async () => {
+ it('branches a compacted live chat without hydrating its transcript in the renderer', async () => {
let branchParams: Record<string, unknown> | undefined
const requestGateway = vi.fn(async (method: string, params?: Record<string, unknown>) => {
@@ -2272,7 +2271,7 @@ describe('branchStoredSession desktop source tagging', () => {
stored_session_id: 'branch-stored',
title: 'Branch',
message_count: 4,
- messages: [],
+ messages_omitted: true,
info: {}
} as never
}
@@ -2286,16 +2285,6 @@ describe('branchStoredSession desktop source tagging', () => {
{ id: 'tail-user', role: 'user', parts: [{ type: 'text', text: 'second question' }] },
{ id: 'tail-assistant', role: 'assistant', parts: [{ type: 'text', text: 'second answer' }] }
])
- vi.mocked(getAllSessionMessages).mockResolvedValue({
- messages: [
- { content: 'first question', role: 'user', timestamp: 1 },
- { content: 'first answer', role: 'assistant', timestamp: 2 },
- { content: 'second question', role: 'user', timestamp: 3 },
- { content: 'second answer', role: 'assistant', timestamp: 4 }
- ],
- session_id: 'stored-parent'
- } as never)
-
let branchCurrentSession: ((messageId?: string) => Promise<boolean>) | null = null
render(
<BranchHarness
@@ -2310,8 +2299,8 @@ describe('branchStoredSession desktop source tagging', () => {
await expect(branchCurrentSession!()).resolves.toBe(true)
- expect(getAllSessionMessages).toHaveBeenCalledWith('stored-parent', undefined)
- expect(branchParams).toEqual({ session_id: 'live-parent' })
+ expect(getAllSessionMessages).not.toHaveBeenCalled()
+ expect(branchParams).toEqual({ session_id: 'live-parent', omit_messages: true })
})
it('aborts if the active runtime changes while the branch transcript is hydrating', async () => {
@@ -2345,16 +2334,17 @@ describe('branchStoredSession desktop source tagging', () => {
)
await waitFor(() => expect(branchCurrentSession).not.toBeNull())
- await expect(branchCurrentSession!()).resolves.toBe(false)
+ await expect(branchCurrentSession!('q1')).resolves.toBe(false)
expect(requestGateway).not.toHaveBeenCalledWith('session.branch', expect.anything())
})
// #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 reading the transcript / creating the branch, so the fork
- // is not created on whichever profile happens to be live.
+ // swap to it before asking the backend to copy the transcript, so the fork is
+ // not created on whichever profile happens to be live.
it('resolves and swaps to the parent profile when the branched session is not cached', async () => {
setSessions([])
+ vi.mocked(getAllSessionMessages).mockClear()
vi.mocked(getSession).mockResolvedValue(storedSession({ id: 'stored-parent', message_count: 1, profile: 'work' }))
vi.mocked(getAllSessionMessages).mockResolvedValue({
messages: [{ content: 'branch me', role: 'user', timestamp: 1 }],
@@ -2382,7 +2372,7 @@ describe('branchStoredSession desktop source tagging', () => {
await expect(branchStoredSession!('stored-parent')).resolves.toBe(true)
expect(ensureGatewayProfile).toHaveBeenCalledWith('work')
- expect(getAllSessionMessages).toHaveBeenCalledWith('stored-parent', 'work')
+ expect(getAllSessionMessages).not.toHaveBeenCalled()
// The create itself must carry the owning profile: in app-global remote
// mode the soft gateway swap alone is not enough — an omitted profile
// lands the branch on the launch (default) profile's state.db.
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 18e1ba8e1ca..e820c44df21 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
@@ -2364,6 +2364,7 @@ export function useSessionActions({
sourceSessionId
? requestBranchGateway<SessionCreateResponse>('session.branch', {
session_id: sourceSessionId,
+ omit_messages: true,
...(branchCount !== undefined ? { count: branchCount } : {})
})
: requestBranchGateway<SessionCreateResponse>('session.create', {
@@ -2371,7 +2372,9 @@ export function useSessionActions({
source: 'desktop',
...(cwd && { cwd }),
...(profile ? { profile } : {}),
- messages: branchMessages.map(({ content, role }) => ({ content, role })),
+ ...(branchMessages.length
+ ? { messages: branchMessages.map(({ content, role }) => ({ content, role })) }
+ : { copy_parent_history: true, omit_messages: true }),
...(parentStoredId && { parent_session_id: parentStoredId })
})
).catch(err => {
@@ -2523,11 +2526,10 @@ export function useSessionActions({
const startingRouteToken = getRouteToken()
const startingCwd = $currentCwd.get().trim()
- // The live atom may be a compacted model projection. Read the durable
- // display projection before choosing the branch prefix so a whole-chat
- // branch does not inherit only the summary/tail. If the backend is
- // temporarily unavailable, retain the local snapshot and let the branch
- // RPC make its own authoritative read.
+ // Message-level branches still need the local message id to choose their
+ // prefix. Whole-chat branches send only the parent identity below; the
+ // backend reads the durable display projection without materializing it in
+ // the renderer.
let authoritativeMessages: ChatMessage[] | null = null
const profile = await resolveSessionProfile(storedSessionId)
@@ -2537,7 +2539,7 @@ export function useSessionActions({
// whichever socket is active.
const ownerRoute = storedSessionId ? sessionOwnerRouteFromRow(cachedSessionRow(storedSessionId)) : undefined
- if (storedSessionId) {
+ if (messageId && storedSessionId) {
try {
const persisted = await getAllSessionMessages(storedSessionId, ownerRoute ?? profile)
const hydrated = toChatMessages(persisted.messages)
@@ -2568,9 +2570,9 @@ export function useSessionActions({
return false
}
- const branchMessages = selectBranchMessages(messages, authoritativeMessages, messageId)
+ const branchMessages = messageId ? selectBranchMessages(messages, authoritativeMessages, messageId) : []
- if (!branchMessages.length) {
+ if (messageId && !branchMessages.length) {
notify({ kind: 'warning', title: copy.nothingToBranch, message: copy.branchNoText })
return false
@@ -2623,21 +2625,10 @@ export function useSessionActions({
await ensureGatewayProfile(profile)
}
- // Read the parent transcript from the backend that OWNS it. A bare
- // profile scope resolves against the active connection, which for a
- // foreign-owned parent holds no such session: the read comes back empty
- // and the branch aborts as "nothing to branch" before any create.
- const { messages } = await getAllSessionMessages(storedSessionId, ownerRoute ?? profile)
- const branchMessages = toBranchMessages(toChatMessages(messages))
-
- if (!branchMessages.length) {
- notify({ kind: 'warning', title: copy.nothingToBranch, message: copy.branchNoText })
-
- return false
- }
-
+ // Ask the owning backend to read and copy the parent transcript. The
+ // renderer deliberately does not materialize the complete history.
return await forkBranch(
- branchMessages,
+ [],
null,
stored?.id ?? storedSessionId,
stored?.cwd?.trim(),
diff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.ts
index dbb9d799c7d..dba2785867c 100644
--- a/apps/desktop/src/types/hermes.ts
+++ b/apps/desktop/src/types/hermes.ts
@@ -507,6 +507,7 @@ export interface SessionCreateResponse {
info?: SessionRuntimeInfo
message_count?: number
messages?: SessionMessage[]
+ messages_omitted?: boolean
session_id: string
stored_session_id?: string
}
diff --git a/tests/tui_gateway/test_tui_gateway_server.py b/tests/tui_gateway/test_tui_gateway_server.py
index e35c0d83c52..0e278e4256c 100644
--- a/tests/tui_gateway/test_tui_gateway_server.py
+++ b/tests/tui_gateway/test_tui_gateway_server.py
@@ -15700,7 +15700,7 @@ def test_session_branch_writes_to_parent_profile_db(monkeypatch, tmp_path):
{
"id": "1",
"method": "session.branch",
- "params": {"session_id": "parent", "name": "forked"},
+ "params": {"session_id": "parent", "name": "forked", "omit_messages": True},
}
)
assert "result" in resp, resp
@@ -15709,6 +15709,8 @@ def test_session_branch_writes_to_parent_profile_db(monkeypatch, tmp_path):
# The branch row is self-describing: stamped with the parent's owning
# profile, not left NULL for aggregators to mis-tag as "default".
assert seen.get("profile_name") == "mlperf"
+ assert resp["result"].get("messages_omitted") is True
+ assert "messages" not in resp["result"]
assert seen.get("title") == (seen["created"], "forked")
assert len(seen["msgs"]) == 1
assert seen.get("launch") is None
@@ -15816,6 +15818,63 @@ def test_session_create_persists_seeded_branch_child(monkeypatch):
server._sessions.pop(runtime_sid, None)
+def test_session_create_copies_parent_history_without_returning_transcript(monkeypatch):
+ """Whole-session desktop branches read the parent in the gateway, not in the renderer."""
+
+ class _Scope:
+ def __init__(self, db):
+ self.db = db
+
+ def __enter__(self):
+ return self.db
+
+ def __exit__(self, *_args):
+ return False
+
+ class _FakeDB:
+ def get_resume_conversations(self, key):
+ assert key == "parent"
+ return [], [
+ {"role": "user", "content": "first question", "timestamp": 1},
+ {"role": "assistant", "content": "first answer", "timestamp": 2},
+ ]
+
+ class _FakeAgent:
+ model = "test-model"
+
+ seen: dict = {}
+ db = _FakeDB()
+
+ monkeypatch.setattr(server, "_profile_db", lambda _params: _Scope(db))
+ monkeypatch.setattr(
+ server,
+ "_seed_branch_row",
+ lambda _record, _key, _parent, history, *_args: seen.update(history=list(history)),
+ )
+ monkeypatch.setattr(server, "_make_agent", lambda *_args, **_kwargs: _FakeAgent())
+ monkeypatch.setattr(server, "_session_info", lambda *_args: {"model": "test-model"})
+
+ resp = server.handle_request(
+ {
+ "id": "1",
+ "method": "session.create",
+ "params": {
+ "cols": 96,
+ "copy_parent_history": True,
+ "omit_messages": True,
+ "parent_session_id": "parent",
+ "source": "desktop",
+ },
+ }
+ )
+
+ assert "result" in resp, resp
+ assert [message["content"] for message in seen["history"]] == ["first question", "first answer"]
+ assert resp["result"]["message_count"] == 2
+ assert resp["result"].get("messages_omitted") is True
+ assert "messages" not in resp["result"]
+
+
def test_session_create_branch_seed_failure_does_not_break_create(monkeypatch):
"""Best-effort persistence: a broken DB must not fail session.create."""
diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.py
index fb6419bdc84..ef397fb42e4 100644
--- a/tui_gateway/methods_session.py
+++ b/tui_gateway/methods_session.py
@@ -344,6 +344,24 @@ def _(rid, params: dict) -> dict:
history = _coerce_seed_history(params.get("messages"))
# Branch: links back so list_sessions_rich keeps it visible and the sidebar nests it.
parent_session_id = _str_param(params, "parent_session_id") or None
+ copy_parent_history = _flag(params, "copy_parent_history")
+ omit_messages = _flag(params, "omit_messages")
+ if copy_parent_history:
+ if not parent_session_id:
+ return _err(rid, 4008, "parent_session_id is required when copying parent history")
+ # Whole-session desktop branches must not serialize the parent's transcript
+ # through the renderer. Read the durable display projection here, where the
+ # owning state.db already lives, and keep the full copy server-side.
+ with _profile_db(params) as db:
+ if db is None:
+ return _db_unavailable_error(rid, code=5008)
+ try:
+ _, display_history = db.get_resume_conversations(parent_session_id)
+ except Exception as exc:
+ return _err(rid, 4008, f"nothing to branch — {exc}")
+ history = _visible_branch_history(display_history)
+ if not history:
+ return _err(rid, 4008, "nothing to branch — send a message first")
# Only an explicitly chosen existing workspace persists as cwd; the launch-dir fallback is "No workspace".
explicit_cwd = False
raw_cwd = _str_param(params, "cwd") # unguarded, as on BASE: only the path check is best-effort
@@ -401,7 +419,8 @@ def _(rid, params: dict) -> dict:
override = session_model_override or {}
messages = _history_to_messages(history, profile_home=profile_home) # hidden seed rows are not on the wire; count what is (as resume does)
return _ok(rid, {
- "session_id": sid, "stored_session_id": key, "message_count": len(messages), "messages": messages,
+ "session_id": sid, "stored_session_id": key, "message_count": len(messages),
+ **({"messages": messages} if not omit_messages else {"messages_omitted": True}),
# Reflect the override now so the client doesn't clobber its sticky pick.
"info": {"model": override.get("model") if override else _session_default_model(_sessions[sid]),
**({"provider": override["provider"]} if override.get("provider") else {}),
@@ -2071,9 +2090,13 @@ def _(rid, params: dict, session: dict) -> dict:
agent = _build_branch_agent(session, new_sid, new_key, history, source)
except Exception as e:
return _err(rid, 5000, f"agent init failed on branch: {e}")
- return _ok(rid, {"session_id": new_sid, "stored_session_id": new_key, "title": title, "parent": old_key,
- "message_count": len(history), "messages": _history_to_messages(history, profile_home=session.get("profile_home")),
- "info": _session_info(agent, _sessions.get(new_sid))})
+ response = {"session_id": new_sid, "stored_session_id": new_key, "title": title, "parent": old_key,
+ "message_count": len(history), "info": _session_info(agent, _sessions.get(new_sid))}
+ if _flag(params, "omit_messages"):
+ response["messages_omitted"] = True
+ else:
+ response["messages"] = _history_to_messages(history, profile_home=session.get("profile_home"))
+ return _ok(rid, response)
# ── interrupt / steer / redirect ─────────────────────────────────────