Skip to content

Commit 2d07e14

Browse files
committed
feat(tui): subagent indicator via isolated sidecar (v2)
Reworks the v1 patch into an additive, dead-code-friendly sidecar: Removes (reverts v1 modifications to existing files): - packages/core/src/background-job.ts: drop the inline LifecycleEvent PubSub + subscribe() method. The sidecar now polls BackgroundJob.list() instead. - packages/opencode/src/background/job.ts: drop the LifecycleEvent re-export and subscribe() wire-up. - packages/opencode/src/session/run-state.ts: drop the subagentCounts map and the per-event fiber. SessionRunState is back to its upstream shape; it no longer drives SessionStatus directly. - packages/schema/src/session-status-event.ts: drop the 'waiting' status variant. SessionStatus stays exactly as upstream defines it. Adds (entirely new surface, easy to remove): - packages/schema/src/local-subagent-indicator-event.ts: a new event type 'local.subagent.indicator' (note the 'local.' prefix) carrying { sessionID, info: { count } }. Independent of SessionStatus. - packages/opencode/src/local/subagent-indicator.ts: a sidecar service gated by the new experimentalLocalSubagentIndicator flag (defaults off). When on, it polls BackgroundJob.list() every 1s, tracks per-parent running counts, and emits the local event. When off, the layer is a no-op. - packages/opencode/src/effect/runtime-flags.ts: 1 new flag, following the existing enabledByExperimental('OPENCODE_EXPERIMENTAL_LOCAL_SUBAGENT_INDICATOR') convention so it can be toggled via the standard OPENCODE_EXPERIMENTAL umbrella or its own env var. - packages/opencode/src/server/server.ts: 1 new Layer.provideMerge line to wire the sidecar into the server layer composition. - packages/schema/src/event-manifest.ts: 1 new line in the inventory. - packages/tui/src/context/sync.tsx: a new local_subagent_indicator field in the sync store and an event.on('local.subagent.indicator', ...) listener to populate it. - packages/tui/src/routes/session/footer.tsx: a new <Show> block that renders '⏳ N subagent(s)' when count > 0. Why this shape: if anomalyco/opencode (or any upstream) ever ships their own subagent indicator — a 'waiting' SessionStatus variant, a tree view, a different event — the local patch becomes inert without conflict. The user just sets experimentalLocalSubagentIndicator: false (or unsets OPENCODE_EXPERIMENTAL_LOCAL_SUBAGENT_INDICATOR) and our sidecar stops; the TUI stops reading from local_subagent_indicator. Nothing in upstream types or interfaces was touched, so a rebase upstream is just `git rm packages/opencode/src/local packages/schema/src/local-subagent-indicator-event.ts` plus reverting the 5 additive lines in event-manifest.ts, runtime-flags.ts, server.ts, sync.tsx, footer.tsx. Polling at 1s (instead of event subscription) is the cost of not modifying BackgroundJob's interface. Acceptable for a footer counter. Related upstream: anomalyco#23784 (existing feature request). Anomalyco's PR anomalyco#32167 closed as too broad; this is a minimal slice explicitly designed to be disposable.
1 parent dd69cfd commit 2d07e14

14 files changed

Lines changed: 434 additions & 169 deletions

File tree

‎HOWTO.md‎

Lines changed: 129 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -1,74 +1,148 @@
1-
# Patched opencode: TUI subagent indicator
1+
# Patched opencode: TUI subagent indicator (sidecar)
2+
3+
Local build of opencode that shows running background subagents in the TUI
4+
footer (e.g. `⏳ 2 subagents`).
5+
6+
## Why this is structured the way it is
7+
8+
The whole point of this patch is to be **dead-code-friendly when upstream
9+
ships a fix**. If `anomalyco/opencode` (or anyone) eventually adds their
10+
own subagent indicator — whether a `waiting` SessionStatus variant, a new
11+
event, or a tree view — our local patch should become inert without
12+
fights, not a permanent fork.
13+
14+
To achieve that, the patch follows three rules:
15+
16+
1. **No modifications to existing upstream types or interfaces.** Nothing in
17+
`packages/schema/src/session-status-event.ts`,
18+
`packages/core/src/background-job.ts`, or any existing service
19+
interface is touched. The `BackgroundJob.subscribe()` method we
20+
prototyped in v1 was removed.
21+
2. **All new code lives in new files** under `packages/schema/src/local-*`
22+
and `packages/opencode/src/local/`. The `local.` prefix on the event
23+
type (`local.subagent.indicator`) is intentional — it cannot collide
24+
with anything upstream picks.
25+
3. **Everything is gated by `experimental.localSubagentIndicator`** in
26+
`RuntimeFlags`. Off → sidecar is a no-op, no events fire, the TUI
27+
shows nothing from us. On → the sidecar runs.
28+
29+
The TUI checks both `session.status` (upstream's) and
30+
`local_subagent_indicator` (ours). If upstream ships a `waiting` variant
31+
with the same field, both indicators will agree. If upstream ships
32+
something with a different shape, our footer just keeps reading from the
33+
local channel; the user disables the flag and we're invisible.
34+
35+
## Architecture
236

3-
Local build of opencode with a small TUI patch that shows running background
4-
subagents in the footer (e.g. `⏳ 2 subagents`).
5-
6-
## What's different
7-
8-
When the parent session is idle but has background subagents running, the TUI
9-
footer now shows a `⏳ N subagent(s)` indicator. Without this, the parent
10-
session looks "idle" and it's unclear whether the main agent is still working
11-
or whether it's actually waiting for subagents to finish.
12-
13-
When the parent is busy (running a model itself), the busy state wins.
14-
When all subagents finish, the indicator disappears and the parent goes idle.
15-
16-
## Files touched
17-
18-
- `packages/schema/src/session-status-event.ts` — new `waiting` status variant
19-
with `subagents: number`
20-
- `packages/core/src/background-job.ts` — PubSub-based lifecycle event bus
21-
(started / settled / cancelled)
22-
- `packages/opencode/src/background/job.ts` — wire up the new `subscribe()`
23-
method
24-
- `packages/opencode/src/session/run-state.ts` — subscriber that maintains a
25-
per-parent running count and transitions SessionStatus accordingly
26-
- `packages/tui/src/routes/session/footer.tsx` — render the indicator
27-
28-
## Install / reinstall
37+
```
38+
BackgroundJob.list() ─── sidecar (polls every 1s) ──> EventV2.publish
39+
│
40+
▼
41+
TUI event listener ◄──── EventV2 stream ◄──── "local.subagent.indicator"
42+
│
43+
▼
44+
sync store: local_subagent_indicator[sessionID] = { count }
45+
│
46+
▼
47+
Footer renders: "⏳ N subagent(s)" when count > 0
48+
```
2949

30-
The patched binary is at:
50+
**Polling at 1 second** instead of subscribing to BackgroundJob events.
51+
This is intentional: it requires zero changes to `core/background-job.ts`.
52+
The cost is up to 1 second of staleness on the indicator — acceptable
53+
for a footer counter.
54+
55+
## Files
56+
57+
- `packages/schema/src/local-subagent-indicator-event.ts` — new event
58+
def: `local.subagent.indicator` with `{ sessionID, info: { count } }`
59+
- `packages/schema/src/event-manifest.ts` — adds the new event to the
60+
inventory (additive — only a new line)
61+
- `packages/opencode/src/effect/runtime-flags.ts` — adds the
62+
`experimentalLocalSubagentIndicator` flag (additive — new line)
63+
- `packages/opencode/src/local/subagent-indicator.ts` — **new file**,
64+
the sidecar service
65+
- `packages/opencode/src/server/server.ts` — wires the sidecar into the
66+
server layer composition (one new `Layer.provideMerge` line)
67+
- `packages/tui/src/context/sync.tsx` — adds the
68+
`local_subagent_indicator` field to the sync store (additive — new
69+
field, new line in initial state, new `event.on` listener)
70+
- `packages/tui/src/routes/session/footer.tsx` — renders the indicator
71+
(additive — new `<Show>` block, no changes to existing code paths)
72+
73+
## Install / rebuild
74+
75+
The patched binary lives at:
3176

3277
```
3378
/var/home/thegalkin/opencode-tui-subagent-indicator/packages/opencode/dist/opencode-linux-x64/bin/opencode
3479
```
3580

36-
A symlink in `~/bin/opencode` already points at it and wins over the
37-
linuxbrew one (verified with `which opencode`).
81+
A symlink at `~/bin/opencode` already points at it and wins over the
82+
linuxbrew version (`which opencode` confirms). To revert, just delete
83+
the symlink — the linuxbrew opencode stays untouched.
3884

3985
To rebuild after editing source:
4086

4187
```sh
4288
cd /var/home/thegalkin/opencode-tui-subagent-indicator
89+
bun script/generate.ts # regen SDK
4390
bunx [email protected] --bun packages/opencode/script/build.ts --single --skip-install --skip-embed-web-ui
4491
```
4592

46-
The homebrew `opencode` is left untouched. To revert, just delete the symlink:
93+
## Enabling the indicator
4794

48-
```sh
49-
rm ~/bin/opencode
50-
```
51-
52-
## Enable background subagents
53-
54-
This is a `OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS=true` feature. Set the
55-
env var (in your shell rc, or per-invocation) when you want agents to be able
56-
to call `task(background=true)`.
95+
Set the env var before launching opencode:
5796

58-
## Try it
59-
60-
1. Open the TUI on any project: `opencode .`
61-
2. Ask the main agent to spawn background subagents (e.g. "run 3 explore tasks
62-
in parallel in the background and tell me when each one finishes")
63-
3. Watch the bottom-right of the TUI: you'll see `⏳ 3 subagents` and the
64-
count will drop as each subagent finishes
65-
66-
## Upstream
97+
```sh
98+
# Either: enable only this feature
99+
export OPENCODE_EXPERIMENTAL_LOCAL_SUBAGENT_INDICATOR=true
67100

68-
The feature is requested in `anomalyco/opencode#23784`. A broader proposal
69-
(`#32167`) was closed as too large. The patch on branch
70-
`feat/tui-subagent-indicator` in `thegalkin/opencode` is a minimal slice of
71-
that — schema-level waiting status + footer indicator only.
101+
# Or: enable the umbrella that turns on all experiments
102+
export OPENCODE_EXPERIMENTAL=true
103+
```
72104

73-
To send upstream: open a PR with the existing branch and reference
74-
`#23784` in the description so maintainers can route it through design review.
105+
(These are read from `RuntimeFlags` via the standard `enabledByExperimental`
106+
helper — the same mechanism used by `OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS`
107+
and friends.)
108+
109+
When the flag is off, the sidecar layer is a no-op: no fiber starts, no
110+
BackgroundJob polling, no events fire. The TUI sees an empty
111+
`local_subagent_indicator` map and renders nothing extra.
112+
113+
## Upstream behavior
114+
115+
If/when `anomalyco/opencode` ships its own fix:
116+
117+
- They likely use a different flag name → our flag stays meaningful, no
118+
conflict, the user can keep using our local version
119+
- They use the same flag name (`experimentalLocalSubagentIndicator`) → user
120+
turns our flag off, upstream's solution takes over
121+
- They add a different mechanism entirely (a `waiting` SessionStatus
122+
variant, a tree view, etc.) → user can keep both: our footer indicator
123+
shows the count, upstream's view shows the tree
124+
- They add a `local.subagent.indicator` event with a different payload
125+
shape → TS compile error on the TUI's `event.on("local.subagent.indicator", ...)`
126+
call. Fix: remove that line (or just disable the flag)
127+
128+
In the worst case, removing our patch is `git rm packages/opencode/src/local/
129+
packages/schema/src/local-subagent-indicator-event.ts` and reverting the
130+
~5 additive lines in `event-manifest.ts`, `runtime-flags.ts`, `server.ts`,
131+
`sync.tsx`, `footer.tsx`.
132+
133+
## How to test
134+
135+
1. Set the env var: `export OPENCODE_EXPERIMENTAL_LOCAL_SUBAGENT_INDICATOR=true`
136+
2. Open the TUI on any project: `opencode .`
137+
3. Ask the main agent to spawn background subagents, e.g.:
138+
"Run 3 explore tasks in parallel in the background and tell me when each
139+
one finishes"
140+
4. Watch the bottom-right of the TUI: `⏳ 3 subagents` appears, count
141+
drops as each subagent finishes, indicator disappears when all done
142+
143+
If nothing shows up, check:
144+
- `opencode --version` returns `0.0.0-feat/tui-subagent-indicator-...`
145+
- The env var is set in the same shell as `opencode`
146+
- The main agent actually called the `task` tool with `background=true`
147+
(and `OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS=true` or the umbrella
148+
is set)

‎packages/core/src/background-job.ts‎

Lines changed: 3 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,11 @@
11
export * as BackgroundJob from "./background-job"
22

3-
import { Cause, Clock, Context, Deferred, Effect, Exit, Layer, PubSub, Scope, SynchronizedRef } from "effect"
3+
import { Cause, Clock, Context, Deferred, Effect, Exit, Layer, Scope, SynchronizedRef } from "effect"
44
import { Identifier } from "./id/id"
55
import { makeGlobalNode } from "./effect/app-node"
66

77
export type Status = "running" | "completed" | "error" | "cancelled"
88

9-
/** Emitted on every transition in a job's lifecycle. */
10-
export type LifecycleEvent = {
11-
type: "started" | "settled" | "cancelled"
12-
info: Info
13-
}
14-
159
export type Info = {
1610
id: string
1711
type: string
@@ -40,7 +34,6 @@ type Active = {
4034
type State = {
4135
jobs: SynchronizedRef.SynchronizedRef<Map<string, Active>>
4236
scope: Scope.Scope
43-
lifecycle: PubSub.PubSub<LifecycleEvent>
4437
}
4538

4639
type FinishResult = {
@@ -101,7 +94,6 @@ export interface Interface {
10194
readonly waitForPromotion: (id: string) => Effect.Effect<Info>
10295
readonly promote: (id: string) => Effect.Effect<Info | undefined>
10396
readonly cancel: (id: string) => Effect.Effect<Info | undefined>
104-
readonly subscribe: () => Effect.Effect<PubSub.Subscription<LifecycleEvent>, never, Scope.Scope>
10597
}
10698

10799
export class Service extends Context.Service<Service, Interface>()("@opencode/BackgroundJob") {}
@@ -129,7 +121,6 @@ export const make = Effect.gen(function* () {
129121
const state: State = {
130122
jobs: yield* SynchronizedRef.make(new Map()),
131123
scope: yield* Scope.Scope,
132-
lifecycle: yield* PubSub.unbounded<LifecycleEvent>(),
133124
}
134125

135126
const settle = Effect.fn("BackgroundJob.settle")(function* (
@@ -176,10 +167,6 @@ export const make = Effect.gen(function* () {
176167
if (result.scope) {
177168
yield* Scope.close(result.scope, Exit.void).pipe(Effect.forkIn(state.scope, { startImmediately: true }))
178169
}
179-
if (result.info && result.info.status !== "running") {
180-
const event: LifecycleEvent = { type: "settled", info: result.info }
181-
yield* PubSub.publish(state.lifecycle, event)
182-
}
183170
return result.info
184171
})
185172

@@ -253,17 +240,14 @@ export const make = Effect.gen(function* () {
253240
]
254241
}),
255242
)
256-
if ("scope" in result) {
243+
if ("scope" in result)
257244
yield* fork(
258245
result.scope,
259246
id,
260247
result.token,
261248
0,
262249
restore(input.run).pipe(Effect.ensuring(Deferred.succeed(tail, undefined))),
263250
)
264-
const event: LifecycleEvent = { type: "started", info: result.info }
265-
yield* PubSub.publish(state.lifecycle, event)
266-
}
267251
return result.info
268252
}),
269253
)
@@ -370,18 +354,10 @@ export const make = Effect.gen(function* () {
370354
})
371355
if (result.info && result.done) yield* Deferred.succeed(result.done, result.info).pipe(Effect.ignore)
372356
if (result.scope) yield* Scope.close(result.scope, Exit.void)
373-
if (result.info && result.info.status === "cancelled") {
374-
const event: LifecycleEvent = { type: "cancelled", info: result.info }
375-
yield* PubSub.publish(state.lifecycle, event)
376-
}
377357
return result.info
378358
})
379359

380-
const subscribe: Interface["subscribe"] = Effect.fn("BackgroundJob.subscribe")(function* () {
381-
return yield* PubSub.subscribe(state.lifecycle)
382-
})
383-
384-
return Service.of({ list, get, start, extend, wait, waitForPromotion, promote, cancel, subscribe })
360+
return Service.of({ list, get, start, extend, wait, waitForPromotion, promote, cancel })
385361
})
386362

387363
const layer = Layer.effect(Service, make)

‎packages/opencode/src/background/job.ts‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ export {
88
type ExtendInput,
99
type Info,
1010
type Interface,
11-
type LifecycleEvent,
1211
type StartInput,
1312
type Status,
1413
type WaitInput,
@@ -29,7 +28,6 @@ const layer = Layer.effect(
2928
waitForPromotion: (id) => InstanceState.useEffect(state, (jobs) => jobs.waitForPromotion(id)),
3029
promote: (id) => InstanceState.useEffect(state, (jobs) => jobs.promote(id)),
3130
cancel: (id) => InstanceState.useEffect(state, (jobs) => jobs.cancel(id)),
32-
subscribe: () => InstanceState.useEffect(state, (jobs) => jobs.subscribe()),
3331
})
3432
}),
3533
)

‎packages/opencode/src/effect/runtime-flags.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ export class Service extends ConfigService.Service<Service>()("@opencode/Runtime
4848
experimentalEventSystem: enabledByExperimental("OPENCODE_EXPERIMENTAL_EVENT_SYSTEM"),
4949
experimentalWorkspaces: enabledByExperimental("OPENCODE_EXPERIMENTAL_WORKSPACES"),
5050
experimentalIconDiscovery: enabledByExperimental("OPENCODE_EXPERIMENTAL_ICON_DISCOVERY"),
51+
experimentalLocalSubagentIndicator: enabledByExperimental("OPENCODE_EXPERIMENTAL_LOCAL_SUBAGENT_INDICATOR"),
5152
outputTokenMax: positiveInteger("OPENCODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX"),
5253
bashDefaultTimeoutMs: positiveInteger("OPENCODE_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS"),
5354
experimentalNativeLlm: bool("OPENCODE_EXPERIMENTAL_NATIVE_LLM"),
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
import { LayerNode } from "@opencode-ai/core/effect/layer-node"
2+
import { EventV2 } from "@opencode-ai/core/event"
3+
import { EventV2Bridge } from "@/event-v2-bridge"
4+
import { RuntimeFlags } from "@/effect/runtime-flags"
5+
import { BackgroundJob } from "@/background/job"
6+
import { LocalSubagentIndicatorEvent } from "@opencode-ai/schema/local-subagent-indicator-event"
7+
import { SessionID } from "@/session/schema"
8+
import { Context, Effect, Layer } from "effect"
9+
10+
class Service extends Context.Service<Service, {}>()("@opencode/LocalSubagentIndicator") {}
11+
12+
const layer = Layer.effect(
13+
Service,
14+
Effect.gen(function* () {
15+
const flags = yield* RuntimeFlags.Service
16+
17+
if (!flags.experimentalLocalSubagentIndicator) {
18+
return Service.of({})
19+
}
20+
21+
const background = yield* BackgroundJob.Service
22+
const events = yield* EventV2Bridge.Service
23+
24+
const counts = new Map<SessionID, number>()
25+
26+
yield* Effect.forkScoped(
27+
Effect.gen(function* () {
28+
while (true) {
29+
const jobs = yield* background.list()
30+
const next = new Map<SessionID, number>()
31+
32+
for (const job of jobs) {
33+
if (job.status !== "running") continue
34+
const parent = job.metadata?.parentSessionId
35+
if (typeof parent !== "string") continue
36+
const sessionID = SessionID.make(parent)
37+
next.set(sessionID, (next.get(sessionID) ?? 0) + 1)
38+
}
39+
40+
for (const [sessionID, count] of next) {
41+
if (count !== counts.get(sessionID)) {
42+
yield* events.publish(LocalSubagentIndicatorEvent.Update, {
43+
sessionID,
44+
info: { count },
45+
})
46+
}
47+
}
48+
49+
for (const [sessionID, prev] of counts) {
50+
if (!next.has(sessionID)) {
51+
yield* events.publish(LocalSubagentIndicatorEvent.Update, {
52+
sessionID,
53+
info: { count: 0 },
54+
})
55+
}
56+
}
57+
58+
counts.clear()
59+
for (const [k, v] of next) counts.set(k, v)
60+
61+
yield* Effect.sleep("1 second")
62+
}
63+
}).pipe(Effect.forever),
64+
)
65+
66+
return Service.of({})
67+
}),
68+
)
69+
70+
export const node = LayerNode.make({
71+
service: Service,
72+
layer,
73+
deps: [BackgroundJob.node, EventV2Bridge.node, RuntimeFlags.node],
74+
})
75+
76+
export * as LocalSubagentIndicator from "./subagent-indicator"

0 commit comments

Comments
 (0)