diff --git a/README.md b/README.md index f889ba0..83383fe 100644 --- a/README.md +++ b/README.md @@ -147,7 +147,8 @@ Pass options with the object form of the plugin entry. Every option is optional. | `voiceModel` | `"openai/gpt-6.1-sol"` | Model for the background agent that thinks for GPT-Live, as `provider/model`. | | `voiceVariant` | `"medium"` | Thinking level for that model. | | `log` | `true` | Keep a local log of each call (see [Privacy](#privacy)). | -| `visual` | automatic | Force the aura's drawing method: `kitty`, `herdr` or `blocks`. | +| `visual` | automatic | Force the aura's drawing method: `kitty`, `herdr` or `blocks`, or `none` to turn the aura off. | +| `fps` | `30` | Highest frame rate for the aura, panel and call strip. Lower it (for example `10`) to reduce terminal load. | ### Custom prompts diff --git a/docs/architecture.md b/docs/architecture.md index a1f7c1e..86e6bf5 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -39,6 +39,7 @@ flowchart LR | `src/server/context.ts` | Conversation history quoted as data, and agent text made speakable. | | `src/server/auth.ts` | Reads OpenCode's ChatGPT OAuth sign-in. | | `src/server/log.ts` | The per-call JSONL log. | +| `src/server/options.ts` | Picks the terminal plugin's options out of the `opencode.json` entry for the `options` RPC. | | `src/tui/index.ts` | Terminal plugin: commands, keys, slots, starting calls. | | `src/tui/controller.ts` | Call state machine in the terminal, helper lifecycle, RPC events, heartbeats. | | `src/tui/helper.ts` | Finds, downloads (with checksum verification) and drives the native helper. | @@ -142,8 +143,12 @@ constraints drive this: - **No JSX.** For the same reason the UI does not use Solid; views are plain objects with `update(now)`, `animating(now)` and optional `interval()`, `suspend()` and `dispose()`. +OpenCode passes the plugin's `opencode.json` options only to the server part. At setup the terminal part asks for them +with the `options` RPC (3 s timeout) and lays its own options on top, so `voice`, `panel`, `duck`, `visual`, `fps` and +`keybinds` work from `opencode.json`. Without an answer it runs on its own options and defaults. + The frame clock runs only while something animates, at the fastest interval any animating view asks for (33 ms for -the aura). +the aura), but never faster than the `fps` option allows. ### The aura @@ -160,6 +165,9 @@ spinning the other way in violet. The level driving it is smoothed with a 40 ms | `kitty` | The renderer reports kitty graphics | Kitty graphics commands over an empty slot, 30 fps (see below) | | `blocks` | Everywhere else | Half-block characters, rendered at 3× and averaged down | +The `visual` option (or `GPT_LIVE_VISUAL`) forces a surface. `none` turns the aura off: the panel has no aura and the +sidebar aura slot is not registered. + The kitty surface (`src/tui/kitty.ts`) does not use OpenTUI's `ImageRenderable`, which clears the cells under an image to the terminal's default background: with a translucent terminal, every late frame flashed a see-through square. It reserves the cells with an empty box instead, so they keep the panel's background, and writes the kitty commands diff --git a/docs/development.md b/docs/development.md index 17bd6c7..201ae20 100644 --- a/docs/development.md +++ b/docs/development.md @@ -68,7 +68,7 @@ Environment variables for testing. They are not user settings. | `GPT_LIVE_OUTPUT` | `none` discards GPT-Live's audio; a path writes it to a WAV file. | | `GPT_LIVE_AUTOSTART` | Start a call as soon as a session is open. | | `GPT_LIVE_DEBUG` | Path to a JSONL file for UI diagnostics: which aura surface was picked, terminal capabilities, errors. | -| `GPT_LIVE_VISUAL` | Force the aura surface: `kitty`, `herdr` or `blocks`. | +| `GPT_LIVE_VISUAL` | Force the aura surface: `kitty`, `herdr`, `blocks` or `none`. | | `GPT_LIVE_HOST` | Path to a `gpt-live-host` binary to use instead of the usual lookup. | A hands-free test run: a recorded question as the microphone, no speaker, the call starting on its own: diff --git a/src/server/index.ts b/src/server/index.ts index c3b4b26..378dbb9 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -7,6 +7,7 @@ import { Bridge } from "./bridge" import { background, historyFrom, type HistoryEntry } from "./context" import { LiveError, MODEL, Sideband, createCall, requestIDs } from "./live" import { CallLog } from "./log" +import { terminalOptions } from "./options" import { loadPrompt } from "./prompt" interface Options { @@ -213,6 +214,8 @@ export default Plugin.define({ await ctx.session.hook("compaction", (event) => shapeRequest(event as never)) const registration = await ctx.rpc.register(GptLive, { + options: async () => terminalOptions(ctx.options as Record), + status: async () => { const auth = await resolveAuth(ctx) return defined({ diff --git a/src/server/options.ts b/src/server/options.ts new file mode 100644 index 0000000..ca3f2c0 --- /dev/null +++ b/src/server/options.ts @@ -0,0 +1,28 @@ +const isString = (value: unknown): value is string => typeof value === "string" +const isKey = (value: unknown) => value === false || isString(value) || (Array.isArray(value) && value.every(isString)) + +/** + * The options the terminal plugin uses. Only well-typed values are kept, so the RPC reply + * always passes its schema and one bad value cannot hide the others. + */ +export function terminalOptions(raw: Record) { + const result: { + voice?: string + panel?: boolean + duck?: boolean + visual?: string + fps?: number + keybinds?: Record + } = {} + if (isString(raw.voice)) result.voice = raw.voice + if (typeof raw.panel === "boolean") result.panel = raw.panel + if (typeof raw.duck === "boolean") result.duck = raw.duck + if (isString(raw.visual)) result.visual = raw.visual + if (typeof raw.fps === "number" && Number.isFinite(raw.fps)) result.fps = raw.fps + if (raw.keybinds && typeof raw.keybinds === "object" && !Array.isArray(raw.keybinds)) + result.keybinds = Object.fromEntries(Object.entries(raw.keybinds).filter(([, value]) => isKey(value))) as Record< + string, + string | string[] | false + > + return result +} diff --git a/src/shared/rpc.ts b/src/shared/rpc.ts index 53ad23f..d497f65 100644 --- a/src/shared/rpc.ts +++ b/src/shared/rpc.ts @@ -66,6 +66,21 @@ export const GptLive = define({ voiceSessionID: z.string().optional(), }), }, + /** + * The terminal plugin's options. OpenCode passes `opencode.json` plugin options only to the + * server part, so the terminal part reads its settings from here. + */ + options: { + input: z.object({}), + output: z.object({ + voice: z.string().optional(), + panel: z.boolean().optional(), + duck: z.boolean().optional(), + visual: z.string().optional(), + fps: z.number().optional(), + keybinds: z.record(z.string(), z.union([z.string(), z.array(z.string()), z.literal(false)])).optional(), + }), + }, /** Heartbeat from the window that owns the call; calls whose window goes quiet are ended. */ alive: { input: z.object({ callID: z.string() }), diff --git a/src/tui/index.ts b/src/tui/index.ts index aaa576c..9432ba6 100644 --- a/src/tui/index.ts +++ b/src/tui/index.ts @@ -1,8 +1,9 @@ import type { Plugin as PluginNamespace } from "@opencode/plugin/tui" -import { VOICES, type Voice } from "../shared/rpc" +import { GptLive, VOICES, type Voice } from "../shared/rpc" import { VoiceController, describeError } from "./controller" import { callModel, type CallModel } from "./model" +import { auraEnabled, configureVisual, debug } from "./surface" import { Frames, footerBadge, transcriptPanel, useCore, voiceAura, voiceStrip, type Core, type View } from "./ui" const PANEL = "gptlive.transcript" @@ -47,26 +48,54 @@ export function resolveKey(value: unknown, fallback: KeyOption): false | string return typeof chosen === "string" ? chosen : resolveKey(undefined, fallback) } +/** + * Options from the plugin's `opencode.json` entry. OpenCode hands those only to the server part, + * so ask it; without an answer the terminal part runs on `cli.json` options and defaults. + */ +async function serverOptions(context: Context): Promise> { + const location = context.location ?? context.data.location.default() + let timer: ReturnType | undefined + const timeout = new Promise((resolve) => { + timer = setTimeout(() => resolve(undefined), 3000) + }) + try { + const reply = await Promise.race([context.client.rpc(GptLive).options({}, { location }), timeout]) + return reply ?? {} + } catch (error) { + debug({ event: "options-error", error: String(error) }) + return {} + } finally { + clearTimeout(timer) + } +} + /** Builds the terminal plugin; `core` must be imported by the entry file (see tui.ts). */ export function createTuiPlugin(module: Core): PluginNamespace.Definition { useCore(module) return { id: "opencode-gpt-live.tui", - setup(context: Context) { - const options = context.options as { + async setup(context: Context) { + const options = { + ...(await serverOptions(context)), + ...(context.options as Record), + } as { voice?: string panel?: boolean duck?: boolean + visual?: string + fps?: number keybinds?: Partial> } + configureVisual(options.visual) const key = (action: KeyAction) => resolveKey(options.keybinds?.[action], DEFAULT_KEYS[action]) const voice = new VoiceController(context, { voice: VOICES.includes(options.voice as Voice) ? (options.voice as Voice) : undefined, // Other apps' audio is turned down during calls and restored afterwards. duck: options.duck !== false, }) - const frames = new Frames(voice) + const frames = new Frames(voice, options.fps) const autoPanel = options.panel !== false + debug({ event: "setup", root: import.meta.dir, options, aura: auraEnabled() }) let preparing: number | undefined let generation = 0 let disposed = false @@ -276,11 +305,15 @@ export function createTuiPlugin(module: Core): PluginNamespace.Definition { return frames.mount(gated) }, }), - context.ui.slot({ - prepend: "sidebar.content", - render: (input) => - frames.mount(voiceAura(context, voice, () => voice.owns(input.sessionID), "gptlive-aura-sidebar")), - }), + ...(auraEnabled() + ? [ + context.ui.slot({ + prepend: "sidebar.content", + render: (input) => + frames.mount(voiceAura(context, voice, () => voice.owns(input.sessionID), "gptlive-aura-sidebar")), + }), + ] + : []), context.ui.slot({ append: "prompt.footer.status", render: () => frames.mount(footerBadge(context, voice)), diff --git a/src/tui/surface.ts b/src/tui/surface.ts index 2e07047..0ac0fe6 100644 --- a/src/tui/surface.ts +++ b/src/tui/surface.ts @@ -6,7 +6,8 @@ import type { Plugin } from "@opencode/plugin/tui" * - herdr: frames streamed through herdr's pane graphics API (herdr does not display kitty * images printed by programs) * - blocks: half-block characters with true color, for every other terminal - * The choice is automatic; GPT_LIVE_VISUAL or the `visual` option can force one. + * The choice is automatic; GPT_LIVE_VISUAL or the `visual` option can force one, or turn the + * aura off with "none". */ import type { RGBA, Renderable, TextRenderable } from "@opentui/core" @@ -43,9 +44,25 @@ export function debug(entry: Record) { } } +/** The `visual` option; set once the plugin's options are known. */ +let configuredVisual: string | undefined + +export function configureVisual(visual: string | undefined) { + configuredVisual = visual +} + +function forcedVisual() { + return configuredVisual ?? process.env.GPT_LIVE_VISUAL +} + +/** False when the `visual` option (or GPT_LIVE_VISUAL) is "none": no aura is drawn anywhere. */ +export function auraEnabled() { + return forcedVisual() !== "none" +} + export function pickSurface(context: Context, layer: string, rows: number): Surface { const renderer = context.renderer - const forced = (context.options as { visual?: string }).visual ?? process.env.GPT_LIVE_VISUAL + const forced = forcedVisual() // A multiplexer nested inside herdr inherits herdr's environment, but herdr's pane // coordinates no longer match what is on screen. const nested = !!(process.env.TMUX || process.env.STY || process.env.ZELLIJ) diff --git a/src/tui/ui.ts b/src/tui/ui.ts index 67b63f6..5891a02 100644 --- a/src/tui/ui.ts +++ b/src/tui/ui.ts @@ -8,7 +8,7 @@ import type { RGBA, Renderable, TextRenderable } from "@opentui/core" import { AuraCanvas, type AuraPalette, type Rgb } from "./aura" import type { Entry, VoiceController } from "./controller" import { type Core, useCore as provideCore } from "./core" -import { debug, fallbackSurface, pickSurface, type Surface } from "./surface" +import { auraEnabled, debug, fallbackSurface, pickSurface, type Surface } from "./surface" import { duration, flap, pulse, shimmer, spinner } from "./visuals" type Context = Plugin.Context @@ -423,8 +423,8 @@ export function transcriptPanel(context: Context, voice: VoiceController, visibl stickyStart: "bottom", marginTop: 1, }) - const aura = voiceAura(context, voice, visible, "gptlive-aura-panel") - root.add(aura.root) + const aura = auraEnabled() ? voiceAura(context, voice, visible, "gptlive-aura-panel") : undefined + if (aura) root.add(aura.root) root.add(header) root.add(devices) root.add(scroll) @@ -434,11 +434,11 @@ export function transcriptPanel(context: Context, voice: VoiceController, visibl return { root, animating: (now) => voice.active || voice.state.entries.some((entry) => entryAnimating(entry, now)), - interval: () => (aura.animating(Date.now()) ? aura.interval!() : 33), - suspend: () => aura.suspend!(), - dispose: () => aura.dispose!(), + interval: () => (aura?.animating(Date.now()) ? aura.interval!() : 33), + suspend: () => aura?.suspend!(), + dispose: () => aura?.dispose!(), update(now) { - aura.update(now) + aura?.update(now) const state = voice.state const p = palette(context.theme) const phase = @@ -529,7 +529,8 @@ export function footerBadge(context: Context, voice: VoiceController): View { /** * Drives every mounted view: redraws on state changes, and while anything is animating at - * the fastest rate an animating view asks for (60 fps for the image aura, else 30). Views whose renderables were removed by the host are dropped automatically. + * the fastest rate an animating view asks for (30 fps by default), capped by + * the `fps` option. Views whose renderables were removed by the host are dropped automatically. */ export class Frames { private readonly views = new Set() @@ -538,8 +539,14 @@ export class Frames { private timer: ReturnType | undefined private period = 0 private readonly stopListening: () => void - - constructor(private readonly voice: VoiceController) { + /** Shortest frame interval allowed, in milliseconds. */ + private readonly minPeriod: number + + constructor( + private readonly voice: VoiceController, + fps?: number, + ) { + this.minPeriod = typeof fps === "number" && fps > 0 ? 1000 / fps : 0 this.stopListening = voice.onChange(() => this.tick()) } @@ -576,6 +583,7 @@ export class Frames { } } } + period = Math.max(period, this.minPeriod) if (this.timer && (!animating || period !== this.period)) { clearInterval(this.timer) this.timer = undefined diff --git a/test/frames.test.ts b/test/frames.test.ts index fef2186..788f25f 100644 --- a/test/frames.test.ts +++ b/test/frames.test.ts @@ -67,4 +67,24 @@ describe("frame clock", () => { // Still mounted: every frame reached the view, including the ones after it failed. expect(updates).toBe(9) }) + + test("the fps option caps the frame rate of animating views", () => { + const voice = { onChange: () => () => {} } + const period = (fps?: number) => { + const frames = new Frames(voice as unknown as VoiceController, fps) + frames.mount({ + root: { isDestroyed: false, destroyRecursively() {} } as unknown as View["root"], + animating: () => true, + interval: () => 33, + update() {}, + }) + const result = (frames as unknown as { period: number }).period + frames.dispose() + return result + } + expect(period()).toBe(33) + expect(period(10)).toBe(100) + expect(period(1000)).toBe(33) + expect(period(0)).toBe(33) + }) }) diff --git a/test/options.test.ts b/test/options.test.ts new file mode 100644 index 0000000..833a0d4 --- /dev/null +++ b/test/options.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, test } from "bun:test" + +import { terminalOptions } from "../src/server/options" + +describe("terminal options", () => { + test("passes the terminal settings through", () => { + expect( + terminalOptions({ + voice: "maple", + visual: "none", + fps: 10, + panel: false, + duck: true, + keybinds: { toggle: "v", mute: ["ctrl+y", "f9"], panel: false }, + instructions: "server only", + }), + ).toEqual({ + voice: "maple", + visual: "none", + fps: 10, + panel: false, + duck: true, + keybinds: { toggle: "v", mute: ["ctrl+y", "f9"], panel: false }, + }) + }) + + test("drops values of the wrong type instead of failing", () => { + expect(terminalOptions({ fps: "10", panel: "no", keybinds: { toggle: 3, mute: "f9" } })).toEqual({ + keybinds: { mute: "f9" }, + }) + }) +})