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.

Chat: a conversation remembers the agent it used, after a restart too (#243)

Rick0dfa42deb73f
diff --git a/.changeset/conversation-remembers-agent.md b/.changeset/conversation-remembers-agent.md
new file mode 100644
index 0000000..da30784
--- /dev/null
+++ b/.changeset/conversation-remembers-agent.md
@@ -0,0 +1,5 @@
+---
+"@openfilm/desktop": patch
+---
+
+A conversation remembers the agent it used, and its model and effort. Opened again, after a restart too, it goes on with them, instead of switching to the agent last picked in another project. When that agent is switched off or signed out, the chat says "This conversation used X" above the composer and the next message goes to the agent picked. A new conversation still starts with the agent picked last.
diff --git a/apps/desktop/bench/conversation-agent.test.mjs b/apps/desktop/bench/conversation-agent.test.mjs
new file mode 100644
index 0000000..b98d6f3
--- /dev/null
+++ b/apps/desktop/bench/conversation-agent.test.mjs
@@ -0,0 +1,106 @@
+/** Conversation options through the real menu and send path, with agent IPC kept inside an isolated fixture. */
+import assert from 'node:assert/strict';
+import { createRequire } from 'node:module';
+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { _electron as electron } from 'playwright-core';
+import { filmHtml } from 'openfilm/film-doc';
+import { DESKTOP, buildShell, prepare } from './app.mjs';
+import { loadChat, saveSessions } from '../src/chat-store.mjs';
+import { launcherEnvironment, loginShellEnvironment } from '../src/environment.mjs';
+
+buildShell();
+const dir = join(DESKTOP, '.dev', `conversation-agent-${Date.now()}`);
+prepare(dir);
+const film = join(dir, 'projects', 'conversation');
+mkdirSync(film);
+writeFileSync(join(film, 'film.html'), filmHtml({ stage: { w: 1920, h: 1080 }, tracks: [] }));
+const now = new Date().toISOString();
+saveSessions(film, { last: 'saved', sessions: [{
+ id: 'saved', title: 'Saved conversation', turns: 1, createdAt: now, updatedAt: now,
+ agent: 'byok', agentPrefs: { byok: { model: 'model-x', effort: 'high' } },
+}] });
+
+const { PATH } = await loginShellEnvironment();
+const app = await electron.launch({
+ executablePath: createRequire(import.meta.url)('electron'), args: [DESKTOP], cwd: DESKTOP,
+ env: { ...launcherEnvironment(process.env, PATH), OPENFILM_DESKTOP_FLAVOR: 'bench', OPENFILM_BENCH_DIR: dir },
+});
+let page;
+try {
+ const findPage = async (matches) => {
+ for (let attempt = 0; attempt < 300; attempt++) {
+ const found = app.context().pages().find((p) => matches(p.url()));
+ if (found) return found;
+ await new Promise((done) => setTimeout(done, 100));
+ }
+ throw new Error('The desktop page did not open.');
+ };
+ await findPage((url) => url.startsWith('http://127.0.0.1:'));
+ // Only the agent boundary is replaced: the menu, conversation loading/saving and send path are real.
+ await app.evaluate(({ ipcMain }) => {
+ const models = [
+ { id: 'model-x', name: 'Model X', model: 'x', levels: ['low', 'high'], effort: 'low' },
+ { id: 'model-y', name: 'Model Y', model: 'y', levels: ['low', 'medium'], effort: 'medium' },
+ ].map((m) => ({ ...m, format: 'responses', baseUrl: 'http://127.0.0.1:1/v1', last4: 'test' }));
+ const options = [
+ { id: 'model', name: 'Model', category: 'model', type: 'select', currentValue: 'model-x', options: models.map((m) => ({ value: m.id, name: m.name })) },
+ { id: 'effort', name: 'Effort', category: 'thought_level', type: 'select', currentValue: 'low', options: [{ value: 'low', name: 'Low' }, { value: 'high', name: 'High' }] },
+ ];
+ const info = () => ({ sessionId: 'fixture', configOptions: options, authMethods: [], mcp: false });
+ const handle = (channel, fn) => { ipcMain.removeHandler(channel); ipcMain.handle(channel, fn); };
+ handle('desktop:agents:list', () => [{ id: 'byok', name: 'Own key', shown: true, status: 'ready', byok: { models } }]);
+ handle('desktop:local-agents:probe', () => ({ ok: true, info: info() }));
+ handle('desktop:local-agents:start', () => ({ ok: true, key: 'fixture', info: info() }));
+ handle('desktop:local-agents:set-option', (_event, { configId, value }) => {
+ const option = options.find((o) => o.id === configId);
+ assertOption(option, value);
+ option.currentValue = value;
+ return { ok: true, result: { configOptions: options } };
+ });
+ function assertOption(option, value) {
+ if (!option?.options.some((o) => o.value === value)) throw new Error(`Invalid fixture option: ${value}`);
+ }
+ handle('desktop:local-agents:prompt', (event) => {
+ globalThis.conversationAgentSent = Object.fromEntries(options.map((o) => [o.id, o.currentValue]));
+ event.sender.send('desktop:local-agents:event', { key: 'fixture', kind: 'update', update: { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'Fixture answer.' } } });
+ return { ok: true, stopReason: 'end_turn' };
+ });
+ });
+ await app.context().addInitScript(() => {
+ localStorage.setItem('openfilm.language', 'en');
+ localStorage.setItem('openfilm.local-agents.v2', JSON.stringify({ picked: 'byok', prefs: { byok: { model: 'model-y', effort: 'medium' } }, options: {} }));
+ });
+ const run = JSON.parse(readFileSync(join(dir, 'home/run.json'), 'utf8'));
+ const response = await fetch(`${run.origin}/api/open`, {
+ method: 'POST', headers: { 'content-type': 'application/json', 'x-studio-key': run.key },
+ body: JSON.stringify({ path: film, fallback: 0 }),
+ });
+ assert.equal(response.status, 200);
+ page = await findPage((url) => url.includes('/projects/'));
+ await page.waitForSelector('[data-prompt-editor]');
+ // Reload after Playwright has attached so the stored global choice precedes the chat's hydration.
+ await page.reload({ waitUntil: 'domcontentloaded' });
+ await page.waitForSelector('[data-prompt-editor]');
+ const model = page.getByRole('button', { name: /^Model X/ });
+ await model.waitFor();
+ assert.match(await model.innerText(), /High/, 'the menu keeps Model X\'s High effort when the global Model Y only offers Low and Medium');
+ await page.locator('[data-prompt-editor]').fill('Check the saved effort.');
+ await page.locator('[data-prompt-editor]').press('Enter');
+ await page.getByText('Fixture answer.', { exact: true }).waitFor();
+ assert.deepEqual(await app.evaluate(() => globalThis.conversationAgentSent), { model: 'model-x', effort: 'high' }, 'the next message uses the conversation\'s model and effort');
+ await page.waitForFunction(async (project) => {
+ const { sessions } = await window.openfilmNative.chat.load(project);
+ return sessions.find((s) => s.id === 'saved')?.turns === 2;
+ }, film);
+ assert.deepEqual(loadChat(film).sessions.find((s) => s.id === 'saved').agentPrefs.byok, { model: 'model-x', effort: 'high' }, 'sending preserves the saved effort');
+ await page.reload({ waitUntil: 'domcontentloaded' });
+ await page.getByRole('button', { name: /^Model X.*High/ }).waitFor();
+ console.log('Conversation agent passed: menu, sent options, saved preferences and reload retain Model X / High despite global Model Y / Medium.');
+} catch (error) {
+ if (page && !page.isClosed()) await page.screenshot({ path: join(dir, 'failed.png') }).catch(() => {});
+ console.error(`Conversation agent artifacts: ${dir}`);
+ throw error;
+} finally {
+ await app.close();
+}
diff --git a/apps/desktop/chat/src/App.tsx b/apps/desktop/chat/src/App.tsx
index 98dc9bb..6fde7b9 100644
--- a/apps/desktop/chat/src/App.tsx
+++ b/apps/desktop/chat/src/App.tsx
@@ -66,6 +66,8 @@ import { agentModelSummary, agentOptions, currentAgent, effectivePrefs, offeredO
import { useLiveActivityFromStore } from '@/lib/live-activity';
import { loadLastSession, loadSessions, newSession, saveLastSession, saveSessions } from '@/lib/local-sessions';
import type { ProjectSessionItem } from '@/lib/project-sessions';
+import { conversationAgent, conversationPrefs, keptPrefs } from '@/lib/conversation-agent';
+import { AGENT_DEFINITIONS, isAgentId } from '../../src/agent-definitions.mjs';
import type { TranscriptItem } from '@/lib/agent-transcript';
import { app, type FfmpegState, type Project, type SkillListing, type StudioRef, type StudioSelection } from './app-bridge';
import { Divider } from './components/Divider';
@@ -251,7 +253,23 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projec
/* ── the agent ── */
const la = useLocalAgents();
React.useEffect(() => { la.hydrate(); void la.refresh(); }, []); // eslint-disable-line react-hooks/exhaustive-deps
- const agent = currentAgent(la);
+ /* the agent this conversation used and its options, whatever was picked since in another one; a new conversation
+ takes the one picked last (lib/conversation-agent). A conversation from before they kept it: its last turn's agent */
+ const shownSessionItem = sessions.find((s) => s.id === sessionId);
+ const lastTurnAgent = asset?.sessionId === sessionId ? asset.localAgent?.id : undefined;
+ const usedAgent = [shownSessionItem?.agent, lastTurnAgent].find((id): id is LocalAgentId => Boolean(id) && isAgentId(id));
+ const { agent, was: agentWas } = conversationAgent(usedAgent, la.roster, currentAgent(la));
+ const agentPrefs = conversationPrefs(la.prefs, shownSessionItem?.agentPrefs);
+ /** the agent or an option changed in the menu: kept on this conversation, once it has said something (a new one
+ takes the pick); not a use of it, so it keeps its place in the list */
+ const keepOnSession = React.useCallback((patch: (s: ProjectSessionItem) => Partial<ProjectSessionItem>) => {
+ setSessions((list) => {
+ if (!list.some((s) => s.id === sessionId && s.turns > 0)) return list;
+ const out = list.map((s) => (s.id === sessionId ? { ...s, ...patch(s) } : s));
+ saveSessions(projectKey, out);
+ return out;
+ });
+ }, [projectKey, sessionId]);
/* what an agent's command asks before it spends: above the composer, as the agent's own questions are */
const spendAsks = React.useSyncExternalStore((change) => app.asks.onChange(change), app.asks.get);
@@ -580,8 +598,10 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projec
const shown = conversation === shownSession.current;
const turn = createLocalAgentTurn(id, agent, ordered.length);
const agentStore = useLocalAgents.getState();
- const options = agentOptions(agentStore, agent);
- const prefs = effectivePrefs(agentStore.prefs, agent, agentStore.roster, options);
+ const own = sessions.find((s) => s.id === sessionId)?.agentPrefs;
+ const picked = conversationPrefs(agentStore.prefs, own);
+ const options = agentOptions({ ...agentStore, prefs: picked }, agent);
+ const prefs = effectivePrefs(picked, agent, agentStore.roster, options);
const summary = agentModelSummary(options, prefs);
/* how hard it thinks, as the menu offers it */
const effortOption = options?.find((o) => o.category === 'thought_level');
@@ -597,7 +617,12 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projec
if (shown) setTurns((list) => mergeAssetLists([started], list));
/* the conversation is named by the words: a reference reads as its name there, not as "[1: name]" */
const title = instruction.replace(/\[\d+: ([^\]]*)\]/g, '$1').replace(/\s+/g, ' ').trim().slice(0, 80);
- touchSession(sessionId, (s) => ({ title: s.title || title, turns: s.turns + 1 }));
+ /* the agent and the model and effort it ran on, kept on the conversation: it goes on with them when opened again.
+ A turn the agent started by itself keeps no options: the person chose none there */
+ touchSession(sessionId, (s) => ({
+ title: s.title || title, turns: s.turns + 1, agent,
+ ...(origin ? {} : { agentPrefs: { ...s.agentPrefs, [agent]: { ...s.agentPrefs?.[agent], ...keptPrefs(options, prefs) } } }),
+ }));
const meta: LocalAgentTurnMeta = {
turnId: id, projectId: projectKey, projectTitle: project.name, sessionId, agent, prompt: instruction,
turnNo: ordered.length, startedAt: Date.now(), turn: started,
@@ -768,9 +793,16 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projec
);
const agentName = agent === 'byok' ? t('composer.agentOwnKey') : la.roster?.find((a) => a.id === agent)?.name ?? agent;
+ const wasName = agentWas === 'byok' ? t('composer.agentOwnKey') : agentWas ? la.roster?.find((a) => a.id === agentWas)?.name ?? AGENT_DEFINITIONS[agentWas]?.name ?? agentWas : '';
const editComposerCard = (
<div className="flex flex-col gap-1">
+ {/* the agent this conversation used cannot be used now: the next message goes to the one picked below */}
+ {agentWas ? (
+ <div className="flex items-center gap-2 rounded-[10px] border border-[var(--border)] bg-[var(--surface-2)] px-3 py-1.5 text-[12px] text-[var(--text-muted)]">
+ <span className="min-w-0 flex-1">{t('composer.agentWas').replace('{name}', wasName)}</span>
+ </div>
+ ) : null}
{contextFull ? (
<div className="flex items-center gap-2 rounded-[10px] border border-[var(--border)] bg-[var(--surface-2)] py-1.5 pl-3 pr-1.5 text-[12px] text-[var(--text-muted)]">
<span className="min-w-0 flex-1">{t('composer.contextFull')}</span>
@@ -907,7 +939,14 @@ function ChatPane({ project, banners, selection, assetsOpen }: { project: Projec
</div>
</div>
<div className="flex items-center gap-0.5 px-0.5">
- <ModelPopover placement="top" align="start" />
+ <ModelPopover
+ placement="top"
+ align="start"
+ agent={agent}
+ prefs={agentPrefs}
+ onPick={(id) => keepOnSession(() => ({ agent: id }))}
+ onPref={(id, configId, value) => keepOnSession((s) => ({ agentPrefs: { ...s.agentPrefs, [id]: { ...s.agentPrefs?.[id], [configId]: value } } }))}
+ />
<div className="min-w-0 flex-1" />
<input
ref={attachInputRef}
diff --git a/apps/desktop/chat/src/components/ModelPopover.tsx b/apps/desktop/chat/src/components/ModelPopover.tsx
index 3e40168..d119c98 100644
--- a/apps/desktop/chat/src/components/ModelPopover.tsx
+++ b/apps/desktop/chat/src/components/ModelPopover.tsx
@@ -59,7 +59,18 @@ export function ChatAgentIcon({ id, size = 14 }: { id: LocalAgentId; size?: numb
return <AgentIcon id={id} size={size} />;
}
-export function ModelPopover({ placement = 'bottom', align = 'start' }: { placement?: 'top' | 'bottom'; align?: 'start' | 'end' } = {}) {
+/**
+ * The composer's agent menu. In a conversation, `agent` and `prefs` are the ones it goes on with (lib/conversation-agent),
+ * and `onPick` and `onPref` keep a change on it too; without them, the agent and options picked last.
+ */
+export function ModelPopover({ placement = 'bottom', align = 'start', agent: conversationAgent, prefs: conversationPrefs, onPick, onPref }: {
+ placement?: 'top' | 'bottom';
+ align?: 'start' | 'end';
+ agent?: LocalAgentId;
+ prefs?: Partial<Record<LocalAgentId, Record<string, unknown>>>;
+ onPick?: (agent: LocalAgentId) => void;
+ onPref?: (agent: LocalAgentId, configId: string, value: unknown) => void;
+} = {}) {
const t = useT();
const [open, setOpen] = React.useState(false);
/** the option whose side menu is open */
@@ -90,7 +101,7 @@ export function ModelPopover({ placement = 'bottom', align = 'start' }: { placem
const la = useLocalAgents();
const { hydrate, refresh, ensureOptions } = la;
React.useEffect(() => { hydrate(); }, [hydrate]);
- const agent = currentAgent(la);
+ const agent = conversationAgent ?? currentAgent(la);
const shown = shownAgents(la.roster);
const ready = (id: LocalAgentId) => shown.find((a) => a.id === id)?.status === 'ready';
React.useEffect(() => { if (ready(agent)) void ensureOptions(agent); });
@@ -101,8 +112,9 @@ export function ModelPopover({ placement = 'bottom', align = 'start' }: { placem
});
}, [open, refresh, ensureOptions]);
- const options = agentOptions(la, agent);
- const prefs = effectivePrefs(la.prefs, agent, la.roster, options);
+ const picked = conversationPrefs ?? la.prefs;
+ const options = agentOptions({ ...la, prefs: picked }, agent);
+ const prefs = effectivePrefs(picked, agent, la.roster, options);
const rows = options ? menuOptions(options, t('composer.optionDefault')).filter((o) => offeredOption(agent, la.roster, o)) : [];
const summary = agentModelSummary(options, prefs);
const triggerModel = summary.model;
@@ -122,7 +134,7 @@ export function ModelPopover({ placement = 'bottom', align = 'start' }: { placem
};
const chooseAgent = (a: RosterAgent) => {
setSide(null);
- if (a.status === 'ready') { la.pick(a.id); return; }
+ if (a.status === 'ready') { la.pick(a.id); onPick?.(a.id); return; }
if (a.status === 'checking' || a.status === 'waiting') return;
/* not connected, signed out, not found, no key: set up in Settings → Agents, where connecting and signing in are */
setOpen(false);
@@ -133,7 +145,7 @@ export function ModelPopover({ placement = 'bottom', align = 'start' }: { placem
const choosing = side ? rows.find((o) => o.id === side) : undefined;
const chosenValue = (o: Option) => (o.fixed ? o.options![0]!.value : optionValue(options, prefs, o.id));
/* a fixed row's one value is already the one in use */
- const pickChoice = (o: Option, value: unknown) => { if (!o.fixed) la.setPref(agent, o.id, value); };
+ const pickChoice = (o: Option, value: unknown) => { if (!o.fixed) { la.setPref(agent, o.id, value); onPref?.(agent, o.id, value); } };
/* the side menu beside its row: on the right of the card, the card sliding left when the window is too narrow for
both, and over the card's right edge only when it cannot slide far enough; measured again once it is drawn */
diff --git a/apps/desktop/chat/src/i18n/locales/en-US.ts b/apps/desktop/chat/src/i18n/locales/en-US.ts
index 0f8ec87..ff34e2c 100644
--- a/apps/desktop/chat/src/i18n/locales/en-US.ts
+++ b/apps/desktop/chat/src/i18n/locales/en-US.ts
@@ -143,6 +143,7 @@ export const enUS = {
agentSection: 'Agent',
agentSetUp: 'Set up',
agentWaiting: 'Signing in…',
+ agentWas: 'This conversation used {name}, which isn’t available now. The next message goes to the agent below.',
effort: 'Effort',
filesFailed: 'Couldn\'t attach {names}: {error} Remove it to send.',
filesPending: 'The files are still being attached.',
diff --git a/apps/desktop/chat/src/i18n/locales/es.ts b/apps/desktop/chat/src/i18n/locales/es.ts
index e6ba3b5..b871dfb 100644
--- a/apps/desktop/chat/src/i18n/locales/es.ts
+++ b/apps/desktop/chat/src/i18n/locales/es.ts
@@ -143,6 +143,7 @@ export const es: Words = {
agentSection: 'Agente',
agentSetUp: 'Configurar',
agentWaiting: 'Iniciando sesión…',
+ agentWas: 'Esta conversación usaba {name}, que ahora no está disponible. El siguiente mensaje irá al agente de abajo.',
effort: 'Esfuerzo',
filesFailed: 'No se pudo adjuntar {names}: {error} Quítalo para enviar.',
filesPending: 'Los archivos aún se están adjuntando.',
diff --git a/apps/desktop/chat/src/i18n/locales/ja.ts b/apps/desktop/chat/src/i18n/locales/ja.ts
index 1f270dd..b2a9391 100644
--- a/apps/desktop/chat/src/i18n/locales/ja.ts
+++ b/apps/desktop/chat/src/i18n/locales/ja.ts
@@ -143,6 +143,7 @@ export const ja: Words = {
agentSection: 'エージェント',
agentSetUp: '設定',
agentWaiting: 'サインイン中…',
+ agentWas: 'この会話は {name} を使っていましたが、今は使えません。次のメッセージは下で選んだエージェントに送られます。',
effort: '思考レベル',
filesFailed: '{names} を追加できませんでした:{error} 削除してから送信してください。',
filesPending: 'ファイルを追加しています。',
diff --git a/apps/desktop/chat/src/i18n/locales/ko.ts b/apps/desktop/chat/src/i18n/locales/ko.ts
index 1fcf152..9e7ac14 100644
--- a/apps/desktop/chat/src/i18n/locales/ko.ts
+++ b/apps/desktop/chat/src/i18n/locales/ko.ts
@@ -139,6 +139,7 @@ export const ko: Words = {
agentSection: '에이전트',
agentSetUp: '설정',
agentWaiting: '로그인하는 중…',
+ agentWas: '이 대화는 {name}을(를) 사용했지만 지금은 사용할 수 없습니다. 다음 메시지는 아래에서 선택한 에이전트로 전송됩니다.',
effort: '추론 강도',
filesFailed: '{names}을(를) 추가하지 못했습니다: {error} 제거한 뒤 보내세요.',
filesPending: '파일을 추가하는 중입니다.',
diff --git a/apps/desktop/chat/src/i18n/locales/zh-CN.ts b/apps/desktop/chat/src/i18n/locales/zh-CN.ts
index 48589e0..82bca96 100644
--- a/apps/desktop/chat/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/chat/src/i18n/locales/zh-CN.ts
@@ -143,6 +143,7 @@ export const zhCN: Words = {
agentSection: '智能体',
agentSetUp: '设置',
agentWaiting: '正在登录…',
+ agentWas: '这段对话原来用的是 {name},现在用不了,下一条消息会发给下面选的智能体。',
effort: '思考强度',
filesFailed: '{names} 添加失败:{error} 移除后再发送。',
filesPending: '文件还在添加中。',
diff --git a/apps/desktop/chat/src/lib/conversation-agent.ts b/apps/desktop/chat/src/lib/conversation-agent.ts
new file mode 100644
index 0000000..799cda0
--- /dev/null
+++ b/apps/desktop/chat/src/lib/conversation-agent.ts
@@ -0,0 +1,45 @@
+/**
+ * Which agent a conversation goes on with, and with which options. Reads no React, so `node --test` can use it.
+ *
+ * A conversation keeps the agent it used and the options it used it with (on its session, lib/project-sessions):
+ * opened again, after a restart too, it goes on with them, whatever was picked since in another one. A new
+ * conversation takes the agent picked last.
+ */
+import type { LocalAgentId, RosterAgent } from './desktop-bridge';
+
+type Prefs = Partial<Record<LocalAgentId, Record<string, unknown>>>;
+
+/**
+ * The agent a conversation goes on with: the one it `used` while that one is switched on and ready (or still being
+ * checked or signing in, as just after a restart), else `fallback`, the one picked last. `was`: the one it used, when
+ * it cannot go on with it.
+ */
+export function conversationAgent(used: LocalAgentId | undefined, roster: RosterAgent[] | null, fallback: LocalAgentId): { agent: LocalAgentId; was: LocalAgentId | null } {
+ if (!used) return { agent: fallback, was: null };
+ const it = roster?.find((a) => a.id === used);
+ if (!roster || (it?.shown && (it.status === 'ready' || it.status === 'checking' || it.status === 'waiting'))) return { agent: used, was: null };
+ return { agent: fallback, was: fallback === used ? null : used };
+}
+
+/**
+ * What a conversation keeps of the options a turn ran with: the model and effort it ran on, the person's pick or else
+ * the agent's own (as its session reported it), so a pick made later in another conversation does not change them. Not
+ * the options the app sets for every turn (its permission mode).
+ */
+export function keptPrefs(options: Array<{ id: string; category?: string | null; currentValue?: unknown }> | undefined, prefs: Record<string, unknown>): Record<string, unknown> {
+ const kept: Record<string, unknown> = {};
+ for (const o of options ?? []) {
+ if (o.category !== 'model' && o.category !== 'thought_level') continue;
+ const value = o.id in prefs ? prefs[o.id] : o.currentValue;
+ if (value != null) kept[o.id] = value;
+ }
+ return kept;
+}
+
+/** The options picked last for each agent (`picked`), with a conversation's `own` for the agents it used standing over them. */
+export function conversationPrefs(picked: Prefs, own: Prefs | undefined): Prefs {
+ if (!own) return picked;
+ const out: Prefs = { ...picked };
+ for (const [agent, values] of Object.entries(own) as Array<[LocalAgentId, Record<string, unknown>]>) out[agent] = { ...picked[agent], ...values };
+ return out;
+}
diff --git a/apps/desktop/chat/src/lib/project-sessions.ts b/apps/desktop/chat/src/lib/project-sessions.ts
index 8c1281f..7d24be5 100644
--- a/apps/desktop/chat/src/lib/project-sessions.ts
+++ b/apps/desktop/chat/src/lib/project-sessions.ts
@@ -1,3 +1,4 @@
+import type { LocalAgentId } from './desktop-bridge';
import type { SkillsGiven } from './skill-pages';
/**
@@ -11,6 +12,10 @@ export interface ProjectSessionItem {
updatedAt: string;
/** How many turns the session has. 0: just opened, nothing said yet. */
turns: number;
+ /** The agent this conversation goes on with: the one it used last, after a restart too (lib/conversation-agent). */
+ agent?: LocalAgentId;
+ /** The options (model, effort) it used each agent with, by agent: they stand over the ones picked last. */
+ agentPrefs?: Partial<Record<LocalAgentId, Record<string, unknown>>>;
/** Each agent's own id of this conversation (by agent): its next turn goes on with it, after a restart too. */
agentSessions?: Record<string, string>;
/** The skills whose SKILL.md each agent's session has had in this conversation (lib/skill-pages), by agent. */
diff --git a/apps/desktop/src/conversation-agent.test.mjs b/apps/desktop/src/conversation-agent.test.mjs
new file mode 100644
index 0000000..c8132b9
--- /dev/null
+++ b/apps/desktop/src/conversation-agent.test.mjs
@@ -0,0 +1,42 @@
+import assert from 'node:assert/strict';
+import { test } from 'node:test';
+import { conversationAgent, conversationPrefs, keptPrefs } from '../chat/src/lib/conversation-agent.ts';
+
+const roster = (...agents) => agents.map(([id, status, shown = true]) => ({ id, name: id, shown, status }));
+
+test('a conversation goes on with the agent it used, not the one picked last in another project', () => {
+ assert.deepEqual(conversationAgent('deepseek', roster(['deepseek', 'ready'], ['codex', 'ready']), 'codex'), { agent: 'deepseek', was: null });
+ /* the roster not told yet, or the agent still being checked as the app starts: no change, nothing said */
+ assert.deepEqual(conversationAgent('deepseek', null, 'codex'), { agent: 'deepseek', was: null });
+ assert.deepEqual(conversationAgent('deepseek', roster(['deepseek', 'checking'], ['codex', 'ready']), 'codex'), { agent: 'deepseek', was: null });
+ /* still signing in, as it can be just after a restart: not gone, so the first message does not move the conversation */
+ assert.deepEqual(conversationAgent('deepseek', roster(['deepseek', 'waiting'], ['codex', 'ready']), 'codex'), { agent: 'deepseek', was: null });
+});
+
+test('a new conversation, one that has said nothing yet, takes the agent picked last', () => {
+ assert.deepEqual(conversationAgent(undefined, roster(['deepseek', 'ready'], ['codex', 'ready']), 'codex'), { agent: 'codex', was: null });
+});
+
+test('the agent it used gone, signed out or switched off: the one picked last, and which one it used is said', () => {
+ assert.deepEqual(conversationAgent('deepseek', roster(['deepseek', 'sign-in'], ['codex', 'ready']), 'codex'), { agent: 'codex', was: 'deepseek' });
+ assert.deepEqual(conversationAgent('deepseek', roster(['deepseek', 'ready', false], ['codex', 'ready']), 'codex'), { agent: 'codex', was: 'deepseek' });
+ assert.deepEqual(conversationAgent('deepseek', roster(['codex', 'ready']), 'codex'), { agent: 'codex', was: 'deepseek' });
+ /* nothing else to go on with: the one it used, as before */
+ assert.deepEqual(conversationAgent('deepseek', roster(['deepseek', 'sign-in']), 'deepseek'), { agent: 'deepseek', was: null });
+});
+
+test("a conversation's own options for an agent stand over the ones picked last for it; the other agents' are left as they are", () => {
+ const picked = { codex: { model: 'gpt-6', reasoning_effort: 'high' }, claude: { model: 'opus' } };
+ assert.deepEqual(conversationPrefs(picked, { codex: { model: 'gpt-5' } }), { codex: { model: 'gpt-5', reasoning_effort: 'high' }, claude: { model: 'opus' } });
+ assert.equal(conversationPrefs(picked, undefined), picked);
+});
+
+test('a conversation keeps the model and effort a turn ran on, picked or the agent\'s own, and none of the options the app sets', () => {
+ const options = [
+ { id: 'model', category: 'model', currentValue: 'gpt-6' },
+ { id: 'reasoning_effort', category: 'thought_level', currentValue: 'medium' },
+ { id: 'mode', category: 'mode', currentValue: 'auto' },
+ ];
+ assert.deepEqual(keptPrefs(options, { reasoning_effort: 'high', mode: 'agent-full-access' }), { model: 'gpt-6', reasoning_effort: 'high' });
+ assert.deepEqual(keptPrefs(undefined, { model: 'gpt-6' }), {});
+});