mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
feat(frontend): improve model selection experience (#237)
* chore: remove dead code and unused exports * fix: preserve model form during config refresh Signed-off-by: mehmet turac <mehmetturac@gmail.com> * loop: model-select-fix completed after 11 iterations * fix(frontend): show provider prefix for duplicate models in quick select dropdown When the same model exists under multiple providers, show the provider name for both entries so users can distinguish them. Detects duplicates by modelID across all favorites and recents. * refactor(frontend): replace useTallScrollContent with scroll visibility hook * fix: harden mirror push rollback * Remove Load button from skill cards, clicking card loads skill * feat(backend): add plugin installation support and schema updates * refactor(frontend): remove unused useHeaderScrollVisibility hook * refactor(frontend): replace model dropdown with bottom sheet selector Replace DropdownMenu-based ModelQuickSelect with a bottom sheet implementation featuring favorites, recents, provider browsing, and search. Remove onShowModelsDialog prop from PromptInput and SessionDetail, using data attribute trigger instead. Fix ZodIssueCode deprecation, input text color, and portal rendering for bottom sheet. * fix(frontend): simplify session model restore and fix mobile swipe reset * loop: single-source-models completed after 10 iterations * refactor(frontend): add desktop sidebar layout to model quick select * refactor(frontend): improve model selector with connected providers, favorites, and recent management * fix(frontend): constrain model name width to prevent overflow in prompt input * fix(frontend): adjust padding and styling in model quick select * fix(frontend): add optimistic removal with rollback for recent models ---------
This commit is contained in:
1 parent
f492faa84b
commit
03bd3dac95
45 files changed
+1728
-1148
No files matched your search
@@ -1,78 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { renderHook, act } from '@testing-library/react'
|
||||
import { useTallScrollContent } from '../useTallScrollContent'
|
||||
|
||||
let mockObserve: ReturnType<typeof vi.fn>
|
||||
let mockDisconnect: ReturnType<typeof vi.fn>
|
||||
let resizeCallback: ((entries: ResizeObserverEntry[]) => void) | null = null
|
||||
|
||||
vi.stubGlobal('ResizeObserver', vi.fn((cb: (entries: ResizeObserverEntry[]) => void) => {
|
||||
resizeCallback = cb
|
||||
return {
|
||||
observe: mockObserve,
|
||||
disconnect: mockDisconnect,
|
||||
unobserve: vi.fn(),
|
||||
}
|
||||
}))
|
||||
|
||||
describe('useTallScrollContent', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockObserve = vi.fn()
|
||||
mockDisconnect = vi.fn()
|
||||
resizeCallback = null
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
function createContainerRef(scrollHeight: number, clientHeight: number) {
|
||||
const el = document.createElement('div')
|
||||
Object.defineProperty(el, 'scrollHeight', { value: scrollHeight, configurable: true })
|
||||
Object.defineProperty(el, 'clientHeight', { value: clientHeight, configurable: true })
|
||||
return { current: el }
|
||||
}
|
||||
|
||||
it('returns false when scrollHeight <= clientHeight * ratio', () => {
|
||||
const ref = createContainerRef(500, 400)
|
||||
|
||||
const { result } = renderHook(() => useTallScrollContent(ref as React.RefObject<HTMLElement>, 1.5))
|
||||
expect(result.current).toBe(false)
|
||||
})
|
||||
|
||||
it('returns true when scrollHeight > clientHeight * ratio', () => {
|
||||
const ref = createContainerRef(2000, 800)
|
||||
|
||||
const { result } = renderHook(() => useTallScrollContent(ref as React.RefObject<HTMLElement>, 1.5))
|
||||
expect(result.current).toBe(true)
|
||||
})
|
||||
|
||||
it('updates from false to true when ResizeObserver fires with taller content', () => {
|
||||
const ref = createContainerRef(500, 400)
|
||||
|
||||
const { result } = renderHook(() => useTallScrollContent(ref as React.RefObject<HTMLElement>, 1.5))
|
||||
expect(result.current).toBe(false)
|
||||
|
||||
Object.defineProperty(ref.current, 'scrollHeight', { value: 2000 })
|
||||
act(() => {
|
||||
resizeCallback?.([] as ResizeObserverEntry[])
|
||||
})
|
||||
|
||||
expect(result.current).toBe(true)
|
||||
})
|
||||
|
||||
it('updates from true to false when ResizeObserver fires with smaller container', () => {
|
||||
const ref = createContainerRef(2000, 800)
|
||||
|
||||
const { result } = renderHook(() => useTallScrollContent(ref as React.RefObject<HTMLElement>, 1.5))
|
||||
expect(result.current).toBe(true)
|
||||
|
||||
Object.defineProperty(ref.current, 'clientHeight', { value: 2000 })
|
||||
act(() => {
|
||||
resizeCallback?.([] as ResizeObserverEntry[])
|
||||
})
|
||||
|
||||
expect(result.current).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -50,6 +50,7 @@ describe('useAutoScroll', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => window.setTimeout(() => callback(performance.now()), 0))
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
@@ -58,6 +59,7 @@ describe('useAutoScroll', () => {
|
||||
containerHarness = null
|
||||
}
|
||||
vi.restoreAllMocks()
|
||||
vi.unstubAllGlobals()
|
||||
vi.clearAllTimers()
|
||||
})
|
||||
|
||||
@@ -165,11 +167,100 @@ describe('useAutoScroll', () => {
|
||||
expect(containerHarness.getScrollTop()).toBe(containerHarness.div.scrollHeight - containerHarness.div.clientHeight)
|
||||
})
|
||||
|
||||
it('scrolls to bottom again after layout frames', () => {
|
||||
const messages = [createMessage('1', 'user'), createMessage('2', 'assistant')]
|
||||
const { renderResult, containerHarness } = setupHook(messages)
|
||||
|
||||
act(() => {
|
||||
renderResult.result.current.scrollToBottom()
|
||||
})
|
||||
|
||||
containerHarness.setScrollHeight(containerHarness.div.scrollHeight + 300)
|
||||
|
||||
act(() => {
|
||||
vi.runOnlyPendingTimers()
|
||||
})
|
||||
|
||||
expect(containerHarness.getScrollTop()).toBe(containerHarness.div.scrollHeight - containerHarness.div.clientHeight)
|
||||
})
|
||||
|
||||
it('does not keep forcing bottom after user scrolls up', () => {
|
||||
const messages = [createMessage('1', 'user'), createMessage('2', 'assistant')]
|
||||
const { renderResult, containerHarness, onScrollStateChange } = setupHook(messages)
|
||||
|
||||
act(() => {
|
||||
renderResult.result.current.scrollToBottom()
|
||||
})
|
||||
|
||||
const userPosition = 100
|
||||
act(() => {
|
||||
containerHarness.setScrollTop(userPosition)
|
||||
containerHarness.div.dispatchEvent(
|
||||
new WheelEvent('wheel', {
|
||||
deltaY: -50,
|
||||
bubbles: true,
|
||||
})
|
||||
)
|
||||
vi.runOnlyPendingTimers()
|
||||
})
|
||||
|
||||
expect(onScrollStateChange).toHaveBeenCalledWith(true)
|
||||
expect(containerHarness.getScrollTop()).toBe(userPosition)
|
||||
})
|
||||
|
||||
it('cancels pending bottom scroll as soon as user touches the list', () => {
|
||||
const messages = [createMessage('1', 'user'), createMessage('2', 'assistant')]
|
||||
const { renderResult, containerHarness } = setupHook(messages)
|
||||
|
||||
act(() => {
|
||||
renderResult.result.current.scrollToBottom()
|
||||
})
|
||||
|
||||
const userPosition = 120
|
||||
act(() => {
|
||||
containerHarness.div.dispatchEvent(
|
||||
new PointerEvent('pointerdown', {
|
||||
clientY: 200,
|
||||
bubbles: true,
|
||||
})
|
||||
)
|
||||
containerHarness.setScrollTop(userPosition)
|
||||
vi.runOnlyPendingTimers()
|
||||
})
|
||||
|
||||
expect(containerHarness.getScrollTop()).toBe(userPosition)
|
||||
})
|
||||
|
||||
it('does not show scroll button on tiny upward drag from bottom', () => {
|
||||
const messages = [createMessage('1', 'user')]
|
||||
const { containerHarness, onScrollStateChange } = setupHook(messages)
|
||||
const bottomPosition = containerHarness.div.scrollHeight - containerHarness.div.clientHeight
|
||||
|
||||
act(() => {
|
||||
containerHarness.setScrollTop(bottomPosition - 20)
|
||||
containerHarness.div.dispatchEvent(
|
||||
new PointerEvent('pointerdown', {
|
||||
clientY: 200,
|
||||
bubbles: true,
|
||||
})
|
||||
)
|
||||
containerHarness.div.dispatchEvent(
|
||||
new PointerEvent('pointermove', {
|
||||
clientY: 260,
|
||||
bubbles: true,
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
expect(onScrollStateChange).not.toHaveBeenCalledWith(true)
|
||||
})
|
||||
|
||||
it('disengages when user fires a wheel-up event', () => {
|
||||
const messages = [createMessage('1', 'user')]
|
||||
const { containerHarness, onScrollStateChange } = setupHook(messages)
|
||||
|
||||
act(() => {
|
||||
containerHarness.setScrollTop(100)
|
||||
containerHarness.div.dispatchEvent(
|
||||
new WheelEvent('wheel', {
|
||||
deltaY: -50,
|
||||
@@ -192,6 +283,7 @@ describe('useAutoScroll', () => {
|
||||
const { containerHarness, onScrollStateChange } = setupHook(messages)
|
||||
|
||||
act(() => {
|
||||
containerHarness.setScrollTop(100)
|
||||
containerHarness.div.dispatchEvent(
|
||||
new PointerEvent('pointerdown', {
|
||||
clientY: 200,
|
||||
@@ -220,6 +312,7 @@ describe('useAutoScroll', () => {
|
||||
const { containerHarness, onScrollStateChange } = setupHook(messages)
|
||||
|
||||
act(() => {
|
||||
containerHarness.setScrollTop(100)
|
||||
containerHarness.div.dispatchEvent(
|
||||
new WheelEvent('wheel', {
|
||||
deltaY: -50,
|
||||
@@ -246,6 +339,7 @@ describe('useAutoScroll', () => {
|
||||
const { renderResult, containerHarness, onScrollStateChange } = setupHook(messages)
|
||||
|
||||
act(() => {
|
||||
containerHarness.setScrollTop(100)
|
||||
containerHarness.div.dispatchEvent(
|
||||
new WheelEvent('wheel', {
|
||||
deltaY: -50,
|
||||
|
||||
@@ -3,6 +3,8 @@ import type { Message } from '@/api/types'
|
||||
|
||||
const SCROLL_LOCK_MS = 300
|
||||
const BOTTOM_THRESHOLD_PX = 48
|
||||
const SHOW_SCROLL_BUTTON_THRESHOLD_PX = 120
|
||||
const SCROLL_TO_BOTTOM_FRAME_COUNT = 2
|
||||
|
||||
interface UseAutoScrollOptions {
|
||||
containerRef?: React.RefObject<HTMLDivElement | null>
|
||||
@@ -30,6 +32,8 @@ export function useAutoScroll({
|
||||
const pointerStartYRef = useRef<number | null>(null)
|
||||
const pointerActiveRef = useRef(false)
|
||||
const onScrollStateChangeRef = useRef(onScrollStateChange)
|
||||
const scrollRequestIdRef = useRef(0)
|
||||
const isScrollButtonVisibleRef = useRef(false)
|
||||
|
||||
onScrollStateChangeRef.current = onScrollStateChange
|
||||
|
||||
@@ -37,7 +41,25 @@ export function useAutoScroll({
|
||||
if (!containerRef?.current) return
|
||||
userScrolledAtRef.current = 0
|
||||
userDisengagedRef.current = false
|
||||
containerRef.current.scrollTop = containerRef.current.scrollHeight
|
||||
isScrollButtonVisibleRef.current = false
|
||||
const scrollRequestId = scrollRequestIdRef.current + 1
|
||||
scrollRequestIdRef.current = scrollRequestId
|
||||
const scroll = () => {
|
||||
if (!containerRef?.current) return
|
||||
containerRef.current.scrollTop = containerRef.current.scrollHeight
|
||||
}
|
||||
|
||||
scroll()
|
||||
let frameCount = 0
|
||||
const scrollAfterLayout = () => {
|
||||
if (scrollRequestIdRef.current !== scrollRequestId) return
|
||||
frameCount += 1
|
||||
scroll()
|
||||
if (frameCount < SCROLL_TO_BOTTOM_FRAME_COUNT) {
|
||||
requestAnimationFrame(scrollAfterLayout)
|
||||
}
|
||||
}
|
||||
requestAnimationFrame(scrollAfterLayout)
|
||||
onScrollStateChangeRef.current?.(false)
|
||||
}, [containerRef])
|
||||
|
||||
@@ -53,8 +75,13 @@ export function useAutoScroll({
|
||||
if (!container) return
|
||||
|
||||
const markDisengaged = () => {
|
||||
const container = containerRef?.current
|
||||
if (!container) return
|
||||
const distanceFromBottom = container.scrollHeight - container.scrollTop - container.clientHeight
|
||||
userScrolledAtRef.current = Date.now()
|
||||
if (!userDisengagedRef.current) {
|
||||
scrollRequestIdRef.current += 1
|
||||
if (!isScrollButtonVisibleRef.current && distanceFromBottom > SHOW_SCROLL_BUTTON_THRESHOLD_PX) {
|
||||
isScrollButtonVisibleRef.current = true
|
||||
onScrollStateChangeRef.current?.(true)
|
||||
}
|
||||
userDisengagedRef.current = true
|
||||
@@ -63,6 +90,7 @@ export function useAutoScroll({
|
||||
const handlePointerDown = (e: PointerEvent) => {
|
||||
pointerStartYRef.current = e.clientY
|
||||
pointerActiveRef.current = true
|
||||
scrollRequestIdRef.current += 1
|
||||
}
|
||||
|
||||
const handlePointerMove = (e: PointerEvent) => {
|
||||
@@ -98,12 +126,19 @@ export function useAutoScroll({
|
||||
if (userDisengagedRef.current) {
|
||||
userScrolledAtRef.current = 0
|
||||
userDisengagedRef.current = false
|
||||
isScrollButtonVisibleRef.current = false
|
||||
onScrollStateChangeRef.current?.(false)
|
||||
}
|
||||
} else if (userDisengagedRef.current && !isScrollButtonVisibleRef.current && scrollHeight - scrollTop - clientHeight > SHOW_SCROLL_BUTTON_THRESHOLD_PX) {
|
||||
isScrollButtonVisibleRef.current = true
|
||||
onScrollStateChangeRef.current?.(true)
|
||||
} else if (pointerActiveRef.current && !userDisengagedRef.current) {
|
||||
userScrolledAtRef.current = Date.now()
|
||||
userDisengagedRef.current = true
|
||||
onScrollStateChangeRef.current?.(true)
|
||||
if (scrollHeight - scrollTop - clientHeight > SHOW_SCROLL_BUTTON_THRESHOLD_PX) {
|
||||
isScrollButtonVisibleRef.current = true
|
||||
onScrollStateChangeRef.current?.(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
|
||||
export function useDebounce<T>(value: T, delay: number): T {
|
||||
const [debouncedValue, setDebouncedValue] = useState<T>(value)
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => setDebouncedValue(value), delay)
|
||||
return () => clearTimeout(timer)
|
||||
}, [value, delay])
|
||||
|
||||
return debouncedValue
|
||||
}
|
||||
@@ -83,12 +83,17 @@ function useSwipeHandlers(
|
||||
const [swipeProgress, setSwipeProgress] = useState(0)
|
||||
const [swipeDeltaPx, setSwipeDeltaPx] = useState(0)
|
||||
const [dismissing, setDismissing] = useState(false)
|
||||
const dismissingRef = useRef(false)
|
||||
dismissingRef.current = dismissing
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) {
|
||||
if (enabled) {
|
||||
setDismissing(false)
|
||||
setSwipeDeltaPx(0)
|
||||
setSwipeProgress(0)
|
||||
} else if (!dismissingRef.current) {
|
||||
setSwipeDeltaPx(0)
|
||||
setSwipeProgress(0)
|
||||
}
|
||||
}, [enabled])
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { renderHook, waitFor } from '@testing-library/react'
|
||||
import { act, renderHook, waitFor } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { useModelSelection } from './useModelSelection'
|
||||
import { useModelStore, type ModelSelection } from '@/stores/modelStore'
|
||||
@@ -30,6 +30,7 @@ vi.mock('@/api/providers', async () => {
|
||||
getProviders: vi.fn(),
|
||||
getOpenCodeModelState: vi.fn(),
|
||||
addOpenCodeRecentModel: vi.fn(),
|
||||
removeOpenCodeRecentModel: vi.fn(),
|
||||
toggleOpenCodeFavoriteModel: vi.fn(),
|
||||
}
|
||||
})
|
||||
@@ -47,6 +48,7 @@ const mockUseOpenCodeClient = vi.mocked(useOpenCodeExports.useOpenCodeClient)
|
||||
const mockGetProviders = vi.mocked(providersApi.getProviders)
|
||||
const mockGetOpenCodeModelState = vi.mocked(providersApi.getOpenCodeModelState)
|
||||
const mockAddOpenCodeRecentModel = vi.mocked(providersApi.addOpenCodeRecentModel)
|
||||
const mockRemoveOpenCodeRecentModel = vi.mocked(providersApi.removeOpenCodeRecentModel)
|
||||
const mockToggleOpenCodeFavoriteModel = vi.mocked(providersApi.toggleOpenCodeFavoriteModel)
|
||||
|
||||
describe('useModelSelection', () => {
|
||||
@@ -72,6 +74,11 @@ describe('useModelSelection', () => {
|
||||
favorite: [],
|
||||
variant: {},
|
||||
})
|
||||
mockRemoveOpenCodeRecentModel.mockResolvedValue({
|
||||
recent: [],
|
||||
favorite: [],
|
||||
variant: {},
|
||||
})
|
||||
mockToggleOpenCodeFavoriteModel.mockResolvedValue({
|
||||
recent: [],
|
||||
favorite: [],
|
||||
@@ -140,7 +147,6 @@ describe('useModelSelection', () => {
|
||||
|
||||
expect(returnValue).toBe(true)
|
||||
expect(useModelStore.getState().model).toEqual(testModel)
|
||||
expect(useModelStore.getState().recentModels).toEqual([])
|
||||
})
|
||||
|
||||
it('rejects unknown model after providers are loaded', async () => {
|
||||
@@ -174,13 +180,150 @@ describe('useModelSelection', () => {
|
||||
})
|
||||
|
||||
const initialModel = useModelStore.getState().model
|
||||
const initialRecentModels = useModelStore.getState().recentModels
|
||||
const testModel: ModelSelection = { providerID: 'anthropic', modelID: 'missing-model' }
|
||||
const returnValue = result.current.setActiveModel(testModel)
|
||||
|
||||
expect(returnValue).toBe(false)
|
||||
expect(useModelStore.getState().model).toEqual(initialModel)
|
||||
expect(useModelStore.getState().recentModels).toEqual(initialRecentModels)
|
||||
})
|
||||
|
||||
describe('recentModels/favoriteModels derived from React Query', () => {
|
||||
it('filters out models not present in providers', async () => {
|
||||
mockGetOpenCodeModelState.mockResolvedValue({
|
||||
recent: [
|
||||
{ providerID: 'AI2', modelID: 'foo' },
|
||||
{ providerID: 'GreatScott', modelID: 'mimo' },
|
||||
],
|
||||
favorite: [
|
||||
{ providerID: 'VLLM', modelID: 'bar' },
|
||||
{ providerID: 'GreatScott', modelID: 'mimo' },
|
||||
],
|
||||
variant: {},
|
||||
})
|
||||
mockGetProviders.mockResolvedValue({
|
||||
providers: [
|
||||
{
|
||||
id: 'AI2',
|
||||
name: 'AI2',
|
||||
models: { foo: { id: 'foo', name: 'Foo' } },
|
||||
isConnected: true,
|
||||
env: [],
|
||||
options: {},
|
||||
},
|
||||
{
|
||||
id: 'VLLM',
|
||||
name: 'VLLM',
|
||||
models: { bar: { id: 'bar', name: 'Bar' } },
|
||||
isConnected: true,
|
||||
env: [],
|
||||
options: {},
|
||||
},
|
||||
],
|
||||
connected: ['AI2', 'VLLM'],
|
||||
default: {},
|
||||
} as any)
|
||||
|
||||
const { result } = renderHookWithProviders()
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.recentModels).toEqual([{ providerID: 'AI2', modelID: 'foo' }])
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.favoriteModels).toEqual([{ providerID: 'VLLM', modelID: 'bar' }])
|
||||
})
|
||||
})
|
||||
|
||||
it('returns raw values when providers query is loading (undefined)', async () => {
|
||||
mockGetOpenCodeModelState.mockResolvedValue({
|
||||
recent: [{ providerID: 'AI2', modelID: 'foo' }],
|
||||
favorite: [{ providerID: 'VLLM', modelID: 'bar' }],
|
||||
variant: {},
|
||||
})
|
||||
mockGetProviders.mockImplementation(() => new Promise(() => {}))
|
||||
|
||||
const { result } = renderHookWithProviders()
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.recentModels).toEqual([{ providerID: 'AI2', modelID: 'foo' }])
|
||||
})
|
||||
|
||||
expect(result.current.favoriteModels).toEqual([{ providerID: 'VLLM', modelID: 'bar' }])
|
||||
})
|
||||
|
||||
it('returns raw values when providers returns empty array', async () => {
|
||||
mockGetOpenCodeModelState.mockResolvedValue({
|
||||
recent: [{ providerID: 'AI2', modelID: 'foo' }],
|
||||
favorite: [{ providerID: 'VLLM', modelID: 'bar' }],
|
||||
variant: {},
|
||||
})
|
||||
mockGetProviders.mockResolvedValue({
|
||||
providers: [],
|
||||
connected: [],
|
||||
default: {},
|
||||
} as any)
|
||||
|
||||
const { result } = renderHookWithProviders()
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.recentModels).toEqual([{ providerID: 'AI2', modelID: 'foo' }])
|
||||
})
|
||||
|
||||
expect(result.current.favoriteModels).toEqual([{ providerID: 'VLLM', modelID: 'bar' }])
|
||||
})
|
||||
})
|
||||
|
||||
it('toggleFavorite calls toggleOpenCodeFavoriteModel and does not mutate Zustand', async () => {
|
||||
const { result } = renderHookWithProviders()
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current).toBeDefined()
|
||||
})
|
||||
|
||||
const testModel: ModelSelection = { providerID: 'anthropic', modelID: 'claude-sonnet-4' }
|
||||
result.current.toggleFavorite(testModel)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockToggleOpenCodeFavoriteModel).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
expect(mockToggleOpenCodeFavoriteModel.mock.calls[0][0]).toEqual(testModel)
|
||||
expect(useModelStore.getState().model).not.toEqual(testModel)
|
||||
})
|
||||
|
||||
it('removes recent models optimistically and rolls back on failure', async () => {
|
||||
const removedModel: ModelSelection = { providerID: 'anthropic', modelID: 'claude-sonnet-4' }
|
||||
const retainedModel: ModelSelection = { providerID: 'openai', modelID: 'gpt-4.1' }
|
||||
let rejectRemove: (error: Error) => void = () => {}
|
||||
mockGetOpenCodeModelState.mockResolvedValue({
|
||||
recent: [removedModel, retainedModel],
|
||||
favorite: [],
|
||||
variant: {},
|
||||
})
|
||||
mockRemoveOpenCodeRecentModel.mockImplementation(() => new Promise((_, reject) => {
|
||||
rejectRemove = reject
|
||||
}))
|
||||
|
||||
const { result } = renderHookWithProviders()
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.recentModels).toEqual([removedModel, retainedModel])
|
||||
})
|
||||
|
||||
act(() => {
|
||||
result.current.removeRecentModel(removedModel)
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.recentModels).toEqual([retainedModel])
|
||||
})
|
||||
|
||||
act(() => {
|
||||
rejectRemove(new Error('remove failed'))
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.recentModels).toEqual([removedModel, retainedModel])
|
||||
})
|
||||
})
|
||||
|
||||
it('user selection still updates recents', async () => {
|
||||
@@ -222,10 +365,24 @@ describe('useModelSelection', () => {
|
||||
result.current.setModel(testModel)
|
||||
|
||||
expect(useModelStore.getState().model).toEqual(testModel)
|
||||
expect(useModelStore.getState().recentModels[0]).toEqual(testModel)
|
||||
await waitFor(() => {
|
||||
expect(mockAddOpenCodeRecentModel).toHaveBeenCalled()
|
||||
expect(mockAddOpenCodeRecentModel.mock.calls[0][0]).toEqual(testModel)
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockAddOpenCodeRecentModel).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
|
||||
it('restoreSessionModel sets model without requiring providers', async () => {
|
||||
mockGetProviders.mockImplementation(() => new Promise(() => {}))
|
||||
|
||||
const { result } = renderHookWithProviders()
|
||||
|
||||
const sessionModel: ModelSelection = { providerID: 'anthropic', modelID: 'claude-sonnet-4' }
|
||||
result.current.restoreSessionModel(sessionModel)
|
||||
|
||||
expect(useModelStore.getState().model).toEqual(sessionModel)
|
||||
})
|
||||
})
|
||||
@@ -1,9 +1,9 @@
|
||||
import { useEffect } from 'react'
|
||||
import { useEffect, useMemo } from 'react'
|
||||
import { keepPreviousData, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useConfig } from './useOpenCode'
|
||||
import { useOpenCodeClient } from './useOpenCode'
|
||||
import { useModelStore, type ModelSelection } from '@/stores/modelStore'
|
||||
import { addOpenCodeRecentModel, getOpenCodeModelState, getProviders, toggleOpenCodeFavoriteModel } from '@/api/providers'
|
||||
import { useModelStore, modelExists, type ModelSelection } from '@/stores/modelStore'
|
||||
import { addOpenCodeRecentModel, getOpenCodeModelState, getProviders, removeOpenCodeRecentModel, toggleOpenCodeFavoriteModel, type OpenCodeModelState } from '@/api/providers'
|
||||
|
||||
interface UseModelSelectionResult {
|
||||
model: ModelSelection | null
|
||||
@@ -12,12 +12,18 @@ interface UseModelSelectionResult {
|
||||
favoriteModels: ModelSelection[]
|
||||
setModel: (model: ModelSelection) => void
|
||||
setActiveModel: (model: ModelSelection) => boolean
|
||||
restoreSessionModel: (model: ModelSelection) => void
|
||||
toggleFavorite: (model: ModelSelection) => void
|
||||
removeRecentModel: (model: ModelSelection) => void
|
||||
isModelStateLoading: boolean
|
||||
}
|
||||
|
||||
const modelStateQueryKey = ['opencode', 'model-state']
|
||||
|
||||
const isSameModel = (left: ModelSelection, right: ModelSelection) => (
|
||||
left.providerID === right.providerID && left.modelID === right.modelID
|
||||
)
|
||||
|
||||
export function useModelSelection(
|
||||
opcodeUrl: string | null | undefined,
|
||||
directory?: string
|
||||
@@ -35,12 +41,9 @@ export function useModelSelection(
|
||||
|
||||
const {
|
||||
model,
|
||||
recentModels,
|
||||
favoriteModels,
|
||||
setModel: setStoreModel,
|
||||
setActiveModel: setStoreActiveModel,
|
||||
syncModelState,
|
||||
toggleFavorite: toggleStoreFavorite,
|
||||
validateAndSyncModel,
|
||||
getModelString
|
||||
} = useModelStore()
|
||||
@@ -77,6 +80,52 @@ export function useModelSelection(
|
||||
},
|
||||
})
|
||||
|
||||
const removeRecentMutation = useMutation({
|
||||
mutationFn: removeOpenCodeRecentModel,
|
||||
onMutate: async (removedModel) => {
|
||||
const queryKey = [...modelStateQueryKey, opcodeUrl, directory]
|
||||
await queryClient.cancelQueries({ queryKey })
|
||||
const previousState = queryClient.getQueryData<OpenCodeModelState>(queryKey)
|
||||
|
||||
if (previousState) {
|
||||
const nextState: OpenCodeModelState = {
|
||||
...previousState,
|
||||
recent: previousState.recent.filter((model) => !isSameModel(model, removedModel)),
|
||||
}
|
||||
queryClient.setQueryData(queryKey, nextState)
|
||||
syncModelState(nextState)
|
||||
}
|
||||
|
||||
return { previousState }
|
||||
},
|
||||
onSuccess: (state) => {
|
||||
syncModelState(state)
|
||||
queryClient.setQueryData([...modelStateQueryKey, opcodeUrl, directory], state)
|
||||
queryClient.invalidateQueries({ queryKey: [...modelStateQueryKey, opcodeUrl, directory] })
|
||||
},
|
||||
onError: (error, _removedModel, context) => {
|
||||
if (context?.previousState) {
|
||||
syncModelState(context.previousState)
|
||||
queryClient.setQueryData([...modelStateQueryKey, opcodeUrl, directory], context.previousState)
|
||||
}
|
||||
console.error('Failed to remove recent model on backend', error)
|
||||
},
|
||||
})
|
||||
|
||||
const providers = providersData?.providers
|
||||
|
||||
const recentModels = useMemo(() => {
|
||||
const raw = modelState?.recent ?? []
|
||||
if (!providers || providers.length === 0) return raw
|
||||
return raw.filter((m) => modelExists(m, providers))
|
||||
}, [modelState?.recent, providers])
|
||||
|
||||
const favoriteModels = useMemo(() => {
|
||||
const raw = modelState?.favorite ?? []
|
||||
if (!providers || providers.length === 0) return raw
|
||||
return raw.filter((m) => modelExists(m, providers))
|
||||
}, [modelState?.favorite, providers])
|
||||
|
||||
const defaultModelString = providersData?.providers
|
||||
.map((provider) => {
|
||||
const modelID = providersData.default[provider.id] || Object.keys(provider.models || {})[0]
|
||||
@@ -113,11 +162,18 @@ export function useModelSelection(
|
||||
return true
|
||||
}
|
||||
|
||||
const restoreSessionModel = (sessionModel: ModelSelection): void => {
|
||||
setStoreActiveModel(sessionModel)
|
||||
}
|
||||
|
||||
const toggleFavorite = (nextModel: ModelSelection) => {
|
||||
toggleStoreFavorite(nextModel)
|
||||
updateFavoriteModel.mutate(nextModel)
|
||||
}
|
||||
|
||||
const removeRecentModel = (nextModel: ModelSelection) => {
|
||||
removeRecentMutation.mutate(nextModel)
|
||||
}
|
||||
|
||||
return {
|
||||
model,
|
||||
modelString: getModelString(),
|
||||
@@ -125,7 +181,9 @@ export function useModelSelection(
|
||||
favoriteModels,
|
||||
setModel,
|
||||
setActiveModel,
|
||||
restoreSessionModel,
|
||||
toggleFavorite,
|
||||
removeRecentModel,
|
||||
isModelStateLoading,
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
|
||||
export function useTallScrollContent(
|
||||
containerRef: React.RefObject<HTMLElement | null>,
|
||||
ratio = 1.5
|
||||
): boolean {
|
||||
const [isTall, setIsTall] = useState(false)
|
||||
const observingRef = useRef<HTMLElement | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const recompute = () => {
|
||||
const el = containerRef.current
|
||||
if (!el) return
|
||||
setIsTall(el.scrollHeight > el.clientHeight * ratio)
|
||||
}
|
||||
|
||||
const el = containerRef.current
|
||||
|
||||
if (!el || el === observingRef.current) return
|
||||
|
||||
observingRef.current = el
|
||||
recompute()
|
||||
|
||||
const observer = new ResizeObserver(recompute)
|
||||
observer.observe(el)
|
||||
el.addEventListener('scroll', recompute)
|
||||
|
||||
return () => {
|
||||
observer.disconnect()
|
||||
el.removeEventListener('scroll', recompute)
|
||||
observingRef.current = null
|
||||
}
|
||||
})
|
||||
|
||||
return isTall
|
||||
}
|
||||
Reference in new issue
Block a user