diff --git a/application/state/sftp/useSftpPaneActions.navHistory.test.tsx b/application/state/sftp/useSftpPaneActions.navHistory.test.tsx index 982f93578..eaf9aae27 100644 --- a/application/state/sftp/useSftpPaneActions.navHistory.test.tsx +++ b/application/state/sftp/useSftpPaneActions.navHistory.test.tsx @@ -45,6 +45,7 @@ function mountHarness(options?: { rightInitialPath?: string; failingPaths?: Set; dirCacheTtlMs?: number; + listDir?: (dirPath: string) => Promise; }) { const previousActFlag = (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT; (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; @@ -82,6 +83,9 @@ function mountHarness(options?: { const listDir = async (dirPath: string): Promise => { listedPaths.push(dirPath); + if (options?.listDir) { + return options.listDir(dirPath); + } if (failingPaths.has(dirPath)) { throw new Error(`Permission denied: ${dirPath}`); } @@ -281,3 +285,139 @@ test("host switch resets navigation history so previous host paths cannot be nav await harness.unmount(); } }); + +function createDeferred() { + let resolve!: (value: T) => void; + let reject!: (reason?: unknown) => void; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve, reject }; +} + +test("mid-flight refresh inherits pending push navigation and clears cleanly on settle or failure", async () => { + const pendingLoads: Array<{ path: string; deferred: ReturnType> }> = []; + const harness = mountHarness({ + dirCacheTtlMs: 0, + listDir: (dirPath) => { + if (dirPath === "/slow" || dirPath === "/slow-fail") { + const deferred = createDeferred(); + pendingLoads.push({ path: dirPath, deferred }); + return deferred.promise; + } + return Promise.resolve([]); + }, + }); + + try { + await harness.render(); + + // Start slow navigation to /slow, then refresh mid-flight before /slow settles. + const slowNavPromise = harness.actions.navigateTo("left", "/slow"); + assert.equal(harness.getPane("left").connection?.currentPath, "/slow"); + assert.equal(harness.getPane("left").loading, true); + assert.deepEqual(harness.getPane("left").navHistory?.entries, ["/home/alice"]); + + const refreshPromise = harness.actions.refresh("left"); + assert.equal(pendingLoads.length, 2); + + // Original slow navigation finishes first (superseded), then refresh settles. + pendingLoads[0].deferred.resolve([]); + assert.equal(await slowNavPromise, "superseded"); + pendingLoads[1].deferred.resolve([]); + await refreshPromise; + + assert.equal(harness.getPane("left").connection?.currentPath, "/slow"); + assert.deepEqual(harness.getPane("left").navHistory?.entries, ["/home/alice", "/slow"]); + assert.equal(harness.getPane("left").navHistory?.index, 1); + + // Back returns to /home/alice cleanly. + assert.equal(await harness.actions.navigateBack("left"), "reached"); + assert.equal(harness.getPane("left").connection?.currentPath, "/home/alice"); + assert.equal(harness.getPane("left").navHistory?.index, 0); + + // If a mid-flight refresh fails, currentPath reverts and history/forward stack stay intact. + pendingLoads.length = 0; + const failNavPromise = harness.actions.navigateTo("left", "/slow-fail"); + const failRefreshPromise = harness.actions.refresh("left"); + assert.equal(pendingLoads.length, 2); + + pendingLoads[0].deferred.resolve([]); + assert.equal(await failNavPromise, "superseded"); + pendingLoads[1].deferred.reject(new Error("I/O error")); + await failRefreshPromise; + + assert.equal(harness.getPane("left").connection?.currentPath, "/home/alice"); + assert.deepEqual(harness.getPane("left").navHistory?.entries, ["/home/alice", "/slow"]); + assert.equal(harness.getPane("left").navHistory?.index, 0); + assert.equal(canGoForward(harness.getPane("left").navHistory!), true); + } finally { + await harness.unmount(); + } +}); + +test("mid-flight refresh during Forward or Back advances history index consistently", async () => { + const pendingLoads: Array<{ path: string; deferred: ReturnType> }> = []; + let interceptTarget: string | null = null; + const harness = mountHarness({ + dirCacheTtlMs: 0, + listDir: (dirPath) => { + if (interceptTarget && dirPath === interceptTarget) { + const deferred = createDeferred(); + pendingLoads.push({ path: dirPath, deferred }); + return deferred.promise; + } + return Promise.resolve([]); + }, + }); + + try { + await harness.render(); + + // Build history: [/home/alice, /var, /var/log], then step Back to /var (index 1). + assert.equal(await harness.actions.navigateTo("left", "/var"), "reached"); + assert.equal(await harness.actions.navigateTo("left", "/var/log"), "reached"); + assert.equal(await harness.actions.navigateBack("left"), "reached"); + assert.equal(harness.getPane("left").connection?.currentPath, "/var"); + assert.equal(harness.getPane("left").navHistory?.index, 1); + + // Start Forward -> /var/log, then trigger Refresh before it finishes. + interceptTarget = "/var/log"; + const forwardPromise = harness.actions.navigateForward("left"); + assert.equal(harness.getPane("left").connection?.currentPath, "/var/log"); + assert.equal(harness.getPane("left").navHistory?.index, 1); + + const refreshPromise = harness.actions.refresh("left"); + assert.equal(pendingLoads.length, 2); + + pendingLoads[0].deferred.resolve([]); + assert.equal(await forwardPromise, "superseded"); + pendingLoads[1].deferred.resolve([]); + await refreshPromise; + + // Displayed directory and history index must stay synchronized at /var/log (index 2). + assert.equal(harness.getPane("left").connection?.currentPath, "/var/log"); + assert.deepEqual(harness.getPane("left").navHistory?.entries, ["/home/alice", "/var", "/var/log"]); + assert.equal(harness.getPane("left").navHistory?.index, 2); + + // Next Back must go to /var (NOT skip /var and jump to /home/alice). + interceptTarget = "/var"; + pendingLoads.length = 0; + const backPromise = harness.actions.navigateBack("left"); + const backRefreshPromise = harness.actions.refresh("left"); + assert.equal(pendingLoads.length, 2); + + pendingLoads[0].deferred.resolve([]); + assert.equal(await backPromise, "superseded"); + pendingLoads[1].deferred.resolve([]); + await backRefreshPromise; + + assert.equal(harness.getPane("left").connection?.currentPath, "/var"); + assert.equal(harness.getPane("left").navHistory?.index, 1); + assert.equal(canGoBack(harness.getPane("left").navHistory!), true); + assert.equal(canGoForward(harness.getPane("left").navHistory!), true); + } finally { + await harness.unmount(); + } +}); diff --git a/application/state/sftp/useSftpPaneActions.ts b/application/state/sftp/useSftpPaneActions.ts index 200ba20fa..40b9a1848 100644 --- a/application/state/sftp/useSftpPaneActions.ts +++ b/application/state/sftp/useSftpPaneActions.ts @@ -29,6 +29,8 @@ import { createNavHistory, goBack, goForward, + resolveSftpEffectiveNavHistoryMode, + type PendingSftpNavHistoryTransition, type SftpNavHistoryTransitionMode, } from "../../../domain/sftpNavHistory"; @@ -162,6 +164,12 @@ export const useSftpPaneActions = ({ new Map; filter: string }>(), ); + // Track the in-flight navigation history transition per tab so a mid-flight + // refresh (historyMode: "none") targeting the same unconfirmed destination + // inherits the pending transition instead of leaving currentPath and + // navHistory out of sync. + const pendingNavHistoryRef = useRef(new Map()); + const navigateTo = useCallback( async ( side: "left" | "right", @@ -194,7 +202,14 @@ export const useSftpPaneActions = ({ ); const connectionId = pane.connection.id; - const historyMode: SftpNavHistoryTransitionMode = options?.historyMode ?? "push"; + const requestedHistoryMode: SftpNavHistoryTransitionMode = options?.historyMode ?? "push"; + const historyMode = resolveSftpEffectiveNavHistoryMode({ + requestedMode: requestedHistoryMode, + pending: pendingNavHistoryRef.current.get(targetTabId), + connectionId, + targetPath: normalizedPath, + isSamePath: isSameSftpPath, + }); const requestId = ++navSeqRef.current[side]; const cacheKey = makeCacheKey(connectionId, normalizedPath, pane.filenameEncoding); const clearFilterForPathChange = shouldClearSftpFilterForPathChange(pane.connection.currentPath, normalizedPath); @@ -209,6 +224,7 @@ export const useSftpPaneActions = ({ cached.files ) { tabNavSeqRef.current.set(targetTabId, requestId); + pendingNavHistoryRef.current.delete(targetTabId); lastConfirmedRef.current.set(targetTabId, { connectionId, path: normalizedPath, @@ -271,6 +287,11 @@ export const useSftpPaneActions = ({ const previousFilter = confirmed.filter; const previousError = pane.error; const isTargetRequestCurrent = () => tabNavSeqRef.current.get(targetTabId) === requestId; + const clearPendingNavHistoryIfCurrent = () => { + if (isTargetRequestCurrent()) { + pendingNavHistoryRef.current.delete(targetTabId); + } + }; const getTargetPane = () => { const currentSideTabs = side === "left" ? leftTabsRef.current : rightTabsRef.current; return currentSideTabs.tabs.find((t) => t.id === targetTabId) ?? null; @@ -281,6 +302,7 @@ export const useSftpPaneActions = ({ ); const restoreConfirmedStateIfCurrent = () => { if (!isTargetRequestCurrent()) return; + pendingNavHistoryRef.current.delete(targetTabId); updateTab(side, targetTabId, (prev) => { if (prev.connection?.id !== connectionId || !isTargetRequestCurrent()) return prev; return { @@ -295,6 +317,15 @@ export const useSftpPaneActions = ({ }); }; tabNavSeqRef.current.set(targetTabId, requestId); + if (historyMode !== "none") { + pendingNavHistoryRef.current.set(targetTabId, { + connectionId, + path: normalizedPath, + mode: historyMode, + }); + } else { + pendingNavHistoryRef.current.delete(targetTabId); + } // Keep existing files visible during loading — the loading overlay // (pointer-events-none) prevents interaction. This avoids blanking a tab // that gets superseded by another tab navigating on the same side. @@ -324,6 +355,7 @@ export const useSftpPaneActions = ({ restoreConfirmedStateIfCurrent(); return "aborted"; } + clearPendingNavHistoryIfCurrent(); clearCacheForConnection(pane.connection.id); // For background tabs (explicit tabId), update that tab directly // instead of handleSessionError which targets the active tab. @@ -350,6 +382,7 @@ export const useSftpPaneActions = ({ restoreConfirmedStateIfCurrent(); return "aborted"; } + clearPendingNavHistoryIfCurrent(); await releaseConnection(pane.connection.id); if (options?.tabId) { updateTab(side, targetTabId, (prev) => ({ @@ -387,6 +420,8 @@ export const useSftpPaneActions = ({ timestamp: Date.now(), }, { ttlMs: dirCacheTtlMs }); + clearPendingNavHistoryIfCurrent(); + lastConfirmedRef.current.set(targetTabId, { connectionId, path: normalizedPath, @@ -433,6 +468,7 @@ export const useSftpPaneActions = ({ restoreConfirmedStateIfCurrent(); return "aborted"; } + clearPendingNavHistoryIfCurrent(); let navigationFailed = false; updateTab(side, targetTabId, (prev) => { if (prev.connection?.id !== connectionId) { diff --git a/domain/sftpNavHistory.test.ts b/domain/sftpNavHistory.test.ts index 25c740e22..847843010 100644 --- a/domain/sftpNavHistory.test.ts +++ b/domain/sftpNavHistory.test.ts @@ -15,6 +15,7 @@ import { pushNavHistory, resetNavHistory, resolveSftpConnectNavHistory, + resolveSftpEffectiveNavHistoryMode, } from "./sftpNavHistory.ts"; test("createNavHistory initializes empty or with an initial path", () => { @@ -242,3 +243,48 @@ test("resolveSftpConnectNavHistory resets on host switch and preserves on same-e assert.deepEqual(reconnectedFallbackPath.entries, ["/home/alice", "/var/log", "/home/alice"]); assert.equal(reconnectedFallbackPath.index, 2); }); + +test("resolveSftpEffectiveNavHistoryMode inherits pending transitions on matching mid-flight refresh", () => { + const pending = { connectionId: "conn-1", path: "/var/log", mode: "forward" as const }; + + assert.equal( + resolveSftpEffectiveNavHistoryMode({ + requestedMode: "none", + pending, + connectionId: "conn-1", + targetPath: "/var/log", + }), + "forward", + ); + + // Different path or connection does not inherit + assert.equal( + resolveSftpEffectiveNavHistoryMode({ + requestedMode: "none", + pending, + connectionId: "conn-1", + targetPath: "/var", + }), + "none", + ); + assert.equal( + resolveSftpEffectiveNavHistoryMode({ + requestedMode: "none", + pending, + connectionId: "conn-2", + targetPath: "/var/log", + }), + "none", + ); + + // Explicit non-"none" mode always wins + assert.equal( + resolveSftpEffectiveNavHistoryMode({ + requestedMode: "back", + pending, + connectionId: "conn-1", + targetPath: "/var/log", + }), + "back", + ); +}); diff --git a/domain/sftpNavHistory.ts b/domain/sftpNavHistory.ts index bf76314ad..6f36e0ff0 100644 --- a/domain/sftpNavHistory.ts +++ b/domain/sftpNavHistory.ts @@ -14,6 +14,12 @@ export interface SftpNavHistoryStep { export type SftpNavHistoryTransitionMode = "push" | "back" | "forward" | "none"; +export interface PendingSftpNavHistoryTransition { + readonly connectionId: string; + readonly path: string; + readonly mode: SftpNavHistoryTransitionMode; +} + export type SftpNavPathComparator = (a: string, b: string) => boolean; const defaultIsSamePath: SftpNavPathComparator = (a, b) => a === b; @@ -182,6 +188,27 @@ export function applySftpNavHistoryTransition(params: { return pushNavHistory(base, params.targetPath, compare); } +export function resolveSftpEffectiveNavHistoryMode(params: { + requestedMode: SftpNavHistoryTransitionMode; + pending?: PendingSftpNavHistoryTransition; + connectionId: string; + targetPath: string; + isSamePath?: SftpNavPathComparator; +}): SftpNavHistoryTransitionMode { + if (params.requestedMode !== "none") { + return params.requestedMode; + } + const compare = params.isSamePath ?? defaultIsSamePath; + if ( + params.pending + && params.pending.connectionId === params.connectionId + && compare(params.pending.path, params.targetPath) + ) { + return params.pending.mode; + } + return "none"; +} + export function resolveSftpConnectNavHistory(params: { sameEndpointReconnect: boolean; previousHistory?: SftpNavHistory;