Skip to content

The open source AI video agent: turns any coding agent into a video agent, with an editor to change anything it makes.

Desktop: reveal replacement pages before releasing closed tabs (#82)

mikas2e72ef112648
diff --git a/.changeset/smooth-tab-close.md b/.changeset/smooth-tab-close.md
new file mode 100644
index 0000000..900c5e5
--- /dev/null
+++ b/.changeset/smooth-tab-close.md
@@ -0,0 +1,5 @@
+---
+"@openfilm/desktop": patch
+---
+
+Keep the outgoing project visible until its replacement is ready when closing a tab, avoiding an empty-window flash.
diff --git a/apps/desktop/src/main.mjs b/apps/desktop/src/main.mjs
index 6aacd28..01e7f21 100644
--- a/apps/desktop/src/main.mjs
+++ b/apps/desktop/src/main.mjs
@@ -19,6 +19,7 @@ import { folderDialogOptions, programDialogOptions } from './folder-dialog.mjs';
import { childEnvironment, loginShellEnvironment } from './environment.mjs';
import { startWindowStudio } from './studio.mjs';
import { CHAT_MIN, STUDIO_MIN, WINDOW_MIN, placeOnDisplays, readWindowState, writeWindowState } from './window-state.mjs';
+import { createPagePresentation, preparePage, revealPage } from './page-presentation.mjs';
import { closeTabOrWindow, keepWindowOnClose, quitAfterStudio } from './window-lifecycle.mjs';
import { applicationMenu } from './menu.mjs';
import { registerLocalAgentIpc } from './local-agents-ipc.mjs';
@@ -67,8 +68,9 @@ let tabs = null;
/** the page of each tab that has one (a tab left behind long enough has none until it is shown again) */
/** @type {Map<string, WebContentsView>} */
const views = new Map();
+let pagePresentation = null;
/** the page in front */
-const activeView = () => (tabs ? views.get(tabs.activeId() ?? HOME) ?? null : null);
+const activeView = () => views.get(pagePresentation?.currentId() ?? tabs?.activeId() ?? HOME) ?? null;
/** something every page is told (the theme, an update, the agents…) */
const broadcast = (channel, value) => { for (const v of views.values()) if (!v.webContents.isDestroyed()) v.webContents.send(channel, value); };
/** the tab whose page this is, or null */
@@ -147,6 +149,8 @@ function makeView(tabId) {
},
});
v.setBackgroundColor(BACKGROUND[theme]);
+ // A newly attached view must not cover the current page with its initial blank frame.
+ v.setVisible(false);
views.set(tabId, v);
win.contentView.addChildView(v);
const { width, height } = win.getContentBounds();
@@ -154,7 +158,7 @@ function makeView(tabId) {
guard(v.webContents, (url) => Boolean(studio) && url.startsWith(`${studio.origin}/`));
/* what went wrong with the page, for the log (logs/studio.log) */
v.webContents.on('render-process-gone', (_event, details) => log(`page: renderer gone (${details.reason}, ${details.exitCode})\n`));
- v.webContents.on('did-fail-load', (_event, code, description, url, mainFrame) => { if (mainFrame) log(`page: ${description} (${code}) loading ${url.replace(/key=[^&]+/, 'key=…')}\n`); });
+ v.webContents.on('did-fail-load', (_event, code, description, url, mainFrame) => { if (mainFrame && code !== -3 && pagePresentation?.wantedId() === tabId) log(`page: ${description} (${code}) loading ${url.replace(/key=[^&]+/, 'key=…')}\n`); });
v.webContents.on('unresponsive', () => log('page: not responding\n'));
/* the page gone (a crash): it comes back where it was; the agents' turns go on in this process meanwhile */
v.webContents.on('render-process-gone', (_event, details) => { if (details.reason !== 'clean-exit' && !quitting) setTimeout(() => { if (!v.webContents.isDestroyed()) v.webContents.reload(); }, 500); });
@@ -173,14 +177,39 @@ function tellTabs() {
saveState();
}
-/** Show a page: a tab's (made again when it has none), or HOME. Once a tab shows, HOME's page goes. */
+function presentation() {
+ return pagePresentation ??= createPagePresentation({
+ fallback: HOME,
+ prepare(id) {
+ const v = makeView(id);
+ // A never-visible native view produces no frames. Paint it underneath the outgoing page.
+ win.contentView.addChildView(v, 0);
+ v.setVisible(true);
+ v.webContents.setBackgroundThrottling(false);
+ const ready = preparePage(v.webContents, pageAddress(id === HOME ? null : tabs?.get(id)))
+ .finally(() => {
+ if (v.webContents.isDestroyed()) return;
+ v.webContents.setBackgroundThrottling(true);
+ if (pagePresentation?.currentId() !== id && pagePresentation?.wantedId() !== id) v.setVisible(false);
+ });
+ return { view: v, ready };
+ },
+ present(_id, v) { if (win) revealPage(win.contentView, v, views.values()); },
+ discard: destroyView,
+ onError: (error) => { if (!quitting) log(`page: could not prepare replacement (${String(error.message).replace(/key=[^&\s)]+/g, 'key=…')})\n`); },
+ });
+}
+
+/** Keep only the lightweight projects page ready, without focusing it. */
+function warmHome() {
+ if (!tabs || !win || quitting) return;
+ void presentation().warm(HOME);
+}
+
+/** A ready page replaces the old frame; a cold page is prepared before it covers it. */
function showPage(id) {
- if (!win || !studio) return;
- let v = views.get(id);
- if (!v) { v = makeView(id); void v.webContents.loadURL(pageAddress(id === HOME ? null : tabs?.get(id))); }
- for (const [other, page] of views) page.setVisible(other === id);
- v.webContents.focus();
- if (id !== HOME) dropView(HOME);
+ if (!win || !studio) return Promise.resolve(false);
+ return presentation().show(id).then((shown) => { if (shown && id !== HOME) warmHome(); return shown; });
}
/** Bring a tab to the front. */
@@ -197,7 +226,7 @@ function newTab(projectId) {
}
/** Let a tab's page go: closed, or behind too long (the tab stays). */
-function dropView(id) {
+function destroyView(id) {
const v = views.get(id);
if (!v) return;
views.delete(id);
@@ -205,6 +234,8 @@ function dropView(id) {
if (!v.webContents.isDestroyed()) v.webContents.close();
}
+function dropView(id) { if (pagePresentation) pagePresentation.drop(id); else destroyView(id); }
+
/** Close a tab; one whose agent is still at work, only once the person says so. */
async function closeTab(id) {
if (!tabs || !win) return;
@@ -217,8 +248,8 @@ async function closeTab(id) {
});
if (response !== 0) return;
}
- dropView(id);
const next = tabs.close(id);
+ presentation().retire(id);
if (next) showTab(next.id);
else { showPage(HOME); tellTabs(); }
}
@@ -400,7 +431,7 @@ async function start() {
win.on('enter-full-screen', () => broadcast('desktop:full-screen', true));
win.on('leave-full-screen', () => broadcast('desktop:full-screen', false));
keepWindowOnClose(win, { mac, isQuitting: () => quitting, save: saveState });
- win.on('closed', () => { win = null; views.clear(); app.quit(); });
+ win.on('closed', () => { win = null; views.clear(); pagePresentation = null; app.quit(); });
ipcMain.on('desktop:theme', (event, next) => { if (fromPage(event)) setTheme(next); });
ipcMain.handle('desktop:hello', (event) => {
@@ -628,6 +659,7 @@ async function start() {
} catch (error) {
log(`Studio did not start: ${error.stack ?? error}\n`);
const v = makeView('failed');
+ v.setVisible(true);
void v.webContents.loadFile(here('./failed.html'), { query: { message: String(error.message ?? error) } });
}
}
diff --git a/apps/desktop/src/page-presentation.mjs b/apps/desktop/src/page-presentation.mjs
new file mode 100644
index 0000000..c1ad52c
--- /dev/null
+++ b/apps/desktop/src/page-presentation.mjs
@@ -0,0 +1,111 @@
+/** Switch native pages without exposing the empty window between their frames. No Electron dependency. */
+export function createPagePresentation({ prepare, present, discard, fallback = null, onError = () => {} }) {
+ const pages = new Map();
+ const retired = new Set();
+ let current = null;
+ let wanted = null;
+ let request = 0;
+
+ function remove(id) {
+ const page = pages.get(id);
+ pages.delete(id);
+ retired.delete(id);
+ if (page) discard(id, page.view);
+ }
+ function ensure(id) {
+ let page = pages.get(id);
+ if (page) return page;
+ const prepared = prepare(id);
+ page = { view: prepared.view, loaded: false, ready: null };
+ pages.set(id, page);
+ page.ready = Promise.resolve(prepared.ready).then(() => { page.loaded = true; }, (error) => {
+ if (pages.get(id) === page) remove(id);
+ throw error;
+ });
+ // A preloaded page may never be shown. Its failure must still be handled.
+ void page.ready.catch(() => {});
+ return page;
+ }
+ function commit(id, page, ticket) {
+ if (ticket !== request || wanted !== id || retired.has(id) || pages.get(id) !== page) return false;
+ present(id, page.view);
+ current = id;
+ for (const old of [...retired]) if (old !== id) remove(old);
+ return true;
+ }
+ function failed(id, ticket, error) {
+ // Closing a loading tab destroys its view and rejects loadURL. It is not a failed destination.
+ if (ticket !== request || wanted !== id || retired.has(id)) return Promise.resolve(false);
+ onError(error);
+ if (fallback == null || id === fallback) return Promise.resolve(false);
+ return show(fallback).then(() => false);
+ }
+ function show(id) {
+ wanted = id;
+ const ticket = ++request;
+ let page;
+ try { page = ensure(id); } catch (error) { return failed(id, ticket, error); }
+ // Already painted background pages switch in this call, without a promise turn.
+ if (page.loaded) return Promise.resolve(commit(id, page, ticket));
+ return page.ready.then(() => commit(id, page, ticket), (error) => failed(id, ticket, error));
+ }
+ return {
+ currentId: () => current,
+ wantedId: () => wanted,
+ show,
+ warm(id) { return ensure(id).ready.then(() => true, () => false); },
+ retire(id) {
+ retired.add(id);
+ // The outgoing page remains until its replacement is presented.
+ if (id !== current) remove(id);
+ },
+ drop(id) {
+ if (id === current || id === wanted) return false;
+ remove(id);
+ return true;
+ },
+ };
+}
+
+/** Load first, then allow two paint frames; neither a hung navigation nor a throttled frame waits forever. */
+export async function preparePage(contents, url, { loadTimeoutMs = 15_000, paintTimeoutMs = 500 } = {}) {
+ let timer;
+ try {
+ await Promise.race([
+ contents.loadURL(url),
+ new Promise((_, reject) => {
+ timer = setTimeout(() => {
+ reject(new Error('Page loading timed out'));
+ if (!contents.isDestroyed()) contents.stop();
+ }, loadTimeoutMs);
+ }),
+ ]);
+ } finally { clearTimeout(timer); }
+ if (contents.isDestroyed()) throw new Error('Page closed while loading');
+ try {
+ await Promise.race([
+ contents.executeJavaScript(`(${waitForPageFrame.toString()})(${paintTimeoutMs})`),
+ // Also bound the host-side wait if the renderer stops responding before it can run its timer.
+ new Promise((resolve) => { timer = setTimeout(resolve, paintTimeoutMs); }),
+ ]);
+ } finally { clearTimeout(timer); }
+ if (contents.isDestroyed()) throw new Error('Page closed while painting');
+}
+
+/** Runs inside the loaded page. A hidden/throttled renderer may not produce animation frames. */
+export function waitForPageFrame(timeoutMs) {
+ return new Promise((resolve) => {
+ let frame;
+ const finish = () => { clearTimeout(timer); cancelAnimationFrame(frame); resolve(); };
+ const timer = setTimeout(finish, timeoutMs);
+ frame = requestAnimationFrame(() => { frame = requestAnimationFrame(finish); });
+ });
+}
+
+/** Show and raise the replacement before hiding any previously visible page. */
+export function revealPage(parent, target, pages) {
+ target.setVisible(true);
+ parent.addChildView(target);
+ for (const page of pages) if (page !== target) page.setVisible(false);
+ target.webContents.focus();
+}
diff --git a/apps/desktop/src/page-presentation.test.mjs b/apps/desktop/src/page-presentation.test.mjs
new file mode 100644
index 0000000..6237d26
--- /dev/null
+++ b/apps/desktop/src/page-presentation.test.mjs
@@ -0,0 +1,226 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { createPagePresentation, preparePage, revealPage, waitForPageFrame } from './page-presentation.mjs';
+import { createTabs } from './tabs.mjs';
+import { runInNewContext } from 'node:vm';
+
+function fixture() {
+ const events = [], loads = new Map();
+ const pages = createPagePresentation({
+ fallback: 'home',
+ prepare(id) {
+ events.push(`prepare:${id}`);
+ let resolve, reject;
+ const ready = new Promise((yes, no) => { resolve = yes; reject = no; });
+ loads.set(id, { resolve, reject });
+ return { view: id, ready };
+ },
+ present: (id) => events.push(`present:${id}`),
+ discard: (id) => events.push(`discard:${id}`),
+ onError: () => events.push('error'),
+ });
+ async function show(id) { const showing = pages.show(id); loads.get(id).resolve(); assert.equal(await showing, true); }
+ return { pages, events, loads, show };
+}
+
+test('closing a page retains its frame until the cold replacement is ready', async () => {
+ const f = fixture();
+ await f.show('front');
+ f.pages.retire('front');
+ const next = f.pages.show('next');
+ assert.equal(f.pages.currentId(), 'front');
+ assert.ok(!f.events.includes('discard:front'));
+ f.loads.get('next').resolve();
+ assert.equal(await next, true);
+ assert.deepEqual(f.events.slice(-2), ['present:next', 'discard:front']);
+});
+
+test('warming never focuses a page; an already ready page is presented synchronously', async () => {
+ const f = fixture();
+ await f.show('front');
+ const warming = f.pages.warm('home');
+ f.loads.get('home').resolve(); await warming;
+ assert.equal(f.pages.currentId(), 'front');
+ assert.ok(!f.events.includes('present:home'));
+ f.pages.retire('front');
+ const shown = f.pages.show('home');
+ assert.equal(f.pages.currentId(), 'home', 'no asynchronous gap for a painted background page');
+ assert.deepEqual(f.events.slice(-2), ['present:home', 'discard:front']);
+ assert.equal(await shown, true);
+});
+
+test('rapid closes cannot reveal a retired or superseded replacement', async () => {
+ const f = fixture();
+ await f.show('a');
+ f.pages.retire('a');
+ const b = f.pages.show('b');
+ f.pages.retire('b');
+ const c = f.pages.show('c');
+ f.loads.get('b').resolve();
+ assert.equal(await b, false);
+ assert.equal(f.pages.currentId(), 'a');
+ f.loads.get('c').resolve();
+ assert.equal(await c, true);
+ assert.ok(!f.events.includes('present:b'));
+ assert.deepEqual(f.events.slice(-2), ['present:c', 'discard:a']);
+});
+
+test('a failed replacement falls back to HOME before discarding the closed page', async () => {
+ const f = fixture();
+ await f.show('a'); f.pages.retire('a');
+ const failed = f.pages.show('b');
+ f.loads.get('b').reject(new Error('offline'));
+ // Allow the failed load to request its fallback.
+ await Promise.resolve(); await Promise.resolve();
+ assert.equal(f.pages.currentId(), 'a');
+ assert.ok(!f.events.includes('discard:a'));
+ assert.equal(f.pages.wantedId(), 'home');
+ f.loads.get('home').resolve();
+ assert.equal(await failed, false);
+ assert.equal(f.pages.currentId(), 'home');
+ assert.deepEqual(f.events.slice(-2), ['present:home', 'discard:a']);
+ assert.equal(f.events.filter((event) => event === 'error').length, 1);
+});
+
+test('an obsolete load rejection neither logs an error nor steals the latest destination', async () => {
+ const f = fixture();
+ await f.show('a'); f.pages.retire('a');
+ const b = f.pages.show('b');
+ f.pages.retire('b');
+ const c = f.pages.show('c');
+ f.loads.get('b').reject(new Error('view destroyed'));
+ assert.equal(await b, false);
+ assert.equal(f.pages.wantedId(), 'c');
+ assert.ok(!f.events.includes('error'));
+ assert.ok(!f.events.includes('prepare:home'));
+ f.loads.get('c').resolve();
+ assert.equal(await c, true);
+ assert.equal(f.pages.currentId(), 'c');
+});
+
+test('a new request supersedes a pending HOME fallback', async () => {
+ const f = fixture();
+ await f.show('a'); f.pages.retire('a');
+ const b = f.pages.show('b');
+ f.loads.get('b').reject(new Error('offline'));
+ await Promise.resolve(); await Promise.resolve();
+ const c = f.pages.show('c');
+ f.loads.get('home').resolve();
+ assert.equal(await b, false);
+ assert.equal(f.pages.currentId(), 'a');
+ f.loads.get('c').resolve();
+ assert.equal(await c, true);
+ assert.equal(f.pages.currentId(), 'c');
+});
+
+test('idle cleanup never drops the visible frame or a requested replacement', async () => {
+ const f = fixture();
+ await f.show('a');
+ const b = f.pages.show('b');
+ assert.equal(f.pages.drop('a'), false);
+ assert.equal(f.pages.drop('b'), false);
+ f.loads.get('b').resolve(); await b;
+ assert.equal(f.pages.drop('a'), true);
+});
+
+test('the native replacement is shown and raised before the outgoing page is hidden', () => {
+ const events = [];
+ let oldVisible = true, newVisible = false;
+ const old = { setVisible: (visible) => { oldVisible = visible; assert.ok(newVisible); events.push('hide-old'); } };
+ const target = { setVisible: (visible) => { newVisible = visible; assert.ok(oldVisible); events.push('show-new'); }, webContents: { focus: () => events.push('focus-new') } };
+ revealPage({ addChildView: () => { assert.ok(newVisible && oldVisible); events.push('raise-new'); } }, target, [old, target]);
+ assert.deepEqual(events, ['show-new', 'raise-new', 'hide-old', 'focus-new']);
+});
+
+test('idle neighbors are evicted even when they are the next close destination', async () => {
+ const f = fixture();
+ let clock = 0;
+ const tabs = createTabs({ now: () => clock });
+ const a = tabs.open({ projectId: 'a' });
+ await f.show(a.id);
+ const b = tabs.open({ projectId: 'b' });
+ await f.show(b.id);
+ clock = 10_000;
+ for (const id of tabs.idle(5_000)) f.pages.drop(id);
+ assert.ok(f.events.includes(`discard:${a.id}`));
+ assert.equal(f.pages.currentId(), b.id);
+});
+
+test('a hung page load fails without presenting unloaded contents', async () => {
+ const events = [];
+ const contents = {
+ loadURL: () => new Promise(() => {}),
+ isDestroyed: () => false,
+ stop: () => events.push('stop'),
+ executeJavaScript: () => events.push('paint'),
+ };
+ await assert.rejects(preparePage(contents, 'https://studio.invalid/', { loadTimeoutMs: 5 }), /timed out/);
+ assert.deepEqual(events, ['stop']);
+});
+
+test('a rejected load never waits for or presents a frame', async () => {
+ const contents = {
+ loadURL: () => Promise.reject(new Error('offline')),
+ executeJavaScript: () => assert.fail('failed load must not paint'),
+ };
+ await assert.rejects(preparePage(contents, 'https://studio.invalid/'), /offline/);
+});
+
+test('a successful load requests bounded paint readiness', async () => {
+ const events = [];
+ const contents = {
+ async loadURL() { events.push('load'); },
+ isDestroyed: () => false,
+ async executeJavaScript(script) {
+ events.push('paint');
+ await runInNewContext(script, {
+ setTimeout, clearTimeout,
+ requestAnimationFrame: () => 1,
+ cancelAnimationFrame: () => {},
+ });
+ },
+ };
+ await preparePage(contents, 'https://studio.invalid/', { paintTimeoutMs: 5 });
+ assert.deepEqual(events, ['load', 'paint']);
+});
+
+test('two painted frames clear their fallback timer; timeout cancels the pending frame', async () => {
+ function paintFixture() {
+ let timeout, frame;
+ const events = [];
+ const promise = runInNewContext(`(${waitForPageFrame.toString()})(500)`, {
+ setTimeout: (fn) => { timeout = fn; return 'timer'; },
+ clearTimeout: (id) => events.push(`clear:${id}`),
+ requestAnimationFrame: (fn) => { frame = fn; return 'frame'; },
+ cancelAnimationFrame: (id) => events.push(`cancel:${id}`),
+ });
+ return { promise, events, tickFrame: () => frame(), tickTimeout: () => timeout() };
+ }
+ const painted = paintFixture();
+ painted.tickFrame(); painted.tickFrame(); await painted.promise;
+ assert.deepEqual(painted.events, ['clear:timer', 'cancel:frame']);
+ const throttled = paintFixture();
+ throttled.tickTimeout(); await throttled.promise;
+ assert.deepEqual(throttled.events, ['clear:timer', 'cancel:frame']);
+});
+
+test('a loaded but unresponsive renderer cannot leave the host waiting for frames forever', async () => {
+ const contents = {
+ async loadURL() {},
+ isDestroyed: () => false,
+ executeJavaScript: () => new Promise(() => {}),
+ };
+ await preparePage(contents, 'https://studio.invalid/', { paintTimeoutMs: 5 });
+});
+
+test('closing the last tab keeps its frame until cold HOME is ready', async () => {
+ const f = fixture();
+ await f.show('last');
+ f.pages.retire('last');
+ const home = f.pages.show('home');
+ assert.equal(f.pages.currentId(), 'last');
+ assert.ok(!f.events.includes('discard:last'));
+ f.loads.get('home').resolve();
+ assert.equal(await home, true);
+ assert.deepEqual(f.events.slice(-2), ['present:home', 'discard:last']);
+});