fix: update settings and skills handling with assistant redirect (#220)

* fix: enable swipe-back suspension on more drawer and remove unused variable

* refactor(frontend): improve dialog component and settings navigation

* fix: disable route swipe suspension in MoreDrawer to prevent unintended navigation

* fix(frontend): enable swipe-back suspension on more drawer route

* refactor(frontend): improve mobile navigation drawer and tab bar

* feat: add schedules service and workspace hook with navigation updates

* chore: add workspace hook, schedules library, and tests

* fix: prevent MoreDrawer sentinel from undoing navigation

* feat: per-agent model selection and UI refinements (#217)

* feat: per-agent model selection and UI refinements

- Add agentModels store with setAgentModel/getAgentModel
- PromptInput uses session model priority and stores agent model on change
- useContextUsage derives model from assistant message instead of global
- Migrate sub-agent/subtask badges from purple to blue with refined styling
- Fix MoreDrawer sentinel to skip history-back on navigation

* refactor: improve per-agent model selection and task tool call status indicators

* feat: add repo management skill and internal repos API

* fix: improve assistant session launcher and UI components

* fix: update atomic-json test assertions

* refactor: split Assistant Mode instructions between AGENTS.md and assistant.md

* loop: todo-header-mobile completed after 3 iterations (#218)

* loop: stt-perf-1 completed after 5 iterations

* fix: load audio worklet per recording context

* fix: canonicalize assistant navigation routes

* fix: adjust scroll-up threshold for header visibility

* fix: update settings and skills handling with assistant redirect

* refactor: simplify context usage indicator and extract token sum helper

* feat: add currently selected model row to popover and fix responsive truncate
This commit is contained in:
Chris Scott authored and GitHub committed 2026-05-07 18:36:03 -04:00
1 parent c7291518c8
commit 74cdeb3926
73 files changed
+4073 -632

No files matched your search

+9 -5
View File
@@ -24,13 +24,14 @@ import { useMobileTabBar } from '@/hooks/useMobileTabBar'
import { TTSProvider } from './contexts/TTSContext'
import { AuthProvider } from './contexts/AuthContext'
import { EventProvider, usePermissions, useEventContext } from '@/contexts/EventContext'
import { SwipeNavigationProvider } from '@/contexts/SwipeNavigationContext'
import { SwipeNavigationProvider, useSwipeNavigation } from '@/contexts/SwipeNavigationContext'
import { PermissionRequestDialog } from './components/session/PermissionRequestDialog'
import { SSHHostKeyDialog } from './components/ssh/SSHHostKeyDialog'
import { loginLoader, setupLoader, registerLoader, protectedLoader } from './lib/auth-loaders'
import { getSwipeBackTarget } from '@/lib/navigation'
import { useAuth } from '@/hooks/useAuth'
import { useServerHealth } from '@/hooks/useServerHealth'
import { useUIState } from '@/stores/uiStateStore'
const queryClient = new QueryClient({
defaultOptions: {
@@ -85,17 +86,19 @@ function AppShell() {
const navigate = useNavigate()
const location = useLocation()
const rootRef = useRef<HTMLDivElement>(null)
const { open: openMobileSheet, openSheet } = useMobileTabBar()
const { openSheet } = useMobileTabBar()
useTheme()
const swipeNav = useSwipeNavigation()
const getRouteSwipeBackTarget = useCallback(
() => getSwipeBackTarget(location.pathname, location.search),
[location.pathname, location.search]
)
const canSwipeBack = useCallback(
() => getRouteSwipeBackTarget() !== null,
[getRouteSwipeBackTarget]
() => !swipeNav?.isSuspended() && getRouteSwipeBackTarget() !== null,
[swipeNav, getRouteSwipeBackTarget]
)
const handleSwipeBack = useCallback(() => {
@@ -117,8 +120,9 @@ function AppShell() {
return /^\/repos\/[^/]+\/sessions\/[^/]+$/.test(location.pathname) && !openSheet
}
const setMoreDrawerOpen = useUIState((state) => state.setMoreDrawerOpen)
const { bind: bindMoreSwipe } = useRightEdgeSwipe(
() => openMobileSheet('more'),
() => setMoreDrawerOpen(true),
{
enabled: canOpenMoreWithSwipe(),
edgeWidth: 32,
+6 -3
View File
@@ -229,9 +229,12 @@ export const settingsApi = {
return fetchWrapper(`${API_BASE_URL}/api/health/version`)
},
listManagedSkills: async (repoId?: number): Promise<SkillFileInfo[]> => {
const params = repoId ? `?repoId=${repoId}` : ''
return fetchWrapper(`${API_BASE_URL}/api/settings/skills${params}`)
listManagedSkills: async (repoId?: number, directory?: string): Promise<SkillFileInfo[]> => {
const searchParams = new URLSearchParams()
if (repoId) searchParams.set('repoId', String(repoId))
if (directory) searchParams.set('directory', directory)
const query = searchParams.toString() ? `?${searchParams.toString()}` : ''
return fetchWrapper(`${API_BASE_URL}/api/settings/skills${query}`)
},
getSkill: async (name: string, scope: SkillScope, repoId?: number): Promise<SkillFileInfo> => {
+125
View File
@@ -0,0 +1,125 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { sttApi } from './stt'
describe('WAV extension selection logic', () => {
const originalFetch = global.fetch
const mockFetch = vi.fn()
beforeEach(() => {
vi.stubGlobal('fetch', mockFetch)
})
afterEach(() => {
vi.restoreAllMocks()
global.fetch = originalFetch
})
const createMockResponse = (ok = true, data = {}) => {
return new Response(JSON.stringify(data), {
status: ok ? 200 : 400,
headers: { 'Content-Type': 'application/json' },
})
}
it('should return wav for audio/wav blob', async () => {
const blob = new Blob([], { type: 'audio/wav' })
mockFetch.mockResolvedValueOnce(createMockResponse(true, { text: 'test' }))
await sttApi.transcribe(blob, 'test-user')
const callArgs = mockFetch.mock.calls[0]
const formData = callArgs[1]?.body as FormData
const audioFile = formData.get('audio') as File
expect(audioFile.name).toBe('recording.wav')
})
it('should return webm for audio/webm blob', async () => {
const blob = new Blob([], { type: 'audio/webm' })
mockFetch.mockResolvedValueOnce(createMockResponse(true, { text: 'test' }))
await sttApi.transcribe(blob, 'test-user')
const callArgs = mockFetch.mock.calls[0]
const formData = callArgs[1]?.body as FormData
const audioFile = formData.get('audio') as File
expect(audioFile.name).toBe('recording.webm')
})
it('should return ogg for audio/ogg blob', async () => {
const blob = new Blob([], { type: 'audio/ogg' })
mockFetch.mockResolvedValueOnce(createMockResponse(true, { text: 'test' }))
await sttApi.transcribe(blob, 'test-user')
const callArgs = mockFetch.mock.calls[0]
const formData = callArgs[1]?.body as FormData
const audioFile = formData.get('audio') as File
expect(audioFile.name).toBe('recording.ogg')
})
it('should return m4a for audio/mp4 blob', async () => {
const blob = new Blob([], { type: 'audio/mp4' })
mockFetch.mockResolvedValueOnce(createMockResponse(true, { text: 'test' }))
await sttApi.transcribe(blob, 'test-user')
const callArgs = mockFetch.mock.calls[0]
const formData = callArgs[1]?.body as FormData
const audioFile = formData.get('audio') as File
expect(audioFile.name).toBe('recording.m4a')
})
it('should default to wav for unknown types', async () => {
const blob = new Blob([], { type: 'audio/unknown' })
mockFetch.mockResolvedValueOnce(createMockResponse(true, { text: 'test' }))
await sttApi.transcribe(blob, 'test-user')
const callArgs = mockFetch.mock.calls[0]
const formData = callArgs[1]?.body as FormData
const audioFile = formData.get('audio') as File
expect(audioFile.name).toBe('recording.wav')
})
it('should prioritize wav over webm when both present', async () => {
const blob = new Blob([], { type: 'audio/wav;codecs=pcm' })
mockFetch.mockResolvedValueOnce(createMockResponse(true, { text: 'test' }))
await sttApi.transcribe(blob, 'test-user')
const callArgs = mockFetch.mock.calls[0]
const formData = callArgs[1]?.body as FormData
const audioFile = formData.get('audio') as File
expect(audioFile.name).toBe('recording.wav')
})
it('should include userId in request URL', async () => {
const blob = new Blob([], { type: 'audio/wav' })
mockFetch.mockResolvedValueOnce(createMockResponse(true, { text: 'test' }))
await sttApi.transcribe(blob, 'custom-user')
const callArgs = mockFetch.mock.calls[0]
const url = callArgs[0] as string
expect(url).toContain('userId=custom-user')
})
it('should send FormData with audio file', async () => {
const blob = new Blob(['audio data'], { type: 'audio/wav' })
mockFetch.mockResolvedValueOnce(createMockResponse(true, { text: 'transcribed text' }))
await sttApi.transcribe(blob, 'test-user')
expect(mockFetch).toHaveBeenCalledWith(
expect.stringContaining('/api/stt/transcribe'),
expect.objectContaining({
method: 'POST',
body: expect.any(FormData),
})
)
const callArgs = mockFetch.mock.calls[0]
const formData = callArgs[1]?.body as FormData
expect(formData.get('audio')).toBeInstanceOf(File)
})
})
+6 -3
View File
@@ -42,9 +42,12 @@ export const sttApi = {
): Promise<STTTranscribeResponse> => {
const formData = new FormData()
const extension = audioBlob.type.includes('webm') ? 'webm' :
audioBlob.type.includes('ogg') ? 'ogg' :
audioBlob.type.includes('mp4') ? 'm4a' : 'webm'
const type = audioBlob.type
const extension =
type.includes('wav') ? 'wav' :
type.includes('webm') ? 'webm' :
type.includes('ogg') ? 'ogg' :
type.includes('mp4') ? 'm4a' : 'wav'
formData.append('audio', audioBlob, `recording.${extension}`)
const urlObj = new URL(`${API_BASE_URL}/api/stt/transcribe`, window.location.origin)
@@ -177,7 +177,7 @@ export const MessagePart = memo(function MessagePart({ part, role, allParts, par
case 'subtask': {
const label = part.description || part.prompt || 'Sub-agent task'
return (
<div className="my-1 w-full rounded border border-purple-500/20 bg-purple-500/5 px-2 py-1 text-left text-xs text-muted-foreground">
<div className="my-1 w-full rounded-lg border border-blue-500/20 bg-blue-500/5 px-3 py-1.5 text-left text-xs text-muted-foreground shadow-sm shadow-blue-500/5">
<div className="flex items-center gap-2 min-w-0">
<span className="truncate">{label}</span>
<span className="ml-auto shrink-0 text-[11px] text-muted-foreground">sub-agent</span>
@@ -429,9 +429,13 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
setMentionRange(null)
}
const handleAgentChange = (agent: string) => {
setLocalMode(agent)
setStoredAgent(sessionID, agent)
const handleAgentChange = (agentName: string) => {
setLocalMode(agentName)
setStoredAgent(sessionID, agentName)
const agent = agents.find(a => a.name === agentName)
if (agent?.model) {
setStoredModel({ providerID: agent.model.providerID, modelID: agent.model.modelID })
}
}
const startVoiceRecording = async () => {
@@ -1226,10 +1230,10 @@ return (
directory={directory}
onOpenFullDialog={() => onShowModelsDialog?.()}
>
<button
className="px-2.5 py-0.5 md:px-3 min-h-[36px] 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] dark:border-white/30 flex flex-col items-start justify-center"
>
<span className="truncate w-full text-left">{displayModelName || 'Select model'}</span>
<button
className="px-2.5 py-0.5 md:px-3 min-h-[36px] min-w-0 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 w-full md:w-auto md:max-w-[220px] dark:border-white/30 flex flex-col items-start justify-center overflow-hidden"
>
<span className="truncate w-full text-left">{displayModelName || 'Select model'}</span>
{hasVariants && currentVariant && (
<span className="text-[10px] text-orange-500 truncate w-full text-center capitalize">{currentVariant}</span>
)}
@@ -0,0 +1,103 @@
import { describe, it, expect, beforeEach } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { SessionTodoDisplay } from './SessionTodoDisplay'
import { useSessionTodos } from '@/stores/sessionTodosStore'
import type { Todo } from './SessionTodoDisplay'
const activeTodos: Todo[] = [
{ id: '1', content: 'Implement mobile header fix', status: 'in_progress', priority: 'high' },
{ id: '2', content: 'Add regression tests', status: 'pending', priority: 'medium' },
{ id: '3', content: 'Verify completed item grouping', status: 'completed', priority: 'low' },
]
const allCompletedTodos: Todo[] = [
{ id: '1', content: 'Task one', status: 'completed', priority: 'high' },
{ id: '2', content: 'Task two', status: 'completed', priority: 'medium' },
]
describe('SessionTodoDisplay', () => {
beforeEach(() => {
useSessionTodos.setState({ todos: new Map() })
})
it('renders collapsed by default', () => {
useSessionTodos.getState().setTodos('session-1', activeTodos)
render(<SessionTodoDisplay sessionID="session-1" />)
expect(screen.getByText('Tasks: 1/3 complete')).toBeInTheDocument()
expect(screen.queryByText('Implement mobile header fix')).not.toBeInTheDocument()
expect(screen.queryByText('Add regression tests')).not.toBeInTheDocument()
})
it('expands to show a small scrollable task preview when clicked', async () => {
const user = userEvent.setup()
useSessionTodos.getState().setTodos('session-1', activeTodos)
render(<SessionTodoDisplay sessionID="session-1" />)
const collapsedRow = screen.getByText('Tasks: 1/3 complete')
await user.click(collapsedRow)
expect(screen.getByText('Implement mobile header fix')).toBeInTheDocument()
expect(screen.getByText('Add regression tests')).toBeInTheDocument()
expect(screen.getByText('Verify completed item grouping')).toBeInTheDocument()
const expandedContainer = screen.getByTestId('todo-expanded-list')
expect(expandedContainer).toHaveClass('max-h-[80px]')
expect(expandedContainer).toHaveClass('sm:max-h-[160px]')
expect(expandedContainer).toHaveClass('overflow-y-auto')
})
it('collapses again when expanded header is clicked', async () => {
const user = userEvent.setup()
useSessionTodos.getState().setTodos('session-1', activeTodos)
render(<SessionTodoDisplay sessionID="session-1" />)
const collapsedRow = screen.getByText('Tasks: 1/3 complete')
await user.click(collapsedRow)
expect(screen.getByTestId('todo-expanded-list')).toBeInTheDocument()
const expandedHeader = screen.getByText('Tasks: 1/3 complete')
await user.click(expandedHeader)
expect(screen.queryByTestId('todo-expanded-list')).not.toBeInTheDocument()
})
it('does not render when all tasks are completed', () => {
useSessionTodos.getState().setTodos('session-1', allCompletedTodos)
const { container } = render(<SessionTodoDisplay sessionID="session-1" />)
expect(container.firstChild).toBeNull()
})
it('dismisses current todo signature and reappears when todo status changes', async () => {
const user = userEvent.setup()
useSessionTodos.getState().setTodos('session-1', activeTodos)
const { rerender } = render(<SessionTodoDisplay sessionID="session-1" />)
expect(screen.getByText('Tasks: 1/3 complete')).toBeInTheDocument()
const dismissButton = screen.getByLabelText('Dismiss tasks')
await user.click(dismissButton)
expect(screen.queryByText('Tasks: 1/3 complete')).not.toBeInTheDocument()
const updatedTodos: Todo[] = [
{ id: '1', content: 'Implement mobile header fix', status: 'completed', priority: 'high' },
{ id: '2', content: 'Add regression tests', status: 'pending', priority: 'medium' },
{ id: '3', content: 'Verify completed item grouping', status: 'completed', priority: 'low' },
]
useSessionTodos.getState().setTodos('session-1', updatedTodos)
rerender(<SessionTodoDisplay sessionID="session-1" />)
expect(screen.getByText('Tasks: 2/3 complete')).toBeInTheDocument()
})
})
@@ -15,7 +15,7 @@ const todoSignature = (todos: Todo[]) =>
export function SessionTodoDisplay({ sessionID }: SessionTodoDisplayProps) {
const todos = useSessionTodosForSession(sessionID)
const [isCollapsed, setIsCollapsed] = useState(false)
const [isCollapsed, setIsCollapsed] = useState(true)
const [isDismissed, setIsDismissed] = useState(false)
const dismissedSignatureRef = useRef<string>('')
@@ -129,7 +129,7 @@ export function SessionTodoDisplay({ sessionID }: SessionTodoDisplayProps) {
<X className="w-3.5 h-3.5" />
</button>
</div>
<div className="max-h-[80px] sm:max-h-[160px] overflow-y-auto p-1.5 sm:p-2 bg-muted/30">
<div data-testid="todo-expanded-list" className="max-h-[80px] sm:max-h-[160px] overflow-y-auto p-1.5 sm:p-2 bg-muted/30">
{renderGroup('In Progress', inProgress)}
{renderGroup('Pending', pending)}
{renderGroup('Completed', completedTodos)}
@@ -2,6 +2,7 @@ import { useState, useRef, useEffect } from 'react'
import type { components } from '@/api/opencode-types'
import { useSettings } from '@/hooks/useSettings'
import { useUserBash } from '@/stores/userBashStore'
import { useSessionStatusForSession } from '@/stores/sessionStatusStore'
import { usePermissions, useQuestions } from '@/contexts/EventContext'
import { detectFileReferences } from '@/lib/fileReferences'
import { ExternalLink, Loader2 } from 'lucide-react'
@@ -68,6 +69,8 @@ function ClickableJson({ json, onFileClick }: { json: unknown; onFileClick?: (fi
export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCallPartProps) {
const { preferences } = useSettings()
const { userBashCommands } = useUserBash()
const taskSessionId = part.tool === 'task' ? getTaskSessionId(part) : undefined
const taskSessionStatus = useSessionStatusForSession(taskSessionId)
const { getForCallID: getPermissionForCallID } = usePermissions()
const { getForCallID: getQuestionForCallID } = useQuestions()
const outputRef = useRef<HTMLDivElement>(null)
@@ -152,17 +155,36 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal
const isFileTool = ['read', 'write', 'edit'].includes(part.tool)
if (part.tool === 'task') {
const sessionId = getTaskSessionId(part)
const sessionId = taskSessionId
const description = previewText || 'Sub-agent task'
const isRunning = part.state.status === 'running' || part.state.status === 'pending'
const status = part.state.status
const isPending = status === 'pending'
const isRunning = status === 'running' && taskSessionStatus.type !== 'idle'
const isCompleted = status === 'completed' || (status === 'running' && !!sessionId && taskSessionStatus.type === 'idle')
const isError = status === 'error'
const content = (
<div className="flex items-center gap-2 min-w-0">
{isRunning ? (
<Loader2 className="w-3.5 h-3.5 animate-spin text-purple-600 dark:text-purple-400" />
) : null}
{isPending && (
<div className="flex gap-1">
<span className="w-2 h-2 rounded-full bg-muted-foreground" />
<span className="w-2 h-2 rounded-full bg-muted-foreground" />
<span className="w-2 h-2 rounded-full bg-muted-foreground" />
</div>
)}
{isRunning && (
<div className="flex gap-1">
<span className="w-2.5 h-2.5 rounded-full bg-blue-500 animate-bounce" style={{ animationDelay: '0ms' }} />
<span className="w-2.5 h-2.5 rounded-full bg-blue-500 animate-bounce" style={{ animationDelay: '150ms' }} />
<span className="w-2.5 h-2.5 rounded-full bg-blue-500 animate-bounce" style={{ animationDelay: '300ms' }} />
</div>
)}
{isCompleted && <span className="text-green-600 text-sm font-medium">✓</span>}
{isError && <span className="text-red-600 text-sm font-medium">✗</span>}
<span className="font-medium text-foreground truncate">{description}</span>
<span className="text-[11px] text-muted-foreground ml-auto shrink-0">sub-agent</span>
{sessionId && <ExternalLink className="w-3 h-3 shrink-0 text-purple-600 dark:text-purple-400" />}
<span className="text-[11px] font-medium text-orange-600 dark:text-orange-400 shrink-0">sub-agent</span>
{sessionId && <ExternalLink className="w-3 h-3 shrink-0 text-blue-600 dark:text-blue-400" />}
</div>
)
@@ -170,7 +192,7 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal
return (
<button
onClick={() => onChildSessionClick?.(sessionId)}
className="my-1 w-full rounded border border-purple-500/20 bg-purple-500/5 px-2 py-1 text-left text-xs text-muted-foreground hover:bg-purple-500/10 transition-colors"
className="my-1 w-full rounded-lg border border-blue-500/20 bg-blue-500/5 px-3 py-1.5 text-left text-xs text-muted-foreground hover:bg-blue-500/10 hover:border-blue-500/30 transition-all duration-200 shadow-sm shadow-blue-500/5"
title="View subagent session"
>
{content}
@@ -179,7 +201,7 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal
}
return (
<div className="my-1 rounded border border-purple-500/20 bg-purple-500/5 px-2 py-1 text-xs text-muted-foreground">
<div className="my-1 rounded-lg border border-blue-500/20 bg-blue-500/5 px-3 py-1.5 text-xs text-muted-foreground shadow-sm shadow-blue-500/5">
{content}
</div>
)
@@ -278,7 +300,7 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal
e.stopPropagation()
onChildSessionClick?.(sessionId)
}}
className="text-purple-600 dark:text-purple-400 text-xs hover:text-purple-700 dark:hover:text-purple-300 cursor-pointer underline decoration-dotted flex items-center gap-1"
className="text-blue-600 dark:text-blue-400 text-xs hover:text-blue-700 dark:hover:text-blue-300 cursor-pointer underline decoration-dotted flex items-center gap-1"
title="View subagent session"
>
<ExternalLink className="w-3 h-3" />
@@ -103,6 +103,8 @@ export function ModelQuickSelect({
toggleFavorite(model)
}
const currentModelDisplayName = model ? getDisplayName(model.providerID, model.modelID) : ''
const currentProviderName = model ? getProviderName(model.providerID) : ''
const isCurrentFavorite = model
? favoriteModels.some((favorite) => favorite.providerID === model.providerID && favorite.modelID === model.modelID)
: false
@@ -116,13 +118,23 @@ export function ModelQuickSelect({
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-56">
{model && (
<DropdownMenuItem
onClick={handleCurrentFavoriteToggle}
className="flex items-center justify-between"
>
<span>{isCurrentFavorite ? 'Remove from favorites' : 'Add to favorites'}</span>
<Star className={`h-4 w-4 ${isCurrentFavorite ? 'fill-yellow-400 text-yellow-400' : ''}`} />
</DropdownMenuItem>
<>
<DropdownMenuItem className="flex items-center justify-between font-medium">
<span className="truncate">
{duplicateDisplayNames.has(currentModelDisplayName)
? `${currentProviderName}/${currentModelDisplayName}`
: currentModelDisplayName}
</span>
<Check className="h-4 w-4" />
</DropdownMenuItem>
<DropdownMenuItem
onClick={handleCurrentFavoriteToggle}
className="flex items-center justify-between"
>
<span>{isCurrentFavorite ? 'Remove from favorites' : 'Add to favorites'}</span>
<Star className={`h-4 w-4 ${isCurrentFavorite ? 'fill-yellow-400 text-yellow-400' : ''}`} />
</DropdownMenuItem>
</>
)}
{hasVariants && (
@@ -27,6 +27,7 @@ import { MemoryRouter } from 'react-router-dom'
import { MobileSheetHost } from './MobileSheetHost'
import { useMobile } from '@/hooks/useMobile'
import { useMobileTabBar } from '@/hooks/useMobileTabBar'
import { useUIState } from '@/stores/uiStateStore'
describe('MobileSheetHost', () => {
beforeEach(() => {
@@ -103,18 +104,15 @@ describe('MobileSheetHost', () => {
expect(screen.getByTestId('notifications-sheet')).toBeInTheDocument()
})
it('renders MoreDrawer when mobileTab=more', () => {
vi.mocked(useMobileTabBar).mockReturnValue({
openSheet: 'more',
open: vi.fn(),
close: vi.fn(),
})
it('renders MoreDrawer when isMoreDrawerOpen is true', () => {
useUIState.setState({ isMoreDrawerOpen: true })
render(
<MemoryRouter initialEntries={['/?mobileTab=more']}>
<MemoryRouter initialEntries={['/']}>
<MobileSheetHost />
</MemoryRouter>,
)
expect(screen.getByTestId('more-drawer')).toBeInTheDocument()
useUIState.setState({ isMoreDrawerOpen: false })
})
it('closes sheet when onClose is called', () => {
@@ -4,10 +4,13 @@ import { FileBrowserSheet } from '@/components/file-browser/FileBrowserSheet'
import { RepoQuickSwitchSheet } from '@/components/navigation/RepoQuickSwitchSheet'
import { NotificationsSheet } from '@/components/navigation/NotificationsSheet'
import { MoreDrawer } from '@/components/navigation/MoreDrawer'
import { useUIState } from '@/stores/uiStateStore'
export function MobileSheetHost() {
const isMobile = useMobile()
const { openSheet, close } = useMobileTabBar()
const isMoreDrawerOpen = useUIState((state) => state.isMoreDrawerOpen)
const setMoreDrawerOpen = useUIState((state) => state.setMoreDrawerOpen)
if (!isMobile) return null
@@ -24,7 +27,7 @@ export function MobileSheetHost() {
/>
)}
{openSheet === 'notifications' && <NotificationsSheet isOpen onClose={close} />}
{openSheet === 'more' && <MoreDrawer isOpen onClose={close} />}
<MoreDrawer isOpen={isMoreDrawerOpen} onClose={() => setMoreDrawerOpen(false)} />
</>
)
}
@@ -67,7 +67,7 @@ describe('MobileTabBar', () => {
const queryClient = new QueryClient()
render(
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={['/repos/123/assistant?view=sessions']}>
<MemoryRouter initialEntries={['/assistant?view=sessions']}>
<MobileTabBar />
</MemoryRouter>
</QueryClientProvider>,
@@ -77,7 +77,7 @@ describe('MobileTabBar', () => {
expect(screen.getByText('Schedules')).toBeInTheDocument()
})
it('navigates to assistant route when repo id is present', async () => {
it('navigates to /assistant when assistant is clicked from repo context', async () => {
vi.mocked(useMobile).mockReturnValue(true)
const queryClient = new QueryClient()
const user = userEvent.setup()
@@ -96,7 +96,7 @@ describe('MobileTabBar', () => {
)
await user.click(screen.getByRole('button', { name: 'Assistant' }))
expect(screen.getByTestId('location')).toHaveTextContent('/repos/123/assistant')
expect(screen.getByTestId('location')).toHaveTextContent('/assistant')
})
it('navigates to assistant route when assistant is clicked without repo id', async () => {
@@ -4,6 +4,8 @@ import { FolderGit2, FolderOpen, CalendarClock, Menu, Info, History, Bot } from
import { cn } from '@/lib/utils'
import { useMobile } from '@/hooks/useMobile'
import { useMobileTabBar, useScheduleTab, type ScheduleTabKey } from '@/hooks/useMobileTabBar'
import { useUIState } from '@/stores/uiStateStore'
import { getAssistantPath, isAssistantPath } from '@/lib/navigation'
interface TabDef {
key: string
@@ -23,6 +25,8 @@ interface GlobalTabsArgs {
navigate: ReturnType<typeof useNavigate>
isInsideRepo: boolean
repoId: string | null
isMoreDrawerOpen: boolean
setMoreDrawerOpen: (open: boolean) => void
}
type TabBarMode = 'hidden' | 'global' | 'schedule'
@@ -34,11 +38,15 @@ interface MobileTabRouteState {
}
function getMobileTabRouteState(pathname: string): MobileTabRouteState {
if (isAssistantPath(pathname)) {
return { mode: 'global', isInsideRepo: false, repoId: null }
}
const repoMatch = pathname.match(/^\/repos\/(\d+)(?:\/([^/]+))?/)
const repoId = repoMatch?.[1] ?? null
const repoSection = repoMatch?.[2]
if (pathname === '/' || pathname === '/schedules' || pathname === '/assistant') {
if (pathname === '/' || pathname === '/schedules') {
return { mode: 'global', isInsideRepo: false, repoId: null }
}
@@ -48,7 +56,6 @@ function getMobileTabRouteState(pathname: string): MobileTabRouteState {
switch (repoSection) {
case undefined:
case 'assistant':
return { mode: 'global', isInsideRepo: true, repoId }
case 'schedules':
return { mode: 'schedule', isInsideRepo: true, repoId }
@@ -57,7 +64,7 @@ function getMobileTabRouteState(pathname: string): MobileTabRouteState {
}
}
function buildGlobalTabs({ pathname, search, openSheet, open, close, navigate, isInsideRepo, repoId }: GlobalTabsArgs): TabDef[] {
function buildGlobalTabs({ pathname, search, openSheet, open, close, navigate, isInsideRepo, repoId, isMoreDrawerOpen, setMoreDrawerOpen }: GlobalTabsArgs): TabDef[] {
const navigateWithSearch = (params: URLSearchParams) => {
const nextSearch = params.toString()
navigate(nextSearch ? `${pathname}?${nextSearch}` : pathname, { replace: true })
@@ -74,14 +81,8 @@ function buildGlobalTabs({ pathname, search, openSheet, open, close, navigate, i
}
const handleAssistantClick = () => {
if (repoId) {
close()
navigate(`/repos/${repoId}/assistant`)
return
}
close()
navigate('/assistant')
navigate(getAssistantPath())
}
return [
@@ -104,7 +105,7 @@ function buildGlobalTabs({ pathname, search, openSheet, open, close, navigate, i
label: 'Assistant',
icon: Bot,
onClick: handleAssistantClick,
active: isInsideRepo && pathname === `/repos/${repoId}/assistant` && !openSheet,
active: isAssistantPath(pathname) && !openSheet,
},
{
key: 'schedules',
@@ -117,8 +118,8 @@ function buildGlobalTabs({ pathname, search, openSheet, open, close, navigate, i
key: 'more',
label: 'More',
icon: Menu,
onClick: () => open('more'),
active: openSheet === 'more',
onClick: () => setMoreDrawerOpen(true),
active: isMoreDrawerOpen,
},
]
}
@@ -190,6 +191,8 @@ export const MobileTabBar = memo(function MobileTabBar() {
const { openSheet, open, close } = useMobileTabBar()
const { scheduleTab, setScheduleTab } = useScheduleTab()
const isMobile = useMobile()
const isMoreDrawerOpen = useUIState((state) => state.isMoreDrawerOpen)
const setMoreDrawerOpen = useUIState((state) => state.setMoreDrawerOpen)
const routeState = useMemo(() => getMobileTabRouteState(pathname), [pathname])
const tabs = useMemo<TabDef[]>(
@@ -204,6 +207,8 @@ export const MobileTabBar = memo(function MobileTabBar() {
navigate,
isInsideRepo: routeState.isInsideRepo,
repoId: routeState.repoId,
isMoreDrawerOpen,
setMoreDrawerOpen,
})),
[
routeState,
@@ -215,6 +220,8 @@ export const MobileTabBar = memo(function MobileTabBar() {
open,
close,
navigate,
isMoreDrawerOpen,
setMoreDrawerOpen,
],
)
@@ -240,4 +240,14 @@ describe('MoreDrawer', () => {
expect(screen.queryByText('wrong-repo')).not.toBeInTheDocument()
})
it('shows Assistant instead of the source repo on canonical /assistant route', () => {
mockAuth()
mockServerHealth()
const handleClose = vi.fn()
renderMoreDrawer({ initialEntry: '/assistant', routePath: '/assistant', onClose: handleClose })
expect(screen.getByText('Assistant')).toBeInTheDocument()
expect(screen.queryByText('wrong-repo')).not.toBeInTheDocument()
})
})
+126 -86
View File
@@ -13,6 +13,7 @@ import { FileBrowserSheet } from '@/components/file-browser/FileBrowserSheet'
import { buildMoreItems } from './moreDrawerItems'
import { useSwipeBack } from '@/hooks/useMobile'
import { getRepoDisplayName } from '@/lib/utils'
import { isAssistantPath } from '@/lib/navigation'
import type { components } from '@/api/opencode-types'
type CommandType = components['schemas']['Command']
@@ -30,11 +31,12 @@ export function MoreDrawer({ isOpen, onClose }: MoreDrawerProps) {
const [commandsOpen, setCommandsOpen] = useState(false)
const [mentionFileBrowserOpen, setMentionFileBrowserOpen] = useState(false)
const swipeRef = useRef<HTMLDivElement>(null)
const { bind } = useSwipeBack(onClose, { enabled: true, suspendsRouteSwipe: true })
const skipHistoryBackOnCloseRef = useRef(false)
const { bind } = useSwipeBack(onClose, { enabled: isOpen, suspendsRouteSwipe: true })
const { logout } = useAuth()
const { data: health } = useServerHealth()
const isSessionDetail = /^\/repos\/\d+\/sessions\/[^/]+$/.test(location.pathname)
const isAssistantRoute = /^\/repos\/\d+\/assistant$/.test(location.pathname)
const isAssistantRoute = isAssistantPath(location.pathname)
const isAssistantSession = isSessionDetail && new URLSearchParams(location.search).get('assistant') === '1'
const { filterCommands } = useCommands(isSessionDetail ? OPENCODE_API_ENDPOINT : null)
const activePromptFileBasePath = useUIState((state) => state.activePromptFileBasePath)
@@ -48,6 +50,37 @@ export function MoreDrawer({ isOpen, onClose }: MoreDrawerProps) {
}
}, [isOpen, bind])
const onCloseRef = useRef(onClose)
useEffect(() => {
onCloseRef.current = onClose
}, [onClose])
useEffect(() => {
if (!isOpen) return
skipHistoryBackOnCloseRef.current = false
let sentinelActive = true
const baseState = window.history.state
const baseUrl = window.location.href
window.history.pushState({ ...(baseState ?? {}), moreDrawerSentinel: true }, '', baseUrl)
const onPop = () => {
if (!sentinelActive) return
sentinelActive = false
onCloseRef.current()
}
window.addEventListener('popstate', onPop)
return () => {
window.removeEventListener('popstate', onPop)
// Only go back if sentinel is still active AND we haven't navigated away
if (sentinelActive && !skipHistoryBackOnCloseRef.current) {
sentinelActive = false
const top = window.history.state as { moreDrawerSentinel?: boolean } | null
if (top?.moreDrawerSentinel && window.location.href === baseUrl) {
window.history.back()
}
}
}
}, [isOpen])
const { data: repo } = useQuery({
queryKey: ['repo', repoId],
queryFn: () => repoId ? getRepo(repoId) : null,
@@ -64,7 +97,9 @@ export function MoreDrawer({ isOpen, onClose }: MoreDrawerProps) {
newParams.delete('mobileTab')
newParams.set('settings', 'open')
newParams.set('tab', 'account')
skipHistoryBackOnCloseRef.current = true
navigate({ search: newParams.toString() }, { replace: true })
onClose()
}
const handleLogoutClick = async () => {
@@ -77,13 +112,16 @@ export function MoreDrawer({ isOpen, onClose }: MoreDrawerProps) {
const handleItemClick = (item: ReturnType<typeof buildMoreItems>[0]) => {
if (item.to) {
skipHistoryBackOnCloseRef.current = true
navigate(item.to)
} else if (item.dialog) {
const newParams = new URLSearchParams(location.search)
newParams.set('dialog', item.dialog)
newParams.delete('mobileTab')
skipHistoryBackOnCloseRef.current = true
navigate({ search: newParams.toString() }, { replace: true })
}
onClose()
}
const handleCommandClick = (command: CommandType) => {
@@ -121,100 +159,102 @@ export function MoreDrawer({ isOpen, onClose }: MoreDrawerProps) {
return (
<SideDrawer isOpen={isOpen} onClose={onClose} side="right" ariaLabel="More" widthClass="w-screen sm:w-[min(90vw,420px)]">
<div ref={swipeRef} className="flex flex-col flex-shrink-0 border-b border-border bg-background px-4 py-1.5">
<div className="flex items-center justify-between gap-3 mb-2">
{versionLabel && (
<span className="truncate text-xs leading-tight text-muted-foreground">{versionLabel}</span>
)}
<button
type="button"
onClick={onClose}
className="shrink-0 rounded-sm p-2 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
aria-label="Close"
>
<X className="h-5 w-5" />
</button>
</div>
{(repoDisplayName || currentBranch) && (
<div className="flex items-center gap-2 text-xs text-muted-foreground">
{repoDisplayName && (
<span className="font-medium text-orange-600 dark:text-orange-400">{repoDisplayName}</span>
<div ref={swipeRef} className="flex flex-col flex-1 min-h-0">
<div className="flex flex-col flex-shrink-0 border-b border-border bg-background px-4 py-1.5">
<div className="flex items-center justify-between gap-3 mb-2">
{versionLabel && (
<span className="truncate text-xs leading-tight text-muted-foreground">{versionLabel}</span>
)}
{currentBranch && (
<>
<GitBranch className="h-3.5 w-3.5" />
<span>{currentBranch}</span>
</>
)}
</div>
)}
</div>
<SideDrawerContent className="flex flex-col gap-1">
{isSessionDetail && (
<div className="flex flex-col gap-1">
<button
type="button"
onClick={() => setCommandsOpen((open) => !open)}
className="flex items-center gap-3 p-3 rounded-lg hover:bg-accent transition-colors text-left w-full"
aria-expanded={commandsOpen}
onClick={onClose}
className="shrink-0 rounded-sm p-2 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
aria-label="Close"
>
<CommandIcon className="w-5 h-5 text-muted-foreground" />
<span className="font-medium text-foreground flex-1">Commands</span>
{commandsOpen ? (
<ChevronDown className="w-4 h-4 text-muted-foreground" />
) : (
<ChevronRight className="w-4 h-4 text-muted-foreground" />
<X className="h-5 w-5" />
</button>
</div>
{(repoDisplayName || currentBranch) && (
<div className="flex items-center gap-2 text-xs text-muted-foreground">
{repoDisplayName && (
<span className="font-medium text-orange-600 dark:text-orange-400">{repoDisplayName}</span>
)}
</button>
{commandsOpen && (
<div className="-mx-4 max-h-64 overflow-y-auto border-y border-border bg-muted/30 p-1 sm:mx-0 sm:rounded-lg sm:border">
{commands.map((command) => (
<button
key={command.name}
type="button"
onClick={() => handleCommandClick(command)}
className="flex w-full min-w-0 items-start gap-3 rounded-md px-3 py-2 text-left transition-colors hover:bg-accent"
>
<span className="font-mono text-sm font-medium text-blue-600 dark:text-blue-400">{command.name}</span>
{command.description && (
<span className="min-w-0 flex-1 truncate text-xs text-muted-foreground">{command.description}</span>
)}
</button>
))}
</div>
)}
{currentBranch && (
<>
<GitBranch className="h-3.5 w-3.5" />
<span>{currentBranch}</span>
</>
)}
</div>
)}
</div>
<SideDrawerContent className="flex flex-col gap-1">
{isSessionDetail && (
<div className="flex flex-col gap-1">
<button
type="button"
onClick={() => setCommandsOpen((open) => !open)}
className="flex items-center gap-3 p-3 rounded-lg hover:bg-accent transition-colors text-left w-full"
aria-expanded={commandsOpen}
>
<CommandIcon className="w-5 h-5 text-muted-foreground" />
<span className="font-medium text-foreground flex-1">Commands</span>
{commandsOpen ? (
<ChevronDown className="w-4 h-4 text-muted-foreground" />
) : (
<ChevronRight className="w-4 h-4 text-muted-foreground" />
)}
</button>
{commandsOpen && (
<div className="-mx-4 max-h-64 overflow-y-auto border-y border-border bg-muted/30 p-1 sm:mx-0 sm:rounded-lg sm:border">
{commands.map((command) => (
<button
key={command.name}
type="button"
onClick={() => handleCommandClick(command)}
className="flex w-full min-w-0 items-start gap-3 rounded-md px-3 py-2 text-left transition-colors hover:bg-accent"
>
<span className="font-mono text-sm font-medium text-blue-600 dark:text-blue-400">{command.name}</span>
{command.description && (
<span className="min-w-0 flex-1 truncate text-xs text-muted-foreground">{command.description}</span>
)}
</button>
))}
</div>
)}
<button
type="button"
onClick={() => setMentionFileBrowserOpen(true)}
className="flex items-center gap-3 p-3 rounded-lg hover:bg-accent transition-colors text-left w-full"
>
<FileText className="w-5 h-5 text-muted-foreground" />
<span className="font-medium text-foreground flex-1">Mention File</span>
<ChevronRight className="w-4 h-4 text-muted-foreground" />
</button>
</div>
)}
{items.map((item) => (
<button
key={item.key}
type="button"
onClick={() => setMentionFileBrowserOpen(true)}
onClick={() => {
if (item.key === 'settings') {
handleSettingsClick()
} else if (item.key === 'logout') {
handleLogoutClick()
} else {
handleItemClick(item)
}
}}
className="flex items-center gap-3 p-3 rounded-lg hover:bg-accent transition-colors text-left w-full"
>
<FileText className="w-5 h-5 text-muted-foreground" />
<span className="font-medium text-foreground flex-1">Mention File</span>
<ChevronRight className="w-4 h-4 text-muted-foreground" />
<item.icon className="w-5 h-5 text-muted-foreground" />
<span className="font-medium text-foreground">{item.label}</span>
</button>
</div>
)}
{items.map((item) => (
<button
key={item.key}
type="button"
onClick={() => {
if (item.key === 'settings') {
handleSettingsClick()
} else if (item.key === 'logout') {
handleLogoutClick()
} else {
handleItemClick(item)
}
}}
className="flex items-center gap-3 p-3 rounded-lg hover:bg-accent transition-colors text-left w-full"
>
<item.icon className="w-5 h-5 text-muted-foreground" />
<span className="font-medium text-foreground">{item.label}</span>
</button>
))}
</SideDrawerContent>
))}
</SideDrawerContent>
</div>
<FileBrowserSheet
isOpen={mentionFileBrowserOpen}
onClose={() => setMentionFileBrowserOpen(false)}
@@ -134,7 +134,7 @@ describe('RepoQuickSwitchSheet', () => {
expect(handleClose).toHaveBeenCalled()
})
it('navigates directly to assistant when mobileTabAction is assistant', async () => {
it('navigates to assistant when mobileTabAction is assistant', async () => {
vi.mocked(listRepos).mockResolvedValue([
{
id: 1,
@@ -172,11 +172,53 @@ describe('RepoQuickSwitchSheet', () => {
fireEvent.click(screen.getByText('repo1'))
expect(screen.getByTestId('location')).toHaveTextContent('/repos/1/assistant')
expect(screen.getByTestId('location')).toHaveTextContent('/assistant')
expect(handleClose).not.toHaveBeenCalled()
})
it('navigates from assistant to repo detail when clicking active repo', async () => {
it('navigates from assistant to repo detail when clicking repo on canonical assistant route', async () => {
vi.mocked(listRepos).mockResolvedValue([
{
id: 1,
repoUrl: 'https://github.com/test/repo1.git',
localPath: '/path/to/repo1',
sourcePath: null,
currentBranch: 'main',
isLocal: false,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
},
])
const handleClose = vi.fn()
render(
<QueryClientProvider client={new QueryClient()}>
<MemoryRouter initialEntries={['/assistant?mobileTab=repos']}>
<Routes>
<Route
path="*"
element={
<>
<RepoQuickSwitchSheet isOpen onClose={handleClose} />
<LocationSpy />
</>
}
/>
</Routes>
</MemoryRouter>
</QueryClientProvider>,
)
await waitFor(() => {
expect(screen.getByText('repo1')).toBeInTheDocument()
})
fireEvent.click(screen.getByText('repo1'))
expect(screen.getByTestId('location')).toHaveTextContent('/repos/1')
expect(handleClose).not.toHaveBeenCalled()
})
it('navigates from legacy assistant route to repo detail when clicking repo', async () => {
vi.mocked(listRepos).mockResolvedValue([
{
id: 1,
@@ -218,6 +260,106 @@ describe('RepoQuickSwitchSheet', () => {
expect(handleClose).not.toHaveBeenCalled()
})
it('does not mark any repo active on /assistant', async () => {
vi.mocked(listRepos).mockResolvedValue([
{
id: 1,
repoUrl: 'https://github.com/test/repo1.git',
localPath: '/path/to/repo1',
sourcePath: null,
currentBranch: 'main',
isLocal: false,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
},
{
id: 2,
repoUrl: 'https://github.com/test/repo2.git',
localPath: '/path/to/repo2',
sourcePath: null,
currentBranch: 'main',
isLocal: false,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
},
])
const handleClose = vi.fn()
render(
<QueryClientProvider client={new QueryClient()}>
<MemoryRouter initialEntries={['/assistant?mobileTab=repos']}>
<Routes>
<Route
path="*"
element={
<>
<RepoQuickSwitchSheet isOpen onClose={handleClose} />
<LocationSpy />
</>
}
/>
</Routes>
</MemoryRouter>
</QueryClientProvider>,
)
await waitFor(() => {
expect(screen.getByText('repo1')).toBeInTheDocument()
expect(screen.getByText('repo2')).toBeInTheDocument()
})
expect(screen.queryByRole('button', { current: 'page' })).toBeNull()
})
it('does not mark any repo active on legacy /repos/1/assistant', async () => {
vi.mocked(listRepos).mockResolvedValue([
{
id: 1,
repoUrl: 'https://github.com/test/repo1.git',
localPath: '/path/to/repo1',
sourcePath: null,
currentBranch: 'main',
isLocal: false,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
},
{
id: 2,
repoUrl: 'https://github.com/test/repo2.git',
localPath: '/path/to/repo2',
sourcePath: null,
currentBranch: 'main',
isLocal: false,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
},
])
const handleClose = vi.fn()
render(
<QueryClientProvider client={new QueryClient()}>
<MemoryRouter initialEntries={['/repos/1/assistant?mobileTab=repos']}>
<Routes>
<Route
path="*"
element={
<>
<RepoQuickSwitchSheet isOpen onClose={handleClose} />
<LocationSpy />
</>
}
/>
</Routes>
</MemoryRouter>
</QueryClientProvider>,
)
await waitFor(() => {
expect(screen.getByText('repo1')).toBeInTheDocument()
expect(screen.getByText('repo2')).toBeInTheDocument()
})
expect(screen.queryByRole('button', { current: 'page' })).toBeNull()
})
it('switches repos from the mobile repos sheet without navigating back to the previous repo', async () => {
vi.mocked(listRepos).mockResolvedValue([
{
@@ -8,6 +8,7 @@ import { cn, getRepoDisplayName } from '@/lib/utils'
import { listRepos } from '@/api/repos'
import { AddRepoDialog } from '@/components/repo/AddRepoDialog'
import { FolderGit2, Check, Plus } from 'lucide-react'
import { isAssistantPath, getAssistantPath } from '@/lib/navigation'
interface RepoQuickSwitchSheetProps {
isOpen: boolean
@@ -20,10 +21,13 @@ export function RepoQuickSwitchSheet({ isOpen, onClose }: RepoQuickSwitchSheetPr
const [searchQuery, setSearchQuery] = useState('')
const [addRepoOpen, setAddRepoOpen] = useState(false)
const isAssistantRoute = useMemo(() => isAssistantPath(location.pathname), [location.pathname])
const activeRepoId = useMemo(() => {
if (isAssistantRoute) return null
const match = location.pathname.match(/^\/repos\/(\d+)/)
return match ? Number(match[1]) : null
}, [location.pathname])
}, [location.pathname, isAssistantRoute])
const { data: repos, isLoading } = useQuery({
queryKey: ['repos'],
@@ -52,18 +56,18 @@ export function RepoQuickSwitchSheet({ isOpen, onClose }: RepoQuickSwitchSheetPr
const handleClick = (id: number) => {
const pendingAction = new URLSearchParams(location.search).get('mobileTabAction')
if (pendingAction === 'assistant') {
navigateAndClose(`/repos/${id}/assistant`)
if (isAssistantRoute) {
navigateAndClose(`/repos/${id}`, { replace: true })
return
}
const isAssistantRoute = location.pathname === `/repos/${id}/assistant`
if (id === activeRepoId) {
if (isAssistantRoute) {
navigateAndClose(`/repos/${id}`, { replace: true })
return
}
if (pendingAction === 'assistant') {
navigateAndClose(getAssistantPath())
return
}
if (id === activeRepoId) {
onClose()
return
}
@@ -1,15 +1,15 @@
import { MoreVertical } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { useMobileTabBar } from '@/hooks/useMobileTabBar'
import { useUIState } from '@/stores/uiStateStore'
export function SessionMoreButton() {
const { open } = useMobileTabBar()
const setMoreDrawerOpen = useUIState((state) => state.setMoreDrawerOpen)
return (
<Button
variant="outline"
size="sm"
onClick={() => open('more')}
onClick={() => setMoreDrawerOpen(true)}
className="md:hidden h-10 w-10 p-0 text-foreground border-border hover:bg-accent"
aria-label="More"
>
@@ -97,7 +97,7 @@ describe('buildNavModel', () => {
expect(model.primary[0].key).toBe('new-session')
expect(model.primary[0].onSelect).toBe('new-session')
expect(model.primary[1].key).toBe('assistant')
expect(model.primary[1].to).toBe('/repos/5/assistant')
expect(model.primary[1].to).toBe('/assistant')
})
it('returns new-session and assistant primary CTAs for session detail', () => {
@@ -107,7 +107,7 @@ describe('buildNavModel', () => {
expect(model.primary[0].onSelect).toBe('new-session')
expect(model.primary[0].variant).toBe('primary')
expect(model.primary[1].key).toBe('assistant')
expect(model.primary[1].to).toBe('/repos/5/assistant')
expect(model.primary[1].to).toBe('/assistant')
expect(model.primary[1].variant).toBe('secondary')
})
@@ -118,7 +118,18 @@ describe('buildNavModel', () => {
expect(model.primary[0].onSelect).toBe('new-session')
expect(model.primary[0].variant).toBe('primary')
expect(model.primary[1].key).toBe('assistant')
expect(model.primary[1].to).toBe('/repos/5/assistant')
expect(model.primary[1].to).toBe('/assistant')
expect(model.primary[1].variant).toBe('secondary')
})
it('returns new-session and assistant primary CTAs for canonical /assistant', () => {
const model = buildNavModel('/assistant')
expect(model.primary).toHaveLength(2)
expect(model.primary[0].key).toBe('new-session')
expect(model.primary[0].onSelect).toBe('new-session')
expect(model.primary[0].variant).toBe('primary')
expect(model.primary[1].key).toBe('assistant')
expect(model.primary[1].to).toBe('/assistant')
expect(model.primary[1].variant).toBe('secondary')
})
@@ -135,7 +146,7 @@ describe('buildNavModel', () => {
expect(model2.primary[0].key).toBe('new-schedule')
expect(model2.primary[0].onSelect).toBe('new-schedule')
expect(model2.primary[1].key).toBe('assistant')
expect(model2.primary[1].to).toBe('/repos/5/assistant')
expect(model2.primary[1].to).toBe('/assistant')
})
it('returns assistant primary for unknown routes', () => {
@@ -1,5 +1,6 @@
import type { LucideIcon } from 'lucide-react'
import { Plug, Sparkles, ShieldOff, CalendarClock, GitCommitHorizontal, Code2, Settings, LogOut, Plus, Bot, Folder, Clock, SquarePlus } from 'lucide-react'
import { getAssistantPath, isAssistantPath } from '@/lib/navigation'
export interface MoreDrawerItem {
key: string
@@ -24,14 +25,12 @@ export interface NavModel {
items: MoreDrawerItem[]
}
function getAssistantNavItem(pathname: string, variant: NavPrimaryCta['variant'] = 'secondary'): NavPrimaryCta {
const repoMatch = /^\/repos\/(\d+)/.exec(pathname)
function getAssistantNavItem(_pathname: string, variant: NavPrimaryCta['variant'] = 'secondary'): NavPrimaryCta {
return {
key: 'assistant',
label: 'Assistant',
icon: Bot,
to: repoMatch ? `/repos/${repoMatch[1]}/assistant` : '/assistant',
to: getAssistantPath(),
variant,
}
}
@@ -89,15 +88,13 @@ export function buildNavModel(pathname: string): NavModel {
}
}
const assistantMatch = /^\/repos\/(\d+)\/assistant$/.exec(pathname)
if (assistantMatch) {
const id = assistantMatch[1]
if (isAssistantPath(pathname)) {
const items: MoreDrawerItem[] = [
{ key: 'files', label: 'Files', icon: Folder, dialog: 'files' },
{ key: 'mcp', label: 'MCP', icon: Plug, dialog: 'mcp' },
{ key: 'skills', label: 'Skills', icon: Sparkles, dialog: 'skills' },
{ key: 'reset-permissions', label: 'Reset Permissions', icon: ShieldOff, dialog: 'resetPermissions', danger: true },
{ key: 'schedules', label: 'Schedules', icon: CalendarClock, to: `/repos/${id}/schedules` },
{ key: 'schedules', label: 'Schedules', icon: CalendarClock, to: '/repos/0/schedules' },
{ key: 'source-control', label: 'Source Control', icon: GitCommitHorizontal, dialog: 'sourceControl' },
...baseItems,
]
@@ -14,7 +14,7 @@ type RepoSkillsDialogBaseProps = {
}
type RepoSkillsDialogProps = RepoSkillsDialogBaseProps & (
| { sessionId: string; opcodeUrl: string; directory: string; onSkillLoaded?: (skill: SkillFileInfo) => void }
| { sessionId: string; opcodeUrl: string; directory?: string; onSkillLoaded?: (skill: SkillFileInfo) => void }
| { sessionId?: undefined; opcodeUrl?: undefined; directory?: undefined; onSkillLoaded?: undefined }
)
@@ -28,9 +28,9 @@ export function RepoSkillsDialog({
onSkillLoaded,
}: RepoSkillsDialogProps) {
const { isLoading, data, error } = useQuery({
queryKey: ['settings', 'skills', repoId],
queryFn: () => settingsApi.listManagedSkills(repoId),
enabled: open && !!repoId,
queryKey: directory ? ['settings', 'skills', 'directory', directory] : ['settings', 'skills', repoId],
queryFn: () => settingsApi.listManagedSkills(repoId, directory),
enabled: open && (!!repoId || !!directory),
staleTime: 30000,
})
@@ -64,7 +64,7 @@ export function RepoSkillsDialog({
onOpenChange(false)
}
if (!repoId) {
if (!repoId && !sessionId) {
return null
}
@@ -60,10 +60,11 @@ export function RepoSkillsList({
{data.map((skill) => (
<div
key={skill.name}
className="p-2 rounded-lg border border-border bg-card flex items-center justify-between gap-2"
onClick={() => onLoad?.(skill)}
className={`p-2 rounded-lg border border-border bg-card flex items-center justify-between gap-2 ${onLoad ? 'cursor-pointer hover:bg-accent transition-colors' : ''}`}
>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium truncate">
<p className="text-sm font-medium truncate text-orange-600 dark:text-orange-400">
{formatSkillName(skill.name)}
</p>
{skill.description && (
@@ -72,15 +73,6 @@ export function RepoSkillsList({
</p>
)}
</div>
{onLoad && (
<button
type="button"
onClick={() => onLoad(skill)}
className="shrink-0 text-xs font-medium text-primary hover:text-foreground transition-colors"
>
Load
</button>
)}
</div>
))}
</div>
@@ -1,6 +1,4 @@
import { useContextUsage } from '@/hooks/useContextUsage'
import { getModel, formatModelName } from '@/api/providers'
import { useState, useEffect } from 'react'
interface ContextUsageIndicatorProps {
opcodeUrl: string | null
@@ -10,35 +8,14 @@ interface ContextUsageIndicatorProps {
isReconnecting?: boolean
}
const getUsageTextColor = (percentage: number) => {
if (percentage < 50) return 'text-green-700 dark:text-green-400'
if (percentage < 80) return 'text-yellow-700 dark:text-yellow-400'
return 'text-red-700 dark:text-red-400'
}
export function ContextUsageIndicator({ opcodeUrl, sessionID, directory, isConnected, isReconnecting }: ContextUsageIndicatorProps) {
const { totalTokens, contextLimit, usagePercentage, currentModel, isLoading } = useContextUsage(opcodeUrl, sessionID, directory)
const [modelName, setModelName] = useState<string>('')
useEffect(() => {
const loadModelName = async () => {
if (currentModel) {
try {
const [providerId, modelId] = currentModel.split('/')
if (providerId && modelId) {
const model = await getModel(providerId, modelId)
if (model) {
setModelName(formatModelName(model))
} else {
setModelName(currentModel)
}
} else {
setModelName(currentModel)
}
} catch {
setModelName(currentModel)
}
} else {
setModelName('')
}
}
loadModelName()
}, [currentModel])
const { totalTokens, contextLimit, usagePercentage, isLoading } = useContextUsage(opcodeUrl, sessionID, directory)
if (isLoading) {
return (
@@ -56,39 +33,15 @@ export function ContextUsageIndicator({ opcodeUrl, sessionID, directory, isConne
return <span className="text-xs text-muted-foreground font-medium">Disconnected</span>
}
if (!modelName) {
return (
<div className="flex items-center gap-2">
<span className="text-xs text-muted-foreground">No model</span>
</div>
)
}
const getUsageTextColor = (percentage: number) => {
if (percentage < 50) return 'text-green-700 dark:text-green-400'
if (percentage < 80) return 'text-yellow-700 dark:text-yellow-400'
return 'text-red-700 dark:text-red-400'
}
if (isReconnecting) {
return null
}
if (!contextLimit) {
return (
<div className="flex items-center gap-2">
<span className="text-xs text-muted-foreground">{modelName}</span>
</div>
)
}
const tokenText = contextLimit
? `${totalTokens.toLocaleString()} / ${contextLimit.toLocaleString()}`
: totalTokens.toLocaleString()
return (
<div className="flex items-center gap-2">
<div className="flex items-center gap-2 min-w-0">
<span className={`text-xs font-medium whitespace-nowrap ${getUsageTextColor(usagePercentage || 0)}`}>
{totalTokens.toLocaleString()} / {contextLimit.toLocaleString()}
</span>
</div>
<span className={`text-xs font-medium whitespace-nowrap ${getUsageTextColor(usagePercentage || 0)}`}>
{tokenText}
</span>
</div>
)
}
@@ -1,4 +1,4 @@
import { useState, useRef, useEffect, useCallback } from 'react'
import { useState, useEffect, useCallback } from 'react'
import { GeneralSettings } from '@/components/settings/GeneralSettings'
import { GitSettings } from '@/components/settings/GitSettings'
import { KeyboardShortcuts } from '@/components/settings/KeyboardShortcuts'
@@ -12,7 +12,6 @@ import { Dialog, DialogContent } from '@/components/ui/dialog'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Settings2, Keyboard, Code, ChevronLeft, Key, GitBranch, User, Volume2, Bell, X } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { useSwipeBack } from '@/hooks/useMobile'
import { useSettingsDialog } from '@/hooks/useSettingsDialog'
type SettingsView = 'menu' | 'general' | 'git' | 'shortcuts' | 'opencode' | 'providers' | 'account' | 'voice' | 'notifications'
@@ -21,7 +20,6 @@ export function SettingsDialog() {
const { isOpen, close, activeTab, setActiveTab } = useSettingsDialog()
const [mobileView, setMobileView] = useState<SettingsView>('menu')
const [sectionHistory, setSectionHistory] = useState<SettingsView[]>([])
const contentRef = useRef<HTMLDivElement>(null)
const pushSectionHistory = useCallback((view: SettingsView) => {
if (view === 'menu') return
@@ -54,16 +52,6 @@ export function SettingsDialog() {
setMobileView('menu')
}, [mobileView, sectionHistory, close, setActiveTab])
const { bind: bindSwipe, swipeStyles } = useSwipeBack(close, {
enabled: isOpen,
canBack: () => mobileView !== 'menu',
onBack: handleSettingsBack,
})
useEffect(() => {
return bindSwipe(contentRef.current)
}, [bindSwipe])
useEffect(() => {
if (!isOpen) {
setMobileView('menu')
@@ -105,13 +93,13 @@ export function SettingsDialog() {
}
return (
<Dialog open={isOpen} modal={false}>
<DialogContent
ref={contentRef}
className="inset-0 w-full h-full max-w-none max-h-none p-0 rounded-none bg-gradient-to-br from-background via-background to-background border-border overflow-hidden !flex !flex-col"
style={swipeStyles}
fullscreen
>
<Dialog open={isOpen} modal={false} onOpenChange={(open) => !open && close()}>
<DialogContent
className="inset-0 w-full h-full max-w-none max-h-none p-0 rounded-none bg-gradient-to-br from-background via-background to-background border-border overflow-hidden !flex !flex-col"
fullscreen
canSwipeBack={() => mobileView !== 'menu'}
onSwipeBack={handleSettingsBack}
>
<div className="hidden sm:flex sm:flex-col sm:h-full">
<div className="sticky top-0 z-10 bg-gradient-to-b from-background via-background to-transparent border-b border-border backdrop-blur-sm px-6 py-4 flex-shrink-0 flex items-center justify-between">
<h2 className="text-2xl font-semibold bg-gradient-to-r from-foreground to-muted-foreground bg-clip-text text-transparent">
@@ -109,7 +109,7 @@ describe('BottomSheet', () => {
expect(useSwipeDismiss).toHaveBeenCalledWith(expect.any(Function), {
enabled: true,
threshold: 80,
threshold: 60,
})
})
+237 -53
View File
@@ -1,4 +1,4 @@
import { describe, it, expect, vi } from "vitest";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen } from "@testing-library/react";
import {
Dialog,
@@ -7,7 +7,30 @@ import {
DialogTitle,
} from "./dialog";
function withMobileViewport(fn: () => void) {
const originalWidth = window.innerWidth
Object.defineProperty(window, 'innerWidth', {
writable: true,
configurable: true,
value: 375,
})
fn()
Object.defineProperty(window, 'innerWidth', {
writable: true,
configurable: true,
value: originalWidth,
})
}
describe("DialogContent", () => {
beforeEach(() => {
Object.defineProperty(window, 'innerWidth', {
writable: true,
configurable: true,
value: 375,
})
})
it("applies safe-area padding when fullscreen prop is true", () => {
render(
<Dialog open>
@@ -162,64 +185,225 @@ describe("DialogContent", () => {
expect(content).toHaveStyle({ paddingTop: "env(safe-area-inset-top, 0px)" });
});
it('renders hidden close trigger when mobileSwipeToClose is enabled', () => {
const onOpenChange = vi.fn();
render(
<Dialog open onOpenChange={onOpenChange}>
<DialogContent mobileFullscreen mobileSwipeToClose>
<DialogHeader>
<DialogTitle>Swipe Dialog</DialogTitle>
</DialogHeader>
</DialogContent>
</Dialog>
);
const closeTrigger = document.querySelector('[data-swipe-close-trigger]');
expect(closeTrigger).toBeInTheDocument();
it('renders hidden close trigger by default on mobile', () => {
withMobileViewport(() => {
const onOpenChange = vi.fn();
render(
<Dialog open onOpenChange={onOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>Swipe Dialog</DialogTitle>
</DialogHeader>
</DialogContent>
</Dialog>
);
const closeTrigger = document.querySelector('[data-swipe-close-trigger]');
expect(closeTrigger).toBeInTheDocument();
});
});
it('does not render hidden close trigger when mobileSwipeToClose is false', () => {
withMobileViewport(() => {
render(
<Dialog open>
<DialogContent mobileSwipeToClose={false}>
<DialogHeader>
<DialogTitle>Swipe Dialog</DialogTitle>
</DialogHeader>
</DialogContent>
</Dialog>
);
const closeTrigger = document.querySelector('[data-swipe-close-trigger]');
expect(closeTrigger).not.toBeInTheDocument();
});
});
it('closes dialog when hidden close trigger is activated', () => {
const onOpenChange = vi.fn();
render(
<Dialog open onOpenChange={onOpenChange}>
<DialogContent mobileFullscreen mobileSwipeToClose>
<DialogHeader>
<DialogTitle>Swipe Dialog</DialogTitle>
</DialogHeader>
</DialogContent>
</Dialog>
);
const closeTrigger = document.querySelector('[data-swipe-close-trigger]') as HTMLButtonElement | null;
expect(closeTrigger).toBeInTheDocument();
if (closeTrigger) {
closeTrigger.click();
withMobileViewport(() => {
const onOpenChange = vi.fn();
render(
<Dialog open onOpenChange={onOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>Swipe Dialog</DialogTitle>
</DialogHeader>
</DialogContent>
</Dialog>
);
const closeTrigger = document.querySelector('[data-swipe-close-trigger]') as HTMLButtonElement | null;
expect(closeTrigger).toBeInTheDocument();
if (closeTrigger) {
closeTrigger.click();
expect(onOpenChange).toHaveBeenCalledWith(false);
}
});
});
it('calls onSwipeBack when canSwipeBack is true and swipe completes', () => {
withMobileViewport(() => {
const mockOnSwipeBack = vi.fn();
const onOpenChange = vi.fn();
render(
<Dialog open onOpenChange={onOpenChange}>
<DialogContent
canSwipeBack={() => true}
onSwipeBack={mockOnSwipeBack}
data-testid="swipe-dialog"
>
Content
</DialogContent>
</Dialog>
);
const content = screen.getByTestId('swipe-dialog');
content.dispatchEvent(new TouchEvent('touchstart', {
touches: [{ clientX: 10, clientY: 100 }] as any,
}));
content.dispatchEvent(new TouchEvent('touchmove', {
touches: [{ clientX: 100, clientY: 100 }] as any,
}));
content.dispatchEvent(new TouchEvent('touchend', {
changedTouches: [{ clientX: 100, clientY: 100 }] as any,
}));
expect(mockOnSwipeBack).toHaveBeenCalled();
expect(onOpenChange).not.toHaveBeenCalled();
});
});
it('attempts close when canSwipeBack is false and swipe completes', () => {
withMobileViewport(() => {
const mockOnSwipeBack = vi.fn();
const onOpenChange = vi.fn();
render(
<Dialog open onOpenChange={onOpenChange}>
<DialogContent
canSwipeBack={() => false}
onSwipeBack={mockOnSwipeBack}
data-testid="swipe-dialog"
>
Content
</DialogContent>
</Dialog>
);
const content = screen.getByTestId('swipe-dialog');
content.dispatchEvent(new TouchEvent('touchstart', {
touches: [{ clientX: 10, clientY: 100 }] as any,
}));
content.dispatchEvent(new TouchEvent('touchmove', {
touches: [{ clientX: 100, clientY: 100 }] as any,
}));
content.dispatchEvent(new TouchEvent('touchend', {
changedTouches: [{ clientX: 100, clientY: 100 }] as any,
}));
expect(mockOnSwipeBack).not.toHaveBeenCalled();
expect(onOpenChange).toHaveBeenCalledWith(false);
}
});
});
it('applies safe-area style and hidden trigger for mobileFullscreen', () => {
withMobileViewport(() => {
render(
<Dialog open>
<DialogContent mobileFullscreen data-testid="dialog-content">
Content
</DialogContent>
</Dialog>
);
const content = screen.getByTestId("dialog-content");
expect(content).toHaveStyle({ paddingTop: "env(safe-area-inset-top, 0px)" });
expect(document.querySelector('[data-swipe-close-trigger]')).toBeInTheDocument();
});
});
it('does not apply transform styles to non-fullscreen dialogs', () => {
withMobileViewport(() => {
render(
<Dialog open>
<DialogContent data-testid="dialog-content">
Content
</DialogContent>
</Dialog>
);
const content = screen.getByTestId("dialog-content");
const style = content.getAttribute("style") || "";
expect(style).not.toMatch(/transform/);
});
});
it('applies swipe transform to fullscreen dialogs during touchmove', () => {
withMobileViewport(() => {
render(
<Dialog open>
<DialogContent fullscreen data-testid="dialog-content">
Content
</DialogContent>
</Dialog>
);
const content = screen.getByTestId("dialog-content");
content.dispatchEvent(new TouchEvent('touchstart', {
touches: [{ clientX: 10, clientY: 100 }] as any,
}));
content.dispatchEvent(new TouchEvent('touchmove', {
touches: [{ clientX: 50, clientY: 100 }] as any,
}));
const style = content.getAttribute("style") || "";
expect(style).toMatch(/transform/);
});
});
it('does not apply swipe transform to non-fullscreen dialogs during touchmove', () => {
withMobileViewport(() => {
render(
<Dialog open>
<DialogContent data-testid="dialog-content">
Content
</DialogContent>
</Dialog>
);
const content = screen.getByTestId("dialog-content");
content.dispatchEvent(new TouchEvent('touchstart', {
touches: [{ clientX: 10, clientY: 100 }] as any,
}));
content.dispatchEvent(new TouchEvent('touchmove', {
touches: [{ clientX: 50, clientY: 100 }] as any,
}));
const style = content.getAttribute("style") || "";
expect(style).not.toMatch(/transform/);
});
});
it('binds swipe handler when mobileSwipeToClose and mobileFullscreen are enabled', () => {
const onOpenChange = vi.fn();
render(
<Dialog open onOpenChange={onOpenChange}>
<DialogContent mobileFullscreen mobileSwipeToClose data-testid="swipe-dialog">
<DialogHeader>
<DialogTitle>Swipe Dialog</DialogTitle>
</DialogHeader>
</DialogContent>
</Dialog>
);
const content = screen.getByTestId('swipe-dialog');
const closeTrigger = document.querySelector('[data-swipe-close-trigger]') as HTMLButtonElement | null;
expect(content).toBeInTheDocument();
expect(closeTrigger).toBeInTheDocument();
const clickSpy = vi.spyOn(closeTrigger as HTMLButtonElement, 'click');
closeTrigger?.click();
expect(clickSpy).toHaveBeenCalled();
expect(onOpenChange).toHaveBeenCalledWith(false);
withMobileViewport(() => {
const onOpenChange = vi.fn();
render(
<Dialog open onOpenChange={onOpenChange}>
<DialogContent mobileFullscreen mobileSwipeToClose data-testid="swipe-dialog">
<DialogHeader>
<DialogTitle>Swipe Dialog</DialogTitle>
</DialogHeader>
</DialogContent>
</Dialog>
);
const content = screen.getByTestId('swipe-dialog');
const closeTrigger = document.querySelector('[data-swipe-close-trigger]') as HTMLButtonElement | null;
expect(content).toBeInTheDocument();
expect(closeTrigger).toBeInTheDocument();
const clickSpy = vi.spyOn(closeTrigger as HTMLButtonElement, 'click');
closeTrigger?.click();
expect(clickSpy).toHaveBeenCalled();
expect(onOpenChange).toHaveBeenCalledWith(false);
});
});
});
+23 -14
View File
@@ -34,6 +34,8 @@ interface DialogContentProps
fullscreen?: boolean
mobileFullscreen?: boolean
mobileSwipeToClose?: boolean
canSwipeBack?: () => boolean
onSwipeBack?: () => void
onOpenChange?: (open: boolean) => void
overlayClassName?: string
}
@@ -41,14 +43,15 @@ interface DialogContentProps
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
DialogContentProps
>(({ className, children, hideCloseButton, fullscreen, mobileFullscreen, mobileSwipeToClose, overlayClassName, ...props }, ref) => {
>(({ className, children, hideCloseButton, fullscreen, mobileFullscreen, mobileSwipeToClose, canSwipeBack, onSwipeBack, overlayClassName, style, ...props }, ref) => {
const isMobileFullscreenMode = fullscreen || mobileFullscreen
const [isMobile, setIsMobile] = React.useState(() => typeof window !== 'undefined' ? window.innerWidth < 768 : false)
const shouldEnableMobileSwipe = mobileSwipeToClose !== false && isMobile
const shouldAnimateSwipe = shouldEnableMobileSwipe && isMobileFullscreenMode
const swipeContainerRef = React.useRef<HTMLDivElement>(null)
const contentRef = React.useRef<HTMLDivElement>(null)
const closeTriggerRef = React.useRef<HTMLButtonElement>(null)
const combinedRef = React.useCallback((node: HTMLDivElement | null) => {
contentRef.current = node
swipeContainerRef.current = node
if (typeof ref === 'function') {
ref(node)
@@ -57,25 +60,33 @@ const DialogContent = React.forwardRef<
}
}, [ref])
const [isMobile, setIsMobile] = React.useState(() => typeof window !== 'undefined' ? window.innerWidth < 768 : false)
React.useEffect(() => {
const check = () => setIsMobile(window.innerWidth < 768)
window.addEventListener('resize', check)
return () => window.removeEventListener('resize', check)
}, [])
const { bind: swipeBind } = useSwipeBack(
const { bind: swipeBind, swipeStyles } = useSwipeBack(
() => closeTriggerRef.current?.click(),
{ enabled: isMobileFullscreenMode && mobileSwipeToClose === true && isMobile }
{ enabled: shouldEnableMobileSwipe, canBack: canSwipeBack, onBack: onSwipeBack }
)
React.useEffect(() => {
if (isMobileFullscreenMode && mobileSwipeToClose && isMobile) {
if (shouldEnableMobileSwipe) {
return swipeBind(swipeContainerRef.current)
}
return undefined
}, [isMobileFullscreenMode, mobileSwipeToClose, isMobile, swipeBind])
}, [shouldEnableMobileSwipe, swipeBind])
const baseStyle = isMobileFullscreenMode
? { paddingTop: 'env(safe-area-inset-top, 0px)' }
: undefined
const mergedStyle = {
...baseStyle,
...style,
...(shouldAnimateSwipe ? swipeStyles : undefined),
}
return (
<DialogPortal>
{!fullscreen && <DialogOverlay className={overlayClassName} />}
@@ -92,13 +103,11 @@ const DialogContent = React.forwardRef<
: "left-[50%] top-[50%] w-[90%] max-w-lg translate-x-[-50%] translate-y-[-50%] p-6 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",
className
)}
style={isMobileFullscreenMode ? {
paddingTop: 'env(safe-area-inset-top, 0px)',
} : undefined}
style={Object.keys(mergedStyle).length > 0 ? mergedStyle : undefined}
{...props}
>
{children}
{mobileSwipeToClose && isMobileFullscreenMode && (
{shouldEnableMobileSwipe && (
<DialogPrimitive.Close ref={closeTriggerRef} className="sr-only" data-swipe-close-trigger />
)}
{!hideCloseButton && !fullscreen && (
@@ -52,16 +52,9 @@ describe("PageHeader", () => {
expect(header).toHaveClass("z-10");
});
it("applies background styling", () => {
it("applies transparent background", () => {
render(<PageHeader data-testid="header">Content</PageHeader>);
const header = screen.getByTestId("header");
expect(header).toHaveClass("bg-gradient-to-b");
expect(header).toHaveClass("from-background");
});
it("applies backdrop-blur-sm for frosted glass effect", () => {
render(<PageHeader data-testid="header">Content</PageHeader>);
const header = screen.getByTestId("header");
expect(header).toHaveClass("backdrop-blur-sm");
expect(header).toHaveClass("bg-transparent");
});
});
+1 -1
View File
@@ -69,7 +69,7 @@ export function SideDrawer({
/>
<div
className={cn(
'fixed top-0 bottom-0 bg-background border-l border-border pt-safe pb-safe flex flex-col',
'fixed top-0 bottom-0 bg-background border-l border-border pt-safe pb-safe flex flex-col z-50',
side === 'right' ? 'right-0' : 'left-0',
widthClass,
className,
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { renderHook, waitFor } from '@testing-library/react'
import { renderHook } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { useMessages } from '../useOpenCode'
@@ -43,10 +43,8 @@ describe('useMessages fallback poll', () => {
expect(mocks.listMessages).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(5000)
await waitFor(() => {
expect(mocks.listMessages).toHaveBeenCalledTimes(2)
})
expect(mocks.listMessages).toHaveBeenCalledTimes(2)
vi.useRealTimers()
})
@@ -0,0 +1,136 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { renderHook, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { useWorkspace } from '../useWorkspace'
import type { AssistantModeStatus, Repo } from '@opencode-manager/shared/types'
const mocks = vi.hoisted(() => ({
getRepo: vi.fn(),
getAssistantModeStatus: vi.fn(),
}))
vi.mock('@/api/repos', () => ({
getRepo: mocks.getRepo,
getAssistantModeStatus: mocks.getAssistantModeStatus,
}))
const createWrapper = () => {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
mutations: { retry: false },
},
})
return ({ children }: { children: React.ReactNode }) =>
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
}
describe('useWorkspace', () => {
beforeEach(() => {
vi.clearAllMocks()
})
describe('repoId === 0 (assistant)', () => {
it('returns assistant workspace with correct properties', async () => {
const mockStatus: AssistantModeStatus = {
repoId: 0,
directory: '/abs/assistant',
relativePath: 'repos/assistant',
files: {
agentsMd: { path: '', exists: false, created: false },
opencodeJson: { path: '', exists: false, created: false },
},
schedulesSkill: { path: '', exists: false, created: false },
}
mocks.getAssistantModeStatus.mockResolvedValue(mockStatus)
const { result } = renderHook(() => useWorkspace(0), { wrapper: createWrapper() })
await waitFor(() => {
expect(result.current.workspace).toBeDefined()
})
expect(result.current.workspace?.kind).toBe('assistant')
expect(result.current.workspace?.fullPath).toBe('/abs/assistant')
expect(result.current.workspace?.repoId).toBe(0)
expect(result.current.workspace?.backHref).toBe('/assistant')
expect(result.current.isLoading).toBe(false)
expect(result.current.isError).toBe(false)
})
it('does not call getRepo for assistant', async () => {
mocks.getAssistantModeStatus.mockResolvedValue({
directory: '/abs/assistant',
relativePath: 'repos/assistant',
files: { agentsMd: { path: '', exists: false, created: false }, opencodeJson: { path: '', exists: false, created: false } },
schedulesSkill: { path: '', exists: false, created: false },
repoId: 0,
})
renderHook(() => useWorkspace(0), { wrapper: createWrapper() })
await vi.waitFor(() => {
expect(mocks.getRepo).not.toHaveBeenCalled()
})
})
})
describe('repoId === 5 (real repo)', () => {
it('returns repo workspace with correct properties', async () => {
const mockRepo: Repo = {
id: 5,
repoUrl: 'https://x/my-repo',
localPath: 'repos/my-repo',
fullPath: '/abs/repos/my-repo',
sourcePath: undefined,
defaultBranch: 'main',
cloneStatus: 'ready',
clonedAt: 0,
}
mocks.getRepo.mockResolvedValue(mockRepo)
const { result } = renderHook(() => useWorkspace(5), { wrapper: createWrapper() })
await waitFor(() => {
expect(result.current.workspace).toBeDefined()
})
expect(result.current.workspace?.kind).toBe('repo')
expect(result.current.workspace?.repoId).toBe(5)
expect(result.current.workspace?.fullPath).toBe('/abs/repos/my-repo')
expect(result.current.workspace?.backHref).toBe('/repos/5')
})
it('does not call getAssistantModeStatus for repo', async () => {
const mockRepo: Repo = {
id: 5,
repoUrl: 'https://x/my-repo',
localPath: 'repos/my-repo',
fullPath: '/abs/repos/my-repo',
sourcePath: undefined,
defaultBranch: 'main',
cloneStatus: 'ready',
clonedAt: 0,
}
mocks.getRepo.mockResolvedValue(mockRepo)
renderHook(() => useWorkspace(5), { wrapper: createWrapper() })
await vi.waitFor(() => {
expect(mocks.getAssistantModeStatus).not.toHaveBeenCalled()
})
})
})
describe('repoId === undefined', () => {
it('returns undefined workspace', () => {
const { result } = renderHook(() => useWorkspace(undefined), { wrapper: createWrapper() })
expect(result.current.workspace).toBeUndefined()
expect(result.current.isLoading).toBe(false)
})
})
})
+6 -6
View File
@@ -5,21 +5,21 @@ import {
} from '@/api/repos'
import type { AssistantModeStatus, AssistantModeInitRequest } from '@opencode-manager/shared/types'
export function useAssistantMode(repoId: number) {
export function useAssistantMode(repoId?: number) {
const queryClient = useQueryClient()
const statusQuery = useQuery<AssistantModeStatus>({
queryKey: ['repo', repoId, 'assistant-mode'],
queryFn: () => getAssistantModeStatus(repoId),
enabled: !!repoId,
queryKey: ['assistant-mode'],
queryFn: () => getAssistantModeStatus(0),
enabled: repoId === 0,
})
const initializeMutation = useMutation({
mutationFn: (options?: AssistantModeInitRequest) =>
initializeAssistantMode(repoId, options),
initializeAssistantMode(0, options),
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ['repo', repoId, 'assistant-mode'],
queryKey: ['assistant-mode'],
})
},
})
@@ -7,7 +7,7 @@ import { initializeAssistantMode } from '@/api/repos'
const mocks = vi.hoisted(() => ({
listSessions: vi.fn(),
createSession: vi.fn(),
sendPrompt: vi.fn(),
sendPromptAsync: vi.fn(),
initializeAssistantMode: vi.fn(),
}))
@@ -19,10 +19,14 @@ vi.mock('@/api/opencode', () => ({
OpenCodeClient: vi.fn(() => ({
listSessions: mocks.listSessions,
createSession: mocks.createSession,
sendPrompt: mocks.sendPrompt,
sendPromptAsync: mocks.sendPromptAsync,
})),
}))
beforeEach(() => {
mocks.sendPromptAsync.mockResolvedValue(undefined)
})
describe('useAssistantSessionLauncher', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -51,6 +55,45 @@ describe('useAssistantSessionLauncher', () => {
expect(OpenCodeClient).toHaveBeenCalledWith('http://localhost:5551', '/assistant')
expect(onNavigate).toHaveBeenCalledWith('newest')
expect(mocks.createSession).not.toHaveBeenCalled()
expect(mocks.sendPromptAsync).not.toHaveBeenCalled()
})
it('notifies an existing assistant session when some generated updates were preserved', async () => {
mocks.initializeAssistantMode.mockResolvedValue({
directory: '/assistant',
warnings: [
{
code: 'assistant-agents-md-preserved',
path: '/assistant/AGENTS.md',
message: 'Some Assistant Mode instruction updates were not applied because AGENTS.md appears to contain customized legacy assistant instructions. To regenerate the default workspace explanation, manually delete AGENTS.md and initialize Assistant Mode again.',
},
],
})
mocks.listSessions.mockResolvedValue([
{ id: 'existing', directory: '/assistant', time: { updated: 10 } },
])
const onNavigate = vi.fn()
const { result } = renderHook(() => useAssistantSessionLauncher({
repoId: 123,
opcodeUrl: 'http://localhost:5551',
onNavigate,
}))
await act(async () => {
await result.current.openAssistant()
})
expect(onNavigate).toHaveBeenCalledWith('existing')
expect(mocks.sendPromptAsync).toHaveBeenCalledWith('existing', {
parts: [
expect.objectContaining({
type: 'text',
text: expect.stringContaining('some generated instruction changes were not applied'),
}),
],
})
const promptText = mocks.sendPromptAsync.mock.calls[0][1].parts[0].text as string
expect(promptText).toContain('manually delete AGENTS.md')
})
it('creates a session when the assistant directory has no root sessions', async () => {
@@ -70,7 +113,7 @@ describe('useAssistantSessionLauncher', () => {
})
expect(mocks.createSession).toHaveBeenCalledWith({ title: 'Assistant' })
expect(mocks.sendPrompt).toHaveBeenCalledWith('created', {
expect(mocks.sendPromptAsync).toHaveBeenCalledWith('created', {
parts: [
expect.objectContaining({
type: 'text',
@@ -79,5 +122,66 @@ describe('useAssistantSessionLauncher', () => {
],
})
expect(onNavigate).toHaveBeenCalledWith('created')
const promptCall = mocks.sendPromptAsync.mock.calls[0]
const promptText = promptCall[1].parts[0].text as string
expect(promptText).toContain('.opencode/agents/assistant.md')
expect(promptText).toContain('AGENTS.md')
expect(promptText).toContain('.opencode/skills/')
expect(promptText).toContain('directory')
expect(promptText).toContain('durable preferences')
expect(promptText).toContain('self-editing rules')
expect(promptText).not.toContain('v file')
expect(promptText).not.toMatch(/AGENTS\.md contains workspace-level instructions, durable preferences, and self-editing rules/)
})
it('navigates after creating a session without waiting for the welcome prompt to complete', async () => {
mocks.listSessions.mockResolvedValue([])
let resolvePrompt: () => void
const promptPromise = new Promise<void>((resolve) => {
resolvePrompt = resolve
})
mocks.createSession.mockResolvedValue({ id: 'created' })
mocks.sendPromptAsync.mockImplementation(() => promptPromise)
const onNavigate = vi.fn()
const { result } = renderHook(() => useAssistantSessionLauncher({
repoId: 123,
opcodeUrl: 'http://localhost:5551',
onNavigate,
}))
await act(async () => {
await result.current.openAssistant()
})
expect(onNavigate).toHaveBeenCalledWith('created')
expect(mocks.sendPromptAsync).toHaveBeenCalledWith('created', {
parts: [
expect.objectContaining({
type: 'text',
text: expect.stringContaining('Welcome to OpenCode Manager!'),
}),
],
})
resolvePrompt!()
})
it('navigates even when welcome prompt fails', async () => {
mocks.listSessions.mockResolvedValue([])
mocks.createSession.mockResolvedValue({ id: 'created' })
mocks.sendPromptAsync.mockRejectedValueOnce(new Error('provider unavailable'))
const onNavigate = vi.fn()
const { result } = renderHook(() => useAssistantSessionLauncher({
repoId: 123,
opcodeUrl: 'http://localhost:5551',
onNavigate,
}))
await act(async () => {
await result.current.openAssistant()
})
expect(onNavigate).toHaveBeenCalledWith('created')
expect(mocks.sendPromptAsync).toHaveBeenCalled()
})
})
@@ -1,6 +1,7 @@
import { useCallback } from 'react'
import { initializeAssistantMode } from '@/api/repos'
import { OpenCodeClient } from '@/api/opencode'
import type { AssistantModeStatus } from '@opencode-manager/shared/types'
interface UseAssistantSessionLauncherOptions {
repoId: number
@@ -8,6 +9,66 @@ interface UseAssistantSessionLauncherOptions {
onNavigate: (sessionId: string) => void
}
const ASSISTANT_WELCOME_PROMPT = `Welcome to OpenCode Manager! I'm your assistant and I'm here to help you work with your code.
To get started, let's set up your assistant:
**1. Name your assistant**
What would you like to call me? This name will help personalize our interactions.
**2. Review AGENTS.md**
AGENTS.md explains the assistant workspace directory and points to the files OpenCode Manager manages.
**3. Review the assistant agent**
.opencode/agents/assistant.md contains the default Assistant Mode agent instructions, durable preferences, self-editing rules, and skill guidance.
**4. Use workspace skills**
.opencode/skills/ contains managed workspace skills for repos, schedules, notifications, and settings.
Take your time exploring and customizing these settings. Let me know when you're ready to start coding, or if you have any questions about getting set up!`
function buildAssistantModeWarningsPrompt(assistant: AssistantModeStatus): string | undefined {
if (!assistant.warnings?.length) return undefined
return [
'Assistant Mode was updated, but some generated instruction changes were not applied.',
'',
...assistant.warnings.map((warning) => `- ${warning.message}`),
].join('\n')
}
function buildAssistantWelcomePrompt(assistant: AssistantModeStatus): string {
const warningsPrompt = buildAssistantModeWarningsPrompt(assistant)
return warningsPrompt
? `${ASSISTANT_WELCOME_PROMPT}\n\n${warningsPrompt}`
: ASSISTANT_WELCOME_PROMPT
}
async function sendAssistantWelcomePrompt(client: OpenCodeClient, sessionId: string, assistant: AssistantModeStatus): Promise<void> {
await client.sendPromptAsync(sessionId, {
parts: [
{
type: 'text',
text: buildAssistantWelcomePrompt(assistant),
},
],
}).catch(() => undefined)
}
async function sendAssistantModeWarningsPrompt(client: OpenCodeClient, sessionId: string, assistant: AssistantModeStatus): Promise<void> {
const warningsPrompt = buildAssistantModeWarningsPrompt(assistant)
if (!warningsPrompt) return
await client.sendPromptAsync(sessionId, {
parts: [
{
type: 'text',
text: warningsPrompt,
},
],
}).catch(() => undefined)
}
export function useAssistantSessionLauncher({
repoId,
opcodeUrl,
@@ -34,30 +95,11 @@ export function useAssistantSessionLauncher({
if (newest) {
onNavigate(newest.id)
void sendAssistantModeWarningsPrompt(client, newest.id, assistant)
} else {
const session = await client.createSession({ title: 'Assistant' })
await client.sendPrompt(session.id, {
parts: [
{
type: 'text',
text: `Welcome to OpenCode Manager! I'm your assistant and I'm here to help you work with your code.
To get started, let's set up your assistant:
**1. Name your assistant**
What would you like to call me? This name will help personalize our interactions.
**2. Configure AGENTS.md**
This file contains instructions that define my behavior, persona, and preferences. You can customize it to match your workflow. Take a moment to review and edit it - you can always adjust it later.
**3. Set up your v file (optional)**
The v file stores conversation state and context between sessions. This helps me maintain memory of our work together.
Take your time exploring and customizing these settings. Let me know when you're ready to start coding, or if you have any questions about getting set up!`,
},
],
})
onNavigate(session.id)
void sendAssistantWelcomePrompt(client, session.id, assistant)
}
}, [repoId, opcodeUrl, onNavigate])
+22 -18
View File
@@ -1,7 +1,6 @@
import { useMemo } from 'react'
import { useMessages } from './useOpenCode'
import { useQuery } from '@tanstack/react-query'
import { useModelSelection } from './useModelSelection'
import { fetchWrapper } from '@/api/fetchWrapper'
interface ContextUsage {
@@ -39,8 +38,6 @@ async function fetchProviders(opcodeUrl: string): Promise<ProvidersResponse> {
export const useContextUsage = (opcodeUrl: string | null | undefined, sessionID: string | undefined, directory?: string): ContextUsage => {
const { data: messages, isLoading: messagesLoading } = useMessages(opcodeUrl, sessionID, directory)
const { modelString: globalModelString } = useModelSelection(opcodeUrl, directory)
const modelString = globalModelString
const { data: providersData } = useQuery({
queryKey: ['providers', opcodeUrl],
@@ -53,19 +50,30 @@ export const useContextUsage = (opcodeUrl: string | null | undefined, sessionID:
})
return useMemo(() => {
const currentModel = modelString || null
const assistantMessages = messages?.filter(msg => msg.info.role === 'assistant') || []
let latestAssistantMessage = assistantMessages[assistantMessages.length - 1]
if (latestAssistantMessage?.info.role === 'assistant') {
const msgInfo = latestAssistantMessage.info as { tokens?: { input: number; output: number; reasoning: number; cache?: { read: number } } }
const tokens = (msgInfo.tokens?.input ?? 0) + (msgInfo.tokens?.output ?? 0) + (msgInfo.tokens?.reasoning ?? 0) + (msgInfo.tokens?.cache?.read ?? 0)
if (tokens === 0 && assistantMessages.length > 1) {
latestAssistantMessage = assistantMessages[assistantMessages.length - 2]
}
const sumTokens = (msg: typeof latestAssistantMessage) => {
if (msg?.info.role !== 'assistant') return 0
const msgInfo = msg.info as { tokens?: { input: number; output: number; reasoning: number; cache?: { read: number } } }
return (msgInfo.tokens?.input ?? 0) + (msgInfo.tokens?.output ?? 0) + (msgInfo.tokens?.reasoning ?? 0) + (msgInfo.tokens?.cache?.read ?? 0)
}
if (sumTokens(latestAssistantMessage) === 0 && assistantMessages.length > 1) {
latestAssistantMessage = assistantMessages[assistantMessages.length - 2]
}
const currentModel = (() => {
if (!latestAssistantMessage || latestAssistantMessage.info.role !== 'assistant') {
return null
}
const msg = latestAssistantMessage.info as { providerID?: string; modelID?: string }
if (msg.providerID && msg.modelID) {
return `${msg.providerID}/${msg.modelID}`
}
return null
})()
let contextLimit: number | null = null
if (currentModel && providersData) {
const [providerId, modelId] = currentModel.split('/')
@@ -88,11 +96,7 @@ export const useContextUsage = (opcodeUrl: string | null | undefined, sessionID:
}
}
let totalTokens = 0
if (latestAssistantMessage?.info.role === 'assistant') {
const msgInfo = latestAssistantMessage.info as { tokens?: { input: number; output: number; reasoning: number; cache?: { read: number } } }
totalTokens = (msgInfo.tokens?.input ?? 0) + (msgInfo.tokens?.output ?? 0) + (msgInfo.tokens?.reasoning ?? 0) + (msgInfo.tokens?.cache?.read ?? 0)
}
const totalTokens = sumTokens(latestAssistantMessage)
const usagePercentage = contextLimit ? (totalTokens / contextLimit) * 100 : null
@@ -103,5 +107,5 @@ export const useContextUsage = (opcodeUrl: string | null | undefined, sessionID:
currentModel,
isLoading: false
}
}, [messages, messagesLoading, modelString, providersData])
}, [messages, messagesLoading, providersData])
}
+35
View File
@@ -101,6 +101,41 @@ describe('useSwipeBack', () => {
document.body.removeChild(element)
})
it('does not call onBack when canBack was false at swipe start', () => {
mockCanBack.mockReturnValueOnce(false).mockReturnValue(true)
const element = document.createElement('div')
document.body.appendChild(element)
const { result } = renderHook(() =>
useSwipeBack(mockOnClose, {
enabled: true,
canBack: mockCanBack,
onBack: mockOnBack,
threshold: 80,
})
)
const cleanup = result.current.bind(element)
element.dispatchEvent(new TouchEvent('touchstart', {
touches: [{ clientX: 10, clientY: 100 }] as any,
}))
element.dispatchEvent(new TouchEvent('touchmove', {
touches: [{ clientX: 100, clientY: 100 }] as any,
}))
element.dispatchEvent(new TouchEvent('touchend', {
changedTouches: [{ clientX: 100, clientY: 100 }] as any,
}))
expect(mockCanBack).toHaveBeenCalledTimes(1)
expect(mockOnBack).not.toHaveBeenCalled()
expect(mockOnClose).toHaveBeenCalled()
cleanup?.()
document.body.removeChild(element)
})
it('falls back to onClose when canBack is not provided', () => {
const { result } = renderHook(() =>
useSwipeBack(mockOnClose, {
+8 -3
View File
@@ -68,6 +68,7 @@ function useSwipeHandlers(
isEdgeSwipe: boolean
startTime: number
blockedByScroll: boolean
canBackAtStart: boolean
}>({
startX: 0,
startY: 0,
@@ -77,6 +78,7 @@ function useSwipeHandlers(
isEdgeSwipe: false,
startTime: 0,
blockedByScroll: false,
canBackAtStart: true,
})
const [swipeProgress, setSwipeProgress] = useState(0)
const [swipeDeltaPx, setSwipeDeltaPx] = useState(0)
@@ -118,6 +120,7 @@ function useSwipeHandlers(
isEdgeSwipe: false,
startTime: Date.now(),
blockedByScroll: !!blockedByScroll,
canBackAtStart: canBack?.() ?? true,
}
} else {
swipeRef.current = {
@@ -129,9 +132,10 @@ function useSwipeHandlers(
isEdgeSwipe: touch.clientX <= edgeWidth,
startTime: Date.now(),
blockedByScroll: false,
canBackAtStart: canBack?.() ?? true,
}
}
}, [enabled, isMobile, edgeWidth, direction])
}, [enabled, isMobile, edgeWidth, direction, canBack])
const handleTouchMove = useCallback((e: TouchEvent) => {
if (!enabled || !isMobile) return
@@ -196,7 +200,7 @@ function useSwipeHandlers(
if (deltaY >= threshold || velocity >= velocityThreshold) {
setDismissing(true)
setTimeout(() => {
if (canBack?.()) {
if (state.canBackAtStart && canBack?.()) {
onBack?.()
} else {
onClose()
@@ -209,7 +213,7 @@ function useSwipeHandlers(
} else {
const deltaX = state.currentX - state.startX
if (deltaX >= threshold) {
if (canBack?.()) {
if (state.canBackAtStart && canBack?.()) {
onBack?.()
} else {
onClose()
@@ -231,6 +235,7 @@ function useSwipeHandlers(
isEdgeSwipe: false,
startTime: 0,
blockedByScroll: false,
canBackAtStart: true,
}
}, [enabled, isMobile, threshold, direction, velocityThreshold, onClose, canBack, onBack])
+22 -3
View File
@@ -25,6 +25,9 @@ export function useSTT(userId = 'default') {
const lastProcessedBlobRef = useRef<Blob | null>(null)
const startupTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const startOpIdRef = useRef(0)
const recorderConfiguredRef = useRef(false)
const interimRafRef = useRef<number | null>(null)
const pendingInterimRef = useRef<string>('')
useEffect(() => {
userIdRef.current = userId
@@ -51,12 +54,21 @@ export function useSTT(userId = 'default') {
rec.onResult((result: SpeechRecognitionResult) => {
setIsProcessing(false)
setTranscript((prev) => prev + ' ' + result.transcript)
setTranscript((prev) => {
const prevTrimmed = prev.trim()
const next = result.transcript.trim()
return prevTrimmed ? `${prevTrimmed} ${next}` : next
})
setIsRecording(false)
})
rec.onInterimResult((interim: string) => {
setInterimTranscript(interim.trim())
pendingInterimRef.current = interim.trim()
if (interimRafRef.current != null) return
interimRafRef.current = requestAnimationFrame(() => {
interimRafRef.current = null
setInterimTranscript(pendingInterimRef.current)
})
})
rec.onError((errorMessage: string) => {
@@ -88,6 +100,10 @@ export function useSTT(userId = 'default') {
return () => {
rec.clearCallbacks()
if (interimRafRef.current != null) {
cancelAnimationFrame(interimRafRef.current)
interimRafRef.current = null
}
}
}, [isEnabled, isExternalProvider])
@@ -178,7 +194,10 @@ export function useSTT(userId = 'default') {
audioRecorder.current = new AudioRecorder()
}
setupAudioRecorder(audioRecorder.current)
if (!recorderConfiguredRef.current) {
setupAudioRecorder(audioRecorder.current)
recorderConfiguredRef.current = true
}
return () => {
if (audioRecorder.current) {
@@ -99,6 +99,12 @@ describe('resolveDefaultSessionAgent', () => {
const result = resolveDefaultSessionAgent('missing-agent', agents, true)
expect(result).toBe('build')
})
it('returns assistant when assistant workspace config sets default_agent to assistant', () => {
const agents = [{ name: 'assistant', mode: 'primary' }]
const result = resolveDefaultSessionAgent('assistant', agents, true)
expect(result).toBe('assistant')
})
})
describe('useSessionAgent', () => {
+33
View File
@@ -0,0 +1,33 @@
import { useQuery } from '@tanstack/react-query'
import { getRepo } from '@/api/repos'
import { useAssistantMode } from '@/hooks/useAssistantMode'
import { isAssistantRepoId, workspaceFromAssistant, workspaceFromRepo } from '@/lib/schedules/workspace'
import type { Workspace } from '@/lib/schedules/workspace'
export function useWorkspace(repoId: number | undefined): {
workspace: Workspace | undefined
isLoading: boolean
isError: boolean
} {
const assistantQuery = useAssistantMode(repoId)
const repoQuery = useQuery({
queryKey: ['repo', repoId],
queryFn: () => getRepo(repoId!),
enabled: repoId !== undefined && repoId > 0,
})
if (isAssistantRepoId(repoId)) {
return {
workspace: assistantQuery.status ? workspaceFromAssistant(assistantQuery.status) : undefined,
isLoading: assistantQuery.isLoading,
isError: assistantQuery.isError,
}
}
return {
workspace: repoQuery.data ? workspaceFromRepo(repoQuery.data) : undefined,
isLoading: repoQuery.isLoading,
isError: repoQuery.isError,
}
}
+2
View File
@@ -43,6 +43,7 @@
html {
background-color: #0a0a0a;
min-height: calc(100% + env(safe-area-inset-top));
overscroll-behavior-x: none;
}
:root:not(.dark) html {
@@ -58,6 +59,7 @@ body {
overflow: hidden;
position: fixed;
width: 100%;
overscroll-behavior-x: none;
}
#root {
+152
View File
@@ -0,0 +1,152 @@
import { describe, it, expect } from 'vitest'
import { AudioRecorder, downsampleAndConvert, encodeWavFromInt16 } from './audioRecorder'
describe('downsampleAndConvert', () => {
it('should produce correct output length for 48kHz to 16kHz', () => {
const inputLength = 4800
const input = new Float32Array(inputLength)
const output = downsampleAndConvert(input, 48000, 16000)
const expectedLength = Math.floor(inputLength * 16000 / 48000)
expect(output.length).toBe(expectedLength)
expect(output.length).toBe(inputLength / 3)
})
it('should produce correct output length for 44.1kHz to 16kHz', () => {
const inputLength = 4410
const input = new Float32Array(inputLength)
const output = downsampleAndConvert(input, 44100, 16000)
const expectedLength = Math.floor(inputLength * 16000 / 44100)
expect(output.length).toBeCloseTo(expectedLength, 0)
})
it('should clamp values in range [-1, 1] to Int16 range', () => {
const input = new Float32Array([1.0, -1.0, 0.5, -0.5, 0.0])
const output = downsampleAndConvert(input, 16000, 16000)
expect(output[0]).toBe(32767)
expect(output[1]).toBe(-32768)
expect(output[2]).toBeCloseTo(16383, 0)
expect(output[3]).toBeCloseTo(-16384, 0)
expect(output[4]).toBe(0)
})
it('should clamp values outside [-1, 1] range', () => {
const input = new Float32Array([1.5, -1.5, 2.0, -2.0])
const output = downsampleAndConvert(input, 16000, 16000)
expect(output[0]).toBe(32767)
expect(output[1]).toBe(-32768)
expect(output[2]).toBe(32767)
expect(output[3]).toBe(-32768)
})
it('should return Int16Array type', () => {
const input = new Float32Array(100)
const output = downsampleAndConvert(input, 48000, 16000)
expect(output instanceof Int16Array).toBe(true)
})
})
describe('encodeWavFromInt16', () => {
it('should create a Blob with audio/wav type', () => {
const samples = new Int16Array(1000)
const blob = encodeWavFromInt16(samples, 16000, 1)
expect(blob.type).toBe('audio/wav')
})
it('should have RIFF header at offset 0', async () => {
const samples = new Int16Array(1000)
const blob = encodeWavFromInt16(samples, 16000, 1)
const arrayBuffer = await blob.arrayBuffer()
const view = new DataView(arrayBuffer)
const riff = String.fromCharCode(
view.getUint8(0),
view.getUint8(1),
view.getUint8(2),
view.getUint8(3)
)
expect(riff).toBe('RIFF')
})
it('should have WAVE identifier at offset 8', async () => {
const samples = new Int16Array(1000)
const blob = encodeWavFromInt16(samples, 16000, 1)
const arrayBuffer = await blob.arrayBuffer()
const view = new DataView(arrayBuffer)
const wave = String.fromCharCode(
view.getUint8(8),
view.getUint8(9),
view.getUint8(10),
view.getUint8(11)
)
expect(wave).toBe('WAVE')
})
it('should have sample rate at offset 24', async () => {
const samples = new Int16Array(1000)
const blob = encodeWavFromInt16(samples, 16000, 1)
const arrayBuffer = await blob.arrayBuffer()
const view = new DataView(arrayBuffer)
const sampleRate = view.getUint32(24, true)
expect(sampleRate).toBe(16000)
})
it('should have data identifier at offset 36', async () => {
const samples = new Int16Array(1000)
const blob = encodeWavFromInt16(samples, 16000, 1)
const arrayBuffer = await blob.arrayBuffer()
const view = new DataView(arrayBuffer)
const data = String.fromCharCode(
view.getUint8(36),
view.getUint8(37),
view.getUint8(38),
view.getUint8(39)
)
expect(data).toBe('data')
})
it('should have correct file size for 1000 samples', async () => {
const samples = new Int16Array(1000)
const blob = encodeWavFromInt16(samples, 16000, 1)
const arrayBuffer = await blob.arrayBuffer()
expect(arrayBuffer.byteLength).toBe(44 + 1000 * 2)
})
it('should handle different sample rates', async () => {
const samples = new Int16Array(1000)
const blob = encodeWavFromInt16(samples, 44100, 1)
const arrayBuffer = await blob.arrayBuffer()
const view = new DataView(arrayBuffer)
const sampleRate = view.getUint32(24, true)
expect(sampleRate).toBe(44100)
})
it('should handle stereo channels', async () => {
const samples = new Int16Array(1000)
const blob = encodeWavFromInt16(samples, 16000, 2)
const arrayBuffer = await blob.arrayBuffer()
const view = new DataView(arrayBuffer)
const channels = view.getUint16(22, true)
expect(channels).toBe(2)
})
})
describe('AudioRecorder.isSupported', () => {
it('should return boolean without throwing', () => {
expect(() => {
const result = AudioRecorder.isSupported()
expect(typeof result).toBe('boolean')
}).not.toThrow()
})
})
+65 -89
View File
@@ -10,54 +10,68 @@ const DEFAULT_OPTIONS: AudioRecorderOptions = {
channelCount: 1,
}
function encodeWAV(audioBuffer: AudioBuffer): Blob {
const numberOfChannels = audioBuffer.numberOfChannels
const sampleRate = audioBuffer.sampleRate
const format = 1
const bitDepth = 16
const workletModulePromises = new WeakMap<AudioContext, Promise<void>>()
const channelData: Float32Array[] = []
function ensureWorkletLoaded(ctx: AudioContext): Promise<void> {
const existingPromise = workletModulePromises.get(ctx)
for (let i = 0; i < numberOfChannels; i++) {
channelData.push(audioBuffer.getChannelData(i))
if (existingPromise) {
return existingPromise
}
const interleaved = interleave(channelData)
const dataLength = interleaved.length * (bitDepth / 8)
const buffer = new ArrayBuffer(44 + dataLength)
const view = new DataView(buffer)
const promise = ctx.audioWorklet.addModule('/audio-worklet-processor.js')
workletModulePromises.set(ctx, promise)
return promise
}
export function downsampleAndConvert(input: Float32Array, inputRate: number, targetRate: number): Int16Array {
const ratio = inputRate / targetRate
const outputLength = Math.floor(input.length / ratio)
const output = new Int16Array(outputLength)
for (let i = 0; i < outputLength; i++) {
const index = i * ratio
const prevIndex = Math.floor(index)
const nextIndex = prevIndex + 1
const t = index - prevIndex
let sample: number
if (nextIndex >= input.length) {
sample = input[prevIndex]
} else {
sample = input[prevIndex] * (1 - t) + input[nextIndex] * t
}
const clamped = Math.max(-1, Math.min(1, sample))
output[i] = clamped < 0 ? clamped * 32768 : clamped * 32767
}
return output
}
export function encodeWavFromInt16(samples: Int16Array, sampleRate: number, channels: number): Blob {
const dataLength = samples.length * 2
const bufferSize = 44 + dataLength
const buffer = new ArrayBuffer(bufferSize)
const view = new DataView(buffer)
writeString(view, 0, 'RIFF')
view.setUint32(4, 36 + dataLength, true)
writeString(view, 8, 'WAVE')
writeString(view, 12, 'fmt ')
view.setUint32(16, 16, true)
view.setUint16(20, format, true)
view.setUint16(22, numberOfChannels, true)
view.setUint16(20, 1, true)
view.setUint16(22, channels, true)
view.setUint32(24, sampleRate, true)
view.setUint32(28, sampleRate * numberOfChannels * (bitDepth / 8), true)
view.setUint16(32, numberOfChannels * (bitDepth / 8), true)
view.setUint16(34, bitDepth, true)
view.setUint32(28, sampleRate * channels * 2, true)
view.setUint16(32, channels * 2, true)
view.setUint16(34, 16, true)
writeString(view, 36, 'data')
view.setUint32(40, dataLength, true)
floatTo16BitPCM(view, 44, interleaved)
return new Blob([view], { type: 'audio/wav' })
}
function interleave(channelData: Float32Array[]): Float32Array {
const length = channelData[0].length * channelData.length
const result = new Float32Array(length)
let offset = 0
for (let i = 0; i < channelData[0].length; i++) {
for (let channel = 0; channel < channelData.length; channel++) {
result[offset++] = channelData[channel][i]
}
}
return result
new Int16Array(buffer, 44).set(samples)
return new Blob([buffer], { type: 'audio/wav' })
}
function writeString(view: DataView, offset: number, string: string): void {
@@ -66,20 +80,13 @@ function writeString(view: DataView, offset: number, string: string): void {
}
}
function floatTo16BitPCM(view: DataView, offset: number, input: Float32Array): void {
for (let i = 0; i < input.length; i++, offset += 2) {
const s = Math.max(-1, Math.min(1, input[i]))
view.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7fff, true)
}
}
export class AudioRecorder {
private audioContext: AudioContext | null = null
private mediaStream: MediaStream | null = null
private source: MediaStreamAudioSourceNode | null = null
private processor: ScriptProcessorNode | null = null
private workletNode: AudioWorkletNode | null = null
private chunks: Float32Array[] = []
private chunks: Int16Array[] = []
private totalSamples: number = 0
private state: AudioRecorderState = 'idle'
private options: AudioRecorderOptions
@@ -152,29 +159,32 @@ export class AudioRecorder {
if (this.audioContext.audioWorklet) {
try {
await this.audioContext.audioWorklet.addModule('/audio-worklet-processor.js')
this.workletNode = new AudioWorkletNode(this.audioContext, 'recorder-processor')
this.workletNode.port.onmessage = (e: MessageEvent<Float32Array>) => {
await ensureWorkletLoaded(this.audioContext)
this.workletNode = new AudioWorkletNode(this.audioContext, 'recorder-processor', {
processorOptions: { targetSampleRate: this.options.sampleRate },
})
this.workletNode.port.onmessage = (e: MessageEvent<Int16Array>) => {
this.chunks.push(e.data)
this.totalSamples += e.data.length
}
this.source.connect(this.workletNode)
this.workletNode.connect(this.audioContext.destination)
} catch {
} catch (error) {
this.audioContext.close()
this.audioContext = null
throw new Error('Failed to load audio worklet processor')
throw new Error('Failed to load audio worklet processor', { cause: error })
}
} else if (this.audioContext) {
const bufferSize = 4096
this.processor = this.audioContext.createScriptProcessor(bufferSize, 1, 1)
const targetRate = this.options.sampleRate ?? 16000
const inputRate = this.audioContext.sampleRate
this.processor.onaudioprocess = (e) => {
const inputData = new Float32Array(e.inputBuffer.getChannelData(0))
this.chunks.push(inputData)
this.totalSamples += inputData.length
const inputData = e.inputBuffer.getChannelData(0)
const int16Chunk = downsampleAndConvert(inputData, inputRate, targetRate)
this.chunks.push(int16Chunk)
this.totalSamples += int16Chunk.length
}
this.source.connect(this.processor)
this.processor.connect(this.audioContext.destination)
}
this.setState('recording')
@@ -220,21 +230,13 @@ export class AudioRecorder {
}
try {
const merged = new Float32Array(this.totalSamples)
const merged = new Int16Array(this.totalSamples)
let offset = 0
for (const chunk of this.chunks) {
merged.set(chunk, offset)
offset += chunk.length
}
const audioBuffer = this.audioContext!.createBuffer(
1,
this.totalSamples,
this.audioContext!.sampleRate
)
audioBuffer.copyToChannel(merged, 0)
const wavBlob = encodeWAV(audioBuffer)
const wavBlob = encodeWavFromInt16(merged, this.options.sampleRate ?? 16000, 1)
this.onDataAvailable?.(wavBlob)
} catch {
this.onError?.('Failed to process recording')
@@ -276,30 +278,4 @@ export class AudioRecorder {
this.chunks = []
this.totalSamples = 0
}
getRecordingBlob(): Blob | null {
if (!this.audioContext || this.chunks.length === 0 || this.totalSamples === 0) {
return null
}
try {
const merged = new Float32Array(this.totalSamples)
let offset = 0
for (const chunk of this.chunks) {
merged.set(chunk, offset)
offset += chunk.length
}
const audioBuffer = this.audioContext.createBuffer(
1,
this.totalSamples,
this.audioContext.sampleRate
)
audioBuffer.copyToChannel(merged, 0)
return encodeWAV(audioBuffer)
} catch {
return null
}
}
}
+57 -11
View File
@@ -1,5 +1,39 @@
import { describe, it, expect } from 'vitest';
import { getSessionListPath, getSwipeBackTarget } from './navigation';
import { getSessionListPath, getSwipeBackTarget, getAssistantPath, getAssistantSessionListPath, isAssistantPath } from './navigation';
describe('getAssistantPath', () => {
it('returns /assistant', () => {
expect(getAssistantPath()).toBe('/assistant');
});
});
describe('getAssistantSessionListPath', () => {
it('returns /assistant?view=sessions', () => {
expect(getAssistantSessionListPath()).toBe('/assistant?view=sessions');
});
});
describe('isAssistantPath', () => {
it('returns true for /assistant', () => {
expect(isAssistantPath('/assistant')).toBe(true);
});
it('returns true for legacy /repos/0/assistant', () => {
expect(isAssistantPath('/repos/0/assistant')).toBe(true);
});
it('returns true for legacy /repos/5/assistant', () => {
expect(isAssistantPath('/repos/5/assistant')).toBe(true);
});
it('returns false for /repos/5', () => {
expect(isAssistantPath('/repos/5')).toBe(false);
});
it('returns false for /schedules', () => {
expect(isAssistantPath('/schedules')).toBe(false);
});
});
describe('getSessionListPath', () => {
it('returns repo path for non-assistant sessions', () => {
@@ -7,9 +41,9 @@ describe('getSessionListPath', () => {
expect(getSessionListPath('123', false)).toBe('/repos/123');
});
it('returns assistant path with view=sessions for assistant sessions', () => {
expect(getSessionListPath(42, true)).toBe('/repos/42/assistant?view=sessions');
expect(getSessionListPath('123', true)).toBe('/repos/123/assistant?view=sessions');
it('returns assistant session list path for assistant sessions', () => {
expect(getSessionListPath(42, true)).toBe('/assistant?view=sessions');
expect(getSessionListPath('123', true)).toBe('/assistant?view=sessions');
});
});
@@ -20,12 +54,12 @@ describe('getSwipeBackTarget', () => {
expect(getSwipeBackTarget('/repos/123/sessions/xyz-789', '')).toBe('/repos/123');
});
it('returns assistant path for assistant session detail with assistant=1', () => {
it('returns assistant session list path for assistant session detail with assistant=1', () => {
expect(getSwipeBackTarget('/repos/42/sessions/abc', '?assistant=1')).toBe(
'/repos/42/assistant?view=sessions'
'/assistant?view=sessions'
);
expect(getSwipeBackTarget('/repos/123/sessions/xyz', '?assistant=1')).toBe(
'/repos/123/assistant?view=sessions'
'/assistant?view=sessions'
);
});
@@ -36,12 +70,20 @@ describe('getSwipeBackTarget', () => {
});
describe('assistant route', () => {
it('returns assistant sessions path for assistant route', () => {
expect(getSwipeBackTarget('/repos/123/assistant', '')).toBe('/repos/123/assistant?view=sessions');
it('returns assistant session list path for canonical assistant route', () => {
expect(getSwipeBackTarget('/assistant', '')).toBe('/assistant?view=sessions');
});
it('returns repo path for assistant session list route', () => {
expect(getSwipeBackTarget('/repos/42/assistant', '?view=sessions')).toBe('/repos/42');
it('returns root for assistant session list route', () => {
expect(getSwipeBackTarget('/assistant', '?view=sessions')).toBe('/');
});
it('returns assistant session list path for legacy assistant route', () => {
expect(getSwipeBackTarget('/repos/123/assistant', '')).toBe('/assistant?view=sessions');
});
it('returns root for legacy assistant session list route', () => {
expect(getSwipeBackTarget('/repos/42/assistant', '?view=sessions')).toBe('/');
});
});
@@ -53,6 +95,10 @@ describe('getSwipeBackTarget', () => {
});
describe('schedules routes', () => {
it('returns /assistant for assistant schedules', () => {
expect(getSwipeBackTarget('/repos/0/schedules', '')).toBe('/assistant');
});
it('returns repo path for repo schedules', () => {
expect(getSwipeBackTarget('/repos/42/schedules', '')).toBe('/repos/42');
});
+20 -7
View File
@@ -1,9 +1,20 @@
export function getAssistantPath(): string {
return '/assistant';
}
export function getAssistantSessionListPath(): string {
return '/assistant?view=sessions';
}
export function isAssistantPath(pathname: string): boolean {
return pathname === '/assistant' || /^\/repos\/[^/]+\/assistant$/.test(pathname);
}
export function getSessionListPath(repoId: string | number, isAssistantSession: boolean): string {
const id = String(repoId);
if (isAssistantSession) {
return `/repos/${id}/assistant?view=sessions`;
return getAssistantSessionListPath();
}
return `/repos/${id}`;
return `/repos/${String(repoId)}`;
}
export function getSwipeBackTarget(pathname: string, search = ''): string | null {
@@ -17,13 +28,12 @@ export function getSwipeBackTarget(pathname: string, search = ''): string | null
return getSessionListPath(repoId, isAssistant);
}
if (pathname === '/repos/:id/assistant' || /^\/repos\/[^/]+\/assistant$/.test(pathname)) {
const repoId = pathname.split('/')[2];
if (isAssistantPath(pathname)) {
const params = new URLSearchParams(search);
if (params.get('view') !== 'sessions') {
return getSessionListPath(repoId, true);
return getAssistantSessionListPath();
}
return `/repos/${repoId}`;
return '/';
}
if (/^\/repos\/[^/]+$/.test(pathname)) {
@@ -32,6 +42,9 @@ export function getSwipeBackTarget(pathname: string, search = ''): string | null
if (/^\/repos\/[^/]+\/schedules$/.test(pathname)) {
const repoId = pathname.split('/')[2];
if (repoId === '0') {
return getAssistantPath();
}
return `/repos/${repoId}`;
}
@@ -0,0 +1,73 @@
import { describe, it, expect } from 'vitest'
import {
isAssistantRepoId,
workspaceFromRepo,
workspaceFromAssistant,
} from './workspace'
import type { AssistantModeStatus } from '@opencode-manager/shared/types'
describe('isAssistantRepoId', () => {
it('returns true for repoId 0', () => {
expect(isAssistantRepoId(0)).toBe(true)
})
it('returns false for positive repoId', () => {
expect(isAssistantRepoId(5)).toBe(false)
})
it('returns false for undefined', () => {
expect(isAssistantRepoId(undefined)).toBe(false)
})
})
describe('workspaceFromRepo', () => {
it('returns correct workspace for a repo', () => {
const repo = {
id: 5,
repoUrl: 'https://x/y',
localPath: 'y',
fullPath: '/abs/y',
sourcePath: undefined,
defaultBranch: 'main',
cloneStatus: 'ready' as const,
clonedAt: 0,
}
const workspace = workspaceFromRepo(repo)
expect(workspace).toEqual({
repoId: 5,
kind: 'repo',
name: 'y',
subtitle: 'y',
fullPath: '/abs/y',
backHref: '/repos/5',
})
})
})
describe('workspaceFromAssistant', () => {
it('returns correct workspace for assistant', () => {
const status: AssistantModeStatus = {
repoId: 0,
directory: '/abs/assistant',
relativePath: 'repos/assistant',
files: {
agentsMd: { path: '', exists: false, created: false },
opencodeJson: { path: '', exists: false, created: false },
},
schedulesSkill: { path: '', exists: false, created: false },
}
const workspace = workspaceFromAssistant(status)
expect(workspace).toEqual({
repoId: 0,
kind: 'assistant',
name: 'Assistant',
subtitle: 'Assistant Workspace',
fullPath: '/abs/assistant',
backHref: '/assistant',
})
})
})
+41
View File
@@ -0,0 +1,41 @@
import type { Repo } from '@/api/types'
import type { AssistantModeStatus } from '@opencode-manager/shared/types'
import { getRepoDisplayName } from '@/lib/utils'
import { getAssistantPath } from '@/lib/navigation'
export interface Workspace {
repoId: number
kind: 'assistant' | 'repo'
name: string
subtitle: string
fullPath: string
backHref: string
}
export const ASSISTANT_REPO_ID = 0
export function isAssistantRepoId(repoId: number | undefined): boolean {
return repoId === ASSISTANT_REPO_ID
}
export function workspaceFromRepo(repo: Repo): Workspace {
return {
repoId: repo.id,
kind: 'repo',
name: getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath),
subtitle: repo.localPath,
fullPath: repo.fullPath,
backHref: `/repos/${repo.id}`,
}
}
export function workspaceFromAssistant(status: AssistantModeStatus): Workspace {
return {
repoId: ASSISTANT_REPO_ID,
kind: 'assistant',
name: 'Assistant',
subtitle: 'Assistant Workspace',
fullPath: status.directory,
backHref: getAssistantPath(),
}
}
+27 -13
View File
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useState } from "react"
import { useParams, useNavigate, useLocation } from "react-router-dom"
import { useQuery, useQueryClient } from "@tanstack/react-query"
import { getRepo, initializeAssistantMode, listRepos } from "@/api/repos"
import { getRepo, initializeAssistantMode } from "@/api/repos"
import { useAssistantSessionLauncher } from "@/hooks/useAssistantSessionLauncher"
import { useCreateSession } from "@/hooks/useOpenCode"
import { useDialogParam } from "@/hooks/useDialogParam"
@@ -17,7 +17,7 @@ import { SourceControlPanel } from "@/components/source-control"
import { ResetPermissionsDialog } from "@/components/repo/ResetPermissionsDialog"
import { PendingActionsGroup } from "@/components/notifications/PendingActionsGroup"
import { invalidateConfigCaches } from "@/lib/queryInvalidation"
import { getSessionListPath } from "@/lib/navigation"
import { getSessionListPath, getAssistantPath } from "@/lib/navigation"
import { SwitchConfigDialog } from "@/components/repo/SwitchConfigDialog"
import { Loader2, Plus } from "lucide-react"
@@ -41,7 +41,7 @@ export function AssistantRedirect() {
const { data: repo } = useQuery({
queryKey: ["repo", repoId],
queryFn: () => getRepo(repoId),
enabled: showSessionList && !!repoId,
enabled: showSessionList && repoId !== undefined,
})
const handleNavigate = useCallback((sessionId: string) => {
@@ -61,7 +61,7 @@ export function AssistantRedirect() {
const { data: assistantMode, isLoading: assistantModeLoading, error: assistantModeError } = useQuery({
queryKey: ["repo", repoId, "assistant-mode"],
queryFn: () => initializeAssistantMode(repoId),
enabled: showSessionList && !!repoId,
enabled: showSessionList && repoId !== undefined,
})
const assistantDirectory = assistantMode?.directory
@@ -84,11 +84,10 @@ export function AssistantRedirect() {
try {
if (showSessionList) return
setStatus("preparing")
if (!repoId) {
const repos = await listRepos()
const fallbackRepo = repos.sort((a, b) => (b.lastAccessedAt ?? 0) - (a.lastAccessedAt ?? 0))[0]
if (!fallbackRepo) throw new Error("No repository available to open Assistant")
navigate(`/repos/${fallbackRepo.id}/assistant`, { replace: true })
if (repoId <= 0) {
if (cancelled) return
setStatus("creating")
await openAssistant()
return
}
@@ -108,13 +107,13 @@ export function AssistantRedirect() {
return () => {
cancelled = true
}
}, [repoId, openAssistant, navigate, showSessionList])
}, [repoId, openAssistant, navigate, showSessionList, id])
if (showSessionList) {
return (
<div className="h-dvh max-h-dvh overflow-hidden bg-gradient-to-br from-background via-background to-background flex flex-col pb-[calc(env(safe-area-inset-bottom)+56px)] sm:pb-0">
<Header>
<Header.BackButton to={`/repos/${repoId}`} />
<Header.BackButton to={getAssistantPath()} />
<Header.Title>Assistant</Header.Title>
<Header.Actions>
<div className="flex items-center gap-1">
@@ -146,7 +145,22 @@ export function AssistantRedirect() {
<>
<FileBrowserSheet isOpen={fileBrowserOpen} onClose={() => setFileBrowserOpen(false)} basePath={assistantFileBasePath} repoName="Assistant" repoId={repoId} />
<RepoMcpDialog open={mcpDialogOpen} onOpenChange={setMcpDialogOpen} directory={assistantDirectory} />
<RepoSkillsDialog open={skillsDialogOpen} onOpenChange={setSkillsDialogOpen} repoId={repoId} />
{assistantDirectory && opcodeUrl ? (
<RepoSkillsDialog
open={skillsDialogOpen}
onOpenChange={setSkillsDialogOpen}
repoId={repoId}
sessionId="assistant-session"
opcodeUrl={opcodeUrl}
directory={assistantDirectory}
/>
) : (
<RepoSkillsDialog
open={skillsDialogOpen}
onOpenChange={setSkillsDialogOpen}
repoId={repoId}
/>
)}
<SourceControlPanel repoId={repoId} isOpen={sourceControlOpen} onClose={() => setSourceControlOpen(false)} currentBranch={repo?.currentBranch || repo?.branch || "main"} repoName="Assistant" />
<ResetPermissionsDialog open={resetPermissionsOpen} onOpenChange={setResetPermissionsOpen} repoId={repoId} repoDirectory={assistantDirectory} />
</>
@@ -174,7 +188,7 @@ export function AssistantRedirect() {
<>
<p className="text-muted-foreground mb-4">{errorMessage}</p>
<Button
onClick={() => navigate(`/repos/${repoId}`)}
onClick={() => navigate(getAssistantPath())}
variant="outline"
>
Go Back
+12 -17
View File
@@ -1,8 +1,6 @@
import { useEffect, useMemo, useState } from 'react'
import { useParams } from 'react-router-dom'
import { useQuery } from '@tanstack/react-query'
import type { CreateScheduleJobRequest, ScheduleJob } from '@opencode-manager/shared/types'
import { getRepo } from '@/api/repos'
import {
useCancelRepoScheduleRun,
useCreateRepoSchedule,
@@ -15,6 +13,7 @@ import {
useUpdateRepoSchedule,
} from '@/hooks/useSchedules'
import { useRepoActivity } from '@/hooks/useRepoActivity'
import { useWorkspace } from '@/hooks/useWorkspace'
import { ScheduleJobDialog, JobsTab, JobDetailTab, RunHistoryTab, ScheduleTabMenu } from '@/components/schedules'
import { useScheduleTab } from '@/hooks/useMobileTabBar'
import { toUpdateScheduleRequest, getJobStatusTone } from '@/components/schedules/schedule-utils'
@@ -23,7 +22,7 @@ import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent } from '@/components/ui/card'
import { DeleteDialog } from '@/components/ui/delete-dialog'
import { getRepoDisplayName, cn } from '@/lib/utils'
import { cn } from '@/lib/utils'
import { CalendarClock, Loader2, Plus } from 'lucide-react'
export function Schedules() {
@@ -36,13 +35,9 @@ export function Schedules() {
const [deleteJobId, setDeleteJobId] = useState<number | null>(null)
const { scheduleTab: activeTab, setScheduleTab: setActiveTab } = useScheduleTab()
const { data: repo, isLoading: repoLoading } = useQuery({
queryKey: ['repo', repoId],
queryFn: () => getRepo(repoId!),
enabled: repoId !== undefined,
})
const { workspace, isLoading: workspaceLoading } = useWorkspace(repoId)
useRepoActivity(repoId ?? 0, Boolean(repo))
useRepoActivity(repoId ?? 0, Boolean(workspace) && workspace?.kind === 'repo')
const { data: jobs, isLoading: jobsLoading } = useRepoSchedules(repoId)
const { data: selectedJob, isFetching: isJobFetching } = useRepoSchedule(repoId, selectedJobId)
@@ -87,7 +82,7 @@ export function Schedules() {
const activeRun = selectedRunDetails ?? activeRunSummary
const runningRun = useMemo(() => runs?.find((run) => run.status === 'running') ?? null, [runs])
if (repoLoading || jobsLoading) {
if (workspaceLoading || jobsLoading) {
return (
<div className="flex items-center justify-center min-h-screen bg-background">
<Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
@@ -95,15 +90,15 @@ export function Schedules() {
)
}
if (!repo || repoId === undefined) {
if (!workspace || repoId === undefined) {
return (
<div className="flex items-center justify-center min-h-screen bg-background">
<p className="text-muted-foreground">Repository not found</p>
<p className="text-muted-foreground">
{repoId === 0 ? 'Workspace not found' : 'Repository not found'}
</p>
</div>
)
}
const repoName = getRepoDisplayName(repo.repoUrl, repo.localPath)
const enabledCount = jobs?.filter((job) => job.enabled).length ?? 0
const hasJobs = (jobs?.length ?? 0) > 0
@@ -197,10 +192,10 @@ export function Schedules() {
return (
<div className="h-dvh max-h-dvh overflow-hidden bg-background flex flex-col pb-[calc(env(safe-area-inset-bottom)+56px)] sm:pb-0">
<Header>
<Header.BackButton to={`/repos/${repoId}`} />
<Header.BackButton to={workspace.backHref} />
<div className="min-w-0 flex-1 px-3">
<Header.Title className="truncate">Schedules</Header.Title>
<p className="text-xs text-muted-foreground truncate">{repoName}</p>
<Header.Title className="truncate">{workspace.name}</Header.Title>
<p className="text-xs text-muted-foreground truncate">{workspace.subtitle}</p>
</div>
<div className="flex items-center gap-2">
<Badge variant="outline" className="h-6 rounded-full px-2 text-xs">{jobs?.length ?? 0} jobs</Badge>
+12 -9
View File
@@ -118,14 +118,14 @@ export function SessionDetail() {
const { data: assistantMode, isLoading: assistantModeLoading } = useQuery({
queryKey: ["repo", repoId, "assistant-mode"],
queryFn: () => initializeAssistantMode(repoId),
enabled: isAssistantSession && !!repoId,
enabled: isAssistantSession,
});
useRepoActivity(repoId, Boolean(repo));
const opcodeUrl = OPENCODE_API_ENDPOINT;
const repoDirectory = isAssistantSession ? assistantMode?.directory : repo?.fullPath;
const repoDirectory = isAssistantSession ? (assistantMode?.directory || repo?.fullPath) : repo?.fullPath;
const sessionRouteSuffix = isAssistantSession ? '?assistant=1' : '';
const { isConnected, isReconnecting } = useSSE(opcodeUrl, repoDirectory, sessionId);
@@ -227,7 +227,7 @@ export function SessionDetail() {
const maxScrollTop = container.scrollHeight - container.clientHeight
const isAtBottom = maxScrollTop - currentScrollTop < 24
const isScrollingDown = currentScrollTop > previousScrollTop + 4
const isScrollingUp = currentScrollTop < previousScrollTop - 4
const isScrollingUp = currentScrollTop < previousScrollTop - 50
if (isAtBottom || isScrollingDown) {
setIsHeaderVisible(true)
@@ -438,7 +438,7 @@ export function SessionDetail() {
return <Navigate to="/" replace />;
}
if (!repo) {
if (!repo && !isAssistantSession) {
return (
<div className="flex items-center justify-center min-h-screen bg-gradient-to-br from-background via-background to-background">
<div className="flex flex-col items-center gap-2">
@@ -449,7 +449,9 @@ export function SessionDetail() {
);
}
const workspaceDisplayName = isAssistantSession ? 'Assistant' : getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath);
const workspaceDisplayName = isAssistantSession || !repo
? 'Assistant'
: getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath);
const sessionBackPath = getSessionListPath(repoId, isAssistantSession);
return (
@@ -457,9 +459,10 @@ export function SessionDetail() {
className="h-dvh max-h-dvh overflow-hidden bg-gradient-to-br from-background via-background to-background flex flex-col"
>
<div
data-testid="session-header-region"
className={`flex-shrink-0 overflow-hidden bg-background transition-all duration-200 ease-out ${
isHeaderVisible
? 'max-h-40 opacity-100 translate-y-0'
? 'max-h-72 sm:max-h-80 opacity-100 translate-y-0'
: 'max-h-0 opacity-0 -translate-y-2'
}`}
>
@@ -510,7 +513,7 @@ export function SessionDetail() {
</div>
</div>
<div className="flex-1 overflow-hidden flex flex-col">
<div className="relative flex-1 overflow-hidden flex flex-col">
<div key={sessionId} ref={messageContainerRef} className="flex-1 overflow-y-auto overflow-x-hidden overscroll-contain [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]" style={{ paddingBottom: promptOverlayHeight + inputBottomOffset + 16 }}>
{repoLoading || assistantModeLoading || sessionLoading || messagesLoading ? (
<MessageSkeleton />
@@ -643,7 +646,7 @@ export function SessionDetail() {
directory={repoDirectory}
/>
{repoDirectory && opcodeUrl && sessionId && (
{opcodeUrl && sessionId && (
<RepoSkillsDialog
open={skillsDialogOpen}
onOpenChange={setSkillsDialogOpen}
@@ -665,7 +668,7 @@ export function SessionDetail() {
repoId={repoId}
isOpen={sourceControlOpen}
onClose={() => setSourceControlOpen(false)}
currentBranch={repo.currentBranch || repo.branch || "main"}
currentBranch={repo?.currentBranch || repo?.branch || "main"}
repoName={workspaceDisplayName}
/>
@@ -0,0 +1,318 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { Schedules } from '../Schedules'
const mocks = vi.hoisted(() => ({
useWorkspace: vi.fn(),
useRepoSchedules: vi.fn(),
useRepoSchedule: vi.fn(),
useRepoScheduleRuns: vi.fn(),
useRepoScheduleRun: vi.fn(),
useCreateRepoSchedule: vi.fn(),
useUpdateRepoSchedule: vi.fn(),
useDeleteRepoSchedule: vi.fn(),
useRunRepoSchedule: vi.fn(),
useCancelRepoScheduleRun: vi.fn(),
useRepoActivity: vi.fn(),
useScheduleTab: vi.fn(),
}))
const mockNavigate = vi.fn()
vi.mock('react-router-dom', async (importOriginal) => ({
...(await importOriginal('react-router-dom')),
useNavigate: () => mockNavigate,
}))
vi.mock('@/hooks/useWorkspace', () => ({
useWorkspace: mocks.useWorkspace,
}))
vi.mock('@/hooks/useSchedules', () => ({
useRepoSchedules: mocks.useRepoSchedules,
useRepoSchedule: mocks.useRepoSchedule,
useRepoScheduleRuns: mocks.useRepoScheduleRuns,
useRepoScheduleRun: mocks.useRepoScheduleRun,
useCreateRepoSchedule: mocks.useCreateRepoSchedule,
useUpdateRepoSchedule: mocks.useUpdateRepoSchedule,
useDeleteRepoSchedule: mocks.useDeleteRepoSchedule,
useRunRepoSchedule: mocks.useRunRepoSchedule,
useCancelRepoScheduleRun: mocks.useCancelRepoScheduleRun,
}))
vi.mock('@/hooks/useRepoActivity', () => ({
useRepoActivity: mocks.useRepoActivity,
}))
vi.mock('@/hooks/useMobileTabBar', () => ({
useScheduleTab: mocks.useScheduleTab,
}))
vi.mock('@/components/schedules', () => ({
ScheduleJobDialog: vi.fn(() => <div>ScheduleJobDialog</div>),
JobsTab: vi.fn(({ onSelectJob }) => (
<div>
<button onClick={() => onSelectJob(123)} data-testid="select-job">Select Job</button>
</div>
)),
JobDetailTab: vi.fn(({ onRunNow }) => (
<div>
<button onClick={onRunNow} data-testid="run-now">Run Now</button>
</div>
)),
RunHistoryTab: vi.fn(() => <div>RunHistoryTab</div>),
ScheduleTabMenu: vi.fn(() => <div>ScheduleTabMenu</div>),
}))
const createWrapper = () => {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
mutations: { retry: false },
},
})
return ({ children }: { children: React.ReactNode }) =>
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
}
const renderSchedules = (repoId: string) => {
return render(
<MemoryRouter initialEntries={[`/repos/${repoId}/schedules`]}>
<Routes>
<Route path="/repos/:id/schedules" element={<Schedules />} />
</Routes>
</MemoryRouter>,
{ wrapper: createWrapper() }
)
}
describe('Schedules', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.useScheduleTab.mockReturnValue({
scheduleTab: 'jobs',
setScheduleTab: vi.fn(),
})
mocks.useCreateRepoSchedule.mockReturnValue({ mutate: vi.fn(), isPending: false })
mocks.useUpdateRepoSchedule.mockReturnValue({ mutate: vi.fn(), isPending: false })
mocks.useDeleteRepoSchedule.mockReturnValue({ mutate: vi.fn(), isPending: false })
mocks.useRunRepoSchedule.mockReturnValue({ mutate: vi.fn(), isPending: false })
mocks.useCancelRepoScheduleRun.mockReturnValue({ mutate: vi.fn(), isPending: false })
})
describe('assistant workspace (repoId=0)', () => {
it('renders assistant title and subtitle', () => {
mocks.useWorkspace.mockReturnValue({
workspace: {
repoId: 0,
kind: 'assistant',
name: 'Assistant',
subtitle: 'Assistant Workspace',
fullPath: '/abs/assistant',
backHref: '/assistant',
},
isLoading: false,
isError: false,
})
mocks.useRepoSchedules.mockReturnValue({ data: [], isLoading: false })
mocks.useRepoSchedule.mockReturnValue({ data: undefined, isFetching: false })
mocks.useRepoScheduleRuns.mockReturnValue({ data: [], isLoading: false })
mocks.useRepoScheduleRun.mockReturnValue({ data: undefined, isLoading: false })
renderSchedules('0')
expect(screen.getByText('Assistant')).toBeInTheDocument()
expect(screen.getByText('Assistant Workspace')).toBeInTheDocument()
})
it('does not render Repository not found', () => {
mocks.useWorkspace.mockReturnValue({
workspace: {
repoId: 0,
kind: 'assistant',
name: 'Assistant',
subtitle: 'Assistant Workspace',
fullPath: '/abs/assistant',
backHref: '/assistant',
},
isLoading: false,
isError: false,
})
mocks.useRepoSchedules.mockReturnValue({ data: [], isLoading: false })
mocks.useRepoSchedule.mockReturnValue({ data: undefined, isFetching: false })
mocks.useRepoScheduleRuns.mockReturnValue({ data: [], isLoading: false })
mocks.useRepoScheduleRun.mockReturnValue({ data: undefined, isLoading: false })
renderSchedules('0')
expect(screen.queryByText('Repository not found')).not.toBeInTheDocument()
})
it('renders back button with correct href', () => {
mockNavigate.mockClear()
mocks.useWorkspace.mockReturnValue({
workspace: {
repoId: 0,
kind: 'assistant',
name: 'Assistant',
subtitle: 'Assistant Workspace',
fullPath: '/abs/assistant',
backHref: '/assistant',
},
isLoading: false,
isError: false,
})
mocks.useRepoSchedules.mockReturnValue({ data: [], isLoading: false })
mocks.useRepoSchedule.mockReturnValue({ data: undefined, isFetching: false })
mocks.useRepoScheduleRuns.mockReturnValue({ data: [], isLoading: false })
mocks.useRepoScheduleRun.mockReturnValue({ data: undefined, isLoading: false })
renderSchedules('0')
const backButton = screen.getAllByRole('button')[0]
expect(backButton).toBeInTheDocument()
fireEvent.click(backButton)
expect(mockNavigate).toHaveBeenCalledWith('/assistant')
})
it('calls runMutation with repoId=0 when Run Now is clicked', () => {
const mutateMock = vi.fn()
mocks.useWorkspace.mockReturnValue({
workspace: {
repoId: 0,
kind: 'assistant',
name: 'Assistant',
subtitle: 'Assistant Workspace',
fullPath: '/abs/assistant',
backHref: '/assistant',
},
isLoading: false,
isError: false,
})
const mockJob = {
id: 123,
name: 'Test Job',
repoId: 0,
cronExpression: null,
intervalMinutes: 30,
timezone: 'UTC',
enabled: true,
createdAt: 0,
updatedAt: 0,
scheduleMode: 'interval' as const,
agentSlug: null,
prompt: 'test',
triggerSource: 'manual' as const,
lastRunAt: null,
nextRunAt: null,
skillMetadata: null,
}
mocks.useScheduleTab.mockReturnValue({
scheduleTab: 'detail',
setScheduleTab: vi.fn(),
})
mocks.useRepoSchedules.mockReturnValue({ data: [mockJob], isLoading: false })
mocks.useRepoSchedule.mockReturnValue({ data: mockJob, isFetching: false })
mocks.useRepoScheduleRuns.mockReturnValue({ data: [], isLoading: false })
mocks.useRepoScheduleRun.mockReturnValue({ data: undefined, isLoading: false })
mocks.useRunRepoSchedule.mockReturnValue({ mutate: mutateMock, isPending: false })
renderSchedules('0')
const runNowButton = screen.getByTestId('run-now')
runNowButton.click()
expect(mutateMock).toHaveBeenCalledWith({ repoId: 0, jobId: 123 }, expect.any(Object))
})
})
describe('repo workspace (repoId=5)', () => {
it('renders repo name and subtitle', () => {
mocks.useWorkspace.mockReturnValue({
workspace: {
repoId: 5,
kind: 'repo',
name: 'my-repo',
subtitle: 'repos/my-repo',
fullPath: '/abs/repos/my-repo',
backHref: '/repos/5',
},
isLoading: false,
isError: false,
})
mocks.useRepoSchedules.mockReturnValue({ data: [], isLoading: false })
mocks.useRepoSchedule.mockReturnValue({ data: undefined, isFetching: false })
mocks.useRepoScheduleRuns.mockReturnValue({ data: [], isLoading: false })
mocks.useRepoScheduleRun.mockReturnValue({ data: undefined, isLoading: false })
renderSchedules('5')
expect(screen.getByText('my-repo')).toBeInTheDocument()
expect(screen.getByText('repos/my-repo')).toBeInTheDocument()
})
it('renders back button with correct href', () => {
mockNavigate.mockClear()
mocks.useWorkspace.mockReturnValue({
workspace: {
repoId: 5,
kind: 'repo',
name: 'my-repo',
subtitle: 'repos/my-repo',
fullPath: '/abs/repos/my-repo',
backHref: '/repos/5',
},
isLoading: false,
isError: false,
})
mocks.useRepoSchedules.mockReturnValue({ data: [], isLoading: false })
mocks.useRepoSchedule.mockReturnValue({ data: undefined, isFetching: false })
mocks.useRepoScheduleRuns.mockReturnValue({ data: [], isLoading: false })
mocks.useRepoScheduleRun.mockReturnValue({ data: undefined, isLoading: false })
renderSchedules('5')
const backButton = screen.getAllByRole('button')[0]
expect(backButton).toBeInTheDocument()
fireEvent.click(backButton)
expect(mockNavigate).toHaveBeenCalledWith('/repos/5')
})
})
describe('workspace not found', () => {
it('renders not found fallback for real repo', () => {
mocks.useWorkspace.mockReturnValue({
workspace: undefined,
isLoading: false,
isError: true,
})
mocks.useRepoSchedules.mockReturnValue({ data: undefined, isLoading: false })
mocks.useRepoSchedule.mockReturnValue({ data: undefined, isFetching: false })
mocks.useRepoScheduleRuns.mockReturnValue({ data: [], isLoading: false })
mocks.useRepoScheduleRun.mockReturnValue({ data: undefined, isLoading: false })
renderSchedules('999')
expect(screen.getByText('Repository not found')).toBeInTheDocument()
})
it('renders not found fallback for assistant', () => {
mocks.useWorkspace.mockReturnValue({
workspace: undefined,
isLoading: false,
isError: true,
})
mocks.useRepoSchedules.mockReturnValue({ data: undefined, isLoading: false })
mocks.useRepoSchedule.mockReturnValue({ data: undefined, isFetching: false })
mocks.useRepoScheduleRuns.mockReturnValue({ data: [], isLoading: false })
mocks.useRepoScheduleRun.mockReturnValue({ data: undefined, isLoading: false })
renderSchedules('0')
expect(screen.getByText('Workspace not found')).toBeInTheDocument()
})
})
})
@@ -0,0 +1,274 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import { SessionDetail } from '../SessionDetail'
const mocks = vi.hoisted(() => ({
useSession: vi.fn(),
useMessages: vi.fn(),
useSSE: vi.fn(),
useRepoActivity: vi.fn(),
usePermissions: vi.fn(),
useQuestions: vi.fn(),
useSSEHealth: vi.fn(),
useConfig: vi.fn(),
useOpenCodeClient: vi.fn(),
useSettings: vi.fn(),
useSettingsDialog: vi.fn(),
useMobile: vi.fn(),
useVisualViewport: vi.fn(),
useKeyboardShortcuts: vi.fn(),
useAutoScroll: vi.fn(),
useDialogParam: vi.fn(),
useSidebarAction: vi.fn(),
RepoSkillsDialog: vi.fn(() => null),
}))
vi.mock('@/hooks/useOpenCode', () => ({
useSession: mocks.useSession,
useAbortSession: vi.fn(() => ({ mutate: vi.fn() })),
useUpdateSession: vi.fn(() => ({ mutate: vi.fn() })),
useCreateSession: vi.fn(() => ({ mutateAsync: vi.fn() })),
useMessages: mocks.useMessages,
useConfig: mocks.useConfig,
}))
vi.mock('@/hooks/useModelSelection', () => ({
useModelSelection: vi.fn(() => ({ model: null, modelString: null })),
}))
vi.mock('@/hooks/useOpenCodeClient', () => ({
useOpenCodeClient: mocks.useOpenCodeClient,
}))
vi.mock('@/hooks/useTTS', () => ({
useTTS: vi.fn(() => ({ isEnabled: false })),
}))
vi.mock('@/hooks/useSettings', () => ({
useSettings: vi.fn(() => ({
preferences: { expandToolCalls: false },
updateSettings: vi.fn(),
})),
}))
vi.mock('@/hooks/useSettingsDialog', () => ({
useSettingsDialog: vi.fn(() => ({ open: vi.fn() })),
}))
vi.mock('@/hooks/useMobile', () => ({
useMobile: vi.fn(() => false),
useSwipeBack: vi.fn(() => ({ ref: vi.fn() })),
}))
vi.mock('@/hooks/useVisualViewport', () => ({
useVisualViewport: vi.fn(() => ({ keyboardHeight: 0 })),
}))
vi.mock('@/hooks/useKeyboardShortcuts', () => ({
useKeyboardShortcuts: vi.fn(() => ({ leaderActive: false })),
}))
vi.mock('@/hooks/useAutoScroll', () => ({
useAutoScroll: vi.fn(() => ({ scrollToBottom: vi.fn() })),
}))
vi.mock('@/hooks/useDialogParam', () => ({
useDialogParam: vi.fn(() => [false, vi.fn()]),
}))
vi.mock('@/hooks/useSidebarAction', () => ({
useSidebarAction: vi.fn(() => {}),
}))
vi.mock('@/hooks/useAutoPlayLastResponse', () => ({
getAssistantText: vi.fn(() => ''),
getLatestPlayableAssistantMessage: vi.fn(() => null),
useAutoPlayLastResponse: vi.fn(() => {}),
}))
vi.mock('@/stores/uiStateStore', () => ({
useUIState: vi.fn(() => vi.fn()),
}))
vi.mock('@/stores/sessionStatusStore', () => ({
useSessionStatus: vi.fn(() => ({ setStatus: vi.fn() })),
useSessionStatusForSession: vi.fn(() => ({ type: 'idle' })),
}))
vi.mock('@/hooks/useSSE', () => ({
useSSE: mocks.useSSE,
}))
vi.mock('@/hooks/useRepoActivity', () => ({
useRepoActivity: mocks.useRepoActivity,
}))
vi.mock('@/contexts/EventContext', async (importOriginal) => {
const actual = await importOriginal()
return {
...(actual as object),
usePermissions: mocks.usePermissions,
useQuestions: mocks.useQuestions,
useSSEHealth: mocks.useSSEHealth,
}
})
vi.mock('@/api/repos', () => ({
getRepo: vi.fn(() => Promise.resolve(null)),
initializeAssistantMode: vi.fn(() => Promise.resolve({ directory: '/abs/assistant', warnings: [] })),
}))
vi.mock('@/components/model/ModelSelectDialog', () => ({
ModelSelectDialog: vi.fn(() => null),
}))
vi.mock('@/components/session/SessionList', () => ({
SessionList: vi.fn(() => null),
}))
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({
FileBrowserSheet: vi.fn(() => null),
}))
vi.mock('@/components/repo/RepoMcpDialog', () => ({
RepoMcpDialog: vi.fn(() => null),
}))
vi.mock('@/components/repo/ResetPermissionsDialog', () => ({
ResetPermissionsDialog: vi.fn(() => null),
}))
vi.mock('@/components/repo/RepoLspDialog', () => ({
RepoLspDialog: vi.fn(() => null),
}))
vi.mock('@/components/repo/RepoSkillsDialog', () => ({
RepoSkillsDialog: mocks.RepoSkillsDialog,
}))
vi.mock('@/components/source-control', () => ({
SourceControlPanel: vi.fn(() => null),
}))
vi.mock('@/components/session/QuestionPrompt', () => ({
QuestionPrompt: vi.fn(() => null),
}))
vi.mock('@/components/session/MinimizedQuestionIndicator', () => ({
MinimizedQuestionIndicator: vi.fn(() => null),
}))
vi.mock('@/components/notifications/PendingActionsGroup', () => ({
PendingActionsGroup: vi.fn(() => null),
}))
describe('SessionDetail assistant loading at repoId=0', () => {
beforeEach(() => {
vi.clearAllMocks()
mocks.useSession.mockReturnValue({ data: undefined, isLoading: false })
mocks.useMessages.mockReturnValue({ data: [], isLoading: false })
mocks.useSSE.mockReturnValue({ isConnected: true, isReconnecting: false })
mocks.useRepoActivity.mockReturnValue(undefined)
mocks.usePermissions.mockReturnValue({
pendingCount: 0,
hasPermissionsForSession: vi.fn(() => false),
syncForSession: vi.fn(),
})
mocks.useQuestions.mockReturnValue({
current: null,
pendingCount: 0,
hasQuestionsForSession: vi.fn(() => false),
reply: vi.fn(),
reject: vi.fn(),
syncForSession: vi.fn(),
})
mocks.useSSEHealth.mockReturnValue({ isHealthy: true })
mocks.useConfig.mockReturnValue({ data: undefined, isLoading: false })
mocks.useOpenCodeClient.mockReturnValue({})
mocks.useSettings.mockReturnValue({
preferences: { expandToolCalls: false },
updateSettings: vi.fn(),
})
mocks.useSettingsDialog.mockReturnValue({ open: vi.fn() })
mocks.useMobile.mockReturnValue(false)
mocks.useVisualViewport.mockReturnValue({ keyboardHeight: 0 })
mocks.useKeyboardShortcuts.mockReturnValue({ leaderActive: false })
mocks.useAutoScroll.mockReturnValue({ scrollToBottom: vi.fn() })
mocks.useDialogParam.mockReturnValue([false, vi.fn()])
mocks.useSidebarAction.mockReturnValue(undefined)
})
const createQueryClient = () =>
new QueryClient({
defaultOptions: {
queries: { retry: false },
},
})
const renderAssistantSession = (sessionId: string) => {
return render(
<MemoryRouter initialEntries={[`/repos/0/sessions/${sessionId}?assistant=1`]}>
<QueryClientProvider client={createQueryClient()}>
<Routes>
<Route path="/repos/:id/sessions/:sessionId" element={<SessionDetail />} />
</Routes>
</QueryClientProvider>
</MemoryRouter>
)
}
it('does not show "Loading repository..." for assistant sessions at repoId=0', async () => {
renderAssistantSession('sess-asst-1')
await waitFor(() => {
expect(screen.queryByText('Loading repository...')).not.toBeInTheDocument()
})
})
it('renders "Assistant" as the workspace display name', async () => {
renderAssistantSession('sess-asst-1')
await waitFor(() => {
expect(screen.getByText('Assistant')).toBeInTheDocument()
})
})
it('passes directory from assistantMode to RepoSkillsDialog once loaded', async () => {
renderAssistantSession('sess-asst-1')
await waitFor(() => {
const lastCall = mocks.RepoSkillsDialog.mock.calls.at(-1)
expect(lastCall).toBeDefined()
expect(lastCall![0].directory).toBe('/abs/assistant')
})
})
it('does not pass empty string for directory when repoDirectory is undefined', async () => {
renderAssistantSession('sess-asst-1')
await waitFor(() => {
expect(mocks.RepoSkillsDialog).toHaveBeenCalled()
})
mocks.RepoSkillsDialog.mock.calls.forEach(([props]) => {
expect(props.directory).not.toBe('')
})
})
it('renders "Assistant" as workspaceDisplayName for non-assistant sessions without repo', async () => {
mocks.useSession.mockReturnValue({ data: undefined, isLoading: false })
return render(
<MemoryRouter initialEntries={['/repos/1/sessions/sess-1']}>
<QueryClientProvider client={createQueryClient()}>
<Routes>
<Route path="/repos/:id/sessions/:sessionId" element={<SessionDetail />} />
</Routes>
</QueryClientProvider>
</MemoryRouter>
)
})
})
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { renderHook, waitFor } from '@testing-library/react'
import { renderHook } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { useQuery } from '@tanstack/react-query'
@@ -51,10 +51,8 @@ describe('SessionDetail pending-actions polling', () => {
expect(mocks.syncPendingActions).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(30000)
await waitFor(() => {
expect(mocks.syncPendingActions).toHaveBeenCalledTimes(2)
})
expect(mocks.syncPendingActions).toHaveBeenCalledTimes(2)
vi.useRealTimers()
})
@@ -0,0 +1,330 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import { useSessionTodos } from '@/stores/sessionTodosStore'
import type { Todo } from '@/components/message/SessionTodoDisplay'
import { SessionDetail } from '../SessionDetail'
const mocks = vi.hoisted(() => ({
useSession: vi.fn(),
useMessages: vi.fn(),
useSSE: vi.fn(),
useRepoActivity: vi.fn(),
usePermissions: vi.fn(),
useQuestions: vi.fn(),
useSSEHealth: vi.fn(),
useConfig: vi.fn(),
useOpenCodeClient: vi.fn(),
useSettings: vi.fn(),
useSettingsDialog: vi.fn(),
useMobile: vi.fn(),
useVisualViewport: vi.fn(),
useKeyboardShortcuts: vi.fn(),
useAutoScroll: vi.fn(),
useDialogParam: vi.fn(),
useSidebarAction: vi.fn(),
}))
vi.mock('@/hooks/useOpenCode', () => ({
useSession: mocks.useSession,
useAbortSession: vi.fn(() => ({ mutate: vi.fn() })),
useUpdateSession: vi.fn(() => ({ mutate: vi.fn() })),
useCreateSession: vi.fn(() => ({ mutateAsync: vi.fn() })),
useMessages: mocks.useMessages,
useConfig: mocks.useConfig,
}))
vi.mock('@/hooks/useModelSelection', () => ({
useModelSelection: vi.fn(() => ({ model: null, modelString: null })),
}))
vi.mock('@/hooks/useOpenCodeClient', () => ({
useOpenCodeClient: mocks.useOpenCodeClient,
}))
vi.mock('@/hooks/useTTS', () => ({
useTTS: vi.fn(() => ({ isEnabled: false })),
}))
vi.mock('@/hooks/useSettings', () => ({
useSettings: vi.fn(() => ({
preferences: { expandToolCalls: false },
updateSettings: vi.fn(),
})),
}))
vi.mock('@/hooks/useSettingsDialog', () => ({
useSettingsDialog: vi.fn(() => ({ open: vi.fn() })),
}))
vi.mock('@/hooks/useMobile', () => ({
useMobile: vi.fn(() => false),
useSwipeBack: vi.fn(() => ({ ref: vi.fn() })),
}))
vi.mock('@/hooks/useVisualViewport', () => ({
useVisualViewport: vi.fn(() => ({ keyboardHeight: 0 })),
}))
vi.mock('@/hooks/useKeyboardShortcuts', () => ({
useKeyboardShortcuts: vi.fn(() => ({ leaderActive: false })),
}))
vi.mock('@/hooks/useAutoScroll', () => ({
useAutoScroll: vi.fn(() => ({ scrollToBottom: vi.fn() })),
}))
vi.mock('@/hooks/useDialogParam', () => ({
useDialogParam: vi.fn(() => [false, vi.fn()]),
}))
vi.mock('@/hooks/useSidebarAction', () => ({
useSidebarAction: vi.fn(() => {}),
}))
vi.mock('@/hooks/useAutoPlayLastResponse', () => ({
getAssistantText: vi.fn(() => ''),
getLatestPlayableAssistantMessage: vi.fn(() => null),
useAutoPlayLastResponse: vi.fn(() => {}),
}))
vi.mock('@/stores/uiStateStore', () => ({
useUIState: vi.fn(() => vi.fn()),
}))
vi.mock('@/stores/sessionStatusStore', () => ({
useSessionStatus: vi.fn(() => ({ setStatus: vi.fn() })),
useSessionStatusForSession: vi.fn(() => ({ type: 'idle' })),
}))
vi.mock('@/hooks/useSSE', () => ({
useSSE: mocks.useSSE,
}))
vi.mock('@/hooks/useRepoActivity', () => ({
useRepoActivity: mocks.useRepoActivity,
}))
vi.mock('@/contexts/EventContext', async (importOriginal) => {
const actual = await importOriginal()
return {
...(actual as object),
usePermissions: mocks.usePermissions,
useQuestions: mocks.useQuestions,
useSSEHealth: mocks.useSSEHealth,
}
})
vi.mock('@/api/repos', () => ({
getRepo: vi.fn(() => Promise.resolve({
id: 1,
repoUrl: 'https://github.com/test/repo',
localPath: '/test/repo',
sourcePath: null,
fullPath: '/test/repo',
branch: 'main',
currentBranch: 'main',
fullSlug: 'test/repo',
repoType: 'github' as const,
})),
initializeAssistantMode: vi.fn(() => Promise.resolve({ directory: '/test/repo' })),
}))
vi.mock('@/components/model/ModelSelectDialog', () => ({
ModelSelectDialog: vi.fn(() => null),
}))
vi.mock('@/components/session/SessionList', () => ({
SessionList: vi.fn(() => null),
}))
vi.mock('@/components/file-browser/FileBrowserSheet', () => ({
FileBrowserSheet: vi.fn(() => null),
}))
vi.mock('@/components/repo/RepoMcpDialog', () => ({
RepoMcpDialog: vi.fn(() => null),
}))
vi.mock('@/components/repo/ResetPermissionsDialog', () => ({
ResetPermissionsDialog: vi.fn(() => null),
}))
vi.mock('@/components/repo/RepoLspDialog', () => ({
RepoLspDialog: vi.fn(() => null),
}))
vi.mock('@/components/repo/RepoSkillsDialog', () => ({
RepoSkillsDialog: vi.fn(() => null),
}))
vi.mock('@/components/source-control', () => ({
SourceControlPanel: vi.fn(() => null),
}))
vi.mock('@/components/session/QuestionPrompt', () => ({
QuestionPrompt: vi.fn(() => null),
}))
vi.mock('@/components/session/MinimizedQuestionIndicator', () => ({
MinimizedQuestionIndicator: vi.fn(() => null),
}))
vi.mock('@/components/notifications/PendingActionsGroup', () => ({
PendingActionsGroup: vi.fn(() => null),
}))
const activeTodos: Todo[] = [
{ id: '1', content: 'Implement mobile header fix', status: 'in_progress', priority: 'high' },
{ id: '2', content: 'Add regression tests', status: 'pending', priority: 'medium' },
{ id: '3', content: 'Verify completed item grouping', status: 'completed', priority: 'low' },
]
describe('SessionDetail todo-header integration', () => {
beforeEach(() => {
vi.clearAllMocks()
useSessionTodos.setState({ todos: new Map() })
mocks.useSession.mockReturnValue({ data: undefined, isLoading: false })
mocks.useMessages.mockReturnValue({ data: [], isLoading: false })
mocks.useSSE.mockReturnValue({ isConnected: true, isReconnecting: false })
mocks.useRepoActivity.mockReturnValue(undefined)
mocks.usePermissions.mockReturnValue({
pendingCount: 0,
hasPermissionsForSession: vi.fn(() => false),
syncForSession: vi.fn(),
})
mocks.useQuestions.mockReturnValue({
current: null,
pendingCount: 0,
hasQuestionsForSession: vi.fn(() => false),
reply: vi.fn(),
reject: vi.fn(),
syncForSession: vi.fn(),
})
mocks.useSSEHealth.mockReturnValue({ isHealthy: true })
mocks.useConfig.mockReturnValue({ data: undefined, isLoading: false })
mocks.useOpenCodeClient.mockReturnValue({})
mocks.useSettings.mockReturnValue({
preferences: { expandToolCalls: false },
updateSettings: vi.fn(),
})
mocks.useSettingsDialog.mockReturnValue({ open: vi.fn() })
mocks.useMobile.mockReturnValue(false)
mocks.useVisualViewport.mockReturnValue({ keyboardHeight: 0 })
mocks.useKeyboardShortcuts.mockReturnValue({ leaderActive: false })
mocks.useAutoScroll.mockReturnValue({ scrollToBottom: vi.fn() })
mocks.useDialogParam.mockReturnValue([false, vi.fn()])
mocks.useSidebarAction.mockReturnValue(undefined)
})
const createQueryClient = () =>
new QueryClient({
defaultOptions: {
queries: { retry: false },
},
})
const renderSessionDetail = (sessionId: string, repoId: number) => {
return render(
<MemoryRouter initialEntries={[`/repos/${repoId}/sessions/${sessionId}`]}>
<QueryClientProvider client={createQueryClient()}>
<Routes>
<Route path="/repos/:id/sessions/:sessionId" element={<SessionDetail />} />
</Routes>
</QueryClientProvider>
</MemoryRouter>
)
}
it('renders SessionTodoDisplay collapsed by default inside SessionDetail header', async () => {
useSessionTodos.getState().setTodos('session-1', activeTodos)
renderSessionDetail('session-1', 1)
await waitFor(() => {
expect(screen.getByText('Tasks: 1/3 complete')).toBeInTheDocument()
})
expect(screen.queryByText('Implement mobile header fix')).not.toBeInTheDocument()
})
it('expands todo list when clicked inside SessionDetail header', async () => {
const user = userEvent.setup()
useSessionTodos.getState().setTodos('session-1', activeTodos)
renderSessionDetail('session-1', 1)
await waitFor(() => {
expect(screen.getByText('Tasks: 1/3 complete')).toBeInTheDocument()
})
const collapsedRow = screen.getByText('Tasks: 1/3 complete')
await user.click(collapsedRow)
expect(screen.getByText('Implement mobile header fix')).toBeInTheDocument()
expect(screen.getByText('Add regression tests')).toBeInTheDocument()
const expandedContainer = screen.getByTestId('todo-expanded-list')
expect(expandedContainer).toHaveClass('max-h-[80px]')
expect(expandedContainer).toHaveClass('sm:max-h-[160px]')
expect(expandedContainer).toHaveClass('overflow-y-auto')
})
it('header wrapper uses max-h-72 sm:max-h-80 and overflow-hidden for proper containment', async () => {
useSessionTodos.getState().setTodos('session-1', activeTodos)
renderSessionDetail('session-1', 1)
await waitFor(() => {
expect(screen.getByTestId('session-header-region')).toBeInTheDocument()
})
const headerRegion = screen.getByTestId('session-header-region')
expect(headerRegion.className).toContain('max-h-72')
expect(headerRegion.className).toContain('sm:max-h-80')
expect(headerRegion.className).toContain('overflow-hidden')
expect(headerRegion.className).not.toContain('max-h-40')
})
it('collapses todo list when expanded header is clicked again', async () => {
const user = userEvent.setup()
useSessionTodos.getState().setTodos('session-1', activeTodos)
renderSessionDetail('session-1', 1)
await waitFor(() => {
expect(screen.getByText('Tasks: 1/3 complete')).toBeInTheDocument()
})
const collapsedRow = screen.getByText('Tasks: 1/3 complete')
await user.click(collapsedRow)
expect(screen.getByTestId('todo-expanded-list')).toBeInTheDocument()
const expandedHeader = screen.getByText('Tasks: 1/3 complete')
await user.click(expandedHeader)
expect(screen.queryByTestId('todo-expanded-list')).not.toBeInTheDocument()
})
it('does not render SessionTodoDisplay when all tasks are completed', async () => {
const allCompletedTodos: Todo[] = [
{ id: '1', content: 'Task one', status: 'completed', priority: 'high' },
{ id: '2', content: 'Task two', status: 'completed', priority: 'medium' },
]
useSessionTodos.getState().setTodos('session-1', allCompletedTodos)
renderSessionDetail('session-1', 1)
await waitFor(() => {
const headerRegion = screen.getByTestId('session-header-region')
expect(headerRegion).toBeInTheDocument()
})
expect(screen.queryByText(/Tasks:/)).not.toBeInTheDocument()
})
})
+19
View File
@@ -9,6 +9,7 @@ export interface ModelSelection {
interface ModelStore {
model: ModelSelection | null
agentModels: Record<string, ModelSelection>
recentModels: ModelSelection[]
favoriteModels: ModelSelection[]
variants: Record<string, string | undefined>
@@ -16,6 +17,8 @@ interface ModelStore {
setModel: (model: ModelSelection) => void
setActiveModel: (model: ModelSelection) => void
setAgentModel: (agent: string, model: ModelSelection) => void
getAgentModel: (agent: string) => ModelSelection | null
syncModelState: (state: { recent: ModelSelection[], favorite: ModelSelection[], variant: Record<string, string | undefined> }) => void
toggleFavorite: (model: ModelSelection) => void
syncFromConfig: (configModel: string | undefined, force?: boolean) => void
@@ -39,6 +42,7 @@ export const useModelStore = create<ModelStore>()(
persist(
(set, get) => ({
model: null,
agentModels: {},
recentModels: [],
favoriteModels: [],
variants: {},
@@ -64,6 +68,20 @@ export const useModelStore = create<ModelStore>()(
set({ model })
},
setAgentModel: (agent: string, model: ModelSelection) => {
set((state) => ({
agentModels: {
...state.agentModels,
[agent]: model,
},
}))
},
getAgentModel: (agent: string) => {
const state = get()
return state.agentModels[agent] ?? null
},
syncModelState: (modelState) => {
set((state) => ({
recentModels: modelState.recent,
@@ -182,6 +200,7 @@ export const useModelStore = create<ModelStore>()(
name: 'opencode-model-selection',
partialize: (state) => ({
model: state.model,
agentModels: state.agentModels,
recentModels: state.recentModels,
favoriteModels: state.favoriteModels,
variants: state.variants,
+4
View File
@@ -8,12 +8,14 @@ interface UIStateStore {
activePromptFileBasePath: string | null
pendingPromptCommand: { id: number; command: CommandType } | null
pendingPromptFile: { id: number; path: string } | null
isMoreDrawerOpen: boolean
setIsEditingMessage: (isEditing: boolean) => void
setActivePromptFileBasePath: (basePath: string | null) => void
selectPromptCommand: (command: CommandType) => void
clearPendingPromptCommand: () => void
selectPromptFile: (path: string) => void
clearPendingPromptFile: () => void
setMoreDrawerOpen: (open: boolean) => void
}
export const useUIState = create<UIStateStore>((set) => ({
@@ -21,10 +23,12 @@ export const useUIState = create<UIStateStore>((set) => ({
activePromptFileBasePath: null,
pendingPromptCommand: null,
pendingPromptFile: null,
isMoreDrawerOpen: false,
setIsEditingMessage: (isEditing: boolean) => set({ isEditingMessage: isEditing }),
setActivePromptFileBasePath: (basePath: string | null) => set({ activePromptFileBasePath: basePath }),
selectPromptCommand: (command: CommandType) => set({ pendingPromptCommand: { id: Date.now(), command } }),
clearPendingPromptCommand: () => set({ pendingPromptCommand: null }),
selectPromptFile: (path: string) => set({ pendingPromptFile: { id: Date.now(), path } }),
clearPendingPromptFile: () => set({ pendingPromptFile: null }),
setMoreDrawerOpen: (open: boolean) => set({ isMoreDrawerOpen: open }),
}))