From 4735e9ace07ab4d23dfd691f3e55d29159a16762 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=A4=A7=E7=8C=AB?= <16399091+binaricat@users.noreply.github.com> Date: Thu, 9 Jul 2026 17:58:18 +0800 Subject: [PATCH] fix: bastion script waits and keyboard-like sendLine (#1960) (#2055) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Keep only the confirmed product fixes for 奇安信-style auto-login: 1. Seed startup screen from viewport or live buffer so on-screen menus stay waitable (never mark the whole buffer consumed at script start). 2. sendLine emits body then CR separately, matching real keyboard input. 3. After sendLine, consume only pre-send buffer length so peer prompts that arrive between body and Enter remain matchable for the next step. --- components/Terminal.tsx | 15 ++ electron/bridges/scriptBridge.cjs | 90 +++++++---- electron/bridges/scriptBridge.test.cjs | 150 +++++++++++++++--- electron/scripts/scriptRuntime.cjs | 20 ++- electron/scripts/sessionOutputBuffer.cjs | 23 +++ .../scripts/screenSnapshotRegistry.ts | 2 + 6 files changed, 244 insertions(+), 56 deletions(-) diff --git a/components/Terminal.tsx b/components/Terminal.tsx index 272529779..9bdb9987d 100644 --- a/components/Terminal.tsx +++ b/components/Terminal.tsx @@ -1720,6 +1720,21 @@ const TerminalComponent: React.FC = ({ return registerScreenSnapshotProvider(sessionId, () => { const term = termRef.current; if (!term?.buffer?.active) { + // Hibernated terminals: prefer last captured viewport for script sync. + const hibernatedViewport = + hibernateViewportSnapshotRef.current + || hibernateSnapshotRef.current + || hibernatePendingBufferRef.current; + if (hibernatedViewport) { + const lines = hibernatedViewport.split("\n"); + return { + rows: Math.max(lines.length, 1), + cols: 80, + currentRow: Math.max(lines.length - 1, 0), + lines, + source: "hibernate-viewport", + }; + } return { rows: 24, cols: 80, currentRow: 0, lines: [] }; } const buffer = term.buffer.active; diff --git a/electron/bridges/scriptBridge.cjs b/electron/bridges/scriptBridge.cjs index 4c974cf45..0275ec7b1 100644 --- a/electron/bridges/scriptBridge.cjs +++ b/electron/bridges/scriptBridge.cjs @@ -180,10 +180,13 @@ function writeToSession(sessionId, data, options = {}) { payload, ); } + // sendLine may emit body and CR as two writes. Only the final write should + // invalidate the startup seed — otherwise prompt text that arrives in the + // gap is marked consumed and the next wait never sees it (#1960). if (options.automated !== false && data && data !== "\x03") { - // Sending a command means later waits must observe post-input output, not - // the startup viewport / preserved prompt that was seeded for #1960. - getOrCreateBuffer(sessionId).invalidateStartupSeed(); + if (options.invalidateStartupSeed !== false) { + getOrCreateBuffer(sessionId).invalidateStartupSeed(); + } notifyScriptSessionInput(sessionId, data); } } @@ -203,6 +206,45 @@ function isViewportSnapshot(snapshot) { return snapshot?.source !== "buffer-fallback"; } +function stripTrailingBlankLines(text) { + return String(text || "").replace(/(?:[ \t]*\r?\n)*$/u, ""); +} + +function normalizeNewlines(text) { + return String(text || "").replace(/\r\n/g, "\n").replace(/\r/g, "\n"); +} + +/** + * Prefer viewport when it is the live screen suffix (drops scrolled-off + * scrollback — #1821). Prefer live buffer when the viewport is empty or a + * lagging/incomplete paint of the menu already on the tap path (#1960). + */ +function resolveStartupSeedText(viewportText, bufferText) { + const viewportRaw = String(viewportText || ""); + const bufferRaw = String(bufferText || ""); + const viewportCore = stripTrailingBlankLines(normalizeNewlines(viewportRaw)); + const bufferCore = stripTrailingBlankLines(normalizeNewlines(bufferRaw)); + + if (!viewportCore) return bufferRaw; + if (!bufferCore) return viewportRaw; + if (viewportCore === bufferCore) return viewportRaw; + if (bufferCore.endsWith(viewportCore)) return viewportRaw; + if (bufferCore.startsWith(viewportCore) || bufferCore.includes(viewportCore)) { + return bufferRaw; + } + return viewportRaw; +} + +function seedBufferFromScreen(buffer, screenText, syncStartText) { + const currentText = buffer.getText(); + const trailingFresh = currentText.startsWith(syncStartText) + ? currentText.slice(syncStartText.length) + : ""; + const seedText = resolveStartupSeedText(screenText, syncStartText); + if (!seedText && !trailingFresh) return; + buffer.replaceWithVisibleScreen(seedText || "", trailingFresh, syncStartText); +} + function defaultDialogValue(type) { if (type === "confirm") return false; if (type === "prompt") return ""; @@ -328,38 +370,21 @@ async function syncOutputBufferFromSnapshot(sessionId, runId, isAborted = () => if (isAborted()) return; const screenText = (snapshot.lines || []).join("\n"); - // Buffer-fallback snapshots are the full script output/scrollback, not the - // visible viewport. Seeding them as waitable would rematch scrolled-off - // text (#1821). Keep the consumed baseline for that path — but only through - // 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(), - }); - return; - } - - // Seed the script buffer from the current visible screen so waits can match - // text already on screen (e.g. bastion "SSH资源" near the top of a long menu). - // Marking the whole buffer consumed made those waits time out (#1960). - // If live output arrived during the snapshot IPC round-trip (BEL keepalives, - // etc.), keep that trailing fresh data after the viewport instead of - // discarding the snapshot. - const currentText = buffer.getText(); - const trailingFresh = currentText.startsWith(syncStartText) - ? currentText.slice(syncStartText.length) - : ""; + // #1960: never mark the startup buffer as fully consumed. Bastion menus + // already on screen must stay waitable. Prefer a real viewport when it is + // the live screen (drops scrolled-off scrollback for #1821); otherwise seed + // the live main-process buffer (empty / lagging / buffer-fallback). if (isAborted()) return; - buffer.replaceWithVisibleScreen(screenText, trailingFresh, syncStartText); + if (isViewportSnapshot(snapshot) && stripTrailingBlankLines(screenText)) { + seedBufferFromScreen(buffer, screenText, syncStartText); + } else { + seedBufferFromScreen(buffer, syncStartText, syncStartText); + } } catch { if (isAborted()) return; - // Snapshot failed: baseline existing buffer so waits require new output. - if (buffer.getText() === syncStartText) { - buffer.markOutputConsumedThrough(syncStartText.length, { - preserveTailPatterns: shellPromptPatterns(), - }); + // Snapshot failed: still seed whatever the script buffer already has. + if (syncStartText) { + seedBufferFromScreen(buffer, "", syncStartText); } } } @@ -685,4 +710,5 @@ module.exports = { registerHandlers, appendSessionOutput, removeSessionBuffer, + resolveStartupSeedText, }; diff --git a/electron/bridges/scriptBridge.test.cjs b/electron/bridges/scriptBridge.test.cjs index b9a945aaf..4ef0fcc83 100644 --- a/electron/bridges/scriptBridge.test.cjs +++ b/electron/bridges/scriptBridge.test.cjs @@ -64,11 +64,17 @@ test("script run writes through terminal worker manager when enabled", async () }); assert.deepEqual(terminalWrites, []); - assert.equal(workerSends.length, 1); + // sendLine emits body then CR as separate keyboard-like writes (#1960). + assert.equal(workerSends.length, 2); assert.equal(workerSends[0].channel, "netcatty:write"); assert.deepEqual(workerSends[0].payload, { sessionId: "session-1", - data: "echo hi\r", + data: "echo hi", + automated: true, + }); + assert.deepEqual(workerSends[1].payload, { + sessionId: "session-1", + data: "\r", automated: true, }); }); @@ -1279,16 +1285,15 @@ test("script waitFor ignores keywords that have scrolled off the visible screen" scriptBridge.removeSessionBuffer(sessionId); }); -test("script waitFor does not seed buffer-fallback scrollback as visible screen", async () => { +test("script waitFor seeds buffer-fallback so connection banners stay waitable (#1960)", async () => { const handlers = new Map(); const sentRunUpdates = []; const sessionId = "session-buffer-fallback-scrollback"; scriptBridge.removeSessionBuffer(sessionId); - // When the session's webContents is missing, requestScreenSnapshot falls back - // to the full script buffer. That must stay consumed so scrolled-off keywords - // do not rematch (#1821 / Codex review on #2035). - scriptBridge.appendSessionOutput(sessionId, "old deployment READY marker\nuser@host:~$ \n"); + // Buffer-fallback must seed the live buffer so bastion menus already + // received stay waitable. Scrolled-off rematch is covered by viewport tests. + scriptBridge.appendSessionOutput(sessionId, "Welcome to SSHD\nSSH资源(5) :\n> \n"); scriptBridge.init({ sessions: new Map([ [sessionId, { webContentsId: 999 }], @@ -1323,31 +1328,20 @@ test("script waitFor does not seed buffer-fallback scrollback as visible screen" }, }); - const runPromise = handlers.get("netcatty:script:run")({}, { + await handlers.get("netcatty:script:run")({}, { scriptId: "buffer-fallback", scriptLabel: "Buffer fallback", sessionId, content: ` - const value = await nct.screen.waitFor('READY', 1000); + const value = await nct.screen.waitForRegex("SSH资源\\\\s*\\\\(\\\\d+\\\\)\\\\s*:", 1000); nct.log('matched ' + value); `, permissionMode: "auto", }); - await delay(50); - const earlyRun = sentRunUpdates.at(-1)?.find((run) => run.scriptId === "buffer-fallback"); - assert.notEqual(earlyRun?.status, "completed"); - assert.doesNotMatch( - (earlyRun?.logs || []).map((entry) => entry.message).join("\n"), - /matched READY/, - ); - - scriptBridge.appendSessionOutput(sessionId, "fresh READY\n"); - await runPromise; - const finalRun = sentRunUpdates.at(-1).find((run) => run.scriptId === "buffer-fallback"); - assert.equal(finalRun.status, "completed"); - assert.match(finalRun.logs.map((entry) => entry.message).join("\n"), /matched READY/); + assert.equal(finalRun.status, "completed", finalRun.error || "expected completed"); + assert.match(finalRun.logs.map((entry) => entry.message).join("\n"), /matched SSH资源\(5\) :/); scriptBridge.removeSessionBuffer(sessionId); }); @@ -1843,7 +1837,7 @@ test("script sendLine invalidates startup seed before later waits", async () => permissionMode: "auto", }); - await delay(40); + await delay(80); assert.ok(writes.some((data) => String(data).includes("echo hi"))); // Startup seed must be gone: waits should not resolve on old READY / old prompt. @@ -1862,3 +1856,113 @@ test("script sendLine invalidates startup seed before later waits", async () => assert.match(finalRun.logs.map((entry) => entry.message).join("\n"), /matched READY/); scriptBridge.removeSessionBuffer(sessionId); }); + +test("script sendLine keeps prompts that arrive between body and CR waitable", async () => { + const handlers = new Map(); + const sentRunUpdates = []; + const sessionId = "session-sendline-gap-prompt"; + const writes = []; + + scriptBridge.removeSessionBuffer(sessionId); + scriptBridge.init({ + sessions: new Map(), + electronModule: { + app: { + getVersion: () => "test", + getPath: () => process.cwd(), + }, + webContents: { + fromId: () => null, + }, + }, + terminalBridge: { + writeToSession(_event, payload) { + writes.push(payload.data); + if (payload.data === "3") { + setTimeout(() => { + scriptBridge.appendSessionOutput(sessionId, "\n资源'[Empty]'账户:"); + }, 5); + } + }, + }, + terminalWorkerManager: null, + getMainWindow: () => ({ + webContents: { + id: 1, + send(channel, payload) { + if (channel === "netcatty:script:runs-updated") { + sentRunUpdates.push(payload.runs); + } + 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: ["SSH资源(5) :", "> "], + }, + }); + }); + } + if (channel === "netcatty:script:dialog-request") { + setImmediate(() => { + handlers.get("netcatty:script:dialog-response")({}, { + requestId: payload.requestId, + value: "abort", + }); + }); + } + }, + }, + }), + }); + scriptBridge.registerHandlers({ + handle(channel, handler) { + handlers.set(channel, handler); + }, + }); + + await handlers.get("netcatty:script:run")({}, { + scriptId: "sendline-gap", + scriptLabel: "SendLine gap prompt", + sessionId, + content: ` + await nct.screen.waitForRegex("SSH资源\\\\s*\\\\(\\\\d+\\\\)\\\\s*:", 1000); + await nct.screen.sendLine("3"); + await nct.screen.waitForText("资源'[Empty]'账户:", 1000); + await nct.screen.sendLine("zxadmin"); + nct.log("account sent"); + `, + permissionMode: "auto", + }); + + const finalRun = sentRunUpdates.at(-1).find((run) => run.scriptId === "sendline-gap"); + assert.equal(finalRun.status, "completed", finalRun.error || "expected completed"); + assert.deepEqual(writes.filter((w) => w === "3" || w === "\r" || w === "zxadmin"), [ + "3", + "\r", + "zxadmin", + "\r", + ]); + assert.match(finalRun.logs.map((entry) => entry.message).join("\n"), /account sent/); + scriptBridge.removeSessionBuffer(sessionId); +}); + +test("resolveStartupSeedText prefers buffer when viewport paint lags bastion menu", () => { + const buffer = + "Welcome to SSHD\n\nuser login success\n\nSSH资源(5) :\n [1] host\n"; + const laggingViewport = "Welcome to SSHD\n\nuser login success\n"; + const seed = scriptBridge.resolveStartupSeedText(laggingViewport, buffer); + assert.match(seed, /SSH资源\(5\)/); + assert.equal(scriptBridge.resolveStartupSeedText("", buffer), buffer); +}); + +test("resolveStartupSeedText prefers viewport when buffer only adds scrolled-off prefix", () => { + const viewport = "SSH资源(5) :\n [1] host\n"; + const buffer = `old deployment READY marker\nuser@host:~$ \n${viewport}`; + const seed = scriptBridge.resolveStartupSeedText(viewport, buffer); + assert.equal(seed, viewport); + assert.doesNotMatch(seed, /READY marker/); +}); diff --git a/electron/scripts/scriptRuntime.cjs b/electron/scripts/scriptRuntime.cjs index 696521a5b..1f84aa384 100644 --- a/electron/scripts/scriptRuntime.cjs +++ b/electron/scripts/scriptRuntime.cjs @@ -629,7 +629,25 @@ function createScriptRuntime(deps) { await trackStep(`sendLine: ${truncateActivityLabel(line, 60)}`); if (deps.isAborted?.()) return; appendLog(runId, `→ ${line}`); - writeToSession(sessionId, `${line}\r`, { automated: true }); + // Bastion menus can ignore a single "line\r" packet even when + // stream.write succeeds. Match xterm: body, then Enter (#1960). + // Consume only pre-send buffer length so prompts that arrive between + // body and CR stay waitable for the next step. + const buffer = getOutputBuffer(sessionId); + const lengthBeforeSend = buffer.getText().length; + if (line.length > 0) { + writeToSession(sessionId, line, { + automated: true, + invalidateStartupSeed: false, + }); + await interruptibleSleep(30, deps.isAborted); + if (deps.isAborted?.()) return; + } + writeToSession(sessionId, "\r", { + automated: true, + invalidateStartupSeed: false, + }); + buffer.consumeThroughAbsolute(lengthBeforeSend); })); }, waitFor(pattern, timeoutMs = 30000) { diff --git a/electron/scripts/sessionOutputBuffer.cjs b/electron/scripts/sessionOutputBuffer.cjs index 1c00f9802..b1c8a4c23 100644 --- a/electron/scripts/sessionOutputBuffer.cjs +++ b/electron/scripts/sessionOutputBuffer.cjs @@ -418,6 +418,16 @@ class SessionOutputBuffer { this.append(normalized); // Seed only the visible viewport — not sync-race trailing bytes. this.seededLength = this.getText().length; + this.scanOffset = 0; + // Re-open pending waiters onto the seeded viewport (#1960). + for (const waiter of this.waiters) { + if (typeof waiter.freshBoundary === "number") { + waiter.freshBoundary = 0; + } + if (waiter.custom && typeof waiter.custom.freshBoundary === "number") { + waiter.custom.freshBoundary = 0; + } + } // Preserve a live-tail shell prompt from the viewport for waitForPrompt, // matching the old markOutputConsumedThrough(preserveTailPatterns) behavior. this.preservedTailMatch = null; @@ -433,6 +443,7 @@ class SessionOutputBuffer { endOffset: fresh.matched.endOffset, }; } + this.flushWaiters(); } /** @@ -447,6 +458,18 @@ class SessionOutputBuffer { this.scanOffset = this.getText().length; } + /** + * Mark output through `absoluteLength` as already seen, without consuming + * anything that arrived after that point. Used by sendLine so peer prompts + * that land between body and CR stay waitable (#1960). + */ + consumeThroughAbsolute(absoluteLength) { + this.seededLength = null; + this.preservedTailMatch = null; + const capped = Math.max(0, Math.min(this.getText().length, Number(absoluteLength) || 0)); + this.scanOffset = Math.max(this.scanOffset, capped); + } + consumeFreshPendingMatch(pattern, freshBoundary = this.currentFreshBoundary()) { while (true) { const matched = this.tryMatchPending(pattern); diff --git a/infrastructure/scripts/screenSnapshotRegistry.ts b/infrastructure/scripts/screenSnapshotRegistry.ts index fe16f64ea..a737dfc1e 100644 --- a/infrastructure/scripts/screenSnapshotRegistry.ts +++ b/infrastructure/scripts/screenSnapshotRegistry.ts @@ -3,6 +3,8 @@ export type ScreenSnapshotProvider = () => { cols: number; currentRow: number; lines: string[]; + /** Optional origin marker (e.g. hibernate-viewport). */ + source?: string; }; const providers = new Map();