The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: address sweeper review on #65411 — notifyError path + idempotent retry
jinglun010-cpu4d8c5922eb2c
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.tsxindex 2e522e344c3..106654b1044 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@@ -6950,7 +6950,7 @@ describe('branchStoredSession failure retry', () => {it('surfaces a retry action when session.create fails, and retry succeeds', async () => {let createCallCount = 0const requestGateway = vi.fn(async (method: string, params?: Record<string, unknown>) => {- if (method === 'session.create') {+ if (method === 'session.create' || method === 'session.branch_stored') {createCallCount += 1if (createCallCount === 1) {@@ -6964,7 +6964,7 @@ describe('branchStoredSession failure retry', () => {})setSessions([storedSession({ id: 'stored-parent', message_count: 1 })])- vi.mocked(getSessionMessages).mockResolvedValue({+ vi.mocked(getAllSessionMessages).mockResolvedValue({messages: [{ content: 'branch me', role: 'user', timestamp: 1 }],session_id: 'stored-parent'} as never)@@ -6997,4 +6997,94 @@ describe('branchStoredSession failure retry', () => {// The retry issued a second session.create and succeeded.await waitFor(() => expect(createCallCount).toBe(2))})++ // Regression for hermes-sweeper review on PR #65411: a retry after a lost+ // response must reuse the SAME idempotency key, otherwise the backend+ // spawns a duplicate child session.+ it('passes the same idempotency_key on retry as on the first attempt', async () => {+ const seenKeys: string[] = []+ let createCallCount = 0+ const requestGateway = vi.fn(async (method: string, params?: Record<string, unknown>) => {+ if (method === 'session.create' || method === 'session.branch_stored') {+ createCallCount += 1+ seenKeys.push(String(params?.idempotency_key ?? ''))++ if (createCallCount === 1) {+ throw new Error('response lost in transit')+ }++ return { session_id: 'branch-runtime', stored_session_id: 'branch-stored' } as never+ }++ return {} as never+ })++ setSessions([storedSession({ id: 'stored-parent', message_count: 1 })])+ 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={requestGateway} />)+ await waitFor(() => expect(branchStoredSession).not.toBeNull())++ // First attempt fails (response lost).+ await expect(branchStoredSession!('stored-parent')).resolves.toBe(false)+ expect(createCallCount).toBe(1)+ expect(seenKeys).toHaveLength(1)+ expect(seenKeys[0]).toMatch(/^branch-/)++ // Click retry — should reuse the same key.+ const retryAction = $notifications.get().find(n => n.kind === 'error')?.action++ expect(retryAction).toBeDefined()+ await act(async () => {+ retryAction!.onClick()+ })++ await waitFor(() => expect(createCallCount).toBe(2))+ expect(seenKeys).toHaveLength(2)+ // Both attempts carried the same idempotency key — backend can dedupe.+ expect(seenKeys[1]).toBe(seenKeys[0])+ })++ // Regression for hermes-sweeper review on PR #65411: the notification must+ // go through notifyError's readableError normalization (wrapper stripping,+ // detail extraction, long-message fallback), not raw err.message.+ it('uses readableError normalization for the failure notification', async () => {+ // Long raw message that should be replaced by the fallback via+ // summarizeErrorMessage (>180 chars → fallback).+ const longRawMessage = 'x'.repeat(200)+ const requestGateway = vi.fn(async (method: string) => {+ if (method === 'session.create' || method === 'session.branch_stored') {+ throw new Error(longRawMessage)+ }++ return {} as never+ })++ setSessions([storedSession({ id: 'stored-parent', message_count: 1 })])+ 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={requestGateway} />)+ await waitFor(() => expect(branchStoredSession).not.toBeNull())++ await expect(branchStoredSession!('stored-parent')).resolves.toBe(false)++ await waitFor(() => {+ const errorNotifications = $notifications.get().filter(n => n.kind === 'error')++ expect(errorNotifications).toHaveLength(1)+ // readableError's summarizeErrorMessage replaced the 200-char raw message+ // with the short fallback title. Pre-fix, the raw 200-char string would+ // have been passed straight through as message.+ expect(errorNotifications[0].message).not.toBe(longRawMessage)+ expect(errorNotifications[0].message.length).toBeLessThan(180)+ })+ })})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.tsindex 5a899e439d7..5fbfa99060e 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@@ -2711,6 +2711,9 @@ export function useSessionActions({// Shared fork: create a child session seeded with `branchMessages`, linked to// `parentStoredId` so it nests under its parent, then open it as its own tab// and switch to it — the parent chat stays put (mirrors openNewSessionTile).+ // `idempotencyKey` lets a caller-driven retry reuse the SAME key so the+ // backend can dedupe (without it, every call generates a fresh key and a+ // response-lost retry would spawn a duplicate child).const forkBranch = useCallback(async (branchMessages: BranchMessage[],@@ -2719,10 +2722,16 @@ export function useSessionActions({cwd?: string,profile?: null | string,branchCount?: number,- ownerRoute?: SessionOwnerRoute+ ownerRoute?: SessionOwnerRoute,+ idempotencyKey?: string): Promise<boolean> => {creatingSessionRef.current = true+ // Stable per-attempt key so a backend retry after a lost response returns+ // the SAME child session instead of spawning a duplicate. Generated here+ // for first-time calls; supplied by the retry action on subsequent tries.+ const key = idempotencyKey ?? `branch-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`+try {// A branch belongs to its parent's OWNING backend. Two facets, and both// matter once more than one connection is configured:@@ -2780,7 +2789,10 @@ export function useSessionActions({source: 'desktop',...(cwd && { cwd }),...(profile ? { profile } : {}),- ...(parentStoredId && { parent_session_id: parentStoredId })+ ...(parentStoredId && { parent_session_id: parentStoredId }),+ // Stable per-attempt key: a backend retry after a lost response+ // returns the SAME child instead of spawning a duplicate (#65410).+ idempotency_key: key}createFlight = (@@ -2932,12 +2944,14 @@ export function useSessionActions({releaseCreatingSessionGuard()// Backend restart / WS drop mid-RPC leaves the branch uncreated with no// recovery path. Surface a persistent error with a retry action so the- // user can re-attempt without re-doing the whole branch flow.+ // user can re-attempt without re-doing the whole branch flow. The retry+ // passes the SAME idempotency key so the backend can dedupe if the+ // first create actually committed but its response was lost.notifyError(err, copy.branchFailed, {action: {label: t.common.retry,onClick: () => {- void forkBranch(branchMessages, sourceSessionId, parentStoredId, cwd, profile, branchCount, ownerRoute)+ void forkBranch(branchMessages, sourceSessionId, parentStoredId, cwd, profile, branchCount, ownerRoute, key)}}})diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex 3601ce7a235..ab4cef7d658 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -2948,6 +2948,7 @@ export interface SessionCreateParams {hidden?: booleanroom_plumbing?: booleanfollow_profile_config?: boolean+ idempotency_key?: string | null}/** One create-time transcript row (``session_history._coerce_seed_history``); ``text`` is the legacy alias of ``content``; only ``display_kind: "hidden"`` is accepted from the wire. Clients forward stored rows verbatim (``_row_id``, ``timestamp``, …) and the coercer drops what it does not use, so the row stays open. */export interface SeedMessage {diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex 9afa9281c88..86be3c7f5b9 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -29719,6 +29719,18 @@"default": false,"title": "Follow Profile Config","type": "boolean"+ },+ "idempotency_key": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Idempotency Key"}},"title": "SessionCreateParams",diff --git a/tests/tui_gateway/test_protocol.py b/tests/tui_gateway/test_protocol.pyindex 0b575999a98..c28d5110a71 100644--- a/tests/tui_gateway/test_protocol.py+++ b/tests/tui_gateway/test_protocol.py@@ -1978,3 +1978,102 @@ def test_peerless_global_broadcast_never_reaches_stdout_in_ws_backend(capture, massert len(a.frames) == 1assert buf.getvalue() == ""+++# ── session.create idempotency (#65410 / PR #65411) ───────────────────+++def _stub_session_create_dependencies(server, monkeypatch):+ """Stub out the heavy deps ``session.create`` touches so it can run without+ a real agent/DB. ``session.create`` lives in the split ``methods_session``+ module but its handlers read server globals (``bind_module`` rebinds them),+ so patching the server module covers both."""+ # session.create's handler reads SERVER globals (bind_module rebinds the+ # split module's functions onto server vars), so patching the server module+ # covers everything the create path touches.+ monkeypatch.setattr(server, "_register_session_cwd", lambda *a, **kw: None)+ monkeypatch.setattr(server, "_schedule_agent_build", lambda *a, **kw: None)+ monkeypatch.setattr(server, "_schedule_session_cap_enforcement", lambda *a, **kw: None)+ monkeypatch.setattr(server, "_enable_gateway_prompts", lambda: None)+ monkeypatch.setattr(server, "_load_show_reasoning", lambda: False)+ monkeypatch.setattr(server, "_load_tool_progress_mode", lambda: None)+ monkeypatch.setattr(server, "_profile_home", lambda p: None)+ monkeypatch.setattr(server, "_profile_build_scope", _null_scope)+ monkeypatch.setattr(server, "_seed_row", lambda *a, **kw: None)+ monkeypatch.setattr(server, "_seed_branch_row", lambda *a, **kw: None)+ monkeypatch.setattr(server, "_ensure_session_db_row", lambda *a, **kw: None)+ # Fresh registry per test: the server and the rebound handler share the+ # same dict object only if we swap it in place.+ server._idempotency_keys.clear()+++class _NullScope:+ def __enter__(self):+ return self++ def __exit__(self, *exc):+ return False+++def _null_scope(profile_home):+ return _NullScope()+++def test_session_create_idempotency_key_dedupes_retry(server, monkeypatch):+ """A retried session.create with the same idempotency_key returns the SAME+ sid instead of spawning a duplicate child (#65410): a create whose first+ response was lost must not leave two children behind."""+ _stub_session_create_dependencies(server, monkeypatch)++ params = {+ "cols": 96,+ "source": "desktop",+ "messages": [{"role": "user", "content": "branch me"}],+ "parent_session_id": "parent-1",+ "idempotency_key": "branch-retry-abc",+ }+ first = server.handle_request({"id": "c1", "method": "session.create", "params": dict(params)})+ assert "error" not in first, first.get("error")+ first_sid = first["result"]["session_id"]+ assert first_sid+ assert len(server._sessions) == 1++ # Client retries after a lost response: same key, same params.+ second = server.handle_request({"id": "c2", "method": "session.create", "params": dict(params)})+ assert "error" not in second, second.get("error")+ assert second["result"]["session_id"] == first_sid+ assert len(server._sessions) == 1+++def test_session_create_no_idempotency_key_creates_distinct_sessions(server, monkeypatch):+ """Without an idempotency_key, repeated creates keep the historic behavior."""+ _stub_session_create_dependencies(server, monkeypatch)++ first = server.handle_request({"id": "c1", "method": "session.create", "params": {"cols": 96, "source": "desktop"}})+ second = server.handle_request({"id": "c2", "method": "session.create", "params": {"cols": 96, "source": "desktop"}})++ assert "error" not in first and "error" not in second+ assert first["result"]["session_id"] != second["result"]["session_id"]+ assert len(server._sessions) == 2+++def test_session_create_idempotency_key_expires_with_session(server, monkeypatch):+ """If the original session closed between create and retry, the same key+ falls through and creates a fresh session (the key does not pin a dead sid)."""+ _stub_session_create_dependencies(server, monkeypatch)++ first = server.handle_request(+ {"id": "c1", "method": "session.create",+ "params": {"cols": 96, "source": "desktop", "idempotency_key": "branch-retry-xyz"}}+ )+ first_sid = first["result"]["session_id"]++ server._sessions.pop(first_sid, None)++ second = server.handle_request(+ {"id": "c2", "method": "session.create",+ "params": {"cols": 96, "source": "desktop", "idempotency_key": "branch-retry-xyz"}}+ )+ assert "error" not in second+ assert second["result"]["session_id"] != first_sid+ assert len(server._sessions) == 1diff --git a/tui_gateway/contracts/sessions.py b/tui_gateway/contracts/sessions.pyindex b1a8a57b978..6ffeca80867 100644--- a/tui_gateway/contracts/sessions.py+++ b/tui_gateway/contracts/sessions.py@@ -133,6 +133,9 @@ class SessionCreateParams(ProfileParams):hidden: bool = Falseroom_plumbing: bool = Falsefollow_profile_config: bool = False+ # #65410: stable caller-chosen key so a retried create (response lost in+ # transit) returns the SAME session instead of a duplicate child.+ idempotency_key: str | None = Noneclass SessionCreateResult(Result):diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.pyindex 537ca8761dc..4e7086c079d 100644--- a/tui_gateway/methods_session.py+++ b/tui_gateway/methods_session.py@@ -358,6 +358,39 @@ def _create_session(rid, params: dict, *, copy_parent_history: bool = False) ->from .methods_session_model_guard import model_override_conflictif conflict := model_override_conflict(params, _profile_build_scope(profile_home)):return _err(rid, -32602, conflict.pop("message"), conflict)+ # Idempotency: a client retrying a create whose first response was lost+ # should get back the SAME session, not a fresh one (which would leave a+ # duplicate child). The caller supplies a stable key per logical create.+ idem_key = _str_param(params, "idempotency_key") or None+ if idem_key is not None:+ with _sessions_lock:+ # Drop expired entries while we're here.+ now_for_gc = time.time()+ expired = [k for k, (_, ts) in _idempotency_keys.items() if now_for_gc - ts > _IDEMPOTENCY_KEY_TTL]+ for k in expired:+ _idempotency_keys.pop(k, None)+ existing = _idempotency_keys.get(idem_key)+ if existing is not None:+ existing_sid, _ = existing+ session = _sessions.get(existing_sid)+ if session is not None:+ # Refresh the TTL so back-to-back retries don't age out mid-flight.+ _idempotency_keys[idem_key] = (existing_sid, now_for_gc)+ history = session["history"]+ override = session.get("model_override") or {}+ 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")),+ "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"]),+ "project": _project_info_for_cwd(session["cwd"]), "lazy": True,+ "desktop_contract": DESKTOP_BACKEND_CONTRACT,+ "profile_name": _response_profile_name(profile)}})+ # The session was closed between the original create and the retry —+ # fall through and create a fresh one under the same key.+ _idempotency_keys.pop(idem_key, None)(sid, source), key = _new_runtime_ids(params), _new_session_key()history = _coerce_seed_history(params.get("messages"))# Branch: links back so list_sessions_rich keeps it visible and the sidebar nests it.@@ -418,6 +451,8 @@ def _create_session(rid, params: dict, *, copy_parent_history: bool = False) ->"transport": current_transport() or _stdio_transport,"auth_user_id": _transport_auth_user_id(current_transport())}_register_session_cwd(_sessions[sid])+ if idem_key is not None:+ _idempotency_keys[idem_key] = (sid, now)if session_model_override:# A composer pick rides in as this override and beats model.default for the whole session;# name both so agent.log alone explains which model a new chat runs, and why (#107410).diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex 7e4454f978a..9a557d52e39 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -102,6 +102,12 @@ _sessions_lock = threading.RLock() # reentrant: _close_session_by_id may run un_cfg_cache: dict | None = None_cfg_sig: tuple | None = None_cfg_path = None++# Idempotency registry for session.create: maps client-supplied key → sid so a+# retried create (e.g. response lost in transit) returns the same session+# instead of spawning a duplicate child. Entries expire with the session.+_idempotency_keys: dict[str, tuple[str, float]] = {}+_IDEMPOTENCY_KEY_TTL = 300.0 # 5 min: longer than any realistic retry window_session_resume_lock = threading.Lock()_SLASH_WORKER_TIMEOUT_S = max(5.0, env_float("HERMES_TUI_SLASH_TIMEOUT_S", 45.0))