worktrust 0.11.0 → 0.11.1
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 +9 -0
- package/engine-release.json +1 -1
- package/package-release.json +1 -1
- package/package.json +9 -1
- package/remote-adapter-claude-code.mjs +5 -3
- package/remote-adapter-codex.mjs +45 -5
- package/remote-adapter-terminal.mjs +248 -0
- package/remote-approval-bridge.mjs +30 -7
- package/remote-approvals.mjs +13 -3
- package/remote-cdp.mjs +60 -0
- package/remote-cli.mjs +7 -2
- package/remote-daemon.mjs +18 -3
- package/remote-inventory.mjs +14 -3
- package/remote-live-preview.mjs +205 -0
- package/remote-protocol.mjs +239 -110
- package/remote-run.mjs +18 -3
- package/remote-screen-approvals.mjs +79 -0
- package/remote-screen-push.mjs +76 -0
- package/remote-screen-states.mjs +113 -0
- package/remote-session-list.mjs +25 -2
- package/remote-sessions.mjs +10 -21
- package/remote-store.mjs +4 -3
- package/remote-terminal-cli.mjs +85 -0
- package/remote-terminal-sessions.mjs +291 -0
- package/worktrust.mjs +2 -2
package/remote-cdp.mjs
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE DEVTOOLS PROTOCOL OVER A PIPE (release 19, 2026-11-09; the live preview, remote-live-preview.mjs). Chrome is started
|
|
3
|
+
* with `--remote-debugging-pipe`: it reads commands from its file descriptor 3 and writes answers and events to 4, each
|
|
4
|
+
* message JSON ending in a NUL byte. NO DEBUGGING PORT IS EVER OPENED: no `--remote-debugging-port`, no TCP listener a
|
|
5
|
+
* page, another process or another computer could reach (held by test-remote-live-preview and check-remote-cli rule F).
|
|
6
|
+
*
|
|
7
|
+
* `createCdp({ write, onEvent })` is the client over any pair of pipes (a fake one in the tests): `send(method, params,
|
|
8
|
+
* sessionId)` resolves with the result or rejects with the error; `feed(chunk)` takes what the browser wrote.
|
|
9
|
+
*/
|
|
10
|
+
import { spawn } from "node:child_process";
|
|
11
|
+
|
|
12
|
+
export const MAX_MESSAGE = 32 * 1024 * 1024;
|
|
13
|
+
const CALL_MS = 15_000;
|
|
14
|
+
|
|
15
|
+
/** The browser on pipes: stdio 0-2 closed to us, 3 for commands, 4 for answers. Never a shell, never a port. */
|
|
16
|
+
export function spawnBrowserOnPipe(file, args, env) {
|
|
17
|
+
if (args.some((a) => /^--remote-debugging-(port|address)/.test(a))) throw new Error("a debugging port is never opened");
|
|
18
|
+
if (!args.includes("--remote-debugging-pipe")) throw new Error("the browser is driven over its pipe only");
|
|
19
|
+
const child = spawn(file, args, { stdio: ["ignore", "ignore", "ignore", "pipe", "pipe"], detached: process.platform !== "win32", windowsHide: true, env });
|
|
20
|
+
const exited = new Promise((resolve) => { child.on("exit", (code) => resolve(code)); child.on("error", () => resolve(-1)); });
|
|
21
|
+
return {
|
|
22
|
+
pid: child.pid,
|
|
23
|
+
write: (data) => { try { child.stdio[3].write(data); } catch { /* gone */ } },
|
|
24
|
+
onData: (fn) => { child.stdio[4].setEncoding("utf8"); child.stdio[4].on("data", fn); }, // utf8: a title split across chunks stays whole
|
|
25
|
+
exited,
|
|
26
|
+
kill: (signal = "SIGTERM") => { try { if (process.platform === "win32") child.kill(signal); else process.kill(-child.pid, signal); } catch { /* gone */ } },
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function createCdp({ write, onEvent }) {
|
|
31
|
+
let next = 0, buffer = "", closed = false;
|
|
32
|
+
const waiting = new Map();
|
|
33
|
+
return {
|
|
34
|
+
send(method, params = {}, sessionId = undefined) {
|
|
35
|
+
if (closed) return Promise.reject(new Error("closed"));
|
|
36
|
+
const id = ++next;
|
|
37
|
+
write(`${JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) })}\0`);
|
|
38
|
+
return new Promise((resolve, reject) => {
|
|
39
|
+
const timer = setTimeout(() => { waiting.delete(id); reject(new Error(`${method}: no answer`)); }, CALL_MS);
|
|
40
|
+
timer.unref?.();
|
|
41
|
+
waiting.set(id, { resolve, reject, timer });
|
|
42
|
+
});
|
|
43
|
+
},
|
|
44
|
+
feed(chunk) {
|
|
45
|
+
buffer += String(chunk);
|
|
46
|
+
if (buffer.length > MAX_MESSAGE) { buffer = ""; return; }
|
|
47
|
+
let end;
|
|
48
|
+
while ((end = buffer.indexOf("\0")) >= 0) {
|
|
49
|
+
const raw = buffer.slice(0, end); buffer = buffer.slice(end + 1);
|
|
50
|
+
let msg = null;
|
|
51
|
+
try { msg = JSON.parse(raw); } catch { continue; }
|
|
52
|
+
if (typeof msg?.id === "number" && waiting.has(msg.id)) {
|
|
53
|
+
const w = waiting.get(msg.id); waiting.delete(msg.id); clearTimeout(w.timer);
|
|
54
|
+
if (msg.error) w.reject(new Error(String(msg.error.message ?? "error"))); else w.resolve(msg.result ?? {});
|
|
55
|
+
} else if (typeof msg?.method === "string") onEvent(msg.method, msg.params ?? {}, msg.sessionId ?? null);
|
|
56
|
+
}
|
|
57
|
+
},
|
|
58
|
+
close() { closed = true; for (const w of waiting.values()) { clearTimeout(w.timer); w.reject(new Error("closed")); } waiting.clear(); },
|
|
59
|
+
};
|
|
60
|
+
}
|
package/remote-cli.mjs
CHANGED
|
@@ -21,6 +21,9 @@
|
|
|
21
21
|
* deems safe without asking, which the person accepts here
|
|
22
22
|
* remote releases [released <number>] the releases on this computer; mark a ready one released (the
|
|
23
23
|
* phone never can: publishing stays at the desk)
|
|
24
|
+
* remote terminal on | off | list | start [<folder>] and remote attach <id> terminal sessions (release 19): Claude Code
|
|
25
|
+
* in tmux on WorkTrust's own socket, seen on the phone, attached here
|
|
26
|
+
* (remote-terminal-cli.mjs; off by default)
|
|
24
27
|
*/
|
|
25
28
|
import { basename } from "node:path";
|
|
26
29
|
import { hostname } from "node:os";
|
|
@@ -43,7 +46,7 @@ import { checkRoot, MAX_ROOTS, rootIdOf, rootLabel } from "./remote-projects.mjs
|
|
|
43
46
|
const fingerprintOf = (keys) => P.deviceFingerprint(keys.public);
|
|
44
47
|
const pretty = (code) => `${code.slice(0, 4)}-${code.slice(4)}`;
|
|
45
48
|
/** A question only a person at this keyboard answers: a terminal, a typed "yes"; --yes and Enter are No. */
|
|
46
|
-
async function askTyped(question) {
|
|
49
|
+
export async function askTyped(question) {
|
|
47
50
|
if (!process.stdin.isTTY) return false;
|
|
48
51
|
const prompt = createInterface({ input: process.stdin, output: process.stdout });
|
|
49
52
|
const answer = (await prompt.question(` ${question} Type yes to confirm: `)).trim().toLowerCase();
|
|
@@ -321,5 +324,7 @@ export async function remoteCommand(args, io) {
|
|
|
321
324
|
return;
|
|
322
325
|
}
|
|
323
326
|
if (sub === "releases") return releasesCommand(io, rest);
|
|
324
|
-
|
|
327
|
+
if (sub === "terminal") return (await import("./remote-terminal-cli.mjs")).terminalCommand(io, rest, askTyped);
|
|
328
|
+
if (sub === "attach") return (await import("./remote-terminal-cli.mjs")).attachCommand(io, rest);
|
|
329
|
+
io.say(" npx worktrust remote enable | pair | status | pause | resume | disable [--forget] | phones [confirm|remove <id>] | projects add|remove|list | run | pipeline review <folder>|status | roots add|remove|list | preview allow|deny|list | codex on|off | terminal on|off|list|start | attach <id> | releases [released <n>]");
|
|
325
330
|
}
|
package/remote-daemon.mjs
CHANGED
|
@@ -16,6 +16,7 @@ import { confirmedFingerprints, controllerKeys, loadChannels, loadPhones, loadPr
|
|
|
16
16
|
import { createProject, rootLabel, worktreeMain } from "./remote-projects.mjs";
|
|
17
17
|
|
|
18
18
|
// What a paused computer still answers: reading, configuring, disconnecting, and taking work away (a pipeline's cancel).
|
|
19
|
+
const LIVE_COMMANDS = new Set(["preview.live_start", "preview.live_input", "preview.live_viewport", "preview.live_follow"]);
|
|
19
20
|
const DEVICE_COMMANDS = new Set(["inventory.get", "device.configure", "status.get", "pairing.revoke", "release.list", "pipeline.cancel"]);
|
|
20
21
|
const KEEP_REMOVED = 20;
|
|
21
22
|
const MAX_PENDING_PHONES = 10;
|
|
@@ -31,7 +32,7 @@ export function createDaemonCore(o) {
|
|
|
31
32
|
function sealAll(record) {
|
|
32
33
|
for (const [id, channel] of channels) {
|
|
33
34
|
if (!confirmed().has(channel.peer_fingerprint)) { channels.delete(id); continue; } // a revoked phone hears nothing
|
|
34
|
-
const draft = { protocol_version: channel.protocol_version, session_id: record.session_id, device_id: self, event_seq: record.event_seq, type: record.type, occurred_at: record.occurred_at, command_id: record.command_id, notify: record.notify };
|
|
35
|
+
const draft = { protocol_version: channel.protocol_version, session_id: record.session_id, device_id: self, event_seq: record.event_seq, type: record.type, occurred_at: record.occurred_at, command_id: record.command_id, notify: record.notify, ...(record.lane ? { lane: record.lane } : {}) };
|
|
35
36
|
const sealed = P.sealEvent(channel, draft, record.body, o.random);
|
|
36
37
|
if (!sealed.ok) { o.log("seal_refused", { type: record.type, code: sealed.code }); continue; }
|
|
37
38
|
channels.set(id, sealed.value.channel);
|
|
@@ -40,7 +41,13 @@ export function createDaemonCore(o) {
|
|
|
40
41
|
persist();
|
|
41
42
|
}
|
|
42
43
|
|
|
43
|
-
|
|
44
|
+
/**
|
|
45
|
+
* `transient` (release 19; a pushed terminal screen, remote-screen-push.mjs): the session's TRANSIENT LANE
|
|
46
|
+
* (envelopes.ts), sealed for the phones and never journaled, so a replay never brings back a stale screen and the
|
|
47
|
+
* session's own sequence has no number missing. Its numbers rise per session from this computer's clock.
|
|
48
|
+
*/
|
|
49
|
+
const laneSeq = new Map();
|
|
50
|
+
function emit(sessionId, type, body, commandId = null, notify = "none", { transient = false } = {}) {
|
|
44
51
|
let shaped = P.validateEventBody(type, body);
|
|
45
52
|
if (!shaped.ok && type === "agent.completed" && body.result) {
|
|
46
53
|
// A result over its caps keeps the reply and names the files; the diffs are said to be cut.
|
|
@@ -49,6 +56,11 @@ export function createDaemonCore(o) {
|
|
|
49
56
|
shaped = P.validateEventBody(type, body);
|
|
50
57
|
}
|
|
51
58
|
if (!shaped.ok) { o.log("event_refused", { type, detail: shaped.code }); return; }
|
|
59
|
+
if (transient) {
|
|
60
|
+
const seq = Math.max((laneSeq.get(sessionId) ?? 0) + 1, o.now());
|
|
61
|
+
laneSeq.set(sessionId, seq);
|
|
62
|
+
return sealAll({ session_id: sessionId, event_seq: seq, type, occurred_at: o.now(), command_id: null, notify: "none", lane: "transient", body });
|
|
63
|
+
}
|
|
52
64
|
const record = { session_id: sessionId, event_seq: o.journal.nextSeq(sessionId), type, occurred_at: o.now(), command_id: commandId, notify, body };
|
|
53
65
|
o.journal.recordEvent(record);
|
|
54
66
|
sealAll(record);
|
|
@@ -140,7 +152,10 @@ export function createDaemonCore(o) {
|
|
|
140
152
|
if (P.RELEASE_COMMANDS.has(env.type)) return releases ? releases.handle(env, payload) : "unsupported"; // remote-releases.mjs
|
|
141
153
|
if (env.type === "attachment.put" || env.type === "attachment.clear") return o.attachments ? o.attachments.handle(env, payload) : "unsupported"; // remote-attachments.mjs
|
|
142
154
|
if (env.type === "preview.targets" || env.type === "preview.render") return o.preview ? o.preview.handle(env, payload) : "unsupported"; // remote-preview.mjs
|
|
143
|
-
return
|
|
155
|
+
if (LIVE_COMMANDS.has(env.type)) return o.live ? o.live.handle(env, payload) : "unsupported"; // remote-live-preview.mjs
|
|
156
|
+
const handled = await sessions.handle(env, payload);
|
|
157
|
+
if (env.type === "session.close") await o.live?.sessionClosed(env.session_id); // its live preview ends with it
|
|
158
|
+
return handled;
|
|
144
159
|
}
|
|
145
160
|
|
|
146
161
|
/** The order of this function is the at-most-once rule (see the header). */
|
package/remote-inventory.mjs
CHANGED
|
@@ -16,6 +16,8 @@ import { existsSync, statSync } from "node:fs";
|
|
|
16
16
|
import { delimiter, join } from "node:path";
|
|
17
17
|
import * as P from "./remote-protocol.mjs";
|
|
18
18
|
import { codexReport } from "./remote-adapter-codex.mjs";
|
|
19
|
+
import { terminalReport, tmuxVersion } from "./remote-adapter-terminal.mjs";
|
|
20
|
+
import { typingTrusted } from "./remote-screen-states.mjs";
|
|
19
21
|
|
|
20
22
|
const NO = Object.freeze({ start: false, attach: false, prompt: false, steer: false, pause: false, resume: false, stop: false, structured_events: false, screen: false, focus: false, resume_by_id: false, permission_modes: ["ask"], approvals: "none", acceptance: "acknowledged" });
|
|
21
23
|
export const AGENTS = Object.freeze({ "claude-code": "claude", codex: "codex", "cursor-agent": "cursor-agent", opencode: "opencode" });
|
|
@@ -115,7 +117,12 @@ export function inventory({ env = process.env, refresh = false, now = Date.now()
|
|
|
115
117
|
const checked = P.validateAdapterReport(report);
|
|
116
118
|
if (!checked.ok) throw new Error(`inventory: ${report.adapter}: ${checked.detail}`);
|
|
117
119
|
}
|
|
118
|
-
|
|
120
|
+
// Claude Code in a terminal (release 19): tmux on its own socket. Kept beside the reports, sent only when turned on (offered).
|
|
121
|
+
const tmux = findOnPath("tmux", env.PATH), claude = reports.find((r) => r.adapter === "claude-code");
|
|
122
|
+
const terminal = terminalReport({ claude: claude?.installed ? { ...claude, features: features["claude-code"] } : null, tmux: tmux ? tmuxVersion(probe(tmux, ["-V"], env)) : null });
|
|
123
|
+
const checkedTerminal = P.validateAdapterReport(terminal);
|
|
124
|
+
if (!checkedTerminal.ok) throw new Error(`inventory: claude-code (terminal): ${checkedTerminal.detail}`);
|
|
125
|
+
cache = { reports, features, terminal, files: { ...Object.fromEntries(Object.keys(AGENTS).map((a) => [a, findOnPath(AGENTS[a], env.PATH)])), tmux }, at: now };
|
|
119
126
|
return cache;
|
|
120
127
|
}
|
|
121
128
|
export const adapterOf = (inv, id) => inv.reports.find((r) => r.adapter === id);
|
|
@@ -127,6 +134,10 @@ export const adapterOf = (inv, id) => inv.reports.find((r) => r.adapter === id);
|
|
|
127
134
|
* listed as installed and offered nothing.
|
|
128
135
|
*/
|
|
129
136
|
export function offered(inv, settings) {
|
|
130
|
-
|
|
131
|
-
|
|
137
|
+
const reports = settings?.codex === true ? inv.reports : inv.reports.map((r) => (r.adapter === "codex" && r.capabilities.start ? { ...r, capabilities: NO } : r));
|
|
138
|
+
// Terminal sessions (release 19) only after `worktrust remote terminal on`: an older phone refuses a second report of one adapter.
|
|
139
|
+
// Typing from a phone only on a screen detector whose fixtures were recorded from the real agent (remote-screen-states.mjs).
|
|
140
|
+
// Answering its dialogs from a phone (screen-hash approvals) needs the same: approvals "screen" only then.
|
|
141
|
+
const terminal = inv.terminal?.capabilities.start && typingTrusted("claude-code") ? { ...inv.terminal, capabilities: { ...inv.terminal.capabilities, prompt: true, approvals: "screen" } } : inv.terminal;
|
|
142
|
+
return { ...inv, reports: settings?.terminal === true && terminal ? [...reports, terminal] : reports };
|
|
132
143
|
}
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE LIVE PREVIEW (release 19, 2026-11-09; owner's preview option A; PROTOCOL.md "The live preview"). The session's
|
|
3
|
+
* granted dev page, live and touchable on the phone: the person's own Chrome, headless, in a throw-away profile, driven over
|
|
4
|
+
* its PIPE (remote-cdp.mjs: never a debugging port), its screencast sent as JPEG frames on the session's transient lane, the
|
|
5
|
+
* phone's taps, scrolls and literal text applied as input events.
|
|
6
|
+
*
|
|
7
|
+
* THE PAGE STAYS ON THE GRANTED ORIGIN, held three ways (each one tested):
|
|
8
|
+
* 1. the network: every request goes to a dead proxy except the granted origin (`--proxy-server` with
|
|
9
|
+
* `--proxy-bypass-list=<-loopback>;127.0.0.1:<port>`), so nothing else is reachable, not even another local port;
|
|
10
|
+
* 2. the DevTools protocol: every request of every frame and worker is paused (Fetch) and continued only for the granted
|
|
11
|
+
* origin; anything else is failed and counted (a document as a navigation, the rest as requests); a page that still
|
|
12
|
+
* lands elsewhere (file://, a scheme) is sent back and counted; a new page (a popup) is closed; a download is denied;
|
|
13
|
+
* a dialog is dismissed; permission prompts are denied by the browser's own switch;
|
|
14
|
+
* 3. the phone: it names a PATH on the granted target, never a URL; input coordinates must lie inside the viewport;
|
|
15
|
+
* text is inserted literally; keys come from a list of three.
|
|
16
|
+
* One live preview per computer. It stops when nobody follows it (LIVE_FOLLOW_MS), when its session closes, when the
|
|
17
|
+
* browser exits, or on follow:false; the browser is ended and its profile and the file server removed.
|
|
18
|
+
*/
|
|
19
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
20
|
+
import { tmpdir } from "node:os";
|
|
21
|
+
import { join } from "node:path";
|
|
22
|
+
import * as P from "./remote-protocol.mjs";
|
|
23
|
+
import { createCdp, spawnBrowserOnPipe } from "./remote-cdp.mjs";
|
|
24
|
+
import { findBrowser, listening, serveProject } from "./remote-preview.mjs";
|
|
25
|
+
|
|
26
|
+
export const FRAME_MS = 200;
|
|
27
|
+
export const LIVE_FOLLOW_MS = 90_000;
|
|
28
|
+
const KEYCODE = { Enter: 13, Backspace: 8, Tab: 9 };
|
|
29
|
+
|
|
30
|
+
/** The command line: headless, its own profile, on its pipe, and a network that reaches the granted origin only. */
|
|
31
|
+
export function liveArgs({ profile, port }) {
|
|
32
|
+
return ["--headless=new", "--remote-debugging-pipe", `--user-data-dir=${profile}`, "--no-first-run", "--no-default-browser-check", "--disable-extensions", "--disable-sync",
|
|
33
|
+
"--mute-audio", "--hide-scrollbars", "--disable-background-networking", "--disable-component-update", "--disable-default-apps", "--deny-permission-prompts", "--block-new-web-contents",
|
|
34
|
+
"--proxy-server=127.0.0.1:9", `--proxy-bypass-list=<-loopback>;127.0.0.1:${port}`, "about:blank"];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The one origin a page may load from: http, 127.0.0.1, the granted (or file server's) port. */
|
|
38
|
+
export const originOk = (url, port) => { try { const u = new URL(url); return u.protocol === "http:" && u.hostname === "127.0.0.1" && u.port === String(port); } catch { return false; } };
|
|
39
|
+
const toB64Url = (s) => s.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
40
|
+
|
|
41
|
+
// ctx: { emit, projects(), grants(), sessionProject(id), env(), log, now, spawnBrowser?, browser?(), listening?(port), serve?(root), followMs?, frameMs? }
|
|
42
|
+
export function createLivePreview(ctx) {
|
|
43
|
+
let live = null; // one per computer
|
|
44
|
+
const followMs = ctx.followMs ?? LIVE_FOLLOW_MS, frameMs = ctx.frameMs ?? FRAME_MS;
|
|
45
|
+
const later = (fn, ms) => { const t = setTimeout(fn, ms); t.unref?.(); return t; };
|
|
46
|
+
const state = (l, s, reason = null) => {
|
|
47
|
+
l.state = s;
|
|
48
|
+
ctx.emit(l.session_id, "preview.live", { state: s, viewport: l.viewport, width: l.vp.width, height: l.vp.height, title: l.title, path: l.path, blocked: { ...l.blocked }, reason }, null);
|
|
49
|
+
};
|
|
50
|
+
const block = (l, kind) => { l.blocked[kind] += 1; if (!l.stopped) l.dirty(); };
|
|
51
|
+
|
|
52
|
+
async function stop(l, reason) {
|
|
53
|
+
if (!l || l.stopped) return;
|
|
54
|
+
l.stopped = true;
|
|
55
|
+
clearTimeout(l.expiry); clearTimeout(l.frameTimer);
|
|
56
|
+
if (live === l) live = null;
|
|
57
|
+
// The browser first, then its files: it asked to close, then its process group ended, each with a grace, and only
|
|
58
|
+
// once it is gone the profile is removed (a browser still writing into it would leave it behind).
|
|
59
|
+
const gone = (ms) => { let t; return Promise.race([l.proc.exited.then(() => true), new Promise((r) => { t = setTimeout(() => r(false), ms); })]).finally(() => clearTimeout(t)); }; // held: a stop finishes
|
|
60
|
+
await Promise.race([l.cdp.send("Browser.close").catch(() => {}), gone(2000)]);
|
|
61
|
+
l.cdp.close();
|
|
62
|
+
if (!(await gone(2000))) { l.proc.kill("SIGTERM"); if (!(await gone(2000))) { l.proc.kill("SIGKILL"); await gone(2000); } }
|
|
63
|
+
l.proc.kill("SIGKILL"); // what is left of its group (a renderer, a helper)
|
|
64
|
+
l.server?.close();
|
|
65
|
+
try { rmSync(l.profile, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); } catch { ctx.log("live_profile_left", {}); }
|
|
66
|
+
state(l, reason === "browser_exited" || reason === "failed" ? "failed" : "stopped", reason);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Newest frame wins; at most one per frameMs; none unless someone follows (an expired follow stops the preview). */
|
|
70
|
+
function offerFrame(l, frame) {
|
|
71
|
+
l.frame = frame;
|
|
72
|
+
if (l.frameTimer) return;
|
|
73
|
+
const wait = l.sentAt + frameMs - ctx.now();
|
|
74
|
+
const go = () => { l.frameTimer = null; const f = l.frame; l.frame = null; if (!f || l.stopped) return; l.sentAt = ctx.now(); ctx.emit(l.session_id, "preview.frame", f, null, "none", { transient: true }); };
|
|
75
|
+
if (wait <= 0) go(); else l.frameTimer = later(go, wait);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async function onEvent(l, method, p, sessionId) {
|
|
79
|
+
const cdp = l.cdp;
|
|
80
|
+
if (method === "Target.attachedToTarget") {
|
|
81
|
+
const sid = p.sessionId, info = p.targetInfo ?? {};
|
|
82
|
+
// The browser's own first page (no opener) is the preview's page; any other page is a popup, closed.
|
|
83
|
+
if (info.type === "page" && !l.targetId && !info.openerId) l.targetId = info.targetId;
|
|
84
|
+
else if (info.type === "page" && info.targetId !== l.targetId) { block(l, "popup"); await cdp.send("Target.closeTarget", { targetId: info.targetId }).catch(() => {}); return; }
|
|
85
|
+
// Every frame and worker of the page passes the same interception, and so do the ones they start.
|
|
86
|
+
await cdp.send("Fetch.enable", { patterns: [{ urlPattern: "*" }] }, sid).catch(() => {});
|
|
87
|
+
await cdp.send("Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: true, flatten: true }, sid).catch(() => {});
|
|
88
|
+
if (info.targetId === l.targetId && !l.pageSession) await page(l, sid);
|
|
89
|
+
await cdp.send("Runtime.runIfWaitingForDebugger", {}, sid).catch(() => {});
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
if (method === "Fetch.requestPaused") {
|
|
93
|
+
if (originOk(p.request?.url, l.port)) return void cdp.send("Fetch.continueRequest", { requestId: p.requestId }, sessionId).catch(() => {});
|
|
94
|
+
block(l, p.resourceType === "Document" ? "navigation" : "request");
|
|
95
|
+
return void cdp.send("Fetch.failRequest", { requestId: p.requestId, errorReason: "BlockedByClient" }, sessionId).catch(() => {});
|
|
96
|
+
}
|
|
97
|
+
if (method === "Page.frameNavigated" && sessionId === l.pageSession && !p.frame?.parentId) {
|
|
98
|
+
const url = String(p.frame?.url ?? "");
|
|
99
|
+
if (url === "about:blank") return;
|
|
100
|
+
if (originOk(url, l.port)) { l.path = new URL(url).pathname.slice(0, 300) || "/"; l.good = url; return; }
|
|
101
|
+
// A navigation the interception failed lands on the browser's error page: back, counted once (by the interception).
|
|
102
|
+
if (!url.startsWith("chrome-error:")) block(l, url.startsWith("file:") ? "file" : "navigation");
|
|
103
|
+
return void cdp.send("Page.navigate", { url: l.good }, l.pageSession).catch(() => {});
|
|
104
|
+
}
|
|
105
|
+
if (method === "Page.screencastFrame" && sessionId === l.pageSession) {
|
|
106
|
+
cdp.send("Page.screencastFrameAck", { sessionId: p.sessionId }, l.pageSession).catch(() => {});
|
|
107
|
+
const data = toB64Url(String(p.data ?? ""));
|
|
108
|
+
if (Math.floor(data.length * 3 / 4) > P.MAX_FRAME_BYTES) return ctx.log("live_frame_dropped", {});
|
|
109
|
+
const m = p.metadata ?? {};
|
|
110
|
+
offerFrame(l, { width: Math.max(1, Math.min(4096, Math.round(m.deviceWidth ?? l.vp.width))), height: Math.max(1, Math.min(16_384, Math.round(m.deviceHeight ?? l.vp.height))), data });
|
|
111
|
+
if (l.state !== "live") { l.state = "live"; l.dirty(); }
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
if (method === "Page.loadEventFired" && sessionId === l.pageSession) {
|
|
115
|
+
const r = await cdp.send("Runtime.evaluate", { expression: "document.title", returnByValue: true }, l.pageSession).catch(() => null);
|
|
116
|
+
const t = typeof r?.result?.value === "string" ? r.result.value.trim().slice(0, 300) : "";
|
|
117
|
+
l.title = t || null; l.dirty();
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
if (method === "Page.javascriptDialogOpening" && sessionId === l.pageSession) { block(l, "popup"); return void cdp.send("Page.handleJavaScriptDialog", { accept: false }, l.pageSession).catch(() => {}); }
|
|
121
|
+
if (method === "Browser.downloadWillBegin") block(l, "download");
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async function viewportOf(l) {
|
|
125
|
+
const mobile = l.viewport !== "desktop";
|
|
126
|
+
await l.cdp.send("Page.stopScreencast", {}, l.pageSession).catch(() => {}); // a second start alone keeps the old size
|
|
127
|
+
await l.cdp.send("Emulation.setDeviceMetricsOverride", { width: l.vp.width, height: l.vp.height, deviceScaleFactor: 1, mobile }, l.pageSession).catch(() => {});
|
|
128
|
+
await l.cdp.send("Page.startScreencast", { format: "jpeg", quality: 60, maxWidth: l.vp.width, maxHeight: l.vp.height, everyNthFrame: 1 }, l.pageSession).catch(() => {});
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async function page(l, sid) {
|
|
132
|
+
l.pageSession = sid;
|
|
133
|
+
await l.cdp.send("Page.enable", {}, sid).catch(() => {});
|
|
134
|
+
await viewportOf(l);
|
|
135
|
+
l.cdp.send("Page.navigate", { url: l.url }, sid).catch(() => {});
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async function start(env, p) {
|
|
139
|
+
const project = ctx.sessionProject(env.session_id);
|
|
140
|
+
if (!project) return "not_found";
|
|
141
|
+
const g = ctx.grants()[project.project_id] ?? { ports: [], files: [] };
|
|
142
|
+
if (p.target === "port" ? !(g.ports ?? []).includes(p.port) : !(g.files ?? []).includes(p.path)) return "unsupported"; // granted at the keyboard only
|
|
143
|
+
const browser = (ctx.browser ?? (() => findBrowser(ctx.env())))();
|
|
144
|
+
if (!browser) return "unsupported";
|
|
145
|
+
if (live && live.session_id !== env.session_id) return "busy"; // one live preview per computer
|
|
146
|
+
if (live) await stop(live, "stopped");
|
|
147
|
+
if (p.target === "port" && !(await (ctx.listening ?? listening)(p.port))) return "not_found";
|
|
148
|
+
const server = p.target === "file" ? await (ctx.serve ?? serveProject)(project.path) : null;
|
|
149
|
+
const port = p.target === "port" ? p.port : server.port;
|
|
150
|
+
const profile = mkdtempSync(join(tmpdir(), "wt-live-"));
|
|
151
|
+
const l = { session_id: env.session_id, viewport: p.viewport, vp: P.PREVIEW_VIEWPORTS[p.viewport], port, server, profile, title: null, path: p.target === "port" ? p.path : `/${p.path}`, url: `http://127.0.0.1:${port}${p.target === "port" ? p.path : `/${p.path}`}`,
|
|
152
|
+
good: "about:blank", blocked: { ...P.NO_BLOCKS }, state: "starting", stopped: false, sentAt: -Infinity, frame: null, frameTimer: null, expiry: null, pageSession: null, targetId: null };
|
|
153
|
+
let dirtyTimer = null;
|
|
154
|
+
l.dirty = () => { if (!dirtyTimer) dirtyTimer = later(() => { dirtyTimer = null; if (!l.stopped) state(l, l.state); }, 250); };
|
|
155
|
+
l.proc = (ctx.spawnBrowser ?? spawnBrowserOnPipe)(browser, liveArgs({ profile: join(profile, "p"), port }), ctx.env());
|
|
156
|
+
l.cdp = createCdp({ write: l.proc.write, onEvent: (m, params, sid) => { onEvent(l, m, params, sid).catch(() => {}); } });
|
|
157
|
+
l.proc.onData((chunk) => l.cdp.feed(chunk));
|
|
158
|
+
l.proc.exited.then(() => { if (!l.stopped) stop(l, "browser_exited"); });
|
|
159
|
+
live = l;
|
|
160
|
+
l.expiry = later(() => stop(l, "unfollowed"), followMs);
|
|
161
|
+
state(l, "starting");
|
|
162
|
+
try {
|
|
163
|
+
await l.cdp.send("Browser.setDownloadBehavior", { behavior: "deny", eventsEnabled: true });
|
|
164
|
+
await l.cdp.send("Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: true, flatten: true });
|
|
165
|
+
// A browser that attached no first page of its own is given one (its attach event makes it the preview's page).
|
|
166
|
+
later(() => { if (!l.targetId && !l.stopped) l.cdp.send("Target.createTarget", { url: "about:blank" }).catch(() => {}); }, 1500);
|
|
167
|
+
} catch { await stop(l, "failed"); return "unsupported"; }
|
|
168
|
+
return "taken";
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
async function input(l, i) {
|
|
172
|
+
if (i.kind === "tap" || i.kind === "scroll") {
|
|
173
|
+
if (i.x >= l.vp.width || i.y >= l.vp.height) return "unsupported"; // inside the viewport only
|
|
174
|
+
if (i.kind === "scroll") return (await l.cdp.send("Input.dispatchMouseEvent", { type: "mouseWheel", x: i.x, y: i.y, deltaX: 0, deltaY: i.dy }, l.pageSession).then(() => "taken", () => "not_found"));
|
|
175
|
+
for (const type of ["mousePressed", "mouseReleased"]) await l.cdp.send("Input.dispatchMouseEvent", { type, x: i.x, y: i.y, button: "left", clickCount: 1 }, l.pageSession).catch(() => {});
|
|
176
|
+
return "taken";
|
|
177
|
+
}
|
|
178
|
+
if (i.kind === "text") { if (!P.liveTextOk(i.text)) return "unsupported"; return l.cdp.send("Input.insertText", { text: i.text }, l.pageSession).then(() => "taken", () => "not_found"); }
|
|
179
|
+
if (!Object.hasOwn(KEYCODE, i.key)) return "unsupported";
|
|
180
|
+
const code = KEYCODE[i.key];
|
|
181
|
+
await l.cdp.send("Input.dispatchKeyEvent", { type: "keyDown", key: i.key, code: i.key, windowsVirtualKeyCode: code, ...(i.key === "Enter" ? { text: "\r" } : {}) }, l.pageSession).catch(() => {});
|
|
182
|
+
await l.cdp.send("Input.dispatchKeyEvent", { type: "keyUp", key: i.key, code: i.key, windowsVirtualKeyCode: code }, l.pageSession).catch(() => {});
|
|
183
|
+
return "taken";
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
return {
|
|
187
|
+
current: () => live,
|
|
188
|
+
async handle(env, payload) {
|
|
189
|
+
if (env.type === "preview.live_start") return start(env, payload);
|
|
190
|
+
const l = live && live.session_id === env.session_id ? live : null;
|
|
191
|
+
if (!l || l.stopped) return "not_found";
|
|
192
|
+
if (env.type === "preview.live_follow") {
|
|
193
|
+
if (!payload.follow) { await stop(l, "stopped"); return "taken"; }
|
|
194
|
+
clearTimeout(l.expiry); l.expiry = later(() => stop(l, "unfollowed"), followMs);
|
|
195
|
+
return "taken";
|
|
196
|
+
}
|
|
197
|
+
if (env.type === "preview.live_viewport") { l.viewport = payload.viewport; l.vp = P.PREVIEW_VIEWPORTS[payload.viewport]; await viewportOf(l); l.dirty(); return "taken"; }
|
|
198
|
+
if (env.type === "preview.live_input") return input(l, payload);
|
|
199
|
+
return "unsupported";
|
|
200
|
+
},
|
|
201
|
+
/** The session closed: its live preview ends. */
|
|
202
|
+
sessionClosed: (sessionId) => (live && live.session_id === sessionId ? stop(live, "closed") : undefined),
|
|
203
|
+
stopAll: () => (live ? stop(live, "stopped") : undefined),
|
|
204
|
+
};
|
|
205
|
+
}
|