Open History to see the last commit
1import {
2 isAtomCommandInterrupted,
3 mapAtomCommandResult,
4 settlePromise,
5 squashAtomCommandFailure,
6 type AtomCommandResult,
7} from "@t3tools/client-runtime/state/runtime";
8import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
9import { AsyncResult } from "effect/reactivity";
10import { type EnvironmentId, type ProjectIconOverride } from "@t3tools/contracts";
11import { useLocation, useNavigate } from "@tanstack/react-router";
12import * as Cause from "effect/Cause";
13import { InfoIcon, Trash2Icon } from "lucide-react";
14import { lazy, Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react";
15
16import { useComposerDraftStore } from "../../composerDraftStore";
17import { releaseProjectDraftUploads } from "../../lib/composerDraftUploads";
18import { readLocalApi } from "../../localApi";
19import {
20 type SidebarProjectGroupMember,
21 type SidebarProjectSnapshot,
22} from "../../sidebarProjectGrouping";
23import { useEnvironments, usePrimaryEnvironmentId } from "../../state/environments";
24import { useThreadShells } from "../../state/entities";
25import { projectEnvironment } from "../../state/projects";
26import { useAtomCommand } from "../../state/use-atom-command";
27import { ProjectFavicon } from "../ProjectFavicon";
28import { Alert, AlertDescription } from "../ui/alert";
29import { Button } from "../ui/button";
30import { Input } from "../ui/input";
31import { stackedThreadToast, toastManager } from "../ui/toast";
32import {
33 SettingResetButton,
34 SettingsPageContainer,
35 SettingsRow,
36 SettingsSection,
37} from "./settingsLayout";
38import {
39 canPickExternalProjectFavicon,
40 ProjectFaviconPickerDialog,
41} from "./ProjectFaviconPickerDialog";
42import { ProjectActionsSettings } from "./ProjectActionsSettings";
43import { ProjectDefaultsSettings } from "./ProjectDefaultsSettings";
44import { projectGroupTitleNeedsUpdate } from "./ProjectSettingsPanel.logic";
45import { useSettingsProjectGroups } from "./useSettingsProjectGroups";
46
47const ProjectIconPickerDialog = lazy(() =>
48 import("./ProjectIconPickerDialog").then((module) => ({
49 default: module.ProjectIconPickerDialog,
50 })),
51);
52
53function memberKey(member: { environmentId: string; id: string }): string {
54 return `${member.environmentId}:${member.id}`;
55}
56
57/** `project` is the Projects page shortcut: the new-thread defaults people change most. */
58export type ProjectSettingsCategory = "general" | "integrations" | "source-control" | "project";
59
60export function ProjectSettingsPanel({
61 projectKey,
62 environmentId = null,
63 checkoutKey = null,
64}: {
65 projectKey: string;
66 environmentId?: EnvironmentId | null;
67 checkoutKey?: string | null;
68}) {
69 const groups = useSettingsProjectGroups();
70 const navigate = useNavigate({ from: "/settings" });
71 const pathname = useLocation({ select: (location) => location.pathname });
72
73 const selected = groups.find((group) => group.projectKey === projectKey) ?? null;
74 const members = useMemo(
75 () =>
76 selected?.memberProjects.filter(
77 (member) =>
78 (environmentId === null || member.environmentId === environmentId) &&
79 (checkoutKey === null || member.physicalProjectKey === checkoutKey),
80 ) ?? [],
81 [selected, environmentId, checkoutKey],
82 );
83
84 // Remember the members of the last rendered group so a grouping-rule change
85 // (which changes the group key) can follow the project to its new group.
86 const lastSelectionRef = useRef<{
87 key: string;
88 environmentId: EnvironmentId | null;
89 checkoutKey: string | null;
90 memberKeys: string[];
91 } | null>(null);
92 useEffect(() => {
93 if (!selected || members.length === 0) return;
94 lastSelectionRef.current = {
95 key: selected.projectKey,
96 environmentId,
97 checkoutKey,
98 memberKeys: members.map((member) => member.physicalProjectKey),
99 };
100 }, [selected, members, environmentId, checkoutKey]);
101
102 // A grouping-rule change replaces the group key mid-visit; follow the
103 // project to its new key instead of parking on the not-found state.
104 useEffect(() => {
105 if (members.length > 0) return;
106 const last = lastSelectionRef.current;
107 if (
108 last?.key !== projectKey ||
109 last.environmentId !== environmentId ||
110 last.checkoutKey !== checkoutKey
111 )
112 return;
113 const successor = groups.find((group) =>
114 group.memberProjects.some((member) => last.memberKeys.includes(member.physicalProjectKey)),
115 );
116 if (successor) {
117 void navigate({
118 to: pathname,
119 search: () => ({
120 project: successor.projectKey,
121 machine: environmentId ?? undefined,
122 checkout: checkoutKey ?? undefined,
123 }),
124 replace: true,
125 hashScrollIntoView: false,
126 });
127 }
128 }, [groups, navigate, pathname, projectKey, members.length, environmentId, checkoutKey]);
129
130 if (!selected) {
131 return (
132 <div className="flex flex-1 items-center justify-center p-8 text-sm text-muted-foreground">
133 {groups.length === 0
134 ? "Add a project from the sidebar to configure it here."
135 : "This project is no longer available."}
136 </div>
137 );
138 }
139 if (members.length === 0)
140 return (
141 <p className="p-8 text-sm text-muted-foreground">
142 This checkout is no longer available in the selected project and environment.
143 </p>
144 );
145 const scopedGroup = {
146 ...selected,
147 memberProjects: members,
148 environmentId: members[0]!.environmentId,
149 id: members[0]!.id,
150 };
151 return (
152 <ProjectDetail
153 key={`${selected.projectKey}:${environmentId ?? "all"}:${checkoutKey ?? "all"}`}
154 group={scopedGroup}
155 hasOtherMembers={members.length < selected.memberProjects.length}
156 />
157 );
158}
159
160function ProjectDetail({
161 group,
162 hasOtherMembers,
163}: {
164 group: SidebarProjectSnapshot;
165 hasOtherMembers: boolean;
166}) {
167 const navigate = useNavigate({ from: "/settings" });
168 const primaryEnvironmentId = usePrimaryEnvironmentId();
169 const { environments } = useEnvironments();
170 const environmentById = useMemo(
171 () => new Map(environments.map((environment) => [environment.environmentId, environment])),
172 [environments],
173 );
174 const representative =
175 group.memberProjects.find(
176 (member) => environmentById.get(member.environmentId)?.serverConfig != null,
177 ) ?? group.memberProjects[0]!;
178 const threads = useThreadShells();
179 const updateProject = useAtomCommand(projectEnvironment.update, { reportFailure: false });
180 const deleteProject = useAtomCommand(projectEnvironment.delete, { reportFailure: false });
181 const projectNameEditedRef = useRef(false);
182
183 const faviconPath = representative.faviconPath ?? null;
184 const projectIcon = representative.projectIcon ?? null;
185 const pickProjectFavicon =
186 typeof window !== "undefined" &&
187 group.memberProjects.every(
188 (member) =>
189 member.environmentId === primaryEnvironmentId &&
190 canPickExternalProjectFavicon(member.workspaceRoot, navigator.platform),
191 )
192 ? window.desktopBridge?.pickProjectFavicon
193 : undefined;
194
195 const reportFailure = useCallback((title: string, result: AtomCommandResult<void, unknown>) => {
196 if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
197 const error = squashAtomCommandFailure(result);
198 toastManager.add(
199 stackedThreadToast({
200 type: "error",
201 title,
202 description: error instanceof Error ? error.message : "An error occurred.",
203 }),
204 );
205 }, []);
206
207 // Group-shared fields live on each physical project record, so a
208 // group-level edit fans out to every member.
209 const updateAllMembers = useCallback(
210 async (
211 input: Partial<{
212 title: string;
213 faviconPath: string | null;
214 projectIcon: ProjectIconOverride | null;
215 }>,
216 failureTitle: string,
217 ): Promise<AtomCommandResult<void, unknown>> => {
218 const unavailable = group.memberProjects.find((member) => {
219 const environment = environmentById.get(member.environmentId);
220 return environment?.connection.phase !== "connected" || !environment.serverConfig;
221 });
222 if (unavailable) {
223 const error = new Error(
224 `Connect ${unavailable.environmentLabel ?? "the selected environment"} and try again.`,
225 );
226 const result: AtomCommandResult<void, unknown> = AsyncResult.failure(Cause.fail(error));
227 reportFailure(failureTitle, result);
228 return result;
229 }
230 for (const member of group.memberProjects) {
231 const result = mapAtomCommandResult(
232 await updateProject({
233 environmentId: member.environmentId,
234 input: { projectId: member.id, ...input },
235 }),
236 () => undefined,
237 );
238 if (result._tag === "Failure") {
239 // A partial fan-out is possible: earlier members already took the
240 // write. Name the environment so the user knows where it stopped.
241 reportFailure(
242 group.memberProjects.length > 1
243 ? `${failureTitle} on ${member.environmentLabel ?? "the current environment"}`
244 : failureTitle,
245 result,
246 );
247 return result;
248 }
249 }
250 return AsyncResult.success(undefined);
251 },
252 [environmentById, group.memberProjects, reportFailure, updateProject],
253 );
254
255 const renameGroup = useCallback(
256 async (nextTitle: string, wasEdited: boolean) => {
257 const title = nextTitle.trim();
258 if (!title) {
259 toastManager.add({ type: "warning", title: "Project title cannot be empty" });
260 return;
261 }
262 if (
263 !projectGroupTitleNeedsUpdate(
264 group.memberProjects.map((member) => member.title),
265 title,
266 wasEdited,
267 )
268 ) {
269 return;
270 }
271 await updateAllMembers({ title }, "Failed to rename project");
272 },
273 [group.memberProjects, updateAllMembers],
274 );
275
276 // ----- project icon -----
277 const [faviconPickerOpen, setFaviconPickerOpen] = useState(false);
278 const [iconPickerOpen, setIconPickerOpen] = useState(false);
279 const [isSavingFavicon, setIsSavingFavicon] = useState(false);
280 const savingFaviconRef = useRef(false);
281 const setProjectIcon = useCallback(
282 async (input: { faviconPath: string | null; projectIcon: ProjectIconOverride | null }) => {
283 if (savingFaviconRef.current) return;
284 savingFaviconRef.current = true;
285 setIsSavingFavicon(true);
286 try {
287 await updateAllMembers(input, "Failed to update project icon");
288 } finally {
289 savingFaviconRef.current = false;
290 setIsSavingFavicon(false);
291 }
292 },
293 [updateAllMembers],
294 );
295
296 const hasMultipleCheckouts = group.memberProjects.length > 1;
297
298 const removeMembers = useCallback(
299 async (members: ReadonlyArray<SidebarProjectGroupMember>) => {
300 const api = readLocalApi();
301 if (!api) return;
302
303 const memberKeys = new Set(members.map(memberKey));
304 const projectThreads = threads.filter((thread) =>
305 memberKeys.has(`${thread.environmentId}:${thread.projectId}`),
306 );
307 const isWholeGroup = members.length === group.memberProjects.length;
308 const targetKind = hasOtherMembers || !isWholeGroup ? "checkout" : "project";
309 const singleMember = members.length === 1 ? members[0]! : null;
310 const targetLabel = singleMember?.title ?? group.displayName;
311 const confirmed = await settlePromise(() =>
312 api.dialogs.confirm(
313 [
314 projectThreads.length > 0
315 ? `Remove ${targetKind} "${targetLabel}" and delete its ${projectThreads.length} thread${projectThreads.length === 1 ? "" : "s"}?`
316 : `Remove ${targetKind} "${targetLabel}"?`,
317 ...(singleMember
318 ? [
319 `Path: ${singleMember.workspaceRoot}`,
320 ...(singleMember.environmentLabel
321 ? [`Environment: ${singleMember.environmentLabel}`]
322 : []),
323 ]
324 : [`This removes ${members.length} grouped project entries.`]),
325 ...(projectThreads.length > 0
326 ? [
327 "This permanently clears conversation history for those threads and any archived threads.",
328 ]
329 : ["This permanently clears any archived conversation history."]),
330 isWholeGroup && !hasOtherMembers
331 ? "This removes only the project entries, not the files on disk."
332 : "Other entries in this grouped project are unaffected.",
333 "This action cannot be undone.",
334 ].join("\n"),
335 { variant: "destructive" },
336 ),
337 );
338 if (confirmed._tag === "Failure" || !confirmed.value) return;
339
340 const draftStore = useComposerDraftStore.getState();
341 for (const member of members) {
342 const memberThreads = projectThreads.filter(
343 (thread) =>
344 thread.environmentId === member.environmentId && thread.projectId === member.id,
345 );
346 const result = mapAtomCommandResult(
347 await deleteProject({
348 environmentId: member.environmentId,
349 input: {
350 projectId: member.id,
351 force: true,
352 },
353 }),
354 () => undefined,
355 );
356 if (result._tag === "Failure") {
357 reportFailure(`Failed to remove "${member.title}"`, result);
358 return;
359 }
360 const projectRef = scopeProjectRef(member.environmentId, member.id);
361 releaseProjectDraftUploads(
362 projectRef,
363 memberThreads.map((thread) => scopeThreadRef(thread.environmentId, thread.id)),
364 );
365 const projectDraftThread = draftStore.getDraftThreadByProjectRef(projectRef);
366 if (projectDraftThread) {
367 draftStore.clearDraftThread(projectDraftThread.draftId);
368 }
369 draftStore.clearProjectDraftThreadId(projectRef);
370 }
371
372 if (isWholeGroup && !hasOtherMembers) {
373 void navigate({ to: "/", replace: true });
374 }
375 },
376 [
377 deleteProject,
378 group.displayName,
379 group.memberProjects.length,
380 hasOtherMembers,
381 navigate,
382 reportFailure,
383 threads,
384 ],
385 );
386
387 const checkoutChoices = (
388 <SettingsSection title="Checkouts">
389 {group.memberProjects.map((member) => (
390 <SettingsRow
391 key={member.physicalProjectKey}
392 title={member.environmentLabel ?? "Environment"}
393 description={member.workspaceRoot}
394 control={
395 <Button
396 size="sm"
397 variant="outline"
398 onClick={() => void removeMembers([member])}
399 aria-label={`Remove checkout ${member.workspaceRoot}`}
400 >
401 Remove
402 </Button>
403 }
404 />
405 ))}
406 </SettingsSection>
407 );
408
409 return (
410 <>
411 <SettingsPageContainer className="gap-6">
412 <Alert variant="info">
413 <InfoIcon aria-hidden />
414 <AlertDescription>
415 Can't find a setting? Keep this project picked above and hop to any other settings page.
416 </AlertDescription>
417 </Alert>
418 <SettingsSection id="project-overview" title="Project" hideTitle>
419 <SettingsRow
420 title="Name"
421 description="The shared name for this project group in the sidebar and thread lists."
422 control={
423 <Input
424 key={`${group.projectKey}:${group.displayName}`}
425 size="sm"
426 className="w-full sm:w-64"
427 aria-label="Project name"
428 defaultValue={group.displayName}
429 onChange={() => {
430 projectNameEditedRef.current = true;
431 }}
432 onBlur={(event) => {
433 const wasEdited = projectNameEditedRef.current;
434 projectNameEditedRef.current = false;
435 void renameGroup(event.currentTarget.value, wasEdited);
436 }}
437 onKeyDown={(event) => {
438 if (event.key === "Enter") event.currentTarget.blur();
439 }}
440 />
441 }
442 />
443 <SettingsRow
444 title="Project icon"
445 description={
446 projectIcon?.kind === "lucide"
447 ? `${projectIcon.name} · ${projectIcon.color}`
448 : projectIcon?.kind === "monogram"
449 ? `${projectIcon.text} · ${projectIcon.color}`
450 : projectIcon?.kind === "emoji"
451 ? projectIcon.emoji
452 : (faviconPath ?? "Automatic")
453 }
454 resetAction={
455 group.memberProjects.some(
456 (member) => member.faviconPath != null || member.projectIcon != null,
457 ) ? (
458 <SettingResetButton
459 label="project icon"
460 disabled={isSavingFavicon}
461 onClick={() => void setProjectIcon({ faviconPath: null, projectIcon: null })}
462 />
463 ) : null
464 }
465 control={
466 <div className="flex items-center gap-2">
467 <ProjectFavicon project={representative} className="size-6" />
468 <Button
469 size="sm"
470 variant="outline"
471 type="button"
472 aria-label="Choose a project icon"
473 disabled={isSavingFavicon}
474 onClick={() => setIconPickerOpen(true)}
475 >
476 Choose icon
477 </Button>
478 <Button
479 size="sm"
480 variant="outline"
481 type="button"
482 aria-label="Choose a project icon file"
483 disabled={isSavingFavicon}
484 onClick={() => setFaviconPickerOpen(true)}
485 >
486 Choose file
487 </Button>
488 </div>
489 }
490 />
491 </SettingsSection>
492 <ProjectDefaultsSettings category="project" />
493 <ProjectActionsSettings />
494 {hasMultipleCheckouts ? checkoutChoices : null}
495 <SettingsSection title="Danger">
496 <SettingsRow
497 title={
498 hasOtherMembers
499 ? "Remove checkout"
500 : group.memberProjects.length > 1
501 ? "Remove this project everywhere"
502 : "Remove project"
503 }
504 description={
505 hasOtherMembers
506 ? "Deletes the selected machine's checkout entries and their threads. Other machines and files on disk are not touched."
507 : group.memberProjects.length > 1
508 ? `Deletes all ${group.memberProjects.length} checkout entries and their threads on every machine. Files on disk are not touched.`
509 : "Deletes the project entry and its threads. Files on disk are not touched."
510 }
511 control={
512 <Button
513 size="sm"
514 variant="destructive-outline"
515 onClick={() => void removeMembers(group.memberProjects)}
516 >
517 <Trash2Icon />
518 {hasOtherMembers
519 ? "Remove checkout"
520 : group.memberProjects.length > 1
521 ? "Remove all entries"
522 : "Remove project"}
523 </Button>
524 }
525 />
526 </SettingsSection>
527 </SettingsPageContainer>
528
529 <ProjectFaviconPickerDialog
530 key={`${representative.environmentId}:${representative.workspaceRoot}:${faviconPickerOpen}`}
531 cwd={representative.workspaceRoot}
532 environmentId={representative.environmentId}
533 onOpenChange={setFaviconPickerOpen}
534 {...(pickProjectFavicon
535 ? { onPickExternal: () => pickProjectFavicon(representative.workspaceRoot) }
536 : {})}
537 onSelect={(path) => void setProjectIcon({ faviconPath: path, projectIcon: null })}
538 open={faviconPickerOpen}
539 projectName={group.displayName}
540 />
541 {iconPickerOpen ? (
542 <Suspense fallback={null}>
543 <ProjectIconPickerDialog
544 current={projectIcon}
545 projectName={representative.title}
546 open
547 onOpenChange={setIconPickerOpen}
548 onSelect={(icon) => void setProjectIcon({ faviconPath: null, projectIcon: icon })}
549 />
550 </Suspense>
551 ) : null}
552 </>
553 );
554}