The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(chat): remove legacy approval card components
Steven Enamakela594fcb9c63b
diff --git a/app/src/components/chat/ApprovalRequestCard.tsx b/app/src/components/chat/ApprovalRequestCard.tsxdeleted file mode 100644index b10cafa12a..0000000000--- a/app/src/components/chat/ApprovalRequestCard.tsx+++ /dev/null@@ -1,129 +0,0 @@-import debug from 'debug';-import React, { useState } from 'react';--import { useT } from '../../lib/i18n/I18nContext';-import { callCoreRpc } from '../../services/coreRpcClient';-import { clearPendingApprovalForThread, type PendingApproval } from '../../store/chatRuntimeSlice';-import { useAppDispatch } from '../../store/hooks';-import Button from '../ui/Button';--/**- * Decision surface for a parked tool call. `approve_once` / `deny` decide the- * current call only; `approve_always_for_tool` additionally persists the tool- * onto the user's `autonomy.auto_approve` ("Always allow") list so the gate- * skips prompting for it on future turns (managed/removable in Settings → Agent- * access). A typed `yes`/`no` chat reply is the equivalent server-side path for- * the once/deny decisions.- */-const log = debug('openhuman:chat:approval-card');--type Decision = 'approve_once' | 'approve_always_for_tool' | 'deny';--interface Props {- threadId: string;- approval: PendingApproval;-}--/**- * Surfaces a `Prompt`-class tool call parked on the ApprovalGate- * (`approval_request` socket event) and routes the user's Approve / Deny to the- * `openhuman.approval_decide` RPC. Rendered above the composer for the active- * thread; clears itself on a recorded decision (the turn-end handlers in- * {@link ChatRuntimeProvider} also clear it if the turn is cancelled).- */-const ApprovalRequestCard: React.FC<Props> = ({ threadId, approval }) => {- const { t } = useT();- const dispatch = useAppDispatch();- const [deciding, setDeciding] = useState<Decision | null>(null);- const [errorMsg, setErrorMsg] = useState<string | null>(null);-- const decide = async (decision: Decision) => {- if (deciding) return;- setDeciding(decision);- setErrorMsg(null);- try {- await callCoreRpc({- method: 'openhuman.approval_decide',- params: { request_id: approval.requestId, decision },- });- // Resolve optimistically; ChatRuntimeProvider also clears on turn end.- dispatch(clearPendingApprovalForThread({ threadId }));- } catch (e) {- // Keep raw RPC error detail in namespaced dev logs only; show the user the- // localized fallback — never leak internal error text into the UI.- log('approval_decide failed: %o', e);- setErrorMsg(t('chat.approval.error'));- setDeciding(null);- }- };-- return (- <div- role="alertdialog"- aria-label={t('chat.approval.title')}- className="rounded-xl border border-amber-300 bg-amber-50 p-3 text-sm shadow-xs dark:border-amber-700 dark:bg-amber-950">- <div className="flex items-start gap-2">- <span aria-hidden className="text-base leading-none text-amber-700 dark:text-amber-200">- 🔒- </span>- <div className="min-w-0 flex-1">- <p className="font-semibold text-amber-900 dark:text-amber-100">- {t('chat.approval.title')}- </p>- <p className="mt-1 wrap-break-word text-amber-800/90 dark:text-amber-200/90">- {approval.message || t('chat.approval.fallback')}- </p>- {approval.command && (- <pre className="mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-all rounded border border-amber-200/80 bg-surface px-2 py-1.5 font-mono text-xs text-content shadow-inner dark:border-amber-700 dark:bg-surface-canvas">- {approval.command}- </pre>- )}- <p className="mt-1 text-xs text-amber-800/80 dark:text-amber-200/80">- {t('chat.approval.tool')}{' '}- <span className="font-mono text-amber-950 dark:text-amber-100">- {approval.toolName}- </span>- </p>-- {errorMsg && (- <p className="mt-2 text-xs text-coral-600 dark:text-coral-400">⚠ {errorMsg}</p>- )}-- <div className="mt-3 flex flex-wrap items-center gap-2">- <Button- variant="primary"- size="sm"- data-analytics-id="chat-approval-approve-once"- onClick={() => void decide('approve_once')}- disabled={deciding !== null}>- {deciding === 'approve_once'- ? t('chat.approval.deciding')- : t('chat.approval.approve')}- </Button>- <Button- variant="secondary"- size="sm"- data-analytics-id="chat-approval-approve-always"- onClick={() => void decide('approve_always_for_tool')}- disabled={deciding !== null}- title={t('chat.approval.alwaysAllowHint')}>- {deciding === 'approve_always_for_tool'- ? t('chat.approval.deciding')- : t('chat.approval.alwaysAllow')}- </Button>- <Button- variant="secondary"- size="sm"- data-analytics-id="chat-approval-deny"- onClick={() => void decide('deny')}- disabled={deciding !== null}>- {deciding === 'deny' ? t('chat.approval.deciding') : t('chat.approval.deny')}- </Button>- </div>- </div>- </div>- </div>- );-};--export default ApprovalRequestCard;diff --git a/app/src/components/chat/IntegrationConnectCard.tsx b/app/src/components/chat/IntegrationConnectCard.tsxdeleted file mode 100644index 09bb7a6286..0000000000--- a/app/src/components/chat/IntegrationConnectCard.tsx+++ /dev/null@@ -1,370 +0,0 @@-import debug from 'debug';-import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';--import { authorize, listConnections } from '../../lib/composio/composioApi';-import { canonicalizeComposioToolkitSlug } from '../../lib/composio/toolkitSlug';-import { deriveComposioState } from '../../lib/composio/types';-import { useT } from '../../lib/i18n/I18nContext';-import { callCoreRpc } from '../../services/coreRpcClient';-import { clearPendingApprovalForThread, type PendingApproval } from '../../store/chatRuntimeSlice';-import { useAppDispatch } from '../../store/hooks';-import { openUrl } from '../../utils/openUrl';-import {- getRequiredFieldsForToolkit,- validateRequiredFieldValues,-} from '../composio/toolkitRequiredFields';-import { Button, TextField } from '../ui';--/**- * Inline OAuth connect card (#3993).- *- * Rendered in place of {@link ApprovalRequestCard} when the agent calls the- * `composio_connect` tool — that tool parks on the same ApprovalGate, so the- * request arrives over the identical `approval_request` socket path, but the- * surface is a **Connect** button rather than approve/deny. Clicking it runs- * `composio_authorize`, opens the OAuth handoff in the browser, and polls- * `composio_list_connections` until the toolkit flips to ACTIVE — at which- * point it resolves the parked tool call with `approve_once` so the agent- * resumes in the same turn. Cancel (or the gate's 10-minute TTL) resolves it- * as `deny`.- *- * Provider-specific required fields (WhatsApp `waba_id`, Jira `subdomain`,- * Dynamics 365 `org_name`) are collected inline from the- * [`toolkitRequiredFields`] registry before the OAuth handoff — so even- * field-gated toolkits connect entirely in-chat rather than failing with a- * raw `ConnectedAccount_MissingRequiredFields` (code 612) error. Mirrors the- * polling + field-collection contract of `ComposioConnectModal` so the two- * connect surfaces behave identically.- */-const log = debug('openhuman:chat:integration-connect-card');--const POLL_INTERVAL_MS = 4_000;-const POLL_TIMEOUT_MS = 5 * 60 * 1_000;--/**- * Composio error slug for missing required fields (code 612). Defensive- * recovery path: if the backend starts requiring a field the registry hasn't- * caught up on, surface a clear message instead of a dead retry loop.- */-const MISSING_REQUIRED_FIELDS_SLUG = 'ConnectedAccount_MissingRequiredFields';--type Phase = 'idle' | 'connecting' | 'error';--interface Props {- threadId: string;- approval: PendingApproval;-}--function errorText(e: unknown): string {- return e instanceof Error ? e.message : String(e);-}--const IntegrationConnectCard: React.FC<Props> = ({ threadId, approval }) => {- const { t } = useT();- const dispatch = useAppDispatch();- // Canonicalize the slug the agent supplied (e.g. `google_drive` →- // `googledrive`) so authorize / list-connections hit the form Composio's- // backend expects (#3993). Defensive: the core already canonicalizes too.- const toolkit = canonicalizeComposioToolkitSlug(approval.toolkit ?? '');-- const [phase, setPhase] = useState<Phase>('idle');- const [errorMsg, setErrorMsg] = useState<string | null>(null);- // Cleared to false on a permanent backend rejection (no auth config, unknown- // toolkit, 400) so the card drops its Retry affordance — retrying won't help.- const [retryable, setRetryable] = useState(true);-- // Provider-specific required fields are sourced from the declarative- // registry — no per-toolkit branches here (mirrors ComposioConnectModal).- const requiredFields = useMemo(() => getRequiredFieldsForToolkit(toolkit), [toolkit]);- const [fieldValues, setFieldValues] = useState<Record<string, string>>({});- const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});-- const pollTimerRef = useRef<number | null>(null);- const pollDeadlineRef = useRef<number>(0);- const isPollingRef = useRef<boolean>(false);- const inFlightRef = useRef<boolean>(false);- // Set once the card is dismissed (Deny) or unmounted, so an `authorize()`- // call still in flight doesn't open OAuth / start polling afterwards.- const cancelledRef = useRef<boolean>(false);-- const stopPolling = useCallback(() => {- isPollingRef.current = false;- if (pollTimerRef.current != null) {- window.clearTimeout(pollTimerRef.current);- pollTimerRef.current = null;- }- }, []);-- // Stop polling if the card unmounts (turn ended, thread switched, decided),- // and mark cancelled so any in-flight authorize continuation aborts.- useEffect(- () => () => {- cancelledRef.current = true;- stopPolling();- },- [stopPolling]- );-- // Resolve the parked `composio_connect` tool call. `approve_once` once the- // connection is live; `deny` when the user cancels. Clears the card on a- // successful decide — ChatRuntimeProvider also clears on turn end.- const resolveGate = useCallback(- async (decision: 'approve_once' | 'deny') => {- try {- await callCoreRpc({- method: 'openhuman.approval_decide',- params: { request_id: approval.requestId, decision },- });- } catch (e) {- // The backend request is still parked. Clearing the card here would- // drop the only surface that can retry/deny it, blocking the thread- // until the gate TTL expires — so keep the card mounted and surface- // the failure instead of clearing it (#4062, coderabbit review).- log('approval_decide(%s) failed: %o', decision, e);- setPhase('error');- setErrorMsg(t('chat.approval.error'));- return;- }- dispatch(clearPendingApprovalForThread({ threadId }));- },- [approval.requestId, dispatch, threadId, t]- );-- const startPolling = useCallback(() => {- stopPolling();- isPollingRef.current = true;- pollDeadlineRef.current = Date.now() + POLL_TIMEOUT_MS;-- const scheduleNext = () => {- if (!isPollingRef.current) return;- pollTimerRef.current = window.setTimeout(() => void tick(), POLL_INTERVAL_MS);- };-- const tick = async () => {- if (inFlightRef.current || !isPollingRef.current) return;- if (Date.now() > pollDeadlineRef.current) {- stopPolling();- setPhase('error');- setErrorMsg(t('composio.connect.oauthTimeout'));- // Resolve the parked tool call now so the agent resumes immediately- // instead of blocking until the 10-min gate TTL (#3993). The agent- // relays the timeout and the user can ask to connect again.- await resolveGate('deny');- return;- }- inFlightRef.current = true;- try {- const resp = await listConnections();- // Scan ALL rows for this toolkit — list_connections returns every row- // (failed / pending / multiple accounts), so the freshly-authorized- // ACTIVE row can sit behind an older FAILED or pending one (#3993,- // codex review). Approve if any row is connected.- const matches = resp.connections.filter(- c => c.toolkit.toLowerCase() === toolkit.toLowerCase()- );- if (matches.some(c => deriveComposioState(c) === 'connected')) {- stopPolling();- await resolveGate('approve_once');- return;- }- // Keep waiting while any handoff is still in flight; only surface an- // error once a failed row exists and nothing is pending.- const pending = matches.some(c => deriveComposioState(c) === 'pending');- const errored = matches.find(c => deriveComposioState(c) === 'error');- if (errored && !pending) {- stopPolling();- setPhase('error');- setErrorMsg(- t('composio.connect.connectionFailed').replace('{status}', String(errored.status))- );- return;- }- } catch (err) {- // Transient poll failures are expected mid-handoff — retry next tick.- log('connection poll failed: %o', err);- } finally {- inFlightRef.current = false;- }- scheduleNext();- };-- void tick();- }, [resolveGate, stopPolling, t, toolkit]);-- const connect = useCallback(async () => {- if (phase === 'connecting' || !toolkit) return;- // A prior Deny (or a failed decide that kept the card mounted) may have set- // cancelledRef — clear it so this fresh, user-initiated attempt isn't- // aborted by the post-authorize cancellation guard.- cancelledRef.current = false;-- // Collect + validate provider-specific required fields before the OAuth- // handoff so field-gated toolkits don't hit a 612 error mid-flow.- let extraParams: Record<string, string> | undefined;- if (requiredFields.length > 0) {- const errors = validateRequiredFieldValues(requiredFields, fieldValues);- if (Object.keys(errors).length > 0) {- setFieldErrors(errors);- return;- }- setFieldErrors({});- extraParams = {};- for (const f of requiredFields) {- extraParams[f.key] = (fieldValues[f.key] ?? '').trim();- }- }-- setPhase('connecting');- setErrorMsg(null);- setRetryable(true);- try {- const resp = await authorize(toolkit, extraParams);- // The user may have hit Deny / dismissed the card while authorize was in- // flight — abort so we don't open OAuth or start polling after the gate- // was already denied, nor race a second approval_decide (codex review).- if (cancelledRef.current) return;- try {- await openUrl(resp.connectUrl);- } catch (openErr) {- // Opening the browser failed, but the handoff may still be reachable;- // keep polling and let the user reopen if needed.- log('openUrl failed: %o', openErr);- }- startPolling();- } catch (e) {- log('authorize failed: %o', e);- setPhase('error');- // Defensive: backend reports a required field the registry lacks. Without- // a field definition we can't collect it inline, so surface a clear- // "needs extra setup" message rather than a retry that will fail again.- if (errorText(e).includes(MISSING_REQUIRED_FIELDS_SLUG) && requiredFields.length === 0) {- setErrorMsg(t('composio.connect.additionalConfigRequired'));- } else {- // Surface the backend's actual reason (e.g. "toolkit not in allowlist")- // so a failed connect is diagnosable — a bare "Connection failed." hides- // whether the toolkit is unsupported, mis-slugged, or a transient error.- // Composio authorize errors are connection diagnostics (no PII); bound- // the length and collapse whitespace before showing.- // Strip the "(status: {status})" clause locale-robustly — the English- // literal differs per locale (de "Status", fr "statut", …), so match the- // parenthetical containing the {status} token rather than the English- // wording, else non-English users see a literal "{status}" (#3993).- const base = t('composio.connect.connectionFailed')- .replace(/\s*\([^)]*\{status\}[^)]*\)/, '')- .trim();- const reason = errorText(e).replace(/\s+/g, ' ').trim().slice(0, 240);- setErrorMsg(reason ? `${base} ${reason}` : base);- // Permanent backend rejections won't change on retry — drop the Retry- // affordance so the user isn't looped on a doomed connect (#3993).- if (/no auth config|not a valid toolkit|unknown toolkit|not found|\b400\b/i.test(reason)) {- setRetryable(false);- }- }- }- }, [phase, requiredFields, fieldValues, startPolling, t, toolkit]);-- const cancel = useCallback(async () => {- cancelledRef.current = true;- stopPolling();- await resolveGate('deny');- }, [resolveGate, stopPolling]);-- const connecting = phase === 'connecting';- const showFields = requiredFields.length > 0 && !connecting;-- return (- <div- role="group"- aria-label={approval.message || t('composio.connect.connect')}- className="rounded-xl border border-primary-200 bg-primary-50 p-3.5 text-sm shadow-xs dark:border-primary-800 dark:bg-primary-950">- <div className="flex items-start gap-3">- <span- aria-hidden- className="mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-primary-100 text-sm text-primary-600 dark:bg-primary-900 dark:text-primary-300">- 🔗- </span>- <div className="min-w-0 flex-1">- <p className="wrap-break-word font-semibold text-content">- {approval.message || t('chat.approval.fallback')}- </p>-- {showFields && (- <div className="mt-2.5 flex flex-col gap-2.5">- {requiredFields.map(field => (- <label key={field.key} className="block text-xs text-content-secondary">- <span className="font-medium">{t(field.labelKey)}</span>- <span className="mt-1 flex items-center gap-1.5">- <TextField- type="text"- value={fieldValues[field.key] ?? ''}- placeholder={field.placeholderKey ? t(field.placeholderKey) : undefined}- onChange={e =>- setFieldValues(prev => ({ ...prev, [field.key]: e.target.value }))- }- className="min-w-0 flex-1"- />- {field.suffix && (- <span className="shrink-0 text-content-faint">{field.suffix}</span>- )}- </span>- {field.hintKey && (- <span className="mt-1 block text-content-muted">{t(field.hintKey)}</span>- )}- {fieldErrors[field.key] && (- <span className="mt-1 block text-coral-600 dark:text-coral-400">- {t(fieldErrors[field.key])}- </span>- )}- </label>- ))}- </div>- )}-- {connecting && (- <p className="mt-1.5 flex items-center gap-1.5 text-xs text-primary-700 dark:text-primary-300">- <span aria-hidden className="h-1.5 w-1.5 animate-pulse rounded-full bg-primary-500" />- {t('composio.connect.waitingHint')}- </p>- )}-- <p className="mt-1.5 text-xs text-content-faint">- {t('chat.approval.tool')}{' '}- <span className="font-mono text-content-muted">{approval.toolName}</span>- </p>-- {errorMsg && (- <p className="mt-2 text-xs text-coral-600 dark:text-coral-400">⚠ {errorMsg}</p>- )}-- <div className="mt-3 flex flex-wrap items-center gap-2">- {/* Hide Connect/Retry on a permanent rejection — retrying a toolkit- the backend can't authorize just loops. Dismiss stays. */}- {!(phase === 'error' && !retryable) && (- <Button- variant="primary"- size="sm"- data-analytics-id="chat-integration-connect"- onClick={() => void connect()}- disabled={connecting || !toolkit}>- {connecting- ? t('chat.approval.deciding')- : phase === 'error'- ? t('composio.connect.retryConnection')- : t('composio.connect.connect')}- </Button>- )}- <Button- variant="secondary"- size="sm"- data-analytics-id="chat-integration-connect-cancel"- onClick={() => void cancel()}>- {t('chat.approval.deny')}- </Button>- </div>- </div>- </div>- </div>- );-};--export default IntegrationConnectCard;diff --git a/app/src/components/chat/UnsubscribeApprovalCard.tsx b/app/src/components/chat/UnsubscribeApprovalCard.tsxdeleted file mode 100644index 32c0d97b21..0000000000--- a/app/src/components/chat/UnsubscribeApprovalCard.tsx+++ /dev/null@@ -1,114 +0,0 @@-import React, { useEffect, useState } from 'react';--import { useT } from '../../lib/i18n/I18nContext';-import { callCoreRpc } from '../../services/coreRpcClient';-import Button from '../ui/Button';--interface UnsubscribePayload {- status: string;- action: string;- metadata: { sender: string; unsubscribe_link: string; message: string };-}--interface Props {- payload: UnsubscribePayload;-}--export const UnsubscribeApprovalCard: React.FC<Props> = ({ payload }) => {- const { t } = useT();- const [status, setStatus] = useState<'pending' | 'approved' | 'denied'>('pending');- const [isProcessing, setIsProcessing] = useState(false);- const [errorMsg, setErrorMsg] = useState<string | null>(null);-- useEffect(() => {- setStatus('pending');- setIsProcessing(false);- setErrorMsg(null);- }, [payload]);-- const handleApprove = async () => {- if (isProcessing || status === 'approved') return;- setIsProcessing(true);- setErrorMsg(null);- try {- // Typically, you would call a core RPC method to execute the URL/mailto- // or instruct the agent to proceed.- await callCoreRpc({- method: 'tools::execute_unsubscribe',- params: { link: payload.metadata.unsubscribe_link },- });- setStatus('approved');- } catch (e: any) {- console.error('Unsubscribe failed', e);- setStatus('pending');- setErrorMsg(e?.message || 'Missing permissions or network error');- } finally {- setIsProcessing(false);- }- };-- const handleDeny = () => {- setStatus('denied');- setErrorMsg(null);- // Optionally notify the agent of the denial so it can update its context- };-- if (payload.action !== 'unsubscribe' || payload.status !== 'pending_approval') return null;-- return (- <div className="border border-line rounded-lg p-4 my-2 bg-surface-muted">- <div className="flex items-start gap-3">- <div className="text-xl">📧</div>- <div className="flex-1">- <h4 className="font-semibold text-sm text-content">- {t('chat.unsubscribeApproval.title')}- </h4>- <p className="text-sm text-content-secondary mt-1">{payload.metadata.message}</p>- <div className="text-xs text-content-muted mt-2 font-mono break-all bg-surface-subtle p-2 rounded">- {payload.metadata.unsubscribe_link}- </div>-- {errorMsg && (- <div className="text-sm text-red-600 font-medium mt-2 bg-red-50 dark:bg-red-900/20 p-2 rounded">- ⚠️ {errorMsg}- </div>- )}-- {status === 'pending' && (- <div className="flex gap-2 mt-4">- <Button- variant="primary"- size="sm"- data-analytics-id="chat-unsubscribe-approve"- onClick={handleApprove}- disabled={isProcessing}>- {isProcessing- ? t('chat.unsubscribeApproval.processing')- : t('chat.unsubscribeApproval.approve')}- </Button>- <Button- variant="secondary"- size="sm"- data-analytics-id="chat-unsubscribe-deny"- onClick={handleDeny}- disabled={isProcessing}>- {t('chat.unsubscribeApproval.deny')}- </Button>- </div>- )}-- {status === 'approved' && (- <div className="text-sm text-green-600 font-medium mt-3">- {t('chat.unsubscribeApproval.approved')}- </div>- )}- {status === 'denied' && (- <div className="text-sm text-red-600 font-medium mt-3">- {t('chat.unsubscribeApproval.denied')}- </div>- )}- </div>- </div>- </div>- );-};diff --git a/app/src/components/chat/__tests__/ApprovalRequestCard.test.tsx b/app/src/components/chat/__tests__/ApprovalRequestCard.test.tsxdeleted file mode 100644index c1f36137cd..0000000000--- a/app/src/components/chat/__tests__/ApprovalRequestCard.test.tsx+++ /dev/null@@ -1,149 +0,0 @@-import { configureStore } from '@reduxjs/toolkit';-import { fireEvent, render, screen, waitFor } from '@testing-library/react';-import { Provider } from 'react-redux';-import { beforeEach, describe, expect, it, vi } from 'vitest';--import { callCoreRpc } from '../../../services/coreRpcClient';-import chatRuntimeReducer, {- type PendingApproval,- setPendingApprovalForThread,-} from '../../../store/chatRuntimeSlice';-import ApprovalRequestCard from '../ApprovalRequestCard';--vi.mock('../../../services/coreRpcClient', () => ({ callCoreRpc: vi.fn() }));--const THREAD = 't1';-const approval: PendingApproval = {- requestId: 'req-approval-1',- toolName: 'shell',- message: 'Run `shell` — shell (18 bytes of arguments)',- command: 'pip show yfinance',-};--function renderCard() {- const store = configureStore({ reducer: { chatRuntime: chatRuntimeReducer } });- store.dispatch(setPendingApprovalForThread({ threadId: THREAD, approval }));- const utils = render(- <Provider store={store}>- <ApprovalRequestCard threadId={THREAD} approval={approval} />- </Provider>- );- return { store, ...utils };-}--describe('ApprovalRequestCard', () => {- beforeEach(() => {- vi.clearAllMocks();- });-- it('renders the action summary, exact command, and tool name', () => {- renderCard();- expect(screen.getByText('Approval needed')).toBeInTheDocument();- expect(screen.getByText('Run `shell` — shell (18 bytes of arguments)')).toBeInTheDocument();- // The exact command being requested is shown verbatim.- expect(screen.getByText('pip show yfinance')).toBeInTheDocument();- expect(screen.getByText('shell')).toBeInTheDocument();- });-- it('uses an opaque warning surface so thread text does not show through', () => {- renderCard();- const card = screen.getByRole('alertdialog', { name: 'Approval needed' });- const command = screen.getByText('pip show yfinance');-- // The real, behavioural invariant: neither the card nor the command chip- // may use a fractional-opacity background utility (e.g.- // `dark:bg-amber-950/40`), which would let the underlying thread text bleed- // through the approval surface. Assert the *absence of any opacity suffix*- // rather than a computed colour — jsdom does not apply Tailwind, so- // getComputedStyle can't observe the background here (plan.md §3).- const OPACITY_SUFFIX = /\bdark:bg-[^\s/]+\/\d+/;- expect(card.className).not.toMatch(OPACITY_SUFFIX);- expect(command.className).not.toMatch(OPACITY_SUFFIX);-- // Deliberate, labeled visual-regression lock on the opaque surface tokens —- // update these only on an intentional restyle of the approval card.- expect(card).toHaveClass('bg-amber-50');- expect(card).toHaveClass('dark:bg-amber-950');- expect(command).toHaveClass('dark:bg-surface-canvas');- });-- it('does not nudge the user to reply yes/no (buttons are the input path)', () => {- renderCard();- expect(screen.queryByText(/reply.*yes/i)).not.toBeInTheDocument();- });-- it('Approve routes approve_once to approval_decide and clears the pending state', async () => {- vi.mocked(callCoreRpc).mockResolvedValueOnce({});- const { store } = renderCard();-- fireEvent.click(screen.getByText('Approve'));-- expect(callCoreRpc).toHaveBeenCalledWith({- method: 'openhuman.approval_decide',- params: { request_id: 'req-approval-1', decision: 'approve_once' },- });- await waitFor(() => {- expect(store.getState().chatRuntime.pendingApprovalByThread[THREAD]).toBeUndefined();- });- });-- it('Deny routes deny to approval_decide', async () => {- vi.mocked(callCoreRpc).mockResolvedValueOnce({});- const { store } = renderCard();-- fireEvent.click(screen.getByText('Deny'));-- expect(callCoreRpc).toHaveBeenCalledWith({- method: 'openhuman.approval_decide',- params: { request_id: 'req-approval-1', decision: 'deny' },- });- await waitFor(() => {- expect(store.getState().chatRuntime.pendingApprovalByThread[THREAD]).toBeUndefined();- });- });-- it('Always allow routes approve_always_for_tool to approval_decide and clears the pending state', async () => {- vi.mocked(callCoreRpc).mockResolvedValueOnce({});- const { store } = renderCard();-- fireEvent.click(screen.getByText('Always allow'));-- expect(callCoreRpc).toHaveBeenCalledWith({- method: 'openhuman.approval_decide',- params: { request_id: 'req-approval-1', decision: 'approve_always_for_tool' },- });- await waitFor(() => {- expect(store.getState().chatRuntime.pendingApprovalByThread[THREAD]).toBeUndefined();- });- });-- it('keeps the prompt and shows an error when the decide RPC fails', async () => {- vi.mocked(callCoreRpc).mockRejectedValueOnce(new Error('gate not installed'));- const { store } = renderCard();-- fireEvent.click(screen.getByText('Approve'));-- await waitFor(() => {- // Raw RPC error text ('gate not installed') is no longer surfaced to the- // user — it's kept in a namespaced debug log; the localized fallback shows.- expect(screen.getByText(/Could not record your decision/)).toBeInTheDocument();- });- // Decision failed → approval stays parked, buttons remain actionable.- expect(store.getState().chatRuntime.pendingApprovalByThread[THREAD]).toEqual(approval);- expect(screen.getByText('Approve')).toBeInTheDocument();- });-- it('falls back to the generic prompt when the approval has no message', () => {- const store = configureStore({ reducer: { chatRuntime: chatRuntimeReducer } });- const noMessage: PendingApproval = { ...approval, message: '' };- store.dispatch(setPendingApprovalForThread({ threadId: THREAD, approval: noMessage }));- render(- <Provider store={store}>- <ApprovalRequestCard threadId={THREAD} approval={noMessage} />- </Provider>- );- expect(- screen.getByText('The agent wants to run an action that needs your approval.')- ).toBeInTheDocument();- });-});diff --git a/app/src/components/chat/__tests__/IntegrationConnectCard.test.tsx b/app/src/components/chat/__tests__/IntegrationConnectCard.test.tsxdeleted file mode 100644index 71cae8a243..0000000000--- a/app/src/components/chat/__tests__/IntegrationConnectCard.test.tsx+++ /dev/null@@ -1,340 +0,0 @@-import { configureStore } from '@reduxjs/toolkit';-import { fireEvent, render, screen, waitFor } from '@testing-library/react';-import { Provider } from 'react-redux';-import { beforeEach, describe, expect, it, vi } from 'vitest';--import { authorize, listConnections } from '../../../lib/composio/composioApi';-import { deriveComposioState } from '../../../lib/composio/types';-import { callCoreRpc } from '../../../services/coreRpcClient';-import chatRuntimeReducer, {- type PendingApproval,- setPendingApprovalForThread,-} from '../../../store/chatRuntimeSlice';-import { openUrl } from '../../../utils/openUrl';-import IntegrationConnectCard from '../IntegrationConnectCard';--vi.mock('../../../services/coreRpcClient', () => ({ callCoreRpc: vi.fn() }));-vi.mock('../../../utils/openUrl', () => ({ openUrl: vi.fn() }));-vi.mock('../../../lib/composio/composioApi', () => ({- authorize: vi.fn(),- listConnections: vi.fn(),-}));-vi.mock('../../../lib/composio/types', () => ({ deriveComposioState: vi.fn() }));--const THREAD = 't1';-const approval: PendingApproval = {- requestId: 'req-connect-1',- toolName: 'composio_connect',- message: 'Connect gmail to complete your task',- toolkit: 'gmail',-};--function renderCard() {- const store = configureStore({ reducer: { chatRuntime: chatRuntimeReducer } });- store.dispatch(setPendingApprovalForThread({ threadId: THREAD, approval }));- const utils = render(- <Provider store={store}>- <IntegrationConnectCard threadId={THREAD} approval={approval} />- </Provider>- );- return { store, ...utils };-}--describe('IntegrationConnectCard', () => {- beforeEach(() => {- vi.clearAllMocks();- });-- it('renders the connect prompt, Connect button, and tool name', () => {- renderCard();- // The action message leads the card (no alarming "Approval needed" title).- expect(screen.getByText('Connect gmail to complete your task')).toBeInTheDocument();- expect(screen.getByText('Connect')).toBeInTheDocument();- expect(screen.getByText('composio_connect')).toBeInTheDocument();- });-- it('Connect authorizes, opens the OAuth url, polls, and resolves approve_once on active', async () => {- vi.mocked(authorize).mockResolvedValueOnce({- connectUrl: 'https://hosted.composio.dev/abc',- connectionId: 'conn-1',- } as Awaited<ReturnType<typeof authorize>>);- vi.mocked(listConnections).mockResolvedValue({- connections: [{ toolkit: 'gmail', status: 'ACTIVE' }],- } as Awaited<ReturnType<typeof listConnections>>);- // First poll tick sees the toolkit ACTIVE.- vi.mocked(deriveComposioState).mockReturnValue('connected');- vi.mocked(callCoreRpc).mockResolvedValue({});-- const { store } = renderCard();- fireEvent.click(screen.getByText('Connect'));-- // No required fields for gmail → authorize called with no extra params.- await waitFor(() => expect(authorize).toHaveBeenCalledWith('gmail', undefined));- await waitFor(() => expect(openUrl).toHaveBeenCalledWith('https://hosted.composio.dev/abc'));- // Polling detected the live connection → parked tool call resolved as approved.- await waitFor(() =>- expect(callCoreRpc).toHaveBeenCalledWith({- method: 'openhuman.approval_decide',- params: { request_id: 'req-connect-1', decision: 'approve_once' },- })- );- await waitFor(() =>- expect(store.getState().chatRuntime.pendingApprovalByThread[THREAD]).toBeUndefined()- );- });-- it('Cancel resolves the parked call as deny', async () => {- vi.mocked(callCoreRpc).mockResolvedValueOnce({});- const { store } = renderCard();-- fireEvent.click(screen.getByText('Deny'));-- expect(callCoreRpc).toHaveBeenCalledWith({- method: 'openhuman.approval_decide',- params: { request_id: 'req-connect-1', decision: 'deny' },- });- await waitFor(() =>- expect(store.getState().chatRuntime.pendingApprovalByThread[THREAD]).toBeUndefined()- );- });-- it('keeps the card mounted and surfaces an error when approval_decide fails', async () => {- // The decide RPC throws — the backend request is still parked, so clearing- // the card would strand the thread until the gate TTL expires. The card- // must stay (so the user can retry/deny) and surface the failure (#4062).- vi.mocked(callCoreRpc).mockRejectedValueOnce(new Error('rpc down'));- const { store } = renderCard();-- fireEvent.click(screen.getByText('Deny'));-- await waitFor(() =>- expect(callCoreRpc).toHaveBeenCalledWith({- method: 'openhuman.approval_decide',- params: { request_id: 'req-connect-1', decision: 'deny' },- })- );- // The parked approval survives the failed decide — not cleared.- expect(store.getState().chatRuntime.pendingApprovalByThread[THREAD]).toBeDefined();- // The failure is shown rather than silently swallowed.- await waitFor(() =>- expect(screen.getByText(/Could not record your decision/)).toBeInTheDocument()- );- });-- it('collects required fields inline before authorizing (whatsapp waba_id)', async () => {- vi.mocked(authorize).mockResolvedValue({- connectUrl: 'https://hosted.composio.dev/wa',- connectionId: 'conn-wa',- } as Awaited<ReturnType<typeof authorize>>);- // Not connected yet — poll keeps waiting; we only assert the authorize args.- vi.mocked(listConnections).mockResolvedValue({ connections: [] } as Awaited<- ReturnType<typeof listConnections>- >);-- const waApproval: PendingApproval = {- requestId: 'req-wa',- toolName: 'composio_connect',- message: 'Connect whatsapp to complete your task',- toolkit: 'whatsapp',- };- const store = configureStore({ reducer: { chatRuntime: chatRuntimeReducer } });- store.dispatch(setPendingApprovalForThread({ threadId: THREAD, approval: waApproval }));- render(- <Provider store={store}>- <IntegrationConnectCard threadId={THREAD} approval={waApproval} />- </Provider>- );-- // The required field is rendered inline.- expect(screen.getByText('WhatsApp Business Account ID (WABA ID)')).toBeInTheDocument();-- // Connecting without filling it blocks authorize and shows a field error.- fireEvent.click(screen.getByText('Connect'));- expect(authorize).not.toHaveBeenCalled();- expect(screen.getByText('This field is required.')).toBeInTheDocument();-- // Filling it forwards the value as an extra_param to authorize.- fireEvent.change(screen.getByRole('textbox'), { target: { value: '123456789012345' } });- fireEvent.click(screen.getByText('Connect'));- await waitFor(() =>- expect(authorize).toHaveBeenCalledWith('whatsapp', { waba_id: '123456789012345' })- );- });-- it('canonicalizes the toolkit slug before authorizing (google_drive → googledrive)', async () => {- vi.mocked(authorize).mockResolvedValueOnce({- connectUrl: 'https://hosted.composio.dev/gd',- connectionId: 'conn-gd',- } as Awaited<ReturnType<typeof authorize>>);- vi.mocked(listConnections).mockResolvedValue({ connections: [] } as Awaited<- ReturnType<typeof listConnections>- >);-- const gdApproval: PendingApproval = {- requestId: 'req-gd',- toolName: 'composio_connect',- message: 'Connect googledrive to complete your task',- toolkit: 'google_drive',- };- const store = configureStore({ reducer: { chatRuntime: chatRuntimeReducer } });- store.dispatch(setPendingApprovalForThread({ threadId: THREAD, approval: gdApproval }));- render(- <Provider store={store}>- <IntegrationConnectCard threadId={THREAD} approval={gdApproval} />- </Provider>- );-- fireEvent.click(screen.getByText('Connect'));- // The card hits the canonical Composio slug, not the agent's guess.- await waitFor(() => expect(authorize).toHaveBeenCalledWith('googledrive', undefined));- });-- it('shows an error and a Retry affordance when authorize fails', async () => {- vi.mocked(authorize).mockRejectedValueOnce(new Error('backend down'));- renderCard();-- fireEvent.click(screen.getByText('Connect'));-- // Raw error text is not surfaced; the localized connection-failed string is.- await waitFor(() => expect(screen.getByText('Retry connection')).toBeInTheDocument());- // The parked call is NOT resolved on a local authorize failure — the user- // can retry without the agent giving up.- expect(callCoreRpc).not.toHaveBeenCalled();- });-- it('surfaces the backend reason and drops Retry on a permanent rejection', async () => {- vi.mocked(authorize).mockRejectedValueOnce(- new Error(- '[composio] authorize failed: Backend returned 400 Bad Request: No auth config found for toolkit "googledrive"'- )- );- renderCard();-- fireEvent.click(screen.getByText('Connect'));-- // The actual backend reason is shown (diagnosable), not a bare "failed".- await waitFor(() => expect(screen.getByText(/No auth config found/)).toBeInTheDocument());- // Retry is gone (it would loop); only Dismiss remains.- expect(screen.queryByText('Retry connection')).not.toBeInTheDocument();- expect(screen.getByText('Deny')).toBeInTheDocument();- });-- it('surfaces the status when polling finds an errored connection', async () => {- vi.mocked(authorize).mockResolvedValueOnce({- connectUrl: 'https://hosted.composio.dev/e',- connectionId: 'conn-e',- } as Awaited<ReturnType<typeof authorize>>);- vi.mocked(listConnections).mockResolvedValue({- connections: [{ toolkit: 'gmail', status: 'FAILED' }],- } as Awaited<ReturnType<typeof listConnections>>);- vi.mocked(deriveComposioState).mockReturnValue('error');-- renderCard();- fireEvent.click(screen.getByText('Connect'));-- await waitFor(() => expect(screen.getByText(/Connection failed/)).toBeInTheDocument());- // A poll-detected error leaves the card for the user to retry/dismiss;- // it does NOT auto-resolve the gate.- expect(callCoreRpc).not.toHaveBeenCalled();- });-- it('shows "additional config required" when authorize reports missing fields for a field-less toolkit', async () => {- vi.mocked(authorize).mockRejectedValueOnce(- new Error('400: ConnectedAccount_MissingRequiredFields')- );- renderCard(); // gmail has no entry in the required-fields registry-- fireEvent.click(screen.getByText('Connect'));-- // Error line renders as "⚠ {msg}", so match the substring.- await waitFor(() => expect(screen.getByText(/Additional config required/)).toBeInTheDocument());- });-- it('approves when any matching row is ACTIVE even behind a stale FAILED row', async () => {- vi.mocked(authorize).mockResolvedValueOnce({- connectUrl: 'https://hosted.composio.dev/m',- connectionId: 'conn-m',- } as Awaited<ReturnType<typeof authorize>>);- // First row is an old FAILED handoff; the freshly-authorized row is ACTIVE.- vi.mocked(listConnections).mockResolvedValue({- connections: [- { toolkit: 'gmail', status: 'FAILED' },- { toolkit: 'gmail', status: 'ACTIVE' },- ],- } as Awaited<ReturnType<typeof listConnections>>);- vi.mocked(deriveComposioState).mockImplementation((c?: { status: string }) =>- c?.status === 'ACTIVE' ? 'connected' : 'error'- );- vi.mocked(callCoreRpc).mockResolvedValue({});-- renderCard();- fireEvent.click(screen.getByText('Connect'));-- // The ACTIVE row wins over the stale FAILED row → approve.- await waitFor(() =>- expect(callCoreRpc).toHaveBeenCalledWith({- method: 'openhuman.approval_decide',- params: { request_id: 'req-connect-1', decision: 'approve_once' },- })- );- });-- it('aborts the authorize continuation if the card is dismissed mid-flight', async () => {- let resolveAuthorize!: (v: Awaited<ReturnType<typeof authorize>>) => void;- vi.mocked(authorize).mockReturnValueOnce(- new Promise(resolve => {- resolveAuthorize = resolve;- })- );- vi.mocked(callCoreRpc).mockResolvedValue({});-- renderCard();- fireEvent.click(screen.getByText('Connect'));- // Deny while authorize is still in flight.- fireEvent.click(screen.getByText('Deny'));- await waitFor(() =>- expect(callCoreRpc).toHaveBeenCalledWith({- method: 'openhuman.approval_decide',- params: { request_id: 'req-connect-1', decision: 'deny' },- })- );-- // authorize finally resolves — the continuation must NOT open OAuth.- resolveAuthorize({- connectUrl: 'https://hosted.composio.dev/x',- connectionId: 'conn-x',- } as Awaited<ReturnType<typeof authorize>>);- await Promise.resolve();- await Promise.resolve();- expect(openUrl).not.toHaveBeenCalled();- });-- it('resolves the gate as deny when the OAuth poll times out', async () => {- vi.useFakeTimers();- try {- vi.mocked(authorize).mockResolvedValueOnce({- connectUrl: 'https://hosted.composio.dev/t',- connectionId: 'conn-t',- } as Awaited<ReturnType<typeof authorize>>);- // Never connects → poll runs until the 5-min deadline.- vi.mocked(listConnections).mockResolvedValue({ connections: [] } as Awaited<- ReturnType<typeof listConnections>- >);- vi.mocked(callCoreRpc).mockResolvedValue({});-- renderCard();- fireEvent.click(screen.getByText('Connect'));-- // Flush authorize + run polling past the 5-min deadline.- await vi.advanceTimersByTimeAsync(5 * 60 * 1000 + 5000);-- // Timeout resolves the parked tool call as deny so the agent resumes.- expect(callCoreRpc).toHaveBeenCalledWith({- method: 'openhuman.approval_decide',- params: { request_id: 'req-connect-1', decision: 'deny' },- });- } finally {- vi.useRealTimers();- }- });-});diff --git a/app/src/components/chat/__tests__/UnsubscribeApprovalCard.test.tsx b/app/src/components/chat/__tests__/UnsubscribeApprovalCard.test.tsxdeleted file mode 100644index 7e8165ad5c..0000000000--- a/app/src/components/chat/__tests__/UnsubscribeApprovalCard.test.tsx+++ /dev/null@@ -1,82 +0,0 @@-import { fireEvent, screen, waitFor } from '@testing-library/react';-import { beforeEach, describe, expect, it, vi } from 'vitest';--import { callCoreRpc } from '../../../services/coreRpcClient';-import { renderWithProviders } from '../../../test/test-utils';-import { UnsubscribeApprovalCard } from '../UnsubscribeApprovalCard';--vi.mock('../../../services/coreRpcClient', () => ({ callCoreRpc: vi.fn() }));--describe('UnsubscribeApprovalCard', () => {- beforeEach(() => {- vi.clearAllMocks();- });-- const mockPayload = {- status: 'pending_approval',- action: 'unsubscribe',- metadata: {- sender: '[email protected]',- unsubscribe_link: 'https://example.com/unsub',- message: 'Agent is requesting permission',- },- };-- it('renders correctly with pending payload', () => {- renderWithProviders(<UnsubscribeApprovalCard payload={mockPayload} />);- expect(screen.getByText('Unsubscribe Request')).toBeInTheDocument();- expect(screen.getByText('Agent is requesting permission')).toBeInTheDocument();- expect(screen.getByText('https://example.com/unsub')).toBeInTheDocument();- });-- it('returns null if action is not unsubscribe', () => {- const payload = { ...mockPayload, action: 'other' };- const { container } = renderWithProviders(<UnsubscribeApprovalCard payload={payload} />);- expect(container).toBeEmptyDOMElement();- });-- it('returns null if status is not pending_approval', () => {- const payload = { ...mockPayload, status: 'completed' };- const { container } = renderWithProviders(<UnsubscribeApprovalCard payload={payload} />);- expect(container).toBeEmptyDOMElement();- });-- it('handles approval successfully', async () => {- vi.mocked(callCoreRpc).mockResolvedValueOnce({ success: true });- renderWithProviders(<UnsubscribeApprovalCard payload={mockPayload} />);-- const approveBtn = screen.getByText('Approve & Unsubscribe');- fireEvent.click(approveBtn);-- expect(callCoreRpc).toHaveBeenCalledWith({- method: 'tools::execute_unsubscribe',- params: { link: 'https://example.com/unsub' },- });-- await waitFor(() => {- expect(screen.getByText('✓ Successfully unsubscribed.')).toBeInTheDocument();- });- });-- it('handles denial', () => {- renderWithProviders(<UnsubscribeApprovalCard payload={mockPayload} />);- const denyBtn = screen.getByText('Deny');- fireEvent.click(denyBtn);- expect(screen.getByText('✕ Request denied.')).toBeInTheDocument();- });-- it('displays error on RPC failure and missing permissions', async () => {- vi.mocked(callCoreRpc).mockRejectedValueOnce(new Error('Missing Gmail write scopes'));- renderWithProviders(<UnsubscribeApprovalCard payload={mockPayload} />);-- const approveBtn = screen.getByText('Approve & Unsubscribe');- fireEvent.click(approveBtn);-- await waitFor(() => {- expect(screen.getByText('⚠️ Missing Gmail write scopes')).toBeInTheDocument();- });-- // Status should remain pending after error- expect(screen.getByText('Approve & Unsubscribe')).toBeInTheDocument();- });-});diff --git a/app/src/features/conversations/aui/toolkit.tsx b/app/src/features/conversations/aui/toolkit.tsxindex 61f55e3e94..cb7c7e6163 100644--- a/app/src/features/conversations/aui/toolkit.tsx+++ b/app/src/features/conversations/aui/toolkit.tsx@@ -6,6 +6,8 @@ import {import { useMemo } from 'react';import { SubagentCall } from '../components/ChatToolParts';+import { MemoryHybridSearchCall, MemoryRecallCall, MemoryStoreCall } from './ChatMemoryChips';+import { CronAddOrUpdateCall, CronListCall, CronRunsCall } from './ChatScheduleCard';import { DocumentArtifactCall, MediaGenerationCall } from './MediaAndDocumentCalls';/**diff --git a/crates/openhuman-core/src/threads/transcript_view/transcript_ordering_tests.rs b/crates/openhuman-core/src/threads/transcript_view/transcript_ordering_tests.rsindex f1344ca1c6..01108507a8 100644--- a/crates/openhuman-core/src/threads/transcript_view/transcript_ordering_tests.rs+++ b/crates/openhuman-core/src/threads/transcript_view/transcript_ordering_tests.rs@@ -370,6 +370,7 @@ fn subagent_of_a_session_root_is_discovered_and_placed_after_its_spawning_call()status,request_id,items,+ ..} => {assert_eq!(id, "sub-abc-123");assert_eq!(agent_id.as_deref(), Some("researcher"));