Skip to content

Commit d080200

Browse files
authored
Let a run carry its tools, context and catalog by reference (#2819)
* Let a run carry its tools, context and catalog by reference Every run the web app sends carries the same tools, context and generative UI catalog, about 145 KB, again on every message and every step of a turn. The deployment answer gains runPartsByReference: where it is true, a run may name each of those parts by the SHA-256 of its JSON, carrying the part itself only until the server holds it, and the server puts every part back before the run goes anywhere. A part the server doesn't hold is refused with RUN_PARTS_NEEDED and nothing runs. shared/run-parts.ts is the form both ends use. Sent by reference, context is an object rather than a list, so a server from before this refuses the run (AG-UI's own schema) instead of running it without its parts. Tested on the run the real app sends for a Bot with every component, its computer and both authoring skills: 146 KB whole, under 5 KB by reference once held, and made whole again byte for byte. * Say a join of a conversation may carry its parts by reference too
1 parent 99df719 commit d080200

9 files changed

Lines changed: 617 additions & 0 deletions

File tree

‎api/openapi.yaml‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31940,6 +31940,9 @@ components:
3194031940
computerStepsByReference:
3194131941
type: boolean
3194231942
description: 'Whether a computer step (runComputerStep) may be sent by reference: its run, its call and the call''s arguments, without the conversation, which the server reads from what it kept of the run. Absent or false, send the whole conversation, as an OpenBot from before this answers any other body with VALIDATION_ERROR.'
31943+
runPartsByReference:
31944+
type: boolean
31945+
description: 'Whether a run sent to the chat runtime (`/api/copilotkit/agent/{botId}/run`), or a join of a conversation (`/api/copilotkit/agent/{botId}/connect`), may carry its large parts by reference: its tools, its context and its generative UI catalog (`forwardedProps.copilotkit.ui["1.0"].inlineCatalogs`), each named by the SHA-256, in hex, of its JSON. In that form `tools` is empty, the catalog is left out, and `context` is an object, not a list: `{ "openbotRunParts": { "tools": { "hash", "value"? }, "context": {...}, "catalog": {...} } }`, with each part''s `value` while the server may not hold it yet. The server puts every part back before the run goes anywhere, so the run, and what each Bot is sent, is the run as it would have been sent whole. A request naming a part the server doesn''t hold is answered 409 with the problem code RUN_PARTS_NEEDED (type https://open.bot/errors/run-parts-needed) and nothing runs: send it again with every part''s value. Absent or false, send every run whole, as an OpenBot from before this refuses a run whose context is not a list (400).'
3194331946
attachmentLimits:
3194431947
$ref: '#/components/schemas/AttachmentLimits'
3194531948
api:
@@ -59610,6 +59613,7 @@ components:
5961059613
isolatedBots: false
5961159614
botComputers: true
5961259615
computerStepsByReference: true
59616+
runPartsByReference: true
5961359617
attachmentLimits:
5961459618
imageBytes: 104857600
5961559619
documentBytes: 104857600

‎api/openapi/admin-settings.yaml‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1416,6 +1416,28 @@ components:
14161416
the conversation, which the server reads from what it kept of the
14171417
run. Absent or false, send the whole conversation, as an OpenBot
14181418
from before this answers any other body with VALIDATION_ERROR.
1419+
runPartsByReference:
1420+
type: boolean
1421+
description: >-
1422+
Whether a run sent to the chat runtime
1423+
(`/api/copilotkit/agent/{botId}/run`), or a join of a conversation
1424+
(`/api/copilotkit/agent/{botId}/connect`), may carry its large
1425+
parts by reference: its tools, its context and its generative UI
1426+
catalog
1427+
(`forwardedProps.copilotkit.ui["1.0"].inlineCatalogs`), each named
1428+
by the SHA-256, in hex, of its JSON. In that form `tools` is empty,
1429+
the catalog is left out, and `context` is an object, not a list:
1430+
`{ "openbotRunParts": { "tools": { "hash", "value"? }, "context":
1431+
{...}, "catalog": {...} } }`, with each part's `value` while the
1432+
server may not hold it yet. The server puts every part back before
1433+
the run goes anywhere, so the run, and what each Bot is sent, is
1434+
the run as it would have been sent whole. A request naming a part
1435+
the server doesn't hold is answered 409 with the problem code
1436+
RUN_PARTS_NEEDED (type
1437+
https://open.bot/errors/run-parts-needed) and nothing runs: send
1438+
it again with every part's value. Absent or false, send every run
1439+
whole, as an OpenBot from before this refuses a run whose context
1440+
is not a list (400).
14191441
attachmentLimits:
14201442
$ref: '#/components/schemas/AttachmentLimits'
14211443
api:
@@ -2702,6 +2724,7 @@ components:
27022724
isolatedBots: false
27032725
botComputers: true
27042726
computerStepsByReference: true
2727+
runPartsByReference: true
27052728
attachmentLimits:
27062729
imageBytes: 104857600
27072730
documentBytes: 104857600

‎app/src/lib/api/generated/model/deployment.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,8 @@ export interface Deployment {
4040
botComputers: boolean;
4141
/** Whether a computer step (runComputerStep) may be sent by reference: its run, its call and the call's arguments, without the conversation, which the server reads from what it kept of the run. Absent or false, send the whole conversation, as an OpenBot from before this answers any other body with VALIDATION_ERROR. */
4242
computerStepsByReference?: boolean;
43+
/** Whether a run sent to the chat runtime (`/api/copilotkit/agent/{botId}/run`), or a join of a conversation (`/api/copilotkit/agent/{botId}/connect`), may carry its large parts by reference: its tools, its context and its generative UI catalog (`forwardedProps.copilotkit.ui["1.0"].inlineCatalogs`), each named by the SHA-256, in hex, of its JSON. In that form `tools` is empty, the catalog is left out, and `context` is an object, not a list: `{ "openbotRunParts": { "tools": { "hash", "value"? }, "context": {...}, "catalog": {...} } }`, with each part's `value` while the server may not hold it yet. The server puts every part back before the run goes anywhere, so the run, and what each Bot is sent, is the run as it would have been sent whole. A request naming a part the server doesn't hold is answered 409 with the problem code RUN_PARTS_NEEDED (type https://open.bot/errors/run-parts-needed) and nothing runs: send it again with every part's value. Absent or false, send every run whole, as an OpenBot from before this refuses a run whose context is not a list (400). */
44+
runPartsByReference?: boolean;
4345
attachmentLimits?: AttachmentLimits;
4446
/**
4547
* The API versions this OpenBot serves, by major, such as v2. An app that speaks none of them can't use it: when they are all newer than the app's, the app needs an update; when they are all older, this OpenBot does. Absent from a release before it was published, which serves v2.

‎app/src/lib/api/generated/organization-settings/organization-settings.msw.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ export const getGetDeploymentResponseMock = (): Deployment => ({
3535
isolatedBots: false,
3636
botComputers: true,
3737
computerStepsByReference: true,
38+
runPartsByReference: true,
3839
attachmentLimits: {
3940
imageBytes: 104857600,
4041
documentBytes: 104857600,

‎app/src/lib/api/generated/organization-settings/organization-settings.zod.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,12 @@ export const GetDeploymentResponse = zod
108108
.describe(
109109
"Whether a computer step (runComputerStep) may be sent by reference: its run, its call and the call's arguments, without the conversation, which the server reads from what it kept of the run. Absent or false, send the whole conversation, as an OpenBot from before this answers any other body with VALIDATION_ERROR.",
110110
),
111+
runPartsByReference: zod
112+
.boolean()
113+
.optional()
114+
.describe(
115+
'Whether a run sent to the chat runtime (`/api/copilotkit/agent/{botId}/run`), or a join of a conversation (`/api/copilotkit/agent/{botId}/connect`), may carry its large parts by reference: its tools, its context and its generative UI catalog (`forwardedProps.copilotkit.ui["1.0"].inlineCatalogs`), each named by the SHA-256, in hex, of its JSON. In that form `tools` is empty, the catalog is left out, and `context` is an object, not a list: `{ "openbotRunParts": { "tools": { "hash", "value"? }, "context": {...}, "catalog": {...} } }`, with each part\'s `value` while the server may not hold it yet. The server puts every part back before the run goes anywhere, so the run, and what each Bot is sent, is the run as it would have been sent whole. A request naming a part the server doesn\'t hold is answered 409 with the problem code RUN_PARTS_NEEDED (type https://open.bot/errors/run-parts-needed) and nothing runs: send it again with every part\'s value. Absent or false, send every run whole, as an OpenBot from before this refuses a run whose context is not a list (400).',
116+
),
111117
attachmentLimits: zod
112118
.object({
113119
imageBytes: zod.int().min(1).describe("The largest image."),

‎app/tests/run-parts-app.tsx‎

Lines changed: 257 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,257 @@
1+
import { GlobalRegistrator } from "@happy-dom/global-registrator";
2+
import { QueryClientProvider } from "@tanstack/react-query";
3+
import { cleanup, render, waitFor } from "@testing-library/react";
4+
import userEvent from "@testing-library/user-event";
5+
import { expect } from "bun:test";
6+
import { ChannelChat } from "@/components/channels/channel-chat";
7+
import { GALLERY as ACTIVITY } from "@/components/gallery/activity";
8+
import { GALLERY as CARDS } from "@/components/gallery/cards";
9+
import { GALLERY as CHARTS } from "@/components/gallery/charts";
10+
import { GALLERY as DECISIONS } from "@/components/gallery/decisions";
11+
import { GALLERY as FORMS } from "@/components/gallery/form";
12+
import { GALLERY as QUOTES } from "@/components/gallery/quote";
13+
import { GALLERY as TABLES } from "@/components/gallery/table";
14+
import type { AgentChannel } from "@/lib/channels/queries";
15+
import { GALLERY_COMPONENTS } from "@/lib/copilot/gallery-registry";
16+
import { CopilotProvider } from "@/lib/copilot/provider";
17+
import { deploymentKeys } from "@/lib/deployment/queries";
18+
import { queryClient } from "@/query-client";
19+
import { MY_CAPABILITIES_PATH } from "./admin-settings-api";
20+
import { botGrantsPath, botGrantsResponse } from "./bot-grants-api";
21+
import { answerBotsList, botPath } from "./bots-api";
22+
import {
23+
ANNOUNCE_COMPONENTS_PATH,
24+
announcedResponse,
25+
botComponentsPath,
26+
botComponentsResponse,
27+
} from "./components-api";
28+
import { settleReactWork } from "./settle-react-work";
29+
30+
/**
31+
* The signed-in app, as a person's conversation with one Bot sends its runs: the app's own
32+
* CopilotKit provider with every tool it registers, and every component of the gallery, as Vite
33+
* registers them (`import.meta.glob` is Vite's, so `bun test` finds none by itself).
34+
*
35+
* The Bot is the one with the most to offer: every component, its computer and both authoring
36+
* skills, with generative UI on. So its runs are production-sized: about 145 KB each, sent whole.
37+
*
38+
* Every run the app sends is kept as it left (`runs`), and answered by `answerRun`, which is the
39+
* server: by default a short reply.
40+
*/
41+
42+
export const BOT = "run-parts-bot";
43+
const channel: AgentChannel = {
44+
id: "run-parts-channel",
45+
name: "Run parts",
46+
agentIds: [BOT],
47+
threadId: "run-parts-thread",
48+
active: true,
49+
lastMessageAt: null,
50+
};
51+
const NativeResponse = globalThis.Response;
52+
const EVERY_COMPONENT = [
53+
...ACTIVITY,
54+
...CARDS,
55+
...CHARTS,
56+
...DECISIONS,
57+
...FORMS,
58+
...QUOTES,
59+
...TABLES,
60+
];
61+
62+
/** A run as it left the browser: its body, exactly. */
63+
export type SentRun = { raw: string; body: Record<string, unknown> };
64+
65+
export function sse(events: unknown[]): Response {
66+
return new NativeResponse(
67+
events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join(""),
68+
{ headers: { "content-type": "text/event-stream" } },
69+
);
70+
}
71+
72+
/** A run answered in a word, as a Bot does. */
73+
export function reply(body: Record<string, unknown>): Response {
74+
const id = `reply-${String(body.runId)}`;
75+
return sse([
76+
{ type: "RUN_STARTED", threadId: body.threadId, runId: body.runId },
77+
{ type: "TEXT_MESSAGE_START", messageId: id, role: "assistant" },
78+
{ type: "TEXT_MESSAGE_CONTENT", messageId: id, delta: "Done." },
79+
{ type: "TEXT_MESSAGE_END", messageId: id },
80+
{ type: "RUN_FINISHED", threadId: body.threadId, runId: body.runId },
81+
]);
82+
}
83+
84+
class QuietSocket {
85+
static readonly OPEN = 1;
86+
readyState = 0;
87+
onopen: (() => void) | null = null;
88+
onclose: (() => void) | null = null;
89+
onerror: (() => void) | null = null;
90+
onmessage: ((event: { data: unknown }) => void) | null = null;
91+
send() {}
92+
close() {}
93+
}
94+
95+
export const runs: SentRun[] = [];
96+
/** The server's answer to each run. */
97+
export let answerRun: (run: SentRun) => Response | Promise<Response> = (run) =>
98+
reply(run.body);
99+
export function answerRunsWith(
100+
answer: (run: SentRun) => Response | Promise<Response>,
101+
) {
102+
answerRun = answer;
103+
}
104+
105+
let originalFetch: typeof fetch;
106+
let originalSocket: typeof WebSocket;
107+
let added: typeof EVERY_COMPONENT = [];
108+
109+
export function setUpApp() {
110+
if (GALLERY_COMPONENTS.length === 0) {
111+
added = [...EVERY_COMPONENT].sort((a, b) => a.name.localeCompare(b.name));
112+
GALLERY_COMPONENTS.push(...added);
113+
}
114+
GlobalRegistrator.register();
115+
originalFetch = globalThis.fetch;
116+
originalSocket = globalThis.WebSocket;
117+
globalThis.WebSocket = QuietSocket as unknown as typeof WebSocket;
118+
globalThis.fetch = Object.assign(
119+
async (input: Parameters<typeof fetch>[0], init?: RequestInit) => {
120+
const url = new URL(
121+
typeof input === "string"
122+
? input
123+
: input instanceof URL
124+
? input.href
125+
: input.url,
126+
"http://localhost",
127+
);
128+
const request = input instanceof Request ? input : new Request(url, init);
129+
if (url.pathname === ANNOUNCE_COMPONENTS_PATH) return announcedResponse();
130+
if (url.pathname === botComponentsPath(BOT))
131+
return botComponentsResponse(
132+
EVERY_COMPONENT.map((spec) => ({
133+
name: spec.name,
134+
description: spec.description,
135+
})),
136+
);
137+
if (url.pathname === botPath(BOT))
138+
return NativeResponse.json({
139+
bot: {
140+
id: BOT,
141+
name: "Run parts",
142+
visibility: "public",
143+
canManage: true,
144+
},
145+
});
146+
if (url.pathname === botGrantsPath(BOT))
147+
return botGrantsResponse({
148+
skills: [
149+
{
150+
slug: "bot-creator",
151+
title: "Make a coworker",
152+
summary: "",
153+
instructions: "",
154+
},
155+
{
156+
slug: "skill-creator",
157+
title: "Make a skill",
158+
summary: "",
159+
instructions: "",
160+
},
161+
],
162+
tools: [],
163+
});
164+
if (url.pathname === MY_CAPABILITIES_PATH)
165+
return NativeResponse.json({ capabilities: {}, enforced: false });
166+
if (url.pathname.endsWith("/info"))
167+
return NativeResponse.json({
168+
version: "fixture",
169+
agents: { [BOT]: { description: "Fixture", capabilities: {} } },
170+
mode: "sse",
171+
telemetryDisabled: true,
172+
});
173+
if (url.pathname.endsWith("/connect")) {
174+
const { threadId } = (await request.json()) as { threadId: string };
175+
return sse([
176+
{ type: "RUN_STARTED", threadId, runId: "join" },
177+
{ type: "MESSAGES_SNAPSHOT", messages: [] },
178+
{ type: "RUN_FINISHED", threadId, runId: "join" },
179+
]);
180+
}
181+
if (url.pathname.endsWith("/run")) {
182+
const raw = await request.text();
183+
const run = { raw, body: JSON.parse(raw) as Record<string, unknown> };
184+
runs.push(run);
185+
return answerRun(run);
186+
}
187+
if (url.pathname.match(/\/threads\/[^/]+\/messages$/))
188+
return NativeResponse.json({ messages: [] });
189+
const bots = answerBotsList(url, init, { visible: [] });
190+
if (bots) return bots;
191+
if (/^\/api\/plugins\/for\/[^/]+$/.test(url.pathname))
192+
return NativeResponse.json({ skills: [], tools: [] });
193+
if (/voice-sessions$/.test(url.pathname))
194+
return NativeResponse.json({ sessions: [], nextCursor: null });
195+
if (/\/(activity|signal-busy|mark-read)$/.test(url.pathname))
196+
return new NativeResponse(null, { status: 204 });
197+
if (/approval-modes\/[^/]+$/.test(url.pathname))
198+
return NativeResponse.json({ asksEveryStep: false });
199+
return NativeResponse.json({ error: "Not found" }, { status: 404 });
200+
},
201+
{ preconnect: () => undefined },
202+
);
203+
}
204+
205+
export async function tearDownApp() {
206+
cleanup();
207+
await settleReactWork();
208+
for (const spec of added)
209+
GALLERY_COMPONENTS.splice(GALLERY_COMPONENTS.indexOf(spec), 1);
210+
added = [];
211+
globalThis.fetch = originalFetch;
212+
globalThis.WebSocket = originalSocket;
213+
GlobalRegistrator.unregister();
214+
}
215+
216+
/**
217+
* The app open on the Bot's conversation, on a server that does or doesn't take a run's parts by
218+
* reference, with `send` to type a message and press Enter.
219+
*/
220+
export async function openConversation(options: {
221+
runPartsByReference: boolean | undefined;
222+
}) {
223+
cleanup();
224+
queryClient.clear();
225+
runs.length = 0;
226+
queryClient.setQueryData(deploymentKeys.capabilities(), {
227+
generativeUi: true,
228+
selfHostBanner: false,
229+
localEvaluation: false,
230+
...(options.runPartsByReference === undefined
231+
? {}
232+
: { runPartsByReference: options.runPartsByReference }),
233+
} as never);
234+
const view = render(
235+
<QueryClientProvider client={queryClient}>
236+
<CopilotProvider>
237+
<ChannelChat channel={channel} runtimeAgentId={BOT} />
238+
</CopilotProvider>
239+
</QueryClientProvider>,
240+
);
241+
const user = userEvent.setup({ document: view.container.ownerDocument });
242+
const editor = await view.findByRole("textbox", { name: "Message" });
243+
await waitFor(() =>
244+
expect(editor.getAttribute("aria-disabled")).not.toBe("true"),
245+
);
246+
const send = async (text: string) => {
247+
const before = runs.length;
248+
await user.click(editor);
249+
await user.keyboard(text);
250+
await user.keyboard("{Enter}");
251+
await waitFor(() => expect(runs.length).toBeGreaterThan(before), {
252+
timeout: 10_000,
253+
});
254+
return runs[runs.length - 1] as SentRun;
255+
};
256+
return { view, send };
257+
}

0 commit comments

Comments
 (0)