diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx
index a4e7a44270..bf8181a7ee 100644
--- a/apps/mobile/app/_layout.tsx
+++ b/apps/mobile/app/_layout.tsx
@@ -92,7 +92,9 @@ function RootNavigator() {
['usage', t.usage],
['model-providers', t.modelProviders.title],
['model-provider-account', t.modelProviders.account],
- ['models', t.modelSettings.title],
+ ['models', t.modelConfig.title],
+ ['model-preset-new', undefined],
+ ['model-sub-choice', undefined],
['model-picker', undefined],
['model-preset', undefined],
['routing-group', undefined],
diff --git a/apps/mobile/app/bot/[slug]/_layout.tsx b/apps/mobile/app/bot/[slug]/_layout.tsx
index 432aa8751a..02fde2f272 100644
--- a/apps/mobile/app/bot/[slug]/_layout.tsx
+++ b/apps/mobile/app/bot/[slug]/_layout.tsx
@@ -43,6 +43,7 @@ export default function BotProfileLayout() {
+
diff --git a/apps/mobile/app/bot/[slug]/model-sub-choice.tsx b/apps/mobile/app/bot/[slug]/model-sub-choice.tsx
new file mode 100644
index 0000000000..2be38e3de5
--- /dev/null
+++ b/apps/mobile/app/bot/[slug]/model-sub-choice.tsx
@@ -0,0 +1,5 @@
+import { SubChoiceRoute } from '../../../src/ui/chat/sub-choice-screen';
+
+export default function BotSubChoiceScreen() {
+ return ;
+}
diff --git a/apps/mobile/app/settings/model-preset-new.tsx b/apps/mobile/app/settings/model-preset-new.tsx
new file mode 100644
index 0000000000..1932beed9c
--- /dev/null
+++ b/apps/mobile/app/settings/model-preset-new.tsx
@@ -0,0 +1,5 @@
+import { ModelPresetNewScreen } from '../../src/ui/chat/model-preset-new-screen';
+
+export default function ModelPresetNewRoute() {
+ return ;
+}
diff --git a/apps/mobile/app/settings/model-sub-choice.tsx b/apps/mobile/app/settings/model-sub-choice.tsx
new file mode 100644
index 0000000000..16532d8971
--- /dev/null
+++ b/apps/mobile/app/settings/model-sub-choice.tsx
@@ -0,0 +1,5 @@
+import { SubChoiceRoute } from '../../src/ui/chat/sub-choice-screen';
+
+export default function PresetSubChoiceScreen() {
+ return ;
+}
diff --git a/apps/mobile/app/settings/models.tsx b/apps/mobile/app/settings/models.tsx
index 467a8ee0a1..5fb7be5094 100644
--- a/apps/mobile/app/settings/models.tsx
+++ b/apps/mobile/app/settings/models.tsx
@@ -1,5 +1,5 @@
-import { ModelSettingsScreen } from '../../src/ui/chat/model-settings-route';
+import { ModelConfigurationScreen } from '../../src/ui/chat/model-configuration-screen';
-export default function GlobalModelsScreen() {
- return ;
+export default function ModelConfigurationRoute() {
+ return ;
}
diff --git a/apps/mobile/src/features/models/strings.ts b/apps/mobile/src/features/models/strings.ts
index 1902225e13..65b06f92db 100644
--- a/apps/mobile/src/features/models/strings.ts
+++ b/apps/mobile/src/features/models/strings.ts
@@ -70,14 +70,26 @@ export const en = {
signInFailed: 'Couldn’t start sign-in. Try again.',
signInTimedOut: 'Sign-in didn’t finish on the computer. Try again.',
},
+ modelConfig: {
+ title: 'Model configuration',
+ section: 'Models',
+ rowHint: 'Default preset, presets and Routing Groups',
+ hint: 'New Bots and Bots without their own models use the Default preset.',
+ sectionDefault: 'Default',
+ sectionPresets: 'Presets',
+ newPreset: 'New preset',
+ emptyPresets: 'No other presets yet.',
+ newPresetHint: 'The new preset starts as a copy of the Default preset.',
+ create: 'Create preset',
+ },
modelSettings: {
- title: 'Models and presets',
+ title: 'Model',
global: 'Global default model',
globalHint:
'Bots use this default unless set on their own. Applying a preset copies its models to that Bot.',
- botHint: 'Orchestrator chats. Assignment models do delegated work. Only this Bot changes.',
+ botHint: 'The main model chats. Task models do delegated work. Only this Bot changes.',
presetHint: 'Bots already using this preset keep their settings until you apply it again.',
- orchestrator: 'Orchestrator model',
+ orchestrator: 'Main model',
assignment: 'Assignment default model',
allowed: 'Allowed Assignment models',
allowedHint:
@@ -88,8 +100,8 @@ export const en = {
groupEffort: 'Set by each group member',
groupEffortHint: 'Each model in this Routing Group runs with its own reasoning effort.',
groupEffortShared: 'Members that support reasoning use this effort. Others run without one.',
- inherit: 'Restore global default',
- inherited: 'Following global default',
+ inherit: 'Use the Default preset',
+ inherited: 'Using the Default preset',
search: 'Search models or providers',
noResults: 'No matching models. Try another name or provider.',
families: 'Model families',
@@ -127,6 +139,23 @@ export const en = {
saved: 'Preset saved',
count: (count: number) => `${count} models`,
},
+ subChoices: {
+ title: 'Task models',
+ hint: 'The main model can pick any of these for a delegated task. Without a pick, it uses the default.',
+ followsMain: 'Same as main model',
+ followsMainHint: 'No task models yet, so delegated tasks use the main model.',
+ inherited: 'From the Default preset. Changing the list gives this Bot its own.',
+ add: 'Add a task model',
+ makeDefault: 'Make default',
+ remove: 'Remove from task models',
+ note: 'When should tasks use it? (optional)',
+ noteLabel: (name: string) => `Note for ${name}`,
+ effort: 'Reasoning effort',
+ stale: 'The group’s models no longer share the saved reasoning levels.',
+ clearEfforts: 'Clear effort limit',
+ full: 'The list already holds 20 models. Remove one to add another.',
+ search: 'Search models, Routing Groups or accounts',
+ },
routingGroup: {
add: 'Add Routing Group',
edit: 'Edit Routing Group',
@@ -246,8 +275,20 @@ export const zh: typeof en = {
signInFailed: '无法开始登录,再试一次。',
signInTimedOut: '电脑上的登录没有完成,再试一次。',
},
+ modelConfig: {
+ title: '模型配置',
+ section: '模型',
+ rowHint: '默认预设、预设和路由组',
+ hint: '新建的 Bot 和没有单独设置模型的 Bot 使用默认预设。',
+ sectionDefault: '默认',
+ sectionPresets: '预设',
+ newPreset: '新建预设',
+ emptyPresets: '还没有其他预设。',
+ newPresetHint: '新预设会先复制默认预设的模型。',
+ create: '创建预设',
+ },
modelSettings: {
- title: '模型与预设',
+ title: '模型',
global: '全局默认模型',
globalHint: 'Bot 未单独设置时使用这里的默认模型。应用预设会把它的模型复制给该 Bot。',
botHint: '主模型负责对话,副模型执行委派任务。只影响此 Bot。',
@@ -262,8 +303,8 @@ export const zh: typeof en = {
groupEffort: '强度由路由组各成员决定',
groupEffortHint: '路由组里的每个模型按各自的推理强度运行。',
groupEffortShared: '支持推理的成员按这个强度运行,其余成员不带强度。',
- inherit: '恢复全局默认',
- inherited: '跟随全局默认',
+ inherit: '恢复为默认预设',
+ inherited: '使用默认预设',
search: '搜索模型或服务商',
noResults: '没有匹配的模型,更换名称或服务商。',
families: '模型系列',
@@ -298,6 +339,24 @@ export const zh: typeof en = {
saved: '预设已保存',
count: (count: number) => `${count} 个模型`,
},
+ subChoices: {
+ title: '副模型',
+ hint: '分派任务时,主模型可以从这些里挑选;没有指定时用标为「默认」的那个。',
+ followsMain: '跟随主模型',
+ followsMainHint: '还没有添加副模型,分派的任务也用主模型。',
+ inherited: '沿用默认预设。改动列表后,这个 Bot 会有自己的副模型。',
+ add: '添加副模型',
+ makeDefault: '设为默认',
+ remove: '从副模型中移除',
+ note: '什么时候用这个模型?(可选)',
+ noteLabel: (name: string) => `${name} 的使用说明`,
+ effort: '推理强度',
+ stale: '组内模型变了,原来的推理强度限制已不适用。',
+ clearEfforts: '清除强度限制',
+ full: '列表里已经有 20 个模型,先移除一个再添加。',
+ search: '搜索模型、路由组或账号',
+ },
+
routingGroup: {
add: '添加路由组',
edit: '编辑路由组',
diff --git a/apps/mobile/src/ui/chat/model-configuration-screen.tsx b/apps/mobile/src/ui/chat/model-configuration-screen.tsx
new file mode 100644
index 0000000000..b89df6158e
--- /dev/null
+++ b/apps/mobile/src/ui/chat/model-configuration-screen.tsx
@@ -0,0 +1,101 @@
+import { useRouter } from 'expo-router';
+import { ScrollView, View } from 'react-native';
+
+import type { HostClient } from '@botharness/host-client/client';
+import { DEFAULT_MODEL_PRESET_ID } from '@botharness/host-client/model-plans';
+import type { ModelPreset } from '@botharness/host-client/bot-settings';
+import { useHostSession } from '../../host/host-session';
+import { space } from '../design/tokens';
+import { LoadingIndicator } from '../primitives/loading-indicator';
+import { SettingsGroupItem, SettingsHeading, SettingsRow } from '../primitives/settings-row';
+import { SheetPage } from '../primitives/sheet-page';
+import { useStrings } from '../strings';
+import { RouteIcon } from './model-route-label';
+import { presetDetail, presetFront } from './model-route-text';
+import { useModels } from './model-settings-screen';
+import { RoutingGroupLink, type RoutingGroupLinkItem } from './routing-group-links';
+import { SHEET_GROUP, SheetFailed, SheetLoading, SheetNote } from './sheet';
+
+export function ModelConfigurationScreen() {
+ const t = useStrings();
+ const { client, saved } = useHostSession();
+ if (client === undefined) return {t.unreachable};
+ return ;
+}
+
+function ModelConfigurationView({ client }: { client: HostClient }) {
+ const t = useStrings();
+ const router = useRouter();
+ const models = useModels(client, { kind: 'global' });
+ const value = models.value;
+ const page = (body: React.ReactNode) => {body};
+ if (value === undefined)
+ return page(
+ models.error === undefined ? (
+
+ ) : (
+
+ ),
+ );
+ const pinned = value.presets.find((preset) => preset.id === DEFAULT_MODEL_PRESET_ID);
+ const others = value.presets.filter((preset) => preset.id !== DEFAULT_MODEL_PRESET_ID);
+ const openPreset = (preset: ModelPreset) =>
+ router.push({ pathname: '/settings/model-preset', params: { id: preset.id } });
+ const presetRow = (preset: ModelPreset, first: boolean, last: boolean) => (
+
+ }
+ detail={presetDetail(value, preset)}
+ disclosure
+ control={{ kind: 'chevron' }}
+ onPress={() => openPreset(preset)}
+ />
+
+ );
+ const groupItems: RoutingGroupLinkItem[] = [
+ ...(value.groups ?? []).map((group) => ({ kind: 'group' as const, group })),
+ { kind: 'add' },
+ ];
+ const heading = (text: string) => (
+
+ {text}
+
+ );
+ return page(
+
+ {t.modelConfig.hint}
+ {models.error === undefined ? null : {models.error}}
+ {models.busy ? : null}
+ {pinned === undefined ? null : (
+ <>
+ {heading(t.modelConfig.sectionDefault)}
+ {presetRow(pinned, true, true)}
+ >
+ )}
+ {heading(t.modelConfig.sectionPresets)}
+ {others.map((preset, index) => presetRow(preset, index === 0, false))}
+
+ router.push('/settings/model-preset-new')}
+ />
+
+ {groupItems.map((item, index) => (
+
+ ))}
+ ,
+ );
+}
diff --git a/apps/mobile/src/ui/chat/model-preset-new-screen.tsx b/apps/mobile/src/ui/chat/model-preset-new-screen.tsx
new file mode 100644
index 0000000000..7fc6e74dae
--- /dev/null
+++ b/apps/mobile/src/ui/chat/model-preset-new-screen.tsx
@@ -0,0 +1,111 @@
+import { useFocusEffect, useRouter } from 'expo-router';
+import { useCallback, useRef, useState } from 'react';
+import { View } from 'react-native';
+
+import { errorText } from '@botharness/host-client/bot-settings';
+import type { HostClient } from '@botharness/host-client/client';
+import { createModelPreset, DEFAULT_MODEL_PRESET_ID } from '@botharness/host-client/model-plans';
+import { presetSubFromLegacy, presetSubWithEngine } from '@botharness/host-protocol/preset-sub';
+import { useHostSession } from '../../host/host-session';
+import { space } from '../design/tokens';
+import { Button } from '../primitives/button';
+import { KeyboardFormScroll } from '../primitives/keyboard-form';
+import { SheetPage } from '../primitives/sheet-page';
+import { TextField } from '../primitives/text-field';
+import { useStrings } from '../strings';
+import { useModels } from './model-settings-screen';
+import { SheetFailed, SheetLoading, SheetNote } from './sheet';
+
+export function ModelPresetNewScreen() {
+ const t = useStrings();
+ const { client, saved } = useHostSession();
+ if (client === undefined) return {t.unreachable};
+ return ;
+}
+
+function ModelPresetNewView({ client }: { client: HostClient }) {
+ const t = useStrings();
+ const router = useRouter();
+ const models = useModels(client, { kind: 'global' });
+ const [name, setName] = useState('');
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState();
+ const focused = useRef(true);
+ useFocusEffect(
+ useCallback(() => {
+ focused.current = true;
+ return () => {
+ focused.current = false;
+ };
+ }, []),
+ );
+ const value = models.value;
+ const source = value?.presets.find((preset) => preset.id === DEFAULT_MODEL_PRESET_ID);
+ const create = () => {
+ if (source === undefined || busy || name.trim() === '') return;
+ setBusy(true);
+ setError(undefined);
+ createModelPreset(client, {
+ name: name.trim(),
+ ...(source.orchestratorGroupId === undefined
+ ? { orchestrator: source.orchestrator }
+ : {
+ orchestratorGroupId: source.orchestratorGroupId,
+ ...(source.orchestratorGroupEffort === undefined
+ ? {}
+ : { orchestratorGroupEffort: source.orchestratorGroupEffort }),
+ }),
+ ...(source.orchestratorEngine === undefined
+ ? {}
+ : { orchestratorEngine: source.orchestratorEngine }),
+ sub: source.sub ?? presetSubWithEngine(presetSubFromLegacy(source), source.assignmentEngine),
+ }).then(
+ (preset) => {
+ setBusy(false);
+ if (focused.current)
+ router.replace({ pathname: '/settings/model-preset', params: { id: preset.id } });
+ },
+ (cause: unknown) => {
+ setError(errorText(cause));
+ setBusy(false);
+ },
+ );
+ };
+ return (
+
+ {value === undefined ? (
+ models.error === undefined ? (
+
+ ) : (
+
+ )
+ ) : (
+
+ {t.modelConfig.newPresetHint}
+
+
+
+
+ {error === undefined ? null : {error}}
+
+ )}
+
+ );
+}
diff --git a/apps/mobile/src/ui/chat/model-settings-route.tsx b/apps/mobile/src/ui/chat/model-settings-route.tsx
index 41d3bc225b..0364a3780a 100644
--- a/apps/mobile/src/ui/chat/model-settings-route.tsx
+++ b/apps/mobile/src/ui/chat/model-settings-route.tsx
@@ -9,6 +9,7 @@ import {
import { useHostSession } from '../../host/host-session';
import { useStrings } from '../strings';
import { ModelsView } from './model-settings-screen';
+import { SubChoicePicker } from './sub-choice-picker';
import { SheetNote } from './sheet';
export function ModelSettingsScreen({
@@ -26,6 +27,8 @@ export function ModelSettingsScreen({
provider = '',
model = '',
group = '',
+ engine = '',
+ account = '',
} = useLocalSearchParams<{
slug: string;
id: string;
@@ -33,6 +36,8 @@ export function ModelSettingsScreen({
provider: string;
model: string;
group: string;
+ engine: string;
+ account: string;
}>();
const { client, saved } = useHostSession();
const scope: ModelScope =
@@ -59,6 +64,25 @@ export function ModelSettingsScreen({
? { kind: 'model', provider, model }
: undefined;
if (client === undefined) return {t.unreachable};
+ if (pick && (field === 'sub-add' || field === 'sub-effort'))
+ return (
+
+ );
return (
modelSettingsResource(client, scope), [client, key]);
const [value, setValue] = useState(resource.peek);
@@ -179,6 +183,7 @@ export function ModelsView({
const t = useStrings();
const router = useRouter();
const models = useModels(client, scope);
+ const engines = useEngineOptions(client);
const theme = useDesignTheme();
const [query, setQuery] = useState('');
const [family, setFamily] = useState();
@@ -210,6 +215,13 @@ export function ModelsView({
params: { field, ...extra, ...(scope.kind === 'preset' ? { id: scope.id } : {}) },
});
};
+ const openChoice = (choice: SubChoice) => {
+ const key = subChoiceKey(choice);
+ if (scope.kind === 'bot')
+ router.push({ pathname: '/bot/[slug]/model-sub-choice', params: { slug: scope.slug, key } });
+ else if (scope.kind === 'preset')
+ router.push({ pathname: '/settings/model-sub-choice', params: { id: scope.id, key } });
+ };
const title =
picker === 'allowed'
? t.modelSettings.allowed
@@ -784,7 +796,7 @@ export function ModelsView({
{models.busy ? : null}
{scope.kind === 'bot' && value.currentTarget?.kind === 'engine' ? (
@@ -817,51 +829,6 @@ export function ModelsView({
onPress={models.busy ? undefined : () => openPicker('orchestrator-effort')}
/>
)}
- {scope.kind === 'global' ? null : (
- <>
-
- }
- onPress={models.busy ? undefined : () => openPicker('assignment')}
- />
- {assignmentGroup === undefined ? null : (
- openPicker('assignment-effort')}
- />
- )}
- openPicker('allowed')
- }
- />
- >
- )}
{scope.kind === 'bot' ? (
- {scope.kind === 'global' || routes.assignmentDefault === undefined ? null : (
- openPicker('allowed-effort', target)}
- />
+ {scope.kind === 'global' ? null : (
+
+ openPicker('sub-add')}
+ />
+
)}
([]);
+ useFocusEffect(
+ useCallback(() => {
+ let active = true;
+ void loadRoutingGroupEngines(client).then(
+ (options) => {
+ if (active) setEngines(options);
+ },
+ () => undefined,
+ );
+ return () => {
+ active = false;
+ };
+ }, [client]),
+ );
+ return engines;
+}
diff --git a/apps/mobile/src/ui/chat/sub-choice-notes.ts b/apps/mobile/src/ui/chat/sub-choice-notes.ts
new file mode 100644
index 0000000000..b7498e8bab
--- /dev/null
+++ b/apps/mobile/src/ui/chat/sub-choice-notes.ts
@@ -0,0 +1,102 @@
+export interface NoteQueue {
+ commit(text: string, saved: string): boolean;
+ pending(): string | undefined;
+ settled(): Promise;
+}
+
+export function noteQueue(
+ write: (text: string) => Promise,
+ onSaved: (text: string) => void,
+ onError: (cause: unknown, text: string) => void,
+): NoteQueue {
+ let chain = Promise.resolve();
+ let latest = 0;
+ let pending: { id: number; text: string } | undefined;
+ return {
+ commit(text, saved) {
+ if (text === (pending?.text ?? saved)) return false;
+ const id = ++latest;
+ pending = { id, text };
+ chain = chain.then(() =>
+ write(text).then(
+ () => {
+ if (pending?.id === id) pending = undefined;
+ onSaved(text);
+ },
+ (cause: unknown) => {
+ if (pending?.id !== id) return;
+ pending = undefined;
+ onError(cause, text);
+ },
+ ),
+ );
+ return true;
+ },
+ pending: () => pending?.text,
+ settled: () => chain,
+ };
+}
+
+export interface FailedNote {
+ text: string;
+ error: string;
+}
+
+const failedNotes = new Map();
+
+export function failedNote(key: string): FailedNote | undefined {
+ return failedNotes.get(key);
+}
+
+export function rememberFailedNote(key: string, note: FailedNote): void {
+ failedNotes.set(key, note);
+}
+
+export function forgetFailedNote(key: string): void {
+ failedNotes.delete(key);
+}
+
+export interface NoteHandlers {
+ write(text: string): Promise;
+ onSaved(text: string): void;
+ onError(cause: unknown, text: string): void;
+}
+
+const sharedQueues = new Map();
+
+export function pendingNote(key: string): string | undefined {
+ return sharedQueues.get(key)?.queue.pending();
+}
+
+export function sharedNoteQueue(key: string, handlers: NoteHandlers): NoteQueue {
+ const entry = sharedQueues.get(key);
+ if (entry !== undefined) {
+ Object.assign(entry.handlers, handlers);
+ return entry.queue;
+ }
+ const current = { ...handlers };
+ const queue = noteQueue(
+ (text) => current.write(text),
+ (text) => current.onSaved(text),
+ (cause, text) => current.onError(cause, text),
+ );
+ sharedQueues.set(key, { queue, handlers: current });
+ return queue;
+}
+
+export function commitNoteDraft(
+ queue: NoteQueue,
+ key: string,
+ note: string,
+ saved: string,
+): 'queued' | 'restored' | 'unchanged' {
+ if (queue.commit(note, saved)) {
+ forgetFailedNote(key);
+ return 'queued';
+ }
+ if (note === saved && queue.pending() === undefined) {
+ forgetFailedNote(key);
+ return 'restored';
+ }
+ return 'unchanged';
+}
diff --git a/apps/mobile/src/ui/chat/sub-choice-picker.tsx b/apps/mobile/src/ui/chat/sub-choice-picker.tsx
new file mode 100644
index 0000000000..9c0ab16314
--- /dev/null
+++ b/apps/mobile/src/ui/chat/sub-choice-picker.tsx
@@ -0,0 +1,174 @@
+import { useRouter } from 'expo-router';
+import { useState } from 'react';
+import { FlatList, View } from 'react-native';
+
+import type { HostClient } from '@botharness/host-client/client';
+import {
+ modelSub,
+ searchSubChoices,
+ setModelSub,
+ subEffortOptions,
+ type AssignmentEffortTarget,
+ type ModelScope,
+ type SubAddOption,
+} from '@botharness/host-client/model-settings';
+import { SUB_MODEL_LIMIT, addSubChoice, setSubEffort } from '@botharness/host-client/preset-sub';
+
+import { useDesignTheme } from '../design/theme';
+import { space } from '../design/tokens';
+import { SearchField } from '../primitives/search-field';
+import { SettingsGroupItem, SettingsRow } from '../primitives/settings-row';
+import { SheetPage } from '../primitives/sheet-page';
+import { useStrings } from '../strings';
+import { ModelTargetIcon } from './model-target-icon';
+import { useModels } from './model-settings-screen';
+import { SHEET_GROUP, SheetFailed, SheetLoading, SheetNote } from './sheet';
+import { useEngineOptions } from './sub-choice-engines';
+import { subChoiceKey, subChoiceView } from './sub-choice-text';
+
+export function SubChoicePicker({
+ client,
+ scope,
+ field,
+ target,
+}: {
+ client: HostClient;
+ scope: ModelScope;
+ field: 'sub-add' | 'sub-effort';
+ target?: AssignmentEffortTarget | undefined;
+}) {
+ const t = useStrings();
+ const theme = useDesignTheme();
+ const router = useRouter();
+ const models = useModels(client, scope);
+ const engines = useEngineOptions(client);
+ const [query, setQuery] = useState('');
+ const value = models.value;
+ const title = field === 'sub-add' ? t.subChoices.add : t.subChoices.effort;
+ if (value === undefined)
+ return (
+
+ {models.error === undefined ? (
+
+ ) : (
+
+ )}
+
+ );
+ const sub = modelSub(value);
+ const back = () => router.back();
+ if (field === 'sub-effort') {
+ const info = target === undefined ? undefined : subEffortOptions(value, target, engines);
+ const rows =
+ info === undefined
+ ? []
+ : [{ id: '', name: t.modelSettings.providerDefault }, ...info.options];
+ return (
+
+ row.id || 'default'}
+ contentContainerStyle={{ paddingVertical: space.x3 }}
+ ListHeaderComponent={
+ models.error === undefined ? undefined : {models.error}
+ }
+ renderItem={({ item, index }) => (
+
+
+ models.run(
+ () =>
+ setModelSub(
+ client,
+ scope,
+ value,
+ setSubEffort(
+ sub,
+ info.selection,
+ item.id,
+ info.options.map((entry) => entry.id),
+ ),
+ ),
+ back,
+ )
+ }
+ />
+
+ )}
+ />
+
+ );
+ }
+ const options = searchSubChoices(value, query, engines);
+ const modelsFull =
+ sub.choices.filter((choice) => choice.kind === 'model').length >= SUB_MODEL_LIMIT;
+ const add = (option: SubAddOption) =>
+ models.run(() => setModelSub(client, scope, value, addSubChoice(sub, option.choice)), back);
+ return (
+
+
+ subChoiceKey(option.choice)}
+ contentContainerStyle={{ paddingVertical: space.x3 }}
+ ListHeaderComponent={
+
+ {modelsFull ? {t.subChoices.full} : null}
+ {models.error === undefined ? null : {models.error}}
+
+ }
+ ListEmptyComponent={{t.modelSettings.noResults}}
+ renderItem={({ item, index }) => {
+ const view = subChoiceView(value, item.choice, engines);
+ return (
+
+
+ }
+ onPress={models.busy ? undefined : () => add(item)}
+ />
+
+ );
+ }}
+ />
+
+ );
+}
diff --git a/apps/mobile/src/ui/chat/sub-choice-screen.tsx b/apps/mobile/src/ui/chat/sub-choice-screen.tsx
new file mode 100644
index 0000000000..8f93b95439
--- /dev/null
+++ b/apps/mobile/src/ui/chat/sub-choice-screen.tsx
@@ -0,0 +1,259 @@
+import { useFocusEffect, useLocalSearchParams, useRouter } from 'expo-router';
+import { useCallback, useMemo, useRef, useState } from 'react';
+import { View } from 'react-native';
+
+import type { HostClient } from '@botharness/host-client/client';
+import { errorText } from '@botharness/host-client/bot-settings';
+import {
+ modelScopeKey,
+ modelSettingsResource,
+ modelSub,
+ setModelSub,
+ subEffortOptions,
+ type AssignmentEffortTarget,
+ type ModelScope,
+} from '@botharness/host-client/model-settings';
+import type { SubSelection } from '@botharness/host-client/preset-sub';
+import {
+ removeSubChoice,
+ setSubDefault,
+ setSubEffort,
+ setSubNote,
+ staleGroupEfforts,
+ subSelectionOf,
+} from '@botharness/host-client/preset-sub';
+import { matchesPresetSubChoice } from '@botharness/host-protocol/preset-sub';
+
+import { useHostSession } from '../../host/host-session';
+import { space } from '../design/tokens';
+import { KeyboardFormScroll } from '../primitives/keyboard-form';
+import { LoadingIndicator } from '../primitives/loading-indicator';
+import { SettingsRow, SettingsSection } from '../primitives/settings-row';
+import { SheetPage } from '../primitives/sheet-page';
+import { TextField } from '../primitives/text-field';
+import { useStrings } from '../strings';
+import { useModels } from './model-settings-screen';
+import { SHEET_GROUP, SheetFailed, SheetLoading, SheetNote } from './sheet';
+import { useEngineOptions } from './sub-choice-engines';
+import {
+ commitNoteDraft,
+ failedNote,
+ forgetFailedNote,
+ pendingNote,
+ rememberFailedNote,
+ sharedNoteQueue,
+ type NoteQueue,
+} from './sub-choice-notes';
+import { subChoiceKey, subChoiceTarget, subChoiceView } from './sub-choice-text';
+
+export function subChoiceTargetParams(target: AssignmentEffortTarget): Record {
+ switch (target.kind) {
+ case 'group':
+ return { group: target.id };
+ case 'model':
+ return { provider: target.provider, model: target.model };
+ case 'engine':
+ return {
+ engine: target.engine,
+ ...(target.accountId === undefined ? {} : { account: target.accountId }),
+ ...(target.model === undefined ? {} : { model: target.model }),
+ };
+ }
+}
+
+export function SubChoiceRoute({ kind }: { kind: 'preset' | 'bot' }) {
+ const t = useStrings();
+ const {
+ id = '',
+ slug = '',
+ key = '',
+ } = useLocalSearchParams<{
+ id: string;
+ slug: string;
+ key: string;
+ }>();
+ const { client, saved } = useHostSession();
+ if (client === undefined) return {t.unreachable};
+ const scope: ModelScope = kind === 'bot' ? { kind, slug } : { kind, id };
+ return (
+
+ );
+}
+
+function SubChoiceDetail({
+ client,
+ hostId,
+ scope,
+ choiceKey,
+}: {
+ client: HostClient;
+ hostId: string;
+ scope: ModelScope;
+ choiceKey: string;
+}) {
+ const t = useStrings();
+ const router = useRouter();
+ const models = useModels(client, scope);
+ const engines = useEngineOptions(client);
+ const value = models.value;
+ const sub = value === undefined ? undefined : modelSub(value);
+ const choice = sub?.choices.find((entry) => subChoiceKey(entry) === choiceKey);
+ const scopeKey = modelScopeKey(scope);
+ const draftKey = `${hostId}:${scopeKey}:${choiceKey}`;
+ const [note, setNote] = useState(
+ () => pendingNote(draftKey) ?? failedNote(draftKey)?.text,
+ );
+ const [noteError, setNoteError] = useState(() => failedNote(draftKey)?.error);
+ const resource = useMemo(() => modelSettingsResource(client, scope), [client, scopeKey]);
+ const notes = useRef(undefined);
+ notes.current ??= sharedNoteQueue(draftKey, {
+ write: async (text) => {
+ const selected = JSON.parse(choiceKey) as SubSelection;
+ await resource.write(async () => {
+ const fresh = await resource.refresh();
+ const list = modelSub(fresh);
+ if (!list.choices.some((entry) => subChoiceKey(entry) === choiceKey)) return;
+ await setModelSub(client, scope, fresh, setSubNote(list, selected, text));
+ });
+ },
+ onSaved: (text) => {
+ forgetFailedNote(draftKey);
+ setNoteError(undefined);
+ setNote((current) => (current === text ? undefined : current));
+ models.refresh();
+ },
+ onError: (cause, text) => {
+ const error = errorText(cause);
+ rememberFailedNote(draftKey, { text, error });
+ setNoteError(error);
+ },
+ });
+ const leave = useRef<() => void>(() => undefined);
+ useFocusEffect(useCallback(() => () => leave.current(), []));
+ const view =
+ value === undefined || choice === undefined ? undefined : subChoiceView(value, choice, engines);
+ const page = (body: React.ReactNode) => (
+ {body}
+ );
+ if (value === undefined || sub === undefined)
+ return page(
+ models.error === undefined ? (
+
+ ) : (
+
+ ),
+ );
+ if (choice === undefined || view === undefined)
+ return page({t.subChoices.followsMainHint});
+ const selection = subSelectionOf(choice);
+ const target = subChoiceTarget(choice);
+ const efforts = subEffortOptions(value, target, engines);
+ const effortIds = efforts?.options.map((entry) => entry.id) ?? [];
+ const stale = staleGroupEfforts(choice, effortIds);
+ const hasEffort = efforts !== undefined && efforts.options.length > 0;
+ const isDefault = sub.default !== null && matchesPresetSubChoice(choice, sub.default);
+ const save = (next: typeof sub, done?: () => void) =>
+ models.run(() => setModelSub(client, scope, value, next), done);
+ const openEffort = () => {
+ const params = { field: 'sub-effort', ...subChoiceTargetParams(target) };
+ if (scope.kind === 'bot')
+ router.push({
+ pathname: '/bot/[slug]/model-picker',
+ params: { slug: scope.slug, ...params },
+ });
+ else
+ router.push({
+ pathname: '/settings/model-picker',
+ params: { ...params, ...(scope.kind === 'preset' ? { id: scope.id } : {}) },
+ });
+ };
+ const shownNote = note ?? choice.note ?? '';
+ const commitNote = () => {
+ const queue = notes.current;
+ if (note === undefined || queue === undefined) return;
+ if (commitNoteDraft(queue, draftKey, note, choice.note ?? '') === 'restored')
+ setNoteError(undefined);
+ };
+ leave.current = commitNote;
+ return page(
+
+ {models.error === undefined ? null : {models.error}}
+ {noteError === undefined ? null : {noteError}}
+ {models.busy ? : null}
+
+ {hasEffort || stale ? (
+
+ {efforts === undefined || efforts.options.length === 0 ? null : (
+ entry.id === efforts.effort)?.name ??
+ efforts.effort)
+ }
+ disclosure
+ onPress={models.busy ? undefined : openEffort}
+ />
+ )}
+ {stale ? (
+ save(setSubEffort(sub, selection, '', effortIds))
+ }
+ />
+ ) : null}
+
+ ) : null}
+
+
+ {isDefault ? null : (
+ save(setSubDefault(sub, selection))}
+ />
+ )}
+ save(removeSubChoice(sub, selection), () => router.back())
+ }
+ />
+
+
+ ,
+ );
+}
diff --git a/apps/mobile/src/ui/chat/sub-choice-section.tsx b/apps/mobile/src/ui/chat/sub-choice-section.tsx
new file mode 100644
index 0000000000..7ad035a06b
--- /dev/null
+++ b/apps/mobile/src/ui/chat/sub-choice-section.tsx
@@ -0,0 +1,109 @@
+import { View } from 'react-native';
+
+import {
+ modelSub,
+ subInherited,
+ type ModelSettingsState,
+} from '@botharness/host-client/model-settings';
+import { type SubChoice } from '@botharness/host-client/preset-sub';
+import { matchesPresetSubChoice } from '@botharness/host-protocol/preset-sub';
+import type { RoutingGroupEngineOptions } from '@botharness/host-protocol/subscription-engine';
+
+import { useDesignTheme } from '../design/theme';
+import { radius, space } from '../design/tokens';
+import { SettingsRow, SettingsSection } from '../primitives/settings-row';
+import { Text } from '../primitives/text';
+import { useStrings } from '../strings';
+import { ModelTargetIcon } from './model-target-icon';
+import { SHEET_GROUP } from './sheet';
+import { subChoiceKey, subChoiceView } from './sub-choice-text';
+
+export function SubChoiceSection({
+ value,
+ engines,
+ busy,
+ onOpen,
+ onAdd,
+}: {
+ value: ModelSettingsState;
+ engines?: readonly RoutingGroupEngineOptions[] | undefined;
+ busy: boolean;
+ onOpen(choice: SubChoice): void;
+ onAdd(): void;
+}) {
+ const t = useStrings();
+ const theme = useDesignTheme();
+ const sub = modelSub(value);
+ const tag = (
+
+
+ {t.routingGroup.defaultTag}
+
+
+ );
+ return (
+
+ {sub.choices.length === 0 ? (
+
+ ) : (
+ sub.choices.map((choice) => {
+ const view = subChoiceView(value, choice, engines);
+ const isDefault = sub.default !== null && matchesPresetSubChoice(choice, sub.default);
+ return (
+
+ }
+ {...(isDefault ? { trailing: tag } : {})}
+ accessibilityLabel={[
+ view.title,
+ isDefault ? t.routingGroup.defaultTag : undefined,
+ view.detail,
+ ]
+ .filter(Boolean)
+ .join(', ')}
+ disclosure
+ onPress={busy ? undefined : () => onOpen(choice)}
+ />
+ );
+ })
+ )}
+
+
+ );
+}
diff --git a/apps/mobile/src/ui/chat/sub-choice-text.ts b/apps/mobile/src/ui/chat/sub-choice-text.ts
new file mode 100644
index 0000000000..b221140752
--- /dev/null
+++ b/apps/mobile/src/ui/chat/sub-choice-text.ts
@@ -0,0 +1,114 @@
+import { sameModel } from '@botharness/host-client/bot-settings';
+import {
+ engineCatalogModel,
+ modelCatalogGroupEfforts,
+ modelCatalogGroupFront,
+ routingGroupEngineChoices,
+ routingGroupEnginePresentation,
+} from '@botharness/host-client/model-catalog';
+import type {
+ AssignmentEffortTarget,
+ ModelSettingsState,
+} from '@botharness/host-client/model-settings';
+import { subSelectionOf, type SubChoice } from '@botharness/host-client/preset-sub';
+import type { ModelBrand } from '@botharness/host-client/shared/model-brand';
+import type { RoutingGroupEngineOptions } from '@botharness/host-protocol/subscription-engine';
+
+import { t } from '../strings';
+import { modelEntryLabel } from './composer-labels';
+
+export function subChoiceKey(choice: SubChoice): string {
+ return JSON.stringify(subSelectionOf(choice));
+}
+
+export function subChoiceTarget(choice: SubChoice): AssignmentEffortTarget {
+ if (choice.kind === 'group') return { kind: 'group', id: choice.group };
+ const selection = subSelectionOf(choice);
+ return selection.kind === 'group' ? { kind: 'group', id: selection.group } : selection;
+}
+
+export interface SubChoiceView {
+ title: string;
+ detail: string;
+ brand: ModelBrand | undefined;
+ external: boolean;
+}
+
+function effortName(efforts: readonly { id: string; name: string }[], effort: string | undefined) {
+ if (effort === undefined || effort === '') return t.modelSettings.providerDefault;
+ return efforts.find((entry) => entry.id === effort)?.name ?? effort;
+}
+
+export function subChoiceView(
+ value: ModelSettingsState,
+ choice: SubChoice,
+ engines: readonly RoutingGroupEngineOptions[] = [],
+): SubChoiceView {
+ switch (choice.kind) {
+ case 'model': {
+ const entry = value.models.find((item) => sameModel(item, choice));
+ return {
+ title: entry?.modelName ?? choice.model,
+ detail: [
+ entry?.providerName ?? choice.provider,
+ effortName(entry?.efforts ?? [], choice.defaultEffort),
+ ].join(' · '),
+ brand: entry === undefined ? undefined : modelEntryLabel(entry).brand,
+ external: false,
+ };
+ }
+ case 'group': {
+ const group = value.groups?.find((item) => item.id === choice.group);
+ const front =
+ group === undefined
+ ? undefined
+ : value.models.find((item) =>
+ sameModel(item, modelCatalogGroupFront(group, value.models)),
+ );
+ return {
+ title: group?.name ?? choice.group,
+ detail: [
+ front === undefined ? undefined : t.modelSettings.groupFront(front.modelName),
+ effortName(
+ group === undefined ? [] : modelCatalogGroupEfforts(group, value.models),
+ choice.defaultEffort,
+ ),
+ ]
+ .filter(Boolean)
+ .join(' · '),
+ brand: front === undefined ? undefined : modelEntryLabel(front).brand,
+ external: false,
+ };
+ }
+ case 'engine': {
+ const accounts = engines.filter(
+ (entry) =>
+ entry.available &&
+ entry.engine === choice.engine &&
+ (choice.accountId === undefined || entry.accountId === choice.accountId),
+ );
+ const model =
+ choice.model === undefined
+ ? routingGroupEngineChoices(accounts).find((entry) => entry.isDefault)?.model
+ : engineCatalogModel(accounts, { engine: choice.engine, model: choice.model });
+ const account = accounts.find((entry) => entry.accountId === choice.accountId)?.accountName;
+ const view = routingGroupEnginePresentation(
+ {
+ kind: 'engine',
+ engine: choice.engine,
+ ...(choice.model === undefined ? {} : { model: choice.model }),
+ ...(choice.accountId === undefined ? {} : { accountId: choice.accountId }),
+ },
+ t.routingGroup.engineRow,
+ model?.name,
+ account,
+ );
+ return {
+ title: view.title,
+ detail: [view.detail, effortName(model?.efforts ?? [], choice.effort)].join(' · '),
+ brand: view.brand,
+ external: true,
+ };
+ }
+ }
+}
diff --git a/apps/mobile/src/ui/settings-view.tsx b/apps/mobile/src/ui/settings-view.tsx
index 5e4730cb22..57ca0d69ed 100644
--- a/apps/mobile/src/ui/settings-view.tsx
+++ b/apps/mobile/src/ui/settings-view.tsx
@@ -52,7 +52,7 @@ export function SettingsView({
-
+
diff --git a/apps/mobile/test/settings-sheet.test.tsx b/apps/mobile/test/settings-sheet.test.tsx
index 2f31b60e4f..1c89e6361b 100644
--- a/apps/mobile/test/settings-sheet.test.tsx
+++ b/apps/mobile/test/settings-sheet.test.tsx
@@ -89,7 +89,7 @@ describe('Settings sheet', () => {
[t.notifications, 'onNotifications'],
[`${t.storage.title}, ${t.storage.hint}`, 'onStorage'],
[`${t.modelProviders.title}, ${t.modelProviders.hint}`, 'onModelProviders'],
- [`${t.modelSettings.title}, ${t.modelSettings.global}`, 'onModels'],
+ [`${t.modelConfig.title}, ${t.modelConfig.rowHint}`, 'onModels'],
];
for (const [label, action] of rows) {
await act(async () => button(view, label)!.click());
diff --git a/apps/mobile/test/sub-choice-notes.test.ts b/apps/mobile/test/sub-choice-notes.test.ts
new file mode 100644
index 0000000000..49dbbcc276
--- /dev/null
+++ b/apps/mobile/test/sub-choice-notes.test.ts
@@ -0,0 +1,216 @@
+import { expect, it, vi } from 'vitest';
+
+import {
+ commitNoteDraft,
+ failedNote,
+ forgetFailedNote,
+ noteQueue,
+ pendingNote,
+ rememberFailedNote,
+ sharedNoteQueue,
+} from '../src/ui/chat/sub-choice-notes';
+
+function deferred() {
+ let resolve: () => void = () => undefined;
+ const promise = new Promise((done) => {
+ resolve = done;
+ });
+ return { promise, resolve };
+}
+
+it('saves a cleared draft committed while an earlier note write is pending', async () => {
+ const first = deferred();
+ const written: string[] = [];
+ const saved = vi.fn();
+ const queue = noteQueue(
+ async (text) => {
+ written.push(text);
+ if (text === 'A') await first.promise;
+ },
+ saved,
+ vi.fn(),
+ );
+ expect(queue.commit('A', '')).toBe(true);
+ expect(queue.commit('', '')).toBe(true);
+ first.resolve();
+ await queue.settled();
+ expect(written).toEqual(['A', '']);
+ expect(saved.mock.calls).toEqual([['A'], ['']]);
+});
+
+it('skips a repeated commit of the queued text and retries after a failed write', async () => {
+ const written: string[] = [];
+ let fail = true;
+ const failed = vi.fn();
+ const queue = noteQueue(
+ async (text) => {
+ written.push(text);
+ if (fail) {
+ fail = false;
+ throw new Error('stale');
+ }
+ },
+ vi.fn(),
+ failed,
+ );
+ expect(queue.commit('A', '')).toBe(true);
+ expect(queue.commit('A', '')).toBe(false);
+ await queue.settled();
+ expect(failed).toHaveBeenCalledOnce();
+ expect(queue.commit('A', '')).toBe(true);
+ await queue.settled();
+ expect(written).toEqual(['A', 'A']);
+});
+
+it('keeps a failed draft for the next visit and clears it after a successful retry', async () => {
+ const key = 'preset:default:{"kind":"model","provider":"p","model":"m"}';
+ let fail = true;
+ const visit = () =>
+ noteQueue(
+ async () => {
+ if (fail) throw new Error('offline');
+ },
+ () => forgetFailedNote(key),
+ (cause, text) => rememberFailedNote(key, { text, error: (cause as Error).message }),
+ );
+ const first = visit();
+ first.commit('Draft', '');
+ await first.settled();
+ expect(failedNote(key)).toEqual({ text: 'Draft', error: 'offline' });
+ fail = false;
+ const second = visit();
+ second.commit(failedNote(key)!.text, '');
+ await second.settled();
+ expect(failedNote(key)).toBeUndefined();
+});
+
+it('clears an older failed draft when a newer note saves', async () => {
+ const key = 'host-a:preset:default:x';
+ const queue = noteQueue(
+ async (text) => {
+ if (text === 'A') throw new Error('stale');
+ },
+ () => forgetFailedNote(key),
+ (cause, text) => rememberFailedNote(key, { text, error: (cause as Error).message }),
+ );
+ queue.commit('A', '');
+ await queue.settled();
+ expect(failedNote(key)).toEqual({ text: 'A', error: 'stale' });
+ queue.commit('B', '');
+ await queue.settled();
+ expect(failedNote(key)).toBeUndefined();
+ expect(failedNote('host-b:preset:default:x')).toBeUndefined();
+});
+
+it('keeps commit order across visits so a later failure is not cleared by an older success', async () => {
+ const key = 'host-a:bot:ada:y';
+ let finishA: () => void = () => undefined;
+ const written: string[] = [];
+ const handlers = () => ({
+ write: async (text: string) => {
+ written.push(text);
+ if (text === 'A') await new Promise((resolve) => (finishA = resolve));
+ if (text === 'C') throw new Error('stale');
+ },
+ onSaved: () => forgetFailedNote(key),
+ onError: (cause: unknown, text: string) =>
+ rememberFailedNote(key, { text, error: (cause as Error).message }),
+ });
+ const firstVisit = sharedNoteQueue(key, handlers());
+ firstVisit.commit('A', '');
+ firstVisit.commit('B', '');
+ const secondVisit = sharedNoteQueue(key, handlers());
+ secondVisit.commit('C', '');
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ finishA();
+ await secondVisit.settled();
+ expect(written).toEqual(['A', 'B', 'C']);
+ expect(failedNote(key)).toEqual({ text: 'C', error: 'stale' });
+});
+
+it('does not keep a failed draft that a newer pending note supersedes', async () => {
+ const key = 'host-a:preset:p:z';
+ let finishB: () => void = () => undefined;
+ const queue = sharedNoteQueue(key, {
+ write: async (text) => {
+ if (text === 'A') throw new Error('stale');
+ await new Promise((resolve) => (finishB = resolve));
+ },
+ onSaved: () => forgetFailedNote(key),
+ onError: (cause, text) => rememberFailedNote(key, { text, error: (cause as Error).message }),
+ });
+ queue.commit('A', '');
+ queue.commit('B', '');
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(failedNote(key)).toBeUndefined();
+ finishB();
+ await queue.settled();
+ expect(failedNote(key)).toBeUndefined();
+});
+
+it('keeps the failure of the latest commit when the same text was committed twice', async () => {
+ const key = 'host-a:preset:p:aba';
+ const written: string[] = [];
+ const queue = noteQueue(
+ async (text) => {
+ written.push(text);
+ if (text === 'A') throw new Error('stale');
+ },
+ () => forgetFailedNote(key),
+ (cause, text) => rememberFailedNote(key, { text, error: (cause as Error).message }),
+ );
+ expect(queue.commit('A', '')).toBe(true);
+ expect(queue.commit('B', '')).toBe(true);
+ expect(queue.commit('A', '')).toBe(true);
+ await queue.settled();
+ expect(written).toEqual(['A', 'B', 'A']);
+ expect(failedNote(key)).toEqual({ text: 'A', error: 'stale' });
+});
+
+it('accepts a note again after it saved and another client changed it', async () => {
+ const queue = noteQueue(async () => undefined, vi.fn(), vi.fn());
+ expect(queue.commit('A', '')).toBe(true);
+ await queue.settled();
+ expect(queue.commit('A', 'B')).toBe(true);
+});
+
+it('restores the newer pending note, not an older failed draft, when the page reopens', async () => {
+ const key = 'host-a:preset:p:reopen';
+ let finishB: () => void = () => undefined;
+ const handlers = {
+ write: async (text: string) => {
+ if (text === 'A') throw new Error('stale');
+ await new Promise((resolve) => (finishB = resolve));
+ },
+ onSaved: () => forgetFailedNote(key),
+ onError: (cause: unknown, text: string) =>
+ rememberFailedNote(key, { text, error: (cause as Error).message }),
+ };
+ const firstVisit = sharedNoteQueue(key, handlers);
+ firstVisit.commit('A', '');
+ await firstVisit.settled();
+ expect(failedNote(key)?.text).toBe('A');
+ if (firstVisit.commit('B', '')) forgetFailedNote(key);
+ expect(failedNote(key)).toBeUndefined();
+ expect(pendingNote(key) ?? failedNote(key)?.text).toBe('B');
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ finishB();
+ await firstVisit.settled();
+ expect(pendingNote(key)).toBeUndefined();
+});
+
+it('drops a failed draft when the note is changed back to the saved text', async () => {
+ const key = 'host-a:preset:p:restore';
+ const queue = sharedNoteQueue(key, {
+ write: async (text) => {
+ if (text === 'A') throw new Error('stale');
+ },
+ onSaved: () => forgetFailedNote(key),
+ onError: (cause, text) => rememberFailedNote(key, { text, error: (cause as Error).message }),
+ });
+ expect(commitNoteDraft(queue, key, 'A', 'B')).toBe('queued');
+ await queue.settled();
+ expect(failedNote(key)?.text).toBe('A');
+ expect(commitNoteDraft(queue, key, 'B', 'B')).toBe('restored');
+ expect(failedNote(key)).toBeUndefined();
+});
diff --git a/apps/mobile/test/sub-choice-section.test.tsx b/apps/mobile/test/sub-choice-section.test.tsx
new file mode 100644
index 0000000000..30a11f549e
--- /dev/null
+++ b/apps/mobile/test/sub-choice-section.test.tsx
@@ -0,0 +1,141 @@
+// @vitest-environment jsdom
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, expect, it, vi } from 'vitest';
+vi.mock('expo-symbols', () => ({ SymbolView: () => null }));
+vi.mock('../src/ui/primitives/row-icon', () => ({ RowIcon: () => null }));
+vi.mock('react-native', async () => await import('./react-native-shim'));
+vi.mock('react-native-svg', () => ({ default: () => null, Path: () => null, SvgXml: () => null }));
+vi.mock('../src/ui/chat/sheet', () => ({ SHEET_GROUP: 'raised' }));
+
+import type { ModelSettingsState } from '@botharness/host-client/model-settings';
+import type { SubChoices } from '@botharness/host-client/preset-sub';
+import { SubChoiceSection } from '../src/ui/chat/sub-choice-section';
+import { subChoiceView } from '../src/ui/chat/sub-choice-text';
+import { t } from '../src/ui/strings';
+
+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+
+let root: Root | undefined;
+let host: HTMLElement | undefined;
+afterEach(() => {
+ act(() => root?.unmount());
+ host?.remove();
+ root = undefined;
+});
+
+const flash = {
+ provider: 'deepseek',
+ providerName: 'DeepSeek',
+ model: 'flash',
+ modelName: 'Flash',
+ efforts: [{ id: 'high', name: 'High' }],
+};
+const pro = { provider: 'deepseek', providerName: 'DeepSeek', model: 'pro', modelName: 'Pro' };
+const group = { id: 'fast', name: 'Fast group', revision: 1, routes: [flash] };
+
+function state(
+ sub: SubChoices | undefined,
+ presets: ModelSettingsState['presets'] = [],
+): ModelSettingsState {
+ return {
+ revision: 1,
+ models: [flash, pro],
+ groups: [group],
+ presets,
+ ...(sub === undefined
+ ? {}
+ : {
+ plan: {
+ revision: 2,
+ sourcePresetId: '',
+ sourcePresetName: '',
+ orchestrator: { provider: 'deepseek', model: 'pro' },
+ sub,
+ },
+ }),
+ };
+}
+
+async function render(value: ModelSettingsState) {
+ const onOpen = vi.fn();
+ const onAdd = vi.fn();
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ await act(async () =>
+ root!.render(),
+ );
+ return { view: host, onOpen, onAdd };
+}
+
+const row = (view: HTMLElement, id: string) =>
+ view.querySelector(`[data-testid="${id}"]`);
+
+it('lists each choice with its source and effort, marks the default and opens a choice', async () => {
+ const sub: SubChoices = {
+ choices: [
+ {
+ kind: 'model',
+ provider: 'deepseek',
+ model: 'flash',
+ allowedEfforts: ['', 'high'],
+ defaultEffort: 'high',
+ },
+ { kind: 'group', group: 'fast' },
+ ],
+ default: { kind: 'group', group: 'fast' },
+ };
+ const { view, onOpen, onAdd } = await render(state(sub));
+ expect(view.textContent).toContain('Flash');
+ expect(view.textContent).toContain('DeepSeek · High');
+ expect(view.textContent).toContain('Fast group');
+ const groupRow = [...view.querySelectorAll('[role="button"]')].find((node) =>
+ node.getAttribute('aria-label')?.startsWith('Fast group'),
+ );
+ expect(groupRow?.getAttribute('aria-label')).toContain(t.routingGroup.defaultTag);
+ await act(async () => (groupRow as HTMLElement).click());
+ expect(onOpen).toHaveBeenCalledWith({ kind: 'group', group: 'fast' });
+ await act(async () => row(view, 'sub-choice-add')!.click());
+ expect(onAdd).toHaveBeenCalledOnce();
+});
+
+it('shows the follows-main row for an empty list and the inherited note for a Bot without its own list', async () => {
+ const own = await render(state({ choices: [], default: null }));
+ expect(row(own.view, 'sub-choice-follows-main')).not.toBeNull();
+ expect(own.view.textContent).toContain(t.subChoices.hint);
+ act(() => root?.unmount());
+ host?.remove();
+ const inherited = await render(
+ state(undefined, [
+ {
+ id: 'default',
+ name: 'Default',
+ revision: 1,
+ orchestrator: { provider: 'deepseek', model: 'pro' },
+ assignmentDefault: { provider: 'deepseek', model: 'flash' },
+ },
+ ]),
+ );
+ expect(inherited.view.textContent).toContain(t.subChoices.inherited);
+ expect(inherited.view.textContent).toContain('Flash');
+});
+
+it('names engine choices from the loaded account catalog', () => {
+ const view = subChoiceView(
+ state({ choices: [], default: null }),
+ { kind: 'engine', engine: 'codex', accountId: 'work', model: 'gpt-6', effort: 'high' },
+ [
+ {
+ engine: 'codex',
+ accountId: 'work',
+ accountName: 'Work',
+ available: true,
+ models: [{ id: 'gpt-6', name: 'GPT-6', efforts: [{ id: 'high', name: 'High' }] }],
+ },
+ ],
+ );
+ expect(view.external).toBe(true);
+ expect(view.detail).toContain('Work');
+ expect(view.detail).toContain('High');
+});
diff --git a/packages/host-client/src/model-settings.ts b/packages/host-client/src/model-settings.ts
index bcc86fea4a..fc783f49c9 100644
--- a/packages/host-client/src/model-settings.ts
+++ b/packages/host-client/src/model-settings.ts
@@ -83,6 +83,7 @@ export function modelScopeKey(scope: ModelScope): string {
const owners = new WeakMap();
const modelSettingsKey = ['mobile-model-settings'];
+const writeChains = new WeakMap>>();
const favoriteWriters = new WeakMap<
ModelSettingsClient,
(choice: ModelChoice, favorite: boolean) => Promise
@@ -109,14 +110,27 @@ export function modelSettingsResource(client: ModelSettingsClient, scope: ModelS
const queryKey = [...modelSettingsKey, modelScopeKey(scope)];
return {
peek: () => owner.getQueryData(queryKey),
- write: async (work: () => Promise) => {
- await owner.cancelQueries({ queryKey, exact: true });
- await work();
- await owner.cancelQueries({ queryKey, exact: true });
- await owner.invalidateQueries({
- queryKey: modelSettingsKey,
- refetchType: 'none',
+ write: (work: () => Promise) => {
+ const scopeKey = modelScopeKey(scope);
+ let chains = writeChains.get(owner);
+ if (chains === undefined) {
+ chains = new Map();
+ writeChains.set(owner, chains);
+ }
+ const current = (chains.get(scopeKey) ?? Promise.resolve()).then(async () => {
+ await owner.cancelQueries({ queryKey, exact: true });
+ await work();
+ await owner.cancelQueries({ queryKey, exact: true });
+ await owner.invalidateQueries({
+ queryKey: modelSettingsKey,
+ refetchType: 'none',
+ });
});
+ chains.set(
+ scopeKey,
+ current.catch(() => undefined),
+ );
+ return current;
},
favorite: async (choice: ModelChoice, favorite: boolean) => {
const favorites = await writeFavorite(client)(choice, favorite);
diff --git a/packages/host-client/test/model-settings-sub.test.ts b/packages/host-client/test/model-settings-sub.test.ts
index 152d3e4dca..383d0eee05 100644
--- a/packages/host-client/test/model-settings-sub.test.ts
+++ b/packages/host-client/test/model-settings-sub.test.ts
@@ -372,3 +372,34 @@ it('returns the stored effort and matching catalog choices for each selected sou
});
expect(subEffortOptions(active, { ...engine, accountId: 'personal' })).toBeUndefined();
});
+
+it('runs writes for the same scope one after another, even after a failure', async () => {
+ const host = { call: vi.fn(async () => ({})) };
+ const resource = modelSettingsResource(host, { kind: 'bot', slug: 'serial' });
+ const order: string[] = [];
+ let finishFirst: () => void = () => undefined;
+ const first = resource.write(
+ () =>
+ new Promise((resolve) => {
+ order.push('first start');
+ finishFirst = () => {
+ order.push('first end');
+ resolve();
+ };
+ }),
+ );
+ const failing = resource.write(async () => {
+ order.push('second');
+ throw new Error('stale');
+ });
+ const third = modelSettingsResource(host, { kind: 'bot', slug: 'serial' }).write(async () => {
+ order.push('third');
+ });
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ expect(order).toEqual(['first start']);
+ finishFirst();
+ await first;
+ await expect(failing).rejects.toThrow('stale');
+ await third;
+ expect(order).toEqual(['first start', 'first end', 'second', 'third']);
+});