Files
archived-orca/src/cli/plugin-dev-watch/plugin-dev-watch-loop.ts
T
Neil b17d408416 Plugin dev loop: TS workers, hot reload with state, orca plugin dev watch, authoring skill (#36982)
* feat(plugins): build-less TypeScript workers

A worker's main may be .ts/.mts. The plugin host installs module.registerHooks scoped to the
plugin folder: .ts files are transpiled with the frames' sucrase options (lines kept, inline
source map, source maps on), relative imports fall back to the frames' candidate files, and a
value import of the type-only 'orca/worker' fails with a clear error. Needs engines.orca
>=1.4.246.

* feat(plugins): components panels hot reload with their state

- In dev folders a save swaps only the hidden guest: keyed memory atoms are handed to the new
  guest (ui.retain → ui.hydrate memory), dropped when an atom's version changes.
- A save that fails to load keeps the last good render and shows an inline file:line:col
  error banner; the next good save clears it. A subtle Reloaded mark follows a reload.
- Transpile and import errors carry line and column; dev worker restarts keep storage.

* feat(plugins): orca plugin dev watch

One command for the inner loop: refreshes .orca/types, dev-loads the folder, follows its frame
and worker logs (plugins.getLogs gains an optional cursor), prints reloads (optional
devChangeCount on list entries) and status changes, and unloads on Ctrl-C. --json streams
NDJSON events for agents.

* feat(skills): orca-plugin-authoring bundled skill guide

A guide for agents to build Orca plugins end to end (decision table, build-less rules, the
dev watch loop, test/check, validate, release-entry, approvals, gotchas) with references
generated from the component catalog, host API table, event schemas, manifest schema and CLI
specs, checked for drift. Fixes the components template's Reset to set(count, 0).

* feat(plugins): orca plugin dev watch --check; test kit details in the authoring skill

- --check runs orca plugin check after the load and after each reload (one at a time; saves
  made meanwhile fold into one rerun) and prints each panel's render or errors inline, as a
  `check` event with --json. Local folders only, since it runs the plugin's code here.
- The orca-plugin-authoring guide's Test and check section now documents orca plugin test and
  check from #36969 exactly (JSON results, exit codes, test placement, the orca/testing kit and
  its common mistakes), and the loop uses dev watch --check.

* refactor(plugins): move the components renderer's timing and helper constants to their own module
2026-11-01 03:32:25 -08:00

213 lines
7.0 KiB
TypeScript

import type { DevLoadResult, LogsResult } from '../handlers/plugin-runtime'
import type { PluginHostListEntry } from '../../shared/plugins/plugin-list-entry'
import type {
PluginDevWatchApproval,
PluginDevWatchEvent,
PluginDevWatchStatus
} from './plugin-dev-watch-events'
import { PluginLogFollower } from './plugin-log-follower'
import {
createPluginDevWatchCheckQueue,
type PluginDevWatchCheckResult
} from './plugin-dev-watch-check'
/** What the loop asks of the Orca host; the handler binds it to RPC for one folder. */
export type PluginDevWatchHost = {
refreshTypes(): Promise<string[]>
devLoad(): Promise<DevLoadResult>
list(): Promise<PluginHostListEntry[]>
logs(pluginKey: string, after: string | undefined): Promise<LogsResult>
/** Re-checks the folder's approval; null when it needs none. */
approvalNeeded(): Promise<PluginDevWatchApproval | null>
devUnload(): Promise<void>
/** `--check` only: validates the folder and renders its components panels once. */
check?: () => Promise<PluginDevWatchCheckResult>
}
export type PluginDevWatchDeps = {
host: PluginDevWatchHost
emit(event: PluginDevWatchEvent): void
/** Resolves after `ms`, or as soon as `signal` aborts. */
wait(ms: number, signal: AbortSignal): Promise<void>
/** Subscribes to Ctrl-C (and the platform's other stop signals); returns the unsubscribe. */
onInterrupt(listener: () => void): () => void
exitNow(code: number): void
isConnectionLost(error: unknown): boolean
}
// Why these rates: logs feel live at 500 ms, and the plugin list (a projection of every plugin) is
// heavier, so it is read once a second.
export const PLUGIN_DEV_WATCH_POLL_MS = 500
const LIST_EVERY_POLLS = 2
const INTERRUPTED_EXIT_CODE = 130
type Snapshot = {
status: PluginDevWatchStatus
error?: string
needsApproval: boolean
devChangeCount?: number
}
function snapshotOf(entry: PluginHostListEntry | null | undefined): Snapshot {
if (!entry) {
return { status: 'missing', needsApproval: false }
}
return {
status: entry.status,
...(entry.error ? { error: entry.error } : {}),
needsApproval: entry.status === 'pending' || entry.needsReconsent,
...(entry.devChangeCount === undefined ? {} : { devChangeCount: entry.devChangeCount })
}
}
/** Our entry, or the one new invalid dev entry: a manifest that no longer parses loses its key. */
function findEntry(
list: readonly PluginHostListEntry[],
pluginKey: string,
otherKeys: ReadonlySet<string>
): PluginHostListEntry | undefined {
const own = list.find((entry) => entry.pluginKey === pluginKey)
if (own) {
return own
}
const strays = list.filter(
(entry) => entry.isDev && entry.status === 'invalid' && !otherKeys.has(entry.pluginKey)
)
return strays.length === 1 ? strays[0] : undefined
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error)
}
/** Loads the folder, then streams its logs and reload status until interrupted. Returns the exit
* code. A failed first load throws (approval_required exits 3 like `orca plugin dev load`). */
export async function runPluginDevWatch(deps: PluginDevWatchDeps): Promise<number> {
const { host, emit } = deps
const typeFiles = await host.refreshTypes()
const loaded = await host.devLoad()
const { pluginKey } = loaded
let snapshot = snapshotOf(loaded.plugin)
emit({
type: 'loaded',
pluginKey,
path: loaded.path,
added: loaded.added,
status: snapshot.status,
...(snapshot.error ? { error: snapshot.error } : {}),
typeFiles
})
const stop = new AbortController()
let interrupts = 0
const unsubscribe = deps.onInterrupt(() => {
interrupts += 1
if (interrupts > 1) {
deps.exitNow(INTERRUPTED_EXIT_CODE)
return
}
stop.abort()
})
const runCheck = host.check
const checks = runCheck
? createPluginDevWatchCheckQueue(async () => {
try {
emit({ type: 'check', pluginKey, ...(await runCheck()) })
} catch (error) {
emit({ type: 'warning', message: `check could not run: ${errorMessage(error)}` })
}
})
: null
checks?.request()
const follower = new PluginLogFollower()
let otherKeys: ReadonlySet<string> | null = null
let lastWarning: string | null = null
const pollLogs = async (): Promise<void> => {
for (const line of follower.take(await host.logs(pluginKey, follower.cursor))) {
emit({ type: 'log', pluginKey, ...line })
}
}
const pollStatus = async (): Promise<void> => {
const list = await host.list()
otherKeys ??= new Set(list.map((entry) => entry.pluginKey).filter((key) => key !== pluginKey))
const next = snapshotOf(findEntry(list, pluginKey, otherKeys))
const changes =
next.devChangeCount !== undefined && snapshot.devChangeCount !== undefined
? next.devChangeCount - snapshot.devChangeCount
: 0
const error = next.error ? { error: next.error } : {}
if (changes > 0) {
emit({ type: 'reloaded', pluginKey, changes, status: next.status, ...error })
checks?.request()
} else if (next.status !== snapshot.status || next.error !== snapshot.error) {
emit({
type: 'status',
pluginKey,
status: next.status,
previousStatus: snapshot.status,
...error
})
}
const newlyNeedsApproval = next.needsApproval && !snapshot.needsApproval
snapshot = next
if (newlyNeedsApproval) {
const approval = await host.approvalNeeded()
if (approval) {
emit({ type: 'approval', pluginKey, ...approval })
}
}
}
try {
let polls = -1
while (!stop.signal.aborted) {
try {
if (polls === -1) {
// Baseline: only lines written from now on are streamed.
follower.take(await host.logs(pluginKey, undefined))
} else {
await pollLogs()
if (polls % LIST_EVERY_POLLS === 0) {
await pollStatus()
}
}
lastWarning = null
} catch (error) {
if (deps.isConnectionLost(error)) {
emit({ type: 'disconnected', message: errorMessage(error) })
return 1
}
// Why once: a host-side failure repeats every poll until something changes.
const message = errorMessage(error)
if (message !== lastWarning) {
emit({ type: 'warning', message })
lastWarning = message
}
}
polls += 1
await deps.wait(PLUGIN_DEV_WATCH_POLL_MS, stop.signal)
}
// A check that is still rendering reports before the unload line.
await checks?.idle()
if (!loaded.added) {
emit({ type: 'unloaded', pluginKey, path: loaded.path, removed: false })
return 0
}
try {
await host.devUnload()
} catch (error) {
emit({
type: deps.isConnectionLost(error) ? 'disconnected' : 'warning',
message: `could not unload ${loaded.path}: ${errorMessage(error)}`
})
return 1
}
emit({ type: 'unloaded', pluginKey, path: loaded.path, removed: true })
return 0
} finally {
unsubscribe()
}
}