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

ThreadDetailsPanel.browser.test.tsx

472 lines15.5 KB

1import { scopeProjectRef } from "@t3tools/client-runtime/environment";
2import {
3 AuthSourceControlWriteScope,
4 EnvironmentId,
5 ProjectId,
6 ThreadId,
7 type AuthSessionState,
8 type ScopedThreadRef,
9 type ThreadPullRequestLink,
10 type VcsRef,
11} from "@t3tools/contracts";
12import * as Effect from "effect/Effect";
13import { AsyncResult, Atom } from "effect/reactivity";
14import { expect, it, vi } from "vite-plus/test";
15import { page } from "vite-plus/test/browser";
16​
17const SCRATCH_ROOT = "/home/user/.t3/scratch";
18​
19const state = vi.hoisted(() => ({
20 workspaceRoot: "",
21 folder: "",
22 pullRequests: [] as unknown[],
23 configLoaded: true,
24 hasServerThread: true,
25 statusAtom: null as unknown,
26 refsAtom: null as unknown,
27}));
28​
29// The read of t3.json is a cache: a re-read is the only way to see what is on disk now.
30const t3File = vi.hoisted(() => ({
31 disk: "",
32 cached: "",
33 listeners: new Set<() => void>(),
34}));
35​
36vi.mock(import("~/components/files/projectFilesQueryState"), async (importOriginal) => {
37 const actual = await importOriginal();
38 const { useSyncExternalStore } = await import("react");
39 return {
40 ...actual,
41 useProjectFileQuery: ((_environmentId: unknown, _cwd: string, relativePath: string | null) => {
42 const contents = useSyncExternalStore(
43 (listener) => {
44 t3File.listeners.add(listener);
45 return () => t3File.listeners.delete(listener);
46 },
47 () => t3File.cached,
48 );
49 const refresh = () => {
50 t3File.cached = t3File.disk;
51 for (const listener of t3File.listeners) listener();
52 };
53 const data =
54 relativePath === "t3.json" && contents !== ""
55 ? { relativePath, contents, byteLength: contents.length, truncated: false }
56 : null;
57 return {
58 data,
59 error: null,
60 isPending: false,
61 readError: null,
62 isNotFile: false,
63 isFile: data !== null,
64 refresh,
65 };
66 }) as never,
67 };
68});
69​
70vi.mock(import("~/state/entities"), async (importOriginal) => {
71 const threadShell = (ref: unknown) =>
72 ref === null || !state.hasServerThread
73 ? null
74 : {
75 id: "thread",
76 environmentId: "environment",
77 projectId: "project",
78 worktreePath: state.folder,
79 branch: null,
80 runtime: null,
81 pullRequests: state.pullRequests,
82 };
83 return {
84 ...(await importOriginal()),
85 useProject: ((ref: unknown) =>
86 ref === null
87 ? null
88 : {
89 id: "project",
90 environmentId: "environment",
91 title: state.workspaceRoot === SCRATCH_ROOT ? "No project" : "plain",
92 workspaceRoot: state.workspaceRoot,
93 scripts: [],
94 }) as never,
95 useProjects: (() => []) as never,
96 useQuietThreadShell: threadShell as never,
97 readThreadShell: threadShell as never,
98 useServerConfigs: (() =>
99 new Map(
100 state.configLoaded
101 ? [
102 [
103 EnvironmentId.make("environment"),
104 {
105 scratchWorkspaceRoot: SCRATCH_ROOT,
106 environment: { capabilities: { pullRequests: true } },
107 },
108 ],
109 ]
110 : [],
111 )) as never,
112 };
113});
114vi.mock(import("~/state/session"), async (importOriginal) => {
115 const actual = await importOriginal();
116 const session = Atom.make(
117 AsyncResult.success({
118 authenticated: true,
119 scopes: [AuthSourceControlWriteScope],
120 auth: {
121 policy: "remote-reachable",
122 bootstrapMethods: ["one-time-token"],
123 sessionMethods: ["bearer-access-token"],
124 sessionCookieName: "t3_session",
125 },
126 } as const satisfies AuthSessionState),
127 );
128 return {
129 ...actual,
130 environmentSession: {
131 ...actual.environmentSession,
132 sessionStateAtom: (() => session) as never,
133 },
134 };
135});
136// Neither folder is a repository by default, which is what the server reports for both.
137vi.mock(import("~/state/vcs"), async (importOriginal) => {
138 const actual = await importOriginal();
139 const notARepo = Atom.make(
140 AsyncResult.success({
141 isRepo: false,
142 hasPrimaryRemote: false,
143 isDefaultRef: false,
144 refName: null,
145 hasWorkingTreeChanges: false,
146 workingTree: { files: [], insertions: 0, deletions: 0 },
147 hasUpstream: false,
148 aheadCount: 0,
149 behindCount: 0,
150 aheadOfDefaultCount: 0,
151 pr: null,
152 }),
153 );
154 return {
155 ...actual,
156 vcsEnvironment: {
157 ...actual.vcsEnvironment,
158 status: (() => state.statusAtom ?? notARepo) as never,
159 listRefs: (() => state.refsAtom) as never,
160 refreshLocalStatusForPicker: {
161 ...actual.vcsEnvironment.refreshLocalStatusForPicker,
162 run: () => Effect.void,
163 } as never,
164 switchRef: {
165 ...actual.vcsEnvironment.switchRef,
166 run: (_registry: unknown, target: { input: { refName: string } }) =>
167 Effect.succeed({ refName: target.input.refName }),
168 } as never,
169 },
170 };
171});
172​
173import { render } from "../../../test/render";
174import { DraftId, useComposerDraftStore } from "../../composerDraftStore";
175import { useRightPanelStore } from "../../rightPanelStore";
176import { PopoverCreateHandle } from "../ui/popover";
177import { ChatCanvasContext } from "./ChatCanvasContext";
178import { resolveChatCanvasLayout } from "./chatCanvasLayout";
179import { ThreadDetailsPanel } from "./ThreadDetailsPanel";
180​
181const threadRef: ScopedThreadRef = {
182 environmentId: EnvironmentId.make("environment"),
183 threadId: ThreadId.make("thread"),
184};
185const container = { width: 1200, height: 800 };
186const placement = { x: 908, y: 0, right: 12, width: 280, height: 400 } as const;
187const linkedPullRequest: ThreadPullRequestLink = {
188 host: "github.com",
189 repository: "pingdotgg/t3code",
190 number: 27513,
191 url: "https://github.com/pingdotgg/t3code/pull/27513",
192 source: "manual",
193 linkedAt: "2026-10-30T00:00:00.000Z",
194 snapshot: null,
195 stack: null,
196};
197​
198function setup(input: {
199 workspaceRoot: string;
200 folder: string;
201 pullRequests?: ThreadPullRequestLink[];
202 configLoaded?: boolean;
203 hasServerThread?: boolean;
204 repo?: { currentBranch: string; refs: readonly VcsRef[] };
205 draftId?: DraftId;
206}) {
207 state.configLoaded = input.configLoaded ?? true;
208 state.workspaceRoot = input.workspaceRoot;
209 state.folder = input.folder;
210 state.pullRequests = input.pullRequests ?? [];
211 state.hasServerThread = input.hasServerThread ?? true;
212 state.statusAtom = input.repo
213 ? Atom.make(
214 AsyncResult.success({
215 isRepo: true,
216 hasPrimaryRemote: true,
217 isDefaultRef: false,
218 refName: input.repo.currentBranch,
219 hasWorkingTreeChanges: false,
220 workingTree: { rootPath: input.workspaceRoot, files: [], insertions: 0, deletions: 0 },
221 hasUpstream: false,
222 aheadCount: 0,
223 behindCount: 0,
224 aheadOfDefaultCount: 0,
225 pr: null,
226 }),
227 )
228 : null;
229 state.refsAtom = input.repo
230 ? Atom.make(
231 AsyncResult.success({
232 refs: input.repo.refs,
233 isRepo: true,
234 hasPrimaryRemote: true,
235 nextCursor: null,
236 totalCount: input.repo.refs.length,
237 }),
238 )
239 : null;
240 useRightPanelStore.setState({ threadPanelVisibilityByThreadKey: {} });
241 const anchor = document.createElement("div");
242 document.body.append(anchor);
243 return {
244 anchor: { current: anchor },
245 handle: PopoverCreateHandle(),
246 [Symbol.dispose]: () => {
247 if (input.draftId) useComposerDraftStore.getState().clearDraftThread(input.draftId);
248 anchor.remove();
249 },
250 };
252​
253const machines = (["This Mac", "Server"] as const).map((label, index) => ({
254 environmentId: EnvironmentId.make(index === 0 ? "environment" : "other"),
255 projectId: ProjectId.make("project"),
256 label,
257 isPrimary: index === 0,
258 machine: "server" as const,
259}));
260​
261function Panel({
262 fixture,
263 draftId,
264 draftEnvMode,
265 worktreePath,
266 isGitRepo = false,
267 offersWorkspaceModes = false,
268 forceNewWorktree = false,
269 onMachines = false,
270 withScripts = false,
271}: {
272 fixture: ReturnType<typeof setup>;
273 draftId?: DraftId;
274 /** Renders an unsent draft in this mode instead of a started thread. */
275 draftEnvMode?: "local" | "worktree";
276 worktreePath?: string | null;
277 isGitRepo?: boolean;
278 offersWorkspaceModes?: boolean;
279 forceNewWorktree?: boolean;
280 onMachines?: boolean;
281 withScripts?: boolean;
282}) {
283 const noop = () => {};
284 const scriptResult = async () => ({ ok: true }) as never;
285 return (
286 <ChatCanvasContext
287 value={{
288 container,
289 lane: { padding: 48, minChatWidth: 640 },
290 layout: resolveChatCanvasLayout({ container, preview: null }),
291 previewKey: null,
292 measureDetailsCard: noop,
293 detailsCardTopInset: 0,
294 preferredDetailsCard: placement,
295 detailsCardPlacement: placement,
296 }}
297 >
298 <ThreadDetailsPanel
299 anchor={fixture.anchor}
300 handle={fixture.handle}
301 environmentId={threadRef.environmentId}
302 threadId={threadRef.threadId}
303 projectId={ProjectId.make("project")}
304 {...(draftId ? { draftId } : {})}
305 composerDraftTarget={draftId ?? threadRef}
306 worktreePath={
307 worktreePath !== undefined
308 ? worktreePath
309 : draftEnvMode === undefined
310 ? state.folder
311 : null
312 }
313 isServerThread={draftEnvMode === undefined}
314 activeProjectName={state.workspaceRoot === SCRATCH_ROOT ? "No project" : "plain"}
315 activeProjectScripts={withScripts ? [] : undefined}
316 preferredScriptId={null}
317 keybindings={[]}
318 availableEditors={[]}
319 showOpenInPicker={false}
320 openInShortcutEnabled={false}
321 gitCwd={state.folder}
322 workspaceMutationId={null}
323 isGitRepo={isGitRepo}
324 offersWorkspaceModes={offersWorkspaceModes}
325 forceNewWorktree={forceNewWorktree}
326 envLocked={draftEnvMode === undefined}
327 availableEnvironments={onMachines ? machines : []}
328 {...(onMachines ? { onEnvironmentChange: noop } : {})}
329 onEnvModeChange={noop}
330 envMode={draftEnvMode ?? "local"}
331 startFromOrigin={false}
332 onStartFromOriginChange={noop}
333 onComposerFocusRequest={noop}
334 onRunProjectScript={noop}
335 onAddProjectScript={scriptResult}
336 onUpdateProjectScript={scriptResult}
337 onDeleteProjectScript={scriptResult}
338 usage={{} as never}
339 taskList={null}
340 />
341 </ChatCanvasContext>
342 );
344​
345it("offers no git controls in a No project thread, but shows its linked pull request", async () => {
346 using fixture = setup({
347 workspaceRoot: SCRATCH_ROOT,
348 folder: `${SCRATCH_ROOT}/thread`,
349 pullRequests: [linkedPullRequest],
350 });
351 await using _screen = await render(<Panel fixture={fixture} />);
352 await expect.element(page.getByText("#27513")).toBeVisible();
353 await expect
354 .element(page.getByRole("button", { name: "Initialize Git" }))
355 .not.toBeInTheDocument();
356});
357​
358it("shows Current checkout where no worktree can come from, even when New worktree is the default", async () => {
359 using fixture = setup({ workspaceRoot: SCRATCH_ROOT, folder: SCRATCH_ROOT });
360 await using _screen = await render(<Panel fixture={fixture} draftEnvMode="worktree" />);
361 await expect.element(page.getByLabelText("Run context: Current checkout")).toBeVisible();
362 await expect.element(page.getByRole("button", { name: /Run context/ })).not.toBeInTheDocument();
363});
364​
365it("offers only machines where no worktree can come from and several machines exist", async () => {
366 using fixture = setup({ workspaceRoot: SCRATCH_ROOT, folder: SCRATCH_ROOT });
367 await using _screen = await render(
368 <Panel fixture={fixture} draftEnvMode="worktree" onMachines />,
369 );
370 await page.getByRole("button", { name: "Run context: This Mac, Current checkout" }).click();
371 await expect.element(page.getByText("Run on")).toBeVisible();
372 await expect.element(page.getByText("New worktree")).not.toBeInTheDocument();
373});
374​
375it("shows a linked pull request in a folder that is not a git repository", async () => {
376 using fixture = setup({
377 workspaceRoot: "/work/plain",
378 folder: "/work/plain",
379 pullRequests: [linkedPullRequest],
380 });
381 await using _screen = await render(<Panel fixture={fixture} />);
382 await expect.element(page.getByRole("region", { name: "Workspace" })).toBeVisible();
383 await expect.element(page.getByText("#27513")).toBeVisible();
384 await expect.element(page.getByRole("button", { name: "Initialize Git" })).toBeVisible();
385});
386​
387it("offers no Initialize Git before the server config says where No project lives", async () => {
388 using fixture = setup({
389 workspaceRoot: SCRATCH_ROOT,
390 folder: `${SCRATCH_ROOT}/thread`,
391 configLoaded: false,
392 });
393 await using _screen = await render(<Panel fixture={fixture} />);
394 await expect.element(page.getByRole("region", { name: "Workspace" })).toBeVisible();
395 await expect
396 .element(page.getByRole("button", { name: "Initialize Git" }))
397 .not.toBeInTheDocument();
398});
399​
400it("lists the t3.json actions on disk when the actions menu opens again after the file changed", async () => {
401 using fixture = setup({ workspaceRoot: "/work/plain", folder: "/work/plain" });
402 const t3Json = (name: string) =>
403 JSON.stringify({ scripts: [{ name, command: `npm run dev -- --port ${name.slice(-4)}` }] });
404 t3File.disk = t3Json("Dev 4100");
405 t3File.cached = t3File.disk;
406 await using _screen = await render(<Panel fixture={fixture} withScripts />);
407​
408 const chooser = page.getByRole("button", { name: "Choose project action" });
409 await chooser.click();
410 await expect.element(page.getByRole("menuitem", { name: /Dev 4100/ })).toBeVisible();
411 await chooser.click();
412 await expect.element(page.getByRole("menu")).not.toBeInTheDocument();
413​
414 // A setup hook rewrites this checkout's t3.json outside T3 Code.
415 t3File.disk = t3Json("Dev 4200");
416​
417 await chooser.click();
418 await expect.element(page.getByRole("menuitem", { name: /Dev 4200/ })).toBeVisible();
419});
420​
421it("updates the draft base branch instead of checking out a previous worktree when forceNewWorktree is set", async () => {
422 const worktreePath = "/work/repo/.t3/worktrees/prev";
423 const draftId = DraftId.make("multi-model-draft");
424 using fixture = setup({
425 workspaceRoot: "/work/repo",
426 folder: worktreePath,
427 hasServerThread: false,
428 repo: {
429 currentBranch: "t3/previous",
430 refs: [
431 { name: "t3/previous", current: true, isDefault: false, worktreePath },
432 { name: "feature", current: false, isDefault: false, worktreePath: null },
433 { name: "main", current: false, isDefault: true, worktreePath: "/work/repo" },
434 ],
435 },
436 draftId,
437 });
438 const store = useComposerDraftStore.getState();
439 store.setProjectDraftThreadId(
440 scopeProjectRef(threadRef.environmentId, ProjectId.make("project")),
441 draftId,
442 );
443 store.setDraftThreadContext(draftId, {
444 branch: "t3/previous",
445 worktreePath,
446 envMode: "worktree",
447 });
448​
449 await using _screen = await render(
450 <Panel
451 fixture={fixture}
452 draftId={draftId}
453 draftEnvMode="worktree"
454 worktreePath={worktreePath}
455 isGitRepo
456 offersWorkspaceModes
457 forceNewWorktree
458 />,
459 );
460​
461 const branchTrigger = page.getByRole("combobox", { name: /^Branch:/ });
462 await expect.element(branchTrigger).toHaveAccessibleName("Branch: From t3/previous");
463 await branchTrigger.click();
464 await page.getByRole("option", { name: "feature", exact: true }).click();
465​
466 await expect.element(branchTrigger).toHaveAccessibleName("Branch: From feature");
467 expect(useComposerDraftStore.getState().getDraftSession(draftId)).toMatchObject({
468 branch: "feature",
469 worktreePath: null,
470 envMode: "worktree",
471 });
472});