Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
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
98 changes: 70 additions & 28 deletions src/hooks/useAgentZeroStatusIndicator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ import type {ReportNameValuePairs} from '@src/types/onyx';
import type {NewestReportAction} from '@selectors/ReportAction';
import type {OnyxEntry} from 'react-native-onyx';

import {getNewestReportActionSelector} from '@selectors/ReportAction';
import {getAgentZeroProcessingLabel} from '@selectors/ReportNameValuePairs';
import {answeredTurnQuestionIDsSelector, getNewestReportActionSelector} from '@selectors/ReportAction';
import {getAgentZeroProcessingLabel, hasPersistedAgentZeroProcessingLabelSelector} from '@selectors/ReportNameValuePairs';
import {useEffect, useRef, useState, useSyncExternalStore} from 'react';

import useLocalize from './useLocalize';
Expand Down Expand Up @@ -42,6 +42,38 @@ const MIN_DISPLAY_TIME = 300; // ms
// Debounce delay for server label updates
const DEBOUNCE_DELAY = 150; // ms

/**
* Subscribes to one agent's optimistic entry in a report and finishes any tracked message once its
* reply is saved under the reserved ID in Onyx. Counting answered turns as done during render hides
* the indicator immediately instead of waiting for the cleanup effect, and also covers replies that
* arrived while this tab was offline.
*/
function useOptimisticAgentZeroEntry(reportID: string | undefined, agentAccountID: number | undefined, shouldCompleteAnsweredTurns = true) {
const subscribeToOptimisticStore = (onStoreChange: () => void) =>
reportID && agentAccountID !== undefined ? AgentZeroOptimisticStore.subscribeToEntry(reportID, agentAccountID, onStoreChange) : () => {};
const getOptimisticSnapshot = () => (reportID && agentAccountID !== undefined ? AgentZeroOptimisticStore.getEntry(reportID, agentAccountID) : undefined);
const optimisticEntry = useSyncExternalStore(subscribeToOptimisticStore, getOptimisticSnapshot, getOptimisticSnapshot);
const pendingTurns = optimisticEntry?.turns;
const shouldTrackReplies = shouldCompleteAnsweredTurns && !!reportID && agentAccountID !== undefined && !!pendingTurns?.length;
const [answeredQuestionIDs] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${shouldTrackReplies ? reportID : undefined}`, {
selector: answeredTurnQuestionIDsSelector(pendingTurns, agentAccountID),
});
useEffect(() => {
for (const questionReportActionID of answeredQuestionIDs ?? []) {
AgentZeroOptimisticStore.completeTurn(questionReportActionID);
}
}, [answeredQuestionIDs]);
const answeredTurnCount = answeredQuestionIDs?.length ?? 0;
const pendingOptimisticRequests = Math.max(0, AgentZeroOptimisticStore.getPendingCount(optimisticEntry) - answeredTurnCount);
const hasPendingTurns = (pendingTurns?.length ?? 0) > answeredTurnCount;

return {
optimisticEntry,
pendingOptimisticRequests,
hasPendingTurns,
};
}

/**
* Hook to manage the AgentZero status indicator for a single agent in a chat where AgentZero
* responds. One instance runs per actively-thinking agent (a room can hold several), so all
Expand All @@ -62,29 +94,30 @@ function useAgentZeroStatusIndicator(reportID: string, agentAccountID: number =
const serverLabelSelector = (reportNameValuePairs: OnyxEntry<ReportNameValuePairs>) => getAgentZeroProcessingLabel(reportNameValuePairs, agentAccountID);
const [serverLabel] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${reportID}`, {selector: serverLabelSelector});

// A label the server saved on the report, such as the escalation notice, is cleared only by the server and comes
// back on the next OpenReport. The local safety clears read this through a ref because they run from a timer.
const [hasPersistedLabel] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${reportID}`, {selector: hasPersistedAgentZeroProcessingLabelSelector});
const hasPersistedLabelRef = useRef<boolean>(!!hasPersistedLabel);
useEffect(() => {
hasPersistedLabelRef.current = !!hasPersistedLabel;
}, [hasPersistedLabel]);

// Track the newest report action so we can fetch missed actions and detect actual Concierge replies.
const [newestReportAction] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`, {selector: getNewestReportActionSelector});
const newestReportActionRef = useRef<NewestReportAction | undefined>(newestReportAction);
useEffect(() => {
newestReportActionRef.current = newestReportAction;
}, [newestReportAction]);

// Track pending optimistic requests with a counter, backed by a module-level store so
// the state survives ReportScreen remounts (switching chats and coming back). Each
// kickoffWaitingIndicator() call increments the counter; when a Concierge reply is
// detected (via Pusher, reconnect, or safety timeout), the entry is cleared — any
// signal that a response arrived resolves all pending requests (optimistic state is
// a display signal, not a queue).
const subscribeToOptimisticStore = (onStoreChange: () => void) =>
AgentZeroOptimisticStore.subscribe((updatedReportID, updatedAgentAccountID) => {
if (updatedReportID !== reportID || updatedAgentAccountID !== agentAccountID) {
return;
}
onStoreChange();
});
const getOptimisticSnapshot = () => AgentZeroOptimisticStore.getEntry(reportID, agentAccountID);
const optimisticEntry = useSyncExternalStore(subscribeToOptimisticStore, getOptimisticSnapshot, getOptimisticSnapshot);
const pendingOptimisticRequests = optimisticEntry?.count ?? 0;
// Track pending optimistic requests in a module-level store so the state survives
// ReportScreen remounts (switching chats and coming back). Messages sent to Concierge are
// tracked one by one and clear on their own reply or completion, so an older reply cannot
// clear a newer message. Other kickoffs are counted and clear on the agent's next reply
// or the safety timeout.
const {optimisticEntry, pendingOptimisticRequests, hasPendingTurns} = useOptimisticAgentZeroEntry(reportID, agentAccountID);
// Included in the label-sync effect deps below so restarting a queued turn's window rearms
// the safety timer even when pendingOptimisticRequests stays unchanged.
const optimisticStartedAt = optimisticEntry?.startedAt;
// Debounced label shown to the user — smooths rapid server label changes.
// displayedLabelRef mirrors state so the label-sync effect can read the current value
// without including displayedLabel in its dependency array (avoids extra effect cycles).
Expand Down Expand Up @@ -131,6 +164,7 @@ function useAgentZeroStatusIndicator(reportID: string, agentAccountID: number =
/**
* Hard-clear the indicator by resetting local state and clearing the Onyx NVP.
* Called as a safety net after MAX_INDICATOR_DURATION_MS if no response has arrived.
* A label the server saved on the report is left alone, because only the server ends it.
*/
const hardClearIndicator = () => {
// If offline, don't clear — the response may arrive when reconnected
Expand All @@ -139,9 +173,11 @@ function useAgentZeroStatusIndicator(reportID: string, agentAccountID: number =
}
clearSafetyTimer();
AgentZeroOptimisticStore.clear(reportID, agentAccountID);
displayedLabelRef.current = '';
setDisplayedLabel('');
clearAgentZeroProcessingIndicator(reportID, agentAccountID);
if (!hasPersistedLabelRef.current) {
displayedLabelRef.current = '';
setDisplayedLabel('');
clearAgentZeroProcessingIndicator(reportID, agentAccountID);
}
getNewerActions(reportID, newestReportActionRef.current?.reportActionID);
};

Expand Down Expand Up @@ -180,11 +216,13 @@ function useAgentZeroStatusIndicator(reportID: string, agentAccountID: number =
onReconnect: () => {
const wasOptimistic = pendingOptimisticRequests > 0;

if (wasOptimistic) {
// Only clear the NVP when no live or persisted server label is active, so a brief
// disconnect mid-run does not wipe the current status label and reasoning history.
if (wasOptimistic && !serverLabel && !hasPersistedLabelRef.current) {
clearAgentZeroProcessingIndicator(reportID, agentAccountID);
}

// Fetch missed actions so the Onyx-driven Concierge-reply detection can fire.
// Fetch missed actions so a reply that landed while offline can finish its message.
getNewerActions(reportID, newestReportActionRef.current?.reportActionID);

if (serverLabel || wasOptimistic) {
Expand Down Expand Up @@ -227,9 +265,8 @@ function useAgentZeroStatusIndicator(reportID: string, agentAccountID: number =
// the server NVP can briefly go truthy→falsy→truthy between processing phases (e.g.,
// "thinking..." → (gap) → "searching documentation..."), and clearing the optimistic
// floor here means a chat-switch during the gap lands on "no optimistic, no serverLabel
// → no indicator." The optimistic entry is cleared by authoritative signals only: the
// reply-detection effect (new agent action newer than baseline), the 120s safety
// timeout, or the onReconnect handler.
// → no indicator." The optimistic entry is cleared by a matching turn completion,
// legacy reply detection, the 120s safety timeout, or the onReconnect handler.
if (hasServerLabel || pendingOptimisticRequests > 0) {
startSafetyTimer();
}
Expand Down Expand Up @@ -280,7 +317,7 @@ function useAgentZeroStatusIndicator(reportID: string, agentAccountID: number =
}
clearTimeout(updateTimerRef.current);
};
}, [serverLabel, reasoningHistory.length, reportID, agentAccountID, pendingOptimisticRequests, translate, startSafetyTimer, clearSafetyTimer]);
}, [serverLabel, reasoningHistory.length, reportID, agentAccountID, pendingOptimisticRequests, optimisticStartedAt, translate, startSafetyTimer, clearSafetyTimer]);

useEffect(() => {
isOfflineRef.current = isOffline;
Expand Down Expand Up @@ -338,6 +375,10 @@ function useAgentZeroStatusIndicator(reportID: string, agentAccountID: number =
const newestActorAccountID = newestReportAction?.actorAccountID;
const newestActionID = newestReportAction?.reportActionID;
useEffect(() => {
// The newest reply can answer an older message. Tracked messages wait for their own reply or completion instead.
if (hasPendingTurns) {
return;
}
if (newestActorAccountID !== agentAccountID) {
return;
}
Expand All @@ -355,7 +396,7 @@ function useAgentZeroStatusIndicator(reportID: string, agentAccountID: number =
clearAgentZeroProcessingIndicator(reportID, agentAccountID);
clearSafetyTimer();
AgentZeroOptimisticStore.clear(reportID, agentAccountID);
}, [newestActorAccountID, newestActionID, serverLabel, pendingOptimisticRequests, reportID, clearSafetyTimer, agentAccountID]);
}, [newestActorAccountID, newestActionID, serverLabel, pendingOptimisticRequests, reportID, clearSafetyTimer, agentAccountID, hasPendingTurns]);

const isProcessing = !isOffline && isIndicatorActive;

Expand All @@ -367,3 +408,4 @@ function useAgentZeroStatusIndicator(reportID: string, agentAccountID: number =
}

export default useAgentZeroStatusIndicator;
export {useOptimisticAgentZeroEntry};
Loading
Loading