Open History to see the last commit
1import { RegistryContext } from "@effect/atom-react";
2import { scopeThreadRef } from "@t3tools/client-runtime/environment";
3import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
4import * as Cause from "effect/Cause";
5import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
6import { expect, it, vi } from "vite-plus/test";
7
8import { act, render } from "../../../test/render";
9import { isMacPlatform } from "../../lib/utils";
10import { linkedThreadSurface } from "../../linkedThreadSurface";
11import {
12 serializeTableElementToCsv,
13 serializeTableElementToHtml,
14 serializeTableElementToMarkdown,
15} from "../../markdown-clipboard";
16import { selectThreadRightPanelState, useRightPanelStore } from "../../rightPanelStore";
17import { MarkdownThreadLink } from "./MarkdownThreadLink";
18
19const HERE = scopeThreadRef(EnvironmentId.make("environment"), ThreadId.make("here"));
20const panel = () => selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, HERE);
21
22const state = vi.hoisted(() => ({
23 reply: null as unknown,
24 remote: null as unknown,
25 cached: null as unknown,
26 linked: new Map<string, string>(),
27 connected: [] as Array<string>,
28}));
29vi.mock(import("../../state/entities"), () => ({
30 useThreadShell: ((ref: { environmentId: string } | null) =>
31 ref?.environmentId === "remote"
32 ? state.remote
33 : ref?.environmentId === "saved-vm"
34 ? state.cached
35 : null) as never,
36 useThreadRefs: (enabled = true) =>
37 enabled
38 ? [{ environmentId: EnvironmentId.make("remote"), threadId: ThreadId.make("older-thread") }]
39 : [],
40 useProject: (ref: { projectId: string } | null) =>
41 ref?.projectId === "essay-project" ? ({ title: "Essays" } as never) : null,
42}));
43vi.mock(import("../../state/environments"), () => ({
44 // The click rule reads the client setting, whose module asks for these.
45 useEnvironments: (() => []) as never,
46 usePrimaryEnvironment: (() => null) as never,
47 useEnvironmentIdentities: () => [
48 { environmentId: EnvironmentId.make("environment"), label: "Here" },
49 { environmentId: EnvironmentId.make("remote"), label: "Remote" },
50 { environmentId: EnvironmentId.make("saved-vm"), label: "Saved VM" },
51 ],
52 useConnectedEnvironmentIds: () => state.connected as never,
53}));
54vi.mock(import("../../state/peerLinks"), () => ({
55 useLinkedEnvironments: ((environmentId: string | null) =>
56 environmentId === null ? new Map() : state.linked) as never,
57}));
58vi.mock(import("../ProjectFavicon"), () => ({
59 ProjectFavicon: () => (
60 <span role="img" aria-label="Essays project icon">
61 P
62 </span>
63 ),
64}));
65vi.mock(import("../ThreadChipHoverCard"), () => ({ ThreadChipHoverCard: () => <span /> }));
66vi.mock(import("../contextChipParts"), () => ({
67 UnresolvedChip: ({ label }: { label: string }) => <span>{label}</span>,
68}));
69vi.mock(import("../../state/orchestration"), () => ({
70 orchestrationEnvironment: { threadLinkMetadata: () => state.reply } as never,
71}));
72
73function setup() {
74 const reply = Atom.make<
75 AsyncResult.AsyncResult<Record<string, { title: string; projectId: ProjectId | null }>, string>
76 >(AsyncResult.initial());
77 state.reply = reply;
78 state.linked = new Map();
79 state.cached = null;
80 state.connected = ["environment", "remote"];
81 useRightPanelStore.setState({ byThreadKey: {} });
82 state.remote = {
83 environmentId: EnvironmentId.make("remote"),
84 id: ThreadId.make("older-thread"),
85 title: "Remote thread",
86 projectId: ProjectId.make("essay-project"),
87 lineage: {
88 rootThreadId: ThreadId.make("older-thread"),
89 parentThreadId: null,
90 relationshipToParent: null,
91 },
92 };
93 return { reply, registry: AtomRegistry.make() };
94}
95
96it.each([
97 { legacy: false, encoded: false },
98 { legacy: true, encoded: false },
99 { legacy: false, encoded: true },
100])(
101 "resolves an unloaded thread with its icon and the correct destination, %j",
102 async ({ legacy, encoded }) => {
103 const { reply, registry } = setup();
104 using _registry = { [Symbol.dispose]: () => registry.dispose() };
105 const environmentId = EnvironmentId.make("environment");
106 const threadId = ThreadId.make(encoded ? "older%2Dthread" : "older-thread");
107 await using screen = await render(
108 <RegistryContext value={registry}>
109 <MarkdownThreadLink
110 environmentId={environmentId}
111 link={{ environmentId: legacy ? null : environmentId, threadId }}
112 label={null}
113 />
114 </RegistryContext>,
115 );
116 await expect
117 .element(screen.getByRole("link", { name: "Thread, Thread", exact: true }))
118 .toBeVisible();
119 await act(() => registry.set(reply, AsyncResult.failure(Cause.fail("offline"))));
120 await expect
121 .element(screen.getByRole("link", { name: "Thread, Thread", exact: true }))
122 .toBeVisible();
123 await act(() =>
124 registry.set(
125 reply,
126 AsyncResult.success({
127 [threadId]: { title: "Older essay", projectId: ProjectId.make("essay-project") },
128 ...(encoded
129 ? {
130 "older-thread": {
131 title: "Decoded essay",
132 projectId: ProjectId.make("essay-project"),
133 },
134 }
135 : {}),
136 }),
137 ),
138 );
139 const link = screen.getByRole("link", { name: "Thread, Older essay" });
140 await expect.element(link).toBeVisible();
141 await expect.element(screen.getByRole("img", { name: "Essays project icon" })).toBeVisible();
142 await link.click();
143 await vi.waitFor(() =>
144 expect(screen.router?.state.location.pathname).toBe(
145 `/environment/${encodeURIComponent(threadId)}`,
146 ),
147 );
148 if (encoded) {
149 await act(() =>
150 registry.set(
151 reply,
152 AsyncResult.success({
153 "older-thread": { title: "Decoded essay", projectId: ProjectId.make("essay-project") },
154 }),
155 ),
156 );
157 const decoded = screen.getByRole("link", { name: "Thread, Decoded essay" });
158 await expect.element(decoded).toBeVisible();
159 await decoded.click();
160 await vi.waitFor(() =>
161 expect(screen.router?.state.location.pathname).toBe("/environment/older-thread"),
162 );
163 }
164 await act(() => registry.set(reply, AsyncResult.success({})));
165 if (legacy) {
166 const remote = screen.getByRole("link", { name: "Thread, Remote thread" });
167 await expect.element(remote).toBeVisible();
168 await remote.click();
169 await vi.waitFor(() =>
170 expect(screen.router?.state.location.pathname).toBe("/remote/older-thread"),
171 );
172 } else {
173 await expect
174 .element(screen.getByText("Thread no longer available", { exact: true }))
175 .toBeVisible();
176 }
177 },
178);
179
180it("names a thread on a machine this client has no connection to, without waiting on it", async () => {
181 const { registry } = setup();
182 using _registry = { [Symbol.dispose]: () => registry.dispose() };
183 await using screen = await render(
184 <RegistryContext value={registry}>
185 <MarkdownThreadLink
186 environmentId={EnvironmentId.make("environment")}
187 link={{ environmentId: EnvironmentId.make("peer"), threadId: ThreadId.make("peer-thread") }}
188 label={null}
189 />
190 </RegistryContext>,
191 );
192 await expect
193 .element(screen.getByText("Thread on another machine", { exact: true }))
194 .toBeVisible();
195 await expect.element(screen.getByRole("link")).not.toBeInTheDocument();
196});
197
198it.for([
199 { name: "a machine only this environment links to", linkedId: "linked-vm" },
200 { name: "a saved machine this client is not connected to", linkedId: "saved-vm" },
201])("opens a thread on $name as a read through the link", async ({ linkedId }) => {
202 const { registry } = setup();
203 using _registry = { [Symbol.dispose]: () => registry.dispose() };
204 state.linked = new Map([[linkedId, "fs-17"]]);
205 const environmentId = EnvironmentId.make("environment");
206 const link = { environmentId: EnvironmentId.make(linkedId), threadId: ThreadId.make("there") };
207 await using screen = await render(
208 <RegistryContext value={registry}>
209 <MarkdownThreadLink environmentId={environmentId} threadRef={HERE} link={link} label={null} />
210 </RegistryContext>,
211 );
212 const chip = screen.getByRole("button", { name: "Thread, Thread on fs-17" });
213 await chip.click();
214 const surface = linkedThreadSurface({
215 viaEnvironmentId: environmentId,
216 ...link,
217 label: "fs-17",
218 title: null,
219 });
220 expect(panel()).toMatchObject({ isOpen: true, activeSurfaceId: surface.id, surfaces: [surface] });
221 await chip.click();
222 expect(panel().surfaces).toHaveLength(1);
223 expect(screen.router?.state.location.pathname).toBe("/");
224 // The modifier reads it on the main screen instead, through the same environment.
225 await chip.click({ modifiers: [isMacPlatform(navigator.platform) ? "Meta" : "Control"] });
226 await vi.waitFor(() =>
227 expect(screen.router?.state.location.pathname).toBe(`/linked/environment/${linkedId}/there`),
228 );
229 expect(panel().surfaces).toHaveLength(1);
230});
231
232it("reads through the link when a disconnected machine's thread is only cached here", async () => {
233 const { registry } = setup();
234 using _registry = { [Symbol.dispose]: () => registry.dispose() };
235 state.linked = new Map([["saved-vm", "fs-17"]]);
236 state.cached = { id: ThreadId.make("there"), title: "Cached title", projectId: null };
237 const environmentId = EnvironmentId.make("environment");
238 const link = { environmentId: EnvironmentId.make("saved-vm"), threadId: ThreadId.make("there") };
239 await using screen = await render(
240 <RegistryContext value={registry}>
241 <MarkdownThreadLink environmentId={environmentId} threadRef={HERE} link={link} label={null} />
242 </RegistryContext>,
243 );
244 await screen.getByRole("button", { name: "Thread, Cached title" }).click();
245 expect(panel().surfaces).toEqual([
246 linkedThreadSurface({
247 viaEnvironmentId: environmentId,
248 ...link,
249 label: "fs-17",
250 title: "Cached title",
251 }),
252 ]);
253});
254
255it("opens a linked machine's thread directly once this client is connected to it", async () => {
256 const { registry, reply } = setup();
257 using _registry = { [Symbol.dispose]: () => registry.dispose() };
258 state.linked = new Map([["saved-vm", "fs-17"]]);
259 state.connected = ["environment", "saved-vm"];
260 registry.set(reply, AsyncResult.success({ there: { title: "Fix the build", projectId: null } }));
261 await using screen = await render(
262 <RegistryContext value={registry}>
263 <MarkdownThreadLink
264 environmentId={EnvironmentId.make("environment")}
265 threadRef={HERE}
266 link={{ environmentId: EnvironmentId.make("saved-vm"), threadId: ThreadId.make("there") }}
267 label={null}
268 />
269 </RegistryContext>,
270 );
271 await expect.element(screen.getByText("Fix the build")).toBeVisible();
272 await expect.element(screen.getByRole("button")).not.toBeInTheDocument();
273});
274
275it("keeps a linked environment thread label when copying a table", async () => {
276 const { registry } = setup();
277 using _registry = { [Symbol.dispose]: () => registry.dispose() };
278 state.linked = new Map([["linked-vm", "fs-17"]]);
279 await using screen = await render(
280 <RegistryContext value={registry}>
281 <table>
282 <thead>
283 <tr>
284 <th>Thread</th>
285 <th>Status</th>
286 </tr>
287 </thead>
288 <tbody>
289 <tr>
290 <td>
291 <MarkdownThreadLink
292 environmentId={EnvironmentId.make("environment")}
293 threadRef={HERE}
294 link={{
295 environmentId: EnvironmentId.make("linked-vm"),
296 threadId: ThreadId.make("there"),
297 }}
298 label="Linked thread"
299 />
300 </td>
301 <td>ready</td>
302 </tr>
303 </tbody>
304 </table>
305 </RegistryContext>,
306 );
307 const table = screen.container.querySelector("table")!;
308 expect(serializeTableElementToCsv(table)).toBe("Thread,Status\nLinked thread,ready");
309 expect(serializeTableElementToMarkdown(table)).toBe(
310 "| Thread | Status |\n| --- | --- |\n| [Linked thread](https://app.t3.codes/threads/linked-vm/there) | ready |",
311 );
312 expect(serializeTableElementToHtml(table)).toContain(">Linked thread</td>");
313});