Open History to see the last commit
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 };
251}
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 registerTimeline: noop,
293 measureDetailsCard: noop,
294 detailsCardTopInset: 0,
295 preferredDetailsCard: placement,
296 detailsCardPlacement: placement,
297 }}
298 >
299 <ThreadDetailsPanel
300 anchor={fixture.anchor}
301 handle={fixture.handle}
302 environmentId={threadRef.environmentId}
303 threadId={threadRef.threadId}
304 projectId={ProjectId.make("project")}
305 {...(draftId ? { draftId } : {})}
306 composerDraftTarget={draftId ?? threadRef}
307 worktreePath={
308 worktreePath !== undefined
309 ? worktreePath
310 : draftEnvMode === undefined
311 ? state.folder
312 : null
313 }
314 isServerThread={draftEnvMode === undefined}
315 activeProjectName={state.workspaceRoot === SCRATCH_ROOT ? "No project" : "plain"}
316 activeProjectScripts={withScripts ? [] : undefined}
317 preferredScriptId={null}
318 keybindings={[]}
319 availableEditors={[]}
320 showOpenInPicker={false}
321 openInShortcutEnabled={false}
322 gitCwd={state.folder}
323 workspaceMutationId={null}
324 isGitRepo={isGitRepo}
325 offersWorkspaceModes={offersWorkspaceModes}
326 forceNewWorktree={forceNewWorktree}
327 envLocked={draftEnvMode === undefined}
328 availableEnvironments={onMachines ? machines : []}
329 {...(onMachines ? { onEnvironmentChange: noop } : {})}
330 onEnvModeChange={noop}
331 envMode={draftEnvMode ?? "local"}
332 startFromOrigin={false}
333 onStartFromOriginChange={noop}
334 onComposerFocusRequest={noop}
335 onRunProjectScript={noop}
336 onAddProjectScript={scriptResult}
337 onUpdateProjectScript={scriptResult}
338 onDeleteProjectScript={scriptResult}
339 usage={{} as never}
340 taskList={null}
341 />
342 </ChatCanvasContext>
343 );
344}
345
346it("offers no git controls in a No project thread, but shows its linked pull request", async () => {
347 using fixture = setup({
348 workspaceRoot: SCRATCH_ROOT,
349 folder: `${SCRATCH_ROOT}/thread`,
350 pullRequests: [linkedPullRequest],
351 });
352 await using _screen = await render(<Panel fixture={fixture} />);
353 await expect.element(page.getByText("#27513")).toBeVisible();
354 await expect
355 .element(page.getByRole("button", { name: "Initialize Git" }))
356 .not.toBeInTheDocument();
357});
358
359it("shows Current checkout where no worktree can come from, even when New worktree is the default", async () => {
360 using fixture = setup({ workspaceRoot: SCRATCH_ROOT, folder: SCRATCH_ROOT });
361 await using _screen = await render(<Panel fixture={fixture} draftEnvMode="worktree" />);
362 await expect.element(page.getByLabelText("Run context: Current checkout")).toBeVisible();
363 await expect.element(page.getByRole("button", { name: /Run context/ })).not.toBeInTheDocument();
364});
365
366it("offers only machines where no worktree can come from and several machines exist", async () => {
367 using fixture = setup({ workspaceRoot: SCRATCH_ROOT, folder: SCRATCH_ROOT });
368 await using _screen = await render(
369 <Panel fixture={fixture} draftEnvMode="worktree" onMachines />,
370 );
371 await page.getByRole("button", { name: "Run context: This Mac, Current checkout" }).click();
372 await expect.element(page.getByText("Run on")).toBeVisible();
373 await expect.element(page.getByText("New worktree")).not.toBeInTheDocument();
374});
375
376it("shows a linked pull request in a folder that is not a git repository", async () => {
377 using fixture = setup({
378 workspaceRoot: "/work/plain",
379 folder: "/work/plain",
380 pullRequests: [linkedPullRequest],
381 });
382 await using _screen = await render(<Panel fixture={fixture} />);
383 await expect.element(page.getByRole("region", { name: "Workspace" })).toBeVisible();
384 await expect.element(page.getByText("#27513")).toBeVisible();
385 await expect.element(page.getByRole("button", { name: "Initialize Git" })).toBeVisible();
386});
387
388it("offers no Initialize Git before the server config says where No project lives", async () => {
389 using fixture = setup({
390 workspaceRoot: SCRATCH_ROOT,
391 folder: `${SCRATCH_ROOT}/thread`,
392 configLoaded: false,
393 });
394 await using _screen = await render(<Panel fixture={fixture} />);
395 await expect.element(page.getByRole("region", { name: "Workspace" })).toBeVisible();
396 await expect
397 .element(page.getByRole("button", { name: "Initialize Git" }))
398 .not.toBeInTheDocument();
399});
400
401it("lists the t3.json actions on disk when the actions menu opens again after the file changed", async () => {
402 using fixture = setup({ workspaceRoot: "/work/plain", folder: "/work/plain" });
403 const t3Json = (name: string) =>
404 JSON.stringify({ scripts: [{ name, command: `npm run dev -- --port ${name.slice(-4)}` }] });
405 t3File.disk = t3Json("Dev 4100");
406 t3File.cached = t3File.disk;
407 await using _screen = await render(<Panel fixture={fixture} withScripts />);
408
409 const chooser = page.getByRole("button", { name: "Choose project action" });
410 await chooser.click();
411 await expect.element(page.getByRole("menuitem", { name: /Dev 4100/ })).toBeVisible();
412 await chooser.click();
413 await expect.element(page.getByRole("menu")).not.toBeInTheDocument();
414
415 // A setup hook rewrites this checkout's t3.json outside T3 Code.
416 t3File.disk = t3Json("Dev 4200");
417
418 await chooser.click();
419 await expect.element(page.getByRole("menuitem", { name: /Dev 4200/ })).toBeVisible();
420});
421
422it("updates the draft base branch instead of checking out a previous worktree when forceNewWorktree is set", async () => {
423 const worktreePath = "/work/repo/.t3/worktrees/prev";
424 const draftId = DraftId.make("multi-model-draft");
425 using fixture = setup({
426 workspaceRoot: "/work/repo",
427 folder: worktreePath,
428 hasServerThread: false,
429 repo: {
430 currentBranch: "t3/previous",
431 refs: [
432 { name: "t3/previous", current: true, isDefault: false, worktreePath },
433 { name: "feature", current: false, isDefault: false, worktreePath: null },
434 { name: "main", current: false, isDefault: true, worktreePath: "/work/repo" },
435 ],
436 },
437 draftId,
438 });
439 const store = useComposerDraftStore.getState();
440 store.setProjectDraftThreadId(
441 scopeProjectRef(threadRef.environmentId, ProjectId.make("project")),
442 draftId,
443 );
444 store.setDraftThreadContext(draftId, {
445 branch: "t3/previous",
446 worktreePath,
447 envMode: "worktree",
448 });
449
450 await using _screen = await render(
451 <Panel
452 fixture={fixture}
453 draftId={draftId}
454 draftEnvMode="worktree"
455 worktreePath={worktreePath}
456 isGitRepo
457 offersWorkspaceModes
458 forceNewWorktree
459 />,
460 );
461
462 const branchTrigger = page.getByRole("combobox", { name: /^Branch:/ });
463 await expect.element(branchTrigger).toHaveAccessibleName("Branch: From t3/previous");
464 await branchTrigger.click();
465 await page.getByRole("option", { name: "feature", exact: true }).click();
466
467 await expect.element(branchTrigger).toHaveAccessibleName("Branch: From feature");
468 expect(useComposerDraftStore.getState().getDraftSession(draftId)).toMatchObject({
469 branch: "feature",
470 worktreePath: null,
471 envMode: "worktree",
472 });
473});