Files
Netcatty/electron/bridges/scriptBridge.cjs
T
陈大猫andCursor 6b9b71ac8a feat(scripts): terminal script automation, recording, and side panel (#1763)
* feat(scripts): add terminal script automation, recording, and side panel

Introduce nct script runtime in the main process with terminal-side recording,
execution overlay, Monaco editor, connect-script queues, and scripts side panel
integration. Fix recording to wire scriptRecorderRef into xterm, use waitForPrompt
for root/user shells, and save recorded scripts through the global editor dialog.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(scripts): address Bugbot review findings for recording and side panel

Refresh script run state in side panel memo, guard toolbar recording against
multi-session conflicts, reset connect scripts on reconnect, resolve focused
session via getActiveTerminalSessionId, and avoid wiping host edit form when
snippets list updates.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(scripts): prevent pending script re-run and improve workspace run feedback

Track one-shot pendingScript execution separately from onConnect queue so
reconnects do not replay Run-now scripts. Fall back to focused session when
running on all tabs outside a workspace, and toast when every tab is still
connecting.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(scripts): consume connect-script window once and filter serial hosts

Mark the onConnect script evaluation as consumed even when the queue is
empty so later snippet/host edits do not rerun automation mid-session.
Restore serial-host filtering in SelectHostPanel confirm handler.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(scripts): grace period before giving up on connect-script queue

Only mark onConnect automation as consumed after scripts run or a short
post-connect grace window expires, so late-loading snippets still trigger
while mid-session Vault edits do not.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(scripts): gate connect-script consumption on vault hydration

Replace the grace timer with vault-init and unresolved host script binding
checks so late-loading snippets still run onConnect automation while
mid-session edits stay suppressed. Clear pending script run state on
disconnect so reconnect retries workspace pending scripts.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(scripts): honor run targets and retry failed connect automation

Route QuickScriptEditorDialog Run through onRunSnippet for multi-host
workspaces. Defer connect/pending script completion markers until each
script succeeds and retry the queue after failures.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(scripts): stabilize pending runs and global connect queue sync

Keep pending script run state across reconnects, run onConnect scripts
before one-shot workspace pending scripts, and strip per-host queue entries
when an onConnect script targets all hosts.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(scripts): defer host queue snippet sync and guard connect runs

Persist snippet target links only when the host panel is saved, block
duplicate connect-script scheduling while a batch is running, and require
runnable hosts before showing Run in the snippets editor footer.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(scripts): retry connect failures and surface output-trigger errors

Use a retry tick in connect-script effect deps, toast automation failures
from output triggers, and require runnable hosts before QuickScript Run.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(scripts): track id-less pending runs and re-arm output triggers

Remember anonymous pendingScript objects after first run and allow
onOutput triggers to fire again when new terminal output arrives.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(scripts): unblock paused connect runs and pass session meta

Resolve waitForScriptRun on pause, run workspace scripts per session
with hostname context, defer output-trigger arming until runs start, and
add noRunnableHosts i18n for QuickScript Run.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(scripts): serialize output triggers and defer empty connect finalize

Fire at most one onOutput trigger per scan while a run is active, and
only finalize an empty connect queue after vault snippets are loaded.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(scripts): guard output launch race and script run waits

Block overlapping onOutput launches, timeout stuck waitForScriptRun
promises, and disable vault Run when no connectable targets exist.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(scripts): match output triggers on new chunks only

Scan onOutput patterns against recent terminal output instead of buffer
length dedupe, and restore overflow-visible on SelectHostPanel new-host flow.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(scripts): await sequential workspace runs and output launch

Wait for each tab script to finish in sequential workspace mode, and hold
output-trigger launch guard until the session run becomes active.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(scripts): wait through pause and hold output trigger until done

Keep connect and sequential workspace queues blocked until scripts
complete or fail, and retain output-trigger guard until the launched run
finishes.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(scripts): harden output trigger wait helpers

Add explicit timeouts to output-trigger wait helpers and stop rescanning
the buffer after script completion to avoid sticky-match rerun loops.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(scripts): allow empty connect queue and match output in new chunks

Treat an empty connectScriptIds array as an explicit cleared queue instead
of re-migrating from snippet targets, and only fire onOutput triggers when
the latest terminal output contains the pattern.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(scripts): require fresh output overlap for onOutput triggers

Only fire output-matched scripts when the regex match extends into the
latest terminal chunk, preventing reruns from stale buffer text.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(scripts): promote manual scripts added to host connect queue

Diff connect queue changes from raw connectScriptIds so saving a host
updates manual scripts to onConnect when they are newly queued.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(scripts): dedupe output triggers by match position

Track the buffer end offset of each output trigger match and ignore
stale re-scans, with a longer wait for run registration before retry.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(scripts): record output trigger matches only after run starts

Propagate automation launch failures to output triggers and commit match
dedupe only once the session run is registered as active.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(scripts): address Codex review on wait cursor and sensitive codegen

Track scan offset so waitFor/waitForAny only match output after the previous wait, and emit sendLine after sensitive prompt in recorded scripts.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(scripts): harden onOutput triggers against PTY echo and local input

Filter server output before pattern matching so onOutput fires only after
Enter on real stdout, not on keystroke/paste echo, OSC/SGR sequences, or
alternate-screen apps. Add dev diagnostics and scope triggers to the active
session when no explicit host targets are configured.

Co-authored-by: Cursor <cursoragent@cursor.com>

* chore(scripts): remove onOutput trigger debug logging

Drop temporary diagnostics module and console traces now that PTY echo
filtering is verified; keep the production trigger pipeline unchanged.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-28 23:48:12 +08:00

585 lines
17 KiB
JavaScript

"use strict";
const path = require("node:path");
const { randomUUID } = require("node:crypto");
const { createScriptRuntime } = require("../scripts/scriptRuntime.cjs");
const { stepsToJavaScript } = require("../scripts/scriptCodegen.cjs");
const {
appendSessionOutput,
getOrCreateBuffer,
removeSessionBuffer,
} = require("../scripts/sessionOutputBuffer.cjs");
const { addTerminalDataTap } = require("../bridges/emitTerminalSessionData.cjs");
const sessionLogStreamManager = require("./sessionLogStreamManager.cjs");
let sessions = null;
let electronModule = null;
let terminalBridge = null;
let terminalWorkerManager = null;
let getMainWindow = null;
/** @type {Map<string, object>} */
const runs = new Map();
/** @type {Map<string, object>} */
const recordings = new Map();
/** @type {Map<string, { resolve, reject, type }>} */
const pendingDialogs = new Map();
/** @type {Map<string, { resolve, reject, sessionId }>} */
const pendingScreenSnapshots = new Map();
/** @type {Map<string, symbol>} */
const scriptLogTokens = new Map();
/** @type {Map<string, Promise<void>>} */
const sessionRunChains = new Map();
/** @type {Map<string, { connected?: boolean, hostname?: string, username?: string }>} */
const rendererSessionMetaById = new Map();
function enqueueSessionRun(sessionId, task) {
const previous = sessionRunChains.get(sessionId) || Promise.resolve();
const next = previous
.catch(() => {})
.then(() => task());
sessionRunChains.set(
sessionId,
next.then(() => {}, () => {}),
);
return next;
}
function init(deps) {
sessions = deps.sessions;
electronModule = deps.electronModule;
terminalBridge = deps.terminalBridge;
terminalWorkerManager = deps.terminalWorkerManager || null;
getMainWindow = deps.getMainWindow;
addTerminalDataTap((sessionId, data) => {
appendSessionOutput(sessionId, data);
});
terminalWorkerManager?.addOutputTap?.((sessionId, data) => {
appendSessionOutput(sessionId, data);
});
}
function broadcastRuns() {
const win = getMainWindow?.();
if (!win?.webContents) return;
win.webContents.send("netcatty:script:runs-updated", {
runs: Array.from(runs.values()).map(serializeRun),
});
}
function serializeRun(run) {
const now = Date.now();
const elapsedMs = run.endedAt
? run.endedAt - run.startedAt
: Math.max(0, now - run.startedAt);
return {
runId: run.runId,
scriptId: run.scriptId,
scriptLabel: run.scriptLabel,
sessionId: run.sessionId,
status: run.status,
startedAt: run.startedAt,
endedAt: run.endedAt,
currentStep: run.currentStep,
stepIndex: run.stepIndex,
totalSteps: run.totalSteps,
progressMode: run.progressMode || "activity",
activityLabel: run.activityLabel,
progressLabel: run.progressLabel,
progressCurrent: run.progressCurrent,
progressTotal: run.progressTotal,
elapsedMs,
waitingFor: run.waitingFor,
logs: run.logs.slice(-200),
error: run.error,
};
}
function isWorkerSessionOpen(sessionId) {
return Boolean(sessionId && terminalWorkerManager?.hasOpenSession?.(sessionId));
}
function rememberRendererSessionMeta(sessionId, meta) {
if (!sessionId || !meta || typeof meta !== "object") return;
const prev = rendererSessionMetaById.get(sessionId) || {};
rendererSessionMetaById.set(sessionId, { ...prev, ...meta });
}
function hasActiveOutputBuffer(sessionId) {
try {
return Boolean(String(getOrCreateBuffer(sessionId).getText() || "").trim());
} catch {
return false;
}
}
function isSessionConnected(sessionId) {
const session = sessions?.get(sessionId);
if (session) {
return session.status !== "disconnected";
}
const rendererMeta = rendererSessionMetaById.get(sessionId);
return Boolean(
rendererMeta?.connected
|| isWorkerSessionOpen(sessionId)
|| hasActiveOutputBuffer(sessionId),
);
}
function getSessionMeta(sessionId) {
const session = sessions?.get(sessionId);
const rendererMeta = rendererSessionMetaById.get(sessionId);
if (session) {
return {
connected: session.status !== "disconnected",
hostname: session.hostname || session.hostLabel || rendererMeta?.hostname || "",
username: session.username || rendererMeta?.username || "",
};
}
if (isSessionConnected(sessionId)) {
return {
connected: true,
hostname: rendererMeta?.hostname || "",
username: rendererMeta?.username || "",
};
}
return { connected: false, hostname: "", username: "" };
}
function notifyScriptSessionInput(sessionId, data) {
const session = sessions?.get(sessionId);
const webContents = session?.webContentsId
? electronModule.webContents.fromId(session.webContentsId)
: getMainWindow?.()?.webContents;
webContents?.send("netcatty:script:session-input", { sessionId, data });
}
function writeToSession(sessionId, data, options = {}) {
const payload = {
sessionId,
data,
automated: options.automated !== false,
};
const webContentsId = getMainWindow?.()?.webContents?.id;
if (terminalWorkerManager) {
terminalWorkerManager.send("netcatty:write", payload, { webContentsId });
} else {
terminalBridge?.writeToSession?.(
{ sender: getMainWindow?.()?.webContents },
payload,
);
}
if (options.automated !== false && data && data !== "\x03") {
notifyScriptSessionInput(sessionId, data);
}
}
async function requestScreenSnapshot(sessionId) {
const session = sessions?.get(sessionId);
const webContents = session?.webContentsId
? electronModule.webContents.fromId(session.webContentsId)
: getMainWindow?.()?.webContents;
if (!webContents) {
return {
rows: 24,
cols: 80,
currentRow: 0,
lines: getOrCreateBuffer(sessionId).getText().split("\n"),
};
}
const requestId = randomUUID();
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
pendingScreenSnapshots.delete(requestId);
resolve({
rows: 24,
cols: 80,
currentRow: 0,
lines: getOrCreateBuffer(sessionId).getText().split("\n"),
});
}, 3000);
pendingScreenSnapshots.set(requestId, {
sessionId,
resolve: (value) => {
clearTimeout(timer);
resolve(value);
},
reject: (err) => {
clearTimeout(timer);
reject(err);
},
});
webContents.send("netcatty:script:screen-snapshot-request", { requestId, sessionId });
});
}
function showDialog(type, message, defaultValue, extras = {}) {
const win = getMainWindow?.();
const webContents = win?.webContents;
if (!webContents) {
if (type === "confirm") return Promise.resolve(false);
if (type === "prompt") return Promise.resolve(defaultValue || "");
if (type === "waitForTimeout") return Promise.resolve("abort");
return Promise.resolve(undefined);
}
const requestId = randomUUID();
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
pendingDialogs.delete(requestId);
reject(new Error("Dialog timed out"));
}, 120000);
pendingDialogs.set(requestId, {
type,
resolve: (value) => {
clearTimeout(timer);
resolve(value);
},
reject: (err) => {
clearTimeout(timer);
reject(err);
},
});
webContents.send("netcatty:script:dialog-request", {
requestId,
type,
message,
defaultValue,
...extras,
});
});
}
function showWaitForTimeoutDialog(pattern, timeoutMs) {
return showDialog(
"waitForTimeout",
`Timed out waiting for "${pattern}" after ${timeoutMs}ms`,
undefined,
{ pattern, timeoutMs },
);
}
function syncOutputBufferFromSnapshot(sessionId) {
return requestScreenSnapshot(sessionId).then((snapshot) => {
const screenText = (snapshot.lines || []).join("\n");
if (!screenText) return;
const buffer = getOrCreateBuffer(sessionId);
const existing = buffer.getText();
if (!existing) {
buffer.append(screenText.endsWith("\n") ? screenText : `${screenText}\n`);
return;
}
const tail = screenText.slice(-8192);
if (!tail) return;
const existingTail = existing.slice(-8192);
if (tail === existingTail || existing.endsWith(tail)) return;
if (existingTail && tail.includes(existingTail)) {
buffer.append(tail.slice(tail.indexOf(existingTail) + existingTail.length));
return;
}
if (!existing.includes(tail.trim())) {
buffer.append(tail.startsWith("\n") ? tail : `\n${tail}`);
}
}).catch(() => {});
}
async function runScriptOnSession({
runId,
scriptId,
scriptLabel,
sessionId,
content,
permissionMode = "auto",
sessionMeta,
}) {
rememberRendererSessionMeta(sessionId, sessionMeta);
const run = {
runId,
scriptId,
scriptLabel,
sessionId,
status: "running",
startedAt: Date.now(),
endedAt: undefined,
currentStep: undefined,
stepIndex: 0,
totalSteps: undefined,
progressMode: "activity",
activityLabel: undefined,
progressLabel: undefined,
progressCurrent: undefined,
progressTotal: undefined,
waitingFor: undefined,
logs: [],
paused: false,
aborted: false,
};
runs.set(runId, run);
broadcastRuns();
const runtime = createScriptRuntime({
sessionId,
runId,
appVersion: electronModule?.app?.getVersion?.(),
appendLog: (id, message) => {
const entry = runs.get(id);
if (!entry) return;
entry.logs.push({ at: Date.now(), message });
broadcastRuns();
},
writeToSession,
getOutputBuffer: getOrCreateBuffer,
getScreenSnapshot: requestScreenSnapshot,
getSessionMeta,
showDialog,
showWaitForTimeoutDialog,
disconnectSession: async (sid) => {
if (terminalWorkerManager) {
terminalWorkerManager.send("netcatty:close", { sessionId: sid });
} else {
terminalBridge?.closeSession?.({ sender: {} }, { sessionId: sid });
}
},
startSessionLog: async (sid, logPath) => {
const session = sessions?.get(sid);
const defaultDir = electronModule?.app?.getPath?.("documents") || process.cwd();
const filePath = logPath
? path.resolve(String(logPath))
: path.join(defaultDir, `netcatty-script-${Date.now()}.log`);
const result = sessionLogStreamManager.startStreamToFile(sid, {
filePath,
hostLabel: session?.hostname || session?.hostLabel || "script",
format: "raw",
stopRequiresToken: true,
});
if (!result.ok) {
throw new Error(result.error || "Failed to start script log");
}
scriptLogTokens.set(sid, result.token);
},
stopSessionLog: async (sid) => {
const token = scriptLogTokens.get(sid);
if (token) {
sessionLogStreamManager.stopStream(sid, token);
scriptLogTokens.delete(sid);
}
},
isPaused: () => Boolean(runs.get(runId)?.paused),
isAborted: () => Boolean(runs.get(runId)?.aborted),
permissionMode,
startedAt: run.startedAt,
onStatusChange: (id, patch) => {
const entry = runs.get(id);
if (!entry) return;
Object.assign(entry, patch);
broadcastRuns();
},
});
try {
await syncOutputBufferFromSnapshot(sessionId);
await runtime.execute(content);
if (run.aborted) {
run.status = "failed";
run.error = run.error || "Stopped by user";
} else {
run.status = "completed";
}
run.endedAt = Date.now();
run.progressMode = "activity";
run.progressLabel = undefined;
run.progressCurrent = undefined;
run.progressTotal = undefined;
} catch (err) {
run.status = "failed";
run.endedAt = Date.now();
run.progressMode = "activity";
run.progressLabel = undefined;
run.progressCurrent = undefined;
run.progressTotal = undefined;
run.error = err?.message || String(err);
run.logs.push({ at: Date.now(), message: run.error });
} finally {
broadcastRuns();
}
}
async function handleScriptRun(_event, payload = {}) {
const {
scriptId,
scriptLabel,
content,
sessionId,
sessionIds,
mode = "parallel",
permissionMode = "auto",
} = payload;
const targets = Array.isArray(sessionIds) && sessionIds.length > 0
? sessionIds
: sessionId
? [sessionId]
: [];
if (targets.length === 0) {
throw new Error("No target session for script run");
}
if (!content || !String(content).trim()) {
throw new Error("Script content is empty");
}
const runIds = [];
const queueRun = (sid) => {
const runId = randomUUID();
runIds.push(runId);
return enqueueSessionRun(sid, () => runScriptOnSession({
runId,
scriptId,
scriptLabel,
sessionId: sid,
content,
permissionMode,
sessionMeta: payload.sessionMeta,
}));
};
if (mode === "sequential") {
for (const sid of targets) {
await queueRun(sid);
}
} else {
await Promise.all(targets.map((sid) => queueRun(sid)));
}
return { runIds, runId: runIds[0] };
}
function handleScriptStop(_event, payload = {}) {
const run = runs.get(payload.runId);
if (!run) return { ok: false };
run.aborted = true;
run.paused = false;
run.status = "failed";
run.error = "Stopped by user";
run.endedAt = Date.now();
run.waitingFor = undefined;
getOrCreateBuffer(run.sessionId).abortWaiters("Stopped by user");
broadcastRuns();
return { ok: true };
}
function handleScriptPause(_event, payload = {}) {
const run = runs.get(payload.runId);
if (!run) return { ok: false };
run.paused = true;
run.status = "paused";
broadcastRuns();
return { ok: true };
}
function handleScriptResume(_event, payload = {}) {
const run = runs.get(payload.runId);
if (!run) return { ok: false };
run.paused = false;
run.status = "running";
broadcastRuns();
return { ok: true };
}
function handleScriptGetRuns(_event, payload = {}) {
const all = Array.from(runs.values()).map(serializeRun);
if (payload.sessionId) {
return all.filter((run) => run.sessionId === payload.sessionId);
}
return all;
}
function handleScriptDialogResponse(_event, payload = {}) {
const pending = pendingDialogs.get(payload.requestId);
if (!pending) return { ok: false };
pendingDialogs.delete(payload.requestId);
if (payload.cancelled) {
pending.reject(new Error("Dialog cancelled"));
return { ok: true };
}
if (pending.type === "confirm") {
pending.resolve(Boolean(payload.value));
} else if (pending.type === "prompt") {
pending.resolve(typeof payload.value === "string" ? payload.value : "");
} else if (pending.type === "waitForTimeout") {
pending.resolve(typeof payload.value === "string" ? payload.value : "abort");
} else {
pending.resolve(undefined);
}
return { ok: true };
}
function handleScriptScreenSnapshotResponse(_event, payload = {}) {
const pending = pendingScreenSnapshots.get(payload.requestId);
if (!pending) return { ok: false };
pendingScreenSnapshots.delete(payload.requestId);
pending.resolve(payload.snapshot || {
rows: 24,
cols: 80,
currentRow: 0,
lines: getOrCreateBuffer(pending.sessionId).getText().split("\n"),
});
return { ok: true };
}
function handleRecordingStart(_event, payload = {}) {
const { sessionId } = payload;
if (!sessionId) throw new Error("sessionId required");
recordings.set(sessionId, {
sessionId,
startedAt: Date.now(),
steps: [],
lastTimestamp: Date.now(),
});
return { ok: true };
}
function handleRecordingStop(_event, payload = {}) {
const { sessionId } = payload;
const recording = recordings.get(sessionId);
if (!recording) {
return { steps: [], code: "" };
}
recordings.delete(sessionId);
const code = stepsToJavaScript(recording.steps, new Date(recording.startedAt).toISOString());
return { steps: recording.steps, code };
}
function handleRecordingAppendStep(_event, payload = {}) {
const { sessionId, step } = payload;
const recording = recordings.get(sessionId);
if (!recording || !step) return { ok: false };
const now = Date.now();
const gap = now - recording.lastTimestamp;
if (gap > 1000 && step.type === "send") {
recording.steps.push({ type: "sleep", value: gap });
}
recording.steps.push(step);
recording.lastTimestamp = now;
return { ok: true };
}
function registerHandlers(ipcMain) {
ipcMain.handle("netcatty:script:run", handleScriptRun);
ipcMain.handle("netcatty:script:stop", handleScriptStop);
ipcMain.handle("netcatty:script:pause", handleScriptPause);
ipcMain.handle("netcatty:script:resume", handleScriptResume);
ipcMain.handle("netcatty:script:get-runs", handleScriptGetRuns);
ipcMain.handle("netcatty:script:dialog-response", handleScriptDialogResponse);
ipcMain.handle("netcatty:script:screen-snapshot-response", handleScriptScreenSnapshotResponse);
ipcMain.handle("netcatty:script:recording:start", handleRecordingStart);
ipcMain.handle("netcatty:script:recording:stop", handleRecordingStop);
ipcMain.handle("netcatty:script:recording:append-step", handleRecordingAppendStep);
}
module.exports = {
init,
registerHandlers,
appendSessionOutput,
removeSessionBuffer,
};