diff --git a/application/state/useScriptRecorder.test.ts b/application/state/useScriptRecorder.test.ts index c2002cec1..7339a0419 100644 --- a/application/state/useScriptRecorder.test.ts +++ b/application/state/useScriptRecorder.test.ts @@ -499,9 +499,10 @@ test("paced recording uses its captured prefix and never imports text typed whil steps.length = 0; recorder.recordInput("prefix for a dropped first line"); const lineRecorder = recorder.captureSubmittedLineRecorder()!; - await lineRecorder("second was sent"); + await lineRecorder("second was sent", { consumePendingInput: false }); + await recorder.recordEnter(); }); - assert.deepEqual(steps.filter(step => step.type === "send").map(step => step.value), ["second was sent"]); + assert.deepEqual(steps.filter(step => step.type === "send").map(step => step.value), ["second was sent", "prefix for a dropped first line"]); } finally { await act(async () => renderer.unmount()); } diff --git a/application/state/useScriptRecorder.ts b/application/state/useScriptRecorder.ts index 34a8e0b7e..dd431d7b5 100644 --- a/application/state/useScriptRecorder.ts +++ b/application/state/useScriptRecorder.ts @@ -247,15 +247,15 @@ export function useScriptRecorder(sessionId: string | undefined) { const isCurrent = () => generation === recordingGenerationRef.current && sid === sessionIdRef.current && isRecordingRef.current && !isPausedRef.current && !isStoppingRef.current; - return (line: string, options?: { sensitive?: boolean; includePendingInput?: boolean }): Promise => { + return (line: string, options?: { sensitive?: boolean; includePendingInput?: boolean; consumePendingInput?: boolean }): Promise => { // Capturing a batch is not a write. Retain its prefix if no receipt - // arrives; on the first write remove only the still-owned prefix. - if (!consumed && generation === recordingGenerationRef.current && sid === sessionIdRef.current + // arrives; only its prefixed first line can consume the still-owned draft. + if (options?.consumePendingInput !== false && !consumed && generation === recordingGenerationRef.current && sid === sessionIdRef.current && revision === inputRevisionRef.current && inputBufferRef.current.startsWith(pendingInput)) { inputBufferRef.current = inputBufferRef.current.slice(pendingInput.length); inputRevisionRef.current += 1; } - consumed = true; + if (options?.consumePendingInput !== false) consumed = true; if (!isCurrent()) return Promise.resolve(); return recordEnter({ sensitive: options?.sensitive, submittedLine: options?.includePendingInput ? `${pendingInput}${line}` : line }); }; diff --git a/components/Terminal.tsx b/components/Terminal.tsx index bca0d3387..3ecb29580 100644 --- a/components/Terminal.tsx +++ b/components/Terminal.tsx @@ -999,6 +999,9 @@ const TerminalComponent: React.FC = ({ autocompleteAcceptTextRef.current = (text: string) => { const id = sessionRef.current; if (id && text) { + if (["\r", "\n", "\b", "\x7f", "\x15"].some(control => text.includes(control))) { + xtermRuntimeRef.current?.invalidatePendingPasteDraft(); + } const sensitive = passwordPromptActiveRef.current; let textToWrite = text; let handledSubmittedInput = false; diff --git a/components/terminal/runtime/createXTermRuntime.ts b/components/terminal/runtime/createXTermRuntime.ts index 72c31845f..a3f42326c 100644 --- a/components/terminal/runtime/createXTermRuntime.ts +++ b/components/terminal/runtime/createXTermRuntime.ts @@ -252,6 +252,7 @@ export type XTermRuntime = { dispose: () => void; /** Track the pending final line of a serial snippet left for editing. */ recordSerialSnippetInput: (data: string) => void; + invalidatePendingPasteDraft: () => void; /** Current working directory detected via OSC 7 */ currentCwd: string | undefined; keywordHighlighter: KeywordHighlighter; @@ -365,7 +366,7 @@ export type CreateXTermRuntimeContext = { recordBackspace: () => void; recordClearLine: () => void; recordEnter: (options?: { sensitive?: boolean }) => Promise; - captureSubmittedLineRecorder?: () => ((line: string, options?: { sensitive?: boolean; includePendingInput?: boolean }) => Promise) | undefined; + captureSubmittedLineRecorder?: () => ((line: string, options?: { sensitive?: boolean; includePendingInput?: boolean; consumePendingInput?: boolean }) => Promise) | undefined; } | undefined>; passwordPromptActiveRef?: RefObject; allowHostStyleGreaterThanPrompt?: boolean; @@ -1170,6 +1171,7 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime // moved away from the tail, so we conservatively assume it is not). let lastInputWasPrintable = !ctx.commandBufferRef?.current; let commandBufferRevision = 0; + const invalidatePendingPasteDraft = () => { commandBufferRevision += 1; }; const restoreSerialTailForEmptyInput = (data: string) => { // Apply the same rule to typed text, pasted text, and editable snippets. @@ -2161,6 +2163,8 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime onAutocompleteInput: ctx.onAutocompleteInput, }); lastInputWasPrintable = true; + invalidatePendingPasteDraft(); + ctx.scriptRecorderRef?.current?.recordClearLine(); if (ctx.passwordPromptActiveRef) { ctx.passwordPromptActiveRef.current = false; } @@ -2780,7 +2784,7 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime inputRevision: number; sensitive: boolean; recorded: Set; - recordLine?: (line: string, options?: { sensitive?: boolean; includePendingInput?: boolean }) => Promise; + recordLine?: (line: string, options?: { sensitive?: boolean; includePendingInput?: boolean; consumePendingInput?: boolean }) => Promise; }>(); const disposePasteWriteReceipts = netcattyBridge.get()?.onTerminalPasteWrite?.((receipt) => { const pending = pendingLinePastes.get(receipt.requestId); @@ -2792,7 +2796,7 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime const index = receipt.index; if (index !== undefined && Number.isInteger(index) && index >= 0 && index < pending.commands.length && !pending.recorded.has(index)) { - if (pending.recorded.size === 0 && pending.inputRevision === commandBufferRevision + if (index === 0 && pending.inputRevision === commandBufferRevision && ctx.commandBufferRef.current.startsWith(pending.pendingInput)) { ctx.commandBufferRef.current = ctx.commandBufferRef.current.slice(pending.pendingInput.length); if (pending.serialPendingInput !== undefined && ctx.serialLineBufferRef?.current.startsWith(pending.serialPendingInput)) { @@ -2814,7 +2818,7 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime acknowledgedWrite: true, }); void pending.recordLine?.(index === 0 ? pending.firstPastedLine : command, { - sensitive, includePendingInput: index === 0, + sensitive, includePendingInput: index === 0, consumePendingInput: index === 0, }).catch((error) => { logger.warn("Failed to record confirmed paste write", error); }); @@ -3288,6 +3292,7 @@ export const createXTermRuntime = (ctx: CreateXTermRuntimeContext): XTermRuntime getKittyKeyboardProtocolEnabled: () => kittyKeyboardProtocolEnabled, setKittyKeyboardProtocolEnabled, recordSerialSnippetInput, + invalidatePendingPasteDraft, dispose: () => { runtimeDisposed = true; disposeLinePasteHandler?.(); diff --git a/components/terminal/runtime/terminalLinePaste.test.ts b/components/terminal/runtime/terminalLinePaste.test.ts index 2afb6e43d..74f022653 100644 --- a/components/terminal/runtime/terminalLinePaste.test.ts +++ b/components/terminal/runtime/terminalLinePaste.test.ts @@ -16,16 +16,20 @@ const start = source.indexOf("let lastInputWasPrintable ="); const end = source.indexOf(" let kittyCompositionPending", start); const registrationStart = source.indexOf(" const pendingLinePastes ="); const registrationEnd = source.indexOf(" term.onData(", registrationStart); +const urgentStart = source.indexOf(" clearTerminalInputStateForInterrupt({"); +const urgentEnd = source.indexOf(" const interruptEventForKitty", urgentStart); +const urgentCode = "\nconst urgent = () => { const id = ctx.sessionRef.current; const interruptTrace = undefined; " + + source.slice(urgentStart, urgentEnd) + "\n};"; const code = ts.transpileModule( source.slice(start, end) + source.slice(registrationStart, registrationEnd) - + "\nglobalThis.api = { input: handleTerminalInputData, dispose: () => { disposeLinePasteHandler(); disposePasteWriteReceipts?.(); pendingLinePastes.clear(); } };", + + urgentCode + "\nglobalThis.api = { urgent, input: handleTerminalInputData, dispose: () => { disposeLinePasteHandler(); disposePasteWriteReceipts?.(); pendingLinePastes.clear(); } };", { compilerOptions: { target: ts.ScriptTarget.ES2022 } }, ).outputText; const helpers = await Promise.all([ "../../../domain/serialCharMetrics.ts", "./terminalReportSequence.ts", "./terminalInputSanitize.ts", "./terminalBackspaceInput.ts", "./terminalPerCharacterInput.ts", "./terminalSudoAutofill.ts", "./terminalCommandExecution.ts", - "./serialLocalEcho.ts", "../autocomplete/terminalStringCellWidth.ts", + "./terminalInterruptInputState.ts", "./serialLocalEcho.ts", "../autocomplete/terminalStringCellWidth.ts", "./shiftEnterText.ts", "./serialLineInput.ts", "./telnetLocalEcho.ts", ].map(path => import(new URL(path, import.meta.url).href))); @@ -35,9 +39,9 @@ for (const [protocol, lineMode, sensitive] of [ ["ssh", false, false], ["ssh", false, true], ["local", false, false], ["mosh", false, false], ["et", false, false], ["plugin:example", false, false], ] as const) { - for (const completion of ["pending-manual", "pending-clear", "pending-ack", "blocked-first", "failed-first", "complete", "manual", "interrupt", "replacement", "password-ref", "password-screen", "output", "serial-text", "serial-backspace", "serial-clear", "serial-arrow", "serial-delete", "serial-report"] as const) { + for (const completion of ["late-urgent", "filtered-first", "pending-manual", "pending-clear", "pending-ack", "blocked-first", "failed-first", "complete", "manual", "interrupt", "replacement", "password-ref", "password-screen", "output", "serial-text", "serial-backspace", "serial-clear", "serial-arrow", "serial-delete", "serial-report"] as const) { if (completion.startsWith("serial-") && !lineMode) continue; - if (completion.startsWith("pending-") && sensitive) continue; + if ((completion.startsWith("pending-") || completion === "filtered-first") && sensitive) continue; test(`${completion}: ${protocol} confirmed line paste consumes pending text with pacing (lineMode=${lineMode}, sensitive=${sensitive})`, async (t) => { t.mock.timers.enable({ apis: ["setTimeout"] }); const wire: string[] = []; @@ -52,6 +56,7 @@ for (const [protocol, lineMode, sensitive] of [ const outputTriggers: string[] = []; const recorded: string[] = []; let recorderInput = ""; + const queuedReceipts: unknown[] = []; let receiptListener: ((event: unknown) => void) | undefined; const writes: Array<{ data: string; sensitive?: boolean; lineDelayMs?: number; automated?: boolean }> = []; let rejectPaste = false; @@ -62,14 +67,18 @@ for (const [protocol, lineMode, sensitive] of [ } } }; bridge.init({ sessions: new Map([["serial-1", session]]), - terminalDataPipeline: completion.startsWith("pending-") ? { + terminalDataPipeline: completion.startsWith("pending-") || completion === "filtered-first" ? { has: () => true, interceptInput(_id: string, data: string) { + if (completion === "filtered-first") return data.includes("version") ? "" : data; if (rejectPaste && !releaseFirst) return new Promise(resolve => { releaseFirst = () => resolve(data); }); return data; }, } : undefined, - electronModule: { webContents: { fromId: () => ({ send(channel: string, event: unknown) { if (channel === "netcatty:paste-write") receiptListener?.(event); } }) } }, + electronModule: { webContents: { fromId: () => ({ send(channel: string, event: unknown) { if (channel === "netcatty:paste-write") { + if (completion === "late-urgent") queuedReceipts.push(event); + else receiptListener?.(event); + } } }) } }, }); const ctx = { host: { protocol, id: "h", label: "h" }, sessionId: "tab-1", @@ -118,12 +127,12 @@ for (const [protocol, lineMode, sensitive] of [ ? { isWrapped: false, translateToString: () => liveLine } : undefined } }, }; const env = { - ...Object.assign({}, ...helpers), ...userPaste, ctx, term, crypto, logger: { warn() {} }, + ...Object.assign({}, ...helpers), ...userPaste, ctx, term, crypto, isPluginHostProtocol: () => false, logger: { warn() {} }, netcattyBridge: { get: () => ({ onTerminalPasteWrite: (listener: typeof receiptListener) => { receiptListener = listener; return () => { receiptListener = undefined; }; } }) }, suppressNextTerminalDataBroadcast: false, handlingKittyBroadcast: false, prioritizeTerminalInput() {}, getFlowControllerForTerm: () => null, scrollToBottomAfterInput() {}, writeLocalTerminalData: (data: string) => echo.push(data), - api: undefined as unknown as { input: (data: string) => void; dispose: () => void }, + api: undefined as unknown as { urgent: () => void; input: (data: string) => void; dispose: () => void }, }; vm.runInNewContext(code, env); t.after(() => env.api.dispose()); @@ -143,6 +152,26 @@ for (const [protocol, lineMode, sensitive] of [ }, onPasteData: data => { broadcast.push(data); return true; }, }); + if (completion === "late-urgent") { + ctx.isBroadcastEnabledRef.current = false; + env.api.urgent(); + env.api.input("show new draft"); + for (const receipt of queuedReceipts.splice(0)) receiptListener?.(receipt); + assert.equal(ctx.commandBufferRef.current, "show new draft"); + if (lineMode) assert.equal(ctx.serialLineBufferRef.current, "show new draft"); + env.api.input("\r"); + if (lineMode) assert.equal(wire.at(-1), "show new draft\r"); + return; + } + if (completion === "filtered-first") { + t.mock.timers.tick(250); + await new Promise(resolve => setImmediate(resolve)); + assert.deepEqual(wire, lineMode ? ["show clock\r"] : ["show ", "show clock\r"]); + assert.equal(ctx.commandBufferRef.current, "show "); + if (lineMode) assert.equal(ctx.serialLineBufferRef.current, "show "); + assert.deepEqual(history, ["show clock"]); + return; + } if (completion.startsWith("pending-")) { assert.equal(ctx.commandBufferRef.current, "show "); assert.deepEqual(history, []);