App icon indicating copy to clipboard operation
App copied to clipboard

[$175] Agents - "It´s not here" page displayed after saving and reopening custom instructions.

Open applause-bot[bot] opened this issue 1 week ago • 11 comments

If you haven’t already, check out our contributing guidelines for onboarding. To join our Slack channel, fill out this form.


Version Number: 9.5.42-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: https://github.com/Expensify/App/pull/107100 Email or phone of affected tester (no customers): [email protected] Issue reported by: Applause Internal Team Bug source: Exploratory - Significant User Experience Deterioration Device used: Motorola MotoG60 / Android 12 (Hybrid app) - Windows 11 / Chrome App Component: Other

Action Performed:

Prerequisite: Use a fresh account.

  1. Open the staging.new.expensify.com website.
  2. Navigate to "Account" > "Agents" > "New Agent"
  3. Click on "Build custom agent" > "Create Agent"
  4. Close chat RHP.
  5. Before agent´s owner column appears on preview, click on row to open the edit RHP.
  6. Click on "Write custom instructions"
  7. Save instructions and reopen them.
  8. Note that you land on "It´s not here" page after reopening custom instructions.

Expected Result:

User should be able to reopen agent´s custom instructions after saving them.

Actual Result:

User lands on "It´s not here" page after saving agent´s custom instructions and reopening them.

Workaround:

Unknown

Platforms:

  • [x] Android: App
  • [ ] Android: mWeb Chrome
  • [ ] iOS: App
  • [ ] iOS: mWeb Safari
  • [ ] iOS: mWeb Chrome
  • [x] Windows: Chrome
  • [x] MacOS: Chrome Safari

Screenshots/Videos

https://github.com/user-attachments/assets/d57544f4-9440-49f8-ad75-678ab359692b

View all open jobs on GitHub

Applause Internal Information Exported by: Chandana Kiran Bug ID: 7318437

Upwork Automation - Do Not Edit

applause-bot[bot] avatar Nov 19 '26 00:11 applause-bot[bot]

While Applause doesn't embed attachments for this bug, here are the links for quick view: https://platform.applause.com/services/links/v1/external/b223d21c460a7fd9d54221b8bb7143b6d5bf449e7e767b9fa507cac19f5be38f

applause-bot[bot] avatar Nov 19 '26 00:11 applause-bot[bot]

Triggered auto assignment to Contributor-plus team member for initial proposal review - @rojiphil (External)

Job added to Upwork: https://www.upwork.com/jobs/~022123218654483112391

Proposal

What is the root cause of that problem?

Likely cause — medium confidence: opening the agent before creation finishes exposes an account-ID type mismatch. Creation updates the open editor with a number, while dynamic URL parsing produces a string. Saving instructions can therefore replace the instructions screen with a second editor instead of returning to the existing editor. Reopening instructions then generates an invalid nested URL and reaches “It’s not here.”

This mechanism is supported by code, but the exact timing-dependent failure was not reproduced.

Code evidence and alternatives checked

An ordinary save failure is a weaker explanation: it rolls back instructions rather than deleting the agent (Agent.ts:283–311).

What changes do you think we should make in order to solve the problem?

Normalize agent editor route IDs consistently to numbers during dynamic parsing, honoring their configured parser. Avoid weakening global navigation comparisons or merely hiding the error.

Add a navigation regression test that opens a pending agent, completes creation, saves instructions, and reopens them. Assert that Save returns to the original editor and the URL contains only one agent-edit segment. This should also confirm the proposed mechanism before implementation is accepted.

What alternative solutions did you explore? (Optional)

Stringifying IDs during reconciliation would address navigation matching, but conflicts with numeric route declarations and mapping lookups. Disabling editing until creation completes would mask the inconsistency.

Possibly related: Agent — “Hmm... it’s not here” when quickly opening Edit Agent after creation. It shares the timing prerequisite, but is not confirmed as the same failure.

Web verification

🤖 Web test steps verification results: ⚠️ partial

Saved instructions reopened successfully after the owner appeared. The required before-owner timing could not be achieved; supported testing controls could not delay creation.

Saved custom instructions reopened successfully after owner appeared
Step Status
Open app with fresh account ✅
Account > Agents > New agent ✅
Build custom agent > Create agent ✅
Close chat RHP ✅
Open before owner appears ⚠️
Write custom instructions after owner appears ✅
Save and reopen ✅
Confirm saved text reopens without not-found ✅
Delay creation and inspect runtime parameter types ⚠️

Next Steps for Contributor+ team: To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/107338) to create a draft PR. To refine: @MelvinBot <your feedback> To reject: Explain why you are rejecting Melvin's proposal.


view run · view recording

MelvinBot avatar Nov 19 '26 00:11 MelvinBot

Proposal

Please re-state the problem that we are trying to solve in this issue.

When a user creates a custom agent, opens its edit RHP (Settings_Agents_Dynamic_Edit) before CreateAgent finishes reconciling (i.e., before the owner column appears), saves custom instructions (Settings_Agents_Dynamic_Edit_Prompt), and then clicks Write custom instructions a second time, the app navigates to the "It's not here" (NotFoundPage) screen instead of reopening the instructions editor.

What is the root cause of that problem?

config.ts declares parse: {accountID: Number} on all four dynamic agent edit screens (SCREENS.SETTINGS.AGENTS.DYNAMIC_EDIT, DYNAMIC_EDIT_NAME, DYNAMIC_EDIT_PROMPT, and DYNAMIC_EDIT_AVATAR at src/libs/Navigation/linkingConfig/config.ts:340-363, matching AccountSettingsParamList.ts:248-259), and createNormalizedConfigs.ts:104 already stores parse on every entry in normalizedConfigs.

However, getStateForDynamicRoute (src/libs/Navigation/helpers/dynamicRoutesUtils/getStateForDynamicRoute.ts:49-83) only reads config.routeNames from normalizedConfigs and completely ignores config.parse:

  1. Before CreateAgent finishes, clicking the optimistic agent row navigates to /settings/agents/<optimisticID>/edit. findAllMatchingDynamicSuffixes extracts pathParams = {accountID: "<optimisticID>"} as a raw string, and getStateForDynamicRoute mounts DYNAMIC_EDIT with params: {accountID: "<optimisticID>"} (string).
  2. When CreateAgent resolves while the editor (or DYNAMIC_EDIT_PROMPT) is mounted, redirectAgentSettingsScreens (src/libs/actions/replaceOptimisticAgentWithActualAgent.ts:52-74) compares Number(route.params.accountID) === optimisticAccountID and calls Navigation.setParams({accountID: realAccountID}, route.key, state?.key), mutating the mounted DYNAMIC_EDIT route's params.accountID to a number (realAccountID).
  3. When the user clicks Save in DynamicEditPromptPage (src/pages/settings/Agents/Fields/DynamicEditPromptPage.tsx:72), Navigation.goBack(backPath) calls goUp('/settings/agents/<realID>/edit') (src/libs/Navigation/Navigation.ts:518-625):
    • getStateFromPath(backToRoute) parses /settings/agents/<realID>/edit via getStateForDynamicRoute, producing a target payload with params: {accountID: "<realID>"} (string) because config.parse was skipped.
    • doesRouteMatchToMinimalActionPayload (Navigation.ts:375-404) compares the mounted DYNAMIC_EDIT route ({accountID: 88442211}) against minimalActionParams ({accountID: "88442211"}) via shallowCompare (===), which returns false (88442211 !== "88442211").
    • Because findRouteToPopTo fails (canPopToRoute === false), Navigation.ts:616-619 dispatches REPLACE instead of POP, replacing DYNAMIC_EDIT_PROMPT on top of the stack with a second DYNAMIC_EDIT screen ([DYNAMIC_EDIT(number), DYNAMIC_EDIT(string)]).
  4. When the user clicks "Write custom instructions" again, getPathFromStateWithDynamicRoute (src/libs/Navigation/helpers/getPathFromState.ts:154-208) serializes both stacked DYNAMIC_EDIT routes into /settings/agents/<realID>/edit/<realID>/edit, so createDynamicRoute(DYNAMIC_ROUTES.AGENT_EDIT_PROMPT.getRoute()) navigates to /settings/agents/<realID>/edit/<realID>/edit/prompt.
    • getStateFromPath strips /prompt and recursively parses /settings/agents/<realID>/edit/<realID>/edit: its outer :accountID/edit suffix sees focusedRoute.name === SCREENS.SETTINGS.AGENTS.DYNAMIC_EDIT, which fails DYNAMIC_ROUTES.AGENT_EDIT.entryScreens ([SCREENS.SETTINGS.AGENTS.ROOT, SCREENS.WORKSPACE.AGENTS] at src/ROUTES.ts:2369), falling through to SCREENS.NOT_FOUND ("It's not here").

(Note: this also confirms why DYNAMIC_PROFILE at ProfilePage.tsx:311 (/a/:accountID/prompt) must remain unaffected: SCREENS.DYNAMIC_PROFILE intentionally has no parse in config.ts (ProfileNavigatorParamList expects accountID: string), whereas DYNAMIC_EDIT_PROMPT has parse: {accountID: Number}. Applying each dynamic route's own config.parse in getStateForDynamicRoute keeps DYNAMIC_PROFILE params as string so goBack('/a/<accountID>') still matches DYNAMIC_PROFILE, while converting DYNAMIC_EDIT / DYNAMIC_EDIT_PROMPT / DYNAMIC_EDIT_NAME / DYNAMIC_EDIT_AVATAR accountID to number.)

What changes do you think we should make in order to solve the problem?

  1. Honor RouteConfig['parse'] inside getStateForDynamicRoute (src/libs/Navigation/helpers/dynamicRoutesUtils/getStateForDynamicRoute.ts):
    • Update getRouteNamesForDynamicRoute (renamed to getRouteConfigForDynamicRoute) to return the matched RouteConfig ({routeNames, parse}) from normalizedConfigs instead of only config.routeNames.
    • When building the leaf route's cleanedParams (lines 72-75), apply matchedConfig.parse to any string-valued param whose key has a parser function in matchedConfig.parse:
      function applyRouteParamParsers(params: Record<string, unknown>, parseConfig: RouteConfig['parse']): Record<string, unknown> {
          if (!parseConfig) {
              return params;
          }
      
          const parsedParams = {...params};
          for (const [key, parser] of Object.entries(parseConfig)) {
              if (typeof parser === 'function' && Object.hasOwn(parsedParams, key) && typeof parsedParams[key] === 'string') {
                  parsedParams[key] = parser(parsedParams[key]);
              }
          }
          return parsedParams;
      }
      
    • This guarantees DYNAMIC_EDIT, DYNAMIC_EDIT_NAME, DYNAMIC_EDIT_PROMPT, and DYNAMIC_EDIT_AVATAR always hold accountID: number (matching AccountSettingsParamList, RNGetStateFromPath, and replaceOptimisticAgentWithActualAgent), while routes without parse (such as SCREENS.DYNAMIC_PROFILE) retain string params untouched.
  2. Add unit and navigation regression tests:
    • In tests/navigation/getStateForDynamicRouteTests.ts: verify that dynamic routes with parse in normalizedConfigs convert string path/parent params (e.g. accountID: Number), skip already-parsed non-string values, and leave routes without parse (DYNAMIC_PROFILE) as strings.
    • In tests/navigation/GoBackTests.tsx (and tests/actions/ReplaceOptimisticAgentWithActualAgentTest.ts): cover opening DYNAMIC_EDIT with an optimistic agent ID, reconciling via replaceOptimisticAgentWithActualAgent, opening DYNAMIC_EDIT_PROMPT, calling Navigation.goBack(backPath), and reopening DYNAMIC_EDIT_PROMPT — asserting the stack pops back to the single DYNAMIC_EDIT instance (/settings/agents/<realID>/edit) and reopens /settings/agents/<realID>/edit/prompt without hitting SCREENS.NOT_FOUND.

What alternative solutions did you explore? (Optional)

  • Passing String(realAccountID) in replaceOptimisticAgentWithActualAgent.ts: Violates AccountSettingsParamList (accountID: number), diverges from cold-start RNGetStateFromPath behavior (config.ts parse: {accountID: Number}), and leaves runtime param types inconsistent with TypeScript definitions.
  • Coercing numbers to strings inside Navigation.ts (doesRouteMatchToMinimalActionPayload): Weakens route parameter matching globally across all navigators instead of fixing the missing config.parse step in getStateForDynamicRoute.

Fabtech21 avatar Nov 19 '26 03:11 Fabtech21

@rojiphil I tested this on the latest main (da1f0beb17d) to check MelvinBot's medium-confidence root cause, and it's correct.

Repro (web): I opened the pending agent's edit RHP, then simulated the CreateAgent response arriving late.

  • After Save, the URL becomes /settings/agents/<id>/edit/<id>/edit.
  • Reopening the instructions goes to /not-found ("Hmm... it's not here").

The open editor gets accountID as a number from setParams, but dynamic route parsing returns a string. goUp's === comparison misses, and the REPLACE that follows stacks a second editor.

Fix: I applied MelvinBot's approach (honor the screen's parse config in getStateForDynamicRoute). Save now returns to a single editor, and the instructions reopen with the saved text.

  • Only 4 of 332 dynamic routes declare parse, all of them agent edit screens, so the change stays scoped to them. /a/:accountID still gets a string.
  • The Agent name page has the same bug, and this fix covers it too.
  • A new navigation test fails on main (3 of 4 cases) and passes with the fix. All 159 navigation and agent suites still pass.

I think MelvinBot's proposal is the right fix here.

oqildev avatar Nov 20 '26 12:11 oqildev

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~013b564a690d9bcdab

Proposal

Fix the agent custom-instructions "It's not here" page by making dynamic URL parsing honor the linking config's parse functions, so a route param resolved from a URL has the same type as the same param set by navigation code. The change is one helper in one file, plus six new regression tests.

Branch: fix-107338-agent-instructions-not-found (base e91964cbf8f2032a8679573d629c831238d4632d).

Please re-state the problem that we are trying to solve in this issue.

Create a new agent, open its custom-instructions editor before creation finishes, save the instructions, then reopen them. Instead of the editor with the saved text, the app shows the "It's not here" page.

The bug only bites when agent creation completes between opening the editor and saving. If creation finishes before the editor opens, or is still running when the save happens, the flow works. That timing condition is why the repro is flaky and why an earlier verification attempt could not reproduce it.

What is the root cause of that problem?

The root cause is an accountID type mismatch between two ways the same edit route gets its params, and the mismatch breaks the save-time back navigation.

  1. Dynamic URL parsing returns params as strings. getStateFromPath extracts path params as Record<string, string> and getStateForDynamicRoute merges them into the leaf route without ever applying the linking config's parse functions, even though the config declares accountID: Number for all four agent edit screens (src/libs/Navigation/linkingConfig/config.ts).
  2. Reconciliation writes a number. When creation completes, replaceOptimisticAgentWithActualAgent redirects the open edit route with Navigation.setParams({accountID: realAccountID}), a number. From that moment the mounted edit route holds a number while any URL-parsed route holds the same digits as a string.
  3. Save goes back by path, and the comparison misses. Saving calls Navigation.goBack(backPath). goUp parses that back path (string params) and compares it with shallowCompare (strict ===) against the mounted edit route (number params). The comparison fails, so goUp takes its REPLACE fallback instead of popping: the prompt route is replaced in place by a second edit route, leaving two edit routes in the RHP stack.
  4. The doubled stack serializes to a doubled URL. getPathFromState turns the two edit routes into /settings/agents/<id>/edit/<id>/edit. Reopening instructions appends /prompt to it, and parsing that URL fails the AGENT_EDIT entry-screens check (DYNAMIC_EDIT is not an allowed entry screen), so it resolves to SCREENS.NOT_FOUND, which renders "It's not here".
  5. The same mismatch has a second consequence, scoped to URL-parsed entries. A save issued while the prompt screen still holds a string optimistic ID calls resolveAgentAccountID(string), which misses the number-keyed in-memory mapping (src/libs/AgentAccountIDMapping.ts), so the prompt write lands on the optimistic key and is wiped when the reconciler clears the optimistic agent. The in-app navigate path already passes numeric IDs, so the string case only arises when the screen's params came from URL parsing (deep link or restored state). This is fixed at the same parser boundary and covered by a direct test; the reconciler-cleanup interplay itself is covered by the existing ReplaceOptimisticAgentWithActualAgentTest.

What changes do you think we should make in order to solve the problem?

Apply the leaf screen's configured parse functions to string-valued merged params when building the leaf route in src/libs/Navigation/helpers/dynamicRoutesUtils/getStateForDynamicRoute.ts (new applyConfiguredParse helper, +27/-1). Only string values are converted, so params already resolved to their converted type keep it. This is the single choke point for path-parsed dynamic routes: getStateFromPath is the only caller. It is not a claim about every route-param source in the app; in-memory state, Navigation.navigate, setParams, and hydrated state are unaffected.

Blast radius, verified by enumerating all 329 dynamic routes: only the four agent edit screens (DYNAMIC_EDIT, DYNAMIC_EDIT_NAME, DYNAMIC_EDIT_PROMPT, DYNAMIC_EDIT_AVATAR) have a parse config anywhere in their route chain, and in each case the parse lives only on the leaf screen (accountID: Number), so leaf-only parsing is sufficient and no ancestor parse can be missed. The other parse configs in the linking config (rules tag index, subscription canChangeSize, merchant orderWeight, reportID) belong to static routes handled by React Navigation's own parser and are untouched by this change.

Deliberately not changed: the global shallowCompare/goBack comparison, the reconciler's numeric setParams, and resolveAgentAccountID.

Tests (new file tests/navigation/AgentEditPromptNavigationTest.ts, 6 tests):

  • Dynamic parsing returns the accountID as a number, for all four agent edit screens. Fails on baseline, passes after the fix.
  • The save-time goBack action matches the reconciled prompt state, so goBack pops instead of replacing. Fails on baseline, passes after the fix.
  • Unreconciled control: the same goBack action matches when nothing was reconciled yet. Passes on both, which pins why the bug needs the reconciliation timing.
  • A stack with two edit routes serializes to the doubled edit segment. Passes on both, characterizing the malformed URL.
  • A URL-parsed optimistic accountID resolves to the real one through resolveAgentAccountID after the mapping is registered. Fails on baseline, passes after the fix.
  • The doubled prompt URL resolves to the not-found screen. Passes on both, characterizing the reported symptom.

Related suites, all green after the fix: 14 suites, 150 tests (getStateFromPathTests, dynamicSettingsRhpBackgroundTests, getDynamicRouteAdaptedStateTests, cardAuthenticationDynamicRouteTests, holdReasonDynamicRouteParamsTest, ReplaceOptimisticAgentWithActualAgentTest, EditPromptPageTest, EditAgentPageTest, EditNamePageTest, getAdaptedStateFromPathTabStripTests, linkingConfigColdStartTests, getMatchingFullScreenRouteTests, getPathWithoutDynamicSuffixTests, betaOverridesDynamicRouteTest). Repo lint passes on both changed files and cspell reports 0 issues.

Honest gaps: no real-device run (jest only), and the full typecheck was skipped because it runs out of memory on the 6 GB machine used for this prep; it should run in CI. The fix itself is type-safe by construction (it only converts string values through the config's own parse functions), and the new tests use no type assertions.

What alternative solutions did you explore? (Optional)

  • Loosen shallowCompare or the goBack comparison so string and number params match. Rejected: it would weaken route identity globally and hide real type drift instead of fixing it.
  • Make the reconciler set a string accountID so both sides stay strings. Rejected: it would encode the parser bug into the reconciler instead of fixing the parser.
  • Make resolveAgentAccountID accept strings. At most defense-in-depth, not a primary fix: it would not solve the duplicate-route and malformed-path chain that produces the Not Found page, and no string source remains from URL parsing once this fix lands.
  • Disable editing until agent creation completes. Rejected: it masks the inconsistency and makes the UI worse for a bug with a one-line root cause.

dankezo avatar Nov 21 '26 15:11 dankezo

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Nov 21 '26 15:11 melvin-bot[bot]

@rojiphil Huh... This is 4 days overdue. Who can take care of this?

@rojiphil 6 days overdue. This is scarier than being forced to listen to Vogon poetry!

@rojiphil 10 days overdue. I'm getting more depressed than Marvin.