Skip to content
Draft
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
5 changes: 3 additions & 2 deletions app/src/components/channels/chat-transcript.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import {
} from "@openbot/shared/generate-image";
import { answeredBy } from "@openbot/shared/handoff-markers";
import { readBrief, readTaskReport } from "@openbot/shared/orchestration";
import { SEND_FILE_TOOL } from "@openbot/shared/send-file";
import { isSendFileTool } from "@openbot/shared/send-file";
import { SUBAGENT_TOOL } from "@openbot/shared/subagent";
import {
answersTheModel,
Expand Down Expand Up @@ -2720,7 +2720,8 @@ export function ChatTranscript({
const made = parseGenerateImageResult(item.result);
return made?.ok ? [{ name: made.image.name, url: made.image.url }] : [];
}
if (item.toolCall.function.name !== SEND_FILE_TOOL) return [];
// A file from the Bot's computer, or one it sent with its contents: the same answer.
if (!isSendFileTool(item.toolCall.function.name)) return [];
const file = sentFileOf(readOutcome(item.result));
return file ? [{ name: file.name, url: file.url }] : [];
});
Expand Down
4 changes: 2 additions & 2 deletions app/src/components/tasks/turn-work.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { SEND_FILE_TOOL } from "@openbot/shared/send-file";
import { isSendFileTool } from "@openbot/shared/send-file";
import { SUBAGENT_TOOL } from "@openbot/shared/subagent";
import { isPlanStep } from "@/components/channels/plan-turns";
import {
Expand Down Expand Up @@ -64,7 +64,7 @@ export const NO_TURN_WORK: TurnWorkFolds = { at: new Map(), inside: new Set() };
function isWorkStep(item: Extract<TranscriptItem, { kind: "tool" }>): boolean {
if (item.result === undefined || asksThePerson(item.result)) return false;
const { name, arguments: args } = item.toolCall.function;
if (name === SEND_FILE_TOOL && sentFileOf(readOutcome(item.result)))
if (isSendFileTool(name) && sentFileOf(readOutcome(item.result)))
return false;
if (name.startsWith("mcp__") || name === SUBAGENT_TOOL) return true;
// A Bot's plan is how the work went, folded with it once the answer is in.
Expand Down
3 changes: 2 additions & 1 deletion app/src/lib/computers/sent-file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import { acceptedFileTypeOf } from "@openbot/shared/attachments";
/**
* A file a Bot sent from its computer into the conversation, as its tool call's answer carries it.
*
* `computer_send_file` answers `{ ok: true, file: { attachmentId, name, mimeType, sizeBytes, url } }`.
* `computer_send_file` answers `{ ok: true, file: { attachmentId, name, mimeType, sizeBytes, url } }`,
* and so does `send_file`, which carries a file's contents from wherever the Bot made it.
* The server stored the file as an attachment of the conversation, so the card reads everything it
* draws from this answer: a reopened conversation shows the same card from the stored answer alone,
* and every member of the conversation reads the file from the same address.
Expand Down
3 changes: 3 additions & 0 deletions app/src/lib/copilot/provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import { MemoryTools } from "./memory-tool";
import { OrchestrationTools } from "./orchestration-tools";
import { PlanTool } from "./plan-tool";
import { SandboxedTools } from "./sandboxed-tools";
import { SendFileTool } from "./send-file-tool";
import { SignInTool } from "./sign-in-tool";
import { SkillTools } from "./skill-tools";

Expand Down Expand Up @@ -112,6 +113,8 @@ export function CopilotProvider({ children }: { children: ReactNode }) {
<MemoryTools />
{/* A Bot making a picture: its card, from the call and its stored answer. Runs on the server. */}
<GenerateImageTool />
{/* A Bot sending a file with its contents: the file's card, from its stored answer. Server-run. */}
<SendFileTool />
{/* A Bot's checklist of a long job, open while it runs. Answered on the server. */}
<PlanTool />
{/* A Bot reading, answering and resolving comments on an artifact. Runs on the server. */}
Expand Down
91 changes: 91 additions & 0 deletions app/src/lib/copilot/send-file-tool.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import { useRenderTool } from "@copilotkit/react-core/v2";
import { outcomeForPerson } from "@openbot/shared/approval-outcomes";
import { SEND_FILE_CONTENTS_TOOL } from "@openbot/shared/send-file";
import { useContext } from "react";
import { z } from "zod";
import { SentFileCard } from "@/components/channels/sent-file-card";
import { ToolLine } from "@/components/channels/tool-line";
import { TurnInFlightContext } from "@/components/gallery/streaming";
import { readOutcome } from "@/lib/computers/activity";
import { sentFileOf } from "@/lib/computers/sent-file";

/**
* How a Bot sending a file with its contents (`send_file`) reads in the conversation: the same file
* card a file from the Bot's computer draws (`SentFileCard`), from the stored answer, so a reload
* draws the same card.
*
* RENDER ONLY. `send_file` runs on the server for every Bot, built-in or connected over AG-UI, which
* checks the bytes as it checks an upload, stores them as a file of the conversation and answers with
* it. Nothing here registers a tool or decides anything.
*
* NEVER THE CONTENTS. The arguments carry the whole file while they stream; the line names the file
* and nothing else.
*/
const parameters = z.object({
name: z.string().optional(),
content: z.string().optional(),
encoding: z.string().optional(),
});

/** One call, as its card or its line. A component, so it can read whether its turn is running. */
export function SendFileCall({
name,
result,
}: {
name?: string;
result?: unknown;
}) {
const turnRunning = useContext(TurnInFlightContext);
const outcome = readOutcome(result);
const sent = sentFileOf(outcome);
if (sent) return <SentFileCard file={sent} />;
const answered = outcome !== null;
const refused = outcome?.refused === true;
const failed = answered && outcome?.ok === false && !refused;
const reason = outcomeForPerson(String(outcome?.reason ?? ""));
return (
<ToolLine
attempted="Send a file"
// The server's sentence already names the file ("notes.exe can't be sent. ..."), so the line
// leads with it rather than saying the name twice in a narrow column.
detail={
refused || failed
? name && !reason.includes(name)
? [name, reason].filter(Boolean).join(" · ")
: reason || name
: name
}
failed={failed}
// Not "Sent a file, didn't work": nothing arrived, so the line says so.
failedLabel="Didn't send a file"
// No answer, and the turn it belongs to is over: none is coming.
interrupted={!answered && !turnRunning}
label={answered ? "Sent a file" : "Sending a file"}
refused={refused}
running={!answered && turnRunning}
/>
);
}

export function SendFileTool() {
useRenderTool({
name: SEND_FILE_CONTENTS_TOOL,
parameters,
render: ({ parameters: given, result }) => (
<SendFileCall name={nameSoFar(given)} result={result} />
),
});
return null;
}

/**
* The file's name from the call's arguments, once it is whole text. While they stream they are
* anything (see `argumentsSoFar` in generate-image-tool.tsx), and the contents are never read here.
*/
export function nameSoFar(given: unknown): string | undefined {
if (!given || typeof given !== "object" || Array.isArray(given))
return undefined;
const { name } = given as Record<string, unknown>;
if (typeof name !== "string" || !name.trim()) return undefined;
return name.trim().split(/[\\/]/).pop() || undefined;
}
3 changes: 2 additions & 1 deletion app/src/lib/markdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,8 @@ export type LinkedFile = { name: string; url: string };
const NO_FILES: readonly LinkedFile[] = [];

/**
* The files a conversation was sent (a Bot's `computer_send_file` answers), for the Bot's words that
* The files a conversation was sent (a Bot's `computer_send_file` and `send_file` answers, and its
* pictures), for the Bot's words that
* link one of them. The transcript provides it; a surface with no conversation has none.
*/
export const SentFilesContext = createContext<readonly LinkedFile[]>(NO_FILES);
Expand Down
154 changes: 154 additions & 0 deletions app/tests/send-file-tool.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
import { afterAll, afterEach, beforeAll, expect, test } from "bun:test";
import { CopilotKitProvider } from "@copilotkit/react-core/v2";
import { GlobalRegistrator } from "@happy-dom/global-registrator";
import { SEND_FILE_CONTENTS_TOOL } from "@openbot/shared/send-file";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import {
createMemoryHistory,
createRootRoute,
createRouter,
RouterProvider,
} from "@tanstack/react-router";
import { cleanup, render, within } from "@testing-library/react";
import { HttpResponse, http } from "msw";
import { setupServer } from "msw/node";
import { ChatTranscript } from "@/components/channels/chat-transcript";
import { attachmentAddress } from "@/lib/channels/attachments";
import { SendFileTool } from "@/lib/copilot/send-file-tool";
import { readableTurns } from "@/lib/copilot/thread-messages";
import { settleReactWork } from "./settle-react-work";

/**
* A file a Bot sent with its contents (`send_file`), as the conversation draws it, live and after a
* reload: the same card a file from the Bot's computer draws.
*
* Found by a customer's connected Bot, which works on its own machine: it had no way to hand the
* person a file, and told them to pick it up from a path there. The server now answers `send_file`
* for every Bot in the shape `computer_send_file` answers, and the app draws it.
*
* Every conversation here is read the way a reopened one is: turns in the history store's own
* dialect, through `readableTurns`, into the app's transcript with the renderer the app registers.
* The server is faked at the HTTP boundary only, answering an attachment's address as the real one
* does.
*/

const FILE = "9d2f7a41-3c1b-4e55-a0d8-6b7c8e9f0a12";
const NOTES = "# Offsite notes\n\n- Book the venue\n- Send the agenda\n";

const server = setupServer(
http.head(
"*/api/v2/organizations/:organizationId/attachments/:id",
() => new HttpResponse(null, { status: 200 }),
),
http.all("*", () => new HttpResponse(null, { status: 404 })),
);

beforeAll(() => {
GlobalRegistrator.register({ url: "http://localhost/" });
server.listen({ onUnhandledRequest: "bypass" });
});
afterEach(() => {
cleanup();
server.resetHandlers();
});
afterAll(async () => {
server.close();
await settleReactWork();
GlobalRegistrator.unregister();
});

/** A conversation in which the person asked for notes and the Bot sent them with `send_file`. */
function storedThread(args: Record<string, unknown>, answer: unknown) {
return [
{ id: "u1", role: "user", content: "Write up the offsite notes for me" },
{
id: "a1",
role: "assistant",
content: null,
toolCalls: [{ id: "call_send", name: SEND_FILE_CONTENTS_TOOL, args }],
},
{
id: "r1",
role: "tool",
toolCallId: "call_send",
content: JSON.stringify(answer),
},
{ id: "a2", role: "assistant", content: "Here are the notes." },
];
}

function draw(stored: unknown[]) {
const { messages, unreadable } = readableTurns(stored);
expect(unreadable).toBe(0);
const client = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
const rootRoute = createRootRoute({
component: () => (
<CopilotKitProvider>
<SendFileTool />
<ChatTranscript busy={false} messages={messages} restoring={false} />
</CopilotKitProvider>
),
});
const router = createRouter({
routeTree: rootRoute,
history: createMemoryHistory({ initialEntries: ["/"] }),
});
return render(
<QueryClientProvider client={client}>
<RouterProvider router={router as never} />
</QueryClientProvider>,
);
}

test("a file a Bot sent with its contents is a card that downloads the stored file, now and on reload, and never shows the contents", async () => {
const answer = {
ok: true,
file: {
attachmentId: FILE,
name: "offsite-notes.md",
mimeType: "text/markdown",
sizeBytes: 54,
url: `/api/attachments/${FILE}`,
},
};
// A reload draws from the stored thread, which is this same list: drawn twice, from scratch.
for (let pass = 0; pass < 2; pass += 1) {
const view = draw(
storedThread({ name: "offsite-notes.md", content: NOTES }, answer),
);
const card = within(
await view.findByRole("figure", {
name: "File from the Bot: offsite-notes.md",
}),
);
expect(card.getByText("Markdown · 54 bytes")).toBeTruthy();
const download = card.getByRole("button", {
name: "Download offsite-notes.md",
});
expect(download.getAttribute("href")).toBe(
attachmentAddress(`/api/attachments/${FILE}`),
);
expect(download.getAttribute("download")).toBe("offsite-notes.md");
// The arguments carried the whole file; none of it is drawn.
expect(view.container.textContent).not.toContain("Book the venue");
cleanup();
}
});

test("a file that was refused is one line with the server's reason, and no card", async () => {
const reason =
"setup.exe can't be sent. Bots can send images (PNG, JPEG, GIF, WebP), PDFs, and text, Markdown, CSV or JSON files.";
const view = draw(
storedThread(
{ name: "setup.exe", content: "TVqQAAMAAAAEAAAA", encoding: "base64" },
{ ok: false, refused: true, reason },
),
);
expect(await view.findByText("Blocked: Send a file")).toBeTruthy();
// The sentence names the file, so the line does not say the name twice.
expect(view.getByText(reason)).toBeTruthy();
expect(view.queryByRole("figure")).toBeNull();
expect(view.queryByRole("button", { name: /Download/ })).toBeNull();
});
9 changes: 8 additions & 1 deletion shared/attachments.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@ import {
officeFileTypeOfMainPart,
shouldClaimPaste,
} from "./attachments";
import { SEND_FILE_TOOL_DESCRIPTION, sendFileUnsupported } from "./send-file";
import {
SEND_FILE_CONTENTS_TOOL_DESCRIPTION,
SEND_FILE_TOOL_DESCRIPTION,
sendFileUnsupported,
} from "./send-file";

/**
* TODAY'S SET OF FILES, PINNED. A person attaches and a Bot sends from this one list, so a change to
Expand Down Expand Up @@ -162,6 +166,9 @@ describe("the one list of files OpenBot takes", () => {
"images (PNG, JPEG, GIF, WebP), PDFs, Word documents, Excel workbooks, PowerPoint presentations, and text, Markdown, CSV or JSON files";
expect(acceptedFilesInWords()).toBe(words);
expect(SEND_FILE_TOOL_DESCRIPTION).toContain(`You can send ${words};`);
expect(SEND_FILE_CONTENTS_TOOL_DESCRIPTION).toContain(
`You can send ${words};`,
);
expect(sendFileUnsupported("tool.bin")).toBe(
`tool.bin can't be sent. Bots can send ${words}.`,
);
Expand Down
23 changes: 19 additions & 4 deletions shared/bot-prompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { PAGE_API_GUIDE } from "./artifacts/page-api-guide";
import { ARTIFACT_CREATE_TOOL } from "./artifacts/tools";
import { SHOW_APP_ACCESS_TOOL } from "./connect-prompt";
import { DELEGATE_TOOL, DELEGATING_GUIDANCE } from "./orchestration";
import { SEND_FILE_TOOL } from "./send-file";
import { SEND_FILE_CONTENTS_TOOL, SEND_FILE_TOOL } from "./send-file";
import { SUBAGENT_TOOL } from "./subagent";

const OPENING_A_PAGE_LINES = [
Expand Down Expand Up @@ -383,9 +383,21 @@ const SEND_FILE_LINES = [
"conversation.",
];

/**
* Sending a file made anywhere else, with its contents (`send_file`). Every Bot holds it. Found by a
* customer's connected Bot, which made a report on its own machine and told the person to pick it up
* from a path there.
*/
const SEND_CONTENTS_LINES = [
"The person cannot open any path on your machine. When you make a file for them anywhere OpenBot",
"can't reach, or write one out yourself, call send_file with its name and contents so it arrives in",
"the conversation. Never tell them to pick a file up from a path.",
];

/**
* How a Bot delivers its work, in its own section ("artifacts") after how it answers, for a run that
* holds the artifact tools, the computer's send-file tool, or both.
* holds the artifact tools, the computer's send-file tool, the tool that sends a file's contents, or
* any of them together.
*
* EVERY BOT THAT HOLDS THEM, WHATEVER RUNS IT, keyed on the run's tools as `delegatingGuidance` is: a
* built-in Bot and a connected AG-UI Bot are offered the same tools and told the same words, and a run
Expand All @@ -397,16 +409,19 @@ export function artifactsGuidance(
const holds = (name: string) => tools.some((tool) => tool.name === name);
const artifacts = holds(ARTIFACT_CREATE_TOOL);
const sends = holds(SEND_FILE_TOOL);
if (!artifacts && !sends) return [];
const sendsContents = holds(SEND_FILE_CONTENTS_TOOL);
if (!artifacts && !sends && !sendsContents) return [];
return promptSection(
"artifacts",
[
asParagraphs([
...(artifacts
? [...ARTIFACT_LINES, "", ...fileLines(holds("computer_run_command"))]
: []),
...(artifacts && sends ? [""] : []),
...(artifacts && (sends || sendsContents) ? [""] : []),
...(sends ? SEND_FILE_LINES : []),
...(sends && sendsContents ? [""] : []),
...(sendsContents ? SEND_CONTENTS_LINES : []),
]),
// What a page can ask its viewer for (window.openbot), word for word as the page runtime
// answers it, so a Bot writing a page knows it whatever runs the Bot.
Expand Down
Loading