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
166 changes: 166 additions & 0 deletions app/src/components/approvals/bot-approval-notice.tsx
Original file line number Diff line number Diff line change
@@ -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<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]);

// 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 (
<div
className="mb-3 flex flex-col gap-2 rounded-md border bg-warning/10 p-3 text-sm"
data-bot-approval
role="status"
>
{open.length > 0 ? (
<p className="font-medium">{botName} asks before it goes on</p>
) : approvals.length > 0 ? (
<p className="font-medium">
{botName} waited too long for this answer and no longer takes it
</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">
{open.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>
);
}
89 changes: 81 additions & 8 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 @@ -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,
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand All @@ -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 <T,>(work: () => Promise<T>): Promise<T> => {
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);
Expand All @@ -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
Expand Down Expand Up @@ -3359,6 +3425,13 @@ 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={answerBotWait}
/>
<HandoffResumeNotice
botId={runtimeAgentId}
agent={agent}
Expand Down
Loading
Loading