Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

feat(mobile): Rework the note screen with editable notes and a transcript sheet (#2370)

Chad Piha86e40760a6e2
diff --git a/openwhispr-mobile/src/components/notes/AttendeesSheet.tsx b/openwhispr-mobile/src/components/notes/AttendeesSheet.tsx
new file mode 100644
index 000000000..b6ec3cb70
--- /dev/null
+++ b/openwhispr-mobile/src/components/notes/AttendeesSheet.tsx
@@ -0,0 +1,75 @@
+import type React from 'react';
+import { Modal, ScrollView, View } from 'react-native';
+import { useSafeAreaInsets } from 'react-native-safe-area-context';
+import { Text } from '@/components/ui/Text';
+import { SystemIcon } from '@/components/ui/SystemIcon';
+import { GlassIconButton } from '@/components/ui/GlassIconButton';
+import type { CalendarParticipant } from '@/data/calendarTypes';
+import { attendeeName, sortAttendees } from '@/lib/notes/noteMeta';
+import { GroupedList } from './GroupedList';
+
+interface AttendeesSheetProps {
+ visible: boolean;
+ participants: CalendarParticipant[];
+ onClose: () => void;
+}
+
+export function AttendeesSheet({
+ visible,
+ participants,
+ onClose,
+}: AttendeesSheetProps): React.JSX.Element {
+ const insets = useSafeAreaInsets();
+ const people = sortAttendees(participants);
+
+ return (
+ <Modal
+ visible={visible}
+ animationType="slide"
+ presentationStyle="pageSheet"
+ onRequestClose={onClose}
+ >
+ <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">
+ Attendees
+ </Text>
+ <GlassIconButton onPress={onClose} accessibilityLabel="Close">
+ <SystemIcon name="xmark" mdName="X" size={15} color="secondaryLabel" />
+ </GlassIconButton>
+ </View>
+ <ScrollView
+ contentContainerClassName="px-6"
+ contentContainerStyle={{ paddingBottom: insets.bottom + 24 }}
+ >
+ <GroupedList>
+ {people.map((participant, index) => {
+ const name = attendeeName(participant);
+ const showEmail = !!participant.email && participant.email !== name;
+ return (
+ <GroupedList.Row
+ key={participant.email ?? `${name}-${index}`}
+ contentInsetLeft={16}
+ >
+ <View testID={`attendee-row-${index}`} className="flex-1 py-1">
+ <View className="flex-row items-center gap-2">
+ <Text className="text-[17px] text-label">{name}</Text>
+ {participant.organizer ? (
+ <Text className="text-[12px] font-medium text-secondaryLabel">
+ Organizer
+ </Text>
+ ) : null}
+ </View>
+ {showEmail ? (
+ <Text className="text-[13px] text-secondaryLabel">{participant.email}</Text>
+ ) : null}
+ </View>
+ </GroupedList.Row>
+ );
+ })}
+ </GroupedList>
+ </ScrollView>
+ </View>
+ </Modal>
+ );
+}
diff --git a/openwhispr-mobile/src/components/notes/CalendarEventPicker.tsx b/openwhispr-mobile/src/components/notes/CalendarEventPicker.tsx
index 9261195a2..74b597481 100644
--- a/openwhispr-mobile/src/components/notes/CalendarEventPicker.tsx
+++ b/openwhispr-mobile/src/components/notes/CalendarEventPicker.tsx
@@ -5,6 +5,7 @@ import { SystemIcon } from '@/components/ui/SystemIcon';
import type { GoogleCalendarAccount, GoogleCalendarEvent } from '@/data/calendarTypes';
import { buildCalendarMeetingContext } from '@/lib/calendar/meetingContext';
import { DEFAULT_MEETING_TITLE } from '@/lib/notes/meetingConstants';
+import { isSameDay } from '@/lib/notes/noteMeta';
import { cn } from '@/lib/utils';
type CalendarEventPickerProps = {
@@ -19,11 +20,6 @@ const parseEventDate = (value: string): Date | null => {
return Number.isNaN(date.getTime()) ? null : date;
};
-const isSameDay = (left: Date, right: Date): boolean =>
- left.getFullYear() === right.getFullYear() &&
- left.getMonth() === right.getMonth() &&
- left.getDate() === right.getDate();
-
const formatEventTime = (event: GoogleCalendarEvent, now = new Date()): string => {
if (event.allDay === 1) return 'All day';
const start = parseEventDate(event.startAt);
diff --git a/openwhispr-mobile/src/components/notes/CloudMeetingRecording.tsx b/openwhispr-mobile/src/components/notes/CloudMeetingRecording.tsx
index d831d73ed..d0590f69b 100644
--- a/openwhispr-mobile/src/components/notes/CloudMeetingRecording.tsx
+++ b/openwhispr-mobile/src/components/notes/CloudMeetingRecording.tsx
@@ -1,11 +1,12 @@
import { useState } from 'react';
import type React from 'react';
-import { KeyboardAvoidingView, Platform, TextInput, View } from 'react-native';
+import { TextInput, View } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useHeaderHeight } from '@react-navigation/elements';
import { Text } from '@/components/ui/Text';
import { Button } from '@/components/ui/Button';
import { iosColor } from '@/config/colors';
+import { useKeyboardHeight } from '@/hooks/useKeyboardHeight';
import { MeetingTabs, type MeetingTab } from './MeetingTabs';
import { LiveTranscriptList } from './LiveTranscriptList';
import type { RealtimeUtterance } from '@/services/transcription/realtimeEvents';
@@ -54,15 +55,13 @@ export function CloudMeetingRecording({
// behind it from y=0 — offset below it or the status bar overlaps the timer card.
const headerHeight = useHeaderHeight();
const [tab, setTab] = useState<MeetingTab>('transcript');
- const footerBottomPadding = Math.max(insets.bottom + 16, 24);
+ const keyboardHeight = useKeyboardHeight();
+ // The view fills the screen, so the keyboard covers the home-indicator inset too.
+ const footerBottomPadding =
+ keyboardHeight > 0 ? keyboardHeight + 12 : Math.max(insets.bottom + 16, 24);
return (
- <KeyboardAvoidingView
- className="flex-1 bg-systemBackground"
- style={{ paddingTop: headerHeight }}
- behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
- keyboardVerticalOffset={headerHeight}
- >
+ <View className="flex-1 bg-systemBackground" style={{ paddingTop: headerHeight }}>
<View
className="mx-4 mt-1 flex-row items-center gap-3 rounded-[22px] border border-separator bg-secondarySystemGroupedBackground p-4 shadow-sm"
style={{ borderCurve: 'continuous' }}
@@ -111,7 +110,7 @@ export function CloudMeetingRecording({
placeholderTextColor={iosColor('tertiaryLabel')}
multiline
textAlignVertical="top"
- className="min-h-[120px] flex-1 text-[16px] leading-6 text-label"
+ className="flex-1 text-[16px] leading-6 text-label"
/>
</View>
) : (
@@ -124,6 +123,6 @@ export function CloudMeetingRecording({
Stop
</Button>
</View>
- </KeyboardAvoidingView>
+ </View>
);
}
diff --git a/openwhispr-mobile/src/components/notes/EditableMarkdown.tsx b/openwhispr-mobile/src/components/notes/EditableMarkdown.tsx
new file mode 100644
index 000000000..434261f42
--- /dev/null
+++ b/openwhispr-mobile/src/components/notes/EditableMarkdown.tsx
@@ -0,0 +1,117 @@
+import { useEffect, useRef, useState } from 'react';
+import type React from 'react';
+import { Pressable, TextInput, View } from 'react-native';
+import { Text } from '@/components/ui/Text';
+import { AppFont } from '@/lib/fonts';
+import { MarkdownRenderer } from './MarkdownRenderer';
+
+interface EditableMarkdownProps {
+ content: string;
+ editable?: boolean;
+ onChange: (text: string) => void;
+ onEditingChange?: (editing: boolean) => void;
+}
+
+/** Rendered Markdown that swaps to its raw source for editing. The caller owns saving. */
+export function EditableMarkdown({
+ content,
+ editable = true,
+ onChange,
+ onEditingChange,
+}: EditableMarkdownProps): React.JSX.Element {
+ const [editing, setEditing] = useState(false);
+ const [draft, setDraft] = useState(content);
+ const editingRef = useRef(editing);
+ editingRef.current = editing;
+ // Whether the open edit has changed the draft. Until it has, the draft follows the saved notes.
+ const draftEditedRef = useRef(false);
+ const onEditingChangeRef = useRef(onEditingChange);
+ onEditingChangeRef.current = onEditingChange;
+
+ const setEditingState = (next: boolean): void => {
+ if (next) draftEditedRef.current = false;
+ setEditing(next);
+ onEditingChangeRef.current?.(next);
+ };
+
+ // New saved notes (regenerated or synced) replace the draft unless the user has typed into it.
+ // Only a change to `content` does this: leaving editing keeps the draft until the caller's save
+ // comes back.
+ useEffect(() => {
+ if (!editingRef.current || !draftEditedRef.current) setDraft(content);
+ }, [content]);
+
+ // An AI action taking over the notes ends the edit.
+ useEffect(() => {
+ if (!editable && editingRef.current) setEditingState(false);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [editable]);
+
+ // Leaving the tab unmounts the editor mid-edit; report it so the caller flushes the save.
+ useEffect(
+ () => () => {
+ if (editingRef.current) onEditingChangeRef.current?.(false);
+ },
+ [],
+ );
+
+ if (editing) {
+ return (
+ <View>
+ <View className="mb-2 flex-row justify-end">
+ <Pressable
+ testID="enhanced-done"
+ accessibilityRole="button"
+ hitSlop={12}
+ onPress={() => setEditingState(false)}
+ >
+ <Text className="text-[15px] font-semibold text-link">Done</Text>
+ </Pressable>
+ </View>
+ <TextInput
+ testID="enhanced-editor"
+ accessibilityLabel="Enhanced notes"
+ value={draft}
+ onChangeText={(text) => {
+ draftEditedRef.current = true;
+ setDraft(text);
+ onChange(text);
+ }}
+ multiline
+ autoFocus
+ textAlignVertical="top"
+ className="min-h-[300px] text-base leading-6 text-label"
+ style={{ fontFamily: AppFont.regular }}
+ />
+ </View>
+ );
+ }
+
+ return (
+ <View>
+ {editable ? (
+ <View className="mb-2 flex-row justify-end">
+ <Pressable
+ testID="enhanced-edit"
+ accessibilityRole="button"
+ hitSlop={12}
+ onPress={() => setEditingState(true)}
+ >
+ <Text className="text-[15px] font-semibold text-link">Edit</Text>
+ </Pressable>
+ </View>
+ ) : null}
+ <Pressable
+ testID="enhanced-read"
+ disabled={!editable}
+ // Screen readers move through the rendered headings and paragraphs; Edit enters editing.
+ accessible={false}
+ onPress={() => setEditingState(true)}
+ // A long press selects text; without this handler Pressable would treat it as a tap.
+ onLongPress={() => {}}
+ >
+ <MarkdownRenderer content={draft} selectable />
+ </Pressable>
+ </View>
+ );
+}
diff --git a/openwhispr-mobile/src/components/notes/MoveToFolderSheet.tsx b/openwhispr-mobile/src/components/notes/MoveToFolderSheet.tsx
index 69a848a1c..074f2ca39 100644
--- a/openwhispr-mobile/src/components/notes/MoveToFolderSheet.tsx
+++ b/openwhispr-mobile/src/components/notes/MoveToFolderSheet.tsx
@@ -9,7 +9,7 @@ import { GlassIconButton } from '@/components/ui/GlassIconButton';
import { safeHaptics } from '@/lib/utils';
import type { Folder, Space } from '@/data';
-type MoveToFolderSheetProps = {
+export type MoveToFolderSheetProps = {
visible: boolean;
/** The folders offered as targets, always from the same space as the note being moved: the
* private space's folders for personal content, the browsed space's folders for space content.
diff --git a/openwhispr-mobile/src/components/notes/NoteActionsMenu.tsx b/openwhispr-mobile/src/components/notes/NoteActionsMenu.tsx
index 6c76fe200..eff2b43cb 100644
--- a/openwhispr-mobile/src/components/notes/NoteActionsMenu.tsx
+++ b/openwhispr-mobile/src/components/notes/NoteActionsMenu.tsx
@@ -19,7 +19,7 @@ interface NoteActionsMenuProps {
onAskNote?: () => void;
askNoteDisabled?: boolean;
onCopyGeneratedNote?: () => void;
- onCopyTranscript?: () => void;
+ onViewTranscript?: () => void;
onShare: () => void;
onDelete: () => void;
}
@@ -27,7 +27,7 @@ interface NoteActionsMenuProps {
const MANAGE_ID = '__manage';
const ASK_NOTE_ID = '__ask_note';
const COPY_GENERATED_NOTE_ID = '__copy_generated_note';
-const COPY_TRANSCRIPT_ID = '__copy_transcript';
+const VIEW_TRANSCRIPT_ID = '__view_transcript';
const SHARE_ID = '__share';
const PRIVACY_ID = '__privacy';
const DELETE_ID = '__delete';
@@ -43,7 +43,7 @@ export function NoteActionsMenu({
onAskNote,
askNoteDisabled = false,
onCopyGeneratedNote,
- onCopyTranscript,
+ onViewTranscript,
onShare,
onDelete,
}: NoteActionsMenuProps) {
@@ -76,7 +76,8 @@ export function NoteActionsMenu({
title: 'Ask about this note',
image: 'message',
imageColor: iconColor,
- attributes: { disabled: !hasContent || askNoteDisabled },
+ // Chat also reads the generated notes, so the caller decides when there is context.
+ attributes: { disabled: askNoteDisabled },
},
]
: []),
@@ -90,14 +91,13 @@ export function NoteActionsMenu({
},
]
: []),
- ...(onCopyTranscript
+ ...(onViewTranscript
? [
{
- id: COPY_TRANSCRIPT_ID,
- title: 'Copy Transcript',
- image: 'doc.on.doc',
+ id: VIEW_TRANSCRIPT_ID,
+ title: 'View Transcript',
+ image: 'text.quote',
imageColor: iconColor,
- attributes: { disabled: !hasContent },
},
]
: []),
@@ -140,8 +140,8 @@ export function NoteActionsMenu({
onCopyGeneratedNote?.();
return;
}
- if (id === COPY_TRANSCRIPT_ID) {
- onCopyTranscript?.();
+ if (id === VIEW_TRANSCRIPT_ID) {
+ onViewTranscript?.();
return;
}
if (id === SHARE_ID) {
diff --git a/openwhispr-mobile/src/components/notes/NoteMetaRow.tsx b/openwhispr-mobile/src/components/notes/NoteMetaRow.tsx
new file mode 100644
index 000000000..55958571c
--- /dev/null
+++ b/openwhispr-mobile/src/components/notes/NoteMetaRow.tsx
@@ -0,0 +1,77 @@
+import type React from 'react';
+import { Pressable, View } from 'react-native';
+import { Text } from '@/components/ui/Text';
+import { SystemIcon } from '@/components/ui/SystemIcon';
+
+interface NoteMetaRowProps {
+ dateLabel: string;
+ attendeeLabel: string | null;
+ folderLabel: string | null;
+ onPressAttendees: () => void;
+ /** Omitted when the note can't be moved; the folder chip is then hidden. */
+ onPressFolder?: () => void;
+}
+
+const CHIP = 'h-9 max-w-full flex-row items-center gap-1.5 rounded-full bg-tertiarySystemFill px-3';
+
+/** The row under a note's title: when it was taken, who attended, and where it lives. */
+export function NoteMetaRow({
+ dateLabel,
+ attendeeLabel,
+ folderLabel,
+ onPressAttendees,
+ onPressFolder,
+}: NoteMetaRowProps): React.JSX.Element {
+ return (
+ <View className="mb-4 flex-row flex-wrap items-center gap-2">
+ {dateLabel || attendeeLabel ? (
+ <View className={CHIP} style={{ borderCurve: 'continuous' }}>
+ {dateLabel ? (
+ <Text className="text-[14px] font-medium text-secondaryLabel">{dateLabel}</Text>
+ ) : null}
+ {attendeeLabel ? (
+ <Pressable
+ testID="note-meta-attendees"
+ accessibilityRole="button"
+ accessibilityLabel={`Attendees: ${attendeeLabel}`}
+ hitSlop={6}
+ onPress={onPressAttendees}
+ className="shrink flex-row items-center gap-1.5"
+ >
+ {dateLabel ? <Text className="text-[14px] text-tertiaryLabel">·</Text> : null}
+ <SystemIcon name="person.2" mdName="Users" size={14} color="secondaryLabel" />
+ <Text
+ numberOfLines={1}
+ // A long name gives way in the middle, so the "+3" count stays visible.
+ ellipsizeMode="middle"
+ className="shrink text-[14px] font-medium text-secondaryLabel"
+ >
+ {attendeeLabel}
+ </Text>
+ </Pressable>
+ ) : null}
+ </View>
+ ) : null}
+ {onPressFolder ? (
+ <Pressable
+ testID="note-meta-folder"
+ accessibilityRole="button"
+ accessibilityLabel={folderLabel ? `Folder: ${folderLabel}. Move note` : 'Add to folder'}
+ onPress={onPressFolder}
+ className={CHIP}
+ style={{ borderCurve: 'continuous' }}
+ >
+ <SystemIcon
+ name={folderLabel ? 'folder' : 'folder.badge.plus'}
+ mdName={folderLabel ? 'Folder' : 'FolderPlus'}
+ size={14}
+ color="secondaryLabel"
+ />
+ <Text numberOfLines={1} className="shrink text-[14px] font-medium text-secondaryLabel">
+ {folderLabel ?? 'Add to folder'}
+ </Text>
+ </Pressable>
+ ) : null}
+ </View>
+ );
+}
diff --git a/openwhispr-mobile/src/components/notes/TranscriptSheet.tsx b/openwhispr-mobile/src/components/notes/TranscriptSheet.tsx
new file mode 100644
index 000000000..1acd631a1
--- /dev/null
+++ b/openwhispr-mobile/src/components/notes/TranscriptSheet.tsx
@@ -0,0 +1,112 @@
+import type React from 'react';
+import { Alert, Modal, Pressable, ScrollView, Share, View } from 'react-native';
+import { MenuView } from '@react-native-menu/menu';
+import { useSafeAreaInsets } from 'react-native-safe-area-context';
+import { Text } from '@/components/ui/Text';
+import { SystemIcon } from '@/components/ui/SystemIcon';
+import { GlassCapsule, GlassIconButton } from '@/components/ui/GlassIconButton';
+import { displayFontFamily } from '@/lib/fonts';
+import type { TranscriptBlock } from '@/lib/diarization/transcriptDisplay';
+import { SpeakerTranscript } from './SpeakerTranscript';
+
+interface TranscriptSheetProps {
+ visible: boolean;
+ blocks: TranscriptBlock[];
+ selectedSpeakerId: number | null;
+ shareText: string;
+ onSpeakerPress: (block: TranscriptBlock) => void;
+ onExport: (format: 'md' | 'txt') => void;
+ onClose: () => void;
+ /** Sheets opened from a speaker (rename, merge, voiceprint). iOS only presents a modal above
+ * this one when it is rendered inside it. */
+ children?: React.ReactNode;
+}
+
+export function TranscriptSheet({
+ visible,
+ blocks,
+ selectedSpeakerId,
+ shareText,
+ onSpeakerPress,
+ onExport,
+ onClose,
+ children,
+}: TranscriptSheetProps): React.JSX.Element {
+ const insets = useSafeAreaInsets();
+
+ const handleShare = async (): Promise<void> => {
+ try {
+ await Share.share({ message: shareText });
+ } catch {
+ Alert.alert('Error', 'Unable to share transcript');
+ }
+ };
+
+ return (
+ <Modal
+ visible={visible}
+ animationType="slide"
+ presentationStyle="pageSheet"
+ onRequestClose={onClose}
+ >
+ <View className="flex-1 bg-systemBackground">
+ <View className="flex-row items-start justify-between gap-4 px-6 pb-4 pt-8">
+ <View className="flex-1">
+ <Text
+ accessibilityRole="header"
+ className="text-[28px] text-label"
+ style={{ fontFamily: displayFontFamily }}
+ >
+ Transcript
+ </Text>
+ <Text className="mt-1 text-[15px] leading-5 text-secondaryLabel">
+ Review, share or export the full transcript.
+ </Text>
+ </View>
+ <View className="flex-row gap-3">
+ <MenuView
+ actions={[
+ { id: 'share', title: 'Share', image: 'square.and.arrow.up' },
+ { id: 'export-md', title: 'Export Markdown', image: 'doc.text' },
+ { id: 'export-txt', title: 'Export Plain Text', image: 'doc.plaintext' },
+ ]}
+ onPressAction={({ nativeEvent }) => {
+ if (nativeEvent.event === 'share') handleShare().catch(() => {});
+ else if (nativeEvent.event === 'export-md') onExport('md');
+ else if (nativeEvent.event === 'export-txt') onExport('txt');
+ }}
+ shouldOpenOnLongPress={false}
+ >
+ <Pressable
+ hitSlop={8}
+ accessibilityRole="button"
+ accessibilityLabel="Share or export transcript"
+ style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })}
+ >
+ <GlassCapsule>
+ <SystemIcon name="square.and.arrow.up" mdName="Share2" size={15} color="label" />
+ </GlassCapsule>
+ </Pressable>
+ </MenuView>
+ <GlassIconButton onPress={onClose} accessibilityLabel="Close">
+ <SystemIcon name="xmark" mdName="X" size={15} color="secondaryLabel" />
+ </GlassIconButton>
+ </View>
+ </View>
+
+ <ScrollView
+ contentContainerClassName="px-6"
+ contentContainerStyle={{ paddingBottom: insets.bottom + 24 }}
+ >
+ <SpeakerTranscript
+ blocks={blocks}
+ selectedSpeakerId={selectedSpeakerId}
+ selectable
+ onSpeakerPress={onSpeakerPress}
+ />
+ </ScrollView>
+ {children}
+ </View>
+ </Modal>
+ );
+}
diff --git a/openwhispr-mobile/src/components/notes/VoiceProfileList.tsx b/openwhispr-mobile/src/components/notes/VoiceProfileList.tsx
index d51ff0cb5..b5834a40e 100644
--- a/openwhispr-mobile/src/components/notes/VoiceProfileList.tsx
+++ b/openwhispr-mobile/src/components/notes/VoiceProfileList.tsx
@@ -51,9 +51,13 @@ export function VoiceProfileList({
color="quaternaryLabel"
/>
<View className="items-center gap-1">
- <Text className="text-[17px] font-semibold text-label">No voice profiles</Text>
+ <Text className="text-[17px] font-semibold text-label">
+ Label speakers automatically
+ </Text>
<Text className="text-center text-[15px] leading-5 text-tertiaryLabel">
- Voice profiles stay on this device and can be deleted anytime.
+ Record a short voice sample and OpenWhispr will recognize you in future meeting
+ transcripts instead of showing "Speaker 1". Works with on-device transcription.
+ Voiceprints stay on this device and can be deleted anytime.
</Text>
</View>
<Pressable
diff --git a/openwhispr-mobile/src/components/notes/__tests__/EditableMarkdown.test.tsx b/openwhispr-mobile/src/components/notes/__tests__/EditableMarkdown.test.tsx
new file mode 100644
index 000000000..e7518876f
--- /dev/null
+++ b/openwhispr-mobile/src/components/notes/__tests__/EditableMarkdown.test.tsx
@@ -0,0 +1,161 @@
+import { fireEvent, render } from '@testing-library/react-native';
+import { EditableMarkdown } from '../EditableMarkdown';
+
+jest.mock('@/components/ui/Text', () => ({ Text: require('react-native').Text }));
+jest.mock('../MarkdownRenderer', () => ({
+ MarkdownRenderer: ({ content }: { content: string }) => {
+ const { Text } = require('react-native');
+ return <Text testID="rendered-markdown">{content}</Text>;
+ },
+}));
+
+describe('EditableMarkdown', () => {
+ it('renders the Markdown and switches to the raw source on Edit', () => {
+ const onEditingChange = jest.fn();
+ const { getByTestId, queryByTestId } = render(
+ <EditableMarkdown
+ content="## Summary"
+ onChange={jest.fn()}
+ onEditingChange={onEditingChange}
+ />,
+ );
+ expect(getByTestId('rendered-markdown').props.children).toBe('## Summary');
+ expect(queryByTestId('enhanced-editor')).toBeNull();
+
+ fireEvent.press(getByTestId('enhanced-edit'));
+
+ expect(getByTestId('enhanced-editor').props.value).toBe('## Summary');
+ expect(onEditingChange).toHaveBeenLastCalledWith(true);
+ });
+
+ it('enters editing when the rendered notes are tapped', () => {
+ const { getByTestId } = render(<EditableMarkdown content="## Summary" onChange={jest.fn()} />);
+ fireEvent.press(getByTestId('enhanced-read'));
+ expect(getByTestId('enhanced-editor')).toBeTruthy();
+ });
+
+ it('does not enter editing on a long press, so text can be selected', () => {
+ const { getByTestId, queryByTestId } = render(
+ <EditableMarkdown content="## Summary" onChange={jest.fn()} />,
+ );
+ fireEvent(getByTestId('enhanced-read'), 'longPress');
+ expect(queryByTestId('enhanced-editor')).toBeNull();
+ });
+
+ it('reports each change and shows the edited notes after Done', () => {
+ const onChange = jest.fn();
+ const onEditingChange = jest.fn();
+ const { getByTestId } = render(
+ <EditableMarkdown
+ content="## Summary"
+ onChange={onChange}
+ onEditingChange={onEditingChange}
+ />,
+ );
+ fireEvent.press(getByTestId('enhanced-edit'));
+ expect(getByTestId('enhanced-editor').props.accessibilityLabel).toBe('Enhanced notes');
+ fireEvent.changeText(getByTestId('enhanced-editor'), '## Summary\n- Launch Friday');
+ expect(onChange).toHaveBeenCalledWith('## Summary\n- Launch Friday');
+
+ fireEvent.press(getByTestId('enhanced-done'));
+
+ expect(onEditingChange).toHaveBeenLastCalledWith(false);
+ expect(getByTestId('rendered-markdown').props.children).toBe('## Summary\n- Launch Friday');
+ });
+
+ it('cannot be edited while editable is false', () => {
+ const { getByTestId, queryByTestId } = render(
+ <EditableMarkdown content="## Summary" editable={false} onChange={jest.fn()} />,
+ );
+ expect(queryByTestId('enhanced-edit')).toBeNull();
+ fireEvent.press(getByTestId('enhanced-read'));
+ expect(queryByTestId('enhanced-editor')).toBeNull();
+ });
+
+ it('leaves editing when it stops being editable', () => {
+ const onEditingChange = jest.fn();
+ const { getByTestId, queryByTestId, rerender } = render(
+ <EditableMarkdown
+ content="## Summary"
+ onChange={jest.fn()}
+ onEditingChange={onEditingChange}
+ />,
+ );
+ fireEvent.press(getByTestId('enhanced-edit'));
+ rerender(
+ <EditableMarkdown
+ content="## Summary"
+ editable={false}
+ onChange={jest.fn()}
+ onEditingChange={onEditingChange}
+ />,
+ );
+ expect(queryByTestId('enhanced-editor')).toBeNull();
+ expect(onEditingChange).toHaveBeenLastCalledWith(false);
+ });
+
+ it('shows new saved notes while reading', () => {
+ const { getByTestId, rerender } = render(
+ <EditableMarkdown content="## Old" onChange={jest.fn()} />,
+ );
+ rerender(<EditableMarkdown content="## New" onChange={jest.fn()} />);
+ expect(getByTestId('rendered-markdown').props.children).toBe('## New');
+ });
+
+ it('follows new saved notes while an open edit is untouched', () => {
+ const { getByTestId, rerender } = render(
+ <EditableMarkdown content="## Old" onChange={jest.fn()} />,
+ );
+ fireEvent.press(getByTestId('enhanced-edit'));
+ rerender(<EditableMarkdown content="## New" onChange={jest.fn()} />);
+ expect(getByTestId('enhanced-editor').props.value).toBe('## New');
+
+ fireEvent.press(getByTestId('enhanced-done'));
+
+ expect(getByTestId('rendered-markdown').props.children).toBe('## New');
+ });
+
+ it('keeps what the user typed when new saved notes arrive mid-edit', () => {
+ const { getByTestId, rerender } = render(
+ <EditableMarkdown content="## Old" onChange={jest.fn()} />,
+ );
+ fireEvent.press(getByTestId('enhanced-edit'));
+ fireEvent.changeText(getByTestId('enhanced-editor'), '## Mine');
+ rerender(<EditableMarkdown content="## New" onChange={jest.fn()} />);
+ expect(getByTestId('enhanced-editor').props.value).toBe('## Mine');
+ });
+
+ it('follows saved notes again once a new edit starts', () => {
+ const { getByTestId, rerender } = render(
+ <EditableMarkdown content="## Old" onChange={jest.fn()} />,
+ );
+ fireEvent.press(getByTestId('enhanced-edit'));
+ fireEvent.changeText(getByTestId('enhanced-editor'), '## Mine');
+ fireEvent.press(getByTestId('enhanced-done'));
+ rerender(<EditableMarkdown content="## Mine" onChange={jest.fn()} />);
+
+ fireEvent.press(getByTestId('enhanced-edit'));
+ rerender(<EditableMarkdown content="## New" onChange={jest.fn()} />);
+
+ expect(getByTestId('enhanced-editor').props.value).toBe('## New');
+ });
+
+ it('leaves the rendered notes to screen readers instead of reading them as one block', () => {
+ const { getByTestId } = render(<EditableMarkdown content="## Summary" onChange={jest.fn()} />);
+ expect(getByTestId('enhanced-read').props.accessible).toBe(false);
+ });
+
+ it('reports leaving editing when unmounted mid-edit', () => {
+ const onEditingChange = jest.fn();
+ const { getByTestId, unmount } = render(
+ <EditableMarkdown
+ content="## Summary"
+ onChange={jest.fn()}
+ onEditingChange={onEditingChange}
+ />,
+ );
+ fireEvent.press(getByTestId('enhanced-edit'));
+ unmount();
+ expect(onEditingChange).toHaveBeenLastCalledWith(false);
+ });
+});
diff --git a/openwhispr-mobile/src/components/notes/__tests__/NoteActionsMenu.test.tsx b/openwhispr-mobile/src/components/notes/__tests__/NoteActionsMenu.test.tsx
new file mode 100644
index 000000000..74343c65c
--- /dev/null
+++ b/openwhispr-mobile/src/components/notes/__tests__/NoteActionsMenu.test.tsx
@@ -0,0 +1,87 @@
+import { fireEvent, render } from '@testing-library/react-native';
+import { NoteActionsMenu } from '../NoteActionsMenu';
+
+jest.mock('@react-native-menu/menu', () => ({
+ MenuView: ({
+ actions,
+ onPressAction,
+ children,
+ }: {
+ actions: { id: string; title: string; attributes?: { disabled?: boolean } }[];
+ onPressAction: (event: { nativeEvent: { event: string } }) => void;
+ children?: React.ReactNode;
+ }) => {
+ const { Pressable, Text, View } = require('react-native');
+ return (
+ <View>
+ {children}
+ {actions.map((action) => (
+ <Pressable
+ key={action.id}
+ testID={`menu-${action.id}`}
+ accessibilityState={{ disabled: !!action.attributes?.disabled }}
+ onPress={() => onPressAction({ nativeEvent: { event: action.id } })}
+ >
+ <Text>{action.title}</Text>
+ </Pressable>
+ ))}
+ </View>
+ );
+ },
+}));
+jest.mock('@sentry/react-native', () => ({ captureException: jest.fn() }));
+jest.mock('@/components/ui/SystemIcon', () => ({ SystemIcon: () => null }));
+jest.mock('@/components/ui/GlassIconButton', () => ({
+ GlassCapsule: ({ children }: { children?: React.ReactNode }) => {
+ const { View } = require('react-native');
+ return <View>{children}</View>;
+ },
+}));
+jest.mock('@/store/useNotesStore', () => {
+ const state = { notes: [], setNotePrivacy: jest.fn() };
+ return {
+ useNotesStore: (selector: (s: typeof state) => unknown) => selector(state),
+ };
+});
+
+const baseProps = {
+ noteId: 7,
+ actions: [],
+ hasContent: true,
+ isRecording: false,
+ processing: false,
+ onRunAction: jest.fn(),
+ onManageActions: jest.fn(),
+ onShare: jest.fn(),
+ onDelete: jest.fn(),
+};
+
+describe('NoteActionsMenu', () => {
+ it('opens the transcript from View Transcript', () => {
+ const onViewTranscript = jest.fn();
+ const { getByTestId, getByText } = render(
+ <NoteActionsMenu {...baseProps} onViewTranscript={onViewTranscript} />,
+ );
+ expect(getByText('View Transcript')).toBeTruthy();
+ fireEvent.press(getByTestId('menu-__view_transcript'));
+ expect(onViewTranscript).toHaveBeenCalled();
+ });
+
+ it('lets the caller decide when Ask is available, even without note body content', () => {
+ const { getByTestId, rerender } = render(
+ <NoteActionsMenu {...baseProps} hasContent={false} onAskNote={jest.fn()} />,
+ );
+ expect(getByTestId('menu-__ask_note').props.accessibilityState.disabled).toBe(false);
+
+ rerender(
+ <NoteActionsMenu {...baseProps} hasContent={false} onAskNote={jest.fn()} askNoteDisabled />,
+ );
+ expect(getByTestId('menu-__ask_note').props.accessibilityState.disabled).toBe(true);
+ });
+
+ it('has no transcript item for a note without a transcript', () => {
+ const { queryByText } = render(<NoteActionsMenu {...baseProps} />);
+ expect(queryByText('View Transcript')).toBeNull();
+ expect(queryByText('Copy Transcript')).toBeNull();
+ });
+});
diff --git a/openwhispr-mobile/src/components/notes/__tests__/NoteMetaRow.test.tsx b/openwhispr-mobile/src/components/notes/__tests__/NoteMetaRow.test.tsx
new file mode 100644
index 000000000..329bb2843
--- /dev/null
+++ b/openwhispr-mobile/src/components/notes/__tests__/NoteMetaRow.test.tsx
@@ -0,0 +1,136 @@
+import { fireEvent, render } from '@testing-library/react-native';
+import type { CalendarParticipant } from '@/data/calendarTypes';
+import { NoteMetaRow } from '../NoteMetaRow';
+import { AttendeesSheet } from '../AttendeesSheet';
+
+jest.mock('react-native-safe-area-context', () => ({
+ useSafeAreaInsets: () => ({ top: 0, right: 0, bottom: 0, left: 0 }),
+}));
+jest.mock('@/components/ui/Text', () => ({ Text: require('react-native').Text }));
+jest.mock('@/components/ui/SystemIcon', () => ({ SystemIcon: () => null }));
+jest.mock('@/components/ui/GlassIconButton', () => ({
+ GlassIconButton: ({
+ children,
+ onPress,
+ accessibilityLabel,
+ }: {
+ children?: React.ReactNode;
+ onPress?: () => void;
+ accessibilityLabel?: string;
+ }) => {
+ const { Pressable } = require('react-native');
+ return (
+ <Pressable accessibilityLabel={accessibilityLabel} onPress={onPress}>
+ {children}
+ </Pressable>
+ );
+ },
+}));
+
+const person = (overrides: Partial<CalendarParticipant> = {}): CalendarParticipant => ({
+ email: null,
+ displayName: null,
+ responseStatus: 'accepted',
+ optional: false,
+ organizer: false,
+ resource: false,
+ self: false,
+ ...overrides,
+});
+
+describe('NoteMetaRow', () => {
+ const props = {
+ dateLabel: 'Today 09:27',
+ attendeeLabel: 'Sam +3',
+ folderLabel: 'Meetings',
+ onPressAttendees: jest.fn(),
+ onPressFolder: jest.fn(),
+ };
+
+ it('shows the date, attendees and folder', () => {
+ const { getByText } = render(<NoteMetaRow {...props} />);
+ expect(getByText('Today 09:27')).toBeTruthy();
+ expect(getByText('Sam +3')).toBeTruthy();
+ expect(getByText('Meetings')).toBeTruthy();
+ });
+
+ it('opens the attendees and the folder picker', () => {
+ const onPressAttendees = jest.fn();
+ const onPressFolder = jest.fn();
+ const { getByTestId } = render(
+ <NoteMetaRow {...props} onPressAttendees={onPressAttendees} onPressFolder={onPressFolder} />,
+ );
+ fireEvent.press(getByTestId('note-meta-attendees'));
+ fireEvent.press(getByTestId('note-meta-folder'));
+ expect(onPressAttendees).toHaveBeenCalled();
+ expect(onPressFolder).toHaveBeenCalled();
+ });
+
+ it('hides the attendees chip when nobody attends', () => {
+ const { queryByTestId, getByText } = render(<NoteMetaRow {...props} attendeeLabel={null} />);
+ expect(queryByTestId('note-meta-attendees')).toBeNull();
+ expect(getByText('Today 09:27')).toBeTruthy();
+ });
+
+ it('keeps long names to one line', () => {
+ const { getByText } = render(
+ <NoteMetaRow
+ {...props}
+ attendeeLabel="Bartholomew-Alexander +12"
+ folderLabel="Quarterly planning and roadmap reviews"
+ />,
+ );
+ expect(getByText('Bartholomew-Alexander +12').props).toMatchObject({
+ numberOfLines: 1,
+ ellipsizeMode: 'middle',
+ });
+ expect(getByText('Quarterly planning and roadmap reviews').props.numberOfLines).toBe(1);
+ });
+
+ it('hides the folder chip for a note that cannot be moved', () => {
+ const { queryByTestId } = render(<NoteMetaRow {...props} onPressFolder={undefined} />);
+ expect(queryByTestId('note-meta-folder')).toBeNull();
+ });
+
+ it('offers Add to folder for a note outside any folder', () => {
+ const { getByText } = render(<NoteMetaRow {...props} folderLabel={null} />);
+ expect(getByText('Add to folder')).toBeTruthy();
+ });
+});
+
+describe('AttendeesSheet', () => {
+ it('lists people with the organizer first, marks the organizer and you, and skips rooms', () => {
+ const { getByText, queryByText, getAllByTestId } = render(
+ <AttendeesSheet
+ visible
+ onClose={jest.fn()}
+ participants={[
+ person({ displayName: 'Sam Lee', email: '[email protected]' }),
+ person({ displayName: 'Board Room', resource: true }),
+ person({ displayName: 'Me', email: '[email protected]', self: true }),
+ person({ displayName: 'Ana Ruiz', email: '[email protected]', organizer: true }),
+ ]}
+ />,
+ );
+ expect(getByText('Attendees')).toBeTruthy();
+ expect(getAllByTestId(/^attendee-row-/).map((row) => row.props.testID)).toEqual([
+ 'attendee-row-0',
+ 'attendee-row-1',
+ 'attendee-row-2',
+ ]);
+ expect(getByText('Ana Ruiz')).toBeTruthy();
+ expect(getByText('Organizer')).toBeTruthy();
+ expect(getByText('You')).toBeTruthy();
+ expect(getByText('[email protected]')).toBeTruthy();
+ expect(queryByText('Board Room')).toBeNull();
+ });
+
+ it('closes from the close button', () => {
+ const onClose = jest.fn();
+ const { getByLabelText } = render(
+ <AttendeesSheet visible onClose={onClose} participants={[person({ displayName: 'Sam' })]} />,
+ );
+ fireEvent.press(getByLabelText('Close'));
+ expect(onClose).toHaveBeenCalled();
+ });
+});
diff --git a/openwhispr-mobile/src/components/notes/__tests__/TranscriptSheet.test.tsx b/openwhispr-mobile/src/components/notes/__tests__/TranscriptSheet.test.tsx
new file mode 100644
index 000000000..67c22790b
--- /dev/null
+++ b/openwhispr-mobile/src/components/notes/__tests__/TranscriptSheet.test.tsx
@@ -0,0 +1,146 @@
+import { Alert, Share, Text } from 'react-native';
+import { act, fireEvent, render } from '@testing-library/react-native';
+import type { TranscriptBlock } from '@/lib/diarization/transcriptDisplay';
+import { TranscriptSheet } from '../TranscriptSheet';
+
+jest.mock('@react-native-menu/menu', () => ({
+ MenuView: ({
+ actions,
+ onPressAction,
+ children,
+ }: {
+ actions: { id: string; title: string }[];
+ onPressAction: (event: { nativeEvent: { event: string } }) => void;
+ children?: React.ReactNode;
+ }) => {
+ const { Pressable, Text: MockText, View } = require('react-native');
+ return (
+ <View>
+ {children}
+ {actions.map((action) => (
+ <Pressable
+ key={action.id}
+ testID={`menu-${action.id}`}
+ onPress={() => onPressAction({ nativeEvent: { event: action.id } })}
+ >
+ <MockText>{action.title}</MockText>
+ </Pressable>
+ ))}
+ </View>
+ );
+ },
+}));
+jest.mock('react-native-safe-area-context', () => ({
+ useSafeAreaInsets: () => ({ top: 0, right: 0, bottom: 0, left: 0 }),
+}));
+jest.mock('@/components/ui/Text', () => ({ Text: require('react-native').Text }));
+jest.mock('@/components/ui/SystemIcon', () => ({ SystemIcon: () => null }));
+jest.mock('@/components/ui/GlassIconButton', () => ({
+ GlassCapsule: ({ children }: { children?: React.ReactNode }) => children,
+ GlassIconButton: ({
+ children,
+ onPress,
+ accessibilityLabel,
+ }: {
+ children?: React.ReactNode;
+ onPress?: () => void;
+ accessibilityLabel?: string;
+ }) => {
+ const { Pressable } = require('react-native');
+ return (
+ <Pressable accessibilityLabel={accessibilityLabel} onPress={onPress}>
+ {children}
+ </Pressable>
+ );
+ },
+}));
+
+const block: TranscriptBlock = {
+ id: 'b1',
+ speakerId: 10,
+ speakerLabel: 'speaker_0',
+ speakerName: 'Speaker 1',
+ speakerColor: '#FF0000',
+ speakerStatus: 'provisional',
+ startMs: 0,
+ endMs: 1000,
+ timestamp: '0:00',
+ text: 'Hello there',
+ segmentIds: [1],
+};
+
+const renderSheet = (overrides: Partial<React.ComponentProps<typeof TranscriptSheet>> = {}) =>
+ render(
+ <TranscriptSheet
+ visible
+ blocks={[block]}
+ selectedSpeakerId={null}
+ shareText="[0:00] Speaker 1: Hello there"
+ onSpeakerPress={jest.fn()}
+ onExport={jest.fn()}
+ onClose={jest.fn()}
+ {...overrides}
+ />,
+ );
+
+describe('TranscriptSheet', () => {
+ it('shows the title, subtitle and transcript', () => {
+ const { getByText } = renderSheet();
+ expect(getByText('Transcript')).toBeTruthy();
+ expect(getByText('Review, share or export the full transcript.')).toBeTruthy();
+ expect(getByText('Hello there')).toBeTruthy();
+ });
+
+ it('hands a tapped speaker to the caller', () => {
+ const onSpeakerPress = jest.fn();
+ const { getByTestId } = renderSheet({ onSpeakerPress });
+ fireEvent.press(getByTestId('speaker-button-10'));
+ expect(onSpeakerPress).toHaveBeenCalledWith(block);
+ });
+
+ it('shares the transcript text', async () => {
+ const shareSpy = jest.spyOn(Share, 'share').mockResolvedValue({ action: 'sharedAction' });
+ const { getByTestId } = renderSheet();
+ await act(async () => {
+ fireEvent.press(getByTestId('menu-share'));
+ });
+ expect(shareSpy).toHaveBeenCalledWith({ message: '[0:00] Speaker 1: Hello there' });
+ shareSpy.mockRestore();
+ });
+
+ it('explains when sharing fails', async () => {
+ const shareSpy = jest.spyOn(Share, 'share').mockRejectedValue(new Error('nope'));
+ const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined);
+ const { getByTestId } = renderSheet();
+ await act(async () => {
+ fireEvent.press(getByTestId('menu-share'));
+ });
+ expect(alertSpy).toHaveBeenCalledWith('Error', 'Unable to share transcript');
+ shareSpy.mockRestore();
+ alertSpy.mockRestore();
+ });
+
+ it('exports the transcript as a Markdown or text file', () => {
+ const onExport = jest.fn();
+ const { getByTestId, getByText } = renderSheet({ onExport });
+ expect(getByText('Export Markdown')).toBeTruthy();
+ expect(getByText('Export Plain Text')).toBeTruthy();
+
+ fireEvent.press(getByTestId('menu-export-md'));
+ fireEvent.press(getByTestId('menu-export-txt'));
+
+ expect(onExport.mock.calls).toEqual([['md'], ['txt']]);
+ });
+
+ it('closes from the close button', () => {
+ const onClose = jest.fn();
+ const { getByLabelText } = renderSheet({ onClose });
+ fireEvent.press(getByLabelText('Close'));
+ expect(onClose).toHaveBeenCalled();
+ });
+
+ it('renders its children inside the sheet so speaker sheets can present above it', () => {
+ const { getByText } = renderSheet({ children: <Text>rename-sheet</Text> });
+ expect(getByText('rename-sheet')).toBeTruthy();
+ });
+});
diff --git a/openwhispr-mobile/src/components/notes/__tests__/VoiceProfiles.test.tsx b/openwhispr-mobile/src/components/notes/__tests__/VoiceProfiles.test.tsx
index 6e77a8a78..dba6b7663 100644
--- a/openwhispr-mobile/src/components/notes/__tests__/VoiceProfiles.test.tsx
+++ b/openwhispr-mobile/src/components/notes/__tests__/VoiceProfiles.test.tsx
@@ -81,10 +81,14 @@ describe('VoiceProfileList', () => {
it('offers owner enrollment in the empty state', () => {
const onEnrollOwner = jest.fn();
- const { getByTestId } = render(
+ const { getByTestId, getByText } = render(
<VoiceProfileList profiles={[]} {...baseListProps} onEnrollOwner={onEnrollOwner} />,
);
+ expect(getByText('Label speakers automatically')).toBeTruthy();
+ expect(getByText(/works with on-device transcription/i)).toBeTruthy();
+ // Worded like the Enroll Me row and prompt card.
+ expect(getByText('Enroll Me')).toBeTruthy();
fireEvent.press(getByTestId('voice-profile-enroll-owner-empty'));
expect(onEnrollOwner).toHaveBeenCalled();
diff --git a/openwhispr-mobile/src/data/local/__tests__/notesRepository.remoteCreatedAt.test.ts b/openwhispr-mobile/src/data/local/__tests__/notesRepository.remoteCreatedAt.test.ts
new file mode 100644
index 000000000..0b09f3525
--- /dev/null
+++ b/openwhispr-mobile/src/data/local/__tests__/notesRepository.remoteCreatedAt.test.ts
@@ -0,0 +1,75 @@
+import { createMemoryRepository } from './testDb';
+import type { RemoteNote } from '@/data/types';
+
+const remoteNote = (overrides: Partial<RemoteNote> = {}): RemoteNote => ({
+ id: 'remote-note-1',
+ client_note_id: 'client-note-1',
+ title: 'Planning Sync',
+ content: 'Discuss launch.',
+ enhanced_content: null,
+ enhancement_prompt: null,
+ note_type: 'meeting',
+ source_file: null,
+ audio_duration_seconds: null,
+ folder_id: null,
+ participants: null,
+ calendar_event_id: null,
+ transcript: null,
+ deleted_at: null,
+ created_at: '2026-06-01T09:00:00.000Z',
+ updated_at: '2026-06-26T10:00:00.000Z',
+ ...overrides,
+});
+
+describe('LocalNotesRepository pulled created_at', () => {
+ it('keeps the server creation time on a pulled note', () => {
+ const { repo } = createMemoryRepository();
+
+ repo.applyRemoteNote(remoteNote(), () => null);
+
+ expect(repo.getAllNotes()[0].createdAt).toBe('2026-06-01T09:00:00.000Z');
+ });
+
+ it('repairs the creation time of a note pulled before it was synced', () => {
+ const { repo } = createMemoryRepository();
+ repo.applyRemoteNote(remoteNote({ created_at: undefined }), () => null);
+ const [pulled] = repo.getAllNotes();
+ expect(pulled.createdAt).not.toBe('2026-06-01T09:00:00.000Z');
+
+ repo.applyRemoteNote(remoteNote({ updated_at: '2026-06-27T10:00:00.000Z' }), () => null);
+
+ expect(repo.getNoteById(pulled.id)?.createdAt).toBe('2026-06-01T09:00:00.000Z');
+ });
+
+ it('repairs the creation time from the server’s reply to a push', () => {
+ const { repo } = createMemoryRepository();
+ repo.applyRemoteNote(remoteNote({ created_at: undefined }), () => null);
+ const [pulled] = repo.getAllNotes();
+ repo.updateNote(pulled.id, { title: 'Planning Sync, edited' });
+
+ repo.markNotePushed(
+ repo.getNoteById(pulled.id)!,
+ 'remote-note-1',
+ '2026-09-28T10:00:00.000Z',
+ undefined,
+ '2026-06-01T09:00:00.000Z',
+ );
+
+ const pushed = repo.getNoteById(pulled.id)!;
+ expect(pushed.createdAt).toBe('2026-06-01T09:00:00.000Z');
+ expect(pushed.cloudUpdatedAt).toBe('2026-09-28T10:00:00.000Z');
+ expect(pushed.pendingSync).toBe(0);
+ });
+
+ it('leaves the stored creation time alone when the server sends none', () => {
+ const { repo } = createMemoryRepository();
+ const local = repo.createNote('Planning Sync', '');
+ repo.setNoteClientId(local.id, 'client-note-1');
+ repo.markNotePushed(repo.getNoteById(local.id)!, 'remote-note-1', '2026-06-26T09:00:00.000Z');
+ const { createdAt } = repo.getNoteById(local.id)!;
+
+ repo.applyRemoteNote(remoteNote({ created_at: undefined }), () => null);
+
+ expect(repo.getNoteById(local.id)?.createdAt).toBe(createdAt);
+ });
+});
diff --git a/openwhispr-mobile/src/data/local/notesRepository.ts b/openwhispr-mobile/src/data/local/notesRepository.ts
index d58f6c474..1b1e69af7 100644
--- a/openwhispr-mobile/src/data/local/notesRepository.ts
+++ b/openwhispr-mobile/src/data/local/notesRepository.ts
@@ -831,6 +831,7 @@ export class LocalNotesRepository implements NotesRepository {
// space, the team pass passes the space it resolved.
spaceId: options.spaceId ?? this.getPrivateSpaceId(),
...this.remoteOwnershipValues(remote, options.applyOwnership),
+ ...(remote.created_at ? { createdAt: remote.created_at } : {}),
cloudUpdatedAt: remote.updated_at,
updatedAt: remote.updated_at,
})
@@ -885,6 +886,8 @@ export class LocalNotesRepository implements NotesRepository {
// space the row keeps whatever space it already sits in.
...(options.spaceId !== undefined ? { spaceId: options.spaceId } : {}),
...this.remoteOwnershipValues(remote, options.applyOwnership),
+ // Also repairs rows pulled before created_at synced, which carry their pull time.
+ ...(remote.created_at ? { createdAt: remote.created_at } : {}),
cloudUpdatedAt: remote.updated_at,
updatedAt: remote.updated_at,
})
@@ -1012,6 +1015,7 @@ export class LocalNotesRepository implements NotesRepository {
remoteId: string,
serverUpdatedAt: string,
cloudUpdatedAt: string | null = serverUpdatedAt,
+ serverCreatedAt?: string,
): void {
const current = this.getNoteById(pushed.id);
// Forked or re-identified while the request was in flight: the ack names
@@ -1024,12 +1028,13 @@ export class LocalNotesRepository implements NotesRepository {
// record the server revision so the follow-up push PATCHes the right base
// instead of re-creating the note.
const unchanged = NOTE_PUSH_ACK_FIELDS.every((field) => current[field] === pushed[field]);
+ const createdAt = serverCreatedAt ? { createdAt: serverCreatedAt } : {};
this.database
.update(notes)
.set(
unchanged
- ? { remoteId, pendingSync: 0, updatedAt: serverUpdatedAt, cloudUpdatedAt }
- : { remoteId, cloudUpdatedAt },
+ ? { remoteId, pendingSync: 0, updatedAt: serverUpdatedAt, cloudUpdatedAt, ...createdAt }
+ : { remoteId, cloudUpdatedAt, ...createdAt },
)
.where(eq(notes.id, pushed.id))
.run();
diff --git a/openwhispr-mobile/src/data/synced/SyncedNotesRepository.ts b/openwhispr-mobile/src/data/synced/SyncedNotesRepository.ts
index 4625437ff..7f658189c 100644
--- a/openwhispr-mobile/src/data/synced/SyncedNotesRepository.ts
+++ b/openwhispr-mobile/src/data/synced/SyncedNotesRepository.ts
@@ -217,8 +217,9 @@ export class SyncedNotesRepository implements NotesRepository {
remoteId: string,
serverUpdatedAt: string,
cloudUpdatedAt?: string | null,
+ serverCreatedAt?: string,
): void {
- this.local.markNotePushed(pushed, remoteId, serverUpdatedAt, cloudUpdatedAt);
+ this.local.markNotePushed(pushed, remoteId, serverUpdatedAt, cloudUpdatedAt, serverCreatedAt);
}
markNoteTerminal(localId: number): void {
this.local.markNoteTerminal(localId);
diff --git a/openwhispr-mobile/src/data/types.ts b/openwhispr-mobile/src/data/types.ts
index 7590bee20..c8698d251 100644
--- a/openwhispr-mobile/src/data/types.ts
+++ b/openwhispr-mobile/src/data/types.ts
@@ -99,6 +99,8 @@ export interface RemoteNote {
/** Desktop-shape transcript JSON; decomposed into segments/speakers on apply. */
transcript: string | null;
deleted_at: string | null;
+ /** Optional: not every server payload that reaches an apply path carries it. */
+ created_at?: string;
updated_at: string;
// Scope fields declared for a later task; not yet populated by pull/apply.
space_id?: string | null;
@@ -292,12 +294,16 @@ export interface NotesRepository {
* as `null` when serverUpdatedAt is itself a local-clock fallback (the server
* response omitted its own updated_at) — cloudUpdatedAt must only ever hold a
* genuine server ack, never a value guaranteed to mismatch on the next push.
+ *
+ * serverCreatedAt, when the response carries it, repairs a createdAt stamped
+ * with the pull time by builds that didn't sync created_at.
*/
markNotePushed(
pushed: Note,
remoteId: string,
serverUpdatedAt: string,
cloudUpdatedAt?: string | null,
+ serverCreatedAt?: string,
): void;
/** Clears pendingSync with no other changes — used when a push was permanently rejected (e.g. HTTP 400) and retrying would never succeed. */
markNoteTerminal(localId: number): void;
diff --git a/openwhispr-mobile/src/hooks/__tests__/useMoveNote.test.ts b/openwhispr-mobile/src/hooks/__tests__/useMoveNote.test.ts
new file mode 100644
index 000000000..d86079a1e
--- /dev/null
+++ b/openwhispr-mobile/src/hooks/__tests__/useMoveNote.test.ts
@@ -0,0 +1,146 @@
+import { act, renderHook } from '@testing-library/react-native';
+import type { Folder, Space } from '@/data';
+import { useMoveNote } from '@/hooks/useMoveNote';
+
+const mockState = {
+ spaces: [] as Space[],
+ folderCounts: { 1: 4 } as Record<number, number>,
+ moveNoteToFolder: jest.fn(),
+ moveNoteToSpace: jest.fn(),
+ createFolder: jest.fn(),
+};
+
+jest.mock('@/store/useNotesStore', () => ({
+ useNotesStore: (selector: (state: typeof mockState) => unknown) => selector(mockState),
+}));
+
+jest.mock('@/lib/utils', () => ({ safeHaptics: jest.fn() }));
+
+const space = (overrides: Partial<Space>): Space =>
+ ({
+ id: 1,
+ clientSpaceId: 'client',
+ cloudSpaceId: 'cloud',
+ workspaceId: null,
+ kind: 'private',
+ name: 'Personal',
+ emoji: null,
+ sortOrder: 0,
+ myRole: null,
+ memberCount: 1,
+ teams: null,
+ syncStatus: 'synced',
+ deletedAt: null,
+ createdAt: null,
+ updatedAt: null,
+ ...overrides,
+ }) as Space;
+
+const folder = (overrides: Partial<Folder>): Folder =>
+ ({
+ id: 1,
+ name: 'Meetings',
+ isDefault: 0,
+ sortOrder: 0,
+ spaceId: 1,
+ clientFolderId: null,
+ remoteId: null,
+ deletedAt: null,
+ pendingSync: 0,
+ createdAt: null,
+ updatedAt: null,
+ ...overrides,
+ }) as Folder;
+
+const privateSpace = space({ id: 1, kind: 'private' });
+const engineering = space({ id: 2, kind: 'team', workspaceId: 'w1', name: 'Engineering' });
+const design = space({ id: 3, kind: 'team', workspaceId: 'w1', name: 'Design' });
+const otherWorkspace = space({ id: 4, kind: 'team', workspaceId: 'w2', name: 'Elsewhere' });
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ mockState.spaces = [privateSpace, engineering, design, otherWorkspace];
+});
+
+describe('useMoveNote', () => {
+ it('starts closed and passes the folders and counts through', () => {
+ const folders = [folder({ id: 1 })];
+ const { result } = renderHook(() =>
+ useMoveNote({ scopeSpaceId: null, targetFolders: folders, excludeFolderId: 1 }),
+ );
+ expect(result.current.sheetProps).toEqual(
+ expect.objectContaining({
+ visible: false,
+ folders,
+ folderCounts: { 1: 4 },
+ excludeFolderId: 1,
+ activeSpaceId: null,
+ }),
+ );
+ });
+
+ it('offers personal content every team space, never the private one', () => {
+ const { result } = renderHook(() =>
+ useMoveNote({ scopeSpaceId: null, targetFolders: [], excludeFolderId: null }),
+ );
+ expect(result.current.sheetProps.spaces?.map((s) => s.id)).toEqual([2, 3, 4]);
+ });
+
+ it('keeps team content inside its own workspace', () => {
+ const { result } = renderHook(() =>
+ useMoveNote({ scopeSpaceId: 2, targetFolders: [], excludeFolderId: null }),
+ );
+ expect(result.current.sheetProps.spaces?.map((s) => s.id)).toEqual([3]);
+ });
+
+ it('moves the opened note into the picked folder and closes', () => {
+ const { result } = renderHook(() =>
+ useMoveNote({ scopeSpaceId: null, targetFolders: [], excludeFolderId: null }),
+ );
+ act(() => result.current.open(7));
+ expect(result.current.sheetProps.visible).toBe(true);
+ act(() => result.current.sheetProps.onPickFolder(5));
+ expect(mockState.moveNoteToFolder).toHaveBeenCalledWith(7, 5);
+ expect(result.current.sheetProps.visible).toBe(false);
+ });
+
+ it('closes without moving when the caller closes it', () => {
+ const { result } = renderHook(() =>
+ useMoveNote({ scopeSpaceId: null, targetFolders: [], excludeFolderId: null }),
+ );
+ act(() => result.current.open(7));
+ act(() => result.current.close());
+ expect(result.current.sheetProps.visible).toBe(false);
+ act(() => result.current.sheetProps.onPickFolder(5));
+ expect(mockState.moveNoteToFolder).not.toHaveBeenCalled();
+ });
+
+ it('creates the new folder in the note’s space and moves the note into it', () => {
+ mockState.createFolder.mockReturnValue(folder({ id: 9, spaceId: 2 }));
+ const { result } = renderHook(() =>
+ useMoveNote({ scopeSpaceId: 2, targetFolders: [], excludeFolderId: null }),
+ );
+ act(() => result.current.open(7));
+ act(() => result.current.sheetProps.onCreateAndPick('Launch'));
+ expect(mockState.createFolder).toHaveBeenCalledWith('Launch', 2);
+ expect(mockState.moveNoteToFolder).toHaveBeenCalledWith(7, 9);
+ });
+
+ it('moves the opened note to the picked space', () => {
+ const { result } = renderHook(() =>
+ useMoveNote({ scopeSpaceId: null, targetFolders: [], excludeFolderId: null }),
+ );
+ act(() => result.current.open(7));
+ act(() => result.current.sheetProps.onPickSpace?.(3));
+ expect(mockState.moveNoteToSpace).toHaveBeenCalledWith(7, 3);
+ expect(result.current.sheetProps.visible).toBe(false);
+ });
+
+ it('does nothing when a pick arrives with no note open', () => {
+ const { result } = renderHook(() =>
+ useMoveNote({ scopeSpaceId: null, targetFolders: [], excludeFolderId: null }),
+ );
+ act(() => result.current.sheetProps.onPickFolder(5));
+ expect(mockState.moveNoteToFolder).not.toHaveBeenCalled();
+ });
+});
diff --git a/openwhispr-mobile/src/hooks/useMoveNote.ts b/openwhispr-mobile/src/hooks/useMoveNote.ts
new file mode 100644
index 000000000..781b4f4ab
--- /dev/null
+++ b/openwhispr-mobile/src/hooks/useMoveNote.ts
@@ -0,0 +1,104 @@
+import { useCallback, useMemo, useState } from 'react';
+import type { MoveToFolderSheetProps } from '@/components/notes/MoveToFolderSheet';
+import type { Folder } from '@/data';
+import { canMoveBetweenSpaces } from '@/lib/spacePermissions';
+import { safeHaptics } from '@/lib/utils';
+import { useNotesStore } from '@/store/useNotesStore';
+
+export interface UseMoveNoteOptions {
+ /** The team space the content belongs to, or null for personal content. */
+ scopeSpaceId: number | null;
+ /** Folders offered as targets, always from the same space as the note. */
+ targetFolders: Folder[];
+ excludeFolderId: number | null;
+}
+
+export interface UseMoveNoteResult {
+ open: (noteId: number) => void;
+ close: () => void;
+ sheetProps: MoveToFolderSheetProps;
+}
+
+export function useMoveNote({
+ scopeSpaceId,
+ targetFolders,
+ excludeFolderId,
+}: UseMoveNoteOptions): UseMoveNoteResult {
+ const spaces = useNotesStore((s) => s.spaces);
+ const folderCounts = useNotesStore((s) => s.folderCounts);
+ const moveNoteToFolder = useNotesStore((s) => s.moveNoteToFolder);
+ const moveNoteToSpace = useNotesStore((s) => s.moveNoteToSpace);
+ const createFolder = useNotesStore((s) => s.createFolder);
+ const [movingNoteId, setMovingNoteId] = useState<number | null>(null);
+
+ // Where this note is allowed to go, by desktop's rule: personal content may
+ // move to any team space, while team content stays inside its own workspace —
+ // never back to the private space, and never across workspaces.
+ const targetSpaces = useMemo(() => {
+ const from =
+ scopeSpaceId != null
+ ? spaces.find((s) => s.id === scopeSpaceId)
+ : spaces.find((s) => s.kind === 'private');
+ if (!from) return [];
+ return spaces.filter(
+ (space) => space.kind === 'team' && space.id !== from.id && canMoveBetweenSpaces(from, space),
+ );
+ }, [spaces, scopeSpaceId]);
+
+ const open = useCallback((noteId: number) => {
+ safeHaptics('medium');
+ setMovingNoteId(noteId);
+ }, []);
+
+ const close = useCallback(() => setMovingNoteId(null), []);
+
+ const pickFolder = useCallback(
+ (folderId: number) => {
+ if (movingNoteId != null) {
+ moveNoteToFolder(movingNoteId, folderId);
+ safeHaptics('success');
+ }
+ setMovingNoteId(null);
+ },
+ [movingNoteId, moveNoteToFolder],
+ );
+
+ const createAndPick = useCallback(
+ (name: string) => {
+ const folder = createFolder(name, scopeSpaceId ?? undefined);
+ if (movingNoteId != null) {
+ moveNoteToFolder(movingNoteId, folder.id);
+ }
+ setMovingNoteId(null);
+ },
+ [movingNoteId, createFolder, moveNoteToFolder, scopeSpaceId],
+ );
+
+ const pickSpace = useCallback(
+ (spaceId: number) => {
+ if (movingNoteId != null) {
+ moveNoteToSpace(movingNoteId, spaceId);
+ safeHaptics('success');
+ }
+ setMovingNoteId(null);
+ },
+ [movingNoteId, moveNoteToSpace],
+ );
+
+ return {
+ open,
+ close,
+ sheetProps: {
+ visible: movingNoteId != null,
+ folders: targetFolders,
+ folderCounts,
+ excludeFolderId,
+ onClose: close,
+ onPickFolder: pickFolder,
+ onCreateAndPick: createAndPick,
+ spaces: targetSpaces,
+ activeSpaceId: scopeSpaceId,
+ onPickSpace: pickSpace,
+ },
+ };
+}
diff --git a/openwhispr-mobile/src/lib/__tests__/noteExport.test.ts b/openwhispr-mobile/src/lib/__tests__/noteExport.test.ts
index c2e5c1cdc..61ca141cb 100644
--- a/openwhispr-mobile/src/lib/__tests__/noteExport.test.ts
+++ b/openwhispr-mobile/src/lib/__tests__/noteExport.test.ts
@@ -2,9 +2,8 @@ import { buildNoteShareContent } from '../noteExport';
describe('buildNoteShareContent', () => {
const base = {
- viewMode: 'original' as const,
+ viewMode: 'notes' as const,
enhancedContent: null,
- usesSegmentTranscript: false,
transcript: '[00:12] Alice: Hello there\n\n[00:15] Bob: Hi',
content: 'Raw note body',
};
@@ -19,29 +18,19 @@ describe('buildNoteShareContent', () => {
).toBe('## Summary\n\n- Decision made');
});
- it('shares the enhanced notes for meeting notes too', () => {
- expect(
- buildNoteShareContent({
- ...base,
- viewMode: 'enhanced',
- enhancedContent: '## Meeting notes',
- usesSegmentTranscript: true,
- }),
- ).toBe('## Meeting notes');
- });
-
- it('shares the formatted transcript when viewing the transcript of a meeting note', () => {
- const shared = buildNoteShareContent({ ...base, usesSegmentTranscript: true });
+ it('shares the formatted transcript when viewing the transcript', () => {
+ const shared = buildNoteShareContent({ ...base, viewMode: 'transcript' });
expect(shared).toBe(base.transcript);
expect(shared).not.toContain('Raw notes captured during the meeting');
expect(shared).not.toContain('Meeting transcript:');
});
- it('shares the note body for plain notes without enhancement', () => {
+ it('shares the note body on My notes', () => {
expect(buildNoteShareContent(base)).toBe('Raw note body');
});
- it('falls back to the original content when enhanced view has no enhanced content', () => {
- expect(buildNoteShareContent({ ...base, viewMode: 'enhanced' })).toBe('Raw note body');
+ it('shares nothing but the title from an empty tab, as the tab shows', () => {
+ expect(buildNoteShareContent({ ...base, viewMode: 'enhanced' })).toBe('');
+ expect(buildNoteShareContent({ ...base, viewMode: 'transcript', transcript: '' })).toBe('');
});
});
diff --git a/openwhispr-mobile/src/lib/calendar/meetingContext.ts b/openwhispr-mobile/src/lib/calendar/meetingContext.ts
index 5bdd4d5ba..04a45ad0c 100644
--- a/openwhispr-mobile/src/lib/calendar/meetingContext.ts
+++ b/openwhispr-mobile/src/lib/calendar/meetingContext.ts
@@ -105,7 +105,7 @@ const isRoomLikeParticipant = (participant: CalendarParticipant): boolean => {
return /\b(boardroom|conference room|huddle room|meeting room|room)\b/.test(displayName);
};
-const getHumanParticipants = (participants: CalendarParticipant[]): CalendarParticipant[] =>
+export const getHumanParticipants = (participants: CalendarParticipant[]): CalendarParticipant[] =>
dedupeParticipants(
participants.filter(
(participant) =>
diff --git a/openwhispr-mobile/src/lib/formatNoteRowTime.ts b/openwhispr-mobile/src/lib/formatNoteRowTime.ts
index 8ad6a39ac..e9460f466 100644
--- a/openwhispr-mobile/src/lib/formatNoteRowTime.ts
+++ b/openwhispr-mobile/src/lib/formatNoteRowTime.ts
@@ -7,6 +7,11 @@ function pad2(n: number): string {
return n < 10 ? `0${n}` : String(n);
}
+/** "14:05", the clock time the notes list shows. */
+export function formatClockTime(d: Date): string {
+ return `${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
+}
+
export function formatNoteRowTime(
updatedAt: string | number | Date | null | undefined,
bucket: DateBucketKey,
@@ -15,7 +20,7 @@ export function formatNoteRowTime(
if (isNaN(d.getTime())) return '';
if (bucket === 'today') {
- return `${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
+ return formatClockTime(d);
}
if (bucket === 'yesterday') {
return 'Yesterday';
diff --git a/openwhispr-mobile/src/lib/noteExport.ts b/openwhispr-mobile/src/lib/noteExport.ts
index d5646f247..eb14d023f 100644
--- a/openwhispr-mobile/src/lib/noteExport.ts
+++ b/openwhispr-mobile/src/lib/noteExport.ts
@@ -1,22 +1,26 @@
import * as FileSystem from 'expo-file-system/legacy';
import type { Note } from '@/data';
+import type { NoteBodyView } from '@/lib/notes/noteBodyTabs';
export interface NoteShareContentInput {
- viewMode: 'original' | 'enhanced';
+ viewMode: NoteBodyView;
enhancedContent: string | null;
- usesSegmentTranscript: boolean;
transcript: string;
content: string;
}
-// What the Share menu exports: the enhanced notes when that's the active view,
-// otherwise what the original view shows — the formatted transcript for
-// meeting notes, the note body for plain notes. Never the LLM prompt input.
+// What the Share menu exports: exactly what the active tab shows — the generated notes, the
+// formatted transcript (empty while it is still being made), or the note body. Never the LLM
+// prompt input.
export function buildNoteShareContent(input: NoteShareContentInput): string {
- if (input.viewMode === 'enhanced' && input.enhancedContent) {
- return input.enhancedContent;
+ switch (input.viewMode) {
+ case 'enhanced':
+ return input.enhancedContent ?? '';
+ case 'transcript':
+ return input.transcript;
+ case 'notes':
+ return input.content;
}
- return input.usesSegmentTranscript ? input.transcript : input.content;
}
function sanitizeFilename(title: string): string {
diff --git a/openwhispr-mobile/src/lib/notes/__tests__/chatOverNote.test.ts b/openwhispr-mobile/src/lib/notes/__tests__/chatOverNote.test.ts
new file mode 100644
index 000000000..60964ff49
--- /dev/null
+++ b/openwhispr-mobile/src/lib/notes/__tests__/chatOverNote.test.ts
@@ -0,0 +1,67 @@
+import { boundChatContext, buildNoteChatContext } from '@/lib/notes/chatOverNote';
+
+describe('buildNoteChatContext', () => {
+ it('returns the source text unchanged when there are no generated notes', () => {
+ expect(buildNoteChatContext({ generatedNotes: null, sourceText: ' Raw notes ' })).toBe(
+ 'Raw notes',
+ );
+ });
+
+ it('puts the note ahead of the generated notes', () => {
+ const context = buildNoteChatContext({
+ generatedNotes: '## Action items\n- Ship it',
+ sourceText: 'Meeting transcript:\n[0:00] Speaker 1: Ship it.',
+ });
+
+ expect(context).toBe(
+ 'Note content:\nMeeting transcript:\n[0:00] Speaker 1: Ship it.\n\n' +
+ 'Generated notes:\n## Action items\n- Ship it',
+ );
+ });
+
+ it('still gives context when only generated notes exist', () => {
+ expect(buildNoteChatContext({ generatedNotes: 'Summary', sourceText: ' ' })).toBe(
+ 'Generated notes:\nSummary',
+ );
+ });
+
+ it('keeps the typed notes and the generated notes when a long transcript is truncated', () => {
+ const context = buildNoteChatContext({
+ generatedNotes: 'Decision: launch Friday',
+ sourceText: `Raw notes captured during the meeting:\nCall the vendor\n\n${'x'.repeat(40_000)}`,
+ });
+
+ const { text } = boundChatContext(context);
+ expect(text).toContain('Call the vendor');
+ expect(text).toContain('Decision: launch Friday');
+ });
+
+ it('keeps the typed notes and the start of long generated notes', () => {
+ const context = buildNoteChatContext({
+ generatedNotes: `## Summary\nLaunch Friday\n\n${'y'.repeat(20_000)}`,
+ sourceText: `Raw notes captured during the meeting:\nCall the vendor\n\n${'x'.repeat(20_000)}`,
+ });
+
+ const { text } = boundChatContext(context);
+ expect(text).toContain('Call the vendor');
+ expect(text).toContain('## Summary\nLaunch Friday');
+ });
+
+ it('leaves long generated notes whole when everything fits', () => {
+ const generated = 'y'.repeat(10_000);
+ expect(buildNoteChatContext({ generatedNotes: generated, sourceText: 'Short note' })).toContain(
+ generated,
+ );
+ });
+
+ it('caps the generated notes when their labels are what push the context over the limit', () => {
+ // Exactly 24,000 characters of text, plus the "Note content:" and "Generated notes:" labels.
+ const context = buildNoteChatContext({
+ generatedNotes: `## Summary\n${'y'.repeat(19_989)}`,
+ sourceText: 'x'.repeat(4_000),
+ });
+
+ expect(context).toContain('[...rest of the generated notes omitted...]');
+ expect(boundChatContext(context).truncated).toBe(false);
+ });
+});
diff --git a/openwhispr-mobile/src/lib/notes/__tests__/noteBodyTabs.test.ts b/openwhispr-mobile/src/lib/notes/__tests__/noteBodyTabs.test.ts
new file mode 100644
index 000000000..5ea5d4b09
--- /dev/null
+++ b/openwhispr-mobile/src/lib/notes/__tests__/noteBodyTabs.test.ts
@@ -0,0 +1,113 @@
+import {
+ defaultNoteBodyView,
+ getNoteBodyTabLabel,
+ getNoteBodyTabs,
+ resolveNoteBodyView,
+ type NoteBodyTabInput,
+} from '@/lib/notes/noteBodyTabs';
+
+const tabInput = (overrides: Partial<NoteBodyTabInput> = {}): NoteBodyTabInput => ({
+ usesSegmentTranscript: false,
+ transcriptPending: false,
+ contentIsTranscript: false,
+ hasEnhanced: false,
+ ...overrides,
+});
+
+describe('getNoteBodyTabs', () => {
+ it('offers Transcript and My notes on a transcript note before notes are generated', () => {
+ expect(getNoteBodyTabs(tabInput({ usesSegmentTranscript: true }))).toEqual([
+ 'transcript',
+ 'notes',
+ ]);
+ });
+
+ it('offers Enhanced and My notes once notes are generated, on any note', () => {
+ expect(getNoteBodyTabs(tabInput({ usesSegmentTranscript: true, hasEnhanced: true }))).toEqual([
+ 'enhanced',
+ 'notes',
+ ]);
+ expect(getNoteBodyTabs(tabInput({ hasEnhanced: true }))).toEqual(['enhanced', 'notes']);
+ });
+
+ it('offers only My notes on a plain note without generated notes', () => {
+ expect(getNoteBodyTabs(tabInput())).toEqual(['notes']);
+ });
+
+ it('keeps a Transcript tab for a transcript still in progress or failed, beside My notes', () => {
+ expect(getNoteBodyTabs(tabInput({ transcriptPending: true }))).toEqual(['transcript', 'notes']);
+ expect(getNoteBodyTabs(tabInput({ transcriptPending: true, hasEnhanced: true }))).toEqual([
+ 'enhanced',
+ 'transcript',
+ 'notes',
+ ]);
+ });
+
+ it('never shows an upload body beside its transcript', () => {
+ const upload = { contentIsTranscript: true };
+ expect(getNoteBodyTabs(tabInput({ ...upload, usesSegmentTranscript: true }))).toEqual([
+ 'transcript',
+ ]);
+ expect(
+ getNoteBodyTabs(tabInput({ ...upload, usesSegmentTranscript: true, hasEnhanced: true })),
+ ).toEqual(['enhanced', 'transcript']);
+ expect(getNoteBodyTabs(tabInput({ ...upload, transcriptPending: true }))).toEqual([
+ 'transcript',
+ ]);
+ });
+
+ it('shows an upload without segments as its editable body', () => {
+ expect(getNoteBodyTabs(tabInput({ contentIsTranscript: true }))).toEqual(['notes']);
+ expect(getNoteBodyTabs(tabInput({ contentIsTranscript: true, hasEnhanced: true }))).toEqual([
+ 'enhanced',
+ 'notes',
+ ]);
+ });
+});
+
+describe('getNoteBodyTabLabel', () => {
+ it('labels the tabs', () => {
+ const input = { contentIsTranscript: false };
+ expect(getNoteBodyTabLabel('enhanced', input)).toBe('Enhanced');
+ expect(getNoteBodyTabLabel('transcript', input)).toBe('Transcript');
+ expect(getNoteBodyTabLabel('notes', input)).toBe('My notes');
+ });
+
+ it("calls an upload's body its transcript", () => {
+ expect(getNoteBodyTabLabel('notes', { contentIsTranscript: true })).toBe('Transcript');
+ });
+});
+
+describe('resolveNoteBodyView', () => {
+ const meeting = tabInput({ usesSegmentTranscript: true });
+ const generated = tabInput({ usesSegmentTranscript: true, hasEnhanced: true });
+
+ it('keeps the requested view while its tab exists', () => {
+ expect(resolveNoteBodyView('transcript', meeting)).toBe('transcript');
+ expect(resolveNoteBodyView('notes', generated)).toBe('notes');
+ });
+
+ it('moves from Transcript to Enhanced when generated notes arrive', () => {
+ expect(resolveNoteBodyView('transcript', generated)).toBe('enhanced');
+ });
+
+ it('falls back to the first tab when the requested one is gone', () => {
+ expect(resolveNoteBodyView('enhanced', meeting)).toBe('transcript');
+ expect(resolveNoteBodyView('enhanced', tabInput())).toBe('notes');
+ });
+});
+
+describe('defaultNoteBodyView', () => {
+ it('opens generated notes when they exist', () => {
+ expect(defaultNoteBodyView({ isAudioTranscript: true, hasEnhanced: true })).toBe('enhanced');
+ expect(defaultNoteBodyView({ isAudioTranscript: false, hasEnhanced: true })).toBe('enhanced');
+ });
+
+ it('opens the transcript on an audio note, even before its segments exist', () => {
+ expect(defaultNoteBodyView({ isAudioTranscript: true, hasEnhanced: false })).toBe('transcript');
+ });
+
+ it('opens My notes on a plain note', () => {
+ expect(defaultNoteBodyView({ isAudioTranscript: false, hasEnhanced: false })).toBe('notes');
+ });
+});
diff --git a/openwhispr-mobile/src/lib/notes/__tests__/noteMeta.test.ts b/openwhispr-mobile/src/lib/notes/__tests__/noteMeta.test.ts
new file mode 100644
index 000000000..9ed94955f
--- /dev/null
+++ b/openwhispr-mobile/src/lib/notes/__tests__/noteMeta.test.ts
@@ -0,0 +1,172 @@
+import {
+ attendeeName,
+ formatAttendeeChipLabel,
+ formatNoteMetaDate,
+ markViewer,
+ noteTakenAt,
+ sortAttendees,
+} from '@/lib/notes/noteMeta';
+import type { CalendarParticipant } from '@/data/calendarTypes';
+
+const person = (overrides: Partial<CalendarParticipant> = {}): CalendarParticipant => ({
+ email: null,
+ displayName: null,
+ responseStatus: 'accepted',
+ optional: false,
+ organizer: false,
+ resource: false,
+ self: false,
+ ...overrides,
+});
+
+// SQLite stores created_at as a UTC "YYYY-MM-DD HH:MM:SS" string.
+const toSqlite = (date: Date): string => date.toISOString().replace('T', ' ').slice(0, 19);
+
+describe('formatNoteMetaDate', () => {
+ const now = new Date(2026, 8, 27, 15, 0);
+
+ it('labels a note created today with its time, as the notes list shows it', () => {
+ expect(formatNoteMetaDate(toSqlite(new Date(2026, 8, 27, 9, 27)), now)).toBe('Today 09:27');
+ });
+
+ it('labels a note created yesterday', () => {
+ expect(formatNoteMetaDate(toSqlite(new Date(2026, 8, 26, 14, 5)), now)).toBe('Yesterday 14:05');
+ });
+
+ it('shows month and day for an earlier date this year', () => {
+ const label = formatNoteMetaDate(toSqlite(new Date(2026, 8, 21, 9, 27)), now);
+ expect(label).toMatch(/^Sep 21, /);
+ expect(label).not.toContain('2026');
+ });
+
+ it('adds the year for an earlier year', () => {
+ expect(formatNoteMetaDate(toSqlite(new Date(2025, 8, 21, 9, 27)), now)).toContain('2025');
+ });
+
+ it('returns an empty label when the timestamp is missing or unparsable', () => {
+ expect(formatNoteMetaDate(null, now)).toBe('');
+ expect(formatNoteMetaDate('not a date', now)).toBe('');
+ });
+});
+
+describe('noteTakenAt', () => {
+ it('uses the creation time of a note made or pulled with it', () => {
+ expect(noteTakenAt('2026-06-01 09:00:00', '2026-06-26T10:00:00.000Z')).toEqual(
+ new Date('2026-06-01T09:00:00.000Z'),
+ );
+ });
+
+ it('uses the last edit when the creation time is the later pull time', () => {
+ expect(noteTakenAt('2026-09-27 08:00:00', '2026-06-26T10:00:00.000Z')).toEqual(
+ new Date('2026-06-26T10:00:00.000Z'),
+ );
+ });
+
+ it('uses whichever timestamp is readable', () => {
+ expect(noteTakenAt(null, '2026-06-26T10:00:00.000Z')).toEqual(
+ new Date('2026-06-26T10:00:00.000Z'),
+ );
+ expect(noteTakenAt('2026-06-01 09:00:00', null)).toEqual(new Date('2026-06-01T09:00:00.000Z'));
+ expect(noteTakenAt(null, null)).toBeNull();
+ });
+});
+
+describe('sortAttendees', () => {
+ it('drops rooms and puts the organizer first', () => {
+ const sam = person({ displayName: 'Sam Lee' });
+ const room = person({ displayName: 'Board Room', resource: true });
+ const ana = person({ displayName: 'Ana Ruiz', organizer: true });
+ expect(sortAttendees([sam, room, ana])).toEqual([ana, sam]);
+ });
+
+ it('drops people who declined', () => {
+ const sam = person({ displayName: 'Sam Lee' });
+ const kim = person({ displayName: 'Kim Park', responseStatus: 'declined' });
+ expect(sortAttendees([sam, kim])).toEqual([sam]);
+ expect(formatAttendeeChipLabel([sam, kim])).toBe('Sam');
+ });
+
+ it('drops rooms known only by their address or name, and repeated people', () => {
+ const sam = person({ displayName: 'Sam Lee', email: '[email protected]' });
+ const roomByEmail = person({ email: '[email protected]' });
+ const roomByName = person({ displayName: 'Huddle Room 2' });
+ const samAgain = person({ displayName: 'Sam', email: '[email protected]' });
+ expect(sortAttendees([sam, roomByEmail, roomByName, samAgain])).toEqual([sam]);
+ });
+});
+
+describe('markViewer', () => {
+ const creator = person({ displayName: 'Sam Lee', email: '[email protected]', self: true });
+ const viewer = person({ displayName: 'Ana Ruiz', email: '[email protected]' });
+
+ it('keeps the calendar’s own row as you on a note you created', () => {
+ expect(
+ markViewer([creator, viewer], { creatorIsViewer: true, viewerEmail: '[email protected]' }),
+ ).toEqual([creator, viewer]);
+ });
+
+ it('marks you, not the creator, on a teammate’s note', () => {
+ const marked = markViewer([creator, viewer], {
+ creatorIsViewer: false,
+ viewerEmail: '[email protected]',
+ });
+ expect(marked.map((participant) => participant.self)).toEqual([false, true]);
+ expect(formatAttendeeChipLabel(marked)).toBe('Sam +1');
+ expect(attendeeName(marked[0])).toBe('Sam Lee');
+ });
+
+ it('marks nobody on a teammate’s note you weren’t invited to', () => {
+ const marked = markViewer([creator, viewer], { creatorIsViewer: false, viewerEmail: null });
+ expect(marked.some((participant) => participant.self)).toBe(false);
+ });
+});
+
+describe('attendeeName', () => {
+ it('prefers the display name, then the email, then Guest', () => {
+ expect(attendeeName(person({ displayName: ' Sam Lee ', email: '[email protected]' }))).toBe('Sam Lee');
+ expect(attendeeName(person({ email: '[email protected]' }))).toBe('[email protected]');
+ expect(attendeeName(person())).toBe('Guest');
+ });
+
+ it('calls your own row You', () => {
+ expect(attendeeName(person({ displayName: 'Me Myself', self: true }))).toBe('You');
+ });
+});
+
+describe('formatAttendeeChipLabel', () => {
+ it('names the first attendee who is not you, by first name, with a count of the rest', () => {
+ const label = formatAttendeeChipLabel([
+ person({ displayName: 'Me', self: true }),
+ person({ displayName: 'Sam Lee' }),
+ person({ displayName: 'Ana Ruiz' }),
+ person({ email: '[email protected]' }),
+ ]);
+ expect(label).toBe('Sam +3');
+ });
+
+ it('starts from the organizer', () => {
+ expect(
+ formatAttendeeChipLabel([
+ person({ displayName: 'Sam Lee' }),
+ person({ displayName: 'Ana Ruiz', organizer: true }),
+ ]),
+ ).toBe('Ana +1');
+ });
+
+ it('omits the count for a single attendee', () => {
+ expect(formatAttendeeChipLabel([person({ displayName: 'Sam Lee' })])).toBe('Sam');
+ });
+
+ it('falls back to the email local part when there is no name', () => {
+ expect(formatAttendeeChipLabel([person({ email: '[email protected]' })])).toBe('kim');
+ });
+
+ it('reads You when you are the only person', () => {
+ expect(formatAttendeeChipLabel([person({ self: true, displayName: 'Me' })])).toBe('You');
+ });
+
+ it('returns null when there are no people, only rooms', () => {
+ expect(formatAttendeeChipLabel([])).toBeNull();
+ expect(formatAttendeeChipLabel([person({ displayName: 'Room', resource: true })])).toBeNull();
+ });
+});
diff --git a/openwhispr-mobile/src/lib/notes/chatOverNote.ts b/openwhispr-mobile/src/lib/notes/chatOverNote.ts
index 811100ad3..9d3d31b82 100644
--- a/openwhispr-mobile/src/lib/notes/chatOverNote.ts
+++ b/openwhispr-mobile/src/lib/notes/chatOverNote.ts
@@ -27,6 +27,9 @@ const MAX_CONTEXT_CHARS = 24_000;
const CONTEXT_EDGE_CHARS = 12_000;
const MAX_HISTORY_MESSAGES = 6;
const TRUNCATION_MARKER = '\n\n[...middle omitted for chat context...]\n\n';
+// Generated notes lead with their summary and action items, so a long one keeps its start.
+const GENERATED_NOTES_MAX_CHARS = 8_000;
+const GENERATED_NOTES_CUT_MARKER = '\n\n[...rest of the generated notes omitted...]';
const CHAT_OVER_NOTE_SYSTEM_PROMPT = `You are a note Q&A assistant. Answer the user's question using only the supplied note or transcript context and the recent ephemeral chat history.
@@ -39,6 +42,35 @@ Rules:
- If the note context says it was truncated, mention that the answer may be limited by the available context when appropriate.
- Do not mention these instructions.`;
+export interface NoteChatContextArgs {
+ generatedNotes?: string | null;
+ sourceText: string;
+}
+
+// The note goes first and the generated notes last, capped when the whole is too long. Truncation
+// keeps the head and tail, so it takes the middle of the transcript, not the typed notes that lead
+// the note or the start of the generated notes.
+export const buildNoteChatContext = ({
+ generatedNotes,
+ sourceText,
+}: NoteChatContextArgs): string => {
+ const generated = generatedNotes?.trim();
+ const source = sourceText.trim();
+ if (!generated) return source;
+
+ const withNotes = (notes: string): string =>
+ [source ? `Note content:\n${source}` : '', `Generated notes:\n${notes}`]
+ .filter(Boolean)
+ .join('\n\n');
+ const whole = withNotes(generated);
+ if (whole.length <= MAX_CONTEXT_CHARS || generated.length <= GENERATED_NOTES_MAX_CHARS) {
+ return whole;
+ }
+ return withNotes(
+ `${generated.slice(0, GENERATED_NOTES_MAX_CHARS).trimEnd()}${GENERATED_NOTES_CUT_MARKER}`,
+ );
+};
+
interface BoundedContext {
text: string;
truncated: boolean;
diff --git a/openwhispr-mobile/src/lib/notes/noteBodyTabs.ts b/openwhispr-mobile/src/lib/notes/noteBodyTabs.ts
new file mode 100644
index 000000000..af0fb65cc
--- /dev/null
+++ b/openwhispr-mobile/src/lib/notes/noteBodyTabs.ts
@@ -0,0 +1,72 @@
+export type NoteBodyView = 'enhanced' | 'transcript' | 'notes';
+
+export interface NoteBodyTabInput {
+ usesSegmentTranscript: boolean;
+ /** The transcript is still being made or failed, so its tab shows that status. */
+ transcriptPending: boolean;
+ /** Uploaded audio stores its flat transcript as the note body; it has no notes of its own. */
+ contentIsTranscript: boolean;
+ hasEnhanced: boolean;
+}
+
+const NOTE_BODY_TAB_LABELS: Record<NoteBodyView, string> = {
+ enhanced: 'Enhanced',
+ transcript: 'Transcript',
+ notes: 'My notes',
+};
+
+/**
+ * Once notes are generated the transcript moves to ⋯ → View Transcript. A transcript status and
+ * an upload's transcript have nowhere else to go, so they keep their tab.
+ */
+export function getNoteBodyTabs({
+ usesSegmentTranscript,
+ transcriptPending,
+ contentIsTranscript,
+ hasEnhanced,
+}: NoteBodyTabInput): NoteBodyView[] {
+ const tabs: NoteBodyView[] = [];
+ if (hasEnhanced) tabs.push('enhanced');
+ const showTranscript =
+ transcriptPending || (usesSegmentTranscript && (!hasEnhanced || contentIsTranscript));
+ if (showTranscript) tabs.push('transcript');
+ // An upload's body only duplicates its transcript, so it shows only when there is no other.
+ if (!(contentIsTranscript && showTranscript)) tabs.push('notes');
+ return tabs;
+}
+
+/** An upload without segments shows its transcript as editable text under the Transcript name. */
+export function getNoteBodyTabLabel(
+ tab: NoteBodyView,
+ { contentIsTranscript }: Pick<NoteBodyTabInput, 'contentIsTranscript'>,
+): string {
+ return tab === 'notes' && contentIsTranscript ? 'Transcript' : NOTE_BODY_TAB_LABELS[tab];
+}
+
+/**
+ * The view to show for the user's last pick. A pick whose tab disappeared (Transcript once notes
+ * are generated) lands on the first tab; My notes stays while it exists, so typing is never
+ * interrupted.
+ */
+export function resolveNoteBodyView(
+ requested: NoteBodyView,
+ input: NoteBodyTabInput,
+): NoteBodyView {
+ const tabs = getNoteBodyTabs(input);
+ return tabs.includes(requested) ? requested : tabs[0];
+}
+
+/**
+ * The pick a note opens with. Audio notes ask for the transcript even before their segments
+ * exist, so the view follows the transcript and then the generated notes as they arrive.
+ */
+export function defaultNoteBodyView({
+ isAudioTranscript,
+ hasEnhanced,
+}: {
+ isAudioTranscript: boolean;
+ hasEnhanced: boolean;
+}): NoteBodyView {
+ if (hasEnhanced) return 'enhanced';
+ return isAudioTranscript ? 'transcript' : 'notes';
+}
diff --git a/openwhispr-mobile/src/lib/notes/noteMeta.ts b/openwhispr-mobile/src/lib/notes/noteMeta.ts
new file mode 100644
index 000000000..9851d9ad2
--- /dev/null
+++ b/openwhispr-mobile/src/lib/notes/noteMeta.ts
@@ -0,0 +1,97 @@
+import type { CalendarParticipant } from '@/data/calendarTypes';
+import { getHumanParticipants } from '@/lib/calendar/meetingContext';
+import { formatClockTime } from '@/lib/formatNoteRowTime';
+import { tryParseNoteTimestamp } from '@/lib/parseNoteTimestamp';
+
+export const isSameDay = (a: Date, b: Date): boolean =>
+ a.getFullYear() === b.getFullYear() &&
+ a.getMonth() === b.getMonth() &&
+ a.getDate() === b.getDate();
+
+/**
+ * When the note was taken. Notes pulled before `created_at` synced were stamped with the pull
+ * time, which is later than their last edit on the server, so the earlier of the two is the
+ * closer answer. Pass the server's last edit: a local edit would move the date to the pull time.
+ */
+export function noteTakenAt(
+ createdAt: string | null | undefined,
+ lastEditedAt: string | null | undefined,
+): Date | null {
+ const created = tryParseNoteTimestamp(createdAt);
+ const lastEdited = tryParseNoteTimestamp(lastEditedAt);
+ if (!created || !lastEdited) return created ?? lastEdited;
+ return created < lastEdited ? created : lastEdited;
+}
+
+/**
+ * "Today 09:27", "Yesterday 14:05", "Sep 21, 09:27", or "Sep 21, 2025, 09:27", with the time
+ * shown as the notes list shows it.
+ */
+export function formatNoteMetaDate(timestamp: string | Date | null | undefined, now: Date): string {
+ const date = tryParseNoteTimestamp(timestamp);
+ if (!date) return '';
+
+ const time = formatClockTime(date);
+ if (isSameDay(date, now)) return `Today ${time}`;
+
+ const yesterday = new Date(now);
+ yesterday.setDate(now.getDate() - 1);
+ if (isSameDay(date, yesterday)) return `Yesterday ${time}`;
+
+ const day = date.toLocaleDateString(
+ undefined,
+ date.getFullYear() === now.getFullYear()
+ ? { month: 'short', day: 'numeric' }
+ : { month: 'short', day: 'numeric', year: 'numeric' },
+ );
+ return `${day}, ${time}`;
+}
+
+/**
+ * People who haven't declined, without rooms (flagged, or known by their address or name) or
+ * repeats, organizer first, otherwise in calendar order.
+ */
+export function sortAttendees(participants: CalendarParticipant[]): CalendarParticipant[] {
+ const people = getHumanParticipants(participants);
+ return [
+ ...people.filter((participant) => participant.organizer),
+ ...people.filter((participant) => !participant.organizer),
+ ];
+}
+
+/**
+ * `self` comes from the calendar of whoever created the note, so on a teammate's note it marks
+ * them. There, you are whoever has your address.
+ */
+export function markViewer(
+ participants: CalendarParticipant[],
+ { creatorIsViewer, viewerEmail }: { creatorIsViewer: boolean; viewerEmail: string | null },
+): CalendarParticipant[] {
+ if (creatorIsViewer) return participants;
+ const email = viewerEmail?.toLowerCase();
+ return participants.map((participant) => ({
+ ...participant,
+ self: !!email && participant.email?.toLowerCase() === email,
+ }));
+}
+
+export function attendeeName(participant: CalendarParticipant): string {
+ if (participant.self) return 'You';
+ return participant.displayName?.trim() || participant.email || 'Guest';
+}
+
+const attendeeFirstName = (participant: CalendarParticipant): string =>
+ participant.displayName?.trim().split(/\s+/)[0] || participant.email?.split('@')[0] || 'Guest';
+
+/** "Sam +3": the first attendee who isn't you, plus everyone else. Null when nobody attends. */
+export function formatAttendeeChipLabel(participants: CalendarParticipant[]): string | null {
+ const people = sortAttendees(participants);
+ if (people.length === 0) return null;
+
+ const first = people.find((participant) => !participant.self);
+ if (!first) return 'You';
+
+ const others = people.length - 1;
+ const name = attendeeFirstName(first);
+ return others > 0 ? `${name} +${others}` : name;
+}
diff --git a/openwhispr-mobile/src/screens/MeetingRecordScreen.tsx b/openwhispr-mobile/src/screens/MeetingRecordScreen.tsx
index ce4102c57..d6602391a 100644
--- a/openwhispr-mobile/src/screens/MeetingRecordScreen.tsx
+++ b/openwhispr-mobile/src/screens/MeetingRecordScreen.tsx
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import type React from 'react';
-import { Alert, KeyboardAvoidingView, Platform, TextInput, View } from 'react-native';
+import { Alert, TextInput, View } from 'react-native';
import { router } from 'expo-router';
import { useHeaderHeight } from '@react-navigation/elements';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
@@ -15,6 +15,7 @@ import { calendarRepository } from '@/data/calendarRepository';
import type { Note } from '@/data/types';
import type { GoogleCalendarEvent } from '@/data/calendarTypes';
import { useAudioRecording } from '@/hooks/useAudioRecording';
+import { useKeyboardHeight } from '@/hooks/useKeyboardHeight';
import { buildCalendarMeetingContext } from '@/lib/calendar/meetingContext';
import { getMeetingCalendarEventSuggestions } from '@/lib/calendar/meetingSuggestions';
import { getPreferredTranscriptionLanguage } from '@/lib/transcriptionLanguage';
@@ -59,6 +60,8 @@ export const MeetingRecordScreen = (): React.JSX.Element => {
const recordingStartedAtRef = useRef<number | null>(null);
const headerHeight = useHeaderHeight();
const insets = useSafeAreaInsets();
+ // Only the recording phase has a notes field to keep above the keyboard.
+ const keyboardHeight = useKeyboardHeight(phase === 'recording');
const googleCalendarAccounts = useGoogleCalendarStore((s) => s.accounts);
const loadGoogleCalendars = useGoogleCalendarStore((s) => s.load);
const createMeetingNote = useNotesStore((s) => s.createMeetingNote);
@@ -428,14 +431,11 @@ export const MeetingRecordScreen = (): React.JSX.Element => {
if (phase === 'recording') {
const countLabel =
count != null ? `${count} ${count === 1 ? 'person' : 'people'}` : 'Auto-detecting';
- const footerBottomPadding = Math.max(insets.bottom + 32, 56);
+ // The view fills the screen, so the keyboard covers the home-indicator inset too.
+ const footerBottomPadding =
+ keyboardHeight > 0 ? keyboardHeight + 12 : Math.max(insets.bottom + 32, 56);
return (
- <KeyboardAvoidingView
- className="flex-1 bg-systemBackground px-6"
- style={{ paddingTop: headerHeight }}
- behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
- keyboardVerticalOffset={headerHeight}
- >
+ <View className="flex-1 bg-systemBackground px-6" style={{ paddingTop: headerHeight }}>
<View className="items-center pb-2 pt-4">
<View className="mb-3 flex-row items-center gap-2">
<View className="h-2 w-2 rounded-full bg-systemRed" />
@@ -493,7 +493,7 @@ export const MeetingRecordScreen = (): React.JSX.Element => {
Stop
</Button>
</View>
- </KeyboardAvoidingView>
+ </View>
);
}
diff --git a/openwhispr-mobile/src/screens/NoteEditorScreen.tsx b/openwhispr-mobile/src/screens/NoteEditorScreen.tsx
index 6b96f2e73..43af5c0fd 100644
--- a/openwhispr-mobile/src/screens/NoteEditorScreen.tsx
+++ b/openwhispr-mobile/src/screens/NoteEditorScreen.tsx
@@ -26,13 +26,31 @@ import { useActionProcessing } from '@/hooks/useActionProcessing';
import { useAudioRecording } from '@/hooks/useAudioRecording';
import { useSuperwallGate } from '@/hooks/useSuperwallGate';
import { useUsageLimitRecovery } from '@/hooks/useUsageLimitRecovery';
-import { MarkdownRenderer } from '@/components/notes/MarkdownRenderer';
+import { EditableMarkdown } from '@/components/notes/EditableMarkdown';
+import {
+ defaultNoteBodyView,
+ getNoteBodyTabLabel,
+ getNoteBodyTabs,
+ resolveNoteBodyView,
+ type NoteBodyView,
+} from '@/lib/notes/noteBodyTabs';
import { NoteShareSheet } from '@/components/notes/NoteShareSheet';
import { NoteActionsMenu } from '@/components/notes/NoteActionsMenu';
import { ConflictBanner } from '@/components/notes/ConflictBanner';
import { NoteChatSheet } from '@/components/notes/NoteChatSheet';
import { isDictationAgentEnabled } from '@/lib/dictationAgent';
import { SpeakerTranscript } from '@/components/notes/SpeakerTranscript';
+import { TranscriptSheet } from '@/components/notes/TranscriptSheet';
+import { NoteMetaRow } from '@/components/notes/NoteMetaRow';
+import { AttendeesSheet } from '@/components/notes/AttendeesSheet';
+import { MoveToFolderSheet } from '@/components/notes/MoveToFolderSheet';
+import { useMoveNote } from '@/hooks/useMoveNote';
+import {
+ formatAttendeeChipLabel,
+ formatNoteMetaDate,
+ markViewer,
+ noteTakenAt,
+} from '@/lib/notes/noteMeta';
import { SpeakerRenameSheet } from '@/components/notes/SpeakerRenameSheet';
import { SpeakerMergeSheet } from '@/components/notes/SpeakerMergeSheet';
import { VoiceprintSuggestionSheet } from '@/components/notes/VoiceprintSuggestionSheet';
@@ -45,7 +63,6 @@ import { TabScreenHeader } from '@/components/ui/TabScreenHeader';
import { buildNoteShareContent, exportNote } from '@/lib/noteExport';
import { AppFont } from '@/lib/fonts';
import { makeContentHash, safeHaptics } from '@/lib/utils';
-import { parseNoteTimestamp } from '@/lib/parseNoteTimestamp';
import { isManagedMeetingAudioUri } from '@/lib/transcriptAudio';
import { BRAND } from '@/config/colors';
import {
@@ -58,6 +75,7 @@ import { promptLocalModelFallback } from '@/lib/privateMode';
import {
getLocalReasoningReadiness,
getLocalReasoningUnavailableMessage,
+ isLocalContextLimitError,
isLocalReasoningRequired,
shouldUseLocalReasoning,
} from '@/lib/localReasoning';
@@ -76,7 +94,7 @@ import { SUPERWALL_PLACEMENTS } from '@/lib/superwall';
import { useKeyboardHeight } from '@/hooks/useKeyboardHeight';
import type { Note } from '@/data/types';
import type { ReasoningRoutingOptions } from '@/types';
-import type { ChatOverNoteMessage } from '@/lib/notes/chatOverNote';
+import { buildNoteChatContext, type ChatOverNoteMessage } from '@/lib/notes/chatOverNote';
import { getNoteChatSuggestions } from '@/lib/notes/noteChatSuggestions';
import {
formatTranscriptForExport,
@@ -84,7 +102,6 @@ import {
groupTranscriptSegments,
type TranscriptBlock,
} from '@/lib/diarization/transcriptDisplay';
-type ViewMode = 'original' | 'enhanced';
const NOTE_EDITOR_BOTTOM_PADDING = 180;
const NOTE_EDITOR_KEYBOARD_BOTTOM_PADDING = 8;
@@ -122,6 +139,10 @@ export default function NoteEditorScreen() {
const getConflictedNote = useNotesStore((s) => s.getConflictedNote);
const resolveConflictKeepMine = useNotesStore((s) => s.resolveConflictKeepMine);
const resolveConflictUseServer = useNotesStore((s) => s.resolveConflictUseServer);
+ const privateFolders = useNotesStore((s) => s.folders);
+ const spaceFolders = useNotesStore((s) => s.spaceFolders);
+ const spaces = useNotesStore((s) => s.spaces);
+ const getSpaceFolders = useNotesStore((s) => s.getSpaceFolders);
const note = useMemo<Note | null>(() => {
if (Number.isNaN(noteId)) return null;
return notes.find((n) => n.id === noteId) ?? getNoteById(noteId);
@@ -155,7 +176,13 @@ export default function NoteEditorScreen() {
const [title, setTitle] = useState(note?.title ?? '');
const [content, setContent] = useState(note?.content ?? '');
- const [viewMode, setViewMode] = useState<ViewMode>('original');
+ // The user's last tab pick; resolveNoteBodyView maps it onto the tabs this note has now.
+ const [viewMode, setViewMode] = useState<NoteBodyView>(() =>
+ defaultNoteBodyView({
+ isAudioTranscript: isAudioTranscriptNote(note),
+ hasEnhanced: !!note?.enhancedContent,
+ }),
+ );
const [selection, setSelection] = useState<{ start: number; end: number }>({
start: (note?.content ?? '').length,
end: (note?.content ?? '').length,
@@ -165,6 +192,11 @@ export default function NoteEditorScreen() {
const [mergeSheetVisible, setMergeSheetVisible] = useState(false);
const [suggestionSheetVisible, setSuggestionSheetVisible] = useState(false);
const [chatVisible, setChatVisible] = useState(false);
+ const [transcriptSheetVisible, setTranscriptSheetVisible] = useState(false);
+ const [attendeesVisible, setAttendeesVisible] = useState(false);
+ const [enhancedEditing, setEnhancedEditing] = useState(false);
+ // Bumped to remount the generated-notes editor when its draft must be thrown away.
+ const [enhancedEditorRevision, setEnhancedEditorRevision] = useState(0);
const [shareVisible, setShareVisible] = useState(false);
const [chatMessages, setChatMessages] = useState<ChatOverNoteMessage[]>([]);
const [chatDraft, setChatDraft] = useState('');
@@ -208,11 +240,23 @@ export default function NoteEditorScreen() {
originalTitleRef.current = note.title;
originalContentRef.current = note.content;
learnedBaselineRef.current = note.content;
- setViewMode(note.enhancedContent ? 'enhanced' : 'original');
+ setViewMode(
+ defaultNoteBodyView({
+ isAudioTranscript: isAudioTranscriptNote(note),
+ hasEnhanced: !!note.enhancedContent,
+ }),
+ );
}
chatAbortRef.current?.abort();
chatAbortRef.current = null;
setChatVisible(false);
+ setTranscriptSheetVisible(false);
+ setRenameSheetVisible(false);
+ setMergeSheetVisible(false);
+ setSuggestionSheetVisible(false);
+ setActiveSpeakerId(null);
+ setAttendeesVisible(false);
+ setEnhancedEditing(false);
setShareVisible(false);
setChatMessages([]);
setChatDraft('');
@@ -230,6 +274,27 @@ export default function NoteEditorScreen() {
[],
);
+ // Until you type, the title and My notes follow the saved note, so a change pulled while the note
+ // is open (an edit on desktop) isn't saved over by the text it replaced.
+ useEffect(() => {
+ if (!note) return;
+ // The refs are set here too: a save that runs before the next render reads them.
+ if (titleRef.current === originalTitleRef.current && note.title !== titleRef.current) {
+ setTitle(note.title);
+ titleRef.current = note.title;
+ originalTitleRef.current = note.title;
+ }
+ if (contentRef.current === originalContentRef.current && note.content !== contentRef.current) {
+ setContent(note.content);
+ const end = note.content.length;
+ setSelection({ start: end, end });
+ contentRef.current = note.content;
+ originalContentRef.current = note.content;
+ learnedBaselineRef.current = note.content;
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [note?.title, note?.content]);
+
const isAudioTranscript = isAudioTranscriptNote(note);
const transcriptStatus = note?.transcriptionStatus ?? 'idle';
// transcriptRevision is an intentional cache-bust dep: it bumps on local speaker/segment writes
@@ -259,6 +324,41 @@ export default function NoteEditorScreen() {
() => parseCalendarParticipants(note?.participants ?? null) ?? [],
[note?.participants],
);
+ const noteSpace = spaces.find((space) => space.id === note?.spaceId);
+ // A Space missing from the list (access just revoked, or not synced yet) has no folders to offer,
+ // and its notes must never be moved into private folders.
+ const isSpaceUnknown = note?.spaceId != null && !noteSpace;
+ const scopeSpaceId = noteSpace?.kind === 'team' ? noteSpace.id : null;
+ const targetFolders = useMemo(
+ () =>
+ isSpaceUnknown ? [] : scopeSpaceId != null ? getSpaceFolders(scopeSpaceId) : privateFolders,
+ // getSpaceFolders reads the repository, so the store's folder lists stand in as the signal to
+ // re-read: every folder reload (create, rename, move, sync) replaces them.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [getSpaceFolders, isSpaceUnknown, privateFolders, scopeSpaceId, spaceFolders],
+ );
+ const folderName = targetFolders.find((folder) => folder.id === note?.folderId)?.name ?? null;
+ const move = useMoveNote({
+ scopeSpaceId,
+ targetFolders,
+ excludeFolderId: note?.folderId ?? null,
+ });
+ const closeMove = move.close;
+ // A picker left open would move a note it no longer shows, or a team note as a personal one.
+ useEffect(() => {
+ closeMove();
+ }, [closeMove, noteId, isSpaceUnknown]);
+ // The participants' `self` comes from the calendar of whoever created the note. Only the team
+ // sync records an owner, so a note without one is yours, even when its Space is unknown here.
+ const attendees = useMemo(
+ () =>
+ markViewer(calendarParticipants, {
+ creatorIsViewer: !note?.ownerUserId || note.ownerUserId === user?.id,
+ viewerEmail: user?.email ?? null,
+ }),
+ [calendarParticipants, note?.ownerUserId, user?.email, user?.id],
+ );
+ const attendeeLabel = formatAttendeeChipLabel(attendees);
const meetingNotesContext = useMemo(
() =>
note?.calendarEventId
@@ -285,11 +385,21 @@ export default function NoteEditorScreen() {
: content;
const actionInputRef = useRef(actionInputText);
actionInputRef.current = actionInputText;
+ const chatContextText = buildNoteChatContext({
+ generatedNotes: note?.enhancedContent,
+ sourceText: actionInputText,
+ });
+ const chatContextRef = useRef(chatContextText);
+ chatContextRef.current = chatContextText;
const generatedMeetingInputRef = useRef(generatedMeetingInputText);
generatedMeetingInputRef.current = generatedMeetingInputText;
const lastEnhancementInputHashRef = useRef('');
const usesSegmentTranscriptRef = useRef(usesSegmentTranscript);
usesSegmentTranscriptRef.current = usesSegmentTranscript;
+ // Desktop stores an uploaded file's flat transcript as the note body.
+ const contentIsTranscript = note?.noteType === 'upload';
+ // Notes typed beside a recording, never the transcript itself.
+ const hasTypedMeetingNotes = isAudioTranscript && !contentIsTranscript;
const activeSpeaker =
activeSpeakerId == null
? null
@@ -313,6 +423,21 @@ export default function NoteEditorScreen() {
const shouldRenderPlainEditor =
!isAudioTranscript ||
(!hasTranscriptSegments && (transcriptStatus === 'idle' || transcriptStatus === 'done'));
+ const shouldRenderPlainEditorRef = useRef(shouldRenderPlainEditor);
+ shouldRenderPlainEditorRef.current = shouldRenderPlainEditor;
+ const transcriptPending = shouldShowTranscriptStatus || shouldShowTranscriptFailed;
+ const hasEnhanced = !!note?.enhancedContent;
+ // An open editor keeps its tab, so clearing the notes to rewrite them doesn't close it.
+ const hasEnhancedTab = hasEnhanced || enhancedEditing;
+ const bodyTabInput = useMemo(
+ () => ({
+ usesSegmentTranscript,
+ transcriptPending,
+ contentIsTranscript,
+ hasEnhanced: hasEnhancedTab,
+ }),
+ [contentIsTranscript, hasEnhancedTab, transcriptPending, usesSegmentTranscript],
+ );
const requiresCloudConfirmation = note?.isPrivate === 1 || activeMode === 'private';
const handleKeepMine = useCallback(() => {
@@ -320,24 +445,6 @@ export default function NoteEditorScreen() {
resolveConflictKeepMine(noteId);
}, [noteId, resolveConflictKeepMine]);
- const handleUseServerCopy = useCallback(() => {
- safeHaptics('selection');
- resolveConflictUseServer(noteId);
- // The editor's title/content state is a local draft, not derived straight from `note` on
- // every render — refresh it explicitly now that the repository holds the server's copy.
- const refreshed = getNoteById(noteId);
- if (refreshed) {
- setTitle(refreshed.title);
- setContent(refreshed.content);
- const end = refreshed.content.length;
- setSelection({ start: end, end });
- originalTitleRef.current = refreshed.title;
- originalContentRef.current = refreshed.content;
- learnedBaselineRef.current = refreshed.content;
- setViewMode(refreshed.enhancedContent ? 'enhanced' : 'original');
- }
- }, [noteId, resolveConflictUseServer, getNoteById]);
-
const maybeLearnCorrections = useCallback(
(newContent: string) => {
if (!autoLearnEnabledRef.current) return;
@@ -356,8 +463,7 @@ export default function NoteEditorScreen() {
if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current);
saveTimeoutRef.current = null;
const titleChanged = titleRef.current !== originalTitleRef.current;
- const contentChanged =
- !usesSegmentTranscriptRef.current && contentRef.current !== originalContentRef.current;
+ const contentChanged = contentRef.current !== originalContentRef.current;
if (!titleChanged && !contentChanged) return;
updateNote(noteId, {
...(titleChanged ? { title: titleRef.current } : {}),
@@ -366,7 +472,9 @@ export default function NoteEditorScreen() {
originalTitleRef.current = titleRef.current;
if (contentChanged) {
originalContentRef.current = contentRef.current;
- maybeLearnCorrections(contentRef.current);
+ // Only notes that can be dictated into teach the dictionary; edits to notes typed beside a
+ // transcript aren't transcription corrections.
+ if (shouldRenderPlainEditorRef.current) maybeLearnCorrections(contentRef.current);
}
}, [noteId, updateNote, maybeLearnCorrections]);
@@ -377,6 +485,76 @@ export default function NoteEditorScreen() {
useEffect(() => flushDraft, [flushDraft]);
+ // Edits to the generated notes save on their own debounce. The pending edit carries its note
+ // id, so a flush that runs after switching notes still writes to the note that was edited.
+ const pendingEnhancedRef = useRef<{ noteId: number; text: string } | null>(null);
+ const enhancedSaveTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ const flushEnhancedSave = useCallback(() => {
+ if (enhancedSaveTimeoutRef.current) clearTimeout(enhancedSaveTimeoutRef.current);
+ enhancedSaveTimeoutRef.current = null;
+ const pending = pendingEnhancedRef.current;
+ if (!pending) return;
+ pendingEnhancedRef.current = null;
+ updateNote(pending.noteId, { enhancedContent: pending.text });
+ }, [updateNote]);
+ const flushEnhancedSaveRef = useRef(flushEnhancedSave);
+ flushEnhancedSaveRef.current = flushEnhancedSave;
+
+ const discardEnhancedSave = useCallback(() => {
+ if (enhancedSaveTimeoutRef.current) clearTimeout(enhancedSaveTimeoutRef.current);
+ enhancedSaveTimeoutRef.current = null;
+ pendingEnhancedRef.current = null;
+ }, []);
+
+ const handleEnhancedChange = useCallback(
+ (text: string) => {
+ pendingEnhancedRef.current = { noteId, text };
+ if (enhancedSaveTimeoutRef.current) clearTimeout(enhancedSaveTimeoutRef.current);
+ enhancedSaveTimeoutRef.current = setTimeout(flushEnhancedSave, 800);
+ },
+ [flushEnhancedSave, noteId],
+ );
+
+ const handleEnhancedEditingChange = useCallback(
+ (editing: boolean) => {
+ setEnhancedEditing(editing);
+ if (!editing) flushEnhancedSave();
+ },
+ [flushEnhancedSave],
+ );
+
+ const handleUseServerCopy = useCallback(() => {
+ safeHaptics('selection');
+ // Unsaved local edits would land on top of the server copy the user just chose.
+ discardEnhancedSave();
+ if (saveTimeoutRef.current) clearTimeout(saveTimeoutRef.current);
+ saveTimeoutRef.current = null;
+ setEnhancedEditorRevision((revision) => revision + 1);
+ resolveConflictUseServer(noteId);
+ // The editor's title/content state is a local draft, not derived straight from `note` on
+ // every render — refresh it explicitly now that the repository holds the server's copy.
+ const refreshed = getNoteById(noteId);
+ if (refreshed) {
+ setTitle(refreshed.title);
+ setContent(refreshed.content);
+ const end = refreshed.content.length;
+ setSelection({ start: end, end });
+ originalTitleRef.current = refreshed.title;
+ originalContentRef.current = refreshed.content;
+ learnedBaselineRef.current = refreshed.content;
+ setViewMode(
+ defaultNoteBodyView({
+ isAudioTranscript: isAudioTranscriptNote(refreshed),
+ hasEnhanced: !!refreshed.enhancedContent,
+ }),
+ );
+ }
+ }, [discardEnhancedSave, noteId, resolveConflictUseServer, getNoteById]);
+
+ // Leaving the note flushes an unfinished edit to the generated notes; it carries its own id.
+ useEffect(() => () => flushEnhancedSaveRef.current(), [noteId]);
+
const handleTitleChange = useCallback(
(text: string) => {
setTitle(text);
@@ -388,12 +566,11 @@ export default function NoteEditorScreen() {
const handleContentChange = useCallback(
(text: string) => {
- if (usesSegmentTranscript) return;
setContent(text);
contentRef.current = text;
debouncedSave();
},
- [debouncedSave, usesSegmentTranscript],
+ [debouncedSave],
);
const handleEnhanceSuccess = useCallback(
@@ -502,13 +679,14 @@ export default function NoteEditorScreen() {
const handleExport = useCallback(
(format: 'md' | 'txt'): void => {
safeHaptics('light');
+ // Export the generated notes as edited, not as last saved.
+ flushEnhancedSave();
exportNote(
{
title: titleRef.current || 'Untitled',
content: buildNoteShareContent({
- viewMode,
- enhancedContent: note?.enhancedContent ?? null,
- usesSegmentTranscript,
+ viewMode: resolveNoteBodyView(viewMode, bodyTabInput),
+ enhancedContent: getNoteById(noteId)?.enhancedContent ?? null,
transcript: formatTranscriptForExport({ blocks: transcriptBlocks }),
content: contentRef.current,
}),
@@ -516,29 +694,47 @@ export default function NoteEditorScreen() {
format,
).catch(() => Alert.alert('Export failed', 'Could not export this note. Please try again.'));
},
- [note?.enhancedContent, transcriptBlocks, usesSegmentTranscript, viewMode],
+ [bodyTabInput, flushEnhancedSave, getNoteById, noteId, transcriptBlocks, viewMode],
);
- const handleCopyTranscript = useCallback(() => {
- if (!transcriptText.trim()) return;
+ const handleViewTranscript = useCallback(() => {
safeHaptics('light');
- Clipboard.setStringAsync(transcriptText).catch(() => {
- Alert.alert('Copy failed', 'Could not copy the transcript.');
- });
- }, [transcriptText]);
+ setTranscriptSheetVisible(true);
+ }, []);
const handleCopyGeneratedNote = useCallback(() => {
- const generatedContent = note?.enhancedContent;
+ // Copy the generated notes as edited, not as last saved.
+ flushEnhancedSave();
+ const generatedContent = getNoteById(noteId)?.enhancedContent;
if (!generatedContent?.trim()) return;
safeHaptics('light');
Clipboard.setStringAsync(generatedContent).catch(() => {
Alert.alert('Copy failed', 'Could not copy the generated notes.');
});
- }, [note?.enhancedContent]);
+ }, [flushEnhancedSave, getNoteById, noteId]);
+
+ const handleExportTranscript = useCallback(
+ (format: 'md' | 'txt'): void => {
+ safeHaptics('light');
+ exportNote(
+ {
+ title: `${titleRef.current || 'Untitled'} Transcript`,
+ content: formatTranscriptForExport({ blocks: transcriptBlocks }),
+ },
+ format,
+ ).catch(() =>
+ Alert.alert('Export failed', 'Could not export this transcript. Please try again.'),
+ );
+ },
+ [transcriptBlocks],
+ );
const runSelectedAction = useCallback(
(action: Parameters<typeof runAction>[0], routing?: ReasoningRoutingOptions) => {
if (processingState === 'processing') return;
+ // Save a queued edit now: it must not land on top of the new notes later, and it must
+ // survive an action that fails.
+ flushEnhancedSave();
const inputText =
usesSegmentTranscriptRef.current && isDefaultGenerateNotesAction(action)
? generatedMeetingInputRef.current
@@ -553,10 +749,10 @@ export default function NoteEditorScreen() {
},
});
},
- [note?.isPrivate, processingState, runAction],
+ [flushEnhancedSave, note?.isPrivate, processingState, runAction],
);
- const handleRunAction = useCallback(
+ const runActionWithRouting = useCallback(
async (action: Parameters<typeof runAction>[0]) => {
const routing = { isPrivateNote: note?.isPrivate === 1 };
// On-Device never leaves this phone: no account, paywall, or fallback to another service.
@@ -637,10 +833,28 @@ export default function NoteEditorScreen() {
],
);
+ const handleRunAction = useCallback(
+ (action: Parameters<typeof runAction>[0]) => {
+ // Decide from the notes on screen: an edit typed since the last save counts too.
+ flushEnhancedSave();
+ if (!getNoteById(noteId)?.enhancedContent?.trim()) {
+ runActionWithRouting(action).catch(() => {});
+ return;
+ }
+ confirmDestructive(
+ 'Replace enhanced notes?',
+ 'Running this action replaces the current enhanced notes, including any edits.',
+ () => runActionWithRouting(action),
+ { destructiveLabel: 'Replace' },
+ );
+ },
+ [flushEnhancedSave, getNoteById, noteId, runActionWithRouting],
+ );
+
const startChatRequest = useCallback(
async (question: string, appendUserMessage: boolean, allowRemoteContent = false) => {
const trimmedQuestion = question.trim();
- const context = actionInputRef.current.trim();
+ const context = chatContextRef.current.trim();
if (!trimmedQuestion || chatAbortRef.current) return;
if (!context) {
Alert.alert('Nothing to ask about', 'Add note content or finish the transcript first.');
@@ -670,14 +884,32 @@ export default function NoteEditorScreen() {
setChatMessages((current) => [...current, userMessage]);
}
- try {
- const response = await ReasoningService.chatOverNote({
- context,
+ const askAbout = (chatContext: string) =>
+ ReasoningService.chatOverNote({
+ context: chatContext,
question: trimmedQuestion,
history,
signal: controller.signal,
routing: { isPrivateNote: note?.isPrivate === 1, allowCloudFallback: allowRemoteContent },
});
+ const sourceContext = actionInputRef.current.trim();
+ try {
+ let response;
+ try {
+ response = await askAbout(context);
+ } catch (error) {
+ // The generated notes can push an on-device request past its limit; the note alone
+ // still fits wherever it did before they were added.
+ if (
+ controller.signal.aborted ||
+ !isLocalContextLimitError(error) ||
+ !sourceContext ||
+ sourceContext === context
+ ) {
+ throw error;
+ }
+ response = await askAbout(sourceContext);
+ }
if (controller.signal.aborted) return;
setChatMessages((current) => [
...current,
@@ -737,7 +969,7 @@ export default function NoteEditorScreen() {
);
const handleAskNote = useCallback(() => {
- if (!actionInputRef.current.trim()) {
+ if (!chatContextRef.current.trim()) {
Alert.alert('Nothing to ask about', 'Add note content or finish the transcript first.');
return;
}
@@ -885,15 +1117,8 @@ export default function NoteEditorScreen() {
);
}
- const updatedAtDisplay = note?.updatedAt
- ? parseNoteTimestamp(note.updatedAt).toLocaleDateString(undefined, {
- month: 'long',
- day: 'numeric',
- year: 'numeric',
- })
- : '';
-
- const hasEnhanced = !!note?.enhancedContent;
+ const bodyTabs = getNoteBodyTabs(bodyTabInput);
+ const bodyView = resolveNoteBodyView(viewMode, bodyTabInput);
const actionInputHash = makeContentHash(actionInputText);
const generatedMeetingInputHash =
usesSegmentTranscript && note?.calendarEventId
@@ -908,13 +1133,52 @@ export default function NoteEditorScreen() {
note?.enhancedAtContentHash !== generatedMeetingInputHash;
const isEnhancing = processingState === 'processing';
+ // iOS only presents a modal above another when it is rendered inside it, so these follow the
+ // transcript sheet while it is open.
+ const speakerSheets = (
+ <>
+ <SpeakerRenameSheet
+ visible={renameSheetVisible}
+ initialName={activeSpeakerName}
+ suggestions={attendeeSpeakerSuggestions}
+ onCancel={() => setRenameSheetVisible(false)}
+ onSave={handleRenameSpeaker}
+ />
+ <SpeakerMergeSheet
+ visible={mergeSheetVisible}
+ sourceSpeaker={activeSpeaker}
+ speakers={speakers}
+ onCancel={() => setMergeSheetVisible(false)}
+ onMerge={handleMergeSpeaker}
+ />
+ <VoiceprintSuggestionSheet
+ visible={suggestionSheetVisible}
+ speakerName={activeSpeakerName}
+ onConfirm={handleConfirmSuggestion}
+ onReject={handleRejectSuggestion}
+ onRename={() => {
+ setSuggestionSheetVisible(false);
+ setRenameSheetVisible(true);
+ }}
+ onMerge={() => {
+ setSuggestionSheetVisible(false);
+ setMergeSheetVisible(true);
+ }}
+ onCancel={() => setSuggestionSheetVisible(false)}
+ />
+ </>
+ );
+
return (
<View className="flex-1 bg-systemBackground">
{shareVisible ? (
<NoteShareSheet
noteId={noteId}
onClose={() => setShareVisible(false)}
- onFlushDraft={flushDraft}
+ onFlushDraft={() => {
+ flushDraft();
+ flushEnhancedSave();
+ }}
onExport={handleExport}
/>
) : null}
@@ -931,9 +1195,9 @@ export default function NoteEditorScreen() {
onRunAction={handleRunAction}
onManageActions={handleManageActions}
onAskNote={chatEnabled && !showAskPill ? handleAskNote : undefined}
- askNoteDisabled={isChatProcessing}
+ askNoteDisabled={isChatProcessing || !chatContextText.trim()}
onCopyGeneratedNote={note?.enhancedContent ? handleCopyGeneratedNote : undefined}
- onCopyTranscript={usesSegmentTranscript ? handleCopyTranscript : undefined}
+ onViewTranscript={usesSegmentTranscript ? handleViewTranscript : undefined}
onShare={() => setShareVisible(true)}
onDelete={handleDelete}
/>
@@ -969,9 +1233,16 @@ export default function NoteEditorScreen() {
style={{ fontFamily: AppFont.bold }}
/>
- {updatedAtDisplay ? (
- <Text className="mb-3 text-[13px] text-tertiaryLabel">{updatedAtDisplay}</Text>
- ) : null}
+ <NoteMetaRow
+ dateLabel={formatNoteMetaDate(
+ noteTakenAt(note?.createdAt, note?.cloudUpdatedAt ?? note?.updatedAt),
+ new Date(),
+ )}
+ attendeeLabel={attendeeLabel}
+ folderLabel={folderName}
+ onPressAttendees={() => setAttendeesVisible(true)}
+ onPressFolder={note && !isSpaceUnknown ? () => move.open(note.id) : undefined}
+ />
{conflict ? (
<ConflictBanner
@@ -981,58 +1252,46 @@ export default function NoteEditorScreen() {
/>
) : null}
- {hasEnhanced ? (
+ {bodyTabs.length > 1 ? (
<View
className="mb-4 flex-row bg-tertiarySystemFill p-0.5"
style={{ borderRadius: 12, borderCurve: 'continuous' }}
>
- <Pressable
- onPress={() => {
- safeHaptics('selection');
- setViewMode('original');
- }}
- className={
- 'flex-1 items-center py-1.5 ' +
- (viewMode === 'original' ? 'bg-brand' : 'bg-transparent')
- }
- style={{ borderRadius: 10, borderCurve: 'continuous' }}
- >
- <Text
- className={
- 'text-[13px] font-medium ' +
- (viewMode === 'original' ? 'text-white' : 'text-secondaryLabel')
- }
- >
- {isAudioTranscript ? 'Transcript' : 'Original'}
- </Text>
- </Pressable>
- <Pressable
- onPress={() => {
- safeHaptics('selection');
- setViewMode('enhanced');
- }}
- className={
- 'flex-1 flex-row items-center justify-center gap-1 py-1.5 ' +
- (viewMode === 'enhanced' ? 'bg-brand' : 'bg-transparent')
- }
- style={{ borderRadius: 10, borderCurve: 'continuous' }}
- >
- <Text
- className={
- 'text-[13px] font-medium ' +
- (viewMode === 'enhanced' ? 'text-white' : 'text-secondaryLabel')
- }
- >
- Enhanced
- </Text>
- {isStale ? (
- <View
- testID="enhanced-stale-indicator"
- className="h-1.5 w-1.5 rounded-full"
- style={{ backgroundColor: '#FF9500' }}
- />
- ) : null}
- </Pressable>
+ {bodyTabs.map((tab) => {
+ const active = bodyView === tab;
+ return (
+ <Pressable
+ key={tab}
+ testID={`note-tab-${tab}`}
+ accessibilityRole="tab"
+ accessibilityState={{ selected: active }}
+ onPress={() => {
+ safeHaptics('selection');
+ setViewMode(tab);
+ }}
+ className={
+ 'flex-1 flex-row items-center justify-center gap-1 py-1.5 ' +
+ (active ? 'bg-brand' : 'bg-transparent')
+ }
+ style={{ borderRadius: 10, borderCurve: 'continuous' }}
+ >
+ <Text
+ className={
+ 'text-[13px] font-medium ' + (active ? 'text-white' : 'text-secondaryLabel')
+ }
+ >
+ {getNoteBodyTabLabel(tab, bodyTabInput)}
+ </Text>
+ {tab === 'enhanced' && isStale ? (
+ <View
+ testID="enhanced-stale-indicator"
+ className="h-1.5 w-1.5 rounded-full"
+ style={{ backgroundColor: '#FF9500' }}
+ />
+ ) : null}
+ </Pressable>
+ );
+ })}
</View>
) : null}
@@ -1041,15 +1300,37 @@ export default function NoteEditorScreen() {
) : null}
<View className="relative">
- {viewMode === 'enhanced' && hasEnhanced ? (
- <MarkdownRenderer content={note!.enhancedContent!} selectable />
- ) : usesSegmentTranscript ? (
- <SpeakerTranscript
- blocks={transcriptBlocks}
- selectedSpeakerId={activeSpeakerId}
- selectable
- onSpeakerPress={handleSpeakerPress}
+ {bodyView === 'enhanced' ? (
+ <EditableMarkdown
+ key={`${noteId}-${enhancedEditorRevision}`}
+ content={note?.enhancedContent ?? ''}
+ editable={!isEnhancing}
+ onChange={handleEnhancedChange}
+ onEditingChange={handleEnhancedEditingChange}
/>
+ ) : bodyView === 'notes' ? (
+ <>
+ {transcriptStatus === 'recording' ? (
+ <Text className="mb-2 text-[13px] text-secondaryLabel">
+ You can edit these notes once the recording stops.
+ </Text>
+ ) : null}
+ <TextInput
+ testID="note-content-input"
+ value={content}
+ onChangeText={handleContentChange}
+ selection={selection}
+ onSelectionChange={(e) => setSelection(e.nativeEvent.selection)}
+ placeholder={hasTypedMeetingNotes ? 'Add your own notes…' : 'Type or dictate…'}
+ placeholderTextColor="rgba(0,0,0,0.2)"
+ multiline
+ // The recording screen still writes these notes until the recording stops.
+ editable={!isEnhancing && transcriptStatus !== 'recording'}
+ textAlignVertical="top"
+ className="min-h-[300px] text-base leading-6 text-label"
+ style={{ fontFamily: AppFont.regular, opacity: isEnhancing ? 0.4 : 1 }}
+ />
+ </>
) : shouldShowTranscriptStatus ? (
<View className="min-h-[180px] flex-row items-center gap-3">
<ActivityIndicator size="small" color={BRAND} />
@@ -1091,22 +1372,13 @@ export default function NoteEditorScreen() {
</Text>
)}
</View>
- ) : shouldRenderPlainEditor ? (
- <TextInput
- value={content}
- onChangeText={handleContentChange}
- selection={selection}
- onSelectionChange={(e) => setSelection(e.nativeEvent.selection)}
- placeholder="Type or dictate…"
- placeholderTextColor="rgba(0,0,0,0.2)"
- multiline
- editable={!isEnhancing}
- textAlignVertical="top"
- className="min-h-[300px] text-base leading-6 text-label"
- style={{ fontFamily: AppFont.regular, opacity: isEnhancing ? 0.4 : 1 }}
- />
) : (
- <View className="min-h-[180px]" />
+ <SpeakerTranscript
+ blocks={transcriptBlocks}
+ selectedSpeakerId={activeSpeakerId}
+ selectable
+ onSpeakerPress={handleSpeakerPress}
+ />
)}
{isEnhancing ? (
@@ -1200,7 +1472,7 @@ export default function NoteEditorScreen() {
draft={chatDraft}
isProcessing={isChatProcessing}
error={chatError}
- canSend={!contentEmpty}
+ canSend={!!chatContextText.trim()}
suggestions={chatSuggestions}
onDraftChange={setChatDraft}
onSend={handleSendChat}
@@ -1209,35 +1481,25 @@ export default function NoteEditorScreen() {
onClear={handleClearChat}
onClose={handleCloseChat}
/>
- <SpeakerRenameSheet
- visible={renameSheetVisible}
- initialName={activeSpeakerName}
- suggestions={attendeeSpeakerSuggestions}
- onCancel={() => setRenameSheetVisible(false)}
- onSave={handleRenameSpeaker}
- />
- <SpeakerMergeSheet
- visible={mergeSheetVisible}
- sourceSpeaker={activeSpeaker}
- speakers={speakers}
- onCancel={() => setMergeSheetVisible(false)}
- onMerge={handleMergeSpeaker}
- />
- <VoiceprintSuggestionSheet
- visible={suggestionSheetVisible}
- speakerName={activeSpeakerName}
- onConfirm={handleConfirmSuggestion}
- onReject={handleRejectSuggestion}
- onRename={() => {
- setSuggestionSheetVisible(false);
- setRenameSheetVisible(true);
- }}
- onMerge={() => {
- setSuggestionSheetVisible(false);
- setMergeSheetVisible(true);
- }}
- onCancel={() => setSuggestionSheetVisible(false)}
+ <AttendeesSheet
+ visible={attendeesVisible}
+ participants={attendees}
+ onClose={() => setAttendeesVisible(false)}
/>
+ {/* Hidden in the render where the Space disappears, before the picker is closed. */}
+ {isSpaceUnknown ? null : <MoveToFolderSheet {...move.sheetProps} />}
+ <TranscriptSheet
+ visible={transcriptSheetVisible}
+ blocks={transcriptBlocks}
+ selectedSpeakerId={activeSpeakerId}
+ shareText={transcriptText}
+ onSpeakerPress={handleSpeakerPress}
+ onExport={handleExportTranscript}
+ onClose={() => setTranscriptSheetVisible(false)}
+ >
+ {transcriptSheetVisible ? speakerSheets : null}
+ </TranscriptSheet>
+ {transcriptSheetVisible ? null : speakerSheets}
</View>
);
}
diff --git a/openwhispr-mobile/src/screens/NotesListScreen.tsx b/openwhispr-mobile/src/screens/NotesListScreen.tsx
index db12c3131..b4b885f2a 100644
--- a/openwhispr-mobile/src/screens/NotesListScreen.tsx
+++ b/openwhispr-mobile/src/screens/NotesListScreen.tsx
@@ -15,12 +15,12 @@ import { NewFolderSheet } from '@/components/notes/NewFolderSheet';
import { SystemIcon } from '@/components/ui/SystemIcon';
import { Fab, FAB_BOTTOM_PADDING, type FabAction } from '@/components/ui/Fab';
import { groupNotesByDate } from '@/lib/groupNotesByDate';
-import { canMoveBetweenSpaces } from '@/lib/spacePermissions';
import { safeHaptics } from '@/lib/utils';
import { confirmDestructive } from '@/lib/alerts';
import { SyncStatusLabel } from '@/components/notes/SyncStatusLabel';
import { VoiceProfilePromptCard } from '@/components/notes/VoiceProfilePromptCard';
import { useManualSyncRefresh } from '@/hooks/useManualSyncRefresh';
+import { useMoveNote } from '@/hooks/useMoveNote';
import { useConfigStore } from '@/store/useConfigStore';
export default function NotesListScreen() {
@@ -44,8 +44,6 @@ export default function NotesListScreen() {
searchQuery,
createNote,
deleteNote,
- moveNoteToFolder,
- moveNoteToSpace,
createFolder,
renameFolder,
deleteFolderSafe,
@@ -55,7 +53,6 @@ export default function NotesListScreen() {
const config = useConfigStore((s) => s.config);
const updateConfig = useConfigStore((s) => s.updateConfig);
- const [movingNoteId, setMovingNoteId] = useState<number | null>(null);
const [newFolderVisible, setNewFolderVisible] = useState(false);
useEffect(() => {
@@ -96,20 +93,11 @@ export default function NotesListScreen() {
[spaceId, folderId, spaceFolders],
);
const moveTargetFolders = contentSpaceId != null ? spaceFolders : folders;
-
- // Where this note is allowed to go, by desktop's rule: personal content may
- // move to any team space, while team content stays inside its own workspace —
- // never back to the private space, and never across workspaces.
- const moveTargetSpaces = useMemo(() => {
- const from =
- contentSpaceId != null
- ? spaces.find((s) => s.id === contentSpaceId)
- : spaces.find((s) => s.kind === 'private');
- if (!from) return [];
- return spaces.filter(
- (space) => space.kind === 'team' && space.id !== from.id && canMoveBetweenSpaces(from, space),
- );
- }, [spaces, contentSpaceId]);
+ const move = useMoveNote({
+ scopeSpaceId: contentSpaceId,
+ targetFolders: moveTargetFolders,
+ excludeFolderId: activeFolderId,
+ });
const buckets = useMemo(() => groupNotesByDate(notes), [notes]);
const totalCount = useMemo(() => {
@@ -144,46 +132,6 @@ export default function NotesListScreen() {
[deleteNote],
);
- const openMoveSheet = useCallback((noteId: number) => {
- safeHaptics('medium');
- setMovingNoteId(noteId);
- }, []);
-
- const closeMoveSheet = useCallback(() => setMovingNoteId(null), []);
-
- const handlePickFolder = useCallback(
- (targetFolderId: number) => {
- if (movingNoteId != null) {
- moveNoteToFolder(movingNoteId, targetFolderId);
- safeHaptics('success');
- }
- setMovingNoteId(null);
- },
- [movingNoteId, moveNoteToFolder],
- );
-
- const handleCreateAndPick = useCallback(
- (name: string) => {
- const folder = createFolder(name, contentSpaceId ?? undefined);
- if (movingNoteId != null) {
- moveNoteToFolder(movingNoteId, folder.id);
- }
- setMovingNoteId(null);
- },
- [movingNoteId, createFolder, moveNoteToFolder, contentSpaceId],
- );
-
- const handlePickSpace = useCallback(
- (targetSpaceId: number) => {
- if (movingNoteId != null) {
- moveNoteToSpace(movingNoteId, targetSpaceId);
- safeHaptics('success');
- }
- setMovingNoteId(null);
- },
- [movingNoteId, moveNoteToSpace],
- );
-
const handleCompose = useCallback(() => {
const note = createNote();
router.push(`/(tabs)/(notes)/${note.id}`);
@@ -430,9 +378,9 @@ export default function NotesListScreen() {
note={note}
bucket={bucket.key}
onPress={() => handleNotePress(note.id)}
- onLongPress={() => openMoveSheet(note.id)}
+ onLongPress={() => move.open(note.id)}
onDelete={() => handleDeleteNote(note.id)}
- onMove={() => openMoveSheet(note.id)}
+ onMove={() => move.open(note.id)}
/>
))}
</GroupedList>
@@ -455,18 +403,7 @@ export default function NotesListScreen() {
onCreate={handleCreateFolderInSpace}
/>
- <MoveToFolderSheet
- visible={movingNoteId != null}
- folders={moveTargetFolders}
- folderCounts={folderCounts}
- excludeFolderId={activeFolderId}
- onClose={closeMoveSheet}
- onPickFolder={handlePickFolder}
- onCreateAndPick={handleCreateAndPick}
- spaces={moveTargetSpaces}
- activeSpaceId={contentSpaceId}
- onPickSpace={handlePickSpace}
- />
+ <MoveToFolderSheet {...move.sheetProps} />
</View>
);
}
diff --git a/openwhispr-mobile/src/screens/__tests__/NoteEditorScreen.calendarContext.test.tsx b/openwhispr-mobile/src/screens/__tests__/NoteEditorScreen.calendarContext.test.tsx
index 1bdb6a481..d4ac8c060 100644
--- a/openwhispr-mobile/src/screens/__tests__/NoteEditorScreen.calendarContext.test.tsx
+++ b/openwhispr-mobile/src/screens/__tests__/NoteEditorScreen.calendarContext.test.tsx
@@ -1,14 +1,16 @@
import React from 'react';
import { Alert } from 'react-native';
-import { act, fireEvent, render, waitFor } from '@testing-library/react-native';
+import { act, fireEvent, render, waitFor, within } from '@testing-library/react-native';
import NoteEditorScreen from '@/screens/NoteEditorScreen';
import { ReasoningService } from '@/services/reasoning/ReasoningService';
import { generateNoteTitle } from '@/utils/generateTitle';
import { buildMeetingNotesInput } from '@/lib/notes/meetingNotesInput';
import { formatTranscriptForExport } from '@/lib/diarization/transcriptDisplay';
import { makeContentHash } from '@/lib/utils';
-import { clearLocalReasoningReadinessCache } from '@/lib/localReasoning';
+import { clearLocalReasoningReadinessCache, LocalReasoningError } from '@/lib/localReasoning';
+import { extractCorrections } from '@/lib/correctionLearner';
import type { Action, Note, Segment, Speaker } from '@/data/types';
+import type { Folder, Space } from '@/data';
import type { UserConfig } from '@/types';
const mockUpdateNote = jest.fn();
@@ -25,6 +27,7 @@ const mockUpdateConfig = jest.fn(async (updates: Record<string, unknown>) => {
});
let mockNote: Note;
+let mockRouteNoteId = '7';
let mockSegments: Segment[];
let mockSpeakers: Speaker[];
let mockActions: Action[];
@@ -45,6 +48,14 @@ const mockNotesState = {
resolveConflictKeepMine: jest.fn(),
resolveConflictUseServer: jest.fn(),
transcriptRevision: 0,
+ folders: [] as Folder[],
+ spaceFolders: [] as Folder[],
+ spaces: [] as Space[],
+ folderCounts: {} as Record<number, number>,
+ moveNoteToFolder: jest.fn(),
+ moveNoteToSpace: jest.fn(),
+ createFolder: jest.fn(),
+ getSpaceFolders: jest.fn(() => [] as Folder[]),
};
const mockActionsState = {
@@ -75,7 +86,7 @@ jest.mock('react-native-safe-area-context', () => ({
}));
jest.mock('expo-router', () => ({
- useLocalSearchParams: () => ({ id: '7' }),
+ useLocalSearchParams: () => ({ id: mockRouteNoteId }),
useRouter: () => ({
push: jest.fn(),
canGoBack: () => true,
@@ -176,6 +187,10 @@ jest.mock('@/lib/privateMode', () => ({
promptLocalModelFallback: jest.fn(),
}));
+jest.mock('@/lib/correctionLearner', () => ({
+ extractCorrections: jest.fn(() => []),
+}));
+
jest.mock('@/components/ui/TabScreenHeader', () => ({
TabScreenHeader: ({
title,
@@ -228,10 +243,14 @@ jest.mock('@/components/notes/NoteActionsMenu', () => ({
actions,
onRunAction,
onAskNote,
+ askNoteDisabled,
+ onViewTranscript,
}: {
actions: Action[];
onRunAction: (action: Action) => void;
onAskNote?: () => void;
+ askNoteDisabled?: boolean;
+ onViewTranscript?: () => void;
}) =>
(() => {
const { Pressable: MockPressable, Text: MockText, View: MockView } = require('react-native');
@@ -246,7 +265,16 @@ jest.mock('@/components/notes/NoteActionsMenu', () => ({
<MockText>{action.name}</MockText>
</MockPressable>
))}
- {onAskNote ? <MockText>Ask about this note</MockText> : null}
+ {onAskNote ? (
+ <MockText testID="menu-ask-note" accessibilityState={{ disabled: !!askNoteDisabled }}>
+ Ask about this note
+ </MockText>
+ ) : null}
+ {onViewTranscript ? (
+ <MockPressable testID="menu-view-transcript" onPress={onViewTranscript}>
+ <MockText>View Transcript</MockText>
+ </MockPressable>
+ ) : null}
</MockView>
);
})(),
@@ -261,13 +289,21 @@ jest.mock('@/components/notes/MarkdownRenderer', () => ({
}));
jest.mock('@/components/notes/SpeakerTranscript', () => ({
- SpeakerTranscript: ({ blocks }: { blocks: { text: string }[] }) =>
+ SpeakerTranscript: ({
+ blocks,
+ onSpeakerPress,
+ }: {
+ blocks: { text: string }[];
+ onSpeakerPress?: (block: { text: string }) => void;
+ }) =>
(() => {
const { Text: MockText, View: MockView } = require('react-native');
return (
<MockView>
{blocks.map((block, index) => (
- <MockText key={index}>{block.text}</MockText>
+ <MockText key={index} onPress={() => onSpeakerPress?.(block)}>
+ {block.text}
+ </MockText>
))}
</MockView>
);
@@ -275,7 +311,11 @@ jest.mock('@/components/notes/SpeakerTranscript', () => ({
}));
jest.mock('@/components/notes/SpeakerRenameSheet', () => ({
- SpeakerRenameSheet: () => null,
+ SpeakerRenameSheet: ({ visible }: { visible: boolean }) =>
+ (() => {
+ const { View: MockView } = require('react-native');
+ return visible ? <MockView testID="speaker-rename-sheet" /> : null;
+ })(),
}));
jest.mock('@/components/notes/SpeakerMergeSheet', () => ({
@@ -286,19 +326,52 @@ jest.mock('@/components/notes/VoiceprintSuggestionSheet', () => ({
VoiceprintSuggestionSheet: () => null,
}));
+jest.mock('@/components/notes/TranscriptSheet', () => ({
+ TranscriptSheet: ({
+ visible,
+ shareText,
+ children,
+ }: {
+ visible: boolean;
+ shareText: string;
+ children?: React.ReactNode;
+ }) =>
+ (() => {
+ const { Text: MockText, View: MockView } = require('react-native');
+ return visible ? (
+ <MockView>
+ <MockText testID="transcript-sheet">{shareText}</MockText>
+ {children}
+ </MockView>
+ ) : null;
+ })(),
+}));
+
+jest.mock('@/components/notes/MoveToFolderSheet', () => ({
+ MoveToFolderSheet: ({ visible }: { visible: boolean }) =>
+ (() => {
+ const { Text: MockText } = require('react-native');
+ return visible ? <MockText testID="move-sheet">move-sheet</MockText> : null;
+ })(),
+}));
+
jest.mock('@/components/notes/NoteChatSheet', () => ({
NoteChatSheet: ({
draft,
+ canSend,
suggestions,
onDraftChange,
onSend,
onSuggestion,
+ onClose,
}: {
draft: string;
+ canSend: boolean;
suggestions: readonly { label: string; prompt: string }[];
onDraftChange: (text: string) => void;
onSend: () => void;
onSuggestion: (prompt: string) => void;
+ onClose: () => void;
}) =>
(() => {
const {
@@ -309,7 +382,12 @@ jest.mock('@/components/notes/NoteChatSheet', () => ({
return (
<MockView>
<MockTextInput testID="chat-draft" value={draft} onChangeText={onDraftChange} />
- <MockPressable testID="chat-send" onPress={onSend} />
+ <MockPressable
+ testID="chat-send"
+ accessibilityState={{ disabled: !canSend }}
+ onPress={onSend}
+ />
+ <MockPressable testID="chat-close" onPress={onClose} />
{suggestions.map((suggestion) => (
<MockPressable
key={suggestion.label}
@@ -432,6 +510,7 @@ const calendarContextInputForCurrentNote = (): string =>
beforeEach(() => {
jest.clearAllMocks();
clearLocalReasoningReadinessCache();
+ mockRouteNoteId = '7';
mockAppleAvailability = 'available';
mockAuthState.user = { id: 'user-1', email: '[email protected]', emailVerified: true };
mockConfigState.config.inference = undefined;
@@ -610,6 +689,35 @@ describe('NoteEditorScreen note chat', () => {
expect(queryByTestId('chat-suggestion-Key decisions')).toBeNull();
});
+ it('lets you ask about a plain note that only has generated notes', () => {
+ mockNote = note({
+ noteType: 'personal',
+ diarizationEnabled: 0,
+ calendarEventId: null,
+ participants: null,
+ content: '',
+ enhancedContent: '## Summary',
+ });
+ mockNotesState.notes = [mockNote];
+ mockSegments = [];
+ const { getByTestId } = render(<NoteEditorScreen />);
+ expect(getByTestId('menu-ask-note').props.accessibilityState.disabled).toBe(false);
+ });
+
+ it('disables Ask on an empty plain note', () => {
+ mockNote = note({
+ noteType: 'personal',
+ diarizationEnabled: 0,
+ calendarEventId: null,
+ participants: null,
+ content: '',
+ });
+ mockNotesState.notes = [mockNote];
+ mockSegments = [];
+ const { getByTestId } = render(<NoteEditorScreen />);
+ expect(getByTestId('menu-ask-note').props.accessibilityState.disabled).toBe(true);
+ });
+
it('offers note-worded shortcuts for an uploaded recording', () => {
mockNote = note({ noteType: 'upload', diarizationEnabled: 0, calendarEventId: null });
mockNotesState.notes = [mockNote];
@@ -637,6 +745,89 @@ describe('NoteEditorScreen note chat', () => {
'What are the next steps from the meeting above that I need to do?',
);
});
+
+ it('asks about the note and its generated notes', async () => {
+ mockNote = note({ enhancedContent: '## Summary\n- Launch Friday' });
+ mockNotesState.notes = [mockNote];
+ (ReasoningService.chatOverNote as jest.Mock).mockResolvedValue({ text: 'Answer', model: 'x' });
+ const { getByTestId } = render(<NoteEditorScreen />);
+ await act(async () => {
+ fireEvent.press(getByTestId('chat-suggestion-List action items'));
+ });
+ await waitFor(() => expect(ReasoningService.chatOverNote).toHaveBeenCalledTimes(1));
+ const { context } = (ReasoningService.chatOverNote as jest.Mock).mock.calls[0][0];
+ expect(context).toContain('Alice owns the launch checklist.');
+ expect(context).toContain('Generated notes:\n## Summary\n- Launch Friday');
+ });
+
+ it('asks about the note alone when the generated notes push it past the on-device limit', async () => {
+ mockNote = note({ enhancedContent: '## Summary\n- Launch Friday' });
+ mockNotesState.notes = [mockNote];
+ (ReasoningService.chatOverNote as jest.Mock)
+ .mockRejectedValueOnce(new LocalReasoningError('LOCAL_CONTEXT_LIMIT', 'Too large'))
+ .mockResolvedValueOnce({ text: 'Answer', model: 'x' });
+ const { getByTestId } = render(<NoteEditorScreen />);
+ await act(async () => {
+ fireEvent.press(getByTestId('chat-suggestion-List action items'));
+ });
+ await waitFor(() => expect(ReasoningService.chatOverNote).toHaveBeenCalledTimes(2));
+ const retry = (ReasoningService.chatOverNote as jest.Mock).mock.calls[1][0];
+ expect(retry.context).toContain('Alice owns the launch checklist.');
+ expect(retry.context).not.toContain('Launch Friday');
+ });
+
+ it('does not ask again once the chat is closed', async () => {
+ mockNote = note({ enhancedContent: '## Summary\n- Launch Friday' });
+ mockNotesState.notes = [mockNote];
+ let failFirstAsk: (error: Error) => void = () => undefined;
+ (ReasoningService.chatOverNote as jest.Mock).mockReturnValueOnce(
+ new Promise((_resolve, reject) => {
+ failFirstAsk = reject;
+ }),
+ );
+ const { getByTestId } = render(<NoteEditorScreen />);
+ await act(async () => {
+ fireEvent.press(getByTestId('chat-suggestion-List action items'));
+ });
+ await waitFor(() => expect(ReasoningService.chatOverNote).toHaveBeenCalledTimes(1));
+
+ fireEvent.press(getByTestId('chat-close'));
+ await act(async () => {
+ failFirstAsk(new LocalReasoningError('LOCAL_CONTEXT_LIMIT', 'Too large'));
+ });
+
+ expect(ReasoningService.chatOverNote).toHaveBeenCalledTimes(1);
+ });
+
+ it('lets you send a question about a note that only has generated notes', () => {
+ mockNote = note({
+ noteType: 'personal',
+ diarizationEnabled: 0,
+ calendarEventId: null,
+ participants: null,
+ content: '',
+ enhancedContent: '## Summary',
+ });
+ mockNotesState.notes = [mockNote];
+ mockSegments = [];
+ const { getByTestId } = render(<NoteEditorScreen />);
+ expect(getByTestId('chat-send').props.accessibilityState.disabled).toBe(false);
+ });
+
+ it('asks only once when chat fails for another reason', async () => {
+ mockNote = note({ enhancedContent: '## Summary\n- Launch Friday' });
+ mockNotesState.notes = [mockNote];
+ (ReasoningService.chatOverNote as jest.Mock).mockRejectedValueOnce(new Error('offline'));
+ const { getByTestId } = render(<NoteEditorScreen />);
+ await act(async () => {
+ fireEvent.press(getByTestId('chat-suggestion-List action items'));
+ });
+ await waitFor(() => expect(ReasoningService.chatOverNote).toHaveBeenCalledTimes(1));
+ await act(async () => {
+ await Promise.resolve();
+ });
+ expect(ReasoningService.chatOverNote).toHaveBeenCalledTimes(1);
+ });
});
describe('NoteEditorScreen generated titles', () => {
@@ -805,3 +996,608 @@ describe('NoteEditorScreen On-Device and provider routes', () => {
expect(mockRegisterSuperwallGate).not.toHaveBeenCalled();
});
});
+
+describe('NoteEditorScreen body tabs', () => {
+ const plainNote = (overrides: Partial<Note> = {}): Note =>
+ note({
+ noteType: 'personal',
+ diarizationEnabled: 0,
+ calendarEventId: null,
+ participants: null,
+ ...overrides,
+ });
+
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
+ it('shows Transcript and My notes on a meeting before notes are generated', () => {
+ const { getByTestId, queryByTestId, getByText } = render(<NoteEditorScreen />);
+ expect(getByTestId('note-tab-transcript')).toBeTruthy();
+ expect(getByTestId('note-tab-notes')).toBeTruthy();
+ expect(queryByTestId('note-tab-enhanced')).toBeNull();
+ expect(getByText('Alice can take the first pass.')).toBeTruthy();
+ });
+
+ it('shows Enhanced and My notes once notes are generated', () => {
+ mockNote = note({ enhancedContent: '## Summary' });
+ mockNotesState.notes = [mockNote];
+ const { getByTestId, queryByTestId, getByText } = render(<NoteEditorScreen />);
+ expect(getByTestId('note-tab-enhanced')).toBeTruthy();
+ expect(getByTestId('note-tab-notes')).toBeTruthy();
+ expect(queryByTestId('note-tab-transcript')).toBeNull();
+ expect(getByText('## Summary')).toBeTruthy();
+ });
+
+ it('shows no tabs on a plain note without generated notes', () => {
+ mockNote = plainNote();
+ mockNotesState.notes = [mockNote];
+ mockSegments = [];
+ const { queryByTestId, getByTestId } = render(<NoteEditorScreen />);
+ expect(queryByTestId('note-tab-notes')).toBeNull();
+ expect(getByTestId('note-content-input')).toBeTruthy();
+ });
+
+ it('shows the processing status on the Transcript tab and keeps My notes reachable', () => {
+ mockNote = note({ transcriptionStatus: 'transcribing' });
+ mockNotesState.notes = [mockNote];
+ mockSegments = [];
+ const { getByText, getByTestId, queryByTestId, queryByText } = render(<NoteEditorScreen />);
+ expect(getByText('Transcribing audio...')).toBeTruthy();
+ expect(queryByTestId('note-content-input')).toBeNull();
+
+ fireEvent.press(getByTestId('note-tab-notes'));
+
+ expect(getByTestId('note-content-input').props.value).toBe('Alice owns the launch checklist.');
+ expect(queryByText('Transcribing audio...')).toBeNull();
+ });
+
+ it('keeps a failed transcript on its own tab beside the generated notes and My notes', () => {
+ mockNote = note({ transcriptionStatus: 'failed', enhancedContent: '## Summary' });
+ mockNotesState.notes = [mockNote];
+ mockSegments = [];
+ const { getByText, getByTestId } = render(<NoteEditorScreen />);
+ expect(getByTestId('note-tab-enhanced')).toBeTruthy();
+ expect(getByTestId('note-tab-notes')).toBeTruthy();
+
+ fireEvent.press(getByTestId('note-tab-transcript'));
+
+ expect(getByText('Transcript failed')).toBeTruthy();
+ });
+
+ it('never shows an uploaded file’s body, the flat copy of its transcript, as My notes', () => {
+ mockNote = note({
+ noteType: 'upload',
+ calendarEventId: null,
+ participants: null,
+ content: 'Alice can take the first pass.',
+ });
+ mockNotesState.notes = [mockNote];
+ const { getByText, queryByTestId } = render(<NoteEditorScreen />);
+ expect(getByText('Alice can take the first pass.')).toBeTruthy();
+ expect(queryByTestId('note-tab-notes')).toBeNull();
+ expect(queryByTestId('note-content-input')).toBeNull();
+ });
+
+ it('keeps an uploaded file’s transcript as a tab once notes are generated', () => {
+ mockNote = note({
+ noteType: 'upload',
+ calendarEventId: null,
+ participants: null,
+ enhancedContent: '## Summary',
+ });
+ mockNotesState.notes = [mockNote];
+ const { getByText, getByTestId, queryByTestId } = render(<NoteEditorScreen />);
+ expect(getByTestId('note-tab-enhanced')).toBeTruthy();
+ expect(queryByTestId('note-tab-notes')).toBeNull();
+
+ fireEvent.press(getByTestId('note-tab-transcript'));
+
+ expect(getByText('Alice can take the first pass.')).toBeTruthy();
+ expect(queryByTestId('note-content-input')).toBeNull();
+ });
+
+ it('shows an uploaded file without segments as its editable transcript text', () => {
+ mockNote = note({
+ noteType: 'upload',
+ calendarEventId: null,
+ participants: null,
+ diarizationEnabled: 0,
+ content: 'Alice can take the first pass.',
+ enhancedContent: '## Summary',
+ });
+ mockNotesState.notes = [mockNote];
+ mockSegments = [];
+ const { getByTestId } = render(<NoteEditorScreen />);
+ const bodyTab = getByTestId('note-tab-notes');
+ expect(within(bodyTab).getByText('Transcript')).toBeTruthy();
+
+ fireEvent.press(bodyTab);
+
+ expect(getByTestId('note-content-input').props.value).toBe('Alice can take the first pass.');
+ });
+
+ it('saves edits to the typed meeting notes without learning dictionary corrections', () => {
+ jest.useFakeTimers();
+ const { getByTestId } = render(<NoteEditorScreen />);
+ fireEvent.press(getByTestId('note-tab-notes'));
+ const input = getByTestId('note-content-input');
+ expect(input.props.value).toBe('Alice owns the launch checklist.');
+
+ fireEvent.changeText(input, 'Alice owns the launch checklist and the demo.');
+ act(() => {
+ jest.advanceTimersByTime(800);
+ });
+
+ // Only changed fields are saved.
+ expect(mockUpdateNote).toHaveBeenCalledWith(7, {
+ content: 'Alice owns the launch checklist and the demo.',
+ });
+ expect(extractCorrections).not.toHaveBeenCalled();
+ });
+
+ it('still learns dictionary corrections from plain note edits', () => {
+ jest.useFakeTimers();
+ mockNote = plainNote();
+ mockNotesState.notes = [mockNote];
+ mockSegments = [];
+ const { getByTestId } = render(<NoteEditorScreen />);
+ fireEvent.changeText(getByTestId('note-content-input'), 'Alice owns the launch checklists.');
+ act(() => {
+ jest.advanceTimersByTime(800);
+ });
+ expect(extractCorrections).toHaveBeenCalled();
+ });
+
+ it('still learns dictionary corrections from a meeting without a transcript, which can be dictated into', () => {
+ jest.useFakeTimers();
+ mockNote = note({ transcriptionStatus: 'done' });
+ mockNotesState.notes = [mockNote];
+ mockSegments = [];
+ const { getByTestId } = render(<NoteEditorScreen />);
+ fireEvent.changeText(getByTestId('note-content-input'), 'Alice owns the launch checklists.');
+ act(() => {
+ jest.advanceTimersByTime(800);
+ });
+ expect(extractCorrections).toHaveBeenCalled();
+ });
+
+ it('keeps My notes read-only while the meeting is still recording them', () => {
+ mockNote = note({ transcriptionStatus: 'recording' });
+ mockNotesState.notes = [mockNote];
+ mockSegments = [];
+ const { getByTestId, getByText } = render(<NoteEditorScreen />);
+ fireEvent.press(getByTestId('note-tab-notes'));
+ expect(getByTestId('note-content-input').props.editable).toBe(false);
+ expect(getByText('You can edit these notes once the recording stops.')).toBeTruthy();
+ });
+
+ it('switches from Transcript to Enhanced when generated notes arrive', () => {
+ const { rerender, getByText, queryByText } = render(<NoteEditorScreen />);
+ expect(getByText('Alice can take the first pass.')).toBeTruthy();
+
+ mockNote = note({ enhancedContent: '## Summary' });
+ mockNotesState.notes = [mockNote];
+ rerender(<NoteEditorScreen />);
+
+ expect(getByText('## Summary')).toBeTruthy();
+ expect(queryByText('Alice can take the first pass.')).toBeNull();
+ });
+
+ it('stays on My notes when generated notes arrive', () => {
+ const { rerender, getByTestId } = render(<NoteEditorScreen />);
+ fireEvent.press(getByTestId('note-tab-notes'));
+
+ mockNote = note({ enhancedContent: '## Summary' });
+ mockNotesState.notes = [mockNote];
+ rerender(<NoteEditorScreen />);
+
+ expect(getByTestId('note-content-input')).toBeTruthy();
+ });
+
+ it('saves edits to the generated notes when Done is pressed', () => {
+ mockNote = note({ enhancedContent: '## Summary' });
+ mockNotesState.notes = [mockNote];
+ const { getByTestId } = render(<NoteEditorScreen />);
+
+ fireEvent.press(getByTestId('enhanced-edit'));
+ fireEvent.changeText(getByTestId('enhanced-editor'), '## Summary\n- Launch Friday');
+ fireEvent.press(getByTestId('enhanced-done'));
+
+ expect(mockUpdateNote).toHaveBeenCalledWith(7, {
+ enhancedContent: '## Summary\n- Launch Friday',
+ });
+ });
+
+ it('saves an unfinished edit to the generated notes when the screen closes', () => {
+ mockNote = note({ enhancedContent: '## Summary' });
+ mockNotesState.notes = [mockNote];
+ const { getByTestId, unmount } = render(<NoteEditorScreen />);
+
+ fireEvent.press(getByTestId('enhanced-edit'));
+ fireEvent.changeText(getByTestId('enhanced-editor'), '## Summary\n- Draft');
+ unmount();
+
+ expect(mockUpdateNote).toHaveBeenCalledWith(7, { enhancedContent: '## Summary\n- Draft' });
+ });
+});
+
+describe('NoteEditorScreen replacing generated notes', () => {
+ let alertSpy: jest.SpyInstance;
+ beforeEach(() => {
+ alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined);
+ mockNote = note({ enhancedContent: '## Summary' });
+ mockNotesState.notes = [mockNote];
+ });
+ afterEach(() => alertSpy.mockRestore());
+
+ const pressReplace = async (): Promise<void> => {
+ const buttons = (alertSpy.mock.calls[0][2] ?? []) as { text: string; onPress?: () => void }[];
+ await act(async () => {
+ buttons.find((button) => button.text === 'Replace')?.onPress?.();
+ });
+ };
+
+ it('asks before an action replaces the generated notes', async () => {
+ const { getByTestId } = render(<NoteEditorScreen />);
+ await act(async () => {
+ fireEvent.press(getByTestId('run-action-1'));
+ });
+
+ expect(alertSpy).toHaveBeenCalledWith(
+ 'Replace enhanced notes?',
+ 'Running this action replaces the current enhanced notes, including any edits.',
+ expect.any(Array),
+ );
+ expect(ReasoningService.processText).not.toHaveBeenCalled();
+
+ await pressReplace();
+ await waitFor(() => expect(ReasoningService.processText).toHaveBeenCalledTimes(1));
+ });
+
+ it('leaves the notes alone when the replacement is cancelled', async () => {
+ const { getByTestId } = render(<NoteEditorScreen />);
+ await act(async () => {
+ fireEvent.press(getByTestId('run-action-1'));
+ });
+ const buttons = (alertSpy.mock.calls[0][2] ?? []) as { text: string; style?: string }[];
+ expect(buttons.map((button) => button.text)).toEqual(['Cancel', 'Replace']);
+ expect(buttons[0].style).toBe('cancel');
+ expect(ReasoningService.processText).not.toHaveBeenCalled();
+ });
+
+ const runActionOverEdit = async (): Promise<ReturnType<typeof render>> => {
+ const screen = render(<NoteEditorScreen />);
+ fireEvent.press(screen.getByTestId('enhanced-edit'));
+ fireEvent.changeText(screen.getByTestId('enhanced-editor'), '## Edited');
+ await act(async () => {
+ fireEvent.press(screen.getByTestId('run-action-1'));
+ });
+ await pressReplace();
+ await waitFor(() => expect(ReasoningService.processText).toHaveBeenCalledTimes(1));
+ // Outlast the 800 ms save debounce.
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 900));
+ });
+ return screen;
+ };
+ const savedEnhanced = (): unknown[] =>
+ mockUpdateNote.mock.calls
+ .map(([, updates]) => updates.enhancedContent)
+ .filter((value) => value !== undefined);
+
+ it('saves an unsaved edit before the action, so it cannot overwrite the new notes', async () => {
+ await runActionOverEdit();
+
+ const saved = savedEnhanced();
+ expect(saved[0]).toBe('## Edited');
+ expect(saved.filter((value) => value === '## Edited')).toHaveLength(1);
+ });
+
+ it('asks before replacing notes typed since they were last cleared', async () => {
+ mockUpdateNote.mockImplementation((id: number, updates: Partial<Note>) => {
+ mockNote = { ...mockNote!, ...updates };
+ mockNotesState.notes = [mockNote];
+ });
+ const { getByTestId, rerender } = render(<NoteEditorScreen />);
+ fireEvent.press(getByTestId('enhanced-edit'));
+ fireEvent.changeText(getByTestId('enhanced-editor'), '');
+ // Outlast the 800 ms save debounce, so the cleared notes are what is saved.
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 900));
+ });
+ rerender(<NoteEditorScreen />);
+ expect(mockNote?.enhancedContent).toBe('');
+
+ fireEvent.changeText(getByTestId('enhanced-editor'), '## Rewritten');
+ await act(async () => {
+ fireEvent.press(getByTestId('run-action-1'));
+ });
+
+ expect(alertSpy).toHaveBeenCalledWith(
+ 'Replace enhanced notes?',
+ expect.any(String),
+ expect.any(Array),
+ );
+ expect(ReasoningService.processText).not.toHaveBeenCalled();
+ });
+
+ it('keeps an unsaved edit when the action fails', async () => {
+ (ReasoningService.processText as jest.Mock).mockRejectedValueOnce(new Error('offline'));
+
+ await runActionOverEdit();
+
+ expect(savedEnhanced()).toEqual(['## Edited']);
+ });
+});
+
+describe('NoteEditorScreen switching notes', () => {
+ it('closes an open speaker sheet when another note opens', () => {
+ const alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined);
+ const { getByText, queryByTestId, rerender } = render(<NoteEditorScreen />);
+ fireEvent.press(getByText('Alice can take the first pass.'));
+ const buttons = (alertSpy.mock.calls[0][2] ?? []) as { text: string; onPress?: () => void }[];
+ act(() => {
+ buttons.find((button) => button.text === 'Rename')?.onPress?.();
+ });
+ expect(queryByTestId('speaker-rename-sheet')).toBeTruthy();
+
+ mockRouteNoteId = '8';
+ mockNote = note({ id: 8 });
+ mockNotesState.notes = [mockNote];
+ rerender(<NoteEditorScreen />);
+
+ expect(queryByTestId('speaker-rename-sheet')).toBeNull();
+ alertSpy.mockRestore();
+ });
+});
+
+describe('NoteEditorScreen transcript sheet', () => {
+ it('opens the full transcript from View Transcript', () => {
+ mockNote = note({ enhancedContent: '## Summary' });
+ mockNotesState.notes = [mockNote];
+ const { getByTestId, queryByTestId } = render(<NoteEditorScreen />);
+ expect(queryByTestId('transcript-sheet')).toBeNull();
+
+ fireEvent.press(getByTestId('menu-view-transcript'));
+
+ expect(getByTestId('transcript-sheet').props.children).toContain(
+ 'Alice can take the first pass.',
+ );
+ });
+
+ it('offers View Transcript before notes are generated too', () => {
+ const { getByTestId } = render(<NoteEditorScreen />);
+ expect(getByTestId('menu-view-transcript')).toBeTruthy();
+ });
+
+ it('has no View Transcript on a plain note', () => {
+ mockNote = note({
+ noteType: 'personal',
+ diarizationEnabled: 0,
+ calendarEventId: null,
+ participants: null,
+ });
+ mockNotesState.notes = [mockNote];
+ mockSegments = [];
+ const { queryByTestId } = render(<NoteEditorScreen />);
+ expect(queryByTestId('menu-view-transcript')).toBeNull();
+ });
+});
+
+describe('NoteEditorScreen meta row', () => {
+ beforeEach(() => {
+ mockNotesState.folders = [
+ {
+ id: 1,
+ name: 'Meetings',
+ isDefault: 0,
+ sortOrder: 0,
+ spaceId: 1,
+ clientFolderId: null,
+ remoteId: null,
+ deletedAt: null,
+ pendingSync: 0,
+ createdAt: null,
+ updatedAt: null,
+ } as Folder,
+ ];
+ });
+ afterEach(() => {
+ mockNotesState.folders = [];
+ mockNotesState.spaces = [];
+ });
+
+ it('shows the attendees and folder of a calendar meeting', () => {
+ const { getByTestId, getByText } = render(<NoteEditorScreen />);
+ expect(getByTestId('note-meta-attendees')).toBeTruthy();
+ expect(getByText('Alice')).toBeTruthy();
+ expect(getByText('Meetings')).toBeTruthy();
+ });
+
+ it('opens the folder picker from the folder chip', () => {
+ const { getByTestId, queryByTestId } = render(<NoteEditorScreen />);
+ expect(queryByTestId('move-sheet')).toBeNull();
+ fireEvent.press(getByTestId('note-meta-folder'));
+ expect(getByTestId('move-sheet')).toBeTruthy();
+ });
+
+ it('lists the attendees from the attendees chip', () => {
+ const { getByTestId, getByText } = render(<NoteEditorScreen />);
+ fireEvent.press(getByTestId('note-meta-attendees'));
+ expect(getByText('Attendees')).toBeTruthy();
+ expect(getByText('Alice Adams')).toBeTruthy();
+ });
+
+ it('hides the attendees chip on a note without attendees', () => {
+ mockNote = note({ calendarEventId: null, participants: null });
+ mockNotesState.notes = [mockNote];
+ const { queryByTestId } = render(<NoteEditorScreen />);
+ expect(queryByTestId('note-meta-attendees')).toBeNull();
+ });
+
+ it('offers no folders for a note whose Space is not on this device', () => {
+ mockNote = note({ spaceId: 99 });
+ mockNotesState.notes = [mockNote];
+ const { queryByTestId, queryByText } = render(<NoteEditorScreen />);
+ expect(queryByTestId('note-meta-folder')).toBeNull();
+ expect(queryByText('Meetings')).toBeNull();
+ });
+
+ it('closes the folder picker if the note’s Space disappears while it is open', () => {
+ mockNote = note({ spaceId: 1 });
+ mockNotesState.notes = [mockNote];
+ mockNotesState.spaces = [{ id: 1, kind: 'private', name: 'Private' } as Space];
+ const { getByTestId, queryByTestId, rerender } = render(<NoteEditorScreen />);
+ fireEvent.press(getByTestId('note-meta-folder'));
+ expect(getByTestId('move-sheet')).toBeTruthy();
+
+ mockNotesState.spaces = [];
+ rerender(<NoteEditorScreen />);
+ expect(queryByTestId('move-sheet')).toBeNull();
+
+ // It stays closed when the Space comes back.
+ mockNotesState.spaces = [{ id: 1, kind: 'private', name: 'Private' } as Space];
+ rerender(<NoteEditorScreen />);
+ expect(queryByTestId('move-sheet')).toBeNull();
+ });
+
+ it('closes the folder picker when another note opens', () => {
+ const { getByTestId, queryByTestId, rerender } = render(<NoteEditorScreen />);
+ fireEvent.press(getByTestId('note-meta-folder'));
+ expect(getByTestId('move-sheet')).toBeTruthy();
+
+ mockRouteNoteId = '8';
+ mockNote = note({ id: 8 });
+ mockNotesState.notes = [mockNote];
+ rerender(<NoteEditorScreen />);
+
+ expect(queryByTestId('move-sheet')).toBeNull();
+ });
+
+ describe('on a team note', () => {
+ const teamSpace = { id: 2, kind: 'team', name: 'Engineering', workspaceId: 'w1' } as Space;
+ const participants = JSON.stringify([
+ {
+ email: '[email protected]',
+ displayName: 'Sam Lee',
+ responseStatus: 'accepted',
+ organizer: true,
+ resource: false,
+ self: true,
+ },
+ {
+ email: '[email protected]',
+ displayName: 'Uma User',
+ responseStatus: 'accepted',
+ organizer: false,
+ resource: false,
+ self: false,
+ },
+ ]);
+ beforeEach(() => {
+ mockNotesState.spaces = [teamSpace];
+ });
+
+ it('labels you, not the teammate who created the note, as You', () => {
+ mockNote = note({ spaceId: 2, ownerUserId: 'teammate-9', participants });
+ mockNotesState.notes = [mockNote];
+ const { getByTestId, getByText, queryByText } = render(<NoteEditorScreen />);
+ expect(getByText('Sam +1')).toBeTruthy();
+
+ fireEvent.press(getByTestId('note-meta-attendees'));
+ expect(getByText('Sam Lee')).toBeTruthy();
+ expect(getByText('You')).toBeTruthy();
+ expect(queryByText('Uma User')).toBeNull();
+ });
+
+ it('labels you, not the teammate who created the note, as You while its Space is unknown', () => {
+ mockNotesState.spaces = [];
+ mockNote = note({ spaceId: 2, ownerUserId: 'teammate-9', participants });
+ mockNotesState.notes = [mockNote];
+ const { getByTestId, getByText, queryByText } = render(<NoteEditorScreen />);
+ fireEvent.press(getByTestId('note-meta-attendees'));
+ expect(getByText('Sam Lee')).toBeTruthy();
+ expect(getByText('You')).toBeTruthy();
+ expect(queryByText('Uma User')).toBeNull();
+ });
+
+ it('trusts your calendar’s own row on a team note you created', () => {
+ // Your calendar account needn't share your OpenWhispr address.
+ const ownCalendar = JSON.stringify([
+ {
+ email: '[email protected]',
+ displayName: 'Uma User',
+ responseStatus: 'accepted',
+ organizer: false,
+ resource: false,
+ self: true,
+ },
+ {
+ email: '[email protected]',
+ displayName: 'Sam Lee',
+ responseStatus: 'accepted',
+ organizer: false,
+ resource: false,
+ self: false,
+ },
+ ]);
+ mockNote = note({ spaceId: 2, ownerUserId: 'user-1', participants: ownCalendar });
+ mockNotesState.notes = [mockNote];
+ const { getByTestId, getByText, queryByText } = render(<NoteEditorScreen />);
+ expect(getByText('Sam +1')).toBeTruthy();
+ fireEvent.press(getByTestId('note-meta-attendees'));
+ expect(getByText('You')).toBeTruthy();
+ expect(queryByText('Uma User')).toBeNull();
+ });
+ });
+
+ it('dates a note pulled before its creation time synced by its last edit, not the pull', () => {
+ mockNote = note({ createdAt: '2025-09-27 08:00:00', updatedAt: '2025-06-26T12:00:00.000Z' });
+ mockNotesState.notes = [mockNote];
+ const { getByText, queryByText } = render(<NoteEditorScreen />);
+ expect(getByText(/^Jun 26, 2025/)).toBeTruthy();
+ expect(queryByText(/^Sep 27, 2025/)).toBeNull();
+ });
+
+ it('keeps that date after the note is edited on this device', () => {
+ mockNote = note({
+ createdAt: '2025-09-27 08:00:00',
+ updatedAt: '2025-09-28 10:00:00',
+ cloudUpdatedAt: '2025-06-26T12:00:00.000Z',
+ });
+ mockNotesState.notes = [mockNote];
+ const { getByText, queryByText } = render(<NoteEditorScreen />);
+ expect(getByText(/^Jun 26, 2025/)).toBeTruthy();
+ expect(queryByText(/^Sep 27, 2025/)).toBeNull();
+ });
+});
+
+describe('NoteEditorScreen clearing generated notes', () => {
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
+ it('keeps the editor open when the generated notes are cleared mid-edit', () => {
+ jest.useFakeTimers();
+ mockNote = note({ enhancedContent: '## Summary' });
+ mockNotesState.notes = [mockNote];
+ const { getByTestId, rerender } = render(<NoteEditorScreen />);
+
+ fireEvent.press(getByTestId('enhanced-edit'));
+ fireEvent.changeText(getByTestId('enhanced-editor'), '');
+ act(() => {
+ jest.advanceTimersByTime(800);
+ });
+ expect(mockUpdateNote).toHaveBeenCalledWith(7, { enhancedContent: '' });
+
+ // The store now holds the cleared notes.
+ mockNote = note({ enhancedContent: '' });
+ mockNotesState.notes = [mockNote];
+ rerender(<NoteEditorScreen />);
+
+ fireEvent.changeText(getByTestId('enhanced-editor'), '## Rewritten');
+ fireEvent.press(getByTestId('enhanced-done'));
+ expect(mockUpdateNote).toHaveBeenLastCalledWith(7, { enhancedContent: '## Rewritten' });
+ });
+});
diff --git a/openwhispr-mobile/src/screens/__tests__/NoteEditorScreen.conflictBanner.test.tsx b/openwhispr-mobile/src/screens/__tests__/NoteEditorScreen.conflictBanner.test.tsx
index 03c83015f..173741a12 100644
--- a/openwhispr-mobile/src/screens/__tests__/NoteEditorScreen.conflictBanner.test.tsx
+++ b/openwhispr-mobile/src/screens/__tests__/NoteEditorScreen.conflictBanner.test.tsx
@@ -1,8 +1,10 @@
import React from 'react';
import { act, fireEvent, render } from '@testing-library/react-native';
import NoteEditorScreen from '@/screens/NoteEditorScreen';
+import * as Clipboard from 'expo-clipboard';
import { exportNote } from '@/lib/noteExport';
import type { Action, ConflictedNote, Note, RemoteNote, Segment, Speaker } from '@/data/types';
+import type { Folder, Space } from '@/data';
const mockUpdateNote = jest.fn();
const mockDeleteNote = jest.fn();
@@ -38,6 +40,14 @@ const mockNotesState = {
resolveConflictKeepMine: mockResolveConflictKeepMine,
resolveConflictUseServer: mockResolveConflictUseServer,
transcriptRevision: 0,
+ folders: [] as Folder[],
+ spaceFolders: [] as Folder[],
+ spaces: [] as Space[],
+ folderCounts: {} as Record<number, number>,
+ moveNoteToFolder: jest.fn(),
+ moveNoteToSpace: jest.fn(),
+ createFolder: jest.fn(),
+ getSpaceFolders: jest.fn(() => [] as Folder[]),
};
const mockActionsState = {
@@ -208,16 +218,53 @@ jest.mock('@/components/ui/SystemIcon', () => ({
}));
jest.mock('@/components/notes/NoteActionsMenu', () => ({
- NoteActionsMenu: ({ onShare }: { onShare: () => void }) => {
- const { Pressable, Text } = require('react-native');
+ NoteActionsMenu: ({
+ onShare,
+ onCopyGeneratedNote,
+ onViewTranscript,
+ }: {
+ onShare: () => void;
+ onCopyGeneratedNote?: () => void;
+ onViewTranscript?: () => void;
+ }) => {
+ const { Pressable, Text, View } = require('react-native');
return (
- <Pressable onPress={onShare}>
- <Text>Share note</Text>
- </Pressable>
+ <View>
+ <Pressable onPress={onShare}>
+ <Text>Share note</Text>
+ </Pressable>
+ {onCopyGeneratedNote ? (
+ <Pressable onPress={onCopyGeneratedNote}>
+ <Text>Copy Notes</Text>
+ </Pressable>
+ ) : null}
+ {onViewTranscript ? (
+ <Pressable onPress={onViewTranscript}>
+ <Text>View Transcript</Text>
+ </Pressable>
+ ) : null}
+ </View>
);
},
}));
+jest.mock('@/components/notes/TranscriptSheet', () => ({
+ TranscriptSheet: ({
+ visible,
+ onExport,
+ }: {
+ visible: boolean;
+ onExport: (format: 'md' | 'txt') => void;
+ }) => {
+ const { Pressable, Text } = require('react-native');
+ return visible ? (
+ <Pressable onPress={() => onExport('txt')}>
+ <Text>Export transcript</Text>
+ </Pressable>
+ ) : null;
+ },
+}));
+
jest.mock('@/components/notes/MarkdownRenderer', () => ({
MarkdownRenderer: ({ content }: { content: string }) =>
(() => {
@@ -242,6 +289,14 @@ jest.mock('@/components/notes/VoiceprintSuggestionSheet', () => ({
VoiceprintSuggestionSheet: () => null,
}));
+jest.mock('@/components/notes/MoveToFolderSheet', () => ({
+ MoveToFolderSheet: ({ visible }: { visible: boolean }) =>
+ (() => {
+ const { Text: MockText } = require('react-native');
+ return visible ? <MockText testID="move-sheet">move-sheet</MockText> : null;
+ })(),
+}));
+
jest.mock('@/components/notes/NoteChatSheet', () => ({
NoteChatSheet: () => null,
}));
@@ -480,3 +535,153 @@ it('flushes a meeting title without replacing its structured transcript with bod
screen.unmount();
expect(mockUpdateNote).toHaveBeenCalledTimes(1);
});
+
+describe('NoteEditorScreen — using the server copy mid-edit', () => {
+ it('drops the unsaved edit to the generated notes and shows the server version', async () => {
+ mockNote = note({ enhancedContent: '## Local notes' });
+ mockNotesState.notes = [mockNote];
+ mockGetConflictedNote.mockReturnValue({
+ id: 7,
+ title: 'Customer Planning',
+ conflictServerNote: remoteNote({ enhanced_content: '## Server notes' }),
+ });
+ const { getByTestId, getByText, queryByTestId } = render(<NoteEditorScreen />);
+
+ fireEvent.press(getByTestId('enhanced-edit'));
+ fireEvent.changeText(getByTestId('enhanced-editor'), '## Mine');
+
+ // The repository now holds the server's copy.
+ mockNote = note({ enhancedContent: '## Server notes' });
+ mockNotesState.notes = [mockNote];
+ act(() => {
+ fireEvent.press(getByTestId('conflict-banner-use-server'));
+ });
+ // Outlast the 800 ms save debounce.
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 900));
+ });
+
+ const savedEnhanced = mockUpdateNote.mock.calls.map(([, updates]) => updates.enhancedContent);
+ expect(savedEnhanced).not.toContain('## Mine');
+ expect(queryByTestId('enhanced-editor')).toBeNull();
+ expect(getByText('## Server notes')).toBeTruthy();
+ });
+});
+
+it('publishes an unfinished edit to the generated notes when sharing', () => {
+ mockNote = note({ enhancedContent: '## Summary' });
+ mockNotesState.notes = [mockNote];
+ const screen = render(<NoteEditorScreen />);
+ fireEvent.press(screen.getByTestId('enhanced-edit'));
+ fireEvent.changeText(screen.getByTestId('enhanced-editor'), '## Summary\n- Shared');
+ fireEvent.press(screen.getByText('Share note'));
+ fireEvent.press(screen.getByText('Create test link'));
+ expect(mockUpdateNote).toHaveBeenCalledWith(7, { enhancedContent: '## Summary\n- Shared' });
+});
+
+it('exports an unfinished edit to the generated notes', () => {
+ mockNote = note({ enhancedContent: '## Summary' });
+ mockNotesState.notes = [mockNote];
+ // The store re-reads the saved note, as the repository does.
+ mockUpdateNote.mockImplementationOnce((_id: number, updates: Partial<Note>) => {
+ mockNote = { ...mockNote, ...updates };
+ });
+ const screen = render(<NoteEditorScreen />);
+ fireEvent.press(screen.getByTestId('enhanced-edit'));
+ fireEvent.changeText(screen.getByTestId('enhanced-editor'), '## Summary\n- Exported');
+ fireEvent.press(screen.getByText('Share note'));
+ fireEvent.press(screen.getByText('Export Markdown'));
+ expect(exportNote).toHaveBeenCalledWith(
+ expect.objectContaining({ content: '## Summary\n- Exported' }),
+ 'md',
+ );
+});
+
+it('exports only the title from a transcript that is still being made', () => {
+ mockNote = note({ noteType: 'meeting', transcriptionStatus: 'transcribing' });
+ mockNotesState.notes = [mockNote];
+ mockSegments = [];
+ const screen = render(<NoteEditorScreen />);
+ expect(screen.getByText('Transcribing audio...')).toBeTruthy();
+ fireEvent.press(screen.getByText('Share note'));
+ fireEvent.press(screen.getByText('Export Markdown'));
+ expect(exportNote).toHaveBeenCalledWith(expect.objectContaining({ content: '' }), 'md');
+});
+
+it('copies an unfinished edit to the generated notes', () => {
+ mockNote = note({ enhancedContent: '## Summary' });
+ mockNotesState.notes = [mockNote];
+ mockUpdateNote.mockImplementationOnce((_id: number, updates: Partial<Note>) => {
+ mockNote = { ...mockNote, ...updates };
+ });
+ const screen = render(<NoteEditorScreen />);
+ fireEvent.press(screen.getByTestId('enhanced-edit'));
+ fireEvent.changeText(screen.getByTestId('enhanced-editor'), '## Summary\n- Copied');
+ fireEvent.press(screen.getByText('Copy Notes'));
+ expect(mockUpdateNote).toHaveBeenCalledWith(7, { enhancedContent: '## Summary\n- Copied' });
+ expect(Clipboard.setStringAsync).toHaveBeenCalledWith('## Summary\n- Copied');
+});
+
+it('exports the transcript as a file once notes are generated', () => {
+ mockNote = note({ noteType: 'meeting', diarizationEnabled: 1, enhancedContent: '## Summary' });
+ mockNotesState.notes = [mockNote];
+ mockSegments = [
+ {
+ id: 1,
+ noteId: 7,
+ text: 'Spoken words',
+ startMs: 0,
+ endMs: 1000,
+ speakerLabel: null,
+ sortOrder: 0,
+ } as unknown as Segment,
+ ];
+ const screen = render(<NoteEditorScreen />);
+ fireEvent.press(screen.getByText('View Transcript'));
+ fireEvent.press(screen.getByText('Export transcript'));
+ expect(exportNote).toHaveBeenCalledWith(
+ {
+ title: 'Customer Planning Transcript',
+ content: expect.stringContaining('Spoken words'),
+ },
+ 'txt',
+ );
+});
+
+describe('NoteEditorScreen — changes pulled while the note is open', () => {
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
+ it('shows a pulled edit instead of saving the old text over it', () => {
+ jest.useFakeTimers();
+ const screen = render(<NoteEditorScreen />);
+
+ mockNote = note({ title: 'Renamed on desktop', content: 'Edited on desktop.' });
+ mockNotesState.notes = [mockNote];
+ screen.rerender(<NoteEditorScreen />);
+
+ const input = screen.getByPlaceholderText('Type or dictate…');
+ expect(input.props.value).toBe('Edited on desktop.');
+ expect(screen.getByPlaceholderText('Title').props.value).toBe('Renamed on desktop');
+
+ fireEvent.changeText(input, 'Edited on desktop. And here.');
+ act(() => {
+ jest.advanceTimersByTime(800);
+ });
+ expect(mockUpdateNote).toHaveBeenCalledTimes(1);
+ expect(mockUpdateNote).toHaveBeenCalledWith(7, { content: 'Edited on desktop. And here.' });
+ });
+
+ it('keeps what you are typing when a pull lands before it saves', () => {
+ jest.useFakeTimers();
+ const screen = render(<NoteEditorScreen />);
+ fireEvent.changeText(screen.getByPlaceholderText('Type or dictate…'), 'Typed here.');
+
+ mockNote = note({ content: 'Edited on desktop.' });
+ mockNotesState.notes = [mockNote];
+ screen.rerender(<NoteEditorScreen />);
+
+ expect(screen.getByPlaceholderText('Type or dictate…').props.value).toBe('Typed here.');
+ });
+});
diff --git a/openwhispr-mobile/src/store/__tests__/useNotesStore.meeting.test.ts b/openwhispr-mobile/src/store/__tests__/useNotesStore.meeting.test.ts
index 7be0fd522..b8cce8290 100644
--- a/openwhispr-mobile/src/store/__tests__/useNotesStore.meeting.test.ts
+++ b/openwhispr-mobile/src/store/__tests__/useNotesStore.meeting.test.ts
@@ -672,6 +672,61 @@ describe('runMeetingPipeline', () => {
);
});
+ describe('with generated notes already on the note', () => {
+ const meetingNote = (enhancedContent: string | null) => ({
+ id: 7,
+ title: 'Planning Sync',
+ content: 'Prioritize onboarding.',
+ noteType: 'meeting',
+ isPrivate: 0,
+ deletedAt: null,
+ enhancedContent,
+ enhancedAtContentHash: null,
+ });
+
+ beforeEach(() => {
+ mockAuthState.user = signedInUser;
+ (notesRepository.getActions as jest.Mock).mockReturnValue([
+ { id: 1, name: 'Generate Notes', prompt: 'Transform this meeting.', isDefault: 1 },
+ ]);
+ (notesRepository.getSegments as jest.Mock).mockReturnValue([segment('Ship the fix.')]);
+ (ReasoningService.processText as jest.Mock).mockResolvedValue({
+ text: 'Fresh notes',
+ model: 'test',
+ });
+ });
+
+ const wroteGeneratedNotes = (): boolean =>
+ (notesRepository.updateNote as jest.Mock).mock.calls.some(
+ ([, updates]) => updates.enhancedContent !== undefined,
+ );
+
+ it('keeps notes the user already has instead of generating over them', async () => {
+ (notesRepository.getNoteById as jest.Mock).mockReturnValue(meetingNote('## My edited notes'));
+
+ await useNotesStore.getState().runMeetingPipeline(7, 'file://meeting.wav', 2);
+
+ expect(ReasoningService.processText).not.toHaveBeenCalledWith(
+ expect.objectContaining({ temperature: 0.3 }),
+ );
+ expect(wroteGeneratedNotes()).toBe(false);
+ });
+
+ it('drops the generated notes when the user wrote some while they were being made', async () => {
+ let current = meetingNote(null);
+ (notesRepository.getNoteById as jest.Mock).mockImplementation(() => current);
+ (ReasoningService.processText as jest.Mock).mockImplementation(async () => {
+ current = meetingNote('## Written meanwhile');
+ return { text: 'Fresh notes', model: 'test' };
+ });
+
+ await useNotesStore.getState().runMeetingPipeline(7, 'file://meeting.wav', 2);
+
+ expect(ReasoningService.processText).toHaveBeenCalled();
+ expect(wroteGeneratedNotes()).toBe(false);
+ });
+ });
+
it('writes On-Device meeting notes through the chunked local path when signed in', async () => {
mockAuthState.user = signedInUser;
mockConfigState.config.inference = { notes: { mode: 'local' } };
diff --git a/openwhispr-mobile/src/store/useNotesStore.ts b/openwhispr-mobile/src/store/useNotesStore.ts
index 4e4ec42f0..cacc206ab 100644
--- a/openwhispr-mobile/src/store/useNotesStore.ts
+++ b/openwhispr-mobile/src/store/useNotesStore.ts
@@ -158,6 +158,9 @@ const canUseCloudForMeetingNote = (note: Note | null | undefined): note is Note
const autoGenerateMeetingNotes = async (noteId: number): Promise<void> => {
const note = notesRepository.getNoteById(noteId);
if (!note || note.deletedAt || note.noteType !== 'meeting') return;
+ // Generated notes the user already has (edited, or from an action they ran) are never replaced
+ // automatically, e.g. by retrying a transcript; the Enhanced tab marks them stale instead.
+ if (note.enhancedContent?.trim()) return;
const action = notesRepository.getActions().find(isDefaultGenerateNotesAction);
if (!action) return;
@@ -200,7 +203,10 @@ const autoGenerateMeetingNotes = async (noteId: number): Promise<void> => {
});
const writeGeneratedText = (generatedText: string) => {
- if (!generatedText.trim()) return;
+ // The user may have run an action or written notes while these were generated.
+ if (!generatedText.trim() || notesRepository.getNoteById(noteId)?.enhancedContent?.trim()) {
+ return;
+ }
notesRepository.updateNote(noteId, {
enhancedContent: generatedText,
enhancementPrompt: action.prompt,
@@ -359,6 +365,8 @@ interface NotesStore {
deleteFolderSafe: (id: number) => void;
/** Creates in the private space unless `spaceId` names a team space to create it inside. */
createFolder: (name: string, spaceId?: number) => Folder;
+ /** Folders of any space, read from the repository. `spaceFolders` only caches the browsed space's. */
+ getSpaceFolders: (spaceId: number) => Folder[];
renameFolder: (id: number, name: string) => void;
setNotePrivacy: (id: number, isPrivate: boolean) => Promise<void>;
/** Data source for the conflict banner (see NoteEditorScreen) — the parked 409 row for this note, if any. */
@@ -560,6 +568,8 @@ export const useNotesStore = create<NotesStore>((set, get) => ({
get().loadFolders();
},
+ getSpaceFolders: (spaceId) => notesRepository.getFoldersBySpace(spaceId),
+
moveNoteToFolder: (noteId, folderId) => {
notesRepository.moveNoteToFolder(noteId, folderId);
get().loadNotes();
diff --git a/openwhispr-mobile/src/sync/__tests__/pushNotes.test.ts b/openwhispr-mobile/src/sync/__tests__/pushNotes.test.ts
index 0b6821577..88037a753 100644
--- a/openwhispr-mobile/src/sync/__tests__/pushNotes.test.ts
+++ b/openwhispr-mobile/src/sync/__tests__/pushNotes.test.ts
@@ -197,6 +197,27 @@ describe('pushNotes calendar context', () => {
expect.objectContaining({ id: 1 }),
'remote-note-1',
'2026-06-26T11:00:00.000Z',
+ undefined,
+ undefined,
+ );
+ });
+
+ it('passes the server’s creation time from an update on to the note', async () => {
+ mockNotesRepository.getPendingNotes.mockReturnValue([note({ remoteId: 'remote-note-1' })]);
+ mockUpdateNoteRemote.mockResolvedValueOnce({
+ id: 'remote-note-1',
+ created_at: '2026-06-01T09:00:00.000Z',
+ updated_at: '2026-06-26T11:00:00.000Z',
+ });
+
+ await pushNotes();
+
+ expect(mockNotesRepository.markNotePushed).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 1 }),
+ 'remote-note-1',
+ '2026-06-26T11:00:00.000Z',
+ undefined,
+ '2026-06-01T09:00:00.000Z',
);
});
diff --git a/openwhispr-mobile/src/sync/pushNotes.ts b/openwhispr-mobile/src/sync/pushNotes.ts
index b0cddf9f5..46a33a28c 100644
--- a/openwhispr-mobile/src/sync/pushNotes.ts
+++ b/openwhispr-mobile/src/sync/pushNotes.ts
@@ -485,7 +485,13 @@ export async function pushNotes(
checkpoint(true);
const server = await updateNote(u.remoteId, u.payload);
checkpoint();
- notesRepository.markNotePushed(u.pushed, server.id, server.updated_at);
+ notesRepository.markNotePushed(
+ u.pushed,
+ server.id,
+ server.updated_at,
+ undefined,
+ server.created_at,
+ );
if (u.pushedTranscript) {
const { raw, segmentIds, speakerIds } = u.pushedTranscript;
notesRepository.markTranscriptPushed(u.localId, raw, segmentIds, speakerIds);