diff --git a/app/src/components/channels/chat-transcript.tsx b/app/src/components/channels/chat-transcript.tsx index 5d40e18203..a3ca2c4785 100644 --- a/app/src/components/channels/chat-transcript.tsx +++ b/app/src/components/channels/chat-transcript.tsx @@ -165,6 +165,10 @@ import { type SlackNames, slackNamesIn, } from "@/lib/slack/mentions"; +import { + publishThreadSubtasks, + subtasksOf, +} from "@/lib/subagents/thread-subtasks"; import { readTeamBotConsent } from "@/lib/team-bots"; import { cn } from "@/lib/utils"; import { VOICE_CHAT_ACTIVITY, type VoiceChatEntry } from "@/lib/voice/archive"; @@ -195,6 +199,7 @@ import { mendedSends } from "./mended-sends"; import { usePacedReveal } from "./paced-reveal"; import { latestPlanPerTurn } from "./plan-turns"; import { ResearchResults } from "./research-results"; +import { SubtaskAskContext } from "./subtask-ask"; import { TeamBotConsentCard } from "./team-bot-consent"; import { MakeArtifactToolbar, @@ -579,6 +584,8 @@ function Stopped({ if (event.key !== "Escape" || event.defaultPrevented) return; const at = event.target instanceof Element ? event.target : null; if (at?.closest(ESCAPE_BELONGS_TO)) return; + // A subtask's page over the conversation takes Escape: it goes back (`SubtaskPage`). + if (document.querySelector('[data-slot="subtask-page"]')) return; onDismiss(); }; document.addEventListener("keydown", onKey); @@ -1243,6 +1250,7 @@ const TranscriptMessage = memo(function TranscriptMessage({ }) { const isUser = role === "user"; const live = useArrivedLive(); + const subtaskAsk = useContext(SubtaskAskContext); const [mode] = useState(() => messageMode(live, streaming)); // A person's message arrives whole; only a Bot's reply is paced. const revealed = usePacedReveal(text, { @@ -1263,13 +1271,18 @@ const TranscriptMessage = memo(function TranscriptMessage({ * A task thread's first message is the Bot's brief, not something the person typed: drawn as sent * from the Bot, without the words that frame it for the model. See `frameBrief`. */ - const brief = isUser ? readBrief(text) : null; + const asked = isUser && subtaskAsk?.messageId === messageId; + const brief = asked ? text : isUser ? readBrief(text) : null; if (brief !== null) { return ( - + @@ -2789,6 +2802,15 @@ export function ChatTranscript({ if (taskThread && threadId) publishThreadWork(threadId, threadWorkOf(visible)); }); + /* + * Its subtasks, for the view that opens one of them (`thread-subtasks.ts`), once it draws the live + * conversation: not while its history is on its way, nor while it draws a copy of it (what was + * kept from last time, or the history the join replays), which may not hold every turn yet. + */ + useEffect(() => { + if (threadId && !restoring && !readOnly && !kept) + publishThreadSubtasks(threadId, subtasksOf(visible, busy)); + }); const taskWork = { folds, lastAskId: [...folds.at.values()].at(-1)?.askId, diff --git a/app/src/components/channels/open-subtask.ts b/app/src/components/channels/open-subtask.ts new file mode 100644 index 0000000000..502fc6638f --- /dev/null +++ b/app/src/components/channels/open-subtask.ts @@ -0,0 +1,19 @@ +import { createContext, useContext } from "react"; + +/** + * Where a subtask's row takes the person: the subtask's own view (`SubtaskView`), given by the + * screen that can show it. A transcript drawn where nothing can show one (a subtask's own view, a + * preview) has none, and its rows open in place to their steps, as they did before there was a view. + */ +export type OpenSubtask = { + /** The address of a subtask's view, so the row is a real link: a new tab, a copied link. */ + hrefOf: (toolCallId: string) => string; + /** Open it here. */ + open: (toolCallId: string) => void; +}; + +export const OpenSubtaskContext = createContext(null); + +export function useOpenSubtask(): OpenSubtask | null { + return useContext(OpenSubtaskContext); +} diff --git a/app/src/components/channels/subtask-ask.ts b/app/src/components/channels/subtask-ask.ts new file mode 100644 index 0000000000..62fd11b7ad --- /dev/null +++ b/app/src/components/channels/subtask-ask.ts @@ -0,0 +1,16 @@ +import { createContext } from "react"; + +/** + * The message a subtask's thread starts with, when the transcript draws a subtask's thread + * (`SubtaskView`): what the Bot asked the subagent, drawn as sent from that Bot, as a task's brief + * is (`SentFromBot`), and never as something the person typed. + * + * A context rather than a reading of the text: the words that frame a subagent's task are the + * server's to change, and the view already knows which message it put there. + */ +export const SubtaskAskContext = createContext<{ + /** The id of the message that carries the task. */ + messageId: string; + /** The Bot that asked, by name. */ + from: string; +} | null>(null); diff --git a/app/src/components/channels/subtask-step.tsx b/app/src/components/channels/subtask-step.tsx index a5235f150c..16b994ef17 100644 --- a/app/src/components/channels/subtask-step.tsx +++ b/app/src/components/channels/subtask-step.tsx @@ -7,6 +7,7 @@ import { TurnInFlightContext } from "@/components/gallery/streaming"; import { IconChevronRight } from "@/components/icons"; import { subagentStepsQueryOptions } from "@/lib/subagents/queries"; import { toVisibleChatItems, type VisibleChatItem } from "./chat-messages"; +import { useOpenSubtask } from "./open-subtask"; import { foldRereads, type StepDetails, @@ -51,6 +52,7 @@ export function SubtaskStep({ active: boolean; }) { const chat = useCopilotChatConfiguration(); + const opens = useOpenSubtask(); const [open, setOpen] = useState(false); const toolCallId = step.subtask?.toolCallId ?? step.id; const result = step.subtask?.result ?? null; @@ -85,6 +87,71 @@ export function SubtaskStep({ const handedBack = result && "handedBack" in result ? result.handedBack : null; + const line = ( + <> + {/* The chevron every line that opens wears (`ToolLine`). */} + + + + + + {/* Shimmers while it works, as every running step does. See `StepRow`. */} + + {step.label} + + {step.detail ? ( + {step.detail} + ) : null} + + + + ); + /* + * A ROW THAT OPENS THE SUBTASK'S OWN VIEW, WHERE THERE IS ONE. Opened in place, a subtask's + * steps were a list under its row, drawn smaller and without the Bot's words between them: a + * subagent that worked for ten minutes read as a column of lines under one row. Its view reads it + * as the conversation reads the Bot (`SubtaskView`). A link, so it opens in a new tab too. + */ + if (opens) + return ( +
  • + { + // A new tab or window is the browser's, as for any link. + if ( + event.defaultPrevented || + event.button !== 0 || + event.metaKey || + event.ctrlKey || + event.shiftKey || + event.altKey + ) + return; + event.preventDefault(); + opens.open(toolCallId); + }} + > + {line} + +
  • + ); return (
  • setOpen(event.currentTarget.open)} > - {/* The chevron every line that opens wears (`ToolLine`). */} - - - - - - {/* Shimmers while it works, as every running step does. See `StepRow`. */} - - {step.label} - - {step.detail ? ( - - {step.detail} - - ) : null} - - + {line}
    {step.subtask?.task ? ( @@ -260,7 +294,7 @@ function SubtaskStatus({ * The action the subagent stopped before, said plainly. Nothing was done and nobody was asked. The * Bot does it itself if it still needs doing, and the person is asked then, on the Bot's own card. */ -function HandedBack({ tool, args }: { tool: string; args: unknown }) { +export function HandedBack({ tool, args }: { tool: string; args: unknown }) { const { label, detail } = tool.startsWith("mcp__") ? readToolName(tool) : { label: humanise(tool.replace(/^computer_/, "")), detail: undefined }; diff --git a/app/src/components/channels/subtask-view.tsx b/app/src/components/channels/subtask-view.tsx new file mode 100644 index 0000000000..fe34bf757a --- /dev/null +++ b/app/src/components/channels/subtask-view.tsx @@ -0,0 +1,284 @@ +import type { Message } from "@ag-ui/core"; +import { CopilotChatConfigurationProvider } from "@copilotkit/react-core/v2"; +import { subagentThreadId } from "@openbot/shared/subagent"; +import { useQuery } from "@tanstack/react-query"; +import { type ReactNode, useEffect, useMemo, useRef, useState } from "react"; +import { IconChevronLeft, IconChevronRight } from "@/components/icons"; +import { SidebarToggle } from "@/components/layout/sidebar-toggle"; +import { Button } from "@/components/ui/button"; +import { + Tooltip, + TooltipContent, + TooltipTrigger, +} from "@/components/ui/tooltip"; +import { channelAgentId } from "@/lib/copilot/active-bot"; +import { subagentStepsQueryOptions } from "@/lib/subagents/queries"; +import { useThreadSubtask } from "@/lib/subagents/thread-subtasks"; +import { cn } from "@/lib/utils"; +import { ChatTranscript, RestoringTranscript } from "./chat-transcript"; +import { transcriptColumn } from "./conversation-columns"; +import { SubtaskAskContext } from "./subtask-ask"; +import { HandedBack, SUBTASK_LINE_EVERY_MS } from "./subtask-step"; +import { stepDetails } from "./tool-activity"; + +/** + * One subtask, read as a conversation of its own: what the Bot asked it, its thinking and steps on + * the same grouped line and rows a conversation draws, and its answer, live while it runs. + * + * It is the conversation's own transcript, given the subagent's thread. A subagent is the same Bot + * run again on one part of the work, in a thread of its own, so what it did reads exactly as what + * the Bot does in the conversation, drawn by the same code and changing with it. + * + * WHAT IT WAS ASKED IS THE CALL'S, NOT THE THREAD'S. The thread starts with the server's framing of + * the task for the model ("You are a subagent: …"), which the person never needs to read; the view + * draws the task the Bot wrote, from its call, in that message's place, sent from the Bot. Whether + * it is still running and how it ended are the call's too (`thread-subtasks.ts`): the thread says + * what the subagent did, never whether it is still doing it. + * + * Read only: a subtask can't be written to. Its steps are read from its thread every five seconds + * while it works, the same read its row in the conversation makes, so the two never disagree and + * the store is asked once for both. + */ +export function SubtaskView({ + channelId, + parentThreadId, + toolCallId, + botName, +}: { + /** The conversation the subtask was started in. */ + channelId: string; + /** Its thread, which the subagent's thread is derived from. */ + parentThreadId: string; + toolCallId: string; + /** The Bot that asked, by name: the task is drawn as sent from it. */ + botName: string; +}) { + const subtask = useThreadSubtask(parentThreadId, toolCallId); + const step = subtask ? stepDetails(subtask.call) : undefined; + const running = Boolean(subtask?.inFlight && step?.pending); + const result = step?.subtask?.result ?? null; + const agentId = channelAgentId(channelId); + const options = subagentStepsQueryOptions({ + toolCallId, + parentThreadId, + threadId: result?.threadId, + agentId, + live: running, + every: SUBTASK_LINE_EVERY_MS, + }); + const thread = useQuery({ + ...options, + enabled: Boolean(subtask) && options.enabled !== false, + }); + const threadId = useSubagentThreadId( + parentThreadId, + toolCallId, + result?.threadId, + ); + const ask = step?.subtask?.task ?? step?.detail; + const stored = thread.data?.messages; + const messages = useMemo((): Message[] => { + if (ask === undefined) return []; + const asked: Message = { + id: askId(toolCallId), + role: "user", + content: ask, + }; + // The thread's first message is the server's framing of the task; the task is drawn in its place. + const work = + stored?.[0]?.role === "user" ? stored.slice(1) : (stored ?? []); + // A thread that can't be read still has its answer, in the call's result. + if (work.length === 0 && result && "answer" in result) + return [ + asked, + { + id: `${askId(toolCallId)}:answer`, + role: "assistant", + content: result.answer, + }, + ]; + return [asked, ...work]; + }, [ask, stored, result, toolCallId]); + // One value while it names the same task and Bot, so the messages under it aren't drawn again. + const asking = useMemo( + () => ({ messageId: askId(toolCallId), from: botName }), + [toolCallId, botName], + ); + const givenUp = useAfter(MISSING_AFTER_MS, subtask === null); + const handedBack = + result && "handedBack" in result ? result.handedBack : null; + const error = + !running && step?.failed && result && "error" in result + ? { message: result.error } + : undefined; + + /* + * Opened at its own address, the conversation is still reading its history, which names it. A + * reload draws it in steps (what was kept from last time, then the history the join replays, then + * the live conversation), and a step may not hold this turn yet: the subtask is said to be missing + * only once the conversation has had a moment to draw it all. + */ + if (!subtask && !(subtask === null && givenUp)) + return ( +
    + +
    + ); + if (!subtask) + return ( +

    + This subtask isn't in this conversation. +

    + ); + return ( +
    + + + + +
    + ), + } + : {})} + /> + + +
    + ); +} + +/** What Back is called, to the eye and to a screen reader: where it goes. */ +const BACK_LABEL = "Back to the conversation"; + +/** + * A subtask in place of its conversation, at an address of its own: its view under one header row, + * which starts with the sidebar's toggle (when the sidebar is hidden) and the way back, and names + * where the person is: the conversation, then the subtask. Drawn as an artifact's full page is + * (`ArtifactFullPage`): Escape is Back too, and Back takes the focus, since the row that opened it + * is behind the page now. + * + * The conversation stays drawn underneath, so going back finds it where it was: scrolled where it + * was, its turn still running, its message box as it was left. + */ +export function SubtaskPage({ + conversation, + onBack, + children, +}: { + /** The conversation it leads back to, by name. */ + conversation: string | undefined; + onBack: () => void; + /** The subtask's view. */ + children: ReactNode; +}) { + const back = useRef(null); + useEffect(() => { + back.current?.focus(); + const onKey = (event: KeyboardEvent) => { + if (!escapeIsOurs(event)) return; + event.preventDefault(); + back.current?.click(); + }; + document.addEventListener("keydown", onKey); + return () => document.removeEventListener("keydown", onKey); + }, []); + return ( +
    +
    + + + + } + > + + + {BACK_LABEL} + + + {conversation} + + +

    Subtask

    +
    + {children} +
    + ); +} + +/** Escape goes back, unless something else takes it: a field, or a menu or dialog over the page. */ +function escapeIsOurs(event: KeyboardEvent): boolean { + if (event.key !== "Escape" || event.defaultPrevented || event.isComposing) + return false; + const target = event.target instanceof Element ? event.target : null; + if (target?.closest("input, textarea, select, [contenteditable=true]")) + return false; + return !document.querySelector( + "[role=dialog], [role=alertdialog], [role=menu], [role=listbox]", + ); +} + +/** How long a subtask the conversation hasn't drawn may take before it is said to be missing. */ +const MISSING_AFTER_MS = 5_000; + +/** True once `when` has held for `ms` without a break. */ +function useAfter(ms: number, when: boolean): boolean { + const [after, setAfter] = useState(false); + useEffect(() => { + setAfter(false); + if (!when) return; + const timer = setTimeout(() => setAfter(true), ms); + return () => clearTimeout(timer); + }, [ms, when]); + return after; +} + +/** The id of the message that carries the task: the same for the subtask's whole life. */ +function askId(toolCallId: string): string { + return `subtask-ask:${toolCallId}`; +} + +/** The subagent's thread: the one its result named, or derived as the server derived it. */ +function useSubagentThreadId( + parentThreadId: string, + toolCallId: string, + named: string | undefined, +): string | undefined { + const [derived, setDerived] = useState(); + useEffect(() => { + if (named) return; + let current = true; + void subagentThreadId(parentThreadId, toolCallId).then((id) => { + if (current) setDerived(id); + }); + return () => { + current = false; + }; + }, [named, parentThreadId, toolCallId]); + return named ?? derived; +} diff --git a/app/src/components/channels/tool-activity.tsx b/app/src/components/channels/tool-activity.tsx index 4442dd00f0..81cce92a35 100644 --- a/app/src/components/channels/tool-activity.tsx +++ b/app/src/components/channels/tool-activity.tsx @@ -119,6 +119,7 @@ import { } from "./browser-activity"; import type { VisibleChatItem } from "./chat-messages"; import { codingOutcome, lookStep } from "./coding-tool-cards"; +import { OpenSubtaskContext, useOpenSubtask } from "./open-subtask"; import { ResearchResults } from "./research-results"; import { SubtaskLiveLine, SubtaskStep } from "./subtask-step"; import { ToolLine, useDrawnOnceOpened } from "./tool-line"; @@ -1869,6 +1870,7 @@ export function SubtaskRows({ const folders = useContext(FolderNamesContext); const inFlight = useContext(TurnInFlightContext); const appName = useAppName(); + const opens = useOpenSubtask(); const [all, setAll] = useState(false); const steps = group.steps.map( stepDetailsIn(folders, active || inFlight, appName), @@ -1900,12 +1902,25 @@ export function SubtaskRows({ {steps.length} subtasks -
      { + setAll(false); + opens.open(toolCallId); + }, + } + } > - {rows(steps)} -
    +
      + {rows(steps)} +
    + ) : null} diff --git a/app/src/components/tasks/task-thread.tsx b/app/src/components/tasks/task-thread.tsx index 1899bdafd7..fd95704f6a 100644 --- a/app/src/components/tasks/task-thread.tsx +++ b/app/src/components/tasks/task-thread.tsx @@ -702,20 +702,30 @@ function ThreadLink({ thread }: { thread: LinkedThread }) { /** * The Bot's brief at the top of a task's thread: the work it was handed, said by the Bot, so the - * thread reads as the Bot's and not as something the person typed. + * thread reads as the Bot's and not as something the person typed. A subtask's thread starts the + * same way, with what the Bot asked the subagent (`SubtaskView`), and names the Bot itself. */ export function SentFromBot({ threadId, brief, + from, }: { /** The task's thread, which names the task and so the Bot that sent it. */ threadId: string | undefined; brief: string; + /** The Bot that sent it, when the thread is a subtask's and no task names it. */ + from?: string; }) { const { data: bots } = useQuery(agentListQueryOptions()); - const { data: tasks } = useQuery(taskListQueryOptions()); - const task = tasks?.find((task) => task.threadId === threadId); - const name = bots?.find((bot) => bot.id === task?.agentId)?.name; + const { data: tasks } = useQuery({ + ...taskListQueryOptions(), + enabled: from === undefined, + }); + const task = + from === undefined + ? tasks?.find((task) => task.threadId === threadId) + : undefined; + const name = from ?? bots?.find((bot) => bot.id === task?.agentId)?.name; const label = `Sent from ${name ?? "your Bot"}`; // The agent the Bot handed it to, when it handed it to one: said after the link, as plain words. const to = task?.agent?.name ? ` to ${task.agent.name}` : ""; diff --git a/app/src/lib/subagents/thread-subtasks.ts b/app/src/lib/subagents/thread-subtasks.ts new file mode 100644 index 0000000000..a014f4f350 --- /dev/null +++ b/app/src/lib/subagents/thread-subtasks.ts @@ -0,0 +1,92 @@ +import { SUBAGENT_TOOL } from "@openbot/shared/subagent"; +import { useSyncExternalStore } from "react"; +import type { VisibleChatItem } from "@/components/channels/chat-messages"; +import { isPersonSentMessage } from "@/components/channels/transcript-turns"; + +type ToolItem = Extract; + +/* + * The subtasks a conversation's transcript is drawing, for the view that opens one of them. + * + * A subtask's own facts (what it was asked, whether it has finished, its answer) are in the + * conversation's call and its result, which only the conversation has: the subagent's own thread + * says what it did, never whether it is still doing it. The transcript hands them over through this + * store as it draws them, as it hands a task's Details pane its work (`thread-work.ts`), so the view + * never reads the conversation a second time and follows the call as it changes. + */ + +/** One subtask as its conversation draws it. */ +export type ThreadSubtask = { + /** The `run_subagent` call, with its result once it has one. */ + call: ToolItem; + /** Its turn is the one in flight, so without a result it is still running. */ + inFlight: boolean; +}; + +/** The subtask calls among a transcript's items, each saying whether its turn is in flight. */ +export function subtasksOf( + items: readonly VisibleChatItem[], + busy: boolean, +): ThreadSubtask[] { + const turnStart = items.findLastIndex( + (item) => + (item.kind === "text" && isPersonSentMessage(item.role, item.text)) || + item.kind === "attachments", + ); + return items.flatMap((item, index) => + item.kind === "tool" && item.toolCall.function.name === SUBAGENT_TOOL + ? [{ call: item, inFlight: busy && index > turnStart }] + : [], + ); +} + +const published = new Map(); +const signatures = new Map(); +const listeners = new Set<() => void>(); + +/** What tells two drawings of a thread's subtasks apart: which calls, their answers, their turn. */ +function signature(subtasks: readonly ThreadSubtask[]): string { + return JSON.stringify( + subtasks.map(({ call, inFlight }) => [ + call.toolCall.id, + call.toolCall.function.arguments, + call.result === undefined ? null : String(call.result), + inFlight, + ]), + ); +} + +/** Say which subtasks a thread's transcript draws now, once its history is drawn. */ +export function publishThreadSubtasks( + threadId: string, + next: readonly ThreadSubtask[], +): void { + const said = signature(next); + if (signatures.get(threadId) === said) return; + signatures.set(threadId, said); + published.set(threadId, next); + for (const listener of listeners) listener(); +} + +function subscribe(listener: () => void) { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; +} + +/** + * One subtask of a conversation, kept current while its transcript is drawn. Undefined until the + * transcript has drawn the conversation's history (its read can take seconds, on a page opened at + * the subtask's own address), and null once it has, if the subtask isn't in it. + */ +export function useThreadSubtask( + threadId: string | undefined, + toolCallId: string, +): ThreadSubtask | null | undefined { + const subtasks = useSyncExternalStore(subscribe, () => + threadId ? published.get(threadId) : undefined, + ); + if (subtasks === undefined) return undefined; + return subtasks.find((one) => one.call.toolCall.id === toolCallId) ?? null; +} diff --git a/app/src/routeTree.gen.ts b/app/src/routeTree.gen.ts index d1f3cc991b..5d8b2492f7 100644 --- a/app/src/routeTree.gen.ts +++ b/app/src/routeTree.gen.ts @@ -158,6 +158,7 @@ import { Route as AuthedSettingsPersonalVaultNewRouteImport } from './routes/_au import { Route as AuthedSettingsProvidersProviderChangeRouteImport } from './routes/_authed/settings/providers_.$provider_.change' import { Route as AuthedAppBotsAgentIdSetupFieldRouteImport } from './routes/_authed/_app/bots.$agentId.setup_.$field' import { Route as AuthedAppBotsAgentIdSetupKeyRouteImport } from './routes/_authed/_app/bots.$agentId.setup_.key' +import { Route as AuthedAppChannelChannelIdSubtaskToolCallIdRouteImport } from './routes/_authed/_app/channel/$channelId.subtask.$toolCallId' import { Route as AuthedAppConnectionsKeyBotsAgentIdRouteImport } from './routes/_authed/_app/connections.$key_.bots.$agentId' import { Route as AuthedAppConnectionsKeyToolsToolRouteImport } from './routes/_authed/_app/connections.$key_.tools.$tool' import { Route as AuthedAppRoutinesSchedulesRoutineIdEditRouteImport } from './routes/_authed/_app/routines_.schedules.$routineId_.edit' @@ -972,6 +973,12 @@ const AuthedAppBotsAgentIdSetupKeyRoute = path: '/bots/$agentId/setup/key', getParentRoute: () => AuthedAppRoute, } as any) +const AuthedAppChannelChannelIdSubtaskToolCallIdRoute = + AuthedAppChannelChannelIdSubtaskToolCallIdRouteImport.update({ + id: '/subtask/$toolCallId', + path: '/subtask/$toolCallId', + getParentRoute: () => AuthedAppChannelChannelIdRoute, + } as any) const AuthedAppConnectionsKeyBotsAgentIdRoute = AuthedAppConnectionsKeyBotsAgentIdRouteImport.update({ id: '/connections/$key_/bots/$agentId', @@ -1071,7 +1078,7 @@ export interface FileRoutesByFullPath { '/bug-reports/$reportId': typeof AuthedAppBugReportsReportIdRoute '/capabilities/memory': typeof AuthedAppCapabilitiesMemoryRoute '/capabilities/skills': typeof AuthedAppCapabilitiesSkillsRoute - '/channel/$channelId': typeof AuthedAppChannelChannelIdRoute + '/channel/$channelId': typeof AuthedAppChannelChannelIdRouteWithChildren '/channel/new': typeof AuthedAppChannelNewRoute '/connections/$key': typeof AuthedAppConnectionsKeyRoute '/connections/new': typeof AuthedAppConnectionsNewRoute @@ -1150,6 +1157,7 @@ export interface FileRoutesByFullPath { '/bots/$agentId/': typeof AuthedAppBotsAgentIdIndexRoute '/bots/$agentId/setup/$field': typeof AuthedAppBotsAgentIdSetupFieldRoute '/bots/$agentId/setup/key': typeof AuthedAppBotsAgentIdSetupKeyRoute + '/channel/$channelId/subtask/$toolCallId': typeof AuthedAppChannelChannelIdSubtaskToolCallIdRoute '/connections/$key/bots/$agentId': typeof AuthedAppConnectionsKeyBotsAgentIdRoute '/connections/$key/tools/$tool': typeof AuthedAppConnectionsKeyToolsToolRoute '/routines/schedules/$routineId/edit': typeof AuthedAppRoutinesSchedulesRoutineIdEditRoute @@ -1222,7 +1230,7 @@ export interface FileRoutesByTo { '/bug-reports/$reportId': typeof AuthedAppBugReportsReportIdRoute '/capabilities/memory': typeof AuthedAppCapabilitiesMemoryRoute '/capabilities/skills': typeof AuthedAppCapabilitiesSkillsRoute - '/channel/$channelId': typeof AuthedAppChannelChannelIdRoute + '/channel/$channelId': typeof AuthedAppChannelChannelIdRouteWithChildren '/channel/new': typeof AuthedAppChannelNewRoute '/connections/$key': typeof AuthedAppConnectionsKeyRoute '/connections/new': typeof AuthedAppConnectionsNewRoute @@ -1301,6 +1309,7 @@ export interface FileRoutesByTo { '/bots/$agentId': typeof AuthedAppBotsAgentIdIndexRoute '/bots/$agentId/setup/$field': typeof AuthedAppBotsAgentIdSetupFieldRoute '/bots/$agentId/setup/key': typeof AuthedAppBotsAgentIdSetupKeyRoute + '/channel/$channelId/subtask/$toolCallId': typeof AuthedAppChannelChannelIdSubtaskToolCallIdRoute '/connections/$key/bots/$agentId': typeof AuthedAppConnectionsKeyBotsAgentIdRoute '/connections/$key/tools/$tool': typeof AuthedAppConnectionsKeyToolsToolRoute '/routines/schedules/$routineId/edit': typeof AuthedAppRoutinesSchedulesRoutineIdEditRoute @@ -1379,7 +1388,7 @@ export interface FileRoutesById { '/_authed/_app/bug-reports/$reportId': typeof AuthedAppBugReportsReportIdRoute '/_authed/_app/capabilities/memory': typeof AuthedAppCapabilitiesMemoryRoute '/_authed/_app/capabilities/skills': typeof AuthedAppCapabilitiesSkillsRoute - '/_authed/_app/channel/$channelId': typeof AuthedAppChannelChannelIdRoute + '/_authed/_app/channel/$channelId': typeof AuthedAppChannelChannelIdRouteWithChildren '/_authed/_app/channel/new': typeof AuthedAppChannelNewRoute '/_authed/_app/connections/$key': typeof AuthedAppConnectionsKeyRoute '/_authed/_app/connections/new': typeof AuthedAppConnectionsNewRoute @@ -1458,6 +1467,7 @@ export interface FileRoutesById { '/_authed/_app/bots/$agentId/': typeof AuthedAppBotsAgentIdIndexRoute '/_authed/_app/bots/$agentId/setup_/$field': typeof AuthedAppBotsAgentIdSetupFieldRoute '/_authed/_app/bots/$agentId/setup_/key': typeof AuthedAppBotsAgentIdSetupKeyRoute + '/_authed/_app/channel/$channelId/subtask/$toolCallId': typeof AuthedAppChannelChannelIdSubtaskToolCallIdRoute '/_authed/_app/connections/$key_/bots/$agentId': typeof AuthedAppConnectionsKeyBotsAgentIdRoute '/_authed/_app/connections/$key_/tools/$tool': typeof AuthedAppConnectionsKeyToolsToolRoute '/_authed/_app/routines_/schedules/$routineId_/edit': typeof AuthedAppRoutinesSchedulesRoutineIdEditRoute @@ -1613,6 +1623,7 @@ export interface FileRouteTypes { | '/bots/$agentId/' | '/bots/$agentId/setup/$field' | '/bots/$agentId/setup/key' + | '/channel/$channelId/subtask/$toolCallId' | '/connections/$key/bots/$agentId' | '/connections/$key/tools/$tool' | '/routines/schedules/$routineId/edit' @@ -1764,6 +1775,7 @@ export interface FileRouteTypes { | '/bots/$agentId' | '/bots/$agentId/setup/$field' | '/bots/$agentId/setup/key' + | '/channel/$channelId/subtask/$toolCallId' | '/connections/$key/bots/$agentId' | '/connections/$key/tools/$tool' | '/routines/schedules/$routineId/edit' @@ -1920,6 +1932,7 @@ export interface FileRouteTypes { | '/_authed/_app/bots/$agentId/' | '/_authed/_app/bots/$agentId/setup_/$field' | '/_authed/_app/bots/$agentId/setup_/key' + | '/_authed/_app/channel/$channelId/subtask/$toolCallId' | '/_authed/_app/connections/$key_/bots/$agentId' | '/_authed/_app/connections/$key_/tools/$tool' | '/_authed/_app/routines_/schedules/$routineId_/edit' @@ -2982,6 +2995,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthedAppBotsAgentIdSetupKeyRouteImport parentRoute: typeof AuthedAppRoute } + '/_authed/_app/channel/$channelId/subtask/$toolCallId': { + id: '/_authed/_app/channel/$channelId/subtask/$toolCallId' + path: '/subtask/$toolCallId' + fullPath: '/channel/$channelId/subtask/$toolCallId' + preLoaderRoute: typeof AuthedAppChannelChannelIdSubtaskToolCallIdRouteImport + parentRoute: typeof AuthedAppChannelChannelIdRoute + } '/_authed/_app/connections/$key_/bots/$agentId': { id: '/_authed/_app/connections/$key_/bots/$agentId' path: '/connections/$key/bots/$agentId' @@ -3212,6 +3232,21 @@ const AuthedSettingsRouteRouteChildren: AuthedSettingsRouteRouteChildren = { const AuthedSettingsRouteRouteWithChildren = AuthedSettingsRouteRoute._addFileChildren(AuthedSettingsRouteRouteChildren) +interface AuthedAppChannelChannelIdRouteChildren { + AuthedAppChannelChannelIdSubtaskToolCallIdRoute: typeof AuthedAppChannelChannelIdSubtaskToolCallIdRoute +} + +const AuthedAppChannelChannelIdRouteChildren: AuthedAppChannelChannelIdRouteChildren = + { + AuthedAppChannelChannelIdSubtaskToolCallIdRoute: + AuthedAppChannelChannelIdSubtaskToolCallIdRoute, + } + +const AuthedAppChannelChannelIdRouteWithChildren = + AuthedAppChannelChannelIdRoute._addFileChildren( + AuthedAppChannelChannelIdRouteChildren, + ) + interface AuthedAppRouteChildren { AuthedAppApprovalsRoute: typeof AuthedAppApprovalsRoute AuthedAppArtifactsRoute: typeof AuthedAppArtifactsRoute @@ -3232,7 +3267,7 @@ interface AuthedAppRouteChildren { AuthedAppBugReportsReportIdRoute: typeof AuthedAppBugReportsReportIdRoute AuthedAppCapabilitiesMemoryRoute: typeof AuthedAppCapabilitiesMemoryRoute AuthedAppCapabilitiesSkillsRoute: typeof AuthedAppCapabilitiesSkillsRoute - AuthedAppChannelChannelIdRoute: typeof AuthedAppChannelChannelIdRoute + AuthedAppChannelChannelIdRoute: typeof AuthedAppChannelChannelIdRouteWithChildren AuthedAppChannelNewRoute: typeof AuthedAppChannelNewRoute AuthedAppConnectionsKeyRoute: typeof AuthedAppConnectionsKeyRoute AuthedAppConnectionsNewRoute: typeof AuthedAppConnectionsNewRoute @@ -3299,7 +3334,7 @@ const AuthedAppRouteChildren: AuthedAppRouteChildren = { AuthedAppBugReportsReportIdRoute: AuthedAppBugReportsReportIdRoute, AuthedAppCapabilitiesMemoryRoute: AuthedAppCapabilitiesMemoryRoute, AuthedAppCapabilitiesSkillsRoute: AuthedAppCapabilitiesSkillsRoute, - AuthedAppChannelChannelIdRoute: AuthedAppChannelChannelIdRoute, + AuthedAppChannelChannelIdRoute: AuthedAppChannelChannelIdRouteWithChildren, AuthedAppChannelNewRoute: AuthedAppChannelNewRoute, AuthedAppConnectionsKeyRoute: AuthedAppConnectionsKeyRoute, AuthedAppConnectionsNewRoute: AuthedAppConnectionsNewRoute, diff --git a/app/src/routes/_authed/_app/channel/$channelId.subtask.$toolCallId.tsx b/app/src/routes/_authed/_app/channel/$channelId.subtask.$toolCallId.tsx new file mode 100644 index 0000000000..714210b1e9 --- /dev/null +++ b/app/src/routes/_authed/_app/channel/$channelId.subtask.$toolCallId.tsx @@ -0,0 +1,85 @@ +import { useQuery } from "@tanstack/react-query"; +import { + createFileRoute, + Navigate, + useLocation, + useRouter, +} from "@tanstack/react-router"; +import { SubtaskPage, SubtaskView } from "@/components/channels/subtask-view"; +import { agentQueryOptions } from "@/lib/agents/queries"; +import { channelQueryOptions } from "@/lib/channels/queries"; + +declare module "@tanstack/react-router" { + interface HistoryState { + /** + * Set by a subtask's row: the subtask's page was opened from its conversation, so its Back goes + * back there, and the browser's Back does the same. + */ + subtaskFromConversation?: boolean; + } +} + +/** + * One subtask, on an address of its own, in place of the conversation that started it: what the Bot + * asked it, its thinking and steps as it works, and its answer (`SubtaskView`). + * + * A child of the conversation's route, so the conversation stays drawn under it (`ChannelChat` + * keeps its run, its scroll and its message box) and Back finds it as it was. Opened from a + * subtask's row, or from "See all"; an address pasted or reloaded opens it too, once the + * conversation has drawn the call (`thread-subtasks.ts`). + */ +export const Route = createFileRoute( + "/_authed/_app/channel/$channelId/subtask/$toolCallId", +)({ + /* + * THE CONVERSATION'S ARRIVAL, SO THE CONVERSATION UNDER IT STAYS. The page is keyed by its leaf + * route (`PageArrival`), and a key of its own remounted the whole conversation under the subtask: + * its history read again, its scroll lost, and, while that read was out, the subtask it had handed + * over gone, so the page went blank (found against OpenBot Cloud). + */ + staticData: { arrival: "conversation" }, + component: SubtaskRoute, +}); + +function SubtaskRoute() { + const { channelId, toolCallId } = Route.useParams(); + const navigate = Route.useNavigate(); + const router = useRouter(); + const fromConversation = useLocation({ + select: (location) => location.state.subtaskFromConversation === true, + }); + const channel = useQuery(channelQueryOptions(channelId)); + const botId = channel.data?.agentIds[0]; + const bot = useQuery({ + ...agentQueryOptions(botId ?? ""), + enabled: botId !== undefined, + }); + // A conversation that can't be opened says so itself, under the page: it gives way to it. + if (channel.error) + return ; + return ( + + fromConversation + ? router.history.back() + : void navigate({ + params: { channelId }, + replace: true, + search: (previous) => previous, + to: "/channel/$channelId", + }) + } + > + {channel.data ? ( + + ) : null} + + ); +} diff --git a/app/src/routes/_authed/_app/channel/$channelId.tsx b/app/src/routes/_authed/_app/channel/$channelId.tsx index ac8acb3e0c..2f717b75f0 100644 --- a/app/src/routes/_authed/_app/channel/$channelId.tsx +++ b/app/src/routes/_authed/_app/channel/$channelId.tsx @@ -1,8 +1,14 @@ import { IconListDetails, IconSettings } from "@/components/icons"; import { useQuery, useQueryClient } from "@tanstack/react-query"; -import { createFileRoute, Navigate } from "@tanstack/react-router"; +import { + createFileRoute, + Navigate, + Outlet, + useMatch, + useRouter, +} from "@tanstack/react-router"; import { motion, useReducedMotion } from "motion/react"; -import { type ReactNode, useState } from "react"; +import { type ReactNode, useEffect, useMemo, useRef, useState } from "react"; import { z } from "zod"; import { AgentProfile } from "@/components/agents/agent-profile"; import { ConversationApprovals } from "@/components/approvals/inline-approval"; @@ -16,6 +22,10 @@ import { BotPausedBanner } from "@/components/bot-profile/pause-banner"; import { ChannelAvatar } from "@/components/channels/avatar"; import { ChannelChat } from "@/components/channels/channel-chat"; import { ConversationActions } from "@/components/channels/conversation-actions"; +import { + type OpenSubtask, + OpenSubtaskContext, +} from "@/components/channels/open-subtask"; import { ComputerChatControls } from "@/components/computer/computer-controls"; import { ComputerViewPanel } from "@/components/computer/computer-panel"; import { useCardsFirst } from "@/components/computer/use-cards-first"; @@ -153,6 +163,55 @@ function RouteComponent() { // An artifact opened from a card in the conversation, in the same pane. const isShowingArtifact = artifact !== undefined; + /* + * A SUBTASK OPENS IN PLACE OF THE CONVERSATION, AT AN ADDRESS OF ITS OWN + * (`$channelId.subtask.$toolCallId.tsx`), as a subagent opens in the coding agents that have them: + * its conversation, read whole, and a way back. The conversation stays drawn under it, inert, so + * Back finds it as it was left, its turn still running. + */ + const subtaskOpen = useMatch({ + from: "/_authed/_app/channel/$channelId/subtask/$toolCallId", + shouldThrow: false, + })?.params.toolCallId; + const router = useRouter(); + /* + * The subtask the person went into, whose row takes the focus back when they come back. Found by + * its address, not kept from the press: Safari doesn't focus a link it clicks, and a row in "See + * all" is gone with its dialog, while its row in the conversation is where it was. + */ + const wentInto = useRef(null); + const opens = useMemo((): OpenSubtask => { + const hrefOf = (toolCallId: string) => + router.buildLocation({ + to: "/channel/$channelId/subtask/$toolCallId", + params: { channelId, toolCallId }, + }).href; + return { + hrefOf, + open: (toolCallId) => { + wentInto.current = hrefOf(toolCallId); + void navigate({ + to: "/channel/$channelId/subtask/$toolCallId", + params: { channelId, toolCallId }, + search: (previous) => previous, + state: { subtaskFromConversation: true }, + }); + }, + }; + }, [channelId, navigate, router]); + useEffect(() => { + if (subtaskOpen !== undefined || wentInto.current === null) return; + const href = wentInto.current; + wentInto.current = null; + const row = [ + ...document.querySelectorAll( + '[data-slot="conversation"] a[href]', + ), + ].find((link) => link.getAttribute("href") === href); + // Where it was: the conversation kept its scroll, and the focus doesn't move it. + row?.focus({ preventScroll: true }); + }, [subtaskOpen]); + // Settings, watch, a task's details and an artifact share one pane; opening one clears the others' URL flags. const show = (next: "settings" | "watch" | "details" | null) => { return navigate({ @@ -231,101 +290,116 @@ function RouteComponent() { ) } > -
    +
    - {/* Keyed on the displayed name so cold channel loads animate the resolved name, not the id. */} -
    - - +
    - - - - {/* Nothing while it loads, unless the list names it; one that could not load is still a conversation. */} - {named?.name ?? (channel.error ? "Conversation" : null)} - + {/* Keyed on the displayed name so cold channel loads animate the resolved name, not the id. */} +
    + + + + + + {/* Nothing while it loads, unless the list names it; one that could not load is still a conversation. */} + {named?.name ?? (channel.error ? "Conversation" : null)} + +
    +
    + {task ? ( + + ) : null} + show(open ? "watch" : null)} + /> + +
    +
    -
    - {task ? ( - - ) : null} - show(open ? "watch" : null)} + {agentId && channel.data?.agentIds.length === 1 ? ( + + ) : null} + + - -
    +
    + {/* A subtask's page, over the conversation it was started in. */} +
    - {agentId && channel.data?.agentIds.length === 1 ? ( - - ) : null} - ); } diff --git a/app/tests/subtask-page-browser.test.tsx b/app/tests/subtask-page-browser.test.tsx new file mode 100644 index 0000000000..c152aaa968 --- /dev/null +++ b/app/tests/subtask-page-browser.test.tsx @@ -0,0 +1,466 @@ +import { afterAll, beforeAll, describe, expect } from "bun:test"; +import { existsSync, mkdirSync, readFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { readSubagentResult } from "@openbot/shared/subagent"; +import type { Server } from "bun"; +import type { Browser, BrowserType, Page } from "playwright-core"; +import { compile } from "tailwindcss"; +import { getGetBotDelegationResponseMock } from "@/lib/api/generated/agents/agents.msw"; +import { getGetBotResponseMock } from "@/lib/api/generated/bots/bots.msw"; +import { personBody } from "./accounts-api"; +import { botGrantsBody } from "./bot-grants-api"; +import { still } from "./page-still"; +import { test } from "./renderer-crash"; +import { answered } from "./subagent.fixture"; + +/** + * A subtask opened from its conversation reads on a page of its own, in a real browser, with the + * app's real conversation and subtask routes inside the app's page wrapper, against a real HTTP + * server on this machine that answers at the API's and the runtime's addresses. + * + * Clicking the subtask's row opens /channel//subtask/: what the Bot asked it, sent from the + * Bot, the turn's line with its steps, and its answer. Escape or Back goes back to the conversation, + * which was never taken down: the same page, scrolled where it was, the row that opened the subtask + * focused again. The page's address opened afresh shows the subtask too, and its Back leads to the + * conversation. + * + * FOUND AGAINST OPENBOT CLOUD, 2026-12-05: the app keys a page by its leaf route (`PageArrival`), and + * the subtask's route had a key of its own, so opening it took the whole conversation down and put + * it up again. The conversation read its history again, lost its scroll, and while that read was + * out the subtask it hands over was gone, so the page went blank. + * + * OPENBOT_APP_BROWSER=1 bun test app/tests/subtask-page-browser.test.tsx + * + * Chromium by default. OPENBOT_APP_ENGINES=chromium,webkit adds WebKit. With OPENBOT_APP_SHOTS= + * each step is saved as subtask-page----.png. + */ +const asked = process.env.OPENBOT_APP_BROWSER === "1"; +const shots = process.env.OPENBOT_APP_SHOTS; +const engines = (process.env.OPENBOT_APP_ENGINES ?? "chromium") + .split(",") + .map((engine) => engine.trim()) + .filter((engine) => engine === "chromium" || engine === "webkit") as ( + | "chromium" + | "webkit" +)[]; + +const APP = join(import.meta.dir, ".."); +const ORGANIZATION = "/api/v2/organizations/default"; +const BOT_ID = "general-assistant"; +const CONVERSATION = "subtask-conversation"; +const BOT_PATH = `${ORGANIZATION}/bots/${BOT_ID}`; +const HERE = `/channel/${CONVERSATION}`; +const SUBTASK = `${HERE}/subtask/${answered.call.id}`; +const PARENT_THREAD = answered.parentThreadId; +const result = readSubagentResult(JSON.parse(answered.result)); +const SUBAGENT_THREAD = result?.threadId ?? ""; + +const ASKED = "Which account needs attention first?"; +/** Words of the Bot's answer, under the subtask in the conversation. */ +const ANSWER = + "Birch Labs is healthy, but its tax-rate ticket has been open for nine days."; + +const BOT = { + ...getGetBotResponseMock().bot, + id: BOT_ID, + name: "General Assistant", + mine: true, + canManage: true, + systemOwned: false, + visibility: "private" as const, +}; +const DELEGATION = { ...getGetBotDelegationResponseMock(), botId: BOT_ID }; + +/** + * The conversation as the runtime keeps it: the person's ask, the Bot's words and the subtask it + * started (recorded off a real run, see the fixture), the subtask's answer, and the Bot's own. A + * long reply above it, so the conversation scrolls and its place can be kept. + */ +const STORED = [ + { id: "earlier-ask", role: "user", content: "What changed this week?" }, + { + id: "earlier-answer", + role: "assistant", + content: Array.from( + { length: 30 }, + (_, line) => `${line + 1}. An account note from this week.`, + ).join("\n"), + }, + { id: "ask", role: "user", content: ASKED }, + { + id: "starting", + role: "assistant", + content: "I'll give Birch Labs to a subtask while I check the rest.", + }, + { + id: "call-message", + role: "assistant", + content: "", + toolCalls: [ + { + id: answered.call.id, + type: "function", + function: { name: answered.call.name, arguments: answered.call.args }, + }, + ], + }, + { + id: "subtask-result", + role: "tool", + toolCallId: answered.call.id, + content: answered.result, + }, + { id: "answer", role: "assistant", content: ANSWER }, +]; + +const json = (body: unknown, status = 200) => + Response.json(body, { + status, + headers: { "cache-control": "private, no-store" }, + }); + +/** What the server answers at the API's and the runtime's addresses. */ +async function answer(request: Request): Promise { + const path = new URL(request.url).pathname; + if (path === "/api/copilotkit/info") + return json({ + version: "fixture", + agents: { [BOT_ID]: { description: "Fixture", capabilities: {} } }, + mode: "sse", + telemetryDisabled: true, + }); + // No run is going: joining the thread replays nothing. + if (path.endsWith("/connect")) + return new Response("", { + headers: { "content-type": "text/event-stream" }, + }); + if (path.startsWith(`${ORGANIZATION}/people/me/approval-modes/`)) + return json({ asksEveryStep: false }); + if (path === `${BOT_PATH}/delegation`) return json(DELEGATION); + if (path === BOT_PATH) return json({ bot: BOT }); + if (path === `${ORGANIZATION}/bots`) + return json({ bots: [BOT], nextCursor: null }); + if (path === `${BOT_PATH}/grants`) return json(botGrantsBody()); + if (path === `${BOT_PATH}/components`) + return json({ components: [], nextCursor: null }); + if (path === `${ORGANIZATION}/people/me/capabilities`) + return json({ capabilities: {}, enforced: false }); + if (path === `${ORGANIZATION}/people/me`) + return json({ + person: personBody({ + id: "atlas", + name: "Ari Atlas", + email: "ari.atlas@northwind.example", + role: "member", + }), + openbotVersion: "v1.2.11", + }); + if (path === `${ORGANIZATION}/deployment`) + return json({ + generativeUi: true, + selfHostBanner: false, + localEvaluation: false, + edition: "team", + authProviders: [], + ssoConfigured: false, + ssoRequired: false, + }); + if (/\/conversations\/[^/]+\/(activity|signal-busy|mark-read)$/.test(path)) + return new Response(null, { status: 204 }); + if (/\/conversations\/[^/]+\/voice-sessions$/.test(path)) + return json({ sessions: [], nextCursor: null }); + if (/\/conversations\/[^/]+\/refused-turns$/.test(path)) + return json({ refusedTurns: [], nextCursor: null }); + if (/\/conversations\/[^/]+\/work$/.test(path)) return json({ work: [] }); + if (path === `${ORGANIZATION}/conversations/${CONVERSATION}/join-tokens`) + return json( + { + joinToken: "jt", + expiresAt: new Date(Date.now() + 30_000).toISOString(), + threadId: PARENT_THREAD, + runId: null, + lastRun: null, + realtime: { clientUrl: "ws://127.0.0.1/client", topic: "thread" }, + }, + 201, + ); + const thread = path.match(/\/threads\/([^/]+)\/messages$/)?.[1]; + if (thread && decodeURIComponent(thread) === PARENT_THREAD) + return json({ messages: STORED }); + if (thread && decodeURIComponent(thread) === SUBAGENT_THREAD) + return json({ messages: answered.subagent }); + return undefined; +} + +async function bundle(): Promise { + const built = await Bun.build({ + entrypoints: [join(import.meta.dir, "subtask-page.fixture.tsx")], + target: "browser", + define: { "process.env.NODE_ENV": JSON.stringify("production") }, + plugins: [ + { + name: "no-marks", + setup(build) { + build.onResolve({ filter: /^@\/lib\/marks$/ }, () => ({ + path: "marks", + namespace: "no-marks", + })); + build.onLoad({ filter: /.*/, namespace: "no-marks" }, () => ({ + contents: "export const markFor = () => null;", + loader: "js", + })); + }, + }, + ], + }); + if (!built.success) throw new AggregateError(built.logs, "bundle failed"); + const script = built.outputs.find((output) => output.kind === "entry-point"); + if (!script) throw new Error("bundle has no entry point"); + return script.text(); +} + +function packageDir(name: string): string { + const dir = [ + join(APP, "node_modules", name), + join(APP, "..", "node_modules", name), + ].find(existsSync); + if (!dir) throw new Error(`no package ${name}`); + return dir; +} + +function packageStylesheet(id: string): string { + const parts = id.split("/"); + const name = id.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0]; + const dir = packageDir(name); + const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")); + const subpath = `.${id.slice(name.length)}`; + const entry = pkg.exports?.[subpath]; + const file = + typeof entry === "string" + ? entry + : (entry?.style ?? entry?.default ?? pkg.main ?? "index.css"); + return join(dir, file); +} + +/** The app's stylesheet, built by Tailwind for these classes, as the app's build does. */ +async function stylesheet(classes: string[]): Promise { + const tailwind = dirname(Bun.resolveSync("tailwindcss/package.json", APP)); + const entry = join(APP, "src", "styles.css"); + const compiler = await compile(readFileSync(entry, "utf8"), { + base: dirname(entry), + loadStylesheet: async (id, base) => { + const path = + id === "tailwindcss" + ? join(tailwind, "index.css") + : id.startsWith(".") + ? join(base, id) + : packageStylesheet(id); + return { path, base: dirname(path), content: readFileSync(path, "utf8") }; + }, + }); + return compiler.build(classes); +} + +const browsers = new Map(); +let server: Server | undefined; +let origin = ""; +let css = ""; + +beforeAll(async () => { + if (!asked) return; + const script = await bundle(); + const figtree = join(packageDir("@fontsource-variable/figtree"), "files"); + server = Bun.serve({ + hostname: "127.0.0.1", + port: 0, + idleTimeout: 0, + async fetch(request) { + const path = new URL(request.url).pathname; + if (path === "/conversation.js") + return new Response(script, { + headers: { "content-type": "text/javascript" }, + }); + if (path === "/app.css") + return new Response(css, { headers: { "content-type": "text/css" } }); + const font = join(figtree, path.split("/").pop() ?? ""); + if (path.startsWith("/files/") && existsSync(font)) + return new Response(Bun.file(font)); + if (path.startsWith("/api/")) + return (await answer(request)) ?? json({ detail: "Not found." }, 404); + const theme = new URL(request.url).searchParams.get("theme") ?? "light"; + return new Response( + `
    `, + { headers: { "content-type": "text/html" } }, + ); + }, + }); + origin = `http://127.0.0.1:${server.port}`; + const playwright = await import("playwright-core"); + for (const engine of engines) { + const type: BrowserType = playwright[engine]; + browsers.set( + engine, + // The CI job installs full Chromium without the headless shell. + await type.launch(engine === "chromium" ? { channel: "chromium" } : {}), + ); + } +}, 120_000); + +afterAll(async () => { + for (const browser of browsers.values()) await browser.close(); + await server?.stop(true); +}); + +/** + * Styled with the classes on the page now, as the app's build styles every class it has: served to + * the next page load, and laid over this one at once. + */ +async function styled(page: Page) { + const classes = await page.evaluate(() => + [...document.querySelectorAll("[class]")].flatMap((element) => [ + ...element.classList, + ]), + ); + for (const name of classes) styledClasses.add(name); + css = await stylesheet([...styledClasses]); + await page.addStyleTag({ content: css }); +} + +/** Every class a page of this test has drawn, so the stylesheet keeps the earlier pages' too. */ +const styledClasses = new Set(); + +async function shoot(page: Page, name: string) { + await styled(page); + await still(page); + if (!shots) return; + mkdirSync(shots, { recursive: true }); + await page.screenshot({ path: join(shots, `${name}.png`) }); +} + +/** Until the page's address is `path`: an address the app moved to itself, so no page loads. */ +async function at(page: Page, path: string) { + await page.waitForFunction((want) => location.pathname === want, path, { + timeout: 15_000, + }); +} + +/** The conversation's own scroller, under the subtask's page or alone. */ +const conversationScroller = (page: Page) => + page.locator( + '[data-slot="conversation"] [data-slot="message-scroller-viewport"]', + ); + +describe.skipIf(!asked)("a subtask's page", () => { + for (const engine of engines) + for (const theme of ["light", "dark"] as const) + for (const window of [ + { width: 1280, height: 800 }, + { width: 390, height: 844 }, + ]) + test(`opens from its row in place of the conversation and goes back to it as it was, in ${engine}, ${theme}, ${window.width}px`, async () => { + const browser = browsers.get(engine); + if (!browser) throw new Error(`no ${engine}`); + const page = await browser.newPage({ + viewport: window, + colorScheme: theme, + reducedMotion: "reduce", + }); + page.on("pageerror", (error) => console.error(error)); + const name = (step: string) => + `subtask-page-${step}-${engine}-${theme}-${window.width}`; + try { + await page.goto(`${origin}${HERE}?theme=${theme}`); + await page.getByText(ANSWER).waitFor({ timeout: 15_000 }); + await styled(page); + + // The finished turn's line, opened, lists the subtask: a link to its own page. + await page + .locator('[data-slot="worked-for"] summary') + .last() + .click(); + const row = page.getByRole("link", { + name: /For customer account Birch Labs/, + }); + await row.scrollIntoViewIfNeeded(); + expect(await row.getAttribute("href")).toBe(SUBTASK); + // The conversation as it is now: its scroller, marked, and where it is scrolled to. + const scroller = conversationScroller(page); + await scroller.evaluate((element) => { + (element as HTMLElement).dataset.kept = "yes"; + }); + await shoot(page, name("1-conversation")); + const scrolledTo = await scroller.evaluate( + (element) => element.scrollTop, + ); + + await row.click(); + await at(page, SUBTASK); + const subtask = page.locator('[data-slot="subtask-page"]'); + // What the Bot asked it, sent from the Bot; its steps on the turn's line; its answer. + await subtask + .getByText("Sent from General Assistant") + .waitFor({ timeout: 15_000 }); + await subtask + .getByText(/^For customer account Birch Labs/) + .waitFor(); + await subtask + .getByText("Marco Diaz", { exact: false }) + .first() + .waitFor({ timeout: 15_000 }); + await subtask + .locator('[data-slot="worked-for"] summary') + .waitFor({ timeout: 15_000 }); + expect(await subtask.getByText(/You are a subagent/).count()).toBe( + 0, + ); + // Back takes the focus: the row that opened it is behind the page now. + expect( + await page.evaluate(() => + document.activeElement?.getAttribute("aria-label"), + ), + ).toBe("Back to the conversation"); + // The conversation is still drawn under it, inert, the very same one. + expect(await page.locator('[data-kept="yes"]').count()).toBe(1); + expect( + await page + .locator('[data-slot="conversation"]') + .getAttribute("inert"), + ).not.toBeNull(); + await shoot(page, name("2-subtask")); + + // Escape goes back, to the conversation as it was left. + await page.keyboard.press("Escape"); + await at(page, HERE); + await subtask.waitFor({ state: "detached" }); + expect(await page.locator('[data-kept="yes"]').count()).toBe(1); + expect( + Math.abs( + (await scroller.evaluate((element) => element.scrollTop)) - + scrolledTo, + ), + ).toBeLessThanOrEqual(1); + expect( + await page.evaluate(() => + document.activeElement?.getAttribute("href"), + ), + ).toBe(SUBTASK); + await shoot(page, name("3-back")); + + // Opened afresh at its own address, it shows the subtask; its Back leads to the conversation. + await page.goto(`${origin}${SUBTASK}?theme=${theme}`); + await page + .locator('[data-slot="subtask-page"]') + .getByText("Marco Diaz", { exact: false }) + .first() + .waitFor({ timeout: 20_000 }); + await shoot(page, name("4-opened-afresh")); + await page + .getByRole("button", { name: "Back to the conversation" }) + .click(); + await at(page, HERE); + await page.getByText(ANSWER).waitFor({ timeout: 15_000 }); + } finally { + await page.close(); + } + }, 120_000); +}); diff --git a/app/tests/subtask-page.fixture.tsx b/app/tests/subtask-page.fixture.tsx new file mode 100644 index 0000000000..fec107ffa9 --- /dev/null +++ b/app/tests/subtask-page.fixture.tsx @@ -0,0 +1,149 @@ +import { CopilotKitProvider } from "@copilotkit/react-core/v2"; +import { type InfiniteData, QueryClientProvider } from "@tanstack/react-query"; +import { + createBrowserHistory, + createRootRoute, + createRoute, + createRouter, + Outlet, + RouterProvider, +} from "@tanstack/react-router"; +import { createRoot } from "react-dom/client"; +import { PageArrival } from "@/components/layout/page-arrival"; +import { SidebarShell } from "@/components/layout/sidebar-shell"; +import { SidebarInset } from "@/components/ui/sidebar"; +import { TooltipProvider } from "@/components/ui/tooltip"; +import { + type AuthenticatedUser, + currentUserQueryOptions, +} from "@/lib/auth/queries"; +import { + type AgentChannel, + type ChannelPage, + channelKeys, + channelQueryOptions, +} from "@/lib/channels/queries"; +import { ActiveBotProvider } from "@/lib/copilot/active-bot"; +import { BotOffers } from "@/lib/copilot/bot-offer"; +import { setCurrentOrganization } from "@/lib/organizations/current"; +import { queryClient } from "@/query-client"; +import { Route as ChannelRoute } from "@/routes/_authed/_app/channel/$channelId"; +import { Route as SubtaskRoute } from "@/routes/_authed/_app/channel/$channelId.subtask.$toolCallId"; +import { answered } from "./subagent.fixture"; + +/** + * A conversation whose Bot gave part of the work to a subtask, for subtask-page-browser.test.tsx to + * bundle and load in a browser: the app's real conversation route and the subtask's route under it, + * wired as the generated route tree wires them, inside the app's frame and its page wrapper + * (`PageArrival`), which keys the page by its leaf route. What the server and the runtime answer + * comes from the test's server. + */ +setCurrentOrganization("default"); + +const CONVERSATION: AgentChannel = { + id: "subtask-conversation", + name: "General Assistant", + agentIds: ["general-assistant"], + threadId: answered.parentThreadId, + active: true, + lastMessageAt: "2026-12-05T10:36:27.000Z", +}; + +// Signed in, as every page of the app is by the time a conversation opens. +const ARI: AuthenticatedUser = { + id: "atlas", + email: "ari.atlas@northwind.example", + name: "Ari Atlas", + role: "member", + onboarding: null, + openbotVersion: "v1.2.11", + providers: [], +}; +queryClient.setQueryData(currentUserQueryOptions().queryKey, ARI); +queryClient.setQueryDefaults(channelKeys.all, { staleTime: Infinity }); +queryClient.setQueryData( + channelQueryOptions(CONVERSATION.id).queryKey, + CONVERSATION, +); +queryClient.setQueryData>(channelKeys.list(), { + pages: [ + { + channels: [ + { + ...CONVERSATION, + summary: "Accounts needing attention", + lastMessage: null, + lastMessageAgentId: null, + createdAt: "2026-12-05T10:36:27.000Z", + pinned: false, + lastReadAt: "2026-12-05T10:36:27.000Z", + }, + ], + nextCursor: null, + }, + ], + pageParams: [""], +}); + +/* + * TanStack's generated tree wires a file route with update({ id, path, getParentRoute }) + * (app/src/routeTree.gen.ts); the update type leaves those fields out, hence the casts. + */ +const rootRoute = createRootRoute({ component: Outlet }); +const authedRoute = createRoute({ + id: "/_authed", + getParentRoute: () => rootRoute, + component: Outlet, +}); +const appRoute = createRoute({ + id: "/_app", + getParentRoute: () => authedRoute, + component: () => ( + + + + + + + + + + + ), +}); +const conversationRoute = ChannelRoute.update({ + id: "/channel/$channelId", + path: "/channel/$channelId", + getParentRoute: () => appRoute, +} as never); +const subtaskRoute = SubtaskRoute.update({ + id: "/subtask/$toolCallId", + path: "/subtask/$toolCallId", + getParentRoute: () => conversationRoute, +} as never); + +const router = createRouter({ + history: createBrowserHistory(), + context: { queryClient }, + routeTree: rootRoute.addChildren([ + authedRoute.addChildren([ + appRoute.addChildren([ + (conversationRoute as typeof ChannelRoute).addChildren([ + subtaskRoute as typeof SubtaskRoute, + ] as never) as never, + ]), + ]), + ]), +}); + +const root = document.getElementById("root"); +if (root) + createRoot(root).render( + + + + + + + , + ); diff --git a/app/tests/subtask-view.test.tsx b/app/tests/subtask-view.test.tsx new file mode 100644 index 0000000000..31673cac2a --- /dev/null +++ b/app/tests/subtask-view.test.tsx @@ -0,0 +1,314 @@ +import { + afterAll, + afterEach, + beforeAll, + expect, + setSystemTime, + test, +} from "bun:test"; +import type { Message } from "@ag-ui/core"; +import { + CopilotChatConfigurationProvider, + CopilotKitProvider, +} from "@copilotkit/react-core/v2"; +import { GlobalRegistrator } from "@happy-dom/global-registrator"; +import { subagentThreadId } from "@openbot/shared/subagent"; +import { QueryClientProvider } from "@tanstack/react-query"; +import { + cleanup, + fireEvent, + render, + waitFor, + within, +} from "@testing-library/react"; +import type { ReactElement } from "react"; +import { ChatTranscript } from "@/components/channels/chat-transcript"; +import { + type OpenSubtask, + OpenSubtaskContext, +} from "@/components/channels/open-subtask"; +import { SubtaskView } from "@/components/channels/subtask-view"; +import { forgetOpenedLines } from "@/components/channels/tool-line"; +import { SUBAGENT_POLL_MS } from "@/lib/subagents/queries"; +import { queryClient } from "@/query-client"; +import { settleReactWork } from "./settle-react-work"; +import { answered, handedBack, type RecordedSubtask } from "./subagent.fixture"; + +/** + * A subtask opened in a view of its own, read as a conversation: what the Bot asked it, its steps on + * the same grouped line the conversation draws while it works, and its answer once it is done. Drawn + * by the real transcript, from a call, a result and a subagent thread recorded off a real run (see + * the fixture), beside the conversation that started it, as the subtask's page draws it over that + * conversation. The subagent's thread is read through the same route a conversation's history is, + * answered here the way the server answered it. + */ + +const originalFetch = globalThis.fetch; +/** The subagent threads the history route serves, by id. */ +const served = new Map(); + +beforeAll(() => { + GlobalRegistrator.register({ url: "http://localhost/" }); + globalThis.fetch = Object.assign( + async (input: RequestInfo | URL) => { + const path = new URL(String(input), "http://localhost/").pathname; + const id = /^\/api\/copilotkit\/threads\/([^/]+)\/messages$/.exec( + path, + )?.[1]; + const messages = id ? served.get(decodeURIComponent(id)) : undefined; + return messages + ? Response.json({ messages }) + : Response.json({ error: "not served" }, { status: 404 }); + }, + { preconnect: originalFetch.preconnect }, + ); +}); + +afterEach(() => { + cleanup(); + forgetOpenedLines(); + queryClient.clear(); + served.clear(); +}); + +afterAll(async () => { + await settleReactWork(); + globalThis.fetch = originalFetch; + GlobalRegistrator.unregister(); +}); + +const BOT = "General Assistant"; + +/** The person's ask, the Bot's calls, and their results once they have them. */ +function turn( + subtasks: readonly RecordedSubtask[], + settled: boolean, +): Message[] { + return [ + { + id: "ask", + role: "user", + content: "Which account needs attention first?", + }, + { + id: "call-message", + role: "assistant", + content: "", + toolCalls: subtasks.map((subtask) => ({ + id: subtask.call.id, + type: "function" as const, + function: { name: subtask.call.name, arguments: subtask.call.args }, + })), + }, + ...(settled + ? subtasks.map((subtask) => ({ + id: `result-${subtask.call.id}`, + role: "tool" as const, + toolCallId: subtask.call.id, + content: subtask.result, + })) + : []), + ]; +} + +function wrap(parentThreadId: string, children: ReactElement) { + return ( + + + + {children} + + + + ); +} + +/** The conversation, and the subtask's view beside it, as its page draws it over the conversation. */ +function conversationAndView( + subtask: RecordedSubtask, + { settled, busy }: { settled: boolean; busy: boolean }, +) { + return wrap( + subtask.parentThreadId, + <> + + + , + ); +} + +function theView(container: HTMLElement) { + const view = container.querySelector( + '[data-slot="subtask-view"]', + ); + if (!view) throw new Error("No subtask view"); + return view; +} + +/** + * The subagent's thread read again. In the browser it comes every few seconds on its own; under this + * test's DOM the query library keeps no timers, so it is asked for here, as its timer would, once a + * poll's interval has gone by. + */ +async function nextPoll() { + setSystemTime(new Date(Date.now() + SUBAGENT_POLL_MS)); + await queryClient.refetchQueries({ queryKey: ["subagents"] }); + setSystemTime(); +} + +test("a subtask's view reads it as a conversation: what the Bot asked it, its steps on the turn's line as it works, its answer once done", async () => { + const thread = await subagentThreadId( + answered.parentThreadId, + answered.call.id, + ); + // It has asked for its first two steps, and neither has answered yet. + served.set(thread, answered.subagent.slice(0, 2)); + const page = render( + conversationAndView(answered, { settled: false, busy: true }), + ); + + // What it was asked: the task the Bot wrote, sent from the Bot, not the server's framing of it. + const view = () => within(theView(page.container)); + expect(await view().findByText(`Sent from ${BOT}`)).toBeTruthy(); + expect(view().getByText(/^For customer account Birch Labs/)).toBeTruthy(); + expect(view().queryByText(/You are a subagent/)).toBeNull(); + + // While it works, its steps are on the turn's one line, running, as a conversation's are. + await waitFor(() => + expect( + theView(page.container).querySelector( + '[data-slot="worked-for"][data-running]', + ), + ).not.toBeNull(), + ); + expect( + theView(page.container) + .querySelector('[role="log"]') + ?.getAttribute("aria-busy"), + ).toBe("true"); + + // It finishes: its steps answer, it writes its answer, and the conversation's call has its result. + served.set(thread, answered.subagent); + await nextPoll(); + page.rerender(conversationAndView(answered, { settled: true, busy: false })); + + // Its answer stands under the turn's line, which says what it did, and nothing is working. + expect(await view().findByText("Marco Diaz", { exact: false })).toBeTruthy(); + await waitFor(() => + expect( + theView(page.container).querySelector( + '[data-slot="worked-for"]:not([data-running])', + ), + ).not.toBeNull(), + ); + expect( + theView(page.container) + .querySelector('[role="log"]') + ?.getAttribute("aria-busy"), + ).toBe("false"); + // The task stays where it started, sent from the Bot. + expect(view().getByText(`Sent from ${BOT}`)).toBeTruthy(); +}, 30_000); + +test("a subtask that stopped before a step needing approval says so in its view, and asks nothing", async () => { + served.set( + await subagentThreadId(handedBack.parentThreadId, handedBack.call.id), + handedBack.subagent, + ); + const page = render( + conversationAndView(handedBack, { settled: true, busy: false }), + ); + const notice = within( + await within(theView(page.container)).findByRole("region", { + name: "Handed back", + }), + ); + expect(notice.getByText("List open tickets on accounts")).toBeTruthy(); + expect( + within(theView(page.container)).queryByRole("button", { name: /Approve/ }), + ).toBeNull(); +}); + +test("a subtask's thread that can't be read still shows what it was asked and its answer, from the call", async () => { + // Nothing served for its thread: the read fails, and the call's result still holds the answer. + const page = render( + conversationAndView(answered, { settled: true, busy: false }), + ); + const view = within(await waitFor(() => theView(page.container))); + expect(await view.findByText(`Sent from ${BOT}`)).toBeTruthy(); + expect(await view.findByText("Marco Diaz", { exact: false })).toBeTruthy(); +}); + +/** Four subtasks the Bot started together, the first three of them listed and the rest behind See all. */ +const four: RecordedSubtask[] = [ + "Birch Labs", + "Acme Robotics", + "Northwind", + "Globex", +].map((account, index) => ({ + ...answered, + call: { + ...answered.call, + id: `call-${index}`, + args: JSON.stringify({ task: `Summarise ${account}'s open tickets.` }), + }, +})); + +test("where its view can open, a subtask's row is a link to it, and so is each row in See all, which makes way", async () => { + const opened: string[] = []; + const opens: OpenSubtask = { + hrefOf: (toolCallId) => `/channel/conversation/subtask/${toolCallId}`, + open: (toolCallId) => opened.push(toolCallId), + }; + const page = render( + wrap( + answered.parentThreadId, + + + , + ), + ); + + // A row is a link to the subtask's own address, and opens nothing in place. + const subtasks = await page.findByRole("list", { name: "Subtasks" }); + const first = within(subtasks).getByRole("link", { + name: /Summarise Birch Labs's open tickets/, + }); + expect(first.getAttribute("href")).toBe( + "/channel/conversation/subtask/call-0", + ); + expect(subtasks.querySelector("details")).toBeNull(); + fireEvent.click(first); + expect(opened).toEqual(["call-0"]); + + // A press that asks for a new tab is the browser's, as on any link. + fireEvent.click(first, { metaKey: true }); + expect(opened).toEqual(["call-0"]); + + // See all lists every one, each a link; the one opened from there puts the list away. + fireEvent.click(page.getByRole("button", { name: /See all/ })); + const all = await page.findByRole("dialog"); + fireEvent.click( + within(all).getByRole("link", { name: /Summarise Globex's open tickets/ }), + ); + expect(opened).toEqual(["call-0", "call-3"]); + await waitFor(() => expect(page.queryByRole("dialog")).toBeNull()); +});