Skip to content
Merged
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
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -775,6 +775,7 @@ jobs:
app/tests/question-answer-prompt-browser.test.tsx
app/tests/queue-send-now-layout.test.tsx
app/tests/reached-as-the-person-browser.test.tsx
app/tests/reconnecting-line-layout.test.tsx
app/tests/rejoin-fresh-token-browser.test.tsx
app/tests/reload-keeps-answer-browser.test.tsx
app/tests/renderer-crash.test.ts
Expand Down
26 changes: 26 additions & 0 deletions api/asyncapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2067,6 +2067,32 @@ components:
type: string
organization_id:
type: string
name:
type: string
description: >-
A CUSTOM event's name. Any Bot may send these, built in or
connected, and an app ignores a name it doesn't know. OpenBot's
own: `openbot.reconnecting`, sent while the Bot waits to try a
model call again after its connection dropped (more than one may
come in a row, one per attempt); and `openbot.reconnected`, sent
when the call it tried again starts answering. The app shows
"Reconnecting…" on the turn's live line from the first until the
second, or until any later event of the run that is not CUSTOM, or
until the run ends.
examples:
- openbot.reconnecting
- openbot.reconnected
value:
description: >-
A CUSTOM event's value. For `openbot.reconnecting`, an object with
`attempt` (the attempt it waits to make, counted from 1),
`attempts` (the most it will make) and `retryInMs` (how long until
it tries). For `openbot.reconnected`, an empty object.
examples:
- attempt: 1
attempts: 4
retryInMs: 2000
- {}
metadata:
type: object
properties:
Expand Down
4 changes: 4 additions & 0 deletions app/src/components/channels/channel-chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@ import {
watchQuietRun,
} from "@/lib/copilot/quiet-run";
import { realtimeTrouble } from "@/lib/copilot/realtime-trouble";
import { useReconnecting } from "@/lib/copilot/reconnecting";
import {
repairUnansweredToolCalls,
unansweredToolCalls,
Expand Down Expand Up @@ -824,6 +825,8 @@ export function ChannelChat({
offerItsOwnTools(agent, runtimeAgentId, queries);
return observeApprovalAgent(agent);
}, [agent, runtimeAgentId, queries]);
// The Bot waiting to try its model again, said on the turn's live line (`reconnecting.ts`).
const reconnecting = useReconnecting(agent);

/**
* First-message seed from the compose screen. It is taken once per mount and retained until the
Expand Down Expand Up @@ -3668,6 +3671,7 @@ export function ChannelChat({
}
stoppedDismissed={stoppedDismissal.dismissed}
onDismissStopped={stoppedDismissal.dismiss}
reconnecting={reconnecting}
/*
* What the server says this conversation waits on: a Bot its Bot asked, a routine.
* Hidden while this tab's own turn is going, which already shows itself and would
Expand Down
26 changes: 22 additions & 4 deletions app/src/components/channels/chat-transcript.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,12 @@ type ChatTranscriptProps = {
* answer will appear.
*/
working?: React.ReactNode;
/**
* The Bot is waiting to try its model again after the connection dropped (`useReconnecting`).
* While `busy`, the turn's live line says "Reconnecting…" in place of "Thinking", under whatever
* the Bot said last.
*/
reconnecting?: boolean;
};

/** One shared empty array, so a screen without a queue does not hand down a new one per render. */
Expand Down Expand Up @@ -440,16 +446,21 @@ export function RestoringTranscript() {
*
* It borrows the shimmer a running tool line uses, so "working on it" reads the same whether the
* work is a tool call or a model that has not spoken yet.
*
* While the Bot waits to try its model again after the connection dropped, the same line says
* "Reconnecting…" (`reconnecting` on the transcript). Same line and same shimmer: the Bot is still
* on it, and the person needs nothing more than that. Only if the tries run out does the turn's
* notice say so.
*/
function Thinking() {
function Thinking({ reconnecting = false }: { reconnecting?: boolean }) {
return (
<p
className="tool-line-running text-muted-foreground text-sm"
// `status` rather than `alert`: this is progress, not something that interrupts what somebody
// is doing. The text says it, so a screen reader is told the same thing the shimmer implies.
role="status"
>
Thinking
{reconnecting ? "Reconnecting…" : "Thinking"}
</p>
);
}
Expand Down Expand Up @@ -2620,6 +2631,7 @@ export function ChatTranscript({
stoppedDismissed = false,
onDismissStopped,
working,
reconnecting = false,
}: ChatTranscriptProps) {
const isDrawn = useDrawnTool();
// Which calls draw a component, so one asked for too early is left out. See `shared/tool-steps.ts`.
Expand Down Expand Up @@ -2766,6 +2778,12 @@ export function ChatTranscript({
* the Thinking indicator.
*/
lastItem?.kind === "attachments");
/*
* WAITING TO RECONNECT IS DRAWN WHEREVER THE TURN IS. The model's connection can drop after the
* Bot has already said something this turn, with its words the last thing on screen. Nothing else
* says it is still working then, so the live line comes back under them until the Bot carries on.
*/
const reconnectingNow = busy && reconnecting;

const viewportRef = useRef<HTMLDivElement | null>(null);
const newestUserMessageId =
Expand Down Expand Up @@ -3320,8 +3338,8 @@ export function ChatTranscript({
reason={stopped}
/>
)
) : waitingOnTheModel ? (
<Thinking />
) : waitingOnTheModel || reconnectingNow ? (
<Thinking reconnecting={reconnectingNow} />
) : null}
{working}
{queued.map((message) => (
Expand Down
4 changes: 4 additions & 0 deletions app/src/components/channels/conversation-view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ export function ConversationView({
stoppedDismissed,
onDismissStopped,
working,
reconnecting = false,
stoppable,
queueWhileBusy = false,
restoring = false,
Expand Down Expand Up @@ -143,6 +144,8 @@ export function ConversationView({
onDismissStopped?: () => void;
/** Work the conversation waits on that is not this tab's run. Drawn at the end of the transcript. */
working?: ReactNode;
/** The Bot is waiting to reconnect to its model; see the transcript's `reconnecting`. */
reconnecting?: boolean;
/**
* There is a run for Stop to abort, which is a narrower fact than `pending` and is the honest one
* to draw a Stop button from. Defaults to `pending` for a caller with no gap between the two.
Expand Down Expand Up @@ -653,6 +656,7 @@ export function ConversationView({
{...(stopped && stoppedDismissed ? { stoppedDismissed } : {})}
{...(stopped && onDismissStopped ? { onDismissStopped } : {})}
working={working}
reconnecting={reconnecting}
/>
</div>
{/* The composer's column, shared with a group conversation; see `ComposerColumn`. */}
Expand Down
72 changes: 72 additions & 0 deletions app/src/lib/copilot/reconnecting.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { type AbstractAgent, EventType } from "@copilotkit/react-core/v2";
import { useEffect, useState } from "react";

/**
* Whether the Bot is waiting to try a dropped model call again, as its run says it is.
*
* A model connection that drops mid-turn is tried again by the Bot itself, with a wait between
* tries, and the turn carries on. While it waits, the run says so in plain AG-UI, so any Bot can,
* built in or connected (api/asyncapi.yaml, `AgUiEvent`):
*
* - `CUSTOM` named `openbot.reconnecting`, `{ attempt, attempts, retryInMs }`, once per wait;
* - `CUSTOM` named `openbot.reconnected`, `{}`, when the call it tried again starts answering.
*
* The wait also ends on anything else the run says: words, a tool call, reasoning, a step, its end.
* Each of those means the Bot is past the wait, whether or not `openbot.reconnected` came first.
* And it ends with the run, however the run ends, so a turn that stops never leaves it standing.
*
* Only the person's live line reads this (`ChatTranscript`'s `reconnecting`). If the Bot runs out
* of tries, the run ends with its error and the turn's usual notice says so, Carry on and all.
*/
export const RECONNECTING_EVENT = "openbot.reconnecting";
export const RECONNECTED_EVENT = "openbot.reconnected";

/** A CUSTOM event's name, when it has one. */
function customName(event: unknown): string | null {
if (!event || typeof event !== "object") return null;
const { type, name } = event as { type?: unknown; name?: unknown };
if (type !== EventType.CUSTOM) return null;
return typeof name === "string" ? name : "";
}

/**
* Tells `setReconnecting` when one agent's run starts and stops waiting to reconnect. Returns the
* function that stops watching, which also says it is no longer waiting.
*/
export function watchReconnecting(
agent: Pick<AbstractAgent, "subscribe">,
setReconnecting: (reconnecting: boolean) => void,
): () => void {
// Only a change is passed on: a reply streams many events a second, and each would set it again.
let waiting = false;
const set = (next: boolean) => {
if (next === waiting) return;
waiting = next;
setReconnecting(next);
};
const subscription = agent.subscribe({
onRunInitialized: () => set(false),
onEvent: ({ event }) => {
const name = customName(event);
if (name === null) set(false);
else if (name === RECONNECTING_EVENT) set(true);
else if (name === RECONNECTED_EVENT) set(false);
// Any other CUSTOM event is about something else, and changes nothing here.
},
onRunFinalized: () => set(false),
onRunFailed: () => set(false),
});
return () => {
subscription.unsubscribe();
set(false);
};
}

/** Whether this agent's run is waiting to reconnect to its model now. See `watchReconnecting`. */
export function useReconnecting(
agent: Pick<AbstractAgent, "subscribe">,
): boolean {
const [reconnecting, setReconnecting] = useState(false);
useEffect(() => watchReconnecting(agent, setReconnecting), [agent]);
return reconnecting;
}
145 changes: 145 additions & 0 deletions app/tests/reconnecting-line-layout.fixture.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import type { Message } from "@ag-ui/core";
import {
AbstractAgent,
type BaseEvent,
CopilotKitProvider,
EventType,
type RunAgentInput,
} from "@copilotkit/react-core/v2";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useEffect, useState } from "react";
import { createRoot } from "react-dom/client";
import { Observable, ReplaySubject } from "rxjs";
import { ConversationView } from "@/components/channels/conversation-view";
import { TooltipProvider } from "@/components/ui/tooltip";
import { useReconnecting } from "@/lib/copilot/reconnecting";
import { setCurrentOrganization } from "@/lib/organizations/current";

/**
* A conversation whose Bot's model connection drops, as a page of its own for
* reconnecting-line-layout.test.tsx to bundle and load in a browser: the real conversation view and
* transcript, and a real AG-UI agent read by `useReconnecting`, as the conversation screen reads it.
* The test says what the run sends next with `window.__say(step)`.
*
* `?theme=dark` draws it in the dark theme.
*/
type Step = "dropped" | "back" | "words" | "more" | "finished";
type Page = Window & { __say: (step: Step) => void };
const page = window as unknown as Page;
setCurrentOrganization("default");

if (new URLSearchParams(location.search).get("theme") === "dark") {
document.documentElement.classList.add("dark");
}

class DroppingBot extends AbstractAgent {
private said = new ReplaySubject<BaseEvent>();
private ids = { threadId: "thread-1", runId: "run-1" };
constructor() {
super({
agentId: "bot",
threadId: "thread-1",
initialMessages: [
{
id: "asked",
role: "user",
content: "Summarize this quarter's numbers for the board.",
},
],
});
}
run(input: RunAgentInput): Observable<BaseEvent> {
this.ids = { threadId: input.threadId, runId: input.runId };
this.say({ type: EventType.RUN_STARTED, ...this.ids });
return new Observable<BaseEvent>((subscriber) => {
const hearing = this.said.subscribe(subscriber);
return () => hearing.unsubscribe();
});
}
say(event: Record<string, unknown>) {
this.said.next(event as unknown as BaseEvent);
}
step(step: Step) {
if (step === "dropped")
this.say({
type: EventType.CUSTOM,
name: "openbot.reconnecting",
value: { attempt: 1, attempts: 4, retryInMs: 2000 },
});
if (step === "back")
this.say({
type: EventType.CUSTOM,
name: "openbot.reconnected",
value: {},
});
if (step === "words" || step === "more") {
const messageId = `said-${step}`;
this.say({
type: EventType.TEXT_MESSAGE_START,
messageId,
role: "assistant",
});
this.say({
type: EventType.TEXT_MESSAGE_CONTENT,
messageId,
delta:
step === "words"
? "Revenue grew 12% on last quarter, led by the two new enterprise contracts."
: "Costs held flat.",
});
this.say({ type: EventType.TEXT_MESSAGE_END, messageId });
}
if (step === "finished") {
this.say({ type: EventType.RUN_FINISHED, ...this.ids });
this.said.complete();
}
}
}

const bot = new DroppingBot();
page.__say = (step) => bot.step(step);

const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});

function Conversation() {
const reconnecting = useReconnecting(bot);
const [messages, setMessages] = useState<Message[]>(() => [...bot.messages]);
const [busy, setBusy] = useState(false);
useEffect(() => {
const subscription = bot.subscribe({
onRunInitialized: () => setBusy(true),
onRunFinalized: () => setBusy(false),
onMessagesChanged: ({ messages: now }) => setMessages([...now]),
});
void bot.runAgent().catch(() => undefined);
return () => subscription.unsubscribe();
}, []);
return (
<ConversationView
busy={busy}
channelId="channel-1"
messages={messages}
onSubmit={async () => {}}
pending={busy}
reconnecting={reconnecting}
stoppable={busy}
/>
);
}

const root = document.getElementById("root");
if (root) {
createRoot(root).render(
<QueryClientProvider client={queryClient}>
<CopilotKitProvider runtimeUrl="/api/copilotkit">
<TooltipProvider>
<div className="flex h-svh flex-col bg-background text-foreground">
<Conversation />
</div>
</TooltipProvider>
</CopilotKitProvider>
</QueryClientProvider>,
);
}
Loading