Skip to content

fix(session-tab): reattach to in-flight turn on KeepAlive activation (#759) - #782

Merged
vybe merged 1 commit into
devfrom
feature/759-session-inflight-reattach
May 11, 2026
Merged

vybe merged 1 commit into
devfrom
feature/759-session-inflight-reattach

Conversation

@webmixgamer

Copy link
Copy Markdown
Contributor

Summary

  • Adds a per-session session_inflight:{session_id} Redis sentinel and exposes turn_in_progress on GET /api/agents/{name}/sessions/{id} so the UI can reattach to a still-running turn after KeepAlive deactivation/reactivation.
  • Replaces the static 5-min resume-lock TTL with a dynamic per-agent value (get_execution_timeout(agent) + 30s, cap 7230s) so turns longer than 5 minutes no longer drop the lock and allow concurrent JSONL writes.
  • Moves Session-tab in-flight / error / fallback-notice state from local component refs into the Pinia store keyed by sessionId, which cures the cross-agent state bleed caused by AgentDetail's <KeepAlive> (one component instance services all /agents/* routes).

Why

Original framing in #759 assumed SessionPanel unmounted on navigation. Reading App.vue:5 showed 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:

  • The original plan named the lock key trinity:session:lock:{uuid}; actual code uses session_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.
  • The original plan returned turn_in_progress=false for cold turns (which skip the resume lock by design). But cold turns are the most likely interruption case (slowest first response). Solved by a separate session_inflight:{session_id} sentinel that covers both cold and warm turns.
  • The original sendMessage optimistic 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; loadSession is 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, _InflightSentinel async context manager, _ResumeLock accepts dynamic ttl_seconds, _LOCK_TTL_SECONDS = 300 removed, _serialize_session accepts turn_in_progress kwarg, 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. sendMessage rewritten (no optimistic insert; state managed in store, keyed by sessionId).
  • src/frontend/src/components/SessionPanel.vue — loading / error / fallbackNotice become computeds reading store state. onActivated re-syncs and starts polling when turn_in_progress=true. onDeactivated stops 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)

Test plan

  • Unit: cd tests && source .venv/bin/activate && python -m pytest unit/test_session_inflight_sentinel.py — 13 passed.
  • Backend integration (manual): fired a real turn against agent-testfix; GET /api/agents/testfix/sessions/{id} returned turn_in_progress=true during the turn and false after, with message_count incrementing by 2 (user + assistant). Sentinel SET/DEL roundtrips cleanly.
  • UI smoke (recommended after merge): navigate Session tab → submit a 30+ s prompt → click NavBar → Agents → click back into the agent → confirm input re-enables and assistant message appears.
  • Cross-agent bleed (recommended after merge): submit on agent A → switch to agent B → switch back to A → confirm input is enabled on B (not stuck in A's loading state).

Fixes #759

🤖 Generated with Claude Code

…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 vybe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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. ✅

@vybe
vybe merged commit d513a5b into dev May 11, 2026
12 checks passed
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]>
@webmixgamer
webmixgamer deleted the feature/759-session-inflight-reattach branch May 11, 2026 16:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

priority-p2 Important type-bug Bug fix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants