mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
Remove console.log debug statements and cleanup debug code
This commit is contained in:
1 parent
ce2630936d
commit
ac188c953b
20 files changed
+462
-220
No files matched your search
@@ -3,7 +3,7 @@ import { z } from 'zod'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { SettingsService } from '../services/settings'
|
||||
import { writeFileContent, readFileContent, fileExists } from '../services/file-operations'
|
||||
import { patchOpenCodeConfig } from '../services/proxy'
|
||||
import { patchOpenCodeConfig, proxyToOpenCodeWithDirectory } from '../services/proxy'
|
||||
import { getOpenCodeConfigFilePath, getAgentsMdPath } from '@opencode-manager/shared/config/env'
|
||||
import {
|
||||
UserPreferencesSchema,
|
||||
@@ -50,6 +50,17 @@ const ValidateGitTokenSchema = z.object({
|
||||
gitToken: z.string(),
|
||||
})
|
||||
|
||||
const ConnectMcpDirectorySchema = z.object({
|
||||
directory: z.string().min(1),
|
||||
})
|
||||
|
||||
async function extractOpenCodeError(response: Response, defaultError: string): Promise<string> {
|
||||
const errorObj = await response.json().catch(() => null)
|
||||
return (errorObj && typeof errorObj === 'object' && 'error' in errorObj)
|
||||
? String(errorObj.error)
|
||||
: defaultError
|
||||
}
|
||||
|
||||
export function createSettingsRoutes(db: Database) {
|
||||
const app = new Hono()
|
||||
const settingsService = new SettingsService(db)
|
||||
@@ -448,5 +459,114 @@ export function createSettingsRoutes(db: Database) {
|
||||
}
|
||||
})
|
||||
|
||||
// MCP directory-aware endpoints
|
||||
app.post('/mcp/:name/connectdirectory', async (c) => {
|
||||
try {
|
||||
const serverName = c.req.param('name')
|
||||
const body = await c.req.json()
|
||||
const { directory } = ConnectMcpDirectorySchema.parse(body)
|
||||
|
||||
const response = await proxyToOpenCodeWithDirectory(
|
||||
`/mcp/${encodeURIComponent(serverName)}/connect`,
|
||||
'POST',
|
||||
directory
|
||||
)
|
||||
|
||||
if (!response.ok) {
|
||||
const errorMsg = await extractOpenCodeError(response, 'Failed to connect MCP server')
|
||||
return c.json({ error: errorMsg }, 400)
|
||||
}
|
||||
|
||||
return c.json({ success: true })
|
||||
} catch (error) {
|
||||
logger.error('Failed to connect MCP server for directory:', error)
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json({ error: 'Invalid request data', details: error.issues }, 400)
|
||||
}
|
||||
return c.json({ error: 'Failed to connect MCP server' }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/mcp/:name/disconnectdirectory', async (c) => {
|
||||
try {
|
||||
const serverName = c.req.param('name')
|
||||
const body = await c.req.json()
|
||||
const { directory } = ConnectMcpDirectorySchema.parse(body)
|
||||
|
||||
const response = await proxyToOpenCodeWithDirectory(
|
||||
`/mcp/${encodeURIComponent(serverName)}/disconnect`,
|
||||
'POST',
|
||||
directory
|
||||
)
|
||||
|
||||
if (!response.ok) {
|
||||
const errorMsg = await extractOpenCodeError(response, 'Failed to disconnect MCP server')
|
||||
return c.json({ error: errorMsg }, 400)
|
||||
}
|
||||
|
||||
return c.json({ success: true })
|
||||
} catch (error) {
|
||||
logger.error('Failed to disconnect MCP server for directory:', error)
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json({ error: 'Invalid request data', details: error.issues }, 400)
|
||||
}
|
||||
return c.json({ error: 'Failed to disconnect MCP server' }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/mcp/:name/authdirectedir', async (c) => {
|
||||
try {
|
||||
const serverName = c.req.param('name')
|
||||
const body = await c.req.json()
|
||||
const { directory } = ConnectMcpDirectorySchema.parse(body)
|
||||
|
||||
const response = await proxyToOpenCodeWithDirectory(
|
||||
`/mcp/${encodeURIComponent(serverName)}/auth/authenticate`,
|
||||
'POST',
|
||||
directory
|
||||
)
|
||||
|
||||
if (!response.ok) {
|
||||
const errorMsg = await extractOpenCodeError(response, 'Failed to authenticate MCP server')
|
||||
return c.json({ error: errorMsg }, 400)
|
||||
}
|
||||
|
||||
return c.json(await response.json())
|
||||
} catch (error) {
|
||||
logger.error('Failed to authenticate MCP server for directory:', error)
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json({ error: 'Invalid request data', details: error.issues }, 400)
|
||||
}
|
||||
return c.json({ error: 'Failed to authenticate MCP server' }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.delete('/mcp/:name/authdir', async (c) => {
|
||||
try {
|
||||
const serverName = c.req.param('name')
|
||||
const body = await c.req.json()
|
||||
const { directory } = ConnectMcpDirectorySchema.parse(body)
|
||||
|
||||
const response = await proxyToOpenCodeWithDirectory(
|
||||
`/mcp/${encodeURIComponent(serverName)}/auth`,
|
||||
'DELETE',
|
||||
directory
|
||||
)
|
||||
|
||||
if (!response.ok) {
|
||||
const errorMsg = await extractOpenCodeError(response, 'Failed to remove MCP auth')
|
||||
return c.json({ error: errorMsg }, 400)
|
||||
}
|
||||
|
||||
return c.json({ success: true })
|
||||
} catch (error) {
|
||||
logger.error('Failed to remove MCP auth for directory:', error)
|
||||
if (error instanceof z.ZodError) {
|
||||
return c.json({ error: 'Invalid request data', details: error.issues }, 400)
|
||||
}
|
||||
return c.json({ error: 'Failed to remove MCP auth' }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
return app
|
||||
}
|
||||
@@ -66,3 +66,44 @@ export async function proxyRequest(request: Request) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export async function proxyToOpenCodeWithDirectory(
|
||||
path: string,
|
||||
method: string,
|
||||
directory: string | undefined,
|
||||
body?: string,
|
||||
headers?: Record<string, string>
|
||||
): Promise<Response> {
|
||||
const url = new URL(`${OPENCODE_SERVER_URL}${path}`)
|
||||
|
||||
if (directory) {
|
||||
url.searchParams.set('directory', directory)
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(url.toString(), {
|
||||
method,
|
||||
headers: headers || { 'Content-Type': 'application/json' },
|
||||
body,
|
||||
})
|
||||
|
||||
const responseHeaders: Record<string, string> = {}
|
||||
response.headers.forEach((value, key) => {
|
||||
if (!['connection', 'transfer-encoding'].includes(key.toLowerCase())) {
|
||||
responseHeaders[key] = value
|
||||
}
|
||||
})
|
||||
|
||||
return new Response(response.body, {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers: responseHeaders,
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error(`Proxy to OpenCode failed for ${path}:`, error)
|
||||
return new Response(JSON.stringify({ error: 'Proxy request failed' }), {
|
||||
status: 502,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -124,4 +124,64 @@ export const mcpApi = {
|
||||
}
|
||||
return response.json()
|
||||
},
|
||||
|
||||
async getStatusFor(directory: string): Promise<McpStatusMap> {
|
||||
const response = await fetch(`${API_BASE}/api/opencode/mcp?directory=${encodeURIComponent(directory)}`)
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to get MCP status for directory: ${response.statusText}`)
|
||||
}
|
||||
return response.json()
|
||||
},
|
||||
|
||||
async connectDirectory(name: string, directory: string): Promise<boolean> {
|
||||
const response = await fetch(`${API_BASE}/api/settings/mcp/${encodeURIComponent(name)}/connectdirectory`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ directory }),
|
||||
})
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: response.statusText }))
|
||||
throw new Error(error.error || `Failed to connect MCP server for directory: ${response.statusText}`)
|
||||
}
|
||||
return response.json()
|
||||
},
|
||||
|
||||
async disconnectDirectory(name: string, directory: string): Promise<boolean> {
|
||||
const response = await fetch(`${API_BASE}/api/settings/mcp/${encodeURIComponent(name)}/disconnectdirectory`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ directory }),
|
||||
})
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: response.statusText }))
|
||||
throw new Error(error.error || `Failed to disconnect MCP server for directory: ${response.statusText}`)
|
||||
}
|
||||
return response.json()
|
||||
},
|
||||
|
||||
async authenticateDirectory(name: string, directory: string): Promise<McpStatus> {
|
||||
const response = await fetch(`${API_BASE}/api/settings/mcp/${encodeURIComponent(name)}/authdirectedir`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ directory }),
|
||||
})
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: response.statusText }))
|
||||
throw new Error(error.error || `Failed to authenticate MCP server for directory: ${response.statusText}`)
|
||||
}
|
||||
return response.json()
|
||||
},
|
||||
|
||||
async removeAuthDirectory(name: string, directory: string): Promise<{ success: true }> {
|
||||
const response = await fetch(`${API_BASE}/api/settings/mcp/${encodeURIComponent(name)}/authdir`, {
|
||||
method: 'DELETE',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ directory }),
|
||||
})
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: response.statusText }))
|
||||
throw new Error(error.error || `Failed to remove MCP auth for directory: ${response.statusText}`)
|
||||
}
|
||||
return response.json()
|
||||
},
|
||||
}
|
||||
@@ -145,6 +145,11 @@ export class OpenCodeClient {
|
||||
return response.data
|
||||
}
|
||||
|
||||
async getSessionStatuses() {
|
||||
const response = await this.client.get<Record<string, { type: 'idle' } | { type: 'busy' } | { type: 'retry'; attempt: number; message: string; next: number }>>('/session/status')
|
||||
return response.data
|
||||
}
|
||||
|
||||
getEventSourceURL() {
|
||||
const base = this.baseURL.startsWith('http')
|
||||
? this.baseURL
|
||||
|
||||
@@ -123,6 +123,23 @@ export interface SSESessionIdleEvent {
|
||||
}
|
||||
}
|
||||
|
||||
export interface SSESessionStatusEvent {
|
||||
type: 'session.status'
|
||||
properties: {
|
||||
sessionID: string
|
||||
status: {
|
||||
type: 'idle'
|
||||
} | {
|
||||
type: 'busy'
|
||||
} | {
|
||||
type: 'retry'
|
||||
attempt: number
|
||||
message: string
|
||||
next: number
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export type SSEEvent =
|
||||
| SSEMessagePartUpdatedEvent
|
||||
| SSEMessageUpdatedEvent
|
||||
@@ -132,6 +149,7 @@ export type SSEEvent =
|
||||
| SSESessionDeletedEvent
|
||||
| SSESessionCompactedEvent
|
||||
| SSESessionIdleEvent
|
||||
| SSESessionStatusEvent
|
||||
| SSETodoUpdatedEvent
|
||||
| SSEPermissionUpdatedEvent
|
||||
| SSEPermissionRepliedEvent
|
||||
|
||||
@@ -95,7 +95,7 @@ export const EditableUserMessage = memo(function EditableUserMessage({
|
||||
<button
|
||||
onClick={onCancel}
|
||||
disabled={refreshMessage.isPending}
|
||||
className="flex items-center gap-1 px-3 py-1.5 rounded text-sm text-muted-foreground hover:text-foreground hover:bg-muted transition-colors disabled:opacity-50"
|
||||
className="flex items-center gap-1 px-3 py-1.5 rounded text-sm border border-muted-foreground/40 bg-secondary text-secondary-foreground hover:bg-secondary/80 hover:border-muted-foreground/60 transition-colors disabled:opacity-50"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
Cancel
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { memo } from 'react'
|
||||
import { X, RefreshCw, Loader2 } from 'lucide-react'
|
||||
import { useRemoveMessage, useRefreshMessage } from '@/hooks/useRemoveMessage'
|
||||
import { X, Loader2 } from 'lucide-react'
|
||||
import { useRemoveMessage } from '@/hooks/useRemoveMessage'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import type { MessageWithParts } from '@/api/types'
|
||||
|
||||
@@ -9,50 +9,22 @@ interface MessageActionButtonsProps {
|
||||
sessionId: string
|
||||
directory?: string
|
||||
message: MessageWithParts
|
||||
isLastAssistantMessage: boolean
|
||||
userMessageContent?: string
|
||||
onEditUserMessage?: () => void
|
||||
model?: string
|
||||
agent?: string
|
||||
}
|
||||
|
||||
export const MessageActionButtons = memo(function MessageActionButtons({
|
||||
opcodeUrl,
|
||||
sessionId,
|
||||
directory,
|
||||
message,
|
||||
isLastAssistantMessage,
|
||||
userMessageContent,
|
||||
onEditUserMessage,
|
||||
model,
|
||||
agent
|
||||
message
|
||||
}: MessageActionButtonsProps) {
|
||||
const isMobile = useMobile()
|
||||
const removeMessage = useRemoveMessage({ opcodeUrl, sessionId, directory })
|
||||
const refreshMessage = useRefreshMessage({ opcodeUrl, sessionId, directory })
|
||||
|
||||
const isLoading = removeMessage.isPending || refreshMessage.isPending
|
||||
|
||||
const handleRemove = () => {
|
||||
if (isLoading) return
|
||||
if (removeMessage.isPending) return
|
||||
removeMessage.mutate({ messageID: message.info.id })
|
||||
}
|
||||
|
||||
const handleRefresh = () => {
|
||||
if (isLoading || !userMessageContent) return
|
||||
|
||||
if (onEditUserMessage) {
|
||||
onEditUserMessage()
|
||||
} else {
|
||||
refreshMessage.mutate({
|
||||
assistantMessageID: message.info.id,
|
||||
userMessageContent,
|
||||
model,
|
||||
agent
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (message.info.role !== 'assistant') {
|
||||
return null
|
||||
}
|
||||
@@ -61,7 +33,7 @@ export const MessageActionButtons = memo(function MessageActionButtons({
|
||||
<div className={`flex items-center gap-1 ${isMobile ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'} transition-opacity`}>
|
||||
<button
|
||||
onClick={handleRemove}
|
||||
disabled={isLoading}
|
||||
disabled={removeMessage.isPending}
|
||||
className="p-1 rounded hover:bg-destructive/20 text-muted-foreground hover:text-destructive transition-colors disabled:opacity-50"
|
||||
title="Remove this message and all after it"
|
||||
>
|
||||
@@ -71,21 +43,6 @@ export const MessageActionButtons = memo(function MessageActionButtons({
|
||||
<X className="w-3.5 h-3.5" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
{isLastAssistantMessage && userMessageContent && (
|
||||
<button
|
||||
onClick={handleRefresh}
|
||||
disabled={isLoading}
|
||||
className="p-1 rounded hover:bg-primary/20 text-muted-foreground hover:text-primary transition-colors disabled:opacity-50"
|
||||
title="Try this prompt again"
|
||||
>
|
||||
{refreshMessage.isPending ? (
|
||||
<Loader2 className="w-3.5 h-3.5 animate-spin" />
|
||||
) : (
|
||||
<RefreshCw className="w-3.5 h-3.5" />
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -4,6 +4,7 @@ import { MessageActionButtons } from './MessageActionButtons'
|
||||
import { UserMessageActionButtons } from './UserMessageActionButtons'
|
||||
import { EditableUserMessage, ClickableUserMessage } from './EditableUserMessage'
|
||||
import type { MessageWithParts } from '@/api/types'
|
||||
import { useSessionStatusForSession } from '@/stores/sessionStatusStore'
|
||||
|
||||
function getMessageTextContent(msg: MessageWithParts): string {
|
||||
return msg.parts
|
||||
@@ -30,6 +31,10 @@ const isMessageStreaming = (msg: MessageWithParts): boolean => {
|
||||
return !('completed' in msg.info.time && msg.info.time.completed)
|
||||
}
|
||||
|
||||
function isSessionInRetry(sessionStatus: { type?: string }): boolean {
|
||||
return sessionStatus?.type === 'retry'
|
||||
}
|
||||
|
||||
const findLastMessageByRole = (
|
||||
messages: MessageWithParts[],
|
||||
role: 'user' | 'assistant',
|
||||
@@ -44,21 +49,6 @@ const findLastMessageByRole = (
|
||||
return undefined
|
||||
}
|
||||
|
||||
const findUserMessageBeforeAssistant = (
|
||||
messages: MessageWithParts[],
|
||||
assistantMessageId: string
|
||||
): string | undefined => {
|
||||
const assistantIndex = messages.findIndex(m => m.info.id === assistantMessageId)
|
||||
if (assistantIndex <= 0) return undefined
|
||||
|
||||
for (let i = assistantIndex - 1; i >= 0; i--) {
|
||||
if (messages[i].info.role === 'user') {
|
||||
return getMessageTextContent(messages[i])
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
export const MessageThread = memo(function MessageThread({
|
||||
opcodeUrl,
|
||||
sessionID,
|
||||
@@ -72,6 +62,7 @@ export const MessageThread = memo(function MessageThread({
|
||||
}: MessageThreadProps) {
|
||||
const [editingUserMessageId, setEditingUserMessageId] = useState<string | null>(null)
|
||||
const [editingForAssistantId, setEditingForAssistantId] = useState<string | null>(null)
|
||||
const sessionStatus = useSessionStatusForSession(sessionID)
|
||||
|
||||
const pendingAssistantId = useMemo(() => {
|
||||
if (!messages) return undefined
|
||||
@@ -88,7 +79,7 @@ export const MessageThread = memo(function MessageThread({
|
||||
return findLastMessageByRole(messages, 'user')
|
||||
}, [messages])
|
||||
|
||||
const isSessionBusy = !!pendingAssistantId
|
||||
const isSessionBusy = !!pendingAssistantId || isSessionInRetry(sessionStatus)
|
||||
|
||||
const handleStartEditUserMessage = useCallback((userMessageId: string, assistantMessageId: string) => {
|
||||
setEditingUserMessageId(userMessageId)
|
||||
@@ -113,7 +104,6 @@ export const MessageThread = memo(function MessageThread({
|
||||
{messages.map((msg, index) => {
|
||||
const streaming = isMessageStreaming(msg)
|
||||
const isQueued = msg.info.role === 'user' && pendingAssistantId && msg.info.id > pendingAssistantId
|
||||
const isLastAssistant = msg.info.id === lastAssistantId
|
||||
const isLastUserMessage = msg.info.role === 'user' && msg.info.id === lastUserMessageId
|
||||
const messageTextContent = getMessageTextContent(msg)
|
||||
|
||||
@@ -121,10 +111,6 @@ export const MessageThread = memo(function MessageThread({
|
||||
const isUserBeforeAssistant = msg.info.role === 'user' && nextAssistantMessage
|
||||
const canEditUserMessage = isUserBeforeAssistant && nextAssistantMessage?.info.id === lastAssistantId && !isSessionBusy
|
||||
const canUndoUserMessage = isLastUserMessage && nextAssistantMessage && !isSessionBusy && onUndoMessage
|
||||
|
||||
const userMessageContent = msg.info.role === 'assistant'
|
||||
? findUserMessageBeforeAssistant(messages, msg.info.id)
|
||||
: undefined
|
||||
|
||||
const isEditingThisMessage = editingUserMessageId === msg.info.id
|
||||
|
||||
@@ -161,22 +147,12 @@ export const MessageThread = memo(function MessageThread({
|
||||
)}
|
||||
</div>
|
||||
|
||||
{msg.info.role === 'assistant' && !streaming && !isSessionBusy && (
|
||||
{msg.info.role === 'assistant' && !streaming && !isSessionBusy && !isSessionInRetry(sessionStatus) && (
|
||||
<MessageActionButtons
|
||||
opcodeUrl={opcodeUrl}
|
||||
sessionId={sessionID}
|
||||
directory={directory}
|
||||
message={msg}
|
||||
isLastAssistantMessage={isLastAssistant}
|
||||
userMessageContent={userMessageContent}
|
||||
onEditUserMessage={userMessageContent ? () => {
|
||||
const userMsg = messages.slice(0, index).reverse().find(m => m.info.role === 'user')
|
||||
if (userMsg) {
|
||||
handleStartEditUserMessage(userMsg.info.id, msg.info.id)
|
||||
}
|
||||
} : undefined}
|
||||
model={model}
|
||||
agent={agent}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -187,10 +163,7 @@ export const MessageThread = memo(function MessageThread({
|
||||
directory={directory}
|
||||
userMessageId={msg.info.id}
|
||||
userMessageContent={messageTextContent}
|
||||
assistantMessageId={nextAssistantMessage.info.id}
|
||||
onUndo={onUndoMessage}
|
||||
model={model}
|
||||
agent={agent}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -476,8 +476,9 @@ export const PromptInput = forwardRef<PromptInputHandle, PromptInputProps>(funct
|
||||
const modeBg = currentMode === 'plan' ? 'bg-yellow-500/20 border-yellow-400 hover:bg-yellow-500/30 hover:border-yellow-300' : 'bg-green-500/20 border-green-400 hover:bg-green-500/30 hover:border-green-300'
|
||||
const modeShadow = currentMode === 'plan' ? 'shadow-yellow-500/20 hover:shadow-yellow-500/30' : 'shadow-green-500/20 hover:shadow-green-500/30'
|
||||
|
||||
const { modelString } = useModelSelection(opcodeUrl, directory)
|
||||
const { model, modelString } = useModelSelection(opcodeUrl, directory)
|
||||
const currentModel = modelString || ''
|
||||
const displayModelName = model?.modelID || currentModel
|
||||
const isMobile = useMobile()
|
||||
const sessionStatus = useSessionStatusForSession(sessionID)
|
||||
const showStopButton = hasActiveStream && (sessionStatus.type === 'busy' || sessionStatus.type === 'retry')
|
||||
@@ -538,9 +539,9 @@ export const PromptInput = forwardRef<PromptInputHandle, PromptInputProps>(funct
|
||||
!hideSecondaryButtons && (
|
||||
<button
|
||||
onClick={onShowModelsDialog}
|
||||
className="px-2.5 py-1.5 md:px-3 md:py-2 rounded-lg text-xs md:text-sm font-medium border bg-muted border-border text-muted-foreground hover:bg-muted-foreground/10 hover:border-foreground/30 transition-colors cursor-pointer max-w-[120px] md:max-w-[180px] truncate dark:border-white/30"
|
||||
className="px-2.5 py-1.5 md:px-3 md:py-2 rounded-lg text-xs md:text-sm font-medium border bg-muted border-border text-muted-foreground hover:bg-muted-foreground/10 hover:border-foreground/30 transition-colors cursor-pointer max-w-[150px] md:max-w-[220px] truncate dark:border-white/30"
|
||||
>
|
||||
{currentModel.length > 12 ? currentModel.substring(0, 10) + '...' : currentModel || 'Select model'}
|
||||
{displayModelName || 'Select model'}
|
||||
</button>
|
||||
)
|
||||
)}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { memo, useState, useEffect } from 'react'
|
||||
import { memo, useEffect, useState } from 'react'
|
||||
import type { components } from '@/api/opencode-types'
|
||||
import { RefreshCw, AlertTriangle } from 'lucide-react'
|
||||
import { useSessionStatusForSession } from '@/stores/sessionStatusStore'
|
||||
|
||||
type RetryPartType = components['schemas']['RetryPart']
|
||||
|
||||
@@ -9,17 +10,29 @@ interface RetryPartProps {
|
||||
}
|
||||
|
||||
export const RetryPart = memo(function RetryPart({ part }: RetryPartProps) {
|
||||
const [countdown, setCountdown] = useState(5)
|
||||
const sessionStatus = useSessionStatusForSession(part.sessionID)
|
||||
const nextTimestamp = sessionStatus.type === 'retry' ? sessionStatus.next : 0
|
||||
const initialCountdown = sessionStatus.type === 'retry' && nextTimestamp > 0
|
||||
? Math.max(0, Math.ceil((nextTimestamp - Date.now()) / 1000))
|
||||
: 0
|
||||
const [countdown, setCountdown] = useState(initialCountdown)
|
||||
|
||||
useEffect(() => {
|
||||
if (countdown <= 0) return
|
||||
if (sessionStatus.type !== 'retry' || nextTimestamp === 0) {
|
||||
setCountdown(0)
|
||||
return
|
||||
}
|
||||
|
||||
const timer = setInterval(() => {
|
||||
setCountdown(prev => Math.max(0, prev - 1))
|
||||
const remaining = Math.max(0, Math.ceil((nextTimestamp - Date.now()) / 1000))
|
||||
setCountdown(remaining)
|
||||
if (remaining <= 0) {
|
||||
clearInterval(timer)
|
||||
}
|
||||
}, 1000)
|
||||
|
||||
return () => clearInterval(timer)
|
||||
}, [countdown])
|
||||
}, [sessionStatus.type, nextTimestamp])
|
||||
|
||||
const errorMessage = part.error?.data?.message || 'An error occurred'
|
||||
|
||||
@@ -36,10 +49,14 @@ export const RetryPart = memo(function RetryPart({ part }: RetryPartProps) {
|
||||
<span className="text-sm font-medium text-amber-600 dark:text-amber-400">
|
||||
Retry attempt {part.attempt}
|
||||
</span>
|
||||
{countdown > 0 && (
|
||||
{countdown > 0 ? (
|
||||
<span className="text-xs text-amber-500/80">
|
||||
(retrying in {countdown}s)
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-xs text-amber-500/80">
|
||||
(retrying...)
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground truncate mt-0.5">
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { memo } from 'react'
|
||||
import { X, RefreshCw, Loader2 } from 'lucide-react'
|
||||
import { X, Loader2 } from 'lucide-react'
|
||||
import { useUndoMessage } from '@/hooks/useUndoMessage'
|
||||
import { useRefreshMessage } from '@/hooks/useRemoveMessage'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
|
||||
interface UserMessageActionButtonsProps {
|
||||
@@ -10,10 +9,7 @@ interface UserMessageActionButtonsProps {
|
||||
directory?: string
|
||||
userMessageId: string
|
||||
userMessageContent: string
|
||||
assistantMessageId: string
|
||||
onUndo: (restoredPrompt: string) => void
|
||||
model?: string
|
||||
agent?: string
|
||||
}
|
||||
|
||||
export const UserMessageActionButtons = memo(function UserMessageActionButtons({
|
||||
@@ -22,10 +18,7 @@ export const UserMessageActionButtons = memo(function UserMessageActionButtons({
|
||||
directory,
|
||||
userMessageId,
|
||||
userMessageContent,
|
||||
assistantMessageId,
|
||||
onUndo,
|
||||
model,
|
||||
agent
|
||||
onUndo
|
||||
}: UserMessageActionButtonsProps) {
|
||||
const isMobile = useMobile()
|
||||
const undoMessage = useUndoMessage({
|
||||
@@ -34,46 +27,20 @@ export const UserMessageActionButtons = memo(function UserMessageActionButtons({
|
||||
directory,
|
||||
onSuccess: onUndo
|
||||
})
|
||||
const refreshMessage = useRefreshMessage({ opcodeUrl, sessionId, directory })
|
||||
|
||||
const isLoading = undoMessage.isPending || refreshMessage.isPending
|
||||
|
||||
const handleUndo = () => {
|
||||
if (isLoading) return
|
||||
if (undoMessage.isPending) return
|
||||
undoMessage.mutate({
|
||||
messageID: userMessageId,
|
||||
messageContent: userMessageContent
|
||||
})
|
||||
}
|
||||
|
||||
const handleRefresh = () => {
|
||||
if (isLoading || !userMessageContent) return
|
||||
refreshMessage.mutate({
|
||||
assistantMessageID: assistantMessageId,
|
||||
userMessageContent,
|
||||
model,
|
||||
agent
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`flex items-center gap-1 ${isMobile ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'} transition-opacity`}>
|
||||
<button
|
||||
onClick={handleRefresh}
|
||||
disabled={isLoading}
|
||||
className="p-1 rounded hover:bg-primary/20 text-muted-foreground hover:text-primary transition-colors disabled:opacity-50"
|
||||
title="Try again for different response"
|
||||
>
|
||||
{refreshMessage.isPending ? (
|
||||
<Loader2 className="w-3.5 h-3.5 animate-spin" />
|
||||
) : (
|
||||
<RefreshCw className="w-3.5 h-3.5" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={handleUndo}
|
||||
disabled={isLoading}
|
||||
disabled={undoMessage.isPending}
|
||||
className="p-1 rounded hover:bg-destructive/20 text-muted-foreground hover:text-destructive transition-colors disabled:opacity-50"
|
||||
title="Undo this message"
|
||||
>
|
||||
|
||||
@@ -2,7 +2,7 @@ import { BackButton } from "@/components/ui/back-button";
|
||||
import { ContextUsageIndicator } from "@/components/session/ContextUsageIndicator";
|
||||
import { BranchSwitcher } from "@/components/repo/BranchSwitcher";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Loader2, Settings, FolderOpen, CornerUpLeft } from "lucide-react";
|
||||
import { Loader2, Settings, CornerUpLeft, Plug, FolderOpen } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
|
||||
interface Repo {
|
||||
@@ -28,6 +28,7 @@ interface SessionDetailHeaderProps {
|
||||
parentSessionId?: string;
|
||||
onFileBrowserOpen: () => void;
|
||||
onSettingsOpen: () => void;
|
||||
onMcpDialogOpen: () => void;
|
||||
onSessionTitleUpdate: (newTitle: string) => void;
|
||||
onParentSessionClick?: () => void;
|
||||
}
|
||||
@@ -44,6 +45,7 @@ export function SessionDetailHeader({
|
||||
parentSessionId,
|
||||
onFileBrowserOpen,
|
||||
onSettingsOpen,
|
||||
onMcpDialogOpen,
|
||||
onSessionTitleUpdate,
|
||||
onParentSessionClick,
|
||||
}: SessionDetailHeaderProps) {
|
||||
@@ -133,13 +135,13 @@ export function SessionDetailHeader({
|
||||
</form>
|
||||
) : (
|
||||
<h1
|
||||
className="text-xs sm:text-base font-semibold bg-gradient-to-r from-foreground to-muted-foreground bg-clip-text text-transparent truncate cursor-pointer hover:opacity-80 transition-opacity"
|
||||
className="text-xs text-green-500 sm:text-base font-semibold bg-gradient-to-r from-foreground to-muted-foreground bg-clip-text text-transparent truncate cursor-pointer hover:opacity-80 transition-opacity"
|
||||
onClick={handleTitleClick}
|
||||
>
|
||||
{sessionTitle}
|
||||
</h1>
|
||||
)}
|
||||
<p className="text-[10px] sm:text-xs text-muted-foreground truncate">
|
||||
<p className="text-[10px] sm:text-xs text-green-600 dark:text-green-400 truncate">
|
||||
{repoName}
|
||||
</p>
|
||||
</div>
|
||||
@@ -161,33 +163,44 @@ export function SessionDetailHeader({
|
||||
className="max-w-[80px] sm:w-[140px] sm:max-w-[140px]"
|
||||
iconOnly
|
||||
/>
|
||||
<div className="flex items-center gap-1 sm:gap-2">
|
||||
<div
|
||||
className={`w-1.5 h-1.5 sm:w-2 sm:h-2 rounded-full ${
|
||||
isConnected
|
||||
? "bg-green-500"
|
||||
: isReconnecting
|
||||
? "bg-yellow-500 animate-pulse"
|
||||
: "bg-red-500"
|
||||
}`}
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground hidden sm:inline">
|
||||
{isConnected ? "Connected" : isReconnecting ? "Reconnecting..." : "Disconnected"}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-1 sm:gap-2">
|
||||
<div
|
||||
className={`w-1.5 h-1.5 sm:w-2 sm:h-2 rounded-full ${
|
||||
isConnected
|
||||
? "bg-green-500"
|
||||
: isReconnecting
|
||||
? "bg-yellow-500 animate-pulse"
|
||||
: "bg-red-500"
|
||||
}`}
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground hidden sm:inline">
|
||||
{isConnected ? "Connected" : isReconnecting ? "Reconnecting..." : "Disconnected"}
|
||||
</span>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={onFileBrowserOpen}
|
||||
className="text-muted-foreground hover:text-foreground hover:bg-accent transition-all duration-200 h-8 w-8"
|
||||
title="Files"
|
||||
>
|
||||
<FolderOpen className="w-4 h-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={onMcpDialogOpen}
|
||||
className="text-muted-foreground hover:text-foreground hover:bg-accent transition-all duration-200 h-8 w-8"
|
||||
title="MCP Servers"
|
||||
>
|
||||
<Plug className="w-4 h-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={onSettingsOpen}
|
||||
className="text-muted-foreground hover:text-foreground hover:bg-accent transition-all duration-200 h-8 w-8"
|
||||
title="Settings"
|
||||
>
|
||||
<Settings className="w-4 h-4" />
|
||||
</Button>
|
||||
|
||||
@@ -28,7 +28,7 @@ export function AgentsMdEditor() {
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['agents-md'] })
|
||||
setHasChanges(false)
|
||||
showToast.success('AGENTS.md saved successfully')
|
||||
showToast.success('AGENTS.md saved and server restarted')
|
||||
},
|
||||
onError: () => {
|
||||
showToast.error('Failed to save AGENTS.md')
|
||||
@@ -45,7 +45,7 @@ export function AgentsMdEditor() {
|
||||
queryClient.invalidateQueries({ queryKey: ['agents-md'] })
|
||||
setContent(defaultContent)
|
||||
setHasChanges(false)
|
||||
showToast.success('AGENTS.md reset to default')
|
||||
showToast.success('AGENTS.md reset to default and server restarted')
|
||||
},
|
||||
onError: () => {
|
||||
showToast.error('Failed to reset AGENTS.md')
|
||||
|
||||
@@ -15,6 +15,7 @@ import { McpManager } from './McpManager'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { parseJsonc, hasJsoncComments } from '@/lib/jsonc'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import type { OpenCodeConfig } from '@/api/types/settings'
|
||||
|
||||
interface Command {
|
||||
@@ -68,17 +69,6 @@ export function OpenCodeConfigManager() {
|
||||
|
||||
const scrollToSection = (ref: React.RefObject<HTMLButtonElement | null>) => {
|
||||
if (ref.current) {
|
||||
const rect = ref.current.getBoundingClientRect()
|
||||
|
||||
console.log('Scroll check:', {
|
||||
section: ref.current.textContent?.trim(),
|
||||
rectTop: rect.top,
|
||||
rectBottom: rect.bottom,
|
||||
viewportHeight: window.innerHeight
|
||||
})
|
||||
|
||||
// Always scroll to ensure the section is at the top when expanded
|
||||
console.log('Scrolling to section:', ref.current.textContent?.trim())
|
||||
ref.current.scrollIntoView({
|
||||
behavior: 'smooth',
|
||||
block: 'start',
|
||||
@@ -91,13 +81,11 @@ export function OpenCodeConfigManager() {
|
||||
mutationFn: async () => {
|
||||
return await settingsApi.restartOpenCodeServer()
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
console.log('OpenCode server restarted successfully:', data.message)
|
||||
// Invalidate agents cache after server restart
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode', 'agents'] })
|
||||
},
|
||||
onError: (error) => {
|
||||
console.error('Failed to restart OpenCode server:', error)
|
||||
onError: () => {
|
||||
showToast.error('Failed to restart OpenCode server')
|
||||
},
|
||||
})
|
||||
|
||||
@@ -135,13 +123,18 @@ export function OpenCodeConfigManager() {
|
||||
// Auto-restart server if agents were modified
|
||||
const agentsChanged = JSON.stringify(previousContent?.agent) !== JSON.stringify(newContent.agent)
|
||||
if (restartServer || agentsChanged) {
|
||||
restartServerMutation.mutate()
|
||||
showToast.loading('Restarting server...', { id: 'update-restart' })
|
||||
await restartServerMutation.mutateAsync()
|
||||
showToast.success('Config updated and server restarted', { id: 'update-restart' })
|
||||
} else {
|
||||
showToast.success('Configuration updated')
|
||||
}
|
||||
|
||||
// Invalidate agents cache so @ mentions get updated
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode', 'agents'] })
|
||||
} catch (error) {
|
||||
console.error('Failed to update config:', error)
|
||||
showToast.error('Failed to update config')
|
||||
} finally {
|
||||
setIsUpdating(false)
|
||||
}
|
||||
@@ -159,6 +152,7 @@ export function OpenCodeConfigManager() {
|
||||
}, [configs, selectedConfig])
|
||||
|
||||
const createConfig = async (name: string, rawContent: string, isDefault: boolean) => {
|
||||
showToast.loading('Creating configuration...', { id: 'create-config' })
|
||||
try {
|
||||
setIsUpdating(true)
|
||||
const parsedContent = parseJsonc<Record<string, unknown>>(rawContent)
|
||||
@@ -176,10 +170,20 @@ export function OpenCodeConfigManager() {
|
||||
})
|
||||
|
||||
setIsCreateDialogOpen(false)
|
||||
fetchConfigs()
|
||||
await fetchConfigs()
|
||||
|
||||
if (isDefault) {
|
||||
showToast.loading('Restarting server...', { id: 'restart-server' })
|
||||
await restartServerMutation.mutateAsync()
|
||||
showToast.success('Configuration created and server restarted', { id: 'restart-server' })
|
||||
} else {
|
||||
showToast.success('Configuration created', { id: 'create-config' })
|
||||
}
|
||||
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode', 'agents'] })
|
||||
} catch (error) {
|
||||
console.error('Failed to create config:', error)
|
||||
showToast.error('Failed to create configuration', { id: 'create-config' })
|
||||
throw error
|
||||
} finally {
|
||||
setIsUpdating(false)
|
||||
@@ -204,12 +208,16 @@ export function OpenCodeConfigManager() {
|
||||
}
|
||||
|
||||
const setDefaultConfig = async (config: OpenCodeConfig) => {
|
||||
showToast.loading('Setting default config and restarting server...', { id: 'set-default' })
|
||||
try {
|
||||
setIsUpdating(true)
|
||||
await settingsApi.setDefaultOpenCodeConfig(config.name)
|
||||
fetchConfigs()
|
||||
await fetchConfigs()
|
||||
await restartServerMutation.mutateAsync()
|
||||
showToast.success('Default config updated and server restarted', { id: 'set-default' })
|
||||
} catch (error) {
|
||||
console.error('Failed to set default config:', error)
|
||||
showToast.error('Failed to set default config', { id: 'set-default' })
|
||||
} finally {
|
||||
setIsUpdating(false)
|
||||
}
|
||||
@@ -250,7 +258,10 @@ export function OpenCodeConfigManager() {
|
||||
<div className="flex gap-2 ">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => restartServerMutation.mutate()}
|
||||
onClick={() => {
|
||||
showToast.loading('Restarting OpenCode server...', { id: 'manual-restart' })
|
||||
restartServerMutation.mutate()
|
||||
}}
|
||||
disabled={restartServerMutation.isPending}
|
||||
>
|
||||
{restartServerMutation.isPending ? (
|
||||
@@ -349,14 +360,23 @@ export function OpenCodeConfigManager() {
|
||||
onClose={() => setIsEditDialogOpen(false)}
|
||||
onUpdate={async (rawContent) => {
|
||||
if (!editingConfig) return
|
||||
const parsedContent = parseJsonc<Record<string, unknown>>(rawContent)
|
||||
const agentsChanged = JSON.stringify(editingConfig.content.agent) !== JSON.stringify(parsedContent.agent)
|
||||
await settingsApi.updateOpenCodeConfig(editingConfig.name, { content: rawContent })
|
||||
await fetchConfigs()
|
||||
if (agentsChanged) {
|
||||
restartServerMutation.mutate()
|
||||
showToast.loading('Saving configuration...', { id: 'edit-config' })
|
||||
try {
|
||||
const parsedContent = parseJsonc<Record<string, unknown>>(rawContent)
|
||||
const agentsChanged = JSON.stringify(editingConfig.content.agent) !== JSON.stringify(parsedContent.agent)
|
||||
await settingsApi.updateOpenCodeConfig(editingConfig.name, { content: rawContent })
|
||||
await fetchConfigs()
|
||||
if (agentsChanged) {
|
||||
showToast.loading('Restarting server...', { id: 'restart-server' })
|
||||
await restartServerMutation.mutateAsync()
|
||||
showToast.success('Config updated and server restarted', { id: 'restart-server' })
|
||||
} else {
|
||||
showToast.success('Configuration saved', { id: 'edit-config' })
|
||||
}
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode', 'agents'] })
|
||||
} catch {
|
||||
showToast.error('Failed to save configuration', { id: 'edit-config' })
|
||||
}
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode', 'agents'] })
|
||||
}}
|
||||
isUpdating={isUpdating}
|
||||
/>
|
||||
@@ -427,10 +447,8 @@ export function OpenCodeConfigManager() {
|
||||
className="w-full px-4 py-3 flex items-center justify-between hover:bg-muted/50 transition-colors min-w-0"
|
||||
onClick={() => {
|
||||
const isExpanding = !expandedSections.commands
|
||||
console.log('Commands clicked, expanding:', isExpanding)
|
||||
setExpandedSections(prev => ({ ...prev, commands: isExpanding }))
|
||||
|
||||
// Only scroll when expanding, not collapsing
|
||||
if (isExpanding) {
|
||||
setTimeout(() => scrollToSection(commandsRef), 100)
|
||||
}
|
||||
@@ -466,10 +484,8 @@ export function OpenCodeConfigManager() {
|
||||
className="w-full px-4 py-3 flex items-center justify-between hover:bg-muted/50 transition-colors min-w-0"
|
||||
onClick={() => {
|
||||
const isExpanding = !expandedSections.agents
|
||||
console.log('Agents clicked, expanding:', isExpanding)
|
||||
setExpandedSections(prev => ({ ...prev, agents: isExpanding }))
|
||||
|
||||
// Only scroll when expanding, not collapsing
|
||||
if (isExpanding) {
|
||||
setTimeout(() => scrollToSection(agentsRef), 100)
|
||||
}
|
||||
@@ -505,10 +521,8 @@ export function OpenCodeConfigManager() {
|
||||
className="w-full px-4 py-3 flex items-center justify-between hover:bg-muted/50 transition-colors min-w-0"
|
||||
onClick={() => {
|
||||
const isExpanding = !expandedSections.mcp
|
||||
console.log('MCP clicked, expanding:', isExpanding)
|
||||
setExpandedSections(prev => ({ ...prev, mcp: isExpanding }))
|
||||
|
||||
// Only scroll when expanding, not collapsing
|
||||
if (isExpanding) {
|
||||
setTimeout(() => scrollToSection(mcpRef), 100)
|
||||
}
|
||||
|
||||
@@ -40,6 +40,7 @@ const DialogContent = React.forwardRef<
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Content
|
||||
ref={ref}
|
||||
aria-describedby={undefined}
|
||||
className={cn(
|
||||
"fixed left-[50%] top-[50%] z-50 grid w-[90%] max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg [&.w-screen]:left-0 [&.w-screen]:top-0 [&.w-screen]:translate-x-0 [&.w-screen]:translate-y-0",
|
||||
className
|
||||
|
||||
@@ -8,16 +8,16 @@ const Switch = React.forwardRef<
|
||||
React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<SwitchPrimitives.Root
|
||||
className={cn(
|
||||
"peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",
|
||||
className
|
||||
)}
|
||||
className={cn(
|
||||
"peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-gray-500 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-green-600 data-[state=checked]:border-green-500 data-[state=unchecked]:bg-gray-700",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
ref={ref}
|
||||
>
|
||||
<SwitchPrimitives.Thumb
|
||||
className={cn(
|
||||
"pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0"
|
||||
"pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0 disabled:bg-gray-400"
|
||||
)}
|
||||
/>
|
||||
</SwitchPrimitives.Root>
|
||||
|
||||
@@ -18,6 +18,7 @@ export function useMcpServers() {
|
||||
mcpApi.addServer(name, config),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['mcp-status'] })
|
||||
queryClient.invalidateQueries({ predicate: (query) => query.queryKey[0] === 'opencode' && (query.queryKey[1] === 'sessions' || query.queryKey[1] === 'session' || query.queryKey[1] === 'messages') })
|
||||
toast.success('MCP server added successfully')
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
@@ -29,6 +30,7 @@ export function useMcpServers() {
|
||||
mutationFn: (name: string) => mcpApi.connect(name),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['mcp-status'] })
|
||||
queryClient.invalidateQueries({ predicate: (query) => query.queryKey[0] === 'opencode' && (query.queryKey[1] === 'sessions' || query.queryKey[1] === 'session' || query.queryKey[1] === 'messages') })
|
||||
toast.success('MCP server connected')
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
@@ -40,6 +42,7 @@ export function useMcpServers() {
|
||||
mutationFn: (name: string) => mcpApi.disconnect(name),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['mcp-status'] })
|
||||
queryClient.invalidateQueries({ predicate: (query) => query.queryKey[0] === 'opencode' && (query.queryKey[1] === 'sessions' || query.queryKey[1] === 'session' || query.queryKey[1] === 'messages') })
|
||||
toast.success('MCP server disconnected')
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
@@ -70,6 +73,7 @@ export function useMcpServers() {
|
||||
mutationFn: (name: string) => mcpApi.authenticate(name),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['mcp-status'] })
|
||||
queryClient.invalidateQueries({ predicate: (query) => query.queryKey[0] === 'opencode' && (query.queryKey[1] === 'sessions' || query.queryKey[1] === 'session' || query.queryKey[1] === 'messages') })
|
||||
toast.success('Authentication completed')
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
@@ -81,6 +85,7 @@ export function useMcpServers() {
|
||||
mutationFn: (name: string) => mcpApi.removeAuth(name),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['mcp-status'] })
|
||||
queryClient.invalidateQueries({ predicate: (query) => query.queryKey[0] === 'opencode' && (query.queryKey[1] === 'sessions' || query.queryKey[1] === 'session' || query.queryKey[1] === 'messages') })
|
||||
toast.success('Authentication credentials removed')
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
|
||||
@@ -120,6 +120,13 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string)
|
||||
}
|
||||
break
|
||||
|
||||
case 'session.status': {
|
||||
if (!('sessionID' in event.properties && 'status' in event.properties)) break
|
||||
const { sessionID, status } = event.properties
|
||||
setSessionStatus(sessionID, status)
|
||||
break
|
||||
}
|
||||
|
||||
case 'message.part.updated':
|
||||
case 'messagev2.part.updated': {
|
||||
if (!('part' in event.properties)) break
|
||||
@@ -128,16 +135,6 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string)
|
||||
const sessionID = part.sessionID
|
||||
const messageID = part.messageID
|
||||
|
||||
if (part.type === 'retry') {
|
||||
const retryPart = part as { attempt: number; error: { data: { message: string } } }
|
||||
setSessionStatus(sessionID, {
|
||||
type: 'retry',
|
||||
attempt: retryPart.attempt,
|
||||
message: retryPart.error?.data?.message || 'Retrying...',
|
||||
next: Date.now() + 5000
|
||||
})
|
||||
}
|
||||
|
||||
const currentData = queryClient.getQueryData<MessageListResponse>(['opencode', 'messages', opcodeUrl, sessionID, directory])
|
||||
if (!currentData) return
|
||||
|
||||
@@ -378,11 +375,22 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string)
|
||||
const eventSource = new EventSource(eventSourceUrl)
|
||||
eventSourceRef.current = eventSource
|
||||
|
||||
eventSource.onopen = () => {
|
||||
eventSource.onopen = async () => {
|
||||
if (!mountedRef.current) return
|
||||
setIsConnected(true)
|
||||
setError(null)
|
||||
resetReconnectDelay()
|
||||
|
||||
try {
|
||||
const statuses = await client.getSessionStatuses()
|
||||
if (statuses && mountedRef.current) {
|
||||
Object.entries(statuses).forEach(([sessionID, status]) => {
|
||||
setSessionStatus(sessionID, status)
|
||||
})
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch initial session statuses:', err)
|
||||
}
|
||||
}
|
||||
|
||||
eventSource.onerror = () => {
|
||||
|
||||
@@ -6,14 +6,15 @@ import { SessionList } from "@/components/session/SessionList";
|
||||
import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet";
|
||||
import { BranchSwitcher } from "@/components/repo/BranchSwitcher";
|
||||
import { SwitchConfigDialog } from "@/components/repo/SwitchConfigDialog";
|
||||
import { RepoMcpDialog } from "@/components/repo/RepoMcpDialog";
|
||||
import { BackButton } from "@/components/ui/back-button";
|
||||
import { useCreateSession } from "@/hooks/useOpenCode";
|
||||
import { OPENCODE_API_ENDPOINT } from "@/config";
|
||||
import { OPENCODE_API_ENDPOINT, API_BASE_URL } from "@/config";
|
||||
import { useSwipeBack } from "@/hooks/useMobile";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Loader2, Plus, FolderOpen, GitBranch } from "lucide-react";
|
||||
import { Loader2, Plus, FolderOpen, GitBranch, Plug } from "lucide-react";
|
||||
|
||||
export function RepoDetail() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
@@ -22,6 +23,7 @@ export function RepoDetail() {
|
||||
const repoId = parseInt(id || "0");
|
||||
const [fileBrowserOpen, setFileBrowserOpen] = useState(false);
|
||||
const [switchConfigOpen, setSwitchConfigOpen] = useState(false);
|
||||
const [mcpDialogOpen, setMcpDialogOpen] = useState(false);
|
||||
const pageRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const handleSwipeBack = useCallback(() => {
|
||||
@@ -42,7 +44,14 @@ export function RepoDetail() {
|
||||
enabled: !!repoId,
|
||||
});
|
||||
|
||||
|
||||
const { data: settings } = useQuery({
|
||||
queryKey: ["opencode-config"],
|
||||
queryFn: async () => {
|
||||
const response = await fetch(`${API_BASE_URL}/api/settings/opencode-configs/default`);
|
||||
if (!response.ok) throw new Error("Failed to fetch config");
|
||||
return response.json();
|
||||
},
|
||||
});
|
||||
|
||||
const opcodeUrl = OPENCODE_API_ENDPOINT;
|
||||
|
||||
@@ -144,26 +153,33 @@ export function RepoDetail() {
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setFileBrowserOpen(true)}
|
||||
size="sm"
|
||||
className="text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105"
|
||||
>
|
||||
<FolderOpen className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Files</span>
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => handleCreateSession()}
|
||||
disabled={!opcodeUrl || createSessionMutation.isPending}
|
||||
variant="outline"
|
||||
onClick={() => setMcpDialogOpen(true)}
|
||||
size="sm"
|
||||
className="bg-blue-600 hover:bg-blue-700 text-white transition-all duration-200 hover:scale-105"
|
||||
className="text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105"
|
||||
>
|
||||
<Plus className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">New Session</span>
|
||||
<Plug className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">MCP</span>
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setFileBrowserOpen(true)}
|
||||
size="sm"
|
||||
className="text-foreground border-border hover:bg-accent transition-all duration-200 hover:scale-105"
|
||||
>
|
||||
<FolderOpen className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">Files</span>
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => handleCreateSession()}
|
||||
disabled={!opcodeUrl || createSessionMutation.isPending}
|
||||
size="sm"
|
||||
className="bg-blue-600 hover:bg-blue-700 text-white transition-all duration-200 hover:scale-105"
|
||||
>
|
||||
<Plus className="w-4 h-4 sm:mr-2" />
|
||||
<span className="hidden sm:inline">New Session</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -185,6 +201,13 @@ export function RepoDetail() {
|
||||
repoName={displayName}
|
||||
/>
|
||||
|
||||
<RepoMcpDialog
|
||||
open={mcpDialogOpen}
|
||||
onOpenChange={setMcpDialogOpen}
|
||||
config={settings}
|
||||
directory={repoDirectory}
|
||||
/>
|
||||
|
||||
{repo && (
|
||||
<SwitchConfigDialog
|
||||
open={switchConfigOpen}
|
||||
|
||||
@@ -12,7 +12,7 @@ import { PermissionRequestDialog } from "@/components/session/PermissionRequestD
|
||||
import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet";
|
||||
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
|
||||
import { useSession, useSessions, useAbortSession, useUpdateSession, useOpenCodeClient, useMessages } from "@/hooks/useOpenCode";
|
||||
import { OPENCODE_API_ENDPOINT } from "@/config";
|
||||
import { OPENCODE_API_ENDPOINT, API_BASE_URL } from "@/config";
|
||||
import { useSSE } from "@/hooks/useSSE";
|
||||
import { useUIState } from "@/stores/uiStateStore";
|
||||
import { useSettings } from "@/hooks/useSettings";
|
||||
@@ -28,6 +28,7 @@ import { MessageSkeleton } from "@/components/message/MessageSkeleton";
|
||||
import { exportSession, downloadMarkdown } from "@/lib/exportSession";
|
||||
import { showToast } from "@/lib/toast";
|
||||
import type { PermissionResponse } from "@/api/types";
|
||||
import { RepoMcpDialog } from "@/components/repo/RepoMcpDialog";
|
||||
|
||||
export function SessionDetail() {
|
||||
const { id, sessionId } = useParams<{ id: string; sessionId: string }>();
|
||||
@@ -40,6 +41,7 @@ export function SessionDetail() {
|
||||
const [modelDialogOpen, setModelDialogOpen] = useState(false);
|
||||
const [sessionsDialogOpen, setSessionsDialogOpen] = useState(false);
|
||||
const [fileBrowserOpen, setFileBrowserOpen] = useState(false);
|
||||
const [mcpDialogOpen, setMcpDialogOpen] = useState(false);
|
||||
const [selectedFilePath, setSelectedFilePath] = useState<string | undefined>();
|
||||
const [showScrollButton, setShowScrollButton] = useState(false);
|
||||
const [hasPromptContent, setHasPromptContent] = useState(false);
|
||||
@@ -62,6 +64,15 @@ export function SessionDetail() {
|
||||
enabled: !!repoId,
|
||||
});
|
||||
|
||||
const { data: settings } = useQuery({
|
||||
queryKey: ["opencode-config"],
|
||||
queryFn: async () => {
|
||||
const response = await fetch(`${API_BASE_URL}/api/settings/opencode-configs/default`);
|
||||
if (!response.ok) throw new Error("Failed to fetch config");
|
||||
return response.json();
|
||||
},
|
||||
});
|
||||
|
||||
const opcodeUrl = OPENCODE_API_ENDPOINT;
|
||||
const openCodeClient = useOpenCodeClient(opcodeUrl, repo?.fullPath);
|
||||
|
||||
@@ -237,6 +248,7 @@ export function SessionDetail() {
|
||||
parentSessionId={session?.parentID}
|
||||
onFileBrowserOpen={() => setFileBrowserOpen(true)}
|
||||
onSettingsOpen={openSettings}
|
||||
onMcpDialogOpen={() => setMcpDialogOpen(true)}
|
||||
onSessionTitleUpdate={handleSessionTitleUpdate}
|
||||
onParentSessionClick={handleParentSessionClick}
|
||||
/>
|
||||
@@ -348,6 +360,13 @@ export function SessionDetail() {
|
||||
initialSelectedFile={selectedFilePath}
|
||||
/>
|
||||
|
||||
<RepoMcpDialog
|
||||
open={mcpDialogOpen}
|
||||
onOpenChange={setMcpDialogOpen}
|
||||
config={settings}
|
||||
directory={repoDirectory}
|
||||
/>
|
||||
|
||||
<PermissionRequestDialog
|
||||
permission={currentPermission}
|
||||
pendingCount={pendingCount}
|
||||
|
||||
Reference in new issue
Block a user