Skip to content

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

fix(chat): answer the tool-approval gate on the assistant-ui surface\n\nA `Prompt`-class tool call parks the turn on the ApprovalGate and waits for\na decision. On `/chat` no decision could be given: the socket handler wrote\n`chatRuntime.pendingApprovalByThread`, and the only reader of that slice\n(`ApprovalRequestCard`) lives inside `Conversations`' `legacyMainPanel`,\nwhich renders only in `mic-cloud` composer mode. The observable failure was\na shell call spinning forever with no prompt, then the core dropping the\nparked call as denied ~2 minutes later and the agent answering with a\nsentence.\n\nBoth halves of the seam were missing, so both are repaired here.\n\nData. The external-store adapter now selects the parked approval and hangs\nit off the tool part it gates, matching by tool name against the newest\nunsettled call — the `approval_request` event carries no `tool_call_id`.\nWhen no row matches (the progress channel is bounded and drops frames, and\nthe gate can park before the `tool_call` frame lands) a part is synthesised\nrather than dropped: a prompt in an imperfect slot beats no prompt at all.\nThe tail message goes to `requires-action`/`interrupt`, which is what gives\nthe gated part the status a decision renders from, and the tail is now\nminted even when the lifecycle reports the turn settled.\n\nDecisions route through `onRespondToToolApproval` to the existing\n`openhuman.approval_decide` RPC. Supplying that callback is load-bearing:\nwithout it the runtime throws "Runtime does not support tool approvals."\nrather than no-opping. Option ids are the core's own decision literals, so\nthey forward with no translation table.\n\nRender. `OpenHumanToolCall` forwarded four fields and dropped `status`,\n`approval` and `respondToApproval`, so a parked call rendered as an\nordinary running one. It now carries a localized decision row, placed\noutside the disclosure — a decision the turn is blocked on must not be\nhidden behind something to open. The kit's own approval-capable\n`ToolFallback` stays unused: `AssistantUiChat` overrides it, and it\nhardcodes English.\n\n`composio_connect` parks on the same gate but must not get approve/deny —\napproving without connecting resumes the agent against a toolkit with no\ncredentials. It routes to the existing `IntegrationConnectCard`, which runs\nthe OAuth handoff and resolves the gate itself once the toolkit is live.\n\nAlso makes the `awaiting input` label reachable. It could only ever fire on\na `status` the adapter forwards for `error`/`cancelled` alone, so the state\nit was written for never reached it.\n

M3gA-Mind52f806ec4fd3
diff --git a/app/src/features/conversations/components/AssistantUiToolCall.tsx b/app/src/features/conversations/components/AssistantUiToolCall.tsx
index 4cf79e6bde..7611d98c12 100644
--- a/app/src/features/conversations/components/AssistantUiToolCall.tsx
+++ b/app/src/features/conversations/components/AssistantUiToolCall.tsx
@@ -1,5 +1,10 @@
-import type { ToolCallMessagePartComponent } from '@assistant-ui/react';
+import type {
+ ToolApprovalOption,
+ ToolCallMessagePart,
+ ToolCallMessagePartComponent,
+} from '@assistant-ui/react';
import { CheckIcon, ChevronDownIcon, CircleXIcon, Loader2Icon, WrenchIcon } from 'lucide-react';
+import { type ReactNode, useEffect, useState } from 'react';
import { cn } from '../../../components/assistant-ui/lib/utils';
import {
@@ -7,6 +12,8 @@ import {
CollapsibleContent,
CollapsibleTrigger,
} from '../../../components/assistant-ui/ui/collapsible';
+import { Button } from '../../../components/ui';
+import { useT } from '../../../lib/i18n/I18nContext';
import type {
ToolFailureExplanation,
ToolTimelineEntryStatus,
@@ -98,6 +105,98 @@ function inferredToolLabel(toolName: string, running: boolean, args: unknown, re
return formatToolName(toolName);
}
+/**
+ * Is this approval still the user's to answer?
+ *
+ * A resolved one keeps its `approval` object (with `approved` / `resolution`
+ * filled in) so the transcript can show what was decided — offering the buttons
+ * again would let a second decision race the first.
+ */
+export function isApprovalPending(approval: ToolCallMessagePart['approval']): boolean {
+ return approval != null && approval.approved === undefined && approval.resolution === undefined;
+}
+
+/**
+ * How long a pressed decision stays disabled before the buttons come back.
+ * Long enough that a slow-but-succeeding decide never flickers; short enough
+ * that a failed one does not strand the only surface that can unblock the turn.
+ */
+const DECISION_RETRY_MS = 10_000;
+
+/** i18n key per assistant-ui approval `kind`; `undefined` for kinds we skip. */
+const APPROVAL_LABEL_KEYS: Record<string, string> = {
+ 'allow-once': 'chat.approval.approve',
+ 'allow-always': 'chat.approval.alwaysAllow',
+ 'reject-once': 'chat.approval.deny',
+ 'reject-always': 'chat.approval.deny',
+};
+
+/**
+ * The decision row for a parked tool call, rendered inline under the call it
+ * gates rather than as a banner elsewhere on the page.
+ *
+ * This is deliberately not `ToolFallbackApproval` from the assistant-ui kit:
+ * that component hardcodes English labels and the kit's own button, while every
+ * other approval surface in OpenHuman is localized and wears the app's buttons.
+ * The wire contract is identical — `respondToApproval({ optionId })` resolves
+ * through the runtime to the adapter's `onRespondToToolApproval`, which is what
+ * calls `openhuman.approval_decide`.
+ */
+function ToolApprovalBar({
+ approval,
+ respondToApproval,
+}: {
+ approval: NonNullable<ToolCallMessagePart['approval']>;
+ respondToApproval: (response: { optionId: string }) => void;
+}) {
+ const { t } = useT();
+ // Local, not derived from the store: the decision RPC is in flight before the
+ // socket clears the gate, and a second click in that window would throw
+ // ("Tool call has no pending approval") inside the runtime.
+ // Which decision is in flight, not merely that one is: only the pressed
+ // button says "Working…", the rest stay readable while disabled — the same
+ // shape `ApprovalRequestCard` uses.
+ const [deciding, setDeciding] = useState<string | null>(null);
+ // A successful decide clears the gate and unmounts this bar within a beat. A
+ // failed one cannot say so — `respondToApproval` returns void and the runtime
+ // swallows the rejection — so re-offer the decision rather than leaving the
+ // user staring at a disabled button on a turn that is still parked.
+ useEffect(() => {
+ if (!deciding) return;
+ const timer = window.setTimeout(() => setDeciding(null), DECISION_RETRY_MS);
+ return () => window.clearTimeout(timer);
+ }, [deciding]);
+ const options: readonly ToolApprovalOption[] = approval.options ?? [];
+ if (options.length === 0) return null;
+
+ return (
+ <div
+ data-testid="assistant-ui-tool-approval"
+ className="flex flex-wrap items-center gap-2 px-3 pb-3">
+ {options.map((option, index) => (
+ <Button
+ key={option.id}
+ type="button"
+ size="sm"
+ variant={index === 0 ? 'primary' : 'secondary'}
+ data-analytics-id={`chat-approval-${option.id}`}
+ title={option.kind === 'allow-always' ? t('chat.approval.alwaysAllowHint') : undefined}
+ disabled={deciding !== null}
+ onClick={() => {
+ if (deciding !== null) return;
+ setDeciding(option.id);
+ respondToApproval({ optionId: option.id });
+ }}>
+ {deciding === option.id
+ ? t('chat.approval.deciding')
+ : (option.label ??
+ (APPROVAL_LABEL_KEYS[option.kind] ? t(APPROVAL_LABEL_KEYS[option.kind]) : option.id))}
+ </Button>
+ ))}
+ </div>
+ );
+}
+
export interface AssistantUiToolCallCardProps {
toolName: string;
args?: unknown;
@@ -108,6 +207,14 @@ export interface AssistantUiToolCallCardProps {
detail?: string;
elapsedMs?: number;
failure?: ToolFailureExplanation;
+ /**
+ * The call is parked on the user — an ApprovalGate request, or a sub-agent
+ * that asked a question. Renders as in-flight (it *is* unfinished) but says
+ * what it is actually waiting for.
+ */
+ awaitingUser?: boolean;
+ /** Decision row / connect affordance, rendered under the call's header. */
+ footer?: ReactNode;
}
/** The single assistant-ui tool-call presentation used at every nesting level. */
@@ -121,10 +228,12 @@ export function AssistantUiToolCallCard({
detail,
elapsedMs,
failure,
+ awaitingUser = false,
+ footer,
}: AssistantUiToolCallCardProps) {
- const running = status
- ? status === 'running' || status === 'awaiting_user'
- : result === undefined;
+ const running =
+ awaitingUser ||
+ (status ? status === 'running' || status === 'awaiting_user' : result === undefined);
const input = hasDisplayValue(args) ? args : parsedValue(argsText ?? '');
const output = result === '' && status && !running ? 'No output' : parsedValue(result);
const suppliedLabel = displayName?.trim();
@@ -132,12 +241,15 @@ export function AssistantUiToolCallCard({
suppliedLabel && suppliedLabel.toLowerCase() !== 'tool'
? suppliedLabel
: inferredToolLabel(toolName, running, args, result);
+ // `awaiting input` was previously reachable only via `status`, which the
+ // adapter forwards for `error` / `cancelled` alone — so the label could never
+ // render for the case it was written for. A parked call now says so.
const statusLabel =
status === 'error'
? 'failed'
: status === 'cancelled'
? 'cancelled'
- : status === 'awaiting_user'
+ : awaitingUser || status === 'awaiting_user'
? 'awaiting input'
: running
? 'running'
@@ -154,6 +266,7 @@ export function AssistantUiToolCallCard({
data-slot="aui_openhuman-tool-call"
data-testid="assistant-ui-tool-call"
defaultOpen={running}
+ data-awaiting-user={awaitingUser ? 'true' : undefined}
className={cn(
'border-border/60 dark:border-muted-foreground/15 rounded-xl border',
running && 'border-dashed'
@@ -188,6 +301,10 @@ export function AssistantUiToolCallCard({
<ToolFailureLines failure={failure} />
</div>
) : null}
+ {/* Outside `CollapsibleContent` on purpose: a decision the turn is
+ blocked on must not be hidden behind a disclosure the user has to
+ find and open. */}
+ {footer}
<CollapsibleContent className="space-y-2 px-3 pb-3">
{hasDisplayValue(input) ? (
<div data-testid="assistant-ui-tool-input">
@@ -237,6 +354,11 @@ function toolStatusEnvelope(
export const OpenHumanToolCall: ToolCallMessagePartComponent = props => {
const envelope = toolStatusEnvelope(props.result);
+ // `approval`, `status` and `respondToApproval` are supplied by assistant-ui on
+ // every tool part; this component used to destructure four fields and drop the
+ // rest, which is why a parked call rendered as an ordinary running one with no
+ // way to answer it.
+ const pending = isApprovalPending(props.approval);
return (
<AssistantUiToolCallCard
toolName={props.toolName}
@@ -245,6 +367,12 @@ export const OpenHumanToolCall: ToolCallMessagePartComponent = props => {
result={envelope ? envelope.value : props.result}
status={envelope?.status}
failure={envelope?.failure}
+ awaitingUser={pending}
+ footer={
+ pending && props.approval && props.respondToApproval ? (
+ <ToolApprovalBar approval={props.approval} respondToApproval={props.respondToApproval} />
+ ) : undefined
+ }
/>
);
};
diff --git a/app/src/features/conversations/components/ChatToolParts.approval.test.tsx b/app/src/features/conversations/components/ChatToolParts.approval.test.tsx
new file mode 100644
index 0000000000..679cf7b077
--- /dev/null
+++ b/app/src/features/conversations/components/ChatToolParts.approval.test.tsx
@@ -0,0 +1,214 @@
+/**
+ * The render half of the parked-approval repair.
+ *
+ * `AssistantUiChat` overrides assistant-ui's `ToolFallback` with
+ * `ChatToolFallback`, and the component behind it destructured four fields and
+ * dropped `status`, `approval` and `respondToApproval` — so even once the
+ * runtime carried a decision, nothing on screen offered it. The kit's own
+ * approval-capable fallback renders on no user-facing surface (only the dev
+ * demo), which is why a grep for approval support in `components/assistant-ui`
+ * looked healthy while the chat had none.
+ */
+import { combineReducers, configureStore } from '@reduxjs/toolkit';
+import { act, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { Provider } from 'react-redux';
+import { describe, expect, it, vi } from 'vitest';
+
+import { AssistantUiRuntimeProvider } from '../../../providers/AssistantUiRuntimeProvider';
+import chatRuntimeReducer, {
+ type PendingApproval,
+ setPendingApprovalForThread,
+} from '../../../store/chatRuntimeSlice';
+import threadReducer from '../../../store/threadSlice';
+import { ChatToolFallback } from './ChatToolParts';
+
+vi.mock('../../../services/api/threadApi', () => ({
+ threadApi: {
+ getDerivedTranscript: vi
+ .fn()
+ .mockResolvedValue({
+ threadId: 't-1',
+ items: [],
+ total: 0,
+ hasMore: false,
+ hasTranscript: false,
+ }),
+ },
+}));
+
+const THREAD_ID = 't-1';
+const REQUEST_ID = 'appr-1';
+
+/** The option set the projection puts on a parked call. */
+const OPTIONS = [
+ { id: 'approve_once', kind: 'allow-once' as const },
+ { id: 'approve_always_for_tool', kind: 'allow-always' as const },
+ { id: 'deny', kind: 'reject-once' as const },
+];
+
+function gatedPart(over: Record<string, unknown> = {}) {
+ return {
+ type: 'tool-call' as const,
+ toolName: 'shell',
+ toolCallId: 'call-1',
+ args: { command: 'ls -la' } as never,
+ argsText: '{"command":"ls -la"}',
+ result: undefined,
+ status: { type: 'requires-action' as const, reason: 'interrupt' as const },
+ approval: { id: REQUEST_ID, options: OPTIONS },
+ addResult: () => {},
+ resume: () => {},
+ respondToApproval: () => {},
+ ...over,
+ };
+}
+
+function buildStore(approval?: PendingApproval) {
+ const store = configureStore({
+ reducer: combineReducers({ thread: threadReducer, chatRuntime: chatRuntimeReducer }),
+ preloadedState: {
+ thread: {
+ threads: [],
+ selectedThreadId: THREAD_ID,
+ activeThreadIds: {},
+ welcomeThreadId: null,
+ messagesByThreadId: {},
+ messages: [],
+ isLoadingThreads: false,
+ isLoadingMessages: false,
+ messagesError: null,
+ },
+ } as never,
+ });
+ if (approval) store.dispatch(setPendingApprovalForThread({ threadId: THREAD_ID, approval }));
+ return store;
+}
+
+/** Mounts the part under a runtime so `useAuiThreadId` resolves, as in the app. */
+function renderInThread(node: React.ReactNode, approval?: PendingApproval) {
+ return render(
+ <Provider store={buildStore(approval)}>
+ <AssistantUiRuntimeProvider>{node}</AssistantUiRuntimeProvider>
+ </Provider>
+ );
+}
+
+describe('ChatToolFallback — parked approval', () => {
+ it('offers the decision on the gated call', () => {
+ render(<ChatToolFallback {...gatedPart()} />);
+
+ const bar = screen.getByTestId('assistant-ui-tool-approval');
+ expect(bar).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Approve' })).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Always allow' })).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Deny' })).toBeInTheDocument();
+ });
+
+ it('says the call is awaiting input, not merely running', () => {
+ // The `awaiting input` label existed but was unreachable: its only trigger
+ // was a `status` the adapter forwards for `error` / `cancelled` alone.
+ render(<ChatToolFallback {...gatedPart()} />);
+
+ expect(screen.getByText('awaiting input')).toBeInTheDocument();
+ expect(screen.queryByText('running')).not.toBeInTheDocument();
+ });
+
+ it('sends the chosen option id straight to the runtime', async () => {
+ const respondToApproval = vi.fn();
+ render(<ChatToolFallback {...gatedPart({ respondToApproval })} />);
+
+ await userEvent.click(screen.getByRole('button', { name: 'Always allow' }));
+
+ // The id is the core's own `approval_decide` decision literal, so the
+ // adapter forwards it without a translation table.
+ expect(respondToApproval).toHaveBeenCalledWith({ optionId: 'approve_always_for_tool' });
+ });
+
+ it('does not offer a second decision while the first is in flight', async () => {
+ const respondToApproval = vi.fn();
+ render(<ChatToolFallback {...gatedPart({ respondToApproval })} />);
+
+ const approve = screen.getByRole('button', { name: 'Approve' });
+ await userEvent.click(approve);
+ await userEvent.click(approve);
+
+ // A second decision throws "Tool call has no pending approval" inside the
+ // runtime, in the window before the socket clears the gate.
+ expect(respondToApproval).toHaveBeenCalledTimes(1);
+ });
+
+ it('re-offers the decision when the decide never lands', async () => {
+ // `respondToApproval` returns void and the runtime swallows a rejection, so
+ // a failed decide is indistinguishable from a slow one here. Coming back is
+ // what keeps a still-parked turn answerable.
+ vi.useFakeTimers();
+ try {
+ const respondToApproval = vi.fn();
+ render(<ChatToolFallback {...gatedPart({ respondToApproval })} />);
+ const approve = screen.getByRole('button', { name: 'Approve' });
+ act(() => approve.click());
+ expect(screen.getByRole('button', { name: 'Working…' })).toBeDisabled();
+
+ act(() => vi.advanceTimersByTime(10_000));
+
+ expect(screen.getByRole('button', { name: 'Approve' })).toBeEnabled();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('leaves an ordinary running tool alone', () => {
+ // Every unsettled tool part in a `requires-action` message inherits that
+ // status, so the prompt must key off the approval, not off the status.
+ render(
+ <ChatToolFallback
+ {...gatedPart({ toolName: 'web_search', approval: undefined, toolCallId: 'call-2' })}
+ />
+ );
+
+ expect(screen.queryByTestId('assistant-ui-tool-approval')).not.toBeInTheDocument();
+ expect(screen.queryByText('awaiting input')).not.toBeInTheDocument();
+ });
+
+ it('gives composio_connect the OAuth affordance rather than approve/deny', () => {
+ // `composio_connect` parks on the same gate, but approving it without
+ // connecting resumes the agent against a toolkit with no credentials.
+ renderInThread(
+ <ChatToolFallback
+ {...gatedPart({ toolName: 'composio_connect', args: { toolkit: 'googledrive' } })}
+ />,
+ {
+ requestId: REQUEST_ID,
+ toolName: 'composio_connect',
+ message: 'Connect Google Drive?',
+ toolkit: 'googledrive',
+ }
+ );
+
+ expect(screen.getByTestId('assistant-ui-integration-connect')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /connect/i })).toBeInTheDocument();
+ expect(screen.queryByTestId('assistant-ui-tool-approval')).not.toBeInTheDocument();
+ });
+
+ it('falls back to the ordinary card when the connect request is not the parked one', () => {
+ // A stale part from an earlier turn must not adopt the live request.
+ renderInThread(
+ <ChatToolFallback
+ {...gatedPart({
+ toolName: 'composio_connect',
+ approval: { id: 'appr-stale', options: OPTIONS },
+ })}
+ />,
+ {
+ requestId: REQUEST_ID,
+ toolName: 'composio_connect',
+ message: 'Connect Google Drive?',
+ toolkit: 'googledrive',
+ }
+ );
+
+ expect(screen.queryByTestId('assistant-ui-integration-connect')).not.toBeInTheDocument();
+ expect(screen.getByTestId('assistant-ui-tool-approval')).toBeInTheDocument();
+ });
+});
diff --git a/app/src/features/conversations/components/ChatToolParts.tsx b/app/src/features/conversations/components/ChatToolParts.tsx
index 4358ac0fa7..362a173909 100644
--- a/app/src/features/conversations/components/ChatToolParts.tsx
+++ b/app/src/features/conversations/components/ChatToolParts.tsx
@@ -7,9 +7,12 @@ import {
ToolGroupRoot,
ToolGroupTrigger,
} from '../../../components/assistant-ui/tool-group';
+import IntegrationConnectCard from '../../../components/chat/IntegrationConnectCard';
+import { useAuiThreadId } from '../../../providers/AssistantUiRuntimeProvider';
import type { SubagentActivity } from '../../../store/chatRuntimeSlice';
+import { useAppSelector } from '../../../store/hooks';
import { AssistantUiSubagentCall, isActiveSubagentStatus } from './AssistantUiSubagentCall';
-import { OpenHumanToolCall } from './AssistantUiToolCall';
+import { isApprovalPending, OpenHumanToolCall } from './AssistantUiToolCall';
function asSubagentActivity(value: unknown): SubagentActivity | undefined {
if (!value || typeof value !== 'object') return undefined;
@@ -74,9 +77,49 @@ export const SubagentCall: ToolCallMessagePartComponent = ({ args, result }) =>
);
};
+/** The tool that parks on the ApprovalGate but needs OAuth, not approve/deny. */
+const COMPOSIO_CONNECT_TOOL = 'composio_connect';
+
+/**
+ * A parked `composio_connect` call.
+ *
+ * It arrives over the same `approval_request` path as every other gated tool,
+ * but "Approve" is the wrong affordance: approving without connecting resumes
+ * the agent against a toolkit that still has no credentials. The existing
+ * connect card runs the OAuth handoff, polls until the toolkit is live, and
+ * only then resolves the gate with `approve_once` (or `deny` on cancel/timeout)
+ * — so it is reused verbatim rather than reimplemented against
+ * `respondToApproval`.
+ *
+ * Falls through to the ordinary card once the approval is resolved, or when the
+ * request is not the one the store holds: `PendingApproval.toolkit` names the
+ * integration to connect and lives in Redux, not on the part.
+ */
+const ComposioConnectCall: ToolCallMessagePartComponent = props => {
+ const threadId = useAuiThreadId();
+ const approval = useAppSelector(state =>
+ threadId ? (state.chatRuntime.pendingApprovalByThread?.[threadId] ?? null) : null
+ );
+ const gated =
+ isApprovalPending(props.approval) &&
+ approval != null &&
+ approval.requestId === props.approval?.id;
+ if (!gated || !threadId || !approval) return <OpenHumanToolCall {...props} />;
+ return (
+ <div data-testid="assistant-ui-integration-connect">
+ {/* Keyed by request id so a second parked connect remounts the card with
+ fresh phase / field / poll state, matching the legacy placement. */}
+ <IntegrationConnectCard key={approval.requestId} threadId={threadId} approval={approval} />
+ </div>
+ );
+};
+
/** Route every call through an assistant-ui-native rich renderer. */
-export const ChatToolFallback: ToolCallMessagePartComponent = props =>
- props.toolName === 'task' ? <SubagentCall {...props} /> : <OpenHumanToolCall {...props} />;
+export const ChatToolFallback: ToolCallMessagePartComponent = props => {
+ if (props.toolName === 'task') return <SubagentCall {...props} />;
+ if (props.toolName === COMPOSIO_CONNECT_TOOL) return <ComposioConnectCall {...props} />;
+ return <OpenHumanToolCall {...props} />;
+};
/** Keep the assistant-ui tool cards visible; each card owns its detail collapse. */
export const ChatToolGroup: FC<PropsWithChildren<{ group: ThreadGroupPart }>> = ({
diff --git a/app/src/providers/AssistantUiRuntimeProvider.tsx b/app/src/providers/AssistantUiRuntimeProvider.tsx
index d03eec2c9f..1718fb6eac 100644
--- a/app/src/providers/AssistantUiRuntimeProvider.tsx
+++ b/app/src/providers/AssistantUiRuntimeProvider.tsx
@@ -1,12 +1,30 @@
import { AssistantRuntimeProvider, useExternalStoreRuntime } from '@assistant-ui/react';
import debugFactory from 'debug';
-import type { ReactNode } from 'react';
+import { createContext, type ReactNode, useContext } from 'react';
import { useAppSelector } from '../store/hooks';
import { useOpenHumanExternalStore } from './useOpenHumanExternalStore';
const debug = debugFactory('openhuman:assistant-ui');
+const AuiThreadIdContext = createContext<string | null>(null);
+
+/**
+ * The OpenHuman thread this assistant-ui runtime represents.
+ *
+ * assistant-ui's own context carries its internal thread identity, not ours, so
+ * a component rendered *inside* the transcript (a tool part, say) has no other
+ * way to name the thread it belongs to. Reading `selectedThreadId` from Redux
+ * instead would be wrong on any surface whose thread is not the selected one —
+ * the Workflow Copilot mounts a runtime on its own builder thread — which is
+ * the same trap {@link AssistantUiRuntimeProvider} documents for messages.
+ *
+ * `null` outside a runtime, or on a surface that has not created its thread yet.
+ */
+export function useAuiThreadId(): string | null {
+ return useContext(AuiThreadIdContext);
+}
+
/**
* Mounts assistant-ui's runtime over one OpenHuman thread.
*
@@ -58,7 +76,13 @@ export function AssistantUiRuntimeProvider({
);
const adapter = useOpenHumanExternalStore(effectiveThreadId);
const runtime = useExternalStoreRuntime(adapter);
- return <AssistantRuntimeProvider runtime={runtime}>{children}</AssistantRuntimeProvider>;
+ return (
+ <AssistantRuntimeProvider runtime={runtime}>
+ <AuiThreadIdContext.Provider value={effectiveThreadId}>
+ {children}
+ </AuiThreadIdContext.Provider>
+ </AssistantRuntimeProvider>
+ );
}
export default AssistantUiRuntimeProvider;
diff --git a/app/src/providers/__tests__/AssistantUiRuntimeProvider.approvalGate.test.tsx b/app/src/providers/__tests__/AssistantUiRuntimeProvider.approvalGate.test.tsx
new file mode 100644
index 0000000000..29993e0a7d
--- /dev/null
+++ b/app/src/providers/__tests__/AssistantUiRuntimeProvider.approvalGate.test.tsx
@@ -0,0 +1,251 @@
+/**
+ * The parked ApprovalGate, end to end through the real assistant-ui runtime.
+ *
+ * The migration to assistant-ui left `onApprovalRequest` writing
+ * `chatRuntime.pendingApprovalByThread` while the only reader of that slice
+ * (`ApprovalRequestCard`) lived inside `Conversations`' legacy panel, which
+ * `/chat` never renders. The observable result was a shell call that spun
+ * forever, no prompt, and a turn the core dropped as denied two minutes later.
+ *
+ * These tests pin both halves of the repair against the actual runtime rather
+ * than the projection alone: the decision must reach the part, and pressing it
+ * must reach `openhuman.approval_decide`.
+ */
+import {
+ MessageByIndexProvider,
+ PartByIndexProvider,
+ useAui,
+ useAuiState,
+} from '@assistant-ui/react';
+import { combineReducers, configureStore } from '@reduxjs/toolkit';
+import { act, render, screen, waitFor } from '@testing-library/react';
+import { Provider } from 'react-redux';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { callCoreRpc } from '../../services/coreRpcClient';
+import chatRuntimeReducer, {
+ beginInferenceTurn,
+ markInferenceTurnStreaming,
+ setPendingApprovalForThread,
+ toolCallReceived,
+} from '../../store/chatRuntimeSlice';
+import threadReducer from '../../store/threadSlice';
+import type { ThreadMessage } from '../../types/thread';
+import { AssistantUiRuntimeProvider } from '../AssistantUiRuntimeProvider';
+
+vi.mock('../../services/api/threadApi', () => ({
+ threadApi: {
+ getDerivedTranscript: vi
+ .fn()
+ .mockResolvedValue({
+ threadId: 't-gate',
+ items: [],
+ total: 0,
+ hasMore: false,
+ hasTranscript: false,
+ }),
+ },
+}));
+
+vi.mock('../../services/coreRpcClient', () => ({ callCoreRpc: vi.fn() }));
+
+const THREAD_ID = 't-gate';
+const REQUEST_ID = 'appr-7';
+
+function msg(id: string, sender: 'user' | 'agent', content: string): ThreadMessage {
+ return {
+ id,
+ sender,
+ type: 'text',
+ content,
+ extraMetadata: {},
+ createdAt: '2026-01-01T00:00:00.000Z',
+ };
+}
+
+function buildStore() {
+ return configureStore({
+ reducer: combineReducers({ thread: threadReducer, chatRuntime: chatRuntimeReducer }),
+ preloadedState: {
+ thread: {
+ threads: [],
+ selectedThreadId: THREAD_ID,
+ activeThreadIds: {},
+ welcomeThreadId: null,
+ messagesByThreadId: { [THREAD_ID]: [msg('q', 'user', 'list the repo')] },
+ messages: [],
+ isLoadingThreads: false,
+ isLoadingMessages: false,
+ messagesError: null,
+ },
+ } as never,
+ });
+}
+
+type Store = ReturnType<typeof buildStore>;
+
+/** A `shell` call parked on the gate, exactly as the socket layer records it. */
+function parkShellCall(store: Store, toolName = 'shell') {
+ store.dispatch(beginInferenceTurn({ threadId: THREAD_ID }));
+ store.dispatch(markInferenceTurnStreaming({ threadId: THREAD_ID }));
+ store.dispatch(
+ toolCallReceived({ threadId: THREAD_ID, round: 1, toolName, toolCallId: 'call-1' })
+ );
+ store.dispatch(
+ setPendingApprovalForThread({
+ threadId: THREAD_ID,
+ approval: {
+ requestId: REQUEST_ID,
+ toolName,
+ message: 'Run a shell command?',
+ command: 'ls -la',
+ },
+ })
+ );
+}
+
+/**
+ * Answers the gate through the very path a decision button uses: the part-scoped
+ * `respondToToolApproval` assistant-ui hands every tool-call renderer.
+ */
+function PartProbe() {
+ const aui = useAui();
+ const part = useAuiState(state => state.part);
+ return (
+ <>
+ <div data-testid="approval-id">
+ {part.type === 'tool-call' ? (part.approval?.id ?? 'none') : 'none'}
+ </div>
+ <div data-testid="approval-tool">{part.type === 'tool-call' ? part.toolName : 'none'}</div>
+ <div data-testid="approval-options">
+ {part.type === 'tool-call'
+ ? (part.approval?.options ?? []).map(option => option.id).join('|')
+ : ''}
+ </div>
+ <div data-testid="part-status">{part.status?.type ?? 'none'}</div>
+ <button
+ type="button"
+ data-testid="always-allow"
+ onClick={() => aui.part.respondToToolApproval({ optionId: 'approve_always_for_tool' })}>
+ always allow
+ </button>
+ </>
+ );
+}
+
+/** Reports what the runtime believes about the gated call. */
+function GateProbe() {
+ const messages = useAuiState(state => state.thread.messages);
+ const lastIndex = messages.length - 1;
+ const last = messages[lastIndex];
+ const partIndex =
+ last?.role === 'assistant'
+ ? last.content.findIndex(part => part.type === 'tool-call' && part.approval != null)
+ : -1;
+ return (
+ <div>
+ <div data-testid="message-status">{last?.status?.type ?? 'none'}</div>
+ <div data-testid="message-reason">
+ {last?.status && 'reason' in last.status ? String(last.status.reason) : 'none'}
+ </div>
+ {partIndex >= 0 ? (
+ <MessageByIndexProvider index={lastIndex}>
+ <PartByIndexProvider index={partIndex}>
+ <PartProbe />
+ </PartByIndexProvider>
+ </MessageByIndexProvider>
+ ) : (
+ <div data-testid="approval-id">none</div>
+ )}
+ </div>
+ );
+}
+
+function renderWith(store: Store) {
+ return render(
+ <Provider store={store}>
+ <AssistantUiRuntimeProvider>
+ <GateProbe />
+ </AssistantUiRuntimeProvider>
+ </Provider>
+ );
+}
+
+beforeEach(() => {
+ vi.mocked(callCoreRpc).mockReset();
+ vi.mocked(callCoreRpc).mockResolvedValue(undefined as never);
+});
+
+afterEach(() => vi.clearAllMocks());
+
+describe('parked approval on the assistant-ui surface', () => {
+ it('hangs the decision off the tool part the gate is holding', async () => {
+ const store = buildStore();
+ renderWith(store);
+ act(() => parkShellCall(store));
+
+ await waitFor(() => expect(screen.getByTestId('approval-id')).toHaveTextContent(REQUEST_ID));
+ // The prompt lands on the parked call itself, not on a synthesised row
+ // beside it — the user reads the command from the card they answer.
+ expect(screen.getByTestId('approval-tool')).toHaveTextContent('shell');
+ expect(screen.getByTestId('approval-options')).toHaveTextContent(
+ 'approve_once|approve_always_for_tool|deny'
+ );
+ });
+
+ it('marks the turn as awaiting the user rather than running', async () => {
+ const store = buildStore();
+ renderWith(store);
+ act(() => parkShellCall(store));
+
+ await waitFor(() =>
+ expect(screen.getByTestId('message-status')).toHaveTextContent('requires-action')
+ );
+ expect(screen.getByTestId('message-reason')).toHaveTextContent('interrupt');
+ // The part inherits it, which is the state a renderer keys the prompt off.
+ expect(screen.getByTestId('part-status')).toHaveTextContent('requires-action');
+ });
+
+ it('routes a decision to openhuman.approval_decide and clears the gate', async () => {
+ const store = buildStore();
+ renderWith(store);
+ act(() => parkShellCall(store));
+ await waitFor(() => expect(screen.getByTestId('approval-id')).toHaveTextContent(REQUEST_ID));
+
+ await act(async () => {
+ screen.getByTestId('always-allow').click();
+ });
+
+ // Without an `onRespondToToolApproval` on the adapter this throws
+ // "Runtime does not support tool approvals." and never reaches the RPC.
+ await waitFor(() => expect(callCoreRpc).toHaveBeenCalledTimes(1));
+ expect(callCoreRpc).toHaveBeenCalledWith({
+ method: 'openhuman.approval_decide',
+ params: { request_id: REQUEST_ID, decision: 'approve_always_for_tool' },
+ });
+ await waitFor(() =>
+ expect(store.getState().chatRuntime.pendingApprovalByThread[THREAD_ID]).toBeUndefined()
+ );
+ });
+
+ it('still prompts when the gate parks with no timeline row to hang it on', async () => {
+ // The progress channel is bounded and drops frames under load, and the gate
+ // can park before the `tool_call` frame lands at all. Dropping the prompt
+ // in that case is the original bug in miniature.
+ const store = buildStore();
+ renderWith(store);
+ act(() => {
+ store.dispatch(beginInferenceTurn({ threadId: THREAD_ID }));
+ store.dispatch(markInferenceTurnStreaming({ threadId: THREAD_ID }));
+ store.dispatch(
+ setPendingApprovalForThread({
+ threadId: THREAD_ID,
+ approval: { requestId: REQUEST_ID, toolName: 'write_file', message: 'Write?' },
+ })
+ );
+ });
+
+ await waitFor(() => expect(screen.getByTestId('approval-id')).toHaveTextContent(REQUEST_ID));
+ expect(screen.getByTestId('approval-tool')).toHaveTextContent('write_file');
+ });
+});
diff --git a/app/src/providers/assistantUiMessages.ts b/app/src/providers/assistantUiMessages.ts
index a261c8a415..7716ddad25 100644
--- a/app/src/providers/assistantUiMessages.ts
+++ b/app/src/providers/assistantUiMessages.ts
@@ -2,11 +2,13 @@ import type {
ThreadAssistantMessagePart,
ThreadMessageLike,
ThreadUserMessagePart,
+ ToolApprovalOption,
} from '@assistant-ui/react';
import { parseMessageImages } from '../lib/attachments';
import { unwrapToolCallEnvelope } from '../lib/chat/toolCallEnvelope';
import type {
+ PendingApproval,
ProcessingTranscriptItem,
StreamingAssistantState,
ToolTimelineEntry,
@@ -129,6 +131,78 @@ function toolPart(entry: ToolTimelineEntry): ThreadAssistantMessagePart {
};
}
+/**
+ * The decision set offered for a parked tool call.
+ *
+ * Each `id` is verbatim the `decision` literal `openhuman.approval_decide`
+ * takes, so the runtime hands the adapter an option id it can forward to the
+ * RPC without a translation table — see `useOpenHumanExternalStore`. The
+ * `kind`s are what assistant-ui resolves to the boolean `approved` it reports
+ * alongside the id, and what a renderer keys its default labels off.
+ *
+ * `reject-always` is deliberately absent: the core has no "never allow this
+ * tool" decision, and offering one that silently degrades to a one-off deny
+ * would be a lie about what the click did.
+ */
+export const APPROVAL_DECISION_OPTIONS: readonly ToolApprovalOption[] = [
+ { id: 'approve_once', kind: 'allow-once' },
+ { id: 'approve_always_for_tool', kind: 'allow-always' },
+ { id: 'deny', kind: 'reject-once' },
+];
+
+/**
+ * `toolCallId` prefix for the part synthesised when a parked approval cannot be
+ * matched to a live timeline row. Namespaced so it can never collide with a
+ * core-issued tool-call id (the duplicate-id invariant above is a hard one).
+ */
+const APPROVAL_PART_ID_PREFIX = '__openhuman_approval__:';
+
+/** The part the parked call is asking about, when no timeline row carries it. */
+function syntheticApprovalPart(approval: PendingApproval): ThreadAssistantMessagePart {
+ // `command` is the redacted command/path/url the gate extracted for display;
+ // rendering it as the call's args is what makes the prompt answerable.
+ const args = approval.command ? { command: approval.command } : {};
+ return {
+ type: 'tool-call',
+ toolCallId: `${APPROVAL_PART_ID_PREFIX}${approval.requestId}`,
+ toolName: approval.toolName,
+ args: args as Record<string, never>,
+ argsText: JSON.stringify(args, null, 2),
+ approval: { id: approval.requestId, options: APPROVAL_DECISION_OPTIONS },
+ };
+}
+
+/**
+ * Hang a parked approval off the tool part it is gating.
+ *
+ * The `approval_request` socket event carries no `tool_call_id` (see
+ * `ChatApprovalRequestEvent`), so the row is matched by name against the
+ * newest still-unsettled call — a `result` means the call already ran and
+ * cannot be the one parked. When nothing matches (the progress channel is
+ * bounded and can drop the `tool_call` frame, and the gate can park before the
+ * frame lands at all) a part is synthesised rather than dropped: a prompt in
+ * the wrong visual slot is recoverable, a turn that parks with no prompt at all
+ * is the bug this exists to close.
+ */
+function withApproval(
+ parts: ThreadAssistantMessagePart[],
+ approval: PendingApproval
+): ThreadAssistantMessagePart[] {
+ const index = parts.reduce(
+ (best, part, at) =>
+ part.type === 'tool-call' && part.toolName === approval.toolName && part.result === undefined
+ ? at
+ : best,
+ -1
+ );
+ if (index < 0) return [...parts, syntheticApprovalPart(approval)];
+ return parts.map((part, at) =>
+ at === index
+ ? { ...part, approval: { id: approval.requestId, options: APPROVAL_DECISION_OPTIONS } }
+ : part
+ );
+}
+
/**
* Project one assistant message into assistant-ui parts.
*
@@ -401,21 +475,27 @@ export function toThreadMessageLike(
export function streamingTailMessage(
streaming: StreamingAssistantState | null,
timeline: readonly ToolTimelineEntry[] = EMPTY_TIMELINE,
- transcript: readonly ProcessingTranscriptItem[] = EMPTY_TRANSCRIPT
+ transcript: readonly ProcessingTranscriptItem[] = EMPTY_TRANSCRIPT,
+ approval: PendingApproval | null = null
): ThreadMessageLike | null {
- if (!streaming && timeline.length === 0 && transcript.length === 0) return null;
+ if (!approval && !streaming && timeline.length === 0 && transcript.length === 0) return null;
const text = streaming?.content ?? '';
- const parts = assistantParts(text, timeline, transcript);
+ let parts = assistantParts(text, timeline, transcript);
if (streaming?.thinking.trim()) {
const hasTranscriptThinking = transcript.some(item => item.kind === 'thinking');
if (!hasTranscriptThinking) parts.unshift({ type: 'reasoning', text: streaming.thinking });
}
+ if (approval) parts = withApproval(parts, approval);
if (parts.length === 0) return null;
return {
id: STREAMING_TAIL_ID,
role: 'assistant',
content: parts,
- status: { type: 'running' },
+ // A parked gate is not a running turn: it is a turn stopped on the user.
+ // `requires-action` is what gives the gated tool part its own
+ // `requires-action` status (a tool part with no result inherits the
+ // message's), which is the state assistant-ui renders a decision on.
+ status: approval ? { type: 'requires-action', reason: 'interrupt' } : { type: 'running' },
metadata: { custom: { requestId: streaming?.requestId, streaming: true } },
};
}
@@ -423,6 +503,12 @@ export function streamingTailMessage(
export type AssistantUiProjection = {
/** Whether the synthetic live tail has an active core turn driving it. */
isRunning?: boolean;
+ /**
+ * The thread's parked ApprovalGate request, if any. Present means the turn is
+ * blocked on the user, and the tail is minted even when nothing else would
+ * mint one — a parked gate with no prompt is the failure mode this closes.
+ */
+ pendingApproval?: PendingApproval | null;
liveTimeline?: readonly ToolTimelineEntry[];
liveTranscript?: readonly ProcessingTranscriptItem[];
turnTimelines?: Readonly<Record<string, readonly ToolTimelineEntry[]>>;
@@ -442,6 +528,10 @@ export function buildRuntimeMessages(
streaming: StreamingAssistantState | null,
projection: AssistantUiProjection = {}
): ThreadMessageLike[] {
+ // A parked approval outranks the lifecycle: `chat_done` has not fired (the
+ // turn is stopped, not finished), but a snapshot race that reports the turn
+ // settled must not swallow the only surface that can unblock it.
+ const pendingApproval = projection.pendingApproval ?? null;
const coalescedMessages = coalesceAssistantSegments(messages);
const out: ThreadMessageLike[] = [];
const claimedRequestIds = new Set(
@@ -497,8 +587,12 @@ export function buildRuntimeMessages(
// indexed into the request maps. Keep the just-settled tools/reasoning on
// the final assistant message during that handoff; never mint a running
// synthetic tail for them.
+ // Not while a gate is parked: the tail below is minted unconditionally in
+ // that case and would emit the same rows a second time, and a repeated
+ // `toolCallId` throws inside assistant-ui rather than dropping a row.
const useSettledLiveFallback =
projection.isRunning === false &&
+ !pendingApproval &&
msg.id === lastVisibleAgentId &&
!persistedTimeline &&
!persistedTranscript;
@@ -515,12 +609,13 @@ export function buildRuntimeMessages(
);
}
const tail =
- projection.isRunning === false
+ projection.isRunning === false && !pendingApproval
? null
: streamingTailMessage(
streaming,
projection.liveTimeline ?? EMPTY_TIMELINE,
- projection.liveTranscript ?? EMPTY_TRANSCRIPT
+ projection.liveTranscript ?? EMPTY_TRANSCRIPT,
+ pendingApproval
);
if (tail) out.push(tail);
return out;
diff --git a/app/src/providers/useOpenHumanExternalStore.ts b/app/src/providers/useOpenHumanExternalStore.ts
index 4ca1347dc6..39dca9695c 100644
--- a/app/src/providers/useOpenHumanExternalStore.ts
+++ b/app/src/providers/useOpenHumanExternalStore.ts
@@ -1,10 +1,15 @@
-import type { AppendMessage } from '@assistant-ui/react';
+import type { AppendMessage, RespondToToolApprovalOptions } from '@assistant-ui/react';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { mapDisplayItems } from '../features/conversations/derived/mapDisplayItems';
+import { type ApprovalDecision, decideApproval } from '../services/api/approvalApi';
import { threadApi } from '../services/api/threadApi';
-import type { InferenceStatus, ToolTimelineEntry } from '../store/chatRuntimeSlice';
-import { useAppSelector } from '../store/hooks';
+import {
+ clearPendingApprovalForThread,
+ type InferenceStatus,
+ type ToolTimelineEntry,
+} from '../store/chatRuntimeSlice';
+import { useAppDispatch, useAppSelector } from '../store/hooks';
import type { DerivedDisplayItem } from '../types/derivedTranscript';
import type { ThreadMessage } from '../types/thread';
import { buildRuntimeMessages } from './assistantUiMessages';
@@ -169,6 +174,7 @@ function appendMessageText(message: AppendMessage): string {
* projection. Redux is not a second transcript database.
*/
export function useOpenHumanExternalStore(threadId: string | null) {
+ const dispatch = useAppDispatch();
const messages = useAppSelector(state =>
threadId ? (state.thread.messagesByThreadId[threadId] ?? EMPTY_MESSAGES) : EMPTY_MESSAGES
);
@@ -194,6 +200,12 @@ export function useOpenHumanExternalStore(threadId: string | null) {
const inferenceStatus = useAppSelector(state =>
threadId ? (state.chatRuntime.inferenceStatusByThread?.[threadId] ?? null) : null
);
+ // The thread's parked ApprovalGate request. Selected here rather than read by
+ // a card somewhere else on the page: the decision belongs on the tool call it
+ // gates, and only this adapter can put it there.
+ const pendingApproval = useAppSelector(state =>
+ threadId ? (state.chatRuntime.pendingApprovalByThread?.[threadId] ?? null) : null
+ );
const settledRevision = `${messages.at(-1)?.id ?? ''}:${messages.at(-1)?.content?.length ?? 0}:${lifecycle ?? ''}`;
const coreTranscript = useCoreTranscriptProjection(
threadId,
@@ -215,10 +227,11 @@ export function useOpenHumanExternalStore(threadId: string | null) {
isRunning,
liveTimeline,
liveTranscript,
+ pendingApproval,
turnTimelines: coreTranscript.timelines,
turnTranscripts: coreTranscript.transcripts,
}),
- [messages, streaming, isRunning, liveTimeline, liveTranscript, coreTranscript]
+ [messages, streaming, isRunning, liveTimeline, liveTranscript, pendingApproval, coreTranscript]
);
// The status line titles its `tool_use` / `subagent` phases from the matching
@@ -256,6 +269,32 @@ export function useOpenHumanExternalStore(threadId: string | null) {
await getChatSurface(threadId)?.cancel?.();
}, [threadId]);
+ /**
+ * Record the user's decision on the parked tool call.
+ *
+ * `optionId` is the core's own `decision` literal (see
+ * `APPROVAL_DECISION_OPTIONS`), so it forwards unchanged; the boolean
+ * `approved` is only the fallback for a renderer that answered with a plain
+ * allow/deny rather than picking one of the declared options.
+ *
+ * Supplying this at all is load-bearing, not optional: without it the runtime
+ * *throws* `Runtime does not support tool approvals.` the moment a decision
+ * button is pressed, rather than no-opping.
+ */
+ const onRespondToToolApproval = useCallback(
+ async ({ approvalId, approved, optionId }: RespondToToolApprovalOptions) => {
+ const decision = (optionId ?? (approved ? 'approve_once' : 'deny')) as ApprovalDecision;
+ await decideApproval(approvalId, decision);
+ // Resolve optimistically, exactly as `ApprovalRequestCard` does — the
+ // turn-end handlers in `ChatRuntimeProvider` clear it again if the turn
+ // is cancelled instead. Only on success: a failed decide leaves the call
+ // parked, and dropping the prompt would strand the thread until the
+ // gate's TTL with nothing left on screen to retry from.
+ if (threadId) dispatch(clearPendingApprovalForThread({ threadId }));
+ },
+ [dispatch, threadId]
+ );
+
return useMemo(
() => ({
messages: runtimeMessages,
@@ -266,7 +305,8 @@ export function useOpenHumanExternalStore(threadId: string | null) {
convertMessage: (m: (typeof runtimeMessages)[number]) => m,
onNew,
onCancel,
+ onRespondToToolApproval,
}),
- [runtimeMessages, isRunning, isLoading, extras, onNew, onCancel]
+ [runtimeMessages, isRunning, isLoading, extras, onNew, onCancel, onRespondToToolApproval]
);
}