feat(sftp): add back and forward directory history navigation (#4324)

* feat(sftp): add back and forward directory history navigation

* fix(sftp): preserve pending nav history transition on mid-flight refresh
This commit is contained in:
陈大猫 authored and GitHub committed 2026-11-25 11:26:13 +08:00
1 parent 196132621c
commit a9cf94aeba
19 files changed
+1413 -6

No files matched your search

+2
View File
@@ -421,6 +421,8 @@ export const enVaultMessages: Messages = {
'sftp.encoding.auto': 'Auto',
'sftp.encoding.utf8': 'UTF-8',
'sftp.encoding.gb18030': 'GB18030',
'sftp.goBack': 'Go back',
'sftp.goForward': 'Go forward',
'sftp.goHome': 'Go to home',
'sftp.goRoot': 'Go to root',
'sftp.folderName': 'Folder name',
+2
View File
@@ -421,6 +421,8 @@ export const esVaultMessages: Messages = {
'sftp.encoding.auto': 'Auto',
'sftp.encoding.utf8': 'UTF-8',
'sftp.encoding.gb18030': 'GB18030',
'sftp.goBack': 'Ir atrás',
'sftp.goForward': 'Ir adelante',
'sftp.goHome': 'Ir al inicio',
'sftp.goRoot': 'Ir a la raíz',
'sftp.folderName': 'Nombre de la carpeta',
+2
View File
@@ -464,6 +464,8 @@ export const ruVaultMessages: Messages = {
'sftp.encoding.auto': 'Авто',
'sftp.encoding.utf8': 'UTF-8',
'sftp.encoding.gb18030': 'GB18030',
'sftp.goBack': 'Назад',
'sftp.goForward': 'Вперёд',
'sftp.goHome': 'Перейти в домашний каталог',
'sftp.goRoot': 'Перейти в корень',
'sftp.folderName': 'Имя папки',
+2
View File
@@ -1167,6 +1167,8 @@ Vaults 标签保持扁平,不使用这块背景。
'sftp.encoding.auto': '自动',
'sftp.encoding.utf8': 'UTF-8',
'sftp.encoding.gb18030': 'GB18030',
'sftp.goBack': '后退',
'sftp.goForward': '前进',
'sftp.goHome': '返回主目录',
'sftp.goRoot': '回到根目录',
'sftp.folderName': '文件夹名称',
+2
View File
@@ -1167,6 +1167,8 @@ Vaults 分頁維持扁平,不使用這塊背景。
'sftp.encoding.auto': '自動',
'sftp.encoding.utf8': 'UTF-8',
'sftp.encoding.gb18030': 'GB18030',
'sftp.goBack': '後退',
'sftp.goForward': '前進',
'sftp.goHome': '返回主目錄',
'sftp.goRoot': '回到根目錄',
'sftp.folderName': '資料夾名稱',
+3
View File
@@ -1,4 +1,5 @@
import { Host, KnownHost, SftpConnection, SftpFileEntry, SftpFilenameEncoding } from "../../../domain/models";
import { createNavHistory, type SftpNavHistory } from "../../../domain/sftpNavHistory";
export interface SftpPane {
id: string;
@@ -13,6 +14,7 @@ export interface SftpPane {
filenameEncoding: SftpFilenameEncoding;
showHiddenFiles: boolean;
transferMutationToken: number;
navHistory?: SftpNavHistory;
}
export interface SftpHostKeyInfo {
@@ -57,6 +59,7 @@ export const createEmptyPane = (
filenameEncoding: "auto",
showHiddenFiles,
transferMutationToken: 0,
navHistory: createNavHistory(),
});
// File watch event types
+15 -1
View File
@@ -9,7 +9,8 @@ import { useSftpDirectoryListing } from "./useSftpDirectoryListing";
import { useSftpHostCredentials } from "./useSftpHostCredentials";
import { buildCacheKey, getSharedRemoteHostCache, setSharedRemoteHostCache } from "./sharedRemoteHostCache";
import { resolveRemoteSftpStartState } from "./sftpConnectStartPath";
import { normalizeSftpPaneNavigationPath } from "./utils";
import { isSameSftpPath, normalizeSftpPaneNavigationPath } from "./utils";
import { createNavHistory, resolveSftpConnectNavHistory } from "../../../domain/sftpNavHistory";
import {
setDirectoryCacheEntry,
type DirectoryListingCache,
@@ -967,6 +968,12 @@ export const useSftpConnections = ({
error: null,
connectionLogs: [],
filenameEncoding, // Reset encoding for new connection
navHistory: resolveSftpConnectNavHistory({
sameEndpointReconnect,
previousHistory: prev.navHistory,
startPath,
isSamePath: isSameSftpPath,
}),
}));
try {
@@ -1039,6 +1046,7 @@ export const useSftpConnections = ({
connectionLogs: [],
files: isReconnectAttempt ? prev.files : (sharedHostCache?.files ?? []),
filenameEncoding, // Reset encoding for new connection
navHistory: sameEndpointReconnect ? prev.navHistory : createNavHistory(),
}));
// Subscribe to SFTP connection progress events for auth logging
@@ -1280,6 +1288,12 @@ export const useSftpConnections = ({
loading: false,
reconnecting: false,
connectionLogs: [], // Clear after successful connect to avoid replay during navigation
navHistory: resolveSftpConnectNavHistory({
sameEndpointReconnect,
previousHistory: prev.navHistory,
startPath,
isSamePath: isSameSftpPath,
}),
}));
} catch (err) {
await settleFailedSftpConnectIfCurrent({
@@ -0,0 +1,423 @@
import assert from "node:assert/strict";
import test from "node:test";
import React from "react";
import { act, create, type ReactTestRenderer } from "react-test-renderer";
import type { SftpFileEntry } from "../../../domain/models";
import {
canGoBack,
canGoForward,
createNavHistory,
resolveSftpConnectNavHistory,
} from "../../../domain/sftpNavHistory";
import type { DirectoryListingCache } from "./directoryListingCache";
import type { SftpPane } from "./types";
import { useSftpPaneActions } from "./useSftpPaneActions";
function createConnectedPane(id: string, connectionId: string, initialPath: string, isLocal = false): SftpPane {
return {
id,
connection: {
id: connectionId,
hostId: isLocal ? "local" : "host-1",
hostLabel: isLocal ? "Local" : "Server",
isLocal,
status: "connected",
currentPath: initialPath,
homeDir: "/home/alice",
},
files: [],
loading: false,
reconnecting: false,
error: null,
connectionLogs: [],
selectedFiles: new Set(),
filter: "",
filenameEncoding: "auto",
showHiddenFiles: false,
transferMutationToken: 0,
navHistory: createNavHistory(initialPath),
};
}
function mountHarness(options?: {
leftInitialPath?: string;
rightInitialPath?: string;
failingPaths?: Set<string>;
dirCacheTtlMs?: number;
listDir?: (dirPath: string) => Promise<SftpFileEntry[]>;
}) {
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;
const leftPane = createConnectedPane("tab-left", "conn-left", options?.leftInitialPath ?? "/home/alice", false);
const rightPane = createConnectedPane("tab-right", "conn-right", options?.rightInitialPath ?? "/tmp", true);
const leftTabsRef = { current: { tabs: [leftPane], activeTabId: leftPane.id as string | null } };
const rightTabsRef = { current: { tabs: [rightPane], activeTabId: rightPane.id as string | null } };
const navSeqRef = { current: { left: 0, right: 0 } };
const dirCacheRef = { current: new Map() as DirectoryListingCache };
const sftpSessionsRef = { current: new Map<string, string>([["conn-left", "sftp-1"]]) };
const lastConnectedHostRef = { current: { left: null, right: null } };
const connectionCacheKeyMapRef = { current: new Map<string, string>() };
const failingPaths = options?.failingPaths ?? new Set<string>();
const listedPaths: string[] = [];
const getSideTabs = (side: "left" | "right") => (side === "left" ? leftTabsRef : rightTabsRef);
const getActivePane = (side: "left" | "right"): SftpPane | null => {
const ref = getSideTabs(side).current;
return ref.tabs.find((tab) => tab.id === ref.activeTabId) ?? null;
};
const updateTab = (side: "left" | "right", tabId: string, updater: (pane: SftpPane) => SftpPane) => {
const ref = getSideTabs(side);
ref.current = {
...ref.current,
tabs: ref.current.tabs.map((tab) => (tab.id === tabId ? updater(tab) : tab)),
};
};
const updateActiveTab = (side: "left" | "right", updater: (pane: SftpPane) => SftpPane) => {
const activeTabId = getSideTabs(side).current.activeTabId;
if (!activeTabId) return;
updateTab(side, activeTabId, updater);
};
const listDir = async (dirPath: string): Promise<SftpFileEntry[]> => {
listedPaths.push(dirPath);
if (options?.listDir) {
return options.listDir(dirPath);
}
if (failingPaths.has(dirPath)) {
throw new Error(`Permission denied: ${dirPath}`);
}
return [];
};
let actions: ReturnType<typeof useSftpPaneActions> | undefined;
let renderer: ReactTestRenderer | undefined;
function Probe() {
actions = useSftpPaneActions({
hosts: [],
getActivePane,
updateTab,
updateActiveTab,
leftTabsRef,
rightTabsRef,
navSeqRef,
dirCacheRef,
sftpSessionsRef,
lastConnectedHostRef,
connectionCacheKeyMapRef,
makeCacheKey: (connectionId, dirPath, encoding) => `${connectionId}::${encoding || "auto"}::${dirPath}`,
clearCacheForConnection: (connectionId) => {
for (const key of dirCacheRef.current.keys()) {
if (key.startsWith(`${connectionId}::`)) dirCacheRef.current.delete(key);
}
},
listLocalFiles: listDir,
listRemoteFiles: (_sftpId, dirPath) => listDir(dirPath),
handleSessionError: () => {},
releaseConnection: async () => {},
isSessionError: () => false,
clearSelectionsExcept: () => {},
dirCacheTtlMs: options?.dirCacheTtlMs ?? 10_000,
});
return null;
}
return {
get actions() {
assert.ok(actions);
return actions;
},
getPane: (side: "left" | "right") => {
const pane = getActivePane(side);
assert.ok(pane);
return pane;
},
failingPaths,
listedPaths,
dirCacheRef,
updateTab,
render: async () => {
await act(async () => {
renderer = create(React.createElement(Probe));
});
},
unmount: async () => {
await act(async () => {
renderer?.unmount();
});
renderer = undefined;
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = previousActFlag;
},
};
}
test("useSftpPaneActions records navigations, traverses back/forward without duplicates, and truncates on branch", async () => {
const harness = mountHarness();
try {
await harness.render();
assert.equal(canGoBack(harness.getPane("left").navHistory!), false);
assert.equal(canGoForward(harness.getPane("left").navHistory!), false);
assert.equal(await harness.actions.navigateTo("left", "/var"), "reached");
assert.equal(await harness.actions.navigateTo("left", "/var/log"), "reached");
// Navigating to the same current path is a no-op in history
assert.equal(await harness.actions.navigateTo("left", "/var/log"), "reached");
assert.deepEqual(harness.getPane("left").navHistory?.entries, ["/home/alice", "/var", "/var/log"]);
assert.equal(harness.getPane("left").navHistory?.index, 2);
// navigateUp pushes parent directory onto history
await harness.actions.navigateUp("left");
assert.equal(harness.getPane("left").connection?.currentPath, "/var");
assert.deepEqual(harness.getPane("left").navHistory?.entries, ["/home/alice", "/var", "/var/log", "/var"]);
assert.equal(harness.getPane("left").navHistory?.index, 3);
// Back moves pointer without pushing duplicates or clearing forward entries
assert.equal(await harness.actions.navigateBack("left"), "reached");
assert.equal(harness.getPane("left").connection?.currentPath, "/var/log");
assert.equal(harness.getPane("left").navHistory?.index, 2);
assert.equal(canGoForward(harness.getPane("left").navHistory!), true);
assert.equal(await harness.actions.navigateBack("left"), "reached");
assert.equal(harness.getPane("left").connection?.currentPath, "/var");
assert.equal(harness.getPane("left").navHistory?.index, 1);
// Refresh preserves forward stack
await harness.actions.refresh("left");
assert.deepEqual(harness.getPane("left").navHistory?.entries, ["/home/alice", "/var", "/var/log", "/var"]);
assert.equal(harness.getPane("left").navHistory?.index, 1);
assert.equal(canGoForward(harness.getPane("left").navHistory!), true);
// Forward steps ahead without duplicating
assert.equal(await harness.actions.navigateForward("left"), "reached");
assert.equal(harness.getPane("left").connection?.currentPath, "/var/log");
assert.equal(harness.getPane("left").navHistory?.index, 2);
// New navigation from mid-stack truncates forward entries
assert.equal(await harness.actions.navigateTo("left", "/etc"), "reached");
assert.deepEqual(harness.getPane("left").navHistory?.entries, ["/home/alice", "/var", "/var/log", "/etc"]);
assert.equal(harness.getPane("left").navHistory?.index, 3);
assert.equal(canGoForward(harness.getPane("left").navHistory!), false);
// Right pane history stays independent
assert.deepEqual(harness.getPane("right").navHistory?.entries, ["/tmp"]);
assert.equal(harness.getPane("right").navHistory?.index, 0);
} finally {
await harness.unmount();
}
});
test("useSftpPaneActions preserves history pointer and forward stack when navigation fails", async () => {
const failingPaths = new Set<string>(["/forbidden"]);
// Disable cache hits so back/forward also exercises async failure rollback
const harness = mountHarness({ failingPaths, dirCacheTtlMs: 0 });
try {
await harness.render();
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);
// Failed normal navigation must NOT truncate forward entry (/var/log) or push /forbidden
assert.equal(await harness.actions.navigateTo("left", "/forbidden"), "failed");
assert.equal(harness.getPane("left").connection?.currentPath, "/var");
assert.deepEqual(harness.getPane("left").navHistory?.entries, ["/home/alice", "/var", "/var/log"]);
assert.equal(harness.getPane("left").navHistory?.index, 1);
assert.equal(canGoForward(harness.getPane("left").navHistory!), true);
// Failed Back navigation must NOT decrement pointer
harness.failingPaths.add("/home/alice");
assert.equal(await harness.actions.navigateBack("left"), "failed");
assert.equal(harness.getPane("left").connection?.currentPath, "/var");
assert.deepEqual(harness.getPane("left").navHistory?.entries, ["/home/alice", "/var", "/var/log"]);
assert.equal(harness.getPane("left").navHistory?.index, 1);
// Failed Forward navigation must NOT increment pointer
harness.failingPaths.add("/var/log");
assert.equal(await harness.actions.navigateForward("left"), "failed");
assert.equal(harness.getPane("left").connection?.currentPath, "/var");
assert.deepEqual(harness.getPane("left").navHistory?.entries, ["/home/alice", "/var", "/var/log"]);
assert.equal(harness.getPane("left").navHistory?.index, 1);
// Once /var/log is readable again, Forward still works cleanly
harness.failingPaths.delete("/var/log");
assert.equal(await harness.actions.navigateForward("left"), "reached");
assert.equal(harness.getPane("left").connection?.currentPath, "/var/log");
assert.equal(harness.getPane("left").navHistory?.index, 2);
} finally {
await harness.unmount();
}
});
test("host switch resets navigation history so previous host paths cannot be navigated via Back", async () => {
const harness = mountHarness();
try {
await harness.render();
assert.equal(await harness.actions.navigateTo("left", "/var"), "reached");
assert.equal(await harness.actions.navigateTo("left", "/etc"), "reached");
assert.equal(canGoBack(harness.getPane("left").navHistory!), true);
// Simulate switching connection on the same tab (sameEndpointReconnect = false)
harness.updateTab("left", "tab-left", (prev) => ({
...prev,
connection: prev.connection
? { ...prev.connection, id: "conn-host-2", hostId: "host-2", currentPath: "/srv/app" }
: null,
navHistory: resolveSftpConnectNavHistory({
sameEndpointReconnect: false,
previousHistory: prev.navHistory,
startPath: "/srv/app",
}),
}));
assert.deepEqual(harness.getPane("left").navHistory?.entries, ["/srv/app"]);
assert.equal(harness.getPane("left").navHistory?.index, 0);
assert.equal(canGoBack(harness.getPane("left").navHistory!), false);
assert.equal(canGoForward(harness.getPane("left").navHistory!), false);
assert.equal(await harness.actions.navigateBack("left"), "aborted");
} finally {
await harness.unmount();
}
});
function createDeferred<T>() {
let resolve!: (value: T) => void;
let reject!: (reason?: unknown) => void;
const promise = new Promise<T>((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<typeof createDeferred<SftpFileEntry[]>> }> = [];
const harness = mountHarness({
dirCacheTtlMs: 0,
listDir: (dirPath) => {
if (dirPath === "/slow" || dirPath === "/slow-fail") {
const deferred = createDeferred<SftpFileEntry[]>();
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<typeof createDeferred<SftpFileEntry[]>> }> = [];
let interceptTarget: string | null = null;
const harness = mountHarness({
dirCacheTtlMs: 0,
listDir: (dirPath) => {
if (interceptTarget && dirPath === interceptTarget) {
const deferred = createDeferred<SftpFileEntry[]>();
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();
}
});
+93 -1
View File
@@ -24,6 +24,15 @@ import {
setDirectoryCacheEntry,
type DirectoryListingCache,
} from "./directoryListingCache";
import {
applySftpNavHistoryTransition,
createNavHistory,
goBack,
goForward,
resolveSftpEffectiveNavHistoryMode,
type PendingSftpNavHistoryTransition,
type SftpNavHistoryTransitionMode,
} from "../../../domain/sftpNavHistory";
/** Shared empty set for navigation resets — never mutate this. */
const EMPTY_SET = new Set<string>();
@@ -58,10 +67,14 @@ export type SftpNavigateOptions = {
shouldApply?: () => boolean;
/** Restore the previous listing without showing a pane error. */
quiet?: boolean;
/** Controls how a successful navigation updates per-pane history. Defaults to "push". */
historyMode?: SftpNavHistoryTransitionMode;
};
interface UseSftpPaneActionsResult {
navigateTo: (side: "left" | "right", path: string, options?: SftpNavigateOptions) => Promise<SftpNavigateResult>;
navigateBack: (side: "left" | "right") => Promise<SftpNavigateResult>;
navigateForward: (side: "left" | "right") => Promise<SftpNavigateResult>;
refresh: (side: "left" | "right", options?: { tabId?: string }) => Promise<void>;
navigateUp: (side: "left" | "right") => Promise<void>;
openEntry: (side: "left" | "right", entry: SftpFileEntry) => Promise<void>;
@@ -151,6 +164,12 @@ export const useSftpPaneActions = ({
new Map<string, { connectionId: string; path: string; files: SftpFileEntry[]; selectedFiles: Set<string>; 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<string, PendingSftpNavHistoryTransition>());
const navigateTo = useCallback(
async (
side: "left" | "right",
@@ -183,6 +202,14 @@ export const useSftpPaneActions = ({
);
const connectionId = pane.connection.id;
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);
@@ -197,6 +224,7 @@ export const useSftpPaneActions = ({
cached.files
) {
tabNavSeqRef.current.set(targetTabId, requestId);
pendingNavHistoryRef.current.delete(targetTabId);
lastConfirmedRef.current.set(targetTabId, {
connectionId,
path: normalizedPath,
@@ -214,6 +242,13 @@ export const useSftpPaneActions = ({
error: null,
selectedFiles: EMPTY_SET,
filter: clearFilterForPathChange ? "" : prev.filter,
navHistory: applySftpNavHistoryTransition({
history: prev.navHistory,
currentPath: prev.connection?.currentPath,
targetPath: normalizedPath,
mode: historyMode,
isSamePath: isSameSftpPath,
}),
}));
if (!pane.connection.isLocal) {
// Use hostId as the shared cache key — this is safe because the
@@ -252,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;
@@ -262,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 {
@@ -276,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.
@@ -305,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.
@@ -331,6 +382,7 @@ export const useSftpPaneActions = ({
restoreConfirmedStateIfCurrent();
return "aborted";
}
clearPendingNavHistoryIfCurrent();
await releaseConnection(pane.connection.id);
if (options?.tabId) {
updateTab(side, targetTabId, (prev) => ({
@@ -368,6 +420,8 @@ export const useSftpPaneActions = ({
timestamp: Date.now(),
}, { ttlMs: dirCacheTtlMs });
clearPendingNavHistoryIfCurrent();
lastConfirmedRef.current.set(targetTabId, {
connectionId,
path: normalizedPath,
@@ -385,6 +439,13 @@ export const useSftpPaneActions = ({
loading: false,
selectedFiles: EMPTY_SET,
filter: clearFilterForPathChange ? "" : prev.filter,
navHistory: applySftpNavHistoryTransition({
history: prev.navHistory,
currentPath: previousPath,
targetPath: normalizedPath,
mode: historyMode,
isSamePath: isSameSftpPath,
}),
}));
if (!pane.connection.isLocal) {
setSharedRemoteHostCache(getActivePaneCacheKey(side, pane.connection.hostId, pane.connection.id), {
@@ -407,6 +468,7 @@ export const useSftpPaneActions = ({
restoreConfirmedStateIfCurrent();
return "aborted";
}
clearPendingNavHistoryIfCurrent();
let navigationFailed = false;
updateTab(side, targetTabId, (prev) => {
if (prev.connection?.id !== connectionId) {
@@ -480,7 +542,11 @@ export const useSftpPaneActions = ({
}
return;
}
await navigateTo(side, pane.connection.currentPath, { force: true, tabId: options?.tabId });
await navigateTo(side, pane.connection.currentPath, {
force: true,
tabId: options?.tabId,
historyMode: "none",
});
} else if (!pane?.connection && pane?.error) {
// For background tabs, don't trigger reconnection (it operates on
// the active tab). Just leave the error state for the user to see
@@ -504,6 +570,30 @@ export const useSftpPaneActions = ({
[getActivePane, leftTabsRef, rightTabsRef, navigateTo, updateActiveTab, lastConnectedHostRef, sftpSessionsRef],
);
const navigateBack = useCallback(
async (side: "left" | "right"): Promise<SftpNavigateResult> => {
const pane = getActivePane(side);
if (!pane?.connection) return "aborted";
const history = pane.navHistory ?? createNavHistory(pane.connection.currentPath);
const step = goBack(history);
if (!step.path) return "aborted";
return navigateTo(side, step.path, { historyMode: "back" });
},
[getActivePane, navigateTo],
);
const navigateForward = useCallback(
async (side: "left" | "right"): Promise<SftpNavigateResult> => {
const pane = getActivePane(side);
if (!pane?.connection) return "aborted";
const history = pane.navHistory ?? createNavHistory(pane.connection.currentPath);
const step = goForward(history);
if (!step.path) return "aborted";
return navigateTo(side, step.path, { historyMode: "forward" });
},
[getActivePane, navigateTo],
);
const navigateUp = useCallback(
async (side: "left" | "right") => {
const pane = getActivePane(side);
@@ -1060,6 +1150,8 @@ export const useSftpPaneActions = ({
return {
navigateTo,
navigateBack,
navigateForward,
refresh,
navigateUp,
openEntry,
+7 -1
View File
@@ -466,6 +466,8 @@ export const useSftpState = (
const {
navigateTo,
navigateBack,
navigateForward,
refresh,
navigateUp,
openEntry,
@@ -523,7 +525,7 @@ export const useSftpState = (
setTimeout(() => {
const refreshedPane = getActivePane(side);
if (refreshedPane?.connection) {
navigateTo(side, refreshedPane.connection.currentPath, { force: true });
navigateTo(side, refreshedPane.connection.currentPath, { force: true, historyMode: "none" });
}
}, 0);
}
@@ -781,6 +783,8 @@ export const useSftpState = (
connect,
disconnect,
navigateTo,
navigateBack,
navigateForward,
navigateUp,
refresh,
openEntry,
@@ -853,6 +857,8 @@ export const useSftpState = (
connect: (...args: Parameters<typeof connect>) => methodsRef.current.connect(...args),
disconnect: (...args: Parameters<typeof disconnect>) => methodsRef.current.disconnect(...args),
navigateTo: (...args: Parameters<typeof navigateTo>) => methodsRef.current.navigateTo(...args),
navigateBack: (...args: Parameters<typeof navigateBack>) => methodsRef.current.navigateBack(...args),
navigateForward: (...args: Parameters<typeof navigateForward>) => methodsRef.current.navigateForward(...args),
navigateUp: (...args: Parameters<typeof navigateUp>) => methodsRef.current.navigateUp(...args),
refresh: (...args: Parameters<typeof refresh>) => methodsRef.current.refresh(...args),
openEntry: (...args: Parameters<typeof openEntry>) => methodsRef.current.openEntry(...args),
+2
View File
@@ -35,6 +35,8 @@ export interface SftpPaneCallbacks {
onDisconnect: () => Promise<boolean>;
onPrepareSelection: () => void;
onNavigateTo: (path: string) => void;
onNavigateBack: () => void;
onNavigateForward: () => void;
onNavigateUp: () => void;
onRefresh: () => void;
onRefreshTab: (tabId: string) => void;
@@ -314,3 +314,166 @@ test("inline bookmark actions navigate and confirm current-path removal", async
}
}
});
test("path toolbar Back and Forward buttons invoke navigation callbacks only when enabled", async () => {
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div></body></html>', {
pretendToBeVisual: true,
url: "http://localhost",
});
const window = dom.window;
const previousGlobals = new Map<string, PropertyDescriptor | undefined>();
const installGlobal = (key: string, value: unknown) => {
previousGlobals.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
Object.defineProperty(globalThis, key, {
configurable: true,
writable: true,
value,
});
};
class ResizeObserverStub {
observe() {}
unobserve() {}
disconnect() {}
}
installGlobal("window", window);
installGlobal("document", window.document);
installGlobal("navigator", window.navigator);
installGlobal("HTMLElement", window.HTMLElement);
installGlobal("HTMLInputElement", window.HTMLInputElement);
installGlobal("HTMLTextAreaElement", window.HTMLTextAreaElement);
installGlobal("Element", window.Element);
installGlobal("SVGElement", window.SVGElement);
installGlobal("Node", window.Node);
installGlobal("NodeFilter", window.NodeFilter);
installGlobal("MutationObserver", window.MutationObserver);
installGlobal("CustomEvent", window.CustomEvent);
installGlobal("Event", window.Event);
installGlobal("StorageEvent", window.StorageEvent);
installGlobal("localStorage", window.localStorage);
installGlobal("sessionStorage", window.sessionStorage);
installGlobal("getComputedStyle", window.getComputedStyle.bind(window));
installGlobal("requestAnimationFrame", window.requestAnimationFrame.bind(window));
installGlobal("cancelAnimationFrame", window.cancelAnimationFrame.bind(window));
installGlobal("ResizeObserver", ResizeObserverStub);
installGlobal("IS_REACT_ACT_ENVIRONMENT", true);
const { default: React, act } = await import("react");
const { createRoot } = await import("react-dom/client");
const { I18nProvider } = await import("../../application/i18n/I18nProvider.tsx");
const { SftpPaneToolbar } = await import("./SftpPaneToolbar.tsx");
const rootNode = window.document.getElementById("root");
assert.ok(rootNode);
const root = createRoot(rootNode);
let backCalls = 0;
let forwardCalls = 0;
const renderWithHistory = async (entries: string[], index: number) => {
await act(async () => {
const toolbar = React.createElement(SftpPaneToolbar, {
t: (key) => ({
"sftp.goBack": "Go back",
"sftp.goForward": "Go forward",
}[key] ?? key),
pane: {
id: "pane-1",
connection: {
id: "conn-1",
hostId: "host-1",
hostLabel: "Example",
status: "connected",
currentPath: entries[index] ?? "/",
homeDir: "/home/app",
isLocal: false,
},
files: [],
loading: false,
reconnecting: false,
error: null,
connectionLogs: [],
selectedFiles: new Set<string>(),
filter: "",
filenameEncoding: "auto",
showHiddenFiles: false,
transferMutationToken: 0,
navHistory: { entries, index, maxEntries: 50 },
},
onNavigateTo: () => {},
onNavigateBack: () => {
backCalls += 1;
},
onNavigateForward: () => {
forwardCalls += 1;
},
onSetFilter: () => {},
onSetFilenameEncoding: () => {},
onRefresh: () => {},
showFilterBar: false,
setShowFilterBar: () => {},
filterInputRef: { current: null },
isEditingPath: false,
editingPathValue: "",
setEditingPathValue: () => {},
setShowPathSuggestions: () => {},
showPathSuggestions: false,
setPathSuggestionIndex: () => {},
pathSuggestions: [],
pathSuggestionIndex: -1,
pathInputRef: { current: null },
pathDropdownRef: { current: null },
handlePathBlur: () => {},
handlePathKeyDown: () => {},
handlePathDoubleClick: () => {},
handlePathSubmit: () => {},
getNextUntitledName: () => "untitled",
setNewFileName: () => {},
setFileNameError: () => {},
setShowNewFileDialog: () => {},
setShowNewFolderDialog: () => {},
setNewFolderName: () => {},
bookmarks: [],
isCurrentPathBookmarked: false,
onToggleBookmark: () => {},
onAddGlobalBookmark: () => {},
isCurrentPathGlobalBookmarked: false,
onNavigateToBookmark: () => {},
onDeleteBookmark: () => {},
showHiddenFiles: false,
onToggleShowHiddenFiles: () => {},
viewMode: "list",
onSetViewMode: () => {},
});
root.render(React.createElement(I18nProvider, { locale: "en", children: toolbar }));
});
};
try {
await renderWithHistory(["/home/app"], 0);
const backBtn = () => window.document.querySelector<HTMLButtonElement>('button[aria-label="Go back"]');
const forwardBtn = () => window.document.querySelector<HTMLButtonElement>('button[aria-label="Go forward"]');
assert.equal(backBtn()?.disabled, true);
assert.equal(forwardBtn()?.disabled, true);
await renderWithHistory(["/home/app", "/var", "/etc"], 1);
assert.equal(backBtn()?.disabled, false);
assert.equal(forwardBtn()?.disabled, false);
await act(async () => backBtn()!.click());
await act(async () => forwardBtn()!.click());
assert.equal(backCalls, 1);
assert.equal(forwardCalls, 1);
await renderWithHistory(["/home/app", "/var", "/etc"], 2);
assert.equal(backBtn()?.disabled, false);
assert.equal(forwardBtn()?.disabled, true);
} finally {
await act(async () => root.unmount());
dom.window.close();
for (const [key, descriptor] of previousGlobals) {
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
else delete (globalThis as Record<string, unknown>)[key];
}
}
});
+92
View File
@@ -600,3 +600,95 @@ test("bookmark list renders saved paths as selectable rows", () => {
assert.match(markup, /aria-label="Remove bookmark"/);
assert.match(markup, /focus-visible:opacity-100/);
});
test("toolbar renders Back and Forward buttons disabled when history is empty and enables them from pane navHistory", () => {
const basePane: SftpPane = {
id: "pane-1",
connection: {
id: "conn-1",
hostId: "host-1",
hostLabel: "Example",
status: "connected",
currentPath: "/var",
homeDir: "/home/app",
isLocal: false,
},
files: [],
loading: false,
reconnecting: false,
error: null,
connectionLogs: [],
selectedFiles: new Set(),
filter: "",
filenameEncoding: "auto",
showHiddenFiles: false,
transferMutationToken: 0,
};
const renderWithPane = (pane: SftpPane) =>
renderToStaticMarkup(
React.createElement(SftpPaneToolbar, {
t: (key: string) => ({
"sftp.goBack": "Go back",
"sftp.goForward": "Go forward",
}[key] ?? key),
pane,
onNavigateTo: () => {},
onNavigateBack: () => {},
onNavigateForward: () => {},
onSetFilter: () => {},
onSetFilenameEncoding: () => {},
onRefresh: () => {},
showFilterBar: false,
setShowFilterBar: () => {},
filterInputRef: { current: null },
isEditingPath: false,
editingPathValue: "",
setEditingPathValue: () => {},
setShowPathSuggestions: () => {},
showPathSuggestions: false,
setPathSuggestionIndex: () => {},
pathSuggestions: [],
pathSuggestionIndex: -1,
pathInputRef: { current: null },
pathDropdownRef: { current: null },
handlePathBlur: () => {},
handlePathKeyDown: () => {},
handlePathDoubleClick: () => {},
handlePathSubmit: () => {},
getNextUntitledName: () => "untitled",
setNewFileName: () => {},
setFileNameError: () => {},
setShowNewFileDialog: () => {},
setShowNewFolderDialog: () => {},
setNewFolderName: () => {},
bookmarks: [],
isCurrentPathBookmarked: false,
onToggleBookmark: () => {},
onAddGlobalBookmark: () => {},
isCurrentPathGlobalBookmarked: false,
onNavigateToBookmark: () => {},
onDeleteBookmark: () => {},
showHiddenFiles: false,
onToggleShowHiddenFiles: () => {},
viewMode: "list",
onSetViewMode: () => {},
}),
);
const emptyMarkup = renderWithPane({
...basePane,
navHistory: { entries: ["/var"], index: 0, maxEntries: 50 },
});
assert.match(emptyMarkup, /aria-label="Go back"[^>]*disabled/);
assert.match(emptyMarkup, /aria-label="Go forward"[^>]*disabled/);
const midMarkup = renderWithPane({
...basePane,
navHistory: { entries: ["/home/app", "/var", "/etc"], index: 1, maxEntries: 50 },
});
assert.match(midMarkup, /aria-label="Go back"/);
assert.doesNotMatch(midMarkup, /aria-label="Go back"[^>]*disabled/);
assert.match(midMarkup, /aria-label="Go forward"/);
assert.doesNotMatch(midMarkup, /aria-label="Go forward"[^>]*disabled/);
});
+58 -3
View File
@@ -1,5 +1,6 @@
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { ArrowDown, ArrowUp, Bookmark, Check, ClipboardCopy, Eye, EyeOff, FilePlus, Folder, FolderPlus, FolderSync, Globe, GripVertical, Home, Languages, List, ListTree, Pencil, RefreshCw, Rows3, Search, Terminal, TerminalSquare, Trash2, X } from "lucide-react";
import { ArrowDown, ArrowLeft, ArrowRight, ArrowUp, Bookmark, Check, ClipboardCopy, Eye, EyeOff, FilePlus, Folder, FolderPlus, FolderSync, Globe, GripVertical, Home, Languages, List, ListTree, Pencil, RefreshCw, Rows3, Search, Terminal, TerminalSquare, Trash2, X } from "lucide-react";
import { canGoBack, canGoForward } from "../../domain/sftpNavHistory";
import {
getNextSftpListDensity,
getSftpListDensityToggleLabelKey,
@@ -191,6 +192,8 @@ interface SftpPaneToolbarProps {
t: (key: string, params?: Record<string, unknown>) => string;
pane: SftpPane;
onNavigateTo: (path: string) => void;
onNavigateBack?: () => void;
onNavigateForward?: () => void;
onSetFilter: (value: string) => void;
onSetFilenameEncoding: (encoding: SftpFilenameEncoding) => void;
onRefresh: () => void;
@@ -493,6 +496,8 @@ export const SftpPaneToolbar: React.FC<SftpPaneToolbarProps> = React.memo(({
t,
pane,
onNavigateTo,
onNavigateBack,
onNavigateForward,
onSetFilter,
onSetFilenameEncoding,
onRefresh,
@@ -665,6 +670,17 @@ export const SftpPaneToolbar: React.FC<SftpPaneToolbarProps> = React.memo(({
}, [displayPath, t]);
const isRemote = !pane.connection?.isLocal;
const isNavHistoryInteractive = Boolean(
pane.connection
&& !pane.reconnecting
&& pane.connection.status !== "connecting",
);
const canNavigateBack = Boolean(
isNavHistoryInteractive && onNavigateBack && pane.navHistory && canGoBack(pane.navHistory),
);
const canNavigateForward = Boolean(
isNavHistoryInteractive && onNavigateForward && pane.navHistory && canGoForward(pane.navHistory),
);
const viewModeToggleTarget = getSftpViewModeToggleTarget(viewMode);
const viewModeToggleLabel = t(viewModeToggleTarget.labelKey);
const listDensityToggleTarget = getNextSftpListDensity(listDensity);
@@ -1330,10 +1346,49 @@ export const SftpPaneToolbar: React.FC<SftpPaneToolbarProps> = React.memo(({
data-section="terminal-sftp-toolbar"
>
<div
className="h-7 px-2 flex items-center min-w-0"
className="h-7 px-2 flex items-center gap-1 min-w-0"
data-section="terminal-sftp-path-row"
>
{pathEditor}
<div
className="flex items-center gap-0.5 shrink-0"
data-section="terminal-sftp-nav-history"
>
<Tooltip>
<TooltipTrigger asChild>
<Button
type="button"
variant="ghost"
size="icon"
className="h-5 w-5 shrink-0 text-muted-foreground hover:text-foreground"
aria-label={t("sftp.goBack")}
disabled={!canNavigateBack}
onClick={onNavigateBack}
>
<ArrowLeft size={13} />
</Button>
</TooltipTrigger>
<TooltipContent>{t("sftp.goBack")}</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<Button
type="button"
variant="ghost"
size="icon"
className="h-5 w-5 shrink-0 text-muted-foreground hover:text-foreground"
aria-label={t("sftp.goForward")}
disabled={!canNavigateForward}
onClick={onNavigateForward}
>
<ArrowRight size={13} />
</Button>
</TooltipTrigger>
<TooltipContent>{t("sftp.goForward")}</TooltipContent>
</Tooltip>
</div>
<div className="flex-1 min-w-0">
{pathEditor}
</div>
</div>
<div
+2
View File
@@ -580,6 +580,8 @@ const SftpPaneViewInner: React.FC<SftpPaneViewProps> = ({
t={t}
pane={pane}
onNavigateTo={callbacks.onNavigateTo}
onNavigateBack={callbacks.onNavigateBack}
onNavigateForward={callbacks.onNavigateForward}
onSetFilter={callbacks.onSetFilter}
onSetFilenameEncoding={callbacks.onSetFilenameEncoding}
onRefresh={handleRefresh}
@@ -33,6 +33,10 @@ interface UseSftpViewPaneActionsResult {
onPrepareSelectionRight: () => void;
onNavigateToLeft: (path: string) => void;
onNavigateToRight: (path: string) => void;
onNavigateBackLeft: () => void;
onNavigateBackRight: () => void;
onNavigateForwardLeft: () => void;
onNavigateForwardRight: () => void;
onNavigateUpLeft: () => void;
onNavigateUpRight: () => void;
onRefreshLeft: () => void;
@@ -255,6 +259,18 @@ export const useSftpViewPaneActions = ({
(path: string) => sftpRef.current.navigateTo("right", path),
[sftpRef],
);
const onNavigateBackLeft = useCallback(() => {
void sftpRef.current.navigateBack("left");
}, [sftpRef]);
const onNavigateBackRight = useCallback(() => {
void sftpRef.current.navigateBack("right");
}, [sftpRef]);
const onNavigateForwardLeft = useCallback(() => {
void sftpRef.current.navigateForward("left");
}, [sftpRef]);
const onNavigateForwardRight = useCallback(() => {
void sftpRef.current.navigateForward("right");
}, [sftpRef]);
const onNavigateUpLeft = useCallback(() => sftpRef.current.navigateUp("left"), [sftpRef]);
const onNavigateUpRight = useCallback(() => sftpRef.current.navigateUp("right"), [sftpRef]);
const onRefreshLeft = useCallback(() => sftpRef.current.refresh("left"), [sftpRef]);
@@ -403,6 +419,10 @@ export const useSftpViewPaneActions = ({
onPrepareSelectionRight,
onNavigateToLeft,
onNavigateToRight,
onNavigateBackLeft,
onNavigateBackRight,
onNavigateForwardLeft,
onNavigateForwardRight,
onNavigateUpLeft,
onNavigateUpRight,
onRefreshLeft,
@@ -132,6 +132,8 @@ export const useSftpViewPaneCallbacks = ({
onDisconnect: paneActions.onDisconnectLeft,
onPrepareSelection: paneActions.onPrepareSelectionLeft,
onNavigateTo: paneActions.onNavigateToLeft,
onNavigateBack: paneActions.onNavigateBackLeft,
onNavigateForward: paneActions.onNavigateForwardLeft,
onNavigateUp: paneActions.onNavigateUpLeft,
onRefresh: paneActions.onRefreshLeft,
onRefreshTab: paneActions.onRefreshTabLeft,
@@ -177,6 +179,8 @@ export const useSftpViewPaneCallbacks = ({
onDisconnect: paneActions.onDisconnectRight,
onPrepareSelection: paneActions.onPrepareSelectionRight,
onNavigateTo: paneActions.onNavigateToRight,
onNavigateBack: paneActions.onNavigateBackRight,
onNavigateForward: paneActions.onNavigateForwardRight,
onNavigateUp: paneActions.onNavigateUpRight,
onRefresh: paneActions.onRefreshRight,
onRefreshTab: paneActions.onRefreshTabRight,
+290
View File
@@ -0,0 +1,290 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
applySftpNavHistoryTransition,
canGoBack,
canGoForward,
createNavHistory,
DEFAULT_SFTP_NAV_HISTORY_MAX_ENTRIES,
getCurrentNavPath,
goBack,
goForward,
peekBackPath,
peekForwardPath,
pushNavHistory,
resetNavHistory,
resolveSftpConnectNavHistory,
resolveSftpEffectiveNavHistoryMode,
} from "./sftpNavHistory.ts";
test("createNavHistory initializes empty or with an initial path", () => {
const empty = createNavHistory();
assert.deepEqual(empty.entries, []);
assert.equal(empty.index, -1);
assert.equal(empty.maxEntries, DEFAULT_SFTP_NAV_HISTORY_MAX_ENTRIES);
assert.equal(getCurrentNavPath(empty), null);
assert.equal(canGoBack(empty), false);
assert.equal(canGoForward(empty), false);
assert.equal(peekBackPath(empty), null);
assert.equal(peekForwardPath(empty), null);
const seeded = createNavHistory("/home/alice");
assert.deepEqual(seeded.entries, ["/home/alice"]);
assert.equal(seeded.index, 0);
assert.equal(getCurrentNavPath(seeded), "/home/alice");
assert.equal(canGoBack(seeded), false);
assert.equal(canGoForward(seeded), false);
const fallbackMax = createNavHistory("/home", 0);
assert.equal(fallbackMax.maxEntries, DEFAULT_SFTP_NAV_HISTORY_MAX_ENTRIES);
const customMax = createNavHistory("/home", 3.9);
assert.equal(customMax.maxEntries, 3);
});
test("pushNavHistory appends distinct paths and ignores empty or duplicate current paths", () => {
const h0 = createNavHistory("/a");
const h1 = pushNavHistory(h0, "/b");
const h2 = pushNavHistory(h1, "/c");
// Immutability check
assert.deepEqual(h0.entries, ["/a"]);
assert.deepEqual(h2.entries, ["/a", "/b", "/c"]);
assert.equal(h2.index, 2);
// Duplicate current path is a no-op returning the same reference
assert.equal(pushNavHistory(h2, "/c"), h2);
// Empty path is a no-op
assert.equal(pushNavHistory(h2, ""), h2);
// Custom comparator dedups case-insensitive paths (e.g. Windows)
const win = createNavHistory("C:\\Users");
const sameWin = pushNavHistory(
win,
"c:\\users",
(a, b) => a.toLowerCase() === b.toLowerCase(),
);
assert.equal(sameWin, win);
});
test("goBack and goForward traverse history without mutating or losing forward entries", () => {
let history = createNavHistory("/a");
history = pushNavHistory(history, "/b");
history = pushNavHistory(history, "/c");
assert.equal(canGoBack(history), true);
assert.equal(canGoForward(history), false);
assert.equal(peekBackPath(history), "/b");
const back1 = goBack(history);
assert.equal(back1.path, "/b");
assert.equal(back1.history.index, 1);
assert.deepEqual(back1.history.entries, ["/a", "/b", "/c"]);
assert.equal(canGoBack(back1.history), true);
assert.equal(canGoForward(back1.history), true);
assert.equal(peekBackPath(back1.history), "/a");
assert.equal(peekForwardPath(back1.history), "/c");
// Pushing the current path while mid-history must NOT wipe forward entries
assert.equal(pushNavHistory(back1.history, "/b"), back1.history);
const back2 = goBack(back1.history);
assert.equal(back2.path, "/a");
assert.equal(back2.history.index, 0);
assert.equal(canGoBack(back2.history), false);
assert.equal(canGoForward(back2.history), true);
// Going back past the start is a no-op
const back3 = goBack(back2.history);
assert.equal(back3.path, null);
assert.equal(back3.history, back2.history);
const fwd1 = goForward(back2.history);
assert.equal(fwd1.path, "/b");
assert.equal(fwd1.history.index, 1);
const fwd2 = goForward(fwd1.history);
assert.equal(fwd2.path, "/c");
assert.equal(fwd2.history.index, 2);
assert.equal(canGoForward(fwd2.history), false);
// Going forward past the end is a no-op
const fwd3 = goForward(fwd2.history);
assert.equal(fwd3.path, null);
assert.equal(fwd3.history, fwd2.history);
});
test("pushNavHistory truncates forward entries after stepping back", () => {
let history = createNavHistory("/a");
history = pushNavHistory(history, "/b");
history = pushNavHistory(history, "/c");
history = pushNavHistory(history, "/d");
const stepped = goBack(goBack(history).history).history;
assert.equal(getCurrentNavPath(stepped), "/b");
assert.equal(canGoForward(stepped), true);
const branched = pushNavHistory(stepped, "/x");
assert.deepEqual(branched.entries, ["/a", "/b", "/x"]);
assert.equal(branched.index, 2);
assert.equal(canGoBack(branched), true);
assert.equal(canGoForward(branched), false);
});
test("pushNavHistory enforces bounded maxEntries capacity", () => {
let history = createNavHistory("/p0", 3);
history = pushNavHistory(history, "/p1");
history = pushNavHistory(history, "/p2");
history = pushNavHistory(history, "/p3");
history = pushNavHistory(history, "/p4");
assert.deepEqual(history.entries, ["/p2", "/p3", "/p4"]);
assert.equal(history.index, 2);
// Default 50-entry bound
let defaultBounded = createNavHistory("/dir-0");
for (let i = 1; i <= 75; i += 1) {
defaultBounded = pushNavHistory(defaultBounded, `/dir-${i}`);
}
assert.equal(defaultBounded.entries.length, DEFAULT_SFTP_NAV_HISTORY_MAX_ENTRIES);
assert.equal(defaultBounded.entries[0], "/dir-26");
assert.equal(defaultBounded.entries[49], "/dir-75");
assert.equal(defaultBounded.index, 49);
});
test("resetNavHistory clears previous history and starts fresh at the new path", () => {
const reset = resetNavHistory("/var/www");
assert.deepEqual(reset.entries, ["/var/www"]);
assert.equal(reset.index, 0);
assert.equal(canGoBack(reset), false);
assert.equal(canGoForward(reset), false);
const cleared = resetNavHistory(null);
assert.deepEqual(cleared.entries, []);
assert.equal(cleared.index, -1);
});
test("applySftpNavHistoryTransition handles push, back, forward, none, and fallback", () => {
// Uninitialized pane history seeds from currentPath before pushing target
const seededPush = applySftpNavHistoryTransition({
history: undefined,
currentPath: "/home",
targetPath: "/var",
mode: "push",
});
assert.deepEqual(seededPush.entries, ["/home", "/var"]);
assert.equal(seededPush.index, 1);
// Back moves pointer without wiping forward entries
const steppedBack = applySftpNavHistoryTransition({
history: seededPush,
currentPath: "/var",
targetPath: "/home",
mode: "back",
});
assert.deepEqual(steppedBack.entries, ["/home", "/var"]);
assert.equal(steppedBack.index, 0);
// Refresh (mode: "none") leaves history and forward stack untouched
const afterRefresh = applySftpNavHistoryTransition({
history: steppedBack,
currentPath: "/home",
targetPath: "/home",
mode: "none",
});
assert.equal(afterRefresh, steppedBack);
// Forward restores pointer
const steppedForward = applySftpNavHistoryTransition({
history: afterRefresh,
currentPath: "/home",
targetPath: "/var",
mode: "forward",
});
assert.deepEqual(steppedForward.entries, ["/home", "/var"]);
assert.equal(steppedForward.index, 1);
// If history drifted concurrently so back target no longer matches, fall back to push
const drifted = applySftpNavHistoryTransition({
history: steppedForward,
currentPath: "/var",
targetPath: "/unexpected",
mode: "back",
});
assert.deepEqual(drifted.entries, ["/home", "/var", "/unexpected"]);
assert.equal(drifted.index, 2);
});
test("resolveSftpConnectNavHistory resets on host switch and preserves on same-endpoint reconnect", () => {
const existing = pushNavHistory(createNavHistory("/home/alice"), "/var/log");
const switchedHost = resolveSftpConnectNavHistory({
sameEndpointReconnect: false,
previousHistory: existing,
startPath: "/home/bob",
});
assert.deepEqual(switchedHost.entries, ["/home/bob"]);
assert.equal(switchedHost.index, 0);
assert.equal(canGoBack(switchedHost), false);
const reconnectedSamePath = resolveSftpConnectNavHistory({
sameEndpointReconnect: true,
previousHistory: existing,
startPath: "/var/log",
});
assert.equal(reconnectedSamePath, existing);
const reconnectedFallbackPath = resolveSftpConnectNavHistory({
sameEndpointReconnect: true,
previousHistory: existing,
startPath: "/home/alice",
});
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",
);
});
+231
View File
@@ -0,0 +1,231 @@
export const DEFAULT_SFTP_NAV_HISTORY_MAX_ENTRIES = 50;
export interface SftpNavHistory {
readonly entries: readonly string[];
/** Current position in `entries`, or -1 when `entries` is empty. */
readonly index: number;
readonly maxEntries: number;
}
export interface SftpNavHistoryStep {
readonly history: SftpNavHistory;
readonly path: string | null;
}
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;
function normalizeMaxEntries(maxEntries?: number): number {
if (typeof maxEntries !== "number" || !Number.isFinite(maxEntries) || maxEntries < 1) {
return DEFAULT_SFTP_NAV_HISTORY_MAX_ENTRIES;
}
return Math.floor(maxEntries);
}
export function createNavHistory(
initialPath?: string | null,
maxEntries: number = DEFAULT_SFTP_NAV_HISTORY_MAX_ENTRIES,
): SftpNavHistory {
const limit = normalizeMaxEntries(maxEntries);
if (typeof initialPath === "string" && initialPath.length > 0) {
return {
entries: [initialPath],
index: 0,
maxEntries: limit,
};
}
return {
entries: [],
index: -1,
maxEntries: limit,
};
}
export function resetNavHistory(
path?: string | null,
maxEntries: number = DEFAULT_SFTP_NAV_HISTORY_MAX_ENTRIES,
): SftpNavHistory {
return createNavHistory(path, maxEntries);
}
export function getCurrentNavPath(history: SftpNavHistory): string | null {
if (history.index < 0 || history.index >= history.entries.length) {
return null;
}
return history.entries[history.index] ?? null;
}
export function canGoBack(history: SftpNavHistory): boolean {
return history.index > 0 && history.entries.length > 1;
}
export function canGoForward(history: SftpNavHistory): boolean {
return history.index >= 0 && history.index < history.entries.length - 1;
}
export function peekBackPath(history: SftpNavHistory): string | null {
if (!canGoBack(history)) {
return null;
}
return history.entries[history.index - 1] ?? null;
}
export function peekForwardPath(history: SftpNavHistory): string | null {
if (!canGoForward(history)) {
return null;
}
return history.entries[history.index + 1] ?? null;
}
export function pushNavHistory(
history: SftpNavHistory,
path: string,
isSamePath: SftpNavPathComparator = defaultIsSamePath,
): SftpNavHistory {
if (!path) {
return history;
}
const current = getCurrentNavPath(history);
if (current !== null && isSamePath(current, path)) {
return history;
}
const limit = normalizeMaxEntries(history.maxEntries);
const base = history.index >= 0
? history.entries.slice(0, history.index + 1)
: [];
let nextEntries = [...base, path];
if (nextEntries.length > limit) {
nextEntries = nextEntries.slice(nextEntries.length - limit);
}
return {
entries: nextEntries,
index: nextEntries.length - 1,
maxEntries: limit,
};
}
export function goBack(history: SftpNavHistory): SftpNavHistoryStep {
const path = peekBackPath(history);
if (path === null) {
return { history, path: null };
}
return {
history: {
...history,
index: history.index - 1,
},
path,
};
}
export function goForward(history: SftpNavHistory): SftpNavHistoryStep {
const path = peekForwardPath(history);
if (path === null) {
return { history, path: null };
}
return {
history: {
...history,
index: history.index + 1,
},
path,
};
}
export function applySftpNavHistoryTransition(params: {
history?: SftpNavHistory;
currentPath?: string | null;
targetPath: string;
mode: SftpNavHistoryTransitionMode;
isSamePath?: SftpNavPathComparator;
}): SftpNavHistory {
const compare = params.isSamePath ?? defaultIsSamePath;
const base = params.history && params.history.entries.length > 0
? params.history
: createNavHistory(params.currentPath);
if (params.mode === "none") {
if (base.entries.length === 0 && params.targetPath) {
return createNavHistory(params.targetPath, base.maxEntries);
}
return base;
}
if (params.mode === "back") {
const step = goBack(base);
if (step.path !== null && compare(step.path, params.targetPath)) {
return step.history;
}
const current = getCurrentNavPath(base);
if (current !== null && compare(current, params.targetPath)) {
return base;
}
return pushNavHistory(base, params.targetPath, compare);
}
if (params.mode === "forward") {
const step = goForward(base);
if (step.path !== null && compare(step.path, params.targetPath)) {
return step.history;
}
const current = getCurrentNavPath(base);
if (current !== null && compare(current, params.targetPath)) {
return base;
}
return pushNavHistory(base, params.targetPath, compare);
}
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;
startPath: string;
isSamePath?: SftpNavPathComparator;
}): SftpNavHistory {
const compare = params.isSamePath ?? defaultIsSamePath;
if (
params.sameEndpointReconnect
&& params.previousHistory
&& params.previousHistory.entries.length > 0
) {
const current = getCurrentNavPath(params.previousHistory);
if (current !== null && compare(current, params.startPath)) {
return params.previousHistory;
}
return pushNavHistory(params.previousHistory, params.startPath, compare);
}
return resetNavHistory(params.startPath);
}