From c191038c2dfc8ce470b3800b20c5eb000f908f6e Mon Sep 17 00:00:00 2001 From: Jaayden Halko Date: Fri, 4 Dec 2026 13:02:53 +0800 Subject: [PATCH] feat(site/src): add the Coder Agents projects page (#32083) Adds the Coder Agents Projects page at `/agents/projects`, the last piece of the Projects page and pinned projects design. The sidebar's **Projects** item (#32040) now opens a real page instead of falling through to the chat route. - **Page:** a **Projects** header with **New project** (the existing create dialog) and two tabs, **Your projects** and **Shared with you**. The selected tab is kept in the URL. The page pairs the project list with the project summaries (#32026) by project ID. - **Order:** pinned projects first, in sidebar order, then the rest by latest chat activity, newest first; projects with no chats go last; ties go by name. - **Cards:** icon, name and a two-line description. The footer shows **Needs attention** (a chat is waiting for input, errored or paused), otherwise **Thinking** (a chat is running), otherwise **N unread** / **N read** / **No chats**; who the project is shared with, in the same words as the project page heading (for example **Everyone, 2 members, 1 group**), or a lock when only the owner can use it; and the latest chat activity time. The whole card links to the project page. - **Pinning:** a pinned card shows a pin icon that turns into an **Unpin project** button on hover or focus. The card's menu has **Pin project** or **Unpin project** next to the existing project actions. While a pin is being saved, the card shows a spinner instead of **Pin project**, so it can't be sent twice. - **States:** loading skeletons, an error with **Retry**, and empty states for both tabs. The page's Storybook stories and the user docs are in the PR stacked on top, to keep this one under the size limit.
Verification `pnpm check`, `pnpm lint` (tsc, oxlint, circular deps, React Compiler, knip), the page and card tests and `make pre-commit` pass. The repository's frontend deep review ran on this diff, with every blocking and should-fix finding fixed. Dogfood ran on a dev deployment with seeded projects, chats in every state, and projects shared by user and group. It took several rounds; the last ones checked mouse and keyboard focus in the Edit and Delete dialogs, stable card controls after an unpin, the pending-pin state, icon contrast, tooltip placement, and a full regression pass, in light and dark themes and at narrow width. Projects page, dark theme Projects page, light theme Card hover with the Unpin project tooltip Empty Your projects tab Narrow layout
> [!NOTE] > Most of this PR was written by AI agents (Xum, with UAT run through Coder Agents). The verification above is from those runs. --------- Co-authored-by: Cursor --- .../Dialog/DeleteDialog/DeleteDialog.tsx | 8 +- .../ProjectsPage/ProjectCard.test.tsx | 114 +++++++ .../AgentsPage/ProjectsPage/ProjectCard.tsx | 309 ++++++++++++++++++ .../ProjectsPage/ProjectsPage.test.tsx | 184 +++++++++++ .../AgentsPage/ProjectsPage/ProjectsPage.tsx | 265 +++++++++++++++ .../ProjectsPage/ProjectsPageView.tsx | 195 +++++++++++ .../chats/ProjectActionsMenuItems.tsx | 11 +- .../dialogs/ChatProjectDialog.tsx | 7 +- site/src/router.tsx | 4 + 9 files changed, 1091 insertions(+), 6 deletions(-) create mode 100644 site/src/pages/AgentsPage/ProjectsPage/ProjectCard.test.tsx create mode 100644 site/src/pages/AgentsPage/ProjectsPage/ProjectCard.tsx create mode 100644 site/src/pages/AgentsPage/ProjectsPage/ProjectsPage.test.tsx create mode 100644 site/src/pages/AgentsPage/ProjectsPage/ProjectsPage.tsx create mode 100644 site/src/pages/AgentsPage/ProjectsPage/ProjectsPageView.tsx diff --git a/site/src/components/Dialog/DeleteDialog/DeleteDialog.tsx b/site/src/components/Dialog/DeleteDialog/DeleteDialog.tsx index 2e8ac78013f..f328a90bd0e 100644 --- a/site/src/components/Dialog/DeleteDialog/DeleteDialog.tsx +++ b/site/src/components/Dialog/DeleteDialog/DeleteDialog.tsx @@ -26,6 +26,7 @@ type DeleteDialogProps = { title?: string; label?: string; confirmText?: string; + onCloseAutoFocus?: (event: Event) => void; }; export const DeleteDialog: React.FC = ({ @@ -41,6 +42,7 @@ export const DeleteDialog: React.FC = ({ title, label, confirmText = "Delete", + onCloseAutoFocus, }) => { const confirmation = useDeleteConfirmation(name, isOpen); @@ -59,7 +61,11 @@ export const DeleteDialog: React.FC = ({ return ( - + {title ?? `Delete ${entity}`} diff --git a/site/src/pages/AgentsPage/ProjectsPage/ProjectCard.test.tsx b/site/src/pages/AgentsPage/ProjectsPage/ProjectCard.test.tsx new file mode 100644 index 00000000000..2aabf4f6d23 --- /dev/null +++ b/site/src/pages/AgentsPage/ProjectsPage/ProjectCard.test.tsx @@ -0,0 +1,114 @@ +import { act, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { MemoryRouter } from "react-router"; +import { describe, expect, it, onTestFinished, vi } from "vitest"; +import type { ChatProject, ChatProjectSummary } from "#/api/typesGenerated"; +import { + MockChatProject, + MockChatProjectSummary, +} from "#/testHelpers/entities"; +import { renderComponent } from "#/testHelpers/renderHelpers"; +import { ProjectCard } from "./ProjectCard"; + +const renderCard = ( + overrides: Partial = {}, + project: ChatProject = MockChatProject, +) => { + const callbacks = { + onPin: vi.fn(), + onUnpin: vi.fn(), + onEdit: vi.fn(), + onDelete: vi.fn(), + }; + renderComponent( + + + , + ); + return callbacks; +}; + +describe("ProjectCard", () => { + it.each<[string, Partial, ChatProject, string]>([ + [ + "a pinned private project", + {}, + MockChatProject, + "Pinned. No chats. Only you.", + ], + [ + "an active shared project", + { + pinned: false, + pin_order: 0, + own_chat_count: 4, + own_unread_count: 3, + last_activity_at: "2026-01-01T10:00:00Z", + }, + { ...MockChatProject, member_count: 2, group_count: 1 }, + "3 unread chats. 2 members, 1 group. Last activity 2 hours ago.", + ], + ])("describes %s", (_, overrides, project, description) => { + vi.setSystemTime("2026-01-01T12:00:00Z"); + onTestFinished(() => { + vi.useRealTimers(); + }); + renderCard(overrides, project); + expect( + screen.getByRole("link", { name: MockChatProject.name }), + ).toHaveAccessibleDescription(description); + }); + + it("unpins from the pin button and keeps focus in the card", async () => { + const user = userEvent.setup(); + const { onUnpin } = renderCard(); + await user.click( + screen.getByRole("button", { name: `Unpin ${MockChatProject.name}` }), + ); + expect(onUnpin).toHaveBeenCalledOnce(); + expect( + screen.getByRole("button", { + name: `Open project actions for ${MockChatProject.name}`, + }), + ).toHaveFocus(); + }); + + it.each([ + ["Edit", "onEdit"], + ["Delete", "onDelete"], + ] as const)("opens %s once the menu has closed", async (item, callback) => { + vi.useFakeTimers(); + onTestFinished(() => { + vi.useRealTimers(); + }); + const user = userEvent.setup({ delay: null }); + const callbacks = renderCard(); + const actions = screen.getByRole("button", { name: /^Open project/ }); + await user.click(actions); + await user.click(screen.getByRole("menuitem", { name: item })); + expect(callbacks[callback]).not.toHaveBeenCalled(); + act(() => vi.runOnlyPendingTimers()); + expect(callbacks[callback]).toHaveBeenCalledExactlyOnceWith(actions); + expect(actions).not.toHaveFocus(); + }); + + it("pins from the actions menu with the keyboard", async () => { + const user = userEvent.setup(); + const { onPin } = renderCard({ pinned: false, pin_order: 0 }); + await user.tab(); + await user.tab(); + await user.keyboard("{Enter}"); + await screen.findByRole("menuitem", { name: "Pin" }); + await user.keyboard("{Enter}"); + expect(onPin).toHaveBeenCalledOnce(); + }); +}); diff --git a/site/src/pages/AgentsPage/ProjectsPage/ProjectCard.tsx b/site/src/pages/AgentsPage/ProjectsPage/ProjectCard.tsx new file mode 100644 index 00000000000..aaf4c965729 --- /dev/null +++ b/site/src/pages/AgentsPage/ProjectsPage/ProjectCard.tsx @@ -0,0 +1,309 @@ +import { + CircleAlertIcon, + EllipsisVerticalIcon, + LockIcon, + PinIcon, + PinOffIcon, + UsersIcon, +} from "lucide-react"; +import { useId, useRef } from "react"; +import { Link, type To } from "react-router"; +import type { ChatProjectWithSummary } from "#/api/queries/chatProjects"; +import type { ChatProject, ChatProjectSummary } from "#/api/typesGenerated"; +import { Button } from "#/components/Button/Button"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, + DropdownMenuTrigger, +} from "#/components/DropdownMenu/DropdownMenu"; +import { Spinner } from "#/components/Spinner/Spinner"; +import { + Tooltip, + TooltipContent, + TooltipTrigger, +} from "#/components/Tooltip/Tooltip"; +import { relativeTime, shortRelativeTime } from "#/utils/time"; +import { ChatProjectIcon } from "../components/ChatProjectIcon"; +import { ProjectActionsMenuItems } from "../components/ChatsSidebar/chats/ProjectActionsMenuItems"; +import { getChatStatusDisplay } from "../components/ChatsSidebar/tree/statusConfig"; +import { formatProjectMembers } from "../components/ProjectPage/projectAccess"; + +type ProjectCardProps = { + readonly summary: ChatProjectWithSummary; + readonly to: To; + readonly onPin: () => void; + readonly onUnpin: () => void; + readonly pinPending: boolean; + readonly onEdit: (returnFocusTo: HTMLElement | null) => void; + readonly onDelete: (returnFocusTo: HTMLElement | null) => void; +}; + +const runningStatus = getChatStatusDisplay("running"); + +export const ProjectCard: React.FC = ({ + summary, + to, + onPin, + onUnpin, + pinPending, + onEdit, + onDelete, +}) => { + const { project, pinned, last_activity_at } = summary; + const descriptionId = useId(); + return ( +
+
+ +
+
+

+ + {project.name} + +

+ {project.description && ( +

+ {project.description} +

+ )} +
+ +
+ + + {last_activity_at && ( + + )} +
+ +
+ ); +}; + +type ProjectCardActionsProps = Omit & { + readonly project: ChatProject; + readonly pinned: boolean; +}; + +const ProjectCardActions: React.FC = ({ + project, + pinned, + pinPending, + onPin, + onUnpin, + onEdit, + onDelete, +}) => { + const actionsButtonRef = useRef(null); + // Edit and Delete open their dialog after the menu closes, or the closing + // menu takes focus back from the dialog. + const openPickedDialogRef = useRef(undefined); + return ( +
+ {pinned ? ( + + + + + + Unpin project + + + ) : ( + // Holds the pin's place so a double-click on Unpin misses the card link. + + + + )} + + + + + { + const openDialog = openPickedDialogRef.current; + openPickedDialogRef.current = undefined; + if (openDialog) { + event.preventDefault(); + openDialog(actionsButtonRef.current); + } + }} + > + { + openPickedDialogRef.current = onEdit; + }} + onDelete={() => { + openPickedDialogRef.current = onDelete; + }} + /> + + +
+ ); +}; + +type ProjectMembersProps = { + readonly project: ChatProject; +}; + +const ownerOnlyLabel = "Only you"; + +const isOwnerOnly = (project: ChatProject) => + project.member_count === 1 && project.group_count === 0; + +const ProjectMembers: React.FC = ({ project }) => { + if (isOwnerOnly(project)) { + return ( + + + ); + } + return ( + + + ); +}; + +const UnreadDot: React.FC = () => ( + +); + +type Activity = { + readonly Icon?: React.ComponentType<{ className?: string }>; + readonly iconClassName?: string; + readonly label: string; + readonly description: string; +}; + +const chatsNoun = (count: number) => (count === 1 ? "chat" : "chats"); + +const getActivity = ({ + own_chat_count, + own_needs_attention, + own_running, + own_unread_count, +}: ChatProjectSummary): Activity => { + if (own_needs_attention) { + return { + Icon: CircleAlertIcon, + iconClassName: "text-highlight-orange", + label: "Needs attention", + description: "Needs attention", + }; + } + if (own_running) { + return { + Icon: runningStatus.icon, + iconClassName: runningStatus.className, + label: "Thinking", + description: "Thinking", + }; + } + if (own_unread_count > 0) { + return { + Icon: UnreadDot, + label: `${own_unread_count} unread`, + description: `${own_unread_count} unread ${chatsNoun(own_unread_count)}`, + }; + } + if (own_chat_count > 0) { + return { + label: `${own_chat_count} read`, + description: `${own_chat_count} read ${chatsNoun(own_chat_count)}`, + }; + } + return { label: "No chats", description: "No chats" }; +}; + +const describeProject = (summary: ChatProjectWithSummary): string => { + const { project, pinned, last_activity_at } = summary; + const parts = [ + getActivity(summary).description, + isOwnerOnly(project) ? ownerOnlyLabel : formatProjectMembers(project), + ]; + if (pinned) { + parts.unshift("Pinned"); + } + if (last_activity_at) { + parts.push(`Last activity ${relativeTime(last_activity_at)}`); + } + return `${parts.join(". ")}.`; +}; + +type ActivityLabelProps = { + readonly summary: ChatProjectSummary; +}; + +const ActivityLabel: React.FC = ({ summary }) => { + const { Icon, iconClassName, label } = getActivity(summary); + return ( + + {Icon && ( + + )} + {label} + + ); +}; diff --git a/site/src/pages/AgentsPage/ProjectsPage/ProjectsPage.test.tsx b/site/src/pages/AgentsPage/ProjectsPage/ProjectsPage.test.tsx new file mode 100644 index 00000000000..d3f41f1cc70 --- /dev/null +++ b/site/src/pages/AgentsPage/ProjectsPage/ProjectsPage.test.tsx @@ -0,0 +1,184 @@ +import { screen, waitFor } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { describe, expect, it, vi } from "vitest"; +import { API } from "#/api/api"; +import type { ChatProjectWithSummary } from "#/api/queries/chatProjects"; +import type { ChatProjectSummary } from "#/api/typesGenerated"; +import { + MockChatProject, + MockChatProjectSummary, + MockUserMember, + MockUserOwner, +} from "#/testHelpers/entities"; +import { renderWithAuth } from "#/testHelpers/renderHelpers"; +import ProjectsPage from "./ProjectsPage"; + +vi.mock("../components/AgentPageHeader", () => ({ + AgentPageHeader: () => null, +})); + +const summary = ( + name: string, + overrides: Partial = {}, + ownerId = MockUserOwner.id, +): ChatProjectWithSummary => ({ + ...MockChatProjectSummary, + pinned: false, + pin_order: 0, + ...overrides, + project_id: name, + project: { ...MockChatProject, id: name, name, owner_id: ownerId }, +}); + +const mockProjectsApi = (summaries: readonly ChatProjectWithSummary[]) => { + vi.spyOn(API.experimental, "getChatProjects").mockResolvedValue( + summaries.map(({ project }) => project), + ); + return vi + .spyOn(API.experimental, "getChatProjectSummaries") + .mockResolvedValue([...summaries]); +}; + +const cardNames = () => + screen.getAllByRole("link").map((link) => link.textContent); + +describe("ProjectsPage", () => { + it("orders your projects and lists others' projects under Shared with you", async () => { + const user = userEvent.setup(); + const earlier = "2026-11-01T00:00:00Z"; + const later = "2026-11-02T00:00:00Z"; + mockProjectsApi([ + summary("zeta"), + summary("Alpha"), + summary("theirs", {}, MockUserMember.id), + summary("older", { last_activity_at: earlier }), + summary("second pin", { pinned: true, pin_order: 2 }), + summary("newer", { last_activity_at: later }), + summary("Tied", { last_activity_at: later }), + summary("first pin", { pinned: true, pin_order: 1 }), + ]); + renderWithAuth(); + await screen.findByRole("link", { name: "zeta" }); + expect(cardNames()).toEqual([ + "first pin", + "second pin", + "newer", + "Tied", + "older", + "Alpha", + "zeta", + ]); + await user.click(screen.getByRole("tab", { name: "Shared with you" })); + await waitFor(() => expect(cardNames()).toEqual(["theirs"])); + }); + + it("pins at the end and holds back Pin while each project's pin is pending", async () => { + const user = userEvent.setup(); + mockProjectsApi([summary("India"), summary("Kilo")]); + const pin = vi + .spyOn(API.experimental, "pinChatProject") + .mockReturnValue(new Promise(() => {})); + renderWithAuth(); + const openActions = async (name: string) => + user.click( + await screen.findByRole("button", { + name: `Open project actions for ${name}`, + }), + ); + + // Pins run in order, so Kilo's pin waits behind India's. + for (const name of ["India", "Kilo"]) { + await openActions(name); + await user.click(await screen.findByRole("menuitem", { name: "Pin" })); + } + await waitFor(() => + expect(pin).toHaveBeenCalledWith( + MockChatProject.organization_id, + "India", + ), + ); + await openActions("India"); + await screen.findByRole("menuitem", { name: "Edit" }); + expect(screen.queryByRole("menuitem", { name: "Pin" })).toBeNull(); + }); + + it("unpins once when the pin button is double-clicked", async () => { + const user = userEvent.setup({ delay: null }); + mockProjectsApi([ + summary("Juliet", { pinned: true, pin_order: 1 }), + summary("Kilo"), + ]); + const unpin = vi + .spyOn(API.experimental, "unpinChatProject") + .mockResolvedValue(); + const pin = vi + .spyOn(API.experimental, "pinChatProject") + .mockReturnValue(new Promise(() => {})); + renderWithAuth(); + await user.dblClick( + await screen.findByRole("button", { name: "Unpin Juliet" }), + ); + // Pin changes run in order, so this pin is sent after any second unpin. + await user.click( + screen.getByRole("button", { name: "Open project actions for Kilo" }), + ); + await user.click(screen.getByRole("menuitem", { name: "Pin" })); + await waitFor(() => expect(pin).toHaveBeenCalled()); + expect(unpin).toHaveBeenCalledOnce(); + }); + + it.each(["Edit", "Delete"])( + "returns focus to the actions button when %s is cancelled", + async (item) => { + const user = userEvent.setup(); + mockProjectsApi([summary("Kilo")]); + renderWithAuth(); + const actions = await screen.findByRole("button", { + name: "Open project actions for Kilo", + }); + await user.click(actions); + await user.click(screen.getByRole("menuitem", { name: item })); + await screen.findByRole("dialog"); + await user.keyboard("{Escape}"); + await waitFor(() => expect(actions).toHaveFocus()); + }, + ); + + it("keeps the delete dialog open while deleting, then focuses New project", async () => { + const user = userEvent.setup(); + mockProjectsApi([summary("Kilo")]); + let finishDelete = () => {}; + vi.spyOn(API.experimental, "deleteChatProject").mockReturnValue( + new Promise((resolve) => { + finishDelete = resolve; + }), + ); + renderWithAuth(); + await user.click( + await screen.findByRole("button", { + name: "Open project actions for Kilo", + }), + ); + await user.click(screen.getByRole("menuitem", { name: "Delete" })); + await user.type( + await screen.findByLabelText("Name of the project to delete"), + "Kilo", + ); + await user.click(screen.getByRole("button", { name: "Delete" })); + await user.keyboard("{Escape}"); + finishDelete(); + await waitFor(() => + expect(screen.getByRole("button", { name: "New project" })).toHaveFocus(), + ); + }); + + it("moves focus to New project when Retry is clicked", async () => { + const user = userEvent.setup(); + mockProjectsApi([summary("Kilo")]).mockRejectedValueOnce(new Error("boom")); + renderWithAuth(); + await user.click(await screen.findByRole("button", { name: "Retry" })); + await waitFor(() => + expect(screen.getByRole("button", { name: "New project" })).toHaveFocus(), + ); + }); +}); diff --git a/site/src/pages/AgentsPage/ProjectsPage/ProjectsPage.tsx b/site/src/pages/AgentsPage/ProjectsPage/ProjectsPage.tsx new file mode 100644 index 00000000000..452236f5185 --- /dev/null +++ b/site/src/pages/AgentsPage/ProjectsPage/ProjectsPage.tsx @@ -0,0 +1,265 @@ +import { useRef, useState } from "react"; +import { + useMutation, + useMutationState, + useQuery, + useQueryClient, +} from "react-query"; +import { useLocation } from "react-router"; +import { getErrorMessage } from "#/api/errors"; +import { + type ChatProjectWithSummary, + chatProjectSummaries, + chatProjects, + createChatProject, + deleteChatProject, + joinChatProjectSummaries, + pinChatProject, + unpinChatProject, + updateChatProject, +} from "#/api/queries/chatProjects"; +import type { ChatProject } from "#/api/typesGenerated"; +import { DeleteDialog } from "#/components/Dialog/DeleteDialog/DeleteDialog"; +import { toast } from "#/components/Toaster/toast"; +import { useAuthenticated } from "#/hooks/useAuthenticated"; +import { useSearchParamsKey } from "#/hooks/useSearchParamsKey"; +import { + getDefaultOrganizationId, + useDashboard, +} from "#/modules/dashboard/useDashboard"; +import { pageTitle } from "#/utils/page"; +import { draftStorageKeys } from "../components/AgentCreateForm"; +import { AgentPageHeader } from "../components/AgentPageHeader"; +import { + ChatProjectDialog, + type ChatProjectFormValues, +} from "../components/ChatsSidebar/dialogs/ChatProjectDialog"; +import { normalizeLocationSearch } from "../components/ChatsSidebar/locationSearch"; +import { type ProjectsByTab, ProjectsPageView } from "./ProjectsPageView"; + +const tabSearchParam = "tab"; + +type DialogState = { readonly project?: ChatProject; readonly open: boolean }; + +// Unpins and reorders share the pin mutation key. +const isPinVariables = ( + variables: unknown, +): variables is { readonly project: ChatProject } => + typeof variables === "object" && variables !== null && "project" in variables; + +const compareNames = (a: ChatProjectWithSummary, b: ChatProjectWithSummary) => + a.project.name.localeCompare(b.project.name, "en-US", { + sensitivity: "accent", + }); + +const activityTime = (summary: ChatProjectWithSummary) => + summary.last_activity_at ? Date.parse(summary.last_activity_at) : 0; + +const compareSummaries = ( + a: ChatProjectWithSummary, + b: ChatProjectWithSummary, +) => { + if (a.pinned !== b.pinned) { + return a.pinned ? -1 : 1; + } + if (a.pinned) { + return a.pin_order - b.pin_order || compareNames(a, b); + } + return activityTime(b) - activityTime(a) || compareNames(a, b); +}; + +const getProjectsByTab = ( + summaries: readonly ChatProjectWithSummary[], + userId: string, +): ProjectsByTab => { + const sorted = summaries.toSorted(compareSummaries); + return { + yours: sorted.filter((summary) => summary.project.owner_id === userId), + shared: sorted.filter((summary) => summary.project.owner_id !== userId), + }; +}; + +const ProjectsPage: React.FC = () => { + const { user } = useAuthenticated(); + const { organizations } = useDashboard(); + const location = useLocation(); + const queryClient = useQueryClient(); + const tabState = useSearchParamsKey({ key: tabSearchParam, replace: false }); + const projectsQuery = useQuery(chatProjects()); + const summariesQuery = useQuery(chatProjectSummaries()); + + const createMutation = useMutation(createChatProject(queryClient)); + const updateMutation = useMutation(updateChatProject(queryClient)); + // Dialogs keep their project after closing so the exit animation does not + // render empty. + const [projectDialog, setProjectDialog] = useState({ + open: false, + }); + const [deleteDialog, setDeleteDialog] = useState({ + open: false, + }); + + const newProjectButtonRef = useRef(null); + const returnFocusRef = useRef(null); + + const deleteMutation = useMutation({ + ...deleteChatProject(queryClient), + onSuccess: (_data, project) => { + const draftKeys = draftStorageKeys(project.id); + localStorage.removeItem(draftKeys.text); + localStorage.removeItem(draftKeys.attachments); + returnFocusRef.current = newProjectButtonRef.current; + setDeleteDialog({ project, open: false }); + }, + onError: (error) => { + toast.error(getErrorMessage(error, "Failed to delete project.")); + }, + }); + + const pinOptions = pinChatProject(queryClient); + const pinMutation = useMutation({ + ...pinOptions, + onError: (error) => { + toast.error(getErrorMessage(error, "Failed to pin project.")); + }, + }); + const unpinOptions = unpinChatProject(queryClient); + const unpinMutation = useMutation({ + ...unpinOptions, + onError: (error, project, context) => { + unpinOptions.onError?.(error, project, context); + toast.error(getErrorMessage(error, "Failed to unpin project.")); + }, + }); + const pendingPinIds = new Set( + useMutationState({ + filters: { mutationKey: pinOptions.mutationKey, status: "pending" }, + select: ({ state: { variables } }) => + isPinVariables(variables) ? variables.project.id : undefined, + }).filter((id) => id !== undefined), + ); + // isPending updates a render late, so a fast double-click would unpin twice. + const unpinningIdRef = useRef(undefined); + + // The dialogs have no trigger for Radix to refocus on close. + const returnFocus = (event: Event) => { + event.preventDefault(); + returnFocusRef.current?.focus(); + }; + + const linkSearchParams = new URLSearchParams(location.search); + linkSearchParams.delete(tabSearchParam); + const projectLinkSearch = normalizeLocationSearch( + linkSearchParams.toString(), + ); + const projectsByTab = + projectsQuery.data && summariesQuery.data + ? getProjectsByTab( + joinChatProjectSummaries(projectsQuery.data, summariesQuery.data), + user.id, + ) + : undefined; + const projectMutation = projectDialog.project + ? updateMutation + : createMutation; + + const openProjectDialog = ( + project: ChatProject | undefined, + returnFocusTo: HTMLElement | null, + ) => { + returnFocusRef.current = returnFocusTo; + createMutation.reset(); + updateMutation.reset(); + setProjectDialog({ project, open: true }); + }; + const closeProjectDialog = () => { + setProjectDialog((current) => ({ ...current, open: false })); + }; + const handleProjectSubmit = async ({ + organizationId, + ...request + }: ChatProjectFormValues) => { + const { project } = projectDialog; + if (project) { + await updateMutation.mutateAsync({ project, request }); + } else if (organizationId) { + await createMutation.mutateAsync({ organizationId, request }); + } + closeProjectDialog(); + }; + + return ( + <> + {pageTitle("Projects", "Agents")} + + + tab === "shared" ? tabState.setValue(tab) : tabState.deleteValue() + } + projects={projectsByTab} + error={projectsQuery.error ?? summariesQuery.error} + onRetry={() => { + // Refetching a query with no data clears its error, unmounting Retry. + newProjectButtonRef.current?.focus(); + projectsQuery.refetch(); + summariesQuery.refetch(); + }} + projectLinkSearch={projectLinkSearch} + newProjectButtonRef={newProjectButtonRef} + onCreateProject={() => + openProjectDialog(undefined, newProjectButtonRef.current) + } + onPin={(project) => pinMutation.mutate({ project })} + pendingPinIds={pendingPinIds} + onUnpin={(project) => { + if (unpinningIdRef.current === project.id) return; + unpinningIdRef.current = project.id; + unpinMutation.mutate(project, { + onSettled: () => { + unpinningIdRef.current = undefined; + }, + }); + }} + onEdit={openProjectDialog} + onDelete={(project, returnFocusTo) => { + returnFocusRef.current = returnFocusTo; + setDeleteDialog({ project, open: true }); + }} + /> + { + if (!open) closeProjectDialog(); + }} + onCloseAutoFocus={returnFocus} + isSubmitting={projectMutation.isPending} + error={projectMutation.error} + onSubmit={handleProjectSubmit} + /> + + deleteDialog.project && deleteMutation.mutate(deleteDialog.project) + } + onCancel={() => { + if (!deleteMutation.isPending) { + setDeleteDialog((current) => ({ ...current, open: false })); + } + }} + onCloseAutoFocus={returnFocus} + entity="project" + name={deleteDialog.project?.name ?? ""} + confirmLoading={deleteMutation.isPending} + info="Its memories and instructions will be deleted. Chats in it, including chats started by people it is shared with, will be kept and move back to each owner's Chats list." + /> + + ); +}; + +export default ProjectsPage; diff --git a/site/src/pages/AgentsPage/ProjectsPage/ProjectsPageView.tsx b/site/src/pages/AgentsPage/ProjectsPage/ProjectsPageView.tsx new file mode 100644 index 00000000000..ec86d734ccf --- /dev/null +++ b/site/src/pages/AgentsPage/ProjectsPage/ProjectsPageView.tsx @@ -0,0 +1,195 @@ +import { PlusIcon } from "lucide-react"; +import type { ChatProjectWithSummary } from "#/api/queries/chatProjects"; +import type { ChatProject } from "#/api/typesGenerated"; +import { ErrorAlert } from "#/components/Alert/ErrorAlert"; +import { Button } from "#/components/Button/Button"; +import { Skeleton } from "#/components/Skeleton/Skeleton"; +import { + Tabs, + TabsContent, + TabsList, + TabsTrigger, +} from "#/components/Tabs/Tabs"; +import { buildAgentProjectPath } from "../utils/navigation"; +import { ProjectCard } from "./ProjectCard"; + +type ProjectsTab = "yours" | "shared"; + +export type ProjectsByTab = Readonly< + Record +>; + +type ProjectAction = ( + project: ChatProject, + returnFocusTo: HTMLElement | null, +) => void; + +type ProjectsPageViewProps = { + readonly tab: ProjectsTab; + readonly onTabChange: (tab: ProjectsTab) => void; + readonly projects: ProjectsByTab | undefined; + readonly error: unknown; + readonly onRetry: () => void; + readonly projectLinkSearch: string; + readonly newProjectButtonRef: React.Ref; + readonly onCreateProject: () => void; + readonly onPin: (project: ChatProject) => void; + readonly onUnpin: (project: ChatProject) => void; + readonly pendingPinIds: ReadonlySet; + readonly onEdit: ProjectAction; + readonly onDelete: ProjectAction; +}; + +export const ProjectsPageView: React.FC = ({ + tab, + onTabChange, + projects, + error, + onRetry, + projectLinkSearch, + newProjectButtonRef, + onCreateProject, + onPin, + onUnpin, + pendingPinIds, + onEdit, + onDelete, +}) => { + const summaries = projects?.[tab]; + let body: React.ReactNode = null; + if (summaries && summaries.length > 0) { + body = ( + + {summaries.map((summary) => ( + onPin(summary.project)} + onUnpin={() => onUnpin(summary.project)} + pinPending={pendingPinIds.has(summary.project.id)} + onEdit={(returnFocusTo) => onEdit(summary.project, returnFocusTo)} + onDelete={(returnFocusTo) => + onDelete(summary.project, returnFocusTo) + } + /> + ))} + + ); + } else if (summaries && tab === "yours") { + body = ( + + + + ); + } else if (summaries) { + body = ( + + ); + } else if (!error) { + body = ( + + Loading projects + {Array.from({ length: 6 }, (_, index) => ( + + ))} + + ); + } + + return ( +
+
+
+

+ Projects +

+ +
+ + onTabChange(value === "shared" ? "shared" : "yours") + } + > + + Your projects + Shared with you + + {/* One panel serves both tabs; only the selected one mounts. */} + + {Boolean(error) && ( + + Retry + + } + /> + )} + {body} + + +
+
+ ); +}; + +const ProjectGrid: React.FC> = (props) => ( +
+); + +type EmptyProjectsProps = { + readonly title: string; + readonly description: string; + readonly children?: React.ReactNode; +}; + +const EmptyProjects: React.FC = ({ + title, + description, + children, +}) => ( +
+ +); diff --git a/site/src/pages/AgentsPage/components/ChatsSidebar/chats/ProjectActionsMenuItems.tsx b/site/src/pages/AgentsPage/components/ChatsSidebar/chats/ProjectActionsMenuItems.tsx index 60afa6cab72..ab260a711e9 100644 --- a/site/src/pages/AgentsPage/components/ChatsSidebar/chats/ProjectActionsMenuItems.tsx +++ b/site/src/pages/AgentsPage/components/ChatsSidebar/chats/ProjectActionsMenuItems.tsx @@ -22,6 +22,7 @@ type ProjectActionsMenuItemsProps = { /** Adds a "New chat" item linking here. Omit on the project page itself. */ readonly projectPath?: To; readonly onNewChatInPlace?: () => void; + readonly onPin?: () => void; readonly onUnpin?: () => void; readonly onMoveUp?: () => void; readonly onMoveDown?: () => void; @@ -43,6 +44,7 @@ export const ProjectActionsMenuItems: React.FC< Separator, projectPath, onNewChatInPlace, + onPin, onUnpin, onMoveUp, onMoveDown, @@ -50,7 +52,7 @@ export const ProjectActionsMenuItems: React.FC< onEdit, onDelete, }) => { - const hasItemsAboveDelete = onUnpin || permissions.update; + const hasItemsAboveDelete = onPin || onUnpin || permissions.update; return ( <> {projectPath !== undefined && ( @@ -65,11 +67,12 @@ export const ProjectActionsMenuItems: React.FC< New chat - {(onUnpin || hasProjectUpdateOrDeleteAction(permissions)) && ( - - )} + {(onPin || + onUnpin || + hasProjectUpdateOrDeleteAction(permissions)) && } )} + {onPin && Pin} {onUnpin && Unpin} {onMoveUp && ( diff --git a/site/src/pages/AgentsPage/components/ChatsSidebar/dialogs/ChatProjectDialog.tsx b/site/src/pages/AgentsPage/components/ChatsSidebar/dialogs/ChatProjectDialog.tsx index 67bcc6c5040..21ec4668c83 100644 --- a/site/src/pages/AgentsPage/components/ChatsSidebar/dialogs/ChatProjectDialog.tsx +++ b/site/src/pages/AgentsPage/components/ChatsSidebar/dialogs/ChatProjectDialog.tsx @@ -92,6 +92,7 @@ type ChatProjectDialogProps = { * through `error`. */ readonly onSubmit: (values: ChatProjectFormValues) => unknown; + readonly onCloseAutoFocus?: (event: Event) => void; }; export const ChatProjectDialog: React.FC = ({ @@ -103,6 +104,7 @@ export const ChatProjectDialog: React.FC = ({ isSubmitting, error, onSubmit, + onCloseAutoFocus, }) => { // Covers the window between Save and the caller's isSubmitting update. const [isSaving, setIsSaving] = useState(false); @@ -121,7 +123,10 @@ export const ChatProjectDialog: React.FC = ({ return ( - + import("./pages/AgentsPage/AgentCreatePage/AgentCreatePage"), ); +const ProjectsPage = lazy( + () => import("./pages/AgentsPage/ProjectsPage/ProjectsPage"), +); const AgentSettingsLayout = lazy( () => import("./pages/AgentsPage/AgentSettingsPage/AgentSettingsLayout"), ); @@ -937,6 +940,7 @@ export const router = createBrowserRouter( element={} /> + } /> } />