From 3d143568c140755b3ee5aead60b40fed86353e15 Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Tue, 6 Oct 2026 19:27:49 -0400 Subject: [PATCH] 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. --- .env.example | 5 +- backend/src/db/change-walkthroughs.ts | 4 ++ backend/src/index.ts | 5 ++ backend/src/services/change-walkthroughs.ts | 22 ++++++- .../test/auth/middleware-same-site.test.ts | 7 ++- backend/test/db/change-walkthroughs.test.ts | 15 +++++ backend/test/routes/mcp-oauth-proxy.test.ts | 2 +- .../test/services/change-walkthroughs.test.ts | 59 +++++++++++++++++++ frontend/package.json | 1 + .../file-browser/MarkdownRenderer.test.tsx | 30 ++++++++++ .../file-browser/MarkdownRenderer.tsx | 5 +- .../components/message/MessagePart.test.tsx | 15 +++++ frontend/src/components/message/TextPart.tsx | 5 +- .../src/components/schedules/JobDetailTab.tsx | 4 +- .../ScheduleJobDialog.model.test.tsx | 14 +++-- .../schedules/ScheduleJobDialog.tsx | 52 ++++------------ .../schedules/ScheduleRunMarkdown.test.tsx | 26 +++++++- .../schedules/ScheduleRunMarkdown.tsx | 4 +- frontend/src/hooks/useModelSelection.ts | 15 +++-- frontend/src/hooks/useScheduleModels.ts | 12 ++-- frontend/src/lib/markdownRehypePlugins.ts | 11 ++++ .../src/lib/schedules/schedule-model.test.ts | 49 ++++++++------- frontend/src/lib/schedules/schedule-model.ts | 39 ++++++++++-- pnpm-lock.yaml | 41 +++++++++++++ shared/src/config/env.ts | 2 +- 25 files changed, 343 insertions(+), 101 deletions(-) create mode 100644 frontend/src/components/file-browser/MarkdownRenderer.test.tsx create mode 100644 frontend/src/lib/markdownRehypePlugins.ts diff --git a/.env.example b/.env.example index 5bc3d226..49cc7b85 100644 --- a/.env.example +++ b/.env.example @@ -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 diff --git a/backend/src/db/change-walkthroughs.ts b/backend/src/db/change-walkthroughs.ts index fea22de2..63baea3d 100644 --- a/backend/src/db/change-walkthroughs.ts +++ b/backend/src/db/change-walkthroughs.ts @@ -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) diff --git a/backend/src/index.ts b/backend/src/index.ts index 717c843d..4dcedd4e 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -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) => { diff --git a/backend/src/services/change-walkthroughs.ts b/backend/src/services/change-walkthroughs.ts index 0c40b1b5..9c9d70e4 100644 --- a/backend/src/services/change-walkthroughs.ts +++ b/backend/src/services/change-walkthroughs.ts @@ -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>() + private readonly deletedDuringGeneration = new Set() 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 } } diff --git a/backend/test/auth/middleware-same-site.test.ts b/backend/test/auth/middleware-same-site.test.ts index 336ec451..5fa8c67c 100644 --- a/backend/test/auth/middleware-same-site.test.ts +++ b/backend/test/auth/middleware-same-site.test.ts @@ -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', + ]) }) }) diff --git a/backend/test/db/change-walkthroughs.test.ts b/backend/test/db/change-walkthroughs.test.ts index 4fa4a3b1..25db50a9 100644 --- a/backend/test/db/change-walkthroughs.test.ts +++ b/backend/test/db/change-walkthroughs.test.ts @@ -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, diff --git a/backend/test/routes/mcp-oauth-proxy.test.ts b/backend/test/routes/mcp-oauth-proxy.test.ts index df7c2dc1..d53fcf92 100644 --- a/backend/test/routes/mcp-oauth-proxy.test.ts +++ b/backend/test/routes/mcp-oauth-proxy.test.ts @@ -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' diff --git a/backend/test/services/change-walkthroughs.test.ts b/backend/test/services/change-walkthroughs.test.ts index d3cec6e0..5f394da7 100644 --- a/backend/test/services/change-walkthroughs.test.ts +++ b/backend/test/services/change-walkthroughs.test.ts @@ -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((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() + }) + }) }) diff --git a/frontend/package.json b/frontend/package.json index ed03830f..82e3223e 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -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", diff --git a/frontend/src/components/file-browser/MarkdownRenderer.test.tsx b/frontend/src/components/file-browser/MarkdownRenderer.test.tsx new file mode 100644 index 00000000..6f244369 --- /dev/null +++ b/frontend/src/components/file-browser/MarkdownRenderer.test.tsx @@ -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() + + 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( + document.documentElement.dataset.fileProbe = 1\n\n

Logo

'} + />, + ) + + expect(container.querySelector('script')).toBeNull() + expect(document.documentElement.dataset.fileProbe).toBeUndefined() + expect(screen.getByAltText('Logo')).toHaveAttribute('src', 'docs/logo.png') + }) +}) diff --git a/frontend/src/components/file-browser/MarkdownRenderer.tsx b/frontend/src/components/file-browser/MarkdownRenderer.tsx index 35e589c7..ccfc798b 100644 --- a/frontend/src/components/file-browser/MarkdownRenderer.tsx +++ b/frontend/src/components/file-browser/MarkdownRenderer.tsx @@ -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
{content} diff --git a/frontend/src/components/message/MessagePart.test.tsx b/frontend/src/components/message/MessagePart.test.tsx index bbef9209..f704cbc4 100644 --- a/frontend/src/components/message/MessagePart.test.tsx +++ b/frontend/src/components/message/MessagePart.test.tsx @@ -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( + \n\n
NotesBody
', + )} + />, + ) + + 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() diff --git a/frontend/src/components/message/TextPart.tsx b/frontend/src/components/message/TextPart.tsx index 38d684ba..40d2e436 100644 --- a/frontend/src/components/message/TextPart.tsx +++ b/frontend/src/components/message/TextPart.tsx @@ -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) {
({ +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()), 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 { 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( (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(() => { - const configuredModels: ComboboxOption[] = [] - const configuredValues = new Set() - - 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(() => { return getPrimaryAgents(agents).map((agent) => ({ diff --git a/frontend/src/components/schedules/ScheduleRunMarkdown.test.tsx b/frontend/src/components/schedules/ScheduleRunMarkdown.test.tsx index 34d80a44..e9471488 100644 --- a/frontend/src/components/schedules/ScheduleRunMarkdown.test.tsx +++ b/frontend/src/components/schedules/ScheduleRunMarkdown.test.tsx @@ -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 = - '' + '' const { container } = render() 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( + MoreHidden body\n\nPress Enter'} />, + ) + + expect(container.querySelector('details summary')?.textContent).toBe('More') + expect(screen.getByText('Enter').tagName).toBe('KBD') + }) + + it('keeps syntax highlighting after sanitization', () => { + const { container } = render() + + 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', () => { diff --git a/frontend/src/components/schedules/ScheduleRunMarkdown.tsx b/frontend/src/components/schedules/ScheduleRunMarkdown.tsx index 7c12f3dd..9e19505e 100644 --- a/frontend/src/components/schedules/ScheduleRunMarkdown.tsx +++ b/frontend/src/components/schedules/ScheduleRunMarkdown.tsx @@ -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
{content} diff --git a/frontend/src/hooks/useModelSelection.ts b/frontend/src/hooks/useModelSelection.ts index 8cae9a99..c615a1d1 100644 --- a/frontend/src/hooks/useModelSelection.ts +++ b/frontend/src/hooks/useModelSelection.ts @@ -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, diff --git a/frontend/src/hooks/useScheduleModels.ts b/frontend/src/hooks/useScheduleModels.ts index 3a760e82..9beb45fa 100644 --- a/frontend/src/hooks/useScheduleModels.ts +++ b/frontend/src/hooks/useScheduleModels.ts @@ -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, diff --git a/frontend/src/lib/markdownRehypePlugins.ts b/frontend/src/lib/markdownRehypePlugins.ts new file mode 100644 index 00000000..2e81a113 --- /dev/null +++ b/frontend/src/lib/markdownRehypePlugins.ts @@ -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 = [rehypeRaw, rehypeSanitize, rehypeHighlight] diff --git a/frontend/src/lib/schedules/schedule-model.test.ts b/frontend/src/lib/schedules/schedule-model.test.ts index 8db8183c..84887f29 100644 --- a/frontend/src/lib/schedules/schedule-model.test.ts +++ b/frontend/src/lib/schedules/schedule-model.test.ts @@ -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): 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' }) }) }) diff --git a/frontend/src/lib/schedules/schedule-model.ts b/frontend/src/lib/schedules/schedule-model.ts index dd0381b5..04d99d8f 100644 --- a/frontend/src/lib/schedules/schedule-model.ts +++ b/frontend/src/lib/schedules/schedule-model.ts @@ -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 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( diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 294f9a94..79f558a8 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -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 diff --git a/shared/src/config/env.ts b/shared/src/config/env.ts index a2806c00..31d4e24d 100644 --- a/shared/src/config/env.ts +++ b/shared/src/config/env.ts @@ -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,