From 9b2833ba317f9991691c5384fc39dace06b38c64 Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Wed, 4 Nov 2026 23:38:47 -0800 Subject: [PATCH] feat(core): make Session.spawn safe to retry with a caller-chosen id --- packages/core/src/session.ts | 44 +++++++++- packages/core/src/session/error.ts | 9 +++ packages/core/test/session-create.test.ts | 97 +++++++++++++++++++++++ packages/server/src/handlers/session.ts | 3 + 4 files changed, 151 insertions(+), 2 deletions(-) diff --git a/packages/core/src/session.ts b/packages/core/src/session.ts index fbabf45d184..6c85c2f5b8b 100644 --- a/packages/core/src/session.ts +++ b/packages/core/src/session.ts @@ -39,6 +39,7 @@ import { NotFoundError, PromptConflictError, SkillNotFoundError, + SpawnConflictError, SyntheticConflictError, } from "./session/error.js" import { Node } from "@opencode/util/effect/app-node" @@ -117,6 +118,12 @@ type CreatedFields = { } type SpawnInput = { + /** + * Child id chosen by the caller. A retry with the same id under the same parent returns the + * recorded child without admitting its prompt again. An id recorded under another parent, on a + * root Session, or equal to the parent fails with `SpawnConflictError`. + */ + readonly id?: SessionSchema.ID readonly parent: { readonly id: SessionSchema.ID; readonly notify?: boolean } readonly agent?: Agent.ID readonly model?: Model.Ref @@ -143,6 +150,7 @@ export { NotFoundError, PromptConflictError, SkillNotFoundError, + SpawnConflictError, SyntheticConflictError, } type InboxItemRef = { readonly sessionID: SessionSchema.ID; readonly inboxID: SessionMessage.ID } @@ -169,10 +177,19 @@ export interface Interface { * * The parent's model is inherited only when the agent is unchanged; otherwise the child keeps * no model and `SessionRunnerModel.resolve` picks the chosen agent's model. + * + * `id` makes the call safe to retry: an id already recorded under the same parent returns that + * child with its title, agent, model and metadata unchanged (the first admission wins), and the + * prompt is admitted only when the child has no messages and no pending inbox item. Reusing an id + * that belongs to another parent, to a root Session, or to the parent itself fails with + * `SpawnConflictError` before any prompt is admitted. */ readonly spawn: ( input: SpawnInput, - ) => Effect.Effect<{ readonly id: SessionSchema.ID }, NotFoundError | Effect.Error>> + ) => Effect.Effect< + { readonly id: SessionSchema.ID }, + NotFoundError | SpawnConflictError | Effect.Error> + > readonly fork: ( input: ForkInput, ) => Effect.Effect @@ -412,8 +429,12 @@ const layer = Layer.effect( }), spawn: Effect.fn("Session.spawn")(function* (input) { const parent = yield* result.get(input.parent.id) + // A retried spawn must not re-admit its prompt, so learn about the recorded child before + // createChild succeeds on its own idempotent path. + const recorded = input.id === undefined ? undefined : yield* store.get(input.id) const keepsAgent = input.agent === undefined || input.agent === parent.agent const child = yield* createChild(parent.id, { + id: input.id, title: input.title, agent: input.agent ?? parent.agent, // Only an unchanged agent inherits the parent's model; a different agent resolves its own. @@ -422,7 +443,26 @@ const layer = Layer.effect( // leaves createChild to keep the parent's metadata as-is. metadata: SubagentMetadata.withNotify(parent.metadata, input.parent.notify !== false), }) - if (input.prompt !== undefined) yield* result.prompt({ ...input.prompt, sessionID: child.id }) + // A reused id has to name a child of this parent: otherwise a foreign session, a root + // session or the parent itself would receive this prompt. Checked on the returned session, + // not only on `recorded`, because losing the concurrent projection race adopts a session + // created elsewhere. + if (child.parentID !== parent.id) + return yield* new SpawnConflictError({ sessionID: child.id, parentID: parent.id }) + // A retry only admits its prompt when the child has no work yet: a message or a pending + // inbox item means the first attempt (or a direct prompt) already started the child. + const alreadyStarted = + recorded !== undefined && + ((yield* result.inbox(child.id)).length > 0 || + (yield* db + .select({ id: SessionMessageTable.id }) + .from(SessionMessageTable) + .where(eq(SessionMessageTable.session_id, child.id)) + .limit(1) + .get() + .pipe(Effect.orDie)) !== undefined) + if (input.prompt !== undefined && !alreadyStarted) + yield* result.prompt({ ...input.prompt, sessionID: child.id }) return { id: child.id } }), fork: Effect.fn("Session.fork")(function* (input) { diff --git a/packages/core/src/session/error.ts b/packages/core/src/session/error.ts index 5d0fb7754ac..de1a19af0ad 100644 --- a/packages/core/src/session/error.ts +++ b/packages/core/src/session/error.ts @@ -94,6 +94,15 @@ export class InboxConflictError extends Schema.TaggedError() inboxID: SessionMessage.ID, }) {} +export class SpawnConflictError extends Schema.TaggedError()("Session.SpawnConflictError", { + sessionID: SessionSchema.ID, + parentID: SessionSchema.ID, +}) { + override get message() { + return `Session ${this.sessionID} already exists and is not a child of ${this.parentID}` + } +} + export class SkillNotFoundError extends Schema.TaggedError()("Session.SkillNotFoundError", { skill: Skill.ID, }) {} diff --git a/packages/core/test/session-create.test.ts b/packages/core/test/session-create.test.ts index 2e7219c5d56..67d9ebdf150 100644 --- a/packages/core/test/session-create.test.ts +++ b/packages/core/test/session-create.test.ts @@ -1417,6 +1417,103 @@ describe("Session.spawn", () => { expect((yield* session.list({ parentID: parent.id })).data.map((item) => item.id)).toEqual([childID]) }), ) + + it.effect("creates a child under the caller-chosen id", () => + Effect.gen(function* () { + const session = yield* Session.Service + const parent = yield* session.create({ location }) + const childID = Session.ID.create() + + const spawned = yield* session.spawn({ id: childID, parent: { id: parent.id }, title: "child" }) + + expect(spawned.id).toBe(childID) + expect(yield* session.get(childID)).toMatchObject({ parentID: parent.id, title: "child" }) + expect((yield* session.list({ parentID: parent.id })).data.map((item) => item.id)).toEqual([childID]) + }), + ) + + it.effect("does not re-admit the prompt when a spawn is retried", () => + Effect.gen(function* () { + const session = yield* Session.Service + const parent = yield* session.create({ location }) + const childID = Session.ID.create() + + const first = yield* session.spawn({ id: childID, parent: { id: parent.id }, prompt: { text: "do it" } }) + const retried = yield* session.spawn({ id: childID, parent: { id: parent.id }, prompt: { text: "do it" } }) + + expect(retried.id).toBe(first.id) + expect((yield* session.list({ parentID: parent.id })).data.map((item) => item.id)).toEqual([childID]) + expect(yield* session.inbox(childID)).toMatchObject([{ type: "user", payload: { text: "do it" } }]) + }), + ) + + it.effect("admits the prompt when the retried child was created without one", () => + Effect.gen(function* () { + const session = yield* Session.Service + const parent = yield* session.create({ location }) + const childID = Session.ID.create() + + yield* session.create({ id: childID, parentID: parent.id }) + const spawned = yield* session.spawn({ id: childID, parent: { id: parent.id }, prompt: { text: "do it" } }) + + expect(spawned.id).toBe(childID) + expect(yield* session.inbox(childID)).toMatchObject([{ type: "user", payload: { text: "do it" } }]) + }), + ) + + it.effect("rejects an id recorded under another parent", () => + Effect.gen(function* () { + const session = yield* Session.Service + const first = yield* session.create({ location }) + const second = yield* session.create({ location }) + const child = yield* session.spawn({ parent: { id: first.id } }) + + expect( + yield* Effect.flip( + session.spawn({ id: child.id, parent: { id: second.id }, prompt: { text: "do it" } }), + ), + ).toEqual(new Session.SpawnConflictError({ sessionID: child.id, parentID: second.id })) + expect(yield* session.inbox(child.id)).toEqual([]) + expect((yield* session.list({ parentID: second.id })).data).toEqual([]) + }), + ) + + it.effect("rejects the parent's own id", () => + Effect.gen(function* () { + const session = yield* Session.Service + const parent = yield* session.create({ location }) + + expect( + yield* Effect.flip(session.spawn({ id: parent.id, parent: { id: parent.id }, prompt: { text: "do it" } })), + ).toEqual(new Session.SpawnConflictError({ sessionID: parent.id, parentID: parent.id })) + expect(yield* session.inbox(parent.id)).toEqual([]) + }), + ) + + it.effect("rejects a root session's id", () => + Effect.gen(function* () { + const session = yield* Session.Service + const parent = yield* session.create({ location }) + const root = yield* session.create({ location }) + + expect(yield* Effect.flip(session.spawn({ id: root.id, parent: { id: parent.id }, prompt: { text: "do it" } }))).toEqual( + new Session.SpawnConflictError({ sessionID: root.id, parentID: parent.id }), + ) + expect(yield* session.inbox(root.id)).toEqual([]) + }), + ) + + it.effect("rejects a missing parent even when an id is supplied", () => + Effect.gen(function* () { + const session = yield* Session.Service + const missing = Session.ID.create() + + expect(yield* Effect.flip(session.spawn({ id: Session.ID.create(), parent: { id: missing } }))).toEqual( + new Session.NotFoundError({ sessionID: missing }), + ) + expect((yield* session.list({ parentID: missing })).data).toEqual([]) + }), + ) }) describe("SessionTransfer", () => { diff --git a/packages/server/src/handlers/session.ts b/packages/server/src/handlers/session.ts index 4a805fb59eb..52d6aafd095 100644 --- a/packages/server/src/handlers/session.ts +++ b/packages/server/src/handlers/session.ts @@ -337,6 +337,9 @@ export const SessionHandler = HttpApiBuilder.group(Api, "server.session", (handl }) .pipe( Effect.catchTag("Session.NotFoundError", missingSession), + Effect.catchTag("Session.SpawnConflictError", (error) => + Effect.fail(new ConflictError({ message: error.message, resource: error.sessionID })), + ), Effect.catchTag("Session.PromptConflictError", (error) => Effect.fail( new ConflictError({