Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions src/ui/terminal/sessionCwd.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { describe, expect, test } from "bun:test";
import { restartCwd } from "@/ui/terminal/sessionCwd";

describe("restartCwd", () => {
test("an absent stored cwd falls back to the root without probing", async () => {
let probed: string | null = null;
const cwd = await restartCwd(null, "/proj", async (path) => {
probed = path;
return true;
});

expect(cwd).toBe("/proj");
expect(probed).toBeNull();
});

test("a stored cwd is probed once and kept when it still exists", async () => {
const probed: string[] = [];
const cwd = await restartCwd("/proj/src", "/proj", async (path) => {
probed.push(path);
return true;
});

expect(cwd).toBe("/proj/src");
expect(probed).toEqual(["/proj/src"]);
});

test("a vanished stored cwd falls back to the root", async () => {
const cwd = await restartCwd("/proj/src", "/proj", async () => false);

expect(cwd).toBe("/proj");
});
});
31 changes: 31 additions & 0 deletions src/ui/terminal/sessionCwd.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { listDir } from "@/lib/project/api";

/**
* Whether `path` still hosts a directory the backend can use.
*
* `list_dir` canonicalizes and refuses paths outside the open projects, so a failure means the cwd
* can no longer be used — a deleted directory and one outside this project both lead to the root.
*/
export async function dirExists(path: string): Promise<boolean> {
try {
await listDir(path);
return true;
} catch {
return false;
}
}

/**
* The directory a restart reopens in: the shell's own cwd while it still exists, the root otherwise.
*
* A restart must not move a shell to wherever the editor happens to be pointing. The active file is
* never consulted, and the project root is the only fallback.
*/
export async function restartCwd(
stored: string | null | undefined,
root: string,
exists: (path: string) => Promise<boolean> = dirExists,
): Promise<string> {
if (stored === null || stored === undefined) return root;
return (await exists(stored)) ? stored : root;
}
87 changes: 87 additions & 0 deletions src/ui/terminal/useTerminalRestart.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import "@/test/dom";
import { afterEach, describe, expect, mock, test } from "bun:test";
import { act, cleanup, renderHook, waitFor } from "@testing-library/react";

const opened: string[] = [];
const closed: string[] = [];

// No real PTY: a restart's chosen cwd is the only thing under test.
mock.module("@/lib/project/api", () => ({
ptyOpen: async (cwd: string) => {
opened.push(cwd);
return { id: `pty:${cwd}`, pid: opened.length };
},
ptyClose: async (id: string) => {
closed.push(id);
},
listDir: async () => [],
}));

import { emptySession } from "@/lib/terminal/sessions";
import { useTerminalRestart } from "@/ui/terminal/useTerminalRestart";

const containerRef = { current: null };

function harness(options: {
root: string;
cwd: string;
activePath: string | null;
dirExists: (path: string) => Promise<boolean>;
}) {
const session = {
...emptySession(1, options.cwd),
ptyId: "pty:old",
pid: 7,
opening: false,
};
return renderHook(() =>
useTerminalRestart({
root: options.root,
activePath: options.activePath,
activeId: 1,
sessions: [session],
containerRef,
updateSession: () => undefined,
dirExists: options.dirExists,
}),
);
}

afterEach(() => {
cleanup();
opened.length = 0;
closed.length = 0;
});

describe("restart keeps the shell where it was opened", () => {
test("a stored cwd still on disk wins over the active file's directory", async () => {
const view = harness({
root: "/proj",
cwd: "/proj/src",
activePath: "/proj/docs/readme.md",
dirExists: async () => true,
});

act(() => {
view.result.current();
});

await waitFor(() => expect(opened).toEqual(["/proj/src"]));
expect(closed).toEqual(["pty:old"]);
});

test("a stored cwd that is gone falls back to the root, not the active file", async () => {
const view = harness({
root: "/proj",
cwd: "/proj/src",
activePath: "/proj/docs/readme.md",
dirExists: async () => false,
});

act(() => {
view.result.current();
});

await waitFor(() => expect(opened).toEqual(["/proj"]));
});
});
19 changes: 9 additions & 10 deletions src/ui/terminal/useTerminalRestart.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { useCallback } from "react";
import { ptyClose, ptyOpen } from "@/lib/project/api";
import { DEFAULT_FONT_SIZE } from "@/lib/terminal/fontSize";
import { parentDir } from "@/lib/project/paths";
import { ptySize, type Session } from "@/lib/terminal/sessions";
import { restartCwd } from "@/ui/terminal/sessionCwd";

/**
* Restarts a tab in place: same cwd, same font size, a fresh shell.
Expand All @@ -11,25 +11,24 @@ import { ptySize, type Session } from "@/lib/terminal/sessions";
*/
export function useTerminalRestart(options: {
root: string;
activePath: string | null | undefined;
/** Accepted for callers that still pass it; a restart never moves a shell to the active file. */
activePath?: string | null;
activeId: number | null;
sessions: Session[];
containerRef: React.RefObject<HTMLDivElement | null>;
updateSession: (id: number, updater: (s: Session) => Session) => void;
/** Injected by tests; production probes the backend through `sessionCwd`. */
dirExists?: (path: string) => Promise<boolean>;
}) {
const { root, activePath, activeId, sessions, containerRef, updateSession } = options;
const { root, activeId, sessions, containerRef, updateSession, dirExists } = options;

return useCallback(() => {
return useCallback(async () => {
if (activeId === null) return;
const session = sessions.find((s) => s.id === activeId);
if (session?.ptyId !== null && session?.ptyId !== undefined) {
void ptyClose(session.ptyId).catch(() => undefined);
}
const cwd =
session?.cwd ??
(activePath !== null && activePath !== undefined
? (parentDir(activePath) ?? root)
: root);
const cwd = await restartCwd(session?.cwd, root, dirExists);
updateSession(activeId, (s) => ({
...s,
ptyId: null,
Expand Down Expand Up @@ -59,5 +58,5 @@ export function useTerminalRestart(options: {
}));
}
})();
}, [activeId, sessions, root, activePath, containerRef, updateSession]);
}, [activeId, sessions, root, containerRef, updateSession, dirExists]);
}
33 changes: 28 additions & 5 deletions src/ui/terminal/useTerminalSessions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,16 @@ import { useTerminalSessions } from "@/ui/terminal/useTerminalSessions";

const containerRef = { current: null };

function harness(root: string) {
function harness(root: string, activePath: string | null = null) {
return renderHook(
({ root }: { root: string }) =>
({ root, activePath }: { root: string; activePath: string | null }) =>
useTerminalSessions({
root,
activePath: null,
activePath,
defaultFontSize: 12,
containerRef,
}),
{ initialProps: { root } },
{ initialProps: { root, activePath } },
);
}

Expand All @@ -51,7 +51,7 @@ describe("terminal sessions across a project root change", () => {
await waitFor(() => expect(view.result.current.sessions[0]?.ptyId).toBe("pty:/one"));

await act(async () => {
view.rerender({ root: "/two" });
view.rerender({ root: "/two", activePath: null });
});

await waitFor(() => expect(closed).toContain("pty:/one"));
Expand All @@ -73,3 +73,26 @@ describe("terminal sessions across a project root change", () => {
await waitFor(() => expect(closed).toContain("pty:/one"));
});
});

describe("default cwd for a new terminal", () => {
test("a file open in src does not pull a new shell into src", async () => {
const view = harness("/proj", "/proj/src/main.cpp");
act(() => {
void view.result.current.openSession();
});

await waitFor(() => expect(view.result.current.sessions[0]?.ptyId).toBe("pty:/proj"));
expect(opened).toEqual(["/proj"]);
expect(view.result.current.sessions[0]?.cwd).toBe("/proj");
});

test("no active file opens at the root too", async () => {
const view = harness("/proj");
act(() => {
void view.result.current.openSession();
});

await waitFor(() => expect(view.result.current.sessions[0]?.ptyId).toBe("pty:/proj"));
expect(opened).toEqual(["/proj"]);
});
});
13 changes: 5 additions & 8 deletions src/ui/terminal/useTerminalSessions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,17 @@ import {
type RawOutputHandler,
type Session,
} from "@/lib/terminal/sessions";
import { parentDir } from "@/lib/project/paths";
import { ptyGate, usePtyEvents } from "@/ui/terminal/usePtyEvents";
/** The terminal's sessions: one PTY each, plus the global event wiring. It owns nothing visual. */
export function useTerminalSessions(options: {
root: string;
activePath: string | null | undefined;
/** Accepted for callers that still pass it; a new shell never derives its cwd from a file. */
activePath?: string | null;
defaultFontSize: number | undefined;
containerRef: React.RefObject<HTMLDivElement | null>;
onNotice?: (message: string) => void;
}) {
const { root, activePath, defaultFontSize, containerRef, onNotice } = options;
const { root, defaultFontSize, containerRef, onNotice } = options;
const writeFailed = useRef<Set<number>>(new Set());
const [sessions, setSessions] = useState<Session[]>([]);
const [activeId, setActiveId] = useState<number | null>(null);
Expand Down Expand Up @@ -47,10 +47,7 @@ export function useTerminalSessions(options: {
const openSession = useCallback(async () => {
const id = nextId.current;
nextId.current += 1;
const cwd =
activePath !== null && activePath !== undefined
? (parentDir(activePath) ?? root)
: root;
const cwd = root;
setSessions((current) => {
// The ref the open guard reads must already hold the row, before React renders it.
const next = [...current, emptySession(id, cwd, defaultFontSize)];
Expand Down Expand Up @@ -82,7 +79,7 @@ export function useTerminalSessions(options: {
opening: false,
}));
}
}, [root, activePath, updateSession, defaultFontSize, containerRef, buffer, listeners]);
}, [root, updateSession, defaultFontSize, containerRef, buffer, listeners]);
// The root effect reads this, so a project switch opens a tab through the newest closure.
useEffect(() => {
openSessionRef.current = openSession;
Expand Down
Loading