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

@@ -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,
}
}