Skip to content

tui: agent catalog never recovers when the completing agent.updated has no location #63435

Done

Description

@sage-z-cn

Summary

On 2.2.7, a long-lived TUI can get stuck with only the built-in agents (build, plan) for its Location and never recover, even though the server keeps returning the full list including plugin-provided agents. The server's agent.list for that directory returns orchestrator at the same moment the TUI shows only build and plan, and restarting the TUI fixes it.

The only observable difference between a stuck instance and a healthy one in the logs: the agent.updated event that completed plugin agent registration for the stuck Location had no location field, and the TUI client drops those events.

Environment

  • opencode version: 2.2.7 (channel latest), Windows 11, Windows Terminal
  • Plugin: [email protected], which registers orchestrator plus five subagents through ctx.agent.transform(...)
  • Several MCP servers configured, including slow ones (npx-launched playwright, rea with 229 tools)
  • Reproduced on two separate days with different working directories, so it is not directory-specific

Actual behavior

The agent picker shows only build and plan. plan is a built-in, so the list contains no plugin agents at all. It stays that way for hours; nothing recovers it except restarting that TUI.

At the same time, the server answers correctly:

GET /api/agent?location[directory]=<workspace>
→ orchestrator, build, compaction, title, summary, plan, explorer, oracle, designer, fixer, observer

So this is a client-side catalog staleness bug, not a registration failure.

Why it never recovers

agent.updated is published once. packages/core/src/agent.ts wires the notify through State.changes, which only publishes when the serialized projection actually changes:

notify: State.changes(list, () => bus.publish(Agent.Event.Updated, {}).pipe(Effect.asVoid)),

After the plugin agents are registered, the list never changes again, so no further agent.updated is emitted. A client that missed that single event has no way back short of a reconnect or restart.

Why the event gets missed

Two things combine:

1. The event may be published without a location. packages/core/src/bus.ts:

const serviceLocation = Option.getOrUndefined(yield* Effect.serviceOption(Location.Service))
const location = options?.global
  ? undefined
  : (options?.location ??
    (serviceLocation
      ? { directory: serviceLocation.directory, workspaceID: serviceLocation.workspaceID }
      : undefined))

If the publishing fiber has no Location.Service in context, the payload simply has no location key. Plugin agent registration can land in exactly that situation: the promise adapter exposes agent.reload as () => run(host.agent.reload()), i.e. a plain microtask (packages/plugin/src/promise/adapter.ts), and a plugin that defers finalization (as this one does when the MCP snapshot is not ready yet) triggers it outside the Location-scoped Effect.

2. The client drops location-less catalog events. packages/client/src/solid/data.ts:

if (!event.location) return
const location = event.location
switch (event.type) {
  ...
  case "agent.updated":
    refreshLocation("agent", result.location.agent, location)

Any agent.updated without location returns early and refreshes nothing.

Note that the mini runtime has the opposite (and safer) behavior in packages/tui/src/mini/stream-v2.transport.ts:

if (input.location && event.location && event.location.directory !== input.location.directory) return
void refreshCatalog(attempt)

It refreshes on a location-less event. The full TUI does not, so the two frontends diverge here.

Log evidence

Two occurrences, both on 2.2.7. Each startup registers plugin agents once per Location, but only some Locations get an agent.updated carrying their directory.

2026-11-11, startup for the affected workspace:

09:28:48.543  location services booted  directory=<workspace> durationMs=344
09:28:48.553  loading plugin [email protected]
09:28:56.365  [plugin] agents registered {"count":6}     ← this Location's registration
09:28:56.410  event type=agent.updated  location=<none>   ← no location: dropped by the client
09:28:56.583  mcp connected server=calc
...
(no further agent.updated for <workspace> for the rest of the session)

2026-11-12, three Locations booting at once:

00:47:32.683  event type=agent.updated  location=<project-a>        ← healthy
00:47:36.285  event type=agent.updated  location=<global config>    ← healthy
00:47:36.741  [plugin] agents registered {"count":6}
00:47:36.768  event type=agent.updated  location=<none>             ← affected workspace, dropped

Both stuck instances map to the location-less event; the Locations that received a located event were fine. In the 11-12 case the affected Location was also the slowest to boot (durationMs=11926, versus 313 and 2517 for the others), which is consistent with the client's first location.sync landing before plugin agents existed.

Steps to reproduce

Timing-dependent; I could not force it deterministically.

  1. Configure oh-my-opencode-slim (or any plugin that registers agents through ctx.agent.transform) plus several slow MCP servers.
  2. Make one Location cold and slow to boot (new directory, or a large worktree).
  3. Start opencode in that directory so the TUI connects and syncs its catalog while the Location is still booting.
  4. Open the agent picker. It shows only built-in agents.
  5. Check /api/agent?location[directory]=... on the same server: the full list is returned.
  6. Restart that TUI: the agents appear.

Expected behavior

The agent list converges to the server's list without requiring a restart, regardless of when the client connected.

Possible fixes

  • Client: do not drop catalog events that lack a location. Refresh every Location the client already holds (or fall back to the current/default Location), as the mini runtime already does.
  • Server: publish agent.updated (and the other catalog events) with a location whenever the change belongs to a Location, including changes triggered from a promise-context plugin call.
  • Belt and braces: after location.sync returns a list, if any plugin is still activating, refresh once more when plugin.updated reports activation settled.

Additional context

  • Likely related: fix(server): stop waiting for plugins in request handlers #62796 ("stop waiting for plugins in request handlers") removed the plugin-activation wait from agent.list, so a cold Location can now legitimately answer with built-ins only. That makes the client's *.updated handling load-bearing; before it, the first read always saw the full list.
  • Related but a different trigger: tui: --prompt sessions start with build instead of default_agent when agents are still loading (2.2.7) #63192 (sessions created before agents load fall back to build).
  • A separate, unrelated failure mode I also hit on 2.2.6: a config hot reload disposes the plugin generation before the next one registers its agents, so an in-flight session drain fails with Session.AgentNotFoundError: Agent not found: "orchestrator". Mentioning it only because it is another way the same agent can be missing at the wrong moment.
  • Workaround: none found. Restarting the affected TUI is the only recovery; saving a config file does not help, because config.updated does not refresh the agent catalog.

Activity

  1. added
    area/tui
    type/bug
    version/v2
    on Nov 12, 2026
  2. opencodejr commented on Nov 12, 2026

    @opencodejr
    Contributor

    Seen with a simulated model or a mock server, not a real provider; a maintainer should confirm.

    Thanks for the detailed report. I was able to reproduce this on 2.2.7. A minimal local plugin stood in for oh-my-opencode-slim: it adds an orchestrator primary agent with ctx.agent.transform 4 seconds after its setup returns. No real MCP servers were involved.

    What I saw:

    • The late registration publishes a single agent.updated event with no location.
    • The server's agent.list then includes orchestrator.
    • The TUI agent picker keeps showing only build and plan and never refreshes.

    The recording and screenshot below show the picker. The script below reproduces it, and it logs the location-less event next to the server's list.

    This matches your analysis: the client ignores agent.updated events that have no location, and the agent list publishes no further event once it stops changing. It still happens on the latest dev (f5ca39a), run from source.

    Related: #63192 (same 2.2.7 cold-Location timing, with --prompt sessions falling back to build).

    recording.mp4

    Screenshot

    Reproduction script (drive.ts)
    // Repro for anomalyco/opencode#63435: a plugin that registers its agents after a
    // delay (outside setup), as plugins that wait for MCP do. The TUI never shows them.
    import { Effect, Stream } from "effect"
    import { OpenCodeDriver } from "opencode-drive"
    
    const plugin = `export default {
      id: "repro.late-agents",
      async setup(ctx) {
        // Register agents later, outside setup (like a plugin waiting on slow MCP servers).
        setTimeout(() => {
          ctx.agent.transform((editor) => {
            editor.update("orchestrator", (a) => { a.name = "Orchestrator"; a.mode = "primary"; a.description = "late plugin agent" })
          }).then(() => console.error("[repro] agents registered"))
        }, 4000)
      },
    }
    `
    
    export default OpenCodeDriver.use(
      {
        ...(process.env.OC_DEV ? { opencode: { dev: process.env.OC_DEV } } : {}),
        project: { git: true, files: { ".opencode/plugins/late-agents.js": plugin } },
        tui: { recording: true, keypressOverlay: true },
      },
      (oc) =>
        Effect.gen(function* () {
          // Log every agent.updated the server publishes, with its location (or none).
          yield* ((oc.opencode as any).event.subscribe() as any).pipe(
            Stream.filter((e: any) => e.type === "agent.updated"),
            Stream.runForEach((e: any) =>
              Effect.log("event agent.updated location=" + (e.location ? JSON.stringify(e.location) : "<none>")),
            ),
            Effect.forkChild,
          ) as Effect.Effect<unknown, never, never>
          yield* oc.ui.screenshot("start")
          yield* Effect.sleep("10 seconds")
          const agents: any = yield* ((oc.opencode as any).agent.list({}) as Effect.Effect<any, any, never>).pipe(
            Effect.catch((e: unknown) => Effect.succeed("list failed: " + String(e))),
          )
          yield* Effect.log("server agent.list ids: " + JSON.stringify((agents?.data ?? agents).map?.((a: any) => a.id) ?? agents))
          yield* oc.ui.press("x", { ctrl: true })
          yield* oc.ui.press("a")
          yield* Effect.sleep("1 second")
          yield* oc.ui.screenshot("agent-picker")
          const frame = yield* oc.ui.capture()
          yield* Effect.log("TUI frame:\n" + (frame as any).lines.map((l: any) => l.spans.map((x: any) => x.text).join("")).join("\n"))
        }),
    )

    Run it with opencode-drive: opencode-drive run ./drive.ts. It drives opencode from your PATH; set OC_DEV to the path of an OpenCode checkout to run that from source instead.

  3. added
    status/repro-simulated
    on Nov 12, 2026
  4. dhairyajangir commented on Nov 12, 2026

    @dhairyajangir

    I found #57186, which addresses the missing Location in asynchronous plugin reloads. Would a complementary client-side fallback that refreshes already-loaded or in-flight agent catalogs for location-less agent.updated events be useful, or should this wait for #57186?

  5. mhenke commented on Nov 14, 2026

    @mhenke

    I maintain oh-my-opencode-slim, the plugin side of this. I traced the path that produces the location-less event against v2.2.0 source.

    Our agent pass finishes one of two ways. Inline: the agent.transform callback finalizes our agents and the host publishes inside the Location-scoped transform, so the event carries a location. Deferred: when the pass runs before the MCP snapshot exists (slow MCP servers), we finish it later from the MCP callback and call ctx.agent.reload() from a microtask.

    Here is where the location goes missing:

    • reload is () => changed in packages/core/src/state.ts, so the notify and Agent.Event.Updated publish run in whichever fiber called reload.
    • Plugins run on fromPromise (packages/plugin/src/promise/adapter.ts). That context does not carry Location.Service.
    • bus.publish then omits location, and the client's if (!event.location) return drops the event.

    I checked that the plugin cannot repair this alone. reload() takes no location argument, and nothing in the plugin context is location-scoped. The fix has to come from the host or the client:

    1. Run a state rebuild's notify under the Location that owns the state, so the catalog event carries a location no matter which fiber triggered it.
    2. Or on the client, do not drop a location-less agent.updated silently. Refresh the agent catalog for the active directory on it.

    Option 2 would also recover sessions that missed an earlier event, which matches what sage-z-cn describes.

    I have not reproduced the live case. The #1374 test in our repo drives the deferred path with a fake host and does not assert the event's location, so it does not prove the chain above end to end.

    Thanks to sage-z-cn for the detailed report and to matrix7095 for the macOS cold-worktree evidence. It narrowed this down a lot.

  6. matthewmorek commented on Nov 20, 2026

    @matthewmorek

    Confirming the symptom on OpenCode v2.3.2 (c0ad18b402eb), macOS 27.2.1 arm64. On first launch in a new Git worktree, /agents stays on Plan and Build. A second TUI in the same worktree shows General and Review while the first remains stale. I also reproduced the first-open symptom with --standalone.

    In a controlled v2.3.2 client test, a matching agent.updated triggered a second fetch and exposed both agents. Omitting only event.location left the client on Plan and Build. In contrast, the unmodified plugin in an isolated ordinary directory emitted a correctly scoped update, and the first client recovered automatically. A missing location reproduces the symptom, but we haven’t captured the event from a failing live launch to confirm that’s the cause.

    Diagnostic versions: @opencode/{client,plugin,server,tui} 2.3.2, solid-js 1.9.17, effect 4.1.0, Bun 1.4.1 (the tag pins 1.4.4).

  7. argszero commented on Nov 21, 2026

    @argszero
    Contributor

    I'd like to work on this.

    I re-checked dev at edacc8686a8b89ed5aae75b2833fd99fcd8da7f9 and both halves of the chain are still there: packages/client/src/solid/data.ts:1460 still returns early on a catalog event that carries no location, while packages/tui/src/mini/stream-v2.transport.ts:1029 already does the opposite and refreshes the catalog on a location-less event. So the two frontends still diverge exactly as the report says.

    My plan is the client-side option the report lists first: stop dropping a location-less agent.updated in the full TUI, and refresh the catalog for the Locations the client already holds instead, mirroring what the mini runtime does. The change stays inside the client data provider, and I'll add a test that fails on today's tree — an agent.updated with no location leaves the picker on the built-ins today, and should refresh it after the change.

    Two notes on scope, so this doesn't surprise anyone later:

    • The server-side option in the thread, publishing the catalog event under the Location that owns the state, looks like the more durable fix. #57186 took the host-side route and was closed unmerged. If you'd rather have that direction instead of the client fallback, say so and I'll switch before opening the PR.
    • I can't watch the original failing launch, since it needs a cold Windows Location with slow MCP servers. My verification will be the client test plus parity with the mini runtime, and I'll say so in the PR rather than imply I reproduced the live case.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area/tuiplatform/windowsstatus/repro-simulatedtype/bugversion/v2

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions