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
5 changes: 5 additions & 0 deletions .changeset/state-backend-binary-base64.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"deepagents": patch
---

`StateBackend` stores binary uploads and writes as base64 text with `encoding: "base64"`, so threads with uploaded images or PDFs keep working after a JSON checkpointer round trip. Uploads at text paths whose bytes are not valid UTF-8 are kept byte-for-byte as `application/octet-stream` instead of being lossily decoded.
6 changes: 6 additions & 0 deletions libs/deepagents/src/backends/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,12 @@ export interface FileDataV2 {
content: string | Uint8Array;
/** MIME type of the file (e.g. "image/png", "text/plain") */
mimeType: string;
/**
* How string `content` is encoded. `"base64"` marks binary bytes stored as
* base64 text so they survive JSON serialization (e.g. a checkpointer).
* Omitted means plain text.
*/
encoding?: "utf-8" | "base64";
/** ISO format timestamp of creation */
created_at: string;
/** ISO format timestamp of last modification */
Expand Down
149 changes: 144 additions & 5 deletions libs/deepagents/src/backends/state.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { StateBackend } from "./state.js";
import type { FileData, FileDataV1 } from "./protocol.js";
import { getConfig, Command } from "@langchain/langgraph";
import { ToolMessage } from "@langchain/core/messages";
import { FileDataSchema } from "../middleware/fs.js";

vi.mock("@langchain/langgraph", async (importOriginal) => {
const actual = await importOriginal();
Expand Down Expand Up @@ -504,7 +505,7 @@ describe("StateBackend", () => {
expect((result as any).filesUpdate["/hello.txt"].content).toBe("Hello");
});

it("should upload binary (image) files as Uint8Array", () => {
it("should store binary (image) uploads as base64 text", () => {
const { state, runtime } = makeConfig();
const backend = new StateBackend(runtime);

Expand All @@ -515,9 +516,11 @@ describe("StateBackend", () => {
expect(result[0].error).toBeNull();

Object.assign(state.files, (result as any).filesUpdate);
const stored = state.files["/image.png"];
expect(stored.content).toBeInstanceOf(Uint8Array);
expect(stored.content).toEqual(pngBytes);
expect(state.files["/image.png"]).toMatchObject({
content: Buffer.from(pngBytes).toString("base64"),
encoding: "base64",
mimeType: "image/png",
});
});
});

Expand Down Expand Up @@ -650,7 +653,7 @@ describe("StateBackend", () => {

const full = backend.read("/img.png");
const withOffsetLimit = backend.read("/img.png", 5, 2);
expect(withOffsetLimit.content).toBe(full.content);
expect(withOffsetLimit.content).toEqual(full.content);
});
});

Expand Down Expand Up @@ -934,4 +937,140 @@ describe("StateBackend", () => {
expect(result.filesUpdate).toBeUndefined();
});
});

describe("JSON-serialized state", () => {
const pngBytes = new Uint8Array([
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0xff,
]);

/** Serialize state the way a JSON checkpointer does, then reopen it. */
function roundTrip(state: { files: Record<string, FileData> }) {
const restored = JSON.parse(JSON.stringify(state));
return {
files: restored.files as Record<string, FileData>,
backend: new StateBackend({ state: restored, store: undefined }),
};
}

function uploadAndRoundTrip(files: Array<[string, Uint8Array]>) {
const { state, runtime } = makeConfig();
const result = new StateBackend(runtime).uploadFiles(files);
Object.assign(state.files, (result as any).filesUpdate);
return roundTrip(state);
}

it("keeps binary uploads valid against the files schema", () => {
const { files } = uploadAndRoundTrip([["/image.png", pngBytes]]);

expect(FileDataSchema.parse(files["/image.png"])).toMatchObject({
encoding: "base64",
mimeType: "image/png",
});
});

it("reads, downloads, and sizes binary uploads byte-identically", () => {
const { backend } = uploadAndRoundTrip([["/image.png", pngBytes]]);

expect(backend.read("/image.png")).toEqual({
content: pngBytes,
mimeType: "image/png",
});
expect(backend.readRaw("/image.png").data!.content).toEqual(pngBytes);
expect(backend.downloadFiles(["/image.png"])[0].content).toEqual(
pngBytes,
);
expect(backend.ls("/").files![0].size).toBe(pngBytes.length);
expect(backend.glob("*.png").files![0].size).toBe(pngBytes.length);
});

it("returns an image block from read_file", async () => {
const { backend } = uploadAndRoundTrip([["/image.png", pngBytes]]);
const { createFilesystemMiddleware } =
await import("../middleware/fs.js");
const readFileTool = createFilesystemMiddleware({ backend }).tools!.find(
(tool) => tool.name === "read_file",
);

const result = await readFileTool!.invoke({ file_path: "/image.png" });

expect(result).toEqual([
{
type: "image",
mimeType: "image/png",
data: Buffer.from(pngBytes).toString("base64"),
},
]);
});

it("stores non-UTF-8 bytes at a text path as binary", () => {
const bytes = new Uint8Array([0xff, 0xfe, 0x00, 0x80, 0x41]);
const { files, backend } = uploadAndRoundTrip([["/blob.dat", bytes]]);

expect(files["/blob.dat"]).toMatchObject({
encoding: "base64",
mimeType: "application/octet-stream",
});
expect(backend.downloadFiles(["/blob.dat"])[0].content).toEqual(bytes);
expect(backend.grep("A").matches).toEqual([]);
});

it("reads text written over a non-UTF-8 upload as text", () => {
const { state, runtime } = makeConfig();
const backend = new StateBackend(runtime);
const upload = backend.uploadFiles([
["/blob.dat", new Uint8Array([0xff, 0xfe])],
]);
Object.assign(state.files, (upload as any).filesUpdate);

const result = backend.write("/blob.dat", "hello");
Object.assign(state.files, result.filesUpdate);

expect(backend.read("/blob.dat")).toMatchObject({
content: "hello",
mimeType: "text/plain",
});
});

it("keeps UTF-8 uploads at text paths as plain text", () => {
const { files } = uploadAndRoundTrip([
["/notes.txt", new TextEncoder().encode("h\u00e9llo")],
]);

expect(files["/notes.txt"].content).toBe("h\u00e9llo");
expect(files["/notes.txt"]).not.toHaveProperty("encoding");
});

it("stores binary-path writes as base64 text", () => {
const { state, runtime } = makeConfig();
const result = new StateBackend(runtime).write(
"/image.png",
Buffer.from(pngBytes).toString("base64"),
);
Object.assign(state.files, result.filesUpdate);

const { files, backend } = roundTrip(state);

expect(files["/image.png"]).toMatchObject({ encoding: "base64" });
expect(backend.downloadFiles(["/image.png"])[0].content).toEqual(
pngBytes,
);
});

it("still reads Uint8Array entries stored before base64 encoding", () => {
const { runtime } = makeConfig({
"/old.png": {
content: pngBytes,
mimeType: "image/png",
created_at: "2024-01-01T00:00:00.000Z",
modified_at: "2024-01-01T00:00:00.000Z",
},
});
const backend = new StateBackend(runtime);

expect(backend.read("/old.png").content).toEqual(pngBytes);
expect(backend.readRaw("/old.png").data!.content).toEqual(pngBytes);
expect(backend.downloadFiles(["/old.png"])[0].content).toEqual(pngBytes);
expect(backend.ls("/").files![0].size).toBe(pngBytes.length);
});
});
});
Loading
Loading