Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
146 changes: 146 additions & 0 deletions app/src/components/approvals/bot-approval-notice.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
import type { Message } from "@ag-ui/core";
import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import {
answersFor,
asksForApproval,
botRaisedInterrupts,
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<unknown>;
}) {
const [, redraw] = useState(0);
const [busy, setBusy] = useState(false);
const [problem, setProblem] = useState<Failure | null>(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]);

const waiting = ready ? botRaisedInterrupts(agent.pendingInterrupts) : [];
if (waiting.length === 0 || agent.isRunning) return null;
const approvals = waiting.filter(asksForApproval);

const answer = async (approved: boolean) => {
if (busy) return;
setBusy(true);
setProblem(null);
try {
await run(answersFor(agent.pendingInterrupts, approved));
} catch (error) {
setProblem(failureOf(error, "Couldn't send your answer. Try again."));
} finally {
setBusy(false);
}
};

return (
<div
className="mb-3 flex flex-col gap-2 rounded-md border bg-warning/10 p-3 text-sm"
data-bot-approval
role="status"
>
{approvals.length > 0 ? (
<p className="font-medium">{botName} asks before it goes on</p>
) : (
<p className="font-medium">
{botName} is waiting for an answer this app can't give
</p>
)}
{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 (
<div className="flex min-w-0 flex-col gap-1" key={interrupt.id}>
{/*
* 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 ? (
<>
<p>
Use <span className="font-medium">{call.name}</span>
</p>
<p className="min-w-0 break-words font-mono text-muted-foreground text-xs">
{call.args}
</p>
</>
) : asked ? (
<p className="break-words">{asked}</p>
) : null}
</div>
);
})}
{problem ? (
<p className="text-destructive" role="alert">
{failureSaid(problem)}
</p>
) : null}
<div className="flex flex-wrap gap-2">
{approvals.length > 0 ? (
<>
<Button disabled={busy} onClick={() => void answer(true)} size="sm">
Allow
</Button>
<Button
disabled={busy}
onClick={() => void answer(false)}
size="sm"
variant="outline"
>
Don't allow
</Button>
</>
) : (
<Button
disabled={busy}
onClick={() => void answer(false)}
size="sm"
variant="outline"
>
Carry on without it
</Button>
)}
</div>
</div>
);
}
17 changes: 17 additions & 0 deletions app/src/components/channels/channel-chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -3359,6 +3360,22 @@ export function ChannelChat({
{channel.active ? (
<ConversationAllowances threadId={channel.threadId} />
) : null}
{/* What the Bot stopped its own run to ask; the answer is the next run's `resume`. */}
<BotApprovalNotice
agent={agent}
botName={botName}
ready={isReady && !restoring && channel.active}
run={async (resume) => {
setRunsInFlight((count) => count + 1);
try {
await whileObserved(agent, () =>
copilotkit.runAgent({ agent, resume }),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2. The resume skips the conversation’s run handling. With a mocked HTTP 503, the SDK reported an error but resolved the promise. The card’s catch never ran, and the conversation showed no failure. A successful resume showed the Bot’s reply in the transcript but sent no activity update for the conversation list. Please route this through the existing run tracking or cover both outcomes explicitly, including a visible error when the answer fails to send.

);
} finally {
setRunsInFlight((count) => count - 1);
}
}}
/>
<HandoffResumeNotice
botId={runtimeAgentId}
agent={agent}
Expand Down
90 changes: 90 additions & 0 deletions app/src/lib/copilot/bot-raised-interrupts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import type { Message } from "@ag-ui/core";
import { serverOwnedInterrupt } from "@/lib/copilot/server-owned-interrupts";

/** An AG-UI interrupt as the agent holds it, as much of it as this reads. */
export type HeldInterrupt = {
id: string;
reason?: string;
message?: string;
toolCallId?: string;
responseSchema?: unknown;
metadata?: Record<string, unknown>;
};

/** 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<T extends HeldInterrupt>(
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<string, { type?: unknown } | undefined>;
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;
}

/**
* The `resume` that answers every interrupt the agent holds, given the person's decision on those
* the Bot raised. 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 is cancelled, which lets the
* conversation go on.
*/
export function answersFor(
pending: readonly HeldInterrupt[],
approved: boolean,
): InterruptAnswer[] {
return botRaisedInterrupts(pending).map((interrupt) =>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1. Mixed waits block the Bot’s answer. If the SDK holds one Bot interrupt and one OpenBot-owned interrupt, this drops the OpenBot ID from resume. AG-UI validates coverage against every pending ID before the run starts. I replayed both kinds together and clicked Allow. No request left the browser, and the card returned with no error. Please reconcile the OpenBot-owned wait before resuming the Bot’s wait, while keeping the OpenBot decision on its existing server path. The helper test covers the filtered payload, so please add a ChannelChat test that verifies the answer actually goes out.

asksForApproval(interrupt)
? { interruptId: interrupt.id, status: "resolved", payload: { approved } }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2. An expired approval can leave the conversation stuck. For a wait with an elapsed expiresAt, the pinned SDK rejects resolved before sending the request. I clicked both Allow and Don’t allow after replaying an expired approval. Neither sent a request, and there was no way to cancel the wait. Please check expiry when the person clicks and give them a way to continue with status: "cancelled".

: { interruptId: interrupt.id, status: "cancelled" },
);
}
42 changes: 28 additions & 14 deletions app/src/lib/deployment/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,31 @@ function showsOpenBotOnThisComputer(): Promise<boolean> {
* 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<Deployment> {
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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please update the PR’s API checklist to call out this browser request change. A 403 from the anonymous deployment read now triggers a second GET with the browser’s cookies, using the existing endpoint and response contract.

}
}

export async function readDeployment(options: {
signal?: AbortSignal;
fallback: string;
Expand All @@ -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) {
Expand All @@ -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);
}
}
Expand Down
Loading
Loading