diff --git a/app/src/components/approvals/bot-approval-notice.tsx b/app/src/components/approvals/bot-approval-notice.tsx new file mode 100644 index 0000000000..3a9dd675c2 --- /dev/null +++ b/app/src/components/approvals/bot-approval-notice.tsx @@ -0,0 +1,166 @@ +import type { Message } from "@ag-ui/core"; +import { useEffect, useState } from "react"; +import { Button } from "@/components/ui/button"; +import { + answersFor, + asksForApproval, + botRaisedInterrupts, + expired, + type HeldInterrupt, + type InterruptAnswer, + interruptedCall, +} from "@/lib/copilot/bot-raised-interrupts"; +import { type Failure, failureOf, failureSaid } from "@/lib/load-failure"; + +type InterruptedAgent = { + pendingInterrupts: HeldInterrupt[]; + messages: readonly Message[]; + isRunning: boolean; + subscribe(subscriber: { + onRunInitialized?: () => void; + onRunFinalized?: () => void; + onRunFailed?: () => void; + }): { unsubscribe(): void }; +}; + +/** + * What a Bot stopped its own run to ask, with the person's answer to it. + * + * Only for a wait the Bot raised itself; OpenBot's own approvals have their cards + * (`bot-raised-interrupts.ts` says which is which). The answer is sent as the next run's `resume`, + * which is how AG-UI carries one. + */ +export function BotApprovalNotice({ + agent, + botName, + ready, + run, +}: { + agent: InterruptedAgent; + botName: string; + ready: boolean; + run: (resume: InterruptAnswer[]) => Promise; +}) { + const [, redraw] = useState(0); + const [busy, setBusy] = useState(false); + const [problem, setProblem] = useState(null); + // The agent's interrupts change when a run ends or starts, which is not a render of its own. + useEffect(() => { + const again = () => redraw((count) => count + 1); + const watching = agent.subscribe({ + onRunInitialized: again, + onRunFinalized: again, + onRunFailed: again, + }); + return () => watching.unsubscribe(); + }, [agent]); + + // Set when a click found the Bot no longer takes the decision, so the card says so from then on. + const [lapsed, setLapsed] = useState(false); + + const waiting = ready ? botRaisedInterrupts(agent.pendingInterrupts) : []; + if (waiting.length === 0 || agent.isRunning) return null; + const approvals = waiting.filter(asksForApproval); + /* + * A decision the Bot still takes. One whose time is over can only be let go: the AG-UI client + * refuses an answer to it before anything is sent, so Allow did nothing and the conversation was + * stuck. Read when the card draws and again at the click, which may come much later. + */ + const open = lapsed ? [] : approvals.filter((asked) => !expired(asked)); + + const answer = async (approved: boolean) => { + if (busy) return; + const now = new Date(); + // Allowing what the Bot no longer waits on would be sent as letting it go: said first instead. + if (approved && approvals.some((asked) => expired(asked, now))) { + setLapsed(true); + return; + } + setBusy(true); + setProblem(null); + try { + await run(answersFor(agent.pendingInterrupts, approved, now)); + } catch (error) { + setProblem(failureOf(error, "Couldn't send your answer. Try again.")); + } finally { + setBusy(false); + } + }; + + return ( +
+ {open.length > 0 ? ( +

{botName} asks before it goes on

+ ) : approvals.length > 0 ? ( +

+ {botName} waited too long for this answer and no longer takes it +

+ ) : ( +

+ {botName} is waiting for an answer this app can't give +

+ )} + {waiting.map((interrupt) => { + const call = interruptedCall(interrupt, agent.messages); + // What the Bot asks, in its own words. Not an error's: nothing here failed. + const asked = interrupt.message; + return ( +
+ {/* + * The call itself when the conversation has it: its name and what it was given, as the + * person would check them. A harness words its question for a terminal (`Approve + * "shell"? Input: {...}`), so its words are only for a wait that names no call. + */} + {call ? ( + <> +

+ Use {call.name} +

+

+ {call.args} +

+ + ) : asked ? ( +

{asked}

+ ) : null} +
+ ); + })} + {problem ? ( +

+ {failureSaid(problem)} +

+ ) : null} +
+ {open.length > 0 ? ( + <> + + + + ) : ( + + )} +
+
+ ); +} diff --git a/app/src/components/channels/channel-chat.tsx b/app/src/components/channels/channel-chat.tsx index 7430124e69..e00a97d8eb 100644 --- a/app/src/components/channels/channel-chat.tsx +++ b/app/src/components/channels/channel-chat.tsx @@ -15,6 +15,7 @@ import { useSyncExternalStore, } from "react"; import { BotOrb } from "@/components/agents/bot-orb"; +import { BotApprovalNotice } from "@/components/approvals/bot-approval-notice"; import { ConversationAllowances } from "@/components/approvals/conversation-allowances"; import { ANSWER_PROMPT, @@ -103,6 +104,7 @@ import { whileObserved, } from "@/lib/copilot/approval-context"; import { offerItsOwnTools } from "@/lib/copilot/bot-offer"; +import type { InterruptAnswer } from "@/lib/copilot/bot-raised-interrupts"; import { isBrokenStream, STREAM_BROKE } from "@/lib/copilot/broken-stream"; import { endsOnStep, @@ -282,6 +284,8 @@ const STOP_FAILED = "Couldn't stop the Bot. Try again."; /** What a turn that never left the browser says, with the person's words back in the box. */ const NOT_SENT = "Your message wasn't sent. Try again."; +/** An answer to a Bot's own wait that never left this browser (`answerBotWait`). */ +const ANSWER_NOT_SENT = "Your answer wasn't sent. Try again."; type ChannelActivitySignature = { agentId: string; @@ -2783,14 +2787,7 @@ export function ChannelChat({ throw new StillWorkingError(); } - const turn = {}; - turnTokens.current.add(turn); - turnsRef.current += 1; - setTurnsInFlight(turnsRef.current); - if (turnsRef.current === 1) { - void setChannelBusy({ channelId: channel.id, busy: true }); - } - try { + return duringTurn(async () => { const reply = await deliver(trimmed, attachments, sent); /* * The person left while this turn was running (holding control of the Bot's browser, say) and the turn went on @@ -2807,6 +2804,23 @@ export function ChannelChat({ reportRef.current(reply || (drawn?.text ?? ""), runtimeAgentId); } return reply; + }); + }; + + /** + * Count `work` as a turn of this conversation for as long as it goes: what `turnsInFlight` says + * above, the roster's working indicator, and the chat open next if this one closes meanwhile. + */ + const duringTurn = async (work: () => Promise): Promise => { + const turn = {}; + turnTokens.current.add(turn); + turnsRef.current += 1; + setTurnsInFlight(turnsRef.current); + if (turnsRef.current === 1) { + void setChannelBusy({ channelId: channel.id, busy: true }); + } + try { + return await work(); } finally { turnsRef.current -= 1; setTurnsInFlight(turnsRef.current); @@ -2829,6 +2843,58 @@ export function ChannelChat({ } }; + /** + * Send the person's answer to a wait the Bot raised itself, as the `resume` of a run. + * + * A TURN LIKE ANY OTHER, WITHOUT A MESSAGE. It is counted and watched as `say`'s are, so what the + * Bot goes on to say reaches the roster and a run that fails is said under the transcript. Sent + * bare, neither happened: `copilotkit.runAgent` resolves on a failed run (`turnFailure`), so a + * gateway's 503 looked like an answer that went, with the card back and nothing said. + * + * THROWS ONLY WHEN THE RUN NEVER LEFT THIS BROWSER, so the card says so beside its buttons: a run + * the agent refused on its own checks reaches no subscriber, and nothing else would say it. One + * that failed on the way is already said under the transcript, by the same `fail` as any turn. + */ + const answerBotWait = (resume: InterruptAnswer[]) => + duringTurn(async () => { + const target = agentRef.current; + setRunError(null); + turnFailure.current = null; + turnRefused.current = false; + stoppedHere.current = false; + reportedReply.current = null; + assistantMessagesBeforeRun.current = new Set( + target.messages + .filter((message) => message.role === "assistant") + .map((message) => message.id), + ); + /* + * A wait OpenBot holds beside the Bot's is the server's to carry on, decided on its own card. + * The agent refuses a run that leaves any wait it holds unaddressed, so with both replayed + * Allow sent nothing at all. Let go of here as before any message; see the module. + */ + releaseServerOwnedInterrupts(target); + let started = false; + const watching = target.subscribe({ + onRunInitialized: () => { + started = true; + }, + }); + awaitingReply.current = true; + setRunsInFlight((count) => count + 1); + try { + await whileObserved(target, () => + copilotkit.runAgent({ agent: target, resume }), + ); + } finally { + watching.unsubscribe(); + awaitingReply.current = false; + setRunsInFlight((count) => count - 1); + } + if (!started && turnFailure.current === null) + throw new Error(ANSWER_NOT_SENT); + }); + useEffect(() => { /* * `laterRun` is a RUN_ERROR from a run of a turn still going here after its first run has @@ -3359,6 +3425,13 @@ export function ChannelChat({ {channel.active ? ( ) : null} + {/* What the Bot stopped its own run to ask; the answer is the next run's `resume`. */} + ; +}; + +/** One answer to an interrupt, as a run's `resume` carries it. */ +export type InterruptAnswer = { + interruptId: string; + status: "resolved" | "cancelled"; + payload?: unknown; +}; + +/** + * The interrupts a Bot raised itself, which only this app can answer. + * + * MOST WAITS ARE THE SERVER'S. An approval, a question or a sign-in OpenBot asks for is answered on + * its own card and carried on by the server (`server-owned-interrupts.ts`). A Bot connected by its + * address can also stop a run on its own: a harness that asks before it runs one of its own tools, a + * graph's `interrupt()`. The server passes that through untouched, and passes its answer back + * (`endpointResume` in the server's copilot.ts), so the run waits on whoever holds the conversation. + * Left unanswered, the conversation is stuck: the agent refuses every later run ("pending + * interrupt(s) not addressed by resume"). + */ +export function botRaisedInterrupts( + pending: readonly T[], +): T[] { + return pending.filter((interrupt) => !serverOwnedInterrupt(interrupt)); +} + +/** + * Whether an interrupt asks yes or no: its answer is an object whose one required field is the + * boolean `approved`. That is what an approval asked by a Bot's own harness looks like on AG-UI; + * anything else has an answer this app cannot draw a form for, and can only be let go. + */ +export function asksForApproval(interrupt: HeldInterrupt): boolean { + const schema = interrupt.responseSchema; + if (!schema || typeof schema !== "object") return false; + const { properties, required } = schema as { + properties?: Record; + required?: unknown; + }; + return ( + properties?.approved?.type === "boolean" && + Array.isArray(required) && + required.length === 1 && + required[0] === "approved" + ); +} + +/** The call an interrupt is about, from the conversation: its name and its arguments as sent. */ +export function interruptedCall( + interrupt: HeldInterrupt, + messages: readonly Message[], +): { name: string; args: string } | undefined { + if (!interrupt.toolCallId) return undefined; + for (const message of messages) { + if (message.role !== "assistant") continue; + const call = message.toolCalls?.find( + (candidate) => candidate.id === interrupt.toolCallId, + ); + if (call) + return { name: call.function.name, args: call.function.arguments }; + } + return undefined; +} + +/** + * Whether an interrupt's time to be answered is over. The AG-UI client refuses a decision on one + * before anything is sent ("expired at ... Cancel it to continue the thread"), so it can only be + * let go. + */ +export function expired(interrupt: HeldInterrupt, now = new Date()): boolean { + if (interrupt.expiresAt === undefined) return false; + return new Date(interrupt.expiresAt) <= now; +} + +/** + * The `resume` that answers the interrupts the Bot raised, given the person's decision on them. A + * run must address all of them at once, so one decision covers each approval the Bot asked for in + * that step. An interrupt that is not a yes or no, or whose time is over, is cancelled, which lets + * the conversation go on. + * + * NOT THE SERVER'S. A wait OpenBot holds beside these is decided on its own card and carried on by + * the server, and is let go of on the agent before this is sent (`releaseServerOwnedInterrupts`), as + * before any message: the agent refuses a run that leaves one it still holds unaddressed. + */ +export function answersFor( + pending: readonly HeldInterrupt[], + approved: boolean, + now = new Date(), +): InterruptAnswer[] { + return botRaisedInterrupts(pending).map((interrupt) => + asksForApproval(interrupt) && !expired(interrupt, now) + ? { interruptId: interrupt.id, status: "resolved", payload: { approved } } + : { interruptId: interrupt.id, status: "cancelled" }, + ); +} diff --git a/app/src/lib/deployment/queries.ts b/app/src/lib/deployment/queries.ts index 762429302d..d8ec871821 100644 --- a/app/src/lib/deployment/queries.ts +++ b/app/src/lib/deployment/queries.ts @@ -158,6 +158,31 @@ function showsOpenBotOnThisComputer(): Promise { * told "not found" and drew the router's error in its place. Told "not found" in the organization * it knows (signed out since, or no longer in it), it is asked the way it is before signing in. */ +/** + * `deployment` at `default`, asked as nobody: without the page's cookies. + * + * ONE OPENBOT REFUSES NOBODY: a single-user one in a container, which answers only a browser that + * came in through its entry address, and knows that browser by a cookie (the server's + * request-trust.ts). Asked without cookies it said "permission denied", on every page, to the very + * browser it had let in: no deployment facts, so no release check and no attachment limits, and a + * failed request in the console each time. That refusal is about the browser, not about a person, + * so the page asks once more with its cookies. Any other OpenBot answers the first ask. + */ +async function asNobody(options: { + signal?: AbortSignal; + fallback: string; +}): Promise { + try { + return await getDeployment(DEPLOYMENT_ORGANIZATION, { + ...options, + credentials: "omit", + }); + } catch (error) { + if (!(error instanceof ClientError) || error.status !== 403) throw error; + return getDeployment(DEPLOYMENT_ORGANIZATION, options); + } +} + export async function readDeployment(options: { signal?: AbortSignal; fallback: string; @@ -169,17 +194,10 @@ export async function readDeployment(options: { } catch (error) { if (!(error instanceof ClientError) || error.status !== 404) throw error; if (await showsOpenBotOnThisComputer()) throw error; - return getDeployment(DEPLOYMENT_ORGANIZATION, { - ...options, - credentials: "omit", - }); + return asNobody(options); } } - if (!(await showsOpenBotOnThisComputer())) - return getDeployment(DEPLOYMENT_ORGANIZATION, { - ...options, - credentials: "omit", - }); + if (!(await showsOpenBotOnThisComputer())) return asNobody(options); try { return await getDeployment(DEPLOYMENT_ORGANIZATION, options); } catch (error) { @@ -188,11 +206,7 @@ export async function readDeployment(options: { .organizations[0]; // In no organization (removed from the last one): what this OpenBot offers anybody, asked as nobody, so the // sign-in screen and the page for somebody in no organization can still offer a way back in. - if (!own) - return getDeployment(DEPLOYMENT_ORGANIZATION, { - ...options, - credentials: "omit", - }); + if (!own) return asNobody(options); return getDeployment(own.id, options); } } diff --git a/app/tests/bot-approval-resume.test.tsx b/app/tests/bot-approval-resume.test.tsx new file mode 100644 index 0000000000..46bfb3ce4d --- /dev/null +++ b/app/tests/bot-approval-resume.test.tsx @@ -0,0 +1,339 @@ +import { afterAll, afterEach, beforeAll, expect, test } from "bun:test"; +import type { Message, RunAgentInput } from "@ag-ui/core"; +import { RunAgentInputSchema } from "@ag-ui/core/schemas"; +import { CopilotKitProvider } from "@copilotkit/react-core/v2"; +import { GlobalRegistrator } from "@happy-dom/global-registrator"; +import { OPENBOT_WAITING_METADATA } from "@openbot/shared/waiting"; +import { QueryClientProvider } from "@tanstack/react-query"; +import { cleanup, render, waitFor } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { z } from "zod"; +import { ChannelChat } from "@/components/channels/channel-chat"; +import { type AgentChannel, channelKeys } from "@/lib/channels/queries"; +import { queryClient } from "@/query-client"; +import { MY_CAPABILITIES_PATH } from "./admin-settings-api"; +import { botGrantsPath, botGrantsResponse } from "./bot-grants-api"; +import { answerBotsList, botPath } from "./bots-api"; +import { settleReactWork } from "./settle-react-work"; +import { botComponentsPath, botComponentsResponse } from "./components-api"; + +/** + * The card for a wait a Bot raised itself (a harness asking before it runs one of its own tools), + * answered by the person in the browser. + * + * Found in review, each with the conversation left stuck: the Bot's wait replayed beside one of + * OpenBot's own, where Allow sent nothing; a wait whose time was over, which neither button could + * answer; and an answer whose run failed, which looked like one that went. + * + * The real provider, ChannelChat and the real AG-UI agent; only the HTTP boundary is synthetic. + */ + +const NativeResponse = globalThis.Response; +const channel: AgentChannel = { + id: "waiting-channel", + name: "Reply to Sam about the spec", + agentIds: ["waiting-bot"], + threadId: "waiting-thread", + active: true, + lastMessageAt: "2026-10-31T05:51:00.000Z", +}; +const ask = { + id: "ask", + role: "user", + content: "Reply to Sam about the spec", +} satisfies Message; +const call = { + id: "asked-to-send", + role: "assistant", + content: "", + toolCalls: [ + { + id: "call-shell", + type: "function", + function: { name: "shell", arguments: '{"command":"ls"}' }, + }, + { + id: "call-send", + type: "function", + function: { + name: "mcp__notion__notion-create-comment", + arguments: '{"text":"Friday works."}', + }, + }, + ], +} satisfies Message; + +/** What the replayed run ended on. */ +let interrupts: Record[]; +/** What the runtime answers a run with, when it is not the run's events. */ +let runStatus: number | null; +let runRequests: RunAgentInput[] = []; +let runEvents: (input: RunAgentInput) => unknown[]; +const ActivitySchema = z.object({ + botId: z.string().nullable(), + text: z.string(), +}); +let activity: z.infer[] = []; +/** Each time the conversation said a turn started or ended, in order. */ +let busy: boolean[] = []; +let originalFetch: typeof fetch; + +function sse(events: unknown[]) { + return new NativeResponse( + events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join(""), + { headers: { "content-type": "text/event-stream" } }, + ); +} + +beforeAll(() => { + GlobalRegistrator.register(); + originalFetch = globalThis.fetch; + globalThis.fetch = Object.assign( + async (input: Parameters[0], init?: RequestInit) => { + const url = new URL( + typeof input === "string" + ? input + : input instanceof URL + ? input.href + : input.url, + "http://localhost", + ); + const bots = answerBotsList(url, init, { visible: [] }); + if (bots) return bots; + if (url.pathname === botGrantsPath("waiting-bot")) + return botGrantsResponse(); + // What the Bot's runs are offered is read from these, as the server answers them. + if (url.pathname === botPath("waiting-bot")) + return NativeResponse.json({ + bot: { id: "waiting-bot", visibility: "public", canManage: true }, + }); + if (url.pathname === botComponentsPath("waiting-bot")) + return botComponentsResponse(); + if (url.pathname === MY_CAPABILITIES_PATH) + return NativeResponse.json({ capabilities: {}, enforced: false }); + if (url.pathname.endsWith("/info")) + return NativeResponse.json({ + version: "fixture", + agents: { + "waiting-bot": { description: "Fixture", capabilities: {} }, + }, + mode: "sse", + telemetryDisabled: true, + }); + // The conversation's last run, replayed: it asked to send and stopped for the person. + if (url.pathname.endsWith("/connect")) + return sse([ + { type: "RUN_STARTED", threadId: channel.threadId, runId: "task" }, + { type: "MESSAGES_SNAPSHOT", messages: [ask, call] }, + { + type: "RUN_FINISHED", + threadId: channel.threadId, + runId: "task", + outcome: { type: "interrupt", interrupts }, + }, + ]); + if (url.pathname.endsWith("/run")) { + const request = + input instanceof Request ? input : new Request(url, init); + const body = RunAgentInputSchema.parse(await request.json()); + runRequests.push(body); + if (runStatus !== null) + return new NativeResponse("unavailable", { status: runStatus }); + return sse(runEvents(body)); + } + if ( + /^\/api\/v2\/organizations\/default\/conversations\/[^/]+\/activity$/.test( + url.pathname, + ) + ) { + const request = + input instanceof Request ? input : new Request(url, init); + activity.push(ActivitySchema.parse(await request.json())); + return new NativeResponse(null, { status: 204 }); + } + if ( + /^\/api\/v2\/organizations\/default\/conversations\/[^/]+\/signal-busy$/.test( + url.pathname, + ) + ) { + const request = + input instanceof Request ? input : new Request(url, init); + busy.push( + z.object({ busy: z.boolean() }).parse(await request.json()).busy, + ); + return new NativeResponse(null, { status: 204 }); + } + if ( + /^\/api\/v2\/organizations\/default\/conversations\/[^/]+\/voice-sessions$/.test( + url.pathname, + ) + ) + return NativeResponse.json({ sessions: [], nextCursor: null }); + if (/\/threads\/[^/]+\/messages$/.test(url.pathname)) + return NativeResponse.json({ messages: [ask, call] }); + throw new Error(`Unexpected fixture request: ${url.pathname}`); + }, + { + preconnect() { + throw new Error("Unexpected fixture preconnect"); + }, + }, + ); +}); +afterEach(() => { + cleanup(); + queryClient.clear(); +}); +afterAll(async () => { + await settleReactWork(); + globalThis.fetch = originalFetch; + GlobalRegistrator.unregister(); +}); + +function mounting() { + runRequests = []; + runStatus = null; + activity = []; + busy = []; + runEvents = (input) => [ + { type: "RUN_STARTED", threadId: input.threadId, runId: input.runId }, + { type: "RUN_FINISHED", threadId: input.threadId, runId: input.runId }, + ]; + queryClient.setQueryData(channelKeys.list(), { + pages: [ + { + channels: [ + { + ...channel, + summary: null, + lastMessage: "Waiting for your approval.", + lastMessageAgentId: "waiting-bot", + createdAt: "2026-10-31T05:50:00.000Z", + pinned: false, + lastReadAt: null, + }, + ], + nextCursor: null, + }, + ], + pageParams: [""], + }); + return render( + + + + + , + ); +} + +/** What a harness sends when it asks before running one of its own tools. */ +const fromTheBot = { + id: "bot-wait", + reason: "tool_call", + toolCallId: "call-shell", + message: 'Approve "shell"?', + responseSchema: { + type: "object", + properties: { approved: { type: "boolean" } }, + required: ["approved"], + }, +}; +/** A wait OpenBot holds itself, decided on its own card and carried on by the server. */ +const fromTheServer = { + id: "call-send", + reason: "human_input", + message: "This action is waiting for your approval.", + metadata: { + [OPENBOT_WAITING_METADATA]: { + kind: "approval", + approvalId: "approval-1", + requestId: "approval-1", + }, + }, +}; + +function replying(text: string) { + runEvents = (input) => [ + { type: "RUN_STARTED", threadId: input.threadId, runId: input.runId }, + { type: "TEXT_MESSAGE_START", messageId: "went-on", role: "assistant" }, + { type: "TEXT_MESSAGE_CONTENT", messageId: "went-on", delta: text }, + { type: "TEXT_MESSAGE_END", messageId: "went-on" }, + { type: "RUN_FINISHED", threadId: input.threadId, runId: input.runId }, + ]; +} + +async function press(view: ReturnType, name: string) { + const user = userEvent.setup({ document: view.container.ownerDocument }); + await user.click(await view.findByRole("button", { name })); +} + +test("Allow goes out though the replayed run also ended on a wait of OpenBot's own", async () => { + interrupts = [fromTheBot, fromTheServer]; + const view = mounting(); + replying("Listed the files."); + + await press(view, "Allow"); + + await waitFor(() => expect(runRequests).toHaveLength(1)); + // Only the Bot's wait is answered from here: OpenBot's decision stays on its server path. + expect(runRequests[0]?.resume).toEqual([ + { + interruptId: "bot-wait", + status: "resolved", + payload: { approved: true }, + }, + ]); +}); + +test("what the Bot says after the answer reaches the roster, as a turn that started and ended once", async () => { + interrupts = [fromTheBot]; + const view = mounting(); + replying("Listed the files."); + + await press(view, "Don't allow"); + + await waitFor(() => + expect(activity.at(-1)).toEqual({ + botId: "waiting-bot", + text: "Listed the files.", + }), + ); + expect(runRequests[0]?.resume).toEqual([ + { + interruptId: "bot-wait", + status: "resolved", + payload: { approved: false }, + }, + ]); + await waitFor(() => expect(busy).toEqual([true, false])); +}); + +test("a wait whose time is over can be let go, so the conversation goes on", async () => { + interrupts = [{ ...fromTheBot, expiresAt: "2020-01-01T00:00:00.000Z" }]; + const view = mounting(); + + await press(view, "Carry on without it"); + + await waitFor(() => expect(runRequests).toHaveLength(1)); + expect(runRequests[0]?.resume).toEqual([ + { interruptId: "bot-wait", status: "cancelled" }, + ]); + // No decision is offered on what the Bot no longer takes one for. + expect(view.queryByRole("button", { name: "Allow" })).toBe(null); +}); + +test("an answer whose run fails says so, and the card is still there to try again", async () => { + interrupts = [fromTheBot]; + const view = mounting(); + runStatus = 503; + + await press(view, "Allow"); + + await waitFor(() => expect(runRequests).toHaveLength(1)); + await waitFor(() => + expect(view.container.querySelector('[role="alert"]')).not.toBe(null), + ); + await view.findByRole("button", { name: "Allow" }); + await waitFor(() => expect(busy).toEqual([true, false])); +}); diff --git a/app/tests/bot-raised-interrupts.test.ts b/app/tests/bot-raised-interrupts.test.ts new file mode 100644 index 0000000000..19d682ae1d --- /dev/null +++ b/app/tests/bot-raised-interrupts.test.ts @@ -0,0 +1,114 @@ +import { describe, expect, test } from "bun:test"; +import type { Message } from "@ag-ui/core"; +import { OPENBOT_WAITING_METADATA } from "@openbot/shared/waiting"; +import { + answersFor, + asksForApproval, + botRaisedInterrupts, + expired, + interruptedCall, +} from "@/lib/copilot/bot-raised-interrupts"; + +const yesOrNo = { + type: "object", + properties: { approved: { type: "boolean" } }, + required: ["approved"], +}; +/** What a Strands harness sends when it asks before running one of its own tools. */ +const fromTheBot = { + id: "int-1", + reason: "tool_call", + toolCallId: "call-1", + responseSchema: yesOrNo, +}; +const fromTheServer = { + id: "call-2", + reason: "human_input", + metadata: { [OPENBOT_WAITING_METADATA]: { requestId: "r1" } }, +}; +const aQuestion = { + id: "int-3", + reason: "input_required", + responseSchema: { type: "object", properties: { city: { type: "string" } } }, +}; + +describe("a wait the Bot raised itself", () => { + test("is told apart from one the server answers", () => { + expect(botRaisedInterrupts([fromTheBot, fromTheServer])).toEqual([ + fromTheBot, + ]); + }); + + test("asks yes or no when its one required answer is the boolean `approved`", () => { + expect(asksForApproval(fromTheBot)).toBe(true); + expect(asksForApproval(aQuestion)).toBe(false); + expect(asksForApproval({ id: "bare" })).toBe(false); + expect( + asksForApproval({ + id: "more", + responseSchema: { ...yesOrNo, required: ["approved", "reason"] }, + }), + ).toBe(false); + }); + + test("names the call it is about, from the conversation", () => { + const messages: Message[] = [ + { id: "u", role: "user", content: "run it" }, + { + id: "a", + role: "assistant", + toolCalls: [ + { + id: "call-1", + type: "function", + function: { name: "shell", arguments: '{"command":"ls"}' }, + }, + ], + }, + ]; + expect(interruptedCall(fromTheBot, messages)).toEqual({ + name: "shell", + args: '{"command":"ls"}', + }); + expect(interruptedCall(aQuestion, messages)).toBeUndefined(); + }); + + test("is answered with the decision, and the server's waits are left to the server", () => { + expect(answersFor([fromTheBot, fromTheServer], true)).toEqual([ + { interruptId: "int-1", status: "resolved", payload: { approved: true } }, + ]); + expect(answersFor([fromTheBot], false)).toEqual([ + { + interruptId: "int-1", + status: "resolved", + payload: { approved: false }, + }, + ]); + }); + + test("is cancelled when its answer is not a yes or no, so the conversation can go on", () => { + expect(answersFor([aQuestion], true)).toEqual([ + { interruptId: "int-3", status: "cancelled" }, + ]); + }); +}); + +describe("a wait whose time is over", () => { + const past = { ...fromTheBot, expiresAt: "2020-01-01T00:00:00.000Z" }; + const later = { ...fromTheBot, expiresAt: "2999-01-01T00:00:00.000Z" }; + + test("is told by its `expiresAt`, and one without is never over", () => { + expect(expired(past)).toBe(true); + expect(expired(later)).toBe(false); + expect(expired(fromTheBot)).toBe(false); + }); + + test("is let go whatever the decision, since the Bot takes none on it", () => { + expect(answersFor([past], true)).toEqual([ + { interruptId: "int-1", status: "cancelled" }, + ]); + expect(answersFor([later], true)).toEqual([ + { interruptId: "int-1", status: "resolved", payload: { approved: true } }, + ]); + }); +}); diff --git a/app/tests/second-organization.test.tsx b/app/tests/second-organization.test.tsx index b8c5d19d77..c3a46dafc2 100644 --- a/app/tests/second-organization.test.tsx +++ b/app/tests/second-organization.test.tsx @@ -63,6 +63,12 @@ const DEPLOYMENT_ADMINS_ONLY = { "Only an admin of the default organization can do this for now, because it applies to every organization here. Ask one of them.", retryable: false, }; +/** What a single-user OpenBot with an install token says to a request that does not carry it. */ +const INSTALL_TOKEN_REFUSAL = { + ...DEPLOYMENT_ADMINS_ONLY, + detail: + "This OpenBot only answers its own app. Open it from the OpenBot app, or use an API key.", +}; const NOT_FOUND = { type: "https://open.bot/errors/organization-not-found", title: "Organization not found.", @@ -354,6 +360,26 @@ test("signed in outside `default`, the app's first load learns what OpenBot offe ]); }); +test("an OpenBot that answers only the browser it let in is asked again with that browser's cookies", async () => { + // A single-user OpenBot in a container knows its one browser by a cookie, and refuses a request without it: the + // deployment asked as nobody, on every page. Refused that way, it is asked once more as the page. + setCurrentOrganization(undefined); + answer = (path, asNobody) => + path === "/api/v2/organizations/default/deployment" && !asNobody + ? Response.json(FACTS) + : problem(INSTALL_TOKEN_REFUSAL); + const capabilities = await freshClient().fetchQuery( + deploymentCapabilitiesQueryOptions(), + ); + expect(capabilities).toMatchObject({ generativeUi: true }); + expect(sent.map((request) => request.path)).toEqual([ + "/api/v2/organizations/default/deployment", + "/api/v2/organizations/default/deployment", + ]); + // The first ask, without cookies, is the one refused; nothing else is. + expect(refused).toHaveLength(1); +}); + test("once the organization is known, what OpenBot offers is asked there, and nobody signed in asks at `default`", async () => { setCurrentOrganization(HARBOR.id); answer = (path) =>