diff --git a/frontend/src/components/session/ContextUsageIndicator.test.tsx b/frontend/src/components/session/ContextUsageIndicator.test.tsx deleted file mode 100644 index 3e835c9e..00000000 --- a/frontend/src/components/session/ContextUsageIndicator.test.tsx +++ /dev/null @@ -1,52 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { render, screen } from '@testing-library/react' -import { ContextUsageIndicator } from './ContextUsageIndicator' - -const mocks = vi.hoisted(() => ({ - useContextUsage: vi.fn(), - useMobile: vi.fn(), -})) - -vi.mock('@/hooks/useContextUsage', () => ({ - useContextUsage: mocks.useContextUsage, -})) - -vi.mock('@/hooks/useMobile', () => ({ - useMobile: mocks.useMobile, -})) - -function renderIndicator() { - return render() -} - -describe('ContextUsageIndicator', () => { - beforeEach(() => { - vi.clearAllMocks() - }) - - it('renders tokens and percentage on desktop', () => { - mocks.useMobile.mockReturnValue(false) - mocks.useContextUsage.mockReturnValue({ usage: { totalTokens: 1234, usagePercentage: 42 }, isLoading: false }) - renderIndicator() - - expect(screen.getByText('1,234 (42%)')).toBeInTheDocument() - expect(screen.queryByText('42%')).not.toBeInTheDocument() - }) - - it('renders only the percentage on mobile', () => { - mocks.useMobile.mockReturnValue(true) - mocks.useContextUsage.mockReturnValue({ usage: { totalTokens: 1234, usagePercentage: 42 }, isLoading: false }) - renderIndicator() - - expect(screen.getByText('42%')).toBeInTheDocument() - expect(screen.queryByText('1,234 (42%)')).not.toBeInTheDocument() - }) - - it('renders only the token count on mobile without a percentage', () => { - mocks.useMobile.mockReturnValue(true) - mocks.useContextUsage.mockReturnValue({ usage: { totalTokens: 1234, usagePercentage: null }, isLoading: false }) - renderIndicator() - - expect(screen.getByText('1,234')).toBeInTheDocument() - }) -}) diff --git a/frontend/src/components/session/ContextUsageIndicator.tsx b/frontend/src/components/session/ContextUsageIndicator.tsx deleted file mode 100644 index 64d4b354..00000000 --- a/frontend/src/components/session/ContextUsageIndicator.tsx +++ /dev/null @@ -1,63 +0,0 @@ -import { useContextUsage } from '@/hooks/useContextUsage' -import { useMobile } from '@/hooks/useMobile' - -interface ContextUsageIndicatorProps { - directory?: string - sessionID: string | undefined - isConnected: boolean - isReconnecting?: boolean - revertMessageID?: string -} - -const getUsageTextColor = (percentage: number) => { - if (percentage < 50) return 'text-success' - if (percentage < 80) return 'text-warning' - return 'text-destructive' -} - -export function ContextUsageIndicator({ - directory, - sessionID, - isConnected, - isReconnecting, - revertMessageID, -}: ContextUsageIndicatorProps) { - const { usage, isLoading } = useContextUsage(sessionID, directory, revertMessageID) - const isMobile = useMobile() - - if (isLoading) { - return ( -
- Loading... -
- ) - } - - if (isReconnecting) { - return Reconnecting... - } - - if (!isConnected) { - return Disconnected - } - - if (!usage) { - return null - } - - const compactText = usage.usagePercentage === null - ? usage.totalTokens.toLocaleString() - : `${usage.usagePercentage}%` - - const fullText = usage.usagePercentage === null - ? usage.totalTokens.toLocaleString() - : `${usage.totalTokens.toLocaleString()} (${usage.usagePercentage}%)` - - return ( -
- - {isMobile ? compactText : fullText} - -
- ) -} diff --git a/frontend/src/components/session/EditSessionTitleDialog.tsx b/frontend/src/components/session/EditSessionTitleDialog.tsx deleted file mode 100644 index 1aa84583..00000000 --- a/frontend/src/components/session/EditSessionTitleDialog.tsx +++ /dev/null @@ -1,105 +0,0 @@ -import { Dialog, DialogContent } from "@/components/ui/dialog"; -import { Button } from "@/components/ui/button"; -import { X, Check } from "lucide-react"; -import { useState, useRef, useEffect } from "react"; -import { useMobile } from "@/hooks/useMobile"; - -interface EditSessionTitleDialogProps { - isOpen: boolean; - currentTitle: string; - onClose: () => void; - onSave: (newTitle: string) => void; -} - -export function EditSessionTitleDialog({ isOpen, currentTitle, onClose, onSave }: EditSessionTitleDialogProps) { - const [editTitle, setEditTitle] = useState(currentTitle); - const inputRef = useRef(null); - const isMobile = useMobile(); - - useEffect(() => { - if (isOpen) { - setEditTitle(currentTitle); - } - }, [isOpen, currentTitle]); - - const handleKeyDown = (e: React.KeyboardEvent) => { - if (e.key === 'Escape') { - setEditTitle(currentTitle); - onClose(); - } else if (e.key === 'Enter') { - if (editTitle.trim() && editTitle !== currentTitle) { - onSave(editTitle.trim()); - } - onClose(); - } - }; - - const handleSubmit = (e: React.FormEvent) => { - e.preventDefault(); - if (editTitle.trim() && editTitle !== currentTitle) { - onSave(editTitle.trim()); - } - onClose(); - }; - - const handleCancel = () => { - setEditTitle(currentTitle); - onClose(); - }; - - return ( - - -
-

Change session title

-
- setEditTitle(e.target.value)} - onKeyDown={handleKeyDown} - className="text-base font-semibold bg-background border border-border rounded px-3 py-2.5 pr-10 outline-none w-full focus:border-primary focus:ring-2 focus:ring-primary/20" - autoFocus - /> - {editTitle && ( - - )} -
-
- - -
-
-
-
- ); -} \ No newline at end of file diff --git a/frontend/src/components/session/ReconnectingBanner.test.tsx b/frontend/src/components/session/ReconnectingBanner.test.tsx new file mode 100644 index 00000000..d203978f --- /dev/null +++ b/frontend/src/components/session/ReconnectingBanner.test.tsx @@ -0,0 +1,36 @@ +import { render, screen } from '@testing-library/react' +import { describe, it, expect } from 'vitest' +import { ReconnectingBanner } from './ReconnectingBanner' + +describe('ReconnectingBanner', () => { + it('stays hidden before the stream has connected', () => { + render() + + expect(screen.queryByRole('status')).not.toBeInTheDocument() + }) + + it('stays hidden while the stream is connected', () => { + render() + + expect(screen.queryByRole('status')).not.toBeInTheDocument() + }) + + it('reports a dropped stream once it connected', () => { + const { rerender } = render() + + rerender() + + const banner = screen.getByRole('status') + expect(banner).toHaveTextContent('Reconnecting… live updates paused') + expect(banner).toHaveAttribute('aria-live', 'polite') + }) + + it('hides again when the stream reconnects', () => { + const { rerender } = render() + + rerender() + rerender() + + expect(screen.queryByRole('status')).not.toBeInTheDocument() + }) +}) diff --git a/frontend/src/components/session/ReconnectingBanner.tsx b/frontend/src/components/session/ReconnectingBanner.tsx new file mode 100644 index 00000000..208fac94 --- /dev/null +++ b/frontend/src/components/session/ReconnectingBanner.tsx @@ -0,0 +1,33 @@ +import { useEffect, useState } from 'react' + +export interface ReconnectingBannerProps { + connected: boolean +} + +/** + * Full-width strip under the session header that reports a paused event + * stream. It stays hidden until the stream has connected at least once, so a + * first paint before the subscription settles does not read as a dropped + * connection. + * + * @param connected Whether the session's event stream is currently connected. + */ +export function ReconnectingBanner({ connected }: ReconnectingBannerProps) { + const [hasConnected, setHasConnected] = useState(false) + + useEffect(() => { + if (connected) setHasConnected(true) + }, [connected]) + + if (connected || !hasConnected) return null + + return ( +
+ Reconnecting… live updates paused +
+ ) +} diff --git a/frontend/src/components/session/SessionDetailsSheet.test.tsx b/frontend/src/components/session/SessionDetailsSheet.test.tsx new file mode 100644 index 00000000..0b204dc8 --- /dev/null +++ b/frontend/src/components/session/SessionDetailsSheet.test.tsx @@ -0,0 +1,237 @@ +import { useState } from 'react' +import { render, screen, fireEvent, act } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { SessionDetailsSheet, type SessionDetailsSheetProps } from './SessionDetailsSheet' + +const mocks = vi.hoisted(() => ({ + useMobile: vi.fn(), + useUpdateSession: vi.fn(), +})) + +vi.mock('@/hooks/useMobile', () => ({ + useMobile: mocks.useMobile, + useSwipeBack: vi.fn(() => ({ bind: vi.fn(), swipeProgress: 0, swipeStyles: {} })), + useSwipeDismiss: vi.fn(() => ({ bind: vi.fn(), swipeProgress: 0, swipeStyles: {} })), +})) + +vi.mock('@/hooks/useOpenCode', () => ({ useUpdateSession: mocks.useUpdateSession })) + +type RenameMutation = { + mutate: ReturnType + reset: ReturnType + 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', +} + +function mockRename(overrides: Partial = {}): RenameMutation { + const mutation: RenameMutation = { + mutate: vi.fn(), + reset: vi.fn(), + error: null, + isPending: false, + ...overrides, + } + mocks.useUpdateSession.mockReturnValue(mutation) + return mutation +} + +function renderSheet(overrides: Partial = {}) { + return render() +} + +describe('SessionDetailsSheet', () => { + beforeEach(() => { + vi.clearAllMocks() + mocks.useMobile.mockReturnValue(false) + mockRename() + }) + + it('lists the local session details', () => { + renderSheet({ branch: 'feat/header', directory: '/abs/repos/oc-manager' }) + + expect(screen.getByText('Session details')).toBeInTheDocument() + expect(screen.getByText('Fix the header')).toBeInTheDocument() + expect(screen.getByText('Local')).toBeInTheDocument() + expect(screen.getByText('oc-manager')).toBeInTheDocument() + expect(screen.getByText('feat/header')).toBeInTheDocument() + expect(screen.getByText('/abs/repos/oc-manager')).toBeInTheDocument() + }) + + it('shows the linked server name and marks the session as remote', () => { + renderSheet({ remote: true, serverName: 'Kitchen' }) + + expect(screen.getByText('Kitchen')).toBeInTheDocument() + }) + + it('falls back to a remote server label without a server name', () => { + renderSheet({ remote: true }) + + expect(screen.getByText('Remote server')).toBeInTheDocument() + }) + + it('omits branch and directory rows when they are unknown', () => { + renderSheet({ branch: null }) + + expect(screen.queryByText('Branch')).not.toBeInTheDocument() + expect(screen.queryByText('Directory')).not.toBeInTheDocument() + }) + + it('falls back to an untitled session label', () => { + renderSheet({ title: ' ' }) + + expect(screen.getByText('Untitled Session')).toBeInTheDocument() + }) + + it('prefills the rename field with the raw title', () => { + renderSheet({ title: ' Raw title ' }) + + fireEvent.click(screen.getByRole('button', { name: 'Rename' })) + + expect(screen.getByLabelText('Session title')).toHaveValue(' Raw title ') + }) + + it('leaves the rename field empty when the session has no title', () => { + renderSheet({ title: undefined }) + + fireEvent.click(screen.getByRole('button', { name: 'Rename' })) + + expect(screen.getByLabelText('Session title')).toHaveValue('') + expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled() + }) + + it('disables Save while the trimmed draft is empty', () => { + renderSheet() + + fireEvent.click(screen.getByRole('button', { name: 'Rename' })) + fireEvent.change(screen.getByLabelText('Session title'), { target: { value: ' ' } }) + + expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled() + }) + + it('saves the trimmed title and leaves edit mode on success', () => { + const mutation = mockRename() + renderSheet() + + 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()) + + expect(screen.queryByLabelText('Session title')).not.toBeInTheDocument() + expect(screen.getByText('Fix the header')).toBeInTheDocument() + }) + + it('saves on Enter', () => { + const mutation = mockRename() + renderSheet() + + fireEvent.click(screen.getByRole('button', { name: 'Rename' })) + fireEvent.change(screen.getByLabelText('Session title'), { target: { value: 'Entered' } }) + fireEvent.keyDown(screen.getByLabelText('Session title'), { key: 'Enter' }) + + expect(mutation.mutate).toHaveBeenCalledWith( + { sessionID: 'ses_1', title: 'Entered' }, + expect.objectContaining({ onSuccess: expect.any(Function) }), + ) + }) + + it('cancels editing and resets the rename error', () => { + const mutation = mockRename({ error: new Error('nope') }) + renderSheet() + + fireEvent.click(screen.getByRole('button', { name: 'Rename' })) + expect(screen.getByText('Rename failed')).toBeInTheDocument() + + fireEvent.click(screen.getByRole('button', { name: 'Cancel' })) + + expect(screen.queryByLabelText('Session title')).not.toBeInTheDocument() + expect(mutation.reset).toHaveBeenCalled() + }) + + it('shows the rename failure inline', () => { + mockRename({ error: new Error('nope') }) + renderSheet() + + 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' })) + + expect(screen.getByLabelText('Session title')).toBeDisabled() + expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled() + }) + + it('does not dismiss while a rename is pending', async () => { + const user = userEvent.setup() + const onOpenChange = vi.fn() + mockRename({ isPending: true }) + renderSheet({ onOpenChange }) + + await user.click(screen.getByRole('button', { name: 'Rename' })) + await user.keyboard('{Escape}') + + expect(onOpenChange).not.toHaveBeenCalled() + expect(screen.getByRole('dialog')).toBeInTheDocument() + }) + + it('resets to view mode and clears the error when reopened', () => { + const mutation = mockRename({ error: new Error('nope') }) + + function Host() { + const [open, setOpen] = useState(true) + return ( + <> + + + + ) + } + + render() + + fireEvent.click(screen.getByRole('button', { name: 'Rename' })) + expect(screen.getByLabelText('Session title')).toBeInTheDocument() + + fireEvent.click(screen.getByText('toggle')) + fireEvent.click(screen.getByText('toggle')) + + expect(screen.queryByLabelText('Session title')).not.toBeInTheDocument() + expect(screen.getByRole('button', { name: 'Rename' })).toBeInTheDocument() + expect(mutation.reset).toHaveBeenCalled() + }) + + it('renders as a bottom sheet on mobile', () => { + mocks.useMobile.mockReturnValue(true) + renderSheet({ branch: 'feat/header' }) + + expect(screen.getByRole('dialog')).toHaveAccessibleName('Session details') + expect(screen.getByText('feat/header')).toBeInTheDocument() + }) +}) diff --git a/frontend/src/components/session/SessionDetailsSheet.tsx b/frontend/src/components/session/SessionDetailsSheet.tsx new file mode 100644 index 00000000..801ae06e --- /dev/null +++ b/frontend/src/components/session/SessionDetailsSheet.tsx @@ -0,0 +1,207 @@ +import { useState, type ReactNode } from 'react' +import { Server } from 'lucide-react' +import { BottomSheet, BottomSheetContent, BottomSheetHeader } from '@/components/ui/bottom-sheet' +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 +} + +interface InfoRowProps { + label: string + value: string + mono?: boolean + leading?: ReactNode +} + +function InfoRow({ label, value, mono, leading }: InfoRowProps) { + return ( +
+ {label} +
+ {leading} + + {value} + +
+
+ ) +} + +/** + * Session details shown from the session header title. It lists the title, + * server, project, branch and directory untruncated, and renames the session + * inline so the sheet stays open while the new title lands through the session + * query. It renders as a bottom sheet on mobile and a dialog on desktop. + * + * Dismissal is blocked while a rename is pending, and the mutation error resets + * when the sheet reopens so a failed rename cannot leak into the next open. + */ +export function SessionDetailsSheet({ + open, + onOpenChange, + sessionId, + title, + serverName, + remote, + project, + branch, + directory, +}: SessionDetailsSheetProps) { + const isMobile = useMobile() + const renameSession = useUpdateSession(directory) + const [editing, setEditing] = useState(false) + const [draft, setDraft] = useState('') + const [lastOpen, setLastOpen] = useState(open) + + if (open !== lastOpen) { + setLastOpen(open) + if (open) { + setEditing(false) + if (renameSession.error) renameSession.reset() + } + } + + const displayTitle = title?.trim() ? title : 'Untitled Session' + const trimmedDraft = draft.trim() + const canSave = trimmedDraft.length > 0 && !renameSession.isPending + + const startEditing = () => { + setDraft(title ?? '') + setEditing(true) + } + + const cancelEditing = () => { + setEditing(false) + if (renameSession.error) renameSession.reset() + } + + const save = () => { + if (!canSave) return + renameSession.mutate( + { sessionID: sessionId, title: trimmedDraft }, + { onSuccess: () => setEditing(false) }, + ) + } + + const handleClose = () => { + if (renameSession.isPending) return + onOpenChange(false) + } + + const handleOpenChange = (nextOpen: boolean) => { + if (!nextOpen) { + handleClose() + return + } + onOpenChange(true) + } + + const body = ( +
+
+ Title + {editing ? ( + <> + setDraft(event.target.value)} + onKeyDown={(event) => { + if (event.key !== 'Enter') return + event.preventDefault() + save() + }} + disabled={renameSession.isPending} + 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 && ( + Rename failed + )} +
+ + +
+ + ) : ( + <> + {displayTitle} + + + )} +
+ : undefined} + /> + + {branch ? : null} + {directory ? : null} +
+ ) + + if (isMobile) { + return ( + + + {body} + + ) + } + + return ( + + + + Session details + + {body} + + + ) +} diff --git a/frontend/src/components/source-control/RemoteSourceControlContent.tsx b/frontend/src/components/source-control/RemoteSourceControlContent.tsx index 645fa10c..a577c243 100644 --- a/frontend/src/components/source-control/RemoteSourceControlContent.tsx +++ b/frontend/src/components/source-control/RemoteSourceControlContent.tsx @@ -3,7 +3,6 @@ import { useQuery, useQueryClient } from '@tanstack/react-query' import { ArrowLeft, FileText, GitBranch, Loader2, RefreshCw } from 'lucide-react' import { getVcsDiff, - getVcsInfo, listVcsStatus, type VcsFileDiff, type VcsFileStatus, @@ -16,6 +15,7 @@ import { cn } from '@/lib/utils' import { serverScopedKey } from '@/lib/serverScope' import { useRefreshOnOpen } from '@/hooks/useRefreshOnOpen' import { useMobile } from '@/hooks/useMobile' +import { useVcsInfo } from '@/hooks/useVcsInfo' import { GIT_UI_COLORS } from '@/lib/git-status-styles' import type { GitFileStatus } from '@/types/git' @@ -60,11 +60,7 @@ export function RemoteSourceControlContent({ [directory, serverId], ) - const infoQuery = useQuery({ - queryKey: [...vcsKey, 'info'], - queryFn: () => getVcsInfo(directory, serverId), - retry: false, - }) + const infoQuery = useVcsInfo(directory, serverId) const statusQuery = useQuery({ queryKey: [...vcsKey, 'status'], diff --git a/frontend/src/components/ui/bottom-sheet.test.tsx b/frontend/src/components/ui/bottom-sheet.test.tsx index 77e94f03..9c6aa32b 100644 --- a/frontend/src/components/ui/bottom-sheet.test.tsx +++ b/frontend/src/components/ui/bottom-sheet.test.tsx @@ -142,6 +142,19 @@ describe('BottomSheet', () => { }) }) + it('disables the swipe gesture when the sheet is not dismissible', () => { + render( + {}} ariaLabel="Test sheet"> +
Test content
+
, + ) + + expect(useSwipeDismiss).toHaveBeenCalledWith(expect.any(Function), { + enabled: false, + threshold: 60, + }) + }) + it('binds gesture to the panel element with aria-modal', () => { const mockBind = vi.fn() vi.mocked(useSwipeDismiss).mockReturnValue({ diff --git a/frontend/src/components/ui/bottom-sheet.tsx b/frontend/src/components/ui/bottom-sheet.tsx index 14b7fa6f..cfb831f3 100644 --- a/frontend/src/components/ui/bottom-sheet.tsx +++ b/frontend/src/components/ui/bottom-sheet.tsx @@ -12,6 +12,7 @@ export interface BottomSheetProps { className?: string children: React.ReactNode ariaLabel?: string + dismissible?: boolean } export function BottomSheet({ @@ -21,6 +22,7 @@ export function BottomSheet({ className, children, ariaLabel, + dismissible = true, }: BottomSheetProps) { const [shouldRender, setShouldRender] = useState(false) const panelRef = useRef(null) @@ -28,7 +30,7 @@ export function BottomSheet({ useRestoreFocusOnClose(isOpen, panelRef) const { bind, swipeStyles } = useSwipeDismiss(onClose, { - enabled: isOpen, + enabled: isOpen && dismissible, threshold: 60, }) diff --git a/frontend/src/components/ui/header.tsx b/frontend/src/components/ui/header.tsx index eb93795f..a6666570 100644 --- a/frontend/src/components/ui/header.tsx +++ b/frontend/src/components/ui/header.tsx @@ -4,12 +4,8 @@ import { BackButton } from "@/components/ui/back-button"; import { PageHeader } from "@/components/ui/page-header"; import { useSettingsDialog } from "@/hooks/useSettingsDialog"; import { useTheme } from "@/hooks/useTheme"; -import { EditSessionTitleDialog } from "@/components/session/EditSessionTitleDialog"; import { cn } from "@/lib/utils"; import type { ReactNode } from "react"; -import { useState, useEffect } from "react"; -import { useMobile } from "@/hooks/useMobile"; -import { X } from "lucide-react"; interface HeaderProps { children: ReactNode; @@ -56,107 +52,6 @@ function HeaderTitle({ children, logo, className }: HeaderTitleProps) { ); } -interface HeaderEditableTitleProps { - value: string; - onChange: (value: string) => void; - subtitle?: React.ReactNode; - className?: string; -} - -function HeaderEditableTitle({ value, onChange, subtitle, className }: HeaderEditableTitleProps) { - const [isEditing, setIsEditing] = useState(false); - const [editTitle, setEditTitle] = useState(value); - const isMobile = useMobile(); - - useEffect(() => { - if (!isEditing) { - setEditTitle(value); - } - }, [value, isEditing]); - - const handleTitleClick = () => { - setIsEditing(true); - setEditTitle(value); - }; - - const handleTitleSubmit = (e: React.FormEvent) => { - e.preventDefault(); - if (editTitle.trim() && editTitle !== value) { - onChange(editTitle.trim()); - } - setIsEditing(false); - }; - - const handleKeyDown = (e: React.KeyboardEvent) => { - if (e.key === 'Escape') { - setEditTitle(value); - setIsEditing(false); - } else if (e.key === 'Enter') { - handleTitleSubmit(e); - } - }; - - const handleSave = (newTitle: string) => { - if (newTitle.trim() && newTitle !== value) { - onChange(newTitle.trim()); - } - setIsEditing(false); - }; - - return ( -
- {isMobile && ( - setIsEditing(false)} - onSave={handleSave} - /> - )} - {isEditing && !isMobile ? ( -
- setEditTitle(e.target.value)} - onBlur={(e) => { - if (!e.relatedTarget?.closest('button')) { - handleTitleSubmit(e); - } - }} - onKeyDown={handleKeyDown} - className="text-[16px] sm:text-base font-semibold bg-background border border-border rounded-l px-2 py-1 outline-none w-full truncate focus:border-primary sm:max-w-[250px] h-7" - autoFocus - /> - -
- ) : ( -
-

- {value} -

- {subtitle && ( -

- {typeof subtitle === 'string' ? subtitle : subtitle} -

- )} -
- )} -
- ); -} - function HeaderActions({ children, className }: { children: ReactNode; className?: string }) { return
{children}
; } @@ -180,13 +75,11 @@ function HeaderSettingsButton() { export const Header = Object.assign(HeaderBase, { BackButton: HeaderBackButton, Title: HeaderTitle, - EditableTitle: HeaderEditableTitle, Actions: HeaderActions, Settings: HeaderSettingsButton, }) as typeof HeaderBase & { BackButton: typeof HeaderBackButton; Title: typeof HeaderTitle; - EditableTitle: typeof HeaderEditableTitle; Actions: typeof HeaderActions; Settings: typeof HeaderSettingsButton; }; diff --git a/frontend/src/hooks/useSessionTranscript.test.tsx b/frontend/src/hooks/useSessionTranscript.test.tsx index b88435a4..e8d7e63d 100644 --- a/frontend/src/hooks/useSessionTranscript.test.tsx +++ b/frontend/src/hooks/useSessionTranscript.test.tsx @@ -8,7 +8,7 @@ import type { V2Event, } from '@opencode-manager/shared/opencode' import { useSessionTranscript } from './useSessionTranscript' -import { ContextUsageIndicator } from '@/components/session/ContextUsageIndicator' +import { useContextUsage } from './useContextUsage' import { OpenCodeServerProvider } from '@/contexts/OpenCodeServerContext' import { applySessionEvent, emptySessionTranscript } from '@/lib/session-projection' import type { TranscriptCache } from '@/lib/session-projection' @@ -1129,13 +1129,8 @@ describe('useSessionTranscript', () => { function PageConsumers() { const { messages } = useSessionTranscript(SESSION_ID, DIRECTORY) pageMessages.current = messages - return ( - - ) + useContextUsage(SESSION_ID, DIRECTORY) + return null } render(, { wrapper: createWrapper(queryClient) }) diff --git a/frontend/src/hooks/useVcsInfo.test.tsx b/frontend/src/hooks/useVcsInfo.test.tsx new file mode 100644 index 00000000..538b111a --- /dev/null +++ b/frontend/src/hooks/useVcsInfo.test.tsx @@ -0,0 +1,62 @@ +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 { useVcsInfo } from './useVcsInfo' + +const mocks = vi.hoisted(() => ({ getVcsInfo: vi.fn() })) + +vi.mock('@/api/opencode', () => ({ getVcsInfo: mocks.getVcsInfo })) + +function createWrapper() { + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }) + return ({ children }: { children: ReactNode }) => ( + {children} + ) +} + +describe('useVcsInfo', () => { + beforeEach(() => { + mocks.getVcsInfo.mockReset() + mocks.getVcsInfo.mockResolvedValue({ + branch: { current: 'feat/header', default: 'main' }, + }) + }) + + it('reads the branch of the directory from the given server', async () => { + const { result } = renderHook(() => useVcsInfo('/abs/repo', 'srv_kitchen'), { + wrapper: createWrapper(), + }) + + await waitFor(() => expect(result.current.data?.branch.current).toBe('feat/header')) + expect(mocks.getVcsInfo).toHaveBeenCalledWith('/abs/repo', 'srv_kitchen') + }) + + it('stays disabled without a directory', () => { + const { result } = renderHook(() => useVcsInfo(undefined, 'srv_kitchen'), { + wrapper: createWrapper(), + }) + + expect(result.current.fetchStatus).toBe('idle') + expect(mocks.getVcsInfo).not.toHaveBeenCalled() + }) + + it('stays disabled when the caller disables it', () => { + renderHook(() => useVcsInfo('/abs/repo', 'srv_kitchen', { enabled: false }), { + wrapper: createWrapper(), + }) + + expect(mocks.getVcsInfo).not.toHaveBeenCalled() + }) + + it('shares one cache entry between callers of the same directory and server', async () => { + const wrapper = createWrapper() + const first = renderHook(() => useVcsInfo('/abs/repo', 'srv_kitchen'), { wrapper }) + const second = renderHook(() => useVcsInfo('/abs/repo', 'srv_kitchen'), { wrapper }) + + await waitFor(() => expect(first.result.current.data?.branch.current).toBe('feat/header')) + await waitFor(() => expect(second.result.current.data?.branch.current).toBe('feat/header')) + + expect(mocks.getVcsInfo).toHaveBeenCalledTimes(1) + }) +}) diff --git a/frontend/src/hooks/useVcsInfo.ts b/frontend/src/hooks/useVcsInfo.ts new file mode 100644 index 00000000..2a2e2009 --- /dev/null +++ b/frontend/src/hooks/useVcsInfo.ts @@ -0,0 +1,33 @@ +import { useQuery } from '@tanstack/react-query' +import { getVcsInfo } from '@/api/opencode' +import { serverScopedKey } from '@/lib/serverScope' + +export interface UseVcsInfoOptions { + enabled?: boolean +} + +/** + * Reads the version-control info of a directory through the OpenCode server in + * scope. The query is keyed by directory and server id, so the session header, + * the project header and the source control panel share one cached read, and a + * linked server reports its own checkout rather than the Manager's. + * + * @param directory Absolute checkout directory; the query stays disabled without one. + * @param serverId Linked server to read from, or the local Manager when omitted. + * @param options.enabled Whether to read the info; defaults to `true`. + */ +export function useVcsInfo( + directory: string | undefined, + serverId: string | undefined, + options: UseVcsInfoOptions = {}, +) { + const { enabled = true } = options + + return useQuery({ + queryKey: [...serverScopedKey(['opencode', 'vcs', directory ?? ''], serverId), 'info'], + queryFn: () => getVcsInfo(directory ?? '', serverId), + enabled: enabled && Boolean(directory), + retry: false, + staleTime: 60_000, + }) +} diff --git a/frontend/src/pages/RemoteProject.tsx b/frontend/src/pages/RemoteProject.tsx index 9b4e2b38..73074e5d 100644 --- a/frontend/src/pages/RemoteProject.tsx +++ b/frontend/src/pages/RemoteProject.tsx @@ -1,8 +1,9 @@ import { useNavigate, useParams, useSearchParams } from 'react-router-dom' import { useQuery } from '@tanstack/react-query' import { FolderGit2, GitBranch, Loader2, Plus, Server } from 'lucide-react' -import { getVcsInfo, listProjects } from '@/api/opencode' +import { listProjects } from '@/api/opencode' import { useCreateSession } from '@/hooks/useOpenCode' +import { useVcsInfo } from '@/hooks/useVcsInfo' import { useOpenCodeServers } from '@/hooks/useOpenCodeServers' import { useSettingsDialog } from '@/hooks/useSettingsDialog' import { useSSE } from '@/hooks/useSSE' @@ -50,12 +51,7 @@ function RemoteProjectContent({ serverId, directory }: { serverId: string; direc retry: false, }) - const vcsQuery = useQuery({ - queryKey: [...serverScopedKey(['opencode', 'vcs', directory ?? ''], serverId), 'info'], - queryFn: () => getVcsInfo(directory ?? '', serverId), - enabled: isReady, - retry: false, - }) + const vcsQuery = useVcsInfo(directory, serverId, { enabled: isReady }) useSSE(directory) diff --git a/frontend/src/pages/SessionDetail.tsx b/frontend/src/pages/SessionDetail.tsx index 6b499e49..e34292f1 100644 --- a/frontend/src/pages/SessionDetail.tsx +++ b/frontend/src/pages/SessionDetail.tsx @@ -5,7 +5,7 @@ import { repoQueryOptions } from "@/lib/repoQuery"; import { MessageThread } from "@/components/message/MessageThread"; import { PromptInput, type PromptInputHandle } from "@/components/message/PromptInput"; import { FloatingTTSButton } from '@/components/message/FloatingTTSButton' -import { X, CornerUpLeft, GitBranch, ArrowDown } from "lucide-react"; +import { X, CornerUpLeft, GitBranch, ArrowDown, Server } from "lucide-react"; import { SquareFill } from "@/components/ui/square-fill"; import { Header } from "@/components/ui/header"; import { Badge } from "@/components/ui/badge"; @@ -14,15 +14,14 @@ import { getRepoPath, getServerProjectPath, getServerSessionPath, getSessionList import { FetchError } from '@/api/fetchWrapper' import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet"; -import { Button } from "@/components/ui/button"; import { NotFoundState } from "@/components/ui/not-found-state"; -import { ContextUsageIndicator } from "@/components/session/ContextUsageIndicator"; import { useSession, useInterruptSession, useUpdateSession, useCreateSession } from "@/hooks/useOpenCode"; import { useSessionTranscript } from "@/hooks/useSessionTranscript"; import { useAutoOpenWalkthrough } from "@/hooks/useAutoOpenWalkthrough"; import { useRepoActivity } from "@/hooks/useRepoActivity"; import { useRepoSiblings } from "@/hooks/useRepoSiblings"; import { useSSE } from "@/hooks/useSSE"; +import { useVcsInfo } from "@/hooks/useVcsInfo"; import { useUIState } from "@/stores/uiStateStore"; import { useSettings } from "@/hooks/useSettings"; import { useModelSelection } from "@/hooks/useModelSelection"; @@ -71,6 +70,8 @@ import { SourceControlPanel, RemoteSourceControlPanel } from "@/components/sourc import { TerminalPanel } from "@/components/terminal/TerminalPanel"; import { PreviewPanel } from "@/components/preview/PreviewPanel"; import { SessionSendErrorBanner } from "@/components/session/SessionSendErrorBanner"; +import { ReconnectingBanner } from "@/components/session/ReconnectingBanner"; +import { SessionDetailsSheet } from "@/components/session/SessionDetailsSheet"; import { BackgroundWorkBar } from "@/components/session/BackgroundWorkBar"; import { SessionGoalBar } from "@/components/session/SessionGoalBar"; import { useDialogParam } from "@/hooks/useDialogParam"; @@ -135,6 +136,7 @@ export function SessionDetail() { const [messageContainer, setMessageContainer] = useState(null); const promptInputRef = useRef(null); const [sessionsDialogOpen, setSessionsDialogOpen] = useState(false); + const [sessionDetailsOpen, setSessionDetailsOpen] = useState(false); const [fileBrowserOpen, setFileBrowserOpen] = useDialogParam('files'); const [mcpDialogOpen, setMcpDialogOpen] = useDialogParam('mcp'); const [skillsDialogOpen, setSkillsDialogOpen] = useDialogParam('skills'); @@ -230,11 +232,19 @@ export function SessionDetail() { 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 sessionBranch = useMemo( () => (repo && !isAssistantSession ? resolveSessionBranch(repo, sessionDirectory, repoSiblings) : null), [repo, isAssistantSession, sessionDirectory, repoSiblings], ); + const { data: remoteVcsInfo } = useVcsInfo(sessionDirectory, serverId, { enabled: isRemoteServer }); + const headerBranch = isRemoteServer ? remoteVcsInfo?.branch.current ?? null : sessionBranch; + const { data: session, isLoading: sessionLoading, error: sessionQueryError } = useSession( sessionId, sessionDirectory, @@ -785,10 +795,8 @@ export function SessionDetail() { } const linkedServer = linkedServers.find((candidate) => candidate.id === serverId); - const workspaceDisplayName = isRemoteServer - ? [linkedServer?.name ?? 'Linked server', sessionDirectory ? getDirectoryName(sessionDirectory) : undefined] - .filter(Boolean) - .join(' · ') + const projectDisplayName = isRemoteServer + ? remoteProjectName ?? (sessionDirectory ? getDirectoryName(sessionDirectory) : 'Project') : isAssistantSession || !repo ? 'Assistant' : getRepoDisplayName(repo); @@ -807,51 +815,52 @@ export function SessionDetail() { >
- {session?.parentID ? ( - <> - + {session?.parentID ? ( + -
- -
- - ) : ( - - )} - - {isRemoteServer ? ( - <> - {linkedServer?.name ?? 'Linked server'} - {sessionDirectory && ` · ${getDirectoryName(sessionDirectory)}`} - - ) : ( - workspaceDisplayName + + Parent session + + ) : ( +

+ {isRemoteServer && ( + )} - {sessionBranch && · {sessionBranch}} - - } - /> - {sessionBranch && ( + {projectDisplayName} + {headerBranch && ( + · {headerBranch} + )} +

+ )} +
+ {headerBranch && ( - {sessionBranch} + {headerBranch} )} @@ -862,17 +871,10 @@ export function SessionDetail() { )} -
- +
@@ -1071,6 +1073,18 @@ export function SessionDetail() { }} /> + + {sideQuestion && sessionId && ( @@ -1160,7 +1174,7 @@ export function SessionDetail() { isOpen={!docked && sourceControlOpen} onClose={() => setSourceControlOpen(false)} currentBranch={repo?.currentBranch || repo?.branch || "main"} - repoName={workspaceDisplayName} + repoName={projectDisplayName} /> )} diff --git a/frontend/src/pages/__tests__/SessionDetail.commands.test.tsx b/frontend/src/pages/__tests__/SessionDetail.commands.test.tsx index deeb1ac4..5d0b29fa 100644 --- a/frontend/src/pages/__tests__/SessionDetail.commands.test.tsx +++ b/frontend/src/pages/__tests__/SessionDetail.commands.test.tsx @@ -124,6 +124,7 @@ vi.mock('@/hooks/useSettingsDialog', () => ({ vi.mock('@/hooks/useMobile', () => ({ useMobile: mocks.useMobile, useSwipeBack: vi.fn(() => ({ ref: vi.fn() })), + useSwipeDismiss: vi.fn(() => ({ bind: vi.fn(), swipeProgress: 0, swipeStyles: {} })), })) vi.mock('@/hooks/useVisualViewport', () => ({ diff --git a/frontend/src/pages/__tests__/SessionDetail.not-found.test.tsx b/frontend/src/pages/__tests__/SessionDetail.not-found.test.tsx index e8eea957..b1b55e60 100644 --- a/frontend/src/pages/__tests__/SessionDetail.not-found.test.tsx +++ b/frontend/src/pages/__tests__/SessionDetail.not-found.test.tsx @@ -53,7 +53,7 @@ vi.mock('@/hooks/useModelSelection', () => ({ vi.mock('@/hooks/useTTS', () => ({ useTTS: vi.fn(() => ({ isEnabled: false })) })) vi.mock('@/hooks/useSettings', () => ({ useSettings: mocks.useSettings })) vi.mock('@/hooks/useSettingsDialog', () => ({ useSettingsDialog: mocks.useSettingsDialog })) -vi.mock('@/hooks/useMobile', () => ({ useMobile: mocks.useMobile })) +vi.mock('@/hooks/useMobile', () => ({ useMobile: mocks.useMobile, useSwipeBack: vi.fn(() => ({ bind: vi.fn(), swipeProgress: 0, swipeStyles: {} })) })) vi.mock('@/hooks/useVisualViewport', () => ({ useVisualViewport: mocks.useVisualViewport })) vi.mock('@/contexts/KeyboardShortcutsContext', () => ({ useShortcutActions: mocks.useShortcutActions })) vi.mock('@/hooks/useAutoScroll', () => ({ useAutoScroll: mocks.useAutoScroll })) @@ -87,7 +87,6 @@ vi.mock('@/components/message/MessageThread', () => ({ MessageThread: mocks.Mess vi.mock('@/components/message/PromptInput', () => ({ PromptInput: mocks.PromptInput })) vi.mock('@/components/message/FloatingTTSButton', () => ({ FloatingTTSButton: () => null })) vi.mock('@/components/message/MessageSkeleton', () => ({ MessageSkeleton: () => null })) -vi.mock('@/components/session/ContextUsageIndicator', () => ({ ContextUsageIndicator: () => null })) vi.mock('@/components/session/SessionSendErrorBanner', () => ({ SessionSendErrorBanner: () => null })) vi.mock('@/components/session/BackgroundWorkBar', () => ({ BackgroundWorkBar: () => null })) vi.mock('@/components/session/SessionGoalBar', () => ({ SessionGoalBar: () => null })) diff --git a/frontend/src/pages/__tests__/SessionDetail.remote.test.tsx b/frontend/src/pages/__tests__/SessionDetail.remote.test.tsx index 4c2ef371..26b81e47 100644 --- a/frontend/src/pages/__tests__/SessionDetail.remote.test.tsx +++ b/frontend/src/pages/__tests__/SessionDetail.remote.test.tsx @@ -8,7 +8,6 @@ import { SwipeNavigationProvider, useSwipeNavigation } from '@/contexts/SwipeNav import { getServerProjectPath } from '@/lib/navigation' import { LocationCatcher } from '@/test/test-utils' import { MessageThread } from '@/components/message/MessageThread' -import { ContextUsageIndicator } from '@/components/session/ContextUsageIndicator' import { SessionSendErrorBanner } from '@/components/session/SessionSendErrorBanner' import { PendingActionsGroup } from '@/components/notifications/PendingActionsGroup' import { SessionDetail } from '../SessionDetail' @@ -133,7 +132,6 @@ vi.mock('@/components/message/MessageThread', () => ({ vi.mock('@/components/message/PromptInput', () => ({ PromptInput: vi.fn(() => null) })) vi.mock('@/components/message/FloatingTTSButton', () => ({ FloatingTTSButton: vi.fn(() => null) })) vi.mock('@/components/message/MessageSkeleton', () => ({ MessageSkeleton: vi.fn(() => null) })) -vi.mock('@/components/session/ContextUsageIndicator', () => ({ ContextUsageIndicator: vi.fn(() => null) })) vi.mock('@/components/session/SessionSendErrorBanner', () => ({ SessionSendErrorBanner: vi.fn(() => null) })) vi.mock('@/components/session/BackgroundWorkBar', () => ({ BackgroundWorkBar: vi.fn(() => null) })) vi.mock('@/components/session/SessionGoalBar', () => ({ SessionGoalBar: mocks.SessionGoalBar })) @@ -279,20 +277,21 @@ describe('SessionDetail remote server mode', () => { expect(mocks.useRepoSiblings).toHaveBeenCalledWith(undefined) }) - it('titles the header with the server name and session directory', async () => { + it('shows the remote project in the header without the server name', async () => { renderRemoteSession() await waitFor(() => { - expect(screen.getByText('Kitchen')).toHaveClass('text-info') + expect(screen.getByLabelText('Remote server')).toBeInTheDocument() }) - expect(screen.getByText('Kitchen').parentElement).toHaveTextContent('Kitchen · app') + expect(screen.getByText('app')).toBeInTheDocument() + expect(screen.queryByText(/Kitchen/)).not.toBeInTheDocument() }) it('returns to the project page from the header back button', async () => { const { capturedPathname, capturedSearch } = renderRemoteSession() await waitFor(() => { - expect(screen.getByText('Kitchen').parentElement).toHaveTextContent('Kitchen · app') + expect(screen.getByLabelText('Remote server')).toBeInTheDocument() }) fireEvent.click(screen.getByRole('button', { name: 'Go back' })) @@ -452,9 +451,6 @@ describe('SessionDetail remote server mode', () => { expect(screen.getByTestId('message-thread')).toBeInTheDocument() }) - expect(vi.mocked(ContextUsageIndicator).mock.calls.at(-1)?.[0]).toEqual( - expect.objectContaining({ isConnected: false, isReconnecting: true }), - ) expect(vi.mocked(SessionSendErrorBanner).mock.calls.at(-1)?.[0]).toEqual( expect.objectContaining({ isConnected: false, isReconnecting: true }), ) @@ -467,9 +463,6 @@ describe('SessionDetail remote server mode', () => { expect(screen.getByTestId('message-thread')).toBeInTheDocument() }) - expect(vi.mocked(ContextUsageIndicator).mock.calls.at(-1)?.[0]).toEqual( - expect.objectContaining({ isConnected: true, isReconnecting: false }), - ) expect(vi.mocked(SessionSendErrorBanner).mock.calls.at(-1)?.[0]).toEqual( expect.objectContaining({ isConnected: true, isReconnecting: false }), ) @@ -484,11 +477,34 @@ describe('SessionDetail remote server mode', () => { expect(screen.getByTestId('message-thread')).toBeInTheDocument() }) - expect(vi.mocked(ContextUsageIndicator).mock.calls.at(-1)?.[0]).toEqual( + expect(vi.mocked(SessionSendErrorBanner).mock.calls.at(-1)?.[0]).toEqual( expect.objectContaining({ isConnected: false, isReconnecting: true }), ) }) + it('navigates to the parent session from the header pill', async () => { + mocks.useSession.mockReturnValue({ + data: { ...remoteSession, parentID: 'ses_parent' }, + isLoading: false, + error: undefined, + }) + + const { capturedPathname } = renderRemoteSession() + + fireEvent.click(await screen.findByRole('button', { name: 'Parent session' })) + + expect(capturedPathname.current).toBe('/servers/srv_kitchen/sessions/ses_parent') + }) + + it('opens the session details sheet from the header title', async () => { + renderRemoteSession() + + fireEvent.click(await screen.findByRole('button', { name: 'Session details' })) + + expect(await screen.findByRole('dialog')).toHaveAccessibleName('Session details') + expect(screen.getByText('/home/me/app')).toBeInTheDocument() + }) + it('navigates child sessions within the linked server route', async () => { const { capturedPathname } = renderRemoteSession() diff --git a/frontend/src/pages/__tests__/SessionDetail.scroll-floating.test.tsx b/frontend/src/pages/__tests__/SessionDetail.scroll-floating.test.tsx index 70b10225..52a379df 100644 --- a/frontend/src/pages/__tests__/SessionDetail.scroll-floating.test.tsx +++ b/frontend/src/pages/__tests__/SessionDetail.scroll-floating.test.tsx @@ -79,6 +79,7 @@ vi.mock('@/hooks/useSettingsDialog', () => ({ vi.mock('@/hooks/useMobile', () => ({ useMobile: mocks.useMobile, useSwipeBack: vi.fn(() => ({ ref: vi.fn() })), + useSwipeDismiss: vi.fn(() => ({ bind: vi.fn(), swipeProgress: 0, swipeStyles: {} })), })) vi.mock('@/hooks/useVisualViewport', () => ({