8 Commits
Author SHA1 Message Date
Worktrunk Botandworktrunk-bot 5e2106c70d fix: set OpenCode activity markers from session.execution events (#4850)
OpenCode 2.3 stopped emitting `session.status` and `session.idle`, the
two events the plugin's OpenCode 2 watcher sets markers from, so `wt
list` never shows 🤖 or 💬 there. The watcher now also handles
`session.execution.started` (🤖) and `succeeded` / `failed` /
`interrupted` (💬). Those events carry only a `sessionID`, so the plugin
looks the session up with `context.session.get` and marks only when the
session's `location.directory` is this instance's worktree and the
session has no `parentID`. Without the `parentID` check, a subagent
finishing would flip a still-working parent to 💬. The old
`session.status` / `session.idle` cases stay for earlier OpenCode 2
hosts, and the OpenCode 1 `server` path is unchanged.

The event names and shapes come from OpenCode v2.3.2's source:
`packages/schema/src/session-event.ts` defines the four execution events
with only `sessionID`, its e2e helper maps `busy`/`idle` onto
`execution.started`/`succeeded`, and `Session.Info` carries `location`
and `parentID`. I drove `setup()` under Node with a fake context and a
fake `wt` that logs its calls. Before this change the event sequence
produced only the teardown `clear`. After it, the parent session sets 🤖
then 💬, and execution events from a subagent, from a session in another
worktree, and for a deleted session set nothing. The existing OpenCode
integration tests pass. Not verified: the plugin running inside a live
OpenCode 2.3 host. The reporter tested a near-identical patch live on
2.3.2.

What this leaves from #4849: finding 3, the duplicate plugin instances
per directory racing on `git config`. That isn't addressed. Both
instances write the same marker, the losing write's error is already
swallowed, and whether a module-level refcount would even be shared
across OpenCode's two loaders isn't something I could check here.

Refs #4849 — automated triage

Co-authored-by: worktrunk-bot <254187624+worktrunk-bot@users.noreply.github.com>
2026-11-19 09:50:57 -08:00
Worktrunk Botandworktrunk-bot 3bf9166a6e fix(plugins): skip Windows Terminal's wt in the pi, omp, and OpenCode plugins (#4698)
The pi, oh-my-pi, and OpenCode plugins ran a bare `wt`. On Windows that
name usually resolves to Windows Terminal's app-execution alias in
`%LOCALAPPDATA%\Microsoft\WindowsApps`. The alias exits 0 and reports
the unknown program in a popup, so every activity-marker update opened
an error window. OpenCode's worktree `switch`/`remove` strategy also
never reached worktrunk. The Claude Code and Codex hooks didn't have
this problem because they run through `plugins/worktrunk/hooks/wt.sh`,
which already handles this case.

Each plugin now has a small `worktrunkBin()` that follows `wt.sh`'s
policy: use `WORKTRUNK_BIN` if set, otherwise use `wt` off Windows. On
Windows, it walks `PATH` in order and prefers `git-wt.exe`, then accepts
a `wt.exe` only if the first one found isn't under `WindowsApps`. When
nothing usable is found, marker updates are skipped, and OpenCode's
strategy throws an error naming `git-wt.exe` and `WORKTRUNK_BIN`. The
helper is copied into all three files because each one is installed as a
standalone file.

Verification: dev/*.ts has no test harness, so I checked locally with
Node 22's type stripping. The check fakes `process.platform = "win32"`,
builds a `PATH` with a `WindowsApps/wt.exe` ahead of a real `wt.exe`,
and stubs `pi.exec`. Before this change, both the pi and omp plugins
exec `wt` (the Terminal alias). After it, they skip; they pick
`git-wt.exe` when it's present and `wt` when the real binary comes first
on `PATH`. OpenCode's strategy surfaces the new error. The existing
plugin install/config integration tests pass.

**Not verified on Windows:** I couldn't run a real Windows host. `lstat`
is used instead of `exists` so the alias's reparse point still counts as
present, which keeps the search order the same as Windows' own lookup.
It's worth a check on a Windows machine with the Terminal alias enabled.

The issue's other suggestion is still open: warning when a `wt` on PATH
turns out not to be worktrunk. That needs a choice about where a plugin
should report it, so it's not in this PR.

Closes #4697 — automated triage

Co-authored-by: worktrunk-bot <254187624+worktrunk-bot@users.noreply.github.com>
2026-11-04 06:07:54 -08:00
Worktrunk Botandworktrunk-bot ca0563dc8d feat(plugin): route OpenCode 2 worktrees through wt switch and wt remove (#4489)
Under OpenCode 2, the plugin that `wt config plugins opencode install`
writes now registers a `worktrunk` worktree strategy. Worktrees that
OpenCode creates and removes then go through `wt switch --create` and
`wt remove`, the same way the Claude Code plugin's
`WorktreeCreate`/`WorktreeRemove` hooks already route them. This was
requested in #4488. I ran the strategy locally against a scratch repo
with this branch's `wt` and a fake OpenCode context. I haven't run it
inside a real OpenCode 2 session, which CI can't drive.

How each callback maps
([`dev/opencode-plugin.ts`](https://github.com/max-sixty/worktrunk/blob/1c906f5599d7a16df832c56c51aa82d13c82bbd3/dev/opencode-plugin.ts)):

- **create**: runs `wt switch [--create] <name> [--base <ref>] --no-cd
--format=json` in the source checkout and returns `.path`. OpenCode's
`branch` input is a [starting ref, not a branch
name](https://github.com/anomalyco/opencode/blob/dev/packages/plugin/src/worktree.ts),
so `<name>` is the basename of the directory OpenCode suggests (the name
the user typed, or a generated slug). The path comes from
`worktree-path`, since OpenCode accepts a different directory than the
one it suggested. An existing branch is reopened, as in #4487. Passing a
starting ref for an existing branch is refused rather than ignored.
- **remove**: runs `wt remove --foreground [--force] <dir>`. It does
nothing if the checkout is already gone.
- **list**: reads `git worktree list --porcelain -z` and reports the
first record as `root`. Bare and prunable entries are skipped.

Things a maintainer may want to weigh:

- **On by default.** OpenCode selects a strategy as soon as a plugin
adds one. Every OpenCode 2 user with the plugin installed switches to
worktrunk-managed worktrees, and OpenCode's `worktree.directory` setting
stops applying. This matches the Claude Code plugin. The docs page says
so.
- **No force prompt on a dirty worktree.** OpenCode only offers to force
when the error is an instance of its own `Worktree.OperationError`
([`operationError`](https://github.com/anomalyco/opencode/blob/dev/packages/core/src/worktree.ts)
uses `instanceof`). A standalone plugin file can't import that class:
the CLI's runtime shim for `@opencode/plugin` doesn't export `Worktree`.
A dirty removal fails with worktrunk's own message instead (`Cannot
remove worktree: … has uncommitted changes`), and nothing is deleted.
- **Default base.** With no starting ref, the new branch starts from
worktrunk's default (the default branch). OpenCode's `git` strategy uses
the source checkout's HEAD instead.

<details><summary>Local check</summary>

A Node harness imported the plugin, called `setup` with a stub
`ctx.worktree.transform`, and ran each callback against a fresh repo
with `target/debug/wt` on PATH:

- create → `ocrepo.brave-tiger` (the `worktree-path` default), and
`list` returned root + that worktree
- create with `branch: "brave-tiger"` → a second worktree based on it
- create for an existing branch with a starting ref → refused. Without a
ref → reopened the existing worktree
- remove of a dirty worktree → wt's error. With `force` → removed. A
repeat remove → no-op
- final `list` → root only

`test_docs_are_in_sync` and the 14 `opencode` integration tests pass.

</details>

Closes #4488

Co-authored-by: worktrunk-bot <254187624+worktrunk-bot@users.noreply.github.com>
2026-10-17 15:06:01 -07:00
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
Worktrunk Botandworktrunk-bot 8e420cb8c4 Load the OpenCode plugin under OpenCode 2 (#4018)
## Problem

`wt config plugins opencode install` writes a plugin OpenCode 2 silently
ignores, reported in #4014. OpenCode 2's loader decodes a plugin
module's default export against a schema that accepts `{ id, effect }`
or `{ id, setup }` — a bare default-exported function, which is what
this plugin has always been, fails the decode and the load is dropped
without a message
([`packages/core/src/plugin/module.ts#L60`](https://github.com/sst/opencode/blob/b2cecc6350d377c382e1ec32ee66ec63ad68f715/packages/core/src/plugin/module.ts#L60)
on the `beta` branch, which is where the OpenCode 2 prereleases come
from — `dev` is the 1.18.x line). The plugin also ran `wt` through Bun's
`$`, which the host only supplies when it is itself running under Bun.

## Solution

One file, both runtimes: the default export is now `{ id, setup, server
}`, and `wt` is spawned with `node:child_process` instead of Bun's
shell. OpenCode 2 reads `setup` and subscribes to session events;
OpenCode 1.16+ reads `server` and gets exactly the hooks it has today.
Each version ignores the other's key, so the install path, filename, and
marker behavior are all unchanged.

Two details in the `setup` arm that differ from the port in the issue's
thread — both from reading the shipped `@opencode-ai/plugin@beta` types:
`session.status` carries `status.type ∈ {idle, busy, retry}` and
`session.idle` is annotated deprecated, so the status is read rather
than the event name; and `session.status` with an `idle` status sets 💬
rather than 🤖.

**The part worth a maintainer's call**: this keeps the OpenCode 1 shape
rather than switching cleanly to v2 alone. OpenCode 2 is still
prerelease (`npm dist-tags` for `@opencode-ai/plugin`: `latest` 1.18.29,
`beta` 0.0.0-beta-19192), so a v2-only file would make every current
stable install fail with `Plugin … must default export an object with
server()`. The cost is the `server` arm plus its two local types — say
the word and I will cut it to `{ id, setup }`. Either way OpenCode below
1.14.19 loses the plugin: that is where `readV1Plugin` — the function
that admits an object-shaped default export — first appears, and older
releases accept only the bare function. 1.16 is the floor worth
documenting, though, because it is where the host began filtering events
to each plugin instance's directory
([v1.16.0](https://github.com/sst/opencode/blob/6cb74317a6efacd656483cb0489d8e7e3701c12e/packages/opencode/src/plugin/index.ts#L258-L259));
[v1.15.0](https://github.com/sst/opencode/blob/2662a4f955e563fd22cd5c4873ca350d21745275/packages/opencode/src/plugin/index.ts#L246)
fans every bus event to every instance, so on 1.14.19–1.15.x the marker
follows the worktree the instance was created for rather than the
session that is active — the same behavior today's plugin has, not a
regression.

## Verification

`cargo test --test integration test_docs_are_in_sync`, the twelve
`opencode` integration tests, and `packaged_assets` pass. Beyond that I
ran the new file through both loaders' own logic under `node
--experimental-strip-types`, with a stub `wt` on `PATH` recording its
arguments.

<details><summary>Loader checks and recorded marker calls</summary>

Decoding the real module with the exact schema OpenCode 2 uses
(`effect@4.0.0-rc.112`, the version its plugin package depends on), and
with OpenCode 1's
[`readV1Plugin`](https://github.com/sst/opencode/blob/337fd144d2ba144743368f78d9579a99cce175bd/packages/opencode/src/plugin/shared.ts#L272)
detect-mode logic:

```
OpenCode 2 module decode : ok, id=worktrunk
OpenCode 1 readV1Plugin  : ok, id=worktrunk
v2 setup returned cleanup: true
v2 setup on a 1.18 context: bails, no throw
```

The last line covers a case worth calling out: OpenCode 1.18 also
carries a `{ id, setup }` loader, but the context it passes has neither
`location` nor `event`. `setup` returns early there instead of throwing,
and `server` drives the marker.

Feeding a fake event stream, the commands the plugin actually issued:

```
v2:  set 🤖   (status busy)
     set 🤖   (status retry)
     set 💬   (status idle)
     — skipped, event location is another worktree —
     set 💬   (session.idle)
     clear    (session.deleted)
     clear    (cleanup)

v1:  set 🤖 / set 💬 / clear   (unchanged from today)
```

What I could not check from CI is the plugin running inside a real
OpenCode 2 session — @pragmaticivan, if you are still up for testing,
`wt config plugins opencode install` off this branch should behave the
same as your local port.

Install location is unchanged and confirmed on `beta`: plugins are still
discovered as `.ts`/`.js` files under `plugin/`, `plugins/` in each
config directory
([`source-directory.ts#L7`](https://github.com/sst/opencode/blob/b2cecc6350d377c382e1ec32ee66ec63ad68f715/packages/core/src/plugin/source-directory.ts#L7)).

</details>

Closes #4014

---------

Co-authored-by: worktrunk-bot <254187624+worktrunk-bot@users.noreply.github.com>
2026-09-06 09:19:38 -07:00
4i3n6and4i3n6 b00e6b612a fix(plugin): scope OpenCode marker commands to the plugin's directory (#3554)
Follow-up to #3552, as invited there.

The OpenCode host injects the process-global Bun shell as `$` — a single
instance shared by every plugin loaded in the process. The
activity-marker plugin issued its commands unscoped, so each one ran in
whatever the process-wide cwd was at spawn time; under concurrent
parallel-agent sessions that means a marker write can land in a
directory other than the one the event came from.

This pins every command with the promise-level `.cwd(directory)`, per
the review notes on the issue:

- `directory` pulled from `PluginInput` (the factory now destructures `{
$, directory }`), and `session.deleted` scopes the same way as `set`.
- Promise-level `.cwd(directory)` only — the instance-level `$.cwd(...)`
would mutate the shared default for every plugin in the host process, so
the call-site comment documents why the per-command form is
load-bearing.

Scope note, consistent with the issue discussion: this closes the "runs
`wt` in the wrong directory" mechanism on the plugin side; it does not
claim to explain the parent-directory `rename(2)` from the original
report. The host-level question (injecting a scoped shell instead of the
global one) belongs upstream with opencode — happy to raise it there as
discussed.

Co-authored-by: 4i3n6 <4i3n6@users.noreply.github.com>
2026-07-24 19:23:36 -07:00
Axel H. a5c7fa76f1 fix(opencode): fix broken unicode escaping depending on Bun version (#1935)
A small fix on the OpenCode plugin: depending on the Bun version,
unicode can be broken ([escaped while it
shouldn't](https://github.com/bikeshaving/crank/issues/342)).

This fix ensures it works whatever the Bun version used in OpenCode (I
already use this fix locally).
2026-04-06 14:27:14 -07:00
4ef64c47ad feat(opencode): add OpenCode integration (activity tracking, plugin, config) (#1807)
This PR adds OpenCode integration: activity tracking markers in `wt
list`, plugin installation via CLI, `wt config show` diagnostics, and
LLM commit generation detection.

Continues the work started in #1295 and #1533 which added OpenCode to
the docs and example config.

## What's included

- **Activity tracking plugin** (`dev/opencode-plugin.ts`): maps
`session.status`/`session.idle`/`session.deleted` to branch markers,
same pattern as Claude Code's plugin
- **`wt config plugins opencode install/uninstall`**: installs the
plugin to `~/.config/opencode/plugins/worktrunk.ts` — source embedded
via `include_str!()`, no npm needed. Sits under `wt config plugins`
alongside Claude Code's `wt config plugins claude`.
- **`wt config show` OPENCODE section**: shows plugin install status
with actionable hints (only when `opencode` is on PATH)
- **`LlmTool::OpenCode` variant**: detected via PATH for commit
generation auto-config

## Docs approach

Kept deliberately low-profile — no dedicated docs page, no README
mention. OpenCode is discoverable via `wt config show` and a mention in
tips-patterns. If it becomes popular, docs prominence can increase.

> _This was written by Claude Code on behalf of @max-sixty_

---------

Co-authored-by: Maximilian Roos <m@maxroos.com>
Co-authored-by: Claude <noreply@anthropic.com>
2026-04-05 18:44:41 -07:00