Open History to see the last commit
1import {
2 addableTaskFolderRepositories,
3 pinnableThreadRepositories,
4 repositorySectionSummary,
5 THREAD_REPOSITORY_SECTIONS_VISIBLE,
6 threadChangedRepositories,
7 threadRepositorySections,
8 type ThreadRepositorySection,
9 type ThreadRepositorySections as RepositorySections,
10} from "@t3tools/client-runtime/state/thread-repositories";
11import { formatDiffCount } from "@t3tools/client-runtime/diff-count";
12import {
13 isAtomCommandInterrupted,
14 squashAtomCommandFailure,
15} from "@t3tools/client-runtime/state/runtime";
16import type {
17 EnvironmentId,
18 ProjectId,
19 ScopedThreadRef,
20 TaskFolder,
21 ThreadId,
22} from "@t3tools/contracts";
23import { useAtomValue } from "@effect/atom-react";
24import {
25 ChevronDownIcon,
26 ChevronRightIcon,
27 FolderGitIcon,
28 PinOffIcon,
29 PlusIcon,
30} from "lucide-react";
31import { msg, T, useGT } from "gt-react";
32import { memo, useState } from "react";
33
34import { m } from "~/i18n/messages";
35import { cn } from "~/lib/utils";
36import { useQuietThreadProjection } from "~/state/entities";
37import { filesystemEnvironment, useFilesystemReadAccess } from "~/state/filesystem";
38import { useEnvironmentQuery } from "~/state/query";
39import { useAtomCommand } from "~/state/use-atom-command";
40import { vcsEnvironment } from "~/state/vcs";
41import { useThreadRepositoryPins, useThreadRepositoryPinsStore } from "~/threadRepositoryPinsStore";
42
43import { GitActionsControl } from "../GitActionsControl";
44import { Menu, MenuItem, MenuItemLabel, MenuPopup, MenuTrigger } from "../ui/menu";
45import { stackedThreadToast, toastManager } from "../ui/toast";
46import { ThreadDetailsControl } from "./ThreadDetailsControl";
47import {
48 THREAD_DETAILS_PANEL_CHEVRON_CLASS,
49 THREAD_DETAILS_PANEL_ICON_CLASS,
50 THREAD_DETAILS_PANEL_LABEL_CLASS,
51} from "./threadDetailsPanelStyles";
52
53interface ThreadRepositorySectionsProps {
54 environmentId: EnvironmentId;
55 threadId: ThreadId;
56 projectId: ProjectId;
57 isServerThread: boolean;
58 /** The thread's own folder, which has its own Git controls when it is a repository. */
59 threadCwd: string | null;
60 /**
61 * The thread's task folder. Its repositories are then the only ones listed, each bound to the
62 * thread's own worktree of it, and adding one creates that worktree.
63 */
64 taskFolder: TaskFolder | null;
65 /** False when the thread reaches no tracked repository: it lists only what it changed. */
66 reachesTracked: boolean;
67 onTaskFolderChange: () => void;
68 /** Says so when no repository is listed, instead of leaving the section blank. */
69 explainsEmpty: boolean;
70 showActions: boolean;
71}
72
73const RepositorySection = memo(function RepositorySection(props: {
74 threadRef: ScopedThreadRef;
75 sectionKey: string;
76 name: string;
77 cwd: string;
78 removable: boolean;
79 expanded: boolean;
80 owner: { readonly threadId?: ThreadId; readonly projectId?: ProjectId };
81 showActions: boolean;
82 onToggle: (key: string) => void;
83 onRemove: (key: string) => void;
84}) {
85 // Local status only: a remote read for every listed repository would fetch on a timer. The
86 // expanded section's actions hold the full subscription, and its remote updates land here too.
87 const status = useEnvironmentQuery(
88 vcsEnvironment.status({
89 environmentId: props.threadRef.environmentId,
90 input: { cwd: props.cwd, includeRemote: false },
91 }),
92 );
93 const summary = repositorySectionSummary(status.data);
94 const Chevron = props.expanded ? ChevronDownIcon : ChevronRightIcon;
95 const bodyId = `thread-repository-${props.sectionKey}`;
96 const gt = useGT();
97
98 return (
99 <div
100 role="group"
101 aria-label={gt("Repository {name}", { name: props.name })}
102 className="flex flex-col"
103 >
104 <ThreadDetailsControl
105 size="sm"
106 variant="ghost"
107 part="row"
108 aria-expanded={props.expanded}
109 aria-controls={props.expanded ? bodyId : undefined}
110 onClick={() => props.onToggle(props.sectionKey)}
111 >
112 <Chevron className={THREAD_DETAILS_PANEL_CHEVRON_CLASS} aria-hidden />
113 <span className="flex min-w-0 flex-1 items-baseline gap-1.5">
114 <span className="max-w-2/3 shrink-0 truncate">{props.name}</span>
115 <span className="min-w-0 truncate font-normal text-muted-foreground">
116 {summary === null
117 ? (status.error ?? "")
118 : !summary.isRepository
119 ? gt("Not a Git repository")
120 : (summary.branch ?? gt("Detached HEAD"))}
121 </span>
122 {summary?.isRepository ? (
123 <span className="ml-auto flex shrink-0 items-baseline gap-2 ps-2 font-mono tabular-nums">
124 {summary.pullRequest ? (
125 <span className="font-sans font-normal text-muted-foreground">
126 #{summary.pullRequest.number}
127 </span>
128 ) : null}
129 {summary.changedFiles > 0 ? (
130 <>
131 <span className="text-diff-addition-foreground">
132 +{formatDiffCount(summary.insertions)}
133 </span>
134 <span className="text-diff-deletion-foreground">
135 -{formatDiffCount(summary.deletions)}
136 </span>
137 </>
138 ) : null}
139 </span>
140 ) : null}
141 </span>
142 </ThreadDetailsControl>
143 {props.expanded ? (
144 <div id={bodyId} className="flex flex-col ps-4">
145 <GitActionsControl
146 target={{ key: props.sectionKey, cwd: props.cwd, name: props.name }}
147 threadRef={props.threadRef}
148 owner={props.owner}
149 showActions={props.showActions}
150 showChanges={false}
151 />
152 {props.removable ? (
153 <ThreadDetailsControl
154 size="sm"
155 variant="ghost"
156 part="row"
157 tone="muted"
158 onClick={() => props.onRemove(props.sectionKey)}
159 >
160 <PinOffIcon className={THREAD_DETAILS_PANEL_ICON_CLASS} aria-hidden />
161 <span className={THREAD_DETAILS_PANEL_LABEL_CLASS}>
162 <T>Remove from this thread</T>
163 </span>
164 </ThreadDetailsControl>
165 ) : null}
166 </div>
167 ) : null}
168 </div>
169 );
170});
171
172/** Mounted while the menu is open, so the folder list is read only when someone asks for it. */
173function OtherRepositoryItems(props: {
174 environmentId: EnvironmentId;
175 projectId: ProjectId;
176 threadCwd: string | null;
177 taskFolder: TaskFolder | null;
178 sections: RepositorySections;
179 onPick: (repository: { repositoryPath: string; name: string }) => void;
180}) {
181 const folders = useEnvironmentQuery(
182 filesystemEnvironment.listFolders({
183 environmentId: props.environmentId,
184 input: { projectId: props.projectId },
185 }),
186 );
187 const gt = useGT();
188 if (folders.data === null) {
189 return (
190 <MenuItem disabled>
191 <MenuItemLabel>{folders.error ?? gt("Loading repositories...")}</MenuItemLabel>
192 </MenuItem>
193 );
194 }
195 const repositories =
196 props.taskFolder === null
197 ? pinnableThreadRepositories({
198 folders: folders.data.folders,
199 sections: props.sections,
200 threadCwd: props.threadCwd,
201 })
202 : addableTaskFolderRepositories({
203 folders: folders.data.folders,
204 taskFolder: props.taskFolder,
205 });
206 if (repositories.length === 0) {
207 return (
208 <MenuItem disabled>
209 <MenuItemLabel>
210 <T>No other repositories</T>
211 </MenuItemLabel>
212 </MenuItem>
213 );
214 }
215 return repositories.map((repository) => (
216 <MenuItem key={repository.repositoryPath} onClick={() => props.onPick(repository)}>
217 <FolderGitIcon />
218 <MenuItemLabel>{repository.name}</MenuItemLabel>
219 </MenuItem>
220 ));
221}
222
223/**
224 * Git state and actions for the tracked repositories a thread changed or the user added, or for
225 * the worktrees in its task folder. Folded sections are not rendered, so they hold no subscription.
226 */
227export function ThreadRepositorySections(props: ThreadRepositorySectionsProps) {
228 const threadRef: ScopedThreadRef = {
229 environmentId: props.environmentId,
230 threadId: props.threadId,
231 };
232 const structure = useQuietThreadProjection(props.isServerThread ? threadRef : null);
233 const pinned = useThreadRepositoryPins(threadRef);
234 const pin = useThreadRepositoryPinsStore((state) => state.pin);
235 const unpin = useThreadRepositoryPinsStore((state) => state.unpin);
236 const { canReadFiles } = useFilesystemReadAccess(props.environmentId);
237 const [showAll, setShowAll] = useState(false);
238 const [expandedKey, setExpandedKey] = useState<string | null>(null);
239 const [isPickerOpen, setIsPickerOpen] = useState(false);
240 const canAddWorktree = useAtomValue(
241 filesystemEnvironment.addTaskFolderRepository.permissionAtom(props.environmentId),
242 );
243 const addTaskFolderRepository = useAtomCommand(filesystemEnvironment.addTaskFolderRepository, {
244 label: "task folder add repository",
245 reportFailure: false,
246 });
247 const [addingName, setAddingName] = useState<string | null>(null);
248 const gt = useGT();
249
250 const { taskFolder } = props;
251 const sections = threadRepositorySections({
252 changed: structure === null ? [] : threadChangedRepositories(structure.projection),
253 pinned,
254 threadCwd: props.threadCwd,
255 showAll,
256 taskFolder,
257 reachesTracked: props.reachesTracked,
258 });
259 const addWorktree = async (repository: { repositoryPath: string; name: string }) => {
260 if (addingName !== null) return;
261 setAddingName(repository.name);
262 const result = await addTaskFolderRepository({
263 environmentId: props.environmentId,
264 input: { threadId: props.threadId, repositoryPath: repository.repositoryPath },
265 });
266 setAddingName(null);
267 if (result._tag === "Failure") {
268 if (isAtomCommandInterrupted(result)) return;
269 const error = squashAtomCommandFailure(result);
270 toastManager.add(
271 stackedThreadToast({
272 type: "error",
273 title: m(msg("Could not add {name}", { name: repository.name })),
274 description: error instanceof Error ? error.message : String(error),
275 }),
276 );
277 return;
278 }
279 props.onTaskFolderChange();
280 setShowAll(true);
281 setExpandedKey(repository.repositoryPath);
282 };
283 const owner = props.isServerThread
284 ? { threadId: props.threadId }
285 : { projectId: props.projectId };
286 const toggle = (key: string) => setExpandedKey((current) => (current === key ? null : key));
287 const remove = (key: string) => unpin(threadRef, key);
288 const renderSection = (section: ThreadRepositorySection) => (
289 <RepositorySection
290 key={section.key}
291 threadRef={threadRef}
292 sectionKey={section.key}
293 name={section.name}
294 cwd={section.cwd}
295 removable={section.origin === "pinned"}
296 expanded={expandedKey === section.key}
297 owner={owner}
298 showActions={props.showActions}
299 onToggle={toggle}
300 onRemove={remove}
301 />
302 );
303
304 return (
305 <>
306 {sections.visible.length === 0 && props.explainsEmpty && props.reachesTracked ? (
307 <p className="px-2.5 py-1.5 text-xs text-muted-foreground">
308 {taskFolder === null
309 ? gt("Repositories appear here once this thread changes them.")
310 : gt("This thread has no repository worktrees yet.")}
311 </p>
312 ) : null}
313 {sections.visible.map(renderSection)}
314 {sections.hidden.length > 0 ||
315 (showAll && sections.visible.length > THREAD_REPOSITORY_SECTIONS_VISIBLE) ? (
316 <ThreadDetailsControl
317 size="sm"
318 variant="ghost"
319 part="row"
320 tone="muted"
321 aria-expanded={showAll}
322 onClick={() => setShowAll((current) => !current)}
323 >
324 <span className={cn("ms-6.5", THREAD_DETAILS_PANEL_LABEL_CLASS)}>
325 {showAll
326 ? gt("Show fewer")
327 : gt("Show {count} more", { count: sections.hidden.length })}
328 </span>
329 </ThreadDetailsControl>
330 ) : null}
331 {props.reachesTracked &&
332 canReadFiles &&
333 (taskFolder === null || (props.isServerThread && canAddWorktree)) ? (
334 <Menu open={isPickerOpen} onOpenChange={setIsPickerOpen}>
335 <MenuTrigger
336 render={<ThreadDetailsControl size="sm" variant="ghost" part="row" tone="muted" />}
337 disabled={addingName !== null}
338 >
339 <PlusIcon className={THREAD_DETAILS_PANEL_ICON_CLASS} aria-hidden />
340 <span className={THREAD_DETAILS_PANEL_LABEL_CLASS}>
341 {addingName === null
342 ? gt("Other repositories...")
343 : gt("Adding a worktree of {name}...", { name: addingName })}
344 </span>
345 </MenuTrigger>
346 <MenuPopup align="start">
347 {isPickerOpen ? (
348 <OtherRepositoryItems
349 environmentId={props.environmentId}
350 projectId={props.projectId}
351 threadCwd={props.threadCwd}
352 taskFolder={taskFolder}
353 sections={sections}
354 onPick={(repository) => {
355 if (taskFolder !== null) {
356 void addWorktree(repository);
357 return;
358 }
359 pin(threadRef, repository);
360 // Pins beyond the visible few would land folded away, out of sight.
361 if (pinned.length >= THREAD_REPOSITORY_SECTIONS_VISIBLE) setShowAll(true);
362 setExpandedKey(repository.repositoryPath);
363 }}
364 />
365 ) : null}
366 </MenuPopup>
367 </Menu>
368 ) : null}
369 </>
370 );
371}