From 1bbca3677c5d00145a216a872c3c2ba37b6f14b0 Mon Sep 17 00:00:00 2001 From: Micah Lee Date: Fri, 11 Sep 2026 12:05:17 -0700 Subject: [PATCH 1/9] Merge a Cyd Bluesky archive into the account that holds its identity MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #97 asks for the entry point #93 removed and for what happens when a picked archive belongs to an identity this installation already has. Routing an archive and merging one are the same decision, so they land together: `chooseBlueskyArchiveImportDestination` reads the DID intake reported and says restore (#96), merge, or reconcile. Nothing looks at the file's name, and nothing is unpacked before intake has verified it. `services/archive-merge` is the merge. It is a union rather than a replacement, decided as a plan before anything is written: rows sharing a stable Bluesky identifier collapse into one, a flag either side set stays set, a deletion either side observed keeps the earlier time, and an archive that is quieter than the account never turns what the account knows back into absence. Because the plan only carries rows that would actually change, importing the same archive twice writes nothing at all, which is the acceptance criterion stated as a property of the code. The account's own columns survive an `INSERT OR REPLACE` because the merge names them: a preserved post stays preserved, a downloader's attempt count stays its own. A merge can bring back records somebody deleted from Cyd on purpose, so the preview names them before the commit does anything (ADR 0018). The commit re-reads the account rather than trusting the preview, so a save that ran in between is merged rather than overwritten. What the ports cannot do is the rest of the promise: there is no way from a merge to write settings, a schedule, a handle or a Bluesky connection, so an existing identity keeps its UUID and everything hanging off it. Duplicate DIDs are the one case with no unambiguous destination (ADR 0011). Mobile has enforced one account per DID since its first migration, so the state only arrives from outside — a database restored from an OS backup, say — and reconciliation shows what each account holds, takes the surviving UUID and the settings the person chose, unions the rest through the same rules, moves the media across, and puts the unique index back, which is also the check that the duplicates are gone. Retiring a local-account UUID retires a server-side reminder with it, so the import tells the server; a reminder still only opens a review. The interchange reader, the translation and the media pass are now shared with restore rather than copied, so the version 2 adapter stays one thing. merge.test.ts and duplicates.test.ts drive the committed real-data fixtures through intake, restore, and then a second import of the same archive, and assert through Mobile's own browse queries and the files on disk. Co-Authored-By: Claude Opus 5 (1M context) --- CONTEXT.md | 8 + components/BlueskyArchiveImportModal.tsx | 411 +++++++++++++ components/CydAccountBar.tsx | 52 +- ...w-a-recovery-merge-before-committing-it.md | 3 + hooks/use-accounts.ts | 5 + hooks/use-bluesky-archive-import.ts | 514 ++++++++++++++++ jest-setup.ts | 6 + package-lock.json | 10 + package.json | 1 + services/account-events.ts | 30 + .../__tests__/destination.test.ts | 64 ++ .../__tests__/duplicates.test.ts | 279 +++++++++ .../__tests__/merge-plan.test.ts | 328 ++++++++++ .../archive-merge/__tests__/merge.test.ts | 296 +++++++++ services/archive-merge/account-rows.ts | 100 +++ services/archive-merge/destination.ts | 37 ++ services/archive-merge/duplicates.ts | 319 ++++++++++ services/archive-merge/environment.ts | 171 ++++++ services/archive-merge/errors.ts | 24 + services/archive-merge/index.ts | 64 ++ services/archive-merge/merge-plan.ts | 581 ++++++++++++++++++ services/archive-merge/merge-writer.ts | 252 ++++++++ services/archive-merge/merge.ts | 302 +++++++++ services/archive-merge/ports.ts | 134 ++++ services/archive-merge/rows.ts | 88 +++ services/archive-merge/union.ts | 69 +++ services/archive-restore/environment.ts | 8 +- services/archive-restore/index.ts | 32 +- services/archive-restore/media.ts | 110 ++++ services/archive-restore/restore.ts | 91 +-- services/scheduled-reminder-sync.ts | 62 ++ testUtils/archiveEnvironments.ts | 134 +++- 32 files changed, 4464 insertions(+), 121 deletions(-) create mode 100644 components/BlueskyArchiveImportModal.tsx create mode 100644 docs/adr/0018-preview-a-recovery-merge-before-committing-it.md create mode 100644 hooks/use-bluesky-archive-import.ts create mode 100644 services/account-events.ts create mode 100644 services/archive-merge/__tests__/destination.test.ts create mode 100644 services/archive-merge/__tests__/duplicates.test.ts create mode 100644 services/archive-merge/__tests__/merge-plan.test.ts create mode 100644 services/archive-merge/__tests__/merge.test.ts create mode 100644 services/archive-merge/account-rows.ts create mode 100644 services/archive-merge/destination.ts create mode 100644 services/archive-merge/duplicates.ts create mode 100644 services/archive-merge/environment.ts create mode 100644 services/archive-merge/errors.ts create mode 100644 services/archive-merge/index.ts create mode 100644 services/archive-merge/merge-plan.ts create mode 100644 services/archive-merge/merge-writer.ts create mode 100644 services/archive-merge/merge.ts create mode 100644 services/archive-merge/ports.ts create mode 100644 services/archive-merge/rows.ts create mode 100644 services/archive-merge/union.ts create mode 100644 services/archive-restore/media.ts create mode 100644 services/scheduled-reminder-sync.ts diff --git a/CONTEXT.md b/CONTEXT.md index e620135..4ccca52 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -44,6 +44,14 @@ _Avoid_: export, backup, archive export Creating one new, disconnected Bluesky local account from a prepared Cyd Bluesky archive for an identity this installation does not already hold. It is the commit half of a Bluesky archive import for a new Bluesky identity; an identity Cyd already has a Bluesky local account for is merged instead. _Avoid_: restore, import, replace +**Bluesky archive merge**: +The commit half of a Bluesky archive import for an identity this installation already holds: a union of the Cyd Bluesky archive into that Bluesky local account's Bluesky saved data, previewed before it is written. It adds and enriches Bluesky saved records and never touches the account's identifier, Bluesky account settings, schedules or Bluesky connection. +_Avoid_: merge, sync, overwrite, import + +**Bluesky identity reconciliation**: +Collapsing several Bluesky local accounts that hold one Bluesky identity into a single surviving one, after the person chooses which local-account UUID and whose Bluesky account settings it keeps. It unions their Bluesky saved data and restores the rule that one Bluesky identity has one Bluesky local account. +_Avoid_: deduplication, account merge, cleanup + **Bluesky account settings**: Local preferences governing how Cyd saves and manages a Bluesky identity. A Cyd Bluesky archive can supply defaults for a new Bluesky local account, but does not silently override an existing Bluesky local account's preferences or schedules. _Avoid_: account settings, account data, archive state diff --git a/components/BlueskyArchiveImportModal.tsx b/components/BlueskyArchiveImportModal.tsx new file mode 100644 index 0000000..9bcdc8a --- /dev/null +++ b/components/BlueskyArchiveImportModal.tsx @@ -0,0 +1,411 @@ +import { useState } from "react"; +import { + ActivityIndicator, + Modal, + Pressable, + ScrollView, + StyleSheet, + Text, + View, +} from "react-native"; + +import { getThemePalette } from "@/constants/theme"; +import { useColorScheme } from "@/hooks/use-color-scheme"; +import type { BlueskyArchiveImportState } from "@/hooks/use-bluesky-archive-import"; + +/** + * What a Bluesky archive import looks like while it happens. + * + * Every state this shows is a point where the import is waiting on the person: + * an archive big enough to be worth asking about, records a merge would bring + * back, or one Bluesky identity held by two local accounts. The progress and + * the outcome are here for the same reason — an import that moves a gigabyte + * of somebody's own posts should never look like a frozen screen. + */ + +type ReconciliationChoice = { + survivingUuid: string; + settingsFromUuid: string; +}; + +export type BlueskyArchiveImportModalProps = { + state: BlueskyArchiveImportState; + onConfirmLargeArchive: () => void; + onConfirmMerge: () => void; + onKeepAccount: (choice: { + survivingUuid: string; + settingsFromUuid: string; + }) => void; + onCancel: () => void; + onDismiss: () => void; +}; + +/** How many of the records coming back are named before the list is cut off. */ +const LISTED_RESTORATIONS = 5; + +export function BlueskyArchiveImportModal({ + state, + onConfirmLargeArchive, + onConfirmMerge, + onKeepAccount, + onCancel, + onDismiss, +}: BlueskyArchiveImportModalProps) { + const palette = getThemePalette(useColorScheme()); + const [picked, setPicked] = useState(null); + + const reconciling = state.status === "reconciling" ? state.preview : null; + /** + * Which account is selected, before anybody has touched anything. + * + * The default is the one holding the most, because it is the one somebody is + * most likely to recognise as theirs — but it is only a default, and a + * selection that names an account this preview does not hold is stale and + * falls back to it. + */ + const known = (uuid: string | undefined): boolean => + reconciling?.accounts.some((account) => account.uuid === uuid) === true; + const fallback = reconciling + ? [...reconciling.accounts].sort( + (left, right) => totalRecords(right) - totalRecords(left), + )[0]?.uuid + : undefined; + const survivingUuid = known(picked?.survivingUuid) + ? picked!.survivingUuid + : fallback; + const settingsFromUuid = known(picked?.settingsFromUuid) + ? picked!.settingsFromUuid + : survivingUuid; + + if (state.status === "idle") { + return null; + } + + const action = ( + label: string, + onPress: () => void, + emphasis: "primary" | "quiet" = "quiet", + ) => ( + [ + styles.action, + { + borderColor: palette.icon + "22", + backgroundColor: + emphasis === "primary" ? palette.tint + "22" : palette.background, + opacity: pressed ? 0.9 : 1, + }, + ]} + > + {label} + + ); + + return ( + + + + {state.status === "working" ? ( + <> + + + {state.message} + + {state.fraction !== null ? ( + + {Math.round(state.fraction * 100)}% + + ) : null} + {state.cancellable ? action("Cancel", onCancel) : null} + + ) : null} + + {state.status === "needs-confirmation" ? ( + <> + + This is a big archive + + + {state.message} + + {action("Import it", onConfirmLargeArchive, "primary")} + {action("Cancel", onCancel)} + + ) : null} + + {state.status === "reconciling" && survivingUuid ? ( + <> + + Two accounts, one Bluesky identity + + + {state.message} + + + {state.preview.accounts.map((account) => ( + + + setPicked({ + survivingUuid: account.uuid, + settingsFromUuid: settingsFromUuid ?? account.uuid, + }) + } + accessibilityRole="radio" + accessibilityState={{ + selected: account.uuid === survivingUuid, + }} + style={[ + styles.choiceButton, + { + borderColor: + account.uuid === survivingUuid + ? palette.tint + : palette.icon + "22", + }, + ]} + > + + {account.handle ?? account.uuid} + + + {account.counts.posts} posts · {account.counts.chats}{" "} + chats · {account.counts.follows} follows + + + + setPicked({ + survivingUuid, + settingsFromUuid: account.uuid, + }) + } + accessibilityRole="radio" + accessibilityState={{ + selected: account.uuid === settingsFromUuid, + }} + > + + {account.uuid === settingsFromUuid + ? "✓ Keeping these settings and schedule" + : "Keep these settings and schedule"} + + + + ))} + + + Nothing is lost either way: the account you keep ends up with + everything both of them held. + + {action( + "Keep this account and continue", + () => + onKeepAccount({ + survivingUuid, + settingsFromUuid: settingsFromUuid ?? survivingUuid, + }), + "primary", + )} + {action("Cancel", onCancel)} + + ) : null} + + {state.status === "reviewing" ? ( + <> + + Merge into @{state.handle} + + + + {describeMerge(state.preview)} + + {state.preview.summary.restorations.total > 0 ? ( + <> + + Coming back to this account + + + These are not in Cyd right now. If you deleted any of them + from Cyd on purpose, importing brings them back. + + {state.preview.summary.restorations.records + .slice(0, LISTED_RESTORATIONS) + .map((record) => ( + + {record.text?.trim() + ? `${record.category}: ${record.text.trim()}` + : `${record.category}: ${record.id}`} + + ))} + {state.preview.summary.restorations.total > + LISTED_RESTORATIONS ? ( + + …and{" "} + {state.preview.summary.restorations.total - + LISTED_RESTORATIONS}{" "} + more. + + ) : null} + + ) : null} + + {action("Import", onConfirmMerge, "primary")} + {action("Cancel", onCancel)} + + ) : null} + + {state.status === "done" ? ( + <> + + {state.title} + + {state.lines.map((line) => ( + + {line} + + ))} + {action("Done", onDismiss, "primary")} + + ) : null} + + {state.status === "failed" ? ( + <> + + Import failed + + + {state.message} + + {action("Close", onDismiss, "primary")} + + ) : null} + + + + ); +} + +function totalRecords(account: { + counts: { posts: number; chats: number; messages: number; follows: number }; +}): number { + return ( + account.counts.posts + + account.counts.chats + + account.counts.messages + + account.counts.follows + ); +} + +/** One sentence about what this archive has that the account does not. */ +function describeMerge(preview: { + summary: { + posts: { added: number; updated: number }; + messages: { added: number; updated: number }; + follows: { added: number; updated: number }; + restorations: { total: number }; + }; + archive: { completeness: "complete" | "incomplete" }; +}): string { + const added = + preview.summary.posts.added + + preview.summary.messages.added + + preview.summary.follows.added; + const updated = + preview.summary.posts.updated + + preview.summary.messages.updated + + preview.summary.follows.updated; + + if (added === 0 && updated === 0) { + return "This archive holds nothing this account does not already have. Importing it will change nothing."; + } + const incomplete = + preview.archive.completeness === "incomplete" + ? " This archive is missing some files, so a few records will arrive without their media." + : ""; + return `${added} records will be added and ${updated} filled in. Your settings, schedule and Bluesky connection are left alone.${incomplete}`; +} + +const styles = StyleSheet.create({ + overlay: { + flex: 1, + backgroundColor: "rgba(0, 0, 0, 0.5)", + justifyContent: "center", + alignItems: "center", + padding: 24, + }, + sheet: { + width: "100%", + maxHeight: "85%", + borderRadius: 16, + padding: 24, + gap: 12, + }, + title: { + fontSize: 18, + fontWeight: "600", + textAlign: "center", + }, + subtitle: { + fontSize: 15, + fontWeight: "600", + marginTop: 12, + }, + body: { + fontSize: 14, + lineHeight: 20, + }, + record: { + fontSize: 13, + lineHeight: 18, + marginTop: 6, + }, + scroll: { + maxHeight: 280, + }, + choice: { + gap: 6, + marginBottom: 12, + }, + choiceButton: { + borderWidth: StyleSheet.hairlineWidth, + borderRadius: 12, + padding: 12, + gap: 4, + }, + choiceTitle: { + fontSize: 15, + fontWeight: "600", + }, + settingsPick: { + fontSize: 13, + paddingHorizontal: 4, + }, + action: { + borderRadius: 16, + borderWidth: StyleSheet.hairlineWidth, + paddingVertical: 14, + paddingHorizontal: 16, + }, + actionText: { + fontSize: 16, + fontWeight: "600", + textAlign: "center", + }, +}); diff --git a/components/CydAccountBar.tsx b/components/CydAccountBar.tsx index 55e7433..da72335 100644 --- a/components/CydAccountBar.tsx +++ b/components/CydAccountBar.tsx @@ -1,4 +1,4 @@ -import { useCallback, useState } from "react"; +import { useCallback, useMemo, useState } from "react"; import { Linking, Modal, @@ -12,8 +12,11 @@ import { useSafeAreaInsets } from "react-native-safe-area-context"; import { getThemePalette } from "@/constants/theme"; import { useCydAccount } from "@/contexts/CydAccountProvider"; +import { useBlueskyArchiveImport } from "@/hooks/use-bluesky-archive-import"; import { useColorScheme } from "@/hooks/use-color-scheme"; +import { createScheduledReminderSync } from "@/services/scheduled-reminder-sync"; +import { BlueskyArchiveImportModal } from "./BlueskyArchiveImportModal"; import { CydSignInModal } from "./CydSignInModal"; type CydAccountBarProps = { @@ -31,10 +34,18 @@ export function CydAccountBar({ Platform.OS === "android" ? Math.max(bottomInset, 8) : bottomInset; const colorScheme = useColorScheme(); const palette = getThemePalette(colorScheme); - const { state, signOut, getDashboardURL } = useCydAccount(); + const { state, signOut, getDashboardURL, apiClient } = useCydAccount(); const [menuVisible, setMenuVisible] = useState(false); const [signInModalVisible, setSignInModalVisible] = useState(false); + const archiveImport = useBlueskyArchiveImport({ + // Reconciling duplicate accounts can retire a local-account UUID the + // server schedules reminders against (ADR 0005), so the import tells it. + reminders: useMemo( + () => createScheduledReminderSync(apiClient, state.isSignedIn), + [apiClient, state.isSignedIn], + ), + }); const handleMenuPress = useCallback(() => { setMenuVisible(true); @@ -71,6 +82,19 @@ export function CydAccountBar({ onShowOnboarding?.(); }, [onShowOnboarding]); + /** + * Import a Cyd Bluesky archive. + * + * Importing needs no Cyd account and no premium subscription — it is how + * somebody gets their own data back — so the menu item is here whether or + * not they are signed in. Where the archive lands is decided by the Bluesky + * identity inside it, not by anything about the file (#97). + */ + const handleImportArchive = useCallback(() => { + setMenuVisible(false); + void archiveImport.start(); + }, [archiveImport]); + if (state.isLoading || hidden) { return null; } @@ -213,6 +237,22 @@ export function CydAccountBar({ { borderColor: palette.icon + "22" }, ]} /> + [ + styles.sheetActionButton, + { + borderColor: palette.icon + "22", + backgroundColor: palette.background, + opacity: pressed ? 0.9 : 1, + }, + ]} + accessibilityRole="button" + > + + Import Bluesky archive + + [ @@ -239,6 +279,14 @@ export function CydAccountBar({ onClose={handleCloseSignInModal} /> + void archiveImport.confirmLargeArchive()} + onConfirmMerge={() => void archiveImport.confirmMerge()} + onKeepAccount={(choice) => void archiveImport.keepAccount(choice)} + onCancel={archiveImport.cancel} + onDismiss={archiveImport.dismiss} + /> ); } diff --git a/docs/adr/0018-preview-a-recovery-merge-before-committing-it.md b/docs/adr/0018-preview-a-recovery-merge-before-committing-it.md new file mode 100644 index 0000000..05bf868 --- /dev/null +++ b/docs/adr/0018-preview-a-recovery-merge-before-committing-it.md @@ -0,0 +1,3 @@ +# Preview a recovery merge before committing it + +Cyd Mobile splits a Bluesky archive merge into a preview that reads the prepared Cyd Bluesky archive and works out every row it would write, and a commit that carries that preview out, because a recovery union can restore Bluesky saved records the person removed through Bluesky local deletion and they must see which ones before it happens. The preview names the records coming back rather than only counting them; the commit re-reads the Bluesky local account instead of trusting the preview's copy, so work that ran in between is merged rather than overwritten, and committing the same Cyd Bluesky archive again writes nothing. diff --git a/hooks/use-accounts.ts b/hooks/use-accounts.ts index ba30215..f3e1d30 100644 --- a/hooks/use-accounts.ts +++ b/hooks/use-accounts.ts @@ -2,6 +2,7 @@ import { useCallback, useEffect, useRef, useState } from "react"; import { useFocusEffect } from "expo-router/react-navigation"; import { type AccountListItem, listAccounts } from "@/database/accounts"; +import { onLocalAccountsChanged } from "@/services/account-events"; export type UseAccountsResult = { accounts: AccountListItem[]; @@ -54,5 +55,9 @@ export function useAccounts(): UseAccountsResult { }, [refresh]), ); + // An import can add or remove an account while this screen keeps focus, so + // focus alone is not enough to keep the list honest (#97). + useEffect(() => onLocalAccountsChanged(() => void refresh()), [refresh]); + return { accounts, loading, error, refresh }; } diff --git a/hooks/use-bluesky-archive-import.ts b/hooks/use-bluesky-archive-import.ts new file mode 100644 index 0000000..16d032b --- /dev/null +++ b/hooks/use-bluesky-archive-import.ts @@ -0,0 +1,514 @@ +import * as Crypto from "expo-crypto"; +import * as DocumentPicker from "expo-document-picker"; +import { useCallback, useRef, useState } from "react"; + +import { + cancelBlueskyArchiveIntake, + createBlueskyArchiveIntakeEnvironment, + openBlueskyArchiveByteReader, + runBlueskyArchiveIntake, + type BlueskyArchiveIntakeEnvironment, + type PreparedBlueskyArchive, +} from "@/services/archive-import"; +import { + chooseBlueskyArchiveImportDestination, + commitBlueskyArchiveMerge, + createBlueskyArchiveMergeEnvironment, + previewBlueskyArchiveMerge, + previewDuplicateReconciliation, + reconcileDuplicateBlueskyAccounts, + type BlueskyArchiveMergeEnvironment, + type BlueskyArchiveMergePreview, + type DuplicateReconciliationPreview, +} from "@/services/archive-merge"; +import { + NO_SCHEDULED_REMINDERS, + type ScheduledReminderSync, +} from "@/services/scheduled-reminder-sync"; +import { + createBlueskyArchiveRestoreEnvironment, + restoreBlueskyArchiveAccount, + type BlueskyArchiveRestoreEnvironment, + type LocalAccountIdentity, +} from "@/services/archive-restore"; +import { emitLocalAccountsChanged } from "@/services/account-events"; + +/** + * Importing a Cyd Bluesky archive, from the menu to the account. + * + * This is the entry point #93 removed and #97 owns again, and it is one thing + * rather than two because routing a picked archive and merging one are the + * same decision: intake reports the Bluesky identity's DID, and whether the + * import creates a Bluesky local account or merges into one follows from + * whether this installation already holds it. + * + * What is deliberately *not* here is the behaviour #91 ruled out. Nothing + * reads the picked file's name, and nothing is unpacked before the archive has + * been inspected — both belong to intake now, which verifies every payload + * against the manifest before it lands in staging. + * + * The person is asked before anything irreversible: to confirm an unusually + * large archive, to look at records a merge would bring back, and to choose + * which Bluesky local account survives when this installation holds one + * identity twice. Cancelling at any of those points takes the staging with it. + */ + +export type BlueskyArchiveImportState = + | { status: "idle" } + | { + status: "working"; + message: string; + /** Fraction done, or null while there is nothing meaningful to show. */ + fraction: number | null; + cancellable: boolean; + } + | { status: "needs-confirmation"; message: string } + | { + status: "reconciling"; + message: string; + preview: DuplicateReconciliationPreview; + } + | { + status: "reviewing"; + preview: BlueskyArchiveMergePreview; + handle: string; + } + | { status: "done"; title: string; lines: string[] } + | { status: "failed"; message: string }; + +/** The device capabilities an import needs, gathered so tests can stand in. */ +export type BlueskyArchiveImportRuntime = { + pickArchive(): Promise<{ uri: string } | null>; + intake: BlueskyArchiveIntakeEnvironment; + restore: BlueskyArchiveRestoreEnvironment; + merge: BlueskyArchiveMergeEnvironment; + /** Server-scheduled reminders, which reconciliation has to keep honest. */ + reminders: ScheduledReminderSync; + newIntakeId(): string; +}; + +function createDeviceRuntime(): BlueskyArchiveImportRuntime { + return { + pickArchive: async () => { + // No filename validation, and no type filter narrow enough to hide a + // real archive: what the file *is* is settled by reading it (#91). + const picked = await DocumentPicker.getDocumentAsync({ + copyToCacheDirectory: true, + multiple: false, + }); + if (picked.canceled || !picked.assets?.[0]) { + return null; + } + return { uri: picked.assets[0].uri }; + }, + intake: createBlueskyArchiveIntakeEnvironment(), + restore: createBlueskyArchiveRestoreEnvironment(), + merge: createBlueskyArchiveMergeEnvironment(), + reminders: NO_SCHEDULED_REMINDERS, + newIntakeId: () => Crypto.randomUUID(), + }; +} + +type Session = { + intakeId: string; + sourceUri: string; + confirmedLargeArchive: boolean; + cancelled: boolean; + /** Set once intake ends *prepared*, so a later step can reach the staging. */ + prepared: PreparedBlueskyArchive | null; +}; + +function messageFor(error: unknown): string { + return error instanceof Error + ? error.message + : "Cyd could not import that archive."; +} + +/** + * Tell the server which Bluesky local account its reminders belong to now. + * + * A reconciliation is finished either way: reminders are a convenience, and an + * offline phone must not be told its accounts failed to merge. The worst case + * is a reminder that opens an account which now holds more than it did. + */ +async function syncReminders( + reminders: ScheduledReminderSync, + reconciled: { survivingUuid: string; removedUuids: string[] }, +): Promise { + try { + for (const uuid of reconciled.removedUuids) { + await reminders.retire(uuid); + } + await reminders.resync(reconciled.survivingUuid); + } catch (error) { + console.warn("[archive-import] could not update reminders", error); + } +} + +function plural(count: number, noun: string): string { + return `${count.toLocaleString()} ${noun}${count === 1 ? "" : "s"}`; +} + +export function useBlueskyArchiveImport( + options: { + runtime?: BlueskyArchiveImportRuntime; + reminders?: ScheduledReminderSync; + } = {}, +) { + const { runtime, reminders } = options; + const [state, setState] = useState({ + status: "idle", + }); + const runtimeRef = useRef( + runtime ?? null, + ); + const sessionRef = useRef(null); + + const environments = useCallback((): BlueskyArchiveImportRuntime => { + if (!runtimeRef.current) { + runtimeRef.current = createDeviceRuntime(); + } + return runtimeRef.current; + }, []); + + /** Abandon an import and take its staging with it (AC: nothing left behind). */ + const discardStaging = useCallback(() => { + const session = sessionRef.current; + if (!session) { + return; + } + try { + cancelBlueskyArchiveIntake(environments().intake, session.intakeId); + } catch (error) { + console.warn("[archive-import] could not clear staging", error); + } + sessionRef.current = null; + }, [environments]); + + const runRestore = useCallback( + async ( + prepared: PreparedBlueskyArchive, + environment: BlueskyArchiveRestoreEnvironment, + ): Promise => { + setState({ + status: "working", + message: "Restoring the account…", + fraction: null, + cancellable: false, + }); + + const result = await restoreBlueskyArchiveAccount(environment, { + archive: { + intakeId: prepared.intakeId, + stagingRoot: prepared.stagingRoot, + }, + onProgress: (progress) => + setState({ + status: "working", + message: "Restoring the account…", + fraction: + progress.totalAssets > 0 + ? progress.restoredAssets / progress.totalAssets + : null, + cancellable: false, + }), + }); + + sessionRef.current = null; + emitLocalAccountsChanged(); + setState({ + status: "done", + title: `Restored @${result.handle}`, + lines: [ + `${plural(result.counts.posts, "post")}, ${plural(result.counts.likes, "like")}, ${plural(result.counts.chats, "chat")}.`, + `${plural(result.assets.restored, "file")} restored${result.assets.missing > 0 ? `, ${result.assets.missing} missing` : ""}.`, + "This account is not connected to Bluesky. Sign in when you want Cyd to act on it.", + ...(result.uuidRemapping ? [result.uuidRemapping.reason] : []), + ], + }); + }, + [], + ); + + const openMergePreview = useCallback( + async ( + prepared: PreparedBlueskyArchive, + environment: BlueskyArchiveMergeEnvironment, + account: LocalAccountIdentity, + ): Promise => { + setState({ + status: "working", + message: "Working out what this archive would add…", + fraction: null, + cancellable: true, + }); + + const preview = await previewBlueskyArchiveMerge(environment, { + archive: { + intakeId: prepared.intakeId, + stagingRoot: prepared.stagingRoot, + }, + account, + }); + + setState({ + status: "reviewing", + preview, + handle: account.handle ?? preview.accountDid, + }); + }, + [], + ); + + /** Where this archive goes, decided by the DID intake reported. */ + const route = useCallback( + async ( + prepared: PreparedBlueskyArchive, + environment: Pick, + ): Promise => { + const identities = + await environment.merge.listLocalAccountIdentities(); + const destination = chooseBlueskyArchiveImportDestination( + prepared.metadata.accountDid, + identities, + ); + + if (destination.kind === "restore") { + await runRestore(prepared, environment.restore); + return; + } + if (destination.kind === "merge") { + await openMergePreview(prepared, environment.merge, destination.account); + return; + } + + setState({ + status: "reconciling", + message: + "This device has more than one Bluesky account for the identity in this archive. Choose which one to keep before importing.", + preview: await previewDuplicateReconciliation(environment.merge, { + did: destination.did, + accounts: identities, + }), + }); + }, + [openMergePreview, runRestore], + ); + + const run = useCallback( + async (session: Session): Promise => { + const { intake, restore, merge } = environments(); + sessionRef.current = session; + + setState({ + status: "working", + message: "Reading the archive…", + fraction: null, + cancellable: true, + }); + + const outcome = await runBlueskyArchiveIntake(intake, { + intakeId: session.intakeId, + sourceUri: session.sourceUri, + openReader: async () => + openBlueskyArchiveByteReader(session.sourceUri), + confirmLargeArchive: session.confirmedLargeArchive, + shouldCancel: () => session.cancelled, + onProgress: (progress) => + setState({ + status: "working", + message: "Reading the archive…", + fraction: + progress.totalBytes > 0 + ? progress.preparedBytes / progress.totalBytes + : null, + cancellable: true, + }), + }); + + if (outcome.status === "cancelled") { + sessionRef.current = null; + setState({ status: "idle" }); + return; + } + if (outcome.status === "rejected") { + // Intake clears staging for an archive it blames, and keeps it for a + // failure it blames the device for, so that freeing space and trying + // again resumes. Nothing offers to resume from here, so a rejection + // ends the import and takes any staging with it either way. + discardStaging(); + setState({ status: "failed", message: outcome.message }); + return; + } + if (outcome.status === "needs-confirmation") { + setState({ status: "needs-confirmation", message: outcome.message }); + return; + } + + sessionRef.current = { ...session, prepared: outcome }; + await route(outcome, { restore, merge }); + }, + [discardStaging, environments, route], + ); + + /** Pick the archive and take it as far as it can go without a decision. */ + const start = useCallback(async (): Promise => { + try { + const picked = await environments().pickArchive(); + if (!picked) { + return; + } + await run({ + intakeId: environments().newIntakeId(), + sourceUri: picked.uri, + confirmedLargeArchive: false, + cancelled: false, + prepared: null, + }); + } catch (error) { + discardStaging(); + setState({ status: "failed", message: messageFor(error) }); + } + }, [discardStaging, environments, run]); + + const confirmLargeArchive = useCallback(async (): Promise => { + const session = sessionRef.current; + if (!session) { + return; + } + try { + await run({ ...session, confirmedLargeArchive: true }); + } catch (error) { + discardStaging(); + setState({ status: "failed", message: messageFor(error) }); + } + }, [discardStaging, run]); + + /** Commit a merge the person has looked at. */ + const confirmMerge = useCallback(async (): Promise => { + if (state.status !== "reviewing") { + return; + } + const { preview, handle } = state; + try { + setState({ + status: "working", + message: "Merging the archive…", + fraction: null, + cancellable: false, + }); + const result = await commitBlueskyArchiveMerge( + environments().merge, + preview, + { + onProgress: (progress) => + setState({ + status: "working", + message: "Merging the archive…", + fraction: + progress.totalAssets > 0 + ? progress.mergedAssets / progress.totalAssets + : null, + cancellable: false, + }), + }, + ); + + sessionRef.current = null; + emitLocalAccountsChanged(); + setState({ + status: "done", + title: `Merged into @${handle}`, + lines: + result.written === 0 + ? ["This archive held nothing that account did not already have."] + : [ + `${plural(result.summary.restorations.total, "record")} came back.`, + `${plural(result.summary.posts.updated + result.summary.messages.updated + result.summary.follows.updated, "record")} gained something.`, + "Your settings, schedule and Bluesky connection were left as they were.", + ], + }); + } catch (error) { + discardStaging(); + setState({ status: "failed", message: messageFor(error) }); + } + }, [discardStaging, environments, state]); + + /** + * Keep one of the duplicate Bluesky local accounts, then carry on importing. + * + * The reconciliation runs first because the import has nowhere to land until + * the identity is held once (ADR 0011). + */ + const keepAccount = useCallback( + async (choice: { + survivingUuid: string; + settingsFromUuid: string; + }): Promise => { + const session = sessionRef.current; + if (state.status !== "reconciling" || !session?.prepared) { + return; + } + const { prepared } = session; + const { merge } = environments(); + try { + setState({ + status: "working", + message: "Merging the duplicate accounts…", + fraction: null, + cancellable: false, + }); + const reconciled = await reconcileDuplicateBlueskyAccounts(merge, { + did: state.preview.did, + accounts: await merge.listLocalAccountIdentities(), + survivingUuid: choice.survivingUuid, + settingsFromUuid: choice.settingsFromUuid, + }); + emitLocalAccountsChanged(); + await syncReminders( + reminders ?? environments().reminders, + reconciled, + ); + + const survivor = (await merge.listLocalAccountIdentities()).find( + (account) => account.uuid === choice.survivingUuid, + ); + if (!survivor) { + throw new Error( + "Cyd could not find the Bluesky account it just kept.", + ); + } + await openMergePreview(prepared, merge, survivor); + } catch (error) { + discardStaging(); + setState({ status: "failed", message: messageFor(error) }); + } + }, + [discardStaging, environments, openMergePreview, reminders, state], + ); + + /** Walk away: nothing has been written, and nothing stays staged. */ + const cancel = useCallback((): void => { + const session = sessionRef.current; + if (session) { + session.cancelled = true; + } + discardStaging(); + setState({ status: "idle" }); + }, [discardStaging]); + + const dismiss = useCallback((): void => { + sessionRef.current = null; + setState({ status: "idle" }); + }, []); + + return { + state, + start, + confirmLargeArchive, + confirmMerge, + keepAccount, + cancel, + dismiss, + }; +} diff --git a/jest-setup.ts b/jest-setup.ts index e25cf88..281934d 100644 --- a/jest-setup.ts +++ b/jest-setup.ts @@ -188,6 +188,12 @@ jest.mock("expo-crypto", () => { }; }); +// Mock expo-document-picker: tests never open a real file picker, and an +// import that is cancelled is the default because it touches nothing. +jest.mock("expo-document-picker", () => ({ + getDocumentAsync: jest.fn(() => Promise.resolve({ canceled: true })), +})); + // Mock expo-file-system jest.mock("expo-file-system", () => { const fileContents = new Map(); diff --git a/package-lock.json b/package-lock.json index 9c16a3c..d806f7f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -28,6 +28,7 @@ "expo-crypto": "~57.0.0", "expo-dev-client": "~57.0.5", "expo-device": "~57.0.0", + "expo-document-picker": "^57.0.2", "expo-font": "~57.0.0", "expo-haptics": "~57.0.0", "expo-iap": "^4.3.6", @@ -10358,6 +10359,15 @@ "expo": "*" } }, + "node_modules/expo-document-picker": { + "version": "57.0.2", + "resolved": "https://registry.npmjs.org/expo-document-picker/-/expo-document-picker-57.0.2.tgz", + "integrity": "sha512-vVBbBNg0piMJUIxjB+DR6JaZZpcSl90ZUoywLA/EgNHTfRkZW+9axP97UxM2a0Zm0W6WfH3cLzzGAEfP9OKGwg==", + "license": "MIT", + "peerDependencies": { + "expo": "*" + } + }, "node_modules/expo-file-system": { "version": "57.0.0", "resolved": "https://registry.npmjs.org/expo-file-system/-/expo-file-system-57.0.0.tgz", diff --git a/package.json b/package.json index 0d5e16f..6e4c5f8 100644 --- a/package.json +++ b/package.json @@ -46,6 +46,7 @@ "expo-crypto": "~57.0.0", "expo-dev-client": "~57.0.5", "expo-device": "~57.0.0", + "expo-document-picker": "^57.0.2", "expo-font": "~57.0.0", "expo-haptics": "~57.0.0", "expo-iap": "^4.3.6", diff --git a/services/account-events.ts b/services/account-events.ts new file mode 100644 index 0000000..fd4a94d --- /dev/null +++ b/services/account-events.ts @@ -0,0 +1,30 @@ +type LocalAccountsListener = () => void; + +const listeners = new Set(); + +/** + * Notice when the set of Bluesky local accounts changes. + * + * A Bluesky archive import can create an account, or fold two of them into + * one, from a menu that lives outside the accounts list (#97). The list + * refreshes when it regains focus, which never happens for a modal opened over + * it, so it listens here instead. Modelled on `services/auth-events.ts`. + */ +export function onLocalAccountsChanged( + listener: LocalAccountsListener, +): () => void { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; +} + +export function emitLocalAccountsChanged(): void { + for (const listener of listeners) { + try { + listener(); + } catch (err) { + console.warn("[account-events] listener error", err); + } + } +} diff --git a/services/archive-merge/__tests__/destination.test.ts b/services/archive-merge/__tests__/destination.test.ts new file mode 100644 index 0000000..448f1f2 --- /dev/null +++ b/services/archive-merge/__tests__/destination.test.ts @@ -0,0 +1,64 @@ +import type { LocalAccountIdentity } from "@/services/archive-restore"; + +import { chooseBlueskyArchiveImportDestination } from "../destination"; + +/** + * Where a picked Cyd Bluesky archive is committed. + * + * Routing is the whole of the decision #97 owns: the same picked file becomes + * a restore, a merge, or a reconciliation depending only on what this + * installation already holds for the archive's DID. + */ + +const identity = ( + uuid: string, + did: string | null, + handle = "somebody.bsky.social", +): LocalAccountIdentity => ({ uuid, did, handle }); + +describe("choosing where a Cyd Bluesky archive is committed", () => { + it("restores an identity this installation does not hold", () => { + const destination = chooseBlueskyArchiveImportDestination( + "did:plc:archive", + [identity("uuid-a", "did:plc:someone-else")], + ); + + expect(destination).toEqual({ kind: "restore" }); + }); + + it("merges into the one Bluesky local account holding the DID", () => { + const existing = identity("uuid-a", "did:plc:archive", "glitter.bsky.social"); + + const destination = chooseBlueskyArchiveImportDestination( + "did:plc:archive", + [identity("uuid-b", "did:plc:someone-else"), existing], + ); + + expect(destination).toEqual({ kind: "merge", account: existing }); + }); + + it("matches on the DID rather than the handle a local account is listed under", () => { + const destination = chooseBlueskyArchiveImportDestination("did:plc:archive", [ + identity("uuid-a", null, "glitter.bsky.social"), + ]); + + expect(destination).toEqual({ kind: "restore" }); + }); + + it("asks for reconciliation when duplicate local accounts hold the DID", () => { + const first = identity("uuid-a", "did:plc:archive"); + const second = identity("uuid-b", "did:plc:archive"); + + const destination = chooseBlueskyArchiveImportDestination("did:plc:archive", [ + first, + identity("uuid-c", "did:plc:someone-else"), + second, + ]); + + expect(destination).toEqual({ + kind: "reconcile", + did: "did:plc:archive", + accounts: [first, second], + }); + }); +}); diff --git a/services/archive-merge/__tests__/duplicates.test.ts b/services/archive-merge/__tests__/duplicates.test.ts new file mode 100644 index 0000000..fbd10b4 --- /dev/null +++ b/services/archive-merge/__tests__/duplicates.test.ts @@ -0,0 +1,279 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import type { DatabaseSync } from "node:sqlite"; + +import { + runBlueskyArchiveIntake, + type PreparedBlueskyArchive, +} from "@/services/archive-import"; +import { restoreBlueskyArchiveAccount } from "@/services/archive-restore"; +import { createMemoryByteReader } from "@/testUtils/archiveFixtures"; +import { + createDiskBlueskyArchiveIntakeEnvironment, + createNodeBlueskyArchiveRestoreEnvironment, + type NodeRestoreEnvironment, +} from "@/testUtils/archiveEnvironments"; + +import { + findDuplicateBlueskyIdentities, + previewDuplicateReconciliation, + reconcileDuplicateBlueskyAccounts, +} from "../duplicates"; + +/** + * Collapsing a Bluesky identity this installation holds twice (ADR 0011). + * + * Duplicates are the state an archive import cannot route around: with two + * Bluesky local accounts for one DID there is no unambiguous destination, so + * the person is shown both and says which one survives and whose settings it + * keeps. What must come out the other side is one account, holding the union + * of both, under an identifier they chose. + */ + +const FIXTURE_DIRECTORY = path.join( + __dirname, + "../../../testUtils/fixtures/bluesky-archive", +); +const ACCOUNT_DID = "did:plc:yn45xekh5kqrat27w6rmafcg"; +const ORPHAN_URI = "at://did:plc:yn45xekh5kqrat27w6rmafcg/app.bsky.feed.post/only-on-the-other-one"; + +jest.setTimeout(120_000); + +type Harness = { + root: string; + environment: NodeRestoreEnvironment; + survivor: { uuid: string; id: number }; + duplicate: { uuid: string; id: number }; +}; + +async function stage(root: string): Promise { + const outcome = await runBlueskyArchiveIntake( + createDiskBlueskyArchiveIntakeEnvironment(path.join(root, "intake")), + { + intakeId: "intake-1", + sourceUri: "file:///fixtures/complete.cyd", + openReader: async () => + createMemoryByteReader( + new Uint8Array( + fs.readFileSync(path.join(FIXTURE_DIRECTORY, "complete.cyd")), + ), + ), + }, + ); + if (outcome.status !== "prepared") { + throw new Error(`intake did not prepare: ${outcome.status}`); + } + return outcome; +} + +/** + * One identity, two Bluesky local accounts: a restored one, and a second the + * person built up separately, holding a post and a file the first never saw. + */ +async function twoAccountsForOneIdentity(): Promise { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "cyd-duplicates-")); + const environment = createNodeBlueskyArchiveRestoreEnvironment({ + root: path.join(root, "app"), + }); + const prepared = await stage(root); + const restored = await restoreBlueskyArchiveAccount(environment, { + archive: { + intakeId: prepared.intakeId, + stagingRoot: prepared.stagingRoot, + }, + }); + + // Mobile's own schema will not hold two accounts for one DID, so the state + // this reconciliation exists for has to be built the way it would arrive: + // from a database that predates the rule. + environment.mainDatabase.exec("DROP INDEX IF EXISTS idx_bsky_account_did;"); + + const duplicate = await environment.createLocalAccount({ + uuid: "11111111-2222-4333-8444-555555555555", + did: ACCOUNT_DID, + handle: ACCOUNT_DID, + displayName: "The other copy", + avatarUrl: null, + settings: { settingSavePosts: 0, settingDeleteLikes: 1 }, + }); + + const database = environment.openRestoredAccountDatabase(duplicate.accountUuid); + const stored = await environment.storeAccountMedia( + duplicate.accountUuid, + "sha256-onlyontheotherone", + async (push) => push(new Uint8Array([1, 2, 3, 4])), + ); + database + .prepare( + `INSERT INTO profile (did, handle, displayName, avatarUrl, savedAt, updatedAt) + VALUES (?, ?, ?, ?, ?, ?);`, + ) + .run(ACCOUNT_DID, "glittertop-cyd.bsky.social", null, null, 10, 10); + database + .prepare( + `INSERT INTO media_asset ( + contentCid, mediaType, mimeType, byteLength, localPath, sourceUrl, + downloadState, attemptCount, downloadedAt + ) VALUES (?, 'image', 'image/jpeg', 4, ?, 'https://cdn.example/one.jpg', 'complete', 0, 10);`, + ) + .run("bafy-only-on-the-other-one", stored.uri); + database + .prepare( + `INSERT INTO post ( + uri, cid, authorDid, text, isReply, isQuote, isRepost, + likeCount, repostCount, replyCount, quoteCount, + viewerLiked, viewerReposted, viewerBookmarked, + createdAt, savedAt, preserve + ) VALUES (?, 'cid-other', ?, 'only on the other copy', 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, '2026-02-02T00:00:00.000Z', 10, 1);`, + ) + .run(ORPHAN_URI, ACCOUNT_DID); + database.close(); + + return { + root, + environment, + survivor: { uuid: restored.accountUuid, id: restored.accountId }, + duplicate: { uuid: duplicate.accountUuid, id: duplicate.accountId }, + }; +} + +function accountRow( + main: DatabaseSync, + accountUuid: string, +): Record | undefined { + return main + .prepare( + `SELECT b.* FROM bsky_account b + INNER JOIN account a ON a.bskyAccountID = b.id + WHERE a.uuid = ?;`, + ) + .get(accountUuid) ?? undefined; +} + +describe("reconciling a Bluesky identity held by two local accounts", () => { + let harness: Harness; + + beforeAll(async () => { + harness = await twoAccountsForOneIdentity(); + }); + + afterAll(() => { + harness.environment.close(); + fs.rmSync(harness.root, { recursive: true, force: true }); + }); + + it("flags the duplicates rather than picking one", async () => { + const duplicates = findDuplicateBlueskyIdentities( + await harness.environment.listLocalAccountIdentities(), + ); + + expect(duplicates).toHaveLength(1); + expect(duplicates[0].did).toBe(ACCOUNT_DID); + expect(duplicates[0].accounts.map((account) => account.uuid).sort()).toEqual( + [harness.duplicate.uuid, harness.survivor.uuid].sort(), + ); + }); + + it("previews what each local account holds and is set to do", async () => { + const preview = await previewDuplicateReconciliation(harness.environment, { + did: ACCOUNT_DID, + accounts: await harness.environment.listLocalAccountIdentities(), + }); + + const other = preview.accounts.find( + (account) => account.uuid === harness.duplicate.uuid, + ); + expect(other).toMatchObject({ + uuid: harness.duplicate.uuid, + counts: { posts: 1, profiles: 1 }, + settings: { settingSavePosts: 0, settingDeleteLikes: 1 }, + }); + expect( + preview.accounts.find( + (account) => account.uuid === harness.survivor.uuid, + )?.counts.posts, + ).toBeGreaterThan(1); + }); + + it("keeps the identifier and settings the person chose, and unions the rest", async () => { + const main = harness.environment.mainDatabase; + const before = accountRow(main, harness.survivor.uuid); + + const result = await reconcileDuplicateBlueskyAccounts(harness.environment, { + did: ACCOUNT_DID, + accounts: await harness.environment.listLocalAccountIdentities(), + survivingUuid: harness.survivor.uuid, + settingsFromUuid: harness.duplicate.uuid, + }); + + expect(result.survivingUuid).toBe(harness.survivor.uuid); + expect(result.removedUuids).toEqual([harness.duplicate.uuid]); + + const database = harness.environment.openRestoredAccountDatabase( + harness.survivor.uuid, + ); + const adopted = database + .prepare("SELECT preserve, text FROM post WHERE uri = ?;") + .get(ORPHAN_URI) as { preserve: number; text: string } | undefined; + const asset = database + .prepare("SELECT localPath FROM media_asset WHERE contentCid = ?;") + .get("bafy-only-on-the-other-one") as { localPath: string } | undefined; + database.close(); + + expect(adopted).toMatchObject({ + text: "only on the other copy", + preserve: 1, + }); + // The file moved with the record, into the surviving account's own storage. + expect(asset?.localPath).toContain( + `bluesky-${harness.survivor.uuid}`, + ); + expect(fs.existsSync(asset!.localPath.replace("file://", ""))).toBe(true); + + // The settings came from the account whose settings were chosen; the + // surviving account's own identifier did not move. + const after = accountRow(main, harness.survivor.uuid); + expect(after).toMatchObject({ + settingSavePosts: 0, + settingDeleteLikes: 1, + did: ACCOUNT_DID, + handle: before?.handle, + }); + }); + + it("leaves one Bluesky local account for the identity, and nothing to reconcile", async () => { + const identities = await harness.environment.listLocalAccountIdentities(); + + expect( + identities.filter((account) => account.did === ACCOUNT_DID), + ).toHaveLength(1); + expect(findDuplicateBlueskyIdentities(identities)).toEqual([]); + expect( + fs.existsSync(harness.environment.accountDirectory(harness.duplicate.uuid)), + ).toBe(false); + + // And the rule is back on, so the installation cannot drift into holding + // the identity twice again. + expect(() => + harness.environment.mainDatabase + .prepare( + `INSERT INTO bsky_account (createdAt, updatedAt, accessedAt, handle, postsCount, did) + VALUES (1, 1, 1, 'another.bsky.social', 0, ?);`, + ) + .run(ACCOUNT_DID), + ).toThrow(/UNIQUE/i); + }); + + it("refuses to keep an account that is not one of the duplicates", async () => { + await expect( + reconcileDuplicateBlueskyAccounts(harness.environment, { + did: ACCOUNT_DID, + accounts: await harness.environment.listLocalAccountIdentities(), + survivingUuid: "99999999-9999-4999-8999-999999999999", + settingsFromUuid: harness.survivor.uuid, + }), + ).rejects.toThrow(/account/i); + }); +}); diff --git a/services/archive-merge/__tests__/merge-plan.test.ts b/services/archive-merge/__tests__/merge-plan.test.ts new file mode 100644 index 0000000..eeecb88 --- /dev/null +++ b/services/archive-merge/__tests__/merge-plan.test.ts @@ -0,0 +1,328 @@ +import type { MobilePostWrite } from "@/services/archive-restore"; + +import { planBlueskyArchiveMerge } from "../merge-plan"; +import type { ExistingAccountRows, ExistingPostRow } from "../rows"; + +/** + * The recovery union, as a decision about rows. + * + * Everything the merge promises somebody — that importing twice changes + * nothing, that a Cyd Bluesky archive never blanks out what this device knows, + * that data the archive says nothing about survives — is decided here, with no + * database in sight. A row the plan does not carry is a row nothing writes. + */ + +const ARCHIVE_DID = "did:plc:archive"; + +function post(overrides: Partial = {}): MobilePostWrite { + return { + uri: "at://did:plc:archive/app.bsky.feed.post/one", + cid: "cid-one", + authorDid: ARCHIVE_DID, + text: "hello", + facetsJSON: null, + embedType: null, + embedJSON: null, + langs: null, + isReply: 0, + replyParentUri: null, + replyRootUri: null, + isQuote: 0, + quotedPostUri: null, + isRepost: 0, + repostUri: null, + repostCid: null, + originalPostUri: null, + likeCount: 0, + repostCount: 0, + replyCount: 0, + quoteCount: 0, + viewerLiked: 0, + likeUri: null, + viewerReposted: 0, + viewerBookmarked: 0, + createdAt: "2026-01-01T00:00:00.000Z", + savedAt: 1_000, + deletedPostAt: null, + deletedRepostAt: null, + deletedLikeAt: null, + deletedBookmarkAt: null, + ...overrides, + }; +} + +/** An archive's row, as it arrives at the plan: no local-only columns set. */ +function archived(row: MobilePostWrite): ExistingPostRow { + return { ...row, preserve: 0 }; +} + +function existing( + overrides: Partial = {}, +): ExistingAccountRows { + return { + profiles: [], + posts: [], + postMedia: [], + postExternals: [], + bookmarks: [], + follows: [], + conversations: [], + messages: [], + mediaAssets: [], + ...overrides, + }; +} + +function incoming( + overrides: Partial = {}, +): ExistingAccountRows { + return { + profiles: [], + posts: [], + postMedia: [], + postExternals: [], + bookmarks: [], + follows: [], + conversations: [], + messages: [], + mediaAssets: [], + ...overrides, + }; +} + +describe("planning a Cyd Bluesky archive merge", () => { + it("adds a record the account no longer holds, and previews it as a restoration", () => { + const plan = planBlueskyArchiveMerge( + existing(), + incoming({ posts: [archived(post({ text: "a post deleted from Cyd" }))] }), + ); + + expect(plan.posts).toHaveLength(1); + expect(plan.posts[0]).toMatchObject({ + uri: "at://did:plc:archive/app.bsky.feed.post/one", + text: "a post deleted from Cyd", + preserve: 0, + }); + expect(plan.summary.posts).toEqual({ added: 1, updated: 0, unchanged: 0 }); + expect(plan.summary.restorations.total).toBe(1); + expect(plan.summary.restorations.records).toEqual([ + { + category: "posts", + id: "at://did:plc:archive/app.bsky.feed.post/one", + text: "a post deleted from Cyd", + createdAt: "2026-01-01T00:00:00.000Z", + }, + ]); + }); + + it("writes nothing when the archive holds what the account already holds", () => { + const plan = planBlueskyArchiveMerge( + existing({ posts: [{ ...post(), preserve: 0 }] }), + incoming({ posts: [archived(post())] }), + ); + + expect(plan.posts).toEqual([]); + expect(plan.summary.posts).toEqual({ added: 0, updated: 0, unchanged: 1 }); + expect(plan.summary.restorations.total).toBe(0); + }); + it("does not let a quieter archive blank out what the account knows", () => { + const plan = planBlueskyArchiveMerge( + existing({ + posts: [ + { + ...post({ text: "the full text", langs: "en", savedAt: 5_000 }), + preserve: 0, + }, + ], + }), + incoming({ posts: [archived(post({ text: "", langs: null, savedAt: 9_000 }))] }), + ); + + expect(plan.posts).toEqual([]); + expect(plan.summary.posts.unchanged).toBe(1); + }); + + it("takes the newer observation when both sides hold a value", () => { + const plan = planBlueskyArchiveMerge( + existing({ + posts: [ + { + ...post({ text: "before an edit", likeCount: 1, savedAt: 5_000 }), + preserve: 0, + }, + ], + }), + incoming({ + posts: [ + archived(post({ text: "after an edit", likeCount: 4, savedAt: 9_000 })), + ], + }), + ); + + expect(plan.posts[0]).toMatchObject({ + text: "after an edit", + likeCount: 4, + // The union of when Cyd held it is when it first did. + savedAt: 5_000, + }); + expect(plan.summary.posts).toEqual({ added: 0, updated: 1, unchanged: 0 }); + }); + + it("keeps a like the archive was taken before, and takes one it was taken after", () => { + const plan = planBlueskyArchiveMerge( + existing({ + posts: [ + { ...post({ viewerLiked: 1, savedAt: 9_000 }), preserve: 0 }, + { + ...post({ + uri: "at://did:plc:archive/app.bsky.feed.post/two", + viewerLiked: 0, + savedAt: 9_000, + }), + preserve: 0, + }, + ], + }), + incoming({ + posts: [ + archived(post({ viewerLiked: 0, savedAt: 1_000 })), + archived( + post({ + uri: "at://did:plc:archive/app.bsky.feed.post/two", + viewerLiked: 1, + savedAt: 1_000, + }), + ), + ], + }), + ); + + expect(plan.posts.map((row) => [row.uri, row.viewerLiked])).toEqual([ + ["at://did:plc:archive/app.bsky.feed.post/one", 1], + ["at://did:plc:archive/app.bsky.feed.post/two", 1], + ]); + }); + + it("keeps a source deletion either side observed, at the earlier time", () => { + const plan = planBlueskyArchiveMerge( + existing({ + posts: [{ ...post({ deletedPostAt: null }), preserve: 0 }], + }), + incoming({ posts: [archived(post({ deletedPostAt: 4_000 }))] }), + ); + + expect(plan.posts[0]).toMatchObject({ deletedPostAt: 4_000 }); + }); + + it("never clears a post the person chose to preserve", () => { + const plan = planBlueskyArchiveMerge( + existing({ + posts: [{ ...post({ text: "kept", savedAt: 1_000 }), preserve: 1 }], + }), + incoming({ posts: [archived(post({ text: "kept again", savedAt: 9_000 }))] }), + ); + + expect(plan.posts[0]).toMatchObject({ text: "kept again", preserve: 1 }); + }); + + it("leaves data the archive says nothing about out of the plan entirely", () => { + const untouched = { + ...post({ uri: "at://did:plc:archive/app.bsky.feed.post/local" }), + preserve: 0, + }; + + const plan = planBlueskyArchiveMerge( + existing({ posts: [untouched] }), + incoming({ posts: [] }), + ); + + expect(plan.posts).toEqual([]); + expect(plan.summary.posts).toEqual({ added: 0, updated: 0, unchanged: 0 }); + expect(plan.summary.restorations.total).toBe(0); + }); + + it("upgrades a failed download when the archive brought the file", () => { + const plan = planBlueskyArchiveMerge( + existing({ + mediaAssets: [ + { + contentCid: "bafy-one", + mediaType: "image", + mimeType: "image/jpeg", + byteLength: null, + localPath: null, + sourceUrl: "https://cdn.bsky.app/one.jpg", + sourceDid: ARCHIVE_DID, + sourceMetadataJSON: null, + downloadState: "failed", + lastError: "Network request failed", + attemptCount: 3, + downloadedAt: null, + }, + ], + }), + incoming({ + mediaAssets: [ + { + contentCid: "bafy-one", + mediaType: "image", + mimeType: "image/jpeg", + byteLength: 1_024, + localPath: "file:///accounts/media/sha256-abc", + sourceUrl: "https://cdn.bsky.app/one.jpg", + sourceDid: ARCHIVE_DID, + sourceMetadataJSON: null, + downloadState: "complete", + lastError: null, + attemptCount: 0, + downloadedAt: 7_000, + }, + ], + }), + ); + + expect(plan.mediaAssets[0]).toMatchObject({ + downloadState: "complete", + localPath: "file:///accounts/media/sha256-abc", + lastError: null, + // What this device has already been through with the file is its own. + attemptCount: 3, + }); + }); + + it("does not trade a file this device holds for one it cannot open", () => { + const stored = { + contentCid: "bafy-one", + mediaType: "image" as const, + mimeType: "image/jpeg", + byteLength: 1_024, + localPath: "file:///accounts/media/sha256-abc", + sourceUrl: "https://cdn.bsky.app/one.jpg", + sourceDid: ARCHIVE_DID, + sourceMetadataJSON: null, + downloadState: "complete" as const, + lastError: null, + attemptCount: 0, + downloadedAt: 7_000, + }; + + const plan = planBlueskyArchiveMerge( + existing({ mediaAssets: [stored] }), + incoming({ + mediaAssets: [ + { + ...stored, + localPath: null, + byteLength: null, + downloadState: "failed", + lastError: "This file was not included in the archive.", + attemptCount: 0, + downloadedAt: null, + }, + ], + }), + ); + + expect(plan.mediaAssets).toEqual([]); + }); +}); diff --git a/services/archive-merge/__tests__/merge.test.ts b/services/archive-merge/__tests__/merge.test.ts new file mode 100644 index 0000000..76404cc --- /dev/null +++ b/services/archive-merge/__tests__/merge.test.ts @@ -0,0 +1,296 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import type { DatabaseSync } from "node:sqlite"; + +import { + buildTotalCountQuery, + getTotalCountParams, + type BrowseType, +} from "@/components/account/browse-shared"; +import { + runBlueskyArchiveIntake, + type PreparedBlueskyArchive, +} from "@/services/archive-import"; +import { restoreBlueskyArchiveAccount } from "@/services/archive-restore"; +import { createMemoryByteReader } from "@/testUtils/archiveFixtures"; +import { + createDiskBlueskyArchiveIntakeEnvironment, + createNodeBlueskyArchiveRestoreEnvironment, + type NodeRestoreEnvironment, +} from "@/testUtils/archiveEnvironments"; + +import { + commitBlueskyArchiveMerge, + previewBlueskyArchiveMerge, +} from "../merge"; + +/** + * Importing a Cyd Bluesky archive into the Bluesky local account that already + * holds its identity. + * + * The archive is the committed real-data fixture, and the account it merges + * into is one this repo's own restore built out of that same fixture — so the + * interesting cases are the ones a recovery actually meets: importing twice, + * importing after somebody deleted things from Cyd, and importing over an + * account whose settings and schedule are none of the archive's business. + */ + +const FIXTURE_DIRECTORY = path.join( + __dirname, + "../../../testUtils/fixtures/bluesky-archive", +); +const ACCOUNT_DID = "did:plc:yn45xekh5kqrat27w6rmafcg"; + +jest.setTimeout(120_000); + +function fixtureBytes(name: string): Uint8Array { + return new Uint8Array(fs.readFileSync(path.join(FIXTURE_DIRECTORY, name))); +} + +type Harness = { + root: string; + environment: NodeRestoreEnvironment; + accountUuid: string; + accountId: number; + database: DatabaseSync; + /** Stage the fixture again, the way a second import would. */ + prepare: (intakeId: string) => Promise; +}; + +async function stage( + root: string, + intakeId: string, + name = "complete.cyd", +): Promise { + const outcome = await runBlueskyArchiveIntake( + createDiskBlueskyArchiveIntakeEnvironment(path.join(root, "intake")), + { + intakeId, + sourceUri: `file:///fixtures/${name}`, + openReader: async () => createMemoryByteReader(fixtureBytes(name)), + }, + ); + if (outcome.status !== "prepared") { + throw new Error(`intake did not prepare ${name}: ${outcome.status}`); + } + return outcome; +} + +/** An account restored from the fixture, ready to have the fixture merged in. */ +async function restoredAccount(): Promise { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "cyd-merge-")); + const environment = createNodeBlueskyArchiveRestoreEnvironment({ + root: path.join(root, "app"), + }); + const prepared = await stage(root, "intake-restore"); + const restored = await restoreBlueskyArchiveAccount(environment, { + archive: { + intakeId: prepared.intakeId, + stagingRoot: prepared.stagingRoot, + }, + }); + + return { + root, + environment, + accountUuid: restored.accountUuid, + accountId: restored.accountId, + database: environment.openRestoredAccountDatabase(restored.accountUuid), + prepare: (intakeId) => stage(root, intakeId), + }; +} + +function browseCount(database: DatabaseSync, type: BrowseType): number { + const row = database + .prepare(buildTotalCountQuery(type)) + .get(...(getTotalCountParams(type, ACCOUNT_DID) as never[])) as { + count: number; + }; + return row.count; +} + +function countRows(database: DatabaseSync, table: string): number { + return ( + database.prepare(`SELECT COUNT(*) AS count FROM ${table};`).get() as { + count: number; + } + ).count; +} + +function identity(harness: Harness) { + return { + uuid: harness.accountUuid, + did: ACCOUNT_DID, + handle: "glittertop-cyd.bsky.social", + }; +} + +async function mergeFixture(harness: Harness, intakeId: string) { + const prepared = await harness.prepare(intakeId); + const preview = await previewBlueskyArchiveMerge(harness.environment, { + archive: { + intakeId: prepared.intakeId, + stagingRoot: prepared.stagingRoot, + }, + account: identity(harness), + }); + const result = await commitBlueskyArchiveMerge(harness.environment, preview); + return { prepared, preview, result }; +} + +describe("merging a Cyd Bluesky archive into an account that holds its identity", () => { + let harness: Harness; + + beforeAll(async () => { + harness = await restoredAccount(); + }); + + afterAll(() => { + harness.database.close(); + harness.environment.close(); + fs.rmSync(harness.root, { recursive: true, force: true }); + }); + + it("changes nothing when the same archive is imported a second time", async () => { + const before = { + posts: browseCount(harness.database, "posts"), + likes: browseCount(harness.database, "likes"), + rows: countRows(harness.database, "post"), + media: countRows(harness.database, "media_asset"), + }; + + const { preview, result } = await mergeFixture(harness, "intake-again"); + + expect(preview.summary.restorations.total).toBe(0); + expect(preview.summary.posts).toEqual({ + added: 0, + updated: 0, + unchanged: before.rows, + }); + expect(result.written).toBe(0); + expect({ + posts: browseCount(harness.database, "posts"), + likes: browseCount(harness.database, "likes"), + rows: countRows(harness.database, "post"), + media: countRows(harness.database, "media_asset"), + }).toEqual(before); + }); + + it("leaves no staging behind once the merge is committed", async () => { + const { prepared } = await mergeFixture(harness, "intake-staging"); + + expect(fs.existsSync(prepared.stagingRoot)).toBe(false); + }); + + it("brings back records deleted from Cyd, and names them before committing", async () => { + const doomed = ( + harness.database + .prepare( + `SELECT uri FROM post WHERE authorDid = ? ORDER BY uri LIMIT 3;`, + ) + .all(ACCOUNT_DID) as { uri: string }[] + ).map((row) => row.uri); + const before = browseCount(harness.database, "posts"); + for (const uri of doomed) { + harness.database.prepare("DELETE FROM post_media WHERE postUri = ?;").run(uri); + harness.database.prepare("DELETE FROM post_external WHERE postUri = ?;").run(uri); + harness.database.prepare("DELETE FROM post WHERE uri = ?;").run(uri); + } + expect(browseCount(harness.database, "posts")).toBe(before - doomed.length); + + const prepared = await harness.prepare("intake-restoration"); + const preview = await previewBlueskyArchiveMerge(harness.environment, { + archive: { + intakeId: prepared.intakeId, + stagingRoot: prepared.stagingRoot, + }, + account: identity(harness), + }); + + expect(preview.summary.restorations.total).toBe(doomed.length); + expect( + preview.summary.restorations.records + .map((record) => record.id) + .sort(), + ).toEqual([...doomed].sort()); + // Nothing is written until the restorations have been shown. + expect(browseCount(harness.database, "posts")).toBe(before - doomed.length); + + await commitBlueskyArchiveMerge(harness.environment, preview); + + expect(browseCount(harness.database, "posts")).toBe(before); + }); + + it("keeps the account's own identifier, settings and schedule", async () => { + const main = harness.environment.mainDatabase; + main + .prepare( + `UPDATE bsky_account + SET settingSavePosts = 0, + settingDeleteLikes = 1, + settingScheduleDeletion = 1, + settingScheduleDeletionFrequency = 'monthly', + settingScheduleDeletionTime = '07:30' + WHERE id = (SELECT bskyAccountID FROM account WHERE uuid = ?);`, + ) + .run(harness.accountUuid); + const settingsBefore = main + .prepare( + `SELECT b.* FROM bsky_account b + INNER JOIN account a ON a.bskyAccountID = b.id + WHERE a.uuid = ?;`, + ) + .get(harness.accountUuid); + + const { result } = await mergeFixture(harness, "intake-settings"); + + expect(result.accountUuid).toBe(harness.accountUuid); + expect( + main + .prepare( + `SELECT b.* FROM bsky_account b + INNER JOIN account a ON a.bskyAccountID = b.id + WHERE a.uuid = ?;`, + ) + .get(harness.accountUuid), + ).toEqual(settingsBefore); + }); + + it("keeps a post the person chose to preserve", async () => { + const [{ uri }] = harness.database + .prepare(`SELECT uri FROM post ORDER BY uri LIMIT 1;`) + .all() as { uri: string }[]; + harness.database + .prepare("UPDATE post SET preserve = 1 WHERE uri = ?;") + .run(uri); + + await mergeFixture(harness, "intake-preserve"); + + expect( + ( + harness.database + .prepare("SELECT preserve FROM post WHERE uri = ?;") + .get(uri) as { preserve: number } + ).preserve, + ).toBe(1); + }); + + it("refuses an archive belonging to a different Bluesky identity", async () => { + const prepared = await harness.prepare("intake-mismatch"); + + await expect( + previewBlueskyArchiveMerge(harness.environment, { + archive: { + intakeId: prepared.intakeId, + stagingRoot: prepared.stagingRoot, + }, + account: { + uuid: harness.accountUuid, + did: "did:plc:somebody-else", + handle: "somebody.bsky.social", + }, + }), + ).rejects.toThrow(/identity/i); + }); +}); diff --git a/services/archive-merge/account-rows.ts b/services/archive-merge/account-rows.ts new file mode 100644 index 0000000..7ed17f4 --- /dev/null +++ b/services/archive-merge/account-rows.ts @@ -0,0 +1,100 @@ +import type { MergeableAccountDatabase } from "./ports"; +import type { + ExistingAccountRows, + ExistingMediaAssetRow, + ExistingPostRow, + MobileBookmarkWrite, + MobileConversationWrite, + MobileFollowWrite, + MobileMessageWrite, + MobilePostExternalWrite, + MobilePostMediaWrite, + MobileProfileWrite, +} from "./rows"; + +/** + * Reading a Bluesky local account back out in the shape a restore writes it. + * + * This is the mirror of `services/archive-restore/account-writer.ts`, and it + * exists so the merge compares like with like: the archive's side arrives as + * Mobile rows through the translation, and this turns the account's own side + * into the same rows. Columns Mobile fills in for itself — a row id, the + * denormalized aspect ratio — are left out, because nothing in a union has an + * opinion about them. + * + * `viewer*` columns are nullable in Mobile's schema and are read as flags + * here. A null and a zero mean the same thing to browse, and normalizing them + * is what keeps a second import of the same archive from writing rows back + * unchanged. + */ + +const flag = (value: number | null): number => (value === 1 ? 1 : 0); + +export async function readExistingAccountRows( + database: MergeableAccountDatabase, +): Promise { + const posts = await database.all( + `SELECT uri, cid, authorDid, text, facetsJSON, embedType, embedJSON, langs, + isReply, replyParentUri, replyRootUri, isQuote, quotedPostUri, + isRepost, repostUri, repostCid, originalPostUri, + likeCount, repostCount, replyCount, quoteCount, + viewerLiked, likeUri, viewerReposted, viewerBookmarked, + createdAt, savedAt, + deletedPostAt, deletedRepostAt, deletedLikeAt, deletedBookmarkAt, + preserve + FROM post ORDER BY uri;`, + ); + + return { + profiles: await database.all( + `SELECT did, handle, displayName, avatarUrl, savedAt, updatedAt + FROM profile ORDER BY did;`, + ), + posts: posts.map((post) => ({ + ...post, + isReply: flag(post.isReply), + isQuote: flag(post.isQuote), + isRepost: flag(post.isRepost), + viewerLiked: flag(post.viewerLiked), + viewerReposted: flag(post.viewerReposted), + viewerBookmarked: flag(post.viewerBookmarked), + preserve: flag(post.preserve), + })), + postMedia: await database.all( + `SELECT postUri, position, mediaType, blobCid, mimeType, alt, + width, height, thumbUrl, fullsizeUrl, playlistUrl, + downloadedAt, assetCid + FROM post_media ORDER BY postUri, position;`, + ), + postExternals: await database.all( + `SELECT postUri, uri, title, description, thumbUrl, thumbLocalPath + FROM post_external ORDER BY postUri;`, + ), + bookmarks: await database.all( + `SELECT subjectUri, postAuthorDid, postAuthorHandle, postText, + postCreatedAt, savedAt, deletedAt + FROM bookmark ORDER BY subjectUri;`, + ), + follows: await database.all( + `SELECT uri, cid, subjectDid, handle, displayName, avatarUrl, + createdAt, savedAt, unfollowedAt + FROM follow ORDER BY uri;`, + ), + conversations: await database.all( + `SELECT convoId, rev, memberDids, muted, lastMessageId, lastMessageText, + lastMessageSentAt, lastMessageSenderDid, savedAt, updatedAt, leftAt + FROM conversation ORDER BY convoId;`, + ), + messages: await database.all( + `SELECT messageId, convoId, rev, senderDid, text, facetsJSON, embedJSON, + sentAt, savedAt, deletedAt + FROM message ORDER BY messageId;`, + ), + mediaAssets: await database.all( + `SELECT contentCid, mediaType, mimeType, byteLength, localPath, sourceUrl, + sourceDid, sourceMetadataJSON, downloadState, lastError, + attemptCount, downloadedAt + FROM media_asset ORDER BY contentCid;`, + ), + }; +} diff --git a/services/archive-merge/destination.ts b/services/archive-merge/destination.ts new file mode 100644 index 0000000..b06f4cc --- /dev/null +++ b/services/archive-merge/destination.ts @@ -0,0 +1,37 @@ +import type { LocalAccountIdentity } from "@/services/archive-restore"; + +/** + * Where a picked Cyd Bluesky archive is committed. + * + * Routing a Cyd Bluesky archive and merging one are the same decision, taken + * once: intake reports the Bluesky identity's DID (#95), and whether this + * installation already holds that identity decides everything that follows. + * Nothing here reads the archive's contents, and nothing matches on a handle + * or a local-account UUID — a handle moves between identities, and a UUID is + * this installation's own name for one. + */ +export type BlueskyArchiveImportDestination = + /** No Bluesky local account for this identity: restore a new one (#96). */ + | { kind: "restore" } + /** Exactly one holds it: the archive is a recovery union into that account. */ + | { kind: "merge"; account: LocalAccountIdentity } + /** + * Several hold it, so there is no unambiguous destination. The duplicates + * are reconciled into one surviving Bluesky local account first (ADR 0011). + */ + | { kind: "reconcile"; did: string; accounts: LocalAccountIdentity[] }; + +export function chooseBlueskyArchiveImportDestination( + archiveDid: string, + existing: LocalAccountIdentity[], +): BlueskyArchiveImportDestination { + const holders = existing.filter((account) => account.did === archiveDid); + + if (holders.length === 0) { + return { kind: "restore" }; + } + if (holders.length === 1) { + return { kind: "merge", account: holders[0] }; + } + return { kind: "reconcile", did: archiveDid, accounts: holders }; +} diff --git a/services/archive-merge/duplicates.ts b/services/archive-merge/duplicates.ts new file mode 100644 index 0000000..5b6cf98 --- /dev/null +++ b/services/archive-merge/duplicates.ts @@ -0,0 +1,319 @@ +import type { LocalAccountIdentity } from "@/services/archive-restore"; + +import { readExistingAccountRows } from "./account-rows"; +import { BlueskyArchiveMergeError } from "./errors"; +import { + planBlueskyArchiveMerge, + type BlueskyArchiveMergeSummary, +} from "./merge-plan"; +import { countPlannedWrites, writeMergedAccountRows } from "./merge-writer"; +import type { + BlueskyArchiveMergeEnvironment, + ReconcilableAccountSettings, +} from "./ports"; +import type { ExistingAccountRows } from "./rows"; + +/** + * Collapsing a Bluesky identity this installation holds more than once. + * + * A migration, a restore that went sideways, or two people sharing a phone can + * leave one DID with several Bluesky local accounts, and then an archive + * import has no unambiguous destination. Cyd does not pick one: it shows what + * each account holds and what each is set to do, and the person says which + * local-account UUID survives and whose settings it keeps (ADR 0011). + * + * What happens afterwards is the same union an archive import performs — the + * surviving account ends up holding everything all of them held — followed by + * the removal of the others, which is what leaves one Bluesky local account + * per identity for imports to aim at. + */ + +export type DuplicateBlueskyIdentity = { + did: string; + accounts: LocalAccountIdentity[]; +}; + +export type DuplicateAccountCounts = { + posts: number; + bookmarks: number; + follows: number; + chats: number; + messages: number; + profiles: number; + media: number; +}; + +export type DuplicateAccountPreview = { + uuid: string; + handle: string | null; + counts: DuplicateAccountCounts; + settings: ReconcilableAccountSettings; +}; + +export type DuplicateReconciliationPreview = { + did: string; + accounts: DuplicateAccountPreview[]; +}; + +export type DuplicateReconciliationChoice = { + did: string; + /** Every Bluesky local account this installation has, as routing saw them. */ + accounts: LocalAccountIdentity[]; + /** The local-account UUID the person chose to keep. */ + survivingUuid: string; + /** Whose Bluesky account settings and schedule the survivor keeps. */ + settingsFromUuid: string; +}; + +export type DuplicateReconciliationResult = { + did: string; + survivingUuid: string; + removedUuids: string[]; + /** Rows the survivor gained, by table, across all the accounts it absorbed. */ + summary: BlueskyArchiveMergeSummary[]; + written: number; +}; + +/** Every DID this installation holds more than one Bluesky local account for. */ +export function findDuplicateBlueskyIdentities( + accounts: LocalAccountIdentity[], +): DuplicateBlueskyIdentity[] { + const byDid = new Map(); + for (const account of accounts) { + if (account.did === null) { + // An account with no DID is not a duplicate of anything: nothing can say + // which Bluesky identity it is. + continue; + } + byDid.set(account.did, [...(byDid.get(account.did) ?? []), account]); + } + + return [...byDid.entries()] + .filter(([, holders]) => holders.length > 1) + .map(([did, holders]) => ({ did, accounts: holders })); +} + +/** + * What each of the duplicates holds, so somebody can tell them apart. + * + * Counts rather than a diff: the union means nothing is lost whichever they + * keep, so the question in front of them is which account they recognise as + * theirs and which settings they want to carry on with. + */ +export async function previewDuplicateReconciliation( + environment: BlueskyArchiveMergeEnvironment, + identity: DuplicateBlueskyIdentity, +): Promise { + const holders = holdersOf(identity.did, identity.accounts); + const accounts: DuplicateAccountPreview[] = []; + + for (const account of holders) { + accounts.push({ + uuid: account.uuid, + handle: account.handle, + counts: countRows(await readAccount(environment, account.uuid)), + settings: await environment.readAccountSettings(account.uuid), + }); + } + + return { did: identity.did, accounts }; +} + +/** + * Carry out the choice: one surviving Bluesky local account, holding the union. + * + * Each duplicate is merged in whole — its rows through the same union rules an + * archive import uses, its media files copied into the survivor's own storage + * so the surviving rows point at files that will still be there — and then + * removed. Nothing is deleted before its data has landed, so a reconciliation + * that fails part way leaves the account it was reading from intact. + */ +export async function reconcileDuplicateBlueskyAccounts( + environment: BlueskyArchiveMergeEnvironment, + choice: DuplicateReconciliationChoice, +): Promise { + const holders = holdersOf(choice.did, choice.accounts); + requireHolder(holders, choice.survivingUuid, "keep"); + requireHolder(holders, choice.settingsFromUuid, "take settings from"); + + const doomed = holders.filter( + (account) => account.uuid !== choice.survivingUuid, + ); + const settings = await environment.readAccountSettings( + choice.settingsFromUuid, + ); + + const summary: BlueskyArchiveMergeSummary[] = []; + let written = 0; + + for (const account of doomed) { + const incoming = await adoptMedia( + environment, + account.uuid, + choice.survivingUuid, + await readAccount(environment, account.uuid), + ); + + const survivor = await environment.openAccountDatabase( + choice.survivingUuid, + ); + try { + const plan = planBlueskyArchiveMerge( + await readExistingAccountRows(survivor), + incoming, + ); + await survivor.transaction(async () => { + await writeMergedAccountRows(survivor, plan); + }); + summary.push(plan.summary); + written += countPlannedWrites(plan); + } finally { + await survivor.close(); + } + } + + // Settings are applied before the losing accounts go, so a failure here is + // recoverable: the accounts are still there to choose between. + await environment.applyAccountSettings(choice.survivingUuid, settings); + + for (const account of doomed) { + await environment.removeLocalAccount({ + accountId: null, + accountUuid: account.uuid, + }); + } + + // With one Bluesky local account left for the identity, the rule that there + // can only be one goes back on, so a later archive import has somewhere + // unambiguous to land (ADR 0011). + await environment.enforceOneAccountPerDid(); + + return { + did: choice.did, + survivingUuid: choice.survivingUuid, + removedUuids: doomed.map((account) => account.uuid), + summary, + written, + }; +} + +function holdersOf( + did: string, + accounts: LocalAccountIdentity[], +): LocalAccountIdentity[] { + const holders = accounts.filter((account) => account.did === did); + if (holders.length < 2) { + throw new BlueskyArchiveMergeError( + "duplicate-identity", + "This device no longer has more than one Bluesky account for that identity.", + ); + } + return holders; +} + +function requireHolder( + holders: LocalAccountIdentity[], + uuid: string, + intent: string, +): void { + if (!holders.some((account) => account.uuid === uuid)) { + throw new BlueskyArchiveMergeError( + "unknown-account", + `The Bluesky account Cyd was asked to ${intent} is not one of the accounts being reconciled.`, + ); + } +} + +async function readAccount( + environment: BlueskyArchiveMergeEnvironment, + accountUuid: string, +): Promise { + const database = await environment.openAccountDatabase(accountUuid); + try { + return await readExistingAccountRows(database); + } finally { + await database.close(); + } +} + +/** + * Bring a duplicate's media files across before its rows point at them. + * + * A row is only worth anything if the file it names is still readable after + * the account it belonged to is gone. A file that has already vanished leaves + * the row as a failed download with its source URL, which is what Cyd would + * have held if the download had never succeeded. + */ +async function adoptMedia( + environment: BlueskyArchiveMergeEnvironment, + sourceAccountUuid: string, + targetAccountUuid: string, + rows: ExistingAccountRows, +): Promise { + const moved = new Map(); + + const relocate = async (localPath: string | null): Promise => { + if (localPath === null) { + return null; + } + if (!moved.has(localPath)) { + const stored = await environment.adoptAccountMedia( + sourceAccountUuid, + targetAccountUuid, + localPath, + ); + moved.set(localPath, stored?.uri ?? null); + } + return moved.get(localPath) ?? null; + }; + + const mediaAssets: ExistingAccountRows["mediaAssets"] = []; + for (const asset of rows.mediaAssets) { + const localPath = await relocate(asset.localPath); + mediaAssets.push( + localPath === null && asset.localPath !== null + ? { + ...asset, + localPath: null, + downloadState: "failed", + lastError: "The copy of this file went missing when Cyd merged two accounts for the same Bluesky identity.", + downloadedAt: null, + } + : { ...asset, localPath }, + ); + } + + const postExternals: ExistingAccountRows["postExternals"] = []; + for (const external of rows.postExternals) { + postExternals.push({ + ...external, + thumbLocalPath: await relocate(external.thumbLocalPath), + }); + } + + const profiles: ExistingAccountRows["profiles"] = []; + for (const profile of rows.profiles) { + // Avatars are stored as URLs, and a restored one points into the account's + // own storage, so it has to move with everything else. + const isLocal = profile.avatarUrl?.startsWith("file://") === true; + profiles.push( + isLocal + ? { ...profile, avatarUrl: await relocate(profile.avatarUrl) } + : profile, + ); + } + + return { ...rows, mediaAssets, postExternals, profiles }; +} + +function countRows(rows: ExistingAccountRows): DuplicateAccountCounts { + return { + posts: rows.posts.length, + bookmarks: rows.bookmarks.length, + follows: rows.follows.length, + chats: rows.conversations.length, + messages: rows.messages.length, + profiles: rows.profiles.length, + media: rows.mediaAssets.length, + }; +} diff --git a/services/archive-merge/environment.ts b/services/archive-merge/environment.ts new file mode 100644 index 0000000..e4b2b34 --- /dev/null +++ b/services/archive-merge/environment.ts @@ -0,0 +1,171 @@ +import { Directory, File } from "expo-file-system"; +import { openDatabaseAsync, type SQLiteDatabase } from "expo-sqlite"; + +import { buildAccountPaths } from "@/controllers/BaseAccountController"; +import { + applyAccountMigrations, + blueskyAccountMigrations, +} from "@/database/account-db"; +import { deleteAccount, listAccounts } from "@/database/accounts"; +import { getDatabase } from "@/database"; +import { openPreparedArchive } from "@/services/archive-restore/environment"; +import type { LocalAccountIdentity } from "@/services/archive-restore"; + +import { + RECONCILABLE_SETTING_COLUMNS, + type BlueskyArchiveMergeEnvironment, + type MergeableAccountDatabase, + type ReconcilableAccountSettings, + type ReconcilableSettingColumn, +} from "./ports"; + +/** + * The device-backed implementation of the merge ports. + * + * It is the restore adapter's neighbour and shares its staging reader: the + * difference between the two halves of an import is which account the rows go + * into, not how an archive is read. Everything else here is the same three + * things a phone does differently — SQLite, files, and Cyd's own account + * tables — so the merge logic never sees any of them. + */ + +async function openAccountDatabase(accountUuid: string): Promise { + const paths = buildAccountPaths("bluesky", accountUuid); + new Directory(paths.accountDir).create({ + intermediates: true, + idempotent: true, + }); + const database = await openDatabaseAsync( + paths.dbNameForSQLite, + {}, + paths.dbDirForSQLite, + ); + await database.execAsync("PRAGMA foreign_keys = ON;"); + applyAccountMigrations(database, blueskyAccountMigrations); + return database; +} + +function asMergeableAccountDatabase( + database: SQLiteDatabase, +): MergeableAccountDatabase { + return { + all: async (sql: string) => database.getAllAsync(sql), + run: async (sql, params) => { + await database.runAsync(sql, params as never[]); + }, + transaction: (work) => database.withTransactionAsync(work), + close: async () => database.closeAsync(), + }; +} + +function mediaUri(accountUuid: string, fileName: string): string { + return `${buildAccountPaths("bluesky", accountUuid).mediaDir}${fileName}`; +} + +export function createBlueskyArchiveMergeEnvironment(): BlueskyArchiveMergeEnvironment { + return { + openPreparedArchive, + + listLocalAccountIdentities: async (): Promise => + (await listAccounts()).map((account) => ({ + uuid: account.uuid, + did: account.did, + handle: account.handle, + })), + + openAccountDatabase: async (accountUuid) => + asMergeableAccountDatabase(await openAccountDatabase(accountUuid)), + + storeAccountMedia: async (accountUuid, fileName, write) => { + const paths = buildAccountPaths("bluesky", accountUuid); + new Directory(paths.mediaDir).create({ + intermediates: true, + idempotent: true, + }); + + const file = new File(mediaUri(accountUuid, fileName)); + file.create({ intermediates: true, overwrite: true }); + const handle = file.open(); + let byteLength = 0; + try { + await write((bytes) => { + handle.writeBytes(bytes); + byteLength += bytes.length; + }); + } finally { + handle.close(); + } + return { uri: file.uri, byteLength }; + }, + + accountMediaUri: mediaUri, + + readAccountSettings: async (accountUuid) => { + const main = await getDatabase(); + const row = await main.getFirstAsync( + `SELECT ${RECONCILABLE_SETTING_COLUMNS.join(", ")} + FROM bsky_account b + INNER JOIN account a ON a.bskyAccountID = b.id + WHERE a.uuid = ?;`, + [accountUuid], + ); + return row ?? {}; + }, + + applyAccountSettings: async (accountUuid, settings) => { + const entries = Object.entries(settings) as [ + ReconcilableSettingColumn, + string | number | null, + ][]; + if (entries.length === 0) { + return; + } + const main = await getDatabase(); + await main.runAsync( + `UPDATE bsky_account + SET ${entries.map(([column]) => `${column} = ?`).join(", ")} + WHERE id = (SELECT bskyAccountID FROM account WHERE uuid = ?);`, + [...entries.map(([, value]) => value), accountUuid], + ); + }, + + adoptAccountMedia: async (_sourceAccountUuid, targetAccountUuid, localPath) => { + const source = new File(localPath); + if (!source.exists) { + return null; + } + const paths = buildAccountPaths("bluesky", targetAccountUuid); + new Directory(paths.mediaDir).create({ + intermediates: true, + idempotent: true, + }); + const destination = new File(mediaUri(targetAccountUuid, source.name)); + if (!destination.exists) { + await source.copy(destination); + } + return { uri: destination.uri, byteLength: destination.size ?? 0 }; + }, + + enforceOneAccountPerDid: async () => { + const main = await getDatabase(); + await main.execAsync( + `CREATE UNIQUE INDEX IF NOT EXISTS idx_bsky_account_did + ON bsky_account(did);`, + ); + }, + + removeLocalAccount: async (account) => { + if (account.accountId !== null) { + await deleteAccount(account.accountId); + } + const directory = new Directory( + buildAccountPaths("bluesky", account.accountUuid).accountDir, + ); + if (directory.exists) { + directory.delete(); + } + }, + + now: () => new Date(), + }; +} diff --git a/services/archive-merge/errors.ts b/services/archive-merge/errors.ts new file mode 100644 index 0000000..46825fa --- /dev/null +++ b/services/archive-merge/errors.ts @@ -0,0 +1,24 @@ +/** + * Why a prepared Cyd Bluesky archive could not be merged. + * + * Intake has proved the package intact (#95) and the shared version 2 adapter + * raises what it thinks of the interchange database, so what is left here is + * about destinations: an archive pointed at the wrong Bluesky local account, a + * Bluesky identity this installation holds twice, or a reconciliation asked to + * keep an account that is not one of the duplicates. The messages are written + * for the person holding the phone. + */ +export type BlueskyArchiveMergeErrorCode = + | "identity-mismatch" + | "duplicate-identity" + | "unknown-account"; + +export class BlueskyArchiveMergeError extends Error { + readonly code: BlueskyArchiveMergeErrorCode; + + constructor(code: BlueskyArchiveMergeErrorCode, message: string) { + super(message); + this.name = "BlueskyArchiveMergeError"; + this.code = code; + } +} diff --git a/services/archive-merge/index.ts b/services/archive-merge/index.ts new file mode 100644 index 0000000..f0d503d --- /dev/null +++ b/services/archive-merge/index.ts @@ -0,0 +1,64 @@ +/** + * Merging a Cyd Bluesky archive into a Bluesky local account Cyd already has. + * + * A Bluesky archive import is one act with two possible endings: an identity + * this installation does not hold is restored as a new Bluesky local account + * (#96), and one it does hold is merged here. The merge is a recovery union — + * everything either side knows survives, records sharing a stable Bluesky + * identifier collapse into one, and the account's own settings, schedules, + * Bluesky connection and local choices are not the archive's business. + * + * Three things leave this module: where an archive should go, what merging it + * would do, and how a Bluesky identity this installation holds twice is + * reconciled down to one (ADR 0011). The union rules, the row reader and the + * writer are internal, and the tests reach for them directly. + */ + +export { chooseBlueskyArchiveImportDestination } from "./destination"; +export type { BlueskyArchiveImportDestination } from "./destination"; +export { + findDuplicateBlueskyIdentities, + previewDuplicateReconciliation, + reconcileDuplicateBlueskyAccounts, +} from "./duplicates"; +export type { + DuplicateBlueskyIdentity, + DuplicateAccountPreview, + DuplicateReconciliationChoice, + DuplicateReconciliationPreview, + DuplicateReconciliationResult, +} from "./duplicates"; +export { createBlueskyArchiveMergeEnvironment } from "./environment"; +export { BlueskyArchiveMergeError } from "./errors"; +export type { BlueskyArchiveMergeErrorCode } from "./errors"; +export { + commitBlueskyArchiveMerge, + previewBlueskyArchiveMerge, +} from "./merge"; +export type { + BlueskyArchiveMergePhase, + BlueskyArchiveMergePreview, + BlueskyArchiveMergeProgress, + BlueskyArchiveMergeRequest, + BlueskyArchiveMergeResult, + MergedAssetSummary, +} from "./merge"; +export { planBlueskyArchiveMerge } from "./merge-plan"; +export type { + BlueskyArchiveMergeCounts, + BlueskyArchiveMergePlan, + BlueskyArchiveMergeSummary, + RestorationPreview, +} from "./merge-plan"; +export { RECONCILABLE_SETTING_COLUMNS } from "./ports"; +export type { + BlueskyArchiveMergeEnvironment, + MergeableAccountDatabase, + ReconcilableAccountSettings, + ReconcilableSettingColumn, +} from "./ports"; +export type { + ExistingAccountRows, + ExistingMediaAssetRow, + ExistingPostRow, +} from "./rows"; diff --git a/services/archive-merge/merge-plan.ts b/services/archive-merge/merge-plan.ts new file mode 100644 index 0000000..a5810e0 --- /dev/null +++ b/services/archive-merge/merge-plan.ts @@ -0,0 +1,581 @@ +import { + earliest, + latest, + preferPopulated, + unionFlag, +} from "./union"; +import type { + ExistingAccountRows, + ExistingMediaAssetRow, + ExistingPostRow, + MobileBookmarkWrite, + MobileConversationWrite, + MobileFollowWrite, + MobileMessageWrite, + MobilePostExternalWrite, + MobilePostMediaWrite, + MobileProfileWrite, +} from "./rows"; + +/** + * The recovery union, decided before anything is written. + * + * A Bluesky archive import into an account this installation already holds is + * a union, not a replacement: every record either side knows about survives, + * records that share a stable Bluesky identifier collapse into one, and an + * archive that is quieter than the account — an older export, a partial one — + * never turns what the account knows back into absence. + * + * The plan is the whole decision. It carries the rows that would change and + * the counts somebody is shown before agreeing to it, so committing is just + * writing what was previewed (AC: "previewed explicitly before commit"). + */ + +export type BlueskyArchiveMergeCounts = { + /** Rows the account does not hold, which the archive brings back. */ + added: number; + /** Rows both sides hold, which the archive has something to add to. */ + updated: number; + unchanged: number; +}; + +/** + * One record the account no longer holds. + * + * Restoring these is the point of a recovery import and also the one thing it + * does that somebody might not want, because a record can be absent because + * they deleted it from Cyd on purpose (Bluesky local deletion). So they are + * named in the preview rather than counted in a total. + */ +export type RestorationPreview = { + category: "posts" | "bookmarks" | "follows" | "chats" | "messages"; + id: string; + text: string | null; + createdAt: string | null; +}; + +/** How many named restorations the preview carries before it stops listing. */ +const MAX_LISTED_RESTORATIONS = 50; + +export type BlueskyArchiveMergeSummary = { + profiles: BlueskyArchiveMergeCounts; + posts: BlueskyArchiveMergeCounts; + postMedia: BlueskyArchiveMergeCounts; + postExternals: BlueskyArchiveMergeCounts; + bookmarks: BlueskyArchiveMergeCounts; + follows: BlueskyArchiveMergeCounts; + conversations: BlueskyArchiveMergeCounts; + messages: BlueskyArchiveMergeCounts; + mediaAssets: BlueskyArchiveMergeCounts; + restorations: { + total: number; + /** The first `MAX_LISTED_RESTORATIONS`, for somebody to look through. */ + records: RestorationPreview[]; + }; +}; + +export type BlueskyArchiveMergePlan = { + profiles: MobileProfileWrite[]; + posts: ExistingPostRow[]; + postMedia: MobilePostMediaWrite[]; + postExternals: MobilePostExternalWrite[]; + bookmarks: MobileBookmarkWrite[]; + follows: MobileFollowWrite[]; + conversations: MobileConversationWrite[]; + messages: MobileMessageWrite[]; + mediaAssets: ExistingMediaAssetRow[]; + summary: BlueskyArchiveMergeSummary; +}; + +type TableRules = { + /** The stable Bluesky identifier two copies of a record share. */ + key: (row: Row) => string; + union: (local: Row, incoming: Row) => Row; +}; + +type TableResult = { + writes: Row[]; + counts: BlueskyArchiveMergeCounts; + added: Row[]; +}; + +/** + * Merge one table, writing only what would actually change. + * + * The comparison against the stored row is what makes a repeated import free: + * a union that comes back equal to what is already there produces no write at + * all, so importing the same Cyd Bluesky archive twice is indistinguishable + * from importing it once. + */ +function mergeTable( + local: Row[], + incoming: Row[], + rules: TableRules, +): TableResult { + const stored = new Map(local.map((row) => [rules.key(row), row])); + const writes: Row[] = []; + const added: Row[] = []; + let updated = 0; + let unchanged = 0; + + for (const row of incoming) { + const existing = stored.get(rules.key(row)); + if (!existing) { + writes.push(row); + added.push(row); + continue; + } + const merged = rules.union(existing, row); + if (sameRow(existing, merged)) { + unchanged += 1; + continue; + } + writes.push(merged); + updated += 1; + } + + return { + writes, + added, + counts: { added: added.length, updated, unchanged }, + }; +} + +function sameRow(left: object, right: object): boolean { + const keys = Object.keys(left); + return keys.every( + (key) => + (left as Record)[key] === + (right as Record)[key], + ); +} + +/** + * Union two accounts' worth of Bluesky saved data. + * + * Both sides are the same shape on purpose: importing a Cyd Bluesky archive + * and collapsing two duplicate Bluesky local accounts (ADR 0011) are the same + * union, so they are the same code and cannot drift into disagreeing about + * what "the same record" means. + */ +export function planBlueskyArchiveMerge( + existing: ExistingAccountRows, + incoming: ExistingAccountRows, +): BlueskyArchiveMergePlan { + const profiles = mergeTable(existing.profiles, incoming.profiles, { + key: (row) => row.did, + union: unionProfile, + }); + const posts = mergeTable(existing.posts, incoming.posts, { + key: (row) => row.uri, + union: unionPost, + }); + const postMedia = mergeTable(existing.postMedia, incoming.postMedia, { + key: (row) => `${row.postUri}#${row.position}`, + union: unionPostMedia, + }); + const postExternals = mergeTable( + existing.postExternals, + incoming.postExternals, + { key: (row) => row.postUri, union: unionPostExternal }, + ); + const bookmarks = mergeTable(existing.bookmarks, incoming.bookmarks, { + key: (row) => row.subjectUri, + union: unionBookmark, + }); + const follows = mergeTable(existing.follows, incoming.follows, { + key: (row) => row.uri, + union: unionFollow, + }); + const conversations = mergeTable( + existing.conversations, + incoming.conversations, + { key: (row) => row.convoId, union: unionConversation }, + ); + const messages = mergeTable(existing.messages, incoming.messages, { + key: (row) => row.messageId, + union: unionMessage, + }); + const mediaAssets = mergeTable(existing.mediaAssets, incoming.mediaAssets, { + key: (row) => row.contentCid, + union: unionMediaAsset, + }); + + return { + profiles: profiles.writes, + posts: posts.writes, + postMedia: postMedia.writes, + postExternals: postExternals.writes, + bookmarks: bookmarks.writes, + follows: follows.writes, + conversations: conversations.writes, + messages: messages.writes, + mediaAssets: mediaAssets.writes, + summary: { + profiles: profiles.counts, + posts: posts.counts, + postMedia: postMedia.counts, + postExternals: postExternals.counts, + bookmarks: bookmarks.counts, + follows: follows.counts, + conversations: conversations.counts, + messages: messages.counts, + mediaAssets: mediaAssets.counts, + restorations: summarizeRestorations({ + posts: posts.added, + bookmarks: bookmarks.added, + follows: follows.added, + conversations: conversations.added, + messages: messages.added, + }), + }, + }; +} + +/** + * The records coming back, in the order somebody would read them. + * + * Only records count: a profile or a media file arrives because a record + * needs it, and listing them would bury the posts and messages the person is + * actually being asked about. + */ +function summarizeRestorations(added: { + posts: ExistingPostRow[]; + bookmarks: MobileBookmarkWrite[]; + follows: MobileFollowWrite[]; + conversations: MobileConversationWrite[]; + messages: MobileMessageWrite[]; +}): BlueskyArchiveMergeSummary["restorations"] { + const records: RestorationPreview[] = [ + ...added.posts.map((row) => ({ + category: "posts" as const, + id: row.uri, + text: row.text, + createdAt: row.createdAt, + })), + ...added.bookmarks.map((row) => ({ + category: "bookmarks" as const, + id: row.subjectUri, + text: row.postText, + createdAt: row.postCreatedAt, + })), + ...added.follows.map((row) => ({ + category: "follows" as const, + id: row.uri, + text: row.handle, + createdAt: row.createdAt, + })), + ...added.conversations.map((row) => ({ + category: "chats" as const, + id: row.convoId, + text: row.lastMessageText, + createdAt: row.lastMessageSentAt, + })), + ...added.messages.map((row) => ({ + category: "messages" as const, + id: row.messageId, + text: row.text, + createdAt: row.sentAt, + })), + ]; + + return { + total: records.length, + records: records.slice(0, MAX_LISTED_RESTORATIONS), + }; +} + +function unionProfile( + local: MobileProfileWrite, + incoming: MobileProfileWrite, +): MobileProfileWrite { + const newer = incoming.updatedAt > local.updatedAt; + return { + did: local.did, + handle: preferPopulated(local.handle, incoming.handle, newer), + displayName: preferPopulated(local.displayName, incoming.displayName, newer), + avatarUrl: preferPopulated(local.avatarUrl, incoming.avatarUrl, newer), + savedAt: earliestObservation(local.savedAt, incoming.savedAt), + updatedAt: Math.max(local.updatedAt, incoming.updatedAt), + }; +} + +/** + * One post, as both sides know it. + * + * Viewer state is a union rather than a choice: a like or a repost recorded on + * either side is something that happened, and an archive taken before somebody + * liked a post must not un-like it. Deletion timestamps take the earliest + * either side observed, because that is when Bluesky stopped holding it. + */ +function unionPost( + local: ExistingPostRow, + incoming: ExistingPostRow, +): ExistingPostRow { + const newer = incoming.savedAt > local.savedAt; + const metric = (left: number, right: number): number => + newer ? right : left; + + return { + uri: local.uri, + cid: preferPopulated(local.cid, incoming.cid, newer), + authorDid: preferPopulated(local.authorDid, incoming.authorDid, newer), + text: preferPopulated(local.text, incoming.text, newer), + facetsJSON: preferPopulated(local.facetsJSON, incoming.facetsJSON, newer), + embedType: preferPopulated(local.embedType, incoming.embedType, newer), + embedJSON: preferPopulated(local.embedJSON, incoming.embedJSON, newer), + langs: preferPopulated(local.langs, incoming.langs, newer), + isReply: unionFlag(local.isReply, incoming.isReply), + replyParentUri: preferPopulated( + local.replyParentUri, + incoming.replyParentUri, + newer, + ), + replyRootUri: preferPopulated( + local.replyRootUri, + incoming.replyRootUri, + newer, + ), + isQuote: unionFlag(local.isQuote, incoming.isQuote), + quotedPostUri: preferPopulated( + local.quotedPostUri, + incoming.quotedPostUri, + newer, + ), + isRepost: unionFlag(local.isRepost, incoming.isRepost), + repostUri: preferPopulated(local.repostUri, incoming.repostUri, newer), + repostCid: preferPopulated(local.repostCid, incoming.repostCid, newer), + originalPostUri: preferPopulated( + local.originalPostUri, + incoming.originalPostUri, + newer, + ), + likeCount: metric(local.likeCount, incoming.likeCount), + repostCount: metric(local.repostCount, incoming.repostCount), + replyCount: metric(local.replyCount, incoming.replyCount), + quoteCount: metric(local.quoteCount, incoming.quoteCount), + viewerLiked: unionFlag(local.viewerLiked, incoming.viewerLiked), + likeUri: preferPopulated(local.likeUri, incoming.likeUri, newer), + viewerReposted: unionFlag(local.viewerReposted, incoming.viewerReposted), + viewerBookmarked: unionFlag( + local.viewerBookmarked, + incoming.viewerBookmarked, + ), + createdAt: preferPopulated(local.createdAt, incoming.createdAt, false), + savedAt: earliestObservation(local.savedAt, incoming.savedAt), + deletedPostAt: earliest(local.deletedPostAt, incoming.deletedPostAt), + deletedRepostAt: earliest(local.deletedRepostAt, incoming.deletedRepostAt), + deletedLikeAt: earliest(local.deletedLikeAt, incoming.deletedLikeAt), + deletedBookmarkAt: earliest( + local.deletedBookmarkAt, + incoming.deletedBookmarkAt, + ), + // A person's own "keep this" is a local choice no archive carries, so an + // import can only ever leave it alone. Two duplicate local accounts can + // both carry one, and then either saying "keep" is the answer. + preserve: unionFlag(local.preserve, incoming.preserve), + }; +} + +function unionPostMedia( + local: MobilePostMediaWrite, + incoming: MobilePostMediaWrite, +): MobilePostMediaWrite { + const newer = (incoming.downloadedAt ?? 0) > (local.downloadedAt ?? 0); + return { + postUri: local.postUri, + position: local.position, + mediaType: preferPopulated(local.mediaType, incoming.mediaType, newer), + blobCid: preferPopulated(local.blobCid, incoming.blobCid, newer), + mimeType: preferPopulated(local.mimeType, incoming.mimeType, newer), + alt: preferPopulated(local.alt, incoming.alt, newer), + width: preferPopulated(local.width, incoming.width, newer), + height: preferPopulated(local.height, incoming.height, newer), + thumbUrl: preferPopulated(local.thumbUrl, incoming.thumbUrl, newer), + fullsizeUrl: preferPopulated(local.fullsizeUrl, incoming.fullsizeUrl, newer), + playlistUrl: preferPopulated(local.playlistUrl, incoming.playlistUrl, newer), + downloadedAt: latest(local.downloadedAt, incoming.downloadedAt), + assetCid: preferPopulated(local.assetCid, incoming.assetCid, newer), + }; +} + +function unionPostExternal( + local: MobilePostExternalWrite, + incoming: MobilePostExternalWrite, +): MobilePostExternalWrite { + return { + postUri: local.postUri, + uri: preferPopulated(local.uri, incoming.uri, false), + title: preferPopulated(local.title, incoming.title, false), + description: preferPopulated(local.description, incoming.description, false), + thumbUrl: preferPopulated(local.thumbUrl, incoming.thumbUrl, false), + // A local copy of the thumbnail beats a URL, and beats another local copy + // only if this account does not already have one that works. + thumbLocalPath: preferPopulated( + local.thumbLocalPath, + incoming.thumbLocalPath, + false, + ), + }; +} + +function unionBookmark( + local: MobileBookmarkWrite, + incoming: MobileBookmarkWrite, +): MobileBookmarkWrite { + const newer = incoming.savedAt > local.savedAt; + return { + subjectUri: local.subjectUri, + postAuthorDid: preferPopulated( + local.postAuthorDid, + incoming.postAuthorDid, + newer, + ), + postAuthorHandle: preferPopulated( + local.postAuthorHandle, + incoming.postAuthorHandle, + newer, + ), + postText: preferPopulated(local.postText, incoming.postText, newer), + postCreatedAt: preferPopulated( + local.postCreatedAt, + incoming.postCreatedAt, + newer, + ), + savedAt: earliestObservation(local.savedAt, incoming.savedAt), + deletedAt: earliest(local.deletedAt, incoming.deletedAt), + }; +} + +function unionFollow( + local: MobileFollowWrite, + incoming: MobileFollowWrite, +): MobileFollowWrite { + const newer = incoming.savedAt > local.savedAt; + return { + uri: local.uri, + cid: preferPopulated(local.cid, incoming.cid, newer), + subjectDid: preferPopulated(local.subjectDid, incoming.subjectDid, newer), + handle: preferPopulated(local.handle, incoming.handle, newer), + displayName: preferPopulated(local.displayName, incoming.displayName, newer), + avatarUrl: preferPopulated(local.avatarUrl, incoming.avatarUrl, newer), + createdAt: preferPopulated(local.createdAt, incoming.createdAt, false), + savedAt: earliestObservation(local.savedAt, incoming.savedAt), + unfollowedAt: earliest(local.unfollowedAt, incoming.unfollowedAt), + }; +} + +function unionConversation( + local: MobileConversationWrite, + incoming: MobileConversationWrite, +): MobileConversationWrite { + const newer = incoming.updatedAt > local.updatedAt; + return { + convoId: local.convoId, + rev: preferPopulated(local.rev, incoming.rev, newer), + memberDids: preferPopulated(local.memberDids, incoming.memberDids, newer), + muted: unionFlag(local.muted, incoming.muted), + lastMessageId: preferPopulated( + local.lastMessageId, + incoming.lastMessageId, + newer, + ), + lastMessageText: preferPopulated( + local.lastMessageText, + incoming.lastMessageText, + newer, + ), + lastMessageSentAt: preferPopulated( + local.lastMessageSentAt, + incoming.lastMessageSentAt, + newer, + ), + lastMessageSenderDid: preferPopulated( + local.lastMessageSenderDid, + incoming.lastMessageSenderDid, + newer, + ), + savedAt: earliestObservation(local.savedAt, incoming.savedAt), + updatedAt: Math.max(local.updatedAt, incoming.updatedAt), + leftAt: earliest(local.leftAt, incoming.leftAt), + }; +} + +function unionMessage( + local: MobileMessageWrite, + incoming: MobileMessageWrite, +): MobileMessageWrite { + const newer = incoming.savedAt > local.savedAt; + return { + messageId: local.messageId, + convoId: preferPopulated(local.convoId, incoming.convoId, newer), + rev: preferPopulated(local.rev, incoming.rev, newer), + senderDid: preferPopulated(local.senderDid, incoming.senderDid, newer), + text: preferPopulated(local.text, incoming.text, newer), + facetsJSON: preferPopulated(local.facetsJSON, incoming.facetsJSON, newer), + embedJSON: preferPopulated(local.embedJSON, incoming.embedJSON, newer), + sentAt: preferPopulated(local.sentAt, incoming.sentAt, false), + savedAt: earliestObservation(local.savedAt, incoming.savedAt), + deletedAt: earliest(local.deletedAt, incoming.deletedAt), + }; +} + +/** + * One media file, as this account holds it. + * + * A file already on this device is the richest thing either side has, so a + * local copy is never traded for a source URL, and a failed download is + * upgraded the moment an archive turns up with the bytes. + */ +function unionMediaAsset( + local: ExistingMediaAssetRow, + incoming: ExistingMediaAssetRow, +): ExistingMediaAssetRow { + const incomingComplete = incoming.downloadState === "complete"; + const localComplete = local.downloadState === "complete"; + const takeIncoming = incomingComplete && !localComplete; + + return { + contentCid: local.contentCid, + mediaType: preferPopulated(local.mediaType, incoming.mediaType, takeIncoming), + mimeType: preferPopulated(local.mimeType, incoming.mimeType, takeIncoming), + byteLength: preferPopulated( + local.byteLength, + incoming.byteLength, + takeIncoming, + ), + localPath: preferPopulated(local.localPath, incoming.localPath, takeIncoming), + sourceUrl: preferPopulated(local.sourceUrl, incoming.sourceUrl, takeIncoming), + sourceDid: preferPopulated(local.sourceDid, incoming.sourceDid, takeIncoming), + sourceMetadataJSON: preferPopulated( + local.sourceMetadataJSON, + incoming.sourceMetadataJSON, + takeIncoming, + ), + downloadState: takeIncoming ? incoming.downloadState : local.downloadState, + // The account's own record of why a download failed stays until a file + // actually arrives to contradict it. + lastError: takeIncoming ? incoming.lastError : local.lastError, + attemptCount: local.attemptCount, + downloadedAt: takeIncoming + ? incoming.downloadedAt + : latest(local.downloadedAt, incoming.downloadedAt), + }; +} + +/** + * When Cyd first held this. + * + * `savedAt` is the moment something entered Bluesky saved data, so the union + * of two accounts of it is the earlier one. A zero means the archive did not + * say, which is not a claim that it was saved at the epoch. + */ +function earliestObservation(local: number, incoming: number): number { + if (local === 0) { + return incoming; + } + if (incoming === 0) { + return local; + } + return Math.min(local, incoming); +} diff --git a/services/archive-merge/merge-writer.ts b/services/archive-merge/merge-writer.ts new file mode 100644 index 0000000..cebc49b --- /dev/null +++ b/services/archive-merge/merge-writer.ts @@ -0,0 +1,252 @@ +import type { BlueskyArchiveMergePlan } from "./merge-plan"; +import type { MergeableAccountDatabase } from "./ports"; + +/** + * Writing a merged plan into a Bluesky local account. + * + * Almost the same statements as a restore's, with one difference that matters: + * `INSERT OR REPLACE` deletes the stored row and inserts a new one, so every + * column a live account fills in for itself has to be named here or a merge + * would quietly clear it. Those columns — a preserved post, a downloader's + * attempt count — come off the merged row, where the union rules already + * carried the local value across. + * + * The order is the restore's order, for the same reason: Mobile's schema has + * foreign keys on, so profiles precede the records that name them, media + * assets precede the attachments that reference them, and conversations + * precede their messages. + */ +export async function writeMergedAccountRows( + database: MergeableAccountDatabase, + plan: BlueskyArchiveMergePlan, +): Promise { + for (const profile of plan.profiles) { + await database.run( + `INSERT OR REPLACE INTO profile (did, handle, displayName, avatarUrl, savedAt, updatedAt) + VALUES (?, ?, ?, ?, ?, ?);`, + [ + profile.did, + profile.handle, + profile.displayName, + profile.avatarUrl, + profile.savedAt, + profile.updatedAt, + ], + ); + } + + for (const post of plan.posts) { + await database.run( + `INSERT OR REPLACE INTO post ( + uri, cid, authorDid, + text, facetsJSON, embedType, embedJSON, langs, + isReply, replyParentUri, replyRootUri, + isQuote, quotedPostUri, + isRepost, repostUri, repostCid, originalPostUri, + likeCount, repostCount, replyCount, quoteCount, + viewerLiked, likeUri, viewerReposted, viewerBookmarked, + createdAt, savedAt, + deletedPostAt, deletedRepostAt, deletedLikeAt, deletedBookmarkAt, + preserve + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);`, + [ + post.uri, + post.cid, + post.authorDid, + post.text, + post.facetsJSON, + post.embedType, + post.embedJSON, + post.langs, + post.isReply, + post.replyParentUri, + post.replyRootUri, + post.isQuote, + post.quotedPostUri, + post.isRepost, + post.repostUri, + post.repostCid, + post.originalPostUri, + post.likeCount, + post.repostCount, + post.replyCount, + post.quoteCount, + post.viewerLiked, + post.likeUri, + post.viewerReposted, + post.viewerBookmarked, + post.createdAt, + post.savedAt, + post.deletedPostAt, + post.deletedRepostAt, + post.deletedLikeAt, + post.deletedBookmarkAt, + post.preserve, + ], + ); + } + + for (const asset of plan.mediaAssets) { + await database.run( + `INSERT OR REPLACE INTO media_asset ( + contentCid, mediaType, mimeType, byteLength, localPath, sourceUrl, + sourceDid, sourceMetadataJSON, downloadState, lastError, attemptCount, + downloadedAt + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);`, + [ + asset.contentCid, + asset.mediaType, + asset.mimeType, + asset.byteLength, + asset.localPath, + asset.sourceUrl, + asset.sourceDid, + asset.sourceMetadataJSON, + asset.downloadState, + asset.lastError, + asset.attemptCount, + asset.downloadedAt, + ], + ); + } + + for (const media of plan.postMedia) { + await database.run( + `INSERT OR REPLACE INTO post_media ( + postUri, position, mediaType, blobCid, mimeType, alt, + width, height, aspectRatioWidth, aspectRatioHeight, + thumbUrl, fullsizeUrl, playlistUrl, downloadedAt, assetCid + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);`, + [ + media.postUri, + media.position, + media.mediaType, + media.blobCid, + media.mimeType, + media.alt, + media.width, + media.height, + media.width, + media.height, + media.thumbUrl, + media.fullsizeUrl, + media.playlistUrl, + media.downloadedAt, + media.assetCid, + ], + ); + } + + for (const external of plan.postExternals) { + await database.run( + `INSERT OR REPLACE INTO post_external ( + postUri, uri, title, description, thumbUrl, thumbLocalPath + ) VALUES (?, ?, ?, ?, ?, ?);`, + [ + external.postUri, + external.uri, + external.title, + external.description, + external.thumbUrl, + external.thumbLocalPath, + ], + ); + } + + for (const bookmark of plan.bookmarks) { + await database.run( + `INSERT OR REPLACE INTO bookmark ( + subjectUri, postAuthorDid, postAuthorHandle, postText, postCreatedAt, + savedAt, deletedAt + ) VALUES (?, ?, ?, ?, ?, ?, ?);`, + [ + bookmark.subjectUri, + bookmark.postAuthorDid, + bookmark.postAuthorHandle, + bookmark.postText, + bookmark.postCreatedAt, + bookmark.savedAt, + bookmark.deletedAt, + ], + ); + } + + for (const follow of plan.follows) { + await database.run( + `INSERT OR REPLACE INTO follow ( + uri, cid, subjectDid, handle, displayName, avatarUrl, + createdAt, savedAt, unfollowedAt + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);`, + [ + follow.uri, + follow.cid, + follow.subjectDid, + follow.handle, + follow.displayName, + follow.avatarUrl, + follow.createdAt, + follow.savedAt, + follow.unfollowedAt, + ], + ); + } + + for (const conversation of plan.conversations) { + await database.run( + `INSERT OR REPLACE INTO conversation ( + convoId, rev, memberDids, muted, + lastMessageId, lastMessageText, lastMessageSentAt, lastMessageSenderDid, + savedAt, updatedAt, leftAt + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);`, + [ + conversation.convoId, + conversation.rev, + conversation.memberDids, + conversation.muted, + conversation.lastMessageId, + conversation.lastMessageText, + conversation.lastMessageSentAt, + conversation.lastMessageSenderDid, + conversation.savedAt, + conversation.updatedAt, + conversation.leftAt, + ], + ); + } + + for (const message of plan.messages) { + await database.run( + `INSERT OR REPLACE INTO message ( + messageId, convoId, rev, senderDid, text, facetsJSON, embedJSON, + sentAt, savedAt, deletedAt + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);`, + [ + message.messageId, + message.convoId, + message.rev, + message.senderDid, + message.text, + message.facetsJSON, + message.embedJSON, + message.sentAt, + message.savedAt, + message.deletedAt, + ], + ); + } +} + +/** How many rows a plan would write, which is what "no effect" means. */ +export function countPlannedWrites(plan: BlueskyArchiveMergePlan): number { + return ( + plan.profiles.length + + plan.posts.length + + plan.postMedia.length + + plan.postExternals.length + + plan.bookmarks.length + + plan.follows.length + + plan.conversations.length + + plan.messages.length + + plan.mediaAssets.length + ); +} diff --git a/services/archive-merge/merge.ts b/services/archive-merge/merge.ts new file mode 100644 index 0000000..2070ee8 --- /dev/null +++ b/services/archive-merge/merge.ts @@ -0,0 +1,302 @@ +import { + placeArchivedMedia, + readBlueskyInterchange, + restoredMediaFileName, + translateInterchangeToMobileRows, + type BlueskyInterchangeSnapshot, + type InterchangeAsset, + type LocalAccountIdentity, + type RestoredAssetPlacement, + type RestoredMobileAccount, + type UnrestorableContent, +} from "@/services/archive-restore"; + +import { readExistingAccountRows } from "./account-rows"; +import { accountRowsFromArchive } from "./rows"; +import { BlueskyArchiveMergeError } from "./errors"; +import { + planBlueskyArchiveMerge, + type BlueskyArchiveMergePlan, + type BlueskyArchiveMergeSummary, +} from "./merge-plan"; +import { countPlannedWrites, writeMergedAccountRows } from "./merge-writer"; +import type { + BlueskyArchiveMergeEnvironment, + PreparedArchiveLocation, +} from "./ports"; + +/** + * The commit half of a Bluesky archive import for an identity Cyd already + * holds. + * + * It runs in two acts, and the split is the point. A **preview** reads the + * prepared archive and works out exactly what merging it would do, touching + * nothing; a **commit** takes that preview and carries it out. Somebody is + * shown the preview first because a recovery merge can bring back records they + * deleted from Cyd on purpose, and nobody should find that out afterwards. + * + * Everything else follows the restore's shape (#96): media is copied in before + * rows are written, so a record's local file path is known when its row is + * built, and an asset that will not copy becomes a failed download rather than + * a failed import. + */ + +export type BlueskyArchiveMergePhase = + | "reading" + | "merging-media" + | "writing" + | "done"; + +export type BlueskyArchiveMergeProgress = { + phase: BlueskyArchiveMergePhase; + mergedAssets: number; + totalAssets: number; +}; + +export type BlueskyArchiveMergeRequest = { + /** An archive intake that ended *prepared* (#95). */ + archive: PreparedArchiveLocation; + /** The Bluesky local account holding this archive's identity. */ + account: LocalAccountIdentity; + onProgress?: (progress: BlueskyArchiveMergeProgress) => void; +}; + +export type MergedAssetSummary = { + total: number; + merged: number; + missing: number; +}; + +export type BlueskyArchiveMergePreview = { + accountUuid: string; + accountDid: string; + /** What the archive says about itself, for somebody deciding about it. */ + archive: { + createdAt: string; + completeness: "complete" | "incomplete"; + accountUuid: string; + }; + summary: BlueskyArchiveMergeSummary; + assets: MergedAssetSummary; + unrestorable: UnrestorableContent; + /** Everything the commit needs, so agreeing to a preview commits that archive. */ + readonly source: { + location: PreparedArchiveLocation; + snapshot: BlueskyInterchangeSnapshot; + }; +}; + +export type BlueskyArchiveMergeResult = { + accountUuid: string; + accountDid: string; + /** Rows actually written. Zero is what a repeated import looks like. */ + written: number; + summary: BlueskyArchiveMergeSummary; + assets: MergedAssetSummary; +}; + +/** + * Work out what merging this archive would do, without doing any of it. + * + * Media is not copied yet, so the plan is built against where each file *will* + * live: the paths are content-addressed, so they are known before the bytes + * move (ADR 0007). A file that then refuses to copy is downgraded at commit + * time, which can only ever turn a restored asset into a failed download. + */ +export async function previewBlueskyArchiveMerge( + environment: BlueskyArchiveMergeEnvironment, + request: BlueskyArchiveMergeRequest, +): Promise { + const report = reporter(request); + report("reading", 0, 0); + + const archive = environment.openPreparedArchive(request.archive); + const interchange = await archive.openInterchange(); + let snapshot: BlueskyInterchangeSnapshot; + try { + snapshot = await readBlueskyInterchange(interchange); + } finally { + await interchange.close(); + } + + requireMatchingIdentity(snapshot.archive.account_did, request.account); + + const incoming = translateInterchangeToMobileRows(snapshot, { + placements: predictPlacements( + environment, + request.account.uuid, + snapshot.assets, + ), + }); + const plan = await planAgainstAccount( + environment, + request.account.uuid, + incoming, + ); + + report("done", 0, snapshot.assets.length); + return { + accountUuid: request.account.uuid, + accountDid: snapshot.archive.account_did, + archive: { + createdAt: snapshot.archive.created_at, + completeness: snapshot.archive.completeness, + accountUuid: snapshot.archive.account_uuid, + }, + summary: plan.summary, + assets: summarizeAssets(snapshot.assets), + unrestorable: incoming.unrestorable, + source: { location: request.archive, snapshot }, + }; +} + +/** + * Carry out a preview somebody agreed to. + * + * The account is read again rather than trusted from the preview: a save that + * ran in between is newer than the archive, and the union rules can only reach + * the right answer if they are given what the account holds *now*. Committing + * twice is therefore as safe as importing twice — the second commit finds + * nothing left to write. + */ +export async function commitBlueskyArchiveMerge( + environment: BlueskyArchiveMergeEnvironment, + preview: BlueskyArchiveMergePreview, + options: { onProgress?: (progress: BlueskyArchiveMergeProgress) => void } = {}, +): Promise { + const { snapshot, location } = preview.source; + const totalAssets = snapshot.assets.length; + const report = reporter({ onProgress: options.onProgress }); + + const archive = environment.openPreparedArchive(location); + + report("merging-media", 0, totalAssets); + const placements = await placeArchivedMedia(environment, { + accountUuid: preview.accountUuid, + archive, + assets: snapshot.assets, + onPlaced: (placed) => report("merging-media", placed, totalAssets), + }); + + const incoming = translateInterchangeToMobileRows(snapshot, { placements }); + const plan = await planAgainstAccount( + environment, + preview.accountUuid, + incoming, + ); + + report("writing", placements.size, totalAssets); + const database = await environment.openAccountDatabase(preview.accountUuid); + try { + await database.transaction(async () => { + await writeMergedAccountRows(database, plan); + }); + } finally { + await database.close(); + } + + // The account holds everything the archive carried, so the staged copy is + // nothing but a second copy of data this device now has. + await archive.discard(); + + report("done", placements.size, totalAssets); + return { + accountUuid: preview.accountUuid, + accountDid: preview.accountDid, + written: countPlannedWrites(plan), + summary: plan.summary, + assets: summarizeAssets(snapshot.assets), + }; +} + +function reporter(options: { + onProgress?: (progress: BlueskyArchiveMergeProgress) => void; +}) { + return ( + phase: BlueskyArchiveMergePhase, + mergedAssets: number, + totalAssets: number, + ): void => options.onProgress?.({ phase, mergedAssets, totalAssets }); +} + +async function planAgainstAccount( + environment: BlueskyArchiveMergeEnvironment, + accountUuid: string, + incoming: RestoredMobileAccount, +): Promise { + const database = await environment.openAccountDatabase(accountUuid); + try { + return planBlueskyArchiveMerge( + await readExistingAccountRows(database), + accountRowsFromArchive(incoming), + ); + } finally { + await database.close(); + } +} + +/** + * Refuse an archive that belongs to somebody else. + * + * The DID is the identity (ADR 0011), so this is the only check worth making: + * a handle that matches proves nothing, and a handle that does not is routine + * for somebody who renamed. + */ +function requireMatchingIdentity( + archiveDid: string, + account: LocalAccountIdentity, +): void { + if (account.did !== archiveDid) { + throw new BlueskyArchiveMergeError( + "identity-mismatch", + "This archive belongs to a different Bluesky identity than the account it was about to be merged into.", + ); + } +} + +/** Where each packaged asset will live once the merge copies it in. */ +function predictPlacements( + environment: BlueskyArchiveMergeEnvironment, + accountUuid: string, + assets: InterchangeAsset[], +): Map { + const placements = new Map(); + for (const asset of assets) { + if (asset.availability !== "available" || !asset.archive_path || !asset.sha256) { + placements.set(asset.id, { + assetId: asset.id, + availability: "missing", + reason: + asset.unavailable_reason ?? + "This file was not included in the archive.", + }); + continue; + } + placements.set(asset.id, { + assetId: asset.id, + availability: "restored", + localPath: environment.accountMediaUri( + accountUuid, + restoredMediaFileName(asset.sha256), + ), + }); + } + return placements; +} + +/** + * What the archive's media amounts to for this account. + * + * An asset the account already holds is not counted as missing: the file is + * there, and the merge simply had nothing to change about it. + */ +function summarizeAssets(assets: InterchangeAsset[]): MergedAssetSummary { + const available = assets.filter( + (asset) => asset.availability === "available" && asset.sha256, + ).length; + return { + total: assets.length, + merged: available, + missing: assets.length - available, + }; +} diff --git a/services/archive-merge/ports.ts b/services/archive-merge/ports.ts new file mode 100644 index 0000000..1e7b57f --- /dev/null +++ b/services/archive-merge/ports.ts @@ -0,0 +1,134 @@ +import type { + DiscardableAccount, + LocalAccountIdentity, + PreparedArchiveLocation, + PreparedArchiveStore, + RestoredAccountDatabase, + StoredMediaFile, +} from "@/services/archive-restore"; + +/** + * The platform capabilities a recovery merge needs, and deliberately no more. + * + * What is missing from this list is the point of it. There is no way from here + * to write a Bluesky local account's settings or schedule, to touch a Bluesky + * connection, or to rename an account: a merge into an existing Bluesky local + * account can only add to that account's Bluesky saved data, so "an existing + * identity keeps its UUID, its settings, its schedules and its connection" is + * a property of the interface rather than a promise somebody has to keep. + * + * The exceptions are the two ports duplicate-DID reconciliation needs, which + * is the one moment a person is asked to choose between two local accounts' + * settings (ADR 0011). They are named for that job so they cannot be reached + * for by accident. + */ + +/** An existing account's database, which a merge reads before it writes. */ +export type MergeableAccountDatabase = RestoredAccountDatabase & { + all(sql: string): Promise; +}; + +/** + * The `bsky_account` columns duplicate-DID reconciliation carries over from + * the account whose settings the person chose to keep. + * + * Schedule columns are here because a surviving Bluesky local account has to + * keep a schedule somebody set. A Bluesky scheduled reminder still only + * prompts a review — carrying it across does not authorize unattended + * deletion, and there is nothing here that could. + */ +export const RECONCILABLE_SETTING_COLUMNS = [ + "settingSavePosts", + "settingSaveLikes", + "settingSaveBookmarks", + "settingSaveChats", + "settingDeletePosts", + "settingDeleteReposts", + "settingDeleteLikes", + "settingDeleteBookmarks", + "settingDeleteChats", + "settingDeleteUnfollowEveryone", + "settingScheduleDeletion", + "settingScheduleDeletionFrequency", + "settingScheduleDeletionDayOfMonth", + "settingScheduleDeletionDayOfWeek", + "settingScheduleDeletionTime", +] as const; + +export type ReconcilableSettingColumn = + (typeof RECONCILABLE_SETTING_COLUMNS)[number]; + +/** One account's settings, as the person would compare them side by side. */ +export type ReconcilableAccountSettings = Partial< + Record +>; + +export type BlueskyArchiveMergeEnvironment = { + openPreparedArchive(archive: PreparedArchiveLocation): PreparedArchiveStore; + + /** Every Bluesky local account this installation has, for routing (#97). */ + listLocalAccountIdentities(): Promise; + + openAccountDatabase(accountUuid: string): Promise; + + /** + * Copy a staged payload into the account's own media storage. + * + * Content-addressed, so a file the account already holds is written once + * (ADR 0007) and merging the same archive twice copies nothing new. + */ + storeAccountMedia( + accountUuid: string, + fileName: string, + write: (push: (bytes: Uint8Array) => void) => Promise, + ): Promise; + + /** + * Where a file of this name will live inside an account's media storage. + * + * Media is content-addressed, so a merge can say where a file is going + * before it moves the bytes. That is what lets somebody be shown the exact + * rows a merge would write without anything being written. + */ + accountMediaUri(accountUuid: string, fileName: string): string; + + /** What a duplicate Bluesky local account is set to do, for the preview. */ + readAccountSettings( + accountUuid: string, + ): Promise; + + /** Give the surviving account the settings the person picked (ADR 0011). */ + applyAccountSettings( + accountUuid: string, + settings: ReconcilableAccountSettings, + ): Promise; + + /** + * Move a media file from a duplicate Bluesky local account into the one that + * survives, returning where it now lives. Null when the file is gone, which + * makes the record a failed download rather than a failed reconciliation. + */ + adoptAccountMedia( + sourceAccountUuid: string, + targetAccountUuid: string, + localPath: string, + ): Promise; + + /** + * Make one Bluesky local account per DID a rule of the database again. + * + * Mobile has carried a unique index on `bsky_account.did` since its first + * migration, so duplicates can only reach an installation from outside it — + * a database restored from an OS backup, or one that predates the index. + * Reconciliation ends by putting the rule back, which is also the check that + * the duplicates really are gone: the statement fails while any remain. + */ + enforceOneAccountPerDid(): Promise; + + /** Remove a reconciled-away Bluesky local account and its storage. */ + removeLocalAccount(account: DiscardableAccount): Promise; + + now(): Date; +}; + +export type { PreparedArchiveLocation, StoredMediaFile }; diff --git a/services/archive-merge/rows.ts b/services/archive-merge/rows.ts new file mode 100644 index 0000000..2d3c88e --- /dev/null +++ b/services/archive-merge/rows.ts @@ -0,0 +1,88 @@ +import type { + RestoredMobileAccount, + MobileBookmarkWrite, + MobileConversationWrite, + MobileFollowWrite, + MobileMediaAssetWrite, + MobileMessageWrite, + MobilePostExternalWrite, + MobilePostMediaWrite, + MobilePostWrite, + MobileProfileWrite, +} from "@/services/archive-restore"; + +/** + * The rows a Bluesky local account already holds, in the shape a restore + * writes them. + * + * A merge compares two descriptions of the same Bluesky saved data, so both + * sides have to be the same shape. Restore's row types are that shape, plus + * the few columns that only a live account has: a person's own decision to + * preserve a post, and what Cyd's downloader has been through with a file. + * They are local facts an archive cannot know, so the merge carries them + * across untouched rather than letting an `INSERT OR REPLACE` quietly reset + * them. + */ + +export type ExistingPostRow = MobilePostWrite & { + /** The person's own "never delete this", which no archive may clear. */ + preserve: number; +}; + +export type ExistingMediaAssetRow = Omit< + MobileMediaAssetWrite, + "downloadState" +> & { + downloadState: "pending" | "downloading" | "complete" | "failed"; + attemptCount: number; +}; + +export type ExistingAccountRows = { + profiles: MobileProfileWrite[]; + posts: ExistingPostRow[]; + postMedia: MobilePostMediaWrite[]; + postExternals: MobilePostExternalWrite[]; + bookmarks: MobileBookmarkWrite[]; + follows: MobileFollowWrite[]; + conversations: MobileConversationWrite[]; + messages: MobileMessageWrite[]; + mediaAssets: ExistingMediaAssetRow[]; +}; + +/** + * A Cyd Bluesky archive's rows, in the shape the account holds them. + * + * The two columns an archive cannot know get the value a newly saved record + * would have, and the union rules carry the account's own values across. It + * is what lets one plan serve both jobs: merging an archive into an account, + * and merging two duplicate accounts into one (ADR 0011). + */ +export function accountRowsFromArchive( + restored: RestoredMobileAccount, +): ExistingAccountRows { + return { + profiles: restored.profiles, + posts: restored.posts.map((row) => ({ ...row, preserve: 0 })), + postMedia: restored.postMedia, + postExternals: restored.postExternals, + bookmarks: restored.bookmarks, + follows: restored.follows, + conversations: restored.conversations, + messages: restored.messages, + mediaAssets: restored.mediaAssets.map((row) => ({ + ...row, + attemptCount: 0, + })), + }; +} + +export type { + MobileBookmarkWrite, + MobileConversationWrite, + MobileFollowWrite, + MobileMessageWrite, + MobilePostExternalWrite, + MobilePostMediaWrite, + MobilePostWrite, + MobileProfileWrite, +}; diff --git a/services/archive-merge/union.ts b/services/archive-merge/union.ts new file mode 100644 index 0000000..610b337 --- /dev/null +++ b/services/archive-merge/union.ts @@ -0,0 +1,69 @@ +/** + * The four rules a recovery union comes down to. + * + * They are small on purpose: every column of every table in `merge-plan.ts` is + * settled by one of them, so "what does importing an old archive do to my + * account?" has one answer to read rather than one per table. + */ + +function populated(value: unknown): boolean { + return value !== null && value !== undefined && value !== ""; +} + +/** + * Keep whichever side actually says something. + * + * Absence is never an observation: an archive exported before Cyd captured a + * post's alt text, or one written by a client that has no column for it, says + * nothing about that field rather than saying it is empty. Only when both + * sides hold a value does the newer observation win. + */ +export function preferPopulated( + local: T, + incoming: T, + incomingIsNewer: boolean, +): T { + if (!populated(incoming)) { + return local; + } + if (!populated(local)) { + return incoming; + } + return incomingIsNewer ? incoming : local; +} + +/** A flag either side set stays set: a union never takes a like back. */ +export function unionFlag( + local: number | null, + incoming: number | null, +): number { + return local === 1 || incoming === 1 ? 1 : 0; +} + +/** The first time either side saw something happen, such as a deletion. */ +export function earliest( + local: number | null, + incoming: number | null, +): number | null { + if (local === null) { + return incoming; + } + if (incoming === null) { + return local; + } + return Math.min(local, incoming); +} + +/** The most recent of two timestamps, when later means better informed. */ +export function latest( + local: number | null, + incoming: number | null, +): number | null { + if (local === null) { + return incoming; + } + if (incoming === null) { + return local; + } + return Math.max(local, incoming); +} diff --git a/services/archive-restore/environment.ts b/services/archive-restore/environment.ts index 02628de..7f10889 100644 --- a/services/archive-restore/environment.ts +++ b/services/archive-restore/environment.ts @@ -91,7 +91,13 @@ async function openAccountDatabase(accountUuid: string): Promise return database; } -function openPreparedArchive( +/** + * Reading a prepared archive out of intake staging. + * + * Exported because a merge reads the same staging the same way (#97): the + * archive does not care which half of the import opened it. + */ +export function openPreparedArchive( archive: PreparedArchiveLocation, ): PreparedArchiveStore { const nativeRoot = `${nativeStagingRoot()}/${archive.intakeId}`; diff --git a/services/archive-restore/index.ts b/services/archive-restore/index.ts index d993bcb..a4156c1 100644 --- a/services/archive-restore/index.ts +++ b/services/archive-restore/index.ts @@ -12,8 +12,14 @@ * * What leaves this module is the entry point, the failures a caller has to * tell somebody about, and the ports an adapter has to implement. Everything - * else — the interchange reader, the translation, the row writer — is internal, - * and its tests reach for it directly. + * else — the translation and the row writer — is internal, and its tests reach + * for it directly. + * + * The pieces a merge needs are the exception. Reading a version 2 interchange + * database, translating it into Mobile's rows, and copying its media into an + * account are the same work whichever half of the import is running, so they + * are exported here and #97 consumes them rather than growing a second v2 + * adapter that can drift from this one. */ export { createBlueskyArchiveRestoreEnvironment } from "./environment"; @@ -32,7 +38,27 @@ export type { RestoredAssetSummary, RestoredCategoryCounts, } from "./restore"; -export type { UnrestorableContent } from "./mobile-rows"; +export { readBlueskyInterchange } from "./interchange-reader"; +export type { + BlueskyInterchangeSnapshot, + InterchangeAsset, +} from "./interchange-reader"; +export { placeArchivedMedia, restoredMediaFileName } from "./media"; +export { translateInterchangeToMobileRows } from "./mobile-rows"; +export type { + MobileBookmarkWrite, + MobileConversationWrite, + MobileFollowWrite, + MobileMediaAssetWrite, + MobileMessageWrite, + MobilePostExternalWrite, + MobilePostMediaWrite, + MobilePostWrite, + MobileProfileWrite, + RestoredAssetPlacement, + RestoredMobileAccount, + UnrestorableContent, +} from "./mobile-rows"; export type { BlueskyArchiveRestoreEnvironment, CreatedLocalAccount, diff --git a/services/archive-restore/media.ts b/services/archive-restore/media.ts new file mode 100644 index 0000000..b05f416 --- /dev/null +++ b/services/archive-restore/media.ts @@ -0,0 +1,110 @@ +import type { InterchangeAsset } from "./interchange-reader"; +import type { RestoredAssetPlacement } from "./mobile-rows"; +import type { PreparedArchiveStore, StoredMediaFile } from "./ports"; + +/** + * Copying a Cyd Bluesky archive's packaged assets into a Bluesky local + * account. + * + * Both halves of an import land here: a restore copies into the account it is + * creating, and a merge copies into the account it is merging with (#97). The + * rule is the same either way, which is why it is one file — an archive's + * media is content-addressed, so the same bytes referenced by several records + * are stored once (ADR 0007). + */ + +/** Content-addressed name of a restored file inside the account's media store. */ +export function restoredMediaFileName(sha256: string): string { + return `sha256-${sha256}`; +} + +/** The one capability placing media needs, out of the larger environments. */ +export type MediaStore = { + storeAccountMedia( + accountUuid: string, + fileName: string, + write: (push: (bytes: Uint8Array) => void) => Promise, + ): Promise; +}; + +/** + * Copy each packaged asset into the Bluesky local account, once per file. + * + * An asset the archive marked unavailable never had bytes to copy. One that + * will not read, or that arrives the wrong size, is treated the same way: the + * archive's promise about that file did not hold, and calling it restored + * would make an incomplete backup look complete. Either way the record keeps + * its reference and the source URL, so saving can fetch it later. + */ +export async function placeArchivedMedia( + environment: MediaStore, + options: { + accountUuid: string; + archive: Pick; + assets: InterchangeAsset[]; + onPlaced: (placed: number) => void; + }, +): Promise> { + const placements = new Map(); + const byDigest = new Map(); + let placed = 0; + + for (const asset of options.assets) { + if (asset.availability !== "available" || !asset.archive_path || !asset.sha256) { + placements.set(asset.id, { + assetId: asset.id, + availability: "missing", + reason: + asset.unavailable_reason ?? + "This file was not included in the archive.", + }); + continue; + } + + const alreadyPlaced = byDigest.get(asset.sha256); + if (alreadyPlaced) { + placements.set(asset.id, { + assetId: asset.id, + availability: "restored", + localPath: alreadyPlaced, + }); + continue; + } + + const archivePath = asset.archive_path; + let stored: StoredMediaFile | null = null; + try { + stored = await environment.storeAccountMedia( + options.accountUuid, + restoredMediaFileName(asset.sha256), + (push) => options.archive.readPayload(archivePath, push), + ); + } catch { + stored = null; + } + + const wrongSize = + stored !== null && + asset.byte_count !== null && + stored.byteLength !== asset.byte_count; + if (stored === null || wrongSize) { + placements.set(asset.id, { + assetId: asset.id, + availability: "missing", + reason: "Cyd could not restore this file from the archive.", + }); + continue; + } + + byDigest.set(asset.sha256, stored.uri); + placements.set(asset.id, { + assetId: asset.id, + availability: "restored", + localPath: stored.uri, + }); + placed += 1; + options.onPlaced(placed); + } + + return placements; +} diff --git a/services/archive-restore/restore.ts b/services/archive-restore/restore.ts index 0911ab8..c5115d8 100644 --- a/services/archive-restore/restore.ts +++ b/services/archive-restore/restore.ts @@ -9,8 +9,8 @@ import { import { readBlueskyInterchange, type BlueskyInterchangeSnapshot, - type InterchangeAsset, } from "./interchange-reader"; +import { placeArchivedMedia } from "./media"; import { translateInterchangeToMobileRows, type RestoredAssetPlacement, @@ -22,9 +22,7 @@ import type { BlueskyArchiveRestoreEnvironment, CreatedLocalAccount, PreparedArchiveLocation, - PreparedArchiveStore, RestoredAccountDatabase, - StoredMediaFile, } from "./ports"; import { writeRestoredAccountRows } from "./account-writer"; @@ -99,11 +97,6 @@ export type BlueskyArchiveRestoreResult = { unrestorable: UnrestorableContent; }; -/** Content-addressed name of a restored file inside the account's media store. */ -export function restoredMediaFileName(sha256: string): string { - return `sha256-${sha256}`; -} - export async function restoreBlueskyArchiveAccount( environment: BlueskyArchiveRestoreEnvironment, request: BlueskyArchiveRestoreRequest, @@ -200,88 +193,6 @@ export async function restoreBlueskyArchiveAccount( } } -/** - * Copy each packaged asset into the Bluesky local account, once per file. - * - * An asset the archive marked unavailable never had bytes to copy. One that - * will not read, or that arrives the wrong size, is treated the same way: the - * archive's promise about that file did not hold, and calling it restored - * would make an incomplete backup look complete. Either way the record keeps - * its reference and the source URL, so saving can fetch it later. - */ -async function placeArchivedMedia( - environment: BlueskyArchiveRestoreEnvironment, - options: { - accountUuid: string; - archive: Pick; - assets: InterchangeAsset[]; - onPlaced: (placed: number) => void; - }, -): Promise> { - const placements = new Map(); - const byDigest = new Map(); - let placed = 0; - - for (const asset of options.assets) { - if (asset.availability !== "available" || !asset.archive_path || !asset.sha256) { - placements.set(asset.id, { - assetId: asset.id, - availability: "missing", - reason: - asset.unavailable_reason ?? - "This file was not included in the archive.", - }); - continue; - } - - const alreadyPlaced = byDigest.get(asset.sha256); - if (alreadyPlaced) { - placements.set(asset.id, { - assetId: asset.id, - availability: "restored", - localPath: alreadyPlaced, - }); - continue; - } - - const archivePath = asset.archive_path; - let stored: StoredMediaFile | null = null; - try { - stored = await environment.storeAccountMedia( - options.accountUuid, - restoredMediaFileName(asset.sha256), - (push) => options.archive.readPayload(archivePath, push), - ); - } catch { - stored = null; - } - - const wrongSize = - stored !== null && - asset.byte_count !== null && - stored.byteLength !== asset.byte_count; - if (stored === null || wrongSize) { - placements.set(asset.id, { - assetId: asset.id, - availability: "missing", - reason: "Cyd could not restore this file from the archive.", - }); - continue; - } - - byDigest.set(asset.sha256, stored.uri); - placements.set(asset.id, { - assetId: asset.id, - availability: "restored", - localPath: stored.uri, - }); - placed += 1; - options.onPlaced(placed); - } - - return placements; -} - /** * What the restored account knows about where it came from. * diff --git a/services/scheduled-reminder-sync.ts b/services/scheduled-reminder-sync.ts new file mode 100644 index 0000000..77f41bb --- /dev/null +++ b/services/scheduled-reminder-sync.ts @@ -0,0 +1,62 @@ +import { listAccounts } from "@/database/accounts"; +import { getAccountScheduleSettings } from "@/database/schedule-settings"; +import type CydAPIClient from "@/services/cyd-api-client"; + +/** + * Keeping server-scheduled Bluesky reminders pointed at the right account. + * + * Mobile delivers reminders as push scheduled by Cyd's server, keyed by the + * local-account UUID (ADR 0005). A merge never touches that — the account + * keeps its UUID and its schedule — but reconciling duplicates does: one UUID + * stops existing, and the survivor may come out of it with the schedule that + * belonged to the other one. + * + * So reconciliation ends by telling the server what is true now. A reminder + * still only prompts somebody to open Cyd and review: nothing here authorizes + * unattended deletion, and there is nothing in the payload that could. + */ +export type ScheduledReminderSync = { + /** Re-send the surviving account's schedule as it now stands. */ + resync(accountUuid: string): Promise; + /** Stop reminders for a Bluesky local account that no longer exists. */ + retire(accountUuid: string): Promise; +}; + +/** Used when there is no Cyd account, and so no server-scheduled reminders. */ +export const NO_SCHEDULED_REMINDERS: ScheduledReminderSync = { + resync: async () => {}, + retire: async () => {}, +}; + +export function createScheduledReminderSync( + apiClient: CydAPIClient, + isSignedIn: boolean, +): ScheduledReminderSync { + if (!isSignedIn) { + return NO_SCHEDULED_REMINDERS; + } + + return { + resync: async (accountUuid) => { + const account = (await listAccounts()).find( + (candidate) => candidate.uuid === accountUuid, + ); + if (!account) { + return; + } + const settings = await getAccountScheduleSettings(account.id); + await apiClient.updateScheduleSettings({ + account_uuid: accountUuid, + schedule_enabled: settings.scheduleDeletion, + schedule_frequency: settings.scheduleDeletionFrequency, + schedule_day_of_month: settings.scheduleDeletionDayOfMonth, + schedule_day_of_week: settings.scheduleDeletionDayOfWeek, + schedule_time: settings.scheduleDeletionTime, + }); + }, + + retire: async (accountUuid) => { + await apiClient.unregisterPushToken({ account_uuid: accountUuid }); + }, + }; +} diff --git a/testUtils/archiveEnvironments.ts b/testUtils/archiveEnvironments.ts index 7957dee..2cb0bcc 100644 --- a/testUtils/archiveEnvironments.ts +++ b/testUtils/archiveEnvironments.ts @@ -31,16 +31,21 @@ import type { StagedFileWriter, } from "@/services/archive-import/ports"; import { stagedPayloadPath } from "@/services/archive-import"; +import type { + BlueskyArchiveMergeEnvironment, + MergeableAccountDatabase, + ReconcilableSettingColumn, +} from "@/services/archive-merge"; +import { RECONCILABLE_SETTING_COLUMNS } from "@/services/archive-merge"; import type { BlueskyArchiveRestoreEnvironment, DiscardableAccount, + LocalAccountIdentity, RestorableSettingColumn, NewLocalAccountRequest, PreparedArchiveStore, ReadableInterchangeDatabase, - RestoredAccountDatabase, } from "@/services/archive-restore"; -import type { LocalAccountIdentity } from "@/services/archive-restore"; const createNodeHasher = (): Hasher => { const hash = crypto.createHash("sha256"); @@ -129,10 +134,12 @@ function asReadableInterchange( }; } -function asRestoredAccountDatabase( +function asMergeableAccountDatabase( database: DatabaseSync, -): RestoredAccountDatabase { +): MergeableAccountDatabase { return { + all: async (sql: string): Promise => + database.prepare(sql).all() as T[], run: async (sql, params) => { database.prepare(sql).run(...(params as never[])); }, @@ -150,13 +157,21 @@ function asRestoredAccountDatabase( }; } -export type NodeRestoreEnvironment = BlueskyArchiveRestoreEnvironment & { +/** + * One Node-backed environment for both halves of an import. + * + * Restore and merge run against the same `main.db`, the same account + * directories and the same media, so splitting them into two doubles would + * only invite the two to disagree about what the device looks like. + */ +export type NodeRestoreEnvironment = BlueskyArchiveRestoreEnvironment & + BlueskyArchiveMergeEnvironment & { /** Mobile's own `main.db`, for asserting what a restore created. */ mainDatabase: DatabaseSync; accountDirectory(accountUuid: string): string; openRestoredAccountDatabase(accountUuid: string): DatabaseSync; close(): void; -}; + }; export type NodeRestoreEnvironmentOptions = { /** A directory standing in for the app's private storage. */ @@ -186,6 +201,12 @@ export function createNodeBlueskyArchiveRestoreEnvironment( const accountDirectory = (accountUuid: string): string => path.join(options.root, "accounts", `bluesky-${accountUuid}`); + const mediaDirectory = (accountUuid: string): string => + path.join(accountDirectory(accountUuid), "media"); + + const accountMediaUri = (accountUuid: string, fileName: string): string => + `file://${path.join(mediaDirectory(accountUuid), fileName)}`; + const openAccount = (accountUuid: string): DatabaseSync => { const directory = accountDirectory(accountUuid); fs.mkdirSync(directory, { recursive: true }); @@ -211,6 +232,30 @@ export function createNodeBlueskyArchiveRestoreEnvironment( return database; }; + const removeAccount = (account: DiscardableAccount): void => { + const row = mainDatabase + .prepare( + account.accountId === null + ? "SELECT bskyAccountID FROM account WHERE uuid = ?;" + : "SELECT bskyAccountID FROM account WHERE id = ?;", + ) + .get(account.accountId ?? account.accountUuid) as + | { bskyAccountID: number } + | undefined; + mainDatabase + .prepare("DELETE FROM account WHERE uuid = ?;") + .run(account.accountUuid); + if (row) { + mainDatabase + .prepare("DELETE FROM bsky_account WHERE id = ?;") + .run(row.bskyAccountID); + } + fs.rmSync(accountDirectory(account.accountUuid), { + recursive: true, + force: true, + }); + }; + let generated = 0; return { @@ -293,10 +338,10 @@ export function createNodeBlueskyArchiveRestoreEnvironment( }, openAccountDatabase: async (accountUuid) => - asRestoredAccountDatabase(openAccount(accountUuid)), + asMergeableAccountDatabase(openAccount(accountUuid)), storeAccountMedia: async (accountUuid, fileName, write) => { - const directory = path.join(accountDirectory(accountUuid), "media"); + const directory = mediaDirectory(accountUuid); fs.mkdirSync(directory, { recursive: true }); const location = path.join(directory, fileName); const chunks: Uint8Array[] = []; @@ -306,26 +351,65 @@ export function createNodeBlueskyArchiveRestoreEnvironment( return { uri: `file://${location}`, byteLength: contents.byteLength }; }, - discardLocalAccount: async (account: DiscardableAccount) => { - if (account.accountId !== null) { - const row = mainDatabase - .prepare("SELECT bskyAccountID FROM account WHERE id = ?;") - .get(account.accountId) as { bskyAccountID: number } | undefined; - mainDatabase - .prepare("DELETE FROM account WHERE id = ?;") - .run(account.accountId); - if (row) { - mainDatabase - .prepare("DELETE FROM bsky_account WHERE id = ?;") - .run(row.bskyAccountID); - } + accountMediaUri, + + readAccountSettings: async (accountUuid) => { + const row = mainDatabase + .prepare( + `SELECT ${RECONCILABLE_SETTING_COLUMNS.join(", ")} + FROM bsky_account b + INNER JOIN account a ON a.bskyAccountID = b.id + WHERE a.uuid = ?;`, + ) + .get(accountUuid); + return row ?? {}; + }, + + applyAccountSettings: async (accountUuid, settings) => { + const entries = Object.entries(settings) as [ + ReconcilableSettingColumn, + string | number | null, + ][]; + if (entries.length === 0) { + return; } - fs.rmSync(accountDirectory(account.accountUuid), { - recursive: true, - force: true, - }); + mainDatabase + .prepare( + `UPDATE bsky_account + SET ${entries.map(([column]) => `${column} = ?`).join(", ")} + WHERE id = (SELECT bskyAccountID FROM account WHERE uuid = ?);`, + ) + .run(...entries.map(([, value]) => value as never), accountUuid); }, + adoptAccountMedia: async (sourceAccountUuid, targetAccountUuid, localPath) => { + const source = localPath.replace(/^file:\/\//, ""); + if (!fs.existsSync(source)) { + return null; + } + const directory = mediaDirectory(targetAccountUuid); + fs.mkdirSync(directory, { recursive: true }); + const location = path.join(directory, path.basename(source)); + fs.copyFileSync(source, location); + return { + uri: `file://${location}`, + byteLength: fs.statSync(location).size, + }; + }, + + enforceOneAccountPerDid: async () => { + mainDatabase.exec( + `CREATE UNIQUE INDEX IF NOT EXISTS idx_bsky_account_did + ON bsky_account(did);`, + ); + }, + + removeLocalAccount: async (account: DiscardableAccount) => + removeAccount(account), + + discardLocalAccount: async (account: DiscardableAccount) => + removeAccount(account), + newUuid: options.newUuid ?? (() => `generated-uuid-${(generated += 1)}`), now: options.now ?? (() => new Date("2026-09-12T00:00:00.000Z")), }; From 127b7106bae0cb4e234d43c8041228df8ffa3d1c Mon Sep 17 00:00:00 2001 From: Micah Lee Date: Fri, 11 Sep 2026 12:35:25 -0700 Subject: [PATCH 2/9] Address review of the archive merge MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two of these were bugs the fixtures could not see, because the Node double was kinder than the device. Reconciliation removed a duplicate Bluesky local account by passing a null account id, which the device adapter read as "no row to delete" — so on a phone the losing account's rows survived while its storage went, leaving the identity still held twice and a listed account pointing at nothing. The port now removes by local-account UUID, which is what reconciliation actually knows, and takes the Bluesky connection with it. Putting the unique index back was the other half of the illusion: Mobile has carried that index since its first migration, so `CREATE UNIQUE INDEX IF NOT EXISTS` can only fail on the databases that lost it, and could never be the proof the docblock claimed. Reconciliation now counts the holders afterwards and refuses to report success while the identity is still held twice. Cancelling during a merge preview did not cancel. The preview cannot be called back, so it finished and reopened itself over staging that cancelling had just deleted; committing from there failed. Imports are now generational: walking away moves the count on, a step that lands afterwards reports to nobody, and intake is asked to stop between payloads rather than only ignored. Cancelling before intake even started used to leave a fully prepared staging directory behind, which the same counter now clears. An archive that never captured engagement counts translates them to zero, and a newer one would write those zeros over counts this device had seen — absence replacing a populated value, which is exactly what the union is not allowed to do. Counts get their own rule, and it is the safe direction: a count that really fell to zero is corrected by the next save. Reconciliation now names the records keeping one account would bring back, rather than only counting what each holds, so the choice between two accounts carries the same disclosure an archive merge does (ADR 0018). Where the survivor inherits a schedule the other account owned, Cyd registers the push token against the surviving UUID before sending the schedule, or the server would hold a reminder it cannot deliver; permission is only read, never asked for, because an import is the wrong moment for a notifications prompt. The rest is what the review called: the unavailable-asset rule and the content-addressed path prediction live in the shared media module rather than in two places, the merge ports lost a clock nothing used, the import hook has one seam for reminders instead of two, and a result type lost two fields nothing read. use-bluesky-archive-import.test.ts covers the entry point the acceptance criteria rest on: restoring without asking, stopping for a decision, and walking away leaving nothing on screen or in staging. Co-Authored-By: Claude Opus 5 (1M context) --- components/BlueskyArchiveImportModal.tsx | 32 ++- .../use-bluesky-archive-import.test.ts | 166 ++++++++++++++++ hooks/use-bluesky-archive-import.ts | 183 +++++++++++------- jest-setup.ts | 32 +++ .../__tests__/duplicates.test.ts | 13 ++ .../__tests__/merge-plan.test.ts | 22 +++ services/archive-merge/duplicates.ts | 78 ++++++-- services/archive-merge/environment.ts | 27 ++- services/archive-merge/index.ts | 1 + services/archive-merge/merge-plan.ts | 3 +- services/archive-merge/merge.ts | 39 +--- services/archive-merge/ports.ts | 15 +- services/archive-merge/union.ts | 24 +++ services/archive-restore/index.ts | 6 +- services/archive-restore/media.ts | 64 +++++- services/scheduled-reminder-sync.ts | 31 ++- testUtils/archiveEnvironments.ts | 4 +- 17 files changed, 580 insertions(+), 160 deletions(-) create mode 100644 hooks/__tests__/use-bluesky-archive-import.test.ts diff --git a/components/BlueskyArchiveImportModal.tsx b/components/BlueskyArchiveImportModal.tsx index 9bcdc8a..e91756f 100644 --- a/components/BlueskyArchiveImportModal.tsx +++ b/components/BlueskyArchiveImportModal.tsx @@ -40,9 +40,6 @@ export type BlueskyArchiveImportModalProps = { onDismiss: () => void; }; -/** How many of the records coming back are named before the list is cut off. */ -const LISTED_RESTORATIONS = 5; - export function BlueskyArchiveImportModal({ state, onConfirmLargeArchive, @@ -174,6 +171,13 @@ export function BlueskyArchiveImportModal({ {account.counts.posts} posts · {account.counts.chats}{" "} chats · {account.counts.follows} follows + {account.gains.total > 0 ? ( + + Keeping this one brings back {account.gains.total}{" "} + records it does not have, including{" "} + {describeRecord(account.gains.records[0])}. + + ) : null} @@ -241,9 +245,8 @@ export function BlueskyArchiveImportModal({ These are not in Cyd right now. If you deleted any of them from Cyd on purpose, importing brings them back. - {state.preview.summary.restorations.records - .slice(0, LISTED_RESTORATIONS) - .map((record) => ( + {state.preview.summary.restorations.records.map( + (record) => ( - ))} + ), + )} {state.preview.summary.restorations.total > - LISTED_RESTORATIONS ? ( + state.preview.summary.restorations.records.length ? ( …and{" "} {state.preview.summary.restorations.total - - LISTED_RESTORATIONS}{" "} + state.preview.summary.restorations.records.length}{" "} more. ) : null} @@ -302,6 +306,16 @@ export function BlueskyArchiveImportModal({ ); } +/** One restored record, short enough to sit inside a sentence. */ +function describeRecord(record: { + category: string; + id: string; + text: string | null; +}): string { + const text = record.text?.trim(); + return text ? `“${text.slice(0, 60)}”` : `one ${record.category} record`; +} + function totalRecords(account: { counts: { posts: number; chats: number; messages: number; follows: number }; }): number { diff --git a/hooks/__tests__/use-bluesky-archive-import.test.ts b/hooks/__tests__/use-bluesky-archive-import.test.ts new file mode 100644 index 0000000..65cd935 --- /dev/null +++ b/hooks/__tests__/use-bluesky-archive-import.test.ts @@ -0,0 +1,166 @@ +import { act, renderHook, waitFor } from "@testing-library/react-native"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { NO_SCHEDULED_REMINDERS } from "@/services/scheduled-reminder-sync"; +import { + createDiskBlueskyArchiveIntakeEnvironment, + createNodeBlueskyArchiveRestoreEnvironment, +} from "@/testUtils/archiveEnvironments"; +import { + useBlueskyArchiveImport, + type BlueskyArchiveImportRuntime, +} from "../use-bluesky-archive-import"; + +/** + * The import as somebody drives it: pick a file, watch it work, decide. + * + * The runtime is the seam — the picker, intake, restore and merge all come in + * from outside — so this runs the real archive services over the committed + * fixture and only stands in for the phone. What it is here to hold down is + * the ordering: an archive for an identity this device does not have is + * restored without asking, one it does have waits for a decision, and walking + * away in the middle leaves nothing behind and nothing on screen. + */ + +const FIXTURE = path.join( + __dirname, + "../../testUtils/fixtures/bluesky-archive/complete.cyd", +); + +jest.setTimeout(120_000); + +type Harness = { + root: string; + runtime: BlueskyArchiveImportRuntime; + stagingParent: string; +}; + +function harnessFor(): Harness { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "cyd-import-hook-")); + const stagingParent = path.join(root, "intake"); + const environment = createNodeBlueskyArchiveRestoreEnvironment({ + root: path.join(root, "app"), + }); + let intakes = 0; + + return { + root, + stagingParent, + runtime: { + pickArchive: async () => ({ uri: `file://${FIXTURE}` }), + intake: createDiskBlueskyArchiveIntakeEnvironment(stagingParent), + restore: environment, + merge: environment, + newIntakeId: () => `intake-${(intakes += 1)}`, + }, + }; +} + +/** + * The hook opens the picked file itself, through the device reader. Under Node + * there is no such reader, so the fixture is served from memory instead. + */ +jest.mock("@/services/archive-import", () => { + const actual = jest.requireActual< + typeof import("@/services/archive-import") + >("@/services/archive-import"); + // eslint-disable-next-line @typescript-eslint/no-require-imports + const nodeFs = require("node:fs") as typeof import("node:fs"); + // eslint-disable-next-line @typescript-eslint/no-require-imports + const fixtures = require("@/testUtils/archiveFixtures") as typeof import("@/testUtils/archiveFixtures"); + return { + ...actual, + openBlueskyArchiveByteReader: (uri: string) => + fixtures.createMemoryByteReader( + new Uint8Array(nodeFs.readFileSync(uri.replace("file://", ""))), + ), + }; +}); + +describe("importing a Cyd Bluesky archive from the menu", () => { + let harness: Harness; + + beforeEach(() => { + harness = harnessFor(); + }); + + afterEach(() => { + fs.rmSync(harness.root, { recursive: true, force: true }); + }); + + it("restores an identity this device does not have, without asking", async () => { + const { result } = renderHook(() => + useBlueskyArchiveImport({ + runtime: harness.runtime, + reminders: NO_SCHEDULED_REMINDERS, + }), + ); + + await act(async () => { + await result.current.start(); + }); + + await waitFor(() => { + expect(result.current.state.status).toBe("done"); + }); + expect(result.current.state).toMatchObject({ + title: "Restored @glittertop-cyd.bsky.social", + }); + // Staging is the import's working state, and the import is over. + expect(fs.readdirSync(harness.stagingParent)).toEqual([]); + }); + + it("waits for a decision before merging into an account it already has", async () => { + const { result } = renderHook(() => + useBlueskyArchiveImport({ + runtime: harness.runtime, + reminders: NO_SCHEDULED_REMINDERS, + }), + ); + + await act(async () => { + await result.current.start(); + }); + await act(async () => { + await result.current.start(); + }); + + expect(result.current.state.status).toBe("reviewing"); + + await act(async () => { + await result.current.confirmMerge(); + }); + + expect(result.current.state).toMatchObject({ + status: "done", + lines: ["This archive held nothing that account did not already have."], + }); + }); + + it("leaves nothing on screen or in staging when somebody walks away", async () => { + const { result } = renderHook(() => + useBlueskyArchiveImport({ + runtime: harness.runtime, + reminders: NO_SCHEDULED_REMINDERS, + }), + ); + + await act(async () => { + await result.current.start(); + }); + // A second import of the same identity stops to be reviewed, which is the + // moment somebody is most likely to change their mind. + const merging = act(async () => { + await result.current.start(); + }); + act(() => { + result.current.cancel(); + }); + await merging; + + expect(result.current.state.status).toBe("idle"); + expect(fs.readdirSync(harness.stagingParent)).toEqual([]); + }); +}); diff --git a/hooks/use-bluesky-archive-import.ts b/hooks/use-bluesky-archive-import.ts index 16d032b..134dc3f 100644 --- a/hooks/use-bluesky-archive-import.ts +++ b/hooks/use-bluesky-archive-import.ts @@ -82,8 +82,6 @@ export type BlueskyArchiveImportRuntime = { intake: BlueskyArchiveIntakeEnvironment; restore: BlueskyArchiveRestoreEnvironment; merge: BlueskyArchiveMergeEnvironment; - /** Server-scheduled reminders, which reconciliation has to keep honest. */ - reminders: ScheduledReminderSync; newIntakeId(): string; }; @@ -104,7 +102,6 @@ function createDeviceRuntime(): BlueskyArchiveImportRuntime { intake: createBlueskyArchiveIntakeEnvironment(), restore: createBlueskyArchiveRestoreEnvironment(), merge: createBlueskyArchiveMergeEnvironment(), - reminders: NO_SCHEDULED_REMINDERS, newIntakeId: () => Crypto.randomUUID(), }; } @@ -113,7 +110,6 @@ type Session = { intakeId: string; sourceUri: string; confirmedLargeArchive: boolean; - cancelled: boolean; /** Set once intake ends *prepared*, so a later step can reach the staging. */ prepared: PreparedBlueskyArchive | null; }; @@ -163,8 +159,30 @@ export function useBlueskyArchiveImport( runtime ?? null, ); const sessionRef = useRef(null); + /** + * Which import the person is actually in. + * + * Every step of an import is asynchronous and none of them can be called + * back: reading an archive off the device, or working out what a merge would + * do, runs to completion whatever happens on screen. Walking away moves the + * count on, and a step that finishes afterwards finds it has been left + * behind and says nothing — otherwise a cancelled import would reappear, + * pointing at staging it no longer has. + */ + const generationRef = useRef(0); + + const settle = useCallback( + (generation: number, next: BlueskyArchiveImportState): boolean => { + if (generationRef.current !== generation) { + return false; + } + setState(next); + return true; + }, + [], + ); - const environments = useCallback((): BlueskyArchiveImportRuntime => { + const importRuntime = useCallback((): BlueskyArchiveImportRuntime => { if (!runtimeRef.current) { runtimeRef.current = createDeviceRuntime(); } @@ -178,19 +196,20 @@ export function useBlueskyArchiveImport( return; } try { - cancelBlueskyArchiveIntake(environments().intake, session.intakeId); + cancelBlueskyArchiveIntake(importRuntime().intake, session.intakeId); } catch (error) { console.warn("[archive-import] could not clear staging", error); } sessionRef.current = null; - }, [environments]); + }, [importRuntime]); const runRestore = useCallback( async ( prepared: PreparedBlueskyArchive, environment: BlueskyArchiveRestoreEnvironment, + generation: number, ): Promise => { - setState({ + settle(generation, { status: "working", message: "Restoring the account…", fraction: null, @@ -203,7 +222,7 @@ export function useBlueskyArchiveImport( stagingRoot: prepared.stagingRoot, }, onProgress: (progress) => - setState({ + settle(generation, { status: "working", message: "Restoring the account…", fraction: @@ -216,7 +235,7 @@ export function useBlueskyArchiveImport( sessionRef.current = null; emitLocalAccountsChanged(); - setState({ + settle(generation, { status: "done", title: `Restored @${result.handle}`, lines: [ @@ -227,7 +246,7 @@ export function useBlueskyArchiveImport( ], }); }, - [], + [settle], ); const openMergePreview = useCallback( @@ -235,8 +254,9 @@ export function useBlueskyArchiveImport( prepared: PreparedBlueskyArchive, environment: BlueskyArchiveMergeEnvironment, account: LocalAccountIdentity, + generation: number, ): Promise => { - setState({ + settle(generation, { status: "working", message: "Working out what this archive would add…", fraction: null, @@ -251,56 +271,63 @@ export function useBlueskyArchiveImport( account, }); - setState({ + settle(generation, { status: "reviewing", preview, handle: account.handle ?? preview.accountDid, }); }, - [], + [settle], ); /** Where this archive goes, decided by the DID intake reported. */ const route = useCallback( async ( prepared: PreparedBlueskyArchive, - environment: Pick, + ports: Pick, + generation: number, ): Promise => { const identities = - await environment.merge.listLocalAccountIdentities(); + await ports.merge.listLocalAccountIdentities(); const destination = chooseBlueskyArchiveImportDestination( prepared.metadata.accountDid, identities, ); if (destination.kind === "restore") { - await runRestore(prepared, environment.restore); + await runRestore(prepared, ports.restore, generation); return; } if (destination.kind === "merge") { - await openMergePreview(prepared, environment.merge, destination.account); + await openMergePreview( + prepared, + ports.merge, + destination.account, + generation, + ); return; } - setState({ + const reconciliation = await previewDuplicateReconciliation( + ports.merge, + { did: destination.did, accounts: identities }, + ); + settle(generation, { status: "reconciling", message: "This device has more than one Bluesky account for the identity in this archive. Choose which one to keep before importing.", - preview: await previewDuplicateReconciliation(environment.merge, { - did: destination.did, - accounts: identities, - }), + preview: reconciliation, }); }, - [openMergePreview, runRestore], + [openMergePreview, runRestore, settle], ); const run = useCallback( - async (session: Session): Promise => { - const { intake, restore, merge } = environments(); + async (session: Session, generation: number): Promise => { + const { intake, restore, merge } = importRuntime(); sessionRef.current = session; - setState({ + settle(generation, { status: "working", message: "Reading the archive…", fraction: null, @@ -313,9 +340,11 @@ export function useBlueskyArchiveImport( openReader: async () => openBlueskyArchiveByteReader(session.sourceUri), confirmLargeArchive: session.confirmedLargeArchive, - shouldCancel: () => session.cancelled, + // Intake asks between payloads, so walking away stops the extraction + // itself rather than only what it reports. + shouldCancel: () => generationRef.current !== generation, onProgress: (progress) => - setState({ + settle(generation, { status: "working", message: "Reading the archive…", fraction: @@ -328,7 +357,7 @@ export function useBlueskyArchiveImport( if (outcome.status === "cancelled") { sessionRef.current = null; - setState({ status: "idle" }); + settle(generation, { status: "idle" }); return; } if (outcome.status === "rejected") { @@ -337,52 +366,69 @@ export function useBlueskyArchiveImport( // again resumes. Nothing offers to resume from here, so a rejection // ends the import and takes any staging with it either way. discardStaging(); - setState({ status: "failed", message: outcome.message }); + settle(generation, { status: "failed", message: outcome.message }); return; } if (outcome.status === "needs-confirmation") { - setState({ status: "needs-confirmation", message: outcome.message }); + settle(generation, { + status: "needs-confirmation", + message: outcome.message, + }); + return; + } + + if (generationRef.current !== generation) { + // Somebody walked away while the last of the archive was being read. + // Intake finished anyway, so the staging it prepared is this import's + // to clear. + discardStaging(); return; } sessionRef.current = { ...session, prepared: outcome }; - await route(outcome, { restore, merge }); + await route(outcome, { restore, merge }, generation); }, - [discardStaging, environments, route], + [discardStaging, importRuntime, route, settle], ); /** Pick the archive and take it as far as it can go without a decision. */ const start = useCallback(async (): Promise => { + const generation = (generationRef.current += 1); try { - const picked = await environments().pickArchive(); + const picked = await importRuntime().pickArchive(); if (!picked) { return; } - await run({ - intakeId: environments().newIntakeId(), - sourceUri: picked.uri, - confirmedLargeArchive: false, - cancelled: false, - prepared: null, - }); + await run( + { + intakeId: importRuntime().newIntakeId(), + sourceUri: picked.uri, + confirmedLargeArchive: false, + prepared: null, + }, + generation, + ); } catch (error) { discardStaging(); - setState({ status: "failed", message: messageFor(error) }); + settle(generation, { status: "failed", message: messageFor(error) }); } - }, [discardStaging, environments, run]); + }, [discardStaging, importRuntime, run, settle]); const confirmLargeArchive = useCallback(async (): Promise => { const session = sessionRef.current; if (!session) { return; } + // The same import, carried on: the generation does not move, so cancelling + // still reaches everything this starts. + const generation = generationRef.current; try { - await run({ ...session, confirmedLargeArchive: true }); + await run({ ...session, confirmedLargeArchive: true }, generation); } catch (error) { discardStaging(); - setState({ status: "failed", message: messageFor(error) }); + settle(generation, { status: "failed", message: messageFor(error) }); } - }, [discardStaging, run]); + }, [discardStaging, run, settle]); /** Commit a merge the person has looked at. */ const confirmMerge = useCallback(async (): Promise => { @@ -390,19 +436,20 @@ export function useBlueskyArchiveImport( return; } const { preview, handle } = state; + const generation = generationRef.current; try { - setState({ + settle(generation, { status: "working", message: "Merging the archive…", fraction: null, cancellable: false, }); const result = await commitBlueskyArchiveMerge( - environments().merge, + importRuntime().merge, preview, { onProgress: (progress) => - setState({ + settle(generation, { status: "working", message: "Merging the archive…", fraction: @@ -416,7 +463,7 @@ export function useBlueskyArchiveImport( sessionRef.current = null; emitLocalAccountsChanged(); - setState({ + settle(generation, { status: "done", title: `Merged into @${handle}`, lines: @@ -430,9 +477,9 @@ export function useBlueskyArchiveImport( }); } catch (error) { discardStaging(); - setState({ status: "failed", message: messageFor(error) }); + settle(generation, { status: "failed", message: messageFor(error) }); } - }, [discardStaging, environments, state]); + }, [discardStaging, importRuntime, settle, state]); /** * Keep one of the duplicate Bluesky local accounts, then carry on importing. @@ -450,9 +497,10 @@ export function useBlueskyArchiveImport( return; } const { prepared } = session; - const { merge } = environments(); + const { merge } = importRuntime(); + const generation = generationRef.current; try { - setState({ + settle(generation, { status: "working", message: "Merging the duplicate accounts…", fraction: null, @@ -465,10 +513,7 @@ export function useBlueskyArchiveImport( settingsFromUuid: choice.settingsFromUuid, }); emitLocalAccountsChanged(); - await syncReminders( - reminders ?? environments().reminders, - reconciled, - ); + await syncReminders(reminders ?? NO_SCHEDULED_REMINDERS, reconciled); const survivor = (await merge.listLocalAccountIdentities()).find( (account) => account.uuid === choice.survivingUuid, @@ -478,26 +523,30 @@ export function useBlueskyArchiveImport( "Cyd could not find the Bluesky account it just kept.", ); } - await openMergePreview(prepared, merge, survivor); + await openMergePreview(prepared, merge, survivor, generation); } catch (error) { discardStaging(); - setState({ status: "failed", message: messageFor(error) }); + settle(generation, { status: "failed", message: messageFor(error) }); } }, - [discardStaging, environments, openMergePreview, reminders, state], + [discardStaging, importRuntime, openMergePreview, reminders, settle, state], ); - /** Walk away: nothing has been written, and nothing stays staged. */ + /** + * Walk away: nothing has been written, and nothing stays staged. + * + * Moving the generation on is what makes this final. A step already in + * flight — an archive being read, a merge being worked out — cannot be + * stopped mid-call, but it can be made to report to nobody. + */ const cancel = useCallback((): void => { - const session = sessionRef.current; - if (session) { - session.cancelled = true; - } + generationRef.current += 1; discardStaging(); setState({ status: "idle" }); }, [discardStaging]); const dismiss = useCallback((): void => { + generationRef.current += 1; sessionRef.current = null; setState({ status: "idle" }); }, []); diff --git a/jest-setup.ts b/jest-setup.ts index 281934d..28591f1 100644 --- a/jest-setup.ts +++ b/jest-setup.ts @@ -188,6 +188,38 @@ jest.mock("expo-crypto", () => { }; }); +// Mock expo-device and expo-notifications: nothing under test is a phone, and +// no test may put a notifications prompt anywhere near itself. Tests about +// push notifications mock these again with the behaviour they need. +jest.mock("expo-device", () => ({ + __esModule: true, + isDevice: false, +})); + +jest.mock("expo-notifications", () => ({ + __esModule: true, + PermissionStatus: { + GRANTED: "granted", + DENIED: "denied", + UNDETERMINED: "undetermined", + }, + AndroidImportance: { HIGH: "high" }, + getPermissionsAsync: jest.fn(() => Promise.resolve({ status: "denied" })), + requestPermissionsAsync: jest.fn(() => Promise.resolve({ status: "denied" })), + setNotificationChannelAsync: jest.fn(), + getExpoPushTokenAsync: jest.fn(), + addNotificationReceivedListener: jest.fn(() => ({ remove: jest.fn() })), + addNotificationResponseReceivedListener: jest.fn(() => ({ + remove: jest.fn(), + })), + setNotificationHandler: jest.fn(), +})); + +// Mock expo-localization: only the calendar's time zone is ever read. +jest.mock("expo-localization", () => ({ + getCalendars: jest.fn(() => [{ timeZone: "UTC" }]), +})); + // Mock expo-document-picker: tests never open a real file picker, and an // import that is cancelled is the default because it touches nothing. jest.mock("expo-document-picker", () => ({ diff --git a/services/archive-merge/__tests__/duplicates.test.ts b/services/archive-merge/__tests__/duplicates.test.ts index fbd10b4..14374be 100644 --- a/services/archive-merge/__tests__/duplicates.test.ts +++ b/services/archive-merge/__tests__/duplicates.test.ts @@ -190,6 +190,19 @@ describe("reconciling a Bluesky identity held by two local accounts", () => { counts: { posts: 1, profiles: 1 }, settings: { settingSavePosts: 0, settingDeleteLikes: 1 }, }); + // Keeping the restored account brings the other one's lone post with it, + // and says which post that is before anybody commits to it. + const survivor = preview.accounts.find( + (account) => account.uuid === harness.survivor.uuid, + ); + expect(survivor?.gains.records).toEqual([ + { + category: "posts", + id: ORPHAN_URI, + text: "only on the other copy", + createdAt: "2026-02-02T00:00:00.000Z", + }, + ]); expect( preview.accounts.find( (account) => account.uuid === harness.survivor.uuid, diff --git a/services/archive-merge/__tests__/merge-plan.test.ts b/services/archive-merge/__tests__/merge-plan.test.ts index eeecb88..9b412fa 100644 --- a/services/archive-merge/__tests__/merge-plan.test.ts +++ b/services/archive-merge/__tests__/merge-plan.test.ts @@ -168,6 +168,28 @@ describe("planning a Cyd Bluesky archive merge", () => { expect(plan.summary.posts).toEqual({ added: 0, updated: 1, unchanged: 0 }); }); + it("does not let an archive that counted nothing zero out a count", () => { + const plan = planBlueskyArchiveMerge( + existing({ + posts: [ + { + ...post({ likeCount: 5, replyCount: 2, savedAt: 5_000 }), + preserve: 0, + }, + ], + }), + incoming({ + posts: [ + archived( + post({ likeCount: 0, replyCount: 3, savedAt: 9_000 }), + ), + ], + }), + ); + + expect(plan.posts[0]).toMatchObject({ likeCount: 5, replyCount: 3 }); + }); + it("keeps a like the archive was taken before, and takes one it was taken after", () => { const plan = planBlueskyArchiveMerge( existing({ diff --git a/services/archive-merge/duplicates.ts b/services/archive-merge/duplicates.ts index 5b6cf98..4f898c9 100644 --- a/services/archive-merge/duplicates.ts +++ b/services/archive-merge/duplicates.ts @@ -4,9 +4,9 @@ import { readExistingAccountRows } from "./account-rows"; import { BlueskyArchiveMergeError } from "./errors"; import { planBlueskyArchiveMerge, - type BlueskyArchiveMergeSummary, + type RestorationPreview, } from "./merge-plan"; -import { countPlannedWrites, writeMergedAccountRows } from "./merge-writer"; +import { writeMergedAccountRows } from "./merge-writer"; import type { BlueskyArchiveMergeEnvironment, ReconcilableAccountSettings, @@ -48,6 +48,18 @@ export type DuplicateAccountPreview = { handle: string | null; counts: DuplicateAccountCounts; settings: ReconcilableAccountSettings; + /** + * What this account would take on from the others if it were the one kept. + * + * Named rather than counted, for the same reason an archive merge names them + * (ADR 0018): a record missing from this account may be missing because + * somebody deleted it from Cyd here on purpose, and keeping this account + * brings it back. + */ + gains: { + total: number; + records: RestorationPreview[]; + }; }; export type DuplicateReconciliationPreview = { @@ -69,9 +81,6 @@ export type DuplicateReconciliationResult = { did: string; survivingUuid: string; removedUuids: string[]; - /** Rows the survivor gained, by table, across all the accounts it absorbed. */ - summary: BlueskyArchiveMergeSummary[]; - written: number; }; /** Every DID this installation holds more than one Bluesky local account for. */ @@ -105,14 +114,35 @@ export async function previewDuplicateReconciliation( identity: DuplicateBlueskyIdentity, ): Promise { const holders = holdersOf(identity.did, identity.accounts); - const accounts: DuplicateAccountPreview[] = []; + const rows = new Map(); + for (const account of holders) { + rows.set(account.uuid, await readAccount(environment, account.uuid)); + } + const accounts: DuplicateAccountPreview[] = []; for (const account of holders) { + const own = rows.get(account.uuid); + if (!own) { + continue; + } + // Planning the union in memory is how the preview and the reconciliation + // stay the same answer: one set of rules, asked a question rather than + // told to write. + const gains = holders + .filter((other) => other.uuid !== account.uuid) + .map((other) => rows.get(other.uuid)) + .filter((other): other is ExistingAccountRows => other !== undefined) + .map((other) => planBlueskyArchiveMerge(own, other).summary.restorations); + accounts.push({ uuid: account.uuid, handle: account.handle, - counts: countRows(await readAccount(environment, account.uuid)), + counts: countRows(own), settings: await environment.readAccountSettings(account.uuid), + gains: { + total: gains.reduce((sum, restoration) => sum + restoration.total, 0), + records: gains.flatMap((restoration) => restoration.records), + }, }); } @@ -143,9 +173,6 @@ export async function reconcileDuplicateBlueskyAccounts( choice.settingsFromUuid, ); - const summary: BlueskyArchiveMergeSummary[] = []; - let written = 0; - for (const account of doomed) { const incoming = await adoptMedia( environment, @@ -165,8 +192,6 @@ export async function reconcileDuplicateBlueskyAccounts( await survivor.transaction(async () => { await writeMergedAccountRows(survivor, plan); }); - summary.push(plan.summary); - written += countPlannedWrites(plan); } finally { await survivor.close(); } @@ -177,26 +202,41 @@ export async function reconcileDuplicateBlueskyAccounts( await environment.applyAccountSettings(choice.survivingUuid, settings); for (const account of doomed) { - await environment.removeLocalAccount({ - accountId: null, - accountUuid: account.uuid, - }); + await environment.removeLocalAccount(account.uuid); } // With one Bluesky local account left for the identity, the rule that there // can only be one goes back on, so a later archive import has somewhere - // unambiguous to land (ADR 0011). + // unambiguous to land (ADR 0011). Putting the index back does nothing on a + // database that never lost it, so the accounts are counted rather than + // trusted: an identity still held twice here means a removal did not take, + // and saying so beats leaving an import with nowhere to go. await environment.enforceOneAccountPerDid(); + await requireSingleHolder(environment, choice.did); return { did: choice.did, survivingUuid: choice.survivingUuid, removedUuids: doomed.map((account) => account.uuid), - summary, - written, }; } +/** Check the rule the reconciliation exists to restore actually holds now. */ +async function requireSingleHolder( + environment: BlueskyArchiveMergeEnvironment, + did: string, +): Promise { + const duplicates = findDuplicateBlueskyIdentities( + await environment.listLocalAccountIdentities(), + ); + if (duplicates.some((duplicate) => duplicate.did === did)) { + throw new BlueskyArchiveMergeError( + "duplicate-identity", + "Cyd merged the accounts but could not remove the duplicates, so this device still has more than one Bluesky account for that identity.", + ); + } +} + function holdersOf( did: string, accounts: LocalAccountIdentity[], diff --git a/services/archive-merge/environment.ts b/services/archive-merge/environment.ts index e4b2b34..86445be 100644 --- a/services/archive-merge/environment.ts +++ b/services/archive-merge/environment.ts @@ -58,8 +58,18 @@ function asMergeableAccountDatabase( }; } +/** + * Where a media file lives, in the exact form storing it reports back. + * + * A merge previews the rows it would write before it copies any bytes, so the + * predicted path has to be the one `storeAccountMedia` ends up returning — + * otherwise every import would look like it had media to update. Going through + * `File` is what guarantees they agree: the same normalization on both sides. + */ function mediaUri(accountUuid: string, fileName: string): string { - return `${buildAccountPaths("bluesky", accountUuid).mediaDir}${fileName}`; + return new File( + `${buildAccountPaths("bluesky", accountUuid).mediaDir}${fileName}`, + ).uri; } export function createBlueskyArchiveMergeEnvironment(): BlueskyArchiveMergeEnvironment { @@ -154,18 +164,21 @@ export function createBlueskyArchiveMergeEnvironment(): BlueskyArchiveMergeEnvir ); }, - removeLocalAccount: async (account) => { - if (account.accountId !== null) { - await deleteAccount(account.accountId); + removeLocalAccount: async (accountUuid) => { + const account = (await listAccounts()).find( + (candidate) => candidate.uuid === accountUuid, + ); + if (account) { + // `deleteAccount` takes the Bluesky connection with it, which is the + // right end for an account nobody is keeping. + await deleteAccount(account.id); } const directory = new Directory( - buildAccountPaths("bluesky", account.accountUuid).accountDir, + buildAccountPaths("bluesky", accountUuid).accountDir, ); if (directory.exists) { directory.delete(); } }, - - now: () => new Date(), }; } diff --git a/services/archive-merge/index.ts b/services/archive-merge/index.ts index f0d503d..5ccd7ed 100644 --- a/services/archive-merge/index.ts +++ b/services/archive-merge/index.ts @@ -23,6 +23,7 @@ export { } from "./duplicates"; export type { DuplicateBlueskyIdentity, + DuplicateAccountCounts, DuplicateAccountPreview, DuplicateReconciliationChoice, DuplicateReconciliationPreview, diff --git a/services/archive-merge/merge-plan.ts b/services/archive-merge/merge-plan.ts index a5810e0..9e8e1a1 100644 --- a/services/archive-merge/merge-plan.ts +++ b/services/archive-merge/merge-plan.ts @@ -1,6 +1,7 @@ import { earliest, latest, + preferCounted, preferPopulated, unionFlag, } from "./union"; @@ -314,7 +315,7 @@ function unionPost( ): ExistingPostRow { const newer = incoming.savedAt > local.savedAt; const metric = (left: number, right: number): number => - newer ? right : left; + preferCounted(left, right, newer); return { uri: local.uri, diff --git a/services/archive-merge/merge.ts b/services/archive-merge/merge.ts index 2070ee8..55baeee 100644 --- a/services/archive-merge/merge.ts +++ b/services/archive-merge/merge.ts @@ -1,12 +1,11 @@ import { placeArchivedMedia, + predictArchivedMedia, readBlueskyInterchange, - restoredMediaFileName, translateInterchangeToMobileRows, type BlueskyInterchangeSnapshot, type InterchangeAsset, type LocalAccountIdentity, - type RestoredAssetPlacement, type RestoredMobileAccount, type UnrestorableContent, } from "@/services/archive-restore"; @@ -122,10 +121,8 @@ export async function previewBlueskyArchiveMerge( requireMatchingIdentity(snapshot.archive.account_did, request.account); const incoming = translateInterchangeToMobileRows(snapshot, { - placements: predictPlacements( - environment, - request.account.uuid, - snapshot.assets, + placements: predictArchivedMedia(snapshot.assets, (fileName) => + environment.accountMediaUri(request.account.uuid, fileName), ), }); const plan = await planAgainstAccount( @@ -254,36 +251,6 @@ function requireMatchingIdentity( } } -/** Where each packaged asset will live once the merge copies it in. */ -function predictPlacements( - environment: BlueskyArchiveMergeEnvironment, - accountUuid: string, - assets: InterchangeAsset[], -): Map { - const placements = new Map(); - for (const asset of assets) { - if (asset.availability !== "available" || !asset.archive_path || !asset.sha256) { - placements.set(asset.id, { - assetId: asset.id, - availability: "missing", - reason: - asset.unavailable_reason ?? - "This file was not included in the archive.", - }); - continue; - } - placements.set(asset.id, { - assetId: asset.id, - availability: "restored", - localPath: environment.accountMediaUri( - accountUuid, - restoredMediaFileName(asset.sha256), - ), - }); - } - return placements; -} - /** * What the archive's media amounts to for this account. * diff --git a/services/archive-merge/ports.ts b/services/archive-merge/ports.ts index 1e7b57f..4c404a2 100644 --- a/services/archive-merge/ports.ts +++ b/services/archive-merge/ports.ts @@ -1,5 +1,4 @@ import type { - DiscardableAccount, LocalAccountIdentity, PreparedArchiveLocation, PreparedArchiveStore, @@ -120,15 +119,17 @@ export type BlueskyArchiveMergeEnvironment = { * Mobile has carried a unique index on `bsky_account.did` since its first * migration, so duplicates can only reach an installation from outside it — * a database restored from an OS backup, or one that predates the index. - * Reconciliation ends by putting the rule back, which is also the check that - * the duplicates really are gone: the statement fails while any remain. + * Putting the rule back is a no-op on a database that still has it, which is + * why reconciliation does not treat it as proof: it checks the accounts + * itself afterwards. */ enforceOneAccountPerDid(): Promise; - /** Remove a reconciled-away Bluesky local account and its storage. */ - removeLocalAccount(account: DiscardableAccount): Promise; - - now(): Date; + /** + * Remove a reconciled-away Bluesky local account, its storage and its + * Bluesky connection, identified the way reconciliation knows it. + */ + removeLocalAccount(accountUuid: string): Promise; }; export type { PreparedArchiveLocation, StoredMediaFile }; diff --git a/services/archive-merge/union.ts b/services/archive-merge/union.ts index 610b337..16fd0a9 100644 --- a/services/archive-merge/union.ts +++ b/services/archive-merge/union.ts @@ -32,6 +32,30 @@ export function preferPopulated( return incomingIsNewer ? incoming : local; } +/** + * An engagement count, where a zero is usually "not counted". + * + * The interchange model carries metrics inside a record's payload, and an + * archive written by a client that did not capture them translates to zero + * rather than to nothing. A zero is therefore not an observation that a post + * has no likes, and must not overwrite a number this device actually saw. A + * count that really did fall to zero is the price, and it is the safe side of + * the trade: nothing is lost, and the next save corrects it. + */ +export function preferCounted( + local: number, + incoming: number, + incomingIsNewer: boolean, +): number { + if (incoming === 0) { + return local; + } + if (local === 0) { + return incoming; + } + return incomingIsNewer ? incoming : local; +} + /** A flag either side set stays set: a union never takes a like back. */ export function unionFlag( local: number | null, diff --git a/services/archive-restore/index.ts b/services/archive-restore/index.ts index a4156c1..f5839b2 100644 --- a/services/archive-restore/index.ts +++ b/services/archive-restore/index.ts @@ -43,7 +43,11 @@ export type { BlueskyInterchangeSnapshot, InterchangeAsset, } from "./interchange-reader"; -export { placeArchivedMedia, restoredMediaFileName } from "./media"; +export { + placeArchivedMedia, + predictArchivedMedia, + restoredMediaFileName, +} from "./media"; export { translateInterchangeToMobileRows } from "./mobile-rows"; export type { MobileBookmarkWrite, diff --git a/services/archive-restore/media.ts b/services/archive-restore/media.ts index b05f416..b547a49 100644 --- a/services/archive-restore/media.ts +++ b/services/archive-restore/media.ts @@ -18,6 +18,60 @@ export function restoredMediaFileName(sha256: string): string { return `sha256-${sha256}`; } +/** + * What an asset the archive cannot supply looks like, wherever it is noticed. + * + * A merge works this out before it copies anything, so that somebody can be + * shown the rows it would write; a restore works it out as it copies. Both + * have to reach the same answer, so they ask the same function. + */ +function missingPlacement(asset: InterchangeAsset): RestoredAssetPlacement { + return { + assetId: asset.id, + availability: "missing", + reason: + asset.unavailable_reason ?? "This file was not included in the archive.", + }; +} + +/** Whether the archive claims to carry this file's bytes at all. */ +function isPackaged( + asset: InterchangeAsset, +): asset is InterchangeAsset & { archive_path: string; sha256: string } { + return ( + asset.availability === "available" && + asset.archive_path !== null && + asset.sha256 !== null + ); +} + +/** + * Where each packaged asset will end up, without moving a byte. + * + * Media is content-addressed, so its path is a fact about the file rather than + * a result of copying it. That is what lets a merge plan the exact rows it + * would write before anybody has agreed to the merge (ADR 0018). + */ +export function predictArchivedMedia( + assets: InterchangeAsset[], + mediaUriFor: (fileName: string) => string, +): Map { + const placements = new Map(); + for (const asset of assets) { + placements.set( + asset.id, + isPackaged(asset) + ? { + assetId: asset.id, + availability: "restored", + localPath: mediaUriFor(restoredMediaFileName(asset.sha256)), + } + : missingPlacement(asset), + ); + } + return placements; +} + /** The one capability placing media needs, out of the larger environments. */ export type MediaStore = { storeAccountMedia( @@ -50,14 +104,8 @@ export async function placeArchivedMedia( let placed = 0; for (const asset of options.assets) { - if (asset.availability !== "available" || !asset.archive_path || !asset.sha256) { - placements.set(asset.id, { - assetId: asset.id, - availability: "missing", - reason: - asset.unavailable_reason ?? - "This file was not included in the archive.", - }); + if (!isPackaged(asset)) { + placements.set(asset.id, missingPlacement(asset)); continue; } diff --git a/services/scheduled-reminder-sync.ts b/services/scheduled-reminder-sync.ts index 77f41bb..a800e65 100644 --- a/services/scheduled-reminder-sync.ts +++ b/services/scheduled-reminder-sync.ts @@ -1,6 +1,12 @@ +import * as Localization from "expo-localization"; + import { listAccounts } from "@/database/accounts"; import { getAccountScheduleSettings } from "@/database/schedule-settings"; import type CydAPIClient from "@/services/cyd-api-client"; +import { + hasNotificationPermission, + registerForPushNotifications, +} from "@/services/push-notifications"; /** * Keeping server-scheduled Bluesky reminders pointed at the right account. @@ -8,15 +14,15 @@ import type CydAPIClient from "@/services/cyd-api-client"; * Mobile delivers reminders as push scheduled by Cyd's server, keyed by the * local-account UUID (ADR 0005). A merge never touches that — the account * keeps its UUID and its schedule — but reconciling duplicates does: one UUID - * stops existing, and the survivor may come out of it with the schedule that - * belonged to the other one. + * stops existing, and the survivor may come out of it holding a schedule that + * belonged to the other one, which the server has no push token for. * * So reconciliation ends by telling the server what is true now. A reminder * still only prompts somebody to open Cyd and review: nothing here authorizes * unattended deletion, and there is nothing in the payload that could. */ export type ScheduledReminderSync = { - /** Re-send the surviving account's schedule as it now stands. */ + /** Re-send the surviving account's schedule, and the token to deliver it. */ resync(accountUuid: string): Promise; /** Stop reminders for a Bluesky local account that no longer exists. */ retire(accountUuid: string): Promise; @@ -45,6 +51,25 @@ export function createScheduledReminderSync( return; } const settings = await getAccountScheduleSettings(account.id); + + // A schedule the survivor inherited may never have had a push token + // bound to this UUID, and the server cannot deliver a reminder without + // one. Permission is only ever read here, never asked for: an import is + // the wrong moment to put a notifications prompt in front of somebody, + // and a person with no permission granted had no reminders to keep. + if (settings.scheduleDeletion && (await hasNotificationPermission())) { + const token = await registerForPushNotifications(); + if (token.success && token.token && token.platform) { + await apiClient.registerPushToken({ + push_token: token.token, + platform: token.platform, + account_uuid: accountUuid, + account_handle: account.handle, + timezone: Localization.getCalendars()[0]?.timeZone ?? "UTC", + }); + } + } + await apiClient.updateScheduleSettings({ account_uuid: accountUuid, schedule_enabled: settings.scheduleDeletion, diff --git a/testUtils/archiveEnvironments.ts b/testUtils/archiveEnvironments.ts index 2cb0bcc..18b6818 100644 --- a/testUtils/archiveEnvironments.ts +++ b/testUtils/archiveEnvironments.ts @@ -404,8 +404,8 @@ export function createNodeBlueskyArchiveRestoreEnvironment( ); }, - removeLocalAccount: async (account: DiscardableAccount) => - removeAccount(account), + removeLocalAccount: async (accountUuid: string) => + removeAccount({ accountId: null, accountUuid }), discardLocalAccount: async (account: DiscardableAccount) => removeAccount(account), From d9eb1ec3452522dcee15a8827e8680fa68606ced Mon Sep 17 00:00:00 2001 From: Micah Lee Date: Sun, 13 Sep 2026 15:21:57 -0700 Subject: [PATCH 3/9] Address what importing an archive on a device showed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Four things the fixtures could not see, found by restoring the committed archives onto a phone and following where they led. A restored Bluesky local account was showing a blank name and a "?" where its avatar goes. The archive is honest: an account that never set a display name exports an empty string, which is an absence rather than a name — the same thing the merge's own `populated` rule refuses to treat as an observation. Restore now stores it as nothing, and the fallbacks both account screens had their own broken copy of live in one place: an account is named by its handle when it has nothing better, and one with no avatar gets a person rather than a punctuation mark. A Cyd Bluesky archive never carries an avatar at all, so this is what a restored account always looks like until it is connected. Signing in from the import dialog authorized the account and left it asking to be authorized again. Whether Cyd can act on a Bluesky local account is cached in that account's own database, and the check returns the cached "signed out" without reading the stored Bluesky connection unless it is forced — which is exactly what an account that has never been connected holds. `connectBlueskyAccount` makes the forced check part of signing in rather than something each caller remembers, which matters most for the caller furthest from the account screen: an account restored from an archive is signed in from the import that created it. `add-account.tsx` still does this inline and could adopt it. Merging an archive that carried a file an earlier export could not described itself as changing nothing. The merge was right — the plan upgraded the failed download and the commit wrote it — but the sentence read three of the summary's nine tables and missed the one that changed. Both the preview and the report after it now ask `totalMergeChanges`, which groups every table into what somebody recognises: records, files, and the rows a record needs to render. Its map is exhaustive over the summary's own keys, so a tenth table will not compile until somebody says what it is. The restore dialog broke the account's handle across two lines mid-word. The title is now the verb alone with the handle under it, and a handle too long for one line breaks before a dot instead of wherever it runs out of room. Nothing is truncated: the handle is how somebody knows which account this is. The dialog also offers the Bluesky sign-in a restored account needs, instead of only "Done". merge.test.ts gains the recovery somebody actually performs — exporting again once a failed download finished, and importing that over the account the first export built. Every existing merge test restores and merges the same fixture, which is the idempotent path, so nothing exercised an upgrade at all. Co-Authored-By: Claude Opus 5 (1M context) --- app/account/[accountId].tsx | 67 ++--------- app/index.tsx | 64 ++-------- components/BlueskyArchiveImportModal.tsx | 110 ++++++++++++++---- components/CydAccountBar.tsx | 36 ++++++ components/account/identity.tsx | 84 +++++++++++++ .../use-bluesky-archive-import.test.ts | 6 +- hooks/use-bluesky-archive-import.ts | 76 ++++++++++-- services/__tests__/bluesky-sign-in.test.ts | 83 +++++++++++++ .../__tests__/merge-plan.test.ts | 67 ++++++++++- .../archive-merge/__tests__/merge.test.ts | 85 +++++++++++++- services/archive-merge/index.ts | 3 +- services/archive-merge/merge-plan.ts | 70 +++++++++++ .../__tests__/mobile-rows.test.ts | 15 +++ services/archive-restore/mobile-rows.ts | 12 +- services/bluesky-sign-in.ts | 48 ++++++++ 15 files changed, 676 insertions(+), 150 deletions(-) create mode 100644 components/account/identity.tsx create mode 100644 services/__tests__/bluesky-sign-in.test.ts create mode 100644 services/bluesky-sign-in.ts diff --git a/app/account/[accountId].tsx b/app/account/[accountId].tsx index fb874ea..8200f96 100644 --- a/app/account/[accountId].tsx +++ b/app/account/[accountId].tsx @@ -36,6 +36,11 @@ import iconHome from "@/assets/images/icon-home.png"; import iconSave from "@/assets/images/icon-save.png"; import iconSchedule from "@/assets/images/icon-schedule.png"; +import { + AccountAvatar, + accountDisplayName, + accountUsername, +} from "@/components/account/identity"; import { getThemePalette } from "@/constants/theme"; import { ACCOUNT_AUTH_STATUS, @@ -311,14 +316,8 @@ export default function AccountScreen() { }, [account]), ); - const avatarUri = account?.avatarUrl ?? null; - const username = account?.handle - ? account.handle.startsWith("@") - ? account.handle - : `@${account.handle}` - : null; - const displayName = account?.displayName ?? username ?? "Unknown"; - const initial = displayName.replace(/^@/, "").charAt(0).toUpperCase() || "?"; + const username = account?.handle ? accountUsername(account.handle) : null; + const displayName = account ? accountDisplayName(account) : "Unknown"; const accountStatus = error ? "Unable to load account" : loading @@ -374,35 +373,11 @@ export default function AccountScreen() { headerBackTitle: "Back", headerTitle: () => ( - {avatarUri ? ( - - ) : ( - - - {initial} - - - )} + - {avatarUri ? ( - - ) : ( - - - {initial} - - - )} + void; + /** Connect the account an import just restored, from where it was restored. */ + onSignIn: (handle: string) => void; onCancel: () => void; onDismiss: () => void; }; @@ -45,6 +51,7 @@ export function BlueskyArchiveImportModal({ onConfirmLargeArchive, onConfirmMerge, onKeepAccount, + onSignIn, onCancel, onDismiss, }: BlueskyArchiveImportModalProps) { @@ -230,7 +237,10 @@ export function BlueskyArchiveImportModal({ {state.status === "reviewing" ? ( <> - Merge into @{state.handle} + Merge into + + + {breakableHandle(state.handle)} @@ -280,12 +290,26 @@ export function BlueskyArchiveImportModal({ {state.title} + + {breakableHandle(state.handle)} + {state.lines.map((line) => ( {line} ))} - {action("Done", onDismiss, "primary")} + {state.offerSignIn ? ( + <> + {action( + "Sign in to Bluesky", + () => onSignIn(state.handle), + "primary", + )} + {action("Not now", onDismiss)} + + ) : ( + action("Done", onDismiss, "primary") + )} ) : null} @@ -306,6 +330,20 @@ export function BlueskyArchiveImportModal({ ); } +/** + * A handle written so a line box breaks it where a reader would. + * + * A handle is a single token with no spaces in it, so a heading wide enough + * for most of one splits it wherever it happens to run out of room — + * "@glittertop-cyd.bsky" above ".social". A zero-width space before each dot + * offers the layout the same break points a person would choose, and leaves + * nothing on screen. Nothing is truncated: a handle is how somebody knows + * which account this is. + */ +function breakableHandle(handle: string): string { + return `@${handle.replace(/^@/, "")}`.replace(/\./g, "\u200B."); +} + /** One restored record, short enough to sit inside a sentence. */ function describeRecord(record: { category: string; @@ -327,33 +365,55 @@ function totalRecords(account: { ); } -/** One sentence about what this archive has that the account does not. */ -function describeMerge(preview: { - summary: { - posts: { added: number; updated: number }; - messages: { added: number; updated: number }; - follows: { added: number; updated: number }; - restorations: { total: number }; - }; - archive: { completeness: "complete" | "incomplete" }; -}): string { - const added = - preview.summary.posts.added + - preview.summary.messages.added + - preview.summary.follows.added; - const updated = - preview.summary.posts.updated + - preview.summary.messages.updated + - preview.summary.follows.updated; +/** `2 posts`, and `1 post` rather than `1 posts`. */ +function count(total: number, noun: string): string { + return `${total.toLocaleString()} ${noun}${total === 1 ? "" : "s"}`; +} + +/** "a, b and c", so a sentence can be built out of whatever is true. */ +function sentence(clauses: string[]): string { + if (clauses.length <= 1) { + return clauses[0] ?? ""; + } + return `${clauses.slice(0, -1).join(", ")} and ${clauses[clauses.length - 1]}`; +} - if (added === 0 && updated === 0) { +/** + * One sentence about what this archive has that the account does not. + * + * Every kind of change counts, not only the ones with a familiar name. An + * export taken again once a download finished differs from the one before it + * by a single image, and telling somebody that importing it changes nothing + * would be both wrong and the exact case they are trying to fix. + */ +function describeMerge(preview: BlueskyArchiveMergePreview): string { + const totals = totalMergeChanges(preview.summary); + + if (totals.total === 0) { return "This archive holds nothing this account does not already have. Importing it will change nothing."; } + + const files = totals.files.added + totals.files.updated; + const clauses: string[] = []; + if (totals.records.added > 0) { + clauses.push(`${count(totals.records.added, "record")} will be added`); + } + if (totals.records.updated > 0) { + clauses.push(`${totals.records.updated.toLocaleString()} will be filled in`); + } + if (files > 0) { + clauses.push(`${count(files, "media file")} will arrive`); + } + if (clauses.length === 0) { + // Only supporting rows changed: an author, an attachment, a link preview. + clauses.push("some records will gain details this account is missing"); + } + const incomplete = preview.archive.completeness === "incomplete" ? " This archive is missing some files, so a few records will arrive without their media." : ""; - return `${added} records will be added and ${updated} filled in. Your settings, schedule and Bluesky connection are left alone.${incomplete}`; + return `${sentence(clauses)}. Your settings, schedule and Bluesky connection are left alone.${incomplete}`; } const styles = StyleSheet.create({ @@ -376,6 +436,12 @@ const styles = StyleSheet.create({ fontWeight: "600", textAlign: "center", }, + handle: { + fontSize: 16, + fontWeight: "600", + textAlign: "center", + marginTop: -4, + }, subtitle: { fontSize: 15, fontWeight: "600", diff --git a/components/CydAccountBar.tsx b/components/CydAccountBar.tsx index da72335..da7893f 100644 --- a/components/CydAccountBar.tsx +++ b/components/CydAccountBar.tsx @@ -1,5 +1,6 @@ import { useCallback, useMemo, useState } from "react"; import { + Alert, Linking, Modal, Platform, @@ -14,6 +15,8 @@ import { getThemePalette } from "@/constants/theme"; import { useCydAccount } from "@/contexts/CydAccountProvider"; import { useBlueskyArchiveImport } from "@/hooks/use-bluesky-archive-import"; import { useColorScheme } from "@/hooks/use-color-scheme"; +import { emitLocalAccountsChanged } from "@/services/account-events"; +import { connectBlueskyAccount } from "@/services/bluesky-sign-in"; import { createScheduledReminderSync } from "@/services/scheduled-reminder-sync"; import { BlueskyArchiveImportModal } from "./BlueskyArchiveImportModal"; @@ -95,6 +98,38 @@ export function CydAccountBar({ void archiveImport.start(); }, [archiveImport]); + /** + * Connect the Bluesky account an import just restored. + * + * A restored Bluesky local account holds somebody's data and no authorization + * to act on it, because a Cyd Bluesky archive never carries a Bluesky + * connection. Offering the sign-in here is offering it at the one moment the + * person is already thinking about that account — and signing in is also what + * fills in the display name and avatar an archive cannot carry. + * + * The import is dismissed first: the OAuth session is a full-screen browser, + * and it should not open over a modal reporting an import that has finished. + */ + const handleSignIn = useCallback( + (handle: string) => { + archiveImport.dismiss(); + void (async () => { + try { + await connectBlueskyAccount(handle); + emitLocalAccountsChanged(); + } catch (err) { + Alert.alert( + "Sign in failed", + err instanceof Error + ? err.message + : "Cyd could not connect to Bluesky right now.", + ); + } + })(); + }, + [archiveImport], + ); + if (state.isLoading || hidden) { return null; } @@ -284,6 +319,7 @@ export function CydAccountBar({ onConfirmLargeArchive={() => void archiveImport.confirmLargeArchive()} onConfirmMerge={() => void archiveImport.confirmMerge()} onKeepAccount={(choice) => void archiveImport.keepAccount(choice)} + onSignIn={handleSignIn} onCancel={archiveImport.cancel} onDismiss={archiveImport.dismiss} /> diff --git a/components/account/identity.tsx b/components/account/identity.tsx new file mode 100644 index 0000000..b74143b --- /dev/null +++ b/components/account/identity.tsx @@ -0,0 +1,84 @@ +import { MaterialIcons } from "@expo/vector-icons"; +import { Image, StyleSheet, View } from "react-native"; + +/** + * What to call a Bluesky local account, and what to show where its avatar goes. + * + * A Bluesky local account restored from a Cyd Bluesky archive usually has + * neither. Avatars are URLs Cyd never preserves (they are not part of a Cyd + * Bluesky archive at all), and a display name nobody ever set arrives as an + * empty string rather than as nothing — the same absence-as-empty-string the + * merge's `populated` rule already refuses to treat as an observation. + * + * Both screens that show an account fell through that gap into a blank name + * and a "?", so the fallbacks live here once: an account is named by its + * handle when it has nothing better, and an account with no avatar gets a + * person rather than a punctuation mark. + */ + +export type AccountIdentity = { + handle: string; + displayName: string | null; +}; + +/** The handle as somebody would write it, whichever form it is stored in. */ +export function accountUsername(handle: string): string { + return handle.startsWith("@") ? handle : `@${handle}`; +} + +/** + * The name to show for an account. + * + * A blank display name is not a name, so it does not get to be one: the handle + * is what is left, and it always names somebody. + */ +export function accountDisplayName(account: AccountIdentity): string { + const displayName = account.displayName?.trim(); + return displayName ? displayName : accountUsername(account.handle); +} + +export type AccountAvatarProps = { + uri: string | null; + size: number; + palette: { icon: string }; +}; + +export function AccountAvatar({ uri, size, palette }: AccountAvatarProps) { + const shape = { + width: size, + height: size, + borderRadius: size / 2, + borderColor: palette.icon + "33", + backgroundColor: palette.icon + "20", + }; + + if (uri) { + return ( + + ); + } + + return ( + + + + ); +} + +const styles = StyleSheet.create({ + avatar: { + borderWidth: StyleSheet.hairlineWidth, + }, + fallback: { + alignItems: "center", + justifyContent: "center", + }, +}); diff --git a/hooks/__tests__/use-bluesky-archive-import.test.ts b/hooks/__tests__/use-bluesky-archive-import.test.ts index 65cd935..52f2ec4 100644 --- a/hooks/__tests__/use-bluesky-archive-import.test.ts +++ b/hooks/__tests__/use-bluesky-archive-import.test.ts @@ -106,7 +106,11 @@ describe("importing a Cyd Bluesky archive from the menu", () => { expect(result.current.state.status).toBe("done"); }); expect(result.current.state).toMatchObject({ - title: "Restored @glittertop-cyd.bsky.social", + title: "Restored", + handle: "glittertop-cyd.bsky.social", + // A restored account has no Bluesky connection, so this is where one is + // offered. + offerSignIn: true, }); // Staging is the import's working state, and the import is over. expect(fs.readdirSync(harness.stagingParent)).toEqual([]); diff --git a/hooks/use-bluesky-archive-import.ts b/hooks/use-bluesky-archive-import.ts index 134dc3f..b82e3e3 100644 --- a/hooks/use-bluesky-archive-import.ts +++ b/hooks/use-bluesky-archive-import.ts @@ -17,8 +17,10 @@ import { previewBlueskyArchiveMerge, previewDuplicateReconciliation, reconcileDuplicateBlueskyAccounts, + totalMergeChanges, type BlueskyArchiveMergeEnvironment, type BlueskyArchiveMergePreview, + type BlueskyArchiveMergeResult, type DuplicateReconciliationPreview, } from "@/services/archive-merge"; import { @@ -73,7 +75,26 @@ export type BlueskyArchiveImportState = preview: BlueskyArchiveMergePreview; handle: string; } - | { status: "done"; title: string; lines: string[] } + | { + status: "done"; + title: string; + /** + * The account the import ended in, kept apart from the title so it can + * be shown on its own line: a handle is one unbroken token, and a title + * that has to wrap around one breaks it wherever it runs out of room. + */ + handle: string; + lines: string[]; + /** + * Whether to offer a Bluesky connection from here. + * + * A restored Bluesky local account has none — a Cyd Bluesky archive + * never carries one — and this is the moment somebody is thinking about + * that account, so it is the moment worth asking. A merge leaves the + * account's existing connection alone and has nothing to offer. + */ + offerSignIn: boolean; + } | { status: "failed"; message: string }; /** The device capabilities an import needs, gathered so tests can stand in. */ @@ -145,6 +166,40 @@ function plural(count: number, noun: string): string { return `${count.toLocaleString()} ${noun}${count === 1 ? "" : "s"}`; } +/** + * What a merge did, counting every kind of change it made. + * + * Only what actually happened is mentioned: a merge that recovered one image + * and nothing else should say so, rather than reporting that no records came + * back and none gained anything — which is true, and tells somebody their + * import did nothing. + */ +function describeMergeResult(result: BlueskyArchiveMergeResult): string[] { + if (result.written === 0) { + return ["This archive held nothing that account did not already have."]; + } + + const totals = totalMergeChanges(result.summary); + const files = totals.files.added + totals.files.updated; + const lines: string[] = []; + if (totals.records.added > 0) { + lines.push(`${plural(totals.records.added, "record")} came back.`); + } + if (totals.records.updated > 0) { + lines.push(`${plural(totals.records.updated, "record")} gained something.`); + } + if (files > 0) { + lines.push(`${plural(files, "media file")} restored.`); + } + if (lines.length === 0) { + lines.push("Some records gained details this account was missing."); + } + lines.push( + "Your settings, schedule and Bluesky connection were left as they were.", + ); + return lines; +} + export function useBlueskyArchiveImport( options: { runtime?: BlueskyArchiveImportRuntime; @@ -237,11 +292,13 @@ export function useBlueskyArchiveImport( emitLocalAccountsChanged(); settle(generation, { status: "done", - title: `Restored @${result.handle}`, + title: "Restored", + handle: result.handle, + offerSignIn: true, lines: [ `${plural(result.counts.posts, "post")}, ${plural(result.counts.likes, "like")}, ${plural(result.counts.chats, "chat")}.`, `${plural(result.assets.restored, "file")} restored${result.assets.missing > 0 ? `, ${result.assets.missing} missing` : ""}.`, - "This account is not connected to Bluesky. Sign in when you want Cyd to act on it.", + "You can browse all of it now. Cyd needs a Bluesky connection before it can save or delete anything for this account.", ...(result.uuidRemapping ? [result.uuidRemapping.reason] : []), ], }); @@ -465,15 +522,10 @@ export function useBlueskyArchiveImport( emitLocalAccountsChanged(); settle(generation, { status: "done", - title: `Merged into @${handle}`, - lines: - result.written === 0 - ? ["This archive held nothing that account did not already have."] - : [ - `${plural(result.summary.restorations.total, "record")} came back.`, - `${plural(result.summary.posts.updated + result.summary.messages.updated + result.summary.follows.updated, "record")} gained something.`, - "Your settings, schedule and Bluesky connection were left as they were.", - ], + title: "Merged into", + handle, + offerSignIn: false, + lines: describeMergeResult(result), }); } catch (error) { discardStaging(); diff --git a/services/__tests__/bluesky-sign-in.test.ts b/services/__tests__/bluesky-sign-in.test.ts new file mode 100644 index 0000000..e131b38 --- /dev/null +++ b/services/__tests__/bluesky-sign-in.test.ts @@ -0,0 +1,83 @@ +jest.mock("@/services/bluesky-oauth", () => ({ + authenticateBlueskyAccount: jest.fn(), +})); + +jest.mock("@/services/bluesky-account-auth-status", () => ({ + verifyBlueskyAccountAuthStatus: jest.fn(async () => "authenticated"), +})); + +jest.mock("@/controllers", () => ({ + withBlueskyController: jest.fn( + async ( + _accountId: number, + _accountUUID: string, + fn: (controller: unknown) => Promise, + ) => fn({ controller: true }), + ), +})); + +jest.mock("@/services/analytics", () => ({ trackEvent: jest.fn() })); + +import { withBlueskyController } from "@/controllers"; +import type { AccountListItem } from "@/database/accounts"; +import { verifyBlueskyAccountAuthStatus } from "@/services/bluesky-account-auth-status"; +import { authenticateBlueskyAccount } from "@/services/bluesky-oauth"; +import { connectBlueskyAccount } from "@/services/bluesky-sign-in"; + +const ACCOUNT = { + id: 7, + uuid: "account-uuid", + handle: "glittertop-cyd.bsky.social", + did: "did:plc:yn45xekh5kqrat27w6rmafcg", +} as AccountListItem; + +describe("signing in to a Bluesky local account", () => { + beforeEach(() => { + jest.clearAllMocks(); + (authenticateBlueskyAccount as jest.Mock).mockResolvedValue(ACCOUNT); + }); + + /** + * The trap this exists for: whether Cyd can act on an account is cached in + * that account's own database, and an unforced check returns the cached + * "signed out" without ever reading the connection. An account restored from + * a Cyd Bluesky archive has never held either, so authorizing it and + * stopping there leaves it asking to be authorized again. + */ + it("refreshes the account's cached auth status, not only its connection", async () => { + const account = await connectBlueskyAccount("glittertop-cyd.bsky.social"); + + expect(account).toBe(ACCOUNT); + expect(withBlueskyController).toHaveBeenCalledWith( + ACCOUNT.id, + ACCOUNT.uuid, + expect.any(Function), + ); + expect(verifyBlueskyAccountAuthStatus).toHaveBeenCalledWith( + expect.anything(), + ACCOUNT, + { force: true }, + ); + }); + + it("still reports a sign-in when the status could not be refreshed", async () => { + // The connection is stored by then, so failing to write down what it means + // is not a failed sign-in. + (withBlueskyController as jest.Mock).mockRejectedValueOnce( + new Error("no controller"), + ); + + await expect( + connectBlueskyAccount("glittertop-cyd.bsky.social"), + ).resolves.toBe(ACCOUNT); + }); + + it("does not authorize twice", async () => { + await connectBlueskyAccount("glittertop-cyd.bsky.social"); + + expect(authenticateBlueskyAccount).toHaveBeenCalledTimes(1); + expect(authenticateBlueskyAccount).toHaveBeenCalledWith( + "glittertop-cyd.bsky.social", + ); + }); +}); diff --git a/services/archive-merge/__tests__/merge-plan.test.ts b/services/archive-merge/__tests__/merge-plan.test.ts index 9b412fa..0b5aea0 100644 --- a/services/archive-merge/__tests__/merge-plan.test.ts +++ b/services/archive-merge/__tests__/merge-plan.test.ts @@ -1,6 +1,7 @@ import type { MobilePostWrite } from "@/services/archive-restore"; -import { planBlueskyArchiveMerge } from "../merge-plan"; +import { planBlueskyArchiveMerge, totalMergeChanges } from "../merge-plan"; +import type { BlueskyArchiveMergeSummary } from "../merge-plan"; import type { ExistingAccountRows, ExistingPostRow } from "../rows"; /** @@ -348,3 +349,67 @@ describe("planning a Cyd Bluesky archive merge", () => { expect(plan.mediaAssets).toEqual([]); }); }); + +/** + * Whether a merge would change anything, asked of the summary rather than of + * whichever tables somebody remembered to look at. + */ +describe("adding a merge summary up", () => { + const none = { added: 0, updated: 0, unchanged: 0 }; + const summary = ( + overrides: Partial = {}, + ): BlueskyArchiveMergeSummary => ({ + profiles: none, + posts: none, + postMedia: none, + postExternals: none, + bookmarks: none, + follows: none, + conversations: none, + messages: none, + mediaAssets: none, + restorations: { total: 0, records: [] }, + ...overrides, + }); + + it("is nothing only when every table is", () => { + expect(totalMergeChanges(summary()).total).toBe(0); + }); + + it("counts a recovered file, which no record table mentions", () => { + const totals = totalMergeChanges( + summary({ mediaAssets: { added: 0, updated: 1, unchanged: 4 } }), + ); + + expect(totals.files).toEqual({ added: 0, updated: 1 }); + expect(totals.records).toEqual({ added: 0, updated: 0 }); + expect(totals.total).toBe(1); + }); + + it("counts the rows a record needs to render, under their own heading", () => { + const totals = totalMergeChanges( + summary({ + profiles: { added: 1, updated: 0, unchanged: 2 }, + postExternals: { added: 0, updated: 1, unchanged: 0 }, + }), + ); + + expect(totals.context).toEqual({ added: 1, updated: 1 }); + expect(totals.total).toBe(2); + }); + + it("groups every kind of record together", () => { + const totals = totalMergeChanges( + summary({ + posts: { added: 2, updated: 1, unchanged: 0 }, + messages: { added: 3, updated: 0, unchanged: 0 }, + conversations: { added: 1, updated: 0, unchanged: 0 }, + bookmarks: { added: 1, updated: 0, unchanged: 0 }, + follows: { added: 1, updated: 0, unchanged: 0 }, + }), + ); + + expect(totals.records).toEqual({ added: 8, updated: 1 }); + expect(totals.total).toBe(9); + }); +}); diff --git a/services/archive-merge/__tests__/merge.test.ts b/services/archive-merge/__tests__/merge.test.ts index 76404cc..cd64a21 100644 --- a/services/archive-merge/__tests__/merge.test.ts +++ b/services/archive-merge/__tests__/merge.test.ts @@ -24,6 +24,7 @@ import { commitBlueskyArchiveMerge, previewBlueskyArchiveMerge, } from "../merge"; +import { totalMergeChanges } from "../merge-plan"; /** * Importing a Cyd Bluesky archive into the Bluesky local account that already @@ -54,8 +55,11 @@ type Harness = { accountUuid: string; accountId: number; database: DatabaseSync; - /** Stage the fixture again, the way a second import would. */ - prepare: (intakeId: string) => Promise; + /** Stage a fixture again, the way a second import would. */ + prepare: ( + intakeId: string, + name?: string, + ) => Promise; }; async function stage( @@ -78,12 +82,12 @@ async function stage( } /** An account restored from the fixture, ready to have the fixture merged in. */ -async function restoredAccount(): Promise { +async function restoredAccount(fixture = "complete.cyd"): Promise { const root = fs.mkdtempSync(path.join(os.tmpdir(), "cyd-merge-")); const environment = createNodeBlueskyArchiveRestoreEnvironment({ root: path.join(root, "app"), }); - const prepared = await stage(root, "intake-restore"); + const prepared = await stage(root, "intake-restore", fixture); const restored = await restoreBlueskyArchiveAccount(environment, { archive: { intakeId: prepared.intakeId, @@ -97,7 +101,7 @@ async function restoredAccount(): Promise { accountUuid: restored.accountUuid, accountId: restored.accountId, database: environment.openRestoredAccountDatabase(restored.accountUuid), - prepare: (intakeId) => stage(root, intakeId), + prepare: (intakeId, name) => stage(root, intakeId, name), }; } @@ -294,3 +298,74 @@ describe("merging a Cyd Bluesky archive into an account that holds its identity" ).rejects.toThrow(/identity/i); }); }); + +/** + * The recovery somebody actually performs: exporting again once a download + * that had failed has finished, and importing that over the account the first + * export built. + * + * The committed fixtures are exactly this pair — `incomplete.cyd` differs from + * `complete.cyd` by one asset and nothing else — so this is the merge whose + * only change is a file, and the one that used to describe itself as changing + * nothing at all. + */ +describe("merging an archive carrying a file an earlier one could not", () => { + let harness: Harness; + + beforeAll(async () => { + harness = await restoredAccount("incomplete.cyd"); + }); + + afterAll(() => { + harness.database.close(); + harness.environment.close(); + fs.rmSync(harness.root, { recursive: true, force: true }); + }); + + function unavailable(): { contentCid: string; localPath: string | null }[] { + return harness.database + .prepare( + `SELECT contentCid, localPath FROM media_asset + WHERE downloadState != 'complete';`, + ) + .all() as { contentCid: string; localPath: string | null }[]; + } + + it("recovers the file, and counts it as a change", async () => { + const missing = unavailable(); + expect(missing).toHaveLength(1); + + const prepared = await harness.prepare("intake-upgrade", "complete.cyd"); + const preview = await previewBlueskyArchiveMerge(harness.environment, { + archive: { + intakeId: prepared.intakeId, + stagingRoot: prepared.stagingRoot, + }, + account: identity(harness), + }); + + // Every record is identical across the pair, so a summary read one table + // at a time finds nothing: the file is the whole of the difference. + expect(preview.summary.posts).toMatchObject({ added: 0, updated: 0 }); + expect(preview.summary.messages).toMatchObject({ added: 0, updated: 0 }); + expect(preview.summary.mediaAssets).toMatchObject({ added: 0, updated: 1 }); + expect(totalMergeChanges(preview.summary)).toMatchObject({ + records: { added: 0, updated: 0 }, + files: { added: 0, updated: 1 }, + total: 1, + }); + + const result = await commitBlueskyArchiveMerge(harness.environment, preview); + + expect(result.written).toBe(1); + expect(unavailable()).toEqual([]); + + const restored = harness.database + .prepare("SELECT localPath FROM media_asset WHERE contentCid = ?;") + .get(missing[0].contentCid) as { localPath: string | null }; + expect(restored.localPath).not.toBeNull(); + expect( + fs.existsSync(restored.localPath!.replace(/^file:\/\//, "")), + ).toBe(true); + }); +}); diff --git a/services/archive-merge/index.ts b/services/archive-merge/index.ts index 5ccd7ed..dd6b52a 100644 --- a/services/archive-merge/index.ts +++ b/services/archive-merge/index.ts @@ -44,11 +44,12 @@ export type { BlueskyArchiveMergeResult, MergedAssetSummary, } from "./merge"; -export { planBlueskyArchiveMerge } from "./merge-plan"; +export { planBlueskyArchiveMerge, totalMergeChanges } from "./merge-plan"; export type { BlueskyArchiveMergeCounts, BlueskyArchiveMergePlan, BlueskyArchiveMergeSummary, + BlueskyArchiveMergeTotals, RestorationPreview, } from "./merge-plan"; export { RECONCILABLE_SETTING_COLUMNS } from "./ports"; diff --git a/services/archive-merge/merge-plan.ts b/services/archive-merge/merge-plan.ts index 9e8e1a1..e87ef6a 100644 --- a/services/archive-merge/merge-plan.ts +++ b/services/archive-merge/merge-plan.ts @@ -75,6 +75,76 @@ export type BlueskyArchiveMergeSummary = { }; }; +/** + * What each table in a summary amounts to, for somebody deciding about it. + * + * A merge summary has one entry per table, and the tables are not equally + * interesting: somebody recognises a post, has no idea what a `post_external` + * is, and thinks of a recovered image as a file rather than a row. Grouping + * them is what lets a preview say something true in one sentence. + * + * The map is exhaustive on purpose. Reading a nine-table summary by hand is + * how a merge that recovers a missing image comes to announce itself as + * changing nothing: whoever adds the tenth table has to say what it is here, + * or this does not compile. + */ +const MERGE_CATEGORIES: Record< + Exclude, + "records" | "files" | "context" +> = { + posts: "records", + bookmarks: "records", + follows: "records", + conversations: "records", + messages: "records", + mediaAssets: "files", + profiles: "context", + postMedia: "context", + postExternals: "context", +}; + +export type BlueskyArchiveMergeTotals = { + /** Records somebody would recognise as theirs. */ + records: { added: number; updated: number }; + /** Media files: one this account never had, or one it failed to download. */ + files: { added: number; updated: number }; + /** What a record needs to render: authors, attachments, link previews. */ + context: { added: number; updated: number }; + /** Every write the plan would make. Zero is the only honest "nothing". */ + total: number; +}; + +/** + * Add a summary up, so that "would this change anything?" has one answer. + * + * Both the preview somebody agrees to and the report afterwards ask it, and a + * merge is only a no-op when every table is: an archive whose single + * difference is the image an earlier export could not carry changes something + * worth being told about. + */ +export function totalMergeChanges( + summary: BlueskyArchiveMergeSummary, +): BlueskyArchiveMergeTotals { + const totals: BlueskyArchiveMergeTotals = { + records: { added: 0, updated: 0 }, + files: { added: 0, updated: 0 }, + context: { added: 0, updated: 0 }, + total: 0, + }; + + for (const [table, group] of Object.entries(MERGE_CATEGORIES) as [ + keyof typeof MERGE_CATEGORIES, + "records" | "files" | "context", + ][]) { + const counts = summary[table]; + totals[group].added += counts.added; + totals[group].updated += counts.updated; + totals.total += counts.added + counts.updated; + } + + return totals; +} + export type BlueskyArchiveMergePlan = { profiles: MobileProfileWrite[]; posts: ExistingPostRow[]; diff --git a/services/archive-restore/__tests__/mobile-rows.test.ts b/services/archive-restore/__tests__/mobile-rows.test.ts index 9441c0b..e2e34de 100644 --- a/services/archive-restore/__tests__/mobile-rows.test.ts +++ b/services/archive-restore/__tests__/mobile-rows.test.ts @@ -811,4 +811,19 @@ describe("translating a Cyd Bluesky archive into Mobile's rows", () => { displayName: "Owner", }); }); + + it("treats a display name nobody set as no display name", () => { + // An account that never set one exports an empty string, which is an + // absence rather than a name: keeping it would show a blank where the + // account's name goes, instead of falling back to its handle. + const snapshot = emptySnapshot(); + snapshot.profiles[0].display_name = ""; + + const { identity } = translate(snapshot); + + expect(identity).toMatchObject({ + handle: "owner.bsky.social", + displayName: null, + }); + }); }); diff --git a/services/archive-restore/mobile-rows.ts b/services/archive-restore/mobile-rows.ts index 09d4c8c..f178013 100644 --- a/services/archive-restore/mobile-rows.ts +++ b/services/archive-restore/mobile-rows.ts @@ -227,6 +227,12 @@ function millisFrom(value: string | null | undefined): number | null { return Number.isNaN(parsed) ? null : parsed; } +/** A name, or nothing: blank is an absence of one rather than an empty one. */ +function named(value: string | null | undefined): string | null { + const trimmed = value?.trim(); + return trimmed ? trimmed : null; +} + function parseJson(value: string | null): unknown { if (!value) { return null; @@ -338,7 +344,11 @@ class MobileRowBuilder { return { did, handle: restored?.handle ?? profile?.handle ?? did, - displayName: restored?.displayName ?? profile?.display_name ?? null, + // A display name nobody ever set arrives as an empty string, which is an + // absence rather than a name — the same thing the merge's `populated` + // rule refuses to treat as an observation. Storing it as nothing is what + // lets the account fall back to its handle instead of showing a blank. + displayName: named(restored?.displayName ?? profile?.display_name), avatarUrl: restored?.avatarUrl ?? null, }; } diff --git a/services/bluesky-sign-in.ts b/services/bluesky-sign-in.ts new file mode 100644 index 0000000..8c09530 --- /dev/null +++ b/services/bluesky-sign-in.ts @@ -0,0 +1,48 @@ +import { withBlueskyController } from "@/controllers"; +import type { AccountListItem } from "@/database/accounts"; +import { trackEvent } from "@/services/analytics"; +import { verifyBlueskyAccountAuthStatus } from "@/services/bluesky-account-auth-status"; +import { authenticateBlueskyAccount } from "@/services/bluesky-oauth"; +import { PlausibleEvents } from "@/types/analytics"; + +/** + * Establish a Bluesky connection and leave the account knowing it has one. + * + * Authorizing is only half of signing in. Whether Cyd can act on a Bluesky + * local account is a value cached in that account's own database, and + * `verifyBlueskyAccountAuthStatus` returns the cached "signed out" without + * looking at the stored connection at all unless it is forced — which is + * exactly what an account that has never been connected holds. So an account + * that was just authorized still reads as signed out, and asks the person to + * authorize again, until something rebuilds its agent from the connection that + * now exists. + * + * That makes the forced check part of signing in rather than something each + * caller remembers, which matters most for the callers furthest from the + * account screen: a Bluesky local account restored from a Cyd Bluesky archive + * has no cached status and no connection, and is signed in from the import + * that created it. + */ +export async function connectBlueskyAccount( + handle: string, +): Promise { + const account = await authenticateBlueskyAccount(handle); + trackEvent(PlausibleEvents.BLUESKY_USER_SIGNED_IN); + + try { + await withBlueskyController(account.id, account.uuid, (controller) => + verifyBlueskyAccountAuthStatus(controller, account, { force: true }), + ); + } catch (err) { + // The connection is stored either way, so this is not a failed sign-in. + // The account will read as signed out until some forced check succeeds — + // opening it is not enough, since that check trusts the cached status — + // but its "sign in" action runs one. + console.warn( + "[BlueskySignIn] could not persist auth status after authorizing", + err, + ); + } + + return account; +} From 5c52991aa0ed93a03e233c83e34f288d3d99d28b Mon Sep 17 00:00:00 2001 From: Micah Lee Date: Sun, 13 Sep 2026 15:44:22 -0700 Subject: [PATCH 4/9] Refresh what an account knows about itself when it signs in MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Browse renders a record's author out of the account's own `profile` table, not out of the account row, so the two can disagree — and after a restore they do. A Cyd Bluesky archive cannot carry an avatar at all, and an account that never set a display name exports an empty one, so a restored account browsed its own posts under the name the archive carried while its header showed the name Bluesky had just given it. Saving posts would have corrected it eventually, as a side effect of saving their authors, but nobody should have to run a save to see their own name. `upsertProfileRow` comes out of `PostPersistence` as a function the class still delegates to, taking the four fields it stores rather than one shape of profile view, so the detailed profile an account fetches about itself fits as well as the basic one attached to a post. `refreshOwnProfile` writes it, and signing in calls it: that is the first moment Cyd has anything newer than the archive. Signing in now happens in one place. The previous commit left the account screen and the add-account screen doing the sequence by hand, and the account screen promptly proved why that does not hold: reauthenticating from it authorized the account and refreshed nothing, because refreshing was somewhere else. Both now call `connectBlueskyAccount`, which returns the status the account screen shows. A profile that will not refresh no longer takes the sign-in with it. Post cards showed an empty circle for an author with no avatar, which is every author an archive restored. They get the same person icon the account screens use. Co-Authored-By: Claude Opus 5 (1M context) --- app/account/[accountId].tsx | 13 ++--- app/add-account.tsx | 30 +--------- components/PostPreview.tsx | 12 +++- controllers/BlueskyAccountController.ts | 23 ++++++++ controllers/bluesky/post-persistence.ts | 65 +++++++++++++++------- services/__tests__/bluesky-sign-in.test.ts | 38 +++++++++++-- services/bluesky-sign-in.ts | 52 ++++++++++++++--- 7 files changed, 164 insertions(+), 69 deletions(-) diff --git a/app/account/[accountId].tsx b/app/account/[accountId].tsx index 8200f96..1d29684 100644 --- a/app/account/[accountId].tsx +++ b/app/account/[accountId].tsx @@ -56,7 +56,7 @@ import { useColorScheme } from "@/hooks/use-color-scheme"; import { onAuthStatusChange } from "@/services/auth-events"; import { verifyBlueskyAccountAuthStatus } from "@/services/bluesky-account-auth-status"; import { disconnectBlueskyAccount } from "@/services/bluesky-disconnect"; -import { authenticateBlueskyAccount } from "@/services/bluesky-oauth"; +import { connectBlueskyAccount } from "@/services/bluesky-sign-in"; import type { AccountTabKey, AccountTabProps } from "@/types/account-tabs"; import { BrowseTab } from "./tabs/browse-tab"; import { DashboardTab } from "./tabs/dashboard-tab"; @@ -152,13 +152,10 @@ export default function AccountScreen() { try { console.log("[AccountScreen] handleReauthenticate -> start", account.id); - await authenticateBlueskyAccount(account.handle); - console.log( - "[AccountScreen] authenticateBlueskyAccount -> success", - account.id, - ); - const nextStatus = await runWithAccountController(account, (controller) => - verifyBlueskyAccountAuthStatus(controller, account, { force: true }), + // Signing in is more than authorizing: it also refreshes what this + // account knows about itself, which is why it is not done by hand here. + const { status: nextStatus } = await connectBlueskyAccount( + account.handle, ); console.log( "[AccountScreen] handleReauthenticate -> verified", diff --git a/app/add-account.tsx b/app/add-account.tsx index 6ae2862..154f8de 100644 --- a/app/add-account.tsx +++ b/app/add-account.tsx @@ -13,16 +13,10 @@ import { import { SafeAreaView } from "react-native-safe-area-context"; import { getThemePalette } from "@/constants/theme"; -import { withBlueskyController } from "@/controllers"; import { useAccounts } from "@/hooks/use-accounts"; import { useColorScheme } from "@/hooks/use-color-scheme"; -import { trackEvent } from "@/services/analytics"; -import { verifyBlueskyAccountAuthStatus } from "@/services/bluesky-account-auth-status"; -import { - authenticateBlueskyAccount, - normalizeHandle, -} from "@/services/bluesky-oauth"; -import { PlausibleEvents } from "@/types/analytics"; +import { normalizeHandle } from "@/services/bluesky-oauth"; +import { connectBlueskyAccount } from "@/services/bluesky-sign-in"; export default function AddAccountScreen() { const router = useRouter(); @@ -56,25 +50,7 @@ export default function AddAccountScreen() { setSubmitting(true); setError(null); try { - const savedAccount = await authenticateBlueskyAccount(handle); - // Track successful sign-in - trackEvent(PlausibleEvents.BLUESKY_USER_SIGNED_IN); - try { - await withBlueskyController( - savedAccount.id, - savedAccount.uuid, - async (controller) => { - await verifyBlueskyAccountAuthStatus(controller, savedAccount, { - force: true, - }); - }, - ); - } catch (verifyError) { - console.warn( - "[AddAccount] Failed to persist auth status after OAuth", - verifyError, - ); - } + const { account: savedAccount } = await connectBlueskyAccount(handle); router.replace({ pathname: "/account/[accountId]", params: { accountId: savedAccount.uuid }, diff --git a/components/PostPreview.tsx b/components/PostPreview.tsx index 5afd0be..3b74b1e 100644 --- a/components/PostPreview.tsx +++ b/components/PostPreview.tsx @@ -1,3 +1,4 @@ +import { MaterialIcons } from "@expo/vector-icons"; import * as Clipboard from "expo-clipboard"; import { useVideoPlayer, VideoView } from "expo-video"; import React, { @@ -50,7 +51,14 @@ type ImageItem = { function Avatar({ uri }: { uri?: string | null }) { if (!uri) { - return ; + // Avatars are URLs Cyd never preserves, so an author it knows only from a + // Cyd Bluesky archive has none at all. A person is a better stand-in for + // somebody than an empty circle. + return ( + + + + ); } return ; } @@ -842,6 +850,8 @@ const styles = StyleSheet.create({ avatarPlaceholder: { borderWidth: StyleSheet.hairlineWidth, borderColor: "#0001", + alignItems: "center", + justifyContent: "center", }, bodyText: { fontSize: 17, diff --git a/controllers/BlueskyAccountController.ts b/controllers/BlueskyAccountController.ts index ef51808..b361c0d 100644 --- a/controllers/BlueskyAccountController.ts +++ b/controllers/BlueskyAccountController.ts @@ -55,6 +55,7 @@ import { type SaveAndDeleteJobOptions, type SaveJobOptions, } from "./bluesky/job-types"; +import { upsertProfileRow } from "./bluesky/post-persistence"; import { BlueskyRateLimiter, type ApiRequestFn } from "./bluesky/rate-limiter"; import type { BlueskyDatabaseStats, @@ -404,6 +405,28 @@ export class BlueskyAccountController extends BaseAccountController { + if (!this.db) { + return; + } + const profile = await this.getProfile(); + if (!profile) { + return; + } + await upsertProfileRow(this.db, profile); + } + /** * Get database statistics */ diff --git a/controllers/bluesky/post-persistence.ts b/controllers/bluesky/post-persistence.ts index fba1946..b50d2ef 100644 --- a/controllers/bluesky/post-persistence.ts +++ b/controllers/bluesky/post-persistence.ts @@ -15,6 +15,50 @@ type FeedRecordInfo = | { kind: "post"; record: AppBskyFeedPost.Record } | { kind: "repost"; record: AppBskyFeedRepost.Record }; +/** + * Write down what Bluesky currently says about somebody. + * + * Browse renders a record's author out of this table, so it is also what Cyd + * knows about an identity when it is offline. Saving posts refreshes it as a + * side effect of saving their author; anything else that learns a fresher + * profile — signing in, most of all, for an account restored from a Cyd + * Bluesky archive that could not carry an avatar — writes it here too. + * + * It takes the four fields it stores rather than a particular profile view, so + * the detailed profile an account fetches about itself fits as well as the + * basic one that arrives attached to a post. + */ +export type ProfileRowSource = Pick< + AppBskyActorDefs.ProfileViewBasic, + "did" | "handle" | "displayName" | "avatar" +>; + +export async function upsertProfileRow( + db: SQLiteDatabase, + profile: ProfileRowSource +): Promise { + const now = Date.now(); + + await db.runAsync( + `INSERT INTO profile ( + did, handle, displayName, avatarUrl, savedAt, updatedAt + ) VALUES (?, ?, ?, ?, ?, ?) + ON CONFLICT(did) DO UPDATE SET + handle = excluded.handle, + displayName = excluded.displayName, + avatarUrl = excluded.avatarUrl, + updatedAt = excluded.updatedAt;`, + [ + profile.did, + profile.handle, + profile.displayName ?? null, + profile.avatar ?? null, + now, + now, + ] + ); +} + export interface PostPersistenceOptions { viewerLiked?: number; viewerReposted?: number; @@ -251,26 +295,7 @@ export class PostPersistence { db: SQLiteDatabase, profile: AppBskyActorDefs.ProfileViewBasic ): Promise { - const now = Date.now(); - - await db.runAsync( - `INSERT INTO profile ( - did, handle, displayName, avatarUrl, savedAt, updatedAt - ) VALUES (?, ?, ?, ?, ?, ?) - ON CONFLICT(did) DO UPDATE SET - handle = excluded.handle, - displayName = excluded.displayName, - avatarUrl = excluded.avatarUrl, - updatedAt = excluded.updatedAt;`, - [ - profile.did, - profile.handle, - profile.displayName ?? null, - profile.avatar ?? null, - now, - now, - ] - ); + await upsertProfileRow(db, profile); } private async downloadAndSaveMedia( diff --git a/services/__tests__/bluesky-sign-in.test.ts b/services/__tests__/bluesky-sign-in.test.ts index e131b38..b376df3 100644 --- a/services/__tests__/bluesky-sign-in.test.ts +++ b/services/__tests__/bluesky-sign-in.test.ts @@ -6,13 +6,16 @@ jest.mock("@/services/bluesky-account-auth-status", () => ({ verifyBlueskyAccountAuthStatus: jest.fn(async () => "authenticated"), })); +const mockRefreshOwnProfile = jest.fn(async () => {}); + jest.mock("@/controllers", () => ({ + ACCOUNT_AUTH_STATUS: { authenticated: "authenticated", signedOut: "signedOut" }, withBlueskyController: jest.fn( async ( _accountId: number, _accountUUID: string, fn: (controller: unknown) => Promise, - ) => fn({ controller: true }), + ) => fn({ refreshOwnProfile: mockRefreshOwnProfile }), ), })); @@ -45,9 +48,9 @@ describe("signing in to a Bluesky local account", () => { * stopping there leaves it asking to be authorized again. */ it("refreshes the account's cached auth status, not only its connection", async () => { - const account = await connectBlueskyAccount("glittertop-cyd.bsky.social"); + const signIn = await connectBlueskyAccount("glittertop-cyd.bsky.social"); - expect(account).toBe(ACCOUNT); + expect(signIn).toEqual({ account: ACCOUNT, status: "authenticated" }); expect(withBlueskyController).toHaveBeenCalledWith( ACCOUNT.id, ACCOUNT.uuid, @@ -67,9 +70,32 @@ describe("signing in to a Bluesky local account", () => { new Error("no controller"), ); - await expect( - connectBlueskyAccount("glittertop-cyd.bsky.social"), - ).resolves.toBe(ACCOUNT); + const signIn = await connectBlueskyAccount("glittertop-cyd.bsky.social"); + + // Authorized, but nothing wrote down what that means, so the account is + // reported as it will actually read until some forced check succeeds. + expect(signIn).toEqual({ account: ACCOUNT, status: "signedOut" }); + }); + + /** + * The account row learns the fresh handle, display name and avatar, but + * Browse renders authors out of the account's own database — which, for an + * account restored from an archive, still holds what the archive carried. + */ + it("writes down the profile it just fetched, for Browse to show", async () => { + await connectBlueskyAccount("glittertop-cyd.bsky.social"); + + expect(mockRefreshOwnProfile).toHaveBeenCalledTimes(1); + }); + + it("does not try to read a profile it could not authenticate for", async () => { + (verifyBlueskyAccountAuthStatus as jest.Mock).mockResolvedValueOnce( + "signedOut", + ); + + await connectBlueskyAccount("glittertop-cyd.bsky.social"); + + expect(mockRefreshOwnProfile).not.toHaveBeenCalled(); }); it("does not authorize twice", async () => { diff --git a/services/bluesky-sign-in.ts b/services/bluesky-sign-in.ts index 8c09530..59528ab 100644 --- a/services/bluesky-sign-in.ts +++ b/services/bluesky-sign-in.ts @@ -1,4 +1,8 @@ -import { withBlueskyController } from "@/controllers"; +import { + ACCOUNT_AUTH_STATUS, + withBlueskyController, + type AccountAuthStatusValue, +} from "@/controllers"; import type { AccountListItem } from "@/database/accounts"; import { trackEvent } from "@/services/analytics"; import { verifyBlueskyAccountAuthStatus } from "@/services/bluesky-account-auth-status"; @@ -22,27 +26,61 @@ import { PlausibleEvents } from "@/types/analytics"; * account screen: a Bluesky local account restored from a Cyd Bluesky archive * has no cached status and no connection, and is signed in from the import * that created it. + * + * Everywhere somebody signs in comes through here, because the steps that + * follow authorizing are the ones easy to leave out and hard to notice + * missing: an account that has to be authorized twice, or one that goes on + * showing the name and avatar an archive carried long after Bluesky told Cyd + * the real ones. */ +export type BlueskySignIn = { + account: AccountListItem; + /** What the account now knows about itself, for a caller showing it. */ + status: AccountAuthStatusValue; +}; + export async function connectBlueskyAccount( handle: string, -): Promise { +): Promise { const account = await authenticateBlueskyAccount(handle); trackEvent(PlausibleEvents.BLUESKY_USER_SIGNED_IN); + let status: AccountAuthStatusValue = ACCOUNT_AUTH_STATUS.signedOut; try { - await withBlueskyController(account.id, account.uuid, (controller) => - verifyBlueskyAccountAuthStatus(controller, account, { force: true }), + status = await withBlueskyController( + account.id, + account.uuid, + async (controller) => { + const verified = await verifyBlueskyAccountAuthStatus( + controller, + account, + { force: true }, + ); + if (verified === ACCOUNT_AUTH_STATUS.authenticated) { + try { + // Browse reads an author out of the account's own database, which + // for a restored account holds what the Cyd Bluesky archive + // carried. This is the first moment Cyd has anything newer to put + // there — and failing to write it down is not a failed sign-in, + // so it does not take the status with it. + await controller.refreshOwnProfile(); + } catch (err) { + console.warn("[BlueskySignIn] could not refresh the profile", err); + } + } + return verified; + }, ); } catch (err) { // The connection is stored either way, so this is not a failed sign-in. // The account will read as signed out until some forced check succeeds — // opening it is not enough, since that check trusts the cached status — - // but its "sign in" action runs one. + // but signing in again runs one. console.warn( - "[BlueskySignIn] could not persist auth status after authorizing", + "[BlueskySignIn] could not finish signing in after authorizing", err, ); } - return account; + return { account, status }; } From d805a8aa7cf4d3294cbf09e5a1b60e28ced0899a Mon Sep 17 00:00:00 2001 From: Micah Lee Date: Sun, 13 Sep 2026 15:59:32 -0700 Subject: [PATCH 5/9] Say what a merge would add, by the names Browse uses MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The merge preview named every record coming back, under a heading warning that importing brings back anything deleted from Cyd on purpose. Mobile has no Bluesky local deletion — setting that state up for a device test took SQL — so the warning described a situation the app cannot produce, and the list under it was a wall of `posts: ` nobody could act on. Both are gone, and ADR 0018 is amended rather than left contradicted: the preview counts rather than names, and naming becomes worth its screen again if Mobile ever lets somebody remove Bluesky saved data without removing it from Bluesky. The plan still carries the records, so that would be a presentation change. It carries them for another reason too. Choosing between two Bluesky local accounts that hold one identity is a different question from what an archive would add, and there an example of what one account holds and the other does not is how somebody tells them apart. That screen keeps its example, with the reasoning it actually rests on. In place of the list, a line per kind: "3 posts will be added", "1 repost will be added", nothing at all for a kind with nothing to add. Mobile keeps posts, reposts, likes and bookmarks in one table and tells them apart by column, so the plan classifies the added rows exactly as `buildTotalCountQuery` does and takes the account DID to do it — a post is the account's own rather than somebody else's that it liked only if the DID says so. A row can land under two headings, which is what Browse shows: the fixture account's own post that it also reposted appears in the Posts tab and the Reposts tab, and now in both lines of the preview. Agreeing with the tabs somebody will go and look at beats adding up to a tidier total. The report after the merge uses the same headings in the past tense. "Your settings, schedule and Bluesky connection are left alone" is gone from the preview and from the report. A merge has no port that can reach any of them, so it was a sentence that was never news. Co-Authored-By: Claude Opus 5 (1M context) --- components/BlueskyArchiveImportModal.tsx | 123 +++++++----------- ...w-a-recovery-merge-before-committing-it.md | 2 +- hooks/use-bluesky-archive-import.ts | 38 +++--- .../__tests__/merge-plan.test.ts | 80 ++++++++++++ .../archive-merge/__tests__/merge.test.ts | 17 +++ services/archive-merge/duplicates.ts | 15 ++- services/archive-merge/merge-plan.ts | 86 ++++++++++-- services/archive-merge/merge.ts | 4 + 8 files changed, 257 insertions(+), 108 deletions(-) diff --git a/components/BlueskyArchiveImportModal.tsx b/components/BlueskyArchiveImportModal.tsx index 852a2ef..7e3e420 100644 --- a/components/BlueskyArchiveImportModal.tsx +++ b/components/BlueskyArchiveImportModal.tsx @@ -242,44 +242,11 @@ export function BlueskyArchiveImportModal({ {breakableHandle(state.handle)} - - - {describeMerge(state.preview)} + {describeMerge(state.preview).map((line) => ( + + {line} - {state.preview.summary.restorations.total > 0 ? ( - <> - - Coming back to this account - - - These are not in Cyd right now. If you deleted any of them - from Cyd on purpose, importing brings them back. - - {state.preview.summary.restorations.records.map( - (record) => ( - - {record.text?.trim() - ? `${record.category}: ${record.text.trim()}` - : `${record.category}: ${record.id}`} - - ), - )} - {state.preview.summary.restorations.total > - state.preview.summary.restorations.records.length ? ( - - …and{" "} - {state.preview.summary.restorations.total - - state.preview.summary.restorations.records.length}{" "} - more. - - ) : null} - - ) : null} - + ))} {action("Import", onConfirmMerge, "primary")} {action("Cancel", onCancel)} @@ -370,50 +337,60 @@ function count(total: number, noun: string): string { return `${total.toLocaleString()} ${noun}${total === 1 ? "" : "s"}`; } -/** "a, b and c", so a sentence can be built out of whatever is true. */ -function sentence(clauses: string[]): string { - if (clauses.length <= 1) { - return clauses[0] ?? ""; - } - return `${clauses.slice(0, -1).join(", ")} and ${clauses[clauses.length - 1]}`; -} - /** - * One sentence about what this archive has that the account does not. + * What this archive has that the account does not, a line per kind. * - * Every kind of change counts, not only the ones with a familiar name. An - * export taken again once a download finished differs from the one before it - * by a single image, and telling somebody that importing it changes nothing - * would be both wrong and the exact case they are trying to fix. + * Named the way Browse names them, so somebody who reads "2 likes will be + * added" can go to the Likes tab afterwards and find two more than before. + * A kind with nothing to add says nothing at all: a list of zeroes is a list + * of things that are not happening. + * + * What a merge leaves alone is not mentioned either. A merge cannot reach an + * account's settings, schedule or Bluesky connection — the ports have no way + * to — so saying so every time is a sentence that is never news. */ -function describeMerge(preview: BlueskyArchiveMergePreview): string { +function describeMerge(preview: BlueskyArchiveMergePreview): string[] { const totals = totalMergeChanges(preview.summary); if (totals.total === 0) { - return "This archive holds nothing this account does not already have. Importing it will change nothing."; + return [ + "This archive holds nothing this account does not already have. Importing it will change nothing.", + ]; } - const files = totals.files.added + totals.files.updated; - const clauses: string[] = []; - if (totals.records.added > 0) { - clauses.push(`${count(totals.records.added, "record")} will be added`); + const added = preview.summary.addedRecords; + const kinds: [number, string][] = [ + [added.posts, "post"], + [added.reposts, "repost"], + [added.likes, "like"], + [added.bookmarks, "bookmark"], + [added.follows, "follow"], + [added.chats, "chat"], + [added.messages, "message"], + [totals.files.added, "media file"], + ]; + + const lines = kinds + .filter(([total]) => total > 0) + .map(([total, noun]) => `${count(total, noun)} will be added.`); + + if (totals.files.updated > 0) { + // A file this account has a record of but never managed to download. + lines.push(`${count(totals.files.updated, "media file")} will be restored.`); } if (totals.records.updated > 0) { - clauses.push(`${totals.records.updated.toLocaleString()} will be filled in`); + lines.push(`${count(totals.records.updated, "record")} will be filled in.`); } - if (files > 0) { - clauses.push(`${count(files, "media file")} will arrive`); - } - if (clauses.length === 0) { + if (lines.length === 0) { // Only supporting rows changed: an author, an attachment, a link preview. - clauses.push("some records will gain details this account is missing"); + lines.push("Some records will gain details this account is missing."); } - - const incomplete = - preview.archive.completeness === "incomplete" - ? " This archive is missing some files, so a few records will arrive without their media." - : ""; - return `${sentence(clauses)}. Your settings, schedule and Bluesky connection are left alone.${incomplete}`; + if (preview.archive.completeness === "incomplete") { + lines.push( + "This archive is missing some files, so a few records will arrive without their media.", + ); + } + return lines; } const styles = StyleSheet.create({ @@ -442,20 +419,10 @@ const styles = StyleSheet.create({ textAlign: "center", marginTop: -4, }, - subtitle: { - fontSize: 15, - fontWeight: "600", - marginTop: 12, - }, body: { fontSize: 14, lineHeight: 20, }, - record: { - fontSize: 13, - lineHeight: 18, - marginTop: 6, - }, scroll: { maxHeight: 280, }, diff --git a/docs/adr/0018-preview-a-recovery-merge-before-committing-it.md b/docs/adr/0018-preview-a-recovery-merge-before-committing-it.md index 05bf868..0a5ca6c 100644 --- a/docs/adr/0018-preview-a-recovery-merge-before-committing-it.md +++ b/docs/adr/0018-preview-a-recovery-merge-before-committing-it.md @@ -1,3 +1,3 @@ # Preview a recovery merge before committing it -Cyd Mobile splits a Bluesky archive merge into a preview that reads the prepared Cyd Bluesky archive and works out every row it would write, and a commit that carries that preview out, because a recovery union can restore Bluesky saved records the person removed through Bluesky local deletion and they must see which ones before it happens. The preview names the records coming back rather than only counting them; the commit re-reads the Bluesky local account instead of trusting the preview's copy, so work that ran in between is merged rather than overwritten, and committing the same Cyd Bluesky archive again writes nothing. +Cyd Mobile splits a Bluesky archive merge into a preview that reads the prepared Cyd Bluesky archive and works out every row it would write, and a commit that carries that preview out, so nobody imports an archive without being told what it would do. The preview counts what it would add rather than naming it: Mobile has no Bluesky local deletion, so a Bluesky saved record missing from a Bluesky local account is one the account never had rather than one somebody chose to be rid of, and there is nothing for them to recognise in a list. Naming each record becomes worth its screen again if Mobile ever lets somebody remove Bluesky saved data without removing it from Bluesky, and the plan already carries the records, so it is a presentation change rather than a new capability. The commit re-reads the Bluesky local account instead of trusting the preview's copy, so work that ran in between is merged rather than overwritten, and committing the same Cyd Bluesky archive again writes nothing. diff --git a/hooks/use-bluesky-archive-import.ts b/hooks/use-bluesky-archive-import.ts index b82e3e3..338a945 100644 --- a/hooks/use-bluesky-archive-import.ts +++ b/hooks/use-bluesky-archive-import.ts @@ -167,12 +167,10 @@ function plural(count: number, noun: string): string { } /** - * What a merge did, counting every kind of change it made. + * What a merge did, a line per kind of thing it did it to. * - * Only what actually happened is mentioned: a merge that recovered one image - * and nothing else should say so, rather than reporting that no records came - * back and none gained anything — which is true, and tells somebody their - * import did nothing. + * The same headings the preview used, in the past tense: somebody who agreed + * to "3 posts will be added" should be told that 3 posts were. */ function describeMergeResult(result: BlueskyArchiveMergeResult): string[] { if (result.written === 0) { @@ -180,23 +178,31 @@ function describeMergeResult(result: BlueskyArchiveMergeResult): string[] { } const totals = totalMergeChanges(result.summary); - const files = totals.files.added + totals.files.updated; - const lines: string[] = []; - if (totals.records.added > 0) { - lines.push(`${plural(totals.records.added, "record")} came back.`); + const added = result.summary.addedRecords; + const kinds: [number, string][] = [ + [added.posts, "post"], + [added.reposts, "repost"], + [added.likes, "like"], + [added.bookmarks, "bookmark"], + [added.follows, "follow"], + [added.chats, "chat"], + [added.messages, "message"], + [totals.files.added, "media file"], + ]; + + const lines = kinds + .filter(([total]) => total > 0) + .map(([total, noun]) => `${plural(total, noun)} added.`); + + if (totals.files.updated > 0) { + lines.push(`${plural(totals.files.updated, "media file")} restored.`); } if (totals.records.updated > 0) { - lines.push(`${plural(totals.records.updated, "record")} gained something.`); - } - if (files > 0) { - lines.push(`${plural(files, "media file")} restored.`); + lines.push(`${plural(totals.records.updated, "record")} filled in.`); } if (lines.length === 0) { lines.push("Some records gained details this account was missing."); } - lines.push( - "Your settings, schedule and Bluesky connection were left as they were.", - ); return lines; } diff --git a/services/archive-merge/__tests__/merge-plan.test.ts b/services/archive-merge/__tests__/merge-plan.test.ts index 0b5aea0..90ee029 100644 --- a/services/archive-merge/__tests__/merge-plan.test.ts +++ b/services/archive-merge/__tests__/merge-plan.test.ts @@ -96,6 +96,7 @@ describe("planning a Cyd Bluesky archive merge", () => { const plan = planBlueskyArchiveMerge( existing(), incoming({ posts: [archived(post({ text: "a post deleted from Cyd" }))] }), + ARCHIVE_DID, ); expect(plan.posts).toHaveLength(1); @@ -120,6 +121,7 @@ describe("planning a Cyd Bluesky archive merge", () => { const plan = planBlueskyArchiveMerge( existing({ posts: [{ ...post(), preserve: 0 }] }), incoming({ posts: [archived(post())] }), + ARCHIVE_DID, ); expect(plan.posts).toEqual([]); @@ -137,6 +139,7 @@ describe("planning a Cyd Bluesky archive merge", () => { ], }), incoming({ posts: [archived(post({ text: "", langs: null, savedAt: 9_000 }))] }), + ARCHIVE_DID, ); expect(plan.posts).toEqual([]); @@ -158,6 +161,7 @@ describe("planning a Cyd Bluesky archive merge", () => { archived(post({ text: "after an edit", likeCount: 4, savedAt: 9_000 })), ], }), + ARCHIVE_DID, ); expect(plan.posts[0]).toMatchObject({ @@ -186,6 +190,7 @@ describe("planning a Cyd Bluesky archive merge", () => { ), ], }), + ARCHIVE_DID, ); expect(plan.posts[0]).toMatchObject({ likeCount: 5, replyCount: 3 }); @@ -218,6 +223,7 @@ describe("planning a Cyd Bluesky archive merge", () => { ), ], }), + ARCHIVE_DID, ); expect(plan.posts.map((row) => [row.uri, row.viewerLiked])).toEqual([ @@ -232,6 +238,7 @@ describe("planning a Cyd Bluesky archive merge", () => { posts: [{ ...post({ deletedPostAt: null }), preserve: 0 }], }), incoming({ posts: [archived(post({ deletedPostAt: 4_000 }))] }), + ARCHIVE_DID, ); expect(plan.posts[0]).toMatchObject({ deletedPostAt: 4_000 }); @@ -243,6 +250,7 @@ describe("planning a Cyd Bluesky archive merge", () => { posts: [{ ...post({ text: "kept", savedAt: 1_000 }), preserve: 1 }], }), incoming({ posts: [archived(post({ text: "kept again", savedAt: 9_000 }))] }), + ARCHIVE_DID, ); expect(plan.posts[0]).toMatchObject({ text: "kept again", preserve: 1 }); @@ -257,6 +265,7 @@ describe("planning a Cyd Bluesky archive merge", () => { const plan = planBlueskyArchiveMerge( existing({ posts: [untouched] }), incoming({ posts: [] }), + ARCHIVE_DID, ); expect(plan.posts).toEqual([]); @@ -302,6 +311,7 @@ describe("planning a Cyd Bluesky archive merge", () => { }, ], }), + ARCHIVE_DID, ); expect(plan.mediaAssets[0]).toMatchObject({ @@ -344,12 +354,73 @@ describe("planning a Cyd Bluesky archive merge", () => { }, ], }), + ARCHIVE_DID, ); expect(plan.mediaAssets).toEqual([]); }); }); +/** + * Counting the added rows the way the Browse tabs count them, so a preview can + * say "2 likes" to somebody who will go and look at the Likes tab. + */ +describe("naming what a merge would add", () => { + const added = (rows: MobilePostWrite[]) => + planBlueskyArchiveMerge( + existing(), + incoming({ posts: rows.map(archived) }), + ARCHIVE_DID, + ).summary.addedRecords; + + it("counts the account's own posts as posts", () => { + expect(added([post()])).toMatchObject({ posts: 1, likes: 0, reposts: 0 }); + }); + + it("counts somebody else's post the account liked as a like, not a post", () => { + const liked = post({ + uri: "at://did:plc:someone/app.bsky.feed.post/two", + authorDid: "did:plc:someone", + viewerLiked: 1, + }); + + expect(added([liked])).toMatchObject({ posts: 0, likes: 1 }); + }); + + it("counts a repost as a repost", () => { + const reposted = post({ + uri: "at://did:plc:someone/app.bsky.feed.post/three", + authorDid: "did:plc:someone", + isRepost: 1, + viewerReposted: 1, + }); + + expect(added([reposted])).toMatchObject({ posts: 0, reposts: 1 }); + }); + + it("counts the account's own post that it also liked under both, as Browse does", () => { + // Browse shows this row in the Posts tab and in the Likes tab, so a + // preview that claimed one or the other would disagree with what somebody + // finds when they go and look. + expect(added([post({ viewerLiked: 1 })])).toMatchObject({ + posts: 1, + likes: 1, + }); + }); + + it("says nothing about a kind with nothing to add", () => { + expect(added([])).toEqual({ + posts: 0, + reposts: 0, + likes: 0, + bookmarks: 0, + follows: 0, + chats: 0, + messages: 0, + }); + }); +}); + /** * Whether a merge would change anything, asked of the summary rather than of * whichever tables somebody remembered to look at. @@ -368,6 +439,15 @@ describe("adding a merge summary up", () => { conversations: none, messages: none, mediaAssets: none, + addedRecords: { + posts: 0, + reposts: 0, + likes: 0, + bookmarks: 0, + follows: 0, + chats: 0, + messages: 0, + }, restorations: { total: 0, records: [] }, ...overrides, }); diff --git a/services/archive-merge/__tests__/merge.test.ts b/services/archive-merge/__tests__/merge.test.ts index cd64a21..bc08564 100644 --- a/services/archive-merge/__tests__/merge.test.ts +++ b/services/archive-merge/__tests__/merge.test.ts @@ -213,6 +213,13 @@ describe("merging a Cyd Bluesky archive into an account that holds its identity" }); expect(preview.summary.restorations.total).toBe(doomed.length); + // What the preview says out loud: three posts, and nothing else. + expect(preview.summary.addedRecords).toMatchObject({ + posts: doomed.length, + reposts: 0, + likes: 0, + messages: 0, + }); expect( preview.summary.restorations.records .map((record) => record.id) @@ -354,6 +361,16 @@ describe("merging an archive carrying a file an earlier one could not", () => { files: { added: 0, updated: 1 }, total: 1, }); + // Nothing to say about any kind of record: the file is the whole of it. + expect(preview.summary.addedRecords).toEqual({ + posts: 0, + reposts: 0, + likes: 0, + bookmarks: 0, + follows: 0, + chats: 0, + messages: 0, + }); const result = await commitBlueskyArchiveMerge(harness.environment, preview); diff --git a/services/archive-merge/duplicates.ts b/services/archive-merge/duplicates.ts index 4f898c9..5c230ae 100644 --- a/services/archive-merge/duplicates.ts +++ b/services/archive-merge/duplicates.ts @@ -51,10 +51,10 @@ export type DuplicateAccountPreview = { /** * What this account would take on from the others if it were the one kept. * - * Named rather than counted, for the same reason an archive merge names them - * (ADR 0018): a record missing from this account may be missing because - * somebody deleted it from Cyd here on purpose, and keeping this account - * brings it back. + * An example is named as well as counted, which the merge preview does not + * do. The question there is what an archive would add; the question here is + * which of two Bluesky local accounts is which, and a record one holds and + * the other does not is the thing somebody recognises. */ gains: { total: number; @@ -132,7 +132,11 @@ export async function previewDuplicateReconciliation( .filter((other) => other.uuid !== account.uuid) .map((other) => rows.get(other.uuid)) .filter((other): other is ExistingAccountRows => other !== undefined) - .map((other) => planBlueskyArchiveMerge(own, other).summary.restorations); + .map( + (other) => + planBlueskyArchiveMerge(own, other, identity.did).summary + .restorations, + ); accounts.push({ uuid: account.uuid, @@ -188,6 +192,7 @@ export async function reconcileDuplicateBlueskyAccounts( const plan = planBlueskyArchiveMerge( await readExistingAccountRows(survivor), incoming, + choice.did, ); await survivor.transaction(async () => { await writeMergedAccountRows(survivor, plan); diff --git a/services/archive-merge/merge-plan.ts b/services/archive-merge/merge-plan.ts index e87ef6a..8df58ae 100644 --- a/services/archive-merge/merge-plan.ts +++ b/services/archive-merge/merge-plan.ts @@ -41,12 +41,14 @@ export type BlueskyArchiveMergeCounts = { }; /** - * One record the account no longer holds. + * One record the account does not hold. * - * Restoring these is the point of a recovery import and also the one thing it - * does that somebody might not want, because a record can be absent because - * they deleted it from Cyd on purpose (Bluesky local deletion). So they are - * named in the preview rather than counted in a total. + * The merge preview counts these rather than listing them (ADR 0018): Mobile + * has no Bluesky local deletion, so a missing record is one this account never + * had, and a list of them is nothing somebody can recognise. They are still + * carried, because choosing between two Bluesky local accounts that hold one + * identity is a different question — there, an example of what one holds and + * the other does not is how somebody tells them apart. */ export type RestorationPreview = { category: "posts" | "bookmarks" | "follows" | "chats" | "messages"; @@ -55,9 +57,29 @@ export type RestorationPreview = { createdAt: string | null; }; -/** How many named restorations the preview carries before it stops listing. */ +/** How many records a plan names before it only counts them. */ const MAX_LISTED_RESTORATIONS = 50; +/** + * How many of each kind of record a merge would add, named the way Browse + * names them. + * + * Mobile keeps posts, reposts, likes and bookmarks in one table and tells them + * apart by column, so this classifies the rows the same way the Browse tabs + * count them. A row can land under two headings — the account's own post that + * it also liked is both — which is exactly what Browse shows, so agreeing with + * it beats adding up to a tidier total. + */ +export type AddedRecordCounts = { + posts: number; + reposts: number; + likes: number; + bookmarks: number; + follows: number; + chats: number; + messages: number; +}; + export type BlueskyArchiveMergeSummary = { profiles: BlueskyArchiveMergeCounts; posts: BlueskyArchiveMergeCounts; @@ -68,9 +90,11 @@ export type BlueskyArchiveMergeSummary = { conversations: BlueskyArchiveMergeCounts; messages: BlueskyArchiveMergeCounts; mediaAssets: BlueskyArchiveMergeCounts; + /** The added rows, by the name somebody would give them. */ + addedRecords: AddedRecordCounts; restorations: { total: number; - /** The first `MAX_LISTED_RESTORATIONS`, for somebody to look through. */ + /** The first `MAX_LISTED_RESTORATIONS`, for a caller that names them. */ records: RestorationPreview[]; }; }; @@ -89,7 +113,7 @@ export type BlueskyArchiveMergeSummary = { * or this does not compile. */ const MERGE_CATEGORIES: Record< - Exclude, + Exclude, "records" | "files" | "context" > = { posts: "records", @@ -232,6 +256,9 @@ function sameRow(left: object, right: object): boolean { export function planBlueskyArchiveMerge( existing: ExistingAccountRows, incoming: ExistingAccountRows, + /** Whose account this is, which is what makes a post theirs rather than + * somebody else's that they liked. */ + accountDid: string, ): BlueskyArchiveMergePlan { const profiles = mergeTable(existing.profiles, incoming.profiles, { key: (row) => row.did, @@ -292,6 +319,13 @@ export function planBlueskyArchiveMerge( conversations: conversations.counts, messages: messages.counts, mediaAssets: mediaAssets.counts, + addedRecords: countAddedRecords(accountDid, { + posts: posts.added, + bookmarks: bookmarks.added, + follows: follows.added, + conversations: conversations.added, + messages: messages.added, + }), restorations: summarizeRestorations({ posts: posts.added, bookmarks: bookmarks.added, @@ -303,6 +337,42 @@ export function planBlueskyArchiveMerge( }; } +/** + * Count the added rows under the headings Browse uses. + * + * The rules are Browse's own (`buildTotalCountQuery`): a post is one this + * account wrote and did not repost, while a repost, a like and a bookmark are + * any post row carrying that mark. Saying "3 posts and 2 likes" rather than + * "5 records" is only true if it is counted the way the tabs somebody will go + * and look at are counted. + */ +function countAddedRecords( + accountDid: string, + added: { + posts: ExistingPostRow[]; + bookmarks: MobileBookmarkWrite[]; + follows: MobileFollowWrite[]; + conversations: MobileConversationWrite[]; + messages: MobileMessageWrite[]; + }, +): AddedRecordCounts { + const posts = added.posts.filter( + (row) => row.authorDid === accountDid && row.isRepost === 0, + ).length; + + return { + posts, + reposts: added.posts.filter((row) => row.viewerReposted === 1).length, + likes: added.posts.filter((row) => row.viewerLiked === 1).length, + // Bookmarks live in their own table as well as on the post row; the table + // is the record, so it is what gets counted. + bookmarks: added.bookmarks.length, + follows: added.follows.length, + chats: added.conversations.length, + messages: added.messages.length, + }; +} + /** * The records coming back, in the order somebody would read them. * diff --git a/services/archive-merge/merge.ts b/services/archive-merge/merge.ts index 55baeee..83bba6f 100644 --- a/services/archive-merge/merge.ts +++ b/services/archive-merge/merge.ts @@ -128,6 +128,7 @@ export async function previewBlueskyArchiveMerge( const plan = await planAgainstAccount( environment, request.account.uuid, + snapshot.archive.account_did, incoming, ); @@ -179,6 +180,7 @@ export async function commitBlueskyArchiveMerge( const plan = await planAgainstAccount( environment, preview.accountUuid, + preview.accountDid, incoming, ); @@ -219,6 +221,7 @@ function reporter(options: { async function planAgainstAccount( environment: BlueskyArchiveMergeEnvironment, accountUuid: string, + accountDid: string, incoming: RestoredMobileAccount, ): Promise { const database = await environment.openAccountDatabase(accountUuid); @@ -226,6 +229,7 @@ async function planAgainstAccount( return planBlueskyArchiveMerge( await readExistingAccountRows(database), accountRowsFromArchive(incoming), + accountDid, ); } finally { await database.close(); From 6d976af32bb1d6177cb7e3d8c71bf39a44791914 Mon Sep 17 00:00:00 2001 From: Micah Lee Date: Sun, 13 Sep 2026 16:10:16 -0700 Subject: [PATCH 6/9] Share one handle per account database, instead of opening a second MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Importing an archive into an account, then opening that account, broke Browse and the auth-status check with Call to function 'NativeDatabase.prepareAsync' has been rejected. → Caused by: java.lang.NullPointerException minutes after the import that caused it, on a controller the manager had cached long before. expo-sqlite keeps one native connection per database path and hands it to everyone who opens it with the same options, but each JS handle also owns it: `NativeDatabase` is a `SharedRef` whose `sharedObjectDidRelease` closes the connection, and that runs when the handle is garbage collected regardless of who else is still holding one. So opening an already-open database is not a second connection. It is a promise that somebody's queries will start failing at whatever later moment the collector runs, which is why this looked like an unrelated screen breaking on its own. `BaseAccountController` already knew this and kept a map of one handle per file, refcounted. The archive adapters did not: restore and merge both called `openDatabaseAsync` themselves and closed what they got, and restore also closed the database it had just created for a new account. The map moves to `database/account-db/shared-handles.ts`, the controller delegates to it, and both adapters borrow — their port's `close` hands the handle back rather than closing it. Acquiring registers the handle before the open resolves, so two callers arriving together share one connection rather than racing into two. A controller holding a handle that never came from the map still closes it itself, since that one is nobody else's. The Node test double has no shared-connection semantics, so no fixture could have caught this. Seven tests cover the map directly. Co-Authored-By: Claude Opus 5 (1M context) --- controllers/BaseAccountController.ts | 107 ++++------------ .../__tests__/shared-handles.test.ts | 109 ++++++++++++++++ database/account-db/shared-handles.ts | 117 ++++++++++++++++++ services/archive-merge/environment.ts | 27 ++-- services/archive-restore/environment.ts | 32 +++-- 5 files changed, 298 insertions(+), 94 deletions(-) create mode 100644 database/account-db/__tests__/shared-handles.test.ts create mode 100644 database/account-db/shared-handles.ts diff --git a/controllers/BaseAccountController.ts b/controllers/BaseAccountController.ts index 3aa2955..67200f6 100644 --- a/controllers/BaseAccountController.ts +++ b/controllers/BaseAccountController.ts @@ -1,12 +1,13 @@ import * as Crypto from "expo-crypto"; import { Directory, File, Paths } from "expo-file-system"; -import { - defaultDatabaseDirectory, - openDatabaseAsync, - type SQLiteDatabase, -} from "expo-sqlite"; +import { defaultDatabaseDirectory, type SQLiteDatabase } from "expo-sqlite"; import { getDatabase } from "@/database"; +import { + accountDatabaseRefCount, + acquireAccountDatabase, + releaseAccountDatabase, +} from "@/database/account-db/shared-handles"; import { getBackupEligibleDataRoot } from "@/services/device-storage"; /** @@ -63,15 +64,10 @@ export class CancelledError extends Error { * configuration storage, and progress tracking. */ export abstract class BaseAccountController { - private static sharedAccountDbs = new Map< - string, - { db: SQLiteDatabase; refCount: number } - >(); - protected accountId: number; protected accountUUID: string; protected db: SQLiteDatabase | null = null; - private sharedDbKey: string | null = null; + private sharedDbKey: { dbDir: string; dbName: string } | null = null; private _disposed = false; protected _progress: TProgress; private paused = false; @@ -265,47 +261,15 @@ export abstract class BaseAccountController { await this.ensureAccountDirectory(); const { dbDir, dbName } = this.getAccountDatabaseSQLiteInfo(); - const dbKey = `${dbDir}::${dbName}`; - - const existing = BaseAccountController.sharedAccountDbs.get(dbKey); - if (existing) { - existing.refCount += 1; - this.sharedDbKey = dbKey; - console.log( - "[BaseAccountController] openAccountDatabase -> reuse shared db", - { - accountId: this.accountId, - accountType: this.getAccountType(), - accountUUID: this.accountUUID, - dbKey, - refCount: existing.refCount, - }, - ); - return existing.db; - } - - console.log( - "[BaseAccountController] openAccountDatabase -> opening new db", - { - accountId: this.accountId, - accountType: this.getAccountType(), - accountUUID: this.accountUUID, - dbKey, - dbDir, - dbName, - }, - ); - const db = await openDatabaseAsync(dbName, {}, dbDir); - await db.execAsync("PRAGMA foreign_keys = ON;"); - - BaseAccountController.sharedAccountDbs.set(dbKey, { db, refCount: 1 }); - this.sharedDbKey = dbKey; - console.log("[BaseAccountController] openAccountDatabase -> opened", { + const db = await acquireAccountDatabase(dbDir, dbName); + this.sharedDbKey = { dbDir, dbName }; + console.log("[BaseAccountController] openAccountDatabase -> acquired", { accountId: this.accountId, accountType: this.getAccountType(), accountUUID: this.accountUUID, - dbKey, - refCount: 1, + dbDir, + dbName, + refCount: accountDatabaseRefCount(dbDir, dbName), }); return db; @@ -401,7 +365,7 @@ export abstract class BaseAccountController { } const dbToRelease = this.db; - const dbKey = this.sharedDbKey; + const shared = this.sharedDbKey; this.db = null; this.sharedDbKey = null; @@ -410,44 +374,27 @@ export abstract class BaseAccountController { accountId: this.accountId, accountType: this.getAccountType(), accountUUID: this.accountUUID, - dbKey, + ...shared, }); - if (dbKey) { - const entry = BaseAccountController.sharedAccountDbs.get(dbKey); - if (entry) { - const beforeRefCount = entry.refCount; - entry.refCount -= 1; - console.log( - "[BaseAccountController] cleanup -> shared refCount decremented", - { - accountId: this.accountId, - accountType: this.getAccountType(), - accountUUID: this.accountUUID, - dbKey, - beforeRefCount, - afterRefCount: entry.refCount, - }, - ); - if (entry.refCount <= 0) { - BaseAccountController.sharedAccountDbs.delete(dbKey); - console.log("[BaseAccountController] cleanup -> closing shared db", { - accountId: this.accountId, - accountType: this.getAccountType(), - accountUUID: this.accountUUID, - dbKey, - }); - await entry.db.closeAsync(); - } - return; - } + if (shared) { + await releaseAccountDatabase(shared.dbDir, shared.dbName); + console.log("[BaseAccountController] cleanup -> released", { + accountId: this.accountId, + accountType: this.getAccountType(), + accountUUID: this.accountUUID, + ...shared, + refCount: accountDatabaseRefCount(shared.dbDir, shared.dbName), + }); + return; } + // A handle that did not come from the shared map is this controller's + // alone, so closing it is closing it for nobody else. console.log("[BaseAccountController] cleanup -> closing direct db", { accountId: this.accountId, accountType: this.getAccountType(), accountUUID: this.accountUUID, - dbKey, }); await dbToRelease.closeAsync(); } diff --git a/database/account-db/__tests__/shared-handles.test.ts b/database/account-db/__tests__/shared-handles.test.ts new file mode 100644 index 0000000..b140362 --- /dev/null +++ b/database/account-db/__tests__/shared-handles.test.ts @@ -0,0 +1,109 @@ +const opened: { path: string; closeAsync: jest.Mock; execAsync: jest.Mock }[] = + []; + +jest.mock("expo-sqlite", () => ({ + openDatabaseAsync: jest.fn(async (dbName: string, _options, dbDir: string) => { + const db = { + path: `${dbDir}::${dbName}`, + closeAsync: jest.fn(async () => {}), + execAsync: jest.fn(async () => {}), + }; + opened.push(db); + return db; + }), +})); + +import { openDatabaseAsync } from "expo-sqlite"; + +import { + accountDatabaseRefCount, + acquireAccountDatabase, + releaseAccountDatabase, +} from "../shared-handles"; + +const DIR = "/files/accounts/bluesky-account"; +const NAME = "data.db"; + +/** + * One handle per account database file. + * + * expo-sqlite hands every caller the same native connection, and every JS + * handle over it can close that connection when it is garbage collected. So + * "open it again and close it when done" is not a local decision: it breaks + * whoever else is holding the database, at whatever later moment the + * collector runs. + */ +describe("sharing one handle per account database", () => { + afterEach(async () => { + // Give everything back, so one test's holders are not another's. + while (accountDatabaseRefCount(DIR, NAME) > 0) { + await releaseAccountDatabase(DIR, NAME); + } + opened.length = 0; + jest.clearAllMocks(); + }); + + it("opens the database once, however many holders it has", async () => { + const first = await acquireAccountDatabase(DIR, NAME); + const second = await acquireAccountDatabase(DIR, NAME); + + expect(second).toBe(first); + expect(openDatabaseAsync).toHaveBeenCalledTimes(1); + expect(accountDatabaseRefCount(DIR, NAME)).toBe(2); + }); + + it("does not close a database somebody else is still holding", async () => { + const db = await acquireAccountDatabase(DIR, NAME); + await acquireAccountDatabase(DIR, NAME); + + await releaseAccountDatabase(DIR, NAME); + + expect(db.closeAsync).not.toHaveBeenCalled(); + }); + + it("closes it when the last holder gives it back", async () => { + const db = await acquireAccountDatabase(DIR, NAME); + await acquireAccountDatabase(DIR, NAME); + + await releaseAccountDatabase(DIR, NAME); + await releaseAccountDatabase(DIR, NAME); + + expect(db.closeAsync).toHaveBeenCalledTimes(1); + expect(accountDatabaseRefCount(DIR, NAME)).toBe(0); + }); + + it("opens a fresh one after the last holder let go", async () => { + await acquireAccountDatabase(DIR, NAME); + await releaseAccountDatabase(DIR, NAME); + + await acquireAccountDatabase(DIR, NAME); + + expect(openDatabaseAsync).toHaveBeenCalledTimes(2); + }); + + it("gives two callers arriving at once the same handle", async () => { + const [first, second] = await Promise.all([ + acquireAccountDatabase(DIR, NAME), + acquireAccountDatabase(DIR, NAME), + ]); + + expect(second).toBe(first); + expect(openDatabaseAsync).toHaveBeenCalledTimes(1); + }); + + it("keeps databases for different accounts apart", async () => { + const mine = await acquireAccountDatabase(DIR, NAME); + const theirs = await acquireAccountDatabase("/files/accounts/other", NAME); + + expect(theirs).not.toBe(mine); + + await releaseAccountDatabase("/files/accounts/other", NAME); + expect(mine.closeAsync).not.toHaveBeenCalled(); + }); + + it("ignores a release from somebody who never acquired", async () => { + await expect( + releaseAccountDatabase("/files/accounts/never-opened", NAME), + ).resolves.toBeUndefined(); + }); +}); diff --git a/database/account-db/shared-handles.ts b/database/account-db/shared-handles.ts new file mode 100644 index 0000000..2fe3921 --- /dev/null +++ b/database/account-db/shared-handles.ts @@ -0,0 +1,117 @@ +import { openDatabaseAsync, type SQLiteDatabase } from "expo-sqlite"; + +/** + * One open handle per account database file, shared for as long as anybody + * wants it. + * + * expo-sqlite keeps one native connection per path and hands the same one to + * every caller that opens it with the same options — but each JS handle also + * *owns* that connection. Its native object is a `SharedRef` whose + * `sharedObjectDidRelease` closes the connection, and that runs when the JS + * handle is garbage collected, no matter who else is still holding one. So a + * second `openDatabaseAsync` for a database the app already has open is not a + * second connection. It is a promise that somebody's queries will start + * failing with + * + * Call to function 'NativeDatabase.prepareAsync' has been rejected. + * → Caused by: java.lang.NullPointerException + * + * at whatever later moment the collector happens to run — which is why it + * looks like an unrelated screen breaking minutes after the work that caused + * it. + * + * Everything that opens an account database goes through here: one handle per + * file, lent out as often as it is asked for, and closed once — when the last + * holder gives it back. + */ + +type SharedHandle = { + db: SQLiteDatabase; + refCount: number; + /** Serializes opens, so two callers at once cannot make two connections. */ + opening: Promise; +}; + +const handles = new Map(); + +function keyFor(dbDir: string, dbName: string): string { + return `${dbDir}::${dbName}`; +} + +/** + * Borrow the handle for an account database, opening it if nobody has it. + * + * Every caller must hand it back with `releaseAccountDatabase`, and none may + * close it themselves: closing a borrowed handle closes it for its other + * holders too. + */ +export async function acquireAccountDatabase( + dbDir: string, + dbName: string, +): Promise { + const key = keyFor(dbDir, dbName); + const existing = handles.get(key); + if (existing) { + existing.refCount += 1; + return existing.opening; + } + + const opening = (async () => { + const db = await openDatabaseAsync(dbName, {}, dbDir); + await db.execAsync("PRAGMA foreign_keys = ON;"); + return db; + })(); + + // Registered before it finishes opening, so a second caller arriving while + // the first is still awaiting waits for that one rather than starting its + // own. + const handle: SharedHandle = { + db: undefined as unknown as SQLiteDatabase, + refCount: 1, + opening, + }; + handles.set(key, handle); + + try { + handle.db = await opening; + } catch (err) { + handles.delete(key); + throw err; + } + return handle.db; +} + +/** + * Give a handle back, closing it when the last holder does. + * + * Releasing one nobody is holding is a no-op rather than an error: a caller + * cleaning up after a failure should not have to know whether it got as far + * as acquiring. + */ +export async function releaseAccountDatabase( + dbDir: string, + dbName: string, +): Promise { + const key = keyFor(dbDir, dbName); + const handle = handles.get(key); + if (!handle) { + return; + } + + handle.refCount -= 1; + if (handle.refCount > 0) { + return; + } + + handles.delete(key); + const db = await handle.opening.catch(() => null); + await db?.closeAsync(); +} + +/** How many holders a database has, for tests and for logging. */ +export function accountDatabaseRefCount( + dbDir: string, + dbName: string, +): number { + return handles.get(keyFor(dbDir, dbName))?.refCount ?? 0; +} diff --git a/services/archive-merge/environment.ts b/services/archive-merge/environment.ts index 86445be..75849da 100644 --- a/services/archive-merge/environment.ts +++ b/services/archive-merge/environment.ts @@ -1,11 +1,15 @@ import { Directory, File } from "expo-file-system"; -import { openDatabaseAsync, type SQLiteDatabase } from "expo-sqlite"; +import type { SQLiteDatabase } from "expo-sqlite"; import { buildAccountPaths } from "@/controllers/BaseAccountController"; import { applyAccountMigrations, blueskyAccountMigrations, } from "@/database/account-db"; +import { + acquireAccountDatabase, + releaseAccountDatabase, +} from "@/database/account-db/shared-handles"; import { deleteAccount, listAccounts } from "@/database/accounts"; import { getDatabase } from "@/database"; import { openPreparedArchive } from "@/services/archive-restore/environment"; @@ -35,26 +39,32 @@ async function openAccountDatabase(accountUuid: string): Promise intermediates: true, idempotent: true, }); - const database = await openDatabaseAsync( - paths.dbNameForSQLite, - {}, + // Borrowed rather than opened: the app may already hold this database, and a + // second handle over the same connection closes it for the first one when it + // is collected. + const database = await acquireAccountDatabase( paths.dbDirForSQLite, + paths.dbNameForSQLite, ); - await database.execAsync("PRAGMA foreign_keys = ON;"); applyAccountMigrations(database, blueskyAccountMigrations); return database; } function asMergeableAccountDatabase( database: SQLiteDatabase, + accountUuid: string, ): MergeableAccountDatabase { + const paths = buildAccountPaths("bluesky", accountUuid); return { all: async (sql: string) => database.getAllAsync(sql), run: async (sql, params) => { await database.runAsync(sql, params as never[]); }, transaction: (work) => database.withTransactionAsync(work), - close: async () => database.closeAsync(), + // Handed back rather than closed. The account screen may be holding this + // very database, and closing a borrowed handle closes it for them too. + close: async () => + releaseAccountDatabase(paths.dbDirForSQLite, paths.dbNameForSQLite), }; } @@ -84,7 +94,10 @@ export function createBlueskyArchiveMergeEnvironment(): BlueskyArchiveMergeEnvir })), openAccountDatabase: async (accountUuid) => - asMergeableAccountDatabase(await openAccountDatabase(accountUuid)), + asMergeableAccountDatabase( + await openAccountDatabase(accountUuid), + accountUuid, + ), storeAccountMedia: async (accountUuid, fileName, write) => { const paths = buildAccountPaths("bluesky", accountUuid); diff --git a/services/archive-restore/environment.ts b/services/archive-restore/environment.ts index 7f10889..06753f1 100644 --- a/services/archive-restore/environment.ts +++ b/services/archive-restore/environment.ts @@ -10,6 +10,10 @@ import { applyAccountMigrations, blueskyAccountMigrations, } from "@/database/account-db"; +import { + acquireAccountDatabase, + releaseAccountDatabase, +} from "@/database/account-db/shared-handles"; import { createBlueskyAccount, deleteAccount, @@ -65,13 +69,18 @@ function asReadableInterchange( function asRestoredAccountDatabase( database: SQLiteDatabase, + accountUuid: string, ): RestoredAccountDatabase { + const paths = buildAccountPaths("bluesky", accountUuid); return { run: async (sql, params) => { await database.runAsync(sql, params as never[]); }, transaction: (work) => database.withTransactionAsync(work), - close: async () => database.closeAsync(), + // Handed back rather than closed: the handle is shared with anything else + // in the app holding this account open. + close: async () => + releaseAccountDatabase(paths.dbDirForSQLite, paths.dbNameForSQLite), }; } @@ -81,12 +90,13 @@ async function openAccountDatabase(accountUuid: string): Promise intermediates: true, idempotent: true, }); - const database = await openDatabaseAsync( - paths.dbNameForSQLite, - {}, + // Borrowed rather than opened: the app may already hold this database, and a + // second handle over the same connection closes it for the first one when it + // is collected. + const database = await acquireAccountDatabase( paths.dbDirForSQLite, + paths.dbNameForSQLite, ); - await database.execAsync("PRAGMA foreign_keys = ON;"); applyAccountMigrations(database, blueskyAccountMigrations); return database; } @@ -186,13 +196,21 @@ export function createBlueskyArchiveRestoreEnvironment(): BlueskyArchiveRestoreE // Creating the database here means a restore that fails later leaves an // account directory to delete rather than a half-migrated one to guess at. - (await openAccountDatabase(request.uuid)).closeSync(); + await openAccountDatabase(request.uuid); + const created = buildAccountPaths("bluesky", request.uuid); + await releaseAccountDatabase( + created.dbDirForSQLite, + created.dbNameForSQLite, + ); return { accountId: account.id, accountUuid: account.uuid }; }, openAccountDatabase: async (accountUuid) => - asRestoredAccountDatabase(await openAccountDatabase(accountUuid)), + asRestoredAccountDatabase( + await openAccountDatabase(accountUuid), + accountUuid, + ), storeAccountMedia: async ( accountUuid, From 0266d203950836f9ceb5fc287843ac98723ff3cc Mon Sep 17 00:00:00 2001 From: Micah Lee Date: Sun, 13 Sep 2026 16:25:34 -0700 Subject: [PATCH 7/9] Drop duplicate-DID reconciliation, which guards an unreachable state MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reviewing the reconciliation screen on a device raised the obvious question: can Cyd Mobile actually hold one Bluesky identity in two Bluesky local accounts? It cannot, and never could. `bsky_account.did` has carried its unique index since the same migration that added the column — both in one statement list, so in one transaction, in the initial commit and still after `dc80de5 "Flatten migrations"` moved them into version 1 together. Every write path reuses the row the DID or handle already names: `findBlueskyLocalAccount` and `saveAuthenticatedBlueskyAccount` both match `did = ? OR handle = ?`, and archive restore refuses an identity this installation holds and merges instead. Restoring an OS backup — the justification this branch gave — restores the index along with everything else, so it does not produce the state either. Setting the state up to test it took `DROP INDEX` over adb. ADR 0011 said Mobile's migration detects duplicates and flags them. No migration does, and the ADR appears to describe the shared Cyd contract's history rather than Mobile's. It is marked superseded here and left standing for clients whose schema does permit the state. So the feature goes: `duplicates.ts` and its tests, the reconciling screen and hook state, the two ports that existed only to read and write another account's settings, the ports that removed an account and put the unique index back, and `scheduled-reminder-sync.ts`, which existed only to retire a local-account UUID that only reconciliation retired. `chooseBlueskyArchiveImportDestination` now refuses an archive it cannot place rather than choosing between two accounts: a database holding one identity twice is one Cyd did not build and cannot reason about, and saying so beats merging into whichever row came back first. What is reachable, and deliberately still unhandled, is an old account with no DID beside a newer one that has it. Nothing proves those are one identity, and guessing from a handle is what the DID exists to avoid. Reconciliation did not handle that case either — `findDuplicateBlueskyIdentities` skipped null DIDs. Co-Authored-By: Claude Opus 5 (1M context) --- CONTEXT.md | 4 - components/BlueskyArchiveImportModal.tsx | 153 +------- components/CydAccountBar.tsx | 15 +- ...licate-dids-before-enforcing-uniqueness.md | 10 +- .../use-bluesky-archive-import.test.ts | 4 - hooks/use-bluesky-archive-import.ts | 117 +----- .../__tests__/destination.test.ts | 28 +- .../__tests__/duplicates.test.ts | 292 -------------- services/archive-merge/destination.ts | 22 +- services/archive-merge/duplicates.ts | 364 ------------------ services/archive-merge/environment.ts | 83 +--- services/archive-merge/errors.ts | 11 +- services/archive-merge/index.ts | 23 +- services/archive-merge/merge-plan.ts | 20 +- services/archive-merge/ports.ts | 89 +---- services/archive-merge/rows.ts | 6 +- services/scheduled-reminder-sync.ts | 87 ----- testUtils/archiveEnvironments.ts | 56 --- 18 files changed, 76 insertions(+), 1308 deletions(-) delete mode 100644 services/archive-merge/__tests__/duplicates.test.ts delete mode 100644 services/archive-merge/duplicates.ts delete mode 100644 services/scheduled-reminder-sync.ts diff --git a/CONTEXT.md b/CONTEXT.md index 4ccca52..7fa9955 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -48,10 +48,6 @@ _Avoid_: restore, import, replace The commit half of a Bluesky archive import for an identity this installation already holds: a union of the Cyd Bluesky archive into that Bluesky local account's Bluesky saved data, previewed before it is written. It adds and enriches Bluesky saved records and never touches the account's identifier, Bluesky account settings, schedules or Bluesky connection. _Avoid_: merge, sync, overwrite, import -**Bluesky identity reconciliation**: -Collapsing several Bluesky local accounts that hold one Bluesky identity into a single surviving one, after the person chooses which local-account UUID and whose Bluesky account settings it keeps. It unions their Bluesky saved data and restores the rule that one Bluesky identity has one Bluesky local account. -_Avoid_: deduplication, account merge, cleanup - **Bluesky account settings**: Local preferences governing how Cyd saves and manages a Bluesky identity. A Cyd Bluesky archive can supply defaults for a new Bluesky local account, but does not silently override an existing Bluesky local account's preferences or schedules. _Avoid_: account settings, account data, archive state diff --git a/components/BlueskyArchiveImportModal.tsx b/components/BlueskyArchiveImportModal.tsx index 7e3e420..a83053b 100644 --- a/components/BlueskyArchiveImportModal.tsx +++ b/components/BlueskyArchiveImportModal.tsx @@ -1,9 +1,7 @@ -import { useState } from "react"; import { ActivityIndicator, Modal, Pressable, - ScrollView, StyleSheet, Text, View, @@ -27,19 +25,10 @@ import type { BlueskyArchiveImportState } from "@/hooks/use-bluesky-archive-impo * of somebody's own posts should never look like a frozen screen. */ -type ReconciliationChoice = { - survivingUuid: string; - settingsFromUuid: string; -}; - export type BlueskyArchiveImportModalProps = { state: BlueskyArchiveImportState; onConfirmLargeArchive: () => void; onConfirmMerge: () => void; - onKeepAccount: (choice: { - survivingUuid: string; - settingsFromUuid: string; - }) => void; /** Connect the account an import just restored, from where it was restored. */ onSignIn: (handle: string) => void; onCancel: () => void; @@ -50,36 +39,11 @@ export function BlueskyArchiveImportModal({ state, onConfirmLargeArchive, onConfirmMerge, - onKeepAccount, onSignIn, onCancel, onDismiss, }: BlueskyArchiveImportModalProps) { const palette = getThemePalette(useColorScheme()); - const [picked, setPicked] = useState(null); - - const reconciling = state.status === "reconciling" ? state.preview : null; - /** - * Which account is selected, before anybody has touched anything. - * - * The default is the one holding the most, because it is the one somebody is - * most likely to recognise as theirs — but it is only a default, and a - * selection that names an account this preview does not hold is stale and - * falls back to it. - */ - const known = (uuid: string | undefined): boolean => - reconciling?.accounts.some((account) => account.uuid === uuid) === true; - const fallback = reconciling - ? [...reconciling.accounts].sort( - (left, right) => totalRecords(right) - totalRecords(left), - )[0]?.uuid - : undefined; - const survivingUuid = known(picked?.survivingUuid) - ? picked!.survivingUuid - : fallback; - const settingsFromUuid = known(picked?.settingsFromUuid) - ? picked!.settingsFromUuid - : survivingUuid; if (state.status === "idle") { return null; @@ -139,101 +103,6 @@ export function BlueskyArchiveImportModal({ ) : null} - {state.status === "reconciling" && survivingUuid ? ( - <> - - Two accounts, one Bluesky identity - - - {state.message} - - - {state.preview.accounts.map((account) => ( - - - setPicked({ - survivingUuid: account.uuid, - settingsFromUuid: settingsFromUuid ?? account.uuid, - }) - } - accessibilityRole="radio" - accessibilityState={{ - selected: account.uuid === survivingUuid, - }} - style={[ - styles.choiceButton, - { - borderColor: - account.uuid === survivingUuid - ? palette.tint - : palette.icon + "22", - }, - ]} - > - - {account.handle ?? account.uuid} - - - {account.counts.posts} posts · {account.counts.chats}{" "} - chats · {account.counts.follows} follows - - {account.gains.total > 0 ? ( - - Keeping this one brings back {account.gains.total}{" "} - records it does not have, including{" "} - {describeRecord(account.gains.records[0])}. - - ) : null} - - - setPicked({ - survivingUuid, - settingsFromUuid: account.uuid, - }) - } - accessibilityRole="radio" - accessibilityState={{ - selected: account.uuid === settingsFromUuid, - }} - > - - {account.uuid === settingsFromUuid - ? "✓ Keeping these settings and schedule" - : "Keep these settings and schedule"} - - - - ))} - - - Nothing is lost either way: the account you keep ends up with - everything both of them held. - - {action( - "Keep this account and continue", - () => - onKeepAccount({ - survivingUuid, - settingsFromUuid: settingsFromUuid ?? survivingUuid, - }), - "primary", - )} - {action("Cancel", onCancel)} - - ) : null} - {state.status === "reviewing" ? ( <> @@ -297,6 +166,7 @@ export function BlueskyArchiveImportModal({ ); } + /** * A handle written so a line box breaks it where a reader would. * @@ -311,27 +181,6 @@ function breakableHandle(handle: string): string { return `@${handle.replace(/^@/, "")}`.replace(/\./g, "\u200B."); } -/** One restored record, short enough to sit inside a sentence. */ -function describeRecord(record: { - category: string; - id: string; - text: string | null; -}): string { - const text = record.text?.trim(); - return text ? `“${text.slice(0, 60)}”` : `one ${record.category} record`; -} - -function totalRecords(account: { - counts: { posts: number; chats: number; messages: number; follows: number }; -}): number { - return ( - account.counts.posts + - account.counts.chats + - account.counts.messages + - account.counts.follows - ); -} - /** `2 posts`, and `1 post` rather than `1 posts`. */ function count(total: number, noun: string): string { return `${total.toLocaleString()} ${noun}${total === 1 ? "" : "s"}`; diff --git a/components/CydAccountBar.tsx b/components/CydAccountBar.tsx index da7893f..7463f13 100644 --- a/components/CydAccountBar.tsx +++ b/components/CydAccountBar.tsx @@ -1,4 +1,4 @@ -import { useCallback, useMemo, useState } from "react"; +import { useCallback, useState } from "react"; import { Alert, Linking, @@ -17,7 +17,6 @@ import { useBlueskyArchiveImport } from "@/hooks/use-bluesky-archive-import"; import { useColorScheme } from "@/hooks/use-color-scheme"; import { emitLocalAccountsChanged } from "@/services/account-events"; import { connectBlueskyAccount } from "@/services/bluesky-sign-in"; -import { createScheduledReminderSync } from "@/services/scheduled-reminder-sync"; import { BlueskyArchiveImportModal } from "./BlueskyArchiveImportModal"; import { CydSignInModal } from "./CydSignInModal"; @@ -37,18 +36,11 @@ export function CydAccountBar({ Platform.OS === "android" ? Math.max(bottomInset, 8) : bottomInset; const colorScheme = useColorScheme(); const palette = getThemePalette(colorScheme); - const { state, signOut, getDashboardURL, apiClient } = useCydAccount(); + const { state, signOut, getDashboardURL } = useCydAccount(); const [menuVisible, setMenuVisible] = useState(false); const [signInModalVisible, setSignInModalVisible] = useState(false); - const archiveImport = useBlueskyArchiveImport({ - // Reconciling duplicate accounts can retire a local-account UUID the - // server schedules reminders against (ADR 0005), so the import tells it. - reminders: useMemo( - () => createScheduledReminderSync(apiClient, state.isSignedIn), - [apiClient, state.isSignedIn], - ), - }); + const archiveImport = useBlueskyArchiveImport(); const handleMenuPress = useCallback(() => { setMenuVisible(true); @@ -318,7 +310,6 @@ export function CydAccountBar({ state={archiveImport.state} onConfirmLargeArchive={() => void archiveImport.confirmLargeArchive()} onConfirmMerge={() => void archiveImport.confirmMerge()} - onKeepAccount={(choice) => void archiveImport.keepAccount(choice)} onSignIn={handleSignIn} onCancel={archiveImport.cancel} onDismiss={archiveImport.dismiss} diff --git a/docs/adr/0011-reconcile-duplicate-dids-before-enforcing-uniqueness.md b/docs/adr/0011-reconcile-duplicate-dids-before-enforcing-uniqueness.md index ce09abc..20c495e 100644 --- a/docs/adr/0011-reconcile-duplicate-dids-before-enforcing-uniqueness.md +++ b/docs/adr/0011-reconcile-duplicate-dids-before-enforcing-uniqueness.md @@ -1,3 +1,11 @@ # Reconcile duplicate DIDs before enforcing uniqueness -Cyd Mobile migration detects existing local accounts that share a Bluesky DID and flags them for explicit reconciliation rather than selecting one silently. The user previews an idempotent union of saved data and chooses the surviving local-account UUID and settings; after duplicates are resolved, mobile enforces one local account per DID so archive imports have an unambiguous destination. +**Superseded on Mobile: the state this describes is unreachable here.** + +The original decision was that Cyd Mobile migration would detect existing Bluesky local accounts sharing a Bluesky DID and flag them for explicit reconciliation — the person previews an idempotent union of Bluesky saved data and chooses the surviving local-account UUID and Bluesky account settings — rather than selecting one silently, after which one local account per DID is enforced so a Bluesky archive import has an unambiguous destination. + +No Mobile migration ever performed that detection, and none could have needed to. `bsky_account.did` has carried a unique index since the same migration that added the column, in the same statement list and so in the same transaction, which means no Mobile database has ever held one Bluesky identity in two Bluesky local accounts. Every path that writes an account reuses the row the DID or handle already names, and Bluesky archive restore refuses an identity this installation holds and merges instead. Restoring an OS backup restores the index with it, so it does not produce the state either. The unique index permits several rows with no DID, but an account whose Bluesky identity is unknown is not a duplicate of anything. + +So Mobile does not carry reconciliation. `chooseBlueskyArchiveImportDestination` refuses an archive it cannot place rather than choosing between two accounts, because a database holding one identity twice is a database Cyd did not build and has no way to reason about. What remains reachable, and is deliberately not handled, is an old Bluesky local account with no DID sitting beside a newer one that has it: nothing proves those are one identity, and guessing from a handle is what the DID exists to avoid. + +This ADR stands for clients whose schema does permit the state. diff --git a/hooks/__tests__/use-bluesky-archive-import.test.ts b/hooks/__tests__/use-bluesky-archive-import.test.ts index 52f2ec4..d5b0d5b 100644 --- a/hooks/__tests__/use-bluesky-archive-import.test.ts +++ b/hooks/__tests__/use-bluesky-archive-import.test.ts @@ -3,7 +3,6 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -import { NO_SCHEDULED_REMINDERS } from "@/services/scheduled-reminder-sync"; import { createDiskBlueskyArchiveIntakeEnvironment, createNodeBlueskyArchiveRestoreEnvironment, @@ -94,7 +93,6 @@ describe("importing a Cyd Bluesky archive from the menu", () => { const { result } = renderHook(() => useBlueskyArchiveImport({ runtime: harness.runtime, - reminders: NO_SCHEDULED_REMINDERS, }), ); @@ -120,7 +118,6 @@ describe("importing a Cyd Bluesky archive from the menu", () => { const { result } = renderHook(() => useBlueskyArchiveImport({ runtime: harness.runtime, - reminders: NO_SCHEDULED_REMINDERS, }), ); @@ -147,7 +144,6 @@ describe("importing a Cyd Bluesky archive from the menu", () => { const { result } = renderHook(() => useBlueskyArchiveImport({ runtime: harness.runtime, - reminders: NO_SCHEDULED_REMINDERS, }), ); diff --git a/hooks/use-bluesky-archive-import.ts b/hooks/use-bluesky-archive-import.ts index 338a945..8d3894b 100644 --- a/hooks/use-bluesky-archive-import.ts +++ b/hooks/use-bluesky-archive-import.ts @@ -15,18 +15,11 @@ import { commitBlueskyArchiveMerge, createBlueskyArchiveMergeEnvironment, previewBlueskyArchiveMerge, - previewDuplicateReconciliation, - reconcileDuplicateBlueskyAccounts, totalMergeChanges, type BlueskyArchiveMergeEnvironment, type BlueskyArchiveMergePreview, type BlueskyArchiveMergeResult, - type DuplicateReconciliationPreview, } from "@/services/archive-merge"; -import { - NO_SCHEDULED_REMINDERS, - type ScheduledReminderSync, -} from "@/services/scheduled-reminder-sync"; import { createBlueskyArchiveRestoreEnvironment, restoreBlueskyArchiveAccount, @@ -50,9 +43,8 @@ import { emitLocalAccountsChanged } from "@/services/account-events"; * against the manifest before it lands in staging. * * The person is asked before anything irreversible: to confirm an unusually - * large archive, to look at records a merge would bring back, and to choose - * which Bluesky local account survives when this installation holds one - * identity twice. Cancelling at any of those points takes the staging with it. + * large archive, and to agree to what a merge would add. Cancelling at either + * point takes the staging with it. */ export type BlueskyArchiveImportState = @@ -65,11 +57,6 @@ export type BlueskyArchiveImportState = cancellable: boolean; } | { status: "needs-confirmation"; message: string } - | { - status: "reconciling"; - message: string; - preview: DuplicateReconciliationPreview; - } | { status: "reviewing"; preview: BlueskyArchiveMergePreview; @@ -141,27 +128,6 @@ function messageFor(error: unknown): string { : "Cyd could not import that archive."; } -/** - * Tell the server which Bluesky local account its reminders belong to now. - * - * A reconciliation is finished either way: reminders are a convenience, and an - * offline phone must not be told its accounts failed to merge. The worst case - * is a reminder that opens an account which now holds more than it did. - */ -async function syncReminders( - reminders: ScheduledReminderSync, - reconciled: { survivingUuid: string; removedUuids: string[] }, -): Promise { - try { - for (const uuid of reconciled.removedUuids) { - await reminders.retire(uuid); - } - await reminders.resync(reconciled.survivingUuid); - } catch (error) { - console.warn("[archive-import] could not update reminders", error); - } -} - function plural(count: number, noun: string): string { return `${count.toLocaleString()} ${noun}${count === 1 ? "" : "s"}`; } @@ -209,10 +175,9 @@ function describeMergeResult(result: BlueskyArchiveMergeResult): string[] { export function useBlueskyArchiveImport( options: { runtime?: BlueskyArchiveImportRuntime; - reminders?: ScheduledReminderSync; } = {}, ) { - const { runtime, reminders } = options; + const { runtime } = options; const [state, setState] = useState({ status: "idle", }); @@ -361,28 +326,14 @@ export function useBlueskyArchiveImport( await runRestore(prepared, ports.restore, generation); return; } - if (destination.kind === "merge") { - await openMergePreview( - prepared, - ports.merge, - destination.account, - generation, - ); - return; - } - - const reconciliation = await previewDuplicateReconciliation( + await openMergePreview( + prepared, ports.merge, - { did: destination.did, accounts: identities }, + destination.account, + generation, ); - settle(generation, { - status: "reconciling", - message: - "This device has more than one Bluesky account for the identity in this archive. Choose which one to keep before importing.", - preview: reconciliation, - }); }, - [openMergePreview, runRestore, settle], + [openMergePreview, runRestore], ); const run = useCallback( @@ -539,57 +490,6 @@ export function useBlueskyArchiveImport( } }, [discardStaging, importRuntime, settle, state]); - /** - * Keep one of the duplicate Bluesky local accounts, then carry on importing. - * - * The reconciliation runs first because the import has nowhere to land until - * the identity is held once (ADR 0011). - */ - const keepAccount = useCallback( - async (choice: { - survivingUuid: string; - settingsFromUuid: string; - }): Promise => { - const session = sessionRef.current; - if (state.status !== "reconciling" || !session?.prepared) { - return; - } - const { prepared } = session; - const { merge } = importRuntime(); - const generation = generationRef.current; - try { - settle(generation, { - status: "working", - message: "Merging the duplicate accounts…", - fraction: null, - cancellable: false, - }); - const reconciled = await reconcileDuplicateBlueskyAccounts(merge, { - did: state.preview.did, - accounts: await merge.listLocalAccountIdentities(), - survivingUuid: choice.survivingUuid, - settingsFromUuid: choice.settingsFromUuid, - }); - emitLocalAccountsChanged(); - await syncReminders(reminders ?? NO_SCHEDULED_REMINDERS, reconciled); - - const survivor = (await merge.listLocalAccountIdentities()).find( - (account) => account.uuid === choice.survivingUuid, - ); - if (!survivor) { - throw new Error( - "Cyd could not find the Bluesky account it just kept.", - ); - } - await openMergePreview(prepared, merge, survivor, generation); - } catch (error) { - discardStaging(); - settle(generation, { status: "failed", message: messageFor(error) }); - } - }, - [discardStaging, importRuntime, openMergePreview, reminders, settle, state], - ); - /** * Walk away: nothing has been written, and nothing stays staged. * @@ -614,7 +514,6 @@ export function useBlueskyArchiveImport( start, confirmLargeArchive, confirmMerge, - keepAccount, cancel, dismiss, }; diff --git a/services/archive-merge/__tests__/destination.test.ts b/services/archive-merge/__tests__/destination.test.ts index 448f1f2..1d75ba3 100644 --- a/services/archive-merge/__tests__/destination.test.ts +++ b/services/archive-merge/__tests__/destination.test.ts @@ -45,20 +45,18 @@ describe("choosing where a Cyd Bluesky archive is committed", () => { expect(destination).toEqual({ kind: "restore" }); }); - it("asks for reconciliation when duplicate local accounts hold the DID", () => { - const first = identity("uuid-a", "did:plc:archive"); - const second = identity("uuid-b", "did:plc:archive"); - - const destination = chooseBlueskyArchiveImportDestination("did:plc:archive", [ - first, - identity("uuid-c", "did:plc:someone-else"), - second, - ]); - - expect(destination).toEqual({ - kind: "reconcile", - did: "did:plc:archive", - accounts: [first, second], - }); + /** + * `bsky_account.did` is unique and has been since the column existed, so no + * database Cyd Mobile built can reach this. If one ever does, an archive has + * no unambiguous destination and there is nothing sensible to pick. + */ + it("refuses rather than guess when two local accounts hold the DID", () => { + expect(() => + chooseBlueskyArchiveImportDestination("did:plc:archive", [ + identity("uuid-a", "did:plc:archive"), + identity("uuid-c", "did:plc:someone-else"), + identity("uuid-b", "did:plc:archive"), + ]), + ).toThrow(/more than one Bluesky account/); }); }); diff --git a/services/archive-merge/__tests__/duplicates.test.ts b/services/archive-merge/__tests__/duplicates.test.ts deleted file mode 100644 index 14374be..0000000 --- a/services/archive-merge/__tests__/duplicates.test.ts +++ /dev/null @@ -1,292 +0,0 @@ -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; -import type { DatabaseSync } from "node:sqlite"; - -import { - runBlueskyArchiveIntake, - type PreparedBlueskyArchive, -} from "@/services/archive-import"; -import { restoreBlueskyArchiveAccount } from "@/services/archive-restore"; -import { createMemoryByteReader } from "@/testUtils/archiveFixtures"; -import { - createDiskBlueskyArchiveIntakeEnvironment, - createNodeBlueskyArchiveRestoreEnvironment, - type NodeRestoreEnvironment, -} from "@/testUtils/archiveEnvironments"; - -import { - findDuplicateBlueskyIdentities, - previewDuplicateReconciliation, - reconcileDuplicateBlueskyAccounts, -} from "../duplicates"; - -/** - * Collapsing a Bluesky identity this installation holds twice (ADR 0011). - * - * Duplicates are the state an archive import cannot route around: with two - * Bluesky local accounts for one DID there is no unambiguous destination, so - * the person is shown both and says which one survives and whose settings it - * keeps. What must come out the other side is one account, holding the union - * of both, under an identifier they chose. - */ - -const FIXTURE_DIRECTORY = path.join( - __dirname, - "../../../testUtils/fixtures/bluesky-archive", -); -const ACCOUNT_DID = "did:plc:yn45xekh5kqrat27w6rmafcg"; -const ORPHAN_URI = "at://did:plc:yn45xekh5kqrat27w6rmafcg/app.bsky.feed.post/only-on-the-other-one"; - -jest.setTimeout(120_000); - -type Harness = { - root: string; - environment: NodeRestoreEnvironment; - survivor: { uuid: string; id: number }; - duplicate: { uuid: string; id: number }; -}; - -async function stage(root: string): Promise { - const outcome = await runBlueskyArchiveIntake( - createDiskBlueskyArchiveIntakeEnvironment(path.join(root, "intake")), - { - intakeId: "intake-1", - sourceUri: "file:///fixtures/complete.cyd", - openReader: async () => - createMemoryByteReader( - new Uint8Array( - fs.readFileSync(path.join(FIXTURE_DIRECTORY, "complete.cyd")), - ), - ), - }, - ); - if (outcome.status !== "prepared") { - throw new Error(`intake did not prepare: ${outcome.status}`); - } - return outcome; -} - -/** - * One identity, two Bluesky local accounts: a restored one, and a second the - * person built up separately, holding a post and a file the first never saw. - */ -async function twoAccountsForOneIdentity(): Promise { - const root = fs.mkdtempSync(path.join(os.tmpdir(), "cyd-duplicates-")); - const environment = createNodeBlueskyArchiveRestoreEnvironment({ - root: path.join(root, "app"), - }); - const prepared = await stage(root); - const restored = await restoreBlueskyArchiveAccount(environment, { - archive: { - intakeId: prepared.intakeId, - stagingRoot: prepared.stagingRoot, - }, - }); - - // Mobile's own schema will not hold two accounts for one DID, so the state - // this reconciliation exists for has to be built the way it would arrive: - // from a database that predates the rule. - environment.mainDatabase.exec("DROP INDEX IF EXISTS idx_bsky_account_did;"); - - const duplicate = await environment.createLocalAccount({ - uuid: "11111111-2222-4333-8444-555555555555", - did: ACCOUNT_DID, - handle: ACCOUNT_DID, - displayName: "The other copy", - avatarUrl: null, - settings: { settingSavePosts: 0, settingDeleteLikes: 1 }, - }); - - const database = environment.openRestoredAccountDatabase(duplicate.accountUuid); - const stored = await environment.storeAccountMedia( - duplicate.accountUuid, - "sha256-onlyontheotherone", - async (push) => push(new Uint8Array([1, 2, 3, 4])), - ); - database - .prepare( - `INSERT INTO profile (did, handle, displayName, avatarUrl, savedAt, updatedAt) - VALUES (?, ?, ?, ?, ?, ?);`, - ) - .run(ACCOUNT_DID, "glittertop-cyd.bsky.social", null, null, 10, 10); - database - .prepare( - `INSERT INTO media_asset ( - contentCid, mediaType, mimeType, byteLength, localPath, sourceUrl, - downloadState, attemptCount, downloadedAt - ) VALUES (?, 'image', 'image/jpeg', 4, ?, 'https://cdn.example/one.jpg', 'complete', 0, 10);`, - ) - .run("bafy-only-on-the-other-one", stored.uri); - database - .prepare( - `INSERT INTO post ( - uri, cid, authorDid, text, isReply, isQuote, isRepost, - likeCount, repostCount, replyCount, quoteCount, - viewerLiked, viewerReposted, viewerBookmarked, - createdAt, savedAt, preserve - ) VALUES (?, 'cid-other', ?, 'only on the other copy', 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, '2026-02-02T00:00:00.000Z', 10, 1);`, - ) - .run(ORPHAN_URI, ACCOUNT_DID); - database.close(); - - return { - root, - environment, - survivor: { uuid: restored.accountUuid, id: restored.accountId }, - duplicate: { uuid: duplicate.accountUuid, id: duplicate.accountId }, - }; -} - -function accountRow( - main: DatabaseSync, - accountUuid: string, -): Record | undefined { - return main - .prepare( - `SELECT b.* FROM bsky_account b - INNER JOIN account a ON a.bskyAccountID = b.id - WHERE a.uuid = ?;`, - ) - .get(accountUuid) ?? undefined; -} - -describe("reconciling a Bluesky identity held by two local accounts", () => { - let harness: Harness; - - beforeAll(async () => { - harness = await twoAccountsForOneIdentity(); - }); - - afterAll(() => { - harness.environment.close(); - fs.rmSync(harness.root, { recursive: true, force: true }); - }); - - it("flags the duplicates rather than picking one", async () => { - const duplicates = findDuplicateBlueskyIdentities( - await harness.environment.listLocalAccountIdentities(), - ); - - expect(duplicates).toHaveLength(1); - expect(duplicates[0].did).toBe(ACCOUNT_DID); - expect(duplicates[0].accounts.map((account) => account.uuid).sort()).toEqual( - [harness.duplicate.uuid, harness.survivor.uuid].sort(), - ); - }); - - it("previews what each local account holds and is set to do", async () => { - const preview = await previewDuplicateReconciliation(harness.environment, { - did: ACCOUNT_DID, - accounts: await harness.environment.listLocalAccountIdentities(), - }); - - const other = preview.accounts.find( - (account) => account.uuid === harness.duplicate.uuid, - ); - expect(other).toMatchObject({ - uuid: harness.duplicate.uuid, - counts: { posts: 1, profiles: 1 }, - settings: { settingSavePosts: 0, settingDeleteLikes: 1 }, - }); - // Keeping the restored account brings the other one's lone post with it, - // and says which post that is before anybody commits to it. - const survivor = preview.accounts.find( - (account) => account.uuid === harness.survivor.uuid, - ); - expect(survivor?.gains.records).toEqual([ - { - category: "posts", - id: ORPHAN_URI, - text: "only on the other copy", - createdAt: "2026-02-02T00:00:00.000Z", - }, - ]); - expect( - preview.accounts.find( - (account) => account.uuid === harness.survivor.uuid, - )?.counts.posts, - ).toBeGreaterThan(1); - }); - - it("keeps the identifier and settings the person chose, and unions the rest", async () => { - const main = harness.environment.mainDatabase; - const before = accountRow(main, harness.survivor.uuid); - - const result = await reconcileDuplicateBlueskyAccounts(harness.environment, { - did: ACCOUNT_DID, - accounts: await harness.environment.listLocalAccountIdentities(), - survivingUuid: harness.survivor.uuid, - settingsFromUuid: harness.duplicate.uuid, - }); - - expect(result.survivingUuid).toBe(harness.survivor.uuid); - expect(result.removedUuids).toEqual([harness.duplicate.uuid]); - - const database = harness.environment.openRestoredAccountDatabase( - harness.survivor.uuid, - ); - const adopted = database - .prepare("SELECT preserve, text FROM post WHERE uri = ?;") - .get(ORPHAN_URI) as { preserve: number; text: string } | undefined; - const asset = database - .prepare("SELECT localPath FROM media_asset WHERE contentCid = ?;") - .get("bafy-only-on-the-other-one") as { localPath: string } | undefined; - database.close(); - - expect(adopted).toMatchObject({ - text: "only on the other copy", - preserve: 1, - }); - // The file moved with the record, into the surviving account's own storage. - expect(asset?.localPath).toContain( - `bluesky-${harness.survivor.uuid}`, - ); - expect(fs.existsSync(asset!.localPath.replace("file://", ""))).toBe(true); - - // The settings came from the account whose settings were chosen; the - // surviving account's own identifier did not move. - const after = accountRow(main, harness.survivor.uuid); - expect(after).toMatchObject({ - settingSavePosts: 0, - settingDeleteLikes: 1, - did: ACCOUNT_DID, - handle: before?.handle, - }); - }); - - it("leaves one Bluesky local account for the identity, and nothing to reconcile", async () => { - const identities = await harness.environment.listLocalAccountIdentities(); - - expect( - identities.filter((account) => account.did === ACCOUNT_DID), - ).toHaveLength(1); - expect(findDuplicateBlueskyIdentities(identities)).toEqual([]); - expect( - fs.existsSync(harness.environment.accountDirectory(harness.duplicate.uuid)), - ).toBe(false); - - // And the rule is back on, so the installation cannot drift into holding - // the identity twice again. - expect(() => - harness.environment.mainDatabase - .prepare( - `INSERT INTO bsky_account (createdAt, updatedAt, accessedAt, handle, postsCount, did) - VALUES (1, 1, 1, 'another.bsky.social', 0, ?);`, - ) - .run(ACCOUNT_DID), - ).toThrow(/UNIQUE/i); - }); - - it("refuses to keep an account that is not one of the duplicates", async () => { - await expect( - reconcileDuplicateBlueskyAccounts(harness.environment, { - did: ACCOUNT_DID, - accounts: await harness.environment.listLocalAccountIdentities(), - survivingUuid: "99999999-9999-4999-8999-999999999999", - settingsFromUuid: harness.survivor.uuid, - }), - ).rejects.toThrow(/account/i); - }); -}); diff --git a/services/archive-merge/destination.ts b/services/archive-merge/destination.ts index b06f4cc..a86378d 100644 --- a/services/archive-merge/destination.ts +++ b/services/archive-merge/destination.ts @@ -1,5 +1,7 @@ import type { LocalAccountIdentity } from "@/services/archive-restore"; +import { BlueskyArchiveMergeError } from "./errors"; + /** * Where a picked Cyd Bluesky archive is committed. * @@ -14,12 +16,7 @@ export type BlueskyArchiveImportDestination = /** No Bluesky local account for this identity: restore a new one (#96). */ | { kind: "restore" } /** Exactly one holds it: the archive is a recovery union into that account. */ - | { kind: "merge"; account: LocalAccountIdentity } - /** - * Several hold it, so there is no unambiguous destination. The duplicates - * are reconciled into one surviving Bluesky local account first (ADR 0011). - */ - | { kind: "reconcile"; did: string; accounts: LocalAccountIdentity[] }; + | { kind: "merge"; account: LocalAccountIdentity }; export function chooseBlueskyArchiveImportDestination( archiveDid: string, @@ -30,8 +27,15 @@ export function chooseBlueskyArchiveImportDestination( if (holders.length === 0) { return { kind: "restore" }; } - if (holders.length === 1) { - return { kind: "merge", account: holders[0] }; + if (holders.length > 1) { + // `bsky_account.did` is unique and has been since the column existed, so + // this cannot happen to a database Cyd Mobile built. If one ever turns up + // holding an identity twice, the archive has no unambiguous destination + // and saying so beats merging into whichever came back first. + throw new BlueskyArchiveMergeError( + "duplicate-identity", + "This device has more than one Bluesky account for the identity in this archive, so Cyd cannot tell where to import it.", + ); } - return { kind: "reconcile", did: archiveDid, accounts: holders }; + return { kind: "merge", account: holders[0] }; } diff --git a/services/archive-merge/duplicates.ts b/services/archive-merge/duplicates.ts deleted file mode 100644 index 5c230ae..0000000 --- a/services/archive-merge/duplicates.ts +++ /dev/null @@ -1,364 +0,0 @@ -import type { LocalAccountIdentity } from "@/services/archive-restore"; - -import { readExistingAccountRows } from "./account-rows"; -import { BlueskyArchiveMergeError } from "./errors"; -import { - planBlueskyArchiveMerge, - type RestorationPreview, -} from "./merge-plan"; -import { writeMergedAccountRows } from "./merge-writer"; -import type { - BlueskyArchiveMergeEnvironment, - ReconcilableAccountSettings, -} from "./ports"; -import type { ExistingAccountRows } from "./rows"; - -/** - * Collapsing a Bluesky identity this installation holds more than once. - * - * A migration, a restore that went sideways, or two people sharing a phone can - * leave one DID with several Bluesky local accounts, and then an archive - * import has no unambiguous destination. Cyd does not pick one: it shows what - * each account holds and what each is set to do, and the person says which - * local-account UUID survives and whose settings it keeps (ADR 0011). - * - * What happens afterwards is the same union an archive import performs — the - * surviving account ends up holding everything all of them held — followed by - * the removal of the others, which is what leaves one Bluesky local account - * per identity for imports to aim at. - */ - -export type DuplicateBlueskyIdentity = { - did: string; - accounts: LocalAccountIdentity[]; -}; - -export type DuplicateAccountCounts = { - posts: number; - bookmarks: number; - follows: number; - chats: number; - messages: number; - profiles: number; - media: number; -}; - -export type DuplicateAccountPreview = { - uuid: string; - handle: string | null; - counts: DuplicateAccountCounts; - settings: ReconcilableAccountSettings; - /** - * What this account would take on from the others if it were the one kept. - * - * An example is named as well as counted, which the merge preview does not - * do. The question there is what an archive would add; the question here is - * which of two Bluesky local accounts is which, and a record one holds and - * the other does not is the thing somebody recognises. - */ - gains: { - total: number; - records: RestorationPreview[]; - }; -}; - -export type DuplicateReconciliationPreview = { - did: string; - accounts: DuplicateAccountPreview[]; -}; - -export type DuplicateReconciliationChoice = { - did: string; - /** Every Bluesky local account this installation has, as routing saw them. */ - accounts: LocalAccountIdentity[]; - /** The local-account UUID the person chose to keep. */ - survivingUuid: string; - /** Whose Bluesky account settings and schedule the survivor keeps. */ - settingsFromUuid: string; -}; - -export type DuplicateReconciliationResult = { - did: string; - survivingUuid: string; - removedUuids: string[]; -}; - -/** Every DID this installation holds more than one Bluesky local account for. */ -export function findDuplicateBlueskyIdentities( - accounts: LocalAccountIdentity[], -): DuplicateBlueskyIdentity[] { - const byDid = new Map(); - for (const account of accounts) { - if (account.did === null) { - // An account with no DID is not a duplicate of anything: nothing can say - // which Bluesky identity it is. - continue; - } - byDid.set(account.did, [...(byDid.get(account.did) ?? []), account]); - } - - return [...byDid.entries()] - .filter(([, holders]) => holders.length > 1) - .map(([did, holders]) => ({ did, accounts: holders })); -} - -/** - * What each of the duplicates holds, so somebody can tell them apart. - * - * Counts rather than a diff: the union means nothing is lost whichever they - * keep, so the question in front of them is which account they recognise as - * theirs and which settings they want to carry on with. - */ -export async function previewDuplicateReconciliation( - environment: BlueskyArchiveMergeEnvironment, - identity: DuplicateBlueskyIdentity, -): Promise { - const holders = holdersOf(identity.did, identity.accounts); - const rows = new Map(); - for (const account of holders) { - rows.set(account.uuid, await readAccount(environment, account.uuid)); - } - - const accounts: DuplicateAccountPreview[] = []; - for (const account of holders) { - const own = rows.get(account.uuid); - if (!own) { - continue; - } - // Planning the union in memory is how the preview and the reconciliation - // stay the same answer: one set of rules, asked a question rather than - // told to write. - const gains = holders - .filter((other) => other.uuid !== account.uuid) - .map((other) => rows.get(other.uuid)) - .filter((other): other is ExistingAccountRows => other !== undefined) - .map( - (other) => - planBlueskyArchiveMerge(own, other, identity.did).summary - .restorations, - ); - - accounts.push({ - uuid: account.uuid, - handle: account.handle, - counts: countRows(own), - settings: await environment.readAccountSettings(account.uuid), - gains: { - total: gains.reduce((sum, restoration) => sum + restoration.total, 0), - records: gains.flatMap((restoration) => restoration.records), - }, - }); - } - - return { did: identity.did, accounts }; -} - -/** - * Carry out the choice: one surviving Bluesky local account, holding the union. - * - * Each duplicate is merged in whole — its rows through the same union rules an - * archive import uses, its media files copied into the survivor's own storage - * so the surviving rows point at files that will still be there — and then - * removed. Nothing is deleted before its data has landed, so a reconciliation - * that fails part way leaves the account it was reading from intact. - */ -export async function reconcileDuplicateBlueskyAccounts( - environment: BlueskyArchiveMergeEnvironment, - choice: DuplicateReconciliationChoice, -): Promise { - const holders = holdersOf(choice.did, choice.accounts); - requireHolder(holders, choice.survivingUuid, "keep"); - requireHolder(holders, choice.settingsFromUuid, "take settings from"); - - const doomed = holders.filter( - (account) => account.uuid !== choice.survivingUuid, - ); - const settings = await environment.readAccountSettings( - choice.settingsFromUuid, - ); - - for (const account of doomed) { - const incoming = await adoptMedia( - environment, - account.uuid, - choice.survivingUuid, - await readAccount(environment, account.uuid), - ); - - const survivor = await environment.openAccountDatabase( - choice.survivingUuid, - ); - try { - const plan = planBlueskyArchiveMerge( - await readExistingAccountRows(survivor), - incoming, - choice.did, - ); - await survivor.transaction(async () => { - await writeMergedAccountRows(survivor, plan); - }); - } finally { - await survivor.close(); - } - } - - // Settings are applied before the losing accounts go, so a failure here is - // recoverable: the accounts are still there to choose between. - await environment.applyAccountSettings(choice.survivingUuid, settings); - - for (const account of doomed) { - await environment.removeLocalAccount(account.uuid); - } - - // With one Bluesky local account left for the identity, the rule that there - // can only be one goes back on, so a later archive import has somewhere - // unambiguous to land (ADR 0011). Putting the index back does nothing on a - // database that never lost it, so the accounts are counted rather than - // trusted: an identity still held twice here means a removal did not take, - // and saying so beats leaving an import with nowhere to go. - await environment.enforceOneAccountPerDid(); - await requireSingleHolder(environment, choice.did); - - return { - did: choice.did, - survivingUuid: choice.survivingUuid, - removedUuids: doomed.map((account) => account.uuid), - }; -} - -/** Check the rule the reconciliation exists to restore actually holds now. */ -async function requireSingleHolder( - environment: BlueskyArchiveMergeEnvironment, - did: string, -): Promise { - const duplicates = findDuplicateBlueskyIdentities( - await environment.listLocalAccountIdentities(), - ); - if (duplicates.some((duplicate) => duplicate.did === did)) { - throw new BlueskyArchiveMergeError( - "duplicate-identity", - "Cyd merged the accounts but could not remove the duplicates, so this device still has more than one Bluesky account for that identity.", - ); - } -} - -function holdersOf( - did: string, - accounts: LocalAccountIdentity[], -): LocalAccountIdentity[] { - const holders = accounts.filter((account) => account.did === did); - if (holders.length < 2) { - throw new BlueskyArchiveMergeError( - "duplicate-identity", - "This device no longer has more than one Bluesky account for that identity.", - ); - } - return holders; -} - -function requireHolder( - holders: LocalAccountIdentity[], - uuid: string, - intent: string, -): void { - if (!holders.some((account) => account.uuid === uuid)) { - throw new BlueskyArchiveMergeError( - "unknown-account", - `The Bluesky account Cyd was asked to ${intent} is not one of the accounts being reconciled.`, - ); - } -} - -async function readAccount( - environment: BlueskyArchiveMergeEnvironment, - accountUuid: string, -): Promise { - const database = await environment.openAccountDatabase(accountUuid); - try { - return await readExistingAccountRows(database); - } finally { - await database.close(); - } -} - -/** - * Bring a duplicate's media files across before its rows point at them. - * - * A row is only worth anything if the file it names is still readable after - * the account it belonged to is gone. A file that has already vanished leaves - * the row as a failed download with its source URL, which is what Cyd would - * have held if the download had never succeeded. - */ -async function adoptMedia( - environment: BlueskyArchiveMergeEnvironment, - sourceAccountUuid: string, - targetAccountUuid: string, - rows: ExistingAccountRows, -): Promise { - const moved = new Map(); - - const relocate = async (localPath: string | null): Promise => { - if (localPath === null) { - return null; - } - if (!moved.has(localPath)) { - const stored = await environment.adoptAccountMedia( - sourceAccountUuid, - targetAccountUuid, - localPath, - ); - moved.set(localPath, stored?.uri ?? null); - } - return moved.get(localPath) ?? null; - }; - - const mediaAssets: ExistingAccountRows["mediaAssets"] = []; - for (const asset of rows.mediaAssets) { - const localPath = await relocate(asset.localPath); - mediaAssets.push( - localPath === null && asset.localPath !== null - ? { - ...asset, - localPath: null, - downloadState: "failed", - lastError: "The copy of this file went missing when Cyd merged two accounts for the same Bluesky identity.", - downloadedAt: null, - } - : { ...asset, localPath }, - ); - } - - const postExternals: ExistingAccountRows["postExternals"] = []; - for (const external of rows.postExternals) { - postExternals.push({ - ...external, - thumbLocalPath: await relocate(external.thumbLocalPath), - }); - } - - const profiles: ExistingAccountRows["profiles"] = []; - for (const profile of rows.profiles) { - // Avatars are stored as URLs, and a restored one points into the account's - // own storage, so it has to move with everything else. - const isLocal = profile.avatarUrl?.startsWith("file://") === true; - profiles.push( - isLocal - ? { ...profile, avatarUrl: await relocate(profile.avatarUrl) } - : profile, - ); - } - - return { ...rows, mediaAssets, postExternals, profiles }; -} - -function countRows(rows: ExistingAccountRows): DuplicateAccountCounts { - return { - posts: rows.posts.length, - bookmarks: rows.bookmarks.length, - follows: rows.follows.length, - chats: rows.conversations.length, - messages: rows.messages.length, - profiles: rows.profiles.length, - media: rows.mediaAssets.length, - }; -} diff --git a/services/archive-merge/environment.ts b/services/archive-merge/environment.ts index 75849da..faac165 100644 --- a/services/archive-merge/environment.ts +++ b/services/archive-merge/environment.ts @@ -10,17 +10,13 @@ import { acquireAccountDatabase, releaseAccountDatabase, } from "@/database/account-db/shared-handles"; -import { deleteAccount, listAccounts } from "@/database/accounts"; -import { getDatabase } from "@/database"; +import { listAccounts } from "@/database/accounts"; import { openPreparedArchive } from "@/services/archive-restore/environment"; import type { LocalAccountIdentity } from "@/services/archive-restore"; -import { - RECONCILABLE_SETTING_COLUMNS, - type BlueskyArchiveMergeEnvironment, - type MergeableAccountDatabase, - type ReconcilableAccountSettings, - type ReconcilableSettingColumn, +import type { + BlueskyArchiveMergeEnvironment, + MergeableAccountDatabase, } from "./ports"; /** @@ -122,76 +118,5 @@ export function createBlueskyArchiveMergeEnvironment(): BlueskyArchiveMergeEnvir }, accountMediaUri: mediaUri, - - readAccountSettings: async (accountUuid) => { - const main = await getDatabase(); - const row = await main.getFirstAsync( - `SELECT ${RECONCILABLE_SETTING_COLUMNS.join(", ")} - FROM bsky_account b - INNER JOIN account a ON a.bskyAccountID = b.id - WHERE a.uuid = ?;`, - [accountUuid], - ); - return row ?? {}; - }, - - applyAccountSettings: async (accountUuid, settings) => { - const entries = Object.entries(settings) as [ - ReconcilableSettingColumn, - string | number | null, - ][]; - if (entries.length === 0) { - return; - } - const main = await getDatabase(); - await main.runAsync( - `UPDATE bsky_account - SET ${entries.map(([column]) => `${column} = ?`).join(", ")} - WHERE id = (SELECT bskyAccountID FROM account WHERE uuid = ?);`, - [...entries.map(([, value]) => value), accountUuid], - ); - }, - - adoptAccountMedia: async (_sourceAccountUuid, targetAccountUuid, localPath) => { - const source = new File(localPath); - if (!source.exists) { - return null; - } - const paths = buildAccountPaths("bluesky", targetAccountUuid); - new Directory(paths.mediaDir).create({ - intermediates: true, - idempotent: true, - }); - const destination = new File(mediaUri(targetAccountUuid, source.name)); - if (!destination.exists) { - await source.copy(destination); - } - return { uri: destination.uri, byteLength: destination.size ?? 0 }; - }, - - enforceOneAccountPerDid: async () => { - const main = await getDatabase(); - await main.execAsync( - `CREATE UNIQUE INDEX IF NOT EXISTS idx_bsky_account_did - ON bsky_account(did);`, - ); - }, - - removeLocalAccount: async (accountUuid) => { - const account = (await listAccounts()).find( - (candidate) => candidate.uuid === accountUuid, - ); - if (account) { - // `deleteAccount` takes the Bluesky connection with it, which is the - // right end for an account nobody is keeping. - await deleteAccount(account.id); - } - const directory = new Directory( - buildAccountPaths("bluesky", accountUuid).accountDir, - ); - if (directory.exists) { - directory.delete(); - } - }, }; } diff --git a/services/archive-merge/errors.ts b/services/archive-merge/errors.ts index 46825fa..1ed20f4 100644 --- a/services/archive-merge/errors.ts +++ b/services/archive-merge/errors.ts @@ -3,15 +3,14 @@ * * Intake has proved the package intact (#95) and the shared version 2 adapter * raises what it thinks of the interchange database, so what is left here is - * about destinations: an archive pointed at the wrong Bluesky local account, a - * Bluesky identity this installation holds twice, or a reconciliation asked to - * keep an account that is not one of the duplicates. The messages are written - * for the person holding the phone. + * about destinations: an archive pointed at the wrong Bluesky local account, + * or a database holding one Bluesky identity twice, which Mobile's schema does + * not allow and which therefore has no destination at all. The messages are + * written for the person holding the phone. */ export type BlueskyArchiveMergeErrorCode = | "identity-mismatch" - | "duplicate-identity" - | "unknown-account"; + | "duplicate-identity"; export class BlueskyArchiveMergeError extends Error { readonly code: BlueskyArchiveMergeErrorCode; diff --git a/services/archive-merge/index.ts b/services/archive-merge/index.ts index dd6b52a..296f052 100644 --- a/services/archive-merge/index.ts +++ b/services/archive-merge/index.ts @@ -8,27 +8,13 @@ * identifier collapse into one, and the account's own settings, schedules, * Bluesky connection and local choices are not the archive's business. * - * Three things leave this module: where an archive should go, what merging it - * would do, and how a Bluesky identity this installation holds twice is - * reconciled down to one (ADR 0011). The union rules, the row reader and the - * writer are internal, and the tests reach for them directly. + * Two things leave this module: where an archive should go, and what merging + * it would do. The union rules, the row reader and the writer are internal, + * and the tests reach for them directly. */ export { chooseBlueskyArchiveImportDestination } from "./destination"; export type { BlueskyArchiveImportDestination } from "./destination"; -export { - findDuplicateBlueskyIdentities, - previewDuplicateReconciliation, - reconcileDuplicateBlueskyAccounts, -} from "./duplicates"; -export type { - DuplicateBlueskyIdentity, - DuplicateAccountCounts, - DuplicateAccountPreview, - DuplicateReconciliationChoice, - DuplicateReconciliationPreview, - DuplicateReconciliationResult, -} from "./duplicates"; export { createBlueskyArchiveMergeEnvironment } from "./environment"; export { BlueskyArchiveMergeError } from "./errors"; export type { BlueskyArchiveMergeErrorCode } from "./errors"; @@ -52,12 +38,9 @@ export type { BlueskyArchiveMergeTotals, RestorationPreview, } from "./merge-plan"; -export { RECONCILABLE_SETTING_COLUMNS } from "./ports"; export type { BlueskyArchiveMergeEnvironment, MergeableAccountDatabase, - ReconcilableAccountSettings, - ReconcilableSettingColumn, } from "./ports"; export type { ExistingAccountRows, diff --git a/services/archive-merge/merge-plan.ts b/services/archive-merge/merge-plan.ts index 8df58ae..dde3a32 100644 --- a/services/archive-merge/merge-plan.ts +++ b/services/archive-merge/merge-plan.ts @@ -43,12 +43,11 @@ export type BlueskyArchiveMergeCounts = { /** * One record the account does not hold. * - * The merge preview counts these rather than listing them (ADR 0018): Mobile - * has no Bluesky local deletion, so a missing record is one this account never - * had, and a list of them is nothing somebody can recognise. They are still - * carried, because choosing between two Bluesky local accounts that hold one - * identity is a different question — there, an example of what one holds and - * the other does not is how somebody tells them apart. + * Nothing shows these: the preview counts what it would add rather than naming + * it, because Mobile has no Bluesky local deletion and a missing record is one + * the account never had (ADR 0018). The plan works them out anyway so that + * naming them stays a presentation change rather than new capability, for a + * client — or a later Mobile — where a record can go missing on purpose. */ export type RestorationPreview = { category: "posts" | "bookmarks" | "follows" | "chats" | "messages"; @@ -246,12 +245,11 @@ function sameRow(left: object, right: object): boolean { } /** - * Union two accounts' worth of Bluesky saved data. + * Union an account's Bluesky saved data with an archive's. * - * Both sides are the same shape on purpose: importing a Cyd Bluesky archive - * and collapsing two duplicate Bluesky local accounts (ADR 0011) are the same - * union, so they are the same code and cannot drift into disagreeing about - * what "the same record" means. + * Both sides are the same shape on purpose: what the account holds and what + * the archive carries are compared as the same rows by the same rules, so + * "the same record" cannot come to mean two things. */ export function planBlueskyArchiveMerge( existing: ExistingAccountRows, diff --git a/services/archive-merge/ports.ts b/services/archive-merge/ports.ts index 4c404a2..eee39b5 100644 --- a/services/archive-merge/ports.ts +++ b/services/archive-merge/ports.ts @@ -11,15 +11,11 @@ import type { * * What is missing from this list is the point of it. There is no way from here * to write a Bluesky local account's settings or schedule, to touch a Bluesky - * connection, or to rename an account: a merge into an existing Bluesky local - * account can only add to that account's Bluesky saved data, so "an existing - * identity keeps its UUID, its settings, its schedules and its connection" is - * a property of the interface rather than a promise somebody has to keep. - * - * The exceptions are the two ports duplicate-DID reconciliation needs, which - * is the one moment a person is asked to choose between two local accounts' - * settings (ADR 0011). They are named for that job so they cannot be reached - * for by accident. + * connection, to rename an account or to remove one: a merge into an existing + * Bluesky local account can only add to that account's Bluesky saved data, so + * "an existing identity keeps its UUID, its settings, its schedules and its + * connection" is a property of the interface rather than a promise somebody + * has to keep. */ /** An existing account's database, which a merge reads before it writes. */ @@ -27,41 +23,6 @@ export type MergeableAccountDatabase = RestoredAccountDatabase & { all(sql: string): Promise; }; -/** - * The `bsky_account` columns duplicate-DID reconciliation carries over from - * the account whose settings the person chose to keep. - * - * Schedule columns are here because a surviving Bluesky local account has to - * keep a schedule somebody set. A Bluesky scheduled reminder still only - * prompts a review — carrying it across does not authorize unattended - * deletion, and there is nothing here that could. - */ -export const RECONCILABLE_SETTING_COLUMNS = [ - "settingSavePosts", - "settingSaveLikes", - "settingSaveBookmarks", - "settingSaveChats", - "settingDeletePosts", - "settingDeleteReposts", - "settingDeleteLikes", - "settingDeleteBookmarks", - "settingDeleteChats", - "settingDeleteUnfollowEveryone", - "settingScheduleDeletion", - "settingScheduleDeletionFrequency", - "settingScheduleDeletionDayOfMonth", - "settingScheduleDeletionDayOfWeek", - "settingScheduleDeletionTime", -] as const; - -export type ReconcilableSettingColumn = - (typeof RECONCILABLE_SETTING_COLUMNS)[number]; - -/** One account's settings, as the person would compare them side by side. */ -export type ReconcilableAccountSettings = Partial< - Record ->; - export type BlueskyArchiveMergeEnvironment = { openPreparedArchive(archive: PreparedArchiveLocation): PreparedArchiveStore; @@ -90,46 +51,6 @@ export type BlueskyArchiveMergeEnvironment = { * rows a merge would write without anything being written. */ accountMediaUri(accountUuid: string, fileName: string): string; - - /** What a duplicate Bluesky local account is set to do, for the preview. */ - readAccountSettings( - accountUuid: string, - ): Promise; - - /** Give the surviving account the settings the person picked (ADR 0011). */ - applyAccountSettings( - accountUuid: string, - settings: ReconcilableAccountSettings, - ): Promise; - - /** - * Move a media file from a duplicate Bluesky local account into the one that - * survives, returning where it now lives. Null when the file is gone, which - * makes the record a failed download rather than a failed reconciliation. - */ - adoptAccountMedia( - sourceAccountUuid: string, - targetAccountUuid: string, - localPath: string, - ): Promise; - - /** - * Make one Bluesky local account per DID a rule of the database again. - * - * Mobile has carried a unique index on `bsky_account.did` since its first - * migration, so duplicates can only reach an installation from outside it — - * a database restored from an OS backup, or one that predates the index. - * Putting the rule back is a no-op on a database that still has it, which is - * why reconciliation does not treat it as proof: it checks the accounts - * itself afterwards. - */ - enforceOneAccountPerDid(): Promise; - - /** - * Remove a reconciled-away Bluesky local account, its storage and its - * Bluesky connection, identified the way reconciliation knows it. - */ - removeLocalAccount(accountUuid: string): Promise; }; export type { PreparedArchiveLocation, StoredMediaFile }; diff --git a/services/archive-merge/rows.ts b/services/archive-merge/rows.ts index 2d3c88e..31bfdec 100644 --- a/services/archive-merge/rows.ts +++ b/services/archive-merge/rows.ts @@ -53,9 +53,9 @@ export type ExistingAccountRows = { * A Cyd Bluesky archive's rows, in the shape the account holds them. * * The two columns an archive cannot know get the value a newly saved record - * would have, and the union rules carry the account's own values across. It - * is what lets one plan serve both jobs: merging an archive into an account, - * and merging two duplicate accounts into one (ADR 0011). + * would have, and the union rules carry the account's own values across, so an + * archive can never reset a person's own decision to preserve a post or a + * downloader's record of what it has been through. */ export function accountRowsFromArchive( restored: RestoredMobileAccount, diff --git a/services/scheduled-reminder-sync.ts b/services/scheduled-reminder-sync.ts deleted file mode 100644 index a800e65..0000000 --- a/services/scheduled-reminder-sync.ts +++ /dev/null @@ -1,87 +0,0 @@ -import * as Localization from "expo-localization"; - -import { listAccounts } from "@/database/accounts"; -import { getAccountScheduleSettings } from "@/database/schedule-settings"; -import type CydAPIClient from "@/services/cyd-api-client"; -import { - hasNotificationPermission, - registerForPushNotifications, -} from "@/services/push-notifications"; - -/** - * Keeping server-scheduled Bluesky reminders pointed at the right account. - * - * Mobile delivers reminders as push scheduled by Cyd's server, keyed by the - * local-account UUID (ADR 0005). A merge never touches that — the account - * keeps its UUID and its schedule — but reconciling duplicates does: one UUID - * stops existing, and the survivor may come out of it holding a schedule that - * belonged to the other one, which the server has no push token for. - * - * So reconciliation ends by telling the server what is true now. A reminder - * still only prompts somebody to open Cyd and review: nothing here authorizes - * unattended deletion, and there is nothing in the payload that could. - */ -export type ScheduledReminderSync = { - /** Re-send the surviving account's schedule, and the token to deliver it. */ - resync(accountUuid: string): Promise; - /** Stop reminders for a Bluesky local account that no longer exists. */ - retire(accountUuid: string): Promise; -}; - -/** Used when there is no Cyd account, and so no server-scheduled reminders. */ -export const NO_SCHEDULED_REMINDERS: ScheduledReminderSync = { - resync: async () => {}, - retire: async () => {}, -}; - -export function createScheduledReminderSync( - apiClient: CydAPIClient, - isSignedIn: boolean, -): ScheduledReminderSync { - if (!isSignedIn) { - return NO_SCHEDULED_REMINDERS; - } - - return { - resync: async (accountUuid) => { - const account = (await listAccounts()).find( - (candidate) => candidate.uuid === accountUuid, - ); - if (!account) { - return; - } - const settings = await getAccountScheduleSettings(account.id); - - // A schedule the survivor inherited may never have had a push token - // bound to this UUID, and the server cannot deliver a reminder without - // one. Permission is only ever read here, never asked for: an import is - // the wrong moment to put a notifications prompt in front of somebody, - // and a person with no permission granted had no reminders to keep. - if (settings.scheduleDeletion && (await hasNotificationPermission())) { - const token = await registerForPushNotifications(); - if (token.success && token.token && token.platform) { - await apiClient.registerPushToken({ - push_token: token.token, - platform: token.platform, - account_uuid: accountUuid, - account_handle: account.handle, - timezone: Localization.getCalendars()[0]?.timeZone ?? "UTC", - }); - } - } - - await apiClient.updateScheduleSettings({ - account_uuid: accountUuid, - schedule_enabled: settings.scheduleDeletion, - schedule_frequency: settings.scheduleDeletionFrequency, - schedule_day_of_month: settings.scheduleDeletionDayOfMonth, - schedule_day_of_week: settings.scheduleDeletionDayOfWeek, - schedule_time: settings.scheduleDeletionTime, - }); - }, - - retire: async (accountUuid) => { - await apiClient.unregisterPushToken({ account_uuid: accountUuid }); - }, - }; -} diff --git a/testUtils/archiveEnvironments.ts b/testUtils/archiveEnvironments.ts index 18b6818..7417069 100644 --- a/testUtils/archiveEnvironments.ts +++ b/testUtils/archiveEnvironments.ts @@ -34,9 +34,7 @@ import { stagedPayloadPath } from "@/services/archive-import"; import type { BlueskyArchiveMergeEnvironment, MergeableAccountDatabase, - ReconcilableSettingColumn, } from "@/services/archive-merge"; -import { RECONCILABLE_SETTING_COLUMNS } from "@/services/archive-merge"; import type { BlueskyArchiveRestoreEnvironment, DiscardableAccount, @@ -353,60 +351,6 @@ export function createNodeBlueskyArchiveRestoreEnvironment( accountMediaUri, - readAccountSettings: async (accountUuid) => { - const row = mainDatabase - .prepare( - `SELECT ${RECONCILABLE_SETTING_COLUMNS.join(", ")} - FROM bsky_account b - INNER JOIN account a ON a.bskyAccountID = b.id - WHERE a.uuid = ?;`, - ) - .get(accountUuid); - return row ?? {}; - }, - - applyAccountSettings: async (accountUuid, settings) => { - const entries = Object.entries(settings) as [ - ReconcilableSettingColumn, - string | number | null, - ][]; - if (entries.length === 0) { - return; - } - mainDatabase - .prepare( - `UPDATE bsky_account - SET ${entries.map(([column]) => `${column} = ?`).join(", ")} - WHERE id = (SELECT bskyAccountID FROM account WHERE uuid = ?);`, - ) - .run(...entries.map(([, value]) => value as never), accountUuid); - }, - - adoptAccountMedia: async (sourceAccountUuid, targetAccountUuid, localPath) => { - const source = localPath.replace(/^file:\/\//, ""); - if (!fs.existsSync(source)) { - return null; - } - const directory = mediaDirectory(targetAccountUuid); - fs.mkdirSync(directory, { recursive: true }); - const location = path.join(directory, path.basename(source)); - fs.copyFileSync(source, location); - return { - uri: `file://${location}`, - byteLength: fs.statSync(location).size, - }; - }, - - enforceOneAccountPerDid: async () => { - mainDatabase.exec( - `CREATE UNIQUE INDEX IF NOT EXISTS idx_bsky_account_did - ON bsky_account(did);`, - ); - }, - - removeLocalAccount: async (accountUuid: string) => - removeAccount({ accountId: null, accountUuid }), - discardLocalAccount: async (account: DiscardableAccount) => removeAccount(account), From 9195c95ee6656c4233d440ffa9307e5ce550f2d3 Mon Sep 17 00:00:00 2001 From: Micah Lee Date: Sun, 13 Sep 2026 16:27:51 -0700 Subject: [PATCH 8/9] Rename a test whose subject moved The merge preview counts what it would add rather than naming it, so a test called "names them before committing" says something the code no longer does. It asserts the plan, which still works the records out. Co-Authored-By: Claude Opus 5 (1M context) --- services/archive-merge/__tests__/merge.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/archive-merge/__tests__/merge.test.ts b/services/archive-merge/__tests__/merge.test.ts index bc08564..41d9324 100644 --- a/services/archive-merge/__tests__/merge.test.ts +++ b/services/archive-merge/__tests__/merge.test.ts @@ -187,7 +187,7 @@ describe("merging a Cyd Bluesky archive into an account that holds its identity" expect(fs.existsSync(prepared.stagingRoot)).toBe(false); }); - it("brings back records deleted from Cyd, and names them before committing", async () => { + it("brings back records the account no longer holds, counting them first", async () => { const doomed = ( harness.database .prepare( From 02d303c0a6bcef53ad9150324d9ed7234ed5920f Mon Sep 17 00:00:00 2001 From: Micah Lee Date: Sun, 13 Sep 2026 16:31:29 -0700 Subject: [PATCH 9/9] Finish the review's small findings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The import modal had no `onRequestClose`, so the Android back button did nothing during an import while every other modal in the repo handles it. Back now does what the nearest button does: cancels a question, dismisses a report, and is ignored only while a merge is being written, for the same reason there is no button to press there. The modal was also rendered inside the account bar, which returns null on the account screen — so an import started from the accounts list went invisible if somebody opened the account while it ran, and carried on without them. It renders whether or not the bar does. `summary.restorations` lost its last reader when the preview stopped naming records, and was still working out and carrying up to fifty of them on every merge. The plan keeps the added rows it counts from, so ADR 0018's point — that naming them again would be a presentation change over rows already in hand — still holds. The test that asserted the named records now asserts the outcome instead: the three posts that come back are the three that went. Co-Authored-By: Claude Opus 5 (1M context) --- components/BlueskyArchiveImportModal.tsx | 28 +++++- components/CydAccountBar.tsx | 31 +++++-- ...w-a-recovery-merge-before-committing-it.md | 2 +- .../__tests__/merge-plan.test.ts | 15 +--- .../archive-merge/__tests__/merge.test.ts | 20 +++-- services/archive-merge/index.ts | 1 - services/archive-merge/merge-plan.ts | 85 +------------------ 7 files changed, 65 insertions(+), 117 deletions(-) diff --git a/components/BlueskyArchiveImportModal.tsx b/components/BlueskyArchiveImportModal.tsx index a83053b..d09c4aa 100644 --- a/components/BlueskyArchiveImportModal.tsx +++ b/components/BlueskyArchiveImportModal.tsx @@ -71,8 +71,34 @@ export function BlueskyArchiveImportModal({ ); + /** + * What the Android back button does, which is what the nearest button does. + * + * Backing out of a question is cancelling it, and backing out of a report is + * dismissing it. The one state with no button is a merge being written, and + * back does nothing there for the same reason there is nothing to press: a + * commit cannot be called back, and half a merge is not a state to leave + * somebody in. + */ + const handleRequestClose = () => { + if (state.status === "done" || state.status === "failed") { + onDismiss(); + return; + } + if (state.status === "working" && !state.cancellable) { + return; + } + onCancel(); + }; + return ( - + {state.status === "working" ? ( diff --git a/components/CydAccountBar.tsx b/components/CydAccountBar.tsx index 7463f13..6f8e324 100644 --- a/components/CydAccountBar.tsx +++ b/components/CydAccountBar.tsx @@ -122,8 +122,28 @@ export function CydAccountBar({ [archiveImport], ); + /** + * The import, which outlives the bar that starts it. + * + * The bar hides itself on the account screen, and an import started from the + * accounts list is still running when somebody opens the account it just + * restored. Rendering this outside the bar's own visibility is what keeps + * the progress and the questions on screen rather than leaving the import + * running invisibly. + */ + const importModal = ( + void archiveImport.confirmLargeArchive()} + onConfirmMerge={() => void archiveImport.confirmMerge()} + onSignIn={handleSignIn} + onCancel={archiveImport.cancel} + onDismiss={archiveImport.dismiss} + /> + ); + if (state.isLoading || hidden) { - return null; + return importModal; } return ( @@ -306,14 +326,7 @@ export function CydAccountBar({ onClose={handleCloseSignInModal} /> - void archiveImport.confirmLargeArchive()} - onConfirmMerge={() => void archiveImport.confirmMerge()} - onSignIn={handleSignIn} - onCancel={archiveImport.cancel} - onDismiss={archiveImport.dismiss} - /> + {importModal} ); } diff --git a/docs/adr/0018-preview-a-recovery-merge-before-committing-it.md b/docs/adr/0018-preview-a-recovery-merge-before-committing-it.md index 0a5ca6c..b9042fa 100644 --- a/docs/adr/0018-preview-a-recovery-merge-before-committing-it.md +++ b/docs/adr/0018-preview-a-recovery-merge-before-committing-it.md @@ -1,3 +1,3 @@ # Preview a recovery merge before committing it -Cyd Mobile splits a Bluesky archive merge into a preview that reads the prepared Cyd Bluesky archive and works out every row it would write, and a commit that carries that preview out, so nobody imports an archive without being told what it would do. The preview counts what it would add rather than naming it: Mobile has no Bluesky local deletion, so a Bluesky saved record missing from a Bluesky local account is one the account never had rather than one somebody chose to be rid of, and there is nothing for them to recognise in a list. Naming each record becomes worth its screen again if Mobile ever lets somebody remove Bluesky saved data without removing it from Bluesky, and the plan already carries the records, so it is a presentation change rather than a new capability. The commit re-reads the Bluesky local account instead of trusting the preview's copy, so work that ran in between is merged rather than overwritten, and committing the same Cyd Bluesky archive again writes nothing. +Cyd Mobile splits a Bluesky archive merge into a preview that reads the prepared Cyd Bluesky archive and works out every row it would write, and a commit that carries that preview out, so nobody imports an archive without being told what it would do. The preview counts what it would add, a line for each kind of Bluesky saved record in the words Bluesky browse uses for them, rather than naming each record: Mobile has no Bluesky local deletion, so a Bluesky saved record missing from a Bluesky local account is one the account never had rather than one somebody chose to be rid of, and there is nothing for them to recognise in a list. Naming each record becomes worth its screen again if Mobile ever lets somebody remove Bluesky saved data without removing it from Bluesky; the plan already separates the records it would add from the ones it would enrich, so that would be a presentation change over rows it has in hand. The commit re-reads the Bluesky local account instead of trusting the preview's copy, so work that ran in between is merged rather than overwritten, and committing the same Cyd Bluesky archive again writes nothing. diff --git a/services/archive-merge/__tests__/merge-plan.test.ts b/services/archive-merge/__tests__/merge-plan.test.ts index 90ee029..546da7e 100644 --- a/services/archive-merge/__tests__/merge-plan.test.ts +++ b/services/archive-merge/__tests__/merge-plan.test.ts @@ -92,7 +92,7 @@ function incoming( } describe("planning a Cyd Bluesky archive merge", () => { - it("adds a record the account no longer holds, and previews it as a restoration", () => { + it("adds a record the account no longer holds, and counts it", () => { const plan = planBlueskyArchiveMerge( existing(), incoming({ posts: [archived(post({ text: "a post deleted from Cyd" }))] }), @@ -106,15 +106,7 @@ describe("planning a Cyd Bluesky archive merge", () => { preserve: 0, }); expect(plan.summary.posts).toEqual({ added: 1, updated: 0, unchanged: 0 }); - expect(plan.summary.restorations.total).toBe(1); - expect(plan.summary.restorations.records).toEqual([ - { - category: "posts", - id: "at://did:plc:archive/app.bsky.feed.post/one", - text: "a post deleted from Cyd", - createdAt: "2026-01-01T00:00:00.000Z", - }, - ]); + expect(plan.summary.addedRecords.posts).toBe(1); }); it("writes nothing when the archive holds what the account already holds", () => { @@ -126,7 +118,6 @@ describe("planning a Cyd Bluesky archive merge", () => { expect(plan.posts).toEqual([]); expect(plan.summary.posts).toEqual({ added: 0, updated: 0, unchanged: 1 }); - expect(plan.summary.restorations.total).toBe(0); }); it("does not let a quieter archive blank out what the account knows", () => { const plan = planBlueskyArchiveMerge( @@ -270,7 +261,6 @@ describe("planning a Cyd Bluesky archive merge", () => { expect(plan.posts).toEqual([]); expect(plan.summary.posts).toEqual({ added: 0, updated: 0, unchanged: 0 }); - expect(plan.summary.restorations.total).toBe(0); }); it("upgrades a failed download when the archive brought the file", () => { @@ -448,7 +438,6 @@ describe("adding a merge summary up", () => { chats: 0, messages: 0, }, - restorations: { total: 0, records: [] }, ...overrides, }); diff --git a/services/archive-merge/__tests__/merge.test.ts b/services/archive-merge/__tests__/merge.test.ts index 41d9324..0026a98 100644 --- a/services/archive-merge/__tests__/merge.test.ts +++ b/services/archive-merge/__tests__/merge.test.ts @@ -166,7 +166,6 @@ describe("merging a Cyd Bluesky archive into an account that holds its identity" const { preview, result } = await mergeFixture(harness, "intake-again"); - expect(preview.summary.restorations.total).toBe(0); expect(preview.summary.posts).toEqual({ added: 0, updated: 0, @@ -212,7 +211,6 @@ describe("merging a Cyd Bluesky archive into an account that holds its identity" account: identity(harness), }); - expect(preview.summary.restorations.total).toBe(doomed.length); // What the preview says out loud: three posts, and nothing else. expect(preview.summary.addedRecords).toMatchObject({ posts: doomed.length, @@ -220,17 +218,23 @@ describe("merging a Cyd Bluesky archive into an account that holds its identity" likes: 0, messages: 0, }); - expect( - preview.summary.restorations.records - .map((record) => record.id) - .sort(), - ).toEqual([...doomed].sort()); - // Nothing is written until the restorations have been shown. + // Nothing is written until somebody has agreed to the preview. expect(browseCount(harness.database, "posts")).toBe(before - doomed.length); await commitBlueskyArchiveMerge(harness.environment, preview); expect(browseCount(harness.database, "posts")).toBe(before); + // The three that came back are the three that went, not three of + // something else that happens to add up. + expect( + ( + harness.database + .prepare( + `SELECT uri FROM post WHERE uri IN (${doomed.map(() => "?").join(", ")}) ORDER BY uri;`, + ) + .all(...doomed) as { uri: string }[] + ).map((row) => row.uri), + ).toEqual([...doomed].sort()); }); it("keeps the account's own identifier, settings and schedule", async () => { diff --git a/services/archive-merge/index.ts b/services/archive-merge/index.ts index 296f052..ae546c2 100644 --- a/services/archive-merge/index.ts +++ b/services/archive-merge/index.ts @@ -36,7 +36,6 @@ export type { BlueskyArchiveMergePlan, BlueskyArchiveMergeSummary, BlueskyArchiveMergeTotals, - RestorationPreview, } from "./merge-plan"; export type { BlueskyArchiveMergeEnvironment, diff --git a/services/archive-merge/merge-plan.ts b/services/archive-merge/merge-plan.ts index dde3a32..ebedb63 100644 --- a/services/archive-merge/merge-plan.ts +++ b/services/archive-merge/merge-plan.ts @@ -40,25 +40,6 @@ export type BlueskyArchiveMergeCounts = { unchanged: number; }; -/** - * One record the account does not hold. - * - * Nothing shows these: the preview counts what it would add rather than naming - * it, because Mobile has no Bluesky local deletion and a missing record is one - * the account never had (ADR 0018). The plan works them out anyway so that - * naming them stays a presentation change rather than new capability, for a - * client — or a later Mobile — where a record can go missing on purpose. - */ -export type RestorationPreview = { - category: "posts" | "bookmarks" | "follows" | "chats" | "messages"; - id: string; - text: string | null; - createdAt: string | null; -}; - -/** How many records a plan names before it only counts them. */ -const MAX_LISTED_RESTORATIONS = 50; - /** * How many of each kind of record a merge would add, named the way Browse * names them. @@ -91,11 +72,6 @@ export type BlueskyArchiveMergeSummary = { mediaAssets: BlueskyArchiveMergeCounts; /** The added rows, by the name somebody would give them. */ addedRecords: AddedRecordCounts; - restorations: { - total: number; - /** The first `MAX_LISTED_RESTORATIONS`, for a caller that names them. */ - records: RestorationPreview[]; - }; }; /** @@ -112,7 +88,7 @@ export type BlueskyArchiveMergeSummary = { * or this does not compile. */ const MERGE_CATEGORIES: Record< - Exclude, + Exclude, "records" | "files" | "context" > = { posts: "records", @@ -324,13 +300,6 @@ export function planBlueskyArchiveMerge( conversations: conversations.added, messages: messages.added, }), - restorations: summarizeRestorations({ - posts: posts.added, - bookmarks: bookmarks.added, - follows: follows.added, - conversations: conversations.added, - messages: messages.added, - }), }, }; } @@ -371,58 +340,6 @@ function countAddedRecords( }; } -/** - * The records coming back, in the order somebody would read them. - * - * Only records count: a profile or a media file arrives because a record - * needs it, and listing them would bury the posts and messages the person is - * actually being asked about. - */ -function summarizeRestorations(added: { - posts: ExistingPostRow[]; - bookmarks: MobileBookmarkWrite[]; - follows: MobileFollowWrite[]; - conversations: MobileConversationWrite[]; - messages: MobileMessageWrite[]; -}): BlueskyArchiveMergeSummary["restorations"] { - const records: RestorationPreview[] = [ - ...added.posts.map((row) => ({ - category: "posts" as const, - id: row.uri, - text: row.text, - createdAt: row.createdAt, - })), - ...added.bookmarks.map((row) => ({ - category: "bookmarks" as const, - id: row.subjectUri, - text: row.postText, - createdAt: row.postCreatedAt, - })), - ...added.follows.map((row) => ({ - category: "follows" as const, - id: row.uri, - text: row.handle, - createdAt: row.createdAt, - })), - ...added.conversations.map((row) => ({ - category: "chats" as const, - id: row.convoId, - text: row.lastMessageText, - createdAt: row.lastMessageSentAt, - })), - ...added.messages.map((row) => ({ - category: "messages" as const, - id: row.messageId, - text: row.text, - createdAt: row.sentAt, - })), - ]; - - return { - total: records.length, - records: records.slice(0, MAX_LISTED_RESTORATIONS), - }; -} function unionProfile( local: MobileProfileWrite,