The best way to control Claude Code, Codex and more from any computer or phone
fix(web): validate terminal links against filesystem metadata (#30526)
Yash Singh committed
Nov 3, 2026 at 20:57 UTC
059804dfdaba54bd6f997355c30e102dae20d3b4
5 files changed
+483
-34
apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx
+124
-3
@@ -1,5 +1,14 @@
1
import { EMPTY_TERMINAL_SESSION_STATE } from "@t3tools/client-runtime/state/terminal";
2
-import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts";
2
+import {
3
+ EnvironmentId,
4
+ ThreadId,
5
+ type ScopedThreadRef,
6
+ type FilesystemEntryMetadata,
7
+} from "@t3tools/contracts";
8
+import { Atom, AsyncResult } from "effect/reactivity";
9
+import type { GhosttyTerminalSurfaceOptions } from "~/terminal/ghostty/surface";
10
+import { AppAtomRegistryProvider, appAtomRegistry } from "../rpc/atomRegistry";
11
+import { extractTerminalLinks } from "../terminal-links";
12
import { expect, it, vi } from "vite-plus/test";
13
import { act, fakeTimers, render } from "../../test/render";
14
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
@@ -7,6 +16,11 @@ import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
16
const fixture = vi.hoisted(() => ({
17
statusByThreadId: new Map<string, "running" | "exited">(),
18
pendingSurfaces: [] as Array<() => void>,
19
+ surfaceOptions: [] as GhosttyTerminalSurfaceOptions[],
20
+ metadata: new Map<
21
+ string,
22
+ Atom.Writable<AsyncResult.AsyncResult<FilesystemEntryMetadata | null>>
23
+ >(),
24
}));
25
26
// 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(
33
);
34
vi.mock("~/terminal/ghostty/surface", () => ({
35
GhosttyTerminalSurface: {
22
- create: () =>
36
+ create: (_mount: HTMLElement, options: GhosttyTerminalSurfaceOptions) =>
37
new Promise((resolve) => {
38
+ fixture.surfaceOptions.push(options);
39
fixture.pendingSurfaces.push(() => resolve(fakeSurface));
40
}),
41
},
@@ -56,6 +71,30 @@ vi.mock("../state/server", async () => {
71
});
72
vi.mock("../state/terminal", () => ({ terminalEnvironment: { write: {}, resize: {} } }));
73
vi.mock("../state/preview", () => ({ previewEnvironment: { open: {} } }));
74
+vi.mock("../state/projects", async () => {
75
+ const { Atom, AsyncResult } = await import("effect/reactivity");
76
+ return {
77
+ projectEnvironment: {
78
+ fileMetadata: ({
79
+ environmentId,
80
+ input,
81
+ }: {
82
+ environmentId: string;
83
+ input: { path: string };
84
+ }) => {
85
+ const key = JSON.stringify([environmentId, input.path]);
86
+ let atom = fixture.metadata.get(key);
87
+ if (!atom) {
88
+ atom = Atom.make<AsyncResult.AsyncResult<FilesystemEntryMetadata | null>>(
89
+ AsyncResult.success(null),
90
+ );
91
+ fixture.metadata.set(key, atom);
92
+ }
93
+ return atom;
94
+ },
95
+ },
96
+ };
97
+});
98
vi.mock("../editorPreferences", () => ({ useOpenInPreferredEditor: () => () => {} }));
99
vi.mock("./preview/openTerminalLinkInPreview", () => ({ openTerminalLinkInPreview: () => {} }));
100
vi.mock("~/localApi", () => ({ readLocalApi: () => null }));
@@ -69,13 +108,14 @@ vi.mock("../hooks/useSettings", async () => {
108
109
function Drawer(props: {
110
threadRef: ScopedThreadRef;
111
+ cwd?: string;
112
onCloseTerminal: (terminalId: string, threadRef?: ScopedThreadRef) => void;
113
}) {
114
return (
115
<ThreadTerminalDrawer
116
threadRef={props.threadRef}
117
threadId={props.threadRef.threadId}
78
- cwd="/repo"
118
+ cwd={props.cwd ?? "/repo"}
119
height={240}
120
terminalIds={["term-1"]}
121
activeTerminalId="term-1"
@@ -107,6 +147,8 @@ function setup() {
147
[other.threadId, "running"],
148
]);
149
fixture.pendingSurfaces = [];
150
+ fixture.surfaceOptions = [];
151
+ fixture.metadata.clear();
152
return { original, other };
153
}
154
@@ -127,3 +169,82 @@ it("closes an exited terminal on its own thread after navigating to one reusing
169
});
170
expect(onCloseTerminal.mock.calls).toEqual([["term-1", original]]);
171
});
172
+
173
+it("only activates terminal paths confirmed to exist on their environment", async () => {
174
+ const { other: threadRef } = setup();
175
+ const key = (path: string) => JSON.stringify([threadRef.environmentId, path]);
176
+ const pending = Atom.make<AsyncResult.AsyncResult<FilesystemEntryMetadata | null>>(
177
+ AsyncResult.initial(),
178
+ );
179
+ fixture.metadata.set(key("/repo/src/main.ts"), pending);
180
+ fixture.metadata.set(
181
+ key("/repo/src/…notes.ts"),
182
+ Atom.make<AsyncResult.AsyncResult<FilesystemEntryMetadata | null>>(
183
+ AsyncResult.success<FilesystemEntryMetadata | null>({ kind: "file" }),
184
+ ),
185
+ );
186
+ fixture.metadata.set(
187
+ key("/repo/src"),
188
+ Atom.make<AsyncResult.AsyncResult<FilesystemEntryMetadata | null>>(
189
+ AsyncResult.success<FilesystemEntryMetadata | null>({ kind: "directory" }),
190
+ ),
191
+ );
192
+ await using screen = await render(
193
+ <AppAtomRegistryProvider>
194
+ <Drawer threadRef={threadRef} onCloseTerminal={() => {}} />
195
+ </AppAtomRegistryProvider>,
196
+ );
197
+ await act(async () => {
198
+ fixture.pendingSurfaces.shift()?.();
199
+ });
200
+ const canActivate = (text: string) => fixture.surfaceOptions.at(-1)!.canActivateLink!(text);
201
+ const validate = (text: string) => fixture.surfaceOptions.at(-1)!.validateLink!(text);
202
+ const hover = (text: string | null) =>
203
+ act(() => fixture.surfaceOptions.at(-1)!.onLinkHover!(text));
204
+
205
+ expect(canActivate("https://example.com")).toBe(true);
206
+ for (const branch of ["t3/fix-html-image-details", "t3/fix-html-…mage-details"]) {
207
+ const candidates = extractTerminalLinks(branch);
208
+ expect(candidates.length).toBeGreaterThan(0);
209
+ for (const candidate of candidates) {
210
+ expect(canActivate(candidate.text)).toBe(false);
211
+ await hover(candidate.text);
212
+ expect(canActivate(candidate.text)).toBe(false);
213
+ expect(await validate(candidate.text)).toBe(false);
214
+ }
215
+ }
216
+ const pressedValidation = validate("src/main.ts:12:7");
217
+ await hover("src/main.ts:12:7");
218
+ expect(canActivate("src/main.ts:12:7")).toBe(false);
219
+ await act(async () => {
220
+ appAtomRegistry.set(pending, AsyncResult.success({ kind: "file" }));
221
+ });
222
+ expect(canActivate("src/main.ts:12:7")).toBe(true);
223
+ expect(await pressedValidation).toBe(true);
224
+ expect(canActivate("missing/file.ts")).toBe(false);
225
+ await hover("missing/file.ts");
226
+ expect(canActivate("missing/file.ts")).toBe(false);
227
+ for (const path of ["/repo/src/…notes.ts", "/repo/src"]) {
228
+ await hover(path);
229
+ expect(canActivate(path)).toBe(true);
230
+ }
231
+ await hover(null);
232
+ expect(canActivate("/repo/src")).toBe(false);
233
+ fixture.metadata.set(
234
+ key("/home/alice/notes.ts"),
235
+ Atom.make<AsyncResult.AsyncResult<FilesystemEntryMetadata | null>>(
236
+ AsyncResult.success<FilesystemEntryMetadata | null>({ kind: "file" }),
237
+ ),
238
+ );
239
+ await screen.rerender(
240
+ <AppAtomRegistryProvider>
241
+ <Drawer threadRef={threadRef} cwd="/home/alice/project" onCloseTerminal={() => {}} />
242
+ </AppAtomRegistryProvider>,
243
+ );
244
+ await act(async () => {
245
+ fixture.pendingSurfaces.shift()?.();
246
+ });
247
+ expect(await validate("~/notes.ts:5:2")).toBe(true);
248
+ await hover("~/notes.ts:5:2");
249
+ expect(canActivate("~/notes.ts:5:2")).toBe(true);
250
+});
apps/web/src/components/ThreadTerminalDrawer.tsx
+64
-13
@@ -2,6 +2,7 @@ import { workspaceAreaProps } from "../lib/workspaceFocus";
2
import { useAtomMount, useAtomValue } from "@effect/atom-react";
3
import {
4
isAtomCommandInterrupted,
5
+ executeAtomQuery,
6
squashAtomCommandFailure,
7
} from "@t3tools/client-runtime/state/runtime";
8
import {
@@ -21,6 +22,7 @@ import {
22
} from "lucide-react";
23
import {
24
AuthPreviewOperateScope,
25
+ AuthFilesystemReadScope,
26
AuthOrchestrationOperateScope,
27
AuthTerminalOperateScope,
28
type ContextMenuItem,
@@ -31,10 +33,12 @@ import {
33
} from "@t3tools/contracts";
34
import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
35
import * as Schema from "effect/Schema";
36
+import { AsyncResult } from "effect/reactivity";
37
import {
38
type PointerEvent as ReactPointerEvent,
39
type ReactNode,
40
useEffect,
41
+ useContext,
42
useEffectEvent,
43
useLayoutEffect,
44
useRef,
@@ -78,6 +82,8 @@ import {
82
import { readLocalApi } from "~/localApi";
83
import { confirmTerminalClose } from "~/lib/terminalCloseConfirm";
84
import { useClientSettings } from "../hooks/useSettings";
85
+import { getFileMetadataQueryAtom } from "../hooks/useFileMetadata";
86
+import { FileMetadataThreadContext } from "../hooks/FileMetadataThreadProvider";
87
import { useLocalStorage } from "../hooks/useLocalStorage";
88
import { attachedTerminalSessionAtom } from "../state/terminalSessions";
89
import { appAtomRegistry } from "../rpc/atomRegistry";
@@ -184,7 +190,7 @@ export function synchronizeTerminalOutput(
190
const selection = cells > 0 && compared ? terminal.getSelection() : "";
191
writeTerminalOutputUpdate(terminal, update);
192
if (!compared || (cells > 0 && terminal.getSelection() !== selection)) {
187
- terminal.clearSelection();
193
+ terminal.clearSelection({ source: "output" });
194
}
195
return update.cursor;
196
}
@@ -525,10 +531,45 @@ function TerminalSessionViewport({
531
readEnvironmentScope(environmentId, AuthTerminalOperateScope),
532
);
533
const canOpenHostEditor = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
528
- const canActivateTerminalLink = useEffectEvent(
529
- (text: string) =>
530
- isTerminalUrl(text) || readEnvironmentScope(environmentId, AuthOrchestrationOperateScope),
531
- );
534
+ const canReadFilesystem = useEnvironmentScope(environmentId, AuthFilesystemReadScope);
535
+ const [linkPath, setLinkPath] = useState<string | null>(null);
536
+ const metadataThreadRef = useContext(FileMetadataThreadContext);
537
+ const linkMetadataQuery =
538
+ linkPath !== null && canOpenHostEditor && canReadFilesystem
539
+ ? getFileMetadataQueryAtom(
540
+ environmentId,
541
+ resolvePathLinkTarget(linkPath, cwd),
542
+ cwd,
543
+ metadataThreadRef,
544
+ )
545
+ : null;
546
+ const canActivateTerminalLink = useEffectEvent((text: string) => {
547
+ if (isTerminalUrl(text)) return true;
548
+ if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return false;
549
+ if (text !== linkPath || !linkMetadataQuery) return false;
550
+ const metadata = AsyncResult.getOrElse(appAtomRegistry.get(linkMetadataQuery), () => null);
551
+ return metadata?.kind === "file" || metadata?.kind === "directory";
552
+ });
553
+ const validateTerminalLink = useEffectEvent(async (text: string) => {
554
+ if (isTerminalUrl(text)) return true;
555
+ if (
556
+ !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) ||
557
+ !readEnvironmentScope(environmentId, AuthFilesystemReadScope)
558
+ )
559
+ return false;
560
+ const query = getFileMetadataQueryAtom(
561
+ environmentId,
562
+ resolvePathLinkTarget(text, cwd),
563
+ cwd,
564
+ metadataThreadRef,
565
+ );
566
+ if (!query) return false;
567
+ const result = await executeAtomQuery(appAtomRegistry, query, { reportFailure: false });
568
+ return (
569
+ result._tag === "Success" &&
570
+ (result.value?.kind === "file" || result.value?.kind === "directory")
571
+ );
572
+ });
573
const serverConfig = useAtomValue(serverEnvironment.configValueAtom(environmentId));
574
const openInPreferredEditor = useOpenInPreferredEditor(
575
environmentId,
@@ -636,14 +677,18 @@ function TerminalSessionViewport({
677
consumePendingTerminalFocus(threadRef, terminalId);
678
}, [canOperateTerminal, terminalId, threadRef]);
679
639
- // Links re-read the grant on activation; only the hovered link's styling needs a nudge.
640
- const linkActivationScopeRef = useRef(canOpenHostEditor);
641
- // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- refreshes link activation styling on the imperative terminal surface when the editor grant changes
680
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- refreshes the imperative terminal's hovered link after filesystem metadata or editor permissions change
681
useEffect(() => {
643
- if (linkActivationScopeRef.current === canOpenHostEditor) return;
644
- linkActivationScopeRef.current = canOpenHostEditor;
645
- terminalRef.current?.refreshLinkActivation();
646
- }, [canOpenHostEditor]);
682
+ if (!linkMetadataQuery) {
683
+ terminalRef.current?.refreshLinkActivation();
684
+ return;
685
+ }
686
+ return appAtomRegistry.subscribe(
687
+ linkMetadataQuery,
688
+ () => terminalRef.current?.refreshLinkActivation(),
689
+ { immediate: true },
690
+ );
691
+ }, [linkMetadataQuery]);
692
693
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- pushes visibility into the terminal surface before paint and consumes focus requests made while hidden
694
useLayoutEffect(() => {
@@ -684,6 +729,8 @@ function TerminalSessionViewport({
729
beforeKey: (event) => handleBeforeKey(event),
730
onLinkActivate: (text, event) => handleLinkActivate(text, event),
731
canActivateLink: (text) => canActivateTerminalLink(text),
732
+ validateLink: (text) => validateTerminalLink(text),
733
+ onLinkHover: (text) => setLinkPath(text !== null && !isTerminalUrl(text) ? text : null),
734
// Surface listeners start before WASM loading finishes and the terminal handler exists.
735
onContextMenu: (event) => {
736
if (terminalRef.current) void showTerminalContextMenu(event);
@@ -992,7 +1039,11 @@ function TerminalSessionViewport({
1039
}
1040
1041
function handleLinkActivate(text: string, event: MouseEvent): void {
995
- if (!canActivateTerminalLink(text)) return;
1042
+ if (
1043
+ !isTerminalUrl(text) &&
1044
+ !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)
1045
+ )
1046
+ return;
1047
const latestTerminal = terminalRef.current;
1048
if (!latestTerminal) return;
1049
if (isTerminalUrl(text)) {
apps/web/src/hooks/useFileMetadata.ts
+23
-8
@@ -1,4 +1,8 @@
1
-import { AuthFilesystemReadScope, type EnvironmentId } from "@t3tools/contracts";
1
+import {
2
+ AuthFilesystemReadScope,
3
+ type EnvironmentId,
4
+ type ScopedThreadRef,
5
+} from "@t3tools/contracts";
6
import { resolvePathLinkTarget, splitFilePathPosition } from "@t3tools/shared/fileLinks";
7
import {
8
isAbsolutePath,
@@ -12,22 +16,21 @@ import { projectEnvironment } from "../state/projects";
16
import { useEnvironmentQuery } from "../state/query";
17
import { FileMetadataThreadContext } from "./FileMetadataThreadProvider";
18
15
-export function useFileMetadata(
16
- environmentId: EnvironmentId | null | undefined,
19
+export function getFileMetadataQueryAtom(
20
+ environmentId: EnvironmentId,
21
path: string,
22
cwd?: string,
23
+ threadRef?: ScopedThreadRef | null,
24
) {
20
- const canRead = useEnvironmentScope(environmentId ?? null, AuthFilesystemReadScope);
21
- const threadRef = useContext(FileMetadataThreadContext);
25
const hostPath = splitFilePathPosition(path).path;
26
const targetPath = normalizeProjectPathForComparison(
27
hostPath.startsWith("~/") || !cwd ? hostPath : resolvePathLinkTarget(hostPath, cwd),
28
);
29
const absolute = isAbsolutePath(targetPath) || targetPath.startsWith("~/");
27
- return useEnvironmentQuery(
30
+ return (
31
// Servers stat what they are asked about, and a network path leaks the
32
// Windows user's NTLM credentials to its host before any chip is clicked.
30
- environmentId && canRead && absolute && !isNetworkPath(targetPath) && targetPath.length <= 512
33
+ absolute && !isNetworkPath(targetPath) && targetPath.length <= 512
34
? projectEnvironment.fileMetadata({
35
environmentId,
36
input: {
@@ -35,6 +38,18 @@ export function useFileMetadata(
38
...(threadRef?.environmentId === environmentId ? { threadId: threadRef.threadId } : {}),
39
},
40
})
38
- : null,
41
+ : null
42
+ );
43
+}
44
+
45
+export function useFileMetadata(
46
+ environmentId: EnvironmentId | null | undefined,
47
+ path: string,
48
+ cwd?: string,
49
+) {
50
+ const canRead = useEnvironmentScope(environmentId ?? null, AuthFilesystemReadScope);
51
+ const threadRef = useContext(FileMetadataThreadContext);
52
+ return useEnvironmentQuery(
53
+ environmentId && canRead ? getFileMetadataQueryAtom(environmentId, path, cwd, threadRef) : null,
54
).data;
55
}
apps/web/src/terminal/ghostty/surface.test.ts
+144
@@ -537,6 +537,150 @@ describe("GhosttyTerminalSurface visibility", () => {
537
expect(onLinkActivate).not.toHaveBeenCalled();
538
});
539
540
+ it.each([
541
+ { scenario: "missing", exists: false },
542
+ { scenario: "file", exists: true },
543
+ { scenario: "replaced", exists: true },
544
+ { scenario: "superseded", exists: false },
545
+ { scenario: "hidden", exists: false },
546
+ { scenario: "dragged", exists: true },
547
+ { scenario: "keyboard-selected", exists: false },
548
+ { scenario: "selection-cleared", exists: true },
549
+ { scenario: "output-cleaned", exists: true },
550
+ ])(
551
+ "validates a quick click without waiting for hover: $scenario",
552
+ async ({ scenario, exists }) => {
553
+ vi.stubGlobal("navigator", { platform: "Linux x86_64" });
554
+ const harness = createHarness();
555
+ let resolveValidation!: (exists: boolean) => void;
556
+ const validation = new Promise<boolean>((resolve) => {
557
+ resolveValidation = resolve;
558
+ });
559
+ const validateLink = vi.fn(() => validation);
560
+ const onLinkActivate = vi.fn();
561
+ const surface = await harness.create({
562
+ beforeKey: () => true,
563
+ canActivateLink: () => false,
564
+ validateLink,
565
+ onLinkActivate,
566
+ });
567
+ surface.write("src/main.ts");
568
+ harness.flushFrame();
569
+ surface.selectAll();
570
+ expect(surface.getSelection()).toBe("src/main.ts");
571
+ harness.pointer("pointerdown", 5, 1);
572
+ expect(validateLink).toHaveBeenCalledWith("src/main.ts");
573
+ if (scenario === "dragged") harness.pointer("pointermove", 45, 1);
574
+ harness.pointer("pointerup", 5, 0);
575
+ expect(onLinkActivate).not.toHaveBeenCalled();
576
+ if (scenario === "replaced") {
577
+ surface.write("\r\x1b[2Ksrc/other.ts");
578
+ harness.flushFrame();
579
+ }
580
+ if (scenario === "superseded") harness.pointer("pointerdown", 5, 1);
581
+ if (scenario === "hidden") {
582
+ surface.setVisible(false);
583
+ surface.setVisible(true);
584
+ }
585
+ if (scenario === "keyboard-selected")
586
+ key(surface, "a", "KeyA", { ctrlKey: true, shiftKey: true });
587
+ if (scenario === "selection-cleared") surface.clearSelection();
588
+ if (scenario === "output-cleaned") surface.clearSelection({ source: "output" });
589
+ resolveValidation(exists);
590
+ await validation;
591
+ expect(onLinkActivate).toHaveBeenCalledTimes(
592
+ scenario === "file" || scenario === "output-cleaned" ? 1 : 0,
593
+ );
594
+ if (scenario === "missing" || scenario === "selection-cleared")
595
+ expect(surface.getSelection()).toBe("");
596
+ if (
597
+ scenario === "file" ||
598
+ scenario === "hidden" ||
599
+ scenario === "superseded" ||
600
+ scenario === "keyboard-selected"
601
+ ) {
602
+ expect(surface.getSelection()).not.toBe("");
603
+ }
604
+ },
605
+ );
606
+
607
+ it("only requests validation for a stable visible link under the pointer", async () => {
608
+ const harness = createHarness();
609
+ const onLinkHover = vi.fn();
610
+ const surface = await harness.create({ onLinkHover, canActivateLink: () => false });
611
+ surface.write("\x1b[?1049h\x1b[Hsrc/first.ts");
612
+ harness.flushFrame();
613
+ vi.advanceTimersByTime(250);
614
+ expect(onLinkHover).not.toHaveBeenCalled();
615
+
616
+ harness.pointer("pointermove", 5, 0);
617
+ expect(onLinkHover).toHaveBeenLastCalledWith("src/first.ts");
618
+ onLinkHover.mockClear();
619
+ for (let index = 0; index < 100; index++) {
620
+ surface.write(`\r\x1b[2Ksrc/file-${index}.ts`);
621
+ harness.flushFrame();
622
+ vi.advanceTimersByTime(10);
623
+ }
624
+ vi.advanceTimersByTime(239);
625
+ expect(onLinkHover.mock.calls.filter(([text]) => text !== null)).toEqual([]);
626
+ vi.advanceTimersByTime(1);
627
+ harness.flushFrame();
628
+ vi.advanceTimersByTime(1_000);
629
+ expect(onLinkHover.mock.calls.filter(([text]) => text !== null)).toEqual([["src/file-99.ts"]]);
630
+ onLinkHover.mockClear();
631
+
632
+ harness.pointer("pointerleave", 5, 0);
633
+ surface.write("\r\x1b[2Ksrc/recent.ts");
634
+ harness.flushFrame();
635
+ vi.advanceTimersByTime(150);
636
+ harness.pointer("pointermove", 5, 0);
637
+ vi.advanceTimersByTime(99);
638
+ expect(onLinkHover.mock.calls.filter(([text]) => text !== null)).toEqual([]);
639
+ vi.advanceTimersByTime(1);
640
+ expect(onLinkHover).toHaveBeenLastCalledWith("src/recent.ts");
641
+ onLinkHover.mockClear();
642
+
643
+ harness.pointer("pointerleave", 5, 0);
644
+ surface.write("\r\x1b[2Ksrc/still.ts");
645
+ harness.flushFrame();
646
+ vi.advanceTimersByTime(250);
647
+ surface.write("\x1b[2;1Hother output");
648
+ harness.flushFrame();
649
+ harness.pointer("pointermove", 5, 0);
650
+ expect(onLinkHover).toHaveBeenLastCalledWith("src/still.ts");
651
+ onLinkHover.mockClear();
652
+
653
+ surface.write("\x1b[H\x1b[2Ksrc/move.ts");
654
+ harness.flushFrame();
655
+ harness.pointer("pointermove", 45, 0);
656
+ vi.advanceTimersByTime(150);
657
+ surface.write("\r\x1b[2K src/move.ts");
658
+ harness.flushFrame();
659
+ vi.advanceTimersByTime(249);
660
+ expect(onLinkHover.mock.calls.filter(([text]) => text !== null)).toEqual([]);
661
+ vi.advanceTimersByTime(1);
662
+ expect(onLinkHover).toHaveBeenLastCalledWith("src/move.ts");
663
+ onLinkHover.mockClear();
664
+
665
+ for (const [index, cancel] of [
666
+ () => {
667
+ surface.write("\r\x1b[2Kplain text");
668
+ harness.flushFrame();
669
+ },
670
+ () => harness.pointer("pointerleave", 5, 0),
671
+ () => surface.setVisible(false),
672
+ () => surface.dispose(),
673
+ ].entries()) {
674
+ surface.setVisible(true);
675
+ surface.write(`\x1b[H\x1b[2Ksrc/next-${index}.ts`);
676
+ harness.flushFrame();
677
+ harness.pointer("pointermove", 5, 0);
678
+ cancel();
679
+ vi.advanceTimersByTime(250);
680
+ expect(onLinkHover.mock.calls.filter(([text]) => text !== null)).toEqual([]);
681
+ }
682
+ });
683
+
684
it.each([false, true])(
685
"uses visibility %s if it changes while WASM initializes",
686
async (visible) => {
apps/web/src/terminal/ghostty/surface.ts
+128
-10
@@ -35,6 +35,7 @@ const DEFAULT_TERMINAL_FONT_FAMILY =
35
const CONTENT_PADDING = 4;
36
const MIN_SCROLLBAR_THUMB_HEIGHT = 18;
37
const CURSOR_BLINK_INTERVAL_MS = 500;
38
+const TERMINAL_LINK_HOVER_DELAY_MS = 250;
39
/** End an unterminated synchronized update instead of freezing the last frame. */
40
const SYNCHRONIZED_OUTPUT_RENDER_TIMEOUT_MS = 500;
41
const TERMINAL_FONT_LOAD_TEXT = "iMW0@# .";
@@ -525,6 +526,9 @@ export interface GhosttyTerminalSurfaceOptions {
526
readonly beforeKey: (event: KeyboardEvent) => boolean;
527
readonly onLinkActivate: (text: string, event: MouseEvent) => void;
528
readonly canActivateLink?: (text: string) => boolean;
529
+ readonly validateLink?: (text: string) => Promise<boolean>;
530
+ /** Reports hovered candidates once their rendered text is stable for 250 ms; null cancels. */
531
+ readonly onLinkHover?: (text: string | null) => void;
532
/** The host must prevent the default menu; native Paste cannot reach a canvas terminal. */
533
readonly onContextMenu?: (event: MouseEvent) => void;
534
}
@@ -585,6 +589,8 @@ export class GhosttyTerminalSurface {
589
private mouseReportingButton: number | null = null;
590
private linkActivationPointerId: number | null = null;
591
private linkActivationLink: TerminalLinkWithRange | null = null;
592
+ private linkActivationValidation: Promise<boolean> | undefined;
593
+ private linkActivationRequestId = 0;
594
private linkActivationOrigin: {
595
x: number;
596
y: number;
@@ -592,6 +598,12 @@ export class GhosttyTerminalSurface {
598
} | null = null;
599
private hoveredLink: TerminalLinkWithRange | null = null;
600
private hoverPointer: { x: number; y: number } | null = null;
601
+ private linkHoverCandidate: TerminalLinkWithRange | null = null;
602
+ private linkHoverTimer: number | null = null;
603
+ private linkRowStability: Array<{
604
+ row: GhosttySnapshot["rowData"][number];
605
+ changedAt: number;
606
+ }> = [];
607
private selectionClickSequence: TerminalSelectionClickSequence | null = null;
608
private selectionMoved = false;
609
private composing = false;
@@ -740,6 +752,9 @@ export class GhosttyTerminalSurface {
752
this.forceFullRender = true;
753
this.scrollbarDirty = true;
754
if (!visible) {
755
+ this.linkActivationRequestId += 1;
756
+ this.clearHoveredLink();
757
+ this.linkRowStability = [];
758
this.cancelRender();
759
this.setSelectionAutoscroll(0);
760
return;
@@ -991,6 +1006,7 @@ export class GhosttyTerminalSurface {
1006
}
1007
1008
selectAll(): void {
1009
+ this.linkActivationRequestId += 1;
1010
this.clearPrimedCopy();
1011
const range = this.core.selectAll();
1012
this.selectionAnchorScreen = range?.start ?? null;
@@ -1033,7 +1049,8 @@ export class GhosttyTerminalSurface {
1049
};
1050
}
1051
1036
- clearSelection(): void {
1052
+ clearSelection({ source = "user" }: { source?: "user" | "output" } = {}): void {
1053
+ if (source === "user") this.linkActivationRequestId += 1;
1054
this.clearPrimedCopy();
1055
this.core.clearSelection();
1056
this.selectionEnd = null;
@@ -1061,6 +1078,7 @@ export class GhosttyTerminalSurface {
1078
dispose(): void {
1079
if (this.disposed) return;
1080
this.disposed = true;
1081
+ this.clearHoveredLink();
1082
this.stopObservingResize();
1083
document.fonts.removeEventListener("loadingdone", this.onFontsLoaded);
1084
this.dprMedia?.removeEventListener("change", this.onDevicePixelRatioChange);
@@ -1344,6 +1362,7 @@ export class GhosttyTerminalSurface {
1362
}
1363
1364
private readonly onPointerDown = (event: PointerEvent) => {
1365
+ this.linkActivationRequestId += 1;
1366
if (event.pointerType === "touch") {
1367
event.preventDefault();
1368
if (!event.isPrimary || this.touchScroll !== null) return;
@@ -1379,12 +1398,13 @@ export class GhosttyTerminalSurface {
1398
}
1399
if (event.button !== 0) return;
1400
const clickCount = this.recordSelectionClick(event);
1382
- const link = this.linkAt(event.clientX, event.clientY);
1401
+ const link = this.linkAt(event.clientX, event.clientY, true);
1402
if (link && !event.shiftKey && clickCount === 1) {
1403
event.preventDefault();
1404
event.stopPropagation();
1405
this.linkActivationPointerId = event.pointerId;
1406
this.linkActivationLink = link;
1407
+ this.linkActivationValidation = this.validateLink(link.text);
1408
this.linkActivationOrigin = {
1409
x: event.clientX,
1410
y: event.clientY,
@@ -1470,6 +1490,7 @@ export class GhosttyTerminalSurface {
1490
}
1491
this.linkActivationPointerId = null;
1492
this.linkActivationLink = null;
1493
+ this.linkActivationValidation = undefined;
1494
this.linkActivationOrigin = null;
1495
this.clearHoveredLink();
1496
this.beginSelection(
@@ -1577,14 +1598,65 @@ export class GhosttyTerminalSurface {
1598
1599
private clearHoveredLink(cursor = ""): void {
1600
this.hoverPointer = null;
1601
+ this.updateLinkHover(null);
1602
this.setHoveredLink(null);
1603
this.canvas.style.cursor = cursor;
1604
}
1605
1606
private refreshHoveredLink(): void {
1607
const pointer = this.hoverPointer;
1586
- const link = pointer ? this.linkAt(pointer.x, pointer.y) : null;
1587
- this.setHoveredLink(link);
1608
+ const link = pointer ? this.findLinkAt(pointer.x, pointer.y) : null;
1609
+ this.updateLinkHover(link);
1610
+ this.setHoveredLink(link && this.options.canActivateLink?.(link.text) !== false ? link : null);
1611
+ }
1612
+
1613
+ private updateLinkHover(link: TerminalLinkWithRange | null): void {
1614
+ if (!this.options.onLinkHover) return;
1615
+ if (link ? isSameTerminalLink(link, this.linkHoverCandidate) : this.linkHoverCandidate === null)
1616
+ return;
1617
+ this.linkHoverCandidate = link;
1618
+ if (this.linkHoverTimer !== null) {
1619
+ window.clearTimeout(this.linkHoverTimer);
1620
+ this.linkHoverTimer = null;
1621
+ }
1622
+ this.options.onLinkHover(null);
1623
+ if (link !== null) {
1624
+ const now = performance.now();
1625
+ let changedAt = 0;
1626
+ for (let y = link.range.start.y; y <= link.range.end.y; y++) {
1627
+ changedAt = Math.max(changedAt, this.linkRowStability[y]?.changedAt ?? now);
1628
+ }
1629
+ const delay = Math.max(0, TERMINAL_LINK_HOVER_DELAY_MS - (now - changedAt));
1630
+ if (delay === 0) {
1631
+ this.options.onLinkHover(link.text);
1632
+ return;
1633
+ }
1634
+ this.linkHoverTimer = window.setTimeout(() => {
1635
+ this.linkHoverTimer = null;
1636
+ this.options.onLinkHover?.(link.text);
1637
+ }, delay);
1638
+ }
1639
+ }
1640
+
1641
+ private updateLinkRowStability(reset: boolean): void {
1642
+ if (!this.options.onLinkHover || !this.snapshot) return;
1643
+ if (reset) {
1644
+ this.updateLinkHover(null);
1645
+ this.linkRowStability = [];
1646
+ }
1647
+ const now = performance.now();
1648
+ this.snapshot.rowData.forEach((row, y) => {
1649
+ const previous = this.linkRowStability[y]?.row;
1650
+ if (
1651
+ !previous ||
1652
+ previous.text !== row.text ||
1653
+ previous.cells.length !== row.cells.length ||
1654
+ previous.isWrapContinuation !== row.isWrapContinuation ||
1655
+ previous.wrapsToNext !== row.wrapsToNext
1656
+ )
1657
+ this.linkRowStability[y] = { row, changedAt: now };
1658
+ });
1659
+ this.linkRowStability.length = this.snapshot.rows;
1660
}
1661
1662
private setHoveredLink(link: TerminalLinkWithRange | null): void {
@@ -1617,8 +1689,8 @@ export class GhosttyTerminalSurface {
1689
this.sendMouse("press", ghosttyMouseButton(0), event);
1690
this.sendMouse("release", ghosttyMouseButton(0), event);
1691
} else {
1620
- const link = this.linkAt(event.clientX, event.clientY);
1621
- if (link) this.options.onLinkActivate(link.text, event);
1692
+ const link = this.linkAt(event.clientX, event.clientY, true);
1693
+ if (link) this.activateLink(link, event);
1694
else this.clearSelection();
1695
}
1696
return;
@@ -1628,15 +1700,17 @@ export class GhosttyTerminalSurface {
1700
event.preventDefault();
1701
event.stopPropagation();
1702
const link = this.linkActivationLink;
1703
+ const validation = this.linkActivationValidation;
1704
this.linkActivationPointerId = null;
1705
this.linkActivationLink = null;
1706
+ this.linkActivationValidation = undefined;
1707
this.linkActivationOrigin = null;
1708
if (this.canvas.hasPointerCapture(event.pointerId)) {
1709
this.canvas.releasePointerCapture(event.pointerId);
1710
}
1711
if (event.type !== "pointercancel") {
1638
- if (link && isSameTerminalLink(link, this.linkAt(event.clientX, event.clientY))) {
1639
- this.options.onLinkActivate(link.text, event);
1712
+ if (link && isSameTerminalLink(link, this.linkAt(event.clientX, event.clientY, true))) {
1713
+ this.activateLink(link, event, validation);
1714
}
1715
}
1716
return;
@@ -1988,10 +2062,12 @@ export class GhosttyTerminalSurface {
2062
this.metrics.height,
2063
anchorBottom,
2064
);
2065
+ const geometryChanged = canvasConfiguration !== null || nextOriginY !== this.originY;
2066
if (nextOriginY !== this.originY) {
2067
this.originY = nextOriginY;
2068
this.forceFullRender = true;
2069
}
2070
+ this.updateLinkRowStability(geometryChanged);
2071
this.refreshHoveredLink();
2072
renderGhosttySnapshot({
2073
context: this.context,
@@ -2080,9 +2156,51 @@ export class GhosttyTerminalSurface {
2156
};
2157
}
2158
2083
- private linkAt(clientX: number, clientY: number): TerminalLinkWithRange | null {
2159
+ private validateLink(text: string): Promise<boolean> | undefined {
2160
+ if (this.options.canActivateLink?.(text) !== false) return;
2161
+ const validation = this.options.validateLink?.(text);
2162
+ // A drag can abandon the press before activateLink subscribes to its result.
2163
+ void validation?.catch(() => {});
2164
+ return validation;
2165
+ }
2166
+
2167
+ private activateLink(
2168
+ link: TerminalLinkWithRange,
2169
+ event: MouseEvent,
2170
+ validation = this.validateLink(link.text),
2171
+ ): void {
2172
+ if (!validation) {
2173
+ this.options.onLinkActivate(link.text, event);
2174
+ return;
2175
+ }
2176
+ const requestId = this.linkActivationRequestId;
2177
+ void validation.then(
2178
+ (valid) => {
2179
+ if (
2180
+ this.disposed ||
2181
+ !this.visible ||
2182
+ requestId !== this.linkActivationRequestId ||
2183
+ !isSameTerminalLink(link, this.findLinkAt(event.clientX, event.clientY))
2184
+ )
2185
+ return;
2186
+ if (valid) this.options.onLinkActivate(link.text, event);
2187
+ else this.clearSelection();
2188
+ },
2189
+ () => {},
2190
+ );
2191
+ }
2192
+
2193
+ private linkAt(
2194
+ clientX: number,
2195
+ clientY: number,
2196
+ allowValidation = false,
2197
+ ): TerminalLinkWithRange | null {
2198
const link = this.findLinkAt(clientX, clientY);
2085
- return link && this.options.canActivateLink?.(link.text) !== false ? link : null;
2199
+ return link &&
2200
+ ((allowValidation && this.options.validateLink) ||
2201
+ this.options.canActivateLink?.(link.text) !== false)
2202
+ ? link
2203
+ : null;
2204
}
2205
2206
private findLinkAt(clientX: number, clientY: number): TerminalLinkWithRange | null {