Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
144 changes: 100 additions & 44 deletions apps/mobile/__tests__/hooks/use-chat-composer.test.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React from 'react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { API } from '@orbit/shared/api'
import { CHAT_SEND_TIMEOUT_MS } from '@orbit/shared/chat'
import { CHAT_STREAM_IDLE_TIMEOUT_MS } from '@orbit/shared/chat'
import type { ChatResponse } from '@orbit/shared/types/chat'
import type { Profile } from '@orbit/shared/types/profile'

Expand All @@ -24,6 +24,7 @@ const mocks = vi.hoisted(() => {
state,
queryClient,
apiClient: vi.fn(),
openChatStream: vi.fn(),
routerPush: vi.fn(),
useQueryClient: vi.fn(() => queryClient),
}
Expand All @@ -37,6 +38,10 @@ vi.mock('@/lib/api-client', () => ({
apiClient: mocks.apiClient,
}))

vi.mock('@/lib/chat-stream', () => ({
openChatStream: mocks.openChatStream,
}))

vi.mock('expo-router', () => ({
useRouter: () => ({ push: mocks.routerPush }),
}))
Expand Down Expand Up @@ -98,18 +103,57 @@ function makeChatResponse(overrides: Partial<ChatResponse> = {}): ChatResponse {
}
}

const frame = (json: string) => `data: ${json}\n\n`

function finalFrame(response: ChatResponse): string {
return frame(JSON.stringify({ type: 'final', response }))
}

function sseStreamResponse(...frames: string[]) {
const encoder = new TextEncoder()
const body = new ReadableStream<Uint8Array>({
start(controller) {
for (const sseFrame of frames) {
controller.enqueue(encoder.encode(sseFrame))
}
controller.close()
},
})
return {
ok: true,
status: 200,
body,
json: async () => null,
}
}

function httpErrorResponse(status: number, errorBody: { error?: string; errorCode?: string }) {
return {
ok: false,
status,
body: null,
json: async () => errorBody,
}
}

describe('mobile useChatComposer', () => {
beforeEach(() => {
mocks.state.profile = undefined
mocks.apiClient.mockReset()
mocks.openChatStream.mockReset()
mocks.routerPush.mockReset()
mocks.queryClient.invalidateQueries.mockClear()
mocks.queryClient.setQueryData.mockClear()
useChatStore.setState({ messages: [], isTyping: false })
})

it('appends the user and AI messages on a successful send', async () => {
mocks.apiClient.mockResolvedValue(makeChatResponse({ aiMessage: 'Logged it' }))
it('streams deltas into a single ai bubble and the final response wins', async () => {
mocks.openChatStream.mockResolvedValue(sseStreamResponse(
frame('{"type":"started"}'),
frame('{"type":"delta","text":"Logged"}'),
frame('{"type":"delta","text":" it"}'),
finalFrame(makeChatResponse({ aiMessage: 'Logged it', correlationId: 'trace-1' })),
))
const composer = await renderComposer()

await TestRenderer.act(async () => {
Expand All @@ -119,16 +163,37 @@ describe('mobile useChatComposer', () => {
const messages = useChatStore.getState().messages
expect(messages).toHaveLength(2)
expect(messages[0]).toMatchObject({ role: 'user', content: 'log water' })
expect(messages[1]).toMatchObject({ role: 'ai', content: 'Logged it' })
expect(mocks.apiClient).toHaveBeenCalledWith(
API.chat.send,
expect.objectContaining({ method: 'POST' }),
)
expect(messages[1]).toMatchObject({
role: 'ai',
content: 'Logged it',
correlationId: 'trace-1',
})
expect(useChatStore.getState().isTyping).toBe(false)
expect(composer.current.canRetryLastSend).toBe(false)
})

it('clears the streamed draft on reset so the final answer is not duplicated', async () => {
mocks.openChatStream.mockResolvedValue(sseStreamResponse(
frame('{"type":"delta","text":"Checking"}'),
frame('{"type":"reset"}'),
frame('{"type":"round","iteration":1}'),
frame('{"type":"delta","text":"Done"}'),
finalFrame(makeChatResponse({ aiMessage: 'Done' })),
))
const composer = await renderComposer()

await TestRenderer.act(async () => {
await composer.current.sendMessage('check my goals')
})

const aiMessages = useChatStore.getState().messages.filter((message) => message.role === 'ai')
expect(aiMessages).toHaveLength(1)
expect(aiMessages[0]?.content).toBe('Done')
})

it('bumps the local AI usage count for non-pro users', async () => {
mocks.state.profile = { aiMessagesUsed: 3 } as Profile
mocks.apiClient.mockResolvedValue(makeChatResponse())
mocks.openChatStream.mockResolvedValue(sseStreamResponse(finalFrame(makeChatResponse())))
const composer = await renderComposer()

await TestRenderer.act(async () => {
Expand All @@ -145,7 +210,7 @@ describe('mobile useChatComposer', () => {

it('does not bump usage for pro users', async () => {
mocks.state.profile = { hasProAccess: true, aiMessagesUsed: 0 } as Profile
mocks.apiClient.mockResolvedValue(makeChatResponse())
mocks.openChatStream.mockResolvedValue(sseStreamResponse(finalFrame(makeChatResponse())))
const composer = await renderComposer()

await TestRenderer.act(async () => {
Expand All @@ -155,11 +220,10 @@ describe('mobile useChatComposer', () => {
expect(mocks.queryClient.setQueryData).not.toHaveBeenCalled()
})

it('routes to upgrade when the backend denies with a premium 403', async () => {
mocks.apiClient.mockRejectedValue({
status: 403,
data: { error: 'Premium plan required to use AI chat' },
})
it('routes to upgrade when the backend denies with a premium 403 before streaming', async () => {
mocks.openChatStream.mockResolvedValue(
httpErrorResponse(403, { error: 'Premium plan required to use AI chat' }),
)
const composer = await renderComposer()

await TestRenderer.act(async () => {
Expand All @@ -170,11 +234,11 @@ describe('mobile useChatComposer', () => {
expect(composer.current.sendError).toBe('Premium plan required to use AI chat')
})

it('surfaces the limit error without routing on a non-upgrade 403', async () => {
mocks.apiClient.mockRejectedValue({
status: 403,
data: { error: 'Daily message limit reached' },
})
it('surfaces the limit error without routing when the stream reports a non-upgrade 403', async () => {
mocks.openChatStream.mockResolvedValue(sseStreamResponse(
frame('{"type":"started"}'),
frame('{"type":"error","status":403,"error":"Daily message limit reached"}'),
))
const composer = await renderComposer()

await TestRenderer.act(async () => {
Expand All @@ -183,6 +247,7 @@ describe('mobile useChatComposer', () => {

expect(mocks.routerPush).not.toHaveBeenCalled()
expect(composer.current.sendError).toBe('chat.limitReachedError')
expect(composer.current.canRetryLastSend).toBe(false)
})

it('blocks sending and surfaces the offline title when offline', async () => {
Expand All @@ -192,17 +257,17 @@ describe('mobile useChatComposer', () => {
await composer.current.sendMessage('hello')
})

expect(mocks.apiClient).not.toHaveBeenCalled()
expect(mocks.openChatStream).not.toHaveBeenCalled()
expect(composer.current.sendError).toBe('You are offline')
})

it('aborts a hung send at the shared timeout and arms retry with the timeout copy', async () => {
it('aborts an idle stream at the watchdog and arms retry with the timeout copy', async () => {
vi.useFakeTimers()
try {
mocks.apiClient.mockImplementation(
(_path: string, options: { signal?: AbortSignal }) =>
mocks.openChatStream.mockImplementation(
(_formData: FormData, signal: AbortSignal) =>
new Promise((_resolve, reject) => {
options.signal?.addEventListener('abort', () => {
signal.addEventListener('abort', () => {
reject(Object.assign(new Error('Aborted'), { name: 'AbortError' }))
})
}),
Expand All @@ -211,7 +276,7 @@ describe('mobile useChatComposer', () => {

await TestRenderer.act(async () => {
const sendPromise = composer.current.sendMessage('hello')
await vi.advanceTimersByTimeAsync(CHAT_SEND_TIMEOUT_MS)
await vi.advanceTimersByTimeAsync(CHAT_STREAM_IDLE_TIMEOUT_MS)
await sendPromise
})

Expand All @@ -224,9 +289,15 @@ describe('mobile useChatComposer', () => {
})

it('retries the failed send without duplicating the user message', async () => {
mocks.apiClient
.mockRejectedValueOnce({ status: 500, data: { error: 'boom' } })
.mockResolvedValueOnce(makeChatResponse({ aiMessage: 'Recovered' }))
mocks.openChatStream
.mockResolvedValueOnce(sseStreamResponse(
frame('{"type":"started"}'),
frame('{"type":"error","status":500,"error":"boom"}'),
))
.mockResolvedValueOnce(sseStreamResponse(
frame('{"type":"delta","text":"Recovered"}'),
finalFrame(makeChatResponse({ aiMessage: 'Recovered' })),
))
const composer = await renderComposer()

await TestRenderer.act(async () => {
Expand All @@ -245,21 +316,6 @@ describe('mobile useChatComposer', () => {
expect(composer.current.sendError).toBeNull()
})

it('does not arm retry when the failure is the monthly message limit', async () => {
mocks.apiClient.mockRejectedValue({
status: 403,
data: { error: 'Daily message limit reached' },
})
const composer = await renderComposer()

await TestRenderer.act(async () => {
await composer.current.sendMessage('hello')
})

expect(composer.current.sendError).toBe('chat.limitReachedError')
expect(composer.current.canRetryLastSend).toBe(false)
})

it('confirms then executes a pending operation through the API', async () => {
mocks.apiClient
.mockResolvedValueOnce({ confirmationToken: 'token-1' })
Expand Down
Loading
Loading