From 30f8b2f4b678041f10d5289920ee89888b127d11 Mon Sep 17 00:00:00 2001 From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Date: Wed, 9 Sep 2026 19:01:16 -0500 Subject: [PATCH] feat(api): filter session messages by type (#48228) --- packages/client/src/effect/api/api.ts | 12 +++ .../client/src/effect/generated/client.ts | 2 +- .../client/src/promise/generated/client.ts | 2 +- .../client/src/promise/generated/types.ts | 53 +++++++++ packages/core/src/session/store.ts | 12 ++- packages/protocol/openapi.json | 54 +++++++++- packages/protocol/src/groups/message.ts | 19 +++- packages/server/src/handlers/message.ts | 1 + packages/server/test/message.test.ts | 102 ++++++++++++++++++ services/www/openapi.json | 54 +++++++++- services/www/public/openapi.json | 54 +++++++++- 11 files changed, 355 insertions(+), 10 deletions(-) create mode 100644 packages/server/test/message.test.ts diff --git a/packages/client/src/effect/api/api.ts b/packages/client/src/effect/api/api.ts index a548a85e6a4..dce80880878 100644 --- a/packages/client/src/effect/api/api.ts +++ b/packages/client/src/effect/api/api.ts @@ -1166,6 +1166,18 @@ export type MessageListInput = { readonly limit?: number | undefined readonly order?: "asc" | "desc" | undefined readonly cursor?: string | undefined + readonly type?: + | "agent-switched" + | "model-switched" + | "location-switched" + | "user" + | "synthetic" + | "system" + | "skill" + | "shell" + | "assistant" + | "compaction" + | 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 cae13bc8cf9..aab4a78999a 100644 --- a/packages/client/src/effect/generated/client.ts +++ b/packages/client/src/effect/generated/client.ts @@ -757,7 +757,7 @@ const EndpointMessageList = (raw: RawClient["server.message"]) => (input: Messag preserveEffect()( raw["session.messages"]({ params: { sessionID: input["sessionID"] }, - query: { limit: input["limit"], order: input["order"], cursor: input["cursor"] }, + query: { limit: input["limit"], order: input["order"], cursor: input["cursor"], type: input["type"] }, }).pipe(Effect.mapError(mapClientError)), ) diff --git a/packages/client/src/promise/generated/client.ts b/packages/client/src/promise/generated/client.ts index 89ce0eed821..ef1e8bf218a 100644 --- a/packages/client/src/promise/generated/client.ts +++ b/packages/client/src/promise/generated/client.ts @@ -1015,7 +1015,7 @@ export function make(options: ClientOptions) { { method: "GET", path: `/api/session/${encodeURIComponent(input.sessionID)}/message`, - query: { limit: input["limit"], order: input["order"], cursor: input["cursor"] }, + query: { limit: input["limit"], order: input["order"], cursor: input["cursor"], type: input["type"] }, successStatus: 200, declaredStatuses: [400, 401, 404, 500], empty: false, diff --git a/packages/client/src/promise/generated/types.ts b/packages/client/src/promise/generated/types.ts index c6206bc813b..c60b9410897 100644 --- a/packages/client/src/promise/generated/types.ts +++ b/packages/client/src/promise/generated/types.ts @@ -4348,17 +4348,70 @@ export type MessageListInput = { readonly limit?: number | undefined readonly order?: "asc" | "desc" | undefined readonly cursor?: string | undefined + readonly type?: + | "agent-switched" + | "model-switched" + | "location-switched" + | "user" + | "synthetic" + | "system" + | "skill" + | "shell" + | "assistant" + | "compaction" + | undefined }["limit"] readonly order?: { readonly limit?: number | undefined readonly order?: "asc" | "desc" | undefined readonly cursor?: string | undefined + readonly type?: + | "agent-switched" + | "model-switched" + | "location-switched" + | "user" + | "synthetic" + | "system" + | "skill" + | "shell" + | "assistant" + | "compaction" + | undefined }["order"] readonly cursor?: { readonly limit?: number | undefined readonly order?: "asc" | "desc" | undefined readonly cursor?: string | undefined + readonly type?: + | "agent-switched" + | "model-switched" + | "location-switched" + | "user" + | "synthetic" + | "system" + | "skill" + | "shell" + | "assistant" + | "compaction" + | undefined }["cursor"] + readonly type?: { + readonly limit?: number | undefined + readonly order?: "asc" | "desc" | undefined + readonly cursor?: string | undefined + readonly type?: + | "agent-switched" + | "model-switched" + | "location-switched" + | "user" + | "synthetic" + | "system" + | "skill" + | "shell" + | "assistant" + | "compaction" + | undefined + }["type"] } export type MessageListOutput = SessionMessagesResponse diff --git a/packages/core/src/session/store.ts b/packages/core/src/session/store.ts index c01abb3e2e2..53bf9e585d0 100644 --- a/packages/core/src/session/store.ts +++ b/packages/core/src/session/store.ts @@ -43,6 +43,7 @@ export type MessagesInput = { sessionID: Session.ID limit?: number order?: "asc" | "desc" + type?: SessionMessage.Type cursor?: { id: SessionMessage.ID direction: "previous" | "next" @@ -156,13 +157,16 @@ const layer = Layer.effect( ? gt(SessionMessageTable.seq, anchor.seq) : lt(SessionMessageTable.seq, anchor.seq) : undefined - const where = boundary - ? and(eq(SessionMessageTable.session_id, input.sessionID), boundary) - : eq(SessionMessageTable.session_id, input.sessionID) const query = db .select() .from(SessionMessageTable) - .where(where) + .where( + and( + eq(SessionMessageTable.session_id, input.sessionID), + boundary, + input.type === undefined ? undefined : eq(SessionMessageTable.type, input.type), + ), + ) .orderBy(order === "asc" ? asc(SessionMessageTable.seq) : desc(SessionMessageTable.seq)) const rows = yield* (input.limit === undefined ? query.all() : query.limit(input.limit).all()).pipe( Effect.orDie, diff --git a/packages/protocol/openapi.json b/packages/protocol/openapi.json index a1110a58375..75b4c8d1de8 100644 --- a/packages/protocol/openapi.json +++ b/packages/protocol/openapi.json @@ -4490,6 +4490,34 @@ ] }, "required": false + }, + { + "name": "type", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "string", + "enum": [ + "agent-switched", + "model-switched", + "location-switched", + "user", + "synthetic", + "system", + "skill", + "shell", + "assistant", + "compaction" + ] + }, + { + "type": "null" + } + ], + "description": "Filter by message type before pagination. When omitted, all message types are returned. Pass the same type when following cursors." + }, + "required": false } ], "security": [], @@ -4552,7 +4580,7 @@ } } }, - "description": "Retrieve projected messages for a session. Items keep the requested order across pages; use cursor.next or cursor.previous to move through the ordered timeline.", + "description": "Retrieve projected messages for a session, optionally filtered by type. Items keep the requested order across pages; use cursor.next or cursor.previous to move through the ordered timeline, passing the same type filter on each page.", "summary": "Get session messages" } }, @@ -14243,6 +14271,9 @@ "compaction": { "$ref": "#/components/schemas/Provider.Compaction" }, + "websocket": { + "type": "boolean" + }, "modelID": { "type": "string" }, @@ -14351,6 +14382,9 @@ "compaction": { "$ref": "#/components/schemas/Provider.Compaction" }, + "websocket": { + "type": "boolean" + }, "canonical": { "type": "string" }, @@ -16297,6 +16331,9 @@ "compaction": { "$ref": "#/components/schemas/Provider.Compaction" }, + "websocket": { + "type": "boolean" + }, "settings": { "type": "object" }, @@ -17285,6 +17322,9 @@ "compaction": { "$ref": "#/components/schemas/Provider.Compaction" }, + "websocket": { + "type": "boolean" + }, "settings": { "type": "object" }, @@ -18256,6 +18296,12 @@ }, "providerContext": { "$ref": "#/components/schemas/Session.ProviderContext" + }, + "cost": { + "$ref": "#/components/schemas/Money.USD" + }, + "tokens": { + "$ref": "#/components/schemas/TokenUsage.Info" } }, "required": ["type", "id", "time", "status", "reason", "summary", "recent"], @@ -18295,6 +18341,12 @@ }, "error": { "$ref": "#/components/schemas/Session.StructuredError" + }, + "cost": { + "$ref": "#/components/schemas/Money.USD" + }, + "tokens": { + "$ref": "#/components/schemas/TokenUsage.Info" } }, "required": ["type", "id", "time", "status", "reason", "error"], diff --git a/packages/protocol/src/groups/message.ts b/packages/protocol/src/groups/message.ts index 559961e710f..fd42c18c6ab 100644 --- a/packages/protocol/src/groups/message.ts +++ b/packages/protocol/src/groups/message.ts @@ -19,6 +19,23 @@ export const SessionMessagesQuery = Schema.Struct({ "Opaque pagination cursor returned as cursor.previous or cursor.next in the previous response. Do not combine with order.", }), ), + type: Schema.optional( + Schema.Literals([ + "agent-switched", + "model-switched", + "location-switched", + "user", + "synthetic", + "system", + "skill", + "shell", + "assistant", + "compaction", + ] satisfies ReadonlyArray), + ).annotate({ + description: + "Filter by message type before pagination. When omitted, all message types are returned. Pass the same type when following cursors.", + }), }).annotate({ identifier: "SessionMessagesQuery" }) export const MessageGroup = HttpApiGroup.make("server.message") @@ -39,7 +56,7 @@ export const MessageGroup = HttpApiGroup.make("server.message") identifier: "v2.message.list", summary: "Get session messages", description: - "Retrieve projected messages for a session. Items keep the requested order across pages; use cursor.next or cursor.previous to move through the ordered timeline.", + "Retrieve projected messages for a session, optionally filtered by type. Items keep the requested order across pages; use cursor.next or cursor.previous to move through the ordered timeline, passing the same type filter on each page.", }), ), ) diff --git a/packages/server/src/handlers/message.ts b/packages/server/src/handlers/message.ts index cfc6b6deee5..04f6120b74b 100644 --- a/packages/server/src/handlers/message.ts +++ b/packages/server/src/handlers/message.ts @@ -44,6 +44,7 @@ export const MessageHandler = HttpApiBuilder.group(Api, "server.message", (handl sessionID: ctx.params.sessionID, limit: ctx.query.limit ?? DefaultMessagesLimit, order, + type: ctx.query.type, cursor: decoded ? { id: decoded.id, direction: decoded.direction } : undefined, }) .pipe( diff --git a/packages/server/test/message.test.ts b/packages/server/test/message.test.ts new file mode 100644 index 00000000000..787cd59b9ea --- /dev/null +++ b/packages/server/test/message.test.ts @@ -0,0 +1,102 @@ +import { expect } from "bun:test" +import { OpenCode, type SessionMessageInfo } from "@opencode/client" +import { Session } from "@opencode/schema/session" +import { Effect } from "effect" +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_assistant", + type: "assistant", + agent: "build", + model: { providerID: "test", id: "test" }, + content: [{ type: "text", text: "First answer" }], + finish: "stop", + time: { created: 400, completed: 500 }, + }, + { id: "msg_b", type: "user", text: "Second request", time: { created: 100 } }, + { id: "msg_synthetic", type: "synthetic", text: "Background completion", time: { created: 200 } }, + { + id: "msg_compaction", + type: "compaction", + status: "completed", + reason: "manual", + summary: "Conversation summary", + recent: "", + time: { created: 700 }, + }, + { id: "msg_x", type: "user", text: "Third request", time: { created: 600 } }, + { id: "msg_system", type: "system", text: "Updated instructions", time: { created: 800 } }, + { id: "msg_a", type: "user", text: "Fourth request", time: { created: 500 } }, +] + +const setup = Effect.gen(function* () { + const handler = yield* ServerFetch.make({ + app: { version: "test" }, + database: { path: ":memory:" }, + config: { project: false }, + models: { fetch: false }, + fs: { filewatcher: false }, + }) + const api = OpenCode.make({ + baseUrl: "http://opencode.local", + fetch: Object.assign((input: string | URL | Request, init?: RequestInit) => handler(new Request(input, init)), { + preconnect: fetch.preconnect, + }), + }) + const session = yield* Effect.promise(async () => { + const template = await api.session.create({ title: "Message filtering" }) + return api.session.import({ info: { ...template, id: Session.ID.create() }, messages }) + }) + return { api, handler, sessionID: session.id } +}) + +it.live("filters message types before paginating in either direction through the generated client", () => + Effect.gen(function* () { + const fixture = yield* setup + yield* Effect.promise(async () => { + const input = { sessionID: fixture.sessionID, type: "user", limit: 2 } as const + // Omission retains the full transcript, in durable sequence rather than timestamp or ID order. + expect( + (await fixture.api.message.list({ sessionID: fixture.sessionID })).data.map((message) => message.id), + ).toEqual(messages.toReversed().map((message) => message.id)) + for (const order of ["asc", "desc"] as const) { + const ids = order === "asc" ? ["msg_z", "msg_b", "msg_x", "msg_a"] : ["msg_a", "msg_x", "msg_b", "msg_z"] + const first = await fixture.api.message.list({ ...input, order }) + expect(first.data.map((message) => message.id)).toEqual(ids.slice(0, 2)) + if (!first.cursor.next) throw new Error("Expected a next cursor") + const second = await fixture.api.message.list({ ...input, cursor: first.cursor.next }) + expect(second.data.map((message) => message.id)).toEqual(ids.slice(2)) + if (!second.cursor.previous || !second.cursor.next) throw new Error("Expected previous and next cursors") + const previous = await fixture.api.message.list({ ...input, cursor: second.cursor.previous }) + expect(previous.data).toEqual(first.data) + const end = await fixture.api.message.list({ ...input, cursor: second.cursor.next }) + expect(end).toEqual({ data: [], cursor: { previous: null, next: null } }) + } + expect((await fixture.api.message.list({ sessionID: fixture.sessionID, type: "compaction" })).data).toEqual([ + messages[4], + ]) + expect( + (await fixture.api.message.list({ sessionID: fixture.sessionID, type: "assistant", limit: 1 })).data, + ).toEqual([messages[1]]) + expect((await fixture.api.message.list({ sessionID: fixture.sessionID, type: "shell" })).data).toEqual([]) + }) + }), +) + +it.live("rejects unknown message type filters at the HTTP boundary", () => + Effect.gen(function* () { + const fixture = yield* setup + yield* Effect.promise(async () => { + for (const type of ["unknown", "tool", "User", ""]) { + const response = await fixture.handler( + new Request(`http://opencode.local/api/session/${fixture.sessionID}/message?type=${type}`), + ) + expect(response.status).toBe(400) + expect(await response.json()).toMatchObject({ _tag: "InvalidRequestError" }) + } + }) + }), +) diff --git a/services/www/openapi.json b/services/www/openapi.json index a1110a58375..75b4c8d1de8 100644 --- a/services/www/openapi.json +++ b/services/www/openapi.json @@ -4490,6 +4490,34 @@ ] }, "required": false + }, + { + "name": "type", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "string", + "enum": [ + "agent-switched", + "model-switched", + "location-switched", + "user", + "synthetic", + "system", + "skill", + "shell", + "assistant", + "compaction" + ] + }, + { + "type": "null" + } + ], + "description": "Filter by message type before pagination. When omitted, all message types are returned. Pass the same type when following cursors." + }, + "required": false } ], "security": [], @@ -4552,7 +4580,7 @@ } } }, - "description": "Retrieve projected messages for a session. Items keep the requested order across pages; use cursor.next or cursor.previous to move through the ordered timeline.", + "description": "Retrieve projected messages for a session, optionally filtered by type. Items keep the requested order across pages; use cursor.next or cursor.previous to move through the ordered timeline, passing the same type filter on each page.", "summary": "Get session messages" } }, @@ -14243,6 +14271,9 @@ "compaction": { "$ref": "#/components/schemas/Provider.Compaction" }, + "websocket": { + "type": "boolean" + }, "modelID": { "type": "string" }, @@ -14351,6 +14382,9 @@ "compaction": { "$ref": "#/components/schemas/Provider.Compaction" }, + "websocket": { + "type": "boolean" + }, "canonical": { "type": "string" }, @@ -16297,6 +16331,9 @@ "compaction": { "$ref": "#/components/schemas/Provider.Compaction" }, + "websocket": { + "type": "boolean" + }, "settings": { "type": "object" }, @@ -17285,6 +17322,9 @@ "compaction": { "$ref": "#/components/schemas/Provider.Compaction" }, + "websocket": { + "type": "boolean" + }, "settings": { "type": "object" }, @@ -18256,6 +18296,12 @@ }, "providerContext": { "$ref": "#/components/schemas/Session.ProviderContext" + }, + "cost": { + "$ref": "#/components/schemas/Money.USD" + }, + "tokens": { + "$ref": "#/components/schemas/TokenUsage.Info" } }, "required": ["type", "id", "time", "status", "reason", "summary", "recent"], @@ -18295,6 +18341,12 @@ }, "error": { "$ref": "#/components/schemas/Session.StructuredError" + }, + "cost": { + "$ref": "#/components/schemas/Money.USD" + }, + "tokens": { + "$ref": "#/components/schemas/TokenUsage.Info" } }, "required": ["type", "id", "time", "status", "reason", "error"], diff --git a/services/www/public/openapi.json b/services/www/public/openapi.json index a1110a58375..75b4c8d1de8 100644 --- a/services/www/public/openapi.json +++ b/services/www/public/openapi.json @@ -4490,6 +4490,34 @@ ] }, "required": false + }, + { + "name": "type", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "string", + "enum": [ + "agent-switched", + "model-switched", + "location-switched", + "user", + "synthetic", + "system", + "skill", + "shell", + "assistant", + "compaction" + ] + }, + { + "type": "null" + } + ], + "description": "Filter by message type before pagination. When omitted, all message types are returned. Pass the same type when following cursors." + }, + "required": false } ], "security": [], @@ -4552,7 +4580,7 @@ } } }, - "description": "Retrieve projected messages for a session. Items keep the requested order across pages; use cursor.next or cursor.previous to move through the ordered timeline.", + "description": "Retrieve projected messages for a session, optionally filtered by type. Items keep the requested order across pages; use cursor.next or cursor.previous to move through the ordered timeline, passing the same type filter on each page.", "summary": "Get session messages" } }, @@ -14243,6 +14271,9 @@ "compaction": { "$ref": "#/components/schemas/Provider.Compaction" }, + "websocket": { + "type": "boolean" + }, "modelID": { "type": "string" }, @@ -14351,6 +14382,9 @@ "compaction": { "$ref": "#/components/schemas/Provider.Compaction" }, + "websocket": { + "type": "boolean" + }, "canonical": { "type": "string" }, @@ -16297,6 +16331,9 @@ "compaction": { "$ref": "#/components/schemas/Provider.Compaction" }, + "websocket": { + "type": "boolean" + }, "settings": { "type": "object" }, @@ -17285,6 +17322,9 @@ "compaction": { "$ref": "#/components/schemas/Provider.Compaction" }, + "websocket": { + "type": "boolean" + }, "settings": { "type": "object" }, @@ -18256,6 +18296,12 @@ }, "providerContext": { "$ref": "#/components/schemas/Session.ProviderContext" + }, + "cost": { + "$ref": "#/components/schemas/Money.USD" + }, + "tokens": { + "$ref": "#/components/schemas/TokenUsage.Info" } }, "required": ["type", "id", "time", "status", "reason", "summary", "recent"], @@ -18295,6 +18341,12 @@ }, "error": { "$ref": "#/components/schemas/Session.StructuredError" + }, + "cost": { + "$ref": "#/components/schemas/Money.USD" + }, + "tokens": { + "$ref": "#/components/schemas/TokenUsage.Info" } }, "required": ["type", "id", "time", "status", "reason", "error"],