mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
fix: sanitize rendered markdown HTML
Add a shared rehype pipeline (rehype-raw -> rehype-sanitize -> rehype-highlight) to every markdown renderer so scripts, frames and event handlers are stripped from model output and repository files while safe HTML and highlighting survive. Also delete change walkthroughs when their session is deleted (including in-flight generation), build schedule model options from default/favorite/recent state, and include 127.0.0.1 origins in the default trusted origins.
This commit is contained in:
1 parent
b36d412ca2
commit
3d143568c1
25 files changed
+343
-101
No files matched your search
@@ -0,0 +1,30 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { render, screen, fireEvent } from '@testing-library/react'
|
||||
import { MarkdownRenderer } from './MarkdownRenderer'
|
||||
|
||||
describe('MarkdownRenderer', () => {
|
||||
it('toggles a task list item in the source content', () => {
|
||||
const onContentChange = vi.fn()
|
||||
render(<MarkdownRenderer content={'- [ ] first\n- [x] second'} onContentChange={onContentChange} />)
|
||||
|
||||
const [first, second] = screen.getAllByRole('checkbox')
|
||||
expect(first).not.toBeChecked()
|
||||
expect(first).toBeEnabled()
|
||||
expect(second).toBeChecked()
|
||||
|
||||
fireEvent.click(first!)
|
||||
expect(onContentChange).toHaveBeenCalledWith('- [x] first\n- [x] second')
|
||||
})
|
||||
|
||||
it('strips unsafe raw HTML from a repository file and keeps safe HTML', () => {
|
||||
const { container } = render(
|
||||
<MarkdownRenderer
|
||||
content={'# Readme\n\n<script>document.documentElement.dataset.fileProbe = 1</script>\n\n<p align="center"><img src="docs/logo.png" alt="Logo"></p>'}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(container.querySelector('script')).toBeNull()
|
||||
expect(document.documentElement.dataset.fileProbe).toBeUndefined()
|
||||
expect(screen.getByAltText('Logo')).toHaveAttribute('src', 'docs/logo.png')
|
||||
})
|
||||
})
|
||||
@@ -1,9 +1,8 @@
|
||||
import { memo, useMemo, useCallback } from 'react'
|
||||
import ReactMarkdown from 'react-markdown'
|
||||
import remarkGfm from 'remark-gfm'
|
||||
import rehypeHighlight from 'rehype-highlight'
|
||||
import rehypeRaw from 'rehype-raw'
|
||||
import { markdownComponents } from './MarkdownComponents'
|
||||
import { markdownRehypePlugins } from '@/lib/markdownRehypePlugins'
|
||||
import { MarkdownLink } from '@/components/ui/markdown-link'
|
||||
import { resolvePathFromFile } from '@/lib/markdownLinks'
|
||||
import type { Components } from 'react-markdown'
|
||||
@@ -95,7 +94,7 @@ export const MarkdownRenderer = memo(function MarkdownRenderer({ content, classN
|
||||
<div className={`pb-[200px] p-4 prose prose-invert prose-enhanced max-w-none text-foreground overflow-hidden break-words leading-snug ${className}`}>
|
||||
<ReactMarkdown
|
||||
remarkPlugins={[remarkGfm]}
|
||||
rehypePlugins={[rehypeHighlight, rehypeRaw]}
|
||||
rehypePlugins={markdownRehypePlugins}
|
||||
components={components}
|
||||
>
|
||||
{content}
|
||||
|
||||
@@ -108,6 +108,21 @@ describe('MessagePart', () => {
|
||||
expect(external).toHaveAttribute('rel', 'noopener noreferrer')
|
||||
})
|
||||
|
||||
it('strips unsafe raw HTML from a text part and keeps safe HTML', () => {
|
||||
const { container } = renderWithProviders(
|
||||
<MessagePart
|
||||
part={textPart(
|
||||
'Reply\n\n<iframe srcdoc="<script>parent.document.documentElement.dataset.chatProbe = 1</script>"></iframe>\n\n<details><summary>Notes</summary>Body</details>',
|
||||
)}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(container.querySelector('iframe')).toBeNull()
|
||||
expect(container.querySelector('script')).toBeNull()
|
||||
expect(document.documentElement.dataset.chatProbe).toBeUndefined()
|
||||
expect(container.querySelector('details summary')?.textContent).toBe('Notes')
|
||||
})
|
||||
|
||||
it('renders null for an empty text part', () => {
|
||||
const { container } = renderWithProviders(<MessagePart part={textPart(' ')} />)
|
||||
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
import React, { useEffect, useState, useId, useCallback } from 'react'
|
||||
import ReactMarkdown from 'react-markdown'
|
||||
import remarkGfm from 'remark-gfm'
|
||||
import rehypeHighlight from 'rehype-highlight'
|
||||
import rehypeRaw from 'rehype-raw'
|
||||
import mermaid from 'mermaid'
|
||||
import { Maximize2, X, AlertCircle } from 'lucide-react'
|
||||
import { CopyButton } from '@/components/ui/copy-button'
|
||||
import { MarkdownLink } from '@/components/ui/markdown-link'
|
||||
import { useTheme } from '@/hooks/useTheme'
|
||||
import { markdownRehypePlugins } from '@/lib/markdownRehypePlugins'
|
||||
|
||||
interface TextPartProps {
|
||||
text: string
|
||||
@@ -195,7 +194,7 @@ export function TextPart({ text, onFileClick }: TextPartProps) {
|
||||
<div className="prose prose-invert prose-enhanced max-w-none text-foreground overflow-hidden break-words leading-snug">
|
||||
<ReactMarkdown
|
||||
remarkPlugins={[remarkGfm]}
|
||||
rehypePlugins={[rehypeHighlight, rehypeRaw]}
|
||||
rehypePlugins={markdownRehypePlugins}
|
||||
components={{
|
||||
code({ className, children, ...props }) {
|
||||
const isInline = !className || !className.includes('language-')
|
||||
|
||||
@@ -14,6 +14,7 @@ import { useRemoveScheduleWorktrees, useScheduleWorktrees } from '@/hooks/useSch
|
||||
import { formatScheduleWorktreeLabel } from '@/lib/schedules/schedule-worktree'
|
||||
import { Bot, CalendarClock, Clock3, GitBranch, History, Loader2, Pencil, Play, Sparkles, Trash2 } from 'lucide-react'
|
||||
import { useScheduleModels } from '@/hooks/useScheduleModels'
|
||||
import { useScheduleTarget } from '@/hooks/useScheduleTarget'
|
||||
import { resolveScheduleModel } from '@/lib/schedules/schedule-model'
|
||||
|
||||
interface JobDetailTabProps {
|
||||
@@ -39,7 +40,8 @@ export function JobDetailTab({
|
||||
runningRun,
|
||||
isJobFetching,
|
||||
}: JobDetailTabProps) {
|
||||
const { availableModelKeys, configDefaultModel } = useScheduleModels(Boolean(selectedJob))
|
||||
const { scheduleTarget } = useScheduleTarget(selectedJob?.repoId)
|
||||
const { availableModelKeys, configDefaultModel } = useScheduleModels(Boolean(selectedJob), scheduleTarget?.fullPath)
|
||||
const resolvedModel = resolveScheduleModel(selectedJob?.model, availableModelKeys, configDefaultModel)
|
||||
const { data: worktrees = [] } = useScheduleWorktrees(selectedJob?.repoId, selectedJob?.id ?? null)
|
||||
const removeWorktrees = useRemoveScheduleWorktrees()
|
||||
|
||||
@@ -9,9 +9,11 @@ import type { ScheduleJob } from '@opencode-manager/shared/types'
|
||||
|
||||
Element.prototype.scrollIntoView = vi.fn()
|
||||
|
||||
const { mockGetProvidersWithModels, mockGetOpenCodeConfig } = vi.hoisted(() => ({
|
||||
const { mockGetProvidersWithModels, mockGetOpenCodeConfig, mockGetOpenCodeConfigModel, mockGetOpenCodeModelState } = vi.hoisted(() => ({
|
||||
mockGetProvidersWithModels: vi.fn(),
|
||||
mockGetOpenCodeConfig: vi.fn(),
|
||||
mockGetOpenCodeConfigModel: vi.fn(),
|
||||
mockGetOpenCodeModelState: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/usePromptTemplates', () => ({
|
||||
@@ -24,6 +26,8 @@ vi.mock('@/hooks/usePromptTemplates', () => ({
|
||||
vi.mock('@/api/providers', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('@/api/providers')>()),
|
||||
getProvidersWithModels: mockGetProvidersWithModels,
|
||||
getOpenCodeConfigModel: mockGetOpenCodeConfigModel,
|
||||
getOpenCodeModelState: mockGetOpenCodeModelState,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useOpenCode', () => ({
|
||||
@@ -53,7 +57,7 @@ const providers: ProviderWithModels[] = [
|
||||
},
|
||||
]
|
||||
|
||||
const config = makeOpenCodeConfigFile({ content: { model: 'openai/gpt-5' } })
|
||||
const config = makeOpenCodeConfigFile({ content: {} })
|
||||
|
||||
function getJob(overrides: Partial<ScheduleJob> = {}): ScheduleJob {
|
||||
return {
|
||||
@@ -97,6 +101,8 @@ describe('ScheduleJobDialog — model fallback', () => {
|
||||
vi.clearAllMocks()
|
||||
mockGetProvidersWithModels.mockResolvedValue(providers)
|
||||
mockGetOpenCodeConfig.mockResolvedValue(config)
|
||||
mockGetOpenCodeConfigModel.mockResolvedValue('openai/gpt-5')
|
||||
mockGetOpenCodeModelState.mockResolvedValue({ recent: [], favorite: [], variant: {} })
|
||||
})
|
||||
|
||||
it('prefills the config default when the stored model no longer exists', async () => {
|
||||
@@ -165,9 +171,7 @@ describe('ScheduleJobDialog — model fallback', () => {
|
||||
isConnected: true,
|
||||
},
|
||||
])
|
||||
mockGetOpenCodeConfig.mockResolvedValue(makeOpenCodeConfigFile({
|
||||
content: { model: 'openai/gpt-5-2025-08-07' },
|
||||
}))
|
||||
mockGetOpenCodeConfigModel.mockResolvedValue('openai/gpt-5-2025-08-07')
|
||||
|
||||
render(
|
||||
<ScheduleJobDialog
|
||||
|
||||
@@ -2,8 +2,7 @@ import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import type { CreateScheduleJobRequest, PromptTemplate, ScheduleJob, ScheduleMcpServer, ScheduleWorkspaceMode } from '@opencode-manager/shared/types'
|
||||
import { useScheduleModels } from '@/hooks/useScheduleModels'
|
||||
import { providerModelRef } from '@/api/providers'
|
||||
import { resolveScheduleModel } from '@/lib/schedules/schedule-model'
|
||||
import { buildScheduleModelOptions, resolveScheduleModel } from '@/lib/schedules/schedule-model'
|
||||
import { useAgents } from '@/hooks/useOpenCode'
|
||||
import { useScheduleTarget } from '@/hooks/useScheduleTarget'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
@@ -82,16 +81,16 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
|
||||
const { data: templates = EMPTY_TEMPLATES } = usePromptTemplates()
|
||||
const deleteTemplateMutation = useDeletePromptTemplate()
|
||||
|
||||
const { providerModels, availableModelKeys, configDefaultModel } = useScheduleModels(open)
|
||||
const effectiveRepoId = selectedRepoId ?? job?.repoId
|
||||
const { scheduleTarget } = useScheduleTarget(open ? effectiveRepoId : undefined)
|
||||
const scheduleDirectory = scheduleTarget?.fullPath
|
||||
|
||||
const { providerModels, modelState, availableModelKeys, configDefaultModel } = useScheduleModels(open, scheduleDirectory)
|
||||
|
||||
const resolvedModel = useMemo(
|
||||
() => (modelDirty ? (model.trim() || null) : resolveScheduleModel(model, availableModelKeys, configDefaultModel)),
|
||||
[model, modelDirty, availableModelKeys, configDefaultModel],
|
||||
)
|
||||
|
||||
const effectiveRepoId = selectedRepoId ?? job?.repoId
|
||||
const { scheduleTarget } = useScheduleTarget(open ? effectiveRepoId : undefined)
|
||||
const scheduleDirectory = scheduleTarget?.fullPath
|
||||
const { data: agents = [], isSuccess: agentsLoaded } = useAgents(scheduleDirectory, { enabled: !!scheduleDirectory })
|
||||
|
||||
const { data: skills = [], isLoading: skillsLoading } = useQuery({
|
||||
@@ -130,41 +129,10 @@ export function ScheduleJobDialog({ open, onOpenChange, job, isSaving, onSubmit,
|
||||
return [assistantOption, ...repoEntries]
|
||||
}, [repos])
|
||||
|
||||
const modelOptions = useMemo<ComboboxOption[]>(() => {
|
||||
const configuredModels: ComboboxOption[] = []
|
||||
const configuredValues = new Set<string>()
|
||||
|
||||
if (configDefaultModel) {
|
||||
const [providerId, ...modelParts] = configDefaultModel.split('/')
|
||||
const modelId = modelParts.join('/')
|
||||
const provider = providerModels.find((p) => p.id === providerId)
|
||||
const providerModel = provider?.models.find((m) => m.key === modelId || m.id === modelId)
|
||||
configuredValues.add(configDefaultModel)
|
||||
if (providerModel) {
|
||||
configuredValues.add(providerModelRef({ id: providerId }, providerModel))
|
||||
configuredValues.add(`${providerId}/${providerModel.id}`)
|
||||
}
|
||||
configuredModels.push({
|
||||
value: configDefaultModel,
|
||||
label: providerModel?.name || modelId,
|
||||
description: configDefaultModel,
|
||||
group: 'Configured',
|
||||
})
|
||||
}
|
||||
|
||||
const allModels = providerModels.flatMap((provider) =>
|
||||
provider.models
|
||||
.filter((providerModel) => !configuredValues.has(providerModelRef(provider, providerModel)))
|
||||
.map((providerModel) => ({
|
||||
value: providerModelRef(provider, providerModel),
|
||||
label: providerModel.name || providerModel.key || providerModel.id,
|
||||
description: providerModelRef(provider, providerModel),
|
||||
group: provider.name,
|
||||
})),
|
||||
)
|
||||
|
||||
return [...configuredModels, ...allModels]
|
||||
}, [providerModels, configDefaultModel])
|
||||
const modelOptions = useMemo(
|
||||
() => buildScheduleModelOptions(providerModels, modelState, configDefaultModel),
|
||||
[providerModels, modelState, configDefaultModel],
|
||||
)
|
||||
|
||||
const agentOptions = useMemo<ComboboxOption[]>(() => {
|
||||
return getPrimaryAgents(agents).map((agent) => ({
|
||||
|
||||
@@ -23,15 +23,35 @@ describe('ScheduleRunMarkdown links', () => {
|
||||
expect(link.getAttribute('rel')).toBe('noopener noreferrer')
|
||||
})
|
||||
|
||||
it('renders raw HTML from generated prose as inert text', () => {
|
||||
it('strips unsafe raw HTML from generated prose', () => {
|
||||
const payload =
|
||||
'<iframe srcdoc="<script>parent.document.documentElement.dataset.scheduleProbe = 1</script>"></iframe>'
|
||||
'<iframe srcdoc="<script>parent.document.documentElement.dataset.scheduleProbe = 1</script>"></iframe><img src="x" onerror="document.documentElement.dataset.scheduleProbe = 2">'
|
||||
const { container } = render(<ScheduleRunMarkdown content={`Before\n\n${payload}\n\nAfter`} />)
|
||||
|
||||
expect(container.querySelector('iframe')).toBeNull()
|
||||
expect(container.querySelector('script')).toBeNull()
|
||||
expect(container.querySelector('img')?.getAttribute('onerror')).toBeNull()
|
||||
expect(document.documentElement.dataset.scheduleProbe).toBeUndefined()
|
||||
expect(screen.getByText(/iframe/)).toBeInTheDocument()
|
||||
expect(screen.getByText('Before')).toBeInTheDocument()
|
||||
expect(screen.getByText('After')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders safe raw HTML', () => {
|
||||
const { container } = render(
|
||||
<ScheduleRunMarkdown content={'<details><summary>More</summary>Hidden body</details>\n\nPress <kbd>Enter</kbd>'} />,
|
||||
)
|
||||
|
||||
expect(container.querySelector('details summary')?.textContent).toBe('More')
|
||||
expect(screen.getByText('Enter').tagName).toBe('KBD')
|
||||
})
|
||||
|
||||
it('keeps syntax highlighting after sanitization', () => {
|
||||
const { container } = render(<ScheduleRunMarkdown content={'```ts\nconst a = 1\n```'} />)
|
||||
|
||||
const code = container.querySelector('pre code')
|
||||
expect(code?.className).toContain('language-ts')
|
||||
expect(code?.className).toContain('hljs')
|
||||
expect(code?.querySelector('[class^="hljs-"]')).not.toBeNull()
|
||||
})
|
||||
|
||||
it('still renders GFM formatting', () => {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import ReactMarkdown, { type Components } from 'react-markdown'
|
||||
import rehypeHighlight from 'rehype-highlight'
|
||||
import remarkGfm from 'remark-gfm'
|
||||
import { markdownComponents } from '@/components/file-browser/MarkdownComponents'
|
||||
import { MarkdownLink } from '@/components/ui/markdown-link'
|
||||
import { markdownRehypePlugins } from '@/lib/markdownRehypePlugins'
|
||||
|
||||
type ScheduleRunMarkdownProps = {
|
||||
content: string
|
||||
@@ -22,7 +22,7 @@ export function ScheduleRunMarkdown({ content, onOpenLocalPath }: ScheduleRunMar
|
||||
<div className="prose prose-invert prose-enhanced max-w-none break-words text-foreground leading-snug">
|
||||
<ReactMarkdown
|
||||
remarkPlugins={[remarkGfm]}
|
||||
rehypePlugins={[rehypeHighlight]}
|
||||
rehypePlugins={markdownRehypePlugins}
|
||||
components={components}
|
||||
>
|
||||
{content}
|
||||
|
||||
@@ -33,6 +33,15 @@ export function useOpenCodeModelState(directory?: string, enabled = true) {
|
||||
})
|
||||
}
|
||||
|
||||
export function useOpenCodeConfigModel(directory?: string, enabled = true) {
|
||||
return useQuery({
|
||||
queryKey: ['opencode', 'config', 'model', directory],
|
||||
queryFn: () => getOpenCodeConfigModel(directory),
|
||||
staleTime: 30000,
|
||||
enabled,
|
||||
})
|
||||
}
|
||||
|
||||
export function useModelSelection(directory?: string): UseModelSelectionResult {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
@@ -49,11 +58,7 @@ export function useModelSelection(directory?: string): UseModelSelectionResult {
|
||||
|
||||
const { data: modelState, isLoading: isModelStateLoading } = useOpenCodeModelState(directory)
|
||||
|
||||
const { data: configModelString, isLoading: isConfigModelLoading } = useQuery({
|
||||
queryKey: ['opencode', 'config', 'model', directory],
|
||||
queryFn: () => getOpenCodeConfigModel(directory),
|
||||
staleTime: 30000,
|
||||
})
|
||||
const { data: configModelString, isLoading: isConfigModelLoading } = useOpenCodeConfigModel(directory)
|
||||
|
||||
const updateRecentModel = useMutation({
|
||||
mutationFn: addOpenCodeRecentModel,
|
||||
|
||||
@@ -1,23 +1,25 @@
|
||||
import { useMemo } from 'react'
|
||||
import { useProvidersWithModels } from '@/hooks/useProvidersWithModels'
|
||||
import { useOpenCodeConfigFile } from '@/hooks/useOpenCodeConfigFile'
|
||||
import { buildAvailableModelKeys, getConfigDefaultModel } from '@/lib/schedules/schedule-model'
|
||||
import { useOpenCodeConfigModel, useOpenCodeModelState } from '@/hooks/useModelSelection'
|
||||
import { buildAvailableModelKeys } from '@/lib/schedules/schedule-model'
|
||||
|
||||
export function useScheduleModels(enabled: boolean) {
|
||||
export function useScheduleModels(enabled: boolean, directory?: string) {
|
||||
const providersQuery = useProvidersWithModels({
|
||||
enabled,
|
||||
directory,
|
||||
keyParts: ['schedule-models'],
|
||||
})
|
||||
const { data: configFile, isLoading: configLoading } = useOpenCodeConfigFile(enabled)
|
||||
const { data: modelState } = useOpenCodeModelState(directory, enabled)
|
||||
const { data: configDefaultModel = null, isLoading: configLoading } = useOpenCodeConfigModel(directory, enabled)
|
||||
const providerModels = providersQuery.data
|
||||
const availableModelKeys = useMemo(
|
||||
() => (providersQuery.isSuccess ? buildAvailableModelKeys(providerModels) : null),
|
||||
[providersQuery.isSuccess, providerModels],
|
||||
)
|
||||
const configDefaultModel = useMemo(() => getConfigDefaultModel(configFile), [configFile])
|
||||
|
||||
return {
|
||||
providerModels,
|
||||
modelState,
|
||||
availableModelKeys,
|
||||
configDefaultModel,
|
||||
isLoading: providersQuery.isLoading || configLoading,
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import rehypeHighlight from 'rehype-highlight'
|
||||
import rehypeRaw from 'rehype-raw'
|
||||
import rehypeSanitize from 'rehype-sanitize'
|
||||
import type { Options } from 'react-markdown'
|
||||
|
||||
/**
|
||||
* Rehype pipeline shared by every Markdown renderer. Raw HTML is parsed, then sanitized to
|
||||
* GitHub's allow-list so scripts, frames and event handlers are stripped from model output and
|
||||
* repository files, and highlighting runs last so its classes survive sanitization.
|
||||
*/
|
||||
export const markdownRehypePlugins: NonNullable<Options['rehypePlugins']> = [rehypeRaw, rehypeSanitize, rehypeHighlight]
|
||||
@@ -1,11 +1,10 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
buildAvailableModelKeys,
|
||||
getConfigDefaultModel,
|
||||
buildScheduleModelOptions,
|
||||
resolveScheduleModel,
|
||||
} from './schedule-model'
|
||||
import type { ProviderWithModels } from '@/api/providers'
|
||||
import type { OpenCodeConfigFile } from '@/api/types/settings'
|
||||
|
||||
function makeProvider(id: string, models: Array<{ id: string; key?: string }>): ProviderWithModels {
|
||||
return {
|
||||
@@ -18,16 +17,6 @@ function makeProvider(id: string, models: Array<{ id: string; key?: string }>):
|
||||
}
|
||||
}
|
||||
|
||||
function makeConfigFile(content: Record<string, unknown>): OpenCodeConfigFile {
|
||||
return {
|
||||
path: '/workspace/.config/opencode/opencode.json',
|
||||
content,
|
||||
rawContent: JSON.stringify(content),
|
||||
isValid: true,
|
||||
updatedAt: 0,
|
||||
}
|
||||
}
|
||||
|
||||
describe('buildAvailableModelKeys', () => {
|
||||
it('collects provider/model keys and backing model ids', () => {
|
||||
const keys = buildAvailableModelKeys([
|
||||
@@ -43,18 +32,34 @@ describe('buildAvailableModelKeys', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('getConfigDefaultModel', () => {
|
||||
it('returns the configured model, trimmed, and ignores small_model', () => {
|
||||
expect(getConfigDefaultModel(makeConfigFile({
|
||||
model: ' openai/gpt-5 ',
|
||||
small_model: 'openai/gpt-5-mini',
|
||||
}))).toBe('openai/gpt-5')
|
||||
describe('buildScheduleModelOptions', () => {
|
||||
const providers = [
|
||||
makeProvider('anthropic', [{ id: 'claude-opus' }, { id: 'claude-sonnet' }]),
|
||||
makeProvider('openai', [{ id: 'backing-gpt-5', key: 'gpt-5' }, { id: 'gpt-5-mini' }]),
|
||||
]
|
||||
|
||||
it('orders default, favorites, and recents ahead of providers without duplicates', () => {
|
||||
const options = buildScheduleModelOptions(
|
||||
providers,
|
||||
{
|
||||
favorite: [{ providerID: 'openai', modelID: 'gpt-5-mini' }],
|
||||
recent: [{ providerID: 'anthropic', modelID: 'claude-sonnet' }, { providerID: 'openai', modelID: 'gpt-5' }],
|
||||
variant: {},
|
||||
},
|
||||
'openai/backing-gpt-5',
|
||||
)
|
||||
|
||||
expect(options.map((option) => [option.group, option.value])).toEqual([
|
||||
['Default', 'openai/backing-gpt-5'],
|
||||
['Favorites', 'openai/gpt-5-mini'],
|
||||
['Recent', 'anthropic/claude-sonnet'],
|
||||
['anthropic', 'anthropic/claude-opus'],
|
||||
])
|
||||
})
|
||||
|
||||
it('returns null when the model is missing or unset', () => {
|
||||
expect(getConfigDefaultModel(undefined)).toBeNull()
|
||||
expect(getConfigDefaultModel(makeConfigFile({}))).toBeNull()
|
||||
expect(getConfigDefaultModel(makeConfigFile({ model: 42 }))).toBeNull()
|
||||
it('keeps an unknown default model selectable', () => {
|
||||
const options = buildScheduleModelOptions(providers, undefined, 'custom/model-x')
|
||||
expect(options[0]).toEqual({ value: 'custom/model-x', label: 'model-x', description: 'custom/model-x', group: 'Default' })
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { ProviderWithModels } from '@/api/providers'
|
||||
import type { OpenCodeModelState, ProviderWithModels } from '@/api/providers'
|
||||
import { providerModelRef } from '@/api/providers'
|
||||
import type { OpenCodeConfigFile } from '@/api/types/settings'
|
||||
import type { ComboboxOption } from '@/components/ui/combobox'
|
||||
import { buildModelSections } from '@/lib/modelSections'
|
||||
|
||||
function normalizeModel(model: unknown): string | null {
|
||||
if (typeof model !== 'string') return null
|
||||
@@ -19,8 +20,38 @@ export function buildAvailableModelKeys(providers: ProviderWithModels[]): Set<st
|
||||
return keys
|
||||
}
|
||||
|
||||
export function getConfigDefaultModel(configFile: OpenCodeConfigFile | undefined): string | null {
|
||||
return normalizeModel(configFile?.content?.model)
|
||||
function findProviderModel(providers: ProviderWithModels[], ref: string) {
|
||||
const [providerId, ...modelParts] = ref.split('/')
|
||||
const modelId = modelParts.join('/')
|
||||
const provider = providers.find((candidate) => candidate.id === providerId)
|
||||
const model = provider?.models.find((candidate) => candidate.key === modelId || candidate.id === modelId)
|
||||
return provider && model ? { value: providerModelRef(provider, model), label: model.name || modelId } : { value: ref, label: modelId || ref }
|
||||
}
|
||||
|
||||
/** Builds schedule model options with the default, favorite, and recent models ahead of the provider groups. */
|
||||
export function buildScheduleModelOptions(
|
||||
providers: ProviderWithModels[],
|
||||
modelState: OpenCodeModelState | undefined,
|
||||
defaultModel: string | null | undefined,
|
||||
): ComboboxOption[] {
|
||||
const normalizedDefault = normalizeModel(defaultModel)
|
||||
const defaultModelMatch = normalizedDefault ? findProviderModel(providers, normalizedDefault) : null
|
||||
const sectionOptions = buildModelSections(providers, modelState).flatMap((section) =>
|
||||
section.options
|
||||
.filter((option) => option.value !== defaultModelMatch?.value)
|
||||
.map((option) => ({
|
||||
value: option.value,
|
||||
label: option.label,
|
||||
description: option.value,
|
||||
group: section.title,
|
||||
})),
|
||||
)
|
||||
|
||||
if (!normalizedDefault || !defaultModelMatch) return sectionOptions
|
||||
return [
|
||||
{ value: normalizedDefault, label: defaultModelMatch.label, description: normalizedDefault, group: 'Default' },
|
||||
...sectionOptions,
|
||||
]
|
||||
}
|
||||
|
||||
export function resolveScheduleModel(
|
||||
|
||||
Reference in new issue
Block a user