App icon indicating copy to clipboard operation
App copied to clipboard

[$250] Add a Suggestions tab to the agent rule creation flow

Open yuwenmemon opened this issue 4 months ago • 31 comments

Child of Expensify/Expensify#655763. This issue tracks the front-end (NewDot / App) work: building a "Suggestions" tab in the agent rule creation flow.

Problem

Adding an agent rule today (src/pages/workspace/rules/AgentRules/AddAgentRulePage.tsx) is a single blank prompt box — the admin has to know what to type and how to phrase a useful rule. We have a set of ready-made, enforceable rules but don't surface any of them in the product, so there's no discovery.

Solution

Add a Suggestions tab to the add-agent-rule flow that lists ready-made rules as selectable suggestions. Picking a suggestion pre-fills the rule prompt (still editable) so the admin can review and save, instead of writing one from scratch. The existing free-text entry stays as the "write your own" path.

Where it goes

  • src/pages/workspace/rules/AgentRulesSection.tsx — the "Add rule" menu item navigates to ROUTES.RULES_AGENT_NEW.
  • src/pages/workspace/rules/AgentRules/AddAgentRulePage.tsx — the destination page; today just the PROMPT input. The Suggestions tab lives here, alongside the existing free-text input.

Behavior

  • Suggestions tab lists each suggested rule by its title.
  • Tapping a suggestion pre-fills the prompt input; the admin can edit it, then saves through the existing addPolicyAgentRule path — no new save flow needed.
  • Handle empty / loading / offline states.
  • Keep the flow beta-gated behind CONST.BETAS.CUSTOM_AGENT, like the rest of the agent rules UI.
  • Add copy + translations for the tab and its strings.

Suggestions data

Each suggestion is a {id, title, prompt} — a display title and the prompt text to prefill.

Source (confirmed): the backend, not shipped App constants. The list is owned by one server-side file in Web-Expensify — lib/InProductSuggestedRules.php (Web#54407) — which is also the exact set the agent-eval gate enforces at 100%, so the suggestions we surface always match what we've tested. App fetches it rather than shipping its own copy, so the two can't drift.

How App gets it: the backend delivers the list to App as Onyx-backed data (same shape of flow as betas) — App reads it from an Onyx key as Array<{id: string; title: string; prompt: string}>. Render that list; the loading/empty/offline states above apply.

Backend dependency: these prompts are PHP-only today (rendered server-side into the agent's system prompt, not yet synced to Onyx), so a small Web-Expensify companion PR is required to expose the list to App — it will define the exact Onyx key + read command (delivered when this flow opens). That companion is the data-source prerequisite; until it lands, build the tab against the {id, title, prompt} shape (a stub list is fine).

Design

https://github.com/user-attachments/assets/243ecba3-62a4-4aff-902f-7a99e82a0951

Next steps

  • [ ] Confirm the final tab UX against the mockup (tabbed page vs. suggestions-first with "write your own")
  • [x] Confirm where the suggestions list comes from — backend-served via Onyx (see Suggestions data); needs a small Web-Expensify companion PR to expose it
  • [ ] Build the Suggestions tab and wire selection → prompt prefill → addPolicyAgentRule
  • [ ] Copy + translations
  • [ ] Tests
Upwork Automation - Do Not Edit

yuwenmemon avatar Jul 09 '26 18:07 yuwenmemon

Triggered auto assignment to Design team member for new feature review - @dubielzyk-expensify (NewFeature)

melvin-bot[bot] avatar Jul 09 '26 18:07 melvin-bot[bot]

🚨 Edited by proposal-police: This proposal was edited at 2026-07-09 18:40:17 UTC.

Proposal

What is the root cause of that problem?

The add-agent-rule flow already has entry points and an App-side save action, but the destination page only renders a single free-text prompt form. There is no client-side suggestions source, no tab state, no searchable suggestion list, and no selection handler that can prefill the prompt before the admin reviews and saves it.

https://github.com/Expensify/App/blob/6e2df6b53e5b1a3ba690d9971068979153cb7d27/src/pages/workspace/rules/AgentRulesSection.tsx#L135-L148

https://github.com/Expensify/App/blob/6e2df6b53e5b1a3ba690d9971068979153cb7d27/src/pages/workspace/rules/AgentRules/AddAgentRulePage.tsx#L68-L80

https://github.com/Expensify/App/blob/6e2df6b53e5b1a3ba690d9971068979153cb7d27/src/pages/workspace/rules/AgentRules/AddAgentRulePage.tsx#L122-L170

The current write contract is already prompt-based, so the missing piece is discovery and prefill UI in App, not a separate save flow.

https://github.com/Expensify/App/blob/6e2df6b53e5b1a3ba690d9971068979153cb7d27/src/libs/actions/Policy/Rules.ts#L332-L399

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

Keep RULES_AGENT_NEW as the add route and update AddAgentRulePage to render two modes that match the design: Suggested and Edit / write-your-own. Use the existing tab selector primitives for the mode switch, and keep the current AccessOrNotFoundWrapper and CONST.BETAS.CUSTOM_AGENT checks around the page.

https://github.com/Expensify/App/blob/6e2df6b53e5b1a3ba690d9971068979153cb7d27/src/components/TabSelector/TabSelectorBase.tsx#L18-L35

https://github.com/Expensify/App/blob/6e2df6b53e5b1a3ba690d9971068979153cb7d27/src/pages/workspace/rules/AgentRules/AddAgentRulePage.tsx#L49-L56

https://github.com/Expensify/App/blob/6e2df6b53e5b1a3ba690d9971068979153cb7d27/src/pages/workspace/rules/AgentRules/AddAgentRulePage.tsx#L122-L128

Add a typed suggestions input, Array<{id: string; title: string; prompt: string}>, from whichever source is finalized for this issue. Render those suggestions in the Suggested tab with the existing selectable-list/search patterns, using title for display and prompt only as the value to prefill. Include the requested loading, empty, offline, and no-results states in that tab.

https://github.com/Expensify/App/blob/6e2df6b53e5b1a3ba690d9971068979153cb7d27/src/pages/workspace/reports/ReportFieldTypePicker/index.tsx#L47-L54

When a suggestion is selected, write its prompt into ONYXKEYS.FORMS.ADD_AGENT_RULE_FORM draft values, switch to the Edit tab, and make the prompt InputWrapper opt into saved drafts with shouldSaveDraft so FormProvider actually reads the prefilled value when the input registers. Clear that form draft after a successful save or when leaving the add flow so a previous suggestion does not appear in the next new rule.

https://github.com/Expensify/App/blob/6e2df6b53e5b1a3ba690d9971068979153cb7d27/src/components/Form/FormProvider.tsx#L382-L385

https://github.com/Expensify/App/blob/6e2df6b53e5b1a3ba690d9971068979153cb7d27/src/components/Form/FormProvider.tsx#L492-L505

https://github.com/Expensify/App/blob/6e2df6b53e5b1a3ba690d9971068979153cb7d27/src/libs/actions/FormActions.ts#L28-L34

Keep the existing validation, keyboard submit behavior, first-rule RuleBot modal, and final addPolicyAgentRule(policyID, rand64(), values[PROMPT]) submit path. Add the new tab labels, empty/error copy, and suggestion-list copy under workspace.rules.agentRules with translations in the supported language files.

https://github.com/Expensify/App/blob/6e2df6b53e5b1a3ba690d9971068979153cb7d27/src/pages/workspace/rules/AgentRules/AddAgentRulePage.tsx#L76-L120

https://github.com/Expensify/App/blob/6e2df6b53e5b1a3ba690d9971068979153cb7d27/src/languages/en.ts#L7950-L7965

Test coverage:

  • Add UI tests for AddAgentRulePage that render suggestions, filter/search them, select a suggestion, assert the prompt is prefilled in the edit tab and remains editable, and assert submit still calls the existing AddPolicyAgentRule path with the edited prompt.
  • Add empty/loading/offline or failed-source state coverage for the suggestions tab.
  • Keep the existing addPolicyAgentRule action tests unchanged unless the API contract changes, because the save payload should remain {policyID, agentRuleID, prompt}.

What alternative solutions did you explore? (Optional)

One alternative is adding a new suggestion-specific route or save action. I would avoid that because picking a suggestion is only a prefill step; the existing add page already owns validation, offline-enabled submission, first-rule RuleBot messaging, and the prompt-based API write.

KJ21-ENG avatar Jul 09 '26 18:07 KJ21-ENG

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

melvin-bot[bot] avatar Jul 09 '26 18:07 melvin-bot[bot]

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

melvin-bot[bot] avatar Jul 09 '26 18:07 melvin-bot[bot]

🚨 Edited by proposal-police: This proposal was edited at 2026-07-10 14:01:35 UTC.

Proposal

What is the root cause of that problem?

Adding an agent rule today lands admins on a single blank prompt box with no way to discover ready-made rules. AddAgentRulePage renders only a FormProvider wrapping one PROMPT InputWrapper, validates that the text is non-empty, and submits it directly to addPolicyAgentRule. There is no Suggestions surface, no selectable curated list, and no Onyx read that could supply {id, title, prompt} suggestions.

https://github.com/Expensify/App/blob/086f3e3a3b1360d018bbc42368bbf5633351a9b3/src/pages/workspace/rules/AgentRules/AddAgentRulePage.tsx#L44-L170

The "Add rule" entry in AgentRulesSection navigates straight to ROUTES.RULES_AGENT_NEW with only policyID, so the destination has nothing to render beyond the free-text form.

https://github.com/Expensify/App/blob/086f3e3a3b1360d018bbc42368bbf5633351a9b3/src/pages/workspace/rules/AgentRulesSection.tsx#L136-L147

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

Match the design mock: a New rule RHP with Suggested / Edit tabs, searchable light-gray rounded suggestion cards (icon + prompt text), Get help from Concierge + Next on Suggested, and the existing editable prompt + save path on Edit.

  1. Keep RULES_AGENT_NEW and turn AddAgentRulePage into a two-tab page using TabSelectorBase + Onyx selected-tab state (CONST.TAB.AGENT_RULE_TAB_TYPE). Prefer TabSelectorBase over OnyxTabNavigator so selecting a suggestion can switch to Edit after mount (OnyxTabNavigator only applies the selected tab as initialRouteName). Keep the existing CONST.BETAS.CUSTOM_AGENT / AccessOrNotFoundWrapper gate.

https://github.com/Expensify/App/blob/086f3e3a3b1360d018bbc42368bbf5633351a9b3/src/pages/workspace/rules/AgentRules/AddAgentRulePage.tsx#L122-L172

https://github.com/Expensify/App/blob/086f3e3a3b1360d018bbc42368bbf5633351a9b3/src/components/TabSelector/TabSelectorBase.tsx#L18-L35

const tabs = [
    {key: CONST.TAB.AGENT_RULE.SUGGESTIONS, title: translate('workspace.rules.agentRules.suggestionsTab'), icon: tabIcons.Bot},
    {key: CONST.TAB.AGENT_RULE.WRITE, title: translate('workspace.rules.agentRules.writeTab'), icon: tabIcons.Pencil},
];

const selectSuggestion = (suggestion: SuggestedAgentRule) => {
    setDraftValues(ONYXKEYS.FORMS.ADD_AGENT_RULE_FORM, {[INPUT_IDS.PROMPT]: suggestion.prompt});
    Tab.setSelectedTab(CONST.TAB.AGENT_RULE_TAB_TYPE, CONST.TAB.AGENT_RULE.WRITE);
};
  1. Add a dedicated SuggestedAgentRule type ({id, title, prompt}) and Onyx key ONYXKEYS.SUGGESTED_AGENT_RULES. Do not reuse AgentPrompt (that type is the agent system-prompt NVP, not curated rule suggestions). Add useSuggestedAgentRules that reads that key and returns {data, isLoading} so the Suggestions tab can show loading, empty, and offline states from real Onyx data.
type SuggestedAgentRule = {
    id: string;
    title: string;
    prompt: string;
};

function useSuggestedAgentRules() {
    const [suggestions, metadata] = useOnyx(ONYXKEYS.SUGGESTED_AGENT_RULES);
    return {
        data: suggestions ?? [],
        isLoading: isLoadingOnyxValue(metadata),
    };
}
  1. Build AddAgentRuleSuggestionsTab: search ("Find a rule"), selectable rounded highlightBG cards (icon + normal-weight title from each suggestion), then footer Get help from Concierge (ROUTES.CONCIERGE) and Next (requires a selection, then prefills + switches to Edit). Use shouldSaveDraft on the Edit prompt input, and clearDraftValues on save / unmount so a prior suggestion does not leak into the next visit.
useEffect(() => {
    Tab.setSelectedTab(CONST.TAB.AGENT_RULE_TAB_TYPE, CONST.TAB.AGENT_RULE.SUGGESTIONS);
    return () => clearDraftValues(ONYXKEYS.FORMS.ADD_AGENT_RULE_FORM);
}, []);
<PressableWithFeedback
    style={[styles.flexRow, styles.alignItemsCenter, styles.ph5, styles.pv4, styles.highlightBG, styles.borderRadiusComponentNormal]}
    onPress={() => setSelectedSuggestionID(suggestion.id)}
>
    <Icon src={icons[iconName]} width={variables.iconSizeLarge} height={variables.iconSizeLarge} />
    <Text style={[styles.flex1, styles.textNormal]}>{suggestion.title}</Text>
</PressableWithFeedback>
  1. Move the existing free-text form into AddAgentRuleWriteTab unchanged for validation, first-rule RuleBot modal, and addPolicyAgentRule(policyID, rand64(), values[PROMPT]).

https://github.com/Expensify/App/blob/086f3e3a3b1360d018bbc42368bbf5633351a9b3/src/pages/workspace/rules/AgentRules/AddAgentRulePage.tsx#L76-L120

  1. Copy under workspace.rules.agentRules: suggestionsTab ("Suggested"), writeTab ("Edit"), findSuggestion ("Find a rule"), getHelpFromConcierge, empty states; header title New rule. Do not put suggestion prompt strings in translations; those come from the backend via Onyx.

  2. Tests: render suggestions from Onyx, select + Next prefills Edit, submit still calls addPolicyAgentRule with the (possibly edited) prompt; cover loading / empty / offline for the Suggestions tab.

What alternative solutions did you explore? (Optional)

Reminder: Please use plain English, be brief and avoid jargon. Feel free to use images, charts or pseudo-code if necessary. Do not post large multi-line diffs or write walls of text. Do not create PRs unless you have been hired for this job.

Solution Verification Result

https://github.com/user-attachments/assets/96a24426-a49b-407e-bb7f-1d6c13fef0ad

samranahm avatar Jul 09 '26 18:07 samranahm

Proposal

What is the root cause of that problem?

Adding an agent rule drops the admin on a single blank prompt box with nothing to discover. AddAgentRulePage is just a FormProvider around one PROMPT InputWrapper; there's no surface that lists ready-made rules.

https://github.com/Expensify/App/blob/6e2df6b53e5b1a3ba690d9971068979153cb7d27/src/pages/workspace/rules/AgentRules/AddAgentRulePage.tsx#L151-L167

The deeper reason there's no discovery is where the choice is forced: the "Add rule" menu item routes straight to RULES_AGENT_NEW, which only carries policyID, so by the time the admin sees anything the only option on screen is "type something."

https://github.com/Expensify/App/blob/6e2df6b53e5b1a3ba690d9971068979153cb7d27/src/pages/workspace/rules/AgentRulesSection.tsx#L135-L150

https://github.com/Expensify/App/blob/6e2df6b53e5b1a3ba690d9971068979153cb7d27/src/ROUTES.ts#L3332-L3335

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

Put discovery at the entry point and keep AddAgentRulePage a single, unchanged form — no tabs, no persisted draft writes.

  1. In AgentRulesSection, change the "Add rule" press to open a PopoverMenu anchored on that menu item, listing each suggested rule by title plus a "Write your own" item at the bottom. This reuses an existing primitive and handles empty (just "Write your own"), loading, and offline states the way menus already do.

https://github.com/Expensify/App/blob/6e2df6b53e5b1a3ba690d9971068979153cb7d27/src/pages/workspace/rules/AgentRulesSection.tsx#L135-L150

  1. Add an optional suggestionID to RULES_AGENT_NEW.getRoute(policyID, suggestionID?). Selecting a suggestion navigates with its id; "Write your own" navigates with none.

https://github.com/Expensify/App/blob/6e2df6b53e5b1a3ba690d9971068979153cb7d27/src/ROUTES.ts#L3332-L3335

  1. In AddAgentRulePage, read suggestionID from route params, look up its prompt in the provided {id, title, prompt} list, and feed it as the input's defaultValue. FormProvider seeds the field from defaultValue when there's no draft, so the prompt lands pre-filled and fully editable with zero form changes — and, unlike writing setDraftValues, nothing sticky is left behind to leak into the next add.

https://github.com/Expensify/App/blob/6e2df6b53e5b1a3ba690d9971068979153cb7d27/src/components/Form/FormProvider.tsx#L384-L392

  1. Save is untouched: same validate → saveRule → addPolicyAgentRule path, so offline submit and the first-rule "RuleBot created" modal keep working, and there's still exactly one submit path.

https://github.com/Expensify/App/blob/6e2df6b53e5b1a3ba690d9971068979153cb7d27/src/pages/workspace/rules/AgentRules/AddAgentRulePage.tsx#L76-L84

  1. Beta gating is unchanged — the page stays wrapped in AccessOrNotFoundWrapper with shouldBeBlocked={!isCustomAgentEnabled}. Treat the suggestions list as an input {id, title, prompt}; until the source is confirmed, feed it from a constant, later swap to a useOnyx read without touching the menu. Add copy for the menu title and "Write your own" under workspace.rules.agentRules.

What alternative solutions did you explore? (Optional)

Adding a Suggestions tab inside AddAgentRulePage (OnyxTabNavigator/TabSelector) that prefills via setDraftValues and switches to a write tab. It works, but it needs new CONST.TAB ids + linking config, and setDraftValues persists the picked prompt in the Onyx draft, which can reappear on the next visit. Surfacing the choice at the entry menu and prefilling through a route param + defaultValue avoids both, and keeps the page a plain single-input form.

lorretheboy avatar Jul 09 '26 18:07 lorretheboy

⚠️ @lorretheboy 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.

github-actions[bot] avatar Jul 09 '26 18:07 github-actions[bot]

Updated my proposal.

What changed: Clarified the selected-suggestion prefill path and kept the route/save flow unchanged.

Why: The current form only reads draft values for inputs that opt into saved drafts, so the prompt field needs an explicit draft-enabled prefill path.

KJ21-ENG avatar Jul 09 '26 18:07 KJ21-ENG

Proposal

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

Adding an agent rule lands the admin on a single blank prompt box with no way to discover ready-made rules. We need a Suggestions tab listing curated {id, title, prompt} rules; picking one prefills the (still-editable) prompt, which then saves through the existing path.

What is the root cause of that problem?

AddAgentRulePage renders only the PROMPT InputWrapper and submits straight to addPolicyAgentRule (AddAgentRulePage.tsx#L76-L80) — there is no list surface. But the route is not the blocker: RULES_AGENT_NEW carrying only policyID is sufficient, because the active tab is presentation state local to the page.

The non-obvious constraint is how a suggestion tap reaches the input. FormProvider keeps field values in local React state — const [inputValues, setInputValues] = useState(...) (FormProvider.tsx#L158) — and registerInput binds each field to it via value: inputValues[inputID] (#L425). It re-syncs only from the ${formID}Draft key (#L162-L165), never from the ${formID} Onyx key. So merging a chosen prompt into ONYXKEYS.FORMS.ADD_AGENT_RULE_FORM would silently fail to update the box — the prefill must be pushed through the form ref.

(The existing AgentPrompt Onyx type (AgentPrompt.ts#L4-L19) models one agent's custom instructions via SHARED_NVP_AGENT_PROMPT/UpdateAgentPrompt — a single prompt string with no id/title — so it is not a suggestion-list source.)

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

  1. Add a controlled two-tab toggle inside AddAgentRulePage using TabSelectorBase + TabSelectorContextProvider driven by local useState, mirroring the sibling rules page (PolicyRulesPageRevamp.tsx#L294-L307). Do not use OnyxTabNavigator — that is a route-backed navigator with its own back-stack, focus trap, and Onyx-persisted selection, overkill for one in-page toggle. Keep the single FormProvider, validate, saveRule, and addPolicyAgentRule untouched.

  2. "Write your own" tab = the existing InputWrapper/TextInput. "Suggestions" tab = a scrollable list of MenuItem rows, reusing the add-rule item idiom (AgentRulesSection.tsx#L135-L150).

  3. Prefill on tap: formRef.current?.resetForm({[INPUT_IDS.PROMPT]: suggestion.prompt}), then setActiveTab(WRITE_YOUR_OWN). resetForm (FormProvider.tsx#L331-L343) calls setInputValues, which registerInput flows to the field (#L425), and clears errors — correct, since the admin is starting a review. The admin edits, then Save runs the unchanged addPolicyAgentRule flow, including the first-rule RuleBot confirm modal (AddAgentRulePage.tsx#L79-L119). No new save flow, route, or command.

  4. Data seam: ship the list as CONST.AGENT_RULE_SUGGESTIONS ({id, title, prompt}[]) consumed through a thin useAgentRuleSuggestions() hook returning {suggestions, isLoading}. When a served source is confirmed, only the hook changes. Render an empty-state Text and a loading branch; since the default is client constants, suggestions exist even offline.

  5. Copy: add workspace.rules.agentRules.suggestions.* (tab title, empty state, disclaimer) plus a writeYourOwn tab title. Beta gating needs no change — AccessOrNotFoundWrapper shouldBeBlocked={!isCustomAgentEnabled} already wraps the page (AddAgentRulePage.tsx#L123-L128).

What alternative solutions did you explore? (Optional)

Merging the chosen prompt into the Onyx form key on tap — rejected: FormProvider never re-reads field values from that key, so the box would stay empty (see root cause). OnyxTabNavigator — rejected for the route-state overhead above. Both rejections are why the proposal commits to resetForm + TabSelectorBase.

trasnake87 avatar Jul 09 '26 18:07 trasnake87

Proposal

What is the root cause of that problem?

This is a feature gap, so the "root cause" is what the current add-rule flow structurally can't do.

Two things block a Suggestions tab today:

1. The add-rule page is a single free-text form with no tab shell and no list surface. AddAgentRulePage is one FormProvider wrapping a single PROMPT input. validate only checks that PROMPT is non-empty, and saveRule submits that raw text straight to addPolicyAgentRule(policyID, rand64(), values[PROMPT]). There's no tab navigator, no list, and no notion of a "selected suggestion" anywhere in the render tree.

The single entry point reinforces this: the "Add agent rule" menu item just navigates to RULES_AGENT_NEW, and that route carries only policyID — no mode, no suggestion context — so the destination has nothing to branch on.

2. There's no client-side catalog of ready-made rules to list. The only agent-rules data on Onyx is policy.rules.agentRules — the admin's own saved rules that AgentRulesSection renders and that each drive addPolicyAgentRule + RuleBot provisioning. git grep for any suggested/suggestion agent-rule source returns nothing. So even if we had the UI, there's no list to feed it. The issue itself flags the source (backend-served vs. shipped constant) as TBD, which is why I treat the list as a typed input {id, title, prompt}[] rather than pinning it to a store.

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

Keep RULES_AGENT_NEW as the single route and turn AddAgentRulePage into a two-tab page. No new route, no second save path.

Render layer — tab shell. Wrap the page body in OnyxTabNavigator + TabSelector with two TopTab.Screens: "Suggestions" and "Write your own". The only workspace page already doing exactly this is EditInviteReceiptPartnerPolicyPage, so I'd copy its structure (navigator + TabScreenWithFocusTrapWrapper + SelectionList per tab) — it already gets narrow-layout, focus-trap, empty-content, and offline behavior right.

This needs a navigator id under CONST.TAB (precedent: CONST.TAB.RECEIPT_PARTNERS.NAVIGATOR_ID). The "Write your own" tab holds the existing FormProvider block unchanged; the "Suggestions" tab holds a SelectionList of the catalog, each row keyed by id with title as the label (and optionally a prompt preview).

Data layer — the catalog as an input. Read the {id, title, prompt}[] list from whatever source the companion/backend task confirms. Don't copy the prompt bodies into en.ts — the shared prompt string is the value we prefill, and duplicating it into translation files just creates drift. Loading / empty / offline states come free from SelectionList's shouldShowListEmptyContent + listEmptyContent plus the ScreenWrapper offline indicator, same as the receipt-partners tab.

The prefill — this is the part worth getting right. On suggestion tap, do two things:

  1. FormActions.setDraftValues(ONYXKEYS.FORMS.ADD_AGENT_RULE_FORM, {[INPUT_IDS.PROMPT]: suggestion.prompt})
  2. Tab.setSelectedTab(<agent-rules navigator id>, <write-your-own tab>) to jump the admin to the editable form.

This works because FormProvider subscribes to ${formID}Draft and live-syncs its inputValues whenever the draft reference changes — not just on mount. So the prompt input reflects the picked suggestion whether the "Write your own" form is lazily mounted on the tab switch (seeded from the draft at construction) or was already mounted (merged in by the live-sync effect). Either way the text lands in the field and stays fully editable.

Because save is untouched, we keep the existing validation, Cmd/Ctrl+Enter submit, the first-rule RuleBot modal, and addPolicyAgentRule(policyID, rand64(), values[PROMPT]) write — the API contract stays {policyID, agentRuleID, prompt}.

  • Rules.ts#L332-L400 — addPolicyAgentRule (optimistic/offline-enabled write we reuse as-is)

One edge case the fix introduces: today nothing writes the PROMPT draft, so it's always empty on open. Once we start calling setDraftValues, the draft persists — so clear it (FormActions.clearDraftValues(ONYXKEYS.FORMS.ADD_AGENT_RULE_FORM)) on save and on unmount, otherwise a previously-picked suggestion reappears the next time the admin opens "Add rule".

Copy layer. Add tab labels + empty/loading strings under workspace.rules.agentRules in en.ts and the other language files. Beta gate and access wrapper stay exactly as-is.

Tests: render the Suggestions tab, pick a suggestion, assert the prompt field is prefilled and still editable, and assert submit calls AddPolicyAgentRule with the selected prompt (write contract unchanged). Plus empty/loading/offline states for the catalog source.

One open UX call from the issue's own checklist — tabbed page vs. suggestions-first with a "write your own" link. I'd go tabbed (matches the "Suggestions tab" framing and the receipt-partners precedent), but that's the design mockup's call to confirm.

What alternative solutions did you explore? (Optional)

Prefill via local React state + defaultValue instead of the draft. Rejected: FormProvider only applies defaultValue/state when an input's value is still undefined at mount (FormProvider.tsx#L386-L391). If the "Write your own" form is already mounted when the admin taps a suggestion, a state change wouldn't flow into the field. setDraftValues wins because the L162-L164 live-sync handles the already-mounted case.

A dedicated /agent-rules/suggestions/:id detail screen that saves directly. Rejected: selection is only a prefill step, but a separate screen forces a second write path parallel to addPolicyAgentRule and re-implements the first-rule RuleBot modal + offline-enabled submit that AddAgentRulePage already owns (AddAgentRulePage.tsx#L76-L120). Two submit paths for one action is exactly what I want to avoid.

Seed suggestions as pre-created entries in policy.rules.agentRules and reuse the existing rule list. Rejected: that collection is the admin's enforced rules — AgentRulesSection renders each one and every entry maps to a live rule + RuleBot provisioning (AgentRulesSection.tsx#L104-L134). Suggested-but-not-adopted rules would show up as active, enforced rules. The catalog has to be a separate source.

oqildev avatar Jul 09 '26 18:07 oqildev

Proposal

What is the root cause of that problem?

AddAgentRulePage only renders one free-text PROMPT input and submits that value directly through the existing addPolicyAgentRule(policyID, rand64(), values[PROMPT]) path. There is no tab state, no suggestions list, and no selection handler that can prefill the editable prompt field.

Relevant code:

  • AddAgentRulePage single prompt form: https://github.com/Expensify/App/blob/6e2df6b53e5b1a3ba690d9971068979153cb7d27/src/pages/workspace/rules/AgentRules/AddAgentRulePage.tsx#L122-L170
  • Existing add route entry point: https://github.com/Expensify/App/blob/6e2df6b53e5b1a3ba690d9971068979153cb7d27/src/pages/workspace/rules/AgentRulesSection.tsx#L135-L148
  • Existing prompt-based save action: https://github.com/Expensify/App/blob/6e2df6b53e5b1a3ba690d9971068979153cb7d27/src/libs/actions/Policy/Rules.ts#L332-L399

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

Add the Suggestions tab inside AddAgentRulePage, keeping RULES_AGENT_NEW and the current save flow unchanged.

Implementation:

  • Add a typed suggestions catalog seam via useAgentRuleSuggestions(), initially backed by CONST.AGENT_RULE_SUGGESTIONS.
  • Add local tab state with TabSelectorBase: Suggested and Edit.
  • Render the suggestions tab with SearchBar, empty/loading/offline copy, and selectable suggestion rows.
  • On suggestion press, write the suggestion prompt to ADD_AGENT_RULE_FORM draft values, then switch to the edit tab.
  • Mark the prompt InputWrapper with shouldSaveDraft so FormProvider reads and live-syncs the selected prompt.
  • Clear ADD_AGENT_RULE_FORM draft values on successful save and unmount so a previous suggestion does not leak into the next add flow.
  • Keep validation, Cmd/Ctrl+Enter, first-rule RuleBot modal, and addPolicyAgentRule unchanged.

Tests to add:

  • Render AddAgentRulePage, confirm the Suggested/Edit tabs appear.
  • Search suggestions and verify no-results behavior.
  • Select a suggestion and assert the Edit tab prompt is prefilled and editable.
  • Submit after editing and assert the existing AddPolicyAgentRule call receives the edited prompt.
  • Cover empty/loading/offline states for the suggestions source.

What alternative solutions did you explore? (Optional)

I considered adding a separate route or save action for suggestions, but selection is only a prefill step. A second route/save path would duplicate validation, offline submission, and the first-rule RuleBot flow already owned by AddAgentRulePage.

I also considered writing directly to ONYXKEYS.FORMS.ADD_AGENT_RULE_FORM, but FormProvider syncs user-visible input values from the draft key, not from the form key. Using setDraftValues with shouldSaveDraft is the reliable path for both mounted and not-yet-mounted edit inputs.

x-dev90 avatar Jul 09 '26 18:07 x-dev90

⚠️ @x-dev90 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.

github-actions[bot] avatar Jul 09 '26 18:07 github-actions[bot]

External Daily NewFeature Help Wanted

Issue: #95742 · Bounty: $250

Proposal

[!IMPORTANT] This comment was auto-withdrawn by ProposalPolice as a "duplicate," then restored here by editing (rather than reposting) per the contributor guide's rule for updating a proposal in place. The distinguishing part of this proposal is the correctness finding below — every proposal on this thread lands on the same tab + prefill shape, but two of them directly contradict each other on the one mechanism that actually makes the prefill work, and that contradiction was never resolved against source.

What is the root cause of that problem?

The mechanism dispute, resolved: two existing proposals disagree about how a tapped suggestion is supposed to reach the editable prompt box. One says writing the suggestion into the Onyx form-draft key will "silently fail" on an already-mounted field and that only formRef.current?.resetForm() works; another says the draft "live-syncs" so setDraftValues alone is enough. I checked this against FormProvider.tsx directly instead of assuming either way:

const [draftValues, draftValuesMetadata] = useOnyx(`${formID}Draft`);
const [inputValues, setInputValues] = useState(() => ({...draftValues}));
const previousDraftValues = useRef(draftValues);

if (!isLoadingDraftValues && draftValues !== previousDraftValues.current) {
    previousDraftValues.current = draftValues;
    setInputValues({...inputValues, ...draftValues});   // FormProvider.tsx L162-165
}

This runs on every render, unconditionally, whenever the Onyx draft object changes — it is not gated behind any input's shouldSaveDraft flag. shouldSaveDraft on a specific InputWrapper only controls two unrelated things: whether that input seeds itself from the draft the first time it mounts, and whether its own keystrokes get written back into the draft (FormProvider.tsx L504-506). Neither gates the merge above.

[!NOTE] Net effect: FormActions.setDraftValues(ONYXKEYS.FORMS.ADD_AGENT_RULE_FORM, {prompt: suggestion.prompt}) correctly updates the visible prompt field whether it's already mounted or mounts for the first time after the tab switch — with no need to mark the prompt input shouldSaveDraft. The "silently fails" claim doesn't hold against L162-165; resetForm() also works, it's just unnecessary machinery here.

The underlying gap itself (same as the rest of the thread, stated briefly for completeness): AddAgentRulePage is a single FormProvider around one PROMPT input that submits straight to addPolicyAgentRule; AgentRulesSection's "Add rule" item navigates to ROUTES.RULES_AGENT_NEW with only policyID; there's no {id, title, prompt} catalog anywhere — the only agent-rules Onyx data (AgentPrompt) is a single string per agent, not a list.

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

Keep RULES_AGENT_NEW as the single route and one FormProvider for the whole page — no new route, no second save path, no navigator.

  1. In-page tab, not a navigator. Local activeTab ('suggestions' | 'edit') useState in AddAgentRulePage, rendered with the existing TabSelectorBase + TabSelectorContextProvider — their own doc comment calls this the pattern for "inline tab selectors like SplitExpensePage," so no OnyxTabNavigator or new CONST.TAB id is needed. Unlike PolicyRulesPageRevamp/SplitExpensePage, skip ONYXKEYS.COLLECTION.SELECTED_TAB persistence — a fresh "Add rule" visit should always open on Suggestions, not remember the last tab.

  2. Data as an input. A thin useAgentRuleSuggestions() hook returns {data: Array<{id: string; title: string; prompt: string}>, isLoading}. The source (backend vs. shipped constant) is still unconfirmed per the issue's checklist, so only this hook changes once it is. Render rows with the same MenuItemWithTopDescription styling AgentRulesSection already uses for saved rules, reusing its offline/empty patterns.

  3. Prefill on tap:

FormActions.setDraftValues(ONYXKEYS.FORMS.ADD_AGENT_RULE_FORM, {[INPUT_IDS.PROMPT]: suggestion.prompt});
setActiveTab('edit');

No shouldSaveDraft on the PROMPT InputWrapper — see root cause above; this also avoids writing every keystroke back into the Onyx draft.

[!IMPORTANT] Because the draft is written once (on tap) and never re-synced from keystrokes, it will still hold that prompt the next time "Add rule" is opened unless cleared. Call FormActions.clearDraftValues(ONYXKEYS.FORMS.ADD_AGENT_RULE_FORM) at the top of saveRule after a successful addPolicyAgentRule, and on unmount — otherwise a previously-picked suggestion leaks into the next new rule.

  1. Unchanged: validate, the first-rule RuleBot modal, addPolicyAgentRule(policyID, rand64(), values[PROMPT]), AccessOrNotFoundWrapper + CONST.BETAS.CUSTOM_AGENT. Write contract ({policyID, agentRuleID, prompt}) doesn't change, so no backend or existing action test needs touching.

  2. Copy: workspace.rules.agentRules.suggestions.* (tab labels, empty/loading text) alongside the existing block in en.ts (~L7950-7965), with translations.

  3. Tests: select a suggestion → prompt field shows that text and stays editable → Save calls addPolicyAgentRule with the (possibly edited) value; empty/loading/offline coverage for the suggestions list; existing addPolicyAgentRule tests untouched.

[!NOTE] Two items are still explicitly open per the issue's own checklist: final tab UX vs. a suggestions-first mockup variant, and where the list is served from. Nothing above depends on either — the hook is the only seam for data source, and if design picks the non-tabbed variant, only the entry surface changes; the prefill mechanism and cleanup rule stay the same.

What alternative solutions did you explore? (Optional)

  • shouldSaveDraft on the prompt input for the prefill — unnecessary per the root-cause finding, and it starts persisting every keystroke into the Onyx draft for no benefit.
  • formRef.current?.resetForm() instead of setDraftValues — also works, but needs a form ref threaded into the suggestions list and duplicates what the draft merge already gives for free.
  • Move the picker to the entry point (AgentRulesSection's "Add rule" menu + route param instead of a tab) — valid if design confirms the suggestions-first mockup over a tab; sidesteps Onyx drafts via defaultValue, but moves suggestion data out of the page that owns validation/save and doesn't match the "Suggestions tab" framing in the issue title.

SARAMALI15792 avatar Jul 09 '26 19:07 SARAMALI15792

⚠️ @SARAMALI15792 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.

github-actions[bot] avatar Jul 09 '26 19:07 github-actions[bot]

Proposal

What is the root cause of that problem?

AddAgentRulePage only renders one controlled PROMPT field and sends it through the existing addPolicyAgentRule() flow. It has no suggestion catalog, tab state, or selection-to-prefill path.

https://github.com/Expensify/App/blob/b794ad367958627ccecd86681ff19ac7deba8596/src/pages/workspace/rules/AgentRules/AddAgentRulePage.tsx#L123-L168

There is also a subtle form-state constraint that the implementation must handle. FormProvider.resetForm() iterates only over keys already present in inputValues; it does not add a field that has never registered.

https://github.com/Expensify/App/blob/b794ad367958627ccecd86681ff19ac7deba8596/src/components/Form/FormProvider.tsx#L331-L345

So if Suggestions is the default tab and the prompt form is conditionally unmounted, calling formRef.current?.resetForm({prompt: suggestion.prompt}) before switching tabs can do nothing: PROMPT is not registered yet. Conversely, using the persistent Onyx draft key just for prefill creates cleanup work and can leak the previous suggestion into the next add-rule visit.

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

  1. Keep RULES_AGENT_NEW and the existing save path. Add an in-page TabSelectorBase with local suggestions | write state, following the sibling rules page instead of adding a route-backed tab navigator.

https://github.com/Expensify/App/blob/b794ad367958627ccecd86681ff19ac7deba8596/src/pages/workspace/rules/PolicyRulesPageRevamp.tsx#L291-L307

  1. Keep the single FormProvider and prompt InputWrapper mounted for the lifetime of the page, even while Suggestions is visible. Hide the write panel and its submit area when Suggestions is active rather than conditionally unmounting them. This guarantees PROMPT is registered, keeps typed edits intact when the admin moves between tabs, and avoids persisting prefill state in Onyx.

  2. On suggestion press, call:

formRef.current?.resetForm({[INPUT_IDS.PROMPT]: suggestion.prompt});
setActiveTab(WRITE_TAB);

Because the input is already registered, resetForm() updates the controlled value and clears any stale validation error. The prompt remains editable and Save still calls the existing addPolicyAgentRule(policyID, rand64(), values[PROMPT]), including the current first-rule RuleBot modal and offline-enabled submission behavior.

  1. Define a small AgentRuleSuggestion type ({id, title, prompt}) and let a hook/adapter expose {items, status}. Do not commit to constants or an Onyx collection until the issue confirms the source. The Suggestions panel can then handle loading, empty, and offline-unavailable states without changing the selection/form contract. The Write your own tab must remain usable in every state.

  2. Add tab, loading, empty, and offline copy under workspace.rules.agentRules and update translations. Keep the existing CONST.BETAS.CUSTOM_AGENT access gate unchanged.

  3. Add page-level tests for:

    • Suggestions is the initial tab and the hidden prompt field is registered.
    • Selecting a suggestion opens Write your own with the prompt prefilled and editable.
    • Switching Suggestions -> Write -> Suggestions -> Write preserves the admin's edits.
    • Saving sends the edited prompt through the existing action.
    • Leaving and reopening Add rule starts clean, with no previous suggestion draft.
    • Loading, empty, and offline suggestion states still allow Write your own.

What alternative solutions did you explore? (Optional)

  • Writing the suggestion to the form draft key: it handles a not-yet-mounted input, but introduces persistent state solely for a one-time prefill and requires careful cleanup on save, back navigation, and unmount.
  • Conditionally mounting the write form and using resetForm(): rejected because resetForm() only updates existing inputValues keys, so the first suggestion selection can be lost.
  • A new route or save action for suggestions: unnecessary because a suggestion only seeds the existing editable prompt; validation and saving should remain single-path.

YfengJ avatar Jul 09 '26 19:07 YfengJ

📣 @YfengJ! 📣 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 Jul 09 '26 19:07 melvin-bot[bot]

Proposal

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

Right now AddAgentRulePage.tsx is a blank text box. To add an agent rule an admin has to already know what a good rule looks like and how to phrase it so the AI agent enforces it correctly. There's no discovery — Expensify has a set of ready-made, enforceable rules (e.g. "Approve any report that consists of expenses under $75") but nothing in the product surfaces them.

The fix is building the missing UI: a Suggestions tab on the add-rule screen that lists these ready-made rules by title. Tapping one pre-fills the prompt box (still editable) so the admin reviews/tweaks and saves normally. Free-text entry ("write your own") stays exactly as it is today.

The issue itself explicitly leaves two things open — the final tab UX and where the suggestions list comes from — so I'm not going to pretend those are settled. Below I show what I found in the code that's relevant to both, without locking in a specific answer for either.


What is the root cause of that problem?

1. AddAgentRulePage.tsx is a single FormProvider with one field — no tab concept at all, just the prompt input and the form's own submit button. Beta gate, save call, first-rule confirmation modal are all already correct and don't need to change.

2. There's no data source for "suggestions" anywhere in the codebase. src/libs/actions/Policy/Rules.ts only has three agent-rule API commands (add/update/delete). No READ command, no Onyx key, nothing shaped like {id, title, prompt} exists today. The issue is explicit that the source is still to be confirmed, so I'm treating it as an input to the UI rather than something to design here.

3. One good clue already exists in the copy that isn't used anywhere yet. agentRules.findRule: 'Find agent rule' in en.ts (line 7956) is defined but referenced by nothing. Every other findRule key in the app labels a search box that filters a list of rules — this is the only unused one, which points at a filterable list being the intent (matching the "Find a rule" box in the mockup).

4. The mockup shows a real detail worth flagging, without me deciding the UX for the team. Both screenshots (Suggested tab, then Edit tab after tapping a suggestion) show the same "Next" button in the same place — the submit action looks shared, not per-tab. That's useful for whoever finalizes the tab UX, but I'm not picking a specific navigation primitive ahead of that decision. The codebase has established patterns either way it goes (IOURequestStartPage.tsx for routed per-tab screens, SetSpendRulesStep.tsx/PolicyRulesPageRevamp.tsx for a single form with a local-state tab toggle).


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

A. The suggestions list UI — independent of both open questions.

Reuse the exact pieces MerchantRulesSection.tsx already uses for "a flat, searchable list of rule-like items": SearchBar + useSearchResults wired to the existing findRule string (shown only past CONST.SEARCH_BAR_THRESHOLD), RulesTabEmptyState.tsx reused as-is for empty, isLoadingOnyxValue/useNetwork().isOffline for loading/offline. Typing {id, title, prompt} next to the existing AgentRule type is a one-line addition, not new complexity.

B. Prefilling the prompt — corrected from my first draft.

The right mechanism here is setDraftValues from @libs/actions/FormActions, not formRef.resetForm(). FormProvider itself calls setDraftValues(formID, {[inputKey]: value}) internally on every keystroke (FormProvider.tsx:505), and it's the established pattern across dozens of call sites for "pick something elsewhere, feed it into a form field" (WorkspaceCreateTaxValuePage.tsx, DynamicReportFieldsInitialListValuePage.tsx, NetSuiteCustomListSelectorPage.tsx, etc.):

setDraftValues(ONYXKEYS.FORMS.ADD_AGENT_RULE_FORM, {[INPUT_IDS.PROMPT]: suggestion.prompt});

This writes to the same draft Onyx key the form already reads from, so it behaves exactly like the user typed it — no separate imperative reset path.

C. Where the list comes from — deferring to the issue's own process, not inventing backend architecture.

Not my call to name a specific READ command or Onyx path here since it involves backend work tracked in a separate (private) issue. What I can say from the front-end alone: the issue calling out loading/offline as required behavior suggests a fetched list rather than a hardcoded one (a constant array has neither state), but that's a question to flag for whoever owns the backend side, not a decision I'm making. Either way, the UI in (A) only needs a value + a loading flag, so it can be built now and pointed at the real source once confirmed.

D. Copy/translations — new tab labels + empty-state copy under the existing agentRules block. findRule already exists.

E. Unchanged: addPolicyAgentRule, beta gate, validate function, first-rule confirmation modal, AgentRulesSection.tsx entry point, ROUTES.RULES_AGENT_NEW.


What alternative solutions did you explore? (Optional)

My first draft committed to TabSelectorBase over OnyxTabNavigator and to a specific new READ command name — both decisions the issue explicitly says aren't made yet. Pulled both back to "here's what exists today, here's what I need confirmed before implementing that part," since over-committing risks a chunk of the proposal being thrown out once those answers land. A hardcoded CONST list stays in mind as a fallback if the backend confirms the list is genuinely static.

bilalup avatar Jul 09 '26 19:07 bilalup

⚠️ @bilalup 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.

github-actions[bot] avatar Jul 09 '26 19:07 github-actions[bot]

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

YfengJ avatar Jul 09 '26 19:07 YfengJ

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

melvin-bot[bot] avatar Jul 09 '26 19:07 melvin-bot[bot]