Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(mobile): align chat navigation and defer keyboard focus (#128598)

Chris Volzer06dd6fea636b
diff --git a/products/mobile/app/chat.tsx b/products/mobile/app/chat.tsx
index d0cca97e3c6b..f6c51cce70ac 100644
--- a/products/mobile/app/chat.tsx
+++ b/products/mobile/app/chat.tsx
@@ -5,11 +5,13 @@ import { useDataMode } from '@/demo/demoMode'
import { ChatScreen } from '@/features/chat/ChatScreen'
import { chatSheetSource } from '@/features/chat/chatSheetEvents'
import { objectContextFromParams } from '@/features/chat/objectContext'
+import { useChatAutoFocus } from '@/features/chat/useChatAutoFocus'
import { currentDefaultPageHref } from '@/features/settings/defaultPageStore'
export default function ChatRoute(): ReactElement {
const router = useRouter()
const dataMode = useDataMode()
+ const autoFocus = useChatAutoFocus()
const { reportId, taskId, runId, entry, origin, objectType, objectId, objectLabel } = useLocalSearchParams<{
reportId?: string
taskId?: string
@@ -35,6 +37,7 @@ export default function ChatRoute(): ReactElement {
initialRunId={runId}
initialObject={objectContextFromParams({ objectType, objectId, objectLabel })}
source={chatSheetSource({ entry, origin, reportId, taskId, objectType })}
+ autoFocus={autoFocus}
onBack={close}
/>
)
diff --git a/products/mobile/docs/CHAT.md b/products/mobile/docs/CHAT.md
index c92c1fdbfce6..967eda5b86f9 100644
--- a/products/mobile/docs/CHAT.md
+++ b/products/mobile/docs/CHAT.md
@@ -4,8 +4,10 @@ The chat screen talks to PostHog AI on the task runtime, as the web app's side-p
Every chat is a task with interactive runs in a sandbox.
A new chat creates the task on its first message; the Chats list reopens one by its task id.
New and existing chats open as full-screen stack pages. Back returns to the previous screen or the
-configured default page for a direct link. The title-free header uses the shared blur and fading edge;
-New chat and the ellipsis share the Inbox's pill control. The composer clears the keyboard and safe area.
+configured default page for a direct link. The title-free header uses the shared blur and fading edge.
+The labeled Back chip matches Settings in style and position.
+Saved chats show New chat and the ellipsis in a matching bordered pill; unsaved chats show only Back.
+The composer clears the keyboard and safe area and receives focus after the page finishes its opening transition.
An active incident affecting PostHog AI in the selected cloud region appears below the header in new and existing chats.
The notice shows the published incident title and phase. Tap it to read the update. For other services, open **PostHog status** below the project name in the
@@ -13,7 +15,8 @@ main tabs’ ellipsis menu. An indicator on that menu signals a regional inciden
The ellipsis menu offers **Copy link to chat** and **Archive chat**. Copy uses the current project's
web URL. Archive returns to the previous page after success and keeps the chat open for retry on failure.
-The menu is disabled for an unsaved new chat. Model, Mode, and attachment options still open as overlays.
+Unsaved new chats hide both right-side controls until the first message creates a task.
+Model, Mode, and attachment options still open as overlays.
The protocol below follows the web's `taskTrackerSceneLogic.ts`, `runInteractionLogic.ts` and `runStreamLogic.ts` in `products/posthog_ai/frontend`.
## Files
@@ -409,7 +412,7 @@ New chat drops it.
## New chat
-The compose button stays available in the header.
+The compose button is available in a saved chat's header.
It drops the open task (or the one the first send created), clears the text and attached reports, and resets the options to Default and Auto.
The header has no chat title.
The empty state with suggested prompts shows while there is no task and no message.
diff --git a/products/mobile/docs/TESTING.md b/products/mobile/docs/TESTING.md
index 7efb416109b6..3599f3f1027a 100644
--- a/products/mobile/docs/TESTING.md
+++ b/products/mobile/docs/TESTING.md
@@ -222,10 +222,12 @@ sheet grabber or drag-down dismissal. Header Back and platform Back return to th
a direct link falls back to the configured default page. Scroll a long thread under the title-free
blurred header and focus the composer to check the keyboard and safe-area spacing.
-New chat and the ellipsis share the Inbox's pill control. Open the menu, copy the link, and confirm
+Saved chats show New chat and the ellipsis in a bordered pill beside the labeled Back chip. Open the menu, copy the link, and confirm
it targets the current project and chat. Archive a saved chat and confirm it disappears from Chats
only after success. Fail each action and retry; repeated taps must not start duplicate requests.
-An unsaved chat has no link or task to archive, so its ellipsis is disabled.
+An unsaved chat shows only Back, aligned with Settings, until the first message creates a task.
+Open New chat several times and check that the page finishes sliding in before the keyboard rises from the bottom.
+Repeat with the AI access check delayed so the composer mounts after the transition, and check the compact landscape layout.
## Chat drafts and rich replies
diff --git a/products/mobile/src/features/chat/ChatHeader.test.tsx b/products/mobile/src/features/chat/ChatHeader.test.tsx
index 15412c27dbc6..3a7ed7615cf0 100644
--- a/products/mobile/src/features/chat/ChatHeader.test.tsx
+++ b/products/mobile/src/features/chat/ChatHeader.test.tsx
@@ -29,7 +29,9 @@ describe('ChatHeader', () => {
<ChatHeader webUrl={url} onBack={onBack} onNewChat={onNewChat} />
)
const view = render(header(taskWebUrl(scope, null)), { wrapper: OverlayHost })
- expect(screen.getByTestId('chat-more')).toBeDisabled()
+ expect(screen.queryByTestId('chat-more')).toBeNull()
+ expect(screen.queryByTestId('chat-new')).toBeNull()
+ expect(screen.getByText('Back')).toBeTruthy()
expect(screen.queryByTestId('chat-copy-link')).toBeNull()
view.rerender(header(taskWebUrl(scope, 'first-task')))
@@ -49,6 +51,10 @@ describe('ChatHeader', () => {
expect(onNewChat).toHaveBeenCalledTimes(1)
fireEvent.press(screen.getByTestId('chat-back'))
expect(onBack).toHaveBeenCalledTimes(1)
+
+ view.rerender(header(undefined))
+ expect(screen.queryByTestId('chat-more')).toBeNull()
+ expect(screen.queryByTestId('chat-new')).toBeNull()
})
test.each(['rejected', 'false'] as const)(
@@ -95,7 +101,10 @@ describe('ChatHeader', () => {
}
)
- test('guards archive against double taps and allows retry after failure', async () => {
+ test.each([
+ { name: 'live', webUrl: 'https://us.posthog.com/project/7/ai?task=task-1' },
+ { name: 'demo', webUrl: undefined },
+ ])('guards archive against double taps and allows retry in a $name chat', async ({ webUrl }) => {
let rejectArchive!: (error: Error) => void
const onArchive = jest.fn(
() =>
@@ -103,15 +112,9 @@ describe('ChatHeader', () => {
rejectArchive = reject
})
)
- render(
- <ChatHeader
- webUrl="https://us.posthog.com/project/7/ai?task=task-1"
- onBack={jest.fn()}
- onNewChat={jest.fn()}
- onArchive={onArchive}
- />,
- { wrapper: OverlayHost }
- )
+ render(<ChatHeader webUrl={webUrl} onBack={jest.fn()} onNewChat={jest.fn()} onArchive={onArchive} />, {
+ wrapper: OverlayHost,
+ })
fireEvent.press(screen.getByTestId('chat-more'))
fireEvent.press(screen.getByTestId('chat-archive'))
fireEvent.press(screen.getByTestId('chat-archive'))
diff --git a/products/mobile/src/features/chat/ChatHeader.tsx b/products/mobile/src/features/chat/ChatHeader.tsx
index f6941b55869d..5eca702500be 100644
--- a/products/mobile/src/features/chat/ChatHeader.tsx
+++ b/products/mobile/src/features/chat/ChatHeader.tsx
@@ -3,24 +3,26 @@ import { View } from 'react-native'
import { useToasts, ViewsToast } from '@/features/views/ViewsToast'
import { useAsyncAction } from '@/lib/useAsyncAction'
+import { BackChip } from '@/ui/BackChip'
import { BlurEdge } from '@/ui/BlurEdge'
import { FadeEdge } from '@/ui/FadeEdge'
-import { ChevronLeftIcon } from '@/ui/icons/ChevronLeftIcon'
import { ComposeIcon } from '@/ui/icons/ComposeIcon'
import { MoreIcon } from '@/ui/icons/MoreIcon'
import { PillControl } from '@/ui/PillControl'
import { Pressable44 } from '@/ui/Pressable44'
-import { createStyles, useColors } from '@/ui/theme'
+import { screenLayout } from '@/ui/screenLayout'
+import { createStyles, useTheme } from '@/ui/theme'
import { iconSizes, layout, radii } from '@/ui/tokens'
import { useScreenInsets } from '@/ui/useScreenInsets'
import { ChatHeaderMenu } from './ChatHeaderMenu'
import { useCopyChatLink } from './useCopyChatLink'
-const HEADER_TOP = 16
-const ROW_HEIGHT = 54
+const HEADER_TOP = screenLayout.top - layout.designStatusBar
+const ROW_HEIGHT = screenLayout.rowHeight
const HEADER_FADE = 24
export const CHAT_HEADER_HEIGHT = HEADER_TOP + ROW_HEIGHT + HEADER_FADE
+export const CHAT_COMPACT_HEADER_HEIGHT = HEADER_TOP + ROW_HEIGHT + 8
interface ChatHeaderProps {
compact?: boolean
@@ -41,7 +43,7 @@ export function ChatHeader({
newChatDisabledReason,
onArchive,
}: ChatHeaderProps): ReactElement {
- const colors = useColors()
+ const { colors, shadows } = useTheme()
const styles = useStyles()
const insets = useScreenInsets()
const [menuOpen, setMenuOpen] = useState(false)
@@ -68,48 +70,45 @@ export function ChatHeader({
collapsable={false}
style={[
styles.header,
- { paddingTop: insets.top + (compact ? 8 : HEADER_TOP), paddingBottom: compact ? 8 : HEADER_FADE },
+ {
+ paddingTop: insets.top + HEADER_TOP,
+ paddingBottom: compact ? 8 : HEADER_FADE,
+ height: insets.top + (compact ? CHAT_COMPACT_HEADER_HEIGHT : CHAT_HEADER_HEIGHT),
+ },
]}
testID="chat-header"
>
<BlurEdge solid={0.7} blurTarget={blurTarget} />
<FadeEdge direction="down" solid={0.7} opacity={layout.chromeTint} />
- <Pressable44
- onPress={onBack}
- accessibilityLabel="Back"
- pressedBackground={colors.background}
- style={styles.round}
- testID="chat-back"
- >
- <ChevronLeftIcon size={iconSizes.control} />
- </Pressable44>
- <PillControl height={compact ? 44 : ROW_HEIGHT}>
- <Pressable44
- onPress={() => (newChatDisabledReason ? toasts.show(newChatDisabledReason) : onNewChat())}
- accessibilityLabel="New chat"
- accessibilityState={{ disabled: !!newChatDisabledReason }}
- accessibilityHint={newChatDisabledReason}
- pressedBackground={colors.background}
- style={[styles.button, compact && { height: 44 }]}
- testID="chat-new"
- >
- <ComposeIcon size={iconSizes.control} />
- </Pressable44>
- <Pressable44
- onPress={() => setMenuOpen(true)}
- accessibilityLabel="Chat options"
- accessibilityState={{ expanded: menuOpen, disabled: !webUrl && !onArchive }}
- disabled={!webUrl && !onArchive}
- pressedBackground={colors.background}
- style={[styles.button, compact && { height: 44 }]}
- testID="chat-more"
- >
- <MoreIcon size={iconSizes.control} color={webUrl || onArchive ? colors.ink : colors.disabled} />
- </Pressable44>
- </PillControl>
+ <BackChip onPress={onBack} testID="chat-back" />
+ {webUrl || onArchive ? (
+ <PillControl height={ROW_HEIGHT} style={[styles.actions, shadows.chip]}>
+ <Pressable44
+ onPress={() => (newChatDisabledReason ? toasts.show(newChatDisabledReason) : onNewChat())}
+ accessibilityLabel="New chat"
+ accessibilityState={{ disabled: !!newChatDisabledReason }}
+ accessibilityHint={newChatDisabledReason}
+ pressedBackground={colors.background}
+ style={styles.button}
+ testID="chat-new"
+ >
+ <ComposeIcon size={iconSizes.control} />
+ </Pressable44>
+ <Pressable44
+ onPress={() => setMenuOpen(true)}
+ accessibilityLabel="Chat options"
+ accessibilityState={{ expanded: menuOpen }}
+ pressedBackground={colors.background}
+ style={styles.button}
+ testID="chat-more"
+ >
+ <MoreIcon size={iconSizes.control} />
+ </Pressable44>
+ </PillControl>
+ ) : null}
<ChatHeaderMenu
visible={menuOpen}
- top={insets.top + (compact ? 60 : HEADER_TOP + ROW_HEIGHT + 8)}
+ top={insets.top + HEADER_TOP + ROW_HEIGHT + 8}
copying={copying}
archiving={archive.pending}
canCopy={!!webUrl}
@@ -123,7 +122,7 @@ export function ChatHeader({
)
}
-const useStyles = createStyles(({ colors }) => ({
+const useStyles = createStyles(() => ({
header: {
position: 'absolute',
top: 0,
@@ -132,25 +131,19 @@ const useStyles = createStyles(({ colors }) => ({
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
- paddingHorizontal: 16,
+ paddingHorizontal: layout.detailGutter,
paddingBottom: HEADER_FADE,
pointerEvents: 'box-none',
},
button: {
- width: 56,
- height: 46,
+ width: 48,
+ height: 44,
borderRadius: radii.pill,
alignItems: 'center',
justifyContent: 'center',
},
- round: {
- width: 44,
- height: 44,
- borderRadius: 22,
- borderWidth: 1,
- borderColor: colors.hairline,
- backgroundColor: colors.surface,
- alignItems: 'center',
- justifyContent: 'center',
+ actions: {
+ paddingVertical: 0,
+ paddingHorizontal: 0,
},
}))
diff --git a/products/mobile/src/features/chat/ChatScreen.test.tsx b/products/mobile/src/features/chat/ChatScreen.test.tsx
index 073f43d889c0..574d7de2aeec 100644
--- a/products/mobile/src/features/chat/ChatScreen.test.tsx
+++ b/products/mobile/src/features/chat/ChatScreen.test.tsx
@@ -1,4 +1,5 @@
import { act, fireEvent, render, screen } from '@testing-library/react-native'
+import { TextInput } from 'react-native'
import { ChatScreen } from './ChatScreen'
import { queueActions, queueReducer } from './messageQueue'
import { useSession } from './session/useSession'
@@ -102,6 +103,18 @@ test.each([null, 'task-1'])('shows the regional AI incident for chat %s', (taskI
})
describe('chat send preparation', () => {
+ test('focuses the composer only when the route is ready', () => {
+ mockReadyChat()
+ const focus = jest.mocked(TextInput.prototype.focus)
+ const view = render(<ChatScreen source={{ entry: 'compose', origin: null }} onBack={jest.fn()} />)
+ expect(focus).not.toHaveBeenCalled()
+
+ view.rerender(<ChatScreen source={{ entry: 'compose', origin: null }} autoFocus onBack={jest.fn()} />)
+ expect(focus).toHaveBeenCalledTimes(1)
+ view.rerender(<ChatScreen source={{ entry: 'compose', origin: null }} autoFocus onBack={jest.fn()} />)
+ expect(focus).toHaveBeenCalledTimes(1)
+ })
+
test('keeps an unsaved draft notice visible and disables retry while saving', () => {
const { session, draft } = mockReadyChat()
session.notice = 'Connection interrupted. Reconnect to continue.'
@@ -352,8 +365,7 @@ describe('chat send preparation', () => {
draft.draft = { text: '', reportIds: [] }
draft.queue = { rows: [{ id: 'queued-1', text: 'Keep this question', attachments: [] }], hold: 'cancelled' }
render(<ChatScreen source={{ entry: 'compose', origin: null }} onBack={jest.fn()} />)
- expect(screen.getByTestId('chat-new').props.accessibilityState.disabled).toBe(true)
- fireEvent.press(screen.getByTestId('chat-new'))
+ expect(screen.queryByTestId('chat-new')).toBeNull()
expect(session.reset).not.toHaveBeenCalled()
expect(session.send).not.toHaveBeenCalled()
expect(screen.getByText('Keep this question')).toBeTruthy()
diff --git a/products/mobile/src/features/chat/ChatScreen.tsx b/products/mobile/src/features/chat/ChatScreen.tsx
index 9b6403c4fc69..c5283914b400 100644
--- a/products/mobile/src/features/chat/ChatScreen.tsx
+++ b/products/mobile/src/features/chat/ChatScreen.tsx
@@ -33,7 +33,7 @@ import type { AttachmentSource, PendingAttachment } from './attachments/types'
import { releaseAttachments, useComposerAttachments } from './attachments/useComposerAttachments'
import { ChatAccessGate } from './ChatAccessGate'
import { ChatEmptyState } from './ChatEmptyState'
-import { CHAT_HEADER_HEIGHT, ChatHeader } from './ChatHeader'
+import { CHAT_COMPACT_HEADER_HEIGHT, CHAT_HEADER_HEIGHT, ChatHeader } from './ChatHeader'
import { type ChatOptionsPage, ChatOptionsSheet } from './ChatOptionsSheet'
import { Composer } from './Composer'
import { ContextChip } from './ContextChip'
@@ -77,6 +77,7 @@ interface ChatScreenProps {
initialTaskId?: string
initialRunId?: string
source: ChatSheetSource
+ autoFocus?: boolean
onBack: () => void
}
@@ -93,13 +94,14 @@ export function ChatScreen({
initialTaskId,
initialRunId,
source,
+ autoFocus = false,
onBack,
}: ChatScreenProps): ReactElement {
const styles = useStyles()
const insets = useScreenInsets()
const { height: sceneHeight, width: sceneWidth } = useSceneDimensions()
const compact = sceneHeight < 480 && sceneWidth >= 600
- const headerHeight = compact ? 60 : CHAT_HEADER_HEIGHT
+ const headerHeight = compact ? CHAT_COMPACT_HEADER_HEIGHT : CHAT_HEADER_HEIGHT
const now = useNow()
const inbox = useInboxItems()
const [target, setTarget] = useState<SessionOptions>(() => sessionTarget(initialTaskId, initialRunId))
@@ -198,6 +200,15 @@ export function ChatScreen({
// never takes them.
const [sendingFileIds, setSendingFileIds] = useState<readonly string[]>([])
const input = useRef<TextInput>(null)
+ const inputRef = useCallback(
+ (node: TextInput | null) => {
+ input.current = node
+ if (autoFocus) {
+ node?.focus()
+ }
+ },
+ [autoFocus]
+ )
const historyStatus = session.history.status
const optionsDisabled =
session.phase !== 'idle' || historyStatus !== 'idle' || session.isSending || session.decision !== undefined
@@ -686,7 +697,7 @@ export function ChatScreen({
) : null}
<Composer
compact={compact}
- ref={input}
+ ref={inputRef}
text={text}
onChangeText={changeText}
chips={chips}
diff --git a/products/mobile/src/features/chat/Composer.tsx b/products/mobile/src/features/chat/Composer.tsx
index a5038aadb624..fe0ca895ceee 100644
--- a/products/mobile/src/features/chat/Composer.tsx
+++ b/products/mobile/src/features/chat/Composer.tsx
@@ -133,7 +133,6 @@ export const Composer = forwardRef<TextInput, ComposerProps>(function Composer(
placeholderTextColor={colors.tertiary}
keyboardAppearance={scheme}
style={[styles.input, compact && styles.inputCompact]}
- autoFocus
multiline
disableFullscreenUI
returnKeyType="send"
diff --git a/products/mobile/src/features/chat/useChatAutoFocus.test.tsx b/products/mobile/src/features/chat/useChatAutoFocus.test.tsx
new file mode 100644
index 000000000000..91166c9dd242
--- /dev/null
+++ b/products/mobile/src/features/chat/useChatAutoFocus.test.tsx
@@ -0,0 +1,102 @@
+import { act, render } from '@testing-library/react-native'
+import { type ReactElement, useCallback } from 'react'
+import { Platform, TextInput } from 'react-native'
+
+import { useChatAutoFocus } from './useChatAutoFocus'
+
+const mockNavigation = { addListener: jest.fn(), isFocused: jest.fn(() => true) }
+jest.mock('expo-router', () => ({ useNavigation: () => mockNavigation }))
+jest.mock('expo-router/react-navigation', () => ({ useIsFocused: () => mockNavigation.isFocused() }))
+
+function Input({ autoFocus }: { autoFocus: boolean }): ReactElement {
+ const ref = useCallback(
+ (node: TextInput | null) => {
+ if (autoFocus) {
+ node?.focus()
+ }
+ },
+ [autoFocus]
+ )
+ return <TextInput ref={ref} />
+}
+
+function Page({ visible = true, chatId = 'new' }: { visible?: boolean; chatId?: string }): ReactElement | null {
+ const autoFocus = useChatAutoFocus()
+ return visible ? <Input key={chatId} autoFocus={autoFocus} /> : null
+}
+
+describe('chat input focus', () => {
+ const focus = jest.mocked(TextInput.prototype.focus)
+ const unsubscribe = jest.fn()
+ let transitionEnd: (event: { data: { closing: boolean } }) => void
+ let blur: () => void
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ mockNavigation.isFocused.mockReturnValue(true)
+ mockNavigation.addListener.mockImplementation((event, listener) => {
+ if (event === 'blur') {
+ blur = listener
+ } else {
+ transitionEnd = listener
+ }
+ return unsubscribe
+ })
+ })
+ afterEach(() => jest.restoreAllMocks())
+
+ test.each(['ios', 'android'] as const)('waits for the opening transition on %s', (platform) => {
+ jest.replaceProperty(Platform, 'OS', platform)
+ const view = render(<Page />)
+ expect(focus).not.toHaveBeenCalled()
+
+ act(() => transitionEnd({ data: { closing: true } }))
+ expect(focus).not.toHaveBeenCalled()
+ act(() => transitionEnd({ data: { closing: false } }))
+ expect(focus).toHaveBeenCalledTimes(1)
+
+ view.rerender(<Page />)
+ act(() => transitionEnd({ data: { closing: false } }))
+ expect(focus).toHaveBeenCalledTimes(1)
+ view.rerender(<Page chatId="another-chat" />)
+ expect(focus).toHaveBeenCalledTimes(2)
+
+ act(() => {
+ mockNavigation.isFocused.mockReturnValue(false)
+ blur()
+ })
+ mockNavigation.isFocused.mockReturnValue(true)
+ view.rerender(<Page chatId="another-chat" />)
+ expect(focus).toHaveBeenCalledTimes(2)
+ act(() => transitionEnd({ data: { closing: false } }))
+ expect(focus).toHaveBeenCalledTimes(3)
+ view.unmount()
+ expect(unsubscribe).toHaveBeenCalledTimes(2)
+ })
+
+ test.each([false, true])('handles the access gate showing the input after opening: %s', (afterOpening) => {
+ const view = render(<Page visible={false} />)
+ if (!afterOpening) {
+ view.rerender(<Page />)
+ }
+ expect(focus).not.toHaveBeenCalled()
+ act(() => transitionEnd({ data: { closing: false } }))
+ if (afterOpening) {
+ view.rerender(<Page />)
+ }
+ expect(focus).toHaveBeenCalledTimes(1)
+ })
+
+ test('does not open the keyboard when the page has lost focus', () => {
+ render(<Page />)
+ mockNavigation.isFocused.mockReturnValue(false)
+ act(() => transitionEnd({ data: { closing: false } }))
+ expect(focus).not.toHaveBeenCalled()
+ })
+
+ test('focuses on web where the native opening event is unavailable', () => {
+ jest.replaceProperty(Platform, 'OS', 'web')
+ render(<Page />)
+ expect(focus).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/products/mobile/src/features/chat/useChatAutoFocus.ts b/products/mobile/src/features/chat/useChatAutoFocus.ts
new file mode 100644
index 000000000000..d7539e8430ef
--- /dev/null
+++ b/products/mobile/src/features/chat/useChatAutoFocus.ts
@@ -0,0 +1,26 @@
+import { useNavigation } from 'expo-router'
+import type { NativeStackNavigationProp } from 'expo-router/native-stack'
+import { type ParamListBase, useIsFocused } from 'expo-router/react-navigation'
+import { useLayoutEffect, useState } from 'react'
+import { Platform } from 'react-native'
+
+export function useChatAutoFocus(): boolean {
+ const navigation = useNavigation<NativeStackNavigationProp<ParamListBase>>()
+ const focused = useIsFocused()
+ const [opened, setOpened] = useState(Platform.OS === 'web')
+
+ useLayoutEffect(() => {
+ const end = navigation.addListener('transitionEnd', ({ data }) => {
+ if (!data.closing) {
+ setOpened(true)
+ }
+ })
+ const blur = navigation.addListener('blur', () => setOpened(Platform.OS === 'web'))
+ return () => {
+ end()
+ blur()
+ }
+ }, [navigation])
+
+ return opened && focused
+}