Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
f474cb5
feat(rules): warn before saving an agent rule that RuleBot cannot do
yuwenmemon Oct 23, 2026
eada752
refactor(rules): run the agent rule check without the describeRule beta
yuwenmemon Oct 26, 2026
7b65576
chore(rules): merge main and share the offline Try this instead guard
yuwenmemon Oct 28, 2026
ad0ad01
fix(rules): stop an agent rule check when the admin edits the text
yuwenmemon Oct 28, 2026
920828c
fix(rules): keep the agent rule check across Write tab switches
yuwenmemon Oct 30, 2026
6a23f67
chore(rules): merge main and use the Use suggestion row on agent rules
yuwenmemon Oct 30, 2026
4cf9558
fix(rules): clear a stale check after reload and block Enter on hidde…
yuwenmemon Nov 2, 2026
da048a7
fix(rules): check an edited fallback draft after a reload
yuwenmemon Nov 3, 2026
0cf3e67
Merge remote-tracking branch 'origin/main' into yuwen-683438-agentRul…
yuwenmemon Nov 3, 2026
b4fad8e
fix(rules): hide agent rule delete during the save check
yuwenmemon Nov 5, 2026
daf3e06
Merge remote-tracking branch 'origin/main' into yuwen-683438-agentRul…
yuwenmemon Nov 5, 2026
219cbed
fix(rules): announce the agent rule check and warning to screen readers
yuwenmemon Nov 6, 2026
bb824cd
Merge remote-tracking branch 'origin/main' into yuwen-683438-agentRul…
yuwenmemon Nov 6, 2026
9ff54cd
Merge remote-tracking branch 'origin/main' into yuwen-683438-agentRul…
yuwenmemon Nov 6, 2026
00246e4
Merge remote-tracking branch 'origin/main' into yuwen-683438-agentRul…
yuwenmemon Nov 6, 2026
c0a9eeb
fix(rules): stop the agent rule check when the discard prompt opens
yuwenmemon Nov 9, 2026
fcabb07
refactor(rules): drop displayName from ImpossibleRuleNotice
yuwenmemon Nov 10, 2026
560f1d2
Merge remote-tracking branch 'origin/main' into yuwen-683438-agentRul…
yuwenmemon Nov 10, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/CONST/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -650,6 +650,9 @@ const CONST = {

GENERATED_RULE: {
PROMPT_MAX_LENGTH: 6000,

// The slowest answers in the eval take about 13 seconds. After this time, the agent rule saves without an answer.
AGENT_RULE_CHECK_TIMEOUT_MS: 20000,
STATE: {
RULE: 'rule',
UNSUPPORTED: 'unsupported',
Expand Down
2 changes: 2 additions & 0 deletions src/languages/de.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9294,6 +9294,8 @@ Fügen Sie weitere Ausgabelimits hinzu, um den Cashflow Ihres Unternehmens zu sc
describeRuleForConcierge: 'Beschreiben Sie Ihre Regel und Concierge erstellt sie',
gotIt: 'Verstanden',
createRule: 'Regel erstellen',
saveAnyway: 'Trotzdem speichern',
checkingRule: 'Ihre Regel wird geprüft...',
fallbackBanner:
'Dies ist keine Standardregel, daher haben wir eine Agentenregel erstellt. Agentenregeln werden ausgeführt, wenn eine Ausgabe oder ein Bericht erstellt oder aktualisiert wird.',
fallbackBannerWithExplanation: (explanation: string) =>
Expand Down
2 changes: 2 additions & 0 deletions src/languages/el.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9748,6 +9748,8 @@ ${reportName}`,
describeRuleHeadline: 'Περιγράψτε τον κανόνα σας',
describeRuleForConcierge: 'Περιγράψτε τον κανόνα σας και το Concierge θα τον δημιουργήσει',
createRule: 'Δημιουργία κανόνα',
saveAnyway: 'Αποθήκευση ούτως ή άλλως',
checkingRule: 'Γίνεται έλεγχος του κανόνα σας...',
fallbackBanner:
'Αυτός δεν είναι τυπικός κανόνας, οπότε συντάξαμε έναν κανόνα πράκτορα. Οι κανόνες πράκτορα εκτελούνται όταν δημιουργείται ή ενημερώνεται ένα έξοδο ή μια αναφορά.',
fallbackBannerWithExplanation: (explanation: string) =>
Expand Down
2 changes: 2 additions & 0 deletions src/languages/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10204,6 +10204,8 @@ const translations = {
describeRuleForConcierge: 'Describe your rule and Concierge will build it',
disclaimer: 'AI agents can make mistakes.',
createRule: 'Create rule',
saveAnyway: 'Save anyway',
checkingRule: 'Checking your rule...',
fallbackBanner: "This isn't a standard rule, so we drafted an agent rule. Agent rules run when an expense or report is created or updated.",
fallbackBannerWithExplanation: (explanation: string) =>
`This isn't a standard rule, so we drafted an agent rule. Agent rules run when an expense or report is created or updated. ${explanation}`,
Expand Down
2 changes: 2 additions & 0 deletions src/languages/es.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9368,6 +9368,8 @@ ${reportName}`,
describeRuleForConcierge: 'Describe tu regla y Concierge la creará',
gotIt: 'Entendido',
createRule: 'Crear regla',
saveAnyway: 'Guardar de todos modos',
checkingRule: 'Comprobando tu regla...',
fallbackBanner: 'Esta no es una regla estándar, así que redactamos una regla de agente. Las reglas de agente se ejecutan cuando se crea o actualiza un gasto o un informe.',
fallbackBannerWithExplanation: (explanation: string) =>
`Esta no es una regla estándar, así que redactamos una regla de agente. Las reglas de agente se ejecutan cuando se crea o actualiza un gasto o un informe. ${explanation}`,
Expand Down
2 changes: 2 additions & 0 deletions src/languages/fr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9322,6 +9322,8 @@ Ajoutez davantage de règles de dépenses pour protéger la trésorerie de l’e
describeRuleForConcierge: 'Décrivez votre règle et Concierge la créera',
gotIt: 'Compris',
createRule: 'Créer une règle',
saveAnyway: 'Enregistrer quand même',
checkingRule: 'Vérification de votre règle...',
fallbackBanner:
'Ce n’est pas une règle standard, nous avons donc rédigé une règle d’agent. Les règles d’agent s’exécutent lorsqu’une dépense ou une note de frais est créée ou mise à jour.',
fallbackBannerWithExplanation: (explanation: string) =>
Expand Down
2 changes: 2 additions & 0 deletions src/languages/it.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9241,6 +9241,8 @@ Aggiungi altre regole di spesa per proteggere il flusso di cassa aziendale.`,
describeRuleForConcierge: 'Descrivi la tua regola e Concierge la creerà',
gotIt: 'Capito',
createRule: 'Crea regola',
saveAnyway: 'Salva comunque',
checkingRule: 'Verifica della tua regola in corso...',
fallbackBanner:
'Questa non è una regola standard, quindi abbiamo creato una regola agente. Le regole agente vengono eseguite quando una spesa o un report viene creato o aggiornato.',
fallbackBannerWithExplanation: (explanation: string) =>
Expand Down
2 changes: 2 additions & 0 deletions src/languages/ja.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9107,6 +9107,8 @@ ${reportName}`,
describeRuleForConcierge: 'ルールの内容を入力すると、Concierge が自動作成します',
gotIt: '了解しました',
createRule: 'ルールを作成',
saveAnyway: 'このまま保存',
checkingRule: 'ルールを確認しています...',
fallbackBanner: 'これは標準ルールではないため、エージェントルールを作成しました。エージェントルールは、経費またはレポートが作成または更新されたときに実行されます。',
fallbackBannerWithExplanation: (explanation: string) =>
`これは標準ルールではないため、エージェントルールを作成しました。エージェントルールは、経費またはレポートが作成または更新されたときに実行されます。${explanation}`,
Expand Down
2 changes: 2 additions & 0 deletions src/languages/nl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9214,6 +9214,8 @@ er bestedingsregels toe om de kasstroom van het bedrijf te beschermen.`,
describeRuleForConcierge: 'Beschrijf je regel en Concierge bouwt hem voor je',
gotIt: 'Begrepen',
createRule: 'Regel maken',
saveAnyway: 'Toch opslaan',
checkingRule: 'Je regel wordt gecontroleerd...',
fallbackBanner:
'Dit is geen standaardregel, dus hebben we een agentregel opgesteld. Agentregels worden uitgevoerd wanneer een declaratie of rapport wordt aangemaakt of bijgewerkt.',
fallbackBannerWithExplanation: (explanation: string) =>
Expand Down
2 changes: 2 additions & 0 deletions src/languages/pl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9248,6 +9248,8 @@ Dodaj więcej zasad wydatków, żeby chronić płynność finansową firmy.`,
describeRuleForConcierge: 'Opisz swoją regułę, a Concierge ją utworzy',
gotIt: 'Jasne',
createRule: 'Utwórz regułę',
saveAnyway: 'Zapisz mimo to',
checkingRule: 'Sprawdzanie reguły...',
fallbackBanner:
'To nie jest standardowa reguła, więc przygotowaliśmy regułę agenta. Reguły agenta są uruchamiane, gdy wydatek lub raport zostanie utworzony albo zaktualizowany.',
fallbackBannerWithExplanation: (explanation: string) =>
Expand Down
2 changes: 2 additions & 0 deletions src/languages/pt-BR.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9234,6 +9234,8 @@ Adicione mais regras de gasto para proteger o fluxo de caixa da empresa.`,
describeRuleForConcierge: 'Descreva sua regra e o Concierge vai criá-la',
gotIt: 'Entendi',
createRule: 'Criar regra',
saveAnyway: 'Salvar mesmo assim',
checkingRule: 'Verificando sua regra...',
fallbackBanner:
'Esta não é uma regra padrão, então criamos uma regra de agente. As regras de agente são executadas quando uma despesa ou um relatório é criado ou atualizado.',
fallbackBannerWithExplanation: (explanation: string) =>
Expand Down
2 changes: 2 additions & 0 deletions src/languages/zh-hans.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8881,6 +8881,8 @@ ${reportName}`,
describeRuleForConcierge: '描述你的规则,Concierge 会帮你创建',
gotIt: '知道了',
createRule: '创建规则',
saveAnyway: '仍然保存',
checkingRule: '正在检查你的规则...',
fallbackBanner: '这不是一条标准规则,所以我们起草了一条代理规则。代理规则会在报销或报表被创建或更新时运行。',
fallbackBannerWithExplanation: (explanation: string) => `这不是一条标准规则,所以我们起草了一条代理规则。代理规则会在报销或报表被创建或更新时运行。${explanation}`,
},
Expand Down
43 changes: 42 additions & 1 deletion src/libs/actions/Policy/Rules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,45 @@ function generateRule(policyID: string, prompt: string, ruleType?: GeneratedRule
return generationID;
}

type AgentRuleFormID = typeof ONYXKEYS.FORMS.ADD_AGENT_RULE_FORM | typeof ONYXKEYS.FORMS.EDIT_AGENT_RULE_FORM;

/**
* Asks Concierge whether RuleBot can carry out an agent rule before the rule saves. The agent rule form shows its loading
* state until the answer arrives under `ONYXKEYS.GENERATED_RULE`. A failed request gets a `failed` answer, so the rule
* still saves.
* @returns the generationID the answer carries
*/
function checkAgentRulePrompt(formID: AgentRuleFormID, policyID: string, prompt: string): string {
const generationID = rand64();
type CheckAgentRuleKey = AgentRuleFormID | typeof ONYXKEYS.GENERATED_RULE;

const optimisticData: Array<OnyxUpdate<CheckAgentRuleKey>> = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: formID,
value: {isLoading: true},
},
];
Comment on lines +384 to +390

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Do we need a finallyData value as well that clears isLoading?

const failureData: Array<OnyxUpdate<CheckAgentRuleKey>> = [
{
onyxMethod: Onyx.METHOD.SET,
key: ONYXKEYS.GENERATED_RULE,
value: {generationID, state: CONST.GENERATED_RULE.STATE.FAILED},
},
];

const parameters: GenerateRuleParams = {policyID, generationID, prompt};

API.write(WRITE_COMMANDS.GENERATE_RULE, parameters, {optimisticData, failureData});

return generationID;
}

/** Stops the loading state of an agent rule form */
function stopAgentRuleCheckLoading(formID: AgentRuleFormID) {
Onyx.merge(formID, {isLoading: false});
}

/** Shows on the prompt form why a description did not become a rule */
function setNewRulePromptError(state: GeneratedRuleState) {
setNewRulePromptErrorMessage(PROMPT_ERROR_BY_STATE[state] ?? 'common.genericErrorMessage');
Expand Down Expand Up @@ -682,9 +721,11 @@ export {
clearGeneratedRule,
clearNewRulePrompt,
stopNewRulePromptLoading,
checkAgentRulePrompt,
stopAgentRuleCheckLoading,
updatePolicyAgentRule,
deletePolicyAgentRule,
clearMerchantRuleErrors,
clearPolicyAgentRuleErrors,
};
export type {ImportedMerchantRule};
export type {AgentRuleFormID, ImportedMerchantRule};
65 changes: 45 additions & 20 deletions src/pages/workspace/rules/AgentRules/AddAgentRulePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -75,12 +75,25 @@ function AddAgentRulePage({
const [activeTabPolicyID, setActiveTabPolicyID] = useState(policyID);
const [draftValues] = useOnyx(ONYXKEYS.FORMS.ADD_AGENT_RULE_FORM_DRAFT);
const [generatedRule] = useOnyx(ONYXKEYS.GENERATED_RULE);
const [isCheckingRule = false] = useOnyx(ONYXKEYS.FORMS.ADD_AGENT_RULE_FORM, {selector: (form) => !!form?.isLoading});
const icons = useMemoizedLazyExpensifyIcons(['Feed', 'Pencil', 'Info']);

const hasDraftPrompt = !!draftValues?.[INPUT_IDS.PROMPT]?.trim();
const [selectedSuggestion, setSelectedSuggestion] = useState<SuggestedAgentRule>();

// A new Write tab stops the check of the previous tab. That check then cannot save its text. The page mounts a new
// Write tab when the admin picks a suggestion, because the suggestion replaces the text. It also mounts one when the
// discard prompt opens during a check, because an answer while the prompt is open must not save the rule.
const [writeTabKey, setWriteTabKey] = useState(0);
const isDraftFromFallback = !!generationID && !selectedSuggestion;
const fallbackExplanation = generatedRule?.generationID === generationID ? generatedRule?.explanation : undefined;
const fallbackAnswer = generatedRule?.generationID === generationID ? generatedRule : undefined;
const fallbackExplanation = fallbackAnswer?.explanation;

// A suggestion or an agent rule that Concierge wrote saves without a check while the admin leaves its text unchanged.
// The answer keeps the agent rule of Concierge after a reload. The draft can hold changes of the admin, and no other
// value keeps the description that the admin sent. Therefore only the agent rule of the answer counts as checked text.
const generatedAgentRulePrompt = fallbackAnswer?.state === CONST.GENERATED_RULE.STATE.AGENT_RULE ? fallbackAnswer.agentRulePrompt : undefined;
const checkedPrompt = selectedSuggestion?.prompt ?? generatedAgentRulePrompt;

// The draft can load after the first render. Open Write one time only, because the admin must still be able to go
// to Suggestions.
Expand Down Expand Up @@ -110,6 +123,12 @@ function AddAgentRulePage({

const {suppressDiscardPrompt} = useDiscardChangesConfirmation({
getHasUnsavedChanges: () => hasDraftPrompt,
onVisibilityChange: (isVisible) => {
if (!isVisible || !isCheckingRule) {
return;
}
setWriteTabKey((key) => key + 1);
},
onConfirm: () => clearDraftValues(ONYXKEYS.FORMS.ADD_AGENT_RULE_FORM),
});

Expand All @@ -132,6 +151,7 @@ function AddAgentRulePage({
}
setDraftValues(ONYXKEYS.FORMS.ADD_AGENT_RULE_FORM, {[INPUT_IDS.PROMPT]: suggestion.prompt});
setSelectedSuggestion(suggestion);
setWriteTabKey((key) => key + 1);
setActiveTab(CONST.TAB.AGENT_RULE.WRITE);
};

Expand Down Expand Up @@ -254,25 +274,30 @@ function AddAgentRulePage({
onSelectSuggestion={selectSuggestion}
/>
</View>
{activeTab === CONST.TAB.AGENT_RULE.WRITE && (
<>
{isDraftFromFallback && (
<Banner
text={
fallbackExplanation
? translate('workspace.rules.agentRules.fallbackBannerWithExplanation', fallbackExplanation)
: translate('workspace.rules.agentRules.fallbackBanner')
}
icon={icons.Info}
iconSize={CONST.ICON_SIZE.SMALL}
shouldShowIcon
containerStyles={[styles.mh5, styles.ph0, styles.pt1, styles.pb4, styles.bgTransparent]}
textStyles={[styles.breakWord, styles.textSupporting]}
/>
)}
<AddAgentRuleWriteTab onSave={saveRule} />
</>
)}
{/* The Write tab stays mounted on Suggestions, so that a running check and its answer stay with the admin's text */}
<View style={[styles.flex1, activeTab !== CONST.TAB.AGENT_RULE.WRITE && styles.dNone]}>
{isDraftFromFallback && (
<Banner
text={
fallbackExplanation
? translate('workspace.rules.agentRules.fallbackBannerWithExplanation', fallbackExplanation)
: translate('workspace.rules.agentRules.fallbackBanner')
}
icon={icons.Info}
iconSize={CONST.ICON_SIZE.SMALL}
shouldShowIcon
containerStyles={[styles.mh5, styles.ph0, styles.pt1, styles.pb4, styles.bgTransparent]}
textStyles={[styles.breakWord, styles.textSupporting]}
/>
)}
<AddAgentRuleWriteTab
key={writeTabKey}
policyID={policyID}
checkedPrompt={checkedPrompt}
isTabActive={activeTab === CONST.TAB.AGENT_RULE.WRITE}
onSave={saveRule}
/>
</View>
</View>
</ScreenWrapper>
</AccessOrNotFoundWrapper>
Expand Down
Loading
Loading