App icon indicating copy to clipboard operation
App copied to clipboard

[$175] Company Card- Card feed is removed in 1st workspace after share with 2nd workspace

Open applause-bot[bot] opened this issue 4 weeks ago • 36 comments

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


Version Number: 9.5.31-0 Reproducible in staging?: Yes Reproducible in production?: Yes If this was caught during regression testing, add the test name, ID and link from BrowserStack: https://github.com/Expensify/App/pull/104160 Email or phone of affected tester (no customers): [email protected] Issue reported by: Applause Internal Team Bug source: Exploratory - Critical User Impact Device used: Windows 11 Chrome App Component: Workspace Settings

Action Performed:

Preconditions:

  • Use E account, create 1 workspace, enable Company Card
  1. Open https://staging.new.expensify.com/
  2. Go to workspace settings
  3. Open Company Card
  4. Add a card feed (Mock commercial card)
  5. Create 2nd workspace
  6. Go to 2nd workspace settings
  7. Open Company Card
  8. Click Add cards
  9. Select Card feed from 1st Workspace
  10. Navigate to 1st Workspace settings
  11. Open Company Card

Expected Result:

The Card feed should be still displayed in 1st Workspace Company card

Actual Result:

The Card feed is removed in 1st Workspace Company card, after share it to 2nd workspace

Workaround:

Unknown

Platforms:

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

Screenshots/Videos

https://github.com/user-attachments/assets/12e823a6-0f2f-4e71-b08c-1b50d6cb5b56

View all open jobs on GitHub

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

Upwork Automation - Do Not Edit
Issue OwnerCurrent Issue Owner: @stitesExpensify

applause-bot[bot] avatar Nov 04 '26 03:11 applause-bot[bot]

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

applause-bot[bot] avatar Nov 04 '26 03:11 applause-bot[bot]

🤖 Web test steps verification results: ⚠️ partial

Verified on dev NewDot web through opening Company Cards in workspace A. Adding cards requires an emailed security code, blocking the mock feed setup and disappearance test.

Account validation blocks adding a company card feed
Step Status
1: Open workspace A settingsCreated workspace A and opened its settings.
✅
2: Open Company CardsCompany cards opened with Add cards available.
✅
3: Add a Mock commercial card feedBlocked: Add cards opened Validate your account, requiring a six-digit emailed security code. No feed was added.
Account validation blocks adding a company card feed
⚠️
4: Create workspace BNot executed after the account-validation blocker.
⚠️
5: Open B settingsNot executed; workspace B was not created.
⚠️
6: Open Company CardsNot executed in workspace B.
⚠️
7: Click Add cardsNot executed in workspace B.
⚠️
8: Select A’s existing card feedBlocked; no feed could be created in workspace A.
⚠️
9: Return to A settingsNot executed after the account-validation blocker.
⚠️
10: Check whether A’s original feed remains visibleUnverified because the required feed could not be created.
⚠️

view run

MelvinBot avatar Nov 04 '26 03:11 MelvinBot

⚠️ Preliminary analysis (low confidence) — treat as a starting point, not a conclusion.

Sharing may hide the original workspace’s feed because the client switches from implicit ownership to explicit workspace links. The triggering data remains unverified; this is not a confirmed deletion.

Code evidence and alternative explanations
  • useCardFeeds.tsx:55–69 ignores original ownership once linkedPolicyIDs is nonempty. If sharing produces only workspace B’s ID, workspace A loses visibility.
  • CardFeedUtils.ts:396–409 applies the same precedence when grouping feeds.
  • CompanyCards.ts:1584–1605 requests the link without optimistically changing memberships. This argues against a local action overwriting workspace A.

An incomplete server association list and a client/server membership-contract mismatch remain possible. Do not blindly include original ownership: it could restore intentionally removed access.

To confirm: Compare feed memberships before sharing, the LinkCardFeedToPolicy response, and a fresh reload. If both workspace IDs remain present, this hypothesis is wrong. If server-side membership loses A, escalate to an internal engineer; that fix is outside App.

Verification limits: Web testing stopped at emailed account validation. Production logs were unavailable.


Next Steps: Reply with @MelvinBot <your feedback> to refine this analysis.


view run · view recording

MelvinBot avatar Nov 04 '26 03:11 MelvinBot

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

melvin-bot[bot] avatar Nov 04 '26 03:11 melvin-bot[bot]

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

melvin-bot[bot] avatar Nov 04 '26 03:11 melvin-bot[bot]

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

Proposal

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

When a company card feed (e.g. Mock commercial card, direct feed, or custom feed) is created in Workspace A, and subsequently shared with Workspace B via Workspace Settings > Company Cards > Add cards > Select Card feed from 1st Workspace, navigating back to Workspace A causes the card feed to disappear from Workspace A's Company Cards page.

What is the root cause of that problem?

  1. In src/hooks/useCardFeeds.tsx (lines 58–69):
const upperPolicyID = policyID.toUpperCase();
const shouldIncludeFeedPredicate = (combinedCardFeed: CombinedCardFeed) => {
    const validLinkedPolicyIDs = combinedCardFeed?.linkedPolicyIDs?.filter(Boolean);
    if (validLinkedPolicyIDs?.length) {
        return validLinkedPolicyIDs.some((linkedPolicyID) => linkedPolicyID.toUpperCase() === upperPolicyID);
    }
    return combinedCardFeed.preferredPolicy ? combinedCardFeed.preferredPolicy === policyID : combinedCardFeed.domainID === effectiveWorkspaceAccountID;
};

When a card feed is initially configured in Workspace A, combinedCardFeed.preferredPolicy is set to Workspace A's ID, and linkedPolicyIDs is empty/undefined. When Workspace B links the card feed using linkCardFeedToPolicy, Workspace B is added to linkedPolicyIDs. Upon navigating back to Workspace A, useCardFeeds(workspaceA_ID) executes. Because validLinkedPolicyIDs is now non-empty (['WORKSPACE_B']), the function enters the if (validLinkedPolicyIDs?.length) branch. It checks whether validLinkedPolicyIDs contains Workspace A. Because validLinkedPolicyIDs only contains Workspace B (Workspace A is recorded as preferredPolicy), validLinkedPolicyIDs.some(...) returns false. Crucially, because of the early return, the fallback combinedCardFeed.preferredPolicy ? combinedCardFeed.preferredPolicy === policyID : ... is never evaluated. Workspace A therefore loses visibility of its own card feed.

  1. A corresponding mutual exclusion occurs in src/libs/CardFeedUtils.ts (lines 400–410) in getCardFeedsForDisplayPerPolicy:
const validLinkedPolicyIDs = linkedPolicyIDs?.filter(Boolean);
if (validLinkedPolicyIDs?.length) {
    for (const linkedPolicyID of validLinkedPolicyIDs) {
        (cardFeedsForDisplayPerPolicy[linkedPolicyID] ||= []).push(feedEntry);
    }
} else if (preferredPolicy) {
    (cardFeedsForDisplayPerPolicy[preferredPolicy] ||= []).push(feedEntry);
}

The if ... else if structure indexes the feed only under validLinkedPolicyIDs if present, completely bypassing else if (preferredPolicy). Consequently, the original workspace is omitted from cardFeedsForDisplayPerPolicy.

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

  1. In src/hooks/useCardFeeds.tsx (lines 58–69): Allow shouldIncludeFeedPredicate to include the feed if the active policy matches linkedPolicyIDs OR matches preferredPolicy (or the domain account ID fallback):
--- a/src/hooks/useCardFeeds.tsx
+++ b/src/hooks/useCardFeeds.tsx
@@ -57,11 +57,10 @@ const useCardFeeds = (policyID: string | undefined): [CombinedCardFeeds | undefi
         const upperPolicyID = policyID.toUpperCase();
         const shouldIncludeFeedPredicate = (combinedCardFeed: CombinedCardFeed) => {
             const validLinkedPolicyIDs = combinedCardFeed?.linkedPolicyIDs?.filter(Boolean);
-            if (validLinkedPolicyIDs?.length) {
-                // Linked policy IDs can differ in casing, so compare case-insensitively. This keeps the "available"
-                // list aligned with the case-insensitive "From other workspaces" check in useOtherFeedsForFeedSelector,
-                // so a case-mismatched linked feed isn't dropped from both lists and lost.
-                return validLinkedPolicyIDs.some((linkedPolicyID) => linkedPolicyID.toUpperCase() === upperPolicyID);
+            const isLinkedToPolicy = !!validLinkedPolicyIDs?.length && validLinkedPolicyIDs.some((linkedPolicyID) => linkedPolicyID.toUpperCase() === upperPolicyID);
+            if (isLinkedToPolicy) {
+                return true;
             }
-            return combinedCardFeed.preferredPolicy ? combinedCardFeed.preferredPolicy === policyID : combinedCardFeed.domainID === effectiveWorkspaceAccountID;
+            return combinedCardFeed.preferredPolicy ? combinedCardFeed.preferredPolicy.toUpperCase() === upperPolicyID : combinedCardFeed.domainID === effectiveWorkspaceAccountID;
         };
         workspaceFeeds = getCombinedCardFeedsFromAllFeeds(allFeeds, shouldIncludeFeedPredicate, feedKeysWithCards);
     }
  1. In src/libs/CardFeedUtils.ts (lines 400–410): In getCardFeedsForDisplayPerPolicy, collect all target policy IDs (validLinkedPolicyIDs and preferredPolicy) using a Set<string> so the originating workspace and all linked workspaces retain their display entry:
--- a/src/libs/CardFeedUtils.ts
+++ b/src/libs/CardFeedUtils.ts
@@ -398,12 +398,17 @@ function getCardFeedsForDisplayPerPolicy(
             };

             const validLinkedPolicyIDs = linkedPolicyIDs?.filter(Boolean);
+            const targetPolicyIDs = new Set<string>();
             if (validLinkedPolicyIDs?.length) {
-                // Index the feed under each linked policy so it appears for all of them
                 for (const linkedPolicyID of validLinkedPolicyIDs) {
-                    (cardFeedsForDisplayPerPolicy[linkedPolicyID] ||= []).push(feedEntry);
+                    targetPolicyIDs.add(linkedPolicyID);
                 }
-            } else if (preferredPolicy) {
-                (cardFeedsForDisplayPerPolicy[preferredPolicy] ||= []).push(feedEntry);
+            }
+            if (preferredPolicy) {
+                targetPolicyIDs.add(preferredPolicy);
+            }
+            if (targetPolicyIDs.size > 0) {
+                for (const targetPolicyID of targetPolicyIDs) {
+                    (cardFeedsForDisplayPerPolicy[targetPolicyID] ||= []).push(feedEntry);
+                }
             } else {
  1. In src/hooks/useOtherFeedsForFeedSelector.tsx (lines 65–75): Ensure that feeds where preferredPolicy matches the active policy are also excluded from the "From other workspaces" list (since the active policy already owns the feed):
--- a/src/hooks/useOtherFeedsForFeedSelector.tsx
+++ b/src/hooks/useOtherFeedsForFeedSelector.tsx
@@ -67,6 +67,9 @@ function useOtherFeedsForFeedSelector({policyID}: UseOtherFeedsForFeedSelectorPr
             // Feeds linked to the active policy are shown as available feeds, not under "From other workspaces".
             // Linked policy IDs can differ in casing, so compare case-insensitively (matches the Expensify-card path).
             if (feed?.linkedPolicyIDs?.filter(Boolean).some((linkedPolicyID) => linkedPolicyID.toUpperCase() === upperPolicyID)) {
+                continue;
+            }
+            if (feed?.preferredPolicy && feed.preferredPolicy.toUpperCase() === upperPolicyID) {
                 continue;
             }

What alternative solutions did you explore? (Optional)

  • Forcing the backend to append the originating preferredPolicy into linkedPolicyIDs upon linking. This was rejected because client-side hooks must be resilient and maintain compatibility with both legacy domain-based feeds (where preferredPolicy holds the primary workspace) and multi-workspace shared feeds without requiring backend schema migrations.

What automated tests can you add to prevent this from re-occurring?

  1. In tests/unit/hooks/useCardFeeds.test.ts: Add a unit test verifying that a domain feed remains included when preferredPolicy matches the active workspace, even if linkedPolicyIDs contains other policies:
it('includes domain feeds when preferredPolicy matches even if linkedPolicyIDs contains other policies (shared feed)', async () => {
    await setupDomainFeed({preferredPolicy: policyID, linkedPolicyIDs: ['OTHER_POLICY']});

    const {result} = renderHook(() => useCardFeeds(policyID));
    await waitForBatchedUpdates();

    await waitFor(() => expect(result.current[0]).toHaveProperty([combinedFeedKey]));
});
  1. In tests/unit/CardFeedUtilsTest.ts: Add a unit test verifying that getCardFeedsForDisplayPerPolicy indexes the feed under both preferredPolicy and linkedPolicyIDs:
it('indexes feed under both preferredPolicy and linkedPolicyIDs when both are present', () => {
    const cardFeedsWithBoth = createCompanyCardFeeds({
        [cardFeedMock]: {preferredPolicy: 'POLICY_A', linkedPolicyIDs: ['POLICY_B']},
    });
    const result = getCardFeedsForDisplayPerPolicy(cardFeedsWithBoth, translateLocal, undefined, undefined);
    expect(result.POLICY_A).toBeDefined();
    expect(result.POLICY_B).toBeDefined();
});

andregrunert-ctrl avatar Nov 04 '26 03:11 andregrunert-ctrl

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

melvin-bot[bot] avatar Nov 04 '26 03:11 melvin-bot[bot]

Proposal

Audit verdict: insufficient evidence for a submission-ready fix. The reported symptom is clear, but the responsible mutation and affected-version code remain unverified. An exact TypeScript patch would currently depend on assumptions.

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

Sharing a company card feed from workspace A with workspace B reportedly makes the feed disappear from workspace A’s Company Cards page. Sharing should preserve its availability in both workspaces.

The report demonstrates a visibility problem; it does not establish that the underlying feed or transactions were deleted.

What is the root cause of that problem?

Not yet established. There is no Expensify checkout in the supplied workspace, and I could not retrieve the affected version or PR #104160.

The inspected public main snapshot provides a precise investigation point: src/hooks/useCardFeeds.tsx, lines 54–64. Its predicate:

  • Uses a nonempty linkedPolicyIDs list as the membership criterion.
  • Falls back to preferredPolicy, then the effective workspace account ID, when that list is absent or empty.
  • Already supports multiple linked workspaces.

I executed three synthetic checks against a transcription of that predicate:

Input                                         Visible in A   Visible in B
preferredPolicy=A, linkedPolicyIDs=[A,B]        true           true
preferredPolicy=A, linkedPolicyIDs=[B]          false          true
preferredPolicy=A, no linkedPolicyIDs          true           false

These checks establish predicate behavior only. They do not prove which state the sharing action produces.

Two materially different explanations remain:

  1. Sharing incorrectly replaces existing membership with [B].
  2. Membership intentionally excludes the origin, but the display logic incorrectly treats it as exhaustive.

Neither explanation qualifies as a confirmed finding without the sharing mutation and its actual input/output.

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

Do not apply a speculative diff. First capture the feed’s settings.companyCards[feedName] before sharing, after the optimistic update, after the server response, and after reload.

The smallest valid fix depends on that evidence:

  • If sharing overwrites membership: correct the responsible mutation to preserve existing memberships and add B. Verify persistence and failure rollback.
  • If the membership contract includes origin visibility separately: correct the predicate at the affected revision, with explicit coverage for unlinking and reassignment.
  • If the server returns incorrect persisted membership: a client display change alone cannot establish that sharing was fixed.

A blanket fallback such as this is rejected pending contract verification:

isLinkedToPolicy || feed.preferredPolicy === policyID

It could restore visibility after an intentional unlink if preferredPolicy remains populated. The supplied evidence does not establish whether that state is valid.

Exact affected-version line numbers, a production patch, and passing Jest results cannot honestly be supplied from the available evidence.

What alternative solutions did you explore? (Optional)

No MelvinBot proposal was supplied, so there is no proposal to dismantle or claim superiority over.

Rejected approaches:

  • Adding linked-policy support without checking the affected revision: the inspected snapshot already contains it.
  • Changing preferredPolicy to B: this does not demonstrate preserved membership in A.
  • Forcing a refresh: this does not repair incorrect persisted membership.

Duplicate and existing-fix status remain unverified because the issue URL and discussion were not supplied.

What automated tests can you add to prevent this from re-occurring?

Add an Onyx-backed Jest hook regression named:

it('keeps a shared company card feed visible in both workspaces')

It should seed the actual pre-share fixture, mount useCardFeeds for A and B, execute the real sharing action, and assert:

  1. A retains the feed throughout the optimistic update.
  2. B gains the same feed identity.
  3. Both retain it after the recorded successful server response and reload.

Add separate cases for failed-share rollback, repeated sharing, sharing with a third workspace, and intentional unlinking.

Validation performed: three synthetic predicate checks passed. No application reproduction, repository Jest run, TypeScript check, or lint run was performed.

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

camesenin avatar Nov 04 '26 04:11 camesenin

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

melvin-bot[bot] avatar Nov 04 '26 04:11 melvin-bot[bot]

Proposal

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

When a company card feed created in Workspace 1 (Policy A) is shared with Workspace 2 (Policy B) via Workspace 2 Settings > Company Card > Add cards > Select Card feed from 1st Workspace, navigating back to Workspace 1 shows that the card feed has disappeared from Workspace 1.

What is the root cause of that problem?

In both src/hooks/useCardFeeds.tsx and src/libs/CardFeedUtils.ts, the logic for determining which workspace policy can display a feed treats linkedPolicyIDs and preferredPolicy as mutually exclusive alternatives (if / else if branching):

  1. In src/hooks/useCardFeeds.tsx (lines 62–71):
const upperPolicyID = policyID.toUpperCase();
const shouldIncludeFeedPredicate = (combinedCardFeed: CombinedCardFeed) => {
    const validLinkedPolicyIDs = combinedCardFeed?.linkedPolicyIDs?.filter(Boolean);
    if (validLinkedPolicyIDs?.length) {
        return validLinkedPolicyIDs.some((linkedPolicyID) => linkedPolicyID.toUpperCase() === upperPolicyID);
    }
    return combinedCardFeed.preferredPolicy ? combinedCardFeed.preferredPolicy === policyID : combinedCardFeed.domainID === effectiveWorkspaceAccountID;
};
  1. In src/libs/CardFeedUtils.ts (getCardFeedsForDisplayPerPolicy, lines 868–880):
const validLinkedPolicyIDs = linkedPolicyIDs?.filter(Boolean);
if (validLinkedPolicyIDs?.length) {
    for (const linkedPolicyID of validLinkedPolicyIDs) {
        (cardFeedsForDisplayPerPolicy[linkedPolicyID] ||= []).push(feedEntry);
    }
} else if (preferredPolicy) {
    (cardFeedsForDisplayPerPolicy[preferredPolicy] ||= []).push(feedEntry);
}

What happens during the sharing flow:

  • When the feed is initially added in Workspace 1, preferredPolicy is set to Workspace 1 (Policy A) and linkedPolicyIDs is empty (undefined or []). Because validLinkedPolicyIDs?.length is falsy, the fallback branch executes (combinedCardFeed.preferredPolicy === policyID), and Workspace 1 displays the feed.
  • When Workspace 2 (Policy B) links the existing feed via linkCardFeedToPolicy, Workspace 2 is added to linkedPolicyIDs (linkedPolicyIDs = ['Policy B']). Notice that preferredPolicy remains Policy A (Workspace 1).
  • When the user navigates back to Workspace 1 (policyID = Policy A), useCardFeeds(Policy A) evaluates shouldIncludeFeedPredicate:
    • validLinkedPolicyIDs?.length is now 1 (['Policy B'], which is truthy).
    • The hook immediately executes the if block: validLinkedPolicyIDs.some((linkedPolicyID) => linkedPolicyID.toUpperCase() === upperPolicyID).
    • Because ['Policy B'] does not include Policy A, this returns false.
    • The fallback combinedCardFeed.preferredPolicy === policyID is never reached.
  • Consequently, the feed is completely dropped from Workspace 1's workspaceFeeds, removing the card feed from Workspace 1's UI.

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

A company card feed belongs to a workspace if the workspace is the feed's original owner (preferredPolicy) OR if the workspace is in linkedPolicyIDs.

1. Fix src/hooks/useCardFeeds.tsx:

Update shouldIncludeFeedPredicate so that having linkedPolicyIDs does not bypass the preferredPolicy check:

--- a/src/hooks/useCardFeeds.tsx
+++ b/src/hooks/useCardFeeds.tsx
@@ -62,10 +62,12 @@ const useCardFeeds = (policyID: string | undefined): [CombinedCardFeeds | undef
         // `policyID` is stable for this hook invocation, so uppercase it once instead of per feed evaluation.
         const upperPolicyID = policyID.toUpperCase();
         const shouldIncludeFeedPredicate = (combinedCardFeed: CombinedCardFeed) => {
+            const isPreferredPolicy = combinedCardFeed.preferredPolicy ? combinedCardFeed.preferredPolicy.toUpperCase() === upperPolicyID : combinedCardFeed.domainID === effectiveWorkspaceAccountID;
             const validLinkedPolicyIDs = combinedCardFeed?.linkedPolicyIDs?.filter(Boolean);
-            if (validLinkedPolicyIDs?.length) {
-                return validLinkedPolicyIDs.some((linkedPolicyID) => linkedPolicyID.toUpperCase() === upperPolicyID);
-            }
-            return combinedCardFeed.preferredPolicy ? combinedCardFeed.preferredPolicy === policyID : combinedCardFeed.domainID === effectiveWorkspaceAccountID;
+            const isLinkedPolicy = !!validLinkedPolicyIDs?.length && validLinkedPolicyIDs.some((linkedPolicyID) => linkedPolicyID.toUpperCase() === upperPolicyID);
+            return isPreferredPolicy || isLinkedPolicy;
         };
         workspaceFeeds = getCombinedCardFeedsFromAllFeeds(allFeeds, shouldIncludeFeedPredicate, feedKeysWithCards);
     }

2. Fix src/libs/CardFeedUtils.ts:

In getCardFeedsForDisplayPerPolicy, index the feed under both preferredPolicy and all linkedPolicyIDs:

--- a/src/libs/CardFeedUtils.ts
+++ b/src/libs/CardFeedUtils.ts
@@ -871,11 +871,15 @@ function getCardFeedsForDisplayPerPolicy(
 
             const validLinkedPolicyIDs = linkedPolicyIDs?.filter(Boolean);
+            const allAssociatedPolicyIDs = new Set<string>();
+            if (preferredPolicy) {
+                allAssociatedPolicyIDs.add(preferredPolicy);
+            }
             if (validLinkedPolicyIDs?.length) {
-                // Index the feed under each linked policy so it appears for all of them
                 for (const linkedPolicyID of validLinkedPolicyIDs) {
-                    (cardFeedsForDisplayPerPolicy[linkedPolicyID] ||= []).push(feedEntry);
+                    allAssociatedPolicyIDs.add(linkedPolicyID);
                 }
-            } else if (preferredPolicy) {
-                (cardFeedsForDisplayPerPolicy[preferredPolicy] ||= []).push(feedEntry);
+            }
+            if (allAssociatedPolicyIDs.size > 0) {
+                for (const associatedPolicyID of allAssociatedPolicyIDs) {
+                    (cardFeedsForDisplayPerPolicy[associatedPolicyID] ||= []).push(feedEntry);
+                }
             } else {

What alternative solutions did you explore? (Optional)

  • Adding the preferredPolicy ID into linkedPolicyIDs when linking to Workspace B: Rejected because linkedPolicyIDs is managed by backend API calls (LINK_CARD_FEED_TO_POLICY). Fixing the client predicate in useCardFeeds and getCardFeedsForDisplayPerPolicy properly honors the data contract where preferredPolicy represents origin and linkedPolicyIDs represents shared workspaces, without requiring backend schema changes or migration scripts.

What automated tests can you add to prevent this from re-occurring?

In tests/unit/hooks/useCardFeeds.test.ts:

  • Add a test:
    it('returns the feed for the preferredPolicy even when linkedPolicyIDs is populated with another policy', async () => {
        const policyA = 'POLICY_A';
        const policyB = 'POLICY_B';
        await Onyx.merge(`${ONYXKEYS.COLLECTION.POLICY}${policyA}`, {id: policyA, policyAccountID: domainID});
        await Onyx.merge(`${ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_DOMAIN_MEMBER}${domainID}`, {
            settings: {
                companyCards: {
                    [oldStyleFeed]: {
                        preferredPolicy: policyA,
                        linkedPolicyIDs: [policyB],
                    },
                },
            },
        });
        const {result} = renderHook(() => useCardFeeds(policyA));
        await waitFor(() => {
            const [workspaceFeeds] = result.current;
            expect(Object.keys(workspaceFeeds ?? {}).length).toBeGreaterThan(0);
        });
    });
    

In tests/unit/CardFeedUtilsTest.ts:

  • Verify getCardFeedsForDisplayPerPolicy indexes a feed under both its preferredPolicy and all entries in linkedPolicyIDs.

Contributor Track Record & Details

  • Proven Open-Source Contributor: Successfully merged pull requests in major enterprise repositories:
    • Vercel AI SDK: vercel/ai#24352 (fix(mistral): preserve Large 4 supported reasoning levels)
    • Microsoft .NET runtime: dotnet/runtime#136828 (Fix event handle leak in ThreadPoolWaitOrTimerCallback)
  • Ready for Immediate Execution: Development environment fully configured, ready to push a clean PR with passing Jest tests immediately upon assignment.

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

sumit-2007-git avatar Nov 04 '26 05:11 sumit-2007-git

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

melvin-bot[bot] avatar Nov 04 '26 05:11 melvin-bot[bot]

Proposal

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

A company card feed added in Workspace A disappears from A's Company Cards page once Workspace B links the same feed through Add cards > From other workspaces. The feed should show in both workspaces.

What is the root cause of that problem?

The App has no single rule for "which workspaces does this feed belong to". Each place answers it on its own, and most of them treat linkedPolicyIDs as the complete list as soon as it isn't empty, which throws away preferredPolicy.

  1. A feed created in A only has preferredPolicy: A, with no linkedPolicyIDs. Linking it from B (linkCardFeedToPolicy, src/libs/actions/CompanyCards.ts:1498) makes the backend send linkedPolicyIDs: [B]. A is still only stored as preferredPolicy.

  2. src/hooks/useCardFeeds.tsx:59-67 returns early on the linked list, so the preferredPolicy fallback is never reached for A:

    if (validLinkedPolicyIDs?.length) {
        return validLinkedPolicyIDs.some((linkedPolicyID) => linkedPolicyID.toUpperCase() === upperPolicyID);
    }
    return combinedCardFeed.preferredPolicy ? combinedCardFeed.preferredPolicy === policyID : ...
    
  3. The same "linked list or preferred policy" rule appears in other places:

    • src/libs/CardFeedUtils.ts:396-403 (getCardFeedsForDisplayPerPolicy): if (validLinkedPolicyIDs?.length) {...} else if (preferredPolicy) {...}.
    • src/libs/CardFeedUtils.ts:335-336 (getAssignedCardFeedAccess): linkedPolicyIDs.length ? linkedPolicyIDs : [feedSettings?.preferredPolicy].
    • src/hooks/useOtherFeedsForFeedSelector.tsx:64 only checks linkedPolicyIDs. So in A, the feed moves to "From other workspaces", as if it belonged to B.
  4. One function in the same file already treats the two fields as a union. getPolicyIDsNamedByCardFeeds (CardFeedUtils.ts:293-309) adds every linkedPolicyIDs entry and preferredPolicy. Because the rules disagree, A loses the feed in some places and keeps it in others.

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

Add one helper that every feed-to-workspace check uses, based on the union rule that getPolicyIDsNamedByCardFeeds already follows.

  1. In src/libs/CardFeedUtils.ts, add the helper:

    /** Every workspace a feed belongs to: the workspaces it's linked to, plus the one it was created in. Compared case-insensitively. */
    function getPolicyIDsForFeed(feedSettings: {linkedPolicyIDs?: string[]; preferredPolicy?: string} | undefined): string[] {
        const policyIDs = [...(feedSettings?.linkedPolicyIDs ?? []), feedSettings?.preferredPolicy].filter((policyID): policyID is string => !!policyID);
        return policyIDs.filter((policyID, index) => policyIDs.findIndex((otherID) => otherID.toUpperCase() === policyID.toUpperCase()) === index);
    }
    
    function isFeedInPolicy(feedSettings: Parameters<typeof getPolicyIDsForFeed>[0], policyID: string): boolean {
        return getPolicyIDsForFeed(feedSettings).some((feedPolicyID) => feedPolicyID.toUpperCase() === policyID.toUpperCase());
    }
    
  2. Use it in useCardFeeds.tsx, keeping the domain fallback for feeds that name no workspace:

    const shouldIncludeFeedPredicate = (combinedCardFeed: CombinedCardFeed) => {
        if (getPolicyIDsForFeed(combinedCardFeed).length) {
            return isFeedInPolicy(combinedCardFeed, policyID);
        }
        return combinedCardFeed.domainID === effectiveWorkspaceAccountID;
    };
    
  3. Use it in getCardFeedsForDisplayPerPolicy (CardFeedUtils.ts:396), so the feed is listed under A and B:

    const feedPolicyIDs = getPolicyIDsForFeed({linkedPolicyIDs, preferredPolicy});
    if (feedPolicyIDs.length) {
        for (const feedPolicyID of feedPolicyIDs) {
            (cardFeedsForDisplayPerPolicy[feedPolicyID] ||= []).push(feedEntry);
        }
    } else {
        // orphan-feed fallback unchanged
    }
    
  4. Use the same helper in getAssignedCardFeedAccess (CardFeedUtils.ts:336) and in useOtherFeedsForFeedSelector.tsx:64:

    if (isFeedInPolicy(feed, policyID)) {
        continue;
    }
    

    A card holder in A then keeps their "Fix feed" link, and A's feed selector no longer offers the feed under "From other workspaces".

  5. Add a unit test for the helper. With all the checks going through one function, a future change can't fix one page and leave the others broken.

Note for the internal engineer: the backend could also seed linkedPolicyIDs with the original preferredPolicy the first time a feed is shared ([A, B] instead of [B]). The App change works either way. When a workspace unlinks a feed, the backend should clear preferredPolicy along with the link, so the union doesn't bring the feed back.

What alternative solutions did you explore? (Optional)

  • Only add || preferredPolicy === policyID to useCardFeeds. This shows the feed on A's main page, but getCardFeedsForDisplayPerPolicy, the wallet "fix feed" link and the "From other workspaces" list would still disagree.
  • Backend-only fix (seed [A, B]). This fixes new shares, but feeds that are already shared stay hidden until the backend migrates them.

Automated Tests

In tests/unit/CardFeedUtilsTest.ts:

  • Given preferredPolicy: A and linkedPolicyIDs: ['B']. When getPolicyIDsForFeed runs. Then it returns [B, A], and getCardFeedsForDisplayPerPolicy lists the feed under both A and B.
  • Given linkedPolicyIDs: ['a'] and preferredPolicy: 'A'. When the helper runs. Then A appears once (case-insensitive dedupe).
  • Given a feed with neither field. When grouped. Then the existing orphan or fund fallback still applies.

In tests/unit/hooks/useCardFeedsTest.ts:

  • Given a feed created in A and then linked to B. When useCardFeeds(A) and useCardFeeds(B) run. Then both include the feed.

In tests/unit/hooks/useOtherFeedsForFeedSelectorTest.ts:

  • Given the same feed. When A's selector runs. Then the feed isn't listed under "From other workspaces".

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

voxturrlabs avatar Nov 04 '26 05:11 voxturrlabs

Problem: A company card feed added to workspace A disappears from A's Company Cards page after it is shared with workspace B (2nd workspace settings > Company Card > Add cards > select the feed from the 1st workspace). Sharing should leave the feed visible in both workspaces.

Root cause: The share path and the display path point at the same persisted membership, and the link step replaces it instead of extending it. Sharing runs through WorkspaceCompanyCardFeedSelectorPage linkOtherWorkspaceFeed, which calls linkCardFeedToPolicy in src/libs/actions/CompanyCards.ts with the 2nd workspace's policyID. That call carries no optimistic Onyx update, so what workspace A shows afterwards is exactly the feed state the link operation persists. On the display side, both consumers already handle multi-workspace membership correctly: the useCardFeeds predicate in src/hooks/useCardFeeds.tsx and the per-policy indexing in getCardFeedsForDisplayPerPolicy in src/libs/CardFeedUtils.ts show a feed under a workspace when that workspace is in its linkedPolicyIDs, falling back to preferredPolicy only when no linked list exists. Workspace A therefore drops out only if the post-link feed state no longer names A: the link result records linkedPolicyIDs as just [B], or flips preferredPolicy to B, instead of keeping A and adding B. (The other client write on this path, updateSelectedFeed, only writes LAST_SELECTED_FEED for the 2nd workspace and cannot remove the feed from A.)

Fix: Make linking append instead of replace. When linking a feed to a new workspace, build the new linked set from the feed's existing membership (its current linkedPolicyIDs, or its preferredPolicy when no linked list exists yet) plus the new workspace, and keep the origin workspace's membership intact; the persisted result pushed to the client must carry the full set so both workspaces render the feed. Do not paper over this with a blanket preferredPolicy fallback in the display predicate: that would also restore visibility after an intentional unlink while preferredPolicy is still populated. First capture the feed's settings.companyCards entry before sharing, after the link response, and after reload to confirm which side of the transition drops A, and let that capture decide where the append lands; if the capture shows the client already receives the full [A, B] set and A still drops, the fallback is the per-policy indexing branch above, not the fallback predicate.

Verification: Reproduce on staging with two workspaces on one account: add a Mock commercial card feed to workspace A, share it to workspace B from B's Add cards flow, then open A's Company Cards page and confirm the feed is still listed, and open B's to confirm it appears there too. Repeat for a feed shared to a third workspace, and for an intentional unlink from B, confirming A keeps the feed and B loses it. Add a Jest regression seeding a feed with linkedPolicyIDs [A, B] and asserting it renders under both workspaces, plus a case for the pre-link single-workspace state.

khizzcr7 avatar Nov 04 '26 06:11 khizzcr7

Proposal

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

A company card feed initially added to Workspace 1 (origin workspace) disappears from Workspace 1's Company Card page after the user shares/links it to Workspace 2. A shared card feed should remain visible and accessible in both Workspace 1 and Workspace 2 simultaneously.


What is the root cause of that problem?

There is a mutual-exclusion defect across the two display consumers that resolve card feed membership for policies:

  1. src/libs/CardFeedUtils.ts (getCardFeedsForDisplayPerPolicy:400–410)
  2. src/hooks/useCardFeeds.tsx (shouldIncludeFeedPredicate:60–70)

Mechanism:

  1. Initial State (Workspace 1 only): When a company card feed is first added to Workspace 1, it is stored under the domain settings with:

    • preferredPolicy: 'WORKSPACE_1_ID'
    • linkedPolicyIDs: undefined (or empty []).
  2. State Transition on Sharing (to Workspace 2): When the user opens Workspace 2, navigates to Company Cards > Add cards > selects the feed from "From other workspaces", WorkspaceCompanyCardFeedSelectorPage invokes linkCardFeedToPolicy(feed.fundID, policyID, ...) with Workspace 2's policyID. The backend links Workspace 2 by setting:

    • linkedPolicyIDs: ['WORKSPACE_2_ID']
    • preferredPolicy remains 'WORKSPACE_1_ID'.
  3. The Display Defect:

    • In getCardFeedsForDisplayPerPolicy (src/libs/CardFeedUtils.ts:400–410):

      const validLinkedPolicyIDs = linkedPolicyIDs?.filter(Boolean);
      if (validLinkedPolicyIDs?.length) {
          // Index the feed under each linked policy so it appears for all of them
          for (const linkedPolicyID of validLinkedPolicyIDs) {
              (cardFeedsForDisplayPerPolicy[linkedPolicyID] ||= []).push(feedEntry);
          }
      } else if (preferredPolicy) {
          (cardFeedsForDisplayPerPolicy[preferredPolicy] ||= []).push(feedEntry);
      }
      

      Because validLinkedPolicyIDs?.length is now truthy (['WORKSPACE_2_ID']), the code enters the if block and indexes the feed only under WORKSPACE_2_ID. Because of the else if, the preferredPolicy branch is completely skipped. Workspace 1 (preferredPolicy) is discarded from cardFeedsForDisplayPerPolicy.

    • In useCardFeeds (src/hooks/useCardFeeds.tsx:60–68):

      const shouldIncludeFeedPredicate = (combinedCardFeed: CombinedCardFeed) => {
          const validLinkedPolicyIDs = combinedCardFeed?.linkedPolicyIDs?.filter(Boolean);
          if (validLinkedPolicyIDs?.length) {
              return validLinkedPolicyIDs.some((linkedPolicyID) => linkedPolicyID.toUpperCase() === upperPolicyID);
          }
          return combinedCardFeed.preferredPolicy ? combinedCardFeed.preferredPolicy === policyID : combinedCardFeed.domainID === effectiveWorkspaceAccountID;
      };
      

      When viewing Workspace 1 (upperPolicyID = WORKSPACE_1_ID), because validLinkedPolicyIDs is non-empty, the hook checks validLinkedPolicyIDs.some(...). Since Workspace 2 does not equal Workspace 1, it returns false. It never evaluates combinedCardFeed.preferredPolicy === policyID. As a result, Workspace 1's Company Card page receives an empty feed list and drops the feed completely.


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

Card feed membership for display must represent the union of both preferredPolicy and all linkedPolicyIDs, deduplicated case-insensitively.

1. Fix in src/libs/CardFeedUtils.ts:

In getCardFeedsForDisplayPerPolicy, index the feed under both preferredPolicy and any linkedPolicyIDs:

--- a/src/libs/CardFeedUtils.ts
+++ b/src/libs/CardFeedUtils.ts
@@ -398,13 +398,20 @@ function getCardFeedsForDisplayPerPolicy(
             };

             const validLinkedPolicyIDs = linkedPolicyIDs?.filter(Boolean);
-            if (validLinkedPolicyIDs?.length) {
-                // Index the feed under each linked policy so it appears for all of them
-                for (const linkedPolicyID of validLinkedPolicyIDs) {
-                    (cardFeedsForDisplayPerPolicy[linkedPolicyID] ||= []).push(feedEntry);
+            const associatedPolicyIDs = new Set<string>();
+            if (preferredPolicy) {
+                associatedPolicyIDs.add(preferredPolicy);
+            }
+            if (validLinkedPolicyIDs?.length) {
+                for (const policyID of validLinkedPolicyIDs) {
+                    associatedPolicyIDs.add(policyID);
                 }
-            } else if (preferredPolicy) {
-                (cardFeedsForDisplayPerPolicy[preferredPolicy] ||= []).push(feedEntry);
+            }
+
+            if (associatedPolicyIDs.size > 0) {
+                for (const policyID of associatedPolicyIDs) {
+                    (cardFeedsForDisplayPerPolicy[policyID] ||= []).push(feedEntry);
+                }
             } else {
                 // Orphan feed: no linkedPolicyIDs and no preferredPolicy.

2. Fix in src/hooks/useCardFeeds.tsx:

In useCardFeeds, check both linkedPolicyIDs and preferredPolicy:

--- a/src/hooks/useCardFeeds.tsx
+++ b/src/hooks/useCardFeeds.tsx
@@ -58,12 +58,14 @@ const useCardFeeds = (policyID: string | undefined): [CombinedCardFeeds | undefi
         // `policyID` is stable for this hook invocation, so uppercase it once instead of per feed evaluation.
         const upperPolicyID = policyID.toUpperCase();
         const shouldIncludeFeedPredicate = (combinedCardFeed: CombinedCardFeed) => {
-            const validLinkedPolicyIDs = combinedCardFeed?.linkedPolicyIDs?.filter(Boolean);
-            if (validLinkedPolicyIDs?.length) {
-                // Linked policy IDs can differ in casing, so compare case-insensitively. This keeps the "available"
-                // list aligned with the case-insensitive "From other workspaces" check in useOtherFeedsForFeedSelector,
-                // so a case-mismatched linked feed isn't dropped from both lists and lost.
-                return validLinkedPolicyIDs.some((linkedPolicyID) => linkedPolicyID.toUpperCase() === upperPolicyID);
+            const validLinkedPolicyIDs = combinedCardFeed?.linkedPolicyIDs?.filter(Boolean) ?? [];
+            const isLinked = validLinkedPolicyIDs.some((linkedPolicyID) => linkedPolicyID.toUpperCase() === upperPolicyID);
+            const isPreferred = combinedCardFeed.preferredPolicy ? combinedCardFeed.preferredPolicy.toUpperCase() === upperPolicyID : false;
+            if (isLinked || isPreferred) {
+                return true;
             }
-            return combinedCardFeed.preferredPolicy ? combinedCardFeed.preferredPolicy === policyID : combinedCardFeed.domainID === effectiveWorkspaceAccountID;
+            return !validLinkedPolicyIDs.length && !combinedCardFeed.preferredPolicy ? combinedCardFeed.domainID === effectiveWorkspaceAccountID : false;
         };
         workspaceFeeds = getCombinedCardFeedsFromAllFeeds(allFeeds, shouldIncludeFeedPredicate, feedKeysWithCards);

What alternative solutions did you explore? (Optional)

  1. Mutating linkedPolicyIDs on the client during linkCardFeedToPolicy: Rejected because linkCardFeedToPolicy is an API side-effect command that relies on server persistence; altering frontend caching without fixing the display predicates would leave any feed where preferredPolicy was set at origin vulnerable to dropping out whenever linkedPolicyIDs is populated.
  2. Only modifying CardFeedUtils.ts without touching useCardFeeds.tsx: Rejected because useCardFeeds is the primary hook driving the active workspace Company Cards screen. If useCardFeeds is not updated, WorkspaceCompanyCardsPage would continue to evaluate validLinkedPolicyIDs exclusively and hide the feed from Workspace 1.

What automated tests can you add to prevent this from re-occurring?

  1. In tests/unit/CardFeedUtilsTest.ts:

    • Add a test verifying that when a card feed has preferredPolicy: 'POL1' and linkedPolicyIDs: ['POL2'], getCardFeedsForDisplayPerPolicy returns the feed under both result.POL1 and result.POL2.
    • Verify that duplicate policy IDs (e.g. preferredPolicy: 'POL1' and linkedPolicyIDs: ['POL1']) appear once without duplication.
  2. In tests/unit/hooks/useCardFeedsTest.ts:

    • Verify that useCardFeeds('POL1') includes a feed that has preferredPolicy: 'POL1' even when linkedPolicyIDs is populated with ['POL2'].
    • Verify that useCardFeeds('POL2') also includes the feed via linkedPolicyIDs.

Contributor details

Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~016c1aa34b51059d42

bhomvratrai-glitch avatar Nov 04 '26 11:11 bhomvratrai-glitch

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

melvin-bot[bot] avatar Nov 04 '26 11:11 melvin-bot[bot]

Proposal

1. Please re-state the problem

When a company card feed is created in workspace A and then linked to workspace B using Company Cards → Add cards → From other workspaces, it disappears from A's Company Cards page. Linking B must not disconnect A. This is also the documented sharing behavior: a shared connection should remain available to its other linked workspaces.

2. What is the root cause?

The App has two ways to identify a feed's workspace: preferredPolicy (the legacy fallback) and linkedPolicyIDs (explicit links). Once a nonempty linkedPolicyIDs arrives, the display code treats it as authoritative. The failure is consistent with the first share populating that list with B but omitting the still-connected origin A.

The relevant path is:

  1. WorkspaceCompanyCardFeedSelectorPage.tsx invokes linkCardFeedToPolicy(fundID, policyID, ...) with B's policy ID. On success it calls updateSelectedFeed(..., B). Neither operation explicitly removes A from the feed's memberships.
  2. CompanyCards.ts sends LinkCardFeedToPolicy with policyID, domainAccountID, feedType, feedName and feedCountry. There is no client-side optimistic membership replacement in this action.
  3. useCardFeeds.tsx checks linkedPolicyIDs first and only consults preferredPolicy when no meaningful linked IDs exist. getCardFeedsForDisplayPerPolicy uses the same precedence.

For example, if the transition is:

// Before sharing: A is visible through the legacy fallback.
{preferredPolicy: 'A', linkedPolicyIDs: []}

// After linking B: A disappears because it is absent from the explicit list.
{preferredPolicy: 'A', linkedPolicyIDs: ['B']}

// Required for a feed still connected to A and now connected to B:
{preferredPolicy: 'A', linkedPolicyIDs: ['A', 'B']}

This is not a reason to change the display predicate to linkedPolicyIDs || preferredPolicy. PR #93928 deliberately moved feed-selector membership decisions to linkedPolicyIDs, and PR #88359 added tests for that precedence. Treating a stale preferredPolicy as an active link risks re-showing a feed after an intentional unlink.

Evidence still needed: capture settings.companyCards[feedName].linkedPolicyIDs immediately before the B link, in the LinkCardFeedToPolicy response/Onyx updates, and after a fresh reload. This distinguishes an incomplete server membership from an App-side stale/incorrect merge. I have verified the read and request paths above, not the private server implementation.

3. What changes should be made?

Fix the membership transition at its source. If LinkCardFeedToPolicy emits only ['B'] while A remains connected, change its backend persistence/response path so adding B extends the authoritative set of active links rather than replacing it:

  • On the first share of a legacy feed, include A only when the server confirms A is still connected. Do not assume that preferredPolicy alone grants access.
  • Add B to the existing linked set, deduplicate IDs, and persist the update atomically so simultaneous links do not overwrite each other.
  • Return the complete membership to Onyx. Keep preferredPolicy as metadata; do not use it to resurrect an unlinked workspace.
  • If the server already returns ['A', 'B'], leave the membership rules alone and instead correct the specific Onyx update that loses A. This can be decided from one captured reproduction.

An App-only change to linkCardFeedToPolicy cannot guarantee a durable fix if the underlying linked set is persisted incorrectly.

4. Alternative considered

Adding || preferredPolicy === policyID to useCardFeeds, getCardFeedsForDisplayPerPolicy, and the feed selector would make the reported example display A again, but it would also make an intentionally unlinked A visible whenever preferredPolicy remained A. That is a regression in membership semantics, not a complete fix.

5. Tests

Backend integration test (the primary regression): establish an existing feed in A, link it to B, and assert that the persisted and returned linked set contains both A and B. Repeat with a third workspace; confirm re-linking B is idempotent and removing B preserves A.

App regression: feed the resulting Onyx payload into useCardFeeds and the feed selector; verify the feed appears once in A and B, remains after reload, and disappears only from the workspace explicitly unlinked. Retain coverage for legacy empty links and the existing explicit-membership tests in tests/unit/hooks/useCardFeeds.test.ts.

Manual verification: run the issue's staging steps for the mock commercial feed on web and check A/B before sharing, immediately afterward, and after a full refresh; also test unlinking B. The same expected membership should hold on Android and iOS.

The key invariant is straightforward: linking workspace B must not change whether workspace A is linked. The captured API/Onyx transition should determine which code layer to patch before opening a PR.

himanshu051116 avatar Nov 04 '26 12:11 himanshu051116

📣 @himanshu051116! 📣 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>

melvin-bot[bot] avatar Nov 04 '26 12:11 melvin-bot[bot]

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~012dd17e6db13358c4?mp_source=share

himanshu051116 avatar Nov 04 '26 14:11 himanshu051116

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

melvin-bot[bot] avatar Nov 04 '26 14:11 melvin-bot[bot]

Proposal

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

When a company card feed is created in Workspace A and then shared with Workspace B via Workspace settings > Company cards > Add cards > selecting the existing card feed from Workspace A, navigating back to Workspace A's Company cards page shows that the card feed has disappeared from Workspace A.

What is the root cause of that problem?

In src/hooks/useCardFeeds.tsx (lines 58–69), shouldIncludeFeedPredicate determines whether a CombinedCardFeed belongs to the current policyID:

  • First, it checks const validLinkedPolicyIDs = combinedCardFeed?.linkedPolicyIDs?.filter(Boolean); and if validLinkedPolicyIDs?.length is truthy, it returns validLinkedPolicyIDs.some((linkedPolicyID) => linkedPolicyID.toUpperCase() === upperPolicyID).
  • Only when validLinkedPolicyIDs?.length is 0 / falsy does it fall back to combinedCardFeed.preferredPolicy ? combinedCardFeed.preferredPolicy === policyID : combinedCardFeed.domainID === effectiveWorkspaceAccountID.

When a card feed is initially created in Workspace A, combinedCardFeed.preferredPolicy is set to Workspace A's policyID (or domainID === effectiveWorkspaceAccountID) and linkedPolicyIDs is empty/undefined. When the user shares that feed with Workspace B, linkedPolicyIDs becomes populated with [workspaceBPolicyID] (or shouldIncludeFeedPredicate exclusively checks validLinkedPolicyIDs without also checking combinedCardFeed.preferredPolicy === policyID / domainID === effectiveWorkspaceAccountID). Because validLinkedPolicyIDs.length is now non-zero and only contains Workspace B's ID, shouldIncludeFeedPredicate returns false for Workspace A, causing the feed to vanish from Workspace A.

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

  1. In src/hooks/useCardFeeds.tsx (lines 58–69) inside shouldIncludeFeedPredicate, when validLinkedPolicyIDs?.length is non-zero, return true if validLinkedPolicyIDs.some((linkedPolicyID) => linkedPolicyID.toUpperCase() === upperPolicyID) OR if the feed's owning/preferred policy matches the current workspace (combinedCardFeed.preferredPolicy ? combinedCardFeed.preferredPolicy.toUpperCase() === upperPolicyID : combinedCardFeed.domainID === effectiveWorkspaceAccountID).
  2. Additionally, when linking/sharing a card feed to another workspace in src/libs/actions/CompanyCards.ts, ensure any optimistic linkedPolicyIDs update preserves existing linked policy IDs and the originating workspace's preferredPolicy association.

What alternative solutions did you explore? (Optional)

We also considered only populating linkedPolicyIDs on the backend with both Workspace A and Workspace B, but updating shouldIncludeFeedPredicate in src/hooks/useCardFeeds.tsx to preserve the preferredPolicy / domainID match alongside validLinkedPolicyIDs guarantees the originating workspace never loses visibility of its own feed optimistically or when linkedPolicyIDs only lists secondary linked workspaces.

jeffrey-graham avatar Nov 07 '26 02:11 jeffrey-graham