From 603922ecd3316de7074548e85993fe56ff12b7ca Mon Sep 17 00:00:00 2001 From: ZQR1101 <2970159221@qq.com> Date: Wed, 25 Nov 2026 02:09:46 +0800 Subject: [PATCH] fix(mobile): close the recovery gaps found in review Runtime: - refuse a send while the transcript is loading or failed to load; the answer would otherwise be written against history the learner cannot see - reuse the client submission id when a start was never confirmed, so a retry hits the server's submission reservation instead of running the question twice - apply a persisted record only to the conversation it was written for, so opening another conversation cannot borrow its outcome banner - re-arm the idle watchdog when a stop request is unconfirmed; the run is still the server's - restore the last conversation silently when no turn was in flight, and forget a remembered conversation the server reports as gone Data: - normalise message row ids to strings: SQLite returns a rowid and PocketBase a record id, and parseInt collapsed every key to 0 on the latter - fall back to a positional render key when a transcript row carries no id List and navigation: - let refresh and retry supersede a stale page fetch instead of being dropped - report a deleted conversation and refresh the index instead of staying silent - disable rename and delete while a conversation is opening --- apps/mobile/__tests__/chat-recovery.test.ts | 164 +++++++++++++++++- apps/mobile/__tests__/chat-screen.test.tsx | 22 +++ apps/mobile/__tests__/session-api.test.ts | 28 ++- apps/mobile/__tests__/session-history.test.ts | 15 +- apps/mobile/app/sessions.tsx | 19 +- .../src/features/chat/MobileChatRuntime.ts | 124 +++++++++++-- apps/mobile/src/features/sessions/history.ts | 15 +- .../src/features/sessions/useSessionList.ts | 4 +- apps/mobile/src/screens/ChatScreen.tsx | 6 +- apps/mobile/src/screens/SessionsScreen.tsx | 2 + apps/mobile/src/services/sessionApi.ts | 16 +- 11 files changed, 374 insertions(+), 41 deletions(-) diff --git a/apps/mobile/__tests__/chat-recovery.test.ts b/apps/mobile/__tests__/chat-recovery.test.ts index bdc0d1d67..806acc311 100644 --- a/apps/mobile/__tests__/chat-recovery.test.ts +++ b/apps/mobile/__tests__/chat-recovery.test.ts @@ -11,6 +11,7 @@ import type { SessionMessage, } from '../src/services/sessionApi'; import type { + LastSessionStore, RecoveryRecord, TurnRecoveryStore, } from '../src/storage/turnRecovery'; @@ -63,11 +64,17 @@ function streamEvent( } function message( - id: number, + id: number | string, role: SessionMessage['role'], content: string, ): SessionMessage { - return { id, role, content, createdAt: id, failedTurn: null }; + return { + id: String(id), + role, + content, + createdAt: typeof id === 'number' ? id : 0, + failedTurn: null, + }; } function detail(overrides: Partial = {}): SessionDetail { @@ -128,7 +135,10 @@ const record: RecoveryRecord = { function harness( api: Partial, recovery: TurnRecoveryStore | null, - options: { onAuthExpired?: () => void } = {}, + options: { + onAuthExpired?: () => void; + lastSession?: LastSessionStore; + } = {}, ) { const sockets: FakeSocket[] = []; const runtime = new MobileChatRuntime({ @@ -140,14 +150,29 @@ function harness( }, sessionApi: api as SessionApi, recovery: recovery ?? undefined, + lastSession: options.lastSession, scope: recovery ? { origin: 'https://tutor.example.test', account: 'acct-1', workspace: '' } : null, - ...options, + onAuthExpired: options.onAuthExpired, }); return { runtime, sockets }; } +function lastSessionStore(initial: string | null) { + let current = initial; + const store = { + read: jest.fn(async () => current), + write: jest.fn(async (_scope: unknown, sessionId: string) => { + current = sessionId; + }), + clear: jest.fn(async () => { + current = null; + }), + }; + return { store: store as unknown as LastSessionStore, calls: store, peek: () => current }; +} + async function settle() { for (let i = 0; i < 12; i += 1) await Promise.resolve(); } @@ -399,3 +424,134 @@ test('reopening the same conversation keeps one transcript', async () => { expect(get).toHaveBeenCalledTimes(2); runtime.stop(); }); + +test('a relaunch quietly reopens the conversation that was open last', async () => { + const memory = memoryStore(null); + const last = lastSessionStore('session-1'); + const get = jest.fn(async () => + detail({ + status: 'completed', + messages: [ + message(1, 'user', 'What is a half?'), + message(2, 'assistant', 'One of two equal parts.'), + ], + }), + ); + const { runtime } = harness({ get }, memory.store, { lastSession: last.store }); + + runtime.start(); + await settle(); + + expect(get).toHaveBeenCalledWith('session-1'); + expect(runtime.getSnapshot()).toMatchObject({ + sessionId: 'session-1', + sessionTitle: 'Fractions', + status: 'completed', + history: 'ready', + // Nothing was running, so there is nothing to announce. + recovery: null, + error: null, + }); + runtime.stop(); +}); + +test('a remembered conversation the server dropped is forgotten silently', async () => { + const memory = memoryStore(null); + const last = lastSessionStore('session-1'); + const get = jest.fn(async () => { + throw new ApiError('http', 'The server returned HTTP 404.', 404); + }); + const { runtime } = harness({ get }, memory.store, { lastSession: last.store }); + + runtime.start(); + await settle(); + + expect(runtime.getSnapshot()).toMatchObject({ + sessionId: null, + messages: [], + history: 'idle', + status: 'idle', + recovery: null, + error: null, + }); + expect(last.calls.clear).toHaveBeenCalled(); + expect(last.peek()).toBeNull(); + runtime.stop(); +}); + +test('a recovery record cannot decorate a conversation opened instead', async () => { + const memory = memoryStore(record); + let release: (value: SessionDetail) => void = () => {}; + const get = jest + .fn, [string]>() + .mockImplementationOnce( + () => + new Promise(resolve => { + release = resolve; + }), + ) + .mockImplementationOnce(async () => + detail({ + id: 'session-2', + title: 'Decimals', + status: 'completed', + messages: [ + message(3, 'user', 'And decimals?'), + message(4, 'assistant', 'They are fractions too.'), + ], + }), + ); + const { runtime } = harness({ get }, memory.store); + runtime.start(); + await settle(); + + await runtime.openSession('session-2'); + // The abandoned load for the recorded conversation must not land either. + release(detail({ activeTurns: [live()] })); + await settle(); + + expect(runtime.getSnapshot()).toMatchObject({ + sessionId: 'session-2', + sessionTitle: 'Decimals', + status: 'completed', + // No "finished while you were away" banner: that record was for session-1. + recovery: null, + }); + runtime.stop(); +}); + +test('retrying an unconfirmed start reuses its submission id', () => { + const memory = memoryStore(null); + const { runtime, sockets } = harness({}, memory.store); + runtime.start(); + const first = sockets.at(-1)!; + first.open(); + + expect(runtime.send('Explain halves')).toBe(true); + const submitted = first.sent.find(frame => frame.type === 'start_turn'); + const submissionId = submitted?.client_submission_id; + expect(typeof submissionId).toBe('string'); + + // The server never confirmed; the runtime gives up and reconnects. + jest.advanceTimersByTime(30_000); + expect(runtime.getSnapshot().status).toBe('failed'); + + const retrySocket = sockets.at(-1)!; + expect(retrySocket).not.toBe(first); + retrySocket.open(); + + // Same question: the server can recognise the retry and must not run it twice. + expect(runtime.send('Explain halves')).toBe(true); + const retried = retrySocket.sent.filter(frame => frame.type === 'start_turn'); + expect(retried).toHaveLength(1); + expect(retried[0].client_submission_id).toBe(submissionId); + + // Once a turn is admitted the id is spent, so a new question is a new submit. + retrySocket.frame(streamEvent('content', 1, { content: 'Half of one.' })); + retrySocket.frame(streamEvent('done', 2)); + expect(runtime.send('Now quarters')).toBe(true); + const later = retrySocket.sent.filter(frame => frame.type === 'start_turn'); + expect(later).toHaveLength(2); + expect(later[1].client_submission_id).not.toBe(submissionId); + runtime.stop(); +}); diff --git a/apps/mobile/__tests__/chat-screen.test.tsx b/apps/mobile/__tests__/chat-screen.test.tsx index e20d430e0..0d93ae52e 100644 --- a/apps/mobile/__tests__/chat-screen.test.tsx +++ b/apps/mobile/__tests__/chat-screen.test.tsx @@ -140,6 +140,28 @@ test('a failed transcript load can be retried', () => { expect(retrySession).toHaveBeenCalledTimes(1); }); +test('a transcript that failed to load does not accept a question', () => { + const send = jest.fn(() => true); + render( + , + ); + fireEvent.changeText( + screen.getByPlaceholderText('Ask a question'), + 'What about quarters?', + ); + const submit = button('Send'); + expect(submit.props.accessibilityState?.disabled).toBe(true); + fireEvent.press(submit); + expect(send).not.toHaveBeenCalled(); +}); + test('a failed turn keeps its question and shows the failure', () => { render( { + const { api: sessions } = api( + response(200, { + ...row, + // PocketBase hands out record strings, SQLite an integer rowid, and a + // row without either must still be addressable. + messages: [ + { id: 'a1b2c3d4e5f6g7h', role: 'user', content: 'Hi' }, + { id: 42, role: 'assistant', content: 'Hello' }, + { role: 'user', content: 'No id' }, + ], + active_turns: [], + }), + ); + const detail = await sessions.get('s1'); + expect(detail.messages.map(message => message.id)).toEqual([ + 'a1b2c3d4e5f6g7h', + '42', + '', + ]); +}); + test('lists a page and reports whether another page exists', async () => { const { api: sessions, fetcher } = api( response(200, { sessions: [row] }), @@ -107,15 +129,15 @@ test('reads a transcript with its failed-turn metadata and active turns', async ); const detail = await sessions.get('s1'); expect(detail.messages).toEqual([ - { id: 1, role: 'user', content: 'Hi', createdAt: 1, failedTurn: null }, + { id: '1', role: 'user', content: 'Hi', createdAt: 1, failedTurn: null }, { - id: 2, + id: '2', role: 'user', content: 'Retry me', createdAt: 2, failedTurn: { turnId: 'turn-3', error: 'Provider down', retryable: true }, }, - { id: 3, role: 'assistant', content: 'Hello', createdAt: 3, failedTurn: null }, + { id: '3', role: 'assistant', content: 'Hello', createdAt: 3, failedTurn: null }, ]); expect(detail.activeTurns).toEqual([ { diff --git a/apps/mobile/__tests__/session-history.test.ts b/apps/mobile/__tests__/session-history.test.ts index dd2b83a9f..26fcb555a 100644 --- a/apps/mobile/__tests__/session-history.test.ts +++ b/apps/mobile/__tests__/session-history.test.ts @@ -5,16 +5,16 @@ import type { } from '../src/services/sessionApi'; function message( - id: number, + id: number | string, role: SessionMessage['role'], content: string, failedTurn?: { turn_id: string; error: string; retryable: boolean }, ): SessionMessage { return { - id, + id: String(id), role, content, - createdAt: id, + createdAt: typeof id === 'number' ? id : 0, failedTurn: failedTurn ? { turnId: failedTurn.turn_id, @@ -130,3 +130,12 @@ test('a turn still in the active set is resumable', () => { test('an unknown conversation has nothing to resume', () => { expect(resolveTurn(null, 'turn-1')).toEqual({ kind: 'missing' }); }); + +test('a transcript without ids still gets one key per exchange', () => { + const exchanges = toExchanges([ + message('', 'user', 'What is a third?'), + message('', 'assistant', 'One of three equal parts.'), + message('', 'user', 'And a quarter?'), + ]); + expect(exchanges.map(exchange => exchange.id)).toEqual(['m#0', 'm#2']); +}); diff --git a/apps/mobile/app/sessions.tsx b/apps/mobile/app/sessions.tsx index e0a67f21d..3f1ec4ab1 100644 --- a/apps/mobile/app/sessions.tsx +++ b/apps/mobile/app/sessions.tsx @@ -17,6 +17,7 @@ export default function SessionsRoute() { [session.origin], ); const list = useSessionList(api, undefined); + const refreshList = list.refresh; const [busySessionId, setBusySessionId] = useState(null); const [openError, setOpenError] = useState(null); @@ -31,17 +32,23 @@ export default function SessionsRoute() { // failure still moves to the chat screen so its retry is reachable. if (chat.getSnapshot().sessionId === sessionId) { router.replace('/chat'); - } else { - setOpenError( - chat.getSnapshot().error ?? - 'Could not open this conversation on the server.', - ); + return; } + const snapshot = chat.getSnapshot(); + const gone = snapshot.recovery?.kind === 'unavailable'; + setOpenError( + gone + ? snapshot.recovery?.message ?? + 'This conversation no longer exists on the server.' + : snapshot.error ?? 'Could not open this conversation on the server.', + ); + // A conversation the server no longer has must not linger in the index. + if (gone) refreshList(); } finally { setBusySessionId(null); } }, - [busySessionId, chat, router], + [busySessionId, chat, refreshList, router], ); const newChat = useCallback(() => { diff --git a/apps/mobile/src/features/chat/MobileChatRuntime.ts b/apps/mobile/src/features/chat/MobileChatRuntime.ts index a7e9ab870..1ffe77f3b 100644 --- a/apps/mobile/src/features/chat/MobileChatRuntime.ts +++ b/apps/mobile/src/features/chat/MobileChatRuntime.ts @@ -26,6 +26,7 @@ import type { TurnStatus, } from '../../services/sessionApi'; import type { + LastSessionStore, RecoveryRecord, RecoveryScope, TurnRecoveryStore, @@ -79,12 +80,16 @@ type ChatOptions = { /** Conversation history transport; absent in unit tests that only drive WS. */ sessionApi?: SessionApi; recovery?: TurnRecoveryStore; + /** Remembers the conversation to reopen on a later launch. */ + lastSession?: LastSessionStore; /** Null disables persistence entirely (nothing is written without an account). */ scope?: RecoveryScope | null; }; type ActiveTurn = { messageId: string; + /** The id sent as `client_submission_id`; the server dedupes on it. */ + submissionId: string; turnId: string | null; replying: boolean; cancelRequested: boolean; @@ -176,6 +181,12 @@ export class MobileChatRuntime { private epoch = 0; /** Record read on cold start, consumed by the transcript load it triggered. */ private pendingRecord: RecoveryRecord | null = null; + /** + * The last start command the server never confirmed. Reusing its id keeps a + * retry idempotent server-side: `start_turn` returns the turn it already + * reserved instead of running the question twice. + */ + private unconfirmedSubmission: { id: string; text: string } | null = null; private authProbe: Promise | undefined; private nextAuthProbeAt = 0; @@ -250,11 +261,19 @@ export class MobileChatRuntime { * about. A conversation the server no longer has is reported as such instead * of being shown as a run that is still going. */ - openSession = async (sessionId: string): Promise => { + openSession = (sessionId: string): Promise => + this.load(sessionId, false); + + private load = async ( + sessionId: string, + silent: boolean, + ): Promise => { if (this.active) { - this.update({ - error: 'Stop the current response before switching conversations.', - }); + if (!silent) { + this.update({ + error: 'Stop the current response before switching conversations.', + }); + } return false; } const api = this.options.sessionApi; @@ -281,7 +300,7 @@ export class MobileChatRuntime { return true; } catch (error) { if (epoch !== this.epoch) return false; - this.failLoad(error); + this.failLoad(error, silent); return false; } }; @@ -302,15 +321,28 @@ export class MobileChatRuntime { this.clearStartTimeout(); this.clearReplayRetry(); this.sessionId = null; + this.unconfirmedSubmission = null; this.retiredTurnIds.clear(); this.closeTransport(); this.update(initialState()); this.openTransport(); this.clearPersisted(); + this.forgetSession(); }; dismissRecovery = () => this.update({ recovery: null }); + /** + * A send needs a transcript the app can append to. Posting while it is still + * loading would write into messages the server copy is about to replace; + * posting after it failed to load would answer with history nobody can see. + * A conversation this runtime created over the socket has no transcript load + * at all (`idle`), which is a fine state to post from. + */ + private canPost(): boolean { + return this.state.history === 'idle' || this.state.history === 'ready'; + } + send = (text: string): boolean => { const question = text.trim(); if ( @@ -318,15 +350,21 @@ export class MobileChatRuntime { this.active || this.client?.state !== 'connected' || !isComposing(this.state.status) || - // Posting before the transcript lands would write into a conversation - // whose messages are about to be replaced by the server's copy. - this.state.history === 'loading' + !this.canPost() ) { return false; } const messageId = newCommandId(); + // Resending the same question after an unconfirmed start reuses the id the + // server may already have reserved, so the retry cannot run it twice. + const submissionId = + this.unconfirmedSubmission?.text === question + ? this.unconfirmedSubmission.id + : newCommandId(); + this.unconfirmedSubmission = { id: submissionId, text: question }; const active: ActiveTurn = { messageId, + submissionId, turnId: null, replying: false, cancelRequested: false, @@ -360,12 +398,14 @@ export class MobileChatRuntime { buildStartTurn({ capability: 'chat', content: question, - client_submission_id: messageId, + client_submission_id: submissionId, ...(this.sessionId ? { session_id: this.sessionId } : {}), }), ); return true; } catch { + // Nothing reached the transport, so there is no reservation to reuse. + this.unconfirmedSubmission = null; this.finishTurn( 'failed', 'Unable to send this message. Check your connection.', @@ -435,8 +475,12 @@ export class MobileChatRuntime { /** Adopt a server transcript, resuming it only if the server says it is live. */ private applyDetail(detail: SessionDetail) { - const record = this.pendingRecord; + // A record only describes the conversation it was written for. + const record = + this.pendingRecord?.sessionId === detail.id ? this.pendingRecord : null; this.pendingRecord = null; + // The server's transcript settles whether anything is still pending. + this.unconfirmedSubmission = null; const messages = toExchanges(detail.messages); const resolved = resolveTurn(detail, record?.turnId ?? ''); const title = detail.title || ''; @@ -461,6 +505,7 @@ export class MobileChatRuntime { } const active: ActiveTurn = { messageId, + submissionId: record?.clientSubmissionId ?? '', turnId: turn.id, replying: false, cancelRequested: false, @@ -484,6 +529,7 @@ export class MobileChatRuntime { }); // seq 0 makes the server replay the whole turn so the answer rebuilds // from its own log; the persisted sequence is kept for diagnostics only. + this.rememberSession(detail.id); this.client?.setResumeCursor(turn.id, 0); this.client?.manualRetry(); this.watchTurn(active); @@ -507,11 +553,20 @@ export class MobileChatRuntime { } : null, }); + this.rememberSession(detail.id); this.clearPersisted(); } - private failLoad(error: unknown) { + private failLoad(error: unknown, silent = false) { const api = error instanceof ApiError ? error : null; + if (api?.status === 404 && silent) { + // A remembered conversation that is now gone is not an incident: forget + // it and open a fresh chat rather than announcing a deletion. + this.sessionId = null; + this.update(initialState()); + this.forgetSession(); + return; + } if (api?.status === 404) { // The conversation is gone on the server. Say so and fall back to a new // chat instead of leaving a dead transcript on screen. @@ -553,18 +608,31 @@ export class MobileChatRuntime { } private async restore() { - const { recovery, scope, sessionApi } = this.options; - if (!recovery || !scope || !sessionApi || this.active) return; + const { recovery, lastSession, scope, sessionApi } = this.options; + if (!scope || !sessionApi || this.active) return; let record: RecoveryRecord | null = null; try { - record = await recovery.read(scope); + record = recovery ? await recovery.read(scope) : null; } catch { + record = null; + } + if (this.active) return; + if (record) { + this.pendingRecord = record; + const opened = await this.load(record.sessionId, false); + if (!opened) this.pendingRecord = null; return; } - if (!record || this.active) return; - this.pendingRecord = record; - const opened = await this.openSession(record.sessionId); - if (!opened) this.pendingRecord = null; + // Nothing was running: reopen the conversation the learner was reading, + // quietly, so a relaunch does not look like the history was lost. + let last: string | null = null; + try { + last = (await lastSession?.read(scope)) ?? null; + } catch { + last = null; + } + if (!last || this.active) return; + await this.load(last, true); } private persist(force = false) { @@ -588,7 +656,7 @@ export class MobileChatRuntime { version: 1, sessionId, turnId: active.turnId, - clientSubmissionId: active.messageId, + clientSubmissionId: active.submissionId || active.messageId, lastSeq: this.client?.cursor.afterSeq ?? 0, status, updatedAt: now, @@ -596,6 +664,18 @@ export class MobileChatRuntime { recovery.write(scope, record).catch(() => {}); } + private rememberSession(sessionId: string) { + const { lastSession, scope } = this.options; + if (!lastSession || !scope) return; + lastSession.write(scope, sessionId).catch(() => {}); + } + + private forgetSession() { + const { lastSession, scope } = this.options; + if (!lastSession || !scope) return; + lastSession.clear(scope).catch(() => {}); + } + private clearPersisted() { const { recovery, scope } = this.options; if (!recovery || !scope) return Promise.resolve(); @@ -633,6 +713,9 @@ export class MobileChatRuntime { error: 'Could not confirm the stop request. Try Stop again.', canLeaveTurn: true, }); + // The run is still the server's; keep the idle watchdog armed so a + // connection that died during the stop still recovers. + this.watchTurn(active); } } @@ -805,6 +888,8 @@ export class MobileChatRuntime { return; if (!active.turnId) { active.turnId = event.turn_id; + // Admitted: the id is spent and must not be reused for a later question. + this.unconfirmedSubmission = null; this.clearStartTimeout(); } if (event.session_id) this.sessionId = event.session_id; @@ -821,6 +906,7 @@ export class MobileChatRuntime { } if (this.state.sessionId !== this.sessionId) { this.update({ sessionId: this.sessionId }); + if (this.sessionId) this.rememberSession(this.sessionId); } switch (event.type) { case 'content': diff --git a/apps/mobile/src/features/sessions/history.ts b/apps/mobile/src/features/sessions/history.ts index 8a185130f..62bd1b2da 100644 --- a/apps/mobile/src/features/sessions/history.ts +++ b/apps/mobile/src/features/sessions/history.ts @@ -18,17 +18,28 @@ export interface ChatExchange { const DEFAULT_FAILURE = 'This response did not finish.'; +/** + * A stable render key per row. The server normally supplies one; when it does + * not, the position in the transcript is the only thing left, and a positional + * key is still better than every row collapsing onto the same one. + */ +function keyOf(message: SessionMessage, index: number): string { + return message.id ? `m${message.id}` : `m#${index}`; +} + export function toExchanges(messages: readonly SessionMessage[]): ChatExchange[] { const exchanges: ChatExchange[] = []; // The row a later assistant message may still attach to. Only the newest // user row can own a reply, so a stale cursor is never reused. let open: ChatExchange | null = null; + let index = -1; for (const message of messages) { + index += 1; if (message.role === 'system') continue; if (message.role === 'user') { const exchange: ChatExchange = { - id: `m${message.id}`, + id: keyOf(message, index), question: message.content, answer: '', failed: message.failedTurn @@ -47,7 +58,7 @@ export function toExchanges(messages: readonly SessionMessage[]): ChatExchange[] continue; } exchanges.push({ - id: `m${message.id}`, + id: keyOf(message, index), question: '', answer: message.content, failed: null, diff --git a/apps/mobile/src/features/sessions/useSessionList.ts b/apps/mobile/src/features/sessions/useSessionList.ts index d248cc79c..d53e8a33d 100644 --- a/apps/mobile/src/features/sessions/useSessionList.ts +++ b/apps/mobile/src/features/sessions/useSessionList.ts @@ -84,7 +84,9 @@ export function useSessionList( async (mode: 'initial' | 'refresh' | 'more') => { const sessionApi = apiRef.current; if (!sessionApi) return; - if (busy.current) return; + // A newer first page or refresh supersedes an older page fetch; only a + // second "load more" is dropped, so one offset is never requested twice. + if (busy.current && mode === 'more') return; if (mode === 'more' && !hasMore.current) return; busy.current = true; inFlight.current?.abort(); diff --git a/apps/mobile/src/screens/ChatScreen.tsx b/apps/mobile/src/screens/ChatScreen.tsx index 40d6163ec..acb5e03f0 100644 --- a/apps/mobile/src/screens/ChatScreen.tsx +++ b/apps/mobile/src/screens/ChatScreen.tsx @@ -105,10 +105,14 @@ export function ChatScreen({ // reply — but starting a different chat would abandon it. const composing = isComposingStatus(status) || awaitingInput; const canStartNewChat = isComposingStatus(status); + // The transcript has to be in hand before a question is appended to it: a + // conversation still loading, or one that failed to load, would otherwise + // answer with history the learner cannot see. + const transcriptReady = history === 'idle' || history === 'ready'; const canSubmit = composing && connection === 'connected' && - history !== 'loading' && + transcriptReady && !replying && !!draft.trim(); const progress = progressCopy(status); diff --git a/apps/mobile/src/screens/SessionsScreen.tsx b/apps/mobile/src/screens/SessionsScreen.tsx index 0f09f6709..86ac44193 100644 --- a/apps/mobile/src/screens/SessionsScreen.tsx +++ b/apps/mobile/src/screens/SessionsScreen.tsx @@ -258,11 +258,13 @@ export function SessionsScreen({ openRename(item)} /> confirmDelete(item)} /> diff --git a/apps/mobile/src/services/sessionApi.ts b/apps/mobile/src/services/sessionApi.ts index 9a63f8a08..119c9e397 100644 --- a/apps/mobile/src/services/sessionApi.ts +++ b/apps/mobile/src/services/sessionApi.ts @@ -25,7 +25,12 @@ export interface FailedTurnInfo { } export interface SessionMessage { - id: number; + /** + * The store's row id. SQLite returns an integer rowid and PocketBase a record + * string, so it is normalised to a string; an empty value means the payload + * carried none and the caller must fall back to a positional key. + */ + id: string; role: 'user' | 'assistant' | 'system'; content: string; createdAt: number; @@ -97,6 +102,13 @@ function count(value: unknown): number { return typeof value === 'number' && Number.isFinite(value) ? value : 0; } +/** Row ids arrive as a SQLite integer or a PocketBase record id. */ +function rowId(value: unknown): string { + if (typeof value === 'string') return value; + if (typeof value === 'number' && Number.isFinite(value)) return String(value); + return ''; +} + function turnStatus(value: unknown): TurnStatus { return TURN_STATUSES.find(status => status === value) ?? 'idle'; } @@ -121,7 +133,7 @@ function parseMessage(value: unknown): SessionMessage { } const metadata = raw.metadata ? record(raw.metadata, 'message metadata') : {}; return { - id: count(raw.id), + id: rowId(raw.id), role, content: text(raw.content), createdAt: count(raw.created_at),