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 and Studio: improve project, timeline, chat and agent controls (#245)

riverisbuilding49812381b40c
diff --git a/.changeset/agent-model-efforts.md b/.changeset/agent-model-efforts.md
new file mode 100644
index 0000000..887a0fb
--- /dev/null
+++ b/.changeset/agent-model-efforts.md
@@ -0,0 +1,7 @@
+---
+"@openfilm/desktop": patch
+---
+
+Enable Cursor's parameterized model picker and refresh agent options for the selected model before the first message. Show native effort choices, including Default, apply them to the conversation, and update the menu when the agent reports new options.
+
+Reset model-specific settings on a model switch and hide the old model's speed and effort choices while the new options load. Reassert Cursor's selected model before applying only the parameters it currently supports, and show the rejected setting when configuration fails.
diff --git a/.changeset/agent-sign-in-cancellation.md b/.changeset/agent-sign-in-cancellation.md
new file mode 100644
index 0000000..ef7dbe4
--- /dev/null
+++ b/.changeset/agent-sign-in-cancellation.md
@@ -0,0 +1,6 @@
+---
+"@openfilm/desktop": patch
+"openfilm": patch
+---
+
+Restore the agent sign-in button when its login terminal closes, and let the user cancel waiting for sign-in from Settings.
diff --git a/.changeset/agent-submenu-bounds.md b/.changeset/agent-submenu-bounds.md
new file mode 100644
index 0000000..6c3febd
--- /dev/null
+++ b/.changeset/agent-submenu-bounds.md
@@ -0,0 +1,5 @@
+---
+"@openfilm/desktop": patch
+---
+
+Keep agent model and effort submenus inside the window when their options change or the window is resized, with scrolling for tall menus.
diff --git a/.changeset/faster-agent-sign-in.md b/.changeset/faster-agent-sign-in.md
new file mode 100644
index 0000000..f5367d6
--- /dev/null
+++ b/.changeset/faster-agent-sign-in.md
@@ -0,0 +1,5 @@
+---
+"@openfilm/desktop": patch
+---
+
+Detect completed agent sign-ins promptly by bypassing cached signed-out status while waiting, checking immediately and then every second, and prioritizing sign-in checks when the app regains focus. Share in-flight checks and keep slow background scans from overwriting newer login results. Point the DeepSeek Harness download link to its official website.
diff --git a/.changeset/project-presence.md b/.changeset/project-presence.md
new file mode 100644
index 0000000..5215e15
--- /dev/null
+++ b/.changeset/project-presence.md
@@ -0,0 +1,5 @@
+---
+"openfilm": patch
+---
+
+Refresh project availability when the library opens and when returning to the app. Check again before opening a project, and leave open editors when their folder or film.html is removed externally, with a short grace period for file saves. Missing project files are distinguished from empty films, and removing unavailable projects from the list preserves any remaining files.
diff --git a/.changeset/remove-preview-axis.md b/.changeset/remove-preview-axis.md
new file mode 100644
index 0000000..838103a
--- /dev/null
+++ b/.changeset/remove-preview-axis.md
@@ -0,0 +1,5 @@
+---
+"openfilm": patch
+---
+
+Remove the timeline's preview axis switch, hover preview and keyboard shortcut. Click or drag the timeline playhead to seek and preview the film.
diff --git a/.changeset/stable-chat-activity.md b/.changeset/stable-chat-activity.md
new file mode 100644
index 0000000..937ca6b
--- /dev/null
+++ b/.changeset/stable-chat-activity.md
@@ -0,0 +1,5 @@
+---
+"@openfilm/desktop": patch
+---
+
+Keep running tools in the same conversation rows and groups when they finish, with matching typography, icons and spacing. Tool counts and separators follow the visible labels without blank padding. Keep the complete hover toolbar on its own row below a visible status, and omit empty status rows so the toolbar stays close to the reply. Fold a finished turn into its Worked line as soon as it ends, keeping the reply where it was, and preserve the turn's reserved height until the next turn or viewport resize. A lone step that made a picture or sound stays a step summary, so its result never disappears when another step joins it.
diff --git a/.changeset/timeline-range-feedback.md b/.changeset/timeline-range-feedback.md
new file mode 100644
index 0000000..22d7e77
--- /dev/null
+++ b/.changeset/timeline-range-feedback.md
@@ -0,0 +1,5 @@
+---
+"openfilm": patch
+---
+
+Keep the ruler's normal pointer until the reference modifier is held. Show referenced ranges only on the ruler, and briefly highlight ranges recalled from chat while seeking to their start without changing the editing selection. Empty space in the subtitle row seeks and scrubs, and the timeline's floating reference button is removed.
diff --git a/apps/desktop/bench/activity-layout.test.mjs b/apps/desktop/bench/activity-layout.test.mjs
new file mode 100644
index 0000000..7797001
--- /dev/null
+++ b/apps/desktop/bench/activity-layout.test.mjs
@@ -0,0 +1,186 @@
+/** Pixel-level regression for tool completion and turn completion: no model requests or Electron required. */
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { fileURLToPath } from 'node:url';
+import { createServer } from 'vite';
+import { chromium } from 'playwright-core';
+import shellConfig from '../shell/vite.config.ts';
+
+test('running tools keep their DOM, styles and position on completion, and a finished turn folds without moving the reply', { timeout: 60_000 }, async () => {
+ const server = await createServer({
+ ...shellConfig, configFile: false, root: fileURLToPath(new URL('..', import.meta.url)),
+ server: { host: '127.0.0.1', port: 0 }, logLevel: 'error',
+ plugins: [...shellConfig.plugins, {
+ name: 'activity-layout-fixture',
+ configureServer(app) {
+ app.middlewares.use('/activity-layout', (_req, res, next) => {
+ res.setHeader('content-type', 'text/html');
+ void app.transformIndexHtml('/activity-layout', '<!doctype html><html><body><div id="root"></div><script type="module" src="/bench/activity-layout.tsx"></script></body></html>')
+ .then((html) => res.end(html), next);
+ });
+ },
+ }],
+ });
+ let browser;
+ try {
+ await server.listen();
+ const port = server.httpServer.address().port;
+ browser = await chromium.launch({ headless: true });
+ const configs = ['en', 'zh-CN'].flatMap((locale) => ['single', 'group', 'counts'].flatMap((scenario) => [
+ { width: 440, height: 620, above: 0, locale, scenario },
+ { width: 320, height: 280, above: 600, locale, scenario },
+ ]));
+ for (const config of configs) {
+ const page = await browser.newPage({ viewport: { width: 800, height: 800 }, reducedMotion: 'reduce' });
+ const errors = [];
+ page.on('pageerror', (e) => errors.push(e.message));
+ await page.addInitScript(() => {
+ window.openfilmDesktop = { developer: { get: async () => ({ logs: false, changes: false }), onChange: () => () => {} } };
+ });
+ await page.goto(`http://127.0.0.1:${port}/activity-layout?${new URLSearchParams(config)}`);
+ await page.waitForFunction(() => Boolean(window.activityFixture), null, { timeout: 10_000 }).catch((error) => {
+ throw new Error(`${error.message}; page errors: ${JSON.stringify(errors)}`);
+ });
+ const answer = page.getByText('Final answer anchor.', { exact: true });
+ await answer.waitFor({ state: 'visible' });
+ await page.evaluate(() => new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(done))));
+ const header = page.locator(`[data-activity-id="${config.scenario === 'single' ? 'command' : config.scenario === 'counts' ? 'edit-0' : 'check'}"]`);
+ assert.equal(await header.getAttribute('aria-busy'), 'true', 'the running tool is already in its conversation row');
+ assert.equal(await page.getByRole('status', { includeHidden: true }).count(), 0, 'an inline tool does not leave a duplicate or empty status row');
+ await header.evaluate((node) => { node.dataset.probe = 'preserved'; });
+ const footer = page.locator('[data-turn-footer]').last();
+ await answer.hover();
+ await page.waitForFunction(() => getComputedStyle([...document.querySelectorAll('[data-turn-footer]')].at(-1)).opacity === '1');
+ const footerGap = async () => {
+ const reply = await answer.boundingBox();
+ return (await footer.boundingBox()).y - reply.y - reply.height;
+ };
+ assert.ok(await footerGap() <= 10, 'the hover actions sit directly under a streaming reply, without an empty status row');
+ const snapshot = () => header.evaluate((node) => {
+ const box = (element, fixed = true) => {
+ if (!element) return null;
+ const { x, y, width, height } = element.getBoundingClientRect();
+ const style = getComputedStyle(element);
+ return { ...(fixed ? { x, y, width, height } : { y, height }), fontSize: style.fontSize, lineHeight: style.lineHeight,
+ fontFamily: style.fontFamily, fontWeight: style.fontWeight, color: style.color,
+ padding: style.padding, gap: style.gap };
+ };
+ return { row: box(node), label: box(node.querySelector('[data-activity-label]'), false),
+ detail: box(node.querySelector('span[title]'), false),
+ icon: box(node.querySelector('svg') ?? node.parentElement.previousElementSibling) };
+ });
+ const runningStyle = await snapshot();
+ const runningLabel = await header.innerText();
+ const beforeTool = await answer.boundingBox();
+ const headerHeights = () => page.locator('[data-activity-header]').evaluateAll((rows) => rows.map((row) => row.getBoundingClientRect().height));
+ const singleHeights = await headerHeights();
+ await page.evaluate(() => window.activityFixture.finishTool());
+ await page.evaluate(() => new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(done))));
+ assert.equal(await header.getAttribute('aria-busy'), 'false', 'completing a later member updates a cached group');
+ assert.equal(await header.getAttribute('data-probe'), 'preserved', 'the tool keeps the same DOM node on completion');
+ assert.notEqual(await header.innerText(), runningLabel, 'the label changes to completed without changing its style');
+ assert.deepEqual(await snapshot(), runningStyle, `tool row position, height and typography stay identical: ${JSON.stringify(config)}`);
+ if (config.scenario === 'counts') {
+ assert.equal(await header.locator('[data-activity-label]').textContent(), config.locale === 'zh-CN'
+ ? '已编辑文件 ×9 · 已运行命令 · 已读取文件'
+ : 'Edited files ×9 · Ran a command · Read files', 'counts and separators follow visible labels with normal spaces');
+ assert.equal(await header.locator('.invisible').count(), 0, 'no hidden label reserves extra spacing before the count');
+ }
+ assert.ok(Math.abs((await answer.boundingBox()).y - beforeTool.y) <= 1, 'finishing a tool preserves the reply position');
+ assert.deepEqual(await headerHeights(), singleHeights, 'single tool rows and their completed summaries have the same height');
+ const before = await answer.boundingBox();
+ await page.evaluate(() => window.activityFixture.finish());
+ await page.getByRole('status').waitFor({ state: 'hidden' });
+ await page.evaluate(() => new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(done))));
+ const after = await answer.boundingBox();
+ /* Folding keeps the reply in place by scrolling; a conversation shorter than its viewport has nothing to scroll. */
+ if (config.above) assert.ok(Math.abs(after.y - before.y) <= 1, `reply moved ${after.y - before.y}px at width ${config.width}`);
+ else assert.ok(after.y <= before.y, 'a short conversation folds upward, never pushing the reply down');
+ assert.ok(await footerGap() <= 10, 'the finished reply keeps the same compact footer spacing');
+ assert.equal(await page.getByText('I will check the project first.', { exact: true }).count(), 0, 'the turn just watched folds as it finishes');
+ assert.equal(await page.locator('[data-activity-header]').count(), 0, 'its steps fold into the Worked line');
+ await page.evaluate(() => window.activityFixture.next());
+ await page.getByText('Continue.', { exact: true }).waitFor();
+ assert.equal(await page.getByText('I will check the project first.', { exact: true }).count(), 0, 'earlier turns stay folded when a new turn starts');
+ assert.deepEqual(errors, []);
+ await page.close();
+ }
+ for (const locale of ['en', 'zh-CN']) {
+ const page = await browser.newPage({ viewport: { width: 800, height: 800 }, reducedMotion: 'reduce' });
+ const errors = [];
+ page.on('pageerror', (e) => errors.push(e.message));
+ await page.addInitScript(() => {
+ window.openfilmDesktop = { developer: { get: async () => ({ logs: false, changes: false }), onChange: () => () => {} } };
+ });
+ await page.goto(`http://127.0.0.1:${port}/activity-layout?${new URLSearchParams({ scenario: 'asset', width: 440, height: 620, locale })}`);
+ await page.waitForFunction(() => Boolean(window.activityFixture));
+ const row = page.locator('[data-activity-id="image"]');
+ await row.waitFor({ state: 'visible' });
+ await row.evaluate((node) => { node.dataset.probe = 'preserved'; });
+ const pictures = () => page.locator('img').evaluateAll((images) => images.filter((image) => image.getBoundingClientRect().height > 0).length);
+ const shown = await pictures();
+ await page.evaluate(() => window.activityFixture.addTool());
+ await page.locator('[data-activity-id="image"][aria-busy="true"]').waitFor();
+ assert.equal(await row.getAttribute('data-probe'), 'preserved', 'a lone act that made a picture keeps its row when another act joins it');
+ assert.equal(await pictures(), shown, `a picture shown in a live turn never disappears when another act joins: ${locale}`);
+ await row.click();
+ await page.waitForFunction(() => [...document.querySelectorAll('img')].some((image) => image.getBoundingClientRect().height > 0));
+ assert.ok(await pictures() >= 1, 'the picture is still in its row once the group is opened');
+ assert.deepEqual(errors, []);
+ await page.close();
+ }
+ for (const config of [
+ { scenario: 'idle', width: 440, touch: false },
+ { scenario: 'thinking', width: 320, touch: false },
+ { scenario: 'thinking', width: 320, touch: true },
+ ]) {
+ const page = await browser.newPage({
+ viewport: { width: 800, height: 800 }, reducedMotion: 'reduce', hasTouch: config.touch, isMobile: config.touch,
+ });
+ await page.addInitScript(() => {
+ window.openfilmDesktop = { developer: { get: async () => ({ logs: false, changes: false }), onChange: () => () => {} } };
+ });
+ await page.goto(`http://127.0.0.1:${port}/activity-layout?${new URLSearchParams({ ...config, height: 620, locale: 'zh-CN' })}`);
+ await page.waitForFunction(() => Boolean(window.activityFixture));
+ const status = page.getByRole('status');
+ const footer = page.locator('[data-turn-footer]');
+ await status.waitFor({ state: 'visible' });
+ const before = await status.boundingBox();
+ const label = await status.locator('.text-sweep').innerText();
+ await footer.hover();
+ await page.waitForFunction(() => getComputedStyle(document.querySelector('[data-turn-footer]')).opacity === '1');
+ assert.equal(await status.evaluate((node) => {
+ for (let element = node; element; element = element.parentElement) {
+ const style = getComputedStyle(element);
+ if (style.opacity === '0' || style.display === 'none' || style.visibility === 'hidden') return false;
+ }
+ return true;
+ }), true, 'hovering the complete toolbar does not hide the status');
+ assert.equal(await status.locator('.text-sweep').innerText(), label);
+ assert.equal(await status.locator('.tabular-nums').count(), 1, 'the status keeps its timer while hovering');
+ assert.deepEqual(await status.boundingBox(), before, 'hovering never replaces or moves the status');
+ const statusBox = await status.boundingBox();
+ const footerBox = await footer.boundingBox();
+ assert.ok(footerBox.y >= statusBox.y + statusBox.height, 'the toolbar has its own row below the status');
+ assert.ok(footerBox.y - statusBox.y - statusBox.height <= 8, 'the two rows stay close together');
+ assert.equal(await footer.getByText('Auto', { exact: true }).isVisible(), true, 'the full model label remains visible');
+ const modelBox = await footer.getByText('Auto', { exact: true }).boundingBox();
+ assert.ok(modelBox.x + modelBox.width <= footerBox.x + footerBox.width, 'the model label fits within the toolbar');
+ if (config.scenario === 'thinking') {
+ assert.equal(await footer.getByRole('button', { name: '复制回复', exact: true }).isVisible(), true, 'the copy button remains available below the status');
+ const answer = page.getByText('Final answer anchor.', { exact: true });
+ const replyBefore = await answer.boundingBox();
+ await page.evaluate(() => window.activityFixture.finishTool());
+ await page.getByRole('status', { includeHidden: true }).waitFor({ state: 'detached' });
+ await page.evaluate(() => new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(done))));
+ const replyAfter = await answer.boundingBox();
+ assert.ok(Math.abs(replyBefore.y - replyAfter.y) <= 1, 'removing an empty status does not move the reply');
+ assert.ok((await footer.boundingBox()).y - replyAfter.y - replyAfter.height <= 10, 'an empty status leaves no spare line above the toolbar');
+ }
+ await page.close();
+ }
+ } finally {
+ await browser?.close();
+ await server.close();
+ }
+});
diff --git a/apps/desktop/bench/activity-layout.tsx b/apps/desktop/bench/activity-layout.tsx
new file mode 100644
index 0000000..068b1da
--- /dev/null
+++ b/apps/desktop/bench/activity-layout.tsx
@@ -0,0 +1,98 @@
+/** Isolated rendering of the real conversation and scrolling hooks, without an agent or personal chat data. */
+import React from 'react';
+import { createRoot } from 'react-dom/client';
+import { ProjectConversation, primeStoredTranscript } from '../chat/src/components/ProjectConversation';
+import { StickToBottomContext, useStickToBottom, useTailSpacer } from '../chat/src/components/useStickToBottom';
+import { ActAssetUrlContext } from '../chat/src/components/AgentActivityRow';
+import type { TranscriptItem } from '../chat/src/lib/agent-transcript';
+import type { ProjectVersion } from '../chat/src/components/project-version';
+import { setLanguage } from '../chat/src/i18n';
+import '../shell/shell.css';
+import '../chat/src/chat.css';
+
+const transcript = (startedAt: number): TranscriptItem[] => [
+ { id: 'intro', kind: 'text', text: 'I will check the project first.', pending: false },
+ { id: 'read', kind: 'act', act: 'files.read', detail: 'film.html', pending: false },
+ { id: 'update', kind: 'text', text: 'The files are ready. Checking the result next.', pending: false },
+ { id: 'check', kind: 'act', act: 'command.run', detail: 'openfilm check', pending: false },
+ { id: 'search', kind: 'act', act: 'files.search', detail: '**/*.{html,md}', pending: true, startedAt },
+ { id: 'answer', kind: 'text', text: 'Final answer anchor.', pending: true },
+];
+
+/** A 1×1 PNG, so a made picture draws without a server. */
+const PIXEL = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==';
+const assetUrl = () => PIXEL;
+
+function Fixture() {
+ const [phase, setPhase] = React.useState('running');
+ const active = phase === 'running' || phase === 'tools-finished' || phase === 'second-tool';
+ const toolPending = phase === 'running';
+ const params = new URLSearchParams(location.search);
+ const scenario = params.get('scenario') ?? 'group';
+ const initial = React.useMemo<TranscriptItem[]>(() => {
+ const startedAt = Date.now() - 5000;
+ if (scenario === 'idle') return [];
+ if (scenario === 'asset') return [
+ { id: 'intro', kind: 'text', text: 'I will make a picture first.', pending: false },
+ { id: 'image', kind: 'act', act: 'asset.genImage', detail: 'A red pixel', pending: false, asset: { kind: 'image', src: 'assets/pixel.png' } },
+ ];
+ if (scenario === 'thinking') return [
+ { id: 'intro', kind: 'text', text: 'I will check the project first.', pending: false },
+ { id: 'thought', kind: 'thought', pending: true, startedAt },
+ { id: 'answer', kind: 'text', text: 'Final answer anchor.', pending: true },
+ ];
+ if (scenario === 'counts') return [
+ { id: 'intro', kind: 'text', text: 'I will check the project first.', pending: false },
+ ...Array.from({ length: 9 }, (_, i): TranscriptItem => ({
+ id: `edit-${i}`, kind: 'act', act: 'files.edit', pending: i === 8, startedAt,
+ })),
+ { id: 'check', kind: 'act', act: 'command.run', pending: false },
+ { id: 'read', kind: 'act', act: 'files.read', pending: false },
+ { id: 'answer', kind: 'text', text: 'Final answer anchor.', pending: true },
+ ];
+ return scenario === 'single' ? [
+ { id: 'intro', kind: 'text', text: 'I will check the project first.', pending: false },
+ { id: 'command', kind: 'act', act: 'command.run', detail: 'openfilm check --project example-with-a-long-folder-name', pending: true, startedAt },
+ { id: 'answer', kind: 'text', text: 'Final answer anchor.', pending: true },
+ ] : transcript(startedAt);
+ }, [scenario]);
+ // Real transcript updates preserve unchanged object identities; this also exercises the row cache.
+ const items = React.useMemo(() => initial.map((item) => item.pending
+ ? { ...item, pending: item.kind === 'act' || item.kind === 'thought' ? toolPending : active } : item)
+ .concat(phase === 'second-tool' ? [{ id: 'after', kind: 'act', act: 'command.run', detail: 'openfilm check', pending: true, startedAt: Date.now() }] : []),
+ [initial, active, toolPending, phase]);
+ const thread = useStickToBottom();
+ const tail = useTailSpacer(thread.viewport, thread.pinIfFollowing, active);
+ const turns: ProjectVersion[] = [{
+ assetId: 'layout-turn', label: '', title: '', prompt: 'Check the project.', attachments: [], current: true,
+ status: active ? 'active' : 'ready', durationMs: active ? undefined : 6000, agent: 'copilot', model: 'Auto',
+ }];
+ if (!active) primeStoredTranscript('layout-turn', items);
+ if (phase === 'next') turns.push({
+ assetId: 'pending:next', label: '', title: '', prompt: 'Continue.', attachments: [], current: true, status: 'active',
+ });
+ React.useEffect(() => {
+ (window as any).activityFixture = {
+ finishTool: () => setPhase('tools-finished'), finish: () => setPhase('finished'), next: () => setPhase('next'),
+ addTool: () => setPhase('second-tool'),
+ };
+ }, []);
+ return (
+ <ActAssetUrlContext.Provider value={assetUrl}>
+ <StickToBottomContext.Provider value={thread}>
+ <div className="of-chat" style={{ width: Number(params.get('width') ?? 440), margin: 20 }}>
+ <div data-activity-viewport ref={thread.viewportRef} style={{ height: Number(params.get('height') ?? 620), overflowY: 'auto', overflowAnchor: 'none' }}>
+ <div ref={thread.contentRef} style={{ padding: 12 }}>
+ <div aria-hidden style={{ height: Number(params.get('above') ?? 0) }} />
+ <ProjectConversation turns={turns} liveAssetId={active ? 'layout-turn' : null} liveTranscript={items}
+ liveActive={active} liveActivity={null} lastTurnRef={tail.lastTurnRef} />
+ </div>
+ </div>
+ </div>
+ </StickToBottomContext.Provider>
+ </ActAssetUrlContext.Provider>
+ );
+}
+
+setLanguage(new URLSearchParams(location.search).get('locale') ?? 'en');
+createRoot(document.getElementById('root')!).render(<Fixture />);
diff --git a/apps/desktop/bench/agent-sign-in.test.mjs b/apps/desktop/bench/agent-sign-in.test.mjs
new file mode 100644
index 0000000..e09ee9f
--- /dev/null
+++ b/apps/desktop/bench/agent-sign-in.test.mjs
@@ -0,0 +1,70 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { fileURLToPath } from 'node:url';
+import { createServer } from 'vite';
+import { chromium } from 'playwright-core';
+import shellConfig from '../shell/vite.config.ts';
+
+test('Settings allows cancelling sign-in and restores the login button on terminal-close updates', { timeout: 60_000 }, async () => {
+ const server = await createServer({
+ ...shellConfig, configFile: false, root: fileURLToPath(new URL('..', import.meta.url)),
+ server: { host: '127.0.0.1', port: 0 }, logLevel: 'error',
+ plugins: [...shellConfig.plugins, {
+ name: 'agent-sign-in-ui-fixture',
+ configureServer(app) {
+ app.middlewares.use('/agent-sign-in-ui', (_req, res, next) => {
+ res.setHeader('content-type', 'text/html');
+ void app.transformIndexHtml('/agent-sign-in-ui', '<!doctype html><html><body><div id="root"></div><script type="module" src="/bench/agent-sign-in.tsx"></script></body></html>')
+ .then((html) => res.end(html), next);
+ });
+ },
+ }],
+ });
+ let browser;
+ try {
+ await server.listen();
+ browser = await chromium.launch({ headless: true });
+ for (const locale of ['en', 'zh-CN']) {
+ const page = await browser.newPage({ viewport: { width: 960, height: 440 } });
+ const errors = [];
+ page.on('pageerror', (error) => errors.push(error.message));
+ await page.addInitScript((locale) => {
+ localStorage.setItem('openfilm.language', locale);
+ let agents = [{ id: 'qwen', name: 'Qwen Code', shown: true, status: 'waiting' }];
+ const listeners = new Set();
+ const calls = { cancel: 0, connect: 0, disconnect: 0 };
+ const publish = (status) => {
+ agents = [{ ...agents[0], status }];
+ for (const listener of listeners) listener(agents);
+ };
+ window.openfilmHost = { version: 1, agents: {
+ list: async () => agents,
+ connect: async () => { calls.connect++; publish('waiting'); return { ok: true }; },
+ cancelSignIn: async () => { calls.cancel++; publish('sign-in'); return { ok: true }; },
+ disconnect: async () => { calls.disconnect++; publish('off'); },
+ setShown: async () => {},
+ onChange: (listener) => { listeners.add(listener); return () => listeners.delete(listener); },
+ } };
+ window.agentSignInUiFixture = { closed: () => publish('sign-in'), calls };
+ }, locale);
+ await page.goto(`http://127.0.0.1:${server.httpServer.address().port}/agent-sign-in-ui`);
+ const cancel = page.getByRole('button', { name: locale === 'en' ? 'Cancel' : '取消', exact: true });
+ const login = page.getByRole('button', { name: locale === 'en' ? 'Sign in' : '登录', exact: true });
+ await cancel.click();
+ await login.waitFor();
+ assert.equal(await login.isEnabled(), true);
+ assert.deepEqual(await page.evaluate(() => window.agentSignInUiFixture.calls), { cancel: 1, connect: 0, disconnect: 0 });
+ await login.click();
+ await cancel.waitFor();
+ await page.evaluate(() => window.agentSignInUiFixture.closed());
+ await login.waitFor();
+ assert.equal(await login.isEnabled(), true, 'terminal-close state updates restore an enabled login button');
+ assert.equal(await cancel.count(), 0);
+ assert.deepEqual(errors, []);
+ await page.close();
+ }
+ } finally {
+ await browser?.close();
+ await server.close();
+ }
+});
diff --git a/apps/desktop/bench/agent-sign-in.tsx b/apps/desktop/bench/agent-sign-in.tsx
new file mode 100644
index 0000000..96cb888
--- /dev/null
+++ b/apps/desktop/bench/agent-sign-in.tsx
@@ -0,0 +1,7 @@
+/** Settings with a simulated agent bridge; no real terminal or sign-in is opened. */
+import React from 'react';
+import { createRoot } from 'react-dom/client';
+import { AgentsSection } from '../../../packages/openfilm/studio/ui/src/components/settings/AgentsSection';
+import '../shell/shell.css';
+
+createRoot(document.getElementById('root')!).render(<div style={{ padding: 24, maxWidth: 900 }}><AgentsSection /></div>);
diff --git a/apps/desktop/bench/model-options.test.mjs b/apps/desktop/bench/model-options.test.mjs
new file mode 100644
index 0000000..9742311
--- /dev/null
+++ b/apps/desktop/bench/model-options.test.mjs
@@ -0,0 +1,106 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { fileURLToPath } from 'node:url';
+import { createServer } from 'vite';
+import { chromium } from 'playwright-core';
+import shellConfig from '../shell/vite.config.ts';
+
+test('agent menus fetch efforts for the picked model, retain Default, and ignore an outdated probe', { timeout: 60_000 }, async () => {
+ const server = await createServer({
+ ...shellConfig, configFile: false, root: fileURLToPath(new URL('..', import.meta.url)),
+ server: { host: '127.0.0.1', port: 0 }, logLevel: 'error',
+ plugins: [...shellConfig.plugins, {
+ name: 'model-options-fixture',
+ configureServer(app) {
+ app.middlewares.use('/model-options', (_req, res, next) => {
+ res.setHeader('content-type', 'text/html');
+ void app.transformIndexHtml('/model-options', '<!doctype html><html><body><div id="root"></div><script type="module" src="/bench/model-options.tsx"></script></body></html>')
+ .then((html) => res.end(html), next);
+ });
+ },
+ }],
+ });
+ let browser;
+ try {
+ await server.listen();
+ browser = await chromium.launch({ headless: true });
+ for (const agent of ['opencode', 'cursor', 'copilot']) {
+ const page = await browser.newPage({ viewport: { width: 900, height: 650 }, reducedMotion: 'reduce' });
+ const errors = [];
+ page.on('pageerror', (e) => errors.push(e.message));
+ await page.goto(`http://127.0.0.1:${server.httpServer.address().port}/model-options?agent=${agent}`);
+ await page.waitForFunction(() => window.modelOptionsFixture?.state().options?.length);
+ await page.locator('[data-model-picker] button').first().click();
+ await page.locator('[data-agent-option="model"]').hover();
+ await page.getByRole('button', { name: 'Reasoning model', exact: true }).click();
+ await page.waitForFunction(() => window.modelOptionsFixture.state().options.some((o) => o.category === 'thought_level'));
+ assert.equal(await page.evaluate(() => window.modelOptionsFixture.calls.at(-1)), 'reasoning', 'the probe receives the model the user picked');
+ const effortId = await page.evaluate(() => window.modelOptionsFixture.effortId);
+ await page.locator(`[data-agent-option="${effortId}"]`).hover();
+ for (const choice of ['Default', 'Low', 'High', 'Max']) assert.equal(await page.getByRole('button', { name: choice, exact: true }).isVisible(), true);
+ await page.getByRole('button', { name: 'High', exact: true }).click();
+ assert.equal(await page.evaluate(() => {
+ const fixture = window.modelOptionsFixture;
+ return fixture.state().prefs[fixture.effortId];
+ }), 'high');
+ await page.evaluate(() => window.modelOptionsFixture.send());
+ assert.deepEqual(await page.evaluate(() => window.modelOptionsFixture.sent), [['model', 'reasoning'], [effortId, 'high'], ['prompt']], 'the selected model is applied before its effort and before sending');
+ if (agent === 'cursor') {
+ await page.evaluate(() => window.modelOptionsFixture.desync());
+ await page.evaluate(() => window.modelOptionsFixture.send());
+ assert.deepEqual(await page.evaluate(() => window.modelOptionsFixture.sent), [['model', 'reasoning'], [effortId, 'high'], ['prompt']], 'Cursor reasserts the model when the actual session no longer matches its cached state');
+ }
+ await page.evaluate(() => window.modelOptionsFixture.publish());
+ await page.getByRole('button', { name: 'Extra high', exact: true }).waitFor({ state: 'visible' });
+ await page.getByRole('button', { name: 'Default', exact: true }).click();
+ assert.equal(await page.evaluate(() => {
+ const fixture = window.modelOptionsFixture;
+ return fixture.state().prefs[fixture.effortId];
+ }), 'default', 'Default is sent to the agent to reset a previous effort');
+ await page.evaluate(() => window.modelOptionsFixture.send());
+ assert.deepEqual(await page.evaluate(() => window.modelOptionsFixture.sent), [...(agent === 'cursor' ? [['model', 'reasoning']] : []), [effortId, 'default'], ['prompt']], 'Default resets the effort on an existing conversation');
+ await page.locator('[data-agent-option="fast"]').hover();
+ await page.getByRole('button', { name: 'Fast', exact: true }).click();
+ assert.equal(await page.evaluate(() => window.modelOptionsFixture.state().prefs.fast), 'true');
+ await page.locator('[data-agent-option="model"]').hover();
+ await page.getByRole('button', { name: 'Auto', exact: true }).click();
+ assert.equal(await page.locator('[data-agent-option="fast"]').count(), 0, 'the old speed selector is hidden immediately on a model switch');
+ await page.waitForFunction(() => window.modelOptionsFixture.state().options.find((o) => o.category === 'model')?.currentValue === 'default');
+ assert.equal(await page.evaluate(() => window.modelOptionsFixture.state().prefs.model), 'default', 'Cursor Auto remains a valid native model selection');
+ assert.deepEqual(await page.evaluate(() => window.modelOptionsFixture.state().rawPrefs), { model: 'default' }, 'Auto does not inherit speed, context or effort from the previous model');
+ assert.equal(await page.evaluate(() => window.modelOptionsFixture.state().summary.effort), null, 'Auto is not mislabeled with a stale High effort');
+ if (agent === 'cursor') {
+ await page.locator('[data-agent-option="model"]').hover();
+ await page.getByRole('button', { name: 'Grok 4.7', exact: true }).click();
+ await page.waitForFunction(() => window.modelOptionsFixture.state().options.find((o) => o.category === 'model')?.currentValue === 'grok');
+ assert.equal(await page.locator('[data-agent-option="reasoning"]').count(), 0, 'the GPT reasoning parameter does not carry into Grok');
+ await page.locator('[data-agent-option="reasoning_effort"]').hover();
+ await page.getByRole('button', { name: 'Medium', exact: true }).click();
+ await page.evaluate(() => window.modelOptionsFixture.send());
+ assert.deepEqual(await page.evaluate(() => window.modelOptionsFixture.sent), [['model', 'grok'], ['reasoning_effort', 'medium'], ['prompt']], 'Grok receives its own effort id and no stale parameters');
+ }
+ await page.evaluate(() => {
+ window.modelOptionsFixture.model('reasoning');
+ window.modelOptionsFixture.model('plain');
+ });
+ await page.waitForFunction(() => window.modelOptionsFixture.state().options.find((o) => o.category === 'model')?.currentValue === 'plain');
+ assert.equal(await page.evaluate(() => window.modelOptionsFixture.state().options.some((o) => o.category === 'thought_level')), false, 'a model with no variants does not retain the old effort list');
+ assert.equal(await page.locator('[data-agent-option="fast"]').count(), 0, 'a model without a speed parameter has no speed row');
+ await page.evaluate(() => window.modelOptionsFixture.stale());
+ assert.deepEqual(await page.evaluate(() => window.modelOptionsFixture.state().prefs), { model: 'plain' }, 'unsupported settings from older saved preferences are excluded');
+ await page.evaluate(() => window.modelOptionsFixture.send());
+ assert.deepEqual(await page.evaluate(() => window.modelOptionsFixture.sent), [['model', 'plain'], ['prompt']], 'a model without parameters is sent no stale speed, effort or context');
+ assert.deepEqual(errors, []);
+ await page.close();
+ }
+ const page = await browser.newPage();
+ await page.goto(`http://127.0.0.1:${server.httpServer.address().port}/model-options?agent=cursor&legacy=1`);
+ await page.waitForFunction(() => window.modelOptionsFixture?.state().options?.some((o) => o.category === 'thought_level'));
+ assert.equal(await page.evaluate(() => window.modelOptionsFixture.state().prefs.model), 'reasoning');
+ assert.equal(await page.evaluate(() => window.modelOptionsFixture.state().prefs.reasoning), 'high', 'the old Cursor model selection retains its embedded effort');
+ await page.close();
+ } finally {
+ await browser?.close();
+ await server.close();
+ }
+});
diff --git a/apps/desktop/bench/model-options.tsx b/apps/desktop/bench/model-options.tsx
new file mode 100644
index 0000000..f3e0711
--- /dev/null
+++ b/apps/desktop/bench/model-options.tsx
@@ -0,0 +1,94 @@
+/** Real model menu and preference store; the fake bridge never starts an agent or sends a prompt. */
+import React from 'react';
+import { createRoot } from 'react-dom/client';
+import { ModelPopover } from '../chat/src/components/ModelPopover';
+import { agentModelSummary, agentOptions, effectivePrefs, useLocalAgents } from '../chat/src/state/local-agent-store';
+import { createLocalAgentTurn, runLocalAgentTurn } from '../chat/src/lib/local-agent-run';
+import type { LocalAgentId } from '../chat/src/lib/desktop-bridge';
+import '../shell/shell.css';
+import '../chat/src/chat.css';
+
+const agent = (new URLSearchParams(location.search).get('agent') ?? 'opencode') as LocalAgentId;
+const effortId = agent === 'cursor' ? 'reasoning' : agent === 'copilot' ? 'reasoning_effort' : 'effort';
+const roster = [{ id: agent, name: agent, shown: true, status: 'ready' as const }];
+const calls: Array<string | undefined> = [];
+const sent: unknown[] = [];
+let onEvent: (event: any) => void = () => {};
+const options = (model = 'plain') => [
+ { id: 'model', name: 'Model', category: 'model', currentValue: model, options: [
+ { value: 'plain', name: 'Plain model' }, { value: 'reasoning', name: 'Reasoning model' }, { value: 'default', name: 'Auto' },
+ ...(agent === 'cursor' ? [{ value: 'grok', name: 'Grok 4.7' }] : []),
+ ] },
+ ...(model === 'reasoning' ? [{ id: effortId, name: 'Effort', category: 'thought_level', currentValue: 'default', options: [
+ { value: 'default', name: 'Default' }, { value: 'low', name: 'Low' }, { value: 'high', name: 'High' }, { value: 'max', name: 'Max' },
+ ] }] : []),
+ ...(model === 'grok' ? [{ id: 'reasoning_effort', name: 'Effort', category: 'thought_level', currentValue: 'high', options: [
+ { value: 'low', name: 'Low' }, { value: 'medium', name: 'Medium' }, { value: 'high', name: 'High' },
+ ] }] : []),
+ ...(['reasoning', 'grok'].includes(model) ? [{ id: 'fast', name: 'Fast', category: 'model_config', currentValue: 'false', options: [
+ { value: 'false', name: 'Off' }, { value: 'true', name: 'Fast' },
+ ] }] : []),
+];
+let sessionOptions = options();
+(window as any).openfilmDesktop = {
+ agents: { list: async () => roster, onChange: () => () => {} },
+ localAgents: {
+ onEvent: (receive: typeof onEvent) => { onEvent = receive; return () => {}; },
+ start: async () => ({ ok: true, key: 'fake-session', info: { configOptions: sessionOptions } }),
+ setOption: async (_key: string, id: string, value: string) => {
+ sent.push([id, value]);
+ const option = sessionOptions.find((o) => o.id === id);
+ if (!option?.options.some((o) => o.value === value)) return { ok: false, error: 'Invalid params' };
+ sessionOptions = id === 'model' ? (option.currentValue === value ? sessionOptions : options(value))
+ : sessionOptions.map((o) => o.id === id ? { ...o, currentValue: value } : o);
+ return { ok: true, result: { configOptions: sessionOptions } };
+ },
+ prompt: async () => { sent.push(['prompt']); return { ok: true, stopReason: 'end_turn' }; },
+ probe: async (_agent: string, model?: string) => {
+ calls.push(model);
+ await new Promise((done) => setTimeout(done, model === 'reasoning' ? 150 : 10));
+ return { ok: true, info: { configOptions: options(model) } };
+ },
+ },
+};
+const legacy = agent === 'cursor' && new URLSearchParams(location.search).has('legacy');
+const legacyModel = 'reasoning[reasoning_effort=high]';
+useLocalAgents.setState({ picked: agent,
+ prefs: legacy ? { cursor: { model: legacyModel } } : {},
+ options: legacy ? { cursor: [{ id: 'model', name: 'Model', category: 'model', currentValue: legacyModel, options: [{ value: legacyModel, name: 'Reasoning model' }] }] } : {},
+ roster, hydrated: true });
+(window as any).modelOptionsFixture = {
+ agent, effortId, calls, sent,
+ desync: () => { sessionOptions = options('default'); },
+ stale: () => {
+ const state = useLocalAgents.getState();
+ useLocalAgents.setState({ prefs: { ...state.prefs, [agent]: { ...state.prefs[agent], fast: 'true', context: '256k', reasoning_effort: 'high' } } });
+ },
+ send: async () => {
+ const state = useLocalAgents.getState();
+ sent.length = 0;
+ return runLocalAgentTurn({ agent, projectId: 'fixture', conversation: 'fixture', cwd: '/fake', text: 'not sent to any agent',
+ turn: createLocalAgentTurn(`local:fixture-${Date.now()}`, agent),
+ options: effectivePrefs(state.prefs, agent, roster, state.options[agent]),
+ onOptions: (next) => useLocalAgents.getState().noteOptions(agent, next),
+ });
+ },
+ publish: () => {
+ onEvent({ key: 'fake-session', kind: 'update', update: { sessionUpdate: 'config_option_update', configOptions: sessionOptions.map((o) =>
+ o.category === 'thought_level' ? { ...o, options: [...o.options, { value: 'xhigh', name: 'Extra high' }] } : o) } });
+ },
+ state: () => {
+ const state = useLocalAgents.getState();
+ const visible = agentOptions(state, agent);
+ const prefs = effectivePrefs(state.prefs, agent, state.roster, visible);
+ return { options: state.options[agent], prefs, visible, summary: agentModelSummary(visible, prefs), rawPrefs: state.prefs[agent] };
+ },
+ model: (model: string) => useLocalAgents.getState().setPref(agent, 'model', model),
+};
+
+createRoot(document.getElementById('root')!).render(
+ <div className="of-chat" style={{ padding: 40, width: 480 }}>
+ <div data-model-picker><ModelPopover /></div>
+ <div id="of-chat-layer" className="of-chat" />
+ </div>,
+);
diff --git a/apps/desktop/bench/model-popover-layout.test.mjs b/apps/desktop/bench/model-popover-layout.test.mjs
new file mode 100644
index 0000000..37919ae
--- /dev/null
+++ b/apps/desktop/bench/model-popover-layout.test.mjs
@@ -0,0 +1,70 @@
+/** Measure the real menus at window edges, including options that arrive while the submenu is open. */
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { fileURLToPath } from 'node:url';
+import { createServer } from 'vite';
+import { chromium } from 'playwright-core';
+import shellConfig from '../shell/vite.config.ts';
+
+test('agent submenus stay inside the viewport as options and window dimensions change', { timeout: 60_000 }, async () => {
+ const server = await createServer({
+ ...shellConfig, configFile: false, root: fileURLToPath(new URL('..', import.meta.url)),
+ server: { host: '127.0.0.1', port: 0 }, logLevel: 'error',
+ plugins: [...shellConfig.plugins, {
+ name: 'model-popover-layout-fixture',
+ configureServer(app) {
+ app.middlewares.use('/model-popover-layout', (_req, res, next) => {
+ res.setHeader('content-type', 'text/html');
+ void app.transformIndexHtml('/model-popover-layout', '<!doctype html><html><body><div id="root"></div><script type="module" src="/bench/model-popover-layout.tsx"></script></body></html>')
+ .then((html) => res.end(html), next);
+ });
+ },
+ }],
+ });
+ let browser;
+ try {
+ await server.listen();
+ browser = await chromium.launch({ headless: true });
+ const page = await browser.newPage({ viewport: { width: 900, height: 650 }, reducedMotion: 'reduce' });
+ page.setDefaultTimeout(5000);
+ const errors = [];
+ page.on('pageerror', (error) => errors.push(error.message));
+ await page.goto(`http://127.0.0.1:${server.httpServer.address().port}/model-popover-layout`);
+ await page.locator('[data-model-picker] button').first().click();
+ const effort = page.locator('[data-agent-option="effort"]');
+ const side = page.getByRole('button', { name: 'Low', exact: true }).locator('..');
+ const settle = () => page.evaluate(() => new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(done))));
+ const assertInside = async (message) => {
+ await settle();
+ const rect = await side.boundingBox();
+ const { width, height } = page.viewportSize();
+ assert.ok(rect.x >= 7 && rect.y >= 7 && rect.x + rect.width <= width - 7 && rect.y + rect.height <= height - 7,
+ `${message}: ${JSON.stringify(rect)} in ${width} × ${height}`);
+ const card = await effort.locator('..').boundingBox();
+ assert.ok(rect.x >= card.x + card.width + 1, 'the submenu stays beside its parent card');
+ };
+ await settle();
+ await effort.hover();
+ await assertInside('initial menu near the bottom and right edges');
+ await page.evaluate(() => window.modelPopoverFixture.grow(3));
+ await assertInside('an open effort menu grows when new options arrive');
+ await page.setViewportSize({ width: 900, height: 360 });
+ await assertInside('only the viewport height shrinks');
+ await page.evaluate(() => window.modelPopoverFixture.grow(30));
+ await assertInside('a tall menu scrolls within the viewport');
+ assert.equal(await side.evaluate((el) => el.scrollHeight > el.clientHeight), true);
+ await page.getByRole('button', { name: 'Extra effort 30', exact: true }).click();
+ assert.equal(await effort.getAttribute('aria-expanded'), 'true', 'the last choice remains selectable');
+ await page.setViewportSize({ width: 340, height: 360 });
+ await assertInside('narrow window after choosing the last effort');
+ await page.locator('[data-agent-option="model"]').hover();
+ const modelMenu = page.getByRole('button', { name: 'A model with a much longer display name', exact: true }).locator('..');
+ await settle();
+ const modelRect = await modelMenu.boundingBox();
+ assert.ok(modelRect.x >= 7 && modelRect.x + modelRect.width <= 333, 'long model labels also stay within a narrow window');
+ assert.deepEqual(errors, []);
+ } finally {
+ await browser?.close();
+ await server.close();
+ }
+});
diff --git a/apps/desktop/bench/model-popover-layout.tsx b/apps/desktop/bench/model-popover-layout.tsx
new file mode 100644
index 0000000..54b8752
--- /dev/null
+++ b/apps/desktop/bench/model-popover-layout.tsx
@@ -0,0 +1,38 @@
+/** Real agent menu with local options only; no agents or model requests. */
+import React from 'react';
+import { createRoot } from 'react-dom/client';
+import { ModelPopover } from '../chat/src/components/ModelPopover';
+import { useLocalAgents } from '../chat/src/state/local-agent-store';
+import type { LocalAgentSessionInfo, RosterAgent } from '../chat/src/lib/desktop-bridge';
+import '../shell/shell.css';
+import '../chat/src/chat.css';
+
+const roster: RosterAgent[] = [
+ { id: 'codex', name: 'Codex', shown: true, status: 'ready' },
+ { id: 'claude', name: 'Claude Code', shown: true, status: 'missing' },
+ { id: 'cursor', name: 'Cursor', shown: true, status: 'ready' },
+ { id: 'codebuddy', name: 'CodeBuddy', shown: true, status: 'ready' },
+];
+const options = (extra = 0): NonNullable<LocalAgentSessionInfo['configOptions']> => [
+ { id: 'model', name: 'Model', category: 'model', currentValue: 'deepseek', options: [
+ { value: 'deepseek', name: 'Deepseek-V4.1-Flash' },
+ { value: 'long', name: 'A model with a much longer display name' },
+ ] },
+ { id: 'effort', name: 'Effort', category: 'thought_level', currentValue: 'low', options: [
+ { value: 'low', name: 'Low' }, { value: 'high', name: 'High' }, { value: 'max', name: 'Max' },
+ ...Array.from({ length: extra }, (_, i) => ({ value: `extra-${i}`, name: `Extra effort ${i + 1}` })),
+ ] },
+];
+useLocalAgents.setState({ picked: 'codebuddy', prefs: {}, options: { codebuddy: options() }, roster, hydrated: true });
+(window as any).modelPopoverFixture = {
+ grow: (extra: number) => useLocalAgents.getState().noteOptions('codebuddy', options(extra)),
+};
+
+createRoot(document.getElementById('root')!).render(
+ <>
+ <div className="of-chat" data-model-picker style={{ position: 'fixed', right: 16, bottom: 8, height: 'auto' }}>
+ <ModelPopover placement="top" align="end" />
+ </div>
+ <div id="of-chat-layer" className="of-chat" />
+ </>,
+);
diff --git a/apps/desktop/chat/src/App.tsx b/apps/desktop/chat/src/App.tsx
index 6fde7b9..a20ba31 100644
--- a/apps/desktop/chat/src/App.tsx
+++ b/apps/desktop/chat/src/App.tsx
@@ -679,8 +679,8 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projec
turn,
options: prefs,
meta,
+ onOptions: (options) => useLocalAgents.getState().noteOptions(agent, options),
onSessionInfo: (info) => {
- useLocalAgents.getState().noteOptions(agent, info.configOptions);
/* a session it could not take up again has none of the skills' pages from before: those of this message only */
const fresh = !info.resumed || info.sessionId !== resume;
if (info.sessionId && fresh) {
diff --git a/apps/desktop/chat/src/components/AgentActivityRow.tsx b/apps/desktop/chat/src/components/AgentActivityRow.tsx
index 0e45f9b..0c5e92e 100644
--- a/apps/desktop/chat/src/components/AgentActivityRow.tsx
+++ b/apps/desktop/chat/src/components/AgentActivityRow.tsx
@@ -24,7 +24,7 @@ import { WaitingContext } from '@/lib/developer';
* sight does not depend on anyone guarding a switch.
*
* No expandable input / output here, no ✓/✗. One row is one plain sentence. Acts finished back to back
- * fold into one row that opens on click, like Cursor's step summary.
+ * fold into one row that opens on click, including while they run, like Cursor's step summary.
*/
export interface AgentActivityItem {
@@ -57,7 +57,7 @@ export interface AgentActivityItem {
endedAt?: number;
}
-/** One folded run. Acts finished back to back form a group; text and the running row stand alone. */
+/** One folded run. Adjacent acts form a group from the start; text stands alone. */
interface ActivityRun {
items: AgentActivityItem[];
}
@@ -73,23 +73,20 @@ interface ActivityRun {
* `oldProps === newProps`, without comparing props.
*
* The inner map is bucketed by key because one row has different keys in different lists (live and
- * archived). The fold count is in the key too: when a run of repeated acts grows, only that row is
- * rebuilt, not the ones before it.
+ * archived). Member identities are checked too: completing any tool in a group must update its row.
*/
-const ROW_ELEMENTS = new WeakMap<AgentActivityItem, Map<string, React.ReactElement>>();
+const ROW_ELEMENTS = new WeakMap<AgentActivityItem, Map<string, { items: AgentActivityItem[]; element: React.ReactElement }>>();
function rowElement(run: ActivityRun, key: string): React.ReactElement {
const first = run.items[0]!;
let byKey = ROW_ELEMENTS.get(first);
if (!byKey) { byKey = new Map(); ROW_ELEMENTS.set(first, byKey); }
- // An asset can arrive late (the saved transcript fills in a receipt the live stream missed) with the count unchanged, so the asset count is in the key too.
- let assets = 0;
- for (const item of run.items) if (item.asset) assets += 1;
- const cacheKey = `${key}#${run.items.length}#${assets}`;
+ const cacheKey = `${key}#${run.items.length}`;
const hit = byKey.get(cacheKey);
- if (hit) return hit;
+ // A later member can finish or gain an asset while the first member and the group size stay unchanged.
+ if (hit && hit.items.every((item, index) => item === run.items[index])) return hit.element;
const made = <AgentActivityRow key={key} items={run.items} />;
- byKey.set(cacheKey, made);
+ byKey.set(cacheKey, { items: run.items, element: made });
return made;
}
@@ -294,11 +291,11 @@ const ACT_ICONS: Record<string, LucideIcon> = {
};
/**
- * A folded group of finished acts.
+ * A folded group of adjacent acts, running or finished.
*
* Closed by default. The summary says which kinds of act ran and how many of each (see actGroupParts);
- * the pictures and sounds the group made stay in the rows of the acts that made them. The running row is
- * not in here; it uses the progressive form and shimmers.
+ * the pictures and sounds the group made stay in the rows of the acts that made them. Pending acts join
+ * the group from the start, so finishing updates its label without replacing the row.
*
* Opening changes the content height. The asset drawer pins the bottom (pinIfFollowing in the same
* frame); here the clicked row must stay put instead: skip the next bottom pin and, in the same frame,
@@ -312,19 +309,23 @@ function ActGroup({ items }: { items: AgentActivityItem[] }) {
const thread = React.useContext(StickToBottomContext);
const rootRef = React.useRef<HTMLDivElement>(null);
const anchorTop = React.useRef<number | null>(null);
- /* Closed until the user opens it — also while the turn runs. The summary counts up in place and the
- status line under the turn says what is running, so unrolling each finished act only made a wall of rows. */
+ /* Closed until the user opens it — also while the turn runs. The summary counts up in place without
+ unrolling a wall of rows or moving a tool from the status line when it finishes. */
const [picked, setPicked] = React.useState<boolean | null>(null);
const open = picked ?? false;
const parts = React.useMemo(() => actGroupParts(items), [items]);
/* At most three kinds, the rest as a count: seven or eight cut off by an ellipsis tell the reader nothing. */
const shown = parts.slice(0, GROUP_PARTS_MAX);
const rest = parts.slice(GROUP_PARTS_MAX).reduce((n, part) => n + part.count, 0);
- const summary = shown
- .map((part) => `${t(actCopyKey(part.label, false))}${part.count > 1 ? ` ×${part.count}` : ''}`)
- .join(' · ');
+ const pendingLabels = new Set(items.filter((item) => item.pending).map((item) => item.label));
+ const pending = pendingLabels.size > 0;
+ const since = items.reduce<number | undefined>((start, item) => item.pending && item.startedAt != null
+ ? Math.min(start ?? item.startedAt, item.startedAt) : start, undefined);
const full = parts
- .map((part) => `${t(actCopyKey(part.label, false))}${part.count > 1 ? ` ×${part.count}` : ''}`)
+ .map((part) => `${t(actCopyKey(part.label, pendingLabels.has(part.label)))}${part.count > 1 ? ` ×${part.count}` : ''}`)
+ .join(' · ');
+ const summary = shown
+ .map((part) => `${t(actCopyKey(part.label, pendingLabels.has(part.label)))}${part.count > 1 ? ` ×${part.count}` : ''}`)
.join(' · ');
const Icon = ACT_ICONS[parts[0]?.label ?? ''] ?? Layers;
@@ -355,15 +356,21 @@ function ActGroup({ items }: { items: AgentActivityItem[] }) {
aria-expanded={open}
onClick={toggle}
title={full}
- className="group/act flex max-w-full min-w-0 items-start gap-2 text-left text-[14px] leading-relaxed text-[var(--chat-hint)] hover:text-[var(--chat-text)]"
+ data-activity-header=""
+ data-activity-id={items[0]?.id}
+ aria-busy={pending}
+ className="group/act flex h-6 w-full min-w-0 items-center gap-2 text-left text-[14px] leading-6 text-[var(--chat-hint)] hover:text-[var(--chat-text)]"
>
- <Icon size={13} aria-hidden className="mt-[5px] shrink-0" />
- <span className="min-w-0 truncate">{summary}</span>
+ <Icon size={13} aria-hidden className="shrink-0" />
+ <span data-activity-label="" className="min-w-0 truncate">{summary}</span>
{rest ? <span className="shrink-0 tabular-nums opacity-80">+{rest}</span> : null}
+ <span className="ml-auto flex w-12 shrink-0 justify-end">
+ {pending ? <PendingElapsed startedAt={since} /> : null}
+ </span>
<ChevronRight
size={13}
aria-hidden
- className={`mt-[5px] shrink-0 transition-[transform,opacity] ${open ? 'rotate-90 opacity-100' : 'opacity-0 group-hover/act:opacity-100 group-focus-visible/act:opacity-100'}`}
+ className={`shrink-0 transition-[transform,opacity] ${open ? 'rotate-90 opacity-100' : 'opacity-0 group-hover/act:opacity-100 group-focus-visible/act:opacity-100'}`}
/>
</button>
{open ? (
@@ -384,28 +391,28 @@ function ActGroup({ items }: { items: AgentActivityItem[] }) {
* does not code; the agent usually fixes it next, and a red cross only suggests the film is broken. When
* the turn really fails, a generic message shows above the composer.
*
- * A running row animates one thing only, the shimmer on its title: several animations per row, over ten
- * rows, read like a dashboard alarm.
+ * The same row stays in place from start to finish. Only its label and clock change; typography, icon,
+ * spacing stay the same. The description follows the visible label, without invisible text reserving a gap.
*
* The description (a narration line, a sound or picture description) is film content: it gets quotes and
* reads apart from the act name. What the act made hangs under the row: images as thumbnails, sounds play
* on click.
*/
function ActRow({ item }: { item: AgentActivityItem }) {
- const t = useT();
const Icon = ACT_ICONS[item.label];
return (
- <div className="flex min-w-0 items-start gap-2 py-1 text-[14px] leading-relaxed">
+ <div className="flex min-w-0 items-start gap-2 py-1 text-[14px] leading-6">
{Icon ? (
<Icon size={13} aria-hidden className="mt-[5px] shrink-0 text-[var(--chat-hint)]" />
) : null}
<div className="min-w-0 flex-1">
<div
- className="flex max-w-full min-w-0 items-baseline gap-1.5 text-left"
+ data-activity-header=""
+ data-activity-id={item.id}
+ aria-busy={!!item.pending}
+ className="flex h-6 max-w-full min-w-0 items-center gap-1.5 text-left"
>
- <span className={item.pending ? 'text-sweep shrink-0' : 'shrink-0 text-[var(--chat-hint)]'}>
- {t(actCopyKey(item.label, item.pending))}
- </span>
+ <ActivityLabel label={item.label} pending={!!item.pending} />
{item.query ? (
<span className="min-w-0 truncate text-[var(--chat-hint)] opacity-80" title={item.query}>
“{item.query}”
@@ -417,7 +424,10 @@ function ActRow({ item }: { item: AgentActivityItem }) {
{item.detail}
</span>
) : null}
- {item.pending ? <PendingElapsed startedAt={item.startedAt} /> : null}
+ {/* Reserve the clock's width after completion so long commands keep the same truncation. */}
+ <span className="ml-auto flex w-12 shrink-0 justify-end">
+ {item.pending ? <PendingElapsed startedAt={item.startedAt} /> : null}
+ </span>
</div>
{item.asset ? <AssetPreview asset={item.asset} /> : null}
{item.ask?.status ? <AskOutcome ask={item.ask} /> : null}
@@ -426,6 +436,16 @@ function ActRow({ item }: { item: AgentActivityItem }) {
);
}
+/** Keep both states in the same type style, using only the visible words' width. */
+function ActivityLabel({ label, pending }: { label: string; pending: boolean }) {
+ const t = useT();
+ return (
+ <span data-activity-label="" className="min-w-0 shrink-0 truncate text-[var(--chat-hint)]">
+ {t(actCopyKey(label, pending))}
+ </span>
+ );
+}
+
/** After a question: the answer (verbatim), or skipped / timed out, in which case the agent went on with its own judgment. */
function AskOutcome({ ask }: { ask: NonNullable<AgentActivityItem['ask']> }) {
const t = useT();
@@ -608,16 +628,14 @@ function togglePlayer(url: string, owner: string): void {
/**
* While a turn runs, the single row underneath: what is happening now.
*
- * It stays from start to finish, always one row high, and only its text changes, which keeps the
- * panel from jumping.
+ * A visible status has its own row above the hover actions. When there is nothing to say, render nothing
+ * rather than an empty row separating the reply from its copy button and model name.
*
- * · work running: that act (with its description or command when there is one); several in
- * parallel read "Narrate ×7 · Sound effect ×6";
+ * · work running: nothing, because the tool already has its row in the conversation;
* · thinking: "Thinking";
* · neither: the caller's text (reconnecting and the like), else "Thinking".
*
- * The clock counts from the earliest start among the running acts. When the turn ends this row becomes
- * the footer, at the same height (h-6). `ownAgent`: the turn runs on the app's own agent (see IdleStatus).
+ * `ownAgent`: the turn runs on the app's own agent (see IdleStatus).
*/
export function StatusLine({ items, fallback, ownAgent = false }: { items: AgentActivityItem[]; fallback?: string | null; ownAgent?: boolean }) {
const t = useT();
@@ -631,34 +649,20 @@ export function StatusLine({ items, fallback, ownAgent = false }: { items: Agent
if (waitingForYou) return <StatusShell Icon={MessageCircleQuestion} label={t('act.waitingForYou')} since={changedAt} waiting />;
const acts = running.filter((item) => item.kind === 'act');
if (acts.length) {
- const parts = actGroupParts(acts);
- const label = parts.slice(0, GROUP_PARTS_MAX)
- .map((part) => `${t(part.label)}${part.count > 1 ? ` ×${part.count}` : ''}`)
- .join(' · ');
- const extra = acts.length === 1 ? (acts[0]!.query ? `“${acts[0]!.query}”` : acts[0]!.detail) : undefined;
- let since: number | undefined;
- for (const item of acts) if (item.startedAt != null && (since == null || item.startedAt < since)) since = item.startedAt;
- /* Only waiting on the person's answer: that time is theirs, not the agent's work — no clock, no sweep. */
- const waiting = acts.every((item) => item.label === 'act.chat.ask');
- return <StatusShell Icon={ACT_ICONS[parts[0]!.label]} label={label} extra={extra} since={since ?? changedAt} waiting={waiting} />;
+ return null;
}
if (running.length || fallback) {
return <StatusShell label={running.length ? t('act.thinking') : fallback!} since={changedAt} />;
}
- /* The agent is speaking (text still streaming): no "Working" underneath, the text itself moves. The row
- keeps its height so what comes next does not jump. Just after a paragraph, stay blank a while (the
- seconds spent wrapping up a turn, or an act about to start) and say "Working" only once it is quiet. */
+ /* The agent is speaking (text still streaming): no "Working" underneath, the text itself moves. Just after a
+ paragraph, say nothing for a while (the seconds spent wrapping up a turn, or an act about to start)
+ and say "Working" only once it is quiet. */
let last: AgentActivityItem | undefined;
for (let i = items.length - 1; i >= 0; i -= 1) if (items[i]!.kind !== 'notice') { last = items[i]; break; }
- if (last?.kind === 'text' && last.pending) return <StatusBlank />;
+ if (last?.kind === 'text' && last.pending) return null;
return <IdleStatus since={changedAt} quietFirst={last?.kind === 'text'} ownAgent={ownAgent} />;
}
-/** The status row's empty slot: same height, says nothing. */
-function StatusBlank() {
- return <div role="status" aria-hidden className="h-6" />;
-}
-
/** How long after a paragraph before saying "Working". */
const AFTER_TEXT_MS = 5_000;
@@ -678,7 +682,7 @@ function IdleStatus({ since, quietFirst = false, ownAgent = false }: { since: nu
const t = useT();
const tick = useTick();
const idle = (tick ?? Date.now()) - since;
- if (quietFirst && idle < AFTER_TEXT_MS) return <StatusBlank />;
+ if (quietFirst && idle < AFTER_TEXT_MS) return null;
const label = idleStatus(idle, ownAgent);
return <StatusShell label={t(label)} extra={label === 'act.waitingForModel' ? t('act.waitingForModelHint') : undefined} plain since={since} />;
}
diff --git a/apps/desktop/chat/src/components/ModelPopover.tsx b/apps/desktop/chat/src/components/ModelPopover.tsx
index d119c98..7c0e283 100644
--- a/apps/desktop/chat/src/components/ModelPopover.tsx
+++ b/apps/desktop/chat/src/components/ModelPopover.tsx
@@ -75,7 +75,7 @@ export function ModelPopover({ placement = 'bottom', align = 'start', agent: con
const [open, setOpen] = React.useState(false);
/** the option whose side menu is open */
const [side, setSide] = React.useState<string | null>(null);
- /** how far the card has slid left to make room for a side menu: it only grows while the menu is open */
+ /** how far the card has slid left to make room for a side menu; kept within the window on resize */
const [cardShift, setCardShift] = React.useState(0);
const [sideStyle, setSideStyle] = React.useState<React.CSSProperties | null>(null);
const cardRef = React.useRef<HTMLDivElement | null>(null);
@@ -147,30 +147,58 @@ export function ModelPopover({ placement = 'bottom', align = 'start', agent: con
/* a fixed row's one value is already the one in use */
const pickChoice = (o: Option, value: unknown) => { if (!o.fixed) { la.setPref(agent, o.id, value); onPref?.(agent, o.id, value); } };
- /* the side menu beside its row: on the right of the card, the card sliding left when the window is too narrow for
- both, and over the card's right edge only when it cannot slide far enough; measured again once it is drawn */
+ /* Keep the side menu beside its row and inside the window, including when an agent adds choices while it is open
+ or the window's height changes. Measure again after width/height constraints change the rendered menu. */
const sidePainted = sideStyle !== null;
React.useLayoutEffect(() => {
const card = cardRef.current;
const row = choosing ? rowRefs.current[choosing.id] : null;
- if (!open || !choosing || !card || !row) { setSideStyle(null); return; }
- const c = card.getBoundingClientRect();
const el = sideRef.current;
- const sideMax = Math.max(0, room - c.width);
- const w = Math.min(sideMax, Math.max(SIDE_MIN_W, el?.offsetWidth ?? SIDE_MIN_W));
- const h = el?.offsetHeight ?? 8 + (choosing.options?.length ?? 0) * 28;
- const width = window.innerWidth;
- const height = window.innerHeight;
- let left = c.right + SIDE_GAP;
- const need = left + w - (width - EDGE);
- if (need > 0) {
- const slide = Math.min(need, Math.max(0, c.left - EDGE));
- if (slide > 0) setCardShift((s) => s + slide);
- left = Math.max(EDGE, Math.min(left - slide, width - EDGE - w));
- }
- let top = row.getBoundingClientRect().top - 4;
- if (top + h > height - EDGE) top = Math.max(EDGE, height - EDGE - h);
- setSideStyle({ position: 'fixed', left, top, zIndex: 10001, minWidth: Math.min(SIDE_MIN_W, sideMax), width: 'max-content', maxWidth: sideMax, maxHeight: height - 2 * EDGE });
+ if (!open || !choosing || !card || !row || !el) { setSideStyle(null); return; }
+ const update = () => {
+ const c = card.getBoundingClientRect();
+ const width = window.innerWidth;
+ const height = window.innerHeight;
+ const sideMax = Math.max(0, width - 2 * EDGE - SIDE_GAP - c.width);
+ const minWidth = Math.min(SIDE_MIN_W, sideMax);
+ const maxHeight = Math.max(0, height - 2 * EDGE);
+ const w = Math.min(sideMax, Math.max(minWidth, el.offsetWidth));
+ const h = Math.min(el.offsetHeight, maxHeight);
+ const baseLeft = c.left + cardShift;
+ let shift = Math.min(cardShift, Math.max(0, baseLeft - EDGE));
+ let left = c.right + cardShift - shift + SIDE_GAP;
+ const need = left + w - (width - EDGE);
+ if (need > 0) {
+ const slide = Math.min(need, Math.max(0, baseLeft - shift - EDGE));
+ shift += slide;
+ left -= slide;
+ }
+ if (shift !== cardShift) setCardShift(shift);
+ left = Math.max(EDGE, Math.min(left, width - EDGE - w));
+ const top = Math.max(EDGE, Math.min(row.getBoundingClientRect().top - 4, height - EDGE - h));
+ setSideStyle((previous) => previous?.left === left && previous.top === top && previous.minWidth === minWidth
+ && previous.maxWidth === sideMax && previous.maxHeight === maxHeight ? previous
+ : { position: 'fixed', left, top, zIndex: 10001, minWidth, width: 'max-content', maxWidth: sideMax, maxHeight });
+ };
+ update();
+ const observer = new ResizeObserver(update);
+ observer.observe(el);
+ observer.observe(card);
+ observer.observe(row);
+ // The parent Popover also moves on resize/scroll. Read after its React update has committed.
+ let frame = 0;
+ const schedule = () => {
+ window.cancelAnimationFrame(frame);
+ frame = window.requestAnimationFrame(update);
+ };
+ window.addEventListener('resize', schedule);
+ window.addEventListener('scroll', schedule, true);
+ return () => {
+ observer.disconnect();
+ window.cancelAnimationFrame(frame);
+ window.removeEventListener('resize', schedule);
+ window.removeEventListener('scroll', schedule, true);
+ };
// eslint-disable-next-line react-hooks/exhaustive-deps -- keyed by the open row
}, [open, choosing?.id, cardShift, sidePainted, room]);
@@ -270,7 +298,7 @@ export function ModelPopover({ placement = 'bottom', align = 'start', agent: con
) : rows.map((o, i) => (
<React.Fragment key={o.id}>
{i > 0 ? <div className="mx-1 my-0.5 h-px bg-[var(--border)]" /> : null}
- <button type="button" ref={(el) => { rowRefs.current[o.id] = el; }} aria-haspopup="menu" aria-expanded={side === o.id}
+ <button type="button" data-agent-option={o.id} ref={(el) => { rowRefs.current[o.id] = el; }} aria-haspopup="menu" aria-expanded={side === o.id}
onMouseDown={keepFocus} onMouseEnter={() => showSide(o.id)} onMouseLeave={hideSideSoon} onFocus={() => showSide(o.id)}
onClick={() => showSide(o.id)}
className={`${ROW_BASE} ${side === o.id ? 'bg-[var(--bg-hover)]' : 'hover:bg-[var(--bg-hover)]'}`}>
diff --git a/apps/desktop/chat/src/components/ProjectConversation.tsx b/apps/desktop/chat/src/components/ProjectConversation.tsx
index 67cd4b1..06b4adb 100644
--- a/apps/desktop/chat/src/components/ProjectConversation.tsx
+++ b/apps/desktop/chat/src/components/ProjectConversation.tsx
@@ -405,8 +405,8 @@ const ConversationTurn = React.memo(function ConversationTurn({
turns it off). No "version N · switch to it" link: going back belongs to the top bar's history. */}
{settled && showChanges && entry.fileChanges?.length ? <FileChangesList changes={entry.fileChanges} /> : null}
- {/* Still running: one status line, always one line high, only its text changes (see StatusLine), and the
- footer under it on hover (its Log is the turn so far). Done, the footer alone. Always there, in one place
+ {/* The status and hover actions occupy separate rows. An empty status takes no room; a visible status
+ stays above the complete footer, including on hover and focus. The footer stays in one place
in the tree: a log opened from it stays open as the turn finishes. An interruption doesn't
show Failed here: the reason and Resume appear above the composer (the last turn's, even after a
restart); an older one's reason is on its footer's Interrupted, on hover. */}
@@ -649,14 +649,13 @@ function CopyButton({ text }: { text: string }) {
/**
* The line under a reply: copy, who answered (icon only) · the model · how long ago, and how it stopped if it
- * didn't finish normally. While it runs, under the status line: copy what it said so far, its log so far, who.
+ * didn't finish normally. While it runs, on hover below the status: copy what it said so far, its log so far, who.
*
* Several agents can answer in one project and their replies look alike, so the footer says which one. A stopped
* turn says so, or a reply cut short leaves the reader unsure whether it finished, broke or was stopped.
*
- * As in Claude, it appears on hover over the reply and keeps its space (h-6, as tall as the status line while
- * running, so the bottom edge stays put when one replaces the other). The time is how long ago; how long it
- * worked is in the "Worked …" line.
+ * It appears on hover over the reply and keeps its space (h-6), independently of the status above it.
+ * The time is how long ago; how long it worked is in the "Worked …" line.
*/
function TurnFooter({ entry, items, running = false }: { entry: ProjectVersion; items: TranscriptItem[] | null; running?: boolean }) {
const t = useT();
@@ -677,8 +676,7 @@ function TurnFooter({ entry, items, running = false }: { entry: ProjectVersion;
const project = React.useContext(ChatProjectContext);
return (
- /* -mt-1.5: the footer belongs to the reply above it — close to it, not a row of its own */
- <div className={`-mt-1.5 flex h-6 min-w-0 items-center gap-1.5 text-[11.5px] text-[var(--chat-hint)] group-hover/reply:opacity-100 ${HOVER_LINE}`}>
+ <div data-turn-footer="" className={`-mt-1.5 flex h-6 min-w-0 items-center gap-1.5 text-[11.5px] text-[var(--chat-hint)] group-hover/reply:opacity-100 ${HOVER_LINE}`}>
{answer ? <CopyButton text={answer} /> : null}
{/* developer mode (Settings → Developer): the turn as it happened, every event; while it runs, as it goes */}
{developer && project && !isPendingAssetId(entry.assetId) ? <TurnLogButton project={project} turnId={entry.assetId} live={running} /> : null}
diff --git a/apps/desktop/chat/src/components/useStickToBottom.ts b/apps/desktop/chat/src/components/useStickToBottom.ts
index 3cdfe6e..b256165 100644
--- a/apps/desktop/chat/src/components/useStickToBottom.ts
+++ b/apps/desktop/chat/src/components/useStickToBottom.ts
@@ -69,7 +69,9 @@ export const StickToBottomContext = React.createContext<StickToBottom | null>(nu
*
* Finished tool rows collapse into a summary while the answer keeps growing; that
* shrink would make the bottom-pinned view bounce back. So the running turn gets a
- * min-height equal to the tallest it has been, released when the run ends.
+ * min-height equal to the tallest it has been. Keep it when the run ends too: removing
+ * the status row must not pull the reply down in a bottom-pinned view. The next turn
+ * (or a viewport resize) releases it.
*
* The min-height only applies when the turn shrinks, so it is never a frame late: the
* value was recorded while the turn grew.
@@ -91,11 +93,10 @@ export function useTailSpacer(
if (!viewport || !node) return;
const size = `${viewport.clientWidth}:${viewport.clientHeight}`;
if (viewportSize.current !== size) { tallest.current = 0; viewportSize.current = size; }
- let min = 0;
if (activeRef.current) {
tallest.current = Math.max(tallest.current, node.getBoundingClientRect().height);
- min = Math.max(min, Math.floor(tallest.current));
- } else tallest.current = 0;
+ }
+ const min = Math.floor(tallest.current);
const next = min > 0 ? `${min}px` : '';
if (node.style.minHeight !== next) {
node.style.minHeight = next;
diff --git a/apps/desktop/chat/src/i18n/index.ts b/apps/desktop/chat/src/i18n/index.ts
index 9ef604b..9c45b5a 100644
--- a/apps/desktop/chat/src/i18n/index.ts
+++ b/apps/desktop/chat/src/i18n/index.ts
@@ -32,11 +32,18 @@ export function useUiLocale(): UiLocale {
return React.useSyncExternalStore(subscribe, () => language, () => 'en' as UiLocale);
}
+function say(locale: UiLocale, path: string): string {
+ const said = locale === 'en' ? null : lookup(TABLES[locale], path);
+ return said && said !== path ? said : lookup(enUS, path);
+}
+
/** t('project.stop'), in the language shown. */
export function useT(): (path: string) => string {
const now = useUiLocale();
- return React.useCallback((path: string) => {
- const said = now === 'en' ? null : lookup(TABLES[now], path);
- return said && said !== path ? said : lookup(enUS, path);
- }, [now]);
+ return React.useCallback((path: string) => say(now, path), [now]);
+}
+
+/** The same outside a component (an error made in lib/), in the language shown now. */
+export function translate(path: string): string {
+ return say(language, path);
}
diff --git a/apps/desktop/chat/src/i18n/locales/en-US.ts b/apps/desktop/chat/src/i18n/locales/en-US.ts
index ff34e2c..aecd92b 100644
--- a/apps/desktop/chat/src/i18n/locales/en-US.ts
+++ b/apps/desktop/chat/src/i18n/locales/en-US.ts
@@ -117,6 +117,9 @@ export const enUS = {
},
agent: {
contextCompacted: 'Earlier conversation folded into a summary',
+ modelGone: 'This agent no longer offers {model}. Choose a model again.',
+ settingFailed: 'Couldn’t set {setting} to {value}: {error}',
+ settingRejected: 'The agent couldn’t apply this setting.',
thinking: 'Thinking',
},
assets: {
diff --git a/apps/desktop/chat/src/i18n/locales/es.ts b/apps/desktop/chat/src/i18n/locales/es.ts
index b871dfb..8ca2640 100644
--- a/apps/desktop/chat/src/i18n/locales/es.ts
+++ b/apps/desktop/chat/src/i18n/locales/es.ts
@@ -117,6 +117,9 @@ export const es: Words = {
},
agent: {
contextCompacted: 'La conversación anterior se resumió',
+ modelGone: 'Este agente ya no ofrece {model}. Vuelve a elegir un modelo.',
+ settingFailed: 'No se pudo poner {setting} en {value}: {error}',
+ settingRejected: 'El agente no pudo aplicar este ajuste.',
thinking: 'Pensando',
},
assets: {
diff --git a/apps/desktop/chat/src/i18n/locales/ja.ts b/apps/desktop/chat/src/i18n/locales/ja.ts
index b2a9391..17fdafc 100644
--- a/apps/desktop/chat/src/i18n/locales/ja.ts
+++ b/apps/desktop/chat/src/i18n/locales/ja.ts
@@ -117,6 +117,9 @@ export const ja: Words = {
},
agent: {
contextCompacted: 'これまでの会話を要約にまとめました',
+ modelGone: 'このエージェントでは {model} を使えなくなりました。モデルを選び直してください。',
+ settingFailed: '{setting} を {value} に設定できませんでした: {error}',
+ settingRejected: 'エージェントがこの設定を適用できませんでした。',
thinking: '考え中',
},
assets: {
diff --git a/apps/desktop/chat/src/i18n/locales/ko.ts b/apps/desktop/chat/src/i18n/locales/ko.ts
index 9e7ac14..4942ea4 100644
--- a/apps/desktop/chat/src/i18n/locales/ko.ts
+++ b/apps/desktop/chat/src/i18n/locales/ko.ts
@@ -113,6 +113,9 @@ export const ko: Words = {
},
agent: {
contextCompacted: '이전 대화를 요약으로 정리했습니다',
+ modelGone: '이 에이전트는 더 이상 {model}을(를) 제공하지 않습니다. 모델을 다시 선택하세요.',
+ settingFailed: '{setting}을(를) {value}(으)로 설정하지 못했습니다: {error}',
+ settingRejected: '에이전트가 이 설정을 적용하지 못했습니다.',
thinking: '생각하는 중',
},
assets: {
diff --git a/apps/desktop/chat/src/i18n/locales/zh-CN.ts b/apps/desktop/chat/src/i18n/locales/zh-CN.ts
index 82bca96..fd893d3 100644
--- a/apps/desktop/chat/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/chat/src/i18n/locales/zh-CN.ts
@@ -117,6 +117,9 @@ export const zhCN: Words = {
},
agent: {
contextCompacted: '之前的对话已折叠为摘要',
+ modelGone: '这个智能体已不再提供 {model},请重新选择模型。',
+ settingFailed: '无法将 {setting} 设为 {value}:{error}',
+ settingRejected: '智能体无法应用这项设置。',
thinking: '正在思考',
},
assets: {
diff --git a/apps/desktop/chat/src/lib/agent-activity-runs.ts b/apps/desktop/chat/src/lib/agent-activity-runs.ts
index bf1b63b..a5ba7ea 100644
--- a/apps/desktop/chat/src/lib/agent-activity-runs.ts
+++ b/apps/desktop/chat/src/lib/agent-activity-runs.ts
@@ -8,9 +8,9 @@ import type { AgentActAsset } from '@openfilm/shared';
* everything below; with many actions in parallel the list jumps up and down.
*
* So:
- * · running actions are not in the list; they live in the single status row under the turn (see pendingWork),
- * one row high throughout, its content changing in place;
- * · finished actions between two messages fold into one row; new ones merge in and the row updates in place;
+ * · actions appear in the list from the moment they start, in the same row and group when they finish;
+ * · adjacent actions between two messages fold into one row, including pending actions, so completing an
+ * action never moves it out of the status line or merges away a row;
* · the agent's messages, plans and notices each get a row.
*
* Some are only status words, not work (thinking, working, planning, reconnecting): shown in the status row
@@ -48,25 +48,25 @@ function isEphemeral(item: ActivityRunItem): boolean {
const STANDALONE_ACT_LABELS = new Set(['act.chat.ask']);
/**
- * Finished work (tool calls). It folds into one summary row, including steps that made something (voice, sound,
+ * Work (tool calls). It folds into one summary row, including steps that made something (voice, sound,
* music, an image, a frame), so a turn with many of them doesn't push the answer away. Expanded, each result still
* hangs under the row that made it.
*/
-function isFinishedWork(item: ActivityRunItem): boolean {
- return item.kind === 'act' && !item.pending && !isEphemeral(item)
+function isWork(item: ActivityRunItem): boolean {
+ return item.kind === 'act' && !isEphemeral(item)
&& !(item.label != null && STANDALONE_ACT_LABELS.has(item.label));
}
export function buildRuns<T extends ActivityRunItem>(items: T[]): ActivityRun<T>[] {
const runs: ActivityRun<T>[] = [];
- /* Whether the last run is finished work. Only the last run matters, so one flag is enough; this runs every frame
+ /* Whether the last run is work. Only the last run matters, so one flag is enough; this runs every frame
while live and must not rescan the run on every merge. */
let lastIsWork = false;
for (const item of items) {
- /* Running actions take no row; status words (thinking, working…) vanish when done */
- if (item.kind === 'thought' || (item.kind === 'act' && (item.pending || isEphemeral(item)))) continue;
+ /* Status words (thinking, working…) stay in the status line, not the tool list. */
+ if (item.kind === 'thought' || isEphemeral(item)) continue;
const last = runs[runs.length - 1];
- const work = isFinishedWork(item);
+ const work = isWork(item);
if (last && lastIsWork && work) {
last.items.push(item);
continue;
diff --git a/apps/desktop/chat/src/lib/agent-menu-rows.ts b/apps/desktop/chat/src/lib/agent-menu-rows.ts
index a697a00..8f48788 100644
--- a/apps/desktop/chat/src/lib/agent-menu-rows.ts
+++ b/apps/desktop/chat/src/lib/agent-menu-rows.ts
@@ -16,7 +16,7 @@ export const isSpeed = (o: MenuOption) => o.category === 'speed' || /^(fast|fast
/**
* The rows the menu shows, in this order: the model and the reasoning effort, always, and the speed when the model has
- * one. A model or an effort the agent offers no choice of (GitHub Copilot picks its own) is a row all the same, its one
+ * one. A model or an effort the agent currently offers no choice of is a row all the same, its one
* value `fixed`: `defaultName` when the agent names none.
*/
export function menuOptions(options: MenuOption[] | undefined, defaultName: string): MenuOption[] {
diff --git a/apps/desktop/chat/src/lib/desktop-bridge.ts b/apps/desktop/chat/src/lib/desktop-bridge.ts
index f2db756..3ddbf63 100644
--- a/apps/desktop/chat/src/lib/desktop-bridge.ts
+++ b/apps/desktop/chat/src/lib/desktop-bridge.ts
@@ -194,7 +194,7 @@ export interface DesktopBridge {
/** Opens Terminal to run its own sign-in command, which opens Anthropic's / OpenAI's sign-in page. */
signIn(agent: LocalAgentId): Promise<{ ok: true } | { ok: false; error: string }>;
/** Opens a session and closes it at once, only for its options. Sends no message, so costs nothing. */
- probe(agent: LocalAgentId): Promise<{ ok: true; info: LocalAgentSessionInfo } | { ok: false; error: string; code?: string }>;
+ probe(agent: LocalAgentId, model?: string): Promise<{ ok: true; info: LocalAgentSessionInfo } | { ok: false; error: string; code?: string }>;
/**
* `resume`: the agent's own id of a conversation it had (an earlier start's info.sessionId), to go on with.
* `meta`: the turn it starts for, whose log says why when it does not start.
diff --git a/apps/desktop/chat/src/lib/local-agent-run.ts b/apps/desktop/chat/src/lib/local-agent-run.ts
index 21b64d0..8c2c5d9 100644
--- a/apps/desktop/chat/src/lib/local-agent-run.ts
+++ b/apps/desktop/chat/src/lib/local-agent-run.ts
@@ -28,6 +28,7 @@ import type { Turn } from '@openfilm/shared';
import type { Balance } from '@/lib/balance';
import { chatTurns, putChatTurn, type SavedTurn } from '@/lib/chat-store';
import { app } from '../app-bridge';
+import { translate } from '@/i18n';
import { isEmptyBackgroundTurn, opensUnprompted } from '@/lib/unprompted';
import { baseName, titleFile } from '@/lib/step-file';
import { reduceTranscript, type TranscriptItem, type TranscriptPlanEntry } from '@/lib/agent-transcript';
@@ -537,6 +538,7 @@ interface LiveSession {
agent: LocalAgentId;
cwd: string;
info: LocalAgentSessionInfo;
+ onOptions?: (options: LocalAgentSessionInfo['configOptions']) => void;
/** the project and the conversation it is the session of */
projectId: string;
conversation: string;
@@ -708,6 +710,14 @@ function listen(): void {
const bridge = desktopBridge()?.localAgents;
if (!bridge) return;
unlisten = bridge.onEvent((event) => {
+ if (event.kind === 'update' && event.update.sessionUpdate === 'config_option_update' && Array.isArray(event.update.configOptions)) {
+ const session = [...sessions.values()].find((s) => s.key === event.key);
+ if (session) {
+ session.info.configOptions = event.update.configOptions as LocalAgentSessionInfo['configOptions'];
+ session.onOptions?.(session.info.configOptions);
+ }
+ return;
+ }
if (event.kind === 'update' && event.update.sessionUpdate === 'usage_update') {
const { used, size, _meta } = event.update as { used?: unknown; size?: unknown; _meta?: Record<string, unknown> };
if (typeof used === 'number' && typeof size === 'number' && size > 0) { contextByKey.set(event.key, { used, size }); tellContext(); }
@@ -807,6 +817,7 @@ export async function runLocalAgentTurn({
turn,
options = {},
onSessionInfo,
+ onOptions,
meta,
images,
}: {
@@ -826,6 +837,7 @@ export async function runLocalAgentTurn({
/** Options the user picked in the model menu (configId → value), set one by one once the session is open. */
options?: Record<string, unknown>;
onSessionInfo?: (info: LocalAgentSessionInfo) => void;
+ onOptions?: (options: LocalAgentSessionInfo['configOptions']) => void;
}): Promise<{ stopReason: string; lastTurnId: string }> {
const bridge = desktopBridge()?.localAgents;
if (!bridge) throw new Error('This needs the OpenFilm Mac app.');
@@ -855,26 +867,38 @@ export async function runLocalAgentTurn({
there are), then the rest one after another. An agent may change other options when one is set (MiniMax Code
resets its thinking effort when the model changes), so what it answers replaces what the session holds */
const live = session;
- const setOption = async ([configId, value]: [string, unknown]) => {
- const option = live.info.configOptions?.find((o) => o.id === configId);
- if (!option || option.currentValue === value) return;
- const r = await bridge.setOption(live.key, configId, value);
- if (!r.ok) return;
- const answered = r.result?.configOptions;
- if (Array.isArray(answered) && answered.length) live.info.configOptions = answered;
- else option.currentValue = value;
- };
- const picked = Object.entries(options);
- const isModel = ([configId]: [string, unknown]) => live.info.configOptions?.find((o) => o.id === configId)?.category === 'model';
- for (const entry of picked.filter(isModel)) await setOption(entry);
- for (const entry of picked.filter((entry) => !isModel(entry))) await setOption(entry);
-
- /* where it is and how to work (the project, the `openfilm` manual, Studio already open) it was told when the
- session started (apps/desktop src/agents.mjs INSTRUCTIONS): the message goes as the person wrote it */
+ live.onOptions = onOptions;
const key = session.key;
- /* the turn the agent's words go to at the end: this one, or the last message sent into it while it ran (steer) */
+ /* A message sent while it ran may have joined this turn. */
const last = () => turnByKey.get(key) ?? turn;
try {
+ const setOption = async ([configId, value]: [string, unknown]) => {
+ const option = live.info.configOptions?.find((o) => o.id === configId);
+ if (!option) return;
+ const model = option.category === 'model';
+ // Cursor can restore a different model when reusing a session. Reassert the selection and read its parameters.
+ if (option.currentValue === value && !(agent === 'cursor' && model)) return;
+ if (option.options?.length && !option.options.some((choice) => choice.value === value)) {
+ if (model) throw new Error(translate('agent.modelGone').replace('{model}', () => String(value)));
+ return;
+ }
+ const r = await bridge.setOption(live.key, configId, value);
+ if (!r.ok) {
+ throw new Error(translate('agent.settingFailed').replace('{setting}', () => option.name).replace('{value}', () => String(value))
+ .replace('{error}', () => r.error ?? translate('agent.settingRejected')));
+ }
+ const answered = r.result?.configOptions;
+ if (Array.isArray(answered) && answered.length) live.info.configOptions = answered;
+ else option.currentValue = value;
+ };
+ const picked = Object.entries(options);
+ const isModel = ([configId]: [string, unknown]) => live.info.configOptions?.find((o) => o.id === configId)?.category === 'model';
+ for (const entry of picked.filter(isModel)) await setOption(entry);
+ for (const entry of picked.filter((entry) => !isModel(entry))) await setOption(entry);
+ onOptions?.(live.info.configOptions);
+
+ /* where it is and how to work (the project, the `openfilm` manual, Studio already open) it was told when the
+ session started (apps/desktop src/agents.mjs INSTRUCTIONS): the message goes as the person wrote it */
const r = await bridge.prompt(key, text, meta, images?.length ? images : undefined);
/* The answer to the prompt can overtake its last updates (the closing words of its reply): stop
listening only once they have stopped coming, or the saved reply ends mid-sentence. */
diff --git a/apps/desktop/chat/src/state/local-agent-store.ts b/apps/desktop/chat/src/state/local-agent-store.ts
index 569aef9..69e3bb4 100644
--- a/apps/desktop/chat/src/state/local-agent-store.ts
+++ b/apps/desktop/chat/src/state/local-agent-store.ts
@@ -50,9 +50,21 @@ interface LocalAgentStore extends Persisted {
}
const probing = new Set<LocalAgentId>();
-/** the agents asked for their options since the app started: the ones kept from before are shown until then, but an
- agent updated since (Claude Code with new models) has other options, so each is asked once a launch */
-const askedThisLaunch = new Set<LocalAgentId>();
+/** The last model asked for this launch. Refresh saved catalogs once, and dependent options on each model pick. */
+const askedThisLaunch = new Map<LocalAgentId, string>();
+
+/** A selected model can have different effort/speed options from the agent's default model. */
+function probeModel(state: Persisted, agent: LocalAgentId): string | undefined {
+ const option = state.options[agent]?.find((o) => o.category === 'model');
+ const model = option && state.prefs[agent]?.[option.id];
+ if (agent === 'cursor' && typeof model === 'string') {
+ const legacy = /^([^\[]+)\[([^\]]*)\]$/.exec(model);
+ if (legacy) return legacy[1];
+ }
+ return typeof model === 'string' && option?.options?.some((o) => o.value === model) ? model : undefined;
+}
+
+const probeKey = (agent: LocalAgentId, model: string | undefined) => JSON.stringify([agent, model]);
const KEY = 'openfilm.local-agents.v2';
@@ -102,7 +114,16 @@ const EFFORT_NAMES: Record<string, string> = { auto: 'Auto', off: 'Off', minimal
* `effort` options, apps/desktop/src/pi-config.mjs). The person's own agents' is the one a session last reported.
*/
export function agentOptions(state: Pick<LocalAgentStore, 'options' | 'roster'> & Partial<Pick<LocalAgentStore, 'prefs'>>, agent: LocalAgentId): ConfigOptions | undefined {
- if (agent !== 'byok') return state.options[agent];
+ if (agent !== 'byok') {
+ const options = state.options[agent];
+ const model = options?.find((o) => o.category === 'model');
+ const picked = model && state.prefs?.[agent]?.[model.id];
+ // Until the new model answers, none of the previous model's effort/speed/context options belong in its menu.
+ if (model && picked != null && picked !== model.currentValue) {
+ return options?.filter((o) => o.category === 'model' || o.category === 'mode' || o.category === 'permissions');
+ }
+ return options;
+ }
const models = byokModels(state.roster);
if (!models.length) return undefined;
const model = ownModelPicked(models, state.prefs?.byok?.model) ?? models[0]!;
@@ -125,12 +146,14 @@ export function offeredOption(agent: LocalAgentId, _roster: RosterAgent[] | null
const CLAUDE_MODELS_OFFERED = 4;
/**
- * The choices a menu row offers, in the agent's order, without a "Default" row (a default is one of the others). Of
+ * The choices a menu row offers, in the agent's order. Native Default choices reset the model's effort. Of
* Claude Code's models, the first four it lists, as its own picker shows them, and the one in use if it is further down.
*/
export function offeredChoices<T extends { value: unknown }>(agent: LocalAgentId, option: { id: string; category?: string; options?: T[] }, chosen: unknown): T[] {
- const choices = (option.options ?? []).filter((choice) => choice.value !== 'default');
- if (agent !== 'claude' || (option.category !== 'model' && option.id !== 'model')) return choices;
+ const all = option.options ?? [];
+ if (agent !== 'claude') return all;
+ const choices = all.filter((choice) => choice.value !== 'default');
+ if (option.category !== 'model' && option.id !== 'model') return choices;
return choices.filter((choice, i) => i < CLAUDE_MODELS_OFFERED || choice.value === chosen);
}
@@ -184,35 +207,58 @@ export const useLocalAgents = create<LocalAgentStore>((set, get) => ({
save(get());
},
setPref(agent, configId, value) {
- const prefs = { ...get().prefs, [agent]: { ...(get().prefs[agent] ?? {}), [configId]: value } };
+ const model = agentOptions(get(), agent)?.find((o) => o.category === 'model');
+ const before = get().prefs[agent] ?? {};
+ const changingModel = model?.id === configId && value !== (before[configId] ?? model.currentValue);
+ // A new model starts with its own defaults; parameters from a different model are not global agent settings.
+ const prefs = { ...get().prefs, [agent]: { ...(changingModel ? {} : before), [configId]: value } };
set({ prefs });
save(get());
+ if (get().options[agent]?.some((o) => o.id === configId && o.category === 'model')) void get().ensureOptions(agent);
},
noteOptions(agent, options) {
if (!options) return;
- set({ options: { ...get().options, [agent]: options } });
+ let prefs = get().prefs;
+ /* Before Cursor's parameterized picker, a model id included effort/speed/context in brackets. Keep that
+ selection when replacing the old catalog with the model and its separately configurable parameters. */
+ const legacy = agent === 'cursor' && typeof prefs.cursor?.model === 'string' ? /^([^\[]+)\[([^\]]*)\]$/.exec(prefs.cursor.model) : null;
+ if (legacy && options.find((o) => o.category === 'model')?.options?.some((o) => o.value === legacy[1])) {
+ const values = Object.fromEntries(legacy[2]!.split(',').map((part) => part.split('=').map((s) => s.trim())));
+ const picked: Record<string, unknown> = { ...prefs.cursor, model: legacy[1] };
+ for (const option of options) {
+ const value = option.category === 'thought_level' ? values.reasoning_effort ?? values.effort ?? values.reasoning : values[option.id];
+ if (!(option.id in picked) && option.options?.some((o) => o.value === value)) picked[option.id] = value;
+ }
+ prefs = { ...prefs, cursor: picked };
+ }
+ set({ prefs, options: { ...get().options, [agent]: options } });
save(get());
},
async ensureOptions(agent, { retry = false } = {}) {
/* the own key's are known from Settings (agentOptions); a failed probe is not tried again on every render, each
try being a whole session of the agent's */
if (agent === 'byok' || probing.has(agent)) return;
+ const model = probeModel(get(), agent);
+ const key = probeKey(agent, model);
const kept = Boolean(get().options[agent]);
- if (kept && askedThisLaunch.has(agent)) return;
- if (get().optionsError[agent] && !retry) return;
+ const matched = model == null || get().options[agent]?.find((o) => o.category === 'model')?.currentValue === model;
+ if (askedThisLaunch.get(agent) === key && (matched || get().optionsError[agent]) && (!retry || !get().optionsError[agent])) return;
const api = desktopBridge()?.localAgents;
if (!api) return;
probing.add(agent);
- askedThisLaunch.add(agent);
+ askedThisLaunch.set(agent, key);
set({ optionsError: { ...get().optionsError, [agent]: undefined } });
try {
- const r = await api.probe(agent).catch((e: unknown) => ({ ok: false as const, error: e instanceof Error ? e.message : String(e), code: undefined }));
+ const r = await api.probe(agent, model).catch((e: unknown) => ({ ok: false as const, error: e instanceof Error ? e.message : String(e), code: undefined }));
+ // A newer model pick wins; an older response must not replace its effort list.
+ if (probeKey(agent, probeModel(get(), agent)) !== key) return;
if (r.ok && r.info.commands?.length) keepCommands(agent, readCommands({ availableCommands: r.info.commands }));
if (r.ok && r.info.configOptions?.length) get().noteOptions(agent, r.info.configOptions);
/* the ones kept from before stay when this launch's ask fails */
- else if (!kept) set({ optionsError: { ...get().optionsError, [agent]: r.ok ? { text: 'no options' } : { text: r.error, ...(r.code ? { code: r.code } : {}) } } });
+ else if (!kept || model != null) set({ optionsError: { ...get().optionsError, [agent]: r.ok ? { text: 'no options' } : { text: r.error, ...(r.code ? { code: r.code } : {}) } } });
} finally {
probing.delete(agent);
+ if (probeKey(agent, probeModel(get(), agent)) !== key) void get().ensureOptions(agent);
}
},
}));
@@ -241,18 +287,20 @@ const DROPPED_PREFS = new Set(['plan', 'collaboration_mode']);
* picked by its name at the service (before each model was set up on its own) is its id now.
*/
export function effectivePrefs(prefs: Persisted['prefs'], agent: LocalAgentId, roster?: RosterAgent[] | null, options?: ConfigOptions): Record<string, unknown> {
- /* "default" was a row the menu no longer offers (the agents name their default for what it is): the agent's own
- current value stands instead. A mode picked once (plan mode, offered for a while) is not kept: every agent works
+ /* An old "default" pick absent from the agent's choices is discarded; a native Default (effort reset, Cursor Auto)
+ remains an explicit selection. A mode picked once (plan mode, offered for a while) is not kept: every agent works
with full access. A pick the agent no longer offers (a model gone in its update, one the own key no longer names)
is not kept either: the agent's own stands instead */
const offers = (id: string, value: unknown) => {
+ if (!options) return true;
const option = options?.find((o) => o.id === id);
- return !option?.options?.length || option.options.some((o) => o.value === value);
+ return !!option && (!option.options?.length || option.options.some((o) => o.value === value));
};
const models = agent === 'byok' ? byokModels(roster ?? null) : null;
const own = Object.entries(prefs[agent] ?? {}).map(([id, value]): [string, unknown] => (models && id === 'model' ? [id, ownModelPicked(models, value)?.id ?? null] : [id, value]));
const kept = Object.fromEntries(own
- .filter(([id, value]) => value !== 'default' && value !== null && !DROPPED_PREFS.has(id) && offers(id, value)));
+ .filter(([id, value]) => value !== null && (value !== 'default' || options?.find((o) => o.id === id)?.options?.some((o) => o.value === value))
+ && !DROPPED_PREFS.has(id) && offers(id, value)));
return { ...kept, ...(AGENT_FORCED_PREFS[agent] ?? {}) };
}
diff --git a/apps/desktop/src/agent-definitions.mjs b/apps/desktop/src/agent-definitions.mjs
index 8deda9b..e429c04 100644
--- a/apps/desktop/src/agent-definitions.mjs
+++ b/apps/desktop/src/agent-definitions.mjs
@@ -11,7 +11,7 @@ const definitions = {
qwen: { name: 'Qwen Code', install: 'https://github.com/QwenLM/qwen-code' },
kimi: { name: 'Kimi', install: 'https://www.kimi.com/code/docs/en/kimi-code-cli/guides/getting-started.html' },
minimax: { name: 'MiniMax Code', install: 'https://www.npmjs.com/package/@minimax-ai/code' },
- deepseek: { name: 'DeepSeek Harness', install: 'https://github.com/deepseek-ai/deepseek-harness' },
+ deepseek: { name: 'DeepSeek Harness', install: 'https://www.deepseek.com/harness/' },
byok: { name: 'Own key', install: null },
};
diff --git a/apps/desktop/src/agent-definitions.test.mjs b/apps/desktop/src/agent-definitions.test.mjs
index f6a9e8c..77403e6 100644
--- a/apps/desktop/src/agent-definitions.test.mjs
+++ b/apps/desktop/src/agent-definitions.test.mjs
@@ -18,6 +18,7 @@ test('the desktop definitions cover exactly the existing launchers and discovery
assert.equal(new URL(AGENT_DOWNLOADS[id]).protocol, 'https:');
}
assert.equal(AGENT_DEFINITIONS.byok.install, null);
+ assert.equal(AGENT_DEFINITIONS.deepseek.install, 'https://www.deepseek.com/harness/');
});
test('the roster and installation API keep their existing metadata exports', () => {
diff --git a/apps/desktop/src/agent-roster.mjs b/apps/desktop/src/agent-roster.mjs
index 63cf17a..b942b62 100644
--- a/apps/desktop/src/agent-roster.mjs
+++ b/apps/desktop/src/agent-roster.mjs
@@ -38,6 +38,7 @@
import { randomBytes } from 'node:crypto';
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
+import { setTimeout as delay } from 'node:timers/promises';
import { PI_APIS, contextLength, modelEffort } from './pi-config.mjs';
import { AGENT_DEFINITIONS, AGENT_IDS, OWN_AGENT_IDS, isAgentId } from './agent-definitions.mjs';
@@ -58,11 +59,13 @@ const DEFAULT_SHOWN = { codex: true, claude: true, byok: false };
signs in to their Claude subscription the first time */
const DEFAULT_DISCONNECTED = Object.freeze(['claude']);
/**
- * How long a sign-in in Terminal is waited for, asked about every few seconds: a person may first sign in to the
- * maker's site, with a code sent to them (five minutes, as it was, was too short for Cursor's). Once it is over, the
- * window coming back into focus asks again (Settings → Agents).
+ * How long a sign-in in Terminal is waited for: a person may first sign in to the maker's site, with a code sent to
+ * them (five minutes, as it was, was too short for Cursor's). Once it is over, the window coming back into focus asks
+ * again (Settings → Agents). A sign-in is asked about every second, so finishing it shows at once; an install, every
+ * few seconds.
*/
-const SIGN_IN_WAIT = { ms: 15 * 60_000, pollMs: 3000 };
+const SIGN_IN_WAIT = { ms: 15 * 60_000, pollMs: 1000 };
+const INSTALL_WAIT = { ms: 15 * 60_000, pollMs: 3000 };
/** A red 16 × 16 picture, for asking a model whether it reads pictures. */
const PROBE_PNG = 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAAFklEQVR4nGN4pqFBEmIY1TCqYfhqAACM5TYQULtblwAAAABJRU5ErkJggg==';
@@ -209,8 +212,8 @@ export async function probeModel({ format, baseUrl, key, model, fetch: fetchImpl
* @param {{
* dataDir: string,
* localAgents: () => Promise<Array<{ id: string, cli: { path: string } | null, signedIn: boolean | null, account?: object | null, problem?: string, install: string | null, setupRequired: string | null, app?: string | null, installer?: string | null }>>,
- * localAgent?: (id: string) => Promise<{ id: string, cli: { path: string } | null, signedIn: boolean | null, account?: object | null, problem?: string, install: string | null, setupRequired: string | null, app?: string | null, installer?: string | null }>,
- * openSignIn: (id: string) => Promise<{ ok: boolean, error?: string }>,
+ * localAgent?: (id: string, options?: { fresh?: boolean }) => Promise<{ id: string, cli: { path: string } | null, signedIn: boolean | null, account?: object | null, problem?: string, install: string | null, setupRequired: string | null, app?: string | null, installer?: string | null }>,
+ * openSignIn: (id: string) => Promise<{ ok: boolean, error?: string, isOpen?: () => Promise<boolean | null> }>,
* openInstaller?: (id: string) => Promise<{ ok: boolean, error?: string }>,
* usePaths?: (paths: Record<string, string>) => void,
* pickProgram?: (id: string, words?: { title?: string, button?: string }) => Promise<string | null>,
@@ -232,6 +235,9 @@ export function createRoster(deps) {
/** what is happening now, beyond what is kept: a sign-in or an install waited for, an error to show */
const live = { waiting: {}, installing: {}, errors: {} };
let local = null;
+ const revision = new Map();
+ const checking = new Map();
+ let refreshing = null;
/* each own model's key by its id; the one key of a version before is the key of the models set up then */
const keysFile = join(dataDir, 'byok-keys');
@@ -284,18 +290,44 @@ export function createRoster(deps) {
const save = (next) => { choices = next; writeChoices(dataDir, choices); changed(); };
async function refresh() {
- const found = await deps.localAgents().catch(() => null);
- local = found ?? local ?? [];
- changed();
- return list();
+ // Focus after signing in should not wait for every other agent to finish its own status command. Only the agent
+ // being signed in is asked fresh; the others keep their cached answers in the full scan.
+ if (deps.localAgent) {
+ for (const id of Object.keys(live.waiting)) {
+ const waiting = live.waiting[id];
+ void lookAgain(id, () => !choices.disconnected.includes(id) && live.waiting[id] === waiting && !waiting.signal.aborted);
+ }
+ }
+ if (!refreshing) {
+ const started = new Map(revision);
+ refreshing = (async () => {
+ const found = await deps.localAgents().catch(() => null);
+ if (found) {
+ const current = local ?? [];
+ // A full scan started before a fresh sign-in check must not overwrite its newer result.
+ local = found.map((a) => revision.get(a.id) !== started.get(a.id) ? current.find((v) => v.id === a.id) ?? a : a);
+ local.push(...current.filter((a) => revision.get(a.id) !== started.get(a.id) && !found.some((v) => v.id === a.id)));
+ } else local ??= [];
+ changed();
+ return list();
+ })().finally(() => { refreshing = null; });
+ }
+ return refreshing;
}
/** The one agent signed in to, asked again: alone when it can be, not every agent every few seconds. */
- async function lookAgain(id) {
- if (!deps.localAgent) { await refresh(); return; }
- const one = await deps.localAgent(id).catch(() => null);
- if (!one) return;
- local = [...(local ?? []).filter((a) => a.id !== id), one];
+ async function lookAgain(id, current) {
+ let pending = checking.get(id);
+ if (!pending) {
+ pending = (deps.localAgent ? deps.localAgent(id, { fresh: Boolean(live.waiting[id]) }) : deps.localAgents()).catch(() => null);
+ checking.set(id, pending);
+ void pending.finally(() => { if (checking.get(id) === pending) checking.delete(id); });
+ }
+ const found = await pending;
+ if (!found || !current()) return;
+ local = deps.localAgent ? [...(local ?? []).filter((a) => a.id !== id), found] : found;
+ if (deps.localAgent) revision.set(id, (revision.get(id) ?? 0) + 1);
+ else for (const one of found) revision.set(one.id, (revision.get(one.id) ?? 0) + 1);
changed();
}
@@ -303,26 +335,53 @@ export function createRoster(deps) {
* Looked at again every few seconds until `done` says so, or for as long as a sign-in is waited for. A wait started
* again for the same agent (Start again) takes over: the one before stops, and leaves the new one's state alone.
*/
- async function waitFor(id, kind, done) {
- const mine = Symbol(kind);
+ async function waitFor(id, kind, done, isOpen) {
+ live[kind][id]?.abort();
+ const mine = new AbortController();
live[kind][id] = mine;
changed();
- const wait = deps.signInWait ?? SIGN_IN_WAIT;
- const until = Date.now() + wait.ms;
- while (Date.now() < until && live[kind][id] === mine) {
- await new Promise((resolve) => setTimeout(resolve, wait.pollMs));
- await lookAgain(id);
- if (done(local?.find((a) => a.id === id))) break;
+ const wait = deps.signInWait ?? (kind === 'waiting' ? SIGN_IN_WAIT : INSTALL_WAIT);
+ const current = () => live[kind][id] === mine && !mine.signal.aborted;
+ const stopped = new Promise((resolve) => mine.signal.addEventListener('abort', resolve, { once: true }));
+ const timeout = setTimeout(() => mine.abort(), wait.ms);
+ let terminalTimer;
+ // Window checks run separately: an ACP sign-in probe may take 30 seconds to answer.
+ const checkTerminal = async () => {
+ const open = await isOpen().catch(() => null);
+ if (!current()) return;
+ if (open === false) mine.abort();
+ else terminalTimer = setTimeout(checkTerminal, wait.pollMs);
+ };
+ if (isOpen) void checkTerminal();
+ try {
+ while (current()) {
+ await Promise.race([lookAgain(id, current), stopped]);
+ if (!current() || done(local?.find((a) => a.id === id))) break;
+ await delay(wait.pollMs, undefined, { signal: mine.signal }).catch(() => {});
+ }
+ } finally {
+ clearTimeout(timeout);
+ clearTimeout(terminalTimer);
+ mine.abort();
}
if (live[kind][id] !== mine) return;
delete live[kind][id];
changed();
}
- const waitForSignIn = (id) => waitFor(id, 'waiting', (a) => a?.signedIn !== false);
+ const waitForSignIn = (id, isOpen) => waitFor(id, 'waiting', (a) => a?.signedIn !== false, isOpen);
+
+ function cancelSignIn(id) {
+ if (!isOwn(id)) return;
+ live.waiting[id]?.abort();
+ delete live.waiting[id];
+ revision.set(id, (revision.get(id) ?? 0) + 1);
+ changed();
+ }
return {
list,
refresh,
+ cancelSignIn,
/** Connect: back on here; its own sign-in when it needs one. */
async connect(id) {
@@ -338,7 +397,7 @@ export function createRoster(deps) {
if (now?.status !== 'sign-in' && now?.status !== 'waiting') return { ok: true };
const opened = await deps.openSignIn(id);
if (!opened.ok) { live.errors[id] = opened.error ?? 'Terminal did not open.'; changed(); return { ok: false, error: live.errors[id] }; }
- void waitForSignIn(id);
+ void waitForSignIn(id, opened.isOpen);
return { ok: true };
}
await refresh();
@@ -353,7 +412,7 @@ export function createRoster(deps) {
/** Disconnect here only: its sessions close; its own sign-in stays as it is (connecting again uses it as it is then). */
disconnect(id) {
if (!isAgentId(id)) return;
- delete live.waiting[id];
+ cancelSignIn(id);
deps.closeSessions(id);
save({ ...choices, disconnected: [...new Set([...choices.disconnected, id])] });
},
diff --git a/apps/desktop/src/agent-roster.test.mjs b/apps/desktop/src/agent-roster.test.mjs
index 1fb4e9c..4cf76df 100644
--- a/apps/desktop/src/agent-roster.test.mjs
+++ b/apps/desktop/src/agent-roster.test.mjs
@@ -19,6 +19,80 @@ const roster = (dataDir, fetch, extra = {}) => createRoster({
...extra,
});
+test('focus publishes a fresh login before a slow full scan and ignores the scan\'s older signed-out result', async () => {
+ const qwen = (signedIn) => ({ id: 'qwen', cli: { path: '/bin/qwen' }, signedIn });
+ const scan = Promise.withResolvers();
+ let signedIn = false;
+ let slow = false;
+ const checks = [];
+ const r = roster(mkdtempSync(join(tmpdir(), 'of-fast-login-')), undefined, {
+ localAgents: async () => slow ? scan.promise : [qwen(signedIn)],
+ localAgent: async (id, options) => { checks.push([id, options]); return qwen(signedIn); },
+ signInWait: { ms: 10_000, pollMs: 5000 },
+ });
+ try {
+ await r.connect('qwen');
+ await new Promise((done) => setImmediate(done));
+ assert.equal(checks.length, 1, 'the first login check starts immediately, before the poll delay');
+ assert.equal(r.list().find((a) => a.id === 'qwen').status, 'waiting');
+ signedIn = true;
+ slow = true;
+ const refreshing = r.refresh();
+ await new Promise((done) => setImmediate(done));
+ assert.equal(r.list().find((a) => a.id === 'qwen').status, 'ready', 'focus does not wait for the full scan or the next poll');
+ assert.ok(checks.every(([id, options]) => id === 'qwen' && options.fresh === true));
+ scan.resolve([qwen(false)]);
+ await refreshing;
+ assert.equal(r.list().find((a) => a.id === 'qwen').status, 'ready', 'the old full scan cannot revert a completed login');
+ } finally { r.cancelSignIn('qwen'); scan.resolve([qwen(false)]); }
+});
+
+test('only the agent being signed in is asked fresh; other signed-out agents and installs keep cached answers', async () => {
+ const agent = (id, signedIn, cli = { path: `/bin/${id}` }) => ({ id, cli, signedIn });
+ const checks = [];
+ const r = roster(mkdtempSync(join(tmpdir(), 'of-fresh-login-')), undefined, {
+ localAgents: async () => [agent('codex', false), agent('qwen', false), agent('cursor', null, null)],
+ // The install is there at its first check, so its wait ends at once.
+ localAgent: async (id, options) => { checks.push([id, options?.fresh === true]); return id === 'cursor' ? agent('cursor', null) : agent(id, false); },
+ openInstaller: async () => ({ ok: true }),
+ signInWait: { ms: 10_000, pollMs: 5000 },
+ });
+ try {
+ await r.refresh();
+ await r.refresh();
+ assert.deepEqual(checks, [], 'a shown, connected, signed-out agent is not asked fresh on every refresh');
+ await r.connect('qwen');
+ await new Promise((done) => setImmediate(done));
+ await r.refresh();
+ assert.ok(checks.length >= 1);
+ assert.ok(checks.every(([id, fresh]) => id === 'qwen' && fresh), `only the agent being signed in is asked fresh: ${JSON.stringify(checks)}`);
+ checks.length = 0;
+ await r.install('cursor');
+ await new Promise((done) => setImmediate(done));
+ assert.deepEqual(checks, [['cursor', false]], 'an install wait uses the cached sign-in answers');
+ } finally { r.cancelSignIn('qwen'); }
+});
+
+test('focus and login polling share a status check, and cancelling ignores its late answer', async () => {
+ const qwen = (signedIn) => ({ id: 'qwen', cli: { path: '/bin/qwen' }, signedIn });
+ const pending = Promise.withResolvers();
+ let checks = 0;
+ const r = roster(mkdtempSync(join(tmpdir(), 'of-fast-login-')), undefined, {
+ localAgents: async () => [qwen(false)],
+ localAgent: async () => { checks++; return pending.promise; },
+ signInWait: { ms: 10_000, pollMs: 5000 },
+ });
+ try {
+ await r.connect('qwen');
+ await Promise.all([r.refresh(), r.refresh(), r.refresh()]);
+ assert.equal(checks, 1);
+ r.cancelSignIn('qwen');
+ pending.resolve(qwen(true));
+ await new Promise((done) => setImmediate(done));
+ assert.equal(r.list().find((a) => a.id === 'qwen').status, 'sign-in');
+ } finally { r.cancelSignIn('qwen'); pending.resolve(qwen(false)); }
+});
+
test('each API format is asked in its own shape, with a picture', () => {
const r = probeRequest('responses', 'https://api.openai.com/v1/', 'k', 'm');
assert.equal(r.url, 'https://api.openai.com/v1/responses');
@@ -388,6 +462,84 @@ test('Start again while a sign-in is waited for opens its sign-in again, and the
assert.equal(status(), 'ready');
});
+test('closing the login terminal restores sign-in even while an authentication probe is stuck', async () => {
+ const qwen = (signedIn) => ({ id: 'qwen', cli: { path: '/bin/qwen' }, signedIn });
+ const pending = Promise.withResolvers();
+ const started = Promise.withResolvers();
+ let open = true;
+ let probes = 0;
+ const r = roster(mkdtempSync(join(tmpdir(), 'of-roster-')), undefined, {
+ localAgents: async () => [qwen(false)],
+ localAgent: async () => { probes++; started.resolve(); return pending.promise; },
+ openSignIn: async () => ({ ok: true, isOpen: async () => open }),
+ signInWait: { ms: 2000, pollMs: 5 },
+ });
+ const status = () => r.list().find((a) => a.id === 'qwen').status;
+ try {
+ await r.connect('qwen');
+ await started.promise;
+ assert.equal(status(), 'waiting');
+ open = false;
+ for (let i = 0; i < 100 && status() === 'waiting'; i++) await new Promise((done) => setTimeout(done, 5));
+ assert.equal(status(), 'sign-in', 'closing the terminal does not wait for the authentication probe or the 15 minute timeout');
+ pending.resolve(qwen(true));
+ await new Promise((done) => setTimeout(done, 30));
+ assert.equal(status(), 'sign-in', 'a stale probe cannot overwrite the cancelled wait');
+ assert.equal(probes, 1, 'polling stops after the terminal closes');
+ } finally {
+ r.cancelSignIn('qwen');
+ pending.resolve(qwen(false));
+ }
+});
+
+test('cancelling sign-in restores the login state without disconnecting or waiting for an outstanding probe', async () => {
+ const qwen = (signedIn) => ({ id: 'qwen', cli: { path: '/bin/qwen' }, signedIn });
+ const pending = Promise.withResolvers();
+ const started = Promise.withResolvers();
+ const dir = mkdtempSync(join(tmpdir(), 'of-roster-'));
+ const r = roster(dir, undefined, {
+ localAgents: async () => [qwen(false)],
+ localAgent: async () => { started.resolve(); return pending.promise; },
+ signInWait: { ms: 2000, pollMs: 5 },
+ });
+ await r.connect('qwen');
+ await started.promise;
+ r.cancelSignIn('qwen');
+ assert.equal(r.list().find((a) => a.id === 'qwen').status, 'sign-in');
+ assert.equal(readChoices(dir).disconnected.includes('qwen'), false);
+ pending.resolve(qwen(true));
+ await new Promise((done) => setTimeout(done, 20));
+ assert.equal(r.list().find((a) => a.id === 'qwen').status, 'sign-in');
+ await r.connect('qwen');
+ for (let i = 0; i < 100 && r.list().find((a) => a.id === 'qwen').status === 'waiting'; i++) await new Promise((done) => setTimeout(done, 5));
+ assert.equal(r.list().find((a) => a.id === 'qwen').status, 'ready', 'sign-in can be started again and complete normally');
+});
+
+test('an old login terminal closing after Start again does not cancel the new login', async () => {
+ const qwen = { id: 'qwen', cli: { path: '/bin/qwen' }, signedIn: false };
+ const windows = [];
+ const r = roster(mkdtempSync(join(tmpdir(), 'of-roster-')), undefined, {
+ localAgents: async () => [qwen], localAgent: async () => qwen,
+ openSignIn: async () => {
+ const window = { open: true };
+ windows.push(window);
+ return { ok: true, isOpen: async () => window.open };
+ },
+ signInWait: { ms: 2000, pollMs: 5 },
+ });
+ const status = () => r.list().find((a) => a.id === 'qwen').status;
+ try {
+ await r.connect('qwen');
+ await r.connect('qwen');
+ windows[0].open = false;
+ await new Promise((done) => setTimeout(done, 30));
+ assert.equal(status(), 'waiting');
+ windows[1].open = false;
+ for (let i = 0; i < 100 && status() === 'waiting'; i++) await new Promise((done) => setTimeout(done, 5));
+ assert.equal(status(), 'sign-in');
+ } finally { r.cancelSignIn('qwen'); }
+});
+
test("an agent found only as its maker's app: the app said, and its installer run in a terminal and waited for until it is there", async () => {
const dir = mkdtempSync(join(tmpdir(), 'of-roster-'));
const missing = { id: 'cursor', cli: null, signedIn: null, install: 'https://cursor.com/cli', setupRequired: null, app: 'Cursor', installer: 'curl https://cursor.com/install -fsS | bash' };
diff --git a/apps/desktop/src/agent-sign-in.test.mjs b/apps/desktop/src/agent-sign-in.test.mjs
new file mode 100644
index 0000000..02a9eb4
--- /dev/null
+++ b/apps/desktop/src/agent-sign-in.test.mjs
@@ -0,0 +1,41 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { signInScript, terminalTabOpenScript, powerShellWindowLaunch } from './agents.mjs';
+
+test('a tracked Mac login returns its exact terminal tab, and checks do not reopen Terminal', () => {
+ const script = signInScript('/bin/qwen', [], { cwd: '/tmp/login', track: true });
+ assert.match(script, /set loginTab to do script/);
+ assert.match(script, /return tty of loginTab/);
+ const check = terminalTabOpenScript('/dev/ttys012');
+ assert.match(check, /^if application "Terminal" is not running then return "closed"/);
+ assert.match(check, /if tty of terminalTab is "\/dev\/ttys012" then return "open"/);
+ assert.doesNotMatch(check, /activate|do script/);
+ assert.throws(() => terminalTabOpenScript('"\nactivate'), /Invalid terminal tty/);
+});
+
+test('tracking a Windows login waits for its console instead of the short lived launcher', () => {
+ const file = 'C:\\Users\\someone\\Temp\\qwen login.ps1';
+ const plain = powerShellWindowLaunch(file);
+ const tracked = powerShellWindowLaunch(file, { wait: true });
+ assert.doesNotMatch(plain.args[3], /\/wait/);
+ assert.match(tracked.args[3], /^"start "" \/wait /);
+ assert.match(tracked.args[3], /-NoExit.*-File "C:\\Users\\someone\\Temp\\qwen login.ps1""$/);
+});
+
+test('on Windows the tracked launcher exits when its sign-in window closes', { skip: process.platform !== 'win32' }, async () => {
+ const { spawn } = await import('node:child_process');
+ const { mkdtempSync, writeFileSync, existsSync } = await import('node:fs');
+ const { tmpdir } = await import('node:os');
+ const { join } = await import('node:path');
+ const dir = mkdtempSync(join(tmpdir(), 'of-login-window '));
+ const mark = join(dir, 'opened');
+ const file = join(dir, 'sign-in.ps1');
+ writeFileSync(file, `\ufeffSet-Content -LiteralPath '${mark.replace(/'/g, "''")}' -Value opened\r\nStart-Sleep -Seconds 1\r\n[Environment]::Exit(0)\r\n`, 'utf8');
+ const how = powerShellWindowLaunch(file, { wait: true });
+ const child = spawn(how.cmd, how.args, { cwd: dir, detached: true, stdio: 'ignore', ...how.options });
+ const exited = new Promise((resolve, reject) => { child.once('exit', resolve); child.once('error', reject); });
+ for (let i = 0; i < 100 && !existsSync(mark); i++) await new Promise((done) => setTimeout(done, 50));
+ assert.ok(existsSync(mark));
+ assert.equal(child.exitCode, null, 'the launcher remains alive while its terminal is open');
+ assert.equal(await exited, 0);
+});
diff --git a/apps/desktop/src/agents.mjs b/apps/desktop/src/agents.mjs
index bb7d838..4431eba 100644
--- a/apps/desktop/src/agents.mjs
+++ b/apps/desktop/src/agents.mjs
@@ -25,7 +25,8 @@
* Reads no Electron module, so `node --test` can use it.
*/
import { execFile, spawn } from 'node:child_process';
-import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { randomUUID } from 'node:crypto';
+import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
import { arch, homedir, release, tmpdir } from 'node:os';
import { createRequire } from 'node:module';
import { dirname, isAbsolute, join, win32 } from 'node:path';
@@ -373,10 +374,10 @@ export async function agentSignedIn(id, cliPath) {
* organization, plan; Codex: how, ChatGPT or an API key), never a key or a token.
* @returns {Promise<{ signedIn: boolean | null, account: AgentAccount | null, problem?: string }>}
*/
-export async function agentStatus(id, cliPath) {
+export async function agentStatus(id, cliPath, { fresh = false } = {}) {
const spec = AGENTS[id];
if (!spec || !cliPath) return { signedIn: null, account: null };
- if (!spec.auth) return { signedIn: await acpSignedIn(id), account: null };
+ if (!spec.auth) return { signedIn: await acpSignedIn(id, { fresh }), account: null };
const how = starting(cliPath, spec.auth);
const r = await run(how.cmd, how.args, 10_000, { env: childEnvironment({ shell: agentShell(id, await loginShellVariables()), extra: how.env }), options: how.options });
return readAgentStatus(id, r.stdout, r.out);
@@ -434,13 +435,16 @@ export function probeFolder() {
* Signed in, for an agent with no command that says: a session opened (in an empty folder of the app's) and closed.
* One it refuses for its sign-in (ACP's auth_required) is signed out; one that opens, signed in; anything else, null.
*/
-export function acpSignedIn(id) {
+export function acpSignedIn(id, { fresh = false } = {}) {
const kept = asked.get(id);
- if (kept && Date.now() - kept.at < (kept.signedIn ? SIGNED_IN_FOR_MS : ASKED_FOR_MS)) return kept.answer;
+ // A sign-in just completed in Terminal: bypass a cached negative result, but share an in-flight probe.
+ if (kept && (kept.pending || ((!fresh || kept.signedIn) && Date.now() - kept.at < (kept.signedIn ? SIGNED_IN_FOR_MS : ASKED_FOR_MS)))) return kept.answer;
const answer = (async () => {
const session = new AgentSession({ agent: id, cwd: probeFolder() });
try {
- await Promise.race([session.start(), new Promise((_, fail) => setTimeout(() => fail(new Error('timed out')), 30_000))]);
+ let timeout;
+ try { await Promise.race([session.start(), new Promise((_, fail) => { timeout = setTimeout(() => fail(new Error('timed out')), 30_000); })]); }
+ finally { clearTimeout(timeout); }
return true;
} catch (e) {
return e?.code === 'sign-in' ? false : null;
@@ -448,9 +452,9 @@ export function acpSignedIn(id) {
session.close();
}
})();
- const entry = { at: Date.now(), answer, signedIn: false };
+ const entry = { at: Date.now(), answer, signedIn: false, pending: true };
asked.set(id, entry);
- void answer.then((yes) => { entry.signedIn = yes === true; });
+ void answer.then((yes) => { entry.signedIn = yes === true; entry.pending = false; entry.at = Date.now(); });
return answer;
}
@@ -468,13 +472,27 @@ const shq = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
* The AppleScript that has Terminal run one command in a new window, in `cwd` when given (SIGN_IN_DIR: not the home
* folder a new window opens in).
*/
-export function signInScript(cliPath, args, { cwd } = {}) {
- return terminalScript(`${cwd ? `cd ${shq(cwd)} && ` : ''}${[cliPath, ...args].map(shq).join(' ')}`);
+export function signInScript(cliPath, args, { cwd, track = false } = {}) {
+ return terminalScript(`${cwd ? `cd ${shq(cwd)} && ` : ''}${[cliPath, ...args].map(shq).join(' ')}`, { track });
}
/** The AppleScript that has Terminal run a command line, as it is, in a new window. */
-export function terminalScript(command) {
- return `tell application "Terminal"\nactivate\ndo script "${command.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"\nend tell`;
+export function terminalScript(command, { track = false } = {}) {
+ return `tell application "Terminal"\nactivate\n${track ? 'set loginTab to ' : ''}do script "${command.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"\n${track ? 'return tty of loginTab\n' : ''}end tell`;
+}
+
+/** Check the exact login tab, including when other Terminal windows remain open. Never launch Terminal to check. */
+export function terminalTabOpenScript(tty) {
+ if (!/^\/dev\/tty[\w]+$/.test(tty)) throw new Error('Invalid terminal tty');
+ return `if application "Terminal" is not running then return "closed"
+tell application "Terminal"
+repeat with terminalWindow in windows
+repeat with terminalTab in tabs of terminalWindow
+if tty of terminalTab is "${tty}" then return "open"
+end repeat
+end repeat
+end tell
+return "closed"`;
}
/**
@@ -496,10 +514,10 @@ const psq = (s) => `'${String(s).replace(/'/g, "''")}'`;
* it a console. Started straight from the app, `detached` makes it a DETACHED_PROCESS with no console at all, and
* PowerShell quits at once without running the script.
*/
-export function powerShellWindowLaunch(file, { comSpec = process.env.ComSpec || 'cmd.exe', systemRoot = process.env.SystemRoot ?? 'C:\\Windows' } = {}) {
+export function powerShellWindowLaunch(file, { comSpec = process.env.ComSpec || 'cmd.exe', systemRoot = process.env.SystemRoot ?? 'C:\\Windows', wait = false } = {}) {
/* a Windows path wherever it is worked out (the tests run on every system) */
const powershell = win32.join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
- const line = ['start', '""', ...[powershell, '-NoLogo', '-NoExit', '-ExecutionPolicy', 'Bypass', '-File', file].map(winArg)].join(' ');
+ const line = ['start', '""', ...(wait ? ['/wait'] : []), ...[powershell, '-NoLogo', '-NoExit', '-ExecutionPolicy', 'Bypass', '-File', file].map(winArg)].join(' ');
return { cmd: comSpec, args: ['/d', '/s', '/c', `"${line}"`], options: { windowsVerbatimArguments: true, windowsHide: true } };
}
@@ -507,15 +525,17 @@ export function powerShellWindowLaunch(file, { comSpec = process.env.ComSpec ||
* A PowerShell window of its own running a script (a sign-in, an installer), left open so what it says can be read
* and answered.
*/
-async function powerShellWindow(name, script, env) {
+async function powerShellWindow(name, script, env, { track = false } = {}) {
const dir = SIGN_IN_DIR();
mkdirSync(dir, { recursive: true });
- const file = join(dir, name);
+ const file = join(dir, track ? `${randomUUID()}-${name}` : name);
writeFileSync(file, script, 'utf8');
- const how = powerShellWindowLaunch(file);
+ const how = powerShellWindowLaunch(file, { wait: track });
const child = spawn(how.cmd, how.args, { cwd: dir, detached: true, stdio: 'ignore', env, ...how.options });
await new Promise((done, fail) => { child.once('spawn', done); child.once('error', fail); });
+ if (track) child.once('exit', () => { try { unlinkSync(file); } catch { /* already removed */ } });
child.unref();
+ return child;
}
/** The person's shell variables as this agent is given them (`fromShell`; all of them, for most). */
@@ -564,9 +584,9 @@ const SIGN_IN_DIR = () => join(tmpdir(), 'openfilm-sign-in');
/**
* Sign in: Terminal runs the program's own sign-in, which opens the maker's own page. The app touches nothing. One
* signed in the way its adapter offers (`acpSignIn`, that way's id) runs the adapter with that way's arguments, as ACP
- * has a client do it.
+ * has a client do it. `track` adds an `isOpen` check for the roster, kept inside the main process.
*/
-export async function openAgentSignIn(id) {
+export async function openAgentSignIn(id, { track = false } = {}) {
const spec = AGENTS[id];
const pathDirs = (await loginShellEnvironment()).PATH.split(PATH_SEP);
const cli = spec ? resolveAgentCli(id, { pathDirs }) : null;
@@ -589,19 +609,28 @@ export async function openAgentSignIn(id) {
how ??= /\.(?:cmd|bat)$/i.test(cli.path) ? { cmd: cli.path, args: spec.login, env: {} } : starting(cli.path, spec.login);
how = { ...how, env: { ...defaults, ...how.env } };
try {
- await powerShellWindow(`${id}.ps1`, powerShellScript(`${spec.label} sign-in`, how.cmd, how.args),
- childEnvironment({ shell: agentShell(id, await loginShellVariables()), extra: how.env }));
- return { ok: true };
+ const child = await powerShellWindow(`${id}.ps1`, powerShellScript(`${spec.label} sign-in`, how.cmd, how.args),
+ childEnvironment({ shell: agentShell(id, await loginShellVariables()), extra: how.env }), { track });
+ return { ok: true, ...(track ? { isOpen: async () => child.exitCode === null && child.signalCode === null } : {}) };
} catch (e) { return { ok: false, error: e instanceof Error ? e.message : String(e) }; }
}
const cwd = SIGN_IN_DIR();
try { mkdirSync(cwd, { recursive: true }); } catch { /* signed in from the home folder, as before */ }
- const where = existsSync(cwd) ? { cwd } : {};
+ const where = { ...(existsSync(cwd) ? { cwd } : {}), track };
const script = how
? signInScript('/usr/bin/env', [...Object.entries(how.env).map(([k, v]) => `${k}=${v}`), how.cmd, ...how.args], where)
: signInScript(cli.path, spec.login, where);
const r = await run('/usr/bin/osascript', ['-e', script], 15_000);
- return r.ok ? { ok: true } : { ok: false, error: r.out.trim() || 'Terminal did not open.' };
+ if (!r.ok) return { ok: false, error: r.out.trim() || 'Terminal did not open.' };
+ const tty = r.stdout.trim();
+ return { ok: true, ...(track && /^\/dev\/tty[\w]+$/.test(tty) ? {
+ isOpen: async () => {
+ const checked = await run('/usr/bin/osascript', ['-e', terminalTabOpenScript(tty)], 5000);
+ if (!checked.ok) return null;
+ const state = checked.stdout.trim();
+ return state === 'open' ? true : state === 'closed' ? false : null;
+ },
+ } : {}) };
}
/**
@@ -643,12 +672,12 @@ export async function listAgents() {
}
/** One agent as listAgents has it, asked alone: while the person signs in to it, only it is asked again. */
-export async function localAgent(id) {
+export async function localAgent(id, { fresh = false } = {}) {
if (!isAgentId(id)) throw new Error(`No agent ${id}`);
- return agentOnComputer(id, (await loginShellEnvironment({ maxAgeMs: 10_000 })).PATH.split(PATH_SEP));
+ return agentOnComputer(id, (await loginShellEnvironment({ maxAgeMs: 10_000 })).PATH.split(PATH_SEP), { fresh });
}
-async function agentOnComputer(id, pathDirs) {
+async function agentOnComputer(id, pathDirs, { fresh = false } = {}) {
const cli = resolveAgentCli(id, { pathDirs });
const { install } = detectAgentInstallation(id);
const app = cli ? null : desktopApp(id);
@@ -658,7 +687,7 @@ async function agentOnComputer(id, pathDirs) {
label: AGENTS[id].label,
cli: cli ? { path: cli.path, source: cli.source } : null,
chosen: chosenPaths[id] ?? null,
- ...(cli ? ownSignIn(AGENTS[id], await agentStatus(id, cli.path)) : { signedIn: null, account: null }),
+ ...(cli ? ownSignIn(AGENTS[id], await agentStatus(id, cli.path, { fresh })) : { signedIn: null, account: null }),
install,
setupRequired: claudeApp ? 'code-tab' : null,
...(cli ? {} : { app: claudeApp ? null : app, installer: installCommand(id) }),
@@ -765,9 +794,9 @@ export const CLIENT_CAPABILITIES = {
auth: { terminal: true },
/* the agent's own warnings (Codex: "Falling back from WebSockets…") come as notices, not as words in its reply */
session: { notices: {} },
- /* Claude Code's "recommended value" extension: its model and effort lists come without a "Default" row, the
- current value named for what it is */
- _meta: { jetbrains: { air: { version: 1, capabilities: ['recommendedValue'] } } },
+ /* Cursor exposes model parameters (effort, speed, context) only to clients with its advanced picker.
+ Claude Code's recommended-value extension names the current model and effort without a Default row. */
+ _meta: { parameterizedModelPicker: true, jetbrains: { air: { version: 1, capabilities: ['recommendedValue'] } } },
};
const CLIENT_INFO = { name: 'openfilm-desktop', title: 'OpenFilm', version: '0.1.0' };
@@ -829,12 +858,13 @@ export function signInError(label, e, { own = false } = {}) {
}
/**
- * An error the agent sends as just "Internal error" with its reason: the reason is in its `data`, as a string or its
+ * An error the agent sends as just "Internal error" or "Invalid params" with its reason: the reason is in its `data`, as a string or its
* `message` or `details` (the ACP SDK puts a thrown Error's text there; Codex its settings it cannot read). The error
* it came as stays its `cause`.
*/
export function errorCause(e) {
- if (e?.code !== INTERNAL_ERROR || String(e.message ?? '').trim() !== 'Internal error') return e;
+ if (!((e?.code === INTERNAL_ERROR && String(e.message ?? '').trim() === 'Internal error')
+ || (e?.code === -32602 && String(e.message ?? '').trim() === 'Invalid params'))) return e;
const data = e.data;
const why = typeof data === 'string' ? data : [data?.message, data?.details].find((v) => typeof v === 'string') ?? '';
return why.trim() ? Object.assign(new Error(why.trim(), { cause: e }), { code: e.code }) : e;
@@ -988,6 +1018,18 @@ export function distinctOptions(configOptions) {
});
}
+/** A menu probe asks the selected model for its own dependent options, without sending a prompt. */
+export async function optionsForModel(session, info, model) {
+ if (model == null) return info;
+ const option = info.configOptions?.find((o) => o.category === 'model');
+ if (!option?.options?.some((choice) => choice.value === model)) throw new Error('The agent does not offer this model.');
+ if (option.currentValue === model) return info;
+ const result = await session.setConfigOption(option.id, model);
+ const options = result?.configOptions ?? info.configOptions.map((o) => o.id === option.id ? { ...o, currentValue: model } : o);
+ if (options.find((o) => o.category === 'model')?.currentValue !== model) throw new Error('The agent did not accept the selected model.');
+ return { ...info, configOptions: options };
+}
+
/**
* One conversation: one ACP session on one adapter process.
*
@@ -1306,7 +1348,7 @@ export class AgentSession {
async setConfigOption(configId, value) {
if (this.legacy && configId === 'mode') return this.setMode(value);
if (this.legacy && configId === 'model') return this.conn.agent.request('session/set_model', { sessionId: this.sessionId, modelId: value });
- const r = await this.conn.agent.request(acp.methods.agent.session.setConfigOption, { sessionId: this.sessionId, configId, value });
+ const r = await this.conn.agent.request(acp.methods.agent.session.setConfigOption, { sessionId: this.sessionId, configId, value }).catch((e) => { throw errorCause(e); });
this.noteModel(r?.configOptions);
return r?.configOptions ? { ...r, configOptions: distinctOptions(r.configOptions) } : r;
}
diff --git a/apps/desktop/src/agents.test.mjs b/apps/desktop/src/agents.test.mjs
index c49c7d5..759b731 100644
--- a/apps/desktop/src/agents.test.mjs
+++ b/apps/desktop/src/agents.test.mjs
@@ -1,7 +1,76 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
-import { AgentSession, CLIENT_CAPABILITIES, agentDefaults, closeEverySession, planProblem, probeFolder, CODEX_UTF8_CMD, agentShell, allowOption, codexDeveloperInstructions, codexLaunchEnv, distinctOptions, errorCause, legacyOptions, powerShellScript, powerShellLine, powerShellWindowLaunch, terminalScript, checkAgentProgram, readAgentStatus, setChosenPaths, signInScript, turnError, signInError, codexTooOld, AGENTS, ownSignIn, codexServiceError, codexRefusal, codexNotice, explainFailure, stderrReason, withToolKind, OWN_GROUP, stopTree, winArg } from './agents.mjs';
+import { AgentSession, CLIENT_CAPABILITIES, agentDefaults, closeEverySession, planProblem, probeFolder, CODEX_UTF8_CMD, agentShell, allowOption, codexDeveloperInstructions, codexLaunchEnv, distinctOptions, errorCause, legacyOptions, optionsForModel, powerShellScript, powerShellLine, powerShellWindowLaunch, terminalScript, checkAgentProgram, readAgentStatus, setChosenPaths, signInScript, turnError, signInError, codexTooOld, AGENTS, ownSignIn, codexServiceError, codexRefusal, codexNotice, explainFailure, stderrReason, withToolKind, OWN_GROUP, stopTree, winArg } from './agents.mjs';
import { spawn } from 'node:child_process';
+import { acpSignedIn } from './agents.mjs';
+
+test('a fresh sign-in check bypasses a cached signed-out result and shares the pending probe', async () => {
+ const { mkdtempSync, readFileSync, writeFileSync, rmSync } = await import('node:fs');
+ const { tmpdir } = await import('node:os');
+ const { join } = await import('node:path');
+ const dir = mkdtempSync(join(tmpdir(), 'of-auth-cache-'));
+ const signedIn = join(dir, 'signed-in');
+ const calls = join(dir, 'calls');
+ const program = join(dir, 'qwen.mjs');
+ writeFileSync(program, `
+ import { createInterface } from 'node:readline';
+ import { appendFileSync, existsSync } from 'node:fs';
+ const send = (message) => process.stdout.write(JSON.stringify(message) + '\\n');
+ createInterface({ input: process.stdin }).on('line', (line) => {
+ const request = JSON.parse(line);
+ if (request.method === 'initialize') send({ jsonrpc: '2.0', id: request.id, result: { protocolVersion: 1, agentCapabilities: {}, authMethods: [] } });
+ if (request.method === 'session/new') {
+ appendFileSync(${JSON.stringify(calls)}, 'check\\n');
+ setTimeout(() => send({ jsonrpc: '2.0', id: request.id, ...(existsSync(${JSON.stringify(signedIn)})
+ ? { result: { sessionId: 'auth-test' } } : { error: { code: -32000, message: 'Authentication required' } }) }), 30);
+ }
+ });
+ `);
+ setChosenPaths({ qwen: program });
+ try {
+ assert.equal(await acpSignedIn('qwen'), false);
+ writeFileSync(signedIn, 'yes');
+ assert.equal(await acpSignedIn('qwen'), false, 'normal background scans may reuse a cached negative');
+ const first = acpSignedIn('qwen', { fresh: true });
+ const second = acpSignedIn('qwen', { fresh: true });
+ assert.equal(first, second, 'focus and the login poll share the same running status check');
+ assert.equal(await first, true, 'the just-completed login is seen without waiting 15 seconds');
+ assert.equal(await acpSignedIn('qwen', { fresh: true }), true);
+ assert.equal(readFileSync(calls, 'utf8').trim().split('\n').length, 2, 'signed-in results remain cached');
+ } finally { setChosenPaths({}); rmSync(dir, { recursive: true, force: true }); }
+});
+
+test('an invalid parameter keeps the reason the agent supplied', () => {
+ const error = Object.assign(new Error('Invalid params'), { code: -32602, data: { details: 'This model does not support fast.' } });
+ const explained = errorCause(error);
+ assert.equal(explained.message, 'This model does not support fast.');
+ assert.equal(explained.cause, error);
+ assert.equal(errorCause(Object.assign(new Error('Invalid params'), { code: -32602 })).message, 'Invalid params');
+});
+
+test('the model picker opts into Cursor model parameters while retaining recommended values', () => {
+ assert.equal(CLIENT_CAPABILITIES._meta.parameterizedModelPicker, true);
+ assert.deepEqual(CLIENT_CAPABILITIES._meta.jetbrains.air.capabilities, ['recommendedValue']);
+});
+
+test('a menu probe selects the requested model before returning its effort options, without a prompt', async () => {
+ const info = { sessionId: 'probe', configOptions: [{ id: 'model', category: 'model', currentValue: 'plain', options: [{ value: 'plain' }, { value: 'reasoning' }] }] };
+ const calls = [];
+ const effort = { id: 'effort', category: 'thought_level', options: [{ value: 'default' }, { value: 'high' }] };
+ const session = { setConfigOption: async (...args) => {
+ calls.push(args);
+ return { configOptions: [{ ...info.configOptions[0], currentValue: args[1] }, effort] };
+ } };
+ assert.equal(await optionsForModel(session, info), info);
+ assert.equal(await optionsForModel(session, info, 'plain'), info);
+ assert.deepEqual(calls, []);
+ const selected = await optionsForModel(session, info, 'reasoning');
+ assert.deepEqual(calls, [['model', 'reasoning']]);
+ assert.equal(selected.configOptions[1], effort);
+ await assert.rejects(optionsForModel(session, info, 'missing'), /does not offer/);
+ assert.equal(calls.length, 1, 'an unavailable model is never sent to the agent');
+ await assert.rejects(optionsForModel({ setConfigOption: async () => ({ configOptions: info.configOptions }) }, info, 'reasoning'), /did not accept/);
+});
test('an agent that asks: yes for good where it offers that, else yes this once; nothing to say yes with is null', () => {
const options = [
@@ -127,7 +196,7 @@ test('a turn the agent ends with just "Internal error" says the reason in its da
assert.equal(errorCause(said), said);
const bare = Object.assign(new Error('Internal error'), { code: -32603, data: { errorKind: 'transport_lost' } });
assert.equal(errorCause(bare), bare);
- const other = Object.assign(new Error('Invalid params'), { code: -32602, data: { message: 'x' } });
+ const other = Object.assign(new Error('Method not found'), { code: -32601, data: { message: 'x' } });
assert.equal(errorCause(other), other);
});
diff --git a/apps/desktop/src/local-agents-ipc.mjs b/apps/desktop/src/local-agents-ipc.mjs
index 46d8de6..854055b 100644
--- a/apps/desktop/src/local-agents-ipc.mjs
+++ b/apps/desktop/src/local-agents-ipc.mjs
@@ -51,7 +51,7 @@ import { recordProblem, problemsFile } from 'openfilm/problems';
import { LOG_SETTLE_MS } from './agent-logs.mjs';
import { RECORDED_AGENTS, agentRecordCalls, compactCalls, recordedModel } from './agent-records.mjs';
import { skillStore } from './agent-skills.mjs';
-import { AGENTS, AgentSession, HARNESS_AGENTS, isAgentId, isChatAgent, listAgents, openAgentSignIn, probeFolder } from './agents.mjs';
+import { AGENTS, AgentSession, HARNESS_AGENTS, isAgentId, isChatAgent, listAgents, openAgentSignIn, optionsForModel, probeFolder } from './agents.mjs';
import { loggedBlocks, logsDir, openLog, writeModelLog } from './chat-store.mjs';
import { loginShellVariables } from './environment.mjs';
@@ -224,12 +224,20 @@ export function registerLocalAgentIpc(ipcMain, { trusted, binDir = null, fallbac
try {
/* its commands too (the composer's / menu), which it says just after the session opens: waited for a moment */
let commands = null;
+ let options = null;
let said = () => {};
const heard = new Promise((done) => { said = done; });
session = new AgentSession({ agent, cwd: probeFolder(), binDir, fallbackDir, env, harness: await harnessFor(agent),
- onUpdate: (update) => { if (update?.sessionUpdate === 'available_commands_update') { commands = update.availableCommands ?? null; said(); } } });
- const info = await session.start();
+ onUpdate: (update) => {
+ if (update?.sessionUpdate === 'available_commands_update') { commands = update.availableCommands ?? null; said(); }
+ if (update?.sessionUpdate === 'config_option_update') options = update.configOptions ?? null;
+ } });
+ let info = await session.start();
+ if (options) info = { ...info, configOptions: options };
+ options = null;
+ info = await optionsForModel(session, info, typeof opts?.model === 'string' ? opts.model : undefined);
await Promise.race([heard, new Promise((done) => setTimeout(done, PROBE_COMMANDS_MS))]);
+ if (options) info = { ...info, configOptions: options };
return { ok: true, info: { ...info, ...(commands ? { commands } : {}) } };
} catch (e) {
const error = e instanceof Error ? e.message : String(e);
diff --git a/apps/desktop/src/main.mjs b/apps/desktop/src/main.mjs
index fe03368..79f1fbd 100644
--- a/apps/desktop/src/main.mjs
+++ b/apps/desktop/src/main.mjs
@@ -615,7 +615,7 @@ async function start() {
dataDir: DATA,
localAgents: listAgents,
localAgent,
- openSignIn: openAgentSignIn,
+ openSignIn: (id) => openAgentSignIn(id, { track: true }),
/* an agent's official installer, in a terminal window, once the person agreed to it in Settings → Agents */
openInstaller: openAgentInstaller,
/* sessions closed on connecting and disconnecting: the next look at its usage is for whichever account is used now */
@@ -638,6 +638,7 @@ async function start() {
});
agentHandle('desktop:agents:list', () => { void roster.refresh(); return roster.list(); });
agentHandle('desktop:agents:connect', ({ id }) => roster.connect(String(id)));
+ agentHandle('desktop:agents:cancel-sign-in', ({ id }) => { roster.cancelSignIn(String(id)); return { ok: true }; });
agentHandle('desktop:agents:disconnect', ({ id }) => { roster.disconnect(String(id)); return { ok: true }; });
/* what is left of Claude Code's and Codex's plan, on OpenFilm's sign-in (agent-usage.mjs); null when it can't say */
agentHandle('desktop:agents:usage', ({ id, fresh }) => agentUsage(String(id), { fresh: fresh === true }));
diff --git a/apps/desktop/src/preload.cjs b/apps/desktop/src/preload.cjs
index de4eadd..975f38b 100644
--- a/apps/desktop/src/preload.cjs
+++ b/apps/desktop/src/preload.cjs
@@ -46,6 +46,7 @@ contextBridge.exposeInMainWorld('openfilmNative', {
agents: {
list: () => ipcRenderer.invoke('desktop:agents:list'),
connect: (id) => ipcRenderer.invoke('desktop:agents:connect', { id }),
+ cancelSignIn: (id) => ipcRenderer.invoke('desktop:agents:cancel-sign-in', { id }),
disconnect: (id) => ipcRenderer.invoke('desktop:agents:disconnect', { id }),
usage: (id, fresh) => ipcRenderer.invoke('desktop:agents:usage', { id, fresh: fresh === true }),
setShown: (id, shown) => ipcRenderer.invoke('desktop:agents:shown', { id, shown: shown === true }),
@@ -71,7 +72,7 @@ contextBridge.exposeInMainWorld('openfilmNative', {
list: () => ipcRenderer.invoke('desktop:local-agents:list'),
signIn: (agent) => invoke('desktop:local-agents:sign-in')({ agent }),
disconnect: (agent) => invoke('desktop:local-agents:disconnect')({ agent }),
- probe: (agent) => invoke('desktop:local-agents:probe')({ agent }),
+ probe: (agent, model) => invoke('desktop:local-agents:probe')({ agent, model }),
start: (agent, cwd, resume, meta) => invoke('desktop:local-agents:start')({ agent, cwd, resume, meta }),
prompt: (key, text, meta, images) => invoke('desktop:local-agents:prompt')({ key, text, meta, images }),
running: () => ipcRenderer.invoke('desktop:local-agents:running'),
diff --git a/packages/openfilm/studio/ruler-refer.test.mjs b/packages/openfilm/studio/ruler-refer.test.mjs
index a92df0c..66eb0ab 100644
--- a/packages/openfilm/studio/ruler-refer.test.mjs
+++ b/packages/openfilm/studio/ruler-refer.test.mjs
@@ -27,9 +27,18 @@ test('with the app\'s chat, a ruler click moves the playhead and a ⌘-click (Ct
const page = await browser.newPage({ viewport: { width: 1280, height: 800 }, locale: 'en-US', reducedMotion: 'reduce' });
/* the app's chat, as far as the ruler sees it: what is referred to it */
await page.addInitScript(() => {
+ // A choice saved by an older version must not bring back hover preview.
+ localStorage.setItem('openfilm.timeline.previewAxis', '1');
window.referred = [];
- window.openfilmHost = { version: 1, refer: (ref) => window.referred.push(ref) };
+ window.openfilmHost = {
+ version: 1, refer: (ref) => window.referred.push(ref),
+ onCommand: (receive) => { window.studioCommand = receive; },
+ };
});
+ await page.route(`**/api/projects/${project.id}/captions`, (route) => route.fulfill({ json: {
+ cues: [{ startMs: 2000, durMs: 500, text: 'Subtitle cue', clip: 'card', src: 'assets/card.svg', line: 0 }],
+ sourceLanguage: null, languages: [], untranscribed: [],
+ } }));
await page.goto(`${studio.origin}/projects/${project.id}?key=${studio.key}`);
await page.locator('[data-block-id]').first().waitFor({ state: 'visible' });
const slider = page.locator('[data-timeline] [role="slider"]').first();
@@ -41,6 +50,11 @@ test('with the app\'s chat, a ruler click moves the playhead and a ⌘-click (Ct
/* the key a box is drawn with on the picture: ⌘ on a Mac, Ctrl elsewhere */
const key = process.platform === 'darwin' ? 'Meta' : 'Control';
assert.equal(await playhead(), 0);
+ assert.equal(await page.locator('[data-timeline-preview-axis], [data-preview-axis]').count(), 0, 'the preview axis switch and line are removed');
+ assert.equal(await page.getByRole('button', { name: 'Preview axis', exact: true }).count(), 0);
+ await page.mouse.move(ruler.x + 200, y + 100);
+ await page.keyboard.press('s');
+ assert.equal(await playhead(), 0, 'hovering and the old shortcut do not seek');
/* a plain click: the playhead goes there, nothing is referred. Just after the page opens, the preview may not take
a seek yet (the playhead is where the preview is), so the click is made again until it does */
@@ -58,16 +72,33 @@ test('with the app\'s chat, a ruler click moves the playhead and a ⌘-click (Ct
await page.mouse.move(ruler.x + 300, y, { steps: 5 });
await page.mouse.up();
await page.waitForFunction((before) => Number(document.querySelector('[data-timeline] [role="slider"]')?.getAttribute('aria-valuenow')) > before, clicked);
- const dragged = await playhead();
assert.deepEqual(await referred(), []);
+ /* blank subtitle space follows the ruler's seeking gesture; a cue itself still selects and edits */
+ const subtitleRow = page.locator('[data-subtitle-row]');
+ await subtitleRow.waitFor({ state: 'visible' });
+ const row = await subtitleRow.boundingBox();
+ const beforeBlank = await playhead();
+ await page.mouse.click(ruler.x + 60, row.y + row.height / 2);
+ await page.waitForFunction((before) => Number(document.querySelector('[data-timeline] [role="slider"]')?.getAttribute('aria-valuenow')) < before, beforeBlank);
+ const blankClicked = await playhead();
+ await page.mouse.move(ruler.x + 60, row.y + row.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(ruler.x + 180, row.y + row.height / 2, { steps: 5 });
+ await page.mouse.up();
+ await page.waitForFunction((before) => Number(document.querySelector('[data-timeline] [role="slider"]')?.getAttribute('aria-valuenow')) > before, blankClicked);
+ const dragged = await playhead();
+ await page.locator('[data-subtitle-cue]').first().click();
+ assert.equal(await playhead(), dragged, 'clicking a subtitle cue does not also seek');
+ assert.equal(await page.getByRole('button', { name: 'Add to chat', exact: true }).count(), 0, 'the floating reference button is absent');
+
/* the moment a click would refer is drawn only while the key is held, with a crosshair */
await page.mouse.move(ruler.x + 60, y);
- assert.equal(await slider.evaluate((el) => el.style.cursor), 'col-resize');
+ assert.equal(await slider.evaluate((el) => el.style.cursor), 'default');
await page.keyboard.down(key);
await page.waitForFunction(() => document.querySelector('[data-timeline] [role="slider"]')?.style.cursor === 'crosshair');
await page.keyboard.up(key);
- await page.waitForFunction(() => document.querySelector('[data-timeline] [role="slider"]')?.style.cursor === 'col-resize');
+ await page.waitForFunction(() => document.querySelector('[data-timeline] [role="slider"]')?.style.cursor === 'default');
/* a ⌘-click refers that moment, a ⌘-drag that span; the playhead stays */
await page.keyboard.down(key);
@@ -75,6 +106,12 @@ test('with the app\'s chat, a ruler click moves the playhead and a ⌘-click (Ct
await page.mouse.move(ruler.x + 40, y);
await page.mouse.down();
await page.mouse.move(ruler.x + 120, y, { steps: 5 });
+ const draft = page.locator('[data-timeline-refer-range]');
+ await draft.waitFor({ state: 'visible' });
+ const band = await draft.boundingBox();
+ assert.ok(band.height <= ruler.height, 'the chosen span stays within the top ruler while dragging');
+ assert.ok(band.width > 20, 'the ruler shows the current span before release');
+ assert.equal(await page.evaluate(() => document.body.classList.contains('tl-pinning')), true);
await page.mouse.up();
await page.keyboard.up(key);
const refs = await referred();
@@ -82,6 +119,34 @@ test('with the app\'s chat, a ruler click moves the playhead and a ⌘-click (Ct
assert.ok(refs[0].time > 0 && refs[0].time * 1000 < clicked);
assert.ok(refs[1].start < refs[1].end);
assert.equal(await playhead(), dragged);
+ assert.equal(await draft.count(), 0, 'release removes the live preview');
+ assert.equal(await page.evaluate(() => document.body.classList.contains('tl-pinning')), false);
+
+ /* recalling that span seeks to its start and briefly tints only the ruler */
+ const flash = page.locator('[data-timeline-range-flash]');
+ await page.evaluate(() => window.studioCommand({ type: 'show-range', start: 0.1, end: 0.6 }));
+ await flash.waitFor({ state: 'visible' });
+ const flashed = await flash.boundingBox();
+ const subtitleBounds = await subtitleRow.boundingBox();
+ assert.ok(flashed.y + flashed.height <= subtitleBounds.y + 0.5, 'the highlight ends above the subtitle and clip rows');
+ assert.equal(await page.locator('[data-timeline-range]').count(), 0, 'no persistent range or its label is created');
+ await page.waitForFunction(() => Math.abs(Number(document.querySelector('[data-timeline] [role="slider"]')?.getAttribute('aria-valuenow')) - 100) <= 40);
+ assert.equal(await page.getByRole('button', { name: 'Add to chat', exact: true }).count(), 0);
+ await flash.waitFor({ state: 'hidden', timeout: 3000 });
+ assert.equal(await page.locator('[data-timeline-range]').count(), 0);
+
+ /* cancelling a reference drag clears the preview and cursor without adding another pill */
+ await page.keyboard.down(key);
+ await page.mouse.move(ruler.x + 40, y);
+ await page.mouse.down();
+ await page.mouse.move(ruler.x + 140, y, { steps: 5 });
+ await draft.waitFor({ state: 'visible' });
+ await page.evaluate(() => window.dispatchEvent(new Event('blur')));
+ await draft.waitFor({ state: 'hidden' });
+ await page.mouse.up();
+ await page.keyboard.up(key);
+ assert.equal((await referred()).length, 2);
+ assert.equal(await page.evaluate(() => document.body.classList.contains('tl-pinning')), false);
} finally {
await browser?.close();
await studio?.close();
diff --git a/packages/openfilm/studio/server/project-presence.mjs b/packages/openfilm/studio/server/project-presence.mjs
new file mode 100644
index 0000000..f0a7d6b
--- /dev/null
+++ b/packages/openfilm/studio/server/project-presence.mjs
@@ -0,0 +1,15 @@
+// @ts-check
+import { statSync } from 'node:fs';
+import { join } from 'node:path';
+import { FILM_FILE } from '../../src/film-doc.mjs';
+
+/**
+ * A project needs both its folder and its film file. Contents are checked by the editor separately: an empty or
+ * unfinished film is still a file the person or agent can fix. Nothing is created while checking presence.
+ * @param {string} root @returns {'folder' | 'film' | undefined}
+ */
+export function projectMissing(root) {
+ if (!statSync(root, { throwIfNoEntry: false })?.isDirectory()) return 'folder';
+ if (!statSync(join(root, FILM_FILE), { throwIfNoEntry: false })?.isFile()) return 'film';
+ return undefined;
+}
diff --git a/packages/openfilm/studio/server/projects.mjs b/packages/openfilm/studio/server/projects.mjs
index 2f1d2d4..3b02dac 100644
--- a/packages/openfilm/studio/server/projects.mjs
+++ b/packages/openfilm/studio/server/projects.mjs
@@ -25,6 +25,7 @@ import { FILM_FILE, filmHtml } from '../../src/film-doc.mjs';
import { writeAtomic } from './atomic.mjs';
import { coverAt } from './cover.mjs';
import { libraryProjects, libraryRoot } from '../../src/locations.mjs';
+import { projectMissing } from './project-presence.mjs';
export const TOOL_DIR = '.film';
@@ -194,11 +195,12 @@ function folderName(/** @type {string} */ name) {
*/
const describe = (/** @type {Recent} */ r) => {
const created = statSync(r.path, { throwIfNoEntry: false });
+ const missingReason = projectMissing(r.path);
const duration = filmDuration(r.path);
const cover = coverAt(r.path);
return {
- /* `missing`: its folder is gone (one that only lost its film.html is still there, and still opens) */
- id: r.id, path: r.path, name: basename(r.path), openedAt: r.openedAt, missing: !created?.isDirectory(),
+ id: r.id, path: r.path, name: basename(r.path), openedAt: r.openedAt, missing: Boolean(missingReason),
+ ...(missingReason ? { missingReason } : {}),
createdAt: created ? Math.round(created.birthtimeMs || created.ctimeMs) : r.openedAt,
...(duration != null ? { duration } : {}),
...(r.folderId ? { folderId: r.folderId } : {}),
@@ -428,12 +430,12 @@ export async function renameProject(/** @type {string} */ id, /** @type {string}
/**
* Delete a project: its folder goes to the system's Trash (where the person can still take it back), and it leaves the
- * list. A folder that is already gone just leaves the list.
+ * list. An unavailable project just leaves the list; any remaining files are kept.
*/
export async function deleteProject(/** @type {string} */ id) {
const found = (await readState()).recent.find((r) => r.id === id);
if (!found) throw new ProjectError('no such project', 404);
- if (existsSync(found.path)) await moveToTrash(found.path);
+ if (!projectMissing(found.path)) await moveToTrash(found.path);
await forgetProject(id);
}
diff --git a/packages/openfilm/studio/server/projects.test.mjs b/packages/openfilm/studio/server/projects.test.mjs
index 0f715b1..ed6e545 100644
--- a/packages/openfilm/studio/server/projects.test.mjs
+++ b/packages/openfilm/studio/server/projects.test.mjs
@@ -1,9 +1,9 @@
import { test, beforeEach } from 'node:test';
import assert from 'node:assert/strict';
-import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, symlinkSync, writeFileSync } from 'node:fs';
+import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { homedir, tmpdir } from 'node:os';
import { join } from 'node:path';
-import { createFolder, createProject, forgetProject, listFolders, listProjects, locateProject, moveFolder, moveLibrary, openProject, projectById, renameProject, ProjectError } from './projects.mjs';
+import { createFolder, createProject, deleteProject, forgetProject, listFolders, listProjects, locateProject, moveFolder, moveLibrary, openProject, projectById, renameProject, ProjectError } from './projects.mjs';
import { chooseFolder } from '../../src/locations.mjs';
import { readFilmFile } from '../../src/film-doc.mjs';
@@ -101,10 +101,29 @@ test('forgetting a project leaves its folder; a deleted folder shows as missing'
const q = await openProject(join(scratch, 'gone'));
(await import('node:fs')).rmSync(q.path, { recursive: true });
assert.equal((await listProjects()).find((x) => x.id === q.id).missing, true);
- /* only the folder being gone is missing: one that lost its film.html is still there (and opens) */
+ /* caches or other remaining files do not make a folder without its film a project */
const r = await openProject(join(scratch, 'no-film'));
- (await import('node:fs')).rmSync(join(r.path, 'film.html'));
- assert.equal((await listProjects()).find((x) => x.id === r.id).missing, false);
+ const film = readFileSync(join(r.path, 'film.html'), 'utf8');
+ rmSync(join(r.path, 'film.html'));
+ assert.equal((await listProjects()).find((x) => x.id === r.id).missing, true);
+ assert.equal((await projectById(r.id)).missingReason, 'film');
+ writeFileSync(join(r.path, 'film.html'), film);
+ assert.equal((await projectById(r.id)).missing, false, 'restoring the file makes it available again');
+ writeFileSync(join(r.path, 'film.html'), '');
+ assert.equal((await projectById(r.id)).missing, false, 'an existing empty file can still be edited');
+ rmSync(join(r.path, 'film.html'));
+ mkdirSync(join(r.path, 'film.html'));
+ assert.equal((await projectById(r.id)).missingReason, 'film', 'a directory named film.html is not a film file');
+});
+
+test('taking an unavailable project off the list preserves its remaining assets and history', async () => {
+ const project = await openProject(join(scratch, 'remaining-files'));
+ rmSync(join(project.path, 'film.html'));
+ writeFileSync(join(project.path, 'keep.txt'), 'work to recover');
+ await deleteProject(project.id);
+ assert.equal(readFileSync(join(project.path, 'keep.txt'), 'utf8'), 'work to recover');
+ assert.equal(readFileSync(join(project.path, '.film', 'id'), 'utf8').trim(), project.id);
+ assert.ok(!(await listProjects()).some((p) => p.id === project.id));
});
test('the disk root, the home folder and files are not projects', async () => {
diff --git a/packages/openfilm/studio/server/server.mjs b/packages/openfilm/studio/server/server.mjs
index 5485fa6..db95e29 100644
--- a/packages/openfilm/studio/server/server.mjs
+++ b/packages/openfilm/studio/server/server.mjs
@@ -43,6 +43,7 @@ import { ensurePreviews, knownLate } from './preview-cache.mjs';
import { npmOpenfilm, olderThanThis } from '../client.mjs';
import { writeAtomic } from './atomic.mjs';
import { createWatchers } from './watch.mjs';
+import { projectMissing } from './project-presence.mjs';
import { installedFonts } from './fonts.mjs';
import { projectFonts, resolveIn } from './project-fonts.mjs';
import { FILM_PAGE, PageFrameError, closePageFrames, filmPoster, pageFacts, pageFrame, warmFilmPoster } from './pageframes.mjs';
@@ -548,9 +549,14 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowse
}
const project = await projectById(parts[1]);
const rest = parts.slice(2).join('/');
- /* a project whose folder is gone (moved, renamed or deleted outside Studio): taking it off the list is all there is */
- if (!existsSync(project.path) && !(!rest && req.method === 'DELETE')) {
- throw new HttpError(410, 'This project’s folder is not there any more: it was moved, renamed or deleted.', { code: 'missing' });
+ /* Never enter or write into a project removed outside Studio, even if cache writers left its folder behind. */
+ const requireProject = () => {
+ const missing = projectMissing(project.path);
+ if (missing) throw new HttpError(410, missing === 'film' ? 'This project’s film.html is missing.'
+ : 'This project’s folder is not there any more: it was moved, renamed or deleted.', { code: missing === 'film' ? 'missing-film' : 'missing' });
+ };
+ if (!(!rest && req.method === 'DELETE')) {
+ requireProject();
}
/* ── subtitles: the film's lines, the person's subtitle style, translation (see captions.mjs) ── */
if (await captionRoutes(req, res, project.path, rest, { translate: subtitleTranslator, transcribe: await subtitleTranscriber() })) return;
@@ -565,6 +571,7 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowse
/* `folder`: the project's files on the film's origin, where the preview loads them */
if (req.method === 'GET') {
const film = await readProjectFilm(project.path);
+ requireProject();
/* opened: its card in the projects list gets a picture before the list first shows it */
if (film.doc?.tracks.some((t) => t.clips.length)) warmFilmPoster(project.path, pages.folderUrl(project));
return json(res, 200, { project, folder: pages.folderUrl(project), ...film });
@@ -996,7 +1003,7 @@ export async function startStudio({ port = 4747, key, openBrowser = systemBrowse
}
if (parts.length === 4 && parts[0] === 'api' && parts[1] === 'projects' && parts[3] === 'events') {
const project = await projectById(parts[2]).catch(() => null);
- if (!project || !existsSync(project.path)) return refuse('404 Not Found');
+ if (!project || project.missing) return refuse('404 Not Found');
const send = acceptWebSocket(req, socket, () => stop());
if (send) stop = projectStream(project, send);
return;
diff --git a/packages/openfilm/studio/server/server.test.mjs b/packages/openfilm/studio/server/server.test.mjs
index d0520f9..14a3607 100644
--- a/packages/openfilm/studio/server/server.test.mjs
+++ b/packages/openfilm/studio/server/server.test.mjs
@@ -526,6 +526,29 @@ test('a project whose folder is gone says so, never takes Studio down, and can b
assert.ok(!(await (await api('/api/projects')).json()).projects.some((p) => p.id === project.id));
});
+test('a removed film is unavailable before opening or editing; remaining files are preserved on removal', async () => {
+ const { project } = await (await api('/api/projects', { method: 'POST', body: { path: join(scratch, 'Film removed externally') } })).json();
+ rmSync(join(project.path, 'film.html'));
+ writeFileSync(join(project.path, 'keep.txt'), 'remaining work');
+ for (const [rest, options] of [
+ ['', {}],
+ ['/opened', { method: 'POST' }],
+ ['/files', {}],
+ ['/edit', { method: 'POST', body: { ops: [{ op: 'insert', clip: { src: 'title.html' } }] } }],
+ ]) {
+ const response = await api(`/api/projects/${project.id}${rest}`, options);
+ assert.equal(response.status, 410, rest || 'opening the project');
+ assert.equal((await response.json()).code, 'missing-film');
+ }
+ assert.ok(!existsSync(join(project.path, 'film.html')), 'opening or editing never recreates the removed film');
+ const listed = (await (await api('/api/projects')).json()).projects.find((p) => p.id === project.id);
+ assert.equal(listed.missing, true);
+ assert.equal(listed.missingReason, 'film');
+ assert.equal((await api(`/api/projects/${project.id}`, { method: 'DELETE' })).status, 200);
+ assert.equal(readFileSync(join(project.path, 'keep.txt'), 'utf8'), 'remaining work');
+ assert.equal((await api('/api/health')).status, 200);
+});
+
test('a page gone mid-request (its connection reset) ends only its own stream, never Studio', async () => {
const { port } = new URL(studio.origin);
const upgrade = (path, key) => `GET ${path} HTTP/1.1\r\nHost: 127.0.0.1:${port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n`
diff --git a/packages/openfilm/studio/server/watch.mjs b/packages/openfilm/studio/server/watch.mjs
index eb99c39..70c567f 100644
--- a/packages/openfilm/studio/server/watch.mjs
+++ b/packages/openfilm/studio/server/watch.mjs
@@ -4,17 +4,20 @@
* file (`files`: a page, a picture, a sound). One watcher per open project, shared by every page showing it, closed when
* the last one leaves. Studio's own folders and the usual build and dependency folders are not watched.
*/
-import { existsSync, readdirSync, watch } from 'node:fs';
+import { readdirSync, watch } from 'node:fs';
import { join } from 'node:path';
import { readProjectFilm } from './film.mjs';
import { FILM_FILE } from '../../src/film-doc.mjs';
+import { projectMissing } from './project-presence.mjs';
/* a dot folder is a tool's (Studio's own .film, .git…), and what builds and packages make is not the film */
const IGNORED = /^(\.[^/\\]+|node_modules|dist|build)([/\\]|$)/;
/** How long changes are gathered before one event: an agent writes a file in several chunks, and often several files. */
const SETTLE_MS = 120;
-/** How long a folder that went is looked at again before its pages are told it is gone. */
+/** How long missing project files are rechecked before their pages are told the project is gone. */
const GONE_RECHECK_MS = 400;
+/** A deleted root is not reliably reported by every file system's watcher. */
+const PRESENCE_MS = 1000;
/* Studio's own half-written files (a file written whole through a random-named sibling, atomic.mjs; an import
streaming in, files.mjs): only the result is a change */
@@ -29,7 +32,7 @@ const WRITING = /(^|[/\\])([^/\\]+\.[0-9a-f-]{8,}\.tmp|\.\d+\.\d+\.importing)$/;
* @typedef {{ type: 'film', rev: string } | { type: 'files', paths?: string[] } | { type: 'history' } | { type: 'export', job: object }
* | { type: 'history-progress', op: string, phase: string, done: number, total: number } | { type: 'project', project: object }
* | { type: 'ask', ask: object } | { type: 'asked', id: string } | { type: 'notice', notice: object }
- * | { type: 'gone' }} FolderEvent `gone`: the project was deleted, or its folder is not there any more
+ * | { type: 'gone' }} FolderEvent `gone`: the project was deleted, or its folder or film file is missing
*/
/**
@@ -44,33 +47,44 @@ export function watchFolder(root, send) {
let timer = /** @type {NodeJS.Timeout | null} */ (null);
let lastRev = '';
let closed = false;
+ let checking = false;
+ let gone = false;
readProjectFilm(root).then((f) => { lastRev = f.rev; }, () => {});
const flush = async () => {
timer = null;
- if (closed) return;
- /* the folder itself went (deleted, or moved away outside Studio): its pages leave the project. Looked at again a
- moment later: a rename in Studio moves its pages to the new folder (createWatchers `move`), closing this */
- if (!existsSync(root)) {
- await new Promise((done) => setTimeout(done, GONE_RECHECK_MS));
- if (!closed && !existsSync(root)) send({ type: 'gone' });
- return;
- }
- const kinds = [...pending];
- const changed = paths;
- pending.clear();
- paths = new Set();
- if (kinds.includes('film')) {
- const { rev } = await readProjectFilm(root).catch(() => ({ rev: '' }));
- /* the same text written again (an editor's save, Studio's own write echoed back) is no change */
- if (closed) return;
- if (rev && rev !== lastRev) { lastRev = rev; send({ type: 'film', rev }); }
+ if (closed || gone || checking) return;
+ checking = true;
+ try {
+ /* A missing film is not an empty one. Recheck after a short grace period: editors can replace files while
+ saving, and a rename in Studio moves the subscription to its new folder, closing this watcher. */
+ if (projectMissing(root)) {
+ await new Promise((done) => setTimeout(done, GONE_RECHECK_MS));
+ if (closed) return;
+ if (projectMissing(root)) { gone = true; pending.clear(); send({ type: 'gone' }); return; }
+ }
+ const kinds = [...pending];
+ const changed = paths;
+ pending.clear();
+ paths = new Set();
+ if (kinds.includes('film')) {
+ const { rev } = await readProjectFilm(root).catch(() => ({ rev: '' }));
+ /* the same text written again (an editor's save, Studio's own write echoed back) is no change */
+ if (closed) return;
+ /* deleted during the read: wait for presence to settle instead of publishing an empty film */
+ if (projectMissing(root)) { pending.add('film'); return; }
+ if (rev && rev !== lastRev) { lastRev = rev; send({ type: 'film', rev }); }
+ }
+ if (kinds.includes('files')) send(changed ? { type: 'files', paths: [...changed] } : { type: 'files' });
+ } finally {
+ checking = false;
+ if (!closed && !gone && pending.size) schedule();
}
- if (kinds.includes('files')) send(changed ? { type: 'files', paths: [...changed] } : { type: 'files' });
};
+ const schedule = () => { if (!timer && !checking && !closed && !gone) timer = setTimeout(flush, SETTLE_MS); };
const close = watchTree(root, (name) => {
- if (closed) return;
+ if (closed || gone) return;
if (!name) { pending.add('files'); pending.add('film'); paths = null; }
else {
const rel = name;
@@ -78,9 +92,11 @@ export function watchFolder(root, send) {
if (rel === FILM_FILE) pending.add('film');
else { pending.add('files'); paths?.add(rel); }
}
- if (!timer) timer = setTimeout(flush, SETTLE_MS);
+ schedule();
});
- return () => { closed = true; if (timer) clearTimeout(timer); close(); };
+ const presence = setInterval(() => { if (!closed && !gone && projectMissing(root)) schedule(); }, PRESENCE_MS);
+ presence.unref();
+ return () => { closed = true; clearInterval(presence); if (timer) clearTimeout(timer); close(); };
}
/**
@@ -96,7 +112,7 @@ export function watchTree(root, onChange, native = process.platform === 'darwin'
let watcher;
try { watcher = watch(root, { recursive: true }, (_event, name) => onChange(name ? String(name).split('\\').join('/') : null)); }
catch { return () => {}; }
- watcher.on('error', () => {});
+ watcher.on('error', () => onChange(null));
return () => watcher.close();
}
/** @type {Map<string, import('node:fs').FSWatcher>} folder-relative folder ('' for the root) → its watcher */
@@ -113,7 +129,7 @@ export function watchTree(root, onChange, native = process.platform === 'darwin'
try { if (readdirSync(join(root, path))) { add(path); addBelow(path); } } catch { /* a file, or gone */ }
});
} catch { return; }
- watcher.on('error', () => { watcher.close(); folders.delete(rel); });
+ watcher.on('error', () => { watcher.close(); folders.delete(rel); onChange(null); });
folders.set(rel, watcher);
};
const addBelow = (/** @type {string} */ rel) => {
diff --git a/packages/openfilm/studio/server/watch.test.mjs b/packages/openfilm/studio/server/watch.test.mjs
index 23dc9de..a147912 100644
--- a/packages/openfilm/studio/server/watch.test.mjs
+++ b/packages/openfilm/studio/server/watch.test.mjs
@@ -4,9 +4,67 @@ import { mkdirSync, mkdtempSync, renameSync, rmSync, writeFileSync } from 'node:
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { revOf } from './film.mjs';
-import { createWatchers, watchTree } from './watch.mjs';
+import { createWatchers, watchFolder, watchTree } from './watch.mjs';
const settle = (ms = 400) => new Promise((r) => setTimeout(r, ms));
+const until = async (ready) => {
+ for (const end = Date.now() + 4000; !ready() && Date.now() < end;) await settle(25);
+ assert.ok(ready(), 'the presence change was reported');
+};
+
+test('a deleted film leaves its editor even when its folder and caches remain; no empty film is published', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'of-watch-film-gone-'));
+ writeFileSync(join(root, 'film.html'), 'original');
+ mkdirSync(join(root, '.film'));
+ const seen = [];
+ const stop = watchFolder(root, (event) => seen.push(event));
+ try {
+ await settle(600);
+ seen.length = 0;
+ rmSync(join(root, 'film.html'));
+ await until(() => seen.some((e) => e.type === 'gone'));
+ writeFileSync(join(root, '.film', 'cache'), 'cache written after deletion');
+ await settle(1200);
+ assert.deepEqual(seen, [{ type: 'gone' }]);
+ } finally {
+ stop();
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test('a film briefly removed during a save is refreshed, without closing its editor', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'of-watch-save-'));
+ writeFileSync(join(root, 'film.html'), 'before');
+ const seen = [];
+ const stop = watchFolder(root, (event) => seen.push(event));
+ try {
+ await settle(600);
+ seen.length = 0;
+ rmSync(join(root, 'film.html'));
+ await settle(200);
+ writeFileSync(join(root, 'film.html'), 'after');
+ await until(() => seen.some((e) => e.type === 'film' && e.rev === revOf('after')));
+ assert.ok(!seen.some((e) => e.type === 'gone' || (e.type === 'film' && e.rev === revOf(''))));
+ } finally {
+ stop();
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test('presence is checked even when no native watcher could start, and stops on unsubscribe', async () => {
+ const scratch = mkdtempSync(join(tmpdir(), 'of-watch-missing-'));
+ const seen = [];
+ const stop = watchFolder(join(scratch, 'gone-before-subscribe'), (event) => seen.push(event));
+ try {
+ await until(() => seen.some((e) => e.type === 'gone'));
+ } finally { stop(); }
+ const cancelled = [];
+ const cancel = watchFolder(join(scratch, 'also-gone'), (event) => cancelled.push(event));
+ cancel();
+ await settle(1600);
+ assert.deepEqual(cancelled, []);
+ rmSync(scratch, { recursive: true, force: true });
+});
test('film.html changes come with their revision, other files as one files event; .film/ is not watched', async () => {
const root = mkdtempSync(join(tmpdir(), 'of-watch-'));
diff --git a/packages/openfilm/studio/ui/src/api.ts b/packages/openfilm/studio/ui/src/api.ts
index bd75b88..1c90d44 100644
--- a/packages/openfilm/studio/ui/src/api.ts
+++ b/packages/openfilm/studio/ui/src/api.ts
@@ -13,7 +13,7 @@ export interface StudioVersion { version: string; latest: string | null; newer:
update?: { status: 'updating' | 'failed'; version: string; error?: string } }
/** `cover`: when the person set a cover of its own (studio/server/cover.mjs), absent when it has none. */
-export type Project = { id: string; path: string; name: string; openedAt: number; missing: boolean; working?: boolean; cover?: number };
+export type Project = { id: string; path: string; name: string; openedAt: number; missing: boolean; missingReason?: 'folder' | 'film'; working?: boolean; cover?: number };
export type Clip = { src: string; id: string; at?: number; time?: [number] | [number, number];
box?: { x: number; y: number; w?: number; h?: number; r?: number }; volume?: number; speed?: number; overrides?: unknown[];
/** a page that sets no size of its own: the px it is laid out at (the stage's without it) */
@@ -199,7 +199,7 @@ export type StudioNotice = { id: string; kind: 'balance'; provider: string; prov
export type FolderEvent = { type: 'film'; rev: string } | { type: 'files'; paths?: string[] } | { type: 'history' } | { type: 'export'; job: ExportJob } | { type: 'open'; to: string }
| { type: 'history-progress'; op: string; phase: string; done: number; total: number }
| { type: 'ask'; ask: SpendAsk } | { type: 'asked'; id: string } | { type: 'notice'; notice: StudioNotice } | { type: 'project'; project: Project }
- /* the project was deleted, or its folder is not there any more: its pages leave it */
+ /* the project was deleted, or its folder or film file is missing: its pages leave it */
| { type: 'gone' };
/**
@@ -313,7 +313,7 @@ export function projectEvents(id: string, on: (event: FolderEvent) => void): ()
/* back after Studio was away: the film, the files and the history may all have changed meanwhile */
const stop = listen(`${p(id)}/events`, tell, {
onBack: () => { tell({ type: 'film', rev: '' }); tell({ type: 'files' }); tell({ type: 'history' }); },
- /* the project off the list, or its folder missing: gone (a list that can't be read says nothing) */
+ /* off the list, or missing its folder or film file: gone (an unreadable list says nothing) */
gone: () => call<{ projects: Project[] }>('projects').then((r) => { const found = r.projects.find((x) => x.id === id); return !found || Boolean(found.missing); }),
});
stream = { stop, listeners };
diff --git a/packages/openfilm/studio/ui/src/components/ProjectView.tsx b/packages/openfilm/studio/ui/src/components/ProjectView.tsx
index 1d977d6..357b783 100644
--- a/packages/openfilm/studio/ui/src/components/ProjectView.tsx
+++ b/packages/openfilm/studio/ui/src/components/ProjectView.tsx
@@ -219,7 +219,7 @@ export function ProjectView({ projectId, onProject, onLeave }: {
/* ── the project, its film and its files ── */
React.useEffect(() => {
/* a project the list no longer has (deleted meanwhile, a tab of it opened again): gone, so this page leaves it */
- api.film(projectId).then(setLoaded, (e: Error) => { if (e instanceof ApiError && e.status === 404) leaveRef.current(); else setFailure(e.message); });
+ api.film(projectId).then(setLoaded, (e: Error) => { if (e instanceof ApiError && (e.status === 404 || e.status === 410)) leaveRef.current(); else setFailure(e.message); });
void api.opened(projectId).catch(() => {});
const loadFiles = () => api.files(projectId).then(setRawListing, () => {});
void loadFiles();
@@ -562,13 +562,6 @@ export function ProjectView({ projectId, onProject, onLeave }: {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [pause]);
const scrubCommit = React.useCallback((ms: number) => { pause(); seek(ms); }, [pause, seek]);
- /* the timeline's preview axis: the picture at the moment under the pointer, the clock and the playhead staying; null:
- back to the playhead's picture. Not while playing (the picture is the film's then) */
- const hoverPreview = React.useCallback((ms: number | null) => {
- if (player.current.playing) return;
- preview.current?.seek(pictureAt(ms == null ? player.current.time() : Math.max(0, ms / 1000)));
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
/* a seek asked for past the film's end as it was (the end of a clip just put on): made once the film is that long */
const seekWhenLonger = React.useRef<number | null>(null);
@@ -1323,6 +1316,13 @@ export function ProjectView({ projectId, onProject, onLeave }: {
));
/* the range marked on the timeline (⇧-drag on the ruler, I and O): Studio's, told to the app with the selection */
const [markedRange, setMarkedRange] = React.useState<FilmRange | null>(null);
+ /* Clicking a range in chat briefly points it out, separately from the editing selection. */
+ const [flashRange, setFlashRange] = React.useState<FilmRange | null>(null);
+ React.useEffect(() => {
+ if (!flashRange) return;
+ const timer = setTimeout(() => setFlashRange(null), 1200);
+ return () => clearTimeout(timer);
+ }, [flashRange]);
rangeNowRef.current = markedRange;
/* the film's stage, for boxes in stage px (film.html's, set below with the picture) */
const stageRef = React.useRef({ w: 1920, h: 1080 });
@@ -1430,6 +1430,12 @@ export function ProjectView({ projectId, onProject, onLeave }: {
if (command.type === 'show-subtitle') { setInspectorContent('subtitles'); setInspectorOpen(true); }
const startMs = Math.max(0, Math.min(command.start, command.end) * 1000);
const endMs = Math.max(command.start, command.end) * 1000;
+ if (command.type === 'show-range') {
+ if (endMs > startMs) setFlashRange({ startMs, endMs });
+ pause();
+ seek(startMs);
+ return;
+ }
if (endMs > startMs) setMarkedRange({ startMs, endMs });
pause();
seek(startMs);
@@ -1828,15 +1834,6 @@ export function ProjectView({ projectId, onProject, onLeave }: {
/* clips dragged out of the timeline onto the app's chat */
const referBlocks = React.useCallback((blocks: TimelineBlock[]) => { for (const b of blocks) studioHost?.refer?.(refOfBlock(b)); }, []); // eslint-disable-line react-hooks/exhaustive-deps
const markedRangeRef = React.useCallback((range: FilmRange) => rangeRef(projectId, range, blocksRef.current), [projectId]);
- /* the selection bar's "Add to chat" (components/SelectionToolbar): on the timeline the clips and the range, or the
- moment of a point picked on the ruler; on the picture what is in hand there */
- const referFromTimeline = React.useCallback((what: { blocks: readonly TimelineBlock[]; range: FilmRange | null; atMs: number | null }) => {
- const refer = studioHost?.refer;
- if (!refer) return;
- if (what.atMs != null) { refer(momentRef(projectId, what.atMs)); return; }
- for (const b of what.blocks) refer(refOfBlock(b));
- if (what.range) refer(rangeRef(projectId, what.range, blocksRef.current));
- }, [projectId]); // eslint-disable-line react-hooks/exhaustive-deps
/* the ruler points at time for the chat: a ⌘-click, that moment; a ⌘-drag, that span */
const referRuler = React.useCallback((what: { atMs: number } | { range: FilmRange }) => {
const refer = studioHost?.refer;
@@ -2509,15 +2506,14 @@ export function ProjectView({ projectId, onProject, onLeave }: {
case 'select-left': case 'select-right': take(); if (once) commands.selectSide(cmd === 'select-left' ? -1 : 1); return;
case 'ripple-start': take(); if (once) commands.rippleTrimStart(); return;
case 'ripple-end': take(); if (once) commands.rippleTrimEnd(); return;
- case 'toggle-snap': case 'toggle-magnet': case 'toggle-linkage': case 'toggle-preview-axis': {
+ case 'toggle-snap': case 'toggle-magnet': case 'toggle-linkage': {
take();
if (!once) return;
- const pref = cmd === 'toggle-snap' ? 'snap' : cmd === 'toggle-magnet' ? 'magnet' : cmd === 'toggle-linkage' ? 'linkage' : 'previewAxis';
+ const pref = cmd === 'toggle-snap' ? 'snap' : cmd === 'toggle-magnet' ? 'magnet' : 'linkage';
const on = !readTimelinePrefs()[pref];
if (pref === 'snap') commands.toggleSnap();
else if (pref === 'magnet') commands.toggleMagnet();
- else if (pref === 'linkage') commands.toggleLinkage();
- else commands.togglePreviewAxis();
+ else commands.toggleLinkage();
toast.show(`${t(`timeline.${pref}`)} · ${t(`timeline.${pref}${on ? 'On' : 'Off'}`)}`);
return;
}
@@ -3064,10 +3060,11 @@ export function ProjectView({ projectId, onProject, onLeave }: {
{...(hostHover ? { onHoverBlock: hoverBlock } : {})}
/* the range (I / O, ⇧-drag on the ruler, Play range) is Studio's own; referring it is the app's */
range={markedRange}
+ flashRange={flashRange}
onRangeChange={setMarkedRange}
trackMenuExtra={trackMenuExtra}
{...(studioHost?.refer ? {
- onReferBlocks: referBlocks, rangeRef: markedRangeRef, onReferSelection: referFromTimeline, onReferRuler: referRuler,
+ onReferBlocks: referBlocks, rangeRef: markedRangeRef, onReferRuler: referRuler,
} : {})}
commandsRef={timelineCommands}
trackNames={trackNames}
@@ -3089,7 +3086,6 @@ export function ProjectView({ projectId, onProject, onLeave }: {
onSeek={(ms) => seek(ms)}
onScrubPreview={scrubPreview}
onScrubCommit={scrubCommit}
- onHoverPreview={hoverPreview}
onRemove={removeBlock}
onRemoveMany={removeBlocks}
onSplit={splitBlocks}
diff --git a/packages/openfilm/studio/ui/src/components/ProjectsLibrary.tsx b/packages/openfilm/studio/ui/src/components/ProjectsLibrary.tsx
index 26aabe1..ef5713b 100644
--- a/packages/openfilm/studio/ui/src/components/ProjectsLibrary.tsx
+++ b/packages/openfilm/studio/ui/src/components/ProjectsLibrary.tsx
@@ -4,9 +4,9 @@
* file projects in folders of the list; or, switched to "Examples", to start from an example (ExamplesGallery). Its
* projects are ProjectsView; this file holds the data and actions.
*
- * Studio's projects are folders on disk: deleting one moves its folder to the system's Trash. One whose folder is gone
- * (moved, renamed or deleted outside Studio: `missing`) cannot be opened; it can be located (the folder it is in now)
- * or taken off the list.
+ * Studio's projects are folders on disk: deleting one moves its folder to the system's Trash. One whose folder or film
+ * file is gone (`missing`) cannot be opened; it can be located (the folder it is in now) or taken off the list,
+ * preserving any remaining files.
*
* A folder is picked with the app's own dialog where there is an app (lib/host.ts `folders`), else with Studio's
* folder browser; one without a film is opened only once the person agrees to start a film in it.
@@ -54,32 +54,35 @@ 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. Waited for a
- while only: a list that never comes is said, not shown as a spinner for ever (one shown already stays) */
+ /* Read on open and when coming back to it (focus, shown again), as returning from Finder. External changes need no
+ app restart, and a slow refresh never overlaps the next one or hides the list already shown. Opening a card
+ checks that project again (openListed). */
React.useEffect(() => {
if (!open) return undefined;
let alive = true;
+ let loading = false;
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; };
+ const refresh = () => {
+ if (!alive || loading) return;
+ loading = true;
+ void 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);
+ setLoadFailed(false);
+ },
+ () => { if (alive) setLoadFailed(true); },
+ ).finally(() => { loading = false; });
+ };
+ const visible = () => { if (document.visibilityState === 'visible') refresh(); };
+ refresh();
+ window.addEventListener('focus', visible);
+ document.addEventListener('visibilitychange', visible);
+ return () => { alive = false; window.removeEventListener('focus', visible); document.removeEventListener('visibilitychange', visible); };
}, [open, tries]);
const retryLoad = React.useCallback(() => setTries((n) => n + 1), []);
- /* shown again (the app's projects page when the last tab closes, a window brought back): read afresh, as it may
- have changed meanwhile */
- React.useEffect(() => {
- if (!open) return undefined;
- const back = () => { if (document.visibilityState === 'visible') retryLoad(); };
- document.addEventListener('visibilitychange', back);
- return () => document.removeEventListener('visibilitychange', back);
- }, [open, retryLoad]);
const reloadFolders = React.useCallback(() => {
void folderApi.list().then(setFolders, () => {});
@@ -292,6 +295,28 @@ export function ProjectsPopover({
setBusy(kind);
onOpen(projectId);
};
+
+ /** The card may have gone since the last refresh: check before opening a tab or entering the editor. */
+ async function openListed(project: LibraryProject) {
+ if (project.missing) { lib.flash(t(project.missingReason === 'film' ? 'projects.missingFilmOpen' : 'projects.missingOpen')); return; }
+ setBusy('opening');
+ try {
+ const { project: current } = await within(api.opened(project.id), LIST_WAIT_MS);
+ if (current.missing) {
+ setBusy(null);
+ lib.retryLoad();
+ lib.flash(t(current.missingReason === 'film' ? 'projects.missingFilmOpen' : 'projects.missingOpen'));
+ return;
+ }
+ go(project.id, 'opening');
+ } catch (e) {
+ setBusy(null);
+ lib.retryLoad();
+ lib.flash(e instanceof ApiError && (e.status === 404 || e.status === 410)
+ ? t(e.body.code === 'missing-film' ? 'projects.missingFilmOpen' : 'projects.missingOpen')
+ : t('projects.openFolderFailed').replace('{error}', e instanceof Error ? e.message : String(e)));
+ }
+ }
/* closed: nothing in progress shows when it opens again */
React.useEffect(() => { if (!open) setBusy(null); }, [open]);
/* another project opened: done */
@@ -394,7 +419,7 @@ export function ProjectsPopover({
if (!open) return null;
- /* what the delete dialog says: a project whose folder is gone only leaves the list (the server keeps to that too) */
+ /* unavailable projects only leave the list; any remaining files stay on disk */
const pendingMissing = (pendingDelete ?? []).filter((id) => lib.projects.find((p) => p.id === id)?.missing).length;
const onlyMissing = pendingDelete != null && pendingMissing === pendingDelete.length;
const deleteTitle = !pendingDelete ? ''
@@ -440,8 +465,8 @@ export function ProjectsPopover({
onOpenFolder={() => void openFolder()}
onGetFromGitHub={() => setGithub({})}
onLocate={(project) => void locate(project)}
- /* its folder is gone: there is nothing to open, and the editor would only say so */
- onOpen={(project) => (project.missing ? lib.flash(t('projects.missingOpen')) : go(project.id, 'opening'))}
+ /* presence is checked again before opening the editor */
+ onOpen={(project) => { void openListed(project); }}
onRename={(projectId, name) => void lib.renameProject(projectId, name)}
/* an agent working in one: said at once, before asking (the server refuses it too) */
onDelete={(ids) => void lib.workingIn(ids).then((working) => {
diff --git a/packages/openfilm/studio/ui/src/components/ProjectsView.tsx b/packages/openfilm/studio/ui/src/components/ProjectsView.tsx
index 03b23a4..92ba9fc 100644
--- a/packages/openfilm/studio/ui/src/components/ProjectsView.tsx
+++ b/packages/openfilm/studio/ui/src/components/ProjectsView.tsx
@@ -692,7 +692,7 @@ function ProjectCard({
) : null}
</button>
<SelectToggle selecting={selecting} selected={selected} onToggle={onToggleSelect} label={t('library.toggleSelect')} />
- {project.missing && !selecting ? <MissingActions onLocate={onLocate} onRemove={onDelete} /> : null}
+ {project.missing && !selecting ? <MissingActions reason={project.missingReason} onLocate={onLocate} onRemove={onDelete} /> : null}
</div>
<div className="mt-2 flex min-w-0 items-start gap-1.5">
@@ -713,7 +713,7 @@ function ProjectCard({
>
<Video size={11} />
{formatDate(project.openedAt, language)}
- {project.missing ? <span className="truncate text-[var(--err)]">· {t('projects.missing')}</span> : null}
+ {project.missing ? <span className="truncate text-[var(--err)]">· {t(project.missingReason === 'film' ? 'projects.missingFilm' : 'projects.missing')}</span> : null}
{project.working ? <span className="truncate text-[var(--accent)]">· {t('projects.agentRunning')}</span> : null}
</button>
</div>
@@ -727,12 +727,12 @@ function ProjectCard({
* On the cover of a project whose folder is gone: "Folder not found", and the two things to do about it: point it at
* the folder it is in now (it keeps its place, and its history goes with the folder), or take it off the list.
*/
-function MissingActions({ onLocate, onRemove, compact = false }: { onLocate: () => void; onRemove: () => void; compact?: boolean }) {
+function MissingActions({ reason, onLocate, onRemove, compact = false }: { reason?: Project['missingReason']; onLocate: () => void; onRemove: () => void; compact?: boolean }) {
const t = useT();
const button = 'inline-flex h-7 items-center gap-1.5 rounded-lg px-2.5 text-[12px] font-medium transition';
return (
<div className={compact ? 'flex items-center gap-1' : 'pointer-events-none absolute inset-0 flex flex-col items-center justify-center gap-2 p-2'}>
- {compact ? null : <span className="text-[12px] font-semibold text-white drop-shadow">{t('projects.missing')}</span>}
+ {compact ? null : <span className="text-[12px] font-semibold text-white drop-shadow">{t(reason === 'film' ? 'projects.missingFilm' : 'projects.missing')}</span>}
<div className="pointer-events-auto flex items-center gap-1.5">
<button type="button" onClick={onLocate} className={`${button} bg-[var(--surface)] text-[var(--text)] shadow hover:brightness-95`}>
<FolderSearch size={13} />
@@ -831,12 +831,12 @@ function ProjectListRow({
</p>
<p className="mt-2 flex items-center gap-2 text-[11.5px] text-[var(--text-faint)]">
{formatDate(project.openedAt, language)}
- {project.missing ? <span className="text-[var(--err)]">· {t('projects.missing')}</span> : null}
+ {project.missing ? <span className="text-[var(--err)]">· {t(project.missingReason === 'film' ? 'projects.missingFilm' : 'projects.missing')}</span> : null}
{project.working ? <span className="text-[var(--accent)]">· {t('projects.agentRunning')}</span> : null}
</p>
</button>
</div>
- {project.missing && !selecting ? <MissingActions compact onLocate={onLocate} onRemove={onDelete} /> : null}
+ {project.missing && !selecting ? <MissingActions compact reason={project.missingReason} onLocate={onLocate} onRemove={onDelete} /> : null}
{!selecting ? <ItemMenu project={project} onOpen={onOpen} onStartRename={onStartRename} onStartSelect={onStartSelect} onMoveToFolder={onMoveToFolder} onLocate={onLocate} onDelete={onDelete} size={15} /> : null}
</article>
);
diff --git a/packages/openfilm/studio/ui/src/components/SubtitleRow.tsx b/packages/openfilm/studio/ui/src/components/SubtitleRow.tsx
index 7e17890..9afe6d2 100644
--- a/packages/openfilm/studio/ui/src/components/SubtitleRow.tsx
+++ b/packages/openfilm/studio/ui/src/components/SubtitleRow.tsx
@@ -145,9 +145,11 @@ export const SubtitleRow = React.forwardRef<SubtitleRowHandle, {
snap: boolean;
/** Where the row's drags snap besides other cues: 0, the playhead, every clip's edges. */
snapTargets: () => SnapTarget[];
+ /** Empty row space seeks and scrubs, just like the ruler; cue and text edits keep their own gestures. */
+ onScrub: (event: React.PointerEvent) => void;
/** Why an edit could not be done, said in the timeline's toolbar. */
onError: (text: string) => void;
-}>(function SubtitleRow({ spec, pxPerMs, scrollLeft, width, playheadMs, snap, snapTargets, onError }, ref) {
+}>(function SubtitleRow({ spec, pxPerMs, scrollLeft, width, playheadMs, snap, snapTargets, onScrub, onError }, ref) {
const t = useT();
const cues = React.useMemo(() => rowOrder(spec.cues), [spec.cues]);
const [selected, setSelected] = React.useState<string | null>(null);
@@ -347,7 +349,7 @@ export const SubtitleRow = React.forwardRef<SubtitleRowHandle, {
data-subtitle-row=""
className="relative shrink-0 overflow-hidden border-b select-none"
style={{ height: SUBTITLE_ROW_H, background: 'var(--tl-lane)', borderColor: 'var(--tl-line)' }}
- onPointerDown={(e) => { if (e.button === 0) { setSelected(null); targeted.current = true; } }}
+ onPointerDown={(e) => { if (e.button === 0) { setSelected(null); targeted.current = true; onScrub(e); } }}
onContextMenu={(e) => openMenu(e, null)}
>
<div ref={innerRef} className="absolute inset-y-0 left-0" style={{ width, transform: `translate3d(${-scrollLeft}px,0,0)` }}>
diff --git a/packages/openfilm/studio/ui/src/components/Timeline.tsx b/packages/openfilm/studio/ui/src/components/Timeline.tsx
index 5de7b91..4801eef 100644
--- a/packages/openfilm/studio/ui/src/components/Timeline.tsx
+++ b/packages/openfilm/studio/ui/src/components/Timeline.tsx
@@ -49,7 +49,6 @@ import {
Link2Off,
Mic,
SeparatorVertical,
- TextCursor,
BetweenHorizontalStart,
ArrowLeftToLine,
ArrowRightToLine,
@@ -558,6 +557,8 @@ export interface TimelineProps {
onReferBlocks?: (blocks: TimelineBlock[]) => void;
/** The range marked on the ruler (the editor keeps it): drawn as a band across the tracks. */
range?: FilmRange | null;
+ /** A range recalled from the chat: a quiet, temporary highlight, separate from the editing selection. */
+ flashRange?: FilmRange | null;
/**
* What the app's chat points at (lib/chat-marks): the clip, track or span of the pill hovered there, lit; and the
* clips of the message being written, each with its number.
@@ -574,11 +575,6 @@ export interface TimelineProps {
* It is about the clips selected, the range marked or the point picked on the ruler, whichever was picked last.
*/
selectionBar?: boolean;
- /**
- * The bar's first button, "Add to chat": the clips selected and the range marked (either, or both), or the moment
- * at the playhead (`atMs`) for a point picked on the ruler. Without it the bar has no such button.
- */
- onReferSelection?: (what: { blocks: readonly TimelineBlock[]; range: FilmRange | null; atMs: number | null }) => void;
/**
* With the app's chat: the ruler points at time for it with ⌘ (Ctrl on Windows) held, as a box is drawn on the
* picture. A ⌘-click there is that moment, a ⌘-drag that span, each one a pill in the chat. A plain click or drag
@@ -602,12 +598,6 @@ export interface TimelineProps {
onScrubPreview: (ms: number) => void;
/** On release, once: settle. */
onScrubCommit: (ms: number) => void;
- /**
- * The preview axis (a switch in the toolbar): the picture at the moment under the pointer while it
- * moves over the tracks, the playhead staying where it is; null: back to the playhead's picture. Without it there is
- * no preview axis.
- */
- onHoverPreview?: (ms: number | null) => void;
/** A single seek: the keyboard. */
onSeek: (ms: number) => void;
/** Delete a clip from film.html. Null = done. */
@@ -743,11 +733,10 @@ export interface TimelineCommands {
unlink: () => void;
/** [ / ]: every clip before / after the playhead selected (lib/timeline-nav sideTargets). */
selectSide: (dir: -1 | 1) => void;
- /** The switches (see lib/timeline-prefs): the main-track magnet, snapping, linkage, the preview axis. */
+ /** The switches (see lib/timeline-prefs): the main-track magnet, snapping and linkage. */
toggleMagnet: () => void;
toggleSnap: () => void;
toggleLinkage: () => void;
- togglePreviewAxis: () => void;
/**
* ⌘B: split the selected clips at the playhead; with nothing selected, the clip under it on the main track, else on
* the targeted track (the one last pressed), else on the topmost track seen. The clips linked to them go too.
@@ -938,12 +927,12 @@ export const Timeline = React.memo(function Timeline({
trackMenuExtra,
onReferBlocks,
range,
+ flashRange,
chat,
onHoverBlock,
onRangeChange,
rangeRef,
selectionBar = false,
- onReferSelection,
onReferRuler,
onDuplicate,
onPlayRange,
@@ -953,7 +942,6 @@ export const Timeline = React.memo(function Timeline({
playing,
onScrubPreview,
onScrubCommit,
- onHoverPreview,
onSeek,
onRemove,
onRemoveMany,
@@ -1039,7 +1027,7 @@ export const Timeline = React.memo(function Timeline({
};
const [zoom, setZoom] = React.useState(ZOOM_DEFAULT);
- /* the switches (the main-track magnet, snapping, linkage, the preview axis); kept on this machine */
+ /* the switches (the main-track magnet, snapping and linkage); kept on this machine */
const prefs = useTimelinePrefs();
const snap = prefs.snap;
const prefsRef = React.useRef(prefs);
@@ -1456,6 +1444,17 @@ export const Timeline = React.memo(function Timeline({
el.scrollLeft = Math.max(0, fromMs * pxPerMs);
}, [pxPerMs]);
+ /* A recalled span outside the view is brought into sight at the current zoom, without seeking. */
+ React.useEffect(() => {
+ const el = scrollRef.current;
+ if (!flashRange || !el || !(pxPerMs > 0)) return;
+ const from = flashRange.startMs * pxPerMs;
+ const to = flashRange.endMs * pxPerMs;
+ if (to < el.scrollLeft || from > el.scrollLeft + el.clientWidth) {
+ panViewTo(flashRange.startMs - el.clientWidth / pxPerMs * 0.1);
+ }
+ }, [flashRange, pxPerMs, panViewTo]);
+
/* Ctrl/⌘ + wheel (and pinch) zooms around the pointer. A native non-passive listener: React's onWheel is passive and
cannot stop the browser's page zoom. Horizontal swipes and Shift+wheel scroll here too: the track area hides its
horizontal scrollbar. */
@@ -1901,6 +1900,8 @@ export const Timeline = React.memo(function Timeline({
* that moment, a ⌘-drag that span, drawn as it is pulled. Without ⌘ it scrubs.
*/
const [referDraft, setReferDraft] = React.useState<FilmRange | null>(null);
+ const stopRefer = React.useRef<(() => void) | null>(null);
+ React.useEffect(() => () => { stopRefer.current?.(); }, []);
/* where the pointer is on the ruler (film ms) while ⌘ is held, shown as the moment a click would refer */
const [rulerHoverMs, setRulerHoverMs] = React.useState<number | null>(null);
/* the pointer's x over the ruler, so ⌘ pressed or let go there shows or hides that moment without a move */
@@ -1933,6 +1934,8 @@ export const Timeline = React.memo(function Timeline({
const startRefer = React.useCallback((e: React.PointerEvent) => {
if (e.button !== 0 || !playable || !onReferRuler) return;
e.preventDefault();
+ stopRefer.current?.();
+ document.body.classList.add('tl-pinning');
const startX = e.clientX;
const at = (clientX: number) => Math.max(0, Math.min(totalMs, msAtClientX(clientX)));
const fromMs = at(e.clientX);
@@ -1948,18 +1951,28 @@ export const Timeline = React.memo(function Timeline({
if (!raf) raf = requestAnimationFrame(flush);
edge.at(ev.clientX);
};
- const up = (ev: PointerEvent) => {
+ const stop = () => {
window.removeEventListener('pointermove', move);
window.removeEventListener('pointerup', up);
+ window.removeEventListener('pointercancel', stop);
+ window.removeEventListener('blur', stop);
edge.stop();
if (raf) cancelAnimationFrame(raf);
setReferDraft(null);
+ document.body.classList.remove('tl-pinning');
+ stopRefer.current = null;
+ };
+ const up = (ev: PointerEvent) => {
const range = orderedRange(fromMs, at(ev.clientX));
+ stop();
if (!dragged) onReferRuler({ atMs: fromMs });
else if (range) onReferRuler({ range });
};
+ stopRefer.current = stop;
window.addEventListener('pointermove', move, { passive: true });
window.addEventListener('pointerup', up);
+ window.addEventListener('pointercancel', stop);
+ window.addEventListener('blur', stop);
}, [msAtClientX, onReferRuler, playable, totalMs]);
/**
@@ -2008,39 +2021,6 @@ export const Timeline = React.memo(function Timeline({
return out;
}, [mode, tracks]);
- /* ── the preview axis: a line under the pointer, the picture there; the playhead stays ── */
- const axisRef = React.useRef<HTMLDivElement | null>(null);
- const axisAt = React.useRef<number | null>(null);
- const axisFrame = React.useRef(0);
- const hoverPreviewRef = React.useRef(onHoverPreview);
- hoverPreviewRef.current = onHoverPreview;
- /** The axis at a moment (null: gone, the picture back at the playhead). Written to the DOM, told once a frame. */
- const showAxis = React.useCallback((ms: number | null) => {
- const line = axisRef.current;
- if (line) {
- line.style.opacity = ms == null ? '0' : '1';
- if (ms != null) line.style.transform = `translateX(${Math.round(ms * laidPxRef.current - scrollLeftRef.current + PLAYHEAD_BLEED)}px)`;
- }
- if (axisAt.current === ms) return;
- axisAt.current = ms;
- if (axisFrame.current) return;
- axisFrame.current = requestAnimationFrame(() => {
- axisFrame.current = 0;
- hoverPreviewRef.current?.(axisAt.current);
- });
- }, []);
- React.useEffect(() => () => { if (axisFrame.current) cancelAnimationFrame(axisFrame.current); }, []);
- /* not while playing, nor with a button held (a drag, a scrub, a marquee): then the picture is theirs */
- const aimAxis = React.useCallback((e: React.PointerEvent) => {
- if (!prefsRef.current.previewAxis || !hoverPreviewRef.current || playing || e.buttons || inHandRef.current) {
- if (axisAt.current != null) showAxis(null);
- return;
- }
- showAxis(Math.max(0, Math.min(totalMs, msAtClientX(e.clientX))));
- }, [playing, totalMs, msAtClientX, showAxis]);
- /* turned off, or playing: the axis goes */
- React.useEffect(() => { if ((!prefs.previewAxis || playing) && axisAt.current != null) showAxis(null); }, [prefs.previewAxis, playing, showAxis]);
-
const bladeRef = React.useRef<HTMLDivElement | null>(null);
const contentRef = React.useRef<HTMLDivElement | null>(null);
const hideBlade = React.useCallback(() => {
@@ -3450,7 +3430,6 @@ export const Timeline = React.memo(function Timeline({
toggleMagnet: () => togglePref('magnet'),
toggleSnap: () => togglePref('snap'),
toggleLinkage: () => togglePref('linkage'),
- togglePreviewAxis: () => togglePref('previewAxis'),
split: () => {
const atMs = timeMsRef.current;
const found = splitTargets(tracks, selectedRef.current, atMs, targetLaneRef.current);
@@ -3798,13 +3777,6 @@ export const Timeline = React.memo(function Timeline({
});
return out;
})();
- /* first, always: the clips and the range, or the moment of the point */
- const barLead = barKind && onReferSelection ? {
- id: 'refer', label: t('selectionBar.addToChat'), icon: <MessageSquarePlus size={14} />, shortcut: keyHint('refer'),
- onSelect: () => onReferSelection(barKind === 'point'
- ? { blocks: [], range: null, atMs: timeMsRef.current }
- : { blocks: selectedBlocks, range: range ?? null, atMs: null }),
- } : null;
const clipCount = selectedBlocks.length;
const clipsWord = clipCount === 1 ? t('selectionBar.oneClip') : t('selectionBar.clips').replace('{n}', String(clipCount));
const barLabel = barKind === 'point' || !clipCount ? undefined
@@ -3946,7 +3918,7 @@ export const Timeline = React.memo(function Timeline({
) : null}
</div>
- {/* the switches (lib/timeline-prefs), in this order: the main-track magnet, snapping, linkage, the preview axis */}
+ {/* the switches (lib/timeline-prefs), in this order: the main-track magnet, snapping and linkage */}
{onEditOps ? <>
<span data-timeline-magnet={prefs.magnet ? '1' : '0'}>
<ToolButton onClick={() => togglePref('magnet')} active={prefs.magnet} label={t('timeline.magnet')}
@@ -3967,14 +3939,6 @@ export const Timeline = React.memo(function Timeline({
</ToolButton>
</span>
</> : null}
- {onHoverPreview ? (
- <span data-timeline-preview-axis={prefs.previewAxis ? '1' : '0'}>
- <ToolButton onClick={() => togglePref('previewAxis')} active={prefs.previewAxis} label={t('timeline.previewAxis')}
- hint={prefs.previewAxis ? t('timeline.previewAxisOn') : t('timeline.previewAxisOff')}>
- <TextCursor size={15} />
- </ToolButton>
- </span>
- ) : null}
<ToolButton
onClick={() => zoomBy(1 / ZOOM_STEP)}
@@ -4108,7 +4072,7 @@ export const Timeline = React.memo(function Timeline({
onBlur={() => setBarFocus((f) => (f === 'point' ? null : f))}
className="relative h-full touch-none select-none outline-none"
/* pointing at time for the chat (⌘ held): a crosshair, as on the picture, and the moment under it drawn */
- style={{ width: trackPx, cursor: onReferRuler ? (rulerHoverMs == null && !referDraft ? 'col-resize' : 'crosshair') : 'col-resize' }}
+ style={{ width: trackPx, cursor: rulerHoverMs != null || referDraft ? 'crosshair' : 'default' }}
>
{tickMarks}
{onReferRuler ? <RulerRefer hoverMs={rulerHoverMs} draft={referDraft} pxPerMs={pxPerMs} widthPx={trackPx} /> : null}
@@ -4118,7 +4082,7 @@ export const Timeline = React.memo(function Timeline({
{subRowShown && subtitleRow ? (
<SubtitleRow ref={subRowRef} spec={subtitleRow} pxPerMs={pxPerMs} scrollLeft={view.left} width={trackPx}
playheadMs={() => timeMsRef.current} snap={snap} snapTargets={() => snapTargetsFor(allBlocks, null, timeMsRef.current)}
- onError={setDropError} />
+ onScrub={startScrub} onError={setDropError} />
) : null}
{/* the markers' row: pins along it, scrolling with the tracks; a press between them moves the playhead (and
@@ -4162,8 +4126,8 @@ export const Timeline = React.memo(function Timeline({
/* capture phase: a press on the playhead line goes to the scrub before clips and marquee (grabPlayhead);
move / leave only manage the cursor */
onPointerDownCapture={grabPlayhead}
- onPointerMove={(e) => { hotPlayhead(e); aimBlade(e); aimAxis(e); }}
- onPointerLeave={() => { coldPlayhead(); hideBlade(); showAxis(null); }}
+ onPointerMove={(e) => { hotPlayhead(e); aimBlade(e); }}
+ onPointerLeave={() => { coldPlayhead(); hideBlade(); }}
/* no rubber-band: a ruler that bounces makes people think they dragged wrong */
className={`tl-scroll absolute inset-0 overflow-y-auto overflow-x-hidden overscroll-none bg-transparent${
mode === 'split' ? ' tl-blade' : ''
@@ -4262,11 +4226,6 @@ export const Timeline = React.memo(function Timeline({
className="pointer-events-none absolute inset-y-0 z-[35]"
style={{ left: headW - PLAYHEAD_BLEED, right: 0, top: TOOLBAR_H, bottom: H_SCROLL_H, overflow: 'hidden' }}
>
- {/* the preview axis under the pointer (showAxis moves it): a thin line, quieter than the playhead */}
- {onHoverPreview ? (
- <div ref={axisRef} data-preview-axis="" aria-hidden className="absolute inset-y-0 left-0 w-px"
- style={{ opacity: 0, background: 'var(--tl-faint)' }} />
- ) : null}
{/* moved with transform, not left: the most frequently moving thing here, and transform skips layout; a zoom
gesture scales its layer (the knob keeps its width) */}
<div data-zoom-layer="view" data-zoom-bleed={PLAYHEAD_BLEED} className="absolute inset-0">
@@ -4347,6 +4306,24 @@ export const Timeline = React.memo(function Timeline({
</div>
) : null}
+ {/* Recalling a range briefly lights only the ruler, without a persistent selection or toolbar. */}
+ {flashRange && hasLanes ? (
+ <div className="pointer-events-none absolute z-[25] overflow-hidden" style={{ left: headW, right: 0, top: TOOLBAR_H, height: RULER_H }}>
+ <div data-zoom-layer="view" className="absolute inset-0">
+ <div
+ data-timeline-range-flash=""
+ className="absolute inset-y-0 left-0 border-x"
+ style={{
+ transform: `translate3d(${flashRange.startMs * pxPerMs - scrollLeft}px,0,0)`,
+ width: Math.max(1, (flashRange.endMs - flashRange.startMs) * pxPerMs),
+ borderColor: 'color-mix(in srgb, var(--tl-accent) 55%, transparent)',
+ background: 'color-mix(in srgb, var(--tl-accent) 10%, transparent)',
+ }}
+ />
+ </div>
+ </div>
+ ) : null}
+
{/* the range marked on the ruler: a band from the ruler's top down through the tracks. It takes no pointer (the
ruler scrubs and the clips under it are pressed as ever); its label does, and is dragged into the app's chat */}
{shownRange && hasLanes ? (() => {
@@ -4400,8 +4377,7 @@ export const Timeline = React.memo(function Timeline({
<SelectionToolbar
selection={barKey}
measure={measureBar}
- hidden={playing || scrubbing || zooming || Boolean(marquee || rangeDraft || drag.preview || laneOrder || assetHint)}
- lead={barLead}
+ hidden={playing || scrubbing || zooming || Boolean(marquee || rangeDraft || referDraft || drag.preview || laneOrder || assetHint)}
{...(barLabel ? { label: barLabel } : {})}
tools={barTools}
ariaLabel={t('selectionBar.toolbar')}
@@ -4896,7 +4872,7 @@ function RulerRefer({ hoverMs, draft, pxPerMs, widthPx }: { hoverMs: number | nu
const width = Math.max(1, (draft.endMs - draft.startMs) * pxPerMs);
return (
<div aria-hidden className="pointer-events-none absolute inset-0">
- <div className="absolute inset-y-0" style={{ left, width, background: 'color-mix(in srgb, var(--tl-accent) 22%, transparent)', boxShadow: 'inset 1px 0 var(--tl-accent), inset -1px 0 var(--tl-accent)' }} />
+ <div data-timeline-refer-range="" className="absolute inset-y-0" style={{ left, width, background: 'color-mix(in srgb, var(--tl-accent) 22%, transparent)', boxShadow: 'inset 1px 0 var(--tl-accent), inset -1px 0 var(--tl-accent)' }} />
{tag(left + width, `${chatClock(draft.startMs)}–${chatClock(draft.endMs)}`)}
</div>
);
diff --git a/packages/openfilm/studio/ui/src/components/settings/AgentsSection.tsx b/packages/openfilm/studio/ui/src/components/settings/AgentsSection.tsx
index 54155b7..620a63e 100644
--- a/packages/openfilm/studio/ui/src/components/settings/AgentsSection.tsx
+++ b/packages/openfilm/studio/ui/src/components/settings/AgentsSection.tsx
@@ -228,6 +228,11 @@ export function AgentsSection() {
if (agent.status === 'key') return <SettingsButton onClick={() => setKeyOpen(true)}>{t('settings.agents.setUpKey')}</SettingsButton>;
if (agent.status === 'unavailable') return null;
if (agent.status === 'checking') return <Loader2 size={16} className="animate-spin text-[var(--text-muted)]" aria-hidden />;
+ if (agent.status === 'waiting') return (
+ <SettingsButton variant="quiet" disabled={working} onClick={() => act(agent.id, () => host.cancelSignIn ? host.cancelSignIn(agent.id) : host.disconnect(agent.id))}>
+ {t('settings.agents.cancel')}
+ </SettingsButton>
+ );
/* disconnected: the program it runs can be pointed at before connecting again (a particular version, another
install); a connected one keeps the program it found. The own key has none */
const canLocate = agent.status === 'off' && host.locate && agent.id !== 'byok';
@@ -238,7 +243,7 @@ export function AgentsSection() {
{t('settings.agents.locate')}
</SettingsButton>
) : null}
- <SettingsButton disabled={working || agent.status === 'waiting'} onClick={() => act(agent.id, () => host.connect(agent.id))}>
+ <SettingsButton disabled={working} onClick={() => act(agent.id, () => host.connect(agent.id))}>
{working ? <Loader2 size={16} className="animate-spin" aria-hidden /> : null}
{agent.status === 'sign-in' ? t('settings.agents.signIn') : t('settings.agents.connect')}
</SettingsButton>
@@ -340,7 +345,7 @@ export function AgentsSection() {
{agent.status === 'waiting' ? (
<p className="text-[14.5px] leading-relaxed text-[var(--text-muted)]">
{t(WAITING_HINTS[agent.id] ?? 'settings.agents.waitingHint')}{' '}
- <button type="button" onClick={() => act(agent.id, () => host.connect(agent.id))} className="underline underline-offset-2 hover:text-[var(--text)]">{t('settings.agents.startAgain')}</button>
+ <button type="button" disabled={busy === agent.id} onClick={() => act(agent.id, () => host.connect(agent.id))} className="underline underline-offset-2 hover:text-[var(--text)]">{t('settings.agents.startAgain')}</button>
</p>
) : null}
{open ? <OwnModels agent={agent} onDone={() => setKeyOpen(false)} /> : null}
diff --git a/packages/openfilm/studio/ui/src/globals.css b/packages/openfilm/studio/ui/src/globals.css
index 8bf778a..d62d0ed 100644
--- a/packages/openfilm/studio/ui/src/globals.css
+++ b/packages/openfilm/studio/ui/src/globals.css
@@ -407,6 +407,9 @@ body.tl-scrubbing * {
cursor: col-resize !important;
}
+/* Keep the reference-selection cursor while dragging beyond the ruler. */
+body.tl-pinning, body.tl-pinning * { cursor: crosshair !important; }
+
/* The range bar: 10px to hit, a 4px thumb that thickens to 8px under the pointer, colored from the text. */
.tl-range-thumb {
top: 50% !important;
diff --git a/packages/openfilm/studio/ui/src/i18n/en.ts b/packages/openfilm/studio/ui/src/i18n/en.ts
index 16d3ac0..ff97c74 100644
--- a/packages/openfilm/studio/ui/src/i18n/en.ts
+++ b/packages/openfilm/studio/ui/src/i18n/en.ts
@@ -203,6 +203,8 @@ export const en = {
creating: 'Creating project',
opening: 'Opening project',
missing: 'Folder not found',
+ missingFilm: 'Project file not found',
+ missingFilmOpen: 'This folder no longer contains film.html. Restore the file or locate the project to open it again.',
missingOpen: 'This project’s folder is not there any more: it was moved, renamed or deleted. You can remove it from the list.',
agentRunning: 'Agent running',
agentRunningRename: 'An agent is running in this project. Stop it first, then rename the project.',
@@ -211,8 +213,8 @@ export const en = {
agentRunningDeleteMany: 'An agent is running in {n} of these projects. Stop it first, then delete them.',
removeFromList: 'Remove from list',
removeTitle: 'Remove from the list?',
- removeDesc: 'Its folder is already gone, and everything a project keeps (versions, chats) was in it, so nothing is left to delete. This takes it off the list.',
- removeAlso: 'Projects whose folder is gone are only taken off the list.',
+ removeDesc: 'This removes the unavailable project from the list. Any files remaining in its folder are kept.',
+ removeAlso: 'Unavailable projects are only taken off the list; any remaining files are kept.',
getFromGitHub: 'Get from GitHub…',
importFrom: 'Import from',
locate: 'Locate…',
@@ -1337,9 +1339,6 @@ export const en = {
linkage: 'Linkage',
linkageOn: 'On: titles, overlays and sound move with the main-track clip under them, and go with it',
linkageOff: 'Off: editing the main track moves only the main track',
- previewAxis: 'Preview axis',
- previewAxisOn: 'On: the picture follows the pointer over the timeline',
- previewAxisOff: 'Off: the picture stays at the playhead',
rippleShort: "Clips on another track were in the way: {s} s left open so everything stays in sync.",
menuCloseGap: 'Close gap',
menuCloseGaps: 'Close all gaps on this track',
@@ -1799,7 +1798,6 @@ export const en = {
"toggle-magnet": "Main track magnet on / off",
"toggle-snap": "Snapping on / off",
"toggle-linkage": "Linkage on / off",
- "toggle-preview-axis": "Preview axis on / off",
"zoom-in": "Zoom in",
"zoom-out": "Zoom out",
"zoom-reset": "Reset zoom",
diff --git a/packages/openfilm/studio/ui/src/i18n/es.ts b/packages/openfilm/studio/ui/src/i18n/es.ts
index a1936d9..dfe545d 100644
--- a/packages/openfilm/studio/ui/src/i18n/es.ts
+++ b/packages/openfilm/studio/ui/src/i18n/es.ts
@@ -202,6 +202,8 @@ export const es: Words = {
creating: 'Creando proyecto',
opening: 'Abriendo proyecto',
missing: 'Carpeta no encontrada',
+ missingFilm: 'Archivo del proyecto no encontrado',
+ missingFilmOpen: 'Esta carpeta ya no contiene film.html. Restaura el archivo o localiza el proyecto para volver a abrirlo.',
missingOpen: 'La carpeta de este proyecto ya no está: se movió, se renombró o se eliminó. Puedes quitarlo de la lista.',
agentRunning: 'Agente en marcha',
agentRunningRename: 'Hay un agente trabajando en este proyecto. Detenlo antes de cambiarle el nombre al proyecto.',
@@ -210,8 +212,8 @@ export const es: Words = {
agentRunningDeleteMany: 'Un agente está trabajando en {n} de estos proyectos. Detenlo primero y luego elimínalos.',
removeFromList: 'Quitar de la lista',
removeTitle: '¿Quitar de la lista?',
- removeDesc: 'Su carpeta ya no existe, y todo lo que guarda un proyecto (versiones, chats) estaba en ella, así que no queda nada que borrar. Esto lo quita de la lista.',
- removeAlso: 'Los proyectos cuya carpeta ya no existe solo se quitan de la lista.',
+ removeDesc: 'Esto quita de la lista el proyecto no disponible. Los archivos que queden en su carpeta se conservan.',
+ removeAlso: 'Los proyectos no disponibles solo se quitan de la lista; los archivos restantes se conservan.',
getFromGitHub: 'Obtener de GitHub…',
importFrom: 'Importar desde',
locate: 'Localizar…',
@@ -1336,9 +1338,6 @@ export const es: Words = {
linkage: 'Vinculación',
linkageOn: 'Activada: títulos, superposiciones y sonido se mueven con el clip de la pista principal que tienen debajo, y se van con él',
linkageOff: 'Desactivada: editar la pista principal solo mueve la pista principal',
- previewAxis: 'Eje de vista previa',
- previewAxisOn: 'Activado: la imagen sigue al puntero sobre la línea de tiempo',
- previewAxisOff: 'Desactivado: la imagen se queda en el cabezal',
rippleShort: 'Había clips en otra pista: quedan {s} s abiertos para que todo siga sincronizado.',
menuCloseGap: 'Cerrar hueco',
menuCloseGaps: 'Cerrar todos los huecos de esta pista',
@@ -1798,7 +1797,6 @@ export const es: Words = {
"toggle-magnet": "Activar / desactivar el imán de la pista principal",
"toggle-snap": "Activar / desactivar el ajuste",
"toggle-linkage": "Activar / desactivar la vinculación",
- "toggle-preview-axis": "Activar / desactivar el eje de vista previa",
"zoom-in": "Acercar",
"zoom-out": "Alejar",
"zoom-reset": "Restablecer zoom",
diff --git a/packages/openfilm/studio/ui/src/i18n/ja.ts b/packages/openfilm/studio/ui/src/i18n/ja.ts
index 3408a42..fa1be1b 100644
--- a/packages/openfilm/studio/ui/src/i18n/ja.ts
+++ b/packages/openfilm/studio/ui/src/i18n/ja.ts
@@ -202,6 +202,8 @@ export const ja: Words = {
creating: 'プロジェクトを作成中',
opening: 'プロジェクトを開いています',
missing: 'フォルダーが見つかりません',
+ missingFilm: 'プロジェクトファイルが見つかりません',
+ missingFilmOpen: 'このフォルダーに film.html がありません。ファイルを復元するか、プロジェクトの新しい場所を指定してから開いてください。',
missingOpen: 'このプロジェクトのフォルダーが見つかりません。移動、名前の変更、または削除されたようです。リストから削除できます。',
agentRunning: 'エージェント実行中',
agentRunningRename: 'このプロジェクトでエージェントが実行中です。先に停止してから、プロジェクト名を変更してください。',
@@ -210,8 +212,8 @@ export const ja: Words = {
agentRunningDeleteMany: '{n} 件のプロジェクトでエージェントが実行中です。先に停止してから削除してください。',
removeFromList: 'リストから削除',
removeTitle: 'リストから削除しますか?',
- removeDesc: 'フォルダーはすでになく、プロジェクトが保存するもの(バージョン履歴やチャット)はすべてその中にあったため、削除すべきものは残っていません。リストから外します。',
- removeAlso: 'フォルダーがなくなったプロジェクトは、リストから外すだけです。',
+ removeDesc: '見つからないプロジェクトをリストから外します。フォルダーに残っているファイルは保持されます。',
+ removeAlso: '見つからないプロジェクトはリストから外すだけで、残っているファイルは保持されます。',
getFromGitHub: 'GitHub から取得…',
importFrom: 'インポート元',
locate: '場所を指定…',
@@ -1336,9 +1338,6 @@ export const ja: Words = {
linkage: '連動',
linkageOn: 'オン:テキスト、オーバーレイ、音声が下のメイントラックのクリップと一緒に動き、一緒に削除されます',
linkageOff: 'オフ:メイントラックの編集はメイントラックだけを動かします',
- previewAxis: 'プレビュー軸',
- previewAxisOn: 'オン:タイムライン上のポインターに合わせて映像が動きます',
- previewAxisOff: 'オフ:映像は再生ヘッドの位置のままです',
rippleShort: '他のトラックのクリップが邪魔をしています:同期を保つため {s} 秒の隙間が残りました。',
menuCloseGap: '隙間を詰める',
menuCloseGaps: 'このトラックの隙間をすべて詰める',
@@ -1798,7 +1797,6 @@ export const ja: Words = {
"toggle-magnet": "メイントラックのマグネットのオン / オフ",
"toggle-snap": "スナップのオン / オフ",
"toggle-linkage": "連動のオン / オフ",
- "toggle-preview-axis": "プレビュー軸のオン / オフ",
"zoom-in": "ズームイン",
"zoom-out": "ズームアウト",
"zoom-reset": "ズームをリセット",
diff --git a/packages/openfilm/studio/ui/src/i18n/ko.ts b/packages/openfilm/studio/ui/src/i18n/ko.ts
index 5f29024..fbf62d0 100644
--- a/packages/openfilm/studio/ui/src/i18n/ko.ts
+++ b/packages/openfilm/studio/ui/src/i18n/ko.ts
@@ -199,6 +199,8 @@ export const ko: Words = {
creating: '프로젝트 만드는 중',
opening: '프로젝트 여는 중',
missing: '폴더를 찾을 수 없음',
+ missingFilm: '프로젝트 파일을 찾을 수 없음',
+ missingFilmOpen: '이 폴더에 film.html이 없습니다. 파일을 복원하거나 프로젝트의 새 위치를 지정한 후 다시 여세요.',
missingOpen: '이 프로젝트의 폴더가 더 이상 없습니다. 이동되었거나, 이름이 바뀌었거나, 삭제되었습니다. 목록에서 제거할 수 있습니다.',
agentRunning: '에이전트 실행 중',
agentRunningRename: '이 프로젝트에서 에이전트가 실행 중입니다. 먼저 중지한 다음 프로젝트 이름을 변경하세요.',
@@ -207,8 +209,8 @@ export const ko: Words = {
agentRunningDeleteMany: '{n}개 프로젝트에서 에이전트가 실행 중입니다. 먼저 중지한 다음 삭제하세요.',
removeFromList: '목록에서 제거',
removeTitle: '목록에서 제거할까요?',
- removeDesc: '폴더가 이미 없고, 프로젝트가 보관하는 모든 것(버전 기록, 대화)은 그 안에 있었으므로 지울 파일이 남아 있지 않습니다. 목록에서 제거합니다.',
- removeAlso: '폴더가 없어진 프로젝트는 목록에서만 제거됩니다.',
+ removeDesc: '찾을 수 없는 프로젝트를 목록에서 제거합니다. 폴더에 남아 있는 파일은 유지됩니다.',
+ removeAlso: '찾을 수 없는 프로젝트는 목록에서만 제거되며, 남아 있는 파일은 유지됩니다.',
getFromGitHub: 'GitHub에서 가져오기…',
importFrom: '가져오기',
locate: '위치 찾기…',
@@ -1333,9 +1335,6 @@ export const ko: Words = {
linkage: '연동',
linkageOn: '켬: 자막, 오버레이, 소리가 아래 메인 트랙 클립과 함께 움직이고 함께 삭제됩니다',
linkageOff: '끔: 메인 트랙을 편집하면 메인 트랙만 움직입니다',
- previewAxis: '미리보기 축',
- previewAxisOn: '켬: 타임라인 위 포인터를 따라 화면이 움직입니다',
- previewAxisOff: '끔: 화면이 재생 헤드 위치에 머뭅니다',
rippleShort: '다른 트랙의 클립이 막고 있습니다: 동기를 유지하려고 {s}초 간격이 남았습니다.',
menuCloseGap: '간격 메우기',
menuCloseGaps: '이 트랙의 간격 모두 메우기',
@@ -1794,7 +1793,6 @@ export const ko: Words = {
"toggle-magnet": "메인 트랙 자석 켜기 / 끄기",
"toggle-snap": "스냅 켜기 / 끄기",
"toggle-linkage": "연동 켜기 / 끄기",
- "toggle-preview-axis": "미리보기 축 켜기 / 끄기",
"zoom-in": "확대",
"zoom-out": "축소",
"zoom-reset": "확대/축소 초기화",
diff --git a/packages/openfilm/studio/ui/src/i18n/zh-CN.ts b/packages/openfilm/studio/ui/src/i18n/zh-CN.ts
index 459d0f0..77950a3 100644
--- a/packages/openfilm/studio/ui/src/i18n/zh-CN.ts
+++ b/packages/openfilm/studio/ui/src/i18n/zh-CN.ts
@@ -203,6 +203,8 @@ export const zhCN: Words = {
creating: '正在创建项目',
opening: '正在打开项目',
missing: '找不到文件夹',
+ missingFilm: '找不到项目文件',
+ missingFilmOpen: '此文件夹中的 film.html 已被移除。请恢复该文件,或定位项目的新位置后再打开。',
missingOpen: '此项目的文件夹已不在原处:它被移动、重命名或删除了。你可以将它从列表中移除。',
agentRunning: 'Agent 运行中',
agentRunningRename: 'Agent 正在这个项目里运行,请先停止它,再重命名项目。',
@@ -211,8 +213,8 @@ export const zhCN: Words = {
agentRunningDeleteMany: '其中 {n} 个项目里有 Agent 正在运行,请先停止,再删除。',
removeFromList: '从列表中移除',
removeTitle: '从列表中移除?',
- removeDesc: '它的文件夹已经不在了,项目的一切(版本历史、对话)都存在那个文件夹里,所以没有残留文件需要删除。这里只是把它从列表中移除。',
- removeAlso: '文件夹已不存在的项目只会从列表中移除。',
+ removeDesc: '这里只会把无法找到的项目从列表中移除,文件夹中的剩余文件会保留。',
+ removeAlso: '无法找到的项目只会从列表中移除,剩余文件会保留。',
getFromGitHub: '从 GitHub 获取…',
importFrom: '导入自',
locate: '定位…',
@@ -1337,9 +1339,6 @@ export const zhCN: Words = {
linkage: '联动',
linkageOn: '开:字幕、画中画、声音跟着下面的主轨片段一起移动、删除',
linkageOff: '关:编辑主轨时只动主轨',
- previewAxis: '预览轴',
- previewAxisOn: '开:鼠标在时间线上移动,画面跟着走',
- previewAxisOff: '关:画面停在播放头处',
rippleShort: '其他轨道上有片段挡着:为保持同步,留下了 {s} 秒的空隙。',
menuCloseGap: '合拢间隙',
menuCloseGaps: '批量闭合空隙',
@@ -1799,7 +1798,6 @@ export const zhCN: Words = {
"toggle-magnet": "主轨磁吸开关",
"toggle-snap": "吸附开关",
"toggle-linkage": "联动开关",
- "toggle-preview-axis": "预览轴开关",
"zoom-in": "时间轴放大",
"zoom-out": "时间轴缩小",
"zoom-reset": "重置缩放",
diff --git a/packages/openfilm/studio/ui/src/lib/host.ts b/packages/openfilm/studio/ui/src/lib/host.ts
index 38b9b2f..3d22c39 100644
--- a/packages/openfilm/studio/ui/src/lib/host.ts
+++ b/packages/openfilm/studio/ui/src/lib/host.ts
@@ -91,6 +91,8 @@ export interface StudioHost {
agents?: {
list: () => Promise<HostAgent[]>;
connect: (id: HostAgentId) => Promise<{ ok: boolean; error?: string }>;
+ /** Stop waiting for terminal sign-in without disconnecting the agent or changing its own sign-in. */
+ cancelSignIn?: (id: HostAgentId) => Promise<unknown>;
disconnect: (id: HostAgentId) => Promise<unknown>;
/** Codex: what is left of its plan, as it says for the account signed in (null: it can't say; other agents, null) */
usage?: (id: HostAgentId, fresh?: boolean) => Promise<HostAgentUsage | null>;
@@ -353,7 +355,7 @@ export interface StudioSelection {
}
/**
- * What an app can ask Studio to show: a clip selected (by its film.html id, or its place), a moment, a range marked,
+ * What an app can ask Studio to show: a clip selected (by its film.html id, or its place), a moment, a range briefly lit,
* a box on the picture shown at its moment, a track, a file of the media pane, a subtitle line (its span marked, the
* subtitle panel open on it).
*
diff --git a/packages/openfilm/studio/ui/src/lib/keymap.test.ts b/packages/openfilm/studio/ui/src/lib/keymap.test.ts
index 6a111b7..1e5d3af 100644
--- a/packages/openfilm/studio/ui/src/lib/keymap.test.ts
+++ b/packages/openfilm/studio/ui/src/lib/keymap.test.ts
@@ -81,7 +81,8 @@ test('OpenFilm\'s keys are the keys Studio had', () => {
assert.equal(mac('`'), 'toggle-linkage');
assert.equal(mac('~', { shiftKey: true }), 'toggle-linkage');
assert.equal(actionOf({ ...press('`'), code: 'Backquote' }, OPENFILM_MAC, true), 'toggle-linkage');
- assert.equal(mac('s'), 'toggle-preview-axis');
+ assert.equal(mac('s'), null);
+ assert.equal(win('s'), null);
assert.equal(mac('S', { shiftKey: true, ctrlKey: true }), 'detach-audio');
assert.equal(win('S', { shiftKey: true, ctrlKey: true }), 'detach-audio');
assert.equal(mac('q'), 'ripple-start');
@@ -178,7 +179,6 @@ test('the built-in schemes: each app\'s keys where Studio has the action, OpenFi
assert.deepEqual(premiere['split-all'], ['mod+shift+k']);
assert.deepEqual(premiere['split-mode'], ['c'], 'the Razor tool');
assert.deepEqual(premiere['toggle-snap'], ['s']);
- assert.deepEqual(premiere['toggle-preview-axis'], [], 'S snaps there: the preview axis has no key');
assert.deepEqual(premiere['toggle-magnet'], ['p', 'shift+n'], 'what the app has no key for keeps OpenFilm\'s');
assert.deepEqual(premiere.refer, ['mod+l']);
assert.deepEqual(premiere['nudge-back'], ['mod+ArrowLeft'], 'macOS');
diff --git a/packages/openfilm/studio/ui/src/lib/keymap.ts b/packages/openfilm/studio/ui/src/lib/keymap.ts
index d1be19f..96f5e18 100644
--- a/packages/openfilm/studio/ui/src/lib/keymap.ts
+++ b/packages/openfilm/studio/ui/src/lib/keymap.ts
@@ -32,7 +32,6 @@ export const ACTIONS = [
{ id: 'toggle-magnet', tab: 'timeline', keys: ['p', 'shift+n'] },
{ id: 'toggle-snap', tab: 'timeline', keys: ['n'] },
{ id: 'toggle-linkage', tab: 'timeline', keys: ['`', 'shift+`'] },
- { id: 'toggle-preview-axis', tab: 'timeline', keys: ['s'] },
{ id: 'zoom-in', tab: 'timeline', keys: ['mod++', 'mod+='] },
{ id: 'zoom-out', tab: 'timeline', keys: ['mod+-'] },
{ id: 'zoom-reset', tab: 'timeline', keys: ['mod+0'] },
@@ -220,9 +219,8 @@ const FINAL_CUT: Partial<Record<ActionId, Binding>> = {
/* Nudge Left / Right */
'nudge-back': [','],
'nudge-forward': ['.'],
- /* Snapping, Skimming */
+ /* Snapping */
'toggle-snap': ['n'],
- 'toggle-preview-axis': ['s'],
'zoom-in': ['mod++', 'mod+='],
'zoom-out': ['mod+-'],
'zoom-fit': ['shift+z'],
diff --git a/packages/openfilm/studio/ui/src/lib/timeline-prefs.test.ts b/packages/openfilm/studio/ui/src/lib/timeline-prefs.test.ts
index 35c0c51..24fd3a9 100644
--- a/packages/openfilm/studio/ui/src/lib/timeline-prefs.test.ts
+++ b/packages/openfilm/studio/ui/src/lib/timeline-prefs.test.ts
@@ -2,6 +2,6 @@ import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readTimelinePrefs } from './timeline-prefs.ts';
-test('the switches start on, but the preview axis', () => {
- assert.deepEqual(readTimelinePrefs(), { snap: true, magnet: true, linkage: true, previewAxis: false });
+test('the editing switches start on', () => {
+ assert.deepEqual(readTimelinePrefs(), { snap: true, magnet: true, linkage: true });
});
diff --git a/packages/openfilm/studio/ui/src/lib/timeline-prefs.ts b/packages/openfilm/studio/ui/src/lib/timeline-prefs.ts
index 548c814..d55f7a7 100644
--- a/packages/openfilm/studio/ui/src/lib/timeline-prefs.ts
+++ b/packages/openfilm/studio/ui/src/lib/timeline-prefs.ts
@@ -1,13 +1,10 @@
/**
- * The timeline's switches, kept on this machine across projects, in the toolbar's order, on by default but the preview
- * axis:
+ * The timeline's switches, kept on this machine across projects, in the toolbar's order, on by default:
* · `magnet` (主轨磁吸): the main track (the lowest picture track) stays closed up — a clip put on it goes in between,
* one deleted or taken off it closes up after it, a trim or a new speed there moves what follows. Off, the main
* track is like the others (lib/timeline-edit);
* · `snap` (自动吸附): drags line up with edges and the playhead; off means "it lands exactly where I let go";
- * · `linkage` (联动): titles, overlays and sounds riding on a main-track clip move with it and go with it;
- * · `previewAxis` (预览轴): the picture follows the pointer over the timeline, the playhead staying where it is. Off
- * by default: the picture stays at the playhead until it is turned on.
+ * · `linkage` (联动): titles, overlays and sounds riding on a main-track clip move with it and go with it.
*
* Clips sharing a `data-link` (a video and its detached sound) are always selected and edited together; ⌥-click picks
* one alone. The inspector reads the switches too (a slower speed pushes the next clip only with the magnet on), so a
@@ -17,17 +14,16 @@ import { useSyncExternalStore } from 'react';
import type { Switches } from './timeline-edit.ts';
-export type TimelinePrefs = { snap: boolean; magnet: boolean; linkage: boolean; previewAxis: boolean };
+export type TimelinePrefs = { snap: boolean; magnet: boolean; linkage: boolean };
type Pref = keyof TimelinePrefs;
-const DEFAULTS: TimelinePrefs = { snap: true, magnet: true, linkage: true, previewAxis: false };
+const DEFAULTS: TimelinePrefs = { snap: true, magnet: true, linkage: true };
const KEY: Record<Pref, string> = {
snap: 'openfilm.timeline.snap',
/* new keys: the main track came back on 10-19 with its magnet and linkage, so choices made for the switches before
do not carry over */
magnet: 'openfilm.timeline.mainTrackMagnet',
linkage: 'openfilm.timeline.mainTrackLinkage',
- previewAxis: 'openfilm.timeline.previewAxis',
};
/** Without localStorage (private window), the choices last this session. */
@@ -44,7 +40,7 @@ function read(pref: Pref): boolean {
}
export function readTimelinePrefs(): TimelinePrefs {
- current ??= { snap: read('snap'), magnet: read('magnet'), linkage: read('linkage'), previewAxis: read('previewAxis') };
+ current ??= { snap: read('snap'), magnet: read('magnet'), linkage: read('linkage') };
return current;
}