feat(ui): dock repo and session tools in a desktop side panel

Add a docked desktop tool panel with an icon rail, driven by the shared panel URL param, and keep the mobile dialogs and drawers. Extract dialog bodies into reusable content components, rename the walkthrough dialog to a sheet, and make walkthrough generation asynchronous with client polling.
This commit is contained in:
Chris Scott committed 2026-10-07 23:58:56 -04:00
1 parent bdbcc60716
commit 485ab940aa
49 files changed
+2631 -1753

No files matched your search

@@ -3,7 +3,7 @@ import { act, renderHook, waitFor } from '@testing-library/react'
import type { ReactNode } from 'react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { changeWalkthroughQueryKey, useChangeWalkthrough, useGenerateChangeWalkthrough } from './useChangeWalkthrough'
import type { ChangeWalkthrough } from '@opencode-manager/shared/schemas'
import type { ChangeWalkthrough, ChangeWalkthroughState } from '@opencode-manager/shared/schemas'
const mocks = vi.hoisted(() => ({
getChangeWalkthrough: vi.fn(),
@@ -25,6 +25,10 @@ const walkthroughForA: ChangeWalkthrough = {
createdAt: 1,
}
function state(overrides: Partial<ChangeWalkthroughState> = {}): ChangeWalkthroughState {
return { walkthrough: null, currentDiffHash: 'hash-a', stale: false, generating: false, error: null, ...overrides }
}
function deferred<T>() {
let resolve!: (value: T) => void
const promise = new Promise<T>((res) => {
@@ -43,9 +47,9 @@ describe('useGenerateChangeWalkthrough', () => {
vi.clearAllMocks()
})
it('caches a completed generation under the originating session when the session changes mid-flight', async () => {
it('caches the returned state under the originating session when the session changes mid-flight', async () => {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
const pending = deferred<ChangeWalkthrough>()
const pending = deferred<ChangeWalkthroughState>()
mocks.generateChangeWalkthrough.mockReturnValue(pending.promise)
const { result, rerender } = renderHook(
@@ -63,51 +67,45 @@ describe('useGenerateChangeWalkthrough', () => {
rerender({ sessionId: 'ses_B' })
await act(async () => {
pending.resolve(walkthroughForA)
pending.resolve(state({ generating: true }))
})
await waitFor(() => {
expect(queryClient.getQueryData(changeWalkthroughQueryKey('ses_A'))).toEqual({
walkthrough: walkthroughForA,
currentDiffHash: 'hash-a',
stale: false,
})
expect(queryClient.getQueryData(changeWalkthroughQueryKey('ses_A'))).toEqual(state({ generating: true }))
})
expect(queryClient.getQueryData(changeWalkthroughQueryKey('ses_B'))).toBeUndefined()
})
})
it('refetches the state query after generation so server-computed staleness wins', async () => {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
mocks.getChangeWalkthrough
.mockResolvedValueOnce({ walkthrough: null, currentDiffHash: null, stale: false })
.mockResolvedValueOnce({ walkthrough: walkthroughForA, currentDiffHash: 'hash-a', stale: true })
mocks.generateChangeWalkthrough.mockResolvedValue(walkthroughForA)
describe('useChangeWalkthrough', () => {
beforeEach(() => {
vi.clearAllMocks()
})
const { result } = renderHook(
() => ({
state: useChangeWalkthrough('ses_A', true),
generate: useGenerateChangeWalkthrough('ses_A'),
}),
{ wrapper: createWrapper(queryClient) },
)
it('polls while a generation is running and stops once it finishes', async () => {
vi.useFakeTimers({ shouldAdvanceTime: true })
try {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
mocks.getChangeWalkthrough
.mockResolvedValueOnce(state({ generating: true }))
.mockResolvedValueOnce(state({ walkthrough: walkthroughForA }))
await waitFor(() => {
expect(mocks.getChangeWalkthrough).toHaveBeenCalledTimes(1)
})
const { result } = renderHook(() => useChangeWalkthrough('ses_A', true), { wrapper: createWrapper(queryClient) })
act(() => {
result.current.generate.mutate({})
})
await waitFor(() => expect(result.current.data?.generating).toBe(true))
await waitFor(() => {
expect(mocks.getChangeWalkthrough).toHaveBeenCalledTimes(2)
})
await waitFor(() => {
expect(result.current.state.data).toEqual({
walkthrough: walkthroughForA,
currentDiffHash: 'hash-a',
stale: true,
await act(async () => {
await vi.advanceTimersByTimeAsync(2_000)
})
})
await waitFor(() => expect(result.current.data?.walkthrough).toEqual(walkthroughForA))
await act(async () => {
await vi.advanceTimersByTimeAsync(10_000)
})
expect(mocks.getChangeWalkthrough).toHaveBeenCalledTimes(2)
} finally {
vi.useRealTimers()
}
})
})
+10 -9
View File
@@ -2,6 +2,8 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { generateChangeWalkthrough, getChangeWalkthrough } from '@/api/changeWalkthroughs'
import type { GenerateChangeWalkthroughRequest } from '@opencode-manager/shared/schemas'
const GENERATING_POLL_INTERVAL_MS = 2_000
export function changeWalkthroughQueryKey(sessionId: string) {
return ['change-walkthrough', sessionId] as const
}
@@ -12,6 +14,7 @@ export function useChangeWalkthrough(sessionId: string | undefined, enabled: boo
queryFn: () => getChangeWalkthrough(sessionId!),
enabled: enabled && !!sessionId,
staleTime: 30_000,
refetchInterval: (query) => (query.state.data?.generating ? GENERATING_POLL_INTERVAL_MS : false),
})
}
@@ -19,15 +22,13 @@ export function useGenerateChangeWalkthrough(sessionId: string | undefined) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (request: GenerateChangeWalkthroughRequest) =>
generateChangeWalkthrough(sessionId!, request),
onSuccess: (walkthrough) => {
queryClient.setQueryData(changeWalkthroughQueryKey(walkthrough.sessionId), {
walkthrough,
currentDiffHash: walkthrough.diffHash,
stale: false,
})
queryClient.invalidateQueries({ queryKey: changeWalkthroughQueryKey(walkthrough.sessionId) })
mutationFn: async (request: GenerateChangeWalkthroughRequest) => {
const targetSessionId = sessionId!
const state = await generateChangeWalkthrough(targetSessionId, request)
return { sessionId: targetSessionId, state }
},
onSuccess: ({ sessionId: targetSessionId, state }) => {
queryClient.setQueryData(changeWalkthroughQueryKey(targetSessionId), state)
},
})
}
+27
View File
@@ -0,0 +1,27 @@
import { useCallback } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import type { MoreDrawerItem } from '@/components/navigation/moreDrawerItems'
import { getPathWithReturnTo } from '@/lib/navigation'
import { openDialogParam } from './useDialogParam'
import { useUrlParams } from './useUrlParams'
/** Opens a navigation item's route or dialog; returns false for items it does not handle. */
export function useOpenNavItem(): (item: MoreDrawerItem) => boolean {
const location = useLocation()
const navigate = useNavigate()
const { updateParams } = useUrlParams()
return useCallback((item: MoreDrawerItem) => {
if (item.to) {
navigate(item.key === 'schedules'
? getPathWithReturnTo(item.to, `${location.pathname}${location.search}`)
: item.to)
return true
}
if (item.dialog) {
openDialogParam(updateParams, item.dialog)
return true
}
return false
}, [location.pathname, location.search, navigate, updateParams])
}
+1 -117
View File
@@ -1,6 +1,6 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { renderHook, act } from '@testing-library/react'
import { useSidebarCollapsed, useSidebarSections } from './useSidebarCollapsed'
import { useSidebarCollapsed } from './useSidebarCollapsed'
const localStorageMock = {
getItem: vi.fn(),
@@ -74,120 +74,4 @@ describe('sidebar collapse hooks', () => {
expect(result.current[0]).toBe(false)
})
})
describe('useSidebarSections', () => {
const sections = ['sessions', 'menu'] as const
it('opens every section by default when no stored value', () => {
localStorageMock.getItem.mockReturnValue(null)
const { result } = renderHook(() => useSidebarSections(sections))
expect(result.current.isSectionOpen('sessions')).toBe(true)
expect(result.current.isSectionOpen('menu')).toBe(true)
})
it('restores closed sections from storage', () => {
localStorageMock.getItem.mockReturnValue(JSON.stringify(['sessions']))
const { result } = renderHook(() => useSidebarSections(sections))
expect(localStorageMock.getItem).toHaveBeenCalledWith('oc:sidebar:collapsed:closed-sections')
expect(result.current.isSectionOpen('sessions')).toBe(false)
expect(result.current.isSectionOpen('menu')).toBe(true)
})
it('ignores unknown sections from storage', () => {
localStorageMock.getItem.mockReturnValue(JSON.stringify(['sessions', 'other']))
const { result } = renderHook(() => useSidebarSections(sections))
expect(result.current.isSectionOpen('sessions')).toBe(false)
expect(result.current.isSectionOpen('menu')).toBe(true)
})
it('opens every section when the stored value is malformed JSON', () => {
localStorageMock.getItem.mockReturnValue('not-json{{')
const { result } = renderHook(() => useSidebarSections(sections))
expect(result.current.isSectionOpen('sessions')).toBe(true)
expect(result.current.isSectionOpen('menu')).toBe(true)
})
it('opens every section when the stored value is not an array', () => {
localStorageMock.getItem.mockReturnValue(JSON.stringify('menu'))
const { result } = renderHook(() => useSidebarSections(sections))
expect(result.current.isSectionOpen('sessions')).toBe(true)
expect(result.current.isSectionOpen('menu')).toBe(true)
})
it('closes a section and persists it without affecting the others', () => {
localStorageMock.getItem.mockReturnValue(null)
const { result } = renderHook(() => useSidebarSections(sections))
act(() => {
result.current.toggleSection('sessions')
})
expect(result.current.isSectionOpen('sessions')).toBe(false)
expect(result.current.isSectionOpen('menu')).toBe(true)
expect(localStorageMock.setItem).toHaveBeenCalledWith(
'oc:sidebar:collapsed:closed-sections',
JSON.stringify(['sessions']),
)
})
it('reopens a closed section when toggled again', () => {
localStorageMock.getItem.mockReturnValue(JSON.stringify(['sessions']))
const { result } = renderHook(() => useSidebarSections(sections))
act(() => {
result.current.toggleSection('sessions')
})
expect(result.current.isSectionOpen('sessions')).toBe(true)
expect(localStorageMock.setItem).toHaveBeenCalledWith(
'oc:sidebar:collapsed:closed-sections',
JSON.stringify([]),
)
})
it('defaults open and keeps toggling in memory when storage throws', () => {
localStorageMock.getItem.mockImplementationOnce(() => {
throw new Error('SecurityError')
})
localStorageMock.setItem.mockImplementationOnce(() => {
throw new Error('QuotaExceededError')
})
const { result } = renderHook(() => useSidebarSections(sections))
expect(result.current.isSectionOpen('sessions')).toBe(true)
act(() => {
result.current.toggleSection('sessions')
})
expect(result.current.isSectionOpen('sessions')).toBe(false)
})
it('tracks each section independently', () => {
localStorageMock.getItem.mockReturnValue(null)
const { result } = renderHook(() => useSidebarSections(sections))
act(() => {
result.current.toggleSection('sessions')
result.current.toggleSection('menu')
})
expect(result.current.isSectionOpen('sessions')).toBe(false)
expect(result.current.isSectionOpen('menu')).toBe(false)
})
})
})
-41
View File
@@ -1,7 +1,6 @@
import { useState, useCallback } from 'react'
const STORAGE_KEY = 'oc:sidebar:collapsed'
const CLOSED_SECTIONS_STORAGE_KEY = `${STORAGE_KEY}:closed-sections`
function readStorage(key: string): string | null {
try {
@@ -46,46 +45,6 @@ function usePersistentBoolean(key: string, fallback: boolean): [boolean, () => v
return [value, toggle]
}
function readStoredClosedSections<T extends string>(sections: readonly T[]): T[] {
const stored = readStorage(CLOSED_SECTIONS_STORAGE_KEY)
if (stored === null) {
return []
}
try {
const parsed = JSON.parse(stored)
if (!Array.isArray(parsed)) {
return []
}
const known = new Set<string>(sections)
return parsed.filter((value): value is T => typeof value === 'string' && known.has(value))
} catch {
return []
}
}
export function useSidebarCollapsed(): [boolean, () => void] {
return usePersistentBoolean(STORAGE_KEY, false)
}
export function useSidebarSections<T extends string>(
sections: readonly T[],
): { isSectionOpen: (section: T) => boolean; toggleSection: (section: T) => void } {
const [closedSections, setClosedSections] = useState<T[]>(() => readStoredClosedSections(sections))
const toggleSection = useCallback((section: T) => {
setClosedSections((prev) => {
const next = prev.includes(section)
? prev.filter((item) => item !== section)
: [...prev, section]
writeStorage(CLOSED_SECTIONS_STORAGE_KEY, next)
return next
})
}, [])
const isSectionOpen = useCallback(
(section: T) => !closedSections.includes(section),
[closedSections],
)
return { isSectionOpen, toggleSection }
}
+87
View File
@@ -0,0 +1,87 @@
import { useCallback, useEffect } from 'react'
import { useUrlParams } from './useUrlParams'
const PANEL_PARAM = 'panel'
const PANEL_TOOLS = ['sourceControl', 'files', 'terminal', 'walkthrough', 'preview', 'mcp', 'actions', 'skills', 'schedules'] as const
export type PanelTool = (typeof PANEL_TOOLS)[number]
const TOOL_OWNED_PARAMS: Partial<Record<PanelTool, readonly string[]>> = {
terminal: ['terminal', 'terminalDirectory'],
preview: ['previewPort', 'previewPath'],
schedules: ['scheduleTab', 'scheduleDialog', 'jobId', 'runId'],
}
const PANEL_ONLY_TOOLS: ReadonlySet<PanelTool> = new Set(['schedules'])
export function isPanelTool(value: string | null): value is PanelTool {
return value !== null && (PANEL_TOOLS as readonly string[]).includes(value)
}
function clearToolParams(params: URLSearchParams, keep?: PanelTool): void {
for (const [tool, owned] of Object.entries(TOOL_OWNED_PARAMS)) {
if (tool === keep) continue
for (const param of owned) params.delete(param)
}
}
export interface ToolPanelState {
activeTool: PanelTool | null
toggleTool: (tool: PanelTool) => void
closePanel: () => void
}
/**
* URL state of the docked desktop tool panel (`?panel=`). While docked, a tool opened through the
* shared `?dialog=` param is moved into the panel; when not docked, an open panel tool falls back to its dialog,
* or closes when it has none.
*/
export function useToolPanel(docked: boolean): ToolPanelState {
const { searchParams, updateParams } = useUrlParams()
const panelParam = searchParams.get(PANEL_PARAM)
const dialogParam = searchParams.get('dialog')
const activeTool = docked && isPanelTool(panelParam) ? panelParam : null
useEffect(() => {
if (docked && isPanelTool(dialogParam)) {
updateParams((params) => {
params.delete('dialog')
params.set(PANEL_PARAM, dialogParam)
clearToolParams(params, dialogParam)
}, 'replace')
return
}
if (!docked && isPanelTool(panelParam)) {
updateParams((params) => {
params.delete(PANEL_PARAM)
if (PANEL_ONLY_TOOLS.has(panelParam)) {
clearToolParams(params)
return
}
if (!params.has('dialog')) params.set('dialog', panelParam)
}, 'replace')
}
}, [docked, dialogParam, panelParam, updateParams])
const toggleTool = useCallback((tool: PanelTool) => {
updateParams((params) => {
if (params.get(PANEL_PARAM) === tool) {
params.delete(PANEL_PARAM)
clearToolParams(params)
return
}
params.set(PANEL_PARAM, tool)
clearToolParams(params, tool)
}, 'push')
}, [updateParams])
const closePanel = useCallback(() => {
updateParams((params) => {
params.delete(PANEL_PARAM)
clearToolParams(params)
}, 'replace')
}, [updateParams])
return { activeTool, toggleTool, closePanel }
}