This commit is contained in:
Hafiar 2026-11-26 21:36:28 +00:00 • committed by GitHub
commit bcb5b702ae
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 110 additions and 6 deletions

View file

@ -4,7 +4,7 @@ export * from "./session/schema.js"
import { DateTime, Effect, Layer, Context, Option, Stream } from "effect"
import { LLMClient } from "@opencode/ai/effect"
import { ListAnchor, ListCursor, ListFilter } from "@opencode/schema/session"
import { and, desc, eq } from "drizzle-orm"
import { and, desc, eq, sql } from "drizzle-orm"
import { Project } from "./project.js"
import { Model } from "@opencode/schema/model"
import { Location } from "./location.js"
@ -42,6 +42,7 @@ import {
PromptConflictError,
SkillNotFoundError,
SyntheticConflictError,
UnmigratedError,
} from "./session/error.js"
import { Node } from "@opencode/util/effect/app-node"
import { LayerNode } from "@opencode/util/effect/layer-node"
@ -121,6 +122,7 @@ export {
PromptConflictError,
SkillNotFoundError,
SyntheticConflictError,
UnmigratedError,
}
type InboxItemRef = { readonly sessionID: SessionSchema.ID; readonly inboxID: SessionMessage.ID }
@ -136,7 +138,7 @@ export interface Interface {
},
InvalidListCursorError
>
readonly create: (input: CreateInput) => Effect.Effect<SessionSchema.Info, NotFoundError>
readonly create: (input: CreateInput) => Effect.Effect<SessionSchema.Info, NotFoundError | UnmigratedError>
readonly fork: (
input: ForkInput,
) => Effect.Effect<SessionSchema.Info, NotFoundError | MessageNotFoundError | ForkEmptyError>
@ -303,6 +305,18 @@ const layer = Layer.effect(
const sessionID = input.id ?? SessionSchema.ID.create()
const recorded = yield* store.get(sessionID)
if (recorded) return recorded
if (input.id) {
// An ID still held by an unmigrated V1 session must not be reused:
// the new row would resolve globally and hide the original session,
// whose history only exists in the legacy `session` table.
const legacyTable = yield* db
.get(sql`SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'session'`)
.pipe(Effect.orDie)
if (legacyTable) {
const legacy = yield* db.get(sql`SELECT id FROM session WHERE id = ${sessionID}`).pipe(Effect.orDie)
if (legacy) return yield* new UnmigratedError({ sessionID })
}
}
const parent = input.parentID ? yield* store.get(input.parentID) : undefined
if (input.parentID && parent === undefined) return yield* new NotFoundError({ sessionID: input.parentID })
const location = parent?.location ?? (input.location && LocationServiceMap.canonical(input.location))

View file

@ -11,6 +11,14 @@ export class NotFoundError extends Schema.TaggedError<NotFoundError>()("Session.
sessionID: SessionSchema.ID,
}) {}
export class UnmigratedError extends Schema.TaggedError<UnmigratedError>()("Session.UnmigratedError", {
sessionID: SessionSchema.ID,
}) {
override get message() {
return `Session exists in V1 data but was not migrated: ${this.sessionID}`
}
}
export class InvalidListCursorError extends Schema.TaggedError<InvalidListCursorError>()(
"Session.InvalidListCursorError",
{},

View file

@ -8,7 +8,7 @@ import { Money } from "@opencode/schema/money"
import { Shell } from "@opencode/schema/shell"
import { Skill } from "@opencode/schema/skill"
import { Agent } from "@opencode/core/agent"
import { and, asc, eq } from "drizzle-orm"
import { and, asc, eq, sql } from "drizzle-orm"
import { Database } from "@opencode/core/database/database"
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
import { LayerNode } from "@opencode/util/effect/layer-node"
@ -397,6 +397,55 @@ describe("Session.create", () => {
}),
)
it.effect("returns the original session when the ID is retried", () =>
Effect.gen(function* () {
const session = yield* Session.Service
const input = { id, location }
const first = yield* session.create(input)
const retried = yield* session.create(input)
expect(retried).toEqual(first)
expect((yield* session.list()).data).toEqual([first])
}),
)
it.effect("rejects creation when the ID is held by an unmigrated V1 session", () =>
Effect.gen(function* () {
const session = yield* Session.Service
const { db } = yield* Database.Service
const legacyID = Session.ID.create()
yield* db.run(sql`CREATE TABLE IF NOT EXISTS session (id text PRIMARY KEY, title text)`)
yield* db.run(sql`INSERT INTO session (id, title) VALUES (${legacyID}, 'Original V1 session')`)
const error = yield* Effect.flip(session.create({ id: legacyID, location }))
expect(error).toEqual(new Session.UnmigratedError({ sessionID: legacyID }))
expect(error.message).toBe(`Session exists in V1 data but was not migrated: ${legacyID}`)
// No shadow row is projected into the V2 store, and the V1 row is untouched.
expect((yield* session.list()).data).toEqual([])
expect(
yield* db.get<{ value: number }>(sql`SELECT COUNT(*) AS value FROM session WHERE id = ${legacyID}`),
).toEqual({
value: 1,
})
}),
)
it.effect("creates with an explicit ID when the V1 table holds only other sessions", () =>
Effect.gen(function* () {
const session = yield* Session.Service
const { db } = yield* Database.Service
yield* db.run(sql`CREATE TABLE IF NOT EXISTS session (id text PRIMARY KEY, title text)`)
yield* db.run(sql`INSERT INTO session (id, title) VALUES (${Session.ID.create()}, 'Other V1 session')`)
const created = yield* session.create({ id, location })
expect(created.id).toBe(id)
const fresh = yield* session.create({ location })
expect(fresh.id).not.toBe(created.id)
expect((yield* session.list()).data).toHaveLength(2)
}),
)
it.effect("stores supplied immutable create attributes", () =>
Effect.gen(function* () {
const session = yield* Session.Service

View file

@ -15,6 +15,13 @@ export function skillLoadFailed(error: Skill.LoadError) {
return new SkillLoadError({ skill: Skill.ID.make(error.skill), message: error.message })
}
export function unmigratedSession(error: Session.UnmigratedError) {
return new SessionNotFoundError({
sessionID: error.sessionID,
message: error.message,
})
}
export function missingMessage(error: Session.MessageNotFoundError) {
return new MessageNotFoundError({
sessionID: error.sessionID,

View file

@ -28,7 +28,14 @@ import {
} from "@opencode/protocol/errors"
import { AbsolutePath } from "@opencode/core/schema"
import { locationErrors } from "../location"
import { failedMessageDecode, failedSnapshot, missingMessage, missingSession, skillLoadFailed } from "./session-error"
import {
failedMessageDecode,
failedSnapshot,
missingMessage,
missingSession,
skillLoadFailed,
unmigratedSession,
} from "./session-error"
function missingForm(id: Form.ID) {
return new FormNotFoundError({ id, message: `Form not found: ${id}` })
@ -118,7 +125,10 @@ export const SessionHandler = HttpApiBuilder.group(Api, "server.session", (handl
? { location: ctx.payload.location ?? { directory: AbsolutePath.make(process.cwd()) } }
: { parentID: ctx.payload.parentID }),
})
.pipe(Effect.catchTag("Session.NotFoundError", missingSession)),
.pipe(
Effect.catchTag("Session.NotFoundError", missingSession),
Effect.catchTag("Session.UnmigratedError", unmigratedSession),
),
}
}),
)

View file

@ -3,7 +3,7 @@ import { SessionMessage } from "@opencode/core/session/message"
import { SessionNotFoundError, UnknownError } from "@opencode/protocol/errors"
import { expect, test } from "bun:test"
import { Effect, Logger, References } from "effect"
import { failedMessageDecode, missingSession } from "../src/handlers/session-error"
import { failedMessageDecode, missingSession, unmigratedSession } from "../src/handlers/session-error"
test("yieldable session errors preserve the handler failure policy", async () => {
const sessionID = Session.ID.create()
@ -18,6 +18,22 @@ test("yieldable session errors preserve the handler failure policy", async () =>
expect(error).toMatchObject({ sessionID, message: `Session not found: ${sessionID}` })
})
test("unmigrated V1 session errors keep the 404 shape with a distinct message", async () => {
const sessionID = Session.ID.create()
const error = await Effect.runPromise(
Effect.fail(new Session.UnmigratedError({ sessionID })).pipe(
Effect.catchTag("Session.UnmigratedError", unmigratedSession),
Effect.flip,
),
)
expect(error).toBeInstanceOf(SessionNotFoundError)
expect(error).toMatchObject({
sessionID,
message: `Session exists in V1 data but was not migrated: ${sessionID}`,
})
})
test("message decode policy preserves its reference and log annotations", async () => {
const sessionID = Session.ID.create()
const messageID = SessionMessage.ID.create()