diff --git a/packages/client/src/client/remote-host-models.tsx b/packages/client/src/client/remote-host-models.tsx index 16e1b67ccc..7485167b87 100644 --- a/packages/client/src/client/remote-host-models.tsx +++ b/packages/client/src/client/remote-host-models.tsx @@ -1,10 +1,8 @@ -import { Checkbox } from './ds/checkbox.js'; import { useMemo, useRef, useState } from 'react'; import { hostSettingsDrafts } from './host-settings-drafts.js'; import * as stylex from '@stylexjs/stylex'; import { - sameModel, HostAnswerInvalid, type ModelRoute, type ModelSettingsClient, @@ -16,8 +14,8 @@ import { saveModelPreset, setModelGroup, setModelRoute, - toggleAssignmentGroup, - toggleAssignmentModel, + modelSub, + setModelSub, type ModelScope, type ModelSettingsState, } from '@botharness/host-client/model-settings'; @@ -28,21 +26,17 @@ import { Select } from './ds/select.js'; import { SettingsRow } from './ds/settings-row.js'; import { space } from './ds/tokens.stylex.js'; import type { BotHarnessTranslate } from './locale.js'; -import { - groupFrontHint, - groupMenuId, - groupMenuKey, - groupMenuItems, - modelMenuItems, - type ModelMenuFavorites, -} from './model-menu.js'; +import { groupMenuId, groupMenuKey, type ModelMenuFavorites } from './model-menu.js'; import { ModelPicker } from './model-picker.js'; -import { ModelTrigger } from './model-trigger.js'; +import { modelOptionsOf } from './model-plan-editor.js'; +import { SubChoiceList } from './sub-choice-list.js'; +import type { SubChoices } from '@botharness/host-client/preset-sub'; import { useMountedResource } from './mounted-resource.js'; const styles = stylex.create({ stack: { display: 'flex', flexDirection: 'column', gap: space.x5, minWidth: 0 }, choices: { display: 'flex', flexDirection: 'column', gap: space.x3 }, + actions: { display: 'flex', gap: space.x2 }, }); type HostModelScope = Exclude; @@ -152,6 +146,7 @@ function Models({ const [error, setError] = useState>(); const [busy, setBusy] = useState(false); const [name, setName] = useState(); + const [subDraft, setSubDraft] = useState<{ sub: SubChoices; base: ModelSettingsState }>(); const [creation, setCreation] = useState({ kind: 'idle' }); const creationOwner = useRef(creation); const generation = useRef(0); @@ -198,8 +193,8 @@ function Models({ if (generation.current === request) setBusy(false); } }; - const savePresetDraft = async () => { - if (name === undefined || value === undefined || pending.current || !available) return false; + const savePresetDraft = async (state: ModelSettingsState | undefined = value) => { + if (name === undefined || state === undefined || pending.current || !available) return false; if (scope.kind === 'global' && creationOwner.current.kind === 'unknown') return false; const request = generation.current + 1; const record = (outcome: PresetCreation) => { @@ -209,11 +204,11 @@ function Models({ return run( async () => { if (scope.kind === 'preset') { - await saveModelPreset(client, value, name, true); + await saveModelPreset(client, state, name, true); } else if (creationOwner.current.kind === 'idle') { record({ kind: 'pending' }); try { - const id = await saveModelPreset(client, value, name, false); + const id = await saveModelPreset(client, state, name, false); record({ kind: 'receipt', id }); } catch (cause) { if ( @@ -263,30 +258,42 @@ function Models({ return; void savePresetDraft(); }; - const draft = useRef({ name, value, scope, available, savePresetDraft }); - draft.current = { name, value, scope, available, savePresetDraft }; + const saveSubDraft = async () => { + const pendingDraft = draft.current.subDraft; + if (pendingDraft === undefined) return true; + return run(async () => { + await setModelSub(client, scope, pendingDraft.base, pendingDraft.sub); + if (draft.current.subDraft === pendingDraft) draft.current.subDraft = undefined; + setSubDraft((current) => (current === pendingDraft ? undefined : current)); + }); + }; + const draft = useRef({ name, value, scope, available, savePresetDraft, subDraft, saveSubDraft }); + draft.current = { name, value, scope, available, savePresetDraft, subDraft, saveSubDraft }; const draftMount = useMountedResource( () => hostSettingsDrafts.register(hostId, { dirty: () => - draft.current.name !== undefined && - (draft.current.scope.kind === 'global' - ? draft.current.name !== '' - : draft.current.name.trim() !== draft.current.value?.preset?.name), + draft.current.subDraft !== undefined || + (draft.current.name !== undefined && + (draft.current.scope.kind === 'global' + ? draft.current.name !== '' + : draft.current.name.trim() !== draft.current.value?.preset?.name)), async save() { - const { name, value, savePresetDraft } = draft.current; - if ( - name === undefined || - value === undefined || - pending.current || - !draft.current.available - ) - return false; + const { name, value, savePresetDraft, subDraft: tasks, saveSubDraft } = draft.current; + if (value === undefined || pending.current || !draft.current.available) return false; + if (tasks !== undefined) { + if (!(await saveSubDraft())) return false; + if (name === undefined || name.trim() === value.preset?.name) return true; + return savePresetDraft(await resource.refresh()); + } + if (name === undefined) return false; return savePresetDraft(); }, discard: () => { draft.current.name = undefined; + draft.current.subDraft = undefined; setName(undefined); + setSubDraft(undefined); }, }), [hostId, client, resource], @@ -426,90 +433,34 @@ function Models({ /> {picker('orchestrator', routes?.orchestrator)} {scope.kind !== 'preset' ? null : ( - <> - {picker('assignment', routes?.assignmentDefault)} -
- - item.group !== undefined && - !routes?.groups.assignmentGroups?.includes(item.group), - ) - .map((item) => ({ ...item, disabled: false })), - ...modelMenuItems( - value.models - .filter( - (entry) => - entry.credential === undefined && - !routes?.assignmentModels.some((option) => sameModel(option, entry)), - ) - .map((entry) => ({ - value: JSON.stringify([entry.provider, entry.model]), - label: entry.modelName, - hint: entry.providerName, - })), - catalog, - ), - ]} - label={t('modelPreset.allowedTitle')} - placeholder={t('modelPreset.chooseModel')} - disabled={busy || !available || routes?.assignmentDefault === undefined} - favoriteSource={favoriteSource} - t={t} - onSelect={(key) => { - const group = groupMenuId(key); - if (group !== undefined) { - void run(() => toggleAssignmentGroup(client, scope, value, group)); - return; - } - const entry = value.models.find( - (item) => JSON.stringify([item.provider, item.model]) === key, - ); - if (entry !== undefined) - void run(() => toggleAssignmentModel(client, scope, value, entry)); - }} - /> - {routes?.groups.assignmentGroups?.map((id) => { - const group = catalogGroups.find((entry) => entry.id === id); - const frontHint = groupFrontHint(group, catalog, t); - const note = routes.groups.assignmentGroupOptions?.find( - (option) => option.group === id, - )?.note; - return ( - - void run(() => toggleAssignmentGroup(client, scope, value, id)) - } - /> - ); - })} - {routes?.assignmentModels.map((option) => ( - { - const entry = value.models.find((item) => sameModel(item, option)); - if (entry !== undefined) - void run(() => toggleAssignmentModel(client, scope, value, entry)); +
+ + setSubDraft((current) => ({ sub, base: current?.base ?? value })) + } + t={t} + /> + {subDraft === undefined ? null : ( +
+ { + void saveSubDraft(); }} - /> - ))} -
- + > + {t('relationships.save')} + + setSubDraft(undefined)}> + {t('common.cancel')} + +
+ )} +
)} { + if (root !== undefined) await act(async () => root!.unmount()); + root = undefined; + document.body.innerHTML = ''; +}); + +const flash = { provider: 'deepseek', model: 'flash' }; +const pro = { provider: 'deepseek', model: 'pro' }; +const flashChoice = { kind: 'model', ...flash, allowedEfforts: [''], defaultEffort: '' }; + +async function flush() { + for (let i = 0; i < 6; i += 1) await act(async () => new Promise((r) => setTimeout(r, 0))); +} + +async function open( + hostId: string, + onWrite: (args: { sub: PresetSub; expectedRevision: number }) => unknown, +) { + Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); + const host = new FakeHost(); + const client = createHostClient({ + routes: [`https://${hostId}.example.ts.net`], + credential: host.credential, + carrier: host.carrier, + }); + const state = { + revision: 4, + sub: { choices: [flashChoice], default: { kind: 'model', ...flash } } as unknown, + }; + host.methods.set('modelCatalog', () => ({ + models: [ + { ...flash, providerName: 'DeepSeek', modelName: 'Flash' }, + { ...pro, providerName: 'DeepSeek', modelName: 'Pro' }, + ], + default: flash, + defaultRevision: 1, + })); + host.methods.set('modelPresets', () => ({ + presets: [ + { + id: 'daily', + name: 'Daily', + revision: state.revision, + orchestrator: flash, + assignmentDefault: flash, + sub: state.sub, + }, + ], + })); + host.methods.set('modelPresetSubSet', (args) => { + const { sub, expectedRevision } = args as Record; + if (!isPresetSub(sub) || typeof expectedRevision !== 'number') + throw new Error('Malformed modelPresetSubSet request'); + const custom = onWrite({ sub, expectedRevision }); + if (custom !== undefined) return custom; + state.revision += 1; + state.sub = sub; + return { id: 'daily', revision: state.revision, sub }; + }); + const container = document.createElement('div'); + document.body.append(container); + root = createRoot(container); + await act(async () => + root!.render(createElement(RemoteHostModels, { hostId, client, t: translate })), + ); + await flush(); + await act(async () => container.querySelector('[aria-label="Models"]')!.click()); + await flush(); + const option = [...document.querySelectorAll('[tabindex="-1"]')].find( + (node) => node.textContent === 'Daily', + ); + await act(async () => option!.click()); + await flush(); + const save = () => + act(async () => + [...container.querySelectorAll('button')] + .find((node) => node.textContent === 'Save')! + .click(), + ); + return { host, state, container, save }; +} + +const writes = (host: FakeHost) => host.calls.filter((call) => call.method === 'modelPresetSubSet'); + +it('saves an edited Task model list once and shows the saved list', async () => { + const { host, container, save } = await open('one', () => undefined); + await choose('Add a task model', 'pro', 'Pro'); + expect(writes(host)).toHaveLength(0); + await save(); + await flush(); + expect(writes(host)).toHaveLength(1); + expect(writes(host)[0]?.args).toMatchObject({ + id: 'daily', + expectedRevision: 4, + sub: { + choices: [flashChoice, { kind: 'model', ...pro }], + default: { kind: 'model', ...flash }, + }, + }); + expect(container.textContent).toContain('Pro'); + expect( + [...container.querySelectorAll('button')].some((node) => node.textContent === 'Cancel'), + ).toBe(false); +}); + +it('retries a failed save at the revision the draft started from', async () => { + let fail = true; + const { host, state, save } = await open('two', () => { + if (!fail) return undefined; + fail = false; + state.revision = 5; + throw Object.assign(new Error('changed'), { code: 'stale-setting' }); + }); + await choose('Add a task model', 'pro', 'Pro'); + await save(); + await flush(); + await save(); + await flush(); + expect( + writes(host).map((call) => (call.args as { expectedRevision: number }).expectedRevision), + ).toEqual([4, 4]); +}); + +it('counts a Task model edit as an unsaved Host settings draft and discards it', async () => { + const { container } = await open('three', () => undefined); + expect(hostSettingsDrafts.hasDirty('three')).toBe(false); + await choose('Add a task model', 'pro', 'Pro'); + expect(hostSettingsDrafts.hasDirty('three')).toBe(true); + await act(async () => + [...container.querySelectorAll('button')] + .find((node) => node.textContent === 'Cancel')! + .click(), + ); + expect(hostSettingsDrafts.hasDirty('three')).toBe(false); +}); + +it('clears the draft once the Host accepted the write, even if the readback fails', async () => { + const { host, save } = await open('four', () => undefined); + await choose('Add a task model', 'pro', 'Pro'); + let failReads = true; + const presets = host.methods.get('modelPresets')!; + host.methods.set('modelPresets', (args) => { + if (failReads) { + failReads = false; + throw new Error('offline'); + } + return presets(args); + }); + await save(); + await flush(); + expect(writes(host)).toHaveLength(1); + expect(hostSettingsDrafts.hasDirty('four')).toBe(false); +});