Skip to content

The agent that grows with you

fix(tui_gateway,desktop): every branch create accepts the idempotency key, and a branch_stored hit keeps its messages off the wire

Brooklyn Nicholsonc579be967f27
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 3de42b04395..a2cbb18216a 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
@@ -3302,9 +3302,11 @@ describe('branchStoredSession desktop source tagging', () => {
expect(requestGateway).toHaveBeenCalledWith('session.branch', {
session_id: 'live-parent',
- count: 2
+ count: 2,
+ // Stable per-attempt key (#65410): present but opaque to this test.
+ idempotency_key: expect.any(String)
})
- expect(branchParams).toEqual({ session_id: 'live-parent', count: 2 })
+ expect(branchParams).toMatchObject({ session_id: 'live-parent', count: 2, idempotency_key: expect.any(String) })
})
it('branches a compacted live chat without hydrating its transcript in the renderer', async () => {
@@ -3348,7 +3350,7 @@ describe('branchStoredSession desktop source tagging', () => {
await expect(branchCurrentSession!()).resolves.toBe(true)
expect(getAllSessionMessages).not.toHaveBeenCalled()
- expect(branchParams).toEqual({ session_id: 'live-parent' })
+ expect(branchParams).toMatchObject({ session_id: 'live-parent', idempotency_key: expect.any(String) })
})
it('aborts if the active runtime changes while the branch transcript is hydrating', async () => {
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 5fbfa99060e..72f75fe1cc6 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
@@ -2781,6 +2781,9 @@ export function useSessionActions({
if (!createFlight) {
const branchParams = {
session_id: sourceSessionId,
+ // Stable per-attempt key: a lost-response retry of session.branch /
+ // session.branch_whole returns the SAME child (#65410).
+ idempotency_key: key,
...(branchCount !== undefined ? { count: branchCount } : {})
}
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index ab4cef7d658..ad6b88f504a 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -3000,6 +3000,7 @@ export interface SessionBranchStoredParams {
cols?: number | null
source?: string | null
cwd?: string | null
+ idempotency_key?: string | null
}
export interface SessionBranchStoredResult {
session_id: string
@@ -3263,6 +3264,7 @@ export interface SessionBranchParams {
profile?: string | null
name?: string | null
count?: number | null
+ idempotency_key?: string | null
}
export interface SessionBranchResult {
session_id: string
@@ -3277,6 +3279,7 @@ export interface SessionBranchWholeParams {
session_id: string
profile?: string | null
name?: string | null
+ idempotency_key?: string | null
}
export interface SessionBranchWholeResult {
session_id: string
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index 86be3c7f5b9..b0f98535e93 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -28649,6 +28649,18 @@
],
"default": null,
"title": "Count"
+ },
+ "idempotency_key": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Idempotency Key"
}
},
"required": [
@@ -28758,6 +28770,18 @@
],
"default": null,
"title": "Cwd"
+ },
+ "idempotency_key": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Idempotency Key"
}
},
"required": [
@@ -28829,6 +28853,18 @@
],
"default": null,
"title": "Name"
+ },
+ "idempotency_key": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Idempotency Key"
}
},
"required": [
diff --git a/tests/tui_gateway/test_protocol.py b/tests/tui_gateway/test_protocol.py
index c28d5110a71..b7325407fcd 100644
--- a/tests/tui_gateway/test_protocol.py
+++ b/tests/tui_gateway/test_protocol.py
@@ -2077,3 +2077,50 @@ def test_session_create_idempotency_key_expires_with_session(server, monkeypatch
assert "error" not in second
assert second["result"]["session_id"] != first_sid
assert len(server._sessions) == 1
+
+
+def test_session_branch_stored_accepts_idempotency_key(server, monkeypatch):
+ """The desktop's whole-session branch (session.branch_stored) rides the same
+ create plumbing and sends idempotency_key on EVERY branch (#65410): the
+ contract must accept it, the create must succeed (the lineage-sidebar e2e
+ failed with a 4000 because SessionBranchStoredParams forbade the key), and a
+ retried branch_stored with the SAME key must return the SAME child instead
+ of a duplicate."""
+ _stub_session_create_dependencies(server, monkeypatch)
+
+ 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},
+ ]
+
+ monkeypatch.setattr(server, "_profile_db", lambda _params: _Scope(_FakeDB()))
+
+ params = {
+ "cols": 96,
+ "parent_session_id": "parent",
+ "source": "desktop",
+ "idempotency_key": "branch-stored-retry-abc",
+ }
+ first = server.handle_request({"id": "b1", "method": "session.branch_stored", "params": dict(params)})
+ assert "error" not in first, first.get("error")
+ first_sid = first["result"]["session_id"]
+ assert len(server._sessions) == 1
+
+ # A lost-response retry: same key, same params, same child.
+ second = server.handle_request({"id": "b2", "method": "session.branch_stored", "params": dict(params)})
+ assert "error" not in second, second.get("error")
+ assert second["result"]["session_id"] == first_sid
+ assert len(server._sessions) == 1
diff --git a/tests/tui_gateway/test_tui_gateway_server.py b/tests/tui_gateway/test_tui_gateway_server.py
index e321fbfbe63..b289d5da6fb 100644
--- a/tests/tui_gateway/test_tui_gateway_server.py
+++ b/tests/tui_gateway/test_tui_gateway_server.py
@@ -23360,3 +23360,93 @@ def test_named_profile_without_backend_stays_local_under_ssh_launch(monkeypatch,
monkeypatch.setattr(server, "_profile_home", lambda name: home if name == "plain" else None)
assert server._completion_cwd({"profile": "plain", "cwd": launch, "cwd_explicit": False}) == launch
+
+
+def test_session_branch_idempotency_key_dedupes_retry(monkeypatch, tmp_path):
+ """A retried session.branch with the SAME idempotency_key returns the SAME
+ child instead of a duplicate (#65410): a branch whose first response was
+ lost must not leave two children behind. The hit answers the SAME result
+ shape (title, parent, message_count) without re-copying the transcript."""
+
+ class ProfileDB:
+ def __init__(self, db_path=None):
+ pass
+
+ def get_session_title(self, _key):
+ return "parent"
+
+ def get_next_title_in_lineage(self, current):
+ return f"{current} (branch)"
+
+ def create_session(self, new_key, **kwargs):
+ pass
+
+ def append_messages_batch(self, session_id, messages, **kwargs):
+ return list(range(1, len(messages) + 1))
+
+ def set_session_title(self, key, title):
+ return True
+
+ def get_session(self, key):
+ return {"id": key, "cwd": str(tmp_path)}
+
+ def update_session_cwd(self, *a, **k):
+ return None
+
+ def close(self):
+ return None
+
+ class FakeAgent:
+ def __init__(self):
+ self.model = "test-model"
+ self.session_id = None
+
+ parent = {
+ "session_key": "parent-key",
+ "history": [{"role": "user", "content": "hi"}],
+ "history_lock": threading.Lock(),
+ "running": False,
+ "cols": 80,
+ "profile_home": None,
+ "source": "tui",
+ "agent": FakeAgent(),
+ "created_at": 1.0,
+ "last_active": 1.0,
+ "cwd": str(tmp_path),
+ }
+ server._sessions["parent"] = parent
+ monkeypatch.setattr(server, "_get_db", lambda: ProfileDB())
+ monkeypatch.setattr("hermes_state_registry.acquire", ProfileDB)
+ monkeypatch.setattr(server, "_claim_active_session_slot", lambda *a, **k: (None, None))
+ monkeypatch.setattr(server, "_make_agent", lambda *a, **k: FakeAgent())
+ monkeypatch.setattr(server, "_set_session_context", lambda *a, **k: {})
+ monkeypatch.setattr(server, "_clear_session_context", lambda *a, **k: None)
+ monkeypatch.setattr(server, "_resolve_model", lambda: "test-model")
+ monkeypatch.setattr(server, "_session_cwd", lambda s: str(tmp_path))
+ monkeypatch.setattr(server, "_register_session_cwd", lambda *a, **k: None)
+ monkeypatch.setattr(server, "_attach_worker", lambda *a, **k: None)
+ server._idempotency_keys.clear()
+ try:
+ params = {"session_id": "parent", "name": "forked", "idempotency_key": "branch-live-retry-1"}
+ first = server.handle_request({"id": "b1", "method": "session.branch", "params": dict(params)})
+ assert "result" in first, first
+ first_sid = first["result"]["session_id"]
+ first_key = first["result"]["stored_session_id"]
+ assert first["result"]["title"] == "forked"
+ assert first["result"]["parent"] == "parent-key"
+
+ # Client retries after a lost response: same key, same params.
+ second = server.handle_request({"id": "b2", "method": "session.branch", "params": dict(params)})
+ assert "result" in second, second
+ assert second["result"]["session_id"] == first_sid
+ assert second["result"]["stored_session_id"] == first_key
+ assert second["result"]["title"] == "forked"
+ assert second["result"]["parent"] == "parent-key"
+
+ # Only ONE child runtime exists besides the parent.
+ children = [sid for sid, s in server._sessions.items() if sid != "parent"]
+ assert len(children) == 1
+ finally:
+ for k in list(server._sessions):
+ server._sessions.pop(k, None)
+ server._idempotency_keys.clear()
diff --git a/tui_gateway/contracts/sessions.py b/tui_gateway/contracts/sessions.py
index 6ffeca80867..074aeb7716b 100644
--- a/tui_gateway/contracts/sessions.py
+++ b/tui_gateway/contracts/sessions.py
@@ -155,6 +155,10 @@ class SessionBranchStoredParams(ProfileParams):
cols: int | None = None
source: str | None = None
cwd: str | None = None
+ # #65410: the desktop's whole-session branch rides the same create plumbing and
+ # now always sends the caller's stable key (its retry path reuses it). Optional
+ # so an older client that omits it keeps the historic behaviour.
+ idempotency_key: str | None = None
class SessionBranchStoredResult(Result):
@@ -392,6 +396,9 @@ method("session.close", params=SessionCloseParams, result=SessionCloseResult,
class SessionBranchParams(SessionParams):
name: str | None = None
count: int | None = None # keep only the first N rows of the source history
+ # #65410: the desktop's mid-chat branch retry reuses the SAME key so a
+ # lost-response retry returns the SAME child instead of a duplicate.
+ idempotency_key: str | None = None
class SessionBranchResult(Result):
@@ -410,6 +417,8 @@ method("session.branch", params=SessionBranchParams, result=SessionBranchResult,
class SessionBranchWholeParams(SessionParams):
name: str | None = None
+ # #65410: same retry contract as session.branch.
+ idempotency_key: str | None = None
class SessionBranchWholeResult(Result):
diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.py
index 4e7086c079d..6373e6a2f4b 100644
--- a/tui_gateway/methods_session.py
+++ b/tui_gateway/methods_session.py
@@ -378,10 +378,16 @@ def _create_session(rid, params: dict, *, copy_parent_history: bool = False) ->
_idempotency_keys[idem_key] = (existing_sid, now_for_gc)
history = session["history"]
override = session.get("model_override") or {}
+ # Same result shape as the fresh-create path below: branch_stored
+ # (copy_parent_history) answers messages_omitted and NEVER puts the
+ # copied transcript on the wire — its result contract forbids
+ # ``messages``, and serializing the parent's history through the
+ # renderer is exactly what the method exists to avoid.
return _ok(rid, {
"session_id": existing_sid, "stored_session_id": session["session_key"],
"message_count": len(history),
- "messages": _history_to_messages(history, profile_home=session.get("profile_home")),
+ **({"messages_omitted": True} if copy_parent_history
+ else {"messages": _history_to_messages(history, profile_home=session.get("profile_home"))}),
"info": {"model": override.get("model") if override else _session_default_model(session),
**({"provider": override["provider"]} if override.get("provider") else {}),
"tools": {}, "skills": {}, "cwd": session["cwd"], "branch": git_probe.branch(session["cwd"]),
@@ -2225,6 +2231,10 @@ def _build_branch_agent(session: dict, new_sid: str, new_key: str, history: list
if new_sid in _sessions:
_sessions[new_sid]["active_session_lease"] = None # claimed lazily on the first turn
_sessions[new_sid]["auth_user_id"] = parent_user_id
+ # The parent's STORED key: the idempotent-hit reply for a retried
+ # session.branch answers the same ``parent`` as the fresh path, and
+ # later readers (lineage, retry) get the linkage from the runtime.
+ _sessions[new_sid]["parent_session_id"] = session.get("session_key")
return agent
finally:
if branch_owns_db and branch_db is not None:
@@ -2258,6 +2268,21 @@ def _branch_source_history(db, session: dict, old_key: str) -> list:
def _branch_live(rid, params: dict, session: dict, *, omit_messages: bool = False) -> dict:
+ # Idempotency (#65410, same registry as session.create): a client retrying a
+ # branch whose first response was lost gets the SAME child, not a duplicate.
+ idem_key = _str_param(params, "idempotency_key") or None
+ if idem_key is not None:
+ with _sessions_lock:
+ now_gc = time.time()
+ existing_sid, ts = _idempotency_keys.get(idem_key, (None, 0.0))
+ if existing_sid is not None and existing_sid in _sessions:
+ if now_gc - ts <= _IDEMPOTENCY_KEY_TTL:
+ # Refresh the TTL so back-to-back retries don't age out mid-flight.
+ _idempotency_keys[idem_key] = (existing_sid, now_gc)
+ return _ok(rid, _branch_idempotent_hit(existing_sid, _sessions[existing_sid], omit_messages))
+ _idempotency_keys.pop(idem_key, None)
+ # Stale key (child closed) or first attempt: fall through to a fresh
+ # branch, which re-registers the key below.
# Write into the parent's profile-scoped state.db; the launch handle would orphan rows.
with _session_db(session) as db:
if db is None:
@@ -2283,6 +2308,13 @@ def _branch_live(rid, params: dict, session: dict, *, omit_messages: bool = Fals
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}")
+ if idem_key is not None:
+ with _sessions_lock:
+ _idempotency_keys[idem_key] = (new_sid, time.time())
+ # The fresh reply's title, so an idempotent hit answers the SAME one
+ # without a DB round-trip.
+ if new_sid in _sessions:
+ _sessions[new_sid]["branch_title"] = title
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 omit_messages:
@@ -2292,6 +2324,30 @@ def _branch_live(rid, params: dict, session: dict, *, omit_messages: bool = Fals
return _ok(rid, response)
+def _branch_idempotent_hit(existing_sid: str, session: dict, omit_messages: bool) -> dict:
+ """The SAME result shape a fresh ``_branch_live`` returns for the existing child."""
+ history = session.get("history") or []
+ key = session.get("session_key") or ""
+ response = {"session_id": existing_sid, "stored_session_id": key,
+ "title": session.get("branch_title") or _branch_title_for(session),
+ "parent": session.get("parent_session_id"), "message_count": len(history),
+ "info": _fallback_session_info(session)}
+ if omit_messages:
+ response["messages_omitted"] = True
+ else:
+ response["messages"] = _history_to_messages(history, profile_home=session.get("profile_home"))
+ return response
+
+
+def _branch_title_for(session: dict) -> str:
+ """The child's persisted title from its stored row, best-effort."""
+ with contextlib.suppress(Exception):
+ with _session_db(session) as db:
+ if db is not None:
+ return db.get_session_title(session.get("session_key") or "") or ""
+ return ""
+
+
@_session_method("session.branch", live=True)
def _(rid, params: dict, session: dict) -> dict:
return _branch_live(rid, params, session)