Files
Netcatty/electron/bridges/sshBridge/sessionOps.cwd.test.cjs
T
f4bc94eadc fix(sftp): follow terminal cwd on macOS/BSD remotes and first open (#2388)
* fix(sftp): follow terminal cwd on macOS/BSD remotes and first open

The "follow terminal directory" probe read the interactive shell's cwd
only via /proc, which does not exist on macOS/BSD remotes, so
getSessionPwd fell back to the home directory (or failed) and the SFTP
panel never tracked the terminal. Add an lsof fallback (read_shell_cwd)
so the probe works on non-Linux remotes; Linux keeps using /proc.

Also fix the first open: while the panel is closed the per-command cwd
probe does not run, so activeTerminalCwd can be stale (login home) even
after the terminal cd-ed elsewhere. On that stale value the follow sync
saw currentPath === terminalCwd and did nothing, leaving the panel at
home. Force one fresh backend probe when the panel first becomes visible
for a connected remote, and re-sync on reopen.

Fixes #2335

Co-authored-by: Cursor Agent <cursor-agent@cursor.com>

* fix(sftp): keep first-open follow from snapping back to stale cwd

Addresses PR review: the first-open resync navigated to the freshly
probed terminal cwd but left the stale `activeTerminalCwd` cache (login
home) in place. Because the one-shot ref was already set, a later
dependency change that re-runs the normal follow sync (e.g. closing an
editor toggles hasActiveWork) would navigate the pane back to that stale
home. Mark the stale cached cwd as already handled before navigating so
the normal sync no-ops until the live cwd catches up;
invalidateInFlightFollowSync clears the guard once activeTerminalCwd
actually changes, letting follow resume.

Co-authored-by: Cursor Agent <cursor-agent@cursor.com>

* fix(sftp): re-check follow eligibility before first-open navigation

Addresses PR review: the first-open resync awaited a fresh terminal-cwd
probe but only re-validated the connection afterward. If the panel was
hidden or interactive work started (editor/dialog) while the probe was
in flight, it still navigated, moving the pane while the follow feature's
own visible/work guards say it should be paused.

Add a live followStillEligible() check (generation, follow enabled/
allowed, visible, no active work, same connection) that gates both the
post-probe continuation and the navigateTo call via shouldApply, matching
the normal follow path. Reset the one-shot guard when bailing mid-probe
so the resync can retry once follow is eligible again.

Co-authored-by: Cursor Agent <cursor-agent@cursor.com>

* test(host-details): align auth row assertion with unified row height

The HostDetailsSection row was unified to `flex h-12 ... px-3` (#2378)
but HostDetailsConnectionSections.test still expected the old
`min-h-12 ... px-3 py-2` class, failing lint-and-test on main. Update the
regex to match the shipped markup.

Co-authored-by: Cursor Agent <cursor-agent@cursor.com>

* fix(sftp): harden terminal cwd resync

---------

Co-authored-by: Cursor Agent <cursor-agent@cursor.com>
Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-07-22 11:58:55 +08:00

202 lines
6.1 KiB
JavaScript

const test = require("node:test");
const assert = require("node:assert/strict");
const { EventEmitter } = require("node:events");
const { createSessionOpsApi, decodeLsofFileName } = require("./sessionOps.cjs");
function quoteShellArg(value) {
return "'" + String(value).replace(/'/g, "'\\''") + "'";
}
function makePwdStream(cwd, loginPid) {
const stream = new EventEmitter();
stream.stderr = new EventEmitter();
stream.close = () => {};
setImmediate(() => {
stream.emit("data", Buffer.from(`${cwd}\n`));
stream.stderr.emit("data", Buffer.from(`NETCATTY_LOGIN_PID=${loginPid}\n`));
stream.emit("close", 0);
});
return stream;
}
function makeApi(session, siblingSessions = [], overrides = {}) {
return createSessionOpsApi({
sessions: new Map([["session-1", session], ...siblingSessions]),
setTimeout: overrides.setTimeout || setTimeout,
clearTimeout: overrides.clearTimeout || clearTimeout,
quoteShellArg,
log: () => {},
});
}
test("shared terminal cwd probe refuses to guess without a shell pid", async () => {
let execCalls = 0;
const connRef = { count: 2 };
const api = makeApi({
connRef,
stream: {},
conn: {
exec() { execCalls += 1; },
},
}, [["session-2", { connRef, stream: {} }]]);
const result = await api.getSessionPwd(null, { sessionId: "session-1" });
assert.equal(result.success, false);
assert.match(result.error, /ambiguous/);
assert.equal(execCalls, 0);
});
test("shared terminal cwd probe targets the shell pid assigned to that tab", async () => {
let command = "";
const session = {
shellPid: "4242",
connRef: { count: 2 },
stream: {},
conn: {
exec(nextCommand, callback) {
command = nextCommand;
callback(null, makePwdStream("/srv/copied-tab", "4242"));
},
},
};
const api = makeApi(session);
const result = await api.getSessionPwd(null, { sessionId: "session-1" });
assert.deepEqual(result, { success: true, cwd: "/srv/copied-tab" });
assert.match(command, /TARGET_LOGIN=4242/);
assert.ok(command.includes("sub(/^.*\\//"));
assert.ok(command.includes("$3 !~ /^\\?+$/"));
assert.match(command, /LC_ALL=C lsof/);
assert.equal(session.shellPid, "4242");
});
test("lsof cwd output decodes UTF-8 bytes and escaped control characters", () => {
assert.equal(
decodeLsofFileName("/tmp/\\xe4\\xb8\\xad\\xe6\\x96\\x87"),
"/tmp/中文",
);
assert.equal(decodeLsofFileName("/tmp/line1\\nline2\\\\tail"), "/tmp/line1\nline2\\tail");
assert.equal(decodeLsofFileName("/tmp/bad\\xQZ"), null);
assert.equal(decodeLsofFileName("/tmp/control-^G-name"), null);
});
test("macOS ps shell names and multi-character no-tty markers classify correctly", () => {
const awk = String.raw`
function isshell(c) { sub(/^.*\//, "", c); sub(/^-/, "", c); return c ~ /^(ba|z|fi|k|da|a|c|tc)?sh$/ }
isshell($4) { print $1, ($3 !~ /^\?+$/ ? "tty" : "no-tty") }
`;
const { spawnSync } = require("node:child_process");
const result = spawnSync("awk", [awk], {
input: "4242 100 ttys001 /bin/zsh\n4243 100 ?? /bin/sh\n",
encoding: "utf8",
});
assert.equal(result.status, 0);
assert.equal(result.stdout, "4242 tty\n4243 no-tty\n");
});
test("session cwd probe decodes the marked lsof pathname", async () => {
const session = {
shellPid: "4242",
connRef: { count: 1 },
stream: {},
conn: {
exec(_command, callback) {
callback(null, makePwdStream(
"NETCATTY_LSOF_CWD=/srv/\\xe4\\xb8\\xad\\xe6\\x96\\x87",
"4242",
));
},
},
};
const api = makeApi(session);
const result = await api.getSessionPwd(null, { sessionId: "session-1" });
assert.deepEqual(result, { success: true, cwd: "/srv/中文" });
});
test("session cwd probe closes a remote command that exceeds its timeout", async () => {
const stream = new EventEmitter();
stream.stderr = new EventEmitter();
let closed = false;
stream.close = () => { closed = true; };
const session = {
shellPid: "4242",
connRef: { count: 1 },
stream: {},
conn: { exec(_command, callback) { callback(null, stream); } },
};
const api = makeApi(session, [], {
setTimeout(callback) { setImmediate(callback); return 1; },
clearTimeout() {},
});
const result = await api.getSessionPwd(null, { sessionId: "session-1" });
assert.deepEqual(result, { success: false, error: "Timeout getting pwd" });
assert.equal(closed, true);
});
test("session cwd probe closes a stream returned after its timeout", async () => {
const stream = new EventEmitter();
stream.stderr = new EventEmitter();
let closed = false;
stream.close = () => { closed = true; };
const session = {
shellPid: "4242",
connRef: { count: 1 },
stream: {},
conn: { exec(_command, callback) { setImmediate(() => callback(null, stream)); } },
};
const api = makeApi(session, [], {
setTimeout(callback) { setImmediate(callback); return 1; },
clearTimeout() {},
});
const result = await api.getSessionPwd(null, { sessionId: "session-1" });
await new Promise((resolve) => setImmediate(resolve));
assert.deepEqual(result, { success: false, error: "Timeout getting pwd" });
assert.equal(closed, true);
});
test("an unshared terminal remembers the shell pid discovered by its cwd probe", async () => {
const session = {
connRef: { count: 1 },
stream: {},
conn: {
exec(_command, callback) {
callback(null, makePwdStream("/home/alice/project", "3131"));
},
},
};
const api = makeApi(session);
const result = await api.getSessionPwd(null, { sessionId: "session-1" });
assert.deepEqual(result, { success: true, cwd: "/home/alice/project" });
assert.equal(session.shellPid, "3131");
});
test("an SFTP reference does not make one terminal cwd ambiguous", async () => {
const session = {
connRef: { count: 2 },
stream: {},
conn: {
exec(_command, callback) {
callback(null, makePwdStream("/home/alice/project", "5151"));
},
},
};
const api = makeApi(session);
const result = await api.getSessionPwd(null, { sessionId: "session-1" });
assert.deepEqual(result, { success: true, cwd: "/home/alice/project" });
assert.equal(session.shellPid, "5151");
});