Skip to content

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

fix(conversations): prevent subagent drawer from closing on click outside

Steven Enamakel636eda5f9f75
diff --git a/app/src/features/conversations/components/SubagentDrawer.tsx b/app/src/features/conversations/components/SubagentDrawer.tsx
index 2782257c58..aeaac7ba01 100644
--- a/app/src/features/conversations/components/SubagentDrawer.tsx
+++ b/app/src/features/conversations/components/SubagentDrawer.tsx
@@ -1,7 +1,9 @@
+import createDebug from 'debug';
import { type ReactNode, useEffect, useState } from 'react';
-import { createPortal } from 'react-dom';
+import Badge from '../../../components/ui/Badge';
import Button from '../../../components/ui/Button';
+import { SheetContent, SheetRoot, SheetTitle } from '../../../components/ui/Sheet';
import { useT } from '../../../lib/i18n/I18nContext';
import { threadApi } from '../../../services/api/threadApi';
import type {
@@ -12,7 +14,14 @@ import type {
import type { ThreadMessage } from '../../../types/thread';
import { stripToolCallEnvelopes } from '../../../utils/toolTimelineFormatting';
import { BubbleMarkdown } from './AgentMessageBubble';
-import { ToolFailureLines } from './ToolFailureLines';
+import {
+ formatElapsed,
+ SubagentToolCallRow,
+ subagentStatusVariant,
+ useSubagentStatusLabel,
+} from './SubagentToolCallRow';
+
+const log = createDebug('app:conversations:subagent-drawer');
/**
* Rebuild a renderable transcript from a worker sub-thread's persisted
@@ -46,58 +55,24 @@ function transcriptFromMessages(messages: ThreadMessage[]): {
}
/**
- * Map a subagent row's terminal/running status to the visual tone used
- * across the drawer (header dot, status pill). Mirrors the colour
- * language of `ToolTimelineBlock` so the inline card and the drawer read
- * as the same surface.
+ * The status dot beside the sub-agent's name. Only the *dot* is hand-drawn —
+ * the textual status is a shared {@link Badge}, so the tone vocabulary lives
+ * in `subagentStatusVariant` and this maps the same statuses to the matching
+ * fill.
*/
-function statusTone(status: ToolTimelineEntryStatus | undefined): {
- dot: string;
- pill: string;
- label:
- | 'statusRunning'
- | 'statusCompleted'
- | 'statusFailed'
- | 'statusAwaitingUser'
- | 'statusCancelled';
-} {
- if (status === 'success') {
- return {
- dot: 'bg-sage-500',
- pill: 'bg-sage-100 dark:bg-sage-500/20 text-sage-700 dark:text-sage-300',
- label: 'statusCompleted',
- };
+function statusDot(status: ToolTimelineEntryStatus | undefined): string {
+ switch (status) {
+ case 'success':
+ return 'bg-sage-500';
+ case 'error':
+ return 'bg-coral-500';
+ case 'cancelled':
+ return 'bg-content-faint';
+ case 'awaiting_user':
+ return 'bg-amber-400 animate-pulse';
+ default:
+ return 'bg-amber-500 animate-pulse';
}
- if (status === 'error') {
- return {
- dot: 'bg-coral-500',
- pill: 'bg-coral-100 dark:bg-coral-500/20 text-coral-700 dark:text-coral-300',
- label: 'statusFailed',
- };
- }
- if (status === 'cancelled') {
- return {
- dot: 'bg-content-faint',
- pill: 'bg-surface-subtle text-content-secondary',
- label: 'statusCancelled',
- };
- }
- if (status === 'awaiting_user') {
- return {
- dot: 'bg-amber-400 animate-pulse',
- pill: 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-300',
- label: 'statusAwaitingUser',
- };
- }
- return {
- dot: 'bg-amber-500 animate-pulse',
- pill: 'bg-amber-100 dark:bg-amber-500/20 text-amber-700 dark:text-amber-300',
- label: 'statusRunning',
- };
-}
-
-function formatElapsed(ms: number): string {
- return ms >= 1000 ? `${(ms / 1000).toFixed(1)}s` : `${ms}ms`;
}
/**
@@ -113,6 +88,10 @@ function formatElapsed(ms: number): string {
*
* Rendered as `null` when no subagent is selected, so the parent can
* mount it unconditionally and just flip `subagent`.
+ *
+ * The overlay itself is the shared Radix-backed {@link SheetRoot}: the
+ * hand-rolled `createPortal` + backdrop `<button>` + `keydown` listener it
+ * replaced had no focus trap, no scroll lock and no focus restore on close.
*/
export function SubagentDrawer({
subagent,
@@ -140,16 +119,6 @@ export function SubagentDrawer({
const [cancelling, setCancelling] = useState(false);
const [cancelError, setCancelError] = useState(false);
- // Close on Escape for keyboard parity with the backdrop click.
- useEffect(() => {
- if (!subagent) return;
- const onKey = (e: KeyboardEvent) => {
- if (e.key === 'Escape') onClose();
- };
- window.addEventListener('keydown', onKey);
- return () => window.removeEventListener('keydown', onKey);
- }, [subagent, onClose]);
-
// Reopen-from-memory: when there's no live transcript (the row was
// restored from a snapshot, or the user navigated back after the turn
// ended) but a worker sub-thread backs it, load that thread's persisted
@@ -167,6 +136,8 @@ export function SubagentDrawer({
const workerThreadId = subagent?.workerThreadId;
const needsFetch = Boolean(subagent && workerThreadId && liveTranscript.length === 0);
+ const statusLabel = useSubagentStatusLabel(status);
+
useEffect(() => {
if (!needsFetch || !workerThreadId) {
setFetched(null);
@@ -176,12 +147,15 @@ export function SubagentDrawer({
// the new request is in flight.
setFetched(null);
let cancelled = false;
+ log('reopen-from-memory: fetching worker thread %s', workerThreadId);
void threadApi
.getThreadMessages(workerThreadId)
.then(data => {
+ log('reopen-from-memory: %s returned %d messages', workerThreadId, data.messages.length);
if (!cancelled) setFetched({ workerThreadId, ...transcriptFromMessages(data.messages) });
})
.catch(() => {
+ log('reopen-from-memory: fetch failed for %s', workerThreadId);
if (!cancelled) setFetched(null);
});
return () => {
@@ -191,7 +165,6 @@ export function SubagentDrawer({
if (!subagent) return null;
- const tone = statusTone(status);
const isRunning = status !== 'success' && status !== 'error' && status !== 'cancelled';
// The "Cancel task" CTA is only meaningful for a live, still-running run the
// parent gave us a cancel handler for.
@@ -199,14 +172,17 @@ export function SubagentDrawer({
const handleCancel = async () => {
if (!onCancel || cancelling) return;
+ log('cancel requested for task %s', subagent.taskId);
setCancelling(true);
setCancelError(false);
try {
await onCancel();
// Success: the parent flips the row to cancelled and the notice rides the
// idle-delivery path into chat — close the drawer.
+ log('cancel succeeded for task %s', subagent.taskId);
onClose();
} catch {
+ log('cancel FAILED for task %s', subagent.taskId);
setCancelling(false);
setCancelError(true);
}
@@ -226,37 +202,38 @@ export function SubagentDrawer({
}
}
- // Portaled to `document.body` rather than rendered in place. This is a
- // viewport-level overlay, but its host tree sits inside `Conversations`'
- // `relative z-10` wrapper — a stacking context. Left in place, `z-50` only
- // orders it against its own siblings; from the outside the whole chat subtree
- // is just "z-10", so any later sibling with a higher z-index paints straight
- // over it. Portaling lifts it into the root stacking context, where `z-50`
- // means what it reads like. Same pattern as `components/ui/ModalShell`.
- return createPortal(
- <div className="fixed inset-0 z-50 flex justify-end" data-testid="subagent-drawer">
- {/* Backdrop */}
- <button
- type="button"
- aria-label={t('conversations.subagent.close')}
- className="absolute inset-0 bg-surface-overlay/30 dark:bg-surface-overlay/50"
- onClick={onClose}
- />
- <aside className="relative flex h-full w-full max-w-md flex-col bg-surface shadow-xl">
+ return (
+ // `open` is hard-coded because this component renders nothing when there is
+ // no subagent (the early return above) — `onOpenChange` is what routes
+ // Escape / outside-click back to the caller's `onClose`.
+ <SheetRoot
+ open
+ onOpenChange={next => {
+ if (!next) onClose();
+ }}>
+ <SheetContent
+ side="right"
+ aria-describedby={undefined}
+ data-testid="subagent-drawer"
+ className="max-w-md">
{/* Header */}
- <header className="flex items-center gap-2.5 border-b border-line px-4 py-3">
- <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary-50 dark:bg-primary-500/15 text-base">
+ <header className="flex shrink-0 items-center gap-2.5 border-b border-line px-4 py-3">
+ <span
+ aria-hidden
+ className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary-50 text-base dark:bg-primary-500/15">
🤖
</span>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
- <span className="truncate font-semibold text-content">{subagent.agentId}</span>
- <span className={`h-2 w-2 shrink-0 rounded-full ${tone.dot}`} />
+ {/* `asChild` keeps the historical inline span so the drawer's
+ layout is unchanged while Radix gets its required title. */}
+ <SheetTitle asChild>
+ <span className="truncate font-semibold text-content">{subagent.agentId}</span>
+ </SheetTitle>
+ <span aria-hidden className={`h-2 w-2 shrink-0 rounded-full ${statusDot(status)}`} />
</div>
<div className="flex flex-wrap items-center gap-1.5 text-[11px] text-content-muted">
- <span className={`rounded-full px-1.5 py-0.5 ${tone.pill}`}>
- {t(`conversations.subagent.${tone.label}`)}
- </span>
+ <Badge variant={subagentStatusVariant(status)}>{statusLabel}</Badge>
{subagent.childIteration != null ? (
<span>
{subagent.childMaxIterations != null
@@ -300,7 +277,7 @@ export function SubagentDrawer({
<div
role="alert"
data-testid="subagent-cancel-error"
- className="border-b border-coral-200 bg-coral-50 px-4 py-2 text-xs text-coral-700 dark:border-coral-500/30 dark:bg-coral-500/10 dark:text-coral-300">
+ className="shrink-0 border-b border-coral-200 bg-coral-50 px-4 py-2 text-xs text-coral-700 dark:border-coral-500/30 dark:bg-coral-500/10 dark:text-coral-300">
{t('conversations.subagent.cancelFailed')}
</div>
) : null}
@@ -324,7 +301,7 @@ export function SubagentDrawer({
{/* Sub-agent side: avatar label + its turns. */}
<div className="flex items-center gap-1.5 text-[10px] font-semibold uppercase tracking-wide text-content-faint">
- <span>🤖</span>
+ <span aria-hidden>🤖</span>
{subagent.agentId}
</div>
@@ -358,7 +335,10 @@ export function SubagentDrawer({
className="rounded-lg bg-surface-muted px-3 py-2"
data-testid="subagent-transcript-thinking">
<div className="mb-1 flex items-center gap-1.5 text-[11px] font-semibold text-content-muted">
- <span className="inline-block h-1.5 w-1.5 rounded-full bg-primary-400" />
+ <span
+ aria-hidden
+ className="inline-block h-1.5 w-1.5 rounded-full bg-primary-400"
+ />
{t('conversations.subagent.thinking')}
</div>
<pre className="whitespace-pre-wrap break-words font-sans text-[12px] leading-relaxed text-content-secondary">
@@ -375,7 +355,10 @@ export function SubagentDrawer({
<div data-testid="subagent-transcript-text">
<BubbleMarkdown content={stripToolCallEnvelopes(item.text)} />
{isRunning && idx === lastTextIdx ? (
- <span className="ml-0.5 inline-block h-3 w-1 animate-pulse bg-primary-400 align-middle" />
+ <span
+ aria-hidden
+ className="ml-0.5 inline-block h-3 w-1 animate-pulse bg-primary-400 align-middle"
+ />
) : null}
</div>
</ItemWrapper>
@@ -384,16 +367,15 @@ export function SubagentDrawer({
return (
<ItemWrapper key={`tl-${item.callId}`} divider={turnDivider}>
- <ToolCallRow item={item} />
+ <SubagentToolCallRow item={item} />
</ItemWrapper>
);
})}
</ol>
)}
</div>
- </aside>
- </div>,
- document.body
+ </SheetContent>
+ </SheetRoot>
);
}
@@ -406,115 +388,3 @@ function ItemWrapper({ divider, children }: { divider: ReactNode; children: Reac
</>
);
}
-
-type SubagentToolItem = Extract<SubagentTranscriptItem, { kind: 'tool' }>;
-
-/**
- * Pretty-print a tool's input arguments for display. Objects/arrays are
- * rendered as indented JSON; a string is shown verbatim. Returns `null` when
- * there are no arguments to show (e.g. a tool called with no input, or a
- * transcript reopened from memory where args weren't persisted).
- */
-function formatArgs(args: unknown): string | null {
- if (args == null) return null;
- if (typeof args === 'string') return args.length > 0 ? args : null;
- try {
- return JSON.stringify(args, null, 2);
- } catch {
- return String(args);
- }
-}
-
-/**
- * One child tool call in the drawer transcript, expandable to reveal exactly
- * *what happened*: the input arguments the sub-agent passed and the raw output
- * the tool returned. Collapsed by default to keep the transcript scannable;
- * the chevron only appears once there's detail to reveal (args present, or the
- * call completed with a captured result). Reopened-from-memory transcripts
- * carry no args/result, so those rows stay non-expandable.
- */
-function ToolCallRow({ item }: { item: SubagentToolItem }) {
- const { t } = useT();
- const [expanded, setExpanded] = useState(false);
-
- const callTone =
- item.status === 'running'
- ? 'text-amber-700 dark:text-amber-300'
- : item.status === 'success'
- ? 'text-sage-700 dark:text-sage-300'
- : item.status === 'cancelled'
- ? 'text-content-secondary'
- : item.status === 'awaiting_user'
- ? 'text-amber-700 dark:text-amber-300'
- : 'text-coral-700 dark:text-coral-300';
- const statusLabel =
- item.status === 'running'
- ? t('conversations.subagent.statusRunning')
- : item.status === 'success'
- ? t('conversations.subagent.statusCompleted')
- : item.status === 'cancelled'
- ? t('conversations.subagent.statusCancelled')
- : item.status === 'awaiting_user'
- ? t('conversations.subagent.statusAwaitingUser')
- : t('conversations.subagent.statusFailed');
-
- const argsText = formatArgs(item.args);
- const hasOutput = item.result != null;
- const expandable = argsText != null || hasOutput;
-
- const detailPre =
- 'max-h-60 overflow-auto whitespace-pre-wrap break-words rounded bg-surface px-2 py-1.5 ' +
- 'font-mono text-[11px] leading-relaxed text-content-secondary dark:bg-surface';
- const detailLabel = 'mb-1 text-[10px] font-semibold uppercase tracking-wide text-content-faint';
-
- return (
- <div
- className="rounded-md border border-line bg-surface-muted text-xs"
- data-testid="subagent-drawer-tool-call">
- <button
- type="button"
- disabled={!expandable}
- onClick={() => setExpanded(v => !v)}
- aria-expanded={expandable ? expanded : undefined}
- data-testid="subagent-tool-call-toggle"
- className="flex w-full items-center gap-2 px-2.5 py-1.5 text-left disabled:cursor-default">
- {expandable ? (
- <span className="shrink-0 text-[9px] text-content-faint">{expanded ? '▾' : '▸'}</span>
- ) : (
- <span className="w-[9px] shrink-0" aria-hidden />
- )}
- <span className={callTone}>🔧</span>
- <span className="font-mono text-content-secondary">{item.toolName}</span>
- <span className={`ml-auto ${callTone}`}>{statusLabel}</span>
- {item.elapsedMs != null && item.status !== 'running' ? (
- <span className="text-[10px] text-content-faint">{formatElapsed(item.elapsedMs)}</span>
- ) : null}
- </button>
- {item.status === 'error' && item.failure ? (
- <div className="px-2.5 pb-1.5">
- <ToolFailureLines failure={item.failure} />
- </div>
- ) : null}
- {expandable && expanded ? (
- <div className="space-y-2 border-t border-line px-2.5 py-2">
- {argsText != null ? (
- <div data-testid="subagent-tool-call-input">
- <div className={detailLabel}>{t('conversations.subagent.input')}</div>
- <pre className={detailPre}>{argsText}</pre>
- </div>
- ) : null}
- {hasOutput ? (
- <div data-testid="subagent-tool-call-output">
- <div className={detailLabel}>{t('conversations.subagent.output')}</div>
- <pre className={detailPre}>
- {item.result && item.result.length > 0
- ? item.result
- : t('conversations.subagent.noOutput')}
- </pre>
- </div>
- ) : null}
- </div>
- ) : null}
- </div>
- );
-}