Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix: preserve Loom import folder destinations
Richie McIlroyeb18cb940a55
diff --git a/apps/web/__tests__/unit/loom-import-destination.test.ts b/apps/web/__tests__/unit/loom-import-destination.test.tsnew file mode 100644index 000000000..41ddd625b--- /dev/null+++ b/apps/web/__tests__/unit/loom-import-destination.test.ts@@ -0,0 +1,68 @@+import { describe, expect, it } from "vitest";+import {+ loomImportDestinationFromPathname,+ loomImportDestinationFromSearchParams,+ loomImportDestinationHref,+ loomImportPageHref,+} from "@/lib/loom-import-destination";++describe("Loom import navigation", () => {+ it.each([+ ["/dashboard/caps", "/dashboard/import", "/dashboard/caps"],+ [+ "/dashboard/folder/nested-folder",+ "/dashboard/import?folderId=nested-folder",+ "/dashboard/folder/nested-folder",+ ],+ [+ "/dashboard/spaces/team-space/folder/nested-folder",+ "/dashboard/import?folderId=nested-folder&spaceId=team-space",+ "/dashboard/spaces/team-space/folder/nested-folder",+ ],+ [+ "/dashboard/spaces/team-space",+ "/dashboard/import?spaceId=team-space",+ "/dashboard/spaces/team-space",+ ],+ [+ "/dashboard/spaces/org-id/folder/nested-folder",+ "/dashboard/import?folderId=nested-folder&spaceId=org-id",+ "/dashboard/spaces/org-id/folder/nested-folder",+ ],+ ["/dashboard/spaces/browse", "/dashboard/import", "/dashboard/caps"],+ ])(+ "preserves the destination from %s through the import hub and back",+ (pathname, importHref, returnHref) => {+ const destination = loomImportDestinationFromPathname(pathname);+ expect(loomImportPageHref(destination)).toBe(importHref);+ const hubParams = Object.fromEntries(+ new URL(importHref, "https://cap.test").searchParams,+ );+ const hubDestination = loomImportDestinationFromSearchParams(hubParams);+ const loomHref = loomImportPageHref(hubDestination, "loom");+ expect(loomHref).toBe(importHref.replace("/import", "/import/loom"));+ const loomDestination = loomImportDestinationFromSearchParams(+ Object.fromEntries(new URL(loomHref, "https://cap.test").searchParams),+ );+ expect(loomImportDestinationHref(loomDestination)).toBe(returnHref);+ },+ );++ it("keeps encoded identifiers inside their path segment", () => {+ const destination = loomImportDestinationFromPathname(+ "/dashboard/folder/a%2Fb%3Fc",+ );+ expect(loomImportPageHref(destination, "loom")).toBe(+ "/dashboard/import/loom?folderId=a%2Fb%3Fc",+ );+ expect(loomImportDestinationHref(destination)).toBe(+ "/dashboard/folder/a%2Fb%3Fc",+ );+ });++ it("does not break navigation on malformed URI escapes", () => {+ expect(() =>+ loomImportDestinationFromPathname("/dashboard/folder/bad%escape"),+ ).not.toThrow();+ });+});diff --git a/apps/web/__tests__/unit/loom-import-ui.test.ts b/apps/web/__tests__/unit/loom-import-ui.test.tsnew file mode 100644index 000000000..ffd14894c--- /dev/null+++ b/apps/web/__tests__/unit/loom-import-ui.test.ts@@ -0,0 +1,282 @@+// @vitest-environment jsdom++import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import React, { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++function queryByRole(+ container: ParentNode,+ role: string,+ options?: { name: string; exact?: boolean },+) {+ const selector = role === "button" ? "button" : `[role="${role}"]`;+ return (+ Array.from(container.querySelectorAll<HTMLElement>(selector)).find(+ (element) => {+ if (!options?.name) return true;+ const label = element.id+ ? document.querySelector(`label[for="${element.id}"]`)?.textContent+ : null;+ return (+ label === options.name || element.textContent?.trim() === options.name+ );+ },+ ) ?? null+ );+}+function getByRole(+ container: ParentNode,+ role: string,+ options?: { name: string; exact?: boolean },+) {+ const element = queryByRole(container, role, options);+ if (!element) throw new Error(`Missing ${role}: ${options?.name ?? ""}`);+ return element;+}+async function waitFor(assertion: () => void) {+ let error: unknown;+ for (let attempt = 0; attempt < 50; attempt++) {+ try {+ assertion();+ return;+ } catch (cause) {+ error = cause;+ }+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 10));+ });+ }+ throw error;+}+const fireEvent = {+ click: (element: HTMLElement) => element.click(),+ keyDown: (element: HTMLElement, init: KeyboardEventInit) =>+ element.dispatchEvent(+ new KeyboardEvent("keydown", { bubbles: true, ...init }),+ ),+ change: (+ element: HTMLInputElement,+ { target }: { target: { value: string } },+ ) => {+ const setter = Object.getOwnPropertyDescriptor(+ HTMLInputElement.prototype,+ "value",+ )?.set;+ if (!setter) throw new Error("Missing input setter");+ setter.call(element, target.value);+ element.dispatchEvent(new Event("input", { bubbles: true }));+ },+};+const mocks = vi.hoisted(() => ({+ folders: vi.fn(),+ import: vi.fn(),+ push: vi.fn(),+ refresh: vi.fn(),+}));+vi.mock("@/app/(org)/dashboard/Contexts", () => ({+ useDashboardContext: () => ({+ user: { id: "owner", isPro: true },+ activeOrganization: {+ organization: { id: "org", name: "Team", ownerId: "owner" },+ members: [],+ },+ spacesData: [{ id: "space", name: "Sales" }],+ }),+}));+vi.mock("@/components/UpgradeModal", () => ({ UpgradeModal: () => null }));+vi.mock("next/navigation", () => ({+ useRouter: () => ({ push: mocks.push, refresh: mocks.refresh }),+}));+vi.mock("next/link", () => ({+ default: ({+ children,+ ...props+ }: React.PropsWithChildren<Record<string, unknown>>) =>+ React.createElement("a", props, children),+}));+vi.mock("@/actions/loom", () => ({+ getLoomImportFolders: mocks.folders,+ importFromLoom: mocks.import,+ importFromLoomCsv: vi.fn(),+}));+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/Select")),+ ...(await import("../../../../packages/ui/src/components/Table")),+ ...(await import("../../../../packages/ui/src/components/input/Input")),+}));++import { Folder, Space } from "@cap/web-domain";+import { ImportLoomPage } from "@/app/(org)/dashboard/import/loom/ImportLoomPage";+import type { LoomImportDestination } from "@/lib/loom-import-destination";++let root: Root;+let container: HTMLDivElement;+let queryClient: QueryClient;+beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ HTMLElement.prototype.scrollIntoView = vi.fn();+ HTMLElement.prototype.hasPointerCapture = () => false;+ HTMLElement.prototype.setPointerCapture = vi.fn();+ HTMLElement.prototype.releasePointerCapture = vi.fn();+ mocks.folders.mockResolvedValue([+ { id: "parent", name: "Course", parentId: null },+ { id: "child", name: "Live Calls - Two", parentId: "parent" },+ { id: "sibling", name: "Design", parentId: "parent" },+ ]);+ mocks.import.mockResolvedValue({ success: true, videoId: "fixture" });+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+ queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+});+afterEach(async () => {+ await act(async () => root.unmount());+ container.remove();+ queryClient.clear();+});+async function render(destination: LoomImportDestination = {}) {+ await act(async () => {+ root.render(+ React.createElement(+ QueryClientProvider,+ { client: queryClient },+ React.createElement(ImportLoomPage, {+ initialDestination: destination,+ }),+ ),+ );+ });+}+async function ready() {+ await waitFor(() =>+ expect(+ (getByRole(container, "combobox") as HTMLButtonElement).disabled,+ ).toBe(false),+ );+}+async function enterUrl() {+ await act(async () => {+ const input = container.querySelector("input");+ if (!input) throw new Error("Missing Loom URL input");+ fireEvent.change(input, {+ target: { value: "https://www.loom.com/share/aaaaaaaaaaa" },+ });+ });+}+async function choose(name: string) {+ await act(async () => {+ fireEvent.keyDown(getByRole(container, "combobox"), { key: "Enter" });+ });+ await act(async () => {+ fireEvent.keyDown(+ getByRole(document.body, "option", { name, exact: true }),+ { key: "Enter" },+ );+ });+}++describe("Loom importer component", () => {+ it("shows the inherited subfolder and submits it then returns there", async () => {+ await render({ folderId: Folder.FolderId.make("child") });+ await ready();+ expect(+ getByRole(container, "combobox", { name: "Import to" }).textContent,+ ).toContain("My Caps / Course / Live Calls - Two");+ await enterUrl();+ await act(async () => {+ fireEvent.click(getByRole(container, "button", { name: "Import Loom" }));+ });+ expect(mocks.import).toHaveBeenCalledWith({+ loomUrl: "https://www.loom.com/share/aaaaaaaaaaa",+ orgId: "org",+ folderId: "child",+ spaceId: undefined,+ });+ expect(mocks.push).toHaveBeenCalledWith("/dashboard/folder/child");+ });+ it("allows choosing a different nested folder", async () => {+ await render({ folderId: Folder.FolderId.make("child") });+ await ready();+ await choose("My Caps / Course / Design");+ await enterUrl();+ await act(async () => {+ fireEvent.click(getByRole(container, "button", { name: "Import Loom" }));+ });+ expect(mocks.import).toHaveBeenCalledWith(+ expect.objectContaining({ folderId: "sibling" }),+ );+ });+ it("blocks a missing folder until the user chooses a destination", async () => {+ await render({ folderId: Folder.FolderId.make("missing") });+ await ready();+ await enterUrl();+ expect(getByRole(container, "alert").textContent).toContain(+ "no longer available",+ );+ expect(+ (+ getByRole(container, "button", {+ name: "Import Loom",+ }) as HTMLButtonElement+ ).disabled,+ ).toBe(true);+ await choose("My Caps");+ await act(async () => {+ fireEvent.click(getByRole(container, "button", { name: "Import Loom" }));+ });+ expect(mocks.import).toHaveBeenCalledWith(+ expect.objectContaining({ folderId: undefined }),+ );+ });+ it("shows a recoverable destination error without enabling import", async () => {+ mocks.folders.mockRejectedValueOnce(new Error("Unavailable"));+ await render();+ await enterUrl();+ await waitFor(() =>+ expect(getByRole(container, "alert").textContent).toContain(+ "couldn't load",+ ),+ );+ expect(+ (+ getByRole(container, "button", {+ name: "Import Loom",+ }) as HTMLButtonElement+ ).disabled,+ ).toBe(true);+ await act(async () => {+ fireEvent.click(getByRole(container, "button", { name: "Retry" }));+ });+ await ready();+ expect(queryByRole(container, "alert")).toBe(null);+ });+ it("shows shared visibility and returns to the selected space folder", async () => {+ await render({+ spaceId: Space.SpaceId.make("space"),+ folderId: Folder.FolderId.make("child"),+ });+ await ready();+ await enterUrl();+ expect(container.textContent).toContain(+ "This video will be shared with Sales.",+ );+ await act(async () => {+ fireEvent.click(getByRole(container, "button", { name: "Import Loom" }));+ });+ expect(mocks.import).toHaveBeenCalledWith(+ expect.objectContaining({+ spaceId: Space.SpaceId.make("space"),+ folderId: Folder.FolderId.make("child"),+ }),+ );+ expect(mocks.push).toHaveBeenCalledWith(+ "/dashboard/spaces/space/folder/child",+ );+ });+});diff --git a/apps/web/__tests__/unit/loom-import.test.ts b/apps/web/__tests__/unit/loom-import.test.tsindex 765347c06..fc1256226 100644--- a/apps/web/__tests__/unit/loom-import.test.ts+++ b/apps/web/__tests__/unit/loom-import.test.ts@@ -9,6 +9,8 @@ const storageGetWritableAccessForUserMock = vi.hoisted(() => vi.fn());const checkRateLimitMock = vi.hoisted(() => vi.fn());const headersMock = vi.hoisted(() => vi.fn());const getOrganizationAccessMock = vi.hoisted(() => vi.fn());+const requireSpaceManagerMock = vi.hoisted(() => vi.fn());+const requireOrganizationSettingsManagerMock = vi.hoisted(() => vi.fn());const mockDb = {select: vi.fn(() => mockDb),@@ -39,6 +41,15 @@ vi.mock("@cap/database/helpers", () => ({}));vi.mock("@cap/database/schema", () => ({+ folders: {+ id: "folderId",+ name: "folderName",+ parentId: "folderParentId",+ organizationId: "folderOrganizationId",+ createdById: "folderCreatedById",+ spaceId: "folderSpaceId",+ },+ sharedVideos: { id: "sharedVideoId" },importedVideos: {id: "id",orgId: "orgId",@@ -149,6 +160,7 @@ vi.mock("@cap/web-domain", () => ({}));vi.mock("drizzle-orm", () => ({+ asc: vi.fn((field: unknown) => ({ field })),and: vi.fn((...args: unknown[]) => args),eq: vi.fn((field: unknown, value: unknown) => ({ field, value })),isNull: vi.fn((field: unknown) => ({ field })),@@ -174,6 +186,11 @@ vi.mock("@/lib/server", async () => {vi.mock("@/actions/organization/authorization", () => ({getOrganizationAccess: getOrganizationAccessMock,requireOrganizationAccess: vi.fn(),+ requireOrganizationSettingsManager: requireOrganizationSettingsManagerMock,+}));++vi.mock("@/actions/organization/space-authorization", () => ({+ requireSpaceManager: requireSpaceManagerMock,}));vi.mock("workflow/api", () => ({@@ -198,6 +215,9 @@ describe("importFromLoom", () => {beforeEach(() => {vi.clearAllMocks();whereMock.mockReset();+ requireSpaceManagerMock.mockReset();+ requireOrganizationSettingsManagerMock.mockReset();+ requireSpaceManagerMock.mockResolvedValue({ organizationId: "org-1" });valuesMock.mockReset();mockDb.select.mockReturnValue(mockDb);mockDb.insert.mockReturnValue(mockDb);@@ -482,6 +502,206 @@ describe("importFromLoom", () => {expect(revalidatePathMock).toHaveBeenCalledWith("/dashboard/caps");});+ function mockSuccessfulDownload() {+ vi.mocked(fetch).mockImplementation(async (input) => {+ const url = String(input);+ if (url.includes("/transcoded-url"))+ return {+ ok: true,+ status: 200,+ text: async () =>+ JSON.stringify({ url: "https://cdn.loom.com/video.mp4" }),+ } as Response;+ if (url === "https://www.loom.com/graphql")+ return {+ ok: true,+ json: async () => ({+ data: { getVideo: { name: "Imported video" } },+ }),+ } as Response;+ if (url.includes("/v1/oembed"))+ return { ok: true, json: async () => ({ duration: 42 }) } as Response;+ throw new Error(`Unexpected fetch: ${url}`);+ });+ }++ it.each([+ {+ spaceId: undefined,+ expectedPersonalFolder: "nested-folder",+ sharing: null,+ },+ {+ spaceId: "space-1",+ expectedPersonalFolder: undefined,+ sharing: {+ spaceId: "space-1",+ folderId: "nested-folder",+ addedById: "user-123",+ },+ },+ {+ spaceId: "org-1",+ expectedPersonalFolder: undefined,+ sharing: {+ organizationId: "org-1",+ folderId: "nested-folder",+ sharedByUserId: "user-123",+ },+ },+ ])(+ "persists a nested folder before processing in $spaceId",+ async ({ spaceId, expectedPersonalFolder, sharing }) => {+ whereMock.mockReturnValueOnce(withLimit([{ id: "nested-folder" }]));+ mockSuccessfulDownload();+ const { importFromLoom } = await import("@/actions/loom");+ const result = await importFromLoom({+ loomUrl: "https://www.loom.com/share/loom-abc1234567",+ orgId: "org-1" as never,+ folderId: "nested-folder" as never,+ spaceId: spaceId as never,+ });+ expect(result.success).toBe(true);+ expect(mockDb.transaction).toHaveBeenCalledTimes(1);+ expect(valuesMock).toHaveBeenNthCalledWith(+ 1,+ expect.objectContaining({+ id: "video-123",+ ownerId: "user-123",+ folderId: expectedPersonalFolder,+ }),+ );+ if (sharing)+ expect(valuesMock).toHaveBeenLastCalledWith(+ expect.objectContaining({ videoId: "video-123", ...sharing }),+ );+ expect(startMock.mock.invocationCallOrder[0]).toBeGreaterThan(+ valuesMock.mock.invocationCallOrder.at(-1) ?? Infinity,+ );+ if (spaceId === "org-1")+ expect(requireOrganizationSettingsManagerMock).toHaveBeenCalledWith(+ "user-123",+ "org-1",+ );+ else if (spaceId)+ expect(requireSpaceManagerMock).toHaveBeenCalledWith(+ "user-123",+ spaceId,+ );+ else expect(requireSpaceManagerMock).not.toHaveBeenCalled();+ expect(revalidatePathMock).toHaveBeenCalledWith(+ "/dashboard/folder/[id]",+ "page",+ );+ if (spaceId)+ expect(revalidatePathMock).toHaveBeenCalledWith(+ "/dashboard/spaces/[spaceId]/folder/[folderId]",+ "page",+ );+ },+ );++ it("rejects a missing or foreign personal folder before fetching or writing", async () => {+ whereMock.mockReturnValueOnce(withLimit([]));+ const { importFromLoom } = await import("@/actions/loom");+ const result = await importFromLoom({+ loomUrl: "https://www.loom.com/share/loom-abc1234567",+ orgId: "org-1" as never,+ folderId: "foreign-folder" as never,+ });+ expect(result.success).toBe(false);+ expect(result.error).toContain("Destination folder not found");+ const conditions = JSON.stringify(whereMock.mock.calls[0]);+ for (const required of [+ "foreign-folder",+ "folderOrganizationId",+ "org-1",+ "folderCreatedById",+ "user-123",+ "folderSpaceId",+ ])+ expect(conditions).toContain(required);+ expect(fetch).not.toHaveBeenCalled();+ expect(valuesMock).not.toHaveBeenCalled();+ });++ it.each(["space-1", "org-1"])(+ "rejects unauthorized shared destination %s",+ async (spaceId) => {+ requireSpaceManagerMock.mockRejectedValue(new Error("Forbidden"));+ requireOrganizationSettingsManagerMock.mockRejectedValue(+ new Error("Forbidden"),+ );+ const { importFromLoom } = await import("@/actions/loom");+ await expect(+ importFromLoom({+ loomUrl: "https://www.loom.com/share/loom-abc1234567",+ orgId: "org-1" as never,+ folderId: "folder-1" as never,+ spaceId: spaceId as never,+ }),+ ).rejects.toThrow("Forbidden");+ expect(fetch).not.toHaveBeenCalled();+ expect(valuesMock).not.toHaveBeenCalled();+ },+ );++ it("rejects a space from a different organization even for its manager", async () => {+ requireSpaceManagerMock.mockResolvedValueOnce({+ organizationId: "foreign-org",+ });+ const { importFromLoom } = await import("@/actions/loom");+ await expect(+ importFromLoom({+ loomUrl: "https://www.loom.com/share/loom-abc1234567",+ orgId: "org-1" as never,+ spaceId: "foreign-space" as never,+ }),+ ).rejects.toThrow("Space not found");+ expect(fetch).not.toHaveBeenCalled();+ expect(valuesMock).not.toHaveBeenCalled();+ });++ it("does not start processing when persisting a shared destination fails", async () => {+ mockSuccessfulDownload();+ valuesMock+ .mockResolvedValueOnce(undefined)+ .mockResolvedValueOnce(undefined)+ .mockResolvedValueOnce(undefined)+ .mockRejectedValueOnce(new Error("Could not save destination"));+ const { importFromLoom } = await import("@/actions/loom");+ await expect(+ importFromLoom({+ loomUrl: "https://www.loom.com/share/loom-abc1234567",+ orgId: "org-1" as never,+ spaceId: "space-1" as never,+ }),+ ).rejects.toThrow("Could not save destination");+ expect(mockDb.transaction).toHaveBeenCalledTimes(1);+ expect(startMock).not.toHaveBeenCalled();+ });++ it("lists only the current user's personal folders in the requested organization", async () => {+ const rows = [+ { id: "parent", name: "Course", parentId: null },+ { id: "child", name: "Live Calls", parentId: "parent" },+ ];+ whereMock.mockReturnValueOnce({ orderBy: vi.fn().mockResolvedValue(rows) });+ const { getLoomImportFolders } = await import("@/actions/loom");+ expect(await getLoomImportFolders({ orgId: "org-1" as never })).toEqual(+ rows,+ );+ const conditions = JSON.stringify(whereMock.mock.calls[0]);+ for (const required of [+ "folderOrganizationId",+ "org-1",+ "folderCreatedById",+ "user-123",+ "folderSpaceId",+ ])+ expect(conditions).toContain(required);+ });+it("rejects a CSV import when the current user is not an organization admin or owner", async () => {getOrganizationAccessMock.mockResolvedValueOnce({id: "org-1",@@ -904,7 +1124,7 @@ describe("importFromLoom", () => {],error: undefined,});- expect(mockDb.transaction).toHaveBeenCalledTimes(1);+ expect(mockDb.transaction).toHaveBeenCalledTimes(2);expect(valuesMock).toHaveBeenCalledWith(expect.objectContaining({name: "Sales Team",diff --git a/apps/web/actions/loom.ts b/apps/web/actions/loom.tsindex 75f3672a2..b9e03dcec 100644--- a/apps/web/actions/loom.ts+++ b/apps/web/actions/loom.ts@@ -5,8 +5,10 @@ import { db } from "@cap/database";import { getCurrentUser } from "@cap/database/auth/session";import { nanoId } from "@cap/database/helpers";import {+ folders,importedVideos,organizationMembers,+ sharedVideos,spaceMembers,spaces,spaceVideos,@@ -24,14 +26,17 @@ import {type User,Video,} from "@cap/web-domain";-import { and, eq } from "drizzle-orm";+import { and, asc, eq, isNull } from "drizzle-orm";import { Option } from "effect";import { revalidatePath } from "next/cache";import { start } from "workflow/api";import {getOrganizationAccess,requireOrganizationAccess,+ requireOrganizationSettingsManager,} from "@/actions/organization/authorization";+import { requireSpaceManager } from "@/actions/organization/space-authorization";+import type { LoomImportDestination } from "@/lib/loom-import-destination";import { provisionOrganizationInvitee } from "@/lib/organization-provisioning";import { canManageOrganizationSettings } from "@/lib/permissions/roles";import { runPromise } from "@/lib/server";@@ -294,10 +299,12 @@ async function importLoomVideoForOwner({loomUrl,orgId,ownerId,+ destination = {},}: {loomUrl: string;orgId: Organisation.OrganisationId;ownerId: User.UserId;+ destination?: LoomImportDestination;}): Promise<LoomImportResult> {const loomVideoId = extractLoomVideoId(loomUrl.trim());if (!loomVideoId) {@@ -387,13 +394,13 @@ async function importLoomVideoForOwner({videoName ||`Loom Import - ${new Date().toLocaleDateString("en-US", { day: "numeric", month: "long", year: "numeric" })}`;- await db()- .insert(videos)- .values({+ await db().transaction(async (tx) => {+ await tx.insert(videos).values({id: videoId,name,ownerId,orgId,+ folderId: destination.spaceId ? undefined : destination.folderId,source: { type: "webMP4" as const },bucket: Option.getOrNull(writable.bucketId),storageIntegrationId: Option.getOrNull(writable.storageIntegrationId),@@ -403,18 +410,37 @@ async function importLoomVideoForOwner({...(oembedMeta?.height ? { height: oembedMeta.height } : {}),});- await db().insert(videoUploads).values({- videoId,- phase: "uploading",- processingProgress: 0,- processingMessage: "Importing from Loom...",- });+ await tx.insert(videoUploads).values({+ videoId,+ phase: "uploading",+ processingProgress: 0,+ processingMessage: "Importing from Loom...",+ });- await db().insert(importedVideos).values({- id: videoId,- orgId,- source: "loom",- sourceId: loomVideoId,+ await tx.insert(importedVideos).values({+ id: videoId,+ orgId,+ source: "loom",+ sourceId: loomVideoId,+ });++ if (destination.spaceId === orgId) {+ await tx.insert(sharedVideos).values({+ id: nanoId(),+ videoId,+ organizationId: orgId,+ sharedByUserId: ownerId,+ folderId: destination.folderId,+ });+ } else if (destination.spaceId) {+ await tx.insert(spaceVideos).values({+ id: nanoId(),+ videoId,+ spaceId: destination.spaceId,+ addedById: ownerId,+ folderId: destination.folderId,+ });+ }});const rawFileKey = `${ownerId}/${videoId}/raw-upload.mp4`;@@ -440,17 +466,69 @@ async function importLoomVideoForOwner({]);revalidatePath("/dashboard/caps");+ if (destination.folderId) revalidatePath("/dashboard/folder/[id]", "page");+ if (destination.spaceId) {+ revalidatePath("/dashboard/spaces/[spaceId]", "page");+ revalidatePath("/dashboard/spaces/[spaceId]/folder/[folderId]", "page");+ }return { success: true, videoId };}+async function requireLoomImportLocationAccess(+ userId: User.UserId,+ orgId: Organisation.OrganisationId,+ spaceId?: Space.SpaceIdOrOrganisationId,+) {+ await requireOrganizationAccess(userId, orgId);+ if (!spaceId) return;+ if (spaceId === orgId) {+ await requireOrganizationSettingsManager(userId, orgId);+ return;+ }+ const access = await requireSpaceManager(userId, spaceId);+ if (access.organizationId !== orgId) throw new Error("Space not found");+}++function loomImportFolderScope(+ userId: User.UserId,+ orgId: Organisation.OrganisationId,+ spaceId?: Space.SpaceIdOrOrganisationId,+) {+ return and(+ eq(folders.organizationId, orgId),+ spaceId+ ? eq(folders.spaceId, spaceId)+ : and(isNull(folders.spaceId), eq(folders.createdById, userId)),+ );+}++export async function getLoomImportFolders({+ orgId,+ spaceId,+}: {+ orgId: Organisation.OrganisationId;+ spaceId?: Space.SpaceIdOrOrganisationId;+}) {+ const user = await getCurrentUser();+ if (!user) throw new Error("Unauthorized");+ await requireLoomImportLocationAccess(user.id, orgId, spaceId);+ return db()+ .select({ id: folders.id, name: folders.name, parentId: folders.parentId })+ .from(folders)+ .where(loomImportFolderScope(user.id, orgId, spaceId))+ .orderBy(asc(folders.name));+}+export async function importFromLoom({loomUrl,orgId,+ folderId,+ spaceId,}: {loomUrl: string;orgId: Organisation.OrganisationId;-}): Promise<LoomImportResult> {+} & LoomImportDestination): Promise<LoomImportResult> {const user = await getCurrentUser();if (!user) return { success: false, error: "Unauthorized" };@@ -461,12 +539,31 @@ export async function importFromLoom({};}- await requireOrganizationAccess(user.id, orgId);+ await requireLoomImportLocationAccess(user.id, orgId, spaceId);+ if (folderId) {+ const [folder] = await db()+ .select({ id: folders.id })+ .from(folders)+ .where(+ and(+ eq(folders.id, folderId),+ loomImportFolderScope(user.id, orgId, spaceId),+ ),+ )+ .limit(1);+ if (!folder)+ return {+ success: false,+ error:+ "Destination folder not found. Choose another folder and try again.",+ };+ }return importLoomVideoForOwner({loomUrl,orgId,ownerId: user.id,+ destination: { folderId, spaceId },});}diff --git a/apps/web/app/(org)/dashboard/_components/Navbar/DashboardSearch.tsx b/apps/web/app/(org)/dashboard/_components/Navbar/DashboardSearch.tsxindex bb0281977..e6aff4707 100644--- a/apps/web/app/(org)/dashboard/_components/Navbar/DashboardSearch.tsx+++ b/apps/web/app/(org)/dashboard/_components/Navbar/DashboardSearch.tsx@@ -29,8 +29,12 @@ import {UserRound,UsersRound,} from "lucide-react";-import { useRouter } from "next/navigation";+import { usePathname, useRouter } from "next/navigation";import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";+import {+ loomImportDestinationFromPathname,+ loomImportPageHref,+} from "@/lib/loom-import-destination";import {canViewOrganizationSettings,getEffectiveOrganizationRole,@@ -121,6 +125,7 @@ export function DashboardSearch({shortcutEnabled?: boolean;} = {}) {const router = useRouter();+ const pathname = usePathname();const { activeOrganization, spacesData, user } = useDashboardContext();const { platform } = useDetectPlatform();const [open, setOpen] = useState(false);@@ -168,7 +173,7 @@ export function DashboardSearch({id: "import-video",title: "Import Media",subtitle: "Bring an existing video or image into Cap",- href: "/dashboard/import",+ href: loomImportPageHref(loomImportDestinationFromPathname(pathname)),value: "import upload loom video image media file",icon: Upload,},@@ -189,7 +194,7 @@ export function DashboardSearch({icon: FolderSearch,},],- [],+ [pathname],);const settingsItems = useMemo<SearchItem[]>(diff --git a/apps/web/app/(org)/dashboard/_components/Navbar/Items.tsx b/apps/web/app/(org)/dashboard/_components/Navbar/Items.tsxindex 54afd814b..e91138d70 100644--- a/apps/web/app/(org)/dashboard/_components/Navbar/Items.tsx+++ b/apps/web/app/(org)/dashboard/_components/Navbar/Items.tsx@@ -42,6 +42,10 @@ import { NewOrganization } from "@/components/forms/NewOrganization";import { SignedImageUrl } from "@/components/SignedImageUrl";import { Tooltip } from "@/components/Tooltip";import { UsageButton } from "@/components/UsageButton";+import {+ loomImportDestinationFromPathname,+ loomImportPageHref,+} from "@/lib/loom-import-destination";import {canViewOrganizationSettings,getEffectiveOrganizationRole,@@ -98,7 +102,7 @@ const AdminNavItems = ({ toggleMobileNav }: Props) => {},{name: "Import Media",- href: `/dashboard/import`,+ href: loomImportPageHref(loomImportDestinationFromPathname(pathname)),matchChildren: true,icon: <ImportIcon />,subNav: [],@@ -174,11 +178,12 @@ const AdminNavItems = ({ toggleMobileNav }: Props) => {}, [canScrollUp, canScrollDown]);const isPathActive = (path: string, matchChildren: boolean = false) => {+ const basePath = path.split("?")[0] ?? path;if (matchChildren) {- return pathname === path || pathname.startsWith(`${path}/`);+ return pathname === basePath || pathname.startsWith(`${basePath}/`);}- return pathname === path;+ return pathname === basePath;};const isDomainSetupVerified =diff --git a/apps/web/app/(org)/dashboard/caps/components/UploadCapButton.tsx b/apps/web/app/(org)/dashboard/caps/components/UploadCapButton.tsxindex 60b50009c..8007792c5 100644--- a/apps/web/app/(org)/dashboard/caps/components/UploadCapButton.tsx+++ b/apps/web/app/(org)/dashboard/caps/components/UploadCapButton.tsx@@ -3,10 +3,14 @@import { Button } from "@cap/ui";import { faUpload } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";-import { useRouter } from "next/navigation";+import { usePathname, useRouter } from "next/navigation";import { useState } from "react";import { useDashboardContext } from "@/app/(org)/dashboard/Contexts";import { UpgradeModal } from "@/components/UpgradeModal";+import {+ loomImportDestinationFromPathname,+ loomImportPageHref,+} from "@/lib/loom-import-destination";export const UploadCapButton = ({size = "md",@@ -17,6 +21,7 @@ export const UploadCapButton = ({const { user } = useDashboardContext();const [upgradeModalOpen, setUpgradeModalOpen] = useState(false);const router = useRouter();+ const pathname = usePathname();const handleClick = () => {if (!user) return;@@ -26,7 +31,9 @@ export const UploadCapButton = ({return;}- router.push("/dashboard/import");+ router.push(+ loomImportPageHref(loomImportDestinationFromPathname(pathname)),+ );};return (diff --git a/apps/web/app/(org)/dashboard/import/ImportPage.tsx b/apps/web/app/(org)/dashboard/import/ImportPage.tsxindex 3cee18f5e..9712a3af2 100644--- a/apps/web/app/(org)/dashboard/import/ImportPage.tsx+++ b/apps/web/app/(org)/dashboard/import/ImportPage.tsx@@ -3,8 +3,16 @@import { faUpload } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";import Link from "next/link";+import {+ type LoomImportDestination,+ loomImportPageHref,+} from "@/lib/loom-import-destination";-export const ImportPage = () => {+export const ImportPage = ({+ initialDestination = {},+}: {+ initialDestination?: LoomImportDestination;+}) => {return (<div className="flex flex-col w-full h-full"><div className="mb-8">@@ -35,7 +43,7 @@ export const ImportPage = () => {</Link><Link- href="/dashboard/import/loom"+ href={loomImportPageHref(initialDestination, "loom")}className="flex overflow-hidden relative flex-col w-full rounded-xl border transition-all duration-200 group border-gray-3 bg-gray-1 hover:border-blue-10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-8"><div className="flex justify-center items-center w-full h-32 transition-colors duration-200 bg-gray-3 group-hover:bg-gray-4">diff --git a/apps/web/app/(org)/dashboard/import/loom/ImportLoomPage.tsx b/apps/web/app/(org)/dashboard/import/loom/ImportLoomPage.tsxindex 58bd4d89e..bab2aaba6 100644--- a/apps/web/app/(org)/dashboard/import/loom/ImportLoomPage.tsx+++ b/apps/web/app/(org)/dashboard/import/loom/ImportLoomPage.tsx@@ -9,6 +9,11 @@ import {DialogTitle,Input,Select,+ SelectContent,+ SelectItem,+ SelectRoot,+ SelectTrigger,+ SelectValue,Table,TableBody,TableCell,@@ -16,6 +21,7 @@ import {TableHeader,TableRow,} from "@cap/ui";+import { Folder } from "@cap/web-domain";import {faArrowLeft,faCircleCheck,@@ -26,6 +32,7 @@ import {faUpload,} from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";+import { useQuery } from "@tanstack/react-query";import clsx from "clsx";import { motion } from "framer-motion";import Link from "next/link";@@ -33,12 +40,14 @@ import { useRouter } from "next/navigation";import {type ChangeEvent,type DragEvent,+ useId,useMemo,useRef,useState,} from "react";import { toast } from "sonner";import {+ getLoomImportFolders,importFromLoom,importFromLoomCsv,type LoomCsvImportResult,@@ -46,6 +55,12 @@ import {} from "@/actions/loom";import { useDashboardContext } from "@/app/(org)/dashboard/Contexts";import { UpgradeModal } from "@/components/UpgradeModal";+import {+ type LoomImportDestination,+ loomImportDestinationHref,+ loomImportPageHref,+} from "@/lib/loom-import-destination";+import { buildMoveFolderDestinationRows } from "@/lib/move-items";import {canManageOrganizationSettings,getEffectiveOrganizationRole,@@ -75,6 +90,8 @@ type MappedRow = {const LOOM_CSV_TEMPLATE ="loom_video_url,user_email,space_name\nhttps://www.loom.com/share/0123456789abcdef,[email protected],Sales\n";+const ROOT_FOLDER_VALUE = "__cap_root_folder__";+const OPTIONAL_COLUMN_VALUE = "__cap_skip_column__";const MAX_SPACE_NAME_LENGTH = 255;const MAX_LOOM_CSV_IMPORT_ROWS = 500;@@ -232,8 +249,12 @@ const LoomMark = ({ size = 18 }: { size?: number }) => (</svg>);-export const ImportLoomPage = () => {- const { user, activeOrganization } = useDashboardContext();+export const ImportLoomPage = ({+ initialDestination = {},+}: {+ initialDestination?: LoomImportDestination;+}) => {+ const { user, activeOrganization, spacesData } = useDashboardContext();const router = useRouter();const currentMember = activeOrganization?.members.find(@@ -250,6 +271,45 @@ export const ImportLoomPage = () => {const activeMode = canUseCsvImport ? mode : "single";const [upgradeModalOpen, setUpgradeModalOpen] = useState(!user?.isPro);+ const [selectedFolderId, setSelectedFolderId] = useState(+ initialDestination.folderId ?? ROOT_FOLDER_VALUE,+ );+ const destinationInputId = useId();+ const orgId = activeOrganization?.organization.id;+ const spaceId = initialDestination.spaceId;+ const foldersQuery = useQuery({+ queryKey: ["loom-import-folders", user.id, orgId, spaceId],+ queryFn: () =>+ orgId ? getLoomImportFolders({ orgId, spaceId }) : Promise.resolve([]),+ enabled: Boolean(orgId) && activeMode === "single",+ });+ const folderRows = useMemo(+ () => buildMoveFolderDestinationRows(foldersQuery.data ?? []),+ [foldersQuery.data],+ );+ const destination: LoomImportDestination = {+ folderId:+ selectedFolderId === ROOT_FOLDER_VALUE+ ? undefined+ : Folder.FolderId.make(selectedFolderId),+ spaceId,+ };+ const rootLabel = !spaceId+ ? "My Caps"+ : spaceId === orgId+ ? (activeOrganization?.organization.name ?? "Organization")+ : (spacesData?.find((space) => space.id === spaceId)?.name ?? "Space");+ const selectedFolder = folderRows.find(+ (folder) => folder.id === selectedFolderId,+ );+ const destinationAvailable =+ foldersQuery.isSuccess &&+ (selectedFolderId === ROOT_FOLDER_VALUE || Boolean(selectedFolder));+ const destinationLabel = selectedFolder+ ? `${rootLabel} / ${selectedFolder.path}`+ : rootLabel;+ const importPageHref = loomImportPageHref(destination);+const [loomUrl, setLoomUrl] = useState("");const [isImporting, setIsImporting] = useState(false);@@ -340,7 +400,7 @@ export const ImportLoomPage = () => {return;}- if (!loomUrl.trim()) return;+ if (!loomUrl.trim() || !destinationAvailable || isImporting) return;setIsImporting(true);@@ -348,6 +408,7 @@ export const ImportLoomPage = () => {const importResult = await importFromLoom({loomUrl: loomUrl.trim(),orgId: activeOrganization.organization.id,+ ...destination,});if (!importResult?.success) {@@ -356,10 +417,9 @@ export const ImportLoomPage = () => {return;}- toast.success(- "Loom video import started! It will appear in your caps shortly.",- );- router.push("/dashboard/caps");+ toast.success(`Loom import started in ${destinationLabel}.`);+ router.push(loomImportDestinationHref(destination));+ router.refresh();} catch {toast.error("An unexpected error occurred. Please try again.");} finally {@@ -518,7 +578,7 @@ export const ImportLoomPage = () => {<div className="flex flex-col w-full h-full"><div className="mb-8"><Link- href="/dashboard/import"+ href={importPageHref}className="inline-flex gap-2 items-center mb-4 text-sm transition-colors text-gray-10 hover:text-gray-12"><FontAwesomeIcon className="size-3" icon={faArrowLeft} />@@ -579,18 +639,98 @@ export const ImportLoomPage = () => {onChange={(event) => setLoomUrl(event.target.value)}placeholder="https://www.loom.com/share/..."onKeyDown={(event) => {- if (event.key === "Enter" && isValidLoomUrl && !isImporting) {+ if (+ event.key === "Enter" &&+ isValidLoomUrl &&+ !isImporting &&+ destinationAvailable+ ) {handleSingleImport();}}}/>+ <div className="flex flex-col gap-2">+ <label+ htmlFor={destinationInputId}+ className="text-sm font-medium text-gray-12"+ >+ Import to+ </label>+ <SelectRoot+ value={foldersQuery.isPending ? "" : selectedFolderId}+ onValueChange={setSelectedFolderId}+ disabled={+ foldersQuery.isPending ||+ foldersQuery.isError ||+ isImporting+ }+ >+ <SelectTrigger+ id={destinationInputId}+ className="w-full min-w-0 [&_span]:truncate"+ >+ <SelectValue+ placeholder={+ foldersQuery.isPending+ ? "Loading folders..."+ : "Choose a destination"+ }+ />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value={ROOT_FOLDER_VALUE}>+ {rootLabel}+ </SelectItem>+ {folderRows.map((folder) => (+ <SelectItem key={folder.id} value={folder.id}>+ {rootLabel} / {folder.path}+ </SelectItem>+ ))}+ </SelectContent>+ </SelectRoot>+ {foldersQuery.isError ? (+ <div+ role="alert"+ className="flex flex-wrap gap-2 items-center text-sm text-red-11"+ >+ <p>+ We couldn't load this destination. Check your access or+ try again.+ </p>+ <Button+ type="button"+ size="sm"+ variant="gray"+ onClick={() => foldersQuery.refetch()}+ disabled={foldersQuery.isFetching}+ >+ Retry+ </Button>+ {spaceId && (+ <Link href="/dashboard/import/loom" className="underline">+ Import to My Caps instead+ </Link>+ )}+ </div>+ ) : foldersQuery.isSuccess && !destinationAvailable ? (+ <p role="alert" className="text-sm text-red-11">+ This folder is no longer available. Choose another+ destination.+ </p>+ ) : spaceId ? (+ <p className="text-xs text-gray-10">+ This video will be shared with {rootLabel}.+ </p>+ ) : null}+ </div>+<div className="flex flex-col-reverse gap-3 justify-end sm:flex-row"><Buttontype="button"size="sm"variant="gray"- onClick={() => router.push("/dashboard/import")}+ onClick={() => router.push(importPageHref)}>Cancel</Button>@@ -600,7 +740,9 @@ export const ImportLoomPage = () => {size="sm"spinner={isImporting}variant="dark"- disabled={!isValidLoomUrl || isImporting}+ disabled={+ !isValidLoomUrl || isImporting || !destinationAvailable+ }>{isImporting ? "Importing..." : "Import Loom"}</Button>diff --git a/apps/web/app/(org)/dashboard/import/loom/page.tsx b/apps/web/app/(org)/dashboard/import/loom/page.tsxindex 6e9def333..86841acb0 100644--- a/apps/web/app/(org)/dashboard/import/loom/page.tsx+++ b/apps/web/app/(org)/dashboard/import/loom/page.tsx@@ -1,10 +1,24 @@import type { Metadata } from "next";+import {+ loomImportDestinationFromSearchParams,+ loomImportPageHref,+} from "@/lib/loom-import-destination";import { ImportLoomPage } from "./ImportLoomPage";export const metadata: Metadata = {title: "Import from Loom — Cap",};-export default function Page() {- return <ImportLoomPage />;+export default async function Page({+ searchParams,+}: {+ searchParams: Promise<Record<string, string | string[] | undefined>>;+}) {+ const destination = loomImportDestinationFromSearchParams(await searchParams);+ return (+ <ImportLoomPage+ key={loomImportPageHref(destination)}+ initialDestination={destination}+ />+ );}diff --git a/apps/web/app/(org)/dashboard/import/page.tsx b/apps/web/app/(org)/dashboard/import/page.tsxindex c7661b56c..9534093fb 100644--- a/apps/web/app/(org)/dashboard/import/page.tsx+++ b/apps/web/app/(org)/dashboard/import/page.tsx@@ -1,10 +1,24 @@import type { Metadata } from "next";+import {+ loomImportDestinationFromSearchParams,+ loomImportPageHref,+} from "@/lib/loom-import-destination";import { ImportPage } from "./ImportPage";export const metadata: Metadata = {title: "Import — Cap",};-export default function Page() {- return <ImportPage />;+export default async function Page({+ searchParams,+}: {+ searchParams: Promise<Record<string, string | string[] | undefined>>;+}) {+ const destination = loomImportDestinationFromSearchParams(await searchParams);+ return (+ <ImportPage+ key={loomImportPageHref(destination)}+ initialDestination={destination}+ />+ );}diff --git a/apps/web/lib/loom-import-destination.ts b/apps/web/lib/loom-import-destination.tsnew file mode 100644index 000000000..9959bd51a--- /dev/null+++ b/apps/web/lib/loom-import-destination.ts@@ -0,0 +1,70 @@+import { Folder, Space } from "@cap/web-domain";++export type LoomImportDestination = {+ folderId?: Folder.FolderId;+ spaceId?: Space.SpaceIdOrOrganisationId;+};++export function loomImportDestinationFromPathname(+ pathname: string,+): LoomImportDestination {+ const personal = pathname.match(/^\/dashboard\/folder\/([^/]+)\/?$/);+ if (personal?.[1])+ return { folderId: Folder.FolderId.make(decodePathSegment(personal[1])) };+ const shared = pathname.match(+ /^\/dashboard\/spaces\/([^/]+)(?:\/folder\/([^/]+))?\/?$/,+ );+ if (!shared?.[1] || shared[1] === "browse") return {};+ return {+ spaceId: Space.SpaceId.make(decodePathSegment(shared[1])),+ folderId: shared[2]+ ? Folder.FolderId.make(decodePathSegment(shared[2]))+ : undefined,+ };+}++export function loomImportDestinationFromSearchParams(+ params: Record<string, string | string[] | undefined>,+): LoomImportDestination {+ return {+ folderId:+ typeof params.folderId === "string" && params.folderId+ ? Folder.FolderId.make(params.folderId)+ : undefined,+ spaceId:+ typeof params.spaceId === "string" && params.spaceId+ ? Space.SpaceId.make(params.spaceId)+ : undefined,+ };+}++export function loomImportPageHref(+ destination: LoomImportDestination,+ source?: "loom",+) {+ const params = new URLSearchParams();+ if (destination.folderId) params.set("folderId", destination.folderId);+ if (destination.spaceId) params.set("spaceId", destination.spaceId);+ const query = params.toString();+ return `/dashboard/import${source ? `/${source}` : ""}${query ? `?${query}` : ""}`;+}++export function loomImportDestinationHref(destination: LoomImportDestination) {+ if (destination.spaceId) {+ const root = `/dashboard/spaces/${encodeURIComponent(destination.spaceId)}`;+ return destination.folderId+ ? `${root}/folder/${encodeURIComponent(destination.folderId)}`+ : root;+ }+ return destination.folderId+ ? `/dashboard/folder/${encodeURIComponent(destination.folderId)}`+ : "/dashboard/caps";+}++function decodePathSegment(value: string) {+ try {+ return decodeURIComponent(value);+ } catch {+ return value;+ }+}