mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-17 05:26:47 +03:00
feat(core): return outcome and text from Session.wait
This commit is contained in:
@@ -80,6 +80,8 @@ import { SubagentMetadata } from "./session/subagent-metadata.js"
|
||||
|
||||
export { ListAnchor, ListCursor }
|
||||
|
||||
export type { WaitResult } from "./session/session.js"
|
||||
|
||||
export const ListInput = SessionStore.ListInput
|
||||
export type ListInput = SessionStore.ListInput
|
||||
|
||||
@@ -276,7 +278,8 @@ export interface Interface {
|
||||
readonly compact: (
|
||||
input: CompactInput,
|
||||
) => Effect.Effect<SessionInbox.Compaction, NotFoundError | CompactionConflictError>
|
||||
readonly wait: (id: SessionSchema.ID) => Effect.Effect<void, NotFoundError>
|
||||
/** Waits until the session is idle, then returns its last outcome and newest completed, error-free assistant text. */
|
||||
readonly wait: (id: SessionSchema.ID) => ReturnType<Session.Handle["wait"]>
|
||||
readonly active: Effect.Effect<ReadonlySet<SessionSchema.ID>>
|
||||
readonly background: (sessionID: SessionSchema.ID) => Effect.Effect<void, NotFoundError>
|
||||
readonly resume: (sessionID: SessionSchema.ID) => Effect.Effect<void, NotFoundError | SessionRunner.RunError>
|
||||
|
||||
@@ -29,12 +29,28 @@ import { SessionShell } from "./shell.js"
|
||||
import { SessionSkill } from "./skill.js"
|
||||
import { SessionSchema } from "./schema.js"
|
||||
import { SessionStore } from "./store.js"
|
||||
import { SubagentCompletion } from "./subagent-completion.js"
|
||||
|
||||
type PromptRequest = SessionPrompt.Input & {
|
||||
id?: SessionMessage.ID
|
||||
resume?: boolean
|
||||
}
|
||||
|
||||
/** What a waiting parent gets back once its child goes idle. */
|
||||
export type WaitResult = {
|
||||
/**
|
||||
* Outcome of the most recent busy period that reached a terminal transition. Absent when the
|
||||
* session never ran; a shutdown interrupt leaves the previous outcome in place.
|
||||
*/
|
||||
readonly outcome: SessionSchema.Info["outcome"]
|
||||
/**
|
||||
* Text of the newest completed, error-free assistant answer, or `SubagentCompletion.NO_TEXT`.
|
||||
* Read regardless of outcome, so a failed or interrupted period can still return an earlier
|
||||
* good answer.
|
||||
*/
|
||||
readonly text: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Build once in the host Scope: `const sessions = yield* Session.make()`.
|
||||
* Use `sessions.forSession(id)` for handles that share host services and reload current state.
|
||||
@@ -278,6 +294,14 @@ export const make = Effect.fn("Session.make")(function* () {
|
||||
const wait = Effect.fn("Session.wait")(function* (sessionID: SessionSchema.ID) {
|
||||
yield* get(sessionID)
|
||||
yield* execution.awaitIdle(sessionID)
|
||||
// Read again after idle: the terminal event writes `idle_outcome` before the deferred behind
|
||||
// `awaitIdle` resolves, so the first get would carry the previous period's outcome.
|
||||
const session = yield* get(sessionID)
|
||||
const messages = yield* store.messages({ sessionID, order: "desc", limit: 20, type: "assistant" })
|
||||
const assistant = messages.find(
|
||||
(message) => message.type === "assistant" && message.time.completed !== undefined && message.error === undefined,
|
||||
)
|
||||
return { outcome: session.outcome, text: SubagentCompletion.text(assistant) } satisfies WaitResult
|
||||
})
|
||||
const resume = Effect.fn("Session.resume")(function* (sessionID: SessionSchema.ID) {
|
||||
yield* get(sessionID)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { describe, expect } from "bun:test"
|
||||
import { eq } from "drizzle-orm"
|
||||
import { Effect, Layer } from "effect"
|
||||
import { Database } from "@opencode/core/database/database"
|
||||
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
|
||||
@@ -10,14 +11,22 @@ import { AbsolutePath } from "@opencode/core/schema"
|
||||
import { Session } from "@opencode/core/session"
|
||||
import { SessionProjector } from "@opencode/core/session/projector"
|
||||
import { SessionExecution } from "@opencode/core/session/execution"
|
||||
import { SessionMessageTable, SessionTable } from "@opencode/core/session/sql"
|
||||
import { SessionStore } from "@opencode/core/session/store"
|
||||
import { SubagentCompletion } from "@opencode/core/session/subagent-completion"
|
||||
import { Agent } from "@opencode/schema/agent"
|
||||
import { Model } from "@opencode/schema/model"
|
||||
import { Provider } from "@opencode/schema/provider"
|
||||
import { SessionMessage } from "@opencode/schema/session-message"
|
||||
import { testEffect } from "./lib/effect"
|
||||
import { globalProjectNode } from "./lib/project"
|
||||
|
||||
const location = Location.Ref.make({ directory: AbsolutePath.make("/project") })
|
||||
const awaited: Session.ID[] = []
|
||||
let duringIdle: Effect.Effect<void> = Effect.void
|
||||
const execution = Layer.mock(SessionExecution.Service, {
|
||||
awaitIdle: (sessionID) => Effect.sync(() => awaited.push(sessionID)),
|
||||
awaitIdle: (sessionID) =>
|
||||
Effect.sync(() => awaited.push(sessionID)).pipe(Effect.flatMap(() => Effect.suspend(() => duringIdle))),
|
||||
})
|
||||
const it = testEffect(
|
||||
AppNodeBuilder.build(
|
||||
@@ -26,16 +35,133 @@ const it = testEffect(
|
||||
),
|
||||
)
|
||||
|
||||
const agent = Agent.ID.make("build")
|
||||
const model = { providerID: Provider.ID.make("anthropic"), id: Model.ID.make("claude-sonnet-4-5") }
|
||||
|
||||
const seedAssistant = (
|
||||
sessionID: Session.ID,
|
||||
input: {
|
||||
id: string
|
||||
seq: number
|
||||
text?: string
|
||||
completed?: boolean
|
||||
failed?: boolean
|
||||
},
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const database = yield* Database.Service
|
||||
yield* database.db
|
||||
.insert(SessionMessageTable)
|
||||
.values({
|
||||
id: SessionMessage.ID.make(input.id),
|
||||
session_id: sessionID,
|
||||
seq: input.seq,
|
||||
type: "assistant",
|
||||
time_created: input.seq,
|
||||
time_updated: input.seq,
|
||||
data: {
|
||||
agent,
|
||||
model,
|
||||
content: input.text === undefined ? [] : [{ type: "text", text: input.text }],
|
||||
...(input.failed ? { error: { type: "unknown", message: "boom" } } : {}),
|
||||
time: { created: input.seq, ...(input.completed === false ? {} : { completed: input.seq + 1 }) },
|
||||
},
|
||||
})
|
||||
.run()
|
||||
})
|
||||
|
||||
describe("Session.wait", () => {
|
||||
it.effect("delegates to SessionExecution.awaitIdle", () =>
|
||||
it.effect("delegates to SessionExecution.awaitIdle and returns an empty result for a fresh session", () =>
|
||||
Effect.gen(function* () {
|
||||
awaited.length = 0
|
||||
duringIdle = Effect.void
|
||||
const sessions = yield* Session.Service
|
||||
const session = yield* sessions.create({ location })
|
||||
|
||||
yield* sessions.wait(session.id)
|
||||
const result = yield* sessions.wait(session.id)
|
||||
|
||||
expect(awaited).toEqual([session.id])
|
||||
expect(result).toEqual({ outcome: undefined, text: SubagentCompletion.NO_TEXT })
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("returns the newest completed answer", () =>
|
||||
Effect.gen(function* () {
|
||||
duringIdle = Effect.void
|
||||
const sessions = yield* Session.Service
|
||||
const session = yield* sessions.create({ location })
|
||||
yield* seedAssistant(session.id, { id: "msg_wait_old", seq: 1, text: "older answer" })
|
||||
yield* seedAssistant(session.id, { id: "msg_wait_new", seq: 2, text: "newer answer" })
|
||||
|
||||
expect((yield* sessions.wait(session.id)).text).toBe("newer answer")
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("skips an incomplete newest answer", () =>
|
||||
Effect.gen(function* () {
|
||||
duringIdle = Effect.void
|
||||
const sessions = yield* Session.Service
|
||||
const session = yield* sessions.create({ location })
|
||||
yield* seedAssistant(session.id, { id: "msg_wait_done", seq: 1, text: "done answer" })
|
||||
yield* seedAssistant(session.id, { id: "msg_wait_partial", seq: 2, text: "still streaming", completed: false })
|
||||
|
||||
expect((yield* sessions.wait(session.id)).text).toBe("done answer")
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("skips a failed newest answer", () =>
|
||||
Effect.gen(function* () {
|
||||
duringIdle = Effect.void
|
||||
const sessions = yield* Session.Service
|
||||
const session = yield* sessions.create({ location })
|
||||
yield* seedAssistant(session.id, { id: "msg_wait_good", seq: 1, text: "good answer" })
|
||||
yield* seedAssistant(session.id, { id: "msg_wait_failed", seq: 2, text: "failed answer", failed: true })
|
||||
|
||||
expect((yield* sessions.wait(session.id)).text).toBe("good answer")
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("returns NO_TEXT when the newest assistant has no text parts", () =>
|
||||
Effect.gen(function* () {
|
||||
duringIdle = Effect.void
|
||||
const sessions = yield* Session.Service
|
||||
const session = yield* sessions.create({ location })
|
||||
yield* seedAssistant(session.id, { id: "msg_wait_empty", seq: 1 })
|
||||
|
||||
expect((yield* sessions.wait(session.id)).text).toBe(SubagentCompletion.NO_TEXT)
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("reads the outcome after awaitIdle settles", () =>
|
||||
Effect.gen(function* () {
|
||||
const sessions = yield* Session.Service
|
||||
const database = yield* Database.Service
|
||||
const session = yield* sessions.create({ location })
|
||||
expect((yield* sessions.get(session.id)).outcome).toBeUndefined()
|
||||
|
||||
duringIdle = Effect.suspend(() =>
|
||||
database.db
|
||||
.update(SessionTable)
|
||||
.set({ idle_outcome: "failed" })
|
||||
.where(eq(SessionTable.id, session.id))
|
||||
.run()
|
||||
.pipe(Effect.orDie, Effect.asVoid),
|
||||
)
|
||||
|
||||
expect((yield* sessions.wait(session.id)).outcome).toBe("failed")
|
||||
duringIdle = Effect.void
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("fails fast for an unknown session without waiting", () =>
|
||||
Effect.gen(function* () {
|
||||
awaited.length = 0
|
||||
duringIdle = Effect.void
|
||||
const sessions = yield* Session.Service
|
||||
const sessionID = Session.ID.make("ses_wait_missing")
|
||||
|
||||
expect(yield* Effect.flip(sessions.wait(sessionID))).toEqual(new Session.NotFoundError({ sessionID }))
|
||||
expect(awaited).toEqual([])
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
@@ -437,7 +437,14 @@ export const SessionHandler = HttpApiBuilder.group(Api, "server.session", (handl
|
||||
.handle(
|
||||
"session.wait",
|
||||
Effect.fn(function* (ctx) {
|
||||
yield* session.wait(ctx.params.sessionID).pipe(Effect.catchTag("Session.NotFoundError", missingSession))
|
||||
// Item sub-spawn-wait.3 surfaces a typed decode failure; today the protocol advertises only
|
||||
// NotFound and ServiceUnavailable, so a corrupt row dies rather than failing a declared error.
|
||||
yield* session
|
||||
.wait(ctx.params.sessionID)
|
||||
.pipe(
|
||||
Effect.catchTag("Session.NotFoundError", missingSession),
|
||||
Effect.catchTag("Session.MessageDecodeError", Effect.die),
|
||||
)
|
||||
return HttpApiSchema.NoContent.make()
|
||||
}),
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user