Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(approvals): surface parks that no chat thread or flow run will ever show

M3gA-Minde7e34f20108d
diff --git a/app/src/components/chat/UnroutedApprovalCard.tsx b/app/src/components/chat/UnroutedApprovalCard.tsx
new file mode 100644
index 0000000000..123e5ce4c9
--- /dev/null
+++ b/app/src/components/chat/UnroutedApprovalCard.tsx
@@ -0,0 +1,109 @@
+/**
+ * UnroutedApprovalCard — the banner for an approval no other surface claims.
+ *
+ * A park raised by a background trigger has no chat thread and no flow run, so
+ * neither `ApprovalRequestCard` nor `FlowApprovalRequestCard` will ever show
+ * it (openhuman#6406, general form openhuman#5746). {@link useUnroutedApprovals}
+ * finds those rows in the durable `approval_list_pending` queue; this renders
+ * one.
+ *
+ * Chrome is `ApprovalDecisionCard`, the same component the other two approval
+ * surfaces use, so all three read as one affordance family rather than three
+ * visually unrelated prompts for the same kind of decision.
+ *
+ * Only two decisions are offered. `approve_always_for_tool` is deliberately
+ * absent: this prompt exists precisely because the request arrived from
+ * attacker-influenceable content with no interactive session behind it, and a
+ * session-wide standing allowlist is the wrong thing to grant from a banner
+ * the user did not go looking for. Once is once.
+ */
+import debug from 'debug';
+import { type FC, useState } from 'react';
+
+import type { ApprovalDecision, PendingApproval } from '../../services/api/approvalApi';
+import ApprovalDecisionCard, {
+ type ApprovalDecisionAction,
+} from '../approvals/ApprovalDecisionCard';
+
+const log = debug('openhuman:chat:unrouted-approval-card');
+
+const ACTION_DECISIONS: Record<string, ApprovalDecision> = {
+ 'unrouted-approval-approve': 'approve_once',
+ 'unrouted-approval-deny': 'deny',
+};
+
+const ACTIONS: ApprovalDecisionAction[] = [
+ {
+ id: 'unrouted-approval-approve',
+ label: 'Approve once',
+ busyLabel: 'Approving…',
+ variant: 'primary',
+ },
+ {
+ id: 'unrouted-approval-deny',
+ label: 'Deny',
+ busyLabel: 'Denying…',
+ variant: 'secondary',
+ tone: 'danger',
+ },
+];
+
+/** `2026-09-23T04:12:00Z` -> `4:12 am`, or `''` when unparseable. */
+function formatRaisedAt(iso: string): string {
+ const at = new Date(iso);
+ if (Number.isNaN(at.getTime())) return '';
+ return at.toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' });
+}
+
+interface Props {
+ approval: PendingApproval;
+ busy: boolean;
+ onDecide: (requestId: string, decision: ApprovalDecision) => Promise<void>;
+}
+
+export const UnroutedApprovalCard: FC<Props> = ({ approval, busy, onDecide }) => {
+ const [busyActionId, setBusyActionId] = useState<string | null>(null);
+
+ const handleAction = (actionId: string) => {
+ const decision = ACTION_DECISIONS[actionId];
+ if (!decision || busy) return;
+ setBusyActionId(actionId);
+ log('deciding request_id=%s decision=%s', approval.request_id, decision);
+ void onDecide(approval.request_id, decision)
+ .catch(() => {
+ // The hook owns the error message and renders it above this card; the
+ // card only needs to stop looking busy so the decision can be retried.
+ })
+ .finally(() => setBusyActionId(null));
+ };
+
+ const raisedAt = formatRaisedAt(approval.created_at);
+
+ return (
+ <ApprovalDecisionCard
+ ariaLabel={`Background approval required: ${approval.tool_name}`}
+ testId="unrouted-approval-card"
+ summary={
+ <>
+ <span className="font-medium">Background task needs approval</span>
+ {' — '}
+ {approval.action_summary || approval.tool_name}
+ </>
+ }
+ metadata={
+ <>
+ <span data-testid="unrouted-approval-tool">{approval.tool_name}</span>
+ {raisedAt && <span> · raised {raisedAt}</span>}
+ {/* No thread to open: this ran with nobody watching, which is why it
+ is here rather than in a transcript. */}
+ <span> · no conversation</span>
+ </>
+ }
+ actions={ACTIONS}
+ busyActionId={busyActionId}
+ onAction={handleAction}
+ />
+ );
+};
+
+export default UnroutedApprovalCard;
diff --git a/app/src/features/conversations/Conversations.tsx b/app/src/features/conversations/Conversations.tsx
index ffea0ef5b8..a1f1b865a1 100644
--- a/app/src/features/conversations/Conversations.tsx
+++ b/app/src/features/conversations/Conversations.tsx
@@ -15,6 +15,7 @@ import ComposerTokenStats from '../../components/chat/ComposerTokenStats';
import { FlowApprovalRequestCard } from '../../components/chat/FlowApprovalRequestCard';
import IntegrationConnectCard from '../../components/chat/IntegrationConnectCard';
import QueuedFollowups from '../../components/chat/QueuedFollowups';
+import { UnroutedApprovalCard } from '../../components/chat/UnroutedApprovalCard';
import WorkflowProposalCard from '../../components/chat/WorkflowProposalCard';
import { ConfirmationModal } from '../../components/intelligence/ConfirmationModal';
import { SidebarContent } from '../../components/layout/shell/SidebarSlot';
@@ -46,6 +47,7 @@ import {
} from '../../features/human/chatMascot';
import MicComposer from '../../features/human/MicComposer';
import { useFlowApprovalRequests } from '../../hooks/useFlowApprovalRequests';
+import { useUnroutedApprovals } from '../../hooks/useUnroutedApprovals';
import { useUsageState } from '../../hooks/useUsageState';
import {
type Attachment,
@@ -418,6 +420,17 @@ const Conversations = ({
// selected thread and surfaced regardless of which one is open.
const { requests: flowApprovalRequests, dismiss: dismissFlowApprovalRequest } =
useFlowApprovalRequests();
+ // Approvals no other surface will show: a background trigger run has no chat
+ // thread and no flow context, so the gate parks it, nothing asks the user,
+ // and it TTL-denies after 600s (#6406; general form #5746). Polled from the
+ // durable `approval_list_pending` queue rather than a socket event, because
+ // the whole point is that it can be raised while nobody is watching.
+ const {
+ approvals: unroutedApprovals,
+ decidingId: unroutedDecidingId,
+ error: unroutedApprovalError,
+ decide: decideUnroutedApproval,
+ } = useUnroutedApprovals();
const pendingPlanReviewByThread = useAppSelector(
state => state.chatRuntime.pendingPlanReviewByThread
);
@@ -2139,6 +2152,29 @@ const Conversations = ({
</div>
) : null;
+ // Background-approval surface: parks raised with no chat thread and no flow
+ // run. Sits beside the flow deck because it is the same affordance with a
+ // different origin, and is likewise not thread-scoped — a pending row has no
+ // thread to be scoped to, which is exactly why it had no surface.
+ const unroutedApprovalDeck =
+ unroutedApprovals.length > 0 ? (
+ <div className="mb-2 flex flex-col gap-2" data-testid="unrouted-approval-deck">
+ {unroutedApprovalError && (
+ <p className="text-xs text-destructive" role="alert">
+ {unroutedApprovalError}
+ </p>
+ )}
+ {unroutedApprovals.map(approval => (
+ <UnroutedApprovalCard
+ key={approval.request_id}
+ approval={approval}
+ busy={unroutedDecidingId !== null}
+ onDecide={decideUnroutedApproval}
+ />
+ ))}
+ </div>
+ ) : null;
+
// Surface in-flight + failed artifact cards above the composer (#2779).
// Mirrors the approval-card placement so the user sees the spinner / error
// without scrolling. `ready` cards are delegated to the header ChatFilesChip
@@ -2345,6 +2381,8 @@ const Conversations = ({
{flowApprovalDeck}
+ {unroutedApprovalDeck}
+
{liveArtifactDeck}
{agentGateCards}
@@ -2528,6 +2566,10 @@ const Conversations = ({
banner carries the only Approve/Reject affordance — so they belong
with the gates, above the transient banners. */}
{flowApprovalDeck}
+ {/* Same reasoning, different origin: a background trigger's park blocks
+ until someone answers it, and this is the only place it is ever
+ asked. */}
+ {unroutedApprovalDeck}
{attachError && (
<div className="rounded-lg border border-coral-200 bg-coral-50 px-3 py-2">
<p className="text-xs text-coral-500" data-chat-send-error-code={attachError.code}>
diff --git a/app/src/hooks/__tests__/flowPendingApprovalsStore.cadence.test.ts b/app/src/hooks/__tests__/flowPendingApprovalsStore.cadence.test.ts
new file mode 100644
index 0000000000..e50d719d72
--- /dev/null
+++ b/app/src/hooks/__tests__/flowPendingApprovalsStore.cadence.test.ts
@@ -0,0 +1,92 @@
+/**
+ * The shared pending-approvals poller now serves consumers with different
+ * cadences, and must run at the fastest one anybody asked for.
+ *
+ * Before the background-approvals surface every consumer wanted 2s, because
+ * every consumer was watching a flow run the user had just started. The
+ * background surface is mounted for the whole session and only needs to notice
+ * a park with a 600s TTL, so polling an almost-always-empty table every 2s for
+ * the life of the app would be cost with no benefit. But a slow consumer must
+ * never be able to slow down a flow run the user IS watching.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { fetchPendingApprovals } from '../../services/api/approvalApi';
+import {
+ resetFlowPendingApprovalsStoreForTests,
+ retainFlowPendingApprovalsPolling,
+} from '../flowPendingApprovalsStore';
+
+vi.mock('../../services/api/approvalApi', async importOriginal => {
+ const actual = await importOriginal<typeof import('../../services/api/approvalApi')>();
+ return { ...actual, fetchPendingApprovals: vi.fn() };
+});
+
+/** Let the in-flight fetch settle so `scheduleNextPoll` has run. */
+const settle = () => vi.advanceTimersByTimeAsync(0);
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ resetFlowPendingApprovalsStoreForTests();
+ vi.mocked(fetchPendingApprovals).mockResolvedValue([]);
+});
+
+afterEach(() => {
+ resetFlowPendingApprovalsStoreForTests();
+ vi.useRealTimers();
+ vi.clearAllMocks();
+});
+
+describe('poll cadence across consumers', () => {
+ it('polls at the slow cadence when only a slow consumer is retained', async () => {
+ const release = retainFlowPendingApprovalsPolling(15_000);
+ await settle();
+ const afterFirst = vi.mocked(fetchPendingApprovals).mock.calls.length;
+
+ await vi.advanceTimersByTimeAsync(2_000);
+ expect(vi.mocked(fetchPendingApprovals).mock.calls.length).toBe(afterFirst);
+
+ await vi.advanceTimersByTimeAsync(13_000);
+ expect(vi.mocked(fetchPendingApprovals).mock.calls.length).toBeGreaterThan(afterFirst);
+ release();
+ });
+
+ it('speeds up immediately when a fast consumer joins a slow poll', async () => {
+ // THE branch that is easy to get wrong: the slow timer is already armed, so
+ // without re-arming, a flow inspector opening would wait out the remaining
+ // 15s before its first 2s tick — the user watching a run would see it stall.
+ const releaseSlow = retainFlowPendingApprovalsPolling(15_000);
+ await settle();
+ const beforeFast = vi.mocked(fetchPendingApprovals).mock.calls.length;
+
+ const releaseFast = retainFlowPendingApprovalsPolling(2_000);
+ await vi.advanceTimersByTimeAsync(2_000);
+
+ expect(vi.mocked(fetchPendingApprovals).mock.calls.length).toBeGreaterThan(beforeFast);
+ releaseFast();
+ releaseSlow();
+ });
+
+ it('returns to the slow cadence when the fast consumer leaves', async () => {
+ const releaseSlow = retainFlowPendingApprovalsPolling(15_000);
+ const releaseFast = retainFlowPendingApprovalsPolling(2_000);
+ await settle();
+ releaseFast();
+ await settle();
+ const afterRelease = vi.mocked(fetchPendingApprovals).mock.calls.length;
+
+ await vi.advanceTimersByTimeAsync(2_000);
+ expect(vi.mocked(fetchPendingApprovals).mock.calls.length).toBe(afterRelease);
+ releaseSlow();
+ });
+
+ it('stops polling once every consumer has released', async () => {
+ const release = retainFlowPendingApprovalsPolling(2_000);
+ await settle();
+ release();
+ const afterRelease = vi.mocked(fetchPendingApprovals).mock.calls.length;
+
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(vi.mocked(fetchPendingApprovals).mock.calls.length).toBe(afterRelease);
+ });
+});
diff --git a/app/src/hooks/__tests__/useUnroutedApprovals.test.tsx b/app/src/hooks/__tests__/useUnroutedApprovals.test.tsx
new file mode 100644
index 0000000000..f49daac7f2
--- /dev/null
+++ b/app/src/hooks/__tests__/useUnroutedApprovals.test.tsx
@@ -0,0 +1,161 @@
+/**
+ * The approvals nobody else will show.
+ *
+ * A background trigger's park has no chat thread and no flow context, so the
+ * gate publishes `ApprovalRequested` with `thread_id: None`, the web-channel
+ * subscriber drops it ("NOT surfacing"), and it TTL-denies after 600 s with
+ * the user never asked (openhuman#6406). This hook is the surface that asks.
+ *
+ * The assertions that matter are about the DISCRIMINATOR: it must show the
+ * unclaimed rows and stay out of the way of the two surfaces that already
+ * work. A hook that showed everything would double every chat approval; one
+ * that showed nothing would be the bug it is fixing.
+ */
+import { configureStore } from '@reduxjs/toolkit';
+import { renderHook, waitFor } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { Provider } from 'react-redux';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ decideApproval,
+ fetchPendingApprovals,
+ type PendingApproval,
+} from '../../services/api/approvalApi';
+import chatRuntimeReducer, { setPendingApprovalForThread } from '../../store/chatRuntimeSlice';
+import threadReducer from '../../store/threadSlice';
+import { resetFlowPendingApprovalsStoreForTests } from '../flowPendingApprovalsStore';
+import { useUnroutedApprovals } from '../useUnroutedApprovals';
+
+vi.mock('../../services/api/approvalApi', async importOriginal => {
+ const actual = await importOriginal<typeof import('../../services/api/approvalApi')>();
+ return { ...actual, fetchPendingApprovals: vi.fn(), decideApproval: vi.fn() };
+});
+
+function row(over: Partial<PendingApproval> = {}): PendingApproval {
+ return {
+ request_id: 'req-bg',
+ tool_name: 'triage.escalate',
+ action_summary: 'triage::ESCALATE target=orchestrator',
+ args_redacted: {},
+ session_id: 's1',
+ created_at: '2026-09-23T04:12:00.000Z',
+ expires_at: '2026-09-23T04:22:00.000Z',
+ ...over,
+ };
+}
+
+function mount(seed?: (store: ReturnType<typeof buildStore>) => void) {
+ const store = buildStore();
+ seed?.(store);
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <Provider store={store}>{children}</Provider>
+ );
+ return renderHook(() => useUnroutedApprovals(), { wrapper });
+}
+
+function buildStore() {
+ return configureStore({ reducer: { thread: threadReducer, chatRuntime: chatRuntimeReducer } });
+}
+
+beforeEach(() => {
+ resetFlowPendingApprovalsStoreForTests();
+ vi.mocked(decideApproval).mockResolvedValue(undefined as never);
+});
+
+afterEach(() => {
+ resetFlowPendingApprovalsStoreForTests();
+ vi.clearAllMocks();
+});
+
+describe('useUnroutedApprovals', () => {
+ it('surfaces a park that has no thread and no flow', async () => {
+ vi.mocked(fetchPendingApprovals).mockResolvedValue([row()]);
+ const { result } = mount();
+
+ await waitFor(() => expect(result.current.approvals).toHaveLength(1));
+ expect(result.current.approvals[0]?.request_id).toBe('req-bg');
+ });
+
+ it('leaves a flow-scoped park to the flow surface', async () => {
+ vi.mocked(fetchPendingApprovals).mockResolvedValue([
+ row({
+ request_id: 'req-flow',
+ source_context: { kind: 'flow', flow_id: 'f1', run_id: 'r1' },
+ }),
+ ]);
+ const { result } = mount();
+
+ // Give the poll a chance to land before asserting an absence.
+ await waitFor(() => expect(vi.mocked(fetchPendingApprovals)).toHaveBeenCalled());
+ await waitFor(() => expect(result.current.approvals).toEqual([]));
+ });
+
+ it('leaves a chat-routed park to the transcript card', async () => {
+ // Same row, twice: once as the durable pending row, once as the chat
+ // surface's live copy. Showing it here as well would put one approval in
+ // two places.
+ vi.mocked(fetchPendingApprovals).mockResolvedValue([row({ request_id: 'req-chat' })]);
+ const { result } = mount(store => {
+ store.dispatch(
+ setPendingApprovalForThread({
+ threadId: 't1',
+ approval: {
+ requestId: 'req-chat',
+ toolName: 'triage.escalate',
+ message: 'in the transcript already',
+ },
+ })
+ );
+ });
+
+ await waitFor(() => expect(vi.mocked(fetchPendingApprovals)).toHaveBeenCalled());
+ await waitFor(() => expect(result.current.approvals).toEqual([]));
+ });
+
+ it('shows a background park raised alongside an unrelated chat approval', async () => {
+ // The discriminator must exclude by request_id, not "is any chat approval
+ // open" — otherwise one chat gate hides every background one behind it.
+ vi.mocked(fetchPendingApprovals).mockResolvedValue([
+ row({ request_id: 'req-chat' }),
+ row({ request_id: 'req-bg' }),
+ ]);
+ const { result } = mount(store => {
+ store.dispatch(
+ setPendingApprovalForThread({
+ threadId: 't1',
+ approval: { requestId: 'req-chat', toolName: 'shell', message: 'in the transcript' },
+ })
+ );
+ });
+
+ await waitFor(() => expect(result.current.approvals).toHaveLength(1));
+ expect(result.current.approvals[0]?.request_id).toBe('req-bg');
+ });
+
+ it('records a decision through the shared approval RPC', async () => {
+ vi.mocked(fetchPendingApprovals).mockResolvedValue([row()]);
+ const { result } = mount();
+ await waitFor(() => expect(result.current.approvals).toHaveLength(1));
+
+ await result.current.decide('req-bg', 'approve_once');
+
+ expect(vi.mocked(decideApproval)).toHaveBeenCalledWith('req-bg', 'approve_once');
+ });
+
+ it('keeps the card and reports why when the decide fails', async () => {
+ // A failed decide leaves the core still parked, so the prompt must stay
+ // answerable rather than vanishing optimistically.
+ vi.mocked(fetchPendingApprovals).mockResolvedValue([row()]);
+ vi.mocked(decideApproval).mockRejectedValue(new Error('core unreachable'));
+ const { result } = mount();
+ await waitFor(() => expect(result.current.approvals).toHaveLength(1));
+
+ await expect(result.current.decide('req-bg', 'approve_once')).rejects.toThrow(
+ 'core unreachable'
+ );
+
+ await waitFor(() => expect(result.current.error).toBe('core unreachable'));
+ expect(result.current.approvals).toHaveLength(1);
+ });
+});
diff --git a/app/src/hooks/flowPendingApprovalsStore.ts b/app/src/hooks/flowPendingApprovalsStore.ts
index 8dcaac27bd..405a08b8e3 100644
--- a/app/src/hooks/flowPendingApprovalsStore.ts
+++ b/app/src/hooks/flowPendingApprovalsStore.ts
@@ -4,6 +4,10 @@ import { useCallback, useEffect, useSyncExternalStore } from 'react';
import { fetchPendingApprovals, type PendingApproval } from '../services/api/approvalApi';
const log = debug('flows:pending-approvals-store');
+/**
+ * Default cadence, and the one every flow consumer uses: a run the user is
+ * watching should feel live.
+ */
const POLL_INTERVAL_MS = 2000;
export interface FlowPendingApprovalsSnapshot {
@@ -40,7 +44,19 @@ const makeSnapshot = (
const INITIAL_SNAPSHOT = makeSnapshot([], null, false);
let snapshot = INITIAL_SNAPSHOT;
-let retainCount = 0;
+/**
+ * One entry per active consumer, holding the cadence it asked for. The poll
+ * runs at the FASTEST cadence anyone wants, so a slow background consumer
+ * never delays a flow run the user is watching, and a fast flow consumer
+ * leaving does not strand the queue at its cadence.
+ *
+ * An array rather than a count because consumers now differ: the background
+ * approvals surface is mounted for the whole session and only needs to notice
+ * a 600 s park, while a flow inspector wants 2 s. Polling a table that is
+ * almost always empty every 2 s for an entire session, to catch something with
+ * a ten-minute lifetime, is cost with no benefit.
+ */
+let retainedIntervals: number[] = [];
let pollTimer: number | undefined;
let requestGeneration = 0;
let nextRequestId = 0;
@@ -66,12 +82,23 @@ function clearPollTimer(): void {
pollTimer = undefined;
}
+/** The fastest cadence any active consumer asked for. */
+function effectiveIntervalMs(): number {
+ return retainedIntervals.length === 0 ? POLL_INTERVAL_MS : Math.min(...retainedIntervals);
+}
+
function scheduleNextPoll(generation: number): void {
- if (retainCount === 0 || generation !== requestGeneration || pollTimer !== undefined) return;
+ if (
+ retainedIntervals.length === 0 ||
+ generation !== requestGeneration ||
+ pollTimer !== undefined
+ ) {
+ return;
+ }
pollTimer = window.setTimeout(() => {
pollTimer = undefined;
void startRefresh(true);
- }, POLL_INTERVAL_MS);
+ }, effectiveIntervalMs());
}
export function subscribeFlowPendingApprovals(listener: () => void): () => void {
@@ -93,16 +120,22 @@ function startRefresh(publishOnlyWhenRetained = false): Promise<void> {
const request = (async () => {
try {
const approvals = await fetchPendingApprovals();
- if (generation !== requestGeneration || (publishOnlyWhenRetained && retainCount === 0)) {
+ if (
+ generation !== requestGeneration ||
+ (publishOnlyWhenRetained && retainedIntervals.length === 0)
+ ) {
return;
}
- emit(makeSnapshot(approvals, null, retainCount > 0));
+ emit(makeSnapshot(approvals, null, retainedIntervals.length > 0));
log('refresh succeeded approval_count=%d', approvals.length);
} catch (error) {
- if (generation !== requestGeneration || (publishOnlyWhenRetained && retainCount === 0)) {
+ if (
+ generation !== requestGeneration ||
+ (publishOnlyWhenRetained && retainedIntervals.length === 0)
+ ) {
return;
}
- emit(makeSnapshot(snapshot.approvals, normalizeError(error), retainCount > 0));
+ emit(makeSnapshot(snapshot.approvals, normalizeError(error), retainedIntervals.length > 0));
const errorType = error instanceof Error ? error.name : typeof error;
log('refresh failed error_type=%s', errorType);
} finally {
@@ -124,10 +157,13 @@ export function refreshFlowPendingApprovals(): Promise<void> {
clearPollTimer();
const generation = requestGeneration;
const activeRequest = inFlight;
- const queuedWhileRetained = retainCount > 0;
+ const queuedWhileRetained = retainedIntervals.length > 0;
const queued: Promise<void> = activeRequest.then(() => {
if (queuedRefresh === queued) queuedRefresh = null;
- if (generation !== requestGeneration || (queuedWhileRetained && retainCount === 0)) {
+ if (
+ generation !== requestGeneration ||
+ (queuedWhileRetained && retainedIntervals.length === 0)
+ ) {
return;
}
return startRefresh();
@@ -136,26 +172,50 @@ export function refreshFlowPendingApprovals(): Promise<void> {
return queued;
}
-export function retainFlowPendingApprovalsPolling(): () => void {
- retainCount += 1;
- if (retainCount === 1) {
+export function retainFlowPendingApprovalsPolling(
+ intervalMs: number = POLL_INTERVAL_MS
+): () => void {
+ const previousInterval = effectiveIntervalMs();
+ retainedIntervals.push(intervalMs);
+ if (retainedIntervals.length === 1) {
emit(makeSnapshot(snapshot.approvals, snapshot.error, true));
if (!inFlight) void startRefresh(true);
+ } else if (intervalMs < previousInterval) {
+ // A faster consumer joined an already-scheduled slow poll. Re-arm, or it
+ // would wait out the slow timer before honouring the new cadence.
+ clearPollTimer();
+ scheduleNextPoll(requestGeneration);
}
let released = false;
return () => {
if (released) return;
released = true;
- retainCount = Math.max(0, retainCount - 1);
- if (retainCount > 0) return;
+ const previous = effectiveIntervalMs();
+ const index = retainedIntervals.indexOf(intervalMs);
+ if (index !== -1) retainedIntervals.splice(index, 1);
+ if (retainedIntervals.length > 0) {
+ // Symmetric with the join branch above: the departing consumer may have
+ // been the fast one, leaving its short timer armed on behalf of
+ // consumers that asked for less. Re-arm at the cadence that is now
+ // current, or the queue keeps polling fast for one more tick after the
+ // flow inspector that wanted it has closed.
+ if (effectiveIntervalMs() > previous) {
+ clearPollTimer();
+ scheduleNextPoll(requestGeneration);
+ }
+ return;
+ }
clearPollTimer();
emit(makeSnapshot(snapshot.approvals, snapshot.error, false));
};
}
-export function useFlowPendingApprovalsSource(enabled: boolean): FlowPendingApprovalsSnapshot {
+export function useFlowPendingApprovalsSource(
+ enabled: boolean,
+ intervalMs: number = POLL_INTERVAL_MS
+): FlowPendingApprovalsSnapshot {
const subscribe = useCallback(
(listener: () => void) => (enabled ? subscribeFlowPendingApprovals(listener) : () => undefined),
[enabled]
@@ -168,8 +228,8 @@ export function useFlowPendingApprovalsSource(enabled: boolean): FlowPendingAppr
useEffect(() => {
if (!enabled) return;
- return retainFlowPendingApprovalsPolling();
- }, [enabled]);
+ return retainFlowPendingApprovalsPolling(intervalMs);
+ }, [enabled, intervalMs]);
return current;
}
@@ -178,7 +238,7 @@ export function resetFlowPendingApprovalsStoreForTests(): void {
clearPollTimer();
requestGeneration += 1;
activeRequestId = null;
- retainCount = 0;
+ retainedIntervals = [];
inFlight = null;
queuedRefresh = null;
snapshot = INITIAL_SNAPSHOT;
diff --git a/app/src/hooks/useUnroutedApprovals.ts b/app/src/hooks/useUnroutedApprovals.ts
new file mode 100644
index 0000000000..9e95a400cc
--- /dev/null
+++ b/app/src/hooks/useUnroutedApprovals.ts
@@ -0,0 +1,125 @@
+/**
+ * useUnroutedApprovals — the approvals no other surface will ever show.
+ *
+ * The approval gate parks a tool call and waits for a decision. Which surface
+ * asks the user for that decision depends on where the call came from:
+ *
+ * - a chat turn -> `ApprovalRequestCard` in the transcript, routed by the
+ * `approval_request` socket event's `thread_id`
+ * - a flow run -> `FlowApprovalRequestCard`, routed by the park's
+ * `source_context`
+ * - anything else-> nothing, until this hook
+ *
+ * That last case is not hypothetical. A background trigger run (a Composio
+ * Gmail trigger reaching `triage.escalate`) has no chat thread and no flow
+ * context, so the gate publishes `ApprovalRequested` with `thread_id: None`
+ * and `client_id: None`, the web-channel subscriber drops it — its own log
+ * line says "NOT surfacing" — and the park sits for its full 600 s TTL and is
+ * denied as `[policy-denied]`. The user is never asked. Every escalated email
+ * is silently dropped (openhuman#6406; the general form is openhuman#5746).
+ *
+ * ## Why poll the durable queue instead of listening for an event
+ *
+ * The defining property of this failure is that **nobody is looking**: the
+ * trigger can fire with the app shut. A socket broadcast with no subscriber at
+ * that instant is lost exactly as completely as the event the subscriber drops
+ * today. `approval_list_pending` is session-agnostic and reads the persisted
+ * `pending_approvals` rows, so a park raised while the app was closed is still
+ * there when it opens. That is what openhuman#5746's first acceptance bullet
+ * asks for in as many words: "an approvals inbox / queue ... rather than only
+ * as an event on a bus nobody is listening to at that moment".
+ *
+ * It is also origin-agnostic. Anything the gate parks and no one claims shows
+ * up here — `ExternalChannel` and `TrustedAutomation{GoalContinuation}` parks
+ * included, not just triage.
+ *
+ * ## The discriminator, and which way it fails
+ *
+ * A pending row carries no `thread_id`, so it cannot say on its own whether a
+ * chat surface is already showing it. Two exclusions instead:
+ *
+ * - a `source_context` means a flow surface owns it;
+ * - a `request_id` already in `pendingApprovalByThread` means the chat
+ * transcript is already showing its card.
+ *
+ * Everything else is unclaimed. If that is ever wrong the user sees one
+ * approval in two places, which is the direction to be wrong in — the bug
+ * being fixed is that they see it in none.
+ */
+import { useCallback, useMemo, useRef, useState } from 'react';
+
+import {
+ type ApprovalDecision,
+ decideApproval,
+ type PendingApproval,
+} from '../services/api/approvalApi';
+import { useAppSelector } from '../store/hooks';
+import {
+ refreshFlowPendingApprovals,
+ useFlowPendingApprovalsSource,
+} from './flowPendingApprovalsStore';
+
+/**
+ * Cadence for this consumer. A flow inspector polls at 2 s because the user is
+ * watching a run; a background park has a 600 s TTL and nobody is watching
+ * anything, so 15 s notices it within 2.5% of its life at a fraction of the
+ * cost. The shared store polls at whatever its fastest consumer asked for, so
+ * this never slows a flow run down.
+ */
+const BACKGROUND_POLL_INTERVAL_MS = 15_000;
+
+export interface UseUnroutedApprovalsResult {
+ /** Parks no other surface will show, oldest first (server order). */
+ approvals: PendingApproval[];
+ /** `request_id` currently being decided, or `null`. */
+ decidingId: string | null;
+ /** Set when the last decide failed; cleared on the next attempt. */
+ error: string | null;
+ decide: (requestId: string, decision: ApprovalDecision) => Promise<void>;
+}
+
+export function useUnroutedApprovals(enabled = true): UseUnroutedApprovalsResult {
+ const [decidingId, setDecidingId] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const source = useFlowPendingApprovalsSource(enabled, BACKGROUND_POLL_INTERVAL_MS);
+ const pendingApprovalByThread = useAppSelector(
+ state => state.chatRuntime.pendingApprovalByThread
+ );
+
+ const chatRoutedIds = useMemo(() => {
+ const ids = new Set<string>();
+ for (const approval of Object.values(pendingApprovalByThread ?? {})) {
+ if (approval?.requestId) ids.add(approval.requestId);
+ }
+ return ids;
+ }, [pendingApprovalByThread]);
+
+ const approvals = useMemo(
+ () =>
+ enabled
+ ? source.approvals.filter(
+ approval => !approval.source_context && !chatRoutedIds.has(approval.request_id)
+ )
+ : [],
+ [chatRoutedIds, enabled, source.approvals]
+ );
+
+ const mountedRef = useRef(true);
+ const decide = useCallback(async (requestId: string, decision: ApprovalDecision) => {
+ setDecidingId(requestId);
+ setError(null);
+ try {
+ await decideApproval(requestId, decision);
+ // Reconcile every approval surface at once rather than waiting out the
+ // 15 s poll — the card must not linger after it has been answered.
+ await refreshFlowPendingApprovals();
+ } catch (err) {
+ if (mountedRef.current) setError(err instanceof Error ? err.message : String(err));
+ throw err;
+ } finally {
+ if (mountedRef.current) setDecidingId(null);
+ }
+ }, []);
+
+ return { approvals, decidingId, error, decide };
+}
diff --git a/app/src/pages/__tests__/Conversations.unroutedApproval.test.tsx b/app/src/pages/__tests__/Conversations.unroutedApproval.test.tsx
new file mode 100644
index 0000000000..1a92e4442f
--- /dev/null
+++ b/app/src/pages/__tests__/Conversations.unroutedApproval.test.tsx
@@ -0,0 +1,154 @@
+/**
+ * The background-approval banner, proven from the LIVE `/chat` route.
+ *
+ * The bug being fixed (openhuman#6406) is entirely one of reachability: the
+ * approval gate parks a background trigger's tool call, the row is persisted
+ * and listable, `approval_decide` works — and no component ever asks for it,
+ * so the park TTL-denies with the user never shown anything. A test that
+ * mounted the card directly would prove nothing about that, which is the whole
+ * point of the defect. So this renders `Conversations` at `/chat/:threadId?`,
+ * the real route element, and asserts the banner arrives on its own.
+ */
+import { combineReducers, configureStore } from '@reduxjs/toolkit';
+import { render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { Provider } from 'react-redux';
+import { MemoryRouter, Route, Routes } from 'react-router-dom';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { SidebarSlotOutlet, SidebarSlotProvider } from '../../components/layout/shell/SidebarSlot';
+import { resetFlowPendingApprovalsStoreForTests } from '../../hooks/flowPendingApprovalsStore';
+import {
+ decideApproval,
+ fetchPendingApprovals,
+ type PendingApproval,
+} from '../../services/api/approvalApi';
+import chatRuntimeReducer from '../../store/chatRuntimeSlice';
+import layoutReducer from '../../store/layoutSlice';
+import socketReducer from '../../store/socketSlice';
+import themeReducer from '../../store/themeSlice';
+import threadReducer from '../../store/threadSlice';
+
+vi.mock('../../services/api/approvalApi', async importOriginal => {
+ const actual = await importOriginal<typeof import('../../services/api/approvalApi')>();
+ return { ...actual, fetchPendingApprovals: vi.fn(), decideApproval: vi.fn() };
+});
+vi.mock('../../services/chatService', async importOriginal => {
+ // Spread the original rather than listing exports: this module has grown
+ // several (`useRustChat`, …) and a hand-written list silently breaks the
+ // whole render the next time one is added.
+ const actual = await importOriginal<typeof import('../../services/chatService')>();
+ return {
+ ...actual,
+ chatCancel: vi.fn().mockResolvedValue(true),
+ chatClearQueue: vi.fn().mockResolvedValue(0),
+ chatSend: vi.fn().mockResolvedValue(undefined),
+ };
+});
+vi.mock('../../services/api/threadApi', () => ({
+ threadApi: {
+ createNewThread: vi.fn().mockResolvedValue({ id: 'new-thread', labels: [] }),
+ getThreads: vi.fn().mockResolvedValue([]),
+ getMessages: vi.fn().mockResolvedValue([]),
+ getDerivedTranscript: vi
+ .fn()
+ .mockResolvedValue({
+ threadId: 't-1',
+ items: [],
+ total: 0,
+ hasMore: false,
+ hasTranscript: false,
+ }),
+ },
+}));
+vi.mock('../../hooks/useUsageState', () => ({
+ // Reads `useCoreState`, which needs a provider this test does not mount.
+ useUsageState: () => ({ usage: null, loading: false, error: null, refresh: vi.fn() }),
+}));
+vi.mock('../../components/chat/ChatNewWindowHero', () => ({ default: () => null }));
+vi.mock('../../lib/coreState/store', () => ({
+ getCoreStateSnapshot: vi.fn(() => ({ isBootstrapping: false, isReady: true })),
+ subscribeCoreState: vi.fn(() => () => undefined),
+}));
+
+const BACKGROUND_PARK: PendingApproval = {
+ request_id: 'req-triage-1',
+ tool_name: 'triage.escalate',
+ action_summary: 'triage::ESCALATE target=orchestrator prompt_chars=812',
+ args_redacted: { action: 'escalate' },
+ session_id: 's1',
+ created_at: '2026-09-23T04:12:00.000Z',
+ expires_at: '2026-09-23T04:22:00.000Z',
+};
+
+async function renderChatRoute() {
+ const store = configureStore({
+ reducer: combineReducers({
+ thread: threadReducer,
+ layout: layoutReducer,
+ socket: socketReducer,
+ chatRuntime: chatRuntimeReducer,
+ theme: themeReducer,
+ }),
+ });
+ const { default: Conversations } = await import('../../features/conversations/Conversations');
+ render(
+ <Provider store={store}>
+ <MemoryRouter initialEntries={['/chat']}>
+ <SidebarSlotProvider>
+ <SidebarSlotOutlet />
+ <Routes>
+ <Route path="/chat/:threadId?" element={<Conversations />} />
+ </Routes>
+ </SidebarSlotProvider>
+ </MemoryRouter>
+ </Provider>
+ );
+ return store;
+}
+
+beforeEach(() => {
+ resetFlowPendingApprovalsStoreForTests();
+ vi.mocked(decideApproval).mockResolvedValue(undefined as never);
+});
+
+afterEach(() => {
+ resetFlowPendingApprovalsStoreForTests();
+ vi.clearAllMocks();
+});
+
+describe('a background approval on /chat', () => {
+ it('surfaces a park that has no thread behind it', async () => {
+ vi.mocked(fetchPendingApprovals).mockResolvedValue([BACKGROUND_PARK]);
+
+ await renderChatRoute();
+
+ const card = await screen.findByTestId('unrouted-approval-card', undefined, { timeout: 5000 });
+ // The tool, so the user can tell what is being asked, not just that
+ // something is.
+ expect(screen.getByTestId('unrouted-approval-tool')).toHaveTextContent('triage.escalate');
+ expect(card).toHaveTextContent('triage::ESCALATE');
+ });
+
+ it('records the decision through the shared approval RPC', async () => {
+ vi.mocked(fetchPendingApprovals).mockResolvedValue([BACKGROUND_PARK]);
+ await renderChatRoute();
+ await screen.findByTestId('unrouted-approval-card', undefined, { timeout: 5000 });
+
+ await userEvent.click(screen.getByRole('button', { name: /approve once/i }));
+
+ await waitFor(() =>
+ expect(vi.mocked(decideApproval)).toHaveBeenCalledWith('req-triage-1', 'approve_once')
+ );
+ });
+
+ it('renders nothing when the queue is empty', async () => {
+ // The banner must not be a permanent fixture of the chat surface.
+ vi.mocked(fetchPendingApprovals).mockResolvedValue([]);
+
+ await renderChatRoute();
+
+ await waitFor(() => expect(vi.mocked(fetchPendingApprovals)).toHaveBeenCalled());
+ expect(screen.queryByTestId('unrouted-approval-card')).toBeNull();
+ });
+});