diff --git a/src/components/Home/ProjectsSection/AllProjectsTable.tsx b/src/components/Home/ProjectsSection/AllProjectsTable.tsx index 002cd53f7f..8ca61e4d84 100644 --- a/src/components/Home/ProjectsSection/AllProjectsTable.tsx +++ b/src/components/Home/ProjectsSection/AllProjectsTable.tsx @@ -47,7 +47,8 @@ export function AllProjectsTable() { const missingAuthor = me && !author.createdBy; const page = useProjects( { - createdBy: me ? author.createdBy : creator || undefined, + myProjectsFor: me ? author.createdBy : undefined, + createdBy: me ? undefined : creator || undefined, workspaceId, pageSize: 10, pageToken: pageTokens.at(-1), diff --git a/src/components/Home/ProjectsSection/ProjectsSection.test.tsx b/src/components/Home/ProjectsSection/ProjectsSection.test.tsx index a2c02695d0..c524b42665 100644 --- a/src/components/Home/ProjectsSection/ProjectsSection.test.tsx +++ b/src/components/Home/ProjectsSection/ProjectsSection.test.tsx @@ -1,5 +1,5 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { render, screen, waitFor, within } from "@testing-library/react"; +import { render, screen, within } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import type { ReactNode } from "react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; @@ -128,7 +128,10 @@ function mockPagedDirectory() { const projects = [project, otherProject, ...archivedProjects]; vi.mocked(listProjects).mockImplementation(async (params = {}) => { const matching = projects.filter( - ({ createdBy, workspaceId }) => + ({ id, createdBy, workspaceId }) => + (!params.myProjectsFor || + id === project.id || + id === otherProject.id) && (!params.createdBy || createdBy === params.createdBy) && (!params.workspaceId || workspaceId === params.workspaceId), ); @@ -327,29 +330,34 @@ describe("ProjectsSection", () => { expect(screen.getByText("Page 1")).toBeVisible(); }); - it("uses the current user's ID for Me and returns everyone's projects when cleared", async () => { + it("shows projects I created or contributed to with Me and clears back to the directory", async () => { mockPagedDirectory(); const user = userEvent.setup(); renderSection(); const table = within(screen.getByRole("table", { name: "All projects" })); await table.findByRole("link", { name: "Forecasting" }); + expect(screen.queryByRole("button", { name: "My projects" })).toBeNull(); + await user.click(screen.getByRole("button", { name: "Next" })); + await table.findByRole("link", { name: "Archived project 11" }); await user.click(screen.getByRole("button", { name: "Me" })); - await screen.findByRole("button", { name: "Clear user filter" }); - await waitFor(() => { - expect(listProjects).toHaveBeenLastCalledWith( - expect.objectContaining({ createdBy: project.createdBy }), - backendUrl, - ); - expect(table.queryByRole("link", { name: "Forecasting" })).toBeNull(); - }); - expect( - await table.findByRole("link", { name: "Churn model" }), - ).toBeVisible(); + await table.findByRole("link", { name: "Churn model" }); + expect(table.getByRole("link", { name: "Forecasting" })).toBeVisible(); + expect(table.getAllByRole("link")).toHaveLength(2); + expect(listProjects).toHaveBeenLastCalledWith( + expect.objectContaining({ + myProjectsFor: project.createdBy, + createdBy: undefined, + pageToken: undefined, + }), + backendUrl, + ); + await user.click(screen.getByRole("button", { name: "Clear user filter" })); expect( - await table.findByRole("link", { name: "Forecasting" }), + await table.findByRole("link", { name: "Archived project 1" }), ).toBeVisible(); + expect(screen.getByText("Page 1")).toBeVisible(); }); it("keeps cached directory results out of Me when the current user is unknown", async () => { diff --git a/src/components/Home/ProjectsSection/useMyProjects.test.tsx b/src/components/Home/ProjectsSection/useMyProjects.test.tsx index 989024fb52..1dba543089 100644 --- a/src/components/Home/ProjectsSection/useMyProjects.test.tsx +++ b/src/components/Home/ProjectsSection/useMyProjects.test.tsx @@ -37,6 +37,7 @@ const render = () => renderHook(() => useMyProjects(), { wrapper }); describe("useMyProjects", () => { beforeEach(() => { vi.mocked(useBackend).mockReturnValue({ + backendUrl: "https://backend.example", configured: true, available: true, } as unknown as ReturnType); @@ -53,7 +54,8 @@ describe("useMyProjects", () => { await waitFor(() => expect(listProjects).toHaveBeenCalledWith( - expect.objectContaining({ createdBy: "someone@example.com" }), + expect.objectContaining({ myProjectsFor: "someone@example.com" }), + "https://backend.example", ), ); }); @@ -72,7 +74,8 @@ describe("useMyProjects", () => { await waitFor(() => expect(listProjects).toHaveBeenCalledWith( - expect.objectContaining({ createdBy: undefined }), + expect.objectContaining({ myProjectsFor: undefined }), + "https://backend.example", ), ); }); diff --git a/src/components/Home/ProjectsSection/useMyProjects.ts b/src/components/Home/ProjectsSection/useMyProjects.ts index eea3f6bced..33e76873e8 100644 --- a/src/components/Home/ProjectsSection/useMyProjects.ts +++ b/src/components/Home/ProjectsSection/useMyProjects.ts @@ -26,7 +26,7 @@ interface MyProjects { * ways under two cache keys. */ export function useMyProjects(): MyProjects { - const { configured, available } = useBackend(); + const { configured, available, backendUrl } = useBackend(); const { createdBy, isPending: isUserPending, @@ -41,9 +41,19 @@ export function useMyProjects(): MyProjects { fetchNextPage, isFetchingNextPage, } = useInfiniteQuery({ - queryKey: ProjectsQueryKeys.List({ createdBy, pageSize: PAGE_SIZE }), + queryKey: [ + ...ProjectsQueryKeys.List({ + myProjectsFor: createdBy, + pageSize: PAGE_SIZE, + }), + backendUrl, + "infinite", + ], queryFn: ({ pageParam }) => - listProjects({ createdBy, pageSize: PAGE_SIZE, pageToken: pageParam }), + listProjects( + { myProjectsFor: createdBy, pageSize: PAGE_SIZE, pageToken: pageParam }, + backendUrl, + ), initialPageParam: undefined as string | undefined, getNextPageParam: (page) => page.nextPageToken ?? undefined, enabled: configured && available && !isUserPending && userError === null, diff --git a/src/components/Project/AddDocumentDialog.tsx b/src/components/Project/AddDocumentDialog.tsx index bed3e3b012..340e011d6b 100644 --- a/src/components/Project/AddDocumentDialog.tsx +++ b/src/components/Project/AddDocumentDialog.tsx @@ -24,7 +24,9 @@ export function AddDocumentDialog({ open, onOpenChange, }: AddDocumentDialogProps) { - const createResource = useCreateProjectResource(projectId); + const createResource = useCreateProjectResource(projectId, { + recordContribution: true, + }); const notify = useToastNotification(); const { track } = useAnalytics(); diff --git a/src/components/Project/AddPipelineDialog.tsx b/src/components/Project/AddPipelineDialog.tsx index e37df4c615..e531d50cd3 100644 --- a/src/components/Project/AddPipelineDialog.tsx +++ b/src/components/Project/AddPipelineDialog.tsx @@ -30,7 +30,7 @@ export function AddPipelineDialog({ }: AddPipelineDialogProps) { const { data: names, isPending, error } = useLocalPipelineNames(); const { mutate: createResource, isPending: isCreating } = - useCreateProjectResource(projectId); + useCreateProjectResource(projectId, { recordContribution: true }); const notify = useToastNotification(); const { track } = useAnalytics(); diff --git a/src/components/Project/DocumentEditor.tsx b/src/components/Project/DocumentEditor.tsx index 531c7c08d6..0ebf572316 100644 --- a/src/components/Project/DocumentEditor.tsx +++ b/src/components/Project/DocumentEditor.tsx @@ -31,7 +31,9 @@ interface DocumentEditorProps { export function DocumentEditor({ projectId, resource }: DocumentEditorProps) { const saved = documentBody(resource) ?? ""; const [edit, setEdit] = useState(null); - const update = useUpdateProjectResource(projectId); + const update = useUpdateProjectResource(projectId, { + recordContribution: true, + }); const { track } = useAnalytics(); if (edit !== null && edit.draft === saved && !update.isPending) { diff --git a/src/components/Project/ProjectContributors.tsx b/src/components/Project/ProjectContributors.tsx new file mode 100644 index 0000000000..07c8989d84 --- /dev/null +++ b/src/components/Project/ProjectContributors.tsx @@ -0,0 +1,28 @@ +import { BlockStack } from "@/components/ui/layout"; +import { Text } from "@/components/ui/typography"; +import { useProjectContributors } from "@/services/projects/useProjectContributors"; + +export function ProjectContributors({ projectId }: { projectId: string }) { + const { data, error, isPending } = useProjectContributors(projectId); + if (data === null) return null; + + return ( + + + Contributors + + {data?.length ? ( +
    + {data.map((person) => ( +
  • {person}
  • + ))} +
+ ) : ( + + {error?.message ?? + (isPending ? "Loading contributors…" : "No contributors yet.")} + + )} +
+ ); +} diff --git a/src/components/Project/ProjectPage.test.tsx b/src/components/Project/ProjectPage.test.tsx index 9f4b38f7c6..d5487fa5cf 100644 --- a/src/components/Project/ProjectPage.test.tsx +++ b/src/components/Project/ProjectPage.test.tsx @@ -34,6 +34,10 @@ vi.mock("@/services/projects/useProjects", () => ({ useUpdateProjectMetadata: () => ({ mutate: vi.fn(), isPending: false }), })); +vi.mock("@/services/projects/useProjectContributors", () => ({ + useProjectContributors: () => ({ data: ["alice@example.com"] }), +})); + vi.mock("@/services/projects/useProjectResources", () => ({ useProjectResources: () => ({ data: { items: [], nextPageToken: null, totalCount: 0 }, diff --git a/src/components/Project/ProjectSidebar.test.tsx b/src/components/Project/ProjectSidebar.test.tsx index 4bae9e0e73..0095516d68 100644 --- a/src/components/Project/ProjectSidebar.test.tsx +++ b/src/components/Project/ProjectSidebar.test.tsx @@ -7,6 +7,10 @@ import { formatDate } from "@/utils/date"; import { ProjectSidebar } from "./ProjectSidebar"; +vi.mock("@/services/projects/useProjectContributors", () => ({ + useProjectContributors: () => ({ data: ["teammate@example.com"] }), +})); + vi.mock("@tanstack/react-router", async (importOriginal) => ({ ...(await importOriginal()), useNavigate: () => vi.fn(), @@ -90,6 +94,9 @@ describe("ProjectSidebar", () => { it("says who made the project and when", () => { renderSidebar(); + expect( + screen.getByRole("list", { name: "Contributors" }), + ).toHaveTextContent("teammate@example.com"); expect(screen.getByText("alice@example.com")).toBeInTheDocument(); expect(screen.getByText(formatDate(project.createdAt))).toBeInTheDocument(); }); diff --git a/src/components/Project/ProjectSidebar.tsx b/src/components/Project/ProjectSidebar.tsx index 56bb2f8c0b..29c0717bd4 100644 --- a/src/components/Project/ProjectSidebar.tsx +++ b/src/components/Project/ProjectSidebar.tsx @@ -10,6 +10,7 @@ import { formatDate, formatRelativeTime } from "@/utils/date"; import { ColumnHeadingRow } from "./ColumnHeadingRow"; import { ProjectAbout } from "./ProjectAbout"; import { ProjectActions } from "./ProjectActions"; +import { ProjectContributors } from "./ProjectContributors"; const HEADING_ID = "project-sidebar-heading"; @@ -61,6 +62,8 @@ export function ProjectSidebar({ project }: ProjectSidebarProps) { + + diff --git a/src/components/shared/Submitters/Tangle/useSubmitPipeline.ts b/src/components/shared/Submitters/Tangle/useSubmitPipeline.ts index 514da58530..1adf0569f9 100644 --- a/src/components/shared/Submitters/Tangle/useSubmitPipeline.ts +++ b/src/components/shared/Submitters/Tangle/useSubmitPipeline.ts @@ -5,10 +5,14 @@ import { useAwaitAuthorization } from "@/components/shared/Authentication/useAwa import { useBackend } from "@/providers/BackendProvider"; import { ONBOARDING_MY_RUN_COUNT_KEY } from "@/providers/OnboardingProvider/onboardingQueryKeys"; import { useRunSubmissionAnnotations } from "@/providers/RunSubmissionScopeProvider"; +import { useRecordProjectContribution } from "@/services/projects/useProjectContributors"; import { invalidateProjectRunQueries } from "@/services/projects/useProjectRuns"; import type { PipelineRun } from "@/types/pipelineRun"; import type { ArgumentType, ComponentSpec } from "@/utils/componentSpec"; -import { projectRunAnnotations } from "@/utils/projectRunAnnotation"; +import { + projectIdsFromAnnotations, + projectRunAnnotations, +} from "@/utils/projectRunAnnotation"; import { submitPipelineRun } from "@/utils/submitPipeline"; import { isAuthorizationRequired } from "../../Authentication/helpers"; @@ -29,6 +33,7 @@ export function useSubmitPipeline() { const { getToken } = useAuthLocalStorage(); const { backendUrl } = useBackend(); + const recordContribution = useRecordProjectContribution(); const scopeAnnotations = useRunSubmissionAnnotations(); const authorizationToken = useRef(getToken()); @@ -55,13 +60,16 @@ export function useSubmitPipeline() { } } + const annotations = annotationsFor(projectIds); return new Promise((resolve, reject) => { submitPipelineRun(componentSpec, backendUrl, { authorizationToken: authorizationToken.current, teamId, taskArguments, - runAnnotations: annotationsFor(projectIds), + runAnnotations: annotations, onSuccess: (data) => { + for (const id of projectIdsFromAnnotations(annotations)) + recordContribution(id); resolve(data); onSuccess(data); }, diff --git a/src/routes/v2/pages/Tangent/components/AddResourceButton.tsx b/src/routes/v2/pages/Tangent/components/AddResourceButton.tsx index 5cf9d8f443..61a019b391 100644 --- a/src/routes/v2/pages/Tangent/components/AddResourceButton.tsx +++ b/src/routes/v2/pages/Tangent/components/AddResourceButton.tsx @@ -93,8 +93,10 @@ export function AddResourceButton({ }: AddResourceButtonProps) { const { open } = useDialog(); const notify = useToastNotification(); - const { mutate: createResource, isPending } = - useCreateProjectResource(projectId); + const { mutate: createResource, isPending } = useCreateProjectResource( + projectId, + { recordContribution: true }, + ); async function openResourceDialog(config: DialogConfig) { const result = await open({ diff --git a/src/routes/v2/pages/Tangent/components/ProjectChatArea.tsx b/src/routes/v2/pages/Tangent/components/ProjectChatArea.tsx index 80d9f12cf8..261d02f411 100644 --- a/src/routes/v2/pages/Tangent/components/ProjectChatArea.tsx +++ b/src/routes/v2/pages/Tangent/components/ProjectChatArea.tsx @@ -15,6 +15,8 @@ import { useRefreshSessionResources } from "@/routes/v2/pages/Tangent/hooks/useR import { AiProviderSetup } from "@/routes/v2/shared/components/AiChat/components/AiProviderSetup"; import { TANGENT_AI_SETUP } from "@/routes/v2/shared/components/AiChat/components/aiSetupCopy"; import { ChatEntityRevealProvider } from "@/routes/v2/shared/components/AiChat/components/ChatEntityRevealContext"; +import { useProjectAuthor } from "@/services/projects/useProjectAuthor"; +import { useRecordProjectContribution } from "@/services/projects/useProjectContributors"; import { getErrorMessage } from "@/utils/string"; export const ProjectChatArea = observer(function ProjectChatArea() { @@ -22,6 +24,8 @@ export const ProjectChatArea = observer(function ProjectChatArea() { const notify = useToastNotification(); const { isConfigured } = useAiProviderSettings(); const references = useChatReferences(store.projectId); + const { createdBy } = useProjectAuthor(); + const recordContribution = useRecordProjectContribution(); const commands = useChatCommands(store.projectId); const refreshSessionResources = useRefreshSessionResources(); const activeSessionId = store.activeSessionId; @@ -73,6 +77,9 @@ export const ProjectChatArea = observer(function ProjectChatArea() { } }} onSendPrompt={(content) => store.recordSessionPrompt(content)} + onPromptAuthor={(authorId) => { + if (authorId === createdBy) recordContribution(store.projectId); + }} onError={(message) => notify(message, "error")} onResourcesChange={() => refreshSessionResources(activeSessionId)} headerAction={} diff --git a/src/routes/v2/pages/Tangent/components/ProjectSettingsDialog.test.tsx b/src/routes/v2/pages/Tangent/components/ProjectSettingsDialog.test.tsx index ad1ab9bec8..71f6f60538 100644 --- a/src/routes/v2/pages/Tangent/components/ProjectSettingsDialog.test.tsx +++ b/src/routes/v2/pages/Tangent/components/ProjectSettingsDialog.test.tsx @@ -6,6 +6,10 @@ import { useProject } from "@/services/projects/useProjects"; import { ProjectSettingsDialog } from "./ProjectSettingsDialog"; +vi.mock("@/services/projects/useProjectContributors", () => ({ + useProjectContributors: () => ({ data: ["teammate@example.com"] }), +})); + vi.mock("@/routes/v2/pages/Tangent/context/TangentProjectContext", () => ({ useTangentProject: () => ({ projectId: "project-1", @@ -153,6 +157,9 @@ describe("ProjectSettingsDialog", () => { projectLoaded(); renderSettings(); + expect( + screen.getByRole("list", { name: "Contributors" }), + ).toHaveTextContent("teammate@example.com"); expect( screen.getByText(/Created by alice@example\.com/), ).toBeInTheDocument(); diff --git a/src/routes/v2/pages/Tangent/components/ProjectSettingsDialog.tsx b/src/routes/v2/pages/Tangent/components/ProjectSettingsDialog.tsx index 69c1a53038..8a23e84301 100644 --- a/src/routes/v2/pages/Tangent/components/ProjectSettingsDialog.tsx +++ b/src/routes/v2/pages/Tangent/components/ProjectSettingsDialog.tsx @@ -7,6 +7,7 @@ import { ProjectDescriptionField, ProjectInstructionsField, } from "@/components/Project/ProjectAbout"; +import { ProjectContributors } from "@/components/Project/ProjectContributors"; import { ProjectWorkspaceLabel } from "@/components/Project/ProjectWorkspaceLabel"; import { Button } from "@/components/ui/button"; import { @@ -169,7 +170,12 @@ export const ProjectSettingsDialog = observer(function ProjectSettingsDialog({ )} - {project && } + {project && ( + <> + + + + )} diff --git a/src/routes/v2/pages/Tangent/components/TangentChatPane.author.test.tsx b/src/routes/v2/pages/Tangent/components/TangentChatPane.author.test.tsx new file mode 100644 index 0000000000..fc9fb06359 --- /dev/null +++ b/src/routes/v2/pages/Tangent/components/TangentChatPane.author.test.tsx @@ -0,0 +1,48 @@ +import { fireEvent, render, screen } from "@testing-library/react"; +import { createElement } from "react"; +import { expect, it, vi } from "vitest"; + +import { CHAT_TAB_VALUE } from "@/routes/v2/pages/Tangent/store/TangentProjectStore"; + +import { TangentChatPane } from "./TangentChatPane"; + +vi.mock("@tangent/embed-react", () => ({ + Chat: () => createElement("tangent-chat", { "data-testid": "chat-prime" }), +})); + +it("reads the local prompt sender and ignores unsigned prompts and broadcasts", () => { + const onAuthor = vi.fn(); + render( + , + ); + const chat = screen.getByTestId("chat-prime"); + fireEvent( + chat, + new CustomEvent("resources-change", { + bubbles: true, + detail: { authorId: "observer" }, + }), + ); + fireEvent( + chat, + new CustomEvent("send-prompt", { + bubbles: true, + detail: { content: "old shell" }, + }), + ); + fireEvent( + chat, + new CustomEvent("send-prompt", { + bubbles: true, + detail: { content: "hello", authorId: "writer" }, + }), + ); + expect(onAuthor).toHaveBeenCalledExactlyOnceWith("writer"); +}); diff --git a/src/routes/v2/pages/Tangent/components/TangentChatPane.tsx b/src/routes/v2/pages/Tangent/components/TangentChatPane.tsx index 151fc3321d..c7170ff1d0 100644 --- a/src/routes/v2/pages/Tangent/components/TangentChatPane.tsx +++ b/src/routes/v2/pages/Tangent/components/TangentChatPane.tsx @@ -29,6 +29,7 @@ interface TangentChatPaneProps { commands?: EmbedCommand[]; onOpenArtifact?: (url: string, title: string) => void; onSendPrompt?: (content: string) => void; + onPromptAuthor?: (authorId: string) => void; onError?: (message: string) => void; onResourcesChange?: () => void; headerAction?: ReactNode; @@ -51,12 +52,32 @@ export function TangentChatPane({ commands, onOpenArtifact, onSendPrompt, + onPromptAuthor, onError, onResourcesChange, headerAction, }: TangentChatPaneProps) { return ( -
+
{ + if (!element || !onPromptAuthor) return; + // The pinned React wrapper forwards only the text of a submitted prompt. + const onSend = (event: Event) => { + if ( + !(event.target instanceof HTMLElement) || + event.target.localName !== "tangent-chat" + ) + return; + const authorId = (event as CustomEvent<{ authorId?: string }>).detail + ?.authorId; + if (typeof authorId === "string" && authorId) + onPromptAuthor(authorId); + }; + element.addEventListener("send-prompt", onSend); + return () => element.removeEventListener("send-prompt", onSend); + }} + > ({ recordSessionRun: vi.fn(), })); +const recordContribution = vi.hoisted(() => vi.fn()); +vi.mock("@/services/projects/useProjectContributors", () => ({ + useRecordProjectContribution: () => recordContribution, +})); + vi.mock("@/routes/v2/pages/Tangent/context/TangentProjectContext", () => ({ useTangentProject: () => fakes.store, })); @@ -131,6 +136,7 @@ describe("useChatCommands", () => { "r-9", "Train", ); + expect(recordContribution).toHaveBeenCalledExactlyOnceWith("project-1"); expect(text).toContain("- [Train](run://id/r-9)"); expect(text).toContain("- `nope`: not one of this project's pipelines"); }); @@ -145,6 +151,7 @@ describe("useChatCommands", () => { expect(text).toContain("`p-1` (Train): A required input has no value."); expect(fakes.recordSessionRun).not.toHaveBeenCalled(); + expect(recordContribution).not.toHaveBeenCalled(); }); it("keeps a run with the chat that asked for it when another is opened meanwhile", async () => { diff --git a/src/routes/v2/pages/Tangent/hooks/useChatCommands.ts b/src/routes/v2/pages/Tangent/hooks/useChatCommands.ts index 9cf07dd736..45cdbecaaf 100644 --- a/src/routes/v2/pages/Tangent/hooks/useChatCommands.ts +++ b/src/routes/v2/pages/Tangent/hooks/useChatCommands.ts @@ -40,6 +40,7 @@ import { parseWorkareaTarget, runTarget, } from "@/services/projects/resourceTarget"; +import { useRecordProjectContribution } from "@/services/projects/useProjectContributors"; import { runExecutionStatsQuery } from "@/services/projects/useProjectRuns"; import { useTeamForSubmission } from "@/services/teams/useTeamForSubmission"; import { buildProjectRunAnnotationKey } from "@/utils/annotations"; @@ -61,6 +62,7 @@ export function useChatCommands(projectId: string): EmbedCommand[] { const storage = usePipelineStorage(); const { getBackendUrl, getAuthToken, queryClient } = useLazyBridgeAuth(); const { baseUrl } = useTangentBaseUrl(projectId); + const recordContribution = useRecordProjectContribution(); const recordSessionRun = useRecordSessionRun(); const runTeam = useTeamForSubmission([projectId]); const runTeamRef = useRef(runTeam); @@ -157,6 +159,7 @@ export function useChatCommands(projectId: string): EmbedCommand[] { if (!result.success || !result.runId) { return { id, name: pipeline.name, error: result.error }; } + recordContribution(projectId); if (sessionId) { // Best effort: the run has started whether or not the chat noted it. await recordSessionRun(sessionId, result.runId, pipeline.name).catch( diff --git a/src/services/projects/projectsService.test.ts b/src/services/projects/projectsService.test.ts index 412226c6e8..c4e8f6d0cd 100644 --- a/src/services/projects/projectsService.test.ts +++ b/src/services/projects/projectsService.test.ts @@ -9,6 +9,7 @@ import type { vi.mock("@/api/sdk.gen"); +import { client } from "@/api/client.gen"; import * as apiSdk from "@/api/sdk.gen"; import { ProjectsApiError, WorkspacesApiError } from "./errors"; @@ -154,6 +155,68 @@ describe("projectsService", () => { }); }); + it("asks for the signed-in user's projects without sending their ID", async () => { + const get = vi.spyOn(client, "get").mockResolvedValueOnce( + createMockApiResponse({ + projects: [projectSummaryDto], + total_count: 8, + next_page_token: "page", + }), + ); + const page = await listProjects( + { + myProjectsFor: "someone", + createdBy: "another", + workspaceId: "w", + pageToken: "next", + }, + "https://backend.example", + ); + expect(get).toHaveBeenCalledWith({ + url: "/api/users/me/projects", + baseUrl: "https://backend.example", + query: { + workspace_id: "w", + created_by: "another", + page_token: "next", + page_size: undefined, + }, + }); + expect(page).toMatchObject({ + items: [{ id: "p1" }], + nextPageToken: "page", + totalCount: 8, + }); + get.mockRestore(); + }); + + it("preserves the creator list on older servers without silently broadening a filtered or refused request", async () => { + const get = vi + .spyOn(client, "get") + .mockResolvedValue(createMockApiErrorResponse(404)); + vi.mocked(apiSdk.listProjectsApiProjectsGet).mockResolvedValue( + createMockApiResponse({ projects: [], total_count: 0 }), + ); + await listProjects({ myProjectsFor: "someone", workspaceId: "w" }); + expect(apiSdk.listProjectsApiProjectsGet).toHaveBeenCalledWith({ + query: expect.objectContaining({ + workspace_id: "w", + created_by: "someone", + }), + }); + const empty = await listProjects({ + myProjectsFor: "someone", + createdBy: "another", + }); + expect(empty.totalCount).toBe(0); + get.mockResolvedValueOnce(createMockApiErrorResponse(403)); + await expect( + listProjects({ myProjectsFor: "someone" }), + ).rejects.toMatchObject({ status: 403 }); + expect(apiSdk.listProjectsApiProjectsGet).toHaveBeenCalledTimes(1); + get.mockRestore(); + }); + it("defaults nextPageToken to null when absent", async () => { vi.mocked(apiSdk.listProjectsApiProjectsGet).mockResolvedValue( createMockApiResponse({ diff --git a/src/services/projects/projectsService.ts b/src/services/projects/projectsService.ts index da6b86bf68..6713b2a87a 100644 --- a/src/services/projects/projectsService.ts +++ b/src/services/projects/projectsService.ts @@ -1,3 +1,4 @@ +import { client } from "@/api/client.gen"; import { createProjectApiProjectsPost, deleteProjectApiProjectsProjectIdDelete, @@ -5,6 +6,7 @@ import { listProjectsApiProjectsGet, updateProjectApiProjectsProjectIdPatch, } from "@/api/sdk.gen"; +import type { ListProjectsApiProjectsGetResponses } from "@/api/types.gen"; import { describeErrorBody } from "@/services/requestFailureMessage"; import { ProjectsApiError } from "./errors"; @@ -22,7 +24,7 @@ export async function listProjects( params: ListProjectsParams = {}, backendUrl?: string, ): Promise { - const result = await listProjectsApiProjectsGet({ + const options = { ...(backendUrl && { baseUrl: backendUrl }), query: { workspace_id: params.workspaceId, @@ -30,7 +32,23 @@ export async function listProjects( page_token: params.pageToken, page_size: params.pageSize, }, - }); + }; + let result = params.myProjectsFor + ? await client.get({ + ...options, + url: "/api/users/me/projects", + }) + : await listProjectsApiProjectsGet(options); + if (params.myProjectsFor && [404, 405].includes(result.response.status)) { + // Older servers can only look up projects by their creator. + if (params.createdBy && params.createdBy !== params.myProjectsFor) { + return { items: [], nextPageToken: null, totalCount: 0 }; + } + result = await listProjectsApiProjectsGet({ + ...options, + query: { ...options.query, created_by: params.myProjectsFor }, + }); + } if (!result.data) { throw new ProjectsApiError( "Failed to list projects", diff --git a/src/services/projects/types.ts b/src/services/projects/types.ts index ca06f6c05b..8071da982d 100644 --- a/src/services/projects/types.ts +++ b/src/services/projects/types.ts @@ -39,6 +39,7 @@ export interface ProjectPage { export interface ListProjectsParams { workspaceId?: string; createdBy?: string; + myProjectsFor?: string; pageToken?: string; pageSize?: number; } diff --git a/src/services/projects/useProjectContributors.ts b/src/services/projects/useProjectContributors.ts new file mode 100644 index 0000000000..75ae9493c2 --- /dev/null +++ b/src/services/projects/useProjectContributors.ts @@ -0,0 +1,76 @@ +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; + +import { client } from "@/api/client.gen"; +import useToastNotification from "@/hooks/useToastNotification"; +import { useBackend } from "@/providers/BackendProvider"; + +import { ProjectsApiError } from "./errors"; +import { projectQueryDefaults } from "./queryDefaults"; + +const contributorKey = (projectId: string, backendUrl: string) => + ["projects", projectId, "contributors", backendUrl] as const; + +export function useProjectContributors(projectId: string) { + const { backendUrl, configured, available } = useBackend(); + return useQuery({ + queryKey: contributorKey(projectId, backendUrl), + queryFn: async () => { + const { data, response } = await client.get<{ + 200: { contributors: string[] }; + }>({ + baseUrl: backendUrl, + url: "/api/projects/{project_id}/contributors", + path: { project_id: projectId }, + }); + if ([404, 405].includes(response.status)) return null; + if (!data) { + throw new ProjectsApiError( + "Unable to load contributors", + response.status, + ); + } + return data.contributors; + }, + enabled: configured && available, + ...projectQueryDefaults, + }); +} + +/** Called only after a person's own action succeeds. The server identifies the contributor. */ +export function useRecordProjectContribution() { + const { backendUrl } = useBackend(); + const queries = useQueryClient(); + const notify = useToastNotification(); + const { mutate } = useMutation({ + mutationFn: async ({ + projectId, + backend, + }: { + projectId: string; + backend: string; + }) => { + const { response } = await client.put({ + baseUrl: backend, + url: "/api/projects/{project_id}/contributors/me", + path: { project_id: projectId }, + }); + if ([404, 405].includes(response.status)) return false; + if (!response.ok) { + throw new ProjectsApiError( + "Unable to record your project contribution", + response.status, + ); + } + return true; + }, + onSuccess: (recorded, { projectId, backend }) => { + if (!recorded) return; + void queries.invalidateQueries({ + queryKey: contributorKey(projectId, backend), + }); + void queries.invalidateQueries({ queryKey: ["projects", "list"] }); + }, + onError: () => notify("Unable to add this project to My projects", "error"), + }); + return (projectId: string) => mutate({ projectId, backend: backendUrl }); +} diff --git a/src/services/projects/useProjectInstructions.ts b/src/services/projects/useProjectInstructions.ts index 2278f6890d..f3deeea224 100644 --- a/src/services/projects/useProjectInstructions.ts +++ b/src/services/projects/useProjectInstructions.ts @@ -52,9 +52,9 @@ export function useProjectInstructions(projectId: string): ProjectInstructions { ); const { mutate: createResource, isPending: isCreating } = - useCreateProjectResource(projectId); + useCreateProjectResource(projectId, { recordContribution: true }); const { mutate: updateResource, isPending: isUpdating } = - useUpdateProjectResource(projectId); + useUpdateProjectResource(projectId, { recordContribution: true }); return { instructions: (resource && documentBody(resource)) ?? "", diff --git a/src/services/projects/useProjectResources.test.tsx b/src/services/projects/useProjectResources.test.tsx index e935bd2d19..a58d594560 100644 --- a/src/services/projects/useProjectResources.test.tsx +++ b/src/services/projects/useProjectResources.test.tsx @@ -4,6 +4,10 @@ import type { ReactNode } from "react"; import { beforeEach, describe, expect, it, vi } from "vitest"; vi.mock("./projectResourcesService"); +const record = vi.hoisted(() => vi.fn()); +vi.mock("./useProjectContributors", () => ({ + useRecordProjectContribution: () => record, +})); let backend = { configured: true, available: true }; vi.mock("@/providers/BackendProvider", () => ({ @@ -158,6 +162,7 @@ describe("project resource mutation hooks", () => { await result.current.mutateAsync({ entity: "pipeline" }); }); + expect(record).not.toHaveBeenCalled(); expect(invalidate).toHaveBeenCalledWith({ queryKey: ["projects", "p1", "resources"], }); @@ -167,6 +172,27 @@ describe("project resource mutation hooks", () => { }); }); + it("records a deliberate resource attachment only after it succeeds", async () => { + const create = vi.mocked(projectResourcesService.createProjectResource); + create + .mockRejectedValueOnce(new Error("failed")) + .mockResolvedValueOnce(resource); + const { result } = renderHook( + () => useCreateProjectResource("p1", { recordContribution: true }), + { wrapper: wrapperFor(makeClient()) }, + ); + await act(async () => { + await expect( + result.current.mutateAsync({ entity: "document" }), + ).rejects.toThrow("failed"); + }); + expect(record).not.toHaveBeenCalled(); + await act(async () => { + await result.current.mutateAsync({ entity: "document" }); + }); + expect(record).toHaveBeenCalledExactlyOnceWith("p1"); + }); + it("useUpdateProjectResource refreshes the resources and the project", async () => { vi.mocked(projectResourcesService.updateProjectResource).mockResolvedValue( resource, diff --git a/src/services/projects/useProjectResources.ts b/src/services/projects/useProjectResources.ts index 901f57993e..68af81c95b 100644 --- a/src/services/projects/useProjectResources.ts +++ b/src/services/projects/useProjectResources.ts @@ -26,6 +26,7 @@ import type { UpdateResourceInput, } from "./types"; import { ProjectResourcesQueryKeys, ProjectsQueryKeys } from "./types"; +import { useRecordProjectContribution } from "./useProjectContributors"; /** * `ProjectsQueryKeys.Id` is a prefix of the project's resources *and* its runs, @@ -129,13 +130,20 @@ export function useProjectResource( }); } -export function useCreateProjectResource(projectId: string) { +export function useCreateProjectResource( + projectId: string, + { recordContribution = false } = {}, +) { + const record = useRecordProjectContribution(); const queryClient = useQueryClient(); const notify = useToastNotification(); return useMutation({ - mutationFn: (input: CreateResourceInput) => - createProjectResource(projectId, input), + mutationFn: async (input: CreateResourceInput) => { + const resource = await createProjectResource(projectId, input); + if (recordContribution) record(projectId); + return resource; + }, onSuccess: () => { invalidateProjectResources(queryClient, projectId); }, @@ -147,17 +155,22 @@ export function useCreateProjectResource(projectId: string) { /** For a caller that only learns the project as it adds — a "which project?" dialog. */ export function useAddResourceToProject() { + const record = useRecordProjectContribution(); const queryClient = useQueryClient(); const notify = useToastNotification(); return useMutation({ - mutationFn: ({ + mutationFn: async ({ projectId, input, }: { projectId: string; input: CreateResourceInput; - }) => createProjectResource(projectId, input), + }) => { + const resource = await createProjectResource(projectId, input); + record(projectId); + return resource; + }, onSuccess: (_resource, { projectId }) => { invalidateProjectResources(queryClient, projectId); }, @@ -167,18 +180,30 @@ export function useAddResourceToProject() { }); } -export function useUpdateProjectResource(projectId: string) { +export function useUpdateProjectResource( + projectId: string, + { recordContribution = false } = {}, +) { + const record = useRecordProjectContribution(); const queryClient = useQueryClient(); const notify = useToastNotification(); return useMutation({ - mutationFn: ({ + mutationFn: async ({ resourceId, input, }: { resourceId: string; input: UpdateResourceInput; - }) => updateProjectResource(projectId, resourceId, input), + }) => { + const resource = await updateProjectResource( + projectId, + resourceId, + input, + ); + if (recordContribution) record(projectId); + return resource; + }, onSuccess: (resource) => { queryClient.setQueryData( ProjectResourcesQueryKeys.Id(projectId, resource.id), diff --git a/src/services/projects/useProjects.test.tsx b/src/services/projects/useProjects.test.tsx index 4aad5b6af0..3aaeb8c9d3 100644 --- a/src/services/projects/useProjects.test.tsx +++ b/src/services/projects/useProjects.test.tsx @@ -4,6 +4,9 @@ import type { ReactNode } from "react"; import { beforeEach, describe, expect, it, vi } from "vitest"; vi.mock("./projectsService"); +vi.mock("./useProjectContributors", () => ({ + useRecordProjectContribution: () => vi.fn(), +})); vi.mock("./workspacesService"); const removeFavorite = vi.fn().mockResolvedValue(undefined); diff --git a/src/services/projects/useProjects.ts b/src/services/projects/useProjects.ts index 08abc1027f..da4bd5618b 100644 --- a/src/services/projects/useProjects.ts +++ b/src/services/projects/useProjects.ts @@ -27,6 +27,7 @@ import type { } from "./types"; import { ProjectsQueryKeys, WorkspacesQueryKeys } from "./types"; import { updateProjectMetadata } from "./updateProjectMetadata"; +import { useRecordProjectContribution } from "./useProjectContributors"; export function useProjects( params: ListProjectsParams = {}, @@ -126,12 +127,22 @@ export function useCreateProject() { } export function useUpdateProject() { + const record = useRecordProjectContribution(); const queryClient = useQueryClient(); const notify = useToastNotification(); return useMutation({ - mutationFn: ({ id, input }: { id: string; input: UpdateProjectInput }) => - updateProject(id, input), + mutationFn: async ({ + id, + input, + }: { + id: string; + input: UpdateProjectInput; + }) => { + const project = await updateProject(id, input); + record(id); + return project; + }, onSuccess: (_project, { id }) => { void queryClient.invalidateQueries({ queryKey: ProjectsQueryKeys.All(), diff --git a/src/services/projects/useReachableProjects.test.tsx b/src/services/projects/useReachableProjects.test.tsx index 8e41820791..2f11374176 100644 --- a/src/services/projects/useReachableProjects.test.tsx +++ b/src/services/projects/useReachableProjects.test.tsx @@ -49,7 +49,7 @@ describe("useReachableProjects", () => { renderHook(() => useReachableProjects()); expect(useProjects).toHaveBeenCalledWith( - expect.objectContaining({ createdBy: "ada@example.com" }), + expect.objectContaining({ myProjectsFor: "ada@example.com" }), expect.anything(), ); }); diff --git a/src/services/projects/useReachableProjects.ts b/src/services/projects/useReachableProjects.ts index 1f34b3de54..ccd0c98264 100644 --- a/src/services/projects/useReachableProjects.ts +++ b/src/services/projects/useReachableProjects.ts @@ -10,16 +10,7 @@ interface ReachableProjects { error: Error | null; } -/** - * The projects a caller can actually get back to: the ones they created, plus - * the ones they pinned. Pinning is the only record of a project someone shared, - * so without it a shared project is gone with the link — which makes these two - * together the whole of what a picker can honestly offer. - * - * Asking for every project instead spends the one page the API will return on - * a deployment's worth of other people's work, which is how a picker came to - * miss projects of the caller's own. - */ +/** Pinned projects, followed by projects the caller has worked on. */ export function useReachableProjects({ enabled = true, }: { enabled?: boolean } = {}): ReachableProjects { @@ -34,7 +25,7 @@ export function useReachableProjects({ isPending: isListPending, error: listError, } = useProjects( - { createdBy, pageSize: MAX_PAGE_SIZE }, + { myProjectsFor: createdBy, pageSize: MAX_PAGE_SIZE }, { enabled: enabled && !isAuthorPending && authorError === null }, );