feat(source-control): edge-anchored sidebar toggle, branches header cleanup, orange current-branch accents (#349)

* feat(source-control): edge-anchored sidebar toggle, branches header cleanup, orange current-branch accents

* feat(settings): sidebar navigation with per-tab two-column layouts and mobile menu landing

* fix(ui): re-measure prompt overlay after edit remount and anchor mobile stop button above input
This commit is contained in:
Chris Scott authored and GitHub committed 2026-09-09 10:57:35 -04:00
1 parent 47d57df628
commit 16f9f9c2ee
28 files changed
+1777 -918

No files matched your search

@@ -1238,7 +1238,7 @@ return (
{showStopButton && (
<button
onClick={handleStop}
className="border fixed bottom-19 right-0 md:hidden z-50 p-3 rounded-xl transition-all duration-200 active:scale-95 hover:scale-105 bg-gradient-to-br from-red-600 to-red-700 hover:from-red-500 hover:to-red-600 text-destructive-foreground border border-red-500/60 shadow-lg shadow-red-500/30"
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-gradient-to-br from-red-600 to-red-700 hover:from-red-500 hover:to-red-600 text-destructive-foreground border border-red-500/60 shadow-lg shadow-red-500/30"
title="Stop"
>
<SquareFill className="w-5 h-5" />
@@ -12,7 +12,6 @@ import {
Sidebar,
SidebarSection,
SidebarItem,
SidebarCollapseToggle,
} from '@/components/ui/sidebar'
import { FolderGit2 } from 'lucide-react'
@@ -78,10 +77,6 @@ export function DesktopSidebar() {
return (
<>
<Sidebar collapsed={collapsed} onToggle={toggle} className='mt-2'>
<div className="flex justify-end px-2 py-1.5">
<SidebarCollapseToggle collapsed={collapsed} onToggle={toggle} />
</div>
{primary.length > 0 && (
<SidebarSection collapsed={collapsed}>
{primary.map((item: NavPrimaryCta) => (
@@ -154,206 +154,208 @@ export function AccountSettings() {
</Alert>
)}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6">
<Card className="border-0 shadow-none">
<CardHeader className="pb-3 sm:pb-4">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<User className="h-4 w-4 sm:h-5 sm:w-5" />
<CardTitle className="text-base sm:text-lg">Profile</CardTitle>
<div className="grid grid-cols-1 gap-4 sm:gap-6 @min-[1000px]:grid-cols-3 @min-[1000px]:items-start">
<div className="min-w-0 space-y-4 sm:space-y-6">
<Card className="border-0 shadow-none">
<CardHeader className="pb-3 sm:pb-4">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<User className="h-4 w-4 sm:h-5 sm:w-5" />
<CardTitle className="text-base sm:text-lg">Profile</CardTitle>
</div>
{!editingProfile && (
<Button variant="ghost" size="sm" onClick={() => setEditingProfile(true)} className="h-8">
<Edit2 className="h-3.5 w-3.5" />
</Button>
)}
</div>
{!editingProfile && (
<Button variant="ghost" size="sm" onClick={() => setEditingProfile(true)} className="h-8">
<Edit2 className="h-3.5 w-3.5" />
</Button>
</CardHeader>
<CardContent>
{editingProfile ? (
<div className="space-y-3 sm:space-y-4">
<div className="space-y-1.5">
<Label className="text-xs sm:text-sm">Name</Label>
<Input value={user.name} disabled className="h-9 sm:h-10 md:text-sm" />
</div>
<div className="space-y-1.5">
<Label className="text-xs sm:text-sm">Email</Label>
<Input value={user.email} disabled className="h-9 sm:h-10 md:text-sm" />
</div>
<Button variant="outline" onClick={() => setEditingProfile(false)} className="h-9 sm:h-10">
Done
</Button>
</div>
) : (
<div className="space-y-2 sm:space-y-3">
<div className="flex flex-col sm:flex-row sm:items-center gap-1.5 sm:gap-4">
<span className="text-xs sm:text-sm text-muted-foreground sm:w-20">Name</span>
<span className="text-sm font-medium truncate">{user.name}</span>
</div>
<div className="flex flex-col sm:flex-row sm:items-center gap-1.5 sm:gap-4">
<span className="text-xs sm:text-sm text-muted-foreground sm:w-20">Email</span>
<span className="text-sm truncate">{user.email}</span>
</div>
</div>
)}
</div>
</CardHeader>
<CardContent>
{editingProfile ? (
<div className="space-y-3 sm:space-y-4">
<div className="space-y-1.5">
<Label className="text-xs sm:text-sm">Name</Label>
<Input value={user.name} disabled className="h-9 sm:h-10 md:text-sm" />
</CardContent>
</Card>
<Card className="border-0 shadow-none">
<CardHeader className="pb-2 sm:pb-4">
<CardTitle className="flex items-center gap-2 text-base sm:text-lg">
<Lock className="h-4 w-4 sm:h-5 sm:w-5" />
Change Password
</CardTitle>
<CardDescription className="text-xs sm:text-sm">Update your account password</CardDescription>
</CardHeader>
<CardContent>
{!showChangePassword ? (
<Button
variant="outline"
onClick={() => setShowChangePassword(true)}
className="h-9 sm:h-10"
>
<Lock className="mr-2 h-4 w-4" />
Change Password
</Button>
) : (
<div className="space-y-3 sm:space-y-4">
<div className="space-y-1.5">
<Label htmlFor="current-password" className="text-xs sm:text-sm">Current Password</Label>
<Input
id="current-password"
type="password"
value={currentPassword}
onChange={(e) => setCurrentPassword(e.target.value)}
placeholder="Enter current password"
className="h-9 sm:h-10 md:text-sm"
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="new-password" className="text-xs sm:text-sm">New Password</Label>
<Input
id="new-password"
type="password"
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
placeholder="At least 8 characters"
className="h-9 sm:h-10 md:text-sm"
/>
</div>
<div className="flex flex-wrap gap-2">
<Button
onClick={handleChangePassword}
disabled={changePasswordMutation.isPending || !currentPassword || !newPassword}
className="h-9 sm:h-10"
>
{changePasswordMutation.isPending ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Lock className="mr-2 h-4 w-4" />
)}
Change Password
</Button>
<Button
variant="ghost"
onClick={() => setShowChangePassword(false)}
className="h-9 sm:h-10"
>
Cancel
</Button>
</div>
</div>
<div className="space-y-1.5">
<Label className="text-xs sm:text-sm">Email</Label>
<Input value={user.email} disabled className="h-9 sm:h-10 md:text-sm" />
</div>
<Button variant="outline" onClick={() => setEditingProfile(false)} className="h-9 sm:h-10">
Done
)}
</CardContent>
</Card>
</div>
<div className="min-w-0 @min-[1000px]:col-span-2">
<Card className="border-0 shadow-none">
<CardHeader className="pb-2 sm:pb-4">
<CardTitle className="flex items-center gap-2 text-base sm:text-lg">
<KeyRound className="h-4 w-4 sm:h-5 sm:w-5" />
Passkeys
</CardTitle>
<CardDescription className="text-xs sm:text-sm">Manage passkeys for passwordless sign-in</CardDescription>
</CardHeader>
<CardContent className="space-y-3 sm:space-y-4">
<div className="flex flex-col sm:flex-row gap-2">
<Input
placeholder="Passkey name (optional)"
value={passkeyName}
onChange={(e) => setPasskeyName(e.target.value)}
className="h-9 sm:h-10 md:text-sm"
/>
<Button
onClick={handleAddPasskey}
disabled={addPasskeyMutation.isPending}
className="h-9 sm:h-10 whitespace-nowrap"
>
{addPasskeyMutation.isPending ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Plus className="mr-2 h-4 w-4" />
)}
Add Passkey
</Button>
</div>
) : (
<div className="space-y-2 sm:space-y-3">
<div className="flex flex-col sm:flex-row sm:items-center gap-1.5 sm:gap-4">
<span className="text-xs sm:text-sm text-muted-foreground sm:w-20">Name</span>
<span className="text-sm font-medium truncate">{user.name}</span>
</div>
<div className="flex flex-col sm:flex-row sm:items-center gap-1.5 sm:gap-4">
<span className="text-xs sm:text-sm text-muted-foreground sm:w-20">Email</span>
<span className="text-sm truncate">{user.email}</span>
</div>
</div>
)}
</CardContent>
</Card>
<Card className="border-0 shadow-none">
<CardHeader className="pb-2 sm:pb-4">
<CardTitle className="flex items-center gap-2 text-base sm:text-lg">
<Lock className="h-4 w-4 sm:h-5 sm:w-5" />
Change Password
</CardTitle>
<CardDescription className="text-xs sm:text-sm">Update your account password</CardDescription>
</CardHeader>
<CardContent>
{!showChangePassword ? (
<Button
variant="outline"
onClick={() => setShowChangePassword(true)}
className="h-9 sm:h-10"
>
<Lock className="mr-2 h-4 w-4" />
Change Password
</Button>
) : (
<div className="space-y-3 sm:space-y-4">
<div className="space-y-1.5">
<Label htmlFor="current-password" className="text-xs sm:text-sm">Current Password</Label>
<Input
id="current-password"
type="password"
value={currentPassword}
onChange={(e) => setCurrentPassword(e.target.value)}
placeholder="Enter current password"
className="h-9 sm:h-10 md:text-sm"
/>
{passkeysLoading ? (
<div className="flex items-center justify-center py-4">
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
</div>
<div className="space-y-1.5">
<Label htmlFor="new-password" className="text-xs sm:text-sm">New Password</Label>
<Input
id="new-password"
type="password"
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
placeholder="At least 8 characters"
className="h-9 sm:h-10 md:text-sm"
/>
) : passkeys && passkeys.length > 0 ? (
<div className="space-y-2">
{passkeys.map((pk) => (
<div
key={pk.id}
className="flex items-center justify-between p-2.5 sm:p-3 bg-muted rounded-lg"
>
<div className="min-w-0 flex-1">
<p className="font-medium text-sm truncate">{pk.name || 'Unnamed Passkey'}</p>
<p className="text-xs text-muted-foreground truncate">
{pk.deviceType} - {new Date(pk.createdAt).toLocaleDateString()}
</p>
</div>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 ml-2 flex-shrink-0"
onClick={() => handleDeletePasskey(pk.id)}
disabled={deletePasskeyMutation.isPending}
>
{deletePasskeyMutation.isPending ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Trash2 className="h-4 w-4 text-destructive" />
)}
</Button>
</div>
))}
</div>
<div className="flex gap-2">
<Button
onClick={handleChangePassword}
disabled={changePasswordMutation.isPending || !currentPassword || !newPassword}
className="h-9 sm:h-10"
>
{changePasswordMutation.isPending ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Lock className="mr-2 h-4 w-4" />
)}
Change Password
</Button>
<Button
variant="ghost"
onClick={() => setShowChangePassword(false)}
className="h-9 sm:h-10"
>
Cancel
</Button>
</div>
</div>
)}
</CardContent>
</Card>
) : (
<p className="text-xs sm:text-sm text-muted-foreground text-center py-3">
No passkeys registered. Add one for passwordless sign-in.
</p>
)}
</CardContent>
</Card>
</div>
</div>
<Card className="border-0 shadow-none">
<CardHeader className="pb-2 sm:pb-4">
<CardTitle className="flex items-center gap-2 text-base sm:text-lg">
<KeyRound className="h-4 w-4 sm:h-5 sm:w-5" />
Passkeys
</CardTitle>
<CardDescription className="text-xs sm:text-sm">Manage passkeys for passwordless sign-in</CardDescription>
</CardHeader>
<CardContent className="space-y-3 sm:space-y-4">
<div className="flex flex-col sm:flex-row gap-2">
<Input
placeholder="Passkey name (optional)"
value={passkeyName}
onChange={(e) => setPasskeyName(e.target.value)}
className="h-9 sm:h-10 md:text-sm"
/>
<Button
onClick={handleAddPasskey}
disabled={addPasskeyMutation.isPending}
className="h-9 sm:h-10 whitespace-nowrap"
>
{addPasskeyMutation.isPending ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Plus className="mr-2 h-4 w-4" />
)}
Add Passkey
</Button>
<div className="flex flex-col gap-3 rounded-lg border border-border bg-card px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
<div className="flex items-center gap-2">
<LogOut className="h-4 w-4 shrink-0 text-destructive" />
<div className="min-w-0">
<p className="text-sm font-medium text-destructive">Sign Out</p>
<p className="text-xs text-muted-foreground">Sign out of your account</p>
</div>
{passkeysLoading ? (
<div className="flex items-center justify-center py-4">
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
</div>
) : passkeys && passkeys.length > 0 ? (
<div className="space-y-2">
{passkeys.map((pk) => (
<div
key={pk.id}
className="flex items-center justify-between p-2.5 sm:p-3 bg-muted rounded-lg"
>
<div className="min-w-0 flex-1">
<p className="font-medium text-sm truncate">{pk.name || 'Unnamed Passkey'}</p>
<p className="text-xs text-muted-foreground truncate">
{pk.deviceType} - {new Date(pk.createdAt).toLocaleDateString()}
</p>
</div>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 ml-2 flex-shrink-0"
onClick={() => handleDeletePasskey(pk.id)}
disabled={deletePasskeyMutation.isPending}
>
{deletePasskeyMutation.isPending ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Trash2 className="h-4 w-4 text-destructive" />
)}
</Button>
</div>
))}
</div>
) : (
<p className="text-xs sm:text-sm text-muted-foreground text-center py-3">
No passkeys registered. Add one for passwordless sign-in.
</p>
)}
</CardContent>
</Card>
<Card className="border-0 shadow-none">
<CardHeader className="pb-2 sm:pb-4">
<CardTitle className="flex items-center gap-2 text-base sm:text-lg text-destructive">
<LogOut className="h-4 w-4 sm:h-5 sm:w-5" />
Sign Out
</CardTitle>
<CardDescription className="text-xs sm:text-sm">Sign out of your account</CardDescription>
</CardHeader>
<CardContent>
<Button variant="destructive" onClick={logout} className="h-9 sm:h-10">
<LogOut className="mr-2 h-4 w-4" />
Sign Out
</Button>
</CardContent>
</Card>
</div>
<Button variant="destructive" onClick={logout} className="h-9 shrink-0 sm:h-10">
<LogOut className="mr-2 h-4 w-4" />
Sign Out
</Button>
</div>
<DeleteDialog
open={deletePasskeyId !== null}
@@ -0,0 +1,117 @@
import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { GeneralSettings } from './GeneralSettings'
import { useSettings } from '@/hooks/useSettings'
import { useVersionCheck } from '@/hooks/useVersionCheck'
import type { UserPreferences } from '@/api/types/settings'
import type { VersionInfo } from '@/api/settings'
vi.mock('@/hooks/useSettings')
vi.mock('@/hooks/useVersionCheck')
const basePreferences: UserPreferences = {
theme: 'dark',
mode: 'build',
autoScroll: true,
expandDiffs: true,
expandToolCalls: false,
showReasoning: false,
simpleChatMode: false,
keyboardShortcuts: {},
customCommands: [],
}
const baseVersionInfo: VersionInfo = {
currentVersion: 'v1.2.3',
latestVersion: null,
updateAvailable: false,
releaseUrl: null,
releaseName: null,
}
function mockUseSettings(overrides: Partial<ReturnType<typeof useSettings>> = {}) {
vi.mocked(useSettings).mockReturnValue({
settings: undefined,
preferences: basePreferences,
isLoading: false,
error: null,
updateSettings: vi.fn(),
updateSettingsAsync: vi.fn(),
resetSettings: vi.fn(),
isUpdating: false,
isResetting: false,
...overrides,
})
}
function mockVersionInfo(overrides: Partial<VersionInfo> = {}) {
vi.mocked(useVersionCheck).mockReturnValue({
data: { ...baseVersionInfo, ...overrides },
isLoading: false,
} as ReturnType<typeof useVersionCheck>)
}
describe('GeneralSettings', () => {
beforeAll(() => {
Element.prototype.hasPointerCapture ??= () => false
Element.prototype.setPointerCapture ??= () => {}
Element.prototype.releasePointerCapture ??= () => {}
})
beforeEach(() => {
vi.clearAllMocks()
})
it('renders the compact heading row with version info and associated preference rows', () => {
mockUseSettings()
mockVersionInfo({ latestVersion: '1.3.0', updateAvailable: true, releaseUrl: 'https://example.com/release' })
render(<GeneralSettings />)
expect(screen.getByRole('heading', { name: 'General Preferences' })).toBeInTheDocument()
expect(screen.getByText('OpenCode Manager')).toBeInTheDocument()
expect(screen.getByText('v1.2.3')).toBeInTheDocument()
expect(screen.getByRole('link', { name: 'v1.3.0 available' })).toHaveAttribute('href', 'https://example.com/release')
expect(screen.getByLabelText('Theme')).toBeInTheDocument()
expect(screen.getByRole('switch', { name: 'Simple chat mode' })).not.toBeChecked()
expect(screen.getByRole('switch', { name: 'Auto-scroll' })).toBeChecked()
expect(screen.getByRole('switch', { name: 'Show reasoning' })).not.toBeChecked()
expect(screen.getByRole('switch', { name: 'Expand tool calls' })).not.toBeChecked()
expect(screen.getByRole('switch', { name: 'Expand diffs' })).toBeChecked()
})
it('writes the theme and toggle preferences', async () => {
const user = userEvent.setup()
const updateSettings = vi.fn()
mockUseSettings({ updateSettings })
mockVersionInfo()
render(<GeneralSettings />)
await user.click(screen.getByRole('combobox', { name: 'Theme' }))
await user.click(screen.getByRole('option', { name: 'Light' }))
expect(updateSettings).toHaveBeenCalledWith({ theme: 'light' })
await user.click(screen.getByRole('switch', { name: 'Auto-scroll' }))
expect(updateSettings).toHaveBeenCalledWith({ autoScroll: false })
})
it('hides the reasoning, tool call, and diff rows while simple chat mode is on', () => {
mockUseSettings({ preferences: { ...basePreferences, simpleChatMode: true } })
mockVersionInfo()
render(<GeneralSettings />)
expect(screen.queryByRole('switch', { name: 'Show reasoning' })).not.toBeInTheDocument()
expect(screen.queryByRole('switch', { name: 'Expand tool calls' })).not.toBeInTheDocument()
expect(screen.queryByRole('switch', { name: 'Expand diffs' })).not.toBeInTheDocument()
})
it('shows the saving state while preferences are updating', () => {
mockUseSettings({ isUpdating: true })
mockVersionInfo()
render(<GeneralSettings />)
expect(screen.getByText('Saving...')).toBeInTheDocument()
})
})
@@ -18,12 +18,11 @@ export function GeneralSettings() {
}
return (
<div className="bg-card border border-border rounded-lg p-6">
<h2 className="text-lg font-semibold text-foreground mb-6">General Preferences</h2>
<div className="space-y-6">
<div className="flex items-center justify-center gap-3 py-3">
<span className="text-sm text-muted-foreground">OpenCode Manager</span>
<div className="space-y-6">
<div className="flex flex-wrap items-center justify-between gap-2">
<h2 className="text-lg font-semibold text-foreground">General Preferences</h2>
<div className="flex flex-wrap items-center gap-2 text-sm text-muted-foreground">
<span>OpenCode Manager</span>
{isVersionLoading ? (
<Loader2 className="h-3 w-3 animate-spin text-muted-foreground" />
) : versionInfo?.currentVersion ? (
@@ -43,33 +42,37 @@ export function GeneralSettings() {
)}
</>
) : (
<span className="text-sm text-muted-foreground">unknown</span>
<span>unknown</span>
)}
</div>
</div>
<div className="space-y-2">
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between sm:gap-4">
<div className="min-w-0 space-y-0.5">
<Label htmlFor="theme">Theme</Label>
<Select
value={preferences?.theme || 'dark'}
onValueChange={(value) => updateSettings({ theme: value as 'dark' | 'light' | 'system' })}
>
<SelectTrigger id="theme">
<SelectValue placeholder="Select a theme" />
</SelectTrigger>
<SelectContent>
<SelectItem value="dark">Dark</SelectItem>
<SelectItem value="light">Light</SelectItem>
<SelectItem value="system">System</SelectItem>
</SelectContent>
</Select>
<p className="text-sm text-muted-foreground">
Choose your preferred color scheme
</p>
</div>
<Select
value={preferences?.theme || 'dark'}
onValueChange={(value) => updateSettings({ theme: value as 'dark' | 'light' | 'system' })}
>
<SelectTrigger id="theme" className="w-full shrink-0 sm:w-40">
<SelectValue placeholder="Select a theme" />
</SelectTrigger>
<SelectContent>
<SelectItem value="dark">Dark</SelectItem>
<SelectItem value="light">Light</SelectItem>
<SelectItem value="system">System</SelectItem>
</SelectContent>
</Select>
</div>
<div className="flex flex-row items-center justify-between rounded-lg border border-border p-4">
<div className="space-y-0.5">
<Label htmlFor="simpleChatMode" className="text-base">Simple chat mode</Label>
<div className="divide-y divide-border">
<div className="flex items-start justify-between gap-4 py-3">
<div className="min-w-0 space-y-0.5">
<Label htmlFor="simpleChatMode">Simple chat mode</Label>
<p className="text-sm text-muted-foreground">
Show only your messages and the assistant's replies. Hides tool calls, reasoning, diffs, and agent details.
</p>
@@ -81,9 +84,9 @@ export function GeneralSettings() {
/>
</div>
<div className="flex flex-row items-center justify-between rounded-lg border border-border p-4">
<div className="space-y-0.5">
<Label htmlFor="autoScroll" className="text-base">Auto-scroll</Label>
<div className="flex items-start justify-between gap-4 py-3">
<div className="min-w-0 space-y-0.5">
<Label htmlFor="autoScroll">Auto-scroll</Label>
<p className="text-sm text-muted-foreground">
Automatically scroll to bottom when new messages arrive
</p>
@@ -97,9 +100,9 @@ export function GeneralSettings() {
{!preferences?.simpleChatMode && (
<>
<div className="flex flex-row items-center justify-between rounded-lg border border-border p-4">
<div className="space-y-0.5">
<Label htmlFor="showReasoning" className="text-base">Show reasoning</Label>
<div className="flex items-start justify-between gap-4 py-3">
<div className="min-w-0 space-y-0.5">
<Label htmlFor="showReasoning">Show reasoning</Label>
<p className="text-sm text-muted-foreground">
Display model reasoning and thought process
</p>
@@ -111,9 +114,9 @@ export function GeneralSettings() {
/>
</div>
<div className="flex flex-row items-center justify-between rounded-lg border border-border p-4">
<div className="space-y-0.5">
<Label htmlFor="expandToolCalls" className="text-base">Expand tool calls</Label>
<div className="flex items-start justify-between gap-4 py-3">
<div className="min-w-0 space-y-0.5">
<Label htmlFor="expandToolCalls">Expand tool calls</Label>
<p className="text-sm text-muted-foreground">
Automatically expand tool call details by default
</p>
@@ -125,9 +128,9 @@ export function GeneralSettings() {
/>
</div>
<div className="flex flex-row items-center justify-between rounded-lg border border-border p-4">
<div className="space-y-0.5">
<Label htmlFor="expandDiffs" className="text-base">Expand diffs</Label>
<div className="flex items-start justify-between gap-4 py-3">
<div className="min-w-0 space-y-0.5">
<Label htmlFor="expandDiffs">Expand diffs</Label>
<p className="text-sm text-muted-foreground">
Show file diffs expanded by default for edit operations
</p>
@@ -140,16 +143,14 @@ export function GeneralSettings() {
</div>
</>
)}
{isUpdating && (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" />
<span>Saving...</span>
</div>
)}
</div>
{isUpdating && (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" />
<span>Saving...</span>
</div>
)}
</div>
)
}
@@ -208,58 +208,58 @@ export function GitSettings() {
)}
</div>
<div className="divide-y divide-border space-y-4 pb-4">
<div>
<div className="flex items-center gap-3 px-6 py-3">
<User className="w-4 h-4 text-muted-foreground" />
<div className="grid grid-cols-1 gap-4 p-4 sm:gap-6 sm:p-6 @min-[1000px]:grid-cols-3 @min-[1000px]:items-start">
<div className="min-w-0 space-y-4">
<div className="flex items-center gap-3">
<User className="w-4 h-4 shrink-0 text-muted-foreground" />
<span className="font-medium">Identity</span>
<span className="text-xs text-muted-foreground ml-auto">
<span className="ml-auto min-w-0 truncate text-xs text-muted-foreground">
{gitIdentity.name || gitIdentity.email ? `${gitIdentity.name || 'No name'} <${gitIdentity.email || 'No email'}>` : 'Not configured'}
</span>
</div>
<div className="px-6 space-y-4 sm:ml-7">
<div className="space-y-4 sm:ml-7">
<p className="text-sm text-muted-foreground">
Author identity used for git commits. Leave empty to use system defaults.
</p>
<div className="grid pb-4 grid-cols-1 sm:grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="git-name">Name</Label>
<Input
id="git-name"
placeholder="Your Name"
value={gitIdentity.name}
onChange={(e) => updateIdentity('name', e.target.value)}
disabled={isSaving}
className="bg-background border-border text-foreground placeholder:text-muted-foreground"
/>
</div>
<div className="space-y-2">
<Label htmlFor="git-email">Email</Label>
<Input
id="git-email"
type="email"
placeholder="you@example.com"
value={gitIdentity.email}
onChange={(e) => updateIdentity('email', e.target.value)}
disabled={isSaving}
className="bg-background border-border text-foreground placeholder:text-muted-foreground"
/>
</div>
</div>
</div>
</div>
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="git-name">Name</Label>
<Input
id="git-name"
placeholder="Your Name"
value={gitIdentity.name}
onChange={(e) => updateIdentity('name', e.target.value)}
disabled={isSaving}
className="bg-background border-border text-foreground placeholder:text-muted-foreground"
/>
</div>
<div className="space-y-2">
<Label htmlFor="git-email">Email</Label>
<Input
id="git-email"
type="email"
placeholder="you@example.com"
value={gitIdentity.email}
onChange={(e) => updateIdentity('email', e.target.value)}
disabled={isSaving}
className="bg-background border-border text-foreground placeholder:text-muted-foreground"
/>
</div>
</div>
</div>
</div>
<div>
<div className="flex items-center gap-3 px-6 py-3">
<Key className="w-4 h-4 text-muted-foreground" />
<div className="min-w-0 space-y-4 @min-[1000px]:col-span-2">
<div className="flex items-center gap-3">
<Key className="w-4 h-4 shrink-0 text-muted-foreground" />
<span className="font-medium">Credentials</span>
<span className="text-xs text-muted-foreground ml-auto">
<span className="ml-auto text-xs text-muted-foreground">
{gitCredentials.length} configured
</span>
</div>
<div className="px-6 space-y-4 sm:ml-7">
<div className="space-y-4 sm:ml-7">
<div className="flex items-center justify-between">
<p className="text-sm text-muted-foreground">
Credentials for cloning private repositories
@@ -283,7 +283,7 @@ export function GitSettings() {
</p>
</div>
) : (
<div className="border border-border rounded-lg overflow-hidden">
<div className="min-w-0 overflow-x-auto rounded-lg border border-border">
<table className="w-full text-sm">
<thead className="bg-muted/50">
<tr>
@@ -0,0 +1,52 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, within } from '@testing-library/react'
import { KeyboardShortcuts } from './KeyboardShortcuts'
import { DEFAULT_KEYBOARD_SHORTCUTS } from '@/api/types/settings'
const { updateSettings } = vi.hoisted(() => ({ updateSettings: vi.fn() }))
vi.mock('@/hooks/useMobile', () => ({ useMobile: () => false }))
vi.mock('@/hooks/useSettings', () => ({
useSettings: () => ({
preferences: { keyboardShortcuts: { customAction: 'Alt+J' } },
isLoading: false,
updateSettings,
}),
}))
describe('KeyboardShortcuts layout', () => {
beforeEach(() => vi.clearAllMocks())
it('groups every default and custom action exactly once', () => {
render(<KeyboardShortcuts />)
expect(screen.getByRole('region', { name: 'Conversation actions' })).toBeInTheDocument()
const navigation = screen.getByRole('region', { name: 'Navigation' })
for (const action of [...Object.keys(DEFAULT_KEYBOARD_SHORTCUTS), 'customAction']) {
expect(screen.getAllByText(action.replace(/([A-Z])/g, ' $1').trim(), { exact: true })).toHaveLength(1)
}
expect(within(navigation).getByText('custom Action')).toBeInTheDocument()
})
it('keeps recording focused through modifier updates and saves the selected action', () => {
render(<KeyboardShortcuts />)
fireEvent.click(screen.getByRole('button', { name: /Alt\+J/ }))
const input = screen.getByPlaceholderText('Press keys...')
expect(input).toHaveFocus()
fireEvent.keyDown(input, { key: 'Control', ctrlKey: true })
expect(screen.getByPlaceholderText('Press keys...')).toBe(input)
expect(input).toHaveFocus()
fireEvent.keyDown(input, { key: 'k', ctrlKey: true })
expect(updateSettings).toHaveBeenCalledWith({ keyboardShortcuts: expect.objectContaining({ customAction: 'Ctrl+K' }) })
expect(screen.queryByPlaceholderText('Press keys...')).not.toBeInTheDocument()
})
it('preserves direct-toggle and clear actions in a grouped row', () => {
render(<KeyboardShortcuts />)
const row = screen.getByText('custom Action').parentElement!.parentElement!
fireEvent.click(within(row).getByRole('button', { name: 'Requires leader key (click to make direct)' }))
expect(updateSettings).toHaveBeenCalledWith({ directShortcuts: ['submit', 'abort', 'customAction'] })
fireEvent.click(within(row).getByTitle('Clear shortcut'))
expect(updateSettings).toHaveBeenCalledWith({ keyboardShortcuts: expect.objectContaining({ customAction: '' }) })
expect(within(row).getByRole('button', { name: 'Not set' })).toBeInTheDocument()
})
})
@@ -13,6 +13,111 @@ const normalizeShortcut = (shortcut: string): string => {
const DEFAULT_DIRECT_SHORTCUTS = ['submit', 'abort']
const CONVERSATION_ACTIONS = ['submit', 'abort', 'toggleMode', 'undo', 'redo', 'compact', 'fork', 'selectModel', 'variantCycle']
const NAVIGATION_ACTIONS = ['settings', 'sessions', 'newSession', 'closeSession', 'toggleSidebar']
const formatShortcutLabel = (action: string): string => {
return action.replace(/([A-Z])/g, ' $1').trim()
}
interface ShortcutGroup {
title: string
actions: string[]
}
const buildShortcutGroups = (shortcuts: Record<string, string>): ShortcutGroup[] => {
const knownActions = new Set([...CONVERSATION_ACTIONS, ...NAVIGATION_ACTIONS])
const unknownActions = Object.keys(shortcuts).filter((action) => !knownActions.has(action))
return [
{
title: 'Conversation actions',
actions: CONVERSATION_ACTIONS.filter((action) => action in shortcuts),
},
{
title: 'Navigation',
actions: [...NAVIGATION_ACTIONS.filter((action) => action in shortcuts), ...unknownActions],
},
]
}
interface RecordingInputProps {
value: string
onStop: () => void
}
function RecordingInput({ value, onStop }: RecordingInputProps) {
return (
<div className="flex min-w-0 max-w-full items-center gap-2">
<input
type="text"
className="min-w-0 w-44 px-3 py-1.5 bg-accent border border-primary rounded text-[16px] md:text-sm text-foreground font-mono outline-none"
placeholder="Press keys..."
value={value || ''}
autoFocus
onBlur={onStop}
readOnly
/>
<button
onClick={onStop}
className="px-2 py-1 text-xs text-muted-foreground hover:text-foreground"
>
Cancel
</button>
</div>
)
}
interface ShortcutRowProps {
action: string
keys: string
isDirect: boolean
display: string
isRecording: boolean
currentKeys: string
onToggleDirect: (action: string) => void
onStartRecording: (action: string) => void
onStopRecording: () => void
onClear: (action: string) => void
}
function ShortcutRow({ action, keys, isDirect, display, isRecording, currentKeys, onToggleDirect, onStartRecording, onStopRecording, onClear }: ShortcutRowProps) {
return (
<div className="flex flex-wrap items-center justify-between gap-2 py-2.5 border-b border-border last:border-0">
<div className="min-w-0 flex-1 basis-48 space-y-0.5">
<p className="truncate text-sm font-medium capitalize text-foreground">{formatShortcutLabel(action)}</p>
<button
onClick={() => onToggleDirect(action)}
className="text-xs text-muted-foreground hover:text-foreground transition-colors text-left"
>
{isDirect ? 'Direct (click to require leader)' : 'Requires leader key (click to make direct)'}
</button>
</div>
{isRecording ? (
<RecordingInput value={currentKeys} onStop={onStopRecording} />
) : (
<div className="flex items-center gap-2">
<button
onClick={() => onStartRecording(action)}
className={`px-3 py-1.5 bg-accent border border-border hover:border-border rounded text-sm font-mono transition-colors ${keys ? 'text-foreground' : 'text-muted-foreground italic'}`}
>
{display}
</button>
{keys && (
<button
onClick={() => onClear(action)}
className="p-1 text-muted-foreground hover:text-destructive transition-colors"
title="Clear shortcut"
>
<X className="w-4 h-4" />
</button>
)}
</div>
)}
</div>
)
}
export function KeyboardShortcuts() {
const { preferences, isLoading, updateSettings } = useSettings()
const isMobile = useMobile()
@@ -25,12 +130,14 @@ export function KeyboardShortcuts() {
const leaderKey = tempLeaderKey ?? preferences?.leaderKey ?? DEFAULT_LEADER_KEY
const directShortcuts = preferences?.directShortcuts ?? DEFAULT_DIRECT_SHORTCUTS
const shortcuts = useMemo(() => ({
...DEFAULT_KEYBOARD_SHORTCUTS,
...preferences?.keyboardShortcuts,
...tempShortcuts
const shortcuts = useMemo(() => ({
...DEFAULT_KEYBOARD_SHORTCUTS,
...preferences?.keyboardShortcuts,
...tempShortcuts
}), [preferences?.keyboardShortcuts, tempShortcuts])
const shortcutGroups = useMemo(() => buildShortcutGroups(shortcuts), [shortcuts])
const shortcutsRef = useRef(shortcuts)
shortcutsRef.current = shortcuts
@@ -67,13 +174,13 @@ export function KeyboardShortcuts() {
const handleKeyDown = (e: KeyboardEvent) => {
e.preventDefault()
const keys = []
if (e.ctrlKey) keys.push('Ctrl')
if (e.metaKey) keys.push('Cmd')
if (e.altKey) keys.push('Alt')
if (e.shiftKey) keys.push('Shift')
const mainKey = e.key
if (!['Control', 'Meta', 'Alt', 'Shift'].includes(mainKey)) {
let displayKey = mainKey
@@ -88,12 +195,12 @@ export function KeyboardShortcuts() {
else if (mainKey === 'Backspace') displayKey = 'Backspace'
else if (mainKey === 'Delete') displayKey = 'Delete'
else if (mainKey.length === 1) displayKey = mainKey.toUpperCase()
keys.push(displayKey)
if (keys.length > 0) {
const shortcut = keys.join('+')
if (recordingLeader) {
setTempLeaderKey(shortcut)
setRecordingLeader(false)
@@ -118,7 +225,7 @@ export function KeyboardShortcuts() {
setCurrentKeys('')
}
}
document.addEventListener('keydown', handleKeyDown)
document.addEventListener('keyup', handleKeyUp)
return () => {
@@ -164,94 +271,47 @@ export function KeyboardShortcuts() {
return (
<div className="bg-card border border-border rounded-lg p-6">
<h2 className="text-lg font-semibold text-foreground mb-6">Keyboard Shortcuts</h2>
<div className="space-y-4">
<div className="flex items-center justify-between py-3 border-b border-border">
<div className="space-y-1">
<p className="text-foreground font-medium">Leader Key</p>
<p className="text-xs text-muted-foreground">Press this first, then the shortcut key</p>
</div>
{recordingLeader ? (
<div className="flex items-center gap-2">
<input
type="text"
className="px-3 py-1.5 bg-accent border border-primary rounded text-[16px] md:text-sm text-foreground font-mono outline-none"
placeholder="Press keys..."
value={currentKeys || ''}
autoFocus
onBlur={stopRecording}
readOnly
/>
<button
onClick={stopRecording}
className="px-2 py-1 text-xs text-muted-foreground hover:text-foreground"
>
Cancel
</button>
</div>
) : (
<button
onClick={startRecordingLeader}
className="px-3 py-1.5 bg-primary/20 border border-primary/50 hover:border-primary rounded text-sm text-foreground font-mono transition-colors"
>
{normalizeShortcut(leaderKey)}
</button>
)}
<div className="flex flex-wrap items-center justify-between gap-2 py-3 border-b border-border">
<div className="flex min-w-0 flex-wrap items-baseline gap-x-2">
<p className="text-sm font-medium text-foreground">Leader Key</p>
<p className="text-xs text-muted-foreground">Press this first, then the shortcut key</p>
</div>
{Object.entries(shortcuts).map(([action, keys]) => (
<div key={action} className="flex items-center justify-between py-3 border-b border-border last:border-0">
<div className="space-y-1">
<p className="text-foreground font-medium capitalize">
{action.replace(/([A-Z])/g, ' $1').trim()}
</p>
<button
onClick={() => toggleDirectShortcut(action)}
className="text-xs text-muted-foreground hover:text-foreground transition-colors"
>
{directShortcuts.includes(action) ? 'Direct (click to require leader)' : 'Requires leader key (click to make direct)'}
</button>
</div>
{recordingKey === action ? (
<div className="flex items-center gap-2">
<input
type="text"
className="px-3 py-1.5 bg-accent border border-primary rounded text-[16px] md:text-sm text-foreground font-mono outline-none"
placeholder="Press keys..."
value={currentKeys || ''}
autoFocus
onBlur={stopRecording}
readOnly
{recordingLeader ? (
<RecordingInput value={currentKeys} onStop={stopRecording} />
) : (
<button
onClick={startRecordingLeader}
className="px-3 py-1.5 bg-primary/20 border border-primary/50 hover:border-primary rounded text-sm text-foreground font-mono transition-colors"
>
{normalizeShortcut(leaderKey)}
</button>
)}
</div>
<div className="grid grid-cols-1 gap-6 pt-4 @min-[1000px]:grid-cols-2 @min-[1000px]:items-start">
{shortcutGroups.map((group) => (
<section key={group.title} className="min-w-0" aria-label={group.title}>
<h3 className="mb-1 text-xs font-medium uppercase tracking-wide text-muted-foreground">{group.title}</h3>
<div>
{group.actions.map((action) => (
<ShortcutRow
key={action}
action={action}
keys={shortcuts[action] ?? ''}
isDirect={directShortcuts.includes(action)}
display={formatShortcutDisplay(action, shortcuts[action] ?? '')}
isRecording={recordingKey === action}
currentKeys={currentKeys}
onToggleDirect={toggleDirectShortcut}
onStartRecording={startRecording}
onStopRecording={stopRecording}
onClear={clearShortcut}
/>
<button
onClick={stopRecording}
className="px-2 py-1 text-xs text-muted-foreground hover:text-foreground"
>
Cancel
</button>
</div>
) : (
<div className="flex items-center gap-2">
<button
onClick={() => startRecording(action)}
className={`px-3 py-1.5 bg-accent border border-border hover:border-border rounded text-sm font-mono transition-colors ${keys ? 'text-foreground' : 'text-muted-foreground italic'}`}
>
{formatShortcutDisplay(action, keys)}
</button>
{keys && (
<button
onClick={() => clearShortcut(action)}
className="p-1 text-muted-foreground hover:text-destructive transition-colors"
title="Clear shortcut"
>
<X className="w-4 h-4" />
</button>
)}
</div>
)}
</div>
))}
</div>
</section>
))}
</div>
@@ -76,9 +76,9 @@ export function LogsViewer() {
.join('\n')
return (
<Card className="border-0 bg-transparent shadow-none">
<CardContent className="space-y-3 p-0">
<div className="flex flex-wrap items-center gap-2">
<Card className="flex h-full min-h-0 flex-col border-0 bg-transparent shadow-none">
<CardContent className="flex min-h-0 flex-1 flex-col gap-3 p-0">
<div className="flex shrink-0 flex-wrap items-center gap-2">
<Select value={level} onValueChange={(value) => setLevel(value as LevelFilter)}>
<SelectTrigger className="min-w-0 flex-1 sm:w-44 sm:flex-none" aria-label="Log level filter">
<SelectValue />
@@ -111,11 +111,11 @@ export function LogsViewer() {
aria-label="Search log messages"
/>
<div className="ml-auto flex items-center gap-2">
<Button variant="outline" size="sm" className="px-2 sm:px-3" onClick={() => setPaused((value) => !value)}>
<Button variant="outline" size="sm" className="px-2 sm:px-3" aria-label={paused ? 'Resume' : 'Pause'} onClick={() => setPaused((value) => !value)}>
{paused ? <Play /> : <Pause />}
<span className="hidden sm:inline">{paused ? 'Resume' : 'Pause'}</span>
</Button>
<Button variant="outline" size="sm" className="px-2 sm:px-3" onClick={clear}>
<Button variant="outline" size="sm" className="px-2 sm:px-3" aria-label="Clear" onClick={clear}>
<Trash2 />
<span className="hidden sm:inline">Clear</span>
</Button>
@@ -125,7 +125,7 @@ export function LogsViewer() {
<div
ref={scrollRef}
onScroll={handleScroll}
className="h-[calc(100dvh-15rem)] min-h-80 space-y-1 overflow-y-auto rounded-md border border-border bg-background p-2 font-mono text-xs"
className="min-h-0 flex-1 space-y-1 overflow-y-auto rounded-md border border-border bg-background p-2 font-mono text-xs"
>
{entries.length === 0 ? (
<p className="p-4 text-center font-sans text-muted-foreground">No log entries captured yet.</p>
@@ -152,7 +152,7 @@ export function LogsViewer() {
)}
</div>
{dropped > 0 && (
<p className="text-xs text-muted-foreground">
<p className="shrink-0 text-xs text-muted-foreground">
{dropped} earlier entries dropped (buffer holds {DEFAULTS.LOGS.BUFFER_CAPACITY})
</p>
)}
@@ -0,0 +1,173 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { NotificationSettings } from './NotificationSettings'
import { useNotifications } from '@/hooks/useNotifications'
import { showToast } from '@/lib/toast'
import type { PushSubscriptionRecord } from '@opencode-manager/shared/types'
vi.mock('@/hooks/useNotifications')
vi.mock('@/lib/toast', () => ({
showToast: { success: vi.fn(), error: vi.fn() },
}))
type NotificationsHook = ReturnType<typeof useNotifications>
const basePreferences = {
enabled: true,
events: {
permissionAsked: true,
questionAsked: false,
sessionError: true,
sessionIdle: false,
},
}
const deviceOne: PushSubscriptionRecord = {
id: 1,
userId: 'default',
endpoint: 'https://push.example.com/one',
p256dh: 'key',
auth: 'auth',
deviceName: 'Chris MacBook',
createdAt: Date.now(),
lastUsedAt: Date.now(),
}
function mockNotifications(overrides: Partial<NotificationsHook> = {}) {
vi.mocked(useNotifications).mockReturnValue({
isSupported: true,
isAvailable: true,
permission: 'granted',
isEnabled: true,
preferences: basePreferences,
subscriptions: [deviceOne],
isLoadingSubscriptions: false,
enable: vi.fn().mockResolvedValue(undefined),
disable: vi.fn().mockResolvedValue(undefined),
updateEventPreference: vi.fn(),
removeDevice: vi.fn(),
sendTest: vi.fn(),
isSubscribing: false,
isTesting: false,
...overrides,
})
}
describe('NotificationSettings', () => {
beforeEach(() => {
vi.clearAllMocks()
mockNotifications()
})
it('places main preferences and Registered Devices in a 2fr/1fr container-query grid', () => {
const { container } = render(<NotificationSettings />)
const root = container.firstElementChild as HTMLElement
expect(root).toHaveClass('@container', 'w-full', 'max-w-7xl')
const layout = root.firstElementChild as HTMLElement
expect(layout).toHaveClass('grid', '@min-[1000px]:grid-cols-[2fr_1fr]', '@min-[1000px]:items-start')
const [preferencesPanel, devicesPanel] = Array.from(layout.children) as HTMLElement[]
expect(preferencesPanel).toHaveClass('min-w-0')
expect(within(preferencesPanel).getByRole('heading', { name: 'Push Notifications' })).toBeInTheDocument()
expect(devicesPanel).toHaveClass('min-w-0')
expect(within(devicesPanel).getByRole('heading', { name: 'Registered Devices' })).toBeInTheDocument()
})
it('renders the preference toggles as compact divider rows', () => {
const { container } = render(<NotificationSettings />)
const rows = container.querySelector('.divide-y') as HTMLElement
expect(rows).toHaveClass('divide-border')
expect(rows.querySelector('.border, .p-4')).toBeNull()
expect(screen.getByRole('switch', { name: 'Enable push notifications' })).toBeChecked()
expect(screen.getByRole('switch', { name: 'Permission requests' })).toBeChecked()
expect(screen.getByRole('switch', { name: 'Agent questions' })).not.toBeChecked()
expect(screen.getByRole('switch', { name: 'Session errors' })).toBeChecked()
expect(screen.getByRole('switch', { name: 'Session completion' })).not.toBeChecked()
})
it('writes event preferences and disable through the hook', async () => {
const user = userEvent.setup()
const enable = vi.fn().mockResolvedValue(undefined)
const disable = vi.fn().mockResolvedValue(undefined)
const updateEventPreference = vi.fn()
mockNotifications({ enable, disable, updateEventPreference })
render(<NotificationSettings />)
await user.click(screen.getByRole('switch', { name: 'Agent questions' }))
expect(updateEventPreference).toHaveBeenCalledWith('questionAsked', true)
await user.click(screen.getByRole('switch', { name: 'Session completion' }))
expect(updateEventPreference).toHaveBeenCalledWith('sessionIdle', true)
await user.click(screen.getByRole('switch', { name: 'Enable push notifications' }))
expect(disable).toHaveBeenCalledTimes(1)
expect(enable).not.toHaveBeenCalled()
})
it('enables push notifications when the switch is turned on', async () => {
const user = userEvent.setup()
const enable = vi.fn().mockResolvedValue(undefined)
mockNotifications({ isEnabled: false, enable })
render(<NotificationSettings />)
await user.click(screen.getByRole('switch', { name: 'Enable push notifications' }))
expect(enable).toHaveBeenCalledTimes(1)
})
it('sends a test notification only when devices are registered and toasts the result', async () => {
const user = userEvent.setup()
const sendTest = vi.fn() as unknown as NotificationsHook['sendTest']
mockNotifications({ sendTest })
const { unmount } = render(<NotificationSettings />)
const testButton = screen.getByRole('button', { name: 'Send test notification' })
expect(testButton).toBeEnabled()
await user.click(testButton)
expect(sendTest).toHaveBeenCalledTimes(1)
const config = (sendTest as ReturnType<typeof vi.fn>).mock.calls[0][1] as {
onSuccess: (data: { devicesNotified: number }) => void
}
config.onSuccess({ devicesNotified: 2 })
expect(vi.mocked(showToast.success)).toHaveBeenCalledWith('Test notification sent to 2 device(s)')
unmount()
mockNotifications({
subscriptions: [],
sendTest: vi.fn() as unknown as NotificationsHook['sendTest'],
})
render(<NotificationSettings />)
expect(screen.getByRole('button', { name: 'Send test notification' })).toBeDisabled()
})
it('removes a registered device from the devices panel', async () => {
const user = userEvent.setup()
const removeDevice = vi.fn()
mockNotifications({ removeDevice })
render(<NotificationSettings />)
const deviceRow = screen.getByText('Chris MacBook').closest('div.justify-between') as HTMLElement
await user.click(within(deviceRow).getByRole('button'))
expect(removeDevice).toHaveBeenCalledWith(1)
})
it('renders the denied permission and unsupported browser states', () => {
mockNotifications({ permission: 'denied' })
const { unmount } = render(<NotificationSettings />)
expect(screen.getByText(/permission was denied/i)).toBeInTheDocument()
unmount()
mockNotifications({ isSupported: false })
render(<NotificationSettings />)
expect(screen.getByText(/not supported in this browser/i)).toBeInTheDocument()
})
})
@@ -106,115 +106,118 @@ export function NotificationSettings() {
};
return (
<div className="space-y-6">
<div className="bg-card border border-border rounded-lg p-6">
<h2 className="text-lg font-semibold text-foreground mb-6">
Push Notifications
</h2>
<div className="@container w-full max-w-7xl space-y-6">
<div className="grid gap-6 @min-[1000px]:grid-cols-[2fr_1fr] @min-[1000px]:items-start">
<div className="min-w-0 bg-card border border-border rounded-lg p-6">
<h2 className="text-lg font-semibold text-foreground mb-6">
Push Notifications
</h2>
<div className="space-y-6">
<div className="flex flex-row items-center justify-between rounded-lg border border-border p-4">
<div className="space-y-0.5">
<Label htmlFor="notificationsEnabled" className="text-base">
Enable push notifications
</Label>
<p className="text-sm text-muted-foreground">
Receive notifications when the app is in the background
</p>
</div>
<Switch
id="notificationsEnabled"
checked={isEnabled}
disabled={isSubscribing}
onCheckedChange={(checked) =>
checked ? handleEnable() : handleDisable()
}
/>
</div>
{isEnabled && (
<>
<div className="space-y-4">
<h3 className="text-sm font-medium text-foreground">
Notification Events
</h3>
<div className="flex flex-row items-center justify-between rounded-lg border border-border p-4">
<div className="space-y-0.5">
<Label
htmlFor="notifPermission"
className="text-base"
>
Permission requests
</Label>
<p className="text-sm text-muted-foreground">
When the agent needs approval to proceed
</p>
</div>
<Switch
id="notifPermission"
checked={preferences.events.permissionAsked}
onCheckedChange={(checked) =>
updateEventPreference("permissionAsked", checked)
}
/>
</div>
<div className="flex flex-row items-center justify-between rounded-lg border border-border p-4">
<div className="space-y-0.5">
<Label htmlFor="notifQuestion" className="text-base">
Agent questions
</Label>
<p className="text-sm text-muted-foreground">
When the agent has a question for you
</p>
</div>
<Switch
id="notifQuestion"
checked={preferences.events.questionAsked}
onCheckedChange={(checked) =>
updateEventPreference("questionAsked", checked)
}
/>
</div>
<div className="flex flex-row items-center justify-between rounded-lg border border-border p-4">
<div className="space-y-0.5">
<Label htmlFor="notifError" className="text-base">
Session errors
</Label>
<p className="text-sm text-muted-foreground">
When a session encounters an error
</p>
</div>
<Switch
id="notifError"
checked={preferences.events.sessionError}
onCheckedChange={(checked) =>
updateEventPreference("sessionError", checked)
}
/>
</div>
<div className="flex flex-row items-center justify-between rounded-lg border border-border p-4">
<div className="space-y-0.5">
<Label htmlFor="notifIdle" className="text-base">
Session completion
</Label>
<p className="text-sm text-muted-foreground">
When a session finishes processing
</p>
</div>
<Switch
id="notifIdle"
checked={preferences.events.sessionIdle}
onCheckedChange={(checked) =>
updateEventPreference("sessionIdle", checked)
}
/>
<div className="space-y-6">
<div className="divide-y divide-border">
<div className="flex items-start justify-between gap-4 py-3">
<div className="min-w-0 space-y-0.5">
<Label htmlFor="notificationsEnabled" className="text-base">
Enable push notifications
</Label>
<p className="text-sm text-muted-foreground">
Receive notifications when the app is in the background
</p>
</div>
<Switch
id="notificationsEnabled"
checked={isEnabled}
disabled={isSubscribing}
onCheckedChange={(checked) =>
checked ? handleEnable() : handleDisable()
}
/>
</div>
{isEnabled && (
<>
<div className="py-3">
<h3 className="text-sm font-medium text-foreground">
Notification Events
</h3>
</div>
<div className="flex items-start justify-between gap-4 py-3">
<div className="min-w-0 space-y-0.5">
<Label htmlFor="notifPermission" className="text-base">
Permission requests
</Label>
<p className="text-sm text-muted-foreground">
When the agent needs approval to proceed
</p>
</div>
<Switch
id="notifPermission"
checked={preferences.events.permissionAsked}
onCheckedChange={(checked) =>
updateEventPreference("permissionAsked", checked)
}
/>
</div>
<div className="flex items-start justify-between gap-4 py-3">
<div className="min-w-0 space-y-0.5">
<Label htmlFor="notifQuestion" className="text-base">
Agent questions
</Label>
<p className="text-sm text-muted-foreground">
When the agent has a question for you
</p>
</div>
<Switch
id="notifQuestion"
checked={preferences.events.questionAsked}
onCheckedChange={(checked) =>
updateEventPreference("questionAsked", checked)
}
/>
</div>
<div className="flex items-start justify-between gap-4 py-3">
<div className="min-w-0 space-y-0.5">
<Label htmlFor="notifError" className="text-base">
Session errors
</Label>
<p className="text-sm text-muted-foreground">
When a session encounters an error
</p>
</div>
<Switch
id="notifError"
checked={preferences.events.sessionError}
onCheckedChange={(checked) =>
updateEventPreference("sessionError", checked)
}
/>
</div>
<div className="flex items-start justify-between gap-4 py-3">
<div className="min-w-0 space-y-0.5">
<Label htmlFor="notifIdle" className="text-base">
Session completion
</Label>
<p className="text-sm text-muted-foreground">
When a session finishes processing
</p>
</div>
<Switch
id="notifIdle"
checked={preferences.events.sessionIdle}
onCheckedChange={(checked) =>
updateEventPreference("sessionIdle", checked)
}
/>
</div>
</>
)}
</div>
{isEnabled && (
<div className="flex gap-2">
<Button
variant="outline"
@@ -230,59 +233,59 @@ export function NotificationSettings() {
Send test notification
</Button>
</div>
</>
)}
)}
</div>
</div>
</div>
{isEnabled && (
<div className="bg-card border border-border rounded-lg p-6">
<h2 className="text-lg font-semibold text-foreground mb-4">
Registered Devices
</h2>
{isEnabled && (
<div className="min-w-0 bg-card border border-border rounded-lg p-6">
<h2 className="text-lg font-semibold text-foreground mb-4">
Registered Devices
</h2>
{isLoadingSubscriptions ? (
<div className="flex items-center justify-center py-4">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
) : subscriptions.length === 0 ? (
<p className="text-sm text-muted-foreground">
No devices registered for push notifications.
</p>
) : (
<div className="space-y-3">
{subscriptions.map((sub) => (
<div
key={sub.id}
className="flex items-center justify-between rounded-lg border border-border p-3"
>
<div className="flex items-center gap-3 min-w-0">
<Monitor className="h-4 w-4 text-muted-foreground flex-shrink-0" />
<div className="min-w-0">
<p className="text-sm font-medium text-foreground truncate">
{sub.deviceName ?? (sub.endpoint.length > 60 ? sub.endpoint.slice(0, 60) + "..." : sub.endpoint)}
</p>
<p className="text-xs text-muted-foreground">
{sub.lastUsedAt
? `Last used ${formatDistanceToNow(sub.lastUsedAt, { addSuffix: true })}`
: `Added ${formatDistanceToNow(sub.createdAt, { addSuffix: true })}`}
</p>
</div>
</div>
<Button
variant="ghost"
size="icon"
className="text-muted-foreground hover:text-destructive flex-shrink-0"
onClick={() => removeDevice(sub.id)}
{isLoadingSubscriptions ? (
<div className="flex items-center justify-center py-4">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
) : subscriptions.length === 0 ? (
<p className="text-sm text-muted-foreground">
No devices registered for push notifications.
</p>
) : (
<div className="space-y-3">
{subscriptions.map((sub) => (
<div
key={sub.id}
className="flex items-center justify-between rounded-lg border border-border p-3"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
))}
</div>
)}
</div>
)}
<div className="flex items-center gap-3 min-w-0">
<Monitor className="h-4 w-4 text-muted-foreground flex-shrink-0" />
<div className="min-w-0">
<p className="text-sm font-medium text-foreground truncate">
{sub.deviceName ?? (sub.endpoint.length > 60 ? sub.endpoint.slice(0, 60) + "..." : sub.endpoint)}
</p>
<p className="text-xs text-muted-foreground">
{sub.lastUsedAt
? `Last used ${formatDistanceToNow(sub.lastUsedAt, { addSuffix: true })}`
: `Added ${formatDistanceToNow(sub.createdAt, { addSuffix: true })}`}
</p>
</div>
</div>
<Button
variant="ghost"
size="icon"
className="text-muted-foreground hover:text-destructive flex-shrink-0"
onClick={() => removeDevice(sub.id)}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
))}
</div>
)}
</div>
)}
</div>
</div>
);
}
@@ -218,4 +218,22 @@ describe('OpenCodeConfigManager', () => {
resolveRefresh()
await waitFor(() => expect(screen.queryByText('Edit Config: default')).not.toBeInTheDocument())
})
it('renders host import collapsed after configurations until expanded', async () => {
const user = userEvent.setup()
renderWithQuery(<OpenCodeConfigManager />)
const importToggle = await screen.findByRole('button', { name: /Existing OpenCode Host Import/i })
expect(importToggle).toHaveAttribute('aria-expanded', 'false')
const importContent = document.getElementById(importToggle.getAttribute('aria-controls') ?? '')
expect(importContent).toHaveClass('hidden')
const configsTitle = screen.getByText('OpenCode Configurations')
expect(configsTitle.compareDocumentPosition(importToggle) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
await user.click(importToggle)
expect(importToggle).toHaveAttribute('aria-expanded', 'true')
expect(importContent).toHaveClass('block')
expect(await screen.findByRole('button', { name: /Import From Host/i })).toBeInTheDocument()
})
})
@@ -1,4 +1,4 @@
import { useState, useEffect, useRef } from 'react'
import { useState, useEffect, useRef, useId } from 'react'
import { cn } from '@/lib/utils'
import { Loader2, Plus, Trash2, Edit, Download, RotateCcw, FileText, ChevronDown, AlertTriangle } from 'lucide-react'
import { Button } from '@/components/ui/button'
@@ -59,6 +59,7 @@ interface Agent {
const EXPANDED_SECTION_CONTENT_CLASS = 'p-2 sm:p-4'
export function OpenCodeConfigManager() {
const hostImportContentId = useId()
const queryClient = useQueryClient()
const { data: health } = useServerHealth()
const [configs, setConfigs] = useState<OpenCodeConfig[]>([])
@@ -74,6 +75,7 @@ export function OpenCodeConfigManager() {
skills: false,
mcp: false,
models: false,
hostImport: false,
})
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false)
const [isEditDialogOpen, setIsEditDialogOpen] = useState(false)
@@ -358,104 +360,6 @@ export function OpenCodeConfigManager() {
</div>
)}
<Card>
<CardHeader className="pb-3">
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<div>
<CardTitle className="text-sm sm:text-base">Existing OpenCode Host Import</CardTitle>
<p className="text-sm text-muted-foreground mt-1">
Import your standalone OpenCode config and session state into this workspace, then restart the server so existing chats can reconnect.
</p>
</div>
<Button
variant="outline"
size="sm"
disabled={!canImportFromHost || syncOpenCodeImportMutation.isPending || isImportStatusLoading}
onClick={async () => {
showToast.loading('Importing existing OpenCode host data...', { id: 'opencode-import' })
try {
const result = await syncOpenCodeImportMutation.mutateAsync()
const importedParts = [result.configImported && 'config', result.stateImported && 'state']
.filter(Boolean)
.join(' and ')
const relinkSummary = result.relinkedRepos
? ` Linked ${result.relinkedRepos.relinkedCount} repos, matched ${result.relinkedRepos.existingCount} existing repos, skipped ${result.relinkedRepos.nonRepoPathCount} non-repo paths, and ignored ${result.relinkedRepos.duplicatePathCount} duplicate session paths.`
: ''
showToast.success(`Imported existing OpenCode ${importedParts || 'data'} and restarted the server.${relinkSummary}`, { id: 'opencode-import' })
} catch (error) {
showToast.error(getOpenCodeImportErrorMessage(error), { id: 'opencode-import' })
}
}}
>
{syncOpenCodeImportMutation.isPending ? (
<Loader2 className="h-3 w-3 sm:h-4 sm:w-4 mr-1 animate-spin" />
) : (
<Download className="h-3 w-3 sm:h-4 sm:w-4 mr-1" />
)}
<span className="text-xs sm:text-sm">Import From Host</span>
</Button>
</div>
</CardHeader>
<CardContent className="space-y-3 text-sm">
<div className="grid gap-3 md:grid-cols-2">
<div className="rounded-lg border border-border p-3">
<p className="font-medium">Config Source</p>
<p className="mt-1 break-all text-muted-foreground">
{isImportStatusLoading ? 'Checking...' : importStatus?.configSourcePath || 'No importable OpenCode config found'}
</p>
</div>
<div className="rounded-lg border border-border p-3">
<p className="font-medium">State Source</p>
<p className="mt-1 break-all text-muted-foreground">
{isImportStatusLoading ? 'Checking...' : importStatus?.stateSourcePath || 'No importable OpenCode state found'}
</p>
</div>
</div>
<div className="rounded-lg border border-border p-3">
<p className="font-medium">Workspace State</p>
<p className="mt-1 break-all text-muted-foreground">
{importStatus?.workspaceStatePath || 'Unavailable'}
</p>
<p className="mt-2 text-xs text-muted-foreground">
{importStatus?.workspaceStateExists
? 'A workspace session database already exists. Import is blocked to protect it from being replaced by detected host state.'
: 'No workspace session database exists yet. Import will seed it from the detected host state.'}
</p>
</div>
{syncOpenCodeImportMutation.error && (
<div className="rounded-lg border border-destructive/40 bg-destructive/5 p-3">
<p className="font-medium text-destructive">Import blocked</p>
<p className="mt-1 text-sm text-destructive/90">
{getOpenCodeImportErrorMessage(syncOpenCodeImportMutation.error)}
</p>
<p className="mt-2 text-xs text-destructive/80">
This workspace already has OpenCode session state, so host state import was stopped to prevent accidental replacement of existing chats and history. If you want to use host state instead, clear the workspace state first and then run the import again.
</p>
</div>
)}
{syncOpenCodeImportMutation.data?.relinkedRepos && (
<div className="rounded-lg border border-border p-3">
<p className="font-medium">Last Relink Result</p>
<p className="mt-1 text-muted-foreground">
Linked {syncOpenCodeImportMutation.data.relinkedRepos.relinkedCount} repos, matched {syncOpenCodeImportMutation.data.relinkedRepos.existingCount} existing repos, skipped {syncOpenCodeImportMutation.data.relinkedRepos.nonRepoPathCount} non-repo session paths, and ignored {syncOpenCodeImportMutation.data.relinkedRepos.duplicatePathCount} duplicate session paths.
</p>
{syncOpenCodeImportMutation.data.relinkedRepos.errors.length > 0 && (
<p className="mt-2 text-xs text-destructive">
{syncOpenCodeImportMutation.data.relinkedRepos.errors.length} repo paths could not be linked.
</p>
)}
</div>
)}
{!canImportFromHost && !isImportStatusLoading && (
<p className="text-xs text-muted-foreground">
No host OpenCode config or state was detected. For Docker installs, bind your host OpenCode config and state into the container before using this action.
</p>
)}
</CardContent>
</Card>
<CreateConfigDialog
isOpen={isCreateDialogOpen}
onOpenChange={setIsCreateDialogOpen}
@@ -889,6 +793,109 @@ export function OpenCodeConfigManager() {
</div>
</div>
<div className="bg-card border border-border rounded-lg overflow-hidden min-w-0">
<button
className={cn("w-full px-4 py-3 flex items-center justify-between transition-colors min-w-0", expandedSections.hostImport ? "bg-muted/40 hover:bg-muted/50" : "hover:bg-muted/50")}
aria-expanded={expandedSections.hostImport}
aria-controls={hostImportContentId}
onClick={() => setExpandedSections(prev => ({ ...prev, hostImport: !prev.hostImport }))}
>
<div className="flex items-center gap-3 min-w-0">
<Download className="h-4 w-4 text-blue-500" />
<h4 className="text-sm font-medium truncate">Existing OpenCode Host Import</h4>
</div>
<ChevronDown className={`h-4 w-4 transition-transform ${expandedSections.hostImport ? 'rotate-90' : ''}`} />
</button>
<div id={hostImportContentId} className={`${expandedSections.hostImport ? 'block' : 'hidden'} border-t border-border`}>
<div className={cn(EXPANDED_SECTION_CONTENT_CLASS, 'space-y-3 text-sm')}>
<p className="text-muted-foreground">
Import your standalone OpenCode config and session state into this workspace, then restart the server so existing chats can reconnect.
</p>
<Button
variant="outline"
size="sm"
disabled={!canImportFromHost || syncOpenCodeImportMutation.isPending || isImportStatusLoading}
onClick={async () => {
showToast.loading('Importing existing OpenCode host data...', { id: 'opencode-import' })
try {
const result = await syncOpenCodeImportMutation.mutateAsync()
const importedParts = [result.configImported && 'config', result.stateImported && 'state']
.filter(Boolean)
.join(' and ')
const relinkSummary = result.relinkedRepos
? ` Linked ${result.relinkedRepos.relinkedCount} repos, matched ${result.relinkedRepos.existingCount} existing repos, skipped ${result.relinkedRepos.nonRepoPathCount} non-repo paths, and ignored ${result.relinkedRepos.duplicatePathCount} duplicate session paths.`
: ''
showToast.success(`Imported existing OpenCode ${importedParts || 'data'} and restarted the server.${relinkSummary}`, { id: 'opencode-import' })
} catch (error) {
showToast.error(getOpenCodeImportErrorMessage(error), { id: 'opencode-import' })
}
}}
>
{syncOpenCodeImportMutation.isPending ? (
<Loader2 className="h-3 w-3 sm:h-4 sm:w-4 mr-1 animate-spin" />
) : (
<Download className="h-3 w-3 sm:h-4 sm:w-4 mr-1" />
)}
<span className="text-xs sm:text-sm">Import From Host</span>
</Button>
<div className="grid gap-3 md:grid-cols-2">
<div className="rounded-lg border border-border p-3">
<p className="font-medium">Config Source</p>
<p className="mt-1 break-all text-muted-foreground">
{isImportStatusLoading ? 'Checking...' : importStatus?.configSourcePath || 'No importable OpenCode config found'}
</p>
</div>
<div className="rounded-lg border border-border p-3">
<p className="font-medium">State Source</p>
<p className="mt-1 break-all text-muted-foreground">
{isImportStatusLoading ? 'Checking...' : importStatus?.stateSourcePath || 'No importable OpenCode state found'}
</p>
</div>
</div>
<div className="rounded-lg border border-border p-3">
<p className="font-medium">Workspace State</p>
<p className="mt-1 break-all text-muted-foreground">
{importStatus?.workspaceStatePath || 'Unavailable'}
</p>
<p className="mt-2 text-xs text-muted-foreground">
{importStatus?.workspaceStateExists
? 'A workspace session database already exists. Import is blocked to protect it from being replaced by detected host state.'
: 'No workspace session database exists yet. Import will seed it from the detected host state.'}
</p>
</div>
{syncOpenCodeImportMutation.error && (
<div className="rounded-lg border border-destructive/40 bg-destructive/5 p-3">
<p className="font-medium text-destructive">Import blocked</p>
<p className="mt-1 text-sm text-destructive/90">
{getOpenCodeImportErrorMessage(syncOpenCodeImportMutation.error)}
</p>
<p className="mt-2 text-xs text-destructive/80">
This workspace already has OpenCode session state, so host state import was stopped to prevent accidental replacement of existing chats and history. If you want to use host state instead, clear the workspace state first and then run the import again.
</p>
</div>
)}
{syncOpenCodeImportMutation.data?.relinkedRepos && (
<div className="rounded-lg border border-border p-3">
<p className="font-medium">Last Relink Result</p>
<p className="mt-1 text-muted-foreground">
Linked {syncOpenCodeImportMutation.data.relinkedRepos.relinkedCount} repos, matched {syncOpenCodeImportMutation.data.relinkedRepos.existingCount} existing repos, skipped {syncOpenCodeImportMutation.data.relinkedRepos.nonRepoPathCount} non-repo session paths, and ignored {syncOpenCodeImportMutation.data.relinkedRepos.duplicatePathCount} duplicate session paths.
</p>
{syncOpenCodeImportMutation.data.relinkedRepos.errors.length > 0 && (
<p className="mt-2 text-xs text-destructive">
{syncOpenCodeImportMutation.data.relinkedRepos.errors.length} repo paths could not be linked.
</p>
)}
</div>
)}
{!canImportFromHost && !isImportStatusLoading && (
<p className="text-xs text-muted-foreground">
No host OpenCode config or state was detected. For Docker installs, bind your host OpenCode config and state into the container before using this action.
</p>
)}
</div>
</div>
</div>
{/* Delete Confirmation Dialog */}
<DeleteDialog
open={!!deleteConfirmConfig}
@@ -0,0 +1,280 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, within, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { ProviderSettings } from './ProviderSettings'
import { getProviders, providerCredentialsApi } from '@/api/providers'
import { oauthApi } from '@/api/oauth'
import type { Provider, Model } from '@/api/providers'
import type { OAuthAuthorizeResponse } from '@/api/oauth'
import type { ReactNode } from 'react'
vi.mock('@/api/providers', () => ({
getProviders: vi.fn(),
providerCredentialsApi: {
list: vi.fn(),
getStatus: vi.fn(),
set: vi.fn(),
delete: vi.fn(),
},
}))
vi.mock('@/api/oauth', () => ({
oauthApi: {
getAuthMethods: vi.fn(),
authorize: vi.fn(),
callback: vi.fn(),
},
}))
vi.mock('./OAuthAuthorizeDialog', () => ({
OAuthAuthorizeDialog: ({
open,
providerId,
}: {
open: boolean
providerId: string
providerName: string
methods: unknown[]
onOpenChange: (open: boolean) => void
onSuccess: (response: OAuthAuthorizeResponse, methodIndex: number) => void
}) => (open ? <div data-testid="oauth-authorize-dialog">{providerId}</div> : null),
}))
vi.mock('./OAuthCallbackDialog', () => ({
OAuthCallbackDialog: ({
open,
providerId,
}: {
open: boolean
providerId: string
providerName: string
authResponse: OAuthAuthorizeResponse
methodIndex: number
onOpenChange: (open: boolean) => void
onSuccess: () => void
}) => (open ? <div data-testid="oauth-callback-dialog">{providerId}</div> : null),
}))
vi.mock('@/components/model/ApiKeyDialog', () => ({
ApiKeyDialog: ({
open,
mode,
provider,
}: {
open: boolean
onOpenChange: (open: boolean) => void
provider: { id: string; name: string; models: { id: string; name: string }[] }
onSuccess: () => void
mode: 'add' | 'edit'
}) => (open ? <div data-testid="api-key-dialog" data-mode={mode}>{provider.name}</div> : null),
}))
vi.mock('@/components/ui/delete-dialog', () => ({
DeleteDialog: ({
open,
onConfirm,
}: {
open: boolean
onOpenChange: (open: boolean) => void
onConfirm: () => void
onCancel: () => void
title: string
description: ReactNode
isDeleting: boolean
}) => (open ? <button onClick={onConfirm}>Confirm delete</button> : null),
}))
function providerFixture(id: string, name: string, modelCount: number): Provider {
return {
id,
name,
env: [],
models: Object.fromEntries(
Array.from({ length: modelCount }, (_, index) => [`model-${index}`, {} as Model]),
),
}
}
const oauthProviderWithKey = providerFixture('anthropic', 'Anthropic', 2)
const oauthProviderWithoutKey = providerFixture('google', 'Google', 3)
const apiKeyProviderWithKey = providerFixture('openai', 'OpenAI', 1)
const apiKeyProviderWithoutKey = providerFixture('together', 'Together AI', 4)
function mockProviderData() {
vi.mocked(getProviders).mockResolvedValue({
providers: [
oauthProviderWithKey,
oauthProviderWithoutKey,
apiKeyProviderWithKey,
apiKeyProviderWithoutKey,
],
connected: [],
default: {},
})
vi.mocked(providerCredentialsApi.list).mockResolvedValue(['anthropic', 'openai'])
vi.mocked(oauthApi.getAuthMethods).mockResolvedValue({
anthropic: [{ type: 'oauth', label: 'OAuth' }],
google: [{ type: 'oauth', label: 'OAuth' }],
})
}
function renderSettings() {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
})
return render(
<QueryClientProvider client={queryClient}>
<ProviderSettings />
</QueryClientProvider>,
)
}
describe('ProviderSettings', () => {
beforeEach(() => {
vi.clearAllMocks()
mockProviderData()
})
it('lays out OAuth and API key columns in a container-query grid that splits at 1000px of content width', async () => {
const { container } = renderSettings()
await screen.findByText('Anthropic')
const root = container.firstElementChild as HTMLElement
expect(root).toHaveClass('@container', 'w-full', 'max-w-7xl')
const layout = root.firstElementChild as HTMLElement
expect(layout).toHaveClass('grid', '@min-[1000px]:grid-cols-2', '@min-[1000px]:items-start')
const [oauthColumn, apiKeysColumn] = Array.from(layout.children) as HTMLElement[]
expect(oauthColumn).toHaveClass('min-w-0')
expect(within(oauthColumn).getByRole('heading', { name: 'OAuth Providers' })).toBeInTheDocument()
expect(apiKeysColumn).toHaveClass('min-w-0')
expect(within(apiKeysColumn).getByRole('heading', { name: 'API Keys' })).toBeInTheDocument()
})
it('renders OAuth providers as compact divider rows with the name, model count, status, and actions', async () => {
const { container } = renderSettings()
await screen.findByText('Anthropic')
const rows = container.querySelector('.divide-y') as HTMLElement
expect(rows).toHaveClass('divide-border')
const connectedRow = screen.getByText('Anthropic').closest('.py-3') as HTMLElement
expect(connectedRow).toHaveClass('flex-wrap')
expect(within(connectedRow).getByText('2 models')).toBeInTheDocument()
expect(within(connectedRow).getByText('Connected')).toBeInTheDocument()
expect(within(connectedRow).getByRole('button', { name: 'Reconnect' })).toBeInTheDocument()
expect(within(connectedRow).getByRole('button', { name: 'Disconnect' })).toBeInTheDocument()
const disconnectedRow = screen.getByText('Google').closest('.py-3') as HTMLElement
expect(within(disconnectedRow).getByText('3 models')).toBeInTheDocument()
expect(within(disconnectedRow).getByText('Not Connected')).toBeInTheDocument()
expect(within(disconnectedRow).getByRole('button', { name: 'Connect' })).toBeInTheDocument()
expect(within(disconnectedRow).queryByRole('button', { name: 'Disconnect' })).not.toBeInTheDocument()
})
it('expands Available Providers by default so the search is visible immediately', async () => {
renderSettings()
await screen.findByText('Together AI')
expect(screen.getByPlaceholderText('Search providers...')).toBeInTheDocument()
expect(screen.getByRole('button', { name: /Available Providers/ })).toHaveAttribute('aria-expanded', 'true')
expect(screen.getByRole('button', { name: /Connected/ })).toHaveAttribute('aria-expanded', 'false')
})
it('keeps the Connected disclosure collapsed and labels its icon-only key actions', async () => {
const user = userEvent.setup()
renderSettings()
await screen.findByText('Anthropic')
expect(screen.queryByText('OpenAI')).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: /Connected/ }))
const connectedCard = screen.getByText('OpenAI').closest('.bg-card') as HTMLElement
expect(within(connectedCard).getByRole('button', { name: 'Edit API key for OpenAI' })).toBeInTheDocument()
expect(within(connectedCard).getByRole('button', { name: 'Remove credentials for OpenAI' })).toBeInTheDocument()
})
it('filters the available provider search list and gives it the taller scroll area', async () => {
const user = userEvent.setup()
const { container } = renderSettings()
await screen.findByText('Together AI')
const list = container.querySelector('.max-h-96') as HTMLElement
expect(list).toBeInTheDocument()
await user.type(screen.getByPlaceholderText('Search providers...'), 'together')
expect(screen.getByText('Together AI')).toBeInTheDocument()
expect(screen.queryByText('OpenAI')).not.toBeInTheDocument()
})
it('opens the OAuth authorize dialog when Connect is chosen', async () => {
const user = userEvent.setup()
renderSettings()
await screen.findByText('Google')
await user.click(screen.getByRole('button', { name: 'Connect' }))
expect(screen.getByTestId('oauth-authorize-dialog')).toHaveTextContent('google')
})
it('opens the API key dialog in add mode from the available list', async () => {
const user = userEvent.setup()
renderSettings()
await screen.findByText('Together AI')
await user.click(screen.getByRole('button', { name: 'Add Key' }))
const dialog = screen.getByTestId('api-key-dialog')
expect(dialog).toHaveAttribute('data-mode', 'add')
expect(dialog).toHaveTextContent('Together AI')
})
it('opens the API key dialog in edit mode from the connected list', async () => {
const user = userEvent.setup()
renderSettings()
await screen.findByText('Anthropic')
await user.click(screen.getByRole('button', { name: /Connected/ }))
await user.click(screen.getByRole('button', { name: 'Edit API key for OpenAI' }))
const dialog = screen.getByTestId('api-key-dialog')
expect(dialog).toHaveAttribute('data-mode', 'edit')
expect(dialog).toHaveTextContent('OpenAI')
})
it('removes credentials through the confirm dialog', async () => {
const user = userEvent.setup()
vi.mocked(providerCredentialsApi.delete).mockResolvedValue(undefined)
renderSettings()
await screen.findByText('Anthropic')
await user.click(screen.getByRole('button', { name: 'Disconnect' }))
await user.click(screen.getByRole('button', { name: 'Confirm delete' }))
await waitFor(() => {
expect(providerCredentialsApi.delete).toHaveBeenCalledWith('anthropic')
})
})
it('shows the empty state when no OAuth-capable providers exist', async () => {
vi.mocked(oauthApi.getAuthMethods).mockResolvedValue({})
renderSettings()
await screen.findByText('No OAuth-capable providers available.')
expect(screen.queryByText('Anthropic')).not.toBeInTheDocument()
})
})
@@ -21,7 +21,7 @@ export function ProviderSettings() {
const [oauthResponse, setOauthResponse] = useState<OAuthAuthorizeResponse | null>(null)
const [oauthMethodIndex, setOauthMethodIndex] = useState<number | null>(null)
const [connectedExpanded, setConnectedExpanded] = useState(false)
const [availableExpanded, setAvailableExpanded] = useState(false)
const [availableExpanded, setAvailableExpanded] = useState(true)
const [availableSearch, setAvailableSearch] = useState('')
const [apiKeyDialogOpen, setApiKeyDialogOpen] = useState(false)
const [apiKeyProvider, setApiKeyProvider] = useState<Provider | null>(null)
@@ -165,120 +165,118 @@ export function ProviderSettings() {
}
return (
<div className="space-y-8">
<div className="space-y-4">
<div>
<h2 className="text-lg font-semibold text-foreground mb-2">OAuth Providers</h2>
<p className="text-sm text-muted-foreground">
Connect to AI providers using OAuth authentication.
</p>
</div>
{oauthProviders.length === 0 ? (
<Card className="bg-card border-border">
<CardContent className="pt-6">
<p className="text-sm text-muted-foreground text-center">
No OAuth-capable providers available.
<div className="@container w-full max-w-7xl space-y-8">
<div className="grid gap-8 @min-[1000px]:grid-cols-2 @min-[1000px]:items-start">
<div className="min-w-0 space-y-4">
<div>
<h2 className="text-lg font-semibold text-foreground mb-2">OAuth Providers</h2>
<p className="text-sm text-muted-foreground">
Connect to AI providers using OAuth authentication.
</p>
</CardContent>
</Card>
) : (
<div className="grid gap-4">
{oauthProviders.map((provider) => {
const hasKey = hasCredentials(provider.id)
const modelCount = Object.keys(provider.models || {}).length
</div>
return (
<Card key={provider.id} className="bg-card border-border">
<CardHeader className="p-2">
<div className="flex flex-col gap-3">
<div className="flex items-start justify-between gap-2">
<CardTitle className="text-base">
{provider.name || provider.id}
</CardTitle>
{hasKey ? (
<Badge variant="default" className="bg-green-600 hover:bg-green-700 shrink-0">
<Check className="h-3 w-3 mr-1" />
Connected
</Badge>
) : (
<Badge variant="secondary" className="shrink-0">
<X className="h-3 w-3 mr-1" />
Not Connected
</Badge>
)}
</div>
<CardDescription>
{modelCount > 0 && (
<span className="text-xs">{modelCount} model{modelCount !== 1 ? 's' : ''}</span>
)}
</CardDescription>
<div className="flex flex-wrap gap-2">
{oauthProviders.length === 0 ? (
<Card className="bg-card border-border">
<CardContent className="pt-6">
<p className="text-sm text-muted-foreground text-center">
No OAuth-capable providers available.
</p>
</CardContent>
</Card>
) : (
<div className="divide-y divide-border">
{oauthProviders.map((provider) => {
const hasKey = hasCredentials(provider.id)
const modelCount = Object.keys(provider.models || {}).length
return (
<div key={provider.id} className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 py-3">
<div className="min-w-0">
<p className="text-sm font-medium text-foreground truncate">
{provider.name || provider.id}
</p>
{modelCount > 0 && (
<p className="text-xs text-muted-foreground">
{modelCount} model{modelCount !== 1 ? 's' : ''}
</p>
)}
</div>
<div className="flex flex-wrap items-center gap-2">
{hasKey ? (
<Badge variant="default" className="bg-green-600 hover:bg-green-700 shrink-0">
<Check className="h-3 w-3 mr-1" />
Connected
</Badge>
) : (
<Badge variant="secondary" className="shrink-0">
<X className="h-3 w-3 mr-1" />
Not Connected
</Badge>
)}
<Button
size="sm"
variant={hasKey ? 'outline' : 'default'}
onClick={() => {
setSelectedProvider(provider.id)
setOauthDialogOpen(true)
}}
>
<Shield className="h-4 w-4 mr-1" />
{hasKey ? 'Reconnect' : 'Connect'}
</Button>
{hasKey && (
<Button
size="sm"
variant={hasKey ? 'outline' : 'default'}
onClick={() => {
setSelectedProvider(provider.id)
setOauthDialogOpen(true)
}}
variant="destructive"
onClick={() => handleDeleteCredential(provider.id)}
disabled={deleteCredentialMutation.isPending}
>
<Shield className="h-4 w-4 mr-1" />
{hasKey ? 'Reconnect' : 'Connect'}
Disconnect
</Button>
{hasKey && (
<Button
size="sm"
variant="destructive"
onClick={() => handleDeleteCredential(provider.id)}
disabled={deleteCredentialMutation.isPending}
>
Disconnect
</Button>
)}
</div>
)}
</div>
</CardHeader>
</Card>
)
})}
</div>
)
})}
</div>
)}
{selectedProvider && (
<OAuthAuthorizeDialog
providerId={selectedProvider}
providerName={selectedProviderName}
methods={authMethods?.[selectedProvider] || []}
open={oauthDialogOpen}
onOpenChange={handleOAuthDialogClose}
onSuccess={handleOAuthAuthorize}
/>
)}
{selectedProvider && oauthResponse && oauthMethodIndex !== null && (
<OAuthCallbackDialog
providerId={selectedProvider}
providerName={selectedProviderName}
authResponse={oauthResponse}
methodIndex={oauthMethodIndex}
open={oauthCallbackDialogOpen}
onOpenChange={setOauthCallbackDialogOpen}
onSuccess={handleOAuthSuccess}
/>
)}
</div>
)}
{selectedProvider && (
<OAuthAuthorizeDialog
providerId={selectedProvider}
providerName={selectedProviderName}
methods={authMethods?.[selectedProvider] || []}
open={oauthDialogOpen}
onOpenChange={handleOAuthDialogClose}
onSuccess={handleOAuthAuthorize}
/>
)}
{selectedProvider && oauthResponse && oauthMethodIndex !== null && (
<OAuthCallbackDialog
providerId={selectedProvider}
providerName={selectedProviderName}
authResponse={oauthResponse}
methodIndex={oauthMethodIndex}
open={oauthCallbackDialogOpen}
onOpenChange={setOauthCallbackDialogOpen}
onSuccess={handleOAuthSuccess}
/>
)}
</div>
<div className="space-y-4">
<div>
<h2 className="text-lg font-semibold text-foreground mb-2">API Keys</h2>
<p className="text-sm text-muted-foreground">
Manage API keys for AI providers.
</p>
</div>
<div className="min-w-0 space-y-4">
<div>
<h2 className="text-lg font-semibold text-foreground mb-2">API Keys</h2>
<p className="text-sm text-muted-foreground">
Manage API keys for AI providers.
</p>
</div>
<div className="space-y-3">
<button
onClick={() => setConnectedExpanded(!connectedExpanded)}
aria-expanded={connectedExpanded}
className="flex items-center gap-2 w-full text-left py-2 px-1 hover:bg-accent/50 rounded-md transition-colors"
>
{connectedExpanded ? (
@@ -324,6 +322,7 @@ export function ProviderSettings() {
size="sm"
variant="ghost"
onClick={() => handleEditApiKey(provider)}
aria-label={`Edit API key for ${provider.name || provider.id}`}
className="h-8 w-8 p-0"
>
<Pencil className="h-3.5 w-3.5" />
@@ -333,6 +332,7 @@ export function ProviderSettings() {
variant="ghost"
onClick={() => handleDeleteCredential(provider.id)}
disabled={deleteCredentialMutation.isPending}
aria-label={`Remove credentials for ${provider.name || provider.id}`}
className="h-8 w-8 p-0 text-destructive hover:text-destructive"
>
<Trash2 className="h-3.5 w-3.5" />
@@ -351,6 +351,7 @@ export function ProviderSettings() {
<div className="space-y-3">
<button
onClick={() => setAvailableExpanded(!availableExpanded)}
aria-expanded={availableExpanded}
className="flex items-center gap-2 w-full text-left py-2 px-1 hover:bg-accent/50 rounded-md transition-colors"
>
{availableExpanded ? (
@@ -377,7 +378,7 @@ export function ProviderSettings() {
/>
</div>
<div className="space-y-2 max-h-64 overflow-y-auto scrollbar-thin pt-4 pb-1 pr-1 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
<div className="space-y-2 max-h-96 overflow-y-auto scrollbar-thin pt-4 pb-1 pr-1 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
{filteredAvailableProviders.length === 0 ? (
<p className="text-sm text-muted-foreground py-2">
{availableSearch ? 'No providers match your search.' : 'No available providers.'}
@@ -415,6 +416,7 @@ export function ProviderSettings() {
)}
</div>
</div>
</div>
{apiKeyProvider && (
<ApiKeyDialog
@@ -27,7 +27,7 @@ export function ServerHealthStatus({ onOpenVersionDialog }: ServerHealthStatusPr
return (
<Card className="bg-transparent border-transparent">
<CardContent className="p-3">
<div className="flex items-center justify-center gap-2">
<div className="flex items-center gap-2">
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
<span className="text-sm text-muted-foreground">Loading server status...</span>
</div>
@@ -41,10 +41,10 @@ export function ServerHealthStatus({ onOpenVersionDialog }: ServerHealthStatusPr
return (
<Card className={cn('bg-transparent border-transparent', isUnhealthy && 'border-destructive')}>
<CardContent className="p-3">
<div className="flex flex-col sm:flex-row sm:items-center items-center justify-center gap-3">
<div className="flex items-center gap-2 flex-wrap justify-center ">
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex min-w-0 flex-wrap items-center gap-2">
<div className={`h-3 w-3 rounded-full ${isUnhealthy ? 'bg-destructive animate-pulse' : 'bg-green-500'}`} />
<p className="font-medium text-sm sm:text-base">
<p className="font-medium text-sm">
Server Status: {isUnhealthy ? 'Unhealthy' : 'Healthy'}
</p>
{health.error && (
@@ -63,7 +63,7 @@ export function ServerHealthStatus({ onOpenVersionDialog }: ServerHealthStatusPr
</p>
)}
</div>
<div className="flex flex-wrap gap-2 justify-center sm:justify-end">
<div className="flex flex-wrap gap-2">
<Button
variant="outline"
size="sm"
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { render, screen, fireEvent, within } from '@testing-library/react'
import { render, screen, fireEvent, within, act } from '@testing-library/react'
import { MemoryRouter, useLocation, useNavigate } from 'react-router-dom'
import { SettingsDialog } from './SettingsDialog'
import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'
@@ -144,10 +144,10 @@ describe('SettingsDialog', () => {
expect(screen.getByTestId('dialog-open')).toBeInTheDocument()
expect(screen.getAllByText('Account').length).toBeGreaterThanOrEqual(1)
expect(screen.getAllByText('General').length).toBeGreaterThanOrEqual(1)
expect(screen.getAllByText('General Settings').length).toBeGreaterThanOrEqual(1)
expect(screen.getAllByText('Git').length).toBeGreaterThanOrEqual(1)
expect(screen.getAllByText('Shortcuts').length).toBeGreaterThanOrEqual(1)
expect(screen.getAllByText('OpenCode').length).toBeGreaterThanOrEqual(1)
expect(screen.getAllByText('Keyboard Shortcuts').length).toBeGreaterThanOrEqual(1)
expect(screen.getAllByText('OpenCode Config').length).toBeGreaterThanOrEqual(1)
expect(screen.getAllByText('Providers').length).toBeGreaterThanOrEqual(1)
const mobileContainer = document.querySelector('.sm\\:hidden') as HTMLElement
@@ -192,7 +192,7 @@ describe('SettingsDialog', () => {
expect(screen.getByTestId('location-search')).toHaveTextContent('settingsTab=logs')
})
it('opens directly on the Logs mobile view from ?settings=open&settingsTab=logs and returns to the menu on back', () => {
it('starts at the menu on mobile even with a deep-linked settingsTab and navigates from there', () => {
stubMatchMedia(false)
function TestWrapper() {
const location = useLocation()
@@ -205,6 +205,7 @@ describe('SettingsDialog', () => {
<>
<button onClick={() => navigate('/')}>Close Settings</button>
{isOpen && <span data-testid="dialog-open">Dialog Open</span>}
{isOpen && <span data-testid="location-search">{location.search}</span>}
<SettingsDialog />
</>
)
@@ -221,9 +222,20 @@ describe('SettingsDialog', () => {
const mobileContainer = document.querySelector('.sm\\:hidden') as HTMLElement
const mobile = within(mobileContainer)
expect(mobile.getByRole('heading', { name: 'Settings' })).toBeInTheDocument()
expect(mobile.getByText('Live manager and OpenCode server logs')).toBeInTheDocument()
expect(mobile.queryByTestId('logs-settings')).not.toBeInTheDocument()
expect(mobileContainer.querySelector('svg.lucide-chevron-left')).toBeNull()
expect(screen.queryByTestId('logs-settings')).not.toBeInTheDocument()
const logsMenuButton = mobile.getByText('Live manager and OpenCode server logs').closest('button')
expect(logsMenuButton).not.toBeNull()
fireEvent.click(logsMenuButton!)
expect(mobile.getByTestId('logs-settings')).toBeInTheDocument()
expect(mobile.getByRole('heading', { name: 'Logs' })).toBeInTheDocument()
expect(screen.getAllByTestId('logs-settings')).toHaveLength(1)
expect(screen.getByTestId('location-search')).toHaveTextContent('settingsTab=logs')
const backButton = mobileContainer.querySelector('svg.lucide-chevron-left')?.closest('button')
expect(backButton).not.toBeNull()
@@ -231,9 +243,7 @@ describe('SettingsDialog', () => {
expect(mobile.queryByTestId('logs-settings')).not.toBeInTheDocument()
expect(mobile.getByRole('heading', { name: 'Settings' })).toBeInTheDocument()
expect(mobile.getByText('Live manager and OpenCode server logs')).toBeInTheDocument()
expect(mobileContainer.querySelector('svg.lucide-chevron-left')).toBeNull()
expect(screen.queryByTestId('logs-settings')).not.toBeInTheDocument()
})
it('mounts exactly one LogsViewer on desktop when the Logs tab is selected', () => {
@@ -299,9 +309,16 @@ describe('SettingsDialog', () => {
expect(desktopTrigger).toHaveAttribute('data-state', 'active')
})
it('applies compact responsive sizing to all nine desktop tab triggers', () => {
it('renders a vertical desktop sidebar driven by menu items with URL and keyboard navigation', async () => {
stubMatchMedia(true)
function TestWrapper() {
return <SettingsDialog />
const location = useLocation()
return (
<>
<span data-testid="location-search">{location.search}</span>
<SettingsDialog />
</>
)
}
render(
@@ -310,16 +327,27 @@ describe('SettingsDialog', () => {
</MemoryRouter>
)
const tablist = screen.getByRole('tablist')
expect(tablist).toHaveAttribute('aria-orientation', 'vertical')
const triggers = screen.getAllByRole('tab')
expect(triggers).toHaveLength(9)
const expected = ['Account', 'General', 'Notify', 'Voice', 'Git', 'Shortcuts', 'OpenCode', 'Logs', 'Providers']
const expected = ['Account', 'General Settings', 'Notifications', 'Voice', 'Git', 'Keyboard Shortcuts', 'OpenCode Config', 'Logs', 'Providers']
expect(triggers.map((trigger) => trigger.textContent)).toEqual(expected)
for (const trigger of triggers) {
expect(trigger.className).toContain('sm:px-2')
expect(trigger.className).toContain('sm:text-xs')
expect(trigger.className).toContain('md:px-3')
expect(trigger.className).toContain('md:text-sm')
}
const logsTrigger = screen.getByRole('tab', { name: 'Logs' })
fireEvent.mouseDown(logsTrigger)
expect(screen.getByTestId('location-search')).toHaveTextContent('settingsTab=logs')
const gitTrigger = screen.getByRole('tab', { name: 'Git' })
act(() => {
gitTrigger.focus()
})
fireEvent.keyDown(gitTrigger, { key: 'ArrowDown' })
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 0))
})
expect(screen.getByRole('tab', { name: 'Keyboard Shortcuts' })).toHaveFocus()
})
it('keeps Settings open when Escape fires inside a nested dialog', () => {
@@ -23,16 +23,33 @@ import { DESKTOP_MEDIA_QUERY, useMediaQuery } from '@/hooks/useMediaQuery'
type SettingsView = 'menu' | SettingsContentTab
const TAB_TRIGGER_CLASS = 'data-[state=active]:bg-blue-600 data-[state=active]:text-white text-muted-foreground transition-all duration-200 sm:px-2 sm:text-xs md:px-3 md:text-sm'
function OpenCodeSettings({ onOpenVersionDialog }: { onOpenVersionDialog: () => void }) {
const [authSectionsOpen, setAuthSectionsOpen] = useState(true)
const toggleAuthSections = useCallback(() => setAuthSectionsOpen((open) => !open), [])
return (
<div className="space-y-6">
<ServerHealthStatus onOpenVersionDialog={onOpenVersionDialog} />
<OpenCodeConfigManager />
<section className="space-y-4 border-t border-border pt-6" aria-label="Server maintenance">
<h2 className="text-lg font-semibold">Server maintenance</h2>
<div className="grid grid-cols-1 items-start gap-4 @min-[1000px]:grid-cols-2">
<OpenCodeServerAuthSettings isOpen={authSectionsOpen} onToggle={toggleAuthSections} />
<ManagerTokenSettings isOpen={authSectionsOpen} onToggle={toggleAuthSections} />
</div>
<ServerEnvVarsSettings />
<SandboxSettings />
</section>
</div>
)
}
export function SettingsDialog() {
const { isOpen, close, activeTab, selectedTab, setActiveTab } = useSettingsDialog()
const { isOpen, close, activeTab, setActiveTab } = useSettingsDialog()
const isDesktop = useMediaQuery(DESKTOP_MEDIA_QUERY)
const [mobileView, setMobileView] = useState<SettingsView>('menu')
const [isVersionDialogOpen, setIsVersionDialogOpen] = useState(false)
const [sectionHistory, setSectionHistory] = useState<SettingsView[]>([])
const [authSectionsOpen, setAuthSectionsOpen] = useState(true)
const toggleAuthSections = useCallback(() => setAuthSectionsOpen((open) => !open), [])
const pushSectionHistory = useCallback((view: SettingsView) => {
if (view === 'menu') return
@@ -87,12 +104,6 @@ export function SettingsDialog() {
return () => document.removeEventListener('keydown', handleKeyDown, { capture: true })
}, [isOpen, close, isVersionDialogOpen])
useEffect(() => {
if (!isOpen || !selectedTab) return
setMobileView(selectedTab)
pushSectionHistory(selectedTab)
}, [isOpen, selectedTab, pushSectionHistory])
const menuItems: Array<{ id: SettingsContentTab; icon: LucideIcon; label: string; description: string }> = [
{ id: 'account', icon: User, label: 'Account', description: 'Profile, passkeys, and sign out' },
{ id: 'general', icon: Settings2, label: 'General Settings', description: 'App preferences and behavior' },
@@ -131,76 +142,51 @@ export function SettingsDialog() {
data-settings-dialog
>
<DialogTitle className="sr-only">Settings</DialogTitle>
<div className="hidden sm:flex sm:flex-col sm:h-full sm:min-h-0">
<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">
Settings
</h2>
<div className="hidden sm:flex sm:h-full sm:min-h-0 sm:flex-col">
<div className="flex h-12 shrink-0 items-center justify-between border-b border-border bg-background px-4">
<h2 className="text-lg font-semibold text-foreground">Settings</h2>
<Button
variant="ghost"
size="icon"
onClick={close}
className="text-muted-foreground hover:text-foreground min-w-[44px] min-h-[44px]"
aria-label="Close"
className="text-muted-foreground hover:text-foreground"
>
<X className="w-5 h-5" />
<X className="w-4 h-4" />
</Button>
</div>
<Tabs defaultValue="account" value={activeTab} onValueChange={handleTabChange} className="w-full flex flex-col flex-1 min-h-0">
<div className="px-6 pt-6 pb-4 flex-shrink-0">
<TabsList className="grid w-full grid-cols-9 bg-card p-1">
<TabsTrigger value="account" className={TAB_TRIGGER_CLASS}>
Account
<Tabs
defaultValue="account"
value={activeTab}
onValueChange={handleTabChange}
orientation="vertical"
className="flex min-h-0 w-full flex-1"
>
<TabsList className="flex h-full min-h-0 w-56 shrink-0 flex-col items-stretch justify-start overflow-y-auto rounded-none border-r border-border bg-card p-1">
{menuItems.map((item) => (
<TabsTrigger
key={item.id}
value={item.id}
className="shrink-0 justify-start gap-2 rounded-md px-3 py-2 text-sm text-muted-foreground transition-colors data-[state=active]:bg-accent data-[state=active]:text-foreground data-[state=active]:shadow-none"
>
<item.icon className="h-4 w-4 shrink-0" />
{item.label}
</TabsTrigger>
<TabsTrigger value="general" className={TAB_TRIGGER_CLASS}>
General
</TabsTrigger>
<TabsTrigger value="notifications" className={TAB_TRIGGER_CLASS}>
Notify
</TabsTrigger>
<TabsTrigger value="voice" className={TAB_TRIGGER_CLASS}>
Voice
</TabsTrigger>
<TabsTrigger value="git" className={TAB_TRIGGER_CLASS}>
Git
</TabsTrigger>
<TabsTrigger value="shortcuts" className={TAB_TRIGGER_CLASS}>
Shortcuts
</TabsTrigger>
<TabsTrigger value="opencode" className={TAB_TRIGGER_CLASS}>
OpenCode
</TabsTrigger>
<TabsTrigger value="logs" className={TAB_TRIGGER_CLASS}>
Logs
</TabsTrigger>
<TabsTrigger value="providers" className={TAB_TRIGGER_CLASS}>
Providers
</TabsTrigger>
</TabsList>
</div>
))}
</TabsList>
<div className="flex-1 min-h-0 overflow-y-auto">
<div className="px-6 pb-6">
<TabsContent key="account" value="account" className="mt-0"><AccountSettings /></TabsContent>
<TabsContent key="general" value="general" className="mt-0"><GeneralSettings /></TabsContent>
<TabsContent key="notifications" value="notifications" className="mt-0"><NotificationSettings /></TabsContent>
<TabsContent key="voice" value="voice" className="mt-0"><VoiceSettings /></TabsContent>
<TabsContent key="git" value="git" className="mt-0"><GitSettings /></TabsContent>
<TabsContent key="shortcuts" value="shortcuts" className="mt-0"><KeyboardShortcuts /></TabsContent>
<TabsContent key="opencode" value="opencode" className="mt-0">
<div className="space-y-6">
<ServerHealthStatus onOpenVersionDialog={() => setIsVersionDialogOpen(true)} />
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<OpenCodeServerAuthSettings isOpen={authSectionsOpen} onToggle={toggleAuthSections} />
<ManagerTokenSettings isOpen={authSectionsOpen} onToggle={toggleAuthSections} />
</div>
<ServerEnvVarsSettings />
<SandboxSettings />
<OpenCodeConfigManager />
</div>
</TabsContent>
<TabsContent key="logs" value="logs" className="mt-0">{isDesktop && <LogsViewer />}</TabsContent>
<TabsContent key="providers" value="providers" className="mt-0"><ProviderSettings /></TabsContent>
</div>
<div className={`@container min-h-0 min-w-0 flex-1 p-6 ${activeTab === 'logs' ? 'overflow-hidden' : 'overflow-y-auto'}`}>
<TabsContent key="account" value="account" className="mt-0 px-0 max-w-7xl"><AccountSettings /></TabsContent>
<TabsContent key="general" value="general" className="mt-0 px-0 max-w-4xl"><GeneralSettings /></TabsContent>
<TabsContent key="notifications" value="notifications" className="mt-0 px-0 max-w-7xl"><NotificationSettings /></TabsContent>
<TabsContent key="voice" value="voice" className="mt-0 px-0 max-w-7xl"><VoiceSettings /></TabsContent>
<TabsContent key="git" value="git" className="mt-0 px-0 max-w-7xl"><GitSettings /></TabsContent>
<TabsContent key="shortcuts" value="shortcuts" className="mt-0 px-0 max-w-7xl"><KeyboardShortcuts /></TabsContent>
<TabsContent key="opencode" value="opencode" className="mt-0 px-0">
<OpenCodeSettings onOpenVersionDialog={() => setIsVersionDialogOpen(true)} />
</TabsContent>
<TabsContent key="logs" value="logs" className="mt-0 h-full min-h-0 px-0">{isDesktop && <LogsViewer />}</TabsContent>
<TabsContent key="providers" value="providers" className="mt-0 px-0 max-w-7xl"><ProviderSettings /></TabsContent>
</div>
</Tabs>
</div>
@@ -222,17 +208,18 @@ export function SettingsDialog() {
{mobileView === 'menu' ? 'Settings' : menuItems.find(item => item.id === mobileView)?.label}
</h2>
</div>
<Button
variant="ghost"
size="icon"
onClick={close}
className="text-muted-foreground hover:text-foreground min-w-[44px] min-h-[44px] flex-shrink-0"
>
<Button
variant="ghost"
size="icon"
onClick={close}
aria-label="Close"
className="text-muted-foreground hover:text-foreground min-w-[44px] min-h-[44px] flex-shrink-0"
>
<X className="w-6 h-6" />
</Button>
</div>
<div className="flex-1 min-h-0 overflow-y-auto p-3 pb-[calc(env(safe-area-inset-bottom)+1rem)]">
<div className={`@container flex-1 min-h-0 p-3 pb-[calc(env(safe-area-inset-bottom)+1rem)] ${mobileView === 'logs' ? 'overflow-hidden' : 'overflow-y-auto'}`}>
{mobileView === 'menu' && (
<div className="space-y-3">
{menuItems.map((item) => (
@@ -262,17 +249,10 @@ export function SettingsDialog() {
{mobileView === 'git' && <div key="git"><GitSettings /></div>}
{mobileView === 'shortcuts' && <div key="shortcuts"><KeyboardShortcuts /></div>}
{mobileView === 'opencode' && (
<div key="opencode" className="space-y-4">
<ServerHealthStatus onOpenVersionDialog={() => setIsVersionDialogOpen(true)} />
<OpenCodeServerAuthSettings />
<ManagerTokenSettings />
<ServerEnvVarsSettings />
<SandboxSettings />
<OpenCodeConfigManager />
</div>
<OpenCodeSettings key="opencode" onOpenVersionDialog={() => setIsVersionDialogOpen(true)} />
)}
{mobileView === 'providers' && <div key="providers"><ProviderSettings /></div>}
{mobileView === 'logs' && !isDesktop && <div key="logs"><LogsViewer /></div>}
{mobileView === 'logs' && !isDesktop && <div key="logs" className="h-full min-h-0"><LogsViewer /></div>}
</div>
</div>
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { render, screen, fireEvent, act } from '@testing-library/react'
import { render, screen, fireEvent, within, act } from '@testing-library/react'
import { MemoryRouter } from 'react-router-dom'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import type { ManagerLogEntry } from '@opencode-manager/shared/schemas'
@@ -90,6 +90,12 @@ async function settleTime(ms: number): Promise<void> {
})
}
function openLogsFromMenu(): void {
const mobileContainer = document.querySelector('.sm\\:hidden') as HTMLElement
const logsMenuButton = within(mobileContainer).getByText('Live manager and OpenCode server logs').closest('button')
fireEvent.click(logsMenuButton!)
}
describe('SettingsDialog live Logs view integration', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -118,6 +124,7 @@ describe('SettingsDialog live Logs view integration', () => {
stubMatchMedia(false)
render(<SettingsDialog />, { wrapper: createWrapper() })
openLogsFromMenu()
await settleTime(0)
expect(getManagerLogs).toHaveBeenCalledTimes(1)
@@ -129,6 +136,7 @@ describe('SettingsDialog live Logs view integration', () => {
getManagerLogs.mockImplementation(async () => makeResponse([]))
render(<SettingsDialog />, { wrapper: createWrapper() })
openLogsFromMenu()
await settleTime(0)
expect(getManagerLogs).toHaveBeenCalledTimes(1)
@@ -0,0 +1,29 @@
import { describe, it, expect, vi } from 'vitest'
import { render, screen } from '@testing-library/react'
import { VoiceSettings } from './VoiceSettings'
vi.mock('./TTSSettings', () => ({
TTSSettings: () => <div data-testid="tts-settings">TTS</div>,
}))
vi.mock('./STTSettings', () => ({
STTSettings: () => <div data-testid="stt-settings">STT</div>,
}))
describe('VoiceSettings', () => {
it('renders TTS and STT as top-aligned equal columns split at 1000px of container width', () => {
const { container } = render(<VoiceSettings />)
const root = container.firstElementChild as HTMLElement
expect(root).toHaveClass('@container', 'w-full', 'max-w-7xl')
const ttsColumn = screen.getByTestId('tts-settings').parentElement as HTMLElement
const sttColumn = screen.getByTestId('stt-settings').parentElement as HTMLElement
expect(ttsColumn).toHaveClass('min-w-0')
expect(sttColumn).toHaveClass('min-w-0')
const layout = ttsColumn.parentElement as HTMLElement
expect(layout).toHaveClass('grid', '@min-[1000px]:grid-cols-2', '@min-[1000px]:items-start')
expect(layout.firstElementChild).toBe(ttsColumn)
})
})
@@ -3,9 +3,15 @@ import { STTSettings } from './STTSettings'
export function VoiceSettings() {
return (
<div className="space-y-6">
<TTSSettings />
<STTSettings />
<div className="@container w-full max-w-7xl">
<div className="grid gap-6 @min-[1000px]:grid-cols-2 @min-[1000px]:items-start">
<div className="min-w-0">
<TTSSettings />
</div>
<div className="min-w-0">
<STTSettings />
</div>
</div>
</div>
)
}
@@ -1,10 +1,10 @@
import { useMemo, useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { listBranches, switchBranch, GitAuthError, getRepo } from '@/api/repos'
import { fetchGitStatus, useGitStatus } from '@/api/git'
import { fetchGitStatus } from '@/api/git'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Loader2, GitBranch, GitBranchPlus, Check, Plus, AlertCircle, ArrowUp, ArrowDown, Globe } from 'lucide-react'
import { Loader2, GitBranch, GitBranchPlus, Check, Plus, AlertCircle, Globe } from 'lucide-react'
import { cn } from '@/lib/utils'
import { showToast } from '@/lib/toast'
import { useGit } from '@/hooks/useGit'
@@ -25,8 +25,6 @@ export function BranchesTab({ repoId, currentBranch }: BranchesTabProps) {
const [worktreeDialogOpen, setWorktreeDialogOpen] = useState(false)
const git = useGit(repoId)
const { data: status } = useGitStatus(repoId)
const { data: branches, isLoading, error, refetch } = useQuery({
queryKey: ['branches', repoId],
queryFn: () => listBranches(repoId),
@@ -103,36 +101,18 @@ export function BranchesTab({ repoId, currentBranch }: BranchesTabProps) {
}
const activeBranch = branches?.branches?.find(b => b.current)?.name || currentBranch
const hasBranches = (branches?.branches?.length ?? 0) > 0
return (
<div className="flex flex-col h-full">
<div className="p-3 border-b border-border space-y-3 flex-shrink-0">
<div className="flex items-center gap-2">
<GitBranch className="w-4 h-4 text-muted-foreground" />
<span className="text-sm font-medium">Current: {activeBranch}</span>
{status && (status.ahead > 0 || status.behind > 0) && (
<div className="flex items-center gap-1 text-xs text-muted-foreground">
{status.ahead > 0 && (
<span className="flex items-center gap-0.5">
<ArrowUp className="w-3 h-3" />{status.ahead}
</span>
)}
{status.behind > 0 && (
<span className="flex items-center gap-0.5">
<ArrowDown className="w-3 h-3" />{status.behind}
</span>
)}
</div>
)}
</div>
<div className="p-3 border-b border-border flex-shrink-0">
{isCreating ? (
<div className="flex items-center gap-2">
<Input
placeholder="New branch name..."
value={newBranchName}
onChange={(e) => setNewBranchName(e.target.value)}
className="h-8 md:text-sm"
className="h-10 md:h-8 md:text-sm"
autoFocus
onKeyDown={(e) => {
if (e.key === 'Enter') handleCreateBranch()
@@ -144,7 +124,7 @@ export function BranchesTab({ repoId, currentBranch }: BranchesTabProps) {
/>
<Button
size="sm"
className="h-8"
className="h-10 md:h-8"
onClick={handleCreateBranch}
disabled={!newBranchName.trim() || git.createBranch.isPending}
>
@@ -157,7 +137,7 @@ export function BranchesTab({ repoId, currentBranch }: BranchesTabProps) {
<Button
size="sm"
variant="ghost"
className="h-8"
className="h-10 md:h-8"
onClick={() => {
setIsCreating(false)
setNewBranchName('')
@@ -168,39 +148,38 @@ export function BranchesTab({ repoId, currentBranch }: BranchesTabProps) {
</div>
) : (
<div className="flex items-center gap-2">
{hasBranches && (
<Input
placeholder="Search branches..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="h-10 md:h-8 md:text-sm flex-1 min-w-0"
/>
)}
<Button
size="sm"
variant="outline"
className="flex-1 h-8"
className="h-10 md:h-8 flex-shrink-0"
onClick={() => setIsCreating(true)}
title="Create branch"
>
<Plus className="w-4 h-4 mr-2" />
Create Branch
<Plus className="w-4 h-4" />
<span className="hidden sm:inline ml-1">Branch</span>
</Button>
{repoUrl && (
<Button
size="sm"
variant="outline"
className="flex-1 h-8"
className="h-10 md:h-8 flex-shrink-0"
onClick={() => setWorktreeDialogOpen(true)}
title="Create as a separate worktree workspace"
>
<GitBranchPlus className="w-4 h-4 mr-2" />
Create Worktree
<GitBranchPlus className="w-4 h-4" />
<span className="hidden sm:inline ml-1">Worktree</span>
</Button>
)}
</div>
)}
{branches?.branches && branches.branches.length > 0 && (
<div className="px-3 pb-1">
<Input
placeholder="Search branches..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="h-8 md:text-sm"
/>
</div>
)}
</div>
<div className="flex-1 overflow-y-auto relative">
@@ -228,7 +207,7 @@ export function BranchesTab({ repoId, currentBranch }: BranchesTabProps) {
key={branch.name}
className={cn(
'flex items-center gap-2 px-3 py-2 w-full text-left transition-colors',
isCurrent && 'bg-accent',
isCurrent && 'bg-orange-500/10',
isCheckedOutElsewhere ? 'opacity-60 cursor-not-allowed' : 'hover:bg-accent/50'
)}
onClick={handleClick}
@@ -112,8 +112,8 @@ export function SourceControlPanel({
<div className="flex items-center justify-between px-3 py-2 border-b border-border flex-shrink-0">
<div className="flex items-center gap-2">
<div className="flex items-center gap-2">
<GitBranch className="w-4 h-4 text-muted-foreground" />
<span className="text-sm font-medium">{displayBranch}</span>
<GitBranch className={cn('w-4 h-4', GIT_UI_COLORS.current)} />
<span className={cn('text-sm font-medium', GIT_UI_COLORS.current)}>{displayBranch}</span>
</div>
{status && (status.ahead > 0 || status.behind > 0) && (
<div className="flex items-center gap-1 text-xs text-muted-foreground">
@@ -114,4 +114,31 @@ describe('SidebarCollapseToggle', () => {
fireEvent.click(screen.getByRole('button'))
expect(handleToggle).toHaveBeenCalledTimes(1)
})
it('calls onToggle when clicked while collapsed', () => {
const handleToggle = vi.fn()
render(
<SidebarCollapseToggle collapsed={true} onToggle={handleToggle} />
)
fireEvent.click(screen.getByRole('button', { name: 'Expand sidebar' }))
expect(handleToggle).toHaveBeenCalledTimes(1)
})
it('exposes expanded state via accessible name and aria-expanded', () => {
const { rerender } = render(
<SidebarCollapseToggle collapsed={false} onToggle={vi.fn()} />
)
expect(
screen.getByRole('button', { name: 'Collapse sidebar' })
).toHaveAttribute('aria-expanded', 'true')
rerender(<SidebarCollapseToggle collapsed={true} onToggle={vi.fn()} />)
expect(
screen.getByRole('button', { name: 'Expand sidebar' })
).toHaveAttribute('aria-expanded', 'false')
})
})
+31 -7
View File
@@ -1,11 +1,11 @@
import type { LucideIcon } from 'lucide-react'
import { PanelLeft, PanelLeftClose } from 'lucide-react'
import { ChevronLeft, ChevronRight } from 'lucide-react'
import { cn } from '@/lib/utils'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
export interface SidebarProps {
collapsed: boolean
onToggle: () => void
onToggle?: () => void
widthClass?: string
collapsedWidthClass?: string
className?: string
@@ -15,6 +15,7 @@ export interface SidebarProps {
export function Sidebar({
collapsed,
onToggle,
widthClass = 'w-60',
collapsedWidthClass = 'w-14',
className,
@@ -24,12 +25,13 @@ export function Sidebar({
return (
<aside
className={cn(
'flex-shrink-0 border-r border-border bg-card/50 backdrop-blur-sm h-dvh flex flex-col pt-safe pb-safe transition-[width] duration-200',
'relative z-20 flex-shrink-0 border-r border-border bg-card/50 backdrop-blur-sm h-dvh flex flex-col pt-safe pb-safe transition-[width] duration-200',
collapsed ? collapsedWidthClass : widthClass,
className
)}
aria-label={ariaLabel}
>
{onToggle && <SidebarCollapseToggle collapsed={collapsed} onToggle={onToggle} />}
{children}
</aside>
)
@@ -125,14 +127,36 @@ export function SidebarCollapseToggle({ collapsed, onToggle }: SidebarCollapseTo
type="button"
onClick={onToggle}
className={cn(
'rounded-md p-2.5',
'hover:bg-accent hover:text-accent-foreground',
'transition-colors duration-150'
'group absolute -right-3 top-1/2 z-20 h-16 w-6 -translate-y-1/2',
'flex items-center justify-center bg-transparent',
'focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background'
)}
title={collapsed ? 'Expand sidebar' : 'Collapse sidebar'}
aria-label={collapsed ? 'Expand sidebar' : 'Collapse sidebar'}
aria-expanded={!collapsed}
>
{collapsed ? <PanelLeft className="h-5 w-5" /> : <PanelLeftClose className="h-5 w-5" />}
<span aria-hidden="true" className="relative flex items-center justify-center">
<span
className={cn(
'h-8 w-1 rounded-full bg-orange-500/60 transition-colors duration-150',
'group-hover:bg-orange-500 group-focus-visible:bg-orange-500'
)}
/>
<ChevronLeft
className={cn(
'absolute left-full ml-0.5 h-3.5 w-3.5 text-muted-foreground opacity-0 transition-opacity duration-150',
'group-hover:opacity-100 group-focus-visible:opacity-100',
collapsed && 'hidden'
)}
/>
<ChevronRight
className={cn(
'absolute left-full ml-0.5 h-3.5 w-3.5 text-muted-foreground opacity-0 transition-opacity duration-150',
'group-hover:opacity-100 group-focus-visible:opacity-100',
!collapsed && 'hidden'
)}
/>
</span>
</button>
)
}
+1 -1
View File
@@ -10,7 +10,7 @@ export const GIT_STATUS_COLORS = {
export const GIT_UI_COLORS = {
ahead: 'text-emerald-600 dark:text-emerald-400',
behind: 'text-amber-600 dark:text-amber-400',
current: 'text-emerald-600 dark:text-emerald-400',
current: 'text-orange-600 dark:text-orange-400',
remote: 'text-blue-600 dark:text-blue-400',
stage: 'text-emerald-600 dark:text-emerald-400',
unstage: 'text-rose-600 dark:text-rose-400',
+11 -11
View File
@@ -101,24 +101,24 @@ export function SessionDetail() {
const isMobile = useMobile();
const { keyboardHeight } = useVisualViewport();
const inputBottomOffset = isMobile ? keyboardHeight : 0;
const promptOverlayRef = useRef<HTMLDivElement>(null);
const promptOverlayObserverRef = useRef<ResizeObserver | null>(null);
const [promptOverlayHeight, setPromptOverlayHeight] = useState(112);
useEffect(() => {
const el = promptOverlayRef.current;
if (!el) return;
let mounted = true;
const promptOverlayRef = useCallback((el: HTMLDivElement | null) => {
promptOverlayObserverRef.current?.disconnect();
promptOverlayObserverRef.current = null;
if (!el) {
setPromptOverlayHeight(0);
return;
}
const observer = new ResizeObserver((entries) => {
const entry = entries[0];
if (entry && mounted) {
if (entry) {
setPromptOverlayHeight(entry.contentRect.height);
}
});
observer.observe(el);
return () => {
mounted = false;
observer.disconnect();
};
promptOverlayObserverRef.current = observer;
}, []);
const { data: repo, isLoading: repoLoading } = useQuery({
@@ -528,7 +528,7 @@ export function SessionDetail() {
</div>
<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 + PROMPT_OVERLAY_CLEARANCE_PX }}>
<div key={sessionId} data-testid="session-message-scroll" 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 + PROMPT_OVERLAY_CLEARANCE_PX }}>
{repoLoading || sessionLoading || messagesLoading ? (
<MessageSkeleton />
) : opcodeUrl && sessionDirectory ? (
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { render, screen, fireEvent, waitFor, act } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import { useEffect } from 'react'
@@ -25,6 +25,7 @@ const mocks = vi.hoisted(() => ({
useSidebarAction: vi.fn(),
useSessionStatusForSession: vi.fn(),
PromptInput: vi.fn(),
uiState: { isEditingMessage: false },
}))
vi.mock('@/config', () => ({
@@ -104,7 +105,7 @@ vi.mock('@/hooks/useAutoPlayLastResponse', () => ({
vi.mock('@/stores/uiStateStore', () => ({
useUIState: vi.fn((selector?: (state: Record<string, unknown>) => unknown) =>
typeof selector === 'function'
? selector({ isEditingMessage: false, setActivePromptFileBasePath: vi.fn() })
? selector({ isEditingMessage: mocks.uiState.isEditingMessage, setActivePromptFileBasePath: vi.fn() })
: false
),
}))
@@ -195,11 +196,53 @@ vi.mock('@/components/message/PromptInput', () => ({
PromptInput: mocks.PromptInput,
}))
interface ObservedElement {
element: Element
callback: ResizeObserverCallback
observer: ResizeObserver
}
const observedElements: ObservedElement[] = []
class TestResizeObserver {
constructor(private readonly callback: ResizeObserverCallback) {}
observe(element: Element) {
observedElements.push({ element, callback: this.callback, observer: this as unknown as ResizeObserver })
}
unobserve(element: Element) {
const index = observedElements.findIndex((entry) => entry.observer === (this as unknown) && entry.element === element)
if (index !== -1) observedElements.splice(index, 1)
}
disconnect() {
for (let index = observedElements.length - 1; index >= 0; index -= 1) {
if (observedElements[index].observer === (this as unknown)) observedElements.splice(index, 1)
}
}
}
const reportObservedHeight = (height: number) => {
act(() => {
for (const entry of [...observedElements]) {
if (!entry.element.isConnected) continue
entry.callback(
[{ target: entry.element, contentRect: { height } } as unknown as ResizeObserverEntry],
entry.observer
)
}
})
}
describe('SessionDetail scroll floating button', () => {
let mockScrollToBottom: ReturnType<typeof vi.fn>
beforeEach(() => {
vi.clearAllMocks()
observedElements.length = 0
mocks.uiState.isEditingMessage = false
vi.stubGlobal('ResizeObserver', TestResizeObserver)
mockScrollToBottom = vi.fn()
@@ -270,15 +313,18 @@ describe('SessionDetail scroll floating button', () => {
)
})
return render(
const queryClient = createQueryClient()
const buildTree = () => (
<MemoryRouter initialEntries={['/repos/1/sessions/test-session']}>
<QueryClientProvider client={createQueryClient()}>
<QueryClientProvider client={queryClient}>
<Routes>
<Route path="/repos/:id/sessions/:sessionId" element={<SessionDetail />} />
</Routes>
</QueryClientProvider>
</MemoryRouter>
)
return Object.assign(render(buildTree()), { buildTree })
}
it('passes scroll button state to PromptInput when showScrollButton is true', async () => {
@@ -355,4 +401,26 @@ describe('SessionDetail scroll floating button', () => {
const props = mocks.PromptInput.mock.calls.at(-1)?.[0] as { disabled?: boolean }
expect(props.disabled).not.toBe(true)
})
it('restores message list clearance after the prompt overlay remounts following a message edit', async () => {
const { buildTree, rerender } = renderWith({ mobile: true, showScrollButton: false })
await waitFor(() => expect(screen.getByText('MockedPromptInput')).toBeInTheDocument())
const paddingBottom = () => screen.getByTestId('session-message-scroll').style.paddingBottom
reportObservedHeight(140)
expect(paddingBottom()).toBe('156px')
mocks.uiState.isEditingMessage = true
rerender(buildTree())
await waitFor(() => expect(screen.queryByText('MockedPromptInput')).not.toBeInTheDocument())
expect(paddingBottom()).toBe('16px')
mocks.uiState.isEditingMessage = false
rerender(buildTree())
await waitFor(() => expect(screen.getByText('MockedPromptInput')).toBeInTheDocument())
reportObservedHeight(140)
expect(paddingBottom()).toBe('156px')
})
})