mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
feat(frontend): consolidate session picker navigation and remote project loading
This commit is contained in:
1 parent
81fb2d4033
commit
52aeb7780f
42 files changed
+1486
-769
No files matched your search
@@ -17,7 +17,7 @@
|
||||
|
||||
## Code Style
|
||||
|
||||
- Doc comments only: JSDoc/TSDoc attached to the declaration they document, in the language's native doc convention. No inline, explanatory, or section comments; code must be self-documenting
|
||||
- Doc comments only in new and changed code: JSDoc/TSDoc attached to the declaration they document, in the language's native doc convention. No inline, explanatory, or section comments; code must be self-documenting
|
||||
- No console logs (use Bun's logger or proper error handling)
|
||||
- Strict TypeScript everywhere, proper typing required
|
||||
- Named imports only: `import { Hono } from 'hono'`, `import { useState } from 'react'`
|
||||
|
||||
+1
-1
@@ -49,7 +49,7 @@ Each item is tagged with a theme to help you find work in your area of interest:
|
||||
|
||||
### Code Style
|
||||
|
||||
- Doc comments only (JSDoc/TSDoc on the declaration they document); no inline or explanatory comments
|
||||
- New and changed code uses doc comments only (JSDoc/TSDoc on the declaration they document); no inline or explanatory comments
|
||||
- Strict TypeScript with proper typing
|
||||
- Named imports only
|
||||
- DRY principles - check for existing patterns before adding new ones
|
||||
|
||||
@@ -20,13 +20,16 @@ import {
|
||||
listPendingPermissions,
|
||||
listSessionMessages,
|
||||
listSessionPage,
|
||||
projectActivityTimestamp,
|
||||
readSessionSnapshot,
|
||||
remoteProjectName,
|
||||
renameSession,
|
||||
replyForm,
|
||||
replyPermission,
|
||||
runCommand,
|
||||
runShell,
|
||||
sendPrompt,
|
||||
sortProjectsByActivity,
|
||||
stageRevert,
|
||||
switchSessionAgent,
|
||||
switchSessionModel,
|
||||
@@ -753,3 +756,47 @@ describe('OpenCode facade', () => {
|
||||
expect(lastRequest().init.method).toBe('DELETE')
|
||||
})
|
||||
})
|
||||
|
||||
const project = (
|
||||
id: string,
|
||||
name: string | undefined,
|
||||
canonical: string,
|
||||
time: { created: number; updated: number; active?: number },
|
||||
) => ({ id, name, canonical, time, sandboxes: [] })
|
||||
|
||||
describe('project helpers', () => {
|
||||
it('prefers the activity time over the update time', () => {
|
||||
const withActivity = project('p1', 'Active', '/work/active', { created: 1, updated: 10, active: 900 })
|
||||
|
||||
expect(projectActivityTimestamp(withActivity)).toBe(900)
|
||||
})
|
||||
|
||||
it('falls back to the update time when the project was never active', () => {
|
||||
const neverActive = project('p1', 'Idle', '/work/idle', { created: 1, updated: 10, active: 0 })
|
||||
|
||||
expect(projectActivityTimestamp(neverActive)).toBe(10)
|
||||
})
|
||||
|
||||
it('orders projects by activity, most recent first, without mutating the input', () => {
|
||||
const stale = project('p_stale', 'Stale', '/work/stale', { created: 1, updated: 500, active: 100 })
|
||||
const recent = project('p_recent', 'Recent', '/work/recent', { created: 1, updated: 100, active: 900 })
|
||||
const middle = project('p_middle', 'Middle', '/work/middle', { created: 1, updated: 700 })
|
||||
const projects = [stale, recent, middle]
|
||||
|
||||
expect(sortProjectsByActivity(projects).map((entry) => entry.id)).toEqual([
|
||||
'p_recent',
|
||||
'p_middle',
|
||||
'p_stale',
|
||||
])
|
||||
expect(projects.map((entry) => entry.id)).toEqual(['p_stale', 'p_recent', 'p_middle'])
|
||||
})
|
||||
|
||||
it('names a project from its trimmed title', () => {
|
||||
expect(remoteProjectName(project('p1', ' Alpha ', '/work/alpha', { created: 1, updated: 2 }))).toBe('Alpha')
|
||||
})
|
||||
|
||||
it('names a project from its directory when it has no title', () => {
|
||||
expect(remoteProjectName(project('p1', undefined, '/work/beta', { created: 1, updated: 2 }))).toBe('beta')
|
||||
expect(remoteProjectName(project('p1', ' ', '/work/gamma', { created: 1, updated: 2 }))).toBe('gamma')
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,7 @@
|
||||
import { openCodeLocation, parseOpenCodeModelRef } from '@opencode-manager/shared/opencode'
|
||||
import { MANAGER_PROMPT_CLIENT_METADATA_KEY } from '@opencode-manager/shared/schemas'
|
||||
import { isMobileViewport } from '@/hooks/useMobile'
|
||||
import { getDirectoryName } from '@/lib/utils'
|
||||
import { callOpenCode } from './opencodeApi'
|
||||
import type {
|
||||
AgentInfo,
|
||||
@@ -37,10 +38,36 @@ export type OpenCodeLocationInfo = Awaited<ReturnType<OpenCodeApi['location']['g
|
||||
|
||||
export type OpenCodeProject = Awaited<ReturnType<OpenCodeApi['project']['list']>>[number]
|
||||
|
||||
/**
|
||||
* Returns the timestamp that represents a project's most recent activity.
|
||||
*
|
||||
* @param project Project whose activity time is read.
|
||||
* @returns The activity time, falling back to the last update when the project was never active.
|
||||
*/
|
||||
export function projectActivityTimestamp(project: OpenCodeProject): number {
|
||||
return project.time.active || project.time.updated
|
||||
}
|
||||
|
||||
/**
|
||||
* Orders projects from the most to the least recently active.
|
||||
*
|
||||
* @param projects Projects to order.
|
||||
* @returns A new array with the projects sorted by activity; the input is left untouched.
|
||||
*/
|
||||
export function sortProjectsByActivity(projects: OpenCodeProject[]): OpenCodeProject[] {
|
||||
return [...projects].sort((a, b) => projectActivityTimestamp(b) - projectActivityTimestamp(a))
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the display name of a project, falling back to the name of its directory.
|
||||
*
|
||||
* @param project Project whose name is resolved.
|
||||
* @returns The trimmed project name, or the last segment of its canonical directory.
|
||||
*/
|
||||
export function remoteProjectName(project: OpenCodeProject): string {
|
||||
return project.name?.trim() || getDirectoryName(project.canonical)
|
||||
}
|
||||
|
||||
export type VcsInfo = Awaited<ReturnType<OpenCodeApi['vcs']['get']>>['data']
|
||||
|
||||
export type VcsFileStatus = Awaited<ReturnType<OpenCodeApi['vcs']['status']>>['data'][number]
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import { memo } from 'react'
|
||||
import { ModelQuickSelect } from '@/components/model/ModelQuickSelect'
|
||||
import { ContextUsageMeter } from '@/components/session/ContextUsageMeter'
|
||||
import { useSession } from '@/hooks/useOpenCode'
|
||||
import { useContextUsage } from '@/hooks/useContextUsage'
|
||||
import type { ModelSelectionSession } from '@/hooks/useModelSelection'
|
||||
import {
|
||||
CONTEXT_USAGE_TEXT_CLASS,
|
||||
contextUsageAccessibleLabel,
|
||||
contextUsageTone,
|
||||
formatContextUsage,
|
||||
} from '@/lib/contextUsage'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
interface ComposerModelPillProps {
|
||||
directory?: string
|
||||
sessionID: string
|
||||
modelName: string
|
||||
variant: string | null
|
||||
modelSelectionSession?: ModelSelectionSession
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
isCompacting: boolean
|
||||
onCompact: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Model selector trigger for the composer.
|
||||
*
|
||||
* Owns the context usage observer so transcript streaming flushes re-render only this pill instead of the
|
||||
* whole composer subtree.
|
||||
*/
|
||||
export const ComposerModelPill = memo(function ComposerModelPill({
|
||||
directory,
|
||||
sessionID,
|
||||
modelName,
|
||||
variant,
|
||||
modelSelectionSession,
|
||||
open,
|
||||
onOpenChange,
|
||||
isCompacting,
|
||||
onCompact,
|
||||
}: ComposerModelPillProps) {
|
||||
const { data: session } = useSession(sessionID, directory)
|
||||
const contextUsage = useContextUsage(sessionID, directory, session?.revert?.messageID)
|
||||
const pillUsage = contextUsage ? formatContextUsage(contextUsage) : null
|
||||
const pillUsageTone = CONTEXT_USAGE_TEXT_CLASS[contextUsageTone(contextUsage?.usagePercentage ?? null)]
|
||||
const pillLabel = [
|
||||
modelName || 'Select model',
|
||||
variant ? `${variant} variant` : null,
|
||||
contextUsage ? contextUsageAccessibleLabel(contextUsage) : null,
|
||||
].filter((part): part is string => part !== null).join(', ')
|
||||
|
||||
return (
|
||||
<ModelQuickSelect
|
||||
directory={directory}
|
||||
open={open}
|
||||
onOpenChange={onOpenChange}
|
||||
session={modelSelectionSession}
|
||||
contextUsage={contextUsage}
|
||||
isCompacting={isCompacting}
|
||||
onCompact={onCompact}
|
||||
>
|
||||
<button
|
||||
aria-label={pillLabel}
|
||||
className="relative px-2.5 py-0.5 md:px-3 min-h-11 md:min-h-9 min-w-0 rounded-lg text-xs md:text-sm font-medium border bg-muted border-border text-muted-foreground hover:bg-muted-foreground/10 hover:border-foreground/30 transition-colors cursor-pointer flex-1 md:flex-initial md:w-auto md:max-w-[220px] dark:border-border/30 flex flex-col items-start justify-center overflow-hidden"
|
||||
>
|
||||
<span className="truncate w-full text-left">{modelName || 'Select model'}</span>
|
||||
{(variant || pillUsage) && (
|
||||
<span className="flex w-full min-w-0 items-center gap-1 text-[10px] leading-tight">
|
||||
{variant && (
|
||||
<span className="truncate text-left capitalize text-highlight">{variant}</span>
|
||||
)}
|
||||
{variant && pillUsage && (
|
||||
<span aria-hidden="true" className="text-muted-foreground">·</span>
|
||||
)}
|
||||
{pillUsage && (
|
||||
<span
|
||||
data-testid="model-pill-context-usage"
|
||||
className={cn('shrink-0 font-medium', pillUsageTone)}
|
||||
>
|
||||
{pillUsage}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
{contextUsage && (
|
||||
<ContextUsageMeter
|
||||
percentage={contextUsage.usagePercentage}
|
||||
className="absolute inset-x-0 bottom-0"
|
||||
/>
|
||||
)}
|
||||
</button>
|
||||
</ModelQuickSelect>
|
||||
)
|
||||
})
|
||||
@@ -1,10 +1,12 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { useSyncExternalStore } from 'react'
|
||||
import { render, screen, fireEvent, waitFor, act } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { PromptInput } from './PromptInput'
|
||||
import { useComposerDraftStore } from '@/stores/composerDraftStore'
|
||||
import { useSessionStatus } from '@/stores/sessionStatusStore'
|
||||
import { createCommandActionsMock, createVoiceConversationControllerMock } from '@/test/test-utils'
|
||||
import type { ContextUsage } from '@/lib/contextUsage'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
useSTT: vi.fn(),
|
||||
@@ -22,6 +24,9 @@ const mocks = vi.hoisted(() => ({
|
||||
useHasBackgroundActivity: vi.fn(),
|
||||
useSendPrompt: vi.fn(),
|
||||
useContextUsage: vi.fn(),
|
||||
contextUsageListeners: new Set<() => void>(),
|
||||
contextUsageValue: null as ContextUsage | null,
|
||||
agentQuickSelectRenders: { current: 0 },
|
||||
sessionData: undefined as { revert?: { messageID: string } } | undefined,
|
||||
hasPendingPermission: vi.fn(() => false),
|
||||
setShowDialog: vi.fn(),
|
||||
@@ -70,7 +75,10 @@ vi.mock('@/contexts/EventContext', () => ({
|
||||
}))
|
||||
|
||||
vi.mock('@/components/agent/AgentQuickSelect', () => ({
|
||||
AgentQuickSelect: () => <div data-testid="agent-quick-select" />,
|
||||
AgentQuickSelect: () => {
|
||||
mocks.agentQuickSelectRenders.current += 1
|
||||
return <div data-testid="agent-quick-select" />
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/components/model/ModelQuickSelect', () => ({
|
||||
@@ -91,6 +99,22 @@ vi.mock('@/hooks/useSessionGoals', () => ({
|
||||
}))
|
||||
vi.mock('@/hooks/useSessionPermissionMode', () => ({ useSessionPermissionMode: () => ({ data: undefined }) }))
|
||||
|
||||
function subscribeContextUsage(listener: () => void) {
|
||||
mocks.contextUsageListeners.add(listener)
|
||||
return () => {
|
||||
mocks.contextUsageListeners.delete(listener)
|
||||
}
|
||||
}
|
||||
|
||||
function getContextUsageSnapshot() {
|
||||
return mocks.contextUsageValue
|
||||
}
|
||||
|
||||
function setContextUsage(usage: ContextUsage | null) {
|
||||
mocks.contextUsageValue = usage
|
||||
mocks.contextUsageListeners.forEach((listener) => listener())
|
||||
}
|
||||
|
||||
const createTestQueryClient = () => new QueryClient({
|
||||
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
|
||||
})
|
||||
@@ -157,7 +181,10 @@ describe('PromptInput composer layout', () => {
|
||||
mocks.useSessionAgentStore.mockImplementation((selector: (state: unknown) => unknown) => selector({ setAgent: vi.fn() }))
|
||||
mocks.useSendErrorStore.mockImplementation((selector: (state: unknown) => unknown) => selector({ errors: {} }))
|
||||
mocks.useHasBackgroundActivity.mockReturnValue(false)
|
||||
mocks.useContextUsage.mockReturnValue({ usage: null, isLoading: false })
|
||||
mocks.useContextUsage.mockReturnValue(null)
|
||||
mocks.contextUsageListeners.clear()
|
||||
mocks.contextUsageValue = null
|
||||
mocks.agentQuickSelectRenders.current = 0
|
||||
mocks.sessionData = undefined
|
||||
})
|
||||
|
||||
@@ -249,8 +276,8 @@ describe('PromptInput composer layout', () => {
|
||||
})
|
||||
|
||||
describe('model pill context usage', () => {
|
||||
const setUsage = (usage: { totalTokens: number, usagePercentage: number | null, contextLimit: number | null }) => {
|
||||
mocks.useContextUsage.mockReturnValue({ usage, isLoading: false })
|
||||
const setUsage = (usage: ContextUsage) => {
|
||||
mocks.useContextUsage.mockReturnValue(usage)
|
||||
}
|
||||
|
||||
it('shows the percentage with its tone and the meter on the model pill', () => {
|
||||
@@ -305,6 +332,24 @@ describe('PromptInput composer layout', () => {
|
||||
expect(screen.queryByTestId('context-usage-meter')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('re-renders only the pill when the context usage changes', () => {
|
||||
mocks.useContextUsage.mockImplementation(() => useSyncExternalStore(subscribeContextUsage, getContextUsageSnapshot))
|
||||
setContextUsage({ totalTokens: 84000, usagePercentage: 42, contextLimit: 200000 })
|
||||
renderComponent()
|
||||
|
||||
const siblingRenders = mocks.agentQuickSelectRenders.current
|
||||
expect(screen.getByTestId('model-pill-context-usage')).toHaveTextContent('42%')
|
||||
expect(siblingRenders).toBeGreaterThan(0)
|
||||
|
||||
act(() => {
|
||||
setContextUsage({ totalTokens: 100000, usagePercentage: 50, contextLimit: 200000 })
|
||||
})
|
||||
|
||||
expect(screen.getByTestId('model-pill-context-usage')).toHaveTextContent('50%')
|
||||
expect(screen.getByTestId('model-pill-context-usage')).toHaveClass('text-warning')
|
||||
expect(mocks.agentQuickSelectRenders.current).toBe(siblingRenders)
|
||||
})
|
||||
|
||||
it('measures usage up to the staged revert boundary', () => {
|
||||
mocks.sessionData = { revert: { messageID: 'msg_2' } }
|
||||
renderComponent()
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { useState, useRef, useEffect, useMemo, useImperativeHandle, forwardRef, memo, useCallback, type KeyboardEvent } from 'react'
|
||||
import { useContextUsage } from '@/hooks/useContextUsage'
|
||||
import { useSendPrompt, useInterruptSession, useSendShell, useAgents, useSkills, useSession } from '@/hooks/useOpenCode'
|
||||
import { useSendPrompt, useInterruptSession, useSendShell, useAgents, useSkills } from '@/hooks/useOpenCode'
|
||||
import { useCommands } from '@/hooks/useCommands'
|
||||
import { useCommandHandler } from '@/hooks/useCommandHandler'
|
||||
import { useFileSearch } from '@/hooks/useFileSearch'
|
||||
@@ -28,12 +27,11 @@ import { IconToggleButton } from '@/components/ui/icon-toggle-button'
|
||||
|
||||
import { PromptSuggestions, type PromptSuggestion } from './PromptSuggestions'
|
||||
import { ComposerActivityBar } from './ComposerActivityBar'
|
||||
import { ModelQuickSelect } from '@/components/model/ModelQuickSelect'
|
||||
import { AgentQuickSelect } from '@/components/agent/AgentQuickSelect'
|
||||
import { VoiceConversation, type VoiceConversationHandle } from './VoiceConversation'
|
||||
import { PermissionModeToggle } from '@/components/session/PermissionModeToggle'
|
||||
import { SessionSandboxMenu } from '@/components/session/SessionSandboxMenu'
|
||||
import { ContextUsageMeter } from '@/components/session/ContextUsageMeter'
|
||||
import { ComposerModelPill } from './ComposerModelPill'
|
||||
import { ComposerToolsMenu } from './ComposerToolsMenu'
|
||||
import { useSessionGoal, useStartSessionGoal } from '@/hooks/useSessionGoals'
|
||||
import { useSessionPermissionMode } from '@/hooks/useSessionPermissionMode'
|
||||
@@ -41,8 +39,7 @@ import { detectMentionTrigger, parsePromptToInput, getFilename, getDirectory, ty
|
||||
import { matchText, rankByMatch, type MatchRange } from '@/lib/fuzzyMatch'
|
||||
import { getNextPrimaryAgentId } from '@/lib/primaryAgents'
|
||||
import { getNextFavoriteModel } from '@/lib/favoriteModels'
|
||||
import { randomId, cn } from '@/lib/utils'
|
||||
import { CONTEXT_USAGE_TEXT_CLASS, contextUsageAccessibleLabel, contextUsageTone, formatContextUsage } from '@/lib/contextUsage'
|
||||
import { randomId } from '@/lib/utils'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { findModelInfo, isSameModelSelection } from '@opencode-manager/shared/opencode'
|
||||
import { isOpenSessionGoal } from '@opencode-manager/shared/schemas'
|
||||
@@ -1015,18 +1012,9 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
|
||||
const { setShowDialog, hasForSession: hasPermissionsForSession } = usePermissions()
|
||||
const hasPendingPermissionForSession = hasPermissionsForSession(sessionID)
|
||||
const { hasVariants, currentVariant, cycleVariant } = useVariants(directory, modelSelectionSession)
|
||||
const { data: session } = useSession(sessionID, directory)
|
||||
const revertMessageID = session?.revert?.messageID
|
||||
const { usage: contextUsage } = useContextUsage(sessionID, directory, revertMessageID)
|
||||
const isCompacting = useSessionStatusForSession(sessionID).type === 'compact'
|
||||
const modelPillVariant = hasVariants && currentVariant ? currentVariant : null
|
||||
const modelPillUsage = contextUsage ? formatContextUsage(contextUsage) : null
|
||||
const modelPillUsageTone = CONTEXT_USAGE_TEXT_CLASS[contextUsageTone(contextUsage?.usagePercentage ?? null)]
|
||||
const modelPillLabel = [
|
||||
displayModelName || 'Select model',
|
||||
modelPillVariant ? `${modelPillVariant} variant` : null,
|
||||
contextUsage ? contextUsageAccessibleLabel(contextUsage) : null,
|
||||
].filter((part): part is string => part !== null).join(', ')
|
||||
const handleCompact = useCallback(() => commandActions.compact(''), [commandActions])
|
||||
|
||||
const handleAgentChange = useCallback((agentId: string) => {
|
||||
setLocalMode(agentId)
|
||||
@@ -1355,46 +1343,17 @@ return (
|
||||
</IconToggleButton>
|
||||
</>
|
||||
) : null}
|
||||
<ModelQuickSelect
|
||||
<ComposerModelPill
|
||||
directory={directory}
|
||||
sessionID={sessionID}
|
||||
modelName={displayModelName}
|
||||
variant={modelPillVariant}
|
||||
modelSelectionSession={modelSelectionSession}
|
||||
open={isModelPickerOpen}
|
||||
onOpenChange={setIsModelPickerOpen}
|
||||
session={modelSelectionSession}
|
||||
contextUsage={contextUsage}
|
||||
isCompacting={isCompacting}
|
||||
onCompact={() => commandActions.compact('')}
|
||||
>
|
||||
<button
|
||||
aria-label={modelPillLabel}
|
||||
className="relative px-2.5 py-0.5 md:px-3 min-h-11 md:min-h-9 min-w-0 rounded-lg text-xs md:text-sm font-medium border bg-muted border-border text-muted-foreground hover:bg-muted-foreground/10 hover:border-foreground/30 transition-colors cursor-pointer flex-1 md:flex-initial md:w-auto md:max-w-[220px] dark:border-border/30 flex flex-col items-start justify-center overflow-hidden"
|
||||
>
|
||||
<span className="truncate w-full text-left">{displayModelName || 'Select model'}</span>
|
||||
{(modelPillVariant || modelPillUsage) && (
|
||||
<span className="flex w-full min-w-0 items-center gap-1 text-[10px] leading-tight">
|
||||
{modelPillVariant && (
|
||||
<span className="truncate text-left capitalize text-highlight">{modelPillVariant}</span>
|
||||
)}
|
||||
{modelPillVariant && modelPillUsage && (
|
||||
<span aria-hidden="true" className="text-muted-foreground">·</span>
|
||||
)}
|
||||
{modelPillUsage && (
|
||||
<span
|
||||
data-testid="model-pill-context-usage"
|
||||
className={cn('shrink-0 font-medium', modelPillUsageTone)}
|
||||
>
|
||||
{modelPillUsage}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
{contextUsage && (
|
||||
<ContextUsageMeter
|
||||
percentage={contextUsage.usagePercentage}
|
||||
className="absolute inset-x-0 bottom-0"
|
||||
/>
|
||||
)}
|
||||
</button>
|
||||
</ModelQuickSelect>
|
||||
onCompact={handleCompact}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -633,3 +633,70 @@ describe('ModelQuickSelect context strip', () => {
|
||||
expect(screen.queryByTestId('context-usage-strip')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('ModelQuickSelect model descriptions', () => {
|
||||
const limitedProviders: Provider[] = [
|
||||
{
|
||||
id: 'anthropic',
|
||||
name: 'Anthropic',
|
||||
models: [
|
||||
{
|
||||
id: 'claude-sonnet-4',
|
||||
key: 'claude-sonnet-4',
|
||||
name: 'Claude Sonnet 4',
|
||||
released: 0,
|
||||
free: false,
|
||||
limit: { context: 200000, output: 8192 },
|
||||
},
|
||||
{
|
||||
id: 'claude-opus-5-5',
|
||||
key: 'claude-opus-5-5',
|
||||
name: 'Claude Opus 5.5',
|
||||
released: 0,
|
||||
free: false,
|
||||
limit: { context: 1000000, output: 8192 },
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
function selectModel(modelID: string) {
|
||||
const modelState = { favorite: [], recent: [], variant: {} }
|
||||
mocks.useModelSelection.mockReturnValue({
|
||||
model: { providerID: 'anthropic', modelID },
|
||||
modelString: `anthropic/${modelID}`,
|
||||
info: undefined,
|
||||
activeAgent: null,
|
||||
recentModels: [],
|
||||
favoriteModels: [],
|
||||
configured: null,
|
||||
modelState,
|
||||
setModel: vi.fn(),
|
||||
setActiveAgent: vi.fn(),
|
||||
toggleFavorite: vi.fn(),
|
||||
removeRecentModel: vi.fn(),
|
||||
isModelReady: true,
|
||||
})
|
||||
mocks.useModelSections.mockReturnValue({
|
||||
providers: limitedProviders,
|
||||
sections: buildModelSections(limitedProviders, modelState, null),
|
||||
defaultModel: null,
|
||||
modelState,
|
||||
isLoading: false,
|
||||
})
|
||||
}
|
||||
|
||||
it('formats the context limit like the context strip', () => {
|
||||
selectModel('claude-sonnet-4')
|
||||
render(<ModelQuickSelect open />)
|
||||
|
||||
expect(screen.getByText('Anthropic · 200k context', { selector: 'p' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('formats million-token limits without a trailing decimal', () => {
|
||||
selectModel('claude-opus-5-5')
|
||||
render(<ModelQuickSelect open />)
|
||||
|
||||
expect(screen.getByText('Anthropic · 1M context', { selector: 'p' })).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -472,8 +472,7 @@ export function ModelQuickSelect({
|
||||
const getDescription = (item: ModelListItem) => {
|
||||
const context = item.model?.limit?.context
|
||||
if (context) {
|
||||
const formattedContext = context >= 1000000 ? `${(context / 1000000).toFixed(1)}M` : context.toLocaleString()
|
||||
return `${item.providerName} · ${formattedContext} context`
|
||||
return `${item.providerName} · ${formatCompactTokens(context)} context`
|
||||
}
|
||||
|
||||
return item.providerName
|
||||
|
||||
@@ -7,6 +7,7 @@ import { useAuth } from '@/hooks/useAuth'
|
||||
import { useUrlParams } from '@/hooks/useUrlParams'
|
||||
import { useOpenNavItem } from '@/hooks/useOpenNavItem'
|
||||
import { useSessionPickerRouteScope } from '@/hooks/useSessionPickerRouteScope'
|
||||
import { useSessionPickerNavigation } from '@/hooks/useSessionPickerNavigation'
|
||||
import { buildNavModel, type MoreDrawerItem, type NavPrimaryCta } from '@/components/navigation/moreDrawerItems'
|
||||
import { SessionPickerDialog } from '@/components/session/SessionPickerDialog'
|
||||
import { DesktopSessionTree } from '@/components/navigation/DesktopSessionTree'
|
||||
@@ -16,14 +17,13 @@ import {
|
||||
SidebarSection,
|
||||
SidebarItem,
|
||||
} from '@/components/ui/sidebar'
|
||||
import { getRepoPath, getServerSessionPath, getSessionPath } from '@/lib/navigation'
|
||||
import { List } from 'lucide-react'
|
||||
|
||||
const FOOTER_ITEM_KEYS = new Set(['home', 'settings', 'logout'])
|
||||
|
||||
function DesktopSessionsPicker({ onDismiss }: { onDismiss: () => void }) {
|
||||
const navigate = useNavigate()
|
||||
const { currentRepo, activeSessionID, remote } = useSessionPickerRouteScope(true)
|
||||
const pickerNavigation = useSessionPickerNavigation({ mode: 'push', onClose: onDismiss })
|
||||
|
||||
return (
|
||||
<SessionPickerDialog
|
||||
@@ -33,27 +33,8 @@ function DesktopSessionsPicker({ onDismiss }: { onDismiss: () => void }) {
|
||||
}}
|
||||
currentRepo={currentRepo}
|
||||
activeSessionID={activeSessionID}
|
||||
{...pickerNavigation}
|
||||
remote={remote}
|
||||
onSelectSession={(session, sessionRepo) => {
|
||||
navigate(getSessionPath(sessionRepo.id, session.id))
|
||||
onDismiss()
|
||||
}}
|
||||
onSelectRemoteSession={(session, serverId) => {
|
||||
navigate(getServerSessionPath(serverId, session.id))
|
||||
onDismiss()
|
||||
}}
|
||||
onDeleteActiveSession={() => {
|
||||
onDismiss()
|
||||
if (currentRepo) navigate(getRepoPath(currentRepo.id))
|
||||
}}
|
||||
onSelectRepo={(selectedRepo) => {
|
||||
navigate(getRepoPath(selectedRepo.id))
|
||||
onDismiss()
|
||||
}}
|
||||
onNavigate={(path) => {
|
||||
navigate(path)
|
||||
onDismiss()
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ import { cn } from '@/lib/utils'
|
||||
|
||||
const LOCAL_SERVER_LABEL = 'OC Manager'
|
||||
|
||||
export type LinkedServersVariant = 'sidebar' | 'rail' | 'header'
|
||||
type LinkedServersVariant = 'sidebar' | 'rail' | 'header'
|
||||
|
||||
interface LinkedServersNavProps {
|
||||
/** `sidebar` renders the full-width trigger row, `rail` the collapsed icon button, `header` a compact page-header trigger. */
|
||||
|
||||
@@ -194,32 +194,6 @@ describe('RemoteProjectNavList', () => {
|
||||
expect(mocks.listProjects).toHaveBeenCalledWith('srv_kitchen')
|
||||
})
|
||||
|
||||
it('orders projects by recent activity', async () => {
|
||||
const now = Date.now()
|
||||
mocks.listProjects.mockResolvedValue([
|
||||
createProject('p_stale', 'Stale', '/projects/stale', {
|
||||
created: now - 10_800_000,
|
||||
updated: now - 300_000,
|
||||
active: now - 10_800_000,
|
||||
}),
|
||||
createProject('p_recent', 'Recent', '/projects/recent', {
|
||||
created: now - 10_800_000,
|
||||
updated: now - 10_800_000,
|
||||
active: now - 300_000,
|
||||
}),
|
||||
])
|
||||
|
||||
const { container } = render(<RemoteListHarness serverId="srv_kitchen" />, {
|
||||
wrapper: createWrapper('/'),
|
||||
})
|
||||
|
||||
await screen.findByText('Recent')
|
||||
|
||||
const text = container.textContent ?? ''
|
||||
expect(text.indexOf('Recent')).toBeGreaterThan(-1)
|
||||
expect(text.indexOf('Recent')).toBeLessThan(text.indexOf('Stale'))
|
||||
})
|
||||
|
||||
it('expands the project of the current project route and loads its sessions', async () => {
|
||||
render(<RemoteListHarness serverId="srv_kitchen" />, {
|
||||
wrapper: createWrapper('/servers/srv_kitchen/projects?directory=%2Fprojects%2Falpha'),
|
||||
|
||||
@@ -1,21 +1,18 @@
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { useLocation } from 'react-router-dom'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { listProjects, projectActivityTimestamp, type OpenCodeProject } from '@/api/opencode'
|
||||
import { remoteProjectName, type OpenCodeProject } from '@/api/opencode'
|
||||
import type { Session } from '@/api/types'
|
||||
import { ActivityStateIndicator } from '@/components/activity/ActivityStateIndicator'
|
||||
import { useSessionsAcrossDirectories, sessionQueryOptions } from '@/hooks/useOpenCode'
|
||||
import { useSessionsAcrossDirectories } from '@/hooks/useOpenCode'
|
||||
import { useActiveRemoteDirectory } from '@/hooks/useActiveRemoteDirectory'
|
||||
import { useRemoteProjects } from '@/hooks/useRemoteProjects'
|
||||
import { useOpenCodeServers, useOpenCodeServerStatuses } from '@/hooks/useOpenCodeServers'
|
||||
import { useProjectActivityState } from '@/hooks/useActiveWork'
|
||||
import { useSessionSearch } from '@/hooks/useSessionSearch'
|
||||
import { serverScopedKey } from '@/lib/serverScope'
|
||||
import {
|
||||
getServerProjectPath,
|
||||
getServerSessionPath,
|
||||
parseServerProjectRoute,
|
||||
parseServerSessionRoute,
|
||||
} from '@/lib/navigation'
|
||||
import { getDirectoryName } from '@/lib/utils'
|
||||
import { getSessionKey } from '@/lib/sessionKey'
|
||||
import {
|
||||
NewSessionButton,
|
||||
@@ -31,10 +28,6 @@ import {
|
||||
type SidebarSessionItem,
|
||||
} from '@/components/navigation/sidebar-session-tree'
|
||||
|
||||
function projectName(project: OpenCodeProject): string {
|
||||
return project.name?.trim() || getDirectoryName(project.canonical)
|
||||
}
|
||||
|
||||
function buildRemoteItem(session: Session, serverId: string, projectLabel: string): SidebarSessionItem {
|
||||
return {
|
||||
key: getSessionKey(session),
|
||||
@@ -55,20 +48,6 @@ function RemoteProjectActivityIndicator({ serverId, directory }: { serverId: str
|
||||
return <ActivityStateIndicator state={state} />
|
||||
}
|
||||
|
||||
function useActiveRemoteDirectory(serverId: string): string | null {
|
||||
const { pathname, search } = useLocation()
|
||||
const projectRoute = parseServerProjectRoute(pathname, search)
|
||||
const sessionRoute = parseServerSessionRoute(pathname)
|
||||
const sessionID = sessionRoute?.serverId === serverId ? sessionRoute.sessionId : undefined
|
||||
const { data: session } = useQuery({
|
||||
...sessionQueryOptions(sessionID, undefined, serverId),
|
||||
enabled: Boolean(sessionID),
|
||||
})
|
||||
|
||||
if (projectRoute?.serverId === serverId) return projectRoute.directory
|
||||
return session?.location.directory ?? null
|
||||
}
|
||||
|
||||
interface RemoteSessionRowsProps {
|
||||
serverId: string
|
||||
projectLabel: string
|
||||
@@ -135,7 +114,7 @@ function RemoteProjectSessions({ serverId, project, onSelectSession }: RemotePro
|
||||
return (
|
||||
<RemoteSessionRows
|
||||
serverId={serverId}
|
||||
projectLabel={projectName(project)}
|
||||
projectLabel={remoteProjectName(project)}
|
||||
sessions={data}
|
||||
isLoading={isLoading}
|
||||
isError={isError}
|
||||
@@ -167,7 +146,7 @@ function RemoteProjectGroup({
|
||||
onSelectSession,
|
||||
children,
|
||||
}: RemoteProjectGroupProps) {
|
||||
const name = projectName(project)
|
||||
const name = remoteProjectName(project)
|
||||
|
||||
return (
|
||||
<RepoNavGroup
|
||||
@@ -290,7 +269,7 @@ function RemoteProjectSearchResults({
|
||||
() =>
|
||||
projects.filter(
|
||||
(project) =>
|
||||
projectName(project).toLowerCase().includes(needle) ||
|
||||
remoteProjectName(project).toLowerCase().includes(needle) ||
|
||||
project.canonical.toLowerCase().includes(needle),
|
||||
),
|
||||
[projects, needle],
|
||||
@@ -342,7 +321,7 @@ function RemoteProjectSearchResults({
|
||||
{matchedSessions ? (
|
||||
<RemoteSessionRows
|
||||
serverId={serverId}
|
||||
projectLabel={projectName(project)}
|
||||
projectLabel={remoteProjectName(project)}
|
||||
sessions={matchedSessions}
|
||||
isLoading={false}
|
||||
isError={false}
|
||||
@@ -386,27 +365,15 @@ export function RemoteProjectNavList({
|
||||
const server = servers.find((candidate) => candidate.id === serverId)
|
||||
const activeDirectory = useActiveRemoteDirectory(serverId)
|
||||
|
||||
const projectsQuery = useQuery({
|
||||
queryKey: serverScopedKey(['opencode', 'projects'], serverId),
|
||||
queryFn: () => listProjects(serverId),
|
||||
enabled: server?.enabled === true,
|
||||
retry: false,
|
||||
})
|
||||
|
||||
const projects = useMemo(
|
||||
() =>
|
||||
[...(projectsQuery.data ?? [])].sort(
|
||||
(a, b) => projectActivityTimestamp(b) - projectActivityTimestamp(a),
|
||||
),
|
||||
[projectsQuery.data],
|
||||
)
|
||||
const { projects, isLoading: projectsLoading, isError: projectsError, hasData: hasProjects } =
|
||||
useRemoteProjects(serverId)
|
||||
const trimmedSearch = search.trim()
|
||||
|
||||
if (isServersLoading) return <SessionNavStatus>Loading projects...</SessionNavStatus>
|
||||
if (!server) return <SessionNavStatus>Server not found</SessionNavStatus>
|
||||
if (!server.enabled) return <SessionNavStatus>Server is disabled</SessionNavStatus>
|
||||
if (projectsQuery.isLoading) return <SessionNavStatus>Loading projects...</SessionNavStatus>
|
||||
if (projectsQuery.isError && projectsQuery.data === undefined) {
|
||||
if (projectsLoading) return <SessionNavStatus>Loading projects...</SessionNavStatus>
|
||||
if (projectsError && !hasProjects) {
|
||||
return (
|
||||
<SessionNavStatus>
|
||||
{statusById[serverId]?.connected === false ? 'Server unreachable' : 'Could not load projects'}
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
import { useMemo, useState } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { Folder, FolderGit2, FolderPlus, GitBranch, Search, Server } from 'lucide-react'
|
||||
import { listProjects, projectActivityTimestamp, type OpenCodeProject } from '@/api/opencode'
|
||||
import { projectActivityTimestamp, remoteProjectName, type OpenCodeProject } from '@/api/opencode'
|
||||
import { useOpenCodeServers } from '@/hooks/useOpenCodeServers'
|
||||
import { useRemoteProjects } from '@/hooks/useRemoteProjects'
|
||||
import { useSettingsDialog } from '@/hooks/useSettingsDialog'
|
||||
import { useProjectActivityState } from '@/hooks/useActiveWork'
|
||||
import { serverScopedKey } from '@/lib/serverScope'
|
||||
import { getServerProjectPath } from '@/lib/navigation'
|
||||
import { formatShortRelativeTime, getDirectoryName } from '@/lib/utils'
|
||||
import { formatShortRelativeTime } from '@/lib/utils'
|
||||
import { OpenCodeServerProvider } from '@/contexts/OpenCodeServerContext'
|
||||
import { ActivityStateIndicator } from '@/components/activity/ActivityStateIndicator'
|
||||
import { Button } from '@/components/ui/button'
|
||||
@@ -20,10 +19,6 @@ import { RepoCardShell } from '@/components/repo/RepoCardShell'
|
||||
import { RepoCardSkeleton } from '@/components/repo/RepoCardSkeleton'
|
||||
import { RepoSearchInput } from '@/components/repo/RepoSearchInput'
|
||||
|
||||
function projectName(project: OpenCodeProject): string {
|
||||
return project.name?.trim() || getDirectoryName(project.canonical)
|
||||
}
|
||||
|
||||
function RemoteProjectCard({ project, serverId }: { project: OpenCodeProject; serverId: string }) {
|
||||
const navigate = useNavigate()
|
||||
const activityState = useProjectActivityState(serverId, project.canonical)
|
||||
@@ -31,7 +26,7 @@ function RemoteProjectCard({ project, serverId }: { project: OpenCodeProject; se
|
||||
|
||||
return (
|
||||
<RepoCardShell
|
||||
title={projectName(project)}
|
||||
title={remoteProjectName(project)}
|
||||
statusDotClassName="bg-success"
|
||||
activity={<ActivityStateIndicator state={activityState} />}
|
||||
actions={<RemoteProjectRowActions serverId={serverId} directory={project.canonical} />}
|
||||
@@ -95,28 +90,15 @@ function RemoteProjectListContent({ serverId }: { serverId: string }) {
|
||||
const server = servers.find((candidate) => candidate.id === serverId)
|
||||
const isDisabled = server !== undefined && !server.enabled
|
||||
|
||||
const projectsQuery = useQuery({
|
||||
queryKey: serverScopedKey(['opencode', 'projects'], serverId),
|
||||
queryFn: () => listProjects(serverId),
|
||||
enabled: server?.enabled === true,
|
||||
retry: false,
|
||||
})
|
||||
|
||||
const projects = useMemo(
|
||||
() =>
|
||||
[...(projectsQuery.data ?? [])].sort(
|
||||
(a, b) => projectActivityTimestamp(b) - projectActivityTimestamp(a),
|
||||
),
|
||||
[projectsQuery.data],
|
||||
)
|
||||
const showsProjectError = projectsQuery.isError && projectsQuery.data === undefined
|
||||
const { projects, isLoading, isError, hasData, error, refetch } = useRemoteProjects(serverId)
|
||||
const showsProjectError = isError && !hasData
|
||||
|
||||
const filteredProjects = useMemo(() => {
|
||||
const query = searchQuery.trim().toLowerCase()
|
||||
if (!query) return projects
|
||||
|
||||
return projects.filter((project) =>
|
||||
projectName(project).toLowerCase().includes(query) ||
|
||||
remoteProjectName(project).toLowerCase().includes(query) ||
|
||||
project.canonical.toLowerCase().includes(query),
|
||||
)
|
||||
}, [projects, searchQuery])
|
||||
@@ -151,19 +133,19 @@ function RemoteProjectListContent({ serverId }: { serverId: string }) {
|
||||
<div>
|
||||
<p className="font-medium">Could not load projects</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{projectsQuery.error instanceof Error
|
||||
? projectsQuery.error.message
|
||||
{error instanceof Error
|
||||
? error.message
|
||||
: 'The server did not respond.'}
|
||||
</p>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" onClick={() => void projectsQuery.refetch()}>
|
||||
<Button variant="outline" size="sm" onClick={() => refetch()}>
|
||||
Retry
|
||||
</Button>
|
||||
</Card>
|
||||
) : null}
|
||||
|
||||
{server && !isDisabled && !showsProjectError ? (
|
||||
projectsQuery.isLoading ? (
|
||||
isLoading ? (
|
||||
<RemoteProjectListLoading />
|
||||
) : projects.length === 0 ? (
|
||||
<div className="flex flex-1 flex-col items-center justify-center p-12 text-center">
|
||||
|
||||
@@ -148,64 +148,34 @@ describe('RemoteProjectList', () => {
|
||||
expect(mocks.listProjects).toHaveBeenCalledWith('srv_kitchen')
|
||||
})
|
||||
|
||||
it('orders projects by recent activity and labels rows with that activity time', async () => {
|
||||
it('labels a row with its project activity time', async () => {
|
||||
const now = Date.now()
|
||||
mocks.listProjects.mockResolvedValue([
|
||||
{
|
||||
...project,
|
||||
id: 'prj_stale',
|
||||
name: 'Stale',
|
||||
canonical: '/work/stale',
|
||||
time: { created: now - 10_800_000, updated: now - 300_000, active: now - 10_800_000 },
|
||||
},
|
||||
{
|
||||
...project,
|
||||
id: 'prj_recent',
|
||||
name: 'Recent',
|
||||
canonical: '/work/recent',
|
||||
time: { created: now - 10_800_000, updated: now - 10_800_000, active: now - 300_000 },
|
||||
},
|
||||
])
|
||||
|
||||
const { container } = renderProjectList()
|
||||
renderProjectList()
|
||||
|
||||
await screen.findByText('Recent')
|
||||
|
||||
const text = container.textContent ?? ''
|
||||
expect(text.indexOf('Recent')).toBeGreaterThan(-1)
|
||||
expect(text.indexOf('Recent')).toBeLessThan(text.indexOf('5m ago'))
|
||||
expect(text.indexOf('5m ago')).toBeLessThan(text.indexOf('Stale'))
|
||||
expect(text.indexOf('Stale')).toBeLessThan(text.indexOf('3h ago'))
|
||||
await screen.findByText('App')
|
||||
expect(screen.getByText('5m ago')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('falls back to the update time when a project has no activity time', async () => {
|
||||
it('labels a row with the update time when the project has no activity time', async () => {
|
||||
const now = Date.now()
|
||||
mocks.listProjects.mockResolvedValue([
|
||||
{
|
||||
...project,
|
||||
id: 'prj_older',
|
||||
name: 'Older',
|
||||
canonical: '/work/older',
|
||||
time: { created: now - 10_800_000, updated: now - 10_800_000 },
|
||||
},
|
||||
{
|
||||
...project,
|
||||
id: 'prj_newer',
|
||||
name: 'Newer',
|
||||
canonical: '/work/newer',
|
||||
time: { created: now - 10_800_000, updated: now - 300_000 },
|
||||
},
|
||||
])
|
||||
|
||||
const { container } = renderProjectList()
|
||||
renderProjectList()
|
||||
|
||||
await screen.findByText('Newer')
|
||||
|
||||
const text = container.textContent ?? ''
|
||||
expect(text.indexOf('Newer')).toBeGreaterThan(-1)
|
||||
expect(text.indexOf('Newer')).toBeLessThan(text.indexOf('5m ago'))
|
||||
expect(text.indexOf('5m ago')).toBeLessThan(text.indexOf('Older'))
|
||||
expect(text.indexOf('Older')).toBeLessThan(text.indexOf('3h ago'))
|
||||
await screen.findByText('App')
|
||||
expect(screen.getByText('5m ago')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('opens the remote project page when a project card is clicked', async () => {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { Progress } from '@/components/ui/progress'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { CONTEXT_USAGE_BG_CLASS, contextUsageTone } from '@/lib/contextUsage'
|
||||
|
||||
@@ -6,20 +7,19 @@ interface ContextUsageMeterProps {
|
||||
className?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Thin context-window fill bar. Its accessible label lives on the model pill, so the bar itself is hidden
|
||||
* from assistive technology.
|
||||
*/
|
||||
export function ContextUsageMeter({ percentage, className }: ContextUsageMeterProps) {
|
||||
const width = percentage === null ? 0 : Math.min(percentage, 100)
|
||||
|
||||
return (
|
||||
<div
|
||||
<Progress
|
||||
data-testid="context-usage-meter"
|
||||
aria-hidden="true"
|
||||
className={cn('h-0.5 w-full overflow-hidden bg-border/50', className)}
|
||||
>
|
||||
<div
|
||||
data-testid="context-usage-meter-fill"
|
||||
className={cn('h-full', CONTEXT_USAGE_BG_CLASS[contextUsageTone(percentage)])}
|
||||
style={{ width: `${width}%` }}
|
||||
/>
|
||||
</div>
|
||||
value={percentage ?? 0}
|
||||
className={cn('h-0.5 rounded-none bg-border/50', className)}
|
||||
indicatorClassName={cn('transition-none', CONTEXT_USAGE_BG_CLASS[contextUsageTone(percentage)])}
|
||||
indicatorTestId="context-usage-meter-fill"
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -1,21 +1,65 @@
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { render, screen, act } from '@testing-library/react'
|
||||
import { afterEach, describe, it, expect, vi } from 'vitest'
|
||||
import { ReconnectingBanner } from './ReconnectingBanner'
|
||||
|
||||
const GRACE_PERIOD_MS = 5000
|
||||
|
||||
describe('ReconnectingBanner', () => {
|
||||
it('stays hidden before the stream has connected', () => {
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('stays hidden during the initial grace period', () => {
|
||||
vi.useFakeTimers()
|
||||
render(<ReconnectingBanner connected={false} />)
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(GRACE_PERIOD_MS - 1)
|
||||
})
|
||||
|
||||
expect(screen.queryByRole('status')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('reports a stream that never connects once the grace period elapses', () => {
|
||||
vi.useFakeTimers()
|
||||
render(<ReconnectingBanner connected={false} />)
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(GRACE_PERIOD_MS)
|
||||
})
|
||||
|
||||
const banner = screen.getByRole('status')
|
||||
expect(banner).toHaveTextContent('Not connected — live updates unavailable')
|
||||
expect(banner).toHaveAttribute('aria-live', 'polite')
|
||||
})
|
||||
|
||||
it('hides the not-connected banner as soon as the stream connects', () => {
|
||||
vi.useFakeTimers()
|
||||
const { rerender } = render(<ReconnectingBanner connected={false} />)
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(GRACE_PERIOD_MS)
|
||||
})
|
||||
expect(screen.getByRole('status')).toBeInTheDocument()
|
||||
|
||||
rerender(<ReconnectingBanner connected />)
|
||||
|
||||
expect(screen.queryByRole('status')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('stays hidden while the stream is connected', () => {
|
||||
vi.useFakeTimers()
|
||||
render(<ReconnectingBanner connected />)
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(GRACE_PERIOD_MS * 2)
|
||||
})
|
||||
|
||||
expect(screen.queryByRole('status')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('reports a dropped stream once it connected', () => {
|
||||
vi.useFakeTimers()
|
||||
const { rerender } = render(<ReconnectingBanner connected />)
|
||||
|
||||
rerender(<ReconnectingBanner connected={false} />)
|
||||
@@ -25,7 +69,20 @@ describe('ReconnectingBanner', () => {
|
||||
expect(banner).toHaveAttribute('aria-live', 'polite')
|
||||
})
|
||||
|
||||
it('keeps the reconnect message when the drop outlasts the grace period', () => {
|
||||
vi.useFakeTimers()
|
||||
const { rerender } = render(<ReconnectingBanner connected />)
|
||||
|
||||
rerender(<ReconnectingBanner connected={false} />)
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(GRACE_PERIOD_MS * 2)
|
||||
})
|
||||
|
||||
expect(screen.getByRole('status')).toHaveTextContent('Reconnecting… live updates paused')
|
||||
})
|
||||
|
||||
it('hides again when the stream reconnects', () => {
|
||||
vi.useFakeTimers()
|
||||
const { rerender } = render(<ReconnectingBanner connected />)
|
||||
|
||||
rerender(<ReconnectingBanner connected={false} />)
|
||||
@@ -33,4 +90,13 @@ describe('ReconnectingBanner', () => {
|
||||
|
||||
expect(screen.queryByRole('status')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('clears the grace timer on unmount', () => {
|
||||
vi.useFakeTimers()
|
||||
const { unmount } = render(<ReconnectingBanner connected={false} />)
|
||||
|
||||
unmount()
|
||||
|
||||
expect(vi.getTimerCount()).toBe(0)
|
||||
})
|
||||
})
|
||||
@@ -1,25 +1,42 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
const NOT_CONNECTED_GRACE_PERIOD_MS = 5000
|
||||
|
||||
export interface ReconnectingBannerProps {
|
||||
connected: boolean
|
||||
}
|
||||
|
||||
export function ReconnectingBanner({ connected }: ReconnectingBannerProps) {
|
||||
const [hasConnected, setHasConnected] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (connected) setHasConnected(true)
|
||||
}, [connected])
|
||||
|
||||
if (connected || !hasConnected) return null
|
||||
|
||||
function StatusBanner({ message }: { message: string }) {
|
||||
return (
|
||||
<div
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
className="w-full border-b border-warning/40 bg-warning/10 px-3 py-1 text-xs text-warning"
|
||||
>
|
||||
Reconnecting… live updates paused
|
||||
{message}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function ReconnectingBanner({ connected }: ReconnectingBannerProps) {
|
||||
const [hasConnected, setHasConnected] = useState(false)
|
||||
const [graceElapsed, setGraceElapsed] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (connected) setHasConnected(true)
|
||||
}, [connected])
|
||||
|
||||
useEffect(() => {
|
||||
if (connected) {
|
||||
setGraceElapsed(false)
|
||||
return
|
||||
}
|
||||
const timer = setTimeout(() => setGraceElapsed(true), NOT_CONNECTED_GRACE_PERIOD_MS)
|
||||
return () => clearTimeout(timer)
|
||||
}, [connected])
|
||||
|
||||
if (connected) return null
|
||||
if (hasConnected) return <StatusBanner message="Reconnecting… live updates paused" />
|
||||
if (graceElapsed) return <StatusBanner message="Not connected — live updates unavailable" />
|
||||
return null
|
||||
}
|
||||
@@ -6,7 +6,6 @@ import { SessionDetailsSheet, type SessionDetailsSheetProps } from './SessionDet
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
useMobile: vi.fn(),
|
||||
useUpdateSession: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useMobile', () => ({
|
||||
@@ -15,34 +14,27 @@ vi.mock('@/hooks/useMobile', () => ({
|
||||
useSwipeDismiss: vi.fn(() => ({ bind: vi.fn(), swipeProgress: 0, swipeStyles: {} })),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useOpenCode', () => ({ useUpdateSession: mocks.useUpdateSession }))
|
||||
|
||||
type RenameMutation = {
|
||||
mutate: ReturnType<typeof vi.fn>
|
||||
reset: ReturnType<typeof vi.fn>
|
||||
error: Error | null
|
||||
isPending: boolean
|
||||
}
|
||||
|
||||
const baseProps: SessionDetailsSheetProps = {
|
||||
open: true,
|
||||
onOpenChange: vi.fn(),
|
||||
sessionId: 'ses_1',
|
||||
title: 'Fix the header',
|
||||
remote: false,
|
||||
project: 'oc-manager',
|
||||
onRename: vi.fn(() => Promise.resolve()),
|
||||
}
|
||||
|
||||
function mockRename(overrides: Partial<RenameMutation> = {}): RenameMutation {
|
||||
const mutation: RenameMutation = {
|
||||
mutate: vi.fn(),
|
||||
reset: vi.fn(),
|
||||
error: null,
|
||||
isPending: false,
|
||||
...overrides,
|
||||
}
|
||||
mocks.useUpdateSession.mockReturnValue(mutation)
|
||||
return mutation
|
||||
function createDeferred() {
|
||||
let resolve!: () => void
|
||||
let reject!: (error: Error) => void
|
||||
const promise = new Promise<void>((res, rej) => {
|
||||
resolve = res
|
||||
reject = rej
|
||||
})
|
||||
return { promise, resolve, reject }
|
||||
}
|
||||
|
||||
function failingRename(error = new Error('nope')) {
|
||||
return vi.fn(() => Promise.reject(error))
|
||||
}
|
||||
|
||||
function renderSheet(overrides: Partial<SessionDetailsSheetProps> = {}) {
|
||||
@@ -53,7 +45,6 @@ describe('SessionDetailsSheet', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.useMobile.mockReturnValue(false)
|
||||
mockRename()
|
||||
})
|
||||
|
||||
it('lists the local session details', () => {
|
||||
@@ -118,101 +109,108 @@ describe('SessionDetailsSheet', () => {
|
||||
expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled()
|
||||
})
|
||||
|
||||
it('saves the trimmed title and leaves edit mode on success', () => {
|
||||
const mutation = mockRename()
|
||||
renderSheet()
|
||||
it('saves the trimmed title and leaves edit mode on success', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onRename = vi.fn(() => Promise.resolve())
|
||||
renderSheet({ onRename })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Rename' }))
|
||||
fireEvent.change(screen.getByLabelText('Session title'), {
|
||||
target: { value: ' New name ' },
|
||||
})
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save' }))
|
||||
|
||||
expect(mutation.mutate).toHaveBeenCalledWith(
|
||||
{ sessionID: 'ses_1', title: 'New name' },
|
||||
expect.objectContaining({ onSuccess: expect.any(Function) }),
|
||||
)
|
||||
|
||||
const options = mutation.mutate.mock.calls[0]![1] as { onSuccess: () => void }
|
||||
act(() => options.onSuccess())
|
||||
await user.click(screen.getByRole('button', { name: 'Rename' }))
|
||||
await user.clear(screen.getByLabelText('Session title'))
|
||||
await user.type(screen.getByLabelText('Session title'), ' New name ')
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }))
|
||||
|
||||
expect(onRename).toHaveBeenCalledWith('New name')
|
||||
expect(screen.queryByLabelText('Session title')).not.toBeInTheDocument()
|
||||
expect(screen.getByText('Fix the header')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('saves on Enter', () => {
|
||||
const mutation = mockRename()
|
||||
renderSheet()
|
||||
it('saves on Enter', async () => {
|
||||
const onRename = vi.fn(() => Promise.resolve())
|
||||
renderSheet({ onRename })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Rename' }))
|
||||
fireEvent.change(screen.getByLabelText('Session title'), { target: { value: 'Entered' } })
|
||||
fireEvent.keyDown(screen.getByLabelText('Session title'), { key: 'Enter' })
|
||||
await act(async () => {
|
||||
fireEvent.keyDown(screen.getByLabelText('Session title'), { key: 'Enter' })
|
||||
})
|
||||
|
||||
expect(mutation.mutate).toHaveBeenCalledWith(
|
||||
{ sessionID: 'ses_1', title: 'Entered' },
|
||||
expect.objectContaining({ onSuccess: expect.any(Function) }),
|
||||
)
|
||||
expect(onRename).toHaveBeenCalledWith('Entered')
|
||||
})
|
||||
|
||||
it('ignores Enter while an IME composition is active', () => {
|
||||
const mutation = mockRename()
|
||||
renderSheet()
|
||||
const onRename = vi.fn(() => Promise.resolve())
|
||||
renderSheet({ onRename })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Rename' }))
|
||||
const input = screen.getByLabelText('Session title')
|
||||
fireEvent.change(input, { target: { value: 'にほんご' } })
|
||||
fireEvent.keyDown(input, { key: 'Enter', isComposing: true })
|
||||
|
||||
expect(mutation.mutate).not.toHaveBeenCalled()
|
||||
expect(onRename).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('cancels editing and resets the rename error', () => {
|
||||
const mutation = mockRename({ error: new Error('nope') })
|
||||
renderSheet()
|
||||
it('shows the rename failure inline', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderSheet({ onRename: failingRename() })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Rename' }))
|
||||
expect(screen.getByText('Rename failed')).toBeInTheDocument()
|
||||
await user.click(screen.getByRole('button', { name: 'Rename' }))
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }))
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
|
||||
expect(await screen.findByText('Rename failed')).toBeInTheDocument()
|
||||
expect(screen.getByLabelText('Session title')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('cancels editing and clears the rename error', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderSheet({ onRename: failingRename() })
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Rename' }))
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }))
|
||||
expect(await screen.findByText('Rename failed')).toBeInTheDocument()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Cancel' }))
|
||||
|
||||
expect(screen.queryByText('Rename failed')).not.toBeInTheDocument()
|
||||
expect(screen.queryByLabelText('Session title')).not.toBeInTheDocument()
|
||||
expect(mutation.reset).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('shows the rename failure inline', () => {
|
||||
mockRename({ error: new Error('nope') })
|
||||
renderSheet()
|
||||
it('disables the title field while a rename is pending', async () => {
|
||||
const user = userEvent.setup()
|
||||
const deferred = createDeferred()
|
||||
renderSheet({ onRename: () => deferred.promise })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Rename' }))
|
||||
|
||||
expect(screen.getByText('Rename failed')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('disables the title field while a rename is pending', () => {
|
||||
mockRename({ isPending: true })
|
||||
renderSheet()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Rename' }))
|
||||
await user.click(screen.getByRole('button', { name: 'Rename' }))
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }))
|
||||
|
||||
expect(screen.getByLabelText('Session title')).toBeDisabled()
|
||||
expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled()
|
||||
|
||||
await act(async () => {
|
||||
deferred.resolve()
|
||||
})
|
||||
})
|
||||
|
||||
it('does not dismiss while a rename is pending', async () => {
|
||||
const user = userEvent.setup()
|
||||
const deferred = createDeferred()
|
||||
const onOpenChange = vi.fn()
|
||||
mockRename({ isPending: true })
|
||||
renderSheet({ onOpenChange })
|
||||
renderSheet({ onOpenChange, onRename: () => deferred.promise })
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Rename' }))
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }))
|
||||
await user.keyboard('{Escape}')
|
||||
await user.click(screen.getByRole('button', { name: 'Close' }))
|
||||
|
||||
expect(onOpenChange).not.toHaveBeenCalled()
|
||||
expect(screen.getByRole('dialog')).toBeInTheDocument()
|
||||
|
||||
await act(async () => {
|
||||
deferred.resolve()
|
||||
})
|
||||
})
|
||||
|
||||
it('resets to view mode and clears the error when reopened', () => {
|
||||
const mutation = mockRename({ error: new Error('nope') })
|
||||
it('resets to view mode and clears the error when reopened', async () => {
|
||||
const user = userEvent.setup()
|
||||
|
||||
function Host() {
|
||||
const [open, setOpen] = useState(true)
|
||||
@@ -221,22 +219,28 @@ describe('SessionDetailsSheet', () => {
|
||||
<button type="button" onClick={() => setOpen((current) => !current)}>
|
||||
toggle
|
||||
</button>
|
||||
<SessionDetailsSheet {...baseProps} open={open} onOpenChange={setOpen} />
|
||||
<SessionDetailsSheet
|
||||
{...baseProps}
|
||||
open={open}
|
||||
onOpenChange={setOpen}
|
||||
onRename={failingRename()}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
render(<Host />)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Rename' }))
|
||||
expect(screen.getByLabelText('Session title')).toBeInTheDocument()
|
||||
await user.click(screen.getByRole('button', { name: 'Rename' }))
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }))
|
||||
expect(await screen.findByText('Rename failed')).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(screen.getByText('toggle'))
|
||||
fireEvent.click(screen.getByText('toggle'))
|
||||
|
||||
expect(screen.queryByLabelText('Session title')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Rename failed')).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Rename' })).toBeInTheDocument()
|
||||
expect(mutation.reset).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('renders as a bottom sheet on mobile', () => {
|
||||
|
||||
@@ -4,19 +4,18 @@ import { BottomSheet, BottomSheetContent, BottomSheetHeader } from '@/components
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import { useUpdateSession } from '@/hooks/useOpenCode'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export interface SessionDetailsSheetProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
sessionId: string
|
||||
title?: string
|
||||
serverName?: string
|
||||
remote: boolean
|
||||
project: string
|
||||
branch?: string | null
|
||||
directory?: string
|
||||
onRename: (title: string) => Promise<void>
|
||||
}
|
||||
|
||||
interface InfoRowProps {
|
||||
@@ -43,31 +42,32 @@ function InfoRow({ label, value, mono, leading }: InfoRowProps) {
|
||||
export function SessionDetailsSheet({
|
||||
open,
|
||||
onOpenChange,
|
||||
sessionId,
|
||||
title,
|
||||
serverName,
|
||||
remote,
|
||||
project,
|
||||
branch,
|
||||
directory,
|
||||
onRename,
|
||||
}: SessionDetailsSheetProps) {
|
||||
const isMobile = useMobile()
|
||||
const renameSession = useUpdateSession(directory)
|
||||
const [editing, setEditing] = useState(false)
|
||||
const [draft, setDraft] = useState('')
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [renameFailed, setRenameFailed] = useState(false)
|
||||
const [lastOpen, setLastOpen] = useState(open)
|
||||
|
||||
if (open !== lastOpen) {
|
||||
setLastOpen(open)
|
||||
if (open) {
|
||||
setEditing(false)
|
||||
if (renameSession.error) renameSession.reset()
|
||||
setRenameFailed(false)
|
||||
}
|
||||
}
|
||||
|
||||
const displayTitle = title?.trim() ? title : 'Untitled Session'
|
||||
const trimmedDraft = draft.trim()
|
||||
const canSave = trimmedDraft.length > 0 && !renameSession.isPending
|
||||
const canSave = trimmedDraft.length > 0 && !saving
|
||||
|
||||
const startEditing = () => {
|
||||
setDraft(title ?? '')
|
||||
@@ -76,19 +76,25 @@ export function SessionDetailsSheet({
|
||||
|
||||
const cancelEditing = () => {
|
||||
setEditing(false)
|
||||
if (renameSession.error) renameSession.reset()
|
||||
setRenameFailed(false)
|
||||
}
|
||||
|
||||
const save = () => {
|
||||
const save = async () => {
|
||||
if (!canSave) return
|
||||
renameSession.mutate(
|
||||
{ sessionID: sessionId, title: trimmedDraft },
|
||||
{ onSuccess: () => setEditing(false) },
|
||||
)
|
||||
setSaving(true)
|
||||
setRenameFailed(false)
|
||||
try {
|
||||
await onRename(trimmedDraft)
|
||||
setEditing(false)
|
||||
} catch {
|
||||
setRenameFailed(true)
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleClose = () => {
|
||||
if (renameSession.isPending) return
|
||||
if (saving) return
|
||||
onOpenChange(false)
|
||||
}
|
||||
|
||||
@@ -116,13 +122,13 @@ export function SessionDetailsSheet({
|
||||
event.preventDefault()
|
||||
save()
|
||||
}}
|
||||
disabled={renameSession.isPending}
|
||||
disabled={saving}
|
||||
aria-label="Session title"
|
||||
placeholder="Session title"
|
||||
autoFocus
|
||||
className="w-full min-w-0 rounded border border-border bg-background px-3 py-2 text-sm font-semibold outline-none focus:border-primary focus:ring-2 focus:ring-primary/20 disabled:opacity-60"
|
||||
/>
|
||||
{renameSession.error && (
|
||||
{renameFailed && (
|
||||
<span className="text-xs text-destructive">Rename failed</span>
|
||||
)}
|
||||
<div className="flex items-center gap-2 pt-1">
|
||||
@@ -178,7 +184,7 @@ export function SessionDetailsSheet({
|
||||
isOpen={open}
|
||||
onClose={handleClose}
|
||||
ariaLabel="Session details"
|
||||
dismissible={!renameSession.isPending}
|
||||
dismissible={!saving}
|
||||
>
|
||||
<BottomSheetHeader title="Session details" />
|
||||
<BottomSheetContent>{body}</BottomSheetContent>
|
||||
|
||||
@@ -7,6 +7,7 @@ import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
import type { Repo, Session } from '@/api/types'
|
||||
import type { ActiveWorkGroups, ActiveWorkItem, ActiveWorkState } from '@/lib/activeWork'
|
||||
import { stubMatchMedia } from '@/test/test-utils'
|
||||
import { makeRepo, makeSession } from '@/test/fixtures/session-picker'
|
||||
import { DEFAULT_ACTIVITY_WINDOW_MINUTES } from '@/api/types/settings'
|
||||
import { KeyboardShortcutsProvider } from '@/contexts/KeyboardShortcutsContext'
|
||||
import { OpenCodeServerProvider } from '@/contexts/OpenCodeServerContext'
|
||||
@@ -21,6 +22,7 @@ const mocks = vi.hoisted(() => ({
|
||||
| { directory: string; project: { id: string; directory: string; canonical: string } }
|
||||
| undefined,
|
||||
sessionsHook: vi.fn(),
|
||||
lastSessionServerId: null as string | null,
|
||||
fetchNextPage: vi.fn(),
|
||||
deleteSessionMock: vi.fn(),
|
||||
deletedSessionServerId: null as string | null,
|
||||
@@ -66,6 +68,7 @@ vi.mock('@/hooks/useOpenCode', async (importOriginal) => {
|
||||
options?: { search?: string; allDirectories?: boolean; project?: { id: string; subpath: string } },
|
||||
) => {
|
||||
mocks.sessionsHook()
|
||||
mocks.lastSessionServerId = useOpenCodeServerId()
|
||||
mocks.lastDirectories = directories
|
||||
mocks.lastAllDirectories = options?.allDirectories ?? false
|
||||
mocks.lastProject = options?.project
|
||||
@@ -127,30 +130,6 @@ vi.mock('@/stores/sessionStatusStore', async (importOriginal) => {
|
||||
return { ...actual, useSessionStatusForSession: () => ({ type: 'idle' }) }
|
||||
})
|
||||
|
||||
function session(id: string, title: string, directory: string, updated = Date.now()): Session {
|
||||
return {
|
||||
id,
|
||||
projectID: 'proj',
|
||||
title,
|
||||
time: { created: updated, updated },
|
||||
location: { directory },
|
||||
cost: 0,
|
||||
tokens: {},
|
||||
} as unknown as Session
|
||||
}
|
||||
|
||||
function repo(id: number, name: string, fullPath: string): Repo {
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
localPath: fullPath,
|
||||
fullPath,
|
||||
defaultBranch: 'main',
|
||||
cloneStatus: 'ready',
|
||||
clonedAt: 0,
|
||||
}
|
||||
}
|
||||
|
||||
function activeWorkItem(
|
||||
id: string,
|
||||
title: string,
|
||||
@@ -158,7 +137,7 @@ function activeWorkItem(
|
||||
state: ActiveWorkState = 'recent',
|
||||
): ActiveWorkItem {
|
||||
const itemRepo = mocks.repos.find((candidate) => candidate.fullPath === directory) ?? mocks.repos[0]
|
||||
const itemSession = session(id, title, directory)
|
||||
const itemSession = makeSession(id, title, directory)
|
||||
return {
|
||||
key: `${directory}:${id}`,
|
||||
session: itemSession,
|
||||
@@ -233,8 +212,9 @@ describe('SessionPickerDialog', () => {
|
||||
}
|
||||
mocks.getOpenCodeLocation.mockResolvedValue(mocks.locationData)
|
||||
mocks.lastProject = undefined
|
||||
mocks.lastSessionServerId = null
|
||||
mocks.sessionPins = []
|
||||
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
|
||||
mocks.repos = [makeRepo(1, 'alpha', '/w/a'), makeRepo(2, 'beta', '/w/b')]
|
||||
mocks.sessionsData = []
|
||||
mocks.activeWorkGroups = { needsInput: [], running: [], recent: [] }
|
||||
mocks.activeWorkWindowMs = 0
|
||||
@@ -247,8 +227,8 @@ describe('SessionPickerDialog', () => {
|
||||
|
||||
it('opens with the active session as the cursor and marks it with a dot', () => {
|
||||
mocks.sessionsData = [
|
||||
session('ses_active', 'Active session', '/w/a', 3000),
|
||||
session('ses_other', 'Other session', '/w/a', 2000),
|
||||
makeSession('ses_active', 'Active session', '/w/a', 3000),
|
||||
makeSession('ses_other', 'Other session', '/w/a', 2000),
|
||||
]
|
||||
|
||||
renderPicker({ activeSessionID: 'ses_active' })
|
||||
@@ -262,8 +242,8 @@ describe('SessionPickerDialog', () => {
|
||||
|
||||
it('filters rows immediately as the query is typed', () => {
|
||||
mocks.sessionsData = [
|
||||
session('ses_alpha', 'alpha task', '/w/a', 2000),
|
||||
session('ses_beta', 'beta task', '/w/a', 1000),
|
||||
makeSession('ses_alpha', 'alpha task', '/w/a', 2000),
|
||||
makeSession('ses_beta', 'beta task', '/w/a', 1000),
|
||||
]
|
||||
|
||||
renderPicker()
|
||||
@@ -276,9 +256,9 @@ describe('SessionPickerDialog', () => {
|
||||
|
||||
it('moves the cursor with arrow keys and Ctrl+N/Ctrl+P, wrapping, and opens the row on Enter', () => {
|
||||
mocks.sessionsData = [
|
||||
session('ses_1', 'First', '/w/a', 3000),
|
||||
session('ses_2', 'Second', '/w/a', 2000),
|
||||
session('ses_3', 'Third', '/w/a', 1000),
|
||||
makeSession('ses_1', 'First', '/w/a', 3000),
|
||||
makeSession('ses_2', 'Second', '/w/a', 2000),
|
||||
makeSession('ses_3', 'Third', '/w/a', 1000),
|
||||
]
|
||||
const { onSelectSession } = renderPicker()
|
||||
|
||||
@@ -312,8 +292,8 @@ describe('SessionPickerDialog', () => {
|
||||
|
||||
it('toggles scope with Ctrl+A, persists it, queries every repo directory and shows repo labels', () => {
|
||||
mocks.sessionsData = [
|
||||
session('ses_a', 'Alpha session', '/w/a', 2000),
|
||||
session('ses_b', 'Beta session', '/w/b', 1000),
|
||||
makeSession('ses_a', 'Alpha session', '/w/a', 2000),
|
||||
makeSession('ses_b', 'Beta session', '/w/b', 1000),
|
||||
]
|
||||
|
||||
renderPicker()
|
||||
@@ -381,8 +361,8 @@ describe('SessionPickerDialog', () => {
|
||||
|
||||
it('labels the sessions tab Sessions and lists every project without a current repo', () => {
|
||||
mocks.sessionsData = [
|
||||
session('ses_a', 'Alpha session', '/w/a', 2000),
|
||||
session('ses_b', 'Beta session', '/w/b', 1000),
|
||||
makeSession('ses_a', 'Alpha session', '/w/a', 2000),
|
||||
makeSession('ses_b', 'Beta session', '/w/b', 1000),
|
||||
]
|
||||
|
||||
renderPicker({ currentRepo: undefined })
|
||||
@@ -428,8 +408,8 @@ describe('SessionPickerDialog', () => {
|
||||
it('starts a new session in a project row and marks a repo that is not ready', async () => {
|
||||
const onNavigate = vi.fn()
|
||||
mocks.repos = [
|
||||
repo(1, 'alpha', '/w/a'),
|
||||
{ ...repo(2, 'beta', '/w/b'), cloneStatus: 'cloning' },
|
||||
makeRepo(1, 'alpha', '/w/a'),
|
||||
{ ...makeRepo(2, 'beta', '/w/b'), cloneStatus: 'cloning' },
|
||||
]
|
||||
renderPicker({ onNavigate })
|
||||
|
||||
@@ -444,15 +424,15 @@ describe('SessionPickerDialog', () => {
|
||||
})
|
||||
|
||||
it('lists project sessions across worktrees and labels them with the folder name', async () => {
|
||||
mocks.repos = [repo(1, 'alpha', '/w/a')]
|
||||
mocks.repos = [makeRepo(1, 'alpha', '/w/a')]
|
||||
mocks.locationData = {
|
||||
directory: '/w/a',
|
||||
project: { id: 'proj_x', directory: '/w/a', canonical: '/w/a' },
|
||||
}
|
||||
mocks.sessionsData = [
|
||||
session('ses_root', 'Root session', '/w/a', 3000),
|
||||
session('ses_wt', 'Worktree session', '/w/.opencode/state/opencode/worktree/proj_x/test', 2000),
|
||||
session('ses_schedule', 'Schedule session', '/w/schedule-worktrees/job-11-run-361', 1000),
|
||||
makeSession('ses_root', 'Root session', '/w/a', 3000),
|
||||
makeSession('ses_wt', 'Worktree session', '/w/.opencode/state/opencode/worktree/proj_x/test', 2000),
|
||||
makeSession('ses_schedule', 'Schedule session', '/w/schedule-worktrees/job-11-run-361', 1000),
|
||||
]
|
||||
|
||||
renderPicker()
|
||||
@@ -471,10 +451,10 @@ describe('SessionPickerDialog', () => {
|
||||
})
|
||||
|
||||
it('falls back to the repo directory listing when the location project is global', async () => {
|
||||
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
|
||||
mocks.repos = [makeRepo(1, 'alpha', '/w/a'), makeRepo(2, 'beta', '/w/b')]
|
||||
mocks.sessionsData = [
|
||||
session('ses_a', 'Alpha session', '/w/a', 2000),
|
||||
session('ses_b', 'Beta session', '/w/b', 1000),
|
||||
makeSession('ses_a', 'Alpha session', '/w/a', 2000),
|
||||
makeSession('ses_b', 'Beta session', '/w/b', 1000),
|
||||
]
|
||||
|
||||
renderPicker()
|
||||
@@ -486,12 +466,12 @@ describe('SessionPickerDialog', () => {
|
||||
})
|
||||
|
||||
it('falls back to the repo directory listing when the location lookup fails', async () => {
|
||||
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
|
||||
mocks.repos = [makeRepo(1, 'alpha', '/w/a'), makeRepo(2, 'beta', '/w/b')]
|
||||
mocks.locationData = undefined
|
||||
mocks.getOpenCodeLocation.mockRejectedValue(new Error('location unavailable'))
|
||||
mocks.sessionsData = [
|
||||
session('ses_a', 'Alpha session', '/w/a', 2000),
|
||||
session('ses_b', 'Beta session', '/w/b', 1000),
|
||||
makeSession('ses_a', 'Alpha session', '/w/a', 2000),
|
||||
makeSession('ses_b', 'Beta session', '/w/b', 1000),
|
||||
]
|
||||
|
||||
renderPicker()
|
||||
@@ -507,7 +487,7 @@ describe('SessionPickerDialog', () => {
|
||||
| undefined
|
||||
mocks.locationData = undefined
|
||||
mocks.getOpenCodeLocation.mockReturnValue(new Promise((resolve) => { resolveLocation = resolve }))
|
||||
mocks.sessionsData = [session('ses_a', 'Alpha session', '/w/a', 2000)]
|
||||
mocks.sessionsData = [makeSession('ses_a', 'Alpha session', '/w/a', 2000)]
|
||||
|
||||
renderPicker()
|
||||
|
||||
@@ -526,7 +506,7 @@ describe('SessionPickerDialog', () => {
|
||||
})
|
||||
|
||||
it('does not query sessions while closed and queries after opening', async () => {
|
||||
mocks.sessionsData = [session('ses_1', 'First', '/w/a', 3000)]
|
||||
mocks.sessionsData = [makeSession('ses_1', 'First', '/w/a', 3000)]
|
||||
|
||||
function Host() {
|
||||
const [open, setOpen] = useState(false)
|
||||
@@ -556,8 +536,8 @@ describe('SessionPickerDialog', () => {
|
||||
|
||||
it('deletes on a second Ctrl+D and clears the pending state on a move', async () => {
|
||||
mocks.sessionsData = [
|
||||
session('ses_1', 'First', '/w/a', 3000),
|
||||
session('ses_2', 'Second', '/w/a', 2000),
|
||||
makeSession('ses_1', 'First', '/w/a', 3000),
|
||||
makeSession('ses_2', 'Second', '/w/a', 2000),
|
||||
]
|
||||
const { onDeleteActiveSession } = renderPicker()
|
||||
|
||||
@@ -581,7 +561,7 @@ describe('SessionPickerDialog', () => {
|
||||
})
|
||||
|
||||
it('notifies when the active session is deleted before the delete completes', async () => {
|
||||
mocks.sessionsData = [session('ses_active', 'Active', '/w/a', 3000)]
|
||||
mocks.sessionsData = [makeSession('ses_active', 'Active', '/w/a', 3000)]
|
||||
let resolveDelete: () => void = () => undefined
|
||||
mocks.deleteSessionMock.mockReturnValue(
|
||||
new Promise<void>((resolve) => {
|
||||
@@ -603,8 +583,8 @@ describe('SessionPickerDialog', () => {
|
||||
|
||||
it('moves the cursor when a mouse pointer moves over a row', () => {
|
||||
mocks.sessionsData = [
|
||||
session('ses_1', 'First', '/w/a', 3000),
|
||||
session('ses_2', 'Second', '/w/a', 2000),
|
||||
makeSession('ses_1', 'First', '/w/a', 3000),
|
||||
makeSession('ses_2', 'Second', '/w/a', 2000),
|
||||
]
|
||||
renderPicker()
|
||||
|
||||
@@ -617,7 +597,7 @@ describe('SessionPickerDialog', () => {
|
||||
})
|
||||
|
||||
it('opens the delete confirmation from the row menu', async () => {
|
||||
mocks.sessionsData = [session('ses_1', 'First', '/w/a', 3000)]
|
||||
mocks.sessionsData = [makeSession('ses_1', 'First', '/w/a', 3000)]
|
||||
renderPicker()
|
||||
const user = userEvent.setup()
|
||||
|
||||
@@ -629,8 +609,8 @@ describe('SessionPickerDialog', () => {
|
||||
|
||||
it('groups older sessions under per-day headings', () => {
|
||||
mocks.sessionsData = [
|
||||
session('ses_jan2', 'Jan two', '/w/a', new Date(2020, 0, 2, 12).getTime()),
|
||||
session('ses_jan1', 'Jan one', '/w/a', new Date(2020, 0, 1, 12).getTime()),
|
||||
makeSession('ses_jan2', 'Jan two', '/w/a', new Date(2020, 0, 2, 12).getTime()),
|
||||
makeSession('ses_jan1', 'Jan one', '/w/a', new Date(2020, 0, 1, 12).getTime()),
|
||||
]
|
||||
|
||||
renderPicker()
|
||||
@@ -641,8 +621,8 @@ describe('SessionPickerDialog', () => {
|
||||
|
||||
it('resets the query and cursor on reopen', async () => {
|
||||
mocks.sessionsData = [
|
||||
session('ses_active', 'Active session', '/w/a', 3000),
|
||||
session('ses_other', 'Other session', '/w/a', 2000),
|
||||
makeSession('ses_active', 'Active session', '/w/a', 3000),
|
||||
makeSession('ses_other', 'Other session', '/w/a', 2000),
|
||||
]
|
||||
|
||||
function Host() {
|
||||
@@ -700,7 +680,7 @@ describe('SessionPickerDialog', () => {
|
||||
})
|
||||
|
||||
it('focuses the projects search input after clicking the Projects tab and filters on typing', async () => {
|
||||
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
|
||||
mocks.repos = [makeRepo(1, 'alpha', '/w/a'), makeRepo(2, 'beta', '/w/b')]
|
||||
const user = userEvent.setup()
|
||||
renderPicker()
|
||||
|
||||
@@ -715,7 +695,7 @@ describe('SessionPickerDialog', () => {
|
||||
})
|
||||
|
||||
it('focuses the projects search input after switching tabs with the shortcut', async () => {
|
||||
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
|
||||
mocks.repos = [makeRepo(1, 'alpha', '/w/a'), makeRepo(2, 'beta', '/w/b')]
|
||||
const user = userEvent.setup()
|
||||
renderPicker()
|
||||
|
||||
@@ -727,7 +707,7 @@ describe('SessionPickerDialog', () => {
|
||||
|
||||
it('focuses the projects search input after the switch shortcut on a coarse pointer device', async () => {
|
||||
stubMatchMedia(false)
|
||||
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
|
||||
mocks.repos = [makeRepo(1, 'alpha', '/w/a'), makeRepo(2, 'beta', '/w/b')]
|
||||
const user = userEvent.setup()
|
||||
renderPicker()
|
||||
|
||||
@@ -739,7 +719,7 @@ describe('SessionPickerDialog', () => {
|
||||
|
||||
it('does not focus the projects search input when switching tabs by pointer on a coarse pointer device', async () => {
|
||||
stubMatchMedia(false)
|
||||
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
|
||||
mocks.repos = [makeRepo(1, 'alpha', '/w/a'), makeRepo(2, 'beta', '/w/b')]
|
||||
const user = userEvent.setup()
|
||||
renderPicker()
|
||||
|
||||
@@ -749,7 +729,7 @@ describe('SessionPickerDialog', () => {
|
||||
})
|
||||
|
||||
it('lists repos in the projects tab and opens the cursor repo on Enter', async () => {
|
||||
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
|
||||
mocks.repos = [makeRepo(1, 'alpha', '/w/a'), makeRepo(2, 'beta', '/w/b')]
|
||||
const { onSelectRepo } = renderPicker()
|
||||
|
||||
openProjectsTab()
|
||||
@@ -765,7 +745,7 @@ describe('SessionPickerDialog', () => {
|
||||
|
||||
it('navigates the projects tab with wrapping arrows, PageUp/PageDown and Enter', async () => {
|
||||
mocks.repos = Array.from({ length: 12 }, (_, index) =>
|
||||
repo(index + 1, `repo-${index + 1}`, `/w/r${index + 1}`),
|
||||
makeRepo(index + 1, `repo-${index + 1}`, `/w/r${index + 1}`),
|
||||
)
|
||||
const { onSelectRepo } = renderPicker()
|
||||
|
||||
@@ -793,7 +773,7 @@ describe('SessionPickerDialog', () => {
|
||||
})
|
||||
|
||||
it('opens a repo on click in the projects tab', async () => {
|
||||
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
|
||||
mocks.repos = [makeRepo(1, 'alpha', '/w/a'), makeRepo(2, 'beta', '/w/b')]
|
||||
const { onSelectRepo } = renderPicker()
|
||||
|
||||
openProjectsTab()
|
||||
@@ -805,8 +785,8 @@ describe('SessionPickerDialog', () => {
|
||||
|
||||
it('filters projects by name and branch', async () => {
|
||||
mocks.repos = [
|
||||
{ ...repo(1, 'alpha', '/w/a'), currentBranch: 'feature/x' },
|
||||
repo(2, 'beta', '/w/b'),
|
||||
{ ...makeRepo(1, 'alpha', '/w/a'), currentBranch: 'feature/x' },
|
||||
makeRepo(2, 'beta', '/w/b'),
|
||||
]
|
||||
renderPicker()
|
||||
|
||||
@@ -912,7 +892,7 @@ describe('SessionPickerDialog', () => {
|
||||
})
|
||||
|
||||
it('groups active work into needs input, running and recent sections with repo labels', async () => {
|
||||
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
|
||||
mocks.repos = [makeRepo(1, 'alpha', '/w/a'), makeRepo(2, 'beta', '/w/b')]
|
||||
mocks.activeWorkGroups = {
|
||||
needsInput: [activeWorkItem('ses_ni', 'Needs input task', '/w/a', 'needs-input')],
|
||||
running: [activeWorkItem('ses_run', 'Running task', '/w/b', 'running')],
|
||||
@@ -958,7 +938,7 @@ describe('SessionPickerDialog', () => {
|
||||
})
|
||||
|
||||
it('opens the cursor active row with Enter and selects its session and repo', async () => {
|
||||
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
|
||||
mocks.repos = [makeRepo(1, 'alpha', '/w/a'), makeRepo(2, 'beta', '/w/b')]
|
||||
mocks.activeWorkGroups = {
|
||||
needsInput: [],
|
||||
running: [activeWorkItem('ses_run', 'Running task', '/w/b', 'running')],
|
||||
@@ -979,7 +959,7 @@ describe('SessionPickerDialog', () => {
|
||||
})
|
||||
|
||||
it('filters active work rows by title and drops sections left empty', async () => {
|
||||
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
|
||||
mocks.repos = [makeRepo(1, 'alpha', '/w/a'), makeRepo(2, 'beta', '/w/b')]
|
||||
mocks.activeWorkGroups = {
|
||||
needsInput: [activeWorkItem('ses_ni', 'Needs input task', '/w/a', 'needs-input')],
|
||||
running: [],
|
||||
@@ -999,7 +979,7 @@ describe('SessionPickerDialog', () => {
|
||||
})
|
||||
|
||||
it('pins an active work row from the shared row menu', async () => {
|
||||
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
|
||||
mocks.repos = [makeRepo(1, 'alpha', '/w/a'), makeRepo(2, 'beta', '/w/b')]
|
||||
mocks.activeWorkGroups = {
|
||||
needsInput: [],
|
||||
running: [activeWorkItem('ses_run', 'Running task', '/w/b', 'running')],
|
||||
@@ -1022,11 +1002,11 @@ describe('SessionPickerDialog', () => {
|
||||
|
||||
describe('linked-server mode', () => {
|
||||
beforeEach(() => {
|
||||
mocks.repos = [repo(1, 'alpha', '/w/a')]
|
||||
mocks.sessionsData = [session('ses_remote', 'Remote session', '/home/me/app')]
|
||||
mocks.repos = [makeRepo(1, 'alpha', '/w/a')]
|
||||
mocks.sessionsData = [makeSession('ses_remote', 'Remote session', '/home/me/app')]
|
||||
})
|
||||
|
||||
it('lists the project sessions without Manager-only tabs and reports the chosen server session', async () => {
|
||||
it('lists the project sessions with the linked server projects tab and reports the chosen server session', async () => {
|
||||
const onSelectRemoteSession = vi.fn()
|
||||
renderPicker({
|
||||
remote: {
|
||||
@@ -1037,7 +1017,7 @@ describe('SessionPickerDialog', () => {
|
||||
onSelectRemoteSession,
|
||||
})
|
||||
|
||||
expect(screen.queryByRole('tab', { name: 'Projects' })).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('tab', { name: 'Projects' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('tab', { name: 'Activity' })).toBeInTheDocument()
|
||||
|
||||
const row = await screen.findByRole('option', { name: /Remote session/ })
|
||||
@@ -1051,13 +1031,22 @@ describe('SessionPickerDialog', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('queries the linked server sessions without a host-supplied server provider', async () => {
|
||||
renderPicker({
|
||||
remote: { serverId: 'srv-1', serverName: 'Kitchen', projectDirectory: '/home/me/app' },
|
||||
})
|
||||
|
||||
expect(await screen.findByRole('option', { name: /Remote session/ })).toBeInTheDocument()
|
||||
expect(mocks.lastSessionServerId).toBe('srv-1')
|
||||
})
|
||||
|
||||
it('navigates a remote active work row through the owning server', async () => {
|
||||
const onSelectRemoteSession = vi.fn()
|
||||
mocks.activeWorkGroups = {
|
||||
needsInput: [
|
||||
{
|
||||
key: '/home/me/app/ses_remote',
|
||||
session: session('ses_remote', 'Remote pending', '/home/me/app'),
|
||||
session: makeSession('ses_remote', 'Remote pending', '/home/me/app'),
|
||||
repo: null,
|
||||
serverId: 'srv_kitchen',
|
||||
serverName: 'Kitchen',
|
||||
|
||||
@@ -3,9 +3,8 @@ import { useQuery } from '@tanstack/react-query'
|
||||
import { format, startOfDay } from 'date-fns'
|
||||
import { ChevronsUpDown, MoreHorizontal, Pin, PinOff, Plus } from 'lucide-react'
|
||||
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
import { getOpenCodeLocation } from '@/api/opencode'
|
||||
import { OpenCodeServerProvider, useOpenCodeServerId } from '@/contexts/OpenCodeServerContext'
|
||||
import { serverScopedKey } from '@/lib/serverScope'
|
||||
import { openCodeLocationQueryOptions } from '@/lib/openCodeLocation'
|
||||
import type { Repo, Session } from '@/api/types'
|
||||
import { ACTIVE_WORK_GROUPS, MS_PER_MINUTE, formatActivityEmptyMessage } from '@/lib/activeWork'
|
||||
import { Button } from '@/components/ui/button'
|
||||
@@ -53,7 +52,6 @@ const NEAR_BOTTOM_PX = 240
|
||||
type SessionPickerTab = 'active' | 'sessions' | 'projects'
|
||||
|
||||
const SESSION_PICKER_TABS: SessionPickerTab[] = ['active', 'sessions', 'projects']
|
||||
const REMOTE_SESSION_PICKER_TABS: SessionPickerTab[] = ['active', 'sessions']
|
||||
|
||||
const SESSION_PICKER_TAB_LABELS: Record<SessionPickerTab, string> = {
|
||||
active: 'Activity',
|
||||
@@ -71,7 +69,7 @@ function sessionsTabLabel(scopeEnabled: boolean, allProjects: boolean): string {
|
||||
return allProjects ? 'All sessions' : 'This project'
|
||||
}
|
||||
|
||||
interface RemotePickerScope {
|
||||
export interface RemotePickerScope {
|
||||
serverId: string
|
||||
serverName?: string
|
||||
projectDirectory?: string
|
||||
@@ -601,10 +599,8 @@ function SessionPickerContent({
|
||||
|
||||
const serverId = useOpenCodeServerId()
|
||||
const locationQuery = useQuery({
|
||||
queryKey: serverScopedKey(['opencode', 'location', currentRepo?.fullPath], serverId),
|
||||
queryFn: () => getOpenCodeLocation(currentRepo!.fullPath, serverId),
|
||||
...openCodeLocationQueryOptions(currentRepo?.fullPath ?? '', serverId),
|
||||
enabled: !allProjects && Boolean(currentRepo?.fullPath),
|
||||
staleTime: 5 * 60 * 1000,
|
||||
})
|
||||
|
||||
const location = locationQuery.data
|
||||
@@ -1212,13 +1208,25 @@ export interface SessionPickerPanelProps {
|
||||
onSelectRepo: (repo: Repo) => void
|
||||
onNavigate: (path: string) => void
|
||||
remote?: RemotePickerScope
|
||||
remoteProjects?: boolean
|
||||
searchTrailing?: React.ReactNode
|
||||
onAddRepo?: () => void
|
||||
renderTitle?: (label: string) => React.ReactNode
|
||||
}
|
||||
|
||||
export function SessionPickerPanel({
|
||||
/**
|
||||
* Picker content shared by the desktop dialog and the mobile sheet. A remote scope supplies its own
|
||||
* server, so every host reads the linked server's sessions without wrapping the panel itself.
|
||||
*/
|
||||
export function SessionPickerPanel(props: SessionPickerPanelProps) {
|
||||
if (!props.remote) return <SessionPickerPanelBody {...props} />
|
||||
return (
|
||||
<OpenCodeServerProvider serverId={props.remote.serverId}>
|
||||
<SessionPickerPanelBody {...props} />
|
||||
</OpenCodeServerProvider>
|
||||
)
|
||||
}
|
||||
|
||||
function SessionPickerPanelBody({
|
||||
open,
|
||||
currentRepo,
|
||||
activeSessionID,
|
||||
@@ -1228,7 +1236,6 @@ export function SessionPickerPanel({
|
||||
onSelectRepo,
|
||||
onNavigate,
|
||||
remote,
|
||||
remoteProjects = false,
|
||||
searchTrailing,
|
||||
onAddRepo,
|
||||
renderTitle,
|
||||
@@ -1254,24 +1261,22 @@ export function SessionPickerPanel({
|
||||
[preferences],
|
||||
)
|
||||
const isRemote = remote !== undefined
|
||||
const pickerTabs = isRemote && !remoteProjects ? REMOTE_SESSION_PICKER_TABS : SESSION_PICKER_TABS
|
||||
const [tab, setTab] = useState<SessionPickerTab>('sessions')
|
||||
const [activeTab, setActiveTab] = useState<SessionPickerTab>('sessions')
|
||||
const [prevOpen, setPrevOpen] = useState(open)
|
||||
|
||||
if (prevOpen !== open) {
|
||||
setPrevOpen(open)
|
||||
if (open) setTab('sessions')
|
||||
if (open) setActiveTab('sessions')
|
||||
}
|
||||
|
||||
const activeTab: SessionPickerTab = pickerTabs.includes(tab) ? tab : 'sessions'
|
||||
const scopeEnabled = !isRemote && Boolean(currentRepo)
|
||||
const allProjects = scopeEnabled ? allProjectsPreference : true
|
||||
const readyRepo = scopeEnabled && currentRepo && isRepoReady(currentRepo) ? currentRepo : undefined
|
||||
|
||||
const toggleTab = useCallback(() => {
|
||||
focusSearchAfterSwitchRef.current = true
|
||||
setTab((current) => nextSessionPickerTab(current, pickerTabs))
|
||||
}, [pickerTabs])
|
||||
setActiveTab((current) => nextSessionPickerTab(current, SESSION_PICKER_TABS))
|
||||
}, [])
|
||||
|
||||
useShortcutActions({ switchPickerTab: open ? toggleTab : undefined })
|
||||
|
||||
@@ -1330,18 +1335,26 @@ export function SessionPickerPanel({
|
||||
const sessionsTrailing = withTrailing(newSessionButton)
|
||||
const projectsTrailing = withTrailing(addRepoButton)
|
||||
|
||||
const canToggleScope = scopeEnabled && activeTab === 'sessions'
|
||||
|
||||
/**
|
||||
* The sessions tab re-activates itself to toggle the scope. Pointer activation records whether the
|
||||
* tab was already selected before Radix activates it, so the click that follows only toggles a
|
||||
* tab that was already current. Keyboard activation toggles on Enter/Space directly and suppresses
|
||||
* the click Radix would otherwise synthesize for the same key press.
|
||||
*/
|
||||
const handleSessionsPointerDown = () => {
|
||||
scopePressRef.current = scopeEnabled && activeTab === 'sessions'
|
||||
scopePressRef.current = canToggleScope
|
||||
}
|
||||
|
||||
const handleSessionsClick = () => {
|
||||
if (!scopePressRef.current) return
|
||||
if (!canToggleScope || !scopePressRef.current) return
|
||||
scopePressRef.current = false
|
||||
toggleAllProjects()
|
||||
}
|
||||
|
||||
const handleSessionsKeyDown = (event: React.KeyboardEvent<HTMLButtonElement>) => {
|
||||
if (!scopeEnabled || activeTab !== 'sessions') return
|
||||
if (!canToggleScope) return
|
||||
if (event.key !== 'Enter' && event.key !== ' ') return
|
||||
event.preventDefault()
|
||||
toggleAllProjects()
|
||||
@@ -1351,7 +1364,7 @@ export function SessionPickerPanel({
|
||||
<>
|
||||
<Tabs
|
||||
value={activeTab}
|
||||
onValueChange={(value) => setTab(value as SessionPickerTab)}
|
||||
onValueChange={(value) => setActiveTab(value as SessionPickerTab)}
|
||||
className="flex min-h-0 w-full min-w-0 flex-1 flex-col gap-0"
|
||||
>
|
||||
<div className="shrink-0 px-4 pt-4 sm:px-0 sm:pt-6">
|
||||
@@ -1369,9 +1382,7 @@ export function SessionPickerPanel({
|
||||
<ChevronsUpDown aria-hidden="true" className="ml-1 h-3 w-3 shrink-0 opacity-60" />
|
||||
)}
|
||||
</TabsTrigger>
|
||||
{pickerTabs.includes('projects') && (
|
||||
<TabsTrigger value="projects">{SESSION_PICKER_TAB_LABELS.projects}</TabsTrigger>
|
||||
)}
|
||||
<TabsTrigger value="projects">{SESSION_PICKER_TAB_LABELS.projects}</TabsTrigger>
|
||||
</TabsList>
|
||||
</div>
|
||||
<TabsContent
|
||||
@@ -1423,33 +1434,31 @@ export function SessionPickerPanel({
|
||||
/>
|
||||
)}
|
||||
</TabsContent>
|
||||
{pickerTabs.includes('projects') && (
|
||||
<TabsContent
|
||||
value="projects"
|
||||
className="mt-0 flex min-h-0 w-full min-w-0 flex-1 flex-col px-0"
|
||||
>
|
||||
{remote ? (
|
||||
<RemoteProjectPickerContent
|
||||
serverId={remote.serverId}
|
||||
open={open}
|
||||
searchInputRef={projectSearchInputRef}
|
||||
searchTrailing={projectsTrailing}
|
||||
onOpenProject={onNavigate}
|
||||
onSelectSession={onNavigate}
|
||||
/>
|
||||
) : (
|
||||
<ProjectPickerContent
|
||||
open={open}
|
||||
currentRepo={currentRepo}
|
||||
onSelectRepo={onSelectRepo}
|
||||
onNavigate={onNavigate}
|
||||
switchHint={switchHint}
|
||||
searchInputRef={projectSearchInputRef}
|
||||
searchTrailing={projectsTrailing}
|
||||
/>
|
||||
)}
|
||||
</TabsContent>
|
||||
)}
|
||||
<TabsContent
|
||||
value="projects"
|
||||
className="mt-0 flex min-h-0 w-full min-w-0 flex-1 flex-col px-0"
|
||||
>
|
||||
{remote ? (
|
||||
<RemoteProjectPickerContent
|
||||
serverId={remote.serverId}
|
||||
open={open}
|
||||
searchInputRef={projectSearchInputRef}
|
||||
searchTrailing={projectsTrailing}
|
||||
onOpenProject={onNavigate}
|
||||
onSelectSession={onNavigate}
|
||||
/>
|
||||
) : (
|
||||
<ProjectPickerContent
|
||||
open={open}
|
||||
currentRepo={currentRepo}
|
||||
onSelectRepo={onSelectRepo}
|
||||
onNavigate={onNavigate}
|
||||
switchHint={switchHint}
|
||||
searchInputRef={projectSearchInputRef}
|
||||
searchTrailing={projectsTrailing}
|
||||
/>
|
||||
)}
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
{addRepoOpen && !onAddRepo && <AddRepoDialog open onOpenChange={setAddRepoOpen} />}
|
||||
</>
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { render, screen, fireEvent, act } from '@testing-library/react'
|
||||
import { MemoryRouter, Route, Routes, useLocation, useNavigationType } from 'react-router-dom'
|
||||
import { render, screen, fireEvent, act, waitFor } from '@testing-library/react'
|
||||
import { MemoryRouter, Route, Routes } from 'react-router-dom'
|
||||
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
import type { Repo, Session } from '@/api/types'
|
||||
import type { ActiveWorkGroups, ActiveWorkItem } from '@/lib/activeWork'
|
||||
import { DEFAULT_ACTIVITY_WINDOW_MINUTES } from '@/api/types/settings'
|
||||
import { KeyboardShortcutsProvider } from '@/contexts/KeyboardShortcutsContext'
|
||||
import { useSidebarServerStore } from '@/stores/sidebarServerStore'
|
||||
import { stubMatchMedia } from '@/test/test-utils'
|
||||
import { LocationCatcher, stubMatchMedia } from '@/test/test-utils'
|
||||
import { makeRepo, makeSession } from '@/test/fixtures/session-picker'
|
||||
import { SessionPickerSheet } from './SessionPickerSheet'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
@@ -22,6 +23,7 @@ const mocks = vi.hoisted(() => ({
|
||||
| undefined,
|
||||
getOpenCodeLocation: vi.fn(),
|
||||
listProjects: vi.fn(),
|
||||
getSession: vi.fn(),
|
||||
repos: [] as Repo[],
|
||||
activeWorkGroups: { needsInput: [], running: [], recent: [] } as ActiveWorkGroups,
|
||||
}))
|
||||
@@ -32,7 +34,12 @@ vi.mock('@/hooks/useSettings', () => ({
|
||||
|
||||
vi.mock('@/api/opencode', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/api/opencode')>()
|
||||
return { ...actual, getOpenCodeLocation: mocks.getOpenCodeLocation, listProjects: mocks.listProjects }
|
||||
return {
|
||||
...actual,
|
||||
getOpenCodeLocation: mocks.getOpenCodeLocation,
|
||||
listProjects: mocks.listProjects,
|
||||
getSession: mocks.getSession,
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/api/repos', () => ({
|
||||
@@ -112,30 +119,6 @@ vi.mock('@/stores/sessionStatusStore', async (importOriginal) => {
|
||||
return { ...actual, useSessionStatusForSession: () => ({ type: 'idle' }) }
|
||||
})
|
||||
|
||||
function session(id: string, title: string, directory: string, updated = Date.now()): Session {
|
||||
return {
|
||||
id,
|
||||
projectID: 'proj',
|
||||
title,
|
||||
time: { created: updated, updated },
|
||||
location: { directory },
|
||||
cost: 0,
|
||||
tokens: {},
|
||||
} as unknown as Session
|
||||
}
|
||||
|
||||
function repo(id: number, name: string, fullPath: string): Repo {
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
localPath: fullPath,
|
||||
fullPath,
|
||||
defaultBranch: 'main',
|
||||
cloneStatus: 'ready',
|
||||
clonedAt: 0,
|
||||
}
|
||||
}
|
||||
|
||||
function activeWorkItem(
|
||||
id: string,
|
||||
directory: string,
|
||||
@@ -145,8 +128,8 @@ function activeWorkItem(
|
||||
return {
|
||||
key: `${server?.id ?? LOCAL_OPENCODE_SERVER_ID}:${id}`,
|
||||
state: 'recent',
|
||||
session: session(id, `Active ${id}`, directory, now),
|
||||
repo: server ? null : repo(1, 'alpha', directory),
|
||||
session: makeSession(id, `Active ${id}`, directory, now),
|
||||
repo: server ? null : makeRepo(1, 'alpha', directory),
|
||||
serverId: server?.id ?? null,
|
||||
serverName: server?.name ?? null,
|
||||
updatedAt: now,
|
||||
@@ -154,17 +137,16 @@ function activeWorkItem(
|
||||
}
|
||||
}
|
||||
|
||||
function LocationProbe() {
|
||||
const location = useLocation()
|
||||
const navigationType = useNavigationType()
|
||||
return (
|
||||
<div data-testid="location">{`${location.pathname}${location.search} ${navigationType}`}</div>
|
||||
)
|
||||
}
|
||||
|
||||
function renderSheet(initialEntries: string[] = ['/repos/1?mobileTab=sessions']) {
|
||||
function renderSheet(
|
||||
initialEntries: string[] = ['/repos/1?mobileTab=sessions'],
|
||||
options: { isOpen?: boolean; cachedRepos?: Repo[] } = {},
|
||||
) {
|
||||
const onClose = vi.fn()
|
||||
const capturedPathname: { current: string } = { current: '' }
|
||||
const capturedSearch: { current: string } = { current: '' }
|
||||
const capturedNavigationType: { current: string } = { current: '' }
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
if (options.cachedRepos) queryClient.setQueryData(['repos'], options.cachedRepos)
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<KeyboardShortcutsProvider>
|
||||
@@ -174,8 +156,12 @@ function renderSheet(initialEntries: string[] = ['/repos/1?mobileTab=sessions'])
|
||||
path="*"
|
||||
element={
|
||||
<>
|
||||
<SessionPickerSheet isOpen onClose={onClose} />
|
||||
<LocationProbe />
|
||||
<SessionPickerSheet isOpen={options.isOpen ?? true} onClose={onClose} />
|
||||
<LocationCatcher
|
||||
capturedPathname={capturedPathname}
|
||||
capturedSearch={capturedSearch}
|
||||
capturedNavigationType={capturedNavigationType}
|
||||
/>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
@@ -184,7 +170,11 @@ function renderSheet(initialEntries: string[] = ['/repos/1?mobileTab=sessions'])
|
||||
</KeyboardShortcutsProvider>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
return { onClose }
|
||||
return {
|
||||
onClose,
|
||||
location: () =>
|
||||
`${capturedPathname.current}${capturedSearch.current} ${capturedNavigationType.current}`,
|
||||
}
|
||||
}
|
||||
|
||||
describe('SessionPickerSheet', () => {
|
||||
@@ -193,7 +183,7 @@ describe('SessionPickerSheet', () => {
|
||||
localStorage.clear()
|
||||
stubMatchMedia(true)
|
||||
useSidebarServerStore.setState({ serverId: LOCAL_OPENCODE_SERVER_ID })
|
||||
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
|
||||
mocks.repos = [makeRepo(1, 'alpha', '/w/a'), makeRepo(2, 'beta', '/w/b')]
|
||||
mocks.sessionsData = []
|
||||
mocks.lastDirectories = []
|
||||
mocks.lastAllDirectories = false
|
||||
@@ -205,6 +195,7 @@ describe('SessionPickerSheet', () => {
|
||||
project: { id: 'global', directory: '/w/a', canonical: '/w/a' },
|
||||
}
|
||||
mocks.getOpenCodeLocation.mockResolvedValue(mocks.locationData)
|
||||
mocks.getSession.mockResolvedValue(null)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
@@ -222,37 +213,35 @@ describe('SessionPickerSheet', () => {
|
||||
})
|
||||
|
||||
it('navigates to the chosen session, replacing the sheet history entry', async () => {
|
||||
mocks.sessionsData = [session('ses_one', 'Solo session', '/w/a')]
|
||||
mocks.sessionsData = [makeSession('ses_one', 'Solo session', '/w/a')]
|
||||
|
||||
renderSheet()
|
||||
const { location } = renderSheet()
|
||||
|
||||
const row = await screen.findByRole('option', { name: /Solo session/ })
|
||||
fireEvent.click(row)
|
||||
|
||||
expect(screen.getByTestId('location')).toHaveTextContent('/repos/1/sessions/ses_one REPLACE')
|
||||
expect(location()).toBe('/repos/1/sessions/ses_one REPLACE')
|
||||
})
|
||||
|
||||
it('closes instead of navigating when the chosen session is already open', async () => {
|
||||
mocks.sessionsData = [session('ses_one', 'Solo session', '/w/a')]
|
||||
mocks.sessionsData = [makeSession('ses_one', 'Solo session', '/w/a')]
|
||||
|
||||
const { onClose } = renderSheet(['/repos/1/sessions/ses_one?mobileTab=sessions'])
|
||||
const { onClose, location } = renderSheet(['/repos/1/sessions/ses_one?mobileTab=sessions'])
|
||||
|
||||
const row = await screen.findByRole('option', { name: /Solo session/ })
|
||||
fireEvent.click(row)
|
||||
|
||||
expect(onClose).toHaveBeenCalled()
|
||||
expect(screen.getByTestId('location')).toHaveTextContent(
|
||||
'/repos/1/sessions/ses_one?mobileTab=sessions POP',
|
||||
)
|
||||
expect(location()).toBe('/repos/1/sessions/ses_one?mobileTab=sessions POP')
|
||||
})
|
||||
|
||||
it('creates a session in the current repo from the header action and opens it', async () => {
|
||||
renderSheet()
|
||||
const { location } = renderSheet()
|
||||
|
||||
fireEvent.click(await screen.findByRole('button', { name: 'New session in alpha' }))
|
||||
|
||||
expect(mocks.createSessionDirectories).toEqual(['/w/a'])
|
||||
expect(screen.getByTestId('location')).toHaveTextContent('/repos/1/sessions/ses_new REPLACE')
|
||||
expect(location()).toBe('/repos/1/sessions/ses_new REPLACE')
|
||||
})
|
||||
|
||||
it('opens the add repository dialog from the projects tab header action', async () => {
|
||||
@@ -267,9 +256,9 @@ describe('SessionPickerSheet', () => {
|
||||
|
||||
it('lists and opens the linked server sessions when a linked server is selected', async () => {
|
||||
useSidebarServerStore.setState({ serverId: 'srv_kitchen' })
|
||||
mocks.sessionsData = [session('ses_remote', 'Remote session', '/home/me/app')]
|
||||
mocks.sessionsData = [makeSession('ses_remote', 'Remote session', '/home/me/app')]
|
||||
|
||||
renderSheet()
|
||||
const { location } = renderSheet()
|
||||
|
||||
const row = await screen.findByRole('option', { name: /Remote session/ })
|
||||
expect(row).toHaveTextContent('Kitchen')
|
||||
@@ -280,9 +269,7 @@ describe('SessionPickerSheet', () => {
|
||||
|
||||
fireEvent.click(row)
|
||||
|
||||
expect(screen.getByTestId('location')).toHaveTextContent(
|
||||
'/servers/srv_kitchen/sessions/ses_remote REPLACE',
|
||||
)
|
||||
expect(location()).toBe('/servers/srv_kitchen/sessions/ses_remote REPLACE')
|
||||
})
|
||||
|
||||
it('lists the linked server projects on the projects tab and opens one', async () => {
|
||||
@@ -297,18 +284,16 @@ describe('SessionPickerSheet', () => {
|
||||
},
|
||||
])
|
||||
|
||||
renderSheet()
|
||||
const { location } = renderSheet()
|
||||
|
||||
fireEvent.mouseDown(screen.getByRole('tab', { name: 'Projects' }))
|
||||
fireEvent.click(await screen.findByText('Alpha'))
|
||||
|
||||
expect(screen.getByTestId('location')).toHaveTextContent(
|
||||
'/servers/srv_kitchen/projects?directory=%2Fprojects%2Falpha REPLACE',
|
||||
)
|
||||
expect(location()).toBe('/servers/srv_kitchen/projects?directory=%2Fprojects%2Falpha REPLACE')
|
||||
})
|
||||
|
||||
it('follows the sidebar server selection to list that server', async () => {
|
||||
mocks.sessionsData = [session('ses_remote', 'Remote session', '/home/me/app')]
|
||||
mocks.sessionsData = [makeSession('ses_remote', 'Remote session', '/home/me/app')]
|
||||
|
||||
renderSheet()
|
||||
|
||||
@@ -328,12 +313,12 @@ describe('SessionPickerSheet', () => {
|
||||
recent: [activeWorkItem('ses_active', '/w/a')],
|
||||
}
|
||||
|
||||
renderSheet()
|
||||
const { location } = renderSheet()
|
||||
|
||||
fireEvent.mouseDown(screen.getByRole('tab', { name: 'Activity' }))
|
||||
fireEvent.click(await screen.findByRole('option', { name: /Active ses_active/ }))
|
||||
|
||||
expect(screen.getByTestId('location')).toHaveTextContent('/repos/1/sessions/ses_active REPLACE')
|
||||
expect(location()).toBe('/repos/1/sessions/ses_active REPLACE')
|
||||
})
|
||||
|
||||
it('opens a remote activity row on its own server while the local server is selected', async () => {
|
||||
@@ -343,14 +328,12 @@ describe('SessionPickerSheet', () => {
|
||||
recent: [activeWorkItem('ses_kitchen', '/home/me/app', { id: 'srv_kitchen', name: 'Kitchen' })],
|
||||
}
|
||||
|
||||
renderSheet()
|
||||
const { location } = renderSheet()
|
||||
|
||||
fireEvent.mouseDown(screen.getByRole('tab', { name: 'Activity' }))
|
||||
fireEvent.click(await screen.findByRole('option', { name: /Active ses_kitchen/ }))
|
||||
|
||||
expect(screen.getByTestId('location')).toHaveTextContent(
|
||||
'/servers/srv_kitchen/sessions/ses_kitchen REPLACE',
|
||||
)
|
||||
expect(location()).toBe('/servers/srv_kitchen/sessions/ses_kitchen REPLACE')
|
||||
})
|
||||
|
||||
it('opens a remote activity row of the same session id that is open on another server', async () => {
|
||||
@@ -361,26 +344,28 @@ describe('SessionPickerSheet', () => {
|
||||
recent: [activeWorkItem('ses_shared', '/home/me/hall', { id: 'srv_hall', name: 'Hall' })],
|
||||
}
|
||||
|
||||
const { onClose } = renderSheet(['/servers/srv_kitchen/sessions/ses_shared?mobileTab=sessions'])
|
||||
const { onClose, location } = renderSheet([
|
||||
'/servers/srv_kitchen/sessions/ses_shared?mobileTab=sessions',
|
||||
])
|
||||
|
||||
fireEvent.mouseDown(screen.getByRole('tab', { name: 'Activity' }))
|
||||
fireEvent.click(await screen.findByRole('option', { name: /Active ses_shared/ }))
|
||||
|
||||
expect(onClose).not.toHaveBeenCalled()
|
||||
expect(screen.getByTestId('location')).toHaveTextContent(
|
||||
'/servers/srv_hall/sessions/ses_shared REPLACE',
|
||||
)
|
||||
expect(location()).toBe('/servers/srv_hall/sessions/ses_shared REPLACE')
|
||||
})
|
||||
|
||||
it('opens a local session row that shares the id of the open remote session', async () => {
|
||||
mocks.sessionsData = [session('ses_shared', 'Shared session', '/w/a')]
|
||||
mocks.sessionsData = [makeSession('ses_shared', 'Shared session', '/w/a')]
|
||||
|
||||
const { onClose } = renderSheet(['/servers/srv_kitchen/sessions/ses_shared?mobileTab=sessions'])
|
||||
const { onClose, location } = renderSheet([
|
||||
'/servers/srv_kitchen/sessions/ses_shared?mobileTab=sessions',
|
||||
])
|
||||
|
||||
fireEvent.click(await screen.findByRole('option', { name: /Shared session/ }))
|
||||
|
||||
expect(onClose).not.toHaveBeenCalled()
|
||||
expect(screen.getByTestId('location')).toHaveTextContent('/repos/1/sessions/ses_shared REPLACE')
|
||||
expect(location()).toBe('/repos/1/sessions/ses_shared REPLACE')
|
||||
})
|
||||
|
||||
it('opens a session row of another linked server than the selected one', async () => {
|
||||
@@ -391,13 +376,67 @@ describe('SessionPickerSheet', () => {
|
||||
recent: [activeWorkItem('ses_hall', '/home/me/hall', { id: 'srv_hall', name: 'Hall' })],
|
||||
}
|
||||
|
||||
renderSheet()
|
||||
const { location } = renderSheet()
|
||||
|
||||
fireEvent.mouseDown(screen.getByRole('tab', { name: 'Activity' }))
|
||||
fireEvent.click(await screen.findByRole('option', { name: /Active ses_hall/ }))
|
||||
|
||||
expect(screen.getByTestId('location')).toHaveTextContent(
|
||||
'/servers/srv_hall/sessions/ses_hall REPLACE',
|
||||
expect(location()).toBe('/servers/srv_hall/sessions/ses_hall REPLACE')
|
||||
})
|
||||
|
||||
it('keeps the assistant session flag when choosing another session of the same repo', async () => {
|
||||
mocks.sessionsData = [makeSession('ses_b', 'Second assistant session', '/w/a')]
|
||||
|
||||
const { location } = renderSheet(['/repos/1/sessions/ses_a?assistant=1&mobileTab=sessions'])
|
||||
|
||||
fireEvent.click(await screen.findByRole('option', { name: /Second assistant session/ }))
|
||||
|
||||
expect(location()).toBe('/repos/1/sessions/ses_b?assistant=1 REPLACE')
|
||||
})
|
||||
|
||||
it('drops the assistant session flag when choosing a session of another repo', async () => {
|
||||
localStorage.setItem('oc:session-picker:all-projects', 'true')
|
||||
mocks.sessionsData = [
|
||||
makeSession('ses_a', 'Assistant session', '/w/a'),
|
||||
makeSession('ses_b', 'Beta session', '/w/b'),
|
||||
]
|
||||
|
||||
const { location } = renderSheet(['/repos/1/sessions/ses_a?assistant=1&mobileTab=sessions'])
|
||||
|
||||
fireEvent.click(await screen.findByRole('option', { name: /Beta session/ }))
|
||||
|
||||
expect(location()).toBe('/repos/2/sessions/ses_b REPLACE')
|
||||
})
|
||||
|
||||
it('scopes the sheet to the open remote session directory on a linked server session route', async () => {
|
||||
useSidebarServerStore.setState({ serverId: 'srv_kitchen' })
|
||||
mocks.getSession.mockResolvedValue(makeSession('ses_remote', 'Remote session', '/home/me/app'))
|
||||
|
||||
renderSheet(['/servers/srv_kitchen/sessions/ses_remote?mobileTab=sessions'])
|
||||
|
||||
await waitFor(() => expect(mocks.lastDirectories).toEqual(['/home/me/app']))
|
||||
expect(mocks.lastAllDirectories).toBe(false)
|
||||
})
|
||||
|
||||
it('does not resolve the remote session directory while the sheet is closed', async () => {
|
||||
useSidebarServerStore.setState({ serverId: 'srv_kitchen' })
|
||||
|
||||
renderSheet(['/servers/srv_kitchen/sessions/ses_remote'], { isOpen: false })
|
||||
|
||||
await waitFor(() => expect(mocks.getSession).not.toHaveBeenCalled())
|
||||
})
|
||||
|
||||
it('prefetches the project location on a repo route while the sheet is closed', async () => {
|
||||
renderSheet(['/repos/1'], { isOpen: false, cachedRepos: mocks.repos })
|
||||
|
||||
await waitFor(() =>
|
||||
expect(mocks.getOpenCodeLocation).toHaveBeenCalledWith('/w/a', LOCAL_OPENCODE_SERVER_ID),
|
||||
)
|
||||
})
|
||||
|
||||
it('does not prefetch the project location outside a repo route', async () => {
|
||||
renderSheet(['/'], { isOpen: false, cachedRepos: mocks.repos })
|
||||
|
||||
await waitFor(() => expect(mocks.getOpenCodeLocation).not.toHaveBeenCalled())
|
||||
})
|
||||
})
|
||||
@@ -1,14 +1,11 @@
|
||||
import { useCallback, useState } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
import type { Repo, Session } from '@/api/types'
|
||||
import { useState } from 'react'
|
||||
import { BottomSheet } from '@/components/ui/bottom-sheet'
|
||||
import { LinkedServersNav } from '@/components/navigation/LinkedServersNav'
|
||||
import { AddRepoDialog } from '@/components/repo/AddRepoDialog'
|
||||
import { SessionPickerPanel } from '@/components/session/SessionPickerDialog'
|
||||
import { OpenCodeServerProvider } from '@/contexts/OpenCodeServerContext'
|
||||
import { useSessionPickerRouteScope } from '@/hooks/useSessionPickerRouteScope'
|
||||
import { getRepoPath, getServerSessionPath, getSessionPath } from '@/lib/navigation'
|
||||
import { useSessionPickerLocationPrefetch } from '@/hooks/useSessionPickerLocationPrefetch'
|
||||
import { useSessionPickerNavigation } from '@/hooks/useSessionPickerNavigation'
|
||||
|
||||
interface SessionPickerSheetProps {
|
||||
isOpen: boolean
|
||||
@@ -16,59 +13,18 @@ interface SessionPickerSheetProps {
|
||||
}
|
||||
|
||||
export function SessionPickerSheet({ isOpen, onClose }: SessionPickerSheetProps) {
|
||||
const navigate = useNavigate()
|
||||
const [addRepoOpen, setAddRepoOpen] = useState(false)
|
||||
const { currentRepo, activeSessionID, activeServerId, remote } = useSessionPickerRouteScope(isOpen)
|
||||
|
||||
const navigateReplacing = useCallback(
|
||||
(path: string) => {
|
||||
navigate(path, { replace: true })
|
||||
},
|
||||
[navigate],
|
||||
)
|
||||
|
||||
const handleSelectSession = useCallback(
|
||||
(session: Session, repo: Repo) => {
|
||||
if (session.id === activeSessionID && activeServerId === LOCAL_OPENCODE_SERVER_ID) {
|
||||
onClose()
|
||||
return
|
||||
}
|
||||
navigateReplacing(getSessionPath(repo.id, session.id))
|
||||
},
|
||||
[activeServerId, activeSessionID, navigateReplacing, onClose],
|
||||
)
|
||||
|
||||
const handleSelectRemoteSession = useCallback(
|
||||
(session: Session, serverId: string) => {
|
||||
if (session.id === activeSessionID && serverId === activeServerId) {
|
||||
onClose()
|
||||
return
|
||||
}
|
||||
navigateReplacing(getServerSessionPath(serverId, session.id))
|
||||
},
|
||||
[activeServerId, activeSessionID, navigateReplacing, onClose],
|
||||
)
|
||||
|
||||
const handleDeleteActiveSession = useCallback(() => {
|
||||
if (!currentRepo) {
|
||||
onClose()
|
||||
return
|
||||
}
|
||||
navigateReplacing(getRepoPath(currentRepo.id))
|
||||
}, [currentRepo, navigateReplacing, onClose])
|
||||
const { currentRepo, activeSessionID, remote } = useSessionPickerRouteScope(isOpen)
|
||||
const pickerNavigation = useSessionPickerNavigation({ mode: 'replace', onClose })
|
||||
useSessionPickerLocationPrefetch()
|
||||
|
||||
const panel = isOpen ? (
|
||||
<SessionPickerPanel
|
||||
open={isOpen}
|
||||
currentRepo={currentRepo}
|
||||
activeSessionID={activeSessionID}
|
||||
onSelectSession={handleSelectSession}
|
||||
onSelectRemoteSession={handleSelectRemoteSession}
|
||||
onDeleteActiveSession={handleDeleteActiveSession}
|
||||
onSelectRepo={(repo) => navigateReplacing(getRepoPath(repo.id))}
|
||||
onNavigate={navigateReplacing}
|
||||
{...pickerNavigation}
|
||||
remote={remote}
|
||||
remoteProjects
|
||||
searchTrailing={<LinkedServersNav variant="header" />}
|
||||
onAddRepo={() => {
|
||||
onClose()
|
||||
@@ -80,11 +36,7 @@ export function SessionPickerSheet({ isOpen, onClose }: SessionPickerSheetProps)
|
||||
return (
|
||||
<>
|
||||
<BottomSheet isOpen={isOpen} onClose={onClose} heightClass="h-[90dvh]" ariaLabel="Sessions">
|
||||
{remote ? (
|
||||
<OpenCodeServerProvider serverId={remote.serverId}>{panel}</OpenCodeServerProvider>
|
||||
) : (
|
||||
panel
|
||||
)}
|
||||
{panel}
|
||||
</BottomSheet>
|
||||
<AddRepoDialog open={addRepoOpen} onOpenChange={setAddRepoOpen} />
|
||||
</>
|
||||
|
||||
@@ -1,8 +1,15 @@
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { useState } from 'react'
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { stubMatchMedia } from '@/test/test-utils'
|
||||
import { BottomSheet, BottomSheetHeader, BottomSheetContent } from './bottom-sheet'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import { useSwipeDismiss } from '@/hooks/useMobile'
|
||||
|
||||
vi.mock('@/hooks/useMobile', () => ({
|
||||
@@ -36,6 +43,34 @@ function AutoFocusSheetHost() {
|
||||
)
|
||||
}
|
||||
|
||||
function OpenSheetHost({ onClose }: { onClose: () => void }) {
|
||||
const [open, setOpen] = useState(false)
|
||||
return (
|
||||
<>
|
||||
<button type="button" onClick={() => setOpen(true)}>open sheet</button>
|
||||
<BottomSheet isOpen={open} onClose={() => { onClose(); setOpen(false) }} ariaLabel="Test sheet">
|
||||
<button type="button">first</button>
|
||||
<button type="button">last</button>
|
||||
</BottomSheet>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function SheetWithMenu({ onClose }: { onClose: () => void }) {
|
||||
return (
|
||||
<BottomSheet isOpen onClose={onClose} ariaLabel="Test sheet">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button type="button">row actions</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent>
|
||||
<DropdownMenuItem>Delete session</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</BottomSheet>
|
||||
)
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
Reflect.deleteProperty(window, 'matchMedia')
|
||||
})
|
||||
@@ -43,6 +78,11 @@ afterEach(() => {
|
||||
describe('BottomSheet', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(useSwipeDismiss).mockReturnValue({
|
||||
bind: vi.fn(),
|
||||
swipeProgress: 0,
|
||||
swipeStyles: {},
|
||||
})
|
||||
})
|
||||
|
||||
it('renders when isOpen is true', () => {
|
||||
@@ -55,17 +95,56 @@ describe('BottomSheet', () => {
|
||||
})
|
||||
|
||||
it('does not render when isOpen is false', async () => {
|
||||
const { container } = render(
|
||||
render(
|
||||
<BottomSheet isOpen={false} onClose={() => {}} ariaLabel="Test sheet">
|
||||
<div>Test content</div>
|
||||
</BottomSheet>,
|
||||
)
|
||||
await waitFor(() => {
|
||||
expect(container.querySelector('[role="dialog"]')).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
it('calls onClose when backdrop is clicked', () => {
|
||||
it('exposes the sheet as a labelled modal dialog', () => {
|
||||
render(
|
||||
<BottomSheet isOpen onClose={() => {}} ariaLabel="Test sheet">
|
||||
<div>Test content</div>
|
||||
</BottomSheet>,
|
||||
)
|
||||
|
||||
const dialog = screen.getByRole('dialog', { name: 'Test sheet' })
|
||||
expect(dialog).toHaveAttribute('aria-modal', 'true')
|
||||
expect(dialog).toHaveAttribute('data-state', 'open')
|
||||
})
|
||||
|
||||
it('moves focus into the sheet panel on open', () => {
|
||||
render(
|
||||
<BottomSheet isOpen onClose={() => {}} ariaLabel="Test sheet">
|
||||
<button type="button">inside</button>
|
||||
</BottomSheet>,
|
||||
)
|
||||
|
||||
expect(screen.getByRole('dialog', { name: 'Test sheet' })).toHaveFocus()
|
||||
})
|
||||
|
||||
it('keeps tab focus inside the sheet', () => {
|
||||
render(
|
||||
<BottomSheet isOpen onClose={() => {}} ariaLabel="Test sheet">
|
||||
<button type="button">first</button>
|
||||
<button type="button">last</button>
|
||||
</BottomSheet>,
|
||||
)
|
||||
|
||||
const first = screen.getByRole('button', { name: 'first' })
|
||||
const last = screen.getByRole('button', { name: 'last' })
|
||||
last.focus()
|
||||
|
||||
fireEvent.keyDown(last, { key: 'Tab' })
|
||||
|
||||
expect(first).toHaveFocus()
|
||||
})
|
||||
|
||||
it('calls onClose when the backdrop is clicked', async () => {
|
||||
const handleClose = vi.fn()
|
||||
render(
|
||||
<BottomSheet isOpen onClose={handleClose} ariaLabel="Test sheet">
|
||||
@@ -73,10 +152,12 @@ describe('BottomSheet', () => {
|
||||
</BottomSheet>,
|
||||
)
|
||||
const backdrop = document.querySelector('.bg-black\\/40')
|
||||
if (backdrop) {
|
||||
fireEvent.click(backdrop)
|
||||
}
|
||||
expect(handleClose).toHaveBeenCalled()
|
||||
if (!backdrop) throw new Error('Missing sheet backdrop')
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 0))
|
||||
fireEvent.pointerDown(backdrop)
|
||||
|
||||
await waitFor(() => expect(handleClose).toHaveBeenCalledTimes(1))
|
||||
})
|
||||
|
||||
it('calls onClose when Escape key is pressed', () => {
|
||||
@@ -87,7 +168,26 @@ describe('BottomSheet', () => {
|
||||
</BottomSheet>,
|
||||
)
|
||||
fireEvent.keyDown(document, { key: 'Escape' })
|
||||
expect(handleClose).toHaveBeenCalled()
|
||||
expect(handleClose).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('closes only the nested menu when Escape is pressed inside it', async () => {
|
||||
const user = userEvent.setup()
|
||||
const handleClose = vi.fn()
|
||||
render(<SheetWithMenu onClose={handleClose} />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'row actions' }))
|
||||
expect(await screen.findByRole('menu')).toBeInTheDocument()
|
||||
|
||||
await user.keyboard('{Escape}')
|
||||
|
||||
await waitFor(() => expect(screen.queryByRole('menu')).not.toBeInTheDocument())
|
||||
expect(handleClose).not.toHaveBeenCalled()
|
||||
expect(screen.getByRole('dialog', { name: 'Test sheet' })).toBeInTheDocument()
|
||||
|
||||
await user.keyboard('{Escape}')
|
||||
|
||||
expect(handleClose).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('applies pb-safe class', () => {
|
||||
@@ -96,7 +196,7 @@ describe('BottomSheet', () => {
|
||||
<div>Test content</div>
|
||||
</BottomSheet>,
|
||||
)
|
||||
const dialog = document.querySelector('[role="dialog"]')
|
||||
const dialog = screen.getByRole('dialog', { name: 'Test sheet' })
|
||||
expect(dialog).toBeInTheDocument()
|
||||
})
|
||||
|
||||
@@ -118,7 +218,7 @@ describe('BottomSheet', () => {
|
||||
<div>Test content</div>
|
||||
</BottomSheet>,
|
||||
)
|
||||
const dialog = document.querySelector('[role="dialog"]')
|
||||
const dialog = screen.getByRole('dialog', { name: 'Test sheet' })
|
||||
expect(dialog).toHaveClass('h-[50dvh]')
|
||||
})
|
||||
|
||||
@@ -172,10 +272,10 @@ describe('BottomSheet', () => {
|
||||
const panelElement = document.querySelector('[aria-modal="true"]')
|
||||
expect(panelElement).toBeInTheDocument()
|
||||
|
||||
expect(mockBind).toHaveBeenCalled()
|
||||
expect(mockBind).toHaveBeenCalledWith(panelElement)
|
||||
})
|
||||
|
||||
it('moves focus to the chat prompt on desktop when it closes', () => {
|
||||
it('moves focus to the chat prompt on desktop when it closes', async () => {
|
||||
stubMatchMedia(true)
|
||||
const { rerender } = renderSheet(false)
|
||||
|
||||
@@ -198,10 +298,10 @@ describe('BottomSheet', () => {
|
||||
</>,
|
||||
)
|
||||
|
||||
expect(screen.getByLabelText('prompt')).toHaveFocus()
|
||||
await waitFor(() => expect(screen.getByLabelText('prompt')).toHaveFocus())
|
||||
})
|
||||
|
||||
it('does not refocus the chat prompt on touch when it closes', () => {
|
||||
it('does not refocus the chat prompt on touch when it closes', async () => {
|
||||
stubMatchMedia(false)
|
||||
const { rerender } = renderSheet(false)
|
||||
|
||||
@@ -224,6 +324,7 @@ describe('BottomSheet', () => {
|
||||
</>,
|
||||
)
|
||||
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
|
||||
expect(screen.getByLabelText('prompt')).not.toHaveFocus()
|
||||
})
|
||||
|
||||
@@ -241,7 +342,7 @@ describe('BottomSheet', () => {
|
||||
await waitFor(() => expect(opener).toHaveFocus())
|
||||
})
|
||||
|
||||
it('captures the opener when mounted already open and restores it on close', () => {
|
||||
it('captures the opener when mounted already open and restores it on close', async () => {
|
||||
stubMatchMedia(true)
|
||||
const { rerender } = render(
|
||||
<button type="button">opener</button>,
|
||||
@@ -267,7 +368,22 @@ describe('BottomSheet', () => {
|
||||
</>,
|
||||
)
|
||||
|
||||
expect(opener).toHaveFocus()
|
||||
await waitFor(() => expect(opener).toHaveFocus())
|
||||
})
|
||||
|
||||
it('returns focus to the opener after the sheet closes through the keyboard', async () => {
|
||||
const user = userEvent.setup()
|
||||
const handleClose = vi.fn()
|
||||
render(<OpenSheetHost onClose={handleClose} />)
|
||||
|
||||
const opener = screen.getByRole('button', { name: 'open sheet' })
|
||||
await user.click(opener)
|
||||
await waitFor(() => expect(screen.getByRole('dialog', { name: 'Test sheet' })).toHaveFocus())
|
||||
|
||||
await user.keyboard('{Escape}')
|
||||
|
||||
expect(handleClose).toHaveBeenCalledTimes(1)
|
||||
await waitFor(() => expect(opener).toHaveFocus())
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
import { useEffect, useState, useRef } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
Content as DialogContent,
|
||||
Overlay as DialogOverlay,
|
||||
Portal as DialogPortal,
|
||||
Root as DialogRoot,
|
||||
Title as DialogTitle,
|
||||
} from '@radix-ui/react-dialog'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { MODAL_TRANSITION_MS } from '@/lib/utils'
|
||||
import { useSwipeDismiss } from '@/hooks/useMobile'
|
||||
import { useRestoreFocusOnClose } from '@/hooks/useRestoreFocusOnClose'
|
||||
import { getFocusedElement, restoreOverlayFocus } from '@/lib/overlayFocus'
|
||||
|
||||
export interface BottomSheetProps {
|
||||
isOpen: boolean
|
||||
@@ -25,9 +31,23 @@ export function BottomSheet({
|
||||
dismissible = true,
|
||||
}: BottomSheetProps) {
|
||||
const [shouldRender, setShouldRender] = useState(false)
|
||||
const [openState, setOpenState] = useState(() => ({
|
||||
open: isOpen,
|
||||
returnFocus: isOpen ? getFocusedElement() : null,
|
||||
}))
|
||||
const panelRef = useRef<HTMLDivElement>(null)
|
||||
const [panelElement, setPanelElement] = useState<HTMLDivElement | null>(null)
|
||||
const setPanelRef = useCallback((node: HTMLDivElement | null) => {
|
||||
panelRef.current = node
|
||||
setPanelElement(node)
|
||||
}, [])
|
||||
|
||||
useRestoreFocusOnClose(isOpen, panelRef)
|
||||
if (openState.open !== isOpen) {
|
||||
setOpenState({
|
||||
open: isOpen,
|
||||
returnFocus: isOpen ? getFocusedElement() : openState.returnFocus,
|
||||
})
|
||||
}
|
||||
|
||||
const { bind, swipeStyles } = useSwipeDismiss(onClose, {
|
||||
enabled: isOpen && dismissible,
|
||||
@@ -35,8 +55,8 @@ export function BottomSheet({
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
return bind(panelRef.current)
|
||||
}, [bind])
|
||||
return bind(panelElement)
|
||||
}, [bind, panelElement])
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
@@ -47,64 +67,65 @@ export function BottomSheet({
|
||||
}
|
||||
}, [isOpen])
|
||||
|
||||
useEffect(() => {
|
||||
const handleEscape = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape' && isOpen) {
|
||||
onClose()
|
||||
}
|
||||
}
|
||||
const handleOpenChange = (nextOpen: boolean) => {
|
||||
if (!nextOpen) onClose()
|
||||
}
|
||||
|
||||
if (isOpen) {
|
||||
document.addEventListener('keydown', handleEscape)
|
||||
document.body.style.overflow = 'hidden'
|
||||
}
|
||||
const handleOpenAutoFocus = (event: Event) => {
|
||||
event.preventDefault()
|
||||
panelRef.current?.focus({ preventScroll: true })
|
||||
}
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('keydown', handleEscape)
|
||||
document.body.style.overflow = 'unset'
|
||||
const handleCloseAutoFocus = (event: Event) => {
|
||||
if (restoreOverlayFocus(openState.returnFocus, event.currentTarget as Element | null)) {
|
||||
event.preventDefault()
|
||||
}
|
||||
}, [isOpen, onClose])
|
||||
}
|
||||
|
||||
if (!isOpen && !shouldRender) return null
|
||||
|
||||
const sheet = (
|
||||
<div
|
||||
className="fixed inset-0 z-[250]"
|
||||
style={{
|
||||
opacity: isOpen ? 1 : 0,
|
||||
pointerEvents: isOpen ? 'auto' : 'none',
|
||||
transition: `opacity ${MODAL_TRANSITION_MS}ms ease-out`,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className="absolute inset-0 bg-black/40 backdrop-blur-sm"
|
||||
onClick={onClose}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<div
|
||||
ref={panelRef}
|
||||
className={cn(
|
||||
'fixed inset-x-0 bottom-0 flex flex-col bg-background rounded-t-2xl border-t border-border',
|
||||
heightClass,
|
||||
className,
|
||||
)}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={ariaLabel}
|
||||
data-state={isOpen ? 'open' : 'closed'}
|
||||
style={swipeStyles}
|
||||
>
|
||||
<div className="w-full flex justify-center pt-3 pb-2">
|
||||
<div className="w-9 h-1 rounded-full bg-muted-foreground/30" />
|
||||
<DialogRoot open={isOpen} onOpenChange={handleOpenChange}>
|
||||
<DialogPortal forceMount>
|
||||
<div
|
||||
className="fixed inset-0 z-[250]"
|
||||
style={{
|
||||
opacity: isOpen ? 1 : 0,
|
||||
pointerEvents: isOpen ? 'auto' : 'none',
|
||||
transition: `opacity ${MODAL_TRANSITION_MS}ms ease-out`,
|
||||
}}
|
||||
>
|
||||
<DialogOverlay
|
||||
forceMount
|
||||
className="absolute inset-0 bg-black/40 backdrop-blur-sm"
|
||||
/>
|
||||
<DialogContent
|
||||
ref={setPanelRef}
|
||||
forceMount
|
||||
aria-modal="true"
|
||||
aria-describedby={undefined}
|
||||
tabIndex={-1}
|
||||
onOpenAutoFocus={handleOpenAutoFocus}
|
||||
onCloseAutoFocus={handleCloseAutoFocus}
|
||||
className={cn(
|
||||
'fixed inset-x-0 bottom-0 flex flex-col bg-background rounded-t-2xl border-t border-border focus:outline-none',
|
||||
heightClass,
|
||||
className,
|
||||
)}
|
||||
style={swipeStyles}
|
||||
>
|
||||
<DialogTitle className="sr-only">{ariaLabel}</DialogTitle>
|
||||
<div className="w-full flex justify-center pt-3 pb-2">
|
||||
<div className="w-9 h-1 rounded-full bg-muted-foreground/30" />
|
||||
</div>
|
||||
{children}
|
||||
</DialogContent>
|
||||
</div>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
</DialogPortal>
|
||||
</DialogRoot>
|
||||
)
|
||||
|
||||
if (typeof document === 'undefined') return sheet
|
||||
|
||||
return createPortal(sheet, document.body)
|
||||
return sheet
|
||||
}
|
||||
|
||||
export interface BottomSheetHeaderProps {
|
||||
|
||||
@@ -4,10 +4,14 @@ import { cn } from "@/lib/utils"
|
||||
interface ProgressProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
value?: number
|
||||
max?: number
|
||||
/** Extra classes merged onto the filled indicator. */
|
||||
indicatorClassName?: string
|
||||
/** Optional test id applied to the filled indicator. */
|
||||
indicatorTestId?: string
|
||||
}
|
||||
|
||||
const Progress = React.forwardRef<HTMLDivElement, ProgressProps>(
|
||||
({ className, value = 0, max = 100, ...props }, ref) => {
|
||||
({ className, value = 0, max = 100, indicatorClassName, indicatorTestId, ...props }, ref) => {
|
||||
const percentage = Math.min(100, Math.max(0, (value / max) * 100))
|
||||
|
||||
return (
|
||||
@@ -24,7 +28,11 @@ const Progress = React.forwardRef<HTMLDivElement, ProgressProps>(
|
||||
{...props}
|
||||
>
|
||||
<div
|
||||
className="h-full bg-primary transition-all duration-300 ease-in-out"
|
||||
data-testid={indicatorTestId}
|
||||
className={cn(
|
||||
"h-full bg-primary transition-all duration-300 ease-in-out",
|
||||
indicatorClassName
|
||||
)}
|
||||
style={{ width: `${percentage}%` }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { useLocation } from 'react-router-dom'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { sessionQueryOptions } from '@/hooks/useOpenCode'
|
||||
import { parseServerProjectRoute, parseServerSessionRoute } from '@/lib/navigation'
|
||||
|
||||
/**
|
||||
* Resolves the linked server directory currently in view: the project route's directory when one
|
||||
* matches the server, otherwise the directory of the session route it belongs to.
|
||||
*
|
||||
* @param serverId Linked server whose active directory is resolved.
|
||||
* @param options.enabled Whether the session lookup may run; omit for routes that always resolve it.
|
||||
* @returns The active directory, or null when neither route identifies one.
|
||||
*/
|
||||
export function useActiveRemoteDirectory(
|
||||
serverId: string,
|
||||
{ enabled = true }: { enabled?: boolean } = {},
|
||||
): string | null {
|
||||
const { pathname, search } = useLocation()
|
||||
const projectRoute = parseServerProjectRoute(pathname, search)
|
||||
const sessionRoute = parseServerSessionRoute(pathname)
|
||||
const sessionID = sessionRoute?.serverId === serverId ? sessionRoute.sessionId : undefined
|
||||
const { data: session } = useQuery({
|
||||
...sessionQueryOptions(sessionID, undefined, serverId),
|
||||
enabled: Boolean(sessionID) && enabled,
|
||||
})
|
||||
|
||||
if (projectRoute?.serverId === serverId) return projectRoute.directory
|
||||
return session?.location.directory ?? null
|
||||
}
|
||||
@@ -87,7 +87,7 @@ describe('useContextUsage', () => {
|
||||
wrapper: createWrapper(queryClient),
|
||||
})
|
||||
|
||||
expect(result.current.usage?.totalTokens).toBe(1515)
|
||||
expect(result.current?.totalTokens).toBe(1515)
|
||||
})
|
||||
|
||||
it('rounds the usage percentage against the model context limit', () => {
|
||||
@@ -108,7 +108,7 @@ describe('useContextUsage', () => {
|
||||
wrapper: createWrapper(queryClient),
|
||||
})
|
||||
|
||||
expect(result.current.usage?.usagePercentage).toBe(152)
|
||||
expect(result.current?.usagePercentage).toBe(152)
|
||||
})
|
||||
|
||||
it('reports the context limit measured against', () => {
|
||||
@@ -129,7 +129,7 @@ describe('useContextUsage', () => {
|
||||
wrapper: createWrapper(queryClient),
|
||||
})
|
||||
|
||||
expect(result.current.usage?.contextLimit).toBe(1000)
|
||||
expect(result.current?.contextLimit).toBe(1000)
|
||||
})
|
||||
|
||||
it('hides usage when the latest assistant has all-zero tokens even if an earlier one had usage', () => {
|
||||
@@ -153,7 +153,7 @@ describe('useContextUsage', () => {
|
||||
wrapper: createWrapper(queryClient),
|
||||
})
|
||||
|
||||
expect(result.current.usage).toBeNull()
|
||||
expect(result.current).toBeNull()
|
||||
})
|
||||
|
||||
it('skips the latest assistant when tokens are undefined and uses the earlier assistant', () => {
|
||||
@@ -172,7 +172,7 @@ describe('useContextUsage', () => {
|
||||
wrapper: createWrapper(queryClient),
|
||||
})
|
||||
|
||||
expect(result.current.usage?.totalTokens).toBe(1515)
|
||||
expect(result.current?.totalTokens).toBe(1515)
|
||||
})
|
||||
|
||||
it('ignores assistants before the latest completed compaction', () => {
|
||||
@@ -191,7 +191,7 @@ describe('useContextUsage', () => {
|
||||
wrapper: createWrapper(queryClient),
|
||||
})
|
||||
|
||||
expect(result.current.usage).toBeNull()
|
||||
expect(result.current).toBeNull()
|
||||
})
|
||||
|
||||
it('uses an assistant that appears after the latest completed compaction', () => {
|
||||
@@ -216,7 +216,7 @@ describe('useContextUsage', () => {
|
||||
wrapper: createWrapper(queryClient),
|
||||
})
|
||||
|
||||
expect(result.current.usage?.totalTokens).toBe(180)
|
||||
expect(result.current?.totalTokens).toBe(180)
|
||||
})
|
||||
|
||||
it('does not treat a running compaction as a boundary', () => {
|
||||
@@ -235,7 +235,7 @@ describe('useContextUsage', () => {
|
||||
wrapper: createWrapper(queryClient),
|
||||
})
|
||||
|
||||
expect(result.current.usage?.totalTokens).toBe(1515)
|
||||
expect(result.current?.totalTokens).toBe(1515)
|
||||
})
|
||||
|
||||
it('ignores assistants at or after the revert boundary', () => {
|
||||
@@ -259,7 +259,7 @@ describe('useContextUsage', () => {
|
||||
wrapper: createWrapper(queryClient),
|
||||
})
|
||||
|
||||
expect(result.current.usage?.totalTokens).toBe(1515)
|
||||
expect(result.current?.totalTokens).toBe(1515)
|
||||
})
|
||||
|
||||
it('hides usage when the revert boundary excludes every assistant', () => {
|
||||
@@ -283,7 +283,7 @@ describe('useContextUsage', () => {
|
||||
wrapper: createWrapper(queryClient),
|
||||
})
|
||||
|
||||
expect(result.current.usage).toBeNull()
|
||||
expect(result.current).toBeNull()
|
||||
})
|
||||
|
||||
it('hides usage when the revert boundary is unknown', () => {
|
||||
@@ -301,6 +301,6 @@ describe('useContextUsage', () => {
|
||||
wrapper: createWrapper(queryClient),
|
||||
})
|
||||
|
||||
expect(result.current.usage).toBeNull()
|
||||
expect(result.current).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -9,11 +9,6 @@ import { serverScopedKey } from '@/lib/serverScope'
|
||||
import type { TranscriptCache } from '@/lib/session-projection'
|
||||
import type { ContextUsage } from '@/lib/contextUsage'
|
||||
|
||||
interface ContextUsageResult {
|
||||
usage: ContextUsage | null
|
||||
isLoading: boolean
|
||||
}
|
||||
|
||||
function lastCompletedCompactionIndex(messages: SessionMessageInfo[], end: number): number {
|
||||
for (let index = end - 1; index >= 0; index -= 1) {
|
||||
const message = messages[index]
|
||||
@@ -34,14 +29,13 @@ export const useContextUsage = (
|
||||
sessionID: string | undefined,
|
||||
directory?: string,
|
||||
revertMessageID?: string,
|
||||
): ContextUsageResult => {
|
||||
): ContextUsage | null => {
|
||||
const serverId = useOpenCodeServerId()
|
||||
const transcriptQuery = useQuery<TranscriptCache>({
|
||||
queryKey: serverScopedKey(sessionTranscriptQueryKey(sessionID ?? ''), serverId),
|
||||
queryFn: skipToken,
|
||||
})
|
||||
const transcriptData = transcriptQuery.data
|
||||
const messagesLoading = transcriptQuery.isPending
|
||||
|
||||
const { data: providersData } = useProviders(directory)
|
||||
const models = providersData?.models
|
||||
@@ -53,7 +47,7 @@ export const useContextUsage = (
|
||||
? messages.findIndex((message) => message.id === revertMessageID)
|
||||
: -1
|
||||
if (revertMessageID && boundaryIndex === -1) {
|
||||
return { usage: null, isLoading: messagesLoading }
|
||||
return null
|
||||
}
|
||||
|
||||
const end = boundaryIndex === -1 ? messages.length : boundaryIndex
|
||||
@@ -61,13 +55,13 @@ export const useContextUsage = (
|
||||
const assistantIndex = lastAssistantWithUsageIndex(messages, compactionIndex, end)
|
||||
const assistant = assistantIndex === -1 ? undefined : messages[assistantIndex]
|
||||
if (assistant?.type !== 'assistant' || assistant.tokens === undefined) {
|
||||
return { usage: null, isLoading: messagesLoading }
|
||||
return null
|
||||
}
|
||||
|
||||
const { input, output, reasoning, cache } = assistant.tokens
|
||||
const totalTokens = input + output + reasoning + cache.read + cache.write
|
||||
if (totalTokens <= 0) {
|
||||
return { usage: null, isLoading: messagesLoading }
|
||||
return null
|
||||
}
|
||||
|
||||
const model = models
|
||||
@@ -76,6 +70,6 @@ export const useContextUsage = (
|
||||
const contextLimit = model?.limit.context ?? null
|
||||
const usagePercentage = contextLimit ? Math.round((totalTokens / contextLimit) * 100) : null
|
||||
|
||||
return { usage: { totalTokens, usagePercentage, contextLimit }, isLoading: messagesLoading }
|
||||
}, [transcriptData, messagesLoading, models, revertMessageID])
|
||||
return { totalTokens, usagePercentage, contextLimit }
|
||||
}, [transcriptData, models, revertMessageID])
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { renderHook, waitFor } from '@testing-library/react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { OpenCodeProject } from '@/api/opencode'
|
||||
import { useRemoteProjects } from './useRemoteProjects'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
listProjects: vi.fn(),
|
||||
useOpenCodeServers: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/opencode', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/api/opencode')>()
|
||||
return { ...actual, listProjects: mocks.listProjects }
|
||||
})
|
||||
|
||||
vi.mock('@/hooks/useOpenCodeServers', () => ({
|
||||
useOpenCodeServers: mocks.useOpenCodeServers,
|
||||
}))
|
||||
|
||||
const kitchen = {
|
||||
id: 'srv_kitchen',
|
||||
name: 'Kitchen',
|
||||
baseUrl: 'https://kitchen.example.com',
|
||||
username: 'opencode',
|
||||
enabled: true,
|
||||
hasPassword: true,
|
||||
createdAt: 1,
|
||||
updatedAt: 2,
|
||||
}
|
||||
|
||||
function createProject(
|
||||
id: string,
|
||||
time: { created: number; updated: number; active?: number },
|
||||
): OpenCodeProject {
|
||||
return { id, name: id, canonical: `/work/${id}`, time, sandboxes: [] }
|
||||
}
|
||||
|
||||
function createWrapper() {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
return ({ children }: { children: ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
)
|
||||
}
|
||||
|
||||
describe('useRemoteProjects', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.useOpenCodeServers.mockReturnValue({ servers: [kitchen], isLoading: false })
|
||||
mocks.listProjects.mockResolvedValue([])
|
||||
})
|
||||
|
||||
it('lists the projects of the linked server, most recently active first', async () => {
|
||||
const stale = createProject('stale', { created: 1, updated: 500, active: 100 })
|
||||
const recent = createProject('recent', { created: 1, updated: 100, active: 900 })
|
||||
mocks.listProjects.mockResolvedValue([stale, recent])
|
||||
|
||||
const { result } = renderHook(() => useRemoteProjects('srv_kitchen'), {
|
||||
wrapper: createWrapper(),
|
||||
})
|
||||
|
||||
await waitFor(() => expect(result.current.projects).toHaveLength(2))
|
||||
expect(result.current.projects.map((project) => project.id)).toEqual(['recent', 'stale'])
|
||||
expect(mocks.listProjects).toHaveBeenCalledWith('srv_kitchen')
|
||||
})
|
||||
|
||||
it('stays idle while the linked server is disabled', () => {
|
||||
mocks.useOpenCodeServers.mockReturnValue({
|
||||
servers: [{ ...kitchen, enabled: false }],
|
||||
isLoading: false,
|
||||
})
|
||||
|
||||
const { result } = renderHook(() => useRemoteProjects('srv_kitchen'), {
|
||||
wrapper: createWrapper(),
|
||||
})
|
||||
|
||||
expect(result.current.isLoading).toBe(false)
|
||||
expect(result.current.projects).toEqual([])
|
||||
expect(mocks.listProjects).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('stays idle when the caller disables it', () => {
|
||||
renderHook(() => useRemoteProjects('srv_kitchen', { enabled: false }), {
|
||||
wrapper: createWrapper(),
|
||||
})
|
||||
|
||||
expect(mocks.listProjects).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps the cached projects and reports the failure when a refetch fails', async () => {
|
||||
mocks.listProjects
|
||||
.mockResolvedValueOnce([createProject('app', { created: 1, updated: 2 })])
|
||||
.mockRejectedValueOnce(new Error('offline'))
|
||||
|
||||
const { result } = renderHook(() => useRemoteProjects('srv_kitchen'), {
|
||||
wrapper: createWrapper(),
|
||||
})
|
||||
|
||||
await waitFor(() => expect(result.current.projects).toHaveLength(1))
|
||||
|
||||
result.current.refetch()
|
||||
|
||||
await waitFor(() => expect(result.current.isError).toBe(true))
|
||||
expect(result.current.hasData).toBe(true)
|
||||
expect(result.current.projects.map((project) => project.id)).toEqual(['app'])
|
||||
expect(result.current.error?.message).toBe('offline')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,55 @@
|
||||
import { useMemo } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { listProjects, sortProjectsByActivity, type OpenCodeProject } from '@/api/opencode'
|
||||
import { useOpenCodeServers } from '@/hooks/useOpenCodeServers'
|
||||
import { serverScopedKey } from '@/lib/serverScope'
|
||||
|
||||
export interface UseRemoteProjectsOptions {
|
||||
/** Caller-side gate that applies on top of the server's own enabled flag. */
|
||||
enabled?: boolean
|
||||
}
|
||||
|
||||
export interface UseRemoteProjectsResult {
|
||||
projects: OpenCodeProject[]
|
||||
isLoading: boolean
|
||||
isError: boolean
|
||||
hasData: boolean
|
||||
error: Error | null
|
||||
refetch: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the projects of one linked server, most recently active first, while that server is enabled.
|
||||
*
|
||||
* @param serverId Linked server whose projects are listed.
|
||||
* @param options Caller-side gate for when the projects may be fetched.
|
||||
* @returns The activity-sorted projects plus the query state callers render.
|
||||
*/
|
||||
export function useRemoteProjects(
|
||||
serverId: string,
|
||||
options: UseRemoteProjectsOptions = {},
|
||||
): UseRemoteProjectsResult {
|
||||
const enabled = options.enabled ?? true
|
||||
const { servers } = useOpenCodeServers({ enabled })
|
||||
const isServerEnabled = servers.find((server) => server.id === serverId)?.enabled === true
|
||||
const projectsQuery = useQuery({
|
||||
queryKey: serverScopedKey(['opencode', 'projects'], serverId),
|
||||
queryFn: () => listProjects(serverId),
|
||||
enabled: enabled && isServerEnabled,
|
||||
retry: false,
|
||||
})
|
||||
|
||||
const projects = useMemo(
|
||||
() => sortProjectsByActivity(projectsQuery.data ?? []),
|
||||
[projectsQuery.data],
|
||||
)
|
||||
|
||||
return {
|
||||
projects,
|
||||
isLoading: projectsQuery.isLoading,
|
||||
isError: projectsQuery.isError,
|
||||
hasData: projectsQuery.data !== undefined,
|
||||
error: projectsQuery.error,
|
||||
refetch: projectsQuery.refetch,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { useEffect } from 'react'
|
||||
import { useLocation } from 'react-router-dom'
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
import type { Repo } from '@/api/types'
|
||||
import { openCodeLocationQueryOptions } from '@/lib/openCodeLocation'
|
||||
import { parseRepoRoute } from '@/lib/navigation'
|
||||
|
||||
/**
|
||||
* Warms the picker's project location on a local repo route so the first session picker open does
|
||||
* not serialise the location lookup ahead of the session list. The repo path comes from the already
|
||||
* cached repos query, and the prefetch never creates a query observer.
|
||||
*/
|
||||
export function useSessionPickerLocationPrefetch(): void {
|
||||
const { pathname } = useLocation()
|
||||
const queryClient = useQueryClient()
|
||||
const repoId = parseRepoRoute(pathname).repoId
|
||||
|
||||
useEffect(() => {
|
||||
if (repoId === null) return
|
||||
const repo = queryClient
|
||||
.getQueryData<Repo[]>(['repos'])
|
||||
?.find((candidate) => candidate.id === repoId)
|
||||
if (!repo) return
|
||||
void queryClient.prefetchQuery(
|
||||
openCodeLocationQueryOptions(repo.fullPath, LOCAL_OPENCODE_SERVER_ID),
|
||||
)
|
||||
}, [queryClient, repoId])
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import { useCallback } from 'react'
|
||||
import { useLocation, useNavigate } from 'react-router-dom'
|
||||
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
import type { Repo, Session } from '@/api/types'
|
||||
import {
|
||||
getRepoPath,
|
||||
getServerSessionPath,
|
||||
getSessionPath,
|
||||
parseRepoRoute,
|
||||
parseServerSessionRoute,
|
||||
withQueryParam,
|
||||
} from '@/lib/navigation'
|
||||
|
||||
export interface SessionPickerNavigationOptions {
|
||||
/**
|
||||
* `replace` rewrites the entry the mobile sheet was opened from so Back returns to the page behind
|
||||
* it; `push` adds an entry and closes the picker.
|
||||
*/
|
||||
mode: 'push' | 'replace'
|
||||
onClose: () => void
|
||||
/** Replaces the default delete behaviour of opening the current repo page. */
|
||||
onDeleteActiveSession?: () => void
|
||||
}
|
||||
|
||||
export interface SessionPickerNavigation {
|
||||
onSelectSession: (session: Session, repo: Repo) => void
|
||||
onSelectRemoteSession: (session: Session, serverId: string) => void
|
||||
onDeleteActiveSession: () => void
|
||||
onSelectRepo: (repo: Repo) => void
|
||||
onNavigate: (path: string) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the session picker handlers shared by the mobile sheet, the desktop dialog and the session
|
||||
* page picker. The route in view comes from the location: choosing the session already open on the
|
||||
* same server only closes the picker, and an assistant session keeps `?assistant=1` when the chosen
|
||||
* session belongs to the current repo.
|
||||
*
|
||||
* @param options Navigation mode, the picker's close callback, and an optional delete override.
|
||||
* @returns Handlers for selecting sessions and repos and for following a prepared path.
|
||||
*/
|
||||
export function useSessionPickerNavigation({
|
||||
mode,
|
||||
onClose,
|
||||
onDeleteActiveSession: deleteActiveSessionOverride,
|
||||
}: SessionPickerNavigationOptions): SessionPickerNavigation {
|
||||
const navigate = useNavigate()
|
||||
const { pathname, search } = useLocation()
|
||||
const repoRoute = parseRepoRoute(pathname)
|
||||
const serverSessionRoute = parseServerSessionRoute(pathname)
|
||||
const currentRepoId = repoRoute.repoId
|
||||
const activeSessionID = repoRoute.sessionId ?? serverSessionRoute?.sessionId ?? undefined
|
||||
const activeServerId = repoRoute.sessionId ? LOCAL_OPENCODE_SERVER_ID : serverSessionRoute?.serverId
|
||||
const isAssistantSession = new URLSearchParams(search).get('assistant') === '1'
|
||||
|
||||
const open = useCallback(
|
||||
(path: string) => {
|
||||
navigate(path, { replace: mode === 'replace' })
|
||||
if (mode === 'push') onClose()
|
||||
},
|
||||
[mode, navigate, onClose],
|
||||
)
|
||||
|
||||
const onSelectSession = useCallback(
|
||||
(session: Session, repo: Repo) => {
|
||||
if (session.id === activeSessionID && activeServerId === LOCAL_OPENCODE_SERVER_ID) {
|
||||
onClose()
|
||||
return
|
||||
}
|
||||
const sessionPath = getSessionPath(repo.id, session.id)
|
||||
open(
|
||||
isAssistantSession && repo.id === currentRepoId
|
||||
? withQueryParam(sessionPath, 'assistant', '1')
|
||||
: sessionPath,
|
||||
)
|
||||
},
|
||||
[activeServerId, activeSessionID, currentRepoId, isAssistantSession, onClose, open],
|
||||
)
|
||||
|
||||
const onSelectRemoteSession = useCallback(
|
||||
(session: Session, serverId: string) => {
|
||||
if (session.id === activeSessionID && serverId === activeServerId) {
|
||||
onClose()
|
||||
return
|
||||
}
|
||||
open(getServerSessionPath(serverId, session.id))
|
||||
},
|
||||
[activeServerId, activeSessionID, onClose, open],
|
||||
)
|
||||
|
||||
const onDeleteActiveSession = useCallback(() => {
|
||||
if (deleteActiveSessionOverride) {
|
||||
onClose()
|
||||
deleteActiveSessionOverride()
|
||||
return
|
||||
}
|
||||
if (currentRepoId === null) {
|
||||
onClose()
|
||||
return
|
||||
}
|
||||
open(getRepoPath(currentRepoId))
|
||||
}, [currentRepoId, deleteActiveSessionOverride, onClose, open])
|
||||
|
||||
const onSelectRepo = useCallback(
|
||||
(repo: Repo) => {
|
||||
open(getRepoPath(repo.id))
|
||||
},
|
||||
[open],
|
||||
)
|
||||
|
||||
return {
|
||||
onSelectSession,
|
||||
onSelectRemoteSession,
|
||||
onDeleteActiveSession,
|
||||
onSelectRepo,
|
||||
onNavigate: open,
|
||||
}
|
||||
}
|
||||
@@ -1,24 +1,26 @@
|
||||
import { useLocation } from 'react-router-dom'
|
||||
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
import type { Repo } from '@/api/types'
|
||||
import { parseRepoRoute, parseServerProjectRoute, parseServerSessionRoute } from '@/lib/navigation'
|
||||
import type { RemotePickerScope } from '@/components/session/SessionPickerDialog'
|
||||
import { parseRepoRoute, parseServerSessionRoute } from '@/lib/navigation'
|
||||
import { useNavigableRepos } from '@/hooks/useSidebarRepoGroups'
|
||||
import { useOpenCodeServers } from '@/hooks/useOpenCodeServers'
|
||||
import { useSidebarServerSelection } from '@/hooks/useSidebarServerSelection'
|
||||
import { useActiveRemoteDirectory } from '@/hooks/useActiveRemoteDirectory'
|
||||
|
||||
export interface SessionPickerRouteScope {
|
||||
currentRepo: Repo | undefined
|
||||
activeSessionID: string | undefined
|
||||
activeServerId: string | undefined
|
||||
isRemote: boolean
|
||||
remote: { serverId: string; serverName?: string; projectDirectory?: string } | undefined
|
||||
remote: RemotePickerScope | undefined
|
||||
}
|
||||
|
||||
export function useSessionPickerRouteScope(enabled: boolean): SessionPickerRouteScope {
|
||||
const { pathname, search } = useLocation()
|
||||
const { pathname } = useLocation()
|
||||
const [selectedServerId] = useSidebarServerSelection()
|
||||
const { repos } = useNavigableRepos(enabled)
|
||||
const { servers } = useOpenCodeServers({ enabled })
|
||||
const activeRemoteDirectory = useActiveRemoteDirectory(selectedServerId, { enabled })
|
||||
|
||||
const isRemote = selectedServerId !== LOCAL_OPENCODE_SERVER_ID
|
||||
const repoRoute = parseRepoRoute(pathname)
|
||||
@@ -28,23 +30,19 @@ export function useSessionPickerRouteScope(enabled: boolean): SessionPickerRoute
|
||||
: repos.find((candidate) => candidate.id === repoRoute.repoId)
|
||||
const activeSessionID = repoRoute.sessionId ?? serverSessionRoute?.sessionId ?? undefined
|
||||
const activeServerId = repoRoute.sessionId ? LOCAL_OPENCODE_SERVER_ID : serverSessionRoute?.serverId
|
||||
const remoteProjectDirectory = isRemote
|
||||
? parseServerProjectRoute(pathname, search)?.directory
|
||||
: undefined
|
||||
|
||||
if (!isRemote) {
|
||||
return { currentRepo, activeSessionID, activeServerId, isRemote, remote: undefined }
|
||||
return { currentRepo, activeSessionID, activeServerId, remote: undefined }
|
||||
}
|
||||
|
||||
return {
|
||||
currentRepo,
|
||||
activeSessionID,
|
||||
activeServerId,
|
||||
isRemote,
|
||||
remote: {
|
||||
serverId: selectedServerId,
|
||||
serverName: servers.find((server) => server.id === selectedServerId)?.name,
|
||||
projectDirectory: remoteProjectDirectory,
|
||||
projectDirectory: activeRemoteDirectory ?? undefined,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@ export function useVcsInfo(
|
||||
queryKey: [...serverScopedKey(['opencode', 'vcs', directory ?? ''], serverId), 'info'],
|
||||
queryFn: () => getVcsInfo(directory ?? '', serverId),
|
||||
enabled: enabled && Boolean(directory),
|
||||
staleTime: 30_000,
|
||||
retry: false,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { queryOptions } from '@tanstack/react-query'
|
||||
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
import { getOpenCodeLocation } from '@/api/opencode'
|
||||
import { serverScopedKey } from '@/lib/serverScope'
|
||||
|
||||
/**
|
||||
* Query options for a repo directory's OpenCode project location, shared by the session picker and
|
||||
* the route-level prefetch so both read and write the same cache entry.
|
||||
*/
|
||||
export function openCodeLocationQueryOptions(
|
||||
fullPath: string,
|
||||
serverId: string = LOCAL_OPENCODE_SERVER_ID,
|
||||
) {
|
||||
return queryOptions({
|
||||
queryKey: serverScopedKey(['opencode', 'location', fullPath], serverId),
|
||||
queryFn: () => getOpenCodeLocation(fullPath, serverId),
|
||||
staleTime: 5 * 60 * 1000,
|
||||
})
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
import { useNavigate, useParams, useSearchParams } from 'react-router-dom'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { FolderGit2, GitBranch, Loader2, Plus, Server } from 'lucide-react'
|
||||
import { listProjects } from '@/api/opencode'
|
||||
import { remoteProjectName } from '@/api/opencode'
|
||||
import { useCreateSession } from '@/hooks/useOpenCode'
|
||||
import { useRemoteProjects } from '@/hooks/useRemoteProjects'
|
||||
import { useVcsInfo } from '@/hooks/useVcsInfo'
|
||||
import { useOpenCodeServers } from '@/hooks/useOpenCodeServers'
|
||||
import { useSettingsDialog } from '@/hooks/useSettingsDialog'
|
||||
@@ -11,7 +11,6 @@ import { useToolPanelLayout } from '@/hooks/useToolPanelLayout'
|
||||
import { useToolPanel } from '@/hooks/useToolPanel'
|
||||
import { useDialogParam } from '@/hooks/useDialogParam'
|
||||
import { useTerminalDialogParam, useTerminalDirectoryParam } from '@/hooks/useOpenTerminal'
|
||||
import { serverScopedKey } from '@/lib/serverScope'
|
||||
import { getServerSessionPath } from '@/lib/navigation'
|
||||
import { getDirectoryName } from '@/lib/utils'
|
||||
import { Header } from '@/components/ui/header'
|
||||
@@ -44,20 +43,19 @@ function RemoteProjectContent({ serverId, directory }: { serverId: string; direc
|
||||
const isReady = server?.enabled === true && Boolean(directory)
|
||||
const createSession = useCreateSession(directory)
|
||||
|
||||
const projectsQuery = useQuery({
|
||||
queryKey: serverScopedKey(['opencode', 'projects'], serverId),
|
||||
queryFn: () => listProjects(serverId),
|
||||
enabled: server?.enabled === true,
|
||||
retry: false,
|
||||
})
|
||||
const { projects } = useRemoteProjects(serverId)
|
||||
|
||||
const vcsQuery = useVcsInfo(directory, serverId, { enabled: isReady })
|
||||
|
||||
useSSE(directory)
|
||||
|
||||
const project = (projectsQuery.data ?? []).find((entry) => entry.canonical === directory)
|
||||
const project = projects.find((entry) => entry.canonical === directory)
|
||||
const branch = vcsQuery.data?.branch.current ?? vcsQuery.data?.branch.default
|
||||
const title = project?.name?.trim() || (directory ? getDirectoryName(directory) : 'Project')
|
||||
const title = project
|
||||
? remoteProjectName(project)
|
||||
: directory
|
||||
? getDirectoryName(directory)
|
||||
: 'Project'
|
||||
|
||||
const openSettings = () => openTab('servers')
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ import { SquareFill } from "@/components/ui/square-fill";
|
||||
import { Header } from "@/components/ui/header";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { SessionPickerDialog } from "@/components/session/SessionPickerDialog";
|
||||
import { getRepoPath, getServerProjectPath, getServerSessionPath, getSessionListPath, getSessionPath } from '@/lib/navigation'
|
||||
import { getServerProjectPath, getSessionListPath, getSessionPath } from '@/lib/navigation'
|
||||
import { FetchError } from '@/api/fetchWrapper'
|
||||
|
||||
import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet";
|
||||
@@ -49,8 +49,9 @@ import { ProjectActionsMenu } from "@/components/repo/ProjectActionsMenu";
|
||||
import { RepoActionsDialog } from "@/components/repo/RepoActionsDialog";
|
||||
import { ResetPermissionsDialog } from "@/components/repo/ResetPermissionsDialog";
|
||||
import { RepoSkillsDialog } from "@/components/repo/RepoSkillsDialog";
|
||||
import { compactSession, forkSession, listProjects, listSessionMessages } from "@/api/opencode";
|
||||
import { compactSession, forkSession, listSessionMessages, remoteProjectName } from "@/api/opencode";
|
||||
import { useOpenCodeServerId, isLocalOpenCodeServer } from "@/contexts/OpenCodeServerContext";
|
||||
import { useRemoteProjects } from "@/hooks/useRemoteProjects";
|
||||
import { useSwipeNavigation } from "@/contexts/SwipeNavigationContext";
|
||||
import { useOpenCodeServers, useOpenCodeServerStatuses } from "@/hooks/useOpenCodeServers";
|
||||
import { serverScopedKey } from "@/lib/serverScope";
|
||||
@@ -83,6 +84,7 @@ import { ChangesWalkthroughSheet, type WalkthroughSourceRequest } from "@/compon
|
||||
import { ToolSidePanel } from "@/components/navigation/ToolSidePanel";
|
||||
import type { WalkthroughSource } from "@opencode-manager/shared/schemas";
|
||||
import { useToolPanel } from "@/hooks/useToolPanel";
|
||||
import { useSessionPickerNavigation } from "@/hooks/useSessionPickerNavigation";
|
||||
|
||||
const OLDER_HISTORY_SCROLL_THRESHOLD_PX = 200
|
||||
|
||||
@@ -191,8 +193,6 @@ export function SessionDetail() {
|
||||
|
||||
useRepoActivity(repoId, Boolean(repo) && !isRemoteServer);
|
||||
|
||||
const sessionRouteSuffix = isAssistantSession && !isRemoteServer ? '?assistant=1' : '';
|
||||
|
||||
const repoDirectory = repo?.fullPath;
|
||||
const [resolvedSessionDirectory, setResolvedSessionDirectory] = useState<{ sessionId: string; directory: string } | null>(null);
|
||||
const resolvedDirectory = (
|
||||
@@ -217,25 +217,20 @@ export function SessionDetail() {
|
||||
|
||||
const { servers: linkedServers } = useOpenCodeServers({ enabled: isRemoteServer });
|
||||
|
||||
const { data: remoteProjects } = useQuery({
|
||||
queryKey: serverScopedKey(['opencode', 'projects'], serverId),
|
||||
queryFn: () => listProjects(serverId),
|
||||
enabled: isRemoteServer,
|
||||
retry: false,
|
||||
});
|
||||
const { projects: remoteProjects } = useRemoteProjects(serverId, { enabled: isRemoteServer });
|
||||
|
||||
const remoteProjectDirectory = useMemo(() => {
|
||||
const remoteProject = useMemo(() => {
|
||||
if (!isRemoteServer || !sessionDirectory) return undefined;
|
||||
const project = remoteProjects?.find(
|
||||
return remoteProjects.find(
|
||||
(entry) => sessionDirectory === entry.canonical || sessionDirectory.startsWith(`${entry.canonical}/`),
|
||||
);
|
||||
return project?.canonical ?? sessionDirectory;
|
||||
}, [isRemoteServer, remoteProjects, sessionDirectory]);
|
||||
|
||||
const remoteProjectName = useMemo(() => {
|
||||
if (!isRemoteServer) return undefined;
|
||||
return remoteProjects?.find((entry) => entry.canonical === remoteProjectDirectory)?.name?.trim() || undefined;
|
||||
}, [isRemoteServer, remoteProjects, remoteProjectDirectory]);
|
||||
const remoteProjectDirectory = isRemoteServer && sessionDirectory
|
||||
? remoteProject?.canonical ?? sessionDirectory
|
||||
: undefined;
|
||||
|
||||
const remoteProjectDisplayName = remoteProject ? remoteProjectName(remoteProject) : undefined;
|
||||
|
||||
const sessionBranch = useMemo(
|
||||
() => (repo && !isAssistantSession ? resolveSessionBranch(repo, sessionDirectory, repoSiblings) : null),
|
||||
@@ -557,6 +552,12 @@ export function SessionDetail() {
|
||||
navigate(getSessionListPath(repoId, isAssistantSession, tab))
|
||||
}, [navigate, repoId, isAssistantSession, isRemoteServer, remoteProjectBackPath, location.search])
|
||||
|
||||
const pickerNavigation = useSessionPickerNavigation({
|
||||
mode: 'push',
|
||||
onClose: () => setSessionsDialogOpen(false),
|
||||
onDeleteActiveSession: handleCloseSession,
|
||||
})
|
||||
|
||||
const handleOpenModelDialog = useCallback(() => {
|
||||
promptInputRef.current?.openModelPicker();
|
||||
}, [])
|
||||
@@ -576,18 +577,22 @@ export function SessionDetail() {
|
||||
setFileBrowserOpen(true)
|
||||
}, [repo?.fullPath, repo?.localPath, sessionDirectory, setFileBrowserOpen]);
|
||||
|
||||
const renameSession = useCallback(async (title: string) => {
|
||||
if (!sessionId) throw new Error('No active session');
|
||||
await updateSessionAsync({ sessionID: sessionId, title: title.trim() });
|
||||
}, [sessionId, updateSessionAsync]);
|
||||
|
||||
const handleRenameSession = useCallback(async (title: string) => {
|
||||
if (!sessionId) return;
|
||||
const trimmedTitle = title.trim();
|
||||
try {
|
||||
await updateSessionAsync({ sessionID: sessionId, title: trimmedTitle });
|
||||
await renameSession(title);
|
||||
if (!trimmedTitle) {
|
||||
showToast.success('Session title regenerated');
|
||||
}
|
||||
} catch (error) {
|
||||
showToast.error(`Rename failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}, [sessionId, updateSessionAsync]);
|
||||
}, [renameSession]);
|
||||
|
||||
const handleFileBrowserClose = useCallback(() => setFileBrowserOpen(false), [setFileBrowserOpen]);
|
||||
|
||||
@@ -796,7 +801,7 @@ export function SessionDetail() {
|
||||
|
||||
const linkedServer = linkedServers.find((candidate) => candidate.id === serverId);
|
||||
const projectDisplayName = isRemoteServer
|
||||
? remoteProjectName ?? (sessionDirectory ? getDirectoryName(sessionDirectory) : 'Project')
|
||||
? remoteProjectDisplayName ?? (sessionDirectory ? getDirectoryName(sessionDirectory) : 'Project')
|
||||
: isAssistantSession || !repo
|
||||
? 'Assistant'
|
||||
: getRepoDisplayName(repo);
|
||||
@@ -1049,42 +1054,19 @@ export function SessionDetail() {
|
||||
? { serverId, serverName: linkedServer?.name, projectDirectory: remoteProjectDirectory }
|
||||
: undefined
|
||||
}
|
||||
onSelectSession={(session, sessionRepo) => {
|
||||
if (!isRemoteServer && sessionRepo.id === repoId) {
|
||||
navigate(`/repos/${repoId}/sessions/${session.id}${sessionRouteSuffix}`)
|
||||
} else {
|
||||
navigate(getSessionPath(sessionRepo.id, session.id))
|
||||
}
|
||||
setSessionsDialogOpen(false)
|
||||
}}
|
||||
onSelectRemoteSession={(session, targetServerId) => {
|
||||
navigate(getServerSessionPath(targetServerId, session.id))
|
||||
setSessionsDialogOpen(false)
|
||||
}}
|
||||
onDeleteActiveSession={() => {
|
||||
setSessionsDialogOpen(false)
|
||||
handleCloseSession()
|
||||
}}
|
||||
onSelectRepo={(selectedRepo) => {
|
||||
navigate(getRepoPath(selectedRepo.id))
|
||||
setSessionsDialogOpen(false)
|
||||
}}
|
||||
onNavigate={(path) => {
|
||||
navigate(path)
|
||||
setSessionsDialogOpen(false)
|
||||
}}
|
||||
{...pickerNavigation}
|
||||
/>
|
||||
|
||||
<SessionDetailsSheet
|
||||
open={sessionDetailsOpen}
|
||||
onOpenChange={setSessionDetailsOpen}
|
||||
sessionId={sessionId}
|
||||
title={session?.title}
|
||||
serverName={linkedServer?.name}
|
||||
remote={isRemoteServer}
|
||||
project={projectDisplayName}
|
||||
branch={headerBranch}
|
||||
directory={sessionDirectory}
|
||||
onRename={renameSession}
|
||||
/>
|
||||
|
||||
{sideQuestion && sessionId && (
|
||||
|
||||
@@ -22,10 +22,10 @@ const mocks = vi.hoisted(() => ({
|
||||
openTab: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/opencode', () => ({
|
||||
listProjects: mocks.listProjects,
|
||||
getVcsInfo: mocks.getVcsInfo,
|
||||
}))
|
||||
vi.mock('@/api/opencode', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/api/opencode')>()
|
||||
return { ...actual, listProjects: mocks.listProjects, getVcsInfo: mocks.getVcsInfo }
|
||||
})
|
||||
|
||||
vi.mock('@/hooks/useOpenCode', () => ({
|
||||
useCreateSession: mocks.useCreateSession,
|
||||
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
import type { Repo, Session } from '@/api/types'
|
||||
|
||||
/**
|
||||
* Builds a session fixture for picker tests.
|
||||
*
|
||||
* @param id Session id.
|
||||
* @param title Session title.
|
||||
* @param directory Session working directory.
|
||||
* @param updated Session creation and update timestamp.
|
||||
*/
|
||||
export function makeSession(id: string, title: string, directory: string, updated = Date.now()): Session {
|
||||
return {
|
||||
id,
|
||||
projectID: 'proj',
|
||||
title,
|
||||
time: { created: updated, updated },
|
||||
location: { directory },
|
||||
cost: 0,
|
||||
tokens: {},
|
||||
} as unknown as Session
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a ready repo fixture for picker tests.
|
||||
*
|
||||
* @param id Repo id.
|
||||
* @param name Repo name.
|
||||
* @param fullPath Repo working directory.
|
||||
*/
|
||||
export function makeRepo(id: number, name: string, fullPath: string): Repo {
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
localPath: fullPath,
|
||||
fullPath,
|
||||
defaultBranch: 'main',
|
||||
cloneStatus: 'ready',
|
||||
clonedAt: 0,
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useEffect, type ReactNode } from 'react'
|
||||
import { renderHook } from '@testing-library/react'
|
||||
import { MemoryRouter, useLocation } from 'react-router-dom'
|
||||
import { MemoryRouter, useLocation, useNavigationType } from 'react-router-dom'
|
||||
import { vi } from 'vitest'
|
||||
import type { useSettings } from '@/hooks/useSettings'
|
||||
import type { VoiceConversationController } from '@/hooks/useVoiceConversation'
|
||||
@@ -89,14 +89,18 @@ export function renderHookWithRouter<T>(renderFn: () => T, initialEntries?: stri
|
||||
export function LocationCatcher({
|
||||
capturedSearch,
|
||||
capturedPathname,
|
||||
capturedNavigationType,
|
||||
}: {
|
||||
capturedSearch: { current: string }
|
||||
capturedPathname?: { current: string }
|
||||
capturedNavigationType?: { current: string }
|
||||
}) {
|
||||
const location = useLocation()
|
||||
const navigationType = useNavigationType()
|
||||
useEffect(() => {
|
||||
capturedSearch.current = location.search
|
||||
if (capturedPathname) capturedPathname.current = location.pathname
|
||||
if (capturedNavigationType) capturedNavigationType.current = navigationType
|
||||
})
|
||||
return null
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user