Skip to content

Open the DM with the new agent right after creation - #95482

Closed
MelvinBot wants to merge 15 commits into
mainfrom
claude-openAgentDmAfterCreation
Closed

MelvinBot wants to merge 15 commits into
mainfrom
claude-openAgentDmAfterCreation

Conversation

@MelvinBot

@MelvinBot MelvinBot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Explanation of Change

After creating a new agent, the user was returned to the Agents list (Navigation.goBack()) with no clear next step. The actual next action is to open a DM with the new agent, but nothing guided the user there.

This change opens the DM with the newly created agent immediately after creation instead of just going back. createAgent already returns the optimistic accountID it writes into Onyx, and the existing useChatWithAgent hook (the same one each row on the Agents list uses) already knows how to open the DM for a given accountID. So AddAgentPage.handleSubmit now captures that optimisticAccountID and hands it to chatWithAgent(...) in place of Navigation.goBack(). This keeps the flow fully optimistic/offline-first — no waiting on the server — matching the existing behavior of the create action.

Updated the AddAgentPage unit tests to assert the new behavior (the DM is opened with the returned agent accountID) instead of the old goBack behavior.

Fixed Issues

$ #94395
PROPOSAL: #94395 (comment)

Tests

  • Create a new agent
  • Verify that you get redirected to a DM with the agent

Offline tests

  • While offline, create a new agent
  • Verify that you don't get redirected to a DM with the agent while offline
  • Verify that you don't get redirected to a DM with the agent after coming back online

QA Steps

Same as tests

PR Author Checklist

  • I linked the correct issue in the ### Fixed Issues section above
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I added steps for the expected offline behavior in the Offline steps section
    • I added steps for Staging and/or Production testing in the QA steps section
    • I added steps to cover failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I followed proper code patterns (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick)
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I followed the guidelines as stated in the Review Guidelines
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG))
  • If new assets were added or existing ones were modified, I verified that:
    • The assets are optimized and compressed (for SVG files, run npm run compress-svg)
    • The assets load correctly across all supported platforms.
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • I added unit tests for any new feature or bug fix in this PR to help automatically prevent regressions in this user flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.

Screenshots/Videos

Android: Native
Android: mWeb Chrome
iOS: Native
iOS: mWeb Safari
MacOS: Chrome / Safari

MelvinBot and others added 2 commits July 7, 2026 10:20
Co-authored-by: Michał Jasikowski <mjasikowski@users.noreply.github.com>
Co-authored-by: Michał Jasikowski <mjasikowski@users.noreply.github.com>
@MelvinBot

Copy link
Copy Markdown
Contributor Author

The only failing check is PR Author Checklist / checklist — every other check (typecheck, all test jobs, Bun tests, ESLint, Oxfmt, builds, perf tests, etc.) passes.

That check isn't a code failure. It fails because the PR description still has its checklist boxes unchecked and the Tests / Offline tests / QA Steps sections contain the // TODO placeholders. From the run log:

❌ PR Author Checklist is not completely filled out. Please check every box to verify you've thought about the item.

These are human-only sections that I can't fill out on your behalf. To make this check pass, mjasikowski, please fill in the Tests, Offline tests, and QA Steps sections and check off the PR Author Checklist boxes, then re-run the check.

There's nothing for me to fix in code, so I haven't pushed any changes.

@mjasikowski

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 70efad1d66

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

: createAgent(firstName, prompt, selectedPresetID ?? undefined, undefined, undefined, policyID);

Navigation.goBack();
chatWithAgent(optimisticAccountID);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Dismiss the add-agent modal before opening the DM

When this page is opened from Settings it is on the RHP/modal stack, but chatWithAgent goes through navigateToAndOpenReportWithAccountIDs, which calls navigateToReport with shouldDismissModal: false. Since this change removed the previous Navigation.goBack(), submitting from the add-agent modal leaves that modal on top while the report navigation happens behind it, so the new DM is not actually shown to the user in that flow. Dismiss/pop the modal before navigating, or use a report navigation path that dismisses the modal.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@MelvinBot address this

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch — fixed in c83ef99.

navigateToAndOpenReportWithAccountIDs hardcoded shouldDismissModal: false, so submitting from the add-agent RHP left the modal on top and the new DM was never shown. I threaded an optional shouldDismissModal param through the navigation path (defaulting to false, so all existing callers — HelpPage, PromotedActionsBar, WorkspaceWorkflowsPayerPage, and the other agent pages — are unchanged) and AddAgentPage now passes true:

  • Report/index.ts — new shouldDismissModal = false param, forwarded to all three navigateToReport calls.
  • useChatWithAgent.ts — chatWithAgent(accountID, {shouldDismissModal}) forwards the flag.
  • AddAgentPage.tsx — passes {shouldDismissModal: true}, going through navigateToReport's existing dismiss-then-navigate timing (rather than a raw dismissModal() + navigate).

Also updated the AddAgentPage unit tests to assert the new argument.

Checks run locally: AddAgentPageTest (10 ✓) and ReportTest (250 ✓) pass, typecheck-tsgo clean, ESLint clean on all changed files, oxfmt applied. react-compiler-compliance-check check-changed couldn't run in this environment (no origin/main merge base), but the change is a trivial arg addition inside an existing callback with no new hooks/components.

@MelvinBot

Copy link
Copy Markdown
Contributor Author

Still nothing for me to fix in code. All functional checks pass. The two remaining failures are both human-only checklist checks:

  • PR Author Checklist / checklist — fails until the Tests / Offline tests / QA Steps sections are filled in and the author boxes are checked.
  • PR Reviewer Checklist / checklist — fails until a reviewer completes their checklist.

I can't complete either of these on your behalf (they require a human to fill out the sections and tick the boxes), and no code change would make them pass. See my earlier comment for details.

@MelvinBot

Copy link
Copy Markdown
Contributor Author

The two currently failing checks are both human-only checklist checks — not code failures, and nothing I can fix by pushing:

  • PR Author Checklist / checklist — fails because the checklist boxes aren't checked and the Tests / Offline tests / QA Steps sections still hold the // TODO placeholders. mjasikowski needs to fill these in.
  • PR Reviewer Checklist / checklist — fails with "No PR Reviewer Checklist was found". This resolves once a reviewer is assigned and completes their checklist.

Every functional check (typecheck, all test jobs, Bun tests, ESLint, Oxfmt, builds, perf tests) passes, so there are no code changes for me to make.

Co-authored-by: Michał Jasikowski <mjasikowski@users.noreply.github.com>
@github-actions

github-actions Bot commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

🚧 mjasikowski has triggered a test Expensify/App build. You can view the workflow run here.

@github-actions

This comment has been minimized.

@mjasikowski

Copy link
Copy Markdown
Contributor

@MelvinBot this still doesn't automatically open the DM with newly created agent. Diagnose why - agent ID is 22542959

@MelvinBot

Copy link
Copy Markdown
Contributor Author

Diagnosis: the DM opens against a fake accountID, not the real agent

Root cause: AddAgentPage opens the DM with the optimistic accountID that createAgent invents client-side — not the agent's real, server-assigned accountID (22542959). Account IDs, unlike report IDs, can't be optimistically generated and reconciled, so that DM never resolves to the real agent and the chat never opens.

Walking the flow:

  1. createAgent mints optimisticAccountID = Number(generateReportID()). generateReportID() returns a random ~16-digit number (up to 2⁵³) — it's designed to mint report IDs, and there's no equivalent optimistic-reconciliation for account IDs.
  2. handleSubmit hands that fake ID straight to chatWithAgent(optimisticAccountID, …), which builds/opens a DM with participants [optimisticAccountID, currentUser].
  3. When CREATE_AGENT resolves, the server creates the agent with its own real accountID (22542959), and the successData nulls out the optimistic personal detail at optimisticAccountID. So the participant we opened the DM with stops existing, and the real agent shows up under a different key.

The Agents-list rows work precisely because they use the real ID — AgentsPage derives each row's accountID from the SHARED_NVP_AGENT_PROMPT key the server wrote (22542959), so chatWithAgent gets a participant that actually exists. AddAgentPage is the only caller passing the pre-server optimistic ID, which is why only the post-creation flow fails.

So the PR's premise — "createAgent returns the optimistic accountID we can open the DM with" — doesn't hold: that ID is never the agent's identity.

Fix options

Option A — App-only, but gives up optimistic navigation. Get the agent's real accountID before navigating, by awaiting the CreateAgent response (a side-effecting request) and reading the real accountID from it, then call chatWithAgent(realAccountID). The agent row stays optimistic; only the DM navigation waits for the server. Simplest correct fix, and it works today entirely within App.

Option B — keep it fully offline-first, needs backend support. Report IDs are reconcilable, so build the optimistic DM report client-side, pass its reportID into CreateAgent, and have the backend attach the new agent's DM to that optimistic report ID. Navigation can then be immediate/offline. This requires a CreateAgent change outside the App repo, so it needs an internal engineer with backend access.

Why not just keep passing the optimistic ID?

There's no client→server mapping for account IDs the way there is for report IDs (openReport reconciles newReportObject report IDs). The optimistic personal detail at optimisticAccountID is explicitly discarded on success, so nothing ever rewrites the DM's participant from the fake ID to 22542959.


Next Steps: Reply with @MelvinBot implement option A to have me draft the App-only fix, or @MelvinBot <feedback> to refine this.

@mjasikowski

Copy link
Copy Markdown
Contributor

@MelvinBot implement option A

Co-authored-by: Michał Jasikowski <mjasikowski@users.noreply.github.com>
@MelvinBot

Copy link
Copy Markdown
Contributor Author

Implemented Option A — pushed 1583419.

What changed: the DM now opens with the agent's real, server-assigned accountID instead of the client-side optimistic one (which was never the agent's real identity, so the DM never resolved).

  • Agent.ts: createAgent keeps its optimistic, offline-capable write and now also returns createdAgentAccountID — a promise that resolves with the real accountID by watching the SHARED_NVP_AGENT_PROMPT collection for the agent that appears after creation (ignoring the optimistic placeholder and pre-existing agents).
  • AddAgentPage.tsx: dismisses the add-agent modal immediately (so the optimistic agent shows in the list and the flow stays usable offline), then opens the DM as soon as the real accountID resolves.
  • Updated the unit tests to assert the modal is dismissed and the DM opens with the real accountID (using 22542959 as the example).

Why not just await the write? API.write() for CreateAgent resolves as soon as the request is queued, not when the server responds (API/index.ts:144-148), so awaiting it wouldn't give us the real accountID. Watching the Onyx collection is the App-only way to learn it while keeping agent creation a normal offline-first write.

Behavior tradeoff to be aware of:

  • Online: modal closes → you briefly see the Agents list with the optimistic agent → the DM opens once CreateAgent responds (typically a moment later).
  • Offline: the agent is created optimistically and shows in the list, but the DM can't open until you're back online and the server assigns the real accountID — the account simply doesn't exist yet to chat with. (Fully-offline instant navigation would need the backend Option B reconciliation I described earlier.)
Local checks run
  • npm run fmt (oxfmt) — clean
  • npm run typecheck-tsgo — clean
  • lint on changed files (./scripts/lint.sh …) — clean
  • npm test -- tests/unit/pages/settings/AddAgentPageTest.tsx — 10/10 passed
  • npm run react-compiler-compliance-check check src/pages/settings/Agents/AddAgentPage.tsx — COMPILED

I couldn't runtime-verify the live server round-trip here, so please confirm on the adhoc build that the DM opens after creating an agent.

@codecov

codecov Bot commented Jul 7, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ Changes either increased or maintained existing code coverage, great job!

Files with missing lines Coverage Δ
src/hooks/useChatWithAgent.ts 100.00% <100.00%> (ø)
src/libs/actions/Report/index.ts 70.72% <100.00%> (+<0.01%) ⬆️
src/pages/settings/Agents/AddAgentPage.tsx 87.30% <100.00%> (+0.86%) ⬆️
src/hooks/useOpenDMWithCreatedAgent.ts 96.42% <96.42%> (ø)
... and 52 files with indirect coverage changes

@MelvinBot

Copy link
Copy Markdown
Contributor Author

Re-checked — the situation is unchanged from my previous comment. Every functional check (typecheck, all test jobs, Bun tests, ESLint, Oxfmt, builds, perf tests) passes.

The only failing check is PR Author Checklist / checklist, and it's not a code failure — it fails because the PR description's checklist boxes are unchecked and the Tests / Offline tests / QA Steps sections still hold the // TODO placeholders. Those are human-only sections I can't complete for you.

To make it pass, mjasikowski, please fill in the Tests, Offline tests, and QA Steps sections and check off the PR Author Checklist boxes. There's nothing for me to change in code, so I haven't pushed anything.

@github-actions

github-actions Bot commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

🚧 mjasikowski has triggered a test Expensify/App build. You can view the workflow run here.

@github-actions

This comment has been minimized.

@mjasikowski

Copy link
Copy Markdown
Contributor

it works now

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 15834192bc

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/libs/actions/Agent.ts Outdated
return;
}

const createdAgentAccountID = currentAgentAccountIDs.find((accountID) => accountID !== optimisticAccountID && !knownAgentAccountIDs?.has(accountID));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Filter out other optimistic agent placeholders

When a user submits a second agent before the first CREATE_AGENT response arrives (e.g. offline or on a slow connection after this flow returns to the Agents list), this find treats the second agent's optimistic sharedNVP_agentPrompt_* key as the newly created real account because it only excludes this request's optimistic ID. That resolves the first promise with the other placeholder/wrong accountID, so AddAgentPage can open a DM for an account ID the server will never use instead of waiting for the matching real agent.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@MelvinBot address this

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch — fixed in 0e020c2.

waitForCreatedAgentAccountID only excluded this request's optimistic ID and the baseline agents, so a second agent's optimistic sharedNVP_agentPrompt_* key (created before the first CREATE_AGENT responded) was new + not our optimistic ID → the find matched it and resolved with a placeholder accountID the server will never use.

The fix now skips any agent still pending creation, not just ours — a real, server-created agent is the only one that appears with no ADD pending action, and that's the accountID we resolve with:

// Skip any *other* agent still pending creation — e.g. a second agent the user created before this
// one's CREATE_AGENT responded (its optimistic accountID is also new and not our optimistic ID).
// Only a real, server-created agent has no ADD pending action, and that's the accountID we can open a DM with.
return agentPrompt?.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD;

See Agent.ts:132-142.

Added a regression test in AgentActionTest.ts that creates an agent, then merges a second optimistic (ADD) placeholder and asserts the promise stays unresolved, and only resolves once a real agent (no ADD) appears.

Local checks
  • AgentActionTest — 55 ✓ (incl. the new case)
  • AddAgentPageTest — 10 ✓
  • typecheck-tsgo — clean
  • lint-changed — clean
  • oxfmt — applied

@MelvinBot

Copy link
Copy Markdown
Contributor Author

🤖 No code fix needed — the only failing check requires human action.

The single failing check is PR Author Checklist, which fails with:

PR Author Checklist is not completely filled out. Please check every box to verify you've thought about the item.

Every other check (tests, typecheck, ESLint, Oxfmt, build, perf, etc.) is passing. This one isn't a code/test failure — it can't be resolved by pushing a commit. It fails because the PR body still has:

  • All PR Author Checklist boxes unchecked
  • ### Tests, ### Offline tests, and ### QA Steps left as TODO placeholders for the human co-author

To resolve: mjasikowski, please fill out the Tests / Offline tests / QA Steps sections and check the author checklist boxes. The checklist re-run will pass once the PR body is complete. I've deliberately not pushed any changes since there's nothing to fix in the code.

…ptimistic placeholder

Co-authored-by: Michał Jasikowski <mjasikowski@users.noreply.github.com>
@MelvinBot

Copy link
Copy Markdown
Contributor Author

⚠️ MelvinBot CI Fix Loop Detected

MelvinBot has made 5 consecutive commits trying to fix CI failures. Automatic CI fix dispatches are now paused for this PR.

Next steps: A human should review the recent commits and resolve the conflicting CI errors manually.

1 similar comment
@MelvinBot

Copy link
Copy Markdown
Contributor Author

⚠️ MelvinBot CI Fix Loop Detected

MelvinBot has made 5 consecutive commits trying to fix CI failures. Automatic CI fix dispatches are now paused for this PR.

Next steps: A human should review the recent commits and resolve the conflicting CI errors manually.

@github-actions

github-actions Bot commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

🚧 mjasikowski has triggered a test Expensify/App build. You can view the workflow run here.

@github-actions

This comment has been minimized.

@mjasikowski
mjasikowski removed request for mountiny and tgolen July 8, 2026 12:37
@mjasikowski

Copy link
Copy Markdown
Contributor

My bad, this shouldn't be in review yet

Comment thread src/libs/actions/Agent.ts Outdated
function waitForCreatedAgentAccountID(optimisticAccountID: number): Promise<number> {
return new Promise((resolve) => {
let knownAgentAccountIDs: Set<number> | undefined;
const connection = Onyx.connectWithoutView({

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

❌ PERF-12 (docs)

This Onyx.connectWithoutView subscription is only ever disconnected on the success path (the Onyx.disconnect(connection) inside the createdAgentEntry branch). If CREATE_AGENT fails, the failureData restores the optimistic row with pendingAction: ADD and no real, server-created agent ever appears, so the .find(...) never matches, resolve is never called, and Onyx.disconnect(connection) is never reached. The subscription (and the pending Promise it lives in) then leaks for the lifetime of the app — and this repeats on every failed creation.

Add a cleanup path so the connection is always torn down. For example, subscribe to the request/failure state (or add a timeout) and disconnect there too:

function waitForCreatedAgentAccountID(optimisticAccountID: number): Promise<number> {
    return new Promise((resolve, reject) => {
        let knownAgentAccountIDs: Set<number> | undefined;
        const connection = Onyx.connectWithoutView({
            key: ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT,
            waitForCollectionCallback: true,
            callback: (agentPrompts) => {
                // ...existing logic...
                Onyx.disconnect(connection);
                resolve(realAccountID);
            },
        });

        // Ensure the subscription is always cleaned up (e.g. on CREATE_AGENT failure / timeout)
        // so it never leaks when the real agent never arrives.
        // e.g. watch failureData/pendingAction restore, or a bounded timeout, then:
        //   Onyx.disconnect(connection); reject(...);
    });
}

Reviewed at: 066f090 | Please rate this suggestion with 👍 or 👎 to help us improve! Reactions are used to monitor reviewer efficiency.

Comment thread src/libs/actions/Agent.ts Outdated
* that already existed. Callers use it to open the DM with the newly created agent once it's real.
*/
function waitForCreatedAgentAccountID(optimisticAccountID: number): Promise<number> {
return new Promise((resolve) => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

❌ CONSISTENCY-6 (docs)

The Promise returned by waitForCreatedAgentAccountID has no failure path: it only ever resolves when a real agent appears. When CREATE_AGENT fails, the optimistic row is restored with pendingAction: ADD, no real agent shows up, and the Promise hangs forever with no error surfaced. The caller in AddAgentPage.tsx (createdAgentAccountID.then(...)) is left with a permanently-pending .then and no way to react to the failure — a silent failure of a data-mutation flow.

Handle the failure case explicitly — reject (or resolve to a sentinel) when CREATE_AGENT fails, and have the caller handle it (e.g. .catch(() => { Log.warn('agent creation failed; skipping auto-open DM'); })). This makes the failure observable and prevents the hanging Promise/subscription.


Reviewed at: 066f090 | Please rate this suggestion with 👍 or 👎 to help us improve! Reactions are used to monitor reviewer efficiency.

Replace the action-layer connectWithoutView watcher with a useOnyx
subscription in AddAgentPage. When online, the page stays mounted
(showing the submit spinner) until the newly created agent appears in
the agent-prompt collection, then opens the DM with its real accountID;
creation failures and offline creations dismiss without opening a DM.
@github-actions

github-actions Bot commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

🚧 mjasikowski has triggered a test Expensify/App build. You can view the workflow run here.

@github-actions

github-actions Bot commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

🧪🧪 Use the links below to test this adhoc build on Android, iOS, and Web. Happy testing! 🧪🧪
Built from App PR #95482.

Android 🤖 iOS 🍎
⏩ SKIPPED ⏩ ⏩ SKIPPED ⏩
The build for Android was skipped The build for iOS was skipped
Web 🕸️
https://95482.pr-testing.expensify.com
Web

👀 View the workflow run that generated this build 👀

@mjasikowski

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b533a0b98c

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

// collection, then the effect opens the DM. Snapshot the existing agents so we can tell the new one apart.
pendingCreatedAgentRef.current = {
optimisticAccountID,
knownAgentAccountIDs: new Set(Object.keys(agentPrompts ?? {}).map(getAgentAccountIDFromKey)),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Require loaded agent prompts before matching the new agent

When the add page is opened cold or by direct link and SHARED_NVP_AGENT_PROMPT has not finished hydrating at submit time, this snapshots an empty/incomplete known-agent set. If existing agents then load before the CREATE_AGENT response, the effect above treats the first old agent without pendingAction: ADD as createdAgentKey and opens that existing DM instead of the agent just created. Please gate the submit/matching logic on the collection load status or otherwise avoid matching against a partial snapshot.

Useful? React with 👍 / 👎.

@MelvinBot

Copy link
Copy Markdown
Contributor Author

🤖 No code fix needed — the only failing check is not a code failure.

The single failing check is PR Reviewer Checklist / checklist, which failed with:

##[error]No PR Reviewer Checklist was found

This is a manual gate, not a CI code failure. It stays red until the assigned reviewer posts the PR Reviewer Checklist as a comment on this PR (from CONTRIBUTING.md / the checklist template). There is no branch change that resolves it — so I have nothing to push.

Every actual code/build/test check is passing: Bun tests, all test (job 1–8), ESLint, Oxfmt, typecheck, React Compiler Compliance, Storybook, knip, unused-styles, perf tests, and the builds. The PR Author Checklist check is also passing.

To clear it: the reviewer just needs to complete and post the reviewer checklist on the PR.

On a cold open or direct link, the agent-prompt collection may not have
hydrated when the user submits, so the baseline snapshot of existing
agents was empty. Agents hydrating before the CREATE_AGENT response were
then mistaken for the newly created one, opening the wrong DM.

Gate matching on the useOnyx load status and capture the baseline lazily
from the first fully-loaded snapshot that already includes our optimistic
placeholder, so late-hydrating existing agents are never matched.
Reword the comments to be plainer and more direct, without changing any
behavior.
@mjasikowski
mjasikowski marked this pull request as ready for review July 8, 2026 14:38
@mjasikowski
mjasikowski requested a review from a team as a code owner July 8, 2026 14:38
@melvin-bot
melvin-bot Bot requested review from QichenZhu and suneox and removed request for a team July 8, 2026 14:38
@melvin-bot

melvin-bot Bot commented Jul 8, 2026

Copy link
Copy Markdown

@suneox Please copy/paste the Reviewer Checklist from here into a new comment on this PR and complete it. If you have the K2 extension, you can simply click: [this button]

@melvin-bot

melvin-bot Bot commented Jul 8, 2026

Copy link
Copy Markdown

@QichenZhu Please copy/paste the Reviewer Checklist from here into a new comment on this PR and complete it. If you have the K2 extension, you can simply click: [this button]

// page open until the created agent shows up in the collection, then open its DM.
const pendingCreatedAgentRef = useRef<PendingCreatedAgent | null>(null);

useEffect(() => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

❌ CLEAN-REACT-PATTERNS-4 (docs)

This single anonymous useEffect bundles several distinct responsibilities inline in the component body: (1) gating on collection load status, (2) recording the set of pre-existing agents into a mutable ref, (3) detecting creation failure and navigating back, and (4) scanning the whole collection to identify the newly-created agent and opening its DM. That is a lot of non-trivial matching/business logic living directly in the render function, coupled to the pendingCreatedAgentRef mutation and the Onyx collection shape. Per this rule, even a single effect benefits from extraction into a focused, well-named, independently testable hook.

Extract this into a dedicated hook (e.g. useOpenDMWithCreatedAgent) that owns the concern end-to-end, so AddAgentPage just calls it:

// useOpenDMWithCreatedAgent.ts — owns the "wait for the created agent, then open its DM" concern
function useOpenDMWithCreatedAgent() {
    const chatWithAgent = useChatWithAgent();
    const [agentPrompts, agentPromptsMetadata] = useOnyx(ONYXKEYS.COLLECTION.SHARED_NVP_AGENT_PROMPT);
    const pendingCreatedAgentRef = useRef<PendingCreatedAgent | null>(null);

    useEffect(() => {
        // ...matching + navigation logic moved here...
    }, [agentPrompts, agentPromptsMetadata.status, chatWithAgent]);

    return (optimisticAccountID: number) => {
        pendingCreatedAgentRef.current = {optimisticAccountID, knownAgentAccountIDs: null};
    };
}

// AddAgentPage.tsx
const watchForCreatedAgent = useOpenDMWithCreatedAgent();
// ...in handleSubmit, online branch:
watchForCreatedAgent(optimisticAccountID);
setIsCreatingAgent(true);

This keeps the matching logic isolated, named, documented, and unit-testable on its own, and slims AddAgentPage down to orchestration.


Reviewed at: 459dcb4 | Please rate this suggestion with 👍 or 👎 to help us improve! Reactions are used to monitor reviewer efficiency.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 459dcb4ebf

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +95 to +99
if (!agentPrompts?.[optimisticAgentKey]) {
return;
}
pendingCreatedAgent.knownAgentAccountIDs = new Set(Object.keys(agentPrompts).map(getAgentAccountIDFromKey));
return;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Match the first loaded result before baselining

If the agent-prompt collection is still loading, or Onyx batches the optimistic and success updates, the first loaded snapshot that reaches this branch can already contain this request's real sharedNVP_agentPrompt_* key. These lines then either keep returning because the optimistic key was already cleared, or record every key in that snapshot as knownAgentAccountIDs and return, so the real account is treated as pre-existing and no later update is guaranteed to open the DM; this is the opposite timing of the earlier hydration case, where this request's response is already present in the initial snapshot. Please initialize the baseline from a pre-response snapshot or immediately match any eligible non-ADD key in this first snapshot.

Useful? React with 👍 / 👎.

Move the matching and navigation logic out of AddAgentPage's render body
into a dedicated hook. AddAgentPage now just calls the hook's returned
function on submit, and its test only covers that wiring; the matching
logic (collection load status, recording existing agents, skipping other
optimistic entries, handling failures) has its own focused test.
@mjasikowski

Copy link
Copy Markdown
Contributor

Closing this to re-approach the optimistic report ID resolution differently.

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.

3 participants