refactor(schema): move session list cursor into schema (#56205)

This commit is contained in:
Aiden Cline
2026-10-16 17:01:13 -05:00
committed by GitHub
Unverified
parent d4a6223d01
commit c77e748dbf
10 changed files with 115 additions and 122 deletions
+2 -2
View File
@@ -1,6 +1,6 @@
import type { OpenCodeClient } from "@opencode/client/effect"
import { SessionsCursor } from "@opencode/protocol/groups/session"
import { AbsolutePath } from "@opencode/schema/schema"
import { Session } from "@opencode/schema/session"
import { FSUtil } from "@opencode/util/fs-util"
import { DateTime, Effect, Ref, Schema } from "effect"
import { withTimestampedFallback } from "@opencode/util/session-title-fallback"
@@ -170,7 +170,7 @@ export function make(input: {
: {}),
order: "desc",
limit: 100,
...(params.cursor ? { cursor: Schema.decodeSync(SessionsCursor)(params.cursor) } : {}),
...(params.cursor ? { cursor: Schema.decodeSync(Session.ListCursor)(params.cursor) } : {}),
})
.pipe(Effect.catch(ACPClient.classify))
return {
-2
View File
@@ -39,7 +39,6 @@ import { Snapshot } from "@opencode/schema/snapshot"
import { Vcs } from "@opencode/schema/vcs"
import { WebSearch } from "@opencode/schema/websearch"
import { Workspace } from "@opencode/schema/workspace"
import { SessionsCursor } from "@opencode/protocol/groups/session"
import { Effect, Schema } from "effect"
import { fileURLToPath } from "url"
@@ -89,7 +88,6 @@ const effectTypeReferences = [
typeReference("AgentAttachment", "@opencode/schema/prompt", AgentAttachment),
typeReference("AbsolutePath", "@opencode/schema/schema", AbsolutePath),
typeReference("RelativePath", "@opencode/schema/schema", RelativePath),
typeReference("SessionsCursor", "@opencode/protocol/groups/session", SessionsCursor),
]
await Effect.runPromise(
+5 -3
View File
@@ -7,7 +7,6 @@ import type { Session } from "@opencode/schema/session"
import type { AbsolutePath } from "@opencode/schema/schema"
import type { Project } from "@opencode/schema/project"
import type { RelativePath } from "@opencode/schema/schema"
import type { SessionsCursor } from "@opencode/protocol/groups/session"
import type { Money } from "@opencode/schema/money"
import type { Model } from "@opencode/schema/model"
import type { DateTime } from "effect"
@@ -125,11 +124,14 @@ export type SessionListInput = {
readonly directory?: AbsolutePath | undefined
readonly project?: Project.ID | undefined
readonly subpath?: RelativePath | undefined
readonly cursor?: SessionsCursor | undefined
readonly cursor?: Session.ListCursor | undefined
}
export type SessionListOutput = {
readonly data: ReadonlyArray<Session.Info>
readonly cursor: { readonly previous?: SessionsCursor | undefined; readonly next?: SessionsCursor | undefined }
readonly cursor: {
readonly previous?: Session.ListCursor | undefined
readonly next?: Session.ListCursor | undefined
}
}
export type SessionListOperation<E = never> = (input?: SessionListInput) => Effect.Effect<SessionListOutput, E>
+2 -2
View File
@@ -3,7 +3,7 @@ export * from "./session/schema.js"
import { Effect, Layer, Schema, Context, Stream } from "effect"
import { LLMClient } from "@opencode/ai"
import { ListAnchor } from "@opencode/schema/session"
import { ListAnchor, ListCursor } from "@opencode/schema/session"
import { and, desc, eq } from "drizzle-orm"
import { Project } from "./project.js"
import { Model } from "@opencode/schema/model"
@@ -75,7 +75,7 @@ import { InstructionEntry } from "./session/instruction-entry.js"
// - by subpath
// - by workspace (home is special)
export { ListAnchor }
export { ListAnchor, ListCursor }
export const ListInput = SessionStore.ListInput
export type ListInput = SessionStore.ListInput
+13 -92
View File
@@ -5,17 +5,9 @@ import { Session } from "@opencode/schema/session"
import { SessionStats } from "@opencode/schema/session-stats"
import { InstructionEntry } from "@opencode/schema/instruction-entry"
import { Project } from "@opencode/schema/project"
import {
AbsolutePath,
DateTimeUtcFromMillis,
NonNegativeInt,
PositiveInt,
RelativePath,
statics,
} from "@opencode/schema/schema"
import { DateTimeUtcFromMillis, NonNegativeInt, PositiveInt } from "@opencode/schema/schema"
import { Event } from "@opencode/schema/event"
import { Context, Effect, Result, Schema, SchemaGetter, SchemaParser, Struct } from "effect"
import { Base64Url } from "effect/encoding"
import { Context, Schema, SchemaGetter, Struct } from "effect"
import { HttpApiEndpoint, HttpApiGroup, HttpApiMiddleware, HttpApiSchema, OpenApi } from "effect/http-api"
import {
ConflictError,
@@ -45,81 +37,6 @@ import { FileDiff } from "@opencode/schema/file-diff"
import { Form } from "@opencode/schema/form"
import { PublicSessionMessage } from "./message.js"
const ParentIDFilter = Schema.Union([
Session.ID,
Schema.Null.pipe(
Schema.encodeTo(Schema.Literal("null"), {
decode: SchemaGetter.transform(() => null),
encode: SchemaGetter.transform(() => "null" as const),
}),
),
]).annotate({
description: "Filter by parent session. Use null to return only root sessions.",
})
const SessionsQueryFields = {
limit: Schema.NumberFromString.pipe(Schema.decodeTo(PositiveInt), Schema.optional).annotate({
description: "Maximum number of sessions to return. Defaults to the newest 50 sessions.",
}),
order: Schema.optional(Schema.Union([Schema.Literal("asc"), Schema.Literal("desc")])).annotate({
description: "Session order for the first page. Use desc for newest first or asc for oldest first.",
}),
search: Schema.optional(Schema.String),
parentID: ParentIDFilter.pipe(Schema.optional),
}
const SessionsDirectoryQuery = Schema.Struct({
...SessionsQueryFields,
directory: AbsolutePath,
})
const SessionsProjectQuery = Schema.Struct({
...SessionsQueryFields,
project: Project.ID,
subpath: RelativePath.pipe(Schema.optional),
})
const SessionsAllQuery = Schema.Struct(SessionsQueryFields)
const withCursor = <Fields extends Schema.Struct.Fields>(schema: Schema.Struct<Fields>) =>
schema.mapFields((fields) => ({
...Struct.omit(fields, ["limit"]),
anchor: Session.ListAnchor,
}))
const SessionsCursorInput = Schema.Union([
withCursor(SessionsDirectoryQuery),
withCursor(SessionsProjectQuery),
withCursor(SessionsAllQuery),
])
const SessionsCursorJson = Schema.fromJsonString(SessionsCursorInput)
const encodeSessionsCursor = Schema.encodeSync(SessionsCursorJson)
const decodeSessionsCursor = Schema.decodeUnknownEffect(SessionsCursorJson)
const invalidCursor = "Invalid cursor" as const
export const SessionsCursor = Schema.String.pipe(
Schema.brand("SessionsCursor"),
Schema.annotate({
identifier: "SessionsCursor",
description: "Opaque pagination cursor returned as cursor.previous or cursor.next in the previous response.",
}),
statics((schema) => {
// Read the default constructor without caching it on the schema, so `make` can be replaced.
const make = SchemaParser.make(schema)
return {
make: (input: typeof SessionsCursorInput.Type) => make(Base64Url.encode(encodeSessionsCursor(input))),
parse: (input: string) =>
Effect.suspend(() => {
const result = Base64Url.decodeString(input)
return Result.isFailure(result)
? Effect.fail(invalidCursor)
: decodeSessionsCursor(result.success).pipe(Effect.mapError(() => invalidCursor))
}),
}
}),
)
export type SessionsCursor = typeof SessionsCursor.Type
const SessionActive = Schema.Struct({
type: Schema.Literal("running"),
}).annotate({ identifier: "SessionActive" })
@@ -165,12 +82,16 @@ const BooleanFromString = Schema.Literals(["true", "false"]).pipe(
}),
)
// Kept so existing imports of SessionsCursor from Protocol keep working.
export const SessionsCursor = Session.ListCursor
export type SessionsCursor = Session.ListCursor
export const SessionsQuery = Schema.Struct({
...SessionsQueryFields,
directory: AbsolutePath.pipe(Schema.optional),
project: Project.ID.pipe(Schema.optional),
subpath: RelativePath.pipe(Schema.optional),
cursor: SessionsCursor.pipe(Schema.optional),
limit: Schema.NumberFromString.pipe(Schema.decodeTo(PositiveInt), Schema.optional).annotate({
description: "Maximum number of sessions to return. Defaults to the newest 50 sessions.",
}),
...Session.ListFilter.fields,
cursor: Session.ListCursor.pipe(Schema.optional),
}).annotate({ identifier: "SessionsQuery" })
export const makeSessionGroup = <I extends HttpApiMiddleware.AnyId, S, FormI extends HttpApiMiddleware.AnyId, FormS>(
@@ -184,8 +105,8 @@ export const makeSessionGroup = <I extends HttpApiMiddleware.AnyId, S, FormI ext
success: Schema.Struct({
data: Schema.Array(PublicSessionInfo),
cursor: Schema.Struct({
previous: SessionsCursor.pipe(Schema.optional),
next: SessionsCursor.pipe(Schema.optional),
previous: Session.ListCursor.pipe(Schema.optional),
next: Session.ListCursor.pipe(Schema.optional),
}),
}).annotate({ identifier: "SessionsResponse" }),
error: [InvalidCursorError, InvalidRequestError],
+4 -15
View File
@@ -1,18 +1,7 @@
import { describe, expect, test } from "bun:test"
import { Effect } from "effect"
import { SessionsCursor } from "../src/groups/session.js"
import { expect, test } from "bun:test"
import { Session } from "@opencode/schema/session"
import { SessionsCursor } from "../src/groups/session.js"
describe("SessionsCursor", () => {
test("round trips without Node globals", async () => {
const input = {
workspace: undefined,
search: "protocol",
order: "desc" as const,
anchor: { id: Session.ID.make("ses_test"), time: 1, direction: "next" as const },
}
const cursor = SessionsCursor.make(input)
expect(await Effect.runPromise(SessionsCursor.parse(cursor))).toEqual(input)
})
test("SessionsCursor remains the canonical session list cursor", () => {
expect(SessionsCursor).toBe(Session.ListCursor)
})
+68 -2
View File
@@ -1,11 +1,12 @@
export * as Session from "./session.js"
import { Schema } from "effect"
import { Effect, Result, Schema, SchemaGetter, SchemaParser } from "effect"
import { Base64Url } from "effect/encoding"
import { Agent } from "./agent.js"
import { Location } from "./location.js"
import { Model } from "./model.js"
import { Project } from "./project.js"
import { DateTimeUtcFromMillis, optional, RelativePath } from "./schema.js"
import { AbsolutePath, DateTimeUtcFromMillis, optional, RelativePath, statics } from "./schema.js"
import { SessionEvent } from "./session-event.js"
import { SessionID } from "./session-id.js"
import { SessionMetadata } from "./session-metadata.js"
@@ -64,3 +65,68 @@ export const ListAnchor = Schema.Struct({
direction: Schema.Literals(["previous", "next"]),
}).annotate({ identifier: "Session.ListAnchor" })
export interface ListAnchor extends Schema.Schema.Type<typeof ListAnchor> {}
// These fields are also the session.list HTTP query parameters. Raw Schema.optional keeps that
// endpoint's OpenAPI parameters unchanged.
const ListFilterFields = {
order: Schema.Literals(["asc", "desc"]).pipe(Schema.optional).annotate({
description: "Session order for the first page. Use desc for newest first or asc for oldest first.",
}),
search: Schema.String.pipe(Schema.optional),
parentID: Schema.Union([
ID,
Schema.Null.pipe(
Schema.encodeTo(Schema.Literal("null"), {
decode: SchemaGetter.transform(() => null),
encode: SchemaGetter.transform(() => "null" as const),
}),
),
])
.annotate({ description: "Filter by parent session. Use null to return only root sessions." })
.pipe(Schema.optional),
}
export const ListFilter = Schema.Struct({
...ListFilterFields,
directory: AbsolutePath.pipe(Schema.optional),
project: Project.ID.pipe(Schema.optional),
subpath: RelativePath.pipe(Schema.optional),
}).annotate({ identifier: "Session.ListFilter" })
export interface ListFilter extends Schema.Schema.Type<typeof ListFilter> {}
const ListCursorInput = Schema.Union([
Schema.Struct({ ...ListFilterFields, directory: AbsolutePath, anchor: ListAnchor }),
Schema.Struct({
...ListFilterFields,
project: Project.ID,
subpath: RelativePath.pipe(Schema.optional),
anchor: ListAnchor,
}),
Schema.Struct({ ...ListFilterFields, anchor: ListAnchor }),
])
const ListCursorJson = Schema.fromJsonString(ListCursorInput)
const encodeListCursor = Schema.encodeSync(ListCursorJson)
const decodeListCursor = Schema.decodeUnknownEffect(ListCursorJson)
export const ListCursor = Schema.String.pipe(
Schema.brand("SessionsCursor"),
Schema.annotate({
identifier: "SessionsCursor",
description: "Opaque pagination cursor returned as cursor.previous or cursor.next in the previous response.",
}),
statics((schema) => {
// Read the default constructor without caching it on the schema, so `make` can be replaced.
const make = SchemaParser.make(schema)
return {
make: (input: typeof ListCursorInput.Type) => make(Base64Url.encode(encodeListCursor(input))),
parse: (input: string) =>
Effect.suspend(() => {
const result = Base64Url.decodeString(input)
return Result.isFailure(result)
? Effect.fail("Invalid cursor" as const)
: decodeListCursor(result.success).pipe(Effect.mapError(() => "Invalid cursor" as const))
}),
}
}),
)
export type ListCursor = typeof ListCursor.Type
@@ -196,6 +196,8 @@ describe("contract hygiene", () => {
Project.Info,
Pty.Info,
Session.ListAnchor,
Session.ListCursor,
Session.ListFilter,
Session.Revert,
SessionInbox.Delivery,
SessionInbox.UserPayload,
@@ -0,0 +1,16 @@
import { describe, expect, test } from "bun:test"
import { Effect } from "effect"
import { Session } from "../src/session.js"
describe("Session.ListCursor", () => {
test("round trips without Node globals", async () => {
const input = {
search: "protocol",
order: "desc" as const,
anchor: { id: Session.ID.make("ses_test"), time: 1, direction: "next" as const },
}
const cursor = Session.ListCursor.make(input)
expect(await Effect.runPromise(Session.ListCursor.parse(cursor))).toEqual(input)
})
})
+3 -4
View File
@@ -7,7 +7,6 @@ import { Form } from "@opencode/core/form"
import { DateTime, Effect, Stream } from "effect"
import { HttpApiBuilder, HttpApiSchema } from "effect/http-api"
import { Api } from "../api"
import { SessionsCursor } from "@opencode/protocol/groups/session"
import {
ConflictError,
CommandExecutionError,
@@ -63,7 +62,7 @@ export const SessionHandler = HttpApiBuilder.group(Api, "server.session", (handl
Effect.fn(function* (ctx) {
const query =
ctx.query.cursor !== undefined
? yield* SessionsCursor.parse(ctx.query.cursor).pipe(
? yield* Session.ListCursor.parse(ctx.query.cursor).pipe(
Effect.mapError(() => new InvalidCursorError({ message: "Invalid cursor" })),
)
: ctx.query
@@ -78,7 +77,7 @@ export const SessionHandler = HttpApiBuilder.group(Api, "server.session", (handl
data: sessions,
cursor: {
previous: first
? SessionsCursor.make({
? Session.ListCursor.make({
...query,
anchor: {
id: first.id,
@@ -88,7 +87,7 @@ export const SessionHandler = HttpApiBuilder.group(Api, "server.session", (handl
})
: undefined,
next: last
? SessionsCursor.make({
? Session.ListCursor.make({
...query,
anchor: {
id: last.id,