Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(mobile): 分离模型收藏与参数调整并保留列表返回位置 (#5388)

DavidShenXDc03513c1b384
diff --git a/apps/mobile/src/__tests__/androidModelPickerParity.test.tsx b/apps/mobile/src/__tests__/androidModelPickerParity.test.tsx
index efad0adbf7..c9e3f9dfc8 100644
--- a/apps/mobile/src/__tests__/androidModelPickerParity.test.tsx
+++ b/apps/mobile/src/__tests__/androidModelPickerParity.test.tsx
@@ -40,6 +40,7 @@ vi.mock("react-native", async () => {
accessibilityRole,
accessibilityValue,
accessibilityLabel,
+ accessibilityElementsHidden,
onLayout,
}: AnyProps) => {
if (testID && onLayout) native.layouts.set(testID, onLayout);
@@ -49,6 +50,7 @@ vi.mock("react-native", async () => {
"data-testid": testID,
role: accessibilityRole,
"aria-label": accessibilityLabel,
+ "aria-hidden": accessibilityElementsHidden,
"aria-valuenow": accessibilityValue?.now,
},
children,
@@ -461,8 +463,8 @@ describe("Android unified model picker follows the iOS structure", () => {
expect(byId("modelSheet")!.getAttribute("data-title")).toBe(
"models.unified.source",
);
- // 搜索框只在列表页出现;来源页有返回。
- expect(byId("modelSheet.search")).toBeNull();
+ // 列表保持挂载以保留位置,但来源页打开时不能访问隐藏的搜索框。
+ expect(byId("modelSheet.search")!.closest('[aria-hidden="true"]')).not.toBeNull();
const quota = byId("modelSheet.source.p1.quota")!;
expect(quota.getAttribute("role")).toBe("progressbar");
expect(quota.getAttribute("aria-valuenow")).toBe("40");
@@ -511,6 +513,7 @@ describe("Android unified model picker follows the iOS structure", () => {
fastCapable: true,
onChange: vi.fn(),
favoritesDisabled: false,
+ canReset: true,
onFavorite: vi.fn(),
onReset: vi.fn(),
context: "Provider One · 200K context",
@@ -588,15 +591,15 @@ describe("Android unified model picker follows the iOS structure", () => {
expect(byId("modelSheet.effort.high")).toBeNull();
});
- it("hides the reset row for favorites", () => {
+ it("offers reset for customized parameters even when opened from favorites", () => {
const props = optionsProps({
row: unifiedRow({ favorite: { uid: "fav-1" } }),
});
render(createElement(UnifiedModelPickerView, props as never));
expect(byId("modelSheet.favorite")!.textContent).toContain(
- "models.unified.removeFavorite",
+ "models.unified.savedConfiguration",
);
- expect(byId("modelSheet.reset")).toBeNull();
+ expect(byId("modelSheet.reset")).not.toBeNull();
});
});
diff --git a/apps/mobile/src/__tests__/composerSheetOrientation.test.tsx b/apps/mobile/src/__tests__/composerSheetOrientation.test.tsx
index eae489eee6..d5feb29e41 100644
--- a/apps/mobile/src/__tests__/composerSheetOrientation.test.tsx
+++ b/apps/mobile/src/__tests__/composerSheetOrientation.test.tsx
@@ -13,7 +13,7 @@ vi.mock('@expo/ui', () => ({ Host: ({ children }: any) => <div>{children}</div>
vi.mock('@expo/ui/swift-ui', () => {
const Container = ({ children }: any) => <div>{children}</div>;
return { Form: Container, Button: Container, Group: Container, HStack: Container, Image: Container,
- RNHostView: Container, Spacer: Container, Text: Container, VStack: Container,
+ RNHostView: Container, Spacer: Container, Text: Container, VStack: Container, ZStack: Container,
BottomSheet: (props: any) => { state.sheet = props; return <div>{props.children}</div>; },
};
});
diff --git a/apps/mobile/src/__tests__/unifiedMobilePicker.test.tsx b/apps/mobile/src/__tests__/unifiedMobilePicker.test.tsx
index 782a613f57..e969167875 100644
--- a/apps/mobile/src/__tests__/unifiedMobilePicker.test.tsx
+++ b/apps/mobile/src/__tests__/unifiedMobilePicker.test.tsx
@@ -7,7 +7,14 @@ vi.mock('expo-crypto', () => ({ randomUUID: () => 'test-uuid' }));
const test = vi.hoisted(() => ({ view: null as any, favoritesReady:true, quotas:{} as any, syncError:null as unknown, prefs: {favorites:[],engines:{}} as any, save: vi.fn(), entries: [] as any[] }));
vi.mock('@/session/UnifiedModelPickerView', () => ({ UnifiedModelPickerView: (p:any) => {test.view=p;return null;} }));
vi.mock('@/session/useMobileModelQuotas',()=>({useMobileModelQuotas:()=>({quotas:test.quotas,now:0})}));
-vi.mock('@/session/mobileModelPreferences', () => ({useMobileModelPreferences:()=>({ready:true,favoritesReady:test.favoritesReady,error:test.syncError,value:test.prefs,save:test.save})}));
+vi.mock('@/session/mobileModelPreferences', async () => {
+ const {useReducer} = await import('react');
+ return {useMobileModelPreferences:()=>{
+ const [,refresh] = useReducer(value => value + 1, 0);
+ return {ready:true,favoritesReady:test.favoritesReady,error:test.syncError,value:test.prefs,
+ save:async (value:typeof test.prefs)=>{await test.save(value);refresh();}};
+ }};
+});
vi.mock('@/session/providerModelSections', () => ({buildMobileModelSections:()=>({activeSourceId:'account'})}));
vi.mock('@/session/draftModelMemory',()=>({useDraftModelMemoryVersion:()=>0}));
vi.mock('@/session/sessionModelMirror',()=>({useSessionModelMirrorVersion:()=>0}));
@@ -16,7 +23,7 @@ vi.mock('@/session/unifiedMobileModels',async importOriginal=>({...await importO
vi.mock('react-i18next',()=>({useTranslation:()=>({t:(key:string)=>key})}));
(globalThis as any).IS_REACT_ACT_ENVIRONMENT=true;
let root:ReturnType<typeof createRoot>;
-beforeEach(()=>{test.favoritesReady=true;test.syncError=null;test.quotas={};test.save.mockReset();test.prefs={favorites:[],engines:{}};test.entries=[{
+beforeEach(()=>{test.favoritesReady=true;test.syncError=null;test.quotas={};test.save.mockReset().mockImplementation(async value => {test.prefs=value;});test.prefs={favorites:[],engines:{}};test.entries=[{
providerId:'account',modelId:'model',displayName:'Model',candidates:['codex','claude-code'],recommended:'codex',nativeAgent:'codex',
capabilities:{codex:{wireModelId:'codex/model',efforts:['medium','high'],defaultEffort:'medium',supportsFastMode:true,contextWindow:200000},
'claude-code':{wireModelId:'model',efforts:['medium','high'],defaultEffort:'medium',supportsFastMode:false,contextWindow:200000}},
@@ -50,11 +57,14 @@ it('shows favorites before recommendations, with selected mark only on the model
expect(test.view.groups[0].rows[0].config).toMatchObject({effort:'high',fast:true});
expect(test.view.groups[1].rows[0].selected).toBe(true);
});
-it('does not mutate a favorite or current task when editing a different configuration copy',async()=>{
+it('edits a favorite only through explicit editing and save, without changing the current task',async()=>{
test.prefs.favorites=[{uid:'fav',providerId:'account',modelId:'codex/model',agent:'codex',effort:'high',fast:false}];
const {onSelect}=await mount();
await act(async()=>test.view.onOptions(test.view.groups[0].rows[0]));
+ await act(async()=>test.view.options.onEditFavorite());
await act(async()=>test.view.options.onChange({...test.view.options.row.config,effort:'medium'}));
+ expect(test.save).not.toHaveBeenCalled();
+ await act(async()=>test.view.options.onSaveEdit());
expect(onSelect).not.toHaveBeenCalled();expect(test.save).toHaveBeenCalledWith(expect.objectContaining({favorites:[expect.objectContaining({uid:'fav',effort:'medium'})]}));
});
it('does not save an engine override when applying the selected row is cancelled',async()=>{
@@ -121,3 +131,399 @@ it('keeps model selection and settings usable when an old host lacks favorites',
expect(onClose).toHaveBeenCalled();
expect(test.view.error).toBeNull();
});
+
+it('preserves search and source filtering when returning from model details', async () => {
+ await mount();
+ await act(async () => test.view.onFilter('account'));
+ await act(async () => test.view.onQuery('Model'));
+ const groups = test.view.groups;
+ await act(async () => test.view.onOptions(groups[0].rows[0]));
+ await act(async () => test.view.onBack());
+ expect(test.view.options).toBeUndefined();
+ expect(test.view.query).toBe('Model');
+ expect(test.view.filter).toBe('account');
+ expect(test.view.groups).toEqual(groups);
+});
+
+it('adds and removes a favorite in place only after saving, without changing the current configuration', async () => {
+ let finishSave!: () => void;
+ test.save.mockImplementation(value => new Promise<void>(resolve => {
+ finishSave = () => {
+ // The host, rather than the phone, assigns the persisted favorite UID.
+ test.prefs = { ...value, favorites: value.favorites.map((item: any) => ({ ...item, uid: 'remote-saved' })) };
+ resolve();
+ };
+ }));
+ const { onSelect, onClose } = await mount(undefined, {selectedEffort:'high', selectedFastMode:true});
+ await act(async () => test.view.onOptions(test.view.groups[0].rows[0]));
+ const source = test.view.options.row;
+ await act(async () => test.view.options.onFavorite());
+ expect(test.view.busy).toBe(true);
+ expect(test.view.options.isFavorite).toBe(false);
+ await act(async () => test.view.options.onFavorite());
+ expect(test.save).toHaveBeenCalledTimes(1);
+ expect(test.save).toHaveBeenCalledWith(expect.objectContaining({
+ favorites: [expect.objectContaining({ ...source.config, modelId: source.entry.modelId })],
+ }));
+ await act(async () => finishSave());
+ expect(test.view.busy).toBe(false);
+ expect(test.view.options.isFavorite).toBe(true);
+ expect(test.view.options.row).toEqual(source);
+ expect(test.view.groups[0].rows[0].favorite.uid).toBe('remote-saved');
+ await act(async () => test.view.options.onFavorite());
+ expect(test.view.busy).toBe(true);
+ expect(test.view.options.isFavorite).toBe(true);
+ expect(test.save).toHaveBeenLastCalledWith(expect.objectContaining({ favorites: [] }));
+ await act(async () => finishSave());
+ expect(test.view.options.isFavorite).toBe(false);
+ expect(test.view.options.row).toEqual(source);
+ expect(onSelect).not.toHaveBeenCalled();
+ expect(onClose).not.toHaveBeenCalled();
+});
+
+it.each([false, true])('preserves favorite state after a failed toggle and allows retry (saved=%s)', async saved => {
+ if (saved) test.prefs.favorites = [{ uid: 'existing', providerId: 'account', modelId: 'model', agent: 'codex', effort: 'medium', fast: false }];
+ test.save.mockRejectedValueOnce(new Error('offline'));
+ await mount();
+ await act(async () => test.view.onOptions(test.view.groups.find((g:any) => g.key === 'recommended').rows[0]));
+ await act(async () => test.view.options.onFavorite());
+ expect(test.view.error).toBe('models.unified.saveFailed');
+ expect(test.view.busy).toBe(false);
+ expect(test.view.options.isFavorite).toBe(saved);
+ await act(async () => test.view.options.onFavorite());
+ expect(test.view.error).toBeNull();
+ expect(test.view.options.isFavorite).toBe(!saved);
+});
+
+it.each(['model', 'codex/model'])('recognizes an existing favorite with ID %s and removes only the matching configuration', async modelId => {
+ const matching = { uid: 'existing', providerId: 'account', modelId, agent: 'codex', effort: 'medium', fast: false };
+ const others = [
+ { ...matching, uid: 'other-effort', effort: 'high' },
+ { ...matching, uid: 'other-fast', fast: true },
+ { ...matching, uid: 'other-provider', providerId: 'other' },
+ { ...matching, uid: 'other-model', modelId: 'other' },
+ { ...matching, uid: 'other-agent', agent: 'claude-code' },
+ { ...matching, uid: 'unsupported-effort', effort: 'max' },
+ ];
+ test.prefs.favorites = [...others, matching];
+ await mount();
+ await act(async () => test.view.onOptions(test.view.groups[1].rows[0]));
+ expect(test.view.options.isFavorite).toBe(true);
+ await act(async () => test.view.options.onFavorite());
+ expect(test.prefs.favorites).toEqual(others);
+ expect(test.view.options.isFavorite).toBe(false);
+});
+
+it('updates favorite state after changing the displayed effort or Fast without editing existing copies', async () => {
+ const saved = { uid: 'existing', providerId: 'account', modelId: 'model', agent: 'codex', effort: 'high', fast: true };
+ test.prefs.favorites = [saved];
+ await mount();
+ await act(async () => test.view.onOptions(test.view.groups[1].rows[0]));
+ expect(test.view.options.isFavorite).toBe(false);
+ await mount(undefined, { selectedEffort: 'high', selectedFastMode: true });
+ expect(test.view.options.isFavorite).toBe(true);
+ await mount(undefined, { selectedEffort: 'high', selectedFastMode: false });
+ expect(test.view.options.isFavorite).toBe(false);
+ await act(async () => test.view.options.onFavorite());
+ expect(test.prefs.favorites).toEqual([saved, expect.objectContaining({ effort: 'high', fast: false })]);
+ expect(test.view.options.isFavorite).toBe(true);
+});
+
+it('reflects persisted favorite state after reopening the source details', async () => {
+ await mount();
+ const source = test.view.groups[0].rows[0];
+ await act(async () => test.view.onOptions(source));
+ await act(async () => test.view.options.onFavorite());
+ await act(async () => test.view.onBack());
+ await act(async () => test.view.onOptions(source));
+ expect(test.view.options.isFavorite).toBe(true);
+ await act(async () => test.view.options.onFavorite());
+ await act(async () => test.view.onBack());
+ await act(async () => test.view.onOptions(source));
+ expect(test.view.options.isFavorite).toBe(false);
+});
+
+it('removes a favorite copy without applying a fallback and keeps its details open', async () => {
+ const saved = { uid: 'existing', providerId: 'account', modelId: 'model', agent: 'codex', effort: 'high', fast: true };
+ test.prefs.favorites = [saved];
+ const {onSelect} = await mount(vi.fn(async () => false), {selectedEffort:'high', selectedFastMode:true});
+ await act(async () => test.view.onOptions(test.view.groups[0].rows[0]));
+ await act(async () => test.view.options.onFavorite());
+ expect(onSelect).not.toHaveBeenCalled();
+ expect(test.save).toHaveBeenCalledWith(expect.objectContaining({favorites:[]}));
+ expect(test.view.options.row.config).toMatchObject({effort:'high',fast:true});
+ expect(test.view.options.isFavorite).toBe(false);
+});
+
+it('adjusts model preferences from favorite details without overwriting the original copy', async () => {
+ const saved = {uid:'original',providerId:'account',modelId:'model',agent:'codex',effort:'high',fast:true};
+ test.prefs.favorites=[saved];
+ const {onSelect}=await mount();
+ await act(async()=>test.view.onOptions(test.view.groups[0].rows[0]));
+ expect(test.view.options.isFavorite).toBe(true);
+ await act(async()=>test.view.options.onChange({...test.view.options.row.config,fast:false}));
+ expect(onSelect).toHaveBeenCalledWith(expect.objectContaining({effort:'high',fast:false}));
+ expect(test.prefs.favorites).toEqual([saved]);
+ expect(test.view.options.row.config).toMatchObject({effort:'high',fast:false});
+ expect(test.view.options.isFavorite).toBe(false);
+ expect(test.view.options.notice).toBe('models.unified.originalFavoriteKept');
+ await act(async()=>test.view.options.onFavorite());
+ expect(test.prefs.favorites).toEqual([saved,expect.objectContaining({effort:'high',fast:false})]);
+});
+
+it('cancels explicit editing without saving or changing the active configuration', async () => {
+ const saved={uid:'original',providerId:'account',modelId:'model',agent:'codex',effort:'medium',fast:false};
+ test.prefs.favorites=[saved];
+ const {onSelect}=await mount();
+ await act(async()=>test.view.onOptions(test.view.groups[0].rows[0]));
+ await act(async()=>test.view.options.onEditFavorite());
+ await act(async()=>test.view.options.onChange({...test.view.options.row.config,effort:'high'}));
+ expect(test.view.options.editingFavorite).toBe(true);
+ await act(async()=>test.view.onBack());
+ expect(test.view.options.editingFavorite).toBe(false);
+ expect(test.view.options.row.config.effort).toBe('medium');
+ expect(test.prefs.favorites).toEqual([saved]);
+ expect(onSelect).not.toHaveBeenCalled();
+ expect(test.save).not.toHaveBeenCalled();
+});
+
+it('keeps explicit edits after failed saving and updates only the favorite when retried', async () => {
+ const saved={uid:'original',providerId:'account',modelId:'model',agent:'codex',effort:'medium',fast:false};
+ test.prefs.favorites=[saved];
+ const {onSelect}=await mount();
+ await act(async()=>test.view.onOptions(test.view.groups[0].rows[0]));
+ await act(async()=>test.view.options.onEditFavorite());
+ await act(async()=>test.view.options.onChange({...test.view.options.row.config,effort:'high'}));
+ test.save.mockRejectedValueOnce(new Error('offline'));
+ await act(async()=>test.view.options.onSaveEdit());
+ expect(test.view.error).toBe('models.unified.saveFailed');
+ expect(test.view.options.editingFavorite).toBe(true);
+ expect(test.view.options.row.config.effort).toBe('high');
+ expect(test.prefs.favorites).toEqual([saved]);
+ await act(async()=>test.view.options.onSaveEdit());
+ expect(test.view.options.editingFavorite).toBe(false);
+ expect(test.prefs.favorites).toEqual([{...saved,effort:'high'}]);
+ expect(onSelect).not.toHaveBeenCalled();
+});
+
+it.each(['changed','removed'])('rejects a stale edit when the original was %s remotely',async mode=>{
+ const saved={uid:'original',providerId:'account',modelId:'model',agent:'codex',effort:'medium',fast:false};
+ test.prefs.favorites=[saved];
+ await mount();
+ await act(async()=>test.view.onOptions(test.view.groups[0].rows[0]));
+ await act(async()=>test.view.options.onEditFavorite());
+ await act(async()=>test.view.options.onChange({...test.view.options.row.config,effort:'high'}));
+ test.prefs={...test.prefs,favorites:mode==='changed'?[{...saved,fast:true}]:[]};
+ await mount();
+ await act(async()=>test.view.options.onSaveEdit());
+ expect(test.save).not.toHaveBeenCalled();
+ expect(test.view.error).toBe('models.unified.favoriteChanged');
+ expect(test.view.options.editingFavorite).toBe(true);
+});
+
+it('rejects duplicate configurations during explicit favorite editing',async()=>{
+ const saved={uid:'original',providerId:'account',modelId:'model',agent:'codex',effort:'medium',fast:false};
+ test.prefs.favorites=[saved,{...saved,uid:'other',modelId:'codex/model',effort:'high'}];
+ await mount();
+ await act(async()=>test.view.onOptions(test.view.groups[0].rows[0]));
+ await act(async()=>test.view.options.onEditFavorite());
+ await act(async()=>test.view.options.onChange({...test.view.options.row.config,effort:'high'}));
+ await act(async()=>test.view.options.onSaveEdit());
+ expect(test.save).not.toHaveBeenCalled();
+ expect(test.view.error).toBe('models.unified.favoriteExists');
+});
+
+it('distinguishes recommended settings from explicit overrides with the same values',async()=>{
+ await mount();
+ await act(async()=>test.view.onOptions(test.view.groups[0].rows[0]));
+ expect(test.view.options.canReset).toBe(false);
+ test.prefs.engines[JSON.stringify(['account','model'])]='codex';
+ await mount();
+ expect(test.view.options.canReset).toBe(true);
+ await act(async()=>test.view.options.onReset());
+ expect(test.view.options.canReset).toBe(false);
+ expect(test.prefs.engines).toEqual({});
+});
+
+it('resets engine, effort and Fast overrides for this model while preserving favorites and other models',async()=>{
+ const effort=new Map([['codex:codex/model','high'],['claude-code:model','high'],['codex:other','high']]);
+ const fast=new Map([['codex:codex/model',true],['claude-code:model',false],['codex:other',true]]);
+ const memory={
+ getEffort:(a:string,_p:string,m:string)=>effort.get(`${a}:${m}`),
+ getFast:(a:string,_p:string,m:string)=>fast.get(`${a}:${m}`),
+ setEffort:vi.fn(),setFast:vi.fn(),
+ clearEffort:vi.fn((a:string,_p:string,m:string)=>{effort.delete(`${a}:${m}`);}),
+ clearFast:vi.fn((a:string,_p:string,m:string)=>{fast.delete(`${a}:${m}`);}),
+ };
+ const saved={uid:'original',providerId:'account',modelId:'model',agent:'codex',effort:'high',fast:true};
+ test.prefs={favorites:[saved],engines:{[JSON.stringify(['account','model'])]:'claude-code',[JSON.stringify(['account','other'])]:'codex'}};
+ const {onSelect}=await mount(undefined,{activeModelId:'other',modelMemory:memory});
+ const source=test.view.groups.flatMap((g:any)=>g.rows).find((r:any)=>!r.favorite);
+ await act(async()=>test.view.onOptions(source));
+ expect(test.view.options.canReset).toBe(true);
+ await act(async()=>test.view.options.onReset());
+ expect(test.view.options.canReset).toBe(false);
+ expect(test.view.options.row.config).toMatchObject({agent:'codex',effort:'medium',fast:false});
+ expect([...effort.entries()]).toEqual([['codex:other','high']]);
+ expect([...fast.entries()]).toEqual([['codex:other',true]]);
+ expect(test.prefs.engines).toEqual({[JSON.stringify(['account','other'])]:'codex'});
+ expect(test.prefs.favorites).toEqual([saved]);
+ expect(onSelect).not.toHaveBeenCalled();
+});
+
+it('does not clear model memory when restoring the active configuration is cancelled',async()=>{
+ const memory={getEffort:()=>undefined,getFast:()=>undefined,setEffort:vi.fn(),setFast:vi.fn(),clearEffort:vi.fn(),clearFast:vi.fn()};
+ await mount(vi.fn(async()=>false),{selectedEffort:'high',selectedFastMode:true,modelMemory:memory});
+ await act(async()=>test.view.onOptions(test.view.groups[0].rows[0]));
+ await act(async()=>test.view.options.onReset());
+ expect(test.view.options.canReset).toBe(true);
+ expect(test.view.options.row.config).toMatchObject({effort:'high',fast:true});
+ expect(memory.clearEffort).not.toHaveBeenCalled();
+ expect(memory.clearFast).not.toHaveBeenCalled();
+ expect(test.save).not.toHaveBeenCalled();
+});
+
+it('restores session mirrors through the existing value-only remote accessors',async()=>{
+ const {makeSessionMirrorAccessors,clearSessionMirror}=await vi.importActual<typeof import('@/session/sessionModelMirror')>('@/session/sessionModelMirror');
+ const onWrite=vi.fn();
+ const memory=makeSessionMirrorAccessors('restore-test',onWrite);
+ try {
+ memory.setEffort('codex','account','codex/model','high');
+ memory.setFast('codex','account','codex/model',true);
+ onWrite.mockClear();
+ await mount(undefined,{activeModelId:'other',modelMemory:memory});
+ await act(async()=>test.view.onOptions(test.view.groups[0].rows[0]));
+ expect(test.view.options.canReset).toBe(true);
+ await act(async()=>test.view.options.onReset());
+ expect(memory.getEffort('codex','account','codex/model')).toBe('medium');
+ expect(memory.getFast('codex','account','codex/model')).toBe(false);
+ expect(onWrite).toHaveBeenCalledWith('codex','account','codex/model',{effort:'medium'});
+ expect(onWrite).toHaveBeenCalledWith('codex','account','codex/model',{fast:false});
+ expect(test.view.options.canReset).toBe(false);
+ } finally { clearSessionMirror('restore-test'); }
+});
+
+it('rolls back the active configuration if saving a recommendation reset fails',async()=>{
+ const memory={getEffort:()=>undefined,getFast:()=>undefined,setEffort:vi.fn(),setFast:vi.fn(),clearEffort:vi.fn(),clearFast:vi.fn()};
+ const {onSelect}=await mount(undefined,{selectedEffort:'high',selectedFastMode:true,modelMemory:memory});
+ await act(async()=>test.view.onOptions(test.view.groups[0].rows[0]));
+ test.save.mockRejectedValueOnce(new Error('disk unavailable'));
+ await act(async()=>test.view.options.onReset());
+ expect(onSelect).toHaveBeenNthCalledWith(1,expect.objectContaining({effort:'medium',fast:false}));
+ expect(onSelect).toHaveBeenNthCalledWith(2,expect.objectContaining({effort:'high',fast:true}));
+ expect(memory.clearEffort).not.toHaveBeenCalled();
+ expect(memory.clearFast).not.toHaveBeenCalled();
+ expect(test.view.options.notice).toBeNull();
+ expect(test.view.error).toBe('models.unified.saveFailed');
+});
+
+it('restores the session-pinned baseline without leaving a reset button', async () => {
+ test.entries[0].nativeAgent = null;
+ test.entries[0].recommended = 'claude-code';
+ const memory = {getEffort:()=>undefined,getFast:()=>undefined,setEffort:vi.fn(),setFast:vi.fn()};
+ await mount(undefined, {activeModelId:'other',modelMemory:memory});
+ await act(async()=>test.view.onOptions(test.view.groups[0].rows[0]));
+ expect(test.view.options.canReset).toBe(false);
+ await act(async()=>test.view.options.onChange({...test.view.options.row.config,agent:'claude-code',modelId:'model',effort:'high'}));
+ expect(test.view.options.canReset).toBe(true);
+ await act(async()=>test.view.options.onReset());
+ expect(test.view.options.row.config).toMatchObject({agent:'codex',effort:'medium',fast:false});
+ expect(test.view.options.canReset).toBe(false);
+ expect(test.prefs.engines).toEqual({});
+});
+
+it.each(['edit','parameters','favorite','failure'])('ignores late %s UI completion after close and reopen', async (operation) => {
+ test.prefs.favorites=[{uid:'fav',providerId:'account',modelId:'model',agent:'codex',effort:'medium',fast:false}];
+ await mount();
+ await act(async()=>test.view.onOptions(test.view.groups[0].rows[0]));
+ if (operation === 'edit' || operation === 'failure') {
+ await act(async()=>test.view.options.onEditFavorite());
+ await act(async()=>test.view.options.onChange({...test.view.options.row.config,effort:'high'}));
+ }
+ let finish!:()=>void;
+ const pending=new Promise<void>(resolve=>{finish=resolve;});
+ test.save.mockImplementationOnce(async value=>{await pending;if(operation==='failure') throw new Error('offline');test.prefs=value;});
+ await act(async()=>{
+ if(operation==='parameters') test.view.options.onChange({...test.view.options.row.config,effort:'high'});
+ else if(operation==='favorite') test.view.options.onFavorite();
+ else test.view.options.onSaveEdit();
+ });
+ expect(test.view.busy).toBe(true);
+ await mount(undefined,{visible:false});
+ await mount(undefined,{visible:true});
+ expect(test.view.options).toBeUndefined();
+ expect(test.view.busy).toBe(true);
+ await act(async()=>{finish();await pending;});
+ expect(test.view.options).toBeUndefined();
+ expect(test.view.error).toBeNull();
+ expect(test.view.busy).toBe(false);
+ if(operation==='edit') expect(test.prefs.favorites[0].effort).toBe('high');
+});
+
+it.each(['success', 'cancel', 'save-failure'])('applies ordinary edits of the running favorite while another model is pending: %s', async outcome => {
+ const saved = {uid:'running',providerId:'account',modelId:'codex/model',agent:'codex',effort:'high',fast:true};
+ test.prefs.favorites = [saved];
+ const onSelect = vi.fn(async () => outcome !== 'cancel');
+ const memory = {getEffort:()=>undefined,getFast:()=>undefined,setEffort:vi.fn(),setFast:vi.fn()};
+ await mount(onSelect, {
+ agentKind:'claude-code',activeModelId:'pending-model',modelMemory:memory,
+ unified:{scope:'user-device',agents:['codex','claude-code'],loadCapabilities:async()=>({hasFastMode:true}),onSelect,
+ currentSelection:{agentKind:'codex',activeModelId:'codex/model',selectedProviderId:'account',selectedEffort:'high',selectedFastMode:true}},
+ });
+ await act(async()=>test.view.onOptions(test.view.groups[0].rows[0]));
+ expect(test.view.options.row.selected).toBe(false);
+ if(outcome === 'save-failure') test.save.mockRejectedValueOnce(new Error('offline'));
+ await act(async()=>test.view.options.onChange({...test.view.options.row.config,effort:'medium'}));
+ expect(onSelect).toHaveBeenNthCalledWith(1,{providerId:'account',modelId:'codex/model',agent:'codex',effort:'medium',fast:true});
+ expect(test.prefs.favorites).toEqual([saved]);
+ if(outcome === 'cancel') {
+ expect(test.save).not.toHaveBeenCalled();
+ expect(memory.setEffort).not.toHaveBeenCalled();
+ } else if(outcome === 'save-failure') {
+ expect(onSelect).toHaveBeenNthCalledWith(2,{providerId:'account',modelId:'codex/model',agent:'codex',effort:'high',fast:true});
+ expect(memory.setEffort).not.toHaveBeenCalled();
+ expect(test.view.error).toBe('models.unified.saveFailed');
+ } else {
+ expect(onSelect).toHaveBeenCalledOnce();
+ expect(memory.setEffort).toHaveBeenCalledWith('codex','account','codex/model','medium');
+ }
+});
+
+it.each(['closed', 'reopened', 'rebound'])('does not roll back a newer selection after the original panel is %s', async lifecycle => {
+ let rejectSave!: (error: Error) => void;
+ const pending = new Promise<void>((_resolve,reject)=>{rejectSave=reject;});
+ test.save.mockImplementationOnce(()=>pending);
+ const onSelect = vi.fn(async()=>true);
+ await mount(onSelect);
+ await act(async()=>test.view.onOptions(test.view.groups[0].rows[0]));
+ await act(async()=>test.view.options.onChange({...test.view.options.row.config,effort:'high'}));
+ expect(onSelect).toHaveBeenCalledOnce();
+ expect(test.save).toHaveBeenCalledOnce();
+ if(lifecycle === 'rebound') {
+ await mount(onSelect,{activeModelId:'new-model',unified:{scope:'other-device',agents:['codex','claude-code'],loadCapabilities:async()=>({hasFastMode:true}),onSelect}});
+ } else {
+ await mount(onSelect,{visible:false,activeModelId:'new-model'});
+ if(lifecycle === 'reopened') await mount(onSelect,{activeModelId:'new-model'});
+ }
+ await act(async()=>{rejectSave(new Error('stale favorite binding'));});
+ expect(onSelect).toHaveBeenCalledOnce();
+ expect(test.view.error).toBeNull();
+ expect(test.view.busy).toBe(false);
+});
+
+it('does not start preference writes after selection completes for a closed panel', async()=>{
+ let finish!: (applied: boolean)=>void;
+ const onSelect = vi.fn(()=>new Promise<boolean>(resolve=>{finish=resolve;}));
+ const memory = {getEffort:()=>undefined,getFast:()=>undefined,setEffort:vi.fn(),setFast:vi.fn()};
+ await mount(onSelect,{modelMemory:memory});
+ await act(async()=>test.view.onOptions(test.view.groups[0].rows[0]));
+ await act(async()=>test.view.options.onChange({...test.view.options.row.config,effort:'high'}));
+ await mount(onSelect,{visible:false,modelMemory:memory});
+ await mount(onSelect,{modelMemory:memory});
+ await act(async()=>{finish(true);});
+ expect(test.save).not.toHaveBeenCalled();
+ expect(memory.setEffort).not.toHaveBeenCalled();
+ expect(onSelect).toHaveBeenCalledOnce();
+ expect(test.view.options).toBeUndefined();
+ expect(test.view.error).toBeNull();
+});
diff --git a/apps/mobile/src/__tests__/unifiedMobilePickerView.test.tsx b/apps/mobile/src/__tests__/unifiedMobilePickerView.test.tsx
index af4facdc2a..cd8b310009 100644
--- a/apps/mobile/src/__tests__/unifiedMobilePickerView.test.tsx
+++ b/apps/mobile/src/__tests__/unifiedMobilePickerView.test.tsx
@@ -1,18 +1,20 @@
// @vitest-environment jsdom
-import { act, createElement } from "react";
-import { createRoot } from "react-dom/client";
-import { afterEach, beforeEach, expect, it, vi } from "vitest";
-import { UnifiedModelPickerView } from "@/session/UnifiedModelPickerView";
+import { act, createElement } from 'react';
+import { createRoot } from 'react-dom/client';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { UnifiedModelPickerView } from '@/session/UnifiedModelPickerView';
+import { UnifiedModelPickerView as IosModelPickerView } from '@/session/UnifiedModelPickerView.ios';
const virtualList = vi.hoisted(() => ({ scrollToOffset: vi.fn() }));
-vi.mock("react-native", async () => {
- const { createElement: el, useImperativeHandle } = await import("react");
- const View = ({ children }: any) => el("div", null, children);
+const theme = vi.hoisted(() => ({ mode: 'light' as 'light' | 'dark' }));
+vi.mock('react-native', async () => {
+ const { createElement: el, useImperativeHandle } = await import('react');
+ const View = ({ children, accessibilityElementsHidden, pointerEvents }: any) => el('div', { 'aria-hidden': accessibilityElementsHidden, 'data-pointer-events': pointerEvents }, children);
return {
Platform: { OS: "android" },
- View,
- ScrollView: View,
+ View, ScrollView: View,
FlatList: ({
ref,
+ testID,
data,
renderItem,
ListHeaderComponent,
@@ -25,7 +27,7 @@ vi.mock("react-native", async () => {
);
return el(
"div",
- null,
+ { "data-testid": testID },
ListHeaderComponent,
data.length
? data.map((item: any, index: number) =>
@@ -34,104 +36,188 @@ vi.mock("react-native", async () => {
: ListEmptyComponent,
);
},
- Pressable: ({ children, onPress, disabled }: any) =>
- el("button", { onClick: onPress, disabled }, children),
+
+ Pressable: ({ children, onPress, disabled, accessibilityLabel }: any) => el('button', { onClick: onPress, disabled, 'aria-label':accessibilityLabel }, children),
StyleSheet: { create: (styles: any) => styles, hairlineWidth: 1 },
- useWindowDimensions: () => ({ height: 800 }),
+ useWindowDimensions: () => ({ width: 400, height: 800 }),
};
});
-vi.mock("@/components/AppText", async () => {
- const { createElement: el } = await import("react");
+vi.mock('@/components/AppText', async () => {
+ const { createElement: el } = await import('react');
+ return { Text: ({ children }: any) => el('span', null, children), TextInput: () => null };
+});
+vi.mock('react-native-safe-area-context', () => ({ useSafeAreaInsets: () => ({ top: 40, bottom: 20 }) }));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+vi.mock('lucide-react-native', () => ({
+ ...Object.fromEntries(['Brain', 'SlidersHorizontal', 'Check', 'Zap', 'LayoutGrid', 'Search', 'X', 'ChevronDown', 'ChevronRight', 'ChevronsUpDown'].map(key => [key, () => null])),
+ Star: ({ fill, color }: any) => createElement('span', { 'data-star-fill': fill, 'data-star-color': color }),
+}));
+vi.mock('@expo/ui/swift-ui', async () => {
+ const { useRef } = await import('react');
+ const Container = ({ children, modifiers, testID }: any) => createElement('div', {
+ 'data-testid': testID, 'data-modifiers': JSON.stringify(modifiers),
+ 'aria-hidden': modifiers?.some((m:any) => m.accessibilityHidden === true),
+ }, children);
return {
- Text: ({ children }: any) => el("span", null, children),
- TextInput: () => null,
+ ...Object.fromEntries(['Form', 'BottomSheet', 'Group', 'ZStack', 'Image', 'Spacer', 'HStack', 'Picker', 'ProgressView', 'RNHostView', 'VStack', 'Text', 'TextField', 'Toggle'].map(key => [key, Container])),
+ Button: ({ children, onPress, modifiers }: any) => createElement('button', {onClick:onPress, 'aria-label':modifiers?.find((m:any)=>m.accessibilityLabel)?.accessibilityLabel}, children),
+ useNativeState: (initial: string) => useRef({ value: initial, get() { return this.value; }, set(value: string) { this.value = value; } }).current,
};
});
-vi.mock("react-native-safe-area-context", () => ({
- useSafeAreaInsets: () => ({ top: 40, bottom: 20 }),
-}));
-vi.mock("react-i18next", () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-vi.mock("lucide-react-native", () =>
- Object.fromEntries(
- [
- "Brain",
- "Star",
- "SlidersHorizontal",
- "Check",
- "Zap",
- "LayoutGrid",
- "Search",
- "X",
- "ChevronDown",
- "ChevronRight",
- "ChevronsUpDown",
- ].map((key) => [key, () => null]),
- ),
-);
-vi.mock("@/platform/chrome", () => ({
- NativePullDownMenu: ({ children }: any) => children,
- NativeSwitch: () => null,
- usesNativePullDownMenu: () => true,
-}));
-vi.mock("@/components/MobileAgentMark", () => ({
- MobileAgentMark: () => null,
-}));
-vi.mock("@/session/MobileProviderMark", () => ({
- MobileModelIconMark: () => null,
- MobileProviderMark: () => null,
-}));
-vi.mock("@/session/SheetModal", () => ({
- SheetModal: ({ children }: any) => children,
-}));
-vi.mock("@/session/SheetSurface", () => ({
- SheetSurface: ({ children, renderScrollContent }: any) =>
- renderScrollContent ? renderScrollContent({}) : children,
-}));
-vi.mock("@/session/sessionAgentSwitch", () => ({
- mobileAgentLabel: (agent: string) => agent,
-}));
-vi.mock("@/theme", async () => ({
- ...(await import("@/theme/tokens")),
- useTheme: () => ({ colors: {} }),
- useThemedStyles: (factory: any) => factory({}),
-}));
+vi.mock('@expo/ui/swift-ui/modifiers', () => ({...Object.fromEntries(
+ ['accessibilityElement', 'accessibilityHidden', 'opacity', 'scrollDisabled', 'scrollContentBackground', 'presentationDetents', 'presentationDragIndicator', 'interactiveDismissDisabled', 'contentShape', 'accessibilityLabel', 'buttonStyle', 'disabled', 'font', 'foregroundStyle', 'frame', 'pickerStyle', 'progressViewStyle', 'tint', 'tag', 'padding', 'autocorrectionDisabled', 'textInputAutocapitalization', 'lineLimit'].map(key => [key, (value: any) => ({ [key]: value })]),
+), shapes:{rectangle:()=>({})}}));
+vi.mock('@expo/ui', () => ({Host:({children}:any)=>children}));
+vi.mock('@/session/ComposerSheet', () => import('@/session/ComposerSheet.ios'));
+vi.mock('@/session/ComposerNativeSection', () => ({ ComposerNativeSection: ({ children }: any) => children }));
+vi.mock('@/session/ComposerNativeRow', () => ({ ComposerNativeRow: ({ leading, title }: any) => createElement('div', null, leading, title) }));
+vi.mock('@/platform/chrome', () => ({ NativePullDownMenu: ({ children }: any) => children, NativeSwitch: () => null, usesNativePullDownMenu: () => true }));
+vi.mock('@/components/MobileAgentMark', () => ({ MobileAgentMark: () => null }));
+vi.mock('@/session/MobileProviderMark', () => ({ MobileModelIconMark: () => null, MobileProviderMark: () => null }));
+vi.mock('@/session/SheetModal', () => ({ SheetModal: ({ children }: any) => children }));
+vi.mock('@/session/SheetSurface', () => ({ SheetSurface: ({ children, pinnedTop, onBack, backAccessibilityLabel, testID, renderScrollContent }: any) => createElement('section', null,
+ onBack ? createElement('button', {onClick:onBack, 'aria-label':backAccessibilityLabel ?? 'shared.back'}, 'Back') : null,
+ pinnedTop, renderScrollContent ? renderScrollContent({ testID: `${testID}.scroll` }) : createElement('div', {'data-testid':`${testID}.scroll`}, children)) }));
+vi.mock('@/session/sessionAgentSwitch', () => ({ mobileAgentLabel: (agent: string) => agent }));
+vi.mock('@/theme', async () => {
+ const tokens = await import('@/theme/tokens');
+ return { ...tokens, useTheme: () => ({ colors: tokens.palettes[theme.mode] }), useThemedStyles: (factory: any) => factory(tokens.palettes[theme.mode]) };
+});
let root: ReturnType<typeof createRoot>;
let host: HTMLDivElement;
beforeEach(() => {
virtualList.scrollToOffset.mockClear();
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
- host = document.createElement("div");
+ host = document.createElement('div');
root = createRoot(host);
});
afterEach(() => act(() => root.unmount()));
-it.each([null, "2d · 70%"])(
- "keeps both account identities visible with quota %s",
- async (quotaLabel) => {
- const rows = ["[email protected]", "[email protected]"].map(
- (subtitle) => ({
- key: subtitle,
- subtitle,
- quotaLabel,
- entry: { displayName: "Same Model" },
- config: { agent: "codex" },
- providerMark: {},
- }),
- );
- await act(async () =>
- root.render(
- createElement(UnifiedModelPickerView, {
- visible: true,
- groups: [{ key: "favorites", title: "Favorites", rows }],
- filters: [],
- } as any),
- ),
- );
- for (const row of rows) expect(host.textContent).toContain(row.subtitle);
- if (quotaLabel) expect(host.textContent).toContain(quotaLabel);
+it.each([null, '2d · 70%'])('keeps both account identities visible with quota %s', async quotaLabel => {
+ const rows = ['[email protected]', '[email protected]'].map(subtitle => ({
+ key: subtitle, subtitle, quotaLabel, entry: { displayName: 'Same Model' },
+ config: { agent: 'codex' }, providerMark: {},
+ }));
+ await act(async () => root.render(createElement(UnifiedModelPickerView, {
+ visible: true, groups: [{ key: 'favorites', title: 'Favorites', rows }], filters: [],
+ } as any)));
+ for (const row of rows) expect(host.textContent).toContain(row.subtitle);
+ if (quotaLabel) expect(host.textContent).toContain(quotaLabel);
+});
+
+it.each([
+ ['Android', 'light', UnifiedModelPickerView],
+ ['Android', 'dark', UnifiedModelPickerView],
+ ['iOS', 'light', IosModelPickerView],
+ ['iOS', 'dark', IosModelPickerView],
+] as const)('shows add/remove favorite states on %s in %s mode while retaining source settings', async (_platform, mode, Component) => {
+ theme.mode = mode;
+ const row = {
+ key: 'model', entry: { capabilities: { codex: { efforts: [] } } },
+ config: { agent: 'codex' },
+ };
+ const render = async (isFavorite: boolean | undefined, favorite = false) => {
+ await act(async () => root.render(createElement(Component, {
+ visible: true, groups: [], filters: [], query: '',
+ options: { row: { ...row, favorite: favorite ? { uid: 'saved' } : undefined }, agents: ['codex'], isFavorite, canReset:true },
+ } as any)));
+ };
+ const fill = () => host.querySelector('[data-star-fill]')?.getAttribute('data-star-fill');
+ await render(false);
+ expect(fill()).toBe('none');
+ expect(host.textContent).toContain('models.unified.favoriteConfiguration');
+ await render(true);
+ const color = host.querySelector('[data-star-fill]')?.getAttribute('data-star-color');
+ expect(color).toBeTruthy();
+ expect(fill()).toBe(color);
+ expect(host.textContent).toContain('models.unified.savedConfiguration');
+ expect(host.textContent).toContain('models.unified.restoreRecommended');
+ await render(false);
+ expect(fill()).toBe('none');
+ expect(host.textContent).toContain('models.unified.favoriteConfiguration');
+ await render(undefined, true);
+ expect(fill()).toBe(color);
+ expect(host.textContent).toContain('models.unified.savedConfiguration');
+});
+
+it.each([['Android', UnifiedModelPickerView], ['iOS', IosModelPickerView]] as const)(
+ 'separates recommendation status, reset and explicit favorite editing on %s', async (_platform, Component) => {
+ const row={key:'model',entry:{displayName:'Model',capabilities:{codex:{efforts:[]}}},config:{agent:'codex',effort:'high',fast:false},providerMark:{}};
+ const render=async(extra:Record<string,unknown>)=>act(async()=>root.render(createElement(Component,{
+ visible:true,testID:'modelSheet',title:'Model',query:'',filter:'all',groups:[],filters:[],
+ options:{row,agents:['codex'],isFavorite:true,configurationSummary:'Codex · high',...extra},
+ } as any)));
+ await render({canReset:false});
+ expect(host.textContent).toContain('models.unified.usingRecommended');
+ expect(host.textContent).not.toContain('models.unified.restoreRecommended');
+ expect(host.textContent).toContain('models.unified.savedConfiguration');
+ await render({canReset:true,onEditFavorite:vi.fn()});
+ expect(host.textContent).toContain('models.unified.customized');
+ expect(host.textContent).toContain('models.unified.restoreRecommended');
+ expect(host.textContent).toContain('models.unified.resetScopeHint');
+ expect(host.textContent).toContain('models.unified.editFavorite');
+ await render({canReset:true,editingFavorite:true});
+ expect(host.textContent).toContain('models.unified.editFavoriteHint');
+ expect(host.textContent).toContain('models.unified.saveFavorite');
+ expect(host.textContent).toContain('models.unified.cancelEdit');
+ expect(host.textContent).not.toContain('models.unified.restoreRecommended');
+ expect(host.textContent).not.toContain('models.unified.savedConfiguration');
},
);
+
+it.each([
+ ['Android', UnifiedModelPickerView, 'modelSheet.scroll', 'modelSheet.list.scroll'],
+ ['iOS', IosModelPickerView, 'modelSheet.list', 'modelSheet.list'],
+] as const)('retains the long list and its scroll position when returning from details on %s', async (_platform, Component, listId, hiddenListId) => {
+ const rows = Array.from({length:60}, (_, i) => ({
+ key:`model-${i}`, entry:{displayName:`Model ${i}`, capabilities:{codex:{efforts:[]}}},
+ config:{agent:'codex'}, subtitle:'Provider', providerMark:{},
+ }));
+ const props = {
+ visible:true, testID:'modelSheet', title:'Models', query:'Model', filter:'provider',
+ filters:[{id:'provider',label:'Provider'}], groups:[{key:'provider',title:'Provider',rows}],
+ onClose:vi.fn(),
+ };
+ const render = (options?: any) => root.render(createElement(Component, {
+ ...props, options, onBack:options ? () => render() : undefined,
+ } as any));
+ await act(async () => render());
+ const list = host.querySelector(`[data-testid="${listId}"]`) as HTMLElement;
+ expect(list).not.toBeNull();
+ list.scrollTop = 960;
+ virtualList.scrollToOffset.mockClear();
+ const listChildren = [...list.childNodes];
+ for (const row of [rows[35], rows[40]]) {
+ await act(async () => render({row, agents:['codex']}));
+ expect(host.querySelector(`[data-testid="${hiddenListId}"]`)).toBe(list);
+ expect([...list.childNodes]).toEqual(listChildren);
+ expect(list.closest('[aria-hidden="true"]')).not.toBeNull();
+ const back = host.querySelector('button[aria-label="models.picker.backToModels"]') as HTMLButtonElement;
+ expect(back).not.toBeNull();
+ await act(async () => back.click());
+ expect(host.querySelector(`[data-testid="${listId}"]`)).toBe(list);
+ expect(list.scrollTop).toBe(960);
+ expect(virtualList.scrollToOffset).not.toHaveBeenCalled();
+ expect(list.closest('[aria-hidden="true"]')).toBeNull();
+ }
+ const sources = host.querySelector('button[aria-label="models.unified.source"]') as HTMLButtonElement;
+ await act(async () => sources.click());
+ expect(host.querySelector(`[data-testid="${hiddenListId}"]`)).toBe(list);
+ expect(list.closest('[aria-hidden="true"]')).not.toBeNull();
+ const back = host.querySelector('button[aria-label="models.picker.backToModels"], button[aria-label="shared.back"]') as HTMLButtonElement;
+ await act(async () => back.click());
+ expect(host.querySelector(`[data-testid="${listId}"]`)).toBe(list);
+ expect(list.scrollTop).toBe(960);
+ expect(list.closest('[aria-hidden="true"]')).toBeNull();
+});
+
+it('keeps selection errors visible in the retained native root list', async () => {
+ await act(async () => root.render(createElement(IosModelPickerView, {
+ visible:true, testID:'modelSheet', query:'', filters:[], groups:[], error:'Save failed',
+ } as any)));
+ const list = host.querySelector('[data-testid="modelSheet.list"]');
+ expect(list?.textContent).toContain('Save failed');
+});
+
it.each(["query", "filter"])(
"returns to the first result when %s changes after scrolling",
async (field) => {
diff --git a/apps/mobile/src/i18n/locales/en/models.json b/apps/mobile/src/i18n/locales/en/models.json
index 593087f552..6ab8332c01 100644
--- a/apps/mobile/src/i18n/locales/en/models.json
+++ b/apps/mobile/src/i18n/locales/en/models.json
@@ -59,13 +59,31 @@
"confirm": "Continue"
},
"unified": {
+ "favoriteConfiguration": "Favorite This Configuration",
+ "savedConfiguration": "Favorited · Tap to Remove",
+ "currentConfiguration": "Current Configuration",
+ "usingRecommended": "Using Recommended Settings",
+ "customized": "Customized",
+ "resetScopeHint": "Restore Recommended resets the harness, reasoning effort, and Fast. Existing favorites stay unchanged.",
+ "saveFavoriteHint": "Save these settings for quick access from Favorites.",
+ "removeFavoriteHint": "Removing the shortcut leaves your current settings unchanged.",
+ "editFavorite": "Edit Original Favorite",
+ "editFavoriteHint": "Changes apply to this favorite only after saving. The configuration in use stays unchanged.",
+ "saveFavorite": "Save Favorite",
+ "cancelEdit": "Cancel Editing",
+ "originalFavoriteKept": "Settings updated. The original favorite is unchanged.",
+ "parametersSaved": "Settings saved.",
+ "restoredHint": "Recommended settings restored. Existing favorites are unchanged.",
+ "favoriteRemoved": "Favorite removed. Current settings are unchanged.",
+ "favoriteSaved": "Configuration added to Favorites.",
+ "favoriteUpdated": "Favorite updated. The configuration in use is unchanged.",
+ "favoriteChanged": "This favorite was changed or removed. Cancel editing and reopen it to try again.",
+ "favoriteExists": "This configuration is already in Favorites. Cancel editing to use it.",
"favorites": "Favorites",
"all": "All models",
"recommended": "Recommended",
"source": "Source",
"harness": "Harness",
- "addFavorite": "Add to favorites",
- "removeFavorite": "Remove favorite",
"restoreRecommended": "Restore recommended",
"saveFailed": "Could not save. Please try again.",
"configure": "Configure",
diff --git a/apps/mobile/src/i18n/locales/ja/models.json b/apps/mobile/src/i18n/locales/ja/models.json
index 79db508984..d4baa1e8a8 100644
--- a/apps/mobile/src/i18n/locales/ja/models.json
+++ b/apps/mobile/src/i18n/locales/ja/models.json
@@ -59,13 +59,31 @@
"confirm": "続けて選択"
},
"unified": {
+ "favoriteConfiguration": "この設定をお気に入りに追加",
+ "savedConfiguration": "登録済み · タップして解除",
+ "currentConfiguration": "現在の設定",
+ "usingRecommended": "推奨設定を使用中",
+ "customized": "カスタマイズ済み",
+ "resetScopeHint": "推奨設定に戻すと、ハーネス、推論強度、Fast がリセットされます。既存のお気に入りは変わりません。",
+ "saveFavoriteHint": "この設定を保存して、次回からお気に入りですぐに選べます。",
+ "removeFavoriteHint": "お気に入りを解除しても、現在の設定は変わりません。",
+ "editFavorite": "元のお気に入りを編集",
+ "editFavoriteHint": "このお気に入りだけを編集し、保存後に反映します。使用中の設定は変わりません。",
+ "saveFavorite": "お気に入りを保存",
+ "cancelEdit": "編集をキャンセル",
+ "originalFavoriteKept": "設定を変更しました。元のお気に入りは保持されています。",
+ "parametersSaved": "設定を保存しました。",
+ "restoredHint": "推奨設定に戻しました。既存のお気に入りは変わりません。",
+ "favoriteRemoved": "お気に入りを解除しました。現在の設定は変わりません。",
+ "favoriteSaved": "この設定をお気に入りに追加しました。",
+ "favoriteUpdated": "お気に入りを更新しました。使用中の設定は変わりません。",
+ "favoriteChanged": "このお気に入りは変更または削除されました。編集をキャンセルし、開き直してお試しください。",
+ "favoriteExists": "同じ設定がすでにお気に入りにあります。編集をキャンセルして使用できます。",
"favorites": "お気に入り",
"all": "すべてのモデル",
"recommended": "おすすめ",
"source": "接続元",
"harness": "Harness",
- "addFavorite": "お気に入りに追加",
- "removeFavorite": "お気に入りを解除",
"restoreRecommended": "推奨設定に戻す",
"saveFailed": "保存できませんでした。再試行してください。",
"configure": "設定",
diff --git a/apps/mobile/src/i18n/locales/ko/models.json b/apps/mobile/src/i18n/locales/ko/models.json
index ec357c9f7a..c0882e5914 100644
--- a/apps/mobile/src/i18n/locales/ko/models.json
+++ b/apps/mobile/src/i18n/locales/ko/models.json
@@ -59,13 +59,31 @@
"confirm": "계속 선택"
},
"unified": {
+ "favoriteConfiguration": "이 설정을 즐겨찾기에 추가",
+ "savedConfiguration": "즐겨찾기에 추가됨 · 눌러서 해제",
+ "currentConfiguration": "현재 설정",
+ "usingRecommended": "권장 설정 사용 중",
+ "customized": "사용자 지정됨",
+ "resetScopeHint": "권장 설정 복원은 하네스, 추론 강도, Fast를 초기화합니다. 기존 즐겨찾기는 유지됩니다.",
+ "saveFavoriteHint": "다음에 즐겨찾기에서 바로 사용할 수 있도록 이 설정을 저장합니다.",
+ "removeFavoriteHint": "즐겨찾기를 해제해도 현재 설정은 유지됩니다.",
+ "editFavorite": "원래 즐겨찾기 편집",
+ "editFavoriteHint": "이 즐겨찾기만 편집하며 저장 후 적용됩니다. 사용 중인 설정은 유지됩니다.",
+ "saveFavorite": "즐겨찾기 저장",
+ "cancelEdit": "편집 취소",
+ "originalFavoriteKept": "설정이 변경되었습니다. 원래 즐겨찾기는 유지됩니다.",
+ "parametersSaved": "설정이 저장되었습니다.",
+ "restoredHint": "권장 설정이 복원되었습니다. 기존 즐겨찾기는 유지됩니다.",
+ "favoriteRemoved": "즐겨찾기가 해제되었습니다. 현재 설정은 유지됩니다.",
+ "favoriteSaved": "이 설정이 즐겨찾기에 추가되었습니다.",
+ "favoriteUpdated": "즐겨찾기가 업데이트되었습니다. 사용 중인 설정은 유지됩니다.",
+ "favoriteChanged": "이 즐겨찾기가 변경되거나 삭제되었습니다. 편집을 취소하고 다시 열어 주세요.",
+ "favoriteExists": "동일한 설정이 이미 즐겨찾기에 있습니다. 편집을 취소하고 사용할 수 있습니다.",
"favorites": "즐겨찾기",
"all": "모든 모델",
"recommended": "추천",
"source": "공급원",
"harness": "Harness",
- "addFavorite": "즐겨찾기에 추가",
- "removeFavorite": "즐겨찾기 해제",
"restoreRecommended": "권장 설정 복원",
"saveFailed": "저장하지 못했습니다. 다시 시도하세요.",
"configure": "설정",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/models.json b/apps/mobile/src/i18n/locales/zh-CN/models.json
index 54f8789263..b9b4bbcce9 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/models.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/models.json
@@ -59,13 +59,31 @@
"confirm": "继续选择"
},
"unified": {
+ "favoriteConfiguration": "收藏此配置",
+ "savedConfiguration": "已收藏 · 点击取消",
+ "currentConfiguration": "当前配置",
+ "usingRecommended": "使用推荐设置",
+ "customized": "已自定义",
+ "resetScopeHint": "恢复推荐会重置引擎、推理强度和 Fast,已有收藏保持不变。",
+ "saveFavoriteHint": "保存这套参数,方便下次从收藏列表直接使用。",
+ "removeFavoriteHint": "取消仅移除快捷入口,当前参数保持不变。",
+ "editFavorite": "编辑原收藏",
+ "editFavoriteHint": "仅编辑这条收藏,保存后生效;正在使用的配置保持不变。",
+ "saveFavorite": "保存收藏",
+ "cancelEdit": "取消编辑",
+ "originalFavoriteKept": "参数已调整,原收藏保留。",
+ "parametersSaved": "参数已保存。",
+ "restoredHint": "已恢复推荐设置,已有收藏保持不变。",
+ "favoriteRemoved": "已取消收藏,当前参数保持不变。",
+ "favoriteSaved": "已收藏这套配置。",
+ "favoriteUpdated": "收藏已更新,正在使用的配置保持不变。",
+ "favoriteChanged": "原收藏已被修改或删除。取消编辑后重新打开再试。",
+ "favoriteExists": "已存在相同配置的收藏。取消编辑后可直接使用。",
"favorites": "收藏",
"all": "全部模型",
"recommended": "推荐",
"source": "来源",
"harness": "Harness",
- "addFavorite": "添加收藏",
- "removeFavorite": "取消收藏",
"restoreRecommended": "恢复推荐",
"saveFailed": "未能保存,请重试。",
"configure": "设置",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/models.json b/apps/mobile/src/i18n/locales/zh-TW/models.json
index 30d526d8a8..3a39de6556 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/models.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/models.json
@@ -59,13 +59,31 @@
"confirm": "繼續選擇"
},
"unified": {
+ "favoriteConfiguration": "收藏此設定",
+ "savedConfiguration": "已收藏 · 點擊取消",
+ "currentConfiguration": "目前設定",
+ "usingRecommended": "使用推薦設定",
+ "customized": "已自訂",
+ "resetScopeHint": "恢復推薦會重設引擎、推理強度和 Fast,已有收藏保持不變。",
+ "saveFavoriteHint": "儲存這組參數,方便下次從收藏清單直接使用。",
+ "removeFavoriteHint": "取消只移除快捷入口,目前參數保持不變。",
+ "editFavorite": "編輯原收藏",
+ "editFavoriteHint": "僅編輯這筆收藏,儲存後生效;正在使用的設定保持不變。",
+ "saveFavorite": "儲存收藏",
+ "cancelEdit": "取消編輯",
+ "originalFavoriteKept": "參數已調整,原收藏保留。",
+ "parametersSaved": "參數已儲存。",
+ "restoredHint": "已恢復推薦設定,已有收藏保持不變。",
+ "favoriteRemoved": "已取消收藏,目前參數保持不變。",
+ "favoriteSaved": "已收藏這組設定。",
+ "favoriteUpdated": "收藏已更新,正在使用的設定保持不變。",
+ "favoriteChanged": "原收藏已被修改或刪除。取消編輯後重新開啟再試。",
+ "favoriteExists": "已存在相同設定的收藏。取消編輯後可直接使用。",
"favorites": "收藏",
"all": "全部模型",
"recommended": "推薦",
"source": "來源",
"harness": "Harness",
- "addFavorite": "加入收藏",
- "removeFavorite": "取消收藏",
"restoreRecommended": "恢復推薦",
"saveFailed": "無法儲存,請重試。",
"configure": "設定",
diff --git a/apps/mobile/src/session/ComposerSheet.ios.tsx b/apps/mobile/src/session/ComposerSheet.ios.tsx
index f0fa794e20..126014bfc9 100644
--- a/apps/mobile/src/session/ComposerSheet.ios.tsx
+++ b/apps/mobile/src/session/ComposerSheet.ios.tsx
@@ -11,9 +11,15 @@ import {
Spacer,
Text,
VStack,
+ ZStack,
} from "@expo/ui/swift-ui";
import {
accessibilityLabel,
+ accessibilityElement,
+ accessibilityHidden,
+ disabled,
+ opacity,
+ scrollDisabled,
contentShape,
shapes,
buttonStyle,
@@ -46,6 +52,7 @@ export function ComposerSheet({
testID,
nativeContent,
nativeHeader,
+ nativeRoot,
preventDismiss = false,
}: ComposerSheetProps) {
const { mode, colors } = useTheme();
@@ -95,7 +102,7 @@ export function ComposerSheet({
<Spacer />
{onBack ? <Spacer modifiers={[frame({ width: 44 })]} /> : null}
</HStack> : null}
- {nativeHeader}
+ {!nativeRoot && nativeHeader}
{aboveContent && aboveContentTitle ? (
<Text modifiers={[
font({ textStyle: "subheadline" }),
@@ -111,7 +118,49 @@ export function ComposerSheet({
</View>
</RNHostView>
) : null}
- {nativeContent ? (
+ {nativeContent && nativeRoot ? (
+ <ZStack
+ modifiers={[frame({ maxWidth: Infinity, maxHeight: Infinity })]}
+ >
+ <VStack
+ spacing={0}
+ modifiers={[
+ frame({ maxWidth: Infinity, maxHeight: Infinity }),
+ opacity(nativeRoot.active ? 1 : 0),
+ disabled(!nativeRoot.active),
+ scrollDisabled(!nativeRoot.active),
+ accessibilityElement(
+ nativeRoot.active ? "contain" : "ignore",
+ ),
+ accessibilityHidden(!nativeRoot.active),
+ ]}
+ >
+ {nativeRoot.header}
+ <Form
+ testID={testID ? `${testID}.list` : undefined}
+ modifiers={[scrollContentBackground("hidden")]}
+ >
+ {nativeRoot.content}
+ </Form>
+ </VStack>
+ {!nativeRoot.active ? (
+ <VStack
+ spacing={0}
+ modifiers={[
+ frame({ maxWidth: Infinity, maxHeight: Infinity }),
+ ]}
+ >
+ {nativeHeader}
+ <Form
+ testID={testID}
+ modifiers={[scrollContentBackground("hidden")]}
+ >
+ {children}
+ </Form>
+ </VStack>
+ ) : null}
+ </ZStack>
+ ) : nativeContent ? (
<Form testID={testID} modifiers={[
scrollContentBackground("hidden"),
...(aboveContent ? [padding({ top: -12 })] : []),
diff --git a/apps/mobile/src/session/ComposerSheet.tsx b/apps/mobile/src/session/ComposerSheet.tsx
index 1f5cb19c62..e3b805132f 100644
--- a/apps/mobile/src/session/ComposerSheet.tsx
+++ b/apps/mobile/src/session/ComposerSheet.tsx
@@ -4,6 +4,8 @@ export interface ComposerSheetProps {
/** Protect an unsaved or in-flight form; explicit Back/Save remains available. */
preventDismiss?: boolean;
nativeHeader?: ReactNode;
+ /** Keep the native root list mounted while a secondary page is shown. */
+ nativeRoot?: { active: boolean; header?: ReactNode; content: ReactNode };
visible: boolean;
onClose(): void;
onClosed?(): void;
diff --git a/apps/mobile/src/session/UnifiedModelPickerSheet.tsx b/apps/mobile/src/session/UnifiedModelPickerSheet.tsx
index 910bd8a591..54d50351bb 100644
--- a/apps/mobile/src/session/UnifiedModelPickerSheet.tsx
+++ b/apps/mobile/src/session/UnifiedModelPickerSheet.tsx
@@ -1,4 +1,4 @@
-import { mobileProviderAccountTitle } from './mobileModelRowPresentation';
+import { mobileProviderAccountTitle } from "./mobileModelRowPresentation";
import { mobileCostMarks, quotaCountdown } from "./mobileModelRowPresentation";
import { useMobileModelQuotas } from "./useMobileModelQuotas";
import { useEffect, useMemo, useRef, useState } from "react";
@@ -26,16 +26,23 @@ import { useSessionModelMirrorVersion } from "./sessionModelMirror";
import { UnifiedModelPickerView } from "./UnifiedModelPickerView";
import { budgetRowDisabled, presentPickerPrice } from "./modelPickerRows";
import { mobileWeeklyQuota } from "./mobileModelRowPresentation";
+import { mobileAgentLabel } from "./sessionAgentSwitch";
function createFavoriteUid(): string {
const cryptoWithUuid = globalThis.crypto as Crypto | undefined;
- if (typeof cryptoWithUuid?.randomUUID === "function") return cryptoWithUuid.randomUUID();
- const expoWithUuid = ExpoCrypto as typeof ExpoCrypto & { randomUUID?: () => string };
- if (typeof expoWithUuid.randomUUID === "function") return expoWithUuid.randomUUID();
+ if (typeof cryptoWithUuid?.randomUUID === "function")
+ return cryptoWithUuid.randomUUID();
+ const expoWithUuid = ExpoCrypto as typeof ExpoCrypto & {
+ randomUUID?: () => string;
+ };
+ if (typeof expoWithUuid.randomUUID === "function")
+ return expoWithUuid.randomUUID();
const bytes = ExpoCrypto.getRandomBytes(16);
bytes[6] = (bytes[6] & 0x0f) | 0x40;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
- const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
+ const hex = Array.from(bytes, (byte) =>
+ byte.toString(16).padStart(2, "0"),
+ ).join("");
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}
@@ -101,6 +108,14 @@ export interface UnifiedMobilePickerViewProps {
fastCapable: boolean;
onChange(config: MobileModelConfiguration): void;
favoritesDisabled: boolean;
+ isFavorite?: boolean;
+ canReset?: boolean;
+ configurationSummary?: string;
+ notice?: string | null;
+ editingFavorite?: boolean;
+ onEditFavorite?(): void;
+ onCancelEdit?(): void;
+ onSaveEdit?(): void;
onFavorite(): void;
onReset(): void;
context: string;
@@ -112,7 +127,8 @@ export function UnifiedModelPickerSheet(
p: ModelPickerSheetProps & { unified: UnifiedMobilePickerOptions },
) {
const { t } = useTranslation();
- const countdown = (reset: number, now: number) => quotaCountdown(reset, now, unit => t(`models.unified.timeUnit.${unit}`));
+ const countdown = (reset: number, now: number) =>
+ quotaCountdown(reset, now, (unit) => t(`models.unified.timeUnit.${unit}`));
const { quotas, now } = useMobileModelQuotas(
p.unified.scope,
p.visible,
@@ -127,18 +143,28 @@ export function UnifiedModelPickerSheet(
providerId: string;
modelId: string;
uid?: string;
+ config?: MobileModelConfiguration;
+ } | null>(null);
+ const [favoriteEdit, setFavoriteEdit] = useState<{
+ original: MobileModelFavorite;
+ config: MobileModelConfiguration;
} | null>(null);
+ const [notice, setNotice] = useState<string | null>(null);
const [caps, setCaps] = useState<
Partial<Record<AgentKind, MobileAgentCapabilities>>
>({});
const [busy, setBusy] = useState(false);
const lock = useRef(false);
+ const opening = useRef(0);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!p.visible) return;
+ opening.current += 1;
setQuery("");
setFilter("all");
setTarget(null);
+ setFavoriteEdit(null);
+ setNotice(null);
setError(null);
let cancelled = false;
setCaps({ [p.agentKind]: p.capabilities });
@@ -154,6 +180,7 @@ export function UnifiedModelPickerSheet(
});
return () => {
cancelled = true;
+ opening.current += 1;
};
}, [p.visible, p.unified.scope]);
const entries = useMemo(
@@ -194,23 +221,26 @@ export function UnifiedModelPickerSheet(
effort: p.selectedEffort,
fast: p.selectedFastMode,
};
- // The visible selection may be a pending next-message engine switch. Keep
- // runtime truth separate, including its provider resolution and capabilities.
+ // The visible selection may belong to a pending next-message engine switch.
+ // Resolve the running configuration separately when editing its favorite.
const current = p.unified.currentSelection;
- const live: MobileModelConfiguration = current ? {
- providerId: buildMobileModelSections({
- providers: p.providers,
- agentKind: current.agentKind,
- selectedModelId: current.activeModelId,
- selectedProviderId: current.selectedProviderId,
- existingSessionRoute: p.existingSessionRoute,
- visibilityOverrides: p.modelVisibilityOverrides,
- }).activeSourceId ?? "",
- modelId: current.activeModelId,
- agent: current.agentKind,
- effort: current.selectedEffort,
- fast: current.selectedFastMode,
- } : selection;
+ const live: MobileModelConfiguration = current
+ ? {
+ providerId:
+ buildMobileModelSections({
+ providers: p.providers,
+ agentKind: current.agentKind,
+ selectedModelId: current.activeModelId,
+ selectedProviderId: current.selectedProviderId,
+ existingSessionRoute: p.existingSessionRoute,
+ visibilityOverrides: p.modelVisibilityOverrides,
+ }).activeSourceId ?? "",
+ modelId: current.activeModelId,
+ agent: current.agentKind,
+ effort: current.selectedEffort,
+ fast: current.selectedFastMode,
+ }
+ : selection;
const fastCapable = (agent: AgentKind) => caps[agent]?.hasFastMode === true;
const describe = (
entry: UnifiedModelEntry,
@@ -279,7 +309,9 @@ export function UnifiedModelPickerSheet(
),
quotaLabel: (() => {
const q = quotas[entry.providerId];
- const modelQuota = q ? mobileWeeklyQuota(q.source, q.raw, now, entry.modelId) : null;
+ const modelQuota = q
+ ? mobileWeeklyQuota(q.source, q.raw, now, entry.modelId)
+ : null;
return modelQuota
? [
modelQuota.resetsAt ? countdown(modelQuota.resetsAt, now) : null,
@@ -347,89 +379,179 @@ export function UnifiedModelPickerSheet(
rows: group,
});
}
- const row = target
- ? target.uid
- ? favorites.find((row) => row.favorite?.uid === target.uid)
- : rows.find(
- (row) =>
- row.entry.providerId === target.providerId &&
- row.entry.modelId === target.modelId,
- )
+ const sourceRow = target
+ ? rows.find(
+ (row) =>
+ row.entry.providerId === target.providerId &&
+ row.entry.modelId === target.modelId,
+ )
+ : undefined;
+ const originFavorite = target?.uid
+ ? prefs.value.favorites.find((item) => item.uid === target.uid)
: undefined;
+ // Opening a favorite copies its parameters into the detail view. Ordinary
+ // adjustments always edit model preferences, never the stored shortcut.
+ const row = sourceRow && {
+ ...sourceRow,
+ key: target?.uid ?? sourceRow.key,
+ config: favoriteEdit?.config ?? target?.config ?? sourceRow.config,
+ favorite: originFavorite,
+ };
+ // A source model can have several saved configurations. Match the complete
+ // configuration without applying capability fallbacks to the saved values.
+ const matchingFavorite =
+ row &&
+ prefs.value.favorites.find(
+ (item) =>
+ matchesEntry(row.entry, item.modelId) &&
+ sameConfiguration({ ...item, modelId: row.config.modelId }, row.config),
+ );
+ const recommendedConfig =
+ row &&
+ resolveMobileModelConfig(row.entry, {
+ pinned: p.existingSessionRoute ? p.agentKind : undefined,
+ fastCapable,
+ });
+ const resetAgents = row
+ ? [...new Set([row.config.agent, recommendedConfig!.agent])]
+ : [];
+ const canReset =
+ !!row &&
+ (!sameConfiguration(row.config, recommendedConfig!) ||
+ prefs.value.engines[modelKey(row.entry.providerId, row.entry.modelId)] !==
+ undefined ||
+ resetAgents.some((agent) => {
+ const capability = row.entry.capabilities[agent];
+ if (!capability) return false;
+ const effort = p.modelMemory?.getEffort(
+ agent,
+ row.entry.providerId,
+ capability.wireModelId,
+ );
+ const fast = p.modelMemory?.getFast(
+ agent,
+ row.entry.providerId,
+ capability.wireModelId,
+ );
+ // Session mirrors cannot delete remote preferences. Like Desktop, those
+ // accessors restore values; their default-valued echoes are not overrides.
+ return (
+ (effort !== undefined &&
+ (!!p.modelMemory?.clearEffort ||
+ effort !==
+ (capability.defaultEffort ?? capability.efforts[0] ?? ""))) ||
+ (fast !== undefined && (!!p.modelMemory?.clearFast || fast))
+ );
+ }));
useEffect(() => {
- if (target && !row) setTarget(null);
+ if (target && !row) {
+ setTarget(null);
+ setFavoriteEdit(null);
+ }
}, [target, row]);
- const transact = async (action: () => Promise<void>) => {
+ const transact = async (
+ action: (isCurrent: () => boolean) => Promise<void>,
+ ) => {
if (lock.current || p.disabled || !prefs.ready) return;
lock.current = true;
+ const generation = opening.current;
+ const isCurrent = () => generation === opening.current;
setBusy(true);
setError(null);
+ setNotice(null);
try {
- await action();
+ await action(isCurrent);
} catch {
- setError(t("models.unified.saveFailed"));
+ if (isCurrent()) setError(t("models.unified.saveFailed"));
} finally {
+ // Keep writes serialized across close/reopen until persistence settles.
+ // No newer transaction can be unlocked by this completion.
lock.current = false;
setBusy(false);
}
};
const select = (row: UnifiedMobileRow) => {
if (row.disabled) return;
- void transact(async () => {
- if (await p.unified.onSelect(row.config)) p.onClose();
+ void transact(async (isCurrent) => {
+ if ((await p.unified.onSelect(row.config)) && isCurrent()) p.onClose();
});
};
const change = (config: MobileModelConfiguration, reset = false) => {
if (!row) return;
- void transact(async () => {
- const appliesLive =
- row.selected || (!!row.favorite && sameConfiguration(row.config, live));
- if (appliesLive && !(await p.unified.onSelect(config))) return;
+ if (favoriteEdit) {
+ if (!lock.current && !p.disabled)
+ setFavoriteEdit({ ...favoriteEdit, config });
+ return;
+ }
+ void transact(async (isCurrent) => {
+ const previousConfig =
+ row.favorite && sameConfiguration(row.config, live)
+ ? live
+ : row.selected
+ ? selection
+ : undefined;
+ if (previousConfig && !(await p.unified.onSelect(config))) return;
+ // Selection can await remote work or a confirmation. Do not begin another
+ // write for a panel that closed or changed its binding while waiting.
+ if (!isCurrent()) return;
try {
- if (row.favorite) {
- await prefs.save({
- ...prefs.value,
- favorites: prefs.value.favorites.map((item) =>
- item.uid === row.favorite!.uid
- ? { ...config, modelId: item.modelId, uid: item.uid }
- : item,
- ),
- });
+ const engines = { ...prefs.value.engines };
+ const key = modelKey(row.entry.providerId, row.entry.modelId);
+ if (reset) delete engines[key];
+ else engines[key] = config.agent;
+ await prefs.save({ ...prefs.value, engines });
+ if (reset) {
+ // Reset the model's overrides, including the previous engine's
+ // parameters. Other models and saved favorite copies stay intact.
+ for (const agent of resetAgents) {
+ const capability = row.entry.capabilities[agent];
+ if (!capability) continue;
+ const modelId = capability.wireModelId;
+ const effort =
+ capability.defaultEffort ?? capability.efforts[0] ?? "";
+ if (p.modelMemory?.clearEffort)
+ p.modelMemory.clearEffort(agent, config.providerId, modelId);
+ else if (effort)
+ p.modelMemory?.setEffort(
+ agent,
+ config.providerId,
+ modelId,
+ effort,
+ );
+ if (p.modelMemory?.clearFast)
+ p.modelMemory.clearFast(agent, config.providerId, modelId);
+ else
+ p.modelMemory?.setFast(agent, config.providerId, modelId, false);
+ }
} else {
- const engines = { ...prefs.value.engines };
- const key = modelKey(row.entry.providerId, row.entry.modelId);
- if (reset) delete engines[key];
- else engines[key] = config.agent;
- await prefs.save({ ...prefs.value, engines });
- if (reset && p.modelMemory?.clearEffort)
- p.modelMemory.clearEffort(
- config.agent,
- config.providerId,
- config.modelId,
- );
- else if (config.effort)
+ if (config.effort)
p.modelMemory?.setEffort(
config.agent,
config.providerId,
config.modelId,
config.effort,
);
- if (reset && p.modelMemory?.clearFast)
- p.modelMemory.clearFast(
- config.agent,
- config.providerId,
- config.modelId,
- );
- else
- p.modelMemory?.setFast(
- config.agent,
- config.providerId,
- config.modelId,
- config.fast,
- );
+ p.modelMemory?.setFast(
+ config.agent,
+ config.providerId,
+ config.modelId,
+ config.fast,
+ );
}
+ if (!isCurrent()) return;
+ if (target?.config) setTarget({ ...target, config });
+ setNotice(
+ t(
+ reset
+ ? "models.unified.restoredHint"
+ : matchingFavorite
+ ? "models.unified.originalFavoriteKept"
+ : "models.unified.parametersSaved",
+ ),
+ );
} catch (error) {
- if (appliesLive) await p.unified.onSelect(row.selected ? selection : live);
+ if (previousConfig && isCurrent())
+ await p.unified.onSelect(previousConfig);
throw error;
}
});
@@ -453,12 +575,19 @@ export function UnifiedModelPickerSheet(
onBack={
row
? () => {
- setTarget(null);
+ if (lock.current) return;
+ if (favoriteEdit) setFavoriteEdit(null);
+ else setTarget(null);
setError(null);
+ setNotice(null);
}
: undefined
}
- title={row?.entry.displayName ?? t("models.picker.title")}
+ title={
+ favoriteEdit
+ ? t("models.unified.editFavorite")
+ : (row?.entry.displayName ?? t("models.picker.title"))
+ }
testID={p.testID ?? "modelSheet"}
query={query}
onQuery={setQuery}
@@ -466,7 +595,9 @@ export function UnifiedModelPickerSheet(
onFilter={setFilter}
filters={[
{ id: "all", label: t("models.unified.all") },
- ...(prefs.favoritesReady ? [{ id: "favorites", label: t("models.unified.favorites") }] : []),
+ ...(prefs.favoritesReady
+ ? [{ id: "favorites", label: t("models.unified.favorites") }]
+ : []),
...p.providers
.filter((provider) =>
entries.some((e) => e.providerId === provider.id),
@@ -474,27 +605,28 @@ export function UnifiedModelPickerSheet(
.map((provider) => ({
id: provider.id,
label: providerName(provider.id),
- quota: quotas[provider.id]?.remaining !== undefined
- ? {
- remaining: quotas[provider.id]!.remaining!,
- label: [
- t("session.menu.usage.week"),
- t("session.menu.usage.remaining", {
- percent: quotas[provider.id]!.remaining,
- }),
- quotas[provider.id]!.resetsAt
- ? t("session.menu.usage.resets", {
- time: countdown(
- quotas[provider.id]!.resetsAt!,
- now,
- ),
- })
- : null,
- ]
- .filter(Boolean)
- .join(" · "),
- }
- : undefined,
+ quota:
+ quotas[provider.id]?.remaining !== undefined
+ ? {
+ remaining: quotas[provider.id]!.remaining!,
+ label: [
+ t("session.menu.usage.week"),
+ t("session.menu.usage.remaining", {
+ percent: quotas[provider.id]!.remaining,
+ }),
+ quotas[provider.id]!.resetsAt
+ ? t("session.menu.usage.resets", {
+ time: countdown(
+ quotas[provider.id]!.resetsAt!,
+ now,
+ ),
+ })
+ : null,
+ ]
+ .filter(Boolean)
+ .join(" · "),
+ }
+ : undefined,
providerMark: {
providerId: provider.id,
name: provider.name,
@@ -509,13 +641,18 @@ export function UnifiedModelPickerSheet(
loading={!!p.loading}
emptyHint={p.emptyHint ?? t("models.picker.noResults")}
onSelect={select}
- onOptions={(row) =>
+ onOptions={(row) => {
+ if (lock.current) return;
+ setFavoriteEdit(null);
+ setNotice(null);
+ setError(null);
setTarget({
providerId: row.entry.providerId,
modelId: row.entry.modelId,
uid: row.favorite?.uid,
- })
- }
+ config: row.favorite ? { ...row.config } : undefined,
+ });
+ }}
options={
row
? {
@@ -538,30 +675,94 @@ export function UnifiedModelPickerSheet(
.join(" · "),
price: price ? `${price.title}\n${price.amountsLine}` : null,
favoritesDisabled: !prefs.favoritesReady,
- onFavorite: () => {
- if (!prefs.favoritesReady) return;
- void transact(async () => {
- if (row.favorite) {
- if (sameConfiguration(row.config, live)) {
- const fallback = resolveMobileModelConfig(row.entry, {
- fastCapable,
- });
- if (!(await p.unified.onSelect(fallback))) return;
- }
- try {
- await prefs.save({
- ...prefs.value,
- favorites: prefs.value.favorites.filter(
- (item) => item.uid !== row.favorite!.uid,
- ),
+ isFavorite: !!matchingFavorite,
+ canReset,
+ configurationSummary: [
+ mobileAgentLabel(row.config.agent),
+ row.config.effort
+ ? t(`models.options.effortLevels.${row.config.effort}`, {
+ defaultValue: row.config.effort,
+ })
+ : null,
+ row.config.fast ? "Fast" : null,
+ ]
+ .filter(Boolean)
+ .join(" · "),
+ notice,
+ editingFavorite: !!favoriteEdit,
+ onEditFavorite:
+ originFavorite && !favoriteEdit
+ ? () => {
+ if (lock.current || p.disabled) return;
+ setFavoriteEdit({
+ original: { ...originFavorite },
+ config: resolveMobileModelConfig(row.entry, {
+ favorite: originFavorite,
+ fastCapable,
+ }),
});
- } catch (error) {
- if (sameConfiguration(row.config, live))
- await p.unified.onSelect(live);
- throw error;
+ setNotice(null);
+ setError(null);
}
- setTarget(null);
- } else
+ : undefined,
+ onCancelEdit: () => {
+ if (lock.current) return;
+ setFavoriteEdit(null);
+ setError(null);
+ setNotice(null);
+ },
+ onSaveEdit: () => {
+ if (!favoriteEdit) return;
+ void transact(async (isCurrent) => {
+ const original = prefs.value.favorites.find(
+ (item) => item.uid === favoriteEdit.original.uid,
+ );
+ if (
+ !original ||
+ !sameConfiguration(original, favoriteEdit.original)
+ ) {
+ setError(t("models.unified.favoriteChanged"));
+ return;
+ }
+ if (
+ matchingFavorite &&
+ matchingFavorite.uid !== original.uid
+ ) {
+ setError(t("models.unified.favoriteExists"));
+ return;
+ }
+ const config = favoriteEdit.config;
+ await prefs.save({
+ ...prefs.value,
+ favorites: prefs.value.favorites.map((item) =>
+ item.uid === original.uid
+ ? {
+ ...config,
+ modelId: row.entry.modelId,
+ uid: item.uid,
+ }
+ : item,
+ ),
+ });
+ if (!isCurrent()) return;
+ setFavoriteEdit(null);
+ if (target) setTarget({ ...target, config });
+ setNotice(t("models.unified.favoriteUpdated"));
+ });
+ },
+ onFavorite: () => {
+ if (!prefs.favoritesReady || favoriteEdit) return;
+ void transact(async (isCurrent) => {
+ if (matchingFavorite) {
+ await prefs.save({
+ ...prefs.value,
+ favorites: prefs.value.favorites.filter(
+ (item) => item.uid !== matchingFavorite.uid,
+ ),
+ });
+ if (isCurrent())
+ setNotice(t("models.unified.favoriteRemoved"));
+ } else {
await prefs.save(
addModelFavorite(
prefs.value,
@@ -569,13 +770,12 @@ export function UnifiedModelPickerSheet(
createFavoriteUid(),
),
);
+ if (isCurrent())
+ setNotice(t("models.unified.favoriteSaved"));
+ }
});
},
- onReset: () =>
- change(
- resolveMobileModelConfig(row.entry, { fastCapable }),
- true,
- ),
+ onReset: () => change(recommendedConfig!, true),
}
: undefined
}
diff --git a/apps/mobile/src/session/UnifiedModelPickerView.ios.tsx b/apps/mobile/src/session/UnifiedModelPickerView.ios.tsx
index 1ffce9dd4b..4d2903e96f 100644
--- a/apps/mobile/src/session/UnifiedModelPickerView.ios.tsx
+++ b/apps/mobile/src/session/UnifiedModelPickerView.ios.tsx
@@ -87,9 +87,189 @@ export function UnifiedModelPickerView(p: UnifiedMobilePickerViewProps) {
if (search.get() !== p.query) search.set(p.query);
}, [p.query, search]);
const options = p.options;
+ const isFavorite = options?.isFavorite ?? !!options?.row.favorite;
const config = options?.row.config;
const level = (id: string) =>
t(`models.options.effortLevels.${id}`, { defaultValue: id });
+ const listHeader = (
+ <HStack spacing={12} modifiers={[padding({ horizontal: 20, bottom: 4 })]}>
+ {mark(Search)}
+ <TextField
+ text={search}
+ onTextChange={p.onQuery}
+ placeholder={t("models.picker.searchPlaceholder")}
+ modifiers={[
+ frame({ maxWidth: Infinity, minHeight: 44 }),
+ autocorrectionDisabled(),
+ textInputAutocapitalization("never"),
+ ]}
+ testID={`${p.testID}.search`}
+ />
+ {p.query ? (
+ <Button
+ onPress={() => p.onQuery("")}
+ modifiers={[
+ buttonStyle("plain"),
+ accessibilityLabel(t("devices.detail.search.clearA11y")),
+ ]}
+ >
+ <HStack modifiers={[frame({ width: 44, height: 44 })]}>
+ {mark(X)}
+ </HStack>
+ </Button>
+ ) : null}
+ <Button
+ onPress={() => setPage("sources")}
+ modifiers={[
+ buttonStyle("plain"),
+ frame({ maxWidth: 120, minHeight: 44 }),
+ accessibilityLabel(t("models.unified.source")),
+ ]}
+ testID={`${p.testID}.filter`}
+ >
+ <HStack>
+ {p.filter === "favorites" ? (
+ mark(Star, true)
+ ) : p.filter === "all" ? (
+ mark(LayoutGrid)
+ ) : (
+ <NativeMark>
+ <MobileProviderMark
+ {...p.filters.find((item) => item.id === p.filter)
+ ?.providerMark}
+ name={
+ p.filters.find((item) => item.id === p.filter)?.providerMark
+ ?.name ?? ""
+ }
+ />
+ </NativeMark>
+ )}
+ <Text modifiers={[lineLimit(1)]}>
+ {p.filters.find((item) => item.id === p.filter)?.label}
+ </Text>
+ </HStack>
+ </Button>
+ </HStack>
+ );
+ const listContent = (
+ <>
+ {p.error ? (
+ <Section>
+ <Text modifiers={[foregroundStyle(colors.errorText)]}>{p.error}</Text>
+ </Section>
+ ) : null}
+ {p.groups.map((group) => (
+ <Section key={group.key} title={group.title}>
+ {group.rows.map((row) => (
+ <ComposerNativeRow
+ key={row.key}
+ title={row.entry.displayName}
+ subtitle={[
+ mobileAgentLabel(row.config.agent),
+ row.subtitle,
+ row.quotaLabel,
+ ]
+ .filter(Boolean)
+ .join(" · ")}
+ titleAccessory={
+ <HStack spacing={4}>
+ {row.costMarks ? (
+ <Text
+ modifiers={[
+ font({ textStyle: "caption" }),
+ foregroundStyle(colors.textSecondary),
+ ]}
+ >
+ {row.costMarks}
+ </Text>
+ ) : null}
+ <RNHostView matchContents>
+ <View
+ pointerEvents="none"
+ style={{ width: iconSize.sm, height: iconSize.sm }}
+ >
+ <MobileAgentMark
+ agentKind={row.config.agent}
+ color={colors.textSecondary}
+ />
+ </View>
+ </RNHostView>
+ {row.effortLabel ? (
+ <Text
+ modifiers={[
+ font({ textStyle: "caption" }),
+ foregroundStyle(colors.textSecondary),
+ ]}
+ >
+ {row.effortLabel}
+ </Text>
+ ) : null}
+ {row.config.fast ? mark(Zap, true) : null}
+ </HStack>
+ }
+ subtitleContent={
+ <VStack alignment="leading" spacing={2}>
+ <Text
+ modifiers={[
+ font({ textStyle: "caption" }),
+ foregroundStyle(colors.textSecondary),
+ ]}
+ >
+ {row.subtitle}
+ </Text>
+ {row.quotaLabel ? (
+ <Text
+ modifiers={[
+ font({ textStyle: "caption2" }),
+ foregroundStyle(colors.textTertiary),
+ ]}
+ >
+ {row.quotaLabel}
+ </Text>
+ ) : null}
+ </VStack>
+ }
+ leading={
+ <RNHostView matchContents>
+ <View
+ style={{
+ width: 28,
+ height: 28,
+ justifyContent: "center",
+ }}
+ >
+ <MobileModelIconMark
+ icon={row.entry.icon}
+ {...row.providerMark}
+ color={colors.textSecondary}
+ />
+ </View>
+ </RNHostView>
+ }
+ optionsIcon={mark(SlidersHorizontal)}
+ selectionIcon={mark(Check)}
+ accessory={row.favorite ? mark(Star, true) : undefined}
+ selected={row.selected}
+ disabled={p.busy || row.disabled}
+ onPress={() => p.onSelect(row)}
+ onOptions={() => p.onOptions(row)}
+ optionsLabel={t("models.picker.configureAccessibility", {
+ model: row.entry.displayName,
+ })}
+ testID={`${p.testID}.model.${row.key}`}
+ />
+ ))}
+ </Section>
+ ))}
+ {!p.groups.length ? (
+ <Section>
+ <Text modifiers={[foregroundStyle(colors.textSecondary)]}>
+ {p.loading ? t("models.picker.loadingDefault") : p.emptyHint}
+ </Text>
+ </Section>
+ ) : null}
+ </>
+ );
return (
<ComposerSheet
nativeContent
@@ -106,71 +286,11 @@ export function UnifiedModelPickerView(p: UnifiedMobilePickerViewProps) {
: p.title
}
testID={p.testID}
- nativeHeader={
- !options && !page ? (
- <HStack
- spacing={12}
- modifiers={[padding({ horizontal: 20, bottom: 4 })]}
- >
- {mark(Search)}
- <TextField
- text={search}
- onTextChange={p.onQuery}
- placeholder={t("models.picker.searchPlaceholder")}
- modifiers={[
- frame({ maxWidth: Infinity, minHeight: 44 }),
- autocorrectionDisabled(),
- textInputAutocapitalization("never"),
- ]}
- testID={`${p.testID}.search`}
- />
- {p.query ? (
- <Button
- onPress={() => p.onQuery("")}
- modifiers={[
- buttonStyle("plain"),
- accessibilityLabel(t("devices.detail.search.clearA11y")),
- ]}
- >
- <HStack modifiers={[frame({ width: 44, height: 44 })]}>
- {mark(X)}
- </HStack>
- </Button>
- ) : null}
- <Button
- onPress={() => setPage("sources")}
- modifiers={[
- buttonStyle("plain"),
- frame({ maxWidth: 120, minHeight: 44 }),
- accessibilityLabel(t("models.unified.source")),
- ]}
- testID={`${p.testID}.filter`}
- >
- <HStack>
- {p.filter === "favorites" ? (
- mark(Star, true)
- ) : p.filter === "all" ? (
- mark(LayoutGrid)
- ) : (
- <NativeMark>
- <MobileProviderMark
- {...p.filters.find((item) => item.id === p.filter)
- ?.providerMark}
- name={
- p.filters.find((item) => item.id === p.filter)
- ?.providerMark?.name ?? ""
- }
- />
- </NativeMark>
- )}
- <Text modifiers={[lineLimit(1)]}>
- {p.filters.find((item) => item.id === p.filter)?.label}
- </Text>
- </HStack>
- </Button>
- </HStack>
- ) : undefined
- }
+ nativeRoot={{
+ active: !options && !page,
+ header: listHeader,
+ content: listContent,
+ }}
>
{p.error ? (
<Section>
@@ -264,6 +384,28 @@ export function UnifiedModelPickerView(p: UnifiedMobilePickerViewProps) {
{options.context}
</Text>
</Section>
+ {options.onEditFavorite ? (
+ <Section>
+ <ComposerNativeRow
+ title={t("models.unified.editFavorite")}
+ onPress={options.onEditFavorite}
+ disabled={p.busy || options.favoritesDisabled}
+ testID={`${p.testID}.editFavorite`}
+ />
+ </Section>
+ ) : null}
+ {options.editingFavorite ? (
+ <Section>
+ <Text
+ modifiers={[
+ font({ textStyle: "footnote" }),
+ foregroundStyle(colors.textSecondary),
+ ]}
+ >
+ {t("models.unified.editFavoriteHint")}
+ </Text>
+ </Section>
+ ) : null}
<Section>
<ComposerNativeRow
title={t("models.unified.harness")}
@@ -312,6 +454,39 @@ export function UnifiedModelPickerView(p: UnifiedMobilePickerViewProps) {
</HStack>
) : null}
</Section>
+ {!options.editingFavorite ? (
+ <Section>
+ <Text
+ testID={`${p.testID}.configState`}
+ modifiers={[
+ font({ textStyle: "footnote" }),
+ foregroundStyle(colors.textSecondary),
+ ]}
+ >
+ {t(
+ options.canReset
+ ? "models.unified.customized"
+ : "models.unified.usingRecommended",
+ )}
+ </Text>
+ {options.canReset ? (
+ <ComposerNativeRow
+ title={t("models.unified.restoreRecommended")}
+ onPress={options.onReset}
+ disabled={p.busy}
+ testID={`${p.testID}.reset`}
+ />
+ ) : null}
+ <Text
+ modifiers={[
+ font({ textStyle: "footnote" }),
+ foregroundStyle(colors.textSecondary),
+ ]}
+ >
+ {t("models.unified.resetScopeHint")}
+ </Text>
+ </Section>
+ ) : null}
{options.price ? (
<Section>
<Text
@@ -324,142 +499,64 @@ export function UnifiedModelPickerView(p: UnifiedMobilePickerViewProps) {
</Text>
</Section>
) : null}
- <Section>
- <ComposerNativeRow
- title={t(
- options.row.favorite
- ? "models.unified.removeFavorite"
- : "models.unified.addFavorite",
- )}
- leading={mark(Star, !!options.row.favorite)}
- disabled={p.busy || options.favoritesDisabled}
- onPress={options.onFavorite}
- testID={`${p.testID}.favorite`}
- />
- {!options.row.favorite ? (
+ {options.editingFavorite ? (
+ <Section>
<ComposerNativeRow
- title={t("models.unified.restoreRecommended")}
+ title={t("models.unified.saveFavorite")}
+ onPress={() => options.onSaveEdit?.()}
+ disabled={p.busy || options.favoritesDisabled}
+ testID={`${p.testID}.saveFavorite`}
+ />
+ <ComposerNativeRow
+ title={t("models.unified.cancelEdit")}
+ onPress={() => options.onCancelEdit?.()}
disabled={p.busy}
- onPress={options.onReset}
- testID={`${p.testID}.reset`}
+ testID={`${p.testID}.cancelEdit`}
/>
- ) : null}
- </Section>
- </>
- ) : (
- <>
- {p.groups.map((group) => (
- <Section key={group.key} title={group.title}>
- {group.rows.map((row) => (
- <ComposerNativeRow
- key={row.key}
- title={row.entry.displayName}
- subtitle={[
- mobileAgentLabel(row.config.agent),
- row.subtitle,
- row.quotaLabel,
- ]
- .filter(Boolean)
- .join(" · ")}
- titleAccessory={
- <HStack spacing={4}>
- {row.costMarks ? (
- <Text
- modifiers={[
- font({ textStyle: "caption" }),
- foregroundStyle(colors.textSecondary),
- ]}
- >
- {row.costMarks}
- </Text>
- ) : null}
- <RNHostView matchContents>
- <View
- pointerEvents="none"
- style={{ width: iconSize.sm, height: iconSize.sm }}
- >
- <MobileAgentMark
- agentKind={row.config.agent}
- color={colors.textSecondary}
- />
- </View>
- </RNHostView>
- {row.effortLabel ? (
- <Text
- modifiers={[
- font({ textStyle: "caption" }),
- foregroundStyle(colors.textSecondary),
- ]}
- >
- {row.effortLabel}
- </Text>
- ) : null}
- {row.config.fast ? mark(Zap, true) : null}
- </HStack>
- }
- subtitleContent={
- <VStack alignment="leading" spacing={2}>
- <Text
- modifiers={[
- font({ textStyle: "caption" }),
- foregroundStyle(colors.textSecondary),
- ]}
- >
- {row.subtitle}
- </Text>
- {row.quotaLabel ? (
- <Text
- modifiers={[
- font({ textStyle: "caption2" }),
- foregroundStyle(colors.textTertiary),
- ]}
- >
- {row.quotaLabel}
- </Text>
- ) : null}
- </VStack>
- }
- leading={
- <RNHostView matchContents>
- <View
- style={{
- width: 28,
- height: 28,
- justifyContent: "center",
- }}
- >
- <MobileModelIconMark
- icon={row.entry.icon}
- {...row.providerMark}
- color={colors.textSecondary}
- />
- </View>
- </RNHostView>
- }
- optionsIcon={mark(SlidersHorizontal)}
- selectionIcon={mark(Check)}
- accessory={row.favorite ? mark(Star, true) : undefined}
- selected={row.selected}
- disabled={p.busy || row.disabled}
- onPress={() => p.onSelect(row)}
- onOptions={() => p.onOptions(row)}
- optionsLabel={t("models.picker.configureAccessibility", {
- model: row.entry.displayName,
- })}
- testID={`${p.testID}.model.${row.key}`}
- />
- ))}
</Section>
- ))}
- {!p.groups.length ? (
+ ) : (
+ <Section title={t("models.unified.currentConfiguration")}>
+ <ComposerNativeRow
+ title={t(
+ isFavorite
+ ? "models.unified.savedConfiguration"
+ : "models.unified.favoriteConfiguration",
+ )}
+ subtitle={options.configurationSummary}
+ leading={mark(Star, isFavorite)}
+ disabled={p.busy || options.favoritesDisabled}
+ onPress={options.onFavorite}
+ testID={`${p.testID}.favorite`}
+ />
+ <Text
+ modifiers={[
+ font({ textStyle: "footnote" }),
+ foregroundStyle(colors.textSecondary),
+ ]}
+ >
+ {t(
+ isFavorite
+ ? "models.unified.removeFavoriteHint"
+ : "models.unified.saveFavoriteHint",
+ )}
+ </Text>
+ </Section>
+ )}
+ {options.notice ? (
<Section>
- <Text modifiers={[foregroundStyle(colors.textSecondary)]}>
- {p.loading ? t("models.picker.loadingDefault") : p.emptyHint}
+ <Text
+ testID={`${p.testID}.notice`}
+ modifiers={[
+ font({ textStyle: "footnote" }),
+ foregroundStyle(colors.textSecondary),
+ ]}
+ >
+ {options.notice}
</Text>
</Section>
) : null}
</>
- )}
+ ) : null}
</ComposerSheet>
);
}
diff --git a/apps/mobile/src/session/UnifiedModelPickerView.tsx b/apps/mobile/src/session/UnifiedModelPickerView.tsx
index 41ddd22a3b..b57d257c82 100644
--- a/apps/mobile/src/session/UnifiedModelPickerView.tsx
+++ b/apps/mobile/src/session/UnifiedModelPickerView.tsx
@@ -253,6 +253,11 @@ export function UnifiedModelPickerView(p: UnifiedMobilePickerViewProps) {
const level = (id: string) =>
t(`models.options.effortLevels.${id}`, { defaultValue: id });
const options = p.options;
+ const showSecondary = !!options || !!page;
+ useEffect(() => {
+ if (showSecondary) searchRef.current?.blur();
+ }, [showSecondary]);
+ const isFavorite = options?.isFavorite ?? !!options?.row.favorite;
const config = options?.row.config;
const back = page ? () => setPage(null) : p.onBack;
const currentFilter = p.filters.find((item) => item.id === p.filter);
@@ -274,72 +279,71 @@ export function UnifiedModelPickerView(p: UnifiedMobilePickerViewProps) {
icon(LayoutGrid)
);
- const searchHeader =
- !options && !page ? (
- <View style={styles.searchRow}>
- <View style={styles.searchField}>
- <Search
- color={colors.textSecondary}
- size={iconSize.md}
- strokeWidth={iconStroke.regular}
- />
- <TextInput
- accessibilityLabel={t("models.picker.searchAccessibility")}
- autoCapitalize="none"
- autoCorrect={false}
- onChangeText={p.onQuery}
- // Android adjustResize:聚焦搜索时吸到 full,边输边看列表(与旧版模型浮窗同口径)。
- onFocus={() => setSnap("full")}
- placeholder={t("models.picker.searchPlaceholder")}
- placeholderTextColor={colors.textPlaceholder}
- ref={searchRef}
- style={styles.searchInput}
- testID={`${p.testID}.search`}
- value={p.query}
- />
- {p.query ? (
- <Pressable
- accessibilityLabel={t("devices.detail.search.clearA11y")}
- accessibilityRole="button"
- hitSlop={4}
- onPress={() => p.onQuery("")}
- style={({ pressed }) => [
- styles.iconButton,
- pressed && styles.pressed,
- ]}
- testID={`${p.testID}.search.clear`}
- >
- <X
- color={colors.textTertiary}
- size={iconSize.md}
- strokeWidth={iconStroke.regular}
- />
- </Pressable>
- ) : null}
- </View>
- <Pressable
- accessibilityLabel={t("models.unified.source")}
- accessibilityRole="button"
- accessibilityValue={{ text: currentFilter?.label ?? "" }}
- onPress={() => setPage("sources")}
- style={({ pressed }) => [
- styles.sourceButton,
- pressed && styles.pressed,
- ]}
- testID={`${p.testID}.filter`}
- >
- <View style={styles.markBox}>{filterMark()}</View>
- <Text numberOfLines={1} style={styles.sourceLabel}>
- {currentFilter?.label ?? ""}
- </Text>
- <ChevronRight
- color={colors.textTertiary}
- size={iconSize.sm}
- strokeWidth={iconStroke.regular}
- />
- </Pressable>
+ const searchHeader = (
+ <View style={styles.searchRow}>
+ <View style={styles.searchField}>
+ <Search
+ color={colors.textSecondary}
+ size={iconSize.md}
+ strokeWidth={iconStroke.regular}
+ />
+ <TextInput
+ accessibilityLabel={t("models.picker.searchAccessibility")}
+ autoCapitalize="none"
+ autoCorrect={false}
+ onChangeText={p.onQuery}
+ // Android adjustResize:聚焦搜索时吸到 full,边输边看列表(与旧版模型浮窗同口径)。
+ onFocus={() => setSnap("full")}
+ placeholder={t("models.picker.searchPlaceholder")}
+ placeholderTextColor={colors.textPlaceholder}
+ ref={searchRef}
+ style={styles.searchInput}
+ testID={`${p.testID}.search`}
+ value={p.query}
+ />
+ {p.query ? (
+ <Pressable
+ accessibilityLabel={t("devices.detail.search.clearA11y")}
+ accessibilityRole="button"
+ hitSlop={4}
+ onPress={() => p.onQuery("")}
+ style={({ pressed }) => [
+ styles.iconButton,
+ pressed && styles.pressed,
+ ]}
+ testID={`${p.testID}.search.clear`}
+ >
+ <X
+ color={colors.textTertiary}
+ size={iconSize.md}
+ strokeWidth={iconStroke.regular}
+ />
+ </Pressable>
+ ) : null}
</View>
- ) : undefined;
+ <Pressable
+ accessibilityLabel={t("models.unified.source")}
+ accessibilityRole="button"
+ accessibilityValue={{ text: currentFilter?.label ?? "" }}
+ onPress={() => setPage("sources")}
+ style={({ pressed }) => [
+ styles.sourceButton,
+ pressed && styles.pressed,
+ ]}
+ testID={`${p.testID}.filter`}
+ >
+ <View style={styles.markBox}>{filterMark()}</View>
+ <Text numberOfLines={1} style={styles.sourceLabel}>
+ {currentFilter?.label ?? ""}
+ </Text>
+ <ChevronRight
+ color={colors.textTertiary}
+ size={iconSize.sm}
+ strokeWidth={iconStroke.regular}
+ />
+ </Pressable>
+ </View>
+ );
const sourcesPage = (
<Group testID={`${p.testID}.sources`}>
@@ -476,6 +480,21 @@ export function UnifiedModelPickerView(p: UnifiedMobilePickerViewProps) {
{options.context}
</Text>
) : null}
+ {options.onEditFavorite ? (
+ <Group>
+ <Row
+ title={t("models.unified.editFavorite")}
+ onPress={options.onEditFavorite}
+ disabled={p.busy || options.favoritesDisabled}
+ testID={`${p.testID}.editFavorite`}
+ />
+ </Group>
+ ) : null}
+ {options.editingFavorite ? (
+ <Text style={styles.footnote}>
+ {t("models.unified.editFavoriteHint")}
+ </Text>
+ ) : null}
<Group>
<Row
disabled={p.busy}
@@ -516,6 +535,30 @@ export function UnifiedModelPickerView(p: UnifiedMobilePickerViewProps) {
</View>
) : null}
</Group>
+ {!options.editingFavorite ? (
+ <>
+ <Text style={styles.footnote} testID={`${p.testID}.configState`}>
+ {t(
+ options.canReset
+ ? "models.unified.customized"
+ : "models.unified.usingRecommended",
+ )}
+ </Text>
+ {options.canReset ? (
+ <Group>
+ <Row
+ title={t("models.unified.restoreRecommended")}
+ onPress={options.onReset}
+ disabled={p.busy}
+ testID={`${p.testID}.reset`}
+ />
+ </Group>
+ ) : null}
+ <Text style={styles.footnote}>
+ {t("models.unified.resetScopeHint")}
+ </Text>
+ </>
+ ) : null}
{options.price ? (
<Text
style={[styles.footnote, styles.price]}
@@ -524,27 +567,55 @@ export function UnifiedModelPickerView(p: UnifiedMobilePickerViewProps) {
{options.price}
</Text>
) : null}
- <Group>
- <Row
- disabled={p.busy || options.favoritesDisabled}
- leading={icon(Star, !!options.row.favorite)}
- onPress={options.onFavorite}
- testID={`${p.testID}.favorite`}
- title={t(
- options.row.favorite
- ? "models.unified.removeFavorite"
- : "models.unified.addFavorite",
- )}
- />
- {!options.row.favorite ? (
+ {options.editingFavorite ? (
+ <Group>
+ <Row
+ title={t("models.unified.saveFavorite")}
+ onPress={() => options.onSaveEdit?.()}
+ disabled={p.busy || options.favoritesDisabled}
+ testID={`${p.testID}.saveFavorite`}
+ />
<Row
+ title={t("models.unified.cancelEdit")}
+ onPress={() => options.onCancelEdit?.()}
disabled={p.busy}
- onPress={options.onReset}
- testID={`${p.testID}.reset`}
- title={t("models.unified.restoreRecommended")}
+ testID={`${p.testID}.cancelEdit`}
/>
- ) : null}
- </Group>
+ </Group>
+ ) : (
+ <>
+ <Group title={t("models.unified.currentConfiguration")}>
+ <Row
+ disabled={p.busy || options.favoritesDisabled}
+ leading={icon(Star, isFavorite)}
+ onPress={options.onFavorite}
+ testID={`${p.testID}.favorite`}
+ title={t(
+ isFavorite
+ ? "models.unified.savedConfiguration"
+ : "models.unified.favoriteConfiguration",
+ )}
+ subtitle={options.configurationSummary}
+ />
+ </Group>
+ <Text style={styles.footnote}>
+ {t(
+ isFavorite
+ ? "models.unified.removeFavoriteHint"
+ : "models.unified.saveFavoriteHint",
+ )}
+ </Text>
+ </>
+ )}
+ {options.notice ? (
+ <Text
+ style={styles.footnote}
+ accessibilityLiveRegion="polite"
+ testID={`${p.testID}.notice`}
+ >
+ {options.notice}
+ </Text>
+ ) : null}
</>
) : null;
@@ -689,84 +760,123 @@ export function UnifiedModelPickerView(p: UnifiedMobilePickerViewProps) {
onRequestClose={back ?? p.onClose}
visible={p.visible}
>
- <SheetSurface
- backAccessibilityLabel={
- page ? undefined : t("models.picker.backToModels")
- }
- bottomInset={insets.bottom}
- heights={heights}
- onBack={back}
- onClose={p.onClose}
- onSnapChange={(next) => {
- // 拖回 half 视为想收起键盘(与旧版模型浮窗同口径)。
- if (next === "half") searchRef.current?.blur();
- setSnap(next);
- }}
- pinnedTop={searchHeader}
- snap={snap}
- testID={p.testID}
- title={title}
- renderScrollContent={
- Platform.OS === "android" && !page && !options
- ? (scrollProps) => (
- <FlatList
- {...scrollProps}
- ref={modelListRef}
- data={modelItems}
- keyExtractor={(item) => item.key}
- initialNumToRender={8}
- maxToRenderPerBatch={4}
- windowSize={3}
- removeClippedSubviews={false}
- ListHeaderComponent={
- p.error ? <Text style={styles.error}>{p.error}</Text> : null
- }
- ListEmptyComponent={
- <Text style={styles.empty} testID={`${p.testID}.empty`}>
- {p.loading
- ? t("models.picker.loadingDefault")
- : p.emptyHint}
- </Text>
- }
- renderItem={({ item }) =>
- item.kind === "header" ? (
- <View
- style={styles.group}
- testID={`${p.testID}.group.${item.group.key}`}
- >
- <Text style={styles.groupLabel}>
- {item.group.title}
- </Text>
- </View>
- ) : (
- <View>
- {item.separator ? (
- <View style={styles.separator} />
- ) : null}
- {modelRow(item.row)}
- </View>
- )
- }
- />
- )
- : undefined
+ <View
+ pointerEvents={showSecondary ? "none" : "auto"}
+ accessibilityElementsHidden={showSecondary}
+ importantForAccessibility={
+ showSecondary ? "no-hide-descendants" : "auto"
}
+ style={showSecondary ? styles.hiddenList : undefined}
>
- {p.error ? <Text style={styles.error}>{p.error}</Text> : null}
- {page === "sources"
- ? sourcesPage
- : page === "harness" && options
- ? harnessPage
- : options
- ? settingsPage
- : listPage}
- </SheetSurface>
+ <SheetSurface
+ bottomInset={insets.bottom}
+ heights={heights}
+ onClose={p.onClose}
+ onSnapChange={(next) => {
+ if (next === "half") searchRef.current?.blur();
+ setSnap(next);
+ }}
+ pinnedTop={searchHeader}
+ snap={snap}
+ testID={showSecondary ? `${p.testID}.list` : p.testID}
+ title={t("models.picker.title")}
+ renderScrollContent={
+ Platform.OS === "android"
+ ? (scrollProps) => (
+ <FlatList
+ {...scrollProps}
+ ref={modelListRef}
+ data={modelItems}
+ keyExtractor={(item) => item.key}
+ initialNumToRender={8}
+ maxToRenderPerBatch={4}
+ windowSize={3}
+ removeClippedSubviews={false}
+ ListHeaderComponent={
+ p.error ? (
+ <Text style={styles.error}>{p.error}</Text>
+ ) : null
+ }
+ ListEmptyComponent={
+ <Text style={styles.empty} testID={`${p.testID}.empty`}>
+ {p.loading
+ ? t("models.picker.loadingDefault")
+ : p.emptyHint}
+ </Text>
+ }
+ renderItem={({ item }) =>
+ item.kind === "header" ? (
+ <View
+ style={styles.group}
+ testID={`${p.testID}.group.${item.group.key}`}
+ >
+ <Text style={styles.groupLabel}>
+ {item.group.title}
+ </Text>
+ </View>
+ ) : (
+ <View>
+ {item.separator ? (
+ <View style={styles.separator} />
+ ) : null}
+ {modelRow(item.row)}
+ </View>
+ )
+ }
+ />
+ )
+ : undefined
+ }
+ >
+ {!showSecondary && p.error ? (
+ <Text style={styles.error}>{p.error}</Text>
+ ) : null}
+ {listPage}
+ </SheetSurface>
+ </View>
+ {showSecondary ? (
+ <View style={styles.secondaryLayer}>
+ <SheetSurface
+ backAccessibilityLabel={
+ page ? undefined : t("models.picker.backToModels")
+ }
+ bottomInset={insets.bottom}
+ heights={heights}
+ onBack={back}
+ onClose={p.onClose}
+ onSnapChange={(next) => {
+ // 拖回 half 视为想收起键盘(与旧版模型浮窗同口径)。
+ if (next === "half") searchRef.current?.blur();
+ setSnap(next);
+ }}
+ snap={snap}
+ testID={p.testID}
+ title={title}
+ >
+ {p.error ? <Text style={styles.error}>{p.error}</Text> : null}
+ {page === "sources"
+ ? sourcesPage
+ : page === "harness" && options
+ ? harnessPage
+ : options
+ ? settingsPage
+ : null}
+ </SheetSurface>
+ </View>
+ ) : null}
</SheetModal>
);
}
function makeStyles(colors: ThemeColors) {
return StyleSheet.create({
+ hiddenList: { opacity: 0 },
+ secondaryLayer: {
+ position: "absolute",
+ left: 0,
+ right: 0,
+ bottom: 0,
+ },
searchRow: {
alignItems: "center",
flexDirection: "row",
diff --git a/docs/product-rules/model-selector-unified.md b/docs/product-rules/model-selector-unified.md
index 11c1f24eac..d3d4bfa694 100644
--- a/docs/product-rules/model-selector-unified.md
+++ b/docs/product-rules/model-selector-unified.md
@@ -26,6 +26,7 @@
- 模型选择、配置编辑与“跟随默认”均等待保存结果;失败保留面板与原配置。选模型或跟随默认成功才收起,配置编辑保持浮层打开。无模型记忆表的设置入口编辑非当前模型时,直接应用其完整配置。已有待生效配置时再次远程选模,先展示最新用户选择;运行时当前配置的来源、模型、引擎、深度与 Fast 始终来自同一快照。
- 结构:搜索框贴顶 → 左侧 rail(★收藏 / 全部 / 各供应商图标) → 右侧列表 → 底部「+配置模型」。
- 列表主体固定高 428px(指定可见行数的入口按其既有高度配置),不随供应商筛选、收藏、搜索或空结果改变高度;窗口空间不足时按可用高度收缩。模型列表与供应商侧栏分别内部滚动,搜索与底部操作保持可见。
+- Mobile 从模型详情或来源子页返回时,保留进入前的列表滚动位置、搜索词与来源筛选,不重新初始化列表。iOS 保留原生 Form,Android 保留原列表 SheetSurface;详情使用独立滚动容器,隐藏列表禁止交互与读屏访问,不叠加第二个 Modal。完整关闭后重新打开仍沿用原有初始化规则。
- 宽度自适应:`max-content`,min 300px / max min(460px, 100vw-48px);优先保持紧凑,超出可用宽度的模型名显示省略号,hover title 保留全名,不为显示完整名称继续加宽(2026-09-17 截断原则;2026-09-21 将上限从 420px 调整为 460px,以完整显示「Codex GPT-6 Astra」量级的名称)。字段形态仍绑定字段宽度;视口和锚点可用空间不足时继续收缩。
- 行(双行):
- L1:厂商图标 · 模型名(弹性,截断) · 价格档/折扣/订阅徽标 · ☆ · 右侧**常驻三元组**`[引擎图标] 深度 [⚡]` · 选中勾。
@@ -57,17 +58,21 @@
- 当前选中模型只切 Harness 时保留正在使用的思考档,不重置成目标 Harness 的推荐或旧记忆;
目标不支持时按实际能力适配,无可调档时不传强度。来源 Harness 的旧偏好不因此删除或改写。
- 恢复推荐 = **删 override**,随版本跟随新推荐;未自定义用户自动获得新默认。
+- Mobile 在参数区显示「使用推荐设置」或「已自定义」;只有存在自定义时才显示「恢复推荐」,并说明它恢复引擎、推理强度和 Fast,不影响收藏。恢复时清除模型的引擎覆盖,以及当前和推荐引擎两格的参数覆盖。支持删除的草稿记忆继续删除 override;会话镜像的既有远程协议没有删除操作,与 Desktop 一样退回写入当前推荐值,不能声称这一兼容路径会自动跟随未来默认值。
- 不设集中管理入口(已裁决删除);恢复只在浮层就地做。
+- Mobile 推荐基线沿用选模时的会话引擎落点规则,自动沿用任务引擎不算自定义;恢复时清除当前及恢复目标引擎的参数覆盖。面板关闭、重开或切换绑定后,上一轮保存的响应不得恢复旧详情、提示或关闭新面板;已开始的持久化仍串行完成。
### 1.5 收藏 = 配置副本
- **远程收藏按被控电脑共享**:Desktop 与 Mobile 连接同一台电脑时读取和修改该电脑当前账号的既有收藏。各被控电脑独立,不将控制端的本机收藏套用或自动合并到远端。收藏以单条新增、条件编辑、条件删除同步,等持久化确认后反馈成功;并发修改同一副本时拒绝旧快照覆盖,重读后再编辑。断线、账号切换、旧版不支持时不得声称已同步;不自动重试写操作,也不影响会话和连接恢复。
-- 行/浮层的 ☆ 是**单向「添加副本」动作**:把当前生效配置(模型+引擎+深度+Fast)拷进收藏区,点亮 0.7s 反馈后恢复;源头行不持有收藏态(多副本下不可判定)。重复添加去重。
+- Desktop 行/浮层的 ☆ 是**单向「添加副本」动作**:把当前生效配置(模型+引擎+深度+Fast)拷进收藏区,点亮 0.7s 反馈后恢复;源头行不持有收藏态。重复添加去重。
+- **Mobile 收藏与参数调整分开**(用户确认交互原型,2026-10-02):按来源、模型、引擎、推理强度与 Fast 完整匹配已保存副本,展示当前配置摘要。空心星标对应「收藏此配置」,保存确认后保持实心星标并显示「已收藏 · 点击取消」;再次点击只删除匹配的副本,所有入口都保持当前配置与详情页,不触发恢复推荐。模型目录 ID 与同一条目的 wire ID 视为同一模型,不把已失效档位或不可用 Fast 自动降级后当成匹配。状态跟随被控端收藏快照,失败保留原状态并允许重试。
+- Mobile 从普通模型或收藏进入详情,普通参数调整均保存模型偏好;当前选中模型继续走完整配置应用与取消/失败回滚规则。原收藏不变,配置不再匹配时星标回到空心,并提示「参数已调整,原收藏保留」。再次收藏新增独立副本。从收藏打开时提供「编辑原收藏」,参数先留在编辑草稿,点击「保存收藏」才更新原条目,且不改变正在使用的配置。取消编辑不落库;保存失败保留编辑内容;原收藏被远端修改或删除时拒绝旧编辑覆盖,相同配置去重。实现与回归见 `UnifiedModelPickerSheet.tsx`、`unifiedMobilePicker.test.tsx`、`unifiedMobilePickerView.test.tsx`。
- 每条收藏有**独立锚点 uid**,浮层绑定与删除按 uid 区分;收藏不显示选中底色或勾;选中态只出现在模型本体上。配置编辑仍核对来源、模型、引擎、深度、Fast 与实际配置。同模型多条目互不牵连。
-- 打开收藏条目的配置浮层后,直接编辑该条。若当前任务正在使用其完整配置,先应用到当前任务,成功才保存收藏;其他旧任务保持原配置,不自动跟随收藏修改,重新打开时按实际配置显示选中行。底栏「收藏配置 · 取消收藏」。
+- Desktop 打开收藏条目的配置浮层后,直接编辑该条。若当前任务正在使用其完整配置,先应用到当前任务,成功才保存收藏;其他旧任务保持原配置,不自动跟随收藏修改,重新打开时按实际配置显示选中行。底栏「收藏配置 · 取消收藏」。Mobile 使用上面的显式编辑入口。
- 点击收藏按一份完整配置应用来源、模型、引擎、深度与 Fast。确认取消、写入失败或抛错时保留原选中态和面板,不提交收藏编辑或删除;成功后再收尾。同一面板的配置操作串行执行,写入及回滚完成前禁止连续修改,失败后允许重试。
-- 非默认配置条目右侧显示 `引擎 · 深度 [⚡]` 后缀;删除选中条目时选中回落到对应模型默认。
+- 非默认配置条目右侧显示 `引擎 · 深度 [⚡]` 后缀;Desktop 从收藏条目详情删除当前正在使用的副本时,选中回落到对应模型默认;Mobile 取消收藏一律保持当前配置。
### 1.6 会话内(切换有损)