Files
Netcatty/components/terminal/restoredSessionGate.test.ts
T
205d1591e8 feat(terminal): add disconnect/reconnect on workspace split status bar (#2769) (#2771)
* feat(terminal): add disconnect/reconnect controls on session status bar

Workspace panes could not reach tab-level reconnect. Expose disconnect
(without closing the pane) and reconnect beside the host info actions so
split sessions stay operable. Closes #2769.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): abort in-flight boot on status-bar disconnect

Disconnect keeps the pane mounted, so cancel's unmount cleanup never runs.
Flip isBootActiveRef (and isCancelling) so a late startSSH/startMosh attach
cannot resurrect the session after the user disconnects mid-connect.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): ignore stale start UI after status-bar disconnect

When disconnect aborts an in-flight connect, starter catch paths must not
reopen auth or repopulate errors. Gate SSH/telnet/mosh/ET/local/serial
failure UI on isTerminalBootActive and harden the boot effect awaits.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): hide disconnect/reconnect on compact popup terminals

Owned command popups use compactToolbar with a one-shot startup command.
Exposing reconnect there can re-run that command; keep the controls on
normal tabs/workspace panes only.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): use boot epoch so reconnect cannot revive aborted starts

Disconnect alone flipping isBootActiveRef is not enough: an immediate
reconnect re-arms boot, and a late startSSH from the aborted attempt can
still attach. Capture a boot epoch per attempt and ignore stale attaches/UI.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): do not let stale attach abort a newer reconnect

tryAttach failure for an expired boot epoch must close the orphan session
only. Calling abortSessionStartAfterUnmount() would force disconnected on
a reconnect that already re-armed boot.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): reject late host-key prompts after disconnect

Disconnect can land before pendingHostKeyRequestId is set. Auto-deny
onHostKeyVerification when boot is inactive or status is disconnected
so approval UI cannot reopen on an aborted pane.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): cancel wake and MFA when status-bar disconnects

Invalidate hibernation reconnect-wake tokens on disconnect so a late wake
cannot re-arm boot. Reject/cancel keyboard-interactive prompts for
disconnected panes and clear any already-queued MFA for that session.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): ignore stale SSH catch UI and password fallback

Check boot attempt currency before resetting reconnect UI state on
SSH start failure, and before launching key→password fallback after
disconnect so a replacement reconnect is not interrupted.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): guard stale SSH progress and host-key prompts

Ignore chain-progress callbacks from superseded boot attempts, and
thread bootEpoch through SSH host-key verification so a late prompt
from an aborted start cannot overwrite a replacement reconnect.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): correlate MFA and jump host-keys with boot epoch

Forward bootEpoch through jump-host verification and keyboard-interactive
prompts, and reject superseded MFA when the retained tab has already
started a replacement reconnect.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): keep replacement SSH session alive across stale starts

Skip closeSession for superseded starts while a newer boot still owns
the shared sessionId, and avoid clearing MFA wait state before the
attempt-freshness guard on SSH success.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): own shared sessionIds by boot epoch

Claim SSH/local registry slots with bootEpoch so a stale start cannot
overwrite a replacement, and make closeSession no-op when the payload
epoch does not match the live session owner.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): claim bootEpoch for all reconnectable backends

Pass bootEpoch through Telnet/Mosh/ET/serial starts, claim registry slots
the same way as SSH/local, and dispose displaced owners when a newer
boot replaces the shared sessionId.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): protect preload listeners and ET artifacts on displace

Defer epoch-scoped closeSession listener teardown until main confirms
ownership, and remove ET external-auth temp artifacts when a newer boot
displaces the previous registry owner.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): clean rejected Mosh starts and keep replacement listeners

Kill superseded Mosh/ET PTYs and auth temp files when claimSessionSlot
rejects, and never clear shared preload listeners on epoch-scoped closes.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): settle superseded boots and stop displaced log streams

Reject Telnet/SSH claim failures through Promise reject/failReuse instead of
uncaught EventEmitter/.then throws, and stop a displaced session's log stream
so a logging-disabled reconnect cannot append into the old file.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): keep woken runtime when disconnect cancels hibernate wake

Disconnect invalidates in-flight hibernated reconnects with keep mode so a
successful wake that already cleared hibernatedRef is not disposed into a
dead pane that can never reconnect. Unmount still disposes orphan runtimes.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): bind reused SSH shellPid only to the claimed session

Late PID discovery after Copy Tab reuse must not write onto a newer
bootEpoch that already replaced the shared sessionId registry slot.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): await plugin cancel cleanup and clear boot epochs on teardown

Track plugin start/cancel promises so Disconnect→Reconnect waits until the
external session finishes unregistering, and stop unmount teardown from
republishing boot epochs into the process-wide map.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): cancel SSH passphrase prompts on disconnect

Register a pending-boot AbortSignal for SSH starts, abort it (and session-
scoped passphrase requests) from closeSession even before a registry slot
exists, and filter/drop late passphrase modals by boot epoch / disconnect.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): close owned boot epoch and scope passphrase cancels

Capture the pre-bump epoch for disconnect/teardown closeSession so live
transports are not skipped by epoch mismatch, cancel only passphrase prompts
at or below that epoch, and revalidate boot currency after async passphrase
lookups before queuing a modal.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): tag Telnet auto-login and Mosh ready with bootEpoch

Emit bootEpoch on telnet auto-login and mosh:ready events so overlapping
Disconnect→Reconnect boots ignore cross-delivered callbacks meant for an
older shared sessionId.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): update disconnect assertion and cancel pending serial opens

Align the disconnect source regression with invalidateBootEpochForClose, and
abort in-flight serialPort.open attempts via pending boot AbortSignal so
Disconnect→Reconnect cannot leave a stale open racing the replacement.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(terminal): keep flow-pause leases on skipped epoch closes

Worker close:await previously cleared pause ownership in finally even when
the worker returned skipped for an epoch mismatch, dropping the live
replacement's lease. Only clear on non-skipped closes; epoch-scoped
fire-and-forget close similarly defers to onSessionClosed.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>
2026-08-06 15:47:20 +08:00

314 lines
17 KiB
TypeScript

import test from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import {
getInitialTerminalStatus,
shouldSuppressHostStartupCommandOnReconnect,
shouldStartTerminalBackend,
} from "./restoredSessionGate.ts";
test("restored disconnected sessions initialize as connecting", () => {
assert.equal(
getInitialTerminalStatus(),
"connecting",
);
});
test("normal sessions initialize as connecting", () => {
assert.equal(getInitialTerminalStatus(), "connecting");
});
test("restored disconnected sessions start terminal backend", () => {
assert.equal(shouldStartTerminalBackend(), true);
});
test("host startup command policy distinguishes restored and automatic reconnects", () => {
assert.equal(shouldSuppressHostStartupCommandOnReconnect("restored"), false);
assert.equal(shouldSuppressHostStartupCommandOnReconnect("manual"), false);
assert.equal(shouldSuppressHostStartupCommandOnReconnect("automatic"), true);
});
test("restored disconnected sessions still create a terminal runtime before backend startup", () => {
const source = readFileSync(new URL("./useTerminalEffects.ts", import.meta.url), "utf8");
const runtimeIndex = source.indexOf("const runtime = createXTermRuntime");
const backendGateIndex = source.indexOf("if (!shouldStartTerminalBackend())");
assert.notEqual(runtimeIndex, -1);
assert.notEqual(backendGateIndex, -1);
assert.ok(
runtimeIndex < backendGateIndex,
"restored sessions need an xterm runtime before the backend starts",
);
});
test("auto reconnect prepares restored session state before clearing the restore marker", () => {
const source = readFileSync(new URL("./useTerminalEffects.ts", import.meta.url), "utf8");
const prepareIndex = source.indexOf("prepareRestoredReconnect?.()");
const updateConnectingIndex = source.indexOf('updateStatus("connecting")', prepareIndex);
assert.notEqual(prepareIndex, -1);
assert.notEqual(updateConnectingIndex, -1);
assert.ok(
prepareIndex < updateConnectingIndex,
"auto reconnect must capture restore details before the restored marker is cleared",
);
});
test("manual reconnect captures restore cwd intent before clearing restored state", () => {
const source = readFileSync(new URL("../Terminal.tsx", import.meta.url), "utf8");
const importIndex = source.indexOf("resolveRestoreCwdIntent");
const refIndex = source.indexOf("const restoreCwdIntentRef = useRef");
const contextIndex = source.indexOf("restoreCwdIntentRef,");
const prepareDefinitionIndex = source.indexOf("const prepareRestoredReconnect = useCallback");
const captureAssignIndex = source.indexOf("restoreCwdIntentRef.current =", prepareDefinitionIndex);
const captureCallIndex = source.indexOf("resolveRestoreCwdIntent", captureAssignIndex);
const reconnectIndex = source.indexOf("const startReconnect = ");
const manualBranchIndex = source.indexOf('if (mode === "manual")', reconnectIndex);
const manualPrepareIndex = source.indexOf("prepareRestoredReconnect();", manualBranchIndex);
const bootActiveIndex = source.indexOf("isBootActiveRef.current = true", manualPrepareIndex);
const connectingIndex = source.indexOf('updateStatus("connecting")', manualPrepareIndex);
const startNewSessionIndex = source.indexOf("const startNewSession = () =>", connectingIndex);
assert.notEqual(importIndex, -1);
assert.notEqual(refIndex, -1);
assert.notEqual(contextIndex, -1);
assert.notEqual(prepareDefinitionIndex, -1);
assert.notEqual(captureCallIndex, -1);
assert.notEqual(captureAssignIndex, -1);
assert.notEqual(reconnectIndex, -1);
assert.notEqual(manualBranchIndex, -1);
assert.notEqual(manualPrepareIndex, -1);
assert.notEqual(bootActiveIndex, -1);
assert.notEqual(connectingIndex, -1);
assert.notEqual(startNewSessionIndex, -1);
assert.ok(
captureAssignIndex < captureCallIndex && manualPrepareIndex < connectingIndex,
"manual retry must capture cwd intent while restoreState is still available",
);
assert.ok(
bootActiveIndex < startNewSessionIndex,
"manual retry must reactivate the boot guard before opening a backend session",
);
});
test("manual reconnect re-arms inherited cwd intent after a failed first connection", () => {
const source = readFileSync(new URL("../Terminal.tsx", import.meta.url), "utf8");
const reconnectIndex = source.indexOf("const startReconnect = ");
const manualBranchIndex = source.indexOf('if (mode === "manual")', reconnectIndex);
const manualPrepareIndex = source.indexOf("prepareRestoredReconnect();", manualBranchIndex);
const rearmIndex = source.indexOf("prepareInitialCwdIntent();", manualPrepareIndex);
const connectingIndex = source.indexOf('updateStatus("connecting")', manualPrepareIndex);
assert.notEqual(reconnectIndex, -1);
assert.notEqual(manualBranchIndex, -1);
assert.notEqual(manualPrepareIndex, -1);
assert.notEqual(rearmIndex, -1);
assert.notEqual(connectingIndex, -1);
assert.ok(
manualPrepareIndex < rearmIndex && rearmIndex < connectingIndex,
"a clone whose first connection fails must re-arm the inherited cwd on manual retry",
);
});
test("auto reconnect connected history ref is initialized after status state exists", () => {
const source = readFileSync(new URL("../Terminal.tsx", import.meta.url), "utf8");
const statusStateIndex = source.indexOf('const [status, setStatus] = useState<TerminalSession["status"]>');
const hasEverConnectedIndex = source.indexOf("const hasEverConnectedRef = useRef");
assert.notEqual(statusStateIndex, -1);
assert.notEqual(hasEverConnectedIndex, -1);
assert.ok(
statusStateIndex < hasEverConnectedIndex,
"auto reconnect refs must not read status before the status state is initialized",
);
});
test("reconnect wakes a hibernated terminal before requiring a terminal instance", () => {
const source = readFileSync(new URL("../Terminal.tsx", import.meta.url), "utf8");
const wakePromiseRefIndex = source.indexOf("const wakePromiseRef = useRef<Promise<boolean> | null>(null)");
const wakeGuardRefIndex = source.indexOf("const reconnectWakeInFlightRef = useRef(false)");
const wakeTokenRefIndex = source.indexOf("const reconnectWakeTokenRef = useRef<symbol | null>(null)");
const wakeInvalidateModeIndex = source.indexOf('const reconnectWakeInvalidateModeRef = useRef<"dispose" | "keep">("dispose")');
const wakeTokenCleanupIndex = source.indexOf("reconnectWakeTokenRef.current = null", wakeTokenRefIndex);
const reconnectIndex = source.indexOf("const startReconnect = ");
const hibernatedBranchIndex = source.indexOf('!termRef.current && hibernatedRef.current', reconnectIndex);
const duplicateWakeGuardIndex = source.indexOf("if (reconnectWakeInFlightRef.current) return", hibernatedBranchIndex);
const markWakeInFlightIndex = source.indexOf("reconnectWakeInFlightRef.current = true", duplicateWakeGuardIndex);
const connectingIndex = source.indexOf('updateStatus("connecting")', markWakeInFlightIndex);
const wakeCallIndex = source.indexOf("wakeHibernatedRuntimeForReconnectRef.current", hibernatedBranchIndex);
const wakeInvocationIndex = source.indexOf("void wakeForReconnect()", wakeCallIndex);
const wakeJoinIndex = source.indexOf("return wakePromiseRef.current ?? false", source.indexOf("const wakeFromHibernateRuntime"));
const wakeTokenIndex = source.indexOf("const wakeToken = Symbol()", hibernatedBranchIndex);
const staleWakeGuardIndex = source.indexOf("reconnectWakeTokenRef.current !== wakeToken", wakeInvocationIndex);
const staleWakeDisposeGuardIndex = source.indexOf('reconnectWakeInvalidateModeRef.current === "dispose"', staleWakeGuardIndex);
const staleWakeDisposeIndex = source.indexOf("disposeRuntimeOnly();", staleWakeDisposeGuardIndex);
const disconnectKeepModeIndex = source.indexOf('reconnectWakeInvalidateModeRef.current = "keep"', source.indexOf("const handleDisconnect"));
const missingTermReturnIndex = source.indexOf("if (!termRef.current) return;", reconnectIndex);
assert.notEqual(wakePromiseRefIndex, -1);
assert.notEqual(wakeGuardRefIndex, -1);
assert.notEqual(wakeTokenRefIndex, -1);
assert.notEqual(wakeInvalidateModeIndex, -1);
assert.notEqual(wakeTokenCleanupIndex, -1);
assert.ok(wakeTokenCleanupIndex < reconnectIndex);
assert.notEqual(reconnectIndex, -1);
assert.notEqual(hibernatedBranchIndex, -1);
assert.notEqual(duplicateWakeGuardIndex, -1);
assert.notEqual(markWakeInFlightIndex, -1);
assert.notEqual(connectingIndex, -1);
assert.notEqual(wakeCallIndex, -1);
assert.notEqual(wakeInvocationIndex, -1);
assert.notEqual(wakeJoinIndex, -1);
assert.notEqual(wakeTokenIndex, -1);
assert.notEqual(staleWakeGuardIndex, -1);
assert.notEqual(staleWakeDisposeGuardIndex, -1);
assert.notEqual(staleWakeDisposeIndex, -1);
assert.notEqual(disconnectKeepModeIndex, -1);
assert.notEqual(missingTermReturnIndex, -1);
assert.ok(
hibernatedBranchIndex < missingTermReturnIndex && wakeCallIndex < missingTermReturnIndex,
"manual and auto reconnect must wake fully hibernated sessions before the terminal guard can stop the retry",
);
assert.ok(
duplicateWakeGuardIndex < markWakeInFlightIndex && markWakeInFlightIndex < connectingIndex,
"hibernated reconnect must block duplicate requests before beginning an asynchronous wake",
);
assert.ok(
wakeTokenIndex < wakeInvocationIndex && wakeInvocationIndex < staleWakeGuardIndex,
"closing a terminal must be able to invalidate a pending hibernated reconnect",
);
assert.ok(
staleWakeGuardIndex < staleWakeDisposeGuardIndex && staleWakeDisposeGuardIndex < staleWakeDisposeIndex,
"an invalidated hibernated wake must dispose any runtime created after unmount cleanup",
);
assert.ok(
disconnectKeepModeIndex !== -1,
"disconnect must keep a woken runtime so later reconnect still has a terminal instance",
);
});
test("dismissing the disconnected dialog returns focus to the terminal for enter reconnect", () => {
const source = readFileSync(new URL("../Terminal.tsx", import.meta.url), "utf8");
const dismissIndex = source.indexOf("const handleDismissDisconnectedDialog = () =>");
const dismissedIndex = source.indexOf("setIsDisconnectedDialogDismissed(true)", dismissIndex);
const focusIndex = source.indexOf("queueMicrotask(() => termRef.current?.focus())", dismissIndex);
const closeSessionIndex = source.indexOf("const handleCloseDisconnectedSession = () =>", dismissIndex);
assert.notEqual(dismissIndex, -1);
assert.notEqual(dismissedIndex, -1);
assert.notEqual(focusIndex, -1);
assert.notEqual(closeSessionIndex, -1);
assert.ok(
dismissedIndex < focusIndex && focusIndex < closeSessionIndex,
"dismissing the disconnected dialog should leave Enter routed back through the terminal",
);
});
test("disconnected connection dialog keeps an Enter-reconnect focus sink", () => {
const source = readFileSync(new URL("./TerminalConnectionDialog.tsx", import.meta.url), "utf8");
assert.match(source, /canEnterReconnectFromDialog/);
assert.match(source, /data-terminal-disconnected-dialog/);
assert.match(source, /shouldReconnectDisconnectedDialogOnEnterKey/);
assert.match(source, /shouldClaimDisconnectedDialogFocus/);
assert.match(source, /shouldRestoreDisconnectedDialogTerminalFocus/);
assert.match(source, /restoreTerminalFocusFromDisconnectedDialog/);
assert.match(source, /dialogFocusRef\.current\?\.focus/);
// Focus claim must key only on enter-reconnect mode, not showLogs/error,
// or toggling "Show logs" steals keyboard focus off the button.
const claimEffectIdx = source.indexOf("Claim focus only when Enter-reconnect mode turns on");
// Restore must run on overlay unmount — not when Enter-reconnect ends into
// auth/host-key while the dialog stays mounted.
const restoreEffectIdx = source.indexOf("Restore xterm focus only when this overlay unmounts");
assert.notEqual(claimEffectIdx, -1);
assert.notEqual(restoreEffectIdx, -1);
const claimDeps = source.indexOf("}, [canEnterReconnectFromDialog, isFocusedPane]);", claimEffectIdx);
const restoreDeps = source.indexOf("}, []);", restoreEffectIdx);
assert.notEqual(claimDeps, -1);
assert.notEqual(restoreDeps, -1);
assert.ok(claimDeps < restoreEffectIdx);
// Claim deps must not re-run on showLogs/error/status; restore is unmount-only.
assert.match(source.slice(claimDeps, claimDeps + 60), /^\}, \[canEnterReconnectFromDialog, isFocusedPane\]\);/);
assert.match(source.slice(restoreDeps, restoreDeps + 10), /^\}, \[\]\);/);
assert.equal(source.includes("}, [canEnterReconnectFromDialog, status, error, showLogs]"), false);
// Split unfocused panes pass isFocusedPane so document blur cannot steal focus.
assert.match(source, /isFocusedPane/);
assert.match(source, /shouldClaimDisconnectedDialogFocus\(\{[\s\S]*isFocusedPane/);
// Unmount restore must also honor isFocusedPane when focus lands on body/html.
assert.match(source, /restoreTerminalFocusFromDisconnectedDialog\(\{[\s\S]*isFocusedPane/);
});
test("open terminal search does not globally gate enter reconnect", () => {
const viewSource = readFileSync(new URL("./TerminalView.tsx", import.meta.url), "utf8");
const gateIndex = viewSource.indexOf("export function shouldReconnectTerminalOnEnterKey");
const bodyEnd = viewSource.indexOf("export function shouldBlockTerminalReconnectForTarget", gateIndex);
const gateBody = viewSource.slice(gateIndex, bodyEnd);
assert.equal(gateBody.includes("!isSearchOpen"), false);
assert.match(viewSource, /isTerminalSearchInput/);
assert.match(
readFileSync(new URL("./TerminalSearchBar.tsx", import.meta.url), "utf8"),
/data-terminal-search-input/,
);
});
test("terminal view receives the effective compose bar state for enter reconnect gating", () => {
const source = readFileSync(new URL("../Terminal.tsx", import.meta.url), "utf8");
const effectiveDefinitionIndex = source.indexOf("const effectiveComposeBarOpen =");
const viewIndex = source.indexOf("<TerminalView ctx={{");
const passEffectiveIndex = source.indexOf("isComposeBarOpen: effectiveComposeBarOpen", viewIndex);
assert.notEqual(effectiveDefinitionIndex, -1);
assert.notEqual(viewIndex, -1);
assert.notEqual(passEffectiveIndex, -1);
assert.ok(
effectiveDefinitionIndex < passEffectiveIndex,
"TerminalView must use the visible workspace compose state before deciding whether Enter can reconnect",
);
});
test("startup and attach cwd cache clears preserve restore cwd metadata", () => {
const terminalSource = readFileSync(new URL("../Terminal.tsx", import.meta.url), "utf8");
const effectsSource = readFileSync(new URL("./useTerminalEffects.ts", import.meta.url), "utf8");
const clearDefinitionIndex = terminalSource.indexOf("const clearTerminalCwd = useCallback");
const clearNotifyIndex = terminalSource.indexOf("onTerminalCwdChange?.(sessionId, null)", clearDefinitionIndex);
const persistGuardIndex = terminalSource.indexOf("persistRestoreMetadata", clearDefinitionIndex);
const attachIndex = terminalSource.indexOf("onSessionAttached: (id: string) =>");
const attachClearIndex = terminalSource.indexOf("clearTerminalCwd({ persistRestoreMetadata: false })", attachIndex);
const startupClearIndex = effectsSource.indexOf("clearTerminalCwd({ persistRestoreMetadata: false })");
assert.notEqual(clearDefinitionIndex, -1);
assert.notEqual(clearNotifyIndex, -1);
assert.notEqual(persistGuardIndex, -1);
assert.notEqual(attachIndex, -1);
assert.notEqual(attachClearIndex, -1);
assert.notEqual(startupClearIndex, -1);
assert.ok(
persistGuardIndex < clearNotifyIndex,
"clearTerminalCwd must gate persisted restore metadata updates",
);
});
test("restored cwd intent marks known cwd before initial backend pwd probe can persist home", () => {
const terminalSource = readFileSync(new URL("../Terminal.tsx", import.meta.url), "utf8");
const effectsSource = readFileSync(new URL("./useTerminalEffects.ts", import.meta.url), "utf8");
const callbackIndex = terminalSource.indexOf("onRestoreCwdIntentConsumed:");
const knownAssignIndex = terminalSource.indexOf("knownCwdRef.current = cwd", callbackIndex);
const backendProbeGuardIndex = effectsSource.indexOf("knownCwdRef.current");
const backendPwdWriteIndex = effectsSource.indexOf("onPluginRuntimeCwdChange(result.cwd)", backendProbeGuardIndex);
assert.notEqual(callbackIndex, -1);
assert.notEqual(knownAssignIndex, -1);
assert.notEqual(backendProbeGuardIndex, -1);
assert.notEqual(backendPwdWriteIndex, -1);
assert.ok(
knownAssignIndex > callbackIndex,
"Terminal must preserve the restore target as a known cwd when the restore command is sent",
);
assert.ok(
backendProbeGuardIndex < backendPwdWriteIndex,
"initial backend pwd probe must remain guarded by knownCwdRef before it publishes the probed cwd",
);
});