From e56d291c1196e0979c137b0dae7489b1f6afe555 Mon Sep 17 00:00:00 2001 From: Akshar Patel Date: Tue, 3 Nov 2026 05:32:38 +0000 Subject: [PATCH 1/2] fix(web): keep completed video changes on retry --- .github/workflows/ci.yml | 1 + .../unit/add-videos-dialog-retry.test.ts | 175 ++++++++++++++++++ .../components/AddVideosDialogBase.tsx | 10 +- apps/web/vitest.config.ts | 16 +- 4 files changed, 199 insertions(+), 3 deletions(-) create mode 100644 apps/web/__tests__/unit/add-videos-dialog-retry.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bee6043e00c..3641c3c9657 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -101,6 +101,7 @@ jobs: - name: Test web React compatibility run: >- bun run --cwd apps/web test + __tests__/unit/add-videos-dialog-retry.test.ts __tests__/unit/analytics-track-route.test.ts __tests__/unit/caps-analytics-round-trips.test.ts __tests__/unit/caps-keyboard.test.ts diff --git a/apps/web/__tests__/unit/add-videos-dialog-retry.test.ts b/apps/web/__tests__/unit/add-videos-dialog-retry.test.ts new file mode 100644 index 00000000000..77454c81cfc --- /dev/null +++ b/apps/web/__tests__/unit/add-videos-dialog-retry.test.ts @@ -0,0 +1,175 @@ +// @vitest-environment jsdom + +import { Video } from "@cap/web-domain"; +import { TooltipProvider } from "@radix-ui/react-tooltip"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { act, createElement } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import AddVideosDialogBase, { + type VideoData, +} from "@/app/(org)/dashboard/spaces/[spaceId]/components/AddVideosDialogBase"; + +vi.mock("@cap/utils", async () => await import("@cap/utils/helpers")); +vi.mock("@cap/ui", async () => ({ + ...(await import("../../../../packages/ui/src/components/Button")), + ...(await import("../../../../packages/ui/src/components/Dialog")), + ...(await import("../../../../packages/ui/src/components/LoadingSpinner")), + ...(await import("../../../../packages/ui/src/components/LogoSpinner")), + ...(await import("../../../../packages/ui/src/components/input/Input")), +})); +vi.mock( + "@/app/(org)/dashboard/Contexts", + async () => import("@/app/(org)/dashboard/DashboardContext"), +); +vi.mock("@rive-app/react-canvas", () => ({ + useRive: () => ({ RiveComponent: () => null }), + Layout: class {}, + Fit: { Contain: "contain" }, +})); + +const newId = Video.VideoId.make("new-video"); +const existingId = Video.VideoId.make("existing-video"); +const videoData: VideoData[] = [newId, existingId].map((id) => ({ + id, + name: id, + ownerId: "owner", + ownerName: "Owner", + createdAt: new Date("2026-01-01"), + totalComments: 0, + totalReactions: 0, +})); + +let root: Root; +let container: HTMLDivElement; +let queryClient: QueryClient; + +beforeEach(() => { + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + vi.stubGlobal( + "fetch", + vi.fn(async () => new Response(null, { status: 503 })), + ); + vi.stubGlobal("matchMedia", (media: string) => ({ matches: false, media })); + vi.stubGlobal( + "IntersectionObserver", + class { + observe() {} + unobserve() {} + disconnect() {} + }, + ); + vi.stubGlobal( + "ResizeObserver", + class { + constructor(private callback: ResizeObserverCallback) {} + observe(target: Element) { + this.callback( + [ + { + target, + contentRect: new DOMRect(0, 0, 640, 300), + borderBoxSize: [{ inlineSize: 640, blockSize: 300 }], + contentBoxSize: [{ inlineSize: 640, blockSize: 300 }], + devicePixelContentBoxSize: [], + }, + ], + this, + ); + } + unobserve() {} + disconnect() {} + }, + ); + vi.spyOn(HTMLElement.prototype, "offsetWidth", "get").mockReturnValue(640); + vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockReturnValue(300); + container = document.createElement("div"); + document.body.append(container); + root = createRoot(container); + queryClient = new QueryClient({ + defaultOptions: { queries: { retry: false }, mutations: { retry: false } }, + }); +}); + +afterEach(async () => { + await act(async () => root.unmount()); + container.remove(); + queryClient.clear(); + vi.unstubAllGlobals(); +}); + +function button(label: string) { + const element = [...document.querySelectorAll("button")].find((element) => + element.textContent?.includes(label), + ); + if (!element) throw new Error(`Button not found: ${label}`); + return element; +} + +async function flushUpdates() { + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 30)); + }); +} + +it.each(["addition", "removal"])( + "retries a failed %s without reversing the successful operation", + async (failure) => { + const membership = new Set([existingId]); + const addVideos = vi.fn(async (_entityId: string, ids: Video.VideoId[]) => { + for (const id of ids) membership.add(id); + return { success: true }; + }); + const removeVideos = vi.fn( + async (_entityId: string, ids: Video.VideoId[]) => { + for (const id of ids) membership.delete(id); + return { success: true }; + }, + ); + if (failure === "addition") + addVideos.mockResolvedValueOnce({ success: false }); + else removeVideos.mockResolvedValueOnce({ success: false }); + const onClose = vi.fn(); + await act(async () => { + root.render( + createElement( + TooltipProvider, + null, + createElement( + QueryClientProvider, + { client: queryClient }, + createElement(AddVideosDialogBase, { + open: true, + onClose, + entityId: "folder", + entityName: "Demo folder", + addVideos, + removeVideos, + getVideos: async () => ({ success: true, data: videoData }), + getEntityVideoIds: async () => ({ + success: true, + data: [...membership], + }), + }), + ), + ), + ); + }); + await flushUpdates(); + await act(async () => button(newId).click()); + await act(async () => button(existingId).click()); + await act(async () => button("Update videos").click()); + await flushUpdates(); + expect([...membership]).toEqual( + failure === "addition" ? [] : [existingId, newId], + ); + expect(onClose).not.toHaveBeenCalled(); + await act(async () => button("Update videos").click()); + await flushUpdates(); + expect([...membership]).toEqual([newId]); + expect(addVideos).toHaveBeenCalledTimes(failure === "addition" ? 2 : 1); + expect(removeVideos).toHaveBeenCalledTimes(failure === "removal" ? 2 : 1); + expect(removeVideos).toHaveBeenLastCalledWith("folder", [existingId]); + expect(onClose).toHaveBeenCalledOnce(); + }, +); diff --git a/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/AddVideosDialogBase.tsx b/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/AddVideosDialogBase.tsx index 5a17c298af5..a9a7edb9235 100644 --- a/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/AddVideosDialogBase.tsx +++ b/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/AddVideosDialogBase.tsx @@ -150,9 +150,17 @@ function AddVideosDialogBase({ } return { addResult, removeResult }; }, - onSuccess: async (result) => { + onSuccess: async (result, { toAdd, toRemove }) => { const { addResult, removeResult } = result || {}; + setSelectedVideos((selected) => + selected.filter( + (id) => + !(addResult.success && toAdd.includes(id)) && + !(removeResult.success && toRemove.includes(id)), + ), + ); + // Invalidate both queries to ensure UI updates await Promise.all([ queryClient.invalidateQueries({ queryKey: ["user-videos"] }), diff --git a/apps/web/vitest.config.ts b/apps/web/vitest.config.ts index edc0ccd697c..bb5ded974f7 100644 --- a/apps/web/vitest.config.ts +++ b/apps/web/vitest.config.ts @@ -23,11 +23,23 @@ export default defineConfig({ optimizer: { ssr: { enabled: true, - include: ["next/link", "next/image", "react-remove-scroll"], + include: [ + "next/link", + "next/image", + "react-remove-scroll", + "react-hook-form", + "@virtual-grid/react", + ], }, web: { enabled: true, - include: ["next/link", "next/image", "react-remove-scroll"], + include: [ + "next/link", + "next/image", + "react-remove-scroll", + "react-hook-form", + "@virtual-grid/react", + ], esbuildOptions: { banner: { js: `import { createRequire } from "node:module"; const require = createRequire(import.meta.url);`, From a8714f2e0d0b6890b34913ac9fbbab2ec880be9d Mon Sep 17 00:00:00 2001 From: Akshar Patel Date: Tue, 3 Nov 2026 06:02:19 +0000 Subject: [PATCH 2/2] fix(web): isolate video updates between dialog sessions --- .../unit/add-videos-dialog-retry.test.ts | 119 ++++++++++++++---- .../components/AddVideosDialogBase.tsx | 40 +++--- 2 files changed, 121 insertions(+), 38 deletions(-) diff --git a/apps/web/__tests__/unit/add-videos-dialog-retry.test.ts b/apps/web/__tests__/unit/add-videos-dialog-retry.test.ts index 77454c81cfc..e64c4d5b835 100644 --- a/apps/web/__tests__/unit/add-videos-dialog-retry.test.ts +++ b/apps/web/__tests__/unit/add-videos-dialog-retry.test.ts @@ -112,6 +112,24 @@ async function flushUpdates() { }); } +async function renderDialog( + props: Parameters>[0], +) { + await act(async () => { + root.render( + createElement( + TooltipProvider, + null, + createElement( + QueryClientProvider, + { client: queryClient }, + createElement(AddVideosDialogBase, props), + ), + ), + ); + }); +} + it.each(["addition", "removal"])( "retries a failed %s without reversing the successful operation", async (failure) => { @@ -130,30 +148,18 @@ it.each(["addition", "removal"])( addVideos.mockResolvedValueOnce({ success: false }); else removeVideos.mockResolvedValueOnce({ success: false }); const onClose = vi.fn(); - await act(async () => { - root.render( - createElement( - TooltipProvider, - null, - createElement( - QueryClientProvider, - { client: queryClient }, - createElement(AddVideosDialogBase, { - open: true, - onClose, - entityId: "folder", - entityName: "Demo folder", - addVideos, - removeVideos, - getVideos: async () => ({ success: true, data: videoData }), - getEntityVideoIds: async () => ({ - success: true, - data: [...membership], - }), - }), - ), - ), - ); + await renderDialog({ + open: true, + onClose, + entityId: "folder", + entityName: "Demo folder", + addVideos, + removeVideos, + getVideos: async () => ({ success: true, data: videoData }), + getEntityVideoIds: async () => ({ + success: true, + data: [...membership], + }), }); await flushUpdates(); await act(async () => button(newId).click()); @@ -173,3 +179,68 @@ it.each(["addition", "removal"])( expect(onClose).toHaveBeenCalledOnce(); }, ); + +it.each([false, true])( + "keeps reopened selections when the previous removal completes with success=%s", + async (success) => { + const membership = new Set([existingId]); + const pending = Promise.withResolvers<{ success: boolean }>(); + const addVideos = vi.fn(async (_entityId: string, ids: Video.VideoId[]) => { + for (const id of ids) membership.add(id); + return { success: true }; + }); + const removeVideos = vi + .fn(async (_entityId: string, ids: Video.VideoId[]) => { + for (const id of ids) membership.delete(id); + return { success: true }; + }) + .mockImplementationOnce(async (_entityId, ids) => { + const result = await pending.promise; + if (result.success) { + for (const id of ids) membership.delete(id); + } + return result; + }); + const onClose = vi.fn(); + const onVideosAdded = vi.fn(); + const props = { + open: true, + onClose, + onVideosAdded, + entityId: "folder", + entityName: "Demo folder", + addVideos, + removeVideos, + getVideos: async () => ({ success: true, data: videoData }), + getEntityVideoIds: async () => ({ + success: true, + data: [...membership], + }), + }; + await renderDialog(props); + await flushUpdates(); + await act(async () => button(newId).click()); + await act(async () => button(existingId).click()); + await act(async () => button("Update videos").click()); + await flushUpdates(); + expect(removeVideos).toHaveBeenCalledOnce(); + await act(async () => button("Cancel").click()); + await renderDialog({ ...props, open: false }); + await renderDialog(props); + await flushUpdates(); + await act(async () => button(newId).click()); + expect(document.body.textContent).toContain("1 video selected"); + await act(async () => pending.resolve({ success })); + await flushUpdates(); + expect(document.body.textContent).toContain("1 video selected"); + expect(onClose).toHaveBeenCalledOnce(); + expect(onVideosAdded).toHaveBeenCalledTimes(success ? 1 : 0); + await act(async () => button("Update videos").click()); + await flushUpdates(); + expect([...membership]).toEqual(success ? [] : [existingId]); + expect(addVideos).toHaveBeenCalledOnce(); + expect(removeVideos).toHaveBeenLastCalledWith("folder", [newId]); + expect(onClose).toHaveBeenCalledTimes(2); + expect(onVideosAdded).toHaveBeenCalledTimes(success ? 2 : 1); + }, +); diff --git a/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/AddVideosDialogBase.tsx b/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/AddVideosDialogBase.tsx index a9a7edb9235..ad9c60fdb8e 100644 --- a/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/AddVideosDialogBase.tsx +++ b/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/AddVideosDialogBase.tsx @@ -16,7 +16,7 @@ import { zodResolver } from "@hookform/resolvers/zod"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import clsx from "clsx"; import { Search } from "lucide-react"; -import { useCallback, useEffect, useMemo, useState } from "react"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useForm } from "react-hook-form"; import { toast } from "sonner"; import * as z from "zod"; @@ -90,6 +90,7 @@ function AddVideosDialogBase({ getEntityVideoIds, }: AddVideosDialogBaseProp) { const [selectedVideos, setSelectedVideos] = useState([]); + const dialogSession = useRef(0); const [searchTerm, setSearchTerm] = useState(""); const filterTabs = ["all", "added", "notAdded"]; @@ -139,6 +140,7 @@ function AddVideosDialogBase({ }: { toAdd: Video.VideoId[]; toRemove: Video.VideoId[]; + session: number; }) => { let addResult: UpdateVideosResult = { success: true }; let removeResult: UpdateVideosResult = { success: true }; @@ -150,16 +152,9 @@ function AddVideosDialogBase({ } return { addResult, removeResult }; }, - onSuccess: async (result, { toAdd, toRemove }) => { - const { addResult, removeResult } = result || {}; - - setSelectedVideos((selected) => - selected.filter( - (id) => - !(addResult.success && toAdd.includes(id)) && - !(removeResult.success && toRemove.includes(id)), - ), - ); + onSuccess: async (result, { toAdd, toRemove, session }) => { + const { addResult, removeResult } = result; + const completed = addResult.success && removeResult.success; // Invalidate both queries to ensure UI updates await Promise.all([ @@ -169,10 +164,20 @@ function AddVideosDialogBase({ }), ]); - if ((addResult?.success ?? true) && (removeResult?.success ?? true)) { + if (completed) onVideosAdded?.(); + if (session !== dialogSession.current) return; + + setSelectedVideos((selected) => + selected.filter( + (id) => + !(addResult.success && toAdd.includes(id)) && + !(removeResult.success && toRemove.includes(id)), + ), + ); + + if (completed) { toast.success("Videos updated successfully"); setSelectedVideos([]); - onVideosAdded?.(); onClose(); } else { toast.error( @@ -222,7 +227,11 @@ function AddVideosDialogBase({ const toAdd = selectedVideos.filter((id) => !entityVideoIds.includes(id)); // To remove: selected and already in entity const toRemove = selectedVideos.filter((id) => entityVideoIds.includes(id)); - updateVideosMutation.mutate({ toAdd, toRemove }); + updateVideosMutation.mutate({ + toAdd, + toRemove, + session: dialogSession.current, + }); }; // Reset state when dialog closes @@ -232,6 +241,9 @@ function AddVideosDialogBase({ setSearchTerm(""); form.reset(); } + return () => { + dialogSession.current += 1; + }; }, [open, form]); return (