From c77e748dbf7c4d2c75515bcc2db7740d0552634b Mon Sep 17 00:00:00 2001 From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Date: Fri, 16 Oct 2026 17:01:13 -0500 Subject: [PATCH] refactor(schema): move session list cursor into schema (#56205) --- packages/cli/src/acp/service.ts | 4 +- packages/client/script/build.ts | 2 - packages/client/src/effect/api/api.ts | 8 +- packages/core/src/session.ts | 4 +- packages/protocol/src/groups/session.ts | 105 +++--------------- packages/protocol/test/session-cursor.test.ts | 19 +--- packages/schema/src/session.ts | 70 +++++++++++- packages/schema/test/contract-hygiene.test.ts | 2 + packages/schema/test/session-cursor.test.ts | 16 +++ packages/server/src/handlers/session.ts | 7 +- 10 files changed, 115 insertions(+), 122 deletions(-) create mode 100644 packages/schema/test/session-cursor.test.ts diff --git a/packages/cli/src/acp/service.ts b/packages/cli/src/acp/service.ts index 4e10bea164c..bdcca8201cf 100644 --- a/packages/cli/src/acp/service.ts +++ b/packages/cli/src/acp/service.ts @@ -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 { diff --git a/packages/client/script/build.ts b/packages/client/script/build.ts index 83043db2de3..3578769e589 100644 --- a/packages/client/script/build.ts +++ b/packages/client/script/build.ts @@ -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( diff --git a/packages/client/src/effect/api/api.ts b/packages/client/src/effect/api/api.ts index 4580c6bbfe3..c44e46f0eed 100644 --- a/packages/client/src/effect/api/api.ts +++ b/packages/client/src/effect/api/api.ts @@ -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 - 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 = (input?: SessionListInput) => Effect.Effect diff --git a/packages/core/src/session.ts b/packages/core/src/session.ts index 39f5f36d3a5..eae82e1c6dd 100644 --- a/packages/core/src/session.ts +++ b/packages/core/src/session.ts @@ -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 diff --git a/packages/protocol/src/groups/session.ts b/packages/protocol/src/groups/session.ts index a9ee5069e59..44e3bddcf8e 100644 --- a/packages/protocol/src/groups/session.ts +++ b/packages/protocol/src/groups/session.ts @@ -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 = (schema: Schema.Struct) => - 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 = ( @@ -184,8 +105,8 @@ export const makeSessionGroup = { - 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) }) diff --git a/packages/schema/src/session.ts b/packages/schema/src/session.ts index b94f0eb2eb6..6ca940ac271 100644 --- a/packages/schema/src/session.ts +++ b/packages/schema/src/session.ts @@ -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 {} + +// 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 {} + +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 diff --git a/packages/schema/test/contract-hygiene.test.ts b/packages/schema/test/contract-hygiene.test.ts index 030e4d18e46..4c41586b4d5 100644 --- a/packages/schema/test/contract-hygiene.test.ts +++ b/packages/schema/test/contract-hygiene.test.ts @@ -196,6 +196,8 @@ describe("contract hygiene", () => { Project.Info, Pty.Info, Session.ListAnchor, + Session.ListCursor, + Session.ListFilter, Session.Revert, SessionInbox.Delivery, SessionInbox.UserPayload, diff --git a/packages/schema/test/session-cursor.test.ts b/packages/schema/test/session-cursor.test.ts new file mode 100644 index 00000000000..54bc5cff7df --- /dev/null +++ b/packages/schema/test/session-cursor.test.ts @@ -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) + }) +}) diff --git a/packages/server/src/handlers/session.ts b/packages/server/src/handlers/session.ts index dd85c2f4ff5..79eb77a803d 100644 --- a/packages/server/src/handlers/session.ts +++ b/packages/server/src/handlers/session.ts @@ -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,