Skip to content

fix(chat): ensure agent persists correctly after page refresh#9832

Open
juliennonin wants to merge 3 commits intoonyx-dot-app:mainfrom
craft-ai:fix/agent_selection_on_page_refresh
Open

fix(chat): ensure agent persists correctly after page refresh#9832
juliennonin wants to merge 3 commits intoonyx-dot-app:mainfrom
craft-ai:fix/agent_selection_on_page_refresh

Conversation

@juliennonin
Copy link
Copy Markdown

@juliennonin juliennonin commented Apr 1, 2026

Description

Fixes #8087.

Fixes a race condition where the agent selection was initialized in useState before availableAgents loaded, causing the wrong agent to be selected after page refresh.

How Has This Been Tested?

Updated live_agent.spec.ts to test after page refresh.

Additional Options

  • [Optional] Please cherry-pick this PR to the latest release version.
  • [Optional] Override Linear Check

Summary by cubic

Fixes a race condition that selected the wrong agent after a page refresh. The chosen agent now persists through reloads and after starting a chat, and stays in sync with the sidebar.

  • Bug Fixes
    • Compute the implied agent with useMemo after availableAgents load, using chat persona_id or defaultAgentId when present.
    • Selection order: explicit user choice, then implied agent, then defaults.
    • Expose data-testid="sidebar-section/{title}" and add a sidebar check in e2e to ensure the selected agent stays highlighted after sending a message and after a hard reload.

Written for commit 6204e7f. Summary will update on new commits.

@juliennonin juliennonin force-pushed the fix/agent_selection_on_page_refresh branch from 68a06d6 to 1126f74 Compare April 1, 2026 19:14
@juliennonin juliennonin changed the title fix(chat): ensure assistant persists correctly after page refresh fix(chat): ensure agent persists correctly after page refresh Apr 1, 2026
@juliennonin juliennonin marked this pull request as ready for review April 1, 2026 19:16
@juliennonin juliennonin requested a review from a team as a code owner April 1, 2026 19:16
@juliennonin juliennonin force-pushed the fix/agent_selection_on_page_refresh branch from 1126f74 to cafea39 Compare April 1, 2026 19:19
Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

2 issues found across 4 files

Confidence score: 3/5

  • There is a concrete regression risk in web/src/hooks/useAgentController.ts: liveAgent can remain memoized without impliedAssistant in its dependency set, so persona/session changes may show a stale assistant state to users.
  • web/tests/e2e/utils/chatActions.ts introduces a reliability risk rather than a product bug: the 1s default timeout is likely too short after refresh and can cause intermittent E2E failures.
  • Given two medium-severity, high-confidence findings (including one user-facing behavior issue), this carries some merge risk and is better addressed before landing.
  • Pay close attention to web/src/hooks/useAgentController.ts and web/tests/e2e/utils/chatActions.ts - stale memoized agent selection and overly aggressive timeout defaults can cause incorrect UI state and flaky tests.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="web/src/hooks/useAgentController.ts">

<violation number="1" location="web/src/hooks/useAgentController.ts:62">
P2: `liveAgent` now returns `impliedAssistant` but the memo deps don’t include it (or its source IDs). When the session/URL persona changes, `impliedAssistant` updates while `liveAgent` stays memoized, leaving a stale agent selection.</violation>
</file>

<file name="web/tests/e2e/utils/chatActions.ts">

<violation number="1" location="web/tests/e2e/utils/chatActions.ts:21">
P2: New sidebar verification helper uses a 1s default timeout, which is too aggressive for post-refresh UI assertions and can cause flaky E2E failures.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

@greptile-apps
Copy link
Copy Markdown
Contributor

greptile-apps bot commented Apr 1, 2026

Greptile Summary

This PR fixes a race condition in useAgentController where the selected agent was initialised inside useState(…) before availableAgents had loaded from SWR, causing the wrong (usually the default) agent to appear after a hard page reload.

Key changes:

  • impliedAssistant is now computed via useMemo (instead of being baked into the useState initial value), so it re-evaluates once availableAgents arrives. The explicit type annotation (MinimalPersonaSnapshot | undefined) follows the repo's type-annotation standards.
  • The selection precedence is made explicit in comments: explicit user choice → implied agent (from chat session persona_id or URL param) → unified/pinned/available defaults.
  • SidebarSection gains a data-testid={sidebar-section/${title}} attribute so e2e tests can reliably target a specific sidebar section.
  • The e2e test live_agent.spec.ts is extended to send a message (persisting the session with a persona_id), hard-reload the page, and assert the correct agent is still highlighted in the sidebar.
  • A new verifyAgentIsChosenInSidebar helper is added in chatActions.ts with a default 5 000 ms timeout — consistent with the existing verifyAgentIsChosen.

The fix is minimal and well-scoped. The only minor nit is a leftover comment stub in the spec file (no assertion follows it) that may confuse future maintainers.

Confidence Score: 5/5

  • Safe to merge — the race-condition fix is correct and the only remaining finding is a minor comment cleanup in a test file.
  • All remaining findings are P2 style suggestions; no logic errors or data-integrity issues were identified. The core useMemo refactor correctly handles the async load of availableAgents, and the selection priority ordering is sound.
  • No files require special attention.

Important Files Changed

Filename Overview
web/src/hooks/useAgentController.ts Core bug fix: moves implied agent computation from useState initialization into a reactive useMemo, correctly handling async availableAgents load on page refresh. Type annotation is explicit. Priority ordering (explicit selection → implied → defaults) is sound.
web/src/sections/sidebar/SidebarSection.tsx Minimal, clean addition of data-testid derived from the title prop to enable sidebar section targeting in e2e tests.
web/tests/e2e/chat/live_agent.spec.ts Adds page-reload persistence test for the selected agent; contains a dangling comment stub with no assertion body that could confuse future maintainers.
web/tests/e2e/utils/chatActions.ts New verifyAgentIsChosenInSidebar helper targets the sidebar section via data-testid and checks the selected state; default timeout is consistent with existing helpers (5000 ms).

Sequence Diagram

sequenceDiagram
    participant Browser
    participant React
    participant SWR
    participant useAgentController

    Browser->>React: Hard page reload
    React->>useAgentController: mount (availableAgents = [])
    Note over useAgentController: selectedAgent = undefined (useState)<br/>impliedAssistant = undefined (availableAgents empty)<br/>liveAgent → unified/default fallback

    React->>SWR: fetch /api/persona & /api/chat-session
    SWR-->>React: availableAgents loaded, chatSession loaded

    React->>useAgentController: re-render (availableAgents populated)
    Note over useAgentController: impliedAssistant = availableAgents.find(chatSession.persona_id)<br/>liveAgent = impliedAssistant ✓ correct agent shown
Loading
Prompt To Fix All With AI
This is a comment left during a code review.
Path: web/tests/e2e/chat/live_agent.spec.ts
Line: 57

Comment:
**Dangling comment with no assertion**

The comment `// Verify the agent is still selected in the sidebar` is left without a corresponding assertion directly below it — the actual `verifyAgentIsChosenInSidebar` call for the pre-reload state was placed above at line 52, and the post-reload check is at line 63. This orphaned comment could mislead future readers into thinking a step was accidentally omitted.

```suggestion
  // Hard refresh the page
```

How can I resolve this? If you propose a fix, please make it concise.

Reviews (3): Last reviewed commit: "Merge branch 'main' into fix/agent_selec..." | Re-trigger Greptile

@juliennonin juliennonin force-pushed the fix/agent_selection_on_page_refresh branch from cafea39 to 0620314 Compare April 2, 2026 06:16
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.

Bug: When refreshing a chat session page, the default agent is being displayed instead of the actual agent

1 participant