feat(frontend): add mobile composer tools menu and base branch select

This commit is contained in:
Chris Scott committed 2026-10-04 00:05:53 -04:00
1 parent fac23b1f1a
commit 4a2e695ec2
21 files changed
+819 -158

No files matched your search

+1 -1
View File
@@ -136,7 +136,7 @@ export async function switchBranch(id: number, branch: string): Promise<Repo> {
} }
} }
interface GitBranch { export interface GitBranch {
name: string name: string
type: 'local' | 'remote' type: 'local' | 'remote'
current: boolean current: boolean
@@ -0,0 +1,128 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { ComposerToolsMenu } from './ComposerToolsMenu'
import { useSessionPermissionMode, useSetSessionPermissionMode } from '@/hooks/useSessionPermissionMode'
import type { SessionPermissionModeState } from '@opencode-manager/shared/schemas'
vi.mock('@/hooks/useSessionPermissionMode')
const baseState: SessionPermissionModeState = {
sessionId: 'ses_1',
rootSessionId: 'ses_1',
mode: 'ask',
lockedReason: null,
}
function mockPermissionMode(state: Partial<SessionPermissionModeState> = {}, mutate = vi.fn()) {
vi.mocked(useSessionPermissionMode).mockReturnValue({
data: { ...baseState, ...state },
isError: false,
} as ReturnType<typeof useSessionPermissionMode>)
vi.mocked(useSetSessionPermissionMode).mockReturnValue({
mutate,
isPending: false,
} as unknown as ReturnType<typeof useSetSessionPermissionMode>)
return mutate
}
function renderMenu(overrides: Partial<React.ComponentProps<typeof ComposerToolsMenu>> = {}) {
const props = {
sessionID: 'ses_1',
directory: '/repo',
goalArmed: false,
goalDisabled: false,
goalLabel: 'Goal mode: the next message becomes the objective',
onToggleGoal: vi.fn(),
onAttachFile: vi.fn(),
...overrides,
}
render(<ComposerToolsMenu {...props} />)
return props
}
describe('ComposerToolsMenu', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('does not highlight the trigger when no tool is active', () => {
mockPermissionMode()
renderMenu()
expect(screen.getByRole('button', { name: 'Composer options' })).not.toHaveClass('bg-highlight')
})
it('highlights the trigger while permissions accept everything', () => {
mockPermissionMode({ mode: 'auto' })
renderMenu()
expect(screen.getByRole('button', { name: 'Composer options' })).toHaveClass('bg-highlight')
})
it('highlights the trigger while goal mode is armed', () => {
mockPermissionMode()
renderMenu({ goalArmed: true })
expect(screen.getByRole('button', { name: 'Composer options' })).toHaveClass('bg-highlight')
})
it('switches permissions to accept everything', async () => {
const user = userEvent.setup()
const mutate = mockPermissionMode()
renderMenu()
await user.click(screen.getByRole('button', { name: 'Composer options' }))
const item = await screen.findByRole('menuitemcheckbox', { name: /Accept all permissions/ })
expect(item).toHaveAttribute('aria-checked', 'false')
await user.click(item)
expect(mutate).toHaveBeenCalledWith({ directory: '/repo', mode: 'auto' })
})
it('shows why permissions cannot be changed', async () => {
const user = userEvent.setup()
mockPermissionMode({ lockedReason: 'child' })
renderMenu()
await user.click(screen.getByRole('button', { name: 'Composer options' }))
const item = await screen.findByRole('menuitemcheckbox', { name: /Accept all permissions/ })
expect(item).toHaveAttribute('aria-disabled', 'true')
expect(item).toHaveTextContent('Inherited from parent session')
})
it('toggles goal mode', async () => {
const user = userEvent.setup()
mockPermissionMode()
const props = renderMenu()
await user.click(screen.getByRole('button', { name: 'Composer options' }))
await user.click(await screen.findByRole('menuitemcheckbox', { name: /Goal mode/ }))
expect(props.onToggleGoal).toHaveBeenCalledTimes(1)
})
it('shows why goal mode is unavailable', async () => {
const user = userEvent.setup()
mockPermissionMode()
renderMenu({ goalDisabled: true, goalLabel: 'A goal is already active for this session' })
await user.click(screen.getByRole('button', { name: 'Composer options' }))
const item = await screen.findByRole('menuitemcheckbox', { name: /Goal mode/ })
expect(item).toHaveAttribute('aria-disabled', 'true')
expect(item).toHaveTextContent('A goal is already active for this session')
})
it('opens the file picker', async () => {
const user = userEvent.setup()
mockPermissionMode()
const props = renderMenu()
await user.click(screen.getByRole('button', { name: 'Composer options' }))
await user.click(await screen.findByRole('menuitem', { name: 'Attach image or PDF' }))
expect(props.onAttachFile).toHaveBeenCalledTimes(1)
})
})
@@ -0,0 +1,85 @@
import type { ReactNode } from 'react'
import { Paperclip, Plus, Shield, ShieldCheck, Target } from 'lucide-react'
import {
DropdownMenu,
DropdownMenuCheckboxItem,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { getIconToggleButtonClassName } from '@/components/ui/icon-toggle-button'
import { usePermissionModeToggle } from '@/hooks/usePermissionModeToggle'
interface ComposerToolsMenuProps {
sessionID: string
directory: string
goalArmed: boolean
goalDisabled: boolean
goalLabel: string
onToggleGoal: () => void
onAttachFile: () => void
}
export function ComposerToolsMenu({
sessionID,
directory,
goalArmed,
goalDisabled,
goalLabel,
onToggleGoal,
onAttachFile,
}: ComposerToolsMenuProps) {
const permission = usePermissionModeToggle(sessionID, directory)
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
type="button"
aria-label="Composer options"
title="Composer options"
className={getIconToggleButtonClassName(permission.isAuto || goalArmed)}
>
<Plus className="w-5 h-5" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent side="top" align="end" collisionPadding={8} className="w-64">
<DropdownMenuCheckboxItem
checked={permission.isAuto}
disabled={permission.disabled}
onCheckedChange={permission.toggle}
>
<ToolMenuItemContent
icon={permission.isAuto ? <ShieldCheck className="h-4 w-4" /> : <Shield className="h-4 w-4" />}
title="Accept all permissions"
detail={permission.disabled ? permission.label : undefined}
/>
</DropdownMenuCheckboxItem>
<DropdownMenuCheckboxItem checked={goalArmed} disabled={goalDisabled} onCheckedChange={onToggleGoal}>
<ToolMenuItemContent
icon={<Target className="h-4 w-4" />}
title="Goal mode"
detail={goalDisabled ? goalLabel : undefined}
/>
</DropdownMenuCheckboxItem>
<DropdownMenuSeparator />
<DropdownMenuItem onSelect={onAttachFile} className="pl-8">
<ToolMenuItemContent icon={<Paperclip className="h-4 w-4" />} title="Attach image or PDF" />
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)
}
function ToolMenuItemContent({ icon, title, detail }: { icon: ReactNode; title: string; detail?: string }) {
return (
<span className="flex items-start gap-2">
<span className="mt-0.5 shrink-0">{icon}</span>
<span className="flex min-w-0 flex-col">
<span>{title}</span>
{detail ? <span className="text-xs text-muted-foreground">{detail}</span> : null}
</span>
</span>
)
}
@@ -102,7 +102,19 @@ vi.mock('@/components/model/ModelQuickSelect', () => ({
})) }))
vi.mock('@/components/session/PermissionModeToggle', () => ({ vi.mock('@/components/session/PermissionModeToggle', () => ({
PermissionModeToggle: () => null, PermissionModeToggle: () => <div data-testid="permission-mode-toggle" />,
}))
vi.mock('./ComposerToolsMenu', () => ({
ComposerToolsMenu: ({ goalDisabled, goalLabel, onToggleGoal }: {
goalDisabled: boolean
goalLabel: string
onToggleGoal: () => void
}) => (
<button type="button" data-testid="composer-tools-menu" title={goalLabel} disabled={goalDisabled} onClick={onToggleGoal}>
Composer options
</button>
),
})) }))
vi.mock('@/components/ui/session-status-indicator', () => ({ vi.mock('@/components/ui/session-status-indicator', () => ({
@@ -318,6 +330,54 @@ describe('PromptInput goal mode', () => {
expect(button).toBeDisabled() expect(button).toBeDisabled()
}) })
it('keeps permission and goal toggles inline on desktop', async () => {
stubMatchMedia(true)
renderComponent()
expect(await screen.findByRole('button', { name: GOAL_BUTTON })).toBeInTheDocument()
expect(screen.getByTestId('permission-mode-toggle')).toBeInTheDocument()
expect(screen.queryByTestId('composer-tools-menu')).not.toBeInTheDocument()
})
it('moves permission and goal toggles into the composer options menu on mobile', async () => {
stubMatchMedia(true)
mocks.useMobile.mockReturnValue(true)
renderComponent()
const menu = await screen.findByTestId('composer-tools-menu')
expect(menu).toHaveAttribute('title', GOAL_BUTTON)
expect(screen.queryByRole('button', { name: GOAL_BUTTON })).not.toBeInTheDocument()
expect(screen.queryByTestId('permission-mode-toggle')).not.toBeInTheDocument()
})
it('starts a goal armed from the mobile composer options menu', async () => {
stubMatchMedia(true)
mocks.useMobile.mockReturnValue(true)
renderComponent()
const input = await screen.findByPlaceholderText('Send a message...')
fireEvent.change(input, { target: { value: 'Ship the feature' } })
fireEvent.click(screen.getByTestId('composer-tools-menu'))
fireEvent.click(screen.getByTitle('Send'))
await waitFor(() => expect(mocks.startGoal).toHaveBeenCalledWith({
sessionId: 'test-session',
directory: '/test',
objective: 'Ship the feature',
}))
})
it('passes the goal lock reason to the mobile composer options menu', async () => {
stubMatchMedia(true)
mocks.useMobile.mockReturnValue(true)
mocks.useSessionGoal.mockReturnValue({ data: { status: 'active' } })
renderComponent()
const menu = await screen.findByTestId('composer-tools-menu')
expect(menu).toHaveAttribute('title', OPEN_GOAL_BUTTON)
expect(menu).toBeDisabled()
})
it('disables goal mode with a reason for child sessions', async () => { it('disables goal mode with a reason for child sessions', async () => {
stubMatchMedia(true) stubMatchMedia(true)
mocks.useSessionPermissionMode.mockReturnValue({ mocks.useSessionPermissionMode.mockReturnValue({
@@ -104,6 +104,10 @@ vi.mock('@/components/session/PermissionModeToggle', () => ({
PermissionModeToggle: () => null, PermissionModeToggle: () => null,
})) }))
vi.mock('./ComposerToolsMenu', () => ({
ComposerToolsMenu: () => null,
}))
vi.mock('@/hooks/useSessionGoals', () => ({ vi.mock('@/hooks/useSessionGoals', () => ({
useSessionGoal: () => ({ data: undefined }), useSessionGoal: () => ({ data: undefined }),
useStartSessionGoal: () => ({ mutateAsync: vi.fn(), isPending: false }), useStartSessionGoal: () => ({ mutateAsync: vi.fn(), isPending: false }),
+36 -31
View File
@@ -29,6 +29,7 @@ import { ModelQuickSelect } from '@/components/model/ModelQuickSelect'
import { AgentQuickSelect } from '@/components/agent/AgentQuickSelect' import { AgentQuickSelect } from '@/components/agent/AgentQuickSelect'
import { VoiceStatusOverlay, type VoiceStatusOverlayState } from './VoiceStatusOverlay' import { VoiceStatusOverlay, type VoiceStatusOverlayState } from './VoiceStatusOverlay'
import { PermissionModeToggle } from '@/components/session/PermissionModeToggle' import { PermissionModeToggle } from '@/components/session/PermissionModeToggle'
import { ComposerToolsMenu } from './ComposerToolsMenu'
import { useSessionGoal, useStartSessionGoal } from '@/hooks/useSessionGoals' import { useSessionGoal, useStartSessionGoal } from '@/hooks/useSessionGoals'
import { useSessionPermissionMode } from '@/hooks/useSessionPermissionMode' import { useSessionPermissionMode } from '@/hooks/useSessionPermissionMode'
import { detectMentionTrigger, parsePromptToInput, getFilename, filterAgentsByQuery } from '@/lib/promptParser' import { detectMentionTrigger, parsePromptToInput, getFilename, filterAgentsByQuery } from '@/lib/promptParser'
@@ -201,6 +202,10 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
clearSubmittedPrompt(pending.prompt, pending.files, pending.images) clearSubmittedPrompt(pending.prompt, pending.files, pending.images)
}, [isStreamingResponse, clearSubmittedPrompt]) }, [isStreamingResponse, clearSubmittedPrompt])
const openFilePicker = useCallback(() => {
fileInputRef.current?.click()
}, [])
useImperativeHandle(ref, () => ({ useImperativeHandle(ref, () => ({
setPromptValue: (value: string) => { setPromptValue: (value: string) => {
setPrompt(value) setPrompt(value)
@@ -219,13 +224,11 @@ export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(
} }
textareaRef.current?.focus() textareaRef.current?.focus()
}, },
triggerFileUpload: () => { triggerFileUpload: openFilePicker,
fileInputRef.current?.click()
},
openModelPicker: () => { openModelPicker: () => {
setIsModelPickerOpen(true) setIsModelPickerOpen(true)
} }
}), [imageAttachments, clearSTT, isRecording, abortRecording, resetVoiceGestureState]) }), [imageAttachments, clearSTT, isRecording, abortRecording, resetVoiceGestureState, openFilePicker])
const sessionAgent = useSessionAgent(sessionID, directory) const sessionAgent = useSessionAgent(sessionID, directory)
const currentMode = localMode ?? sessionAgent.agent const currentMode = localMode ?? sessionAgent.agent
const setStoredAgent = useSessionAgentStore((s) => s.setAgent) const setStoredAgent = useSessionAgentStore((s) => s.setAgent)
@@ -1187,16 +1190,8 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
: isGoalArmed : isGoalArmed
? 'Goal mode armed: the next message becomes the objective' ? 'Goal mode armed: the next message becomes the objective'
: 'Goal mode: the next message becomes the objective' : 'Goal mode: the next message becomes the objective'
const goalModeButton = directory ? ( const isGoalModeDisabled = lockedReason !== null || hasOpenGoal || isBashMode || startGoal.isPending
<IconToggleButton const toggleGoalArmed = () => setIsGoalArmed((value) => !value)
active={isGoalArmed}
label={goalButtonLabel}
disabled={lockedReason !== null || hasOpenGoal || isBashMode || startGoal.isPending}
onClick={() => setIsGoalArmed((value) => !value)}
>
<Target className="w-5 h-5" />
</IconToggleButton>
) : null
const voiceFeedbackState: VoiceStatusOverlayState | null = isTogglingRecording const voiceFeedbackState: VoiceStatusOverlayState | null = isTogglingRecording
? 'starting' ? 'starting'
: isProcessing : isProcessing
@@ -1320,16 +1315,6 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
return ( return (
<div className={`relative backdrop-blur-md bg-background opacity-95 border border-border dark:border-border/30 rounded-xl p-2 md:p-3 mb-4 md:mb-1 w-full transition-all ${hasPendingPermissionForSession ? 'border-highlight/50 ring-1 ring-highlight/30' : ''}`}> <div className={`relative backdrop-blur-md bg-background opacity-95 border border-border dark:border-border/30 rounded-xl p-2 md:p-3 mb-4 md:mb-1 w-full transition-all ${hasPendingPermissionForSession ? 'border-highlight/50 ring-1 ring-highlight/30' : ''}`}>
{showStopButton && (
<button
onClick={handleStop}
className="absolute bottom-full right-0 mb-2 md:hidden z-50 p-3 rounded-xl transition-all duration-200 active:scale-95 hover:scale-105 bg-destructive hover:bg-destructive/90 text-destructive-foreground border border-destructive/60 shadow-lg shadow-destructive/30"
title="Stop"
>
<SquareFill className="w-5 h-5" />
</button>
)}
<textarea <textarea
ref={textareaRef} ref={textareaRef}
value={prompt} value={prompt}
@@ -1396,8 +1381,6 @@ return (
open={isModelPickerOpen} open={isModelPickerOpen}
onOpenChange={setIsModelPickerOpen} onOpenChange={setIsModelPickerOpen}
/> />
{directory && <PermissionModeToggle sessionID={sessionID} directory={directory} />}
{goalModeButton}
</> </>
) : ( ) : (
<> <>
@@ -1407,8 +1390,19 @@ return (
onAgentChange={handleAgentChange} onAgentChange={handleAgentChange}
isBashMode={isBashMode} isBashMode={isBashMode}
/> />
{directory && <PermissionModeToggle sessionID={sessionID} directory={directory} />} {directory && !isMobile && (
{goalModeButton} <>
<PermissionModeToggle sessionID={sessionID} directory={directory} />
<IconToggleButton
active={isGoalArmed}
label={goalButtonLabel}
disabled={isGoalModeDisabled}
onClick={toggleGoalArmed}
>
<Target className="w-5 h-5" />
</IconToggleButton>
</>
)}
{isSessionActive && ( {isSessionActive && (
<div className="px-2.5 py-1.5 md:px-3 md:py-2 rounded-lg text-xs md:text-sm font-medium text-muted-foreground max-w-[120px] md:max-w-[180px]"> <div className="px-2.5 py-1.5 md:px-3 md:py-2 rounded-lg text-xs md:text-sm font-medium text-muted-foreground max-w-[120px] md:max-w-[180px]">
<SessionStatusIndicator sessionID={sessionID} showLabel /> <SessionStatusIndicator sessionID={sessionID} showLabel />
@@ -1421,11 +1415,11 @@ return (
> >
{!isSessionActive && !hideSecondaryButtons && ( {!isSessionActive && !hideSecondaryButtons && (
<button <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 flex-1 md:flex-initial md:w-auto max-w-[110px] md:max-w-[220px] dark:border-border/30 flex flex-col items-start justify-center overflow-hidden" 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 flex-1 md:flex-initial md:w-auto md:max-w-[220px] dark:border-border/30 flex flex-col items-start justify-center overflow-hidden"
> >
<span className="truncate w-full text-left">{displayModelName || 'Select model'}</span> <span className="truncate w-full text-left">{displayModelName || 'Select model'}</span>
{hasVariants && currentVariant && ( {hasVariants && currentVariant && (
<span className="text-[10px] text-highlight truncate w-full text-center capitalize">{currentVariant}</span> <span className="text-[10px] text-highlight truncate w-full text-left capitalize">{currentVariant}</span>
)} )}
</button> </button>
)} )}
@@ -1461,12 +1455,23 @@ return (
/> />
<button <button
type="button" type="button"
onClick={() => fileInputRef.current?.click()} onClick={openFilePicker}
className="hidden md:block p-2 rounded-lg bg-muted hover:bg-muted-foreground/20 text-muted-foreground hover:text-foreground transition-all duration-200 active:scale-95 hover:scale-105 shadow-md border border-border" className="hidden md:block p-2 rounded-lg bg-muted hover:bg-muted-foreground/20 text-muted-foreground hover:text-foreground transition-all duration-200 active:scale-95 hover:scale-105 shadow-md border border-border"
title="Upload image or PDF" title="Upload image or PDF"
> >
<Upload className="w-5 h-5" /> <Upload className="w-5 h-5" />
</button> </button>
{isMobile && directory && (
<ComposerToolsMenu
sessionID={sessionID}
directory={directory}
goalArmed={isGoalArmed}
goalDisabled={isGoalModeDisabled}
goalLabel={goalButtonLabel}
onToggleGoal={toggleGoalArmed}
onAttachFile={openFilePicker}
/>
)}
{sttEnabled && sttSupported && ( {sttEnabled && sttSupported && (
renderVoiceButton('desktop') renderVoiceButton('desktop')
)} )}
@@ -576,7 +576,7 @@ export function ModelQuickSelect({
return ( return (
<> <>
{children && ( {children && (
<span onClick={() => !disabled && handleOpenChange(true)}> <span className="contents" onClick={() => !disabled && handleOpenChange(true)}>
{children} {children}
</span> </span>
)} )}
@@ -0,0 +1,54 @@
import { useQuery } from '@tanstack/react-query'
import { GitBranch } from 'lucide-react'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { listBranches } from '@/api/repos'
import { getOriginOnlyBranchNames } from '@/lib/utils'
interface BaseBranchSelectProps {
repoId: number
value: string
onValueChange: (value: string) => void
id?: string
placeholder: string
}
export function BaseBranchSelect({ repoId, value, onValueChange, id, placeholder }: BaseBranchSelectProps) {
const { data: branchesData, isLoading } = useQuery({
queryKey: ['branches', repoId],
queryFn: () => listBranches(repoId),
staleTime: 30000,
})
const localBranches = (branchesData?.branches ?? []).filter((b) => b.type === 'local')
const remoteBranchNames = getOriginOnlyBranchNames(branchesData?.branches ?? [])
return (
<Select value={value} onValueChange={onValueChange} disabled={isLoading}>
<SelectTrigger id={id} className="bg-background border-border text-foreground">
<SelectValue placeholder={isLoading ? 'Loading branches...' : placeholder} />
</SelectTrigger>
<SelectContent className="bg-popover border-border">
{localBranches.map((branch) => (
<SelectItem key={`local-${branch.name}`} value={branch.name}>
<div className="flex items-center gap-2">
<GitBranch className="w-3.5 h-3.5" />
<span>{branch.name}</span>
{branch.current && (
<span className="text-xs text-muted-foreground">(current)</span>
)}
</div>
</SelectItem>
))}
{remoteBranchNames.map((name) => (
<SelectItem key={`remote-${name}`} value={`origin/${name}`}>
<div className="flex items-center gap-2">
<GitBranch className="w-3.5 h-3.5 text-info" />
<span>{name}</span>
<span className="text-xs text-muted-foreground">(remote)</span>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
)
}
@@ -8,6 +8,8 @@ import { AlertCircle, GitBranch, Loader2 } from 'lucide-react'
import { createRepo, listBranches, type CreateRepoOptions } from '@/api/repos' import { createRepo, listBranches, type CreateRepoOptions } from '@/api/repos'
import { showToast } from '@/lib/toast' import { showToast } from '@/lib/toast'
import { invalidateRepoGitCaches } from '@/lib/queryInvalidation' import { invalidateRepoGitCaches } from '@/lib/queryInvalidation'
import { getOriginOnlyBranchNames } from '@/lib/utils'
import { BaseBranchSelect } from './BaseBranchSelect'
interface CreateWorktreeDialogProps { interface CreateWorktreeDialogProps {
open: boolean open: boolean
@@ -51,28 +53,18 @@ export function CreateWorktreeDialog({
const localBranches = (branchesData?.branches ?? []).filter((b) => b.type === 'local') const localBranches = (branchesData?.branches ?? []).filter((b) => b.type === 'local')
const seenRemoteNames = new Set<string>() const remoteBranchNames = getOriginOnlyBranchNames(branchesData?.branches ?? [])
const remoteBranches = (branchesData?.branches ?? [])
.filter((b) => b.type === 'remote' && b.name.startsWith('remotes/origin/'))
.map((b) => ({ ...b, shortName: b.name.slice('remotes/origin/'.length) }))
.filter((b) => b.shortName.length > 0)
.filter((b) => !localBranches.some((lb) => lb.name === b.shortName))
.filter((b) => {
if (seenRemoteNames.has(b.shortName)) return false
seenRemoteNames.add(b.shortName)
return true
})
const checkoutCandidates = [ const checkoutCandidates = [
...localBranches ...localBranches
.filter((b) => !b.current && !b.isWorktree) .filter((b) => !b.current && !b.isWorktree)
.map((b) => ({ name: b.name, remote: false })), .map((b) => ({ name: b.name, remote: false })),
...remoteBranches.map((b) => ({ name: b.shortName, remote: true })), ...remoteBranchNames.map((name) => ({ name, remote: true })),
] ]
const existingBranchNames = new Set([ const existingBranchNames = new Set([
...localBranches.map((b) => b.name), ...localBranches.map((b) => b.name),
...remoteBranches.map((b) => b.shortName), ...remoteBranchNames,
]) ])
const trimmedBranchName = branchName.trim() const trimmedBranchName = branchName.trim()
@@ -219,37 +211,12 @@ export function CreateWorktreeDialog({
<div className="space-y-1.5"> <div className="space-y-1.5">
<label className="text-sm font-medium">Base branch</label> <label className="text-sm font-medium">Base branch</label>
<Select value={baseBranch} onValueChange={setBaseBranch} disabled={branchesLoading}> <BaseBranchSelect
<SelectTrigger className="bg-background border-border text-foreground"> repoId={repoId}
<SelectValue placeholder={branchesLoading ? 'Loading branches...' : 'Select a base branch'} /> value={baseBranch}
</SelectTrigger> onValueChange={setBaseBranch}
<SelectContent className="bg-popover border-border"> placeholder="Select a base branch"
{localBranches.length > 0 && ( />
<>
{localBranches.map((branch) => (
<SelectItem key={`local-${branch.name}`} value={branch.name}>
<div className="flex items-center gap-2">
<GitBranch className="w-3.5 h-3.5" />
<span>{branch.name}</span>
{branch.current && (
<span className="text-xs text-muted-foreground">(current)</span>
)}
</div>
</SelectItem>
))}
</>
)}
{remoteBranches.map((branch) => (
<SelectItem key={`remote-${branch.name}`} value={`origin/${branch.shortName}`}>
<div className="flex items-center gap-2">
<GitBranch className="w-3.5 h-3.5 text-info" />
<span>{branch.shortName}</span>
<span className="text-xs text-muted-foreground">(remote)</span>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground">
The new branch will be created from this branch. The new branch will be created from this branch.
</p> </p>
@@ -1,4 +1,4 @@
import { describe, it, expect, vi, beforeEach } from 'vitest' import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest'
import { render, screen, waitFor, within } from '@testing-library/react' import { render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event' import userEvent from '@testing-library/user-event'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
@@ -11,6 +11,8 @@ const mocks = vi.hoisted(() => ({
launchMultiRun: vi.fn(), launchMultiRun: vi.fn(),
discardMultiRunEntry: vi.fn(), discardMultiRunEntry: vi.fn(),
useProvidersWithModels: vi.fn(), useProvidersWithModels: vi.fn(),
useOpenCodeModelState: vi.fn(),
listBranches: vi.fn(),
})) }))
const mockNavigate = vi.fn() const mockNavigate = vi.fn()
@@ -30,6 +32,14 @@ vi.mock('@/hooks/useProvidersWithModels', () => ({
useProvidersWithModels: mocks.useProvidersWithModels, useProvidersWithModels: mocks.useProvidersWithModels,
})) }))
vi.mock('@/hooks/useModelSelection', () => ({
useOpenCodeModelState: mocks.useOpenCodeModelState,
}))
vi.mock('@/api/repos', () => ({
listBranches: mocks.listBranches,
}))
vi.mock('@/lib/toast', () => ({ vi.mock('@/lib/toast', () => ({
showToast: { showToast: {
success: vi.fn(), success: vi.fn(),
@@ -120,13 +130,141 @@ function renderDialog(overrides: Partial<React.ComponentProps<typeof MultiRunDia
) )
} }
function checkboxLabels() {
return screen.getAllByRole('checkbox').map((checkbox) => checkbox.getAttribute('aria-label'))
}
async function fillLaunchForm(user: ReturnType<typeof userEvent.setup>) {
await user.type(screen.getByLabelText('Group name'), 'Sweep')
await user.type(screen.getByLabelText('Prompt'), 'go')
await user.click(screen.getByRole('checkbox', { name: 'GPT-4o' }))
}
describe('MultiRunDialog', () => { describe('MultiRunDialog', () => {
beforeAll(() => {
Element.prototype.hasPointerCapture ??= () => false
Element.prototype.setPointerCapture ??= () => {}
Element.prototype.releasePointerCapture ??= () => {}
Element.prototype.scrollIntoView ??= () => {}
})
beforeEach(() => { beforeEach(() => {
vi.clearAllMocks() vi.clearAllMocks()
mocks.useProvidersWithModels.mockReturnValue({ data: providers, isLoading: false }) mocks.useProvidersWithModels.mockReturnValue({ data: providers, isLoading: false })
mocks.useOpenCodeModelState.mockReturnValue({ data: { recent: [], favorite: [], variant: {} } })
mocks.listBranches.mockResolvedValue({
branches: [
{ name: 'main', type: 'local', current: true },
{ name: 'remotes/origin/HEAD', type: 'remote', current: false },
{ name: 'remotes/origin/release', type: 'remote', current: false },
],
status: { ahead: 0, behind: 0 },
})
mocks.listMultiRuns.mockResolvedValue([]) mocks.listMultiRuns.mockResolvedValue([])
}) })
it('lists favorite then recent models before provider groups without duplicates', () => {
mocks.useOpenCodeModelState.mockReturnValue({
data: {
favorite: [{ providerID: 'anthropic', modelID: 'claude-sonnet' }],
recent: [
{ providerID: 'openai', modelID: 'gpt-4.1' },
{ providerID: 'anthropic', modelID: 'claude-sonnet' },
{ providerID: 'missing', modelID: 'gone' },
],
variant: {},
},
})
renderDialog()
expect(screen.getByText('Favorites')).toBeInTheDocument()
expect(screen.getByText('Recent')).toBeInTheDocument()
expect(checkboxLabels()).toEqual([
'Claude Sonnet',
'GPT-4.1',
'GPT-4o',
'GPT-4o mini',
'Claude Opus',
'Claude Haiku',
'Claude Sonnet 4.5',
])
})
it('filters models by every search term and keeps favorites first', async () => {
const user = userEvent.setup()
mocks.useOpenCodeModelState.mockReturnValue({
data: { favorite: [{ providerID: 'anthropic', modelID: 'claude-sonnet-4.5' }], recent: [], variant: {} },
})
renderDialog()
await user.type(screen.getByLabelText('Search models'), 'sonnet')
await waitFor(() => expect(checkboxLabels()).toEqual(['Claude Sonnet 4.5', 'Claude Sonnet']))
await user.clear(screen.getByLabelText('Search models'))
await user.type(screen.getByLabelText('Search models'), 'anthropic haiku')
await waitFor(() => expect(checkboxLabels()).toEqual(['Claude Haiku']))
await user.type(screen.getByLabelText('Search models'), 'zzz')
expect(await screen.findByText('No models match your search.')).toBeInTheDocument()
})
it('keeps selections that are hidden by the search filter', async () => {
const user = userEvent.setup()
renderDialog()
await user.click(screen.getByRole('checkbox', { name: 'GPT-4o' }))
await user.type(screen.getByLabelText('Search models'), 'claude')
await waitFor(() => expect(screen.queryByRole('checkbox', { name: 'GPT-4o' })).not.toBeInTheDocument())
expect(screen.getByText('1/5 selected')).toBeInTheDocument()
})
it('submits the selected remote branch as the base ref', async () => {
const user = userEvent.setup()
mocks.launchMultiRun.mockResolvedValue(startedRun)
renderDialog()
await fillLaunchForm(user)
const branchSelect = screen.getByRole('combobox', { name: 'Start from' })
await waitFor(() => expect(branchSelect).toBeEnabled())
await user.click(branchSelect)
expect(screen.queryByRole('option', { name: /HEAD/ })).not.toBeInTheDocument()
await user.click(screen.getByRole('option', { name: /release/ }))
await user.click(screen.getByRole('button', { name: 'Launch' }))
await waitFor(() => {
expect(mocks.launchMultiRun).toHaveBeenCalledWith({
repoId: 7,
name: 'Sweep',
prompt: 'go',
models: ['openai/gpt-4o'],
isolate: true,
baseRef: 'origin/release',
})
})
})
it('hides the base branch and omits it when runs are not isolated', async () => {
const user = userEvent.setup()
mocks.launchMultiRun.mockResolvedValue(startedRun)
renderDialog()
await fillLaunchForm(user)
await user.click(screen.getByRole('switch', { name: 'Isolate runs' }))
expect(screen.queryByRole('combobox', { name: 'Start from' })).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Launch' }))
await waitFor(() => {
expect(mocks.launchMultiRun).toHaveBeenCalledWith({
repoId: 7,
name: 'Sweep',
prompt: 'go',
models: ['openai/gpt-4o'],
isolate: false,
})
})
})
it('caps model selection at five', async () => { it('caps model selection at five', async () => {
const user = userEvent.setup() const user = userEvent.setup()
renderDialog() renderDialog()
+131 -32
View File
@@ -1,6 +1,6 @@
import { memo, useCallback, useEffect, useMemo, useState } from 'react' import { memo, useCallback, useDeferredValue, useEffect, useMemo, useState, type ReactNode } from 'react'
import { useNavigate } from 'react-router-dom' import { useNavigate } from 'react-router-dom'
import { Loader2, Trash2, ArrowUpRight } from 'lucide-react' import { Loader2, Trash2, ArrowUpRight, Clock, Search, Star } from 'lucide-react'
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog' import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs' import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
@@ -12,9 +12,18 @@ import { Badge } from '@/components/ui/badge'
import { Label } from '@/components/ui/label' import { Label } from '@/components/ui/label'
import { ConfirmDestructiveDialog } from '@/components/ui/confirm-destructive-dialog' import { ConfirmDestructiveDialog } from '@/components/ui/confirm-destructive-dialog'
import { SessionStatusIndicator } from '@/components/ui/session-status-indicator' import { SessionStatusIndicator } from '@/components/ui/session-status-indicator'
import { BaseBranchSelect } from '@/components/repo/BaseBranchSelect'
import { useProvidersWithModels } from '@/hooks/useProvidersWithModels' import { useProvidersWithModels } from '@/hooks/useProvidersWithModels'
import { useOpenCodeModelState } from '@/hooks/useModelSelection'
import { useDiscardMultiRunEntry, useLaunchMultiRun, useMultiRuns } from '@/hooks/useMultiRuns' import { useDiscardMultiRunEntry, useLaunchMultiRun, useMultiRuns } from '@/hooks/useMultiRuns'
import { formatModelName, formatProviderName, providerModelRef, type ProviderWithModels } from '@/api/providers' import {
formatModelName,
formatProviderName,
providerModelRef,
type ModelSelection,
type OpenCodeModelState,
type ProviderWithModels,
} from '@/api/providers'
import { buildSessionPath } from '@opencode-manager/shared/utils' import { buildSessionPath } from '@opencode-manager/shared/utils'
import { import {
MULTI_RUN_MAX_MODELS, MULTI_RUN_MAX_MODELS,
@@ -38,6 +47,21 @@ interface PendingDiscard {
isolated: boolean isolated: boolean
} }
interface ModelOption {
value: string
label: string
providerName: string
searchText: string
}
interface ModelSection {
key: string
title: string
icon?: ReactNode
pinned: boolean
options: ModelOption[]
}
const STATUS_LABELS: Record<MultiRunEntryStatus, string> = { const STATUS_LABELS: Record<MultiRunEntryStatus, string> = {
starting: 'Starting', starting: 'Starting',
started: 'Started', started: 'Started',
@@ -45,6 +69,54 @@ const STATUS_LABELS: Record<MultiRunEntryStatus, string> = {
discarded: 'Discarded', discarded: 'Discarded',
} }
function buildModelSections(providers: ProviderWithModels[], modelState: OpenCodeModelState | undefined): ModelSection[] {
const optionsByValue = new Map<string, ModelOption>()
const providerSections = providers.map((provider): ModelSection => {
const providerName = formatProviderName(provider)
const options = provider.models.map((model) => {
const label = formatModelName(model)
const value = providerModelRef(provider, model)
const option = { value, label, providerName, searchText: `${label} ${value} ${providerName}`.toLowerCase() }
optionsByValue.set(value, option)
return option
})
return { key: `provider:${provider.id}`, title: providerName, pinned: false, options }
})
const pinnedValues = new Set<string>()
const pinOptions = (selections: ModelSelection[] = []) =>
selections.flatMap((selection) => {
const option = optionsByValue.get(providerModelRef({ id: selection.providerID }, { id: selection.modelID }))
if (!option || pinnedValues.has(option.value)) return []
pinnedValues.add(option.value)
return [option]
})
const favoriteOptions = pinOptions(modelState?.favorite)
const recentOptions = pinOptions(modelState?.recent)
const sections: ModelSection[] = [
{ key: 'favorites', title: 'Favorites', icon: <Star className="h-3.5 w-3.5" />, pinned: true, options: favoriteOptions },
{ key: 'recent', title: 'Recent', icon: <Clock className="h-3.5 w-3.5" />, pinned: true, options: recentOptions },
...providerSections.map((section) => ({
...section,
options: section.options.filter((option) => !pinnedValues.has(option.value)),
})),
]
return sections.filter((section) => section.options.length > 0)
}
function filterModelSections(sections: ModelSection[], query: string): ModelSection[] {
const terms = query.toLowerCase().split(/\s+/).filter(Boolean)
if (terms.length === 0) return sections
return sections
.map((section) => ({
...section,
options: section.options.filter((option) => terms.every((term) => option.searchText.includes(term))),
}))
.filter((section) => section.options.length > 0)
}
export function MultiRunDialog({ export function MultiRunDialog({
repoId, repoId,
directory, directory,
@@ -59,9 +131,12 @@ export function MultiRunDialog({
const [selectedModels, setSelectedModels] = useState<string[]>([]) const [selectedModels, setSelectedModels] = useState<string[]>([])
const [isolate, setIsolate] = useState(true) const [isolate, setIsolate] = useState(true)
const [baseRef, setBaseRef] = useState('') const [baseRef, setBaseRef] = useState('')
const [modelSearch, setModelSearch] = useState('')
const deferredModelSearch = useDeferredValue(modelSearch)
const [pendingDiscard, setPendingDiscard] = useState<PendingDiscard | null>(null) const [pendingDiscard, setPendingDiscard] = useState<PendingDiscard | null>(null)
const { data: providers } = useProvidersWithModels({ enabled: open, directory }) const { data: providers } = useProvidersWithModels({ enabled: open, directory })
const { data: modelState } = useOpenCodeModelState(directory, open)
const runsQuery = useMultiRuns(repoId, open) const runsQuery = useMultiRuns(repoId, open)
const launch = useLaunchMultiRun(repoId) const launch = useLaunchMultiRun(repoId)
const discard = useDiscardMultiRunEntry(repoId) const discard = useDiscardMultiRunEntry(repoId)
@@ -74,11 +149,13 @@ export function MultiRunDialog({
setSelectedModels([]) setSelectedModels([])
setIsolate(true) setIsolate(true)
setBaseRef(defaultBaseRef ?? '') setBaseRef(defaultBaseRef ?? '')
setModelSearch('')
}, [open, defaultBaseRef]) }, [open, defaultBaseRef])
const modelGroups = useMemo( const modelSections = useMemo(() => buildModelSections(providers, modelState), [providers, modelState])
() => providers.filter((provider) => provider.models.length > 0), const visibleModelSections = useMemo(
[providers], () => filterModelSections(modelSections, deferredModelSearch),
[modelSections, deferredModelSearch],
) )
const toggleModel = useCallback((value: string, checked: boolean) => { const toggleModel = useCallback((value: string, checked: boolean) => {
@@ -101,7 +178,7 @@ export function MultiRunDialog({
prompt: prompt.trim(), prompt: prompt.trim(),
models: selectedModels, models: selectedModels,
isolate, isolate,
...(baseRef.trim() ? { baseRef: baseRef.trim() } : {}), ...(isolate && baseRef ? { baseRef } : {}),
} }
launch.mutate(request, { onSuccess: () => setActiveTab('runs') }) launch.mutate(request, { onSuccess: () => setActiveTab('runs') })
} }
@@ -170,11 +247,23 @@ export function MultiRunDialog({
{selectedModels.length}/{MULTI_RUN_MAX_MODELS} selected {selectedModels.length}/{MULTI_RUN_MAX_MODELS} selected
</span> </span>
</div> </div>
<div className="relative">
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
value={modelSearch}
onChange={(event) => setModelSearch(event.target.value)}
placeholder="Search models..."
aria-label="Search models"
autoComplete="off"
className="pl-9"
/>
</div>
<div className="max-h-56 overflow-y-auto rounded-md border border-border divide-y divide-border"> <div className="max-h-56 overflow-y-auto rounded-md border border-border divide-y divide-border">
<ModelCheckboxList <ModelCheckboxList
providers={modelGroups} sections={visibleModelSections}
selectedModels={selectedModels} selectedModels={selectedModels}
onToggle={toggleModel} onToggle={toggleModel}
emptyLabel={modelSections.length === 0 ? 'No models available.' : 'No models match your search.'}
/> />
</div> </div>
</div> </div>
@@ -187,16 +276,19 @@ export function MultiRunDialog({
<Switch id="multi-run-isolate" checked={isolate} onCheckedChange={setIsolate} /> <Switch id="multi-run-isolate" checked={isolate} onCheckedChange={setIsolate} />
</div> </div>
<div className="space-y-1.5"> {isolate && (
<Label htmlFor="multi-run-base-ref">Start from</Label> <div className="space-y-1.5">
<Input <Label htmlFor="multi-run-base-ref">Start from</Label>
id="multi-run-base-ref" <BaseBranchSelect
value={baseRef} id="multi-run-base-ref"
onChange={(event) => setBaseRef(event.target.value)} repoId={repoId}
placeholder="Current HEAD" value={baseRef}
/> onValueChange={setBaseRef}
<p className="text-xs text-muted-foreground">Branch or ref. Empty starts from the current HEAD.</p> placeholder="Current HEAD"
</div> />
<p className="text-xs text-muted-foreground">Each isolated workspace starts from this branch.</p>
</div>
)}
<div className="flex justify-end"> <div className="flex justify-end">
<Button onClick={handleLaunch} disabled={!canSubmit}> <Button onClick={handleLaunch} disabled={!canSubmit}>
@@ -300,38 +392,45 @@ export function MultiRunDialog({
} }
interface ModelCheckboxListProps { interface ModelCheckboxListProps {
providers: ProviderWithModels[] sections: ModelSection[]
selectedModels: string[] selectedModels: string[]
onToggle: (value: string, checked: boolean) => void onToggle: (value: string, checked: boolean) => void
emptyLabel: string
} }
const ModelCheckboxList = memo(function ModelCheckboxList({ const ModelCheckboxList = memo(function ModelCheckboxList({
providers, sections,
selectedModels, selectedModels,
onToggle, onToggle,
emptyLabel,
}: ModelCheckboxListProps) { }: ModelCheckboxListProps) {
if (providers.length === 0) { if (sections.length === 0) {
return <p className="p-3 text-sm text-muted-foreground">No models available.</p> return <p className="p-3 text-sm text-muted-foreground">{emptyLabel}</p>
} }
return ( return (
<> <>
{providers.map((provider) => ( {sections.map((section) => (
<div key={provider.id} className="p-3 space-y-2"> <div key={section.key} className="p-3 space-y-2">
<p className="text-xs font-medium text-muted-foreground">{formatProviderName(provider)}</p> <p className="flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
{provider.models.map((model) => { {section.icon}
const value = providerModelRef(provider, model) {section.title}
const checked = selectedModels.includes(value) </p>
{section.options.map((option) => {
const checked = selectedModels.includes(option.value)
const atCapacity = selectedModels.length >= MULTI_RUN_MAX_MODELS && !checked const atCapacity = selectedModels.length >= MULTI_RUN_MAX_MODELS && !checked
return ( return (
<label key={value} className="flex items-center gap-2 text-sm"> <label key={option.value} className="flex items-center gap-2 text-sm">
<Checkbox <Checkbox
aria-label={formatModelName(model)} aria-label={option.label}
checked={checked} checked={checked}
disabled={atCapacity} disabled={atCapacity}
onCheckedChange={(next) => onToggle(value, next === true)} onCheckedChange={(next) => onToggle(option.value, next === true)}
/> />
<span className="truncate">{formatModelName(model)}</span> <span className="truncate">{option.label}</span>
{section.pinned ? (
<span className="ml-auto shrink-0 text-xs text-muted-foreground">{option.providerName}</span>
) : null}
</label> </label>
) )
})} })}
@@ -257,7 +257,7 @@ export function BackgroundWorkBar({ sessionID, directory, messages, isSessionAct
<button <button
type="button" type="button"
onClick={() => setExpanded((value) => !value)} onClick={() => setExpanded((value) => !value)}
className="ml-auto flex items-center gap-1 rounded-md border border-border bg-card/60 px-2 py-1 text-muted-foreground hover:text-foreground" className="ml-auto flex items-center gap-1 rounded-md border border-border bg-card px-2 py-1 text-muted-foreground hover:text-foreground"
aria-expanded={expanded} aria-expanded={expanded}
> >
{hasRunningTask {hasRunningTask
@@ -270,7 +270,7 @@ export function BackgroundWorkBar({ sessionID, directory, messages, isSessionAct
</div> </div>
{expanded && tasks.length > 0 && ( {expanded && tasks.length > 0 && (
<ul className="rounded-md border border-border bg-card/60"> <ul className="rounded-md border border-border bg-card">
{tasks.map((task) => ( {tasks.map((task) => (
<BackgroundTaskRow <BackgroundTaskRow
key={`${task.kind}:${task.id}`} key={`${task.kind}:${task.id}`}
@@ -1,5 +1,5 @@
import { Shield, ShieldCheck } from 'lucide-react' import { Shield, ShieldCheck } from 'lucide-react'
import { useSessionPermissionMode, useSetSessionPermissionMode } from '@/hooks/useSessionPermissionMode' import { usePermissionModeToggle } from '@/hooks/usePermissionModeToggle'
import { IconToggleButton } from '@/components/ui/icon-toggle-button' import { IconToggleButton } from '@/components/ui/icon-toggle-button'
interface PermissionModeToggleProps { interface PermissionModeToggleProps {
@@ -8,33 +8,10 @@ interface PermissionModeToggleProps {
} }
export function PermissionModeToggle({ sessionID, directory }: PermissionModeToggleProps) { export function PermissionModeToggle({ sessionID, directory }: PermissionModeToggleProps) {
const { data, isError } = useSessionPermissionMode(sessionID) const { isAuto, disabled, label, toggle } = usePermissionModeToggle(sessionID, directory)
const setMode = useSetSessionPermissionMode(sessionID)
const loaded = data !== undefined
const isAuto = data?.mode === 'auto'
const lockedReason = data?.lockedReason ?? null
const disabled = !loaded || lockedReason !== null || setMode.isPending
const label = !loaded
? isError
? 'Permissions: unavailable'
: 'Permissions: loading'
: lockedReason === 'child'
? 'Inherited from parent session'
: lockedReason === 'schedule'
? "Scheduled runs use the schedule's permission configuration"
: isAuto
? 'Permissions: accept everything'
: 'Permissions: ask every time'
const handleClick = () => {
if (disabled) return
setMode.mutate({ directory, mode: isAuto ? 'ask' : 'auto' })
}
return ( return (
<IconToggleButton active={isAuto} label={label} disabled={disabled} onClick={handleClick}> <IconToggleButton active={isAuto} label={label} disabled={disabled} onClick={toggle}>
{isAuto ? <ShieldCheck className="w-5 h-5" /> : <Shield className="w-5 h-5" />} {isAuto ? <ShieldCheck className="w-5 h-5" /> : <Shield className="w-5 h-5" />}
</IconToggleButton> </IconToggleButton>
) )
@@ -40,7 +40,7 @@ export function SessionGoalBar({ sessionID }: { sessionID: string }) {
const reason = goal.stopReason ? getGoalStopReasonLabel(goal.stopReason) : goal.lastReason const reason = goal.stopReason ? getGoalStopReasonLabel(goal.stopReason) : goal.lastReason
return ( return (
<div className="mb-1 flex flex-col gap-1 rounded-lg border border-border bg-card/70 px-2 py-1.5 text-xs"> <div className="mb-1 flex flex-col gap-1 rounded-lg border border-border bg-card px-2 py-1.5 text-xs">
<div className="flex flex-wrap items-center gap-2"> <div className="flex flex-wrap items-center gap-2">
<Badge <Badge
variant="outline" variant="outline"
@@ -8,6 +8,14 @@ interface IconToggleButtonProps {
children: ReactNode children: ReactNode
} }
export function getIconToggleButtonClassName(active: boolean): string {
return `p-2 rounded-lg transition-all duration-200 active:scale-95 hover:scale-105 shadow-md border disabled:opacity-50 disabled:cursor-not-allowed disabled:active:scale-100 disabled:hover:scale-100 ${
active
? 'bg-highlight hover:bg-highlight/90 text-highlight-foreground border-highlight'
: 'bg-muted hover:bg-muted-foreground/20 text-muted-foreground hover:text-foreground border-border'
}`
}
export function IconToggleButton({ active, label, disabled = false, onClick, children }: IconToggleButtonProps) { export function IconToggleButton({ active, label, disabled = false, onClick, children }: IconToggleButtonProps) {
return ( return (
<button <button
@@ -17,11 +25,7 @@ export function IconToggleButton({ active, label, disabled = false, onClick, chi
aria-pressed={active} aria-pressed={active}
aria-label={label} aria-label={label}
title={label} title={label}
className={`p-2 rounded-lg transition-all duration-200 active:scale-95 hover:scale-105 shadow-md border disabled:opacity-50 disabled:cursor-not-allowed disabled:active:scale-100 disabled:hover:scale-100 ${ className={getIconToggleButtonClassName(active)}
active
? 'bg-highlight hover:bg-highlight/90 text-highlight-foreground border-highlight'
: 'bg-muted hover:bg-muted-foreground/20 text-muted-foreground hover:text-foreground border-border'
}`}
> >
{children} {children}
</button> </button>
+11 -6
View File
@@ -23,6 +23,16 @@ const isSameModel = (left: ModelSelection, right: ModelSelection) => (
left.providerID === right.providerID && left.modelID === right.modelID left.providerID === right.providerID && left.modelID === right.modelID
) )
export function useOpenCodeModelState(directory?: string, enabled = true) {
return useQuery({
queryKey: [...modelStateQueryKey, directory],
queryFn: () => getOpenCodeModelState(),
staleTime: 30000,
placeholderData: keepPreviousData,
enabled,
})
}
export function useModelSelection(directory?: string): UseModelSelectionResult { export function useModelSelection(directory?: string): UseModelSelectionResult {
const queryClient = useQueryClient() const queryClient = useQueryClient()
@@ -37,12 +47,7 @@ export function useModelSelection(directory?: string): UseModelSelectionResult {
getModelString getModelString
} = useModelStore() } = useModelStore()
const { data: modelState, isLoading: isModelStateLoading } = useQuery({ const { data: modelState, isLoading: isModelStateLoading } = useOpenCodeModelState(directory)
queryKey: [...modelStateQueryKey, directory],
queryFn: () => getOpenCodeModelState(),
staleTime: 30000,
placeholderData: keepPreviousData,
})
const { data: configModelString, isLoading: isConfigModelLoading } = useQuery({ const { data: configModelString, isLoading: isConfigModelLoading } = useQuery({
queryKey: ['opencode', 'config', 'model', directory], queryKey: ['opencode', 'config', 'model', directory],
@@ -0,0 +1,30 @@
import { useSessionPermissionMode, useSetSessionPermissionMode } from '@/hooks/useSessionPermissionMode'
export function usePermissionModeToggle(sessionID: string, directory: string) {
const { data, isError } = useSessionPermissionMode(sessionID)
const setMode = useSetSessionPermissionMode(sessionID)
const loaded = data !== undefined
const isAuto = data?.mode === 'auto'
const lockedReason = data?.lockedReason ?? null
const disabled = !loaded || lockedReason !== null || setMode.isPending
const label = !loaded
? isError
? 'Permissions: unavailable'
: 'Permissions: loading'
: lockedReason === 'child'
? 'Inherited from parent session'
: lockedReason === 'schedule'
? "Scheduled runs use the schedule's permission configuration"
: isAuto
? 'Permissions: accept everything'
: 'Permissions: ask every time'
const toggle = () => {
if (disabled) return
setMode.mutate({ directory, mode: isAuto ? 'ask' : 'auto' })
}
return { isAuto, disabled, label, toggle }
}
+54
View File
@@ -5,6 +5,7 @@ import {
sanitizeForTTS, sanitizeForTTS,
randomId, randomId,
formatShortRelativeTime, formatShortRelativeTime,
getOriginOnlyBranchNames,
} from './utils' } from './utils'
describe('sanitizeForTTS', () => { describe('sanitizeForTTS', () => {
@@ -89,6 +90,59 @@ describe('sanitizeForTTS', () => {
}) })
}) })
describe('getOriginOnlyBranchNames', () => {
it('returns short names for origin remote branches without a local branch', () => {
expect(
getOriginOnlyBranchNames([
{ name: 'main', type: 'local' },
{ name: 'remotes/origin/release', type: 'remote' },
]),
).toEqual(['release'])
})
it('excludes remote branches shadowed by a local branch', () => {
expect(
getOriginOnlyBranchNames([
{ name: 'release', type: 'local' },
{ name: 'remotes/origin/release', type: 'remote' },
]),
).toEqual([])
})
it('excludes non-origin remotes', () => {
expect(
getOriginOnlyBranchNames([
{ name: 'remotes/upstream/release', type: 'remote' },
{ name: 'remotes/origin/release', type: 'remote' },
]),
).toEqual(['release'])
})
it('excludes HEAD', () => {
expect(
getOriginOnlyBranchNames([
{ name: 'remotes/origin/HEAD', type: 'remote' },
{ name: 'remotes/origin/main', type: 'remote' },
]),
).toEqual(['main'])
})
it('excludes empty short names', () => {
expect(getOriginOnlyBranchNames([{ name: 'remotes/origin/', type: 'remote' }])).toEqual([])
})
it('dedupes while preserving input order', () => {
expect(
getOriginOnlyBranchNames([
{ name: 'remotes/origin/zeta', type: 'remote' },
{ name: 'remotes/origin/alpha', type: 'remote' },
{ name: 'remotes/origin/zeta', type: 'remote' },
{ name: 'remotes/origin/beta', type: 'remote' },
]),
).toEqual(['zeta', 'alpha', 'beta'])
})
})
describe('randomId', () => { describe('randomId', () => {
const originalRandomUUID = globalThis.crypto?.randomUUID const originalRandomUUID = globalThis.crypto?.randomUUID
+20
View File
@@ -2,6 +2,7 @@ import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge" import { twMerge } from "tailwind-merge"
import type { CSSProperties } from "react" import type { CSSProperties } from "react"
import type { Repo } from "@/api/types" import type { Repo } from "@/api/types"
import type { GitBranch } from "@/api/repos"
export { getRepoDisplayName } from '@opencode-manager/shared/utils' export { getRepoDisplayName } from '@opencode-manager/shared/utils'
@@ -9,6 +10,25 @@ export function getRepoBranchLabel(repo: Pick<Repo, 'currentBranch' | 'branch'>)
return repo.currentBranch || repo.branch || null return repo.currentBranch || repo.branch || null
} }
const ORIGIN_REMOTE_PREFIX = 'remotes/origin/'
export function getOriginOnlyBranchNames(branches: Pick<GitBranch, 'name' | 'type'>[]): string[] {
const localNames = new Set(branches.filter((b) => b.type === 'local').map((b) => b.name))
const seen = new Set<string>()
const result: string[] = []
for (const branch of branches) {
if (branch.type !== 'remote' || !branch.name.startsWith(ORIGIN_REMOTE_PREFIX)) continue
const shortName = branch.name.slice(ORIGIN_REMOTE_PREFIX.length)
if (shortName.length === 0 || shortName === 'HEAD') continue
if (localNames.has(shortName) || seen.has(shortName)) continue
seen.add(shortName)
result.push(shortName)
}
return result
}
export function cn(...inputs: ClassValue[]) { export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs)) return twMerge(clsx(inputs))
} }
+20 -6
View File
@@ -6,6 +6,7 @@ import { MessageThread } from "@/components/message/MessageThread";
import { PromptInput, type PromptInputHandle } from "@/components/message/PromptInput"; import { PromptInput, type PromptInputHandle } from "@/components/message/PromptInput";
import { FloatingTTSButton } from '@/components/message/FloatingTTSButton' import { FloatingTTSButton } from '@/components/message/FloatingTTSButton'
import { X, CornerUpLeft } from "lucide-react"; import { X, CornerUpLeft } from "lucide-react";
import { SquareFill } from "@/components/ui/square-fill";
import { Header } from "@/components/ui/header"; import { Header } from "@/components/ui/header";
import { SessionList } from "@/components/session/SessionList"; import { SessionList } from "@/components/session/SessionList";
import { getSessionListPath } from '@/lib/navigation' import { getSessionListPath } from '@/lib/navigation'
@@ -435,6 +436,12 @@ export function SessionDetail() {
promptInputRef.current?.openModelPicker(); promptInputRef.current?.openModelPicker();
}, []) }, [])
const handleInterruptSession = () => {
if (sessionId) {
interruptSession.mutate(sessionId);
}
};
const { leaderActive } = useKeyboardShortcuts({ const { leaderActive } = useKeyboardShortcuts({
openModelDialog: handleOpenModelDialog, openModelDialog: handleOpenModelDialog,
openSessions: handleShowSessionsDialog, openSessions: handleShowSessionsDialog,
@@ -458,11 +465,7 @@ export function SessionDetail() {
) as HTMLButtonElement; ) as HTMLButtonElement;
submitButton?.click(); submitButton?.click();
}, },
interruptSession: () => { interruptSession: handleInterruptSession,
if (sessionId) {
interruptSession.mutate(sessionId);
}
},
}); });
@@ -715,7 +718,7 @@ export function SessionDetail() {
style={{ bottom: inputBottomOffset }} style={{ bottom: inputBottomOffset }}
> >
<div className="relative w-[94%] md:max-w-4xl"> <div className="relative w-[94%] md:max-w-4xl">
<div className="absolute -top-9 right-0 z-50 flex flex-col items-end gap-2"> <div className="absolute bottom-full right-0 mb-2 z-50 flex flex-col items-end gap-2">
{ttsEnabled && !hasPromptContent && !isSessionActive && latestPlayableAssistant && ( {ttsEnabled && !hasPromptContent && !isSessionActive && latestPlayableAssistant && (
<FloatingTTSButton <FloatingTTSButton
messageId={latestPlayableAssistant.messageId} messageId={latestPlayableAssistant.messageId}
@@ -737,6 +740,17 @@ export function SessionDetail() {
<span className="text-sm font-medium hidden sm:inline">Clear</span> <span className="text-sm font-medium hidden sm:inline">Clear</span>
</button> </button>
)} )}
{isSessionActive && (
<button
type="button"
onClick={handleInterruptSession}
title="Stop"
aria-label="Stop"
className="md:hidden p-3 rounded-xl transition-all duration-200 active:scale-95 hover:scale-105 bg-destructive hover:bg-destructive/90 text-destructive-foreground border border-destructive/60 shadow-lg shadow-destructive/30"
>
<SquareFill className="w-5 h-5" />
</button>
)}
</div> </div>
{leaderActive && ( {leaderActive && (
<div className="absolute -top-12 left-1/2 -translate-x-1/2 z-50 px-4 py-2 rounded-xl bg-primary/90 text-primary-foreground border border-primary shadow-lg backdrop-blur-md animate-pulse"> <div className="absolute -top-12 left-1/2 -translate-x-1/2 z-50 px-4 py-2 rounded-xl bg-primary/90 text-primary-foreground border border-primary shadow-lg backdrop-blur-md animate-pulse">
@@ -22,6 +22,7 @@ const mocks = vi.hoisted(() => ({
useAutoScroll: vi.fn(), useAutoScroll: vi.fn(),
useDialogParam: vi.fn(), useDialogParam: vi.fn(),
useSessionStatusForSession: vi.fn(), useSessionStatusForSession: vi.fn(),
interruptMutate: vi.fn(),
PromptInput: vi.fn(), PromptInput: vi.fn(),
uiState: { isEditingMessage: false }, uiState: { isEditingMessage: false },
})) }))
@@ -39,7 +40,7 @@ vi.mock('@/config', () => ({
vi.mock('@/hooks/useOpenCode', () => ({ vi.mock('@/hooks/useOpenCode', () => ({
useSession: mocks.useSession, useSession: mocks.useSession,
useInterruptSession: vi.fn(() => ({ mutate: vi.fn() })), useInterruptSession: vi.fn(() => ({ mutate: mocks.interruptMutate })),
useUpdateSession: vi.fn(() => ({ mutate: vi.fn() })), useUpdateSession: vi.fn(() => ({ mutate: vi.fn() })),
useCreateSession: vi.fn(() => ({ mutateAsync: vi.fn() })), useCreateSession: vi.fn(() => ({ mutateAsync: vi.fn() })),
useConfig: mocks.useConfig, useConfig: mocks.useConfig,
@@ -389,6 +390,22 @@ describe('SessionDetail scroll floating button', () => {
expect(screen.queryByLabelText('Clear')).not.toBeInTheDocument() expect(screen.queryByLabelText('Clear')).not.toBeInTheDocument()
}) })
it('renders the mobile stop button while the session is active and interrupts on click', async () => {
renderWith({ mobile: true, showScrollButton: false, sessionActive: true })
const stopButton = await screen.findByTitle('Stop')
fireEvent.click(stopButton)
expect(mocks.interruptMutate).toHaveBeenCalledWith('test-session')
})
it('does not render the stop button while the session is idle', async () => {
renderWith({ mobile: true, showScrollButton: false, sessionActive: false })
await waitFor(() => expect(screen.getByText('MockedPromptInput')).toBeInTheDocument())
expect(screen.queryByTitle('Stop')).not.toBeInTheDocument()
})
it('clicking PromptInput scroll button calls scrollToBottom from useAutoScroll', async () => { it('clicking PromptInput scroll button calls scrollToBottom from useAutoScroll', async () => {
renderWith({ mobile: true, showScrollButton: true }) renderWith({ mobile: true, showScrollButton: true })