refactor(cli): group plugin and skill implementation owners (#41549)

This commit is contained in:
Neil
2026-11-12 05:47:35 -08:00
committed by GitHub
parent 3eb2765e66
commit 382c7cfcb3
92 changed files with 221 additions and 632 deletions
@@ -0,0 +1,29 @@
import { PassThrough } from 'node:stream'
import { describe, expect, it } from 'vitest'
import '../../runtime/types'
import { createTerminalConfirm } from './plugin-dev-watch-approval'
import './plugin-dev-watch-loop'
function terminal(isTTY = true) {
const input = Object.assign(new PassThrough(), { isTTY })
const output = Object.assign(new PassThrough(), { isTTY })
let printed = ''
output.on('data', (chunk: Buffer) => {
printed += chunk.toString()
})
return { input, output, printed: () => printed }
}
describe('pluginDevWatchConfirmFor', () => {
it.each([
['end of input', (input: PassThrough) => input.end()],
['Ctrl-C', (input: PassThrough) => input.write('\u0003')]
])('reads %s as no', async (_name, stop) => {
const streams = terminal()
const answer = createTerminalConfirm(streams)('Approve and load? [y/N] ')
stop(streams.input)
await expect(answer).resolves.toBe(false)
})
})
@@ -0,0 +1,128 @@
import { createInterface } from 'node:readline'
import { z } from 'zod'
import { formatPluginGrantLines } from '../plugin-grant-lines'
import { RuntimeClientError } from '../../runtime/types'
import type { DevLoadResult } from '../plugin-runtime'
/** Asks a yes/no question; false on anything but yes, end of input or Ctrl-C. */
export type PluginDevWatchConfirm = (question: string) => Promise<boolean>
const firstLoadApprovalSchema = z.object({
pluginKey: z.string(),
name: z.string(),
version: z.string(),
approvalFingerprint: z.string(),
why: z.string().optional(),
grants: z.object({
execution: z.string(),
executionDescription: z.string(),
capabilities: z.array(z.object({ description: z.string() })),
contributions: z.array(z.object({ kind: z.string(), name: z.string() }))
})
})
type FirstLoadApproval = z.infer<typeof firstLoadApprovalSchema>
function firstLoadApprovalOf(error: unknown): FirstLoadApproval | null {
// Why not `approval_stale`: it answers a fingerprint passed with --approve, which stays explicit.
if (!(error instanceof RuntimeClientError) || error.code !== 'approval_required') {
return null
}
const parsed = firstLoadApprovalSchema.safeParse(error.data)
return parsed.success ? parsed.data : null
}
export function pluginDevWatchApprovalQuestion(approval: FirstLoadApproval): string {
return [
`${approval.name} needs your approval before Orca runs it. Approving grants:`,
...formatPluginGrantLines(approval),
...(approval.why ? [approval.why] : []),
'Approve and load? [y/N] '
].join('\n')
}
/** The first dev load; with `confirm` (a person at a terminal) an approval is asked, never assumed.
* A declined or unanswered ask fails with approval_required (exit 3) and only the re-run command. */
export async function devLoadWithApproval(
devLoad: (approvalFingerprint?: string) => Promise<DevLoadResult>,
confirm: PluginDevWatchConfirm | undefined
): Promise<DevLoadResult> {
try {
return await devLoad()
} catch (error) {
const approval = confirm ? firstLoadApprovalOf(error) : null
if (!confirm || !approval) {
throw error
}
if (!(await confirm(pluginDevWatchApprovalQuestion(approval)))) {
throw declinedApprovalError(error, approval)
}
return devLoad(approval.approvalFingerprint)
}
}
/** Why trimmed: the person just read the grants; repeating them buries the re-run command. */
function declinedApprovalError(error: unknown, approval: FirstLoadApproval): RuntimeClientError {
const data = error instanceof RuntimeClientError ? error.data : undefined
const command =
typeof data === 'object' &&
data !== null &&
'command' in data &&
typeof data.command === 'string'
? data.command
: null
return new RuntimeClientError(
'approval_required',
command ? `Not approved. To approve later, run: ${command}` : 'Not approved.',
{
pluginKey: approval.pluginKey,
approvalFingerprint: approval.approvalFingerprint,
command,
nextSteps: []
}
)
}
type PromptStreams = {
input: NodeJS.ReadableStream & { isTTY?: boolean }
output: NodeJS.WritableStream & { isTTY?: boolean }
}
/** A prompt only for a person at a terminal; agents, pipes and `--json` keep the exit-3 error. */
export function pluginDevWatchConfirmFor(
json: boolean,
streams: PromptStreams = { input: process.stdin, output: process.stdout }
): PluginDevWatchConfirm | undefined {
return !json && streams.input.isTTY && streams.output.isTTY
? createTerminalConfirm(streams)
: undefined
}
/** readline works the same in Windows cmd, PowerShell and Windows Terminal as on POSIX ttys. */
export function createTerminalConfirm(streams: PromptStreams): PluginDevWatchConfirm {
return (question) =>
new Promise((resolve) => {
const rl = createInterface({ input: streams.input, output: streams.output })
let answered = false
const finish = (yes: boolean): void => {
if (answered) {
return
}
answered = true
rl.close()
resolve(yes)
}
// Why: with no SIGINT listener readline only pauses on Ctrl-C, leaving the prompt hanging.
rl.on('SIGINT', () => {
streams.output.write('\n')
finish(false)
})
rl.on('close', () => {
if (!answered) {
streams.output.write('\n')
}
finish(false)
})
rl.question(question, (answer) => finish(/^y(es)?$/i.test(answer.trim())))
})
}
@@ -0,0 +1,104 @@
import { describe, expect, it, vi } from 'vitest'
import type { PluginHostListEntry } from '../../../shared/plugins/plugin-list-entry'
import type { PluginDevWatchCheckResult } from './plugin-dev-watch-check'
import { formatPluginDevWatchEvent, type PluginDevWatchEvent } from './plugin-dev-watch-events'
import { runPluginDevWatch, type PluginDevWatchHost } from './plugin-dev-watch-loop'
const KEY = 'acme.todos'
function entry(
devChangeCount: number,
status: PluginHostListEntry['status'] = 'idle'
): PluginHostListEntry {
return {
pluginKey: KEY,
consentFingerprint: 'sha256-x',
name: 'Todos',
version: '1.0.0',
publisher: 'acme',
status,
needsReconsent: false,
isDev: true,
devChangeCount,
official: false,
bundled: false,
capabilities: [],
panels: [],
commands: [],
hasWorker: false,
restarts: 0
}
}
const passed: PluginDevWatchCheckResult = {
ok: true,
invalid: [],
panels: [
{
panel: 'todos',
entry: 'src/panel.tsx',
elements: 12,
summary: ['Heading "Tasks"'],
issues: [],
warnings: []
}
],
editors: []
}
/** Polls: 1 baseline, 2 status (unchanged), 3 logs, 4 status (one save), then Ctrl-C. */
async function watch(
check: PluginDevWatchHost['check'],
lists = [[entry(0)], [entry(1)]]
): Promise<PluginDevWatchEvent[]> {
const events: PluginDevWatchEvent[] = []
let interrupt = () => {}
let poll = 0
const host: PluginDevWatchHost = {
refreshTypes: async () => [],
devLoad: async () => ({
path: '/work/todos',
pluginKey: KEY,
added: true,
approval: 'approve-flag',
plugin: entry(0)
}),
list: async () => (lists.length > 1 ? lists.shift() : lists[0]) ?? [entry(1)],
logs: async () => ({ pluginKey: KEY, lines: [] }),
approvalNeeded: async () => null,
devUnload: async () => {},
check
}
await runPluginDevWatch({
host,
emit: (event) => events.push(event),
wait: async () => {
poll += 1
if (poll === 6) {
interrupt()
}
},
onInterrupt: (listener) => {
interrupt = listener
return () => {}
},
exitNow: () => {},
isConnectionLost: () => false
})
return events
}
describe('plugin dev watch --check', () => {
it('fails a check that renders while Orca does not run the plugin', async () => {
const pending = entry(1, 'pending')
const events = await watch(vi.fn().mockResolvedValue(passed), [[entry(0)], [pending]])
const checks = events.filter((event) => event.type === 'check')
expect(checks.map((event) => [event.ok, event.checkOk, event.pluginStatus])).toEqual([
[true, true, 'idle'],
[false, true, 'pending']
])
expect(formatPluginDevWatchEvent(checks[1]).split('\n')[0]).toBe(
'✗ check passed, but in Orca acme.todos is pending approval'
)
})
})
@@ -0,0 +1,60 @@
import { validatePluginTarget } from '../authoring/plugin-folder-validation'
import { checkPluginPanels, type PluginPanelCheck } from '../authoring/plugin-panel-check'
import { checkPluginEditors, type PluginEditorCheck } from '../authoring/plugin-editor-check'
/** `orca plugin check` for one folder, as data: validation errors, else each panel's render. */
export type PluginDevWatchCheckResult = {
ok: boolean
/** Manifest problems; panels are not rendered while there are any. */
invalid: string[]
panels: PluginPanelCheck[]
/** Each custom editor's static check. */
editors: PluginEditorCheck[]
}
export async function checkPluginDevFolder(dir: string): Promise<PluginDevWatchCheckResult> {
const report = await validatePluginTarget(dir)
if (!report.valid) {
return { ok: false, invalid: report.errors, panels: [], editors: [] }
}
const [rendered, editors] = await Promise.all([
checkPluginPanels(report.path),
checkPluginEditors(report.path)
])
// Why no tree: a watch prints one line per save; the summary says what drew.
const panels = rendered.map(({ tree: _tree, ...panel }) => panel)
const ok = [...panels, ...editors].every((check) => check.issues.length === 0)
return { ok, invalid: [], panels, editors }
}
/** Runs checks one at a time: a request while one runs queues a single rerun of the newest code. */
export function createPluginDevWatchCheckQueue(run: () => Promise<void>): {
request(): void
idle(): Promise<void>
} {
let running: Promise<void> | null = null
let again = false
const start = (): void => {
running = run().finally(() => {
running = null
if (again) {
again = false
start()
}
})
}
return {
request: () => {
if (running) {
again = true
return
}
start()
},
idle: async () => {
while (running) {
await running
}
}
}
}
@@ -0,0 +1,148 @@
import type { PluginHostStatus } from '../../../shared/plugins/plugin-list-entry'
import { formatPluginPanelCheck } from '../authoring/plugin-panel-check'
import type { PluginDevWatchCheckResult } from './plugin-dev-watch-check'
import { formatPluginEditorCheck } from '../authoring/plugin-editor-check'
import { PLUGIN_DEV_WATCH_SHOOTABLE, type PluginDevWatchShot } from './plugin-dev-watch-shot'
/** `missing`: the host lists no plugin for the folder (for example, its id changed). */
export type PluginDevWatchStatus = PluginHostStatus | 'missing'
export type PluginDevWatchApproval = { message: string; fingerprint: string; command: string }
/** One `--json` line each; `type` is the discriminant agents switch on. */
export type PluginDevWatchEvent =
| {
type: 'loaded'
pluginKey: string
path: string
added: boolean
status: PluginDevWatchStatus
error?: string
typeFiles: string[]
}
| {
type: 'log'
pluginKey: string
ts: number
level: string
line: string
/** A panel line that arrived this many times together (absent: once). */
count?: number
/** `count` more copies of a panel line printed earlier in this reload. */
repeat?: true
}
| {
type: 'reloaded'
pluginKey: string
/** File changes the host saw since the last reload. */
changes: number
status: PluginDevWatchStatus
error?: string
}
| {
type: 'status'
pluginKey: string
status: PluginDevWatchStatus
previousStatus: PluginDevWatchStatus
error?: string
}
| ({ type: 'approval'; pluginKey: string } & PluginDevWatchApproval)
/** `--check`: `orca plugin check` after the load and after each reload. `ok` also needs Orca to
* run the plugin (`pluginStatus` running, idle or restarting); `checkOk` is the check alone. */
| ({
type: 'check'
pluginKey: string
checkOk: boolean
pluginStatus: PluginDevWatchStatus
pluginError?: string
} & PluginDevWatchCheckResult)
/** `--shot`: a PNG of one panel after the load and after each reload that left it running. */
| ({ type: 'shot'; pluginKey: string } & PluginDevWatchShot)
/** `--shot`: the person switched away from the panel; once per time away, never switched back. */
| { type: 'shot_skipped'; pluginKey: string; panelId: string; reason: string }
| { type: 'warning'; message: string }
| { type: 'disconnected'; message: string }
| { type: 'unloaded'; pluginKey: string; path: string; removed: boolean }
function withError(status: PluginDevWatchStatus, error: string | undefined): string {
return error ? `${status}: ${error}` : status
}
function clockTime(ts: number): string {
const date = new Date(ts)
const pad = (value: number, width = 2) => String(value).padStart(width, '0')
return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}.${pad(date.getMilliseconds(), 3)}`
}
function pluginStatusPhrase(status: PluginDevWatchStatus, error: string | undefined): string {
const phrase =
status === 'pending' ? 'pending approval' : status === 'missing' ? 'not loaded' : status
return error ? `${phrase}: ${error}` : phrase
}
function checkHeadline(event: Extract<PluginDevWatchEvent, { type: 'check' }>): string {
if (event.ok) {
return `✓ check passed for ${event.pluginKey}`
}
if (!event.checkOk) {
return `✗ check failed for ${event.pluginKey}`
}
return `✗ check passed, but in Orca ${event.pluginKey} is ${pluginStatusPhrase(event.pluginStatus, event.pluginError)}`
}
export function formatPluginDevWatchEvent(event: PluginDevWatchEvent): string {
switch (event.type) {
case 'loaded':
return [
`${event.added ? 'Loaded' : 'Watching'} ${event.pluginKey} from ${event.path} (${withError(event.status, event.error)}).`,
...event.typeFiles.map((file) => `Refreshed ${file}`),
'Watching for changes and logs; Ctrl-C to stop.'
].join('\n')
case 'log': {
const times = event.repeat
? ` (×${event.count ?? 1} more)`
: event.count && event.count > 1
? ` ×${event.count}`
: ''
return `${clockTime(event.ts)} ${event.level.padEnd(5)} ${event.line}${times}`
}
case 'reloaded': {
const changes = event.changes === 1 ? '1 file changed' : `${event.changes} files changed`
return `↻ reloaded ${event.pluginKey} (${changes}): ${withError(event.status, event.error)}`
}
case 'status':
return `${event.pluginKey} is now ${withError(event.status, event.error)} (was ${event.previousStatus})`
case 'approval':
return `${event.pluginKey} needs approval: ${event.message}\n To approve, run: ${event.command}`
case 'check':
return [
checkHeadline(event),
...(!event.ok && !event.checkOk && !PLUGIN_DEV_WATCH_SHOOTABLE.has(event.pluginStatus)
? [` in Orca: ${pluginStatusPhrase(event.pluginStatus, event.pluginError)}`]
: []),
...event.invalid.map((error) => ` invalid: ${error}`),
...event.panels.flatMap(formatPluginPanelCheck).map((line) => ` ${line}`),
...event.editors.flatMap(formatPluginEditorCheck).map((line) => ` ${line}`)
].join('\n')
case 'shot':
return [
`shot ${event.path} (${event.width}x${event.height})${event.settled ? '' : ', not finished drawing'}`,
...(event.pendingRequests
? [
` note: ${event.pendingRequests} host call(s) were still unanswered; the panel may show its loading state`
]
: []),
...event.errors.map((error) => ` error: ${error}`)
].join('\n')
case 'shot_skipped':
return `shot skipped: ${event.reason}, so ${event.panelId} is not on screen; open it again to resume`
case 'warning':
return `warning: ${event.message}`
case 'disconnected':
return `Lost the connection to Orca: ${event.message}`
case 'unloaded':
return event.removed
? `Unloaded ${event.pluginKey} (${event.path}).`
: `Left ${event.pluginKey} loaded: it was loaded before this session.`
}
}
@@ -0,0 +1,204 @@
import { describe, expect, it, vi } from 'vitest'
import type { PluginHostListEntry } from '../../../shared/plugins/plugin-list-entry'
import type { LogsResult } from '../plugin-runtime'
import type { PluginDevWatchEvent } from './plugin-dev-watch-events'
import { formatPluginDevWatchEvent } from './plugin-dev-watch-events'
import { runPluginDevWatch, type PluginDevWatchHost } from './plugin-dev-watch-loop'
const KEY = 'acme.notes'
const PATH = '/work/notes'
function entry(overrides: Partial<PluginHostListEntry> = {}): PluginHostListEntry {
return {
pluginKey: KEY,
consentFingerprint: 'sha256-x',
name: 'Notes',
version: '1.0.0',
publisher: 'acme',
status: 'running',
needsReconsent: false,
isDev: true,
devChangeCount: 0,
official: false,
bundled: false,
capabilities: [],
panels: [],
commands: [],
hasWorker: true,
restarts: 0,
...overrides
}
}
class LostError extends Error {}
/** A scripted host: each poll (one wait) advances to the next step. */
function harness(options: {
added?: boolean
logs?: LogsResult[]
lists?: PluginHostListEntry[][]
failAt?: { poll: number; error: Error }
stopAfterPolls?: number
approvalNeeded?: PluginDevWatchHost['approvalNeeded']
devUnload?: PluginDevWatchHost['devUnload']
}) {
const events: PluginDevWatchEvent[] = []
let interrupt: () => void = () => {}
let poll = 0
const logs = options.logs ?? []
const lists = options.lists ?? []
const logCalls: (string | undefined)[] = []
const host: PluginDevWatchHost = {
refreshTypes: vi.fn(async () => ['.orca/types/orca/index.d.ts']),
devLoad: vi.fn(async () => ({
path: PATH,
pluginKey: KEY,
added: options.added ?? true,
approval: 'approve-flag' as const,
plugin: entry()
})),
list: vi.fn(async () => {
if (options.failAt?.poll === poll) {
throw options.failAt.error
}
return lists.shift() ?? [entry()]
}),
logs: vi.fn(async (_key: string, after: string | undefined) => {
logCalls.push(after)
if (options.failAt?.poll === poll) {
throw options.failAt.error
}
return logs.shift() ?? { pluginKey: KEY, lines: [] }
}),
approvalNeeded: options.approvalNeeded ?? vi.fn(async () => null),
devUnload: options.devUnload ?? vi.fn(async () => {})
}
const unsubscribe = vi.fn()
const exitNow = vi.fn()
const run = runPluginDevWatch({
host,
emit: (event) => events.push(event),
wait: async () => {
poll += 1
if (poll === (options.stopAfterPolls ?? 4)) {
interrupt()
}
},
onInterrupt: (listener) => {
interrupt = listener
return unsubscribe
},
exitNow,
isConnectionLost: (error) => error instanceof LostError
})
return { run, events, host, logCalls, unsubscribe, exitNow, interrupt: () => interrupt() }
}
const line = (ts: number, text: string, level = 'info') => ({ ts, level, line: text })
describe('runPluginDevWatch', () => {
it('loads, skips old lines, follows the host cursor, and unloads on Ctrl-C', async () => {
const { run, events, host, logCalls, unsubscribe } = harness({
logs: [
{ pluginKey: KEY, lines: [line(1, 'before the session')], cursor: 'n:1' },
{ pluginKey: KEY, lines: [line(2, '[frame] panel.tsx:3 boom', 'error')], cursor: 'n:2' },
{ pluginKey: KEY, lines: [], cursor: 'n:2' }
]
})
await expect(run).resolves.toBe(0)
expect(logCalls.slice(0, 3)).toEqual([undefined, 'n:1', 'n:2'])
expect(events.map((event) => event.type)).toEqual(['loaded', 'log', 'unloaded'])
expect(events[1]).toMatchObject({ line: '[frame] panel.tsx:3 boom', level: 'error' })
expect(events.at(-1)).toEqual({ type: 'unloaded', pluginKey: KEY, path: PATH, removed: true })
expect(host.devUnload).toHaveBeenCalledTimes(1)
expect(unsubscribe).toHaveBeenCalled()
})
it('de-duplicates whole-ring replies from hosts without the cursor', async () => {
const { run, events } = harness({
logs: [
{ pluginKey: KEY, lines: [line(5, 'a')] },
{ pluginKey: KEY, lines: [line(5, 'a'), line(5, 'b')] },
{ pluginKey: KEY, lines: [line(5, 'a'), line(5, 'b'), line(6, 'c')] }
]
})
await run
expect(events.filter((event) => event.type === 'log').map((event) => event.line)).toEqual([
'b',
'c'
])
})
it('reports a reload with the new status, and a later status change', async () => {
const { run, events } = harness({
stopAfterPolls: 6,
lists: [
[entry({ devChangeCount: 2, status: 'errored', error: 'SyntaxError in main.ts:4' })],
[entry({ devChangeCount: 2, status: 'running' })]
]
})
await run
const reload = events.find((event) => event.type === 'reloaded')
expect(reload).toEqual({
type: 'reloaded',
pluginKey: KEY,
changes: 2,
status: 'errored',
error: 'SyntaxError in main.ts:4'
})
expect(reload && formatPluginDevWatchEvent(reload)).toBe(
'↻ reloaded acme.notes (2 files changed): errored: SyntaxError in main.ts:4'
)
expect(events.find((event) => event.type === 'status')).toMatchObject({
status: 'running',
previousStatus: 'errored'
})
})
it('prints a reload before the lines its new code logged in the same poll', async () => {
const { run, events } = harness({
logs: [
{ pluginKey: KEY, lines: [], cursor: 'n:0' },
{ pluginKey: KEY, lines: [line(2, 'new code started')], cursor: 'n:1' }
],
lists: [[entry({ devChangeCount: 1 })]]
})
await run
expect(events.map((event) => event.type)).toEqual(['loaded', 'reloaded', 'log', 'unloaded'])
})
it('follows a manifest that stopped parsing to the one new invalid dev entry', async () => {
const stray = entry({
pluginKey: 'invalid-development-plugin-2',
status: 'invalid',
error: 'invalid manifest: id',
devChangeCount: 1
})
const { run, events } = harness({
lists: [[entry(), entry({ pluginKey: 'acme.other', isDev: false })], [stray]]
})
await run
expect(events.find((event) => event.type === 'reloaded')).toMatchObject({
status: 'invalid',
error: 'invalid manifest: id'
})
})
it('exits 1 without unloading when the host connection drops', async () => {
const { run, events, host } = harness({
failAt: { poll: 1, error: new LostError('connect ECONNREFUSED') }
})
await expect(run).resolves.toBe(1)
expect(events.at(-1)).toEqual({ type: 'disconnected', message: 'connect ECONNREFUSED' })
expect(host.devUnload).not.toHaveBeenCalled()
})
it('reports a host-side poll failure once and keeps watching', async () => {
const { run, events } = harness({
stopAfterPolls: 6,
failAt: { poll: 2, error: new Error('Plugin service is not available') }
})
await expect(run).resolves.toBe(0)
expect(events.filter((event) => event.type === 'warning')).toHaveLength(1)
})
})
@@ -0,0 +1,284 @@
import type { DevLoadResult, LogsResult } from '../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 { devLoadWithApproval, type PluginDevWatchConfirm } from './plugin-dev-watch-approval'
import { PluginFrameLogDedupe, type PluginDevWatchLogLine } from './plugin-frame-log-dedupe'
import {
createPluginDevWatchCheckQueue,
type PluginDevWatchCheckResult
} from './plugin-dev-watch-check'
import {
createPluginDevWatchShooter,
PLUGIN_DEV_WATCH_SHOOTABLE,
type PluginDevWatchShotHost
} from './plugin-dev-watch-shot'
/** What the loop asks of the Orca host; the handler binds it to RPC for one folder. */
export type PluginDevWatchHost = {
refreshTypes(): Promise<string[]>
/** `approvalFingerprint` overrides `--approve` once the person approved at the prompt. */
devLoad(approvalFingerprint?: string): 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>
/** `--shot` only: a PNG of one panel after each good reload, while it stays on screen. */
shot?: PluginDevWatchShotHost
}
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
/** Only for a person at a terminal without `--json`: asks to approve a first load that needs it. */
confirm?: PluginDevWatchConfirm
}
// 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
}
/** A check that renders still fails while Orca itself does not run the plugin. */
function checkEvent(
pluginKey: string,
result: PluginDevWatchCheckResult,
snapshot: Snapshot
): PluginDevWatchEvent {
return {
type: 'check',
pluginKey,
...result,
ok: result.ok && PLUGIN_DEV_WATCH_SHOOTABLE.has(snapshot.status),
checkOk: result.ok,
pluginStatus: snapshot.status,
...(snapshot.error ? { pluginError: snapshot.error } : {})
}
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error)
}
/** `--shot`: picks the panel once; an unknown `--shot-panel` unloads what this run loaded and fails. */
async function startShooter(
host: PluginDevWatchHost,
loaded: DevLoadResult,
emit: (event: PluginDevWatchEvent) => void
): Promise<(() => Promise<void>) | null> {
if (!host.shot) {
return null
}
let panelId: string | null
try {
panelId = host.shot.panelOf(loaded.plugin)
} catch (error) {
if (loaded.added) {
await host.devUnload().catch(() => undefined)
}
throw error
}
if (panelId === null) {
emit({ type: 'warning', message: `${loaded.pluginKey} has no panel for --shot to capture` })
return null
}
return createPluginDevWatchShooter(host.shot, loaded.pluginKey, panelId, emit)
}
/** 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`) unless
* the person approves it at the `confirm` prompt. */
export async function runPluginDevWatch(deps: PluginDevWatchDeps): Promise<number> {
const { host, emit } = deps
const typeFiles = await host.refreshTypes()
const loaded = await devLoadWithApproval((fingerprint) => host.devLoad(fingerprint), deps.confirm)
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 shoot = await startShooter(host, loaded, emit)
// Check, then shot: one at a time, and saves during a run coalesce into one more.
const afterLoad =
runCheck || shoot
? createPluginDevWatchCheckQueue(async () => {
if (runCheck) {
try {
emit(checkEvent(pluginKey, await runCheck(), snapshot))
} catch (error) {
emit({ type: 'warning', message: `check could not run: ${errorMessage(error)}` })
}
}
if (shoot && PLUGIN_DEV_WATCH_SHOOTABLE.has(snapshot.status)) {
await shoot()
}
})
: null
afterLoad?.request()
const follower = new PluginLogFollower()
const dedupe = new PluginFrameLogDedupe()
const emitLogs = (lines: readonly PluginDevWatchLogLine[]): void => {
for (const line of lines) {
emit({ type: 'log', pluginKey, ...line })
}
}
let otherKeys: ReadonlySet<string> | null = null
let lastWarning: string | null = null
const pollLogs = async (): Promise<void> => {
emitLogs(dedupe.take(follower.take(await host.logs(pluginKey, follower.cursor))))
}
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) {
emitLogs(dedupe.flush())
emit({ type: 'reloaded', pluginKey, changes, status: next.status, ...error })
} 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 (changes > 0) {
afterLoad?.request()
}
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 {
// Status first, so a reload's `reloaded` line precedes the lines its new code logs.
if (polls % LIST_EVERY_POLLS === 0) {
await pollStatus()
}
await pollLogs()
}
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 or shot that is still running reports before the unload line.
await afterLoad?.idle()
emitLogs(dedupe.flush())
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()
}
}
@@ -0,0 +1,41 @@
/** Ctrl-C everywhere; Ctrl-Break on Windows; a closed terminal or `kill` on POSIX. */
function stopSignals(platform: NodeJS.Platform): NodeJS.Signals[] {
return platform === 'win32' ? ['SIGINT', 'SIGBREAK'] : ['SIGINT', 'SIGTERM', 'SIGHUP']
}
type SignalTarget = {
platform: NodeJS.Platform
on(signal: NodeJS.Signals, listener: () => void): unknown
off(signal: NodeJS.Signals, listener: () => void): unknown
}
export function onPluginDevWatchInterrupt(
listener: () => void,
target: SignalTarget = process
): () => void {
const signals = stopSignals(target.platform)
for (const signal of signals) {
target.on(signal, listener)
}
return () => {
for (const signal of signals) {
target.off(signal, listener)
}
}
}
export function waitUnlessAborted(ms: number, signal: AbortSignal): Promise<void> {
return new Promise((resolve) => {
if (signal.aborted) {
resolve()
return
}
const done = (): void => {
clearTimeout(timer)
signal.removeEventListener('abort', done)
resolve()
}
const timer = setTimeout(done, ms)
signal.addEventListener('abort', done, { once: true })
})
}
@@ -0,0 +1,149 @@
import { describe, expect, it, vi } from 'vitest'
import type {
PluginHostListEntry,
PluginHostStatus
} from '../../../shared/plugins/plugin-list-entry'
import { formatPluginDevWatchEvent, type PluginDevWatchEvent } from './plugin-dev-watch-events'
import { runPluginDevWatch, type PluginDevWatchHost } from './plugin-dev-watch-loop'
import {
pluginDevWatchShotPanel,
type PluginDevWatchShot,
type PluginDevWatchShotHost
} from './plugin-dev-watch-shot'
const KEY = 'acme.todos'
function entry(devChangeCount: number, status: PluginHostStatus = 'idle'): PluginHostListEntry {
return {
pluginKey: KEY,
consentFingerprint: 'sha256-x',
name: 'Todos',
version: '1.0.0',
publisher: 'acme',
status,
needsReconsent: false,
isDev: true,
devChangeCount,
official: false,
bundled: false,
capabilities: [],
panels: [
{ id: 'todos', title: 'Todos', tabKey: `plugin:${KEY}/todos` },
{ id: 'stats', title: 'Stats', tabKey: `plugin:${KEY}/stats` }
],
commands: [],
hasWorker: false,
restarts: 0
}
}
const SHOT: PluginDevWatchShot = {
panelId: 'todos',
path: '/work/shots/acme.todos-todos.png',
width: 360,
height: 700,
settled: true,
errors: []
}
type Take = PluginDevWatchShotHost['take']
function shotHost(take: Take, requested?: string) {
const open = vi.fn<PluginDevWatchShotHost['open']>(async () => {})
const host: PluginDevWatchShotHost = {
panelOf: (loaded) => pluginDevWatchShotPanel(loaded, requested),
open,
take: vi.fn(take)
}
return { host, open, take: host.take }
}
/** The load, then one status poll per entry in `saves` (each one save later), then Ctrl-C. */
async function watch(
host: Partial<Pick<PluginDevWatchHost, 'check' | 'shot' | 'devUnload'>>,
saves: PluginHostListEntry[] = [entry(1)]
): Promise<PluginDevWatchEvent[]> {
const events: PluginDevWatchEvent[] = []
const lists = [[entry(0)], ...saves.map((save) => [save])]
let interrupt = () => {}
let poll = 0
await runPluginDevWatch({
host: {
refreshTypes: async () => [],
devLoad: async () => ({
path: '/work/todos',
pluginKey: KEY,
added: true,
approval: 'approve-flag',
plugin: entry(0)
}),
list: async () => lists.shift() ?? [saves.at(-1) ?? entry(0)],
logs: async () => ({ pluginKey: KEY, lines: [] }),
approvalNeeded: async () => null,
devUnload: async () => {},
...host
},
emit: (event) => events.push(event),
wait: async () => {
poll += 1
if (poll === 2 * (saves.length + 1)) {
interrupt()
}
},
onInterrupt: (listener) => {
interrupt = listener
return () => {}
},
exitNow: () => {},
isConnectionLost: () => false
})
return events
}
const ofType = <T extends PluginDevWatchEvent['type']>(events: PluginDevWatchEvent[], type: T) =>
events.filter((event): event is Extract<PluginDevWatchEvent, { type: T }> => event.type === type)
describe('plugin dev watch --shot', () => {
it('shoots --shot-panel and fails at start, unloading, on an unknown id', async () => {
const { host, open } = shotHost(async () => ({ ...SHOT, panelId: 'stats' }), 'stats')
await watch({ shot: host })
expect(open).toHaveBeenCalledWith(KEY, 'stats')
const devUnload = vi.fn(async () => {})
await expect(
watch({ shot: shotHost(async () => SHOT, 'nope').host, devUnload })
).rejects.toMatchObject({
code: 'invalid_argument',
message: '--shot-panel: acme.todos has no panel nope; its panels: todos, stats.'
})
expect(devUnload).toHaveBeenCalledTimes(1)
})
it('skips while away, says so once per time away, and resumes when back', async () => {
const outcomes: Awaited<ReturnType<Take>>[] = [
SHOT,
{ notShown: 'the right sidebar shows another tab' },
{ notShown: 'the right sidebar shows another tab' },
SHOT,
{ notShown: 'the right sidebar is closed' }
]
const { host, open } = shotHost(async () => outcomes.shift() ?? SHOT)
const events = await watch({ shot: host }, [entry(1), entry(2), entry(3), entry(4)])
expect(open).toHaveBeenCalledTimes(1)
expect(
events
.filter((event) => event.type === 'shot' || event.type === 'shot_skipped')
.map((event) => event.type)
).toEqual(['shot', 'shot_skipped', 'shot', 'shot_skipped'])
const skipped = ofType(events, 'shot_skipped')
expect(skipped[0]).toEqual({
type: 'shot_skipped',
pluginKey: KEY,
panelId: 'todos',
reason: 'the right sidebar shows another tab'
})
expect(formatPluginDevWatchEvent(skipped[1]!)).toBe(
'shot skipped: the right sidebar is closed, so todos is not on screen; open it again to resume'
)
})
})
@@ -0,0 +1,113 @@
import type { PluginHostListEntry } from '../../../shared/plugins/plugin-list-entry'
import { RuntimeClientError, RuntimeRpcFailureError } from '../../runtime/types'
import type { PluginDevWatchEvent } from './plugin-dev-watch-events'
/** One `--shot` PNG written after a load or reload. */
export type PluginDevWatchShot = {
panelId: string
path: string
width: number
height: number
/** False when the panel had not finished drawing by the host's timeout. */
settled: boolean
errors: string[]
/** Host calls still unanswered at the capture; absent on hosts that predate it. */
pendingRequests?: number
}
/** What `--shot` asks of the Orca host; the handler binds it to RPC. */
export type PluginDevWatchShotHost = {
/** `--shot-panel`, else the plugin's first panel; null when it has none. Throws on an unknown id. */
panelOf(entry: PluginHostListEntry | null): string | null
/** Shows the panel in the right sidebar; called once per session. */
open(pluginKey: string, panelId: string): Promise<void>
/** Captures it only while it is the open right-sidebar tab. */
take(pluginKey: string, panelId: string): Promise<PluginDevWatchShot | { notShown: string }>
}
/** Statuses whose panels Orca draws; an errored or invalid reload has nothing new to show. */
export const PLUGIN_DEV_WATCH_SHOOTABLE = new Set(['running', 'idle', 'restarting'])
/** A host that cannot capture now never will this session: too old, or no desktop window. */
export function isLastingShotFailure(error: unknown): boolean {
if (error instanceof RuntimeRpcFailureError) {
return error.response.error.message.includes('only available in the Orca desktop app')
}
return error instanceof RuntimeClientError && error.code === 'runtime_unsupported'
}
/** `--shot-panel` must name one of the plugin's panels; checked once, at start. */
export function pluginDevWatchShotPanel(
entry: PluginHostListEntry | null,
requested: string | undefined
): string | null {
const ids = entry?.panels.map((panel) => panel.id) ?? []
if (requested === undefined) {
return ids[0] ?? null
}
if (entry && !ids.includes(requested)) {
throw new RuntimeClientError(
'invalid_argument',
ids.length === 0
? `--shot-panel: ${entry.pluginKey} has no panels.`
: `--shot-panel: ${entry.pluginKey} has no panel ${requested}; its panels: ${ids.join(', ')}.`
)
}
return requested
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error)
}
/**
* Opens the panel once, then captures it after each good reload while it stays on screen. Once
* the person switches away it never switches back: it skips, saying so once per time away.
*/
export function createPluginDevWatchShooter(
host: PluginDevWatchShotHost,
pluginKey: string,
panelId: string,
emit: (event: PluginDevWatchEvent) => void
): () => Promise<void> {
let opened = false
let away = false
let off = false
const warn = (what: string, error: unknown): void => {
off = isLastingShotFailure(error)
emit({
type: 'warning',
message: `${what}${off ? ', so --shot is off' : ''}: ${errorMessage(error)}`
})
}
return async () => {
if (off) {
return
}
if (!opened) {
opened = true
try {
await host.open(pluginKey, panelId)
} catch (error) {
warn(`could not show ${panelId} for --shot`, error)
if (off) {
return
}
}
}
try {
const outcome = await host.take(pluginKey, panelId)
if ('notShown' in outcome) {
if (!away) {
away = true
emit({ type: 'shot_skipped', pluginKey, panelId, reason: outcome.notShown })
}
return
}
away = false
emit({ type: 'shot', pluginKey, ...outcome })
} catch (error) {
warn('shot could not run', error)
}
}
}
@@ -0,0 +1,164 @@
import { mkdtemp, readFile, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { describe, expect, it, vi } from 'vitest'
import { COMMAND_SPECS } from '../../specs/index'
import { findCommandSpec, normalizeCommandPositionals, parseArgs } from '../../args'
import { specPaths } from '../../command-spec'
import type { HandlerContext } from '../../dispatch'
import { reportCliError } from '../../cli-error'
import type { RuntimeClient } from '../../runtime/client'
import { RuntimeClientError, RuntimeRpcFailureError } from '../../runtime/types'
import { bindPluginDevWatchHost, PluginHostUnreachableError } from './plugin-dev-watch'
function context(call: ReturnType<typeof vi.fn>, rawArgs: string[] = []): HandlerContext {
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the watch host only calls client.call and reads isRemote.
const client = { call, isRemote: true } as unknown as RuntimeClient
return { flags: new Map(), client, cwd: '/work', json: false, rawArgs }
}
function rpcFailure(code: string, data?: unknown): RuntimeRpcFailureError {
return new RuntimeRpcFailureError({
id: 'req',
ok: false,
error: { code, message: `${code} message`, data },
_meta: { runtimeId: 'runtime_local' }
})
}
function parse(argv: string[]) {
const paths = COMMAND_SPECS.flatMap((spec) => specPaths(spec))
return normalizeCommandPositionals(COMMAND_SPECS, parseArgs(argv, paths, COMMAND_SPECS))
}
describe('orca plugin dev watch', () => {
it('suggests an approval command that dev reload accepts, without watch-only flags', async () => {
const rawArgs = [
'plugin',
'dev',
'watch',
'--check',
'/work/notes',
'--shot',
'./shots',
'--shot-panel=stats',
'--approve',
'ap1-old',
'--json',
'--environment',
'box'
]
const call = vi
.fn()
.mockRejectedValue(rpcFailure('approval_required', { approvalFingerprint: 'ap1-new' }))
const approval = await bindPluginDevWatchHost(
context(call, rawArgs),
'/work/notes'
).approvalNeeded()
const argv = approval?.command.split(' ').slice(1) ?? []
const parsed = parse(argv)
expect(parsed.commandPath).toEqual(['plugin', 'dev', 'reload'])
const spec = findCommandSpec(COMMAND_SPECS, parsed.commandPath)
expect([...parsed.flags.keys()].filter((flag) => !spec?.allowedFlags.includes(flag))).toEqual(
[]
)
expect(Object.fromEntries(parsed.flags)).toEqual({
dir: '/work/notes',
approve: 'ap1-new',
json: true,
environment: 'box'
})
})
it('treats a transport failure as a lost host but a host error reply as a reply', async () => {
const call = vi
.fn()
.mockRejectedValueOnce(new RuntimeClientError('runtime_unavailable', 'Orca is not running'))
.mockRejectedValueOnce(rpcFailure('internal_error'))
const host = bindPluginDevWatchHost(context(call), '/work/notes')
await expect(host.list()).rejects.toBeInstanceOf(PluginHostUnreachableError)
const reply = await host.list().catch((error: unknown) => error)
expect(reply).not.toBeInstanceOf(PluginHostUnreachableError)
expect(reply).toMatchObject({ code: 'internal_error' })
})
})
describe('plugin dev watch --json errors', () => {
it('prints a failed first load as one JSON line, unlike other commands', () => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
try {
const error = new RuntimeClientError('approval_required', 'acme.notes needs approval')
reportCliError(error, true, { commandPath: ['plugin', 'dev', 'watch'] })
reportCliError(error, true, { commandPath: ['plugin', 'dev', 'load'] })
const [watchLine, loadOutput] = log.mock.calls.map(([text]) => String(text))
expect(watchLine).not.toContain('\n')
expect(JSON.parse(watchLine)).toMatchObject({
ok: false,
error: { code: 'approval_required' }
})
expect(loadOutput).toContain('\n')
} finally {
log.mockRestore()
}
})
})
describe('plugin dev watch --check', () => {
it('needs a local folder, since it renders the plugin on this machine', () => {
const remote = context(vi.fn())
remote.flags.set('check', true)
expect(() => bindPluginDevWatchHost(remote, '/work/notes')).toThrow(/needs a local folder/)
expect(bindPluginDevWatchHost(context(vi.fn()), '/work/notes').check).toBeUndefined()
})
})
describe('plugin dev watch --shot', () => {
it('opens once by RPC, then shoots only while shown, also from a remote host', async () => {
const dir = await mkdtemp(join(tmpdir(), 'orca-watch-shot-'))
try {
const png = Buffer.from('png').toString('base64')
const replies = [
{
pluginKey: 'acme.notes',
panelId: 'a',
png,
width: 300,
height: 500,
colorScheme: 'dark',
themeApplied: false,
settled: true,
errors: [],
pendingRequests: 1
},
{
pluginKey: 'acme.notes',
panelId: 'a',
title: 'A',
notShown: 'the right sidebar is closed'
}
]
const call = vi.fn(async (method: string, _params?: unknown) => ({
result: method === 'plugins.open' ? { kind: 'panel' } : replies.shift()
}))
const ctx = context(call)
ctx.flags.set('shot', dir)
const shot = bindPluginDevWatchHost(ctx, '/work/notes').shot
await shot?.open('acme.notes', 'a')
await expect(shot?.take('acme.notes', 'a')).resolves.toMatchObject({
path: join(dir, 'acme.notes-a.png'),
pendingRequests: 1
})
await expect(shot?.take('acme.notes', 'a')).resolves.toEqual({
notShown: 'the right sidebar is closed'
})
expect(await readFile(join(dir, 'acme.notes-a.png'), 'utf8')).toBe('png')
expect(call.mock.calls.map(([method, params]) => [method, params])).toEqual([
['plugins.open', { pluginKey: 'acme.notes', panelId: 'a' }],
['plugins.shot', { pluginKey: 'acme.notes', panelId: 'a', ifShown: true }],
['plugins.shot', { pluginKey: 'acme.notes', panelId: 'a', ifShown: true }]
])
} finally {
await rm(dir, { recursive: true, force: true })
}
})
})
@@ -0,0 +1,179 @@
import type { CommandHandler, HandlerContext } from '../../dispatch'
import { requirePluginPathArg } from '../plugin-cli-output'
import { formatPluginDevWatchEvent, type PluginDevWatchApproval } from './plugin-dev-watch-events'
import { runPluginDevWatch, type PluginDevWatchHost } from './plugin-dev-watch-loop'
import { onPluginDevWatchInterrupt, waitUnlessAborted } from './plugin-dev-watch-process'
import { RuntimeClientError, RuntimeRpcFailureError } from '../../runtime/types'
import { writeStdoutLine } from '../../stdout-line'
import type { PluginHostListEntry } from '../../../shared/plugins/plugin-list-entry'
import { CLI_BOOLEAN_FLAGS } from '../../../shared/cli-argument-boundary'
import { checkPluginDevFolder } from './plugin-dev-watch-check'
import { pluginDevWatchConfirmFor } from './plugin-dev-watch-approval'
import { pluginDevWatchShotPanel, type PluginDevWatchShotHost } from './plugin-dev-watch-shot'
import {
defaultPluginShotPath,
resolveLocalShotPath,
takePluginShotIfShown
} from '../view/plugin-view'
import {
callPlugins,
refreshDevTypes,
resolveHostPluginPath,
translatePluginRpcError,
type DevLoadResult,
type LogsResult
} from '../plugin-runtime'
/** The host did not answer: Orca quit, or the network to a remote server dropped. */
export class PluginHostUnreachableError extends Error {}
// Why: `dev reload` rejects watch-only flags; the old `--approve` is replaced by the new one.
const WATCH_ONLY_FLAGS = new Set(['check', 'shot', 'shot-panel', 'approve'])
/** `orca … plugin dev watch <dir>` → `… plugin dev reload <dir>`, so approving keeps this session. */
export function devReloadArgs(rawArgs: readonly string[]): string[] {
const watch = rawArgs.findIndex((arg, index) => arg === 'watch' && rawArgs[index - 1] === 'dev')
const kept: string[] = []
for (let index = 0; index < rawArgs.length; index += 1) {
const arg = rawArgs[index]
const name = arg.startsWith('--') ? arg.slice(2).split('=')[0] : null
if (name === null || !WATCH_ONLY_FLAGS.has(name)) {
kept.push(index === watch ? 'reload' : arg)
continue
}
// Same value rule as parseArgs: a non-boolean flag takes the next token unless it is a flag.
const next = rawArgs[index + 1]
if (
!arg.includes('=') &&
!CLI_BOOLEAN_FLAGS.has(name) &&
next !== undefined &&
!next.startsWith('--')
) {
index += 1
}
}
return kept
}
function approvalOf(error: unknown): PluginDevWatchApproval | null {
if (!(error instanceof RuntimeClientError) || typeof error.data !== 'object' || !error.data) {
return null
}
const data = error.data
const fingerprint =
'approvalFingerprint' in data && typeof data.approvalFingerprint === 'string'
? data.approvalFingerprint
: null
const command = 'command' in data && typeof data.command === 'string' ? data.command : null
return fingerprint && command ? { message: error.message, fingerprint, command } : null
}
/** Why classify before translating: any reply, even an error, proves the host is still there. */
async function pollHost<T>(ctx: HandlerContext, method: string, params?: unknown): Promise<T> {
try {
return (await ctx.client.call<T>(method, params)).result
} catch (error) {
if (error instanceof RuntimeRpcFailureError) {
throw translatePluginRpcError(ctx, method, error)
}
throw new PluginHostUnreachableError(error instanceof Error ? error.message : String(error))
}
}
function bindShotHost(
ctx: HandlerContext,
shotDir: string,
shotPanel: string | boolean | undefined
): PluginDevWatchShotHost {
return {
panelOf: (entry) =>
pluginDevWatchShotPanel(entry, typeof shotPanel === 'string' ? shotPanel : undefined),
open: async (pluginKey, panelId) => {
await callPlugins(ctx, 'plugins.open', { pluginKey, panelId })
},
take: async (pluginKey, panelId) => {
const shot = await takePluginShotIfShown(ctx, {
pluginKey,
panelId,
outFor: (id) => defaultPluginShotPath(shotDir, pluginKey, id)
})
if ('notShown' in shot) {
return { notShown: shot.notShown }
}
const { path: file, width, height, settled, errors, pendingRequests } = shot
return {
panelId,
path: file,
width,
height,
settled,
errors,
...(pendingRequests === undefined ? {} : { pendingRequests })
}
}
}
}
export function bindPluginDevWatchHost(ctx: HandlerContext, path: string): PluginDevWatchHost {
const approve = ctx.flags.get('approve')
const check = ctx.flags.get('check') === true
// Why local only: the check renders the folder's code on this machine, not on the Orca host.
if (check && ctx.client.isRemote) {
throw new RuntimeClientError(
'invalid_argument',
'--check renders the plugin on this machine, so it needs a local folder; drop --environment or --check.'
)
}
const shotFlag = ctx.flags.get('shot')
const shotDir = typeof shotFlag === 'string' ? resolveLocalShotPath(ctx, shotFlag) : null
const shotPanel = ctx.flags.get('shot-panel')
if (shotPanel !== undefined && shotDir === null) {
throw new RuntimeClientError('invalid_argument', '--shot-panel needs --shot <out-dir>.')
}
return {
...(check ? { check: () => checkPluginDevFolder(path) } : {}),
...(shotDir ? { shot: bindShotHost(ctx, shotDir, shotPanel) } : {}),
refreshTypes: () => refreshDevTypes(ctx, path),
devLoad: (approvalFingerprint) =>
callPlugins<DevLoadResult>(ctx, 'plugins.devLoad', {
path,
approvalFingerprint:
approvalFingerprint ?? (typeof approve === 'string' ? approve : undefined)
}),
list: () => pollHost<PluginHostListEntry[]>(ctx, 'plugins.list'),
logs: (pluginKey, after) =>
pollHost<LogsResult>(ctx, 'plugins.getLogs', { pluginKey, ...(after ? { after } : {}) }),
approvalNeeded: async () => {
const reloadCtx = { ...ctx, rawArgs: devReloadArgs(ctx.rawArgs ?? []) }
try {
await pollHost(reloadCtx, 'plugins.devLoad', { path })
return null
} catch (error) {
const approval = approvalOf(error)
if (approval) {
return approval
}
throw error
}
},
devUnload: async () => {
await pollHost(ctx, 'plugins.devUnload', { path })
}
}
}
export const PLUGIN_DEV_WATCH_HANDLERS: Record<string, CommandHandler> = {
'plugin dev watch': async (ctx) => {
const path = resolveHostPluginPath(ctx, requirePluginPathArg(ctx, 'dir'))
process.exitCode = await runPluginDevWatch({
host: bindPluginDevWatchHost(ctx, path),
emit: (event) =>
writeStdoutLine(ctx.json ? JSON.stringify(event) : formatPluginDevWatchEvent(event)),
wait: waitUnlessAborted,
onInterrupt: onPluginDevWatchInterrupt,
exitNow: (code) => process.exit(code),
isConnectionLost: (error) => error instanceof PluginHostUnreachableError,
confirm: pluginDevWatchConfirmFor(ctx.json)
})
}
}
@@ -0,0 +1,22 @@
import { describe, expect, it } from 'vitest'
import { PluginFrameLogDedupe } from './plugin-frame-log-dedupe'
const line = (ts: number, text: string, level = 'warn') => ({ ts, level, line: text })
const KEY_WARNING = '[frame] Each child in a list should have a unique "key"'
describe('PluginFrameLogDedupe', () => {
it('prints a repeated panel line once per reload with its count, then the later copies', () => {
const dedupe = new PluginFrameLogDedupe()
expect(
dedupe.take([line(1, KEY_WARNING), line(2, 'worker tick', 'info'), line(3, KEY_WARNING)])
).toEqual([{ ...line(1, KEY_WARNING), count: 2 }, line(2, 'worker tick', 'info')])
// Worker lines are never folded; the panel line already printed this reload is only counted.
expect(
dedupe.take([line(4, KEY_WARNING), line(5, 'worker tick', 'info'), line(6, KEY_WARNING)])
).toEqual([line(5, 'worker tick', 'info')])
expect(dedupe.flush()).toEqual([{ ...line(6, KEY_WARNING), count: 2, repeat: true }])
// A new reload prints it again.
expect(dedupe.take([line(7, KEY_WARNING)])).toEqual([line(7, KEY_WARNING)])
expect(dedupe.flush()).toEqual([])
})
})
@@ -0,0 +1,63 @@
import type { PluginLogLine } from './plugin-log-follower'
/** A log line as dev watch prints it: `count` identical lines, or `repeat`s of one printed earlier. */
export type PluginDevWatchLogLine = PluginLogLine & { count?: number; repeat?: true }
const FRAME_PREFIX = '[frame] '
const keyOf = (line: PluginLogLine): string => `${line.level}\u0000${line.line}`
/**
* Panel console lines repeat per item and per render (a warning inside `items.map`), so within one
* reload each `[frame]` line prints once with how many arrived together; later copies are counted
* and reported once when the plugin reloads or the watch ends. Worker lines pass through as is.
*/
export class PluginFrameLogDedupe {
private readonly repeats = new Map<string, { more: number; last: PluginLogLine }>()
take(lines: readonly PluginLogLine[]): PluginDevWatchLogLine[] {
const batch = new Map<string, number>()
for (const line of lines) {
if (line.line.startsWith(FRAME_PREFIX)) {
batch.set(keyOf(line), (batch.get(keyOf(line)) ?? 0) + 1)
}
}
const out: PluginDevWatchLogLine[] = []
const printed = new Map<string, PluginLogLine>()
for (const line of lines) {
const key = keyOf(line)
const count = batch.get(key)
if (count === undefined) {
out.push(line)
continue
}
const seen = this.repeats.get(key)
if (seen) {
seen.more += 1
seen.last = line
continue
}
if (!printed.has(key)) {
printed.set(key, line)
out.push(count > 1 ? { ...line, count } : line)
}
}
// After the loop, so this batch's own copies count in `count`, not as repeats.
for (const [key, line] of printed) {
this.repeats.set(key, { more: 0, last: line })
}
return out
}
/** A reload (or the end of the watch): what repeated since it printed, then a clean slate. */
flush(): PluginDevWatchLogLine[] {
const out: PluginDevWatchLogLine[] = []
for (const { more, last } of this.repeats.values()) {
if (more > 0) {
out.push({ ...last, count: more, repeat: true })
}
}
this.repeats.clear()
return out
}
}
@@ -0,0 +1,43 @@
import type { LogsResult } from '../plugin-runtime'
export type PluginLogLine = LogsResult['lines'][number]
/**
* Turns repeated `plugins.getLogs` replies into only the lines not yet seen. Hosts with the
* `after` cursor send just those; older hosts send their whole ring, which is ordered by time,
* so lines past the last timestamp seen (and past those already seen at it) are new.
*/
export class PluginLogFollower {
private hostCursor: string | undefined
private lastTs = Number.NEGATIVE_INFINITY
private seenAtLastTs = 0
/** Pass as `after`; undefined until a host that supports it replied. */
get cursor(): string | undefined {
return this.hostCursor
}
take(reply: LogsResult): PluginLogLine[] {
if (typeof reply.cursor === 'string') {
this.hostCursor = reply.cursor
return reply.lines
}
const fresh: PluginLogLine[] = []
let skipAtLastTs = this.seenAtLastTs
for (const line of reply.lines) {
if (line.ts < this.lastTs) {
continue
}
if (line.ts === this.lastTs && skipAtLastTs > 0) {
skipAtLastTs -= 1
continue
}
fresh.push(line)
}
for (const line of fresh) {
this.seenAtLastTs = line.ts === this.lastTs ? this.seenAtLastTs + 1 : 1
this.lastTs = line.ts
}
return fresh
}
}