Files
worktrunk/dev/opencode-plugin.ts
T
Worktrunk Botandworktrunk-bot c83606447d fix(opencode): clear the activity marker when OpenCode 1 disposes the plugin (#4129)
## Problem

On OpenCode 1.x the plugin's `server` export drives the marker, and its
only clearing path is the `session.deleted` event — which fires when a
session is explicitly deleted, not when one ends normally. So a finished
session leaves its last `set 💬` in place and `wt list` keeps showing a
dead session as active until `wt config state marker clear` is run by
hand. Reported in #4128 against worktrunk 0.77.0 and OpenCode 1.18.18.

The `server` path does have a teardown hook; the plugin just wasn't
implementing it. OpenCode's v1 plugin interface declares [`dispose?: ()
=>
Promise<void>`](https://github.com/sst/opencode/blob/v1.18.18/packages/plugin/src/index.ts)
as the first member of `Hooks`, and the host calls it from an
`Effect.addFinalizer` registered alongside the event subscription in
[`packages/opencode/src/plugin/index.ts`](https://github.com/sst/opencode/blob/v1.18.18/packages/opencode/src/plugin/index.ts)
— the same place it tears the event listener down. `dispose` has been in
that interface since v1.16.0, which is the floor the `server` export
already targets, and older hosts ignore an unknown key, so there is no
version gate to add.

This also means the issue's suggested route — having OpenCode 1.18 honor
`setup()`'s return value as a teardown — is not the path: that loader is
the v2 one, and the v1 hook object already carries the teardown.

## Solution

`server()` now returns a `dispose` that clears the marker, mirroring
what the OpenCode 2 `setup()` path already does in its returned
teardown. The OpenCode 2 path is untouched.

A `dispose` that only calls `clear` isn't enough on its own, because the
host dispatches the `event` hook fire-and-forget — `void
hook["event"]?.({ event: ... })`, with no `await` and no handle kept.
The `wt config state marker set 💬` subprocess spawned by the final
`session.idle` is therefore still running when the finalizer calls
`dispose`, both write `worktrunk.state.<branch>.marker`, and whichever
`wt` finishes last decides it. That gap is narrowest in the issue's own
repro: `opencode run "wait"` goes idle and exits immediately.

So every marker call chains onto one promise, which is the handle the
`server` path otherwise lacks — the `clear` enqueues behind whatever is
outstanding. Effect closes scope finalizers LIFO and the `dispose`
finalizer is registered after the one holding `unsubscribe`, so the
listener is still live during teardown; a `disposed` flag drops what
arrives in that window rather than letting it re-set after the clear.

The doc sentence asserting that every plugin clears on session end was,
for this path, false; it is true again with this change. The same
sentence still said "all four plugins" while the list above it names
five (Claude Code, Codex, OpenCode, Pi, Gemini), so that count is
corrected in the same edit. The two `claude-code.md` mirrors are the
sync test's regeneration of the primary in `docs/src/content/docs/`.

## Testing

Node's type stripping runs `dev/opencode-plugin.ts` directly, so the
hook shape and its subprocess calls are observable without OpenCode:
with a stub `wt` on `PATH` recording each invocation and its cwd,
`server({ directory })` is called, fed events the way the host
dispatches them, and then disposed the way the host's finalizer would.

Before any of this the returned object exposed only `event`, there was
nothing for the finalizer to call, and the recorded calls ended at
`config state marker set 💬` — the stale marker. With `dispose` alone,
dispatching `session.idle` unawaited and then disposing still ended on
`set 💬`, because the clear overtook the in-flight set. With the ordering
fix the recording ends on `config state marker clear` in both that case
and the one where an event is delivered after `dispose` has begun.

`cargo test --test integration test_docs_are_in_sync`, the 13 `opencode`
integration tests, and `packaged_assets` pass.

What this cannot verify from CI is the host half — that OpenCode
actually closes that scope on a normal `opencode run` exit rather than
only on an explicit shutdown. That rests on reading the finalizer
registration above, not on an observed run; the reporter offered to test
a fix and is the fastest confirmation of the end-to-end behavior. A
`SIGKILL`ed process still skips the finalizer, which is the stale-marker
caveat the docs already carry.

There is also no test harness for `dev/*.ts` in the repo, so none of
this is pinned by CI — the checks here only assert that the plugin file
is packaged and installed. Committing the Node harness would add a test
surface rather than extend one, so it is left as a maintainer call.

Closes #4128 — automated triage

---------

Co-authored-by: worktrunk-bot <254187624+worktrunk-bot@users.noreply.github.com>
2026-09-15 22:39:09 -07:00

152 lines
5.8 KiB
TypeScript

// Worktrunk activity tracking plugin for OpenCode.
//
// Tracks OpenCode session activity per branch, showing status markers in `wt list`:
// 🤖 — agent is working
// 💬 — agent is waiting for input
//
// Installed globally via: wt config plugins opencode install
// Or manually: copy to ~/.config/opencode/plugins/worktrunk.ts
//
// One file, two plugin runtimes. OpenCode 2 decodes the default export as
// `{ id, setup }` and loads nothing else — the bare default-exported function
// this file used to be is rejected without a message. OpenCode 1 reads
// `{ id, server }` and never looks at `setup`; 1.16 is the floor that matters,
// where the host began filtering events per plugin instance (the object shape
// itself loads as far back as 1.14.19). Both ignore the other's key, so
// a single installed file works either side of the version boundary.
//
// The types below are declared locally rather than imported from
// `@opencode-ai/plugin`: its `Plugin` type means different things in the two
// versions, and a lone file in the config directory has no package to resolve.
import { execFile } from "node:child_process";
import { promisify } from "node:util";
const execute = promisify(execFile);
const WORKING = "🤖";
const WAITING = "💬";
/**
* Run `wt config state marker …` in this plugin instance's worktree.
*
* `cwd` is load-bearing: the marker belongs to the worktree the session is in,
* not to whatever directory the host process happens to sit in.
*/
async function marker(directory: string, args: string[]): Promise<void> {
try {
await execute("wt", ["config", "state", "marker", ...args], { cwd: directory });
} catch {
// `wt` may be off PATH, or the directory may no longer be a worktree. An
// activity marker is not worth raising an error into the session over.
}
}
// --- OpenCode 2 -------------------------------------------------------------
type SessionEvent = {
type: string;
location?: { directory: string };
data?: { status?: { type?: string } };
};
type SetupContext = {
location?: { directory: string };
event?: { subscribe(options?: { signal?: AbortSignal }): AsyncIterable<SessionEvent> };
};
function setup(context: SetupContext) {
const directory = context.location?.directory;
const events = context.event;
// OpenCode 1.18 also calls `setup`, from a second loader that passes neither
// of these. Its `server` hook below drives the marker there, so bail quietly
// rather than throwing out of a plugin the host did load.
if (!directory || !events) return;
const controller = new AbortController();
const watcher = (async () => {
for await (const event of events.subscribe({ signal: controller.signal })) {
// The event envelope makes `location` optional; the session events below
// carry one, and skipping the rest keeps each instance to its own worktree.
if (event.location?.directory !== directory) continue;
switch (event.type) {
case "session.status":
// Status is `idle | busy | retry`. OpenCode 2 marks `session.idle`
// deprecated in favor of this, so read the status, not the event name.
await marker(directory, ["set", event.data?.status?.type === "idle" ? WAITING : WORKING]);
break;
case "session.idle":
await marker(directory, ["set", WAITING]);
break;
case "session.deleted":
await marker(directory, ["clear"]);
break;
}
}
})().catch((error: unknown) => {
if (!controller.signal.aborted) {
console.error("Worktrunk activity tracking stopped", error);
}
});
// Awaiting the watcher before clearing keeps an in-flight `set` from landing
// after the `clear` and leaving a marker behind.
return async () => {
controller.abort();
await watcher;
await marker(directory, ["clear"]);
};
}
// --- OpenCode 1 (1.16+) -----------------------------------------------------
type ServerInput = { directory: string };
type HookInput = { event: { type: string } };
function server({ directory }: ServerInput) {
// The host dispatches `event` without awaiting it, so a `set` can still be
// running when the teardown below clears. Chaining every call onto one
// promise is what puts the `clear` last; `disposed` drops the events the
// host can still deliver, since it unsubscribes after calling `dispose`.
let pending: Promise<void> = Promise.resolve();
let disposed = false;
const enqueue = (args: string[]): Promise<void> => {
pending = pending.then(() => marker(directory, args));
return pending;
};
return {
// The host runs this when it tears the plugin instance down, which is what
// a normal session exit does. `session.deleted` below only fires when a
// session is explicitly deleted, so without `dispose` the last `set` stays
// the final state and `wt list` shows a finished session as still active.
// Part of the hook interface since 1.16, the floor the `server` path targets.
dispose: async () => {
disposed = true;
await enqueue(["clear"]);
},
// OpenCode 1.16+ filters events to this plugin's directory before calling
// the hook, so there is nothing to match on here. 1.15.x does not — it fans
// every bus event to every plugin instance — so the marker there follows the
// worktree the instance was created for, whichever session is active.
event: async ({ event }: HookInput) => {
if (disposed) return;
switch (event.type) {
case "session.status":
await enqueue(["set", WORKING]);
break;
case "session.idle":
await enqueue(["set", WAITING]);
break;
case "session.deleted":
await enqueue(["clear"]);
break;
}
},
};
}
export default { id: "worktrunk", setup, server };