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: each own model takes its context length (#88)

riverisbuilding893641de9e90
diff --git a/.changeset/own-model-context.md b/.changeset/own-model-context.md
new file mode 100644
index 0000000..99805f8
--- /dev/null
+++ b/.changeset/own-model-context.md
@@ -0,0 +1,6 @@
+---
+'@openfilm/desktop': patch
+'openfilm': patch
+---
+
+Desktop: each of your own models takes its context length in Settings, so the agent compacts before the model's own limit instead of at 128K.
diff --git a/apps/desktop/src/agent-roster.mjs b/apps/desktop/src/agent-roster.mjs
index e465cd1..3682c87 100644
--- a/apps/desktop/src/agent-roster.mjs
+++ b/apps/desktop/src/agent-roster.mjs
@@ -11,10 +11,11 @@
* · byok — the app's own agent (Pi, pi-agent.mjs) on the person's own models, each set up on its own: the name the
* chat's menu shows, its service (an address 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), its own key, the model asked for there, and the reasoning efforts the person
- * says it takes and the one it starts on (`auto` alone, sending no reasoning setting, when they said nothing). 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 one up sends it one small request with a picture, and a model that cannot take it is refused.
+ * (…/v1/messages); Pi speaks each), its own key, the model asked for there, the reasoning efforts the person
+ * says it takes and the one it starts on (`auto` alone, sending no reasoning setting, when they said nothing), and
+ * its context length, when they gave one (128K when not). 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 one up sends it one small
+ * request with a picture, and a model that cannot take it is refused.
*
* One of the person's own agents not found where it is looked for can be pointed at (`locate`): the program they choose
* is tried (it has to answer `--version`) and used from then on, until they go back to finding it (`useAutomatic`).
@@ -32,7 +33,7 @@
import { randomBytes } from 'node:crypto';
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
-import { PI_APIS, modelEffort } from './pi-config.mjs';
+import { PI_APIS, contextLength, modelEffort } from './pi-config.mjs';
/** The person's own agents, as agents.mjs AGENTS has them. */
export const OWN_AGENT_IDS = Object.freeze(['codex', 'claude', 'copilot', 'cursor', 'opencode', 'codebuddy', 'qwen', 'kimi', 'minimax']);
@@ -84,11 +85,17 @@ export function readChoices(dataDir) {
};
}
+/** A model's context length, as kept: there only when the person gave one that holds. */
+const ownContext = (/** @type {unknown} */ value) => {
+ const context = contextLength(value);
+ return context ? { context } : {};
+};
+
/**
- * The person's own models as kept: `[{ id, name, format, baseUrl, model, levels, effort, last4 }]`, the first the one a
- * conversation starts on. One without a known format, an address or a model is left out. Kept before each model was set
- * up on its own (one service, its models by name, `efforts` by name): each of those models on that service (`m1`, `m2`…),
- * on the key kept then.
+ * The person's own models as kept: `[{ id, name, format, baseUrl, model, levels, effort, context?, last4 }]`, the first
+ * the one a conversation starts on. One without a known format, an address or a model is left out; a context length
+ * that does not hold is dropped. Kept before each model was set up on its own (one service, its models by name,
+ * `efforts` by name): each of those models on that service (`m1`, `m2`…), on the key kept then.
*/
export function ownModels(raw) {
if (!raw || typeof raw !== 'object') return [];
@@ -107,7 +114,7 @@ export function ownModels(raw) {
const id = String(m?.id ?? '');
if (!model || !baseUrl || !Object.hasOwn(BYOK_FORMATS, m?.format) || !/^[a-z0-9]+$/.test(id) || ids.has(id)) return [];
ids.add(id);
- return [{ id, name: String(m.name ?? '').trim() || model, format: m.format, baseUrl, model, ...modelEffort(m.levels, m.effort), last4: String(m.last4 ?? '') }];
+ return [{ id, name: String(m.name ?? '').trim() || model, format: m.format, baseUrl, model, ...modelEffort(m.levels, m.effort), ...ownContext(m.context), last4: String(m.last4 ?? '') }];
});
}
@@ -348,10 +355,11 @@ export function createRoster(deps) {
/**
* One of the person's own models, set up or changed (`id` names one already set up): its name (the model, when
- * none), its API format, the service's address, the model asked for there, its key, and its efforts (pi-config.mjs
- * EFFORTS: the ones it takes and the one it starts on). A key left empty keeps the one it has, or takes the key of
- * another model on the same address. Checked first (the key is taken, the model reads pictures).
- * @param {{ id?: string, name?: string, format: string, baseUrl?: string, model: string, key?: string, levels?: string[], effort?: string }} config
+ * none), its API format, the service's address, the model asked for there, its key, its efforts (pi-config.mjs
+ * EFFORTS: the ones it takes and the one it starts on) and its context length (none: 128K). A key left empty keeps
+ * the one it has, or takes the key of another model on the same address. Checked first (the key is taken, the
+ * model reads pictures).
+ * @param {{ id?: string, name?: string, format: string, baseUrl?: string, model: string, key?: string, levels?: string[], effort?: string, context?: number }} config
* @returns {Promise<{ ok: true, id: string } | { ok: false, error: string, code?: string }>}
*/
async saveOwnModel(config) {
@@ -371,7 +379,7 @@ export function createRoster(deps) {
if (!probe.ok) return probe;
let id = before?.id;
while (!id || models.some((m) => m.id === id && m !== before)) id = randomBytes(4).toString('hex');
- const entry = { id, name: String(config.name ?? '').trim() || model, format: config.format, baseUrl, model, ...modelEffort(config.levels, config.effort), last4: key.slice(-4) };
+ const entry = { id, name: String(config.name ?? '').trim() || model, format: config.format, baseUrl, model, ...modelEffort(config.levels, config.effort), ...ownContext(config.context), last4: key.slice(-4) };
writeKeys({ ...byokKeys(), [id]: key });
delete live.errors.byok;
save({
@@ -408,7 +416,7 @@ export function createRoster(deps) {
const own = models.map((m, i) => {
const keyEnv = `OPENFILM_BYOK_KEY_${i + 1}`;
env[keyEnv] = keyOf(m.id);
- return { id: m.id, name: m.name, api: PI_APIS[m.format], baseUrl: m.baseUrl, keyEnv, model: m.model, levels: [...m.levels], effort: m.effort };
+ return { id: m.id, name: m.name, api: PI_APIS[m.format], baseUrl: m.baseUrl, keyEnv, model: m.model, levels: [...m.levels], effort: m.effort, ...ownContext(m.context) };
});
return { home: join(dataDir, 'agents', 'byok', 'pi'), models: own, model: own[0].id, env };
},
diff --git a/apps/desktop/src/agent-roster.test.mjs b/apps/desktop/src/agent-roster.test.mjs
index 05fe1b8..a676643 100644
--- a/apps/desktop/src/agent-roster.test.mjs
+++ b/apps/desktop/src/agent-roster.test.mjs
@@ -94,6 +94,32 @@ test('a model changed keeps its place, its id and, given none, its key; one remo
assert.equal(closed.filter((id) => id === 'byok').length, 5, 'its sessions closed on each change: they run on the models set up');
});
+test("a model's context length is kept when it holds (32K to 10M tokens), and dropped quietly when not: 128K then", async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'of-roster-'));
+ const r = roster(dir, async () => new Response('{}', { status: 200 }));
+ const big = await r.saveOwnModel({ format: 'responses', model: 'big', key: 'sk-a', context: 1_000_000 });
+ const odd = await r.saveOwnModel({ format: 'responses', model: 'odd', context: 1_000 });
+ const plain = await r.saveOwnModel({ format: 'responses', model: 'plain' });
+ assert.deepEqual(readChoices(dir).byok.models.map((m) => [m.model, m.context]), [['big', 1_000_000], ['odd', undefined], ['plain', undefined]]);
+ assert.equal(Object.hasOwn(readChoices(dir).byok.models[1], 'context'), false, 'none kept, not a null');
+ assert.deepEqual(r.harness('byok').models.map((m) => m.context), [1_000_000, undefined, undefined], 'the agent runs with it');
+ assert.equal(r.list().find((a) => a.id === 'byok').byok.models[0].context, 1_000_000, 'Settings shows it');
+ /* changed without one: back to none */
+ await r.saveOwnModel({ id: big.id, format: 'responses', model: 'big' });
+ assert.equal(readChoices(dir).byok.models[0].context, undefined);
+ assert.ok(odd.ok && plain.ok);
+
+ /* as read: a whole number in bounds is kept, anything else dropped */
+ const kept = (context) => {
+ writeFileSync(join(dir, 'agents.json'), JSON.stringify({ byok: { models: [{ id: 'a', format: 'chat', baseUrl: 'https://x.test/v1', model: 'm', context }] } }));
+ return readChoices(dir).byok.models[0].context;
+ };
+ assert.equal(kept(32_000), 32_000);
+ assert.equal(kept(10_000_000), 10_000_000);
+ assert.equal(kept(200_000), 200_000);
+ for (const bad of [31_999, 4_000, 10_000_001, 128_000.5, '200000', -1, 0, null, true, {}]) assert.equal(kept(bad), undefined, `${JSON.stringify(bad)} dropped`);
+});
+
test('one service with several models, kept before each model was set up on its own, is those models on it, on its key', async () => {
const dir = mkdtempSync(join(tmpdir(), 'of-roster-'));
writeFileSync(join(dir, 'agents.json'), JSON.stringify({ byok: { format: 'chat', baseUrl: 'https://api.deepseek.com/v1', model: 'a', models: ['a', 'b'],
diff --git a/apps/desktop/src/pi-config.mjs b/apps/desktop/src/pi-config.mjs
index b4dd6e0..ccfeef2 100644
--- a/apps/desktop/src/pi-config.mjs
+++ b/apps/desktop/src/pi-config.mjs
@@ -2,8 +2,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 person's own models, each set up on its own (agent-roster.mjs): its name, its service (an address on one of three
- * APIs, and its own key), the model asked for there and its reasoning efforts. Each is a provider of its own in Pi's
- * `models.json`, so the chat's menu switches between them (`modelOption`), one service to another.
+ * APIs, and its own key), the model asked for there, its reasoning efforts and its context length. Each is a provider
+ * of its own in Pi's `models.json`, so the chat's menu switches between them (`modelOption`), one service to another.
*
* Reads no Electron module, so `node --test` can use it.
*/
@@ -36,10 +36,24 @@ export function modelEffort(/** @type {unknown} */ levels, /** @type {unknown} *
return { levels: offered, effort: offered.includes(String(effort)) ? String(effort) : offered[0] };
}
+/** A context length for a model the person gave none: 128K. */
+const CONTEXT = 128_000;
+/** The most a model is asked to write in one answer: a quarter of 128K, so a long context does not ask for more. */
+const MAX_OUTPUT = 32_000;
+
+/**
+ * A model's context length as kept: a whole number of tokens from 32K to 10M, as the person gave it in Settings (the
+ * service documents it; OpenFilm cannot know it). Null for none or anything else: the model gets 128K.
+ */
+export function contextLength(/** @type {unknown} */ value) {
+ return typeof value === 'number' && Number.isInteger(value) && value >= 32_000 && value <= 10_000_000 ? value : null;
+}
+
/**
* One of the person's own models as the agent runs it: `id` (the app's, never shown), `name` (the menu's), Pi's `api`,
- * the service's `baseUrl`, the variable its key is in (`keyEnv`), the `model` asked for there and its efforts.
- * @typedef {{ id: string, name: string, api: string, baseUrl: string, keyEnv: string, model: string, levels: string[], effort: string }} OwnModel
+ * the service's `baseUrl`, the variable its key is in (`keyEnv`), the `model` asked for there, its efforts and its
+ * `context` length in tokens (128K when none).
+ * @typedef {{ id: string, name: string, api: string, baseUrl: string, keyEnv: string, model: string, levels: string[], effort: string, context?: number }} OwnModel
*/
/** Pi's provider for one of the person's own models: each its own service. */
@@ -51,9 +65,6 @@ export const THINKING = (/** @type {string} */ id) => `${id}-thinking`;
/* what a level is called on the wire: Pi's own names, but "none" for off on OpenAI's APIs */
const wire = (/** @type {string} */ api, /** @type {string} */ level) => (level === 'off' && api !== 'anthropic-messages' ? 'none' : level);
-/** A context length for a model the service does not describe. */
-const CONTEXT = 128_000;
-
/**
* Pi's `models.json` for the person's own models: each its own provider (its address and key), twice when it offers
* levels: as itself, told not to reason (`auto`: no reasoning setting is sent), and as THINKING(provider) told exactly
@@ -61,16 +72,19 @@ const CONTEXT = 128_000;
* @param {OwnModel[]} models
*/
export function modelsJson(models) {
- const entry = (/** @type {OwnModel} */ m, /** @type {string[] | null} */ levels) => ({
- id: m.model,
- name: m.name,
- input: ['text', 'image'],
- contextWindow: CONTEXT,
- maxTokens: Math.floor(CONTEXT / 4),
- reasoning: Boolean(levels),
- ...(levels ? { thinkingLevelMap: Object.fromEntries(EFFORTS.slice(1).map((l) => [l, levels.includes(l) ? wire(m.api, l) : null])) } : {}),
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
- });
+ const entry = (/** @type {OwnModel} */ m, /** @type {string[] | null} */ levels) => {
+ const context = contextLength(m.context) ?? CONTEXT;
+ return {
+ id: m.model,
+ name: m.name,
+ input: ['text', 'image'],
+ contextWindow: context,
+ maxTokens: Math.min(Math.floor(context / 4), MAX_OUTPUT),
+ reasoning: Boolean(levels),
+ ...(levels ? { thinkingLevelMap: Object.fromEntries(EFFORTS.slice(1).map((l) => [l, levels.includes(l) ? wire(m.api, l) : null])) } : {}),
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
+ };
+ };
/** @type {Record<string, any>} */
const providers = {};
for (const m of models) {
diff --git a/apps/desktop/src/pi-config.test.mjs b/apps/desktop/src/pi-config.test.mjs
index d3a6de6..bf410bb 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 { THINKING, contextUsed, effortOption, modelEffort, modelOption, modelsJson, outOfBalance, providerOf, stopReason, toolCall, toolContent } from './pi-config.mjs';
+import { THINKING, contextLength, contextUsed, effortOption, modelEffort, modelOption, modelsJson, outOfBalance, providerOf, stopReason, toolCall, toolContent } from './pi-config.mjs';
/** One of the person's own models, as the roster's harness gives it. */
const own = (id, over = {}) => ({ id, name: id.toUpperCase(), api: 'openai-completions', baseUrl: `https://${id}.test/v1`, keyEnv: `K_${id}`, model: `${id}-model`, levels: ['auto'], effort: 'auto', ...over });
@@ -22,6 +22,18 @@ test("each of the person's models is a provider of its own in Pi's models.json:
assert.equal(model.reasoning, false);
});
+test("a model's context length is its window in Pi, and a quarter of it its answers, never more than 32K", () => {
+ const model = (over) => modelsJson([own('a', over)]).providers[providerOf('a')].models[0];
+ assert.deepEqual([model({}).contextWindow, model({}).maxTokens], [128_000, 32_000], 'none given: 128K, as before');
+ assert.deepEqual([model({ context: 64_000 }).contextWindow, model({ context: 64_000 }).maxTokens], [64_000, 16_000]);
+ assert.deepEqual([model({ context: 1_000_000 }).contextWindow, model({ context: 1_000_000 }).maxTokens], [1_000_000, 32_000], 'a long one asks for no more than 32K');
+ assert.equal(model({ context: 50 }).contextWindow, 128_000, 'one that does not hold: 128K');
+ const thinking = modelsJson([own('a', { context: 200_000, ...modelEffort(['auto', 'high'], 'high') })]).providers[THINKING(providerOf('a'))].models[0];
+ assert.deepEqual([thinking.contextWindow, thinking.maxTokens], [200_000, 32_000], 'thinking, the same length');
+ assert.deepEqual(contextUsed({ usage: { input: 150_000, output: 10 } }, model({ context: 1_000_000 })), { used: 150_010, size: 1_000_000 }, 'the usage bar reads the same window');
+ assert.deepEqual([32_000, 10_000_000, 31_999, 4_000, 10_000_001, 150_000.5, '200000', null].map(contextLength), [32_000, 10_000_000, null, null, null, null, null, null]);
+});
+
test("the chat's menu reads the person's models by their names, each picked by its id", () => {
assert.deepEqual(modelOption([own('a'), own('b')], 'b'), {
id: 'model', name: 'Model', category: 'model', type: 'select', currentValue: 'b',
diff --git a/packages/openfilm/studio/ui/src/components/settings/AgentsSection.tsx b/packages/openfilm/studio/ui/src/components/settings/AgentsSection.tsx
index c20d9c4..c3d4f26 100644
--- a/packages/openfilm/studio/ui/src/components/settings/AgentsSection.tsx
+++ b/packages/openfilm/studio/ui/src/components/settings/AgentsSection.tsx
@@ -20,6 +20,7 @@ import React from 'react';
import { Check, Copy, Download, KeyRound, Loader2, Plus, X } from 'lucide-react';
import { useLanguage, useT } from '@/i18n';
import { BYOK_EFFORTS, studioHost, type HostAgent, type HostAgentDiagnosis, type HostAgentId, type HostAgentUsage, type HostByokEffort, type HostByokEffortLevel, type HostByokFormat, type HostOwnModel } from '@/lib/host';
+import { parseContextLength } from '@/lib/context-length';
/** What is left of the plan: what Codex can say (the app's agent-usage.mjs; Claude Code's own report is wrong for Team accounts). */
const PLAN_AGENTS: readonly HostAgentId[] = ['codex'];
@@ -452,8 +453,9 @@ function OwnModels({ agent, onDone }: { agent: HostAgent; onDone: () => void })
/**
* One own model, set up or changed: its name (the model, when empty), the API format, the service's address, the
- * model asked for there, the key (left empty: its own, or another model's on the same address), and the efforts it
- * takes (each a toggle, at least one on) with the one a conversation starts on. Checked before it is kept.
+ * model asked for there, the key (left empty: its own, or another model's on the same address), the efforts it takes
+ * (each a toggle, at least one on) with the one a conversation starts on, and its context length (empty: 128K).
+ * Checked before it is kept.
*/
function OwnModelForm({ model, models, onDone }: { model?: HostOwnModel; models: HostOwnModel[]; onDone: () => void }) {
const t = useT();
@@ -465,6 +467,9 @@ function OwnModelForm({ model, models, onDone }: { model?: HostOwnModel; models:
const [modelId, setModelId] = React.useState(model?.model ?? '');
const [key, setKey] = React.useState('');
const [effort, setEffort] = React.useState<HostByokEffort>({ levels: model?.levels ?? ['auto'], effort: model?.effort ?? 'auto' });
+ const [contextText, setContextText] = React.useState(model?.context ? String(model.context) : '');
+ /* {} when empty (128K), null when what is typed does not hold */
+ const context = parseContextLength(contextText);
const [state, setState] = React.useState<{ busy: boolean; error: string | null }>({ busy: false, error: null });
/* another model on this address, whose key an empty field takes */
const sameService = models.find((m) => m.id !== model?.id && addressKey(m.baseUrl) === addressKey(baseUrl));
@@ -473,11 +478,11 @@ function OwnModelForm({ model, models, onDone }: { model?: HostOwnModel; models:
if (FORMATS.some((f) => f.address === baseUrl.trim()) || !baseUrl.trim()) setBaseUrl(FORMATS.find((f) => f.value === next)!.address);
setFormat(next);
};
- const ready = modelId.trim() && baseUrl.trim() && (key.trim() || model || sameService);
+ const ready = modelId.trim() && baseUrl.trim() && (key.trim() || model || sameService) && context;
const save = () => {
if (!host || !ready) return;
setState({ busy: true, error: null });
- void host.saveOwnModel({ ...(model ? { id: model.id } : {}), name, format, baseUrl, model: modelId, ...(key.trim() ? { key } : {}), levels: effort.levels, effort: effort.effort })
+ void host.saveOwnModel({ ...(model ? { id: model.id } : {}), name, format, baseUrl, model: modelId, ...(key.trim() ? { key } : {}), levels: effort.levels, effort: effort.effort, ...context })
.then((r) => { if (r.ok) 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) }));
};
@@ -516,6 +521,16 @@ function OwnModelForm({ model, models, onDone }: { model?: HostOwnModel; models:
<p className="text-[12.5px] leading-relaxed text-[var(--text-faint)]">{t('settings.agents.effortHint')}</p>
</div>
</div>
+ <div className="flex items-start gap-2">
+ <span className="flex h-10 items-center">{label(t('settings.agents.context'))}</span>
+ <div className="flex min-w-0 flex-1 flex-col gap-2">
+ <SettingsField value={contextText} onChange={(e) => setContextText(e.target.value)} inputMode="numeric" placeholder="128000"
+ aria-label={t('settings.agents.context')} aria-invalid={!context} className="font-mono placeholder:font-sans" spellCheck={false} />
+ <p className={context ? 'text-[12.5px] leading-relaxed text-[var(--text-faint)]' : 'text-[12.5px] leading-relaxed text-[var(--err)]'}>
+ {t(context ? 'settings.agents.contextHint' : 'settings.agents.contextBad')}
+ </p>
+ </div>
+ </div>
{state.error ? <p className={settingsError}>{state.error}</p> : null}
<div className="flex justify-end gap-1.5">
<SettingsButton variant="quiet" onClick={onDone}>{t('settings.agents.cancel')}</SettingsButton>
diff --git a/packages/openfilm/studio/ui/src/i18n/en.ts b/packages/openfilm/studio/ui/src/i18n/en.ts
index f761224..eb15527 100644
--- a/packages/openfilm/studio/ui/src/i18n/en.ts
+++ b/packages/openfilm/studio/ui/src/i18n/en.ts
@@ -1569,6 +1569,9 @@ export const en = {
effortStart: 'Starts on',
effortHint: 'Tick the efforts this model takes: the chat offers those. Auto sends none, so the service decides.',
effortLevels: { auto: 'Auto', off: 'Off', minimal: 'Minimal', low: 'Low', medium: 'Medium', high: 'High', xhigh: 'Extra high', max: 'Max' },
+ context: 'Context length',
+ contextHint: 'Tokens, as the model\'s service documents it. Empty: 128K.',
+ contextBad: 'A whole number of tokens, from 32,000 to 10,000,000.',
key: 'API key',
keyPlaceholder: 'Paste your API key',
keyKept: 'Key ending in {last4} (leave empty to keep it)',
diff --git a/packages/openfilm/studio/ui/src/i18n/es.ts b/packages/openfilm/studio/ui/src/i18n/es.ts
index 8a4ce7e..57eeb5a 100644
--- a/packages/openfilm/studio/ui/src/i18n/es.ts
+++ b/packages/openfilm/studio/ui/src/i18n/es.ts
@@ -1568,6 +1568,9 @@ export const es: Words = {
effortStart: 'Empieza en',
effortHint: 'Marca los esfuerzos que admite este modelo: el chat ofrece esos. Automático no envía ninguno, así decide el servicio.',
effortLevels: { auto: 'Automático', off: 'Sin razonar', minimal: 'Mínimo', low: 'Bajo', medium: 'Medio', high: 'Alto', xhigh: 'Muy alto', max: 'Máximo' },
+ context: 'Longitud de contexto',
+ contextHint: 'En tokens, según la documentación del servicio del modelo. Vacío: 128K.',
+ contextBad: 'Un número entero de tokens, de 32.000 a 10.000.000.',
key: 'Clave de API',
keyPlaceholder: 'Pega tu clave de API',
keyKept: 'Clave terminada en {last4} (déjalo vacío para conservarla)',
diff --git a/packages/openfilm/studio/ui/src/i18n/ja.ts b/packages/openfilm/studio/ui/src/i18n/ja.ts
index 798be79..d8b8cea 100644
--- a/packages/openfilm/studio/ui/src/i18n/ja.ts
+++ b/packages/openfilm/studio/ui/src/i18n/ja.ts
@@ -1568,6 +1568,9 @@ export const ja: Words = {
effortStart: '最初の強さ',
effortHint: 'このモデルが対応する推論の強さにチェックを入れてください。チャットではそれだけが選べます。「自動」は何も送らず、サービスに任せます。',
effortLevels: { auto: '自動', off: 'オフ', minimal: '最小', low: '低', medium: '中', high: '高', xhigh: '特高', max: '最大' },
+ context: 'コンテキスト長',
+ contextHint: 'トークン数。モデルのサービスのドキュメントにある値を入れてください。空欄なら 128K です。',
+ contextBad: '32,000〜10,000,000 のトークン数を整数で入れてください。',
key: 'API キー',
keyPlaceholder: 'API キーを貼り付け',
keyKept: '末尾が {last4} のキー(空欄のままにすると現在のキーを使います)',
diff --git a/packages/openfilm/studio/ui/src/i18n/ko.ts b/packages/openfilm/studio/ui/src/i18n/ko.ts
index 9251850..7e267e9 100644
--- a/packages/openfilm/studio/ui/src/i18n/ko.ts
+++ b/packages/openfilm/studio/ui/src/i18n/ko.ts
@@ -1567,6 +1567,9 @@ export const ko: Words = {
effortStart: '시작 강도',
effortHint: '이 모델이 지원하는 추론 강도를 체크하세요. 채팅에는 체크한 것만 나옵니다. "자동"은 아무것도 보내지 않고 서비스에 맡깁니다.',
effortLevels: { auto: '자동', off: '끔', minimal: '최소', low: '낮음', medium: '중간', high: '높음', xhigh: '매우 높음', max: '최대' },
+ context: '컨텍스트 길이',
+ contextHint: '토큰 수입니다. 모델 서비스 문서에 나온 값을 입력하세요. 비워 두면 128K입니다.',
+ contextBad: '32,000~10,000,000 사이의 토큰 수를 정수로 입력하세요.',
key: 'API 키',
keyPlaceholder: 'API 키 붙여넣기',
keyKept: '{last4}(으)로 끝나는 키(유지하려면 비워 두세요)',
diff --git a/packages/openfilm/studio/ui/src/i18n/zh-CN.ts b/packages/openfilm/studio/ui/src/i18n/zh-CN.ts
index e73474a..054d7a0 100644
--- a/packages/openfilm/studio/ui/src/i18n/zh-CN.ts
+++ b/packages/openfilm/studio/ui/src/i18n/zh-CN.ts
@@ -1569,6 +1569,9 @@ export const zhCN: Words = {
effortStart: '起始档位',
effortHint: '勾选这个模型支持的推理档位,聊天里只会出现这些档位。「自动」不发送推理参数,由服务决定。',
effortLevels: { auto: '自动', off: '不思考', minimal: '极低', low: '低', medium: '中', high: '高', xhigh: '超高', max: '最高' },
+ context: '上下文长度',
+ contextHint: '单位是 token,以模型服务的文档为准。留空为 128K。',
+ contextBad: '填一个整数,单位是 token,32,000 到 10,000,000 之间。',
key: 'API 密钥',
keyPlaceholder: '粘贴你的 API 密钥',
keyKept: '尾号为 {last4} 的密钥(留空则保留)',
diff --git a/packages/openfilm/studio/ui/src/lib/context-length.test.ts b/packages/openfilm/studio/ui/src/lib/context-length.test.ts
new file mode 100644
index 0000000..5455e0d
--- /dev/null
+++ b/packages/openfilm/studio/ui/src/lib/context-length.test.ts
@@ -0,0 +1,15 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { parseContextLength } from './context-length.ts';
+
+test('a context length as typed: empty is none, a whole number from 32K to 10M holds, anything else does not', () => {
+ assert.deepEqual(parseContextLength(''), {});
+ assert.deepEqual(parseContextLength(' '), {});
+ assert.deepEqual(parseContextLength('200000'), { context: 200_000 });
+ assert.deepEqual(parseContextLength(' 1,000,000 '), { context: 1_000_000 }, 'thousands separators');
+ assert.deepEqual(parseContextLength('128.000'), { context: 128_000 }, 'a thousands point');
+ assert.deepEqual(parseContextLength('32000'), { context: 32_000 });
+ assert.deepEqual(parseContextLength('10000000'), { context: 10_000_000 });
+ assert.deepEqual(parseContextLength('200 000'), { context: 200_000 });
+ for (const bad of ['31999', '4000', '10000001', '128K', '-8000', '1e6', 'abc', '128000.5', '40000,5', '1,0000']) assert.equal(parseContextLength(bad), null, bad);
+});
diff --git a/packages/openfilm/studio/ui/src/lib/context-length.ts b/packages/openfilm/studio/ui/src/lib/context-length.ts
new file mode 100644
index 0000000..4650c83
--- /dev/null
+++ b/packages/openfilm/studio/ui/src/lib/context-length.ts
@@ -0,0 +1,12 @@
+/**
+ * The context length of one of the person's own models, as typed in Settings → Agents: a whole number of tokens from
+ * 32K to 10M (apps/desktop src/pi-config.mjs contextLength), its thousands separated or not.
+ * `{}` when empty (the model gets 128K), `{ context }` when it holds, null when it does not.
+ */
+export function parseContextLength(text: string): { context?: number } | null {
+ const typed = text.trim();
+ if (!typed) return {};
+ if (!/^\d+$|^\d{1,3}([,. '’]\d{3})+$/.test(typed)) return null;
+ const context = Number(typed.replace(/\D/g, ''));
+ return context >= 32_000 && context <= 10_000_000 ? { context } : null;
+}
diff --git a/packages/openfilm/studio/ui/src/lib/host.ts b/packages/openfilm/studio/ui/src/lib/host.ts
index 0f36f50..6245c2f 100644
--- a/packages/openfilm/studio/ui/src/lib/host.ts
+++ b/packages/openfilm/studio/ui/src/lib/host.ts
@@ -233,12 +233,13 @@ export interface HostAgent {
/**
* One of the person's own models: its `id` (the app's), the `name` the chat's menu shows, its service (API `format`
- * and `baseUrl`), the `model` asked for there, its efforts, and the last four characters of its key.
+ * and `baseUrl`), the `model` asked for there, its efforts, its `context` length in tokens (none: 128K), and the last
+ * four characters of its key.
*/
-export interface HostOwnModel extends HostByokEffort { id: string; name: string; format: HostByokFormat; baseUrl: string; model: string; last4: string }
+export interface HostOwnModel extends HostByokEffort { id: string; name: string; format: HostByokFormat; baseUrl: string; model: string; context?: number; last4: string }
-/** What setting up one of the person's own models sends: `id` to change one, no `key` to keep its key. */
-export interface HostOwnModelConfig { id?: string; name?: string; format: HostByokFormat; baseUrl: string; model: string; key?: string; levels: HostByokEffortLevel[]; effort: HostByokEffortLevel }
+/** What setting up one of the person's own models sends: `id` to change one, no `key` to keep its key, no `context` for 128K. */
+export interface HostOwnModelConfig { id?: string; name?: string; format: HostByokFormat; baseUrl: string; model: string; key?: string; levels: HostByokEffortLevel[]; effort: HostByokEffortLevel; context?: number }
/**
* The reasoning efforts a model of the person's own key offers, in this order (`auto`: none is sent, the service decides),