mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-20 18:57:17 +03:00
fix(core): preserve subagent notifications across location eviction (#54072)
This commit is contained in:
committed by
GitHub
Unverified
parent
93a7c8404f
commit
ee0e614221
@@ -36,7 +36,7 @@ export const Plugin = define({
|
||||
const shell = yield* ShellSelect.Service
|
||||
const sessions = yield* Session.Service
|
||||
const agents = yield* Agent.Service
|
||||
const subagents = yield* SubagentJob.make
|
||||
const subagents = yield* SubagentJob.Service
|
||||
const load = Effect.fn("ConfigCommandPlugin.load")(function* () {
|
||||
return yield* Effect.forEach(yield* config.entries(), loadEntry).pipe(Effect.map((documents) => documents.flat()))
|
||||
})
|
||||
|
||||
@@ -61,6 +61,7 @@ import { Ripgrep } from "../ripgrep.js"
|
||||
import { Session } from "../session.js"
|
||||
import { SessionCompaction } from "../session/compaction.js"
|
||||
import { SessionInstructions } from "../session/instructions.js"
|
||||
import { SubagentJob } from "../session/subagent-job.js"
|
||||
import { Shell } from "../shell.js"
|
||||
import { ShellSelect } from "../shell/select.js"
|
||||
import { Snapshot } from "../snapshot.js"
|
||||
@@ -142,6 +143,7 @@ const services = [
|
||||
Session.Service,
|
||||
SessionCompaction.Service,
|
||||
SessionInstructions.Service,
|
||||
SubagentJob.Service,
|
||||
Shell.Service,
|
||||
ShellSelect.Service,
|
||||
Snapshot.Service,
|
||||
@@ -195,6 +197,7 @@ export const requirements = LayerNode.group([
|
||||
Session.node,
|
||||
SessionCompaction.node,
|
||||
SessionInstructions.node,
|
||||
SubagentJob.node,
|
||||
Shell.node,
|
||||
ShellSelect.node,
|
||||
Snapshot.node,
|
||||
|
||||
@@ -1,22 +1,29 @@
|
||||
export * as SubagentJob from "./subagent-job.js"
|
||||
|
||||
import { Effect, Scope } from "effect"
|
||||
import { Context, Effect, Layer, Scope } from "effect"
|
||||
import { Node } from "@opencode/util/effect/app-node"
|
||||
import type { LayerNode } from "@opencode/util/effect/layer-node"
|
||||
import { Job } from "../job.js"
|
||||
import { Session } from "../session.js"
|
||||
import { SubagentCompletion } from "./subagent-completion.js"
|
||||
|
||||
type Recovery = Extract<Job.Recovery, { kind: "subagent" }>
|
||||
|
||||
interface Runner {
|
||||
export interface Interface {
|
||||
start: (recovery: Recovery) => Effect.Effect<Job.Info>
|
||||
background: (recovery: Recovery) => Effect.Effect<void>
|
||||
notify: (recovery: Recovery, startedAt: number) => Effect.Effect<void>
|
||||
}
|
||||
|
||||
export const make: Effect.Effect<Runner, never, Session.Service | Job.Service | Scope.Scope> = Effect.gen(function* () {
|
||||
export class Service extends Context.Service<Service, Interface>()("@opencode/SubagentJob") {}
|
||||
|
||||
const make: Effect.Effect<Interface, never, Session.Service | Job.Service | Scope.Scope> = Effect.gen(function* () {
|
||||
const sessions = yield* Session.Service
|
||||
const jobs = yield* Job.Service
|
||||
const scope = yield* Scope.Scope
|
||||
// Jobs and their completion observers outlive the plugin that launched them.
|
||||
// Fork with the global context too, rather than retaining the caller's location.
|
||||
const context = yield* Effect.context<never>()
|
||||
// One observer per job generation, including continuations of the same child.
|
||||
const notifications = new Set<string>()
|
||||
|
||||
@@ -30,31 +37,40 @@ export const make: Effect.Effect<Runner, never, Session.Service | Job.Service |
|
||||
}).pipe(
|
||||
Effect.ensuring(Effect.sync(() => notifications.delete(key))),
|
||||
Effect.forkIn(scope, { startImmediately: true }),
|
||||
Effect.setContext(context),
|
||||
)
|
||||
})
|
||||
|
||||
return {
|
||||
return Service.of({
|
||||
start: (recovery: Recovery) =>
|
||||
jobs.start({
|
||||
id: recovery.childSessionID,
|
||||
type: "subagent",
|
||||
title: recovery.description,
|
||||
metadata: {},
|
||||
recovery,
|
||||
run: Effect.gen(function* () {
|
||||
yield* sessions.resume(recovery.childSessionID)
|
||||
const messages = yield* sessions.messages({ sessionID: recovery.childSessionID, order: "desc", limit: 20 })
|
||||
const assistant = messages.find(
|
||||
(message) =>
|
||||
message.type === "assistant" && message.time.completed !== undefined && message.error === undefined,
|
||||
)
|
||||
return SubagentCompletion.text(assistant)
|
||||
}),
|
||||
}),
|
||||
jobs
|
||||
.start({
|
||||
id: recovery.childSessionID,
|
||||
type: "subagent",
|
||||
title: recovery.description,
|
||||
metadata: {},
|
||||
recovery,
|
||||
run: Effect.gen(function* () {
|
||||
yield* sessions.resume(recovery.childSessionID)
|
||||
const messages = yield* sessions.messages({ sessionID: recovery.childSessionID, order: "desc", limit: 20 })
|
||||
const assistant = messages.find(
|
||||
(message) =>
|
||||
message.type === "assistant" && message.time.completed !== undefined && message.error === undefined,
|
||||
)
|
||||
return SubagentCompletion.text(assistant)
|
||||
}),
|
||||
})
|
||||
.pipe(Effect.setContext(context)),
|
||||
background: Effect.fn("SubagentJob.background")(function* (recovery: Recovery) {
|
||||
const info = yield* jobs.background(recovery.childSessionID)
|
||||
if (info) yield* notify(recovery, info.started_at)
|
||||
}),
|
||||
notify,
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
export const node: LayerNode.Provider<Service, never, typeof Node.tags.values.global> = Node.makeGlobalNode({
|
||||
service: Service,
|
||||
layer: Layer.effect(Service, make),
|
||||
deps: [Session.node, Job.node],
|
||||
})
|
||||
|
||||
@@ -70,7 +70,7 @@ export const Plugin = {
|
||||
const config = yield* Config.Service
|
||||
const permission = yield* Permission.Service
|
||||
const models = yield* Model.Service
|
||||
const subagents = yield* SubagentJob.make
|
||||
const subagents = yield* SubagentJob.Service
|
||||
|
||||
const resolveModel = Effect.fn("SubagentTool.resolveModel")(function* (input: string) {
|
||||
const ref = yield* Effect.try({
|
||||
|
||||
@@ -7,6 +7,7 @@ import { Directory, Document, Event, Info } from "@opencode/schema/config"
|
||||
import { Session } from "@opencode/core/session"
|
||||
import { SessionExecution } from "@opencode/core/session/execution"
|
||||
import { Job } from "@opencode/core/job"
|
||||
import { SubagentJob } from "@opencode/core/session/subagent-job"
|
||||
import { Agent } from "@opencode/core/agent"
|
||||
import { SessionInbox } from "@opencode/schema/session-inbox"
|
||||
import { SessionMessage } from "@opencode/schema/session-message"
|
||||
@@ -55,6 +56,7 @@ const it = testEffect(
|
||||
ShellSelect.node,
|
||||
Session.node,
|
||||
Job.node,
|
||||
SubagentJob.node,
|
||||
Agent.node,
|
||||
]),
|
||||
[
|
||||
|
||||
@@ -22,6 +22,7 @@ import { Reference } from "@opencode/core/reference"
|
||||
import { Skill } from "@opencode/core/skill"
|
||||
import { ShellSelect } from "@opencode/core/shell/select"
|
||||
import { Job } from "@opencode/core/job"
|
||||
import { SubagentJob } from "@opencode/core/session/subagent-job"
|
||||
import { Global } from "@opencode/util/global"
|
||||
import { Location } from "@opencode/core/location"
|
||||
import { Credential } from "@opencode/core/credential"
|
||||
@@ -38,7 +39,10 @@ import { location } from "../fixture/location"
|
||||
import { tmpdir } from "../fixture/tmpdir"
|
||||
|
||||
const it = testEffect(
|
||||
Layer.merge(PluginTestLayer, AppNodeBuilder.build(LayerNode.group([AppProcess.node, ShellSelect.node, Job.node]))),
|
||||
Layer.merge(
|
||||
PluginTestLayer,
|
||||
AppNodeBuilder.build(LayerNode.group([AppProcess.node, ShellSelect.node, Job.node, SubagentJob.node])),
|
||||
),
|
||||
)
|
||||
const decode = Schema.decodeUnknownSync(Info)
|
||||
const document = path.join(import.meta.dir, "opencode.json")
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
import { describe, expect } from "bun:test"
|
||||
import { Effect, Layer } from "effect"
|
||||
import { LanguageModel } from "@opencode/ai"
|
||||
import { OpenAIChat } from "@opencode/ai/protocols"
|
||||
import { TestLLM } from "@opencode/ai/testing"
|
||||
import { Agent } from "@opencode/core/agent"
|
||||
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
|
||||
import { LayerNodePlatform } from "@opencode/core/effect/app-node-platform"
|
||||
import { Watcher } from "@opencode/core/filesystem/watcher"
|
||||
import { Job } from "@opencode/core/job"
|
||||
import { LocationServiceMap } from "@opencode/core/location-service-map"
|
||||
import { Model } from "@opencode/core/model"
|
||||
import { Plugin } from "@opencode/core/plugin"
|
||||
import { Provider } from "@opencode/core/provider"
|
||||
import { AbsolutePath } from "@opencode/core/schema"
|
||||
import { Session } from "@opencode/core/session"
|
||||
import { SessionRunnerModel } from "@opencode/core/session/runner/model"
|
||||
import { Tool } from "@opencode/core/tool"
|
||||
import { LayerNode } from "@opencode/util/effect/layer-node"
|
||||
import { Global } from "@opencode/util/global"
|
||||
import { tempGlobalLayer } from "./fixture/global"
|
||||
import { offlineModels } from "./fixture/models"
|
||||
import { tmpdirScoped } from "./fixture/tmpdir"
|
||||
import { testEffect } from "./lib/effect"
|
||||
import { executeTool, toolIdentity } from "./lib/tool"
|
||||
|
||||
const llmLayer = TestLLM.testLayer({ fallback: TestLLM.text("Review complete", "review") })
|
||||
const it = testEffect(
|
||||
Layer.merge(
|
||||
llmLayer,
|
||||
AppNodeBuilder.build(LayerNode.group([Session.node, Job.node, LocationServiceMap.node]), [
|
||||
Global.node.replace(tempGlobalLayer),
|
||||
offlineModels,
|
||||
Watcher.node.replace(Watcher.configured({ enabled: false })),
|
||||
LayerNodePlatform.llmClient.replace(llmLayer),
|
||||
SessionRunnerModel.node.replace(
|
||||
Layer.succeed(SessionRunnerModel.Service, {
|
||||
resolve: () =>
|
||||
Effect.succeed(
|
||||
SessionRunnerModel.resolved(
|
||||
LanguageModel.make({ id: "review", provider: "test", route: OpenAIChat.route }),
|
||||
{
|
||||
capabilities: { tools: true, input: ["text"], output: ["text"] },
|
||||
cost: [],
|
||||
limit: { context: 200_000, output: 32_000 },
|
||||
},
|
||||
),
|
||||
),
|
||||
}),
|
||||
),
|
||||
]),
|
||||
),
|
||||
)
|
||||
|
||||
describe("subagent observer lifetime", () => {
|
||||
for (const [evict, outcome] of [
|
||||
[false, "completed"],
|
||||
[true, "completed"],
|
||||
[true, "cancelled"],
|
||||
] as const) {
|
||||
it.live(
|
||||
`notifies an idle parent exactly once after its moved child ${outcome} (evict=${evict})`,
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const parentDir = yield* tmpdirScoped()
|
||||
const childDir = yield* tmpdirScoped()
|
||||
yield* Effect.promise(() =>
|
||||
Bun.write(
|
||||
`${parentDir.path}/opencode.json`,
|
||||
JSON.stringify({
|
||||
agents: { reviewer: { mode: "subagent" } },
|
||||
permissions: [{ action: "*", resource: "*", effect: "allow" }],
|
||||
}),
|
||||
),
|
||||
)
|
||||
yield* Effect.promise(() =>
|
||||
Bun.write(`${childDir.path}/opencode.json`, JSON.stringify({ agents: { reviewer: { mode: "subagent" } } })),
|
||||
)
|
||||
const sessions = yield* Session.Service
|
||||
const locations = yield* LocationServiceMap.Service
|
||||
const jobs = yield* Job.Service
|
||||
const llm = yield* TestLLM.Test
|
||||
const parent = yield* sessions.create({
|
||||
location: { directory: AbsolutePath.make(parentDir.path) },
|
||||
agent: Agent.ID.make("build"),
|
||||
model: Model.Ref.make({ id: Model.ID.make("parent"), providerID: Provider.ID.make("test") }),
|
||||
})
|
||||
const child = yield* sessions.create({ parentID: parent.id, agent: Agent.ID.make("reviewer") })
|
||||
yield* sessions.move({ sessionID: child.id, directory: AbsolutePath.make(childDir.path) })
|
||||
yield* sessions.wait(child.id)
|
||||
expect((yield* sessions.get(child.id)).location.directory).toBe(AbsolutePath.make(childDir.path))
|
||||
yield* Plugin.Service.use((plugins) => plugins.awaitActivation).pipe(
|
||||
Effect.provide(locations.get(parent.location)),
|
||||
)
|
||||
const registry = yield* Tool.Service.pipe(Effect.provide(locations.get(parent.location)))
|
||||
const gate = yield* llm.gate()
|
||||
const result = yield* executeTool(registry, {
|
||||
sessionID: parent.id,
|
||||
...toolIdentity,
|
||||
call: {
|
||||
type: "tool-call",
|
||||
id: "call-review",
|
||||
name: "subagent",
|
||||
input: {
|
||||
agent: "reviewer",
|
||||
sessionID: child.id,
|
||||
description: "Review fixture",
|
||||
prompt: "Review the fixture",
|
||||
background: true,
|
||||
},
|
||||
},
|
||||
})
|
||||
expect(result.status).toBe("completed")
|
||||
yield* gate.started
|
||||
expect(yield* sessions.context(parent.id)).toEqual([])
|
||||
if (evict) {
|
||||
yield* locations.invalidate(parent.location)
|
||||
// Rebuilding a location must not lose or duplicate its former observer.
|
||||
yield* Plugin.Service.use((plugins) => plugins.awaitActivation).pipe(
|
||||
Effect.provide(locations.get(parent.location)),
|
||||
)
|
||||
yield* locations.invalidate(parent.location)
|
||||
}
|
||||
if (outcome === "cancelled") yield* jobs.cancel(child.id)
|
||||
yield* gate.release
|
||||
yield* jobs.wait({ id: child.id })
|
||||
yield* llm.wait(2).pipe(Effect.timeout("2 seconds"))
|
||||
yield* sessions.wait(parent.id)
|
||||
const notices = (yield* sessions.context(parent.id)).filter((message) => message.type === "synthetic")
|
||||
expect(notices).toHaveLength(1)
|
||||
expect(notices[0]).toMatchObject({ metadata: { source: "subagent", childID: child.id, state: outcome } })
|
||||
expect(yield* jobs.pendingBackground).toEqual([])
|
||||
yield* locations.invalidate(parent.location)
|
||||
yield* Plugin.Service.use((plugins) => plugins.awaitActivation).pipe(
|
||||
Effect.provide(locations.get(parent.location)),
|
||||
)
|
||||
expect((yield* sessions.context(parent.id)).filter((message) => message.type === "synthetic")).toEqual(
|
||||
notices,
|
||||
)
|
||||
expect(yield* llm.requests()).toHaveLength(2)
|
||||
}),
|
||||
20_000,
|
||||
)
|
||||
}
|
||||
})
|
||||
@@ -29,6 +29,7 @@ import { SessionInbox } from "@opencode/core/session/inbox"
|
||||
import { SessionMessage } from "@opencode/core/session/message"
|
||||
import { SessionRunnerModel } from "@opencode/core/session/runner/model"
|
||||
import { SessionStore } from "@opencode/core/session/store"
|
||||
import { SubagentJob } from "@opencode/core/session/subagent-job"
|
||||
import { Plugin } from "@opencode/core/plugin"
|
||||
import { PluginHooks } from "@opencode/core/plugin/hooks"
|
||||
import { PluginSupervisor } from "@opencode/core/plugin/supervisor"
|
||||
@@ -119,7 +120,17 @@ const subagentPluginSupervisor = makeLocationNode({
|
||||
yield* registerToolPlugin(SubagentTool.Plugin, {}, (name, callback) => hooks.register("tool", name, callback))
|
||||
}),
|
||||
),
|
||||
deps: [Agent.node, Config.node, Model.node, Permission.node, Session.node, Job.node, Tool.node, PluginHooks.node],
|
||||
deps: [
|
||||
Agent.node,
|
||||
Config.node,
|
||||
Model.node,
|
||||
Permission.node,
|
||||
Session.node,
|
||||
Job.node,
|
||||
SubagentJob.node,
|
||||
Tool.node,
|
||||
PluginHooks.node,
|
||||
],
|
||||
})
|
||||
|
||||
const nodes = LayerNode.group([
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
# Background completion after parent-location eviction
|
||||
|
||||
`subagent-eviction.ts` drives an isolated server and its real TUI. It starts a
|
||||
background subagent, moves the child to another directory, leaves the parent
|
||||
idle, evicts and rebuilds the parent location, then lets the child finish.
|
||||
|
||||
Only the LLM responses and a `fixture_hold` tool are simulated. Session movement,
|
||||
job scopes, completion delivery, SQLite persistence, and the parent wake are real.
|
||||
The existing `DELETE /api/debug/location` endpoint invalidates the same location
|
||||
graph as inactivity eviction, so the proof does not wait for the 60-minute TTL.
|
||||
It does not change the server clock or restart the server.
|
||||
|
||||
## Run
|
||||
|
||||
Use Bun 1.4.2, an available `opencode-drive` 2.1.3 installation on the module path,
|
||||
and a dependency-installed V2 checkout. The script is an Effect program, run with
|
||||
`opencode-drive run` (which typechecks before launch).
|
||||
|
||||
```sh
|
||||
OPENCODE_DRIVE_DB=proof.sqlite \
|
||||
OPENCODE_DRIVE_MEDIA_DIR=$PWD/.drive-output \
|
||||
DEMO_LABEL=AFTER \
|
||||
opencode-drive run script/drive/subagent-eviction.ts
|
||||
```
|
||||
|
||||
Run that same script against an immutable base checkout:
|
||||
|
||||
```sh
|
||||
OPENCODE_DEV=/path/to/base-checkout \
|
||||
OPENCODE_DRIVE_DB=proof.sqlite \
|
||||
OPENCODE_DRIVE_MEDIA_DIR=$PWD/.drive-output \
|
||||
DEMO_LABEL=BEFORE \
|
||||
opencode-drive run script/drive/subagent-eviction.ts
|
||||
```
|
||||
|
||||
`DEMO_LABEL=BEFORE` asserts the known missing wake; `AFTER` asserts successful
|
||||
delivery. `DEMO_EVICT=false` is a control and must wake even on the base.
|
||||
|
||||
The script checks the child's completed answer, counts the parent's synthetic
|
||||
notifications, and reads only its isolated database's background marker. It
|
||||
writes `proof.json` inside the reported artifacts directory, saves a screenshot,
|
||||
and exports an annotated recording. Another location eviction/rebuild must not
|
||||
duplicate the notification.
|
||||
|
||||
| Check | Base with eviction | Fixed / no-eviction control |
|
||||
| -------------------- | ------------------------- | --------------------------- |
|
||||
| Child completed | true | true |
|
||||
| Parent resumed | false | true |
|
||||
| Parent notifications | 0 | 1 |
|
||||
| Background marker | completed, unacknowledged | absent |
|
||||
|
||||
The dynamic hold tool avoids the static adapter loading issue in
|
||||
[opencode-drive#116](https://github.com/anomalyco/opencode-drive/issues/116).
|
||||
|
||||
## History
|
||||
|
||||
- `94e3a29d2f` (#34320, June 28): the original V2 subagent tool registered at the
|
||||
global application root, so its completion observer shared that lifetime.
|
||||
- `194b0615e0` (#34619, June 30): plugin-provided tools moved it into the
|
||||
location-scoped plugin layer while retaining its captured-scope observer.
|
||||
- `282b644cde` (#44275, August 22): location expiry became driven by durable
|
||||
session activity. A moved child's activity cannot refresh the idle parent's
|
||||
original location.
|
||||
- `7819e7f503` (#47081, September 3): command subagents reused `SubagentJob.make`,
|
||||
preserving the same activation-scoped observer in both entry points.
|
||||
|
||||
This is source-history attribution of the lifetime mismatch, not a claim that
|
||||
every historical revision has been executed. The before proof runs V2
|
||||
`93a7c8404fdc4fdb182eb6bbef7d925cb81e8306`.
|
||||
@@ -0,0 +1,153 @@
|
||||
import { Deferred, Effect, Stream } from "effect"
|
||||
import { Llm, OpenCodeDriver } from "opencode-drive"
|
||||
import { AbsolutePath } from "../../packages/schema/src/schema"
|
||||
import { Database } from "bun:sqlite"
|
||||
|
||||
const label = process.env.DEMO_LABEL ?? "AFTER"
|
||||
const evict = process.env.DEMO_EVICT !== "false"
|
||||
|
||||
// Run with OPENCODE_DRIVE_DB=proof.sqlite. Only model output and fixture_hold are
|
||||
// simulated. The debug endpoint closes the real graph without waiting an hour.
|
||||
// Dynamic tools avoid the static adapter issue: anomalyco/opencode-drive#116.
|
||||
export default OpenCodeDriver.use(
|
||||
{
|
||||
opencode: { dev: process.env.OPENCODE_DEV ?? process.cwd() },
|
||||
keepArtifacts: true,
|
||||
tui: { recording: true, viewport: { cols: 100, rows: 30 } },
|
||||
config: {
|
||||
autoupdate: false,
|
||||
username: "Demo",
|
||||
agents: { reviewer: { mode: "subagent", description: "Review the fixture" } },
|
||||
},
|
||||
tuiConfig: { theme: { name: "opencode", mode: "dark" }, animations: false, tabs: { mode: "off" } },
|
||||
project: { git: true, files: { "README.md": "# Parent fixture\n", "child/README.md": "# Child fixture\n" } },
|
||||
},
|
||||
({ ui, llm, tui, opencode, artifacts, tools }) =>
|
||||
Effect.gen(function* () {
|
||||
const release = yield* Deferred.make<void>()
|
||||
const held = yield* Deferred.make<void>()
|
||||
yield* tools.attach({
|
||||
tools: [
|
||||
{
|
||||
name: "fixture_hold",
|
||||
description: "Wait for the fixture",
|
||||
inputSchema: { type: "object", properties: {} },
|
||||
options: { codemode: false },
|
||||
},
|
||||
],
|
||||
})
|
||||
let parentRequests = 0
|
||||
let childRequests = 0
|
||||
yield* llm.serve((request) => {
|
||||
const body = JSON.stringify(request)
|
||||
if (body.includes("You are a subagent spawned")) {
|
||||
childRequests++
|
||||
if (childRequests === 1)
|
||||
return Stream.make(
|
||||
Llm.toolCall({ index: 0, id: "call_hold", name: "fixture_hold", input: {} }),
|
||||
Llm.finish("tool-calls"),
|
||||
)
|
||||
return Stream.fromEffect(
|
||||
Deferred.succeed(held, undefined).pipe(Effect.andThen(Deferred.await(release))),
|
||||
).pipe(Stream.flatMap(() => Stream.make(Llm.text("CHILD_REVIEW_COMPLETE"))))
|
||||
}
|
||||
parentRequests++
|
||||
if (parentRequests === 1)
|
||||
return Stream.make(
|
||||
Llm.toolCall({
|
||||
index: 0,
|
||||
id: "call_review",
|
||||
name: "subagent",
|
||||
input: {
|
||||
agent: "reviewer",
|
||||
description: "Review fixture",
|
||||
prompt: "Review the child fixture",
|
||||
background: true,
|
||||
},
|
||||
}),
|
||||
Llm.finish("tool-calls"),
|
||||
)
|
||||
return Stream.make(
|
||||
Llm.text(
|
||||
parentRequests === 2 ? "Review is running in the background." : "Review received. All checks passed.",
|
||||
),
|
||||
)
|
||||
})
|
||||
yield* ui.waitFor("Simulated Model", { timeout: 30000 })
|
||||
yield* ui.submit("Run the fixture review in the background.")
|
||||
yield* ui.waitFor("Review is running in the background.", { timeout: 30000 })
|
||||
const parent = (yield* opencode.session.list({ limit: 20 })).data.find((session) => !session.parentID)
|
||||
if (!parent) return yield* Effect.fail(new Error("Parent missing"))
|
||||
const child = (yield* opencode.session.list({ parentID: parent.id })).data[0]
|
||||
if (!child) return yield* Effect.fail(new Error("Child missing"))
|
||||
const hold = yield* tools.take("call_hold")
|
||||
yield* opencode.session.move({ sessionID: child.id, directory: AbsolutePath.make(`${artifacts}/files/child`) })
|
||||
yield* hold.finish({ structured: {}, content: [{ type: "text", text: "Fixture ready" }] })
|
||||
yield* Deferred.await(held).pipe(Effect.timeout("30 seconds"))
|
||||
const moved = yield* opencode.session.get({ sessionID: child.id })
|
||||
if (moved.location.directory !== `${artifacts}/files/child`)
|
||||
return yield* Effect.fail(new Error("Child did not move"))
|
||||
yield* opencode.session.wait({ sessionID: parent.id })
|
||||
if (evict) {
|
||||
yield* opencode.debug.location.evict({ location: { directory: parent.location.directory } })
|
||||
yield* opencode.location.get({ location: { directory: parent.location.directory } })
|
||||
}
|
||||
if (tui.recording)
|
||||
yield* tui.recording.mark(`${label}: parent idle${evict ? ", original location evicted" : " (control)"}`)
|
||||
yield* Deferred.succeed(release, undefined)
|
||||
yield* opencode.session.wait({ sessionID: child.id })
|
||||
const resumed = yield* ui.waitFor("Review received. All checks passed.", { timeout: 5000 }).pipe(
|
||||
Effect.as(true),
|
||||
Effect.catchTag("UiWaitTimeoutError", () => Effect.succeed(false)),
|
||||
)
|
||||
const messages = yield* opencode.message.list({ sessionID: parent.id })
|
||||
const childMessages = yield* opencode.message.list({ sessionID: child.id })
|
||||
const completed = childMessages.data.some(
|
||||
(message) =>
|
||||
message.type === "assistant" &&
|
||||
message.finish === "stop" &&
|
||||
message.content.some((part) => part.type === "text" && part.text === "CHILD_REVIEW_COMPLETE"),
|
||||
)
|
||||
const notifications = messages.data.filter(
|
||||
(message) => message.type === "synthetic" && message.metadata?.source === "subagent",
|
||||
).length
|
||||
const marker = yield* Effect.acquireUseRelease(
|
||||
Effect.sync(() => new Database(`${artifacts}/logs/opencode/proof.sqlite`, { readonly: true })),
|
||||
(database) =>
|
||||
Effect.sync(() =>
|
||||
database
|
||||
.query<
|
||||
{ status: string; output: string },
|
||||
[string]
|
||||
>("SELECT json_extract(value, '$.status') AS status, json_extract(value, '$.output') AS output FROM kv WHERE key LIKE 'job.background/%' AND json_extract(value, '$.recovery.childSessionID') = ?")
|
||||
.get(child.id),
|
||||
),
|
||||
(database) => Effect.sync(() => database.close()),
|
||||
)
|
||||
const proof = { label, evict, resumed, completed, notifications, parentRequests, childRequests, marker }
|
||||
console.log(JSON.stringify(proof, null, 2))
|
||||
yield* Effect.promise(() => Bun.write(`${artifacts}/proof.json`, JSON.stringify(proof, null, 2)))
|
||||
if (
|
||||
!completed ||
|
||||
notifications !== (resumed ? 1 : 0) ||
|
||||
(resumed ? marker !== null : marker?.status !== "completed")
|
||||
)
|
||||
return yield* Effect.fail(new Error("Inconsistent completion evidence"))
|
||||
if (evict) {
|
||||
yield* opencode.debug.location.evict({ location: { directory: parent.location.directory } })
|
||||
yield* opencode.location.get({ location: { directory: parent.location.directory } })
|
||||
const rebuilt = yield* opencode.message.list({ sessionID: parent.id })
|
||||
if (rebuilt.data.filter((message) => message.type === "synthetic").length !== notifications)
|
||||
return yield* Effect.fail(new Error("Location rebuild duplicated notification"))
|
||||
}
|
||||
if (tui.recording)
|
||||
yield* tui.recording.mark(
|
||||
`${label}: ${resumed ? "completion resumes parent" : "child finished; parent never resumed"}`,
|
||||
)
|
||||
yield* Effect.sleep("2 seconds")
|
||||
console.log("screenshot", yield* ui.screenshot("completion"))
|
||||
if (tui.recording) console.log("video", yield* tui.recording.finish())
|
||||
if (resumed !== (label === "AFTER" || !evict))
|
||||
return yield* Effect.fail(new Error("Unexpected completion delivery"))
|
||||
}),
|
||||
)
|
||||
Reference in New Issue
Block a user