@robono/messaging-react-native 0.24.0 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +75 -1
  3. package/RobonoMessagingRuntime.podspec +2 -0
  4. package/SBOM.spdx.json +1829 -557
  5. package/android/build.gradle +4 -1
  6. package/android/src/main/java/com/robono/messaging/RobonoBackupGoogle.java +76 -0
  7. package/android/src/main/java/com/robono/messaging/RobonoHistoryStore.java +173 -0
  8. package/android/src/main/java/com/robono/messaging/RobonoMessagingPackage.java +1 -1
  9. package/app.plugin.cjs +14 -1
  10. package/cloudkit/backup-schema.ckdb +13 -0
  11. package/dist/account-pages.d.ts +51 -0
  12. package/dist/account-pages.js +65 -0
  13. package/dist/account.d.ts +2 -1
  14. package/dist/account.js +6 -2
  15. package/dist/backup-background.d.ts +25 -0
  16. package/dist/backup-background.js +71 -0
  17. package/dist/backup-base64.d.ts +3 -0
  18. package/dist/backup-base64.js +41 -0
  19. package/dist/backup-google-authorization.d.ts +23 -0
  20. package/dist/backup-google-authorization.js +95 -0
  21. package/dist/backup.js +61 -16
  22. package/dist/bubble-design.d.ts +1 -1
  23. package/dist/cloudkit-backup.d.ts +14 -0
  24. package/dist/cloudkit-backup.js +193 -0
  25. package/dist/conversation-details.js +1 -1
  26. package/dist/customization.d.ts +1 -0
  27. package/dist/delivery-bar.d.ts +1 -1
  28. package/dist/delivery-bar.js +5 -2
  29. package/dist/delivery-notice.d.ts +9 -0
  30. package/dist/delivery-notice.js +15 -0
  31. package/dist/expo-backup-background.d.ts +17 -0
  32. package/dist/expo-backup-background.js +57 -0
  33. package/dist/expo-backup-cloudkit.d.ts +6 -0
  34. package/dist/expo-backup-cloudkit.js +11 -0
  35. package/dist/expo-backup-google.d.ts +7 -0
  36. package/dist/expo-backup-google.js +16 -0
  37. package/dist/expo-backup-network.d.ts +8 -0
  38. package/dist/expo-backup-network.js +18 -0
  39. package/dist/expo-backup-passkeys.d.ts +7 -0
  40. package/dist/expo-backup-passkeys.js +31 -7
  41. package/dist/expo-backup-settings.js +26 -8
  42. package/dist/expo-backup.d.ts +14 -0
  43. package/dist/expo-backup.js +22 -0
  44. package/dist/expo-bridge.d.ts +2 -0
  45. package/dist/expo-bridge.js +3 -1
  46. package/dist/expo-cache.js +20 -1
  47. package/dist/expo-device-history.d.ts +24 -0
  48. package/dist/expo-device-history.js +88 -0
  49. package/dist/expo-durable-history.d.ts +26 -0
  50. package/dist/expo-durable-history.js +56 -0
  51. package/dist/expo-history-backup.d.ts +3 -0
  52. package/dist/expo-history-backup.js +79 -0
  53. package/dist/expo-history-maintenance.d.ts +4 -0
  54. package/dist/expo-history-maintenance.js +23 -0
  55. package/dist/expo-history-previews.d.ts +5 -0
  56. package/dist/expo-history-previews.js +57 -0
  57. package/dist/expo-history.d.ts +1 -1
  58. package/dist/expo-history.js +2 -2
  59. package/dist/expo-media.d.ts +2 -0
  60. package/dist/expo-media.js +15 -21
  61. package/dist/expo-messenger.d.ts +8 -0
  62. package/dist/expo-messenger.js +18 -7
  63. package/dist/expo-notifications.d.ts +17 -1
  64. package/dist/expo-notifications.js +36 -16
  65. package/dist/expo-outbox.d.ts +2 -0
  66. package/dist/expo-outbox.js +1 -1
  67. package/dist/expo-oversight.d.ts +15 -0
  68. package/dist/expo-oversight.js +15 -0
  69. package/dist/expo-reviews.d.ts +4 -1
  70. package/dist/expo-reviews.js +122 -17
  71. package/dist/expo-screen.js +5 -4
  72. package/dist/expo-thumbnails.d.ts +2 -2
  73. package/dist/expo-thumbnails.js +48 -5
  74. package/dist/expo.d.ts +10 -0
  75. package/dist/expo.js +8 -0
  76. package/dist/header-calls.js +1 -1
  77. package/dist/inbox-search.d.ts +1 -1
  78. package/dist/inbox-search.js +7 -3
  79. package/dist/inbox.d.ts +1 -0
  80. package/dist/inbox.js +5 -5
  81. package/dist/index.d.ts +8 -3
  82. package/dist/index.js +138 -63
  83. package/dist/linked-apps.d.ts +45 -0
  84. package/dist/linked-apps.js +40 -0
  85. package/dist/loading-messages.d.ts +1 -1
  86. package/dist/loading-messages.js +1 -1
  87. package/dist/media-controller.d.ts +2 -0
  88. package/dist/native-history-authorization.d.ts +4 -0
  89. package/dist/native-history-authorization.js +69 -0
  90. package/dist/native-history-backup.d.ts +16 -0
  91. package/dist/native-history-backup.js +144 -0
  92. package/dist/native-history.d.ts +14 -0
  93. package/dist/native-history.js +186 -0
  94. package/dist/native-outbox.d.ts +2 -0
  95. package/dist/oversight-session.d.ts +4 -0
  96. package/dist/oversight-session.js +14 -0
  97. package/dist/preview-layout.d.ts +12 -0
  98. package/dist/preview-layout.js +102 -0
  99. package/dist/recent-media.js +2 -1
  100. package/dist/reviews.d.ts +8 -4
  101. package/dist/reviews.js +53 -26
  102. package/dist/scheduled.js +2 -2
  103. package/dist/search.js +18 -8
  104. package/ios/RobonoBackupCloudKit.m +96 -0
  105. package/ios/RobonoHistoryStore.m +170 -0
  106. package/package.json +22 -4
  107. package/plugin/backup-expiration.cjs +23 -0
  108. package/plugin/prepare-native.cjs +12 -0
@@ -0,0 +1,45 @@
1
+ import React from 'react';
2
+ export interface MessagingLinkedNetwork {
3
+ id: string;
4
+ display_name: string;
5
+ description: string;
6
+ accepted_identifier: {
7
+ label: string;
8
+ description: string;
9
+ example: string;
10
+ input_type: string;
11
+ };
12
+ }
13
+ export interface MessagingLinkedContact {
14
+ id: string;
15
+ status: 'accepted' | 'pending';
16
+ incoming: boolean;
17
+ name: string;
18
+ network: string;
19
+ contactId?: string;
20
+ conversationId?: string;
21
+ avatarUrl?: string;
22
+ }
23
+ export interface MessagingLinkedApps {
24
+ listNetworks: (signal?: AbortSignal) => Promise<{
25
+ networks: MessagingLinkedNetwork[];
26
+ }>;
27
+ listConnections: (signal?: AbortSignal) => Promise<{
28
+ connections: MessagingLinkedContact[];
29
+ }>;
30
+ request: (networkId: string, identifier: string, requestId: string) => Promise<unknown>;
31
+ respond: (id: string, status: 'accepted' | 'rejected') => Promise<{
32
+ connections: MessagingLinkedContact[];
33
+ }>;
34
+ disconnect: (id: string) => Promise<{
35
+ connections: MessagingLinkedContact[];
36
+ }>;
37
+ createRequestId: () => string;
38
+ onOpen: (contact: {
39
+ conversationId?: string;
40
+ contactId?: string;
41
+ }) => Promise<void>;
42
+ }
43
+ export declare function MessagingLinkedAppsScreen({ service }: {
44
+ service: MessagingLinkedApps;
45
+ }): React.JSX.Element;
@@ -0,0 +1,40 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { useMessagingAppearance } from './appearance-context.js';
3
+ import React, { useEffect, useRef, useState } from 'react';
4
+ import { ActivityIndicator, Pressable, View } from 'react-native';
5
+ import { Text, TextInput } from './typography.js';
6
+ import { useMessagingPopupColors } from './popup.js';
7
+ import { useRobonoLocale } from './localization.js';
8
+ export function MessagingLinkedAppsScreen({ service }) {
9
+ const palette = useMessagingPopupColors(undefined, 'linkedApps'), accent = palette.accent, { text } = useRobonoLocale();
10
+ const features = useMessagingAppearance()?.screenFeatures?.linkedApps;
11
+ const [confirm, setConfirm] = useState(null);
12
+ const [networks, setNetworks] = useState([]), [contacts, setContacts] = useState([]), [selected, setSelected] = useState(null), [identifier, setIdentifier] = useState(''), [busy, setBusy] = useState(false), [ready, setReady] = useState(false), [error, setError] = useState(''), [sent, setSent] = useState(false);
13
+ const [attempt, setAttempt] = useState(0);
14
+ const request = useRef(null), alive = useRef(true);
15
+ useEffect(() => { alive.current = true; const controller = new AbortController(); setReady(false); setError(''); void Promise.all([service.listNetworks(controller.signal), service.listConnections(controller.signal)]).then(([n, c]) => { if (!controller.signal.aborted) {
16
+ setNetworks(n.networks);
17
+ setContacts(c.connections);
18
+ setReady(true);
19
+ } }).catch(() => { if (!controller.signal.aborted)
20
+ setError('Networks could not load. Check your connection and try again.'); }); return () => { alive.current = false; controller.abort(); }; }, [service, attempt]);
21
+ async function run(action) { if (busy)
22
+ return; setBusy(true); setError(''); try {
23
+ await action();
24
+ }
25
+ catch (e) {
26
+ if (alive.current)
27
+ setError(e instanceof Error ? e.message : 'The connection could not be updated.');
28
+ }
29
+ finally {
30
+ if (alive.current)
31
+ setBusy(false);
32
+ } }
33
+ const button = (label, action, disabled = false) => _jsxs(Pressable, { accessibilityRole: "button", accessibilityLabel: text(label), accessibilityState: { busy, disabled: busy || disabled }, disabled: busy || disabled, onPress: action, style: { minHeight: 46, paddingHorizontal: 14, paddingVertical: 11, borderRadius: 10, borderWidth: 1, borderColor: accent, justifyContent: 'center', opacity: busy || disabled ? .5 : 1 }, children: [_jsx(Text, { style: { color: accent, fontSize: 17, fontWeight: '600', opacity: busy ? 0 : 1 }, children: text(label) }), busy && _jsx(View, { pointerEvents: "none", style: { position: 'absolute', inset: 0, alignItems: 'center', justifyContent: 'center' }, children: _jsx(ActivityIndicator, { color: accent }) })] });
34
+ return _jsxs(View, { style: { gap: 16, minHeight: 160 }, children: [!ready && !error && _jsx(View, { style: { height: 160, justifyContent: 'center' }, accessibilityState: { busy: true }, children: _jsx(ActivityIndicator, { color: accent }) }), ready && _jsxs(_Fragment, { children: [contacts.map(c => _jsxs(View, { style: { gap: 10, paddingVertical: 12, borderBottomWidth: 1, borderColor: palette.secondary }, children: [_jsx(Text, { style: { color: palette.foreground, fontSize: 19, fontWeight: '600' }, children: c.name }), _jsxs(Text, { style: { color: palette.secondary, fontSize: 16 }, children: [c.network, c.status === 'pending' ? ' · ' + (c.incoming ? 'Wants to connect' : 'Waiting for acceptance') : ''] }), _jsx(View, { style: { flexDirection: 'row', gap: 12, flexWrap: 'wrap' }, children: c.status === 'accepted' ? _jsxs(_Fragment, { children: [features?.openChat !== false && button('Open chat', () => void run(() => service.onOpen(c))), features?.disconnect !== false && (confirm === c.id ? _jsxs(_Fragment, { children: [button('Keep connection', () => setConfirm(null)), button('Confirm disconnect', () => void run(async () => { const result = await service.disconnect(c.id); if (alive.current) {
35
+ setContacts(result.connections);
36
+ setConfirm(null);
37
+ } }))] }) : button('Disconnect', () => setConfirm(c.id)))] }) : c.incoming && features?.respond !== false ? _jsxs(_Fragment, { children: [button('Accept', () => void run(async () => { const result = await service.respond(c.id, 'accepted'); setContacts(result.connections); const contact = result.connections.find(row => row.id === c.id); if (contact?.conversationId)
38
+ await service.onOpen(contact); })), button('Decline', () => void run(async () => { setContacts((await service.respond(c.id, 'rejected')).connections); }))] }) : null })] }, c.id)), features?.connect !== false && _jsxs(_Fragment, { children: [_jsx(Text, { style: { color: palette.foreground, fontSize: 19, fontWeight: '600' }, children: "Connect to another network" }), !selected ? networks.map(n => _jsx(React.Fragment, { children: button(n.display_name, () => { setSelected(n); setIdentifier(''); setSent(false); }) }, n.id)) : _jsxs(_Fragment, { children: [_jsxs(View, { style: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', gap: 12 }, children: [_jsx(Text, { style: { color: palette.foreground, fontSize: 18, flex: 1 }, children: selected.display_name }), button('Change', () => setSelected(null))] }), _jsx(Text, { style: { color: palette.secondary, fontSize: 16 }, children: selected.accepted_identifier.description }), _jsx(TextInput, { accessibilityLabel: selected.accepted_identifier.label, value: identifier, onChangeText: v => { setIdentifier(v); setSent(false); }, editable: !busy, autoCapitalize: "none", autoCorrect: false, placeholder: selected.accepted_identifier.example, placeholderTextColor: palette.secondary, keyboardType: selected.accepted_identifier.input_type === 'tel' ? 'phone-pad' : selected.accepted_identifier.input_type === 'email' ? 'email-address' : 'default', style: { borderWidth: 1, borderColor: '#555', borderRadius: 10, color: palette.foreground, fontSize: 18, padding: 14 } }), button(sent ? 'Request sent' : 'Send request', () => void run(async () => { const target = selected.id + ':' + identifier.trim(); if (request.current?.target !== target)
39
+ request.current = { target, id: service.createRequestId() }; await service.request(selected.id, identifier, request.current.id); setSent(true); setContacts((await service.listConnections()).connections); }), !identifier.trim() || sent)] }), ready && !networks.length && _jsx(Text, { style: { color: palette.secondary, fontSize: 16 }, children: "No other networks are available right now." })] })] }), !ready && error && button('Try again', () => setAttempt(value => value + 1)), busy && _jsx(ActivityIndicator, { color: accent }), !!error && _jsx(Text, { accessibilityRole: "alert", style: { color: palette.danger, fontSize: 16 }, children: error })] });
40
+ }
@@ -2,4 +2,4 @@ import React from 'react';
2
2
  /** Keep brief authorized reads visually quiet; indicate a slow read in place. */
3
3
  export declare function MessagingLoadingMessages({ color }: {
4
4
  color: string;
5
- }): React.JSX.Element | null;
5
+ }): React.JSX.Element;
@@ -6,5 +6,5 @@ import { useRobonoLocale } from './localization.js';
6
6
  export function MessagingLoadingMessages({ color }) {
7
7
  const { text } = useRobonoLocale(), [visible, setVisible] = useState(false);
8
8
  useEffect(() => { const timer = setTimeout(() => setVisible(true), 500); return () => clearTimeout(timer); }, []);
9
- return visible ? _jsx(View, { testID: "messaging-loading-messages", style: { padding: 16, alignItems: 'center' }, children: _jsx(ActivityIndicator, { accessibilityLabel: text('Loading messages…'), color: color }) }) : null;
9
+ return _jsx(View, { testID: "messaging-loading-messages", style: { height: 52, alignItems: 'center', justifyContent: 'center' }, children: visible && _jsx(ActivityIndicator, { accessibilityLabel: text('Loading messages…'), color: color }) });
10
10
  }
@@ -10,6 +10,8 @@ export interface LocalMessagingMedia extends Omit<MessageMedia, 'assetId'> {
10
10
  autoPlay?: boolean;
11
11
  }
12
12
  export interface MediaTransferOptions {
13
+ /** Background preview work must not cancel another preview or a user-opened viewer. */
14
+ purpose?: 'preview' | 'open';
13
15
  reauthorize?: boolean;
14
16
  signal: AbortSignal;
15
17
  onProgress: (fraction: number) => void;
@@ -0,0 +1,4 @@
1
+ import { type MessagingDurableHistoryStore } from '@robono/messaging';
2
+ import type { HistoryStatement, NativeHistoryDatabase } from './native-history.js';
3
+ export declare const nativeHistoryAuthorizationTables: HistoryStatement[];
4
+ export declare function nativeHistoryAuthorization(database: NativeHistoryDatabase, ready: Promise<void>): Required<Pick<MessagingDurableHistoryStore, 'authorize' | 'authorizedPage' | 'authorizedRecord' | 'revokeAuthorization'>>;
@@ -0,0 +1,69 @@
1
+ import { historyAuthorization, historyAuthorizationPolicy, historyAuthorizationRecords } from '@robono/messaging';
2
+ export const nativeHistoryAuthorizationTables = [
3
+ { sql: 'CREATE TABLE IF NOT EXISTS history_authorization(conversation TEXT PRIMARY KEY,issued INTEGER NOT NULL,expires INTEGER NOT NULL,policy TEXT NOT NULL,authorization TEXT NOT NULL)', args: [] },
4
+ { sql: 'CREATE TABLE IF NOT EXISTS history_authorized_records(conversation TEXT NOT NULL,id TEXT NOT NULL,revision INTEGER NOT NULL,expires INTEGER NOT NULL,sort_key TEXT NOT NULL,PRIMARY KEY(conversation,id))', args: [] },
5
+ { sql: 'CREATE INDEX IF NOT EXISTS history_authorized_order ON history_authorized_records(conversation,sort_key)', args: [] },
6
+ { sql: 'CREATE INDEX IF NOT EXISTS history_authorized_expiry ON history_authorized_records(conversation,expires)', args: [] },
7
+ ];
8
+ export function nativeHistoryAuthorization(database, ready) {
9
+ const clear = (conversation) => ['history_authorized_records', 'history_authorization'].map(table => ({ sql: `DELETE FROM ${table}${conversation === undefined ? '' : ' WHERE conversation=?'}`, args: conversation === undefined ? [] : [conversation] }));
10
+ return {
11
+ async authorize(conversation, value, records, expected, renewThroughCursor) {
12
+ await ready;
13
+ historyAuthorizationRecords(records);
14
+ if (!Number.isSafeInteger(expected) || expected < 0)
15
+ throw Error('History storage changed.');
16
+ const commands = [{ sql: 'INSERT OR REPLACE INTO history_write_guard(id,epoch) VALUES(1,CASE WHEN (SELECT epoch FROM history_control WHERE id=1)=? THEN ? ELSE NULL END)', args: [expected, expected] }];
17
+ const authorization = historyAuthorization(value);
18
+ if (!authorization) {
19
+ await database([...commands, { sql: 'UPDATE history_control SET epoch=epoch+1 WHERE id=1 AND EXISTS(SELECT 1 FROM history_authorization WHERE conversation=?)', args: [conversation] }, ...clear(conversation)]);
20
+ return;
21
+ }
22
+ const policy = historyAuthorizationPolicy(authorization);
23
+ if (renewThroughCursor !== undefined) {
24
+ if (!/^(0|[1-9][0-9]{0,29})$/.test(renewThroughCursor))
25
+ throw Error('History storage changed.');
26
+ commands.push({ sql: 'INSERT OR REPLACE INTO history_write_guard(id,epoch) VALUES(1,CASE WHEN coalesce((SELECT cursor FROM cursors WHERE conversation=?),\'0\')=? THEN ? ELSE NULL END)', args: [conversation, renewThroughCursor, expected] });
27
+ }
28
+ commands.push({ sql: 'DELETE FROM history_authorized_records WHERE conversation=? AND EXISTS(SELECT 1 FROM history_authorization WHERE conversation=? AND policy<>? AND issued<=?)', args: [conversation, conversation, policy, authorization.issuedAt] });
29
+ commands.push({ sql: 'INSERT INTO history_authorization(conversation,issued,expires,policy,authorization) VALUES(?,?,?,?,?) ON CONFLICT(conversation) DO UPDATE SET issued=excluded.issued,expires=excluded.expires,policy=excluded.policy,authorization=excluded.authorization WHERE issued<=excluded.issued', args: [conversation, authorization.issuedAt, authorization.expiresAt, policy, JSON.stringify(authorization)] });
30
+ for (const record of records)
31
+ commands.push({ sql: 'INSERT INTO history_authorized_records(conversation,id,revision,expires,sort_key) SELECT conversation,id,revision,?,sort_key FROM records WHERE conversation=? AND id=? AND revision=? AND deleted=0 AND EXISTS(SELECT 1 FROM history_authorization WHERE conversation=? AND policy=?) ON CONFLICT(conversation,id) DO UPDATE SET revision=excluded.revision,sort_key=excluded.sort_key,expires=CASE WHEN revision=excluded.revision THEN max(expires,excluded.expires) ELSE excluded.expires END', args: [authorization.expiresAt, conversation, record.id, record.revision, conversation, policy] });
32
+ if (renewThroughCursor !== undefined)
33
+ commands.push({ sql: 'UPDATE history_authorized_records SET expires=max(expires,?) WHERE conversation=? AND EXISTS(SELECT 1 FROM history_authorization WHERE conversation=? AND policy=?) AND EXISTS(SELECT 1 FROM records r WHERE r.conversation=history_authorized_records.conversation AND r.id=history_authorized_records.id AND r.revision=history_authorized_records.revision AND r.deleted=0)', args: [authorization.expiresAt, conversation, conversation, policy] });
34
+ await database(commands);
35
+ },
36
+ async authorizedPage(conversation, before, limit = 50) {
37
+ await ready;
38
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100 || before !== undefined && (typeof before !== 'string' || !before || before.length > 200))
39
+ throw Error('Choose a valid offline history page.');
40
+ const now = Date.now(), rows = await database([
41
+ { sql: 'SELECT epoch FROM history_control WHERE id=1', args: [] },
42
+ { sql: 'SELECT authorization FROM history_authorization WHERE conversation=? AND expires>?', args: [conversation, now] },
43
+ { sql: `SELECT r.record,g.expires FROM history_authorized_records g JOIN records r ON r.conversation=g.conversation AND r.id=g.id AND r.revision=g.revision AND r.deleted=0 WHERE g.conversation=? AND g.expires>?${before ? ' AND g.sort_key<(SELECT sort_key FROM records WHERE conversation=? AND id=?)' : ''} ORDER BY g.sort_key DESC LIMIT ?`, args: [conversation, now, ...(before ? [conversation, before] : []), limit + 1] },
44
+ ]);
45
+ const authorization = historyAuthorization(rows[1][0] ? JSON.parse(rows[1][0].authorization) : null, now);
46
+ if (!authorization)
47
+ return null;
48
+ const selected = rows[2].slice(0, limit), hasMore = rows[2].length > limit;
49
+ if (selected.length)
50
+ authorization.expiresAt = Math.min(authorization.expiresAt, ...selected.map(r => Number(r.expires)));
51
+ const records = selected.map(r => JSON.parse(r.record)).reverse();
52
+ return { authorization, records, generation: Number(rows[0][0].epoch), hasMore, nextCursor: hasMore ? records[0].message.id : null };
53
+ },
54
+ async authorizedRecord(conversation, id) {
55
+ await ready;
56
+ const now = Date.now(), rows = await database([
57
+ { sql: 'SELECT epoch FROM history_control WHERE id=1', args: [] },
58
+ { sql: 'SELECT authorization FROM history_authorization WHERE conversation=? AND expires>?', args: [conversation, now] },
59
+ { sql: 'SELECT r.record,g.expires FROM history_authorized_records g JOIN records r ON r.conversation=g.conversation AND r.id=g.id AND r.revision=g.revision AND r.deleted=0 WHERE g.conversation=? AND g.id=? AND g.expires>?', args: [conversation, id, now] },
60
+ ]);
61
+ const authorization = historyAuthorization(rows[1][0] ? JSON.parse(rows[1][0].authorization) : null, now), row = rows[2][0];
62
+ if (!authorization || !row)
63
+ return null;
64
+ authorization.expiresAt = Math.min(authorization.expiresAt, Number(row.expires));
65
+ return { authorization, records: [JSON.parse(row.record)], generation: Number(rows[0][0].epoch), hasMore: false, nextCursor: null };
66
+ },
67
+ async revokeAuthorization(conversation) { await ready; await database([{ sql: 'UPDATE history_control SET epoch=epoch+1 WHERE id=1', args: [] }, ...clear(conversation)]); },
68
+ };
69
+ }
@@ -0,0 +1,16 @@
1
+ import { type NativeHistoryDatabase } from './native-history.js';
2
+ export interface NativeHistoryBackupFiles {
3
+ read(sha256: string, offset: number, length: number): Promise<Uint8Array>;
4
+ stage(session: string): Promise<{
5
+ write(sha256: string, byteSize: number, offset: number, bytes: Uint8Array): Promise<void>;
6
+ promote(sha256: string, byteSize: number, expectedGeneration: number): Promise<{
7
+ reference: string;
8
+ sha256: string;
9
+ byteSize: number;
10
+ }>;
11
+ discard(): Promise<void>;
12
+ }>;
13
+ }
14
+ /** SQL snapshots and staging share the account's private history database.
15
+ * Original bytes are streamed separately; restore publishes metadata atomically. */
16
+ export declare function createNativeHistoryBackupSource(database: NativeHistoryDatabase, files: NativeHistoryBackupFiles, sessionId: () => string): import("@robono/messaging").MessagingBackupSource;
@@ -0,0 +1,144 @@
1
+ import { createDurableHistoryBackupSource, durableHistorySortKey, durableHistoryMediaKey, durableHistorySearchText, historyContentIdentity } from '@robono/messaging';
2
+ import { nativeHistoryBackupTables, nativeHistoryMediaTables } from './native-history.js';
3
+ const schema = [
4
+ { sql: 'CREATE TABLE IF NOT EXISTS history_control(id INTEGER PRIMARY KEY,epoch INTEGER NOT NULL)', args: [] },
5
+ { sql: 'INSERT OR IGNORE INTO history_control(id,epoch) VALUES(1,0)', args: [] },
6
+ { sql: 'CREATE TABLE IF NOT EXISTS history_format(name TEXT PRIMARY KEY,value INTEGER NOT NULL)', args: [] },
7
+ ...nativeHistoryBackupTables,
8
+ ...nativeHistoryMediaTables,
9
+ ];
10
+ /** SQL snapshots and staging share the account's private history database.
11
+ * Original bytes are streamed separately; restore publishes metadata atomically. */
12
+ export function createNativeHistoryBackupSource(database, files, sessionId) {
13
+ const check = (signal) => { if (signal.aborted)
14
+ throw Error('Backup cancelled.'); };
15
+ const newSession = () => { const value = sessionId(); if (!/^[a-zA-Z0-9-]{16,80}$/.test(value))
16
+ throw Error('Invalid backup session.'); return value; };
17
+ const remove = (session) => database(['backup_records', 'backup_merge_guards', 'backup_media', 'backup_search', 'backup_sessions'].map(table => ({ sql: `DELETE FROM ${table} WHERE session=?`, args: [session] }))).then(() => { });
18
+ const touch = (session) => ({ sql: 'UPDATE backup_sessions SET touched=? WHERE session=?', args: [Date.now(), session] });
19
+ return createDurableHistoryBackupSource({
20
+ async snapshot(signal) {
21
+ check(signal);
22
+ const session = newSession();
23
+ const results = await database([...schema, { sql: 'INSERT INTO backup_sessions(session,touched) VALUES(?,?)', args: [session, Date.now()] }, { sql: 'INSERT INTO backup_records SELECT ?,conversation,id,sort_key,revision,deleted,record FROM records', args: [session] }, { sql: 'SELECT epoch FROM history_control WHERE id=1', args: [] }]);
24
+ const epoch = results.at(-1)[0].epoch;
25
+ let closed = false;
26
+ const active = () => { check(signal); if (closed)
27
+ throw Error('Backup snapshot closed.'); };
28
+ return {
29
+ async *records() {
30
+ let conversation = '', id = '';
31
+ for (;;) {
32
+ active();
33
+ const rows = await database([{ sql: 'SELECT epoch FROM history_control WHERE id=1', args: [] }, { sql: 'SELECT conversation,id,record FROM backup_records WHERE session=? AND (conversation>? OR (conversation=? AND id>?)) ORDER BY conversation,id LIMIT 100', args: [session, conversation, conversation, id] }, touch(session)]);
34
+ active();
35
+ if (rows[0][0].epoch !== epoch)
36
+ throw Error('History account changed.');
37
+ for (const row of rows[1]) {
38
+ active();
39
+ yield JSON.parse(row.record);
40
+ conversation = row.conversation;
41
+ id = row.id;
42
+ }
43
+ if (rows[1].length < 100)
44
+ return;
45
+ }
46
+ },
47
+ async original(sha, offset, length) { active(); const rows = await database([{ sql: 'SELECT epoch FROM history_control WHERE id=1', args: [] }, touch(session)]); if (rows[0][0].epoch !== epoch)
48
+ throw Error('History account changed.'); const bytes = await files.read(sha, offset, length); active(); return bytes; },
49
+ async close() { closed = true; await remove(session); },
50
+ };
51
+ },
52
+ async stage(signal) {
53
+ check(signal);
54
+ const session = newSession(), rows = await database([...schema, { sql: 'INSERT INTO backup_sessions(session,touched) VALUES(?,?)', args: [session, Date.now()] }, { sql: 'SELECT epoch FROM history_control WHERE id=1', args: [] }]), epoch = rows.at(-1)[0].epoch;
55
+ const staging = await files.stage(session), originals = new Map();
56
+ let pending = [], finished = false;
57
+ const active = () => { check(signal); if (finished)
58
+ throw Error('Backup restore closed.'); };
59
+ const flush = async () => { active(); if (pending.length) {
60
+ const commands = pending;
61
+ pending = [];
62
+ await database([{ sql: 'UPDATE history_control SET epoch=CASE WHEN epoch=? THEN epoch ELSE NULL END WHERE id=1', args: [epoch] }, touch(session), ...commands]);
63
+ active();
64
+ } };
65
+ return {
66
+ async record(row) {
67
+ active();
68
+ const m = row.message;
69
+ if (row.original && !row.original.omitted)
70
+ originals.set(row.original.sha256, row.original.byteSize);
71
+ pending.push({ sql: 'INSERT INTO backup_records(session,conversation,id,sort_key,revision,deleted,record) VALUES(?,?,?,?,?,?,?)', args: [session, m.conversationId, m.id, durableHistorySortKey(m), m.revision ?? 0, m.deleted ? 1 : 0, JSON.stringify(row)] });
72
+ pending.push({ sql: 'INSERT INTO backup_media(session,conversation,id,position) VALUES(?,?,?,?)', args: [session, m.conversationId, m.id, durableHistoryMediaKey(m) ?? null] });
73
+ pending.push({ sql: 'INSERT INTO backup_search(session,conversation,id,position,words) VALUES(?,?,?,?,?)', args: [session, m.conversationId, m.id, m.id.padStart(36, '0'), durableHistorySearchText(m)] });
74
+ if (pending.length >= 100)
75
+ await flush();
76
+ },
77
+ async original(sha, size, offset, bytes) { active(); await database([{ sql: 'UPDATE history_control SET epoch=CASE WHEN epoch=? THEN epoch ELSE NULL END WHERE id=1', args: [epoch] }, touch(session)]); await staging.write(sha, size, offset, bytes); active(); },
78
+ async commit() {
79
+ active();
80
+ await flush();
81
+ const promoted = new Map();
82
+ for (const [sha, size] of originals) {
83
+ active();
84
+ const original = await staging.promote(sha, size, epoch);
85
+ if (original.sha256 !== sha || original.byteSize !== size || !original.reference)
86
+ throw Error('Original verification failed.');
87
+ promoted.set(sha, original);
88
+ }
89
+ let conversation = '', id = '';
90
+ for (;;) {
91
+ active();
92
+ const rows = (await database([{ sql: 'SELECT b.conversation,b.id,b.record,r.record AS previous FROM backup_records b LEFT JOIN records r ON r.conversation=b.conversation AND r.id=b.id WHERE b.session=? AND (b.conversation>? OR (b.conversation=? AND b.id>?)) ORDER BY b.conversation,b.id LIMIT 100', args: [session, conversation, conversation, id] }]))[0];
93
+ const commands = [];
94
+ for (const row of rows) {
95
+ const input = JSON.parse(row.record);
96
+ let record = { message: input.message };
97
+ if (input.original && !input.original.omitted)
98
+ record.original = promoted.get(input.original.sha256);
99
+ if (input.original?.omitted)
100
+ record.omittedOriginal = { sha256: input.original.sha256, byteSize: input.original.byteSize };
101
+ const previous = row.previous ? JSON.parse(row.previous) : undefined;
102
+ if (previous && !previous.message.deleted && !previous.original && record.original && historyContentIdentity(previous.message) === historyContentIdentity(record.message)) {
103
+ record = { ...previous, original: record.original };
104
+ delete record.omittedOriginal;
105
+ commands.push({ sql: 'INSERT INTO backup_merge_guards(session,conversation,id,record) VALUES(?,?,?,?)', args: [session, row.conversation, row.id, row.previous] });
106
+ }
107
+ commands.push({ sql: 'UPDATE backup_records SET record=? WHERE session=? AND conversation=? AND id=?', args: [JSON.stringify(record), session, row.conversation, row.id] });
108
+ }
109
+ if (commands.length)
110
+ await database(commands);
111
+ if (rows.length < 100)
112
+ break;
113
+ conversation = rows.at(-1).conversation;
114
+ id = rows.at(-1).id;
115
+ }
116
+ active();
117
+ await database([
118
+ // A sign-out/clear invalidates in-flight snapshots and restorations even
119
+ // when another SDK instance performs it while this one awaits the OS.
120
+ { sql: 'UPDATE history_control SET epoch=CASE WHEN epoch=? THEN epoch ELSE NULL END WHERE id=1', args: [epoch] },
121
+ { sql: 'INSERT OR REPLACE INTO records(conversation,id,sort_key,revision,deleted,record,receipt,ack_pending) SELECT b.conversation,b.id,b.sort_key,b.revision,b.deleted,b.record,r.receipt,COALESCE(r.ack_pending,0) FROM backup_records b JOIN backup_merge_guards g ON g.session=b.session AND g.conversation=b.conversation AND g.id=b.id JOIN records r ON r.conversation=b.conversation AND r.id=b.id AND r.record=g.record WHERE b.session=?', args: [session] },
122
+ { sql: 'INSERT OR REPLACE INTO records(conversation,id,sort_key,revision,deleted,record,receipt,ack_pending) SELECT b.conversation,b.id,b.sort_key,b.revision,b.deleted,b.record,NULL,0 FROM backup_records b WHERE b.session=? AND NOT EXISTS(SELECT 1 FROM records r WHERE r.conversation=b.conversation AND r.id=b.id AND (r.deleted=1 OR r.revision>=b.revision))', args: [session] },
123
+ { sql: 'INSERT OR REPLACE INTO history_media(conversation,id,position) SELECT g.conversation,g.id,g.position FROM backup_media g JOIN backup_records b ON b.session=g.session AND b.conversation=g.conversation AND b.id=g.id JOIN records r ON r.conversation=b.conversation AND r.id=b.id AND r.record=b.record WHERE g.session=?', args: [session] },
124
+ { sql: 'INSERT OR REPLACE INTO history_search(conversation,id,position,words) SELECT g.conversation,g.id,g.position,g.words FROM backup_search g JOIN backup_records b ON b.session=g.session AND b.conversation=g.conversation AND b.id=g.id JOIN records r ON r.conversation=b.conversation AND r.id=b.id AND r.record=b.record WHERE g.session=?', args: [session] },
125
+ { sql: 'DELETE FROM backup_records WHERE session=?', args: [session] },
126
+ { sql: 'DELETE FROM backup_merge_guards WHERE session=?', args: [session] },
127
+ { sql: 'DELETE FROM backup_media WHERE session=?', args: [session] },
128
+ { sql: 'DELETE FROM backup_search WHERE session=?', args: [session] },
129
+ { sql: 'DELETE FROM backup_sessions WHERE session=?', args: [session] },
130
+ { sql: "INSERT INTO history_format(name,value) VALUES('cleanup-needed',1) ON CONFLICT(name) DO UPDATE SET value=value+1", args: [] },
131
+ ]);
132
+ finished = true;
133
+ await staging.discard();
134
+ },
135
+ async discard() { finished = true; pending = []; try {
136
+ await remove(session);
137
+ }
138
+ finally {
139
+ await staging.discard();
140
+ } },
141
+ };
142
+ },
143
+ });
144
+ }
@@ -0,0 +1,14 @@
1
+ import { type MessagingDurableHistoryStore } from '@robono/messaging';
2
+ export type HistoryStatement = {
3
+ sql: string;
4
+ args: (string | number | null)[];
5
+ };
6
+ export type NativeHistoryDatabase = (commands: HistoryStatement[]) => Promise<Record<string, any>[][]>;
7
+ export declare const nativeHistoryPreviewTable: HistoryStatement;
8
+ export declare const nativeHistoryBackupTables: HistoryStatement[];
9
+ export declare const nativeHistoryMediaTables: HistoryStatement[];
10
+ /** Prepared SQL shared by the iPhone and Android adapters. No network-provided SQL. */
11
+ export declare function createNativeHistoryStore(database: NativeHistoryDatabase, options?: {
12
+ clearAll: NativeHistoryDatabase;
13
+ clearConversation?: NativeHistoryDatabase;
14
+ }): MessagingDurableHistoryStore;
@@ -0,0 +1,186 @@
1
+ import { historyContentIdentity, durableHistorySortKey, durableHistoryMediaKey, durableHistorySearchWords, durableHistorySearchText } from '@robono/messaging';
2
+ import { nativeHistoryAuthorization, nativeHistoryAuthorizationTables } from './native-history-authorization.js';
3
+ export const nativeHistoryPreviewTable = { sql: 'CREATE TABLE IF NOT EXISTS history_previews(sha TEXT PRIMARY KEY,preview TEXT NOT NULL)', args: [] };
4
+ export const nativeHistoryBackupTables = [
5
+ { sql: 'CREATE TABLE IF NOT EXISTS backup_sessions(session TEXT PRIMARY KEY,touched INTEGER NOT NULL)', args: [] },
6
+ { sql: 'CREATE TABLE IF NOT EXISTS backup_media(session TEXT NOT NULL,conversation TEXT NOT NULL,id TEXT NOT NULL,position TEXT,PRIMARY KEY(session,conversation,id))', args: [] },
7
+ { sql: 'CREATE TABLE IF NOT EXISTS backup_search(session TEXT NOT NULL,conversation TEXT NOT NULL,id TEXT NOT NULL,position TEXT NOT NULL,words TEXT,PRIMARY KEY(session,conversation,id))', args: [] },
8
+ { sql: 'CREATE TABLE IF NOT EXISTS backup_records(session TEXT NOT NULL,conversation TEXT NOT NULL,id TEXT NOT NULL,sort_key TEXT NOT NULL,revision INTEGER NOT NULL,deleted INTEGER NOT NULL,record TEXT NOT NULL,PRIMARY KEY(session,conversation,id))', args: [] },
9
+ { sql: 'CREATE TABLE IF NOT EXISTS backup_merge_guards(session TEXT NOT NULL,conversation TEXT NOT NULL,id TEXT NOT NULL,record TEXT NOT NULL,PRIMARY KEY(session,conversation,id))', args: [] },
10
+ ];
11
+ export const nativeHistoryMediaTables = [
12
+ { sql: 'CREATE TABLE IF NOT EXISTS history_search(conversation TEXT NOT NULL,id TEXT NOT NULL,position TEXT NOT NULL,words TEXT,PRIMARY KEY(conversation,id))', args: [] },
13
+ { sql: 'CREATE INDEX IF NOT EXISTS history_search_order ON history_search(conversation,position) WHERE words IS NOT NULL', args: [] },
14
+ { sql: 'CREATE INDEX IF NOT EXISTS history_search_inbox_order ON history_search(position) WHERE words IS NOT NULL', args: [] },
15
+ { sql: 'CREATE TABLE IF NOT EXISTS history_media(conversation TEXT NOT NULL,id TEXT NOT NULL,position TEXT,PRIMARY KEY(conversation,id))', args: [] },
16
+ { sql: 'CREATE INDEX IF NOT EXISTS history_media_order ON history_media(conversation,position) WHERE position IS NOT NULL', args: [] },
17
+ ];
18
+ const indexMedia = (conversation, id, record) => ({ sql: 'INSERT OR REPLACE INTO history_media(conversation,id,position) SELECT ?,?,? WHERE EXISTS(SELECT 1 FROM records WHERE conversation=? AND id=? AND record=?)', args: [conversation, id, durableHistoryMediaKey(record.message) ?? null, conversation, id, JSON.stringify(record)] });
19
+ const searchSelection = 'SELECT ?,?,?,? WHERE EXISTS(SELECT 1 FROM records WHERE conversation=? AND id=? AND revision=? AND deleted=?)';
20
+ const searchArgs = (conversation, id, record) => [conversation, id, id.padStart(36, '0'), durableHistorySearchText(record.message), conversation, id, record.message.revision ?? 0, record.message.deleted ? 1 : 0];
21
+ const indexSearch = (conversation, id, record) => ({ sql: 'INSERT OR REPLACE INTO history_search(conversation,id,position,words) ' + searchSelection, args: searchArgs(conversation, id, record) });
22
+ /** Prepared SQL shared by the iPhone and Android adapters. No network-provided SQL. */
23
+ export function createNativeHistoryStore(database, options) {
24
+ const ready = (async () => {
25
+ await database([...nativeHistoryBackupTables, ...nativeHistoryAuthorizationTables, { sql: 'INSERT OR IGNORE INTO backup_sessions(session,touched) SELECT DISTINCT session,? FROM backup_records', args: [Date.now()] }]);
26
+ const initial = await database([{ sql: 'CREATE INDEX IF NOT EXISTS history_pending_conversation ON records(ack_pending,conversation)', args: [] }, { sql: 'CREATE INDEX IF NOT EXISTS history_receipt ON records(receipt) WHERE receipt IS NOT NULL', args: [] }, { sql: 'CREATE TABLE IF NOT EXISTS history_control(id INTEGER PRIMARY KEY,epoch INTEGER NOT NULL)', args: [] }, { sql: 'INSERT OR IGNORE INTO history_control(id,epoch) VALUES(1,0)', args: [] }, { sql: 'CREATE TABLE IF NOT EXISTS history_write_guard(id INTEGER PRIMARY KEY,epoch INTEGER NOT NULL)', args: [] }, { sql: 'CREATE TABLE IF NOT EXISTS history_format(name TEXT PRIMARY KEY,value INTEGER NOT NULL)', args: [] }, { sql: "SELECT value FROM history_format WHERE name='utc-order'", args: [] }]);
27
+ const mediaFormat = await database([...nativeHistoryMediaTables, { sql: "SELECT value FROM history_format WHERE name='media-order'", args: [] }]);
28
+ const searchFormat = await database([{ sql: "SELECT value FROM history_format WHERE name='search-words'", args: [] }]);
29
+ if (initial.at(-1)?.[0]?.value === 1 && mediaFormat.at(-1)?.[0]?.value === 1 && searchFormat[0]?.[0]?.value === 1)
30
+ return;
31
+ // A bounded one-time migration canonicalizes Z/offset/fraction timestamps.
32
+ // SQLite's datetime parser rounds fractional milliseconds; use the same JS
33
+ // ordering as the shared Messenger instead, preserving original wire fields.
34
+ let conversation = '', id = '';
35
+ for (;;) {
36
+ const rows = (await database([{ sql: 'SELECT conversation,id,record FROM records WHERE conversation>? OR (conversation=? AND id>?) ORDER BY conversation,id LIMIT 50', args: [conversation, conversation, id] }]))[0];
37
+ if (!rows.length)
38
+ break;
39
+ await database(rows.flatMap(row => { const record = JSON.parse(row.record); return [{ sql: 'UPDATE records SET sort_key=? WHERE conversation=? AND id=? AND record=?', args: [durableHistorySortKey(record.message), row.conversation, row.id, row.record] }, indexMedia(row.conversation, row.id, record), indexSearch(row.conversation, row.id, record)]; }));
40
+ conversation = rows.at(-1).conversation;
41
+ id = rows.at(-1).id;
42
+ }
43
+ await database([{ sql: "INSERT OR REPLACE INTO history_format(name,value) VALUES('utc-order',1),('media-order',1),('search-words',1)", args: [] }]);
44
+ })();
45
+ void ready.catch(() => { });
46
+ const run = async (sql, args) => { await ready; return database([{ sql, args }]); };
47
+ const generation = async () => Number((await run('SELECT epoch FROM history_control WHERE id=1', []))[0][0].epoch);
48
+ const readMany = async (conversation, ids) => {
49
+ if (ids.length > 100 || ids.some(id => typeof id !== 'string' || !id || id.length > 200))
50
+ throw Error('Choose up to 100 history messages.');
51
+ if (!ids.length)
52
+ return [];
53
+ const rows = await run(`SELECT record FROM records WHERE conversation=? AND id IN(${ids.map(() => '?').join(',')})`, [conversation, ...ids]);
54
+ return rows[0].map(row => JSON.parse(row.record));
55
+ };
56
+ return {
57
+ durable: true, readMany, generation,
58
+ ...nativeHistoryAuthorization(database, ready),
59
+ async cursor(conversation) { const rows = await run('SELECT cursor FROM cursors WHERE conversation=?', [conversation]); return rows[0][0]?.cursor ?? '0'; },
60
+ async read(conversationId, id) { const rows = await run('SELECT record FROM records WHERE conversation=? AND id=?', [conversationId, id]); return rows[0][0] ? JSON.parse(rows[0][0].record) : null; },
61
+ async inspect(conversationId, id) { const rows = await run('SELECT c.epoch,r.record FROM history_control c LEFT JOIN records r ON r.conversation=? AND r.id=? WHERE c.id=1', [conversationId, id]); const row = rows[0][0]; return { generation: Number(row.epoch), record: row.record ? JSON.parse(row.record) : null }; },
62
+ async page(conversationId, before, limit = 50) {
63
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100)
64
+ throw Error('Choose a history page size from 1 to 100.');
65
+ const rows = await run(`SELECT record FROM records WHERE conversation=? AND deleted=0${before ? ' AND sort_key < (SELECT sort_key FROM records WHERE conversation=? AND id=?)' : ''} ORDER BY sort_key DESC LIMIT ?`, [conversationId, ...(before ? [conversationId, before] : []), limit]);
66
+ return rows[0].map(row => JSON.parse(row.record)).reverse();
67
+ },
68
+ async query(conversationId, query) {
69
+ const limit = query.limit ?? 50;
70
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100 || query.before && query.after)
71
+ throw Error('Choose a valid history range.');
72
+ const anchor = query.before ?? query.after;
73
+ if (anchor && (!anchor.id || !Number.isFinite(Date.parse(anchor.createdAt))))
74
+ throw Error('Choose a valid history boundary.');
75
+ const ascending = Boolean(query.after);
76
+ const rows = await run(`SELECT record FROM records WHERE conversation=? AND deleted=0${anchor ? ` AND sort_key ${ascending ? '>' : '<'} ?` : ''} ORDER BY sort_key ${ascending ? 'ASC' : 'DESC'} LIMIT ?`, [conversationId, ...(anchor ? [durableHistorySortKey(anchor)] : []), limit]);
77
+ const values = rows[0].map(row => JSON.parse(row.record));
78
+ return ascending ? values : values.reverse();
79
+ },
80
+ async mediaPage(conversation, before, limit = 30) {
81
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100 || before !== undefined && (typeof before !== 'string' || !before || before.length > 200))
82
+ throw Error('Choose a valid media page.');
83
+ const rows = await run(`SELECT r.record FROM history_media g JOIN records r ON r.conversation=g.conversation AND r.id=g.id WHERE g.conversation=? AND g.position IS NOT NULL AND r.deleted=0${before ? ' AND g.position<?' : ''} ORDER BY g.position DESC LIMIT ?`, [conversation, ...(before ? [before.padStart(36, '0')] : []), limit]);
84
+ return rows[0].map(row => JSON.parse(row.record));
85
+ },
86
+ async searchPage(conversation, query, before, limit = 51) {
87
+ if (typeof query !== 'string' || query.length > 200 || !query.trim() || !Number.isInteger(limit) || limit < 1 || limit > 100 || before !== undefined && !/^[1-9][0-9]{0,18}$/.test(before))
88
+ throw Error('Choose a valid search page.');
89
+ const words = durableHistorySearchWords(query);
90
+ if (!words.length)
91
+ return [];
92
+ const rows = await run(`SELECT r.record FROM history_search s JOIN records r ON r.conversation=s.conversation AND r.id=s.id WHERE s.conversation=? AND s.words IS NOT NULL AND r.deleted=0${before ? ' AND s.position<?' : ''} AND ${words.map(() => "instr(s.words,?)>0").join(' AND ')} ORDER BY s.position DESC LIMIT ?`, [conversation, ...(before ? [before.padStart(36, '0')] : []), ...words.map(word => ' ' + word + ' '), limit]);
93
+ return rows[0].map(row => JSON.parse(row.record));
94
+ },
95
+ async searchInboxPage(query, before, limit = 51) {
96
+ if (typeof query !== 'string' || query.length > 200 || !query.trim() || !Number.isInteger(limit) || limit < 1 || limit > 100 || before !== undefined && !/^[1-9][0-9]{0,18}$/.test(before))
97
+ throw Error('Choose a valid search page.');
98
+ const words = durableHistorySearchWords(query);
99
+ if (!words.length)
100
+ return [];
101
+ const rows = await run(`SELECT r.record FROM history_search s JOIN records r ON r.conversation=s.conversation AND r.id=s.id WHERE s.words IS NOT NULL AND r.deleted=0 AND s.id NOT GLOB '*[^0-9]*'${before ? ' AND s.position<?' : ''} AND ${words.map(() => "instr(s.words,?)>0").join(' AND ')} ORDER BY s.position DESC LIMIT ?`, [...(before ? [before.padStart(36, '0')] : []), ...words.map(word => ' ' + word + ' '), limit]);
102
+ return rows[0].map(row => JSON.parse(row.record));
103
+ },
104
+ async commit(batch) {
105
+ await ready;
106
+ const expected = batch.expectedGeneration ?? await generation();
107
+ if (!Number.isSafeInteger(expected) || expected < 0)
108
+ throw Error('History storage changed.');
109
+ if (typeof batch.cursor !== 'string' || !/^(0|[1-9][0-9]{0,29})$/.test(batch.cursor))
110
+ throw Error('Invalid history position.');
111
+ const previousRows = new Map((await readMany(batch.conversationId, batch.records.map(r => r.message.id))).map(r => [r.message.id, r]));
112
+ const commands = [{ sql: 'INSERT OR REPLACE INTO history_write_guard(id,epoch) VALUES(1,CASE WHEN (SELECT epoch FROM history_control WHERE id=1)=? THEN ? ELSE NULL END)', args: [expected, expected] }];
113
+ for (const record of batch.records) {
114
+ const m = record.message, revision = m.revision ?? 0;
115
+ const previous = previousRows.get(m.id);
116
+ if (previous && (previous.message.revision ?? 0) === revision && historyContentIdentity(previous.message) !== historyContentIdentity(m))
117
+ throw Error('Conflicting history revision.');
118
+ // The predicate executes within the same native transaction as insertion.
119
+ // It protects another client instance, retries and old backup restoration.
120
+ // A same-revision concurrent change fails the NOT NULL constraint instead
121
+ // of silently overwriting content checked outside this native transaction.
122
+ commands.push({ sql: 'INSERT OR REPLACE INTO records(conversation,id,sort_key,revision,deleted,record,receipt,ack_pending) SELECT ?,?,?,?,?,CASE WHEN EXISTS(SELECT 1 FROM records WHERE conversation=? AND id=? AND revision=? AND record IS NOT ?) THEN NULL ELSE ? END,?,COALESCE((SELECT ack_pending FROM records WHERE conversation=? AND id=? AND receipt IS ?),?) WHERE NOT EXISTS(SELECT 1 FROM records WHERE conversation=? AND id=? AND (revision>? OR (deleted=1 AND ?=0)))', args: [batch.conversationId, m.id, durableHistorySortKey(m), revision, m.deleted ? 1 : 0, batch.conversationId, m.id, revision, previous ? JSON.stringify(previous) : null, JSON.stringify(record), record.receipt ?? null, batch.conversationId, m.id, record.receipt ?? null, record.receipt ? 1 : 0, batch.conversationId, m.id, revision, m.deleted ? 1 : 0] });
123
+ commands.push(indexMedia(batch.conversationId, m.id, record));
124
+ }
125
+ // Keep the original 100-message commit atomic within the installed native
126
+ // limits (250 commands, 8 KiB SQL per statement), without copying JSON
127
+ // bodies again just to derive their search index.
128
+ for (let offset = 0; offset < batch.records.length; offset += 40) {
129
+ const rows = batch.records.slice(offset, offset + 40);
130
+ commands.push({ sql: 'INSERT OR REPLACE INTO history_search(conversation,id,position,words) ' + rows.map(() => searchSelection).join(' UNION ALL '), args: rows.flatMap(record => searchArgs(batch.conversationId, record.message.id, record)) });
131
+ }
132
+ commands.push({ sql: 'INSERT OR REPLACE INTO cursors(conversation,cursor) SELECT ?,? WHERE NOT EXISTS(SELECT 1 FROM cursors WHERE conversation=? AND (length(cursor)>length(?) OR (length(cursor)=length(?) AND cursor>=?)))', args: [batch.conversationId, batch.cursor, batch.conversationId, batch.cursor, batch.cursor, batch.cursor] });
133
+ if (batch.records.some(record => { const previous = previousRows.get(record.message.id); return previous?.original && previous.original.sha256 !== record.original?.sha256; }))
134
+ commands.push({ sql: "INSERT INTO history_format(name,value) VALUES('cleanup-needed',1) ON CONFLICT(name) DO UPDATE SET value=value+1", args: [] });
135
+ await database(commands);
136
+ },
137
+ async maintain() {
138
+ if (!options?.clearConversation)
139
+ return;
140
+ await ready;
141
+ const now = Date.now(), cutoff = now - 86400000;
142
+ const state = await database([{ sql: "SELECT name,value FROM history_format WHERE name IN('cleanup-needed','cleanup-time')", args: [] }, { sql: 'SELECT session FROM backup_sessions WHERE touched>? LIMIT 1', args: [cutoff] }]);
143
+ if (state[1].length)
144
+ return;
145
+ const values = new Map(state[0].map(row => [row.name, Number(row.value)]));
146
+ if (!values.has('cleanup-needed') && (values.get('cleanup-time') ?? 0) > cutoff)
147
+ return;
148
+ // Advancing the epoch and removing files are one native queue operation.
149
+ // A download started before maintenance cannot subsequently commit a
150
+ // receipt for an original which this operation has removed.
151
+ await options.clearConversation([
152
+ { sql: 'UPDATE history_control SET epoch=CASE WHEN EXISTS(SELECT 1 FROM backup_sessions WHERE touched>?) THEN NULL ELSE epoch+1 END WHERE id=1', args: [cutoff] },
153
+ ...['backup_records', 'backup_merge_guards', 'backup_media', 'backup_search'].map(table => ({ sql: `DELETE FROM ${table} WHERE session IN(SELECT session FROM backup_sessions WHERE touched<=?)`, args: [cutoff] })),
154
+ { sql: 'DELETE FROM backup_sessions WHERE touched<=?', args: [cutoff] },
155
+ nativeHistoryPreviewTable,
156
+ { sql: `DELETE FROM history_previews WHERE NOT EXISTS(SELECT 1 FROM records WHERE instr(record,'"sha256":"'||history_previews.sha||'"')>0)`, args: [] },
157
+ ]);
158
+ // Record success only after native file deletion succeeds; a disk error is
159
+ // retried on the next sync rather than losing the durable cleanup marker.
160
+ await database([{ sql: "INSERT OR REPLACE INTO history_format(name,value) VALUES('cleanup-time',?)", args: [now] }, { sql: "DELETE FROM history_format WHERE name='cleanup-needed' AND value=?", args: [values.get('cleanup-needed') ?? 0] }]);
161
+ },
162
+ async pendingReceipts(limit) { const rows = await run('SELECT receipt FROM records WHERE ack_pending=1 AND receipt IS NOT NULL LIMIT ?', [Math.max(1, Math.min(100, limit))]); return rows[0].map(row => row.receipt); },
163
+ async pendingReceiptRecords(limit, conversation) { const rows = await run('SELECT record FROM records WHERE ack_pending=1 AND receipt IS NOT NULL' + (conversation === undefined ? '' : ' AND conversation=?') + ' LIMIT ?', [...(conversation === undefined ? [] : [conversation]), Math.max(1, Math.min(100, limit))]); return rows[0].map(row => JSON.parse(row.record)); },
164
+ async confirmReceipts(receipts) { if (!receipts.length)
165
+ return; await ready; await database(receipts.map(receipt => ({ sql: 'UPDATE records SET ack_pending=0 WHERE receipt=?', args: [receipt] }))); },
166
+ async clear(conversationId) {
167
+ await ready;
168
+ await (conversationId === undefined ? (options?.clearAll ?? database) : (options?.clearConversation ?? database))([
169
+ { sql: 'CREATE TABLE IF NOT EXISTS history_control(id INTEGER PRIMARY KEY,epoch INTEGER NOT NULL)', args: [] },
170
+ { sql: 'INSERT OR IGNORE INTO history_control(id,epoch) VALUES(1,0)', args: [] },
171
+ { sql: 'UPDATE history_control SET epoch=epoch+1 WHERE id=1', args: [] },
172
+ ...nativeHistoryBackupTables,
173
+ // A clear invalidates all in-flight backup sessions through the epoch.
174
+ // Erase their snapshots/staging metadata in the same transaction too.
175
+ { sql: 'DELETE FROM backup_records', args: [] },
176
+ { sql: 'DELETE FROM backup_merge_guards', args: [] },
177
+ { sql: 'DELETE FROM backup_media', args: [] },
178
+ { sql: 'DELETE FROM backup_search', args: [] },
179
+ { sql: 'DELETE FROM backup_sessions', args: [] },
180
+ ...['records', 'cursors', 'history_media', 'history_search', 'history_authorization', 'history_authorized_records'].map(table => ({ sql: `DELETE FROM ${table}${conversationId === undefined ? '' : ' WHERE conversation=?'}`, args: conversationId === undefined ? [] : [conversationId] })),
181
+ nativeHistoryPreviewTable,
182
+ { sql: conversationId === undefined ? 'DELETE FROM history_previews' : `DELETE FROM history_previews WHERE NOT EXISTS(SELECT 1 FROM records WHERE instr(record,'"sha256":"'||history_previews.sha||'"')>0)`, args: [] },
183
+ ]);
184
+ },
185
+ };
186
+ }
@@ -39,6 +39,8 @@ export declare class NativeMessagingOutbox implements MessagingOutbox {
39
39
  load(cid: string): Promise<{
40
40
  draft: string;
41
41
  messages: {
42
+ screeningFailure?: boolean;
43
+ retrySafety?: boolean;
42
44
  retry?: import("@robono/messaging").OutgoingRetry;
43
45
  clientMessageId: string;
44
46
  createdAt: string;
@@ -0,0 +1,4 @@
1
+ import { type MessagingClient, type MessagingRequest } from '@robono/messaging';
2
+ /** Own clients inside the effect lifecycle, including React Strict Mode's
3
+ * setup/cleanup/setup cycle. Never reuse a disposed reviewer session. */
4
+ export declare function useMessagingOversightSession(request: MessagingRequest, reviewerId: string, subjectId: string, conversationId: string): MessagingClient | null;
@@ -0,0 +1,14 @@
1
+ import { useEffect, useState } from 'react';
2
+ import { createMessagingOversightClient } from '@robono/messaging';
3
+ /** Own clients inside the effect lifecycle, including React Strict Mode's
4
+ * setup/cleanup/setup cycle. Never reuse a disposed reviewer session. */
5
+ export function useMessagingOversightSession(request, reviewerId, subjectId, conversationId) {
6
+ const [session, setSession] = useState(null);
7
+ useEffect(() => {
8
+ const client = createMessagingOversightClient({ request, reviewerId, subjectId, pollIntervalMs: 5000 });
9
+ setSession({ request, reviewerId, subjectId, conversationId, client });
10
+ void client.open(conversationId).catch(() => { });
11
+ return () => client.dispose();
12
+ }, [request, reviewerId, subjectId, conversationId]);
13
+ return session?.request === request && session.reviewerId === reviewerId && session.subjectId === subjectId && session.conversationId === conversationId ? session.client : null;
14
+ }