Open History to see the last commit
1import {
2 AuthTerminalOperateScope,
3 EnvironmentId,
4 ThreadId,
5 type AuthEnvironmentScope,
6} from "@t3tools/contracts";
7import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
8import { nextTerminalAttachSeedState } from "@t3tools/client-runtime/state/terminal";
9import { AsyncResult } from "effect/reactivity";
10import { act, create, type ReactTestRenderer } from "react-test-renderer";
11import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
12import type {
13 GhosttyTerminalSurface,
14 GhosttyTerminalSurfaceOptions,
15} from "~/terminal/ghostty/surface";
16
17const state = vi.hoisted(() => ({
18 allowed: true,
19 listeners: new Set<() => void>(),
20 resize: vi.fn(),
21 otherCommand: vi.fn(),
22 createSurface:
23 vi.fn<
24 (
25 mount: HTMLElement,
26 options: GhosttyTerminalSurfaceOptions,
27 ) => Promise<GhosttyTerminalSurface>
28 >(),
29}));
30
31vi.mock("@effect/atom-react", () => ({ useAtomValue: () => null }));
32vi.mock("../hooks/useSettings", () => ({
33 getClientSettings: () => DEFAULT_CLIENT_SETTINGS,
34 useClientSettings: (select: (settings: typeof DEFAULT_CLIENT_SETTINGS) => unknown) =>
35 select(DEFAULT_CLIENT_SETTINGS),
36}));
37vi.mock("../editorPreferences", () => ({ useOpenInPreferredEditor: () => state.otherCommand }));
38vi.mock("../localApi", () => ({ readLocalApi: () => null }));
39vi.mock("../state/server", () => ({
40 serverEnvironment: { configValueAtom: () => "config" },
41}));
42vi.mock("../state/preview", () => ({ previewEnvironment: { open: "open" } }));
43vi.mock("../state/terminal", () => ({ terminalEnvironment: { resize: "resize", write: "write" } }));
44vi.mock("../state/use-atom-command", () => ({
45 useAtomCommand: (command: string) => (command === "resize" ? state.resize : state.otherCommand),
46}));
47vi.mock("../state/terminalSessions", () => ({
48 useAttachedTerminalSession: () => session,
49}));
50vi.mock("~/terminal/ghostty/surface", () => ({
51 GhosttyTerminalSurface: { create: state.createSurface },
52}));
53vi.mock("../state/session", async () => {
54 const { useSyncExternalStore } = await import("react");
55 const readEnvironmentScope = (id: EnvironmentId | null, scope: AuthEnvironmentScope) =>
56 id !== null &&
57 (scope !== AuthTerminalOperateScope || id !== threadRef.environmentId || state.allowed);
58 return {
59 readEnvironmentScope,
60 useEnvironmentScope: (id: EnvironmentId | null, scope: AuthEnvironmentScope) =>
61 useSyncExternalStore(
62 (listener) => {
63 state.listeners.add(listener);
64 return () => state.listeners.delete(listener);
65 },
66 () => readEnvironmentScope(id, scope),
67 ),
68 };
69});
70
71import { TerminalViewport } from "./ThreadTerminalDrawer";
72
73const threadRef = {
74 environmentId: EnvironmentId.make("secondary-terminal"),
75 threadId: ThreadId.make("thread"),
76};
77const session = { ...nextTerminalAttachSeedState(), status: "running" as const, version: 1 };
78let renderer: ReactTestRenderer | undefined;
79
80beforeEach(() => {
81 state.allowed = true;
82 state.listeners.clear();
83 state.resize.mockReset().mockResolvedValue(AsyncResult.success(undefined));
84 state.otherCommand.mockReset().mockResolvedValue(AsyncResult.success(undefined));
85 // A surface can report its initial grid while asynchronous WASM setup is
86 // pending. Keep that unrelated setup pending while exercising its callback.
87 state.createSurface.mockReset().mockReturnValue(new Promise(() => undefined));
88 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
89 vi.stubGlobal("document", {
90 body: {},
91 documentElement: { classList: { contains: () => false } },
92 querySelector: () => null,
93 createElement: () => ({ getContext: () => null }),
94 });
95 vi.stubGlobal("getComputedStyle", () => ({
96 colorScheme: "light",
97 backgroundColor: "",
98 color: "",
99 getPropertyValue: () => "",
100 }));
101});
102
103afterEach(async () => {
104 await act(async () => renderer?.unmount());
105 renderer = undefined;
106 vi.unstubAllGlobals();
107});
108
109it("rechecks the target terminal grant when a retained surface callback reports a resize", async () => {
110 await act(async () => {
111 renderer = create(
112 <TerminalViewport
113 advancedTypography={false}
114 threadRef={threadRef}
115 threadId={threadRef.threadId}
116 terminalId="terminal-1"
117 terminalLabel="Terminal 1"
118 cwd="/repo"
119 onSessionExited={state.otherCommand}
120 focusRequestId={0}
121 autoFocus={false}
122 visible={true}
123 resizeEpoch={0}
124 drawerHeight={200}
125 keybindings={[]}
126 />,
127 { createNodeMock: () => ({ closest: () => null, contains: () => false }) },
128 );
129 });
130 expect(state.createSurface).toHaveBeenCalledOnce();
131 const onResize = state.createSurface.mock.calls[0]![1].onResize;
132 if (!onResize) throw new Error("The terminal did not register its resize callback.");
133
134 onResize(80, 24);
135 expect(state.resize).toHaveBeenCalledExactlyOnceWith({
136 environmentId: threadRef.environmentId,
137 input: { threadId: threadRef.threadId, terminalId: "terminal-1", cols: 80, rows: 24 },
138 });
139
140 // The connection updates before React commits its external-store update.
141 // Other environments retain access; only this terminal's target is revoked.
142 state.allowed = false;
143 onResize(120, 40);
144 expect(state.resize).toHaveBeenCalledTimes(1);
145
146 state.allowed = true;
147 onResize(100, 30);
148 expect(state.resize).toHaveBeenCalledTimes(2);
149 expect(state.resize).toHaveBeenLastCalledWith({
150 environmentId: threadRef.environmentId,
151 input: { threadId: threadRef.threadId, terminalId: "terminal-1", cols: 100, rows: 30 },
152 });
153});