Skip to content

feat(plugin): plugin system v1a foundation — shared contract, async API, capability gate - #5801

Closed
gsxdsm wants to merge 44 commits into
stablyai:mainfrom
gsxdsm:gsxdsm/plugin-system-v1a
Closed

gsxdsm wants to merge 44 commits into
stablyai:mainfrom
gsxdsm:gsxdsm/plugin-system-v1a

Conversation

@gsxdsm

@gsxdsm gsxdsm commented Jun 19, 2026 •

Copy link
Copy Markdown
Contributor

Draft. Plugin system for Orca (VS Code-style): trusted Node backend per plugin + sandboxed webview UI, right-sidebar panel + Settings management, npm/git/tarball/local install. Plan: #5738.

Status

Desktop: complete end-to-end and build-green (lint incl. localization, node + web typecheck, ~141 tests). Mobile/relay (v1c) + runtime verification remain.

Flow: Settings → Plugins → install (npm name / git / tarball / local path) → activate → the plugin spawns a trusted Node child-process backend, gets a right-sidebar tab, and the tab renders its sandboxed orca-plugin:// webview.

Landed (build-green)

  • Host engine — manifest+validation+id-safety, capability gate + consent, settings store + JSON-schema validator, supervision (crash/backoff), output ring buffer, trusted child-process runtime (real forked-child crash-isolation integration test), capability-gated host handler, orca-plugin:// asset protocol, runtime orchestrator. Unit/integration-tested.
  • Main wiring — composition root, IPC, window.api.plugins preload, boot (scheme pre-ready + system + protocol + handlers + build entry + asar-unpack).
  • Renderer — plugin: routing seam (+ both validators), activity-bar tab for active plugins, PluginPanel webview, webview attach-gate hardening, Settings → Plugins pane (registered in nav).
  • Installer — source parsing + integrity/lockfile + orchestration + real adapters (node:https + system git/tar, no new deps), wired to the Settings UI.
  • SDK + example plugin (examples/hello-sidebar-plugin) + authoring/security docs.
  • 8-persona code review run; all findings fixed (incl. a localization regression caught mid-build).

NEEDS-RUNTIME-VERIFY

All renderer/Electron runtime behavior (webview attach, scheme serving, fork, the no-preload guest bridge) compiles + lints + typechecks but is proven only by launching the app. To verify: launch orca-dev (full quit+reopen), Settings → Plugins, install examples/hello-sidebar-plugin, activate, confirm the tab + panel.

v1c relay + mobile integration (landed, build-green)

  • Relay — registerRelayPluginHandlers now wired into the live RelayDispatcher (src/relay/relay.ts); plugins resolve under $HOME/.orca-relay/plugins; workspace snapshot defaults to a bounded-empty value (no live root on the relay). Electron-free; relay bundle builds for all 6 targets. plugin.* error branches covered by tests.
  • Mobile — installed plugins surface as a session Plugins pane (activity-bar button + dock + narrow-layout route); list → open → MobilePluginPanel. Pure list-parsing + panel-routing logic unit-tested. JSX/navigation wiring is NEEDS-RUNTIME-VERIFY (Expo build can't run in CI env — expo deps absent).

Remaining

  • Relay-host trusted backend child + device round-trip for commands/settings bridge methods (relay denies them cleanly today) — the remote-provisioning tier.
  • Transitive npm dep resolution for plugins (v1 targets self-contained bundles).
  • Runtime verification of the desktop flow + on-device mobile pass (Expo).

The plan doc lives under docs/ (gitignored) — see PR #5738.


Relay-host backend runtime (landed, build-green)

The trusted per-plugin backend child now runs on the relay host, reusing the electron-free PluginManager + PluginRuntime + PluginHost stack (plain-node fork, no ELECTRON_RUN_AS_NODE). plugin.bridge was replaced by the real async message-passing model: plugin.activate/deactivate/postUi drive the child, and child responses are pushed back to only the originating client as plugin.uiMessage notifications (reqId-correlated by the in-webview ui-bridge-client). settings.* and workspace.getSnapshot are now served by the real backend; commands.invokeHost stays denied (device round-trip deferred). pluginId is validated (isSafePluginId + installed-manifest match) at every entry. Relay bundle builds electron-free for all targets.

Residual Review Findings

The backend-tier review fixed the P1 cross-client broadcast leak (per-client routing), the orphaned-children-on-exit bug (synchronous terminate()), and the mobile activate-error/deactivate-on-unmount gaps.

A follow-up residual-hardening pass (fix(plugin): harden deferred relay-plugin review residuals + fix(review): apply autofix feedback (residual hardening)) then resolved three of the previously-deferred items:

  • ✅ startSocketServer cleanup — exitWithCleanup now runs on the socket-server failure path, uncaughtException, shutdown, and the module-level main().catch, so plugin children aren't orphaned on any post-registration exit.
  • ✅ bridge reqId hang — the in-webview ui-bridge-client gained a correlated request() with a bounded (30s default) timeout that rejects + cleans up instead of hanging.
  • ✅ multi-client deactivate — subscribers are refcounted; the shared backend child stops only when its last subscriber leaves (via plugin.deactivate or client detach).

The reviewers found no production bugs in the hardening pass (correctness traced clean; the rest were test-strength + clarity, applied as autofixes). Remaining intentionally-deferred items:

  • P2 · maintainability · mobile/src/transport/rpc-client.ts — pre-existing >1k-line monolith; a larger decomposition (terminal-stream / browser-screencast blocks) is the real fix.
  • P3 · perf · src/relay/plugin-handler.ts — discoverPlugins re-scans the plugins dir per request; cache with explicit invalidation (deferred to avoid a staleness regression).
  • P3 · correctness · src/relay/plugin-handler.ts — a postUi racing a concurrent activate on a cold child can drop the first message before the child registers its UI handler (narrow; the awaited path is safe).
  • P3 · clarity · src/relay/plugin-handler.ts — releasePlugin's undefined-clientId full-stop branch has no production caller (kept as a type-required defensive default for context.clientId); could tighten the signature if a force-stop entry point is never needed.
  • Info · ui-bridge-client — a timed-out request() doesn't tell the relay to abort the in-flight postUi round-trip; the late response is harmlessly ignored. No relay-side resource accumulates.

Remote provisioning (landed, build-green)

A provisioning tier (feat(plugin): relay-host plugin provisioning + fix(review): apply autofix feedback (provisioning)) closes the gating prerequisite — an installed plugin's files now reach the relay host:

  • ✅ bundle codec — desktop packages a plugin dir into a file-list payload with sha256 integrity, a byte cap + file-count cap, and per-file path-safety (control chars rejected).
  • ✅ plugin.provision — the relay verifies integrity + isSafePluginId + manifest-id match, stages to a temp dir, and swaps into relayPluginsDir()/<id> via a backup-restore that never destroys the prior install on a failed rename.
  • ✅ host-entry shipping — the relay build emits plugin-host-entry.js next to relay.js; relayPluginHostEntryPath() resolves bundle-relative, so only plugin files transfer.
  • ✅ desktop package + send — readPluginBundleFromDisk (symlink/traversal-guarded) + provisionToRelay; a package↔unpack round-trip test proves the contract without a live relay.

A 6-reviewer security pass (correctness/security/adversarial/reliability/testing/maintainability) found no surviving exploitable write-outside-dir or integrity bypass; the two HIGH findings it surfaced (destructive replace, staging-throw) were fixed in the autofix commit. Remaining provisioning residuals:

  • P3 · reliability · src/relay/plugin-provision.ts — a brand-new install across a cross-volume pluginsDir/staging boundary (EXDEV) fails safely (prior preserved) but without a copy-fallback; only relevant under non-default mount config.
  • P3 · perf · src/relay/plugin-provision.ts — provisioning is synchronous fs (bounded by the 4 MB cap); a worker/stream is deferred.
  • P3 · validation · src/shared/plugin/manifest.ts — isSafePluginId accepts trailing-dot / mixed-case ids that could collide on case-insensitive filesystems; pre-existing id-rule hardening, tracked separately.

Desktop→relay activate path (landed, build-green)

An activate-path tier (feat(plugin): desktop→relay activate path + fix(review): apply autofix feedback (activate path)) adds the pure, unit-tested coordinator that sequences provision-then-remote-activate vs local activate:

  • ✅ coordinator — activatePluginForWorkspace({pluginId, remote}, deps): shouldProvisionToRelay(remote) false → local runtime.activate (behavior unchanged); true → readPluginBundleFromDisk → provisionToRelay → on success plugin.activate over the injected relay request fn. Every throw/reject becomes a typed {ok:false,error}; a provision failure aborts before activate.
  • ✅ system seam — PluginSystem.activateForWorkspace(pluginId, remote?); the plugins:activate IPC routes through it (local default). resolveRelayRequest defaults to a rejects-on-call fn so the remote path is explicit, never a silent no-op.
  • ✅ autofix review — a 6-reviewer pass (correctness/adversarial/testing/reliability/maintainability/project-standards) found no production bug on the local path. Fixed in the autofix commit: a pluginId traversal guard (isSafePluginId runs before any disk read or relay call, so the remote bundle-packaging sink can't harvest bytes outside the plugin dir), result-type consolidation onto ActivateResult (no drift), lazy relay-request resolution (a future SSH-opening resolver never runs on a local activation), and the no-cleanup-on-partial-commit contract is now documented in-code.

Remaining activate-path residuals (intentionally deferred):

  • P1 · reliability · RelayRequest contract — no per-request timeout; a stuck relay makes provision/activate await indefinitely. Needs a deadline at the transport-contract level (or a Promise.race wrapper yielding provision_timeout/activate_timeout). Deferred with the live-transport wiring.
  • P2 · reliability/adversarial · plugin-activation-coordinator.ts — provision-succeeds-but-activate-fails leaves the relay provisioned-but-inactive with no compensating plugin.deactivate; safe for v1a (re-provision is idempotent) and documented in-code. A deprovision path + a distinct activate_failed_provisioned code is the real fix.
  • P3 · adversarial · plugin-activation-coordinator.ts — concurrent activateForWorkspace for the same id can race the relay's non-atomic bundle swap; needs a per-id in-flight coalescing map and/or relay-side serialization (requires runtime verification).
  • P3 · reliability · transfer — a ~5.3 MB base64 bundle ships in one synchronous frame; chunked transfer is v1c.
  • P2 · maintainability — RemoteDescriptor is a single optional boolean today; it will need richer relay-addressing fields when the production resolver lands, and normalizeRelayResponse could be extracted to dedupe the relay-result guard.

Activation failure-mode hardening (landed, build-green)

A hardening tier (fix(plugin): harden activation coordinator remote-path failure modes + fix(review): apply autofix feedback (coordinator hardening)) closes the deferred residuals from the activate-path review:

  • ✅ per-request timeout — each remote relay call (provision + activate) races an injected delay (default 20s, unref'd); expiry yields a typed provision_timeout / activate_timeout instead of an indefinite hang.
  • ✅ compensating deactivate — when provision succeeds but activate fails by any means (reject / ok:false / no_response / timeout), a best-effort, deadline-bounded plugin.deactivate reclaims a forked-but-unacknowledged backend; its outcome is swallowed so it never masks or outlasts the original error.
  • ✅ concurrent-activation coalescing — a pure coalesceByKey + a per-tier:pluginId in-flight Map on PluginSystem so concurrent same-id activations share one activation (and a local vs remote activation of the same plugin don't coalesce into each other).

A 6-reviewer pass (correctness/adversarial/testing/reliability/maintainability/project-standards) found no shipped bug; the autofix commit then fixed the one real issue all reviewers converged on — the compensating deactivate was originally un-timed and could re-introduce the very hang the timeout removed — by bounding it with the same raceWithTimeout, plus a type-guarded activate response and a tier-keyed coalesce map. Remaining hardening residuals (intentionally deferred):

  • P2 · reliability/adversarial · local path — runtime.activate (in-process) is not deadline-bounded, so a hung plugin-host fork can wedge the local coalesce entry. The remote path is now bounded by the timeout; a local-path timeout is a behavior change deferred until the fork-hang risk is verified.
  • P2 · adversarial · plugin-activation-coordinator.ts — a provisionToRelay that resolves after its timeout may have committed a bundle on the relay that is never activated or reclaimed (orphan window); best addressed by relay-side GC of unacknowledged provisions.
  • P3 · reliability — accepted — the losing raceWithTimeout timer is unref'd (no process-lifetime leak) but not cancelled, leaving a ≤20s handle tail per call; a cancel-token on the injected delay would remove it.
  • Note (won't-fix) · the lazy per-call resolveRelayRequest wrapper is intentional — it defers session resolution to the remote path so a future SSH-opening resolver never runs on a local activation; "resolve once" was declined for that reason.

Relay discovery cache (landed, build-green)

A perf tier (perf(relay): cache plugin discovery with provision-scoped invalidation + fix(review): apply autofix feedback (discovery cache)) resolves the deferred discoverPlugins-per-request residual:

  • ✅ closure-held memoization — registerRelayPluginHandlers caches the discovery scan; back-to-back plugin.list/getEntry/activate/postUi requests scan once instead of re-reading + re-validating every manifest per call.
  • ✅ provision-scoped invalidation — the cache is dropped only on a successful plugin.provision (the sole relay-side mutation of the installed set), so a freshly-provisioned plugin is immediately discoverable (never a stale unknown_plugin); a failed provision keeps the cache. provisionPlugin is synchronous, so invalidation runs the same turn as the disk swap — no interleave.
  • ✅ getEntry boundary hardening (review autofix) — plugin.getEntry now runs the isSafePluginId gate first (matching activate/postUi) and returns entry_read_failed on an existsSync→readFileSync I/O race instead of leaking a raw fs error.

A 6-reviewer pass (correctness/adversarial/testing/reliability/maintainability/project-standards) confirmed the cache-coherency core is sound (synchronous provision + same-turn invalidate; no interleave; isSafePluginId not bypassable via the cache; provision is the only pluginsDir mutation path). Remaining hardening residuals (intentionally deferred — independent of the cache):

  • P2 · adversarial · src/relay/plugin-handler.ts — re-provisioning an already-running plugin invalidates the cache but leaves the old backend child forked from the old dir (new UI ↔ old backend until a crash-restart). Fix: have plugin.provision also await runtime.deactivate(pluginId) so the next activate rebuilds — a behavior change needing runtime verification.
  • P2 · adversarial · src/relay/plugin-provision.ts — the commitStaged .bak-* backup dir is written inside pluginsDir; an interrupted cleanup leaves a backup that discovery re-scans as a second valid plugin with the same manifest.id. Fix: put the backup outside pluginsDir, or de-dup discovery by manifest.id. (Pre-existing provisioning code.)
  • P3 · adversarial · provisioning — a custom stagingDir resolving inside pluginsDir would surface partial bundles as discovered plugins; the default sibling path is safe but the invariant is unenforced.
  • P3 · project-standards · src/relay/plugin-handler.ts — the pre-existing 14-line file header + a couple of handler comments narrate mechanism beyond the AGENTS.md "why, briefly" limit; a trim is deferred to avoid unrelated churn in a perf PR.

Still deferred (the hardest tier): the live SSH transfer + real remote fork, the production host-context threading + relay-request resolver from SshRelaySession into plugins:activate (the coordinator + seam now exist; the live wiring does not), commands.invokeHost device round-trip, and full runtime verification (desktop launch + on-device mobile/Expo).

🤖 Generated with Claude Code

ELI5

Foundation for a VS Code-style plugin system: install plugins, run a trusted backend, sandbox UI, and manage them in Settings. Desktop end-to-end base; mobile pieces later.

…e (v1a foundation)

First implementation increment of the plugin system (plan PR stablyai#5738), scoped to
the pure, electron-free shared core so it lands with full unit coverage and no
half-wired cross-process plumbing:

- manifest + validation: npm-package manifest shape, closed capability union,
  single-file UI entry validation (traversal/absolute/non-.html rejected),
  Lucide icon-name format check, pre-stable 0.x hostApiVersion gating.
- api-contract: async (Promise-returning) context surface, bounded
  WorkspaceSnapshot, host-command allowlist, lifecycle events, bridge envelope,
  method->capability map.
- capability-gate: deny-by-default method gate, open-external-url scheme
  validation, snapshot field projection — pure + electron-free so main and the
  relay share one gate (conformance-tested in a later unit).
- capability-consent: per-capability consent copy + required "not a limit"
  disclaimer (capabilities are declared intent, not a runtime jail).

32 tests, lint + typecheck clean. Child-process runtime, IPC, renderer,
installer, and relay are deferred to follow-up increments per the plan's v1a.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@ghost

ghost commented Jun 19, 2026 •

Copy link
Copy Markdown

gsxdsm and others added 12 commits June 19, 2026 03:14
…ate (U2 core)

Second v1a increment (plan PR stablyai#5738; builds on the shared contract). Host-side
authority for the plugin lifecycle, electron-free and fully injectable
(pluginsDir + stateFilePath) so it unit-tests against temp dirs:

- plugin-store: persisted install/activation state; idempotent setActive;
  reinstall preserves the active flag; corrupt-state resets to empty.
- plugin-discovery: scan a plugins dir, read plugin.json or package.json#orca,
  validate via the shared contract; separates valid vs invalid with errors.
- plugin-install: local-folder install that validates BEFORE copying (nothing
  written for an invalid bundle); folder copy runs no lifecycle scripts.
- plugin-manager: composes the above — list/get/discover/installLocal/activate/
  deactivate/remove, idempotent, deactivate-before-remove, state persisted.

21 new tests (53 total in the plugin tree), lint + typecheck clean. The
Electron-coupled orca-plugin:// asset protocol + webview-partition lifecycle and
the trusted child-process runtime are deferred to later increments per the plan,
so nothing here is half-wired.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…r (U13 core)

Third v1a increment (plan PR stablyai#5738). Plugin-owned settings persistence,
electron-free and injectable so it unit-tests against temp dirs:

- settings-schema (shared): minimal JSON-Schema-subset validator (type,
  properties, required, items, enum, additionalProperties) so main and the
  relay validate writes identically without a heavy dependency.
- plugin-settings-store: each plugin's settings live in their OWN file
  (<pluginsDir>/<id>/settings.json) — never a shared blob — with id path-safety
  so one plugin's path can't resolve into another's. Writes validate against the
  manifest settingsSchema when present; invalid writes leave the file untouched.

14 new tests (67 total in the plugin tree), lint + typecheck clean. The
renderer settings-host webview and the context.settings IPC wiring are deferred
to later increments per the plan.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…U10 core)

Fourth v1a increment (plan PR stablyai#5738). The pure, unit-testable half of the
trusted child-process runtime (the real child_process fork + crash-isolation
are wired and integration-tested separately, per the plan):

- plugin-output-buffer: bounded ring buffer for backend stdout/stderr (drops
  oldest past capacity) so the management UI's View Output stays memory-safe.
- plugin-supervision: deterministic restart policy — clean exit -> inactive;
  crash -> restart with backoff until maxRestarts, then Errored; fresh
  activation resets the crash counter; per-plugin isolated state.

12 new tests (79 total in the plugin tree), lint + typecheck clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ness hardening)

8-persona review of the v1a foundation. Fixes applied:

P0 (security+correctness+adversarial agree): untrusted manifest id reached
rmSync/cpSync via join(pluginsDir,id) with only a non-empty-string check.
Added isSafePluginId at the shared validation trust boundary (rejects path
traversal, separators, absolute paths, and prototype keys __proto__/constructor/
prototype); deduped the settings-store guard to import it.

P1: prototype pollution via id as map key -> null-prototype plugins map in the
store (defense-in-depth). Empty backoffMs -> Math.min(n,-1) undefined delay ->
constructor guard + clamp + untracked-exit -> inactive (no phantom restart).

P2: output buffer bounded by line count not bytes (multi-MB line = ~10GB) ->
maxLineLength cap + chunk-boundary reassembly (pending tail) + flush(); install
now rolls back a partial copy on cpSync failure (+ manager guards state-write
failure); store/settings writes are atomic (temp+rename) with no
mutate-before-persist divergence and per-entry load validation; removed dead
exports (EMPTY_STATE, DEFAULT_CONFIG) and unused re-exports; replaced the
`as unknown as PluginManifest` cast with explicit field construction.

P3: strip trailing CR (CRLF); guard statSync in discovery (dangling symlink/
EACCES no longer aborts the scan); additionalProperties:false now rejects keys
even without a properties map; validateHostCommand is exhaustive (switch +
never); maxRestarts:0 documented; tightened the consent-copy assertion.

98 tests (was 79), lint + typecheck clean. Residual (not applied): validManifest
fixture triplication and the dual onDidChange/events API are noted for the PR.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…otocol (U10 spawn)

Runtime-integration tier (one-PR full build). The forked Node child that runs a
plugin's trusted backend:

- plugin-host-protocol: typed IPC messages shared by parent and child.
- plugin-host-process (PluginHost): forks the child (mirrors sidecar-client.ts:
  in prod fork process.execPath with ELECTRON_RUN_AS_NODE + app.asar.unpacked
  entry, injected via entryPath/env so it stays Electron-free), captures
  stdout/stderr into the output buffer, relays backend->host bridge requests to
  onHostRequest, delivers host->backend messages, and stops gracefully
  (deactivate then SIGKILL after grace). Crash/restart policy stays in
  PluginSupervisor; this reports exits.
- plugin-host-entry (NEEDS-RUNTIME-VERIFY): child bootstrap — requires the
  plugin main, builds the async `context` (host-backed calls round-trip over
  IPC), drives activate/deactivate. Runs only in the built out/ under
  ELECTRON_RUN_AS_NODE; its host side is integration-tested.

PluginHost is verified by a real forked-child integration test (a CJS fixture
speaking the protocol): ready handshake, backend->host request round-trip,
stdout capture, and crash isolation (a crashing child does not affect another
running host). 100 tests total, lint + typecheck clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Wires the shared gate + WorkspaceSnapshot projection + host-command validation
+ per-plugin settings store into the onHostRequest callback PluginHost passes
backend->host bridge calls to. Deny-by-default; snapshot is projected so a
leaky service impl can't expose path/credential fields; host commands are
validated before invocation; thrown errors map to a new 'internal' bridge error
code. Injected services so the same handler serves Electron main and (mirrored)
the relay. 5 tests with fakes + a real settings store; 105 plugin tests total,
lint + typecheck clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…(U2 electron)

Serves a plugin's single-file UI over orca-plugin://<id>/<path>, scoped to the
install dir. The security-critical parts are pure + unit-tested: URL parsing
(preserves id case), and path resolution that rejects traversal, unsafe ids, and
inactive plugins. The Electron scheme registration (registerSchemesAsPrivileged
pre-app-ready) and protocol.handle wiring are thin wrappers marked
NEEDS-RUNTIME-VERIFY (require the running app). 7 tests; 112 plugin tests total,
lint + typecheck clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…t together)

The layer that actually runs plugins on the host: on activate it loads +
validates the on-disk manifest, spawns a PluginHost wired to the
capability-gated host handler and a per-plugin settings store, captures output,
and marks the plugin active; on crash it applies the supervisor's bounded
backoff restart (skipping restart if the plugin was deactivated meanwhile); on
deactivate it stops the host and clears active state. PluginHost factory and the
restart timer are injectable, so the orchestration is unit-tested with a fake
host (activate/spawn, crash->scheduled restart, deactivate->stop, no-restart-
after-deactivate) against a real PluginManager. 5 tests; 122 plugin tests total,
lint + typecheck clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…docs (U8)

- ui-bridge-client (shared): substrate-detecting UI<->backend messaging client
  so one plugin UI bundle works on both desktop (Electron webview) and mobile
  (react-native-webview). Detection + the mobile JSON path are unit-tested; the
  exact desktop post target is NEEDS-RUNTIME-VERIFY (confirmed when the renderer
  panel lands).
- examples/hello-sidebar-plugin: a real reference plugin — trusted Node backend
  (reads workspace + host info, opens links via the allowlisted host command),
  single-file sidebar + settings UIs, manifest with settingsSchema, and a
  README covering authoring + the trust/security model (docs/** is gitignored,
  so the guide ships with the example).
- example-plugin test validates the shipped manifest against the live validator
  so the example can't drift from the contract.

123 plugin tests total, lint + typecheck clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
NEEDS-RUNTIME-VERIFY (Electron-only glue; node-typechecks + lints clean, runs
only in the app):

- plugin-system: the main composition root. Builds PluginManager + PluginRuntime
  against Electron userData paths, implements the allowlisted host commands
  (open-external-url via shell.openExternal, copy-to-clipboard via clipboard),
  resolves the plugin-host-entry from app.asar.unpacked (mirrors sidecar-client),
  and registers the orca-plugin:// asset protocol. Singleton accessor.
- ipc/plugins: thin ipcMain.handle surface (list/install-local/activate/
  deactivate/remove/get-output/ui-message) delegating to the unit-tested
  manager + runtime. UI bridge is sender-bound (no caller-supplied pluginId).

Header comments enumerate the remaining explicit wiring (register the scheme
pre-ready, call registerPluginHandlers from register-core-handlers, add the
plugin-host-entry build target, expose window.api.plugins in preload, build the
renderer panel + management UI). 123 plugin tests still green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Adds the `plugin:${string}` variant to RightSidebarTab and teaches BOTH runtime
validators to accept it — the route normalizer (right-sidebar-route.ts) and the
per-worktree prune (worktrees.ts pruneRightSidebarTabByWorktree) — so a
plugin:<id> tab survives persistence + route normalization instead of being
silently dropped (the seam-drift risk KTD4 calls out). Node + web typecheck
clean (no exhaustiveness breaks); route test covers the plugin: case.

Remaining renderer wiring (NEEDS-RUNTIME-VERIFY): augment activityItems from the
plugin registry, render a sandboxed <webview> PluginPanel in
right-sidebar-panel-content, and add the plugins store slice.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…enderer side)

NEEDS-RUNTIME-VERIFY. Adds a `plugins` namespace to PreloadApi + the preload
`api` object (list / installLocal / activate / deactivate / remove / getOutput /
sendUiMessage), delegating to the plugins IPC handlers via ipcRenderer.invoke.
Structural types keep preload decoupled from main; the `window.api = api`
assignment keeps the runtime object and PreloadApi in lockstep. Node + web
typecheck clean; 123 plugin tests still green.

Remaining: call registerPluginHandlers from register-core-handlers + register
the scheme/protocol in app bootstrap + add the plugin-host-entry build target;
then the renderer panel + management UI consume window.api.plugins.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 19, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds an Orca plugin system across shared contracts, Electron main, relay, renderer, and mobile. It introduces manifest and bridge validation, plugin installation and integrity handling, child-process plugin runtime management, relay provisioning and activation, plugin asset loading, and IPC surfaces. Desktop renderer settings and right-sidebar views now list, activate, remove, and render plugins. Mobile gains plugin list and detail panels backed by RPC notifications and WebViews. The build and packaging configuration now emits and unpacks a dedicated plugin-host-entry.js, and an example sidebar plugin with README is included.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The PR description covers summary/status, but it omits required template sections for screenshots, testing, AI review report, security audit, and notes. Add the missing template sections with screenshots or 'No visual change', test checklist status, review/security summaries, and any platform-specific notes.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: a plugin system foundation with shared contract, async API, and capability gating for Orca.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

gsxdsm and others added 15 commits June 19, 2026 04:37
…IFY)

Connects the host engine to the running app:
- index.ts: registerPluginScheme() before app.whenReady() (privileged scheme
  must be declared pre-ready); inside whenReady, createPluginSystem() +
  registerAssetProtocol() + registerPluginHandlers() (guarded so a plugin init
  failure can't block startup).
- electron.vite.config: build plugin-host-entry to out/main/.
- electron-builder: asar-unpack plugin-host-entry.js (ELECTRON_RUN_AS_NODE forks
  bypass asar require integration, like daemon-entry/computer-sidecar).

Node typecheck + builder-config test + 123 plugin tests green. Runtime behavior
(scheme serving, fork, activation) is verifiable only by launching the app.

Remaining: renderer UI (panel + Settings management + store slice), mobile, and
the npm/git/tarball installer (adds deps).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… (U5 UI)

NEEDS-RUNTIME-VERIFY. PluginPanel imperatively creates a sandboxed <webview>
(the repo manages webviews imperatively, not via JSX) pointed at
orca-plugin://<id>/ in a per-plugin partition with Node disabled — fault
isolation, not privilege. Loading/error/crashed states via dom-ready/
did-fail-load/render-process-gone; guest UI messages forwarded to the backend
through window.api.plugins.sendUiMessage on `ipc-message`. The right-sidebar
panel switch renders it for any `plugin:<id>` effectiveTab. Web typecheck +
lint clean.

The no-preload guest->host channel (whether the guest can emit ipc-message
without a minimal plugin preload) is the desktop bit the runtime pass confirms.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ity)

NEEDS-RUNTIME-VERIFY. The will-attach-webview gate previously fail-closed any
non-browser-session partition, so plugin UI webviews (persist:orca-plugin-<id>
serving orca-plugin://<id>/) would be rejected. Adds a plugin branch that allows
them with the SAME hardening (preload stripped, Node off, sandbox +
contextIsolation, webSecurity on) and requires the plugin partition and the
orca-plugin:// scheme to agree (mismatch fails closed). Node typecheck + lint
clean. Guest navigation-lock to orca-plugin://<id>/* is the runtime-pass item.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
NEEDS-RUNTIME-VERIFY. Enriches the plugins:list IPC with each plugin's manifest
title + Lucide icon name (plugin-system reads the manifest per installed
plugin), widens the PreloadApi list shape, and adds usePluginActivityItems which
turns active plugins into activity-bar items (resolving the Lucide icon name to
a component, falling back to Plug). The right-sidebar activityItems memo appends
these after the built-in tabs, so an active plugin gets a selectable tab that
renders its PluginPanel webview. Lint + node + web typecheck clean; 123 plugin
tests green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…(U6)

- PluginsPane: lists installed plugins (window.api.plugins.list, enriched with
  title/icon), activate/deactivate toggle, remove, and install-from-local-folder,
  with a prominent "plugins run with full access" trust note. NEEDS-RUNTIME-
  VERIFY; not yet wired into the grouped Settings nav (that registration + its
  group/mount/search wiring is the runtime-pass step).
- Fixes a localization-coverage regression: the earlier plugin-panel.tsx commit
  shipped untranslated JSX strings ("Loading plugin…", error text) that would
  fail `pnpm lint` (verify:localization-coverage). Both panels now route user
  strings through translate(); new keys synced into all locale catalogs.

verify:localization-catalog + coverage pass, oxlint + web typecheck clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
NEEDS-RUNTIME-VERIFY. Adds a 'plugins' section (interface group) to
useSettingsNavigationMetadata and renders PluginsPane via a SettingsSection in
Settings.tsx; mounting is navigation-driven (mounts when the section becomes
active), so no mount-allowlist change is needed. New nav title/description i18n
keys synced across all locale catalogs. localization coverage + catalog verify,
oxlint, and web typecheck all clean; 124 plugin tests green.

This completes the desktop management surface: install/activate/remove a plugin
from Settings, and active plugins appear as right-sidebar tabs rendering their
sandboxed webview.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…12 core)

The pure, unit-tested core of multi-source install, with NO new dependencies:
- install-source: parseInstallSource heuristically classifies an install string
  into local | registry (name@version, scoped) | git | tarball.
- install-integrity: sha256 + verify, a pinned lockfile (id/version/source/
  integrity), reinstall byte-verification against the lock, and an HTTPS-only
  guard for remote sources.

The actual fetching per source kind (public/private registry via arborist/
pacote, git clone, tarball download) adds production deps and is the NEEDS-DEPS /
NEEDS-RUNTIME-VERIFY adapter layer to wire on top of this core. 11 new tests
(135 plugin tests total), lint + node typecheck clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
resolveAndInstall dispatches local/registry/git/tarball through INJECTED fetch
adapters (real impls use node:https + system git/tar — no arborist/pacote), then
validates the staged manifest, re-checks id safety before placement, pins
integrity (sha256 for registry/tarball, commit for git), installs into
pluginsDir/<id>, and updates the lockfile. https-only for tarballs; staging is
cleaned up on any failure so a bad fetch leaves nothing behind. v1 targets
self-contained plugins (transitive dep resolution is a follow-up).

6 resolver tests with fake adapters (registry/git/tarball/local, integrity,
https guard, invalid-manifest + unsafe-id rejection with cleanup). 141 plugin
tests total, lint + node typecheck clean. The thin real adapters (https/git/tar)
are the NEEDS-RUNTIME-VERIFY layer on top.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…r (U12)

NEEDS-RUNTIME-VERIFY. createInstallAdapters implements the InstallAdapters the
resolver injects, using ONLY node:https + system git/tar (no arborist/pacote, no
new production deps):
- registry: GET registry.npmjs.org metadata, resolve version (requested or
  dist-tags.latest), download dist.tarball (follows one redirect to the CDN).
- tarball: https GET bytes.
- extractTarball: write to a temp .tgz and `tar -xzf --strip-components=1`
  (flattens npm's package/ prefix) into the dest.
- cloneGit: `git clone --depth 1` then `git rev-parse HEAD` to pin the commit.

Completes the installer (parse → fetch → extract/clone → validate → integrity →
place → lockfile) with zero dependency additions. Node typecheck + lint clean.
Network/subprocess behavior is runtime-only; the orchestration is unit-tested.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
NEEDS-RUNTIME-VERIFY. Connects the installer to the UI end to end:
- plugin-store: widen PluginInstallSource to local | registry | git | tarball.
- plugin-manager: recordInstalled() passthrough for externally-placed installs.
- plugin-system: installFromSource() — parse the input, resolveAndInstall via
  the real adapters, persist a userData/plugins-lock.json (load/save, corrupt-
  reset), and record the plugin (inactive).
- ipc/plugins: plugins:install handler; preload exposes window.api.plugins
  .installFromSource.
- PluginsPane: the install field now accepts an npm name / git URL / .tgz / local
  path (not just a folder), routed through installFromSource.

Settings → Plugins can now install from any supported source. localization
coverage + catalog, oxlint, node + web typecheck, and 141 plugin tests all green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The boot/IPC/preload wiring it listed as "remaining" is now in place; update the
comment to reflect that mobile/relay (v1c) + runtime verification are what's left.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
NEEDS-RUNTIME-VERIFY (relay bundle/runtime). Registers plugin.* JSON-RPC methods
so the mobile app reaches plugins where the workspace lives (relay host):
- plugin.list — discover installed plugins (id/title/icon/version/ui).
- plugin.getEntry — return a plugin's single UI HTML inline (mobile feeds it to
  react-native-webview as { html } — no on-device server).
- plugin.bridge — UI->backend bridge, gated by the SHARED electron-free
  capability-gate (identical decisions to the desktop main path, KTD3); serves a
  projected workspace snapshot, denies undeclared capabilities.

Electron-free; reuses plugin-discovery + the shared gate (no electron / src/main
glue beyond electron-free discovery). 5 tests with a fake dispatcher. Running
the trusted backend child on the relay + device-routed host commands are the
remaining remote-provisioning work. 146 plugin tests total, node typecheck +
lint clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
NEEDS-RUNTIME-VERIFY (mobile/Expo build). MobilePluginPanel fetches a plugin's
single UI HTML over the relay (plugin.getEntry) and renders it in
react-native-webview as { html } — no on-device server, no relative-asset
resolution. UI messages round-trip to the relay-hosted backend via plugin.bridge
over the RpcClient; loading + error states. Mirrors the existing TerminalWebView
pattern (same react-native-webview WebView/WebViewMessageEvent usage).

oxlint clean. The mobile TypeScript toolchain is not installed in this
environment (the whole mobile project reports ~3998 "cannot find react-native" /
"--jsx not set" errors, including unrelated files), so this is lint-verified +
pattern-mirrored only — verify with the mobile build (cd mobile && tsc) + a
device. Wiring it into the mobile nav + pairing the relay handler into the
dispatcher are the remaining mobile-integration steps.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Wire registerRelayPluginHandlers into relay.ts so plugin.list, plugin.getEntry,
and plugin.bridge resolve in the running relay. Plugins live under
$HOME/.orca-relay/plugins (the relay's userData equivalent); the workspace
snapshot defaults to a bounded empty value since the relay no longer tracks a
live root. Electron-free; relay bundle builds for all targets.
Add a 'plugins' panel to the mobile session dock/activity bar: a tested
plugin.list parser (mobile-plugin-list.ts), a MobilePluginListPanel that lists
installed plugins and opens one into MobilePluginPanel, the dock render branch,
the activity-bar button, and the narrow-layout plugins route. Pure logic is
unit-tested; JSX/navigation wiring is NEEDS-RUNTIME-VERIFY (Expo build can't run
here).
gsxdsm and others added 11 commits June 19, 2026 07:35
Security (P1): plugin.uiMessage no longer broadcasts to every relay client.
Track which clients opened each plugin and route backend responses only to
them via dispatcher.notifyClient; clear on deactivate + client detach. Prevents
one client's settings/workspace payloads leaking to other connected clients.

Reliability (R-001): add PluginHost.terminate() + PluginRuntime.stopAllSync()
and call it synchronously in relay socket cleanup, so backend children get
SIGTERM inline before process.exit instead of being orphaned.

Mobile (R-003): MobilePluginPanel surfaces a failed plugin.activate and sends
plugin.deactivate on unmount/plugin-switch so children don't accumulate.

Maintainability: createRelayPluginRuntime returns { runtime } only (drop unused
manager); PluginUiMatch is a discriminated union; export NotificationFrame for a
named cast; describe the stream-result guards by concept.

Tests: notification-listeners registry (dispatch/fanout/unsubscribe/false-paths),
deactivate traversal rejection, postUi activation_failed, deactivate stop()
assertion, and per-client uiMessage isolation + post-detach delivery.
- R-002: route the post-registration startSocketServer failure through a new
  exitWithCleanup() so plugin backend children are stopped, not orphaned.
- multi-client: refcount plugin subscribers — plugin.deactivate (and client
  detach) stop the shared backend child only when the last subscriber for that
  plugin leaves, instead of killing a child another client still has open.
- R-004: add a correlated request(message, {timeoutMs}) to the ui-bridge-client
  so a dropped relay connection rejects a pending bridge call instead of hanging
  the plugin UI forever (default 30s; clears timer + listener on settle).

Node+web typecheck, relay esbuild bundle, plugin/relay/shared tests, and
localization all green.
- M-01: reorder ui-bridge request() so finish is declared before the off/timer
  callbacks reference it (removes a TDZ risk if a substrate delivers sync).
- M-03: route relay uncaughtException + shutdown through exitWithCleanup so all
  post-registration exit paths stop plugin children uniformly.
- REL-01: .catch() the fire-and-forget releasePlugin in onClientDetached so a
  failed deactivate is logged, not dropped as an unhandled rejection.
- REL-02: module-level main().catch now runs cleanup before exit (safety net for
  late-startup rejections that escape the in-main guards).
- REL-03: comment the narrow crash-restart message-loss window.
- tests: assert clearTimeout fires + listener actually unregistered (not just
  settled-guarded), non-subscriber deactivate leaves another client's child
  running, and multi-plugin detach releases every open plugin.

Reviewers found no production bugs in the increment; these are hardening + test
strength. Node+web typecheck, relay bundle, tests, oxlint/oxfmt green.
Provision an installed plugin's files to the relay host so its backend can run.
- U1: shared plugin-bundle codec (file list + sha256 integrity + path-safety +
  byte cap), reusing install-integrity; pure + tested.
- U2: relay plugin.provision handler — verify integrity/paths, validate the
  embedded manifest + isSafePluginId, stage to temp, atomic rename under
  relayPluginsDir(); nothing written unless every check passes.
- U3: build-relay now emits plugin-host-entry.js next to relay.js per platform;
  relayPluginHostEntryPath() resolves bundle-relative (env override wins), so
  only plugin files transfer, not the entry. Relay bundle stays electron-free.
- U4: desktop readPluginBundleFromDisk (recursive, symlink/traversal-guarded) +
  provisionToRelay + shouldProvisionToRelay; a package<->unpack round-trip test
  proves the contract end to end without a live relay.

Live SSH transfer + real remote fork remain NEEDS-RUNTIME-VERIFY. Node+web
typecheck, relay esbuild bundle (now emitting the entry), plugin/relay/shared
tests, oxlint/oxfmt, localization green.
Security/adversarial (HIGH): provisionPlugin no longer destroys the prior
install on a failed swap — rmSync(dest)+rename replaced by a backup-restore
commit (move prior aside, rename staged in, restore on EXDEV/rename failure).
Staging setup moved inside the result-contract try so a staging-creation error
returns {ok:false} instead of throwing out of the handler.

Hardening: isSafeBundlePath rejects control chars (closes a newline digest-
collision in canonicalize); a file-count cap (PLUGIN_BUNDLE_MAX_FILES) bounds
inode/syscall abuse; relay-side paths reconstructed from posix segments via
native join (Windows relay hosts); provisionToRelay catches a rejected relay
request and returns a typed failure; readPluginBundleFromDisk documents its
throw-on-fs-error contract.

Maintainability: relayPluginStagingDir() + stagingDir config field (policy out
of the handler); build-relay shares a BASE_BUILD config across the two esbuild
outputs.

Tests: control-char path rejection (via fromCharCode), file-count cap, the
plugin.provision dispatch layer (valid write + invalid-bundle), staging-clean-
after-success, and provisionToRelay arg-forwarding + rejection mapping.

Note: provisionPlugin is fully synchronous so concurrent same-id provisions
can't interleave (no per-id lock needed). Cross-volume EXDEV for a brand-new
install still fails (safely, prior preserved); copy-fallback deferred. Node+web
typecheck, relay bundle (electron-free, emits host-entry), tests, lint, l10n green.
- U1: pure, injected coordinator (activatePluginForWorkspace) — local workspaces
  activate in-process unchanged; remote workspaces package the plugin, send
  plugin.provision, and only on success send plugin.activate over an injected
  relay request fn. Typed-failure on bundle-read throw / relay reject; provision
  failure aborts before activate. Fully unit-tested with fakes (local, happy,
  provision-fail, bundle-throw, activate-reject, ok:false, ordering).
- U2: PluginSystem.activateForWorkspace(pluginId, remote?) composes the
  coordinator; a resolveRelayRequest dep (default rejects-on-call) keeps the
  remote path an explicit, never-silent seam. plugins:activate routes through it
  (local by default — behavior unchanged) with the host-context wire marked
  NEEDS-RUNTIME-VERIFY.

The production remote-descriptor + relay-request resolver (from the workspace's
SshRelaySession) and live transfer/fork remain NEEDS-RUNTIME-VERIFY. Node+web
typecheck, plugin/relay/shared tests, oxlint/oxfmt green.
- guard pluginId with isSafePluginId before any disk read or relay call
  (remote provision path packages pluginsDir/<id>; reject traversal ids)
- consolidate ActivationResult onto PluginRuntime's ActivateResult (no drift)
- resolve relay request fn lazily so a future SSH-opening resolver never
  runs on a local activation
- document the intentional no-cleanup contract when provision succeeds but
  activate fails (re-provision is idempotent)
- add coverage: no_response, provision/bundle/activate fallback strings,
  async localActivate flatten, explicit non-remote descriptor, unsafe-id guard
- trim verbose comment blocks to the why (AGENTS.md)

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Addresses the deferred review residuals from the activate-path tier:
- per-request timeout: race each remote relay call (provision + activate)
  against an injected delay; expiry yields typed provision_timeout /
  activate_timeout instead of hanging (RELAY_REQUEST_TIMEOUT_MS default).
- compensating deactivate: when provision succeeds but activate fails by
  any means (reject / ok:false / no_response / timeout), best-effort fire
  plugin.deactivate before returning the original error; the deactivate's
  own rejection is swallowed and never masks the activate error.
- concurrent-activation coalescing: a pure coalesceByKey helper + a
  per-pluginId in-flight Map on PluginSystem so concurrent activations for
  one id share a single activation and can't race the relay bundle swap.

Coordinator stays pure + dependency-injected (delay/timeout, relayRequest,
localActivate, readBundle); +20 unit tests, no real relay or timers. Live
SSH transfer + production resolver wiring remain NEEDS-RUNTIME-VERIFY.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
- bound the compensating plugin.deactivate with the same raceWithTimeout
  (P1, 3-reviewer consensus): an un-timed cleanup call could re-introduce
  the exact indefinite hang U1's timeout was added to kill.
- key the in-flight coalesce map by tier+pluginId so a local and a remote
  activation of the same plugin can't coalesce into each other's result.
- narrow the relay activate response via a readActivateResult type guard
  instead of an `as` cast; the activate leg now returns a typed
  ActivationResult (drops the uninitialized let-activateError fallthrough).
- trim verbose comments to the why (AGENTS.md); add a test proving
  activation still returns activate_timeout when both activate AND the
  compensating deactivate hang.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
isInstalledPlugin/plugin.list/plugin.getEntry called discoverPlugins
(full dir scan + per-manifest validate) on every relay request. Memoize
the discovery result in a closure-held cache inside registerRelayPluginHandlers
and invalidate it only on a SUCCESSFUL plugin.provision (the sole relay-side
mutation of the installed set), so back-to-back activate/list/getEntry/postUi
requests scan once while a freshly-provisioned plugin is still immediately
discoverable (never a stale unknown_plugin). A failed provision keeps the
cache; the isSafePluginId boundary gate still runs before any discovery.

Adds an injectable discover fn (defaults to discoverPlugins) so tests assert
scan counts deterministically. Electron-free; relay bundle builds for all 6
targets.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Cross-reviewer consensus hardening of plugin.getEntry (the one handler
that didn't share the boundary contract):
- gate isSafePluginId first (matches activate/postUi), short-circuiting
  unsafe ids before the cache lookup. Not previously exploitable (the raw
  id is only matched === a validated manifest.id, never path-joined), but
  unifies the boundary shape and adds defense-in-depth.
- wrap readFileSync in try/catch → entry_read_failed so an existsSync→read
  I/O race returns the structured contract instead of leaking a raw fs error.

Tests: getEntry gates an unsafe id (scans()===0), postUi reads the cache
(no re-scan), and a newly-provisioned plugin appears in plugin.list after
invalidation.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@gsxdsm

gsxdsm commented Jun 19, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jun 19, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

Note

Due to the large number of review comments, Critical severity comments were prioritized as inline comments.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
config/scripts/build-relay.mjs (1)

67-71: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Include plugin-host-entry.js in the deploy hash.

The .version file still hashes only relay.js. If only the plugin host entry changes, the deploy check can skip updating the co-located child bundle and the relay will fork stale code.

Proposed fix
-  const relayContent = readFileSync(join(outDir, 'relay.js'))
-  const hash = createHash('sha256').update(relayContent).digest('hex').slice(0, 12)
+  const hash = createHash('sha256')
+    .update('relay.js\0')
+    .update(readFileSync(join(outDir, 'relay.js')))
+    .update('\0plugin-host-entry.js\0')
+    .update(readFileSync(join(outDir, 'plugin-host-entry.js')))
+    .digest('hex')
+    .slice(0, 12)
   writeFileSync(join(outDir, '.version'), `${RELAY_VERSION}+${hash}`)
🟠 Major comments (17)
examples/hello-sidebar-plugin/ui/index.html-24-25 (1)

24-25: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Use a real button for the “Open Orca docs” action.

At Line 24 the control is an <a> without href, so keyboard activation and semantics are broken. This is an accessibility blocker for users who navigate by keyboard.

Suggested fix
-    <p><a id="docs">Open Orca docs</a></p>
+    <p><button id="docs" type="button">Open Orca docs</button></p>
-      a { color: `#6cb6ff`; cursor: pointer; }
+      button {
+        color: `#6cb6ff`;
+        background: none;
+        border: 0;
+        padding: 0;
+        cursor: pointer;
+        text-decoration: underline;
+        font: inherit;
+      }

Also applies to: 43-45

src/shared/plugin/ui-bridge-client.ts-49-51 (1)

49-51: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Do not fall back to self-post in desktop mode.

When win.parent === win, Line 50 posts to self; then Lines 88-95 can match the outbound reqId and resolve the request immediately with its own request payload.

Suggested fix
-    const target = win.parent ?? win
-    target.postMessage?.(message, '*')
+    const target = win.parent && !Object.is(win.parent, win) ? win.parent : undefined
+    if (!target?.postMessage) {
+      throw new Error('UiBridge desktop mode requires an embedded parent window')
+    }
+    target.postMessage(message, '*')

Also applies to: 88-101

examples/hello-sidebar-plugin/main.js-15-39 (1)

15-39: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Capture and safely run event subscriptions.

Line 15 drops the onMessage disposable, and Lines 15-23/38 execute async work without a rejection path. That can leak handlers on re-activation and produce unhandled rejections from host calls.

Suggested fix
-  context.ui.onMessage(async (message) => {
-    if (message && message.type === 'open' && typeof message.url === 'string') {
-      // Allowlisted host command; the host validates the scheme (http/https).
-      await context.commands.invokeHost('open-external-url', { url: message.url })
-    }
-    if (message && message.type === 'set-greeting' && typeof message.value === 'string') {
-      await context.settings.set('greeting', message.value)
-    }
-  })
+  const uiSubscription = context.ui.onMessage((message) => {
+    void (async () => {
+      if (message && message.type === 'open' && typeof message.url === 'string') {
+        // Allowlisted host command; the host validates the scheme (http/https).
+        await context.commands.invokeHost('open-external-url', { url: message.url })
+      }
+      if (message && message.type === 'set-greeting' && typeof message.value === 'string') {
+        await context.settings.set('greeting', message.value)
+      }
+    })().catch((error) => context.log('ui.onMessage handler failed', error))
+  })
+  context.subscriptions.push(uiSubscription)
@@
-  context.subscriptions.push(context.workspace.onDidChange(() => void push()))
+  context.subscriptions.push(
+    context.workspace.onDidChange(() => {
+      void push().catch((error) => context.log('workspace push failed', error))
+    })
+  )
src/shared/plugin/settings-schema.ts-43-47 (1)

43-47: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Reject NaN/Infinity for type: 'number'.

Lines 45-47 currently accept non-finite numbers. Those values are invalid in JSON and can corrupt persisted settings semantics.

Suggested fix
 function matchesType(value: unknown, expected: JsonSchemaType): boolean {
-  const actual = typeOf(value)
-  if (expected === 'number') {
-    return actual === 'number' || actual === 'integer'
-  }
-  return actual === expected
+  if (expected === 'integer') {
+    return typeof value === 'number' && Number.isInteger(value)
+  }
+  if (expected === 'number') {
+    return typeof value === 'number' && Number.isFinite(value)
+  }
+  return typeOf(value) === expected
 }
src/shared/plugin/manifest-validate.ts-17-36 (1)

17-36: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Harden ui/main path validation to block Windows-root and UNC escapes

validateUiEntry currently misses some absolute Windows forms, and main is only checked for non-empty text. Because runtime later does join(dir, manifest.main), a traversing/absolute main can resolve outside the plugin directory boundary.

Suggested fix
+import path from 'node:path'
 import {
   isPluginCapability,
   isSafePluginId,
   SUPPORTED_HOST_API_MAJOR,
   type PluginManifest,
   type PluginContributes
 } from './manifest'
@@
-function validateUiEntry(value: unknown, field: string, errors: string[]): void {
+function validateRelativePath(
+  value: unknown,
+  field: string,
+  errors: string[],
+  opts: { requireHtml: boolean }
+): void {
   if (typeof value !== 'string' || value.length === 0) {
-    errors.push(`${field}: must be a non-empty string path to a single .html file`)
+    errors.push(
+      opts.requireHtml
+        ? `${field}: must be a non-empty string path to a single .html file`
+        : `${field}: required non-empty relative file path`
+    )
     return
   }
-  if (value.includes('..')) {
+  const normalized = value.replace(/\\/g, '/')
+  if (normalized.split('/').includes('..')) {
     errors.push(`${field}: must not contain '..' (path traversal)`)
   }
-  if (value.startsWith('/') || /^[A-Za-z]:[\\/]/.test(value)) {
+  if (path.posix.isAbsolute(normalized) || path.win32.isAbsolute(value)) {
     errors.push(`${field}: must be a relative path, not absolute`)
   }
-  if (!value.toLowerCase().endsWith('.html')) {
+  if (opts.requireHtml && !normalized.toLowerCase().endsWith('.html')) {
     errors.push(
       `${field}: must point to a single .html file (multi-file UIs are not supported yet)`
     )
   }
 }
@@
-    validateUiEntry(sidebar.ui, 'contributes.sidebar.ui', errors)
+    validateRelativePath(sidebar.ui, 'contributes.sidebar.ui', errors, { requireHtml: true })
@@
-      validateUiEntry(contributes.settings.ui, 'contributes.settings.ui', errors)
+      validateRelativePath(contributes.settings.ui, 'contributes.settings.ui', errors, {
+        requireHtml: true
+      })
@@
   requireString(record, 'main', errors)
+  validateRelativePath(record.main, 'main', errors, { requireHtml: false })

As per coding guidelines, "Use path.join or Electron/Node path utilities for file paths — never assume / or \ for cross-platform compatibility".

Also applies to: 142-145

Source: Coding guidelines

src/relay/plugin-provision.ts-84-86 (1)

84-86: ⚠️ Potential issue | 🟠 Major

Suppress backup cleanup failures to preserve successful provision status

At Line 85, rmSync can throw after the staged plugin has already been successfully moved into place at Line 76. Without a try-catch, this exception propagates to the outer catch block at Line 61, converting the success to { ok: false }, causing callers to see failure despite the plugin being provisioned on disk.

Suggested fix
 function commitStaged(staged: string, dest: string): ProvisionResult {
   if (hadPrior) {
-    rmSync(backup, { recursive: true, force: true })
+    try {
+      rmSync(backup, { recursive: true, force: true })
+    } catch {
+      // Commit already succeeded; keep the success contract even if backup cleanup fails.
+    }
   }
   return { ok: true }
 }
src/relay/plugin-handler.ts-205-212 (1)

205-212: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Rollback subscriber registration when activation fails.

On Line [210] and Line [232], the client is subscribed before activation succeeds. If runtime.activate() fails, that stale subscriber remains and can later receive another client’s plugin.uiMessage traffic.

💡 Suggested fix
@@
   const subscribers = new Map<string, Set<number>>()
@@
   const subscribe = (pluginId: string, clientId: number | undefined): void => {
@@
     set.add(clientId)
   }
+
+  const unsubscribe = (pluginId: string, clientId: number | undefined): void => {
+    if (clientId === undefined) {
+      return
+    }
+    const set = subscribers.get(pluginId)
+    if (!set) {
+      return
+    }
+    set.delete(clientId)
+    if (set.size === 0) {
+      subscribers.delete(pluginId)
+    }
+  }
@@
   dispatcher.onRequest('plugin.activate', async (params, context) => {
@@
     subscribe(pluginId, context.clientId)
-    return runtime.activate(pluginId)
+    const activated = await runtime.activate(pluginId)
+    if (!activated.ok) {
+      unsubscribe(pluginId, context.clientId)
+    }
+    return activated
   })
@@
   dispatcher.onRequest('plugin.postUi', async (params, context) => {
@@
     subscribe(pluginId, context.clientId)
     if (!runtime.isRunning(pluginId)) {
       const activated = await runtime.activate(pluginId)
       if (!activated.ok) {
+        unsubscribe(pluginId, context.clientId)
         return { ok: false, error: 'activation_failed' }
       }
     }

Also applies to: 227-237

mobile/src/components/plugins/MobilePluginPanel.tsx-95-101 (1)

95-101: ⚠️ Potential issue | 🟠 Major

Add navigation handler to prevent plugin HTML from navigating outside its sandbox.

The WebView lacks an onShouldStartLoadWithRequest handler, which means if the plugin HTML/JS attempts to navigate (via window.location, form submission, or link tap), originWhitelist={['*']} will silently allow any destination. Add a navigation guard to block unexpected navigation and maintain the sandbox boundary.

Based on the existing pattern in MobileHtmlPreview.tsx (which handles a similar inline-HTML artifact), restrict navigation to about:blank and data: URLs:

Suggested implementation
   return (
     <WebView
       ref={webViewRef}
       originWhitelist={['*']}
       source={{ html }}
       onMessage={onMessage}
+      onShouldStartLoadWithRequest={(request) => {
+        // Only allow the initial document and data: URLs (e.g., from injectJavaScript).
+        // External navigations indicate unexpected behavior; block them.
+        if (request.url === 'about:blank' || request.url.startsWith('data:')) {
+          return true
+        }
+        return false
+      }}
       javaScriptEnabled
       style={styles.webview}
     />
   )
src/main/plugin/install/install-resolver.ts-82-99 (1)

82-99: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Make install placement atomic and fully guarded by error handling.

The manifest/placement block is outside the try/catch, and dest is deleted before the new copy is guaranteed. A filesystem failure here can throw (instead of returning { ok: false }) and leave the plugin uninstalled.

Suggested direction
-import { cpSync, existsSync, rmSync } from 'node:fs'
+import { cpSync, existsSync, renameSync, rmSync } from 'node:fs'
...
-  const validated = validatePluginManifest(readManifestRaw(stagingDir))
-  if (!validated.ok) {
-    rmSync(stagingDir, { recursive: true, force: true })
-    return { ok: false, errors: validated.errors }
-  }
-  const manifest = validated.manifest
-  ...
-  const dest = join(pluginsDir, manifest.id)
-  rmSync(dest, { recursive: true, force: true })
-  cpSync(stagingDir, dest, { recursive: true })
-  rmSync(stagingDir, { recursive: true, force: true })
+  try {
+    const validated = validatePluginManifest(readManifestRaw(stagingDir))
+    if (!validated.ok) return { ok: false, errors: validated.errors }
+    const manifest = validated.manifest
+    ...
+    const dest = join(pluginsDir, manifest.id)
+    const next = join(pluginsDir, `${manifest.id}.next`)
+    const backup = join(pluginsDir, `${manifest.id}.bak`)
+    rmSync(next, { recursive: true, force: true })
+    rmSync(backup, { recursive: true, force: true })
+    cpSync(stagingDir, next, { recursive: true })
+    if (existsSync(dest)) renameSync(dest, backup)
+    renameSync(next, dest)
+    rmSync(backup, { recursive: true, force: true })
+    ...
+  } catch (error) {
+    return { ok: false, errors: [error instanceof Error ? error.message : String(error)] }
+  } finally {
+    rmSync(stagingDir, { recursive: true, force: true })
+  }
src/main/plugin/plugin-install.ts-29-39 (1)

29-39: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Reinstall flow can silently remove a working plugin on copy failure.

Line 29 removes the existing install before Line 33 attempts the copy. If copy fails, the previous version is gone and the plugin ends up uninstalled.

Consider staging into a temp directory (<id>.tmp) and renaming on success so failed upgrades preserve the prior working bundle.

src/main/plugin/plugin-manager.ts-85-96 (1)

85-96: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

remove() can restore store state while files are already deleted.

Line 93 deletes plugin files before this.store.remove(id) persists. If persistence fails, PluginStore.remove() rolls back the entry, leaving state that says installed while the directory is gone.

This needs transactional ordering/compensation so disk and persisted state cannot diverge on partial failure.

src/renderer/src/components/settings/PluginsPane.tsx-32-69 (1)

32-69: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Async UI actions can fail with unhandled promise rejections.

install, toggle, and remove await IPC calls but do not catch thrown errors; with void event handlers, failures are unhandled and user feedback is skipped.

Suggested pattern
+  const toErrorMessage = (error: unknown): string =>
+    error instanceof Error ? error.message : String(error)
+
   const install = useCallback(async () => {
     if (!sourceDir.trim()) {
       return
     }
     setBusy(true)
     setError(null)
     try {
       const result = await window.api.plugins.installFromSource(sourceDir.trim())
       if (!result.ok) {
         setError(
           result.errors?.join('; ') ?? translate('plugins.pane.installFailed', 'Install failed')
         )
       } else {
         setSourceDir('')
       }
       await refresh()
+    } catch (error) {
+      setError(toErrorMessage(error))
     } finally {
       setBusy(false)
     }
   }, [sourceDir, refresh])

   const toggle = useCallback(
     async (plugin: PluginRow) => {
-      await (plugin.active
-        ? window.api.plugins.deactivate(plugin.id)
-        : window.api.plugins.activate(plugin.id))
-      await refresh()
+      try {
+        await (plugin.active
+          ? window.api.plugins.deactivate(plugin.id)
+          : window.api.plugins.activate(plugin.id))
+        await refresh()
+      } catch (error) {
+        setError(toErrorMessage(error))
+      }
     },
     [refresh]
   )

   const remove = useCallback(
     async (plugin: PluginRow) => {
-      await window.api.plugins.remove(plugin.id)
-      await refresh()
+      try {
+        await window.api.plugins.remove(plugin.id)
+        await refresh()
+      } catch (error) {
+        setError(toErrorMessage(error))
+      }
     },
     [refresh]
   )

Also applies to: 98-131

src/main/plugin/plugin-manager.ts-60-65 (1)

60-65: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

installLocal() can throw despite returning InstallResult.

If Line 63 cleanup (rmSync) fails, the catch block throws and breaks the method contract (InstallResult instead of exceptions).

Suggested guard for cleanup failure
     } catch (error) {
-      // State write failed — remove the copied dir so we never leave an
-      // installed-but-unrecorded plugin behind.
-      rmSync(join(this.config.pluginsDir, result.id), { recursive: true, force: true })
-      return { ok: false, errors: [error instanceof Error ? error.message : String(error)] }
+      const errors = [error instanceof Error ? error.message : String(error)]
+      try {
+        rmSync(join(this.config.pluginsDir, result.id), { recursive: true, force: true })
+      } catch (cleanupError) {
+        errors.push(
+          cleanupError instanceof Error ? cleanupError.message : String(cleanupError)
+        )
+      }
+      return { ok: false, errors }
     }
src/main/plugin/plugin-host-handler.ts-71-78 (1)

71-78: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Differentiate schema errors from persistence failures in settings.set responses.

Line 77 currently returns invalid_params for every failed write. That misclassifies disk/write failures as caller mistakes and hides operational faults from the plugin bridge. Return internal for persistence errors and reserve invalid_params for schema/validation failures.

Suggested direction
// plugin-settings-store.ts
-export type SettingsWriteResult = { ok: true } | { ok: false; errors: string[] }
+export type SettingsWriteResult =
+  | { ok: true }
+  | { ok: false; reason: 'validation' | 'storage'; errors: string[] }

// plugin-host-handler.ts
-const result = services.settings.set(params.key, params.value)
-return result.ok ? ok(request.reqId, undefined) : fail(request.reqId, 'invalid_params')
+const result = services.settings.set(params.key, params.value)
+if (!result.ok) {
+  return fail(request.reqId, result.reason === 'validation' ? 'invalid_params' : 'internal')
+}
+return ok(request.reqId, undefined)
src/main/plugin/plugin-runtime.ts-109-112 (1)

109-112: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

handleExit is called twice for pre-ready failures.

When host.start() rejects, Line 111 calls handleExit(...), but unexpected child exits are already routed through onExit (Line 103). This double-counts crashes and can schedule duplicate restarts.

Proposed fix
    } catch (error) {
      this.running.delete(pluginId)
-      this.handleExit(pluginId, false)
+      // Ensure any failed-start child is cleaned up; exit callback handles state transitions.
+      await host.stop().catch(() => host.terminate())
      return { ok: false, error: error instanceof Error ? error.message : String(error) }
    }
src/main/ipc/plugins.ts-41-45 (1)

41-45: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Derive the UI bridge plugin identity server-side.

This handler still trusts the pluginId argument from the renderer; _event is ignored, so the sender-bound identity described above is not enforced. Bind each plugin UI bridge to a main-owned webContents/session/token → pluginId mapping and call postUi with the derived id instead of accepting it from IPC.

src/main/window/createMainWindow.ts-472-489 (1)

472-489: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Require the plugin partition id to match the orca-plugin:// host.

The current check only requires both prefixes, so persist:orca-plugin-beta can load orca-plugin://alpha/.... That breaks the intended per-plugin isolation/identity boundary.

Proposed fix
-    const pluginPartition = partition.startsWith('persist:orca-plugin-')
-    const pluginSrc = src.startsWith('orca-plugin://')
-    if (pluginPartition || pluginSrc) {
-      if (!pluginPartition || !pluginSrc) {
+    const pluginPartitionPrefix = 'persist:orca-plugin-'
+    const pluginSrcPrefix = 'orca-plugin://'
+    const pluginPartitionId = partition.startsWith(pluginPartitionPrefix)
+      ? partition.slice(pluginPartitionPrefix.length)
+      : null
+    const pluginSrcId = src.startsWith(pluginSrcPrefix)
+      ? src.slice(pluginSrcPrefix.length).split(/[/?#]/, 1)[0]
+      : null
+    if (pluginPartitionId || pluginSrcId) {
+      if (!pluginPartitionId || !pluginSrcId || pluginPartitionId !== pluginSrcId) {
         event.preventDefault()
         return
       }
🟡 Minor comments (8)
examples/hello-sidebar-plugin/README.md-10-15 (1)

10-15: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add a language to the fenced code block.

The code fence at Line 10 is missing a language tag, which triggers markdownlint MD040.

Suggested fix
-```
+```text
 plugin.json        # manifest (id, version, hostApiVersion, contributes, capabilities, settingsSchema)
 main.js            # backend (trusted Node) — exports activate(context) / deactivate()
 ui/index.html      # sidebar panel UI (single self-contained file)
 ui/settings.html   # settings page UI (single self-contained file)
</details>

<!-- cr-comment:v1:0d41f3d99dd84ac65e766f7b -->

_Source: Linters/SAST tools_

</blockquote></details>
<details>
<summary>src/shared/plugin/capability-gate.ts-88-91 (1)</summary><blockquote>

`88-91`: _⚠️ Potential issue_ | _🟡 Minor_ | _⚡ Quick win_

**Normalize `openFileCount` to a non-negative integer.**

Line 88 currently accepts values like `-1` or `2.5`. For a bounded workspace snapshot, this should fall back to `0` unless it is an integer `>= 0`.






<details>
<summary>Suggested fix</summary>

```diff
-    openFileCount:
-      typeof source.openFileCount === 'number' && Number.isFinite(source.openFileCount)
-        ? source.openFileCount
-        : 0
+    openFileCount:
+      typeof source.openFileCount === 'number' &&
+      Number.isInteger(source.openFileCount) &&
+      source.openFileCount >= 0
+        ? source.openFileCount
+        : 0
mobile/src/transport/notification-listeners.ts-31-33 (1)

31-33: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Validate params shape before invoking listeners.

At Line 31, frame.params is force-cast to Record<string, unknown> without runtime checks. Non-object payloads can violate the listener contract and break consumers that assume key/value access.

Suggested fix
-    const params = (frame.params ?? {}) as Record<string, unknown>
+    const params =
+      frame.params && typeof frame.params === 'object' && !Array.isArray(frame.params)
+        ? (frame.params as Record<string, unknown>)
+        : {}
src/main/plugin/install/install-adapters.ts-24-27 (1)

24-27: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Unbounded redirect following could cause issues.

The recursive httpsGet call follows redirects without a depth limit. While npm registry redirects are typically finite, a malicious or misconfigured tarball URL could cause a redirect loop leading to stack overflow or hang.

Consider adding a depth parameter to limit redirect following.

🛡️ Proposed fix to add redirect depth limit
-function httpsGet(url: string, asJson: boolean): Promise<Buffer> {
+function httpsGet(url: string, asJson: boolean, maxRedirects = 3): Promise<Buffer> {
   return new Promise((resolve, reject) => {
     const req = request(
       url,
       { method: 'GET', headers: asJson ? { accept: 'application/json' } : {} },
       (res) => {
         const status = res.statusCode ?? 0
         // Follow one level of redirect (registry tarballs commonly 3xx to a CDN).
-        if (status >= 300 && status < 400 && res.headers.location) {
+        if (status >= 300 && status < 400 && res.headers.location && maxRedirects > 0) {
           res.resume()
-          httpsGet(new URL(res.headers.location, url).toString(), asJson).then(resolve, reject)
+          httpsGet(new URL(res.headers.location, url).toString(), asJson, maxRedirects - 1).then(resolve, reject)
           return
         }
+        if (status >= 300 && status < 400) {
+          res.resume()
+          reject(new Error(`GET ${url} failed: too many redirects`))
+          return
+        }
src/main/plugin/plugin-store.ts-39-49 (1)

39-49: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

load() admits partial entries that violate PluginStateEntry invariants.

isValidEntry does not validate source or installedAt, so list()/get() can return structurally incomplete entries after loading a malformed state file.

Suggested hardening
 function isValidEntry(value: unknown): value is PluginStateEntry {
   if (typeof value !== 'object' || value === null) {
     return false
   }
   const entry = value as Record<string, unknown>
   return (
     typeof entry.id === 'string' &&
     typeof entry.version === 'string' &&
-    typeof entry.active === 'boolean'
+    typeof entry.active === 'boolean' &&
+    typeof entry.installedAt === 'string' &&
+    typeof entry.source === 'object' &&
+    entry.source !== null &&
+    typeof (entry.source as Record<string, unknown>).kind === 'string'
   )
 }

Also applies to: 69-72

src/main/plugin/plugin-asset-protocol.test.ts-5-5 (1)

5-5: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Use node:path utilities instead of a hardcoded POSIX path.

'/plugins' bakes in / and violates the cross-platform path rule; use join/resolve to construct this test root consistently.

Suggested patch
 import { describe, expect, it } from 'vitest'
-import { resolve } from 'node:path'
+import { join, resolve } from 'node:path'
 import { parsePluginAssetUrl, resolvePluginAsset } from './plugin-asset-protocol'
 
-const PLUGINS_DIR = '/plugins'
+const PLUGINS_DIR = join('plugins-root')
 const active = (id: string): boolean => id === 'acme.foo'

As per coding guidelines, “Use path.join or Electron/Node path utilities for file paths — never assume / or \ for cross-platform compatibility.”

Source: Coding guidelines

src/renderer/src/components/right-sidebar/plugin-panel.tsx-41-44 (1)

41-44: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Handle sendUiMessage rejection to avoid unhandled promise noise.

At Line 43, rejected IPC calls are dropped without handling; repeated guest messages can generate unhandled rejections in the renderer.

Suggested fix
     const onIpc = (event: Electron.IpcMessageEvent): void => {
       if (event.channel === 'plugin-ui') {
-        void window.api.plugins.sendUiMessage(pluginId, event.args?.[0])
+        void window.api.plugins.sendUiMessage(pluginId, event.args?.[0]).catch(() => {
+          // Channel unavailable (plugin/runtime teardown); ignore one-way message failure.
+        })
       }
     }
src/main/plugin/plugin-asset-protocol.ts-20-27 (1)

20-27: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Strip query and fragment before resolving asset files.

assetPath currently includes ? / #, so orca-plugin://acme.foo/app.js?v=1 resolves to a literal app.js?v=1 filename and common cache-busted plugin assets fail to load.

Proposed fix
-  const rest = url.slice(prefix.length)
+  const rawRest = url.slice(prefix.length)
+  const suffixStart = rawRest.search(/[?#]/)
+  const rest = suffixStart === -1 ? rawRest : rawRest.slice(0, suffixStart)
   const slash = rest.indexOf('/')
🧹 Nitpick comments (3)
mobile/src/transport/notification-listeners.test.ts (1)

24-30: ⚡ Quick win

Add a malformed params case to lock the runtime contract.

Please add a case for frames like { method: 'm', params: 42 } (or array/string) so dispatch behavior for non-object payloads is explicitly tested and regression-safe.

src/main/plugin/install/install-adapters.ts (1)

16-41: ⚡ Quick win

No timeout on HTTPS requests could hang indefinitely.

The httpsGet function doesn't set a timeout. A slow or unresponsive server could cause plugin installation to hang forever, blocking the user and potentially holding resources.

Consider adding a request timeout.

♻️ Proposed fix to add request timeout
 function httpsGet(url: string, asJson: boolean): Promise<Buffer> {
   return new Promise((resolve, reject) => {
     const req = request(
       url,
-      { method: 'GET', headers: asJson ? { accept: 'application/json' } : {} },
+      { method: 'GET', headers: asJson ? { accept: 'application/json' } : {}, timeout: 30_000 },
       (res) => {
         // ... existing handler
       }
     )
+    req.on('timeout', () => {
+      req.destroy()
+      reject(new Error(`GET ${url} failed: request timed out`))
+    })
     req.on('error', reject)
     req.end()
   })
 }
src/main/plugin/plugin-system.ts (1)

191-203: 💤 Low value

invokeCommand silently converts undefined args to string "undefined".

If args.url or args.text is undefined, String(args.url) yields "undefined". For open-external-url, Electron would reject "undefined" as an invalid URL. For copy-to-clipboard, it would copy the literal text "undefined".

Since the comment states the gate already validated params, consider adding a debug assertion or early return for malformed args.

🛡️ Proposed defensive check
   private async invokeCommand(name: HostCommand, params: unknown): Promise<unknown> {
     const args = (params ?? {}) as { url?: string; text?: string }
     switch (name) {
       case 'open-external-url':
+        if (typeof args.url !== 'string') return undefined
         await shell.openExternal(String(args.url))
         return undefined
       case 'copy-to-clipboard':
+        if (typeof args.text !== 'string') return undefined
         clipboard.writeText(String(args.text))
         return undefined
       default:
         return undefined
     }
   }

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: fe83f53f-a1e6-4bec-b3eb-9f18ad5027da

📥 Commits

Reviewing files that changed from the base of the PR and between ae77156 and 0dbdbd7.

📒 Files selected for processing (109)
  • config/electron-builder.config.cjs
  • config/scripts/build-relay.mjs
  • electron.vite.config.ts
  • examples/hello-sidebar-plugin/README.md
  • examples/hello-sidebar-plugin/main.js
  • examples/hello-sidebar-plugin/plugin.json
  • examples/hello-sidebar-plugin/ui/index.html
  • examples/hello-sidebar-plugin/ui/settings.html
  • mobile/app/h/[hostId]/plugins/[worktreeId].tsx
  • mobile/app/h/[hostId]/session/[worktreeId].tsx
  • mobile/src/components/plugins/MobilePluginListPanel.tsx
  • mobile/src/components/plugins/MobilePluginPanel.tsx
  • mobile/src/components/plugins/mobile-plugin-bridge.test.ts
  • mobile/src/components/plugins/mobile-plugin-bridge.ts
  • mobile/src/components/plugins/mobile-plugin-list.test.ts
  • mobile/src/components/plugins/mobile-plugin-list.ts
  • mobile/src/session/SessionDockColumn.tsx
  • mobile/src/session/session-panel-host.test.ts
  • mobile/src/session/session-panel-host.ts
  • mobile/src/transport/notification-listeners.test.ts
  • mobile/src/transport/notification-listeners.ts
  • mobile/src/transport/rpc-client.ts
  • mobile/src/transport/rpc-stream-result-guards.ts
  • src/main/index.ts
  • src/main/ipc/plugins.ts
  • src/main/plugin/in-flight-coalesce.test.ts
  • src/main/plugin/in-flight-coalesce.ts
  • src/main/plugin/install/install-adapters.ts
  • src/main/plugin/install/install-integrity.test.ts
  • src/main/plugin/install/install-integrity.ts
  • src/main/plugin/install/install-resolver.test.ts
  • src/main/plugin/install/install-resolver.ts
  • src/main/plugin/install/install-source.test.ts
  • src/main/plugin/install/install-source.ts
  • src/main/plugin/plugin-activation-coordinator.test.ts
  • src/main/plugin/plugin-activation-coordinator.ts
  • src/main/plugin/plugin-asset-protocol.test.ts
  • src/main/plugin/plugin-asset-protocol.ts
  • src/main/plugin/plugin-bundle.test.ts
  • src/main/plugin/plugin-bundle.ts
  • src/main/plugin/plugin-discovery.test.ts
  • src/main/plugin/plugin-discovery.ts
  • src/main/plugin/plugin-host-entry.ts
  • src/main/plugin/plugin-host-handler.test.ts
  • src/main/plugin/plugin-host-handler.ts
  • src/main/plugin/plugin-host-process.test.ts
  • src/main/plugin/plugin-host-process.ts
  • src/main/plugin/plugin-host-protocol.ts
  • src/main/plugin/plugin-install.test.ts
  • src/main/plugin/plugin-install.ts
  • src/main/plugin/plugin-manager.test.ts
  • src/main/plugin/plugin-manager.ts
  • src/main/plugin/plugin-output-buffer.test.ts
  • src/main/plugin/plugin-output-buffer.ts
  • src/main/plugin/plugin-remote-provision.test.ts
  • src/main/plugin/plugin-remote-provision.ts
  • src/main/plugin/plugin-runtime.test.ts
  • src/main/plugin/plugin-runtime.ts
  • src/main/plugin/plugin-settings-store.test.ts
  • src/main/plugin/plugin-settings-store.ts
  • src/main/plugin/plugin-store.test.ts
  • src/main/plugin/plugin-store.ts
  • src/main/plugin/plugin-supervision.test.ts
  • src/main/plugin/plugin-supervision.ts
  • src/main/plugin/plugin-system.ts
  • src/main/window/createMainWindow.ts
  • src/preload/api-types.ts
  • src/preload/index.ts
  • src/relay/dispatcher.ts
  • src/relay/plugin-handler.test.ts
  • src/relay/plugin-handler.ts
  • src/relay/plugin-provision.test.ts
  • src/relay/plugin-provision.ts
  • src/relay/relay-plugin-config.test.ts
  • src/relay/relay-plugin-config.ts
  • src/relay/relay-plugin-runtime.test.ts
  • src/relay/relay-plugin-runtime.ts
  • src/relay/relay.ts
  • src/renderer/src/components/right-sidebar/index.tsx
  • src/renderer/src/components/right-sidebar/plugin-panel.tsx
  • src/renderer/src/components/right-sidebar/right-sidebar-panel-content.tsx
  • src/renderer/src/components/right-sidebar/use-plugin-activity-items.ts
  • src/renderer/src/components/settings/PluginsPane.tsx
  • src/renderer/src/components/settings/Settings.tsx
  • src/renderer/src/hooks/useSettingsNavigationMetadata.ts
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/i18n/locales/es.json
  • src/renderer/src/i18n/locales/ja.json
  • src/renderer/src/i18n/locales/ko.json
  • src/renderer/src/i18n/locales/zh.json
  • src/renderer/src/store/right-sidebar-route.test.ts
  • src/renderer/src/store/right-sidebar-route.ts
  • src/renderer/src/store/slices/worktrees.ts
  • src/shared/plugin/api-contract.test.ts
  • src/shared/plugin/api-contract.ts
  • src/shared/plugin/capability-consent.test.ts
  • src/shared/plugin/capability-consent.ts
  • src/shared/plugin/capability-gate.test.ts
  • src/shared/plugin/capability-gate.ts
  • src/shared/plugin/example-plugin.test.ts
  • src/shared/plugin/manifest-validate.test.ts
  • src/shared/plugin/manifest-validate.ts
  • src/shared/plugin/manifest.test.ts
  • src/shared/plugin/manifest.ts
  • src/shared/plugin/settings-schema.test.ts
  • src/shared/plugin/settings-schema.ts
  • src/shared/plugin/ui-bridge-client.test.ts
  • src/shared/plugin/ui-bridge-client.ts
  • src/shared/types.ts

Comment thread src/main/plugin/plugin-host-entry.ts Resolved
Comment thread src/main/plugin/plugin-runtime.ts Resolved
- install-resolver: verify reinstall integrity. A same-id/same-version
  reinstall from a bytes-addressable source (registry/tarball) now checks
  the freshly-fetched bytes against the pinned lock integrity before
  overwriting, so a compromised registry can't swap bytes under a known
  version. A different version (upgrade) skips the check.
- plugin-runtime: honor the restart cap. A supervisor-driven restart no
  longer resets the crash counter (only a fresh user activation does), so
  crash loops actually reach maxRestarts and mark the plugin errored
  instead of restarting forever.
- plugin-runtime: terminate the child on a failed start() so an
  activate-error that left the fork alive isn't orphaned (parent-side, so
  the supervisor isn't double-driven).
- use-plugin-activity-items: guard icon resolution to renderable forwardRef
  components, so an untrusted manifest naming a non-icon export (e.g.
  createLucideIcon) falls back to Plug instead of crashing the sidebar.

Tests added for each. Note: the icon guard is stricter than the suggested
one — createLucideIcon is itself a function, so a typeof==='function'
check would let it through; only 67871typeof-bearing components pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@boudydegeer

Copy link
Copy Markdown

We're building a PR-dashboard plugin (backend runs gh pr list + checks and pushes results to the panel). The v0 experimental plugin API works great for notifications, but the panel can't receive worker data yet — the postUi/uiMessage bridge in this v1a track is exactly what we need. Happy to test the desktop runtime flow with a real-world plugin when it's ready.

@AmethystLiang

Copy link
Copy Markdown
Contributor

Thanks for the contribution — the underlying change is already implemented in main, so we’re closing this PR as superseded.

@gsxdsm
gsxdsm deleted the gsxdsm/plugin-system-v1a branch October 31, 2026 18:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants