The open source AI video agent: turns any coding agent into a video agent, with an editor to change anything it makes.
Projects: one click on "New project" opens the project; going back to Projects never spins for ever (#129)
riverisbuilding008edef0ebd9
diff --git a/.changeset/new-project-one-click.md b/.changeset/new-project-one-click.mdnew file mode 100644index 0000000..05eb551--- /dev/null+++ b/.changeset/new-project-one-click.md@@ -0,0 +1,6 @@+---+"openfilm": patch+"@openfilm/desktop": patch+---++Projects: one click on "New project" makes the project and opens it, named Untitled (Untitled 2…); rename it later. Going back to Projects no longer spins forever: a card whose picture is still being drawn shows its color and asks again, instead of holding Studio's connections while the next page waits, and a list that can't be read says so, with Try again.diff --git a/packages/openfilm/studio/server/pageframes.mjs b/packages/openfilm/studio/server/pageframes.mjsindex 003151f..9db15cf 100644--- a/packages/openfilm/studio/server/pageframes.mjs+++ b/packages/openfilm/studio/server/pageframes.mjs@@ -151,6 +151,9 @@ const FILM_POSTER = 'film-poster.jpg';/** How long a card waits for the film's current poster before it is given the last one: one drawn already is read* from the cache in far less, and drawing one takes seconds. */const STALE_AFTER_MS = 300;+/** How long a card waits for a film's first poster (none drawn before) before it is told to ask again: the card's+ * request holds one of the few connections a browser opens to Studio, and the editor's own requests wait behind it. */+const FIRST_WAIT_MS = 2_000;/** How long after a project opens its first poster is drawn: after the editor's own first thumbnails. */const WARM_MS = 10_000;/** @type {Map<string, NodeJS.Timeout>} projects whose first poster is about to be drawn */@@ -161,21 +164,31 @@ const warming = new Map();* in the projects list. Drawing it takes seconds (the whole film opens, every page in it, one frame at a time behind* the open project's own thumbnails), and any change to film.html makes a new one, so a card waiting for it showed* nothing. The current poster comes when it is drawn already; else the last one comes at once while the current one- * is drawn for next time; a film never drawn is waited for.- * @param {string} root @param {string} base+ * is drawn for next time; a film never drawn is waited for a moment (FIRST_WAIT_MS), then null: it is still being+ * drawn, ask again.+ * @param {string} root @param {string} base @returns {Promise<Buffer | null>}*/export async function filmPoster(root, base) {const fresh = pageFrame(root, base, FILM_PAGE, -1, POSTER_W);+ /* drawn for next time, whoever waits for it: a film that can't be drawn now (a page's library offline) still shows+ its last picture */+ fresh.catch(() => {});+ const soon = await within(fresh.catch(() => null), STALE_AFTER_MS);+ if (soon) return soon;+ const last = await readFile(join(root, TOOL_DIR, 'cache', FILM_POSTER)).catch(() => null);+ if (last) return last;+ return within(fresh, FIRST_WAIT_MS - STALE_AFTER_MS);+}++/** What `promise` gives within `ms`, else null (it goes on). @template T @param {Promise<T>} promise @param {number} ms */+async function within(promise, ms) {/** @type {NodeJS.Timeout | undefined} */let timer;- const soon = await Promise.race([fresh.catch(() => null), new Promise((done) => { timer = setTimeout(() => done(null), STALE_AFTER_MS); })]);- clearTimeout(timer);- if (soon) return /** @type {Buffer} */ (soon);- const last = await readFile(join(root, TOOL_DIR, 'cache', FILM_POSTER)).catch(() => null);- if (!last) return fresh;- /* drawn for next time: a film that can't be drawn now (a page's library offline) still shows its last picture */- fresh.catch(() => {});- return last;+ try {+ return await Promise.race([promise, new Promise((/** @type {(value: null) => void} */ done) => { timer = setTimeout(() => done(null), ms); })]);+ } finally {+ clearTimeout(timer);+ }}/**diff --git a/packages/openfilm/studio/server/pageframes.test.mjs b/packages/openfilm/studio/server/pageframes.test.mjsindex 32d25b6..f0fde23 100644--- a/packages/openfilm/studio/server/pageframes.test.mjs+++ b/packages/openfilm/studio/server/pageframes.test.mjs@@ -28,6 +28,17 @@ const posterOf = async (id) => {assert.equal(res.status, 200);return Buffer.from(await res.arrayBuffer());};+/* a film's first poster, asked for again while it is being drawn (503), as a card does */+const firstPosterOf = async (id) => {+ for (const end = Date.now() + 60_000; Date.now() < end; await new Promise((r) => setTimeout(r, 250))) {+ const res = await api(`/api/projects/${id}/poster`);+ if (res.status !== 503) {+ assert.equal(res.status, 200);+ return Buffer.from(await res.arrayBuffer());+ }+ }+ assert.fail('never drawn');+};test('a project\'s card: its film\'s poster; once the film changes, the last one at once while the new one is drawn', async () => {const { project } = await (await api('/api/projects', { method: 'POST', body: { path: join(scratch, 'Card') } })).json();@@ -37,8 +48,8 @@ test('a project\'s card: its film\'s poster; once the film changes, the last one</script></body>`);page('#f00');writeFileSync(join(project.path, 'film.html'), filmHtml({ tracks: [{ clips: [{ src: 'p.html' }] }] }));- /* never drawn: waited for */- const red = await posterOf(project.id);+ /* never drawn: drawn, asked for again meanwhile */+ const red = await firstPosterOf(project.id);assert.deepEqual([...red.subarray(0, 2)], [0xff, 0xd8]);assert.ok(existsSync(join(project.path, '.film', 'cache', 'film-poster.jpg')), 'kept as the film\'s last poster');@@ -57,6 +68,22 @@ test('a project\'s card: its film\'s poster; once the film changes, the last oneassert.ok(!fresh.equals(red), 'the changed film\'s poster, next time');});+test('a card waits a moment only for a film\'s first poster: drawn on, it is asked for again (the request held no connection)', async () => {+ const { project } = await (await api('/api/projects', { method: 'POST', body: { path: join(scratch, 'Slow') } })).json();+ writeFileSync(join(project.path, 'p.html'), `<!doctype html><body style="margin:0;background:#0a0"><script>+ window.film = { duration: 2, ready: new Promise((r) => setTimeout(r, 6000)), frame() {} };+ </script></body>`);+ writeFileSync(join(project.path, 'film.html'), filmHtml({ tracks: [{ clips: [{ src: 'p.html' }] }] }));+ const t0 = Date.now();+ const res = await api(`/api/projects/${project.id}/poster`);+ assert.equal(res.status, 503);+ assert.equal(res.headers.get('retry-after'), '5');+ assert.equal((await res.json()).code, 'drawing');+ assert.ok(Date.now() - t0 < 4000, 'answered within moments');+ const poster = await firstPosterOf(project.id);+ assert.deepEqual([...poster.subarray(0, 2)], [0xff, 0xd8]);+});+test('a film that has nothing in it has no poster', async () => {const { project } = await (await api('/api/projects', { method: 'POST', body: { path: join(scratch, 'Empty') } })).json();writeFileSync(join(project.path, 'film.html'), filmHtml({ tracks: [{ clips: [] }] }));@@ -142,7 +169,7 @@ test('a film whose footage no browser decodes (ProRes) has its picture on its caconst { project } = await (await api('/api/projects', { method: 'POST', body: { path: join(scratch, 'ProRes') } })).json();execFileSync('ffmpeg', ['-v', 'error', '-y', '-f', 'lavfi', '-i', 'color=c=0x2060c0:size=320x180:rate=30', '-t', '2', '-c:v', 'prores_ks', '-profile:v', '3', join(project.path, 'a.mov')]);writeFileSync(join(project.path, 'film.html'), filmHtml({ stage: { w: 320, h: 180 }, tracks: [{ clips: [{ id: 'v', src: 'a.mov', at: 0, time: [0, 2] }] }] }));- const jpeg = await posterOf(project.id);+ const jpeg = await firstPosterOf(project.id);const [r, g, b] = execFileSync('ffmpeg', ['-v', 'error', '-f', 'image2pipe', '-i', '-', '-frames:v', '1', '-vf', 'crop=4:4:iw/2:ih/2,format=rgb24', '-f', 'rawvideo', '-'], { input: jpeg });assert.ok(Math.abs(r - 0x20) < 20 && Math.abs(g - 0x60) < 20 && Math.abs(b - 0xc0) < 20, `the footage's colour: ${r},${g},${b}`);});diff --git a/packages/openfilm/studio/server/server.mjs b/packages/openfilm/studio/server/server.mjsindex f466e8b..89e4c2a 100644--- a/packages/openfilm/studio/server/server.mjs+++ b/packages/openfilm/studio/server/server.mjs@@ -886,6 +886,11 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowseconst jpeg = await filmPoster(project.path, pages.folderUrl(project)).catch((e) => {throw new HttpError(e instanceof PageFrameError ? 404 : 422, String(e?.message ?? e));});+ /* its first one is still being drawn: the card asks again in a while, rather than hold a connection meanwhile */+ if (!jpeg) {+ res.writeHead(503, { 'retry-after': '5', 'cache-control': 'no-store', 'content-type': 'application/json' });+ return res.end(JSON.stringify({ error: 'the film\'s poster is being drawn; ask again in a few seconds', code: 'drawing' }));+ }res.writeHead(200, { 'content-type': 'image/jpeg', 'cache-control': 'private, max-age=60', 'content-length': jpeg.length });return res.end(jpeg);}diff --git a/packages/openfilm/studio/ui/src/App.tsx b/packages/openfilm/studio/ui/src/App.tsxindex 0a1c8ab..bb1e431 100644--- a/packages/openfilm/studio/ui/src/App.tsx+++ b/packages/openfilm/studio/ui/src/App.tsx@@ -18,6 +18,7 @@ import { Launcher } from './components/Launcher';import { studioHost } from './lib/host';import { WhatsNew } from './components/WhatsNew';import { sourcesApi } from './lib/project-sources';+import { LIST_WAIT_MS, within } from './lib/projects-page';/*** `to` with this page's key in its address (the server puts it there): the address bar is what a person copies, and@@ -68,12 +69,13 @@ export function App() {useEffect(() => {if (id || tabs) return;let alive = true;- void api.projects().then((projects) => {+ /* the list not read (refused, or no answer in time): the Projects window, which says so and tries again */+ void within(api.projects(), LIST_WAIT_MS).then((projects) => {if (!alive) return;const last = projects.find((p) => !p.missing);if (last) go(`/projects/${last.id}`, true);else setNone(true);- });+ }, () => { if (alive) setNone(true); });return () => { alive = false; setNone(false); };}, [id]);diff --git a/packages/openfilm/studio/ui/src/components/ProjectsLibrary.tsx b/packages/openfilm/studio/ui/src/components/ProjectsLibrary.tsxindex c11da29..435b7da 100644--- a/packages/openfilm/studio/ui/src/components/ProjectsLibrary.tsx+++ b/packages/openfilm/studio/ui/src/components/ProjectsLibrary.tsx@@ -23,6 +23,7 @@ import { useT } from '@/i18n';import { folderApi, folderCounts, folderTrail, type ProjectFolder } from '@/lib/project-folders';import { studioHost } from '@/lib/host';import { SourceError, sourcesApi } from '@/lib/project-sources';+import { LIST_WAIT_MS, within } from '@/lib/projects-page';import { ConfirmDialog } from './ConfirmDialog';import { ProjectsView, type LibraryProject } from './ProjectsView';import { FolderBrowserDialog, GitHubDialog } from './ProjectSources';@@ -39,6 +40,9 @@ function useProjectLibrary(open: boolean) {const [projects, setProjects] = React.useState<LibraryProject[]>([]);const [folders, setFolders] = React.useState<ProjectFolder[]>([]);const [loaded, setLoaded] = React.useState(false);+ /** the list could not be read (Studio refused, or did not answer in time): said, with a way to try again */+ const [loadFailed, setLoadFailed] = React.useState(false);+ const [tries, setTries] = React.useState(0);const [error, setError] = React.useState<string | null>(null);const errorTimer = React.useRef<ReturnType<typeof setTimeout> | null>(null);React.useEffect(() => () => { if (errorTimer.current) clearTimeout(errorTimer.current); }, []);@@ -49,19 +53,24 @@ function useProjectLibrary(open: boolean) {errorTimer.current = setTimeout(() => setError(null), 4000);}, []);- /* fetched fresh on every open: the agent or another window may have made or removed one meanwhile */+ /* fetched fresh on every open: the agent or another window may have made or removed one meanwhile. Waited for a+ while only: a list that never comes is said, not shown as a spinner for ever (one shown already stays) */React.useEffect(() => {if (!open) return undefined;let alive = true;- void Promise.all([- api.projects().then(- (list) => { if (alive) setProjects(list.map((p) => ({ ...p, poster: posterOf(p) }))); },- () => {},- ),- folderApi.list().then((list) => { if (alive) setFolders(list); }, () => {}),- ]).then(() => { if (alive) setLoaded(true); });+ setLoadFailed(false);+ Promise.all([within(api.projects(), LIST_WAIT_MS), within(folderApi.list(), LIST_WAIT_MS)]).then(+ ([list, folderList]) => {+ if (!alive) return;+ setProjects(list.map((p) => ({ ...p, poster: posterOf(p) })));+ setFolders(folderList);+ setLoaded(true);+ },+ () => { if (alive) setLoadFailed(true); },+ );return () => { alive = false; };- }, [open]);+ }, [open, tries]);+ const retryLoad = React.useCallback(() => setTries((n) => n + 1), []);const reloadFolders = React.useCallback(() => {void folderApi.list().then(setFolders, () => {});@@ -179,7 +188,7 @@ function useProjectLibrary(open: boolean) {}}- return { projects, folders, loaded, error, flash, reload: reloadFolders, agentRunning, workingIn, deleteProjects, renameProject, createFolder, renameFolder, moveProject, deleteFolder, coverChanged };+ return { projects, folders, loaded, loadFailed, retryLoad, error, flash, reload: reloadFolders, agentRunning, workingIn, deleteProjects, renameProject, createFolder, renameFolder, moveProject, deleteFolder, coverChanged };}/** The launcher's two views: the person's projects, and the examples to start from (ExamplesGallery). */@@ -255,6 +264,7 @@ export function ProjectsPopover({if (wasOpen.current) latestClose.current();}, [currentProjectId]);+ /** A new project, named as Studio names it (Untitled, Untitled 2…), opened at once: it is renamed later. */async function newProject() {setBusy('creating');try {@@ -409,6 +419,17 @@ export function ProjectsPopover({onClose={onClose}/></ProjectCoverContext.Provider>+ ) : lib.loadFailed ? (+ <div role="alert" className="flex flex-1 flex-col items-center justify-center gap-3 text-[13px] text-[var(--text-muted)]">+ {t('projects.loadFailed')}+ <button+ type="button"+ onClick={lib.retryLoad}+ className="h-8 rounded-lg bg-[var(--surface-2)] px-3 text-[12.5px] font-medium text-[var(--text)] transition hover:bg-[var(--bg-hover)]"+ >+ {t('projects.loadRetry')}+ </button>+ </div>) : (<div className="flex flex-1 items-center justify-center text-[var(--text-muted)]"><Loader2 size={18} className="animate-spin" />diff --git a/packages/openfilm/studio/ui/src/components/ProjectsView.tsx b/packages/openfilm/studio/ui/src/components/ProjectsView.tsxindex 40e0350..91f04f9 100644--- a/packages/openfilm/studio/ui/src/components/ProjectsView.tsx+++ b/packages/openfilm/studio/ui/src/components/ProjectsView.tsx@@ -33,6 +33,7 @@ import { useLanguage, useT, type Language } from '@/i18n';import { limitTitleWidth, TITLE_MAX_WIDTH } from '@/lib/title';import { api, type Project } from '@/api';import { folderCounts, folderPosters, folderTrail, parentOf, visibleProjects, type LibrarySort, type ProjectFolder } from '@/lib/project-folders';+import { posterRetryDelay, posterTry } from '@/lib/projects-page';import { ContextMenu } from './ContextMenu';import { ProjectMenu } from './ProjectMenu';import { ProjectCoverContext } from './ProjectCover';@@ -71,6 +72,7 @@ export function ProjectsView({projects: LibraryProject[];/** A project is being created or opened; "New project" does not take a second click meanwhile. */creating?: boolean;+ /** "New project": made at once, named as Studio names it (Untitled, Untitled 2…), and opened. */onNewProject: () => void;/** "Open folder…": a folder anywhere, opened as a project (the app's own dialog, else Studio's folder browser). */onOpenFolder: () => void;@@ -1357,32 +1359,42 @@ function FolderPicker({/*** The cover, or (none, or it failed to load) a gradient made from the id. While Studio draws it (the first time can- * take a while) the card shows its plain face with the film mark, not a black frame that reads as a black film.+ * take a while) the card shows its plain face with the film mark, not a black frame that reads as a black film. Studio+ * answers at once while it draws a film's first poster (so the card holds none of the browser's few connections to+ * it): the card shows its gradient and asks again a few times.*/function PosterMedia({ project, shade = false }: { project: LibraryProject; shade?: boolean }) {- const [failedUrl, setFailedUrl] = React.useState<string | null>(null);+ /* the try asked for now (0: the first) and whether it failed, for this poster */+ const [attempt, setAttempt] = React.useState<{ url: string; n: number; failed: boolean } | null>(null);const [loadedUrl, setLoadedUrl] = React.useState<string | null>(null);+ const tried = attempt && attempt.url === project.poster ? attempt : { url: project.poster ?? '', n: 0, failed: false };+ const again = tried.failed ? posterRetryDelay(tried.n) : null;+ React.useEffect(() => {+ if (again == null) return undefined;+ const timer = setTimeout(() => setAttempt({ url: tried.url, n: tried.n + 1, failed: false }), again);+ return () => clearTimeout(timer);+ }, [again, tried.url, tried.n]);/* `shade`: darker toward the bottom, under the length badge; only over a picture (on the plain face it is a smudge) */const shadow = shade ? <div className="absolute inset-0 bg-gradient-to-t from-black/55 via-transparent to-transparent opacity-90" /> : null;- if (!project.poster || failedUrl === project.poster) {- return <><div className="absolute inset-0 opacity-80" style={{ background: gradientForId(project.id) }} />{shadow}</>;- }- const ready = loadedUrl === project.poster;+ const face = <div className="absolute inset-0 opacity-80" style={{ background: gradientForId(project.id) }} />;+ if (!project.poster || (tried.failed && again == null)) return <>{face}{shadow}</>;+ const src = posterTry(project.poster, tried.n);+ const ready = loadedUrl === src;return (<>- {ready ? null : (+ {ready ? null : tried.n > 0 || tried.failed ? face : (<span aria-hidden className="absolute inset-0 flex items-center justify-center text-[var(--text-faint)]"><Video size={22} strokeWidth={1.5} /></span>)}<img- src={project.poster}+ src={src}alt=""loading="lazy"decoding="async"draggable={false}- onLoad={() => setLoadedUrl(project.poster ?? null)}- onError={() => setFailedUrl(project.poster ?? null)}+ onLoad={() => setLoadedUrl(src)}+ onError={() => setAttempt({ url: tried.url, n: tried.n, failed: true })}className={`absolute inset-0 h-full w-full object-cover transition-opacity duration-200 ${ready ? 'opacity-100' : 'opacity-0'}`}/>{ready ? shadow : null}diff --git a/packages/openfilm/studio/ui/src/i18n/en.ts b/packages/openfilm/studio/ui/src/i18n/en.tsindex 74da364..e99c585 100644--- a/packages/openfilm/studio/ui/src/i18n/en.ts+++ b/packages/openfilm/studio/ui/src/i18n/en.ts@@ -143,6 +143,8 @@ export const en = {projects: {newProject: 'New project',localProjectFailed: 'Couldn’t create the project. Please retry.',+ loadFailed: 'Couldn’t load your projects.',+ loadRetry: 'Try again',revealFolder: `Reveal in ${FILES}`,folderAll: 'All',folderUp: 'Up one level',diff --git a/packages/openfilm/studio/ui/src/i18n/es.ts b/packages/openfilm/studio/ui/src/i18n/es.tsindex 126b958..db37ec2 100644--- a/packages/openfilm/studio/ui/src/i18n/es.ts+++ b/packages/openfilm/studio/ui/src/i18n/es.ts@@ -142,6 +142,8 @@ export const es: Words = {projects: {newProject: 'Nuevo proyecto',localProjectFailed: 'No se pudo crear el proyecto. Inténtalo de nuevo.',+ loadFailed: 'No se pudieron cargar tus proyectos.',+ loadRetry: 'Reintentar',revealFolder: `Mostrar en ${FILES}`,folderAll: 'Todos',folderUp: 'Subir un nivel',diff --git a/packages/openfilm/studio/ui/src/i18n/ja.ts b/packages/openfilm/studio/ui/src/i18n/ja.tsindex 2213663..f73ef45 100644--- a/packages/openfilm/studio/ui/src/i18n/ja.ts+++ b/packages/openfilm/studio/ui/src/i18n/ja.ts@@ -142,6 +142,8 @@ export const ja: Words = {projects: {newProject: '新規プロジェクト',localProjectFailed: 'プロジェクトを作成できませんでした。もう一度お試しください。',+ loadFailed: 'プロジェクトを読み込めませんでした。',+ loadRetry: '再試行',revealFolder: `${FILES}で表示`,folderAll: 'すべて',folderUp: '1 つ上へ',diff --git a/packages/openfilm/studio/ui/src/i18n/ko.ts b/packages/openfilm/studio/ui/src/i18n/ko.tsindex 9642f14..a085259 100644--- a/packages/openfilm/studio/ui/src/i18n/ko.ts+++ b/packages/openfilm/studio/ui/src/i18n/ko.ts@@ -142,6 +142,8 @@ export const ko: Words = {projects: {newProject: '새 프로젝트',localProjectFailed: '프로젝트를 만들지 못했습니다. 다시 시도하세요.',+ loadFailed: '프로젝트를 불러오지 못했습니다.',+ loadRetry: '다시 시도',revealFolder: `${FILES}에서 보기`,folderAll: '전체',folderUp: '한 단계 위로',diff --git a/packages/openfilm/studio/ui/src/i18n/zh-CN.ts b/packages/openfilm/studio/ui/src/i18n/zh-CN.tsindex 8bab389..a1c845f 100644--- a/packages/openfilm/studio/ui/src/i18n/zh-CN.ts+++ b/packages/openfilm/studio/ui/src/i18n/zh-CN.ts@@ -143,6 +143,8 @@ export const zhCN: Words = {projects: {newProject: '新建项目',localProjectFailed: '无法创建项目,请重试。',+ loadFailed: '无法加载你的项目。',+ loadRetry: '重试',revealFolder: `在${FILES}中显示`,folderAll: '全部',folderUp: '返回上一级',diff --git a/packages/openfilm/studio/ui/src/lib/projects-page.test.ts b/packages/openfilm/studio/ui/src/lib/projects-page.test.tsnew file mode 100644index 0000000..7849ae9--- /dev/null+++ b/packages/openfilm/studio/ui/src/lib/projects-page.test.ts@@ -0,0 +1,18 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { posterRetryDelay, posterTry, within } from './projects-page.ts';++test('a list that never comes fails in its own time; one that comes or fails is passed on as it is', async () => {+ assert.equal(await within(Promise.resolve(3), 50), 3);+ await assert.rejects(within(Promise.reject(new Error('refused')), 50), /refused/);+ const t0 = Date.now();+ await assert.rejects(within(new Promise(() => {}), 50), /no answer within/);+ assert.ok(Date.now() - t0 < 1000);+});++test('a poster still being drawn is asked for again, less often each time, then given up on', () => {+ assert.deepEqual([0, 1, 2, 3, 4].map(posterRetryDelay), [4000, 8000, 16000, 32000, null]);+ assert.equal(posterTry('/api/projects/a/poster', 0), '/api/projects/a/poster');+ assert.equal(posterTry('/api/projects/a/poster', 2), '/api/projects/a/poster?try=2');+ assert.equal(posterTry('/api/projects/a/poster?cover=5', 1), '/api/projects/a/poster?cover=5&try=1');+});diff --git a/packages/openfilm/studio/ui/src/lib/projects-page.ts b/packages/openfilm/studio/ui/src/lib/projects-page.tsnew file mode 100644index 0000000..607d98e--- /dev/null+++ b/packages/openfilm/studio/ui/src/lib/projects-page.ts@@ -0,0 +1,31 @@+/**+ * Small rules of the Projects page: how long its list is waited for, and when a card asks again for a poster that is+ * still being drawn.+ */++/** How long the list is waited for before the page says it could not load it (and offers to try again). */+export const LIST_WAIT_MS = 15_000;++/** What `promise` gives, or a failure once `ms` have passed without it. */+export function within<T>(promise: Promise<T>, ms: number): Promise<T> {+ return new Promise<T>((done, fail) => {+ const timer = setTimeout(() => fail(new Error(`no answer within ${ms / 1000} s`)), ms);+ promise.then(+ (value) => { clearTimeout(timer); done(value); },+ (error: unknown) => { clearTimeout(timer); fail(error); },+ );+ });+}++/**+ * A card's poster that did not come (still being drawn, which Studio answers at once rather than hold the browser's+ * connection): asked for again after this many ms, `tried` times so far; null: given up (the card keeps its face).+ */+export function posterRetryDelay(tried: number): number | null {+ return tried < 4 ? 4000 * 2 ** tried : null;+}++/** The poster's address for try `n` (0: the first), so the browser asks Studio again rather than its cache. */+export function posterTry(url: string, n: number): string {+ return n ? `${url}${url.includes('?') ? '&' : '?'}try=${n}` : url;+}