mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-21 23:50:45 +00:00
* fix(terminal): restore hibernate scrollback before viewport Hibernate wake was writing the viewport first and appending older scrollback on idle. Under a finite xterm scrollback cap that trims the just-restored newest rows, so switching back to a hibernated tab could permanently drop the end of large output (#2762). Replay scrollback → viewport → pending on the wake path while keeping chunked writes. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> * fix(terminal): prefer full hibernate snapshot on wake SerializeAddon range slices omit the seam newline, so concatenating scrollback+viewport can merge boundary lines. Prefer the coherent full snapshot for wake history, with a scrollback-then-viewport fallback, and cover the seam with a real SerializeAddon regression. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> * style(terminal): keep hibernate wake comments ASCII-only Address Codex P3: replace em dash / arrow punctuation in touched comments per AGENTS.md ASCII convention. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> * fix(terminal): drain hibernate pending via take-and-clear on wake Full-history replay widens the window where capped pending output can grow without increasing length. Length-based slice drains then skip new bytes. Capture and clear pending before replay, then drain pure deltas. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> * fix(terminal): final pending drain before hibernate listener teardown After the bounded take-and-clear loop, take any remaining pending once more before stopHibernateListeners so wake-time output is not dropped. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> * fix(terminal): stop hibernate listeners before final pending drain Awaiting the final pending write while listeners are still live can lose already-acked bytes that arrive during that write. Stop listeners first, then take-and-replay any remainder. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> * fix(terminal): keep hibernate exit listener through final pending replay Stop only the data listener before the final pending drain so pending stops growing, but leave the exit listener registered until after the reattach decision so an exit during that await is not missed. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> * fix(terminal): pause backend flow across hibernate history replay Full-history wake no longer races the 512 KiB pending cap or the 64 KiB preload backlog. Pause-and-wait drains into pending, stop the data listener, take pending once, replay, reattach, then resume. Removes the multi-pass drain that still dropped ACKed bytes under sustained output. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> * fix(terminal): harden hibernate wake against drain failure and exit tails Check setSessionFlowPausedAndWait success. On drain failure keep the hibernate data listener with the pending cap disabled for the wake window. After history replay, take pending once more so exit "[session closed]" tails and uncapped live arrivals are not discarded. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> * fix(terminal): pause reconnect hibernate wakes and recheck exit after late drain Always pause when a backend session exists (including sessionConnected=false reconnect wakes). Drain late pending plus an exit-tail take before deciding reattach. Resume flow only after reattach, or on wake failure; successful reconnect wakes stay paused until cleanupSession. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> * fix(terminal): restore hibernate listeners on failed wake On wake failure, dispose the partial xterm runtime and reinstall hibernate listeners (preserving pending) instead of unpausing into a listener-less backlog gap. Successful reconnect wakes still keep the pause until cleanupSession. Add a final pending take before exit-listener teardown. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> * fix(terminal): restore take-and-cleared pending on failed hibernate wake Track every pending take during wake and pass it to restoreAfterFailedWake so a thrown replay/reattach cannot permanently drop already-buffered output with the disposed partial xterm. Also take once more before exit-listener teardown. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> * fix(terminal): drain hibernate pending until empty before teardown After history replay, loop take-and-append until an empty take so an exit or residual chunk that arrives during an awaited replay cannot be dropped by stopHibernateListeners. Data listener is already stopped, so the loop stays short in practice. Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com> --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com> Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>
279 lines
10 KiB
TypeScript
279 lines
10 KiB
TypeScript
import type { MutableRefObject } from "react";
|
|
import type { FitAddon } from "@xterm/addon-fit";
|
|
import type { SearchAddon } from "@xterm/addon-search";
|
|
import type { SerializeAddon } from "@xterm/addon-serialize";
|
|
import type { Terminal as XTerm } from "@xterm/xterm";
|
|
|
|
import { logger } from "../../lib/logger";
|
|
import type { TerminalHibernateWakePayload } from "../../domain/terminalHibernate";
|
|
import {
|
|
createXTermRuntime,
|
|
type CreateXTermRuntimeContext,
|
|
type XTermRuntime,
|
|
} from "./runtime/createXTermRuntime";
|
|
import {
|
|
appendTerminalReplayData,
|
|
applyHibernateWakeToTerminal,
|
|
nudgeAlternateScreenRedraw,
|
|
} from "./terminalHibernateRuntime";
|
|
import {
|
|
applyTerminalKeywordHighlightRules,
|
|
type AdditionalTerminalKeywordHighlightRule,
|
|
} from "./terminalKeywordHighlightRules";
|
|
|
|
export { applyTerminalKeywordHighlightRules } from "./terminalKeywordHighlightRules";
|
|
|
|
export type TerminalRuntimeRefs = {
|
|
xtermRuntimeRef: MutableRefObject<XTermRuntime | null>;
|
|
termRef: MutableRefObject<XTerm | null>;
|
|
fitAddonRef: MutableRefObject<FitAddon | null>;
|
|
serializeAddonRef: MutableRefObject<SerializeAddon | null>;
|
|
searchAddonRef: MutableRefObject<SearchAddon | null>;
|
|
hasRuntimeRef: MutableRefObject<boolean>;
|
|
};
|
|
|
|
export function assignTerminalRuntimeRefs(
|
|
refs: TerminalRuntimeRefs,
|
|
runtime: XTermRuntime,
|
|
): void {
|
|
refs.xtermRuntimeRef.current = runtime;
|
|
refs.termRef.current = runtime.term;
|
|
refs.fitAddonRef.current = runtime.fitAddon;
|
|
refs.serializeAddonRef.current = runtime.serializeAddon;
|
|
refs.searchAddonRef.current = runtime.searchAddon;
|
|
refs.hasRuntimeRef.current = true;
|
|
}
|
|
|
|
export type WakeTerminalFromHibernateOptions = {
|
|
refs: TerminalRuntimeRefs;
|
|
runtimeContext: Omit<CreateXTermRuntimeContext, "container" | "initiallyVisible" | "deferWebglUntilReplayComplete">;
|
|
container: HTMLDivElement;
|
|
getPayload: () => TerminalHibernateWakePayload;
|
|
/**
|
|
* Pause backend output and wait for in-flight chunks to drain into the
|
|
* hibernate pending buffer before history replay. Returns true when the
|
|
* drain succeeded (safe to detach the data listener). Returns false when
|
|
* pause/drain was best-effort only; caller must keep a live uncapped
|
|
* pending listener through history replay (#2762).
|
|
*/
|
|
prepareWakeFlow?: () => Promise<boolean>;
|
|
/**
|
|
* Atomically read and clear hibernate pending output after the data listener
|
|
* has been stopped (and preferably after prepareWakeFlow).
|
|
*/
|
|
takePendingBuffer: () => string;
|
|
/** Stop only the hibernate data listener so pending stops growing. */
|
|
stopHibernateDataListener: () => void;
|
|
/**
|
|
* When prepareWakeFlow returns false, disable the 512 KiB pending cap so
|
|
* ACKed bytes that arrive during history replay are not trimmed.
|
|
*/
|
|
setHibernatePendingCapDisabled?: (disabled: boolean) => void;
|
|
/**
|
|
* Stop hibernate data+exit listeners and clear flow-ack state.
|
|
* Must keep the backend paused until resumeAfterReattach runs.
|
|
*/
|
|
stopHibernateListeners: () => void;
|
|
/**
|
|
* On a thrown/failed wake: dispose the partial xterm runtime and restore
|
|
* hibernate listeners so output is ACKed again (never unpause without a
|
|
* listener). `takenPending` is every byte already take-and-cleared during
|
|
* this wake attempt; it must be restored because those bytes no longer
|
|
* live in the pending ref and the partial xterm is disposed.
|
|
*/
|
|
restoreAfterFailedWake?: (takenPending: string) => void;
|
|
/** Resume backend output after the live display listener is attached. */
|
|
resumeAfterReattach?: () => void;
|
|
reattachSession: (term: XTerm) => void;
|
|
safeFit: (options?: { force?: boolean; requireVisible?: boolean }) => void;
|
|
resizeSession: () => void;
|
|
forceSyncRenderAfterResize: (term: XTerm) => void;
|
|
lastFittedSizeRef: MutableRefObject<{ width: number; height: number } | null>;
|
|
isBootActiveRef: MutableRefObject<boolean>;
|
|
sessionId: string;
|
|
updateStatus: (status: "connected") => void;
|
|
/** When false, recreate xterm and replay output without reattaching or forcing connected status. */
|
|
sessionConnected?: boolean;
|
|
getSessionConnected?: () => boolean;
|
|
replayChunkBytes?: number;
|
|
additionalKeywordHighlightRules?: readonly AdditionalTerminalKeywordHighlightRule[];
|
|
};
|
|
|
|
export async function wakeTerminalFromHibernate(
|
|
options: WakeTerminalFromHibernateOptions,
|
|
): Promise<boolean> {
|
|
const {
|
|
refs,
|
|
runtimeContext,
|
|
container,
|
|
getPayload,
|
|
prepareWakeFlow,
|
|
takePendingBuffer,
|
|
stopHibernateDataListener,
|
|
setHibernatePendingCapDisabled,
|
|
stopHibernateListeners,
|
|
restoreAfterFailedWake,
|
|
resumeAfterReattach,
|
|
reattachSession,
|
|
safeFit,
|
|
resizeSession,
|
|
forceSyncRenderAfterResize,
|
|
lastFittedSizeRef,
|
|
isBootActiveRef,
|
|
sessionId,
|
|
updateStatus,
|
|
sessionConnected = true,
|
|
getSessionConnected,
|
|
replayChunkBytes = 16 * 1024,
|
|
additionalKeywordHighlightRules = Object.freeze([]),
|
|
} = options;
|
|
|
|
if (refs.hasRuntimeRef.current) {
|
|
return true;
|
|
}
|
|
|
|
await new Promise<void>((resolve) => {
|
|
if (typeof requestAnimationFrame === "function") {
|
|
requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
|
|
return;
|
|
}
|
|
window.setTimeout(resolve, 0);
|
|
});
|
|
|
|
isBootActiveRef.current = true;
|
|
lastFittedSizeRef.current = null;
|
|
|
|
const runtime = createXTermRuntime({
|
|
...runtimeContext,
|
|
container,
|
|
initiallyVisible: true,
|
|
deferWebglUntilReplayComplete: true,
|
|
});
|
|
|
|
assignTerminalRuntimeRefs(refs, runtime);
|
|
applyTerminalKeywordHighlightRules(
|
|
runtime,
|
|
runtimeContext.terminalSettingsRef,
|
|
runtimeContext.host,
|
|
additionalKeywordHighlightRules,
|
|
);
|
|
|
|
const term = runtime.term;
|
|
// Pause first so in-flight output drains into pending via the still-live
|
|
// hibernate listener, then detach that listener before capturing pending.
|
|
// Full-history replay can take many frames; leaving the capped pending
|
|
// buffer open (or leaving no display listener while flow is live) drops
|
|
// ACKed bytes under sustained `cat` output (#2762).
|
|
let didReattach = false;
|
|
let wakeSucceeded = false;
|
|
// Bytes take-and-cleared from the pending ref during this wake. On failure
|
|
// they must be handed back: the partial xterm is disposed and the ref no
|
|
// longer holds them.
|
|
let takenPendingForRestore = "";
|
|
const takeAndTrackPending = (): string => {
|
|
const pending = takePendingBuffer();
|
|
if (pending) takenPendingForRestore += pending;
|
|
return pending;
|
|
};
|
|
try {
|
|
const drainOk = (await prepareWakeFlow?.()) ?? true;
|
|
if (drainOk) {
|
|
stopHibernateDataListener();
|
|
} else {
|
|
// Drain timed out / unavailable: keep the hibernate data listener so
|
|
// in-flight ACKed bytes still land in pending, but disable the 512 KiB
|
|
// cap for the wake window so a busy `cat` cannot trim the front.
|
|
setHibernatePendingCapDisabled?.(true);
|
|
}
|
|
const initialPayload = getPayload();
|
|
const pendingAtApplyStart = takeAndTrackPending();
|
|
const replayOptions = { chunkBytes: replayChunkBytes };
|
|
let replayedPendingChars = pendingAtApplyStart.length;
|
|
|
|
await applyHibernateWakeToTerminal(term, runtime, {
|
|
...initialPayload,
|
|
pendingBuffer: pendingAtApplyStart,
|
|
}, {
|
|
replayOptions,
|
|
deferWebgl: true,
|
|
});
|
|
runtime.cursorLineHighlighter.refresh({ force: true });
|
|
|
|
// Stop the data listener before draining residual pending. Captures:
|
|
// - exit "[session closed]" tails appended during history replay
|
|
// - uncapped live arrivals when drainOk was false
|
|
// Only the exit listener can still append after this point, so a short
|
|
// until-empty loop is enough; the last take before teardown must be empty
|
|
// after any awaited replay.
|
|
stopHibernateDataListener();
|
|
setHibernatePendingCapDisabled?.(false);
|
|
for (;;) {
|
|
const pendingTail = takeAndTrackPending();
|
|
if (!pendingTail) break;
|
|
await appendTerminalReplayData(term, pendingTail, replayOptions);
|
|
replayedPendingChars += pendingTail.length;
|
|
}
|
|
|
|
// Recompute after drains so an exit during those awaits cannot leave
|
|
// shouldReattach stale (would reattach a dead session as connected).
|
|
const shouldReattach = sessionConnected && (getSessionConnected?.() ?? true);
|
|
stopHibernateListeners();
|
|
if (shouldReattach) {
|
|
reattachSession(term);
|
|
updateStatus("connected");
|
|
didReattach = true;
|
|
}
|
|
|
|
runtime.ensureWebglRenderer();
|
|
runtime.clearTextureAtlas();
|
|
|
|
safeFit({ force: true });
|
|
resizeSession();
|
|
forceSyncRenderAfterResize(term);
|
|
if (initialPayload.alternateScreen) {
|
|
nudgeAlternateScreenRedraw(term);
|
|
} else {
|
|
term.scrollToBottom();
|
|
}
|
|
|
|
window.setTimeout(() => safeFit({ force: true }), 0);
|
|
window.setTimeout(() => {
|
|
safeFit({ force: true });
|
|
forceSyncRenderAfterResize(term);
|
|
if (initialPayload.alternateScreen) {
|
|
nudgeAlternateScreenRedraw(term);
|
|
}
|
|
}, 100);
|
|
window.setTimeout(() => {
|
|
safeFit({ force: true });
|
|
forceSyncRenderAfterResize(term);
|
|
if (initialPayload.alternateScreen) {
|
|
nudgeAlternateScreenRedraw(term);
|
|
}
|
|
}, 350);
|
|
|
|
logger.info("[Terminal] Resumed from hibernate", {
|
|
sessionId,
|
|
snapshotChars: initialPayload.snapshot.length,
|
|
viewportChars: initialPayload.viewportSnapshot?.length ?? initialPayload.snapshot.length,
|
|
scrollbackChars: initialPayload.scrollbackSnapshot?.length ?? 0,
|
|
pendingChars: replayedPendingChars,
|
|
alternateScreen: initialPayload.alternateScreen,
|
|
});
|
|
wakeSucceeded = true;
|
|
return true;
|
|
} finally {
|
|
setHibernatePendingCapDisabled?.(false);
|
|
if (!wakeSucceeded) {
|
|
// Dispose the partial runtime and restore hibernate listeners so a
|
|
// failed wake never unpauses into a listener-less backlog gap, and so a
|
|
// retry can re-enter wake (hasRuntimeRef stays false). Hand back every
|
|
// take-and-cleared pending byte so it is not lost with the disposed term.
|
|
restoreAfterFailedWake?.(takenPendingForRestore);
|
|
} else if (didReattach) {
|
|
resumeAfterReattach?.();
|
|
}
|
|
// Successful reconnect wakes (!didReattach) keep the pause until cleanupSession.
|
|
}
|
|
}
|