Skip to content
Closed
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
2 changes: 1 addition & 1 deletion packages/app/src/session/timeline/turn-navigator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 },
)

Expand Down
1 change: 1 addition & 0 deletions packages/client/src/effect/api/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1400,6 +1400,7 @@ export type MessageListInput = {
| "compaction"
| "idle"
| undefined
readonly includeFiles?: boolean | undefined
}
export type MessageListOutput = {
readonly data: ReadonlyArray<SessionMessage.Info>
Expand Down
1 change: 1 addition & 0 deletions packages/client/src/effect/generated/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)),
)
Expand Down
1 change: 1 addition & 0 deletions packages/client/src/promise/generated/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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],
Expand Down
25 changes: 25 additions & 0 deletions packages/client/src/promise/generated/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5769,6 +5769,7 @@ export type MessageListInput = {
| "compaction"
| "idle"
| undefined
readonly includeFiles?: boolean | undefined
}["limit"]
readonly order?: {
readonly limit?: number | undefined
Expand All @@ -5788,6 +5789,7 @@ export type MessageListInput = {
| "compaction"
| "idle"
| undefined
readonly includeFiles?: boolean | undefined
}["order"]
readonly cursor?: {
readonly limit?: number | undefined
Expand All @@ -5807,6 +5809,7 @@ export type MessageListInput = {
| "compaction"
| "idle"
| undefined
readonly includeFiles?: boolean | undefined
}["cursor"]
readonly before?: {
readonly limit?: number | undefined
Expand All @@ -5826,6 +5829,7 @@ export type MessageListInput = {
| "compaction"
| "idle"
| undefined
readonly includeFiles?: boolean | undefined
}["before"]
readonly type?: {
readonly limit?: number | undefined
Expand All @@ -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
Expand Down
16 changes: 15 additions & 1 deletion packages/core/src/session/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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(
Expand Down
13 changes: 12 additions & 1 deletion packages/protocol/src/groups/message.ts
Original file line number Diff line number Diff line change
@@ -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"

Expand Down Expand Up @@ -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({
Expand Down
69 changes: 69 additions & 0 deletions packages/server/script/benchmark-message-index.ts
Original file line number Diff line number Diff line change
@@ -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))
1 change: 1 addition & 0 deletions packages/server/src/handlers/message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down
28 changes: 27 additions & 1 deletion packages/server/test/message.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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"])
Expand Down
Loading