: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(mobile): preserve queued chat messages across restarts (#127522)
Chris Volzer0433ca0e8253
diff --git a/products/mobile/docs/CHAT.md b/products/mobile/docs/CHAT.mdindex f4c91d0eefdd..91289c17a101 100644--- a/products/mobile/docs/CHAT.md+++ b/products/mobile/docs/CHAT.md@@ -62,7 +62,11 @@ Text and attached report IDs are saved separately for each task, each report disthe new-chat composer. Native drafts use encrypted device storage, scoped to the account,host and project, with at most 50 drafts per project. Changes save after 400 ms of idle timeand flush when the composer closes or the app backgrounds. Opening a saved chat restores its-draft after storage loads.+draft after storage loads. If a save fails, the composer keeps the text and shows an unsaved-draft+notice with **Retry save**. The notice stays until saving succeeds. When saved messages reach the+device limit, remove a queued message to free space, then retry before closing the chat.+Close and background saves use the same storage checks; a failed save leaves previously saved+messages intact.`mobile_chat_draft_restored` is captured with `text_length` and `report_count` when the restored draft has text.A successful send clears the submitted text. A failed send keeps it, and a delayed completion@@ -204,22 +208,28 @@ On the next message to a live run, `useSession` first sends one command per chanAn untouched model sends no triple, so the server keeps the previous run's selection; the mode maps onto the previous run's harness.No `branch`: a resumed run keeps its base branch.- **Queue.** A message sent while the agent works, while a send or an answer is in flight, while a decision waits, or behind earlier queued messages goes into a queue above the composer instead (`messageQueue.ts`, `QueuedMessages.tsx`), as on the web.- The banner shows "N queued" and one row per message, each with a remove control.- The queue lives in memory only.+ The banner shows "N queued" and one row per message, each with a remove control. During delivery it shows "Sending queued messages" and hides the recovery warning until delivery settles.+ Queued text is saved with the chat's draft in native secure storage before the composer clears.+ Task adoption waits for pending queue writes and carries live files, cleared composer text, and Stop holds into the saved task.+ A failed storage read aborts the save and leaves existing queues intact.+ A per-project storage budget refuses additional text while preserving saved messages; removing messages still works if an older store exceeds the limit.While the agent works and the input has text, Send shows beside Stop, which turns into an outline button.- **Automatic drain.** When the turn ends and nothing else is in flight or waiting, the queued rows go out as one message, joined by blank lines.A run that has ended takes the queue too: the send resumes it, as for any follow-up.- **Send now.** Sends the queue into the live turn at once with `params.steer: true` on `user_message`, when the session reports `canSteer`; otherwise it goes as an ordinary follow-up.It is disabled with "Answer the agent first" while a decision waits, and with "Wait for the agent to start" while the turn runs but the stream has not shown the agent generating yet.+ It also waits for saved messages and conversation history to load. If history fails, retry loading it before sending recovered messages.The reason shows under the banner, because a phone has no tooltip.-- **Hold.** Stop holds the queue, so it does not go out when the stopped turn ends; the banner then says "N queued, not sent yet".+- **Hold.** Stop holds the queue, so it does not go out when the stopped turn ends; the banner then says "N queued, review before sending".A new message lifts that hold.- A failed delivery puts its rows back in front of anything queued since and holds them; only Send now sends them again, because the failed send may have reached the agent.-- Closing the sheet, an Android back, or New chat puts the queued messages back in front of the composer text, so the draft keeps them.+ Acknowledged rows are removed even if Stop interrupts delivery; any remaining rows keep the Stop hold.+ Delivery keeps its saved rows until acknowledgment. A failed delivery holds them; only Send now sends them again, because the failed send may have reached the agent.+- Closing the sheet or using Android back preserves queued text separately from the composer. Reopening holds the recovered queue for review before Send now.+ New chat waits while a taskless send or queue is pending, so those messages cannot drain into a different conversation.- **Files.** A queued message takes the composer's files with it, as on the web, and the row shows "1 file" or "N files".The drained message, or Send now, carries the files of every row in queue order. The 10-file cap applies per composer message, not to the join.A failed delivery puts the rows back with their files. Removing a row drops its files.- Closing the sheet or New chat drops the queued files, as closing drops unsent composer files. The queued text folds into the chat's own draft, so its files must not follow into another chat.+ Closing the sheet or New chat drops the queued files, as closing drops unsent composer files. Recovered rows record that files are missing and cannot send until their text is copied, removed, and attached again. File paths and contents are not saved.Attach stays enabled while messages queue. Files of a direct send still in flight stay with that send and never join the queue.- `mobile_session_queued` is captured with `queue_length` when a message joins the queue, `mobile_session_queue_removed` with `queue_length` after a row is removed,and `mobile_session_queue_sent_now` with `queued_count` and `steer` (the session could steer at the tap).diff --git a/products/mobile/docs/GAPS.md b/products/mobile/docs/GAPS.mdindex 6da392a07833..facdccab95f6 100644--- a/products/mobile/docs/GAPS.md+++ b/products/mobile/docs/GAPS.md@@ -38,8 +38,8 @@ Known gaps and behavior that stays on the device.- **The suggested prompts stay visible behind the organization AI notice.** When the organization has not allowed AI processing, the empty state's prompt chips still render above the notice, and a tap on one has no composer to fill.- **Legacy conversations are not listed.** The Chats list shows task sessions only.LangGraph chats made before the move stay in the web app's legacy view and `/ai?chat=<id>` links.-- **No message queueing while the agent works.** Stop replaces Send until the turn ends.- The web queues messages typed meanwhile and joins them into one `user_message` after `turn_complete`.+- **Queued messages require review after reopening a chat.** Queued text is saved with the chat's draft in native secure storage before the composer clears. Delivery keeps that saved text until the server acknowledges it. After a restart or reopening, the queue waits for **Send now** because a message may already have reached the agent. Check the conversation before repeating it; delivery is not exactly once.+ Queued files stay in memory. After reopening, messages that had files cannot send until you copy their text, remove them, and attach the files again. File paths and contents are not saved in the draft store. Storage failures keep the composer or queue visible and show retry feedback. Drafts and queues are isolated by account, host, project, and chat, and cleared on sign-out. The web preview keeps them in memory only.- **No PostHog Desktop access pre-check.** A refused user learns it from the 403 on the first send.`GET /api/code/invites/check-access/` evaluates the server-side current team, which can differ from the app's project,and the project-scoped `desktop/access/` needs `llm_gateway:read`, which the app does not request.diff --git a/products/mobile/src/features/chat/ChatHeader.tsx b/products/mobile/src/features/chat/ChatHeader.tsxindex c7418a86516b..36fed79d4767 100644--- a/products/mobile/src/features/chat/ChatHeader.tsx+++ b/products/mobile/src/features/chat/ChatHeader.tsx@@ -27,10 +27,18 @@ interface ChatHeaderProps {blurTarget?: RefObject<View | null>onBack: () => voidonNewChat: () => void+ newChatDisabledReason?: stringonArchive?: () => Promise<void>}-export function ChatHeader({ webUrl, blurTarget, onBack, onNewChat, onArchive }: ChatHeaderProps): ReactElement {+export function ChatHeader({+ webUrl,+ blurTarget,+ onBack,+ onNewChat,+ newChatDisabledReason,+ onArchive,+}: ChatHeaderProps): ReactElement {const colors = useColors()const styles = useStyles()const insets = useScreenInsets()@@ -68,8 +76,10 @@ export function ChatHeader({ webUrl, blurTarget, onBack, onNewChat, onArchive }:</Pressable44><PillControl height={ROW_HEIGHT}><Pressable44- onPress={onNewChat}+ onPress={() => (newChatDisabledReason ? toasts.show(newChatDisabledReason) : onNewChat())}accessibilityLabel="New chat"+ accessibilityState={{ disabled: !!newChatDisabledReason }}+ accessibilityHint={newChatDisabledReason}pressedBackground={colors.background}style={styles.button}testID="chat-new"diff --git a/products/mobile/src/features/chat/ChatScreen.test.tsx b/products/mobile/src/features/chat/ChatScreen.test.tsxindex 9970662527d3..d3bdb2a38234 100644--- a/products/mobile/src/features/chat/ChatScreen.test.tsx+++ b/products/mobile/src/features/chat/ChatScreen.test.tsx@@ -1,5 +1,6 @@import { act, fireEvent, render, screen } from '@testing-library/react-native'import { ChatScreen } from './ChatScreen'+import { queueActions, queueReducer } from './messageQueue'import { useSession } from './session/useSession'import { useChatDraft } from './useChatDraft'@@ -41,7 +42,65 @@ afterEach(() => {jest.useRealTimers()})+function mockReadyChat(): { session: ReturnType<typeof useSession>; draft: ReturnType<typeof useChatDraft> } {+ const session: ReturnType<typeof useSession> = {+ taskId: 'task-1',+ runId: 'run-1',+ title: 'Example chat',+ runStatus: 'completed',+ items: [],+ invocations: new Map(),+ phase: 'idle',+ history: { status: 'idle', error: null },+ isSending: false,+ isStopping: false,+ canSteer: false,+ start: jest.fn(async () => true),+ send: jest.fn(async () => true),+ answer: jest.fn(),+ stop: jest.fn(),+ reloadHistory: jest.fn(),+ reset: jest.fn(),+ dismissNotice: jest.fn(),+ }+ const draft: ReturnType<typeof useChatDraft> = {+ draft: { text: 'First message', reportIds: [] },+ ready: true,+ queue: { rows: [], hold: null },+ queuePending: false,+ draftError: undefined,+ draftSaving: false,+ retrySave: jest.fn(async () => undefined),+ queueError: undefined,+ dismissQueueError: jest.fn(),+ updateQueue: jest.fn(async () => true),+ change: jest.fn(),+ beginSend: jest.fn(async () => async () => undefined),+ }+ jest.mocked(useSession).mockImplementation(() => session)+ jest.mocked(useChatDraft).mockImplementation(() => draft)+ return { session, draft }+}+describe('chat send preparation', () => {+ test('keeps an unsaved draft notice visible and disables retry while saving', () => {+ const { draft } = mockReadyChat()+ draft.draftError = 'Draft not saved. Remove a queued message before saving more.'+ const view = render(<ChatScreen source={{ entry: 'compose', origin: null }} onBack={jest.fn()} />)+ expect(screen.getByDisplayValue('First message')).toBeTruthy()+ expect(screen.getByText(draft.draftError)).toBeTruthy()+ fireEvent.press(screen.getByTestId('chat-draft-retry'))+ expect(draft.retrySave).toHaveBeenCalledTimes(1)+ draft.draftSaving = true+ view.rerender(<ChatScreen source={{ entry: 'compose', origin: null }} onBack={jest.fn()} />)+ expect(screen.getByText('Saving…')).toBeTruthy()+ fireEvent.press(screen.getByTestId('chat-draft-retry'))+ expect(draft.retrySave).toHaveBeenCalledTimes(1)+ draft.draftSaving = false+ draft.draftError = undefined+ view.rerender(<ChatScreen source={{ entry: 'compose', origin: null }} onBack={jest.fn()} />)+ expect(screen.queryByTestId('chat-draft-retry')).toBeNull()+ })test.each(['new', 'close', 'unmount'])('a prepared message does not send after %s', async (transition) => {let finishStorage!: (settle: (sent: boolean) => Promise<void>) => voidconst beginSend = jest.fn(@@ -56,6 +115,14 @@ describe('chat send preparation', () => {jest.mocked(useChatDraft).mockReturnValue({draft: { text: 'Continue the old chat', reportIds: [] },ready: true,+ queue: { rows: [], hold: null },+ queuePending: false,+ draftError: undefined,+ draftSaving: false,+ retrySave: jest.fn(async () => undefined),+ queueError: undefined,+ dismissQueueError: jest.fn(),+ updateQueue: jest.fn(async () => true),change: jest.fn(),beginSend,})@@ -94,4 +161,176 @@ describe('chat send preparation', () => {expect(settle).toHaveBeenCalledWith(false)if (transition === 'new') expect(reset).toHaveBeenCalledTimes(1)})+ it('cancels a queued delivery when Stop is pressed before the recovery write finishes', async () => {+ let finishStorage!: (saved: boolean) => void+ const updateQueue = jest+ .fn<Promise<boolean>, Parameters<ReturnType<typeof useChatDraft>['updateQueue']>>()+ .mockImplementationOnce(+ () =>+ new Promise<boolean>((resolve) => {+ finishStorage = resolve+ })+ )+ .mockResolvedValue(true)+ const send = jest.fn(async () => true)+ const stop = jest.fn()+ jest.mocked(useChatDraft).mockReturnValue({+ draft: { text: '', reportIds: [] },+ ready: true,+ queue: { rows: [{ id: 'queued-1', text: 'Wait for me', attachments: [] }], hold: null },+ queuePending: false,+ draftError: undefined,+ draftSaving: false,+ retrySave: jest.fn(async () => undefined),+ queueError: undefined,+ dismissQueueError: jest.fn(),+ updateQueue,+ change: jest.fn(),+ beginSend: jest.fn(),+ })+ jest.mocked(useSession).mockReturnValue({+ taskId: 'task-1',+ runId: 'run-1',+ title: 'Chat',+ runStatus: 'in_progress',+ items: [],+ invocations: new Map(),+ phase: 'working',+ history: { status: 'idle', error: null },+ isSending: false,+ isStopping: false,+ canSteer: true,+ start: send,+ send,+ answer: jest.fn(),+ stop,+ reloadHistory: jest.fn(),+ reset: jest.fn(),+ dismissNotice: jest.fn(),+ })+ render(<ChatScreen source={{ entry: 'compose', origin: null }} onBack={jest.fn()} />)+ fireEvent.press(screen.getByTestId('chat-queue-send-now'))+ expect(send).not.toHaveBeenCalled()+ fireEvent.press(screen.getByTestId('chat-stop'))+ expect(stop).toHaveBeenCalledTimes(1)+ await act(async () => {+ finishStorage(true)+ })+ expect(send).not.toHaveBeenCalled()+ })+ it.each(['stop', 'new', 'close', 'unmount'])(+ 'handles queue acknowledgment after %s interrupts delivery',+ async (transition) => {+ const { session, draft } = mockReadyChat()+ session.phase = 'working'+ session.canSteer = true+ draft.queue = { rows: [{ id: 'queued-1', text: 'Follow up', attachments: [] }], hold: 'unconfirmed' }+ jest.mocked(draft.updateQueue).mockImplementation(async (action) => {+ draft.queue = queueReducer(draft.queue, action)+ return true+ })+ let finish!: (sent: boolean) => void+ jest.mocked(session.send).mockImplementationOnce(+ () =>+ new Promise<boolean>((resolve) => {+ finish = resolve+ })+ )+ const view = render(<ChatScreen source={{ entry: 'compose', origin: null }} onBack={jest.fn()} />)+ await act(async () => {+ fireEvent.press(screen.getByTestId('chat-queue-send-now'))+ })+ expect(session.send).toHaveBeenCalledTimes(1)+ draft.queue = queueReducer(draft.queue, queueActions.enqueue('Later question'))+ if (transition === 'unmount') view.unmount()+ else+ fireEvent.press(+ screen.getByTestId(+ transition === 'new' ? 'chat-new' : transition === 'close' ? 'chat-back' : 'chat-stop'+ )+ )+ await act(async () => {+ finish(true)+ })+ if (transition === 'stop') {+ session.phase = 'idle'+ view.rerender(<ChatScreen source={{ entry: 'compose', origin: null }} onBack={jest.fn()} />)+ expect(screen.queryByText('Follow up')).toBeNull()+ expect(screen.getByText('Later question')).toBeTruthy()+ expect(draft.queue.hold).toBe('cancelled')+ expect(session.send).toHaveBeenCalledTimes(1)+ } else {+ expect(draft.queue.rows.map((row) => row.text)).toEqual(['Follow up', 'Later question'])+ }+ }+ )++ it.each(['loading', 'error'] as const)(+ 'waits for history before sending a recovered queue, history=%s',+ async (status) => {+ const { session, draft } = mockReadyChat()+ session.history = { status, error: null }+ draft.queue = {+ rows: [{ id: 'queued-1', text: 'Recovered question', attachments: [] }],+ hold: 'unconfirmed',+ }+ const view = render(<ChatScreen source={{ entry: 'compose', origin: null }} onBack={jest.fn()} />)+ expect(screen.getByTestId('chat-queue-send-now').props.accessibilityState.disabled).toBe(true)+ fireEvent.press(screen.getByTestId('chat-queue-send-now'))+ expect(session.send).not.toHaveBeenCalled()+ session.history = { status: 'idle', error: null }+ view.rerender(<ChatScreen source={{ entry: 'compose', origin: null }} onBack={jest.fn()} />)+ await act(async () => {+ fireEvent.press(screen.getByTestId('chat-queue-send-now'))+ })+ expect(session.send).toHaveBeenCalledTimes(1)+ }+ )++ it('allows another direct send after Stop interrupts a pending direct reply', async () => {+ const { session, draft } = mockReadyChat()+ let finishSend!: (sent: boolean) => void+ let started!: () => void+ const sending = new Promise<void>((resolve) => {+ started = resolve+ })+ jest.mocked(session.send).mockImplementationOnce(() => {+ started()+ return new Promise<boolean>((resolve) => {+ finishSend = resolve+ })+ })+ const view = render(<ChatScreen source={{ entry: 'compose', origin: null }} onBack={jest.fn()} />)+ await act(async () => {+ fireEvent.press(screen.getByTestId('chat-send'))+ await sending+ })+ session.phase = 'working'+ view.rerender(<ChatScreen source={{ entry: 'compose', origin: null }} onBack={jest.fn()} />)+ fireEvent.press(screen.getByTestId('chat-stop'))+ await act(async () => {+ finishSend(false)+ })+ session.phase = 'idle'+ view.rerender(<ChatScreen source={{ entry: 'compose', origin: null }} onBack={jest.fn()} />)+ await act(async () => {+ fireEvent.press(screen.getByTestId('chat-send'))+ })+ expect(draft.beginSend).toHaveBeenCalledTimes(2)+ expect(draft.updateQueue).toHaveBeenCalledWith({ type: 'hold', reason: 'cancelled' })+ expect(draft.updateQueue).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'enqueue' }), true)+ })++ it('does not start a new conversation while a taskless queue still holds messages', () => {+ const { session, draft } = mockReadyChat()+ session.taskId = null+ 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(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.tsxindex 5035ab928e18..1c142894c525 100644--- a/products/mobile/src/features/chat/ChatScreen.tsx+++ b/products/mobile/src/features/chat/ChatScreen.tsx@@ -45,16 +45,12 @@ import {} from './chatRunOptions'import { type ChatSheetSource, useChatSheetEvents } from './chatSheetEvents'import { inboxContextItem, reportContextFromItem, reportContextFromView } from './contextPrompt'-import type { ChatDraft } from './draftStore'import { MentionPopover } from './MentionPopover'import {canDrain,- EMPTY_QUEUE,joinQueue,joinQueueAttachments,- type QueueState,queueActions,- queueReducer,type SendGate,sendNowState,shouldQueue,@@ -117,6 +113,7 @@ export function ChatScreen({const preparingSend = useRef(false)const [preparing, setPreparing] = useState(false)const queueEpoch = useRef(0)+ const conversationEpoch = useRef(0)const [visible, setVisible] = useState(true)const pathname = usePathname()const userUuid = useAuthStore((state) => state.user?.uuid)@@ -134,6 +131,7 @@ export function ChatScreen({}, [visible, pathname, demo, scope, userUuid, session.taskId])const close = useCallback((): void => {queueEpoch.current+++ conversationEpoch.current++setVisible(false)onBack()}, [onBack])@@ -175,17 +173,9 @@ export function ChatScreen({reportIds: typeof value === 'function' ? value(attached) : value,})}- const [queue, dispatchQueue] = useReducer(queueReducer, EMPTY_QUEUE)+ const queue = composerDraft.queueconst delivering = useRef(false)const [isDelivering, setDelivering] = useState(false)- const latest = useRef<{ queue: QueueState; draft: ChatDraft; change: (draft: ChatDraft) => void }>({- queue,- draft: composerDraft.draft,- change: composerDraft.change,- })- useEffect(() => {- latest.current = { queue, draft: composerDraft.draft, change: composerDraft.change }- })const [reports, setReports] = useState<Record<string, ReportView>>({})const [mentionOpen, setMentionOpen] = useState(false)const mentionTrigger = useRef<'button' | 'typed'>('button')@@ -268,7 +258,7 @@ export function ChatScreen({const bottomInset = insets.bottomconst keyboardStyle = useAnimatedStyle(() => ({ paddingBottom: Math.max(-keyboard.height.value, bottomInset) }))// A message sent before the stored history loads would land in a thread the person cannot see yet.- const composerReady = composerDraft.ready && historyStatus === 'idle'+ const composerReady = composerDraft.ready && !composerDraft.queuePending && historyStatus === 'idle'const ready = composerReady && !preparing && !session.isSendingconst gate: SendGate = {phase: session.phase,@@ -276,7 +266,7 @@ export function ChatScreen({decisionPending: session.decision !== undefined,}const queueing = shouldQueue(gate, queue)- // Queueing needs no network, so only a direct send waits for the previous one.+ // Queueing needs no network, but the device write must finish before the composer can submit again.const canSend = text.trim().length > 0 && (queueing ? composerReady : ready)const sendNow = sendNowState({...gate,@@ -370,9 +360,11 @@ export function ChatScreen({setAttachOpen(false)void attachments.pick(source).finally(() => input.current?.focus())}- const notice = attachments.notice ?? session.notice+ const notice = composerDraft.draftError ?? composerDraft.queueError ?? attachments.notice ?? session.noticeconst dismissNotice = (): void => {- if (attachments.notice) {+ if (composerDraft.queueError) {+ composerDraft.dismissQueueError()+ } else if (attachments.notice) {attachments.dismissNotice()} else {session.dismissNotice()@@ -404,49 +396,45 @@ export function ChatScreen({})setAttached((previous) => previous.filter((id) => id !== reportId))}- // Queued messages go back into the composer draft, so closing the sheet or starting a new chat loses none.- // Returns the queued files; the draft cannot hold them.- const foldQueue = (): PendingAttachment[] => {- queueEpoch.current++- const { queue: current, draft, change } = latest.current- if (current.rows.length === 0) {- return []+ const screenMounted = useRef(true)+ const queuedFiles = useRef<PendingAttachment[]>([])+ queuedFiles.current = joinQueueAttachments(queue.rows)+ useEffect(() => {+ screenMounted.current = true+ return () => {+ screenMounted.current = false+ queueEpoch.current+++ conversationEpoch.current+++ releaseAttachments(queuedFiles.current)}- const next = { ...draft, text: [joinQueue(current.rows), draft.text.trim()].filter(Boolean).join('\n\n') }- latest.current = { queue: EMPTY_QUEUE, draft: next, change }- dispatchQueue(queueActions.clear())- change(next)- return joinQueueAttachments(current.rows)- }- // Native Back also unmounts the route without the header callback.- // biome-ignore lint/correctness/useExhaustiveDependencies: `foldQueue` reads only refs.- useEffect(() => () => releaseAttachments(foldQueue()), [])+ }, [])// The mode the chip shows, already mapped onto the harness the message runs on.const sendOptions = (): ChatRunOptions => ({ ...runOptions, permissionMode })const deliverQueue = (steer: boolean): void => {const rows = queue.rows- if (rows.length === 0 || delivering.current) {+ if (!composerReady || rows.length === 0 || rows.some((row) => row.missingAttachments) || delivering.current) {return}const epoch = queueEpoch.current+ const conversation = conversationEpoch.currentdelivering.current = truesetDelivering(true)- // Cleared before the send, so a message queued while it is in flight waits for the next delivery.- dispatchQueue(queueActions.clear())- void session- .send(joinQueue(rows), buildContext(), sendOptions(), {- ...(steer ? { steer: true } : {}),- queuedCount: rows.length,- attachments: joinQueueAttachments(rows),- })- .catch(() => false)- .then((sent) => {+ void composerDraft+ .updateQueue(queueActions.hold('unconfirmed'))+ .then(async (saved) => {+ if (!saved || queueEpoch.current !== epoch) return+ const sent = await session+ .send(joinQueue(rows), buildContext(), sendOptions(), {+ ...(steer ? { steer: true } : {}),+ queuedCount: rows.length,+ attachments: joinQueueAttachments(rows),+ })+ .catch(() => false)if (sent) {sheetEvents.countSent()- } else if (queueEpoch.current === epoch) {- // Held, because the failed send may have reached the agent, and a second automatic try could- // deliver it twice.- dispatchQueue(queueActions.restore(rows))+ if (conversationEpoch.current === conversation) {+ await composerDraft.updateQueue({ type: 'delivered', ids: rows.map((row) => row.id) })+ }}}).finally(() => {@@ -454,7 +442,7 @@ export function ChatScreen({setDelivering(false)})}- const drainable = composerReady && canDrain(gate, queue)+ const drainable = composerReady && !composerDraft.queueError && canDrain(gate, queue)// biome-ignore lint/correctness/useExhaustiveDependencies: drains on the transition into a drainable state only.useEffect(() => {if (drainable) {@@ -462,22 +450,37 @@ export function ChatScreen({}}, [drainable])const sendQueueNow = (): void => {- if (queue.rows.length === 0 || sendNow.pending || sendNow.disabledReason) {+ if (!composerReady || queue.rows.length === 0 || sendNow.pending || sendNow.disabledReason) {return}track('mobile_session_queue_sent_now', { queued_count: queue.rows.length, steer: session.canSteer })deliverQueue(true)}const removeQueued = (id: string): void => {- releaseAttachments(queue.rows.find((row) => row.id === id)?.attachments ?? [])- dispatchQueue(queueActions.remove(id))+ if (isDelivering) return+ const files = queue.rows.find((row) => row.id === id)?.attachments ?? []+ void composerDraft.updateQueue(queueActions.remove(id)).then((saved) => {+ if (saved) releaseAttachments(files)+ })track('mobile_session_queue_removed', {queue_length: queue.rows.filter((row) => row.id !== id).length,})}+ const clearPreparation = (): void => {+ preparingSend.current = false+ setPreparing(false)+ setSendingFileIds([])+ }+ const newChatDisabledReason =+ !draftTaskId &&+ (preparing || session.isSending || isDelivering || composerDraft.queuePending || queue.rows.length > 0)+ ? 'Finish this message or remove queued messages before starting a new chat.'+ : undefinedconst stop = (): void => {+ queueEpoch.current+++ clearPreparation()// The stopped turn ends like any other, so without the hold the queue would go out right after the Stop.- dispatchQueue(queueActions.hold('cancelled'))+ void composerDraft.updateQueue(queueActions.hold('cancelled'))session.stop()}const send = (): void => {@@ -488,10 +491,11 @@ export function ChatScreen({if (queueing || preparingSend.current) {setMentionOpen(false)const queuedFiles = attachments.files.filter((file) => !sendingFileIds.includes(file.id))- dispatchQueue(queueActions.enqueue(message, queuedFiles))- attachments.clear({ only: queuedFiles.map((file) => file.id), release: false })+ void composerDraft.updateQueue(queueActions.enqueue(message, queuedFiles), true).then((saved) => {+ if (saved) attachments.clear({ only: queuedFiles.map((file) => file.id), release: false })+ else if (!screenMounted.current) releaseAttachments(queuedFiles)+ })track('mobile_session_queued', { queue_length: queue.rows.length + 1 })- composerDraft.change({ text: '', reportIds: attached })return}if (!ready) {@@ -526,19 +530,17 @@ export function ChatScreen({}).finally(() => {if (queueEpoch.current === epoch) {- preparingSend.current = false- setPreparing(false)- setSendingFileIds([])+ clearPreparation()}})}const startNewChat = (): void => {+ if (newChatDisabledReason || (!draftTaskId && (preparingSend.current || delivering.current))) returnsheetEvents.countNewChat()- // The queued text folds into this chat's draft, so its files must not follow into the new chat.- releaseAttachments(foldQueue())- preparingSend.current = false- setPreparing(false)- setSendingFileIds([])+ queueEpoch.current+++ conversationEpoch.current+++ releaseAttachments(joinQueueAttachments(queue.rows))+ clearPreparation()if (target.taskId) {// The session reloads as an empty new chat when its task option goes.setTarget({})@@ -623,10 +625,29 @@ export function ChatScreen({<QueuedMessagesrows={queue.rows}held={queue.hold !== null}+ delivering={isDelivering}onRemove={removeQueued}onSendNow={sendQueueNow}- sendNowDisabledReason={sendNow.disabledReason}- sendNowPending={sendNow.pending}+ sendNowDisabledReason={+ queue.rows.some((row) => row.missingAttachments)+ ? 'Files were not saved. Copy the queued text, remove it, and attach the files again.'+ : historyStatus === 'loading'+ ? 'Loading conversation…'+ : historyStatus === 'error'+ ? 'Retry loading the conversation before sending.'+ : sendNow.disabledReason+ }+ notice={+ queue.hold === 'unconfirmed'+ ? 'Check the conversation before sending again. These messages may already have reached the agent.'+ : undefined+ }+ sendNowPending={+ sendNow.pending ||+ !composerDraft.ready ||+ composerDraft.queuePending ||+ historyStatus === 'loading'+ }/><SessionDecisionPaneldecision={session.decision}@@ -634,6 +655,8 @@ export function ChatScreen({pending={session.isSending}onAnswer={(answerInput) => void session.answer(answerInput)}onDismissNotice={dismissNotice}+ onRetryNotice={composerDraft.draftError ? composerDraft.retrySave : undefined}+ noticePending={composerDraft.draftSaving}/>{/* A pending decision has its own reply field, so it replaces the composer, as on the web. */}{session.decision ? null : (@@ -675,6 +698,7 @@ export function ChatScreen({blurTarget={blurTarget}onBack={close}onNewChat={startNewChat}+ newChatDisabledReason={newChatDisabledReason}onArchive={session.taskId ? archiveChat : undefined}/><ChatOptionsSheetdiff --git a/products/mobile/src/features/chat/QueuedMessages.test.tsx b/products/mobile/src/features/chat/QueuedMessages.test.tsxnew file mode 100644index 000000000000..a568455f3ea9--- /dev/null+++ b/products/mobile/src/features/chat/QueuedMessages.test.tsx@@ -0,0 +1,21 @@+import { render, screen } from '@testing-library/react-native'++import { QueuedMessages } from './QueuedMessages'++it('shows delivery progress until an interrupted queue needs review', () => {+ const props = {+ rows: [{ id: 'queued-1', text: 'Check the examples', attachments: [] }],+ held: true,+ notice: 'Check the conversation before sending again.',+ onRemove: jest.fn(),+ onSendNow: jest.fn(),+ }+ const view = render(<QueuedMessages {...props} delivering sendNowPending />)+ expect(screen.getByText('Sending queued messages')).toBeTruthy()+ expect(screen.queryByText(props.notice)).toBeNull()+ expect(screen.getByTestId('chat-queue-send-now')).toBeDisabled()+ view.rerender(<QueuedMessages {...props} delivering={false} sendNowPending={false} />)+ expect(screen.queryByText('Sending queued messages')).toBeNull()+ expect(screen.getByText('1 queued, review before sending')).toBeTruthy()+ expect(screen.getByText(props.notice)).toBeTruthy()+})diff --git a/products/mobile/src/features/chat/QueuedMessages.tsx b/products/mobile/src/features/chat/QueuedMessages.tsxindex a9a14ded322e..8ad34b965fc2 100644--- a/products/mobile/src/features/chat/QueuedMessages.tsx+++ b/products/mobile/src/features/chat/QueuedMessages.tsx@@ -1,4 +1,5 @@-import type { ReactElement } from 'react'+import * as Clipboard from 'expo-clipboard'+import { type ReactElement, useState } from 'react'import { ActivityIndicator, ScrollView, Text, View } from 'react-native'import { CloseIcon } from '@/ui/icons/CloseIcon'@@ -11,6 +12,8 @@ import type { QueuedMessage } from './messageQueue'interface QueuedMessagesProps {rows: QueuedMessage[]held: boolean+ delivering: boolean+ notice?: stringonRemove: (id: string) => voidonSendNow: () => voidsendNowDisabledReason?: string@@ -20,11 +23,14 @@ interface QueuedMessagesProps {export function QueuedMessages({rows,held,+ delivering,+ notice,onRemove,onSendNow,sendNowDisabledReason,sendNowPending,}: QueuedMessagesProps): ReactElement | null {+ const [copyNotice, setCopyNotice] = useState<string>()const colors = useColors()const styles = useStyles()if (rows.length === 0) {@@ -35,7 +41,9 @@ export function QueuedMessages({<View style={styles.banner} testID="chat-queue"><View style={styles.header}><Text style={styles.label} accessibilityLiveRegion="polite">- {`${rows.length} queued${held ? ', not sent yet' : ''}`}+ {delivering+ ? 'Sending queued messages'+ : `${rows.length} queued${held ? ', review before sending' : ''}`}</Text><Pressable44onPress={onSendNow}@@ -51,6 +59,16 @@ export function QueuedMessages({<Text style={styles.sendNowLabel}>Send now</Text></Pressable44></View>+ {copyNotice ? (+ <Text style={styles.reason} accessibilityLiveRegion="polite">+ {copyNotice}+ </Text>+ ) : null}+ {notice && !delivering ? (+ <Text style={styles.reason} accessibilityLiveRegion="polite">+ {notice}+ </Text>+ ) : null}{sendNowDisabledReason ? <Text style={styles.reason}>{sendNowDisabledReason}</Text> : null}{/* Capped so a long queue cannot push the composer off the screen. */}<ScrollView@@ -63,13 +81,34 @@ export function QueuedMessages({<Text style={styles.rowText} numberOfLines={2}>{row.text}</Text>- {row.attachments.length > 0 ? (+ {(row.missingAttachments ?? 0) > 0 ? (+ <Text style={styles.rowFiles}>Reattach files</Text>+ ) : row.attachments.length > 0 ? (<Text style={styles.rowFiles} testID="chat-queue-row-files">{row.attachments.length === 1 ? '1 file' : `${row.attachments.length} files`}</Text>) : null}+ {row.missingAttachments ? (+ <Pressable44+ onPress={() => {+ void Clipboard.setStringAsync(row.text).then(+ () =>+ setCopyNotice(+ 'Copied. Remove the queued message, paste the text, and attach the files again.'+ ),+ () => setCopyNotice("Couldn't copy the text. Try again.")+ )+ }}+ accessibilityLabel="Copy queued text"+ style={styles.remove}+ pressedBackground={colors.pressed}+ >+ <Text style={styles.rowFiles}>Copy</Text>+ </Pressable44>+ ) : null}<Pressable44onPress={() => onRemove(row.id)}+ disabled={sendNowPending}accessibilityLabel="Remove from queue"pressedBackground={colors.pressed}style={styles.remove}diff --git a/products/mobile/src/features/chat/draftPersistence.test.ts b/products/mobile/src/features/chat/draftPersistence.test.tsindex 03bb4a2f9422..deee2f48438f 100644--- a/products/mobile/src/features/chat/draftPersistence.test.ts+++ b/products/mobile/src/features/chat/draftPersistence.test.ts@@ -1,5 +1,6 @@const mockAuth = { signedIn: true, host: 'https://example.com', user: { uuid: 'user-1' }, projectId: 1 }const mockSecure = new Map<string, string>()+let mockFailedRead: string | undefinedlet mockRevision = 0jest.mock('@/auth/tokens', () => ({ getSessionTokens: () => ({ accessToken: 'fake' }) }))@@ -14,7 +15,13 @@ jest.mock('expo-crypto', () => ({randomUUID: () => `revision-${mockRevision++}`,}))jest.mock('expo-secure-store', () => ({- getItemAsync: async (key: string) => mockSecure.get(key) ?? null,+ getItemAsync: async (key: string) => {+ if (key === mockFailedRead) {+ mockFailedRead = undefined+ throw new Error('SecureStore read failed')+ }+ return mockSecure.get(key) ?? null+ },setItemAsync: async (key: string, value: string) => {if (Buffer.byteLength(value, 'utf8') > 2048) {throw new Error('SecureStore item too large')@@ -27,10 +34,12 @@ jest.mock('expo-secure-store', () => ({}))import { chatDrafts, draftIdentity, draftScope } from './draftPersistence'+import { EMPTY_QUEUE, queueActions, queueReducer } from './messageQueue'beforeEach(async () => {await chatDrafts.clear([])mockSecure.clear()+ mockFailedRead = undefinedmockAuth.projectId = 1})@@ -48,6 +57,21 @@ describe('chat draft persistence', () => {}})+ it('preserves all saved queues when a project manifest read fails', async () => {+ const scope = (await draftScope(draftIdentity() as string)) as string+ const first = queueReducer(EMPTY_QUEUE, queueActions.enqueue('First saved question'))+ const second = queueReducer(EMPTY_QUEUE, queueActions.enqueue('Second saved question'))+ await chatDrafts.saveQueue(scope, 'task:first', first)+ const before = new Map(mockSecure)+ mockFailedRead = scope+ await expect(chatDrafts.saveQueue(scope, 'task:second', second)).rejects.toThrow('SecureStore read failed')+ expect(mockSecure).toEqual(before)+ expect((await chatDrafts.loadQueue(scope, 'task:first')).rows).toMatchObject([{ text: 'First saved question' }])+ await chatDrafts.saveQueue(scope, 'task:second', second)+ expect((await chatDrafts.loadQueue(scope, 'task:first')).rows).toHaveLength(1)+ expect((await chatDrafts.loadQueue(scope, 'task:second')).rows).toHaveLength(1)+ })+it('wipes encrypted drafts for every project on session end and invalidates pending sends', async () => {const first = (await draftScope(draftIdentity() as string)) as stringconst settle = await chatDrafts.beginSend(first, 'new-chat', { text: 'Private', reportIds: [] })diff --git a/products/mobile/src/features/chat/draftPersistence.ts b/products/mobile/src/features/chat/draftPersistence.tsindex 054df61b265a..a5d723a6fbb1 100644--- a/products/mobile/src/features/chat/draftPersistence.ts+++ b/products/mobile/src/features/chat/draftPersistence.ts@@ -33,8 +33,9 @@ interface Manifest {}async function manifest(key: string): Promise<Manifest | null> {+ const stored = await itemStorage.getItem(key)try {- const value: unknown = JSON.parse((await itemStorage.getItem(key)) ?? 'null')+ const value: unknown = JSON.parse(stored ?? 'null')if (value && typeof value === 'object') {const record = value as Record<string, unknown>if (diff --git a/products/mobile/src/features/chat/draftStore.test.ts b/products/mobile/src/features/chat/draftStore.test.tsindex 420c1d89f058..64ac98610905 100644--- a/products/mobile/src/features/chat/draftStore.test.ts+++ b/products/mobile/src/features/chat/draftStore.test.ts@@ -1,4 +1,7 @@-import { type DraftStorage, DraftStore } from './draftStore'+import * as Crypto from 'expo-crypto'++import { type DraftStorage, DraftStorageLimitError, DraftStore } from './draftStore'+import { EMPTY_QUEUE, queueActions, queueReducer } from './messageQueue'function memoryStorage(): DraftStorage {const values = new Map<string, string>()@@ -15,6 +18,11 @@ function memoryStorage(): DraftStorage {const draft = (text: string, reportIds: string[] = []): { text: string; reportIds: string[] } => ({ text, reportIds })+let nextQueueId = 0+jest.spyOn(Crypto, 'randomUUID').mockImplementation(+ () => `00000000-0000-4000-8000-${String(++nextQueueId).padStart(12, '0')}`+)+describe('chat draft persistence', () => {it('restores across app restarts and isolates account, host and project scopes', async () => {const storage = memoryStorage()@@ -58,6 +66,28 @@ describe('chat draft persistence', () => {expect(await restarted.load('project', 'task:1')).toBeNull()})+ it.each(['read', 'write'])(+ 'clears a stale accepted-send marker on autosave after a failed settlement %s',+ async (failure) => {+ const storage = memoryStorage()+ const store = new DraftStore(storage)+ const queued = queueReducer(EMPTY_QUEUE, queueActions.enqueue('Queued follow-up'))+ await store.saveQueue('project', 'task:1', queued)+ const settle = await store.beginSend('project', 'task:1', draft('Accepted'))+ if (failure === 'read') {+ jest.spyOn(storage, 'getItem').mockRejectedValueOnce(new Error('Read failed'))+ } else {+ jest.spyOn(storage, 'setItem').mockRejectedValueOnce(new Error('Write failed'))+ }+ await expect(settle(true)).rejects.toThrow()+ await store.save('project', 'task:1', draft('New typing'))+ await store.save('project', 'task:1', draft(''))+ const restarted = new DraftStore(storage)+ expect(await restarted.load('project', 'task:1')).toBeNull()+ expect((await restarted.loadQueue('project', 'task:1')).rows[0]?.text).toBe('Queued follow-up')+ }+ )+it('moves pending sends to the created task without redirecting the next new chat', async () => {const store = new DraftStore(memoryStorage())const settle = await store.beginSend('project', 'new-chat', draft('First'))@@ -90,4 +120,143 @@ describe('chat draft persistence', () => {expect(await store.load('project', 'task:2')).toEqual(draft('Still usable'))})+ it.each(['queued', 'sending'])(+ 'recovers %s rows held across restart without persisting file paths',+ async (stage) => {+ const storage = memoryStorage()+ const store = new DraftStore(storage)+ let queue = queueReducer(+ EMPTY_QUEUE,+ queueActions.enqueue('Question', [+ {+ id: 'file-1',+ uri: 'file:///private/example',+ name: 'example.txt',+ size: 1,+ contentType: 'text/plain',+ isImage: false,+ },+ ])+ )+ if (stage === 'sending') queue = queueReducer(queue, queueActions.hold('unconfirmed'))+ await store.saveQueue('project', 'task:1', queue, draft(''))+ await store.save('project', 'task:1', draft('Next question'))+ const restarted = new DraftStore(storage)+ expect(await restarted.load('project', 'task:1')).toEqual(draft('Next question'))+ expect(await restarted.loadQueue('project', 'task:1')).toEqual({+ rows: [{ id: queue.rows[0]?.id, text: 'Question', attachments: [], missingAttachments: 1 }],+ hold: 'unconfirmed',+ })+ expect(await storage.getItem('project')).not.toContain('file:///')+ for (const scope of ['other-account', 'other-host', 'other-project']) {+ expect((await restarted.loadQueue(scope, 'task:1')).rows).toEqual([])+ }+ expect((await restarted.loadQueue('project', 'task:2')).rows).toEqual([])+ await restarted.clear(['project'])+ expect((await new DraftStore(storage).loadQueue('project', 'task:1')).rows).toEqual([])+ }+ )++ it('retains an in-flight batch until acknowledgment and removes only that batch', async () => {+ const storage = memoryStorage()+ const store = new DraftStore(storage)+ const first = queueReducer(EMPTY_QUEUE, queueActions.enqueue('First'))+ await store.saveQueue('project', 'new-chat', first, draft(''))+ await store.move('project', 'new-chat', 'task:1')+ expect((await store.loadQueue('project', 'new-chat')).rows).toEqual([])+ const held = queueReducer(first, queueActions.hold('unconfirmed'))+ await store.saveQueue('project', 'task:1', held)+ const later = queueReducer(held, queueActions.enqueue('Second'))+ await store.saveQueue('project', 'task:1', later)+ const confirmed = queueReducer(later, { type: 'delivered', ids: first.rows.map((row) => row.id) })+ await store.saveQueue('project', 'task:1', confirmed)+ expect((await new DraftStore(storage).loadQueue('project', 'task:1')).rows.map((row) => row.text)).toEqual([+ 'Second',+ ])+ })+ it('clears an in-flight queue write on sign-out and refuses saves queued before it', async () => {+ const storage = memoryStorage()+ let finish!: () => void+ const gate = new Promise<void>((resolve) => {+ finish = resolve+ })+ const write = storage.setItem+ storage.setItem = async (key, value) => {+ await gate+ await write(key, value)+ }+ const store = new DraftStore(storage)+ const queue = queueReducer(EMPTY_QUEUE, queueActions.enqueue('Private text'))+ const saving = store.saveQueue('project', 'task:1', queue)+ const waiting = store.saveQueue('project', 'task:2', queue).catch(() => undefined)+ const cleared = store.clear(['project'])+ finish()+ await Promise.all([saving.catch(() => undefined), waiting, cleared])+ const restarted = new DraftStore(storage)+ expect((await restarted.loadQueue('project', 'task:1')).rows).toEqual([])+ expect((await restarted.loadQueue('project', 'task:2')).rows).toEqual([])+ })+ it('refuses additional queued text before it can make saved queues unreadable', async () => {+ const storage = memoryStorage()+ const store = new DraftStore(storage)+ const first = queueReducer(EMPTY_QUEUE, queueActions.enqueue('First question'))+ await store.saveQueue('project', 'task:1', first)+ const before = await storage.getItem('project')+ const oversized = queueReducer(EMPTY_QUEUE, queueActions.enqueue('x'.repeat(128 * 1024)))+ await expect(store.saveQueue('project', 'task:2', oversized, draft(''))).rejects.toBeInstanceOf(+ DraftStorageLimitError+ )+ expect(await storage.getItem('project')).toBe(before)+ expect((await new DraftStore(storage).loadQueue('project', 'task:1')).rows[0]?.text).toBe('First question')+ await store.saveQueue('project', 'task:2', first)+ expect((await store.loadQueue('project', 'task:2')).rows).toHaveLength(1)+ })+ it('allows shrinking a preexisting oversized project without dropping remaining queues', async () => {+ const storage = memoryStorage()+ const rows = Object.fromEntries(+ ['one', 'two', 'three'].map((id) => [+ `task:${id}`,+ { draft: draft(''), queue: { rows: [{ id, text: 'x'.repeat(80_000), attachments: [] }], hold: null } },+ ])+ )+ await storage.setItem('project', JSON.stringify(rows))+ const store = new DraftStore(storage)+ await store.saveQueue('project', 'task:one', EMPTY_QUEUE)+ expect((await storage.getItem('project'))?.length).toBeGreaterThan(128 * 1024)+ expect((await store.loadQueue('project', 'task:two')).rows[0]?.text).toHaveLength(80_000)+ await store.saveQueue('project', 'task:two', EMPTY_QUEUE)+ expect((await store.loadQueue('project', 'task:three')).rows[0]?.text).toHaveLength(80_000)+ })++ it('does not retain a pending-send handle when its durable write exceeds the budget', async () => {+ const store = new DraftStore(memoryStorage())+ const queue = queueReducer(EMPTY_QUEUE, queueActions.enqueue('x'.repeat(100_000)))+ await store.saveQueue('project', 'task:queued', queue)+ await expect(store.beginSend('project', 'new-chat', draft('y'.repeat(40_000)))).rejects.toBeInstanceOf(+ DraftStorageLimitError+ )+ await store.save('project', 'new-chat', draft('Later'))+ expect(await store.load('project', 'new-chat')).toEqual(draft('Later'))+ const settle = await store.beginSend('project', 'new-chat', draft('Next'))+ await settle(true)+ expect(await store.load('project', 'new-chat')).toBeNull()+ expect((await store.loadQueue('project', 'task:queued')).rows[0]?.text).toHaveLength(100_000)+ })+ it('adopts an unchanged near-limit queue even when the task key is longer', async () => {+ const storage = memoryStorage()+ const store = new DraftStore(storage)+ const queued = queueReducer(EMPTY_QUEUE, queueActions.enqueue('Question'))+ await store.saveQueue('project', 'new-chat', queued)+ const overhead = (await storage.getItem('project'))?.length ?? 0+ const text = 'x'.repeat(128 * 1024 - overhead + 'Question'.length)+ const full = queueReducer(EMPTY_QUEUE, queueActions.enqueue(text))+ await store.saveQueue('project', 'new-chat', full)+ const task = 'task:00000000-0000-4000-8000-000000000001'+ await store.move('project', 'new-chat', task)+ expect((await store.loadQueue('project', 'new-chat')).rows).toEqual([])+ expect((await store.loadQueue('project', task)).rows[0]?.text).toBe(text)+ const larger = queueReducer(full, queueActions.enqueue('Additional text'))+ await expect(store.saveQueue('project', task, larger)).rejects.toBeInstanceOf(DraftStorageLimitError)+ expect((await store.loadQueue('project', task)).rows).toHaveLength(1)+ })})diff --git a/products/mobile/src/features/chat/draftStore.ts b/products/mobile/src/features/chat/draftStore.tsindex 2da7aff86e94..817d99e8fde3 100644--- a/products/mobile/src/features/chat/draftStore.ts+++ b/products/mobile/src/features/chat/draftStore.ts@@ -1,3 +1,5 @@+import { EMPTY_QUEUE, type QueueState } from './messageQueue'+export interface ChatDraft {text: stringreportIds: string[]@@ -10,6 +12,7 @@ export interface DraftStorage {}interface SavedDraft {+ queue?: QueueStatedraft: ChatDraftunsent?: ChatDraft}@@ -17,6 +20,14 @@ interface SavedDraft {type Drafts = Record<string, SavedDraft>const EMPTY: ChatDraft = { text: '', reportIds: [] }const LIMIT = 50+const MAX_PROJECT_CHARACTERS = 128 * 1024++export class DraftStorageLimitError extends Error {+ constructor() {+ super("Saved messages have reached this device's limit. Remove a queued message before saving more.")+ this.name = 'DraftStorageLimitError'+ }+}function parseDraft(value: unknown): ChatDraft {const record = value && typeof value === 'object' ? (value as Record<string, unknown>) : {}@@ -28,6 +39,22 @@ function parseDraft(value: unknown): ChatDraft {}}+function parseQueue(value: unknown): QueueState {+ if (!value || typeof value !== 'object' || !('rows' in value) || !Array.isArray(value.rows)) return EMPTY_QUEUE+ const rows: QueueState['rows'] = []+ for (const row of value.rows) {+ if (!row || typeof row !== 'object' || typeof row.id !== 'string' || typeof row.text !== 'string') continue+ rows.push({+ id: row.id,+ text: row.text,+ attachments: [],+ missingAttachments:+ Number.isSafeInteger(row.missingAttachments) && row.missingAttachments > 0 ? row.missingAttachments : 0,+ })+ }+ return { rows, hold: rows.length ? 'unconfirmed' : null }+}+function hasContent(draft: ChatDraft): boolean {return draft.text.trim().length > 0 || draft.reportIds.length > 0}@@ -54,8 +81,9 @@ export class DraftStore {}private async read(scope: string): Promise<Drafts> {+ const stored = await this.storage.getItem(scope)try {- const value: unknown = JSON.parse((await this.storage.getItem(scope)) ?? '{}')+ const value: unknown = JSON.parse(stored ?? '{}')if (!value || typeof value !== 'object' || Array.isArray(value)) {return {}}@@ -68,6 +96,7 @@ export class DraftStore {result[key] = {draft: parseDraft(saved.draft),...(saved.unsent ? { unsent: parseDraft(saved.unsent) } : {}),+ queue: parseQueue(saved.queue),}}return result@@ -76,17 +105,27 @@ export class DraftStore {}}- private async write(scope: string, key: string, saved: SavedDraft, drafts: Drafts): Promise<void> {+ private async write(+ scope: string,+ key: string,+ saved: SavedDraft,+ drafts: Drafts,+ maxCharacters: number = MAX_PROJECT_CHARACTERS+ ): Promise<void> {+ const previousSize = JSON.stringify(drafts).lengthdelete drafts[key]- if (hasContent(saved.draft) || saved.unsent) {+ if (hasContent(saved.draft) || saved.unsent || saved.queue?.rows.length) {drafts[key] = saved}const keys = Object.keys(drafts)for (const stale of keys.slice(0, Math.max(0, keys.length - LIMIT))) {- delete drafts[stale]+ if (!drafts[stale]?.queue?.rows.length) delete drafts[stale]}if (Object.keys(drafts).length) {- await this.storage.setItem(scope, JSON.stringify(drafts))+ const serialized = JSON.stringify(drafts)+ if (serialized.length > maxCharacters && serialized.length >= previousSize)+ throw new DraftStorageLimitError()+ await this.storage.setItem(scope, serialized)} else {await this.storage.removeItem(scope)}@@ -102,7 +141,7 @@ export class DraftStore {let draft = saved.draftif (saved.unsent && !this.pending.has(`${scope}:${key}`)) {draft = restoreUnsent(draft, saved.unsent)- await this.write(scope, key, { draft }, drafts)+ await this.write(scope, key, { ...saved, draft, unsent: undefined }, drafts)}return hasContent(draft) ? draft : null})@@ -115,7 +154,8 @@ export class DraftStore {return}const unsent = this.pending.get(`${scope}:${key}`)?.message- await this.write(scope, key, { draft, ...(unsent ? { unsent } : {}) }, await this.read(scope))+ const drafts = await this.read(scope)+ await this.write(scope, key, { ...drafts[key], draft, unsent }, drafts)})}@@ -126,8 +166,15 @@ export class DraftStore {if (generation !== this.generation) {return}- this.pending.set(`${scope}:${key}`, handle)- await this.write(scope, key, { draft: EMPTY, unsent: message }, await this.read(scope))+ const id = `${scope}:${key}`+ this.pending.set(id, handle)+ try {+ const drafts = await this.read(scope)+ await this.write(scope, key, { ...drafts[key], draft: EMPTY, unsent: message }, drafts)+ } catch (error) {+ if (this.pending.get(id) === handle) this.pending.delete(id)+ throw error+ }})return (sent) =>this.enqueue(async () => {@@ -142,10 +189,47 @@ export class DraftStore {this.pending.delete(id)const drafts = await this.read(scope)const typed = drafts[target]?.draft ?? EMPTY- await this.write(scope, target, { draft: sent ? typed : restoreUnsent(typed, message) }, drafts)+ await this.write(+ scope,+ target,+ { ...drafts[target], unsent: undefined, draft: sent ? typed : restoreUnsent(typed, message) },+ drafts+ )})}+ loadQueue(scope: string, key: string): Promise<QueueState> {+ return this.enqueue(async () => (await this.read(scope))[key]?.queue ?? EMPTY_QUEUE)+ }++ saveQueue(scope: string, key: string, queue: QueueState, draft?: ChatDraft): Promise<void> {+ const generation = this.generation+ // File handles cannot survive a restart. Store only a count, so recovery never sends a message without its files.+ const savedQueue: QueueState = {+ hold: queue.hold,+ rows: queue.rows.map(({ id, text, attachments, missingAttachments }) => ({+ id,+ text,+ attachments: [],+ missingAttachments: (missingAttachments ?? 0) + attachments.length,+ })),+ }+ return this.enqueue(async () => {+ if (generation !== this.generation) throw new Error('Session ended')+ const drafts = await this.read(scope)+ await this.write(+ scope,+ key,+ {+ ...drafts[key],+ draft: draft ?? drafts[key]?.draft ?? EMPTY,+ queue: savedQueue,+ },+ drafts+ )+ })+ }+move(scope: string, from: string, to: string): Promise<void> {const generation = this.generationreturn this.enqueue(async () => {@@ -154,6 +238,7 @@ export class DraftStore {}const drafts = await this.read(scope)const saved = drafts[from]+ const previousSize = JSON.stringify(drafts).lengthconst pending = this.pending.get(`${scope}:${from}`)this.pending.delete(`${scope}:${from}`)if (pending) {@@ -162,7 +247,8 @@ export class DraftStore {}delete drafts[from]if (saved) {- await this.write(scope, to, saved, drafts)+ const keyGrowth = Math.max(0, JSON.stringify(to).length - JSON.stringify(from).length)+ await this.write(scope, to, saved, drafts, Math.max(MAX_PROJECT_CHARACTERS, previousSize + keyGrowth))}})}diff --git a/products/mobile/src/features/chat/messageQueue.test.ts b/products/mobile/src/features/chat/messageQueue.test.tsindex 447c97d11dc4..02c51db00476 100644--- a/products/mobile/src/features/chat/messageQueue.test.ts+++ b/products/mobile/src/features/chat/messageQueue.test.ts@@ -1,3 +1,5 @@+import * as Crypto from 'expo-crypto'+import type { PendingAttachment } from './attachments/types'import {canDrain,@@ -22,6 +24,11 @@ function file(name: string): PendingAttachment {return { id: name, uri: `file:///picked/${name}`, name, size: 1, contentType: 'text/plain', isImage: false }}+let nextQueueId = 0+jest.spyOn(Crypto, 'randomUUID').mockImplementation(+ () => `00000000-0000-4000-8000-${String(++nextQueueId).padStart(12, '0')}`+)+describe('message queue', () => {test.each<[string, QueueAction[], QueueState['hold']]>([['a new message lifts a Stop hold', [queueActions.hold('cancelled'), queueActions.enqueue('b')], null],@@ -81,6 +88,24 @@ describe('message queue', () => {expect(shouldQueue(IDLE, held)).toBe(true)})+ test.each(['unconfirmed', 'cancelled'] as const)(+ 'acknowledgment preserves a %s hold only when Stop requires it',+ (hold) => {+ const first = apply(queueActions.enqueue('First'))+ const queued = queueReducer(queueReducer(first, queueActions.enqueue('Second')), queueActions.hold(hold))+ const confirmed = queueReducer(queued, { type: 'delivered', ids: first.rows.map((row) => row.id) })+ expect(confirmed.rows.map((row) => row.text)).toEqual(['Second'])+ expect(confirmed.hold).toBe(hold === 'cancelled' ? 'cancelled' : null)+ }+ )++ it('does not auto-send recovered text that is missing its files', () => {+ const queued = apply(queueActions.enqueue('With a file'))+ const row = queued.rows[0]+ if (!row) throw new Error('Expected queued row')+ expect(canDrain(IDLE, { ...queued, rows: [{ ...row, missingAttachments: 1 }] })).toBe(false)+ })+test.each<[string, Parameters<typeof sendNowState>[0], ReturnType<typeof sendNowState>]>([['a pending decision',diff --git a/products/mobile/src/features/chat/messageQueue.ts b/products/mobile/src/features/chat/messageQueue.tsindex c1188ac529d9..728ac3de98ed 100644--- a/products/mobile/src/features/chat/messageQueue.ts+++ b/products/mobile/src/features/chat/messageQueue.ts@@ -1,3 +1,5 @@+import { randomUUID } from 'expo-crypto'+import type { PendingAttachment } from './attachments/types'import type { SessionPhase } from './session/types'@@ -5,6 +7,7 @@ export interface QueuedMessage {id: stringtext: string/** The composer's files when the message was queued. They go with it, as on the web. */+ missingAttachments?: numberattachments: PendingAttachment[]}@@ -26,15 +29,14 @@ export type QueueAction =| { type: 'restore'; rows: QueuedMessage[] }| { type: 'hold'; reason: QueueHold }| { type: 'release' }+ | { type: 'delivered'; ids: string[] }export const EMPTY_QUEUE: QueueState = { rows: [], hold: null }-let lastId = 0-export const queueActions = {enqueue: (text: string, attachments: readonly PendingAttachment[] = []): QueueAction => ({type: 'enqueue',- id: `queued-${++lastId}`,+ id: `queued-${randomUUID()}`,text,attachments: [...attachments],}),@@ -58,6 +60,10 @@ export function queueReducer(state: QueueState, action: QueueAction): QueueStateconst rows = state.rows.filter((row) => row.id !== action.id)return { rows, hold: rows.length > 0 ? state.hold : null }}+ case 'delivered': {+ const rows = state.rows.filter((row) => !action.ids.includes(row.id))+ return { rows, hold: rows.length && state.hold === 'cancelled' ? 'cancelled' : null }+ }case 'clear':return EMPTY_QUEUEcase 'restore':@@ -94,7 +100,12 @@ export function shouldQueue(gate: SendGate, queue: QueueState): boolean {export function canDrain(gate: SendGate, queue: QueueState): boolean {return (- queue.rows.length > 0 && queue.hold === null && gate.phase === 'idle' && !gate.sending && !gate.decisionPending+ queue.rows.length > 0 &&+ !queue.rows.some((row) => row.missingAttachments) &&+ queue.hold === null &&+ gate.phase === 'idle' &&+ !gate.sending &&+ !gate.decisionPending)}diff --git a/products/mobile/src/features/chat/session/SessionDecisionPanel.tsx b/products/mobile/src/features/chat/session/SessionDecisionPanel.tsxindex 262895ea8c18..22b54e71d39e 100644--- a/products/mobile/src/features/chat/session/SessionDecisionPanel.tsx+++ b/products/mobile/src/features/chat/session/SessionDecisionPanel.tsx@@ -15,6 +15,8 @@ interface SessionDecisionPanelProps {notice: string | undefinedpending: booleanonAnswer: (input: DecisionAnswerInput) => void+ onRetryNotice?: () => void+ noticePending?: booleanonDismissNotice: () => void}@@ -24,6 +26,8 @@ export function SessionDecisionPanel({pending,onAnswer,onDismissNotice,+ onRetryNotice,+ noticePending,}: SessionDecisionPanelProps): ReactElement | null {const colors = useColors()const styles = useStyles()@@ -35,14 +39,27 @@ export function SessionDecisionPanel({{notice ? (<View style={styles.notice} testID="session-decision-notice"><Text style={styles.noticeText}>{notice}</Text>- <Pressable44- onPress={onDismissNotice}- accessibilityLabel="Dismiss"- style={styles.close}- hitSlop={10}- >- <CloseIcon size={iconSizes.inline} color={colors.orange} />- </Pressable44>+ {onRetryNotice ? (+ <Pressable44+ onPress={onRetryNotice}+ disabled={noticePending}+ accessibilityLabel="Retry saving draft"+ accessibilityState={{ disabled: noticePending, busy: noticePending }}+ style={styles.retry}+ testID="chat-draft-retry"+ >+ <Text style={styles.retryText}>{noticePending ? 'Saving…' : 'Retry save'}</Text>+ </Pressable44>+ ) : (+ <Pressable44+ onPress={onDismissNotice}+ accessibilityLabel="Dismiss"+ style={styles.close}+ hitSlop={10}+ >+ <CloseIcon size={iconSizes.inline} color={colors.orange} />+ </Pressable44>+ )}</View>) : null}{decision ? (@@ -75,6 +92,8 @@ const useStyles = createStyles(({ colors }) => ({color: colors.orange,flex: 1,},+ retry: { paddingHorizontal: 8 },+ retryText: { ...type.meta, color: colors.orange },close: {width: 24,height: 24,diff --git a/products/mobile/src/features/chat/useChatDraft.test.tsx b/products/mobile/src/features/chat/useChatDraft.test.tsxindex 4f20ceed6d91..264e35a7075e 100644--- a/products/mobile/src/features/chat/useChatDraft.test.tsx+++ b/products/mobile/src/features/chat/useChatDraft.test.tsx@@ -1,7 +1,10 @@import { act, renderHook, waitFor } from '@testing-library/react-native'+import { AppState } from 'react-native'const mockAuth = { signedIn: true, host: 'https://example.com', user: { uuid: 'user-1' }, projectId: 1 }let mockStorageUnavailable = false+let mockWriteGate: Promise<void> | undefined+let mockWriteFailure = falseconst mockValues = new Map<string, string>()jest.mock('@/auth/authStore', () => ({@@ -20,6 +23,8 @@ jest.mock('./draftPersistence', () => {chatDrafts: new DraftStore({getItem: async (key: string) => mockValues.get(key) ?? null,setItem: async (key: string, value: string) => {+ await mockWriteGate+ if (mockWriteFailure) throw new Error('Device full')mockValues.set(key, value)},removeItem: async (key: string) => {@@ -30,11 +35,14 @@ jest.mock('./draftPersistence', () => {})import { chatDrafts } from './draftPersistence'+import { canDrain, EMPTY_QUEUE, queueActions, queueReducer } from './messageQueue'import { useChatDraft } from './useChatDraft'beforeEach(async () => {mockAuth.projectId = 1mockStorageUnavailable = false+ mockWriteGate = undefined+ mockWriteFailure = falseawait chatDrafts.clear(['scope-1', 'scope-2'])mockValues.clear()})@@ -51,6 +59,60 @@ describe('chat draft persistence', () => {reopened.unmount()})+ it.each(['debounce', 'background', 'close'])(+ 'handles composer quota failures during %s without replacing saved queues',+ async (trigger) => {+ jest.useFakeTimers()+ const subscription = jest.mocked(AppState.addEventListener)+ const savedQueue = queueReducer(EMPTY_QUEUE, queueActions.enqueue('x'.repeat(120 * 1024)))+ await chatDrafts.saveQueue('scope-1', 'task:queued', savedQueue)+ const before = mockValues.get('scope-1')+ const hook = renderHook(() => useChatDraft('task-1', undefined))+ await waitFor(() => expect(hook.result.current.ready).toBe(true))+ const text = 'y'.repeat(10 * 1024)+ act(() => hook.result.current.change({ text, reportIds: [] }))+ await act(async () => {+ if (trigger === 'close') hook.unmount()+ else if (trigger === 'background') subscription.mock.calls.at(-1)?.[1]('background')+ else jest.advanceTimersByTime(400)+ await chatDrafts.loadQueue('scope-1', 'task:queued')+ })+ expect(mockValues.get('scope-1')).toBe(before)+ expect(await chatDrafts.load('scope-1', 'task:task-1')).toBeNull()+ if (trigger !== 'close') {+ expect(hook.result.current.draft.text).toBe(text)+ expect(hook.result.current.draftError).toContain('Draft not saved.')+ expect(hook.result.current.draftError).toContain('Remove a queued message')+ expect(hook.result.current.draftSaving).toBe(false)+ await act(async () => {+ await hook.result.current.retrySave()+ })+ expect(hook.result.current.draftError).toBeDefined()+ await chatDrafts.saveQueue('scope-1', 'task:queued', EMPTY_QUEUE)+ let finish!: () => void+ mockWriteGate = new Promise<void>((resolve) => {+ finish = resolve+ })+ let retry!: Promise<void>+ act(() => {+ retry = hook.result.current.retrySave()+ })+ expect(hook.result.current.draftSaving).toBe(true)+ expect(hook.result.current.draftError).toBeDefined()+ await act(async () => {+ finish()+ await retry+ })+ expect(hook.result.current.draftError).toBeUndefined()+ expect(hook.result.current.draftSaving).toBe(false)+ expect(hook.result.current.draft.text).toBe(text)+ expect((await chatDrafts.load('scope-1', 'task:task-1'))?.text).toBe(text)+ hook.unmount()+ }+ jest.useRealTimers()+ }+ )+it('keeps text typed while sending and follows task adoption without consuming the next new-chat slot', async () => {const hook = renderHook(({ taskId }: { taskId: string | null }) => useChatDraft(taskId, undefined), {initialProps: { taskId: null },@@ -156,4 +218,224 @@ describe('chat draft persistence', () => {expect(hook.result.current.draft.text).toBe('')hook.unmount()})+ it('commits queued text before clearing the composer and restores it held after reopening', async () => {+ const hook = renderHook(() => useChatDraft('task-1', undefined))+ await waitFor(() => expect(hook.result.current.ready).toBe(true))+ act(() => hook.result.current.change({ text: 'Keep this', reportIds: [] }))+ let finish!: () => void+ mockWriteGate = new Promise<void>((resolve) => {+ finish = resolve+ })+ let queued!: Promise<boolean>+ act(() => {+ queued = hook.result.current.updateQueue(queueActions.enqueue('Keep this'), true)+ })+ expect(hook.result.current.draft.text).toBe('Keep this')+ act(() => hook.result.current.change({ text: 'New typing', reportIds: [] }))+ await act(async () => {+ finish()+ await queued+ })+ expect(hook.result.current.draft.text).toBe('New typing')+ hook.unmount()+ const reopened = renderHook(() => useChatDraft('task-1', undefined))+ await waitFor(() => expect(reopened.result.current.ready).toBe(true))+ expect(reopened.result.current.queue).toMatchObject({ rows: [{ text: 'Keep this' }], hold: 'unconfirmed' })+ expect(reopened.result.current.draft.text).toBe('New typing')+ reopened.unmount()+ })++ it('keeps the composer when the queue write fails and allows an explicit retry', async () => {+ const hook = renderHook(() => useChatDraft('task-1', undefined))+ await waitFor(() => expect(hook.result.current.ready).toBe(true))+ act(() => hook.result.current.change({ text: 'Not saved', reportIds: [] }))+ mockWriteFailure = true+ await act(async () => {+ expect(await hook.result.current.updateQueue(queueActions.enqueue('Not saved'), true)).toBe(false)+ })+ expect(hook.result.current.draft.text).toBe('Not saved')+ expect(hook.result.current.queue.rows).toEqual([])+ expect(hook.result.current.queueError).toBeDefined()+ mockWriteFailure = false+ await act(async () => {+ expect(await hook.result.current.updateQueue(queueActions.enqueue('Not saved'), true)).toBe(true)+ })+ expect(hook.result.current.draft.text).toBe('')+ expect(hook.result.current.queue.rows).toHaveLength(1)+ hook.unmount()+ })++ it('does not hydrate a previous chat after switching destinations during a queue write', async () => {+ const hook = renderHook(({ taskId }: { taskId: string }) => useChatDraft(taskId, undefined), {+ initialProps: { taskId: 'task-1' },+ })+ await waitFor(() => expect(hook.result.current.ready).toBe(true))+ let finish!: () => void+ mockWriteGate = new Promise<void>((resolve) => {+ finish = resolve+ })+ let queued!: Promise<boolean>+ act(() => {+ queued = hook.result.current.updateQueue(queueActions.enqueue('First chat'), true)+ })+ hook.rerender({ taskId: 'task-2' })+ await act(async () => {+ finish()+ await queued+ })+ await waitFor(() => expect(hook.result.current.ready).toBe(true))+ expect(hook.result.current.queue.rows).toEqual([])+ hook.rerender({ taskId: 'task-1' })+ await waitFor(() => expect(hook.result.current.queue.rows).toHaveLength(1))+ expect(hook.result.current.queue.hold).toBe('unconfirmed')+ hook.unmount()+ })+ it.each(['settled', 'pending', 'adopting'])(+ 'keeps queued files live during task adoption, Stop=%s',+ async (timing) => {+ const pending = timing !== 'settled'+ const hook = renderHook(({ taskId }: { taskId: string | null }) => useChatDraft(taskId, undefined), {+ initialProps: { taskId: null },+ })+ await waitFor(() => expect(hook.result.current.ready).toBe(true))+ const file = {+ id: 'file-1',+ uri: 'file:///example',+ name: 'example.txt',+ size: 1,+ contentType: 'text/plain',+ isImage: false,+ }+ act(() => hook.result.current.change({ text: 'With a file', reportIds: [] }))+ let finish!: () => void+ if (pending)+ mockWriteGate = new Promise<void>((resolve) => {+ finish = resolve+ })+ let saving!: Promise<boolean>+ let stopped!: Promise<boolean>+ act(() => {+ saving = hook.result.current.updateQueue(queueActions.enqueue('With a file', [file]), true)+ if (timing !== 'adopting') stopped = hook.result.current.updateQueue(queueActions.hold('cancelled'))+ })+ if (!pending)+ await act(async () => {+ await saving+ await stopped+ })+ hook.rerender({ taskId: 'created-task' })+ if (timing === 'adopting')+ act(() => {+ stopped = hook.result.current.updateQueue(queueActions.hold('cancelled'))+ })+ await act(async () => {+ if (pending) finish()+ expect(await saving).toBe(true)+ expect(await stopped).toBe(true)+ })+ await waitFor(() => expect(hook.result.current.ready).toBe(true))+ expect(hook.result.current.draft.text).toBe('')+ expect(hook.result.current.queue.hold).toBe('cancelled')+ expect(hook.result.current.queue.rows[0]?.attachments).toEqual([file])+ expect(hook.result.current.queue.rows[0]?.missingAttachments).toBeUndefined()+ expect((await chatDrafts.loadQueue('scope-1', 'new-chat')).rows).toEqual([])+ hook.unmount()+ const reopened = renderHook(() => useChatDraft('created-task', undefined))+ await waitFor(() => expect(reopened.result.current.ready).toBe(true))+ expect(reopened.result.current.queue.rows[0]).toMatchObject({ attachments: [], missingAttachments: 1 })+ reopened.unmount()+ }+ )++ it('holds a queue even when Stop races its device write', async () => {+ const hook = renderHook(() => useChatDraft('task-1', undefined))+ await waitFor(() => expect(hook.result.current.ready).toBe(true))+ let finish!: () => void+ mockWriteGate = new Promise<void>((resolve) => {+ finish = resolve+ })+ let queued!: Promise<boolean>+ let stopped!: Promise<boolean>+ act(() => {+ queued = hook.result.current.updateQueue(queueActions.enqueue('Wait'), true)+ stopped = hook.result.current.updateQueue(queueActions.hold('cancelled'))+ })+ await act(async () => {+ finish()+ await queued+ await stopped+ })+ expect(hook.result.current.queue.hold).toBe('cancelled')+ hook.unmount()+ })+ it('keeps Stop in effect when its device write fails and the error is dismissed', async () => {+ const hook = renderHook(() => useChatDraft('task-1', undefined))+ await waitFor(() => expect(hook.result.current.ready).toBe(true))+ await act(async () => {+ await hook.result.current.updateQueue(queueActions.enqueue('Stay queued'), true)+ })+ mockWriteFailure = true+ await act(async () => {+ expect(await hook.result.current.updateQueue(queueActions.hold('cancelled'))).toBe(false)+ })+ expect(hook.result.current.queueError).toBeDefined()+ act(() => hook.result.current.dismissQueueError())+ expect(hook.result.current.queueError).toBeUndefined()+ expect(hook.result.current.queue.hold).toBe('cancelled')+ expect(canDrain({ phase: 'idle', sending: false, decisionPending: false }, hook.result.current.queue)).toBe(+ false+ )+ mockWriteFailure = false+ hook.unmount()+ })+ it.each([false, true])('does not duplicate a committed queue on close, newer typing=%s', async (newerTyping) => {+ const hook = renderHook(() => useChatDraft('task-1', undefined))+ await waitFor(() => expect(hook.result.current.ready).toBe(true))+ act(() => hook.result.current.change({ text: 'Queued question', reportIds: [] }))+ let finish!: () => void+ mockWriteGate = new Promise<void>((resolve) => {+ finish = resolve+ })+ let saving!: Promise<boolean>+ act(() => {+ saving = hook.result.current.updateQueue(queueActions.enqueue('Queued question'), true)+ })+ if (newerTyping) act(() => hook.result.current.change({ text: 'New question', reportIds: [] }))+ hook.unmount()+ await act(async () => {+ finish()+ await saving+ })+ const reopened = renderHook(() => useChatDraft('task-1', undefined))+ await waitFor(() => expect(reopened.result.current.ready).toBe(true))+ expect(reopened.result.current.queue.rows.map((row) => row.text)).toEqual(['Queued question'])+ expect(reopened.result.current.draft.text).toBe(newerTyping ? 'New question' : '')+ reopened.unmount()+ })+ it('keeps newer typing only in the adopted task after a queued write resolves', async () => {+ const hook = renderHook(({ taskId }: { taskId: string | null }) => useChatDraft(taskId, undefined), {+ initialProps: { taskId: null },+ })+ await waitFor(() => expect(hook.result.current.ready).toBe(true))+ act(() => hook.result.current.change({ text: 'Queued question', reportIds: [] }))+ let finish!: () => void+ mockWriteGate = new Promise<void>((resolve) => {+ finish = resolve+ })+ let saving!: Promise<boolean>+ act(() => {+ saving = hook.result.current.updateQueue(queueActions.enqueue('Queued question'), true)+ })+ act(() => hook.result.current.change({ text: 'New question', reportIds: [] }))+ hook.rerender({ taskId: 'adopted-task' })+ await act(async () => {+ finish()+ await saving+ })+ await waitFor(() => expect(hook.result.current.ready).toBe(true))+ expect(hook.result.current.draft.text).toBe('New question')+ expect((await chatDrafts.load('scope-1', 'task:adopted-task'))?.text).toBe('New question')+ expect(await chatDrafts.load('scope-1', 'new-chat')).toBeNull()+ hook.unmount()+ })})diff --git a/products/mobile/src/features/chat/useChatDraft.ts b/products/mobile/src/features/chat/useChatDraft.tsindex 50dab8acb55a..0d4098f86fcb 100644--- a/products/mobile/src/features/chat/useChatDraft.ts+++ b/products/mobile/src/features/chat/useChatDraft.ts@@ -5,7 +5,8 @@ import { useAuthStore } from '@/auth/authStore'import { track } from '@/lib/analytics'import { chatDrafts, draftIdentity, draftScope } from './draftPersistence'-import { type ChatDraft, restoreUnsent } from './draftStore'+import { type ChatDraft, DraftStorageLimitError, restoreUnsent } from './draftStore'+import { EMPTY_QUEUE, type QueueAction, type QueueState, queueReducer } from './messageQueue'interface DraftTarget {identity: string@@ -19,6 +20,14 @@ export function useChatDraft(demo = false): {draft: ChatDraft+ queue: QueueState+ queuePending: boolean+ queueError: string | undefined+ dismissQueueError: () => void+ updateQueue: (action: QueueAction, clearComposer?: boolean) => Promise<boolean>+ draftError: string | undefined+ draftSaving: boolean+ retrySave: () => Promise<void>ready: booleanchange: (draft: ChatDraft) => voidbeginSend: (message: ChatDraft) => Promise<(sent: boolean) => Promise<void>>@@ -31,22 +40,62 @@ export function useChatDraft(const key = taskId ? `task:${taskId}` : reportId ? `report:${reportId}` : 'new-chat'const initial = { text: '', reportIds: reportId ? [reportId] : [] }const [draft, setDraft] = useState<ChatDraft>(initial)+ const [queue, setQueue] = useState<QueueState>(EMPTY_QUEUE)+ const queueRef = useRef(queue)+ const queueBusy = useRef(false)+ const queueWrite = useRef<Promise<void>>(Promise.resolve())+ const queueClear = useRef<{ draft: ChatDraft; committed: boolean } | null>(null)+ const [queuePending, setQueuePending] = useState(false)+ const [queueError, setQueueError] = useState<string>()+ const [draftError, setDraftError] = useState<string>()+ const [draftSaving, setDraftSaving] = useState(false)+ const saveVersion = useRef(0)const latest = useRef(draft)const target = useRef<DraftTarget | null>(null)const [ready, setReady] = useState(false)const mounted = useRef(false)const destination = useRef(0)+ const previousDestination = useRef({ identity, key })const edited = useRef(false)const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null)- const flush = useCallback((): void => {+ const flush = useCallback(async (): Promise<void> => {if (saveTimer.current) {clearTimeout(saveTimer.current)saveTimer.current = null}const current = target.current- if (current && draftIdentity() === current.identity) {- void chatDrafts.save(current.scope, current.key, latest.current).catch(() => undefined)+ if (!current || draftIdentity() !== current.identity) return+ const typed = latest.current+ const pendingClear = queueClear.current+ const mine = destination.current+ const version = ++saveVersion.current+ const active = (): boolean =>+ mounted.current &&+ mine === destination.current &&+ target.current === current &&+ draftIdentity() === current.identity &&+ version === saveVersion.current+ if (active()) setDraftSaving(true)+ try {+ if (queueBusy.current) await queueWrite.current+ if (draftIdentity() !== current.identity) return+ const savedDraft =+ pendingClear?.committed && pendingClear.draft === typed+ ? { text: '', reportIds: typed.reportIds }+ : typed+ await chatDrafts.save(current.scope, current.key, savedDraft)+ if (active() && latest.current === typed) setDraftError(undefined)+ } catch (error) {+ if (active() && latest.current === typed) {+ setDraftError(+ error instanceof DraftStorageLimitError+ ? `Draft not saved. ${error.message}`+ : 'Draft not saved on this device. Retry before closing the chat.'+ )+ }+ } finally {+ if (active()) setDraftSaving(false)}}, [])@@ -66,7 +115,7 @@ export function useChatDraft(useEffect(() => {const subscription = AppState.addEventListener('change', (state) => {if (state !== 'active') {- flush()+ void flush()}})return () => subscription.remove()@@ -75,19 +124,30 @@ export function useChatDraft(useEffect(() => {let cancelled = falsemounted.current = true- destination.current++setReady(false)+ setQueueError(undefined)const previous = target.current- const adopting = previous?.identity === identity && !previous.key.startsWith('task:') && key.startsWith('task:')+ const prior = previousDestination.current+ const adopting = prior.identity === identity && !prior.key.startsWith('task:') && key.startsWith('task:')+ previousDestination.current = { identity, key }if (!adopting) {+ destination.current+++ queueBusy.current = false+ setQueuePending(false)+ setDraftError(undefined)+ setDraftSaving(false)edited.current = falselatest.current = { text: '', reportIds: reportId ? [reportId] : [] }setDraft(latest.current)+ queueRef.current = EMPTY_QUEUE+ setQueue(EMPTY_QUEUE)}- target.current = null+ if (!adopting) target.current = nullif (!identity) {setReady(true)- return undefined+ return () => {+ mounted.current = false+ }}void (async () => {const scope = await draftScope(identity)@@ -95,18 +155,33 @@ export function useChatDraft(return}if (adopting && previous) {- await chatDrafts.move(scope, previous.key, key)+ while (queueBusy.current) await queueWrite.current+ if (cancelled || draftIdentity() !== identity) return+ const source = previous.key+ previous.key = key+ await chatDrafts.move(scope, source, key)}const saved = await chatDrafts.load(scope, key)+ const savedQueue = await chatDrafts.loadQueue(scope, key)if (cancelled || draftIdentity() !== identity) {return}if (adopting && previous) {- previous.key = keytarget.current = previous} else {target.current = { identity, scope, key }}+ const restored = adopting+ ? {+ ...savedQueue,+ hold: queueRef.current.hold,+ rows: savedQueue.rows.map(+ (row) => queueRef.current.rows.find((live) => live.id === row.id) ?? row+ ),+ }+ : savedQueue+ queueRef.current = restored+ setQueue(restored)if (!edited.current && saved) {latest.current = savedsetDraft(saved)@@ -117,21 +192,88 @@ export function useChatDraft(})}} else if (edited.current) {- await chatDrafts.save(scope, key, latest.current)+ await flush()}setReady(true)})().catch(() => {if (!cancelled) {+ setQueueError("Couldn't load saved messages. Close and reopen this chat to try again.")setReady(true)}})return () => {- flush()+ void flush()mounted.current = falsecancelled = true}}, [identity, key, reportId, flush])+ const updateQueue = useCallback(+ async (action: QueueAction, clearComposer = false): Promise<boolean> => {+ const current = target.current+ const mine = destination.current+ if (queueBusy.current && (action.type === 'enqueue' || action.type === 'remove')) return false+ while (queueBusy.current) await queueWrite.current+ if (mine !== destination.current) return false+ if (+ (!ready && !(action.type === 'hold' && current)) ||+ (identity && (!current || draftIdentity() !== current.identity))+ ) {+ if (mine === destination.current && mounted.current)+ setQueueError("Couldn't load saved messages. Close and reopen this chat to try again.")+ return false+ }+ queueBusy.current = true+ let finish!: () => void+ queueWrite.current = new Promise<void>((resolve) => {+ finish = resolve+ })+ setQueuePending(true)+ setQueueError(undefined)+ const next = queueReducer(queueRef.current, action)+ if (action.type === 'hold') {+ queueRef.current = next+ setQueue(next)+ }+ const typed = latest.current+ const cleared = { text: '', reportIds: typed.reportIds }+ const clearing = clearComposer ? { draft: typed, committed: false } : null+ queueClear.current = clearing+ try {+ if (current)+ await chatDrafts.saveQueue(current.scope, current.key, next, clearComposer ? cleared : undefined)+ if (clearing) clearing.committed = true+ if (+ mine !== destination.current ||+ (current && draftIdentity() !== current.identity) ||+ !mounted.current+ )+ return false+ queueRef.current = next+ setQueue(next)+ if (clearComposer && latest.current === typed) change(cleared)+ return true+ } catch (error) {+ if (mine === destination.current && mounted.current) {+ setQueueError(+ error instanceof DraftStorageLimitError+ ? error.message+ : "Couldn't save queued messages on this device. Try again before closing the chat."+ )+ }+ return false+ } finally {+ if (queueClear.current === clearing) queueClear.current = null+ finish()+ if (mine === destination.current) {+ queueBusy.current = false+ setQueuePending(false)+ }+ }+ },+ [change, identity, ready]+ )+const beginSend = useCallback(async (message: ChatDraft): Promise<(sent: boolean) => Promise<void>> => {const current = target.current@@ -161,5 +303,19 @@ export function useChatDraft([change])- return { draft, ready, change, beginSend }+ const dismissQueueError = useCallback((): void => setQueueError(undefined), [])+ return {+ draft,+ ready,+ change,+ beginSend,+ queue,+ queuePending,+ queueError,+ dismissQueueError,+ updateQueue,+ draftError,+ draftSaving,+ retrySave: flush,+ }}