The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
feat(mobile): restore chats from the automatic backup, with a hint in the chat list
purplec8bf0943aee8
diff --git a/src/lib/store-backup.ts b/src/lib/store-backup.tsindex aac15859..633ab1ab 100644--- a/src/lib/store-backup.ts+++ b/src/lib/store-backup.ts@@ -84,6 +84,10 @@ export const STORE_KEYS = [// lu-mobile-unload-in-background model settings: free the model in the background'lu-mobile-theme', 'lu-mobile-settings-prefs', 'lu-mobile-remote-desktops','lu-mobile-resume-seen', 'lu-mobile-download-wifi-only', 'lu-mobile-unload-in-background',+ // C46 (3.1.0): the chats deleted on the phone (mobile/lib/chat-rescue.ts).+ // The chat archives of the backup keep them; after a lost storage this note+ // keeps the restore hint from offering them back.+ 'lu-mobile-chats-deleted',// Round 3 (M8). Found missing by the review: the text of the backup says// "chats and settings", and these did not come back.// lu-mobile-remote the chats held with a paired desktop, ondiff --git a/src/mobile/boot/__tests__/settings-durable.test.ts b/src/mobile/boot/__tests__/settings-durable.test.tsindex 993644d2..2e52d9a3 100644--- a/src/mobile/boot/__tests__/settings-durable.test.ts+++ b/src/mobile/boot/__tests__/settings-durable.test.ts@@ -113,6 +113,7 @@ describe('which keys are kept', () => {'LU-create-orders': 'the orders of Create in chat, which is locked on the phone until it has the order card','lu-mobile-switched-under-answer': 'a note per answer; lost, the chat says "interrupted" instead of "you switched models"','lu-mobile-settings-stamp': 'the stamp of this copy itself; in the native backup it dates the settings there (L5)',+ 'lu-mobile-chats-deleted': 'chats deleted on the phone (C46); lost, the restore hint offers them once and Not now keeps it away',}for (const key of STORE_KEYS) {const copied = DURABLE_SETTINGS_KEYS.includes(key)diff --git a/src/mobile/lib/__tests__/chat-rescue.test.ts b/src/mobile/lib/__tests__/chat-rescue.test.tsnew file mode 100644index 00000000..4ed3a0ac--- /dev/null+++ b/src/mobile/lib/__tests__/chat-rescue.test.ts@@ -0,0 +1,187 @@+// @vitest-environment jsdom+/**+ * C46 (3.1.0): restore chats from the automatic backup on the phone, and the+ * hint in the chat list. The backup files are what `chat_backup_conversations`+ * hands back: every chat of the live backup, the ring, prev.json and the chat+ * archives, one entry per id.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import type { Conversation } from '../../../types/chat'++const world = vi.hoisted(() => ({+ backup: [] as unknown[],+ readFails: false,+ written: true,+ hydrated: true,+ onHydrated: [] as (() => void)[],+}))++vi.mock('../../../api/backend', () => ({+ isTauri: () => true,+ backendCall: async (cmd: string) => {+ if (cmd !== 'chat_backup_conversations') return null+ if (world.readFails) throw new Error('backup unreadable')+ return JSON.stringify(world.backup)+ },+}))+vi.mock('../../boot/restore', () => ({ restoreDecided: Promise.resolve() }))+vi.mock('../../screens/settings/parts/durable', () => ({ chatsAreWritten: async () => world.written }))+vi.mock('../../../stores/chatStore', async () => {+ const { create } = await import('zustand')+ const store = create<{ conversations: Conversation[]; importConversations: (chats: Conversation[], mode: 'merge') => { added: number; skipped: number } }>((set, get) => ({+ conversations: [],+ importConversations: (chats) => {+ const have = new Set(get().conversations.map((c) => c.id))+ const fresh = chats.filter((c) => !have.has(c.id))+ set({ conversations: [...fresh, ...get().conversations] })+ return { added: fresh.length, skipped: chats.length - fresh.length }+ },+ }))+ Object.assign(store, {+ persist: {+ hasHydrated: () => world.hydrated,+ onFinishHydration: (fn: () => void) => void world.onHydrated.push(fn),+ },+ })+ return { useChatStore: store }+})++const chat = (id: string, updatedAt = 1): Conversation =>+ ({ id, title: id, messages: [{ id: `${id}-m`, role: 'user', content: 'hi', timestamp: updatedAt }], createdAt: updatedAt, updatedAt }) as unknown as Conversation++async function load() {+ const rescue = await import('../chat-rescue')+ const hint = await import('../../screens/chat/parts/adapters/chat-rescue-hint')+ const { useChatStore } = await import('../../../stores/chatStore')+ useChatStore.setState({ conversations: [] })+ return { rescue, hint, useChatStore }+}++beforeEach(() => {+ vi.resetModules()+ localStorage.clear()+ world.backup = []+ world.readFails = false+ world.written = true+ world.hydrated = true+ world.onHydrated = []+})++afterEach(() => {+ vi.useRealTimers()+})++describe('the note of chats deleted on this phone', () => {+ it('sees which ids left and which came back, and nothing while an answer streams', async () => {+ const { rescue } = await load()+ const a = chat('a'), b = chat('b'), c = chat('c')+ expect(rescue.chatIdsChanged([a, b], [{ ...a }, { ...b }])).toEqual({ gone: [], back: [] })+ expect(rescue.chatIdsChanged([a, b, c], [a, c])).toEqual({ gone: ['b'], back: [] })+ expect(rescue.chatIdsChanged([a], [b, a])).toEqual({ gone: [], back: ['b'] })+ })++ it('keeps the newest ids and forgets a chat that came back', async () => {+ const { rescue } = await load()+ rescue.noteChatsLeft(['a', 'b'], [])+ rescue.noteChatsLeft([], ['a'])+ expect([...rescue.readDeletedChats()]).toEqual(['b'])+ rescue.noteChatsLeft(Array.from({ length: rescue.DELETED_CHATS_MAX + 10 }, (_, i) => `x${i}`), [])+ const kept = [...rescue.readDeletedChats()]+ expect(kept).toHaveLength(rescue.DELETED_CHATS_MAX)+ expect(kept.at(-1)).toBe(`x${rescue.DELETED_CHATS_MAX + 9}`)+ expect(kept).not.toContain('b')+ })++ it('starts after hydration: what hydration did not bring is the loss, not a deletion', async () => {+ world.hydrated = false+ const { rescue, useChatStore } = await load()+ rescue.installDeletionNote()+ // The store is still the empty start value; hydration brings one chat. Nothing is noted for that.+ useChatStore.setState({ conversations: [chat('kept')] })+ world.onHydrated.forEach((fn) => fn())+ expect([...rescue.readDeletedChats()]).toEqual([])+ // From here on a chat that leaves the list was deleted.+ useChatStore.setState({ conversations: [] })+ expect([...rescue.readDeletedChats()]).toEqual(['kept'])+ rescue.__resetDeletionNoteForTests()+ })+})++describe('restore from the automatic backup', () => {+ it('offers the chats the list lost, not the ones deleted here, and adds each once', async () => {+ const { rescue, useChatStore } = await load()+ useChatStore.setState({ conversations: [chat('new-after-loss', 9)] })+ world.backup = [chat('lost-1'), chat('lost-2'), chat('deleted'), chat('new-after-loss', 9)]+ rescue.noteChatsLeft(['deleted'], [])+ expect((await rescue.restorableChats()).map((c) => c.id)).toEqual(['lost-1', 'lost-2'])+ expect(await rescue.restoreChatsFromPhoneBackup()).toEqual(['lost-1', 'lost-2'])+ expect(useChatStore.getState().conversations.map((c) => c.id).sort()).toEqual(['lost-1', 'lost-2', 'new-after-loss'])+ // A second run adds nothing.+ expect(await rescue.restoreChatsFromPhoneBackup()).toEqual([])+ })+})++describe('the hint in the chat list', () => {+ it('shows when the backup holds more chats than the list, once per start', async () => {+ const { hint, useChatStore } = await load()+ useChatStore.setState({ conversations: [chat('one-new')] })+ world.backup = [chat('l1'), chat('l2'), chat('l3')]+ await hint.lookForRescue(async () => {})+ expect(hint.useRescueHint.getState().count).toBe(3)+ // A second look in the same start reads nothing again.+ world.backup = []+ await hint.lookForRescue(async () => {})+ expect(hint.useRescueHint.getState().count).toBe(3)+ })++ it('stays away for chats deleted on this phone ("Delete all chats" is not offered back)', async () => {+ const { rescue, hint } = await load()+ world.backup = [chat('a'), chat('b')]+ rescue.noteChatsLeft(['a', 'b'], [])+ await hint.lookForRescue(async () => {})+ expect(hint.useRescueHint.getState().count).toBe(0)+ })++ it('Restore brings them back and says so only once they are written', async () => {+ const { hint, useChatStore } = await load()+ world.backup = [chat('l1'), chat('l2')]+ await hint.lookForRescue(async () => {})+ expect(await hint.restoreFromHint()).toEqual({ outcome: 'restored', added: 2 })+ expect(useChatStore.getState().conversations).toHaveLength(2)+ expect(hint.useRescueHint.getState()).toMatchObject({ count: 0, busy: false })+ })++ it('a write the phone refused is not "restored"', async () => {+ const { hint } = await load()+ world.backup = [chat('l1')]+ world.written = false+ await hint.lookForRescue(async () => {})+ expect(await hint.restoreFromHint()).toEqual({ outcome: 'not-saved', added: 1 })+ })++ it('Not now keeps it away until the backup holds more', async () => {+ const { hint } = await load()+ world.backup = [chat('l1'), chat('l2')]+ await hint.lookForRescue(async () => {})+ hint.dismissRescueHint()+ expect(hint.useRescueHint.getState().count).toBe(0)+ // The next start, same backup: no hint.+ vi.resetModules()+ const again = (await load()).hint+ await again.lookForRescue(async () => {})+ expect(again.useRescueHint.getState().count).toBe(0)+ // One more chat in the backup: it comes back.+ vi.resetModules()+ world.backup = [chat('l1'), chat('l2'), chat('l3')]+ const more = (await load()).hint+ await more.lookForRescue(async () => {})+ expect(more.useRescueHint.getState().count).toBe(3)+ })++ it('a backup that cannot be read shows no hint and breaks nothing', async () => {+ const { hint } = await load()+ world.readFails = true+ await hint.lookForRescue(async () => {})+ expect(hint.useRescueHint.getState().count).toBe(0)+ })+})diff --git a/src/mobile/lib/chat-rescue.ts b/src/mobile/lib/chat-rescue.tsnew file mode 100644index 00000000..8b75e6ab--- /dev/null+++ b/src/mobile/lib/chat-rescue.ts@@ -0,0 +1,114 @@+/**+ * Restore chats from the automatic backup, on the phone (C46, 3.1.0).+ *+ * The desktop got this in 3.0.10 (lib/chat-rescue.ts, perrt 05.11.2026): when+ * the chat list loses chats, the native backup keeps the previous copy as an+ * archive (`backup_stores`, store_backup.chats-*.json), and+ * `chat_backup_conversations` hands back every chat the backup files hold.+ * Both run on the phone as they are. What the phone lacked was a way back:+ * the button on the backup page and the hint in the chat list use this module.+ *+ * One thing differs from the desktop. The archive keeps every chat that left+ * the list, also the ones the user deleted. A hint that offers "Delete all+ * chats" back at the next start is wrong, so the phone notes the chats that+ * leave the list while the app runs (`installDeletionNote`). Those are+ * deliberate: a chat that is lost the way perrt's were never leaves a running+ * list, it is missing when the store comes up. The noted ones are not offered+ * again, neither by the hint nor by the button; a backup file picked by hand+ * still brings them back.+ */+import { chatsMissingFrom, readBackupChats } from '../../lib/chat-rescue'+import { useChatStore } from '../../stores/chatStore'+import type { Conversation } from '../../types/chat'++/** The ids of chats that left the list while the app ran, newest last. */+export const DELETED_CHATS_KEY = 'lu-mobile-chats-deleted'+/** More would only grow the value: a chat deleted that long ago is no longer in the ring or the archives. */+export const DELETED_CHATS_MAX = 500++type Store = Pick<Storage, 'getItem' | 'setItem'> | null++function storage(): Store {+ try {+ return typeof localStorage !== 'undefined' ? localStorage : null+ } catch {+ return null+ }+}++export function readDeletedChats(store: Store = storage()): Set<string> {+ try {+ const list: unknown = JSON.parse(store?.getItem(DELETED_CHATS_KEY) ?? '[]')+ return new Set(Array.isArray(list) ? list.filter((id): id is string => typeof id === 'string') : [])+ } catch {+ return new Set()+ }+}++/** Notes the ids that left and forgets the ones that came back, keeping the newest DELETED_CHATS_MAX. */+export function noteChatsLeft(gone: readonly string[], back: readonly string[], store: Store = storage()): void {+ if (!store || (gone.length === 0 && back.length === 0)) return+ const returned = new Set(back)+ const list = [...readDeletedChats(store)].filter((id) => !returned.has(id) && !gone.includes(id))+ list.push(...gone.filter((id) => !returned.has(id)))+ try {+ store.setItem(DELETED_CHATS_KEY, JSON.stringify(list.slice(-DELETED_CHATS_MAX)))+ } catch {+ /* a full storage: the hint may offer a deleted chat once, the user dismisses it */+ }+}++/** Pure: the ids of `next` that `prev` did not have, and the other way round. */+export function chatIdsChanged(prev: readonly Conversation[], next: readonly Conversation[]): { gone: string[]; back: string[] } {+ // Every token of an answer makes a new list with the same chats in the same order: no sets for that.+ if (prev.length === next.length && prev.every((c, i) => c.id === next[i].id)) return { gone: [], back: [] }+ const before = new Set(prev.map((c) => c.id))+ const after = new Set(next.map((c) => c.id))+ return { gone: [...before].filter((id) => !after.has(id)), back: [...after].filter((id) => !before.has(id)) }+}++let deletionNoteInstalled = false+let stopDeletionNote: () => void = () => {}++/**+ * From the moment the chat store has hydrated, every chat that leaves the+ * list is noted as deleted on purpose. Before that the list is the empty+ * start value, and what hydration does not bring is exactly the loss this+ * module is for.+ */+export function installDeletionNote(): void {+ if (deletionNoteInstalled) return+ deletionNoteInstalled = true+ const start = () => {+ let prev = useChatStore.getState().conversations+ stopDeletionNote = useChatStore.subscribe((state) => {+ if (state.conversations === prev) return+ const { gone, back } = chatIdsChanged(prev, state.conversations)+ prev = state.conversations+ noteChatsLeft(gone, back)+ })+ }+ if (useChatStore.persist.hasHydrated()) start()+ else useChatStore.persist.onFinishHydration(() => start())+}++/** The chats the backup files hold that are not in the list and were not deleted here on purpose. */+export async function restorableChats(): Promise<Conversation[]> {+ const deleted = readDeletedChats()+ return chatsMissingFrom(useChatStore.getState().conversations, await readBackupChats()).filter((c) => !deleted.has(c.id))+}++/** Adds them to the list. Returns their ids, so the caller can wait until they are written. */+export async function restoreChatsFromPhoneBackup(): Promise<string[]> {+ const missing = await restorableChats()+ if (missing.length === 0) return []+ useChatStore.getState().importConversations(missing, 'merge')+ return missing.map((c) => c.id)+}++/** Only for tests. */+export function __resetDeletionNoteForTests(): void {+ stopDeletionNote()+ stopDeletionNote = () => {}+ deletionNoteInstalled = false+}diff --git a/src/mobile/screens/chat/ChatsPage.tsx b/src/mobile/screens/chat/ChatsPage.tsxindex 290e9cc8..d3b2ef62 100644--- a/src/mobile/screens/chat/ChatsPage.tsx+++ b/src/mobile/screens/chat/ChatsPage.tsx@@ -15,12 +15,14 @@ import { useModelStore } from '../../../stores/modelStore'import { nav, useChatsSegment } from '../../nav'import { CHAT_STRINGS } from '../../strings/chat'import { useFootScrolls } from '../../ui/screen-shape'-import { Button, EmptyState, ErrorState, Field, IconButton, ListGroup, RootPage, Row, Segmented, SkeletonRows, Sparse } from '../../ui'+import { Button, EmptyState, ErrorState, Field, IconButton, ListGroup, Notice, RootPage, Row, Segmented, SkeletonRows, Sparse, toast } from '../../ui'import { RemoteHome } from '../remote/RemoteHome'import { remoteDesktopOffered } from '../../policy/gates'import { CloudSwitch } from '../settings/cloud/CloudSwitch'import { useChatsUnreadable } from '../../lib/storage-alerts'import { useBackupFound } from './parts/adapters/backup-found'+import { dismissRescueHint, lookForRescue, restoreFromHint, useRescueHint } from './parts/adapters/chat-rescue-hint'+import { installDeletionNote } from '../../lib/chat-rescue'import './parts/chat.css'import { chatModelLabel } from './parts/model-name'import { useChatsHydrated } from './parts/hooks'@@ -38,6 +40,8 @@ installChatPreload()// The catalogue of the phone knows which of its models think (parts/model-name.ts).installCatalogueFacts()installThinkingDefault()+// A chat that leaves the list from here on was deleted on purpose: the restore from the backup does not offer it (C46).+installDeletionNote()function ChatRow(props: { chat: Conversation; answering: boolean; model: string; now: number }) {@@ -106,7 +110,18 @@ export default function ChatsPage() {const shown = useMemo(() => matchChats(chats, deferredQuery), [chats, deferredQuery])// Not read is not empty: no "no chats yet", no restore offer, no new chat that could not be saved (F11).const unreadable = useChatsUnreadable()- const backupFound = useBackupFound(hydrated && chats.length === 0 && !unreadable)+ const rescue = useRescueHint()+ useEffect(() => {+ void lookForRescue()+ }, [])+ const showRescue = segment === 'phone' && hydrated && !unreadable && rescue.count > 0+ // The hint carries the restore itself; the quiet link of the empty list would be a second way to the same.+ const backupFound = useBackupFound(hydrated && chats.length === 0 && !unreadable) && !showRescue+ const restoreRescue = async () => {+ const { outcome, added } = await restoreFromHint()+ if (outcome === 'restored') toast(S.rescueDone(added), { testid: 'm-chats-rescue-done' })+ else toast(outcome === 'not-saved' ? S.rescueNotSaved : S.rescueFailed, { tone: 'error', testid: 'm-chats-rescue-error' })+ }const newChat = () => nav.push('/chat/:id', { id: 'new' })const searching = query.trim().length > 0// On a page too low for a fixed footer (a phone on its side) "New chat" stands at the end of the list; the@@ -230,6 +245,24 @@ export default function ChatsPage() {<Field label={S.search} hideLabel placeholder={S.search} type="search" icon={Search} clearable value={query} onChange={setQuery} testid="m-chats-search" el="C1.3" />) : null}</div>+ {showRescue ? (+ <Notice+ title={S.rescueTitle(rescue.count)}+ testid="m-chats-rescue"+ actions={+ <>+ <Button compact variant="primary" busy={rescue.busy} onPress={() => void restoreRescue()} testid="m-chats-rescue-restore">+ {S.rescueRestore}+ </Button>+ <Button compact variant="quiet" onPress={dismissRescueHint} testid="m-chats-rescue-dismiss">+ {S.rescueNotNow}+ </Button>+ </>+ }+ >+ {S.rescueText(rescue.count)}+ </Notice>+ ) : null}{segment === 'phone' ? list : <RemoteHome />}{segment === 'phone' && searching && shown.length > 0 ? <span className="m-sr" role="status">{`${shown.length}`}</span> : null}</RootPage>diff --git a/src/mobile/screens/chat/parts/adapters/chat-rescue-hint.ts b/src/mobile/screens/chat/parts/adapters/chat-rescue-hint.tsnew file mode 100644index 00000000..a8a906b7--- /dev/null+++ b/src/mobile/screens/chat/parts/adapters/chat-rescue-hint.ts@@ -0,0 +1,85 @@+/**+ * The hint in the chat list (C46, 3.1.0): the automatic backup holds chats+ * the list does not. Same rule as the desktop (lib/chat-rescue.ts,+ * shouldShowRescueHint): more chats in the backup than in the list, or an+ * empty list, and not dismissed at this count. It only says so; the chats+ * come back when the user taps Restore.+ *+ * Asked once per start, after the restore at the start has decided (it may+ * reload the page), because it reads every backup file natively.+ */+import { create } from 'zustand'+import { isTauri } from '../../../../../api/backend'+import { readDismissedAt, rememberDismissed, shouldShowRescueHint } from '../../../../../lib/chat-rescue'+import { useChatStore } from '../../../../../stores/chatStore'+import { restoreDecided } from '../../../../boot/restore'+import { restorableChats, restoreChatsFromPhoneBackup } from '../../../../lib/chat-rescue'+import { chatsAreWritten } from '../../../settings/parts/durable'++/** After the first page is up and the backup loop had its first turn. */+export const LOOK_AFTER_MS = 1500++export type RescueOutcome = 'restored' | 'not-saved' | 'failed'++interface RescueHintState {+ /** Chats the hint offers. 0: no hint. */+ count: number+ busy: boolean+}++export const useRescueHint = create<RescueHintState>(() => ({ count: 0, busy: false }))++function local(): Pick<Storage, 'getItem' | 'setItem'> | null {+ try {+ return typeof localStorage !== 'undefined' ? localStorage : null+ } catch {+ return null+ }+}++let looked: Promise<void> | null = null++/** Looks once per start. Later calls return the same look. */+export function lookForRescue(wait: (ms: number) => Promise<void> = (ms) => new Promise((r) => setTimeout(r, ms))): Promise<void> {+ if (!isTauri()) return Promise.resolve()+ looked ??= (async () => {+ await restoreDecided+ await new Promise<void>((resolve) => {+ if (useChatStore.persist.hasHydrated()) resolve()+ else useChatStore.persist.onFinishHydration(() => resolve())+ })+ await wait(LOOK_AFTER_MS)+ const restorable = (await restorableChats()).length+ if (shouldShowRescueHint(useChatStore.getState().conversations.length, restorable, readDismissedAt(local()))) useRescueHint.setState({ count: restorable })+ })().catch(() => {+ /* no hint is the behaviour before C46 */+ })+ return looked+}++/** Restore from the hint. "Restored" only once the chats are in the storage of the phone. */+export async function restoreFromHint(): Promise<{ outcome: RescueOutcome; added: number }> {+ useRescueHint.setState({ busy: true })+ try {+ const ids = await restoreChatsFromPhoneBackup()+ const written = ids.length === 0 || (await chatsAreWritten({ present: ids }))+ useRescueHint.setState({ count: 0 })+ return { outcome: written ? 'restored' : 'not-saved', added: ids.length }+ } catch {+ return { outcome: 'failed', added: 0 }+ } finally {+ useRescueHint.setState({ busy: false })+ }+}++/** "Not now": the hint comes back only when the backup holds more chats than now. */+export function dismissRescueHint(): void {+ rememberDismissed(local(), useRescueHint.getState().count)+ useRescueHint.setState({ count: 0 })+}++/** Only for tests. */+export function __resetRescueHintForTests(): void {+ looked = null+ useRescueHint.setState({ count: 0, busy: false })+}diff --git a/src/mobile/screens/settings/DataPage.tsx b/src/mobile/screens/settings/DataPage.tsxindex f8f0ce34..e8fdd663 100644--- a/src/mobile/screens/settings/DataPage.tsx+++ b/src/mobile/screens/settings/DataPage.tsx@@ -5,11 +5,12 @@* the import from other chat apps, the automatic backup in the app folder,* and deleting every chat behind two questions.*/-import { useState, useSyncExternalStore } from 'react'-import { DatabaseBackup, FileDown, FileUp, Import, Save, Trash2 } from 'lucide-react'+import { useEffect, useState, useSyncExternalStore } from 'react'+import { ArchiveRestore, DatabaseBackup, FileDown, FileUp, Import, Save, Trash2 } from 'lucide-react'import { portableConversation, serializeAllConversations } from '../../../lib/chat-export'import { backupStoresNow, lastStoreBackupAt, onStoreBackupWritten } from '../../../lib/store-backup'import { useChatStore } from '../../../stores/chatStore'+import { restorableChats, restoreChatsFromPhoneBackup } from '../../lib/chat-rescue'import type { Conversation } from '../../../types/chat'import { nav } from '../../nav'import { hasNativeBridge, isNativeUnavailable, pickFiles, saveToDevice, shareFile } from '../../platform'@@ -49,6 +50,20 @@ export default function DataPage() {const [restore, setRestore] = useState<Restore>({ kind: 'idle' })const [backingUp, setBackingUp] = useState(false)const [deleting, setDeleting] = useState(false)+ /** Chats of the automatic backup that are not in the list (C46). null: still looking; 'unreadable': the backup could not be read. */+ const [inBackup, setInBackup] = useState<number | 'unreadable' | null>(hasNativeBridge() ? null : 0)+ const [rescuing, setRescuing] = useState(false)++ const lookInBackup = async () => {+ try {+ setInBackup((await restorableChats()).length)+ } catch {+ setInBackup('unreadable')+ }+ }+ useEffect(() => {+ if (hasNativeBridge()) void lookInBackup()+ }, [count])/*** One file with every chat, out of the app in one of two ways: into a folder@@ -130,6 +145,23 @@ export default function DataPage() {toast(T.restoreDone(added, skipped), { testid: 'restore-done' })}+ /** Every chat of the automatic backup that is not in the list, "restored" only once it is written. */+ const rescue = async () => {+ if (rescuing) return+ setRescuing(true)+ try {+ const ids = await restoreChatsFromPhoneBackup()+ const written = ids.length === 0 || (await chatsAreWritten({ present: ids }))+ if (written) toast(T.rescueDone(ids.length), { testid: 'rescue-done' })+ else toast(T.restoreNotSaved, { tone: 'error', testid: 'rescue-not-saved' })+ } catch {+ toast(T.rescueUnreadable, { tone: 'error', testid: 'rescue-unreadable' })+ } finally {+ setRescuing(false)+ void lookInBackup()+ }+ }+const backupNow = async () => {if (backingUp) returnsetBackingUp(true)@@ -257,6 +289,22 @@ export default function DataPage() {testid="m-settings-data-auto"el="E16.4"/>+ {hasNativeBridge() ? (+ <Row+ icon={ArchiveRestore}+ title={T.rescue}+ subtitle={+ rescuing ? T.rescueWorking : inBackup === null ? T.rescueLooking : inBackup === 'unreadable' ? T.rescueUnreadable : inBackup > 0 ? T.rescueFound(inBackup) : T.rescueNone+ }+ chevron={false}+ disabled={rescuing || inBackup === null || inBackup === 'unreadable' || inBackup === 0}+ disabledReason={inBackup === 0 ? T.rescueNone : inBackup === 'unreadable' ? T.rescueUnreadable : T.rescueLooking}+ onPress={() => void rescue()}+ testid="m-settings-data-rescue"+ state={typeof inBackup === 'number' ? `found-${inBackup}` : inBackup === null ? 'looking' : inBackup}+ el="E16.4"+ />+ ) : null}</ListGroup><Block><Hint>{T.autoText}</Hint>diff --git a/src/mobile/strings/chat.ts b/src/mobile/strings/chat.tsindex cdafffa0..b2875c07 100644--- a/src/mobile/strings/chat.ts+++ b/src/mobile/strings/chat.ts@@ -29,6 +29,15 @@ export const CHAT_STRINGS = {noMessages: 'No messages yet',untitled: 'New chat',restore: 'Restore from backup',+ // The automatic backup holds chats the list does not (C46). Said, never done by itself.+ rescueTitle: (n: number) => `${n} ${n === 1 ? 'chat' : 'chats'} in your backup`,+ rescueText: (n: number) =>+ `The automatic backup on this phone holds ${n === 1 ? 'a chat that is' : `${n} chats that are`} not in your list. Restore ${n === 1 ? 'it' : 'them'}? The chats in your list stay as they are.`,+ rescueRestore: 'Restore',+ rescueNotNow: 'Not now',+ rescueDone: (n: number) => `${n} ${n === 1 ? 'chat' : 'chats'} restored`,+ rescueNotSaved: 'The chats are in your list, but they could not be saved on this phone. Free some storage, then restore them again in Settings, Backup and import.',+ rescueFailed: 'The backup could not be read.',// The stored chats could not be read at the start. They are not gone, and the list never says "no chats" then (F11).unreadableTitle: 'Your chats could not be read',unreadableNoSpace: 'LU cannot open your saved chats right now. This happens when the phone is out of storage. Your chats are still on this phone and are not changed. Free up space, then try again.',diff --git a/src/mobile/strings/settings.ts b/src/mobile/strings/settings.tsindex 8baa6433..00187b81 100644--- a/src/mobile/strings/settings.ts+++ b/src/mobile/strings/settings.ts@@ -667,6 +667,14 @@ export const SETTINGS_STRINGS = {autoNow: 'Back up now',autoDone: 'Backup written',autoUnavailable: 'The automatic backup is not available on this device.',+ // C46: the chats of the automatic backup that are not in the list. Chats deleted on this phone are not offered.+ rescue: 'Restore chats from the automatic backup',+ rescueLooking: 'Looking in the backup',+ rescueFound: (n: number) => `${n} ${n === 1 ? 'chat' : 'chats'} not in your list`,+ rescueNone: 'Every chat of the backup is in your list',+ rescueUnreadable: 'The backup could not be read',+ rescueWorking: 'Restoring',+ rescueDone: (n: number) => `${n} ${n === 1 ? 'chat' : 'chats'} restored`,today: 'today',yesterday: 'yesterday',groupDanger: 'Delete',