diff --git a/packages/app/src/session/timeline/turn-navigator.tsx b/packages/app/src/session/timeline/turn-navigator.tsx index 420cc1865454..ce9bcca4ac81 100644 --- a/packages/app/src/session/timeline/turn-navigator.tsx +++ b/packages/app/src/session/timeline/turn-navigator.tsx @@ -66,7 +66,7 @@ export function TurnNavigator(props: TurnNavigatorProps) { // Newest first, so a capped index still meets the loaded tail. const loadIndex = async (cursor?: string, count = 0): Promise<[string, string][]> => { const page = await sdk.api.message.list( - { sessionID: props.sessionID, type: "user", limit: turnPageLimit, cursor }, + { sessionID: props.sessionID, type: "user", includeFiles: false, limit: turnPageLimit, cursor }, { signal: abort.signal }, ) diff --git a/packages/client/src/effect/api/api.ts b/packages/client/src/effect/api/api.ts index 2a90c2dd7279..27cfe2b93e19 100644 --- a/packages/client/src/effect/api/api.ts +++ b/packages/client/src/effect/api/api.ts @@ -1400,6 +1400,7 @@ export type MessageListInput = { | "compaction" | "idle" | undefined + readonly includeFiles?: boolean | undefined } export type MessageListOutput = { readonly data: ReadonlyArray diff --git a/packages/client/src/effect/generated/client.ts b/packages/client/src/effect/generated/client.ts index c31f3899b8ee..3be7c5da4b1d 100644 --- a/packages/client/src/effect/generated/client.ts +++ b/packages/client/src/effect/generated/client.ts @@ -846,6 +846,7 @@ const EndpointMessageList = (raw: RawClient["server.message"]) => (input: Messag cursor: input["cursor"], before: input["before"], type: input["type"], + includeFiles: input["includeFiles"], }, }).pipe(Effect.mapError(mapClientError)), ) diff --git a/packages/client/src/promise/generated/client.ts b/packages/client/src/promise/generated/client.ts index 657a64c121ae..031a4b01dfbb 100644 --- a/packages/client/src/promise/generated/client.ts +++ b/packages/client/src/promise/generated/client.ts @@ -1117,6 +1117,7 @@ export function make(options: ClientOptions) { cursor: input["cursor"], before: input["before"], type: input["type"], + includeFiles: input["includeFiles"], }, successStatus: 200, declaredStatuses: [400, 401, 404, 500], diff --git a/packages/client/src/promise/generated/types.ts b/packages/client/src/promise/generated/types.ts index 1c2348852f8d..df7ad5d9c715 100644 --- a/packages/client/src/promise/generated/types.ts +++ b/packages/client/src/promise/generated/types.ts @@ -5769,6 +5769,7 @@ export type MessageListInput = { | "compaction" | "idle" | undefined + readonly includeFiles?: boolean | undefined }["limit"] readonly order?: { readonly limit?: number | undefined @@ -5788,6 +5789,7 @@ export type MessageListInput = { | "compaction" | "idle" | undefined + readonly includeFiles?: boolean | undefined }["order"] readonly cursor?: { readonly limit?: number | undefined @@ -5807,6 +5809,7 @@ export type MessageListInput = { | "compaction" | "idle" | undefined + readonly includeFiles?: boolean | undefined }["cursor"] readonly before?: { readonly limit?: number | undefined @@ -5826,6 +5829,7 @@ export type MessageListInput = { | "compaction" | "idle" | undefined + readonly includeFiles?: boolean | undefined }["before"] readonly type?: { readonly limit?: number | undefined @@ -5845,7 +5849,28 @@ export type MessageListInput = { | "compaction" | "idle" | undefined + readonly includeFiles?: boolean | undefined }["type"] + readonly includeFiles?: { + readonly limit?: number | undefined + readonly order?: "asc" | "desc" | undefined + readonly cursor?: string | undefined + readonly before?: string | undefined + readonly type?: + | "agent-switched" + | "model-switched" + | "location-switched" + | "user" + | "synthetic" + | "system" + | "skill" + | "shell" + | "assistant" + | "compaction" + | "idle" + | undefined + readonly includeFiles?: boolean | undefined + }["includeFiles"] } export type MessageListOutput = SessionMessagesResponse diff --git a/packages/core/src/session/store.ts b/packages/core/src/session/store.ts index d86cd6ab60c5..bf137b740e63 100644 --- a/packages/core/src/session/store.ts +++ b/packages/core/src/session/store.ts @@ -45,6 +45,8 @@ export type MessagesInput = { limit?: number order?: "asc" | "desc" type?: SessionMessage.Type + /** Omit top-level user attachments for text-only indexes; normal history includes them. */ + includeFiles?: boolean cursor?: { id: SessionMessage.ID direction: "previous" | "next" @@ -161,7 +163,19 @@ const layer = Layer.effect( : lt(SessionMessageTable.seq, anchor.seq) : undefined const query = db - .select() + .select({ + id: SessionMessageTable.id, + session_id: SessionMessageTable.session_id, + type: SessionMessageTable.type, + seq: SessionMessageTable.seq, + time_created: SessionMessageTable.time_created, + time_updated: SessionMessageTable.time_updated, + // Strip file bytes in SQLite before JSON parsing and schema validation in JS. + data: + input.includeFiles === false + ? sql`json_remove(${SessionMessageTable.data}, '$.files')`.mapWith(SessionMessageTable.data) + : SessionMessageTable.data, + }) .from(SessionMessageTable) .where( and( diff --git a/packages/protocol/src/groups/message.ts b/packages/protocol/src/groups/message.ts index 21b00a3a6ba5..14330cc1ff0e 100644 --- a/packages/protocol/src/groups/message.ts +++ b/packages/protocol/src/groups/message.ts @@ -1,7 +1,7 @@ import { Session } from "@opencode/schema/session" import { SessionMessage } from "@opencode/schema/session-message" import { Location } from "@opencode/schema/location" -import { Schema, Struct } from "effect" +import { Schema, SchemaGetter, Struct } from "effect" import { HttpApiEndpoint, HttpApiGroup, OpenApi } from "effect/http-api" import { InvalidCursorError, SessionNotFoundError, UnknownError } from "../errors.js" @@ -43,6 +43,17 @@ export const SessionMessagesQuery = Schema.Struct({ description: "Filter by message type before pagination. When omitted, all message types are returned. Pass the same type when following cursors.", }), + includeFiles: Schema.Literals(["true", "false"]).pipe( + Schema.decodeTo(Schema.Boolean, { + decode: SchemaGetter.transform((value) => value === "true"), + encode: SchemaGetter.transform((value): "true" | "false" => (value ? "true" : "false")), + }), + Schema.optional, + Schema.annotate({ + description: + "Include user message file attachments. Defaults to true. False omits the top-level files field for text-only indexes; tool results are unaffected. Pass the same value when following cursors.", + }), + ), }).annotate({ identifier: "SessionMessagesQuery" }) const PublicLocationSwitched = Schema.Struct({ diff --git a/packages/server/script/benchmark-message-index.ts b/packages/server/script/benchmark-message-index.ts new file mode 100644 index 000000000000..dce80cb50cce --- /dev/null +++ b/packages/server/script/benchmark-message-index.ts @@ -0,0 +1,69 @@ +// Manual benchmark of the real HTTP handler and generated client, with isolated synthetic data. +import { OpenCode, type SessionMessageInfo } from "@opencode/client" +import { Session } from "@opencode/schema/session" +import { Effect } from "effect" +import assert from "node:assert/strict" +import { ServerFetch } from "../src/fetch" +import { tempGlobalLayer } from "../../core/test/fixture/global" + +await Effect.runPromise(Effect.gen(function* () { + const handler = yield* ServerFetch.make({ + app: { version: "benchmark" }, + database: { path: ":memory:" }, + config: { project: false }, + models: { fetch: false }, + fs: { filewatcher: false }, + }) + const measured = { bytes: 0 } + const api = OpenCode.make({ + baseUrl: "http://fixture.invalid", + fetch: Object.assign(async (input: string | URL | Request, init?: RequestInit) => { + const response = await handler(new Request(input, init)) + const body = await response.arrayBuffer() + measured.bytes += body.byteLength + return new Response(body, { status: response.status, headers: response.headers }) + }, { preconnect: fetch.preconnect }), + }) + yield* Effect.promise(async () => { + const template = await api.session.create({ title: "Attachment-heavy prompt index" }) + const messages: SessionMessageInfo[] = Array.from({ length: 1000 }, (_, index) => ({ + id: `msg_fixture_${index}`, + type: "user", + text: `Prompt ${index}. ` + "Synthetic prompt text. ".repeat(18), + metadata: { displayText: `Prompt ${index}`, comments: [], attachments: [] }, + files: [{ data: "A".repeat(22000), mime: "image/png", source: { type: "inline" } }], + time: { created: index }, + })) + const session = await api.session.import({ info: { ...template, id: Session.ID.create() }, messages }) + const samples: { iteration: number; variant: string; ms: number; bytes: number; requests: number }[] = [] + for (let iteration = 0; iteration < 8; iteration++) { + for (const includeFiles of iteration % 2 ? [false, true] : [true, false]) { + measured.bytes = 0 + const start = performance.now() + const result: SessionMessageInfo[] = [] + let cursor: string | undefined + let requests = 0 + do { + const page = await api.message.list({ sessionID: session.id, type: "user", limit: 200, cursor, includeFiles }) + requests++ + result.push(...page.data) + cursor = page.cursor.next ?? undefined + } while (cursor && result.length < 1000) + const sample = { iteration, variant: includeFiles ? "before" : "after", ms: performance.now() - start, bytes: measured.bytes, requests } + assert.equal(result.length, 1000) + assert.deepEqual(result.map((message) => message.id), messages.toReversed().map((message) => message.id)) + const first = result[0] + assert(first?.type === "user") + assert.equal(first.metadata?.displayText, "Prompt 999") + assert.equal(first.files?.length, includeFiles ? 1 : undefined) + samples.push(sample) + } + } + const summaries = Object.fromEntries(["before", "after"].map((variant) => { + const rows = samples.filter((sample) => sample.iteration > 0 && sample.variant === variant) + const times = rows.map((sample) => sample.ms).sort((a, b) => a - b) + return [variant, { median: times[3], min: times[0], max: times.at(-1), bytes: rows[0]?.bytes, requests: rows[0]?.requests }] + })) + console.log(JSON.stringify({ fixture: "1000 user prompts, 22000 base64 characters each; synthetic, not an exact HOME replay", summaries, samples }, null, 2)) + }) +}).pipe(Effect.provide(tempGlobalLayer), Effect.scoped)) diff --git a/packages/server/src/handlers/message.ts b/packages/server/src/handlers/message.ts index fcd9d919e124..632ccc7da9a8 100644 --- a/packages/server/src/handlers/message.ts +++ b/packages/server/src/handlers/message.ts @@ -47,6 +47,7 @@ export const MessageHandler = HttpApiBuilder.group(Api, "server.message", (handl limit: ctx.query.limit ?? DefaultMessagesLimit, order, type: ctx.query.type, + includeFiles: ctx.query.includeFiles, // Descending past an anchor yields exactly the messages before it. cursor: decoded ? { id: decoded.id, direction: decoded.direction } diff --git a/packages/server/test/message.test.ts b/packages/server/test/message.test.ts index 60d1399a1df5..96e59c5e7153 100644 --- a/packages/server/test/message.test.ts +++ b/packages/server/test/message.test.ts @@ -6,7 +6,14 @@ import { it } from "../../core/test/lib/effect" import { ServerFetch } from "../src/fetch" const messages: SessionMessageInfo[] = [ - { id: "msg_z", type: "user", text: "First request", time: { created: 300 } }, + { + id: "msg_z", + type: "user", + text: "First request", + metadata: { displayText: "Visible first request", comments: [], attachments: [] }, + files: [{ data: "AQID", mime: "image/png", source: { type: "inline" } }], + time: { created: 300 }, + }, { id: "msg_assistant", type: "assistant", @@ -86,6 +93,25 @@ it.live("filters message types before paginating in either direction through the messages[8], ]) expect((await fixture.api.message.list({ sessionID: fixture.sessionID, type: "shell" })).data).toEqual([]) + const textOnly = await fixture.api.message.list({ ...input, order: "asc", includeFiles: false }) + expect(textOnly.data).toEqual([ + { + id: "msg_z", + type: "user", + text: "First request", + metadata: { displayText: "Visible first request", comments: [], attachments: [] }, + time: { created: 300 }, + }, + messages[2], + ]) + expect((await fixture.api.message.list({ ...input, order: "asc", includeFiles: true })).data).toEqual([ + messages[0], + messages[2], + ]) + if (!textOnly.cursor.next) throw new Error("Expected a text-only next cursor") + expect( + (await fixture.api.message.list({ ...input, cursor: textOnly.cursor.next, includeFiles: false })).data, + ).toEqual([messages[5], messages[7]]) // Before excludes its anchor; the returned cursor continues further back through matching messages. const before = await fixture.api.message.list({ ...input, before: "msg_a" }) expect(before.data.map((message) => message.id)).toEqual(["msg_x", "msg_b"])