@bypane/cli 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,27 +1,29 @@
1
1
  # bypane
2
2
 
3
- A fast, lightweight side pane next to your terminal coding agent for everything that reads poorly in scrolling chat: plans, checklists, screenshots, files, tables, charts, and approval prompts.
3
+ Anything beyond the chat, right beside it.
4
4
 
5
- Built on [`tui-sdk`](https://tui-sdk.dev) with zero extra runtime dependencies: **~2 ms startup**, **~4 MB RAM**, **~2 MB native binary** (via `scriptc`), and **60 fps differential rendering** so it feels instant like `fzf`, never like a heavy Electron or web sidecar.
5
+ `bypane` is a lightweight companion terminal pane next to your coding agent for visual and interactive work: Markdown plans with checklists, files and screenshots, filterable tables, braille charts, live logs, approval prompts, and generative terminal UIs built on [`tui-sdk`](https://tui-sdk.dev).
6
6
 
7
- When your agent has something visual or interactive to share, `bypane` opens beside your chat automatically. You review plans, check off tasks, filter data, add notes, or pick an option, then press `s` to send your structured feedback straight back into your agent's prompt.
7
+ When an agent has something structured or interactive to share, `bypane` opens beside your chat automatically. You toggle tasks, tune sliders, inspect a timeline, add state-scoped notes (`n`), or submit a decision, and `bypane` injects the structured result straight back into the originating agent pane.
8
8
 
9
9
  ## What you get
10
10
 
11
- - **One-key feedback back to your agent (`s`):** Check off plan items, highlight a table row, or attach quick notes (`n`), then press `s`. `bypane` formats a compact summary of your exact choices and notes and injects it directly into the agent pane that sent the tab, ready for you to hit Enter. No copy-pasting or re-explaining line numbers.
12
- - **Instant and tiny footprint:** Starts in ~2 ms with ~4 MB peak RAM as a ~2 MB native binary (or runs directly on Node.js 24 with sub-millisecond frame diffs). No Electron, no browser engine, no Virtual DOM, and live filtering scales smoothly to huge tables and logs.
13
- - **Interactive plans and checklists:** Read Markdown plans without them scrolling off screen, toggle `- [ ]` tasks with `Space` or a click, and leave notes on any tab. Agents can also read your live state at any time with `bypane state`.
14
- - **QuickLook for files, screenshots, and binaries (`o`):** View PNG screenshots right inside Kitty or Ghostty (with half-block fallback everywhere else), jump straight to highlighted lines of code, and press `o` on PDFs, videos, images, or archives to open them in your local desktop apps.
15
- - **Live tables, charts, and logs:** Filter table rows as you type (`/`), sort columns (`r`), inspect braille line charts for metrics or benchmarks, and filter streaming logs without leaving the terminal.
16
- - **Human-only decision prompts:** Answer single-choice, multi-choice, text, or confirmation prompts in a dedicated tab. Agents can pre-highlight a suggested default, while final submission stays strictly human-only.
11
+ - **State-scoped notes, inline quotes, and direct push-back (`n`, `s`):** Drag or double-click any fragment in Markdown or code to highlight it, then press `n` to attach a comment with the exact `Quote:` (and `:start-end` line range on files) straight into your agent pane. On interactive UIs, `n` → `Enter` tags the active state or stage, submit buttons push immediately, and `s` sends current state plus any unsent notes without duplicating earlier sends.
12
+ - **Generative terminal UIs (`bypane ui`):** Agents can compose custom interfaces from declarative `tui-sdk` primitives: layout containers (`col`, `row`, `box`, `divider`), visual components (`text`, `badge`, `stat`, `markdown`, `meter`, `sparkline`, `chart`, `canvas`, `table`), and interactive controls (`slider`, `toggle`, `segmented`, `select`, `checkboxes`, `input`, `timeline` in `steps` or `gantt` mode, `button`). Values update live through safe `{{expr}}` formulas with zero `eval`.
13
+ - **Custom `tui-sdk` apps (`bypane app`):** When declarative controls fall short, agents can run arbitrary TypeScript or JavaScript modules using the full `tui` SDK (`drawShader`, `createCanvas`, `createSpring`, custom widgets, mouse and drag handlers) alongside `bypane/primitives`. Each app runs in an isolated worker process, pauses animation timers when its tab is inactive, hot-reloads on code changes, accepts live state patches without restarting, and traps errors inside its own tab.
14
+ - **Interactive plans and checklists:** Read Markdown plans without them scrolling off screen, toggle `- [ ]` tasks with `Space` or a click, and let agents inspect live edits via `bypane state`.
15
+ - **QuickLook for files, screenshots, and binaries (`o`):** View PNG screenshots inline in Kitty or Ghostty (with truecolor half-block fallback everywhere else), inspect highlighted code ranges, and press `o` on PDFs, images, videos, or archives to open them in local desktop apps.
16
+ - **Live tables, charts, and logs:** Filter rows or log lines as you type (`/`), sort columns (`r`), and inspect braille line charts inside the terminal.
17
+ - **Human-only gates (`ask`, `ui --wait`, `app --wait`):** Agents can pre-highlight a default or render interactive controls, while final submission stays strictly human-only.
18
+ - **Small footprint:** Built on `tui-sdk` with zero extra runtime dependencies: ~2 ms startup and ~4 MB peak RAM as a ~2 MB native binary (via `scriptc`), or direct execution on Node.js 24 with cell-diff rendering at 60 fps.
17
19
 
18
20
  ## Smooth Rex Integration
19
21
 
20
22
  `bypane` works in any terminal (and in tmux), and is tuned to feel native inside [Rex](https://superlogical.com/rex):
21
23
 
22
- - **Zero-setup auto-docking:** The first time an agent pushes a plan, image, table, or prompt, `bypane` automatically splits a companion pane beside your chat (`rex split --focus=false`) without stealing your cursor.
24
+ - **Zero-setup auto-docking:** The first time an agent pushes a surface, `bypane` splits a companion pane beside your chat (`rex split --focus=false`) without stealing focus.
23
25
  - **One-key remote file open (`o`):** Working on a remote Linux devbox over Rex? Pressing `o` on a PDF, screenshot, or video runs `rex open`, transferring and opening it directly in your Mac's native app.
24
- - **Direct push-back (`s`) and origin jump (`g`):** Each tab remembers which Rex block pushed it. Press `s` to send your feedback straight into that pane (`rex send`), or `g` to jump focus back to it (`rex focus`) when juggling multiple agents.
26
+ - **Direct push-back (`n`, `s`) and origin jump (`g`):** Each tab remembers which Rex block pushed it. Notes, submit actions, and `s` summaries inject directly into that pane (`rex send`), and `g` jumps focus back to it (`rex focus`) when juggling multiple agents.
25
27
  - **Automatic per-window isolation:** Each Rex window gets its own `bypane` workspace automatically, so separate projects stay separate.
26
28
 
27
29
  ## Quick Start
@@ -42,27 +44,33 @@ Copy and paste this into Claude Code, Codex, OpenCode, or Antigravity:
42
44
 
43
45
  > Run `npx -y @bypane/cli setup --yes` so `bypane` and its agent skill are installed and configured, then run `bypane demo` so I can try it.
44
46
 
45
- ### Try the demo without configuring anything
47
+ ### Try the demos without configuring anything
46
48
 
47
49
  ```bash
50
+ # Built-in workspace (plans, image, table, chart, decision gate, Rollout Tuner, Release Timeline)
48
51
  npx @bypane/cli --demo
52
+
53
+ # Custom tui-sdk app example (live 30 fps shader stage + braille spring curve + sliders)
54
+ bypane app examples/spring-studio.ts --id spring --title "Spring Studio"
49
55
  ```
50
56
 
51
57
  ## Keyboard Shortcuts
52
58
 
53
59
  | Key | Action |
54
60
  | :--- | :--- |
55
- | `s` or `Ctrl+S` | Push your checklist, notes, or selected row straight into the agent pane |
61
+ | `n` or `Ctrl+E` | Add a state- or quote-scoped note (`Enter` saves and sends immediately to the agent pane) |
62
+ | `Drag` / `Double-click` | Highlight a text fragment in Markdown or code (`n` comment, `y` copy, `Esc` clear) |
63
+ | `s` or `Ctrl+S` | Push current state and any unsent notes straight into the agent pane |
56
64
  | `o` or `Ctrl+O` | Open the current file or image on your local machine (`rex open` / `open`) |
57
- | `n` or `Ctrl+E` | Add a note for the agent on the current tab |
58
65
  | `g` | Jump focus back to the Rex or tmux pane that pushed the current tab |
59
66
  | `1–9` / `[` `]` | Switch tabs (or click with mouse) |
60
- | `Tab` | Move focus between document, checklist, filter, and tabs |
61
- | `Space` / `Enter` | Toggle checklist items or submit a decision prompt |
67
+ | `Tab` / `Shift+Tab` | Cycle focus across controls, checklists, filters, custom app widgets, and tabs |
68
+ | `←` `→` / `↑` `↓` | Adjust sliders and segmented controls, step timeline stages, or scroll |
69
+ | `Space` / `Enter` | Toggle checkboxes/switches, press buttons, or submit a decision prompt |
62
70
  | `/` or `Ctrl+F` | Filter table rows or log lines |
63
71
  | `r` | Cycle column sort (tables) |
64
- | `y` | Copy the selected row, file path, or feedback summary to clipboard |
65
- | `w` or `Ctrl+W` | Close the current tab |
72
+ | `y` | Copy the selected row, file path, or full scoped summary to clipboard |
73
+ | `w` or `Ctrl+W` | Close the current tab (and stop any attached app worker) |
66
74
  | `?` | Show or hide shortcuts |
67
75
 
68
76
  ---
@@ -71,19 +79,57 @@ npx @bypane/cli --demo
71
79
 
72
80
  ### Architecture & Performance
73
81
 
74
- `bypane` is built with [`tui-sdk`](https://tui-sdk.dev) and has zero other runtime dependencies. The TUI pane, CLI commands, and MCP server talk over a per-window Unix domain socket (scoped by Rex window, tmux window, working directory, or `--session <name>`).
82
+ `bypane` is built with [`tui-sdk`](https://tui-sdk.dev) and has zero other runtime dependencies. The TUI pane, CLI commands, and MCP server communicate over a per-window Unix domain socket (scoped by Rex window, tmux window, working directory, or `--session <name>`).
83
+
84
+ Custom apps (`bypane app`) run in isolated Node 24 child processes with native TypeScript support and a module hook that resolves `"tui"`, `"tui/*"`, and `"bypane/primitives"` from any file path or inline code string. Workers stream binary `Cells` buffers and incremental style tables over Node IPC, pause animation timers when their tab is inactive, and translate host keyboard, focus, and SGR mouse events into app-local coordinates.
75
85
 
76
86
  | Runtime | Startup | Peak RAM | Size |
77
87
  | :--- | ---: | ---: | ---: |
78
88
  | Native binary (`scriptc`) | ~2 ms | ~4 MB | ~2 MB |
79
89
  | Node.js 24 (`npx @bypane/cli`) | ~90 ms | ~96 MB | Node runtime |
80
90
 
81
- Every frame is diffed cell-by-cell so idle panes use zero CPU and scrolling/filtering stays crisp at 60 fps. To compile a standalone native binary locally (requires `clang` + `lld`):
91
+ Every frame is diffed cell-by-cell so idle panes use zero CPU and scrolling, filtering, and animations stay responsive up to 60 fps. To compile a standalone native binary locally (requires `clang` + `lld`):
82
92
 
83
93
  ```bash
84
94
  npm run build:native
85
95
  ```
86
96
 
97
+ ### Authoring a Custom App (`bypane app`)
98
+
99
+ Export a default factory receiving `ctx` (or named `view` / `keys` exports):
100
+
101
+ ```ts
102
+ import { drawShader, rgb, split } from "tui"
103
+ import { Slider } from "bypane/primitives"
104
+
105
+ export default function (ctx) {
106
+ let gain = Number(ctx.state.gain ?? 50)
107
+ return {
108
+ fps: 30,
109
+ hints: ["←/→ tune", "Enter apply"],
110
+ summary: () => `gain=${gain}%`,
111
+ view(frame) {
112
+ const [stage, controls] = split(frame.rect, "rows", [-1, 4], 1)
113
+ drawShader(frame, stage, (x, y, t) => rgb(0.1, gain / 120, 0.4 + 0.2 * Math.sin(x * 0.1 - t)))
114
+ Slider.Root(
115
+ frame,
116
+ { id: "gain", label: "Gain", min: 0, max: 100, step: 5, unit: "%", value: gain, onValueChange: (v) => { gain = v; ctx.setState({ gain }) } },
117
+ (r) => Slider.Track(r, controls),
118
+ )
119
+ },
120
+ keys(key) {
121
+ if (key.name === "enter") {
122
+ ctx.submit("apply", { gain })
123
+ return true
124
+ }
125
+ return false
126
+ },
127
+ }
128
+ }
129
+ ```
130
+
131
+ See [`examples/spring-studio.ts`](examples/spring-studio.ts) for a complete example combining `drawShader`, `createCanvas("braille")`, `Slider`, `Button`, live `ctx.onState(...)` updates, and mouse interaction.
132
+
87
133
  ### CLI Reference
88
134
 
89
135
  Agents and shell scripts can push tabs directly from the command line (or `npx -y @bypane/cli ...` if not installed globally):
@@ -107,7 +153,14 @@ tail -n 200 app.log | bypane log --title "App Log"
107
153
  # Present a human-only decision prompt (blocks until submitted)
108
154
  bypane ask --title "Deploy" --prompt "Choose rollout" --option canary --option prod
109
155
 
110
- # Read current tab state (checked items, notes, selected row, ask answers)
156
+ # Compose a declarative generative UI (sliders, timelines, reactive stats/charts)
157
+ cat tuner.json | bypane ui --id tuner --title "Rollout Tuner" --wait
158
+
159
+ # Run a custom tui-sdk TypeScript app (or stream live state without restarting)
160
+ bypane app examples/spring-studio.ts --id spring --title "Spring Studio"
161
+ bypane app --id spring --state '{"stiffness":420,"damping":14}'
162
+
163
+ # Read current tab state (checked items, notes, selected row, UI/app state)
111
164
  bypane state
112
165
 
113
166
  # Manage installed agent skill files
@@ -118,7 +171,9 @@ bypane skill setup | status | show | remove
118
171
 
119
172
  Agents can use `bypane` via the installed skill and CLI alone, or connect over MCP (`bypane mcp` or `npx -y @bypane/cli mcp`) for structured tools:
120
173
 
121
- - `bypane_present`: create or update `markdown`, `file`, `image`, `table`, `chart`, or `log` tabs
174
+ - `bypane_present`: create or update `markdown`, `file`, `image`, `table`, `chart`, `log`, `ui`, or `app` tabs
175
+ - `bypane_ui`: compose a declarative generative UI tree with `{{expr}}` formulas and optional `wait: true` human submission
176
+ - `bypane_app`: run arbitrary TypeScript/JavaScript `tui` SDK code (`path` or inline `code`) in an isolated worker, stream live `state` patches, or block with `wait: true`
122
177
  - `bypane_append_log`: append lines to an open log tab
123
178
  - `bypane_ask`: show a human-gated `select`, `multiselect`, `text`, or `confirm` prompt
124
179
  - `bypane_list`, `bypane_state`, `bypane_close`: inspect open tabs, read user edits, or close tabs
@@ -0,0 +1,408 @@
1
+ import { fork } from "node:child_process";
2
+ import { chmodSync, mkdirSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { setCell, setCluster, write, } from "tui";
6
+ import { socketDir } from "./ipc.js";
7
+ const CLUSTER = 0x80000000;
8
+ const PACKED = 0x80000000;
9
+ const hostExt = import.meta.url.endsWith(".ts") ? ".ts" : ".js";
10
+ const WORKER_SCRIPT = fileURLToPath(new URL(`./app-worker${hostExt}`, import.meta.url));
11
+ export class AppHostManager {
12
+ store;
13
+ callbacks;
14
+ apps = new Map();
15
+ disposed = false;
16
+ exitHooked = false;
17
+ exitHandler;
18
+ constructor(store, callbacks) {
19
+ this.store = store;
20
+ this.callbacks = callbacks;
21
+ this.exitHandler = () => {
22
+ this.disposeAll(true);
23
+ };
24
+ }
25
+ send(managed, msg) {
26
+ if (managed.stopping || !managed.child.connected)
27
+ return;
28
+ try {
29
+ managed.child.send(msg);
30
+ }
31
+ catch {
32
+ // Child already disconnected.
33
+ }
34
+ }
35
+ resolveModulePath(surface) {
36
+ if (surface.code !== undefined) {
37
+ const dir = join(socketDir(), "apps");
38
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
39
+ try {
40
+ chmodSync(dir, 0o700);
41
+ }
42
+ catch {
43
+ // Ignore on platforms where chmod fails.
44
+ }
45
+ const safeId = surface.id.replace(/[^a-zA-Z0-9._-]/g, "_").slice(0, 48);
46
+ const tempFile = join(dir, `${safeId}-r${surface.revision}-${process.pid}.ts`);
47
+ writeFileSync(tempFile, surface.code, { encoding: "utf8", mode: 0o600 });
48
+ return { modulePath: tempFile, tempFile };
49
+ }
50
+ if (surface.entryPath) {
51
+ return { modulePath: surface.entryPath };
52
+ }
53
+ throw new Error("App surface requires either a module `path` or inline `code`.");
54
+ }
55
+ cleanupTempFile(tempFile) {
56
+ if (!tempFile)
57
+ return;
58
+ try {
59
+ unlinkSync(tempFile);
60
+ }
61
+ catch {
62
+ // Ignore cleanup errors.
63
+ }
64
+ }
65
+ startWorker(surface, columns, rows, active) {
66
+ this.stop(surface.id);
67
+ if (this.disposed)
68
+ return null;
69
+ let modulePath;
70
+ let tempFile;
71
+ try {
72
+ const resolved = this.resolveModulePath(surface);
73
+ modulePath = resolved.modulePath;
74
+ tempFile = resolved.tempFile;
75
+ }
76
+ catch (err) {
77
+ this.store.setAppRuntime(surface.id, "error", err.message);
78
+ return null;
79
+ }
80
+ if (!this.exitHooked) {
81
+ this.exitHooked = true;
82
+ process.once("exit", this.exitHandler);
83
+ }
84
+ const child = fork(WORKER_SCRIPT, [], {
85
+ execArgv: [],
86
+ serialization: "advanced",
87
+ stdio: ["ignore", "pipe", "pipe", "ipc"],
88
+ env: { ...process.env },
89
+ });
90
+ const managed = {
91
+ surfaceId: surface.id,
92
+ revision: surface.revision,
93
+ stateRevision: surface.stateRevision,
94
+ child,
95
+ tempFile,
96
+ styleInputs: [{}],
97
+ styleMaps: new WeakMap(),
98
+ latestFrame: null,
99
+ lastCols: columns,
100
+ lastRows: rows,
101
+ lastActive: active,
102
+ stderrBuf: "",
103
+ stopping: false,
104
+ };
105
+ this.apps.set(surface.id, managed);
106
+ child.stderr?.on("data", (chunk) => {
107
+ managed.stderrBuf = (managed.stderrBuf + String(chunk)).slice(-2048);
108
+ });
109
+ child.on("message", (msg) => {
110
+ if (this.apps.get(surface.id) !== managed)
111
+ return;
112
+ this.handleWorkerMessage(managed, msg);
113
+ });
114
+ child.on("exit", (code, signal) => {
115
+ this.cleanupTempFile(managed.tempFile);
116
+ managed.tempFile = undefined;
117
+ if (this.apps.get(surface.id) !== managed)
118
+ return;
119
+ if (managed.stopping)
120
+ return;
121
+ const surf = this.store.get(surface.id);
122
+ if (!surf || surf.kind !== "app")
123
+ return;
124
+ if (surf.runtimeStatus !== "error") {
125
+ const detail = managed.stderrBuf.trim() || `Worker exited (${signal ?? code ?? "unknown"})`;
126
+ this.store.setAppRuntime(surface.id, code === 0 ? "exited" : "error", code === 0 ? undefined : detail);
127
+ this.callbacks.onRedraw();
128
+ }
129
+ });
130
+ child.on("error", (err) => {
131
+ if (this.apps.get(surface.id) !== managed)
132
+ return;
133
+ this.store.setAppRuntime(surface.id, "error", err.message);
134
+ this.callbacks.onRedraw();
135
+ });
136
+ this.send(managed, {
137
+ type: "init",
138
+ id: surface.id,
139
+ title: surface.title,
140
+ modulePath,
141
+ state: { ...surface.state },
142
+ columns: Math.max(10, columns),
143
+ rows: Math.max(4, rows),
144
+ active,
145
+ });
146
+ return managed;
147
+ }
148
+ handleWorkerMessage(managed, msg) {
149
+ const surf = this.store.get(managed.surfaceId);
150
+ if (!surf || surf.kind !== "app")
151
+ return;
152
+ switch (msg.type) {
153
+ case "ready":
154
+ this.store.setAppRuntime(surf.id, "running");
155
+ this.store.setAppMeta(surf.id, {
156
+ hints: msg.hints,
157
+ captureKeys: msg.captureKeys,
158
+ customSummary: msg.summary,
159
+ });
160
+ this.store.setAppState(surf.id, msg.state, msg.summary);
161
+ this.callbacks.onRedraw();
162
+ return;
163
+ case "frame": {
164
+ const f = msg.frame;
165
+ if (f.newStyles.length > 0) {
166
+ for (let i = 0; i < f.newStyles.length; i++) {
167
+ managed.styleInputs[f.styleOffset + i] = f.newStyles[i];
168
+ }
169
+ }
170
+ managed.latestFrame = f;
171
+ if (msg.summary !== undefined && surf.customSummary !== msg.summary) {
172
+ surf.customSummary = msg.summary || undefined;
173
+ }
174
+ if (surf.runtimeStatus === "starting") {
175
+ this.store.setAppRuntime(surf.id, "running");
176
+ }
177
+ this.callbacks.onRedraw();
178
+ return;
179
+ }
180
+ case "state":
181
+ this.store.setAppState(surf.id, msg.state, msg.summary);
182
+ this.callbacks.onRedraw();
183
+ return;
184
+ case "submit": {
185
+ if (msg.summary !== undefined)
186
+ surf.customSummary = msg.summary || undefined;
187
+ const hadWaiter = this.store.hasAppWaiter(surf.id);
188
+ this.store.submitApp(surf.id, msg.action, msg.state);
189
+ if (!hadWaiter) {
190
+ this.callbacks.onSubmit?.(surf, msg.action);
191
+ }
192
+ this.callbacks.onRedraw();
193
+ return;
194
+ }
195
+ case "send":
196
+ this.store.setAppState(surf.id, msg.state, msg.summary);
197
+ this.callbacks.onSend?.(surf, msg.message);
198
+ this.callbacks.onRedraw();
199
+ return;
200
+ case "toast":
201
+ this.store.setToast(msg.text, msg.tone);
202
+ this.callbacks.onRedraw();
203
+ return;
204
+ case "copy":
205
+ this.callbacks.onCopy?.(msg.text);
206
+ return;
207
+ case "error": {
208
+ const detail = msg.stack ? `${msg.message}\n${msg.stack}` : msg.message;
209
+ this.store.setAppRuntime(surf.id, "error", detail);
210
+ this.callbacks.onRedraw();
211
+ return;
212
+ }
213
+ }
214
+ }
215
+ /**
216
+ * Ensures the given app surface has a running worker synced to its current revision, state, size, and active status.
217
+ */
218
+ sync(surface, columns, rows, active) {
219
+ const cols = Math.max(10, columns);
220
+ const rws = Math.max(4, rows);
221
+ const existing = this.apps.get(surface.id);
222
+ if (!existing || existing.revision !== surface.revision) {
223
+ this.startWorker(surface, cols, rws, active);
224
+ return;
225
+ }
226
+ if (existing.stateRevision !== surface.stateRevision) {
227
+ existing.stateRevision = surface.stateRevision;
228
+ this.send(existing, { type: "state", state: { ...surface.state } });
229
+ }
230
+ if (existing.lastCols !== cols || existing.lastRows !== rws) {
231
+ existing.lastCols = cols;
232
+ existing.lastRows = rws;
233
+ this.send(existing, { type: "resize", columns: cols, rows: rws });
234
+ }
235
+ if (existing.lastActive !== active) {
236
+ existing.lastActive = active;
237
+ this.send(existing, { type: "active", active });
238
+ }
239
+ }
240
+ /**
241
+ * Pauses inactive app workers (0% background CPU) and reaps workers for closed surfaces.
242
+ */
243
+ reconcile(activeSurfaceId) {
244
+ for (const [id, managed] of this.apps) {
245
+ const surf = this.store.get(id);
246
+ if (!surf || surf.kind !== "app") {
247
+ this.stop(id);
248
+ continue;
249
+ }
250
+ const shouldBeActive = id === activeSurfaceId;
251
+ if (managed.lastActive !== shouldBeActive) {
252
+ managed.lastActive = shouldBeActive;
253
+ this.send(managed, { type: "active", active: shouldBeActive });
254
+ }
255
+ }
256
+ }
257
+ sendKey(surfaceId, key) {
258
+ const managed = this.apps.get(surfaceId);
259
+ if (managed)
260
+ this.send(managed, { type: "key", key });
261
+ }
262
+ sendMouse(surfaceId, mouse, ctrl, alt, shift) {
263
+ const managed = this.apps.get(surfaceId);
264
+ if (managed)
265
+ this.send(managed, { type: "mouse", mouse, ctrl, alt, shift });
266
+ }
267
+ sendFocus(surfaceId, workerFocusId) {
268
+ const managed = this.apps.get(surfaceId);
269
+ if (managed)
270
+ this.send(managed, { type: "focus", id: workerFocusId });
271
+ }
272
+ getFrameMeta(surfaceId) {
273
+ const f = this.apps.get(surfaceId)?.latestFrame;
274
+ if (!f) {
275
+ return { focusables: [], focused: "", hasTrap: false, textInputFocused: false };
276
+ }
277
+ return {
278
+ focusables: f.focusables,
279
+ focused: f.focused,
280
+ hasTrap: f.hasTrap,
281
+ textInputFocused: f.cursor !== null,
282
+ };
283
+ }
284
+ /**
285
+ * Blits the worker's latest `Cells` snapshot into `frame.cells` inside `rect` with O(1) style remapping.
286
+ */
287
+ blit(surfaceId, frame, rect, applyCursor) {
288
+ const managed = this.apps.get(surfaceId);
289
+ const src = managed?.latestFrame;
290
+ if (!managed || !src)
291
+ return false;
292
+ let map = managed.styleMaps.get(frame.styles);
293
+ if (!map) {
294
+ map = [0];
295
+ managed.styleMaps.set(frame.styles, map);
296
+ }
297
+ for (let i = map.length; i < managed.styleInputs.length; i++) {
298
+ const input = managed.styleInputs[i];
299
+ map[i] = input ? frame.styles.style(input) : 0;
300
+ }
301
+ const copyCols = Math.min(src.columns, rect.columns);
302
+ const copyRows = Math.min(src.rows, rect.rows);
303
+ const rightEdge = rect.x + copyCols;
304
+ for (let r = 0; r < copyRows; r++) {
305
+ const srcRow = r * src.columns;
306
+ const dstY = rect.y + r;
307
+ for (let c = 0; c < copyCols; c++) {
308
+ const idx = srcRow + c;
309
+ const w = src.widths[idx] ?? 1;
310
+ if (w === 0)
311
+ continue;
312
+ const rawStyle = (src.styles[idx] ?? 0) >>> 0;
313
+ const dstStyle = rawStyle === 0 || rawStyle >= PACKED ? rawStyle : (map[rawStyle] ?? 0);
314
+ const ch = (src.chars[idx] ?? 0x20) >>> 0;
315
+ if (ch >= CLUSTER) {
316
+ const cluster = src.clusters[ch - CLUSTER] ?? " ";
317
+ if (w === 2) {
318
+ if (c + 1 < copyCols) {
319
+ write(frame.cells, rect.x + c, dstY, cluster, dstStyle, rightEdge);
320
+ }
321
+ }
322
+ else {
323
+ setCluster(frame.cells, rect.x + c, dstY, cluster, dstStyle);
324
+ }
325
+ }
326
+ else if (w === 2) {
327
+ if (c + 1 < copyCols) {
328
+ write(frame.cells, rect.x + c, dstY, String.fromCodePoint(ch), dstStyle, rightEdge);
329
+ }
330
+ }
331
+ else {
332
+ setCell(frame.cells, rect.x + c, dstY, ch, dstStyle);
333
+ }
334
+ }
335
+ }
336
+ if (applyCursor && src.cursor) {
337
+ if (src.cursor.x >= 0 && src.cursor.x < copyCols && src.cursor.y >= 0 && src.cursor.y < copyRows) {
338
+ frame.cursor = { x: rect.x + src.cursor.x, y: rect.y + src.cursor.y };
339
+ }
340
+ }
341
+ return true;
342
+ }
343
+ stop(surfaceId, immediate = false) {
344
+ const managed = this.apps.get(surfaceId);
345
+ if (!managed)
346
+ return;
347
+ this.apps.delete(surfaceId);
348
+ managed.stopping = true;
349
+ this.cleanupTempFile(managed.tempFile);
350
+ managed.tempFile = undefined;
351
+ const child = managed.child;
352
+ if (immediate) {
353
+ try {
354
+ child.kill("SIGTERM");
355
+ }
356
+ catch {
357
+ // Ignore.
358
+ }
359
+ return;
360
+ }
361
+ try {
362
+ if (child.connected) {
363
+ child.send({ type: "dispose" });
364
+ }
365
+ }
366
+ catch {
367
+ // Ignore send failure on already exiting child.
368
+ }
369
+ const termTimer = setTimeout(() => {
370
+ if (!child.killed) {
371
+ try {
372
+ child.kill("SIGTERM");
373
+ }
374
+ catch {
375
+ // Ignore.
376
+ }
377
+ }
378
+ }, 120);
379
+ termTimer.unref();
380
+ const killTimer = setTimeout(() => {
381
+ if (!child.killed) {
382
+ try {
383
+ child.kill("SIGKILL");
384
+ }
385
+ catch {
386
+ // Ignore.
387
+ }
388
+ }
389
+ }, 350);
390
+ killTimer.unref();
391
+ child.once("exit", () => {
392
+ clearTimeout(termTimer);
393
+ clearTimeout(killTimer);
394
+ });
395
+ }
396
+ disposeAll(immediate = false) {
397
+ if (this.disposed)
398
+ return;
399
+ this.disposed = true;
400
+ if (this.exitHooked) {
401
+ this.exitHooked = false;
402
+ process.removeListener("exit", this.exitHandler);
403
+ }
404
+ for (const id of [...this.apps.keys()]) {
405
+ this.stop(id, immediate);
406
+ }
407
+ }
408
+ }
@@ -0,0 +1 @@
1
+ export {};