diff --git a/README.md b/README.md index 1496dbb2e6f70..c07dba36f0cd6 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ This is a fork of T3 Code that integrates a few additional features, including: - **FYI messages between agents:** an agent can send another thread an FYI, a note of at most 16,000 characters that needs no action and starts no turn. The receiving agent gets it with its next turn; a running Claude Code thread gets it at its next tool call. An FYI counts as delivered only when the turn that carries it finishes: a turn that fails, is stopped, restarts or is reverted gives it back, so the agent may see it twice. When a thread has an FYI waiting and has been idle for 6 hours, T3 Code wakes it to deliver its FYIs, unless the thread is settled, archived, waiting for your answer or holds queued messages; a snoozed thread waits until its snooze ends. The 6 hours count from the thread's last turn, or from the reset of a usage limit that stopped it on the provider it still uses (or from the end of a snooze that ends after that reset), so an FYI to a thread that has been idle longer wakes it within minutes. A thread whose usage limit has no known reset time, or whose provider fails every turn, gets a failed wake every 6 hours while an FYI waits. A wake carries up to 16,000 characters of FYIs. The rest, and any that a wake gives back because it failed or you stopped it, get another wake after 6 more idle hours. A wake is a new turn, so **Resume** no longer continues a turn that ended before it. Settle or archive a thread to stop its wakes. The timeline marks these messages "FYI · waiting", "FYI · sent" while the turn that carries them runs, and "FYI" once it finished. - **Open server files by their path:** in a browser signed in to T3 Code at its own address, open `/` (such as `https://t3.example.com/home/ana/work/report.html`) to see that file read-only, for files under the server user's home folder and temp folder. A session needs the `filesystem:read` permission, and a signed-out browser gets a sign-in page. Text and code of any type show as plain text, and images, PDFs, audio and video show as themselves. A folder shows its `index.html`, or else a list of its files. Links ending in `:line` or `:line:col` open the file. Names that start with `.`, and T3 Code's own data folder, are not served. An HTML page runs in a sandboxed frame at the same address: its scripts run but cannot act as you in T3, and it loads files from its own folder and below for an hour, though its scripts cannot fetch them. A page directly in the home or temp folder loads no other files. An HTML page linked from another site, or any HTML page over plain HTTP, first shows an Open link. - **HTML pages from disk block their own network calls:** an HTML file that the file viewer, "Open in browser" or a server file path shows from disk runs its own scripts and loads scripts, styles, fonts and images over HTTPS. It cannot use fetch, XHR, WebSocket, EventSource, beacons or form posts, its frames cannot load other addresses, and audio and video play only from its own files or inline data. A page that fetches its data while it runs needs that data inline. An allowed load can still carry data in its URL, so these limits do not make an untrusted page safe. -- **Folders on file links:** Settings → Appearance → File link folders shows up to four folders before the file name on file links in messages and Markdown previews, such as `review-pipeline/glossary.md`, so you need not hover a link to see where the file is. Each browser, and the desktop app, keeps its own choice. A file name that repeats in one message keeps its folder hint after the name. +- **Folders on file links:** By default, file links in messages and Markdown previews show one folder before the file name, such as `docs/guide.md`. Settings → Appearance → File link folders lets you pick the file name alone or up to four folders. When you show folders, the prefix stops at the thread machine's home folder with `~/` or at filesystem root with `/`, as in `~/notes.md` and `/etc/hosts`. On Windows, when the prefix reaches a drive root, it shows the drive, such as `C:/`. A link written relative to the project without a leading `./` shows only the folders it names, because it may open a matching file in another folder. Each browser and the desktop app keeps its own choice. If a browser or the desktop app already saved its settings, it keeps the saved value. The setting's reset button gives the new default. A file name that repeats in one message keeps its folder hint after the name. - Enabling math rendering by default. - Other small fixes. diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 1ea6af9cf5b1f..3e8a0e43f4ba1 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -1897,6 +1897,7 @@ export const layerWsRpc = ( auth, cwd: config.cwd, hostname: yield* HostProcess.Hostname, + homeDirectory: yield* HostProcess.HomeDirectory, keybindingsConfigPath: config.keybindingsConfigPath, keybindings: keybindingsConfig.keybindings, issues: keybindingsConfig.issues, diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index 7dd8bd7ac2878..373a6841fce6d 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -819,7 +819,7 @@ function useChatMarkdownState( const fileLinksKey = `${fileLinkSourcesKey(text, cwd, imageBaseDir, isStreaming ? (streamingBlocks ?? splitMarkdownBlocks(text) ?? [text]) : null, fileLinkPeerPaths, hostFileOrigins)}`; const { markdownFileLinkMetaByHref, inlineCodeFileLinkMetaByText, fileLinkParentSuffixByPath } = resolveFileLinkSources(fileLinksKey, cwd, imageBaseDir); - const fileLinkPrefix = useFileLinkPrefix(fileLinkParentSuffixByPath); + const fileLinkPrefix = useFileLinkPrefix(fileLinkParentSuffixByPath, environmentId); const resolveThreadPullRequest = ( href: string, ): (ThreadPullRequestKey & { readonly url: string }) | null => { diff --git a/apps/web/src/fork/FileLinkPathPrefix.tsx b/apps/web/src/fork/FileLinkPathPrefix.tsx index 2604a8f409de4..99537e8f53ec2 100644 --- a/apps/web/src/fork/FileLinkPathPrefix.tsx +++ b/apps/web/src/fork/FileLinkPathPrefix.tsx @@ -1,9 +1,33 @@ +import { useAtomValue } from "@effect/atom-react"; +import type { EnvironmentId } from "@t3tools/contracts"; +import { Atom } from "effect/reactivity"; + import { useClientSettings } from "../hooks/useSettings"; -import { type FileLinkPathMeta, fileLinkPathPrefix } from "./fileLinkPathDepth"; +import { serverEnvironment } from "../state/server"; +import { type FileLinkPathMeta, fileLinkPathPrefix, repeatedFileNames } from "./fileLinkPathDepth"; + +// Only the home string and the OS flag, so other config updates do not re-render every message. +const serverHomeAtom = Atom.family((environmentId: EnvironmentId | null) => + Atom.make( + (get) => get(serverEnvironment.configValueAtom(environmentId))?.homeDirectory || null, + ).pipe(Atom.withLabel(`file-link-server-home:${environmentId}`)), +); +const serverWindowsAtom = Atom.family((environmentId: EnvironmentId | null) => + Atom.make( + (get) => + get(serverEnvironment.configValueAtom(environmentId))?.environment.platform.os === "windows", + ).pipe(Atom.withLabel(`file-link-server-windows:${environmentId}`)), +); -export function useFileLinkPrefix(parentSuffixByPath: ReadonlyMap) { +export function useFileLinkPrefix( + parentSuffixByPath: ReadonlyMap, + environmentId: EnvironmentId | null, +) { const depth = useClientSettings((settings) => settings.fileLinkPathDepth); - return (meta: FileLinkPathMeta) => fileLinkPathPrefix(meta, parentSuffixByPath, depth); + const home = useAtomValue(serverHomeAtom(environmentId)); + const windows = useAtomValue(serverWindowsAtom(environmentId)); + const view = { depth, home, windows, repeatedNames: repeatedFileNames(parentSuffixByPath) }; + return (meta: FileLinkPathMeta) => fileLinkPathPrefix(meta, view); } /** diff --git a/apps/web/src/fork/fileLinkPathDepth.browser.test.tsx b/apps/web/src/fork/fileLinkPathDepth.browser.test.tsx index 44e3ed546c4f1..7eb9e95bbf89f 100644 --- a/apps/web/src/fork/fileLinkPathDepth.browser.test.tsx +++ b/apps/web/src/fork/fileLinkPathDepth.browser.test.tsx @@ -1,5 +1,10 @@ -import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts"; -import { expect, it } from "vite-plus/test"; +import { + DEFAULT_CLIENT_SETTINGS, + EnvironmentId, + type EditorId, + ThreadId, +} from "@t3tools/contracts"; +import { expect, it, vi } from "vite-plus/test"; import { userEvent } from "vite-plus/test/browser"; import "~/index.css"; @@ -9,34 +14,67 @@ import ChatMarkdown from "../components/ChatMarkdown"; import { collectThreadFindRanges } from "../components/chat/threadFindHighlights"; import { __setClientSettingsForTests, persistClientSettingsPatch } from "../hooks/useSettings"; +const SERVER_HOME_ENVIRONMENT = vi.hoisted(() => "server-home"); + +// One environment reports a home folder that its thread's cwd does not reveal. +vi.mock(import("../state/server"), async (original) => { + const actual = await original(); + const { Atom } = await import("effect/reactivity"); + const config = Atom.make({ + availableEditors: [] as readonly EditorId[], + environment: { platform: { os: "linux" }, capabilities: {} }, + homeDirectory: "/srv/me", + }); + const configValueAtom = actual.serverEnvironment.configValueAtom; + return { + ...actual, + serverEnvironment: { + ...actual.serverEnvironment, + configValueAtom: ((environmentId: EnvironmentId | null) => + environmentId === SERVER_HOME_ENVIRONMENT + ? config + : configValueAtom(environmentId)) as never, + }, + }; +}); + const TEXT = [ - "See [glossary](docs/review-pipeline/glossary.md#L12), [web](src/web/index.ts), [server](src/server/index.ts) and [readme](README.md).", + "See [glossary](docs/review-pipeline/glossary.md#L12), [web](src/web/index.ts), [server](src/server/index.ts), [readme](README.md) and [hosts](/etc/hosts).", "The review is done.", ].join("\n\n"); -it("draws the chosen folders before file names, outside the label text", async () => { +function withDefaultSettings(): Disposable { __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS); - using _settings = { - [Symbol.dispose]: () => __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS), - }; + return { [Symbol.dispose]: () => __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS) }; +} + +function chipPrefixes(container: HTMLElement) { + return [...container.querySelectorAll(".chat-markdown-file-link")].map((chip) => { + const prefix = chip.querySelector("[data-file-link-prefix]"); + return [prefix && getComputedStyle(prefix, "::after").content, chip.textContent]; + }); +} + +it("draws the chosen folders before file names, outside the label text", async () => { + using _settings = withDefaultSettings(); await using screen = await render(
, ); - const chips = () => - [...screen.container.querySelectorAll(".chat-markdown-file-link")].map((chip) => { - const prefix = chip.querySelector("[data-file-link-prefix]"); - return [prefix && getComputedStyle(prefix, "::after").content, chip.textContent]; - }); - const labels = ["glossary.md · L12", "index.ts · src/web", "index.ts · src/server", "README.md"]; - expect(chips()).toEqual(labels.map((label) => [null, label])); - - await act(() => persistClientSettingsPatch({ fileLinkPathDepth: 2 }, async () => {})); - - expect(chips()).toEqual([ + const labels = [ + "glossary.md · L12", + "index.ts · src/web", + "index.ts · src/server", + "README.md", + "hosts", + ]; + expect(chipPrefixes(screen.container)).toEqual([ ['"review-pipeline/"', labels[0]], - ...labels.slice(1).map((label) => [null, label]), + [null, labels[1]], + [null, labels[2]], + [null, labels[3]], + ['"/etc/"', labels[4]], ]); await expect .element( @@ -60,4 +98,32 @@ it("draws the chosen folders before file names, outside the label text", async ( position: { x: word.left - box.left + 4, y: word.top - box.top + word.height / 2 }, }); expect(window.getSelection()?.toString().trim()).toBe(paragraph.textContent?.trim()); + + await act(() => persistClientSettingsPatch({ fileLinkPathDepth: 1 }, async () => {})); + + expect(chipPrefixes(screen.container)).toEqual(labels.map((label) => [null, label])); +}); + +it("draws ~/ at the home folder the thread's server reports", async () => { + using _settings = withDefaultSettings(); + const text = "See [a](/srv/me/notes/a.md) and [b](/srv/other/notes/b.md)."; + await using screen = await render( + <> + + + , + ); + expect(chipPrefixes(screen.container)).toEqual([ + ['"~/notes/"', "a.md"], + ['"notes/"', "b.md"], + ['"notes/"', "a.md"], + ['"notes/"', "b.md"], + ]); }); diff --git a/apps/web/src/fork/fileLinkPathDepth.test.ts b/apps/web/src/fork/fileLinkPathDepth.test.ts index 189bc91934497..cd335702e4ddd 100644 --- a/apps/web/src/fork/fileLinkPathDepth.test.ts +++ b/apps/web/src/fork/fileLinkPathDepth.test.ts @@ -1,45 +1,177 @@ import type { FileLinkPathDepth } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { fileLinkPathPrefix } from "./fileLinkPathDepth"; +import { type FileLinkPathMeta, fileLinkPathPrefix, repeatedFileNames } from "./fileLinkPathDepth"; -type Meta = Parameters[0]; - -const inWorkspace = (workspaceRelativePath: string): Meta => ({ - filePath: `/home/me/project/${workspaceRelativePath}`, +const HOME = "/home/me"; +const inWorkspace = ( + workspaceRelativePath: string, + root = "/home/me/project", +): FileLinkPathMeta => ({ + filePath: `${root}/${workspaceRelativePath}`, workspaceRelativePath, + workspaceLookupPath: null, +}); +// A link written relative to the workspace, which may open a search match elsewhere. +const written = (workspaceRelativePath: string, root = "/home/me/project"): FileLinkPathMeta => ({ + ...inWorkspace(workspaceRelativePath, root), + workspaceLookupPath: workspaceRelativePath, +}); +const outside = (filePath: string): FileLinkPathMeta => ({ + filePath, + workspaceRelativePath: null, + workspaceLookupPath: null, }); -const outside = (filePath: string): Meta => ({ filePath, workspaceRelativePath: null }); const collisions = new Map([ ["/home/me/project/src/web/index.ts", "src/web"], ["C:/repo/src/server/index.ts", "src/server"], ]); describe("fileLinkPathPrefix", () => { - it.each<[string, Meta, FileLinkPathDepth, string | undefined]>([ - ["depth 1 shows no folder", inWorkspace("docs/review-pipeline/glossary.md"), 1, undefined], - ["depth 2", inWorkspace("docs/review-pipeline/glossary.md"), 2, "review-pipeline/"], - ["depth 3", inWorkspace("docs/review-pipeline/glossary.md"), 3, "docs/review-pipeline/"], - ["a workspace root file", inWorkspace("README.md"), 3, undefined], - ["fewer folders than the depth", inWorkspace("docs/glossary.md"), 5, "docs/"], - [ - "an absolute path outside the workspace", - outside("/etc/nginx/sites/app.conf"), + it.each< + [string, FileLinkPathMeta, FileLinkPathDepth, string | null, string | undefined, boolean?] + >([ + // Home and root examples at the default depth. + ["a file in home", outside("/home/me/a.md"), 2, HOME, "~/"], + ["a folder in home", outside("/home/me/dir/a.md"), 2, HOME, "~/dir/"], + ["a file at root", outside("/a.md"), 2, HOME, "/"], + ["a folder at root", outside("/etc/a.conf"), 2, HOME, "/etc/"], + ["past home", outside("/home/me/x/dir/a.md"), 2, HOME, "dir/"], + ["reaching home after two folders", outside("/home/me/x/dir/a.md"), 3, HOME, "~/x/dir/"], + ["past root", outside("/etc/x/a.conf"), 2, HOME, "x/"], + ["fewer folders than the depth at home", outside("/home/me/a.md"), 5, HOME, "~/"], + ["fewer folders than the depth at root", outside("/etc/nginx/a.conf"), 5, HOME, "/etc/nginx/"], + ["depth 1 shows no folder", outside("/home/me/dir/a.md"), 1, HOME, undefined], + ["depth 1 shows no root", outside("/a.md"), 1, HOME, undefined], + ["another user's home", outside("/home/bob/a.md"), 2, HOME, "bob/"], + ["another user's home reaching root", outside("/home/bob/a.md"), 3, HOME, "/home/bob/"], + ["a folder that only starts like home", outside("/home/me2/a.md"), 2, HOME, "me2/"], + ["the folder above home", outside("/home/a.md"), 2, HOME, "/home/"], + ["home unknown", outside("/home/me/a.md"), 2, null, "me/"], + ["home at /root", outside("/root/notes/a.md"), 2, "/root", "~/notes/"], + ["a home at root", outside("/etc/hosts"), 2, "/", "/etc/"], + ["a home at a drive root", outside("C:\\x\\a.md"), 2, "C:\\", "C:/x/"], + ["home given with a trailing slash", outside("/home/me/dir/a.md"), 2, "/home/me/", "~/dir/"], + // An unexpanded `~/` link. + ["a literal ~ file", outside("~/a.md"), 2, null, "~/"], + ["a literal ~ folder", outside("~/notes/a.md"), 2, null, "~/notes/"], + ["past a literal ~", outside("~/x/notes/a.md"), 2, null, "notes/"], + ["a literal ~ with home known", outside("~/notes/a.md"), 3, HOME, "~/notes/"], + // The workspace no longer stops the walk. + [ + "a workspace file", + inWorkspace("docs/review-pipeline/glossary.md"), + 2, + HOME, + "review-pipeline/", + ], + [ + "a workspace file, deeper", + inWorkspace("docs/review-pipeline/glossary.md"), + 3, + HOME, + "docs/review-pipeline/", + ], + ["a workspace root file", inWorkspace("README.md", "/home/me/code/proj"), 2, HOME, "proj/"], + [ + "a workspace root file reaching home", + inWorkspace("README.md", "/home/me/code/proj"), + 3, + HOME, + "~/code/proj/", + ], + ["a workspace in home", inWorkspace("README.md", "/home/me/proj"), 2, HOME, "~/proj/"], + ["a workspace at home", inWorkspace("README.md", HOME), 2, HOME, "~/"], + ["a workspace at home, one folder", inWorkspace("notes/a.md", HOME), 2, HOME, "~/notes/"], + ["a workspace at root", inWorkspace("a.md", ""), 2, null, "/"], + ["a POSIX folder named like a drive", inWorkspace("C:/a.md", ""), 2, null, "/C:/"], + ["a workspace folder named like a drive", inWorkspace("C:/docs/a.md"), 3, HOME, "C:/docs/"], + // `..` and `.` fold before the walk. + ["a .. reaching home", outside("/home/me/proj/../a.md"), 2, HOME, "~/"], + ["a .. outside home", outside("/home/me/proj/../x/y/a.ts"), 2, HOME, "y/"], + ["a .. past root", outside("/a/../../b/c.md"), 3, HOME, "/b/"], + ["a .. that names a parent", inWorkspace("docs/guides/../glossary.md"), 2, HOME, "docs/"], + ["folders after a leading ..", outside("../../shared/lib/util.ts"), 4, HOME, "shared/lib/"], + ["a dot folder", outside("./src/./app.ts"), 3, HOME, "src/"], + // Windows. + ["a Windows drive root file", outside("C:\\a.md"), 2, null, "C:/"], + ["a Windows drive path", outside("C:\\Users\\me\\notes.md"), 2, null, "me/"], + [ + "a Windows drive path reaching the drive", + outside("C:\\Users\\me\\notes.md"), + 4, + null, + "C:/Users/me/", + ], + ["a Windows home", outside("C:\\Users\\me\\notes.md"), 2, "C:\\Users\\me", "~/"], + [ + "a Windows home in another case", + outside("c:\\users\\ME\\d\\notes.md"), + 2, + "C:\\Users\\me", + "~/d/", + ], + [ + "a Windows path on another drive", + outside("D:\\Users\\me\\notes.md"), 3, - "nginx/sites/", - ], - ["a POSIX name with a backslash", outside("/tmp/notes/a\\b.md"), 2, undefined], - ["a workspace folder named like a drive", inWorkspace("C:/docs/a.md"), 3, "C:/docs/"], - ["a slash-prefixed Windows drive path", outside("/C:/Users/me/notes.md"), 3, "Users/me/"], - ["a Windows drive path", outside("C:\\Users\\me\\notes.md"), 4, "Users/me/"], - ["a UNC path", outside("\\\\server\\share\\docs\\a.md"), 3, "share/docs/"], - ["folders after a leading ..", outside("../../shared/lib/util.ts"), 4, "shared/lib/"], - ["a .. that names a parent", inWorkspace("docs/guides/../glossary.md"), 2, "docs/"], - ["a .. past the folders", outside("/a/../../b/c.md"), 3, "b/"], - ["a dot folder", outside("./src/./app.ts"), 3, "src/"], - ["a colliding path", inWorkspace("src/web/index.ts"), 3, undefined], - ["a colliding Windows path", outside("C:\\repo\\src\\server\\index.ts"), 3, undefined], - ])("%s", (_name, meta, depth, expected) => { - expect(fileLinkPathPrefix(meta, collisions, depth)).toBe(expected); + "C:\\Users\\me", + "D:/Users/me/", + ], + ["a POSIX home for a Windows path", outside("C:\\home\\me\\a.md"), 2, HOME, "me/"], + ["a .. at a drive root", outside("C:\\..\\a.md"), 2, null, "C:/"], + ["a slash-prefixed Windows drive", outside("/C:/Users/me/notes.md"), 3, null, "C:/Users/me/"], + ["a slash-prefixed Windows home", outside("/C:/Users/me/notes.md"), 3, "C:\\Users\\me", "~/"], + ["a UNC path", outside("\\\\server\\share\\docs\\a.md"), 3, null, "share/docs/"], + [ + "a UNC path shows its server", + outside("\\\\server\\share\\docs\\a.md"), + 5, + null, + "server/share/docs/", + ], + // A written workspace link shows only the folders it names. + [ + "a written workspace link", + written("docs/review-pipeline/glossary.md"), + 5, + HOME, + "docs/review-pipeline/", + ], + ["a written file name", written("README.md"), 3, HOME, undefined], + ["a written file name at home", written("README.md", HOME), 2, HOME, undefined], + [ + "a written ./ link walks on", + { ...written("./docs/a.md"), filePath: "/home/me/project/docs/a.md" }, + 3, + HOME, + "~/project/docs/", + ], + // An unexpanded `~/` link and a Windows server's Git Bash path use the reported home. + ["a literal ~ with home at root", outside("~/notes.md"), 2, "/", "/"], + ["a literal ~ with a .. past home", outside("~/../notes.md"), 2, "/srv/me", "/srv/"], + [ + "a Git Bash path on a Windows server", + outside("/c/Users/alex/notes.md"), + 2, + "C:\\Users\\alex", + "~/", + true, + ], + ["a Git Bash drive root", outside("/d/a.md"), 2, "C:\\Users\\alex", "D:/", true], + ["a Git Bash path with no reported home", outside("/d/a.md"), 2, null, "D:/", true], + ["a /c folder on a POSIX server", outside("/c/a.md"), 2, HOME, "/c/"], + ["a written link past its own folders", written("docs/../../notes.md"), 5, HOME, undefined], + ["a link to home itself", outside("~/"), 2, "/srv/me", undefined], + // No prefix. + ["a root file named like a repeated file", outside("/home/me/index.ts"), 2, HOME, undefined], + ["a link to a parent folder", outside("/home/me/one/project/../"), 2, HOME, undefined], + ["a link to a current folder", outside("/home/me/one/."), 2, HOME, undefined], + ["a POSIX name with a backslash", outside("/tmp/notes/a\\b.md"), 2, HOME, undefined], + ["a colliding path", inWorkspace("src/web/index.ts"), 3, HOME, undefined], + ["a colliding Windows path", outside("C:\\repo\\src\\server\\index.ts"), 3, null, undefined], + ])("%s", (_name, meta, depth, home, expected, windows = false) => { + const repeatedNames = repeatedFileNames(collisions); + expect(fileLinkPathPrefix(meta, { depth, home, windows, repeatedNames })).toBe(expected); }); }); diff --git a/apps/web/src/fork/fileLinkPathDepth.ts b/apps/web/src/fork/fileLinkPathDepth.ts index 171c1c49bf3fe..ac19bb975901c 100644 --- a/apps/web/src/fork/fileLinkPathDepth.ts +++ b/apps/web/src/fork/fileLinkPathDepth.ts @@ -3,29 +3,145 @@ import { isWindowsAbsolutePath, stripSlashPrefixedWindowsDrive } from "@t3tools/ import type { MarkdownFileLinkMeta } from "../markdown-links"; -export type FileLinkPathMeta = Pick; +export type FileLinkPathMeta = Pick< + MarkdownFileLinkMeta, + "filePath" | "workspaceRelativePath" | "workspaceLookupPath" +>; -/** The last `depth - 1` folders of a file link as `a/b/`, or undefined when there are none to show. */ +export interface FileLinkPathView { + readonly depth: FileLinkPathDepth; + readonly home: string | null; + // The server runs on Windows, where Git Bash writes `C:\x` as `/c/x`. + readonly windows: boolean; + // File names that repeat in the message, from `repeatedFileNames`. + readonly repeatedNames: ReadonlySet; +} + +/** The file names of a message's repeated-name folder hints. */ +export function repeatedFileNames(parentSuffixByPath: ReadonlyMap): Set { + return new Set([...parentSuffixByPath.keys()].map(lastName)); +} + +type PathKind = "posix" | "relative" | "drive" | "unc"; + +interface FoldedPath { + readonly kind: PathKind; + // `.` dropped and `..` folded; a drive path starts with its drive (`C:`), a UNC path with its server. + readonly names: readonly string[]; + // The walk shows no folder before this index. + readonly floor: number; +} + +function foldPath(raw: string): FoldedPath { + const kind: PathKind = raw.startsWith("\\\\") + ? "unc" + : isWindowsAbsolutePath(raw) + ? "drive" + : raw.startsWith("/") + ? "posix" + : "relative"; + const windows = kind === "drive" || kind === "unc"; + // `..` never climbs above a drive or a UNC share. + const top = kind === "drive" ? 1 : kind === "unc" ? 2 : 0; + const names: string[] = []; + for (const part of raw.split(windows ? /[\\/]/ : "/")) { + if (part === "" || part === ".") continue; + if (part !== "..") names.push(part); + else if (names.length > top && names.at(-1) !== "..") names.pop(); + else if (kind === "relative") names.push(part); + } + // A UNC path shows its server and share like folders, as before; it draws no root marker. + const floor = kind === "relative" ? names.lastIndexOf("..") + 1 : 0; + return { kind, names, floor }; +} + +// How many leading names of `path` are the home folder; undefined when it is not under home. +function homeLength(path: FoldedPath, home: string | null): number | undefined { + if (path.kind === "relative") return path.floor === 0 && path.names[0] === "~" ? 1 : undefined; + if (home === null) return undefined; + const homePath = foldPath(home); + // A home at `/` or at a drive root is that root, which draws its own marker. + if (homePath.names.length <= (homePath.kind === "drive" ? 1 : 0)) return undefined; + if (homePath.kind !== path.kind || homePath.names.length > path.names.length) return undefined; + const same = + path.kind === "posix" + ? (a: string, b: string) => a === b + : (a: string, b: string) => a.toLowerCase() === b.toLowerCase(); + return homePath.names.every((name, i) => same(name, path.names[i]!)) + ? homePath.names.length + : undefined; +} + +/** + * Returns the path prefix before a file link's name, with up to `depth - 1` folders, ending in `/`. + * Stops early at home with `~/`, at POSIX root with `/`, or at a Windows drive root such as `C:/`. + * Returns `undefined` at depth 1, for a repeated file name, or when there is nothing to show. + */ export function fileLinkPathPrefix( meta: FileLinkPathMeta, - parentSuffixByPath: ReadonlyMap, - depth: FileLinkPathDepth, + view: FileLinkPathView, ): string | undefined { - if (depth === 1 || parentSuffixByPath.has(meta.filePath.replaceAll("\\", "/"))) return undefined; - // Workspace-relative paths already use `/`; a POSIX name may contain `\`. - const path = meta.workspaceRelativePath ?? stripSlashPrefixedWindowsDrive(meta.filePath); - const windows = meta.workspaceRelativePath === null && isWindowsAbsolutePath(path); - const segments = path - .split(windows ? /[\\/]/ : "/") - .filter((segment) => segment !== "" && segment !== "."); - if (windows && /^[A-Za-z]:$/.test(segments[0] ?? "")) segments.shift(); + if (view.depth === 1) return undefined; + // A repeated file name keeps its folder hint after the name instead. The hint map leaves out a + // copy that has no folder above it, so the check goes by name. + const name = lastName(meta.filePath); + if (view.repeatedNames.has(name)) return undefined; + // The label of a link ending in `.`, `..` or a bare `~` is that name, not the folder it + // reaches, so any folders drawn before it would name another path. + if (name === "." || name === ".." || /^~[\\/]*$/.test(meta.filePath)) return undefined; + const path = foldPath(hostPath(meta, view)); // The label names such a file by its last `\` part, so folders before it would misname the path. - if (!windows && segments.at(-1)?.includes("\\")) return undefined; - const resolved: string[] = []; - for (const segment of segments) { - if (segment === ".." && resolved.length > 0 && resolved.at(-1) !== "..") resolved.pop(); - else resolved.push(segment); + if ((path.kind === "posix" || path.kind === "relative") && path.names.at(-1)?.includes("\\")) { + return undefined; + } + const folders = path.names.length - 1; + const home = homeLength(path, view.home); + // A link written relative to the workspace may open a search match in another folder, so only + // the folders it names are sure, and no marker is drawn above them. + const lookup = meta.workspaceLookupPath; + const written = + lookup !== null && !/^(?:\.{1,2}|~)[\\/]/.test(lookup) && !/[\\/]$/.test(lookup) + ? foldPath(lookup) + : null; + // Names before any leading `..` the link keeps are not folders it names. + const unsure = written === null ? -1 : path.names.length - (written.names.length - written.floor); + // `above` counts the folders still hidden; the walk moves up one folder at a time. + let above = folders; + let marker = ""; + while (above > unsure) { + if (above === home) marker = "~/"; + else if (path.kind === "posix" && above === 0) marker = "/"; + else if (path.kind === "drive" && above === 1) marker = `${path.names[0]}/`; + if (marker !== "" || above <= path.floor || folders - above === view.depth - 1) break; + above -= 1; + } + const shown = path.names.slice(Math.max(above, unsure), folders); + const prefix = marker + shown.map((folder) => `${folder}/`).join(""); + return prefix === "" ? undefined : prefix; +} + +function lastName(path: string): string { + return ( + path + .split(/[\\/]/) + .filter((part) => part !== "") + .at(-1) ?? "" + ); +} + +// The file's path as the server reads it, as far as display needs it. +function hostPath(meta: FileLinkPathMeta, { home, windows }: FileLinkPathView): string { + // An unexpanded `~/` link names the reported home. + if (/^~[\\/]/.test(meta.filePath) && home) { + return `${home.replace(/[\\/]+$/, "")}/${meta.filePath.slice(2)}`; + } + // Only a path outside the workspace may be a Windows drive written after a slash; inside a + // workspace at `/`, `/C:/a.md` names a POSIX folder `C:`. + if (meta.workspaceRelativePath !== null) return meta.filePath; + // A Windows server reads Git Bash's `/c/x` as `C:/x`. + if (windows) { + const drive = /^\/([a-zA-Z])(?=\/|$)/.exec(meta.filePath); + if (drive !== null) return `${drive[1]!.toUpperCase()}:${meta.filePath.slice(2) || "/"}`; } - const folders = resolved.slice(resolved.lastIndexOf("..") + 1, -1).slice(1 - depth); - return folders.length === 0 ? undefined : `${folders.join("/")}/`; + return stripSlashPrefixedWindowsDrive(meta.filePath); } diff --git a/packages/contracts/src/fork/fileLinkPathDepth.test.ts b/packages/contracts/src/fork/fileLinkPathDepth.test.ts index b0248f4f5b6e5..c4ad81cca6aee 100644 --- a/packages/contracts/src/fork/fileLinkPathDepth.test.ts +++ b/packages/contracts/src/fork/fileLinkPathDepth.test.ts @@ -7,22 +7,24 @@ const decodeClientSettings = Schema.decodeUnknownSync(ClientSettingsSchema); const encodeClientSettings = Schema.encodeSync(ClientSettingsSchema); describe("fileLinkPathDepth", () => { - it("defaults to the file name alone", () => { - expect(decodeClientSettings({}).fileLinkPathDepth).toBe(1); + it("defaults to one folder and the file name", () => { + expect(decodeClientSettings({}).fileLinkPathDepth).toBe(2); }); - it.each([9, 0, 2.5, "2", null, { depth: 2 }])( - "a bad stored depth %j decodes to 1 and keeps the other settings", + it.each([9, 0, 2.5, "3", null, { depth: 3 }])( + "a bad stored depth %j decodes to 2 and keeps the other settings", (fileLinkPathDepth) => { const settings = decodeClientSettings({ fileLinkPathDepth, wordWrap: false }); - expect(settings.fileLinkPathDepth).toBe(1); + expect(settings.fileLinkPathDepth).toBe(2); expect(settings.wordWrap).toBe(false); }, ); - it("round-trips a valid depth", () => { - const settings = decodeClientSettings({ fileLinkPathDepth: 3 }); - expect(settings.fileLinkPathDepth).toBe(3); - expect(decodeClientSettings(encodeClientSettings(settings)).fileLinkPathDepth).toBe(3); + it.each([1, 3] as const)("round-trips a saved depth %j", (fileLinkPathDepth) => { + const settings = decodeClientSettings({ fileLinkPathDepth }); + expect(settings.fileLinkPathDepth).toBe(fileLinkPathDepth); + expect(decodeClientSettings(encodeClientSettings(settings)).fileLinkPathDepth).toBe( + fileLinkPathDepth, + ); }); }); diff --git a/packages/contracts/src/fork/fileLinkPathDepth.ts b/packages/contracts/src/fork/fileLinkPathDepth.ts index efc4ff724c3e2..44b61a31a574b 100644 --- a/packages/contracts/src/fork/fileLinkPathDepth.ts +++ b/packages/contracts/src/fork/fileLinkPathDepth.ts @@ -5,8 +5,10 @@ import * as Schema from "effect/Schema"; export const FileLinkPathDepth = Schema.Literals([1, 2, 3, 4, 5]); export type FileLinkPathDepth = typeof FileLinkPathDepth.Type; -/** The stored field: a bad value decodes to 1, so it can never fail the client settings. */ +const DEFAULT_FILE_LINK_PATH_DEPTH: FileLinkPathDepth = 2; + +/** Stored file link depth. A missing or invalid value defaults to 2 so client settings never fail. */ export const StoredFileLinkPathDepth = FileLinkPathDepth.pipe( - Schema.catchDecoding(() => Effect.succeedSome(1 as const)), - Schema.withDecodingDefault(Effect.succeed(1 as const)), + Schema.catchDecoding(() => Effect.succeedSome(DEFAULT_FILE_LINK_PATH_DEPTH)), + Schema.withDecodingDefault(Effect.succeed(DEFAULT_FILE_LINK_PATH_DEPTH)), ); diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts index 1e70426001495..b4424e2382c8f 100644 --- a/packages/contracts/src/server.ts +++ b/packages/contracts/src/server.ts @@ -713,6 +713,8 @@ export const ServerConfig = Schema.Struct({ cwd: TrimmedNonEmptyString, /** The machine's own name, which file URIs from its shells may carry. Older servers omit it. */ hostname: Schema.optionalKey(Schema.String), + /** The server machine's home folder, which chat file links shorten to `~/`. Older servers omit it. */ + homeDirectory: Schema.optionalKey(Schema.String), keybindingsConfigPath: TrimmedNonEmptyString, keybindings: ResolvedKeybindingsConfig, issues: ServerConfigIssues,