GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — refactor(core): remove leftover foreground subagent and reattach code… · drpr/opencode@23dd370

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • packages/core
    • src
      • job.ts
      • session
        • background.ts
        • execution.ts
        • execution
          • restart.ts
          • subagent-report.ts
        • subagent-completion.ts
        • subagent-job.ts
      • tool/plugin
        • image-generate.ts
        • shell.ts
    • test
      • job.test.ts
      • session-background.test.ts
      • subagent-report.test.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎packages/core/src/job.ts‎

Copy file name to clipboardExpand all lines: packages/core/src/job.ts
+5-17Lines changed: 5 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,6 @@ export type Background = typeof Background.Type
3838
export type Status = Background["status"]
3939

4040
export type SubagentReportState =
41-
| { readonly mode: "foreground" }
4241
| {
4342
readonly mode: "background"
4443
readonly notificationID: SessionMessage.ID
@@ -107,7 +106,7 @@ type BackgroundResult = {
107106
backgrounded?: Deferred.Deferred<Info>
108107
}
109108

110-
type StartResult = { info: Info } | { info: Info; job: Active } | { info: Info; backgrounded: Deferred.Deferred<Info> }
109+
type StartResult = { info: Info } | { info: Info; job: Active }
111110

112111
type BlockWait = {
113112
done: Deferred.Deferred<Info>
@@ -363,14 +362,7 @@ export const make = Effect.gen(function* () {
363362
const existing = jobs.get(input.id)
364363
// A settling generation is already reporting; new work starts a fresh generation.
365364
if (existing?.info.status === "running" && !existing.settling) {
366-
if (!input.background || existing.isBackgrounded) return [{ info: snapshot(existing) }, jobs]
367-
// Joining live work after its start must register the durable marker before a fast
368-
// drain can settle and classify the period as foreground.
369-
const updated = yield* markBackground(existing)
370-
return [
371-
{ info: snapshot(updated), backgrounded: existing.backgrounded },
372-
new Map(jobs).set(input.id, updated),
373-
]
365+
return [{ info: snapshot(existing) }, jobs]
374366
}
375367
const scope = yield* Scope.fork(state.scope, "parallel")
376368
// Closing the registry interrupts the work without settling it; interrupt its observers too.
@@ -406,7 +398,6 @@ export const make = Effect.gen(function* () {
406398
return [{ info: snapshot(job), job }, new Map(jobs).set(input.id, job)]
407399
}),
408400
)
409-
if ("backgrounded" in result) yield* Deferred.succeed(result.backgrounded, result.info)
410401
if ("job" in result)
411402
yield* restore(input.run).pipe(
412403
Effect.exit,
@@ -498,8 +489,6 @@ export const make = Effect.gen(function* () {
498489
const job = jobs.get(id)
499490
// Recoverable work may finish before the caller backgrounds it.
500491
if (!job || (job.info.status !== "running" && !job.recovery)) return [{}, jobs]
501-
// A settling generation already reported as foreground; a late Ctrl+B must not revive it.
502-
if (job.settling) return [{}, jobs]
503492
if (job.isBackgrounded) return [{ info: snapshot(job) }, jobs]
504493
const next = yield* markBackground(job)
505494
return [{ info: snapshot(next), backgrounded: job.backgrounded }, new Map(jobs).set(id, next)]
@@ -519,7 +508,6 @@ export const make = Effect.gen(function* () {
519508
const next = new Map(jobs)
520509
for (const [id, job] of jobs) {
521510
if (job.info.status !== "running") continue
522-
if (job.settling) continue
523511
if (job.isBackgrounded) continue
524512
if (input.type !== undefined && job.info.type !== input.type) continue
525513
if (!job.blockingSessions.has(input.sessionID)) continue
@@ -649,7 +637,9 @@ export const make = Effect.gen(function* () {
649637
return yield* SynchronizedRef.modify(state.jobs, (jobs): readonly [SubagentReportState, Map<string, Active>] => {
650638
const job = jobs.get(id)
651639
// A generation reports at most once, even when an earlier attempt only observed a cancel.
652-
if (!job || job.reported) return [{ mode: "none" }, jobs]
640+
if (!job?.isBackgrounded || job.reported || !job.info.notificationID || job.recovery?.kind !== "subagent") {
641+
return [{ mode: "none" }, jobs]
642+
}
653643
const live = job.info.status === "running" && !job.settling
654644
// A cancel within this busy period already consumed the live entry, but it still belongs
655645
// here. A creation-tick interruption never bound a generation, so any cancel matches.
@@ -662,8 +652,6 @@ export const make = Effect.gen(function* () {
662652
...(job.info.status === "running" ? { settling: true } : {}),
663653
}
664654
const next = new Map(jobs).set(id, updated)
665-
if (!job.isBackgrounded) return [{ mode: "foreground" }, next]
666-
if (!job.info.notificationID || job.recovery?.kind !== "subagent") return [{ mode: "none" }, next]
667655
return [
668656
{
669657
mode: "background",
Collapse file

‎packages/core/src/session/background.ts‎

Copy file name to clipboardExpand all lines: packages/core/src/session/background.ts
+2-7Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -82,14 +82,9 @@ export const outstanding = Effect.fnUntraced(function* (
8282
const children = new Set(items.flatMap((item) => (item.kind === "subagent" ? [item.childSessionID] : [])))
8383
for (const activeID of active) {
8484
if (activeID === sessionID || children.has(activeID)) continue
85-
// Foreground-blocking work is the caller's inline result, and cancelled work is
86-
// acknowledged elsewhere: neither is still running for this report.
85+
// A cancelled child may still be draining while it cleans up.
8786
const tracked = jobs.get ? yield* jobs.get(activeID) : undefined
88-
if (
89-
tracked &&
90-
((tracked.status === "running" && tracked.notificationID === undefined) || tracked.status === "cancelled")
91-
)
92-
continue
87+
if (tracked?.status === "cancelled") continue
9388
if (!(yield* descends(store, parents, activeID, sessionID))) continue
9489
const info = yield* store.get(activeID)
9590
if (!info?.parentID) continue
Collapse file

‎packages/core/src/session/execution.ts‎

Copy file name to clipboardExpand all lines: packages/core/src/session/execution.ts
+1-2Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -158,8 +158,7 @@ export const layer = Layer.effect(
158158
yield* bus.publish(SessionEvent.Execution.Interrupted, { sessionID, reason: "shutdown" })
159159
return
160160
}
161-
// Classify and claim the Job generation before cancelling it: the settlement commit
162-
// owns the outbox row, and a cancel must not race a foreground classification.
161+
// Claim the Job generation before cancelling it so the settlement commit owns its outbox row.
163162
const settlement = yield* subagentReport.prepare(sessionID, outcome)
164163
if (outcome.type === "interrupted") yield* jobs.cancel(sessionID)
165164
yield* publishTerminal(bus, sessionID, outcome, settlement.commit)
Collapse file

‎packages/core/src/session/execution/restart.ts‎

Copy file name to clipboardExpand all lines: packages/core/src/session/execution/restart.ts
+10-27Lines changed: 10 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import { SessionStore } from "../store.js"
1919
import { ImageNotice } from "../../image/notice.js"
2020
import { ShellResult } from "../../shell/result.js"
2121
import { SubagentCompletion } from "../subagent-completion.js"
22+
import { SubagentJob } from "../subagent-job.js"
2223
import { SubagentMetadata } from "../subagent-metadata.js"
2324

2425
const CONTINUE_AFTER_SERVER_RESTART =
@@ -41,6 +42,8 @@ export interface Options {
4142

4243
const DEFAULT_MAX_ATTEMPTS = 10
4344

45+
type Notices = Pick<Session.Interface, "synthetic">
46+
4447
export interface Interface {
4548
/**
4649
* Resumes Sessions whose execution claim was never released — turns orphaned
@@ -214,7 +217,7 @@ export const layer = (options?: Options) =>
214217
const recoverShellJob = Effect.fnUntraced(function* (
215218
background: Job.Background,
216219
recovery: Extract<Job.Recovery, { kind: "shell" }>,
217-
notices: Session.Interface,
220+
notices: Notices,
218221
reattached: Set<string>,
219222
) {
220223
const shell = background.status === "running" ? yield* shellOf(recovery.sessionID) : undefined
@@ -238,7 +241,7 @@ export const layer = (options?: Options) =>
238241
// command still running in the daemon. Settle the call as moved to the background and watch the command.
239242
const settleBackgroundedCalls = Effect.fnUntraced(function* (
240243
sessionID: SessionSchema.ID,
241-
notices: Session.Interface,
244+
notices: Notices,
242245
reattached: ReadonlySet<string>,
243246
) {
244247
const calls = (yield* SessionHistory.incompleteAssistants(db, sessionID)).flatMap((message) =>
@@ -282,7 +285,7 @@ export const layer = (options?: Options) =>
282285
})
283286

284287
const deliverSubagentSafe = Effect.fnUntraced(function* (
285-
notices: Session.Interface,
288+
notices: Notices,
286289
notificationID: Job.Background["notificationID"],
287290
recovery: Extract<Job.Recovery, { kind: "subagent" }>,
288291
result: Pick<Job.Background, "status" | "output" | "error">,
@@ -328,7 +331,7 @@ export const layer = (options?: Options) =>
328331
const recoverSubagent = Effect.fnUntraced(function* (
329332
background: Job.Background,
330333
recovery: Extract<Job.Recovery, { kind: "subagent" }>,
331-
notices: Session.Interface,
334+
notices: Notices,
332335
): Effect.fn.Return<boolean> {
333336
const child = yield* store.get(recovery.childSessionID)
334337
if (!child || child.parentID !== recovery.parentSessionID || !(yield* store.get(recovery.parentSessionID))) {
@@ -396,12 +399,11 @@ export const layer = (options?: Options) =>
396399
)
397400
// Hold notice wakes until every suspended root has counted its attempt, so a woken
398401
// child cannot settle mid-sweep and wake its parent past that budget.
399-
const notices: Session.Interface = {
400-
...sessions,
402+
const notices: Notices = {
401403
synthetic: (input) =>
402404
sessions.synthetic({ ...input, resume: false }).pipe(
403405
Effect.tap(() => {
404-
if (input.resume === false || suspended.has(input.sessionID)) return Effect.void
406+
if (suspended.has(input.sessionID)) return Effect.void
405407
if (!state.defer) return wake(input.sessionID)
406408
wakes.add(input.sessionID)
407409
return Effect.void
@@ -465,26 +467,7 @@ export const layer = (options?: Options) =>
465467
yield* Effect.forEach(
466468
resumable,
467469
Effect.fnUntraced(function* ({ background, recovery }) {
468-
yield* jobs.start({
469-
id: background.id,
470-
type: "subagent",
471-
title: recovery.description,
472-
notificationID: background.notificationID,
473-
recovery,
474-
background: true,
475-
run: execution.resume(recovery.childSessionID).pipe(
476-
Effect.onInterrupt(() =>
477-
jobs
478-
.isCancelled(background.id)
479-
.pipe(
480-
Effect.flatMap((cancelled) =>
481-
cancelled ? execution.interrupt(recovery.childSessionID) : Effect.void,
482-
),
483-
),
484-
),
485-
Effect.as(""),
486-
),
487-
})
470+
yield* SubagentJob.start(jobs, execution, recovery, background.notificationID)
488471
suspended.delete(recovery.childSessionID)
489472
}),
490473
{ discard: true },
Collapse file

‎packages/core/src/session/execution/subagent-report.ts‎

Copy file name to clipboardExpand all lines: packages/core/src/session/execution/subagent-report.ts
-6Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -135,12 +135,6 @@ export const make = (deps: Deps) => {
135135
const period = periods.get(sessionID)
136136
periods.delete(sessionID)
137137
const jobState = yield* deps.jobs.prepareSubagentReport(sessionID, period?.boundGeneration)
138-
if (jobState.mode === "foreground") {
139-
return {
140-
commit: () => deps.store.release(sessionID),
141-
deliver: Effect.void,
142-
}
143-
}
144138
const initial = yield* deps.store.get(sessionID)
145139
if (!initial?.parentID && jobState.mode === "none") {
146140
return {
Collapse file

‎packages/core/src/session/subagent-completion.ts‎

Copy file name to clipboardExpand all lines: packages/core/src/session/subagent-completion.ts
-3Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ export interface SyntheticSession<E = never> {
1818
readonly text: string
1919
readonly description?: string
2020
readonly metadata?: SessionSchema.Metadata
21-
readonly resume?: boolean
2221
}) => Effect.Effect<unknown, E>
2322
}
2423

@@ -56,7 +55,6 @@ export const deliver = Effect.fnUntraced(function* <E>(
5655
jobs: Pick<Job.Interface, "completeBackground">,
5756
input: Pick<Job.Info, "status" | "output" | "error" | "notificationID"> & {
5857
recovery: Extract<Job.Recovery, { kind: "subagent" }>
59-
resume?: boolean
6058
},
6159
) {
6260
if (input.status === "running") return
@@ -70,7 +68,6 @@ export const deliver = Effect.fnUntraced(function* <E>(
7068
yield* sessions.synthetic({
7169
...(input.notificationID ? { id: input.notificationID } : {}),
7270
sessionID: recovery.parentSessionID,
73-
...(input.resume === false ? { resume: false } : {}),
7471
description: recovery.description,
7572
text: `<subagent sessionID="${recovery.childSessionID}" state="${input.status}" description="${recovery.description}">\n${body}\n</subagent>`,
7673
metadata: { source: "subagent", childID: recovery.childSessionID, agent: recovery.agent, state: input.status },
Collapse file

‎packages/core/src/session/subagent-job.ts‎

Copy file name to clipboardExpand all lines: packages/core/src/session/subagent-job.ts
+27-25Lines changed: 27 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,32 @@ export interface Interface {
1414

1515
export class Service extends Context.Service<Service, Interface>()("@opencode/SubagentJob") {}
1616

17+
export function start(
18+
jobs: Job.Interface,
19+
execution: SessionExecution.Interface,
20+
recovery: Recovery,
21+
notificationID?: Job.Background["notificationID"],
22+
) {
23+
const id = recovery.childSessionID
24+
return jobs.start({
25+
id,
26+
type: "subagent",
27+
title: recovery.description,
28+
metadata: notificationID === undefined ? {} : undefined,
29+
recovery,
30+
notificationID,
31+
background: true,
32+
run: execution.resume(id).pipe(
33+
// Only an explicit caller cancel releases the child's claim. A server shutdown
34+
// interrupts this job but must leave the child resumable on the next start.
35+
Effect.onInterrupt(() =>
36+
jobs.isCancelled(id).pipe(Effect.flatMap((cancelled) => (cancelled ? execution.interrupt(id) : Effect.void))),
37+
),
38+
Effect.as(""),
39+
),
40+
})
41+
}
42+
1743
const make = Effect.gen(function* () {
1844
const execution = yield* SessionExecution.Service
1945
const jobs = yield* Job.Service
@@ -22,31 +48,7 @@ const make = Effect.gen(function* () {
2248
const context = yield* Effect.context<never>()
2349

2450
return Service.of({
25-
start: (recovery) =>
26-
jobs
27-
.start({
28-
id: recovery.childSessionID,
29-
type: "subagent",
30-
title: recovery.description,
31-
metadata: {},
32-
recovery,
33-
background: true,
34-
run: execution.resume(recovery.childSessionID).pipe(
35-
// Only an explicit caller cancel releases the child's claim. A server shutdown
36-
// interrupts this job but must leave the child resumable on the next start.
37-
Effect.onInterrupt(() =>
38-
jobs
39-
.isCancelled(recovery.childSessionID)
40-
.pipe(
41-
Effect.flatMap((cancelled) =>
42-
cancelled ? execution.interrupt(recovery.childSessionID) : Effect.void,
43-
),
44-
),
45-
),
46-
Effect.as(""),
47-
),
48-
})
49-
.pipe(Effect.setContext(context)),
51+
start: (recovery) => start(jobs, execution, recovery).pipe(Effect.setContext(context)),
5052
})
5153
})
5254

Collapse file

‎packages/core/src/tool/plugin/image-generate.ts‎

Copy file name to clipboardExpand all lines: packages/core/src/tool/plugin/image-generate.ts
+2-4Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -345,9 +345,9 @@ export const Plugin = {
345345
title: input.prompt,
346346
metadata: { sessionID: context.sessionID, path: stem, model: ref },
347347
recovery: { kind: "image", sessionID: context.sessionID, path: stem, model: ref },
348+
background: true,
348349
run,
349350
})
350-
yield* jobs.background(id)
351351
yield* notifyWhenDone({ sessionID: context.sessionID, id, notificationID, file: stem })
352352
return {
353353
output: { id, path: stem, model: ref },
@@ -359,9 +359,7 @@ export const Plugin = {
359359
].join("\n"),
360360
metadata: { path: stem, model: ref, jobID: id },
361361
}
362-
}).pipe(
363-
Effect.mapError(toolFailure("Unable to generate image")),
364-
),
362+
}).pipe(Effect.mapError(toolFailure("Unable to generate image"))),
365363
})
366364
})
367365
.pipe(Effect.orDie)
Collapse file

‎packages/core/src/tool/plugin/shell.ts‎

Copy file name to clipboardExpand all lines: packages/core/src/tool/plugin/shell.ts
+5-10Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -122,23 +122,20 @@ const backgroundResult = (info: ShellResult.Result["info"], timeout?: number) =>
122122

123123
// Tells the session how a background command ended, once its job settles.
124124
const notify = Effect.fnUntraced(function* (
125-
sessions: Session.Interface,
125+
sessions: Pick<Session.Interface, "synthetic">,
126126
jobs: Job.Interface,
127127
input: {
128128
readonly sessionID: SessionSchema.ID
129129
readonly id: string
130130
readonly shellID: string
131131
readonly command: string
132132
readonly settled: Deferred.Deferred<Output>
133-
// Read at delivery; `false` admits the notice without waking the session.
134-
readonly resume?: () => false | undefined
135133
},
136134
) {
137135
const info = (yield* jobs.wait({ id: input.id })).info
138136
if (!info || info.status === "running") return
139137
const output = info.status === "completed" ? yield* Deferred.await(input.settled) : undefined
140138
const text = output ? (info.output ?? "") : info.status === "error" ? (info.error ?? "Command failed") : "Cancelled"
141-
const resume = input.resume?.()
142139
// A session deleted while its command ran has no one left to tell.
143140
yield* sessions
144141
.synthetic({
@@ -153,7 +150,6 @@ const notify = Effect.fnUntraced(function* (
153150
text,
154151
output,
155152
}),
156-
...(resume === false ? { resume } : {}),
157153
})
158154
.pipe(Effect.catchTag("Session.NotFoundError", () => Effect.void))
159155
if (info.notificationID) yield* jobs.completeBackground(info.notificationID)
@@ -166,6 +162,7 @@ const startJob = Effect.fnUntraced(function* (
166162
input: {
167163
readonly sessionID: SessionSchema.ID
168164
readonly info: ShellSchema.Info
165+
readonly background?: boolean
169166
readonly notificationID?: SessionMessage.ID
170167
readonly timeout?: () => number
171168
},
@@ -185,6 +182,7 @@ const startJob = Effect.fnUntraced(function* (
185182
command: info.command,
186183
},
187184
...(input.notificationID ? { notificationID: input.notificationID } : {}),
185+
background: input.background,
188186
run: Effect.gen(function* () {
189187
const result = yield* shell.result(info)
190188
if (!result.capture) return yield* new Shell.NotFoundError({ id: info.id })
@@ -225,22 +223,19 @@ export const backgroundToolResult = (info: ShellSchema.Info) => {
225223
export const reattach = Effect.fnUntraced(function* (input: {
226224
readonly shell: Shell.Interface
227225
readonly jobs: Job.Interface
228-
readonly sessions: Session.Interface
226+
readonly sessions: Pick<Session.Interface, "synthetic">
229227
readonly sessionID: SessionSchema.ID
230228
readonly info: ShellSchema.Info
231229
// The job's existing durable row, if the previous server had backgrounded it.
232230
readonly notificationID?: SessionMessage.ID
233-
readonly resume?: () => false | undefined
234231
}) {
235-
const { job, settled } = yield* startJob(input.jobs, input.shell, input)
236-
yield* input.jobs.background(job.id)
232+
const { job, settled } = yield* startJob(input.jobs, input.shell, { ...input, background: true })
237233
const notifying = notify(input.sessions, input.jobs, {
238234
sessionID: input.sessionID,
239235
id: job.id,
240236
shellID: input.info.id,
241237
command: input.info.command,
242238
settled,
243-
resume: input.resume,
244239
})
245240
const current = yield* input.shell.get(input.info.id).pipe(Effect.option)
246241
if (Option.isSome(current) && current.value.status !== "running")

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.