From d48996e09c12bdf158905822c9e3a6f42520815c Mon Sep 17 00:00:00 2001 From: Archie Cho Date: Sat, 21 Nov 2026 15:57:51 +0900 Subject: [PATCH 1/7] fix(wshutil): process terminal input RPCs in arrival order Terminal input commands were dispatched one goroutine per packet, so two controllerinput messages sent in order could reach the PTY reversed. JobCmd.HandleInput holds a mutex, but that only serializes concurrent writers; it cannot restore arrival order. Route controllerinput and jobinput through a single FIFO worker fed by the read loop. Other commands keep running concurrently. TestControllerInputOrdering fails before this change (recorded order is scrambled) and passes after. The symptom was seen with Korean IME input on Windows, but the race applies to any fast typing, paste, or high-latency (WSL/SSH) connection. --- pkg/wshutil/wshrpc.go | 34 ++++++++++++ pkg/wshutil/wshrpc_ordering_test.go | 81 +++++++++++++++++++++++++++++ 2 files changed, 115 insertions(+) create mode 100644 pkg/wshutil/wshrpc_ordering_test.go diff --git a/pkg/wshutil/wshrpc.go b/pkg/wshutil/wshrpc.go index 8a29e204bd..426ed69891 100644 --- a/pkg/wshutil/wshrpc.go +++ b/pkg/wshutil/wshrpc.go @@ -29,6 +29,7 @@ const DefaultTimeoutMs = 5000 const RespChSize = 32 const DefaultMessageChSize = 32 const CtxDoneChSize = 10 +const OrderedChSize = 1024 var blockingExpMap = ds.MakeExpMap[bool]() @@ -58,11 +59,17 @@ type WshRpc struct { EventListener *EventListener ResponseHandlerMap map[string]*RpcResponseHandler // reqId => handler StreamBroker *streamclient.Broker + OrderedCh chan orderedRpcRequest // input commands, handled in arrival order Debug bool DebugName string ServerDone bool } +type orderedRpcRequest struct { + msg RpcMessage + ingressLinkId baseds.LinkId +} + type wshRpcContextKey struct{} type wshRpcRespHandlerContextKey struct{} @@ -231,9 +238,11 @@ func MakeWshRpcWithChannels(inputCh chan baseds.RpcInputChType, outputCh chan [] EventListener: MakeEventListener(), ServerImpl: serverImpl, ResponseHandlerMap: make(map[string]*RpcResponseHandler), + OrderedCh: make(chan orderedRpcRequest, OrderedChSize), } rtn.RpcContext.Store(&rpcCtx) rtn.StreamBroker = streamclient.NewBroker(AdaptWshRpc(rtn)) + go rtn.runOrderedRequests() go rtn.runServer() return rtn } @@ -378,9 +387,27 @@ func (w *WshRpc) handleRequestInternal(req *RpcMessage, ingressLinkId baseds.Lin isAsync = !handlerFn(respHandler) } +// Commands that carry terminal keystrokes. They must be processed in the order the +// read loop received them; everything else may run concurrently. +func isOrderedInputCommand(cmd string) bool { + return cmd == wshrpc.Command_ControllerInput || cmd == "jobinput" +} + +// Single worker: input commands are handled one at a time, in arrival order. +func (w *WshRpc) runOrderedRequests() { + defer panichandler.PanicHandler("wshrpc.runOrderedRequests", recover()) + for req := range w.OrderedCh { + func() { + defer panichandler.PanicHandler("wshrpc.handleOrderedRequest", recover()) + w.handleRequest(&req.msg, req.ingressLinkId) + }() + } +} + func (w *WshRpc) runServer() { defer func() { panichandler.PanicHandler("wshrpc.runServer", recover()) + close(w.OrderedCh) close(w.OutputCh) w.setServerDone() }() @@ -429,6 +456,13 @@ outer: w.handleStreamAck(&msg) continue } + if isOrderedInputCommand(msg.Command) { + // Terminal input must reach the PTY in arrival order. Handling it in a + // goroutine lets a later packet overtake an earlier one, which shows up as + // reordered Hangul/CJK input at the shell. + w.OrderedCh <- orderedRpcRequest{msg: msg, ingressLinkId: inputVal.IngressLinkId} + continue + } ingressLinkId := inputVal.IngressLinkId go func() { diff --git a/pkg/wshutil/wshrpc_ordering_test.go b/pkg/wshutil/wshrpc_ordering_test.go new file mode 100644 index 0000000000..5c8fb2ca64 --- /dev/null +++ b/pkg/wshutil/wshrpc_ordering_test.go @@ -0,0 +1,81 @@ +// Copyright 2026, Command Line Inc. +// SPDX-License-Identifier: Apache-2.0 + +package wshutil + +import ( + "context" + "encoding/json" + "fmt" + "strconv" + "sync" + "testing" + "time" + + "github.com/wavetermdev/waveterm/pkg/baseds" + "github.com/wavetermdev/waveterm/pkg/wshrpc" +) + +type orderTestServer struct { + mu sync.Mutex + got []int +} + +func (s *orderTestServer) WshServerImpl() {} + +func (s *orderTestServer) ControllerInputCommand(ctx context.Context, data wshrpc.CommandBlockInputData) error { + // Earlier messages take longer, so concurrent handling records them out of order. + idx, _ := strconv.Atoi(data.InputData64) + time.Sleep(time.Duration(6-(idx%6)) * time.Millisecond) + s.mu.Lock() + s.got = append(s.got, idx) + s.mu.Unlock() + return nil +} + +func (s *orderTestServer) results() []int { + s.mu.Lock() + defer s.mu.Unlock() + return append([]int(nil), s.got...) +} + +func TestControllerInputOrdering(t *testing.T) { + const n = 40 + inputCh := make(chan baseds.RpcInputChType, n*2) + outputCh := make(chan []byte, n*2) + srv := &orderTestServer{} + MakeWshRpcWithChannels(inputCh, outputCh, wshrpc.RpcContext{Conn: "test"}, srv, "ordertest") + + go func() { + for range outputCh { + } + }() + + for i := 0; i < n; i++ { + payload, err := json.Marshal(wshrpc.CommandBlockInputData{BlockId: "b", InputData64: fmt.Sprintf("%03d", i)}) + if err != nil { + t.Fatalf("marshal: %v", err) + } + msg := RpcMessage{Command: wshrpc.Command_ControllerInput, ReqId: fmt.Sprintf("req-%d", i), Data: json.RawMessage(payload)} + b, err := json.Marshal(msg) + if err != nil { + t.Fatalf("marshal msg: %v", err) + } + inputCh <- baseds.RpcInputChType{MsgBytes: b} + } + + deadline := time.Now().Add(10 * time.Second) + for len(srv.results()) < n && time.Now().Before(deadline) { + time.Sleep(5 * time.Millisecond) + } + + got := srv.results() + if len(got) != n { + t.Fatalf("expected %d handled inputs, got %d", n, len(got)) + } + for i := range got { + if got[i] != i { + t.Fatalf("input order broken at %d: got %v", i, got) + } + } +} From ef3f82c3e0332ac8fe66328a5eabd079eacc951a Mon Sep 17 00:00:00 2001 From: Archie Cho Date: Sat, 21 Nov 2026 15:57:52 +0900 Subject: [PATCH 2/7] fix(term): keep IME terminator behind the composed syllable xterm's CompositionHelper defers the final composition text through setTimeout(0). On Windows the Microsoft Korean IME reports every key during composition as 229/Process, so the terminating space or punctuation arrives as a bare textarea input event, overtakes the syllable still sitting in that timer, and the late syllable re-read then carries the terminator a second time. A question mark typed after a Hangul syllable ended up one syllable early. While composing (or within 75ms of compositionend) hold back only short printable-ASCII terminators, at most 4 characters and for at most 30ms, re-emit them behind the committed text, and drop the duplicate when the late chunk already ends with the held data. While composing, only a carriage return is held. Ctrl/Cmd/Alt shortcuts still go to Wave; other keys are deferred to xterm so _finalizeComposition runs before Enter is acted on. Adapted from dandacompany/waveterm commits 5914ee5 and 3aabe93 (Apache-2.0), reviewed and verified on Windows 11 with the Microsoft Korean IME. --- frontend/app/view/term/term-model.ts | 3 + .../view/term/termwrap-composition.test.ts | 65 ++++++ frontend/app/view/term/termwrap.ts | 186 +++++++++++++++++- 3 files changed, 252 insertions(+), 2 deletions(-) create mode 100644 frontend/app/view/term/termwrap-composition.test.ts diff --git a/frontend/app/view/term/term-model.ts b/frontend/app/view/term/term-model.ts index a256929e7d..3af9f23950 100644 --- a/frontend/app/view/term/term-model.ts +++ b/frontend/app/view/term/term-model.ts @@ -697,6 +697,9 @@ export class TermViewModel implements ViewModel { } handleTerminalKeydown(event: KeyboardEvent): boolean { + if (event.isComposing || event.keyCode == 229) { + return true; + } const waveEvent = keyutil.adaptFromReactOrNativeKeyEvent(event); if (waveEvent.type != "keydown") { return true; diff --git a/frontend/app/view/term/termwrap-composition.test.ts b/frontend/app/view/term/termwrap-composition.test.ts new file mode 100644 index 0000000000..5fdb8a303a --- /dev/null +++ b/frontend/app/view/term/termwrap-composition.test.ts @@ -0,0 +1,65 @@ +// Copyright 2026, Command Line Inc. +// SPDX-License-Identifier: Apache-2.0 + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { TermWrap, isCompositionSuffixData } from "./termwrap"; + +function makeFakeTermWrap(): TermWrap & { sent: string[] } { + const tw = Object.create(TermWrap.prototype) as TermWrap & { sent: string[] }; + tw.loaded = true; + tw.compositionActive = false; + tw.compositionRecentlyEndedUntil = Date.now() + 75; + tw.pendingCompositionSuffix = null; + tw.sent = []; + tw.sendDataHandler = (d: string) => tw.sent.push(d); + tw.multiInputCallback = () => {}; + return tw; +} + +describe("isCompositionSuffixData", () => { + it("accepts short printable ASCII terminators only", () => { + expect(isCompositionSuffixData(" ")).toBe(true); + expect(isCompositionSuffixData("?")).toBe(true); + expect(isCompositionSuffixData(",")).toBe(true); + expect(isCompositionSuffixData("고")).toBe(false); + expect(isCompositionSuffixData("\r")).toBe(false); + expect(isCompositionSuffixData("toolong")).toBe(false); + }); +}); + +describe("TermWrap composition ordering", () => { + beforeEach(() => vi.useFakeTimers()); + afterEach(() => { + vi.runOnlyPendingTimers(); + vi.useRealTimers(); + }); + + it("puts a terminator behind the syllable it followed (Windows order)", () => { + const tw = makeFakeTermWrap(); + tw.handleTermData(" "); + expect(tw.sent).toEqual([]); + tw.handleTermData("고"); + expect(tw.sent.join("")).toBe("고 "); + }); + + it("drops the duplicated terminator in the late textarea re-read", () => { + const tw = makeFakeTermWrap(); + tw.handleTermData("?"); + tw.handleTermData("다?"); + expect(tw.sent.join("")).toBe("다?"); + }); + + it("does not hold ordinary keystrokes outside the commit window", () => { + const tw = makeFakeTermWrap(); + tw.compositionRecentlyEndedUntil = 0; + tw.handleTermData("abc"); + expect(tw.sent).toEqual(["abc"]); + }); + + it("flushes a held terminator when nothing follows", () => { + const tw = makeFakeTermWrap(); + tw.handleTermData(" "); + vi.advanceTimersByTime(40); + expect(tw.sent).toEqual([" "]); + }); +}); diff --git a/frontend/app/view/term/termwrap.ts b/frontend/app/view/term/termwrap.ts index 956d5fc9e2..c70af356c4 100644 --- a/frontend/app/view/term/termwrap.ts +++ b/frontend/app/view/term/termwrap.ts @@ -53,6 +53,7 @@ const TermCacheFileName = "cache:term:full"; const MinDataProcessedForCache = 100 * 1024; export const SupportsImageInput = true; const MaxRepaintTransactionMs = 2000; +const MaxCompositionSuffixLength = 4; // detect webgl support function detectWebGLSupport(): boolean { @@ -68,6 +69,21 @@ function detectWebGLSupport(): boolean { export const WebGLSupported = detectWebGLSupport(); let loggedWebGL = false; +// Short printable-ASCII chunk (space, comma, period, question mark, ...). Anything else is +// treated as committed composition text, which must never be buffered. +export function isCompositionSuffixData(data: string): boolean { + if (data.length === 0 || data.length > MaxCompositionSuffixLength) { + return false; + } + for (const ch of data) { + const codePoint = ch.codePointAt(0); + if (codePoint == null || codePoint < 0x20 || codePoint > 0x7e) { + return false; + } + } + return true; +} + type TermWrapOptions = { keydownHandler?: (e: KeyboardEvent) => boolean; useWebGl?: boolean; @@ -112,6 +128,13 @@ export class TermWrap { lastPasteData: string = ""; lastPasteTime: number = 0; + // IME composition ordering. On Windows the MS Korean IME reports every key as + // 229/Process, so the terminating space/punctuation arrives as a bare input event and + // can overtake the syllable xterm is still committing on a deferred timer. + compositionActive: boolean = false; + compositionRecentlyEndedUntil: number = 0; + pendingCompositionSuffix: { data: string; timeout: ReturnType | null } | null = null; + // dev only (for debugging) recentWrites: { idx: number; data: string; ts: number }[] = []; recentWritesCounter: number = 0; @@ -261,7 +284,16 @@ export class TermWrap { return true; }) ); + // Wave's handler runs before xterm's CompositionHelper, and returning false makes + // xterm skip _finalizeComposition. While composing (or just composed) every + // non-shortcut key must reach xterm so the composed text is flushed first. this.terminal.attachCustomKeyEventHandler((e: KeyboardEvent) => { + if (e.isComposing || e.keyCode == 229) { + return true; + } + if (this.shouldBypassWaveKeydownForComposition(e)) { + return true; + } if (!waveOptions.keydownHandler) { return true; } @@ -272,6 +304,7 @@ export class TermWrap { this.heldData = []; this.handleResize_debounced = debounce(50, this.handleResize.bind(this)); this.terminal.open(this.connectElem); + this.registerCompositionEventHandlers(); const dragoverHandler = (e: DragEvent) => { e.preventDefault(); @@ -440,6 +473,7 @@ export class TermWrap { } }); this.promptMarkers = []; + this.cancelPendingCompositionSuffix(); this.webglContextLossDisposable?.dispose(); this.webglContextLossDisposable = null; this.terminal.dispose(); @@ -453,15 +487,163 @@ export class TermWrap { this.mainFileSubject.release(); } - handleTermData(data: string) { - if (!this.loaded) { + registerCompositionEventHandlers() { + const textarea = this.terminal.textarea; + if (textarea == null) { return; } + const compositionStartHandler = () => { + this.compositionActive = true; + this.compositionRecentlyEndedUntil = 0; + this.flushPendingCompositionSuffix(); + }; + const compositionEndHandler = () => { + this.compositionActive = false; + this.compositionRecentlyEndedUntil = Date.now() + 75; + this.schedulePendingCompositionSuffixFlush(); + }; + textarea.addEventListener("compositionstart", compositionStartHandler); + textarea.addEventListener("compositionend", compositionEndHandler); + this.toDispose.push({ + dispose: () => { + textarea.removeEventListener("compositionstart", compositionStartHandler); + textarea.removeEventListener("compositionend", compositionEndHandler); + this.cancelPendingCompositionSuffix(); + }, + }); + } + + shouldBypassWaveKeydownForComposition(event: KeyboardEvent): boolean { + if (event.ctrlKey || event.metaKey || event.altKey) { + // real shortcuts still belong to Wave, even mid-composition + return false; + } + if (this.compositionActive) { + return true; + } + return Date.now() <= this.compositionRecentlyEndedUntil; + } + sendTermData(data: string) { this.sendDataHandler?.(data); this.multiInputCallback?.(data); } + flushPendingCompositionSuffix() { + if (this.pendingCompositionSuffix == null) { + return; + } + const pendingData = this.pendingCompositionSuffix.data; + if (this.pendingCompositionSuffix.timeout != null) { + clearTimeout(this.pendingCompositionSuffix.timeout); + } + this.pendingCompositionSuffix = null; + if (!this.loaded) { + return; + } + this.sendTermData(pendingData); + } + + cancelPendingCompositionSuffix() { + if (this.pendingCompositionSuffix == null) { + return; + } + if (this.pendingCompositionSuffix.timeout != null) { + clearTimeout(this.pendingCompositionSuffix.timeout); + } + this.pendingCompositionSuffix = null; + } + + schedulePendingCompositionSuffixFlush() { + if (this.pendingCompositionSuffix == null) { + return; + } + if (this.pendingCompositionSuffix.timeout != null) { + clearTimeout(this.pendingCompositionSuffix.timeout); + this.pendingCompositionSuffix.timeout = null; + } + if (this.compositionActive) { + return; + } + this.pendingCompositionSuffix.timeout = setTimeout(() => { + this.flushPendingCompositionSuffix(); + }, 30); + } + + isLikelyCompositionText(data: string): boolean { + if (data.length === 0) { + return false; + } + let hasNonAscii = false; + for (const ch of data) { + const codePoint = ch.codePointAt(0); + if (codePoint == null || codePoint <= 0x1f || codePoint === 0x7f) { + return false; + } + if (codePoint > 0x7f) { + hasNonAscii = true; + } + } + return hasNonAscii; + } + + shouldDeferCompositionData(data: string): boolean { + if (this.compositionActive) { + return data === "\r"; + } + if (Date.now() > this.compositionRecentlyEndedUntil) { + return false; + } + return data === "\r" || isCompositionSuffixData(data); + } + + handleTermData(data: string) { + if (!this.loaded) { + return; + } + + if (this.pendingCompositionSuffix != null) { + if (this.isLikelyCompositionText(data)) { + const pendingData = this.pendingCompositionSuffix.data; + if (this.pendingCompositionSuffix.timeout != null) { + clearTimeout(this.pendingCompositionSuffix.timeout); + } + this.pendingCompositionSuffix = null; + this.sendTermData(data); + // Windows re-reads the terminator from the textarea, so the late chunk may + // already contain it. Sending it again would duplicate the character. + if (!data.endsWith(pendingData)) { + this.sendTermData(pendingData); + } + return; + } + if ( + this.shouldDeferCompositionData(data) && + this.pendingCompositionSuffix.data.length + data.length <= MaxCompositionSuffixLength + ) { + if (this.pendingCompositionSuffix.timeout != null) { + clearTimeout(this.pendingCompositionSuffix.timeout); + this.pendingCompositionSuffix.timeout = null; + } + this.pendingCompositionSuffix.data += data; + this.schedulePendingCompositionSuffixFlush(); + return; + } + this.flushPendingCompositionSuffix(); + } + + if (this.shouldDeferCompositionData(data)) { + this.pendingCompositionSuffix = { + data, + timeout: null, + }; + this.schedulePendingCompositionSuffixFlush(); + return; + } + + this.sendTermData(data); + } + addFocusListener(focusFn: () => void) { this.terminal.textarea.addEventListener("focus", focusFn); } From 6d67629f82868664f299e0d979d02bb8744a0ce7 Mon Sep 17 00:00:00 2001 From: Archie Cho Date: Sat, 21 Nov 2026 18:09:20 +0900 Subject: [PATCH 3/7] fix(wshutil): keep ordered input per terminal, not per connection Review follow-up. A single ordered worker serialized every terminal's input, so a terminal whose PTY stops consuming could delay input for unrelated terminals, and once its queue filled it blocked the RPC read loop, which then could not process responses, timeout notifications or recovery commands such as destroying the stuck block. Queue per block/job instead: enqueue appends to that key's FIFO and starts a draining goroutine, so the read loop never waits on a handler and a stalled terminal only holds up its own queue. Panic handlers are now deferred closures so recover() runs at panic time. TestOrderedInputIsPerTerminal blocks one terminal inside its handler and checks that a second terminal and a non-input command still complete. --- pkg/wshutil/wshrpc.go | 82 ++++++++++++++++---- pkg/wshutil/wshrpc_ordering_test.go | 113 +++++++++++++++++++++++----- 2 files changed, 161 insertions(+), 34 deletions(-) diff --git a/pkg/wshutil/wshrpc.go b/pkg/wshutil/wshrpc.go index 426ed69891..5ba399f354 100644 --- a/pkg/wshutil/wshrpc.go +++ b/pkg/wshutil/wshrpc.go @@ -29,7 +29,6 @@ const DefaultTimeoutMs = 5000 const RespChSize = 32 const DefaultMessageChSize = 32 const CtxDoneChSize = 10 -const OrderedChSize = 1024 var blockingExpMap = ds.MakeExpMap[bool]() @@ -59,7 +58,8 @@ type WshRpc struct { EventListener *EventListener ResponseHandlerMap map[string]*RpcResponseHandler // reqId => handler StreamBroker *streamclient.Broker - OrderedCh chan orderedRpcRequest // input commands, handled in arrival order + OrderedLock *sync.Mutex + OrderedQueue map[string]*orderedInputQueue // per-terminal FIFO for input commands Debug bool DebugName string ServerDone bool @@ -70,6 +70,11 @@ type orderedRpcRequest struct { ingressLinkId baseds.LinkId } +type orderedInputQueue struct { + items []orderedRpcRequest + running bool +} + type wshRpcContextKey struct{} type wshRpcRespHandlerContextKey struct{} @@ -238,11 +243,11 @@ func MakeWshRpcWithChannels(inputCh chan baseds.RpcInputChType, outputCh chan [] EventListener: MakeEventListener(), ServerImpl: serverImpl, ResponseHandlerMap: make(map[string]*RpcResponseHandler), - OrderedCh: make(chan orderedRpcRequest, OrderedChSize), + OrderedLock: &sync.Mutex{}, + OrderedQueue: make(map[string]*orderedInputQueue), } rtn.RpcContext.Store(&rpcCtx) rtn.StreamBroker = streamclient.NewBroker(AdaptWshRpc(rtn)) - go rtn.runOrderedRequests() go rtn.runServer() return rtn } @@ -388,17 +393,66 @@ func (w *WshRpc) handleRequestInternal(req *RpcMessage, ingressLinkId baseds.Lin } // Commands that carry terminal keystrokes. They must be processed in the order the -// read loop received them; everything else may run concurrently. +// read loop received them, in arrival order per terminal; everything else may run +// concurrently. func isOrderedInputCommand(cmd string) bool { return cmd == wshrpc.Command_ControllerInput || cmd == "jobinput" } -// Single worker: input commands are handled one at a time, in arrival order. -func (w *WshRpc) runOrderedRequests() { - defer panichandler.PanicHandler("wshrpc.runOrderedRequests", recover()) - for req := range w.OrderedCh { +// Terminal a request belongs to. Order only has to hold within one terminal, so +// queues are keyed by block (controllerinput) or job (jobinput). +func orderedInputKey(msg *RpcMessage) string { + data, ok := msg.Data.(map[string]any) + if !ok { + return "input:" + msg.Command + } + if blockId, _ := data["blockid"].(string); blockId != "" { + return "block:" + blockId + } + if jobId, _ := data["jobid"].(string); jobId != "" { + return "job:" + jobId + } + return "input:" + msg.Command +} + +// Enqueues without ever blocking the read loop. A terminal whose PTY stops reading +// only holds up its own queue. +func (w *WshRpc) enqueueOrderedInput(key string, msg RpcMessage, ingressLinkId baseds.LinkId) { + w.OrderedLock.Lock() + q := w.OrderedQueue[key] + if q == nil { + q = &orderedInputQueue{} + w.OrderedQueue[key] = q + } + q.items = append(q.items, orderedRpcRequest{msg: msg, ingressLinkId: ingressLinkId}) + startWorker := !q.running + q.running = true + w.OrderedLock.Unlock() + if startWorker { + go w.runOrderedInputQueue(key) + } +} + +// Drains one terminal's queue in FIFO order. +func (w *WshRpc) runOrderedInputQueue(key string) { + for { + w.OrderedLock.Lock() + q := w.OrderedQueue[key] + if q == nil || len(q.items) == 0 { + if q != nil { + delete(w.OrderedQueue, key) + } + w.OrderedLock.Unlock() + return + } + req := q.items[0] + q.items = q.items[1:] + w.OrderedLock.Unlock() + func() { - defer panichandler.PanicHandler("wshrpc.handleOrderedRequest", recover()) + defer func() { + panichandler.PanicHandler("wshrpc.handleOrderedInput", recover()) + }() w.handleRequest(&req.msg, req.ingressLinkId) }() } @@ -407,7 +461,6 @@ func (w *WshRpc) runOrderedRequests() { func (w *WshRpc) runServer() { defer func() { panichandler.PanicHandler("wshrpc.runServer", recover()) - close(w.OrderedCh) close(w.OutputCh) w.setServerDone() }() @@ -458,9 +511,10 @@ outer: } if isOrderedInputCommand(msg.Command) { // Terminal input must reach the PTY in arrival order. Handling it in a - // goroutine lets a later packet overtake an earlier one, which shows up as - // reordered Hangul/CJK input at the shell. - w.OrderedCh <- orderedRpcRequest{msg: msg, ingressLinkId: inputVal.IngressLinkId} + // plain goroutine lets a later packet overtake an earlier one, which shows + // up as reordered Hangul/CJK input at the shell. Enqueueing here is + // non-blocking so a stalled terminal cannot stop this loop. + w.enqueueOrderedInput(orderedInputKey(&msg), msg, inputVal.IngressLinkId) continue } diff --git a/pkg/wshutil/wshrpc_ordering_test.go b/pkg/wshutil/wshrpc_ordering_test.go index 5c8fb2ca64..10737810ee 100644 --- a/pkg/wshutil/wshrpc_ordering_test.go +++ b/pkg/wshutil/wshrpc_ordering_test.go @@ -17,19 +17,34 @@ import ( ) type orderTestServer struct { - mu sync.Mutex - got []int + mu sync.Mutex + got []int + slowGate chan struct{} // closed to release inputs for block "slow" + fast chan int + messages chan string } func (s *orderTestServer) WshServerImpl() {} func (s *orderTestServer) ControllerInputCommand(ctx context.Context, data wshrpc.CommandBlockInputData) error { - // Earlier messages take longer, so concurrent handling records them out of order. + if data.BlockId == "slow" { + <-s.slowGate + return nil + } + // Earlier messages take longer, so unordered handling would record them reversed. idx, _ := strconv.Atoi(data.InputData64) time.Sleep(time.Duration(6-(idx%6)) * time.Millisecond) s.mu.Lock() s.got = append(s.got, idx) s.mu.Unlock() + if s.fast != nil { + s.fast <- idx + } + return nil +} + +func (s *orderTestServer) MessageCommand(ctx context.Context, data wshrpc.CommandMessageData) error { + s.messages <- data.Message return nil } @@ -39,29 +54,49 @@ func (s *orderTestServer) results() []int { return append([]int(nil), s.got...) } -func TestControllerInputOrdering(t *testing.T) { - const n = 40 - inputCh := make(chan baseds.RpcInputChType, n*2) - outputCh := make(chan []byte, n*2) - srv := &orderTestServer{} - MakeWshRpcWithChannels(inputCh, outputCh, wshrpc.RpcContext{Conn: "test"}, srv, "ordertest") - +func makeTestRpc(t *testing.T, srv ServerImpl) (*WshRpc, chan baseds.RpcInputChType) { + t.Helper() + inputCh := make(chan baseds.RpcInputChType, 128) + outputCh := make(chan []byte, 128) + w := MakeWshRpcWithChannels(inputCh, outputCh, wshrpc.RpcContext{Conn: "test"}, srv, "ordertest") go func() { for range outputCh { } }() + return w, inputCh +} + +func sendInput(t *testing.T, inputCh chan baseds.RpcInputChType, blockId string, idx int) { + t.Helper() + payload, err := json.Marshal(wshrpc.CommandBlockInputData{BlockId: blockId, InputData64: fmt.Sprintf("%03d", idx)}) + if err != nil { + t.Fatalf("marshal: %v", err) + } + msg := RpcMessage{Command: wshrpc.Command_ControllerInput, ReqId: fmt.Sprintf("req-%s-%d", blockId, idx), Data: json.RawMessage(payload)} + b, err := json.Marshal(msg) + if err != nil { + t.Fatalf("marshal msg: %v", err) + } + inputCh <- baseds.RpcInputChType{MsgBytes: b} +} + +func sendMessage(t *testing.T, inputCh chan baseds.RpcInputChType, text string) { + t.Helper() + msg := RpcMessage{Command: wshrpc.Command_Message, Data: map[string]any{"message": text}} + b, err := json.Marshal(msg) + if err != nil { + t.Fatalf("marshal msg: %v", err) + } + inputCh <- baseds.RpcInputChType{MsgBytes: b} +} + +func TestControllerInputOrdering(t *testing.T) { + const n = 40 + srv := &orderTestServer{} + _, inputCh := makeTestRpc(t, srv) for i := 0; i < n; i++ { - payload, err := json.Marshal(wshrpc.CommandBlockInputData{BlockId: "b", InputData64: fmt.Sprintf("%03d", i)}) - if err != nil { - t.Fatalf("marshal: %v", err) - } - msg := RpcMessage{Command: wshrpc.Command_ControllerInput, ReqId: fmt.Sprintf("req-%d", i), Data: json.RawMessage(payload)} - b, err := json.Marshal(msg) - if err != nil { - t.Fatalf("marshal msg: %v", err) - } - inputCh <- baseds.RpcInputChType{MsgBytes: b} + sendInput(t, inputCh, "b", i) } deadline := time.Now().Add(10 * time.Second) @@ -79,3 +114,41 @@ func TestControllerInputOrdering(t *testing.T) { } } } + +// A terminal that stops consuming input must not stall other terminals, and must not +// stall protocol demultiplexing in the read loop. +func TestOrderedInputIsPerTerminal(t *testing.T) { + srv := &orderTestServer{ + slowGate: make(chan struct{}), + fast: make(chan int, 8), + messages: make(chan string, 8), + } + _, inputCh := makeTestRpc(t, srv) + + sendInput(t, inputCh, "slow", 0) + sendInput(t, inputCh, "slow", 1) + + for i := 0; i < 4; i++ { + sendInput(t, inputCh, "fast", i) + } + sendMessage(t, inputCh, "ping") + + // "slow" is blocked inside its handler; "fast" and the message must still flow. + for i := 0; i < 4; i++ { + select { + case <-srv.fast: + case <-time.After(3 * time.Second): + t.Fatalf("fast terminal stalled behind slow terminal at %d", i) + } + } + select { + case msg := <-srv.messages: + if msg != "ping" { + t.Fatalf("unexpected message %q", msg) + } + case <-time.After(3 * time.Second): + t.Fatalf("read loop stalled while terminal input was blocked") + } + + close(srv.slowGate) +} From db3132c3c1afcdbe15f417394913aecb20a7a96f Mon Sep 17 00:00:00 2001 From: Archie Cho Date: Sat, 21 Nov 2026 18:09:20 +0900 Subject: [PATCH 4/7] fix(term): keep IME shortcuts, paste and multi-input intact Review follow-up for the composition ordering change: - Let Ctrl/Cmd/Alt shortcuts reach Wave during composition instead of deferring every key to xterm. Ctrl+Shift+V and friends keep working while a syllable is being composed. - Capture the multi-input recipients when a terminator is held, so a delayed Enter goes to the terminals that were selected at keystroke time rather than whatever selection exists at flush time. - Flush a held terminator before pasted text and never let paste content satisfy the duplicate-terminator check, so pasting text ending in a space cannot swallow a held space. --- frontend/app/view/term/term-model.ts | 2 +- .../view/term/termwrap-composition.test.ts | 21 ++++++++++++++ frontend/app/view/term/termwrap.ts | 28 +++++++++++++++---- 3 files changed, 44 insertions(+), 7 deletions(-) diff --git a/frontend/app/view/term/term-model.ts b/frontend/app/view/term/term-model.ts index 3af9f23950..187594c5eb 100644 --- a/frontend/app/view/term/term-model.ts +++ b/frontend/app/view/term/term-model.ts @@ -697,7 +697,7 @@ export class TermViewModel implements ViewModel { } handleTerminalKeydown(event: KeyboardEvent): boolean { - if (event.isComposing || event.keyCode == 229) { + if ((event.isComposing || event.keyCode == 229) && !event.ctrlKey && !event.metaKey && !event.altKey) { return true; } const waveEvent = keyutil.adaptFromReactOrNativeKeyEvent(event); diff --git a/frontend/app/view/term/termwrap-composition.test.ts b/frontend/app/view/term/termwrap-composition.test.ts index 5fdb8a303a..e2fd578522 100644 --- a/frontend/app/view/term/termwrap-composition.test.ts +++ b/frontend/app/view/term/termwrap-composition.test.ts @@ -62,4 +62,25 @@ describe("TermWrap composition ordering", () => { vi.advanceTimersByTime(40); expect(tw.sent).toEqual([" "]); }); + + it("flushes a held terminator before pasted text", () => { + const tw = makeFakeTermWrap(); + tw.handleTermData(" "); + tw.pasteActive = true; + tw.handleTermData("붙여넣기 "); + expect(tw.sent.join("")).toBe(" 붙여넣기 "); + }); + + it("sends a held terminator to the multi-input recipients captured at keystroke time", () => { + const tw = makeFakeTermWrap(); + const atKeystroke = vi.fn(); + const laterRetarget = vi.fn(); + tw.multiInputCallback = atKeystroke; + tw.handleTermData(" "); + tw.multiInputCallback = laterRetarget; + vi.advanceTimersByTime(40); + expect(tw.sent).toEqual([" "]); + expect(atKeystroke).toHaveBeenCalledWith(" "); + expect(laterRetarget).not.toHaveBeenCalled(); + }); }); diff --git a/frontend/app/view/term/termwrap.ts b/frontend/app/view/term/termwrap.ts index c70af356c4..5ce9f799b1 100644 --- a/frontend/app/view/term/termwrap.ts +++ b/frontend/app/view/term/termwrap.ts @@ -133,7 +133,11 @@ export class TermWrap { // can overtake the syllable xterm is still committing on a deferred timer. compositionActive: boolean = false; compositionRecentlyEndedUntil: number = 0; - pendingCompositionSuffix: { data: string; timeout: ReturnType | null } | null = null; + pendingCompositionSuffix: { + data: string; + timeout: ReturnType | null; + multiInput?: (data: string) => void; + } | null = null; // dev only (for debugging) recentWrites: { idx: number; data: string; ts: number }[] = []; @@ -288,7 +292,7 @@ export class TermWrap { // xterm skip _finalizeComposition. While composing (or just composed) every // non-shortcut key must reach xterm so the composed text is flushed first. this.terminal.attachCustomKeyEventHandler((e: KeyboardEvent) => { - if (e.isComposing || e.keyCode == 229) { + if ((e.isComposing || e.keyCode == 229) && !e.ctrlKey && !e.altKey && !e.metaKey) { return true; } if (this.shouldBypassWaveKeydownForComposition(e)) { @@ -524,9 +528,9 @@ export class TermWrap { return Date.now() <= this.compositionRecentlyEndedUntil; } - sendTermData(data: string) { + sendTermData(data: string, multiInput: (data: string) => void = this.multiInputCallback) { this.sendDataHandler?.(data); - this.multiInputCallback?.(data); + multiInput?.(data); } flushPendingCompositionSuffix() { @@ -534,6 +538,7 @@ export class TermWrap { return; } const pendingData = this.pendingCompositionSuffix.data; + const pendingMultiInput = this.pendingCompositionSuffix.multiInput; if (this.pendingCompositionSuffix.timeout != null) { clearTimeout(this.pendingCompositionSuffix.timeout); } @@ -541,7 +546,8 @@ export class TermWrap { if (!this.loaded) { return; } - this.sendTermData(pendingData); + // Use the recipients that were active when the key was typed. + this.sendTermData(pendingData, pendingMultiInput); } cancelPendingCompositionSuffix() { @@ -602,9 +608,18 @@ export class TermWrap { return; } + if (this.pasteActive) { + // Pasted text is not a composition chunk: flush the held terminator first and + // never let the paste satisfy the duplicate-terminator check. + this.flushPendingCompositionSuffix(); + this.sendTermData(data); + return; + } + if (this.pendingCompositionSuffix != null) { if (this.isLikelyCompositionText(data)) { const pendingData = this.pendingCompositionSuffix.data; + const pendingMultiInput = this.pendingCompositionSuffix.multiInput; if (this.pendingCompositionSuffix.timeout != null) { clearTimeout(this.pendingCompositionSuffix.timeout); } @@ -613,7 +628,7 @@ export class TermWrap { // Windows re-reads the terminator from the textarea, so the late chunk may // already contain it. Sending it again would duplicate the character. if (!data.endsWith(pendingData)) { - this.sendTermData(pendingData); + this.sendTermData(pendingData, pendingMultiInput); } return; } @@ -636,6 +651,7 @@ export class TermWrap { this.pendingCompositionSuffix = { data, timeout: null, + multiInput: this.multiInputCallback, }; this.schedulePendingCompositionSuffixFlush(); return; From 7d0af14dc9be8a0802d86380b476ff0365ec0275 Mon Sep 17 00:00:00 2001 From: Archie Cho Date: Sat, 21 Nov 2026 18:27:24 +0900 Subject: [PATCH 5/7] fix(jobcontroller): do not wait for a remote ack on terminal input SendInput used NoResponse: false, so every keystroke on a durable (SSH or WSL) session waited for the job's round trip before the next one could be handled. At 200ms that caps typing at roughly five events per second. Ordering is now preserved by the per-job queue on the receiving side, so the acknowledgement adds latency without adding safety. Errors from the remote side were already invisible to the user through this path; CheckJobConnected still reports a disconnected job. --- pkg/jobcontroller/jobcontroller.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pkg/jobcontroller/jobcontroller.go b/pkg/jobcontroller/jobcontroller.go index e41d77585c..465a598d97 100644 --- a/pkg/jobcontroller/jobcontroller.go +++ b/pkg/jobcontroller/jobcontroller.go @@ -1523,10 +1523,12 @@ func SendInput(ctx context.Context, data wshrpc.CommandJobInputData) error { return err } + // Input order is preserved by the per-job queue on the receiving side, so waiting for + // a remote acknowledgement would cap typing at the round-trip rate (5/s at 200ms). rpcOpts := &wshrpc.RpcOpts{ Route: wshutil.MakeJobRouteId(jobId), Timeout: 5000, - NoResponse: false, + NoResponse: true, } bareRpc := wshclient.GetBareRpcClient() From 5795c64bd2392512ef7d44b26c609a2b6d8e2384 Mon Sep 17 00:00:00 2001 From: Archie Cho Date: Sat, 21 Nov 2026 18:27:24 +0900 Subject: [PATCH 6/7] fix(term): bind held input to its multi-input target and paste dispatch Review follow-up: - Distinguish "multi-input was off when the key was pressed" from "no callback captured". A null is now carried through to the flush instead of falling back to the current callback, so enabling multi-input later cannot receive input typed before it was on. - Flush the pending suffix when the multi-input callback changes before another chunk arrives, instead of merging chunks that belong to different recipients. - Mark only the actual terminal.paste dispatch instead of the whole asynchronous clipboard read, so keystrokes arriving while the clipboard is being read keep the composition ordering path. --- .../view/term/termwrap-composition.test.ts | 44 ++++++++++++++---- frontend/app/view/term/termwrap.ts | 45 ++++++++++++------- 2 files changed, 65 insertions(+), 24 deletions(-) diff --git a/frontend/app/view/term/termwrap-composition.test.ts b/frontend/app/view/term/termwrap-composition.test.ts index e2fd578522..2fa64f2292 100644 --- a/frontend/app/view/term/termwrap-composition.test.ts +++ b/frontend/app/view/term/termwrap-composition.test.ts @@ -1,4 +1,4 @@ -// Copyright 2026, Command Line Inc. +// Copyright 2026, Command Line Inc. // SPDX-License-Identifier: Apache-2.0 import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; @@ -21,7 +21,7 @@ describe("isCompositionSuffixData", () => { expect(isCompositionSuffixData(" ")).toBe(true); expect(isCompositionSuffixData("?")).toBe(true); expect(isCompositionSuffixData(",")).toBe(true); - expect(isCompositionSuffixData("고")).toBe(false); + expect(isCompositionSuffixData("\uACE0")).toBe(false); expect(isCompositionSuffixData("\r")).toBe(false); expect(isCompositionSuffixData("toolong")).toBe(false); }); @@ -38,15 +38,15 @@ describe("TermWrap composition ordering", () => { const tw = makeFakeTermWrap(); tw.handleTermData(" "); expect(tw.sent).toEqual([]); - tw.handleTermData("고"); - expect(tw.sent.join("")).toBe("고 "); + tw.handleTermData("\uACE0"); + expect(tw.sent.join("")).toBe("\uACE0 "); }); it("drops the duplicated terminator in the late textarea re-read", () => { const tw = makeFakeTermWrap(); tw.handleTermData("?"); - tw.handleTermData("다?"); - expect(tw.sent.join("")).toBe("다?"); + tw.handleTermData("\uB2E4?"); + expect(tw.sent.join("")).toBe("\uB2E4?"); }); it("does not hold ordinary keystrokes outside the commit window", () => { @@ -66,9 +66,9 @@ describe("TermWrap composition ordering", () => { it("flushes a held terminator before pasted text", () => { const tw = makeFakeTermWrap(); tw.handleTermData(" "); - tw.pasteActive = true; - tw.handleTermData("붙여넣기 "); - expect(tw.sent.join("")).toBe(" 붙여넣기 "); + tw.pasteDispatching = true; + tw.handleTermData("\uBD99\uC5EC\uB123\uAE30 "); + expect(tw.sent.join("")).toBe(" \uBD99\uC5EC\uB123\uAE30 "); }); it("sends a held terminator to the multi-input recipients captured at keystroke time", () => { @@ -83,4 +83,30 @@ describe("TermWrap composition ordering", () => { expect(atKeystroke).toHaveBeenCalledWith(" "); expect(laterRetarget).not.toHaveBeenCalled(); }); + + it("keeps a held terminator away from multi-input enabled after the keystroke", () => { + const tw = makeFakeTermWrap(); + const laterEnabled = vi.fn(); + (tw as any).multiInputCallback = undefined; + tw.handleTermData(" "); + tw.multiInputCallback = laterEnabled; + vi.advanceTimersByTime(40); + expect(tw.sent).toEqual([" "]); + expect(laterEnabled).not.toHaveBeenCalled(); + }); + + it("does not merge suffix chunks produced for different multi-input recipients", () => { + const tw = makeFakeTermWrap(); + const first = vi.fn(); + const second = vi.fn(); + tw.multiInputCallback = first; + tw.handleTermData(" "); + tw.multiInputCallback = second; + tw.handleTermData("?"); + expect(tw.sent).toEqual([" "]); + vi.advanceTimersByTime(40); + expect(tw.sent).toEqual([" ", "?"]); + expect(first).toHaveBeenCalledWith(" "); + expect(second).toHaveBeenCalledWith("?"); + }); }); diff --git a/frontend/app/view/term/termwrap.ts b/frontend/app/view/term/termwrap.ts index 5ce9f799b1..ad3f99d506 100644 --- a/frontend/app/view/term/termwrap.ts +++ b/frontend/app/view/term/termwrap.ts @@ -113,7 +113,7 @@ export class TermWrap { webglAddon: WebglAddon | null = null; webglContextLossDisposable: TermTypes.IDisposable | null = null; webglEnabledAtom: jotai.PrimitiveAtom; - pasteActive: boolean = false; + pasteDispatching: boolean = false; lastUpdated: number; promptMarkers: TermTypes.IMarker[] = []; shellIntegrationStatusAtom: jotai.PrimitiveAtom; @@ -136,7 +136,7 @@ export class TermWrap { pendingCompositionSuffix: { data: string; timeout: ReturnType | null; - multiInput?: (data: string) => void; + multiInput: ((data: string) => void) | null; } | null = null; // dev only (for debugging) @@ -528,9 +528,14 @@ export class TermWrap { return Date.now() <= this.compositionRecentlyEndedUntil; } - sendTermData(data: string, multiInput: (data: string) => void = this.multiInputCallback) { + sendTermData(data: string, multiInput?: ((data: string) => void) | null) { this.sendDataHandler?.(data); - multiInput?.(data); + if (multiInput === undefined) { + this.multiInputCallback?.(data); + } else { + // null means multi-input was off when this data was produced + multiInput?.(data); + } } flushPendingCompositionSuffix() { @@ -608,7 +613,7 @@ export class TermWrap { return; } - if (this.pasteActive) { + if (this.pasteDispatching) { // Pasted text is not a composition chunk: flush the held terminator first and // never let the paste satisfy the duplicate-terminator check. this.flushPendingCompositionSuffix(); @@ -619,7 +624,7 @@ export class TermWrap { if (this.pendingCompositionSuffix != null) { if (this.isLikelyCompositionText(data)) { const pendingData = this.pendingCompositionSuffix.data; - const pendingMultiInput = this.pendingCompositionSuffix.multiInput; + const pendingMultiInput = this.pendingCompositionSuffix.multiInput ?? null; if (this.pendingCompositionSuffix.timeout != null) { clearTimeout(this.pendingCompositionSuffix.timeout); } @@ -632,9 +637,11 @@ export class TermWrap { } return; } + const currentMultiInput = this.multiInputCallback ?? null; if ( this.shouldDeferCompositionData(data) && - this.pendingCompositionSuffix.data.length + data.length <= MaxCompositionSuffixLength + this.pendingCompositionSuffix.data.length + data.length <= MaxCompositionSuffixLength && + this.pendingCompositionSuffix.multiInput === currentMultiInput ) { if (this.pendingCompositionSuffix.timeout != null) { clearTimeout(this.pendingCompositionSuffix.timeout); @@ -651,7 +658,7 @@ export class TermWrap { this.pendingCompositionSuffix = { data, timeout: null, - multiInput: this.multiInputCallback, + multiInput: this.multiInputCallback ?? null, }; this.schedulePendingCompositionSuffixFlush(); return; @@ -797,8 +804,20 @@ export class TermWrap { }, 5000); } + // Only marks the actual paste dispatch: clipboard reading is asynchronous and must + // not swallow normal keystrokes that arrive while it is in flight. + dispatchPaste(text: string) { + this.pasteDispatching = true; + try { + this.terminal.paste(text); + } finally { + setTimeout(() => { + this.pasteDispatching = false; + }, 0); + } + } + async pasteHandler(e?: ClipboardEvent): Promise { - this.pasteActive = true; e?.preventDefault(); e?.stopPropagation(); @@ -811,19 +830,15 @@ export class TermWrap { await new Promise((r) => setTimeout(r, 150)); } const tempPath = await createTempFileFromBlob(data.image); - this.terminal.paste(tempPath + " "); + this.dispatchPaste(tempPath + " "); firstImage = false; } if (data.text) { - this.terminal.paste(data.text); + this.dispatchPaste(data.text); } } } catch (err) { console.error("Paste error:", err); - } finally { - setTimeout(() => { - this.pasteActive = false; - }, 30); } } From 6eb76d7a35fff219790b3565338d7ae1829e37df Mon Sep 17 00:00:00 2001 From: Archie Cho Date: Sat, 21 Nov 2026 18:51:21 +0900 Subject: [PATCH 7/7] fix(jobmanager): wait for input queue space instead of dropping keys With NoResponse the sender no longer waits for the receiver, so input can arrive faster than the job queue drains. QueueItem returned a plain error when full and JobInputCommand ignored it, so keystrokes were lost with no error on either side. Return a sentinel (ErrReorderQueueFull) and retry in JobInputCommand until the queue has room or the RPC context expires. The retry runs on the per-job input worker, so a stalled terminal cannot block other terminals, and nothing waits while holding the queue lock. If the context expires, the drop is logged instead of disappearing. --- pkg/jobmanager/mainserverconn.go | 23 +++++++++++++++++++++-- pkg/utilds/quickreorderqueue.go | 7 ++++++- pkg/utilds/quickreorderqueue_test.go | 14 ++++++++++++++ 3 files changed, 41 insertions(+), 3 deletions(-) diff --git a/pkg/jobmanager/mainserverconn.go b/pkg/jobmanager/mainserverconn.go index 33bb10cdfb..e9ddc3998e 100644 --- a/pkg/jobmanager/mainserverconn.go +++ b/pkg/jobmanager/mainserverconn.go @@ -5,13 +5,16 @@ package jobmanager import ( "context" + "errors" "fmt" "log" "net" "sync" "sync/atomic" + "time" "github.com/wavetermdev/waveterm/pkg/baseds" + "github.com/wavetermdev/waveterm/pkg/utilds" "github.com/wavetermdev/waveterm/pkg/wavejwt" "github.com/wavetermdev/waveterm/pkg/wshrpc" "github.com/wavetermdev/waveterm/pkg/wshrpc/wshclient" @@ -129,6 +132,22 @@ func (msc *MainServerConn) JobInputCommand(ctx context.Context, data wshrpc.Comm return fmt.Errorf("job not started") } - WshCmdJobManager.InputQueue.QueueItem(data.InputSessionId, data.SeqNum, data) - return nil + // The sender does not wait for an acknowledgement, so input can arrive faster than the + // job drains it. Wait for room instead of dropping keystrokes; the caller handles one + // job's input on its own worker, so this blocks only this terminal. + for { + err := WshCmdJobManager.InputQueue.QueueItem(data.InputSessionId, data.SeqNum, data) + if err == nil { + return nil + } + if !errors.Is(err, utilds.ErrReorderQueueFull) { + return fmt.Errorf("failed to queue input: %w", err) + } + select { + case <-ctx.Done(): + log.Printf("[job] input queue full for %s, dropping input: %v", data.JobId, err) + return fmt.Errorf("failed to queue input: %w", err) + case <-time.After(5 * time.Millisecond): + } + } } diff --git a/pkg/utilds/quickreorderqueue.go b/pkg/utilds/quickreorderqueue.go index 6b95823c08..b7c8d92526 100644 --- a/pkg/utilds/quickreorderqueue.go +++ b/pkg/utilds/quickreorderqueue.go @@ -4,12 +4,17 @@ package utilds import ( + "errors" "fmt" "sort" "sync" "time" ) +// ErrReorderQueueFull is returned when the queue cannot accept more items. Callers that +// must not lose data can wait and retry instead of dropping the item. +var ErrReorderQueueFull = errors.New("reorder queue is full") + // the quick reorder queue implements reordering of items with a certain timerame (the timeout passed) // if an item is queued in order, it gets processed immediately // if it comes in out of order it gets buffered for up to the timeout while we wait for the correct next seq to come in @@ -122,7 +127,7 @@ func (q *QuickReorderQueue[T]) QueueItem(sessionId string, seqNum int, data T) e } if len(q.buffer)+len(q.outCh) >= cap(q.outCh) { - return fmt.Errorf("queue is full, cannot accept new items, cap: %d", cap(q.outCh)) + return fmt.Errorf("%w, cap: %d", ErrReorderQueueFull, cap(q.outCh)) } q.ensureSessionTs_withlock(sessionId) diff --git a/pkg/utilds/quickreorderqueue_test.go b/pkg/utilds/quickreorderqueue_test.go index 1fb5131854..2fc1137574 100644 --- a/pkg/utilds/quickreorderqueue_test.go +++ b/pkg/utilds/quickreorderqueue_test.go @@ -4,6 +4,7 @@ package utilds import ( + "errors" "testing" "time" ) @@ -441,3 +442,16 @@ func TestQuickReorderQueue_MultiSessionComplexReordering(t *testing.T) { } } } + +func TestQuickReorderQueue_FullReturnsSentinel(t *testing.T) { + q := MakeQuickReorderQueue[string](1, time.Second) + defer q.Close() + + if err := q.QueueItem("session1", 1, "item1"); err != nil { + t.Fatalf("first queue item failed: %v", err) + } + err := q.QueueItem("session1", 2, "item2") + if !errors.Is(err, ErrReorderQueueFull) { + t.Fatalf("expected ErrReorderQueueFull, got %v", err) + } +}