Skip to content
Merged
5 changes: 5 additions & 0 deletions .changeset/error-states-keyboard.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'lyra': patch
---

Problems with a recording (the microphone lost, computer audio not being recorded) now show on Home and People too, not only in the session you left. When a change can't be saved, the session keeps a warning on screen until it's dismissed or the next change is saved, instead of a six-second notice shown once. Errors when starting or finishing a recording, saving a voice or naming a speaker no longer start with "Error invoking remote method". Section headings in the transcript can be focused and opened with Shift+F10 or the menu key, references in your notes can be followed with Ctrl+Enter (⌘↩ on macOS), the shortcut setting tells screen readers what it sets and its current shortcut and lets Tab move on while it listens, and a recording that never started is announced as cancelled rather than stopped.
33 changes: 26 additions & 7 deletions apps/lyra/src/renderer/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,9 @@ export default function App(): React.JSX.Element {
create,
remove,
restore,
flush
flush,
saveFailed,
dismissSaveFailed
} = usePages()
const [status, setStatus] = useState<WhisperStatus>({ state: 'idle' })
const [copied, setCopied] = useState(false)
Expand Down Expand Up @@ -515,6 +517,21 @@ export default function App(): React.JSX.Element {
const activity = dockActivity(status, dictation.progress ? behindLabel(dictation.progress) : null)
const activityElement = activity ? <ActivityToast activity={activity} /> : null

// A recording keeps going when the session is left, so its problems (the mic lost, computer
// audio not recorded, the disk full) show on Home and People too, not only in the session.
const recorderMessages = (
<>
<DictationMessage error={dictation.error} notice={dictation.notice} onDismiss={dictation.dismissMessage} />
{dictation.systemAudioMessageShown ? (
<SystemAudioMessage
state={dictation.systemAudio}
onRetry={dictation.retrySystemAudio}
onDismiss={dictation.dismissSystemAudio}
/>
) : null}
</>
)

// Hovering or focusing the toast holds it; F6 reaches its button from anywhere (see onKey).
const toastElement = toast ? (
<Toast
Expand Down Expand Up @@ -1194,14 +1211,15 @@ export default function App(): React.JSX.Element {
}
/>
) : null}
<DictationMessage error={dictation.error} notice={dictation.notice} onDismiss={dictation.dismissMessage} />
{dictation.systemAudioMessageShown ? (
<SystemAudioMessage
state={dictation.systemAudio}
onRetry={dictation.retrySystemAudio}
onDismiss={dictation.dismissSystemAudio}
{saveFailed ? (
<Toast
tone="error"
role="alert"
text="Lyra couldn’t save your latest changes to this session. Copy anything important, then reopen it."
onDismiss={dismissSaveFailed}
/>
) : null}
{recorderMessages}
{toastElement}
</ToastStack>
</div>
Expand Down Expand Up @@ -1272,6 +1290,7 @@ export default function App(): React.JSX.Element {
)}
<ToastStack>
{activityElement}
{recorderMessages}
{toastElement}
</ToastStack>
</div>
Expand Down
12 changes: 10 additions & 2 deletions apps/lyra/src/renderer/src/components/HotkeyInput.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { useState, type KeyboardEvent } from 'react'
import { isMac } from '../lib/format'
import { shortcutButtonLabel } from '../lib/keys'

type Props = {
value: string
onChange: (accelerator: string) => void
/** What the shortcut does, for its accessible name ("Session shortcut"). */
label: string
}

const MODIFIER_KEYS = new Set(['Control', 'Meta', 'Alt', 'Shift', 'AltGraph', 'CapsLock'])
Expand Down Expand Up @@ -64,11 +67,16 @@ export function displayAccelerator(accelerator: string): string {
return parts.join(isMac ? '' : '+')
}

export function HotkeyInput({ value, onChange }: Props) {
export function HotkeyInput({ value, onChange, label }: Props) {
const [recording, setRecording] = useState(false)

const onKeyDown = (event: KeyboardEvent<HTMLButtonElement>): void => {
if (!recording) return
// Tab alone can't be a shortcut: let it move focus on, so the keyboard is never stuck here.
if (event.key === 'Tab' && !event.ctrlKey && !event.metaKey && !event.altKey) {
setRecording(false)
return
}
event.preventDefault()
event.stopPropagation()
if (event.key === 'Escape') {
Expand All @@ -92,7 +100,7 @@ export function HotkeyInput({ value, onChange }: Props) {
setRecording(false)
}}
onKeyDown={onKeyDown}
aria-label="Change shortcut"
aria-label={shortcutButtonLabel(label, displayAccelerator(value), recording)}
>
{recording ? 'Press a shortcut…' : displayAccelerator(value)}
</button>
Expand Down
12 changes: 12 additions & 0 deletions apps/lyra/src/renderer/src/components/NotesEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,18 @@ export function NotesEditor({ value, onChange, placeholder, onReference, ref }:
if (!href.startsWith(REFERENCE_PREFIX)) return false
onReferenceRef.current?.(decodeURIComponent(href.slice(REFERENCE_PREFIX.length)))
return true
},
// Ctrl+Enter (⌘↩ on macOS) with the caret on a reference follows it, as a click does.
// Runs before the editor's own keymap, so elsewhere it still inserts a line break.
handleKeyDown: (view, event) => {
if (event.key !== 'Enter' || !(event.metaKey || event.ctrlKey)) return false
const { $from } = view.state.selection
const marks = [...$from.marks(), ...($from.nodeAfter?.marks ?? []), ...($from.nodeBefore?.marks ?? [])]
const href: unknown = marks.find((mark) => mark.type.name === 'link')?.attrs.href
if (typeof href !== 'string' || !href.startsWith(REFERENCE_PREFIX)) return false
event.preventDefault()
onReferenceRef.current?.(decodeURIComponent(href.slice(REFERENCE_PREFIX.length)))
return true
}
},
onUpdate: ({ editor: current }) => {
Expand Down
3 changes: 2 additions & 1 deletion apps/lyra/src/renderer/src/components/People.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { Person } from '../../../shared/types'
import { openMicrophone, startCapture, type CaptureHandle } from '../audio/capture'
import { SAMPLE_RATE } from '../../../shared/audio/vad'
import { perform } from '../lib/history'
import { ipcErrorMessage } from '../lib/ipcError'
import { log } from '../lib/log'
import { notify } from '../lib/toast'
import { ConfirmDialog } from './ConfirmDialog'
Expand Down Expand Up @@ -186,7 +187,7 @@ function Enroll({ micDeviceId, onDone }: EnrollProps) {
if (attempt.current === run) attempt.current = null
if (stopped()) return
log('people', 'enroll failed', errorText(caught))
setError(caught instanceof Error ? caught.message : 'Could not save the voice')
setError(ipcErrorMessage(caught, 'Couldn’t save the voice.'))
setAnnouncement('')
setPhase('idle')
}
Expand Down
6 changes: 5 additions & 1 deletion apps/lyra/src/renderer/src/components/Settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,11 @@ function StartupSection({ settings, update }: SectionProps) {
label="Start or stop a session"
hint="Works from any app, even when Lyra is hidden."
>
<HotkeyInput value={settings.hotkey} onChange={(hotkey) => void update({ hotkey })} />
<HotkeyInput
label="Session shortcut"
value={settings.hotkey}
onChange={(hotkey) => void update({ hotkey })}
/>
{settings.hotkey !== DEFAULT_HOTKEY ? (
<Button type="button" onClick={() => void update({ hotkey: DEFAULT_HOTKEY })}>
Reset
Expand Down
40 changes: 34 additions & 6 deletions apps/lyra/src/renderer/src/components/Transcript.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,12 @@ import { useAnchoredPosition } from '../hooks/useAnchoredPosition'
import { useDialogFocus } from '../hooks/useDialogFocus'
import { rovingIndex } from '../lib/focus'
import { clockLabel as clock } from '../lib/format'
import { ipcErrorMessage } from '../lib/ipcError'
import { log } from '../lib/log'
import { unusedSpeakerName } from '../lib/status'
import { notify } from '../lib/toast'
import { sendToPromptApp, usePromptApps } from '../hooks/usePromptApps'
import { useContextMenu } from './ContextMenu'
import { useContextMenu, type MenuItem } from './ContextMenu'
import { pausePlayback, play, playbackState, resumePlayback, stopPlayback, usePlayback } from '../lib/playback'
import { scrollBehavior } from '../lib/motion'
import { defaultHighlight, GROUP_LABEL, speakerOptions, type SpeakerOption } from '../lib/speakerOptions'
Expand Down Expand Up @@ -326,7 +327,7 @@ function SpeakerPicker({
onClose()
} catch (caught) {
log('transcript', 'could not name speaker', String(caught))
setError(caught instanceof Error ? caught.message : 'Could not name this speaker')
setError(ipcErrorMessage(caught, 'Couldn’t name this speaker.'))
}
}

Expand Down Expand Up @@ -1150,13 +1151,33 @@ export function Transcript({
}
return transcript.slice(from, to)
}
/** A section heading's menu: from a right-click, or Shift+F10 and the menu key on the heading. */
const sectionMenu = (
event: ReactMouseEvent,
event: ReactMouseEvent | ReactKeyboardEvent,
first: TranscriptSegment,
section: { start: number; title: string; summary: string }
): void => {
const items = sectionItems(first, section)
if ('clientX' in event) {
// Already opened from the keydown; this is the same press.
if (Date.now() - keyboardMenuAt.current < KEYBOARD_MENU_MS) {
event.preventDefault()
return
}
speakerMenu.open(event, section.title, items)
return
}
event.preventDefault()
keyboardMenuAt.current = Date.now()
const rect = event.currentTarget.getBoundingClientRect()
speakerMenu.openAt({ x: rect.left + 8, y: rect.bottom, label: section.title, items })
}
const sectionItems = (
first: TranscriptSegment,
section: { start: number; title: string; summary: string }
): MenuItem[] => {
const label = `§ ${section.title} · ${clock(section.start)}`
speakerMenu.open(event, section.title, [
return [
{
label: 'Reference in notes',
icon: <NoteIcon />,
Expand Down Expand Up @@ -1193,7 +1214,7 @@ export function Transcript({
notify('Copied the section summary')
}
}
])
]
}

return (
Expand Down Expand Up @@ -1291,10 +1312,17 @@ export function Transcript({
{section ? (
// Sticks to the top of the transcript while its section is on screen; the next
// section's heading takes its place.
// Focusable, so its menu (reference, play, copy) is reachable without a mouse.
<h3
className="section-heading sticky top-0 z-[2] m-0 -mx-2 flex cursor-context-menu items-baseline gap-2.5 border-b border-border bg-background/95 px-4 py-1.5 text-body-sm font-semibold backdrop-blur-[2px]"
className="section-heading sticky top-0 z-[2] m-0 -mx-2 flex cursor-context-menu items-baseline gap-2.5 border-b border-border bg-background/95 px-4 py-1.5 text-body-sm font-semibold backdrop-blur-[2px] focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring"
data-section-start={section.start}
tabIndex={0}
aria-haspopup="menu"
aria-keyshortcuts="Shift+F10"
onContextMenu={(event) => sectionMenu(event, line, section)}
onKeyDown={(event) => {
if ((event.key === 'F10' && event.shiftKey) || event.key === 'ContextMenu') sectionMenu(event, line, section)
}}
>
<span className="font-mono text-label font-medium text-brand-text">{clock(section.start)}</span>
<span className="min-w-0 truncate">{section.title}</span>
Expand Down
6 changes: 4 additions & 2 deletions apps/lyra/src/renderer/src/hooks/useDictation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
import { SessionRecorder } from '../audio/sessionRecorder'
import { rms } from '../../../shared/audio/vad'
import type { TranscriptProgress } from '../../../shared/types'
import { ipcErrorMessage } from '../lib/ipcError'
import { log } from '../lib/log'

export type DictationPhase = 'idle' | 'starting' | 'listening' | 'finishing'
Expand Down Expand Up @@ -354,7 +355,8 @@ export function useDictation({ getDeviceId }: Options) {
if (cancelled()) return 'cancelled'
log('dictation', 'failed to start', errorText(caught))
if (owner.current === attempt) {
setError(caught instanceof Error ? caught.message : 'Recording failed')
// Main's errors come wrapped ("Error invoking remote method …"); the wrapper goes to the log.
setError(ipcErrorMessage(caught, 'Couldn’t start recording.'))
setSystemAudio('off')
setPageId(null)
setPhase('idle')
Expand Down Expand Up @@ -391,7 +393,7 @@ export function useDictation({ getDeviceId }: Options) {
await current.stop()
} catch (caught) {
log('dictation', 'stop failed', errorText(caught))
setError(`The recording stopped, but finishing its transcript failed: ${errorText(caught)}`)
setError(`The recording stopped, but finishing its transcript failed: ${ipcErrorMessage(caught, 'something went wrong.')}`)
} finally {
// A newer session (started once this one settled) owns the state from here.
if (owner.current === current.owner) {
Expand Down
25 changes: 18 additions & 7 deletions apps/lyra/src/renderer/src/hooks/usePages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import {
import type { Span, TranscriptEdit } from '../../../shared/transcriptOverlay'
import { log } from '../lib/log'
import { SessionReplica } from '../lib/sessionReplica'
import { notify } from '../lib/toast'
import { latest } from './latest'

/** What the editor shows of the open session. */
Expand All @@ -34,7 +33,7 @@ type Open = {
replica: SessionReplica
/** Draws the session's current state. */
render: () => void
/** An edit main refused: it's gone from the view; the user is told once. */
/** An edit main refused: it's gone from the view, and the session shows it until dismissed. */
failed: (error: unknown) => void
dispose: () => void
}
Expand All @@ -54,6 +53,11 @@ export function usePages() {
const [opens] = useState(latest)
/** The session the newest `attach` is opening. */
const wanted = useRef<string | null>(null)
/**
* The session an edit was refused for, until one lands or the person dismisses it: a lasting
* `role="alert"`, never only a toast (docs/STATES.md).
*/
const [refusedIn, setRefusedIn] = useState<string | null>(null)

const show = (page: OpenPage | null): void => {
currentRef.current = page
Expand Down Expand Up @@ -140,7 +144,6 @@ export function usePages() {
return sent
}
const replica = new SessionReplica(id, state, send)
let warnedUnsaved = false
const opened: Open = {
replica,
render: () => {
Expand All @@ -160,9 +163,7 @@ export function usePages() {
failed: (error) => {
log('pages', 'could not save change', String(error))
opened.render()
if (warnedUnsaved) return
warnedUnsaved = true
notify('Lyra couldn’t save your latest changes to this session. Copy anything important, then reopen it.')
if (session.current === opened) setRefusedIn(id)
},
dispose: stop
}
Expand All @@ -178,9 +179,16 @@ export function usePages() {
const apply = useCallback((ops: SessionOp[], undoable: 'step' | 'typing' | 'none') => {
const open = session.current
if (!open) return
open.replica.edit(ops, undoable).catch(open.failed)
open.replica.edit(ops, undoable).then(
() => {
// Edits are taken again: the warning about the refused one has done its job.
setRefusedIn((refused) => (refused === open.replica.id ? null : refused))
},
open.failed
)
open.render()
}, [])
const dismissSaveFailed = useCallback(() => setRefusedIn(null), [])

const edit = useCallback(
(changes: Edit) => {
Expand Down Expand Up @@ -351,6 +359,9 @@ export function usePages() {
pages,
current,
currentRef,
/** An edit to the open session was refused, and nothing has landed since. */
saveFailed: refusedIn !== null && refusedIn === current?.id,
dismissSaveFailed,
edit,
editSummary,
editSegment,
Expand Down
17 changes: 16 additions & 1 deletion apps/lyra/src/renderer/src/lib/keys.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
import { keyName } from './keys'
import { keyName, shortcutButtonLabel } from './keys'

describe('keyName', () => {
it('uses symbols on macOS', () => {
Expand All @@ -15,3 +15,18 @@ describe('keyName', () => {
expect(keyName('Esc', false)).toBe('Esc')
})
})

describe('shortcutButtonLabel', () => {
it('names the setting and holds the shortcut it shows', () => {
const name = shortcutButtonLabel('Session shortcut', 'Ctrl+Shift+Space', false)
expect(name).toContain('Session shortcut')
expect(name).toContain('Ctrl+Shift+Space')
})

it('says how to finish or back out while it listens', () => {
const name = shortcutButtonLabel('Session shortcut', 'Ctrl+Shift+Space', true)
// The visible text then is "Press a shortcut…"; the name contains it (WCAG 2.5.3).
expect(name.toLowerCase()).toContain('press a shortcut')
expect(name).toContain('Esc to cancel')
})
})
8 changes: 8 additions & 0 deletions apps/lyra/src/renderer/src/lib/keys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,11 @@ export function keyName(key: NamedKey, mac: boolean): string {
return mac ? '⌘⌫' : 'Del'
}
}

/**
* The shortcut button's accessible name: what it sets and its current shortcut (the visible
* text, so voice control can say it), or, while it listens, how to finish or back out.
*/
export function shortcutButtonLabel(setting: string, shortcut: string, listening: boolean): string {
return listening ? `${setting}: press a shortcut, or Esc to cancel` : `${setting}: ${shortcut}. Change`
}
7 changes: 6 additions & 1 deletion apps/lyra/src/renderer/src/lib/status.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,12 @@ describe('phaseAnnouncement', () => {
'Recording stopped. Finishing the transcript'
)
expect(phaseAnnouncement('finishing', 'idle')).toBe('Transcript finished')
expect(phaseAnnouncement('starting', 'idle')).toBe('Recording stopped')
expect(phaseAnnouncement('listening', 'idle')).toBe('Recording stopped')
})

it('never says a recording that never started has stopped', () => {
// Mic access denied, or Stop pressed while the model warmed up: the alert says why.
expect(phaseAnnouncement('starting', 'idle')).toBe('Recording cancelled')
})
})

Expand Down
Loading
Loading