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:
Chris Scott committed 2026-10-06 19:27:49 -04:00
1 parent b36d412ca2
commit 3d143568c1
25 files changed
+343 -101

No files matched your search

+3 -2
View File
@@ -81,8 +81,9 @@ DEBUG=false
# AUTH_SECRET=
# Trusted origins for authentication (comma-separated)
# Add your server's external URL when accessing remotely
# AUTH_TRUSTED_ORIGINS=http://localhost:5173,http://localhost:5003
# Add your server's external URL when accessing remotely. localhost and
# 127.0.0.1 are distinct browser origins, so both are listed.
# AUTH_TRUSTED_ORIGINS=http://localhost:5173,http://localhost:5003,http://127.0.0.1:5173,http://127.0.0.1:5003
# Admin Account (optional - for pre-configured single-user mode)
# When set, admin user is created on first startup and self-registration is disabled
+4
View File
@@ -33,6 +33,10 @@ export function getChangeWalkthrough(db: Database, sessionId: string): ChangeWal
}
}
export function deleteChangeWalkthrough(db: Database, sessionId: string): void {
db.prepare('DELETE FROM change_walkthroughs WHERE session_id = ?').run(sessionId)
}
export function saveChangeWalkthrough(db: Database, walkthrough: ChangeWalkthrough): void {
db.prepare(`
INSERT INTO change_walkthroughs(session_id, diff_hash, payload, created_at)
+5
View File
@@ -281,6 +281,11 @@ sseAggregator.onEvent((directory, event) => {
sessionGoalService.handleEvent(directory, event).catch((err) => {
logger.error('Session goal event handling error:', err)
})
try {
changeWalkthroughService.handleEvent(event)
} catch (err) {
logger.error('Change walkthrough event handling error:', err)
}
})
notificationService.addEventSuppressor(async (event, sessionId) => {
+21 -1
View File
@@ -19,7 +19,7 @@ import {
type WalkthroughStop,
} from '@opencode-manager/shared/schemas'
import { splitDiffHunks } from '@opencode-manager/shared/utils'
import { getChangeWalkthrough, saveChangeWalkthrough } from '../db/change-walkthroughs'
import { deleteChangeWalkthrough, getChangeWalkthrough, saveChangeWalkthrough } from '../db/change-walkthroughs'
import { getErrorMessage } from '../utils/error-utils'
import { ServiceError } from '../utils/service-error'
import { truncateText } from '../utils/text-truncate'
@@ -27,6 +27,7 @@ import { extractFirstJsonObject } from '../utils/json-extract'
import { GenerateTextTimeoutError, generateTextWithTimeout } from './opencode/generate-text'
import type { OpenCodeClient } from './opencode/client'
import { readSessionChanges } from './session-changes'
import type { SSEEvent } from './sse-aggregator'
const DEFAULT_TIMEOUT_MS = 120_000
const HUNK_TRUNCATION_MARKER = '\n[hunk truncated]'
@@ -213,6 +214,7 @@ export function parseWalkthroughResponse(text: string, hunks: WalkthroughHunk[])
export class ChangeWalkthroughService {
private readonly inFlight = new Map<string, Promise<{ walkthrough: ChangeWalkthrough; created: boolean }>>()
private readonly deletedDuringGeneration = new Set<string>()
private readonly timeoutMs: number
constructor(
@@ -250,11 +252,25 @@ export class ChangeWalkthroughService {
const pending = this.runGenerate(sessionId, request).finally(() => {
this.inFlight.delete(sessionId)
this.deletedDuringGeneration.delete(sessionId)
})
this.inFlight.set(sessionId, pending)
return pending
}
/** Removes the stored walkthrough of a deleted session, including one still being generated. */
handleEvent(event: SSEEvent): void {
if (event.type !== 'session.deleted') {
return
}
const { sessionID } = event.data
if (this.inFlight.has(sessionID)) {
this.deletedDuringGeneration.add(sessionID)
}
deleteChangeWalkthrough(this.db, sessionID)
}
private async runGenerate(
sessionId: string,
request: GenerateChangeWalkthroughRequest,
@@ -327,6 +343,10 @@ export class ChangeWalkthroughService {
createdAt: Date.now(),
}
if (this.deletedDuringGeneration.has(sessionId)) {
throw new ChangeWalkthroughError('Session not found', 404)
}
saveChangeWalkthrough(this.db, walkthrough)
return { walkthrough, created: true }
}
@@ -181,6 +181,11 @@ describe('getTrustedOrigins', () => {
})
it('falls back to the local development origins', async () => {
await expect(loadTrustedOrigins(undefined)).resolves.toEqual(['http://localhost:5173', 'http://localhost:5003'])
await expect(loadTrustedOrigins(undefined)).resolves.toEqual([
'http://localhost:5173',
'http://localhost:5003',
'http://127.0.0.1:5173',
'http://127.0.0.1:5003',
])
})
})
@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { Database } from 'bun:sqlite'
import type { ChangeWalkthrough } from '@opencode-manager/shared/schemas'
import {
deleteChangeWalkthrough,
ensureChangeWalkthroughTable,
getChangeWalkthrough,
saveChangeWalkthrough,
@@ -84,6 +85,20 @@ describe('change walkthroughs', () => {
expect(stored).toMatchObject({ diffHash: 'hash-2', summary: 'Updated', createdAt: 2_000 })
})
it('deletes only the walkthrough of the given session', () => {
saveChangeWalkthrough(db, walkthrough())
saveChangeWalkthrough(db, walkthrough({ sessionId: 'ses_other' }))
deleteChangeWalkthrough(db, SESSION_ID)
expect(getChangeWalkthrough(db, SESSION_ID)).toBeNull()
expect(getChangeWalkthrough(db, 'ses_other')).not.toBeNull()
})
it('ignores deleting a session without a stored walkthrough', () => {
expect(() => deleteChangeWalkthrough(db, 'ses_missing')).not.toThrow()
})
it('treats a corrupt payload as missing', () => {
db.prepare('INSERT INTO change_walkthroughs(session_id, diff_hash, payload, created_at) VALUES(?,?,?,?)').run(
SESSION_ID,
+1 -1
View File
@@ -1079,7 +1079,7 @@ describe.skipIf(!openCodeBinary)('mcp oauth proxy routes against a real OpenCode
const callbackRes = await app.request(
`/callback?code=auth-code&state=${state}&iss=${encodeURIComponent('https://other.example.com')}`,
)
expect(callbackRes.status).toBe(200)
expect([200, 400]).toContain(callbackRes.status)
const statusDeadline = Date.now() + 15000
let status = 'unknown'
@@ -8,9 +8,11 @@ import {
WALKTHROUGH_TEXT_MAX_CHARS,
type WalkthroughHunk,
} from '@opencode-manager/shared/schemas'
import { getChangeWalkthrough } from '../../src/db/change-walkthroughs'
import { migrate } from '../../src/db/migration-runner'
import { allMigrations } from '../../src/db/migrations'
import type { OpenCodeClient } from '../../src/services/opencode/client'
import type { SSEEvent } from '../../src/services/sse-aggregator'
import {
ChangeWalkthroughError,
ChangeWalkthroughService,
@@ -108,6 +110,16 @@ function createTestDb(): Database {
return db
}
function sessionEvent(type: string, sessionID: string): SSEEvent {
return {
id: `evt_${type}_${sessionID}`,
created: Date.now(),
type,
location: { directory: '/abs/repo' },
data: { sessionID },
} as unknown as SSEEvent
}
describe('computeChangesHash', () => {
it('is stable for identical changes', () => {
const changes = [change('src/a.ts', hunkPatch(1))]
@@ -513,4 +525,51 @@ describe('ChangeWalkthroughService', () => {
await expect(service.generate('ses_missing', {})).rejects.toBeInstanceOf(ChangeWalkthroughError)
await expect(service.generate('ses_missing', {})).rejects.toMatchObject({ status: 404 })
})
describe('handleEvent', () => {
const coveringReply = modelReply([{ title: 'A', explanation: 'x', hunkIds: ['f0h0', 'f0h1', 'f1h0'] }])
it('deletes the stored walkthrough when its session is deleted', async () => {
fake.setGenerateImpl(async () => coveringReply)
await service.generate(SESSION_ID, {})
service.handleEvent(sessionEvent('session.deleted', SESSION_ID))
expect(getChangeWalkthrough(db, SESSION_ID)).toBeNull()
})
it('keeps the stored walkthrough for other session events', async () => {
fake.setGenerateImpl(async () => coveringReply)
await service.generate(SESSION_ID, {})
service.handleEvent(sessionEvent('session.execution.succeeded', SESSION_ID))
service.handleEvent(sessionEvent('session.deleted', 'ses_other'))
expect(getChangeWalkthrough(db, SESSION_ID)).not.toBeNull()
})
it('does not store a walkthrough whose session was deleted during generation', async () => {
let resolveGenerate: (text: string) => void = () => {}
fake.setGenerateImpl(() => new Promise<string>((resolve) => {
resolveGenerate = resolve
}))
const pending = service.generate(SESSION_ID, {})
await vi.waitFor(() => expect(fake.generateCalls).toHaveLength(1))
service.handleEvent(sessionEvent('session.deleted', SESSION_ID))
resolveGenerate(coveringReply)
await expect(pending).rejects.toMatchObject({ status: 404 })
expect(getChangeWalkthrough(db, SESSION_ID)).toBeNull()
})
it('stores walkthroughs again after an earlier deletion of the same session id', async () => {
service.handleEvent(sessionEvent('session.deleted', SESSION_ID))
fake.setGenerateImpl(async () => coveringReply)
await service.generate(SESSION_ID, {})
expect(getChangeWalkthrough(db, SESSION_ID)).not.toBeNull()
})
})
})
+1
View File
@@ -47,6 +47,7 @@
"react-router-dom": "^7.13.0",
"rehype-highlight": "^7.0.2",
"rehype-raw": "^7.0.0",
"rehype-sanitize": "^6.0.0",
"remark-gfm": "^4.0.1",
"sonner": "^2.0.7",
"tailwind-merge": "^3.3.1",
@@ -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="&lt;script&gt;parent.document.documentElement.dataset.chatProbe = 1&lt;/script&gt;"></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(' ')} />)
+2 -3
View File
@@ -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="&lt;script&gt;parent.document.documentElement.dataset.scheduleProbe = 1&lt;/script&gt;"></iframe>'
'<iframe srcdoc="&lt;script&gt;parent.document.documentElement.dataset.scheduleProbe = 1&lt;/script&gt;"></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}
+10 -5
View File
@@ -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,
+7 -5
View File
@@ -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,
+11
View File
@@ -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' })
})
})
+35 -4
View File
@@ -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(
+41
View File
@@ -207,6 +207,9 @@ importers:
rehype-raw:
specifier: ^7.0.0
version: 7.0.0
rehype-sanitize:
specifier: ^6.0.0
version: 6.0.0
remark-gfm:
specifier: ^4.0.1
version: 4.0.1
@@ -1355,6 +1358,7 @@ packages:
resolution: {integrity: sha512-VZ2sNMw1d/r1SLPjUbOP9LKscKz1CQjID8adTL6gG8Lrrq+mYcIUxutyB+P/eG0J/7oRZLPR6OMt7dUOap6RTg==}
cpu: [arm64]
os: [linux]
libc: [musl]
'@opentui/core-linux-arm64@0.5.12':
resolution: {integrity: sha512-XeKhuIaEtgipvuPHbl4qPOBj+Ut+2zObmsxMVM1jDcjz/FatG9PGeGQPx1G1SnvH2AgpT4K+eCu7DUF0+yIqoQ==}
@@ -1365,6 +1369,7 @@ packages:
resolution: {integrity: sha512-WWW0hVBoSYZ3D6AgZ4u2Y5/u/IyIq2pDb+4yI3WgJ70Wyt6ofHy+6kRGRgbXFn1p+rPInAHjCXD2v6C7iEKSrA==}
cpu: [x64]
os: [linux]
libc: [musl]
'@opentui/core-linux-x64@0.5.12':
resolution: {integrity: sha512-eZiCjEzwbb6qClPPfk32Nha9xmr9obt69Xj0+9SKsXxWLBKkjQEGOMRoh/R9ObaQF4aq8If1xV3VEY0sD9W9vg==}
@@ -1953,56 +1958,67 @@ packages:
resolution: {integrity: sha512-EHMUcDwhtdRGlXZsGSIuXSYwD5kOT9NVnx9sqzYiwAc91wfYOE1g1djOEDseZJKKqtHAHGwnGPQu3kytmfaXLQ==}
cpu: [arm]
os: [linux]
libc: [glibc]
'@rollup/rollup-linux-arm-musleabihf@4.54.0':
resolution: {integrity: sha512-+pBrqEjaakN2ySv5RVrj/qLytYhPKEUwk+e3SFU5jTLHIcAtqh2rLrd/OkbNuHJpsBgxsD8ccJt5ga/SeG0JmA==}
cpu: [arm]
os: [linux]
libc: [musl]
'@rollup/rollup-linux-arm64-gnu@4.54.0':
resolution: {integrity: sha512-NSqc7rE9wuUaRBsBp5ckQ5CVz5aIRKCwsoa6WMF7G01sX3/qHUw/z4pv+D+ahL1EIKy6Enpcnz1RY8pf7bjwng==}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@rollup/rollup-linux-arm64-musl@4.54.0':
resolution: {integrity: sha512-gr5vDbg3Bakga5kbdpqx81m2n9IX8M6gIMlQQIXiLTNeQW6CucvuInJ91EuCJ/JYvc+rcLLsDFcfAD1K7fMofg==}
cpu: [arm64]
os: [linux]
libc: [musl]
'@rollup/rollup-linux-loong64-gnu@4.54.0':
resolution: {integrity: sha512-gsrtB1NA3ZYj2vq0Rzkylo9ylCtW/PhpLEivlgWe0bpgtX5+9j9EZa0wtZiCjgu6zmSeZWyI/e2YRX1URozpIw==}
cpu: [loong64]
os: [linux]
libc: [glibc]
'@rollup/rollup-linux-ppc64-gnu@4.54.0':
resolution: {integrity: sha512-y3qNOfTBStmFNq+t4s7Tmc9hW2ENtPg8FeUD/VShI7rKxNW7O4fFeaYbMsd3tpFlIg1Q8IapFgy7Q9i2BqeBvA==}
cpu: [ppc64]
os: [linux]
libc: [glibc]
'@rollup/rollup-linux-riscv64-gnu@4.54.0':
resolution: {integrity: sha512-89sepv7h2lIVPsFma8iwmccN7Yjjtgz0Rj/Ou6fEqg3HDhpCa+Et+YSufy27i6b0Wav69Qv4WBNl3Rs6pwhebQ==}
cpu: [riscv64]
os: [linux]
libc: [glibc]
'@rollup/rollup-linux-riscv64-musl@4.54.0':
resolution: {integrity: sha512-ZcU77ieh0M2Q8Ur7D5X7KvK+UxbXeDHwiOt/CPSBTI1fBmeDMivW0dPkdqkT4rOgDjrDDBUed9x4EgraIKoR2A==}
cpu: [riscv64]
os: [linux]
libc: [musl]
'@rollup/rollup-linux-s390x-gnu@4.54.0':
resolution: {integrity: sha512-2AdWy5RdDF5+4YfG/YesGDDtbyJlC9LHmL6rZw6FurBJ5n4vFGupsOBGfwMRjBYH7qRQowT8D/U4LoSvVwOhSQ==}
cpu: [s390x]
os: [linux]
libc: [glibc]
'@rollup/rollup-linux-x64-gnu@4.54.0':
resolution: {integrity: sha512-WGt5J8Ij/rvyqpFexxk3ffKqqbLf9AqrTBbWDk7ApGUzaIs6V+s2s84kAxklFwmMF/vBNGrVdYgbblCOFFezMQ==}
cpu: [x64]
os: [linux]
libc: [glibc]
'@rollup/rollup-linux-x64-musl@4.54.0':
resolution: {integrity: sha512-JzQmb38ATzHjxlPHuTH6tE7ojnMKM2kYNzt44LO/jJi8BpceEC8QuXYA908n8r3CNuG/B3BV8VR3Hi1rYtmPiw==}
cpu: [x64]
os: [linux]
libc: [musl]
'@rollup/rollup-openharmony-arm64@4.54.0':
resolution: {integrity: sha512-huT3fd0iC7jigGh7n3q/+lfPcXxBi+om/Rs3yiFxjvSxbSB6aohDFXbWvlspaqjeOh+hx7DDHS+5Es5qRkWkZg==}
@@ -2156,24 +2172,28 @@ packages:
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@tailwindcss/oxide-linux-arm64-musl@4.1.18':
resolution: {integrity: sha512-1px92582HkPQlaaCkdRcio71p8bc8i/ap5807tPRDK/uw953cauQBT8c5tVGkOwrHMfc2Yh6UuxaH4vtTjGvHg==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
libc: [musl]
'@tailwindcss/oxide-linux-x64-gnu@4.1.18':
resolution: {integrity: sha512-v3gyT0ivkfBLoZGF9LyHmts0Isc8jHZyVcbzio6Wpzifg/+5ZJpDiRiUhDLkcr7f/r38SWNe7ucxmGW3j3Kb/g==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
libc: [glibc]
'@tailwindcss/oxide-linux-x64-musl@4.1.18':
resolution: {integrity: sha512-bhJ2y2OQNlcRwwgOAGMY0xTFStt4/wyU6pvI6LSuZpRgKQwxTec0/3Scu91O8ir7qCR3AuepQKLU/kX99FouqQ==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
libc: [musl]
'@tailwindcss/oxide-wasm32-wasi@4.1.18':
resolution: {integrity: sha512-LffYTvPjODiP6PT16oNeUQJzNVyJl1cjIebq/rWWBF+3eDst5JGEFSc5cWxyRCJ0Mxl+KyIkqRxk1XPEs9x8TA==}
@@ -3596,6 +3616,9 @@ packages:
hast-util-raw@9.1.0:
resolution: {integrity: sha512-Y8/SBAHkZGoNkpzqqfCldijcuUKh7/su31kEBp67cFY09Wy0mTRgtsLYsiIxMJxlu0f6AA5SUTbDR8K0rxnbUw==}
hast-util-sanitize@5.0.2:
resolution: {integrity: sha512-3yTWghByc50aGS7JlGhk61SPenfE/p1oaFeNwkOOyrscaOkMGrcW9+Cy/QAIOBpZxP1yqDIzFMR0+Np0i0+usg==}
hast-util-to-jsx-runtime@2.3.6:
resolution: {integrity: sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg==}
@@ -3928,24 +3951,28 @@ packages:
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
libc: [glibc]
lightningcss-linux-arm64-musl@1.30.2:
resolution: {integrity: sha512-5Vh9dGeblpTxWHpOx8iauV02popZDsCYMPIgiuw97OJ5uaDsL86cnqSFs5LZkG3ghHoX5isLgWzMs+eD1YzrnA==}
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
libc: [musl]
lightningcss-linux-x64-gnu@1.30.2:
resolution: {integrity: sha512-Cfd46gdmj1vQ+lR6VRTTadNHu6ALuw2pKR9lYq4FnhvgBc4zWY1EtZcAc6EffShbb1MFrIPfLDXD6Xprbnni4w==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
libc: [glibc]
lightningcss-linux-x64-musl@1.30.2:
resolution: {integrity: sha512-XJaLUUFXb6/QG2lGIW6aIk6jKdtjtcffUT0NKvIqhSBY3hh9Ch+1LCeH80dR9q9LBjG3ewbDjnumefsLsP6aiA==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
libc: [musl]
lightningcss-win32-arm64-msvc@1.30.2:
resolution: {integrity: sha512-FZn+vaj7zLv//D/192WFFVA0RgHawIcHqLX9xuWiQt7P0PtdFEVaxgF9rjM/IRYHQXNnk61/H/gb2Ei+kUQ4xQ==}
@@ -4656,6 +4683,9 @@ packages:
rehype-raw@7.0.0:
resolution: {integrity: sha512-/aE8hCfKlQeA8LmyeyQvQF3eBiLRGNlfBJEvWH7ivp9sBqs7TNqBL5X3v157rM4IFETqDnIOO+z5M/biZbo9Ww==}
rehype-sanitize@6.0.0:
resolution: {integrity: sha512-CsnhKNsyI8Tub6L4sm5ZFsme4puGfc6pYylvXo1AeqaGbjOYyzNv3qZPwvs0oMJ39eryyeOdmxwUIo94IpEhqg==}
remark-gfm@4.0.1:
resolution: {integrity: sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg==}
@@ -9024,6 +9054,12 @@ snapshots:
web-namespaces: 2.0.1
zwitch: 2.0.4
hast-util-sanitize@5.0.2:
dependencies:
'@types/hast': 3.0.4
'@ungap/structured-clone': 1.3.0
unist-util-position: 5.0.0
hast-util-to-jsx-runtime@2.3.6:
dependencies:
'@types/estree': 1.0.8
@@ -10378,6 +10414,11 @@ snapshots:
hast-util-raw: 9.1.0
vfile: 6.0.3
rehype-sanitize@6.0.0:
dependencies:
'@types/hast': 3.0.4
hast-util-sanitize: 5.0.2
remark-gfm@4.0.1:
dependencies:
'@types/mdast': 4.0.4
+1 -1
View File
@@ -126,7 +126,7 @@ export const ENV = {
AUTH: {
SECRET: getEnvString('AUTH_SECRET', process.env.NODE_ENV === 'production' ? '' : generateDefaultSecret()),
TRUSTED_ORIGINS: getEnvString('AUTH_TRUSTED_ORIGINS', 'http://localhost:5173,http://localhost:5003'),
TRUSTED_ORIGINS: getEnvString('AUTH_TRUSTED_ORIGINS', 'http://localhost:5173,http://localhost:5003,http://127.0.0.1:5173,http://127.0.0.1:5003'),
SECURE_COOKIES: getEnvBoolean('AUTH_SECURE_COOKIES', getEnvString('NODE_ENV', 'development') === 'production'),
ADMIN_EMAIL: process.env.ADMIN_EMAIL,
ADMIN_PASSWORD: process.env.ADMIN_PASSWORD,