From 006d5090d5a7b4c88828182e7312e7468a579555 Mon Sep 17 00:00:00 2001 From: Yizhou Jiang Date: Sun, 22 Nov 2026 12:32:03 +0800 Subject: [PATCH] fix(terminal): a new shell starts at the project root, not the active file's folder --- src/ui/terminal/sessionCwd.test.ts | 32 ++++++++ src/ui/terminal/sessionCwd.ts | 31 ++++++++ src/ui/terminal/useTerminalRestart.test.ts | 87 +++++++++++++++++++++ src/ui/terminal/useTerminalRestart.ts | 19 +++-- src/ui/terminal/useTerminalSessions.test.ts | 33 ++++++-- src/ui/terminal/useTerminalSessions.ts | 13 ++- 6 files changed, 192 insertions(+), 23 deletions(-) create mode 100644 src/ui/terminal/sessionCwd.test.ts create mode 100644 src/ui/terminal/sessionCwd.ts create mode 100644 src/ui/terminal/useTerminalRestart.test.ts diff --git a/src/ui/terminal/sessionCwd.test.ts b/src/ui/terminal/sessionCwd.test.ts new file mode 100644 index 00000000..c81f84ab --- /dev/null +++ b/src/ui/terminal/sessionCwd.test.ts @@ -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"); + }); +}); diff --git a/src/ui/terminal/sessionCwd.ts b/src/ui/terminal/sessionCwd.ts new file mode 100644 index 00000000..98e88f2c --- /dev/null +++ b/src/ui/terminal/sessionCwd.ts @@ -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 { + 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 = dirExists, +): Promise { + if (stored === null || stored === undefined) return root; + return (await exists(stored)) ? stored : root; +} diff --git a/src/ui/terminal/useTerminalRestart.test.ts b/src/ui/terminal/useTerminalRestart.test.ts new file mode 100644 index 00000000..f59f27f4 --- /dev/null +++ b/src/ui/terminal/useTerminalRestart.test.ts @@ -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; +}) { + 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"])); + }); +}); diff --git a/src/ui/terminal/useTerminalRestart.ts b/src/ui/terminal/useTerminalRestart.ts index ee38c292..c238aa02 100644 --- a/src/ui/terminal/useTerminalRestart.ts +++ b/src/ui/terminal/useTerminalRestart.ts @@ -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. @@ -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; updateSession: (id: number, updater: (s: Session) => Session) => void; + /** Injected by tests; production probes the backend through `sessionCwd`. */ + dirExists?: (path: string) => Promise; }) { - 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, @@ -59,5 +58,5 @@ export function useTerminalRestart(options: { })); } })(); - }, [activeId, sessions, root, activePath, containerRef, updateSession]); + }, [activeId, sessions, root, containerRef, updateSession, dirExists]); } diff --git a/src/ui/terminal/useTerminalSessions.test.ts b/src/ui/terminal/useTerminalSessions.test.ts index b3e84c7f..5e78b5dd 100644 --- a/src/ui/terminal/useTerminalSessions.test.ts +++ b/src/ui/terminal/useTerminalSessions.test.ts @@ -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 } }, ); } @@ -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")); @@ -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"]); + }); +}); diff --git a/src/ui/terminal/useTerminalSessions.ts b/src/ui/terminal/useTerminalSessions.ts index 0756698c..f41ef0fb 100644 --- a/src/ui/terminal/useTerminalSessions.ts +++ b/src/ui/terminal/useTerminalSessions.ts @@ -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; onNotice?: (message: string) => void; }) { - const { root, activePath, defaultFontSize, containerRef, onNotice } = options; + const { root, defaultFontSize, containerRef, onNotice } = options; const writeFailed = useRef>(new Set()); const [sessions, setSessions] = useState([]); const [activeId, setActiveId] = useState(null); @@ -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)]; @@ -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;