Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
feat(mobile): Add note sharing and access controls (#2361)
Chad Pihacb4a7b2d96a1
diff --git a/openwhispr-mobile/CONTRIBUTING.md b/openwhispr-mobile/CONTRIBUTING.mdindex 3099ed96d..b6bba2152 100644--- a/openwhispr-mobile/CONTRIBUTING.md+++ b/openwhispr-mobile/CONTRIBUTING.md@@ -78,6 +78,8 @@ Use [.env.example](./.env.example) as the canonical variable reference. It groupVariables prefixed with `EXPO_PUBLIC_` are embedded in the application bundle and must never contain secrets. Keep contributor-specific values in `.env.local`, which is ignored by Git.+Note sharing uses `https://notes.openwhispr.com` with the hosted production API. When setting a custom `EXPO_PUBLIC_API_URL`, also set `EXPO_PUBLIC_NOTES_URL` to the matching notes viewer before creating links. The viewer URL must use HTTPS, except HTTP on loopback for local development. Configure the backend's `SHARE_VIEWER_BASE_URL` to the same viewer so invitation emails open in the correct environment.+## Physical iOS Devices and ForksThe committed configuration contains OpenWhispr's production identifiers. Do not manually replace identifiers throughout the source. For a local physical-device build, set a unique identity in `.env.local`:diff --git a/openwhispr-mobile/README.md b/openwhispr-mobile/README.mdindex 0f811eb6a..ead9586db 100644--- a/openwhispr-mobile/README.md+++ b/openwhispr-mobile/README.md@@ -9,8 +9,19 @@ The mobile app lives in the main [`OpenWhispr/openwhispr`](https://github.com/Op- **Cloud, Private, or Bring Your Own Key** — choose hosted transcription, on-device inference, or your own provider key on iOS- **iOS dictation keyboard** — dictate from any text field system-wide via a custom keyboard extension- **Markdown notes** — folders, full-text search, AI-assisted cleanup+- **Note sharing** — web links, email invitations, organization domains, and viewer/editor access; Markdown and plain-text exports remain available offline- **Native iOS feel** — Liquid Glass tab bar and headers on iOS 26+, blur fallback on iOS 18+## Sharing notes++Open a note’s menu and choose **Share**. Creating a link or inviting someone uploads the latest saved draft through normal cloud sync, then uses the existing notes website for recipients. Opening the sheet does not publish a note. Private notes require an explicit cloud-sync opt-in; exports work without an account or cloud sync.++Full link tokens stay in account-scoped secure storage on the device that creates them. They survive sign-out and guest mode, and are removed when a different account signs in on the device or the account is deleted. **Invited only** sharing offers the same sign-in link invitation emails carry, so it works on any device. For link and organization sharing, a link created on another device may require **Replace link**, which invalidates the previous link, including links already sent in invitation emails. Sharing modes your organization's policy blocks are hidden, and sharing a personal note that has never been uploaded requires Pro. **Disable external sharing** permanently invalidates the link and pauses invitations and people added to the note; sharing again creates a new link and restores people added (resend invitations so their emailed links work). Access through a team space or workspace is unaffected, and grant records are kept. If cloud deletion is pending after making a note private, **Disable previous link** can revoke its old external link separately.++Sharing changes do not advance the note's content version on the server, so they never turn later edits into sync conflicts. This requires an `openwhispr-api` release that stops sharing changes from updating `notes.updated_at`; against an older API, editing a note with unsynced changes right after a sharing change can still show a sync conflict. Native device and cross-device acceptance are still required before release.++For a custom API, configure its paired notes viewer as described in [CONTRIBUTING.md](./CONTRIBUTING.md).+## Tech stackExpo SDK 55 · React 19 · expo-router (NativeTabs) · NativeWind · Zustand · Drizzle + expo-sqlite · whisper.rn · Sentrydiff --git a/openwhispr-mobile/src/components/notes/GroupedList.tsx b/openwhispr-mobile/src/components/notes/GroupedList.tsxindex 97eb99d0b..ad88f9702 100644--- a/openwhispr-mobile/src/components/notes/GroupedList.tsx+++ b/openwhispr-mobile/src/components/notes/GroupedList.tsx@@ -22,6 +22,7 @@ type GroupedListRowProps = {contentInsetLeft?: number;onPress?: () => void;onLongPress?: () => void;+ disabled?: boolean;accessibilityLabel?: string;accessibilityRole?: 'button';testID?: string;@@ -33,6 +34,7 @@ function Row({contentInsetLeft = NOTES_ROW_CONTENT_INSET,onPress,onLongPress,+ disabled,accessibilityLabel,accessibilityRole,testID,@@ -40,10 +42,14 @@ function Row({}: GroupedListRowProps) {return (<Pressable+ // An accessible row hides nested controls from VoiceOver, so only pressable rows group.+ accessible={Boolean(onPress || onLongPress)}onPress={onPress}onLongPress={onLongPress}+ disabled={disabled}accessibilityRole={accessibilityRole}accessibilityLabel={accessibilityLabel}+ accessibilityState={disabled === undefined ? undefined : { disabled }}testID={testID}className="flex-row items-center active:bg-tertiarySystemFill"style={{diff --git a/openwhispr-mobile/src/components/notes/NoteActionsMenu.tsx b/openwhispr-mobile/src/components/notes/NoteActionsMenu.tsxindex 843f30512..6c76fe200 100644--- a/openwhispr-mobile/src/components/notes/NoteActionsMenu.tsx+++ b/openwhispr-mobile/src/components/notes/NoteActionsMenu.tsx@@ -106,7 +106,6 @@ export function NoteActionsMenu({title: 'Share',image: 'square.and.arrow.up',imageColor: iconColor,- attributes: { disabled: !hasContent },},{id: PRIVACY_ID,diff --git a/openwhispr-mobile/src/components/notes/NoteShareAccessList.tsx b/openwhispr-mobile/src/components/notes/NoteShareAccessList.tsxnew file mode 100644index 000000000..adbd763fa--- /dev/null+++ b/openwhispr-mobile/src/components/notes/NoteShareAccessList.tsx@@ -0,0 +1,286 @@+import { useEffect, useState } from 'react';+import { Alert, View } from 'react-native';+import { SearchField } from '@/components/ui/SearchField';+import { Text } from '@/components/ui/Text';+import { searchNoteAccessPrincipals } from '@/data/remote/noteSharingApi';+import { confirmDestructive } from '@/lib/alerts';+import type {+ AccessPrincipalSuggestion,+ NoteAccessGrant,+ NoteAccessPrincipalType,+ NoteAccessState,+ NoteShareInvitation,+} from '@/data/remote/noteSharingTypes';+import {+ canChangeGrant,+ isGroupPrincipal,+ isPausedBySharingOff,+ isScopeGrant,+} from '@/lib/notes/noteShareAccess';+import { GroupedList } from './GroupedList';+import { ShareTextButton } from './ShareTextButton';++const PRINCIPAL_LABEL: Record<NoteAccessPrincipalType, string> = {+ user: 'Person',+ email: 'Email',+ team: 'Team',+ space: 'Team space',+ folder: 'Folder',+ workspace: 'Workspace',+};++function grantDetail(grant: NoteAccessGrant): string {+ if (isScopeGrant(grant) && grant.source !== 'direct')+ return `Inherited from ${PRINCIPAL_LABEL[grant.source].toLowerCase()}`;+ // Stored group grants are flagged inherited because their members inherit them.+ return isGroupPrincipal(grant.principal.type) ? PRINCIPAL_LABEL[grant.principal.type] : 'Direct';+}++function confirmEditor(name: string, onConfirm: () => void): void {+ Alert.alert(+ `Make ${name} an editor?`,+ 'Editors can change this note and manage who it is shared with.',+ [+ { text: 'Cancel', style: 'cancel' },+ { text: 'Make editor', onPress: onConfirm },+ ],+ );+}++interface NoteShareAccessListProps {+ remoteId?: string;+ access: NoteAccessState;+ invitations: NoteShareInvitation[];+ /** External sharing is off, which suspends stored grants and invitations on the server. */+ paused?: boolean;+ /** Organization policy allows invitations, new grants, and raising a permission to editor. */+ canInvite?: boolean;+ busy: boolean;+ onAddPrincipal?: (principal: AccessPrincipalSuggestion) => void;+ onUpdateGrant: (grant: NoteAccessGrant, permission: NoteAccessGrant['permission']) => void;+ onRemoveGrant: (grant: NoteAccessGrant) => void;+ onRevokeInvitation: (invitation: NoteShareInvitation) => void;+ onResendInvitation: (invitation: NoteShareInvitation) => void;+}++export function NoteShareAccessList({+ remoteId,+ access,+ invitations,+ paused = false,+ canInvite = true,+ busy,+ onAddPrincipal,+ onUpdateGrant,+ onRemoveGrant,+ onRevokeInvitation,+ onResendInvitation,+}: NoteShareAccessListProps) {+ const [query, setQuery] = useState('');+ const [suggestions, setSuggestions] = useState<AccessPrincipalSuggestion[]>([]);+ const [searchError, setSearchError] = useState(false);+ useEffect(() => {+ setSuggestions([]);+ setSearchError(false);+ if (!remoteId || !access.can_manage_access || query.trim().length < 2) return;+ const controller = new AbortController();+ const timer = setTimeout(() => {+ searchNoteAccessPrincipals(remoteId, query.trim(), { signal: controller.signal })+ .then((result) => {+ if (!controller.signal.aborted) setSuggestions(result.suggestions);+ })+ .catch(() => {+ if (!controller.signal.aborted) setSearchError(true);+ });+ }, 300);+ return (): void => {+ clearTimeout(timer);+ controller.abort();+ };+ }, [remoteId, access.can_manage_access, query]);+ const pending = invitations.filter((invite) => !invite.revoked_at && !invite.accepted_at);+ const invitationEmails = new Set(pending.map((invite) => invite.email.toLowerCase()));+ const grants = access.grants.filter(+ (grant) =>+ !(+ grant.id.startsWith('invite:') &&+ grant.principal.email &&+ invitationEmails.has(grant.principal.email.toLowerCase())+ ),+ );+ const existingIds = new Set(access.grants.map((grant) => grant.principal.id).filter(Boolean));+ const existingEmails = new Set([+ ...access.grants.map((grant) => grant.principal.email?.toLowerCase()).filter(Boolean),+ ...invitations+ .filter((invite) => !invite.revoked_at)+ .map((invite) => invite.email.toLowerCase()),+ ]);+ const available = suggestions.filter(+ (principal) =>+ !principal.existing_grant_id &&+ !existingIds.has(principal.id) &&+ !existingEmails.has(principal.email?.toLowerCase()) &&+ (!isGroupPrincipal(principal.type) || access.can_manage_inherited_access),+ );++ return (+ <View className="gap-2">+ <Text className="px-1 text-[13px] uppercase tracking-wider text-secondaryLabel">+ People with access+ </Text>+ {paused && (+ <Text className="px-1 text-[12px] text-secondaryLabel">+ People you added and invitations are paused until you share this note again.+ </Text>+ )}+ {access.can_manage_access && canInvite && remoteId && onAddPrincipal && (+ <View className="gap-2">+ <View className="flex-row">+ <SearchField+ accessibilityLabel="Find people or groups"+ placeholder="Find people or groups"+ value={query}+ onChangeText={setQuery}+ />+ </View>+ {searchError && (+ <Text className="text-[12px] text-systemRed">Search unavailable. Try again.</Text>+ )}+ {available.length > 0 && (+ <GroupedList dividerInset={16}>+ {available.map((principal) => (+ <GroupedList.Row+ key={`${principal.type}:${principal.id ?? principal.email}`}+ onPress={() => {+ onAddPrincipal(principal);+ setQuery('');+ }}+ disabled={busy}+ accessibilityRole="button"+ accessibilityLabel={`Grant access to ${principal.name || principal.email}`}+ >+ <Text+ className={busy ? 'text-[15px] text-tertiaryLabel' : 'text-[15px] text-label'}+ >+ {principal.name || principal.email}+ </Text>+ <Text className="text-[12px] text-secondaryLabel">+ {PRINCIPAL_LABEL[principal.type]}+ </Text>+ </GroupedList.Row>+ ))}+ </GroupedList>+ )}+ </View>+ )}+ <GroupedList dividerInset={16}>+ <GroupedList.Row>+ <View className="flex-row items-center justify-between">+ <Text className="text-[15px] font-medium text-label">+ {access.owner.name || access.owner.email || 'Owner'}+ </Text>+ <Text className="text-[13px] text-secondaryLabel">Owner</Text>+ </View>+ </GroupedList.Row>+ {grants.map((grant) => {+ const name = grant.principal.name || grant.principal.email || 'Unnamed group';+ const canEdit = canChangeGrant(access, grant);+ return (+ <GroupedList.Row key={grant.id}>+ <Text className="text-[15px] font-medium text-label">{name}</Text>+ <Text className="text-[12px] text-secondaryLabel">+ {grant.permission === 'editor' ? 'Editor' : 'Viewer'}+ {` · ${grantDetail(grant)}`}+ {grant.pending ? ' · Pending' : ''}+ {paused && isPausedBySharingOff(grant) ? ' · Paused' : ''}+ </Text>+ {canEdit && (+ <View className="flex-row gap-6">+ {(canInvite || grant.permission === 'editor') && (+ <ShareTextButton+ label={grant.permission === 'viewer' ? 'Make editor' : 'Make viewer'}+ accessibilityLabel={`${grant.permission === 'viewer' ? 'Make' : 'Change'} ${name} ${grant.permission === 'viewer' ? 'an editor' : 'a viewer'}`}+ disabled={busy}+ onPress={() =>+ grant.permission === 'viewer'+ ? confirmEditor(name, () => onUpdateGrant(grant, 'editor'))+ : onUpdateGrant(grant, 'viewer')+ }+ />+ )}+ <ShareTextButton+ label="Remove"+ accessibilityLabel={`Remove access for ${name}`}+ destructive+ disabled={busy}+ onPress={() =>+ confirmDestructive(+ 'Remove access?',+ `${name} will lose the access granted on this note.`,+ () => onRemoveGrant(grant),+ { destructiveLabel: 'Remove' },+ )+ }+ />+ </View>+ )}+ </GroupedList.Row>+ );+ })}+ {pending.map((invite) => {+ const invitationGrant = access.grants.find((grant) => grant.id === `invite:${invite.id}`);+ return (+ <GroupedList.Row key={invite.id}>+ <Text className="text-[15px] font-medium text-label">{invite.email}</Text>+ <Text className="text-[12px] text-secondaryLabel">+ Pending invitation+ {paused ? ' · Paused' : ''}+ {` · ${invite.permission === 'editor' ? 'Editor' : 'Viewer'}`}+ </Text>+ {access.can_manage_access && (+ <View className="flex-row gap-6">+ {invitationGrant && (canInvite || invite.permission === 'editor') && (+ <ShareTextButton+ label={invite.permission === 'viewer' ? 'Make editor' : 'Make viewer'}+ accessibilityLabel={`Make ${invite.email} ${invite.permission === 'viewer' ? 'an editor' : 'a viewer'}`}+ disabled={busy}+ onPress={() =>+ invite.permission === 'viewer'+ ? confirmEditor(invite.email, () =>+ onUpdateGrant(invitationGrant, 'editor'),+ )+ : onUpdateGrant(invitationGrant, 'viewer')+ }+ />+ )}+ {canInvite && !paused && (+ <ShareTextButton+ label="Resend"+ accessibilityLabel={`Resend invitation to ${invite.email}`}+ disabled={busy}+ onPress={() => onResendInvitation(invite)}+ />+ )}+ <ShareTextButton+ label="Revoke"+ accessibilityLabel={`Revoke invitation for ${invite.email}`}+ destructive+ disabled={busy}+ onPress={() =>+ confirmDestructive(+ 'Revoke invitation?',+ `${invite.email} will lose the access this invitation gave them.`,+ () => onRevokeInvitation(invite),+ { destructiveLabel: 'Revoke' },+ )+ }+ />+ </View>+ )}+ </GroupedList.Row>+ );+ })}+ </GroupedList>+ </View>+ );+}diff --git a/openwhispr-mobile/src/components/notes/NoteShareSheet.tsx b/openwhispr-mobile/src/components/notes/NoteShareSheet.tsxnew file mode 100644index 000000000..7d73f140a--- /dev/null+++ b/openwhispr-mobile/src/components/notes/NoteShareSheet.tsx@@ -0,0 +1,579 @@+import { useEffect, useState, type ReactNode } from 'react';+import {+ AccessibilityInfo,+ ActivityIndicator,+ Alert,+ Modal,+ ScrollView,+ TextInput,+ View,+ type TextStyle,+} from 'react-native';+import { useRouter } from 'expo-router';+import { useSafeAreaInsets } from 'react-native-safe-area-context';+import { Text } from '@/components/ui/Text';+import { GlassIconButton } from '@/components/ui/GlassIconButton';+import { SystemIcon } from '@/components/ui/SystemIcon';+import { INVALID_EMAIL_ERROR, useNoteSharing } from '@/hooks/useNoteSharing';+import { useSuperwallGate } from '@/hooks/useSuperwallGate';+import { SUPERWALL_PLACEMENTS } from '@/lib/superwall';+import { AppFont } from '@/lib/fonts';+import { confirmDestructive } from '@/lib/alerts';+import { isValidEmail } from '@/lib/utils';+import { iosColor } from '@/config/colors';+import { useConfigStore } from '@/store/useConfigStore';+import { useNotesStore } from '@/store/useNotesStore';+import { useUsageStore } from '@/store/useUsageStore';+import { requestSync } from '@/sync/syncEngine';+import { useSyncStore } from '@/sync/useSyncStore';+import { emailDomain, isPersonalEmailDomain } from '@/lib/notes/noteShareDomains';+import { isShareVisibilityAllowed } from '@/lib/notes/noteSharePolicy';+import { isScopeGrant } from '@/lib/notes/noteShareAccess';+import type { ShareVisibility } from '@/data/remote/noteSharingTypes';+import { GroupedList } from './GroupedList';+import { NoteShareAccessList } from './NoteShareAccessList';+import { ShareTextButton } from './ShareTextButton';++export interface NoteShareSheetProps {+ noteId: number;+ onClose: () => void;+ onFlushDraft: () => void;+ onExport: (format: 'md' | 'txt') => void;+}++const PLACEHOLDER_COLOR = iosColor('tertiaryLabel');+const EMAIL_INPUT_STYLE: TextStyle = { fontFamily: AppFont.regular, borderCurve: 'continuous' };++const VISIBILITY_REACH: Record<ShareVisibility, number> = {+ private: 0,+ invited: 1,+ domain: 2,+ link: 3,+};++const VISIBILITY_LABEL: Record<ShareVisibility, string> = {+ private: 'Only you',+ link: 'Anyone with the link',+ domain: 'Your organization',+ invited: 'Invited people',+};++/** Announces each new message to VoiceOver. */+function useAnnouncement(text: string | null): void {+ useEffect(() => {+ if (text) AccessibilityInfo.announceForAccessibility(text);+ }, [text]);+}++export function NoteShareSheet({ noteId, onClose, onFlushDraft, onExport }: NoteShareSheetProps) {+ const sharing = useNoteSharing(noteId, onFlushDraft);+ const router = useRouter();+ const insets = useSafeAreaInsets();+ const cloudBackupEnabled = useConfigStore((state) => state.config?.cloudBackupEnabled ?? true);+ const setNotePrivacy = useNotesStore((state) => state.setNotePrivacy);+ const spaces = useNotesStore((state) => state.spaces);+ const usage = useUsageStore((state) => state.usage);+ const subscriptionRequired = useSyncStore((state) => state.subscriptionRequired);+ const { register: registerSuperwallGate } = useSuperwallGate();+ const [email, setEmail] = useState('');+ const [privacyError, setPrivacyError] = useState<string | null>(null);+ const businessDomain = emailDomain(sharing.user?.email ?? '');+ const domainEligible = Boolean(businessDomain && !isPersonalEmailDomain(businessDomain));+ const note = sharing.note;+ const signedOut = !sharing.user || sharing.user.isAnonymous;+ const privateNote = note?.isPrivate === 1;+ const isTeamNote = spaces.some((space) => space.id === note?.spaceId && space.kind === 'team');+ // With backup off, an uploaded note's existing sharing stays manageable, but nothing that+ // needs a fresh upload (new links, invitations, visibility changes) can succeed.+ const backupOff = !cloudBackupEnabled && !isTeamNote;+ const localOnly = privateNote || (backupOff && !note?.remoteId);+ // A running operation loads the settings itself, including right after the note's first upload.+ const unknown = Boolean(+ note?.remoteId &&+ !sharing.state &&+ !sharing.loading &&+ !sharing.busy &&+ !localOnly &&+ !signedOut,+ );+ const canManage = sharing.state?.access.can_manage_access !== false;+ const visibility = sharing.state?.share.visibility;+ const shared = Boolean(visibility && visibility !== 'private');+ const canDisablePrevious = Boolean(privateNote && note?.remoteId && shared && canManage);+ // Adding someone to a paused share turns it back on, which restores everyone it paused.+ const pausedAccess =+ visibility === 'private' &&+ Boolean(sharing.state?.access.grants.some((grant) => !isScopeGrant(grant)));+ // Uploading a personal note is what needs Pro; a note already in the cloud stays manageable.+ const upgradeRequired =+ (usage ? !usage.isSubscribed : subscriptionRequired) && !isTeamNote && !note?.remoteId;+ // New edits to a note already in the cloud still need Pro to sync before they can be shared.+ const editsNeedPro =+ (usage ? !usage.isSubscribed : subscriptionRequired) && !isTeamNote && Boolean(note?.remoteId);+ const managed = !signedOut && !localOnly && !upgradeRequired && !sharing.loading && !unknown;+ const allowed = (target: ShareVisibility): boolean =>+ isShareVisibilityAllowed(sharing.sharingMode, target);+ const offered = (target: ShareVisibility): boolean => visibility === target || allowed(target);+ const scrollContentStyle = { paddingHorizontal: 24, paddingBottom: insets.bottom + 24, gap: 18 };+ // Waiting for the upload can be abandoned; a sharing change in flight must finish to keep its link.+ const closable = !sharing.busy || sharing.cancellable;+ const close = (): void => {+ if (closable) onClose();+ };+ useAnnouncement(sharing.error);+ useAnnouncement(privacyError);+ useAnnouncement(sharing.message);+ const openPrivacySettings = (): void => {+ onClose();+ router.push('/(account)/privacy');+ };++ const changeVisibility = (target: ShareVisibility): void => {+ if (sharing.busy || !canManage || target === visibility) return;+ if (target === 'private') {+ confirmDestructive(+ 'Disable external sharing?',+ 'Links stop working, and people you added and invited lose access. Sharing again creates a new link and restores people you added; resend invitations so their emailed links work. Access through a team space or workspace is unaffected.',+ () => sharing.setVisibility('private'),+ { destructiveLabel: 'Disable external sharing' },+ );+ return;+ }+ const apply = (): void => {+ if (target === 'domain') sharing.setVisibility(target, [businessDomain]);+ else sharing.setVisibility(target);+ };+ if (+ !visibility ||+ visibility === 'private' ||+ VISIBILITY_REACH[target] <= VISIBILITY_REACH[visibility]+ ) {+ apply();+ return;+ }+ // The existing token survives the switch, so links already sent reach the wider audience.+ Alert.alert(+ target === 'link' ? 'Make this note public?' : `Share with ${businessDomain}?`,+ target === 'link'+ ? 'Anyone with the link will be able to view this note, including anyone you already sent a link to.'+ : `Anyone signed in with an ${businessDomain} email will be able to view this note with its link.`,+ [+ { text: 'Cancel', style: 'cancel' },+ { text: target === 'link' ? 'Make public' : 'Share', onPress: apply },+ ],+ );+ };++ const modeButton = (target: ShareVisibility, label: string): ReactNode => (+ <ShareTextButton+ label={label}+ selected={visibility === target}+ disabled={sharing.busy}+ onPress={() => changeVisibility(target)}+ />+ );++ const enableCloudSync = (): void => {+ Alert.alert(+ 'Enable cloud sync?',+ 'This note will be uploaded to your account. Sharing will still require a separate action.',+ [+ { text: 'Cancel', style: 'cancel' },+ {+ text: 'Enable cloud sync',+ onPress: async () => {+ setPrivacyError(null);+ try {+ await setNotePrivacy(noteId, false);+ } catch {+ setPrivacyError('Unable to enable cloud sync. Try again.');+ }+ },+ },+ ],+ );+ };++ const replaceLink = (): void => {+ confirmDestructive(+ 'Replace link?',+ 'The previous link will stop working, including links already sent in invitation emails. Share the new link with anyone who still needs access.',+ () => sharing.replaceLink(),+ { destructiveLabel: 'Replace link' },+ );+ };++ const resumeSharing = (add: () => void): void => {+ if (!pausedAccess) {+ add();+ return;+ }+ Alert.alert(+ 'Turn sharing back on?',+ 'Adding someone turns external sharing back on, so people you added or invited before get their access back.',+ [+ { text: 'Cancel', style: 'cancel' },+ { text: 'Turn on sharing', onPress: add },+ ],+ );+ };++ const invite = (): void => {+ const address = email.trim();+ if (!address || sharing.busy) return;+ const send = async (): Promise<void> => {+ if (await sharing.inviteEmail(email)) setEmail('');+ };+ // An invalid address is reported straight away rather than after the confirmation.+ if (isValidEmail(address)) resumeSharing(send);+ else send();+ };++ const upgrade = (): void => {+ registerSuperwallGate({+ placement: SUPERWALL_PLACEMENTS.cloudSyncRequired,+ params: { source: 'note_share_sheet', isSubscribed: usage?.isSubscribed ?? false },+ feature: () => {+ useUsageStore+ .getState()+ .load(true)+ .catch(() => {})+ .finally(() => requestSync('manual'));+ },+ }).catch(() => {});+ };++ // In the sharing view, feedback sits next to the controls that trigger it rather than below the list.+ const feedback: ReactNode = (+ <>+ {sharing.error && !unknown && !(privateNote && note?.remoteId) && (+ <View className="gap-1">+ <Text accessibilityRole="alert" className="text-systemRed">+ {sharing.error}+ </Text>+ <View className="flex-row flex-wrap gap-x-6">+ {managed && editsNeedPro && (+ <ShareTextButton label="Upgrade to Pro" onPress={upgrade} />+ )}+ {managed && note?.remoteId && (+ <ShareTextButton+ label="Refresh"+ accessibilityLabel="Refresh sharing settings"+ disabled={sharing.busy}+ onPress={() => sharing.refresh()}+ />+ )}+ </View>+ </View>+ )}+ {privacyError && (+ <Text accessibilityRole="alert" className="text-systemRed">+ {privacyError}+ </Text>+ )}+ {sharing.message && (+ <Text accessibilityRole="alert" className="text-secondaryLabel">+ {sharing.message}+ </Text>+ )}+ </>+ );++ const sectionLabel = (label: string): ReactNode => (+ <Text className="px-1 text-[13px] uppercase tracking-wider text-secondaryLabel">{label}</Text>+ );++ return (+ <Modal visible animationType="slide" presentationStyle="pageSheet" onRequestClose={close}>+ <View className="flex-1 bg-systemBackground">+ <View className="flex-row items-center justify-between px-6 pb-4 pt-8">+ <Text accessibilityRole="header" className="text-[22px] font-bold text-label">+ Share note+ </Text>+ {closable && (+ <GlassIconButton onPress={close} accessibilityLabel="Close share sheet">+ <SystemIcon name="xmark" mdName="X" size={15} color="secondaryLabel" />+ </GlassIconButton>+ )}+ </View>+ <ScrollView+ keyboardShouldPersistTaps="handled"+ automaticallyAdjustKeyboardInsets+ contentContainerStyle={scrollContentStyle}+ >+ {sharing.busy && (+ <View className="flex-row items-center gap-2" accessibilityRole="alert">+ <ActivityIndicator size="small" />+ <Text className="text-[13px] text-secondaryLabel">Updating sharing…</Text>+ </View>+ )}+ {signedOut ? (+ <View className="gap-3">+ <Text className="text-secondaryLabel">Sign in to share this note online.</Text>+ <ShareTextButton+ label="Sign in"+ accessibilityLabel="Sign in to share"+ onPress={() => {+ onClose();+ router.push('/auth');+ }}+ />+ </View>+ ) : localOnly ? (+ <View className="gap-3">+ <Text className="text-secondaryLabel">+ {backupOff+ ? 'Cloud backup is off. Turn it on in Privacy & Data to share personal notes.'+ : 'Enable cloud sync for this note before sharing.'}+ </Text>+ {note?.remoteId && !sharing.loading && (+ <Text className="text-[13px] text-secondaryLabel">+ {shared+ ? 'A previous link may still be active.'+ : 'Removal of a previous cloud copy may still be pending.'}+ </Text>+ )}+ {sharing.loading && note?.remoteId && (+ <View className="flex-row items-center gap-2">+ <ActivityIndicator size="small" />+ <Text className="text-[13px] text-secondaryLabel">+ Checking previous sharing…+ </Text>+ </View>+ )}+ {sharing.error && note?.remoteId && (+ <View className="gap-2">+ <Text accessibilityRole="alert" className="text-systemRed">+ {sharing.error}+ </Text>+ <ShareTextButton label="Retry" onPress={() => sharing.refresh()} />+ </View>+ )}+ {canDisablePrevious && (+ <ShareTextButton+ label="Disable previous link"+ destructive+ disabled={sharing.busy || sharing.loading}+ onPress={() => changeVisibility('private')}+ />+ )}+ {backupOff ? (+ <ShareTextButton+ label="Open privacy settings"+ disabled={sharing.busy}+ onPress={openPrivacySettings}+ />+ ) : (+ <ShareTextButton+ label="Enable cloud sync"+ accessibilityLabel="Enable cloud sync for this note"+ disabled={sharing.busy}+ onPress={enableCloudSync}+ />+ )}+ </View>+ ) : upgradeRequired ? (+ <View className="gap-3">+ <Text className="text-secondaryLabel">+ Sharing uploads this note to your cloud account, which requires Pro.+ </Text>+ <ShareTextButton label="Upgrade to Pro" onPress={upgrade} />+ </View>+ ) : sharing.loading ? (+ <View className="flex-row items-center gap-3 py-3">+ <ActivityIndicator />+ <Text className="text-secondaryLabel">Loading sharing settings…</Text>+ </View>+ ) : unknown ? (+ <View className="gap-3">+ <Text className="text-secondaryLabel">+ {sharing.error || 'Sharing settings are unavailable.'}+ </Text>+ <ShareTextButton label="Retry" onPress={() => sharing.refresh()} />+ </View>+ ) : (+ <>+ {backupOff && (+ <View className="gap-1">+ <Text className="text-secondaryLabel">+ Cloud backup is off. Turn it on in Privacy & Data to change who this note is+ shared with.+ </Text>+ <ShareTextButton+ label="Open privacy settings"+ disabled={sharing.busy}+ onPress={openPrivacySettings}+ />+ </View>+ )}+ {sectionLabel('General access')}+ <GroupedList dividerInset={16}>+ <GroupedList.Row>+ <Text className="text-[15px] font-medium text-label">+ {shared || !isTeamNote+ ? VISIBILITY_LABEL[visibility ?? 'private']+ : 'Everyone in this team space'}+ </Text>+ {visibility === 'domain' && (+ <Text className="text-[12px] text-secondaryLabel">+ {sharing.state?.share.domain_allowlist.join(', ')}+ </Text>+ )}+ </GroupedList.Row>+ </GroupedList>+ {canManage && !backupOff && (+ <View className="gap-2">+ {sharing.sharingMode === 'domain_only' && (+ <Text className="text-[13px] text-secondaryLabel">+ Your organization only allows sharing within your company domain.+ </Text>+ )}+ {sharing.sharingMode === 'disabled' && (+ <Text className="text-[13px] text-secondaryLabel">+ Your organization does not allow sharing notes outside it.+ </Text>+ )}+ {!shared && allowed('link') && (+ <View>+ <Text className="text-[13px] text-secondaryLabel">+ Anyone with the link can view this note.+ </Text>+ <ShareTextButton+ label="Create link"+ disabled={sharing.busy}+ onPress={() => changeVisibility('link')}+ />+ </View>+ )}+ <View className="flex-row flex-wrap gap-x-6">+ {shared && offered('link') && modeButton('link', 'Anyone with link')}+ {offered('invited') && modeButton('invited', 'Invited only')}+ {domainEligible &&+ offered('domain') &&+ modeButton('domain', `Organization (${businessDomain})`)}+ </View>+ </View>+ )}+ {visibility && shared && canManage && allowed(visibility) && (+ <View className="gap-2">+ {sectionLabel('Link')}+ {sharing.hasLink ? (+ <View className="flex-row flex-wrap gap-x-6">+ <ShareTextButton+ label="Share link"+ disabled={sharing.busy}+ onPress={() => sharing.shareLink()}+ />+ <ShareTextButton+ label="Copy link"+ disabled={sharing.busy}+ onPress={() => sharing.copyLink()}+ />+ <ShareTextButton+ label="Open in browser"+ disabled={sharing.busy}+ onPress={() => sharing.openLink()}+ />+ </View>+ ) : (+ <Text className="text-[13px] text-secondaryLabel">+ The full link is unavailable on this device.+ </Text>+ )}+ {!backupOff && (+ <ShareTextButton+ label="Replace link"+ disabled={sharing.busy}+ onPress={replaceLink}+ />+ )}+ </View>+ )}+ {canManage && !backupOff && allowed('invited') && (+ <View className="gap-2">+ {sectionLabel('Invite by email')}+ <View className="flex-row items-center gap-2">+ <TextInput+ accessibilityLabel="Email address"+ className="h-12 min-w-0 flex-1 rounded-[10px] bg-tertiarySystemFill px-3 text-[15px] text-label"+ style={EMAIL_INPUT_STYLE}+ placeholder="[email protected]"+ placeholderTextColor={PLACEHOLDER_COLOR}+ autoCapitalize="none"+ autoCorrect={false}+ autoComplete="email"+ textContentType="emailAddress"+ keyboardType="email-address"+ returnKeyType="send"+ value={email}+ onChangeText={(value) => {+ setEmail(value);+ if (sharing.error === INVALID_EMAIL_ERROR) sharing.dismissError();+ }}+ onSubmitEditing={invite}+ />+ <ShareTextButton+ label="Invite"+ accessibilityLabel="Invite email"+ disabled={sharing.busy || !email.trim()}+ onPress={invite}+ />+ </View>+ </View>+ )}+ {feedback}+ {sharing.state && (+ <NoteShareAccessList+ key={`${sharing.user?.id}:${note?.remoteId}`}+ remoteId={note?.remoteId ?? undefined}+ access={sharing.state.access}+ invitations={sharing.state.invitations}+ paused={visibility === 'private'}+ canInvite={allowed('invited')}+ busy={sharing.busy}+ onAddPrincipal={+ backupOff+ ? undefined+ : (principal) => resumeSharing(() => sharing.addPrincipal(principal))+ }+ onUpdateGrant={(grant, permission) => sharing.updateGrant(grant, permission)}+ onRemoveGrant={(grant) => sharing.removeGrant(grant)}+ onRevokeInvitation={(invitation) => sharing.revokeInvitation(invitation)}+ onResendInvitation={(invitation) => sharing.resendInvitation(invitation)}+ />+ )}+ {shared && canManage && (+ <ShareTextButton+ label="Disable external sharing"+ destructive+ disabled={sharing.busy}+ onPress={() => changeVisibility('private')}+ />+ )}+ </>+ )}+ {!managed && feedback}+ <View className="gap-2">+ {sectionLabel('Export')}+ <GroupedList dividerInset={16}>+ <GroupedList.Row+ onPress={() => onExport('md')}+ accessibilityRole="button"+ accessibilityLabel="Export Markdown"+ >+ <Text className="text-[15px] text-label">Export Markdown</Text>+ </GroupedList.Row>+ <GroupedList.Row+ onPress={() => onExport('txt')}+ accessibilityRole="button"+ accessibilityLabel="Export Plain Text"+ >+ <Text className="text-[15px] text-label">Export Plain Text</Text>+ </GroupedList.Row>+ </GroupedList>+ </View>+ </ScrollView>+ </View>+ </Modal>+ );+}diff --git a/openwhispr-mobile/src/components/notes/ShareTextButton.tsx b/openwhispr-mobile/src/components/notes/ShareTextButton.tsxnew file mode 100644index 000000000..bce8a8a44--- /dev/null+++ b/openwhispr-mobile/src/components/notes/ShareTextButton.tsx@@ -0,0 +1,43 @@+import { Pressable } from 'react-native';+import { Text } from '@/components/ui/Text';++interface ShareTextButtonProps {+ label: string;+ onPress: () => void;+ disabled?: boolean;+ destructive?: boolean;+ /** Marks the current choice in a set of options; a selected option cannot be pressed again. */+ selected?: boolean;+ accessibilityLabel?: string;+}++/** A text action for the share sheet with a 44pt minimum touch target. */+export function ShareTextButton({+ label,+ onPress,+ disabled = false,+ destructive = false,+ selected,+ accessibilityLabel,+}: ShareTextButtonProps) {+ const inactive = disabled || Boolean(selected);+ const tone = selected+ ? 'font-semibold text-label'+ : disabled+ ? 'text-tertiaryLabel'+ : destructive+ ? 'text-systemRed'+ : 'text-link';+ return (+ <Pressable+ accessibilityRole="button"+ accessibilityLabel={accessibilityLabel ?? label}+ accessibilityState={{ disabled: inactive, ...(selected === undefined ? {} : { selected }) }}+ className="min-h-[44px] min-w-[44px] justify-center active:opacity-70"+ disabled={inactive}+ onPress={onPress}+ >+ <Text className={tone}>{label}</Text>+ </Pressable>+ );+}diff --git a/openwhispr-mobile/src/components/notes/__tests__/NoteShareAccessList.test.tsx b/openwhispr-mobile/src/components/notes/__tests__/NoteShareAccessList.test.tsxnew file mode 100644index 000000000..0801bc1c9--- /dev/null+++ b/openwhispr-mobile/src/components/notes/__tests__/NoteShareAccessList.test.tsx@@ -0,0 +1,430 @@+import { Alert, type AlertButton } from 'react-native';+import { act, fireEvent, render, waitFor } from '@testing-library/react-native';+import type { NoteAccessState, NoteShareInvitation } from '@/data/remote/noteSharingTypes';+import { NoteShareAccessList } from '../NoteShareAccessList';++const mockSearch = jest.fn();+jest.mock('@/data/remote/noteSharingApi', () => ({+ searchNoteAccessPrincipals: (...args: unknown[]) => mockSearch(...args),+}));++jest.mock('@/components/ui/Text', () => ({ Text: require('react-native').Text }));+jest.mock('@/components/ui/SystemIcon', () => ({ SystemIcon: () => null }));++beforeEach(() => {+ jest.spyOn(Alert, 'alert').mockImplementation(jest.fn());+});++afterEach(() => {+ jest.restoreAllMocks();+});++/** Presses the named button of the most recent confirmation. */+function confirmAlert(action: string): void {+ const buttons = (Alert.alert as jest.Mock).mock.lastCall[2] as AlertButton[];+ buttons.find((button) => button.text === action)?.onPress?.();+}++const owner = {+ type: 'user' as const,+ id: 'owner',+ email: '[email protected]',+ name: 'Owner',+ image: null,+ member_count: null,+};+const access: NoteAccessState = {+ owner,+ grants: [+ {+ id: 'grant-1',+ principal: { ...owner, id: 'person', email: '[email protected]', name: 'Person' },+ permission: 'viewer',+ source: 'direct',+ inherited: false,+ pending: false,+ created_at: '',+ updated_at: '',+ },+ ],+ my_permission: 'owner',+ can_manage_access: true,+ can_manage_inherited_access: false,+};+const invitation: NoteShareInvitation = {+ id: 'inv-1',+ email: '[email protected]',+ invited_by_user_id: 'owner',+ accepted_at: null,+ revoked_at: null,+ last_emailed_at: null,+ created_at: '',+ permission: 'viewer',+};++it('shows owner, grants, and pending invitations, and forwards permitted changes', () => {+ const updateGrant = jest.fn();+ const revokeInvitation = jest.fn();+ const screen = render(+ <NoteShareAccessList+ access={access}+ invitations={[invitation]}+ busy={false}+ onUpdateGrant={updateGrant}+ onRemoveGrant={jest.fn()}+ onRevokeInvitation={revokeInvitation}+ onResendInvitation={jest.fn()}+ />,+ );+ expect(screen.getAllByText('Owner')).toHaveLength(2);+ expect(screen.getByText('Person')).toBeTruthy();+ expect(screen.getByText('Viewer · Direct')).toBeTruthy();+ expect(screen.getByText('[email protected]')).toBeTruthy();+ fireEvent.press(screen.getByLabelText('Make Person an editor'));+ expect(updateGrant).not.toHaveBeenCalled();+ confirmAlert('Make editor');+ expect(updateGrant).toHaveBeenCalledWith(access.grants[0], 'editor');+ fireEvent.press(screen.getByLabelText('Revoke invitation for [email protected]'));+ expect(revokeInvitation).not.toHaveBeenCalled();+ confirmAlert('Cancel');+ expect(revokeInvitation).not.toHaveBeenCalled();+ fireEvent.press(screen.getByLabelText('Revoke invitation for [email protected]'));+ confirmAlert('Revoke');+ expect(revokeInvitation).toHaveBeenCalledWith(invitation);+});++it('keeps inherited grants read-only and invitation actions visible beside invite grants', () => {+ const inherited = {+ ...access.grants[0],+ id: 'scope:workspace:00000000-0000-4000-8000-000000000001',+ inherited: true,+ source: 'workspace' as const,+ };+ const screen = render(+ <NoteShareAccessList+ access={{+ ...access,+ can_manage_inherited_access: true,+ grants: [+ inherited,+ {+ ...access.grants[0],+ id: 'invite:inv-1',+ pending: true,+ principal: {+ ...access.grants[0].principal,+ name: 'Pending Person',+ email: '[email protected]',+ },+ },+ ],+ }}+ invitations={[invitation]}+ busy={false}+ onUpdateGrant={jest.fn()}+ onRemoveGrant={jest.fn()}+ onRevokeInvitation={jest.fn()}+ onResendInvitation={jest.fn()}+ />,+ );+ expect(screen.queryByLabelText('Make Person an editor')).toBeNull();+ expect(screen.getByLabelText('Revoke invitation for [email protected]')).toBeTruthy();+ expect(screen.getByLabelText('Make [email protected] an editor')).toBeTruthy();+ expect(screen.getByLabelText('Resend invitation to [email protected]')).toBeTruthy();+ expect(screen.queryByText('Pending Person')).toBeNull();+});++it('searches principals and only offers grants allowed by server permissions', async () => {+ jest.useFakeTimers();+ mockSearch.mockResolvedValue({+ suggestions: [+ {+ type: 'user',+ id: 'user-2',+ name: 'Jamie',+ email: '[email protected]',+ image: null,+ member_count: null,+ existing_grant_id: null,+ },+ {+ type: 'team',+ id: 'team-2',+ name: 'Engineering',+ email: null,+ image: null,+ member_count: 3,+ existing_grant_id: null,+ },+ ],+ });+ const onAddPrincipal = jest.fn();+ const screen = render(+ <NoteShareAccessList+ remoteId="remote-1"+ access={access}+ invitations={[]}+ busy={false}+ onAddPrincipal={onAddPrincipal}+ onUpdateGrant={jest.fn()}+ onRemoveGrant={jest.fn()}+ onRevokeInvitation={jest.fn()}+ onResendInvitation={jest.fn()}+ />,+ );+ fireEvent.changeText(screen.getByLabelText('Find people or groups'), 'jam');+ await act(async () => {+ jest.advanceTimersByTime(350);+ await Promise.resolve();+ });+ await waitFor(() => expect(screen.getByText('Jamie')).toBeTruthy());+ expect(screen.queryByText('Engineering')).toBeNull();+ fireEvent.press(screen.getByText('Jamie'));+ expect(onAddPrincipal).toHaveBeenCalledWith(expect.objectContaining({ id: 'user-2' }));+ onAddPrincipal.mockClear();+ screen.rerender(+ <NoteShareAccessList+ remoteId="remote-1"+ access={access}+ invitations={[]}+ busy+ onAddPrincipal={onAddPrincipal}+ onUpdateGrant={jest.fn()}+ onRemoveGrant={jest.fn()}+ onRevokeInvitation={jest.fn()}+ onResendInvitation={jest.fn()}+ />,+ );+ fireEvent.changeText(screen.getByLabelText('Find people or groups'), 'jam');+ await act(async () => {+ jest.advanceTimersByTime(350);+ await Promise.resolve();+ });+ fireEvent.press(screen.getByText('Jamie'));+ expect(onAddPrincipal).not.toHaveBeenCalled();+ jest.useRealTimers();+});++const teamGrant = {+ ...access.grants[0],+ id: 'grant-team',+ principal: { ...owner, type: 'team' as const, id: 'team-1', email: null, name: 'Design' },+ inherited: true,+ source: 'team' as const,+};+it.each([+ [true, true],+ [false, false],+])(+ 'lets group managers change stored team grants (can manage inherited: %s)',+ (canManageInherited, editable) => {+ const removeGrant = jest.fn();+ const screen = render(+ <NoteShareAccessList+ access={{ ...access, can_manage_inherited_access: canManageInherited, grants: [teamGrant] }}+ invitations={[]}+ busy={false}+ onUpdateGrant={jest.fn()}+ onRemoveGrant={removeGrant}+ onRevokeInvitation={jest.fn()}+ onResendInvitation={jest.fn()}+ />,+ );+ if (editable) {+ expect(screen.getByText('Viewer · Team')).toBeTruthy();+ fireEvent.press(screen.getByLabelText('Remove access for Design'));+ expect(removeGrant).not.toHaveBeenCalled();+ confirmAlert('Remove');+ expect(removeGrant).toHaveBeenCalledWith(teamGrant);+ } else {+ expect(screen.queryByLabelText('Remove access for Design')).toBeNull();+ }+ },+);++it('marks direct access and invitations as paused while external sharing is off', () => {+ const screen = render(+ <NoteShareAccessList+ access={access}+ invitations={[invitation]}+ paused+ busy={false}+ onUpdateGrant={jest.fn()}+ onRemoveGrant={jest.fn()}+ onRevokeInvitation={jest.fn()}+ onResendInvitation={jest.fn()}+ />,+ );+ expect(screen.getByText(/paused until you share this note again/i)).toBeTruthy();+ expect(screen.getByText(/Viewer · Direct · Paused/)).toBeTruthy();+ expect(screen.getByText(/Pending invitation · Paused/)).toBeTruthy();+});++const scopeGrant = {+ ...access.grants[0],+ id: 'scope:space:1',+ principal: { ...owner, type: 'space' as const, id: 'space', email: null, name: 'Design space' },+ source: 'space' as const,+ inherited: true,+};++it('stops offering Resend while sharing is paused, since the email could not open the note', () => {+ const screen = render(+ <NoteShareAccessList+ access={access}+ invitations={[invitation]}+ paused+ busy={false}+ onUpdateGrant={jest.fn()}+ onRemoveGrant={jest.fn()}+ onRevokeInvitation={jest.fn()}+ onResendInvitation={jest.fn()}+ />,+ );+ expect(screen.queryByLabelText('Resend invitation to [email protected]')).toBeNull();+ expect(screen.getByLabelText('Revoke invitation for [email protected]')).toBeTruthy();+});++it('never marks team-space membership as paused', () => {+ const screen = render(+ <NoteShareAccessList+ access={{ ...access, grants: [scopeGrant] }}+ invitations={[]}+ paused+ busy={false}+ onUpdateGrant={jest.fn()}+ onRemoveGrant={jest.fn()}+ onRevokeInvitation={jest.fn()}+ onResendInvitation={jest.fn()}+ />,+ );+ expect(screen.getByText('Viewer · Inherited from team space')).toBeTruthy();+});++it('keeps only removals when the organization blocks invitations', () => {+ const screen = render(+ <NoteShareAccessList+ remoteId="remote"+ access={access}+ invitations={[invitation]}+ canInvite={false}+ busy={false}+ onAddPrincipal={jest.fn()}+ onUpdateGrant={jest.fn()}+ onRemoveGrant={jest.fn()}+ onRevokeInvitation={jest.fn()}+ onResendInvitation={jest.fn()}+ />,+ );+ expect(screen.queryByLabelText('Find people or groups')).toBeNull();+ expect(screen.queryByLabelText('Make Person an editor')).toBeNull();+ expect(screen.queryByLabelText('Resend invitation to [email protected]')).toBeNull();+ expect(screen.getByLabelText('Remove access for Person')).toBeTruthy();+ expect(screen.getByLabelText('Revoke invitation for [email protected]')).toBeTruthy();+});++it('shows an invitation permission from the invitation itself', () => {+ const screen = render(+ <NoteShareAccessList+ access={access}+ invitations={[{ ...invitation, permission: 'editor' }]}+ busy={false}+ onUpdateGrant={jest.fn()}+ onRemoveGrant={jest.fn()}+ onRevokeInvitation={jest.fn()}+ onResendInvitation={jest.fn()}+ />,+ );+ expect(screen.getByText('Pending invitation · Editor')).toBeTruthy();+});++it('gives every action a 44pt touch target and greys it out while busy', () => {+ const screen = render(+ <NoteShareAccessList+ access={access}+ invitations={[invitation]}+ busy+ onUpdateGrant={jest.fn()}+ onRemoveGrant={jest.fn()}+ onRevokeInvitation={jest.fn()}+ onResendInvitation={jest.fn()}+ />,+ );+ for (const label of [+ 'Make Person an editor',+ 'Remove access for Person',+ 'Resend invitation to [email protected]',+ 'Revoke invitation for [email protected]',+ ]) {+ const button = screen.getByLabelText(label);+ expect(button.props.className).toContain('min-h-[44px]');+ expect(button.props.accessibilityState).toMatchObject({ disabled: true });+ }+});++it('still lets a manager reduce access when the organization blocks invitations', () => {+ const editorGrant = { ...access.grants[0], permission: 'editor' as const };+ const updateGrant = jest.fn();+ const screen = render(+ <NoteShareAccessList+ access={{+ ...access,+ grants: [+ editorGrant,+ {+ ...access.grants[0],+ id: 'invite:inv-1',+ principal: {+ ...owner,+ type: 'email',+ id: null,+ email: '[email protected]',+ name: null,+ },+ permission: 'editor' as const,+ },+ ],+ }}+ invitations={[{ ...invitation, permission: 'editor' }]}+ canInvite={false}+ busy={false}+ onUpdateGrant={updateGrant}+ onRemoveGrant={jest.fn()}+ onRevokeInvitation={jest.fn()}+ onResendInvitation={jest.fn()}+ />,+ );+ fireEvent.press(screen.getByLabelText('Change Person a viewer'));+ expect(updateGrant).toHaveBeenCalledWith(editorGrant, 'viewer');+ expect(screen.getByLabelText('Make [email protected] a viewer')).toBeTruthy();+});++/** VoiceOver can't focus an element inside another accessible element, so nested actions vanish. */+type RenderedElement = ReturnType<ReturnType<typeof render>['getByLabelText']>;+function insideAccessibleElement(element: RenderedElement): boolean {+ for (let node = element.parent; node; node = node.parent) {+ if (typeof node.type === 'string' && node.props.accessible) return true;+ }+ return false;+}+it('leaves per-person actions reachable by VoiceOver', () => {+ const screen = render(+ <NoteShareAccessList+ access={access}+ invitations={[invitation]}+ busy={false}+ onUpdateGrant={jest.fn()}+ onRemoveGrant={jest.fn()}+ onRevokeInvitation={jest.fn()}+ onResendInvitation={jest.fn()}+ />,+ );+ for (const label of [+ 'Make Person an editor',+ 'Remove access for Person',+ 'Resend invitation to [email protected]',+ 'Revoke invitation for [email protected]',+ ]) {+ expect(insideAccessibleElement(screen.getByLabelText(label))).toBe(false);+ }+});diff --git a/openwhispr-mobile/src/components/notes/__tests__/NoteShareSheet.test.tsx b/openwhispr-mobile/src/components/notes/__tests__/NoteShareSheet.test.tsxnew file mode 100644index 000000000..16937d2e0--- /dev/null+++ b/openwhispr-mobile/src/components/notes/__tests__/NoteShareSheet.test.tsx@@ -0,0 +1,666 @@+import { AccessibilityInfo, Alert } from 'react-native';+import { act, fireEvent, render, waitFor } from '@testing-library/react-native';+import { INVALID_EMAIL_ERROR, type NoteSharingController } from '@/hooks/useNoteSharing';+import { searchNoteAccessPrincipals } from '@/data/remote/noteSharingApi';+import { NoteShareSheet } from '../NoteShareSheet';++const mockController = {+ state: null,+ loading: false,+ busy: false,+ cancellable: false,+ error: null,+ message: null,+ hasLink: false,+ sharingMode: null,+ note: { id: 1, isPrivate: 0, remoteId: 'remote-1' },+ user: { id: 'user-1', email: '[email protected]' },+ refresh: jest.fn(),+ dismissError: jest.fn(),+ setVisibility: jest.fn(),+ replaceLink: jest.fn(),+ copyLink: jest.fn(),+ shareLink: jest.fn(),+ openLink: jest.fn(),+ inviteEmail: jest.fn(),+ addPrincipal: jest.fn(),+ updateGrant: jest.fn(),+ removeGrant: jest.fn(),+ revokeInvitation: jest.fn(),+ resendInvitation: jest.fn(),+} as unknown as NoteSharingController;+const mockSetNotePrivacy = jest.fn();+const mockRegisterGate = jest.fn(() => Promise.resolve(true));+const mockSpaces: { id: number; kind: string }[] = [];+let mockUsage: { isSubscribed: boolean } | null = null;++jest.mock('@/hooks/useNoteSharing', () => ({+ INVALID_EMAIL_ERROR: 'Enter a valid email address.',+ useNoteSharing: () => mockController,+}));+jest.mock('@/data/remote/noteSharingApi', () => ({ searchNoteAccessPrincipals: jest.fn() }));+jest.mock('@/components/ui/Text', () => ({ Text: require('react-native').Text }));+jest.mock('@/components/ui/SystemIcon', () => ({ SystemIcon: () => null }));+jest.mock('@/components/ui/GlassIconButton', () => ({+ GlassIconButton: ({+ onPress,+ accessibilityLabel,+ }: {+ onPress: () => void;+ accessibilityLabel: string;+ }) => {+ const { Pressable } = require('react-native');+ return <Pressable onPress={onPress} accessibilityLabel={accessibilityLabel} />;+ },+}));+jest.mock('react-native-safe-area-context', () => ({+ useSafeAreaInsets: () => ({ top: 0, right: 0, bottom: 0, left: 0 }),+}));+jest.mock('expo-router', () => ({ useRouter: () => ({ push: jest.fn() }) }));+let mockCloudBackupEnabled = true;+jest.mock('@/store/useConfigStore', () => ({+ useConfigStore: (selector: (state: { config: { cloudBackupEnabled: boolean } }) => unknown) =>+ selector({ config: { cloudBackupEnabled: mockCloudBackupEnabled } }),+}));+jest.mock('@/store/useNotesStore', () => ({+ useNotesStore: (+ selector: (state: {+ setNotePrivacy: () => Promise<void>;+ spaces: { id: number; kind: string }[];+ }) => unknown,+ ) => selector({ setNotePrivacy: mockSetNotePrivacy, spaces: mockSpaces }),+}));+jest.mock('@/store/useUsageStore', () => ({+ useUsageStore: Object.assign(+ (selector: (state: { usage: typeof mockUsage }) => unknown) => selector({ usage: mockUsage }),+ { getState: () => ({ load: () => Promise.resolve() }) },+ ),+}));+let mockSubscriptionRequired = false;+jest.mock('@/sync/useSyncStore', () => ({+ useSyncStore: (selector: (state: { subscriptionRequired: boolean }) => unknown) =>+ selector({ subscriptionRequired: mockSubscriptionRequired }),+}));+jest.mock('@/sync/syncEngine', () => ({ requestSync: jest.fn() }));+jest.mock('@/hooks/useSuperwallGate', () => ({+ useSuperwallGate: () => ({ register: mockRegisterGate }),+}));++const share = {+ visibility: 'private' as const,+ token_prefix: null,+ domain_allowlist: [],+ updated_at: null,+ updated_by_user_id: null,+};+const access = {+ owner: {+ type: 'user' as const,+ id: 'owner',+ name: 'Owner',+ email: '[email protected]',+ image: null,+ member_count: null,+ },+ grants: [],+ my_permission: 'owner' as const,+ can_manage_access: true,+ can_manage_inherited_access: false,+};+const pendingInvitation = {+ id: 'inv-1',+ email: '[email protected]',+ invited_by_user_id: 'owner',+ permission: 'viewer' as const,+ accepted_at: null,+ revoked_at: null,+ last_emailed_at: null,+ created_at: '',+};+const props = {+ noteId: 1,+ onClose: jest.fn(),+ onFlushDraft: jest.fn(),+ onExport: jest.fn(),+};++beforeEach(() => {+ Object.assign(mockController, {+ state: null,+ loading: false,+ busy: false,+ cancellable: false,+ error: null,+ message: null,+ hasLink: false,+ sharingMode: null,+ note: { id: 1, isPrivate: 0, remoteId: 'remote-1' },+ user: { id: 'user-1', email: '[email protected]' },+ });+ mockSpaces.length = 0;+ mockUsage = null;+ mockCloudBackupEnabled = true;+ mockSubscriptionRequired = false;+ jest.clearAllMocks();+ jest.spyOn(Alert, 'alert').mockImplementation(jest.fn());+});++it('offers invited sharing and email invitation before a new note has a remote ID', () => {+ mockController.note = { ...mockController.note!, remoteId: null };+ const screen = render(<NoteShareSheet {...props} />);+ fireEvent.press(screen.getByText('Invited only'));+ expect(mockController.setVisibility).toHaveBeenCalledWith('invited');+ fireEvent.changeText(screen.getByLabelText('Email address'), '[email protected]');+ fireEvent.press(screen.getByLabelText('Invite email'));+ expect(mockController.inviteEmail).toHaveBeenCalledWith('[email protected]');+});++it('offers the owner business domain without making a new note public', () => {+ mockController.note = { ...mockController.note!, remoteId: null };+ const screen = render(<NoteShareSheet {...props} />);+ fireEvent.press(screen.getByText('Organization (example.com)'));+ expect(mockController.setVisibility).toHaveBeenCalledWith('domain', ['example.com']);+ expect(mockController.setVisibility).not.toHaveBeenCalledWith('link');+});++it('asks for cloud sync consent before changing a private note', () => {+ mockController.note = { ...mockController.note!, isPrivate: 1 };+ const screen = render(<NoteShareSheet {...props} />);+ expect(screen.queryByText('Create link')).toBeNull();+ fireEvent.press(screen.getByText('Enable cloud sync'));+ expect((Alert.alert as jest.Mock).mock.calls[0][0]).toBe('Enable cloud sync?');+});++it('lets a private note revoke its retained cloud link without enabling sync', () => {+ mockController.note = { ...mockController.note!, isPrivate: 1 };+ mockController.state = {+ share: { ...share, visibility: 'link', token_prefix: 'abc' },+ invitations: [],+ access: {+ owner: {+ type: 'user',+ id: 'owner',+ name: 'Owner',+ email: '[email protected]',+ image: null,+ member_count: null,+ },+ grants: [],+ my_permission: 'owner',+ can_manage_access: true,+ can_manage_inherited_access: false,+ },+ };+ const screen = render(<NoteShareSheet {...props} />);+ fireEvent.press(screen.getByText('Disable previous link'));+ const buttons = (Alert.alert as jest.Mock).mock.calls[0][2];+ expect((Alert.alert as jest.Mock).mock.calls[0][1]).toMatch(/links stop working/i);+ expect((Alert.alert as jest.Mock).mock.calls[0][1]).toMatch(/new link/i);+ expect((Alert.alert as jest.Mock).mock.calls[0][1]).not.toMatch(/links.*until you share/i);+ expect((Alert.alert as jest.Mock).mock.calls[0][1]).not.toMatch(/team and space access remains/i);+ buttons[1].onPress();+ expect(mockController.setVisibility).toHaveBeenCalledWith('private');+ expect(mockSetNotePrivacy).not.toHaveBeenCalled();+ expect(props.onFlushDraft).not.toHaveBeenCalled();+});++it('does not offer private-link revocation without confirmed management permission', () => {+ mockController.note = { ...mockController.note!, isPrivate: 1 };+ mockController.state = {+ share: { ...share, visibility: 'link', token_prefix: 'abc' },+ invitations: [],+ access: {+ owner: {+ type: 'user',+ id: 'owner',+ name: 'Owner',+ email: '[email protected]',+ image: null,+ member_count: null,+ },+ grants: [],+ my_permission: 'viewer',+ can_manage_access: false,+ can_manage_inherited_access: false,+ },+ };+ const screen = render(<NoteShareSheet {...props} />);+ expect(screen.queryByText('Disable previous link')).toBeNull();+});++it('shows a failed cloud sync opt-in', async () => {+ mockController.note = { ...mockController.note!, isPrivate: 1 };+ mockSetNotePrivacy.mockRejectedValueOnce(new Error('Sync unavailable'));+ const screen = render(<NoteShareSheet {...props} />);+ fireEvent.press(screen.getByText('Enable cloud sync'));+ const buttons = (Alert.alert as jest.Mock).mock.calls[0][2];+ await act(async () => {+ await buttons[1].onPress();+ });+ expect(screen.getByText('Unable to enable cloud sync. Try again.')).toBeTruthy();+ expect(screen.queryByText('Sync unavailable')).toBeNull();+});++it('keeps both exports available when sharing settings cannot load', () => {+ mockController.error = 'Network unavailable';+ const screen = render(<NoteShareSheet {...props} />);+ expect(screen.getByText('Network unavailable')).toBeTruthy();+ expect(screen.queryByText('Create link')).toBeNull();+ fireEvent.press(screen.getByText('Retry'));+ expect(mockController.refresh).toHaveBeenCalled();+ fireEvent.press(screen.getByText('Export Markdown'));+ expect(props.onExport).toHaveBeenCalledWith('md');+});++it('creates public links only after an explicit tap', () => {+ mockController.state = { share, invitations: [], access };+ const screen = render(<NoteShareSheet {...props} />);+ expect(screen.getByText('Anyone with the link can view this note.')).toBeTruthy();+ expect(mockController.setVisibility).not.toHaveBeenCalled();+ fireEvent.press(screen.getByText('Create link'));+ expect(mockController.setVisibility).toHaveBeenCalledWith('link');+});++it('shows the actual invited setting and confirms replacement of an unavailable token', () => {+ mockController.state = {+ share: { ...share, visibility: 'invited', token_prefix: 'abc' },+ invitations: [],+ access,+ };+ const screen = render(<NoteShareSheet {...props} />);+ expect(screen.getByText('Invited people')).toBeTruthy();+ expect(screen.queryByText('Create link')).toBeNull();+ fireEvent.press(screen.getByText('Replace link'));+ const buttons = (Alert.alert as jest.Mock).mock.calls[0][2];+ expect((Alert.alert as jest.Mock).mock.calls[0][1]).toContain('previous link will stop working');+ buttons[1].onPress();+ expect(mockController.replaceLink).toHaveBeenCalled();+});++it('lets a manager replace a known link and shows a busy status', () => {+ mockController.state = {+ share: { ...share, visibility: 'link', token_prefix: 'abc' },+ invitations: [],+ access,+ };+ mockController.hasLink = true;+ mockController.busy = true;+ const screen = render(<NoteShareSheet {...props} />);+ expect(screen.getByText('Updating sharing…')).toBeTruthy();+ expect(screen.getByText('Replace link')).toBeTruthy();+ expect(screen.queryByLabelText('Close share sheet')).toBeNull();+});++it('hides link management actions when access cannot be managed', () => {+ mockController.state = {+ share: { ...share, visibility: 'link', token_prefix: 'abc' },+ invitations: [],+ access: {+ owner: {+ type: 'user',+ id: 'owner',+ name: 'Owner',+ email: '[email protected]',+ image: null,+ member_count: null,+ },+ grants: [],+ my_permission: 'viewer',+ can_manage_access: false,+ can_manage_inherited_access: false,+ },+ };+ mockController.hasLink = true;+ const screen = render(<NoteShareSheet {...props} />);+ expect(screen.queryByText('Share link')).toBeNull();+ expect(screen.queryByText('Replace link')).toBeNull();+ expect(screen.getByText('Export Markdown')).toBeTruthy();+});++it('allows legacy sharing revocation when the share endpoint authorizes access', () => {+ mockController.note = { ...mockController.note!, isPrivate: 1 };+ mockController.state = { share: { ...share, visibility: 'link' }, invitations: [], access };+ const screen = render(<NoteShareSheet {...props} />);+ expect(screen.getByText('Disable previous link')).toBeTruthy();+});++it('confirms before widening a restricted share to anyone with the link', () => {+ mockController.state = {+ share: { ...share, visibility: 'invited', token_prefix: 'abc' },+ invitations: [],+ access,+ };+ const screen = render(<NoteShareSheet {...props} />);+ fireEvent.press(screen.getByText('Anyone with link'));+ expect(mockController.setVisibility).not.toHaveBeenCalled();+ const [title, , buttons] = (Alert.alert as jest.Mock).mock.calls[0];+ expect(title).toBe('Make this note public?');+ buttons[1].onPress();+ expect(mockController.setVisibility).toHaveBeenCalledWith('link');+});++it('marks the current access mode as selected for assistive technology', () => {+ mockController.state = {+ share: { ...share, visibility: 'invited', token_prefix: 'abc' },+ invitations: [],+ access,+ };+ const screen = render(<NoteShareSheet {...props} />);+ expect(screen.getByLabelText('Invited only').props.accessibilityState).toMatchObject({+ selected: true,+ });+ expect(screen.getByLabelText('Anyone with link').props.accessibilityState).toMatchObject({+ selected: false,+ });+});++it('shows paused direct access after external sharing is disabled', () => {+ mockController.state = { share, invitations: [pendingInvitation], access };+ const screen = render(<NoteShareSheet {...props} />);+ expect(screen.getByText(/Pending invitation · Paused/)).toBeTruthy();+});++it('confirms before widening invited-only sharing to the organization', () => {+ mockController.state = {+ share: { ...share, visibility: 'invited', token_prefix: 'abc' },+ invitations: [],+ access,+ };+ const screen = render(<NoteShareSheet {...props} />);+ fireEvent.press(screen.getByText('Organization (example.com)'));+ expect(mockController.setVisibility).not.toHaveBeenCalled();+ const [title, , buttons] = (Alert.alert as jest.Mock).mock.calls[0];+ expect(title).toBe('Share with example.com?');+ buttons[1].onPress();+ expect(mockController.setVisibility).toHaveBeenCalledWith('domain', ['example.com']);+});++it('narrows sharing without asking', () => {+ mockController.state = {+ share: { ...share, visibility: 'link', token_prefix: 'abc' },+ invitations: [],+ access,+ };+ const screen = render(<NoteShareSheet {...props} />);+ fireEvent.press(screen.getByText('Invited only'));+ expect(Alert.alert).not.toHaveBeenCalled();+ expect(mockController.setVisibility).toHaveBeenCalledWith('invited');+});++it('describes a private team-space note as shared with the space', () => {+ mockSpaces.push({ id: 7, kind: 'team' });+ mockController.note = {+ ...mockController.note!,+ spaceId: 7,+ } as typeof mockController.note;+ mockController.state = { share, invitations: [], access };+ const screen = render(<NoteShareSheet {...props} />);+ expect(screen.getByText('Everyone in this team space')).toBeTruthy();+ expect(screen.queryByText('Only you')).toBeNull();+});++it('warns that replacing a link breaks links in invitation emails', () => {+ mockController.state = {+ share: { ...share, visibility: 'link', token_prefix: 'ow_share_abcdefg' },+ invitations: [pendingInvitation],+ access,+ };+ const screen = render(<NoteShareSheet {...props} />);+ fireEvent.press(screen.getByText('Replace link'));+ expect((Alert.alert as jest.Mock).mock.calls[0][1]).toMatch(/invitation emails/i);+});++it('clears the email field only after a confirmed invitation', async () => {+ jest.mocked(mockController.inviteEmail).mockResolvedValueOnce(false).mockResolvedValueOnce(true);+ mockController.state = { share, invitations: [], access };+ const screen = render(<NoteShareSheet {...props} />);+ const input = screen.getByLabelText('Email address');+ fireEvent.changeText(input, '[email protected]');+ await act(async () => {+ fireEvent.press(screen.getByLabelText('Invite email'));+ });+ expect(screen.getByLabelText('Email address').props.value).toBe('[email protected]');+ await act(async () => {+ fireEvent.press(screen.getByLabelText('Invite email'));+ });+ expect(screen.getByLabelText('Email address').props.value).toBe('');+});++it('can be closed while the note is still uploading, but not while sharing is saved', () => {+ mockController.busy = true;+ mockController.cancellable = true;+ const screen = render(<NoteShareSheet {...props} />);+ fireEvent.press(screen.getByLabelText('Close share sheet'));+ expect(props.onClose).toHaveBeenCalled();+ mockController.cancellable = false;+ screen.rerender(<NoteShareSheet {...props} />);+ expect(screen.queryByLabelText('Close share sheet')).toBeNull();+});++it('does not flash the pending-removal note while checking a private note', () => {+ mockController.note = { ...mockController.note!, isPrivate: 1 };+ mockController.loading = true;+ const screen = render(<NoteShareSheet {...props} />);+ expect(screen.getByText('Checking previous sharing…')).toBeTruthy();+ expect(screen.queryByText(/Removal of a previous cloud copy/)).toBeNull();+});++it('offers only domain sharing under a domain-only organization policy', () => {+ mockController.user = { id: 'user-1', email: '[email protected]' } as typeof mockController.user;+ mockController.sharingMode = 'domain_only';+ mockController.state = { share, invitations: [], access };+ const screen = render(<NoteShareSheet {...props} />);+ expect(screen.getByText(/only allows sharing within your company/i)).toBeTruthy();+ expect(screen.queryByText('Create link')).toBeNull();+ expect(screen.queryByText('Invited only')).toBeNull();+ expect(screen.queryByLabelText('Email address')).toBeNull();+ fireEvent.press(screen.getByText('Organization (company.com)'));+ expect(mockController.setVisibility).toHaveBeenCalledWith('domain', ['company.com']);+});++it('keeps only disabling when the organization does not allow external sharing', () => {+ mockController.sharingMode = 'disabled';+ mockController.hasLink = true;+ mockController.state = {+ share: { ...share, visibility: 'link', token_prefix: 'ow_share_abcdefg' },+ invitations: [],+ access,+ };+ const screen = render(<NoteShareSheet {...props} />);+ expect(screen.getByText(/does not allow sharing notes outside/i)).toBeTruthy();+ expect(screen.queryByText('Invited only')).toBeNull();+ expect(screen.queryByText('Copy link')).toBeNull();+ expect(screen.queryByText('Replace link')).toBeNull();+ expect(screen.getByText('Disable external sharing')).toBeTruthy();+});++it('offers an upgrade before uploading a personal note without a subscription', () => {+ mockUsage = { isSubscribed: false };+ mockController.note = { ...mockController.note!, remoteId: null };+ const screen = render(<NoteShareSheet {...props} />);+ expect(screen.queryByText('Create link')).toBeNull();+ fireEvent.press(screen.getByText('Upgrade to Pro'));+ expect(mockRegisterGate).toHaveBeenCalledWith(+ expect.objectContaining({ placement: 'cloud_sync_required' }),+ );+});++it('greys out link actions while an operation runs', () => {+ mockController.busy = true;+ mockController.hasLink = true;+ mockController.state = {+ share: { ...share, visibility: 'link', token_prefix: 'ow_share_abcdefg' },+ invitations: [],+ access,+ };+ const screen = render(<NoteShareSheet {...props} />);+ for (const label of ['Share link', 'Copy link', 'Open in browser', 'Replace link']) {+ expect(screen.getByLabelText(label).props.accessibilityState).toMatchObject({ disabled: true });+ }+});++it('keeps the sheet open while a previous link is being disabled', () => {+ mockCloudBackupEnabled = false;+ mockController.busy = true;+ mockController.note = { ...mockController.note!, isPrivate: 1 };+ mockController.state = {+ share: { ...share, visibility: 'link', token_prefix: 'ow_share_abcdefg' },+ invitations: [],+ access,+ };+ const screen = render(<NoteShareSheet {...props} />);+ expect(screen.getByLabelText('Open privacy settings').props.accessibilityState).toMatchObject({+ disabled: true,+ });+});++it('keeps existing sharing manageable but blocks uploads while cloud backup is off', () => {+ mockCloudBackupEnabled = false;+ mockController.hasLink = true;+ mockController.state = {+ share: { ...share, visibility: 'link', token_prefix: 'ow_share_abcdefg' },+ invitations: [pendingInvitation],+ access,+ };+ const screen = render(<NoteShareSheet {...props} />);+ expect(screen.getByText(/Cloud backup is off\. Turn it on in Privacy & Data/)).toBeTruthy();+ expect(screen.getByText('Open privacy settings')).toBeTruthy();+ expect(screen.getByText('[email protected]')).toBeTruthy();+ expect(screen.getByLabelText('Revoke invitation for [email protected]')).toBeTruthy();+ expect(screen.getByText('Copy link')).toBeTruthy();+ expect(screen.queryByText('Invite by email')).toBeNull();+ expect(screen.queryByText('Replace link')).toBeNull();+ expect(screen.queryByText('Invited only')).toBeNull();+ expect(screen.queryByLabelText('Find people or groups')).toBeNull();+ fireEvent.press(screen.getByText('Disable external sharing'));+ const buttons = (Alert.alert as jest.Mock).mock.calls[0][2];+ buttons[1].onPress();+ expect(mockController.setVisibility).toHaveBeenCalledWith('private');+});++it('points a never-uploaded personal note at privacy settings while cloud backup is off', () => {+ mockCloudBackupEnabled = false;+ mockController.note = { ...mockController.note!, remoteId: null };+ const screen = render(<NoteShareSheet {...props} />);+ expect(screen.getByText(/Cloud backup is off/)).toBeTruthy();+ expect(screen.getByText('Open privacy settings')).toBeTruthy();+ expect(screen.queryByText('Create link')).toBeNull();+ expect(screen.queryByText('Invite by email')).toBeNull();+});++it('marks the sheet title as a heading', () => {+ const screen = render(<NoteShareSheet {...props} />);+ expect(screen.getByRole('header', { name: 'Share note' })).toBeTruthy();+});++it('offers Pro when new edits to a synced note cannot sync without it', () => {+ mockSubscriptionRequired = true;+ mockController.state = { share, invitations: [], access };+ mockController.error = 'An active subscription is required to sync this note.';+ const screen = render(<NoteShareSheet {...props} />);+ fireEvent.press(screen.getByText('Upgrade to Pro'));+ expect(mockRegisterGate).toHaveBeenCalled();+});++it('shows errors beside the controls with a way to refresh', () => {+ mockController.state = { share, invitations: [], access };+ mockController.error = 'Sharing settings changed. Refresh and try again.';+ const spy = jest.spyOn(AccessibilityInfo, 'announceForAccessibility');+ const screen = render(<NoteShareSheet {...props} />);+ expect(spy).toHaveBeenCalledWith('Sharing settings changed. Refresh and try again.');+ expect(screen.queryByText('Upgrade to Pro')).toBeNull();+ fireEvent.press(screen.getByLabelText('Refresh sharing settings'));+ expect(mockController.refresh).toHaveBeenCalled();+ fireEvent.changeText(screen.getByLabelText('Email address'), 'friend@');+ expect(mockController.dismissError).not.toHaveBeenCalled();+});++it('clears an invalid email error once the address is edited', () => {+ mockController.state = { share, invitations: [], access };+ mockController.error = INVALID_EMAIL_ERROR;+ const screen = render(<NoteShareSheet {...props} />);+ fireEvent.changeText(screen.getByLabelText('Email address'), '[email protected]');+ expect(mockController.dismissError).toHaveBeenCalled();+});++it('does not offer Pro to a subscriber whose sync check failed', () => {+ mockUsage = { isSubscribed: true };+ mockSubscriptionRequired = true;+ mockController.state = { share, invitations: [], access };+ mockController.error = 'Can’t reach OpenWhispr. Check your connection and try again.';+ const screen = render(<NoteShareSheet {...props} />);+ expect(screen.queryByText('Upgrade to Pro')).toBeNull();+});++const pausedGrant = {+ id: 'grant-1',+ principal: { ...access.owner, id: 'user-2', name: 'Jamie', email: '[email protected]' },+ permission: 'viewer' as const,+ source: 'direct' as const,+ inherited: false,+ pending: false,+ created_at: '',+ updated_at: '',+};+it('keeps the controls while an operation loads settings after the first upload', () => {+ Object.assign(mockController, { busy: true, state: null });+ const screen = render(<NoteShareSheet {...props} />);+ expect(screen.queryByText('Sharing settings are unavailable.')).toBeNull();+ expect(screen.queryByText('Retry')).toBeNull();+ expect(screen.getByLabelText('Email address')).toBeTruthy();+});+it('asks before an invitation turns paused sharing back on', () => {+ mockController.state = { share, invitations: [], access: { ...access, grants: [pausedGrant] } };+ const screen = render(<NoteShareSheet {...props} />);+ fireEvent.changeText(screen.getByLabelText('Email address'), '[email protected]');+ fireEvent.press(screen.getByLabelText('Invite email'));+ expect(mockController.inviteEmail).not.toHaveBeenCalled();+ const [title, message, buttons] = (Alert.alert as jest.Mock).mock.calls[0];+ expect(title).toBe('Turn sharing back on?');+ expect(message).toMatch(/get their access back/i);+ buttons[1].onPress();+ expect(mockController.inviteEmail).toHaveBeenCalledWith('[email protected]');+});+it('reports an invalid address on a paused share without asking first', () => {+ mockController.state = { share, invitations: [], access: { ...access, grants: [pausedGrant] } };+ const screen = render(<NoteShareSheet {...props} />);+ fireEvent.changeText(screen.getByLabelText('Email address'), 'not-an-email');+ fireEvent.press(screen.getByLabelText('Invite email'));+ expect(Alert.alert).not.toHaveBeenCalled();+ expect(mockController.inviteEmail).toHaveBeenCalledWith('not-an-email');+});+it('invites without asking when no access is paused', () => {+ const inherited = { ...pausedGrant, id: 'scope:space-1', inherited: true };+ mockController.state = { share, invitations: [], access: { ...access, grants: [inherited] } };+ const screen = render(<NoteShareSheet {...props} />);+ fireEvent.changeText(screen.getByLabelText('Email address'), '[email protected]');+ fireEvent.press(screen.getByLabelText('Invite email'));+ expect(Alert.alert).not.toHaveBeenCalled();+ expect(mockController.inviteEmail).toHaveBeenCalledWith('[email protected]');+});+it('asks before adding someone turns paused sharing back on', async () => {+ jest.mocked(searchNoteAccessPrincipals).mockResolvedValue({+ suggestions: [+ {+ type: 'user',+ id: 'user-3',+ name: 'Riley',+ email: '[email protected]',+ image: null,+ member_count: null,+ existing_grant_id: null,+ },+ ],+ });+ mockController.state = { share, invitations: [], access: { ...access, grants: [pausedGrant] } };+ const screen = render(<NoteShareSheet {...props} />);+ fireEvent.changeText(screen.getByLabelText('Find people or groups'), 'ril');+ await waitFor(() => expect(screen.getByText('Riley')).toBeTruthy());+ fireEvent.press(screen.getByText('Riley'));+ expect(mockController.addPrincipal).not.toHaveBeenCalled();+ expect((Alert.alert as jest.Mock).mock.calls[0][0]).toBe('Turn sharing back on?');+ (Alert.alert as jest.Mock).mock.calls[0][2][1].onPress();+ expect(mockController.addPrincipal).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'user-3' }),+ );+});diff --git a/openwhispr-mobile/src/config/__tests__/noteSharing.test.ts b/openwhispr-mobile/src/config/__tests__/noteSharing.test.tsnew file mode 100644index 000000000..2fb6e4dc8--- /dev/null+++ b/openwhispr-mobile/src/config/__tests__/noteSharing.test.ts@@ -0,0 +1,44 @@+import { getNoteShareViewerBaseUrl } from '../noteSharing';+import { buildNoteShareUrl } from '@/lib/notes/noteShareTokens';++const token = `ow_share_${'a'.repeat(32)}`;+const originalApiUrl = process.env.EXPO_PUBLIC_API_URL;+const originalNotesUrl = process.env.EXPO_PUBLIC_NOTES_URL;++afterEach(() => {+ if (originalApiUrl === undefined) delete process.env.EXPO_PUBLIC_API_URL;+ else process.env.EXPO_PUBLIC_API_URL = originalApiUrl;+ if (originalNotesUrl === undefined) delete process.env.EXPO_PUBLIC_NOTES_URL;+ else process.env.EXPO_PUBLIC_NOTES_URL = originalNotesUrl;+});++it('uses the hosted viewer only with the hosted API', () => {+ delete process.env.EXPO_PUBLIC_API_URL;+ delete process.env.EXPO_PUBLIC_NOTES_URL;+ expect(getNoteShareViewerBaseUrl()).toBe('https://notes.openwhispr.com');+ expect(buildNoteShareUrl(token)).toBe(`https://notes.openwhispr.com/n/${token}`);+});++it('requires a paired viewer for a custom API', () => {+ process.env.EXPO_PUBLIC_API_URL = 'https://staging.example.com';+ delete process.env.EXPO_PUBLIC_NOTES_URL;+ expect(() => buildNoteShareUrl(token)).toThrow();+ process.env.EXPO_PUBLIC_NOTES_URL = 'https://notes.staging.example.com/';+ expect(buildNoteShareUrl(token)).toBe(`https://notes.staging.example.com/n/${token}`);+});++it.each([+ 'http://notes.example.com',+ 'https://user:[email protected]',+ 'https://notes.example.com?query=1',+ 'https://notes.example.com/#fragment',+])('rejects unsafe viewer base %s', (url) => {+ process.env.EXPO_PUBLIC_NOTES_URL = url;+ expect(() => getNoteShareViewerBaseUrl()).toThrow();+});++it('accepts loopback HTTP for local development', () => {+ process.env.EXPO_PUBLIC_API_URL = 'http://localhost:3000';+ process.env.EXPO_PUBLIC_NOTES_URL = 'http://127.0.0.1:3001';+ expect(buildNoteShareUrl(token)).toBe(`http://127.0.0.1:3001/n/${token}`);+});diff --git a/openwhispr-mobile/src/config/noteSharing.ts b/openwhispr-mobile/src/config/noteSharing.tsnew file mode 100644index 000000000..c5442f773--- /dev/null+++ b/openwhispr-mobile/src/config/noteSharing.ts@@ -0,0 +1,31 @@+const HOSTED_API_URL = 'https://api.openwhispr.com';+const HOSTED_VIEWER_URL = 'https://notes.openwhispr.com';++export function getNoteShareViewerBaseUrl(): string {+ const configured = process.env.EXPO_PUBLIC_NOTES_URL;+ const apiUrl = process.env.EXPO_PUBLIC_API_URL || HOSTED_API_URL;+ if (!configured && apiUrl.replace(/\/$/, '') === HOSTED_API_URL) return HOSTED_VIEWER_URL;+ if (!configured) throw new Error('Configure EXPO_PUBLIC_NOTES_URL for this API');++ let parsed: URL;+ try {+ parsed = new URL(configured);+ } catch {+ throw new Error('Invalid EXPO_PUBLIC_NOTES_URL');+ }+ const loopback =+ parsed.hostname === 'localhost' ||+ parsed.hostname === '127.0.0.1' ||+ parsed.hostname === '[::1]';+ if (+ (parsed.protocol !== 'https:' && !(parsed.protocol === 'http:' && loopback)) ||+ parsed.username ||+ parsed.password ||+ parsed.search ||+ parsed.hash ||+ parsed.pathname !== '/'+ ) {+ throw new Error('Invalid EXPO_PUBLIC_NOTES_URL');+ }+ return parsed.origin;+}diff --git a/openwhispr-mobile/src/data/local/__tests__/notesRepository.conflicts.test.ts b/openwhispr-mobile/src/data/local/__tests__/notesRepository.conflicts.test.tsindex 7180746af..178a2b2ed 100644--- a/openwhispr-mobile/src/data/local/__tests__/notesRepository.conflicts.test.ts+++ b/openwhispr-mobile/src/data/local/__tests__/notesRepository.conflicts.test.ts@@ -667,3 +667,44 @@ describe('LocalNotesRepository.resolveConflictUseServer — dirty transcript (fiexpect(repo.getPendingNotes().map((n) => n.id)).not.toContain(note.id);});});++describe('LocalNotesRepository — server copies clear a push rejection', () => {+ it('when a pull applies the server copy over a rejected upload', () => {+ const { repo } = createMemoryRepository();+ const local = repo.createNote('Title', 'Content');+ repo.setNoteClientId(local.id, 'client-1');+ repo.markNotePushed(repo.getNoteById(local.id)!, 'srv-1', '2026-08-24T09:00:00.000Z');+ repo.markNoteTerminal(local.id);++ repo.applyRemoteNote(remoteNote({ content: 'Server content' }), noFolder);++ expect(repo.getNoteById(local.id)?.content).toBe('Server content');+ expect(repo.isNotePushRejected(local.id)).toBe(false);+ });++ it('when a pull deletes a note whose last upload was rejected', () => {+ const { repo } = createMemoryRepository();+ const local = repo.createNote('Title', 'Content');+ repo.setNoteClientId(local.id, 'client-1');+ repo.markNotePushed(repo.getNoteById(local.id)!, 'srv-1', '2026-08-24T09:00:00.000Z');+ repo.markNoteTerminal(local.id);++ repo.applyRemoteNote(remoteNote({ deleted_at: '2026-08-24T10:00:00.000Z' }), noFolder);++ expect(repo.getNoteById(local.id)).toBeNull();+ expect(repo.isNotePushRejected(local.id)).toBe(false);+ });++ it('when using the server copy accepts a deletion', () => {+ const { repo } = createMemoryRepository();+ const local = repo.createNote('Title', 'Content');+ repo.setNoteClientId(local.id, 'client-1');+ repo.markNoteTerminal(local.id);+ repo.parkNoteConflict(local.id, remoteNote({ deleted_at: '2026-08-24T10:00:00.000Z' }));++ repo.resolveConflictUseServer(local.id);++ expect(repo.getNoteById(local.id)).toBeNull();+ expect(repo.isNotePushRejected(local.id)).toBe(false);+ });+});diff --git a/openwhispr-mobile/src/data/local/__tests__/notesRepository.pushRecovery.test.ts b/openwhispr-mobile/src/data/local/__tests__/notesRepository.pushRecovery.test.tsindex 7568c9305..e1dd35fac 100644--- a/openwhispr-mobile/src/data/local/__tests__/notesRepository.pushRecovery.test.ts+++ b/openwhispr-mobile/src/data/local/__tests__/notesRepository.pushRecovery.test.ts@@ -181,3 +181,28 @@ describe('LocalNotesRepository.clearSyncState', () => {expect(repo.getSyncState('notes.last_sync_at')).toBe('2026-08-24T11:00:00.000Z');});});++describe('rejected note upload tracking', () => {+ it.each(['markNoteTerminal', 'dropNotePushAttempt'] as const)(+ 'persists %s rejection until a successful acknowledgement',+ (method) => {+ const { repo } = createMemoryRepository();+ const note = repo.createNote('Title', 'Unaccepted body');+ repo[method](note.id);+ expect(repo.isNotePushRejected(note.id)).toBe(true);+ repo.markNotePushed(repo.getNoteById(note.id)!, 'remote', 'server-time', null);+ expect(repo.isNotePushRejected(note.id)).toBe(false);+ },+ );++ it('retains rejection while a newer local edit is still unacknowledged', () => {+ const { repo } = createMemoryRepository();+ const note = repo.createNote('Title', 'Body');+ repo.markNoteTerminal(note.id);+ repo.updateNote(note.id, { content: 'Newer body' });+ repo.markNotePushed(note, 'remote', 'server-time');+ expect(repo.isNotePushRejected(note.id)).toBe(true);+ repo.hardDeleteNote(note.id);+ expect(repo.isNotePushRejected(note.id)).toBe(false);+ });+});diff --git a/openwhispr-mobile/src/data/local/notesRepository.ts b/openwhispr-mobile/src/data/local/notesRepository.tsindex b3f568622..d58f6c474 100644--- a/openwhispr-mobile/src/data/local/notesRepository.ts+++ b/openwhispr-mobile/src/data/local/notesRepository.ts@@ -133,6 +133,8 @@ const NOTE_PUSH_ACK_FIELDS: ReadonlyArray<keyof Note> = ['deletedAt',];+const pushRejectedKey = (localId: number): string => `note.pushRejected.${localId}`;+export class LocalNotesRepository implements NotesRepository {private readonly database: NotesDb;@@ -844,8 +846,7 @@ export class LocalNotesRepository implements NotesRepository {if (local.pendingSync === 1) return;if (remote.deleted_at) {- this.deleteNoteChildrenAndAudio(local.id);- this.database.delete(notes).where(eq(notes.id, local.id)).run();+ this.hardDeleteNote(local.id);return;}@@ -890,6 +891,8 @@ export class LocalNotesRepository implements NotesRepository {.where(eq(notes.id, local.id)).run();+ this.clearSyncState(pushRejectedKey(local.id));+// Rebuild the transcript when the server sent a different one. Normally// gated on !hasDirtyTranscript (un-pushed local edits are authoritative// during an ordinary pull) — options.forceTranscript (resolveConflictUseServer@@ -1030,13 +1033,20 @@ export class LocalNotesRepository implements NotesRepository {).where(eq(notes.id, pushed.id)).run();+ if (unchanged) this.clearSyncState(pushRejectedKey(pushed.id));}markNoteTerminal(localId: number): void {// Clear pendingSync so the row stops re-attempting; preserve the local state// so the user still sees their attempted change. They can edit it to fix and// retry — that will re-flag pending.- this.database.update(notes).set({ pendingSync: 0 }).where(eq(notes.id, localId)).run();+ this.database.transaction((tx) => {+ tx.insert(syncState)+ .values({ key: pushRejectedKey(localId), value: '1' })+ .onConflictDoUpdate({ target: syncState.key, set: { value: '1' } })+ .run();+ tx.update(notes).set({ pendingSync: 0 }).where(eq(notes.id, localId)).run();+ });}dropNotePushAttempt(localId: number): void {@@ -1044,11 +1054,17 @@ export class LocalNotesRepository implements NotesRepository {// whatever it was before — the next pull carries the truth. Clearing// cloud_updated_at alongside pendingSync means that pull re-seeds the sync// base instead of leaving a base this device can no longer trust.- this.database- .update(notes)- .set({ pendingSync: 0, cloudUpdatedAt: null })- .where(eq(notes.id, localId))- .run();+ this.database.transaction((tx) => {+ // A cleared queue flag alone must never be mistaken for uploaded content.+ tx.insert(syncState)+ .values({ key: pushRejectedKey(localId), value: '1' })+ .onConflictDoUpdate({ target: syncState.key, set: { value: '1' } })+ .run();+ tx.update(notes)+ .set({ pendingSync: 0, cloudUpdatedAt: null })+ .where(eq(notes.id, localId))+ .run();+ });}parkNoteConflict(localId: number, serverNote: RemoteNote): void {@@ -1125,10 +1141,8 @@ export class LocalNotesRepository implements NotesRepository {// "Use server's copy" must mean accepting that, not resurrecting a// zombie local row that still points remoteId at a gone server note —// the delta-cursor pull may never re-deliver that tombstone once our- // watermark has moved past it. Mirrors applyRemoteNote's own tombstone- // path (deleteNoteChildrenAndAudio + hard delete).- this.deleteNoteChildrenAndAudio(local.id);- this.database.delete(notes).where(eq(notes.id, local.id)).run();+ // watermark has moved past it. Mirrors applyRemoteNote's tombstone path.+ this.hardDeleteNote(local.id);return;}// Bypasses applyRemoteNote's pendingSync/conflict guards on purpose — the@@ -1144,7 +1158,12 @@ export class LocalNotesRepository implements NotesRepository {this.database.delete(folders).where(eq(folders.id, localId)).run();}+ isNotePushRejected(localId: number): boolean {+ return this.getSyncState(pushRejectedKey(localId)) !== null;+ }+hardDeleteNote(localId: number): void {+ this.clearSyncState(pushRejectedKey(localId));this.deleteNoteChildrenAndAudio(localId);this.database.delete(notes).where(eq(notes.id, localId)).run();}diff --git a/openwhispr-mobile/src/data/remote/__tests__/noteSharingApi.test.ts b/openwhispr-mobile/src/data/remote/__tests__/noteSharingApi.test.tsnew file mode 100644index 000000000..734a1ba03--- /dev/null+++ b/openwhispr-mobile/src/data/remote/__tests__/noteSharingApi.test.ts@@ -0,0 +1,129 @@+jest.mock('@/lib/apiClient', () => ({+ api: { get: jest.fn(), patch: jest.fn(), post: jest.fn(), delete: jest.fn() },+}));++import { api } from '@/lib/apiClient';+import {+ getNoteShareState,+ setNoteShareVisibility,+ disableNoteShare,+ replaceNoteShareToken,+ getExternalSharingMode,+ searchNoteAccessPrincipals,+ createNoteAccessGrant,+ updateNoteAccessGrant,+ removeNoteAccessGrant,+ revokeNoteInvitation,+ resendNoteInvitation,+} from '../noteSharingApi';++const mockApi = jest.mocked(api);+const options = { signal: new AbortController().signal };+const share = {+ visibility: 'invited' as const,+ token_prefix: 'ow_share_Ab_9-xY',+ domain_allowlist: [],+ updated_by_user_id: 'owner',+ updated_at: '2026-09-22T00:00:00.000Z',+};++beforeEach(() => jest.clearAllMocks());++it('reads share settings, invitations, and access in one request', async () => {+ const state = {+ share,+ invitations: [],+ access: {+ owner: { type: 'user', id: 'owner', email: '[email protected]', name: null, image: null },+ grants: [],+ my_permission: 'owner',+ can_manage_access: true,+ can_manage_inherited_access: true,+ },+ };+ mockApi.get.mockResolvedValueOnce(state);+ await expect(getNoteShareState('note/id', options)).resolves.toBe(state);+ expect(mockApi.get).toHaveBeenCalledTimes(1);+ expect(mockApi.get).toHaveBeenCalledWith('/api/notes/note%2Fid/share', options);+});++it('reads the organization external sharing mode, permissive when unmanaged', async () => {+ const policy = (managed: boolean, mode: string) => ({+ data: { managed, policy: { sharing: { externalLinkSharing: mode } }, policyUpdatedAt: null },+ });+ mockApi.get.mockResolvedValueOnce(policy(true, 'domain_only'));+ await expect(getExternalSharingMode(options)).resolves.toBe('domain_only');+ expect(mockApi.get).toHaveBeenCalledWith('/api/workspace-policy', {+ ...options,+ headers: { 'Cache-Control': 'no-cache' },+ });+ mockApi.get.mockResolvedValueOnce(policy(false, 'disabled'));+ await expect(getExternalSharingMode()).resolves.toBe('allowed');+});+it('leaves a managed workspace whose policy is still pending to the server', async () => {+ mockApi.get.mockResolvedValueOnce({+ data: { managed: true, policy: null, policyUpdatedAt: null },+ });+ await expect(getExternalSharingMode(options)).resolves.toBeNull();+});++it('preserves returned raw token and writes expected share endpoints', async () => {+ const response = { share: { ...share, visibility: 'link' as const }, raw_token: null };+ mockApi.patch.mockResolvedValue(response);+ await expect(setNoteShareVisibility('note/id', 'link', [], options)).resolves.toEqual(response);+ expect(mockApi.patch).toHaveBeenCalledWith(+ '/api/notes/note%2Fid/share',+ {+ visibility: 'link',+ domain_allowlist: [],+ },+ options,+ );+ await disableNoteShare('note/id', options);+ expect(mockApi.delete).toHaveBeenCalledWith('/api/notes/note%2Fid/share', undefined, options);+ await replaceNoteShareToken('note/id', options);+ expect(mockApi.post).toHaveBeenCalledWith(+ '/api/notes/note%2Fid/share/rotate-token',+ undefined,+ options,+ );+});++it('routes ACL grants, principal search, and invitations with encoded ids', async () => {+ await searchNoteAccessPrincipals('note/id', 'a+b', options);+ const input = {+ principal_type: 'email' as const,+ email: '[email protected]',+ permission: 'viewer' as const,+ };+ await createNoteAccessGrant('note/id', input, options);+ await updateNoteAccessGrant('note/id', 'grant/id', 'editor', options);+ await removeNoteAccessGrant('note/id', 'grant/id', options);+ await revokeNoteInvitation('note/id', 'inv/id', options);+ await resendNoteInvitation('note/id', 'inv/id', options);+ expect(mockApi.get).toHaveBeenCalledWith(+ '/api/notes/note%2Fid/access/suggestions?q=a%2Bb',+ options,+ );+ expect(mockApi.post).toHaveBeenCalledWith('/api/notes/note%2Fid/access/grants', input, options);+ expect(mockApi.patch).toHaveBeenCalledWith(+ '/api/notes/note%2Fid/access/grants/grant%2Fid',+ { permission: 'editor' },+ options,+ );+ expect(mockApi.delete).toHaveBeenCalledWith(+ '/api/notes/note%2Fid/access/grants/grant%2Fid',+ undefined,+ options,+ );+ expect(mockApi.delete).toHaveBeenCalledWith(+ '/api/notes/note%2Fid/share/invitations/inv%2Fid',+ undefined,+ options,+ );+ expect(mockApi.post).toHaveBeenCalledWith(+ '/api/notes/note%2Fid/share/invitations/inv%2Fid/resend',+ undefined,+ options,+ );+});diff --git a/openwhispr-mobile/src/data/remote/noteSharingApi.ts b/openwhispr-mobile/src/data/remote/noteSharingApi.tsnew file mode 100644index 000000000..35ec33158--- /dev/null+++ b/openwhispr-mobile/src/data/remote/noteSharingApi.ts@@ -0,0 +1,142 @@+import { api } from '@/lib/apiClient';+import type {+ AccessPrincipalSuggestion,+ CreateAccessGrantInput,+ ExternalSharingMode,+ NoteAccessGrant,+ NotePermission,+ RotateTokenResponse,+ ShareMutationResponse,+ ShareSettings,+ ShareStateResponse,+ ShareVisibility,+} from './noteSharingTypes';++export type NoteSharingRequestOptions = { signal?: AbortSignal };++function sharePath(remoteId: string, suffix = ''): string {+ return `/api/notes/${encodeURIComponent(remoteId)}/share${suffix}`;+}++function accessPath(remoteId: string, suffix = ''): string {+ return `/api/notes/${encodeURIComponent(remoteId)}/access${suffix}`;+}++export async function getNoteShareState(+ remoteId: string,+ options?: NoteSharingRequestOptions,+): Promise<ShareStateResponse> {+ return api.get<ShareStateResponse>(sharePath(remoteId), options);+}++/**+ * The strictest external-sharing mode across the caller's workspaces, or null while a managed+ * workspace's policy is still pending; the server enforces it either way.+ */+export async function getExternalSharingMode(+ options?: NoteSharingRequestOptions,+): Promise<ExternalSharingMode | null> {+ // The response may be cached per device, not per account; revalidate so a switch shows the new policy.+ const { data } = await api.get<{+ data: {+ managed: boolean;+ policy: { sharing?: { externalLinkSharing?: ExternalSharingMode } } | null;+ };+ }>('/api/workspace-policy', { ...options, headers: { 'Cache-Control': 'no-cache' } });+ return data.managed ? (data.policy?.sharing?.externalLinkSharing ?? null) : 'allowed';+}++export async function setNoteShareVisibility(+ remoteId: string,+ visibility: ShareVisibility,+ domainAllowlist: string[],+ options?: NoteSharingRequestOptions,+): Promise<ShareMutationResponse> {+ return api.patch<ShareMutationResponse>(+ sharePath(remoteId),+ { visibility, domain_allowlist: domainAllowlist },+ options,+ );+}++export async function disableNoteShare(+ remoteId: string,+ options?: NoteSharingRequestOptions,+): Promise<{ share: ShareSettings }> {+ return api.delete<{ share: ShareSettings }>(sharePath(remoteId), undefined, options);+}++export async function replaceNoteShareToken(+ remoteId: string,+ options?: NoteSharingRequestOptions,+): Promise<RotateTokenResponse> {+ return api.post<RotateTokenResponse>(sharePath(remoteId, '/rotate-token'), undefined, options);+}++export async function searchNoteAccessPrincipals(+ remoteId: string,+ query: string,+ options?: NoteSharingRequestOptions,+): Promise<{ suggestions: AccessPrincipalSuggestion[] }> {+ return api.get<{ suggestions: AccessPrincipalSuggestion[] }>(+ accessPath(remoteId, `/suggestions?q=${encodeURIComponent(query)}`),+ options,+ );+}++export async function createNoteAccessGrant(+ remoteId: string,+ input: CreateAccessGrantInput,+ options?: NoteSharingRequestOptions,+): Promise<NoteAccessGrant> {+ return api.post<NoteAccessGrant>(accessPath(remoteId, '/grants'), input, options);+}++export async function updateNoteAccessGrant(+ remoteId: string,+ grantId: string,+ permission: Exclude<NotePermission, 'owner'>,+ options?: NoteSharingRequestOptions,+): Promise<NoteAccessGrant> {+ return api.patch<NoteAccessGrant>(+ accessPath(remoteId, `/grants/${encodeURIComponent(grantId)}`),+ { permission },+ options,+ );+}++export async function removeNoteAccessGrant(+ remoteId: string,+ grantId: string,+ options?: NoteSharingRequestOptions,+): Promise<void> {+ await api.delete<void>(+ accessPath(remoteId, `/grants/${encodeURIComponent(grantId)}`),+ undefined,+ options,+ );+}++export async function revokeNoteInvitation(+ remoteId: string,+ invitationId: string,+ options?: NoteSharingRequestOptions,+): Promise<void> {+ await api.delete<void>(+ sharePath(remoteId, `/invitations/${encodeURIComponent(invitationId)}`),+ undefined,+ options,+ );+}++export async function resendNoteInvitation(+ remoteId: string,+ invitationId: string,+ options?: NoteSharingRequestOptions,+): Promise<{ id: string; resent: boolean }> {+ return api.post<{ id: string; resent: boolean }>(+ sharePath(remoteId, `/invitations/${encodeURIComponent(invitationId)}/resend`),+ undefined,+ options,+ );+}diff --git a/openwhispr-mobile/src/data/remote/noteSharingTypes.ts b/openwhispr-mobile/src/data/remote/noteSharingTypes.tsnew file mode 100644index 000000000..77692fbe4--- /dev/null+++ b/openwhispr-mobile/src/data/remote/noteSharingTypes.ts@@ -0,0 +1,79 @@+export type ShareVisibility = 'private' | 'link' | 'domain' | 'invited';+export type NotePermission = 'owner' | 'editor' | 'viewer';+// 'space' only appears on synthetic `scope:` rows for team-space membership.+export type NoteAccessPrincipalType = 'user' | 'email' | 'team' | 'space' | 'folder' | 'workspace';+export type ExternalSharingMode = 'allowed' | 'domain_only' | 'disabled';++export interface NoteAccessPrincipal {+ type: NoteAccessPrincipalType;+ id: string | null;+ email: string | null;+ name: string | null;+ image: string | null;+ member_count: number | null;+}++export interface NoteAccessGrant {+ id: string;+ principal: NoteAccessPrincipal;+ permission: Exclude<NotePermission, 'owner'>;+ source: 'direct' | 'team' | 'space' | 'folder' | 'workspace';+ inherited: boolean;+ pending: boolean;+ created_at: string;+ updated_at: string;+}++export interface NoteAccessState {+ owner: NoteAccessPrincipal;+ grants: NoteAccessGrant[];+ my_permission: NotePermission;+ can_manage_access: boolean;+ can_manage_inherited_access: boolean;+}++export interface ShareSettings {+ visibility: ShareVisibility;+ token_prefix: string | null;+ domain_allowlist: string[];+ updated_by_user_id: string | null;+ updated_at: string | null;+}++export interface NoteShareInvitation {+ id: string;+ email: string;+ invited_by_user_id: string | null;+ permission: Exclude<NotePermission, 'owner'>;+ accepted_at: string | null;+ revoked_at: string | null;+ last_emailed_at: string | null;+ created_at: string;+}++export interface ShareStateResponse {+ share: ShareSettings;+ invitations: NoteShareInvitation[];+ access: NoteAccessState;+}++export interface ShareMutationResponse {+ share: ShareSettings;+ raw_token: string | null;+}++export interface RotateTokenResponse {+ share: ShareSettings;+ raw_token: string;+}++export interface AccessPrincipalSuggestion extends NoteAccessPrincipal {+ existing_grant_id: string | null;+}++export interface CreateAccessGrantInput {+ principal_type: NoteAccessPrincipal['type'];+ principal_id?: string;+ email?: string;+ permission: Exclude<NotePermission, 'owner'>;+}diff --git a/openwhispr-mobile/src/data/synced/SyncedNotesRepository.ts b/openwhispr-mobile/src/data/synced/SyncedNotesRepository.tsindex 49ce1f543..4625437ff 100644--- a/openwhispr-mobile/src/data/synced/SyncedNotesRepository.ts+++ b/openwhispr-mobile/src/data/synced/SyncedNotesRepository.ts@@ -226,6 +226,9 @@ export class SyncedNotesRepository implements NotesRepository {dropNotePushAttempt(localId: number): void {this.local.dropNotePushAttempt(localId);}+ isNotePushRejected(localId: number): boolean {+ return this.local.isNotePushRejected(localId);+ }parkNoteConflict(localId: number, serverNote: RemoteNote): void {this.local.parkNoteConflict(localId, serverNote);}diff --git a/openwhispr-mobile/src/data/types.ts b/openwhispr-mobile/src/data/types.tsindex f13b32d07..7590bee20 100644--- a/openwhispr-mobile/src/data/types.ts+++ b/openwhispr-mobile/src/data/types.ts@@ -309,6 +309,8 @@ export interface NotesRepository {* that pull could otherwise be followed by a stale-base 409.*/dropNotePushAttempt(localId: number): void;+ /** True while the note's latest push was refused (terminal or dropped) and no later push, pull or delete has settled it. */+ isNotePushRejected(localId: number): boolean;/*** Records a push-time 409 note_version_conflict: stores the server's current* copy in conflict_server_note and leaves pendingSync untouched (local editsdiff --git a/openwhispr-mobile/src/hooks/__tests__/useNoteSharing.test.ts b/openwhispr-mobile/src/hooks/__tests__/useNoteSharing.test.tsnew file mode 100644index 000000000..1ec85445c--- /dev/null+++ b/openwhispr-mobile/src/hooks/__tests__/useNoteSharing.test.ts@@ -0,0 +1,1183 @@+import { act, renderHook, waitFor } from '@testing-library/react-native';+import * as WebBrowser from 'expo-web-browser';+import { AppState, Share, type AppStateStatus } from 'react-native';+import type { Note } from '@/data';++jest.mock('@/store/useAuthStore', () => ({+ useAuthStore: require('zustand').create(() => ({+ user: { id: 'owner', email: '[email protected]' },+ sessionCookie: 'cookie',+ isGuest: false,+ isLoading: false,+ })),+}));+jest.mock('@/store/useNotesStore', () => ({+ useNotesStore: require('zustand').create(() => ({ notes: [] })),+}));+jest.mock('@/data', () => ({ notesRepository: { getNoteById: jest.fn() } }));+jest.mock('@/sync/ensureNoteSynced', () => ({ ensureNoteSynced: jest.fn() }));+jest.mock('@/sync/syncEngine', () => ({ requestSync: jest.fn() }));+jest.mock('@/lib/apiClient', () => ({+ ApiError: class extends Error {+ status: number;+ code?: string;+ constructor(message: string, status: number, code?: string) {+ super(message);+ this.status = status;+ this.code = code;+ }+ },+}));+jest.mock('expo-clipboard', () => ({ setStringAsync: jest.fn() }));+jest.mock('expo-web-browser', () => ({ openBrowserAsync: jest.fn() }));+jest.mock('@/lib/notes/noteShareTokens', () => ({+ readNoteShareToken: jest.fn(),+ saveNoteShareToken: jest.fn(),+ removeNoteShareToken: jest.fn(),+ buildNoteShareUrl: (token: string): string => `https://notes.openwhispr.com/n/${token}`,+ buildNoteInviteUrl: (prefix: string): string => `https://notes.openwhispr.com/invite/${prefix}`,+}));+jest.mock('@/data/remote/noteSharingApi', () => ({+ getNoteShareState: jest.fn(),+ getExternalSharingMode: jest.fn(),+ setNoteShareVisibility: jest.fn(),+ disableNoteShare: jest.fn(),+ replaceNoteShareToken: jest.fn(),+ searchNoteAccessPrincipals: jest.fn(),+ createNoteAccessGrant: jest.fn(),+ updateNoteAccessGrant: jest.fn(),+ removeNoteAccessGrant: jest.fn(),+ revokeNoteInvitation: jest.fn(),+ resendNoteInvitation: jest.fn(),+}));+import * as Clipboard from 'expo-clipboard';+import { ApiError } from '@/lib/apiClient';+import * as sharing from '@/data/remote/noteSharingApi';+import * as tokens from '@/lib/notes/noteShareTokens';+import { notesRepository } from '@/data';+import { useAuthStore } from '@/store/useAuthStore';+import { useNotesStore } from '@/store/useNotesStore';+import { ensureNoteSynced } from '@/sync/ensureNoteSynced';+import { useNoteSharing } from '../useNoteSharing';++const share = {+ visibility: 'private' as const,+ token_prefix: null,+ domain_allowlist: [],+ updated_by_user_id: null,+ updated_at: null,+};+const access = {+ owner: {+ type: 'user' as const,+ id: 'owner',+ email: '[email protected]',+ name: 'Owner',+ image: null,+ member_count: null,+ },+ grants: [],+ my_permission: 'owner' as const,+ can_manage_access: true,+ can_manage_inherited_access: true,+};+const TOKEN = 'ow_share_abcdefghijklmnopqrstuvwxyz123456';+let note: Note;+const flushDraft = jest.fn();+function setup(): ReturnType<typeof renderHook<ReturnType<typeof useNoteSharing>, unknown>> {+ return renderHook(() => useNoteSharing(1, flushDraft));+}+/** Like the real store: a token only reads back while it matches the server's current prefix. */+function storeToken(token: string): void {+ jest+ .mocked(tokens.readNoteShareToken)+ .mockImplementation(async (_userId, _remoteId, prefix) =>+ prefix && token.startsWith(prefix) ? token : null,+ );+}+beforeEach((): void => {+ jest.clearAllMocks();+ jest.mocked(tokens.removeNoteShareToken).mockResolvedValue(undefined);+ jest.mocked(tokens.saveNoteShareToken).mockResolvedValue(undefined);+ note = {+ id: 1,+ clientNoteId: 'client',+ remoteId: 'remote',+ isPrivate: 0,+ title: 'Test note',+ deletedAt: null,+ } as Note;+ jest.mocked(notesRepository.getNoteById).mockImplementation(() => note);+ useNotesStore.setState({ notes: [note] });+ useAuthStore.setState({+ user: { id: 'owner', email: '[email protected]' } as NonNullable<+ ReturnType<typeof useAuthStore.getState>['user']+ >,+ sessionCookie: 'cookie',+ isGuest: false,+ isLoading: false,+ });+ jest.mocked(sharing.getNoteShareState).mockResolvedValue({ share, invitations: [], access });+ jest.mocked(sharing.getExternalSharingMode).mockResolvedValue('allowed');+ jest.mocked(sharing.setNoteShareVisibility).mockResolvedValue({+ share: { ...share, visibility: 'invited', token_prefix: TOKEN.slice(0, 16) },+ raw_token: TOKEN,+ });+ jest.mocked(tokens.readNoteShareToken).mockResolvedValue(null);+ jest.mocked(ensureNoteSynced).mockResolvedValue('remote');+ jest.spyOn(Share, 'share').mockResolvedValue({ action: Share.dismissedAction });+});+it('only loads settings when opened', async (): Promise<void> => {+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ expect(result.current.state?.share.visibility).toBe('private');+ expect(ensureNoteSynced).not.toHaveBeenCalled();+ expect(sharing.setNoteShareVisibility).not.toHaveBeenCalled();+ expect(sharing.replaceNoteShareToken).not.toHaveBeenCalled();+});+it('flushes and syncs before creating a public link; cancelling OS share leaves it active', async (): Promise<void> => {+ const publicShare = { ...share, visibility: 'link' as const, token_prefix: TOKEN.slice(0, 16) };+ jest+ .mocked(sharing.setNoteShareVisibility)+ .mockResolvedValue({ share: publicShare, raw_token: TOKEN });+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ await act(async (): Promise<void> => {+ await result.current.setVisibility('link');+ });+ expect(flushDraft.mock.invocationCallOrder[0]).toBeLessThan(+ jest.mocked(ensureNoteSynced).mock.invocationCallOrder[0],+ );+ expect(jest.mocked(ensureNoteSynced).mock.invocationCallOrder[0]).toBeLessThan(+ jest.mocked(sharing.setNoteShareVisibility).mock.invocationCallOrder[0],+ );+ expect(tokens.saveNoteShareToken).toHaveBeenCalledWith('owner', 'remote', TOKEN);+ expect(result.current.state?.share.visibility).toBe('link');+ expect(Share.share).toHaveBeenCalled();+ expect(sharing.disableNoteShare).not.toHaveBeenCalled();+});+it('does not rotate an existing link when the token is unavailable', async (): Promise<void> => {+ jest.mocked(sharing.getNoteShareState).mockResolvedValue({+ share: { ...share, visibility: 'link', token_prefix: TOKEN.slice(0, 16) },+ invitations: [],+ access,+ });+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ await act(async (): Promise<void> => {+ await result.current.copyLink();+ });+ expect(sharing.replaceNoteShareToken).not.toHaveBeenCalled();+ expect(result.current.error).toMatch(/replace/i);+});+it('revokes external sharing without requiring content sync', async (): Promise<void> => {+ note = { ...note, conflictServerNote: '{}' };+ jest.mocked(sharing.disableNoteShare).mockResolvedValue({ share });+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ await act(async (): Promise<void> => {+ await result.current.setVisibility('private');+ });+ expect(sharing.disableNoteShare).toHaveBeenCalled();+ expect(ensureNoteSynced).not.toHaveBeenCalled();+});+it('prevents mutation after permission is revoked', async (): Promise<void> => {+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ jest+ .mocked(sharing.getNoteShareState)+ .mockRejectedValue(new ApiError('Insufficient note permission', 403, 'note_access_denied'));+ await act(async (): Promise<void> => {+ await result.current.setVisibility('link');+ });+ expect(sharing.setNoteShareVisibility).not.toHaveBeenCalled();+ expect(result.current.error).toMatch(/permission/i);+});+it('ignores a delayed settings response after logout', async (): Promise<void> => {+ let finish!: (value: Awaited<ReturnType<typeof sharing.getNoteShareState>>) => void;+ jest.mocked(sharing.getNoteShareState).mockReturnValue(+ new Promise((resolve) => {+ finish = resolve;+ }),+ );+ const { result } = setup();+ await act(async (): Promise<void> => {+ useAuthStore.setState({ user: null });+ finish({ share, invitations: [], access });+ });+ expect(result.current.state).toBeNull();+});+it('can inspect old cloud sharing but cannot publish a private note', async (): Promise<void> => {+ note = { ...note, isPrivate: 1 };+ useNotesStore.setState({ notes: [note] });+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ expect(sharing.getNoteShareState).toHaveBeenCalled();+ await act(async (): Promise<void> => {+ await result.current.setVisibility('link');+ });+ expect(sharing.setNoteShareVisibility).not.toHaveBeenCalled();+});+it('uses ACL grants for email invitations when supported', async (): Promise<void> => {+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ await act(async (): Promise<void> => {+ await result.current.inviteEmail(' [email protected] ');+ });+ expect(sharing.createNoteAccessGrant).toHaveBeenCalledWith(+ 'remote',+ { principal_type: 'email', email: '[email protected]', permission: 'viewer' },+ expect.anything(),+ );+});++it('keeps confirmed sharing active if secure storage fails', async (): Promise<void> => {+ jest.mocked(sharing.setNoteShareVisibility).mockResolvedValue({+ share: { ...share, visibility: 'link', token_prefix: TOKEN.slice(0, 16) },+ raw_token: TOKEN,+ });+ jest+ .mocked(tokens.saveNoteShareToken)+ .mockRejectedValueOnce(new Error('Device storage unavailable'));+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ await act(async (): Promise<void> => {+ await result.current.setVisibility('link');+ });+ expect(result.current.state?.share.visibility).toBe('link');+ expect(result.current.error).toMatch(/storage/i);+ expect(sharing.disableNoteShare).not.toHaveBeenCalled();+ expect(sharing.replaceNoteShareToken).not.toHaveBeenCalled();+});+it('rejects cached tokens replaced on another device', async (): Promise<void> => {+ storeToken(TOKEN);+ jest.mocked(sharing.getNoteShareState).mockResolvedValue({+ share: { ...share, visibility: 'link', token_prefix: 'ow_share_NEWNEW1' },+ invitations: [],+ access,+ });+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ expect(result.current.hasLink).toBe(false);+ expect(tokens.readNoteShareToken).toHaveBeenCalledWith('owner', 'remote', 'ow_share_NEWNEW1');+});+it('cannot modify inherited scope access even with group management permission', async (): Promise<void> => {+ const grant = {+ id: 'scope:workspace:00000000-0000-4000-8000-000000000001',+ principal: { ...access.owner, type: 'workspace' as const },+ permission: 'viewer' as const,+ inherited: true,+ source: 'workspace' as const,+ pending: false,+ created_at: 'now',+ updated_at: 'now',+ };+ jest+ .mocked(sharing.getNoteShareState)+ .mockResolvedValue({ share, invitations: [], access: { ...access, grants: [grant] } });+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ await act(async (): Promise<void> => {+ await result.current.updateGrant(grant, 'editor');+ });+ expect(sharing.updateNoteAccessGrant).not.toHaveBeenCalled();+ expect(result.current.error).toMatch(/inherited/i);+});+// The server marks every stored group grant `inherited: true`; only `scope:` rows are read-only.+const teamGrant = {+ id: 'grant-team',+ principal: { ...access.owner, id: 'team-1', type: 'team' as const, name: 'Design' },+ permission: 'viewer' as const,+ inherited: true,+ source: 'team' as const,+ pending: false,+ created_at: 'now',+ updated_at: 'now',+};+it('lets group managers change and remove a stored team grant', async (): Promise<void> => {+ jest+ .mocked(sharing.getNoteShareState)+ .mockResolvedValue({ share, invitations: [], access: { ...access, grants: [teamGrant] } });+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ await act(async (): Promise<void> => {+ await result.current.updateGrant(teamGrant, 'editor');+ });+ expect(sharing.updateNoteAccessGrant).toHaveBeenCalledWith(+ 'remote',+ 'grant-team',+ 'editor',+ expect.anything(),+ );+ await act(async (): Promise<void> => {+ await result.current.removeGrant(teamGrant);+ });+ expect(sharing.removeNoteAccessGrant).toHaveBeenCalledWith(+ 'remote',+ 'grant-team',+ expect.anything(),+ );+});+it('blocks stored team grant changes without inherited-access management', async (): Promise<void> => {+ jest.mocked(sharing.getNoteShareState).mockResolvedValue({+ share,+ invitations: [],+ access: { ...access, can_manage_inherited_access: false, grants: [teamGrant] },+ });+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ await act(async (): Promise<void> => {+ await result.current.removeGrant(teamGrant);+ });+ expect(sharing.removeNoteAccessGrant).not.toHaveBeenCalled();+ expect(result.current.error).toMatch(/permission/i);+});+it('does not duplicate existing invitations with different email casing', async (): Promise<void> => {+ jest.mocked(sharing.getNoteShareState).mockResolvedValue({+ share,+ invitations: [+ {+ id: 'invite',+ email: '[email protected]',+ revoked_at: null,+ accepted_at: null,+ created_at: 'now',+ last_emailed_at: null,+ invited_by_user_id: 'owner',+ permission: 'viewer',+ },+ ],+ access,+ });+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ await act(async (): Promise<void> => {+ await result.current.inviteEmail('[email protected]');+ });+ expect(sharing.createNoteAccessGrant).not.toHaveBeenCalled();+ expect(result.current.error).toMatch(/already/i);+});+it('ignores a mutation result after privacy opt-out', async (): Promise<void> => {+ let finish!: (value: Awaited<ReturnType<typeof sharing.setNoteShareVisibility>>) => void;+ jest.mocked(sharing.setNoteShareVisibility).mockReturnValueOnce(+ new Promise((resolve) => {+ finish = resolve;+ }),+ );+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ let pending!: Promise<void>;+ act(() => {+ pending = result.current.setVisibility('link');+ });+ await waitFor(() => expect(sharing.setNoteShareVisibility).toHaveBeenCalled());+ await act(async (): Promise<void> => {+ note = { ...note, isPrivate: 1 };+ useNotesStore.setState({ notes: [note] });+ });+ await act(async (): Promise<void> => {+ finish({+ share: { ...share, visibility: 'link', token_prefix: TOKEN.slice(0, 16) },+ raw_token: TOKEN,+ });+ await pending;+ });+ expect(tokens.saveNoteShareToken).not.toHaveBeenCalled();+ expect(result.current.state?.share.visibility).not.toBe('link');+});+it('requires a paired viewer before uploading to a custom API', async (): Promise<void> => {+ const previousApi = process.env.EXPO_PUBLIC_API_URL;+ process.env.EXPO_PUBLIC_API_URL = 'https://api.example.com';+ try {+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ await act(async (): Promise<void> => {+ await result.current.setVisibility('link');+ });+ expect(ensureNoteSynced).not.toHaveBeenCalled();+ expect(sharing.setNoteShareVisibility).not.toHaveBeenCalled();+ expect(result.current.error).toMatch(/EXPO_PUBLIC_NOTES_URL/);+ } finally {+ if (previousApi === undefined) delete process.env.EXPO_PUBLIC_API_URL;+ else process.env.EXPO_PUBLIC_API_URL = previousApi;+ }+});++it('shares a new link without waiting for a later server revision', async (): Promise<void> => {+ jest.mocked(sharing.setNoteShareVisibility).mockResolvedValue({+ share: {+ ...share,+ visibility: 'link',+ token_prefix: TOKEN.slice(0, 16),+ updated_at: '2026-09-22T12:00:00Z',+ },+ raw_token: TOKEN,+ });+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ await act(async (): Promise<void> => {+ await result.current.setVisibility('link');+ });+ expect(ensureNoteSynced).toHaveBeenCalledTimes(1);+ expect(Share.share).toHaveBeenCalled();+ expect(result.current.error).toBeNull();+});++it('can disable an old external link after local cloud sync opt-out', async (): Promise<void> => {+ note = { ...note, isPrivate: 1 };+ useNotesStore.setState({ notes: [note] });+ jest.mocked(sharing.disableNoteShare).mockResolvedValue({ share });+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ await act(async (): Promise<void> => {+ await result.current.setVisibility('private');+ });+ expect(sharing.disableNoteShare).toHaveBeenCalledWith('remote', expect.anything());+ expect(ensureNoteSynced).not.toHaveBeenCalled();+ expect(flushDraft).not.toHaveBeenCalled();+});+it('clears unconfirmed sharing state after a lost mutation response', async (): Promise<void> => {+ jest+ .mocked(sharing.setNoteShareVisibility)+ .mockRejectedValueOnce(new Error('Network request failed'));+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ await act(async (): Promise<void> => {+ await result.current.setVisibility('link');+ });+ expect(result.current.state).toBeNull();+ expect(result.current.error).toMatch(/refresh settings/i);+ expect(sharing.setNoteShareVisibility).toHaveBeenCalledTimes(1);+});+it('reports ACL invitation delivery failure after reading fresh invitations', async (): Promise<void> => {+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ jest+ .mocked(sharing.getNoteShareState)+ .mockResolvedValueOnce({ share, invitations: [], access })+ .mockResolvedValueOnce({+ share,+ access,+ invitations: [+ {+ id: 'invite',+ email: '[email protected]',+ revoked_at: null,+ accepted_at: null,+ last_emailed_at: null,+ created_at: 'now',+ invited_by_user_id: 'owner',+ permission: 'viewer',+ },+ ],+ });+ await act(async (): Promise<void> => {+ await result.current.inviteEmail('[email protected]');+ });+ expect(result.current.message).toMatch(/email was not sent/i);+ expect(sharing.createNoteAccessGrant).toHaveBeenCalledTimes(1);+});++it('requires refreshing access after a confirmed grant cannot be reloaded', async (): Promise<void> => {+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ jest+ .mocked(sharing.getNoteShareState)+ .mockResolvedValueOnce({ share, invitations: [], access })+ .mockRejectedValueOnce(new Error('Network down'));+ await act(async (): Promise<void> => {+ await result.current.inviteEmail('[email protected]');+ });+ expect(sharing.createNoteAccessGrant).toHaveBeenCalledTimes(1);+ expect(result.current.state).toBeNull();+ expect(result.current.message).toBeNull();+ expect(result.current.error).toMatch(/sharing changed.*refresh/i);+});++const linkShare = { ...share, visibility: 'link' as const, token_prefix: TOKEN.slice(0, 16) };+it('keeps the stored link when the note leaves the current notes list', async (): Promise<void> => {+ jest.mocked(sharing.getNoteShareState).mockResolvedValue({+ share: linkShare,+ invitations: [],+ access,+ });+ storeToken(TOKEN);+ const { result } = setup();+ await waitFor(() => expect(result.current.hasLink).toBe(true));+ await act(async (): Promise<void> => {+ useNotesStore.setState({ notes: [] });+ });+ expect(result.current.note?.remoteId).toBe('remote');+ expect(tokens.removeNoteShareToken).not.toHaveBeenCalled();+ expect(result.current.hasLink).toBe(true);+});+it('finishes creating a link after the note leaves the current notes list', async (): Promise<void> => {+ let finish!: (value: Awaited<ReturnType<typeof sharing.setNoteShareVisibility>>) => void;+ jest.mocked(sharing.setNoteShareVisibility).mockReturnValueOnce(+ new Promise((resolve) => {+ finish = resolve;+ }),+ );+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ let pending!: Promise<void>;+ act(() => {+ pending = result.current.setVisibility('link');+ });+ await waitFor(() => expect(sharing.setNoteShareVisibility).toHaveBeenCalled());+ await act(async (): Promise<void> => {+ useNotesStore.setState({ notes: [] });+ });+ await act(async (): Promise<void> => {+ finish({ share: linkShare, raw_token: TOKEN });+ await pending;+ });+ expect(tokens.saveNoteShareToken).toHaveBeenCalledWith('owner', 'remote', TOKEN);+ expect(Share.share).toHaveBeenCalled();+});+it('never makes a restricted share public when settings changed after loading', async (): Promise<void> => {+ const { result } = setup();+ await waitFor(() => expect(result.current.state?.share.visibility).toBe('private'));+ jest.mocked(sharing.getNoteShareState).mockResolvedValue({+ share: { ...linkShare, visibility: 'invited' },+ invitations: [],+ access,+ });+ await act(async (): Promise<void> => {+ await result.current.setVisibility('link');+ });+ expect(sharing.setNoteShareVisibility).not.toHaveBeenCalled();+ expect(result.current.state?.share.visibility).toBe('invited');+ expect(result.current.error).toMatch(/changed/i);+});+it('copies an existing link without syncing note content', async (): Promise<void> => {+ note = { ...note, conflictServerNote: '{}' };+ jest.mocked(sharing.getNoteShareState).mockResolvedValue({+ share: linkShare,+ invitations: [],+ access,+ });+ storeToken(TOKEN);+ const { result } = setup();+ await waitFor(() => expect(result.current.hasLink).toBe(true));+ await act(async (): Promise<void> => {+ await result.current.copyLink();+ });+ expect(Clipboard.setStringAsync).toHaveBeenCalledWith(`https://notes.openwhispr.com/n/${TOKEN}`);+ expect(ensureNoteSynced).not.toHaveBeenCalled();+ expect(flushDraft).not.toHaveBeenCalled();+ expect(result.current.error).toBeNull();+});+it('does not time out while the OS share sheet stays open', async (): Promise<void> => {+ jest.mocked(sharing.getNoteShareState).mockResolvedValue({+ share: linkShare,+ invitations: [],+ access,+ });+ storeToken(TOKEN);+ const { result } = setup();+ await waitFor(() => expect(result.current.hasLink).toBe(true));+ jest.useFakeTimers();+ try {+ jest.spyOn(Share, 'share').mockReturnValue(new Promise(() => undefined));+ await act(async (): Promise<void> => {+ result.current.shareLink();+ await Promise.resolve();+ });+ await act(async (): Promise<void> => {+ for (let tick = 0; tick < 5; tick += 1) await Promise.resolve();+ });+ expect(Share.share).toHaveBeenCalled();+ await act(async (): Promise<void> => {+ jest.advanceTimersByTime(61_000);+ });+ expect(result.current.error).toBeNull();+ expect(result.current.state?.share.visibility).toBe('link');+ expect(result.current.busy).toBe(false);+ } finally {+ jest.useRealTimers();+ }+});+it('keeps settings when an invitation email cannot be resent', async (): Promise<void> => {+ const invitation = {+ id: 'invite',+ email: '[email protected]',+ revoked_at: null,+ accepted_at: null,+ created_at: 'now',+ last_emailed_at: 'now',+ invited_by_user_id: 'owner',+ permission: 'viewer' as const,+ };+ jest.mocked(sharing.getNoteShareState).mockResolvedValue({+ share: { ...linkShare, visibility: 'invited' },+ invitations: [invitation],+ access,+ });+ jest+ .mocked(sharing.resendNoteInvitation)+ .mockRejectedValueOnce(new ApiError('Failed to send invitation email', 502))+ .mockRejectedValueOnce(new ApiError('Please wait before resending', 429, 'resend_cooldown'));+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ await act(async (): Promise<void> => {+ await result.current.resendInvitation(invitation);+ });+ expect(result.current.state?.invitations).toHaveLength(1);+ expect(result.current.error).toMatch(/could not be sent/i);+ await act(async (): Promise<void> => {+ await result.current.resendInvitation(invitation);+ });+ expect(result.current.state?.invitations).toHaveLength(1);+ expect(result.current.error).toMatch(/wait a minute/i);+});++const invitedShare = { ...linkShare, visibility: 'invited' as const };+it('offers the invitation link for invited sharing without a stored token', async (): Promise<void> => {+ jest.mocked(sharing.getNoteShareState).mockResolvedValue({+ share: invitedShare,+ invitations: [],+ access,+ });+ const { result } = setup();+ await waitFor(() => expect(result.current.hasLink).toBe(true));+ await act(async (): Promise<void> => {+ await result.current.copyLink();+ });+ expect(Clipboard.setStringAsync).toHaveBeenCalledWith(+ `https://notes.openwhispr.com/invite/${invitedShare.token_prefix}`,+ );+ expect(sharing.replaceNoteShareToken).not.toHaveBeenCalled();+ expect(result.current.error).toBeNull();+});+it('does not time out while the in-app browser stays open', async (): Promise<void> => {+ jest.mocked(sharing.getNoteShareState).mockResolvedValue({+ share: linkShare,+ invitations: [],+ access,+ });+ storeToken(TOKEN);+ const { result } = setup();+ await waitFor(() => expect(result.current.hasLink).toBe(true));+ jest.useFakeTimers();+ try {+ jest.mocked(WebBrowser.openBrowserAsync).mockReturnValue(new Promise(() => undefined));+ await act(async (): Promise<void> => {+ result.current.openLink();+ for (let tick = 0; tick < 5; tick += 1) await Promise.resolve();+ });+ expect(WebBrowser.openBrowserAsync).toHaveBeenCalled();+ await act(async (): Promise<void> => {+ jest.advanceTimersByTime(61_000);+ });+ expect(result.current.error).toBeNull();+ expect(result.current.busy).toBe(false);+ } finally {+ jest.useRealTimers();+ }+});+it('rejects an invalid email before flushing or syncing the note', async (): Promise<void> => {+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ let invited: boolean | undefined;+ await act(async (): Promise<void> => {+ invited = await result.current.inviteEmail('bob@');+ });+ expect(invited).toBe(false);+ expect(result.current.error).toMatch(/valid email/i);+ expect(flushDraft).not.toHaveBeenCalled();+ expect(ensureNoteSynced).not.toHaveBeenCalled();+ expect(sharing.getNoteShareState).toHaveBeenCalledTimes(1);+});+it('reports a completed invitation so the field can be cleared', async (): Promise<void> => {+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ let invited: boolean | undefined;+ await act(async (): Promise<void> => {+ invited = await result.current.inviteEmail('[email protected]');+ });+ expect(invited).toBe(true);+ jest+ .mocked(sharing.createNoteAccessGrant)+ .mockRejectedValueOnce(+ new ApiError('Too many invitations', 429, 'invitations_per_day_exceeded'),+ );+ await act(async (): Promise<void> => {+ invited = await result.current.inviteEmail('[email protected]');+ });+ expect(invited).toBe(false);+ expect(result.current.error).toBe(+ 'You have reached today’s invitation limit. Try again tomorrow.',+ );+});+it('can be cancelled while waiting for the note to upload, but not while saving', async (): Promise<void> => {+ let uploaded!: (remoteId: string) => void;+ jest.mocked(ensureNoteSynced).mockReturnValueOnce(+ new Promise((resolve) => {+ uploaded = resolve;+ }),+ );+ let finish!: (value: Awaited<ReturnType<typeof sharing.setNoteShareVisibility>>) => void;+ jest.mocked(sharing.setNoteShareVisibility).mockReturnValueOnce(+ new Promise((resolve) => {+ finish = resolve;+ }),+ );+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ let pending!: Promise<void>;+ act(() => {+ pending = result.current.setVisibility('invited');+ });+ await waitFor(() => expect(result.current.cancellable).toBe(true));+ expect(result.current.busy).toBe(true);+ await act(async (): Promise<void> => {+ uploaded('remote');+ });+ await waitFor(() => expect(sharing.setNoteShareVisibility).toHaveBeenCalled());+ expect(result.current.cancellable).toBe(false);+ expect(result.current.busy).toBe(true);+ await act(async (): Promise<void> => {+ finish({ share: invitedShare, raw_token: null });+ await pending;+ });+ expect(result.current.busy).toBe(false);+});+it('starts loading on the first render instead of flashing an error state', () => {+ jest.mocked(sharing.getNoteShareState).mockReturnValue(new Promise(() => undefined));+ const renders: boolean[] = [];+ renderHook(() => {+ const controller = useNoteSharing(1, flushDraft);+ renders.push(controller.loading);+ return controller;+ });+ expect(renders[0]).toBe(true);+});+it('does not load cloud settings for a note that was never uploaded', async (): Promise<void> => {+ note = { ...note, remoteId: null };+ useNotesStore.setState({ notes: [note] });+ const { result } = setup();+ expect(result.current.loading).toBe(false);+ await waitFor(() => expect(sharing.getExternalSharingMode).toHaveBeenCalled());+ expect(sharing.getNoteShareState).not.toHaveBeenCalled();+});+it('reads the organization sharing mode, leaving enforcement to the server when unknown', async (): Promise<void> => {+ jest.mocked(sharing.getExternalSharingMode).mockResolvedValueOnce('domain_only');+ const { result, unmount } = setup();+ await waitFor(() => expect(result.current.sharingMode).toBe('domain_only'));+ unmount();+ jest.mocked(sharing.getExternalSharingMode).mockRejectedValueOnce(new Error('offline'));+ const second = setup();+ await waitFor(() => expect(sharing.getExternalSharingMode).toHaveBeenCalledTimes(2));+ expect(second.result.current.sharingMode).toBeNull();+});+it.each([+ [+ new ApiError('Insufficient note permission', 403, 'note_access_denied'),+ 'You do not have permission to manage sharing for this note.',+ ],+ [+ new ApiError('Sign in with company SSO', 403, 'SSO_REQUIRED'),+ 'Sign in with your company SSO to manage sharing.',+ ],+ [new ApiError('Space archived', 410, 'space_archived'), 'This note is in an archived space.'],+ [+ new ApiError('Invalid session', 401),+ 'Your session has expired. Sign in again to manage sharing.',+ ],+ [+ new ApiError("Cannot rotate a private note's token", 409),+ 'Sharing settings changed. Refresh and try again.',+ ],+ [new ApiError('Note not found', 404), 'Unable to update sharing. Please try again.'],+ [new ApiError('Invalid email address', 400), 'Invalid email address'],+ [new ApiError('HTTP 400', 400), 'Unable to update sharing. Please try again.'],+ [+ // The shape of expo/fetch's FetchError when the request never reaches the server.+ new Error('fetch failed: The Internet connection appears to be offline.'),+ 'Can’t reach OpenWhispr. Check your connection and try again.',+ ],+])('explains %s instead of showing server text', async (failure, message) => {+ jest.mocked(sharing.getNoteShareState).mockRejectedValue(failure);+ const { result } = setup();+ await waitFor(() => expect(result.current.error).toBe(message));+});++it('stops being cancellable when the note changes identity mid-upload', async (): Promise<void> => {+ jest.mocked(ensureNoteSynced).mockReturnValueOnce(new Promise(() => undefined));+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ act(() => {+ result.current.setVisibility('invited');+ });+ await waitFor(() => expect(result.current.cancellable).toBe(true));+ await act(async (): Promise<void> => {+ note = { ...note, remoteId: 'forked' };+ useNotesStore.setState({ notes: [note] });+ });+ expect(result.current.busy).toBe(false);+ expect(result.current.cancellable).toBe(false);+});++it('keeps the full link of a first invitation, so a later link share works', async (): Promise<void> => {+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ await act(async (): Promise<void> => {+ await result.current.inviteEmail('[email protected]');+ });+ expect(sharing.setNoteShareVisibility).toHaveBeenCalledWith(+ 'remote',+ 'invited',+ [],+ expect.anything(),+ );+ expect(jest.mocked(sharing.setNoteShareVisibility).mock.invocationCallOrder[0]).toBeLessThan(+ jest.mocked(sharing.createNoteAccessGrant).mock.invocationCallOrder[0],+ );+ expect(tokens.saveNoteShareToken).toHaveBeenCalledWith('owner', 'remote', TOKEN);+});+it('keeps an existing link when inviting or adding people', async (): Promise<void> => {+ jest.mocked(sharing.getNoteShareState).mockResolvedValue({+ share: { ...share, visibility: 'invited', token_prefix: TOKEN.slice(0, 16) },+ invitations: [],+ access,+ });+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ await act(async (): Promise<void> => {+ await result.current.inviteEmail('[email protected]');+ await result.current.addPrincipal({ ...access.owner, id: 'user-2', existing_grant_id: null });+ });+ expect(sharing.createNoteAccessGrant).toHaveBeenCalledTimes(2);+ expect(sharing.setNoteShareVisibility).not.toHaveBeenCalled();+});+it('keeps the full link of a first group grant', async (): Promise<void> => {+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ await act(async (): Promise<void> => {+ await result.current.addPrincipal({+ ...access.owner,+ type: 'team',+ id: 'team-1',+ existing_grant_id: null,+ });+ });+ expect(sharing.setNoteShareVisibility).toHaveBeenCalledWith(+ 'remote',+ 'invited',+ [],+ expect.anything(),+ );+ expect(tokens.saveNoteShareToken).toHaveBeenCalledWith('owner', 'remote', TOKEN);+});+it('never widens a domain share whose allowed domains changed elsewhere', async (): Promise<void> => {+ const domainShare = {+ ...linkShare,+ visibility: 'domain' as const,+ domain_allowlist: ['company.com'],+ };+ jest+ .mocked(sharing.getNoteShareState)+ .mockResolvedValue({ share: domainShare, invitations: [], access });+ const { result } = setup();+ await waitFor(() => expect(result.current.state?.share.visibility).toBe('domain'));+ jest.mocked(sharing.getNoteShareState).mockResolvedValue({+ share: { ...domainShare, domain_allowlist: ['other.com'] },+ invitations: [],+ access,+ });+ await act(async (): Promise<void> => {+ await result.current.setVisibility('link');+ });+ expect(sharing.setNoteShareVisibility).not.toHaveBeenCalled();+ expect(result.current.error).toMatch(/changed/i);+});+it('refreshes quietly when the app returns to the foreground', async (): Promise<void> => {+ let onChange!: (state: AppStateStatus) => void;+ jest.spyOn(AppState, 'addEventListener').mockImplementation((_type, listener) => {+ onChange = listener;+ return { remove: jest.fn() };+ });+ const { result } = setup();+ await waitFor(() => expect(result.current.state?.share.visibility).toBe('private'));+ let finish!: (value: Awaited<ReturnType<typeof sharing.getNoteShareState>>) => void;+ jest+ .mocked(sharing.getNoteShareState)+ .mockReturnValueOnce(+ new Promise((resolve) => {+ finish = resolve;+ }),+ )+ .mockRejectedValueOnce(new Error('fetch failed: offline'));+ act(() => onChange('active'));+ expect(result.current.loading).toBe(false);+ expect(result.current.state?.share.visibility).toBe('private');+ await act(async (): Promise<void> => {+ finish({ share: linkShare, invitations: [], access });+ });+ expect(result.current.state?.share.visibility).toBe('link');+ await act(async (): Promise<void> => {+ onChange('active');+ });+ expect(result.current.state?.share.visibility).toBe('link');+ expect(result.current.error).toBeNull();+});+it('keeps stored links when the account changes while the sheet is open', async (): Promise<void> => {+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ await act(async (): Promise<void> => {+ useAuthStore.setState({ user: null });+ });+ expect(tokens.removeNoteShareToken).not.toHaveBeenCalled();+ expect(result.current.hasLink).toBe(false);+});+it('clears an error once the user corrects their input', async (): Promise<void> => {+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ await act(async (): Promise<void> => {+ await result.current.inviteEmail('bob@');+ });+ expect(result.current.error).toMatch(/valid email/i);+ act(() => result.current.dismissError());+ expect(result.current.error).toBeNull();+});+it('names an untitled note when handing its link to the share sheet', async (): Promise<void> => {+ note = { ...note, title: '' };+ useNotesStore.setState({ notes: [note] });+ jest+ .mocked(sharing.setNoteShareVisibility)+ .mockResolvedValue({ share: linkShare, raw_token: TOKEN });+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ await act(async (): Promise<void> => {+ await result.current.setVisibility('link');+ });+ expect(Share.share).toHaveBeenCalledWith(expect.objectContaining({ title: 'Untitled' }));+});+it('lets the server lift a paused private note only after it accepts the invitation', async (): Promise<void> => {+ jest.mocked(sharing.getNoteShareState).mockResolvedValue({+ share,+ access: {+ ...access,+ grants: [+ {+ id: 'grant-1',+ principal: { ...access.owner, id: 'user-2', name: 'Paused' },+ permission: 'viewer',+ source: 'direct' as const,+ inherited: false,+ pending: false,+ created_at: '',+ updated_at: '',+ },+ ],+ },+ invitations: [],+ });+ jest+ .mocked(sharing.createNoteAccessGrant)+ .mockRejectedValueOnce(new ApiError('Invalid email address', 400));+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ await act(async (): Promise<void> => {+ await result.current.inviteEmail('[email protected]');+ });+ expect(sharing.setNoteShareVisibility).not.toHaveBeenCalled();+ expect(result.current.state?.share.visibility).toBe('private');+ expect(result.current.error).toBe('Invalid email address');+});+it('does not let a quiet refresh hide the first load failing', async (): Promise<void> => {+ let onChange!: (state: AppStateStatus) => void;+ jest.spyOn(AppState, 'addEventListener').mockImplementation((_type, listener) => {+ onChange = listener;+ return { remove: jest.fn() };+ });+ let fail!: (reason: unknown) => void;+ jest.mocked(sharing.getNoteShareState).mockReturnValueOnce(+ new Promise((_resolve, reject) => {+ fail = reject;+ }),+ );+ const { result } = setup();+ act(() => onChange('active'));+ await act(async (): Promise<void> => {+ fail(new ApiError('Forbidden', 403, 'note_access_denied'));+ });+ expect(result.current.error).toMatch(/permission/i);+ expect(sharing.getNoteShareState).toHaveBeenCalledTimes(1);+});+it('loads settings once background sync uploads a note opened before its upload', async (): Promise<void> => {+ let onChange!: (state: AppStateStatus) => void;+ jest.spyOn(AppState, 'addEventListener').mockImplementation((_type, listener) => {+ onChange = listener;+ return { remove: jest.fn() };+ });+ note = { ...note, remoteId: null };+ useNotesStore.setState({ notes: [note] });+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ expect(sharing.getNoteShareState).not.toHaveBeenCalled();+ note = { ...note, remoteId: 'remote' };+ await act(async (): Promise<void> => {+ useNotesStore.setState({ notes: [note] });+ });+ await waitFor(() => expect(result.current.state?.share.visibility).toBe('private'));+ expect(sharing.getNoteShareState).toHaveBeenCalledTimes(1);+ await act(async (): Promise<void> => {+ onChange('active');+ });+ expect(sharing.getNoteShareState).toHaveBeenCalledTimes(2);+});++const pausedGrant = {+ id: 'grant-1',+ principal: { ...access.owner, id: 'user-2', name: 'Paused' },+ permission: 'viewer' as const,+ source: 'direct' as const,+ inherited: false,+ pending: false,+ created_at: '',+ updated_at: '',+};+it('copies the bearer link after replacing the link of a link share', async (): Promise<void> => {+ jest+ .mocked(sharing.getNoteShareState)+ .mockResolvedValue({ share: linkShare, invitations: [], access });+ jest+ .mocked(sharing.replaceNoteShareToken)+ .mockResolvedValue({ share: linkShare, raw_token: TOKEN });+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ await act(async (): Promise<void> => {+ await result.current.replaceLink();+ });+ expect(tokens.saveNoteShareToken).toHaveBeenCalledWith('owner', 'remote', TOKEN);+ expect(Clipboard.setStringAsync).toHaveBeenCalledWith(`https://notes.openwhispr.com/n/${TOKEN}`);+});+it('copies the invitation link after replacing the link of invited sharing', async (): Promise<void> => {+ jest+ .mocked(sharing.getNoteShareState)+ .mockResolvedValue({ share: invitedShare, invitations: [], access });+ jest+ .mocked(sharing.replaceNoteShareToken)+ .mockResolvedValue({ share: invitedShare, raw_token: TOKEN });+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ await act(async (): Promise<void> => {+ await result.current.replaceLink();+ });+ expect(tokens.saveNoteShareToken).toHaveBeenCalledWith('owner', 'remote', TOKEN);+ expect(Clipboard.setStringAsync).toHaveBeenCalledWith(+ `https://notes.openwhispr.com/invite/${invitedShare.token_prefix}`,+ );+});+it('shows the server’s settings after it refuses a change that still reopened sharing', async (): Promise<void> => {+ const paused = { share, access: { ...access, grants: [pausedGrant] }, invitations: [] };+ jest+ .mocked(sharing.getNoteShareState)+ .mockResolvedValueOnce(paused)+ .mockResolvedValueOnce(paused)+ .mockResolvedValue({ ...paused, share: invitedShare });+ jest+ .mocked(sharing.createNoteAccessGrant)+ .mockRejectedValueOnce(+ new ApiError('Daily invitation limit reached', 429, 'invitations_per_day_exceeded'),+ );+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ await act(async (): Promise<void> => {+ await result.current.inviteEmail('[email protected]');+ });+ expect(result.current.state?.share.visibility).toBe('invited');+ expect(result.current.error).toMatch(/invitation limit/i);+});+it('turns an empty share back off when the server refuses its first grant', async (): Promise<void> => {+ jest+ .mocked(sharing.createNoteAccessGrant)+ .mockRejectedValueOnce(new ApiError('Verify your email', 403, 'email_verification_required'));+ jest.mocked(sharing.disableNoteShare).mockResolvedValue({ share });+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ await act(async (): Promise<void> => {+ await result.current.inviteEmail('[email protected]');+ });+ expect(sharing.setNoteShareVisibility).toHaveBeenCalledTimes(1);+ expect(sharing.disableNoteShare).toHaveBeenCalledTimes(1);+ expect(tokens.removeNoteShareToken).toHaveBeenCalledWith('owner', 'remote');+ expect(result.current.state?.share.visibility).toBe('private');+ expect(result.current.hasLink).toBe(false);+ expect(result.current.error).toMatch(/verify your email/i);+});+it('keeps the share of a first grant whose outcome is unknown', async (): Promise<void> => {+ jest+ .mocked(sharing.createNoteAccessGrant)+ .mockRejectedValueOnce(new ApiError('Internal server error', 500));+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ await act(async (): Promise<void> => {+ await result.current.inviteEmail('[email protected]');+ });+ expect(sharing.disableNoteShare).not.toHaveBeenCalled();+ expect(result.current.error).toMatch(/could not be confirmed/i);+});+it('explains losing access after removing your own grant', async (): Promise<void> => {+ const withGrant = { share, access: { ...access, grants: [pausedGrant] }, invitations: [] };+ jest+ .mocked(sharing.getNoteShareState)+ .mockResolvedValueOnce(withGrant)+ .mockResolvedValueOnce(withGrant)+ .mockRejectedValueOnce(new ApiError('Not found', 404));+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ await act(async (): Promise<void> => {+ await result.current.removeGrant(pausedGrant);+ });+ expect(sharing.removeNoteAccessGrant).toHaveBeenCalledTimes(1);+ expect(result.current.state).toBeNull();+ expect(result.current.error).toMatch(/no longer manage sharing/i);+});+it('keeps the full link of a first invitation when the only access is inherited', async (): Promise<void> => {+ jest.mocked(sharing.getNoteShareState).mockResolvedValue({+ share,+ access: {+ ...access,+ grants: [{ ...pausedGrant, id: 'scope:space-1', inherited: true }],+ },+ invitations: [],+ });+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ await act(async (): Promise<void> => {+ await result.current.inviteEmail('[email protected]');+ });+ expect(sharing.setNoteShareVisibility).toHaveBeenCalledWith(+ 'remote',+ 'invited',+ [],+ expect.anything(),+ );+ expect(tokens.saveNoteShareToken).toHaveBeenCalledWith('owner', 'remote', TOKEN);+});+it('never widens a share it could not show when the server reports one already', async (): Promise<void> => {+ jest+ .mocked(sharing.getNoteShareState)+ .mockRejectedValueOnce(new Error('Network down'))+ .mockResolvedValue({ share: invitedShare, invitations: [], access });+ const { result } = setup();+ await waitFor(() => expect(result.current.error).not.toBeNull());+ expect(result.current.state).toBeNull();+ await act(async (): Promise<void> => {+ await result.current.setVisibility('link');+ });+ expect(sharing.setNoteShareVisibility).not.toHaveBeenCalled();+ expect(result.current.error).toMatch(/changed/i);+});+it('erases the stored link when the note’s cloud copy changes', async (): Promise<void> => {+ const { result } = setup();+ await waitFor(() => expect(result.current.loading).toBe(false));+ note = { ...note, remoteId: 'remote-2' };+ await act(async (): Promise<void> => {+ useNotesStore.setState({ notes: [note] });+ });+ expect(tokens.removeNoteShareToken).toHaveBeenCalledWith('owner', 'remote');+});diff --git a/openwhispr-mobile/src/hooks/useNoteSharing.ts b/openwhispr-mobile/src/hooks/useNoteSharing.tsnew file mode 100644index 000000000..60c2ff09f--- /dev/null+++ b/openwhispr-mobile/src/hooks/useNoteSharing.ts@@ -0,0 +1,729 @@+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { AppState, Platform, Share } from 'react-native';+import * as Clipboard from 'expo-clipboard';+import * as WebBrowser from 'expo-web-browser';+import { notesRepository, type Note } from '@/data';+import { ApiError } from '@/lib/apiClient';+import { getErrorMessage, isValidEmail } from '@/lib/utils';+import type { AuthUser } from '@/lib/authClient';+import { getNoteShareViewerBaseUrl } from '@/config/noteSharing';+import { useAuthStore } from '@/store/useAuthStore';+import { useNotesStore } from '@/store/useNotesStore';+import * as api from '@/data/remote/noteSharingApi';+import type {+ ExternalSharingMode,+ ShareSettings,+ ShareStateResponse,+ ShareVisibility,+ NoteAccessGrant,+ NoteShareInvitation,+ AccessPrincipalSuggestion,+} from '@/data/remote/noteSharingTypes';+import {+ buildNoteInviteUrl,+ buildNoteShareUrl,+ readNoteShareToken,+ saveNoteShareToken,+ removeNoteShareToken,+} from '@/lib/notes/noteShareTokens';+import { canChangeGrant, isGroupPrincipal, isScopeGrant } from '@/lib/notes/noteShareAccess';+import {+ NOTE_PRIVATE_ERROR,+ NOTE_UNAVAILABLE_ERROR,+ ensureNoteSynced,+} from '@/sync/ensureNoteSynced';+import { requestSync } from '@/sync/syncEngine';++export interface NoteSharingController {+ state: ShareStateResponse | null;+ loading: boolean;+ busy: boolean;+ /** The running operation is still waiting for the note upload, so abandoning it changes nothing. */+ cancellable: boolean;+ error: string | null;+ message: string | null;+ /** Invited sharing links to the invitation page; other modes need the full link stored here. */+ hasLink: boolean;+ /** Null while unknown; the server enforces the policy either way. */+ sharingMode: ExternalSharingMode | null;+ note: Note | undefined;+ user: AuthUser | null;+ refresh: () => Promise<void>;+ dismissError: () => void;+ setVisibility: (visibility: ShareVisibility, domainAllowlist?: string[]) => Promise<void>;+ replaceLink: () => Promise<void>;+ copyLink: () => Promise<void>;+ shareLink: () => Promise<void>;+ openLink: () => Promise<void>;+ /** Resolves true once the invitation is confirmed. */+ inviteEmail: (email: string) => Promise<boolean>;+ addPrincipal: (principal: AccessPrincipalSuggestion) => Promise<void>;+ updateGrant: (grant: NoteAccessGrant, permission: NoteAccessGrant['permission']) => Promise<void>;+ removeGrant: (grant: NoteAccessGrant) => Promise<void>;+ revokeInvitation: (invitation: NoteShareInvitation) => Promise<void>;+ resendInvitation: (invitation: NoteShareInvitation) => Promise<void>;+}++interface SharingOperation {+ remoteId: string;+ userId: string;+ signal: AbortSignal;+ current: ShareStateResponse;+ check: () => void;+ mutate: <Result>(request: () => Promise<Result>) => Promise<Result>;+ /** Ends the operation before handing off to OS UI that stays open until the user dismisses it. */+ release: () => void;+}++interface RunOptions {+ /** Flush the draft and wait for its acknowledged upload before reading settings. */+ publish?: boolean;+ /** Allow a locally private note, e.g. to disable a link left over from its old cloud copy. */+ allowPrivate?: boolean;+}++export const INVALID_EMAIL_ERROR = 'Enter a valid email address.';++const GENERIC_ERROR = 'Unable to update sharing. Please try again.';++const ERROR_MESSAGES: Record<string, string> = {+ POLICY_SHARING_BLOCKED: 'Sharing is restricted by your organization.',+ POLICY_UNRESOLVABLE: 'Sharing is restricted by your organization.',+ note_access_denied: 'You do not have permission to manage sharing for this note.',+ SSO_REQUIRED: 'Sign in with your company SSO to manage sharing.',+ space_archived: 'This note is in an archived space.',+ email_verification_required: 'Verify your email before inviting people.',+ invitations_per_day_exceeded: 'You have reached today’s invitation limit. Try again tomorrow.',+ resend_cooldown: 'Please wait a minute before resending.',+};++function sharingError(error: unknown): string {+ if (error instanceof ApiError) {+ const known = error.code ? ERROR_MESSAGES[error.code] : undefined;+ if (known) return known;+ if (error.status === 401) return 'Your session has expired. Sign in again to manage sharing.';+ if (error.status === 409) return 'Sharing settings changed. Refresh and try again.';+ // Validation messages (an invalid email, a personal domain) are written for people; a bare+ // status from a response without a body is not.+ if ((error.status === 400 || error.status === 426) && !error.message.startsWith('HTTP '))+ return error.message;+ return GENERIC_ERROR;+ }+ // expo/fetch rejects with a FetchError (not exported) when the request never reaches the server.+ if (error instanceof Error && error.message.startsWith('fetch failed'))+ return 'Can’t reach OpenWhispr. Check your connection and try again.';+ return getErrorMessage(error, GENERIC_ERROR);+}++function sameSettings(left: ShareSettings, right: ShareSettings): boolean {+ return (+ left.visibility === right.visibility &&+ left.domain_allowlist.join(',') === right.domain_allowlist.join(',')+ );+}++/** Invited sharing hands out the invitation link, which stays closed if visibility later widens. */+function invitationLink(share: ShareSettings): string | null {+ return share.visibility === 'invited' && share.token_prefix+ ? buildNoteInviteUrl(share.token_prefix)+ : null;+}++/** The cloud copy whose settings can load; private notes still load to manage an old link. */+function loadableRemoteId(user: AuthUser | null, local: Note | null | undefined): string | null {+ return user && !user.isAnonymous && local?.remoteId && !local.deletedAt ? local.remoteId : null;+}++/** A stored full link is kept only while it matches the server's current token. */+function loadToken(+ userId: string,+ remoteId: string,+ current: ShareStateResponse,+): Promise<string | null> {+ return readNoteShareToken(+ userId,+ remoteId,+ current.share.visibility === 'private' ? null : current.share.token_prefix,+ );+}++export function useNoteSharing(noteId: number, onFlushDraft: () => void): NoteSharingController {+ const user = useAuthStore((s) => s.user);+ const cookie = useAuthStore((s) => s.sessionCookie);+ const notes = useNotesStore((s) => s.notes);+ // The store only holds the current folder/space/search view; like the editor, fall back to the+ // repository so a note outside that view keeps its identity (and its stored link).+ const note = useMemo<Note | undefined>(+ () =>+ notes.find((item) => item.id === noteId) ?? notesRepository.getNoteById(noteId) ?? undefined,+ [notes, noteId],+ );+ const [state, setState] = useState<ShareStateResponse | null>(null);+ const [loading, setLoading] = useState(() =>+ Boolean(loadableRemoteId(user, notesRepository.getNoteById(noteId))),+ );+ const [busy, setBusy] = useState(false);+ const [cancellable, setCancellable] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [message, setMessage] = useState<string | null>(null);+ const [hasToken, setHasToken] = useState(false);+ const [sharingMode, setSharingMode] = useState<ExternalSharingMode | null>(null);+ const operation = useRef<AbortController | null>(null);+ const loadRequest = useRef<AbortController | null>(null);+ const generation = useRef(0);+ const previousIdentity = useRef<{ userId: string; remoteId: string } | null>(null);+ const observedRemoteId = useRef(note?.remoteId ?? null);++ /** A silent refresh keeps the current settings on screen and only replaces them on success. */+ const refresh = useCallback(+ async (silent?: boolean): Promise<void> => {+ // A quiet refresh must not replace a load in flight, which would hide that load's error.+ if (operation.current || (silent && loadRequest.current)) return;+ loadRequest.current?.abort();+ const controller = new AbortController();+ loadRequest.current = controller;+ const version = generation.current;+ const local = notesRepository.getNoteById(noteId);+ const valid = (): boolean =>+ !controller.signal.aborted &&+ version === generation.current &&+ useAuthStore.getState().user?.id === user?.id &&+ useAuthStore.getState().sessionCookie === cookie &&+ notesRepository.getNoteById(noteId)?.remoteId === local?.remoteId &&+ notesRepository.getNoteById(noteId)?.isPrivate === local?.isPrivate;+ const remoteId = loadableRemoteId(user, local);+ if (!silent || !user || !remoteId) {+ setState(null);+ setError(null);+ setHasToken(false);+ }+ if (!user || !remoteId) {+ loadRequest.current = null;+ setLoading(false);+ return;+ }+ if (!silent) setLoading(true);+ const timer = setTimeout(() => {+ controller.abort();+ if (loadRequest.current === controller) {+ setLoading(false);+ if (!silent) setError('Sharing settings timed out. Check your connection and retry.');+ }+ }, 30_000);+ controller.signal.addEventListener('abort', () => clearTimeout(timer), { once: true });+ try {+ const current = await api.getNoteShareState(remoteId, { signal: controller.signal });+ if (!valid()) return;+ const token = local?.isPrivate === 1 ? null : await loadToken(user.id, remoteId, current);+ if (!valid()) return;+ setState(current);+ setError(null);+ setHasToken(Boolean(token));+ } catch (failure) {+ if (valid() && !silent) setError(sharingError(failure));+ } finally {+ clearTimeout(timer);+ if (loadRequest.current === controller) {+ loadRequest.current = null;+ setLoading(false);+ }+ }+ },+ [user, cookie, noteId],+ );++ useEffect(() => {+ generation.current += 1;+ operation.current?.abort();+ operation.current = null;+ setBusy(false);+ setCancellable(false);+ setMessage(null);+ refresh();+ // Returning from the share sheet or browser must not blank the sheet or drop a search.+ const subscription = AppState.addEventListener('change', (next) => {+ if (next === 'active') refresh(true);+ });+ return (): void => {+ generation.current += 1;+ operation.current?.abort();+ loadRequest.current?.abort();+ subscription.remove();+ };+ }, [refresh, note?.isPrivate, note?.clientNoteId]);++ const policyUserId = user && !user.isAnonymous ? user.id : null;+ useEffect(() => {+ setSharingMode(null);+ if (!policyUserId) return;+ const controller = new AbortController();+ api+ .getExternalSharingMode({ signal: controller.signal })+ .then((mode) => {+ if (!controller.signal.aborted) setSharingMode(mode);+ })+ .catch(() => undefined);+ return (): void => controller.abort();+ }, [policyUserId, cookie]);++ useEffect(() => {+ const previous = previousIdentity.current;+ // Stored links survive sign-out and account switches; they are only dropped for this account.+ if (previous && previous.userId !== user?.id) setHasToken(false);+ else if (previous && (previous.remoteId !== note?.remoteId || note?.isPrivate === 1)) {+ removeNoteShareToken(previous.userId, previous.remoteId).catch(() => undefined);+ setHasToken(false);+ }+ if (previous && previous.userId === user?.id && previous.remoteId !== note?.remoteId) {+ generation.current += 1;+ operation.current?.abort();+ operation.current = null;+ setBusy(false);+ setCancellable(false);+ refresh();+ } else if (!observedRemoteId.current && note?.remoteId) {+ // Background sync uploaded the note while the sheet was open, so it now has settings to load.+ // A running operation loads them itself, and refresh() leaves it alone.+ refresh();+ }+ observedRemoteId.current = note?.remoteId ?? null;+ previousIdentity.current =+ user && note?.remoteId ? { userId: user.id, remoteId: note.remoteId } : null;+ }, [user, note?.remoteId, note?.isPrivate, refresh]);++ /** Resolves true when the task completed. */+ const run = async (+ task: (context: SharingOperation) => Promise<void>,+ { publish = false, allowPrivate = false }: RunOptions = {},+ ): Promise<boolean> => {+ if (operation.current) return false;+ const controller = new AbortController();+ operation.current = controller;+ loadRequest.current?.abort();+ setLoading(false);+ setBusy(true);+ setError(null);+ setMessage(null);+ const original = notesRepository.getNoteById(noteId);+ const version = generation.current;+ const timer = setTimeout(() => {+ controller.abort();+ if (operation.current === controller) {+ setState(null);+ setBusy(false);+ setError('Sharing timed out. Refresh settings to check whether the change completed.');+ }+ }, 60_000);+ controller.signal.addEventListener('abort', () => clearTimeout(timer), { once: true });+ const release = (): void => {+ clearTimeout(timer);+ if (operation.current === controller) {+ operation.current = null;+ setBusy(false);+ setCancellable(false);+ }+ };+ const check = (): void => {+ const auth = useAuthStore.getState();+ const current = notesRepository.getNoteById(noteId);+ if (+ controller.signal.aborted ||+ version !== generation.current ||+ auth.user?.id !== user?.id ||+ auth.sessionCookie !== cookie ||+ auth.isGuest ||+ auth.isLoading ||+ current?.clientNoteId !== original?.clientNoteId ||+ (original?.remoteId && current?.remoteId !== original.remoteId)+ ) {+ throw new Error('Sharing cancelled because the account or note changed.');+ }+ if (!auth.user || auth.user.isAnonymous)+ throw new Error('Sign in to an account to share notes.');+ if (!current || current.deletedAt) throw new Error(NOTE_UNAVAILABLE_ERROR);+ if (current.isPrivate === 1 && !allowPrivate) throw new Error(NOTE_PRIVATE_ERROR);+ };+ try {+ check();+ let remoteId = original?.remoteId;+ if (publish) {+ getNoteShareViewerBaseUrl();+ onFlushDraft();+ setCancellable(true);+ remoteId = await ensureNoteSynced(noteId, { signal: controller.signal });+ setCancellable(false);+ check();+ }+ if (!remoteId || !user) throw new Error('Sync this note before sharing.');+ const current = await api.getNoteShareState(remoteId, { signal: controller.signal });+ check();+ setState(current);+ const mutate = async <Result>(request: () => Promise<Result>): Promise<Result> => {+ try {+ return await request();+ } catch (failure) {+ check();+ if (!(failure instanceof ApiError) || failure.status >= 500) {+ setState(null);+ setHasToken(false);+ throw new Error(+ 'The sharing change could not be confirmed. Refresh settings before trying again.',+ );+ }+ // A refused change can still leave sharing different from what the sheet shows: a row+ // removed elsewhere answers 404, and older servers lift a paused note before the daily+ // invitation cap.+ try {+ const latest = await api.getNoteShareState(remoteId, { signal: controller.signal });+ check();+ setState(latest);+ } catch {+ // The refusal is the error worth showing.+ }+ throw failure;+ }+ };+ await task({+ remoteId,+ userId: user.id,+ signal: controller.signal,+ current,+ check,+ mutate,+ release,+ });+ return true;+ } catch (failure) {+ if (!controller.signal.aborted && version === generation.current)+ setError(sharingError(failure));+ return false;+ } finally {+ release();+ }+ };++ const adopt = async (context: SharingOperation): Promise<ShareStateResponse> => {+ let current: ShareStateResponse;+ try {+ current = await api.getNoteShareState(context.remoteId, { signal: context.signal });+ context.check();+ } catch (failure) {+ context.check();+ setState(null);+ setMessage(null);+ // Removing or demoting your own access leaves nothing this account may load.+ if (failure instanceof ApiError && (failure.status === 403 || failure.status === 404))+ throw new Error('Sharing changed. You can no longer manage sharing for this note.');+ throw new Error(+ 'Sharing changed, but the updated settings could not be loaded. Refresh to continue.',+ );+ }+ setState(current);+ requestSync('manual');+ return current;+ };+ const sendUrl = async (context: SharingOperation, url: string): Promise<void> => {+ context.release();+ const title = note?.title || 'Untitled';+ await Share.share(Platform.OS === 'ios' ? { url, title } : { message: url, title });+ };+ const remember = async (context: SharingOperation, token: string): Promise<void> => {+ context.check();+ await saveNoteShareToken(context.userId, context.remoteId, token);+ context.check();+ setHasToken(true);+ };++ const setVisibility = async (+ visibility: ShareVisibility,+ domainAllowlist: string[] = [],+ ): Promise<void> => {+ // Compare-and-set against what the sheet showed, so a restricted share changed elsewhere (or+ // unknown locally) is never widened by a tap that was meant for different settings.+ const shown = state?.share;+ await run(+ async (context) => {+ if (visibility === 'private') {+ const result = await context.mutate(() =>+ api.disableNoteShare(context.remoteId, { signal: context.signal }),+ );+ context.check();+ setState({ ...context.current, share: result.share });+ setHasToken(false);+ await removeNoteShareToken(context.userId, context.remoteId);+ requestSync('manual');+ return;+ }+ if (+ shown+ ? !sameSettings(context.current.share, shown)+ : context.current.share.visibility !== 'private'+ )+ throw new Error('Sharing settings changed. Review them and try again.');+ const result = await context.mutate(() =>+ api.setNoteShareVisibility(context.remoteId, visibility, domainAllowlist, {+ signal: context.signal,+ }),+ );+ context.check();+ const next = { ...context.current, share: result.share };+ setState(next);+ requestSync('manual');+ if (result.raw_token) {+ await remember(context, result.raw_token);+ if (visibility === 'link') await sendUrl(context, buildNoteShareUrl(result.raw_token));+ } else {+ const token = await loadToken(context.userId, context.remoteId, next);+ context.check();+ setHasToken(Boolean(token));+ }+ },+ { publish: visibility !== 'private', allowPrivate: visibility === 'private' },+ );+ };++ const replaceLink = async (): Promise<void> => {+ await run(+ async (context) => {+ const result = await context.mutate(() =>+ api.replaceNoteShareToken(context.remoteId, { signal: context.signal }),+ );+ context.check();+ setState({ ...context.current, share: result.share });+ requestSync('manual');+ await remember(context, result.raw_token);+ await Clipboard.setStringAsync(+ invitationLink(result.share) ?? buildNoteShareUrl(result.raw_token),+ );+ context.check();+ setMessage(+ 'New link copied. The previous link, including links in invitation emails, no longer works.',+ );+ },+ { publish: true },+ );+ };++ // The server mints a first invitation's link without returning it, so mint it here to keep the+ // full link; otherwise switching to a link share later could only replace it, breaking the emails.+ // Lifting a private note restores paused grants and invitations (listed as `invite:` grants), so+ // only do it when there are none: a request the server then rejects must not reopen them.+ // The grant is checked only after the lift, so a refused grant turns the empty share back off.+ const grantWithFullLink = async (+ context: SharingOperation,+ grant: () => Promise<unknown>,+ ): Promise<void> => {+ const { share, access } = context.current;+ if (share.visibility !== 'private' || access.grants.some((item) => !isScopeGrant(item))) {+ await context.mutate(grant);+ return;+ }+ const lifted = await context.mutate(() =>+ api.setNoteShareVisibility(context.remoteId, 'invited', [], { signal: context.signal }),+ );+ context.check();+ setState({ ...context.current, share: lifted.share });+ requestSync('manual');+ if (lifted.raw_token) await remember(context, lifted.raw_token);+ try {+ await context.mutate(grant);+ } catch (failure) {+ // Only a refusal leaves the grant unmade; an unconfirmed request may have gone through.+ if (failure instanceof ApiError) {+ const restored = await api+ .disableNoteShare(context.remoteId, { signal: context.signal })+ .catch(() => null);+ context.check();+ if (restored) {+ setState((shown) => shown && { ...shown, share: restored.share });+ setHasToken(false);+ await removeNoteShareToken(context.userId, context.remoteId).catch(() => undefined);+ }+ }+ throw failure;+ }+ };++ const linkFor = async (context: SharingOperation): Promise<string> => {+ const invitation = invitationLink(context.current.share);+ if (invitation) return invitation;+ const token = await loadToken(context.userId, context.remoteId, context.current);+ context.check();+ setHasToken(Boolean(token));+ if (!token)+ throw new Error(+ 'The link is unavailable on this device. Choose Replace link to create a new one.',+ );+ return buildNoteShareUrl(token);+ };++ const sendLink = async (destination: 'copy' | 'share' | 'open'): Promise<void> => {+ await run(async (context) => {+ const url = await linkFor(context);+ if (destination === 'copy') {+ await Clipboard.setStringAsync(url);+ context.check();+ setMessage('Link copied.');+ } else if (destination === 'open') {+ context.release();+ await WebBrowser.openBrowserAsync(url);+ } else await sendUrl(context, url);+ });+ };++ const inviteEmail = async (input: string): Promise<boolean> => {+ const email = input.trim().toLowerCase();+ if (!isValidEmail(email)) {+ setMessage(null);+ setError(INVALID_EMAIL_ERROR);+ return false;+ }+ return run(+ async (context) => {+ if (+ context.current.access.grants.some(+ (grant) => grant.principal.email?.toLowerCase() === email,+ ) ||+ context.current.invitations.some(+ (invite) => !invite.revoked_at && invite.email.toLowerCase() === email,+ )+ ) {+ throw new Error('This person already has access or an invitation.');+ }+ await grantWithFullLink(context, () =>+ api.createNoteAccessGrant(+ context.remoteId,+ { principal_type: 'email', email, permission: 'viewer' },+ { signal: context.signal },+ ),+ );+ context.check();+ setMessage('Access granted.');+ const updated = await adopt(context);+ if (+ updated.invitations.some(+ (invite) =>+ invite.email.toLowerCase() === email && !invite.revoked_at && !invite.last_emailed_at,+ )+ ) {+ setMessage(+ 'Access granted, but the invitation email was not sent. Use Resend to try again.',+ );+ }+ },+ { publish: true },+ );+ };++ const addPrincipal = async (principal: AccessPrincipalSuggestion): Promise<void> => {+ await run(+ async (context) => {+ if (+ isGroupPrincipal(principal.type) &&+ !context.current.access.can_manage_inherited_access+ ) {+ throw new Error('You do not have permission to manage group access.');+ }+ await grantWithFullLink(context, () =>+ api.createNoteAccessGrant(+ context.remoteId,+ {+ principal_type: principal.type,+ ...(principal.id ? { principal_id: principal.id } : { email: principal.email ?? '' }),+ permission: 'viewer',+ },+ { signal: context.signal },+ ),+ );+ context.check();+ await adopt(context);+ setMessage('Access granted.');+ },+ { publish: true },+ );+ };+ const changeGrant = async (+ grant: NoteAccessGrant,+ permission: NoteAccessGrant['permission'] | null,+ ): Promise<void> => {+ await run(async (context) => {+ const fresh = context.current.access.grants.find((item) => item.id === grant.id);+ if (!fresh) throw new Error('Access changed. Refresh and try again.');+ if (!canChangeGrant(context.current.access, fresh)) {+ if (isScopeGrant(fresh))+ throw new Error('Inherited access is managed in its team or space.');+ throw new Error('You do not have permission to change inherited access.');+ }+ if (permission)+ await context.mutate(() =>+ api.updateNoteAccessGrant(context.remoteId, grant.id, permission, {+ signal: context.signal,+ }),+ );+ else+ await context.mutate(() =>+ api.removeNoteAccessGrant(context.remoteId, grant.id, { signal: context.signal }),+ );+ context.check();+ await adopt(context);+ });+ };+ const invitationAction = async (+ invitation: NoteShareInvitation,+ resend: boolean,+ ): Promise<void> => {+ await run(async (context) => {+ if (resend) {+ // A resend only sends email, so a failure never leaves sharing settings unconfirmed.+ try {+ await api.resendNoteInvitation(context.remoteId, invitation.id, {+ signal: context.signal,+ });+ } catch (failure) {+ context.check();+ if (failure instanceof ApiError && failure.status === 502)+ throw new Error('The invitation email could not be sent. Try again later.');+ throw failure;+ }+ context.check();+ setMessage('Invitation sent.');+ } else+ await context.mutate(() =>+ api.revokeNoteInvitation(context.remoteId, invitation.id, { signal: context.signal }),+ );+ context.check();+ await adopt(context);+ });+ };++ return {+ state,+ loading,+ busy,+ cancellable,+ error,+ message,+ hasLink: hasToken || Boolean(state && invitationLink(state.share)),+ sharingMode,+ note,+ user,+ refresh: (): Promise<void> => refresh(),+ dismissError: (): void => setError(null),+ setVisibility,+ replaceLink,+ copyLink: (): Promise<void> => sendLink('copy'),+ shareLink: (): Promise<void> => sendLink('share'),+ openLink: (): Promise<void> => sendLink('open'),+ inviteEmail,+ addPrincipal,+ updateGrant: (+ grant: NoteAccessGrant,+ permission: NoteAccessGrant['permission'],+ ): Promise<void> => changeGrant(grant, permission),+ removeGrant: (grant: NoteAccessGrant): Promise<void> => changeGrant(grant, null),+ revokeInvitation: (invitation: NoteShareInvitation): Promise<void> =>+ invitationAction(invitation, false),+ resendInvitation: (invitation: NoteShareInvitation): Promise<void> =>+ invitationAction(invitation, true),+ };+}diff --git a/openwhispr-mobile/src/lib/notes/__tests__/noteShareDomains.test.ts b/openwhispr-mobile/src/lib/notes/__tests__/noteShareDomains.test.tsnew file mode 100644index 000000000..53600bcae--- /dev/null+++ b/openwhispr-mobile/src/lib/notes/__tests__/noteShareDomains.test.ts@@ -0,0 +1,16 @@+import { emailDomain, isPersonalEmailDomain } from '../noteShareDomains';++it('extracts normalized address domains including display-name forms', () => {+ expect(emailDomain(' Ada <[email protected]> ')).toBe('example.com');+ expect(emailDomain('invalid')).toBe('');+});++it('classifies desktop personal domains exactly', () => {+ expect(isPersonalEmailDomain('GMAIL.COM')).toBe(true);+ expect(isPersonalEmailDomain('example.com')).toBe(false);+});++it('treats Apple relay addresses as personal like the server does', () => {+ expect(isPersonalEmailDomain('privaterelay.appleid.com')).toBe(true);+ expect(isPersonalEmailDomain('private.icloud.com')).toBe(true);+});diff --git a/openwhispr-mobile/src/lib/notes/__tests__/noteSharePolicy.test.ts b/openwhispr-mobile/src/lib/notes/__tests__/noteSharePolicy.test.tsnew file mode 100644index 000000000..9b3380344--- /dev/null+++ b/openwhispr-mobile/src/lib/notes/__tests__/noteSharePolicy.test.ts@@ -0,0 +1,21 @@+import { isShareVisibilityAllowed } from '../noteSharePolicy';++it('allows every mode when sharing is unrestricted or the policy is unknown', () => {+ for (const mode of ['allowed', null] as const) {+ expect(isShareVisibilityAllowed(mode, 'link')).toBe(true);+ expect(isShareVisibilityAllowed(mode, 'invited')).toBe(true);+ expect(isShareVisibilityAllowed(mode, 'domain')).toBe(true);+ }+});++it('limits a domain-only organization to domain sharing, like the server', () => {+ expect(isShareVisibilityAllowed('domain_only', 'domain')).toBe(true);+ expect(isShareVisibilityAllowed('domain_only', 'invited')).toBe(false);+ expect(isShareVisibilityAllowed('domain_only', 'link')).toBe(false);+});++it('keeps making a note private available when sharing is disabled', () => {+ expect(isShareVisibilityAllowed('disabled', 'private')).toBe(true);+ expect(isShareVisibilityAllowed('disabled', 'domain')).toBe(false);+ expect(isShareVisibilityAllowed('disabled', 'invited')).toBe(false);+});diff --git a/openwhispr-mobile/src/lib/notes/__tests__/noteShareTokens.test.ts b/openwhispr-mobile/src/lib/notes/__tests__/noteShareTokens.test.tsnew file mode 100644index 000000000..81635855e--- /dev/null+++ b/openwhispr-mobile/src/lib/notes/__tests__/noteShareTokens.test.ts@@ -0,0 +1,206 @@+const mockStored = new Map<string, string>();+jest.mock('expo-secure-store', () => ({+ AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY: 3,+ getItemAsync: jest.fn(async (key: string) => mockStored.get(key) ?? null),+ setItemAsync: jest.fn(async (key: string, value: string) => {+ mockStored.set(key, value);+ }),+ deleteItemAsync: jest.fn(async (key: string) => {+ mockStored.delete(key);+ }),+}));++import * as SecureStore from 'expo-secure-store';+import {+ readNoteShareToken,+ saveNoteShareToken,+ removeNoteShareToken,+ clearNoteShareTokens,+ claimNoteShareTokens,+ buildNoteShareUrl,+ buildNoteInviteUrl,+} from '../noteShareTokens';++const token = `ow_share_${'A'.repeat(32)}`;++beforeEach(() => {+ mockStored.clear();+ jest.clearAllMocks();+});++it('isolates tokens by account and note', async () => {+ await saveNoteShareToken('account-a', 'note', token);+ expect(await readNoteShareToken('account-a', 'note')).toBe(token);+ expect(await readNoteShareToken('account-b', 'note')).toBeNull();+ expect(await readNoteShareToken('account-a', 'other')).toBeNull();+});++it('rejects malformed tokens without writing them', async () => {+ await expect(saveNoteShareToken('user', 'note', 'ow_share_short')).rejects.toThrow();+ expect(mockStored.size).toBe(0);+ expect(() => buildNoteShareUrl('ow_share_short')).toThrow();+});++it('builds the invitation link from the server token prefix', () => {+ expect(buildNoteInviteUrl('ow_share_Ab_9-xY')).toBe(+ 'https://notes.openwhispr.com/invite/ow_share_Ab_9-xY',+ );+ expect(() => buildNoteInviteUrl(token)).toThrow();+ expect(() => buildNoteInviteUrl('ow_share_ab')).toThrow();+});++it('removes a token when the server prefix changes', async () => {+ await saveNoteShareToken('user', 'note', token);+ expect(await readNoteShareToken('user', 'note', 'ow_share_B')).toBeNull();+ expect(await readNoteShareToken('user', 'note')).toBeNull();+});++it('removes individual tokens and all tokens for an account', async () => {+ await Promise.all([+ saveNoteShareToken('user', 'one', token),+ saveNoteShareToken('user', 'two', token),+ ]);+ await removeNoteShareToken('user', 'one');+ expect(await readNoteShareToken('user', 'one')).toBeNull();+ await clearNoteShareTokens('user');+ expect(await readNoteShareToken('user', 'two')).toBeNull();+ expect(mockStored.size).toBe(0);+});++it('does not recreate a secret when cleanup overtakes a pending write', async () => {+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ jest.mocked(SecureStore.setItemAsync).mockImplementationOnce(async (key, value) => {+ await gate;+ mockStored.set(key, value);+ });+ const save = saveNoteShareToken('user', 'note', token);+ while (jest.mocked(SecureStore.setItemAsync).mock.calls.length === 0) await Promise.resolve();+ const clear = clearNoteShareTokens('user');+ release();+ await Promise.all([save, clear]);+ expect(await readNoteShareToken('user', 'note')).toBeNull();+ expect(mockStored.size).toBe(0);+});++it('propagates storage failures without leaving an indexed token', async () => {+ jest.mocked(SecureStore.setItemAsync).mockRejectedValueOnce(new Error('storage unavailable'));+ await expect(saveNoteShareToken('user', 'note', token)).rejects.toThrow('storage unavailable');+ expect(await readNoteShareToken('user', 'note')).toBeNull();+});++it('removes a newly saved secret if its account index cannot be stored', async () => {+ jest+ .mocked(SecureStore.setItemAsync)+ .mockImplementationOnce(async (key, value) => {+ mockStored.set(key, value);+ })+ .mockRejectedValueOnce(new Error('index unavailable'));+ await expect(saveNoteShareToken('user', 'note', token)).rejects.toThrow('index unavailable');+ expect(await readNoteShareToken('user', 'note')).toBeNull();+});++it('removes a cached token when the server reports no live token prefix', async (): Promise<void> => {+ await saveNoteShareToken('user', 'note', token);+ expect(await readNoteShareToken('user', 'note', null)).toBeNull();+ expect(await readNoteShareToken('user', 'note')).toBeNull();+});++it('keeps secrets on this device and readable in the background', async (): Promise<void> => {+ await claimNoteShareTokens('user');+ await saveNoteShareToken('user', 'note', token);+ await readNoteShareToken('user', 'note');+ await removeNoteShareToken('user', 'note');+ await clearNoteShareTokens('user');+ const calls = [+ ...jest.mocked(SecureStore.getItemAsync).mock.calls.map(([, options]) => options),+ ...jest.mocked(SecureStore.setItemAsync).mock.calls.map(([, , options]) => options),+ ...jest.mocked(SecureStore.deleteItemAsync).mock.calls.map(([, options]) => options),+ ];+ expect(calls.length).toBeGreaterThan(0);+ for (const options of calls) {+ expect(options).toEqual({+ keychainAccessible: SecureStore.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY,+ requireAuthentication: false,+ });+ }+});++describe('claimNoteShareTokens', () => {+ it('keeps the links of the account that signs back in', async (): Promise<void> => {+ await claimNoteShareTokens('account-a');+ await saveNoteShareToken('account-a', 'note', token);+ await claimNoteShareTokens('account-a');+ expect(await readNoteShareToken('account-a', 'note')).toBe(token);+ });++ it('erases the previous account links when a different account signs in', async (): Promise<void> => {+ await claimNoteShareTokens('account-a');+ await saveNoteShareToken('account-a', 'note', token);+ await claimNoteShareTokens('account-b');+ expect(await readNoteShareToken('account-a', 'note')).toBeNull();+ await saveNoteShareToken('account-b', 'note', token);+ await claimNoteShareTokens('account-b');+ expect(await readNoteShareToken('account-b', 'note')).toBe(token);+ });++ it('retries an erase that failed at the next sign-in', async (): Promise<void> => {+ await claimNoteShareTokens('account-a');+ await saveNoteShareToken('account-a', 'note', token);+ jest+ .mocked(SecureStore.getItemAsync)+ .mockImplementationOnce(async (key) => mockStored.get(key) ?? null)+ .mockRejectedValueOnce(new Error('keychain locked'));+ await expect(claimNoteShareTokens('account-b')).rejects.toThrow();+ expect(await readNoteShareToken('account-a', 'note')).toBe(token);+ await saveNoteShareToken('account-b', 'note', token);+ await claimNoteShareTokens('account-c');+ expect(await readNoteShareToken('account-a', 'note')).toBeNull();+ expect(await readNoteShareToken('account-b', 'note')).toBeNull();+ });+});++describe('clearNoteShareTokens', () => {+ it('retries a failed account erase at the next sign-in of another account', async (): Promise<void> => {+ await claimNoteShareTokens('account-a');+ await saveNoteShareToken('account-a', 'note', token);+ jest.mocked(SecureStore.getItemAsync).mockRejectedValueOnce(new Error('keychain locked'));+ await expect(clearNoteShareTokens('account-a')).rejects.toThrow('keychain locked');+ expect(await readNoteShareToken('account-a', 'note')).toBe(token);+ await claimNoteShareTokens('account-b');+ expect(await readNoteShareToken('account-a', 'note')).toBeNull();+ });++ it('forgets an erased account so it no longer counts as a previous owner', async (): Promise<void> => {+ await claimNoteShareTokens('account-a');+ await clearNoteShareTokens('account-a');+ expect(mockStored.size).toBe(0);+ });+});++describe('owner records', () => {+ it('records an account when it stores a link, even if its sign-in claim failed', async (): Promise<void> => {+ await saveNoteShareToken('account-a', 'note', token);+ await claimNoteShareTokens('account-b');+ expect(await readNoteShareToken('account-a', 'note')).toBeNull();+ });++ it('treats a corrupt owners record as empty instead of failing every sign-in', async (): Promise<void> => {+ mockStored.set('openwhispr.noteShares.owners', '{not json');+ await expect(claimNoteShareTokens('account-a')).resolves.toBeUndefined();+ await saveNoteShareToken('account-a', 'note', token);+ await claimNoteShareTokens('account-b');+ expect(await readNoteShareToken('account-a', 'note')).toBeNull();+ });++ it('keeps the owners record consistent when claims overlap', async (): Promise<void> => {+ await saveNoteShareToken('account-a', 'note', token);+ await saveNoteShareToken('account-b', 'note', token);+ await Promise.all([claimNoteShareTokens('account-b'), claimNoteShareTokens('account-c')]);+ expect(await readNoteShareToken('account-a', 'note')).toBeNull();+ expect(await readNoteShareToken('account-b', 'note')).toBeNull();+ expect(mockStored.has('openwhispr.noteShares.owners')).toBe(false);+ });+});diff --git a/openwhispr-mobile/src/lib/notes/noteShareAccess.ts b/openwhispr-mobile/src/lib/notes/noteShareAccess.tsnew file mode 100644index 000000000..8b8a1199e--- /dev/null+++ b/openwhispr-mobile/src/lib/notes/noteShareAccess.ts@@ -0,0 +1,30 @@+import type { NoteAccessGrant, NoteAccessState } from '@/data/remote/noteSharingTypes';++export function isGroupPrincipal(type: NoteAccessGrant['principal']['type']): boolean {+ return type === 'team' || type === 'folder' || type === 'workspace';+}++/** A synthetic row for team-space or workspace membership, which is managed where it comes from. */+export function isScopeGrant(grant: NoteAccessGrant): boolean {+ return grant.id.startsWith('scope:');+}++/**+ * The server marks every stored group grant `inherited`; only synthetic `scope:` rows (space or+ * workspace membership) are read-only. Stored group grants need inherited-access management.+ */+export function canChangeGrant(+ access: NoteAccessState | undefined,+ grant: NoteAccessGrant,+): boolean {+ return Boolean(+ access?.can_manage_access &&+ !isScopeGrant(grant) &&+ (!grant.inherited || access.can_manage_inherited_access),+ );+}++/** Private visibility suspends every stored grant and invitation; scope membership still applies. */+export function isPausedBySharingOff(grant: NoteAccessGrant): boolean {+ return !isScopeGrant(grant);+}diff --git a/openwhispr-mobile/src/lib/notes/noteShareDomains.ts b/openwhispr-mobile/src/lib/notes/noteShareDomains.tsnew file mode 100644index 000000000..519ed5cd0--- /dev/null+++ b/openwhispr-mobile/src/lib/notes/noteShareDomains.ts@@ -0,0 +1,58 @@+// Mirrors PERSONAL_EMAIL_DOMAINS in the API's lib/personal-email-domains.ts, which rejects these+// as domain allowlists; an entry missing here offers an organization option the server refuses.+const PERSONAL_EMAIL_DOMAINS = new Set<string>([+ 'gmail.com',+ 'googlemail.com',+ 'outlook.com',+ 'hotmail.com',+ 'live.com',+ 'msn.com',+ 'yahoo.com',+ 'yahoo.co.uk',+ 'ymail.com',+ 'rocketmail.com',+ 'icloud.com',+ 'me.com',+ 'mac.com',+ 'privaterelay.appleid.com',+ 'private.icloud.com',+ 'proton.me',+ 'protonmail.com',+ 'pm.me',+ 'aol.com',+ 'fastmail.com',+ 'fastmail.fm',+ 'tutanota.com',+ 'tuta.io',+ 'gmx.com',+ 'gmx.de',+ 'gmx.net',+ 'mail.com',+ 'zoho.com',+ 'yandex.com',+ 'yandex.ru',+ 'duck.com',+ 'hey.com',+ 'qq.com',+ '163.com',+ '126.com',+ 'sina.com',+]);++export function emailDomain(email: string): string {+ if (typeof email !== 'string') return '';+ const trimmed = email.trim();+ const angle = /<([^<>]+)>/.exec(trimmed);+ const address = (angle ? angle[1] : trimmed).trim();+ const at = address.lastIndexOf('@');+ if (at === -1) return '';+ return address+ .slice(at + 1)+ .trim()+ .toLowerCase();+}++export function isPersonalEmailDomain(domain: string): boolean {+ if (typeof domain !== 'string') return false;+ return PERSONAL_EMAIL_DOMAINS.has(domain.toLowerCase());+}diff --git a/openwhispr-mobile/src/lib/notes/noteSharePolicy.ts b/openwhispr-mobile/src/lib/notes/noteSharePolicy.tsnew file mode 100644index 000000000..c291e8a72--- /dev/null+++ b/openwhispr-mobile/src/lib/notes/noteSharePolicy.ts@@ -0,0 +1,10 @@+import type { ExternalSharingMode, ShareVisibility } from '@/data/remote/noteSharingTypes';++/** Mirrors the server's isSharingBlocked; an unknown policy is left to the server to enforce. */+export function isShareVisibilityAllowed(+ mode: ExternalSharingMode | null,+ visibility: ShareVisibility,+): boolean {+ if (visibility === 'private' || !mode || mode === 'allowed') return true;+ return mode === 'domain_only' && visibility === 'domain';+}diff --git a/openwhispr-mobile/src/lib/notes/noteShareTokens.ts b/openwhispr-mobile/src/lib/notes/noteShareTokens.tsnew file mode 100644index 000000000..a25095d0a--- /dev/null+++ b/openwhispr-mobile/src/lib/notes/noteShareTokens.ts@@ -0,0 +1,177 @@+import * as SecureStore from 'expo-secure-store';+import { Buffer } from 'buffer';+import { getNoteShareViewerBaseUrl } from '@/config/noteSharing';++const FULL_TOKEN = /^ow_share_[A-Za-z0-9_-]{32}$/;+const TOKEN_PREFIX = /^ow_share_[A-Za-z0-9_-]{7}$/;+const ACCOUNT_PREFIX = 'openwhispr.noteShares.';+const OWNERS_KEY = `${ACCOUNT_PREFIX}owners`;+const SECURE_OPTIONS: SecureStore.SecureStoreOptions = {+ keychainAccessible: SecureStore.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY,+ requireAuthentication: false,+};+const accountQueues = new Map<string, Promise<void>>();+const accountEpochs = new Map<string, number>();++function accountKey(userId: string): string {+ return `${ACCOUNT_PREFIX}${Buffer.from(userId, 'utf8').toString('hex')}`;+}++function indexKey(userId: string): string {+ return `${accountKey(userId)}.index`;+}++function tokenKey(userId: string, remoteId: string): string {+ return `${accountKey(userId)}.${Buffer.from(remoteId, 'utf8').toString('hex')}`;+}++/** Serializes read-modify-write operations on one account's entries, or on the owners record. */+function enqueue(queue: string, operation: () => Promise<void>): Promise<void> {+ const previous = accountQueues.get(queue) ?? Promise.resolve();+ const current = previous.catch(() => undefined).then(operation);+ accountQueues.set(queue, current);+ const release = (): void => {+ if (accountQueues.get(queue) === current) accountQueues.delete(queue);+ };+ current.then(release, release);+ return current;+}++async function readIds(key: string): Promise<string[]> {+ const value = await SecureStore.getItemAsync(key, SECURE_OPTIONS);+ if (!value) return [];+ // A record we cannot trust must not block saving or signing in for good.+ try {+ const parsed: unknown = JSON.parse(value);+ return Array.isArray(parsed) && parsed.every((item) => typeof item === 'string') ? parsed : [];+ } catch {+ return [];+ }+}++async function writeIds(key: string, ids: string[]): Promise<void> {+ if (ids.length) await SecureStore.setItemAsync(key, JSON.stringify(ids), SECURE_OPTIONS);+ else await SecureStore.deleteItemAsync(key, SECURE_OPTIONS);+}++export async function readNoteShareToken(+ userId: string,+ remoteId: string,+ expectedPrefix?: string | null,+): Promise<string | null> {+ const epoch = accountEpochs.get(userId) ?? 0;+ const stored = await SecureStore.getItemAsync(tokenKey(userId, remoteId), SECURE_OPTIONS);+ if (epoch !== (accountEpochs.get(userId) ?? 0)) return null;+ if (!stored) return null;+ if (+ !FULL_TOKEN.test(stored) ||+ (expectedPrefix !== undefined && (!expectedPrefix || !stored.startsWith(expectedPrefix)))+ ) {+ await removeNoteShareToken(userId, remoteId);+ return null;+ }+ return stored;+}++export async function saveNoteShareToken(+ userId: string,+ remoteId: string,+ token: string,+): Promise<void> {+ if (!FULL_TOKEN.test(token)) throw new Error('Invalid note share token');+ const epoch = accountEpochs.get(userId) ?? 0;+ // Record the owner before storing a secret, so the next account to sign in always erases it.+ await enqueue(OWNERS_KEY, async () => {+ const owners = await readIds(OWNERS_KEY);+ if (!owners.includes(userId)) await writeIds(OWNERS_KEY, [...owners, userId]);+ });+ await enqueue(userId, async () => {+ if (epoch !== (accountEpochs.get(userId) ?? 0)) return;+ const index = await readIds(indexKey(userId));+ if (epoch !== (accountEpochs.get(userId) ?? 0)) return;+ await SecureStore.setItemAsync(tokenKey(userId, remoteId), token, SECURE_OPTIONS);+ if (epoch !== (accountEpochs.get(userId) ?? 0)) {+ await SecureStore.deleteItemAsync(tokenKey(userId, remoteId), SECURE_OPTIONS);+ return;+ }+ if (!index.includes(remoteId)) {+ try {+ await writeIds(indexKey(userId), [...index, remoteId]);+ } catch (error) {+ await SecureStore.deleteItemAsync(tokenKey(userId, remoteId), SECURE_OPTIONS);+ throw error;+ }+ }+ });+}++export async function removeNoteShareToken(userId: string, remoteId: string): Promise<void> {+ await enqueue(userId, async () => {+ const index = await readIds(indexKey(userId));+ await SecureStore.deleteItemAsync(tokenKey(userId, remoteId), SECURE_OPTIONS);+ if (index.includes(remoteId)) {+ await writeIds(+ indexKey(userId),+ index.filter((id) => id !== remoteId),+ );+ }+ });+}++async function eraseAccount(userId: string): Promise<void> {+ accountEpochs.set(userId, (accountEpochs.get(userId) ?? 0) + 1);+ await enqueue(userId, async () => {+ for (const remoteId of await readIds(indexKey(userId))) {+ await SecureStore.deleteItemAsync(tokenKey(userId, remoteId), SECURE_OPTIONS);+ }+ await SecureStore.deleteItemAsync(indexKey(userId), SECURE_OPTIONS);+ });+}++/**+ * Erases the links every other account stored on this device, so links survive sign-out but+ * not the next account. Accounts are recorded when they store a link; one whose links could not+ * be erased stays recorded, and the next sign-in retries it.+ */+export async function claimNoteShareTokens(userId: string): Promise<void> {+ let failed = false;+ await enqueue(OWNERS_KEY, async () => {+ const owners = await readIds(OWNERS_KEY);+ const kept = owners.filter((id) => id === userId);+ for (const owner of owners.filter((id) => id !== userId)) {+ try {+ await eraseAccount(owner);+ } catch {+ kept.push(owner);+ failed = true;+ }+ }+ if (kept.length !== owners.length) await writeIds(OWNERS_KEY, kept);+ });+ if (failed) throw new Error('Could not erase note share links of a previous account');+}++/** Erases an account's links; if that fails, the account stays recorded for the next sign-in. */+export async function clearNoteShareTokens(userId: string): Promise<void> {+ await eraseAccount(userId);+ await enqueue(OWNERS_KEY, async () => {+ const owners = await readIds(OWNERS_KEY);+ if (owners.includes(userId)) {+ await writeIds(+ OWNERS_KEY,+ owners.filter((id) => id !== userId),+ );+ }+ });+}++export function buildNoteShareUrl(token: string): string {+ if (!FULL_TOKEN.test(token)) throw new Error('Invalid note share token');+ return `${getNoteShareViewerBaseUrl()}/n/${token}`;+}++/** The sign-in link invitation emails carry; it opens for invited people and needs no full token. */+export function buildNoteInviteUrl(prefix: string): string {+ if (!TOKEN_PREFIX.test(prefix)) throw new Error('Invalid note share token prefix');+ return `${getNoteShareViewerBaseUrl()}/invite/${prefix}`;+}diff --git a/openwhispr-mobile/src/screens/NoteEditorScreen.tsx b/openwhispr-mobile/src/screens/NoteEditorScreen.tsxindex 2028d24a1..6b96f2e73 100644--- a/openwhispr-mobile/src/screens/NoteEditorScreen.tsx+++ b/openwhispr-mobile/src/screens/NoteEditorScreen.tsx@@ -6,7 +6,6 @@ import {Pressable,KeyboardAvoidingView,Platform,- ActionSheetIOS,ActivityIndicator,Alert,} from 'react-native';@@ -28,6 +27,7 @@ import { useAudioRecording } from '@/hooks/useAudioRecording';import { useSuperwallGate } from '@/hooks/useSuperwallGate';import { useUsageLimitRecovery } from '@/hooks/useUsageLimitRecovery';import { MarkdownRenderer } from '@/components/notes/MarkdownRenderer';+import { NoteShareSheet } from '@/components/notes/NoteShareSheet';import { NoteActionsMenu } from '@/components/notes/NoteActionsMenu';import { ConflictBanner } from '@/components/notes/ConflictBanner';import { NoteChatSheet } from '@/components/notes/NoteChatSheet';@@ -165,6 +165,7 @@ export default function NoteEditorScreen() {const [mergeSheetVisible, setMergeSheetVisible] = useState(false);const [suggestionSheetVisible, setSuggestionSheetVisible] = useState(false);const [chatVisible, setChatVisible] = useState(false);+ const [shareVisible, setShareVisible] = useState(false);const [chatMessages, setChatMessages] = useState<ChatOverNoteMessage[]>([]);const [chatDraft, setChatDraft] = useState('');const [chatError, setChatError] = useState<string | null>(null);@@ -212,6 +213,7 @@ export default function NoteEditorScreen() {chatAbortRef.current?.abort();chatAbortRef.current = null;setChatVisible(false);+ setShareVisible(false);setChatMessages([]);setChatDraft('');setChatError(null);@@ -350,50 +352,46 @@ export default function NoteEditorScreen() {[addLearnedWords],);- const debouncedSave = useCallback(- (updates: { title?: string; content?: string }) => {- if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current);- saveTimeoutRef.current = setTimeout(() => {- updateNote(noteId, updates);- if (typeof updates.content === 'string') {- maybeLearnCorrections(updates.content);- }- }, 800);- },- [noteId, updateNote, maybeLearnCorrections],- );+ const flushDraft = useCallback((): void => {+ if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current);+ saveTimeoutRef.current = null;+ const titleChanged = titleRef.current !== originalTitleRef.current;+ const contentChanged =+ !usesSegmentTranscriptRef.current && contentRef.current !== originalContentRef.current;+ if (!titleChanged && !contentChanged) return;+ updateNote(noteId, {+ ...(titleChanged ? { title: titleRef.current } : {}),+ ...(contentChanged ? { content: contentRef.current } : {}),+ });+ originalTitleRef.current = titleRef.current;+ if (contentChanged) {+ originalContentRef.current = contentRef.current;+ maybeLearnCorrections(contentRef.current);+ }+ }, [noteId, updateNote, maybeLearnCorrections]);- useEffect(- () => () => {- if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current);- const titleChanged = titleRef.current !== originalTitleRef.current;- const contentChanged =- !usesSegmentTranscriptRef.current && contentRef.current !== originalContentRef.current;- if (!titleChanged && !contentChanged) return;- updateNote(noteId, {- ...(titleChanged ? { title: titleRef.current } : {}),- ...(contentChanged ? { content: contentRef.current } : {}),- });- },- // eslint-disable-next-line react-hooks/exhaustive-deps- [noteId],- );+ const debouncedSave = useCallback((): void => {+ if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current);+ saveTimeoutRef.current = setTimeout(flushDraft, 800);+ }, [flushDraft]);++ useEffect(() => flushDraft, [flushDraft]);const handleTitleChange = useCallback((text: string) => {setTitle(text);- debouncedSave(- usesSegmentTranscript ? { title: text } : { title: text, content: contentRef.current },- );+ titleRef.current = text;+ debouncedSave();},- [debouncedSave, usesSegmentTranscript],+ [debouncedSave],);const handleContentChange = useCallback((text: string) => {if (usesSegmentTranscript) return;setContent(text);- debouncedSave({ title: titleRef.current, content: text });+ contentRef.current = text;+ debouncedSave();},[debouncedSave, usesSegmentTranscript],);@@ -442,7 +440,9 @@ export default function NoteEditorScreen() {// Re-root the learner baseline to the freshly-dictated text so we only// learn from user edits performed after this dictation.learnedBaselineRef.current = newContent;- debouncedSave({ title: titleRef.current, content: newContent });+ // The save reads the ref, and an unmounted editor never re-renders to update it.+ contentRef.current = newContent;+ debouncedSave();safeHaptics('success');if (useProcessingModeStore.getState().activeMode === 'cloud') {useUsageStore.getState().load(true);@@ -499,30 +499,25 @@ export default function NoteEditorScreen() {}}, [activeMode, isRecording, registerSuperwallGate, startRecording, stopRecording, user]);- const handleExport = useCallback(() => {- safeHaptics('light');- ActionSheetIOS.showActionSheetWithOptions(- {- options: ['Export as Markdown', 'Export as Plain Text', 'Cancel'],- cancelButtonIndex: 2,- },- (buttonIndex) => {- const payload = {- title: titleRef.current,+ const handleExport = useCallback(+ (format: 'md' | 'txt'): void => {+ safeHaptics('light');+ exportNote(+ {+ title: titleRef.current || 'Untitled',content: buildNoteShareContent({viewMode,enhancedContent: note?.enhancedContent ?? null,usesSegmentTranscript,- // Title-free: exportNote already leads the file with the title.transcript: formatTranscriptForExport({ blocks: transcriptBlocks }),content: contentRef.current,}),- };- if (buttonIndex === 0) exportNote(payload, 'md');- if (buttonIndex === 1) exportNote(payload, 'txt');- },- );- }, [note?.enhancedContent, transcriptBlocks, usesSegmentTranscript, viewMode]);+ },+ format,+ ).catch(() => Alert.alert('Export failed', 'Could not export this note. Please try again.'));+ },+ [note?.enhancedContent, transcriptBlocks, usesSegmentTranscript, viewMode],+ );const handleCopyTranscript = useCallback(() => {if (!transcriptText.trim()) return;@@ -915,6 +910,14 @@ export default function NoteEditorScreen() {return (<View className="flex-1 bg-systemBackground">+ {shareVisible ? (+ <NoteShareSheet+ noteId={noteId}+ onClose={() => setShareVisible(false)}+ onFlushDraft={flushDraft}+ onExport={handleExport}+ />+ ) : null}<TabScreenHeadertitle={title || 'Untitled'}left={<GlassBackButton fallbackRoute="/(tabs)/(notes)" />}@@ -931,7 +934,7 @@ export default function NoteEditorScreen() {askNoteDisabled={isChatProcessing}onCopyGeneratedNote={note?.enhancedContent ? handleCopyGeneratedNote : undefined}onCopyTranscript={usesSegmentTranscript ? handleCopyTranscript : undefined}- onShare={handleExport}+ onShare={() => setShareVisible(true)}onDelete={handleDelete}/>}diff --git a/openwhispr-mobile/src/screens/__tests__/NoteEditorScreen.calendarContext.test.tsx b/openwhispr-mobile/src/screens/__tests__/NoteEditorScreen.calendarContext.test.tsxindex e300fc0d0..1bdb6a481 100644--- a/openwhispr-mobile/src/screens/__tests__/NoteEditorScreen.calendarContext.test.tsx+++ b/openwhispr-mobile/src/screens/__tests__/NoteEditorScreen.calendarContext.test.tsx@@ -687,6 +687,8 @@ describe('NoteEditorScreen generated titles', () => {});});+jest.mock('@/components/notes/NoteShareSheet', () => ({ NoteShareSheet: () => null }));+it('runs signed-out note formatting through Providers without requiring a Cloud account', async () => {mockAuthState.user = null;mockConfigState.config.inference = {diff --git a/openwhispr-mobile/src/screens/__tests__/NoteEditorScreen.conflictBanner.test.tsx b/openwhispr-mobile/src/screens/__tests__/NoteEditorScreen.conflictBanner.test.tsxindex e38632eee..03c83015f 100644--- a/openwhispr-mobile/src/screens/__tests__/NoteEditorScreen.conflictBanner.test.tsx+++ b/openwhispr-mobile/src/screens/__tests__/NoteEditorScreen.conflictBanner.test.tsx@@ -1,6 +1,7 @@import React from 'react';import { act, fireEvent, render } from '@testing-library/react-native';import NoteEditorScreen from '@/screens/NoteEditorScreen';+import { exportNote } from '@/lib/noteExport';import type { Action, ConflictedNote, Note, RemoteNote, Segment, Speaker } from '@/data/types';const mockUpdateNote = jest.fn();@@ -126,14 +127,19 @@ jest.mock('@/store/useUsageStore', () => {return { useUsageStore };});+let mockOnDictationComplete: ((text: string) => void) | null = null;+jest.mock('@/hooks/useAudioRecording', () => ({- useAudioRecording: () => ({- isRecording: false,- isProcessing: false,- currentText: '',- startRecording: jest.fn(),- stopRecording: jest.fn(),- }),+ useAudioRecording: ({ onComplete }: { onComplete: (text: string) => void }) => {+ mockOnDictationComplete = onComplete;+ return {+ isRecording: false,+ isProcessing: false,+ currentText: '',+ startRecording: jest.fn(),+ stopRecording: jest.fn(),+ };+ },}));jest.mock('@/hooks/useKeyboardHeight', () => ({@@ -202,7 +208,14 @@ jest.mock('@/components/ui/SystemIcon', () => ({}));jest.mock('@/components/notes/NoteActionsMenu', () => ({- NoteActionsMenu: () => null,+ NoteActionsMenu: ({ onShare }: { onShare: () => void }) => {+ const { Pressable, Text } = require('react-native');+ return (+ <Pressable onPress={onShare}>+ <Text>Share note</Text>+ </Pressable>+ );+ },}));jest.mock('@/components/notes/MarkdownRenderer', () => ({@@ -363,3 +376,107 @@ describe('NoteEditorScreen — conflict banner', () => {expect(mockNotesState.getNoteById).toHaveBeenCalledWith(7);});});++jest.mock('@/components/notes/NoteShareSheet', () => ({+ NoteShareSheet: ({+ onFlushDraft,+ onExport,+ }: {+ onFlushDraft: () => void;+ onExport: (format: 'md' | 'txt') => void;+ }) => {+ const { Pressable, Text, View } = require('react-native');+ return (+ <View>+ <Pressable onPress={onFlushDraft}>+ <Text>Create test link</Text>+ </Pressable>+ <Pressable onPress={() => onExport('md')}>+ <Text>Export Markdown</Text>+ </Pressable>+ </View>+ );+ },+}));++jest.mock('@/lib/noteExport', () => ({+ ...jest.requireActual('@/lib/noteExport'),+ exportNote: jest.fn(async () => undefined),+}));++describe('NoteEditorScreen — sharing drafts', () => {+ it('flushes title and body before publishing and does not resave on exit', () => {+ jest.useFakeTimers();+ const screen = render(<NoteEditorScreen />);+ fireEvent.changeText(screen.getByPlaceholderText('Title'), 'Latest title');+ fireEvent.changeText(screen.getByPlaceholderText('Type or dictate…'), 'Latest body');+ fireEvent.press(screen.getByText('Share note'));+ expect(mockUpdateNote).not.toHaveBeenCalled();+ fireEvent.press(screen.getByText('Create test link'));+ expect(mockUpdateNote).toHaveBeenCalledWith(7, {+ title: 'Latest title',+ content: 'Latest body',+ });+ act(() => {+ jest.advanceTimersByTime(1000);+ });+ screen.unmount();+ expect(mockUpdateNote).toHaveBeenCalledTimes(1);+ jest.useRealTimers();+ });++ it('saves dictation that completes after the editor has closed', () => {+ jest.useFakeTimers();+ const screen = render(<NoteEditorScreen />);+ screen.unmount();+ act(() => {+ mockOnDictationComplete?.(' dictated words');+ jest.advanceTimersByTime(1000);+ });+ expect(mockUpdateNote).toHaveBeenCalledWith(7, {+ content: 'Alice owns the launch checklist. dictated words',+ });+ jest.useRealTimers();+ });++ it('exports an untitled note under the untitled label', () => {+ mockNote = note({ title: '' });+ mockNotesState.notes = [mockNote];+ const screen = render(<NoteEditorScreen />);+ fireEvent.press(screen.getByText('Share note'));+ fireEvent.press(screen.getByText('Export Markdown'));+ expect(exportNote).toHaveBeenCalledWith(expect.objectContaining({ title: 'Untitled' }), 'md');+ });++ it('does not dirty an unchanged note when opening or publishing', () => {+ const screen = render(<NoteEditorScreen />);+ fireEvent.press(screen.getByText('Share note'));+ fireEvent.press(screen.getByText('Create test link'));+ screen.unmount();+ expect(mockUpdateNote).not.toHaveBeenCalled();+ });+});++it('flushes a meeting title without replacing its structured transcript with body text', () => {+ mockNote = note({ noteType: 'meeting', content: 'Stored body' });+ mockNotesState.notes = [mockNote];+ mockSegments = [+ {+ id: 1,+ noteId: 7,+ text: 'Spoken words',+ startMs: 0,+ endMs: 1000,+ speakerId: null,+ segmentIndex: 0,+ source: 'local',+ } as unknown as Segment,+ ];+ const screen = render(<NoteEditorScreen />);+ fireEvent.changeText(screen.getByPlaceholderText('Title'), 'Meeting title');+ fireEvent.press(screen.getByText('Share note'));+ fireEvent.press(screen.getByText('Create test link'));+ expect(mockUpdateNote).toHaveBeenCalledWith(7, { title: 'Meeting title' });+ screen.unmount();+ expect(mockUpdateNote).toHaveBeenCalledTimes(1);+});diff --git a/openwhispr-mobile/src/store/__tests__/useAuthStore.noteShares.test.ts b/openwhispr-mobile/src/store/__tests__/useAuthStore.noteShares.test.tsnew file mode 100644index 000000000..c2e607934--- /dev/null+++ b/openwhispr-mobile/src/store/__tests__/useAuthStore.noteShares.test.ts@@ -0,0 +1,158 @@+const mockStored = new Map<string, string>();++jest.mock('@/lib/authClient', () => ({+ getStoredSession: jest.fn(),+ clearSession: jest.fn(),+ signInWithEmail: jest.fn(),+ signUpWithEmail: jest.fn(),+ signOut: jest.fn(),+ signInWithGoogle: jest.fn(),+ signInWithApple: jest.fn(),+ signInWithMicrosoft: jest.fn(),+ signInAnonymously: jest.fn(),+ deleteAccount: jest.fn(),+ getSession: jest.fn(),+ initAuthenticatedUser: jest.fn(),+}));+jest.mock('@/lib/sentry', () => ({+ Sentry: { captureMessage: jest.fn(), captureException: jest.fn() },+}));+jest.mock('@/store/useUsageStore', () => ({+ useUsageStore: { getState: () => ({ reset: jest.fn(), load: jest.fn() }) },+}));+jest.mock('@/services/agent/AgentComposerService', () => ({ clearAllSessions: jest.fn() }));+jest.mock('@/services/providers/ProviderCredentials', () => ({+ clearProviderCredentials: jest.fn().mockResolvedValue(undefined),+}));+jest.mock('expo-secure-store', () => ({+ AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY: 3,+ getItemAsync: jest.fn(async (key: string) => mockStored.get(key) ?? null),+ setItemAsync: jest.fn(async (key: string, value: string) => {+ mockStored.set(key, value);+ }),+ deleteItemAsync: jest.fn(async (key: string) => {+ mockStored.delete(key);+ }),+}));++import * as SecureStore from 'expo-secure-store';+import { useAuthStore } from '@/store/useAuthStore';+import { deleteAccount, getSession, signInWithEmail, signUpWithEmail } from '@/lib/authClient';+import { readNoteShareToken, saveNoteShareToken } from '@/lib/notes/noteShareTokens';+import type { AuthUser } from '@/lib/authClient';++const token = `ow_share_${'A'.repeat(32)}`;+const accountA: AuthUser = {+ id: 'account-a',+ email: '[email protected]',+ emailVerified: true,+ isAnonymous: false,+};+const accountB: AuthUser = { ...accountA, id: 'account-b', email: '[email protected]' };+const anonymousUser: AuthUser = {+ id: 'anon-user',+ email: '[email protected]',+ emailVerified: false,+ isAnonymous: true,+};++async function signInAs(user: AuthUser): Promise<void> {+ jest+ .mocked(signInWithEmail)+ .mockResolvedValueOnce({ user, sessionCookie: `session=${user.id}`, error: null });+ await useAuthStore.getState().signIn(user.email, 'password');+}++async function shareAs(user: AuthUser): Promise<void> {+ await signInAs(user);+ await saveNoteShareToken(user.id, 'note', token);+}++beforeEach(() => {+ mockStored.clear();+ jest.clearAllMocks();+ useAuthStore.setState({+ user: null,+ sessionCookie: null,+ isGuest: false,+ isInitialized: true,+ isLoading: false,+ error: null,+ });+});++it('keeps stored links when the same account signs back in', async (): Promise<void> => {+ await shareAs(accountA);+ await useAuthStore.getState().signOut();+ await signInAs(accountA);+ expect(await readNoteShareToken(accountA.id, 'note')).toBe(token);+});++it('clears the previous account links when a different account signs in', async (): Promise<void> => {+ await shareAs(accountA);+ await useAuthStore.getState().signOut();+ expect(await readNoteShareToken(accountA.id, 'note')).toBe(token);+ await signInAs(accountB);+ expect(await readNoteShareToken(accountA.id, 'note')).toBeNull();+ expect(useAuthStore.getState().user?.id).toBe(accountB.id);+});++it('keeps links through guest mode, then clears them for the next account', async (): Promise<void> => {+ await shareAs(accountA);+ await useAuthStore.getState().signOut();+ await useAuthStore.getState().continueAsGuest();+ expect(await readNoteShareToken(accountA.id, 'note')).toBe(token);+ await signInAs(accountB);+ expect(await readNoteShareToken(accountA.id, 'note')).toBeNull();+});++it('clears the previous account links when an anonymous session signs up as another account', async (): Promise<void> => {+ await shareAs(accountA);+ await useAuthStore.getState().signOut();+ useAuthStore.setState({ user: anonymousUser, sessionCookie: 'session=anon' });+ jest+ .mocked(signUpWithEmail)+ .mockResolvedValueOnce({ user: accountB, sessionCookie: 'session=b', error: null });+ await useAuthStore.getState().signUp(accountB.email, 'password');+ expect(await readNoteShareToken(accountA.id, 'note')).toBeNull();+});++it('clears the previous account links when a different session is restored at launch', async (): Promise<void> => {+ await shareAs(accountA);+ jest.mocked(getSession).mockResolvedValueOnce(accountB);+ await useAuthStore.getState().initialize();+ expect(await readNoteShareToken(accountA.id, 'note')).toBeNull();+});++it('keeps stored links when an anonymous session is restored at launch', async (): Promise<void> => {+ await shareAs(accountA);+ await useAuthStore.getState().signOut();+ jest.mocked(getSession).mockResolvedValueOnce(anonymousUser);+ await useAuthStore.getState().initialize();+ expect(await readNoteShareToken(accountA.id, 'note')).toBe(token);+});++it('clears stored links after the account is deleted', async (): Promise<void> => {+ await shareAs(accountA);+ await useAuthStore.getState().deleteAccount();+ expect(await readNoteShareToken(accountA.id, 'note')).toBeNull();+ expect(mockStored.size).toBe(0);+});++it('keeps stored links when account deletion fails', async (): Promise<void> => {+ await shareAs(accountA);+ jest.mocked(deleteAccount).mockRejectedValueOnce(new Error('Network request failed'));+ await expect(useAuthStore.getState().deleteAccount()).rejects.toThrow(/network/i);+ expect(await readNoteShareToken(accountA.id, 'note')).toBe(token);+ expect(useAuthStore.getState().user?.id).toBe(accountA.id);+});++it('completes a deletion whose link cleanup failed and retries it at the next sign-in', async (): Promise<void> => {+ await shareAs(accountA);+ jest.mocked(SecureStore.getItemAsync).mockRejectedValueOnce(new Error('keychain locked'));+ await useAuthStore.getState().deleteAccount();+ expect(useAuthStore.getState()).toMatchObject({ user: null, isLoading: false, error: null });+ expect(await readNoteShareToken(accountA.id, 'note')).toBe(token);+ await signInAs(accountB);+ expect(await readNoteShareToken(accountA.id, 'note')).toBeNull();+});diff --git a/openwhispr-mobile/src/store/useAuthStore.ts b/openwhispr-mobile/src/store/useAuthStore.tsindex 56535185c..282eb55bd 100644--- a/openwhispr-mobile/src/store/useAuthStore.ts+++ b/openwhispr-mobile/src/store/useAuthStore.ts@@ -19,6 +19,7 @@ import {import { Sentry } from '@/lib/sentry';import { useUsageStore } from '@/store/useUsageStore';import { clearAllSessions as clearAgentSessions } from '@/services/agent/AgentComposerService';+import { claimNoteShareTokens, clearNoteShareTokens } from '@/lib/notes/noteShareTokens';const GUEST_SESSION_KEY = 'openwhispr_guest_session';@@ -69,6 +70,7 @@ export const useAuthStore = create<AuthStore>((set) => ({try {const user = await getSession();if (user) {+ await claimNoteShares(user);const sessionCookie = await getStoredSession();set({ user, sessionCookie, isGuest: false, isInitialized: true, isLoading: false });} else {@@ -189,6 +191,8 @@ export const useAuthStore = create<AuthStore>((set) => ({await anonymousSignInInFlight?.catch(() => undefined);try {await deleteAccountApi();+ const deletedUserId = useAuthStore.getState().user?.id;+ if (deletedUserId) await tolerateCacheFailure('clear', clearNoteShareTokens(deletedUserId));// Keys survive sign-out by design, but not account deletion. They are erased only// once the account is gone, so a failed delete keeps them. A failed erase leaves// them for Remove all provider keys rather than undoing a completed deletion.@@ -213,6 +217,29 @@ export const useAuthStore = create<AuthStore>((set) => ({type SetState = StoreApi<AuthStore>['setState'];+// A local cache failure must not block sign-in or undo a completed account deletion.+async function tolerateCacheFailure(+ operation: 'claim' | 'clear',+ cleanup: Promise<void>,+): Promise<void> {+ try {+ await cleanup;+ } catch (error) {+ Sentry.captureException(error, {+ level: 'warning',+ tags: { feature: 'note-sharing', operation },+ });+ }+}++// Every real sign-in, including a session restored at launch, passes through here. Only real+// accounts can share, so an anonymous session leaves other accounts' stored links in place.+async function claimNoteShares(user: AuthUser | null): Promise<void> {+ if (user && !user.isAnonymous) {+ await tolerateCacheFailure('claim', claimNoteShareTokens(user.id));+ }+}+async function applyAuthenticatedSession(set: SetState,result: SessionResult,@@ -220,6 +247,7 @@ async function applyAuthenticatedSession(): Promise<void> {await SecureStore.deleteItemAsync(GUEST_SESSION_KEY);await initAuthenticatedUser(result.user, fallbackName);+ await claimNoteShares(result.user);useUsageStore.getState().reset();set({user: result.user,diff --git a/openwhispr-mobile/src/sync/__tests__/ensureNoteSynced.test.ts b/openwhispr-mobile/src/sync/__tests__/ensureNoteSynced.test.tsnew file mode 100644index 000000000..24f6f4a44--- /dev/null+++ b/openwhispr-mobile/src/sync/__tests__/ensureNoteSynced.test.ts@@ -0,0 +1,323 @@+import type { Note } from '@/data';++jest.mock('@/store/useAuthStore', () => ({+ useAuthStore: require('zustand').create(() => ({+ user: { id: 'owner', isAnonymous: false },+ sessionCookie: 'session',+ isGuest: false,+ isLoading: false,+ })),+}));+jest.mock('@/store/useNotesStore', () => ({+ useNotesStore: require('zustand').create(() => ({ notes: [] })),+}));+jest.mock('@/store/useConfigStore', () => ({+ useConfigStore: require('zustand').create(() => ({ config: { cloudBackupEnabled: true } })),+}));+jest.mock('@/data', () => ({+ notesRepository: {+ getNoteById: jest.fn(),+ hasDirtyTranscript: jest.fn(),+ isRemoteNoteHeldByFolderDelete: jest.fn(),+ getSyncState: jest.fn(),+ isNotePushRejected: jest.fn(),+ },+ spacesRepository: { listSpaces: jest.fn(() => []) },+}));+jest.mock('expo-network', () => ({ getNetworkStateAsync: jest.fn() }));+const mockListeners = new Set<(hasQueuedRun: boolean) => void>();+jest.mock('../syncEngine', () => ({+ requestSync: jest.fn(),+ subscribeSyncCompletion: (callback: (hasQueuedRun: boolean) => void): (() => void) => {+ mockListeners.add(callback);+ return () => {+ mockListeners.delete(callback);+ };+ },+}));+import * as Network from 'expo-network';+import { notesRepository, spacesRepository } from '@/data';+import { useAuthStore } from '@/store/useAuthStore';+import { useNotesStore } from '@/store/useNotesStore';+import { useConfigStore } from '@/store/useConfigStore';+import { requestSync } from '../syncEngine';+import { useSyncStore } from '../useSyncStore';+import { ensureNoteSynced } from '../ensureNoteSynced';++let note: Note;+let controller: AbortController;+const complete = (hasQueuedRun = false): void => {+ for (const listener of mockListeners) listener(hasQueuedRun);+};+beforeEach((): void => {+ jest.useFakeTimers();+ jest.clearAllMocks();+ jest.mocked(notesRepository.getSyncState).mockReturnValue(null);+ jest.mocked(notesRepository.isNotePushRejected).mockReturnValue(false);+ jest+ .mocked(Network.getNetworkStateAsync)+ .mockResolvedValue({ isConnected: true } as Network.NetworkState);+ note = {+ id: 1,+ clientNoteId: 'client',+ remoteId: null,+ isPrivate: 0,+ pendingSync: 1,+ deletedAt: null,+ conflictServerNote: null,+ spaceId: null,+ } as Note;+ controller = new AbortController();+ jest.mocked(notesRepository.getNoteById).mockImplementation(() => note);+ jest.mocked(notesRepository.hasDirtyTranscript).mockReturnValue(false);+ jest.mocked(notesRepository.isRemoteNoteHeldByFolderDelete).mockReturnValue(false);+ jest.mocked(spacesRepository.listSpaces).mockReturnValue([]);+ useAuthStore.setState({+ user: { id: 'owner', isAnonymous: false } as NonNullable<+ ReturnType<typeof useAuthStore.getState>['user']+ >,+ sessionCookie: 'session',+ isGuest: false,+ isLoading: false,+ });+ useConfigStore.setState({+ config: { cloudBackupEnabled: true } as NonNullable<+ ReturnType<typeof useConfigStore.getState>['config']+ >,+ });+ useSyncStore+ .getState()+ .set({ status: 'idle', lastError: null, policyBlocked: false, subscriptionRequired: false });+});+afterEach((): void => {+ controller.abort();+ jest.useRealTimers();+});++it('waits for an acknowledged current revision, including edits during a pass', async (): Promise<void> => {+ const settled = jest.fn();+ const pending = ensureNoteSynced(1, { signal: controller.signal }).then(settled);+ expect(requestSync).toHaveBeenCalledWith('manual');+ note = { ...note, remoteId: 'remote', pendingSync: 1 };+ complete();+ await Promise.resolve();+ expect(settled).not.toHaveBeenCalled();+ note = { ...note, pendingSync: 0 };+ complete();+ await pending;+ expect(settled).toHaveBeenCalledWith('remote');+ expect(mockListeners.size).toBe(0);+});+it('does not resolve an existing remote ID with dirty transcript data', async (): Promise<void> => {+ note = { ...note, remoteId: 'remote', pendingSync: 0 };+ jest.mocked(notesRepository.hasDirtyTranscript).mockReturnValue(true);+ const settled = jest.fn();+ const pending = ensureNoteSynced(1, { signal: controller.signal }).then(settled);+ complete();+ await Promise.resolve();+ expect(settled).not.toHaveBeenCalled();+ jest.mocked(notesRepository.hasDirtyTranscript).mockReturnValue(false);+ complete();+ await pending;+ expect(settled).toHaveBeenCalledWith('remote');+});+it.each([+ ['private', { isPrivate: 1 }, /cloud sync/i],+ ['deleted', { deletedAt: 'now' }, /available/i],+ ['conflicted', { conflictServerNote: '{}' }, /conflict/i],+])('rejects a %s note before publishing', async (_label, patch, message): Promise<void> => {+ note = { ...note, ...patch };+ await expect(ensureNoteSynced(1, { signal: controller.signal })).rejects.toThrow(message);+ expect(requestSync).not.toHaveBeenCalled();+});+it('rejects a note held by a folder deletion', async (): Promise<void> => {+ jest.mocked(notesRepository.isRemoteNoteHeldByFolderDelete).mockReturnValue(true);+ await expect(ensureNoteSynced(1, { signal: controller.signal })).rejects.toThrow(/available/i);+});+it('rejects anonymous sessions', async (): Promise<void> => {+ useAuthStore.setState({+ user: { id: 'owner', isAnonymous: true } as NonNullable<+ ReturnType<typeof useAuthStore.getState>['user']+ >,+ });+ await expect(ensureNoteSynced(1, { signal: controller.signal })).rejects.toThrow(/account/i);+});+it('aborts if the session changes while sync is running', async (): Promise<void> => {+ const pending = ensureNoteSynced(1, { signal: controller.signal });+ useAuthStore.setState({ sessionCookie: 'replacement' });+ await expect(pending).rejects.toThrow(/changed/i);+ expect(mockListeners.size).toBe(0);+});+it('aborts if the note becomes private while waiting', async (): Promise<void> => {+ const pending = ensureNoteSynced(1, { signal: controller.signal });+ note = { ...note, isPrivate: 1 };+ useNotesStore.setState({ notes: [note] });+ await expect(pending).rejects.toThrow(/cloud sync/i);+});+it('does not adopt a republished note identity', async (): Promise<void> => {+ const pending = ensureNoteSynced(1, { signal: controller.signal });+ note = { ...note, clientNoteId: 'new-client', remoteId: 'new-remote', pendingSync: 0 };+ complete();+ await expect(pending).rejects.toThrow(/changed/i);+});+it('surfaces a subscription gate for personal notes', async (): Promise<void> => {+ const pending = ensureNoteSynced(1, { signal: controller.signal });+ useSyncStore.getState().set({ subscriptionRequired: true });+ complete();+ await expect(pending).rejects.toThrow(/subscription/i);+});+it('reports a failed sync, not a missing subscription, when the server is unreachable', async (): Promise<void> => {+ const pending = ensureNoteSynced(1, { signal: controller.signal });+ useSyncStore+ .getState()+ .set({ subscriptionRequired: true, lastError: new Error('Network request failed') });+ complete();+ await expect(pending).rejects.toThrow(/unable to sync/i);+});+it('explains an organization that blocks cloud backup', async (): Promise<void> => {+ const pending = ensureNoteSynced(1, { signal: controller.signal });+ useSyncStore.getState().set({ policyBlocked: true });+ complete();+ await expect(pending).rejects.toThrow(/organization/i);+});+it('does not apply the personal subscription gate to a synced team note', async (): Promise<void> => {+ note = { ...note, spaceId: 2 };+ jest+ .mocked(spacesRepository.listSpaces)+ .mockReturnValue([+ { id: 2, kind: 'team' } as ReturnType<typeof spacesRepository.listSpaces>[number],+ ]);+ const pending = ensureNoteSynced(1, { signal: controller.signal });+ useSyncStore.getState().set({ subscriptionRequired: true });+ note = { ...note, remoteId: 'team-note', pendingSync: 0 };+ complete();+ await expect(pending).resolves.toBe('team-note');+});+it('rejects promptly once a finished pass leaves the note unsynced while offline', async (): Promise<void> => {+ jest+ .mocked(Network.getNetworkStateAsync)+ .mockResolvedValue({ isConnected: false } as Network.NetworkState);+ const pending = ensureNoteSynced(1, { signal: controller.signal });+ // A failed subscription check is how an offline pass looks to the sync store.+ useSyncStore.getState().set({ subscriptionRequired: true });+ complete();+ await expect(pending).rejects.toThrow(/offline/i);+});+it('waits for the network answer before judging a finished pass', async (): Promise<void> => {+ jest+ .mocked(Network.getNetworkStateAsync)+ .mockResolvedValue({ isConnected: false } as Network.NetworkState);+ const pending = ensureNoteSynced(1, { signal: controller.signal });+ useSyncStore.getState().set({ subscriptionRequired: true });+ complete();+ // An unrelated store update lands before the OS answers.+ useNotesStore.setState({ notes: [] });+ await expect(pending).rejects.toThrow(/offline/i);+});+it('judges a pass as online when the network state is unavailable', async (): Promise<void> => {+ jest.mocked(Network.getNetworkStateAsync).mockRejectedValue(new Error('unavailable'));+ const pending = ensureNoteSynced(1, { signal: controller.signal });+ useSyncStore.getState().set({ subscriptionRequired: true });+ complete();+ await expect(pending).rejects.toThrow(/subscription/i);+});+it('points personal notes at the Cloud Backup setting when it is off', async (): Promise<void> => {+ useConfigStore.setState({+ config: { cloudBackupEnabled: false } as NonNullable<+ ReturnType<typeof useConfigStore.getState>['config']+ >,+ });+ await expect(ensureNoteSynced(1, { signal: controller.signal })).rejects.toThrow(+ /Privacy & Data/,+ );+});+it('rejects after a bounded wait and unsubscribes', async (): Promise<void> => {+ const pending = ensureNoteSynced(1, { signal: controller.signal, timeoutMs: 30 });+ jest.advanceTimersByTime(30);+ await expect(pending).rejects.toThrow(/sync.*try again/i);+ expect(mockListeners.size).toBe(0);+});+it('cancels without stopping background sync', async (): Promise<void> => {+ const pending = ensureNoteSynced(1, { signal: controller.signal });+ controller.abort();+ await expect(pending).rejects.toThrow(/cancel/i);+ expect(mockListeners.size).toBe(0);+});++it('rejects terminally dropped edits instead of sharing stale cloud content', async (): Promise<void> => {+ note = { ...note, remoteId: 'remote' };+ const pending = ensureNoteSynced(1, { signal: controller.signal });+ note = { ...note, pendingSync: 0 };+ jest.mocked(notesRepository.isNotePushRejected).mockReturnValue(true);+ complete();+ await expect(pending).rejects.toThrow(/rejected/i);+});+it('rejects a never-synced note whose upload was terminally rejected', async (): Promise<void> => {+ const pending = ensureNoteSynced(1, { signal: controller.signal });+ note = { ...note, pendingSync: 0 };+ jest.mocked(notesRepository.isNotePushRejected).mockReturnValue(true);+ complete();+ await expect(pending).rejects.toThrow(/rejected/i);+});+it('rejects a rejected push whose transcript rows stay dirty after a retry', async (): Promise<void> => {+ note = { ...note, remoteId: 'remote', pendingSync: 0 };+ jest.mocked(notesRepository.hasDirtyTranscript).mockReturnValue(true);+ jest.mocked(notesRepository.isNotePushRejected).mockReturnValue(true);+ const settled = jest.fn();+ const pending = ensureNoteSynced(1, { signal: controller.signal });+ pending.catch(settled);+ await Promise.resolve();+ expect(settled).not.toHaveBeenCalled();+ complete();+ await expect(pending).rejects.toThrow(/rejected/i);+});+it('shares a transcript edit that a retry accepts after an earlier rejection', async (): Promise<void> => {+ note = { ...note, remoteId: 'remote', pendingSync: 0 };+ jest.mocked(notesRepository.hasDirtyTranscript).mockReturnValue(true);+ jest.mocked(notesRepository.isNotePushRejected).mockReturnValue(true);+ const pending = ensureNoteSynced(1, { signal: controller.signal });+ jest.mocked(notesRepository.hasDirtyTranscript).mockReturnValue(false);+ jest.mocked(notesRepository.isNotePushRejected).mockReturnValue(false);+ complete();+ await expect(pending).resolves.toBe('remote');+});+it('stops waiting when a different account signs in with the same session', async (): Promise<void> => {+ const pending = ensureNoteSynced(1, { signal: controller.signal });+ useAuthStore.setState({+ user: { id: 'other', isAnonymous: false } as NonNullable<+ ReturnType<typeof useAuthStore.getState>['user']+ >,+ });+ await expect(pending).rejects.toThrow(/account changed/i);+});+it('explains a note held back because its space cannot sync', async (): Promise<void> => {+ note = { ...note, spaceId: 5 };+ jest+ .mocked(notesRepository.getSyncState)+ .mockImplementation((key) => (key === 'team_spaces_capability' ? 'true' : null));+ const pending = ensureNoteSynced(1, { signal: controller.signal });+ complete();+ await expect(pending).rejects.toThrow(/space/i);+});+it('waits for the queued manual pass before using an earlier pass’s gate', async (): Promise<void> => {+ const pending = ensureNoteSynced(1, { signal: controller.signal });+ useSyncStore.getState().set({ subscriptionRequired: true });+ complete(true);+ useSyncStore.getState().set({ subscriptionRequired: false });+ note = { ...note, remoteId: 'remote', pendingSync: 0 };+ complete();+ await expect(pending).resolves.toBe('remote');+});++it('resolves an acknowledged note even if a queued pass never reports back', async (): Promise<void> => {+ // Acknowledgement is repository state, so it never waits on a later pass.+ const pending = ensureNoteSynced(1, { signal: controller.signal });+ note = { ...note, remoteId: 'remote', pendingSync: 0 };+ complete(true);+ await expect(pending).resolves.toBe('remote');+});+it('resolves an already acknowledged note without waiting for another pass', async (): Promise<void> => {+ note = { ...note, remoteId: 'remote', pendingSync: 0 };+ await expect(ensureNoteSynced(1, { signal: controller.signal })).resolves.toBe('remote');+ expect(requestSync).not.toHaveBeenCalled();+});diff --git a/openwhispr-mobile/src/sync/__tests__/syncEngine.test.ts b/openwhispr-mobile/src/sync/__tests__/syncEngine.test.tsindex ae0b1f3fb..5e0baa1eb 100644--- a/openwhispr-mobile/src/sync/__tests__/syncEngine.test.ts+++ b/openwhispr-mobile/src/sync/__tests__/syncEngine.test.ts@@ -125,7 +125,7 @@ jest.mock('../initialBackfill', () => ({runInitialBackfillIfNeeded: (...args: unknown[]) => mockRunInitialBackfillIfNeeded(...args),}));-import { requestSync } from '../syncEngine';+import { requestSync, subscribeSyncCompletion } from '../syncEngine';import { pushPrivateNoteDeletes } from '../privateNoteDeletion';import { useSyncStore } from '../useSyncStore';import { ApiError } from '@/lib/apiClient';@@ -737,6 +737,123 @@ describe('in-flight cancellation', () => {});});+it('notifies sync completion after a gated pass and supports unsubscription', async (): Promise<void> => {+ const finished = jest.fn();+ const unsubscribe = subscribeSyncCompletion(finished);+ mockConfigState.config = { cloudBackupEnabled: false };+ mockSyncSpaces.mockResolvedValue({ capable: false, activeSpaces: [] });+ requestSync('manual');+ await flush();+ expect(finished).toHaveBeenCalledTimes(1);+ unsubscribe();+ requestSync('manual');+ await flush();+ expect(finished).toHaveBeenCalledTimes(1);+});++describe('queued runs', () => {+ // Parks the next run on its notes pull; resolving the returned function lets it finish.+ function holdNextRun(): () => void {+ let release: () => void = () => {};+ mockPullNotes.mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ release = resolve;+ }),+ );+ return () => release();+ }++ // A foreground run that just completed throttles the next foreground trigger.+ async function throttleForeground(): Promise<void> {+ requestSync('foreground');+ await flush();+ jest.clearAllMocks();+ }++ it('keeps a queued manual run when a throttled foreground trigger arrives behind it', async (): Promise<void> => {+ await throttleForeground();+ const finished = jest.fn();+ const unsubscribe = subscribeSyncCompletion(finished);+ try {+ const release = holdNextRun();+ requestSync('manual');+ await flush();+ requestSync('manual');+ requestSync('foreground');+ release();+ await flush();+ } finally {+ unsubscribe();+ }++ // Both manual runs force a fresh subscription check.+ expect(mockFetchUsage).toHaveBeenCalledTimes(2);+ expect(mockPullNotes).toHaveBeenCalledTimes(2);+ expect(finished.mock.calls).toEqual([[true], [false]]);+ });++ it('does not report a queued foreground run the throttle will skip', async (): Promise<void> => {+ await throttleForeground();+ const finished = jest.fn();+ const unsubscribe = subscribeSyncCompletion(finished);+ try {+ const release = holdNextRun();+ requestSync('manual');+ await flush();+ requestSync('foreground');+ release();+ await flush();+ } finally {+ unsubscribe();+ }++ expect(mockPullNotes).toHaveBeenCalledTimes(1);+ expect(finished.mock.calls).toEqual([[false]]);+ });++ it('still notifies later listeners and replays the queued run when a listener throws', async (): Promise<void> => {+ const failure = new Error('listener failed');+ const later = jest.fn();+ const unsubscribeThrowing = subscribeSyncCompletion(() => {+ throw failure;+ });+ const unsubscribeLater = subscribeSyncCompletion(later);+ try {+ const release = holdNextRun();+ requestSync('manual');+ await flush();+ requestSync('manual');+ release();+ await flush();+ } finally {+ unsubscribeThrowing();+ unsubscribeLater();+ }++ expect(mockPullNotes).toHaveBeenCalledTimes(2);+ expect(later.mock.calls).toEqual([[true], [false]]);+ expect(Sentry.captureException).toHaveBeenCalledWith(failure, {+ tags: { sync: 'completionListener' },+ });+ });++ it('settles a queued foreground request the throttle drops', async (): Promise<void> => {+ await throttleForeground();+ const release = holdNextRun();+ requestSync('manual');+ await flush();+ let settled = false;+ const queued = requestSync('foreground').then(() => {+ settled = true;+ });+ release();+ await queued;+ expect(settled).toBe(true);+ expect(mockPullNotes).toHaveBeenCalledTimes(1);+ });+});+// Pull-to-refresh holds its spinner on this promise, so it has to settle once the// run the request caused is over — including a run that was queued behind another,// one that failed, and a request that never started a run at all.diff --git a/openwhispr-mobile/src/sync/__tests__/syncSecurity.test.ts b/openwhispr-mobile/src/sync/__tests__/syncSecurity.test.tsindex 5b82846d5..3cc4e7cb1 100644--- a/openwhispr-mobile/src/sync/__tests__/syncSecurity.test.ts+++ b/openwhispr-mobile/src/sync/__tests__/syncSecurity.test.ts@@ -294,3 +294,45 @@ it('does not process an old account rejection against new local work', async ()).rejects.toThrow(SyncCancelledError);expect(mockRepo.getNoteById(created.id)!.pendingSync).toBe(1);});++it('uses the pulled sharing revision as the next content update base', async (): Promise<void> => {+ const note = mockRepo.createNote('Title', 'Body');+ const originalRevision = '2026-09-22T10:00:00.000Z';+ const sharingRevision = '2026-09-22T10:00:01.000Z';+ mockRepo.markNotePushed(note, 'remote-note', originalRevision);+ const remote = {+ id: 'remote-note',+ client_note_id: note.clientNoteId,+ title: 'Title',+ content: 'Body',+ enhanced_content: null,+ enhancement_prompt: null,+ note_type: 'personal',+ source_file: null,+ audio_duration_seconds: null,+ folder_id: null,+ participants: null,+ calendar_event_id: null,+ transcript: null,+ deleted_at: null,+ updated_at: sharingRevision,+ };+ jest.mocked(fetchNotes).mockResolvedValueOnce({ notes: [remote], hasMore: false });+ await pullNotes();+ expect(mockRepo.getNoteById(note.id)?.cloudUpdatedAt).toBe(sharingRevision);+ mockRepo.updateNote(note.id, { content: 'Edited after sharing' });+ jest.mocked(updateNote).mockResolvedValueOnce({+ ...remote,+ content: 'Edited after sharing',+ updated_at: '2026-09-22T10:00:02.000Z',+ });+ await pushNotes();+ expect(updateNote).toHaveBeenCalledWith(+ 'remote-note',+ expect.objectContaining({+ content: 'Edited after sharing',+ base_updated_at: sharingRevision,+ }),+ );+ expect(mockRepo.getNoteById(note.id)?.pendingSync).toBe(0);+});diff --git a/openwhispr-mobile/src/sync/ensureNoteSynced.ts b/openwhispr-mobile/src/sync/ensureNoteSynced.tsnew file mode 100644index 000000000..db828e53d--- /dev/null+++ b/openwhispr-mobile/src/sync/ensureNoteSynced.ts@@ -0,0 +1,150 @@+import * as Network from 'expo-network';+import { notesRepository, type Note } from '@/data';+import { useAuthStore } from '@/store/useAuthStore';+import { useConfigStore } from '@/store/useConfigStore';+import { useNotesStore } from '@/store/useNotesStore';+import { createPushScopeResolver, createTeamSpaceFilter } from './pushScope';+import { requestSync, subscribeSyncCompletion } from './syncEngine';+import { useSyncStore } from './useSyncStore';++export const NOTE_UNAVAILABLE_ERROR = 'This note is no longer available.';+export const NOTE_PRIVATE_ERROR = 'Enable cloud sync for this note before sharing.';++function readPublishableNote(noteId: number): Note {+ const note = notesRepository.getNoteById(noteId);+ if (+ !note ||+ note.deletedAt ||+ notesRepository.isRemoteNoteHeldByFolderDelete({+ id: note.remoteId ?? '',+ client_note_id: note.clientNoteId,+ })+ )+ throw new Error(NOTE_UNAVAILABLE_ERROR);+ if (note.isPrivate === 1) throw new Error(NOTE_PRIVATE_ERROR);+ if (note.conflictServerNote) throw new Error('Resolve this note’s sync conflict before sharing.');+ return note;+}++/** Wait for the existing sync pipeline to acknowledge this note's latest edits. */+export async function ensureNoteSynced(+ noteId: number,+ { signal, timeoutMs = 30_000 }: { signal: AbortSignal; timeoutMs?: number },+): Promise<string> {+ const auth = useAuthStore.getState();+ if (!auth.user || auth.user.isAnonymous || auth.isGuest || auth.isLoading) {+ throw new Error('Sign in to an account before sharing.');+ }+ if (signal.aborted) throw new Error('Sharing cancelled.');+ const original = readPublishableNote(noteId);+ const isTeamNote = createTeamSpaceFilter()(original.spaceId);++ return new Promise<string>((resolve, reject) => {+ let settled = false;+ let completedPass = false;+ let passes = 0;+ let offline = false;+ const unsubscribe: Array<() => void> = [];+ const finish = (value: string | Error): void => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ signal.removeEventListener('abort', cancel);+ unsubscribe.forEach((stop) => stop());+ if (value instanceof Error) reject(value);+ else resolve(value);+ };+ const cancel = (): void => finish(new Error('Sharing cancelled.'));+ const timer = setTimeout(+ () =>+ finish(+ new Error('The note has not finished syncing. Check your connection and try again.'),+ ),+ timeoutMs,+ );+ const inspect = (): void => {+ try {+ const current = useAuthStore.getState();+ if (+ current.user?.id !== auth.user?.id ||+ current.sessionCookie !== auth.sessionCookie ||+ current.isLoading ||+ current.isGuest+ )+ throw new Error('Your account changed. Open sharing again.');+ const note = readPublishableNote(noteId);+ if (+ note.clientNoteId !== original.clientNoteId ||+ (original.remoteId && note.remoteId !== original.remoteId)+ )+ throw new Error('This note’s cloud identity changed. Open sharing again.');+ if (!isTeamNote && useConfigStore.getState().config?.cloudBackupEnabled === false) {+ throw new Error('Turn on Cloud Backup in Account → Privacy & Data before sharing.');+ }+ // Acknowledgement is repository state: a push clears pendingSync only when the server+ // accepted this exact snapshot, terminal rejections leave a flag, and conflicts or privacy+ // changes are rejected above. It needs no completed pass to observe.+ if (!note.pendingSync) {+ const dirtyTranscript = notesRepository.hasDirtyTranscript(noteId);+ // A rejected create settles with no remote ID, so check before requiring one. A rejection+ // also leaves transcript rows dirty; with those, judge it once a pass has retried them.+ if (notesRepository.isNotePushRejected(noteId) && (!dirtyTranscript || completedPass)) {+ throw new Error(+ 'The latest changes were rejected by sync. Edit the note and retry before sharing.',+ );+ }+ if (note.remoteId && !dirtyTranscript) {+ finish(note.remoteId);+ return;+ }+ }+ // Sync status only reflects this request once a pass has finished with nothing queued.+ if (!completedPass) return;+ if (offline) throw new Error('You’re offline. Connect to the internet to share this note.');+ const sync = useSyncStore.getState();+ if (sync.policyBlocked) throw new Error('Your organization does not allow cloud backup.');+ // The subscription check fails closed, so an unreachable server also reads as unsubscribed.+ if (sync.lastError)+ throw new Error('Unable to sync this note. Check your connection and try again.');+ if (!isTeamNote && sync.subscriptionRequired) {+ throw new Error('An active subscription is required to sync this note.');+ }+ // The same test pushNotes uses to leave a row queued until its space resolves.+ if (!createPushScopeResolver()(note.spaceId)) {+ throw new Error('This note’s space is not available to sync yet. Try again later.');+ }+ } catch (error) {+ finish(error instanceof Error ? error : new Error('Unable to sync this note.'));+ }+ };+ signal.addEventListener('abort', cancel, { once: true });+ unsubscribe.push(+ useAuthStore.subscribe(inspect),+ useNotesStore.subscribe(inspect),+ useConfigStore.subscribe(inspect),+ subscribeSyncCompletion((hasQueuedRun): void => {+ const pass = ++passes;+ completedPass = false;+ if (hasQueuedRun) {+ inspect();+ return;+ }+ // Offline passes end quietly or read as a missing subscription, so the pass only counts+ // once the OS has answered; a newer pass supersedes a slower answer.+ Network.getNetworkStateAsync()+ .then(+ (network) => network.isConnected === false,+ () => false,+ )+ .then((isOffline) => {+ if (pass !== passes) return;+ offline = isOffline;+ completedPass = true;+ inspect();+ });+ }),+ );+ inspect();+ if (!settled) requestSync('manual');+ });+}diff --git a/openwhispr-mobile/src/sync/syncEngine.ts b/openwhispr-mobile/src/sync/syncEngine.tsindex 28bc58739..a30cb1d9b 100644--- a/openwhispr-mobile/src/sync/syncEngine.ts+++ b/openwhispr-mobile/src/sync/syncEngine.ts@@ -35,11 +35,29 @@ import { ApiError, isPolicyCloudBackupBlockedError } from '@/lib/apiClient';export type SyncReason = 'after-write' | 'foreground' | 'sign-in' | 'manual';+// Triggers that arrive mid-run coalesce into one queued run, which keeps the+// strongest reason asked for: a foreground run can be throttled away, and only+// manual and sign-in runs force a fresh subscription check.+const QUEUE_PRIORITY: Record<SyncReason, number> = {+ foreground: 0,+ 'after-write': 1,+ manual: 2,+ 'sign-in': 2,+};+let inFlight = false;let pendingTrigger: SyncReason | null = null;// Callers waiting on the queued run (see requestSync); settled once it ends.let pendingTriggerWaiters: Array<() => void> = [];let postWriteTimer: ReturnType<typeof setTimeout> | null = null;+const syncCompletionListeners = new Set<(hasQueuedRun: boolean) => void>();++export function subscribeSyncCompletion(listener: (hasQueuedRun: boolean) => void): () => void {+ syncCompletionListeners.add(listener);+ return (): void => {+ syncCompletionListeners.delete(listener);+ };+}// The snippets endpoints (/api/snippets/*) may not be deployed yet on the// backend. A missing route returns 404/405; treat that as "endpoint unavailable"@@ -96,6 +114,10 @@ const FOREGROUND_THROTTLE_MS = 30_000;let lastForegroundSyncAt = 0;+function isForegroundThrottled(): boolean {+ return Date.now() - lastForegroundSyncAt < FOREGROUND_THROTTLE_MS;+}+let subscriptionCachedAt = 0;let subscriptionCached = false;@@ -204,7 +226,9 @@ async function runSyncNow(reason: SyncReason): Promise<void> {const auth = useAuthStore.getState();if (!auth.user || auth.isGuest) return;if (inFlight) {- pendingTrigger = reason;+ if (!pendingTrigger || QUEUE_PRIORITY[reason] > QUEUE_PRIORITY[pendingTrigger]) {+ pendingTrigger = reason;+ }return new Promise((resolve) => pendingTriggerWaiters.push(resolve));}@@ -213,9 +237,7 @@ async function runSyncNow(reason: SyncReason): Promise<void> {// Foreground triggers fire on every AppState→active transition, which can// be noisy (window focus, sim re-focus). Skip if we synced very recently.// Applies to every run below, personal or team-only.- if (reason === 'foreground' && Date.now() - lastForegroundSyncAt < FOREGROUND_THROTTLE_MS) {- return;- }+ if (reason === 'foreground' && isForegroundThrottled()) return;// Claimed before the paygate's network round trip, not after it. A run that// parks on that request while the user signs up would otherwise overlap the@@ -460,15 +482,27 @@ async function runSyncNow(reason: SyncReason): Promise<void> {} finally {dispose();inFlight = false;+ // Replaying it would return before reaching this block, so listeners told+ // a run was queued would never hear back.+ if (pendingTrigger === 'foreground' && isForegroundThrottled()) pendingTrigger = null;+ const hasQueuedRun = pendingTrigger !== null;+ syncCompletionListeners.forEach((listener) => {+ try {+ listener(hasQueuedRun);+ } catch (err) {+ Sentry.captureException(err, { tags: { sync: 'completionListener' } });+ }+ });+ const waiters = pendingTriggerWaiters;+ pendingTriggerWaiters = [];+ const settleWaiters = (): void => waiters.forEach((resolve) => resolve());if (pendingTrigger) {const next = pendingTrigger;- const waiters = pendingTriggerWaiters;pendingTrigger = null;- pendingTriggerWaiters = [];runSyncNow(next).catch(() => {})- .finally(() => waiters.forEach((resolve) => resolve()));- }+ .finally(settleWaiters);+ } else settleWaiters();}}