mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
feat(frontend): move session activity scanner under the composer
- Keep the model picker visible while a session is active - Render a full-width segmented scanner below the composer via shared ScannerBars - Reduce SessionStatusIndicator to the list-row spinner
This commit is contained in:
1 parent
e8adbb3e65
commit
332fb07f45
15 files changed
+554
-185
No files matched your search
@@ -64,7 +64,7 @@ function ActivityStateIcon({ item, iconClassName }: { item: ActiveWorkItem; icon
|
||||
return <CircleAlert className={cn(iconClassName, 'text-warning')} aria-hidden="true" />
|
||||
}
|
||||
if (item.state === 'running') {
|
||||
return <SessionStatusIndicator sessionID={item.session.id} size="sm" />
|
||||
return <SessionStatusIndicator sessionID={item.session.id} />
|
||||
}
|
||||
if (item.outcome === 'failed') {
|
||||
return <CircleX className={cn(iconClassName, 'text-destructive')} aria-hidden="true" />
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
import { act, render, screen } from '@testing-library/react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { ComposerActivityBar } from './ComposerActivityBar'
|
||||
import { useSessionStatus } from '@/stores/sessionStatusStore'
|
||||
import { stubMatchMedia } from '@/test/test-utils'
|
||||
|
||||
const originalMatchMedia = window.matchMedia
|
||||
const originalResizeObserver = global.ResizeObserver
|
||||
|
||||
class MockResizeObserver {
|
||||
static instances: MockResizeObserver[] = []
|
||||
|
||||
readonly callback: ResizeObserverCallback
|
||||
|
||||
constructor(callback: ResizeObserverCallback) {
|
||||
this.callback = callback
|
||||
MockResizeObserver.instances.push(this)
|
||||
}
|
||||
|
||||
observe() {}
|
||||
|
||||
unobserve() {}
|
||||
|
||||
disconnect() {}
|
||||
|
||||
trigger(width: number) {
|
||||
this.callback(
|
||||
[{ contentRect: { width } } as ResizeObserverEntry],
|
||||
this as unknown as ResizeObserver,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const resetStore = () => {
|
||||
useSessionStatus.setState({
|
||||
statuses: new Map(),
|
||||
statusCache: new Map(),
|
||||
statusRevisions: new Map(),
|
||||
knownSessions: new Set(),
|
||||
outcomes: new Map(),
|
||||
parents: new Map(),
|
||||
directories: new Map(),
|
||||
runningShells: new Map(),
|
||||
revision: 0,
|
||||
})
|
||||
}
|
||||
|
||||
const segmentsOf = (bar: HTMLElement) =>
|
||||
Array.from(bar.firstElementChild?.children ?? []) as HTMLElement[]
|
||||
|
||||
const measureWidth = (width: number) => {
|
||||
act(() => {
|
||||
MockResizeObserver.instances.forEach((instance) => instance.trigger(width))
|
||||
})
|
||||
}
|
||||
|
||||
describe('ComposerActivityBar', () => {
|
||||
beforeEach(() => {
|
||||
resetStore()
|
||||
MockResizeObserver.instances = []
|
||||
global.ResizeObserver = MockResizeObserver as unknown as typeof ResizeObserver
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
global.ResizeObserver = originalResizeObserver
|
||||
Object.defineProperty(window, 'matchMedia', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: originalMatchMedia,
|
||||
})
|
||||
})
|
||||
|
||||
it('renders nothing when the session is idle without background activity', () => {
|
||||
const { container } = render(<ComposerActivityBar sessionID="session-a" />)
|
||||
|
||||
expect(container).toBeEmptyDOMElement()
|
||||
})
|
||||
|
||||
it('anchors a pointer-transparent progressbar in the gap below the composer', () => {
|
||||
useSessionStatus.getState().setStatus('session-a', { type: 'busy' })
|
||||
|
||||
render(<ComposerActivityBar sessionID="session-a" />)
|
||||
|
||||
const bar = screen.getByRole('progressbar', { name: 'Session working' })
|
||||
expect(bar).toHaveClass('pointer-events-none')
|
||||
expect(bar).toHaveClass('absolute')
|
||||
expect(bar).toHaveClass('inset-x-3')
|
||||
expect(bar).toHaveClass('-bottom-[13px]')
|
||||
expect(bar).toHaveClass('md:-bottom-[11px]')
|
||||
expect(bar).toHaveClass('flex')
|
||||
})
|
||||
|
||||
it('fills the measured width with 4x8 segments', () => {
|
||||
useSessionStatus.getState().setStatus('session-a', { type: 'busy' })
|
||||
|
||||
render(<ComposerActivityBar sessionID="session-a" />)
|
||||
|
||||
const bar = screen.getByRole('progressbar', { name: 'Session working' })
|
||||
expect(bar.firstElementChild).toHaveClass('gap-0.5')
|
||||
|
||||
measureWidth(602)
|
||||
|
||||
const segments = segmentsOf(bar)
|
||||
expect(segments).toHaveLength(100)
|
||||
expect(segments[0]).toHaveClass('w-1')
|
||||
expect(segments[0]).toHaveClass('h-2')
|
||||
expect(segments[0]).toHaveClass('rounded-[1px]')
|
||||
expect(segments[0]).toHaveClass('transition-colors')
|
||||
expect(segments[0]).toHaveClass('duration-75')
|
||||
expect(segments[0]).not.toHaveClass('flex-1')
|
||||
})
|
||||
|
||||
it('keeps the minimum segment count for narrow containers', () => {
|
||||
useSessionStatus.getState().setStatus('session-a', { type: 'busy' })
|
||||
|
||||
render(<ComposerActivityBar sessionID="session-a" />)
|
||||
|
||||
const bar = screen.getByRole('progressbar', { name: 'Session working' })
|
||||
measureWidth(20)
|
||||
|
||||
expect(segmentsOf(bar)).toHaveLength(12)
|
||||
})
|
||||
|
||||
it('lights the info tiers around the scanner window', () => {
|
||||
useSessionStatus.getState().setStatus('session-a', { type: 'busy' })
|
||||
|
||||
render(<ComposerActivityBar sessionID="session-a" />)
|
||||
|
||||
measureWidth(602)
|
||||
|
||||
const segments = segmentsOf(screen.getByRole('progressbar', { name: 'Session working' }))
|
||||
expect(segments[3]).toHaveClass('bg-info')
|
||||
expect(segments[4]).toHaveClass('bg-info/70')
|
||||
expect(segments[6]).toHaveClass('bg-info/40')
|
||||
expect(segments[7]).toHaveClass('bg-info/20')
|
||||
expect(segments[8]).toHaveClass('bg-muted/20')
|
||||
expect(segments[99]).toHaveClass('bg-muted/20')
|
||||
})
|
||||
|
||||
it('renders the compacting state with primary colors', () => {
|
||||
useSessionStatus.getState().setStatus('session-a', { type: 'compact' })
|
||||
|
||||
render(<ComposerActivityBar sessionID="session-a" />)
|
||||
|
||||
measureWidth(602)
|
||||
|
||||
const segments = segmentsOf(screen.getByRole('progressbar', { name: 'Compacting' }))
|
||||
expect(segments[3]).toHaveClass('bg-primary')
|
||||
expect(segments[4]).toHaveClass('bg-primary/70')
|
||||
expect(segments[6]).toHaveClass('bg-primary/40')
|
||||
expect(segments[7]).toHaveClass('bg-primary/20')
|
||||
expect(segments[8]).toHaveClass('bg-muted/20')
|
||||
})
|
||||
|
||||
it('reports the retry attempt in the label with warning colors', () => {
|
||||
useSessionStatus.getState().setStatus('session-a', {
|
||||
type: 'retry',
|
||||
attempt: 2,
|
||||
message: 'rate limited',
|
||||
next: Date.now() + 5_000,
|
||||
})
|
||||
|
||||
render(<ComposerActivityBar sessionID="session-a" />)
|
||||
|
||||
measureWidth(602)
|
||||
|
||||
const segments = segmentsOf(screen.getByRole('progressbar', { name: 'Retrying (Retry #2)' }))
|
||||
expect(segments[3]).toHaveClass('bg-warning')
|
||||
expect(segments[4]).toHaveClass('bg-warning/70')
|
||||
expect(segments[6]).toHaveClass('bg-warning/40')
|
||||
expect(segments[7]).toHaveClass('bg-warning/20')
|
||||
expect(segments[8]).toHaveClass('bg-muted/20')
|
||||
})
|
||||
|
||||
it('renders the muted background activity state when idle with a running shell', () => {
|
||||
useSessionStatus.getState().setShellRunning('shell-1', 'session-a', '/repo')
|
||||
|
||||
render(<ComposerActivityBar sessionID="session-a" />)
|
||||
|
||||
measureWidth(602)
|
||||
|
||||
const segments = segmentsOf(screen.getByRole('progressbar', { name: 'Background tasks running' }))
|
||||
expect(segments[3]).toHaveClass('bg-muted-foreground')
|
||||
expect(segments[4]).toHaveClass('bg-muted-foreground/70')
|
||||
expect(segments[6]).toHaveClass('bg-muted-foreground/40')
|
||||
expect(segments[7]).toHaveClass('bg-muted-foreground/20')
|
||||
expect(segments[8]).toHaveClass('bg-muted/20')
|
||||
})
|
||||
|
||||
it('sweeps the lit window on the step interval', () => {
|
||||
vi.useFakeTimers()
|
||||
useSessionStatus.getState().setStatus('session-a', { type: 'busy' })
|
||||
|
||||
render(<ComposerActivityBar sessionID="session-a" />)
|
||||
|
||||
const bar = screen.getByRole('progressbar', { name: 'Session working' })
|
||||
measureWidth(602)
|
||||
expect(segmentsOf(bar)[3]).toHaveClass('bg-info')
|
||||
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(120)
|
||||
})
|
||||
|
||||
const segments = segmentsOf(bar)
|
||||
expect(segments[7]).toHaveClass('bg-info')
|
||||
expect(segments[4]).toHaveClass('bg-info/40')
|
||||
})
|
||||
|
||||
it('renders every segment statically when reduced motion is requested', () => {
|
||||
vi.useFakeTimers()
|
||||
stubMatchMedia(true)
|
||||
useSessionStatus.getState().setStatus('session-a', { type: 'busy' })
|
||||
|
||||
render(<ComposerActivityBar sessionID="session-a" />)
|
||||
|
||||
const bar = screen.getByRole('progressbar', { name: 'Session working' })
|
||||
measureWidth(602)
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(600)
|
||||
})
|
||||
|
||||
const segments = segmentsOf(bar)
|
||||
expect(segments).toHaveLength(100)
|
||||
expect(segments.every((segment) => segment.classList.contains('bg-info/60'))).toBe(true)
|
||||
expect(segments.some((segment) => segment.classList.contains('bg-muted/20'))).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,62 @@
|
||||
import { ScannerBars, type ScannerTone } from '@/components/ui/scanner-bars'
|
||||
import { useHasBackgroundActivity, useSessionStatusForSession } from '@/stores/sessionStatusStore'
|
||||
|
||||
interface ComposerActivityBarProps {
|
||||
sessionID: string
|
||||
}
|
||||
|
||||
const LIT_WIDTH = 6
|
||||
const STEP_INTERVAL_MS = 30
|
||||
|
||||
const ACTIVITY_PRESENTATION = {
|
||||
background: {
|
||||
label: 'Background tasks running',
|
||||
tone: 'muted-foreground',
|
||||
},
|
||||
busy: {
|
||||
label: 'Session working',
|
||||
tone: 'info',
|
||||
},
|
||||
compact: {
|
||||
label: 'Compacting',
|
||||
tone: 'primary',
|
||||
},
|
||||
retry: {
|
||||
label: 'Retrying',
|
||||
tone: 'warning',
|
||||
},
|
||||
} as const satisfies Record<string, { label: string; tone: ScannerTone }>
|
||||
|
||||
/**
|
||||
* Session activity scanner anchored in the gap below the composer frame. The strip uses the same
|
||||
* 4x8px segments as the session status scanner and fills the composer width with as many segments
|
||||
* as fit. Renders nothing while the session is idle and has no background activity; otherwise
|
||||
* announces the current activity through an indeterminate progressbar.
|
||||
*/
|
||||
export function ComposerActivityBar({ sessionID }: ComposerActivityBarProps) {
|
||||
const status = useSessionStatusForSession(sessionID)
|
||||
const hasBackgroundActivity = useHasBackgroundActivity(sessionID)
|
||||
|
||||
if (status.type === 'idle' && !hasBackgroundActivity) {
|
||||
return null
|
||||
}
|
||||
|
||||
const activity = status.type === 'idle'
|
||||
? ACTIVITY_PRESENTATION.background
|
||||
: ACTIVITY_PRESENTATION[status.type]
|
||||
const label = status.type === 'retry'
|
||||
? `${ACTIVITY_PRESENTATION.retry.label} (Retry #${status.attempt})`
|
||||
: activity.label
|
||||
|
||||
return (
|
||||
<div
|
||||
role="progressbar"
|
||||
aria-label={label}
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={100}
|
||||
className="pointer-events-none absolute inset-x-3 -bottom-[13px] md:-bottom-[11px] flex"
|
||||
>
|
||||
<ScannerBars tone={activity.tone} litWidth={LIT_WIDTH} intervalMs={STEP_INTERVAL_MS} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -103,10 +103,6 @@ vi.mock('@/hooks/useSessionPermissionMode', () => ({
|
||||
useSessionPermissionMode: () => ({ data: undefined }),
|
||||
}))
|
||||
|
||||
vi.mock('@/components/ui/session-status-indicator', () => ({
|
||||
SessionStatusIndicator: () => <div>SessionStatus</div>,
|
||||
}))
|
||||
|
||||
vi.mock('./ComposerToolsMenu', () => ({
|
||||
ComposerToolsMenu: () => null,
|
||||
}))
|
||||
@@ -274,6 +270,23 @@ describe('PromptInput command submission', () => {
|
||||
expect(screen.getByRole('status')).toHaveTextContent('Background tasks running')
|
||||
})
|
||||
|
||||
it('keeps the model picker visible while the session is active', async () => {
|
||||
const queryClient = createTestQueryClient()
|
||||
queryClient.setQueryData(['opencode', 'session', 'test-session', '/test'], sessionInfo())
|
||||
const buildPrompt = (props: { isSessionActive?: boolean }) => (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<PromptInput {...defaultProps} {...props} />
|
||||
</QueryClientProvider>
|
||||
)
|
||||
|
||||
const { rerender } = render(buildPrompt({}))
|
||||
await screen.findByPlaceholderText('Send a message...')
|
||||
expect(screen.getByTestId('model-quick-select').querySelector('button')).not.toBeNull()
|
||||
|
||||
rerender(buildPrompt({ isSessionActive: true }))
|
||||
expect(screen.getByTestId('model-quick-select').querySelector('button')).not.toBeNull()
|
||||
})
|
||||
|
||||
it('disables submit and does not run a command while the model is not ready', async () => {
|
||||
mocks.useModelSelection.mockReturnValue({
|
||||
model: null,
|
||||
|
||||
@@ -122,10 +122,6 @@ vi.mock('@/components/session/SessionSandboxMenu', () => ({
|
||||
SessionSandboxMenu: () => null,
|
||||
}))
|
||||
|
||||
vi.mock('@/components/ui/session-status-indicator', () => ({
|
||||
SessionStatusIndicator: () => <div>SessionStatus</div>,
|
||||
}))
|
||||
|
||||
vi.mock('./PromptSuggestions', () => ({
|
||||
PromptSuggestions: () => null,
|
||||
}))
|
||||
|
||||
@@ -89,10 +89,6 @@ vi.mock('@/hooks/useSessionPermissionMode', () => ({
|
||||
useSessionPermissionMode: () => ({ data: undefined }),
|
||||
}))
|
||||
|
||||
vi.mock('@/components/ui/session-status-indicator', () => ({
|
||||
SessionStatusIndicator: () => <div>SessionStatus</div>,
|
||||
}))
|
||||
|
||||
vi.mock('./PromptSuggestions', () => ({
|
||||
PromptSuggestions: (props: { isOpen: boolean; selectedIndex: number }) => {
|
||||
if (props.isOpen) {
|
||||
|
||||
@@ -121,10 +121,6 @@ vi.mock('@/hooks/useSessionPermissionMode', () => ({
|
||||
useSessionPermissionMode: () => ({ data: undefined }),
|
||||
}))
|
||||
|
||||
vi.mock('@/components/ui/session-status-indicator', () => ({
|
||||
SessionStatusIndicator: () => <div>SessionStatus</div>,
|
||||
}))
|
||||
|
||||
vi.mock('./PromptSuggestions', () => ({
|
||||
PromptSuggestions: () => null,
|
||||
}))
|
||||
|
||||
@@ -25,7 +25,7 @@ import { SquareFill } from '@/components/ui/square-fill'
|
||||
import { IconToggleButton } from '@/components/ui/icon-toggle-button'
|
||||
|
||||
import { PromptSuggestions, type PromptSuggestion } from './PromptSuggestions'
|
||||
import { SessionStatusIndicator } from '@/components/ui/session-status-indicator'
|
||||
import { ComposerActivityBar } from './ComposerActivityBar'
|
||||
import { ModelQuickSelect } from '@/components/model/ModelQuickSelect'
|
||||
import { AgentQuickSelect } from '@/components/agent/AgentQuickSelect'
|
||||
import { VoiceStatusOverlay, type VoiceStatusOverlayState } from './VoiceStatusOverlay'
|
||||
@@ -1488,10 +1488,11 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
|
||||
: ''
|
||||
|
||||
return (
|
||||
<div className={`relative isolate border border-border dark:border-border/30 rounded-xl p-2 md:p-3 mb-4 md:mb-1 w-full before:pointer-events-none before:absolute before:-inset-px before:-z-10 before:rounded-xl before:bg-background/95 before:backdrop-blur-md before:content-[''] ${hasPendingPermissionForSession ? 'border-highlight/50 ring-1 ring-highlight/30' : composerModeStyle?.frame ?? ''} ${isTakeoverOpen ? 'z-[60]' : ''}`}>
|
||||
<div className={`relative isolate border border-border dark:border-border/30 rounded-xl p-2 md:p-3 mb-4 md:mb-3 w-full before:pointer-events-none before:absolute before:-inset-px before:-z-10 before:rounded-xl before:bg-background/95 before:backdrop-blur-md before:content-[''] ${hasPendingPermissionForSession ? 'border-highlight/50 ring-1 ring-highlight/30' : composerModeStyle?.frame ?? ''} ${isTakeoverOpen ? 'z-[60]' : ''}`}>
|
||||
<div role="status" aria-live="polite" className="sr-only">
|
||||
{sessionActivityAnnouncement}
|
||||
</div>
|
||||
<ComposerActivityBar sessionID={sessionID} />
|
||||
{composerModeStyle && (
|
||||
<span
|
||||
data-testid="composer-mode-badge"
|
||||
@@ -1559,11 +1560,6 @@ return (
|
||||
<ArrowDown className="w-4 h-4" />
|
||||
<span>Latest</span>
|
||||
</button>
|
||||
{(isSessionActive || hasBackgroundActivity) && (
|
||||
<div className="px-2.5 py-1.5 rounded-lg text-xs font-medium text-muted-foreground max-w-[120px]">
|
||||
<SessionStatusIndicator sessionID={sessionID} showLabel />
|
||||
</div>
|
||||
)}
|
||||
<ModelQuickSelect
|
||||
directory={directory}
|
||||
open={isModelPickerOpen}
|
||||
@@ -1593,18 +1589,13 @@ return (
|
||||
</IconToggleButton>
|
||||
</>
|
||||
) : null}
|
||||
{(isSessionActive || hasBackgroundActivity) && (
|
||||
<div className="px-2.5 py-1.5 md:px-3 md:py-2 rounded-lg text-xs md:text-sm font-medium text-muted-foreground max-w-[120px] md:max-w-[180px]">
|
||||
<SessionStatusIndicator sessionID={sessionID} showLabel />
|
||||
</div>
|
||||
)}
|
||||
<ModelQuickSelect
|
||||
directory={directory}
|
||||
open={isModelPickerOpen}
|
||||
onOpenChange={setIsModelPickerOpen}
|
||||
session={modelSelectionSession}
|
||||
>
|
||||
{!isSessionActive && !hideSecondaryButtons && (
|
||||
{!hideSecondaryButtons && (
|
||||
<button
|
||||
className="px-2.5 py-0.5 md:px-3 min-h-[44px] md:min-h-[36px] min-w-0 rounded-lg text-xs md:text-sm font-medium border bg-muted border-border text-muted-foreground hover:bg-muted-foreground/10 hover:border-foreground/30 transition-colors cursor-pointer flex-1 md:flex-initial md:w-auto md:max-w-[220px] dark:border-border/30 flex flex-col items-start justify-center overflow-hidden"
|
||||
>
|
||||
|
||||
@@ -145,7 +145,7 @@ export function SessionNavRow({ item, isCurrent, onSelect, repoLabel }: SessionN
|
||||
{item.worktreeBranch}
|
||||
</span>
|
||||
)}
|
||||
<SessionStatusIndicator sessionID={item.session.id} size="sm" />
|
||||
<SessionStatusIndicator sessionID={item.session.id} />
|
||||
{hasPermission(item.session.id) && (
|
||||
<Bell className="h-3 w-3 shrink-0 text-highlight" aria-label="Pending permission" />
|
||||
)}
|
||||
|
||||
@@ -329,7 +329,7 @@ function EntryRow({
|
||||
<p className="truncate text-sm font-medium">{entry.model}</p>
|
||||
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
|
||||
<StatusPill label={readiness.label} tone={readiness.tone} />
|
||||
{readiness.label === 'Running' && sessionId ? <SessionStatusIndicator sessionID={sessionId} size="sm" /> : null}
|
||||
{readiness.label === 'Running' && sessionId ? <SessionStatusIndicator sessionID={sessionId} /> : null}
|
||||
<span className="text-xs text-muted-foreground">{isolationLabel}</span>
|
||||
</div>
|
||||
{detail ? (
|
||||
@@ -389,7 +389,7 @@ function FusionRow({ fusion, onOpenSession, onWalkthrough }: FusionRowProps) {
|
||||
<p className="truncate text-sm font-medium">{fusion.model}</p>
|
||||
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
|
||||
<StatusPill label={status.label} tone={status.tone} />
|
||||
{fusion.status === 'started' && sessionId ? <SessionStatusIndicator sessionID={sessionId} size="sm" /> : null}
|
||||
{fusion.status === 'started' && sessionId ? <SessionStatusIndicator sessionID={sessionId} /> : null}
|
||||
<span className="text-xs text-muted-foreground">
|
||||
<span>
|
||||
from {fusion.sources.length} source{fusion.sources.length === 1 ? '' : 's'}
|
||||
|
||||
@@ -95,7 +95,7 @@ export const SessionCard = ({
|
||||
}}
|
||||
className="w-5 h-5 flex-shrink-0"
|
||||
/>
|
||||
<SessionStatusIndicator sessionID={session.id} size="sm" />
|
||||
<SessionStatusIndicator sessionID={session.id} />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-1">
|
||||
@@ -130,7 +130,7 @@ export const SessionCard = ({
|
||||
addSuffix: true,
|
||||
})}
|
||||
</span>
|
||||
<SessionStatusIndicator sessionID={session.id} size="sm" />
|
||||
<SessionStatusIndicator sessionID={session.id} />
|
||||
</div>
|
||||
</div>
|
||||
{onTogglePin && (
|
||||
|
||||
@@ -181,7 +181,7 @@ function SessionPickerGutter({ sessionID, isActive }: { sessionID: string; isAct
|
||||
const status = useSessionStatusForSession(sessionID)
|
||||
if (status.type !== 'idle') {
|
||||
return (
|
||||
<SessionStatusIndicator sessionID={sessionID} size="sm" />
|
||||
<SessionStatusIndicator sessionID={sessionID} />
|
||||
)
|
||||
}
|
||||
if (isActive) {
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
import { useLayoutEffect, useRef, useState, type RefObject } from 'react'
|
||||
import { useMediaQuery } from '@/hooks/useMediaQuery'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export type ScannerTone = 'info' | 'primary' | 'warning' | 'muted-foreground'
|
||||
|
||||
export const SCANNER_REDUCED_MOTION_QUERY = '(prefers-reduced-motion: reduce)'
|
||||
|
||||
const SCANNER_SEGMENT_WIDTH = 4
|
||||
const SCANNER_SEGMENT_GAP = 2
|
||||
const SCANNER_SEGMENT_PITCH = SCANNER_SEGMENT_WIDTH + SCANNER_SEGMENT_GAP
|
||||
const SCANNER_MIN_SEGMENTS = 12
|
||||
|
||||
const SCANNER_SEGMENT_CLASS = 'w-1 h-2 rounded-[1px] transition-colors duration-75'
|
||||
|
||||
const SCANNER_TONE_TIERS: Record<ScannerTone, readonly [string, string, string, string]> = {
|
||||
info: ['bg-info', 'bg-info/70', 'bg-info/40', 'bg-info/20'],
|
||||
primary: ['bg-primary', 'bg-primary/70', 'bg-primary/40', 'bg-primary/20'],
|
||||
warning: ['bg-warning', 'bg-warning/70', 'bg-warning/40', 'bg-warning/20'],
|
||||
'muted-foreground': ['bg-muted-foreground', 'bg-muted-foreground/70', 'bg-muted-foreground/40', 'bg-muted-foreground/20'],
|
||||
}
|
||||
|
||||
const SCANNER_STATIC_TONE_CLASS: Record<ScannerTone, string> = {
|
||||
info: 'bg-info/60',
|
||||
primary: 'bg-primary/60',
|
||||
warning: 'bg-warning/60',
|
||||
'muted-foreground': 'bg-muted-foreground/60',
|
||||
}
|
||||
|
||||
const SCANNER_OFF_CLASS = 'bg-muted/20'
|
||||
const SCANNER_INTENSITY_THRESHOLDS = [0.8, 0.5, 0.2] as const
|
||||
const SCANNER_FAINTEST_TIER = SCANNER_INTENSITY_THRESHOLDS.length
|
||||
|
||||
/**
|
||||
* Returns how many fixed-width segments fit into `width`: each segment is 4px wide and the
|
||||
* container adds a 2px gap between neighbors, so `n` segments occupy `6n - 2` pixels. Never
|
||||
* drops below `SCANNER_MIN_SEGMENTS` so an unmeasured container still renders a usable scanner.
|
||||
*/
|
||||
export function scannerSegmentCountForWidth(width: number): number {
|
||||
return Math.max(SCANNER_MIN_SEGMENTS, Math.floor((width + SCANNER_SEGMENT_GAP) / SCANNER_SEGMENT_PITCH))
|
||||
}
|
||||
|
||||
/**
|
||||
* Tracks the content width of a container across resizes. Returns 0 until the first measurement.
|
||||
*/
|
||||
function useContainerWidth(ref: RefObject<HTMLElement | null>): number {
|
||||
const [width, setWidth] = useState(0)
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const element = ref.current
|
||||
if (!element) {
|
||||
return
|
||||
}
|
||||
|
||||
const update = (next: number) => setWidth((previous) => (previous === next ? previous : next))
|
||||
update(element.getBoundingClientRect().width)
|
||||
|
||||
if (typeof ResizeObserver === 'undefined') {
|
||||
return
|
||||
}
|
||||
|
||||
const observer = new ResizeObserver((entries) => {
|
||||
const entry = entries[0]
|
||||
if (entry) {
|
||||
update(entry.contentRect.width)
|
||||
}
|
||||
})
|
||||
observer.observe(element)
|
||||
return () => observer.disconnect()
|
||||
}, [ref])
|
||||
|
||||
return width
|
||||
}
|
||||
|
||||
interface ScannerSegmentClassOptions {
|
||||
index: number
|
||||
position: number
|
||||
litWidth: number
|
||||
tone: ScannerTone
|
||||
static?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the background class for one scanner segment. Segments within the lit window fade out
|
||||
* with distance from the window center across four intensity tiers; everything outside the window
|
||||
* stays muted. `static` skips the window math and renders the uniform reduced-motion tint.
|
||||
*/
|
||||
export function scannerSegmentClass({
|
||||
index,
|
||||
position,
|
||||
litWidth,
|
||||
tone,
|
||||
static: isStatic = false,
|
||||
}: ScannerSegmentClassOptions): string {
|
||||
if (isStatic) {
|
||||
return SCANNER_STATIC_TONE_CLASS[tone]
|
||||
}
|
||||
|
||||
const halfWidth = litWidth / 2
|
||||
const distance = Math.abs(index - (position + halfWidth))
|
||||
|
||||
if (distance > halfWidth + 1) {
|
||||
return SCANNER_OFF_CLASS
|
||||
}
|
||||
|
||||
const intensity = Math.max(0, 1 - distance / (halfWidth + 2))
|
||||
const tier = SCANNER_INTENSITY_THRESHOLDS.findIndex((threshold) => intensity > threshold)
|
||||
|
||||
return SCANNER_TONE_TIERS[tone][tier === -1 ? SCANNER_FAINTEST_TIER : tier]
|
||||
}
|
||||
|
||||
interface ScannerPositionOptions {
|
||||
segmentCount: number
|
||||
litWidth: number
|
||||
intervalMs: number
|
||||
paused: boolean
|
||||
}
|
||||
|
||||
function useScannerPosition({
|
||||
segmentCount,
|
||||
litWidth,
|
||||
intervalMs,
|
||||
paused,
|
||||
}: ScannerPositionOptions): number {
|
||||
const [position, setPosition] = useState(0)
|
||||
const direction = useRef(1)
|
||||
const maxPosition = Math.max(0, segmentCount - litWidth)
|
||||
|
||||
useLayoutEffect(() => {
|
||||
setPosition((previous) => Math.min(previous, maxPosition))
|
||||
}, [maxPosition])
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (paused || maxPosition === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
const interval = setInterval(() => {
|
||||
setPosition((previous) => {
|
||||
const next = previous + direction.current
|
||||
if (next >= maxPosition) {
|
||||
direction.current = -1
|
||||
return maxPosition
|
||||
}
|
||||
if (next <= 0) {
|
||||
direction.current = 1
|
||||
return 0
|
||||
}
|
||||
return next
|
||||
})
|
||||
}, intervalMs)
|
||||
|
||||
return () => clearInterval(interval)
|
||||
}, [paused, maxPosition, intervalMs])
|
||||
|
||||
return position
|
||||
}
|
||||
|
||||
interface ScannerBarsProps {
|
||||
tone: ScannerTone
|
||||
segmentCount?: number
|
||||
litWidth?: number
|
||||
intervalMs?: number
|
||||
className?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Segmented scanner matching the session status scanner: 4x8px segments with a 2px gap and a lit
|
||||
* window of `litWidth` segments that sweeps back and forth. Without an explicit `segmentCount` the
|
||||
* count is measured from the container width so the strip spans the space it is given. Under
|
||||
* `prefers-reduced-motion: reduce` the sweep is not started and every segment renders statically at
|
||||
* 60% opacity.
|
||||
*/
|
||||
export function ScannerBars({
|
||||
tone,
|
||||
segmentCount,
|
||||
litWidth = 6,
|
||||
intervalMs = 60,
|
||||
className,
|
||||
}: ScannerBarsProps) {
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const reducedMotion = useMediaQuery(SCANNER_REDUCED_MOTION_QUERY)
|
||||
const measuredWidth = useContainerWidth(containerRef)
|
||||
const resolvedCount = segmentCount ?? scannerSegmentCountForWidth(measuredWidth)
|
||||
const position = useScannerPosition({
|
||||
segmentCount: resolvedCount,
|
||||
litWidth,
|
||||
intervalMs,
|
||||
paused: reducedMotion,
|
||||
})
|
||||
|
||||
return (
|
||||
<div ref={containerRef} className={cn('flex w-full items-center gap-0.5', className)}>
|
||||
{Array.from({ length: resolvedCount }, (_, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className={cn(
|
||||
SCANNER_SEGMENT_CLASS,
|
||||
scannerSegmentClass({ index, position, litWidth, tone, static: reducedMotion }),
|
||||
)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -26,13 +26,13 @@ describe('SessionStatusIndicator background activity', () => {
|
||||
it('shows the background tasks label when idle with a running shell', () => {
|
||||
useSessionStatus.getState().setShellRunning('shell-1', 'session-a', '/repo')
|
||||
|
||||
render(<SessionStatusIndicator sessionID="session-a" showLabel />)
|
||||
render(<SessionStatusIndicator sessionID="session-a" />)
|
||||
|
||||
expect(screen.getByLabelText('Background tasks running')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders nothing when idle without background activity', () => {
|
||||
const { container } = render(<SessionStatusIndicator sessionID="session-a" showLabel />)
|
||||
const { container } = render(<SessionStatusIndicator sessionID="session-a" />)
|
||||
|
||||
expect(container).toBeEmptyDOMElement()
|
||||
})
|
||||
@@ -40,7 +40,7 @@ describe('SessionStatusIndicator background activity', () => {
|
||||
it('renders the braille spinner with a running label for a busy session', () => {
|
||||
useSessionStatus.getState().setStatus('session-a', { type: 'busy' })
|
||||
|
||||
const { container } = render(<SessionStatusIndicator sessionID="session-a" size="sm" />)
|
||||
const { container } = render(<SessionStatusIndicator sessionID="session-a" />)
|
||||
|
||||
expect(screen.getByLabelText('Running')).toBeInTheDocument()
|
||||
const litDots = container.querySelectorAll('svg[aria-hidden="true"] circle[fill-opacity="1"]')
|
||||
|
||||
@@ -1,169 +1,51 @@
|
||||
import { memo, useEffect, useState } from 'react'
|
||||
import { memo } from 'react'
|
||||
import { ActivitySpinner } from '@/components/ui/activity-spinner'
|
||||
import { useHasBackgroundActivity, useSessionStatusForSession, type SessionStatusType } from '@/stores/sessionStatusStore'
|
||||
import { useHasBackgroundActivity, useSessionStatusForSession } from '@/stores/sessionStatusStore'
|
||||
|
||||
interface SessionStatusIndicatorProps {
|
||||
sessionID: string
|
||||
className?: string
|
||||
size?: 'sm' | 'md'
|
||||
showLabel?: boolean
|
||||
}
|
||||
|
||||
const SCANNER_WIDTH = 6
|
||||
const SCANNER_SEGMENTS = 12
|
||||
|
||||
/**
|
||||
* Shows a session's activity. `sm` renders the braille spinner sized for list rows;
|
||||
* `md` renders the animated scanner used by the session composer.
|
||||
* Shows a session's activity as the braille spinner sized for list rows.
|
||||
* Renders nothing while the session is idle and has no background activity.
|
||||
*/
|
||||
export const SessionStatusIndicator = memo(function SessionStatusIndicator({
|
||||
sessionID,
|
||||
export const SessionStatusIndicator = memo(function SessionStatusIndicator({
|
||||
sessionID,
|
||||
className = '',
|
||||
size = 'md',
|
||||
showLabel = false
|
||||
}: SessionStatusIndicatorProps) {
|
||||
const status = useSessionStatusForSession(sessionID)
|
||||
const hasBackground = useHasBackgroundActivity(sessionID)
|
||||
const [position, setPosition] = useState(0)
|
||||
const [direction, setDirection] = useState(1)
|
||||
const [retryCountdown, setRetryCountdown] = useState(0)
|
||||
const backgroundOnly = status.type === 'idle' && hasBackground
|
||||
|
||||
useEffect(() => {
|
||||
if (size !== 'md') {
|
||||
return
|
||||
}
|
||||
if (status.type === 'idle' && !hasBackground) {
|
||||
return
|
||||
}
|
||||
|
||||
const interval = setInterval(() => {
|
||||
setPosition(prev => {
|
||||
const next = prev + direction
|
||||
if (next >= SCANNER_SEGMENTS - SCANNER_WIDTH) {
|
||||
setDirection(-1)
|
||||
return SCANNER_SEGMENTS - SCANNER_WIDTH
|
||||
}
|
||||
if (next <= 0) {
|
||||
setDirection(1)
|
||||
return 0
|
||||
}
|
||||
return next
|
||||
})
|
||||
}, 60)
|
||||
|
||||
return () => clearInterval(interval)
|
||||
}, [size, status.type, hasBackground, direction])
|
||||
|
||||
useEffect(() => {
|
||||
if (!showLabel || status.type !== 'retry') {
|
||||
setRetryCountdown(0)
|
||||
return
|
||||
}
|
||||
|
||||
const remaining = Math.max(0, Math.ceil((status.next - Date.now()) / 1000))
|
||||
setRetryCountdown(remaining)
|
||||
|
||||
const interval = setInterval(() => {
|
||||
const newRemaining = Math.max(0, Math.ceil((status.next - Date.now()) / 1000))
|
||||
setRetryCountdown(newRemaining)
|
||||
}, 1000)
|
||||
|
||||
return () => clearInterval(interval)
|
||||
}, [status, showLabel])
|
||||
|
||||
|
||||
if (status.type === 'idle' && !hasBackground) {
|
||||
return null
|
||||
}
|
||||
|
||||
if (size === 'sm') {
|
||||
const colorClass = backgroundOnly
|
||||
? 'text-muted-foreground'
|
||||
: status.type === 'retry'
|
||||
? 'text-warning'
|
||||
: status.type === 'compact'
|
||||
? 'text-primary'
|
||||
: 'text-info'
|
||||
const label = backgroundOnly
|
||||
? 'Background tasks running'
|
||||
: status.type === 'retry'
|
||||
? 'Retrying'
|
||||
: status.type === 'compact'
|
||||
? 'Compacting'
|
||||
: 'Running'
|
||||
|
||||
return (
|
||||
<span
|
||||
role="img"
|
||||
aria-label={label}
|
||||
title={backgroundOnly ? label : undefined}
|
||||
className={`inline-flex items-center ${colorClass} ${className}`}
|
||||
>
|
||||
<ActivitySpinner />
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
const getSegmentColor = (index: number, statusType: SessionStatusType['type'], background: boolean) => {
|
||||
const distance = Math.abs(index - (position + SCANNER_WIDTH / 2))
|
||||
const maxDistance = SCANNER_WIDTH / 2
|
||||
|
||||
if (distance > maxDistance + 1) {
|
||||
return 'bg-muted/20'
|
||||
}
|
||||
|
||||
const intensity = Math.max(0, 1 - distance / (maxDistance + 2))
|
||||
|
||||
if (background) {
|
||||
if (intensity > 0.8) return 'bg-muted-foreground'
|
||||
if (intensity > 0.5) return 'bg-muted-foreground/70'
|
||||
if (intensity > 0.2) return 'bg-muted-foreground/40'
|
||||
return 'bg-muted-foreground/20'
|
||||
}
|
||||
const colorClass = backgroundOnly
|
||||
? 'text-muted-foreground'
|
||||
: status.type === 'retry'
|
||||
? 'text-warning'
|
||||
: status.type === 'compact'
|
||||
? 'text-primary'
|
||||
: 'text-info'
|
||||
const label = backgroundOnly
|
||||
? 'Background tasks running'
|
||||
: status.type === 'retry'
|
||||
? 'Retrying'
|
||||
: status.type === 'compact'
|
||||
? 'Compacting'
|
||||
: 'Running'
|
||||
|
||||
if (statusType === 'retry') {
|
||||
if (intensity > 0.8) return 'bg-warning'
|
||||
if (intensity > 0.5) return 'bg-warning/70'
|
||||
if (intensity > 0.2) return 'bg-warning/40'
|
||||
return 'bg-warning/20'
|
||||
}
|
||||
|
||||
if (statusType === 'compact') {
|
||||
if (intensity > 0.8) return 'bg-primary'
|
||||
if (intensity > 0.5) return 'bg-primary/70'
|
||||
if (intensity > 0.2) return 'bg-primary/40'
|
||||
return 'bg-primary/20'
|
||||
}
|
||||
|
||||
if (intensity > 0.8) return 'bg-info'
|
||||
if (intensity > 0.5) return 'bg-info/70'
|
||||
if (intensity > 0.2) return 'bg-info/40'
|
||||
return 'bg-info/20'
|
||||
}
|
||||
|
||||
const segmentClass = 'w-1 h-4'
|
||||
const containerGap = showLabel ? 'gap-2' : ''
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`flex items-center ${containerGap} ${className}`}
|
||||
title={backgroundOnly ? 'Background tasks running' : undefined}
|
||||
aria-label={backgroundOnly ? 'Background tasks running' : undefined}
|
||||
<span
|
||||
role="img"
|
||||
aria-label={label}
|
||||
title={backgroundOnly ? label : undefined}
|
||||
className={`inline-flex items-center ${colorClass} ${className}`}
|
||||
>
|
||||
<div className="flex gap-0.5">
|
||||
{Array.from({ length: SCANNER_SEGMENTS }).map((_, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className={`${segmentClass} rounded-sm transition-colors duration-75 ${getSegmentColor(i, status.type, backgroundOnly)}`}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
{showLabel && status.type === 'retry' && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Retry #{status.attempt}
|
||||
{retryCountdown > 0 && <span className="text-warning ml-1">({retryCountdown}s)</span>}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<ActivitySpinner />
|
||||
</span>
|
||||
)
|
||||
})
|
||||
Reference in new issue
Block a user