Skip to content
TypeScript

fix(web): validate terminal links against filesystem metadata (#30526)

Yash Singh059804dfdaba
diff --git a/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx b/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx
index a99434f6659..9fd27587475 100644
--- a/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx
+++ b/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx
@@ -1,5 +1,14 @@
import { EMPTY_TERMINAL_SESSION_STATE } from "@t3tools/client-runtime/state/terminal";
-import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts";
+import {
+ EnvironmentId,
+ ThreadId,
+ type ScopedThreadRef,
+ type FilesystemEntryMetadata,
+} from "@t3tools/contracts";
+import { Atom, AsyncResult } from "effect/reactivity";
+import type { GhosttyTerminalSurfaceOptions } from "~/terminal/ghostty/surface";
+import { AppAtomRegistryProvider, appAtomRegistry } from "../rpc/atomRegistry";
+import { extractTerminalLinks } from "../terminal-links";
import { expect, it, vi } from "vite-plus/test";
import { act, fakeTimers, render } from "../../test/render";
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
@@ -7,6 +16,11 @@ import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
const fixture = vi.hoisted(() => ({
statusByThreadId: new Map<string, "running" | "exited">(),
pendingSurfaces: [] as Array<() => void>,
+ surfaceOptions: [] as GhosttyTerminalSurfaceOptions[],
+ metadata: new Map<
+ string,
+ Atom.Writable<AsyncResult.AsyncResult<FilesystemEntryMetadata | null>>
+ >(),
}));
// Every surface method is a no-op; `then` stays undefined so awaiting the surface resolves to it.
@@ -19,8 +33,9 @@ const fakeSurface: object = new Proxy(
);
vi.mock("~/terminal/ghostty/surface", () => ({
GhosttyTerminalSurface: {
- create: () =>
+ create: (_mount: HTMLElement, options: GhosttyTerminalSurfaceOptions) =>
new Promise((resolve) => {
+ fixture.surfaceOptions.push(options);
fixture.pendingSurfaces.push(() => resolve(fakeSurface));
}),
},
@@ -56,6 +71,30 @@ vi.mock("../state/server", async () => {
});
vi.mock("../state/terminal", () => ({ terminalEnvironment: { write: {}, resize: {} } }));
vi.mock("../state/preview", () => ({ previewEnvironment: { open: {} } }));
+vi.mock("../state/projects", async () => {
+ const { Atom, AsyncResult } = await import("effect/reactivity");
+ return {
+ projectEnvironment: {
+ fileMetadata: ({
+ environmentId,
+ input,
+ }: {
+ environmentId: string;
+ input: { path: string };
+ }) => {
+ const key = JSON.stringify([environmentId, input.path]);
+ let atom = fixture.metadata.get(key);
+ if (!atom) {
+ atom = Atom.make<AsyncResult.AsyncResult<FilesystemEntryMetadata | null>>(
+ AsyncResult.success(null),
+ );
+ fixture.metadata.set(key, atom);
+ }
+ return atom;
+ },
+ },
+ };
+});
vi.mock("../editorPreferences", () => ({ useOpenInPreferredEditor: () => () => {} }));
vi.mock("./preview/openTerminalLinkInPreview", () => ({ openTerminalLinkInPreview: () => {} }));
vi.mock("~/localApi", () => ({ readLocalApi: () => null }));
@@ -69,13 +108,14 @@ vi.mock("../hooks/useSettings", async () => {
function Drawer(props: {
threadRef: ScopedThreadRef;
+ cwd?: string;
onCloseTerminal: (terminalId: string, threadRef?: ScopedThreadRef) => void;
}) {
return (
<ThreadTerminalDrawer
threadRef={props.threadRef}
threadId={props.threadRef.threadId}
- cwd="/repo"
+ cwd={props.cwd ?? "/repo"}
height={240}
terminalIds={["term-1"]}
activeTerminalId="term-1"
@@ -107,6 +147,8 @@ function setup() {
[other.threadId, "running"],
]);
fixture.pendingSurfaces = [];
+ fixture.surfaceOptions = [];
+ fixture.metadata.clear();
return { original, other };
}
@@ -127,3 +169,82 @@ it("closes an exited terminal on its own thread after navigating to one reusing
});
expect(onCloseTerminal.mock.calls).toEqual([["term-1", original]]);
});
+
+it("only activates terminal paths confirmed to exist on their environment", async () => {
+ const { other: threadRef } = setup();
+ const key = (path: string) => JSON.stringify([threadRef.environmentId, path]);
+ const pending = Atom.make<AsyncResult.AsyncResult<FilesystemEntryMetadata | null>>(
+ AsyncResult.initial(),
+ );
+ fixture.metadata.set(key("/repo/src/main.ts"), pending);
+ fixture.metadata.set(
+ key("/repo/src/…notes.ts"),
+ Atom.make<AsyncResult.AsyncResult<FilesystemEntryMetadata | null>>(
+ AsyncResult.success<FilesystemEntryMetadata | null>({ kind: "file" }),
+ ),
+ );
+ fixture.metadata.set(
+ key("/repo/src"),
+ Atom.make<AsyncResult.AsyncResult<FilesystemEntryMetadata | null>>(
+ AsyncResult.success<FilesystemEntryMetadata | null>({ kind: "directory" }),
+ ),
+ );
+ await using screen = await render(
+ <AppAtomRegistryProvider>
+ <Drawer threadRef={threadRef} onCloseTerminal={() => {}} />
+ </AppAtomRegistryProvider>,
+ );
+ await act(async () => {
+ fixture.pendingSurfaces.shift()?.();
+ });
+ const canActivate = (text: string) => fixture.surfaceOptions.at(-1)!.canActivateLink!(text);
+ const validate = (text: string) => fixture.surfaceOptions.at(-1)!.validateLink!(text);
+ const hover = (text: string | null) =>
+ act(() => fixture.surfaceOptions.at(-1)!.onLinkHover!(text));
+
+ expect(canActivate("https://example.com")).toBe(true);
+ for (const branch of ["t3/fix-html-image-details", "t3/fix-html-…mage-details"]) {
+ const candidates = extractTerminalLinks(branch);
+ expect(candidates.length).toBeGreaterThan(0);
+ for (const candidate of candidates) {
+ expect(canActivate(candidate.text)).toBe(false);
+ await hover(candidate.text);
+ expect(canActivate(candidate.text)).toBe(false);
+ expect(await validate(candidate.text)).toBe(false);
+ }
+ }
+ const pressedValidation = validate("src/main.ts:12:7");
+ await hover("src/main.ts:12:7");
+ expect(canActivate("src/main.ts:12:7")).toBe(false);
+ await act(async () => {
+ appAtomRegistry.set(pending, AsyncResult.success({ kind: "file" }));
+ });
+ expect(canActivate("src/main.ts:12:7")).toBe(true);
+ expect(await pressedValidation).toBe(true);
+ expect(canActivate("missing/file.ts")).toBe(false);
+ await hover("missing/file.ts");
+ expect(canActivate("missing/file.ts")).toBe(false);
+ for (const path of ["/repo/src/…notes.ts", "/repo/src"]) {
+ await hover(path);
+ expect(canActivate(path)).toBe(true);
+ }
+ await hover(null);
+ expect(canActivate("/repo/src")).toBe(false);
+ fixture.metadata.set(
+ key("/home/alice/notes.ts"),
+ Atom.make<AsyncResult.AsyncResult<FilesystemEntryMetadata | null>>(
+ AsyncResult.success<FilesystemEntryMetadata | null>({ kind: "file" }),
+ ),
+ );
+ await screen.rerender(
+ <AppAtomRegistryProvider>
+ <Drawer threadRef={threadRef} cwd="/home/alice/project" onCloseTerminal={() => {}} />
+ </AppAtomRegistryProvider>,
+ );
+ await act(async () => {
+ fixture.pendingSurfaces.shift()?.();
+ });
+ expect(await validate("~/notes.ts:5:2")).toBe(true);
+ await hover("~/notes.ts:5:2");
+ expect(canActivate("~/notes.ts:5:2")).toBe(true);
+});
diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx
index 88a945becc9..45318dd5981 100644
--- a/apps/web/src/components/ThreadTerminalDrawer.tsx
+++ b/apps/web/src/components/ThreadTerminalDrawer.tsx
@@ -2,6 +2,7 @@ import { workspaceAreaProps } from "../lib/workspaceFocus";
import { useAtomMount, useAtomValue } from "@effect/atom-react";
import {
isAtomCommandInterrupted,
+ executeAtomQuery,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import {
@@ -21,6 +22,7 @@ import {
} from "lucide-react";
import {
AuthPreviewOperateScope,
+ AuthFilesystemReadScope,
AuthOrchestrationOperateScope,
AuthTerminalOperateScope,
type ContextMenuItem,
@@ -31,10 +33,12 @@ import {
} from "@t3tools/contracts";
import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
import * as Schema from "effect/Schema";
+import { AsyncResult } from "effect/reactivity";
import {
type PointerEvent as ReactPointerEvent,
type ReactNode,
useEffect,
+ useContext,
useEffectEvent,
useLayoutEffect,
useRef,
@@ -78,6 +82,8 @@ import {
import { readLocalApi } from "~/localApi";
import { confirmTerminalClose } from "~/lib/terminalCloseConfirm";
import { useClientSettings } from "../hooks/useSettings";
+import { getFileMetadataQueryAtom } from "../hooks/useFileMetadata";
+import { FileMetadataThreadContext } from "../hooks/FileMetadataThreadProvider";
import { useLocalStorage } from "../hooks/useLocalStorage";
import { attachedTerminalSessionAtom } from "../state/terminalSessions";
import { appAtomRegistry } from "../rpc/atomRegistry";
@@ -184,7 +190,7 @@ export function synchronizeTerminalOutput(
const selection = cells > 0 && compared ? terminal.getSelection() : "";
writeTerminalOutputUpdate(terminal, update);
if (!compared || (cells > 0 && terminal.getSelection() !== selection)) {
- terminal.clearSelection();
+ terminal.clearSelection({ source: "output" });
}
return update.cursor;
}
@@ -525,10 +531,45 @@ function TerminalSessionViewport({
readEnvironmentScope(environmentId, AuthTerminalOperateScope),
);
const canOpenHostEditor = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
- const canActivateTerminalLink = useEffectEvent(
- (text: string) =>
- isTerminalUrl(text) || readEnvironmentScope(environmentId, AuthOrchestrationOperateScope),
- );
+ const canReadFilesystem = useEnvironmentScope(environmentId, AuthFilesystemReadScope);
+ const [linkPath, setLinkPath] = useState<string | null>(null);
+ const metadataThreadRef = useContext(FileMetadataThreadContext);
+ const linkMetadataQuery =
+ linkPath !== null && canOpenHostEditor && canReadFilesystem
+ ? getFileMetadataQueryAtom(
+ environmentId,
+ resolvePathLinkTarget(linkPath, cwd),
+ cwd,
+ metadataThreadRef,
+ )
+ : null;
+ const canActivateTerminalLink = useEffectEvent((text: string) => {
+ if (isTerminalUrl(text)) return true;
+ if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return false;
+ if (text !== linkPath || !linkMetadataQuery) return false;
+ const metadata = AsyncResult.getOrElse(appAtomRegistry.get(linkMetadataQuery), () => null);
+ return metadata?.kind === "file" || metadata?.kind === "directory";
+ });
+ const validateTerminalLink = useEffectEvent(async (text: string) => {
+ if (isTerminalUrl(text)) return true;
+ if (
+ !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) ||
+ !readEnvironmentScope(environmentId, AuthFilesystemReadScope)
+ )
+ return false;
+ const query = getFileMetadataQueryAtom(
+ environmentId,
+ resolvePathLinkTarget(text, cwd),
+ cwd,
+ metadataThreadRef,
+ );
+ if (!query) return false;
+ const result = await executeAtomQuery(appAtomRegistry, query, { reportFailure: false });
+ return (
+ result._tag === "Success" &&
+ (result.value?.kind === "file" || result.value?.kind === "directory")
+ );
+ });
const serverConfig = useAtomValue(serverEnvironment.configValueAtom(environmentId));
const openInPreferredEditor = useOpenInPreferredEditor(
environmentId,
@@ -636,14 +677,18 @@ function TerminalSessionViewport({
consumePendingTerminalFocus(threadRef, terminalId);
}, [canOperateTerminal, terminalId, threadRef]);
- // Links re-read the grant on activation; only the hovered link's styling needs a nudge.
- const linkActivationScopeRef = useRef(canOpenHostEditor);
- // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- refreshes link activation styling on the imperative terminal surface when the editor grant changes
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- refreshes the imperative terminal's hovered link after filesystem metadata or editor permissions change
useEffect(() => {
- if (linkActivationScopeRef.current === canOpenHostEditor) return;
- linkActivationScopeRef.current = canOpenHostEditor;
- terminalRef.current?.refreshLinkActivation();
- }, [canOpenHostEditor]);
+ if (!linkMetadataQuery) {
+ terminalRef.current?.refreshLinkActivation();
+ return;
+ }
+ return appAtomRegistry.subscribe(
+ linkMetadataQuery,
+ () => terminalRef.current?.refreshLinkActivation(),
+ { immediate: true },
+ );
+ }, [linkMetadataQuery]);
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- pushes visibility into the terminal surface before paint and consumes focus requests made while hidden
useLayoutEffect(() => {
@@ -684,6 +729,8 @@ function TerminalSessionViewport({
beforeKey: (event) => handleBeforeKey(event),
onLinkActivate: (text, event) => handleLinkActivate(text, event),
canActivateLink: (text) => canActivateTerminalLink(text),
+ validateLink: (text) => validateTerminalLink(text),
+ onLinkHover: (text) => setLinkPath(text !== null && !isTerminalUrl(text) ? text : null),
// Surface listeners start before WASM loading finishes and the terminal handler exists.
onContextMenu: (event) => {
if (terminalRef.current) void showTerminalContextMenu(event);
@@ -992,7 +1039,11 @@ function TerminalSessionViewport({
}
function handleLinkActivate(text: string, event: MouseEvent): void {
- if (!canActivateTerminalLink(text)) return;
+ if (
+ !isTerminalUrl(text) &&
+ !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)
+ )
+ return;
const latestTerminal = terminalRef.current;
if (!latestTerminal) return;
if (isTerminalUrl(text)) {
diff --git a/apps/web/src/hooks/useFileMetadata.ts b/apps/web/src/hooks/useFileMetadata.ts
index 497cc67d989..398df04a88d 100644
--- a/apps/web/src/hooks/useFileMetadata.ts
+++ b/apps/web/src/hooks/useFileMetadata.ts
@@ -1,4 +1,8 @@
-import { AuthFilesystemReadScope, type EnvironmentId } from "@t3tools/contracts";
+import {
+ AuthFilesystemReadScope,
+ type EnvironmentId,
+ type ScopedThreadRef,
+} from "@t3tools/contracts";
import { resolvePathLinkTarget, splitFilePathPosition } from "@t3tools/shared/fileLinks";
import {
isAbsolutePath,
@@ -12,22 +16,21 @@ import { projectEnvironment } from "../state/projects";
import { useEnvironmentQuery } from "../state/query";
import { FileMetadataThreadContext } from "./FileMetadataThreadProvider";
-export function useFileMetadata(
- environmentId: EnvironmentId | null | undefined,
+export function getFileMetadataQueryAtom(
+ environmentId: EnvironmentId,
path: string,
cwd?: string,
+ threadRef?: ScopedThreadRef | null,
) {
- const canRead = useEnvironmentScope(environmentId ?? null, AuthFilesystemReadScope);
- const threadRef = useContext(FileMetadataThreadContext);
const hostPath = splitFilePathPosition(path).path;
const targetPath = normalizeProjectPathForComparison(
hostPath.startsWith("~/") || !cwd ? hostPath : resolvePathLinkTarget(hostPath, cwd),
);
const absolute = isAbsolutePath(targetPath) || targetPath.startsWith("~/");
- return useEnvironmentQuery(
+ return (
// Servers stat what they are asked about, and a network path leaks the
// Windows user's NTLM credentials to its host before any chip is clicked.
- environmentId && canRead && absolute && !isNetworkPath(targetPath) && targetPath.length <= 512
+ absolute && !isNetworkPath(targetPath) && targetPath.length <= 512
? projectEnvironment.fileMetadata({
environmentId,
input: {
@@ -35,6 +38,18 @@ export function useFileMetadata(
...(threadRef?.environmentId === environmentId ? { threadId: threadRef.threadId } : {}),
},
})
- : null,
+ : null
+ );
+}
+
+export function useFileMetadata(
+ environmentId: EnvironmentId | null | undefined,
+ path: string,
+ cwd?: string,
+) {
+ const canRead = useEnvironmentScope(environmentId ?? null, AuthFilesystemReadScope);
+ const threadRef = useContext(FileMetadataThreadContext);
+ return useEnvironmentQuery(
+ environmentId && canRead ? getFileMetadataQueryAtom(environmentId, path, cwd, threadRef) : null,
).data;
}
diff --git a/apps/web/src/terminal/ghostty/surface.test.ts b/apps/web/src/terminal/ghostty/surface.test.ts
index d0b1e67de26..c7e938524fa 100644
--- a/apps/web/src/terminal/ghostty/surface.test.ts
+++ b/apps/web/src/terminal/ghostty/surface.test.ts
@@ -537,6 +537,150 @@ describe("GhosttyTerminalSurface visibility", () => {
expect(onLinkActivate).not.toHaveBeenCalled();
});
+ it.each([
+ { scenario: "missing", exists: false },
+ { scenario: "file", exists: true },
+ { scenario: "replaced", exists: true },
+ { scenario: "superseded", exists: false },
+ { scenario: "hidden", exists: false },
+ { scenario: "dragged", exists: true },
+ { scenario: "keyboard-selected", exists: false },
+ { scenario: "selection-cleared", exists: true },
+ { scenario: "output-cleaned", exists: true },
+ ])(
+ "validates a quick click without waiting for hover: $scenario",
+ async ({ scenario, exists }) => {
+ vi.stubGlobal("navigator", { platform: "Linux x86_64" });
+ const harness = createHarness();
+ let resolveValidation!: (exists: boolean) => void;
+ const validation = new Promise<boolean>((resolve) => {
+ resolveValidation = resolve;
+ });
+ const validateLink = vi.fn(() => validation);
+ const onLinkActivate = vi.fn();
+ const surface = await harness.create({
+ beforeKey: () => true,
+ canActivateLink: () => false,
+ validateLink,
+ onLinkActivate,
+ });
+ surface.write("src/main.ts");
+ harness.flushFrame();
+ surface.selectAll();
+ expect(surface.getSelection()).toBe("src/main.ts");
+ harness.pointer("pointerdown", 5, 1);
+ expect(validateLink).toHaveBeenCalledWith("src/main.ts");
+ if (scenario === "dragged") harness.pointer("pointermove", 45, 1);
+ harness.pointer("pointerup", 5, 0);
+ expect(onLinkActivate).not.toHaveBeenCalled();
+ if (scenario === "replaced") {
+ surface.write("\r\x1b[2Ksrc/other.ts");
+ harness.flushFrame();
+ }
+ if (scenario === "superseded") harness.pointer("pointerdown", 5, 1);
+ if (scenario === "hidden") {
+ surface.setVisible(false);
+ surface.setVisible(true);
+ }
+ if (scenario === "keyboard-selected")
+ key(surface, "a", "KeyA", { ctrlKey: true, shiftKey: true });
+ if (scenario === "selection-cleared") surface.clearSelection();
+ if (scenario === "output-cleaned") surface.clearSelection({ source: "output" });
+ resolveValidation(exists);
+ await validation;
+ expect(onLinkActivate).toHaveBeenCalledTimes(
+ scenario === "file" || scenario === "output-cleaned" ? 1 : 0,
+ );
+ if (scenario === "missing" || scenario === "selection-cleared")
+ expect(surface.getSelection()).toBe("");
+ if (
+ scenario === "file" ||
+ scenario === "hidden" ||
+ scenario === "superseded" ||
+ scenario === "keyboard-selected"
+ ) {
+ expect(surface.getSelection()).not.toBe("");
+ }
+ },
+ );
+
+ it("only requests validation for a stable visible link under the pointer", async () => {
+ const harness = createHarness();
+ const onLinkHover = vi.fn();
+ const surface = await harness.create({ onLinkHover, canActivateLink: () => false });
+ surface.write("\x1b[?1049h\x1b[Hsrc/first.ts");
+ harness.flushFrame();
+ vi.advanceTimersByTime(250);
+ expect(onLinkHover).not.toHaveBeenCalled();
+
+ harness.pointer("pointermove", 5, 0);
+ expect(onLinkHover).toHaveBeenLastCalledWith("src/first.ts");
+ onLinkHover.mockClear();
+ for (let index = 0; index < 100; index++) {
+ surface.write(`\r\x1b[2Ksrc/file-${index}.ts`);
+ harness.flushFrame();
+ vi.advanceTimersByTime(10);
+ }
+ vi.advanceTimersByTime(239);
+ expect(onLinkHover.mock.calls.filter(([text]) => text !== null)).toEqual([]);
+ vi.advanceTimersByTime(1);
+ harness.flushFrame();
+ vi.advanceTimersByTime(1_000);
+ expect(onLinkHover.mock.calls.filter(([text]) => text !== null)).toEqual([["src/file-99.ts"]]);
+ onLinkHover.mockClear();
+
+ harness.pointer("pointerleave", 5, 0);
+ surface.write("\r\x1b[2Ksrc/recent.ts");
+ harness.flushFrame();
+ vi.advanceTimersByTime(150);
+ harness.pointer("pointermove", 5, 0);
+ vi.advanceTimersByTime(99);
+ expect(onLinkHover.mock.calls.filter(([text]) => text !== null)).toEqual([]);
+ vi.advanceTimersByTime(1);
+ expect(onLinkHover).toHaveBeenLastCalledWith("src/recent.ts");
+ onLinkHover.mockClear();
+
+ harness.pointer("pointerleave", 5, 0);
+ surface.write("\r\x1b[2Ksrc/still.ts");
+ harness.flushFrame();
+ vi.advanceTimersByTime(250);
+ surface.write("\x1b[2;1Hother output");
+ harness.flushFrame();
+ harness.pointer("pointermove", 5, 0);
+ expect(onLinkHover).toHaveBeenLastCalledWith("src/still.ts");
+ onLinkHover.mockClear();
+
+ surface.write("\x1b[H\x1b[2Ksrc/move.ts");
+ harness.flushFrame();
+ harness.pointer("pointermove", 45, 0);
+ vi.advanceTimersByTime(150);
+ surface.write("\r\x1b[2K src/move.ts");
+ harness.flushFrame();
+ vi.advanceTimersByTime(249);
+ expect(onLinkHover.mock.calls.filter(([text]) => text !== null)).toEqual([]);
+ vi.advanceTimersByTime(1);
+ expect(onLinkHover).toHaveBeenLastCalledWith("src/move.ts");
+ onLinkHover.mockClear();
+
+ for (const [index, cancel] of [
+ () => {
+ surface.write("\r\x1b[2Kplain text");
+ harness.flushFrame();
+ },
+ () => harness.pointer("pointerleave", 5, 0),
+ () => surface.setVisible(false),
+ () => surface.dispose(),
+ ].entries()) {
+ surface.setVisible(true);
+ surface.write(`\x1b[H\x1b[2Ksrc/next-${index}.ts`);
+ harness.flushFrame();
+ harness.pointer("pointermove", 5, 0);
+ cancel();
+ vi.advanceTimersByTime(250);
+ expect(onLinkHover.mock.calls.filter(([text]) => text !== null)).toEqual([]);
+ }
+ });
+
it.each([false, true])(
"uses visibility %s if it changes while WASM initializes",
async (visible) => {
diff --git a/apps/web/src/terminal/ghostty/surface.ts b/apps/web/src/terminal/ghostty/surface.ts
index a1a762cd8a7..f1db43056f7 100644
--- a/apps/web/src/terminal/ghostty/surface.ts
+++ b/apps/web/src/terminal/ghostty/surface.ts
@@ -35,6 +35,7 @@ const DEFAULT_TERMINAL_FONT_FAMILY =
const CONTENT_PADDING = 4;
const MIN_SCROLLBAR_THUMB_HEIGHT = 18;
const CURSOR_BLINK_INTERVAL_MS = 500;
+const TERMINAL_LINK_HOVER_DELAY_MS = 250;
/** End an unterminated synchronized update instead of freezing the last frame. */
const SYNCHRONIZED_OUTPUT_RENDER_TIMEOUT_MS = 500;
const TERMINAL_FONT_LOAD_TEXT = "iMW0@# .";
@@ -525,6 +526,9 @@ export interface GhosttyTerminalSurfaceOptions {
readonly beforeKey: (event: KeyboardEvent) => boolean;
readonly onLinkActivate: (text: string, event: MouseEvent) => void;
readonly canActivateLink?: (text: string) => boolean;
+ readonly validateLink?: (text: string) => Promise<boolean>;
+ /** Reports hovered candidates once their rendered text is stable for 250 ms; null cancels. */
+ readonly onLinkHover?: (text: string | null) => void;
/** The host must prevent the default menu; native Paste cannot reach a canvas terminal. */
readonly onContextMenu?: (event: MouseEvent) => void;
}
@@ -585,6 +589,8 @@ export class GhosttyTerminalSurface {
private mouseReportingButton: number | null = null;
private linkActivationPointerId: number | null = null;
private linkActivationLink: TerminalLinkWithRange | null = null;
+ private linkActivationValidation: Promise<boolean> | undefined;
+ private linkActivationRequestId = 0;
private linkActivationOrigin: {
x: number;
y: number;
@@ -592,6 +598,12 @@ export class GhosttyTerminalSurface {
} | null = null;
private hoveredLink: TerminalLinkWithRange | null = null;
private hoverPointer: { x: number; y: number } | null = null;
+ private linkHoverCandidate: TerminalLinkWithRange | null = null;
+ private linkHoverTimer: number | null = null;
+ private linkRowStability: Array<{
+ row: GhosttySnapshot["rowData"][number];
+ changedAt: number;
+ }> = [];
private selectionClickSequence: TerminalSelectionClickSequence | null = null;
private selectionMoved = false;
private composing = false;
@@ -740,6 +752,9 @@ export class GhosttyTerminalSurface {
this.forceFullRender = true;
this.scrollbarDirty = true;
if (!visible) {
+ this.linkActivationRequestId += 1;
+ this.clearHoveredLink();
+ this.linkRowStability = [];
this.cancelRender();
this.setSelectionAutoscroll(0);
return;
@@ -991,6 +1006,7 @@ export class GhosttyTerminalSurface {
}
selectAll(): void {
+ this.linkActivationRequestId += 1;
this.clearPrimedCopy();
const range = this.core.selectAll();
this.selectionAnchorScreen = range?.start ?? null;
@@ -1033,7 +1049,8 @@ export class GhosttyTerminalSurface {
};
}
- clearSelection(): void {
+ clearSelection({ source = "user" }: { source?: "user" | "output" } = {}): void {
+ if (source === "user") this.linkActivationRequestId += 1;
this.clearPrimedCopy();
this.core.clearSelection();
this.selectionEnd = null;
@@ -1061,6 +1078,7 @@ export class GhosttyTerminalSurface {
dispose(): void {
if (this.disposed) return;
this.disposed = true;
+ this.clearHoveredLink();
this.stopObservingResize();
document.fonts.removeEventListener("loadingdone", this.onFontsLoaded);
this.dprMedia?.removeEventListener("change", this.onDevicePixelRatioChange);
@@ -1344,6 +1362,7 @@ export class GhosttyTerminalSurface {
}
private readonly onPointerDown = (event: PointerEvent) => {
+ this.linkActivationRequestId += 1;
if (event.pointerType === "touch") {
event.preventDefault();
if (!event.isPrimary || this.touchScroll !== null) return;
@@ -1379,12 +1398,13 @@ export class GhosttyTerminalSurface {
}
if (event.button !== 0) return;
const clickCount = this.recordSelectionClick(event);
- const link = this.linkAt(event.clientX, event.clientY);
+ const link = this.linkAt(event.clientX, event.clientY, true);
if (link && !event.shiftKey && clickCount === 1) {
event.preventDefault();
event.stopPropagation();
this.linkActivationPointerId = event.pointerId;
this.linkActivationLink = link;
+ this.linkActivationValidation = this.validateLink(link.text);
this.linkActivationOrigin = {
x: event.clientX,
y: event.clientY,
@@ -1470,6 +1490,7 @@ export class GhosttyTerminalSurface {
}
this.linkActivationPointerId = null;
this.linkActivationLink = null;
+ this.linkActivationValidation = undefined;
this.linkActivationOrigin = null;
this.clearHoveredLink();
this.beginSelection(
@@ -1577,14 +1598,65 @@ export class GhosttyTerminalSurface {
private clearHoveredLink(cursor = ""): void {
this.hoverPointer = null;
+ this.updateLinkHover(null);
this.setHoveredLink(null);
this.canvas.style.cursor = cursor;
}
private refreshHoveredLink(): void {
const pointer = this.hoverPointer;
- const link = pointer ? this.linkAt(pointer.x, pointer.y) : null;
- this.setHoveredLink(link);
+ const link = pointer ? this.findLinkAt(pointer.x, pointer.y) : null;
+ this.updateLinkHover(link);
+ this.setHoveredLink(link && this.options.canActivateLink?.(link.text) !== false ? link : null);
+ }
+
+ private updateLinkHover(link: TerminalLinkWithRange | null): void {
+ if (!this.options.onLinkHover) return;
+ if (link ? isSameTerminalLink(link, this.linkHoverCandidate) : this.linkHoverCandidate === null)
+ return;
+ this.linkHoverCandidate = link;
+ if (this.linkHoverTimer !== null) {
+ window.clearTimeout(this.linkHoverTimer);
+ this.linkHoverTimer = null;
+ }
+ this.options.onLinkHover(null);
+ if (link !== null) {
+ const now = performance.now();
+ let changedAt = 0;
+ for (let y = link.range.start.y; y <= link.range.end.y; y++) {
+ changedAt = Math.max(changedAt, this.linkRowStability[y]?.changedAt ?? now);
+ }
+ const delay = Math.max(0, TERMINAL_LINK_HOVER_DELAY_MS - (now - changedAt));
+ if (delay === 0) {
+ this.options.onLinkHover(link.text);
+ return;
+ }
+ this.linkHoverTimer = window.setTimeout(() => {
+ this.linkHoverTimer = null;
+ this.options.onLinkHover?.(link.text);
+ }, delay);
+ }
+ }
+
+ private updateLinkRowStability(reset: boolean): void {
+ if (!this.options.onLinkHover || !this.snapshot) return;
+ if (reset) {
+ this.updateLinkHover(null);
+ this.linkRowStability = [];
+ }
+ const now = performance.now();
+ this.snapshot.rowData.forEach((row, y) => {
+ const previous = this.linkRowStability[y]?.row;
+ if (
+ !previous ||
+ previous.text !== row.text ||
+ previous.cells.length !== row.cells.length ||
+ previous.isWrapContinuation !== row.isWrapContinuation ||
+ previous.wrapsToNext !== row.wrapsToNext
+ )
+ this.linkRowStability[y] = { row, changedAt: now };
+ });
+ this.linkRowStability.length = this.snapshot.rows;
}
private setHoveredLink(link: TerminalLinkWithRange | null): void {
@@ -1617,8 +1689,8 @@ export class GhosttyTerminalSurface {
this.sendMouse("press", ghosttyMouseButton(0), event);
this.sendMouse("release", ghosttyMouseButton(0), event);
} else {
- const link = this.linkAt(event.clientX, event.clientY);
- if (link) this.options.onLinkActivate(link.text, event);
+ const link = this.linkAt(event.clientX, event.clientY, true);
+ if (link) this.activateLink(link, event);
else this.clearSelection();
}
return;
@@ -1628,15 +1700,17 @@ export class GhosttyTerminalSurface {
event.preventDefault();
event.stopPropagation();
const link = this.linkActivationLink;
+ const validation = this.linkActivationValidation;
this.linkActivationPointerId = null;
this.linkActivationLink = null;
+ this.linkActivationValidation = undefined;
this.linkActivationOrigin = null;
if (this.canvas.hasPointerCapture(event.pointerId)) {
this.canvas.releasePointerCapture(event.pointerId);
}
if (event.type !== "pointercancel") {
- if (link && isSameTerminalLink(link, this.linkAt(event.clientX, event.clientY))) {
- this.options.onLinkActivate(link.text, event);
+ if (link && isSameTerminalLink(link, this.linkAt(event.clientX, event.clientY, true))) {
+ this.activateLink(link, event, validation);
}
}
return;
@@ -1988,10 +2062,12 @@ export class GhosttyTerminalSurface {
this.metrics.height,
anchorBottom,
);
+ const geometryChanged = canvasConfiguration !== null || nextOriginY !== this.originY;
if (nextOriginY !== this.originY) {
this.originY = nextOriginY;
this.forceFullRender = true;
}
+ this.updateLinkRowStability(geometryChanged);
this.refreshHoveredLink();
renderGhosttySnapshot({
context: this.context,
@@ -2080,9 +2156,51 @@ export class GhosttyTerminalSurface {
};
}
- private linkAt(clientX: number, clientY: number): TerminalLinkWithRange | null {
+ private validateLink(text: string): Promise<boolean> | undefined {
+ if (this.options.canActivateLink?.(text) !== false) return;
+ const validation = this.options.validateLink?.(text);
+ // A drag can abandon the press before activateLink subscribes to its result.
+ void validation?.catch(() => {});
+ return validation;
+ }
+
+ private activateLink(
+ link: TerminalLinkWithRange,
+ event: MouseEvent,
+ validation = this.validateLink(link.text),
+ ): void {
+ if (!validation) {
+ this.options.onLinkActivate(link.text, event);
+ return;
+ }
+ const requestId = this.linkActivationRequestId;
+ void validation.then(
+ (valid) => {
+ if (
+ this.disposed ||
+ !this.visible ||
+ requestId !== this.linkActivationRequestId ||
+ !isSameTerminalLink(link, this.findLinkAt(event.clientX, event.clientY))
+ )
+ return;
+ if (valid) this.options.onLinkActivate(link.text, event);
+ else this.clearSelection();
+ },
+ () => {},
+ );
+ }
+
+ private linkAt(
+ clientX: number,
+ clientY: number,
+ allowValidation = false,
+ ): TerminalLinkWithRange | null {
const link = this.findLinkAt(clientX, clientY);
- return link && this.options.canActivateLink?.(link.text) !== false ? link : null;
+ return link &&
+ ((allowValidation && this.options.validateLink) ||
+ this.options.canActivateLink?.(link.text) !== false)
+ ? link
+ : null;
}
private findLinkAt(clientX: number, clientY: number): TerminalLinkWithRange | null {