CodeNomad/scripts/test-session-goal-native.mjs
Pascal André f747d47f41
Some checks are pending
Download Caches / seed (windows-2025) (push) Waiting to run
Download Caches / seed (ubuntu-24.04) (push) Waiting to run
Download Caches / seed (macos-15-intel) (push) Waiting to run
Download Caches / seed (macos-26) (push) Waiting to run
Publish help / build (push) Waiting to run
Publish help / deploy (push) Blocked by required conditions
fix(opencode): prepare cold Location RPCs before one-shot dispatch (#1448)
## Problem

OpenCode 2.2.7 intentionally removes `Plugin.awaitActivation` from
`rpc.call`. On unchanged CodeNomad, native cold history/pruning returns
`rpc.unavailable`, `/goal` incorrectly reports unsupported, and a
headless integration host can fail its first advertisement. The same
native checks pass on 2.2.6.

## Adaptation

- Adopt the existing bounded, connection-owned pruning readiness
foundation and its eight fixed broker families. Preparation targets the
already-authorized exact native Location and requires a fresh
lease/registration-scope acknowledgement, rather than treating a
backend-wide startup marker as universal readiness.
- Preserve session/workspace/connection, deletion/ABA, cancellation and
extension-grant fences around waits and the single functional dispatch.
No pruning mutation is probed, replayed or retried; generic RPC proxy
access stays closed.
- Share the native catalogue activation wait with `/goal`. Only method
absence after activation proves unsupported; transient registration loss
remains unavailable.
- Preserve current Memory provisioning and ownership options while
adopting the foundation. Abort the startup marker observer on close so
cleanup does not wait on an unreferenced polling timer.
- Correct the reference host discovery client, vendored byte-for-byte
from [opencode-integrations
#17](https://github.com/NeuralNomadsAI/opencode-integrations/pull/17):
payload-free status preparation may repeat while registration is
unavailable; advertise/withdraw are sent once, with no directory
fallback after dispatch. The external PR publishes source only;
installed hosts need the corresponding host update.
- Keep minimum, recommendation and authoring dependency pins unchanged.
Add cold fixed-broker native coverage to minimum/latest and
Windows/Linux/macOS native lanes.

## Validation

- **199** affected broker/lifecycle/readiness/goal tests pass; the final
cancellation cleanup additionally passes **40** focused tests.
- **30** real-browser Images/panel-extension journeys pass.
- Official isolated **2.2.3, 2.2.6 and 2.2.7**, driven by pinned **Node
24.22.2**: full pruning/history/Images/replay fixture, production goal
route, cold fixed preview/prune/history/Images brokers and headless
integration discovery/advertise/attach/withdraw all pass. The cold
broker check asserts one prune dispatch and retained conclusion bytes,
plus a new backend lease.
- **2.2.7 split storage** passes full pruning, native proxy/UI
contracts, assets/gallery, mixed split+inline content after flag
disable/restart, receipts, active-claim refusal and retained model
payload.
- Server/UI typechecks, complete server/UI/native-plugin build, **27**
package/vendor parity tests, **31** help tests, native driver test, YAML
and whitespace checks pass.
- External Python reference tests **9/9** and kit test typechecking
pass; Blender's vendored copy equals the reference.

Only private synthetic daemons, local providers and owned fixture state
were used. No shared service restart, real
credentials/database/configuration change or stable publication. Earlier
fixture attempts exposed an import-ID conflict, Windows path
normalization in the fixture ownership stub, and teardown ordering;
those harness defects were corrected without relaxing assertions. One
final rerun was needed after a simultaneous build cleaned its dist
input; the post-build rerun passes.

The native tests reuse source from the independently prepared readiness
foundation and broker work, adapted onto current dev without taking the
unrelated multi-backend branch. Public labels, controls and documented
steps stay unchanged; the fix restores their documented behavior. Large
existing touched files: `packages/server/src/index.ts` (~758 lines),
`packages/server/src/server/http-server.ts` (~2574),
`packages/server/src/workspaces/manager.ts` (~1230), and
`packages/server/src/server/routes/pending-requests.test.ts` (~1025).
Integrated CI and platform builds remain the final gate.
2026-11-10 16:25:51 +01:00

88 lines
5.7 KiB
JavaScript

// The Status tab's goal line against OpenCode's `/goal` plugin: CodeNomad's goal route
// reads the native `opencode.goal` RPC, the native commands change it, and its `changed`
// events reach a workspace through CodeNomad's event relay.
// Usage: node --import tsx scripts/test-session-goal-native.mjs <absolute-cli>
import assert from "node:assert/strict"
import { setTimeout as delay } from "node:timers/promises"
import Fastify from "fastify"
import { withProductRuntime } from "./native-product-fixture.mjs"
import { EventBus } from "../packages/server/src/events/bus.ts"
import { InstanceEventBridge } from "../packages/server/src/workspaces/instance-events.ts"
import { registerSessionGoalRoute } from "../packages/server/src/server/routes/session-goal.ts"
import { GOAL_CHANGED_EVENT, goalChangedSchema } from "../packages/server/src/opencode/goal-contract.ts"
import { getOpencodeErrorMessage } from "../packages/ui/src/lib/opencode-api.ts"
await withProductRuntime(process.argv[2], async () => ({}), async ({ client, root, connection }) => {
const owns = async (id, location) => id === "fixture" && location?.directory === root
const records = [{ id: "fixture", path: root }]
const location = { directory: root }
const manager = {
get: id => records.find(record => record.id === id), getServiceLocation: id => id === "fixture" ? location : undefined,
getSharedServiceConnection: async () => connection,
list: () => records, ownsDirectory: async (id, directory) => owns(id, { directory }), ownsLocation: owns,
getSharedServiceClient: async () => client, subscribeToSharedService: signal => client.event.subscribe({ signal }),
invalidateWorktrees() {},
}
const bus = new EventBus(), routed = []
let connected = false
bus.on("instance.eventStatus", event => { if (event.status === "connected") connected = true })
bus.on("instance.event", event => { if (event.event.type === GOAL_CHANGED_EVENT) routed.push(event) })
const bridge = new InstanceEventBridge({ workspaceManager: manager, eventBus: bus, logger: { debug() {}, info() {}, warn() {}, error() {} } })
const app = Fastify()
registerSessionGoalRoute(app, { workspaceManager: manager })
const until = async (predicate, message, timeout = 60_000) => {
const deadline = Date.now() + timeout
while (!await predicate()) {
assert.ok(Date.now() < deadline, message)
await delay(50)
}
}
try {
bus.publish({ type: "workspace.started", workspace: records[0] })
await until(() => connected, "the relay connects")
const session = await client.session.create({ location: { directory: root } })
const read = async (sessionID = session.id, workspace = "fixture") => {
const response = await app.inject({ method: "GET", url: `/api/workspaces/${workspace}/sessions/${sessionID}/goal` })
return { status: response.statusCode, body: response.json() }
}
const command = text => client.session.command({ sessionID: session.id, name: "goal", text, delivery: "steer" })
const changes = () => routed.filter(event => event.event.data?.sessionID === session.id)
assert.deepEqual(await read(), { status: 200, body: { status: "goal", goal: null } }, "a new session has no goal")
assert.equal((await read(session.id, "elsewhere")).status, 403, "another workspace cannot read it")
const refused = await command("pause").then(() => undefined, error => error)
assert.ok(refused, "pausing without a goal fails")
assert.match(getOpencodeErrorMessage(refused, ""), /No active goal to pause/, "the failure carries the plugin's message")
// The kickoff runs a turn; the fixture provider's plain reply is no verdict, so the
// reviewer pauses the goal on its own.
await command("Reach the fixture objective")
await until(() => changes().some(event => event.event.data.goal?.status === "active"), "setting a goal publishes it")
const set = changes()[0]
assert.equal(set.instanceId, "fixture", "the change reaches the Session's workspace")
assert.equal(set.event.location?.directory, root, "the change carries the Session's Location")
assert.ok(goalChangedSchema.safeParse(set.event.data).success, "the published value matches the consumed contract")
assert.equal(set.event.data.goal.objective, "Reach the fixture objective")
await until(async () => (await read()).body.goal?.status === "paused", "the reviewer settles the goal")
const paused = (await read()).body.goal
assert.equal(typeof paused.reason, "string")
assert.equal(paused.maxRounds > 0 && paused.rounds >= 0, true)
// The read can answer before the relay delivers the same write's event.
await until(() => changes().some(event => event.event.data.goal?.status === "paused"), "the pause is relayed too", 15_000)
const pausedChange = changes().find(event => event.event.data.goal?.status === "paused")
assert.equal(pausedChange.event.data.goal.reason, paused.reason, "the relayed pause carries the read's reason")
const before = changes().length
await command("resume")
await until(() => changes().slice(before).some(event => event.event.data.goal?.status === "active"), "resuming publishes the active goal")
await command("clear")
await until(() => changes().at(-1)?.event.data.goal === null, "clearing publishes no goal")
await until(async () => (await read()).body.goal === null, "the route reads the cleared goal")
const cleared = await command("clear").then(() => undefined, error => error)
assert.match(getOpencodeErrorMessage(cleared, ""), /No goal is set/)
console.log(`PASS native session goal: route read, refused pause, ${changes().length} relayed changes (set, reviewer pause: "${paused.reason}", resume, clear)`)
} finally {
bridge.shutdown()
await app.close()
}
})