feat(frontend): open session details from the header

Pressing the session title opens a details sheet with server, project, branch and directory and inline rename. Linked-server sessions show a server icon and their branch, child sessions show a parent session pill, a banner marks paused live updates while the stream reconnects, and the header context indicator is removed now that usage lives on the model pill.
This commit is contained in:
Chris Scott committed 2026-10-23 20:18:27 -04:00
1 parent 52162d5c4a
commit d99fcc268e
20 files changed
+732 -418

No files matched your search

@@ -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(<ContextUsageIndicator sessionID="ses_1" isConnected={true} />)
}
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()
})
})
@@ -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 (
<div className="flex items-center gap-2">
<span className="text-xs text-muted-foreground">Loading...</span>
</div>
)
}
if (isReconnecting) {
return <span className="text-xs text-warning font-medium">Reconnecting...</span>
}
if (!isConnected) {
return <span className="text-xs text-muted-foreground font-medium">Disconnected</span>
}
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 (
<div className="flex items-center gap-2">
<span className={`text-xs font-medium whitespace-nowrap ${getUsageTextColor(usage.usagePercentage ?? 0)}`}>
{isMobile ? compactText : fullText}
</span>
</div>
)
}
@@ -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<HTMLInputElement>(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 (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent
hideCloseButton
className={isMobile
? "w-screen max-w-none left-0 top-0 translate-x-0 translate-y-0 rounded-none border-0 border-b bg-background p-4 gap-0 pt-safe"
: "p-6 gap-0"
}
>
<form onSubmit={handleSubmit} className="min-w-0">
<p className="text-sm text-muted-foreground mb-2">Change session title</p>
<div className="relative">
<input
ref={inputRef}
type="text"
value={editTitle}
onChange={(e) => 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 && (
<button
type="button"
onClick={() => {
setEditTitle("");
inputRef.current?.focus();
}}
className="absolute right-2 top-1/2 -translate-y-1/2 p-1.5 rounded-full hover:bg-destructive/10 text-destructive transition-colors"
>
<X className="w-5 h-5" />
</button>
)}
</div>
<div className="flex items-center gap-2 mt-3">
<Button
type="button"
variant="outline"
onClick={handleCancel}
className="flex-1 h-10"
>
Cancel
</Button>
<Button
type="submit"
className="flex-1 h-10"
>
<Check className="w-4 h-4 mr-2" />
Save
</Button>
</div>
</form>
</DialogContent>
</Dialog>
);
}
@@ -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(<ReconnectingBanner connected={false} />)
expect(screen.queryByRole('status')).not.toBeInTheDocument()
})
it('stays hidden while the stream is connected', () => {
render(<ReconnectingBanner connected />)
expect(screen.queryByRole('status')).not.toBeInTheDocument()
})
it('reports a dropped stream once it connected', () => {
const { rerender } = render(<ReconnectingBanner connected />)
rerender(<ReconnectingBanner connected={false} />)
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(<ReconnectingBanner connected />)
rerender(<ReconnectingBanner connected={false} />)
rerender(<ReconnectingBanner connected />)
expect(screen.queryByRole('status')).not.toBeInTheDocument()
})
})
@@ -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 (
<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
</div>
)
}
@@ -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<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',
}
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 renderSheet(overrides: Partial<SessionDetailsSheetProps> = {}) {
return render(<SessionDetailsSheet {...baseProps} {...overrides} />)
}
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 (
<>
<button type="button" onClick={() => setOpen((current) => !current)}>
toggle
</button>
<SessionDetailsSheet {...baseProps} open={open} onOpenChange={setOpen} />
</>
)
}
render(<Host />)
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()
})
})
@@ -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 (
<div className="flex min-w-0 flex-col gap-1">
<span className="text-xs text-muted-foreground">{label}</span>
<div className="flex min-w-0 items-start gap-1.5">
{leading}
<span className={cn('min-w-0 select-text break-words', mono && 'font-mono text-xs')}>
{value}
</span>
</div>
</div>
)
}
/**
* 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 = (
<div className="flex min-w-0 flex-col gap-4">
<div className="flex min-w-0 flex-col gap-1">
<span className="text-xs text-muted-foreground">Title</span>
{editing ? (
<>
<input
type="text"
value={draft}
onChange={(event) => 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 && (
<span className="text-xs text-destructive">Rename failed</span>
)}
<div className="flex items-center gap-2 pt-1">
<Button
type="button"
variant="outline"
size="sm"
onClick={cancelEditing}
className="flex-1"
>
Cancel
</Button>
<Button
type="button"
size="sm"
onClick={save}
disabled={!canSave}
className="flex-1"
>
Save
</Button>
</div>
</>
) : (
<>
<span className="select-text break-words text-sm">{displayTitle}</span>
<Button
type="button"
variant="outline"
size="sm"
onClick={startEditing}
className="mt-1 self-start"
>
Rename
</Button>
</>
)}
</div>
<InfoRow
label="Server"
value={remote ? serverName || 'Remote server' : 'Local'}
leading={remote ? <Server className="mt-0.5 h-3.5 w-3.5 shrink-0 text-highlight" /> : undefined}
/>
<InfoRow label="Project" value={project} />
{branch ? <InfoRow label="Branch" value={branch} mono /> : null}
{directory ? <InfoRow label="Directory" value={directory} mono /> : null}
</div>
)
if (isMobile) {
return (
<BottomSheet
isOpen={open}
onClose={handleClose}
ariaLabel="Session details"
dismissible={!renameSession.isPending}
>
<BottomSheetHeader title="Session details" />
<BottomSheetContent>{body}</BottomSheetContent>
</BottomSheet>
)
}
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle>Session details</DialogTitle>
</DialogHeader>
{body}
</DialogContent>
</Dialog>
)
}
@@ -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'],
@@ -142,6 +142,19 @@ describe('BottomSheet', () => {
})
})
it('disables the swipe gesture when the sheet is not dismissible', () => {
render(
<BottomSheet isOpen dismissible={false} onClose={() => {}} ariaLabel="Test sheet">
<div>Test content</div>
</BottomSheet>,
)
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({
+3 -1
View File
@@ -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<HTMLDivElement>(null)
@@ -28,7 +30,7 @@ export function BottomSheet({
useRestoreFocusOnClose(isOpen, panelRef)
const { bind, swipeStyles } = useSwipeDismiss(onClose, {
enabled: isOpen,
enabled: isOpen && dismissible,
threshold: 60,
})
-107
View File
@@ -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 (
<div className={cn("min-w-0 flex-1", className)}>
{isMobile && (
<EditSessionTitleDialog
isOpen={isEditing}
currentTitle={value}
onClose={() => setIsEditing(false)}
onSave={handleSave}
/>
)}
{isEditing && !isMobile ? (
<form onSubmit={handleTitleSubmit} className="flex items-center gap-1 min-w-0">
<input
type="text"
value={editTitle}
onChange={(e) => 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
/>
<Button
type="button"
variant="ghost"
size="icon"
className="h-7 w-7 rounded-l-none border border-l-0 border-border hover:bg-accent flex-shrink-0 mt-0"
onClick={() => setEditTitle("")}
>
<X className="w-3.5 h-3.5" />
</Button>
</form>
) : (
<div className="min-w-0">
<h1
className="text-xs sm:text-base font-semibold bg-gradient-to-r from-foreground to-muted-foreground bg-clip-text text-transparent truncate cursor-pointer hover:opacity-80 transition-opacity"
onClick={handleTitleClick}
>
{value}
</h1>
{subtitle && (
<p className="text-[10px] sm:text-xs text-muted-foreground truncate">
{typeof subtitle === 'string' ? subtitle : subtitle}
</p>
)}
</div>
)}
</div>
);
}
function HeaderActions({ children, className }: { children: ReactNode; className?: string }) {
return <div className={cn("flex items-center gap-2", className)}>{children}</div>;
}
@@ -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;
};