diff --git a/frontend/app/view/term/term-model.ts b/frontend/app/view/term/term-model.ts index a256929e7d..187594c5eb 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) && !event.ctrlKey && !event.metaKey && !event.altKey) { + 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..2fa64f2292 --- /dev/null +++ b/frontend/app/view/term/termwrap-composition.test.ts @@ -0,0 +1,112 @@ +// 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("\uACE0")).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("\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("\uB2E4?"); + expect(tw.sent.join("")).toBe("\uB2E4?"); + }); + + 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([" "]); + }); + + it("flushes a held terminator before pasted text", () => { + const tw = makeFakeTermWrap(); + tw.handleTermData(" "); + 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", () => { + 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(); + }); + + 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 956d5fc9e2..ad3f99d506 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; @@ -97,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; @@ -112,6 +128,17 @@ 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; + multiInput: ((data: string) => void) | null; + } | null = null; + // dev only (for debugging) recentWrites: { idx: number; data: string; ts: number }[] = []; recentWritesCounter: number = 0; @@ -261,7 +288,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) && !e.ctrlKey && !e.altKey && !e.metaKey) { + return true; + } + if (this.shouldBypassWaveKeydownForComposition(e)) { + return true; + } if (!waveOptions.keydownHandler) { return true; } @@ -272,6 +308,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 +477,7 @@ export class TermWrap { } }); this.promptMarkers = []; + this.cancelPendingCompositionSuffix(); this.webglContextLossDisposable?.dispose(); this.webglContextLossDisposable = null; this.terminal.dispose(); @@ -453,13 +491,180 @@ export class TermWrap { this.mainFileSubject.release(); } + 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, multiInput?: ((data: string) => void) | null) { + this.sendDataHandler?.(data); + if (multiInput === undefined) { + this.multiInputCallback?.(data); + } else { + // null means multi-input was off when this data was produced + multiInput?.(data); + } + } + + flushPendingCompositionSuffix() { + if (this.pendingCompositionSuffix == null) { + return; + } + const pendingData = this.pendingCompositionSuffix.data; + const pendingMultiInput = this.pendingCompositionSuffix.multiInput; + if (this.pendingCompositionSuffix.timeout != null) { + clearTimeout(this.pendingCompositionSuffix.timeout); + } + this.pendingCompositionSuffix = null; + if (!this.loaded) { + return; + } + // Use the recipients that were active when the key was typed. + this.sendTermData(pendingData, pendingMultiInput); + } + + 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; } - this.sendDataHandler?.(data); - this.multiInputCallback?.(data); + 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(); + this.sendTermData(data); + return; + } + + if (this.pendingCompositionSuffix != null) { + if (this.isLikelyCompositionText(data)) { + const pendingData = this.pendingCompositionSuffix.data; + const pendingMultiInput = this.pendingCompositionSuffix.multiInput ?? null; + 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, pendingMultiInput); + } + return; + } + const currentMultiInput = this.multiInputCallback ?? null; + if ( + this.shouldDeferCompositionData(data) && + this.pendingCompositionSuffix.data.length + data.length <= MaxCompositionSuffixLength && + this.pendingCompositionSuffix.multiInput === currentMultiInput + ) { + 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, + multiInput: this.multiInputCallback ?? null, + }; + this.schedulePendingCompositionSuffixFlush(); + return; + } + + this.sendTermData(data); } addFocusListener(focusFn: () => void) { @@ -599,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(); @@ -613,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); } } 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() 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) + } +} diff --git a/pkg/wshutil/wshrpc.go b/pkg/wshutil/wshrpc.go index 8a29e204bd..5ba399f354 100644 --- a/pkg/wshutil/wshrpc.go +++ b/pkg/wshutil/wshrpc.go @@ -58,11 +58,23 @@ type WshRpc struct { EventListener *EventListener ResponseHandlerMap map[string]*RpcResponseHandler // reqId => handler StreamBroker *streamclient.Broker + OrderedLock *sync.Mutex + OrderedQueue map[string]*orderedInputQueue // per-terminal FIFO for input commands Debug bool DebugName string ServerDone bool } +type orderedRpcRequest struct { + msg RpcMessage + ingressLinkId baseds.LinkId +} + +type orderedInputQueue struct { + items []orderedRpcRequest + running bool +} + type wshRpcContextKey struct{} type wshRpcRespHandlerContextKey struct{} @@ -231,6 +243,8 @@ func MakeWshRpcWithChannels(inputCh chan baseds.RpcInputChType, outputCh chan [] EventListener: MakeEventListener(), ServerImpl: serverImpl, ResponseHandlerMap: make(map[string]*RpcResponseHandler), + OrderedLock: &sync.Mutex{}, + OrderedQueue: make(map[string]*orderedInputQueue), } rtn.RpcContext.Store(&rpcCtx) rtn.StreamBroker = streamclient.NewBroker(AdaptWshRpc(rtn)) @@ -378,6 +392,72 @@ 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, in arrival order per terminal; everything else may run +// concurrently. +func isOrderedInputCommand(cmd string) bool { + return cmd == wshrpc.Command_ControllerInput || cmd == "jobinput" +} + +// 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 func() { + panichandler.PanicHandler("wshrpc.handleOrderedInput", recover()) + }() + w.handleRequest(&req.msg, req.ingressLinkId) + }() + } +} + func (w *WshRpc) runServer() { defer func() { panichandler.PanicHandler("wshrpc.runServer", recover()) @@ -429,6 +509,14 @@ outer: w.handleStreamAck(&msg) continue } + if isOrderedInputCommand(msg.Command) { + // Terminal input must reach the PTY in arrival order. Handling it in a + // 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 + } 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..10737810ee --- /dev/null +++ b/pkg/wshutil/wshrpc_ordering_test.go @@ -0,0 +1,154 @@ +// 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 + 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 { + 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 +} + +func (s *orderTestServer) results() []int { + s.mu.Lock() + defer s.mu.Unlock() + return append([]int(nil), s.got...) +} + +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++ { + sendInput(t, inputCh, "b", i) + } + + 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) + } + } +} + +// 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) +}