Repository navigation
fix(session-tab): reattach to in-flight turn on KeepAlive activation (#759) - #782
Merged
Merged
Conversation
…759) AgentDetail is wrapped in <KeepAlive>, so SessionPanel deactivates on navigation rather than unmounting. Local refs (loading, error, fallbackNotice) survived deactivation; a transient error became a permanent "Failed to send" toast, the input stayed disabled, and state bled across agents (one cached instance services all /agents/* routes). Backend (routers/sessions.py): - New `session_inflight:{session_id}` Redis sentinel SET for the duration of any turn (cold + warm), DEL in finally. Drives the new `turn_in_progress` field on GET sessions/{id} so the UI can reattach on KeepAlive activation. Distinct from the per-(agent, claude_uuid) resume lock — that one skips cold turns by design. - `_session_lock_key(agent, uuid)` helper extracted as the single source of the lock-key string. Regression guard against typo class. - Static `_LOCK_TTL_SECONDS = 300` removed. TTL is now per-call, resolved via `db.get_execution_timeout(agent) + 30s`, capped at 7230s. Long turns no longer drop the lock mid-flight and allow concurrent JSONL writes. Frontend (stores/sessions.js + SessionPanel.vue): - inFlightBySession / errorBySession / fallbackNoticeBySession move from local refs into Pinia keyed by sessionId. Cures cross-agent bleed automatically (each agent has different session ids). - onActivated re-syncs via loadSession; if `turn_in_progress=true`, ref-counted polling (2s -> 5s -> 15s backoff, 60-attempt cap) runs until the assistant message lands or backend signals completion. - onDeactivated stops polling; agent-change watch clears UI ephemera. - Optimistic insert dropped (autoplan TD2) — loadSession is the canonical source. Tests: 13 AST/structural + formula unit tests pinning the lock-key helper usage, sentinel context-manager wrapping, dynamic TTL formula, serializer contract. Cold-turn JSONL race is filed separately as #779. Fixes #759 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
vybe
approved these changes
May 11, 2026
vybe
left a comment
Contributor
There was a problem hiding this comment.
LGTM — well-engineered fix. Root cause analysis (KeepAlive deactivation vs unmount) is correct. Two-primitive Redis design is the right separation. Dynamic TTL is a real correctness fix. 13 AST/structural unit tests are a nice touch. Docs all updated. Security clean. ✅
This was referenced May 11, 2026
Closed
vybe
pushed a commit
that referenced
this pull request
May 11, 2026
… user-message echo (#790) Two follow-up fixes for #782's KeepAlive reattach work, both on the same SessionPanel code path. Filed and tested as #789. 1. TOCTOU race in onActivated (SessionPanel.vue) AgentDetail's route watcher calls loadAgent() async, so `agent.value` (and therefore `SessionPanel.props.agentName`) can update mid-await. Reading `props.agentName` after `await sessionsStore.loadSession(...)` paired the previous agent's session id with the new agent's name; startPolling captured the cross-agent pair and 404'd ~60 times per incident against `GET /api/agents/<new>/sessions/<old-sid>` until MAX_ATTEMPTS hit ~22 min later. Surface: stuck spinner + blocked input on the original agent after switching away and back. Fix: capture `agentName` and `sid` into locals before the await; pass the captured pair to startPolling. 2. Missing optimistic user-message insert (stores/sessions.js) PR #782 dropped the optimistic insert from sendMessage on the assumption that turns are fast ("~100-300 ms perceived latency"). For a 30s+ Bash/sleep prompt the user stares at a bare spinner for the full turn duration. The Chat tab does this correctly at ChatPanel.vue:612. Fix: optimistic insert at the start of sendMessage without rollback on error. Backend persists the user row at turn start so loadSession on success overwrites the optimistic row with the canonical one (same content, no flicker). On error the row is intentionally kept in view — server-side failures occur after the user row is persisted, and for the rare network failure where the POST never reaches the server, keeping the row visible is still better than silent disappearance. Tests: tests/unit/test_session_panel_race_capture.py — 4 AST/regex guards pinning (a) `const agentName = props.agentName` captured before first await in onActivated, (b) no re-read of props.agentName after the capture, (c) `messagesBySession[sessionId] = [...]` precedes the axios.post in sendMessage, (d) the optimistic insert spreads existing messages rather than replacing. Same convention as test_session_inflight_sentinel.py. Docs: feature-flows/session-tab.md line 51 corrected — "optimistic insert + rollback on failure" was wrong both before #782 (which removed it entirely) and after #789 (which restores it without rollback). Verified live against testfix + testfix-2: - 404 polling errors gone. - Cross-agent stuck-spinner repro gone. - User message echoes immediately on send. - #759 cross-agent bleed scenario still works end-to-end. Fixes #789 Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
session_inflight:{session_id}Redis sentinel and exposesturn_in_progressonGET /api/agents/{name}/sessions/{id}so the UI can reattach to a still-running turn after KeepAlive deactivation/reactivation.get_execution_timeout(agent) + 30s, cap 7230s) so turns longer than 5 minutes no longer drop the lock and allow concurrent JSONL writes.<KeepAlive>(one component instance services all/agents/*routes).Why
Original framing in #759 assumed SessionPanel unmounted on navigation. Reading
App.vue:5showed it's wrapped in<KeepAlive :include="['SystemAgent', 'AgentDetail']">, so the component deactivates instead. Local refs survive, which makes a transient error become a permanent "Failed to send" toast and leaves the input disabled even after the backend turn completes.Two independent reviews of the original draft (strategy + engineering subagents in /autoplan) caught additional issues that are also addressed:
trinity:session:lock:{uuid}; actual code usessession_lock:{agent}:{uuid}. A typo would have silently split-brained the producer (lock acquire) and the new probe (EXISTS check). Lock-key construction is now centralised in a_session_lock_key()helper, asserted by an AST regression test.turn_in_progress=falsefor cold turns (which skip the resume lock by design). But cold turns are the most likely interruption case (slowest first response). Solved by a separatesession_inflight:{session_id}sentinel that covers both cold and warm turns.sendMessageoptimistic rollback wiped the user's message from view on any failure, even though the backend persists the user row at turn start. Optimistic insert dropped per the plan-review decision;loadSessionis the canonical source.Cold-turn JSONL race (a separate defect surfaced during reproduction) is filed as #779 and explicitly out of scope.
Changes
src/backend/routers/sessions.py—_session_lock_key,_session_inflight_key,_resolve_lock_ttl,_get_async_redis, sentinel SET/DEL/EXISTS helpers,_InflightSentinelasync context manager,_ResumeLockaccepts dynamicttl_seconds,_LOCK_TTL_SECONDS = 300removed,_serialize_sessionacceptsturn_in_progresskwarg, GET endpoint computes the field, turn handler bracketed by the sentinel.src/frontend/src/stores/sessions.js— new state:inFlightBySession,errorBySession,fallbackNoticeBySession,pollTimerBySession,pollWatchersBySession. Getters and actions to drive ref-counted polling (startPolling/stopPolling) with 2 s → 5 s → 15 s backoff and a 60-attempt cap.sendMessagerewritten (no optimistic insert; state managed in store, keyed by sessionId).src/frontend/src/components/SessionPanel.vue—loading/error/fallbackNoticebecome computeds reading store state.onActivatedre-syncs and starts polling whenturn_in_progress=true.onDeactivatedstops polling. Agent-change watch clears local UI ephemera so it doesn't bleed across agents.tests/unit/test_session_inflight_sentinel.py— 13 AST / structural / formula tests, all passing locally.docs/memory/architecture.md,docs/memory/feature-flows.md,docs/memory/feature-flows/session-tab.md— describe the two-primitive design + dynamic TTL.Out of scope (filed separately)
AgentDetail.Test plan
cd tests && source .venv/bin/activate && python -m pytest unit/test_session_inflight_sentinel.py— 13 passed.agent-testfix;GET /api/agents/testfix/sessions/{id}returnedturn_in_progress=trueduring the turn andfalseafter, withmessage_countincrementing by 2 (user + assistant). Sentinel SET/DEL roundtrips cleanly.Fixes #759
🤖 Generated with Claude Code