feat(api): filter session messages by type (#48228)

This commit is contained in:
Aiden Cline
2026-09-09 19:01:16 -05:00
committed by GitHub
Unverified
parent 0f67a15f3b
commit 30f8b2f4b6
11 changed files with 355 additions and 10 deletions
+12
View File
@@ -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<SessionMessage.Info>
@@ -757,7 +757,7 @@ const EndpointMessageList = (raw: RawClient["server.message"]) => (input: Messag
preserveEffect<MessageListOutput>()(
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)),
)
@@ -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,
@@ -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
+8 -4
View File
@@ -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,
+53 -1
View File
@@ -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"],
+18 -1
View File
@@ -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<SessionMessage.Type>),
).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.",
}),
),
)
+1
View File
@@ -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(
+102
View File
@@ -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" })
}
})
}),
)
+53 -1
View File
@@ -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"],
+53 -1
View File
@@ -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"],