Open History to see the last commit
1import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts";
2import { scopedThreadKey } from "@t3tools/client-runtime/environment";
3import { expect, it, vi } from "vite-plus/test";
4import { act, render } from "../../test/render";
5import { useClosedViewStore } from "../closedViewStore";
6import { selectThreadRightPanelState, useRightPanelStore } from "../rightPanelStore";
7import { useTerminalUiStateStore } from "../terminalUiStateStore";
8import { useRightPanelSurfaceClose } from "./useRightPanelSurfaceClose";
9
10const fixture = vi.hoisted(() => ({
11 confirm: (_labels: readonly string[]): Promise<boolean> => Promise.resolve(false),
12 allowed: new Set<string>(),
13 sessions: new Map<string, string>(),
14 failClose: false,
15 previewSessions: {} as Record<string, unknown>,
16 shells: new Map<string, unknown>(),
17}));
18vi.mock("../lib/terminalCloseConfirm", () => ({
19 confirmTerminalClose: (labels: readonly string[]) => fixture.confirm(labels),
20}));
21vi.mock("../components/ChatView.logic", () => ({
22 agentControlledBrowserCloseConfirmation: () => null,
23}));
24vi.mock("../previewStateStore", () => ({
25 useThreadPreviewState: () => ({ sessions: fixture.previewSessions, desktopByTabId: {} }),
26 setActivePreviewTab: () => {},
27 beginPreviewSessionClose: () => {},
28 cancelPreviewSessionClose: () => {},
29}));
30vi.mock("../browser/previewRuntime", () => ({ rendersServerTabNatively: () => false }));
31vi.mock("../state/primaryEnvironment", async () => {
32 const { Atom } = await import("effect/reactivity");
33 return { primaryEnvironmentIdAtom: Atom.make(null) };
34});
35vi.mock("../state/session", () => ({
36 useEnvironmentScope: (id: string) => fixture.allowed.has(id),
37 readEnvironmentScope: (id: string) => fixture.allowed.has(id),
38}));
39vi.mock("../state/entities", () => ({
40 useQuietThreadShell: () => null,
41 useProject: () => null,
42 readThreadShell: (ref: ScopedThreadRef) => fixture.shells.get(ref.threadId) ?? null,
43 waitForThreadShellRemoval: async () => true,
44}));
45vi.mock("../state/terminalSessions", () => ({ useKnownTerminalSessions: () => null }));
46vi.mock("../composerDraftStore", async () => {
47 const Schema = await import("effect/Schema");
48 return {
49 useComposerDraftStore: () => null,
50 DraftId: Schema.String.pipe(Schema.brand("DraftId")),
51 };
52});
53vi.mock("../state/use-atom-command", () => ({
54 useAtomCommand:
55 (_command: unknown, label: string) =>
56 async (request: {
57 environmentId: string;
58 input: { threadId: string; terminalId: string; data?: string };
59 }) => {
60 const key = `${request.environmentId}/${request.input.threadId}/${request.input.terminalId}`;
61 if (label === "terminal close" && fixture.failClose) return { _tag: "Failure" };
62 if (label === "terminal close" || label === "terminal write") fixture.sessions.delete(key);
63 return { _tag: "Success" };
64 },
65}));
66// The commands are replaced above; importing their runtime would connect a client.
67vi.mock("../state/terminal", () => ({ terminalEnvironment: { open: {}, close: {}, write: {} } }));
68vi.mock("../state/preview", () => ({ previewEnvironment: { close: {} } }));
69vi.mock("../state/threads", () => ({ threadEnvironment: { delete: {} } }));
70vi.mock("../state/shell", () => ({ environmentShell: { stateValueAtom: () => null } }));
71vi.mock("@t3tools/client-runtime/state/runtime", () => ({
72 isAtomCommandInterrupted: () => false,
73}));
74
75function setup(mode: "single" | "all") {
76 fixture.allowed = new Set(["environment-a", "environment-b"]);
77 fixture.sessions = new Map();
78 fixture.failClose = false;
79 useRightPanelStore.setState({ byThreadKey: {} });
80 useTerminalUiStateStore.setState({ terminalUiStateByThreadKey: {} });
81 const original: ScopedThreadRef = {
82 environmentId: EnvironmentId.make("environment-a"),
83 threadId: ThreadId.make("thread-a"),
84 };
85 const other: ScopedThreadRef = {
86 environmentId: EnvironmentId.make("environment-b"),
87 threadId: ThreadId.make("thread-b"),
88 };
89 for (const ref of [original, other]) {
90 fixture.sessions.set(`${ref.environmentId}/${ref.threadId}/term-1`, "history to preserve");
91 useRightPanelStore.getState().openTerminal(ref, "term-1");
92 }
93 const surface = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, original)
94 .surfaces[0]!;
95 let resolve!: (confirmed: boolean) => void;
96 const confirmation = new Promise<boolean>((done) => {
97 resolve = done;
98 });
99 fixture.confirm = () => confirmation;
100 function Harness({ threadRef }: { threadRef: ScopedThreadRef }) {
101 const { closeSurface, closeAllSurfaces } = useRightPanelSurfaceClose({
102 threadRef,
103 terminalLabelsById: new Map(),
104 });
105 return (
106 <button onClick={() => (mode === "all" ? closeAllSurfaces() : closeSurface(surface))}>
107 Close original terminal
108 </button>
109 );
110 }
111 return { original, other, Harness, resolve };
112}
113
114it.each([
115 { mode: "single", failClose: false },
116 { mode: "single", failClose: true },
117 { mode: "all", failClose: false },
118 { mode: "all", failClose: true },
119] as const)(
120 "keeps a pending $mode close on its original environment and thread, fallback=$failClose",
121 async ({ mode, failClose }) => {
122 const { original, other, Harness, resolve } = setup(mode);
123 fixture.failClose = failClose;
124 await using screen = await render(<Harness threadRef={original} />);
125 await screen.getByRole("button").click();
126 expect(fixture.sessions.size).toBe(2);
127 await screen.rerender(<Harness threadRef={other} />);
128 await act(async () => {
129 resolve(true);
130 });
131 expect([...fixture.sessions]).toEqual([
132 ["environment-b/thread-b/term-1", "history to preserve"],
133 ]);
134 const panels = useRightPanelStore.getState().byThreadKey;
135 expect(selectThreadRightPanelState(panels, original).surfaces).toEqual([]);
136 expect(selectThreadRightPanelState(panels, other).surfaces).toHaveLength(1);
137 },
138);
139
140it.each([
141 { mode: "single", outcome: "cancel" },
142 { mode: "single", outcome: "revoked" },
143 { mode: "all", outcome: "cancel" },
144 { mode: "all", outcome: "revoked" },
145] as const)(
146 "leaves both sessions intact when $mode confirmation is $outcome",
147 async ({ mode, outcome }) => {
148 const { original, other, Harness, resolve } = setup(mode);
149 await using screen = await render(<Harness threadRef={original} />);
150 await screen.getByRole("button").click();
151 expect(fixture.sessions.size).toBe(2);
152 await screen.rerender(<Harness threadRef={other} />);
153 if (outcome === "revoked") fixture.allowed.delete(original.environmentId);
154 await act(async () => {
155 resolve(outcome !== "cancel");
156 });
157 expect(fixture.sessions.size).toBe(2);
158 expect(
159 useRightPanelStore.getState().byThreadKey[scopedThreadKey(other)]?.surfaces,
160 ).toHaveLength(1);
161 },
162);
163
164it("reopens the active browser first after closing every browser tab", async () => {
165 fixture.allowed = new Set(["environment-a"]);
166 const ref: ScopedThreadRef = {
167 environmentId: EnvironmentId.make("environment-a"),
168 threadId: ThreadId.make("thread-browsers"),
169 };
170 fixture.previewSessions = Object.fromEntries(
171 ["tab-a", "tab-b"].map((tabId) => [tabId, { tabId, navStatus: { _tag: "Idle" } }]),
172 );
173 useRightPanelStore.setState({ byThreadKey: {} });
174 useClosedViewStore.setState({ entries: [] });
175 useRightPanelStore.getState().openBrowser(ref, "tab-a");
176 useRightPanelStore.getState().openBrowser(ref, "tab-b");
177 useRightPanelStore.getState().activateSurface(ref, "browser:tab-a");
178 function Harness() {
179 const { closeAllSurfaces } = useRightPanelSurfaceClose({
180 threadRef: ref,
181 terminalLabelsById: new Map(),
182 });
183 return <button onClick={() => closeAllSurfaces()}>Close all</button>;
184 }
185 await using screen = await render(<Harness />);
186 await screen.getByRole("button").click();
187 await vi.waitFor(() => expect(useClosedViewStore.getState().entries).toHaveLength(2));
188 expect(
189 useClosedViewStore
190 .getState()
191 .entries.map((entry) => (entry.kind === "browser" ? entry.snapshot.tabId : null)),
192 ).toEqual(["tab-a", "tab-b"]);
193});
194
195it("does not offer a side chat for reopen once closing it deleted it", async () => {
196 fixture.allowed = new Set(["environment-a"]);
197 const ref: ScopedThreadRef = {
198 environmentId: EnvironmentId.make("environment-a"),
199 threadId: ThreadId.make("thread-parent"),
200 };
201 const sideChatId = ThreadId.make("thread-side-chat");
202 fixture.shells = new Map([
203 [
204 sideChatId,
205 {
206 id: sideChatId,
207 lineage: { sideChat: true, parentThreadId: ref.threadId },
208 },
209 ],
210 ]);
211 useRightPanelStore.setState({ byThreadKey: {} });
212 useClosedViewStore.setState({ entries: [] });
213 useRightPanelStore.getState().openThread(ref, sideChatId);
214 const surface = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, ref)
215 .surfaces[0]!;
216 function Harness() {
217 const { closeSurface } = useRightPanelSurfaceClose({
218 threadRef: ref,
219 terminalLabelsById: new Map(),
220 });
221 return <button onClick={() => closeSurface(surface)}>Close side chat</button>;
222 }
223 try {
224 await using screen = await render(<Harness />);
225 await screen.getByRole("button").click();
226 await vi.waitFor(() => expect(useClosedViewStore.getState().entries).toEqual([]));
227 } finally {
228 fixture.shells = new Map();
229 }
230});