CodeNomad/scripts/test-plugin-runtime-native.mjs
Pascal André f3bf6c4032
feat(plugins): protect CodeNomad-managed system plugins (#1308)
## Problem

CodeNomad's own OpenCode plugins appeared as ordinary plugins with
activation switches, so users could disable an application feature
without knowing it. Filtering by a `codenomad` name or ID would also
hide unrelated third-party plugins and lose loading failures.

## Behavior

- Verified CodeNomad-managed plugins stay outside ordinary plugin rows,
activation switches, package actions and source-removal controls.
- Disabled, failed or loading-unconfirmed managed plugins appear in a
compact warning above the list, with accessible on-demand
error/configuration details.
- **Re-enable** uses the existing activation path: append a positive
exact-ID rule, preserve the disabling rule and unrelated configuration,
and target the disabling Global/Project scope when writable, otherwise
the writable Project override.
- A configuration write does not clear the warning. A fenced native
inventory refresh must confirm active runtime; failed or unconfirmed
loading stays visible. OpenCode is never restarted automatically.

## Approach and edge cases

The server computes `managedBy: "codenomad"` from the authenticated
daemon's discovery root, a validated installer-generated entry and its
SHA-256-addressed payload location/content. The UI filters that marker
rather than recognizing names. Shared installer parsing preserves
retained outside-root storage. Build scripts publish a minimal
exported-ID descriptor inside the hashed payload so absent runtime
entries can still be correlated with exact, prefix and all-plugin
disabling rules, without importing executable code or adding an ID
catalogue.

- Windows paths and file URLs retain their native identity; WSL
translates native directories only for host IO. Reserved WSL UNC
zero-device metadata still requires independent handles, matching
nonzero inodes, regular single-link files, stable bounded reads and
SHA-256 verification. Final file links remain detectable.
- Inherited/external and virtual configuration origins remain distinct
from the writable Project recovery destination; unavailable destinations
offer no mutation.
- Managed failures before exporting an ID retain details, including
native references, without fabricated activation switches or duplicate
warnings. Unproven and third-party local failures retain ordinary path
rows.
- Third-party homonyms remain controllable. The separately packaged
session-pruning TUI companion is not installer-owned merely because its
ID resembles a desktop plugin.
- Concurrent mutation/read reconciliation preserves newer runtime
provenance and failure details; keyboard focus returns to Refresh when a
warning disappears.

## Documentation

Updated `dev-docs/PLUGIN_CONTROLS.md`,
`dev-docs/OPENCODE_COMPATIBILITY.md`, and `docs/help/*/integrations.md`
in all ten supported languages, alongside localized UI labels. The
plugin list is documented on the Integrations help page.

## Validation

Publication rerun on the pushed commits:

- `node --import tsx --test
packages/server/src/opencode/desktop-plugin-artifact.test.ts
packages/server/src/opencode/desktop-plugin-managed.test.ts
packages/server/src/opencode/plugin-controls.test.ts
packages/ui/src/stores/plugin-controls.test.ts` — **96 passed, 0 failed,
0 skipped**. Covers verified managed files, third-party homonyms,
tampering/links, disabled rules, scoped recovery, stale-response fencing
and runtime confirmation.
- `node --import tsx --test --test-concurrency=1
packages/ui/tests/browser/plugin-controls.test.ts` — **28 passed, 0
failed, 0 skipped**. Exercises the real list, warning, Re-enable, native
events, failure details, scope labels and keyboard focus.
- `npm run test:help` — **31 passed**; validates **28 pages in 10
locales**.
- `npm run typecheck --workspace @neuralnomads/codenomad` and `npm run
typecheck --workspace @codenomad/ui` — **passed**.
- `node --import tsx scripts/test-plugin-runtime-native.mjs
<absolute-isolated-cli>` with **OpenCode 2.2.5** — **passed**: native
loading reports the generated `.ts` shim, matches verified installation
provenance, and agrees with the exported-ID descriptor; isolated native
RPC/Form checks also pass.
- With `CODENOMAD_TEST_WSL_PLUGIN_CONTROLS=Ubuntu`, the real
`desktop-plugin-managed-wsl.test.ts` case **passed**, including
zero-device metadata, corruption repair and hard/symbolic-link refusal.
The combined rerun with `plugin-control-document-wsl.test.ts` exceeded
its 180-second local budget after successful document cases; that full
rerun is not claimed complete.
- `git diff --check origin/dev...HEAD` — **passed**. Clean worktree;
exactly the two delivery commits above `origin/dev`, with no rebase,
force push or push to `dev`.
2026-11-06 04:13:30 +01:00

58 lines
4 KiB
JavaScript

// Explicit isolated CLI/bundle only; no shared service, real credentials or user storage.
import assert from "node:assert/strict"
import { readFile, mkdir } from "node:fs/promises"
import path from "node:path"
import { fileURLToPath } from "node:url"
import { setTimeout as delay } from "node:timers/promises"
import { tsImport } from "tsx/esm/api"
import { withProductRuntime } from "./native-product-fixture.mjs"
const bundle = process.argv[3] ?? fileURLToPath(new URL("../packages/server/dist/plugins/session-pruning/plugin.mjs", import.meta.url))
assert(path.isAbsolute(bundle), "Pass an absolute private bundle path")
const { installPruningPresence } = await tsImport("../packages/server/src/opencode/pruning-installation.ts", import.meta.url)
const { readManagedDesktopPlugins, managedDesktopPluginForSource } = await tsImport("../packages/server/src/opencode/desktop-plugin-managed.ts", import.meta.url)
let closePresence
try {
await withProductRuntime(process.argv[2], async ({ root, configDirectory }) => {
closePresence = await installPruningPresence(await readFile(bundle), { config: configDirectory, data: path.join(root, "presence") })
return {}
}, async ({ client, root, connection }) => {
const location = { directory: root }
await client.location.get({ location })
const deadline = Date.now() + 15_000
let plugin
do {
plugin = (await client.plugin.list({ location })).data.find(item => item.id === "codenomad-session-pruning" || item.source.type === "local" && item.state.status === "failed")
if (plugin?.state.status === "failed") throw new Error(JSON.stringify(plugin))
if (plugin?.state.status === "active") break
await delay(50)
} while (Date.now() < deadline)
assert.equal(plugin?.state.status, "active", "Shipped plugin must load")
const globalDirectory = (await client.config.get({ location })).find(entry => entry.type === "directory")?.path
assert(globalDirectory, "Daemon reports its discovery directory")
const installations = await readManagedDesktopPlugins({ globalDirectory, paths: process.platform === "win32" ? path.win32 : path.posix,
hostPath: async file => file, assertCurrent: connection.assertCurrent })
assert.equal(plugin.source.type, "local")
const managed = managedDesktopPluginForSource(installations, plugin.source.path, process.platform === "win32" ? path.win32 : path.posix)
assert(managed, "Real native source matches the verified published installation")
assert(managed.ids.includes(plugin.id), "Published descriptor agrees with the exported native plugin ID")
console.log(`PASS: native managed source is ${plugin.source.path === managed.entry ? "generated .ts shim" : "content-addressed .mjs bundle"}`)
const session = await client.session.create({ location })
const form = await client.session.form.create({ sessionID: session.id, title: "Runtime contract fixture", fields: [{ key: "answer", type: "string" }] })
const cold = path.join(root, "cold")
await mkdir(cold)
const url = new URL("/api/rpc/codenomad.pending-requests/snapshot", connection.endpoint.url)
url.searchParams.set("location[directory]", root)
const response = await connection.fetch(url, { method: "POST", headers: { "content-type": "application/json",
authorization: `Basic ${Buffer.from(`opencode:${connection.endpoint.auth.password}`).toString("base64")}` },
body: JSON.stringify({ input: { directories: [root, cold] } }) })
const text = await response.text()
assert.equal(response.status, 200, text)
const snapshot = JSON.parse(text).output
assert.equal(snapshot.originDirectory, root)
assert(snapshot.data.find(item => item.directory === root).locations.some(item => item.forms.some(item => item.id === form.id)))
assert.deepEqual(snapshot.data.find(item => item.directory === cold).locations, [])
await client.session.form.cancel({ sessionID: session.id, formID: form.id })
console.log("PASS: native plugin loading, host Effect/Schema/RPC, existing-only pending snapshot and Form settlement")
})
} finally { await closePresence?.() }