mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-23 16:42:19 +00:00
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>
This commit is contained in:
1 parent
9d98853091
commit
6b9b71ac8a
112 files changed
+8776
-680
No files matched your search
@@ -0,0 +1,41 @@
|
||||
"use strict";
|
||||
|
||||
const HEADER = "// Auto-generated by Netcatty Script Recorder\n";
|
||||
|
||||
function escapeJsString(value) {
|
||||
return JSON.stringify(String(value ?? ""));
|
||||
}
|
||||
|
||||
function stepsToJavaScript(steps, recordedAt) {
|
||||
const lines = [
|
||||
HEADER.trimEnd(),
|
||||
recordedAt ? `// Recorded on ${recordedAt}` : "",
|
||||
"",
|
||||
"async function main() {",
|
||||
].filter(Boolean);
|
||||
|
||||
for (let index = 0; index < steps.length; index += 1) {
|
||||
const step = steps[index];
|
||||
if (step.type === "send") {
|
||||
if (step.sensitive) {
|
||||
lines.push(` const sensitiveValue${index} = await nct.dialog.prompt("Enter sensitive value", "");`);
|
||||
lines.push(` await nct.screen.sendLine(sensitiveValue${index});`);
|
||||
continue;
|
||||
}
|
||||
lines.push(` await nct.screen.sendLine(${escapeJsString(step.value)});`);
|
||||
} else if (step.type === "waitFor") {
|
||||
lines.push(` await nct.screen.waitFor(${escapeJsString(step.value)}, ${step.timeoutMs || 5000});`);
|
||||
} else if (step.type === "waitForPrompt") {
|
||||
lines.push(` await nct.screen.waitForPrompt(${step.timeoutMs || 30000});`);
|
||||
} else if (step.type === "sleep") {
|
||||
lines.push(` await nct.session.sleep(${Number(step.value) || 1000});`);
|
||||
}
|
||||
}
|
||||
|
||||
lines.push("}", "", "await main();");
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
stepsToJavaScript,
|
||||
};
|
||||
@@ -0,0 +1,461 @@
|
||||
"use strict";
|
||||
|
||||
const vm = require("node:vm");
|
||||
const { shellPromptPatterns } = require("./shellPromptPatterns.cjs");
|
||||
|
||||
function wrapScriptSource(source) {
|
||||
const trimmed = String(source || "").trim();
|
||||
if (!trimmed) {
|
||||
throw new Error("Script content is empty");
|
||||
}
|
||||
|
||||
if (/^\(\s*async\s*\(\s*\)\s*=>/m.test(trimmed) || /^\(\s*async\s+function\s*\(\s*\)\s*\{/m.test(trimmed)) {
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
const hasMainFunction = /\basync\s+function\s+main\s*\(/m.test(trimmed) || /\bfunction\s+main\s*\(/m.test(trimmed);
|
||||
if (hasMainFunction) {
|
||||
const body = trimmed.replace(/\n\s*;?\s*await\s+main\s*\(\s*\)\s*;?\s*$/m, "").trimEnd();
|
||||
const invokeMain = /\basync\s+function\s+main\s*\(/m.test(body)
|
||||
? "await main();"
|
||||
: "await Promise.resolve(main());";
|
||||
return `(async () => {\n${body}\n${invokeMain}\n})();`;
|
||||
}
|
||||
|
||||
return `(async () => {\n${trimmed}\n})();`;
|
||||
}
|
||||
|
||||
function truncateActivityLabel(value, max = 80) {
|
||||
const text = String(value ?? "");
|
||||
return text.length > max ? `${text.slice(0, max - 1)}…` : text;
|
||||
}
|
||||
|
||||
function createScriptRuntime(deps) {
|
||||
const {
|
||||
sessionId,
|
||||
runId,
|
||||
appendLog,
|
||||
writeToSession,
|
||||
getOutputBuffer,
|
||||
getScreenSnapshot,
|
||||
getSessionMeta,
|
||||
showDialog,
|
||||
showWaitForTimeoutDialog,
|
||||
disconnectSession,
|
||||
startSessionLog,
|
||||
stopSessionLog,
|
||||
onStatusChange,
|
||||
isPaused,
|
||||
permissionMode = "auto",
|
||||
startedAt = Date.now(),
|
||||
} = deps;
|
||||
|
||||
let stepIndex = 0;
|
||||
let progressMode = "activity";
|
||||
let progressLabel;
|
||||
let progressCurrent = 0;
|
||||
let progressTotal = 0;
|
||||
|
||||
let screenSnapshot = {
|
||||
rows: 24,
|
||||
cols: 80,
|
||||
currentRow: 0,
|
||||
lines: [],
|
||||
};
|
||||
|
||||
function emitStatus(patch = {}) {
|
||||
onStatusChange?.(runId, {
|
||||
progressMode,
|
||||
progressLabel: progressMode === "determinate" ? progressLabel : undefined,
|
||||
progressCurrent: progressMode === "determinate" ? progressCurrent : undefined,
|
||||
progressTotal: progressMode === "determinate" ? progressTotal : undefined,
|
||||
elapsedMs: Math.max(0, Date.now() - startedAt),
|
||||
stepIndex,
|
||||
status: "running",
|
||||
...patch,
|
||||
});
|
||||
}
|
||||
|
||||
function assertWriteAllowed(operation) {
|
||||
if (permissionMode !== "observer") return;
|
||||
throw new Error(`Observer mode: ${operation} is disabled. Switch to Confirm or Auto mode.`);
|
||||
}
|
||||
|
||||
async function trackStep(label) {
|
||||
stepIndex += 1;
|
||||
const activityLabel = truncateActivityLabel(label);
|
||||
emitStatus({
|
||||
activityLabel,
|
||||
currentStep: activityLabel,
|
||||
});
|
||||
}
|
||||
|
||||
async function refreshScreenSnapshot() {
|
||||
if (typeof getScreenSnapshot === "function") {
|
||||
try {
|
||||
screenSnapshot = await getScreenSnapshot(sessionId);
|
||||
} catch {
|
||||
// fall back to output buffer text
|
||||
}
|
||||
}
|
||||
return screenSnapshot;
|
||||
}
|
||||
|
||||
async function waitForPromptWithRecovery(timeoutMs = 60000) {
|
||||
let stepTracked = false;
|
||||
while (true) {
|
||||
if (deps.isAborted?.()) {
|
||||
throw new Error("Script stopped");
|
||||
}
|
||||
if (!stepTracked) {
|
||||
await trackStep("waitForPrompt");
|
||||
stepTracked = true;
|
||||
}
|
||||
onStatusChange?.(runId, { waitingFor: "shell prompt", status: "running", elapsedMs: Math.max(0, Date.now() - startedAt) });
|
||||
try {
|
||||
return await getOutputBuffer(sessionId).waitForAny(
|
||||
shellPromptPatterns(),
|
||||
timeoutMs,
|
||||
() => Boolean(deps.isAborted?.()),
|
||||
);
|
||||
} catch (err) {
|
||||
if (!String(err?.message || err).includes("timed out")) {
|
||||
throw err;
|
||||
}
|
||||
onStatusChange?.(runId, { status: "paused", waitingFor: "shell prompt", elapsedMs: Math.max(0, Date.now() - startedAt) });
|
||||
const action = await showWaitForTimeoutDialog?.("shell prompt", timeoutMs);
|
||||
onStatusChange?.(runId, { status: "running" });
|
||||
if (action === "retry") {
|
||||
continue;
|
||||
}
|
||||
if (action === "skip") {
|
||||
return -1;
|
||||
}
|
||||
throw new Error("Script stopped by user");
|
||||
} finally {
|
||||
onStatusChange?.(runId, { waitingFor: undefined, status: "running", elapsedMs: Math.max(0, Date.now() - startedAt) });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function waitForAnyWithRecovery(patterns, timeoutMs = 30000) {
|
||||
const label = Array.isArray(patterns)
|
||||
? patterns.map((pattern) => (pattern instanceof RegExp ? pattern.source : String(pattern))).join(" | ")
|
||||
: String(patterns);
|
||||
let stepTracked = false;
|
||||
while (true) {
|
||||
if (deps.isAborted?.()) {
|
||||
throw new Error("Script stopped");
|
||||
}
|
||||
if (!stepTracked) {
|
||||
await trackStep(`waitForAny ${truncateActivityLabel(label, 60)}`);
|
||||
stepTracked = true;
|
||||
}
|
||||
onStatusChange?.(runId, { waitingFor: label, status: "running", elapsedMs: Math.max(0, Date.now() - startedAt) });
|
||||
try {
|
||||
return await getOutputBuffer(sessionId).waitForAny(
|
||||
patterns,
|
||||
timeoutMs,
|
||||
() => Boolean(deps.isAborted?.()),
|
||||
);
|
||||
} catch (err) {
|
||||
if (!String(err?.message || err).includes("timed out")) {
|
||||
throw err;
|
||||
}
|
||||
onStatusChange?.(runId, { status: "paused", waitingFor: label, elapsedMs: Math.max(0, Date.now() - startedAt) });
|
||||
const action = await showWaitForTimeoutDialog?.(label, timeoutMs);
|
||||
onStatusChange?.(runId, { status: "running" });
|
||||
if (action === "retry") {
|
||||
continue;
|
||||
}
|
||||
if (action === "skip") {
|
||||
return -1;
|
||||
}
|
||||
throw new Error("Script stopped by user");
|
||||
} finally {
|
||||
onStatusChange?.(runId, { waitingFor: undefined, status: "running", elapsedMs: Math.max(0, Date.now() - startedAt) });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function waitForWithRecovery(pattern, timeoutMs = 30000) {
|
||||
const patternLabel = pattern instanceof RegExp ? pattern.source : String(pattern);
|
||||
let stepTracked = false;
|
||||
while (true) {
|
||||
if (deps.isAborted?.()) {
|
||||
throw new Error("Script stopped");
|
||||
}
|
||||
if (!stepTracked) {
|
||||
await trackStep(`waitFor ${truncateActivityLabel(patternLabel, 60)}`);
|
||||
stepTracked = true;
|
||||
}
|
||||
onStatusChange?.(runId, { waitingFor: patternLabel, status: "running", elapsedMs: Math.max(0, Date.now() - startedAt) });
|
||||
try {
|
||||
return await getOutputBuffer(sessionId).waitFor(
|
||||
pattern,
|
||||
timeoutMs,
|
||||
() => Boolean(deps.isAborted?.()),
|
||||
);
|
||||
} catch (err) {
|
||||
if (!String(err?.message || err).includes("timed out")) {
|
||||
throw err;
|
||||
}
|
||||
onStatusChange?.(runId, { status: "paused", waitingFor: patternLabel, elapsedMs: Math.max(0, Date.now() - startedAt) });
|
||||
const action = await showWaitForTimeoutDialog?.(patternLabel, timeoutMs);
|
||||
onStatusChange?.(runId, { status: "running" });
|
||||
if (action === "retry") {
|
||||
continue;
|
||||
}
|
||||
if (action === "skip") {
|
||||
return "";
|
||||
}
|
||||
throw new Error("Script stopped by user");
|
||||
} finally {
|
||||
onStatusChange?.(runId, { waitingFor: undefined, status: "running", elapsedMs: Math.max(0, Date.now() - startedAt) });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const progressApi = {
|
||||
start(label, total) {
|
||||
progressMode = "determinate";
|
||||
progressLabel = truncateActivityLabel(label || "Progress", 60);
|
||||
progressTotal = Math.max(1, Number(total) || 1);
|
||||
progressCurrent = 0;
|
||||
emitStatus({
|
||||
progressMode,
|
||||
progressLabel,
|
||||
progressCurrent,
|
||||
progressTotal,
|
||||
activityLabel: progressLabel,
|
||||
});
|
||||
},
|
||||
set(current, detail) {
|
||||
if (progressMode !== "determinate") return;
|
||||
progressCurrent = Math.max(0, Math.min(progressTotal, Number(current) || 0));
|
||||
const patch = {
|
||||
progressCurrent,
|
||||
progressTotal,
|
||||
progressLabel,
|
||||
};
|
||||
if (detail !== undefined && detail !== null && detail !== "") {
|
||||
patch.activityLabel = truncateActivityLabel(detail);
|
||||
}
|
||||
emitStatus(patch);
|
||||
},
|
||||
step(detail) {
|
||||
if (progressMode !== "determinate") return;
|
||||
progressCurrent = Math.min(progressTotal, progressCurrent + 1);
|
||||
const patch = {
|
||||
progressCurrent,
|
||||
progressTotal,
|
||||
progressLabel,
|
||||
};
|
||||
if (detail !== undefined && detail !== null && detail !== "") {
|
||||
patch.activityLabel = truncateActivityLabel(detail);
|
||||
}
|
||||
emitStatus(patch);
|
||||
},
|
||||
done() {
|
||||
if (progressMode !== "determinate") return;
|
||||
progressCurrent = progressTotal;
|
||||
emitStatus({
|
||||
progressCurrent,
|
||||
progressTotal,
|
||||
progressLabel,
|
||||
});
|
||||
progressMode = "activity";
|
||||
progressLabel = undefined;
|
||||
progressCurrent = 0;
|
||||
progressTotal = 0;
|
||||
emitStatus({
|
||||
progressMode: "activity",
|
||||
progressLabel: undefined,
|
||||
progressCurrent: undefined,
|
||||
progressTotal: undefined,
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
const sessionApi = {
|
||||
get connected() {
|
||||
const meta = getSessionMeta?.(sessionId);
|
||||
return Boolean(meta?.connected);
|
||||
},
|
||||
get hostname() {
|
||||
return getSessionMeta?.(sessionId)?.hostname || "";
|
||||
},
|
||||
get username() {
|
||||
return getSessionMeta?.(sessionId)?.username || "";
|
||||
},
|
||||
sleep(ms) {
|
||||
const delay = Math.max(0, Number(ms) || 0);
|
||||
return trackStep(`sleep ${delay}ms`).then(() => interruptibleSleep(delay, deps.isAborted));
|
||||
},
|
||||
async startLog(path) {
|
||||
assertWriteAllowed("session.startLog");
|
||||
await trackStep("startLog");
|
||||
await startSessionLog?.(sessionId, path);
|
||||
},
|
||||
async stopLog() {
|
||||
await trackStep("stopLog");
|
||||
await stopSessionLog?.(sessionId);
|
||||
},
|
||||
async disconnect() {
|
||||
assertWriteAllowed("session.disconnect");
|
||||
await trackStep("disconnect");
|
||||
await disconnectSession?.(sessionId);
|
||||
},
|
||||
};
|
||||
|
||||
const screenApi = {
|
||||
async send(text) {
|
||||
assertWriteAllowed("screen.send");
|
||||
await waitIfPaused();
|
||||
const payload = String(text ?? "");
|
||||
await trackStep(`send: ${truncateActivityLabel(formatScriptInputForLog(payload), 60)}`);
|
||||
appendLog(runId, `→ ${formatScriptInputForLog(payload)}`);
|
||||
writeToSession(sessionId, payload, { automated: true });
|
||||
},
|
||||
async sendLine(text) {
|
||||
assertWriteAllowed("screen.sendLine");
|
||||
await waitIfPaused();
|
||||
const line = String(text ?? "");
|
||||
await trackStep(`sendLine: ${truncateActivityLabel(line, 60)}`);
|
||||
appendLog(runId, `→ ${line}`);
|
||||
writeToSession(sessionId, `${line}\r`, { automated: true });
|
||||
},
|
||||
waitFor(pattern, timeoutMs = 30000) {
|
||||
return waitForWithRecovery(pattern, timeoutMs);
|
||||
},
|
||||
waitForPrompt(timeoutMs = 60000) {
|
||||
return waitForPromptWithRecovery(timeoutMs);
|
||||
},
|
||||
async waitForAny(patterns, timeoutMs = 30000) {
|
||||
return waitForAnyWithRecovery(patterns, timeoutMs);
|
||||
},
|
||||
async getText(startRow, endRow) {
|
||||
await refreshScreenSnapshot();
|
||||
const lines = screenSnapshot.lines || [];
|
||||
const start = typeof startRow === "number" ? Math.max(0, startRow) : 0;
|
||||
const end = typeof endRow === "number" ? Math.min(lines.length - 1, endRow) : lines.length - 1;
|
||||
if (lines.length === 0) {
|
||||
return getOutputBuffer(sessionId).getText();
|
||||
}
|
||||
return lines.slice(start, end + 1).join("\n");
|
||||
},
|
||||
get currentRow() {
|
||||
return screenSnapshot.currentRow ?? 0;
|
||||
},
|
||||
get rows() {
|
||||
return screenSnapshot.rows ?? 24;
|
||||
},
|
||||
get cols() {
|
||||
return screenSnapshot.cols ?? 80;
|
||||
},
|
||||
async clear() {
|
||||
assertWriteAllowed("screen.clear");
|
||||
await trackStep("clear");
|
||||
writeToSession(sessionId, "\x1b[2J\x1b[H", { automated: true });
|
||||
},
|
||||
};
|
||||
|
||||
const dialogApi = {
|
||||
alert(message) {
|
||||
return showDialog("alert", String(message ?? ""));
|
||||
},
|
||||
confirm(message) {
|
||||
return showDialog("confirm", String(message ?? ""));
|
||||
},
|
||||
prompt(message, defaultValue = "") {
|
||||
return showDialog("prompt", String(message ?? ""), String(defaultValue ?? ""));
|
||||
},
|
||||
};
|
||||
|
||||
const nct = {
|
||||
session: sessionApi,
|
||||
screen: screenApi,
|
||||
dialog: dialogApi,
|
||||
progress: progressApi,
|
||||
version: deps.appVersion || "0.0.0",
|
||||
sleep: sessionApi.sleep.bind(sessionApi),
|
||||
log(message) {
|
||||
stepIndex += 1;
|
||||
emitStatus({
|
||||
activityLabel: "log",
|
||||
currentStep: "log",
|
||||
});
|
||||
appendLog(runId, String(message ?? ""));
|
||||
},
|
||||
};
|
||||
|
||||
async function waitIfPaused() {
|
||||
while (isPaused?.()) {
|
||||
if (deps.isAborted?.()) {
|
||||
throw new Error("Script stopped");
|
||||
}
|
||||
onStatusChange?.(runId, { status: "paused", elapsedMs: Math.max(0, Date.now() - startedAt) });
|
||||
await interruptibleSleep(100, deps.isAborted);
|
||||
}
|
||||
onStatusChange?.(runId, { status: "running", elapsedMs: Math.max(0, Date.now() - startedAt) });
|
||||
}
|
||||
|
||||
async function execute(source) {
|
||||
if (deps.isAborted?.()) {
|
||||
throw new Error("Script stopped");
|
||||
}
|
||||
const wrapped = wrapScriptSource(source);
|
||||
const sandbox = {
|
||||
nct,
|
||||
console: {
|
||||
log: (...args) => {
|
||||
appendLog(runId, args.map((arg) => String(arg)).join(" "));
|
||||
},
|
||||
},
|
||||
};
|
||||
vm.createContext(sandbox);
|
||||
const script = new vm.Script(wrapped, { filename: `script-${runId}.js` });
|
||||
const result = script.runInContext(sandbox, { displayErrors: true });
|
||||
if (result && typeof result.then === "function") {
|
||||
await result;
|
||||
}
|
||||
}
|
||||
|
||||
return { execute, nct };
|
||||
}
|
||||
|
||||
function interruptibleSleep(ms, isAborted) {
|
||||
const delay = Math.max(0, Number(ms) || 0);
|
||||
if (!isAborted) {
|
||||
return new Promise((resolve) => setTimeout(resolve, delay));
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
const startedAt = Date.now();
|
||||
const timer = setInterval(() => {
|
||||
if (isAborted()) {
|
||||
clearInterval(timer);
|
||||
reject(new Error("Script stopped"));
|
||||
return;
|
||||
}
|
||||
if (Date.now() - startedAt >= delay) {
|
||||
clearInterval(timer);
|
||||
resolve(undefined);
|
||||
}
|
||||
}, 50);
|
||||
});
|
||||
}
|
||||
|
||||
function formatScriptInputForLog(data) {
|
||||
return String(data ?? "")
|
||||
.replace(/\r/g, "\\r")
|
||||
.replace(/\n/g, "\\n")
|
||||
.replace(/\x03/g, "^C")
|
||||
.replace(/\x1b/g, "\\e");
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
createScriptRuntime,
|
||||
wrapScriptSource,
|
||||
interruptibleSleep,
|
||||
formatScriptInputForLog,
|
||||
};
|
||||
@@ -0,0 +1,153 @@
|
||||
"use strict";
|
||||
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const { createScriptRuntime, wrapScriptSource, interruptibleSleep } = require("./scriptRuntime.cjs");
|
||||
|
||||
test("wrapScriptSource wraps async main scripts in async IIFE", () => {
|
||||
const wrapped = wrapScriptSource(`
|
||||
// generated
|
||||
async function main() {
|
||||
await nct.log('hi');
|
||||
}
|
||||
|
||||
await main();
|
||||
`);
|
||||
assert.match(wrapped, /^\(async \(\) => \{/);
|
||||
assert.match(wrapped, /await main\(\);\n\}\)\(\);$/);
|
||||
});
|
||||
|
||||
test("wrapScriptSource wraps bare statements in async IIFE", () => {
|
||||
const wrapped = wrapScriptSource("await nct.log('hi');");
|
||||
assert.match(wrapped, /async \(\) =>/);
|
||||
});
|
||||
|
||||
test("interruptibleSleep rejects when aborted", async () => {
|
||||
let aborted = false;
|
||||
const pending = interruptibleSleep(5000, () => aborted);
|
||||
setTimeout(() => {
|
||||
aborted = true;
|
||||
}, 50);
|
||||
await assert.rejects(pending, /Script stopped/);
|
||||
});
|
||||
|
||||
test("createScriptRuntime executes async main script", async () => {
|
||||
const logs = [];
|
||||
const runtime = createScriptRuntime({
|
||||
sessionId: "s1",
|
||||
runId: "r1",
|
||||
appendLog: (_id, message) => logs.push(message),
|
||||
writeToSession: () => {},
|
||||
getOutputBuffer: () => ({
|
||||
waitFor: async () => "ok",
|
||||
waitForAny: async () => 0,
|
||||
getText: () => "",
|
||||
}),
|
||||
getSessionMeta: () => ({ connected: true, hostname: "host", username: "user" }),
|
||||
showDialog: async () => true,
|
||||
isPaused: () => false,
|
||||
isAborted: () => false,
|
||||
onStatusChange: () => {},
|
||||
});
|
||||
|
||||
await runtime.execute(`
|
||||
async function main() {
|
||||
nct.log('from-main');
|
||||
}
|
||||
|
||||
await main();
|
||||
`);
|
||||
assert.deepEqual(logs, ["from-main"]);
|
||||
});
|
||||
|
||||
test("createScriptRuntime executes simple log script", async () => {
|
||||
const logs = [];
|
||||
const runtime = createScriptRuntime({
|
||||
sessionId: "s1",
|
||||
runId: "r1",
|
||||
appendLog: (_id, message) => logs.push(message),
|
||||
writeToSession: () => {},
|
||||
getOutputBuffer: () => ({
|
||||
waitFor: async () => "ok",
|
||||
waitForAny: async () => 0,
|
||||
getText: () => "",
|
||||
}),
|
||||
getSessionMeta: () => ({ connected: true, hostname: "host", username: "user" }),
|
||||
showDialog: async () => true,
|
||||
isPaused: () => false,
|
||||
isAborted: () => false,
|
||||
onStatusChange: () => {},
|
||||
});
|
||||
|
||||
await runtime.execute("nct.log('hello');");
|
||||
assert.deepEqual(logs, ["hello"]);
|
||||
});
|
||||
|
||||
test("createScriptRuntime reports activity labels for loops without X/Y totals", async () => {
|
||||
const statuses = [];
|
||||
const runtime = createScriptRuntime({
|
||||
sessionId: "s1",
|
||||
runId: "r1",
|
||||
appendLog: () => {},
|
||||
writeToSession: () => {},
|
||||
getOutputBuffer: () => ({
|
||||
waitFor: async () => "ok",
|
||||
waitForAny: async () => 0,
|
||||
getText: () => "",
|
||||
}),
|
||||
getSessionMeta: () => ({ connected: true, hostname: "host", username: "user" }),
|
||||
showDialog: async () => true,
|
||||
isPaused: () => false,
|
||||
isAborted: () => false,
|
||||
onStatusChange: (_id, patch) => statuses.push(patch),
|
||||
});
|
||||
|
||||
await runtime.execute("for (let i = 0; i < 3; i += 1) { nct.log(`step ${i}`); }");
|
||||
|
||||
const last = statuses.at(-1);
|
||||
assert.equal(last.stepIndex, 3);
|
||||
assert.equal(last.activityLabel, "log");
|
||||
assert.equal(last.progressMode, "activity");
|
||||
assert.equal(last.totalSteps, undefined);
|
||||
assert.equal(last.currentStep, "log");
|
||||
});
|
||||
|
||||
test("createScriptRuntime supports explicit determinate progress API", async () => {
|
||||
const statuses = [];
|
||||
const runtime = createScriptRuntime({
|
||||
sessionId: "s1",
|
||||
runId: "r1",
|
||||
appendLog: () => {},
|
||||
writeToSession: () => {},
|
||||
getOutputBuffer: () => ({
|
||||
waitFor: async () => "ok",
|
||||
waitForAny: async () => 0,
|
||||
getText: () => "",
|
||||
}),
|
||||
getSessionMeta: () => ({ connected: true, hostname: "host", username: "user" }),
|
||||
showDialog: async () => true,
|
||||
isPaused: () => false,
|
||||
isAborted: () => false,
|
||||
onStatusChange: (_id, patch) => statuses.push(patch),
|
||||
});
|
||||
|
||||
await runtime.execute(`
|
||||
nct.progress.start('Sampling', 3);
|
||||
for (let i = 0; i < 3; i += 1) {
|
||||
nct.progress.step('item ' + i);
|
||||
}
|
||||
nct.progress.done();
|
||||
nct.log('finished');
|
||||
`);
|
||||
|
||||
const during = statuses.find((patch) => patch.progressMode === "determinate" && patch.progressCurrent === 2);
|
||||
assert.ok(during);
|
||||
assert.equal(during.progressLabel, "Sampling");
|
||||
assert.equal(during.progressTotal, 3);
|
||||
assert.equal(during.activityLabel, "item 1");
|
||||
|
||||
const afterDone = statuses.filter((patch) => patch.progressMode === "activity").at(-1);
|
||||
assert.ok(afterDone);
|
||||
assert.equal(afterDone.progressCurrent, undefined);
|
||||
assert.equal(afterDone.progressTotal, undefined);
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
"use strict";
|
||||
|
||||
const STEP_MATCHERS = [
|
||||
{ regex: /await\s+nct\.screen\.waitForPrompt\s*\(/g, label: "waitForPrompt" },
|
||||
{ regex: /await\s+nct\.screen\.waitForAny\s*\(/g, label: "waitForAny" },
|
||||
{ regex: /await\s+nct\.screen\.waitFor\s*\(/g, label: "waitFor" },
|
||||
{ regex: /await\s+nct\.screen\.sendLine\s*\(/g, label: "sendLine" },
|
||||
{ regex: /await\s+nct\.screen\.send\s*\(/g, label: "send" },
|
||||
{ regex: /await\s+nct\.screen\.clear\s*\(/g, label: "clear" },
|
||||
{ regex: /await\s+nct\.session\.sleep\s*\(/g, label: "sleep" },
|
||||
{ regex: /await\s+nct\.sleep\s*\(/g, label: "sleep" },
|
||||
{ regex: /await\s+nct\.session\.disconnect\s*\(/g, label: "disconnect" },
|
||||
{ regex: /await\s+nct\.session\.startLog\s*\(/g, label: "startLog" },
|
||||
{ regex: /nct\.log\s*\(/g, label: "log" },
|
||||
];
|
||||
|
||||
function countScriptSteps(source) {
|
||||
const text = String(source || "");
|
||||
let total = 0;
|
||||
for (const matcher of STEP_MATCHERS) {
|
||||
const matches = text.match(matcher.regex);
|
||||
if (matches) total += matches.length;
|
||||
}
|
||||
return Math.max(total, 1);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
STEP_MATCHERS,
|
||||
countScriptSteps,
|
||||
};
|
||||
@@ -0,0 +1,14 @@
|
||||
"use strict";
|
||||
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const { countScriptSteps } = require("./scriptStepCounter.cjs");
|
||||
|
||||
test("countScriptSteps counts common nct calls", () => {
|
||||
const source = `
|
||||
await nct.screen.waitFor('$ ', 5000);
|
||||
await nct.screen.sendLine('ls');
|
||||
nct.log('done');
|
||||
`;
|
||||
assert.equal(countScriptSteps(source), 3);
|
||||
});
|
||||
@@ -0,0 +1,259 @@
|
||||
"use strict";
|
||||
|
||||
const DEFAULT_BUFFER_SIZE = 1024 * 1024;
|
||||
|
||||
function isRegExpLike(pattern) {
|
||||
return Boolean(
|
||||
pattern
|
||||
&& typeof pattern === "object"
|
||||
&& typeof pattern.exec === "function"
|
||||
&& typeof pattern.test === "function",
|
||||
);
|
||||
}
|
||||
|
||||
function compilePattern(pattern) {
|
||||
if (pattern instanceof RegExp || isRegExpLike(pattern)) return pattern;
|
||||
if (typeof pattern !== "string") {
|
||||
throw new TypeError("waitFor pattern must be a string or RegExp");
|
||||
}
|
||||
const slashMatch = pattern.match(/^\/(.+)\/([gimsuy]*)$/);
|
||||
if (slashMatch) {
|
||||
return new RegExp(slashMatch[1], slashMatch[2]);
|
||||
}
|
||||
const escaped = pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
return new RegExp(escaped);
|
||||
}
|
||||
|
||||
function tryMatch(text, pattern) {
|
||||
const regex = compilePattern(pattern);
|
||||
const match = regex.exec(text);
|
||||
if (!match) return null;
|
||||
return match[0];
|
||||
}
|
||||
|
||||
function tryMatchWithEnd(text, pattern) {
|
||||
const regex = compilePattern(pattern);
|
||||
const match = regex.exec(text);
|
||||
if (!match || match.index === undefined) return null;
|
||||
return {
|
||||
value: match[0],
|
||||
endOffset: match.index + match[0].length,
|
||||
};
|
||||
}
|
||||
|
||||
class SessionOutputBuffer {
|
||||
constructor(sessionId, maxSize = DEFAULT_BUFFER_SIZE) {
|
||||
this.sessionId = sessionId;
|
||||
this.maxSize = maxSize;
|
||||
this.chunks = [];
|
||||
this.totalLength = 0;
|
||||
this.scanOffset = 0;
|
||||
this.waiters = [];
|
||||
}
|
||||
|
||||
append(data) {
|
||||
if (!data) return;
|
||||
this.chunks.push(String(data));
|
||||
this.totalLength += this.chunks[this.chunks.length - 1].length;
|
||||
while (this.totalLength > this.maxSize && this.chunks.length > 1) {
|
||||
const removed = this.chunks.shift();
|
||||
const removedLength = removed.length;
|
||||
this.totalLength -= removedLength;
|
||||
this.scanOffset = Math.max(0, this.scanOffset - removedLength);
|
||||
}
|
||||
this.flushWaiters();
|
||||
}
|
||||
|
||||
getText() {
|
||||
return this.chunks.join("");
|
||||
}
|
||||
|
||||
getPendingText() {
|
||||
return this.getText().slice(this.scanOffset);
|
||||
}
|
||||
|
||||
tryMatchPending(pattern) {
|
||||
return tryMatchWithEnd(this.getPendingText(), pattern);
|
||||
}
|
||||
|
||||
advanceScanOffset(endOffset) {
|
||||
const absoluteEnd = this.scanOffset + endOffset;
|
||||
this.scanOffset = Math.min(absoluteEnd, this.getText().length);
|
||||
}
|
||||
|
||||
clear() {
|
||||
this.chunks = [];
|
||||
this.totalLength = 0;
|
||||
this.scanOffset = 0;
|
||||
}
|
||||
|
||||
flushWaiters() {
|
||||
if (this.waiters.length === 0) return;
|
||||
const remaining = [];
|
||||
for (const waiter of this.waiters) {
|
||||
if (waiter.custom) {
|
||||
if (!waiter.custom.check()) {
|
||||
remaining.push(waiter);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const matched = this.tryMatchPending(waiter.pattern);
|
||||
if (matched !== null) {
|
||||
this.advanceScanOffset(matched.endOffset);
|
||||
clearTimeout(waiter.timer);
|
||||
if (waiter.abortInterval) clearInterval(waiter.abortInterval);
|
||||
waiter.resolve(matched.value);
|
||||
} else {
|
||||
remaining.push(waiter);
|
||||
}
|
||||
}
|
||||
this.waiters = remaining;
|
||||
}
|
||||
|
||||
waitFor(pattern, timeoutMs = 30000, shouldAbort) {
|
||||
const immediate = this.tryMatchPending(pattern);
|
||||
if (immediate !== null) {
|
||||
this.advanceScanOffset(immediate.endOffset);
|
||||
return Promise.resolve(immediate.value);
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const waiter = {
|
||||
pattern,
|
||||
resolve,
|
||||
reject,
|
||||
shouldAbort,
|
||||
timer: setTimeout(() => {
|
||||
this.waiters = this.waiters.filter((entry) => entry !== waiter);
|
||||
if (waiter.abortInterval) clearInterval(waiter.abortInterval);
|
||||
reject(new Error(`waitFor timed out after ${timeoutMs}ms`));
|
||||
}, timeoutMs),
|
||||
};
|
||||
if (typeof shouldAbort === "function") {
|
||||
waiter.abortInterval = setInterval(() => {
|
||||
if (!shouldAbort()) return;
|
||||
clearTimeout(waiter.timer);
|
||||
clearInterval(waiter.abortInterval);
|
||||
this.waiters = this.waiters.filter((entry) => entry !== waiter);
|
||||
reject(new Error("Script stopped"));
|
||||
}, 100);
|
||||
}
|
||||
this.waiters.push(waiter);
|
||||
});
|
||||
}
|
||||
|
||||
abortWaiters(reason = "Script stopped") {
|
||||
for (const waiter of this.waiters) {
|
||||
clearTimeout(waiter.timer);
|
||||
if (waiter.abortInterval) clearInterval(waiter.abortInterval);
|
||||
waiter.reject?.(new Error(reason));
|
||||
}
|
||||
this.waiters = [];
|
||||
}
|
||||
|
||||
async waitForAny(patterns, timeoutMs = 30000, shouldAbort) {
|
||||
if (!Array.isArray(patterns) || patterns.length === 0) {
|
||||
throw new TypeError("waitForAny requires a non-empty patterns array");
|
||||
}
|
||||
for (let index = 0; index < patterns.length; index += 1) {
|
||||
const matched = this.tryMatchPending(patterns[index]);
|
||||
if (matched !== null) {
|
||||
this.advanceScanOffset(matched.endOffset);
|
||||
return index;
|
||||
}
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const waiter = {
|
||||
patterns,
|
||||
resolve,
|
||||
reject,
|
||||
shouldAbort,
|
||||
timer: null,
|
||||
interval: null,
|
||||
check: () => {
|
||||
for (let index = 0; index < patterns.length; index += 1) {
|
||||
const matched = this.tryMatchPending(patterns[index]);
|
||||
if (matched !== null) {
|
||||
this.advanceScanOffset(matched.endOffset);
|
||||
clearTimeout(waiter.timer);
|
||||
if (waiter.interval) clearInterval(waiter.interval);
|
||||
if (waiter.abortInterval) clearInterval(waiter.abortInterval);
|
||||
this.waiters = this.waiters.filter((entry) => entry.custom !== waiter);
|
||||
resolve(index);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
},
|
||||
};
|
||||
waiter.timer = setTimeout(() => {
|
||||
if (waiter.interval) clearInterval(waiter.interval);
|
||||
if (waiter.abortInterval) clearInterval(waiter.abortInterval);
|
||||
this.waiters = this.waiters.filter((entry) => entry.custom !== waiter);
|
||||
reject(new Error(`waitForAny timed out after ${timeoutMs}ms`));
|
||||
}, timeoutMs);
|
||||
waiter.interval = setInterval(() => {
|
||||
waiter.check();
|
||||
}, 50);
|
||||
if (typeof shouldAbort === "function") {
|
||||
waiter.abortInterval = setInterval(() => {
|
||||
if (!shouldAbort()) return;
|
||||
clearTimeout(waiter.timer);
|
||||
clearInterval(waiter.interval);
|
||||
clearInterval(waiter.abortInterval);
|
||||
this.waiters = this.waiters.filter((entry) => entry.custom !== waiter);
|
||||
reject(new Error("Script stopped"));
|
||||
}, 100);
|
||||
}
|
||||
this.waiters.push({
|
||||
pattern: patterns[0],
|
||||
resolve: () => {},
|
||||
reject: () => {},
|
||||
timer: waiter.timer,
|
||||
custom: waiter,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
dispose() {
|
||||
for (const waiter of this.waiters) {
|
||||
clearTimeout(waiter.timer);
|
||||
waiter.reject?.(new Error("Session output buffer disposed"));
|
||||
}
|
||||
this.waiters = [];
|
||||
this.chunks = [];
|
||||
this.totalLength = 0;
|
||||
this.scanOffset = 0;
|
||||
}
|
||||
}
|
||||
|
||||
const buffers = new Map();
|
||||
|
||||
function getOrCreateBuffer(sessionId) {
|
||||
if (!buffers.has(sessionId)) {
|
||||
buffers.set(sessionId, new SessionOutputBuffer(sessionId));
|
||||
}
|
||||
return buffers.get(sessionId);
|
||||
}
|
||||
|
||||
function appendSessionOutput(sessionId, data) {
|
||||
getOrCreateBuffer(sessionId).append(data);
|
||||
}
|
||||
|
||||
function removeSessionBuffer(sessionId) {
|
||||
const buffer = buffers.get(sessionId);
|
||||
if (buffer) {
|
||||
buffer.dispose();
|
||||
buffers.delete(sessionId);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
SessionOutputBuffer,
|
||||
appendSessionOutput,
|
||||
getOrCreateBuffer,
|
||||
removeSessionBuffer,
|
||||
tryMatch,
|
||||
compilePattern,
|
||||
};
|
||||
@@ -0,0 +1,88 @@
|
||||
"use strict";
|
||||
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const { SessionOutputBuffer, tryMatch } = require("./sessionOutputBuffer.cjs");
|
||||
const { SHELL_PROMPT_END_REGEX } = require("./shellPromptPatterns.cjs");
|
||||
const { stepsToJavaScript } = require("./scriptCodegen.cjs");
|
||||
|
||||
test("tryMatch finds substring patterns", () => {
|
||||
assert.equal(tryMatch("hello world", "world"), "world");
|
||||
});
|
||||
|
||||
test("tryMatch supports slash-delimited regex patterns", () => {
|
||||
assert.equal(tryMatch("sudo password:", "/password/i"), "password");
|
||||
});
|
||||
|
||||
test("tryMatch accepts RegExp objects from an isolated vm context", () => {
|
||||
const vm = require("node:vm");
|
||||
const sandbox = {};
|
||||
vm.createContext(sandbox);
|
||||
const pattern = vm.runInContext("/SAMPLE_4_DONE/", sandbox);
|
||||
assert.equal(tryMatch("tag_SAMPLE_4_DONE ok", pattern), "SAMPLE_4_DONE");
|
||||
});
|
||||
|
||||
test("SessionOutputBuffer waitFor resolves on appended data", async () => {
|
||||
const buffer = new SessionOutputBuffer("s1");
|
||||
const pending = buffer.waitFor("$ ", 1000);
|
||||
buffer.append("user@host:$ ");
|
||||
assert.equal(await pending, "$ ");
|
||||
});
|
||||
|
||||
test("SessionOutputBuffer waitFor resolves root shell prompt", async () => {
|
||||
const buffer = new SessionOutputBuffer("s1");
|
||||
const pending = buffer.waitFor("# ", 1000);
|
||||
buffer.append("Welcome to Ubuntu\nroot@VM-4-16-ubuntu:~# ");
|
||||
assert.equal(await pending, "# ");
|
||||
});
|
||||
|
||||
test("shell prompt regex matches root and user prompts", () => {
|
||||
assert.match("root@VM-4-16-ubuntu:~# ", SHELL_PROMPT_END_REGEX);
|
||||
assert.match("user@host:~$ ", SHELL_PROMPT_END_REGEX);
|
||||
assert.doesNotMatch("Welcome to Ubuntu 22.04", SHELL_PROMPT_END_REGEX);
|
||||
});
|
||||
|
||||
test("SessionOutputBuffer waitForAny matches shell prompt patterns", async () => {
|
||||
const buffer = new SessionOutputBuffer("s1");
|
||||
const pending = buffer.waitForAny(["# ", "$ ", SHELL_PROMPT_END_REGEX], 1000);
|
||||
buffer.append("root@VM-4-16-ubuntu:~# ");
|
||||
assert.equal(await pending, 0);
|
||||
});
|
||||
|
||||
test("SessionOutputBuffer waitFor ignores stale prompt before cursor", async () => {
|
||||
const buffer = new SessionOutputBuffer("s1");
|
||||
buffer.append("user@host:~$ ");
|
||||
const first = buffer.waitFor("$ ", 1000);
|
||||
assert.equal(await first, "$ ");
|
||||
|
||||
const second = buffer.waitFor("$ ", 1000);
|
||||
let resolvedEarly = false;
|
||||
void second.then(() => {
|
||||
resolvedEarly = true;
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
assert.equal(resolvedEarly, false);
|
||||
|
||||
buffer.append("ls output\nuser@host:~$ ");
|
||||
assert.equal(await second, "$ ");
|
||||
});
|
||||
|
||||
test("stepsToJavaScript sends sensitive prompt result", () => {
|
||||
const code = stepsToJavaScript([
|
||||
{ type: "send", value: "secret", sensitive: true },
|
||||
{ type: "waitForPrompt", timeoutMs: 30000 },
|
||||
], "2026-06-27");
|
||||
assert.match(code, /const sensitiveValue0 = await nct\.dialog\.prompt\("Enter sensitive value", ""\);/);
|
||||
assert.match(code, /await nct\.screen\.sendLine\(sensitiveValue0\);/);
|
||||
});
|
||||
|
||||
test("stepsToJavaScript generates sendLine and waitForPrompt steps", () => {
|
||||
const code = stepsToJavaScript([
|
||||
{ type: "waitForPrompt", timeoutMs: 30000 },
|
||||
{ type: "send", value: "ls -la" },
|
||||
{ type: "waitForPrompt", timeoutMs: 30000 },
|
||||
], "2026-06-27");
|
||||
assert.match(code, /sendLine\("ls -la"\)/);
|
||||
assert.match(code, /waitForPrompt\(30000\)/);
|
||||
assert.doesNotMatch(code, /waitFor\("\$ "/);
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
"use strict";
|
||||
|
||||
/** @see domain/snippetScript.ts DEFAULT_SHELL_PROMPT_PATTERNS */
|
||||
const DEFAULT_SHELL_PROMPT_PATTERNS = ["# ", "$ ", "~# ", "~$ ", "% "];
|
||||
|
||||
/** @see domain/snippetScript.ts SHELL_PROMPT_END_REGEX */
|
||||
const SHELL_PROMPT_END_REGEX = /(?:~[#$]\s*|[@][^\n]{0,120}[:][^\n]{0,120}[#$%]\s*)$/m;
|
||||
|
||||
function shellPromptPatterns() {
|
||||
return [...DEFAULT_SHELL_PROMPT_PATTERNS, SHELL_PROMPT_END_REGEX];
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
DEFAULT_SHELL_PROMPT_PATTERNS,
|
||||
SHELL_PROMPT_END_REGEX,
|
||||
shellPromptPatterns,
|
||||
};
|
||||
Reference in new issue
Block a user