Skip to content

fix(chat): harden session view ownership#1979

Merged
zhangmo8 merged 2 commits into
devfrom
fix/chat-session-view-races
Jul 15, 2026
Merged

fix(chat): harden session view ownership#1979
zhangmo8 merged 2 commits into
devfrom
fix/chat-session-view-races

Conversation

@zhangmo8

@zhangmo8 zhangmo8 commented Jul 15, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • make the message store the sole owner of selected and committed session-view readiness
  • fence message restore, history, stream, pending-input, submit, and session hydration work against stale and A-B-A ownership
  • preserve optimistic and streaming mutations during same-session refreshes and keep recent-view cache invalidation monotonic
  • add deterministic regression coverage for first-submit, cache, stream terminal, history overlap, and rapid-switch races

Root cause

PR #1974 introduced atomic view commits and recent-session caching, but ChatPage retained an independent readiness owner. A matching stream-end refresh could supersede the page restore, commit the correct view, and leave the composer guarded until the user switched conversations. Several adjacent paths also used session-ID-only checks, which could admit stale work after A-B-A navigation or overwrite newer in-memory mutations.

Compatibility

No database, persisted-data, preload, or shared IPC contract changes.

Validation

  • pnpm test: 5,516 passed, 198 skipped; the only 3 failures were sandbox listen EPERM errors in Feishu loopback callback tests
  • Feishu callback suite rerun with local-listen permission: 22/22 passed
  • focused renderer race suites passed
  • pnpm run typecheck
  • pnpm run format
  • pnpm run i18n
  • pnpm run lint
  • pnpm run build

Local validation used Node 26.0.0 while the repository declares Node >=24.14.1 <25. Provider and ACP registry refreshes fell back to existing snapshots because their remote endpoints were unavailable in the validation environment.

SDD: docs/issues/chat-session-view-races/spec.md

Summary by CodeRabbit

  • Bug Fixes
    • Improved chat session switching, restoration, and hydration correctness, including rapid A→B→A navigation.
    • Prevented stale session loads, streaming updates, terminal events, and queued/pending input results from overwriting the active view.
    • Hardened optimistic/draft handling and streaming UI behavior to keep composer and displayed messages in sync.
  • Documentation
    • Updated architecture specs for session/view ownership, streaming correctness, and cache invalidation/race handling.
  • Tests
    • Expanded automated coverage for session races, streaming ordering, cache invalidation, hydration flow, queued inputs, and stale async protections.

@coderabbitai

coderabbitai Bot commented Jul 15, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 0ffd34ac-ff62-47b0-9047-6069417b6c37

📥 Commits

Reviewing files that changed from the base of the PR and between 8e934ed and 3a11f01.

📒 Files selected for processing (9)
  • docs/issues/chat-session-view-races/spec.md
  • src/renderer/src/pages/ChatPage.vue
  • src/renderer/src/stores/ui/message.ts
  • src/renderer/src/stores/ui/messageIpc.ts
  • src/renderer/src/stores/ui/pendingInput.ts
  • src/renderer/src/stores/ui/session.ts
  • test/renderer/components/ChatPage.test.ts
  • test/renderer/stores/messageStore.test.ts
  • test/renderer/stores/sessionStore.test.ts
🚧 Files skipped from review as they are similar to previous changes (7)
  • test/renderer/stores/sessionStore.test.ts
  • src/renderer/src/stores/ui/pendingInput.ts
  • test/renderer/stores/messageStore.test.ts
  • test/renderer/components/ChatPage.test.ts
  • src/renderer/src/stores/ui/session.ts
  • src/renderer/src/stores/ui/message.ts
  • src/renderer/src/pages/ChatPage.vue

📝 Walkthrough

Walkthrough

The change centralizes session-view ownership in the message store and adds request, revision, and stream identity fences across ChatPage, session hydration, pending inputs, caching, and IPC streaming. Tests and architecture documentation cover rapid navigation, stale async work, cache invalidation, stream ordering, and submit races.

Changes

Chat session race hardening

Layer / File(s) Summary
Message ownership and cache revisions
src/renderer/src/stores/ui/message.ts, src/renderer/src/stores/ui/stream.ts, test/renderer/stores/messageStore.test.ts, docs/architecture/chat-scroll-ownership/*, docs/issues/chat-session-view-races/spec.md
The message store tracks committed sessions, mutation revisions, invalidated recent views, guarded loads, optimistic-message ownership, and revised cache activation behavior.
Request-aware stream lifecycle
src/renderer/src/stores/ui/messageIpc.ts, src/renderer/src/stores/ui/stream.ts
Streaming updates and terminals are ordered and settled by session/request identity, timestamps, metadata, and settled-request tracking.
Session-scoped rendering and async writes
src/renderer/src/pages/ChatPage.vue, test/renderer/components/ChatPage.test.ts
ChatPage rendering, restoration, submit, queue, steer, compaction, and unmount continuations are guarded by current session and page-generation ownership.
Session hydration and pending-input fencing
src/renderer/src/stores/ui/session.ts, src/renderer/src/stores/ui/pendingInput.ts, test/renderer/stores/sessionStore.test.ts, test/renderer/stores/pendingInputStore.test.ts
Session hydration carries activation request identity and invalidates recent views; pending-input operations apply only for the latest request and active session.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant ChatPage
  participant messageStore
  participant chatClient
  ChatPage->>messageStore: verify session and page generation
  ChatPage->>chatClient: submit chat turn
  chatClient-->>messageStore: stream updates with request identity
  messageStore-->>ChatPage: render current-session stream
  chatClient-->>messageStore: terminal event
  messageStore->>messageStore: settle only the owning request
Loading

Possibly related PRs

Suggested reviewers: zerob13

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly captures the main change: hardening chat session-view ownership against stale races.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/chat-session-view-races

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 2

🧹 Nitpick comments (2)
src/renderer/src/stores/ui/pendingInput.ts (1)

50-137: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Repeated mutate-then-conditionally-reload pattern across queueInput, updateQueueInput, moveQueueInput, steerPendingInput, deleteInput.

Each function repeats the same "clear error if current session → call client → reload if still current session → set error if still current session, rethrow" shape. Worth extracting into a shared helper to reduce duplication.

♻️ Suggested extraction
+  async function runSessionScopedMutation(
+    sessionId: string,
+    operation: () => Promise<void>,
+    errorPrefix: string
+  ): Promise<void> {
+    if (currentSessionId.value === sessionId) {
+      error.value = null
+    }
+    try {
+      await operation()
+      if (currentSessionId.value === sessionId) {
+        await loadPendingInputs(sessionId)
+      }
+    } catch (e) {
+      if (currentSessionId.value === sessionId) {
+        error.value = `${errorPrefix}: ${e}`
+      }
+      throw e
+    }
+  }
+
   async function queueInput(sessionId: string, input: string | SendMessageInput): Promise<void> {
-    if (currentSessionId.value === sessionId) {
-      error.value = null
-    }
-    try {
-      await sessionClient.queuePendingInput(sessionId, input)
-      if (currentSessionId.value === sessionId) {
-        await loadPendingInputs(sessionId)
-      }
-    } catch (e) {
-      if (currentSessionId.value === sessionId) {
-        error.value = `Failed to queue message: ${e}`
-      }
-      throw e
-    }
+    return runSessionScopedMutation(
+      sessionId,
+      () => sessionClient.queuePendingInput(sessionId, input),
+      'Failed to queue message'
+    )
   }

Apply the same pattern to updateQueueInput, moveQueueInput, steerPendingInput, and deleteInput.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/renderer/src/stores/ui/pendingInput.ts` around lines 50 - 137, Extract
the repeated clear-error, client mutation, conditional reload, and
session-scoped error handling from queueInput, updateQueueInput, moveQueueInput,
steerPendingInput, and deleteInput into a shared helper. Have each operation
delegate its client call and operation-specific failure message to that helper
while preserving the existing current-session checks and rethrow behavior.
src/renderer/src/stores/ui/message.ts (1)

74-83: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

messageMutationRevisions, recentViewInvalidationRevisions, and dirtyRecentSessionViews grow unbounded across the app lifetime.

Unlike recentSessionViews (a bounded LRU), these three plain Map/Set structures are only cleared wholesale in clear(). Deleted sessions invalidate their cached view (invalidateRecentSessionView, e.g. called from removeSessions in session.ts) but never purge their entries here, so every session ever created or switched away from during a long-running Electron session leaks a small amount of memory indefinitely.

♻️ Suggested cleanup hook
+  function purgeSessionTracking(sessionId: string): void {
+    messageMutationRevisions.delete(sessionId)
+    recentViewInvalidationRevisions.delete(sessionId)
+    dirtyRecentSessionViews.delete(sessionId)
+  }

Expose purgeSessionTracking and call it alongside invalidateRecentSessionView wherever a session is permanently removed.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/renderer/src/stores/ui/message.ts` around lines 74 - 83, Expose a
purgeSessionTracking helper that removes a session’s entries from
messageMutationRevisions, recentViewInvalidationRevisions, and
dirtyRecentSessionViews. Invoke it alongside invalidateRecentSessionView in the
permanent session-removal flow, including removeSessions, while preserving
existing invalidation behavior for non-deleted sessions.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/renderer/src/pages/ChatPage.vue`:
- Around line 2542-2544: Update the restore flow around loadMessagesForSession
and applyRestoredSessionSummary to check whether restoredSession is null before
applying it. Return without updating the active summary when the load returns
null, while preserving the existing canWriteSessionView validation and applying
non-null results normally.

In `@src/renderer/src/stores/ui/messageIpc.ts`:
- Around line 39-53: Update the stream acceptance logic around streamKey,
markStreamSettled, and the affected lines 57–79 so a request ID that was
superseded or settled cannot reclaim the session stream, regardless of event
timestamp or settled-key eviction. Track a durable per-session
generation/tombstone state, reject late superseded events such as A@3 after B@2,
and add a regression test covering that sequence.

---

Nitpick comments:
In `@src/renderer/src/stores/ui/message.ts`:
- Around line 74-83: Expose a purgeSessionTracking helper that removes a
session’s entries from messageMutationRevisions,
recentViewInvalidationRevisions, and dirtyRecentSessionViews. Invoke it
alongside invalidateRecentSessionView in the permanent session-removal flow,
including removeSessions, while preserving existing invalidation behavior for
non-deleted sessions.

In `@src/renderer/src/stores/ui/pendingInput.ts`:
- Around line 50-137: Extract the repeated clear-error, client mutation,
conditional reload, and session-scoped error handling from queueInput,
updateQueueInput, moveQueueInput, steerPendingInput, and deleteInput into a
shared helper. Have each operation delegate its client call and
operation-specific failure message to that helper while preserving the existing
current-session checks and rethrow behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 6ca27d02-0aeb-4790-9d6f-d2fee506b03e

📥 Commits

Reviewing files that changed from the base of the PR and between ce480c2 and 8e934ed.

📒 Files selected for processing (14)
  • docs/architecture/chat-scroll-ownership/spec.md
  • docs/architecture/chat-scroll-ownership/tasks.md
  • docs/issues/chat-session-view-races/spec.md
  • src/renderer/src/pages/ChatPage.vue
  • src/renderer/src/stores/ui/message.ts
  • src/renderer/src/stores/ui/messageIpc.ts
  • src/renderer/src/stores/ui/pendingInput.ts
  • src/renderer/src/stores/ui/session.ts
  • src/renderer/src/stores/ui/stream.ts
  • test/renderer/components/ChatPage.test.ts
  • test/renderer/stores/messageStore.reactivity.test.ts
  • test/renderer/stores/messageStore.test.ts
  • test/renderer/stores/pendingInputStore.test.ts
  • test/renderer/stores/sessionStore.test.ts

Comment thread src/renderer/src/pages/ChatPage.vue
Comment thread src/renderer/src/stores/ui/messageIpc.ts Outdated
@zhangmo8

Copy link
Copy Markdown
Collaborator Author

Addressed the two review-summary nitpicks in 3a11f01cd as well: pending-input mutations now share one session-scoped helper, and permanent session removal purges message revision, cache invalidation, dirty-view, and stream tombstone tracking. Validation: 171/171 focused tests, Web typecheck, format, i18n, and lint passed.

@zhangmo8 zhangmo8 merged commit 1034903 into dev Jul 15, 2026
4 checks passed
@zhangmo8 zhangmo8 deleted the fix/chat-session-view-races branch July 16, 2026 01:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant