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: own key with several models, ffmpeg and browser in the installer; Studio's own subtitle menus (#5)

riverisbuildinge4679d2d8225
diff --git a/.changeset/byok-models.md b/.changeset/byok-models.md
new file mode 100644
index 0000000..18e253f
--- /dev/null
+++ b/.changeset/byok-models.md
@@ -0,0 +1,6 @@
+---
+"@openfilm/desktop": patch
+"openfilm": patch
+---
+
+Desktop: your own key can name several models (Settings → Agents, separated by commas), each checked for reading pictures; the chat's menu switches between them. The menu no longer stays on "Loading" for an agent with nothing to choose.
diff --git a/.changeset/desktop-bundled-runtime.md b/.changeset/desktop-bundled-runtime.md
new file mode 100644
index 0000000..76b3dc7
--- /dev/null
+++ b/.changeset/desktop-bundled-runtime.md
@@ -0,0 +1,5 @@
+---
+"@openfilm/desktop": patch
+---
+
+Desktop: the installer comes with ffmpeg and the headless browser Studio draws pages in, so the first start downloads nothing (on a slow or blocked connection it used to fail there). A build without them downloads ffmpeg as before, now stopped and tried again when the download stalls.
diff --git a/.changeset/studio-menu-select.md b/.changeset/studio-menu-select.md
new file mode 100644
index 0000000..04a93f6
--- /dev/null
+++ b/.changeset/studio-menu-select.md
@@ -0,0 +1,5 @@
+---
+"openfilm": patch
+---
+
+Studio: the subtitle panel's language and typeface menus are Studio's own, in its colors, grouped and with the chosen one checked, in place of the browser's list, which was light in a dark Studio and read as if every choice were disabled.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 0b4eab6..0d1eacd 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -72,10 +72,11 @@ node --test --test-name-pattern="split" studio/server/film.test.mjs
### Trying a change with a coding agent
While `pnpm dev` runs, `packages/openfilm/.dev/bin/openfilm` (`openfilm.cmd` on Windows) is your checkout's command
-on that Studio: `pnpm dev` prints its path. Ask Claude Code, Codex or any coding agent for a film, telling it to run
-that command and follow the manual it prints (the manual names the same command, so the agent keeps using it). Your
-films appear in the Studio `pnpm dev` opened, and an installed OpenFilm, its Studio on port 4747 and `~/.openfilm`
-are left alone. (`npx -y openfilm@latest`, which the skill uses, fetches the release instead.)
+on that Studio. Open Codex, Claude Code or any coding agent in `packages/openfilm/.dev/projects` (that Studio's library)
+and ask for a film: the AGENTS.md and CLAUDE.md `pnpm dev` writes there tell it to run that command instead of the
+skill's `npx -y openfilm@latest` (the release), and the manual names the same command, so it keeps using it. Elsewhere,
+tell your agent to run the command. Your films appear in the Studio `pnpm dev` opened, and an installed OpenFilm, its
+Studio on port 4747 and `~/.openfilm` are left alone.
To make your checkout the `openfilm` your agents use everywhere, `npm link` in `packages/openfilm` (`npm unlink -g
openfilm` undoes it). That one shares `~/.openfilm` and port 4747 with an installed OpenFilm; of two Studios, the
diff --git a/README.md b/README.md
index 6be2854..7467ef3 100644
--- a/README.md
+++ b/README.md
@@ -44,7 +44,8 @@ It opens the film in Studio and you watch it take shape. If your agent has no sk
`npx -y openfilm@latest` and follow the manual it prints."
Or download the desktop app for macOS or Windows from [openfilm.dev](https://openfilm.dev) or
-[Releases](https://github.com/openfilm/openfilm/releases): Studio with a chat beside it for the agents you have.
+[Releases](https://github.com/openfilm/openfilm/releases): Studio with a chat beside it for the agents you have. It
+comes with ffmpeg and the headless browser, so there is nothing else to install.
Making, editing and rendering films needs no account. For generated voice, music, images and video, connect the
services you use (ElevenLabs, OpenAI, Google, fal and others) with your own keys in Studio's Settings → Providers.
@@ -142,7 +143,7 @@ pnpm dev # Studio from this checkout, with a sample film, apart from
pnpm test
```
-`pnpm dev` also prints a command your coding agent can run to make films with your checkout, in that Studio.
+Open your coding agent in `packages/openfilm/.dev/projects` and it makes films with your checkout, in that Studio.
`pnpm dev:desktop` runs the desktop app from source, and `pnpm typecheck`, `pnpm build` and `pnpm audit:public` do
what they say.
diff --git a/README.zh-CN.md b/README.zh-CN.md
index ff9d54e..11d2385 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -43,7 +43,8 @@ npx skills add openfilm/openfilm
`npx -y openfilm@latest`,按它打印的手册来做。”
也可以从 [openfilm.dev](https://openfilm.dev) 或 [Releases](https://github.com/openfilm/openfilm/releases)
-下载 macOS 或 Windows 桌面版:就是 Studio,旁边多了一个对话窗口,接上你已有的智能体。
+下载 macOS 或 Windows 桌面版:就是 Studio,旁边多了一个对话窗口,接上你已有的智能体。它自带 ffmpeg 和无界面浏览器,
+不用另外安装。
制作、剪辑和渲染片子都不需要账号。需要生成配音、音乐、图片和视频时,在 Studio 的设置 → 服务商里,用你自己的 key
连接你在用的服务(ElevenLabs、OpenAI、Google、fal 等)。
@@ -137,7 +138,7 @@ pnpm dev # 用这份源码运行 Studio,带一部示例片,和你
pnpm test
```
-`pnpm dev` 还会打印一条命令,你的编程智能体运行它,就能用这份源码在这个 Studio 里做片子。
+在 `packages/openfilm/.dev/projects` 里打开你的编程智能体,它就会用这份源码在这个 Studio 里做片子。
`pnpm dev:desktop` 从源码运行桌面版;`pnpm typecheck`、`pnpm build` 和 `pnpm audit:public` 分别是类型检查、构建和
公开内容审计。各个包的详细说明见 [CONTRIBUTING.md](CONTRIBUTING.md)(英文)。
diff --git a/apps/desktop/chat/src/App.tsx b/apps/desktop/chat/src/App.tsx
index c574297..246e68b 100644
--- a/apps/desktop/chat/src/App.tsx
+++ b/apps/desktop/chat/src/App.tsx
@@ -47,7 +47,7 @@ import { readBalance, type TurnBalance } from '@/lib/balance';
import { BalanceNotice } from '@/components/BalanceNotice';
import { readStudioFilm } from '@/lib/studio-film';
import { studioRefsFromTransfer, transferHasStudioRefs } from '@/lib/studio-transfer';
-import { agentModelSummary, currentAgent, effectivePrefs, fixedModel, offeredOption, useLocalAgents } from '@/state/local-agent-store';
+import { agentModelSummary, agentOptions, currentAgent, effectivePrefs, offeredOption, useLocalAgents } from '@/state/local-agent-store';
import { useLiveActivityFromStore } from '@/lib/live-activity';
import { loadLastSession, loadSessions, newSession, saveLastSession, saveSessions } from '@/lib/local-sessions';
import type { ProjectSessionItem } from '@/lib/project-sessions';
@@ -412,13 +412,13 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projec
function startTurn(id: string, instruction: string, prepared: Promise<{ text: string; images: PromptImage[] }>, promptDisplay: Turn['promptDisplay'] | null, attachments: Turn['attachments'] = []): void {
const turn = createLocalAgentTurn(id, agent, ordered.length);
const agentStore = useLocalAgents.getState();
- const prefs = effectivePrefs(agentStore.prefs, agent, agentStore.roster, agentStore.options[agent]);
- const summary = agentModelSummary(agentStore.options[agent], prefs);
- const fixed = fixedModel(agent, agentStore.roster);
+ const options = agentOptions(agentStore, agent);
+ const prefs = effectivePrefs(agentStore.prefs, agent, agentStore.roster, options);
+ const summary = agentModelSummary(options, prefs);
/* how hard it thinks, as the menu offers it */
- const effortOption = agentStore.options[agent]?.find((o) => o.category === 'thought_level');
+ const effortOption = options?.find((o) => o.category === 'thought_level');
const effort = effortOption && offeredOption(agent, agentStore.roster, effortOption) ? summary.effort : null;
- const modelLabel = [fixed ?? summary.model, effort].filter(Boolean).join(' · ');
+ const modelLabel = [summary.model, effort].filter(Boolean).join(' · ');
const started: Turn = {
...makePlaceholder(id, 'video', instruction, { projectId: projectKey, sessionId }),
...(promptDisplay ? { promptDisplay } : {}),
diff --git a/apps/desktop/chat/src/components/ModelPopover.tsx b/apps/desktop/chat/src/components/ModelPopover.tsx
index a84ce88..9ef9fde 100644
--- a/apps/desktop/chat/src/components/ModelPopover.tsx
+++ b/apps/desktop/chat/src/components/ModelPopover.tsx
@@ -19,7 +19,7 @@ import { Tooltip } from '@/components/Tooltip';
import { AgentIcon } from '@/components/AgentIcons';
import { POPOVER_CHROME } from '@/components/ComposerCard';
import { desktopBridge, type LocalAgentId, type RosterAgent } from '@/lib/desktop-bridge';
-import { agentModelSummary, currentAgent, effectivePrefs, fixedModel, offeredOption, optionLabel, optionValue, shownAgents, useLocalAgents } from '@/state/local-agent-store';
+import { agentModelSummary, agentOptions, currentAgent, effectivePrefs, offeredOption, optionLabel, optionValue, shownAgents, useLocalAgents } from '@/state/local-agent-store';
import { chatLayer } from '@/lib/chat-layer';
/** the card, wider when it lists the agents; the side menu's least width; the gap between them; the window's margin */
@@ -94,11 +94,11 @@ export function ModelPopover({ placement = 'bottom', align = 'start' }: { placem
});
}, [open, refresh, ensureOptions]);
- const options = la.options[agent];
- const prefs = effectivePrefs(la.prefs, agent, la.roster, la.options[agent]);
+ const options = agentOptions(la, agent);
+ const prefs = effectivePrefs(la.prefs, agent, la.roster, options);
const rows = menuOptions(options).filter((o) => offeredOption(agent, la.roster, o));
const summary = agentModelSummary(options, prefs);
- const triggerModel = fixedModel(agent, la.roster) ?? summary.model;
+ const triggerModel = summary.model;
const triggerEffort = rows.some((o) => o.category === 'thought_level') ? summary.effort : null;
const valueOf = (o: Option) => (o.category === 'model' ? triggerModel : null) ?? optionLabel(options, o.id, optionValue(options, prefs, o.id)) ?? '';
const rowLabel = (o: Option) => (o.category === 'model' ? t('composer.model') : o.category === 'thought_level' ? t('composer.effort') : isSpeed(o) ? t('composer.speed') : o.name);
@@ -232,7 +232,7 @@ export function ModelPopover({ placement = 'bottom', align = 'start' }: { placem
{current ? `${nameOf(current)}: ${statusOf(current) ?? ''}` : t('composer.agentLoading')}{' '}
<button type="button" onMouseDown={keepFocus} onClick={openSettings} className="text-[var(--text)] underline underline-offset-2">{t('composer.openSettings')}</button>
</div>
- ) : rows.length === 0 ? (
+ ) : rows.length === 0 && options && !la.optionsError[agent] ? null : rows.length === 0 ? (
<p className="px-2.5 py-1.5 text-[12px] leading-relaxed text-[var(--text-muted)]">
{la.optionsError[agent]
? <>{t('composer.agentOptionsFailed')} <button type="button" onMouseDown={keepFocus} onClick={() => void la.ensureOptions(agent)} className="text-[var(--text)] underline underline-offset-2">{t('project.retry')}</button></>
diff --git a/apps/desktop/chat/src/lib/desktop-bridge.ts b/apps/desktop/chat/src/lib/desktop-bridge.ts
index ecca496..9f08636 100644
--- a/apps/desktop/chat/src/lib/desktop-bridge.ts
+++ b/apps/desktop/chat/src/lib/desktop-bridge.ts
@@ -24,7 +24,7 @@ export interface RosterAgent {
install?: string | null;
setupRequired?: string | null;
error?: string;
- byok?: { format: 'responses' | 'chat' | 'anthropic'; baseUrl: string; model: string; last4: string };
+ byok?: { format: 'responses' | 'chat' | 'anthropic'; baseUrl: string; model: string; models?: string[]; last4: string };
}
export interface LocalAgentState {
diff --git a/apps/desktop/chat/src/state/local-agent-store.ts b/apps/desktop/chat/src/state/local-agent-store.ts
index cc329c6..4df646e 100644
--- a/apps/desktop/chat/src/state/local-agent-store.ts
+++ b/apps/desktop/chat/src/state/local-agent-store.ts
@@ -73,23 +73,28 @@ function save(s: Persisted): void {
} catch { /* private mode */ }
}
-/**
- * What an agent's model is called, when Settings sets it rather than the agent: the own key's model. Null for the
- * person's own agents, whose own option list says.
- */
-export function fixedModel(agent: LocalAgentId, roster: RosterAgent[] | null): string | null {
- if (agent === 'byok') return roster?.find((a) => a.id === 'byok')?.byok?.model ?? null;
- return null;
+/** The own key's models, as Settings names them (the first one to begin with). */
+function byokModels(roster: RosterAgent[] | null): string[] {
+ const byok = roster?.find((a) => a.id === 'byok')?.byok;
+ if (!byok) return [];
+ return byok.models?.length ? byok.models : [byok.model].filter(Boolean);
}
/**
- * Which of an agent's options the menu offers. The app's own agent runs the model Settings names (Codex would list
- * OpenAI's, which the person's service may not have), and no OpenAI fast mode; through the Chat Completions
- * translator, no reasoning effort either (it does not carry it).
+ * An agent's option list, for the menu. The own key's is its models, from Settings: no session has to start to know
+ * them (the app's own agent reports the same `model` option, apps/desktop/src/pi-config.mjs modelOption). The person's
+ * own agents' is the one a session last reported.
*/
+export function agentOptions(state: Pick<LocalAgentStore, 'options' | 'roster'>, agent: LocalAgentId): ConfigOptions | undefined {
+ if (agent !== 'byok') return state.options[agent];
+ const models = byokModels(state.roster);
+ if (!models.length) return undefined;
+ return [{ id: 'model', name: 'Model', category: 'model', type: 'select', currentValue: models[0], options: models.map((m) => ({ value: m, name: m })) }];
+}
+
+/** Which of an agent's options the menu offers. The app's own agent offers its models, and no OpenAI fast mode. */
export function offeredOption(agent: LocalAgentId, roster: RosterAgent[] | null, option: { id: string; category?: string; name: string }): boolean {
if (agent !== 'byok') return true;
- if (option.category === 'model') return false;
if (/^(fast|fast-mode|speed)$/i.test(option.id) || option.category === 'speed') return false;
if (option.category === 'thought_level') return roster?.find((a) => a.id === 'byok')?.byok?.format !== 'chat';
return true;
@@ -128,8 +133,8 @@ export const useLocalAgents = create<LocalAgentStore>((set, get) => ({
for (const before of get().roster ?? []) {
const now = roster.find((a) => a.id === before.id);
if (before.status === 'ready' && now?.status !== 'ready') forgetLocalAgentSessions(before.id);
- /* another model (the own key's): its sessions were closed for the next one to use it */
- else if (before.byok?.model !== now?.byok?.model) forgetLocalAgentSessions(before.id);
+ /* other models (the own key's): its sessions were closed for the next ones to use them */
+ else if (String(byokModels([before])) !== String(byokModels(now ? [now] : []))) forgetLocalAgentSessions(before.id);
}
set({ roster });
});
@@ -155,7 +160,8 @@ export const useLocalAgents = create<LocalAgentStore>((set, get) => ({
save(get());
},
async ensureOptions(agent) {
- if (get().options[agent] || probing.has(agent)) return;
+ /* the own key's are known from Settings (agentOptions) */
+ if (agent === 'byok' || get().options[agent] || probing.has(agent)) return;
const api = desktopBridge()?.localAgents;
if (!api) return;
probing.add(agent);
@@ -192,7 +198,10 @@ export function effectivePrefs(prefs: Persisted['prefs'], agent: LocalAgentId, r
const claudeHarness = agent === 'byok' && roster?.find((a) => a.id === 'byok')?.byok?.format === 'anthropic';
/* "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 */
- const kept = Object.fromEntries(Object.entries(prefs[agent] ?? {}).filter(([, value]) => value !== 'default'));
+ /* a model the own key no longer names: its first one stands instead */
+ const models = agent === 'byok' ? byokModels(roster ?? null) : null;
+ const kept = Object.fromEntries(Object.entries(prefs[agent] ?? {})
+ .filter(([id, value]) => value !== 'default' && !(models && id === 'model' && !models.includes(String(value)))));
const effort = options?.find((o) => o.category === 'thought_level');
const high = effort && !(effort.id in kept) && effort.options?.some((o) => o.value === 'high') ? { [effort.id]: 'high' } : {};
return { ...high, ...kept, ...(AGENT_FORCED_PREFS[claudeHarness ? 'claude' : agent] ?? {}) };
diff --git a/apps/desktop/scripts/release.mjs b/apps/desktop/scripts/release.mjs
index 81d9dee..6b07ff7 100644
--- a/apps/desktop/scripts/release.mjs
+++ b/apps/desktop/scripts/release.mjs
@@ -14,6 +14,11 @@
* and the updater. Optional dependencies are left out: the adapters would bring the makers' own Claude Code and
* Codex programs (200–330 MB each), and the app uses the person's own installation instead (src/agents.mjs).
* The staged `openfilm` package gets the build's product.json;
+ * 2b. the programs the app needs that are not node modules, for the platform and chip built for, in the app's
+ * resources (runtime/; src/main.mjs puts them to use): ffmpeg and ffprobe with their license (src/ffmpeg-runtime.mjs),
+ * and the headless browser Studio and `openfilm` draw pages in (Playwright's, the revision the staged
+ * playwright-core takes). People never download either: on a slow or blocked connection the first start used to
+ * fail there;
* 3. electron-builder makes the .dmg (to download) and the .zip (for updates), signed with the Developer ID
* OPENFILM_SIGN_IDENTITY ("Name (TEAMID)") and notarized (APPLE_TEAM_ID, the `openfilm-notary` keychain profile or
* OPENFILM_NOTARY_PROFILE), with the update feed written in (none without one). Without OPENFILM_SIGN_IDENTITY
@@ -33,7 +38,7 @@ import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, write
import { createRequire } from 'node:module';
import { createHash } from 'node:crypto';
import { basename, dirname, join, resolve } from 'node:path';
-import { fileURLToPath } from 'node:url';
+import { fileURLToPath, pathToFileURL } from 'node:url';
const require = createRequire(import.meta.url);
const desktop = resolve(dirname(fileURLToPath(import.meta.url)), '..');
@@ -94,6 +99,16 @@ run('npm', ['install', '--omit=dev', '--omit=optional', '--no-audit', '--no-fund
/* the build's product file */
cpSync(productFile, join(stage, 'node_modules/openfilm/product.json'));
+/* 2b. ffmpeg and the headless browser, for the platform and chip built for */
+const runtime = join(work, 'runtime');
+const { ffmpegDownloadable, fetchFfmpeg } = await import(pathToFileURL(join(desktop, 'src/ffmpeg-runtime.mjs')).href);
+const platform = win ? 'win32' : 'darwin';
+if (ffmpegDownloadable(platform, arch)) await fetchFfmpeg(join(runtime, 'ffmpeg'), { platform, arch, license: true });
+else console.warn(`No ffmpeg build for ${platform}-${arch}: this app downloads none either; people install their own.`);
+run(process.execPath, [join(stage, 'node_modules/playwright-core/cli.js'), 'install', 'chromium-headless-shell'], {
+ env: { ...process.env, PLAYWRIGHT_BROWSERS_PATH: join(runtime, 'ms-playwright'), PLAYWRIGHT_HOST_PLATFORM_OVERRIDE: win ? 'win64' : arch === 'arm64' ? 'mac15-arm64' : 'mac15' },
+});
+
/* 3. the app */
const builder = require('electron-builder');
const electronVersion = require('electron/package.json').version;
@@ -129,6 +144,8 @@ await builder.build({
/* run by Electron as Node from outside the archive: the CLI the agents run, the agents' adapters */
asarUnpack: ['node_modules/openfilm/**', 'node_modules/@agentclientprotocol/**', 'node_modules/playwright-core/**'],
files: ['src/**/*', 'shell/dist/**/*', 'package.json', 'node_modules/**/*'],
+ /* ffmpeg and the headless browser (2b), as files of their own beside the archive: they run as programs */
+ extraResources: [{ from: runtime, to: 'runtime' }],
directories: { output: out, buildResources: join(desktop, 'build') },
electronFuses: {
runAsNode: true,
diff --git a/apps/desktop/src/agent-roster.mjs b/apps/desktop/src/agent-roster.mjs
index d87648f..290ea9b 100644
--- a/apps/desktop/src/agent-roster.mjs
+++ b/apps/desktop/src/agent-roster.mjs
@@ -9,8 +9,9 @@
* connects one or switches it on.
* · byok — the app's own agent (Pi, pi-agent.mjs) on the person's own key, on a standard API in one of three formats: the OpenAI
* Responses API (…/v1/responses), the OpenAI Chat Completions API (…/v1/chat/completions) or the Anthropic Messages
- * API (…/v1/messages); Pi speaks each. The model has to read pictures (the agent looks at its own frames): setting
- * it up sends one small request with a picture, and a model that cannot take it is refused.
+ * API (…/v1/messages); Pi speaks each. It may name several models (the chat's menu switches between them, the first
+ * one to begin with). Each has to read pictures (the agent looks at its own frames): setting it up sends one small
+ * request with a picture to each, and a model that cannot take it is refused.
*
* Each has a switch for whether the chat's menu shows it. Kept in the app's data folder: agents.json (the choices) and
* byok.key (the key, sealed with the system's keychain by the caller's `seal`/`unseal`).
@@ -60,7 +61,7 @@ export function readChoices(dataDir) {
const shown = { ...DEFAULT_SHOWN };
for (const id of AGENT_IDS) if (typeof raw.shown?.[id] === 'boolean') shown[id] = raw.shown[id];
const byok = raw.byok && typeof raw.byok === 'object' && Object.hasOwn(BYOK_FORMATS, raw.byok.format)
- ? { format: raw.byok.format, baseUrl: String(raw.byok.baseUrl ?? ''), model: String(raw.byok.model ?? ''), last4: String(raw.byok.last4 ?? '') }
+ ? byokChoice(raw.byok)
: null;
return {
shown,
@@ -69,6 +70,18 @@ export function readChoices(dataDir) {
};
}
+/** The own key's choice as kept: its models (one kept before there could be several is the one), the first the default. */
+function byokChoice(raw) {
+ const models = modelList(Array.isArray(raw.models) && raw.models.length ? raw.models : [raw.model]);
+ return { format: raw.format, baseUrl: String(raw.baseUrl ?? ''), model: models[0] ?? '', models, last4: String(raw.last4 ?? '') };
+}
+
+/** Model names, from a list or text (separated by commas or new lines): trimmed, each once, in order. */
+export function modelList(value) {
+ const names = (Array.isArray(value) ? value : String(value ?? '').split(/[,\n]/)).map((m) => String(m ?? '').trim()).filter(Boolean);
+ return [...new Set(names)];
+}
+
function writeChoices(dataDir, choices) {
mkdirSync(dataDir, { recursive: true });
writeFileSync(join(dataDir, 'agents.json'), `${JSON.stringify(choices, null, 2)}\n`);
@@ -170,7 +183,7 @@ export function createRoster(deps) {
shown: choices.shown[id] ?? false,
...stateOf(id),
...(live.errors[id] ? { error: live.errors[id] } : {}),
- ...(id === 'byok' && choices.byok ? { byok: { format: choices.byok.format, baseUrl: choices.byok.baseUrl, model: choices.byok.model, last4: choices.byok.last4 } } : {}),
+ ...(id === 'byok' && choices.byok ? { byok: { ...choices.byok, models: [...choices.byok.models] } } : {}),
}));
}
@@ -240,21 +253,23 @@ export function createRoster(deps) {
},
/**
- * The person's own key: checked (key accepted, model reads pictures) before it is kept. A key left empty keeps
- * the one kept already (the model or the address changed).
- * @param {{ format: string, baseUrl?: string, model: string, key?: string }} config
+ * The person's own key: checked (key accepted, each model reads pictures) before it is kept. A key left empty keeps
+ * the one kept already (the models or the address changed). `models`: a list, or text with the names separated by
+ * commas or new lines (`model`, one name, as before).
+ * @param {{ format: string, baseUrl?: string, models?: string[] | string, model?: string, key?: string }} config
*/
async configureByok(config) {
const format = BYOK_FORMATS[config?.format];
if (!format) return { ok: false, error: 'Choose the API format.' };
const baseUrl = String(config.baseUrl || format.baseUrl).trim().replace(/\/+$/, '');
if (!/^https?:\/\/[^\s]+$/.test(baseUrl)) return { ok: false, error: 'The address has to start with https:// (or http:// for one on this computer).' };
- const model = String(config.model ?? '').trim();
- if (!model) return { ok: false, error: 'Name the model.' };
+ const models = modelList(config.models ?? config.model);
+ if (!models.length) return { ok: false, error: 'Name the model.' };
const key = String(config.key ?? '').trim() || byokKey();
if (!key) return { ok: false, error: 'Paste the key.' };
- const probe = await probeModel({ format: config.format, baseUrl, key, model, fetch: deps.fetch });
- if (!probe.ok) return probe;
+ const probes = await Promise.all(models.map((model) => probeModel({ format: config.format, baseUrl, key, model, fetch: deps.fetch })));
+ const failed = probes.findIndex((p) => !p.ok);
+ if (failed >= 0) return models.length > 1 ? { ...probes[failed], error: `${models[failed]}: ${probes[failed].error}` } : probes[failed];
mkdirSync(dataDir, { recursive: true });
writeFileSync(keyFile, deps.seal(key), { mode: 0o600 });
delete live.errors.byok;
@@ -262,7 +277,7 @@ export function createRoster(deps) {
...choices,
shown: { ...choices.shown, byok: true },
disconnected: choices.disconnected.filter((a) => a !== 'byok'),
- byok: { format: config.format, baseUrl, model, last4: key.slice(-4) },
+ byok: { format: config.format, baseUrl, model: models[0], models, last4: key.slice(-4) },
});
deps.closeSessions('byok');
changed();
@@ -271,15 +286,16 @@ export function createRoster(deps) {
/**
* What a session of the app's own agent runs with (pi-agent.mjs): Pi's own folder, the service (Pi's provider:
- * its API, address and the variable its key is in), the model, and the key itself (`env`).
+ * its API, address and the variable its key is in), the models (`model` the one it starts on), and the key itself
+ * (`env`).
*/
harness(id) {
if (id !== 'byok') return null;
const key = byokKey();
if (!choices.byok || !key) return null;
- const { format, baseUrl, model } = choices.byok;
+ const { format, baseUrl, model, models } = choices.byok;
const provider = { id: 'byok', api: PI_APIS[format], baseUrl, apiKeyEnv: 'OPENFILM_BYOK_KEY' };
- return { home: join(dataDir, 'agents', 'byok', 'pi'), provider, model, env: { OPENFILM_BYOK_KEY: key } };
+ return { home: join(dataDir, 'agents', 'byok', 'pi'), provider, model, models: [...models], env: { OPENFILM_BYOK_KEY: key } };
},
};
}
diff --git a/apps/desktop/src/agent-roster.test.mjs b/apps/desktop/src/agent-roster.test.mjs
index 287677a..f96af1e 100644
--- a/apps/desktop/src/agent-roster.test.mjs
+++ b/apps/desktop/src/agent-roster.test.mjs
@@ -1,6 +1,6 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
-import { mkdtempSync, readFileSync } from 'node:fs';
+import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { createRoster, probeRequest, readChoices } from './agent-roster.mjs';
@@ -43,7 +43,7 @@ test('a key is kept only once the service took it with a picture; a model that c
assert.match((await r.configureByok({ format: 'chat', baseUrl: 'https://api.deepseek.com/v1', model: 'm', key: 'bad' })).error, /did not accept/);
answer = { status: 200, body: { choices: [] } };
assert.deepEqual(await r.configureByok({ format: 'chat', baseUrl: 'https://api.deepseek.com/v1/', model: 'vision', key: 'sk-good-9876' }), { ok: true });
- assert.deepEqual(readChoices(dir).byok, { format: 'chat', baseUrl: 'https://api.deepseek.com/v1', model: 'vision', last4: '9876' });
+ assert.deepEqual(readChoices(dir).byok, { format: 'chat', baseUrl: 'https://api.deepseek.com/v1', model: 'vision', models: ['vision'], last4: '9876' });
assert.equal(readChoices(dir).shown.byok, true, 'set up: shown in the chat');
assert.equal(readFileSync(join(dir, 'byok.key'), 'utf8'), 'sealed:sk-good-9876', 'the key sealed');
assert.equal(JSON.stringify(readChoices(dir)).includes('sk-good'), false, 'never in the choices file');
@@ -73,6 +73,37 @@ test('each format is Pi\'s provider on that API, the key in its own variable', a
assert.equal(h.model, 'claude-x');
});
+test('a key may name several models: each is asked with a picture, the first is the one a session starts on', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'of-roster-'));
+ const asked = [];
+ const fetch = async (_url, init) => {
+ const { model } = JSON.parse(init.body);
+ asked.push(model);
+ return model === 'text-only'
+ ? new Response(JSON.stringify({ error: { message: 'This model does not support image input.' } }), { status: 400 })
+ : new Response('{}', { status: 200 });
+ };
+ const r = roster(dir, fetch);
+ const refused = await r.configureByok({ format: 'chat', baseUrl: 'https://api.deepseek.com/v1', models: 'vision, text-only', key: 'sk-1234' });
+ assert.equal(refused.ok, false);
+ assert.match(refused.error, /^text-only: /, 'says which model');
+ assert.equal(readChoices(dir).byok, null, 'nothing kept');
+ asked.length = 0;
+ assert.deepEqual(await r.configureByok({ format: 'chat', baseUrl: 'https://api.deepseek.com/v1', models: 'vision\n big , vision,', key: 'sk-1234' }), { ok: true });
+ assert.deepEqual(asked.sort(), ['big', 'vision']);
+ assert.deepEqual(readChoices(dir).byok.models, ['vision', 'big'], 'trimmed, each once, in order');
+ const h = r.harness('byok');
+ assert.equal(h.model, 'vision');
+ assert.deepEqual(h.models, ['vision', 'big']);
+ assert.deepEqual(r.list().find((a) => a.id === 'byok').byok.models, ['vision', 'big']);
+});
+
+test('a key kept with one model, before there could be several, reads as that one', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'of-roster-'));
+ writeFileSync(join(dir, 'agents.json'), JSON.stringify({ byok: { format: 'responses', baseUrl: 'https://api.openai.com/v1', model: 'gpt-x', last4: 'abcd' } }));
+ assert.deepEqual(readChoices(dir).byok, { format: 'responses', baseUrl: 'https://api.openai.com/v1', model: 'gpt-x', models: ['gpt-x'], last4: 'abcd' });
+});
+
test("Codex and Claude Code are shown in the chat from the start, the person's other agents once connected or switched on", async () => {
const dir = mkdtempSync(join(tmpdir(), 'of-roster-'));
const found = (id, cli) => ({ id, cli, signedIn: true, install: 'https://example.test', setupRequired: null });
diff --git a/apps/desktop/src/agents.mjs b/apps/desktop/src/agents.mjs
index 28dcec5..cfa2386 100644
--- a/apps/desktop/src/agents.mjs
+++ b/apps/desktop/src/agents.mjs
@@ -389,7 +389,7 @@ export class AgentSession {
const own = !harness ? {} : {
...harness.env,
OPENFILM_GET_WEB: '1',
- OPENFILM_PI: JSON.stringify({ agentDir: harness.home, provider: harness.provider, model: harness.model, systemPrompt: ownAgentPrompt() }),
+ OPENFILM_PI: JSON.stringify({ agentDir: harness.home, provider: harness.provider, model: harness.model, models: harness.models ?? [harness.model], systemPrompt: ownAgentPrompt() }),
};
/* an agent that speaks ACP itself: its own program, started as the registry starts it */
const native = cli && !this.spec.adapter ? starting(cli.path, this.spec.args) : null;
diff --git a/apps/desktop/src/ffmpeg-runtime.mjs b/apps/desktop/src/ffmpeg-runtime.mjs
index fd4027e..db52efe 100644
--- a/apps/desktop/src/ffmpeg-runtime.mjs
+++ b/apps/desktop/src/ffmpeg-runtime.mjs
@@ -1,9 +1,10 @@
/**
- * ffmpeg and ffprobe for a computer that has none: Studio and `openfilm` need them for video pictures, sound and every
- * export. When they are not on the PATH, the app downloads them once into its data folder, from the ffmpeg-static
- * project's release (static builds, GPL-3.0, as published there: the app does not ship them), each checked against
- * the sha256 pinned here. The folder is on the PATH Studio and the agents get from the start, so they find the
- * programs the moment they land, without a restart.
+ * ffmpeg and ffprobe: Studio and `openfilm` need them for video pictures, sound and every export. The installer brings
+ * its own (scripts/release.mjs puts them in the app's resources, `runtime/ffmpeg`, with their license), so the app
+ * works without a download. A build without them (from source) downloads them once into its data folder when the
+ * computer has none on its PATH. Both come from the ffmpeg-static project's release (static builds, GPL-3.0, as
+ * published there), each checked against the sha256 pinned here. The folder is on the PATH Studio and the agents get
+ * from the start, so they find the programs the moment they land, without a restart.
*
* Reads no Electron module, so `node --test` can use it.
*/
@@ -15,28 +16,40 @@ import { gunzipSync } from 'node:zlib';
const RELEASE = 'b6.1.1';
const BASE = `https://github.com/eugeneware/ffmpeg-static/releases/download/${RELEASE}`;
-
-/** The pinned builds: `<program>-<platform>-<arch>.gz` and its sha256 (as the release publishes it). */
+/**
+ * The pinned builds: `<program>-<platform>-<arch>.gz` and its sha256 (as the release publishes it), and the FFmpeg
+ * version each is (as `ffmpeg -version` says), whose source goes beside it for its GPL.
+ */
const BUILDS = Object.freeze({
'darwin-arm64': {
+ version: '6.0',
ffmpeg: '8923876afa8db5585022d7860ec7e589af192f441c56793971276d450ed3bbfa',
ffprobe: 'd986a8ec7b030899fe66a8a288ed809a3543338705a3ce178cfb85869c5d80be',
},
'darwin-x64': {
+ version: '6.1.1',
ffmpeg: '929b375c1182d956c51f7ac25e0b2b0411fb01f6f407aa15c9758efeb4242106',
ffprobe: 'd4da574d6e2e197bd259b47d69cf262df9e312af24ad960444f6d806d3d4c186',
},
'win32-x64': {
+ version: '6.1.1',
ffmpeg: '8883a3dffbd0a16cf4ef95206ea05283f78908dbfb118f73c83f4951dcc06d77',
ffprobe: 'f309e6223ad89d2fe54bccd420a7709b66fd27540674e92309578ed491a43c8d',
},
});
+/** A download that brings nothing for this long has stalled: it is stopped and tried again. */
+const STALL_MS = 30_000;
+const TRIES = 3;
+
const exe = (name, platform = process.platform) => (platform === 'win32' ? `${name}.exe` : name);
/** The folder the downloaded programs go in (on the PATH of Studio and the agents, whether they are there yet or not). */
export const ffmpegDir = (dataDir) => join(dataDir, 'runtime', `ffmpeg-${RELEASE}`);
+/** Whether a folder holds both programs (the installer's, or a download that finished). */
+export const ffmpegIn = (dir, platform = process.platform) => ['ffmpeg', 'ffprobe'].every((n) => existsSync(join(dir, exe(n, platform))));
+
/** Whether both programs run from this PATH. */
export function ffmpegOnPath(path) {
return ['ffmpeg', 'ffprobe'].every((bin) => {
@@ -56,13 +69,19 @@ let downloading = null;
*/
export function ensureFfmpeg(dataDir, { onProgress = () => {}, fetch: fetchImpl = fetch } = {}) {
const dir = ffmpegDir(dataDir);
- if (['ffmpeg', 'ffprobe'].every((n) => existsSync(join(dir, exe(n))))) return Promise.resolve(dir);
- downloading ??= download(dir, onProgress, fetchImpl).finally(() => { downloading = null; });
+ if (ffmpegIn(dir)) return Promise.resolve(dir);
+ downloading ??= fetchFfmpeg(dir, { onProgress, fetch: fetchImpl }).finally(() => { downloading = null; });
return downloading;
}
-async function download(dir, onProgress, fetchImpl) {
- const key = `${process.platform}-${process.arch}`;
+/**
+ * Download one platform's build into `dir`: both programs, and with `license`, its LICENSE, its README and where its
+ * source is (what the installer ships beside them). A download that stalls is tried again.
+ * @param {string} dir
+ * @param {{ platform?: string, arch?: string, license?: boolean, onProgress?: (fraction: number) => void, fetch?: typeof fetch, stallMs?: number }} [options]
+ */
+export async function fetchFfmpeg(dir, { platform = process.platform, arch = process.arch, license = false, onProgress = () => {}, fetch: fetchImpl = fetch, stallMs = STALL_MS } = {}) {
+ const key = `${platform}-${arch}`;
const build = BUILDS[key];
if (!build) throw new Error(`There is no ffmpeg to download for ${key}: install it from ffmpeg.org.`);
mkdirSync(dir, { recursive: true });
@@ -74,24 +93,55 @@ async function download(dir, onProgress, fetchImpl) {
if (all) onProgress(Math.min(0.99, (got.ffmpeg + got.ffprobe) / all));
};
await Promise.all(names.map(async (name) => {
- const target = join(dir, exe(name));
+ const target = join(dir, exe(name, platform));
if (existsSync(target)) return;
- const res = await fetchImpl(`${BASE}/${name}-${key}.gz`);
- if (!res.ok || !res.body) throw new Error(`Downloading ${name} failed (${res.status}).`);
- total[name] = Number(res.headers.get('content-length')) || 0;
- const chunks = [];
- for await (const chunk of res.body) {
- chunks.push(chunk);
- got[name] += chunk.length;
- tell();
- }
- const gz = Buffer.concat(chunks);
+ const gz = await retried(() => {
+ got[name] = 0;
+ return download(`${BASE}/${name}-${key}.gz`, fetchImpl, stallMs, (size) => { total[name] = size; }, (n) => { got[name] += n; tell(); });
+ });
if (createHash('sha256').update(gz).digest('hex') !== build[name]) throw new Error(`The ${name} download did not match its checksum; nothing was kept.`);
const part = `${target}.part`;
writeFileSync(part, gunzipSync(gz));
chmodSync(part, 0o755);
renameSync(part, target);
}));
+ if (license) {
+ for (const [from, to] of [[`${key}.LICENSE`, 'LICENSE'], [`${key}.README`, 'README']]) {
+ writeFileSync(join(dir, to), await retried(() => download(`${BASE}/${from}`, fetchImpl, stallMs)));
+ }
+ writeFileSync(join(dir, 'SOURCE'), `FFmpeg ${build.version}, the static build of ffmpeg-static ${RELEASE} (${BASE}).\n`
+ + `Its source: https://ffmpeg.org/releases/ffmpeg-${build.version}.tar.xz\n`);
+ }
onProgress(1);
return dir;
}
+
+/** One file's bytes; one that stops coming for `stallMs` is an error. */
+async function download(url, fetchImpl, stallMs, onSize = () => {}, onBytes = () => {}) {
+ const stop = new AbortController();
+ let timer = setTimeout(() => stop.abort(), stallMs);
+ const alive = () => { clearTimeout(timer); timer = setTimeout(() => stop.abort(), stallMs); };
+ try {
+ const res = await fetchImpl(url, { signal: stop.signal });
+ if (!res.ok || !res.body) throw new Error(`Downloading ${url.split('/').pop()} failed (${res.status}).`);
+ onSize(Number(res.headers.get('content-length')) || 0);
+ const chunks = [];
+ for await (const chunk of res.body) {
+ alive();
+ chunks.push(chunk);
+ onBytes(chunk.length);
+ }
+ return Buffer.concat(chunks);
+ } catch (e) {
+ if (stop.signal.aborted) throw new Error(`Downloading ${url.split('/').pop()} stalled.`);
+ throw e;
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+async function retried(attempt) {
+ for (let i = 1; ; i++) {
+ try { return await attempt(); } catch (e) { if (i >= TRIES) throw e; }
+ }
+}
diff --git a/apps/desktop/src/ffmpeg-runtime.test.mjs b/apps/desktop/src/ffmpeg-runtime.test.mjs
new file mode 100644
index 0000000..8af3e73
--- /dev/null
+++ b/apps/desktop/src/ffmpeg-runtime.test.mjs
@@ -0,0 +1,54 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { gzipSync } from 'node:zlib';
+import { fetchFfmpeg, ffmpegIn } from './ffmpeg-runtime.mjs';
+
+/** A response whose body comes in one piece. */
+const answer = (bytes) => new Response(new ReadableStream({ start(c) { c.enqueue(bytes); c.close(); } }), { headers: { 'content-length': String(bytes.length) } });
+
+test('a build whose checksum is not the pinned one is not kept', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'of-ffmpeg-'));
+ const fetch = async () => answer(gzipSync(Buffer.from('not ffmpeg')));
+ await assert.rejects(fetchFfmpeg(dir, { platform: 'darwin', arch: 'arm64', fetch }), /did not match its checksum/);
+ assert.equal(ffmpegIn(dir, 'darwin'), false);
+});
+
+test('no build for a platform says so', async () => {
+ await assert.rejects(fetchFfmpeg(mkdtempSync(join(tmpdir(), 'of-ffmpeg-')), { platform: 'linux', arch: 'x64' }), /no ffmpeg to download for linux-x64/);
+});
+
+test('a download that fails is tried again, three times in all', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'of-ffmpeg-'));
+ const asked = [];
+ const fetch = async (url) => { asked.push(url.split('/').pop()); throw new TypeError('fetch failed'); };
+ await assert.rejects(fetchFfmpeg(dir, { platform: 'win32', arch: 'x64', fetch }), /fetch failed/);
+ assert.deepEqual(asked.filter((n) => n === 'ffmpeg-win32-x64.gz').length, 3);
+});
+
+test('a download that stops coming is stopped and tried again', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'of-ffmpeg-'));
+ let tries = 0;
+ const fetch = async (url, { signal }) => {
+ if (url.endsWith('ffmpeg-darwin-x64.gz')) tries++;
+ /* fetch ends a body whose request is aborted with an error */
+ return new Response(new ReadableStream({ start(c) { signal.addEventListener('abort', () => c.error(new DOMException('aborted', 'AbortError'))); } }));
+ };
+ await assert.rejects(fetchFfmpeg(dir, { platform: 'darwin', arch: 'x64', fetch, stallMs: 50 }), /stalled/);
+ assert.equal(tries, 3);
+});
+
+test('the installer\'s copy has the build\'s license, its readme and where its source is', async () => {
+ /* the programs themselves are the pinned builds: a stand-in with the pinned checksum is not to be had, so this
+ checks the license files only, with the programs already there */
+ const dir = mkdtempSync(join(tmpdir(), 'of-ffmpeg-'));
+ writeFileSync(join(dir, 'ffmpeg.exe'), '');
+ writeFileSync(join(dir, 'ffprobe.exe'), '');
+ const fetch = async (url) => answer(Buffer.from(`text of ${url.split('/').pop()}`));
+ await fetchFfmpeg(dir, { platform: 'win32', arch: 'x64', license: true, fetch });
+ assert.equal(readFileSync(join(dir, 'LICENSE'), 'utf8'), 'text of win32-x64.LICENSE');
+ assert.equal(readFileSync(join(dir, 'README'), 'utf8'), 'text of win32-x64.README');
+ assert.match(readFileSync(join(dir, 'SOURCE'), 'utf8'), /^FFmpeg 6\.1\.1,[^]*ffmpeg-6\.1\.1\.tar\.xz/);
+});
diff --git a/apps/desktop/src/main.mjs b/apps/desktop/src/main.mjs
index f422296..db92417 100644
--- a/apps/desktop/src/main.mjs
+++ b/apps/desktop/src/main.mjs
@@ -8,7 +8,7 @@
* ffmpeg, updates (preload.cjs). The window opens straight into the last project.
*/
import { BaseWindow, Menu, WebContentsView, app, dialog, ipcMain, nativeTheme, safeStorage, screen, shell } from 'electron';
-import { appendFileSync, createReadStream, mkdirSync, statSync } from 'node:fs';
+import { appendFileSync, createReadStream, existsSync, mkdirSync, statSync } from 'node:fs';
import { basename, join } from 'node:path';
import { Readable } from 'node:stream';
import { fileURLToPath } from 'node:url';
@@ -23,7 +23,7 @@ import { createRoster } from './agent-roster.mjs';
import { listAgents, openAgentSignIn } from './agents.mjs';
import { installOpenfilmCommand } from './openfilm-command.mjs';
import { startUpdates } from './updates.mjs';
-import { ensureFfmpeg, ffmpegDir, ffmpegDownloadable, ffmpegOnPath } from './ffmpeg-runtime.mjs';
+import { ensureFfmpeg, ffmpegDir, ffmpegDownloadable, ffmpegIn, ffmpegOnPath } from './ffmpeg-runtime.mjs';
import { PATH_SEP } from './environment.mjs';
const here = (path) => fileURLToPath(new URL(path, import.meta.url));
@@ -209,10 +209,17 @@ async function start() {
});
- /* no ffmpeg on this computer: the app's own goes first on the PATH of Studio and the agents, and is downloaded
- once the window is up (they find it the moment it lands) */
- const needFfmpeg = !ffmpegOnPath(env.PATH) && ffmpegDownloadable();
- if (needFfmpeg) env.PATH = [ffmpegDir(DATA), env.PATH].join(PATH_SEP);
+ /* what the installer brings (scripts/release.mjs): ffmpeg and ffprobe, first on the PATH of Studio and the agents,
+ and the headless browser Studio and `openfilm` draw pages in. A build without them (from source): no ffmpeg on
+ this computer, the app's own goes first on the PATH and is downloaded once the window is up (they find it the
+ moment it lands); the browser, Studio downloads the first time (studio-process.mjs) */
+ const runtime = app.isPackaged ? join(process.resourcesPath, 'runtime') : null;
+ const ownFfmpeg = runtime && ffmpegIn(join(runtime, 'ffmpeg')) ? join(runtime, 'ffmpeg') : null;
+ const needFfmpeg = !ownFfmpeg && !ffmpegOnPath(env.PATH) && ffmpegDownloadable();
+ const ffmpegHere = ownFfmpeg ?? (needFfmpeg ? ffmpegDir(DATA) : null);
+ if (ffmpegHere) env.PATH = [ffmpegHere, env.PATH].join(PATH_SEP);
+ const browsers = runtime && existsSync(join(runtime, 'ms-playwright')) ? { PLAYWRIGHT_BROWSERS_PATH: join(runtime, 'ms-playwright') } : {};
+ Object.assign(env, browsers);
const display = screen.getPrimaryDisplay().workArea;
const width = Math.min(1480, display.width);
@@ -291,9 +298,9 @@ async function start() {
log,
/* Studio refuses to delete a project an agent is working in */
onWorking: tellWorking,
- /* the `openfilm` command, and the app's ffmpeg when the computer has none (several folders, PATH-joined) */
- binDir: [installOpenfilmCommand(DATA), ...(needFfmpeg ? [ffmpegDir(DATA)] : [])].join(PATH_SEP),
- env: { OPENFILM_HOME: env.OPENFILM_HOME, ...(env.OPENFILM_LIBRARY ? { OPENFILM_LIBRARY: env.OPENFILM_LIBRARY } : {}) },
+ /* the `openfilm` command, and the app's ffmpeg (several folders, PATH-joined) */
+ binDir: [installOpenfilmCommand(DATA), ...(ffmpegHere ? [ffmpegHere] : [])].join(PATH_SEP),
+ env: { OPENFILM_HOME: env.OPENFILM_HOME, ...(env.OPENFILM_LIBRARY ? { OPENFILM_LIBRARY: env.OPENFILM_LIBRARY } : {}), ...browsers },
harness: async (id) => roster?.harness(id) ?? null,
});
/* Settings → Agents (in Studio's page) and the chat's agent menu: one roster, both told of every change */
diff --git a/apps/desktop/src/pi-agent.mjs b/apps/desktop/src/pi-agent.mjs
index 000e8d8..420dea6 100644
--- a/apps/desktop/src/pi-agent.mjs
+++ b/apps/desktop/src/pi-agent.mjs
@@ -4,7 +4,8 @@
* (agents.mjs starts it with Electron as Node).
*
* What it runs with comes in OPENFILM_PI (JSON; pi-config.mjs): its own folder (`agentDir`: Pi's models and settings,
- * never the person's ~/.pi), the service (`provider`), its model, and its whole system prompt (agents.mjs
+ * never the person's ~/.pi), the service (`provider`), its models (`model` the one a session starts on; the chat
+ * switches between them with the session's `model` option), and its whole system prompt (agents.mjs
* ownAgentPrompt), in place of Pi's. Of the project's instructions only its own AGENTS.md (or CLAUDE.md) is read, not
* the folders above it; no skills, no SYSTEM.md. Besides Pi's read, bash, edit and write it has `ask`: questions for
* the person, with options, shown in the chat as Claude Code's and Codex's are (an ACP form).
@@ -23,17 +24,18 @@ import { Readable, Writable } from 'node:stream';
import * as acp from '@agentclientprotocol/sdk';
import { DefaultResourceLoader, ModelRuntime, SessionManager, SettingsManager, createAgentSession } from '@earendil-works/pi-coding-agent';
import { agentSessionsDir, openLog } from './chat-store.mjs';
-import { contextUsed, modelsJson, stopReason, toolCall, toolContent } from './pi-config.mjs';
+import { contextUsed, modelOption, modelsJson, stopReason, toolCall, toolContent } from './pi-config.mjs';
/* stdout is the protocol's: anything else Pi or a library prints goes to stderr */
console.log = console.info = console.warn = console.debug = (...args) => process.stderr.write(`${args.map(String).join(' ')}\n`);
const config = JSON.parse(process.env.OPENFILM_PI ?? '{}');
const VERSION = '1.1.0';
+const models = Array.isArray(config.models) && config.models.length ? config.models : [config.model];
mkdirSync(config.agentDir, { recursive: true });
const modelsPath = join(config.agentDir, 'models.json');
-writeFileSync(modelsPath, JSON.stringify(modelsJson(config.provider, config.model), null, 2));
+writeFileSync(modelsPath, JSON.stringify(modelsJson(config.provider, models), null, 2));
const modelRuntime = await ModelRuntime.create({ authPath: join(config.agentDir, 'auth.json'), modelsPath });
/** Each open session: Pi's, and the turn being logged. */
@@ -134,7 +136,7 @@ async function open(client, cwd, resumeId) {
}
});
sessions.set(sessionId, entry);
- return { sessionId, configOptions: [], modes: null };
+ return { sessionId, configOptions: [modelOption(models, model.id)], modes: null };
}
/**
@@ -236,6 +238,15 @@ const connection = new acp.AgentSideConnection((client) => ({
entry.log = null;
}
},
+ async setSessionConfigOption(params) {
+ const entry = sessions.get(params.sessionId);
+ if (!entry) throw new Error('This conversation has ended.');
+ if (params.configId !== 'model') throw new Error(`No option ${params.configId}.`);
+ const model = models.includes(params.value) ? modelRuntime.getModel(config.provider.id, params.value) : null;
+ if (!model) throw new Error(`No model ${params.value} at ${config.provider.id}.`);
+ await entry.session.setModel(model);
+ return { configOptions: [modelOption(models, model.id)] };
+ },
async cancel(params) { await sessions.get(params.sessionId)?.session.abort(); },
async closeSession(params) {
sessions.get(params.sessionId)?.session.dispose();
diff --git a/apps/desktop/src/pi-agent.test.mjs b/apps/desktop/src/pi-agent.test.mjs
new file mode 100644
index 0000000..d3f6492
--- /dev/null
+++ b/apps/desktop/src/pi-agent.test.mjs
@@ -0,0 +1,57 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { createServer } from 'node:http';
+import { mkdtempSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { AgentSession } from './agents.mjs';
+
+/** A service on the Chat Completions API that answers "ok" and notes the model each request named. */
+async function service() {
+ const asked = [];
+ const server = createServer((req, res) => {
+ let body = '';
+ req.on('data', (d) => { body += d; });
+ req.on('end', () => {
+ const { model } = JSON.parse(body || '{}');
+ asked.push(model);
+ res.writeHead(200, { 'content-type': 'text/event-stream' });
+ const chunk = (choice, extra = {}) => `data: ${JSON.stringify({ id: 'c', object: 'chat.completion.chunk', created: 0, model, choices: [choice], ...extra })}\n\n`;
+ res.end(chunk({ index: 0, delta: { role: 'assistant', content: 'ok' }, finish_reason: null })
+ + chunk({ index: 0, delta: {}, finish_reason: 'stop' }, { usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 } })
+ + 'data: [DONE]\n\n');
+ });
+ });
+ await new Promise((done) => server.listen(0, '127.0.0.1', done));
+ return { asked, url: `http://127.0.0.1:${server.address().port}/v1`, close: () => server.close() };
+}
+
+test('the own key\'s agent offers its models as the session\'s model option, and a turn after a switch goes to that model', { timeout: 60_000 }, async () => {
+ const svc = await service();
+ const session = new AgentSession({
+ agent: 'byok',
+ cwd: mkdtempSync(join(tmpdir(), 'of-pi-')),
+ harness: {
+ home: mkdtempSync(join(tmpdir(), 'of-pi-home-')),
+ provider: { id: 'byok', api: 'openai-completions', baseUrl: svc.url, apiKeyEnv: 'OPENFILM_BYOK_KEY' },
+ model: 'vision', models: ['vision', 'big'],
+ env: { OPENFILM_BYOK_KEY: 'sk-test' },
+ },
+ });
+ try {
+ const info = await session.start();
+ const option = info.configOptions.find((o) => o.id === 'model');
+ assert.equal(option.category, 'model');
+ assert.equal(option.currentValue, 'vision', 'the first model to begin with');
+ assert.deepEqual(option.options.map((o) => o.value), ['vision', 'big']);
+ await session.prompt([{ type: 'text', text: 'hi' }]);
+ const switched = await session.setConfigOption('model', 'big');
+ assert.equal(switched.configOptions[0].currentValue, 'big');
+ await session.prompt([{ type: 'text', text: 'again' }]);
+ assert.deepEqual(svc.asked, ['vision', 'big']);
+ await assert.rejects(session.setConfigOption('model', 'other'), 'a model the key does not name is refused');
+ } finally {
+ session.close();
+ svc.close();
+ }
+});
diff --git a/apps/desktop/src/pi-config.mjs b/apps/desktop/src/pi-config.mjs
index 9ee1faf..653437c 100644
--- a/apps/desktop/src/pi-config.mjs
+++ b/apps/desktop/src/pi-config.mjs
@@ -1,8 +1,8 @@
/**
* What the app's own agent (Pi, src/pi-agent.mjs) runs with, and how what it does reads in the chat (ACP).
*
- * The service is one provider in Pi's `models.json`: the person's own key on one of three APIs, with the one model
- * they named.
+ * The service is one provider in Pi's `models.json`: the person's own key on one of three APIs, with the models they
+ * named; the chat's menu switches between them (`modelOption`).
*
* Reads no Electron module, so `node --test` can use it.
*/
@@ -14,17 +14,17 @@ export const PI_APIS = Object.freeze({ chat: 'openai-completions', responses: 'o
const CONTEXT = 128_000;
/**
- * Pi's `models.json` for the service and its model.
- * @param {{ id: string, api: string, baseUrl: string, apiKeyEnv: string }} provider @param {string} model
+ * Pi's `models.json` for the service and its models.
+ * @param {{ id: string, api: string, baseUrl: string, apiKeyEnv: string }} provider @param {string[] | string} models
*/
-export function modelsJson(provider, model) {
+export function modelsJson(provider, models) {
return {
providers: {
[provider.id]: {
baseUrl: provider.baseUrl,
api: provider.api,
apiKey: `$${provider.apiKeyEnv}`,
- models: [{
+ models: [models].flat().map((model) => ({
id: model,
name: model,
input: ['text', 'image'],
@@ -32,12 +32,17 @@ export function modelsJson(provider, model) {
maxTokens: Math.floor(CONTEXT / 4),
reasoning: false,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
- }],
+ })),
},
},
};
}
+/** The model as a config option the chat's menu reads (ACP): the models named, and the one a session runs. */
+export function modelOption(models, current) {
+ return { id: 'model', name: 'Model', category: 'model', type: 'select', currentValue: current, options: models.map((m) => ({ value: m, name: m })) };
+}
+
/** A tool call as the chat reads it (ACP): its kind, its title, and what it was run with. */
export function toolCall(name, args) {
const a = args && typeof args === 'object' ? args : {};
diff --git a/apps/desktop/src/pi-config.test.mjs b/apps/desktop/src/pi-config.test.mjs
index e6a86a5..3935109 100644
--- a/apps/desktop/src/pi-config.test.mjs
+++ b/apps/desktop/src/pi-config.test.mjs
@@ -1,6 +1,6 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
-import { contextUsed, modelsJson, outOfBalance, stopReason, toolCall, toolContent } from './pi-config.mjs';
+import { contextUsed, modelOption, modelsJson, outOfBalance, stopReason, toolCall, toolContent } from './pi-config.mjs';
test('the person\'s own key is one provider in Pi\'s models.json, with the one model they named', () => {
const p = modelsJson({ id: 'byok', api: 'openai-completions', baseUrl: 'https://api.deepseek.com/v1', apiKeyEnv: 'K' }, 'vision').providers.byok;
@@ -15,6 +15,15 @@ test('the person\'s own key is one provider in Pi\'s models.json, with the one m
assert.equal(model.reasoning, false);
});
+test('several models are each one of the provider\'s, and the chat\'s menu reads them as the model option', () => {
+ const p = modelsJson({ id: 'byok', api: 'openai-responses', baseUrl: 'https://api.openai.com/v1', apiKeyEnv: 'K' }, ['gpt-a', 'gpt-b']).providers.byok;
+ assert.deepEqual(p.models.map((m) => m.id), ['gpt-a', 'gpt-b']);
+ assert.deepEqual(modelOption(['gpt-a', 'gpt-b'], 'gpt-b'), {
+ id: 'model', name: 'Model', category: 'model', type: 'select', currentValue: 'gpt-b',
+ options: [{ value: 'gpt-a', name: 'gpt-a' }, { value: 'gpt-b', name: 'gpt-b' }],
+ });
+});
+
test('what Pi does reads in the chat as Codex\'s did: a command\'s kind and title, a file\'s path, the result\'s text and pictures', () => {
assert.deepEqual(toolCall('bash', { command: 'openfilm look' }), { kind: 'execute', title: 'openfilm look', rawInput: { command: 'openfilm look' } });
assert.deepEqual(toolCall('read', { path: 'film.html' }), { kind: 'read', title: 'Read film.html', rawInput: { path: 'film.html' } });
diff --git a/packages/openfilm/scripts/dev.mjs b/packages/openfilm/scripts/dev.mjs
index 941d318..1a8bcd0 100644
--- a/packages/openfilm/scripts/dev.mjs
+++ b/packages/openfilm/scripts/dev.mjs
@@ -7,7 +7,8 @@
* your browser (OPENFILM_NO_BROWSER=1: it only prints the address). Ctrl+C stops it all.
*
* It also writes .dev/bin/openfilm (and openfilm.cmd on Windows): this checkout's command on this Studio, for your own
- * agent to try your changes with.
+ * agent to try your changes with; and in .dev/projects (this Studio's library) an AGENTS.md and a CLAUDE.md saying so,
+ * so an agent opened in that folder uses it without being told.
*/
import { spawn } from 'node:child_process';
import { chmodSync, existsSync, mkdirSync, readFileSync, watch, writeFileSync } from 'node:fs';
@@ -39,6 +40,23 @@ if (process.platform === 'win32') {
writeFileSync(join(BIN, 'openfilm.cmd'), `@echo off\r\n${SHARED.map((k) => `set "${k}=${env[k]}"`).join('\r\n')}\r\nset "OPENFILM_RUN=%~f0"\r\n"${process.execPath}" "${CLI}" %*\r\n`);
}
+/* an agent opened in this Studio's library (Codex reads AGENTS.md, Claude Code CLAUDE.md) makes its films with this
+ checkout, on this Studio: the skill's `npx openfilm@latest` is the release, on the Studio of an installed OpenFilm */
+const command = process.platform === 'win32' ? join(BIN, 'openfilm.cmd') : sh;
+const AGENT_NOTE = `# Films made with an OpenFilm checkout
+
+This folder is the library of the Studio that \`pnpm dev\` runs from an OpenFilm checkout. Here OpenFilm is that
+checkout: wherever a skill or the manual says \`openfilm\` or \`npx openfilm\`, run
+
+ ${command}
+
+and never \`npx openfilm\` (the published version, on another Studio). Run it with no arguments for the manual. Make
+each film in a folder of its own here; it shows in that Studio.
+`;
+mkdirSync(env.OPENFILM_LIBRARY, { recursive: true });
+writeFileSync(join(env.OPENFILM_LIBRARY, 'AGENTS.md'), AGENT_NOTE);
+writeFileSync(join(env.OPENFILM_LIBRARY, 'CLAUDE.md'), AGENT_NOTE);
+
/* a small film to open: one page, drawn by frame(t) */
const SAMPLE = join(DEV, 'projects', 'Sample');
if (!existsSync(join(SAMPLE, 'film.html'))) {
@@ -109,8 +127,7 @@ for (const end = Date.now() + 30_000; Date.now() < end; await new Promise((r) =>
body: JSON.stringify({ path: SAMPLE, now: !quiet, fallback: 0 }),
}).catch((e) => ({ ok: false, json: async () => ({ error: e.message }) }));
const said = await res.json();
- const command = process.platform === 'win32' ? join(BIN, 'openfilm.cmd') : sh;
- console.log(res.ok ? `\nStudio (dev) ${said.url}\nhome ${env.OPENFILM_HOME}\nyour agent tell it to run ${command} instead of npx openfilm: this checkout, on this Studio\n` : `\ncould not open the sample: ${said.error}\n`);
+ console.log(res.ok ? `\nStudio (dev) ${said.url}\nhome ${env.OPENFILM_HOME}\nyour agent open it in ${env.OPENFILM_LIBRARY} (its AGENTS.md and CLAUDE.md say to run ${command}): this checkout, on this Studio\n` : `\ncould not open the sample: ${said.error}\n`);
break;
}
diff --git a/packages/openfilm/studio/ui/src/components/MenuSelect.tsx b/packages/openfilm/studio/ui/src/components/MenuSelect.tsx
new file mode 100644
index 0000000..cc40273
--- /dev/null
+++ b/packages/openfilm/studio/ui/src/components/MenuSelect.tsx
@@ -0,0 +1,124 @@
+/**
+ * A field that opens a menu of choices, drawn as Studio's own menus are (a card in the panel's colors, the chosen one
+ * checked), in place of the browser's own list: that one is drawn by the system, light in a dark Studio, and with
+ * the field's text color it read as if every choice were disabled. Choices may come in groups, each under a small
+ * heading. The arrow keys move through them, Enter picks, Esc closes.
+ */
+import React from 'react';
+import { Check, ChevronDown } from 'lucide-react';
+import { Popover } from './Popover';
+
+export type MenuChoice = { value: string; label: string };
+export type MenuGroup = { label?: string; choices: MenuChoice[] };
+
+export function MenuSelect({
+ label, value, groups, onPick, disabled = false, className = '',
+}: {
+ /** what it chooses, for screen readers (the field shows the choice) */
+ label: string;
+ value: string;
+ groups: MenuGroup[];
+ onPick: (value: string) => void;
+ disabled?: boolean;
+ className?: string;
+}) {
+ const [open, setOpen] = React.useState(false);
+ const [width, setWidth] = React.useState(0);
+ const [active, setActive] = React.useState(-1);
+ const triggerRef = React.useRef<HTMLButtonElement | null>(null);
+ const listRef = React.useRef<HTMLDivElement | null>(null);
+ const all = React.useMemo(() => groups.flatMap((g) => g.choices), [groups]);
+ const current = all.find((c) => c.value === value);
+
+ /* opened: as wide as the field, the chosen one in view and lit for the keys */
+ React.useLayoutEffect(() => {
+ if (!open) return;
+ setWidth(triggerRef.current?.getBoundingClientRect().width ?? 0);
+ setActive(Math.max(0, all.findIndex((c) => c.value === value)));
+ }, [open]); // eslint-disable-line react-hooks/exhaustive-deps
+ React.useEffect(() => {
+ if (!open || active < 0) return;
+ listRef.current?.querySelector(`[data-index="${active}"]`)?.scrollIntoView({ block: 'nearest' });
+ }, [open, active]);
+
+ const pick = (choice: MenuChoice) => {
+ setOpen(false);
+ triggerRef.current?.focus();
+ if (choice.value !== value) onPick(choice.value);
+ };
+ const onKeyDown = (e: React.KeyboardEvent) => {
+ if (disabled) return;
+ if (!open) {
+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp' || e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setOpen(true); }
+ return;
+ }
+ if (e.key === 'ArrowDown') { e.preventDefault(); setActive((i) => Math.min(all.length - 1, i + 1)); }
+ else if (e.key === 'ArrowUp') { e.preventDefault(); setActive((i) => Math.max(0, i - 1)); }
+ else if (e.key === 'Home') { e.preventDefault(); setActive(0); }
+ else if (e.key === 'End') { e.preventDefault(); setActive(all.length - 1); }
+ else if ((e.key === 'Enter' || e.key === ' ') && all[active]) { e.preventDefault(); pick(all[active]); }
+ else if (e.key === 'Tab') setOpen(false);
+ };
+
+ let index = -1;
+ return (
+ <Popover open={open && !disabled} onOpenChange={(next) => setOpen(next && !disabled)} placement="auto" block trigger={(
+ <button
+ ref={triggerRef}
+ type="button"
+ aria-label={label}
+ aria-haspopup="listbox"
+ aria-expanded={open}
+ disabled={disabled}
+ /* the popover keeps focus where it was on a press: the keys need it here */
+ onClick={(e) => e.currentTarget.focus()}
+ onKeyDown={onKeyDown}
+ className={`flex h-7 min-w-0 flex-1 items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--fill-tsp)] pl-2 pr-1.5 text-left text-[11px] text-[var(--text)] outline-none transition hover:border-[var(--text-faint)] focus-visible:border-[var(--accent)] disabled:opacity-50 ${open ? 'border-[var(--accent)]' : ''} ${className}`}
+ >
+ <span className="min-w-0 flex-1 truncate">{current?.label ?? value}</span>
+ <ChevronDown size={12} aria-hidden className={`shrink-0 text-[var(--text-faint)] transition-transform ${open ? 'rotate-180' : ''}`} />
+ </button>
+ )}>
+ <div
+ ref={listRef}
+ data-film-inspector=""
+ role="listbox"
+ aria-label={label}
+ onKeyDown={onKeyDown}
+ className="overflow-y-auto rounded-[8px] border border-[var(--border)] bg-[var(--panel)] p-1 shadow-[var(--shadow-lg)]"
+ style={{ width: Math.max(width, 160), maxHeight: 'min(320px, var(--popover-max-h, 320px))' }}
+ >
+ {groups.map((group, g) => (
+ <div key={group.label ?? g} role="group" aria-label={group.label}>
+ {group.label ? (
+ <div className={`px-2 pb-1 text-[10.5px] font-medium text-[var(--text-faint)] ${g > 0 ? 'mt-1 border-t border-[var(--border)] pt-2' : 'pt-1'}`}>
+ {group.label}
+ </div>
+ ) : g > 0 ? <div className="mx-1 my-1 h-px bg-[var(--border)]" /> : null}
+ {group.choices.map((choice) => {
+ index += 1;
+ const i = index;
+ const chosen = choice.value === value;
+ return (
+ <button
+ key={choice.value}
+ type="button"
+ role="option"
+ aria-selected={chosen}
+ data-index={i}
+ onMouseEnter={() => setActive(i)}
+ onMouseDown={(e) => e.preventDefault()}
+ onClick={() => pick(choice)}
+ className={`flex h-7 w-full items-center gap-2 rounded-[5px] px-2 text-left text-[11.5px] text-[var(--text)] ${i === active ? 'bg-[var(--bg-hover)]' : ''}`}
+ >
+ <span className="min-w-0 flex-1 truncate">{choice.label}</span>
+ {chosen ? <Check size={12} aria-hidden className="shrink-0 text-[var(--accent)]" /> : null}
+ </button>
+ );
+ })}
+ </div>
+ ))}
+ </div>
+ </Popover>
+ );
+}
diff --git a/packages/openfilm/studio/ui/src/components/Popover.tsx b/packages/openfilm/studio/ui/src/components/Popover.tsx
index 5279a96..aee28f6 100644
--- a/packages/openfilm/studio/ui/src/components/Popover.tsx
+++ b/packages/openfilm/studio/ui/src/components/Popover.tsx
@@ -22,6 +22,7 @@ export function Popover({
placement = 'bottom',
align = 'start',
layer = 10000,
+ block = false,
}: {
open: boolean;
onOpenChange: (v: boolean) => void;
@@ -32,6 +33,8 @@ export function Popover({
align?: 'start' | 'end';
/** its z-index: above a dialog it opens in */
layer?: number;
+ /** the trigger takes the width it is given (a field), not only its own */
+ block?: boolean;
}) {
const ref = React.useRef<HTMLDivElement | null>(null);
const panelRef = React.useRef<HTMLDivElement | null>(null);
@@ -146,8 +149,8 @@ export function Popover({
) : null;
return (
- <div ref={ref} className="inline-flex w-fit">
- <div className="inline-flex w-fit" onMouseDown={keepFocus} onClick={() => onOpenChange(!open)}>
+ <div ref={ref} className={block ? 'flex min-w-0 flex-1' : 'inline-flex w-fit'}>
+ <div className={block ? 'flex min-w-0 flex-1' : 'inline-flex w-fit'} onMouseDown={keepFocus} onClick={() => onOpenChange(!open)}>
{trigger}
</div>
{typeof document !== 'undefined' && panel ? createPortal(panel, document.body) : null}
diff --git a/packages/openfilm/studio/ui/src/components/SubtitleInspector.tsx b/packages/openfilm/studio/ui/src/components/SubtitleInspector.tsx
index 5012a42..871f40b 100644
--- a/packages/openfilm/studio/ui/src/components/SubtitleInspector.tsx
+++ b/packages/openfilm/studio/ui/src/components/SubtitleInspector.tsx
@@ -9,6 +9,7 @@ import {
} from '@/lib/subtitles';
import { SUBTITLE_FONT_SYSTEM, useSubtitleFonts, type SubtitleFontOption } from '@/lib/use-subtitle-font';
import { Tooltip } from './Tooltip';
+import { MenuSelect } from './MenuSelect';
import { InspectorPanel } from './InspectorPanel';
import { SubtitleRowToggle } from './SubtitleRow';
import styles from './SubtitleInspector.module.css';
@@ -548,21 +549,16 @@ function SubtitleLanguage({ style, set, translate, sourceLanguage }: {
return (
<StyleGroup label={t('timeline.subtitleLanguageGroup')}>
<div className="flex min-h-8 items-center gap-2 py-1">
- <select
+ <MenuSelect
+ label={t('timeline.subtitleLanguageGroup')}
value={chosen ?? ''}
- aria-label={t('timeline.subtitleLanguageGroup')}
disabled={state.busy}
- onChange={(e) => pick(e.target.value)}
- className="h-7 min-w-0 flex-1 rounded-md border px-2 text-[11px]"
- style={{ background: 'var(--fill-tsp)', borderColor: 'var(--border)', color: 'var(--text)' }}
- >
- <option value="">
- {sourceLanguage ? t('timeline.subtitleLanguageOriginalNamed').replace('{lang}', nameOf(sourceLanguage)) : t('timeline.subtitleLanguageOriginal')}
- </option>
- <optgroup label={t('timeline.subtitleLanguageTranslate')}>
- {targets.map((item) => <option key={item.code} value={item.code}>{item.native}</option>)}
- </optgroup>
- </select>
+ onPick={pick}
+ groups={[
+ { choices: [{ value: '', label: sourceLanguage ? t('timeline.subtitleLanguageOriginalNamed').replace('{lang}', nameOf(sourceLanguage)) : t('timeline.subtitleLanguageOriginal') }] },
+ { label: t('timeline.subtitleLanguageTranslate'), choices: targets.map((item) => ({ value: item.code, label: item.native })) },
+ ]}
+ />
</div>
{state.busy ? (
<p className="flex items-center gap-1.5 pb-1 text-[11px]" role="status" style={{ color: 'var(--text-muted)' }}>
@@ -768,24 +764,15 @@ function StyleFamily({
<span className="w-[58px] shrink-0 text-[11px]" style={{ color: 'var(--text-muted)' }}>
{label}
</span>
- <select
+ <MenuSelect
+ label={label}
value={value}
- aria-label={label}
- onChange={(e) => onPick(e.target.value)}
- className="h-7 min-w-0 flex-1 rounded-md border px-2 text-[11px]"
- style={{
- background: 'var(--fill-tsp)',
- borderColor: 'var(--border)',
- color: 'var(--text)',
- }}
- >
- <option value={SUBTITLE_FONT_SYSTEM}>{t('timeline.subtitleFamilyDefault')}</option>
- {groups.map(([locale, list]) => (
- <optgroup key={locale} label={locale}>
- {list.map((f) => <option key={f.family} value={f.family}>{f.family}</option>)}
- </optgroup>
- ))}
- </select>
+ onPick={onPick}
+ groups={[
+ { choices: [{ value: SUBTITLE_FONT_SYSTEM, label: t('timeline.subtitleFamilyDefault') }] },
+ ...groups.map(([locale, list]) => ({ label: locale, choices: list.map((f) => ({ value: f.family, label: f.family })) })),
+ ]}
+ />
</div>
);
}
diff --git a/packages/openfilm/studio/ui/src/components/settings/AgentsSection.tsx b/packages/openfilm/studio/ui/src/components/settings/AgentsSection.tsx
index 2e34327..fa5d1be 100644
--- a/packages/openfilm/studio/ui/src/components/settings/AgentsSection.tsx
+++ b/packages/openfilm/studio/ui/src/components/settings/AgentsSection.tsx
@@ -110,7 +110,7 @@ export function AgentsSection() {
{t('settings.agents.recommended')}
</span>
) : null}
- {agent.status === 'ready' && chosen ? <SettingsStatus>{ownKey ? `${agent.byok!.model} · •••• ${agent.byok!.last4}` : t('settings.agents.ready')}</SettingsStatus> : null}
+ {agent.status === 'ready' && chosen ? <SettingsStatus>{ownKey ? `${byokModels(agent).join(', ')} · •••• ${agent.byok!.last4}` : t('settings.agents.ready')}</SettingsStatus> : null}
</>
)}
description={agent.status === 'ready' ? null : statusLine(agent)}
@@ -162,14 +162,23 @@ const FORMATS: ReadonlyArray<{ value: HostByokFormat; label: string; address: st
{ value: 'anthropic', label: 'Anthropic Messages', address: 'https://api.anthropic.com' },
];
-/** The person's own key: the API format, its address (the official one, or any service that speaks it), the model and the key. Checked before it is kept. */
+/** The own key's models, the first one the chat begins with. */
+const byokModels = (agent: HostAgent) => (agent.byok?.models?.length ? agent.byok.models : [agent.byok?.model ?? ''].filter(Boolean));
+
+/** Model names typed in one field, separated by commas or new lines: trimmed, each once. */
+const modelNames = (text: string) => [...new Set(text.split(/[,\n]/).map((m) => m.trim()).filter(Boolean))];
+
+/**
+ * The person's own key: the API format, its address (the official one, or any service that speaks it), the models (the
+ * chat's menu switches between them) and the key. Checked before it is kept.
+ */
function ByokForm({ agent, onDone }: { agent: HostAgent; onDone: () => void }) {
const t = useT();
const host = studioHost?.agents;
const [format, setFormat] = React.useState<HostByokFormat>(agent.byok?.format ?? 'responses');
const official = FORMATS.find((f) => f.value === format)!;
const [baseUrl, setBaseUrl] = React.useState(agent.byok?.baseUrl ?? official.address);
- const [model, setModel] = React.useState(agent.byok?.model ?? '');
+ const [models, setModels] = React.useState(byokModels(agent).join(', '));
const [key, setKey] = React.useState('');
const [state, setState] = React.useState<{ busy: boolean; error: string | null }>({ busy: false, error: null });
/* another format: its official address, unless the person typed one of their own */
@@ -180,11 +189,11 @@ function ByokForm({ agent, onDone }: { agent: HostAgent; onDone: () => void }) {
const save = () => {
if (!host) return;
setState({ busy: true, error: null });
- void host.configureByok({ format, baseUrl, model, ...(key ? { key } : {}) })
+ void host.configureByok({ format, baseUrl, models: modelNames(models), ...(key ? { key } : {}) })
.then((r) => { if (r.ok) { setKey(''); setState({ busy: false, error: null }); onDone(); } else setState({ busy: false, error: r.error ?? t('settings.agents.failed') }); })
.catch((e: unknown) => setState({ busy: false, error: e instanceof Error ? e.message : String(e) }));
};
- const ready = model.trim() && baseUrl.trim() && (key.trim() || agent.byok);
+ const ready = modelNames(models).length > 0 && baseUrl.trim() && (key.trim() || agent.byok);
const label = (text: string) => <span className="w-[92px] shrink-0 text-[13px] text-[var(--text-muted)]">{text}</span>;
return (
<SettingsInset>
@@ -200,7 +209,7 @@ function ByokForm({ agent, onDone }: { agent: HostAgent; onDone: () => void }) {
</div>
<div className="flex items-center gap-2">
{label(t('settings.agents.model'))}
- <SettingsField value={model} onChange={(e) => setModel(e.target.value)} placeholder={t('settings.agents.modelPlaceholder')} aria-label={t('settings.agents.model')} spellCheck={false} />
+ <SettingsField value={models} onChange={(e) => setModels(e.target.value)} placeholder={t('settings.agents.modelPlaceholder')} aria-label={t('settings.agents.model')} spellCheck={false} />
</div>
<div className="flex items-center gap-2">
{label(t('settings.agents.key'))}
diff --git a/packages/openfilm/studio/ui/src/i18n/en.ts b/packages/openfilm/studio/ui/src/i18n/en.ts
index bc5ed84..392bed1 100644
--- a/packages/openfilm/studio/ui/src/i18n/en.ts
+++ b/packages/openfilm/studio/ui/src/i18n/en.ts
@@ -1309,12 +1309,12 @@ export const en = {
failed: 'That did not work. Try again.',
format: 'API format',
address: 'Address',
- model: 'Model',
- modelPlaceholder: 'Model, as the service names it',
+ model: 'Models',
+ modelPlaceholder: 'As the service names them, separated by commas',
key: 'API key',
keyPlaceholder: 'Paste your API key',
keyKept: 'Key ending in {last4} (leave empty to keep it)',
- byokNote: 'The model has to read pictures: the agent looks at its own frames. Your key stays on this computer and goes only to that service.',
+ byokNote: 'Each model has to read pictures: the agent looks at its own frames. Your key stays on this computer and goes only to that service.',
save: 'Check and save',
checkingKey: 'Checking…',
cancel: 'Cancel',
diff --git a/packages/openfilm/studio/ui/src/i18n/es.ts b/packages/openfilm/studio/ui/src/i18n/es.ts
index f277ddf..fec42a4 100644
--- a/packages/openfilm/studio/ui/src/i18n/es.ts
+++ b/packages/openfilm/studio/ui/src/i18n/es.ts
@@ -1308,12 +1308,12 @@ export const es: Words = {
failed: 'No ha funcionado. Inténtalo de nuevo.',
format: 'Formato de API',
address: 'Dirección',
- model: 'Modelo',
- modelPlaceholder: 'El modelo, tal como lo llama el servicio',
+ model: 'Modelos',
+ modelPlaceholder: 'Como los llama el servicio, separados por comas',
key: 'Clave de API',
keyPlaceholder: 'Pega tu clave de API',
keyKept: 'Clave terminada en {last4} (déjalo vacío para conservarla)',
- byokNote: 'El modelo tiene que poder leer imágenes: el agente mira sus propios fotogramas. Tu clave se queda en este equipo y solo se envía a ese servicio.',
+ byokNote: 'Cada modelo tiene que poder leer imágenes: el agente mira sus propios fotogramas. Tu clave se queda en este equipo y solo se envía a ese servicio.',
save: 'Comprobar y guardar',
checkingKey: 'Comprobando…',
cancel: 'Cancelar',
diff --git a/packages/openfilm/studio/ui/src/i18n/ja.ts b/packages/openfilm/studio/ui/src/i18n/ja.ts
index 04703b1..4b977a8 100644
--- a/packages/openfilm/studio/ui/src/i18n/ja.ts
+++ b/packages/openfilm/studio/ui/src/i18n/ja.ts
@@ -1309,11 +1309,11 @@ export const ja: Words = {
format: 'API 形式',
address: 'アドレス',
model: 'モデル',
- modelPlaceholder: 'サービスでのモデル名',
+ modelPlaceholder: 'サービスでのモデル名。複数ある場合はカンマで区切る',
key: 'API キー',
keyPlaceholder: 'API キーを貼り付け',
keyKept: '末尾が {last4} のキー(空欄のままにすると現在のキーを使います)',
- byokNote: 'モデルは画像を読める必要があります。エージェントは自分で作ったフレームを確認するためです。キーはこのコンピューターに保存され、そのサービス以外には送信されません。',
+ byokNote: 'どのモデルも画像を読める必要があります。エージェントは自分で作ったフレームを確認するためです。キーはこのコンピューターに保存され、そのサービス以外には送信されません。',
save: '確認して保存',
checkingKey: '確認中…',
cancel: 'キャンセル',
diff --git a/packages/openfilm/studio/ui/src/i18n/ko.ts b/packages/openfilm/studio/ui/src/i18n/ko.ts
index 8f25813..557208a 100644
--- a/packages/openfilm/studio/ui/src/i18n/ko.ts
+++ b/packages/openfilm/studio/ui/src/i18n/ko.ts
@@ -1308,11 +1308,11 @@ export const ko: Words = {
format: 'API 형식',
address: '주소',
model: '모델',
- modelPlaceholder: '서비스에서 쓰는 모델 이름',
+ modelPlaceholder: '서비스에서 쓰는 모델 이름, 여러 개는 쉼표로 구분',
key: 'API 키',
keyPlaceholder: 'API 키 붙여넣기',
keyKept: '{last4}(으)로 끝나는 키(유지하려면 비워 두세요)',
- byokNote: '모델이 이미지를 읽을 수 있어야 합니다. 에이전트가 직접 만든 프레임을 확인하기 때문입니다. 키는 이 컴퓨터에만 저장되며 해당 서비스로만 전송됩니다.',
+ byokNote: '모든 모델이 이미지를 읽을 수 있어야 합니다. 에이전트가 직접 만든 프레임을 확인하기 때문입니다. 키는 이 컴퓨터에만 저장되며 해당 서비스로만 전송됩니다.',
save: '확인 후 저장',
checkingKey: '확인 중…',
cancel: '취소',
diff --git a/packages/openfilm/studio/ui/src/i18n/zh-CN.ts b/packages/openfilm/studio/ui/src/i18n/zh-CN.ts
index 2bd7db4..43f3f52 100644
--- a/packages/openfilm/studio/ui/src/i18n/zh-CN.ts
+++ b/packages/openfilm/studio/ui/src/i18n/zh-CN.ts
@@ -1310,11 +1310,11 @@ export const zhCN: Words = {
format: 'API 格式',
address: '地址',
model: '模型',
- modelPlaceholder: '模型名称,与服务中的写法一致',
+ modelPlaceholder: '与服务中的写法一致,多个用逗号分隔',
key: 'API 密钥',
keyPlaceholder: '粘贴你的 API 密钥',
keyKept: '尾号为 {last4} 的密钥(留空则保留)',
- byokNote: '模型需要能看图:智能体会查看自己生成的画面。你的密钥只保存在这台电脑上,且只会发送给该服务。',
+ byokNote: '每个模型都需要能看图:智能体会查看自己生成的画面。你的密钥只保存在这台电脑上,且只会发送给该服务。',
save: '检查并保存',
checkingKey: '正在检查…',
cancel: '取消',
diff --git a/packages/openfilm/studio/ui/src/lib/host.ts b/packages/openfilm/studio/ui/src/lib/host.ts
index 6b15c9c..dbe5c18 100644
--- a/packages/openfilm/studio/ui/src/lib/host.ts
+++ b/packages/openfilm/studio/ui/src/lib/host.ts
@@ -68,7 +68,7 @@ export interface StudioHost {
connect: (id: HostAgentId) => Promise<{ ok: boolean; error?: string }>;
disconnect: (id: HostAgentId) => Promise<unknown>;
setShown: (id: HostAgentId, shown: boolean) => Promise<unknown>;
- configureByok: (config: { format: HostByokFormat; baseUrl?: string; model: string; key?: string }) => Promise<{ ok: boolean; error?: string; code?: string }>;
+ configureByok: (config: { format: HostByokFormat; baseUrl?: string; models: string[]; key?: string }) => Promise<{ ok: boolean; error?: string; code?: string }>;
onChange: (listener: (agents: HostAgent[]) => void) => () => void;
};
/**
@@ -116,7 +116,7 @@ export interface HostAgent {
/** What installing it takes, when `install` is not a download: 'code-tab', Claude Code comes with the Claude app (its Code tab). */
setupRequired?: string | null;
error?: string;
- byok?: { format: HostByokFormat; baseUrl: string; model: string; last4: string };
+ byok?: { format: HostByokFormat; baseUrl: string; model: string; models?: string[]; last4: string };
}
/** A box on the picture, in the film's stage pixels (the stage is `stage.w` × `stage.h`, film.html's stage). */