// The parent session's view of its sub-sessions' waits: every question and // tool approval a descendant is blocked on, pinned above the composer and // answered in place. Answers and decisions go to the sub-session itself, // through the same requests its own page sends, so the agent cannot tell the // difference and the server's permission checks apply unchanged. // "Let the agent decide" instead hands a question to this chat's own agent, // which answers it for the sub-session. import type { McpElicitationAnswer, OpenGeniClient, SessionEvent, SessionHumanInputRequest, SessionSummary, SubmitHumanInputResponseRequest, } from "@opengeni/sdk"; import { ChevronDownIcon, CornerDownRightIcon } from "lucide-react"; import { useCallback, useEffect, useId, useMemo, useRef, useState, type ReactNode } from "react"; import type { PendingApproval } from "../../../approvals"; import type { HumanInputFormProps } from "../../../components/human-input-form"; import { usePolledValue } from "../../../hooks/internal"; import { useHumanInputRequests } from "../../../hooks/use-human-input"; import { delegatedHumanInputRequestIds, humanInputDelegationMessage, } from "../../../human-input-delegation"; import { useOpenGeniText } from "../../../messages/runtime"; import { ApprovalSurface, HumanInputSurface, type ToolReviewDetailsLoader, } from "../../../session-ui"; import { buttonVariants } from "../../../ui/button"; import { userErrorText } from "../../../ui/api-error"; import { DESCENDANT_REQUEST_EVENT_LIMIT, DESCENDANT_REQUEST_EVENT_TYPES, descendantRequestActivity, subSessionsNeedYouLabel, } from "../../lib/descendant-requests"; import { Link } from "../../lib/navigation"; import { sessionDisplayTitle } from "../../lib/session-rename"; import { toast } from "../../lib/toast"; import { cn } from "../../lib/utils"; /** The exact client surface the card reads and answers through. */ export type DescendantRequestsClient = Pick< OpenGeniClient, | "getSession" | "streamEvents" | "listHumanInputRequests" | "submitHumanInputResponse" | "sendMessage" | "listEventPage" | "sendApprovalDecision" | "getToolActionReview" | "getToolReviewDetails" >; export type DescendantRequestsProps = { client: DescendantRequestsClient; workspaceId: string; /** The session whose page shows the card; keys the collapsed preference. */ parentSessionId: string; /** * The viewing session's own events: its messages that handed a question to * its agent mark that card as being decided. */ events?: readonly SessionEvent[] | undefined; /** Descendants waiting on the person, longest-waiting first. */ waiting: readonly SessionSummary[]; /** Something was answered or decided here: re-read the tree. */ onResolved?: (() => void) | undefined; /** * A sub-session started resuming from an approval decided here (`true`), or * has no approval left to decide while it runs (`false`). While it resumes, * the host keeps it in `waiting` so its other approvals stay decidable. */ onResumingChange?: ((sessionId: string, resuming: boolean) => void) | undefined; /** Bumped when this session's agent answered or steered a sub-session; every item re-reads. */ refreshSignal?: number | undefined; loadSkillReview?: HumanInputFormProps["loadSkillReview"]; allowedSaveTo?: HumanInputFormProps["allowedSaveTo"]; /** Safety-net re-read of questions while shown (live hints drive the rest). */ pollIntervalMs?: number | undefined; }; // The shared-feed mode with an empty feed: no live stream per sub-session. // The parent's list hints and lineage reads drive refreshes instead. const NO_EVENTS: SessionEvent[] = []; const DEFAULT_POLL_MS = 15_000; // Approvals are rebuilt from an event page, a heavier read than the question // list; it is re-read on every change the tree sees, so its own poll is slow. const ACTIVITY_POLL_FACTOR = 3; // Whether a parent's stack was collapsed, for this tab: it stays collapsed // after opening a sub-session and coming back. const collapsedStacks = new Map(); // Questions handed to the agent from this tab, until its message shows up in // the viewing session's events. const delegatedRequests = new Set(); export function resetDescendantRequestsStateForTests(): void { collapsedStacks.clear(); delegatedRequests.clear(); } /** * Pending questions and approvals from a session's sub-sessions. One waiting * sub-session shows its request directly; several stack under one line that * collapses them ("3 sub-sessions need you"). Each request names the * sub-session asking and links to it. */ export function DescendantRequests(props: DescendantRequestsProps) { const stackKey = `${props.workspaceId}\u0000${props.parentSessionId}`; // Read from the map on every render, so switching parents never shows the // previous parent's choice for a frame. const [, rerender] = useState(0); const stackId = useId(); const collapsed = collapsedStacks.get(stackKey) ?? false; const setCollapsed = (next: boolean) => { collapsedStacks.set(stackKey, next); rerender((value) => value + 1); }; const count = props.waiting.length; const events = props.events; const delegatedInEvents = useMemo(() => delegatedHumanInputRequestIds(events ?? []), [events]); if (count === 0) return null; const stacked = count > 1; const label = subSessionsNeedYouLabel(count); return (
{stacked ? ( ) : null} {stacked && collapsed ? null : (
{props.waiting.map((session, index) => ( // Later asks start as compact bars so every one is visible. 0} /> ))}
)}
); } export default DescendantRequests; function DescendantRequestItem({ client, workspaceId, parentSessionId, session, compact, delegatedInEvents, onResolved, onResumingChange, refreshSignal = 0, loadSkillReview, allowedSaveTo, pollIntervalMs = DEFAULT_POLL_MS, }: DescendantRequestsProps & { session: SessionSummary; compact: boolean; delegatedInEvents: ReadonlySet; }) { const sessionId = session.id; const t = useOpenGeniText(); const humanInput = useHumanInputRequests(sessionId, { client, workspaceId, events: NO_EVENTS, pollIntervalMs, }); // The SDK's event page read takes no abort signal; an unmounted item's // last read finishes and is dropped. const loadActivity = useCallback(async () => { const page = await client.listEventPage(workspaceId, sessionId, { includeTypes: DESCENDANT_REQUEST_EVENT_TYPES, direction: "before", limit: DESCENDANT_REQUEST_EVENT_LIMIT, payloadMode: "full", }); return descendantRequestActivity(page.events); }, [client, sessionId, workspaceId]); const activity = usePolledValue(loadActivity, { pollIntervalMs: pollIntervalMs * ACTIVITY_POLL_FACTOR, }); // Re-read when the sub-session moved on (a new request, or one settled // elsewhere) or this session's agent answered one. The first render reads. const refreshHumanInput = humanInput.refresh; const refreshActivity = activity.refresh; const seen = useRef({ lastSequence: session.lastSequence, refreshSignal }); useEffect(() => { const previous = seen.current; seen.current = { lastSequence: session.lastSequence, refreshSignal }; if (previous.lastSequence === session.lastSequence && previous.refreshSignal === refreshSignal) return; void refreshHumanInput(); void refreshActivity(); }, [refreshActivity, refreshHumanInput, refreshSignal, session.lastSequence]); const title = sessionDisplayTitle(session); const requests = humanInput.requests; const approvals = activity.data?.approvals ?? []; const requestSequences = activity.data?.requestSequences; const firstRequest = requests[0]; const hasRequest = requests.length > 0 || approvals.length > 0; // Once this wait showed a question or an approval, its end is the request // settling (here, on the sub-session's page or by an agent). The tree still // shows the sub-session waiting until it is re-read, so say nothing for the // rest of that wait; a new wait has a new start time. const waitKey = session.requiresActionSince ?? `sequence:${session.lastSequence}`; const [handledWait, setHandledWait] = useState(null); useEffect(() => { if (hasRequest) setHandledWait(waitKey); }, [hasRequest, waitKey]); const settled = () => { setHandledWait(waitKey); onResolved?.(); }; // Stable, so a re-render never reloads a review that is already shown. const loadReview = useCallback( (approval: PendingApproval) => client.getToolActionReview(workspaceId, sessionId, approval.id), [client, sessionId, workspaceId], ); const loadDetails = useCallback( (review, path, offset) => client.getToolReviewDetails(workspaceId, sessionId, review.id, { actionDigest: review.actionDigest, path, offset, }), [client, sessionId, workspaceId], ); const decide = async ( approval: PendingApproval, decision: "approve" | "reject", answer?: McpElicitationAnswer, ) => { try { await client.sendApprovalDecision(workspaceId, sessionId, { approvalId: approval.id, decision, ...answer, }); } catch (error) { toast.error("Couldn't submit the decision", { description: userErrorText(error) }); throw error instanceof Error ? error : new Error(String(error)); } // The sub-session resumes now; its other approvals stay decidable here. onResumingChange?.(sessionId, true); settled(); await refreshActivity(); }; // Resuming with nothing left to decide: the card has done its part. const resumingWithoutApprovals = session.status !== "requires_action" && activity.data !== null && activity.data.approvals.length === 0; useEffect(() => { if (resumingWithoutApprovals) onResumingChange?.(sessionId, false); }, [onResumingChange, resumingWithoutApprovals, sessionId]); const [delegations, markDelegated] = useState(0); const agentDeciding = useMemo(() => { const ids = new Set(delegatedInEvents); for (const request of requests) if (delegatedRequests.has(request.id)) ids.add(request.id); // `delegations` re-reads the tab-local set after a hand-off. void delegations; return ids; }, [delegatedInEvents, delegations, requests]); const letAgentDecide = async (request: SessionHumanInputRequest) => { const message = humanInputDelegationMessage(t, { sessionId, sessionTitle: title, request }); // A failure reaches the card as is, so it shows the API's own message. await client.sendMessage(workspaceId, parentSessionId, { ...message, clientEventId: crypto.randomUUID(), }); delegatedRequests.add(request.id); markDelegated((value) => value + 1); }; if (hasRequest) { return (
0 ? "question" : "approval"} className="flex flex-col gap-2" > {requests.length > 0 ? (
} /> { // A failed send resolves null. Reject so the form keeps what was // typed (and its draft) for a retry, as on the sub-session's page. if (!(await humanInput.respond(requestId, response))) { throw new Error("Your answer wasn't sent. Try again."); } settled(); }} />
) : null} {approvals.length > 0 ? (
} /> decide(approval, "approve", answer)} onReject={(approval) => decide(approval, "reject")} />
) : null}
); } // Waiting on something only its own page can take (a reconnect, a sign-in): // say so once both reads are in, and point there. const loaded = !humanInput.loading && (activity.data !== null || activity.error !== null); // A sub-session kept up while it resumes waits on nobody once it has no request. if (!loaded || handledWait === waitKey || session.status !== "requires_action") return null; return (
); } /** Which sub-session is asking, and the way to it. */ function ItemSource({ title, verb, link }: { title: string; verb: string; link: ReactNode }) { return (
); } /** Opens the sub-session, scrolled to where it asked when that is known. */ function SubSessionLink({ workspaceId, sessionId, title, at, className, }: { workspaceId: string; sessionId: string; title: string; at: number | null; className?: string | undefined; }) { return ( Open sub-session ); }