From 0c7f69dc8f5e996ca69905669c0a91aeccff12c9 Mon Sep 17 00:00:00 2001 From: bincxz <16399091+binaricat@users.noreply.github.com> Date: Thu, 9 Jul 2026 16:27:23 +0800 Subject: [PATCH] Fix rerunning stopped automation scripts --- electron/bridges/scriptBridge.cjs | 108 +++++- electron/bridges/scriptBridge.test.cjs | 478 ++++++++++++++++++++++++ electron/scripts/scriptRuntime.cjs | 280 +++++++++----- electron/scripts/scriptRuntime.test.cjs | 38 ++ 4 files changed, 788 insertions(+), 116 deletions(-) diff --git a/electron/bridges/scriptBridge.cjs b/electron/bridges/scriptBridge.cjs index 90db5558d..1f23cdf62 100644 --- a/electron/bridges/scriptBridge.cjs +++ b/electron/bridges/scriptBridge.cjs @@ -23,14 +23,16 @@ let getMainWindow = null; const runs = new Map(); /** @type {Map} */ const recordings = new Map(); -/** @type {Map} */ +/** @type {Map} */ const pendingDialogs = new Map(); -/** @type {Map} */ +/** @type {Map} */ const pendingScreenSnapshots = new Map(); /** @type {Map} */ const scriptLogTokens = new Map(); /** @type {Map>} */ const sessionRunChains = new Map(); +/** @type {Map void }>} */ +const runAbortControls = new Map(); /** @type {Map} */ const rendererSessionMetaById = new Map(); @@ -39,10 +41,13 @@ function enqueueSessionRun(sessionId, task) { const next = previous .catch(() => {}) .then(() => task()); - sessionRunChains.set( - sessionId, - next.then(() => {}, () => {}), - ); + const settled = next.then(() => {}, () => {}); + sessionRunChains.set(sessionId, settled); + settled.finally(() => { + if (sessionRunChains.get(sessionId) === settled) { + sessionRunChains.delete(sessionId); + } + }); return next; } @@ -198,7 +203,38 @@ function isViewportSnapshot(snapshot) { return snapshot?.source !== "buffer-fallback"; } -async function requestScreenSnapshot(sessionId) { +function defaultDialogValue(type) { + if (type === "confirm") return false; + if (type === "prompt") return ""; + if (type === "form") return {}; + if (type === "waitForTimeout") return "abort"; + return undefined; +} + +function settlePendingRunRequests(runId, options = {}) { + const reject = options.reject === true; + const reason = options.reason || new Error("Stopped by user"); + for (const [requestId, pending] of pendingScreenSnapshots.entries()) { + if (pending.runId !== runId) continue; + pendingScreenSnapshots.delete(requestId); + if (reject) { + pending.reject(reason); + } else { + pending.resolve(bufferFallbackSnapshot(pending.sessionId)); + } + } + for (const [requestId, pending] of pendingDialogs.entries()) { + if (pending.runId !== runId) continue; + pendingDialogs.delete(requestId); + if (reject) { + pending.reject(reason); + } else { + pending.resolve(defaultDialogValue(pending.type)); + } + } +} + +async function requestScreenSnapshot(sessionId, runId) { const session = sessions?.get(sessionId); const webContents = session?.webContentsId ? electronModule.webContents.fromId(session.webContentsId) @@ -215,6 +251,7 @@ async function requestScreenSnapshot(sessionId) { }, 3000); pendingScreenSnapshots.set(requestId, { sessionId, + runId, resolve: (value) => { clearTimeout(timer); resolve(value); @@ -228,7 +265,7 @@ async function requestScreenSnapshot(sessionId) { }); } -function showDialog(type, message, defaultValue, extras = {}) { +function showDialog(type, message, defaultValue, extras = {}, runId) { const win = getMainWindow?.(); const webContents = win?.webContents; if (!webContents) { @@ -246,6 +283,7 @@ function showDialog(type, message, defaultValue, extras = {}) { }, 120000); pendingDialogs.set(requestId, { type, + runId, resolve: (value) => { clearTimeout(timer); resolve(value); @@ -265,20 +303,22 @@ function showDialog(type, message, defaultValue, extras = {}) { }); } -function showWaitForTimeoutDialog(pattern, timeoutMs) { +function showWaitForTimeoutDialog(pattern, timeoutMs, runId) { return showDialog( "waitForTimeout", `Timed out waiting for "${pattern}" after ${timeoutMs}ms`, undefined, { pattern, timeoutMs }, + runId, ); } -async function syncOutputBufferFromSnapshot(sessionId) { +async function syncOutputBufferFromSnapshot(sessionId, runId, isAborted = () => false) { const buffer = getOrCreateBuffer(sessionId); const syncStartText = buffer.getText(); try { - const snapshot = await requestScreenSnapshot(sessionId); + const snapshot = await requestScreenSnapshot(sessionId, runId); + if (isAborted()) return; const screenText = (snapshot.lines || []).join("\n"); // Buffer-fallback snapshots are the full script output/scrollback, not the @@ -287,6 +327,7 @@ async function syncOutputBufferFromSnapshot(sessionId) { // the pre-sync length so bytes that arrived during the await stay fresh // (same trailingFresh idea as the viewport path). if (!isViewportSnapshot(snapshot) || !screenText) { + if (isAborted()) return; buffer.markOutputConsumedThrough(syncStartText.length, { preserveTailPatterns: shellPromptPatterns(), }); @@ -303,8 +344,10 @@ async function syncOutputBufferFromSnapshot(sessionId) { const trailingFresh = currentText.startsWith(syncStartText) ? currentText.slice(syncStartText.length) : ""; + if (isAborted()) return; buffer.replaceWithVisibleScreen(screenText, trailingFresh, syncStartText); } catch { + if (isAborted()) return; // Snapshot failed: baseline existing buffer so waits require new output. if (buffer.getText() === syncStartText) { buffer.markOutputConsumedThrough(syncStartText.length, { @@ -348,22 +391,32 @@ async function runScriptOnSession({ runs.set(runId, run); broadcastRuns(); + let abortRun = () => {}; + const abortPromise = new Promise((_, reject) => { + abortRun = (reason) => reject(reason || new Error("Script stopped")); + }); + abortPromise.catch(() => {}); + runAbortControls.set(runId, { abort: abortRun }); + const runtime = createScriptRuntime({ sessionId, runId, appVersion: electronModule?.app?.getVersion?.(), appendLog: (id, message) => { const entry = runs.get(id); - if (!entry) return; + if (!entry || entry.aborted || entry.endedAt) return; entry.logs.push({ at: Date.now(), message }); broadcastRuns(); }, - writeToSession, + writeToSession: (sid, data, options) => { + if (run.aborted || run.endedAt) return; + writeToSession(sid, data, options); + }, getOutputBuffer: getOrCreateBuffer, - getScreenSnapshot: requestScreenSnapshot, + getScreenSnapshot: (sid) => requestScreenSnapshot(sid, runId), getSessionMeta, - showDialog, - showWaitForTimeoutDialog, + showDialog: (type, message, defaultValue, extras) => showDialog(type, message, defaultValue, extras, runId), + showWaitForTimeoutDialog: (pattern, timeoutMs) => showWaitForTimeoutDialog(pattern, timeoutMs, runId), disconnectSession: async (sid) => { if (terminalWorkerManager) { terminalWorkerManager.send("netcatty:close", { sessionId: sid }); @@ -401,15 +454,22 @@ async function runScriptOnSession({ startedAt: run.startedAt, onStatusChange: (id, patch) => { const entry = runs.get(id); - if (!entry) return; + if (!entry || entry.aborted || entry.endedAt) return; Object.assign(entry, patch); broadcastRuns(); }, }); try { - await syncOutputBufferFromSnapshot(sessionId); - await runtime.execute(content); + const operationPromise = (async () => { + await syncOutputBufferFromSnapshot(sessionId, runId, () => run.aborted); + await runtime.execute(content); + })(); + operationPromise.catch(() => {}); + await Promise.race([ + operationPromise, + abortPromise, + ]); if (run.aborted) { run.status = "failed"; run.error = run.error || "Stopped by user"; @@ -431,6 +491,11 @@ async function runScriptOnSession({ run.error = err?.message || String(err); run.logs.push({ at: Date.now(), message: run.error }); } finally { + settlePendingRunRequests(runId, { + reject: run.aborted, + reason: new Error("Stopped by user"), + }); + runAbortControls.delete(runId); broadcastRuns(); } } @@ -493,6 +558,11 @@ function handleScriptStop(_event, payload = {}) { run.endedAt = Date.now(); run.waitingFor = undefined; getOrCreateBuffer(run.sessionId).abortWaiters("Stopped by user"); + settlePendingRunRequests(run.runId, { + reject: false, + reason: new Error("Stopped by user"), + }); + runAbortControls.get(run.runId)?.abort(new Error("Stopped by user")); broadcastRuns(); return { ok: true }; } diff --git a/electron/bridges/scriptBridge.test.cjs b/electron/bridges/scriptBridge.test.cjs index 2a8fdc212..cbadb9293 100644 --- a/electron/bridges/scriptBridge.test.cjs +++ b/electron/bridges/scriptBridge.test.cjs @@ -7,6 +7,16 @@ function delay(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } +async function waitUntil(predicate, timeoutMs = 1000) { + const startedAt = Date.now(); + while (Date.now() - startedAt < timeoutMs) { + const value = predicate(); + if (value) return value; + await delay(10); + } + throw new Error("Timed out waiting for condition"); +} + test("script run writes through terminal worker manager when enabled", async () => { const handlers = new Map(); const workerSends = []; @@ -156,6 +166,474 @@ test("same session script runs are serialized through the session mutex", async assert.deepEqual(writeOrder, ["slow-run", "fast-run"]); }); +test("stopping a script releases the session queue so it can run again", async () => { + const handlers = new Map(); + const sentRunUpdates = []; + const writes = []; + let dialogRequestId; + + scriptBridge.init({ + sessions: new Map(), + electronModule: { + app: { + getVersion: () => "test", + getPath: () => process.cwd(), + }, + }, + terminalBridge: { + writeToSession(_event, payload) { + writes.push(String(payload.data || "")); + }, + }, + terminalWorkerManager: null, + getMainWindow: () => ({ + webContents: { + send(channel, payload) { + if (channel === "netcatty:script:runs-updated") { + sentRunUpdates.push(payload.runs); + } + if (channel === "netcatty:script:dialog-request") { + dialogRequestId = payload.requestId; + } + if (channel === "netcatty:script:screen-snapshot-request") { + setImmediate(() => { + handlers.get("netcatty:script:screen-snapshot-response")({}, { + requestId: payload.requestId, + snapshot: { + rows: 24, + cols: 80, + currentRow: 0, + lines: [], + }, + }); + }); + } + }, + }, + }), + }); + scriptBridge.registerHandlers({ + handle(channel, handler) { + handlers.set(channel, handler); + }, + }); + + const runHandler = handlers.get("netcatty:script:run"); + const firstRunPromise = runHandler({}, { + scriptId: "stopped", + scriptLabel: "Stopped", + sessionId: "session-rerun", + content: ` + const allowed = await nct.dialog.confirm('continue?'); + if (allowed) { + await nct.screen.sendLine('old-run'); + } + `, + permissionMode: "auto", + }); + + await waitUntil(() => dialogRequestId); + const firstRunId = await waitUntil(() => ( + sentRunUpdates + .flat() + .find((run) => run.scriptId === "stopped" && run.status === "running") + ?.runId + )); + + assert.deepEqual(await handlers.get("netcatty:script:stop")({}, { runId: firstRunId }), { ok: true }); + + await Promise.race([ + runHandler({}, { + scriptId: "rerun", + scriptLabel: "Rerun", + sessionId: "session-rerun", + content: "await nct.screen.sendLine('second-run');", + permissionMode: "auto", + }), + delay(500).then(() => { + throw new Error("rerun stayed blocked behind stopped script"); + }), + ]); + await firstRunPromise; + + assert.ok(writes.some((data) => data.includes("second-run"))); + assert.ok(!writes.some((data) => data.includes("old-run"))); + + assert.deepEqual(await handlers.get("netcatty:script:dialog-response")({}, { + requestId: dialogRequestId, + value: true, + }), { ok: false }); + await delay(100); + assert.ok(!writes.some((data) => data.includes("old-run"))); + + const stoppedRun = sentRunUpdates.flat().find((run) => ( + run.runId === firstRunId && run.status === "failed" + )); + assert.equal(stoppedRun.status, "failed"); + assert.equal(stoppedRun.error, "Stopped by user"); +}); + +test("late startup snapshots from a stopped script do not seed the next run", async () => { + const handlers = new Map(); + const writes = []; + const sentRunUpdates = []; + const snapshotRequestIds = []; + + scriptBridge.removeSessionBuffer("session-late-snapshot"); + scriptBridge.init({ + sessions: new Map(), + electronModule: { + app: { + getVersion: () => "test", + getPath: () => process.cwd(), + }, + }, + terminalBridge: { + writeToSession(_event, payload) { + writes.push(String(payload.data || "")); + }, + }, + terminalWorkerManager: null, + getMainWindow: () => ({ + webContents: { + send(channel, payload) { + if (channel === "netcatty:script:runs-updated") { + sentRunUpdates.push(payload.runs); + } + if (channel === "netcatty:script:dialog-request") { + setImmediate(() => { + handlers.get("netcatty:script:dialog-response")({}, { + requestId: payload.requestId, + value: "abort", + }); + }); + } + if (channel === "netcatty:script:screen-snapshot-request") { + snapshotRequestIds.push(payload.requestId); + } + }, + }, + }), + }); + scriptBridge.registerHandlers({ + handle(channel, handler) { + handlers.set(channel, handler); + }, + }); + + const runHandler = handlers.get("netcatty:script:run"); + const firstRunPromise = runHandler({}, { + scriptId: "stopped-before-snapshot", + scriptLabel: "Stopped before snapshot", + sessionId: "session-late-snapshot", + content: "await nct.screen.sendLine('old-run');", + permissionMode: "auto", + }); + + const firstSnapshotRequestId = await waitUntil(() => snapshotRequestIds[0]); + const firstRunId = await waitUntil(() => ( + sentRunUpdates + .flat() + .find((run) => run.scriptId === "stopped-before-snapshot" && run.status === "running") + ?.runId + )); + assert.deepEqual(await handlers.get("netcatty:script:stop")({}, { runId: firstRunId }), { ok: true }); + await firstRunPromise; + + const secondRunPromise = runHandler({}, { + scriptId: "second-after-late-snapshot", + scriptLabel: "Second after late snapshot", + sessionId: "session-late-snapshot", + content: ` + try { + await nct.screen.waitForText('OLD_READY', 200); + await nct.screen.sendLine('bad-write'); + } catch { + await nct.screen.sendLine('good-write'); + } + `, + permissionMode: "auto", + }); + + const secondSnapshotRequestId = await waitUntil(() => snapshotRequestIds[1]); + assert.deepEqual(await handlers.get("netcatty:script:screen-snapshot-response")({}, { + requestId: secondSnapshotRequestId, + snapshot: { + rows: 24, + cols: 80, + currentRow: 0, + lines: [], + }, + }), { ok: true }); + + await delay(30); + assert.deepEqual(await handlers.get("netcatty:script:screen-snapshot-response")({}, { + requestId: firstSnapshotRequestId, + snapshot: { + rows: 24, + cols: 80, + currentRow: 0, + lines: ["OLD_READY"], + }, + }), { ok: false }); + + await secondRunPromise; + assert.ok(writes.some((data) => data.includes("good-write"))); + assert.ok(!writes.some((data) => data.includes("bad-write"))); + assert.ok(!writes.some((data) => data.includes("old-run"))); + scriptBridge.removeSessionBuffer("session-late-snapshot"); +}); + +test("completed scripts clear unawaited dialog requests without rejecting them as stopped", async () => { + const handlers = new Map(); + const sentRunUpdates = []; + let dialogRequestId; + + scriptBridge.init({ + sessions: new Map(), + electronModule: { + app: { + getVersion: () => "test", + getPath: () => process.cwd(), + }, + }, + terminalBridge: { + writeToSession() {}, + }, + terminalWorkerManager: null, + getMainWindow: () => ({ + webContents: { + send(channel, payload) { + if (channel === "netcatty:script:runs-updated") { + sentRunUpdates.push(payload.runs); + } + if (channel === "netcatty:script:dialog-request") { + dialogRequestId = payload.requestId; + } + if (channel === "netcatty:script:screen-snapshot-request") { + setImmediate(() => { + handlers.get("netcatty:script:screen-snapshot-response")({}, { + requestId: payload.requestId, + snapshot: { + rows: 24, + cols: 80, + currentRow: 0, + lines: [], + }, + }); + }); + } + }, + }, + }), + }); + scriptBridge.registerHandlers({ + handle(channel, handler) { + handlers.set(channel, handler); + }, + }); + + await handlers.get("netcatty:script:run")({}, { + scriptId: "unawaited-dialog", + scriptLabel: "Unawaited dialog", + sessionId: "session-unawaited-dialog", + content: ` + void nct.dialog.confirm('background prompt'); + nct.log('done'); + `, + permissionMode: "auto", + }); + + assert.ok(dialogRequestId); + const finalRun = sentRunUpdates.at(-1).find((run) => run.scriptId === "unawaited-dialog"); + assert.equal(finalRun.status, "completed"); + assert.deepEqual(await handlers.get("netcatty:script:dialog-response")({}, { + requestId: dialogRequestId, + value: true, + }), { ok: false }); +}); + +test("stopping scripts clears unawaited dialog requests without unhandled rejections", async () => { + const handlers = new Map(); + const sentRunUpdates = []; + const unhandled = []; + let dialogRequestId; + + const onUnhandledRejection = (reason) => { + unhandled.push(reason); + }; + process.on("unhandledRejection", onUnhandledRejection); + try { + scriptBridge.init({ + sessions: new Map(), + electronModule: { + app: { + getVersion: () => "test", + getPath: () => process.cwd(), + }, + }, + terminalBridge: { + writeToSession() {}, + }, + terminalWorkerManager: null, + getMainWindow: () => ({ + webContents: { + send(channel, payload) { + if (channel === "netcatty:script:runs-updated") { + sentRunUpdates.push(payload.runs); + } + if (channel === "netcatty:script:dialog-request") { + dialogRequestId = payload.requestId; + } + if (channel === "netcatty:script:screen-snapshot-request") { + setImmediate(() => { + handlers.get("netcatty:script:screen-snapshot-response")({}, { + requestId: payload.requestId, + snapshot: { + rows: 24, + cols: 80, + currentRow: 0, + lines: [], + }, + }); + }); + } + }, + }, + }), + }); + scriptBridge.registerHandlers({ + handle(channel, handler) { + handlers.set(channel, handler); + }, + }); + + const runPromise = handlers.get("netcatty:script:run")({}, { + scriptId: "stop-unawaited-dialog", + scriptLabel: "Stop unawaited dialog", + sessionId: "session-stop-unawaited-dialog", + content: ` + void nct.dialog.confirm('background prompt'); + await nct.sleep(5000); + `, + permissionMode: "auto", + }); + + await waitUntil(() => dialogRequestId); + const runId = await waitUntil(() => ( + sentRunUpdates + .flat() + .find((run) => run.scriptId === "stop-unawaited-dialog" && run.status === "running") + ?.runId + )); + + assert.deepEqual(await handlers.get("netcatty:script:stop")({}, { runId }), { ok: true }); + await runPromise; + await delay(100); + + assert.equal(unhandled.length, 0); + assert.deepEqual(await handlers.get("netcatty:script:dialog-response")({}, { + requestId: dialogRequestId, + value: true, + }), { ok: false }); + } finally { + process.off("unhandledRejection", onUnhandledRejection); + } +}); + +test("stopping scripts clears unawaited screen reads without unhandled rejections", async () => { + const handlers = new Map(); + const sentRunUpdates = []; + const snapshotRequestIds = []; + const unhandled = []; + + const onUnhandledRejection = (reason) => { + unhandled.push(reason); + }; + process.on("unhandledRejection", onUnhandledRejection); + try { + scriptBridge.init({ + sessions: new Map(), + electronModule: { + app: { + getVersion: () => "test", + getPath: () => process.cwd(), + }, + }, + terminalBridge: { + writeToSession() {}, + }, + terminalWorkerManager: null, + getMainWindow: () => ({ + webContents: { + send(channel, payload) { + if (channel === "netcatty:script:runs-updated") { + sentRunUpdates.push(payload.runs); + } + if (channel === "netcatty:script:screen-snapshot-request") { + snapshotRequestIds.push(payload.requestId); + if (snapshotRequestIds.length === 1) { + setImmediate(() => { + handlers.get("netcatty:script:screen-snapshot-response")({}, { + requestId: payload.requestId, + snapshot: { + rows: 24, + cols: 80, + currentRow: 0, + lines: [], + }, + }); + }); + } + } + }, + }, + }), + }); + scriptBridge.registerHandlers({ + handle(channel, handler) { + handlers.set(channel, handler); + }, + }); + + const runPromise = handlers.get("netcatty:script:run")({}, { + scriptId: "stop-unawaited-screen-read", + scriptLabel: "Stop unawaited screen read", + sessionId: "session-stop-unawaited-screen-read", + content: ` + void nct.screen.getText(); + await nct.sleep(5000); + `, + permissionMode: "auto", + }); + + await waitUntil(() => snapshotRequestIds[1]); + const runId = await waitUntil(() => ( + sentRunUpdates + .flat() + .find((run) => run.scriptId === "stop-unawaited-screen-read" && run.status === "running") + ?.runId + )); + + assert.deepEqual(await handlers.get("netcatty:script:stop")({}, { runId }), { ok: true }); + await runPromise; + await delay(100); + + assert.equal(unhandled.length, 0); + assert.deepEqual(await handlers.get("netcatty:script:screen-snapshot-response")({}, { + requestId: snapshotRequestIds[1], + snapshot: { + rows: 24, + cols: 80, + currentRow: 0, + lines: ["late"], + }, + }), { ok: false }); + } finally { + process.off("unhandledRejection", onUnhandledRejection); + } +}); + test("script run treats worker-managed sessions as connected", async () => { const handlers = new Map(); const sentRunUpdates = []; diff --git a/electron/scripts/scriptRuntime.cjs b/electron/scripts/scriptRuntime.cjs index 1922c7e5f..0aba523a9 100644 --- a/electron/scripts/scriptRuntime.cjs +++ b/electron/scripts/scriptRuntime.cjs @@ -286,6 +286,53 @@ function createScriptRuntime(deps) { lines: [], }; + function assertNotAborted() { + if (deps.isAborted?.()) { + throw new Error("Script stopped"); + } + } + + function abortable(promise) { + if (typeof deps.isAborted !== "function") { + return promise; + } + assertNotAborted(); + return new Promise((resolve, reject) => { + let settled = false; + const finish = (callback, value) => { + if (settled) return; + settled = true; + clearInterval(timer); + callback(value); + }; + const timer = setInterval(() => { + if (!deps.isAborted?.()) return; + finish(reject, new Error("Script stopped")); + }, 50); + Promise.resolve(promise).then( + (value) => { + if (deps.isAborted?.()) { + finish(reject, new Error("Script stopped")); + return; + } + finish(resolve, value); + }, + (err) => { + if (deps.isAborted?.()) { + finish(reject, new Error("Script stopped")); + return; + } + finish(reject, err); + }, + ); + }); + } + + function markHandled(promise) { + Promise.resolve(promise).catch(() => {}); + return promise; + } + function emitStatus(patch = {}) { onStatusChange?.(runId, { progressMode, @@ -305,6 +352,7 @@ function createScriptRuntime(deps) { } async function trackStep(label) { + assertNotAborted(); stepIndex += 1; const activityLabel = truncateActivityLabel(label); emitStatus({ @@ -314,13 +362,15 @@ function createScriptRuntime(deps) { } async function refreshScreenSnapshot() { + assertNotAborted(); if (typeof getScreenSnapshot === "function") { try { - screenSnapshot = await getScreenSnapshot(sessionId); + screenSnapshot = await abortable(getScreenSnapshot(sessionId)); } catch { // fall back to output buffer text } } + assertNotAborted(); return screenSnapshot; } @@ -347,7 +397,8 @@ function createScriptRuntime(deps) { throw err; } onStatusChange?.(runId, { status: "paused", waitingFor: "shell prompt", elapsedMs: Math.max(0, Date.now() - startedAt) }); - const action = await showWaitForTimeoutDialog?.("shell prompt", timeoutMs); + assertNotAborted(); + const action = await abortable(showWaitForTimeoutDialog?.("shell prompt", timeoutMs)); onStatusChange?.(runId, { status: "running" }); if (action === "retry") { continue; @@ -387,7 +438,8 @@ function createScriptRuntime(deps) { throw err; } onStatusChange?.(runId, { status: "paused", waitingFor: label, elapsedMs: Math.max(0, Date.now() - startedAt) }); - const action = await showWaitForTimeoutDialog?.(label, timeoutMs); + assertNotAborted(); + const action = await abortable(showWaitForTimeoutDialog?.(label, timeoutMs)); onStatusChange?.(runId, { status: "running" }); if (action === "retry") { continue; @@ -427,7 +479,8 @@ function createScriptRuntime(deps) { throw err; } onStatusChange?.(runId, { status: "paused", waitingFor: patternLabel, elapsedMs: Math.max(0, Date.now() - startedAt) }); - const action = await showWaitForTimeoutDialog?.(patternLabel, timeoutMs); + assertNotAborted(); + const action = await abortable(showWaitForTimeoutDialog?.(patternLabel, timeoutMs)); onStatusChange?.(runId, { status: "running" }); if (action === "retry") { continue; @@ -516,71 +569,91 @@ function createScriptRuntime(deps) { }, sleep(ms) { const delay = Math.max(0, Number(ms) || 0); - return trackStep(`sleep ${delay}ms`).then(() => interruptibleSleep(delay, deps.isAborted)); + return markHandled(trackStep(`sleep ${delay}ms`).then(() => interruptibleSleep(delay, deps.isAborted))); }, - async startLog(path) { - assertWriteAllowed("session.startLog"); - await trackStep("startLog"); - await startSessionLog?.(sessionId, path); + startLog(path) { + return markHandled((async () => { + assertWriteAllowed("session.startLog"); + await trackStep("startLog"); + assertNotAborted(); + await startSessionLog?.(sessionId, path); + })()); }, - async stopLog() { - await trackStep("stopLog"); - await stopSessionLog?.(sessionId); + stopLog() { + return markHandled((async () => { + await trackStep("stopLog"); + assertNotAborted(); + await stopSessionLog?.(sessionId); + })()); }, - async disconnect() { - assertWriteAllowed("session.disconnect"); - await trackStep("disconnect"); - await disconnectSession?.(sessionId); + disconnect() { + return markHandled((async () => { + assertWriteAllowed("session.disconnect"); + await trackStep("disconnect"); + assertNotAborted(); + 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 }); + send(text) { + return markHandled((async () => { + assertWriteAllowed("screen.send"); + assertNotAborted(); + await waitIfPaused(); + const payload = String(text ?? ""); + await trackStep(`send: ${truncateActivityLabel(formatScriptInputForLog(payload), 60)}`); + assertNotAborted(); + 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 }); + sendLine(text) { + return markHandled((async () => { + assertWriteAllowed("screen.sendLine"); + assertNotAborted(); + await waitIfPaused(); + const line = String(text ?? ""); + await trackStep(`sendLine: ${truncateActivityLabel(line, 60)}`); + assertNotAborted(); + appendLog(runId, `→ ${line}`); + writeToSession(sessionId, `${line}\r`, { automated: true }); + })()); }, waitFor(pattern, timeoutMs = 30000) { - return waitForWithRecovery(pattern, timeoutMs); + return markHandled(waitForWithRecovery(pattern, timeoutMs)); }, waitForText(text, timeoutMs = 30000) { - return waitForWithRecovery(text, timeoutMs, { + return markHandled(waitForWithRecovery(text, timeoutMs, { waitMethod: "waitForText", operationLabel: "waitForText", - }); + })); }, waitForRegex(pattern, timeoutMs = 30000) { - return waitForWithRecovery(pattern, timeoutMs, { + return markHandled(waitForWithRecovery(pattern, timeoutMs, { waitMethod: "waitForRegex", operationLabel: "waitForRegex", - }); + })); }, waitForPrompt(timeoutMs = 60000) { - return waitForPromptWithRecovery(timeoutMs); + return markHandled(waitForPromptWithRecovery(timeoutMs)); }, - async waitForAny(patterns, timeoutMs = 30000) { - return waitForAnyWithRecovery(patterns, timeoutMs); + waitForAny(patterns, timeoutMs = 30000) { + return markHandled(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"); + getText(startRow, endRow) { + return markHandled((async () => { + await refreshScreenSnapshot(); + assertNotAborted(); + 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; @@ -591,64 +664,77 @@ function createScriptRuntime(deps) { get cols() { return screenSnapshot.cols ?? 80; }, - async clear() { - assertWriteAllowed("screen.clear"); - await trackStep("clear"); - writeToSession(sessionId, "\x1b[2J\x1b[H", { automated: true }); + clear() { + return markHandled((async () => { + assertWriteAllowed("screen.clear"); + await trackStep("clear"); + assertNotAborted(); + writeToSession(sessionId, "\x1b[2J\x1b[H", { automated: true }); + })()); }, }; const dialogApi = { alert(message) { - return showDialog("alert", String(message ?? "")); + assertNotAborted(); + return markHandled(showDialog("alert", String(message ?? ""))); }, confirm(message) { - return showDialog("confirm", String(message ?? "")); + assertNotAborted(); + return markHandled(showDialog("confirm", String(message ?? ""))); }, prompt(message, defaultValue = "") { - return showDialog("prompt", String(message ?? ""), String(defaultValue ?? "")); + assertNotAborted(); + return markHandled(showDialog("prompt", String(message ?? ""), String(defaultValue ?? ""))); }, form(spec) { + assertNotAborted(); const form = normalizeDialogFormSpec(spec); - return showDialog("form", form.message, undefined, { form }); + return markHandled(showDialog("form", form.message, undefined, { form })); }, - async select(message, options, defaultValue) { - const values = await dialogApi.form({ - message, - fields: [{ - type: "select", - name: "value", - label: message, - options, - defaultValue, - }], - }); - return String(values?.value ?? ""); + select(message, options, defaultValue) { + return markHandled((async () => { + const values = await dialogApi.form({ + message, + fields: [{ + type: "select", + name: "value", + label: message, + options, + defaultValue, + }], + }); + return String(values?.value ?? ""); + })()); }, - async radio(message, options, defaultValue) { - const values = await dialogApi.form({ - message, - fields: [{ - type: "radio", - name: "value", - label: message, - options, - defaultValue, - }], - }); - return String(values?.value ?? ""); + radio(message, options, defaultValue) { + return markHandled((async () => { + const values = await dialogApi.form({ + message, + fields: [{ + type: "radio", + name: "value", + label: message, + options, + defaultValue, + }], + }); + return String(values?.value ?? ""); + })()); }, - async checkbox(message, defaultChecked = false) { - const values = await dialogApi.form({ - message, - fields: [{ - type: "checkbox", - name: "value", - label: message, - defaultValue: defaultChecked, - }], - }); - return Boolean(values?.value); + checkbox(message, defaultChecked = false) { + return markHandled((async () => { + const values = await dialogApi.form({ + message, + fields: [{ + type: "checkbox", + name: "value", + label: message, + defaultValue: defaultChecked, + }], + }); + return Boolean(values?.value); + })()); }, }; @@ -660,6 +746,7 @@ function createScriptRuntime(deps) { version: deps.appVersion || "0.0.0", sleep: sessionApi.sleep.bind(sessionApi), log(message) { + assertNotAborted(); stepIndex += 1; emitStatus({ activityLabel: "log", @@ -670,20 +757,18 @@ function createScriptRuntime(deps) { }; async function waitIfPaused() { + assertNotAborted(); while (isPaused?.()) { - if (deps.isAborted?.()) { - throw new Error("Script stopped"); - } + assertNotAborted(); onStatusChange?.(runId, { status: "paused", elapsedMs: Math.max(0, Date.now() - startedAt) }); await interruptibleSleep(100, deps.isAborted); } + assertNotAborted(); onStatusChange?.(runId, { status: "running", elapsedMs: Math.max(0, Date.now() - startedAt) }); } async function execute(source) { - if (deps.isAborted?.()) { - throw new Error("Script stopped"); - } + assertNotAborted(); const wrapped = wrapScriptSource(source); const sandbox = { nct, @@ -697,8 +782,9 @@ function createScriptRuntime(deps) { 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; + await abortable(result); } + assertNotAborted(); } return { execute, nct }; diff --git a/electron/scripts/scriptRuntime.test.cjs b/electron/scripts/scriptRuntime.test.cjs index f6d142802..fb4eedd2e 100644 --- a/electron/scripts/scriptRuntime.test.cjs +++ b/electron/scripts/scriptRuntime.test.cjs @@ -427,3 +427,41 @@ test("createScriptRuntime convenience dialog controls return single values", asy assert.deepEqual(calls.map((call) => call.fieldType), ["select", "radio", "checkbox"]); assert.deepEqual(values, ["prod", "safe", "true"]); }); + +test("createScriptRuntime does not open dialogs after a script is stopped", async () => { + let aborted = false; + let dialogCalls = 0; + 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 () => { + dialogCalls += 1; + return true; + }, + isPaused: () => false, + isAborted: () => aborted, + onStatusChange: () => {}, + }); + + const run = runtime.execute(` + try { + await nct.sleep(5000); + } catch { + await nct.dialog.confirm('still there?'); + } + `); + setTimeout(() => { + aborted = true; + }, 30); + + await assert.rejects(run, /Script stopped/); + assert.equal(dialogCalls, 0); +});