feat(web): overhaul project settings into a real settings page (#5768)

Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
Theo BrowneandClaude Fable 5 authored and GitHub committed 2026-08-08 18:50:03 -07:00
1 parent 5208bdeb0d
commit 288d8e3457
11 files changed
+1609 -756

No files matched your search

@@ -1505,6 +1505,17 @@ function OpenCommandPaletteDialog(props: {
},
});
actionItems.push({
kind: "action",
value: "action:project-settings",
searchTerms: ["project", "settings", "scripts", "model", "grouping", "checkout"],
title: "Project settings",
icon: <FolderIcon className={ITEM_ICON_CLASS} />,
run: async () => {
await navigate({ to: "/settings/projects" });
},
});
const rootGroups = buildRootGroups({ actionItems, recentThreadItems });
const sourceSelectionViewValue =
addProjectEnvironmentId === null ? null : `sources:${addProjectEnvironmentId}`;
+32 -382
View File
@@ -1,61 +1,28 @@
import type {
ProjectScript,
ProjectScriptIcon,
ResolvedKeybindingsConfig,
T3ProjectFileScript,
} from "@t3tools/contracts";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
type AtomCommandResult,
} from "@t3tools/client-runtime/state/runtime";
import {
BugIcon,
ChevronDownIcon,
DownloadIcon,
FlaskConicalIcon,
HammerIcon,
ListChecksIcon,
PlayIcon,
PlusIcon,
SettingsIcon,
WrenchIcon,
} from "lucide-react";
import React, { type FormEvent, type KeyboardEvent, useCallback, useMemo, useState } from "react";
import { ChevronDownIcon, DownloadIcon, PlusIcon, SettingsIcon } from "lucide-react";
import { useCallback, useMemo, useState } from "react";
import {
keybindingValueForCommand,
decodeProjectScriptKeybindingRule,
} from "~/lib/projectScriptKeybindings";
import { keybindingFromKeyboardEvent } from "~/components/settings/KeybindingsSettings.logic";
import {
commandForProjectScript,
nextProjectScriptId,
primaryProjectScript,
} from "~/projectScripts";
import { commandForProjectScript, primaryProjectScript } from "~/projectScripts";
import { shortcutLabelForCommand } from "~/keybindings";
import {
AlertDialog,
AlertDialogClose,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogPopup,
AlertDialogTitle,
} from "./ui/alert-dialog";
EMPTY_PROJECT_SCRIPT_INPUT,
editorRequestForScript,
ProjectScriptEditorDialog,
ScriptIcon,
type NewProjectScriptInput,
type ProjectScriptActionResult,
type ProjectScriptEditorRequest,
} from "./projectScriptEditor";
import { Button } from "./ui/button";
import {
Dialog,
DialogDescription,
DialogFooter,
DialogHeader,
DialogPanel,
DialogPopup,
DialogTitle,
} from "./ui/dialog";
import { Group, GroupSeparator } from "./ui/group";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import {
Menu,
MenuGroup,
@@ -66,48 +33,9 @@ import {
MenuShortcut,
MenuTrigger,
} from "./ui/menu";
import { Popover, PopoverPopup, PopoverTrigger } from "./ui/popover";
import { Switch } from "./ui/switch";
import { Textarea } from "./ui/textarea";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
const SCRIPT_ICONS: Array<{ id: ProjectScriptIcon; label: string }> = [
{ id: "play", label: "Play" },
{ id: "test", label: "Test" },
{ id: "lint", label: "Lint" },
{ id: "configure", label: "Configure" },
{ id: "build", label: "Build" },
{ id: "debug", label: "Debug" },
];
function ScriptIcon({
icon,
className = "size-3.5",
}: {
icon: ProjectScriptIcon;
className?: string;
}) {
if (icon === "test") return <FlaskConicalIcon className={className} />;
if (icon === "lint") return <ListChecksIcon className={className} />;
if (icon === "configure") return <WrenchIcon className={className} />;
if (icon === "build") return <HammerIcon className={className} />;
if (icon === "debug") return <BugIcon className={className} />;
return <PlayIcon className={className} />;
}
export interface NewProjectScriptInput {
name: string;
command: string;
icon: ProjectScriptIcon;
runOnWorktreeCreate: boolean;
keybinding: string | null;
/** Optional URL to open in the in-app preview when this script runs. */
previewUrl: string | null;
/** When true, automatically open the preview panel pointed at `previewUrl`. */
autoOpenPreview: boolean;
}
export type ProjectScriptActionResult = AtomCommandResult<void, unknown>;
export type { NewProjectScriptInput, ProjectScriptActionResult };
const NO_FILE_SCRIPTS: ReadonlyArray<T3ProjectFileScript> = [];
@@ -136,23 +64,11 @@ export default function ProjectScriptsControl({
onUpdateScript,
onDeleteScript,
}: ProjectScriptsControlProps) {
const addScriptFormId = React.useId();
const [editingScriptId, setEditingScriptId] = useState<string | null>(null);
const [actionsMenuOpen, setActionsMenuOpen] = useState({
scripts: false,
imports: false,
});
const [dialogOpen, setDialogOpen] = useState(false);
const [name, setName] = useState("");
const [command, setCommand] = useState("");
const [icon, setIcon] = useState<ProjectScriptIcon>("play");
const [iconPickerOpen, setIconPickerOpen] = useState(false);
const [runOnWorktreeCreate, setRunOnWorktreeCreate] = useState(false);
const [keybinding, setKeybinding] = useState("");
const [previewUrl, setPreviewUrl] = useState("");
const [autoOpenPreview, setAutoOpenPreview] = useState(false);
const [validationError, setValidationError] = useState<string | null>(null);
const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
const [editorRequest, setEditorRequest] = useState<ProjectScriptEditorRequest | null>(null);
const primaryScript = useMemo(() => {
if (preferredScriptId) {
@@ -173,112 +89,23 @@ export default function ProjectScriptsControl({
),
[fileScripts, scripts],
);
const isEditing = editingScriptId !== null;
const dropdownItemClassName =
"data-highlighted:bg-transparent data-highlighted:text-foreground hover:bg-accent hover:text-accent-foreground focus-visible:bg-accent focus-visible:text-accent-foreground data-highlighted:hover:bg-accent data-highlighted:hover:text-accent-foreground data-highlighted:focus-visible:bg-accent data-highlighted:focus-visible:text-accent-foreground";
const captureKeybinding = (event: KeyboardEvent<HTMLInputElement>) => {
if (event.key === "Tab") return;
event.preventDefault();
if (event.key === "Backspace" || event.key === "Delete") {
setKeybinding("");
return;
}
const next = keybindingFromKeyboardEvent(event, navigator.platform);
if (!next) return;
setKeybinding(next);
};
const submitAddScript = async (event: FormEvent) => {
event.preventDefault();
const trimmedName = name.trim();
const trimmedCommand = command.trim();
if (trimmedName.length === 0) {
setValidationError("Name is required.");
return;
}
if (trimmedCommand.length === 0) {
setValidationError("Command is required.");
return;
}
setValidationError(null);
let payload: NewProjectScriptInput;
try {
const scriptIdForValidation =
editingScriptId ??
nextProjectScriptId(
trimmedName,
scripts.map((script) => script.id),
);
const keybindingRule = decodeProjectScriptKeybindingRule({
keybinding,
command: commandForProjectScript(scriptIdForValidation),
});
const trimmedPreviewUrl = previewUrl.trim();
payload = {
name: trimmedName,
command: trimmedCommand,
icon,
runOnWorktreeCreate,
keybinding: keybindingRule?.key ?? null,
previewUrl: trimmedPreviewUrl.length > 0 ? trimmedPreviewUrl : null,
autoOpenPreview: trimmedPreviewUrl.length > 0 ? autoOpenPreview : false,
} satisfies NewProjectScriptInput;
} catch (error) {
setValidationError(error instanceof Error ? error.message : "Failed to save action.");
return;
}
const result = editingScriptId
? await onUpdateScript(editingScriptId, payload)
: await onAddScript(payload);
if (result._tag === "Failure") {
if (!isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
setValidationError(error instanceof Error ? error.message : "Failed to save action.");
}
return;
}
setDialogOpen(false);
setIconPickerOpen(false);
};
const openAddDialog = () => {
setEditingScriptId(null);
setName("");
setCommand("");
setIcon("play");
setIconPickerOpen(false);
setRunOnWorktreeCreate(false);
setKeybinding("");
setPreviewUrl("");
setAutoOpenPreview(false);
setValidationError(null);
setDialogOpen(true);
setEditorRequest({ scriptId: null, initial: EMPTY_PROJECT_SCRIPT_INPUT });
};
const openEditDialog = (script: ProjectScript) => {
setActionsMenuOpen({ scripts: false, imports: false });
setEditingScriptId(script.id);
setName(script.name);
setCommand(script.command);
setIcon(script.icon);
setIconPickerOpen(false);
setRunOnWorktreeCreate(script.runOnWorktreeCreate);
setKeybinding(keybindingValueForCommand(keybindings, commandForProjectScript(script.id)) ?? "");
setPreviewUrl(script.previewUrl ?? "");
setAutoOpenPreview(script.autoOpenPreview ?? false);
setValidationError(null);
setDialogOpen(true);
setEditorRequest(editorRequestForScript(script, keybindings));
};
const confirmDeleteScript = useCallback(() => {
if (!editingScriptId) return;
setDeleteConfirmOpen(false);
setDialogOpen(false);
void onDeleteScript(editingScriptId);
}, [editingScriptId, onDeleteScript]);
const submitScript = useCallback(
(scriptId: string | null, input: NewProjectScriptInput) =>
scriptId === null ? onAddScript(input) : onUpdateScript(scriptId, input),
[onAddScript, onUpdateScript],
);
const importFileScript = async (fileScript: T3ProjectFileScript) => {
const payload: NewProjectScriptInput = {
@@ -295,17 +122,11 @@ export default function ProjectScriptsControl({
// Surface the failure through the regular add dialog, prefilled so the
// user can adjust and retry.
const error = squashAtomCommandFailure(result);
setEditingScriptId(null);
setName(payload.name);
setCommand(payload.command);
setIcon(payload.icon);
setIconPickerOpen(false);
setRunOnWorktreeCreate(payload.runOnWorktreeCreate);
setKeybinding("");
setPreviewUrl(payload.previewUrl ?? "");
setAutoOpenPreview(payload.autoOpenPreview);
setValidationError(error instanceof Error ? error.message : "Failed to import action.");
setDialogOpen(true);
setEditorRequest({
scriptId: null,
initial: payload,
error: error instanceof Error ? error.message : "Failed to import action.",
});
}
};
@@ -466,184 +287,13 @@ export default function ProjectScriptsControl({
</Tooltip>
)}
<Dialog
onOpenChange={(open) => {
setDialogOpen(open);
if (!open) {
setIconPickerOpen(false);
}
}}
onOpenChangeComplete={(open) => {
if (open) return;
setEditingScriptId(null);
setName("");
setCommand("");
setIcon("play");
setRunOnWorktreeCreate(false);
setKeybinding("");
setPreviewUrl("");
setAutoOpenPreview(false);
setValidationError(null);
}}
open={dialogOpen}
>
<DialogPopup>
<DialogHeader>
<DialogTitle>{isEditing ? "Edit Action" : "Add Action"}</DialogTitle>
<DialogDescription>
Actions are project-scoped commands you can run from the top bar or keybindings.
</DialogDescription>
</DialogHeader>
<DialogPanel>
<form id={addScriptFormId} className="space-y-4" onSubmit={submitAddScript}>
<div className="space-y-1.5">
<Label htmlFor="script-name">Name</Label>
<div className="flex items-center gap-2">
<Popover onOpenChange={setIconPickerOpen} open={iconPickerOpen}>
<PopoverTrigger
render={
<Button
type="button"
variant="outline"
className="size-9 shrink-0 hover:bg-popover active:bg-popover data-pressed:bg-popover data-pressed:shadow-xs/5 data-pressed:before:shadow-[0_1px_--theme(--color-black/4%)] dark:border-transparent dark:bg-white/[0.035] dark:data-pressed:before:shadow-none"
aria-label="Choose icon"
/>
}
>
<ScriptIcon icon={icon} className="size-4.5" />
</PopoverTrigger>
<PopoverPopup align="start">
<div className="grid grid-cols-3 gap-2">
{SCRIPT_ICONS.map((entry) => {
const isSelected = entry.id === icon;
return (
<button
key={entry.id}
type="button"
className={`relative flex flex-col items-center gap-2 rounded-md border px-2 py-2 text-xs dark:border-transparent ${
isSelected
? "border-primary/70 bg-primary/10 dark:ring-1 dark:ring-primary/30"
: "border-border/70 hover:bg-accent/60 dark:bg-white/[0.035]"
}`}
onClick={() => {
setIcon(entry.id);
setIconPickerOpen(false);
}}
>
<ScriptIcon icon={entry.id} className="size-4" />
<span>{entry.label}</span>
</button>
);
})}
</div>
</PopoverPopup>
</Popover>
<Input
id="script-name"
autoFocus
placeholder="Test"
value={name}
onChange={(event) => setName(event.target.value)}
/>
</div>
</div>
<div className="space-y-1.5">
<Label htmlFor="script-keybinding">Keybinding</Label>
<Input
id="script-keybinding"
placeholder="Press shortcut"
value={keybinding}
readOnly
onKeyDown={captureKeybinding}
/>
<p className="text-xs text-muted-foreground">
Press a shortcut. Use <code>Backspace</code> to clear.
</p>
</div>
<div className="space-y-1.5">
<Label htmlFor="script-command">Command</Label>
<Textarea
id="script-command"
placeholder="bun test"
value={command}
onChange={(event) => setCommand(event.target.value)}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="script-preview-url">Preview URL (optional)</Label>
<Input
id="script-preview-url"
placeholder="http://localhost:5173"
value={previewUrl}
onChange={(event) => setPreviewUrl(event.target.value)}
/>
<p className="text-xs text-muted-foreground">
Open this URL in the in-app preview when this action runs.
</p>
</div>
<label className="flex items-center justify-between gap-3 rounded-md border border-border/70 px-3 py-2 text-sm dark:border-transparent dark:bg-white/[0.035]">
<span>Run automatically on worktree creation</span>
<Switch
checked={runOnWorktreeCreate}
onCheckedChange={(checked) => setRunOnWorktreeCreate(Boolean(checked))}
/>
</label>
<label
className={`flex items-center justify-between gap-3 rounded-md border border-border/70 px-3 py-2 text-sm dark:border-transparent dark:bg-white/[0.035] ${
previewUrl.trim().length === 0 ? "opacity-60" : ""
}`}
>
<span>Open preview automatically when this action runs</span>
<Switch
checked={autoOpenPreview}
disabled={previewUrl.trim().length === 0}
onCheckedChange={(checked) => setAutoOpenPreview(Boolean(checked))}
/>
</label>
{validationError && <p className="text-sm text-destructive">{validationError}</p>}
</form>
</DialogPanel>
<DialogFooter className="dark:border-transparent dark:bg-transparent">
{isEditing && (
<Button
type="button"
variant="destructive-outline"
className="mr-auto"
onClick={() => setDeleteConfirmOpen(true)}
>
Delete
</Button>
)}
<Button
type="button"
variant="outline"
onClick={() => {
setDialogOpen(false);
}}
>
Cancel
</Button>
<Button form={addScriptFormId} type="submit">
{isEditing ? "Save changes" : "Save action"}
</Button>
</DialogFooter>
</DialogPopup>
</Dialog>
<AlertDialog open={deleteConfirmOpen} onOpenChange={setDeleteConfirmOpen}>
<AlertDialogPopup>
<AlertDialogHeader>
<AlertDialogTitle>Delete action "{name}"?</AlertDialogTitle>
<AlertDialogDescription>This action cannot be undone.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
<Button variant="destructive" onClick={confirmDeleteScript}>
Delete action
</Button>
</AlertDialogFooter>
</AlertDialogPopup>
</AlertDialog>
<ProjectScriptEditorDialog
request={editorRequest}
scripts={scripts}
onSubmit={submitScript}
onDelete={(scriptId) => void onDeleteScript(scriptId)}
onClose={() => setEditorRequest(null)}
/>
</>
);
}
+11 -365
View File
@@ -28,7 +28,7 @@ import {
scopeThreadRef,
scopedThreadKey,
} from "@t3tools/client-runtime/environment";
import type { ScopedThreadRef, SidebarProjectGroupingMode } from "@t3tools/contracts";
import type { ScopedThreadRef } from "@t3tools/contracts";
import type { TimestampFormat } from "@t3tools/contracts/settings";
import {
AlarmClockIcon,
@@ -39,7 +39,6 @@ import {
CircleCheckIcon,
CircleDashedIcon,
ClockIcon,
CopyIcon,
FolderIcon,
FolderPlusIcon,
GitBranchIcon,
@@ -51,7 +50,6 @@ import {
ServerIcon,
SquarePenIcon,
TerminalIcon,
Trash2Icon,
Undo2Icon,
XIcon,
} from "lucide-react";
@@ -89,14 +87,9 @@ import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../termina
import { isMacPlatform } from "~/lib/utils";
import { useOpenPrLink } from "../lib/openPullRequestLink";
import { readLocalApi } from "../localApi";
import {
deriveProjectGroupingOverrideKey,
getProjectOrderKey,
selectProjectGroupingSettings,
} from "../logicalProject";
import { getProjectOrderKey, selectProjectGroupingSettings } from "../logicalProject";
import {
buildSidebarProjectSnapshots,
type SidebarProjectGroupMember,
type SidebarProjectSnapshot,
} from "../sidebarProjectGrouping";
import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore";
@@ -105,7 +98,7 @@ import { useThreadActions } from "../hooks/useThreadActions";
import { useHandleNewThread } from "../hooks/useHandleNewThread";
import { openCommandPalette } from "../commandPaletteBus";
import { startNewThreadFromContext } from "../lib/chatThreadActions";
import { useClientSettings, useUpdateClientSettings } from "../hooks/useSettings";
import { useClientSettings } from "../hooks/useSettings";
import { useCopyToClipboard } from "../hooks/useCopyToClipboard";
import { useNowMinute } from "../hooks/useNowMinute";
import { useEnvironments, usePrimaryEnvironmentId } from "../state/environments";
@@ -113,7 +106,6 @@ import { useProjects, useThreadShells } from "../state/entities";
import { environmentServerConfigsAtom, primaryServerKeybindingsAtom } from "../state/server";
import { vcsEnvironment } from "../state/vcs";
import { threadEnvironment } from "../state/threads";
import { projectEnvironment } from "../state/projects";
import { useEnvironmentQuery } from "../state/query";
import { useAtomCommand } from "../state/use-atom-command";
import {
@@ -138,7 +130,6 @@ import {
resolveSidebarThreadStatus,
searchSidebarThreadsByTitle,
resolveWorkingStartedAt,
shouldNavigateAfterProjectRemoval,
sortLogicalProjectsForSidebar,
sortPinnedThreadsForSidebar,
sortSettledThreadsForSidebar,
@@ -166,18 +157,8 @@ import { primaryServerProvidersAtom } from "../state/server";
import { useThreadRunningTerminalIds } from "../state/terminalSessions";
import { stackedThreadToast, toastManager } from "./ui/toast";
import { Button } from "./ui/button";
import {
Dialog,
DialogDescription,
DialogFooter,
DialogHeader,
DialogPanel,
DialogPopup,
DialogTitle,
} from "./ui/dialog";
import { Input } from "./ui/input";
import { Menu, MenuPopup, MenuRadioGroup, MenuRadioItem, MenuTrigger } from "./ui/menu";
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./ui/select";
import { SidebarContent, SidebarGroup, SidebarMenuButton, useSidebar } from "./ui/sidebar";
import { SidebarChromeFooter, SidebarChromeHeader } from "./sidebar/SidebarChrome";
import { Popover, PopoverPopup, PopoverTrigger } from "./ui/popover";
@@ -188,11 +169,6 @@ import { useComposerDraftStore } from "../composerDraftStore";
// stays behind an explicit Show more.
const SETTLED_TAIL_INITIAL_COUNT = 10;
const SETTLED_TAIL_PAGE_COUNT = 25;
const PROJECT_GROUPING_MODE_LABELS: Record<SidebarProjectGroupingMode, string> = {
repository: "Group by repository",
repository_path: "Group by repository path",
separate: "Keep separate",
};
function compactSidebarTimeLabel(label: string): string {
if (label === "just now") return "now";
@@ -1379,13 +1355,6 @@ export default function Sidebar() {
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
reportFailure: false,
});
const deleteProject = useAtomCommand(projectEnvironment.delete, {
reportFailure: false,
});
const updateProject = useAtomCommand(projectEnvironment.update, {
reportFailure: false,
});
const updateSettings = useUpdateClientSettings();
const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{ path: string }>({
onCopy: ({ path }) => {
toastManager.add({
@@ -1423,9 +1392,6 @@ export default function Sidebar() {
);
},
});
const [projectActionsTarget, setProjectActionsTarget] = useState<SidebarProjectSnapshot | null>(
null,
);
const [projectScopeMenuOpen, setProjectScopeMenuOpen] = useState(false);
const newThreadContext = useHandleNewThread();
const openAddProjectCommandPalette = useCallback(
@@ -1602,156 +1568,20 @@ export default function Sidebar() {
clearSelection();
}, [clearSelection, projectScopeKey]);
const handleRemoveProjectMembers = useCallback(
async (projectGroup: SidebarProjectSnapshot, members: readonly SidebarProjectGroupMember[]) => {
const api = readLocalApi();
if (!api) return;
const memberKeys = new Set(members.map((member) => `${member.environmentId}:${member.id}`));
const projectThreads = threads.filter((thread) =>
memberKeys.has(`${thread.environmentId}:${thread.projectId}`),
);
const isWholeGroup = members.length === projectGroup.memberProjects.length;
const singleMember = members.length === 1 ? members[0]! : null;
const targetLabel = singleMember?.title ?? projectGroup.displayName;
const confirmed = await settlePromise(() =>
api.dialogs.confirm(
projectThreads.length > 0
? [
`Remove project "${targetLabel}" and delete its ${projectThreads.length} thread${projectThreads.length === 1 ? "" : "s"}?`,
...(singleMember
? [
`Path: ${singleMember.workspaceRoot}`,
...(singleMember.environmentLabel
? [`Environment: ${singleMember.environmentLabel}`]
: []),
]
: [`This removes ${members.length} grouped project entries.`]),
"This permanently clears conversation history for those threads.",
isWholeGroup
? "This removes only the project entries, not the files on disk."
: "Other entries in this grouped project are unaffected.",
"This action cannot be undone.",
].join("\n")
: [
`Remove project "${targetLabel}"?`,
...(singleMember
? [
`Path: ${singleMember.workspaceRoot}`,
...(singleMember.environmentLabel
? [`Environment: ${singleMember.environmentLabel}`]
: []),
]
: [`This removes ${members.length} grouped project entries.`]),
isWholeGroup
? "This removes only the project entries, not the files on disk."
: "Other entries in this grouped project are unaffected.",
].join("\n"),
),
);
if (confirmed._tag === "Failure" || !confirmed.value) return;
const draftStore = useComposerDraftStore.getState();
let shouldNavigate = false;
for (const project of members) {
const memberThreads = projectThreads.filter(
(thread) =>
thread.environmentId === project.environmentId && thread.projectId === project.id,
);
const projectRef = scopeProjectRef(project.environmentId, project.id);
const projectDraftThread = draftStore.getDraftThreadByProjectRef(projectRef);
const memberRemovalNeedsNavigation = shouldNavigateAfterProjectRemoval({
routeTarget: routeTargetRef.current,
projectThreads: memberThreads,
projectDraftId: projectDraftThread?.draftId ?? null,
});
const result = await deleteProject({
environmentId: project.environmentId,
input: {
projectId: project.id,
...(memberThreads.length > 0 ? { force: true } : {}),
},
});
if (result._tag === "Failure") {
if (!isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: `Failed to remove "${project.title}"`,
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
}
if (shouldNavigate) {
void router.navigate({ to: "/" });
}
return;
}
shouldNavigate ||= memberRemovalNeedsNavigation;
if (projectDraftThread) {
draftStore.clearDraftThread(projectDraftThread.draftId);
}
draftStore.clearProjectDraftThreadId(projectRef);
}
if (shouldNavigate) {
void router.navigate({ to: "/" });
}
},
[deleteProject, router, threads],
);
const renameProjectMember = useCallback(
async (member: SidebarProjectGroupMember, nextTitle: string) => {
const title = nextTitle.trim();
if (!title) {
toastManager.add({ type: "warning", title: "Project title cannot be empty" });
return;
}
if (title === member.title) return;
const result = await updateProject({
environmentId: member.environmentId,
input: { projectId: member.id, title },
});
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to rename project",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
}
},
[updateProject],
);
const updateProjectGroupingPreference = useCallback(
(member: SidebarProjectGroupMember, selection: SidebarProjectGroupingMode | "inherit") => {
const overrideKey = deriveProjectGroupingOverrideKey(member);
const nextOverrides = { ...projectGroupingSettings.sidebarProjectGroupingOverrides };
if (selection === "inherit") {
delete nextOverrides[overrideKey];
} else {
nextOverrides[overrideKey] = selection;
}
updateSettings({ sidebarProjectGroupingOverrides: nextOverrides });
},
[projectGroupingSettings.sidebarProjectGroupingOverrides, updateSettings],
);
const handleProjectActions = useCallback(
(event: ReactMouseEvent<HTMLButtonElement>, projectGroup: SidebarProjectSnapshot) => {
event.preventDefault();
event.stopPropagation();
setProjectScopeMenuOpen(false);
window.requestAnimationFrame(() => setProjectActionsTarget(projectGroup));
if (isMobile) {
setOpenMobile(false);
}
void router.navigate({
to: "/settings/projects/$projectKey",
params: { projectKey: projectGroup.projectKey },
});
},
[],
[isMobile, router, setOpenMobile],
);
// Settled threads stay in the live shell stream (settled ≠ archived), so
@@ -3545,190 +3375,6 @@ export default function Sidebar() {
) : null}
</SidebarGroup>
</SidebarContent>
<Dialog
open={projectActionsTarget !== null}
onOpenChange={(open) => {
if (!open) setProjectActionsTarget(null);
}}
>
<DialogPopup className="max-w-xl">
<DialogHeader className="gap-3 pb-1!">
<DialogTitle className="text-balance">Project settings</DialogTitle>
<DialogDescription className="sr-only">
Manage project names, grouping rules, and environments.
</DialogDescription>
<div className="grid gap-1.5 text-base text-muted-foreground">
{projectActionsTarget?.memberProjects.map((member) => (
<div key={member.physicalProjectKey} className="flex min-w-0 items-center gap-3">
<span className="flex min-w-0 items-center gap-1">
<FolderIcon className="size-3.5 shrink-0 opacity-60" />
<span className="min-w-0 truncate font-mono">{member.workspaceRoot}</span>
<Button
size="icon-xs"
variant="ghost"
className="size-4 shrink-0 rounded-sm"
aria-label="Copy project path"
title="Copy project path"
onClick={() =>
copyPathToClipboard(member.workspaceRoot, { path: member.workspaceRoot })
}
>
<CopyIcon className="size-3.5" />
</Button>
</span>
<span className="flex min-w-0 shrink-0 items-center gap-1">
<ServerIcon className="size-3.5 shrink-0 opacity-60" />
<span className="min-w-0 truncate">
{member.environmentLabel ?? "Current environment"}
</span>
</span>
</div>
))}
</div>
</DialogHeader>
<DialogPanel className="p-0">
<div className="divide-y divide-border/60">
{projectActionsTarget?.memberProjects.map((member) => (
<section
key={member.physicalProjectKey}
className="grid min-w-0 gap-5 px-6 pb-5 pt-2 sm:gap-4 sm:pb-4 sm:pt-2"
>
<div className="grid gap-4 sm:grid-cols-2 sm:gap-3">
<label className="grid min-w-0 gap-1.5">
<span className="font-medium text-foreground">Project name</span>
<Input
key={`${member.physicalProjectKey}:${member.title}`}
aria-label={`Project name in ${member.environmentLabel ?? "current environment"}`}
defaultValue={member.title}
onBlur={(event) => {
void renameProjectMember(member, event.currentTarget.value);
}}
onKeyDown={(event) => {
if (event.key === "Enter") event.currentTarget.blur();
}}
/>
</label>
<label className="grid min-w-0 gap-1.5">
<span className="font-medium text-foreground">Grouping rule</span>
<Select
value={
projectGroupingSettings.sidebarProjectGroupingOverrides?.[
deriveProjectGroupingOverrideKey(member)
] ?? "inherit"
}
onValueChange={(value) => {
if (
value === "inherit" ||
value === "repository" ||
value === "repository_path" ||
value === "separate"
) {
updateProjectGroupingPreference(member, value);
}
}}
>
<SelectTrigger
className="w-full sm:min-h-7.5"
aria-label={`Grouping rule for ${member.environmentLabel ?? "current environment"}`}
>
<SelectValue>
{(() => {
const selection =
projectGroupingSettings.sidebarProjectGroupingOverrides?.[
deriveProjectGroupingOverrideKey(member)
] ?? "inherit";
return selection === "inherit"
? `Default (${PROJECT_GROUPING_MODE_LABELS[projectGroupingSettings.sidebarProjectGroupingMode]})`
: PROJECT_GROUPING_MODE_LABELS[selection];
})()}
</SelectValue>
</SelectTrigger>
<SelectPopup align="start" alignItemWithTrigger={false}>
<SelectItem hideIndicator value="inherit">
Use global default
</SelectItem>
<SelectItem hideIndicator value="repository">
{PROJECT_GROUPING_MODE_LABELS.repository}
</SelectItem>
<SelectItem hideIndicator value="repository_path">
{PROJECT_GROUPING_MODE_LABELS.repository_path}
</SelectItem>
<SelectItem hideIndicator value="separate">
{PROJECT_GROUPING_MODE_LABELS.separate}
</SelectItem>
</SelectPopup>
</Select>
</label>
</div>
{projectActionsTarget.memberProjects.length > 1 ? (
<div className="flex justify-end">
<Button
size="sm"
variant="ghost"
className="text-destructive-foreground hover:bg-destructive/8 hover:text-destructive-foreground"
onClick={() => {
const projectGroup = projectActionsTarget;
setProjectActionsTarget(null);
void handleRemoveProjectMembers(projectGroup, [member]);
}}
>
<Trash2Icon />
Remove project
</Button>
</div>
) : null}
</section>
))}
</div>
{projectActionsTarget && projectActionsTarget.memberProjects.length > 1 ? (
<div className="flex flex-col gap-3 border-t border-border/60 bg-muted/32 px-6 py-4 sm:flex-row sm:items-center sm:justify-between">
<div className="min-w-0">
<p className="text-base font-medium text-foreground sm:text-sm">
Remove this project everywhere
</p>
<p className="text-base text-pretty text-muted-foreground sm:text-sm">
Deletes all grouped entries and their conversation history.
</p>
</div>
<Button
size="sm"
variant="destructive-outline"
className="shrink-0"
onClick={() => {
const projectGroup = projectActionsTarget;
setProjectActionsTarget(null);
void handleRemoveProjectMembers(projectGroup, projectGroup.memberProjects);
}}
>
<Trash2Icon />
Remove all entries
</Button>
</div>
) : null}
</DialogPanel>
<DialogFooter
variant="bare"
className={cn(
projectActionsTarget?.memberProjects.length === 1 && "sm:justify-between",
)}
>
{projectActionsTarget?.memberProjects.length === 1 ? (
<Button
variant="destructive-outline"
onClick={() => {
const projectGroup = projectActionsTarget;
setProjectActionsTarget(null);
void handleRemoveProjectMembers(projectGroup, projectGroup.memberProjects);
}}
>
<Trash2Icon />
Remove project
</Button>
) : null}
<Button onClick={() => setProjectActionsTarget(null)}>Close</Button>
</DialogFooter>
</DialogPopup>
</Dialog>
<SidebarChromeFooter />
</>
);
@@ -0,0 +1,415 @@
import type {
ProjectScript,
ProjectScriptIcon,
ResolvedKeybindingsConfig,
} from "@t3tools/contracts";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
type AtomCommandResult,
} from "@t3tools/client-runtime/state/runtime";
import {
BugIcon,
FlaskConicalIcon,
HammerIcon,
ListChecksIcon,
PlayIcon,
WrenchIcon,
} from "lucide-react";
import React, { type FormEvent, type KeyboardEvent, useEffect, useState } from "react";
import {
keybindingValueForCommand,
decodeProjectScriptKeybindingRule,
} from "~/lib/projectScriptKeybindings";
import { keybindingFromKeyboardEvent } from "~/components/settings/KeybindingsSettings.logic";
import { commandForProjectScript, nextProjectScriptId } from "~/projectScripts";
import {
AlertDialog,
AlertDialogClose,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogPopup,
AlertDialogTitle,
} from "./ui/alert-dialog";
import { Button } from "./ui/button";
import {
Dialog,
DialogDescription,
DialogFooter,
DialogHeader,
DialogPanel,
DialogPopup,
DialogTitle,
} from "./ui/dialog";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Popover, PopoverPopup, PopoverTrigger } from "./ui/popover";
import { Switch } from "./ui/switch";
import { Textarea } from "./ui/textarea";
export const SCRIPT_ICONS: Array<{ id: ProjectScriptIcon; label: string }> = [
{ id: "play", label: "Play" },
{ id: "test", label: "Test" },
{ id: "lint", label: "Lint" },
{ id: "configure", label: "Configure" },
{ id: "build", label: "Build" },
{ id: "debug", label: "Debug" },
];
export function ScriptIcon({
icon,
className = "size-3.5",
}: {
icon: ProjectScriptIcon;
className?: string;
}) {
if (icon === "test") return <FlaskConicalIcon className={className} />;
if (icon === "lint") return <ListChecksIcon className={className} />;
if (icon === "configure") return <WrenchIcon className={className} />;
if (icon === "build") return <HammerIcon className={className} />;
if (icon === "debug") return <BugIcon className={className} />;
return <PlayIcon className={className} />;
}
export interface NewProjectScriptInput {
name: string;
command: string;
icon: ProjectScriptIcon;
runOnWorktreeCreate: boolean;
keybinding: string | null;
/** Optional URL to open in the in-app preview when this script runs. */
previewUrl: string | null;
/** When true, automatically open the preview panel pointed at `previewUrl`. */
autoOpenPreview: boolean;
}
export type ProjectScriptActionResult = AtomCommandResult<void, unknown>;
export const EMPTY_PROJECT_SCRIPT_INPUT: NewProjectScriptInput = {
name: "",
command: "",
icon: "play",
runOnWorktreeCreate: false,
keybinding: null,
previewUrl: null,
autoOpenPreview: false,
};
/** What the editor dialog should open with. `scriptId: null` means "add". */
export interface ProjectScriptEditorRequest {
scriptId: string | null;
initial: NewProjectScriptInput;
/** Validation error to show immediately (e.g. a failed t3.json import). */
error?: string;
}
export function editorRequestForScript(
script: ProjectScript,
keybindings: ResolvedKeybindingsConfig,
): ProjectScriptEditorRequest {
return {
scriptId: script.id,
initial: {
name: script.name,
command: script.command,
icon: script.icon,
runOnWorktreeCreate: script.runOnWorktreeCreate,
keybinding: keybindingValueForCommand(keybindings, commandForProjectScript(script.id)),
previewUrl: script.previewUrl ?? null,
autoOpenPreview: script.autoOpenPreview ?? false,
},
};
}
/**
* Add/edit dialog for a project script, shared by the chat-header scripts menu
* and the project settings page. The parent owns which script (if any) is
* being edited via `request`; the dialog owns the form state and validation.
*/
export function ProjectScriptEditorDialog({
request,
scripts,
onSubmit,
onDelete,
onClose,
}: {
request: ProjectScriptEditorRequest | null;
/** Existing scripts, used to derive a unique id for new scripts. */
scripts: ReadonlyArray<ProjectScript>;
onSubmit: (
scriptId: string | null,
input: NewProjectScriptInput,
) => Promise<ProjectScriptActionResult>;
onDelete: (scriptId: string) => void;
onClose: () => void;
}) {
const formId = React.useId();
const [name, setName] = useState("");
const [command, setCommand] = useState("");
const [icon, setIcon] = useState<ProjectScriptIcon>("play");
const [iconPickerOpen, setIconPickerOpen] = useState(false);
const [runOnWorktreeCreate, setRunOnWorktreeCreate] = useState(false);
const [keybinding, setKeybinding] = useState("");
const [previewUrl, setPreviewUrl] = useState("");
const [autoOpenPreview, setAutoOpenPreview] = useState(false);
const [validationError, setValidationError] = useState<string | null>(null);
const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
const isOpen = request !== null;
const isEditing = request?.scriptId != null;
// Hydrate the form whenever a new request opens the dialog.
useEffect(() => {
if (!request) return;
setName(request.initial.name);
setCommand(request.initial.command);
setIcon(request.initial.icon);
setIconPickerOpen(false);
setRunOnWorktreeCreate(request.initial.runOnWorktreeCreate);
setKeybinding(request.initial.keybinding ?? "");
setPreviewUrl(request.initial.previewUrl ?? "");
setAutoOpenPreview(request.initial.autoOpenPreview);
setValidationError(request.error ?? null);
}, [request]);
const captureKeybinding = (event: KeyboardEvent<HTMLInputElement>) => {
if (event.key === "Tab") return;
event.preventDefault();
if (event.key === "Backspace" || event.key === "Delete") {
setKeybinding("");
return;
}
const next = keybindingFromKeyboardEvent(event, navigator.platform);
if (!next) return;
setKeybinding(next);
};
const submit = async (event: FormEvent) => {
event.preventDefault();
if (!request) return;
const trimmedName = name.trim();
const trimmedCommand = command.trim();
if (trimmedName.length === 0) {
setValidationError("Name is required.");
return;
}
if (trimmedCommand.length === 0) {
setValidationError("Command is required.");
return;
}
setValidationError(null);
let payload: NewProjectScriptInput;
try {
const scriptIdForValidation =
request.scriptId ??
nextProjectScriptId(
trimmedName,
scripts.map((script) => script.id),
);
const keybindingRule = decodeProjectScriptKeybindingRule({
keybinding,
command: commandForProjectScript(scriptIdForValidation),
});
const trimmedPreviewUrl = previewUrl.trim();
payload = {
name: trimmedName,
command: trimmedCommand,
icon,
runOnWorktreeCreate,
keybinding: keybindingRule?.key ?? null,
previewUrl: trimmedPreviewUrl.length > 0 ? trimmedPreviewUrl : null,
autoOpenPreview: trimmedPreviewUrl.length > 0 ? autoOpenPreview : false,
} satisfies NewProjectScriptInput;
} catch (error) {
setValidationError(error instanceof Error ? error.message : "Failed to save action.");
return;
}
const result = await onSubmit(request.scriptId, payload);
if (result._tag === "Failure") {
if (!isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
setValidationError(error instanceof Error ? error.message : "Failed to save action.");
}
return;
}
setIconPickerOpen(false);
onClose();
};
return (
<>
<Dialog
open={isOpen}
onOpenChange={(open) => {
if (!open) {
setIconPickerOpen(false);
onClose();
}
}}
>
<DialogPopup>
<DialogHeader>
<DialogTitle>{isEditing ? "Edit Action" : "Add Action"}</DialogTitle>
<DialogDescription>
Actions are project-scoped commands you can run from the top bar or keybindings.
</DialogDescription>
</DialogHeader>
<DialogPanel>
<form id={formId} className="space-y-4" onSubmit={submit}>
<div className="space-y-1.5">
<Label htmlFor="script-name">Name</Label>
<div className="flex items-center gap-2">
<Popover onOpenChange={setIconPickerOpen} open={iconPickerOpen}>
<PopoverTrigger
render={
<Button
type="button"
variant="outline"
className="size-9 shrink-0 hover:bg-popover active:bg-popover data-pressed:bg-popover data-pressed:shadow-xs/5 data-pressed:before:shadow-[0_1px_--theme(--color-black/4%)] dark:border-transparent dark:bg-white/[0.035] dark:data-pressed:before:shadow-none"
aria-label="Choose icon"
/>
}
>
<ScriptIcon icon={icon} className="size-4.5" />
</PopoverTrigger>
<PopoverPopup align="start">
<div className="grid grid-cols-3 gap-2">
{SCRIPT_ICONS.map((entry) => {
const isSelected = entry.id === icon;
return (
<button
key={entry.id}
type="button"
className={`relative flex flex-col items-center gap-2 rounded-md border px-2 py-2 text-xs dark:border-transparent ${
isSelected
? "border-primary/70 bg-primary/10 dark:ring-1 dark:ring-primary/30"
: "border-border/70 hover:bg-accent/60 dark:bg-white/[0.035]"
}`}
onClick={() => {
setIcon(entry.id);
setIconPickerOpen(false);
}}
>
<ScriptIcon icon={entry.id} className="size-4" />
<span>{entry.label}</span>
</button>
);
})}
</div>
</PopoverPopup>
</Popover>
<Input
id="script-name"
autoFocus
placeholder="Test"
value={name}
onChange={(event) => setName(event.target.value)}
/>
</div>
</div>
<div className="space-y-1.5">
<Label htmlFor="script-keybinding">Keybinding</Label>
<Input
id="script-keybinding"
placeholder="Press shortcut"
value={keybinding}
readOnly
onKeyDown={captureKeybinding}
/>
<p className="text-xs text-muted-foreground">
Press a shortcut. Use <code>Backspace</code> to clear.
</p>
</div>
<div className="space-y-1.5">
<Label htmlFor="script-command">Command</Label>
<Textarea
id="script-command"
placeholder="bun test"
value={command}
onChange={(event) => setCommand(event.target.value)}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="script-preview-url">Preview URL (optional)</Label>
<Input
id="script-preview-url"
placeholder="http://localhost:5173"
value={previewUrl}
onChange={(event) => setPreviewUrl(event.target.value)}
/>
<p className="text-xs text-muted-foreground">
Open this URL in the in-app preview when this action runs.
</p>
</div>
<label className="flex items-center justify-between gap-3 rounded-md border border-border/70 px-3 py-2 text-sm dark:border-transparent dark:bg-white/[0.035]">
<span>Run automatically on worktree creation</span>
<Switch
checked={runOnWorktreeCreate}
onCheckedChange={(checked) => setRunOnWorktreeCreate(Boolean(checked))}
/>
</label>
<label
className={`flex items-center justify-between gap-3 rounded-md border border-border/70 px-3 py-2 text-sm dark:border-transparent dark:bg-white/[0.035] ${
previewUrl.trim().length === 0 ? "opacity-60" : ""
}`}
>
<span>Open preview automatically when this action runs</span>
<Switch
checked={autoOpenPreview}
disabled={previewUrl.trim().length === 0}
onCheckedChange={(checked) => setAutoOpenPreview(Boolean(checked))}
/>
</label>
{validationError && <p className="text-sm text-destructive">{validationError}</p>}
</form>
</DialogPanel>
<DialogFooter className="dark:border-transparent dark:bg-transparent">
{isEditing && (
<Button
type="button"
variant="destructive-outline"
className="mr-auto"
onClick={() => setDeleteConfirmOpen(true)}
>
Delete
</Button>
)}
<Button type="button" variant="outline" onClick={onClose}>
Cancel
</Button>
<Button form={formId} type="submit">
{isEditing ? "Save changes" : "Save action"}
</Button>
</DialogFooter>
</DialogPopup>
</Dialog>
<AlertDialog open={deleteConfirmOpen} onOpenChange={setDeleteConfirmOpen}>
<AlertDialogPopup>
<AlertDialogHeader>
<AlertDialogTitle>Delete action "{name}"?</AlertDialogTitle>
<AlertDialogDescription>This action cannot be undone.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
<Button
variant="destructive"
onClick={() => {
if (!request?.scriptId) return;
setDeleteConfirmOpen(false);
onClose();
onDelete(request.scriptId);
}}
>
Delete action
</Button>
</AlertDialogFooter>
</AlertDialogPopup>
</AlertDialog>
</>
);
}
File diff suppressed because it is too large. Load diff
@@ -11,6 +11,7 @@ import {
ArchiveIcon,
ArrowLeftIcon,
BotIcon,
FolderIcon,
GitBranchIcon,
KeyboardIcon,
Link2Icon,
@@ -48,6 +49,7 @@ const SETTINGS_SECTION_ICONS: Readonly<
"/settings/general": Settings2Icon,
"/settings/appearance": PaletteIcon,
"/settings/keybindings": KeyboardIcon,
"/settings/projects": FolderIcon,
"/settings/providers": BotIcon,
"/settings/source-control": GitBranchIcon,
"/settings/connections": Link2Icon,
@@ -279,7 +281,9 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {
))
: SETTINGS_NAV_ITEMS.map((item) => {
const Icon = item.icon;
const isActive = pathname === item.to;
// Prefix match keeps the section active on nested routes
// like /settings/projects/$projectKey.
const isActive = pathname === item.to || pathname.startsWith(`${item.to}/`);
return (
<SidebarMenuItem key={item.to}>
<SidebarMenuButton
@@ -2,6 +2,7 @@ export type SettingsPath =
| "/settings/general"
| "/settings/appearance"
| "/settings/keybindings"
| "/settings/projects"
| "/settings/providers"
| "/settings/source-control"
| "/settings/connections"
@@ -22,6 +23,7 @@ export const SETTINGS_SECTION_LABELS: Readonly<Record<SettingsPath, string>> = {
"/settings/general": "General",
"/settings/appearance": "Appearance",
"/settings/keybindings": "Keybindings",
"/settings/projects": "Projects",
"/settings/providers": "Providers",
"/settings/source-control": "Source Control",
"/settings/connections": "Connections",
@@ -174,6 +176,26 @@ export const SETTINGS_SEARCH_ITEMS = [
title: "Keybindings",
to: "/settings/keybindings",
},
{
id: "projects",
title: "Projects",
to: "/settings/projects",
},
{
id: "project-default-model",
title: "Project default model",
to: "/settings/projects",
},
{
id: "project-scripts",
title: "Project scripts",
to: "/settings/projects",
},
{
id: "project-checkouts",
title: "Project checkouts",
to: "/settings/projects",
},
{
id: "providers",
title: "Providers",
+36 -8
View File
@@ -14,6 +14,41 @@ const decodeT3ProjectFile = Schema.decodeExit(T3ProjectFileFromJson);
const NO_SCRIPTS: ReadonlyArray<T3ProjectFileScript> = [];
export interface T3ProjectFileState {
/**
* - `valid`: t3.json exists and decoded.
* - `invalid`: t3.json exists but fails to decode (the server then ignores
* the whole file, including `iconPath` and every script).
* - `missing`: no readable t3.json at the workspace root.
* - `loading`: the file query has not settled yet.
*/
status: "loading" | "missing" | "invalid" | "valid";
scripts: ReadonlyArray<T3ProjectFileScript>;
}
/**
* Decoded state of the project's checked-in `t3.json`, including whether the
* file exists but is broken — which the runtime otherwise swallows silently.
*/
export function useT3ProjectFileState(
environmentId: EnvironmentId,
cwd: string | null,
): T3ProjectFileState {
const query = useProjectFileQuery(environmentId, cwd ?? "", T3_PROJECT_FILE_NAME, cwd !== null);
const contents = query.data && !query.data.truncated ? query.data.contents : null;
const isPending = query.isPending;
return useMemo(() => {
if (contents === null) {
return { status: isPending ? "loading" : "missing", scripts: NO_SCRIPTS } as const;
}
const decoded = decodeT3ProjectFile(contents);
if (Exit.isFailure(decoded)) {
return { status: "invalid", scripts: NO_SCRIPTS } as const;
}
return { status: "valid", scripts: decoded.value.scripts ?? NO_SCRIPTS } as const;
}, [contents, isPending]);
}
/**
* Scripts declared in the project's checked-in `t3.json`, offered in the
* scripts menu for import. Missing, truncated, or invalid files resolve to
@@ -23,12 +58,5 @@ export function useT3ProjectFileScripts(
environmentId: EnvironmentId,
cwd: string | null,
): ReadonlyArray<T3ProjectFileScript> {
const query = useProjectFileQuery(environmentId, cwd ?? "", T3_PROJECT_FILE_NAME, cwd !== null);
const contents = query.data && !query.data.truncated ? query.data.contents : null;
return useMemo(() => {
if (contents === null) return NO_SCRIPTS;
const decoded = decodeT3ProjectFile(contents);
if (Exit.isFailure(decoded)) return NO_SCRIPTS;
return decoded.value.scripts ?? NO_SCRIPTS;
}, [contents]);
return useT3ProjectFileState(environmentId, cwd).scripts;
}
+43
View File
@@ -17,6 +17,7 @@ import { Route as ChatRouteImport } from './routes/_chat'
import { Route as ChatIndexRouteImport } from './routes/_chat.index'
import { Route as SettingsSourceControlRouteImport } from './routes/settings.source-control'
import { Route as SettingsProvidersRouteImport } from './routes/settings.providers'
import { Route as SettingsProjectsRouteImport } from './routes/settings.projects'
import { Route as SettingsKeybindingsRouteImport } from './routes/settings.keybindings'
import { Route as SettingsGeneralRouteImport } from './routes/settings.general'
import { Route as SettingsDiagnosticsRouteImport } from './routes/settings.diagnostics'
@@ -24,6 +25,7 @@ import { Route as SettingsConnectionsRouteImport } from './routes/settings.conne
import { Route as SettingsArchivedRouteImport } from './routes/settings.archived'
import { Route as SettingsAppearanceRouteImport } from './routes/settings.appearance'
import { Route as ConnectCallbackRouteImport } from './routes/connect_.callback'
import { Route as SettingsProjectsProjectKeyRouteImport } from './routes/settings.projects_.$projectKey'
import { Route as ChatDraftDraftIdRouteImport } from './routes/_chat.draft.$draftId'
import { Route as ChatEnvironmentIdThreadIdRouteImport } from './routes/_chat.$environmentId.$threadId'
@@ -66,6 +68,11 @@ const SettingsProvidersRoute = SettingsProvidersRouteImport.update({
path: '/providers',
getParentRoute: () => SettingsRoute,
} as any)
const SettingsProjectsRoute = SettingsProjectsRouteImport.update({
id: '/projects',
path: '/projects',
getParentRoute: () => SettingsRoute,
} as any)
const SettingsKeybindingsRoute = SettingsKeybindingsRouteImport.update({
id: '/keybindings',
path: '/keybindings',
@@ -101,6 +108,12 @@ const ConnectCallbackRoute = ConnectCallbackRouteImport.update({
path: '/connect/callback',
getParentRoute: () => rootRouteImport,
} as any)
const SettingsProjectsProjectKeyRoute =
SettingsProjectsProjectKeyRouteImport.update({
id: '/projects_/$projectKey',
path: '/projects/$projectKey',
getParentRoute: () => SettingsRoute,
} as any)
const ChatDraftDraftIdRoute = ChatDraftDraftIdRouteImport.update({
id: '/draft/$draftId',
path: '/draft/$draftId',
@@ -126,10 +139,12 @@ export interface FileRoutesByFullPath {
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
'/settings/general': typeof SettingsGeneralRoute
'/settings/keybindings': typeof SettingsKeybindingsRoute
'/settings/projects': typeof SettingsProjectsRoute
'/settings/providers': typeof SettingsProvidersRoute
'/settings/source-control': typeof SettingsSourceControlRoute
'/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute
'/draft/$draftId': typeof ChatDraftDraftIdRoute
'/settings/projects/$projectKey': typeof SettingsProjectsProjectKeyRoute
}
export interface FileRoutesByTo {
'/connect': typeof ConnectRoute
@@ -143,11 +158,13 @@ export interface FileRoutesByTo {
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
'/settings/general': typeof SettingsGeneralRoute
'/settings/keybindings': typeof SettingsKeybindingsRoute
'/settings/projects': typeof SettingsProjectsRoute
'/settings/providers': typeof SettingsProvidersRoute
'/settings/source-control': typeof SettingsSourceControlRoute
'/': typeof ChatIndexRoute
'/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute
'/draft/$draftId': typeof ChatDraftDraftIdRoute
'/settings/projects/$projectKey': typeof SettingsProjectsProjectKeyRoute
}
export interface FileRoutesById {
__root__: typeof rootRouteImport
@@ -163,11 +180,13 @@ export interface FileRoutesById {
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
'/settings/general': typeof SettingsGeneralRoute
'/settings/keybindings': typeof SettingsKeybindingsRoute
'/settings/projects': typeof SettingsProjectsRoute
'/settings/providers': typeof SettingsProvidersRoute
'/settings/source-control': typeof SettingsSourceControlRoute
'/_chat/': typeof ChatIndexRoute
'/_chat/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute
'/_chat/draft/$draftId': typeof ChatDraftDraftIdRoute
'/settings/projects_/$projectKey': typeof SettingsProjectsProjectKeyRoute
}
export interface FileRouteTypes {
fileRoutesByFullPath: FileRoutesByFullPath
@@ -184,10 +203,12 @@ export interface FileRouteTypes {
| '/settings/diagnostics'
| '/settings/general'
| '/settings/keybindings'
| '/settings/projects'
| '/settings/providers'
| '/settings/source-control'
| '/$environmentId/$threadId'
| '/draft/$draftId'
| '/settings/projects/$projectKey'
fileRoutesByTo: FileRoutesByTo
to:
| '/connect'
@@ -201,11 +222,13 @@ export interface FileRouteTypes {
| '/settings/diagnostics'
| '/settings/general'
| '/settings/keybindings'
| '/settings/projects'
| '/settings/providers'
| '/settings/source-control'
| '/'
| '/$environmentId/$threadId'
| '/draft/$draftId'
| '/settings/projects/$projectKey'
id:
| '__root__'
| '/_chat'
@@ -220,11 +243,13 @@ export interface FileRouteTypes {
| '/settings/diagnostics'
| '/settings/general'
| '/settings/keybindings'
| '/settings/projects'
| '/settings/providers'
| '/settings/source-control'
| '/_chat/'
| '/_chat/$environmentId/$threadId'
| '/_chat/draft/$draftId'
| '/settings/projects_/$projectKey'
fileRoutesById: FileRoutesById
}
export interface RootRouteChildren {
@@ -294,6 +319,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof SettingsProvidersRouteImport
parentRoute: typeof SettingsRoute
}
'/settings/projects': {
id: '/settings/projects'
path: '/projects'
fullPath: '/settings/projects'
preLoaderRoute: typeof SettingsProjectsRouteImport
parentRoute: typeof SettingsRoute
}
'/settings/keybindings': {
id: '/settings/keybindings'
path: '/keybindings'
@@ -343,6 +375,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof ConnectCallbackRouteImport
parentRoute: typeof rootRouteImport
}
'/settings/projects_/$projectKey': {
id: '/settings/projects_/$projectKey'
path: '/projects/$projectKey'
fullPath: '/settings/projects/$projectKey'
preLoaderRoute: typeof SettingsProjectsProjectKeyRouteImport
parentRoute: typeof SettingsRoute
}
'/_chat/draft/$draftId': {
id: '/_chat/draft/$draftId'
path: '/draft/$draftId'
@@ -381,8 +420,10 @@ interface SettingsRouteChildren {
SettingsDiagnosticsRoute: typeof SettingsDiagnosticsRoute
SettingsGeneralRoute: typeof SettingsGeneralRoute
SettingsKeybindingsRoute: typeof SettingsKeybindingsRoute
SettingsProjectsRoute: typeof SettingsProjectsRoute
SettingsProvidersRoute: typeof SettingsProvidersRoute
SettingsSourceControlRoute: typeof SettingsSourceControlRoute
SettingsProjectsProjectKeyRoute: typeof SettingsProjectsProjectKeyRoute
}
const SettingsRouteChildren: SettingsRouteChildren = {
@@ -392,8 +433,10 @@ const SettingsRouteChildren: SettingsRouteChildren = {
SettingsDiagnosticsRoute: SettingsDiagnosticsRoute,
SettingsGeneralRoute: SettingsGeneralRoute,
SettingsKeybindingsRoute: SettingsKeybindingsRoute,
SettingsProjectsRoute: SettingsProjectsRoute,
SettingsProvidersRoute: SettingsProvidersRoute,
SettingsSourceControlRoute: SettingsSourceControlRoute,
SettingsProjectsProjectKeyRoute: SettingsProjectsProjectKeyRoute,
}
const SettingsRouteWithChildren = SettingsRoute._addFileChildren(
+11
View File
@@ -0,0 +1,11 @@
import { createFileRoute } from "@tanstack/react-router";
import { ProjectSettingsPanel } from "../components/settings/ProjectSettingsPanel";
function SettingsProjectsRoute() {
return <ProjectSettingsPanel selectedProjectKey={null} />;
}
export const Route = createFileRoute("/settings/projects")({
component: SettingsProjectsRoute,
});
@@ -0,0 +1,12 @@
import { createFileRoute } from "@tanstack/react-router";
import { ProjectSettingsPanel } from "../components/settings/ProjectSettingsPanel";
function SettingsProjectDetailRoute() {
const { projectKey } = Route.useParams();
return <ProjectSettingsPanel selectedProjectKey={projectKey} />;
}
export const Route = createFileRoute("/settings/projects_/$projectKey")({
component: SettingsProjectDetailRoute,
});