Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadTerminalDrawer.permissions.browser.test.tsx

189 lines6.4 KB

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 } from "react";
11import { createRoot, type Root } from "react-dom/client";
12import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
13import type {
14 GhosttyTerminalSurface,
15 GhosttyTerminalSurfaceOptions,
16} from "~/terminal/ghostty/surface";
17​
18const state = vi.hoisted(() => ({
19 allowed: true,
20 listeners: new Set<() => void>(),
21 resize: vi.fn(),
22 otherCommand: vi.fn(),
23 createSurface:
24 vi.fn<
25 (
26 mount: HTMLElement,
27 options: GhosttyTerminalSurfaceOptions,
28 ) => Promise<GhosttyTerminalSurface>
29 >(),
30}));
31​
32vi.mock(import("@effect/atom-react"), async (original) => ({
33 ...(await original()),
34 useAtomValue: (() => null) as never,
35}));
36vi.mock(import("../hooks/useSettings"), async (original) => ({
37 ...(await original()),
38 getClientSettings: () => DEFAULT_CLIENT_SETTINGS,
39 useClientSettings: ((select: (settings: typeof DEFAULT_CLIENT_SETTINGS) => unknown) =>
40 select(DEFAULT_CLIENT_SETTINGS)) as never,
41}));
42vi.mock(import("../editorPreferences"), async (original) => ({
43 ...(await original()),
44 useOpenInPreferredEditor: (() => state.otherCommand) as never,
45}));
46vi.mock(import("../state/terminal"), async (original) => {
47 const actual = await original();
48 return {
49 ...actual,
50 terminalEnvironment: { ...actual.terminalEnvironment, resize: "resize" as never },
51 };
52});
53vi.mock(import("../state/use-atom-command"), async (original) => ({
54 ...(await original()),
55 useAtomCommand: ((command: unknown) =>
56 command === "resize" ? state.resize : state.otherCommand) as never,
57}));
58vi.mock(import("../state/terminalSessions"), async (original) => ({
59 ...(await original()),
60 useAttachedTerminalSession: (() => session) as never,
61}));
62vi.mock(import("~/terminal/ghostty/surface"), async (original) => ({
63 ...(await original()),
64 GhosttyTerminalSurface: { create: state.createSurface } as never,
65}));
66vi.mock(import("../state/session"), async (original) => {
67 const { useSyncExternalStore } = await import("react");
68 const readEnvironmentScope = (id: EnvironmentId | null, scope: AuthEnvironmentScope) =>
69 id !== null &&
70 (scope !== AuthTerminalOperateScope || id !== threadRef.environmentId || state.allowed);
71 return {
72 ...(await original()),
73 readEnvironmentScope,
74 useEnvironmentScope: (id: EnvironmentId | null, scope: AuthEnvironmentScope) =>
75 useSyncExternalStore(
76 (listener) => {
77 state.listeners.add(listener);
78 return () => state.listeners.delete(listener);
79 },
80 () => readEnvironmentScope(id, scope),
81 ),
82 };
83});
84​
85import { TerminalViewport } from "./ThreadTerminalDrawer";
86import { KeptViewLifetimeContext, createKeptViewLifetime } from "./keptView";
87​
88const threadRef = {
89 environmentId: EnvironmentId.make("secondary-terminal"),
90 threadId: ThreadId.make("thread"),
91};
92const session = { ...nextTerminalAttachSeedState(), status: "running" as const, version: 1 };
93let root: Root;
94let container: HTMLDivElement;
95​
96beforeEach(() => {
97 state.allowed = true;
98 state.listeners.clear();
99 state.resize.mockReset().mockResolvedValue(AsyncResult.success(undefined));
100 state.otherCommand.mockReset().mockResolvedValue(AsyncResult.success(undefined));
101 // A surface can report its initial grid while asynchronous WASM setup is
102 // pending. Keep that unrelated setup pending while exercising its callback.
103 state.createSurface.mockReset().mockReturnValue(new Promise(() => undefined));
104 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
105 container = document.createElement("div");
106 document.body.append(container);
107 root = createRoot(container);
108});
109​
110afterEach(async () => {
111 await act(async () => root.unmount());
112 container.remove();
113 vi.unstubAllGlobals();
114});
115​
116it("keeps a replacement terminal session visible while the drawer stays open", async () => {
117 const lifetime = createKeptViewLifetime();
118 const viewport = (terminalId: string) => (
119 <KeptViewLifetimeContext value={lifetime}>
120 <TerminalViewport
121 advancedTypography={false}
122 threadRef={threadRef}
123 threadId={threadRef.threadId}
124 terminalId={terminalId}
125 terminalLabel="Terminal"
126 cwd="/repo"
127 onSessionExited={state.otherCommand}
128 focusRequestId={0}
129 autoFocus={false}
130 visible={true}
131 resizeEpoch={0}
132 drawerHeight={200}
133 keybindings={[]}
134 />
135 </KeptViewLifetimeContext>
136 );
137 try {
138 await act(async () => root.render(viewport("terminal-1")));
139 expect(state.createSurface.mock.calls[0]![1].visible).toBe(true);
140 await act(async () => root.render(viewport("terminal-2")));
141 expect(state.createSurface).toHaveBeenCalledTimes(2);
142 expect(state.createSurface.mock.calls[1]![1].visible).toBe(true);
143 } finally {
144 lifetime.dispose();
145 }
146});
147​
148it("rechecks the target terminal grant when a retained surface callback reports a resize", async () => {
149 await act(async () =>
150 root.render(
151 <TerminalViewport
152 advancedTypography={false}
153 threadRef={threadRef}
154 threadId={threadRef.threadId}
155 terminalId="terminal-1"
156 terminalLabel="Terminal 1"
157 cwd="/repo"
158 onSessionExited={state.otherCommand}
159 focusRequestId={0}
160 autoFocus={false}
161 visible={true}
162 resizeEpoch={0}
163 drawerHeight={200}
164 keybindings={[]}
165 />,
166 ),
167 );
168 expect(state.createSurface).toHaveBeenCalledOnce();
169 const onResize = state.createSurface.mock.calls[0]![1].onResize;
170 if (!onResize) throw new Error("The terminal did not register its resize callback.");
171​
172 onResize(80, 24);
173 expect(state.resize).toHaveBeenCalledExactlyOnceWith({
174 environmentId: threadRef.environmentId,
175 input: { threadId: threadRef.threadId, terminalId: "terminal-1", cols: 80, rows: 24 },
176 });
177​
178 state.allowed = false;
179 onResize(120, 40);
180 expect(state.resize).toHaveBeenCalledTimes(1);
181​
182 state.allowed = true;
183 onResize(100, 30);
184 expect(state.resize).toHaveBeenCalledTimes(2);
185 expect(state.resize).toHaveBeenLastCalledWith({
186 environmentId: threadRef.environmentId,
187 input: { threadId: threadRef.threadId, terminalId: "terminal-1", cols: 100, rows: 30 },
188 });
189});