Files
Michael Ramos 82a8f236ec feat(opencode): restore the slash commands on OpenCode 2 (#1434)
* feat(opencode): restore the slash commands on OpenCode 2

OpenCode's V2 plugin API gained native command execution upstream
(anomalyco/opencode issue #2185, PR #44765): ctx.command.transform lets a
plugin add a command whose execute callback fully owns the invocation. That
shape currently ships on the beta and dev dist-tags of @opencode-ai/plugin
while next and latest still carry the older context, so the capability is
duck-typed at runtime and never imported. On a host that exposes it the V2
adapter registers /plannotator-review, /plannotator-annotate and
/plannotator-last and runs the same handleCliCommand machinery OpenCode 1
uses, passing the raw argument tail straight through to the CLI. On a host
without it nothing new is registered and behavior is byte-identical to before.

Also wires ctx.session.switchAgent (same API generation, same probe) so an
agent switch chosen in the review UI is applied instead of only warned about,
and accepts both agent.list() response shapes: the HTTP client types it as a
{ location, data } envelope while the in-process plugin domain answers with a
bare array, where reading .data threw and silently emptied the agent list.

The shared command stubs get model-mediated fallback bodies for OpenCode 2
hosts on the stale channels. They carry no shell interpolation on purpose:
OpenCode 1 evaluates a template's !`...` before the V1 plugin's
command.execute.before hook can clear the parts, so a bang template there
would launch a second Plannotator session on every OC1 invocation. A source
level test pins that.

AI-assisted (Claude) under maintainer direction.

* fix(opencode): probe the command draft and reclaim the names from the stubs

Review found the capability probe was wrong in the direction that matters.
ctx.command.transform exists on pre-#44765 hosts too: our own pinned
@opencode-ai/plugin@0.0.0-next-16775 declares CommandDraft as
{ list, get, update, remove } with no add. The probe therefore returned true on
next and latest, draft.add was undefined, and because transforms are stored and
replayed the TypeError landed in the batched reload flush and aborted it before
commit, plausibly taking every command registration on the host down with it.
Capability is now read from the draft handed to the callback, which is the only
witness, and the registration call is wrapped so no transform rejection can fail
plugin setup.

The stubs also shadowed the native definitions on new hosts. Command definitions
land in a name-keyed map where add is Map.set, transforms replay in registration
order, and OpenCode's own ConfigCommandPlugin activates in the post group after
package plugins while scanning the exact directory the installer writes the
three stubs to. A setup-time registration is therefore always overwritten on a
normal install. The plugin now re-registers the same transform once activation
settles, so its definitions are last in the replay order, and calls
ctx.command.reload() explicitly because a late registration only adds its reload
to the already-flushed boot batch. Ownership is read back from
ctx.command.list() by description, which is why the native descriptions and the
stub frontmatter are deliberately distinct. If the reclaim cannot run the stubs
keep the names and the commands still work through their fallback bodies.

Also: a failing switchAgent no longer costs the reviewer their feedback on the
command path, feedback is delivered as "queue" rather than replaying the
invocation's admission mode minutes later when a steer would land mid-turn, and
the agent-list comment no longer asserts a bare-array response that could not be
reproduced upstream (accepting both shapes is still right, since reading .data
blindly throws into a catch that degrades silently).

Tests: the real old-host draft shape registers nothing and throws nothing, the
shadowing contest is modelled against upstream's replay semantics, the OpenCode 1
parts-clearing invariant is pinned for all three commands in both plan-agent and
manual mode now that the stubs carry real instructions, and the V2 smoke asserts
the plugin did not activate as failed and that all three commands resolve. The
smoke now also installs the stubs into its sandbox config dir so the contest
actually happens there. scripts/opencode2-native-commands-smoke.sh runs the same
smoke against a dev-channel build with native commands required; CI cannot,
because it pins a next build.

AI-assisted (Claude) under maintainer direction.

* fix(opencode): keep the reclaim ticking and stop an unbuilt checkout failing setup

The reclaim ended the loop when the draft-probe flag read false, but that flag
only flips when the transform replays, which under boot batching is the flush
after every plugin has loaded. Plannotator loads before the post-group config
plugins, so the first tick legitimately reads false and the loop exited for
good: the reclaim was inert in exactly the shape production has. The tick is
skipped now instead, with a test that flips the flag between ticks.

The V1 entry called resolveBundledHtmlPath synchronously during plugin
construction, outside the .catch that was there to absorb a missing asset, so an
unbuilt checkout threw out of construction before any code path that needs the
HTML. The Test workflow runs bun test with no build step, so the new OpenCode 1
interception tests failed there. Both preloads are guarded; the lazy getters
still raise a clear error if something actually needs the file.

The smoke's failed-plugin guard read entry.state.status, but Plugin.Info carries
status and error at the top level, so a failed activation slipped through.
Reads the top level first and keeps the nested one as a fallback.

Comment corrections: State.batch clears its active flag before flushing, so a
late transform registration materializes on its own; the explicit reload() is
redundant-but-defensive rather than required. The reclaim schedule is a list of
deltas the loop awaits in turn, so the ticks land near 0.3s, 1.5s, 5.5s and
15.5s, not at the raw numbers.

AI-assisted (Claude) under maintainer direction.
2026-08-31 10:42:26 -07:00

92 lines
3.5 KiB
TypeScript

import { afterEach, describe, expect, test } from "bun:test";
import { createTestEnvironment } from "../../tests/helpers/environment";
import PlannotatorPlugin from "./index";
/**
* OpenCode 1 slash-command interception.
*
* The V1 plugin clears `output.parts` IN PLACE before anything reaches the
* model. Now that the shared markdown stubs carry real instructions ("run the
* plannotator CLI and relay stdout", for OpenCode 2 hosts on the stale
* channels), a regression here would leak those instructions to the OpenCode 1
* model and re-open the #713 class: OpenCode resolves prompt parts over
* "<body> <arguments>" and auto-attaches any file path it finds, which on a
* large file blows the context before the annotation UI even opens.
*
* Interception lives on the always-built plugin object; `shouldRegisterSubmitPlan`
* only gates `plugin.tool`, so `workflow: "manual"` must intercept too.
*/
const envKeys = ["PLANNOTATOR_BIN", "PLANNOTATOR_DATA_DIR"] as const;
const environment = createTestEnvironment(envKeys, "plannotator-oc1-intercept-");
afterEach(() => environment.restore());
const COMMANDS = ["plannotator-review", "plannotator-annotate", "plannotator-last"] as const;
function makeClient() {
return {
app: {
log: async () => ({}),
agents: async () => ({ data: [] }),
},
config: { get: async () => ({ data: {} }) },
session: {
messages: async () => ({ data: [] }),
prompt: async () => ({}),
},
};
}
async function interceptionHandler(options: Record<string, unknown>) {
const plugin = await PlannotatorPlugin(
{ client: makeClient(), directory: "/project" } as never,
// "cli" keeps the embedded server out of the test; the CLI spawn then fails
// fast against the bogus PLANNOTATOR_BIN below and is swallowed by
// handleCliCommand's own catch.
{ runtime: "cli", ...options } as never,
);
return (plugin as Record<string, any>)["command.execute.before"] as (
input: Record<string, unknown>,
output: { parts: unknown[] },
) => Promise<void>;
}
describe("OpenCode 1 command interception", () => {
for (const workflow of ["plan-agent", "manual"] as const) {
for (const command of COMMANDS) {
test(`${workflow}: /${command} empties output.parts before the model sees it`, async () => {
environment.reset();
process.env.PLANNOTATOR_BIN = "/nonexistent/plannotator-interception-test";
process.env.PLANNOTATOR_DATA_DIR = environment.makeTempDir();
const handler = await interceptionHandler({ workflow });
const parts = [{ type: "text", text: "run the plannotator CLI and relay stdout" }];
const output = { parts };
await handler(
{ command, sessionID: "session-1", arguments: "" },
output,
);
expect(parts.length).toBe(0);
// Mutated in place, never reassigned: the caller holds this exact array
// and ignores anything assigned to output.parts.
expect(output.parts).toBe(parts);
});
}
}
test("an unrelated command keeps its parts untouched", async () => {
environment.reset();
process.env.PLANNOTATOR_BIN = "/nonexistent/plannotator-interception-test";
process.env.PLANNOTATOR_DATA_DIR = environment.makeTempDir();
const handler = await interceptionHandler({ workflow: "plan-agent" });
const output = { parts: [{ type: "text", text: "someone else's command" }] };
await handler({ command: "other-command", sessionID: "session-1", arguments: "" }, output);
expect(output.parts.length).toBe(1);
});
});