From 0f021687384f8d79f73da3f30ccb3f0d62c951e3 Mon Sep 17 00:00:00 2001 From: DoodleBear Date: Mon, 23 Nov 2026 06:40:26 +0900 Subject: [PATCH 1/3] feat(client): Remote Host Settings edit a preset's Task models with the shared list (#4860) Co-Authored-By: Claude Opus 5.5 --- .../client/src/client/remote-host-models.tsx | 133 +++++------------- .../test/remote-host-task-models.test.tsx | 98 +++++++++++++ 2 files changed, 135 insertions(+), 96 deletions(-) create mode 100644 packages/client/test/remote-host-task-models.test.tsx diff --git a/packages/client/src/client/remote-host-models.tsx b/packages/client/src/client/remote-host-models.tsx index 16e1b67ccc..744068bb5b 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(); const [creation, setCreation] = useState({ kind: 'idle' }); const creationOwner = useRef(creation); const generation = useRef(0); @@ -426,90 +421,36 @@ 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)); +
+ + {subDraft === undefined ? null : ( +
+ { + const next = subDraft; + void run( + () => setModelSub(client, scope, value, next), + () => setSubDraft((current) => (current === next ? undefined : current)), + ); }} - /> - ))} -
- + > + {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' }; + +async function flush() { + for (let i = 0; i < 6; i += 1) await act(async () => new Promise((r) => setTimeout(r, 0))); +} + +it('edits a remote preset Task model list as a draft and saves it in one write', async () => { + Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); + const host = new FakeHost(); + const client = createHostClient({ + routes: ['https://remote.example.ts.net'], + credential: host.credential, + carrier: host.carrier, + }); + const sub = { + choices: [{ kind: 'model', ...flash, allowedEfforts: [''], defaultEffort: '' }], + default: { kind: 'model', ...flash }, + }; + 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: 4, + orchestrator: flash, + assignmentDefault: flash, + sub, + }, + ], + })); + host.methods.set('modelPresetSubSet', (args) => ({ + id: 'daily', + revision: 5, + sub: (args as { sub: unknown }).sub, + })); + const container = document.createElement('div'); + document.body.append(container); + root = createRoot(container); + await act(async () => + root!.render(createElement(RemoteHostModels, { hostId: 'remote', client, t: translate })), + ); + await flush(); + const select = container.querySelector('[aria-label="Models"]'); + expect(select).not.toBeNull(); + await act(async () => select!.click()); + await flush(); + const option = [...document.querySelectorAll('[tabindex="-1"]')].find( + (node) => node.textContent === 'Daily', + ); + expect(option).toBeDefined(); + await act(async () => option!.click()); + await flush(); + expect(container.textContent).toContain('Flash'); + await choose('Add a task model', 'pro', 'Pro'); + expect(host.calls.some((call) => call.method === 'modelPresetSubSet')).toBe(false); + const save = [...container.querySelectorAll('button')].find( + (node) => node.textContent === 'Save', + ); + await act(async () => save!.click()); + await flush(); + const write = host.calls.find((call) => call.method === 'modelPresetSubSet'); + expect(write?.args).toMatchObject({ + id: 'daily', + expectedRevision: 4, + sub: { + choices: [ + { kind: 'model', ...flash }, + { kind: 'model', ...pro }, + ], + default: { kind: 'model', ...flash }, + }, + }); +}); From bfdb783c589b895793b5900b5c4172d4aa54ddb0 Mon Sep 17 00:00:00 2001 From: DoodleBear Date: Mon, 23 Nov 2026 07:02:58 +0900 Subject: [PATCH 2/3] fix(client): keep the Task model draft's base revision and register it in the Host settings draft guard Co-Authored-By: Claude Opus 5.5 --- .../client/src/client/remote-host-models.tsx | 64 ++++++----- .../test/remote-host-task-models.test.tsx | 107 +++++++++++++----- 2 files changed, 116 insertions(+), 55 deletions(-) diff --git a/packages/client/src/client/remote-host-models.tsx b/packages/client/src/client/remote-host-models.tsx index 744068bb5b..10cf85ba0d 100644 --- a/packages/client/src/client/remote-host-models.tsx +++ b/packages/client/src/client/remote-host-models.tsx @@ -146,7 +146,7 @@ function Models({ const [error, setError] = useState>(); const [busy, setBusy] = useState(false); const [name, setName] = useState(); - const [subDraft, setSubDraft] = useState(); + const [subDraft, setSubDraft] = useState<{ sub: SubChoices; base: ModelSettingsState }>(); const [creation, setCreation] = useState({ kind: 'idle' }); const creationOwner = useRef(creation); const generation = useRef(0); @@ -193,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) => { @@ -204,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 ( @@ -258,30 +258,44 @@ 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( + () => 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], @@ -423,12 +437,14 @@ function Models({ {scope.kind !== 'preset' ? null : (
+ setSubDraft((current) => ({ sub, base: current?.base ?? value })) + } t={t} /> {subDraft === undefined ? null : ( @@ -436,11 +452,7 @@ function Models({ { - const next = subDraft; - void run( - () => setModelSub(client, scope, value, next), - () => setSubDraft((current) => (current === next ? undefined : current)), - ); + void saveSubDraft(); }} > {t('relationships.save')} diff --git a/packages/client/test/remote-host-task-models.test.tsx b/packages/client/test/remote-host-task-models.test.tsx index 355e85fe2b..6f60d27b3b 100644 --- a/packages/client/test/remote-host-task-models.test.tsx +++ b/packages/client/test/remote-host-task-models.test.tsx @@ -5,6 +5,7 @@ import { createRoot, type Root } from 'react-dom/client'; import { afterEach, expect, it } from 'vitest'; import { createHostClient } from '@botharness/host-client/client'; import { FakeHost } from '../../host-client/test/fake-host.js'; +import { hostSettingsDrafts } from '../src/client/host-settings-drafts.js'; import { RemoteHostModels } from '../src/client/remote-host-models.js'; let root: Root | undefined; @@ -16,22 +17,26 @@ afterEach(async () => { 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))); } -it('edits a remote preset Task model list as a draft and saves it in one write', async () => { +async function open( + hostId: string, + onWrite: (args: { sub: unknown; expectedRevision: number }) => unknown, +) { Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); const host = new FakeHost(); const client = createHostClient({ - routes: ['https://remote.example.ts.net'], + routes: [`https://${hostId}.example.ts.net`], credential: host.credential, carrier: host.carrier, }); - const sub = { - choices: [{ kind: 'model', ...flash, allowedEfforts: [''], defaultEffort: '' }], - default: { kind: 'model', ...flash }, + const state = { + revision: 4, + sub: { choices: [flashChoice], default: { kind: 'model', ...flash } } as unknown, }; host.methods.set('modelCatalog', () => ({ models: [ @@ -46,53 +51,97 @@ it('edits a remote preset Task model list as a draft and saves it in one write', { id: 'daily', name: 'Daily', - revision: 4, + revision: state.revision, orchestrator: flash, assignmentDefault: flash, - sub, + sub: state.sub, }, ], })); - host.methods.set('modelPresetSubSet', (args) => ({ - id: 'daily', - revision: 5, - sub: (args as { sub: unknown }).sub, - })); + host.methods.set( + 'modelPresetSubSet', + (args) => + onWrite(args as never) ?? + (() => { + const { sub } = args as { sub: unknown }; + 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: 'remote', client, t: translate })), + root!.render(createElement(RemoteHostModels, { hostId, client, t: translate })), ); await flush(); - const select = container.querySelector('[aria-label="Models"]'); - expect(select).not.toBeNull(); - await act(async () => select!.click()); + await act(async () => container.querySelector('[aria-label="Models"]')!.click()); await flush(); const option = [...document.querySelectorAll('[tabindex="-1"]')].find( (node) => node.textContent === 'Daily', ); - expect(option).toBeDefined(); await act(async () => option!.click()); await flush(); - expect(container.textContent).toContain('Flash'); + 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(host.calls.some((call) => call.method === 'modelPresetSubSet')).toBe(false); - const save = [...container.querySelectorAll('button')].find( - (node) => node.textContent === 'Save', - ); - await act(async () => save!.click()); + expect(writes(host)).toHaveLength(0); + await save(); await flush(); - const write = host.calls.find((call) => call.method === 'modelPresetSubSet'); - expect(write?.args).toMatchObject({ + expect(writes(host)).toHaveLength(1); + expect(writes(host)[0]?.args).toMatchObject({ id: 'daily', expectedRevision: 4, sub: { - choices: [ - { kind: 'model', ...flash }, - { kind: 'model', ...pro }, - ], + 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); }); From 6a3d73f769f6a157db96c4e38136480898329af5 Mon Sep 17 00:00:00 2001 From: DoodleBear Date: Mon, 23 Nov 2026 07:13:12 +0900 Subject: [PATCH 3/3] fix(client): clear the remote task-model draft once the Host accepts it Validate the fake Host request in the test fixture. Co-Authored-By: Claude Opus 5.5 --- .../client/src/client/remote-host-models.tsx | 12 +++--- .../test/remote-host-task-models.test.tsx | 42 +++++++++++++------ 2 files changed, 35 insertions(+), 19 deletions(-) diff --git a/packages/client/src/client/remote-host-models.tsx b/packages/client/src/client/remote-host-models.tsx index 10cf85ba0d..7485167b87 100644 --- a/packages/client/src/client/remote-host-models.tsx +++ b/packages/client/src/client/remote-host-models.tsx @@ -261,13 +261,11 @@ function Models({ const saveSubDraft = async () => { const pendingDraft = draft.current.subDraft; if (pendingDraft === undefined) return true; - return run( - () => setModelSub(client, scope, pendingDraft.base, pendingDraft.sub), - () => { - if (draft.current.subDraft === pendingDraft) draft.current.subDraft = undefined; - setSubDraft((current) => (current === pendingDraft ? undefined : current)); - }, - ); + 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 }; diff --git a/packages/client/test/remote-host-task-models.test.tsx b/packages/client/test/remote-host-task-models.test.tsx index 6f60d27b3b..80b86b9a4b 100644 --- a/packages/client/test/remote-host-task-models.test.tsx +++ b/packages/client/test/remote-host-task-models.test.tsx @@ -4,6 +4,7 @@ import { act, createElement } from 'react'; import { createRoot, type Root } from 'react-dom/client'; import { afterEach, expect, it } from 'vitest'; import { createHostClient } from '@botharness/host-client/client'; +import { isPresetSub, type PresetSub } from '@botharness/host-protocol/preset-sub'; import { FakeHost } from '../../host-client/test/fake-host.js'; import { hostSettingsDrafts } from '../src/client/host-settings-drafts.js'; import { RemoteHostModels } from '../src/client/remote-host-models.js'; @@ -25,7 +26,7 @@ async function flush() { async function open( hostId: string, - onWrite: (args: { sub: unknown; expectedRevision: number }) => unknown, + onWrite: (args: { sub: PresetSub; expectedRevision: number }) => unknown, ) { Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); const host = new FakeHost(); @@ -58,17 +59,16 @@ async function open( }, ], })); - host.methods.set( - 'modelPresetSubSet', - (args) => - onWrite(args as never) ?? - (() => { - const { sub } = args as { sub: unknown }; - state.revision += 1; - state.sub = sub; - return { id: 'daily', revision: state.revision, 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); @@ -145,3 +145,21 @@ it('counts a Task model edit as an unsaved Host settings draft and discards it', ); 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); +});