Open source CapCut alternative.
TypeScript
fix(site): resume link imports after a reload [rebuild]
David Le1fb198696c6c
diff --git a/site/src/cut/components/LibraryView.tsx b/site/src/cut/components/LibraryView.tsxindex ee857f70..aa46d6fd 100644--- a/site/src/cut/components/LibraryView.tsx+++ b/site/src/cut/components/LibraryView.tsx@@ -1,6 +1,6 @@"use client";-import { dismissLibraryImport, importLibraryFiles, useLibraryFileImports, type LibraryArrival as Pending } from "@/cut/lib/libraryIntake";+import { dismissLibraryImport, importLibraryFiles, importLibraryLink, resumeLibraryLinks, useLibraryImports, type LibraryArrival as Pending } from "@/cut/lib/libraryIntake";import { LibraryImportCard } from "@/cut/components/LibraryImportCard";import { libraryFolderRef } from "@/cut/lib/folderReference";import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";@@ -39,9 +39,7 @@ import {deleteFromLibrary,deleteLibraryFolder,deleteTemplate,- estimatedShape,folderDeleteTakes,- importUrlToLibrary,libraryMediaUrl,carryAssetTo,carryTemplateTo,@@ -59,7 +57,7 @@ import { dialogOnTop, isPasteTarget } from "@/cut/lib/shortcutGate";import { lightboxItemFromLibrary, useLightbox } from "@/cut/lib/lightbox";import { reportActivity } from "@/cut/lib/tabActivity";import { useNewProjectTarget } from "@/cut/lib/newProject";-import { useListedResidencies, useLocalCompute } from "@/cut/lib/backend/hooks";+import { useEngineUser, useListedResidencies, useLocalCompute } from "@/cut/lib/backend/hooks";import { setNeedsApp } from "@/cut/lib/needsApp";import type { Residency } from "@/cut/lib/residency";import { LibraryShareDialog } from "@/cut/components/LibraryShareDialog";@@ -109,46 +107,6 @@ const isTemplate = (x: LibraryAsset | LibraryTemplateItem): x is LibraryTemplatetype DeleteSet = { folders: LibraryFolder[]; items: (LibraryAsset | LibraryTemplateItem)[] };const NO_PICK: DeleteSet = { folders: [], items: [] };-/** Routing words a path spends on the way to the thing: they say nothing about- * which post this is, so a label built from one ("youtube.com/watch") reads the- * same for every import from that site. */-const ROUTE_SEGMENT = new Set([- "watch",- "video",- "videos",- "embed",- "v",- "e",- "p",- "post",- "posts",- "status",- "share",- "media",- "download",-]);--/** A link's name on its tile: the site it points at and the token that- * identifies the post — the last telling path segment, or the id a watch URL- * carries in its query — so two imports from one site read apart. */-function linkLabel(url: string): string {- try {- const u = new URL(url);- const host = u.hostname.replace(/^www\./, "");- const id =- u.pathname- .split("/")- .filter(Boolean)- .reverse()- .find((seg) => !ROUTE_SEGMENT.has(seg.toLowerCase())) ??- u.searchParams.get("v");- return id ? `${host}/${id}` : host;- } catch {- return url;- }-}--export function LibraryView() {const noteView = useRef<NotesViewHandle>(null);const router = useRouter();@@ -203,9 +161,12 @@ export function LibraryView() {// Media on its way in — an upload or a link — each one a tile in the grid// from the moment it starts, so the library shows the work rather than the// dialog holding it.- const [linkPending, setPending] = useState<Pending[]>([]);- const filePending = useLibraryFileImports((state) => state.items);- const pending = useMemo(() => [...linkPending, ...filePending], [linkPending, filePending]);+ const pending = useLibraryImports((state) => state.items);+ // A reload cuts a link import's page off from its job; its tile comes back.+ const engineUser = useEngineUser();+ useEffect(() => {+ void resumeLibraryLinks(client);+ }, [client, engineUser]);// One drain bounds probe, decode, and transfer work across overlapping drops.const [sharing, setSharing] = useState<(LibraryShareTarget & { residency: Residency }) | null>(null);useLayoutEffect(() => () => setSharing(null), []);@@ -262,32 +223,8 @@ export function LibraryView() {useEffect(() => {reportActivity("import", pending.some((p) => !p.error));}, [pending]);- const addPending = (p: Pending) => setPending((q) => [...q, p]);- const setStage = (id: string, stage: Pending["stage"]) =>- setPending((q) => q.map((p) => (p.id === id ? { ...p, stage } : p)));- const failPending = (id: string, error: string) =>- setPending((q) => q.map((p) => (p.id === id ? { ...p, error } : p)));- const dropPending = (id: string) => {- setPending((q) => q.filter((p) => p.id !== id));- dismissLibraryImport(id);- };- // Run a failed arrival again on the tile it already has: the reason clears,- // the clock restarts, and the same work goes out once more.- const retryPending = (item: Pending) => {- setPending((q) =>- q.map((p) =>- p.id === item.id- ? {- ...p,- error: undefined,- stage: item.startStage,- startedAt: Date.now(),- }- : p,- ),- );- void item.run();- };+ // Run a failed arrival again on the tile it already has.+ const retryPending = (item: Pending) => void item.run();const upload = (files: FileList | File[], into: string | null = openFolder) => {const destination = landing(into);@@ -301,50 +238,11 @@ export function LibraryView() {const importLink = async (raw: string) => {const value = normalizeLink(raw);if (!value) return;- const { residency, folderId } = landing(openFolder);- if (!live(residency)) return;+ const destination = landing(openFolder);+ if (!live(destination.residency)) return;setUrl("");setAddOpen(false);- const id = crypto.randomUUID();- const run = async () => {- try {- // The card's id goes with the link: a retry from this card gets the- // job it already queued.- const imported = await importUrlToLibrary(- value,- residency,- (stage) => setStage(id, stage),- id,- );- if (folderId) {- for (const asset of imported) {- await moveLibraryItem(residency, asset.id, folderId).catch(- () => {},- );- asset.folderId = folderId;- }- }- patch((d) => ({ ...d, assets: [...imported, ...d.assets] }));- dropPending(id);- } catch (e) {- failPending(- id,- e instanceof Error ? e.message : "Could not import that URL.",- );- }- };- addPending({- id,- name: linkLabel(value),- folderId,- source: value,- stage: "queued",- startStage: "queued",- startedAt: Date.now(),- shape: estimatedShape(value),- run,- });- await run();+ await importLibraryLink(value, destination, client);};// ⌘V takes what a drop takes: files copied from the desktop upload into the@@ -881,7 +779,7 @@ export function LibraryView() {item={tile.pending}area={tile.pending.mediaType === "video" || tile.pending.mediaType === "image" ? TILE_AREA : audioArea}onRetry={() => retryPending(tile.pending)}- onDismiss={() => dropPending(tile.pending.id)}+ onDismiss={() => dismissLibraryImport(tile.pending.id)}opensOn="click"/>);diff --git a/site/src/cut/components/SidePanel.tsx b/site/src/cut/components/SidePanel.tsxindex 7c1bad8a..9d8fa0bd 100644--- a/site/src/cut/components/SidePanel.tsx+++ b/site/src/cut/components/SidePanel.tsx@@ -1,6 +1,6 @@"use client";-import { dismissLibraryImport, importLibraryFiles, useLibraryFileImports } from "@/cut/lib/libraryIntake";+import { dismissLibraryImport, importLibraryFiles, useLibraryImports } from "@/cut/lib/libraryIntake";import { LibraryImportCard } from "@/cut/components/LibraryImportCard";import { libraryFolderRef, projectFolderRef } from "@/cut/lib/folderReference";@@ -1688,7 +1688,7 @@ function LibraryPanel({ projectId, onImport }: {const [deleting, setDeleting] = useState<LibraryDeleteSet | null>(null);// The folder whose name field is open, when the right-click menu opened it.const [renamingFolder, setRenamingFolder] = useState<string | null>(null);- const arrivals = useLibraryFileImports((state) => state.items);+ const arrivals = useLibraryImports((state) => state.items);const pending = arrivals.filter((item) => item.folderId === openFolder);// Where an asset shows: phone recordings gather in the derived Camera Rolldiff --git a/site/src/cut/lib/library.ts b/site/src/cut/lib/library.tsindex 7fd11290..6b9f92f8 100644--- a/site/src/cut/lib/library.ts+++ b/site/src/cut/lib/library.ts@@ -395,6 +395,8 @@ export async function importUrlToLibrary(}}+const STAGED_GONE = 404;+/*** A link fetched by the cloud worker and landed on a shelf of this machine.*@@ -441,6 +443,9 @@ async function importUrlThroughCloud(const bytes = await cloudBackend.fetch(`/api/cut/library/media/${encodeURIComponent(staged.fileName)}`,);+ // A page resuming this key after its earlier run landed the media+ // finds the staged copy already dropped: the shelf holds it.+ if (bytes.status === STAGED_GONE && landed.length === 0) return [];if (!bytes.ok) throw new Error("Could not import that URL.");const form = new FormData();form.append("file", await bytes.blob(), staged.fileName);diff --git a/site/src/cut/lib/libraryIntake.test.ts b/site/src/cut/lib/libraryIntake.test.tsindex 80ebcafb..83a3abf3 100644--- a/site/src/cut/lib/libraryIntake.test.ts+++ b/site/src/cut/lib/libraryIntake.test.ts@@ -3,13 +3,14 @@ import { QueryClient } from "@tanstack/react-query";import * as library from "@/cut/lib/library";import * as linked from "@/cut/lib/linkedLibrary";import { libraryKey, libraryScope } from "@/cut/lib/queries";-import { importLibraryFiles, useLibraryFileImports } from "@/cut/lib/libraryIntake";+import * as cache from "@/cut/lib/cache";+import { importLibraryFiles, importLibraryLink, resumeLibraryLinks, useLibraryImports } from "@/cut/lib/libraryIntake";import type { Residency } from "@/cut/lib/residency";const restores: (() => void)[] = [];afterEach(() => {for (const restore of restores.splice(0)) restore();- useLibraryFileImports.setState({ items: [] });+ useLibraryImports.setState({ items: [] });});function setup() {@@ -37,12 +38,12 @@ describe("shared Library file intake", () => {...(linked.linkedTypeOfFile(lut) ? [lut] : []),];const done = importLibraryFiles(files, { residency, folderId: "folder" }, h.client);- expect(useLibraryFileImports.getState().items.map((item) => item.file)).toEqual(files);+ expect(useLibraryImports.getState().items.map((item) => item.file)).toEqual(files);expect(h.upload).not.toHaveBeenCalled();await done;expect(h.upload.mock.calls.map((call) => call[1])).toEqual(files.map(() => residency));expect(h.move.mock.calls.map((call) => call[2])).toEqual(files.map(() => "folder"));- expect(useLibraryFileImports.getState().items).toEqual([]);+ expect(useLibraryImports.getState().items).toEqual([]);const data = h.client.getQueryData<library.LibraryData>(libraryKey(libraryScope()))!;expect(data.assets).toHaveLength(files.length);expect(data.assets.every((asset) => asset.folderId === "folder")).toBe(true);@@ -54,12 +55,12 @@ describe("shared Library file intake", () => {let first = true;h.move.mockImplementation(async () => { if (first) { first = false; throw new Error("Folder write failed"); } });await importLibraryFiles([new File(["video"], "phone.mov")], { residency: "cloud", folderId: "folder" }, h.client);- const item = useLibraryFileImports.getState().items[0];+ const item = useLibraryImports.getState().items[0];expect(item.error).toBe("Folder write failed");await Promise.all([item.run(), item.run()]);expect(h.upload.mock.calls.length).toBe(1);expect(h.move.mock.calls.length).toBe(2);- expect(useLibraryFileImports.getState().items).toEqual([]);+ expect(useLibraryImports.getState().items).toEqual([]);});test("a failed file stays retryable while the rest of the drop lands", async () => {@@ -69,8 +70,8 @@ describe("shared Library file intake", () => {return { id: file.name, fileName: file.name, name: file.name, type: "video", duration: 1, addedAt: 0, residency: residency! };});await importLibraryFiles([new File(["a"], "a.mp4"), new File(["b"], "b.mp4")], { residency: "cloud", folderId: null }, h.client);- expect(useLibraryFileImports.getState().items.map((item) => item.name)).toEqual(["a.mp4"]);- expect(useLibraryFileImports.getState().items[0].error).toBe("Storage unavailable");+ expect(useLibraryImports.getState().items.map((item) => item.name)).toEqual(["a.mp4"]);+ expect(useLibraryImports.getState().items[0].error).toBe("Storage unavailable");expect(h.upload.mock.calls.length).toBe(2);});@@ -81,9 +82,53 @@ describe("shared Library file intake", () => {const expand = spyOn(linked, "expandLinkedFiles").mockImplementation(async ([file]) => file === archive ? [font] : [file]);restores.push(() => expand.mockRestore());const done = importLibraryFiles([archive], { residency: "browser", folderId: "fonts" }, h.client);- expect(useLibraryFileImports.getState().items[0].file).toBe(archive);+ expect(useLibraryImports.getState().items[0].file).toBe(archive);await done;expect(h.upload.mock.calls[0]?.[0]).toBe(font);expect(h.move.mock.calls[0]).toEqual(["browser", "face.ttf", "fonts"]);});});++describe("Library link intake", () => {+ test("a link import outlives the page that started it and picks up its own job", async () => {+ const h = setup();+ const saved = new Map<string, unknown>();+ const write = spyOn(cache, "writeSnapshot").mockImplementation((key, value) => void saved.set(key, value));+ const read = spyOn(cache, "readSnapshot").mockImplementation(async (key) => saved.has(key) ? { value: saved.get(key) as never, at: Date.now() } : null);+ const keys: (string | undefined)[] = [];+ let land: ((assets: library.LibraryAsset[]) => void) | undefined;+ const fetchLink = spyOn(library, "importUrlToLibrary").mockImplementation((_url, _r, _stage, key) => {+ keys.push(key);+ return new Promise((resolve) => { land = resolve; });+ });+ restores.push(() => { write.mockRestore(); read.mockRestore(); fetchLink.mockRestore(); });++ void importLibraryLink("https://www.youtube.com/watch?v=abc", { residency: "cloud", folderId: null }, h.client);+ const id = useLibraryImports.getState().items[0].id;+ await new Promise((r) => setTimeout(r, 0));++ // The page reloads: the tile is gone from memory, the job is still running.+ useLibraryImports.setState({ items: [] });+ await resumeLibraryLinks(h.client);+ expect(useLibraryImports.getState().items.map((item) => item.id)).toEqual([id]);+ await new Promise((r) => setTimeout(r, 0));+ expect(keys).toEqual([id, id]);++ land!([{ id: "yt", fileName: "yt.mp4", name: "Video", type: "video", duration: 1, addedAt: 0, residency: "cloud" }]);+ await new Promise((r) => setTimeout(r, 0));+ expect(useLibraryImports.getState().items).toEqual([]);+ expect(h.client.getQueryData<library.LibraryData>(libraryKey(libraryScope()))!.assets.map((a) => a.id)).toEqual(["yt"]);+ await resumeLibraryLinks(h.client);+ expect(keys).toEqual([id, id]);+ });++ test("a landed link the listing already shows is not listed twice", async () => {+ const h = setup();+ const asset: library.LibraryAsset = { id: "yt", fileName: "yt.mp4", name: "Video", type: "video", duration: 1, addedAt: 0, residency: "cloud" };+ h.client.setQueryData(libraryKey(libraryScope()), { assets: [asset], folders: [], templates: [] });+ const fetchLink = spyOn(library, "importUrlToLibrary").mockResolvedValue([asset]);+ restores.push(() => fetchLink.mockRestore());+ await importLibraryLink("https://www.youtube.com/watch?v=abc", { residency: "cloud", folderId: null }, h.client);+ expect(h.client.getQueryData<library.LibraryData>(libraryKey(libraryScope()))!.assets).toHaveLength(1);+ });+});diff --git a/site/src/cut/lib/libraryIntake.ts b/site/src/cut/lib/libraryIntake.tsindex 214e6830..d2f30573 100644--- a/site/src/cut/lib/libraryIntake.ts+++ b/site/src/cut/lib/libraryIntake.ts@@ -6,7 +6,8 @@ import { currentEngineUser, subscribeEngineUser } from "@/cut/lib/api";import { assetTypeOf, isMediaFile } from "@/cut/lib/media";import { isFontArchive } from "@/cut/lib/fontArchive";import { expandLinkedFiles, isLinkedFile, isLinkedType, linkedTypeOfFile, shelfForNewItem, syncLinkedLibrary } from "@/cut/lib/linkedLibrary";-import { moveLibraryItem, uploadToLibrary, type ImportStage, type LibraryAsset } from "@/cut/lib/library";+import { readSnapshot, snapshotKey, writeSnapshot } from "@/cut/lib/cache";+import { estimatedShape, importUrlToLibrary, moveLibraryItem, uploadToLibrary, type ImportStage, type LibraryAsset } from "@/cut/lib/library";import type { LibraryUploadState } from "@/cut/lib/libraryUpload";import { libraryKey, libraryScope, patchLibrary, refetchLibrary } from "@/cut/lib/queries";import type { Residency } from "@/cut/lib/residency";@@ -27,16 +28,19 @@ export type LibraryArrival = {run: () => Promise<void>;};-export const useLibraryFileImports = create<{ items: LibraryArrival[] }>(() => ({ items: [] }));+export const useLibraryImports = create<{ items: LibraryArrival[] }>(() => ({ items: [] }));const update = (fn: (items: LibraryArrival[]) => LibraryArrival[]) =>- useLibraryFileImports.setState((state) => ({ items: fn(state.items) }));-export const dismissLibraryImport = (id: string) => update((items) => items.filter((item) => item.id !== id));+ useLibraryImports.setState((state) => ({ items: fn(state.items) }));+export const dismissLibraryImport = (id: string) => {+ update((items) => items.filter((item) => item.id !== id));+ void editLinks(currentEngineUser(), (links) => links.filter((link) => link.id !== id));+};/** The arriving picture's measured size, so its tile takes the shape the asset will. */export const setLibraryImportShape = (id: string, shape: { width: number; height: number }) =>update((items) => items.map((item) => item.id === id ? { ...item, shape } : item));// Navigation changes the view of these jobs; the files and retries belong to the account.-subscribeEngineUser(() => useLibraryFileImports.setState({ items: [] }));+subscribeEngineUser(() => useLibraryImports.setState({ items: [] }));let tail = Promise.resolve();const accepts = (file: File) => isMediaFile(file) || isLinkedFile(file);@@ -47,7 +51,7 @@ export function importLibraryFiles(client: QueryClient,): Promise<void> {const owner = currentEngineUser();- const wanted = (id: string) => currentEngineUser() === owner && useLibraryFileImports.getState().items.some((item) => item.id === id);+ const wanted = (id: string) => currentEngineUser() === owner && useLibraryImports.getState().items.some((item) => item.id === id);const prepare = (file: File): LibraryArrival => {const id = crypto.randomUUID();const state: LibraryUploadState = {};@@ -102,3 +106,139 @@ export function importLibraryFiles(tail = tail.then(async () => { for (const item of batch) await item.run(); });return tail;}++/** A link import as it is kept across reloads: enough to ask its shelf for the+ * same work again. It is stored while the work runs and dropped when it ends. */+type SavedLink = { id: string; url: string; residency: Residency; folderId: string | null; startedAt: number };++/** How long a saved link is worth resuming. An import still unsettled after+ * this has landed or failed on its own, and the listing shows which. */+const LINK_RESUME_MS = 30 * 60 * 1000;+const LINKS_SNAPSHOT = "library-links";++// Each account's saved links, read from disk once and edited in order after.+const savedLinks = new Map<string, Promise<SavedLink[]>>();+const linksOf = (owner: string | null) => {+ const key = snapshotKey("all", LINKS_SNAPSHOT);+ let links = savedLinks.get(key);+ if (!links) {+ links = readSnapshot<SavedLink[]>(key).then((hit) => hit?.value ?? []);+ savedLinks.set(key, links);+ }+ return owner === currentEngineUser() ? links : Promise.resolve(null);+};+let linkEdits = Promise.resolve();+function editLinks(owner: string | null, fn: (links: SavedLink[]) => SavedLink[]): Promise<void> {+ linkEdits = linkEdits.then(async () => {+ const links = await linksOf(owner);+ if (!links || owner !== currentEngineUser()) {+ return;+ }+ const next = fn(links);+ links.splice(0, links.length, ...next);+ writeSnapshot(snapshotKey("all", LINKS_SNAPSHOT), next);+ });+ return linkEdits;+}++/** Routing words a path spends on the way to the thing: they say nothing about+ * which post this is, so a label built from one ("youtube.com/watch") reads the+ * same for every import from that site. */+const ROUTE_SEGMENT = new Set(["watch", "video", "videos", "embed", "v", "e", "p", "post", "posts", "status", "share", "media", "download"]);++/** A link's name on its tile: the site it points at and the token that+ * identifies the post — the last telling path segment, or the id a watch URL+ * carries in its query — so two imports from one site read apart. */+function linkLabel(url: string): string {+ try {+ const u = new URL(url);+ const host = u.hostname.replace(/^www\./, "");+ const id = u.pathname.split("/").filter(Boolean).reverse().find((seg) => !ROUTE_SEGMENT.has(seg.toLowerCase())) ?? u.searchParams.get("v");+ return id ? `${host}/${id}` : host;+ } catch {+ return url;+ }+}++/** The tile for one link and the work behind it. The tile's id is the+ * import's key, so running it again — a retry, or a reload resuming it — gets+ * the job the shelf already has for it and the link lands once. */+function linkArrival(saved: SavedLink, client: QueryClient): LibraryArrival {+ const owner = currentEngineUser();+ const { id, url, residency, folderId } = saved;+ let link = saved;+ const wanted = () => currentEngineUser() === owner && useLibraryImports.getState().items.some((item) => item.id === id);+ let running: Promise<void> | undefined;+ const work = async () => {+ // A retry restarts the clock on the tile and on the saved link.+ if (useLibraryImports.getState().items.find((item) => item.id === id)?.error) {+ link = { ...link, startedAt: Date.now() };+ update((items) => items.map((item) => item.id === id ? { ...item, error: undefined, stage: item.startStage, startedAt: link.startedAt } : item));+ }+ await editLinks(owner, (links) => [...links.filter((l) => l.id !== id), link]);+ try {+ const imported = await importUrlToLibrary(url, residency, (stage) => {+ if (wanted()) update((items) => items.map((item) => item.id === id ? { ...item, stage } : item));+ }, id);+ if (folderId) {+ for (const asset of imported) {+ await moveLibraryItem(residency, asset.id, folderId).catch(() => {});+ asset.folderId = folderId;+ }+ }++ // The listing may have read the asset already: it replaces that copy.+ if (currentEngineUser() === owner) {+ const ids = new Set(imported.map((asset) => asset.id));+ patchLibrary(client, (data) => ({ ...data, assets: [...imported, ...data.assets.filter((asset) => !ids.has(asset.id))] }));+ }+ dismissLibraryImport(id);+ } catch (error) {+ if (wanted()) update((items) => items.map((item) => item.id === id ? { ...item, error: error instanceof Error ? error.message : "Could not import that URL." } : item));+ await editLinks(owner, (links) => links.filter((l) => l.id !== id));+ }+ };+ return {+ id, name: linkLabel(url), folderId, residency, source: url,+ stage: "queued", startStage: "queued", startedAt: saved.startedAt,+ shape: estimatedShape(url),+ run: () => running ??= work().finally(() => { running = undefined; }),+ };+}++/** Import a link into a shelf: its tile goes up at once and stays until the+ * asset takes its place, across reloads. */+export function importLibraryLink(+ url: string,+ target: { residency: Residency; folderId: string | null },+ client: QueryClient,+): Promise<void> {+ const item = linkArrival({ id: crypto.randomUUID(), url, ...target, startedAt: Date.now() }, client);+ update((items) => [...items, item]);+ return item.run();+}++/** Put back the tiles of link imports a reload cut off and pick their work up+ * again. Only publishes them; each one's work runs on. */+export async function resumeLibraryLinks(client: QueryClient): Promise<void> {+ const owner = currentEngineUser();+ const links = await linksOf(owner);+ if (!links) {+ return;+ }++ // Links past the resume window are dropped; the listing shows how they ended.+ const fresh = links.filter((link) => Date.now() - link.startedAt < LINK_RESUME_MS);+ if (fresh.length < links.length) {+ void editLinks(owner, (all) => all.filter((link) => fresh.includes(link)));+ }+ const shown = new Set(useLibraryImports.getState().items.map((item) => item.id));+ const back = fresh.filter((link) => !shown.has(link.id)).map((link) => linkArrival(link, client));+ if (back.length === 0) {+ return;+ }+ update((items) => [...items, ...back]);+ for (const item of back) {+ void item.run();+ }+}diff --git a/site/src/cut/server/http/library.ts b/site/src/cut/server/http/library.tsindex 9420a06a..503d865b 100644--- a/site/src/cut/server/http/library.ts+++ b/site/src/cut/server/http/library.ts@@ -19,6 +19,7 @@ import {saveTemplate,copyLibraryAssetToProject,copyTemplateToProject,+ type LibraryAsset,type LibrarySource,type LinkedMeta,type TemplateInput,@@ -32,6 +33,32 @@ const err = (message: string, status: number) =>const caught = (e: unknown, fallback: string) =>err(errorMessage(e, fallback), 500);+/** Link imports by the key the page sent with them. A page that reloads+ * mid-import asks again under the same key and waits on the download already+ * running; one that asks after it landed gets the same assets back. A failure+ * is forgotten so a retry runs again. Landed keys are held as long as the+ * page resumes an import. */+const importsByKey = new Map<string, Promise<LibraryAsset[]>>();+const IMPORT_KEY_HOLD_MS = 30 * 60 * 1000;+const IMPORT_KEY = /^[A-Za-z0-9_-]{1,128}$/;++function importOnce(key: string | undefined, run: () => Promise<LibraryAsset[]>): Promise<LibraryAsset[]> {+ if (!key || !IMPORT_KEY.test(key)) {+ return run();+ }+ const running = importsByKey.get(key);+ if (running) {+ return running;+ }+ const started = run();+ importsByKey.set(key, started);+ started.then(+ () => setTimeout(() => importsByKey.delete(key), IMPORT_KEY_HOLD_MS).unref?.(),+ () => importsByKey.delete(key),+ );+ return started;+}+/** The shared library: reusable media outside any project. */export const libraryApi = {async list() {@@ -139,9 +166,9 @@ export const libraryApi = {/** Download a media URL straight into the library. */async importUrl(req: Request) {try {- const { url, audio } = (await req.json()) as { url?: string; audio?: boolean };+ const { url, audio, key } = (await req.json()) as { url?: string; audio?: boolean; key?: string };if (!url) return err("No URL provided.", 400);- return Response.json(await importFromUrl(url, { audio: audio === true }));+ return Response.json(await importOnce(key, () => importFromUrl(url, { audio: audio === true })));} catch (e) {return caught(e, "Could not import that URL.");}diff --git a/site/src/cut/server/http/libraryImportKey.test.ts b/site/src/cut/server/http/libraryImportKey.test.tsnew file mode 100644index 00000000..dcb37c03--- /dev/null+++ b/site/src/cut/server/http/libraryImportKey.test.ts@@ -0,0 +1,37 @@+import { afterEach, expect, spyOn, test } from "bun:test";+import * as urlImport from "../urlImport";+import { libraryApi } from "./library";++const restores: (() => void)[] = [];+afterEach(() => {+ for (const restore of restores.splice(0)) restore();+});++const post = (key: string) =>+ libraryApi.importUrl(new Request("http://engine/api/cut/library/import-url", {+ method: "POST",+ body: JSON.stringify({ url: "https://www.youtube.com/watch?v=abc", key }),+ }));++test("a link asked for again under its key waits on the download already running", async () => {+ let land: ((assets: Awaited<ReturnType<typeof urlImport.importFromUrl>>) => void) | undefined;+ const fetchLink = spyOn(urlImport, "importFromUrl").mockImplementation(() => new Promise((resolve) => { land = resolve; }));+ restores.push(() => fetchLink.mockRestore());+ const key = crypto.randomUUID();+ const first = post(key);+ const again = post(key);+ await new Promise((r) => setTimeout(r, 0));+ land!([{ id: "yt", fileName: "yt.mp4", name: "Video", type: "video", duration: 1, addedAt: 0 } as never]);+ expect(await (await first).json()).toEqual(await (await again).json());+ expect(((await (await post(key)).json()) as { id: string }[]).map((a) => a.id)).toEqual(["yt"]);+ expect(fetchLink.mock.calls.length).toBe(1);+});++test("a failed link runs again under the same key", async () => {+ const fetchLink = spyOn(urlImport, "importFromUrl").mockImplementation(async () => { throw new Error("Site refused"); });+ restores.push(() => fetchLink.mockRestore());+ const key = crypto.randomUUID();+ expect((await post(key)).ok).toBe(false);+ expect((await post(key)).ok).toBe(false);+ expect(fetchLink.mock.calls.length).toBe(2);+});