mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
feat(worktree): worktree tabs, server env vars, and multi-directory SSE (#240)
* loop: worktree-tabs-2 completed after 4 iterations * loop: server-env-vars completed after 7 iterations * feat(worktree): add worktree tabs and server env vars settings * refactor(worktree): multi-directory SSE support and workspace chip row * feat(workspace): collapsible workspace manager and sibling filtering * feat(workspace): workspace creation endpoint, refactored workspace manager, and tests * refactor(frontend): unify workspace label and remove dead code - extract shared workspaceLabel helper into api/repos and reuse in WorkspaceManager and RepoDetail directoryLabels - remove unused useSessions hook and subscribeToDirectory subscription - drop redundant frontend workspace dedup now guaranteed by backend - align WorktreeTabs empty-state test with create-workspace button
This commit is contained in:
1 parent
60ed756a0b
commit
b9236f7f20
38 files changed
+2423
-133
No files matched your search
@@ -1251,7 +1251,7 @@ return (
|
||||
directory={directory}
|
||||
>
|
||||
<button
|
||||
className="px-2.5 py-0.5 md:px-3 min-h-[36px] min-w-0 rounded-lg text-xs md:text-sm font-medium border bg-muted border-border text-muted-foreground hover:bg-muted-foreground/10 hover:border-foreground/30 transition-colors cursor-pointer w-full md:w-auto max-w-[130px] md:max-w-[220px] dark:border-white/30 flex flex-col items-start justify-center overflow-hidden"
|
||||
className="px-2.5 py-0.5 md:px-3 min-h-[36px] min-w-0 rounded-lg text-xs md:text-sm font-medium border bg-muted border-border text-muted-foreground hover:bg-muted-foreground/10 hover:border-foreground/30 transition-colors cursor-pointer flex-1 md:flex-initial md:w-auto max-w-[110px] md:max-w-[220px] dark:border-white/30 flex flex-col items-start justify-center overflow-hidden"
|
||||
>
|
||||
<span className="truncate w-full text-left">{displayModelName || 'Select model'}</span>
|
||||
{hasVariants && currentVariant && (
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { DeleteDialog } from '@/components/ui/delete-dialog'
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { GitBranch, Plus, Search, Trash2 } from 'lucide-react'
|
||||
import { workspaceLabel, type RepoSibling } from '@/api/repos'
|
||||
|
||||
interface WorkspaceManagerProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
workspaces: RepoSibling[]
|
||||
onDelete: (workspaceIds: string[]) => void
|
||||
activeWorkspaceDirectory?: string
|
||||
onActiveWorkspaceChange: (directory: string) => void
|
||||
onCreateWorkspace: () => void
|
||||
isDeleting?: boolean
|
||||
}
|
||||
|
||||
export function WorkspaceManager({
|
||||
open,
|
||||
onOpenChange,
|
||||
workspaces,
|
||||
onDelete,
|
||||
activeWorkspaceDirectory,
|
||||
onActiveWorkspaceChange,
|
||||
onCreateWorkspace,
|
||||
isDeleting = false,
|
||||
}: WorkspaceManagerProps) {
|
||||
const [selected, setSelected] = useState<Set<string>>(new Set())
|
||||
const [confirmOpen, setConfirmOpen] = useState(false)
|
||||
const [manageMode, setManageMode] = useState(false)
|
||||
const [searchQuery, setSearchQuery] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setSearchQuery('')
|
||||
}
|
||||
}, [open])
|
||||
|
||||
const filteredWorkspaces = useMemo(() => {
|
||||
const query = searchQuery.trim().toLowerCase()
|
||||
if (!query) return workspaces
|
||||
|
||||
return workspaces.filter((workspace) => {
|
||||
const haystack = [
|
||||
workspaceLabel(workspace),
|
||||
workspace.fullPath,
|
||||
workspace.workspaceName,
|
||||
workspace.workspaceId,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' ')
|
||||
.toLowerCase()
|
||||
return haystack.includes(query)
|
||||
})
|
||||
}, [searchQuery, workspaces])
|
||||
|
||||
const selectableIds = useMemo(
|
||||
() => filteredWorkspaces.map((workspace) => workspace.workspaceId).filter((id): id is string => !!id),
|
||||
[filteredWorkspaces],
|
||||
)
|
||||
|
||||
const allSelected = selectableIds.length > 0 && selectableIds.every((id) => selected.has(id))
|
||||
const selectedCount = selected.size
|
||||
|
||||
const toggle = (workspaceId: string, checked: boolean) => {
|
||||
setSelected((prev) => {
|
||||
const next = new Set(prev)
|
||||
if (checked) {
|
||||
next.add(workspaceId)
|
||||
} else {
|
||||
next.delete(workspaceId)
|
||||
}
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
const toggleAll = () => {
|
||||
setSelected(allSelected ? new Set() : new Set(selectableIds))
|
||||
}
|
||||
|
||||
const handleConfirm = () => {
|
||||
onDelete(Array.from(selected))
|
||||
setSelected(new Set())
|
||||
setManageMode(false)
|
||||
setConfirmOpen(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent mobileFullscreen className="flex flex-col gap-0 overflow-hidden p-0 sm:max-h-[85vh] sm:max-w-[560px]">
|
||||
<DialogHeader className="border-b border-border px-4 py-4">
|
||||
<DialogTitle>Workspaces</DialogTitle>
|
||||
<DialogDescription>Choose where new sessions should start.</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-3 p-4">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
{manageMode ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox checked={allSelected} onCheckedChange={toggleAll} aria-label="Select all workspaces" />
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{selectedCount > 0 ? `${selectedCount} selected` : 'Select all'}
|
||||
</span>
|
||||
</div>
|
||||
) : (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{activeWorkspaceDirectory ? 'Selected workspace' : 'Select a workspace'}
|
||||
</span>
|
||||
)}
|
||||
<div className="flex shrink-0 items-center gap-1">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7"
|
||||
onClick={() => {
|
||||
onOpenChange(false)
|
||||
onCreateWorkspace()
|
||||
}}
|
||||
>
|
||||
<Plus className="h-3.5 w-3.5 mr-1" />
|
||||
New
|
||||
</Button>
|
||||
{manageMode ? (
|
||||
<>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 text-destructive hover:text-destructive"
|
||||
disabled={selectedCount === 0 || isDeleting}
|
||||
onClick={() => setConfirmOpen(true)}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5 mr-1" />
|
||||
Delete
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7"
|
||||
onClick={() => {
|
||||
setSelected(new Set())
|
||||
setManageMode(false)
|
||||
}}
|
||||
>
|
||||
Done
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7"
|
||||
onClick={() => setManageMode(true)}
|
||||
>
|
||||
Manage
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<input
|
||||
value={searchQuery}
|
||||
onChange={(event) => setSearchQuery(event.target.value)}
|
||||
placeholder="Search workspaces..."
|
||||
className="h-10 w-full rounded-md border border-border bg-background pl-9 pr-3 text-sm outline-none placeholder:text-muted-foreground focus:border-primary"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-1 overflow-y-auto pr-1">
|
||||
{filteredWorkspaces.map((workspace) => {
|
||||
if (!workspace.workspaceId) return null
|
||||
const workspaceId = workspace.workspaceId
|
||||
const isChecked = selected.has(workspaceId)
|
||||
const isActive = !!workspace.fullPath && workspace.fullPath === activeWorkspaceDirectory
|
||||
const label = workspaceLabel(workspace)
|
||||
const rowClassName = isActive
|
||||
? 'border-purple-500/50 bg-purple-500/10 text-foreground'
|
||||
: 'border-border bg-muted/30 hover:bg-muted/50'
|
||||
if (!manageMode) {
|
||||
return (
|
||||
<button
|
||||
key={workspaceId}
|
||||
type="button"
|
||||
disabled={!workspace.fullPath}
|
||||
onClick={() => {
|
||||
if (!workspace.fullPath) return
|
||||
onActiveWorkspaceChange(workspace.fullPath)
|
||||
onOpenChange(false)
|
||||
}}
|
||||
className={`flex min-h-11 items-center gap-2 rounded-md border px-3 py-2 text-sm text-left ${rowClassName}`}
|
||||
aria-pressed={isActive}
|
||||
>
|
||||
<GitBranch className="h-3.5 w-3.5 text-purple-400 flex-shrink-0" />
|
||||
<span className="truncate">{label}</span>
|
||||
{isActive && <span className="text-xs text-purple-400">Selected</span>}
|
||||
{workspace.fullPath && (
|
||||
<span className="ml-auto hidden truncate text-xs text-muted-foreground md:block md:max-w-[45%]">
|
||||
{workspace.fullPath}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div
|
||||
key={workspaceId}
|
||||
className="flex min-h-11 items-center gap-2 rounded-md border border-border bg-muted/30 px-3 py-2 text-sm hover:bg-muted/50"
|
||||
>
|
||||
<Checkbox
|
||||
checked={isChecked}
|
||||
disabled={isDeleting}
|
||||
onCheckedChange={(checked) => toggle(workspaceId, checked === true)}
|
||||
aria-label={`Select workspace ${label}`}
|
||||
/>
|
||||
<GitBranch className="h-3.5 w-3.5 text-purple-400 flex-shrink-0" />
|
||||
<span className="truncate">{label}</span>
|
||||
{workspace.fullPath && (
|
||||
<span className="ml-auto hidden truncate text-xs text-muted-foreground md:block md:max-w-[45%]">
|
||||
{workspace.fullPath}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
{filteredWorkspaces.length === 0 && (
|
||||
<div className="rounded-md border border-dashed border-border px-3 py-6 text-center text-sm text-muted-foreground">
|
||||
No workspaces found
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<DeleteDialog
|
||||
open={confirmOpen}
|
||||
onOpenChange={setConfirmOpen}
|
||||
onConfirm={handleConfirm}
|
||||
onCancel={() => setConfirmOpen(false)}
|
||||
title={selectedCount === 1 ? 'Delete Workspace' : 'Delete Workspaces'}
|
||||
description={
|
||||
selectedCount === 1
|
||||
? 'Are you sure you want to delete this OpenCode workspace? This removes the workspace and its sessions in OpenCode.'
|
||||
: `Are you sure you want to delete ${selectedCount} OpenCode workspaces? This removes the workspaces and their sessions in OpenCode.`
|
||||
}
|
||||
isDeleting={isDeleting}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { WorktreeTabs } from './WorktreeTabs'
|
||||
import type { RepoSibling } from '@/api/repos'
|
||||
|
||||
const makeWorkspaceSibling = (workspaceId: string, branch: string): RepoSibling => ({
|
||||
id: -1,
|
||||
localPath: branch,
|
||||
fullPath: `/w/${branch}`,
|
||||
defaultBranch: 'main',
|
||||
cloneStatus: 'ready',
|
||||
clonedAt: 0,
|
||||
isWorktree: true,
|
||||
currentBranch: branch,
|
||||
branch,
|
||||
workspaceId,
|
||||
workspaceName: branch,
|
||||
})
|
||||
|
||||
const onValueChange = vi.fn()
|
||||
|
||||
beforeEach(() => {
|
||||
onValueChange.mockReset()
|
||||
})
|
||||
|
||||
describe('WorktreeTabs', () => {
|
||||
it('renders the repo tab with a create-workspace button when there are no workspaces', () => {
|
||||
render(
|
||||
<WorktreeTabs workspaces={[]} value="repo" onValueChange={onValueChange} baseLabel="main" />
|
||||
)
|
||||
expect(screen.getAllByRole('tab')).toHaveLength(1)
|
||||
expect(screen.getByText('main')).toBeInTheDocument()
|
||||
expect(screen.getByText('Workspace')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders Repo and Workspaces tabs when at least one workspace exists', () => {
|
||||
const workspaces = [makeWorkspaceSibling('wrk_a', 'feature-a')]
|
||||
render(<WorktreeTabs workspaces={workspaces} value="repo" onValueChange={onValueChange} baseLabel="main" />)
|
||||
|
||||
const tabs = screen.getAllByRole('tab')
|
||||
expect(tabs).toHaveLength(2)
|
||||
expect(screen.getByText('main')).toBeInTheDocument()
|
||||
expect(screen.getByText('Workspaces')).toBeInTheDocument()
|
||||
expect(screen.getByText('(1)')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('marks the active tab', () => {
|
||||
const workspaces = [makeWorkspaceSibling('wrk_a', 'feature-a')]
|
||||
render(<WorktreeTabs workspaces={workspaces} value="workspaces" onValueChange={onValueChange} baseLabel="main" />)
|
||||
|
||||
const tabs = screen.getAllByRole('tab')
|
||||
expect(tabs[0]).toHaveAttribute('data-state', 'inactive')
|
||||
expect(tabs[1]).toHaveAttribute('data-state', 'active')
|
||||
})
|
||||
|
||||
it('calls onValueChange when a different tab is clicked', async () => {
|
||||
const workspaces = [makeWorkspaceSibling('wrk_a', 'feature-a')]
|
||||
render(<WorktreeTabs workspaces={workspaces} value="repo" onValueChange={onValueChange} baseLabel="main" />)
|
||||
|
||||
await userEvent.click(screen.getAllByRole('tab')[1])
|
||||
expect(onValueChange).toHaveBeenCalledWith('workspaces')
|
||||
})
|
||||
|
||||
it('shows the workspace count in the workspaces tab', () => {
|
||||
const workspaces = [
|
||||
makeWorkspaceSibling('wrk_a', 'feature-a'),
|
||||
makeWorkspaceSibling('wrk_b', 'feature-b'),
|
||||
makeWorkspaceSibling('wrk_c', 'feature-c'),
|
||||
]
|
||||
render(<WorktreeTabs workspaces={workspaces} value="repo" onValueChange={onValueChange} baseLabel="main" />)
|
||||
|
||||
expect(screen.getByText('(3)')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,59 @@
|
||||
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||
import { GitBranch, Layers, Plus } from 'lucide-react'
|
||||
import type { RepoSibling } from '@/api/repos'
|
||||
import type { WorktreeTabValue } from '@/hooks/useWorktreeTab'
|
||||
|
||||
interface WorktreeTabsProps {
|
||||
workspaces: RepoSibling[]
|
||||
value: WorktreeTabValue
|
||||
onValueChange: (value: WorktreeTabValue) => void
|
||||
baseLabel: string
|
||||
activeWorkspaceLabel?: string
|
||||
onCreateWorkspace?: () => void
|
||||
onWorkspaceMenu?: () => void
|
||||
}
|
||||
|
||||
export function WorktreeTabs({
|
||||
workspaces,
|
||||
value,
|
||||
onValueChange,
|
||||
baseLabel,
|
||||
activeWorkspaceLabel,
|
||||
onCreateWorkspace,
|
||||
onWorkspaceMenu,
|
||||
}: WorktreeTabsProps) {
|
||||
const hasWorkspaces = workspaces.length > 0
|
||||
const workspaceLabel = value === 'workspaces' && activeWorkspaceLabel ? activeWorkspaceLabel : 'Workspaces'
|
||||
|
||||
return (
|
||||
<div className="px-4 pt-2 flex-shrink-0">
|
||||
<Tabs value={value} onValueChange={(next) => onValueChange(next as WorktreeTabValue)} className="min-w-0">
|
||||
<TabsList className="w-full justify-start overflow-hidden">
|
||||
<TabsTrigger value="repo" className="min-w-0 flex-1 gap-1.5 px-2 sm:flex-none sm:px-3">
|
||||
<GitBranch className="h-3 w-3 shrink-0" />
|
||||
<span className="min-w-0 truncate">{baseLabel}</span>
|
||||
</TabsTrigger>
|
||||
{hasWorkspaces ? (
|
||||
<>
|
||||
<TabsTrigger value="workspaces" className="min-w-0 flex-1 gap-1.5 px-2 sm:flex-none sm:px-3" onClick={onWorkspaceMenu}>
|
||||
<Layers className="h-3 w-3 shrink-0 text-purple-400" />
|
||||
<span className="min-w-0 truncate">{workspaceLabel}</span>
|
||||
<span className="shrink-0 text-xs text-muted-foreground">({workspaces.length})</span>
|
||||
</TabsTrigger>
|
||||
</>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onCreateWorkspace}
|
||||
className="inline-flex h-8 min-w-0 flex-1 items-center justify-center gap-1.5 rounded-md px-2 text-sm font-medium text-muted-foreground hover:bg-background hover:text-foreground sm:flex-none sm:px-3"
|
||||
>
|
||||
<Layers className="h-3 w-3 shrink-0 text-purple-400" />
|
||||
<span className="min-w-0 truncate">Workspace</span>
|
||||
<Plus className="h-3.5 w-3.5 shrink-0" />
|
||||
</button>
|
||||
)}
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -12,6 +12,7 @@ interface SessionCardProps {
|
||||
isSelected: boolean;
|
||||
isActive: boolean;
|
||||
manageMode: boolean;
|
||||
workspaceLabel?: string;
|
||||
onSelect: (sessionID: string) => void;
|
||||
onToggleSelection: (selected: boolean) => void;
|
||||
onDelete: (e: React.MouseEvent<HTMLButtonElement>) => void;
|
||||
@@ -22,6 +23,7 @@ export const SessionCard = ({
|
||||
isSelected,
|
||||
isActive,
|
||||
manageMode,
|
||||
workspaceLabel,
|
||||
onSelect,
|
||||
onToggleSelection,
|
||||
onDelete,
|
||||
@@ -107,6 +109,9 @@ export const SessionCard = ({
|
||||
addSuffix: true,
|
||||
})}
|
||||
</span>
|
||||
{workspaceLabel ? (
|
||||
<span className="text-purple-400 truncate max-w-[140px]">{workspaceLabel}</span>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -122,6 +127,9 @@ export const SessionCard = ({
|
||||
addSuffix: true,
|
||||
})}
|
||||
</span>
|
||||
{workspaceLabel ? (
|
||||
<span className="text-purple-400 truncate max-w-[120px]">{workspaceLabel}</span>
|
||||
) : null}
|
||||
<SessionStatusIndicator sessionID={session.id} size="sm" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { render, screen, waitFor, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { SessionList } from './SessionList'
|
||||
|
||||
const { createSessionMock, deleteSessionMock, sessionsData, createSessionState } = vi.hoisted(() => ({
|
||||
createSessionMock: vi.fn(),
|
||||
deleteSessionMock: vi.fn(),
|
||||
sessionsData: [] as Array<{ id: string; title: string; directory: string; workspaceID?: string; time: { updated: number } }>,
|
||||
createSessionState: { directory: undefined as string | undefined },
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useOpenCode', () => ({
|
||||
useSessionsAcrossDirectories: () => ({
|
||||
data: sessionsData,
|
||||
isLoading: false,
|
||||
}),
|
||||
useCreateSession: (_opcodeUrl: string, directory?: string) => {
|
||||
createSessionState.directory = directory
|
||||
return { mutate: createSessionMock }
|
||||
},
|
||||
useDeleteSession: () => ({ mutateAsync: deleteSessionMock, isPending: false }),
|
||||
}))
|
||||
|
||||
describe('SessionList', () => {
|
||||
beforeEach(() => {
|
||||
sessionsData.splice(0, sessionsData.length,
|
||||
{ id: 'ses_same', title: 'audit: mic-warmup 1/2 #2', directory: '/w/a', workspaceID: 'wrk_a', time: { updated: Date.now() } },
|
||||
{ id: 'ses_same', title: 'audit: mic-warmup 1/2 #2', directory: '/w/b', workspaceID: 'wrk_b', time: { updated: Date.now() } },
|
||||
{ id: 'ses_same', title: 'audit: mic-warmup 1/2 #2', directory: '/w/c', workspaceID: 'wrk_c', time: { updated: Date.now() } },
|
||||
)
|
||||
createSessionMock.mockReset()
|
||||
createSessionState.directory = undefined
|
||||
deleteSessionMock.mockReset()
|
||||
deleteSessionMock.mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('selects duplicate session IDs independently by workspace directory', async () => {
|
||||
const user = userEvent.setup()
|
||||
|
||||
render(
|
||||
<SessionList
|
||||
opcodeUrl="/api/opencode"
|
||||
directories={['/w/a', '/w/b', '/w/c']}
|
||||
onSelectSession={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Manage sessions' }))
|
||||
await user.click(screen.getByRole('button', { name: 'Select All' }))
|
||||
|
||||
expect(screen.getByText('3 selected')).toBeTruthy()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Delete' }))
|
||||
|
||||
const dialog = screen.getByRole('dialog', { name: 'Delete Sessions' })
|
||||
expect(dialog).toBeTruthy()
|
||||
expect(screen.getByText('3')).toBeTruthy()
|
||||
|
||||
await user.click(within(dialog).getByRole('button', { name: 'Delete' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(deleteSessionMock).toHaveBeenCalledWith([
|
||||
{ id: 'ses_same', directory: '/w/a', workspaceID: 'wrk_a' },
|
||||
{ id: 'ses_same', directory: '/w/b', workspaceID: 'wrk_b' },
|
||||
{ id: 'ses_same', directory: '/w/c', workspaceID: 'wrk_c' },
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
it('deduplicates repeated session records from the same workspace directory', async () => {
|
||||
const user = userEvent.setup()
|
||||
sessionsData.splice(0, sessionsData.length,
|
||||
{ id: 'ses_same', title: 'audit: mic-warmup 1/2 #2', directory: '/w/a', time: { updated: Date.now() } },
|
||||
{ id: 'ses_same', title: 'audit: mic-warmup 1/2 #2', directory: '/w/a', time: { updated: Date.now() } },
|
||||
{ id: 'ses_same', title: 'audit: mic-warmup 1/2 #2', directory: '/w/a', time: { updated: Date.now() } },
|
||||
)
|
||||
|
||||
render(
|
||||
<SessionList
|
||||
opcodeUrl="/api/opencode"
|
||||
directories={['/w/a', '/w/a', '/w/a']}
|
||||
onSelectSession={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getAllByText('audit: mic-warmup 1/2 #2')).toHaveLength(1)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Manage sessions' }))
|
||||
await user.click(screen.getByRole('button', { name: 'Select All' }))
|
||||
|
||||
expect(screen.getByText('1 selected')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('creates sessions in the explicit create directory', async () => {
|
||||
const user = userEvent.setup()
|
||||
sessionsData.splice(0, sessionsData.length)
|
||||
|
||||
render(
|
||||
<SessionList
|
||||
opcodeUrl="/api/opencode"
|
||||
directories={['/w/a', '/w/b']}
|
||||
createDirectory="/w/b"
|
||||
onSelectSession={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
await user.click(screen.getByText('No sessions yet'))
|
||||
|
||||
expect(createSessionState.directory).toBe('/w/b')
|
||||
expect(createSessionMock).toHaveBeenCalledWith({ agent: undefined })
|
||||
})
|
||||
})
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useState, useMemo } from "react";
|
||||
import { useSessions, useDeleteSession, useCreateSession } from "@/hooks/useOpenCode";
|
||||
import { useCallback, useState, useMemo } from "react";
|
||||
import { useSessionsAcrossDirectories, useDeleteSession, useCreateSession } from "@/hooks/useOpenCode";
|
||||
import type { DeleteSessionTarget } from "@/hooks/useOpenCode";
|
||||
import { DeleteSessionDialog } from "./DeleteSessionDialog";
|
||||
import { SessionCard } from "./SessionCard";
|
||||
import { Card } from "@/components/ui/card";
|
||||
@@ -10,6 +11,9 @@ import { Search, Trash2, Pencil, X } from "lucide-react";
|
||||
interface SessionListProps {
|
||||
opcodeUrl: string;
|
||||
directory?: string;
|
||||
directories?: string[];
|
||||
createDirectory?: string;
|
||||
directoryLabels?: Record<string, string>;
|
||||
activeSessionID?: string;
|
||||
onSelectSession: (sessionID: string) => void;
|
||||
}
|
||||
@@ -17,16 +21,29 @@ interface SessionListProps {
|
||||
export const SessionList = ({
|
||||
opcodeUrl,
|
||||
directory,
|
||||
directories,
|
||||
createDirectory,
|
||||
directoryLabels,
|
||||
activeSessionID,
|
||||
onSelectSession,
|
||||
}: SessionListProps) => {
|
||||
const { data: sessions, isLoading } = useSessions(opcodeUrl, directory);
|
||||
const deleteSession = useDeleteSession(opcodeUrl, directory);
|
||||
const createSession = useCreateSession(opcodeUrl, directory, (newSession) => {
|
||||
const directoriesList = useMemo(() => {
|
||||
const source = directories && directories.length > 0 ? directories : directory ? [directory] : [];
|
||||
return Array.from(new Set(source.filter(Boolean)));
|
||||
}, [directory, directories]);
|
||||
const directorySet = useMemo(() => new Set(directoriesList), [directoriesList]);
|
||||
const primaryDirectory = directoriesList[0];
|
||||
const sessionCreateDirectory = createDirectory ?? primaryDirectory;
|
||||
const getSessionSelectionKey = useCallback((session: { id: string; directory?: string }) =>
|
||||
`${session.directory ?? primaryDirectory ?? ''}:${session.id}`,
|
||||
[primaryDirectory]);
|
||||
const { data: sessions, isLoading } = useSessionsAcrossDirectories(opcodeUrl, directoriesList);
|
||||
const deleteSession = useDeleteSession(opcodeUrl, directoriesList);
|
||||
const createSession = useCreateSession(opcodeUrl, sessionCreateDirectory, (newSession) => {
|
||||
onSelectSession(newSession.id);
|
||||
});
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [sessionToDelete, setSessionToDelete] = useState<string | string[] | null>(null);
|
||||
const [sessionToDelete, setSessionToDelete] = useState<DeleteSessionTarget | DeleteSessionTarget[] | null>(null);
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [selectedSessions, setSelectedSessions] = useState<Set<string>>(new Set());
|
||||
const [manageMode, setManageMode] = useState(false);
|
||||
@@ -36,7 +53,7 @@ export const SessionList = ({
|
||||
|
||||
let filtered = sessions.filter((session) => {
|
||||
if (session.parentID) return false;
|
||||
if (directory && session.directory && session.directory !== directory) return false;
|
||||
if (directorySet.size > 0 && session.directory && !directorySet.has(session.directory)) return false;
|
||||
return true;
|
||||
});
|
||||
|
||||
@@ -47,8 +64,16 @@ export const SessionList = ({
|
||||
);
|
||||
}
|
||||
|
||||
return filtered.sort((a, b) => b.time.updated - a.time.updated);
|
||||
}, [sessions, searchQuery, directory]);
|
||||
const uniqueSessions = new Map<string, (typeof filtered)[number]>();
|
||||
filtered.forEach((session) => {
|
||||
const key = getSessionSelectionKey(session);
|
||||
if (!uniqueSessions.has(key)) {
|
||||
uniqueSessions.set(key, session);
|
||||
}
|
||||
});
|
||||
|
||||
return Array.from(uniqueSessions.values()).sort((a, b) => b.time.updated - a.time.updated);
|
||||
}, [sessions, searchQuery, directorySet, getSessionSelectionKey]);
|
||||
|
||||
const todaySessions = useMemo(() => {
|
||||
const today = new Date();
|
||||
@@ -84,9 +109,20 @@ export const SessionList = ({
|
||||
);
|
||||
}
|
||||
|
||||
const handleDelete = (sessionId: string, e: React.MouseEvent<HTMLButtonElement>) => {
|
||||
const getDeleteTarget = (session: { id: string; directory?: string; workspaceID?: string }): DeleteSessionTarget => {
|
||||
const target: Extract<DeleteSessionTarget, { id: string }> = {
|
||||
id: session.id,
|
||||
directory: session.directory ?? primaryDirectory,
|
||||
};
|
||||
if (session.workspaceID) {
|
||||
target.workspaceID = session.workspaceID;
|
||||
}
|
||||
return target;
|
||||
};
|
||||
|
||||
const handleDelete = (session: { id: string; directory?: string; workspaceID?: string }, e: React.MouseEvent<HTMLButtonElement>) => {
|
||||
e.stopPropagation();
|
||||
setSessionToDelete(sessionId);
|
||||
setSessionToDelete(getDeleteTarget(session));
|
||||
setDeleteDialogOpen(true);
|
||||
};
|
||||
|
||||
@@ -107,31 +143,36 @@ export const SessionList = ({
|
||||
setManageMode(false);
|
||||
};
|
||||
|
||||
const toggleSessionSelection = (sessionId: string, selected: boolean) => {
|
||||
const toggleSessionSelection = (session: { id: string; directory?: string }, selected: boolean) => {
|
||||
const selectionKey = getSessionSelectionKey(session);
|
||||
const newSelected = new Set(selectedSessions);
|
||||
if (selected) {
|
||||
newSelected.add(sessionId);
|
||||
newSelected.add(selectionKey);
|
||||
} else {
|
||||
newSelected.delete(sessionId);
|
||||
newSelected.delete(selectionKey);
|
||||
}
|
||||
setSelectedSessions(newSelected);
|
||||
};
|
||||
|
||||
const allVisibleSelected =
|
||||
filteredSessions.length > 0 &&
|
||||
filteredSessions.every((s) => selectedSessions.has(s.id));
|
||||
filteredSessions.every((session) => selectedSessions.has(getSessionSelectionKey(session)));
|
||||
|
||||
const toggleSelectAll = () => {
|
||||
if (allVisibleSelected) {
|
||||
setSelectedSessions(new Set());
|
||||
} else {
|
||||
setSelectedSessions(new Set(filteredSessions.map((s) => s.id)));
|
||||
setSelectedSessions(new Set(filteredSessions.map(getSessionSelectionKey)));
|
||||
}
|
||||
};
|
||||
|
||||
const handleBulkDelete = () => {
|
||||
if (selectedSessions.size > 0) {
|
||||
setSessionToDelete(Array.from(selectedSessions));
|
||||
const selectedTargets = filteredSessions
|
||||
.filter((session) => selectedSessions.has(getSessionSelectionKey(session)))
|
||||
.map(getDeleteTarget);
|
||||
if (selectedTargets.length === 0) return;
|
||||
setSessionToDelete(selectedTargets);
|
||||
setDeleteDialogOpen(true);
|
||||
}
|
||||
};
|
||||
@@ -183,6 +224,7 @@ export const SessionList = ({
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
aria-label="Manage sessions"
|
||||
className="shrink-0 size-9"
|
||||
onClick={() => {
|
||||
setManageMode(true);
|
||||
@@ -209,14 +251,15 @@ export const SessionList = ({
|
||||
</div>
|
||||
{todaySessions.map((session) => (
|
||||
<SessionCard
|
||||
key={session.id}
|
||||
key={getSessionSelectionKey(session)}
|
||||
session={session}
|
||||
isSelected={selectedSessions.has(session.id)}
|
||||
isSelected={selectedSessions.has(getSessionSelectionKey(session))}
|
||||
isActive={activeSessionID === session.id}
|
||||
manageMode={manageMode}
|
||||
workspaceLabel={session.directory ? directoryLabels?.[session.directory] : undefined}
|
||||
onSelect={onSelectSession}
|
||||
onToggleSelection={(selected) => toggleSessionSelection(session.id, selected)}
|
||||
onDelete={(e) => handleDelete(session.id, e)}
|
||||
onToggleSelection={(selected) => toggleSessionSelection(session, selected)}
|
||||
onDelete={(e) => handleDelete(session, e)}
|
||||
/>
|
||||
))}
|
||||
</>
|
||||
@@ -227,14 +270,15 @@ export const SessionList = ({
|
||||
)}
|
||||
{olderSessions.map((session) => (
|
||||
<SessionCard
|
||||
key={session.id}
|
||||
key={getSessionSelectionKey(session)}
|
||||
session={session}
|
||||
isSelected={selectedSessions.has(session.id)}
|
||||
isSelected={selectedSessions.has(getSessionSelectionKey(session))}
|
||||
isActive={activeSessionID === session.id}
|
||||
manageMode={manageMode}
|
||||
workspaceLabel={session.directory ? directoryLabels?.[session.directory] : undefined}
|
||||
onSelect={onSelectSession}
|
||||
onToggleSelection={(selected) => toggleSessionSelection(session.id, selected)}
|
||||
onDelete={(e) => handleDelete(session.id, e)}
|
||||
onToggleSelection={(selected) => toggleSessionSelection(session, selected)}
|
||||
onDelete={(e) => handleDelete(session, e)}
|
||||
/>
|
||||
))}
|
||||
</>
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
import { useState, useEffect, useMemo } from 'react'
|
||||
import { useSettings } from '@/hooks/useSettings'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||
import { ChevronDown, Plus, Trash2, RotateCcw } from 'lucide-react'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { BLOCKED_SERVER_ENV_KEYS, DEFAULT_SERVER_ENV_VARS } from '@/api/types/settings'
|
||||
|
||||
interface EnvVar {
|
||||
key: string
|
||||
value: string
|
||||
}
|
||||
|
||||
export function ServerEnvVarsSettings() {
|
||||
const { preferences, updateSettingsAsync, isUpdating } = useSettings()
|
||||
const [isOpen, setIsOpen] = useState(false)
|
||||
const [envVars, setEnvVars] = useState<EnvVar[]>([])
|
||||
const [disabledDefaultKeys, setDisabledDefaultKeys] = useState<string[]>([])
|
||||
const [needsRestart, setNeedsRestart] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
setEnvVars(preferences?.serverEnvVars ?? [])
|
||||
setDisabledDefaultKeys(preferences?.disabledDefaultServerEnvVars ?? [])
|
||||
}, [preferences?.disabledDefaultServerEnvVars, preferences?.serverEnvVars])
|
||||
|
||||
const blockedSet = useMemo(() => new Set<string>(BLOCKED_SERVER_ENV_KEYS), [])
|
||||
|
||||
const blockedKeys = useMemo(
|
||||
() => envVars
|
||||
.map((envVar) => envVar.key.trim())
|
||||
.filter((key) => key.length > 0 && blockedSet.has(key)),
|
||||
[envVars, blockedSet],
|
||||
)
|
||||
|
||||
const disabledDefaultSet = useMemo(() => new Set(disabledDefaultKeys), [disabledDefaultKeys])
|
||||
const enabledDefaultCount = DEFAULT_SERVER_ENV_VARS.filter((envVar) => !disabledDefaultSet.has(envVar.key)).length
|
||||
|
||||
const handleDefaultToggle = (key: string, enabled: boolean) => {
|
||||
setDisabledDefaultKeys((prev) => enabled
|
||||
? prev.filter((disabledKey) => disabledKey !== key)
|
||||
: [...new Set([...prev, key])])
|
||||
}
|
||||
|
||||
const handleAdd = () => {
|
||||
setEnvVars((prev) => [...prev, { key: '', value: '' }])
|
||||
}
|
||||
|
||||
const handleRemove = (index: number) => {
|
||||
setEnvVars((prev) => prev.filter((_, i) => i !== index))
|
||||
}
|
||||
|
||||
const handleChange = (index: number, field: keyof EnvVar, value: string) => {
|
||||
setEnvVars((prev) => prev.map((envVar, i) => (i === index ? { ...envVar, [field]: value } : envVar)))
|
||||
}
|
||||
|
||||
const handleSave = async () => {
|
||||
if (blockedKeys.length > 0) return
|
||||
|
||||
const filtered = envVars.filter((envVar) => envVar.key.trim() !== '')
|
||||
|
||||
try {
|
||||
await updateSettingsAsync({
|
||||
serverEnvVars: filtered,
|
||||
disabledDefaultServerEnvVars: disabledDefaultKeys,
|
||||
})
|
||||
setNeedsRestart(true)
|
||||
showToast.success('Environment variables saved')
|
||||
} catch {
|
||||
showToast.error('Failed to save environment variables')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border bg-card overflow-hidden">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsOpen((value) => !value)}
|
||||
className="w-full px-4 py-3 flex items-center justify-between hover:bg-muted/50 transition-colors"
|
||||
>
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<h3 className="text-sm font-semibold truncate">Server Environment Variables</h3>
|
||||
<Badge variant="outline" className="text-xs">
|
||||
{enabledDefaultCount + (preferences?.serverEnvVars ?? []).length}
|
||||
</Badge>
|
||||
</div>
|
||||
<ChevronDown className={`h-4 w-4 transition-transform ${isOpen ? 'rotate-180' : ''}`} />
|
||||
</button>
|
||||
|
||||
{isOpen && (
|
||||
<div className="px-4 pb-4 pt-1 border-t border-border space-y-3">
|
||||
{needsRestart && (
|
||||
<Alert>
|
||||
<RotateCcw className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
Restart the OpenCode server to apply environment variable changes.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="rounded-md border bg-muted/20 p-3 space-y-2">
|
||||
<div className="text-xs font-medium text-muted-foreground">Default variables</div>
|
||||
{DEFAULT_SERVER_ENV_VARS.map((envVar) => {
|
||||
const isEnabled = !disabledDefaultSet.has(envVar.key)
|
||||
|
||||
return (
|
||||
<div key={envVar.key} className="flex items-center justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<div className="font-mono text-xs truncate">{envVar.key}={envVar.value}</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Required for OpenCode workspace listing and deletion.
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={isEnabled}
|
||||
onCheckedChange={(checked) => handleDefaultToggle(envVar.key, checked)}
|
||||
aria-label={`Toggle ${envVar.key}`}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{envVars.map((envVar, index) => {
|
||||
const isBlocked = blockedSet.has(envVar.key.trim())
|
||||
|
||||
return (
|
||||
<div key={index} className="flex gap-2 items-center">
|
||||
<div className="flex-1 flex gap-2">
|
||||
<Input
|
||||
value={envVar.key}
|
||||
onChange={(event) => handleChange(index, 'key', event.target.value)}
|
||||
placeholder="VARIABLE_NAME"
|
||||
className={`font-mono ${isBlocked ? 'border-destructive' : ''}`}
|
||||
/>
|
||||
<Input
|
||||
value={envVar.value}
|
||||
onChange={(event) => handleChange(index, 'value', event.target.value)}
|
||||
placeholder="value"
|
||||
className="font-mono"
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => handleRemove(index)}
|
||||
className="shrink-0"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
{blockedKeys.length > 0 && (
|
||||
<p className="text-xs text-destructive">
|
||||
Reserved keys cannot be overridden: {blockedKeys.join(', ')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 pt-1">
|
||||
<Button type="button" variant="outline" size="sm" onClick={handleAdd}>
|
||||
<Plus className="h-3 w-3 mr-1" />
|
||||
Add variable
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
onClick={handleSave}
|
||||
disabled={isUpdating || blockedKeys.length > 0}
|
||||
>
|
||||
{isUpdating ? 'Saving...' : 'Save'}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Variables are injected into the OpenCode server process at startup.
|
||||
Changes require a server restart.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { KeyboardShortcuts } from '@/components/settings/KeyboardShortcuts'
|
||||
import { OpenCodeConfigManager } from '@/components/settings/OpenCodeConfigManager'
|
||||
import { OpenCodeServerAuthSettings } from '@/components/settings/OpenCodeServerAuthSettings'
|
||||
import { ManagerTokenSettings } from '@/components/settings/ManagerTokenSettings'
|
||||
import { ServerEnvVarsSettings } from '@/components/settings/ServerEnvVarsSettings'
|
||||
import { ServerHealthStatus } from '@/components/settings/ServerHealthStatus'
|
||||
import { ProviderSettings } from '@/components/settings/ProviderSettings'
|
||||
import { AccountSettings } from '@/components/settings/AccountSettings'
|
||||
@@ -163,6 +164,7 @@ export function SettingsDialog() {
|
||||
<OpenCodeServerAuthSettings isOpen={authSectionsOpen} onToggle={toggleAuthSections} />
|
||||
<ManagerTokenSettings isOpen={authSectionsOpen} onToggle={toggleAuthSections} />
|
||||
</div>
|
||||
<ServerEnvVarsSettings />
|
||||
<OpenCodeConfigManager hideHealthStatus />
|
||||
</div>
|
||||
</TabsContent>
|
||||
@@ -228,14 +230,15 @@ export function SettingsDialog() {
|
||||
{mobileView === 'voice' && <div key="voice"><VoiceSettings /></div>}
|
||||
{mobileView === 'git' && <div key="git"><GitSettings /></div>}
|
||||
{mobileView === 'shortcuts' && <div key="shortcuts"><KeyboardShortcuts /></div>}
|
||||
{mobileView === 'opencode' && (
|
||||
<div key="opencode" className="space-y-6">
|
||||
<ServerHealthStatus />
|
||||
<OpenCodeServerAuthSettings />
|
||||
<ManagerTokenSettings />
|
||||
<OpenCodeConfigManager hideHealthStatus />
|
||||
</div>
|
||||
)}
|
||||
{mobileView === 'opencode' && (
|
||||
<div key="opencode" className="space-y-6">
|
||||
<ServerHealthStatus />
|
||||
<OpenCodeServerAuthSettings />
|
||||
<ManagerTokenSettings />
|
||||
<ServerEnvVarsSettings />
|
||||
<OpenCodeConfigManager hideHealthStatus />
|
||||
</div>
|
||||
)}
|
||||
{mobileView === 'providers' && <div key="providers"><ProviderSettings /></div>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Reference in new issue
Block a user