Skip to content

[$250] Workspace - Concierge message order breaks when sending consecutive messages #96101

Closed

Description

@applause-bot

If you haven’t already, check out our contributing guidelines for onboarding and email contributors@expensify.com to request to join our Slack channel!


Version Number: 9.4.34-2
Reproducible in staging?: Yes
Reproducible in production?: Yes
If this was caught during regression testing, add the test name, ID and link from BrowserStack: #95002
Email or phone of affected tester (no customers): jose.sat94+10jul@gmail.com
Issue reported by: Applause Internal Team
Bug source: Pull Request QA execution
Device used: MacBook Pro/13.7.8
App Component: Workspace Settings

Action Performed:

  1. Launch the Expensify app.
  2. Log in with valid credentials to an account with a workspace (or create one).
  3. Start a 1:1 chat with Concierge and ask a question that returns suggested follow-up buttons (e.g., "Does Expensify support QuickBooks Online?").
  4. Click one of the suggested follow-up buttons.
  5. While Concierge is still generating the response (or while the follow-up buttons are still loading), send another message (e.g., "Does Expensify support Certinia?").
  6. Wait for all responses to finish loading.

Expected Result:

The conversation maintains the correct chronological order, with Concierge responses appearing after their corresponding user messages.

Actual Result:

The message order is not maintained. Concierge responses jump to the latest point in the conversation instead of staying with their corresponding user messages.

Workaround:

Unknown

Platforms:

  • Android: App
  • Android: mWeb Chrome
  • iOS: App
  • iOS: mWeb Safari
  • iOS: mWeb Chrome
  • Windows: Chrome
  • MacOS: Chrome Safari

Screenshots/Videos

bandicam.2026-07-14.19-24-15-078.mp4

View all open jobs on GitHub

Applause Internal Information
Exported by: Julia Ponikarchuk
Bug ID: 7208293

Upwork Automation - Do Not Edit

Activity

  1. added
    BugSomething is broken. Auto assigns a BugZero manager.
    on Jul 14, 2026
  2. applause-bot commented on Jul 14, 2026

    @applause-bot
    Author

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

  3. MelvinBot commented on Jul 14, 2026

    @MelvinBot
    Contributor

    Issue Analysis

    Root Cause: Concierge report actions are ordered purely by their created timestamp (ReportActionsUtils.ts getSortedReportActions). When you click a suggested-followup and then send another message before the reply lands, the Concierge reply gets a fresh server-side created (current time) instead of the timestamp of the message it belongs to — so on the next server merge it re-sorts to the bottom of the chat, "jumping" past the message you sent in the meantime.

    This already has an intended fix that is client-side only — the remaining work is on the backend. PR #95002 (merged 2026-07-11, shipped to staging in 9.4.34-0) makes the App build the optimistic Concierge action first and send its exact timestamp (optimisticConciergeCreated) with the AddComment request, so the server can persist the reply at that position. The App half is present in the build this bug was reported against (9.4.34-2), but it only supplies the timestamp — it depends on server-side changes to read optimisticConciergeCreated and persist the Concierge reply at that timestamp. Because the bug still reproduces with the App fix deployed, the server half is not yet in effect on staging/production.

    Recommended next step: The fix required here lives outside the App repository (backend persistence of the Concierge reply timestamp). This can't be resolved with an App-side code change. Please escalate to an internal engineer to confirm the corresponding backend changes are deployed and correctly persisting the reply at the supplied optimisticConciergeCreated value.

    Investigation details & evidence

    How the timestamp is built and sent (App side, confirmed working):

    Why the reply jumps: display order is (actionName===CREATED first, created, reportActionID as tiebreak) — previousReportActionID is not used. If the server assigns a new created = now to the Concierge reply, it sorts below any message the user sent while waiting.

    Deployment evidence: PR #95002 was deployed to staging in version 9.4.34-0 (per its OSBotify deploy comment); this issue is reported on 9.4.34-2, so the App-side fix is present in the tested build yet the bug persists — pointing to the backend half as the remaining gap.

    Alternative explanations considered: (1) App not sending the param — ruled out, code path confirmed above. (2) Offset too small to guarantee ordering — ruled out, offset is 4000ms and the comment at SuggestedFollowup.ts:90-92 notes 1ms was insufficient and was deliberately widened. (3) Different flow than #95002 — ruled out, the reproduction steps match #95002's test steps exactly.

    Confidence: High on the mechanism and that the fix is not client-side-only; the exact backend deploy status could not be verified from the public App repo.

    Related issues: No open duplicate found. #95634 and #91700 touch Concierge/agent rendering but are unrelated to message ordering.


    This appears to require a backend/internal fix, so I'm not proposing an App code change. Reply with @MelvinBot <feedback> to refine this analysis.

  4. added
    ExternalAdded to denote the issue can be worked on by a contributor
    on Jul 14, 2026
  5. added
    Help WantedApply this label when an issue is open to proposals by contributors
    on Jul 14, 2026
  6. aswin-s commented on Jul 14, 2026

    @aswin-s
    Contributor

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

    When a user clicks a Concierge suggested follow-up and then, while that response is still loading, sends another message, the Concierge response for the first question appears AFTER the second user message instead of between the two user messages. Expected behavior is that each Concierge response stays chronologically anchored beneath the user message it answers — that is, the response to the first question must appear before the second user message, not after it.

    What is the root cause of that problem?

    In src/libs/actions/Report/SuggestedFollowup.ts:93-103, the optimistic Concierge response is built with createdOffset: CONCIERGE_RESPONSE_DELAY_MS (4000). In src/libs/ReportUtils.ts:6389, buildOptimisticAddCommentReportAction computes created = getDBTimeWithSkew(Date.now() + createdOffset) — i.e. the Concierge action's timestamp is fixed at the moment of the follow-up click + 4s. If the user sends a second message more than ~4s after clicking the first follow-up (exactly the repro window: "while Concierge is still generating"), the second user comment's created (stamped at second-send time) is later than the pending Concierge action's created. When applyPendingConciergeAction (SuggestedFollowup.ts:178) later merges the pending Concierge action into REPORT_ACTIONS, sort by created (via getSortedReportActionsForDisplay) places it before the second user message, producing the observed out-of-order display.

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

    The fix must ensure the Concierge response is anchored between the first user message and the second user message — not pushed to the latest position in the conversation. The correct anchor is a timestamp that is strictly after the first user message but strictly before the second user message that was sent during the delay window.

    1. src/libs/actions/Report/SuggestedFollowup.ts:93-103 — at the moment of the follow-up click, record the click timestamp (clickedAt = Date.now()). Build the optimistic Concierge action with a small createdOffset of 1 (one millisecond after the click), so the initial placeholder timestamp is getDBTimeWithSkew(clickedAt + 1). Store clickedAt alongside the pending action in Onyx so it is available when the response arrives.

    2. src/libs/actions/Report/SuggestedFollowup.ts:178-199 (applyPendingConciergeAction) — before merging into REPORT_ACTIONS, re-stamp reportAction.created to getDBTimeWithSkew(clickedAt + 1) using the stored click time, not Date.now() at arrival. This anchors the Concierge response immediately after the first user message (click time + 1 ms), which is always earlier than any subsequent user message sent during the delay window. The response correctly appears between the two user messages rather than after the latest one.

    3. src/libs/actions/Report/index.ts — since optimisticConciergeCreated is sent to the server as an API parameter (AddCommentOrAttachmentParams.optimisticConciergeCreated), send the same getDBTimeWithSkew(clickedAt + 1) value (the click-anchored timestamp) so the server-persisted Concierge action matches the client-visible order.

    4. As a complementary guard: in SuggestedFollowup.ts, if a new addComment is issued on the same reportID while a pending Concierge response exists, do not re-stamp the pending action's created — leave it at clickedAt + 1. Any subsequent user messages will naturally receive a later timestamp, preserving the correct interleaving without extra logic.

    5. Add a regression test in tests/actions/ReportTest.ts covering: click follow-up → record clickedAt → wait > 4s → send another comment (timestamped after clickedAt + 4000) → apply pending Concierge action (anchored to clickedAt + 1) → assert sort order is [user1 (at clickedAt), concierge1 (at clickedAt + 1), user2 (at clickedAt + 4001+)].

    What alternative solutions did you explore? (Optional)

    Re-stamping the Concierge action to Date.now() at the moment applyPendingConciergeAction fires was considered, but this would push the Concierge response to the very end of the conversation — after the second user message — which reproduces the same failure mode the issue reports. The click-anchored approach above is preferable because it ties the response to the action that triggered it rather than to its arrival time.

  7. David-2002065 commented on Jul 14, 2026

    @David-2002065
    Contributor

    🚨 Edited by proposal-police: This proposal was edited at 2026-07-14 17:21:20 UTC.

    Proposal

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

    When the user clicks a suggested follow-up button in the Concierge chat and sends another message while the pre-generated response is still pending, the Concierge response is inserted after the newer message instead of staying right below the question it answers, and the wrong order persists after the server round-trip.

    What is the root cause of that problem?

    When a suggested follow-up has a pre-generated response, resolveSuggestedFollowup builds the optimistic Concierge reply with createdOffset: CONCIERGE_RESPONSE_DELAY_MS (4000 ms), so the reply's created timestamp is stamped 4 seconds in the future:

    // Use the full delay as createdOffset so the Concierge response timestamp is
    // strictly after the user's comment — a 1ms offset was not enough to guarantee
    // correct sort order when both actions are queued to Onyx near-simultaneously.
    const optimisticConciergeAction = buildOptimisticAddCommentReportAction({
    text: selectedFollowup.response,
    actorAccountID: CONST.ACCOUNT_ID.CONCIERGE,
    createdOffset: CONCIERGE_RESPONSE_DELAY_MS,
    reportActionID: optimisticConciergeReportActionID,
    reportID,
    isHTML: true,
    currentUserEmail,
    currentUserAccountID,
    delegateAccountIDParam: delegateAccountID,
    });

    The offset feeds directly into the action's chronological timestamp:

    function getPolicyDescriptionText(policy: OnyxEntry<Policy>): string {

    That 4-second value is really the display delay, but baking it into created opens a 4-second window: any message the user sends during that window gets a created that falls between the follow-up question and its reply. Report actions are sorted by created, so the pending reply materializes below the newer user message (Q1, Q2, A1 instead of Q1, A1, Q2).

    Since PR #95002 this future timestamp is also sent to the backend as optimisticConciergeCreated, and the server persists the final Concierge reply at that exact position — so the wrong order is now permanent, not just optimistic:

    pregeneratedResponseParams: {
    optimisticConciergeReportActionID,
    optimisticConciergeCreated: optimisticConciergeAction.reportAction.created,
    pregeneratedResponse: selectedFollowup.response,
    },

    The 4-second offset exists only because a 1 ms offset was racy (per the code comment): the user's comment gets its created from a separate, later getDBTimeWithSkew() read inside addActions, so the relative order of two independent wall-clock reads wasn't guaranteed:

    resolvedNotifyReportID = notifyReportID;
    }
    let reportCommentText = '';
    let reportCommentAction: OptimisticAddCommentReportAction | undefined;
    let attachmentAction: OptimisticAddCommentReportAction | undefined;

    Meanwhile the actual 4-second reveal delay is handled independently by displayAfter in PENDING_CONCIERGE_RESPONSE, so nothing requires the persisted timestamp to be in the future.

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

    Anchor the Concierge reply's created to the user comment's created + 1 ms deterministically, and keep the 4 seconds purely as a display delay.

    In resolveSuggestedFollowup, stamp the user comment's time once and derive both timestamps from that single read:

    const userCommentCreated = getDBTimeWithSkew();
    
    const optimisticConciergeAction = buildOptimisticAddCommentReportAction({
        text: selectedFollowup.response,
        actorAccountID: CONST.ACCOUNT_ID.CONCIERGE,
        created: DateUtils.addMillisecondsFromDateTime(userCommentCreated, 1),
        reportActionID: optimisticConciergeReportActionID,
        reportID,
        isHTML: true,
        currentUserEmail,
        currentUserAccountID,
        delegateAccountIDParam: delegateAccountID,
    });
    
    addComment({
        // ...existing params unchanged
        created: userCommentCreated,
        pregeneratedResponseParams: {
            optimisticConciergeReportActionID,
            optimisticConciergeCreated: optimisticConciergeAction.reportAction.created,
            pregeneratedResponse: selectedFollowup.response,
        },
    });

    Add an optional created param to buildOptimisticAddCommentReportAction that takes precedence over the wall-clock read:

    created: created ?? getDBTimeWithSkew(Date.now() + createdOffset),

    And thread the optional created through addComment/addActions to the user-comment build (same pattern as the existing reportActionID pass-through), so the user's comment uses the exact same base timestamp. clientCreatedTime sent to the API stays consistent automatically since it reads reportCommentAction.created.

    Result: the question is stamped at T and its reply at T + 1 ms, so any message sent later sorts after both — optimistically and server-side (the backend already honors optimisticConciergeCreated). The reply still reveals 4 seconds later via displayAfter; it just materializes at its correct chronological slot, right below its question. The now-stale comment about the 4-second offset should be removed, and since both timestamps derive from one clock read, the ordering race that motivated the 4-second hammer is gone by construction.

    What specific scenarios should we cover in automated tests to prevent reintroducing the issue?

    1. Resolve a suggested follow-up with a pre-generated response, immediately add a second user comment, then apply the pending Concierge action — assert the sorted report actions are question 1, Concierge reply, question 2.
    2. Assert the AddComment API call carries optimisticConciergeCreated equal to the queued pending action's created, exactly 1 ms after the user comment's clientCreatedTime.
    3. Assert displayAfter on PENDING_CONCIERGE_RESPONSE is still roughly now + CONCIERGE_RESPONSE_DELAY_MS, so the display delay is unaffected by the timestamp change.

    What alternative solutions did you explore? (Optional)

    • Flushing the pending Concierge response as soon as the user sends another message (applying it to REPORT_ACTIONS early): this doesn't fix the order — the reply's created (and the optimisticConciergeCreated already sent to the backend) is still stamped after the new message, so it would still render below it.
    • Reverting to a small offset from a second wall-clock read (e.g. 1–50 ms): reintroduces the nondeterministic ordering race the 4-second value was added to fix, because the user comment is stamped by a separate later clock read inside addActions.
    • Server-side clamping (backend repositions the pre-generated reply when newer messages already exist): requires Web-Expensify/Auth changes and still leaves the optimistic order wrong on the client during the 4-second window.
  8. lorretheboy commented on Jul 14, 2026

    @lorretheboy
    Contributor

    Note: This isn't a duplicate — Same root cause area (createdOffset: CONCIERGE_RESPONSE_DELAY_MS at SuggestedFollowup.ts:96), but the fixes are materially different: the flagged proposal re-stamps the Concierge action's created to a fresh Date.now() inside applyPendingConciergeAction at apply time, so the reply sorts to the end of the conversation (after the newer user message) — it changes where the reply lands rather than keeping it under its own question, and its "small offset from a second Date.now()" reintroduces the two-independent-clock-reads race the existing code comment documents. Ours never touches applyPendingConciergeAction: it captures one clock read in resolveSuggestedFollowup, threads it through addComment/addActions as an explicit created for the user's comment, and derives the Concierge stamp from that same base (+~2ms), so the reply is deterministically pinned directly below its own question and the corrected optimisticConciergeCreated matches server-side — a different code path, different mechanism, and a different resulting message order.

    Proposal

    What is the root cause of that problem?

    When a suggested follow-up with a pregenerated response is clicked, the optimistic Concierge reply is stamped with a created that is 4 seconds in the future (createdOffset: CONCIERGE_RESPONSE_DELAY_MS):

    // Use the full delay as createdOffset so the Concierge response timestamp is
    // strictly after the user's comment — a 1ms offset was not enough to guarantee
    // correct sort order when both actions are queued to Onyx near-simultaneously.
    const optimisticConciergeAction = buildOptimisticAddCommentReportAction({
    text: selectedFollowup.response,
    actorAccountID: CONST.ACCOUNT_ID.CONCIERGE,
    createdOffset: CONCIERGE_RESPONSE_DELAY_MS,
    reportActionID: optimisticConciergeReportActionID,
    reportID,
    isHTML: true,
    currentUserEmail,
    currentUserAccountID,
    delegateAccountIDParam: delegateAccountID,
    });

    Since PR #95002, that future timestamp is also sent to the backend as optimisticConciergeCreated, and the server now persists the final Concierge reply at exactly that time:

    pregeneratedResponseParams: {
    optimisticConciergeReportActionID,
    optimisticConciergeCreated: optimisticConciergeAction.reportAction.created,
    pregeneratedResponse: selectedFollowup.response,
    },

    The causal chain: the reply for message 1 is stamped t + 4s → the user sends message 2 during that 4-second window, and its comment is stamped "now" (< t + 4s) because addActions builds it with no offset:

    const reportComment = buildOptimisticAddCommentReportAction({text, reportID, reportActionID, delegateAccountIDParam: delegateAccountID});

    → report actions sort by created, so Concierge's reply to message 1 lands after message 2. Before PR #95002 this was only a transient local glitch — the server assigned its own created when it persisted the reply, restoring the order. Now the client's future timestamp is pinned server-side, so the wrong order is permanent.

    The future stamp is unnecessary: the 4-second reveal delay is already handled purely as a display concern by displayAfter in PENDING_CONCIERGE_RESPONSE, which holds the action out of REPORT_ACTIONS until the delay elapses:

    function addOptimisticConciergeActionWithDelay(reportID: string, optimisticConciergeAction: OptimisticReportAction) {
    // The "Concierge is thinking..." indicator is driven by the server-owned
    // agentZeroProcessingIndicator NVP, so this client-local delayed response
    // must not also write REPORT_USER_IS_TYPING for Concierge.
    Onyx.set(`${ONYXKEYS.COLLECTION.PENDING_CONCIERGE_RESPONSE}${reportID}`, {
    reportAction: optimisticConciergeAction.reportAction,
    displayAfter: Date.now() + CONCIERGE_RESPONSE_DELAY_MS,
    });
    }

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

    Stop using the display delay as the timestamp offset. The Concierge reply only needs to sort just after the user's comment, so stamp it a millisecond or two after that comment — not 4 seconds in the future.

    The reason a small offset previously failed (per the comment in resolveSuggestedFollowup) is that the two actions were built from two independent Date.now() calls, so the user comment could end up later than the Concierge stamp. Fix that by deriving both from one shared base: in resolveSuggestedFollowup, capture Date.now() once, pass it through addComment/addActions as an optional explicit created time for the user's comment (a tiny addition to buildOptimisticAddCommentReportAction, which already accepts createdOffset here):

    created: getDBTimeWithSkew(Date.now() + createdOffset),

    and build the Concierge action from the same base with a createdOffset of ~2ms (equivalently, DateUtils.addMillisecondsFromDateTime on the comment's created). Ordering is then deterministic — reply strictly after its own comment, and any later user message (always stamped at real "now") sorts after both, locally and on the server since optimisticConciergeCreated carries the corrected value. displayAfter keeps handling the 4-second reveal, unchanged.

    What alternative solutions did you explore? (Optional)

    Have the backend clamp optimisticConciergeCreated to server time when it's in the future — but that reintroduces the position-shift PR #95002 was fixing and needs a Web-Expensify change; fixing the stamp client-side addresses the actual mistake.

  9. ahmdshrif commented on Jul 14, 2026

    @ahmdshrif
    Contributor

    🚨 Edited by proposal-police: This proposal was edited at 2026-07-14 17:22:48 UTC.

    Proposal

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

    Click a suggested follow-up button in the Concierge chat, then send another message while the reply is still "generating": the pre-generated Concierge reply renders below your newer message — permanently — instead of directly under the question it answers.

    What is the root cause of that problem?

    The reply's chronological sort key was given the UI display delay, and PR #95002 made that future-dated key permanent on the server.

    1. Clicking a suggested follow-up builds the pre-generated Concierge reply with createdOffset: CONCIERGE_RESPONSE_DELAY_MS (4000 ms) — so its created is stamped 4 seconds in the future:
      // Use the full delay as createdOffset so the Concierge response timestamp is
      // strictly after the user's comment — a 1ms offset was not enough to guarantee
      // correct sort order when both actions are queued to Onyx near-simultaneously.
      const optimisticConciergeAction = buildOptimisticAddCommentReportAction({
      text: selectedFollowup.response,
      actorAccountID: CONST.ACCOUNT_ID.CONCIERGE,
      createdOffset: CONCIERGE_RESPONSE_DELAY_MS,
      reportActionID: optimisticConciergeReportActionID,
      reportID,
      isHTML: true,
      currentUserEmail,
      currentUserAccountID,
      delegateAccountIDParam: delegateAccountID,
      });
      and
      created: getDBTimeWithSkew(Date.now() + createdOffset),
    2. Since PR #95002, that timestamp is sent to the API as optimisticConciergeCreated and the backend persists the final reply with it verbatim (that PR's goal — keep the reply from jumping on reconcile):
      pregeneratedResponseParams: {
      optimisticConciergeReportActionID,
      optimisticConciergeCreated: optimisticConciergeAction.reportAction.created,
      pregeneratedResponse: selectedFollowup.response,
      },
      and
      // Add pregenerated params
      if (pregeneratedResponseParams) {
      parameters.optimisticConciergeReportActionID = pregeneratedResponseParams.optimisticConciergeReportActionID;
      parameters.optimisticConciergeCreated = pregeneratedResponseParams.optimisticConciergeCreated;
      parameters.pregeneratedResponse = pregeneratedResponseParams.pregeneratedResponse;
      }
    3. A message sent during that 4-second window is stamped with the real current time and is also persisted verbatim via clientCreatedTime:
      clientCreatedTime: file ? attachmentAction?.created : reportCommentAction?.created,
    4. The chat renders actions sorted by created:
      // Ensure that neither first's nor second's created property is undefined
      if (first.created === undefined || second.created === undefined) {
      return (first.created === undefined ? -1 : 1) * invertedMultiplier;
      }
      // Then sort by timestamp
      if (first.created !== second.created) {
      return (first.created < second.created ? -1 : 1) * invertedMultiplier;
      }
      — so the order becomes question (t) → your newer message (t+2s) → Concierge reply (t+4s).

    Because both timestamps are client-authored and server-persisted, the wrong order survives reload and shows on every client — which is why QA reproduced it on staging and production right after #95002. Before that PR the future stamp was a transient local quirk the server silently corrected; now it is the permanent record.

    All paths this single cause feeds (each covered below): the persisted order on every platform (shared TS, nothing web-specific); the in-flight "trickle" bubble, inserted by the same created comparison (

    // Insert the synthetic draft into the already-descending render list without treating it as a persisted report action.
    for (const [index, action] of sortedVisibleReportActions.entries()) {
    if (action.reportActionID === draftReportAction.reportActionID) {
    const isDraftStillRevealingPersistedAction = getReportActionHtml(action) !== getReportActionHtml(draftReportAction);
    if (!isDraftPendingCompletion && !isDraftStillRevealingPersistedAction) {
    return sortedVisibleReportActions;
    }
    const visibleReportActionsWithDraft = [...sortedVisibleReportActions];
    visibleReportActionsWithDraft[index] = draftReportAction;
    return visibleReportActionsWithDraft;
    }
    if (isNewerReportAction(draftReportAction, action)) {
    const visibleReportActionsWithDraft = [...sortedVisibleReportActions];
    visibleReportActionsWithDraft.splice(index, 0, draftReportAction);
    return visibleReportActionsWithDraft;
    }
    }
    const visibleReportActionsWithDraft = [...sortedVisibleReportActions];
    visibleReportActionsWithDraft.push(draftReportAction);
    return visibleReportActionsWithDraft;
    ); the final merge in applyPendingConciergeAction (
    function applyPendingConciergeAction(reportID: string | undefined, reportAction: ReportAction) {
    Onyx.update([
    {
    onyxMethod: Onyx.METHOD.SET,
    key: `${ONYXKEYS.COLLECTION.PENDING_CONCIERGE_RESPONSE}${reportID}`,
    value: null,
    },
    {
    onyxMethod: Onyx.METHOD.MERGE,
    key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`,
    value: {[reportAction.reportActionID]: reportAction},
    },
    {
    onyxMethod: Onyx.METHOD.SET,
    key: `${ONYXKEYS.COLLECTION.CONCIERGE_PENDING_FOLLOWUP_LIST}${reportID}`,
    value: {
    reportActionID: reportAction.reportActionID,
    createdAt: Date.now(),
    },
    },
    ]);
    ); and the second Concierge reply (to your newer message), which is server-stamped and can even land before the pre-generated one's t+4s — that's why "responses" (plural) jumble.

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

    Derive both timestamps from one clock reading, and keep the 4-second delay purely as UI state. In resolveSuggestedFollowup:

    const followupClickedAt = Date.now();
    const optimisticConciergeAction = buildOptimisticAddCommentReportAction({
        // ...same args, createdOffset removed...
        created: getDBTimeWithSkew(followupClickedAt + 1), // 1ms after the user's comment
    });
    addComment({/* ...same args... */, created: getDBTimeWithSkew(followupClickedAt)});

    Supporting plumbing: add an optional created?: string to buildOptimisticAddCommentReportAction (created: created ?? getDBTimeWithSkew(Date.now() + createdOffset) at

    created: getDBTimeWithSkew(Date.now() + createdOffset),
    ) and thread the optional created through addComment → addActions to the comment build at
    const reportComment = buildOptimisticAddCommentReportAction({text, reportID, reportActionID, delegateAccountIDParam: delegateAccountID});
    . displayAfter (
    function addOptimisticConciergeActionWithDelay(reportID: string, optimisticConciergeAction: OptimisticReportAction) {
    // The "Concierge is thinking..." indicator is driven by the server-owned
    // agentZeroProcessingIndicator NVP, so this client-local delayed response
    // must not also write REPORT_USER_IS_TYPING for Concierge.
    Onyx.set(`${ONYXKEYS.COLLECTION.PENDING_CONCIERGE_RESPONSE}${reportID}`, {
    reportAction: optimisticConciergeAction.reportAction,
    displayAfter: Date.now() + CONCIERGE_RESPONSE_DELAY_MS,
    });
    }
    ) is untouched, so the 4-second reveal animation and #95002's persist-the-optimistic-timestamp design are both preserved — only the value becomes correct. Persisted order is then always question (t) → reply (t+1 ms) → anything sent later. I'd update the resolveSuggestedFollowup block in tests/actions/ReportTest.ts to assert the reply's created is 1 ms after the comment's rather than ~4 s in the future.

    Regression safety in one sentence: the new created params are optional with the current expressions as fallback, so every other caller (tasks, onboarding, attachments, plain comments) is byte-for-byte unchanged.

    Why the obvious one-line fix fails: just shrinking createdOffset from 4000 to 1 was already tried and abandoned — the in-code comment (

    // Use the full delay as createdOffset so the Concierge response timestamp is
    // strictly after the user's comment — a 1ms offset was not enough to guarantee
    // correct sort order when both actions are queued to Onyx near-simultaneously.
    ) records that "a 1ms offset was not enough". The mechanism: the user's comment is stamped by a later Date.now() inside addActions (after synchronous comment parsing), so a 1 ms offset can leave the reply stamped before its own trigger comment; any offset large enough to absorb that jitter re-opens the consecutive-message window proportionally. Deterministic order requires one shared clock reading — threading the explicit created, not tuning the offset.

    What alternative solutions did you explore? (Optional)

    1. A small fixed createdOffset (e.g. 250 ms) — no plumbing, but it only shrinks the race on both sides (slow-device stamp jitter vs. a fast second message); this class of fix already failed once per the in-code comment.
    2. Flush/re-stamp the pending reply when the user sends a new message — the reply's created was already sent to the server in the click-time AddComment request, so a local re-stamp desyncs client and server and reintroduces the reconcile position-jump #95002 fixed; flushing early also kills the intentional delayed reveal.
    3. Backend clamp of optimisticConciergeCreated — the upstream half lives in Web-Expensify, but the App-side change above fully resolves the ordering on its own and is the mergeable fix here.
  10. shivang-goliyan commented on Jul 14, 2026

    @shivang-goliyan
    Contributor

    🚨 Edited by proposal-police: This proposal was edited at 2026-07-14 17:42:43 UTC.

    Proposal

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

    When you click a suggested follow-up button in a Concierge chat and then send another message before the answer finishes loading, the answer ends up below your newer message instead of sitting right after the question it belongs to. The conversation reads out of order.

    What is the root cause of that problem?

    The pregenerated Concierge reply is stamped roughly 4 seconds in the future. In resolveSuggestedFollowup (src/libs/actions/Report/SuggestedFollowup.ts:96) the reply is built with createdOffset: CONCIERGE_RESPONSE_DELAY_MS (4000, defined at line 19), and buildOptimisticAddCommentReportAction turns that into created = getDBTimeWithSkew(Date.now() + createdOffset) at src/libs/ReportUtils.ts:6389. Chat order is decided entirely by that created string: getSortedReportActions (src/libs/ReportActionsUtils.ts:788) sorts ascending by created, tie-broken by reportActionID, with no special-casing for Concierge or ADD_COMMENT. So the reply lands at click_time + 4000ms. Your second message is stamped at its own Date.now() with no offset, so if you send it any time inside that 4-second window it sorts between the question and the reply, and the answer renders below it.

    The 4000 isn't arbitrary, and that's the real issue. The Concierge action is built before the user's comment, so an earlier attempt using a 1ms offset (commit 9e54be51cc9) failed: the reply was measured from an earlier Date.now() than the user comment's own build instant, so it could sort before its own question. Commit 83358d1cbd9 (2026-03-25) bumped the offset 1ms → 4000ms to guarantee the reply came after the question. That fixed the single-message race but widened the reorder window from 1ms to a full 4 seconds, which is what makes this so easy to hit. The deeper problem is that one 4000ms constant is doing two unrelated jobs: it's the reply's sort key offset here, and separately it's the reveal delay (displayAfter = Date.now() + 4000 at line 139, consumed by usePendingConciergeResponse). The reveal delay legitimately needs 4 seconds; the sort key does not, and coupling them is what puts the reply in the wrong place.

    This also affects the persisted order, not just the optimistic view. SuggestedFollowup.ts:117 forwards that same created into addComment as optimisticConciergeCreated, which reaches the backend via #95002 so the server persists the reply at the App-provided timestamp. So the wrong value the App computes is the value the server plants. Fixing the computation here fixes both the optimistic display and what gets persisted.

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

    Anchor the reply's created to the user comment's own created plus a 1ms epsilon, instead of Date.now() + 4000. Concretely: compute one shared base timestamp for the user comment, stamp the user comment with it, and stamp the Concierge reply at base + 1ms. This is the same "second optimistic action sorts immediately after the first" idiom already used across the codebase via DateUtils.addMillisecondsFromDateTime (src/libs/DateUtils.ts:377) in IOU/Hold.ts, IOU/RejectMoneyRequest.ts, IOU/SplitTransactionUpdate.ts and ReportUtils.ts:7622.

    One honest note on the plumbing, since it's more than a one-liner: buildOptimisticAddCommentReportAction today only accepts createdOffset (an offset from Date.now()), not an explicit created, and addComment/addActions builds the user comment with its own internal getDBTimeWithSkew(Date.now()). To make the user comment and its reply share one base, we thread a new optional created (or shared base) through SuggestedFollowup → addComment/addActions → buildOptimisticAddCommentReportAction, defaulted so every other caller is unchanged. Keep displayAfter's 4-second reveal exactly as it is — it's computed independently and doesn't need the created stamp to be future-dated.

    Why 1ms is enough now when it wasn't before: the old 1ms failed because it was measured from an earlier instant than the user comment's own build time. Deriving the reply from the user comment's own created removes that race — the epsilon is measured against the exact value it has to beat, so question < reply < any later message holds in every case. And the corrected value is what flows into optimisticConciergeCreated, so the persisted position is right too (assuming the backend honours the App value per #95002's design — worth confirming against Web-Expensify #54097 / Auth #22590, since we can't see server-side persistence from this repo).

    I'd also add the test coverage that's currently missing. #95002 added a test that optimisticConciergeCreated is forwarded, but nothing covers the interleaved-message ordering that actually broke. Add a Jest test that builds the optimistic Concierge action, sends a second user comment with a created between the click and the reveal, runs getSortedReportActions, and asserts [Q1, reply-to-Q1, Q2] — plus that the reply's created equals the user comment's created + 1ms, not now + 4000.

    What alternative solutions did you explore? (Optional)

    Shrinking the offset from 4000 to something small while still measuring off Date.now() doesn't work — it re-opens the original race (reply can sort before its own question) and still breaks whenever a message lands inside the smaller window. It narrows the bug rather than removing it. Plumbing the timestamp to the backend and stopping there is what #95002 already did, and QA reproduced this on top of it, so it's necessary but not sufficient. Special-casing Concierge replies inside getSortedReportActions would touch a global used by every report list, so I'd rather fix the value at its source than change the sort for all chats.

  11. KJ21-ENG commented on Jul 14, 2026

    @KJ21-ENG
    Contributor

    🚨 Edited by proposal-police: This proposal was edited at 2026-07-14 20:32:14 UTC.

    Proposal

    What is the root cause of that problem?

    This is a regression from PR #95002 (4a7cc2db5c4). For a pre-generated follow-up reply, resolveSuggestedFollowup() uses the four-second UI reveal delay as createdOffset, then sends that future timestamp to the API as optimisticConciergeCreated.

    // If there's a pre-generated response, queue it for delayed display.
    const optimisticConciergeReportActionID = rand64();
    // Use the full delay as createdOffset so the Concierge response timestamp is
    // strictly after the user's comment — a 1ms offset was not enough to guarantee
    // correct sort order when both actions are queued to Onyx near-simultaneously.
    const optimisticConciergeAction = buildOptimisticAddCommentReportAction({
    text: selectedFollowup.response,
    actorAccountID: CONST.ACCOUNT_ID.CONCIERGE,
    createdOffset: CONCIERGE_RESPONSE_DELAY_MS,
    reportActionID: optimisticConciergeReportActionID,
    reportID,
    isHTML: true,
    currentUserEmail,
    currentUserAccountID,
    delegateAccountIDParam: delegateAccountID,
    });
    // Post user's comment immediately
    addComment({
    report,
    notifyReportID: notifyReportID ?? reportID,
    ancestors,
    text: selectedFollowup.text,
    timezoneParam,
    currentUserAccountID,
    shouldPlaySound: false,
    isInSidePanel: false,
    pregeneratedResponseParams: {
    optimisticConciergeReportActionID,
    optimisticConciergeCreated: optimisticConciergeAction.reportAction.created,
    pregeneratedResponse: selectedFollowup.response,
    },
    delegateAccountID,
    conciergeReportID,
    });
    addOptimisticConciergeActionWithDelay(reportID, optimisticConciergeAction);

    That timestamp is conversation-ordering data, not merely reveal timing. Report actions are ordered by created, and the synthetic Concierge draft is also inserted into the list according to its copied created value. Therefore, any second user message sent during those four seconds has an earlier timestamp than the first question's Concierge reply, so the reply moves below the second message. The short-reply and persisted paths have the same problem because they apply the same pending report action.

    /**
    * Sort an array of reportActions by their created timestamp first, and reportActionID second
    * This gives us a stable order even in the case of multiple reportActions created on the same millisecond
    *
    */
    function getSortedReportActions(reportActions: ReportAction[] | null, shouldSortInDescendingOrder = false): ReportAction[] {
    if (!Array.isArray(reportActions)) {
    throw new Error(`ReportActionsUtils.getSortedReportActions requires an array, received ${typeof reportActions}`);
    }
    const invertedMultiplier = shouldSortInDescendingOrder ? -1 : 1;
    const sortedActions = reportActions?.filter(Boolean).sort((first, second) => {
    // First sort by action type, ensuring that `CREATED` actions always come first if they have the same or even a later timestamp as another action type
    if ((first.actionName === CONST.REPORT.ACTIONS.TYPE.CREATED || second.actionName === CONST.REPORT.ACTIONS.TYPE.CREATED) && first.actionName !== second.actionName) {
    return (first.actionName === CONST.REPORT.ACTIONS.TYPE.CREATED ? -1 : 1) * invertedMultiplier;
    }
    // Ensure that neither first's nor second's created property is undefined
    if (first.created === undefined || second.created === undefined) {
    return (first.created === undefined ? -1 : 1) * invertedMultiplier;
    }
    // Then sort by timestamp
    if (first.created !== second.created) {
    return (first.created < second.created ? -1 : 1) * invertedMultiplier;
    }
    // Ensure that `REPORT_PREVIEW` actions always come after if they have the same timestamp as another action type
    if ((first.actionName === CONST.REPORT.ACTIONS.TYPE.REPORT_PREVIEW || second.actionName === CONST.REPORT.ACTIONS.TYPE.REPORT_PREVIEW) && first.actionName !== second.actionName) {
    return (first.actionName === CONST.REPORT.ACTIONS.TYPE.REPORT_PREVIEW ? 1 : -1) * invertedMultiplier;
    }
    // Then fallback on reportActionID as the final sorting criteria. It is a random number,
    // but using this will ensure that the order of reportActions with the same created time and action type
    // will be consistent across all users and devices
    return (first.reportActionID < second.reportActionID ? -1 : 1) * invertedMultiplier;

    const shouldTrickle = snapshotTokens.length >= MIN_TRICKLE_TOKEN_COUNT && !!snapshotHtml;
    if (!shouldTrickle) {
    const timer = setTimeout(() => applyPendingConciergeAction(reportID, reportAction), Math.max(0, remainingDelay));
    return () => clearTimeout(timer);
    }
    const session = rand64();
    let sequence = 0;
    let intervalID: ReturnType<typeof setInterval> | null = null;
    let trickleStart = 0;
    let effectiveDuration = DEFAULT_STREAM_DURATION_MS;
    let lastStage = 0;
    let cancelled = false;
    // Snapshot of trickle progress at the moment the canonical reportComment
    // arrives. Presence (`arrival !== undefined`) doubles as the
    // "acceleration fired" check that selects the completion reason below.
    let arrival: {progress: number; elapsedMs: number} | undefined;
    const dispatch = (status: ConciergeDraftEvent['status'], finalRenderedHTML: string) => {
    if (cancelled) {
    return;
    }
    sequence += 1;
    // Read dispatch fn from the ref so a context-provider refresh doesn't pin
    // the trickle to a stale handler. The ref always points at the latest.
    trickleInputsRef.current.dispatchLocalDraftEvent({
    reportID,
    reportActionID,
    streamSessionID: session,
    sequence,
    status,
    created: reportAction.created,
    finalRenderedHTML,
    });

    const persistedDraftReportAction = draftReportAction ? sortedVisibleReportActions.find((action) => action.reportActionID === draftReportAction.reportActionID) : undefined;
    const renderedVisibleReportActions = (() => {
    if (!draftReportAction) {
    return sortedVisibleReportActions;
    }
    if (showHiddenHistory && sessionStartTime && draftReportAction.created < sessionStartTime) {
    return sortedVisibleReportActions;
    }
    // Insert the synthetic draft into the already-descending render list without treating it as a persisted report action.
    for (const [index, action] of sortedVisibleReportActions.entries()) {
    if (action.reportActionID === draftReportAction.reportActionID) {
    const isDraftStillRevealingPersistedAction = getReportActionHtml(action) !== getReportActionHtml(draftReportAction);
    if (!isDraftPendingCompletion && !isDraftStillRevealingPersistedAction) {
    return sortedVisibleReportActions;
    }
    const visibleReportActionsWithDraft = [...sortedVisibleReportActions];
    visibleReportActionsWithDraft[index] = draftReportAction;
    return visibleReportActionsWithDraft;
    }
    if (isNewerReportAction(draftReportAction, action)) {
    const visibleReportActionsWithDraft = [...sortedVisibleReportActions];
    visibleReportActionsWithDraft.splice(index, 0, draftReportAction);
    return visibleReportActionsWithDraft;
    }
    }
    const visibleReportActionsWithDraft = [...sortedVisibleReportActions];
    visibleReportActionsWithDraft.push(draftReportAction);

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

    Decouple the response's chronological timestamp from CONCIERGE_RESPONSE_DELAY_MS. In resolveSuggestedFollowup(), capture one base time for the selected user question, assign that exact time to the optimistic question, and assign the pre-generated Concierge action a deterministic timestamp one millisecond later. Continue using displayAfter = Date.now() + CONCIERGE_RESPONSE_DELAY_MS solely to control when the response becomes visible. Pass the same paired Concierge timestamp through optimisticConciergeCreated, so the optimistic draft, delayed Onyx action, and server action all remain immediately after their corresponding question even when newer messages arrive.

    To make this deterministic, allow buildOptimisticAddCommentReportAction() and the narrow addActions() path to accept an optional explicit created value. Only resolveSuggestedFollowup() should supply it for the paired user/Concierge actions. Existing builder consumers (addActions() for ordinary text/attachments, buildOptimisticTaskCommentReportAction(), onboarding welcome messages, respondToProactiveAppReview(), pressLockedBankAccount(), buildOnyxDataForTestDriveIOU(), and addCommentToSplitTransactionThread()) should omit the new option and retain their current timestamp behavior. The shared report-action sorter is correct and should not be changed.

    App/src/libs/ReportUtils.ts

    Lines 337 to 350 in 2790fa4

    type BuildOptimisticAddCommentReportActionParams = {
    currentUserEmail?: string;
    // TODO: This will be required eventually. Refactor issue: https://github.com/Expensify/App/issues/66412
    currentUserAccountID?: number;
    text?: string;
    file?: FileObject;
    actorAccountID?: number;
    createdOffset?: number;
    reportID?: string;
    reportActionID?: string;
    attachmentID?: string;
    isHTML?: boolean;
    delegateAccountIDParam: number | undefined;
    };

    App/src/libs/ReportUtils.ts

    Lines 6347 to 6385 in 2790fa4

    function buildOptimisticAddCommentReportAction({
    text,
    file,
    actorAccountID,
    createdOffset = 0,
    reportID,
    reportActionID = rand64(),
    attachmentID,
    currentUserEmail,
    currentUserAccountID,
    isHTML = false,
    delegateAccountIDParam,
    }: BuildOptimisticAddCommentReportActionParams): OptimisticReportAction {
    const commentText = isHTML ? (text ?? '') : getParsedComment(text ?? '', {reportID});
    const attachmentHtml = getUploadingAttachmentHtml(file, attachmentID);
    const htmlForNewComment = `${commentText}${commentText && attachmentHtml ? '<br /><br />' : ''}${attachmentHtml}`;
    const textForNewComment = Parser.htmlToText(htmlForNewComment);
    const isAttachmentOnly = file && !text;
    const isAttachmentWithText = !!text && file !== undefined;
    const accountID = actorAccountID ?? currentUserAccountID ?? deprecatedCurrentUserAccountID ?? CONST.DEFAULT_NUMBER_ID;
    // Falls back to module-level delegateEmail (from Onyx.connect) for callers not yet migrated; will be removed in https://github.com/Expensify/App/issues/66425
    const effectiveDelegateAccountID = delegateAccountIDParam ?? (delegateEmail ? getPersonalDetailByEmail(delegateEmail)?.accountID : undefined);
    // Remove HTML from text when applying optimistic offline comment
    return {
    commentText,
    reportAction: {
    reportActionID,
    reportID,
    actionName: CONST.REPORT.ACTIONS.TYPE.ADD_COMMENT,
    actorAccountID: accountID,
    person: [
    {
    style: 'strong',
    text: allPersonalDetails?.[accountID]?.displayName ?? currentUserEmail ?? deprecatedCurrentUserEmail,
    type: 'TEXT',
    },

    type PregeneratedResponseParams = {
    optimisticConciergeReportActionID: string;
    optimisticConciergeCreated: string;
    pregeneratedResponse: string;
    };
    type AddCommentParams = {
    report: OnyxEntry<Report>;
    notifyReportID: string;
    ancestors: Ancestor[];
    text: string;
    timezoneParam: Timezone;
    currentUserAccountID: number;
    shouldPlaySound?: boolean;
    isInSidePanel?: boolean;
    sidePanelContext?: SidePanelContext;
    pregeneratedResponseParams?: PregeneratedResponseParams;
    reportActionID?: string;
    delegateAccountID: number | undefined;
    conciergeReportID: string | undefined;
    };
    type AddActionsParams = {
    report: OnyxEntry<Report>;
    notifyReportID: string | string[];
    ancestors: Ancestor[];
    timezoneParam: Timezone;
    currentUserAccountID: number;
    text?: string;
    file?: FileObject;
    isInSidePanel?: boolean;
    sidePanelContext?: SidePanelContext;
    pregeneratedResponseParams?: PregeneratedResponseParams;
    reportActionID?: string;

    const attachmentID = rand64();
    if (text && !file) {
    const reportComment = buildOptimisticAddCommentReportAction({text, reportID, reportActionID, delegateAccountIDParam: delegateAccountID});
    reportCommentAction = reportComment.reportAction;
    reportCommentText = reportComment.commentText;

    Keep the existing API contract that sends the local Concierge ID and timestamp; only change how the timestamp is derived.

    const parameters: AddCommentOrAttachmentParams = {
    reportID,
    reportActionID: resolvedReportActionID,
    commentReportActionID: file && reportCommentAction ? reportCommentAction.reportActionID : null,
    reportComment: reportCommentText,
    file,
    clientCreatedTime: file ? attachmentAction?.created : reportCommentAction?.created,
    idempotencyKey: Str.guid(),
    };
    const isConciergeChat = isConciergeChatReport(reportForAction, conciergeReportID);
    if (reportIDDeeplinkedFromOldDot === reportID && isConciergeChat) {
    parameters.isOldDotConciergeChat = true;
    }
    if (file) {
    parameters.attachmentID = attachmentID;
    }
    if (isInSidePanel && (isConciergeChat || isAdminRoom(reportForAction))) {
    const pageHTML = capturePageHTML();
    if (pageHTML) {
    parameters.pageHTML = pageHTML;
    }
    }
    if (isInSidePanel && isConciergeChat && sidePanelContext && commandName === WRITE_COMMANDS.ADD_COMMENT) {
    parameters.sidePanelContext = JSON.stringify(sidePanelContext);
    }
    // Add pregenerated params
    if (pregeneratedResponseParams) {
    parameters.optimisticConciergeReportActionID = pregeneratedResponseParams.optimisticConciergeReportActionID;
    parameters.optimisticConciergeCreated = pregeneratedResponseParams.optimisticConciergeCreated;
    parameters.pregeneratedResponse = pregeneratedResponseParams.pregeneratedResponse;

    Test coverage:

    • Extend resolveSuggestedFollowup tests to freeze time, click a follow-up with a pre-generated response, add another normal message before the four-second reveal, and assert the sorted order remains selected question, paired Concierge response, then the newer user message.
    • Assert the paired response is exactly one millisecond after its question, displayAfter remains four seconds later, and the API's optimisticConciergeCreated equals the local pending action's created value.
    • Cover both a short response applied directly to REPORT_ACTIONS and a long response dispatched through the Concierge draft path so optimistic, streaming, and canonical rendering use the same chronological anchor.

    // Set up initial Onyx state with real timers
    await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${REPORT_ID}`, report);
    await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${REPORT_ID}`, {
    [REPORT_ACTION_ID]: reportAction,
    });
    await waitForBatchedUpdates();
    resolveSuggestedFollowup(
    report,
    undefined,
    reportAction,
    {text: 'How do I set up QuickBooks?', response: 'To set up QuickBooks, go to Settings...'},
    CONST.DEFAULT_TIME_ZONE,
    TEST_USER_ACCOUNT_ID,
    TEST_USER_EMAIL,
    undefined,
    undefined,
    );
    await waitForBatchedUpdates();
    // Verify the followup-list was marked as selected
    const reportActions = await getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${REPORT_ID}` as const);
    const updatedHtml = (reportActions?.[REPORT_ACTION_ID]?.message as Message[])?.at(0)?.html;
    expect(updatedHtml).toContain('<followup-list selected>');
    // Verify addComment was called (which triggers ADD_COMMENT API call)
    // With pre-generated response, the API call should include the optimistic Concierge response params
    TestHelper.expectAPICommandToHaveBeenCalled(WRITE_COMMANDS.ADD_COMMENT, 1);
    // Verify the pending concierge response was written to Onyx (the hook will process it)
    const pendingResponse = await getOnyxValue(`${ONYXKEYS.COLLECTION.PENDING_CONCIERGE_RESPONSE}${REPORT_ID}` as const);
    expect(pendingResponse).not.toBeNull();
    expect(pendingResponse?.reportAction.actorAccountID).toBe(CONST.ACCOUNT_ID.CONCIERGE);
    expect(pendingResponse?.displayAfter).toBeGreaterThan(Date.now() - CONCIERGE_RESPONSE_DELAY_MS);
    expect(apiWriteSpy).toHaveBeenCalledWith(
    WRITE_COMMANDS.ADD_COMMENT,
    expect.objectContaining({
    optimisticConciergeReportActionID: pendingResponse?.reportAction.reportActionID,
    optimisticConciergeCreated: pendingResponse?.reportAction.created,
    }),
    expect.anything(),
    );
    // Verify the client did NOT set REPORT_USER_IS_TYPING. The server-owned
    // agentZeroProcessingIndicator is the source of truth for the "Concierge is thinking..."
    // state during the delayed pre-generated response window.
    const typingStatus = await getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT_USER_IS_TYPING}${REPORT_ID}` as const);
    expect(typingStatus?.[CONST.ACCOUNT_ID.CONCIERGE]).toBeFalsy();
    });
    it('should create Concierge response with timestamp strictly after the user comment', async () => {
    const reportAction = createMock<OnyxTypes.ReportAction>({
    reportActionID: REPORT_ACTION_ID,
    actorAccountID: CONST.ACCOUNT_ID.CONCIERGE,
    message: [
    {
    html: '<p>Here is help</p><followup-list><followup><followup-text>How do I set up QuickBooks?</followup-text><followup-response>To set up QuickBooks, go to Settings...</followup-response></followup></followup-list>',
    text: 'Here is help',
    type: CONST.REPORT.MESSAGE.TYPE.COMMENT,
    },
    ],
    });
    await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${REPORT_ID}`, report);
    await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${REPORT_ID}`, {
    [REPORT_ACTION_ID]: reportAction,
    });
    await waitForBatchedUpdates();
    resolveSuggestedFollowup(
    report,
    undefined,
    reportAction,
    {text: 'How do I set up QuickBooks?', response: 'To set up QuickBooks, go to Settings...'},
    CONST.DEFAULT_TIME_ZONE,
    TEST_USER_ACCOUNT_ID,
    TEST_USER_EMAIL,
    undefined,
    undefined,
    );
    await waitForBatchedUpdates();
    // Get the pending Concierge response and verify its created timestamp
    const pendingResponse = await getOnyxValue(`${ONYXKEYS.COLLECTION.PENDING_CONCIERGE_RESPONSE}${REPORT_ID}` as const);
    expect(pendingResponse).not.toBeNull();
    // Find the user's comment action (any new action that isn't the original Concierge message)
    const reportActions = await getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${REPORT_ID}` as const);
    const userCommentAction = Object.values(reportActions ?? {}).find(
    (action) => action?.reportActionID !== REPORT_ACTION_ID && action?.actorAccountID !== CONST.ACCOUNT_ID.CONCIERGE,
    );
    // The Concierge response timestamp should be strictly after the user comment
    expect(userCommentAction).toBeDefined();
    expect(userCommentAction?.created).toBeDefined();
    expect(pendingResponse?.reportAction.created).toBeDefined();
    expect(new Date(pendingResponse?.reportAction.created ?? 0).getTime()).toBeGreaterThan(new Date(userCommentAction?.created ?? 0).getTime());
    });

    What alternative solutions did you explore? (Optional)

    I considered changing ReportActionsList to insert an active Concierge draft next to the user question by report-action ID instead of by timestamp. That would address only the synthetic streaming bubble; short replies and canonical REPORT_ACTIONS would still be sorted by the future created timestamp, and other clients would still receive the wrong chronology. Correcting the paired timestamps at creation time fixes every rendering path while preserving the shared sorter.

  12. melvin-bot commented on Jul 14, 2026

    @melvin-bot

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

  13. 14 remaining items

  14. jl3panadero-source commented on Jul 14, 2026

    @jl3panadero-source

    🔧 AgentWork — Solución

    Análise do Erro

    O erro ocorre quando o usuário envia mensagens consecutivas para o Concierge enquanto as respostas anteriores ainda estão sendo geradas. Isso causa a quebra da ordem cronológica da conversa, fazendo com que as respostas do Concierge sejam exibidas no final da conversa em vez de serem exibidas após as mensagens correspondentes do usuário.

    Código Corrigido

    Para corrigir esse erro, é necessário implementar uma lógica que garanta a ordem cronológica da conversa. Uma possível solução é utilizar um mecanismo de fila para gerenciar as mensagens e respostas do Concierge.

    Aqui está um exemplo de código que pode ser utilizado para corrigir o erro:

    import threading
    from queue import Queue
    
    class Concierge:
        def __init__(self):
            self.message_queue = Queue()
    
        def send_message(self, message):
            self.message_queue.put(message)
    
        def process_messages(self):
            while True:
                message = self.message_queue.get()
                # Processar a mensagem e gerar a resposta
                response = self.generate_response(message)
                # Exibir a resposta na conversa
                self.display_response(response)
                self.message_queue.task_done()
    
        def generate_response(self, message):
            # Lógica para gerar a resposta do Concierge
            pass
    
        def display_response(self, response):
            # Lógica para exibir a resposta na conversa
            pass
    
    concierge = Concierge()
    threading.Thread(target=concierge.process_messages).start()
    
    # Enviar mensagens para o Concierge
    concierge.send_message("Does Expensify support QuickBooks Online?")
    concierge.send_message("Does Expensify support Certinia?")

    Nesse exemplo, o Concierge utiliza uma fila para gerenciar as mensagens e respostas. Quando o usuário envia uma mensagem, ela é adicionada à fila. O Concierge processa as mensagens na fila e gera as respostas correspondentes. As respostas são então exibidas na conversa.

    Explicação da Correção

    A correção consiste em implementar um mecanismo de fila para gerenciar as mensagens e respostas do Concierge. Isso garante que as mensagens sejam processadas na ordem em que foram enviadas e que as respostas sejam exibidas na conversa de forma cronológica.

    Além disso, a utilização de uma fila permite que o Concierge processe as mensagens de forma assíncrona, o que melhora a performance e a escalabilidade da aplicação.


    ══════════════════════════════════════════════════════
    TRABAJO ENTREGADO POR AgentWork jl1panadero@hotmail.com🔧
    Elige tu método de pago preferido:
    ══════════════════════════════════════════════════════
    💳 Stripe (tarjeta): https://buy.stripe.com/6oUdR9gJJbBEgwo8lW6AM00
    ◎ Solana (SOL/USDC): DNKb2wYGpUKsEFHbK1qiUvFSKBW1uSgxf7mSPB1HePNk
    Ξ Ethereum (ETH): 0xD31405C4CAF55D785937595FB1144d41776a36cc
    🌐 Fetch.ai (FET): 0x6600871B4a7a1D10B4081C30C2D73715482e3DfD
    ₿ Bitcoin (BTC): bc1qt4ue0u4hgwlyqaza98h9099zfqxpl5580ypng4
    ══════════════════════════════════════════════════════
    Gracias por confiar en AgentWork 🔧
    ══════════════════════════════════════════════════════


    Entregado por AgentWork v3.1
    Si necesitas un PR, puedo crearlo.

  15. andriiops commented on Jul 14, 2026

    @andriiops

    Proposal

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

    In a 1:1 Concierge chat, clicking a suggested follow-up (which has a pre-generated response) and then sending another message while that reply is still pending causes the Concierge reply to render after the newer message instead of directly beneath the question it answers — and, since PR #95002, the wrong order is now persisted server-side and survives reload.

    What is the root cause of that problem?

    In resolveSuggestedFollowup, the optimistic Concierge reply is built with createdOffset: CONCIERGE_RESPONSE_DELAY_MS (4000ms), so its created is stamped 4 seconds in the future:

    https://github.com/Expensify/App/blob/main/src/libs/actions/Report/SuggestedFollowup.ts#L88-L103

    createdOffset flows straight into the sort key:

    https://github.com/Expensify/App/blob/main/src/libs/ReportUtils.ts#L6389

    Since PR #95002, that same future timestamp is sent to the API as optimisticConciergeCreated and the backend persists the reply at exactly that position:

    https://github.com/Expensify/App/blob/main/src/libs/actions/Report/SuggestedFollowup.ts#L106-L119

    Meanwhile any message the user sends during the 4s window goes through the normal addActions path with no offset, so it gets created = getDBTimeWithSkew(Date.now()) — a value earlier than T0 + 4000:

    https://github.com/Expensify/App/blob/main/src/libs/actions/Report/index.ts#L874

    Report actions are displayed sorted by created, so once the pending Concierge action is merged into REPORT_ACTIONS it sorts after the newer user message → Q1 → Q2 → A1 instead of Q1 → A1 → Q2:

    https://github.com/Expensify/App/blob/main/src/libs/ReportActionsUtils.ts#L788-L813

    The 4s future stamp is unnecessary for display: the reveal delay is handled independently by displayAfter in PENDING_CONCIERGE_RESPONSE, which holds the action out of REPORT_ACTIONS until the timer fires:

    https://github.com/Expensify/App/blob/main/src/libs/actions/Report/SuggestedFollowup.ts#L126-L135

    So CONCIERGE_RESPONSE_DELAY_MS is doing double duty — the visual reveal delay AND the sort offset — and those two requirements conflict. The in-code comment notes a 1ms offset was "not enough", because the user's comment is stamped by a separate, later Date.now() inside addActions; the two independent clock reads couldn't be ordered reliably, which is why the offset was widened to the full 4s (overcorrecting into this bug).

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

    Derive both timestamps from a single clock read and stamp the reply 1ms after its own question — keeping the 4s purely as a display delay. This respects PR #95002's design (we still send optimisticConciergeCreated); we only make the value correct.

    In resolveSuggestedFollowup:

    const userCommentCreated = getDBTimeWithSkew();
    
    const optimisticConciergeAction = buildOptimisticAddCommentReportAction({
        text: selectedFollowup.response,
        actorAccountID: CONST.ACCOUNT_ID.CONCIERGE,
        created: DateUtils.addMillisecondsFromDateTime(userCommentCreated, 1),
        reportActionID: optimisticConciergeReportActionID,
        reportID,
        isHTML: true,
        currentUserEmail,
        currentUserAccountID,
        delegateAccountIDParam: delegateAccountID,
    });
    
    addComment({
        // ...existing params...
        created: userCommentCreated,
        pregeneratedResponseParams: {
            optimisticConciergeReportActionID,
            optimisticConciergeCreated: optimisticConciergeAction.reportAction.created,
            pregeneratedResponse: selectedFollowup.response,
        },
    });

    Supporting plumbing:

    • Add an optional created?: string to buildOptimisticAddCommentReportAction — created: created ?? getDBTimeWithSkew(Date.now() + createdOffset). Optional with the current expression as fallback, so every other caller (tasks, onboarding, attachments, plain comments) is byte-for-byte unchanged.
    • Thread the optional created through addComment → addActions to the user comment build (same pattern the existing reportActionID pass-through uses), so the user's comment and the reply share one base.
    • addOptimisticConciergeActionWithDelay / usePendingConciergeResponse untouched — displayAfter keeps driving the 4s reveal.
    • Remove the now-stale 4s-offset comment.

    Result: question stamped at T, reply at T + 1ms, so anything sent later always sorts after both — optimistically and server-side. The reply stays pinned directly beneath its own question (Q1 → A1 → Q2), which is exactly the Expected Result.

    Note: re-stamping the reply to a fresh Date.now() at apply time is intentionally NOT used — that pushes the reply to the end of the conversation (after Q2), contradicting the Expected Result that the reply stays with its corresponding user message.

    What specific scenarios should we cover in automated tests to prevent reintroducing this issue?

    1. Resolve a follow-up with a pre-generated response, add a second user comment, then apply the pending Concierge action → assert sorted order is [question1, conciergeReply1, question2].
    2. Assert the AddComment request carries optimisticConciergeCreated exactly 1ms after the user comment's created.
    3. Assert displayAfter on PENDING_CONCIERGE_RESPONSE is still ≈ now + CONCIERGE_RESPONSE_DELAY_MS (reveal delay unaffected).

    What alternative solutions did you explore? (Optional)

  16. melvin-bot commented on Jul 14, 2026

    @melvin-bot

    📣 @panandrusha-beep! 📣
    Hey, it seems we don’t have your contributor details yet! You'll only have to do this once, and this is how we'll hire you on Upwork.
    Please follow these steps:

    1. Make sure you've read and understood the contributing guidelines.
    2. Get the email address used to login to your Expensify account. If you don't already have an Expensify account, create one here. If you have multiple accounts (e.g. one for testing), please use your main account email.
    3. Get the link to your Upwork profile. It's necessary because we only pay via Upwork. You can access it by logging in, and then clicking on your name. It'll look like this. If you don't already have an account, sign up for one here.
    4. Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details.
      Screen Shot 2022-11-16 at 4 42 54 PM
      Format:
    Contributor details
    Your Expensify account email: <REPLACE EMAIL HERE>
    Upwork Profile Link: <REPLACE LINK HERE>
    
  17. andriiops commented on Jul 14, 2026

    @andriiops

    Contributor details
    Your Expensify account email: panandrusha@gmail.com
    Upwork Profile Link: https://www.upwork.com/freelancers/~01ddfdbabd386de370

  18. melvin-bot commented on Jul 14, 2026

    @melvin-bot

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

  19. neerajbachani commented on Jul 14, 2026

    @neerajbachani
    Contributor

    Proposal

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

    In a 1:1 Concierge chat, when a user taps a suggested follow-up that has a pre-generated response and then sends another message while that reply is still pending (during the ~4s “Concierge is thinking” window), the Concierge answer appears after the newer message instead of directly beneath the question it answers. Expected order is Q1 → A1 → Q2; actual order is Q1 → Q2 → A1. This matches the QA reproduction for PR #95002 and reproduces on every listed platform because sorting is shared TypeScript, not platform-specific UI.

    What is the root cause of that problem?

    Report actions are ordered primarily by each action’s created timestamp (with reportActionID only as a same-millisecond tie-break). There is no separate parent/child link that keeps a Concierge reply next to the prompt that triggered it:

    const sortedActions = reportActions?.filter(Boolean).sort((first, second) => {
    // First sort by action type, ensuring that `CREATED` actions always come first if they have the same or even a later timestamp as another action type
    if ((first.actionName === CONST.REPORT.ACTIONS.TYPE.CREATED || second.actionName === CONST.REPORT.ACTIONS.TYPE.CREATED) && first.actionName !== second.actionName) {
    return (first.actionName === CONST.REPORT.ACTIONS.TYPE.CREATED ? -1 : 1) * invertedMultiplier;
    }
    // Ensure that neither first's nor second's created property is undefined
    if (first.created === undefined || second.created === undefined) {
    return (first.created === undefined ? -1 : 1) * invertedMultiplier;
    }
    // Then sort by timestamp
    if (first.created !== second.created) {
    return (first.created < second.created ? -1 : 1) * invertedMultiplier;
    }
    // Ensure that `REPORT_PREVIEW` actions always come after if they have the same timestamp as another action type
    if ((first.actionName === CONST.REPORT.ACTIONS.TYPE.REPORT_PREVIEW || second.actionName === CONST.REPORT.ACTIONS.TYPE.REPORT_PREVIEW) && first.actionName !== second.actionName) {
    return (first.actionName === CONST.REPORT.ACTIONS.TYPE.REPORT_PREVIEW ? 1 : -1) * invertedMultiplier;
    }
    // Then fallback on reportActionID as the final sorting criteria. It is a random number,
    // but using this will ensure that the order of reportActions with the same created time and action type
    // will be consistent across all users and devices
    return (first.reportActionID < second.reportActionID ? -1 : 1) * invertedMultiplier;

    When a suggested follow-up includes a pre-generated reply, resolveSuggestedFollowup builds that optimistic Concierge action with createdOffset: CONCIERGE_RESPONSE_DELAY_MS (4000ms) — the same constant used for the visual reveal delay:

    /** Delay before showing pre-generated Concierge response (in milliseconds) */
    const CONCIERGE_RESPONSE_DELAY_MS = 4000;

    // Use the full delay as createdOffset so the Concierge response timestamp is
    // strictly after the user's comment — a 1ms offset was not enough to guarantee
    // correct sort order when both actions are queued to Onyx near-simultaneously.
    const optimisticConciergeAction = buildOptimisticAddCommentReportAction({
    text: selectedFollowup.response,
    actorAccountID: CONST.ACCOUNT_ID.CONCIERGE,
    createdOffset: CONCIERGE_RESPONSE_DELAY_MS,
    reportActionID: optimisticConciergeReportActionID,
    reportID,
    isHTML: true,
    currentUserEmail,
    currentUserAccountID,
    delegateAccountIDParam: delegateAccountID,
    });
    // Post user's comment immediately
    addComment({
    report,
    notifyReportID: notifyReportID ?? reportID,
    ancestors,
    text: selectedFollowup.text,
    timezoneParam,
    currentUserAccountID,
    shouldPlaySound: false,
    isInSidePanel: false,
    pregeneratedResponseParams: {
    optimisticConciergeReportActionID,
    optimisticConciergeCreated: optimisticConciergeAction.reportAction.created,
    pregeneratedResponse: selectedFollowup.response,
    },
    delegateAccountID,
    conciergeReportID,
    });
    addOptimisticConciergeActionWithDelay(reportID, optimisticConciergeAction);

    That offset is baked directly into the sort key:

    App/src/libs/ReportUtils.ts

    Lines 6386 to 6388 in 6d2f215

    automatic: false,
    avatar: allPersonalDetails?.[accountID]?.avatar,
    created: getDBTimeWithSkew(Date.now() + createdOffset),

    Meanwhile the user’s follow-up question is stamped later inside addActions with no offset (a separate Date.now() read):

    if (text && !file) {
    const reportComment = buildOptimisticAddCommentReportAction({text, reportID, reportActionID, delegateAccountIDParam: delegateAccountID});
    reportCommentAction = reportComment.reportAction;
    reportCommentText = reportComment.commentText;

    The 4-second reveal is already handled independently by displayAfter on PENDING_CONCIERGE_RESPONSE (consumed by usePendingConciergeResponse); created is not needed for that delay:

    function addOptimisticConciergeActionWithDelay(reportID: string, optimisticConciergeAction: OptimisticReportAction) {
    // The "Concierge is thinking..." indicator is driven by the server-owned
    // agentZeroProcessingIndicator NVP, so this client-local delayed response
    // must not also write REPORT_USER_IS_TYPING for Concierge.
    Onyx.set(`${ONYXKEYS.COLLECTION.PENDING_CONCIERGE_RESPONSE}${reportID}`, {
    reportAction: optimisticConciergeAction.reportAction,
    displayAfter: Date.now() + CONCIERGE_RESPONSE_DELAY_MS,
    });

    Race timeline (why consecutive messages break):

    1. Click follow-up at T0 → question stamps created ≈ T0.
    2. Pregenerated Concierge reply stamps created = T0 + 4000ms and is held out of the list until displayAfter.
    3. User sends another message at T0 + ~2s → that message stamps created ≈ T0 + 2s.
    4. Sort by created yields Q1 (T0) → Q2 (T0+2s) → A1 (T0+4s).

    That future created is also sent to the API as optimisticConciergeCreated (added by PR #95002), so the backend is asked to persist the reply at the same incorrect position:

    optimisticConciergeReportActionID?: string;
    optimisticConciergeCreated?: string;
    pregeneratedResponse?: string;

    // Add pregenerated params
    if (pregeneratedResponseParams) {
    parameters.optimisticConciergeReportActionID = pregeneratedResponseParams.optimisticConciergeReportActionID;
    parameters.optimisticConciergeCreated = pregeneratedResponseParams.optimisticConciergeCreated;
    parameters.pregeneratedResponse = pregeneratedResponseParams.pregeneratedResponse;
    }

    How we got here historically:

    • A 1ms createdOffset was first used to keep A1 after Q1, with reveal delay left to displayAfter (commit 9e54be51cc94).
    • That failed under two independent clock reads (Concierge built before addComment stamps the question), so PR #86382 widened the offset to the full 4s reveal delay — fixing the single-message case but opening this consecutive-message window.
    • PR #95002 correctly threads the client’s Concierge created through AddComment so reconciliation doesn’t reposition the reply, but it still transports the future-dated value from the 4s offset. This issue was filed from QA of that PR (#95002 in the issue body; jponikarchuk confirmed it on the PR). #95002 is the incomplete fix under test, not a separate PR that newly introduced the local race.

    MelvinBot’s “backend half not deployed” diagnosis is incomplete: even perfect server persistence of T0 + 4000ms still sorts A1 after any Q2 sent inside the 4s window. The App chooses the wrong anchor.

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

    Decouple the sort key from the reveal delay. Keep #95002’s optimisticConciergeCreated plumbing; only make the value it carries correct. Follow the existing Hold/Reject pattern of one shared base timestamp + 1ms for the paired action:

    const currentTime = DateUtils.getDBTime();
    const reportID = initialReportID ?? generateReportID();
    const createdReportAction = buildOptimisticHoldReportAction(currentTime);
    const createdReportActionComment = buildOptimisticHoldReportActionComment(comment, DateUtils.addMillisecondsFromDateTime(currentTime, 1));

    1. In resolveSuggestedFollowup, take one clock read and derive both timestamps from it

    const userCommentCreated = getDBTimeWithSkew();
    const optimisticConciergeAction = buildOptimisticAddCommentReportAction({
        text: selectedFollowup.response,
        actorAccountID: CONST.ACCOUNT_ID.CONCIERGE,
        created: DateUtils.addMillisecondsFromDateTime(userCommentCreated, 1),
        reportActionID: optimisticConciergeReportActionID,
        reportID,
        isHTML: true,
        currentUserEmail,
        currentUserAccountID,
        delegateAccountIDParam: delegateAccountID,
    });
    
    addComment({
        // ...existing args unchanged...
        created: userCommentCreated,
        pregeneratedResponseParams: {
            optimisticConciergeReportActionID,
            optimisticConciergeCreated: optimisticConciergeAction.reportAction.created,
            pregeneratedResponse: selectedFollowup.response,
        },
        // ...
    });

    Remove the stale comment that claims the 4s offset is required for sort order. Leave addOptimisticConciergeActionWithDelay / displayAfter: Date.now() + CONCIERGE_RESPONSE_DELAY_MS untouched so the thinking/trickle reveal pacing is unchanged.

    2. Optional created?: string on buildOptimisticAddCommentReportAction

    Today’s params only expose createdOffset (an offset from a fresh Date.now()):

    App/src/libs/ReportUtils.ts

    Lines 337 to 350 in 6d2f215

    type BuildOptimisticAddCommentReportActionParams = {
    currentUserEmail?: string;
    // TODO: This will be required eventually. Refactor issue: https://github.com/Expensify/App/issues/66412
    currentUserAccountID?: number;
    text?: string;
    file?: FileObject;
    actorAccountID?: number;
    createdOffset?: number;
    reportID?: string;
    reportActionID?: string;
    attachmentID?: string;
    isHTML?: boolean;
    delegateAccountIDParam: number | undefined;
    };

    // in BuildOptimisticAddCommentReportActionParams
    created?: string;
    
    // in the built action
    created: created ?? getDBTimeWithSkew(Date.now() + createdOffset),

    Optional fallback keeps every other caller byte-for-byte unchanged.

    3. Thread the same optional created through addComment → addActions

    Same pass-through pattern already used for reportActionID:

    // AddCommentParams / AddActionsParams
    created?: string;
    
    // in addActions when building the text comment
    const reportComment = buildOptimisticAddCommentReportAction({
        text,
        reportID,
        reportActionID,
        created,
        delegateAccountIDParam: delegateAccountID,
    });

    clientCreatedTime already reads reportCommentAction?.created, so the API stays consistent automatically.

    Resulting order: Q1 (T) → A1 (T+1ms) → Q2 (later wall clock). Both optimistic and persisted positions stay correct because optimisticConciergeCreated still carries A1’s created. Why 1ms works now but failed historically: the old 1ms offset was measured from an earlier independent Date.now() than the question’s stamp inside addActions; deriving A1 from the question’s own created removes that race by construction.

    Blast radius: Suggested-followup pregenerated path + a defaulted optional param on shared builders. Ordinary composer sends, attachments, onboarding, and non-pregenerated Concierge replies are unchanged. displayAfter / trickle / thinking indicator unchanged. #95002’s reconciliation contract is preserved — only the timestamp value becomes adjacent to its question.

    What alternative solutions did you explore? (Optional)

    1. Backend-only / “wait for Web-Expensify” (MelvinBot): incomplete. Persisting T0 + 4000ms still places A1 after any Q2 sent in the delay window. The App must stop choosing that future anchor.
    2. Just shrink createdOffset to 1ms / 50ms with two independent clock reads: reopens the original Q1/A1 race that PR #86382 documented; a small window also still breaks for a fast second message. Shared base + 1ms is required.
    3. Re-stamp Concierge created to Date.now() inside applyPendingConciergeAction: that pushes A1 to the end of the chat (after Q2), which is the reported wrong order, and desyncs from the optimisticConciergeCreated already sent at click time — undoing #95002.
    4. Special-case Concierge inside getSortedReportActions: touches the global sort path for every report list to mask one bad timestamp written in one place. Prefer fixing the value at its source.
    5. Flush / cancel the pending reply when a second message is sent: still leaves A1’s already-sent future optimisticConciergeCreated wrong on the server, and kills the intentional delayed reveal.

    What specific scenarios should we cover in automated tests?

    • Resolve a suggested follow-up with a pre-generated response, insert a second user comment whose created falls between Q1 and the old T0+4000ms Concierge stamp, apply the pending Concierge action, and assert getSortedReportActions order is chronologically [Q1, A1, Q2] (and never [Q1, Q2, A1]).
    • Assert ADD_COMMENT carries optimisticConciergeCreated equal to the pending action’s created, and that value is exactly 1ms after the user comment’s created / clientCreatedTime (update the existing “strictly after user comment” test in tests/actions/ReportTest.ts so it no longer encodes a ~4s gap as the success criterion).
    • Assert PENDING_CONCIERGE_RESPONSE.displayAfter is still approximately now + CONCIERGE_RESPONSE_DELAY_MS, so the reveal delay is unaffected by the sort-key change.
    • Non-pregenerated follow-up path (no response) still only posts the user comment and does not invent Concierge timestamps.
  20. wildan-m commented on Jul 14, 2026

    @wildan-m
    Contributor

    Proposal updated — added compare branch with implementation.

  21. FitseTLT commented on Jul 14, 2026

    @FitseTLT
    Contributor

    Not a duplicate. Every proposal posted so far fixes this by choosing a smaller client-side offset for the Concierge reply (a shared clock read plus 1–2ms, or a 50ms constant). I tested that approach end to end and it does not work — the reply still lands above its own question, deterministically when the follow-up is clicked offline, and intermittently when online. The reason is in the root cause below: the reply's timestamp is authored by the client while the question's is authored by the server, so no fixed offset can be correct. This proposal fixes the anchor instead of the offset, and also fixes a second render path that no other proposal has mentioned.

    Proposal

    What is the root cause of that problem?

    Report actions are ordered purely by created (getSortedReportActions). There are three separate defects that together produce the reported behaviour.

    1. The 4-second display delay is being used as the sort key.

    When a suggested follow-up has a pre-generated reply, the reply is built with the reveal delay as its timestamp offset (SuggestedFollowup.ts:90-96), and that offset lands directly in created (ReportUtils.ts:6389). So the reply is stamped 4 seconds in the future. Any message the user sends inside that window is stamped with the real current time and therefore sorts between the question and its reply — the reported symptom.

    The reply never needed a future timestamp. The 4-second reveal is already owned entirely by displayAfter (SuggestedFollowup.ts:139), which is what holds the action out of REPORT_ACTIONS until the timer fires (usePendingConciergeResponse.ts:138). Nothing in the reveal path reads created.

    2. The reply's timestamp is client-authored; the question's is server-authored. This is why no offset works.

    This is the part that matters, and it is why simply shrinking the offset fails.

    The reply is stamped by the client, at click time, as an absolute value. The question is not: AddComment re-stamps it with the server's created, and — I confirmed this — the AddComment response does not include the Concierge reply. So the moment the request lands, the client is holding a server-stamped question next to a client-stamped reply, and nothing ever reconciles the reply.

    The gap between those two clocks is unbounded:

    • Online, it is clock skew plus network latency. Small, and it varies — so the reply lands above its own question only sometimes. That is exactly the flakiness you get from any 1ms/2ms/50ms offset.
    • Offline, it is the entire time the request sat in the queue. Deterministic repro: go offline, click a suggested follow-up, wait 2 minutes, reconnect. The question is re-stamped ~2 minutes into the future while the reply keeps its old stamp, so the reply sits above its own question — with no second message involved at all. Clearing the cache shows the correct order, which proves the server stores the pair correctly and the defect is purely in the client's optimistic copy.

    This also explains the history that the in-code comment gets wrong. createdOffset: 1 was tried in 9e54be51cc9 and abandoned; 83358d1cbd9 widened it to the full 4s, blaming "both actions queued to Onyx near-simultaneously". That diagnosis is incorrect. 1ms did not fail because of an Onyx race — it failed because 1ms cannot bridge two clocks. The 4000ms was never a race guard; it was a latency cushion. Any fixed number is guessing at a delay it has no way to bound.

    3. The reply has two render paths, and only one of them reads the corrected timestamp.

    After the reveal, the reply renders from REPORT_ACTIONS. During the reveal, a long reply renders as a synthetic draft which ReportActionsList.tsx:223 splices into the list by its copied created — and that value is read from a snapshot taken when the effect started (usePendingConciergeResponse.ts:181). So even with a correct timestamp in Onyx, the trickling bubble still renders at the stale slot. Any fix that only corrects created leaves this path broken.

    Separately, the short-reply path applies the optimistic copy on a bare timer with no persistedAction check (usePendingConciergeResponse.ts:152), unlike the trickle path which guards against exactly this (:213). So a stale optimistic reply can overwrite the server's correct one.

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

    1. Take the display delay out of the sort key. Stop passing createdOffset: CONCIERGE_RESPONSE_DELAY_MS. Stamp the question and the reply from a single clock read, with the reply 1ms after the question. displayAfter keeps owning the 4-second reveal and the trickle, unchanged. This requires an optional explicit created on buildOptimisticAddCommentReportAction (ReportUtils.ts:6389) threaded through addComment/addActions (index.ts:874); it defaults to today's expression so every other caller is unchanged.

    2. Keep the reply anchored to its question instead of snapshotting it. This is the core of the fix, and what makes the offline and clock-skew cases correct.

    Pin the question's reportActionID when the follow-up is clicked (addComment already accepts one), store it on PENDING_CONCIERGE_RESPONSE, and carry it into CONCIERGE_PENDING_FOLLOWUP_LIST in applyPendingConciergeAction so the link survives the reveal. Then, in usePendingConciergeResponse, watch the question's created and re-derive the reply's to question + 1ms every time the question moves — writing to the pending key before the reveal, and into REPORT_ACTIONS after it.

    The client cannot predict what timestamp the server will give the question, so it must not try. Re-deriving is the only stamp it can be sure of. When AddComment finally lands — 200ms later or 2 minutes later — the reply follows the question down instead of being stranded above it.

    3. Make the trickling draft read the live created rather than the click-time snapshot, so the synthetic bubble renders in the same slot the action will land in.

    4. Give the short-reply path the same persistedAction guard the trickle path already has, so a stale optimistic reply can never clobber the canonical one.

    The result: the reply sits directly beneath the question it answers, whatever timestamp the server assigns that question, online or offline — and the "Concierge is thinking…" pause and trickle animation are untouched.

    What alternative solutions did you explore? (Optional)

    • A smaller offset from a second clock read (1ms, 2ms, or a 50ms constant) — the approach taken by every other proposal here. It cannot work, for the reason in root cause 2: the required offset is clock skew plus network latency, which is unbounded (offline it is minutes). This is the same class of fix that already failed once and was widened to 4000ms.
    • Re-stamping the reply at reveal time, from Date.now() or from a stored click time. Still a snapshot — the question moves after the reveal when the request was queued offline, so the reply is stranded again.
    • A backend clamp on optimisticConciergeCreated. Unnecessary: the server already persists the pair in the correct order (clearing the cache after every repro shows the right order). The defect is entirely in the client's optimistic copy.
    • Special-casing Concierge replies inside getSortedReportActions. That changes a hot path used by every report in the app to compensate for one bad timestamp written in one place.
  22. godzillaxbox19982014-lgtm commented on Jul 14, 2026

    @godzillaxbox19982014-lgtm

    A small clarification to my earlier comment: the Workspace component paths I cited are not involved in this flow.

    One additional verified detail in the actual pending-response path: correcting PENDING_CONCIERGE_RESPONSE.reportAction.created without changing the action ID will not reach a short reply. usePendingConciergeResponse snapshots reportAction and displayAfter, then its binary branch schedules that captured object (usePendingConciergeResponse.ts:125-153). Although later Onyx values refresh trickleInputsRef (lines 57-60), this effect only depends on reportID and reportActionID (lines 274-283), so a same-ID created change neither restarts the timer nor changes the object it will merge.

    Therefore, timestamp reconciliation must also make the binary timer read the latest pending action (or rerun when created changes); a persisted-action guard alone does not cover this case. Add a regression that queues a short reply at T, updates the same pending ID to T′ before displayAfter, advances the timer, and asserts REPORT_ACTIONS[id].created === T′. Otherwise the short path can restore the stale order even after pending state was corrected.

  23. Dip-G-Git commented on Jul 15, 2026

    @Dip-G-Git

    🚫 Duplicated proposal withdrawn by 🤖 ProposalPolice.

  24. github-actions commented on Jul 15, 2026

    @github-actions
    Contributor

    ⚠️ @Dip-G-Git Your proposal is a duplicate of an already existing proposal and has been automatically withdrawn to prevent spam. Please review the existing proposals before submitting a new one.

  25. bernhardoj commented on Jul 15, 2026

    @bernhardoj
    Contributor

    @inimaga I don't think this is a bug.

    I can't reproduce the "Concierge is thinking..." message when selecting the follow-up options, but I do see it when sending a normal message. "Concierge is thinking..." is not a real message, it's technically a header, an indicator that concierge is processing the message, so it's always shown at the bottom of the chat (list is inverted).

    function ReportActionsListHeader({reportID, hasActiveDraft}: ReportActionsListHeaderProps) {
    if (hasActiveDraft) {
    return null;
    }
    return <ConciergeThinkingMessage reportID={reportID} />;
    }

    So, when we send more messages before the processing is done, it makes sense that the concierge responses will be at the end.

  26. inimaga commented on Jul 15, 2026

    @inimaga
    Contributor

    @bernhardoj Yeah, I agree with your assessment. I am able to reproduce but this behaviour is as intended. We just recently had a couple of PRs merged for this current order. Closing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

BugSomething is broken. Auto assigns a BugZero manager.DailyKSv2ExternalAdded to denote the issue can be worked on by a contributorHelp WantedApply this label when an issue is open to proposals by contributors

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions