@bypane/cli 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +188 -2
- package/dist/app-host.js +408 -0
- package/dist/app-protocol.js +1 -0
- package/dist/app-worker.js +556 -0
- package/dist/cli.js +810 -0
- package/dist/config.js +42 -0
- package/dist/demo.js +430 -0
- package/dist/expr.js +460 -0
- package/dist/ipc.js +201 -0
- package/dist/mcp.js +416 -0
- package/dist/multiplexer.js +281 -0
- package/dist/png.js +208 -0
- package/dist/primitives.js +669 -0
- package/dist/selection.js +170 -0
- package/dist/setup.js +329 -0
- package/dist/skill.js +219 -0
- package/dist/state.js +1147 -0
- package/dist/types.js +1 -0
- package/dist/ui-surface.js +744 -0
- package/dist/ui.js +1466 -0
- package/examples/spring-studio.ts +420 -0
- package/package.json +58 -4
- package/skills/bypane/SKILL.md +136 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Vlad Arbatov
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,189 @@
|
|
|
1
|
-
#
|
|
1
|
+
# bypane
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Anything beyond the chat, right beside it.
|
|
4
|
+
|
|
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
|
+
|
|
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
|
+
|
|
9
|
+
## What you get
|
|
10
|
+
|
|
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.
|
|
19
|
+
|
|
20
|
+
## Smooth Rex Integration
|
|
21
|
+
|
|
22
|
+
`bypane` works in any terminal (and in tmux), and is tuned to feel native inside [Rex](https://superlogical.com/rex):
|
|
23
|
+
|
|
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.
|
|
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.
|
|
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.
|
|
27
|
+
- **Automatic per-window isolation:** Each Rex window gets its own `bypane` workspace automatically, so separate projects stay separate.
|
|
28
|
+
|
|
29
|
+
## Quick Start
|
|
30
|
+
|
|
31
|
+
Requires Node.js 24+.
|
|
32
|
+
|
|
33
|
+
### Option 1: One command
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
npx @bypane/cli setup
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
The inline setup wizard installs `bypane` permanently on your `PATH`, adds the `bypane` skill to your agent folders (all pre-checked), lets you pick how `bypane` auto-splits in Rex or tmux, prints optional MCP config, and offers to launch a live demo pane.
|
|
40
|
+
|
|
41
|
+
### Option 2: Let your coding agent set it up
|
|
42
|
+
|
|
43
|
+
Copy and paste this into Claude Code, Codex, OpenCode, or Antigravity:
|
|
44
|
+
|
|
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.
|
|
46
|
+
|
|
47
|
+
### Try the demos without configuring anything
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
# Built-in workspace (plans, image, table, chart, decision gate, Rollout Tuner, Release Timeline)
|
|
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"
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Keyboard Shortcuts
|
|
58
|
+
|
|
59
|
+
| Key | Action |
|
|
60
|
+
| :--- | :--- |
|
|
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 |
|
|
64
|
+
| `o` or `Ctrl+O` | Open the current file or image on your local machine (`rex open` / `open`) |
|
|
65
|
+
| `g` | Jump focus back to the Rex or tmux pane that pushed the current tab |
|
|
66
|
+
| `1–9` / `[` `]` | Switch tabs (or click with mouse) |
|
|
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 |
|
|
70
|
+
| `/` or `Ctrl+F` | Filter table rows or log lines |
|
|
71
|
+
| `r` | Cycle column sort (tables) |
|
|
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) |
|
|
74
|
+
| `?` | Show or hide shortcuts |
|
|
75
|
+
|
|
76
|
+
---
|
|
77
|
+
|
|
78
|
+
## Technical Details
|
|
79
|
+
|
|
80
|
+
### Architecture & Performance
|
|
81
|
+
|
|
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.
|
|
85
|
+
|
|
86
|
+
| Runtime | Startup | Peak RAM | Size |
|
|
87
|
+
| :--- | ---: | ---: | ---: |
|
|
88
|
+
| Native binary (`scriptc`) | ~2 ms | ~4 MB | ~2 MB |
|
|
89
|
+
| Node.js 24 (`npx @bypane/cli`) | ~90 ms | ~96 MB | Node runtime |
|
|
90
|
+
|
|
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`):
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
npm run build:native
|
|
95
|
+
```
|
|
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
|
+
|
|
133
|
+
### CLI Reference
|
|
134
|
+
|
|
135
|
+
Agents and shell scripts can push tabs directly from the command line (or `npx -y @bypane/cli ...` if not installed globally):
|
|
136
|
+
|
|
137
|
+
```bash
|
|
138
|
+
# Show Markdown, code with highlighted lines, PNG images, or binary QuickLook
|
|
139
|
+
bypane show PLAN.md
|
|
140
|
+
bypane show src/ui.ts:1-60
|
|
141
|
+
bypane show screenshot.png --caption "After layout polish"
|
|
142
|
+
bypane show report.pdf
|
|
143
|
+
|
|
144
|
+
# Pipe JSON, CSV, or TSV into a filterable, sortable table
|
|
145
|
+
cat rows.json | bypane table --title "Results"
|
|
146
|
+
|
|
147
|
+
# Render a braille chart
|
|
148
|
+
bypane chart --title "Latency" --unit ms --series p50:12,14,11,10 --series p99:42,38,31,29
|
|
149
|
+
|
|
150
|
+
# Stream lines into a filterable log surface
|
|
151
|
+
tail -n 200 app.log | bypane log --title "App Log"
|
|
152
|
+
|
|
153
|
+
# Present a human-only decision prompt (blocks until submitted)
|
|
154
|
+
bypane ask --title "Deploy" --prompt "Choose rollout" --option canary --option prod
|
|
155
|
+
|
|
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)
|
|
164
|
+
bypane state
|
|
165
|
+
|
|
166
|
+
# Manage installed agent skill files
|
|
167
|
+
bypane skill setup | status | show | remove
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
### MCP Server (Optional)
|
|
171
|
+
|
|
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:
|
|
173
|
+
|
|
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`
|
|
177
|
+
- `bypane_append_log`: append lines to an open log tab
|
|
178
|
+
- `bypane_ask`: show a human-gated `select`, `multiselect`, `text`, or `confirm` prompt
|
|
179
|
+
- `bypane_list`, `bypane_state`, `bypane_close`: inspect open tabs, read user edits, or close tabs
|
|
180
|
+
- `bypane_snapshot`, `bypane_act`: inspect live UI components or run non-destructive UI actions via `tui/agent`
|
|
181
|
+
|
|
182
|
+
### Development
|
|
183
|
+
|
|
184
|
+
```bash
|
|
185
|
+
npm install
|
|
186
|
+
npm run typecheck
|
|
187
|
+
npm run build
|
|
188
|
+
npm test
|
|
189
|
+
```
|
package/dist/app-host.js
ADDED
|
@@ -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 {};
|