Agent - "Hmm... it's not here" appears when quickly opening the Edit Agent page after creating an agent
If you haven’t already, check out our contributing guidelines for onboarding. To join our Slack channel, fill out this form.
Version Number: 9.4.75-0 Reproducible in staging?: Yes Reproducible in production?: Yes If this was caught during regression testing, add the test name, ID and link from BrowserStack: Email or phone of affected tester (no customers): Logs: https://stackoverflow.com/c/expensify/questions/4856 Expensify/Expensify Issue URL: Issue reported by: @huult Slack conversation (hyperlinked to channel name): #expensify_bugs
Action Performed:
- Go to Account → Agents → New Agent.
- Create an agent.
- Quickly open the agent that was just created.
Expected Result:
The Edit Agent page should be displayed.
Actual Result:
"Hmm... it's not here" appears instead of the Edit Agent page.
Workaround:
Unknown
Platforms:
Select the officially supported platforms where the issue was reproduced:
- [ ] Android: App
- [ ] Android: mWeb Chrome
- [ ] iOS: App
- [ ] iOS: mWeb Safari
- [ ] iOS: mWeb Chrome
- [x] Windows: Chrome
- [ ] MacOS: Chrome / Safari
Screenshots/Videos
https://github.com/user-attachments/assets/f9de41b5-fef7-4af5-8043-7dbacdd04721
Proposal
What is the root cause of that problem?
A newly created agent lives under a client-generated optimistic accountID (Agent.ts:51), because only the backend can assign the real one. When CreateAgent responds, replaceOptimisticAgentWithActualAgent does two things in order: it rewrites the accountID param of any already-open agent settings screen, then deletes the optimistic personalDetailsList entry and sharedNVP_agentPrompt_<optimisticID> key (replaceOptimisticAgentWithActualAgent.ts:110-125).
That rewrite is a one-shot sweep of the navigation state at a single instant (:56-76) and nothing re-runs it. So if you open the agent at almost exactly the moment the response lands, your route is created with the optimistic ID but is not in navigationRef.getRootState() when the sweep walks it — the sweep misses it, and the two Onyx keys it points at are then deleted permanently.
EditAgentPage reads the route param raw and 404s as soon as both keys resolve to nothing (EditAgentPage.tsx:44-53):
const accountID = route.params.accountID;
const shouldShowNotFoundPage = isOnyxLoaded && !agent && !personalDetails;
The session already keeps an in-memory optimistic→real map for exactly this case — its own docblock calls it "the only way a late caller (e.g. an agent settings screen opened before the redirect) can still translate an optimistic accountID" (AgentAccountIDMapping.ts:15-17) — but no read path ever calls resolveAgentAccountID; only the four write actions in Agent.ts do. So the miss is unrecoverable and the page stays on "Hmm... it's not here".
Why the race is easy to hit on web, and the two ways it fires
runAfterTransitions({callback}) is called without waitForUpcomingTransition, so when no transition is active it invokes the callback synchronously (TransitionTracker.ts:207-210). The tracker itself notes that on web transitionStart fires before the nav state event (:170), so a tap can be dispatched with the route not yet committed to the nav state that the sweep reads.
Two variants, same root cause:
- Tap lands just before the sweep — the push is dispatched but not yet in
getRootState(), sosetParamsmisses it and lines 120-121 delete the data out from under the screen that just mounted. - Tap lands just after the sweep — the
AgentsPagerow closure captured the optimistic ID (AgentsPage.tsx:119) and hasn't re-rendered from the Onyx deletion yet, so the navigation starts with a dead ID after the sweep already ran.
Ruled out: a failed CreateAgent isn't the cause — failureData keeps the optimistic row with an RBR error, so the Edit page would render, not 404. Route-param parsing isn't the cause either — optimistic IDs are safe integers and linkingConfig parses accountID as Number.
Same root cause reaches other entry points, which is why a navigation-only fix isn't enough: ProfilePage links to SETTINGS_AGENTS_EDIT_PROMPT with the raw accountID and is deliberately excluded from the sweep, and on web an already-pushed history entry for settings/agents/<optimisticID>/edit can't be rewritten by setParams at all.
What changes do you think we should make in order to solve the problem?
Resolve the optimistic accountID on the read path, so a screen holding a dead optimistic ID still finds the real agent no matter when it was opened.
- In
EditAgentPage.tsx:44, passroute.params.accountIDthroughresolveAgentAccountID()before the Onyx lookups instead of using it raw. - Do the same in the sibling agent screens that read the param raw and have no not-found guard at all:
Fields/EditNamePage.tsx:31,Fields/EditPromptPage.tsx:44,Fields/EditAgentAvatarPage.tsx:236, andProfilePage's agent rows. - Share it as one small hook (for example
useAgentAccountID(routeAccountID)) so all five screens stay consistent. The mapping is registered at:105before the deletes at:120-122, so the re-render caused by the deletion is already the render where the resolve returns the real ID — the page swaps to the real agent instead of flashing not-found. Note the mapping is a module-levelMap, so read it inside that hook rather than inline in render, to keep the screens React Compiler friendly.
Keep the existing sweep — it still repairs the visible URL for open screens. This change just stops the sweep's timing from being load-bearing.
Suggested regression test: create an agent while throttling the CreateAgent response, tap the new row from the Agents list during the pending window, and assert the Edit page renders the agent (never NotFoundPage) both before and after the response lands.
What alternative solutions did you explore? (Optional)
- Pass
waitForUpcomingTransition: 'navigation'torunAfterTransitionsat:111so the sweep waits for an in-flight navigation. This narrows the window but doesn't close it — the sweep is still one-shot, and it does nothing forProfilePagelinks or web history entries. - Keep the optimistic keys around instead of deleting them. Rejected: it leaves duplicate rows in the Agents list, since
AgentsPage.tsx:89-125has no dedupe. - Block the Agents row until the create resolves. Rejected: it degrades the offline-first experience for a race that only lasts a few hundred milliseconds.
Related issues
- Expensify/App#93272 — "Add Agent" leads to "It's not here" after creating the first agent. Very likely the same root cause (a route built with an optimistic agent
accountIDthat no longer resolves); worth fixing together, and it already has a PR in review. - Expensify/App#99507 — not-here page appears briefly when copiloting into an agent's account. Possibly related: the optimistic personal detail deliberately omits
login(Agent.ts:60-66), which the copilot path depends on.
Confidence: Medium-High. The mechanism is confirmed from code (the exact not-found condition, the one-shot sweep, the synchronous runAfterTransitions path, and the fact that no read path calls resolveAgentAccountID). Which of the two race variants fires in a given repro needs instrumentation to pin down, but both are fixed by the same change.
Next Steps for Contributor+ team:
To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/100865) to create a draft PR.
To refine: @MelvinBot <your feedback>
To reject: Explain why you are rejecting Melvin's proposal.
Triggered auto assignment to Contributor-plus team member for initial proposal review - @getusha (External)
Unable to auto-create job on Upwork. The BZ team member should create it manually for this issue.
Checking if this should be solved by https://github.com/Expensify/App/pull/100577 too.
Proposal
What is the root cause of that problem?
A newly created agent first uses a temporary accountID. When the server returns the real ID, replaceOptimisticAgentWithActualAgent redirects the agent settings screens currently in the navigation state, then removes the temporary personal details, prompt, and ID mapping.
Navigation redirect and cleanup
The failure occurs when another browser tab processes the creation request. That tab receives the temporary-to-real ID mapping, redirects its own navigation state, and deletes the mapping along with the temporary agent data. Cross-tab Onyx synchronization notifies the Edit tab that the key changed, but by the time that tab reads it, the mapping can already be empty.
The Edit page reads route.params.accountID directly. Without receiving the mapping, it stays on the temporary ID and reads the deleted personal details and prompt, so it renders "Hmm... it's not here" even though the real agent exists.
Edit page subscriptions and not-found condition
The module-level ID map cannot recover this missed update because each tab has its own instance.
I reproduced this sequence on staging 9.4.77-1 with a trace in both tabs: the processing tab received and cleared the mapping; the Edit tab received only an empty mapping and remained on the temporary URL. Its real agent details were present. Returning to the list and reopening the real-ID row recovered the page. The failure also reproduced after removing the diagnostic hooks.
Melvin's proposal identifies the missing read-side resolution. The paired trace establishes why a session-local resolver alone is insufficient: the Edit tab may never receive the mapping to register. This proposal retains the mapping in Onyx and makes the Edit screens react to it.
This agent-ID failure reproduces independently of the marketing-window change in #100577. I suggest a dedicated PR for #100865, subject to scope approval.
What changes do you think we should make in order to solve the problem?
-
Retain valid temporary-to-real ID mappings in
ONYXKEYS.OPTIMISTIC_AGENT_ACCOUNT_ID_MAPPINGafter replacement. Continue removing the temporary personal details and prompt, and continue rejecting malformed or identity mappings. Record processed ID pairs in each tab before scheduling replacement so later mapping updates do not repeat its navigation and cleanup work. Keep registration with the existing action resolver before this guard. -
Add a shared
useAgentAccountIDhook that subscribes to the mapping for the route's ID and returns the resolved ID and loading metadata. Use it in Edit Agent, Edit Name, Edit Prompt, and Edit Avatar so their subscriptions, saves, and child navigation use the real ID as soon as it becomes available. -
When the resolved ID changes, update that mounted screen's route through its own navigator. This keeps the parent and child routes consistent, so Save or Back returns to the existing Edit screen rather than creating a second Edit screen. Keep the existing navigation sweep for routes already in the stack.
-
Wait for the ID mapping and agent data subscriptions to finish loading before deciding that Edit Agent is not found. A retained mapping only resolves identity: if the real agent has actually been deleted, the existing not-found behavior must still apply.
Test coverage:
- Retain the mapping after temporary-data cleanup, including when another tab reads it later; preserve repeated-delivery, invalid-mapping, and startup behavior.
- Keep an already-open temporary-ID Edit screen usable when the real data and mapping arrive, and resolve a temporary-ID route opened after replacement has completed.
- Verify the screen requests the real ID in its route params and still renders not-found after the real agent is deleted.
- Exercise rapid opening, offline creation and reconnect from another tab, old temporary-ID URL reload, and Name/Prompt/Avatar Save and Back navigation.
The local candidate includes changes to the replacement-action and Edit Agent tests. Those tests and the remote checks have not run yet.
What alternative solutions did you explore? (Optional)
Calling resolveAgentAccountID() directly from each screen would help when the current tab has already registered the mapping, but it cannot recover a mapping that the tab never received or retain it across a reload. A reactive Onyx subscription covers those cases.
Waiting longer before the navigation sweep only changes its timing. A later route, a second tab, or an old URL can still reference the temporary ID after that sweep has finished.
Keeping the temporary personal details and prompt would leave duplicate or stale agent data. Retaining only the identity mapping allows the existing cleanup to continue. Disabling the pending agent row would also prevent the supported offline editing flow.
Validation so far
A matched before-and-after test now demonstrates the same two-tab failure on the baseline and success on the isolated comparison commit. Both phases used the same Chrome profile, account, development runtime, ordinary network settings, and Create → close automatic chat → immediately open Edit sequence. A separate observed tab sent CreateAgent in every counted attempt.
| Source | Result |
|---|---|
Baseline 6d42ea0, without the candidate |
Edit opened on the temporary ID after 2.637 seconds. The processing tab cleared the mapping before Edit read it; Edit stayed on the temporary URL and rendered not-found. |
Candidate 4143d88, first attempt |
Edit opened on the temporary ID after 2.571 seconds, received the retained mapping, and reached the real-ID page with name/avatar/login and enabled Chat/Copilot buttons. |
| Same candidate, repeated creation | The same scenario passed again at 2.449 seconds, with complete details for both candidate agents. |
Comparison branch :- https://github.com/Expensify/App/compare/6d42ea040fb11d2f82aabe64548f4665589a9675...KJ21-ENG:4143d88b97b37abf5dce26cd43d6b72fec4b70a4
cc: @carlosmiceli @huult @getusha
| Before | After |
|---|---|
| Watch recording | Watch recording |
@MelvinBot after applying your fix the agent preview no longer gets updated. can you investigate why?
You're right, and my proposal was wrong. resolveAgentAccountID() on the read path can't work, because AgentAccountIDMapping is not a reactive store — so the screen resolves once, at mount, and never again. If it mounted before the mapping registered, it stays subscribed to the optimistic keys forever while every write goes to the real ones. That's the preview going dead.
Why it breaks
1. Nothing re-renders the screen when the mapping registers. resolveAgentAccountID() is a bare read of a module-level Map with no subscribe mechanism (src/libs/AgentAccountIDMapping.ts:9-17). registerAgentAccountIDMapping() mutates it without touching Onyx or React state.
The re-render I assumed would rescue it doesn't happen. useOnyx(PERSONAL_DETAILS_LIST, {selector: (list) => list?.[accountID]}) gates updates on shouldUpdateResult = !areValuesEqual, using memoizedShallowEqual on the selector output. A screen pointing at a dead optimistic ID selects undefined before and after the cleanup, so Onyx suppresses the render. Neither "the real entry appeared" nor "the optimistic entry was deleted" wakes it.
2. Meanwhile the writes have already moved. updateAgentName / updateAgentPrompt / updateAgentAvatar / deleteAgent all resolve internally (Agent.ts:204, :244, :285, :351). So edits land on sharedNVP_agentPrompt_<real> and personalDetailsList[real] — keys the frozen screen isn't watching. Change the prompt, come back, preview shows the old text.
3. React Compiler makes it permanent. The compiler runs on all of src/ (babel.config.js:35) with no compilationMode override and no "use no memo" anywhere. const accountID = resolveAgentAccountID(route.params.accountID) is an imported non-hook call whose result escapes into hooks and JSX, so it gets a memo slot keyed on route.params.accountID — which never changes on a route the sweep missed. The call is skipped on every subsequent render.
The other half: even a correct re-resolve would swap onto empty keys
The mapping is registered in the middleware at ReplaceOptimisticAgentAccountID.ts:144, which is ordered before SaveResponseInOnyx (register.ts:63 vs :82). And because CreateAgent is a WRITE, its response onyxData is deferred until the sequential queue drains (OnyxUpdates.ts:62) — the module doc at replaceOptimisticAgentWithActualAgent.ts:24-26 says as much.
So for that whole window resolve(optimistic) === real while the real keys hold nothing but whatever deltas the resolved write actions merged. A screen that re-resolved there would read agent === undefined and personalDetails === undefined, both metadata statuses would go loaded, and EditAgentPage.tsx:52-53 would render NotFoundPage — the exact flash the redirect-before-clear ordering at :113-122 exists to prevent.
Two smaller consequences of a read-side resolve, worth knowing if you keep any of it:
- Destructive rollbacks. The Fields pages pass the pre-edit value they read as
originalFirstName/originalPrompt/currentAvatar. Read from an empty real key, those become''/undefined, and a failed request rolls the agent's name or prompt back to blank (Agent.ts:226-237,:262-268). - Duplicate Edit screens.
Navigation.goBack(ROUTES.SETTINGS_AGENTS_EDIT.getRoute(accountID))atEditNamePage.tsx:38matches on name and params (compareParams: true). A resolved real-ID fallback won't match the stack's optimistic-ID Edit route, so it REPLACEs instead of popping, leaving two Edit screens.
What to do instead
The read path needs a reactive source and complete data. Two changes, and they're independent:
- Make the mapping subscribable. Either keep the optimistic→real entry in
ONYXKEYS.OPTIMISTIC_AGENT_ACCOUNT_ID_MAPPINGinstead of clearing it and read it withuseOnyx, or giveAgentAccountIDMappinga listener set and exposeuseAgentAccountID()viauseSyncExternalStore— the existing precedent isAgentZeroReasoningStore.tsconsumed atuseAgentZeroStatusIndicator.ts:212, whose comment cites React Compiler correctness for exactly this reason. A bare function call in render will not survive the compiler. - Migrate the data, don't just delete it. When the mapping is registered, copy
personalDetailsList[optimistic]andsharedNVP_agentPrompt_<optimistic>onto the real keys, then delete the optimistic ones — instead of deleting at flush time and leaving the real keys empty in between. Otherwise a correctly-reactive resolve still lands on nothing and 404s.
KJ21-ENG's proposal has the right shape for (1) — retained Onyx mapping plus a reactive useAgentAccountID hook — and its step 4 (wait for the subscriptions to load before deciding not-found) partly covers (2). Worth checking there that loaded + empty real keys during the queue-drain window doesn't still fall through to NotFoundPage.
Confidence: points 1 and 2 are confirmed from the source (I read the shouldUpdateResult / memoizedShallowEqual gate in react-native-onyx's useOnyx and the middleware ordering directly). Point 3 is traced from the installed compiler's caching semantics but I couldn't execute a Babel run in this environment to show the emitted memo block — npm run react-compiler-compliance-check check --verbose src/pages/settings/Agents/EditAgentPage.tsx on your patched file will confirm it.
Sorry for the bad steer — my original proposal treated the sweep's timing as the only problem and missed that the mapping has no way to notify React.
view run · no recording available
:sos: C+ Help Wanted
Proposal
What is the root cause of that problem?
A freshly created agent lives under a client-generated optimistic accountID (Agent.ts:51) until CreateAgent responds. The response writes the real PERSONAL_DETAILS_LIST[realID] and SHARED_NVP_AGENT_PROMPT_<realID>, sets the optimistic→real mapping, and that mapping fires replaceOptimisticAgentWithActualAgent, which does three things in order:
- registers an in-memory optimistic→real map (
replaceOptimisticAgentWithActualAgent.ts:105), - one-shot walks the current nav state and
setParams-rewrites the id on any already-open agent screen (:56-76), - deletes the optimistic personal-detail and prompt keys (
:120-122).
EditAgentPage is the screen that renders the reported "Hmm... it's not here". It reads the route param raw and 404s once both keys resolve to nothing (EditAgentPage.tsx:44, :52-53):
const accountID = route.params.accountID;
const shouldShowNotFoundPage = isOnyxLoaded && !agent && !personalDetails;
The step-2 rewrite is the only thing repairing an open screen, and it walks the nav state at a single instant. It can't touch a navigation that begins after it has run. That is exactly the reported flow: you create the agent, the response lands (register + delete both fire), and then you tap the Agents-list row — whose navigate target still carries the optimistic id (AgentsPage.tsx:111) because the row hasn't re-rendered off the Onyx deletion yet. EditAgentPage mounts on a dead optimistic id, both keys are already gone, and nothing re-runs the sweep → permanent 404. (The mirror case — opening the screen before the response — is already handled: the screen is in the nav state when the sweep runs, so step 2 rewrites its param. That's why this can't be fixed inside the sweep.)
The infrastructure to recover was already built and is sitting unused on the read side. AgentAccountIDMapping.ts keeps a session map whose own docblock says it exists so "a late caller (e.g. an agent settings screen opened before the redirect) can still translate an optimistic accountID" (:1-17). But resolveAgentAccountID is only ever called by the four write actions in Agent.ts (e.g. :204) — no read path calls it, so the screen has no way to translate the dead id.
What changes do you think we should make in order to solve the problem?
Fix layer: read. Resolve the optimistic id where the screen consumes it, so a page holding a dead id finds the real agent no matter when it opened. In EditAgentPage.tsx:44:
// import {resolveAgentAccountID} from '@libs/AgentAccountIDMapping';
const accountID = resolveAgentAccountID(route.params.accountID);
That one line fixes the reported 404. The three sibling field screens read the param raw the same way (EditNamePage.tsx:31, EditPromptPage.tsx:44, EditAgentAvatarPage) and would render stale/empty in the same window — they have no 404 gate, so they're lower priority, but the same one-liner keeps them consistent. Since these are the exact four routes the sweep already enumerates in AGENT_SETTINGS_SCREENS, I'd expose it as a tiny useAgentAccountID(routeAccountID) hook so the resolve stays in one place and both React Compilers treat it identically (a module-level Map read belongs in a hook, not inline in render).
Why this is race-free, not race-narrowing: the map is registered at :105 strictly before the deletes at :120-122, and it's never cleared for the session. There is no ordering in which the page can observe the deleted keys without also being able to resolve to the real id — the re-render caused by the deletion is already the render that resolves to real. Keep the sweep as-is; it still repairs the visible URL for open screens. This change just stops its timing from being load-bearing.
Verification. I traced this against the existing tests/unit/pages/settings/EditAgentPageTest.tsx harness (8 tests). None of them mock resolveAgentAccountID, so the resolve-on-read change leaves all 8 green (a map miss returns the id unchanged). The regression test that fails on main and passes with the patch:
import {registerAgentAccountIDMapping} from '@libs/AgentAccountIDMapping';
it('resolves an optimistic accountID to the reconciled agent instead of 404', () => {
const OPTIMISTIC_ID = 987654321;
const REAL_ID = 12345;
registerAgentAccountIDMapping(OPTIMISTIC_ID, REAL_ID);
const route = createMock<EditAgentPageRoute>({params: {accountID: OPTIMISTIC_ID}});
mockUseOnyx.mockImplementation((key, options) => {
if (key === `${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}${REAL_ID}`) {
return [{prompt: 'Reconciled'}, {status: 'loaded'}];
}
if (key === ONYXKEYS.PERSONAL_DETAILS_LIST && options?.selector) {
return [options.selector({[REAL_ID]: {displayName: 'Reconciled Agent'}}), {status: 'loaded'}];
}
return [undefined, {status: 'loaded'}]; // optimistic keys already cleared
});
const out = JSON.stringify(render(<EditAgentPage route={route} navigation={mockNavigation} />).toJSON());
expect(out).not.toContain('notFound.notHere');
expect(out).toContain('Reconciled Agent');
});
On main the page uses OPTIMISTIC_ID, the selector returns undefined for both keys, and it 404s; with the patch it resolves to REAL_ID and renders. I couldn't execute jest in my environment (Node 26, jest not installed here), so these pass/fail claims are reasoned from the mock structure above rather than a live run — the test is written to drop straight into that file.
What alternative solutions did you explore? (Optional)
- Make the sweep wait for the in-flight navigation (
waitForUpcomingTransitiononrunAfterTransitionsat:111). Rejected: it's still one-shot, so it can't reach a tap that happens after it runs — the reported case — and it does nothing for a deep link intosettings/agents/<optimisticID>/edit. - Stop deleting the optimistic keys (leave them and dedupe). Rejected:
AgentsPagebuilds its rows straight off the prompt collection (:81-117) with no dedupe, so you'd get two rows for one agent. - Migrate the optimistic Onyx data onto the real keys instead of deleting. Rejected, and the module documents why: the mapping is flushed only after the queue drains, so any state still on the optimistic keys is stale — migrating it would resurrect stale data. Resolving on read sidesteps this by leaning on the server's real keys, which already exist by the time the delete fires.
Proposal
Please re-state the problem that we are trying to solve in this issue.
Right after creating an agent (Account → Agents → New Agent → create), if you quickly open the newly-created agent's Edit page, the "Hmm... it's not here" not-found view is shown instead of the Edit Agent page.
What is the root cause of that problem?
A new agent is stored under a client-generated optimistic accountID because only the server can assign the real one. createAgent writes the optimistic personal detail and the SHARED_NVP_AGENT_PROMPT{optimisticAccountID} prompt, and the SETTINGS_AGENTS_EDIT route the agents list navigates to is built with that optimistic accountID:
https://github.com/Expensify/App/blob/8742c87bd3d7d7257daf0e43876e588831abea36/src/libs/actions/Agent.ts#L51
https://github.com/Expensify/App/blob/8742c87bd3d7d7257daf0e43876e588831abea36/src/pages/settings/Agents/AgentsPage.tsx#L119
When CreateAgent responds, replaceOptimisticAgentWithActualAgent reconciles it: it redirects any already-open agent settings screen to the real accountID (via Navigation.setParams) and then clears the optimistic personal detail and SHARED_NVP_AGENT_PROMPT{optimisticAccountID}. The redirect deliberately runs before the clear so an open screen doesn't flash its not-found view:
https://github.com/Expensify/App/blob/8742c87bd3d7d7257daf0e43876e588831abea36/src/libs/actions/replaceOptimisticAgentWithActualAgent.ts#L110-L125
The problem is that EditAgentPage reads Onyx directly from the raw, unresolved route.params.accountID and never translates the optimistic ID to the real one. Its not-found guard therefore depends entirely on that setParams redirect landing on this exact screen in time:
https://github.com/Expensify/App/blob/8742c87bd3d7d7257daf0e43876e588831abea36/src/pages/settings/Agents/EditAgentPage.tsx#L44-L53
This loses the "quickly open" race. When the response is reconciled around the moment the screen opens, the optimistic keys get cleared, but this screen's accountID param can still hold the now-dead optimistic ID — either because the screen mounted after the redirect already swept the navigation tree (so it was never redirected), or because the async Onyx clear reaches the component before the navigation param update does. Both agent and personalDetails then read empty for a key that no longer exists, isOnyxLoaded is true, and the not-found page renders:
https://github.com/Expensify/App/blob/8742c87bd3d7d7257daf0e43876e588831abea36/src/pages/settings/Agents/EditAgentPage.tsx#L88-L90
Note that every mutating action in Agent.ts (updateAgentName, updateAgentPrompt, updateAgentAvatar, deleteAgent) already guards against exactly this by calling resolveAgentAccountID(accountID) — but the read side in EditAgentPage does not. The in-memory mapping exists precisely for this case ("a late caller … an agent settings screen … can still translate an optimistic accountID"), and it is populated synchronously the moment the response arrives, before any optimistic data is cleared:
https://github.com/Expensify/App/blob/8742c87bd3d7d7257daf0e43876e588831abea36/src/libs/AgentAccountIDMapping.ts#L1-L17
What changes do you think we should make in order to solve the problem?
Make EditAgentPage resolve the optimistic accountID through the existing resolveAgentAccountID helper (mirroring the action files), and use the resolved ID for the Onyx reads, the not-found decision, and the navigations to the sub-screens. Because registerAgentAccountIDMapping runs synchronously when the response arrives — before the optimistic keys are cleared — the resolved read always points at the real, still-present keys. This closes the race independently of the setParams redirect timing: even if the redirect never lands, the Onyx clear that triggers a re-render will now resolve to the real ID and render the Edit page. It also propagates the real accountID into the EDIT_NAME / EDIT_PROMPT / EDIT_AVATAR sub-screens (which read the raw param too), so they benefit from the same translation.
https://github.com/Expensify/App/blob/8742c87bd3d7d7257daf0e43876e588831abea36/src/pages/settings/Agents/EditAgentPage.tsx#L44
Add the import:
import {resolveAgentAccountID} from '@libs/AgentAccountIDMapping';
Resolve the param:
const accountID = resolveAgentAccountID(route.params.accountID);
All existing usages (agent/personalDetails reads, shouldShowNotFoundPage, and the handleEdit*Press navigations) keep referencing accountID unchanged and now transparently use the resolved value.
For full consistency, the same one-line resolve can be applied to EditNamePage and EditPromptPage (and the edit-avatar page), which likewise build their Onyx reads from route.params.accountID, so a directly-deep-linked or slow-reconciling sub-screen reads the correct agent as well.
Proposal
Please re-state the problem that we are trying to solve in this issue.
Right after creating a new agent, opening that agent from Account → Agents shows the "Hmm... it's not here" not-found page instead of the Edit Agent page.
What is the root cause of that problem?
A new agent is first stored under a client-generated optimistic accountID, because only the server can assign the real one. When CreateAgent responds, the server returns an optimistic-to-real accountID mapping, and the app repairs everything that still points at the optimistic ID.
That repair is push-only and one-shot. When the mapping is consumed, redirectAgentSettingsScreens() walks the current navigation state and rewrites the accountID param of any agent settings route that happens to be mounted at that instant, and then immediately deletes the optimistic personal detail and agent prompt from Onyx:
https://github.com/Expensify/App/blob/a68e6f4f69027e719edd4a20641475873c85bc92/src/libs/actions/replaceOptimisticAgentWithActualAgent.ts#L110-L125
The Edit Agent screen itself never translates its own route param. It reads Onyx straight from route.params.accountID and shows the not-found page as soon as both subscriptions resolve empty:
https://github.com/Expensify/App/blob/a68e6f4f69027e719edd4a20641475873c85bc92/src/pages/settings/Agents/EditAgentPage.tsx#L44-L53
So the screen is only ever correct if it was already in the navigation state when the sweep ran. Opening it quickly after creation loses that race: the agents list row captures the optimistic accountID in its action callback at render time:
https://github.com/Expensify/App/blob/a68e6f4f69027e719edd4a20641475873c85bc92/src/pages/settings/Agents/AgentsPage.tsx#L119
If the mapping is consumed in the window between that tap and the Edit Agent screen entering the navigation state, the sweep finds no route to rewrite, the optimistic keys are deleted, and the screen then mounts against an accountID that no longer exists in Onyx — agent and personalDetails are both empty, shouldShowNotFoundPage becomes true, and the user sees "Hmm... it's not here". Waiting a moment before tapping avoids the window, which is exactly why the bug is described as happening only when opening the agent quickly.
The translation helper that would fix this already exists, and its own documentation says it is meant for "an agent settings screen opened before the redirect" — but no screen actually calls it; today only the write actions in Agent.ts do:
https://github.com/Expensify/App/blob/a68e6f4f69027e719edd4a20641475873c85bc92/src/libs/AgentAccountIDMapping.ts#L1-L19
What changes do you think we should make in order to solve the problem?
Make the Edit Agent screen resolve its own accountID instead of relying purely on the navigation sweep, so it is correct no matter when it mounts.
In EditAgentPage, pass the route's accountID through resolveAgentAccountID() from AgentAccountIDMapping and use that resolved value for the Onyx subscriptions and for everything derived from them. Because the mapping is registered in memory as soon as the CreateAgent response is handled — before the optimistic Onyx keys are cleared — a screen that mounts after the sweep now reads the real agent's data rather than the deleted optimistic keys. For a screen that mounts before the response arrives nothing changes: the optimistic ID is not in the map yet, so it resolves to itself, renders the optimistic data as it does today, and the existing redirectAgentSettingsScreens() param rewrite still corrects it. The two mechanisms together cover the whole window, and the call is idempotent — a real accountID is not in the map and resolves to itself.
We should also stop the not-found page from firing while an accountID is mid-translation. Extend the shouldShowNotFoundPage condition so it only triggers when the route's accountID resolves to itself. When the route param is a known optimistic ID whose real record has not been written to Onyx yet, the agent is guaranteed to arrive from the same response, so the screen should keep showing its normal content while the data lands instead of flashing the not-found view.
The same route param is read by the agent name, prompt and avatar screens, which are reachable from the Edit Agent page and by deep link, so they should resolve their accountID the same way for consistency:
https://github.com/Expensify/App/blob/a68e6f4f69027e719edd4a20641475873c85bc92/src/pages/settings/Agents/Fields/EditNamePage.tsx#L31-L32
https://github.com/Expensify/App/blob/a68e6f4f69027e719edd4a20641475873c85bc92/src/pages/settings/Agents/Fields/EditPromptPage.tsx#L44-L45
https://github.com/Expensify/App/blob/a68e6f4f69027e719edd4a20641475873c85bc92/src/pages/settings/Agents/Fields/EditAgentAvatarPage.tsx#L236-L240
Compare branch: https://github.com/Expensify/App/compare/main...wildan-m:App:wildan/100865-resolve-agent-accountid?expand=1
What alternative solutions did you explore? (Optional)
Disabling the agent row in the list until the create request settles would also close the window, but it makes a newly created agent unusable for as long as the request takes and does not help a deep link or a back navigation that lands on a stale optimistic ID.
Delaying the deletion of the optimistic Onyx keys (for example keeping them for a short grace period after the mapping is consumed) would hide the symptom, but it leaves two records for the same agent in the list for that period and only moves the race rather than removing it.
Unable to auto-create job on Upwork. The BZ team member should create it manually for this issue.
Proposal
Please re-state the problem that we are trying to solve in this issue.
Right after creating an agent, quickly opening that agent's Edit page shows "Hmm... it's not here" instead of the Edit Agent page.
What is the root cause of that problem?
A new agent lives under a client-generated optimistic accountID until CreateAgent responds, because only the server can assign the real one:
https://github.com/Expensify/App/blob/d22a64c95bbc300ec70f1514ace4c6e963bc0081/src/libs/actions/Agent.ts#L51
The success response writes the real personalDetailsList[real] and sharedNVP_agentPrompt_<real>, plus an optimistic to real entry on OPTIMISTIC_AGENT_ACCOUNT_ID_MAPPING. replaceOptimisticAgentWithActualAgent listens to that mapping and, for each entry, registers an in-memory optimistic to real map, sweeps the navigation state to rewrite the accountID param of any open agent screen, then deletes the optimistic personal detail and prompt and nulls the consumed entry:
https://github.com/Expensify/App/blob/d22a64c95bbc300ec70f1514ace4c6e963bc0081/src/libs/actions/replaceOptimisticAgentWithActualAgent.ts#L110-L125
The reported failure is cross-tab, not a same-tab timing race. Only the leader tab processes the request queue:
https://github.com/Expensify/App/blob/d22a64c95bbc300ec70f1514ace4c6e963bc0081/src/libs/Network/SequentialQueue.ts#L622-L625
So the response, the middleware registration, and the whole register plus sweep plus delete sequence all run in the leader tab:
https://github.com/Expensify/App/blob/d22a64c95bbc300ec70f1514ace4c6e963bc0081/src/libs/Middleware/ReplaceOptimisticAgentAccountID.ts#L141-L144
When a different tab has the Edit screen open, that tab is a follower. It never runs any of the above and learns about the change only through Onyx cross-tab sync. That sync does not carry values, it signals key names, coalesces every key signaled in a tick into one setTimeout(0), then re-reads the current value of each key with a single multiGet:
https://github.com/Expensify/react-native-onyx/blob/3.0.111/lib/storage/InstanceSync/index.web.ts#L105-L128
The leader writes the mapping entry {opt: real} at the response flush and nulls it {opt: null} in the cleanup callback within the same macrotask. So the follower coalesces both writes into one re-read and reads the final value {opt: null}: the mapping's useful value is transient and gets dropped. The optimistic-data deletions, by contrast, are the final state (null) and arrive reliably.
The follower's mapping callback therefore fires with {opt: null}, hits the "already consumed, skip" branch, and never registers the mapping and never runs the sweep:
https://github.com/Expensify/App/blob/d22a64c95bbc300ec70f1514ace4c6e963bc0081/src/libs/actions/replaceOptimisticAgentWithActualAgent.ts#L130-L146
Its Edit route keeps the dead optimistic ID, but the optimistic keys it reads are now gone, so EditAgentPage renders the not-found page:
https://github.com/Expensify/App/blob/d22a64c95bbc300ec70f1514ace4c6e963bc0081/src/pages/settings/Agents/EditAgentPage.tsx#L44-L53
const accountID = route.params.accountID;
const [agent, agentMetadata] = useOnyx(`${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}${accountID}`);
const [personalDetails, personalDetailsMetadata] = useOnyx(ONYXKEYS.PERSONAL_DETAILS_LIST, {selector: (list) => list?.[accountID]});
const shouldShowNotFoundPage = isOnyxLoaded && !agent && !personalDetails;
The reported video proves the cross-tab path, frame by frame. The Edit page renders the full agent for about 5 seconds at .../settings/agents/1064214986992105/edit (a 16-digit optimistic ID), then flips to "Hmm... it's not here" at the exact frame the Agents list in the background populates the real row, and the URL never changes. The sweep walks the whole nav state and rewrites any mounted agent route whose param matches the optimistic ID:
https://github.com/Expensify/App/blob/d22a64c95bbc300ec70f1514ace4c6e963bc0081/src/libs/actions/replaceOptimisticAgentWithActualAgent.ts#L56-L76
That screen is mounted (it is rendering the agent) and its param is the optimistic ID (it is in the URL), so a same-tab sweep would have matched it and changed the URL to the real ID. The optimistic data getting cleared with no URL rewrite is only possible if the sweep ran in another tab. That is the signature of the follower receiving the deletion over cross-tab sync while never receiving the mapping. Opening the agent slowly avoids it because the Agents list row already carries the real ID by then, which is why the bug only shows when opening "quickly".
Why resolving on the read path cannot fix this. An earlier version of this proposal, and several others here, passed route.params.accountID through resolveAgentAccountID. That does not work, for two independent reasons:
https://github.com/Expensify/App/blob/d22a64c95bbc300ec70f1514ace4c6e963bc0081/src/libs/AgentAccountIDMapping.ts#L9-L17
- The helper reads a per-tab in-memory
Map. The failing tab never callsregisterAgentAccountIDMapping(its mapping callback gotnull), so that map is empty there and the resolve returns the optimistic ID unchanged. The one thing that could recover the ID is exactly what cross-tab sync starved. - Even inside a single tab it fails, which is the "agent preview stops updating" regression already reported on the read-side fix: the map is not reactive, so a screen mounted before the mapping registers never re-renders to pick up the real ID and stays subscribed to the dead keys, and during the queue-drain window
resolve(opt) === realwhile the real keys are still empty, so it 404-flashes anyway.
What changes do you think we should make in order to solve the problem?
The repair mechanism already exists and is correct: redirectAgentSettingsScreens running per tab is exactly what fixes an open Edit screen. The only reason the follower stays broken is that it never receives the mapping to act on. So fix the delivery, not the read path, entirely inside replaceOptimisticAgentWithActualAgent.ts:
-
Stop nulling the live mapping entry the instant it is consumed. Keep
{opt: real}inOPTIMISTIC_AGENT_ACCOUNT_ID_MAPPINGso a follower's cross-tab re-read reliably observes it, runs its ownregisterAgentAccountIDMappingplus sweep, and rewrites its Edit route to the real ID. The follower already received the realpersonalDetailsList[real]andsharedNVP_agentPrompt_<real>from the same response, so the moment its route resolves to the real ID the page reads populated keys. The existing "redirect before clear" ordering keeps it flash-free. -
Guard re-processing with a module-level
Setof already-replaced optimistic IDs. The callback now fires again whenever the retained entry is re-signaled, so skip an ID already handled in this tab. The redirect and the deletes are idempotent, but the guard avoids re-walking the nav state on every mapping write. -
Clear the entry only for the startup-persisted case. The module already consumes a leftover entry on app start:
https://github.com/Expensify/App/blob/d22a64c95bbc300ec70f1514ace4c6e963bc0081/src/libs/actions/replaceOptimisticAgentWithActualAgent.ts#L128-L146
Keep nulling it there, so a stale reloaded .../agents/<optimisticID>/edit URL is still repaired and the mapping does not grow across sessions, while live entries stay available to every tab open right now.
No data migration is needed, and the module documents why copying optimistic data onto the real keys is wrong (it is stale by flush time):
https://github.com/Expensify/App/blob/d22a64c95bbc300ec70f1514ace4c6e963bc0081/src/libs/actions/replaceOptimisticAgentWithActualAgent.ts#L24-L26
We do not need it: the server's real keys already reach the follower over the same sync, so retaining the identity mapping alone is enough for the follower's sweep to point the screen at data that is already there.
Regression test: with two clients, have the leader process CreateAgent while a follower holds EditAgentPage open on the optimistic ID, and assert the follower's route is redirected to the real ID and renders the agent (never NotFoundPage). Add coverage that a retained live entry is not re-processed (the Set guard) and that a startup-persisted entry is consumed and then cleared.
What alternative solutions did you explore? (Optional)
- Resolve
route.params.accountIDthroughresolveAgentAccountIDinEditAgentPage(the shape most proposals here share, including an earlier version of this one). Refuted above: the failing tab never registers the mapping, so its map is empty and the resolve is a no-op, and even same-tab the map is non-reactive and hits the empty-real-keys queue-drain window, which is the preview-not-updating regression. - Retain the mapping in Onyx and subscribe to it from a reactive
useAgentAccountIDhook in the four agent screens. It works, but it copies the resolve into four components, needs a loading gate so the queue-drain window does not 404, and needs route rewriting so Save and Back do not stack a second Edit screen. Keeping the single existing sweep as the only repair path is smaller and sidesteps those edges, since the sweep already rewrites the route param for every open agent screen in one place. waitForUpcomingTransitionon the sweep. Does nothing here: the failing tab has no in-flight navigation to wait for and never runs the sweep at all.- Stop deleting the optimistic keys, or disable the list row while the create is pending. Rejected:
AgentsPagehas no dedupe so retained keys show two rows, and blocking the row regresses the offline-first flow for a window that only lasts a moment.
Proposal
Please re-state the problem that we are trying to solve in this issue.
Create an agent, then click the new row in Settings > Agents right away: the Edit Agent page shows "Hmm... it's not here". Waiting a second works.
What is the root cause of that problem?
A new agent lives under a optimistic accountID until CreateAgent returns the real one:
https://github.com/Expensify/App/blob/a18f525f93d9f87a44f41a0793816cd1bc3f059e/src/libs/actions/Agent.ts#L51
When the response lands, replaceOptimisticAgentWithActualAgent repairs any screen already sitting on that ID, then deletes the optimistic personalDetailsList entry and sharedNVP_agentPrompt_<optimisticID>:
https://github.com/Expensify/App/blob/a18f525f93d9f87a44f41a0793816cd1bc3f059e/src/libs/actions/replaceOptimisticAgentWithActualAgent.ts#L111-L123
That repair is a one-shot walk of navigationRef.getRootState() at a single instant — nothing re-runs it:
https://github.com/Expensify/App/blob/a18f525f93d9f87a44f41a0793816cd1bc3f059e/src/libs/actions/replaceOptimisticAgentWithActualAgent.ts#L56-L76
So the ID survives only for routes in the nav state at that instant; anything else holding it is left pointing at two deleted keys. Here that "anything else" is the Agents list row: its action closure captures the accountID it rendered with, and the deletes are async Onyx.merge calls, so between the sweep and the list's re-render the row is still on screen and still navigates to the dead ID:
https://github.com/Expensify/App/blob/a18f525f93d9f87a44f41a0793816cd1bc3f059e/src/pages/settings/Agents/AgentsPage.tsx#L89-L119
That window is wide open on wide layouts (Windows Chrome, the reported platform): AddAgentPage opens the agent DM with forceReplace in a dedicated RHP, so the Agents list stays mounted and clickable in the central pane, scrolled to and highlighting the new row:
https://github.com/Expensify/App/blob/a18f525f93d9f87a44f41a0793816cd1bc3f059e/src/pages/settings/Agents/AddAgentPage.tsx#L151-L161
EditAgentPage reads the route param raw, both useOnyx subscriptions settle as loaded with no value, and the not-found page renders:
https://github.com/Expensify/App/blob/a18f525f93d9f87a44f41a0793816cd1bc3f059e/src/pages/settings/Agents/EditAgentPage.tsx#L44-L53
Structurally: the navigation sweep is the only translation step, and it is a snapshot. The codebase already has the non-snapshot half — an in-memory optimistic→real map whose own docblock says it exists so "a late caller (e.g. an agent settings screen opened before the redirect) can still translate an optimistic accountID":
https://github.com/Expensify/App/blob/a18f525f93d9f87a44f41a0793816cd1bc3f059e/src/libs/AgentAccountIDMapping.ts#L1-L17
…but no read path calls resolveAgentAccountID. Only the four write actions in Agent.ts do (lines 204/244/285/351). The map is filled in the API middleware at response-processing time, strictly before the Onyx flush and therefore before any delete can run:
https://github.com/Expensify/App/blob/a18f525f93d9f87a44f41a0793816cd1bc3f059e/src/libs/Middleware/ReplaceOptimisticAgentAccountID.ts#L138-L144
So when the Edit page mounts on a dead ID the correct ID is already in memory — the page never asks for it. That explains every detail: the click must be quick (the row must still be the optimistic one), it is layout-dependent, and waiting fixes it (the list re-renders onto the real row).
What changes do you think we should make in order to solve the problem?
Translate the accountID on the read path, exactly as the write actions already do. One line, one file — EditAgentPage.tsx#L44:
const accountID = resolveAgentAccountID(route.params.accountID);
On mount resolveAgentAccountID returns the real accountID (the middleware registered it before the deletes), both Onyx keys resolve, and shouldShowNotFoundPage is false. Regression safety: the sweep is untouched, and a non-optimistic ID passes through the map unchanged (consumedOptimisticAccountIDs.get(accountID) ?? accountID), so every existing agent behaves identically.
Is the one-liner enough? Yes — and I'd argue against anything larger. Substituting the repro: map populated at T−RTT, sweep at T±ε, click at T. The page mounts after the click, so the resolve runs after registration in every ordering that produces the bug — which is why no reactive subscription to the map is needed. What it does not fix: the browser URL still shows the optimistic ID, so a hard reload of it 404s — out of scope, and already the sweep's job.
Secondary (optional, not needed for this repro): three sibling screens read the param raw with no not-found guard and would render an empty form on the same dead ID — Fields/EditNamePage.tsx#L31, Fields/EditPromptPage.tsx#L44, Fields/EditAgentAvatarPage.tsx#L236, reachable from ProfilePage.tsx#L319. Same one-line change; the reported repro never reaches them.
What alternative solutions did you explore? (Optional)
Pass waitForUpcomingTransition: 'navigation' to runAfterTransitions at replaceOptimisticAgentWithActualAgent.ts#L111 so the sweep waits for an in-flight push. Rejected: it only helps when the click lands before the sweep. It does nothing on the path that fails here — a click landing after the sweep deleted the keys but before the list re-renders, where there is no upcoming transition to wait for. It also costs: MAX_TRANSITION_START_WAIT_MS is 1000ms, so every creation keeps the optimistic personal detail and prompt alive for up to a second, and AgentsPage has no dedupe — the list would show the optimistic row and the real row together for that whole window.
Stop deleting the optimistic keys. Rejected: the same duplicate-row problem, permanently.
Disable the row until CreateAgent resolves. Rejected: it breaks the offline-first behaviour the flow is built on, to guard a few hundred milliseconds.
🤖 ProposalPolice™ is tracking duplicate proposals for this issue using an OpenAI Conversation. This comment stores that Conversation's ID and can be safely ignored.
Proposal
What is the root cause of that problem?
The Agents feature sits behind the CUSTOM_AGENT beta (AgentsPage.tsx:58). Creating an agent is a pure optimistic write: createAgent() in src/libs/actions/Agent.ts:39-115 generates a placeholder ID with Number(generateReportID()) (line 47), a random number, not the deterministic generateAccountID(email) hash this codebase uses elsewhere for a known login (see src/libs/actions/Domain.ts:887, addMemberToDomain). It has to be random because the agent's login is server-assigned, not chosen by the user (Agent.ts:56, "Omit login (server-assigned)"). That's also why CreateAgentParams.optimisticAccountID (src/libs/API/parameters/CreateAgentParams.ts:9) is sent to the server at all, and why the project's own test for it is titled "passes the optimistic accountID through to the server so it can echo a real-ID mapping" (tests/unit/AgentActionTest.ts:265-269).
When CREATE_AGENT succeeds, successData wipes the placeholder entirely (Agent.ts:77-88):
const successData: AnyOnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.PERSONAL_DETAILS_LIST,
value: {[optimisticAccountID]: null},
},
{
onyxMethod: Onyx.METHOD.MERGE,
key: `${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}${optimisticAccountID}`,
value: null,
},
];
This is intentional. The project's own passing test is literally titled "success data nulls out both optimistic entries" (AgentActionTest.ts:253-263), and it has to happen once the real record lands somewhere else. The gap is that nothing stops the row pointing at that placeholder ID from being opened while this is in flight. AgentsPage.tsx only disables a row for a pending delete:
AgentsPage.tsx:93-94:
const pendingAction = agentPrompt?.pendingAction;
const isPendingDeletion = pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE;
AgentsPage.tsx:116-117:
disabled: isPendingDeletion,
action: () => Navigation.navigate(ROUTES.SETTINGS_AGENTS_EDIT.getRoute(accountID)),
A row whose pendingAction is ADD, meaning the agent was just created and CREATE_AGENT hasn't resolved yet or has just resolved, is fully clickable. The dedicated Edit button in AgentsTableRow.tsx:124-132 has the identical gap: it's disabled on isPendingDeletion only, while the Chat and Copilot buttons a few lines above it in the same file are already correctly gated by areActionsDisabled, which does cover the ADD case (AgentsTableRow.tsx:45-47):
const isPendingDeletion = item.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE;
const isPendingAddOrDelete = item.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD || isPendingDeletion;
const areActionsDisabled = isPendingAddOrDelete || item.accountID <= 0 || !item.login;
So tapping the row, or the Edit button, for a just-created agent navigates to EditAgentPage with route.params.accountID set to the placeholder ID. EditAgentPage.tsx:42-51 reads that param directly:
const accountID = route.params.accountID;
const [agent, agentMetadata] = useOnyx(`${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}${accountID}`);
const [personalDetails, personalDetailsMetadata] = useOnyx(ONYXKEYS.PERSONAL_DETAILS_LIST, {selector: (list) => list?.[accountID]});
const shouldShowNotFoundPage = isOnyxLoaded && !agent && !personalDetails;
Once successData clears the placeholder, which is exactly what "quickly" opening a just-created agent races against, both agent and personalDetails resolve empty for that ID and the page falls straight to NotFoundPage, "Hmm... it's not here." There's no fallback or redirect for this in EditAgentPage.tsx, and no listener comparable to src/libs/actions/replaceOptimisticReportWithActualReport.ts (which this codebase already uses to redirect a user off an optimistic report ID once the server assigns a different real one) exists for agents. A failed CREATE_AGENT isn't the cause: failureData (Agent.ts:90-105) keeps the placeholder row, with an error, so the Edit page still renders fine in that case.
What changes do you think we should make in order to solve the problem?
The row and its Edit button need to stay non-interactive while the agent is still unconfirmed, the same way this code already gates Chat and Copilot.
In src/pages/settings/Agents/AgentsPage.tsx, compute the ADD case alongside the existing delete one and use it for disabled:
const pendingAction = agentPrompt?.pendingAction;
const isPendingDeletion = pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE;
const isPendingAddOrDelete = pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD || isPendingDeletion;
and change line 116 from disabled: isPendingDeletion, to disabled: isPendingAddOrDelete,. Table.Row's press handler (src/components/Table/TableRow.tsx:188-191) already checks item.disabled before calling onPress, so this alone blocks the whole-row tap, including on narrow layout where the row is the only way to open an agent (the Chat/Copilot/Edit buttons are hidden there).
In src/components/Tables/AgentsTable/AgentsTableRow.tsx:127, change the Edit button's isDisabled={isPendingDeletion} to isDisabled={areActionsDisabled}, matching the Chat and Copilot buttons right above it (lines 107 and 117) instead of being the one action that skips the ADD check.
With both changes a newly created agent's row still shows up immediately, the optimistic UX is unchanged, but it isn't navigable until pendingAction clears. Since createAgent's successData deletes the placeholder outright on success, the row just disappears from the list at that point instead of ever being tappable while it points at data that's about to vanish. If CREATE_AGENT fails, pendingAction stays ADD (per failureData) and the row stays disabled, which also fixes an existing side issue: a failed, non-existent agent's row was previously still clickable into EditAgentPage.
For regression coverage, tests/unit/pages/settings/AgentsTableRowTest.tsx already has pressing the row navigates to the edit agent page (line 228) and pressing Edit button navigates to the edit agent page (line 270), both against a BASE_ITEM with no pendingAction. Add a sibling test that renders AgentsTableRow with item: {...BASE_ITEM, pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD}, fires fireEvent.press on both the row (getByLabelText('Test Agent, [email protected]')) and the Edit button (getByText('common.edit')), and asserts mockNavigate is never called either way. That test fails against the current code, since both presses call Navigation.navigate today regardless of pendingAction, and passes once the fix lands. On the AgentsPage.tsx side, tests/unit/pages/settings/AgentsPageTest.tsx can get a matching case: seed SHARED_NVP_AGENT_PROMPT for a test account with pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD and assert the resulting row's disabled is true.
What alternative solutions did you explore? (Optional)
I considered fixing this in EditAgentPage.tsx instead, treating a missing agent/personalDetails pair as a loading state rather than an immediate not-found. Dropped it because there's nothing to wait for at that point: createAgent's successData deletes the placeholder key outright rather than replacing it, so once the page is on that ID there's no data left for it to converge on. Closing the interactivity gate that lets a user reach a soon-to-be-deleted ID in the first place is the smaller, more direct change, and it matches the disabled-state pattern this same component already uses for its other two row actions.
Proposal updated — added compare branch with implementation.
Proposal
Please re-state the problem that we are trying to solve in this issue.
After creating a new agent, quickly opening that agent from the Agents list can land on the "Hmm... it's not here" page instead of the Edit Agent screen. The agent was created successfully, but the Edit page cannot find its Onyx data because the route still carries the client-generated optimistic accountID after that ID has already been reconciled to the server-assigned real one.
What is the root cause of that problem?
New agents are stored under a client-generated optimistic accountID until CreateAgent responds with the real one:
App/src/libs/actions/Agent.ts Lines 51 to 66 in a18f525f93d
const optimisticAccountID = Number(generateReportID());
...
// Optimistic row for Settings > Agents until CREATE_AGENT responds. Omit `login` (server-assigned).
const optimisticPersonalDetail = {
accountID: optimisticAccountID,
displayName: firstName,
isOptimisticPersonalDetail: true,
...(avatarURI ? {avatar: avatarURI, avatarThumbnail: avatarURI} : {}),
};
https://github.com/Expensify/App/blob/a18f525f93d9f87a44f41a0793816cd1bc3f059e/src/libs/actions/Agent.ts#L51-L66
When CreateAgent succeeds, replaceOptimisticAgentWithActualAgent registers an in-memory optimistic→real mapping, walks the navigation tree once to rewrite any already-open agent settings routes, then deletes the optimistic Onyx keys:
App/src/libs/actions/replaceOptimisticAgentWithActualAgent.ts Lines 95 to 125 in a18f525f93d
function replaceOptimisticAgentWithActualAgent(optimisticAccountID: number, realAccountID: number) {
...
registerAgentAccountIDMapping(optimisticAccountID, realAccountID);
Promise.all([reportsHydrationPromise, Navigation.isNavigationReady()]).then(() => {
TransitionTracker.runAfterTransitions({
callback: () => {
if (navigationRef.isReady()) {
redirectAgentSettingsScreens(optimisticAccountID, realAccountID);
}
remapReportParticipants(optimisticAccountID, realAccountID);
Onyx.merge(ONYXKEYS.PERSONAL_DETAILS_LIST, {[optimisticAccountID]: null});
Onyx.merge(`${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}${optimisticAccountID}`, null);
Onyx.merge(ONYXKEYS.OPTIMISTIC_AGENT_ACCOUNT_ID_MAPPING, {[optimisticAccountID]: null});
},
});
});
}
https://github.com/Expensify/App/blob/a18f525f93d9f87a44f41a0793816cd1bc3f059e/src/libs/actions/replaceOptimisticAgentWithActualAgent.ts#L95-L125
The redirect sweep is a one-shot snapshot of navigationRef.getRootState() at a single instant:
App/src/libs/actions/replaceOptimisticAgentWithActualAgent.ts Lines 56 to 76 in a18f525f93d
function redirectAgentSettingsScreens(optimisticAccountID: number, realAccountID: number) {
const statesToVisit: Array<NavigationState | PartialState<NavigationState>> = [navigationRef.getRootState()];
while (statesToVisit.length > 0) {
const state = statesToVisit.pop();
for (const route of state?.routes ?? []) {
const isOptimisticAgentRoute =
AGENT_SETTINGS_SCREENS.has(route.name) &&
!!route.params &&
typeof route.params === 'object' &&
'accountID' in route.params &&
Number(route.params.accountID) === optimisticAccountID;
if (isOptimisticAgentRoute && route.key) {
Navigation.setParams({accountID: realAccountID}, route.key, state?.key);
}
if (route.state) {
statesToVisit.push(route.state);
}
}
}
}
https://github.com/Expensify/App/blob/a18f525f93d9f87a44f41a0793816cd1bc3f059e/src/libs/actions/replaceOptimisticAgentWithActualAgent.ts#L56-L76
Nothing re-runs that sweep. If the Edit Agent route is pushed after the sweep (or is not yet committed to nav state when the sweep reads it), it keeps the dead optimistic ID. Immediately afterward the optimistic keys are deleted, so the screen has nothing to load.
EditAgentPage reads the route param raw and 404s as soon as both Onyx lookups resolve to nothing:
App/src/pages/settings/Agents/EditAgentPage.tsx Lines 44 to 53 in a18f525f93d
const accountID = route.params.accountID;
const [agent, agentMetadata] = useOnyx(`${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}${accountID}`);
const [personalDetails, personalDetailsMetadata] = useOnyx(ONYXKEYS.PERSONAL_DETAILS_LIST, {selector: (list) => list?.[accountID]});
...
const shouldShowNotFoundPage = isOnyxLoaded && !agent && !personalDetails;
https://github.com/Expensify/App/blob/a18f525f93d9f87a44f41a0793816cd1bc3f059e/src/pages/settings/Agents/EditAgentPage.tsx#L44-L53
The codebase already maintains an in-memory optimistic→real map for exactly this scenario — its docblock explicitly calls out "a late caller (e.g. an agent settings screen opened before the redirect)" — but no read path uses it:
App/src/libs/AgentAccountIDMapping.ts Lines 1 to 17 in a18f525f93d
/**
* In-memory record of the {optimisticAccountID: realAccountID} agent mappings consumed this session. The Onyx
* mapping entry is cleared once consumed, so this is the only way a late caller (e.g. an agent settings screen
* opened before the redirect) can still translate an optimistic accountID.
* ...
*/
const consumedOptimisticAccountIDs = new Map<number, number>();
function resolveAgentAccountID(accountID: number): number {
return consumedOptimisticAccountIDs.get(accountID) ?? accountID;
}
https://github.com/Expensify/App/blob/a18f525f93d9f87a44f41a0793816cd1bc3f059e/src/libs/AgentAccountIDMapping.ts#L1-L17
resolveAgentAccountID is only called from the four write actions in Agent.ts (updateAgentName, updateAgentPrompt, updateAgentAvatar, deleteAgent), not from any screen that reads route.params.accountID.
Why this reproduces on Windows Chrome but not mobile: On wide layouts, after creating an agent the Agents list stays visible in the central pane while the new agent's DM opens in the RHP, making it easy to click the row immediately. On narrow layouts, submit navigates straight into the DM and the list is not immediately accessible.
Two race variants, same root cause:
- Tap lands just before/during the sweep — navigation is dispatched but not yet in
getRootState()when the sweep runs, sosetParamsmisses it and the subsequent Onyx deletes remove the data the mounting screen needs. - Tap lands just after the sweep — the
AgentsPagerow action closure still captured the optimisticaccountID(line 119) before the list re-rendered with the real ID, so navigation starts with a dead ID after cleanup already ran.
runAfterTransitions is invoked without waitForUpcomingTransition, so when no transition is active the callback runs synchronously (TransitionTracker lines 207–209), which makes the timing window easy to hit on web where transitionStart fires before the nav state event (line 170).
This is not a failed create — failureData keeps the optimistic row with an RBR error, so Edit would still render. ProfilePage links to agent settings with a raw accountID and is outside the sweep's screen set, so the same dead-ID problem can reach that entry point too.
What changes do you think we should make in order to solve the problem?
Resolve the optimistic accountID on the read path, so any screen holding a stale optimistic ID still loads the real agent regardless of when it was opened relative to the one-shot nav sweep.
1. Add a small shared hook (e.g. useAgentAccountID) that resolves the route param once per render:
// src/hooks/useAgentAccountID.ts
import {resolveAgentAccountID} from '@libs/AgentAccountIDMapping';
function useAgentAccountID(routeAccountID: number): number {
return resolveAgentAccountID(routeAccountID);
}
export default useAgentAccountID;
The mapping is registered at line 105 of replaceOptimisticAgentWithActualAgent.ts before the deferred cleanup at lines 120–122, so by the time the optimistic keys are deleted, resolveAgentAccountID already returns the real ID and the screen swaps to the real agent instead of hitting the not-found guard.
2. Use the hook in every agent settings screen that reads route.params.accountID raw:
EditAgentPage.tsx— replace line 44 and use the resolved ID for all Onyx lookups and the not-found checkFields/EditNamePage.tsx— line 31Fields/EditPromptPage.tsx— line 44Fields/EditAgentAvatarPage.tsx— line 236ProfilePage.tsx— line 319 (SETTINGS_AGENTS_EDIT_PROMPTnavigation)
Example change in EditAgentPage:
- const accountID = route.params.accountID;
+ const accountID = useAgentAccountID(route.params.accountID);
const [agent, agentMetadata] = useOnyx(`${ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT}${accountID}`);
const [personalDetails, personalDetailsMetadata] = useOnyx(ONYXKEYS.PERSONAL_DETAILS_LIST, {selector: (list) => list?.[accountID]});
Because consumedOptimisticAccountIDs is a module-level Map, reading it inside the hook (rather than inline in render) keeps the screens React Compiler friendly.
Keep the existing nav sweep — it still repairs URLs for routes that are already open when the response lands. This change simply stops the sweep's timing from being load-bearing for correctness.
Regression test: Create an agent while throttling the CreateAgent response, tap the new row from the Agents list during the pending window, and assert the Edit page renders the agent (never NotFoundPage) both before and after the response lands. The existing ReplaceOptimisticAgentWithActualAgentTest already validates that resolveAgentAccountID returns the real ID once the mapping is consumed; extend coverage to assert an EditAgentPage mounted with an optimistic route param resolves correctly after mapping registration.
What alternative solutions did you explore? (Optional)
- Pass
waitForUpcomingTransition: 'navigation'torunAfterTransitionsat line 111 ofreplaceOptimisticAgentWithActualAgent.tsso the sweep waits for an in-flight navigation. This narrows the window but does not close it — the sweep is still one-shot, and it does nothing forProfilePagelinks or web history entries that cannot be rewritten bysetParams. - Keep the optimistic Onyx keys instead of deleting them. Rejected:
AgentsPagebuilds its table from the agent prompt collection with no dedupe, so stale optimistic rows would produce duplicate agents in the list. - Disable the Agents row until
CreateAgentresolves. Rejected: degrades the offline-first UX for a race that only lasts a few hundred milliseconds.
Related issues: Expensify/App#93272 reported a similar "not here" symptom after creating an agent, but via a different entry path (Approvals workflow navigation with a blank email during optimistic save). That flow has since been refactored and is likely a separate bug class. Expensify/App#99507 (copilot into agent account) may share the missing-login optimistic personal detail, but is a distinct symptom.
Blast radius: Read-path only; write actions already resolve IDs. Existing nav redirect behavior is unchanged. Edge cases checked: identity mapping (rejected at line 98), invalid IDs, screens opened before/after cleanup, and sibling field pages that lack a not-found guard (they would silently show empty forms without this fix).
@KJ21-ENG please don't post proposal before Help Wanted label :)