diff --git a/.changeset/auto-updates.md b/.changeset/auto-updates.md new file mode 100644 index 0000000..7aea66b --- /dev/null +++ b/.changeset/auto-updates.md @@ -0,0 +1,5 @@ +--- +'lyra': minor +--- + +Lyra now keeps itself up to date: when a new release is out on GitHub it downloads in the background and installs the next time Lyra restarts, with a "Restart to update" row in Activity if you'd rather not wait. Settings → About has a new Updates section where you can choose Automatically, Ask first (the old behaviour) or Only when I check, see whether you're on the latest version, and check now. Macs without a signed build still open the releases page instead of downloading. diff --git a/apps/lyra/src/main/diagnosticsText.test.ts b/apps/lyra/src/main/diagnosticsText.test.ts index c63668f..387887f 100644 --- a/apps/lyra/src/main/diagnosticsText.test.ts +++ b/apps/lyra/src/main/diagnosticsText.test.ts @@ -9,6 +9,7 @@ const settings: Settings = { micDeviceId: null, hotkey: 'Alt+Space', launchAtLogin: false, + updates: 'auto', micPrompt: { enabled: false, ignoredApps: [] }, meetingPrompt: false, audioRetentionDays: 30, diff --git a/apps/lyra/src/main/ipcSchemas.ts b/apps/lyra/src/main/ipcSchemas.ts index 4c0c733..2e0ec7e 100644 --- a/apps/lyra/src/main/ipcSchemas.ts +++ b/apps/lyra/src/main/ipcSchemas.ts @@ -52,6 +52,7 @@ const SettingsPatchSchema = z micDeviceId: field.micDeviceId.exactOptional(), hotkey: field.hotkey.exactOptional(), launchAtLogin: field.launchAtLogin.exactOptional(), + updates: field.updates.exactOptional(), micPrompt: field.micPrompt.exactOptional(), meetingPrompt: field.meetingPrompt.exactOptional(), audioRetentionDays: field.audioRetentionDays.exactOptional(), diff --git a/apps/lyra/src/main/meeting/writers.test.ts b/apps/lyra/src/main/meeting/writers.test.ts index 3ffd7c6..746ea33 100644 --- a/apps/lyra/src/main/meeting/writers.test.ts +++ b/apps/lyra/src/main/meeting/writers.test.ts @@ -89,6 +89,7 @@ describe('chooseWriter', () => { micDeviceId: null, hotkey: 'Alt+Space', launchAtLogin: false, + updates: 'auto', micPrompt: { enabled: false, ignoredApps: [] }, meetingPrompt: false, audioRetentionDays: null, diff --git a/apps/lyra/src/main/settings.ts b/apps/lyra/src/main/settings.ts index d5d9d91..9b57db6 100644 --- a/apps/lyra/src/main/settings.ts +++ b/apps/lyra/src/main/settings.ts @@ -17,6 +17,8 @@ export function defaultSettings(): Settings { micDeviceId: null, hotkey: 'CommandOrControl+Shift+Space', launchAtLogin: false, + // On: it only fetches Lyra's own releases, and installs on the next restart, never mid-session. + updates: 'auto', micPrompt: { enabled: false, ignoredApps: [] }, // On: it only asks, never records, and runs on this computer (see meetingApps.ts). meetingPrompt: true, diff --git a/apps/lyra/src/main/settingsFile.test.ts b/apps/lyra/src/main/settingsFile.test.ts index a61f0e3..92a7c6d 100644 --- a/apps/lyra/src/main/settingsFile.test.ts +++ b/apps/lyra/src/main/settingsFile.test.ts @@ -52,6 +52,7 @@ describe('retentionUnread', () => { micDeviceId: null, hotkey: 'Alt+Space', launchAtLogin: false, + updates: 'auto', micPrompt: { enabled: false, ignoredApps: [] }, meetingPrompt: true, audioRetentionDays: 30, diff --git a/apps/lyra/src/main/tasks/smoke.ts b/apps/lyra/src/main/tasks/smoke.ts index 148e00b..da1af47 100644 --- a/apps/lyra/src/main/tasks/smoke.ts +++ b/apps/lyra/src/main/tasks/smoke.ts @@ -1701,6 +1701,21 @@ export async function runUiSmoke(win: BrowserWindow): Promise { if (!Array.isArray(modelStates) || modelStates.some((entry) => !['semanticSearch', 'localNotes'].includes(entry.feature) || typeof entry.model !== 'string')) { fail('model status: ' + JSON.stringify(modelStates)) } + // Updates: a test run never updates, so a check answers "unavailable" and fetches nothing; + // the mode is a setting, and an unknown one is refused. + await window.api.checkForUpdates() + const updateStatus = await new Promise((resolve) => { + const stop = window.api.onUpdateStatus((status) => { + stop() + resolve(status) + }) + }) + if (updateStatus.state !== 'unavailable') fail('update status in a test run: ' + JSON.stringify(updateStatus)) + const updatesBefore = (await window.api.getSettings()).updates + if (updatesBefore !== 'auto') fail('updates default: ' + JSON.stringify(updatesBefore)) + if ((await window.api.updateSettings({ updates: 'notify' })).updates !== 'notify') fail('updates: notify not saved') + if ((await window.api.updateSettings({ updates: 'sometimes' })).updates !== 'notify') fail('updates took an unknown mode') + await window.api.updateSettings({ updates: updatesBefore }) const stopModelStatus = window.api.onModelStatus(() => {}) if (typeof stopModelStatus !== 'function') fail('onModelStatus returned no unsubscribe') stopModelStatus() diff --git a/apps/lyra/src/main/updatePolicy.test.ts b/apps/lyra/src/main/updatePolicy.test.ts new file mode 100644 index 0000000..4fd08e1 --- /dev/null +++ b/apps/lyra/src/main/updatePolicy.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it } from 'vitest' +import { autoDownloads, checkMayStart, checksOnItsOwn, shownInActivity } from './updatePolicy' + +describe('autoDownloads', () => { + it('downloads on its own only in auto mode, where the app can replace itself', () => { + expect(autoDownloads('auto', true)).toBe(true) + expect(autoDownloads('auto', false)).toBe(false) + expect(autoDownloads('notify', true)).toBe(false) + expect(autoDownloads('off', true)).toBe(false) + }) +}) + +describe('checksOnItsOwn', () => { + it('checks on a timer unless updates are off', () => { + expect(checksOnItsOwn('auto')).toBe(true) + expect(checksOnItsOwn('notify')).toBe(true) + expect(checksOnItsOwn('off')).toBe(false) + }) +}) + +describe('checkMayStart', () => { + it('starts from a settled state', () => { + expect(checkMayStart('idle')).toBe(true) + expect(checkMayStart('latest')).toBe(true) + expect(checkMayStart('available')).toBe(true) + expect(checkMayStart('error')).toBe(true) + }) + + it('never interrupts a check, a download or an update waiting to install', () => { + expect(checkMayStart('checking')).toBe(false) + expect(checkMayStart('downloading')).toBe(false) + expect(checkMayStart('ready')).toBe(false) + expect(checkMayStart('unavailable')).toBe(false) + }) +}) + +describe('shownInActivity', () => { + it('keeps a background download quiet until it is ready', () => { + expect(shownInActivity('available', true)).toBe(false) + expect(shownInActivity('downloading', true)).toBe(false) + expect(shownInActivity('ready', true)).toBe(true) + }) + + it('shows the progress of a download the person started', () => { + expect(shownInActivity('available', false)).toBe(true) + expect(shownInActivity('downloading', false)).toBe(true) + }) + + it('always shows a failure and never a check or an up-to-date app', () => { + expect(shownInActivity('error', true)).toBe(true) + expect(shownInActivity('error', false)).toBe(true) + expect(shownInActivity('checking', false)).toBe(false) + expect(shownInActivity('latest', false)).toBe(false) + expect(shownInActivity('idle', false)).toBe(false) + }) +}) diff --git a/apps/lyra/src/main/updatePolicy.ts b/apps/lyra/src/main/updatePolicy.ts new file mode 100644 index 0000000..8abf584 --- /dev/null +++ b/apps/lyra/src/main/updatePolicy.ts @@ -0,0 +1,57 @@ +import type { UpdateMode } from '../shared/settings' +import type { UpdateStatus } from '../shared/types' + +/** + * Whether an update downloads as soon as one is found. Only in `auto`, and only where it can be + * installed in place: an unsigned Mac build can't replace itself, so its person is sent to the + * releases page instead, and downloading first would only waste the bandwidth. + */ +export function autoDownloads(mode: UpdateMode, canInstallInPlace: boolean): boolean { + return mode === 'auto' && canInstallInPlace +} + +/** Whether Lyra looks for updates on a timer, not only when asked. */ +export function checksOnItsOwn(mode: UpdateMode): boolean { + return mode !== 'off' +} + +/** + * Whether a new check may start now. Not while one is running, a download is under way or an + * update waits to be installed (checking again would only find the same release), nor in a + * development build. + */ +export function checkMayStart(state: UpdateStatus['state']): boolean { + switch (state) { + case 'idle': + case 'latest': + case 'available': + case 'error': + return true + case 'unavailable': + case 'checking': + case 'downloading': + case 'ready': + return false + } +} + +/** + * Whether Activity lists this status. A download Lyra started on its own stays out of sight until + * it's ready to install (docs/STATES.md: automatic work you didn't ask for shows nothing while it + * works); one the person started shows its progress. + */ +export function shownInActivity(state: UpdateStatus['state'], background: boolean): boolean { + switch (state) { + case 'available': + case 'downloading': + return !background + case 'ready': + case 'error': + return true + case 'unavailable': + case 'idle': + case 'checking': + case 'latest': + return false + } +} diff --git a/apps/lyra/src/main/updater.ts b/apps/lyra/src/main/updater.ts index cfa09ac..c0625c7 100644 --- a/apps/lyra/src/main/updater.ts +++ b/apps/lyra/src/main/updater.ts @@ -1,43 +1,82 @@ import { app, BrowserWindow, ipcMain, shell } from 'electron' -import { spawnSync } from 'node:child_process' +import { execFile } from 'node:child_process' import { join } from 'node:path' +import { promisify } from 'node:util' import { autoUpdater } from 'electron-updater' +import type { UpdateMode } from '../shared/settings' import type { UpdateStatus } from '../shared/types' import { clear, end, onActivityAction, report, waiting } from './activity' +import { log } from './log' +import { getSettings, onSettingsChanged } from './settings' +import { autoDownloads, checkMayStart, checksOnItsOwn, shownInActivity } from './updatePolicy' const RELEASES_URL = 'https://github.com/osbytes/lyra/releases' const CHECK_EVERY_MS = 4 * 60 * 60 * 1000 -let current: UpdateStatus = { state: 'idle' } +const execFileAsync = promisify(execFile) + +let current: UpdateStatus = { state: 'unavailable' } let checkTimer: ReturnType | null = null +/** The person asked for this check or download, so its progress and failures are shown. */ let userInitiated = false +/** The newest release found, so a failed background download can still be offered. */ +let foundVersion: string | null = null /** Off for task runs (smoke tests, screenshots); set by registerUpdater. */ let allowed = true /** Tells the app it is really quitting, so closing the window doesn't just hide it. */ let beforeInstall = (): void => undefined +let inPlace: Promise | null = null + +/** Read fresh after an await, when an updater event may have moved it on. */ +function state(): UpdateStatus['state'] { + return current.state +} function updaterEnabled(): boolean { return allowed && app.isPackaged } +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error) +} + function macAppBundle(): string { return join(app.getPath('exe'), '../../..') } -function canInstallInPlace(): boolean { +/** Only a Developer ID-signed Mac app can replace itself; elsewhere the installer does it. */ +async function signedForInPlaceInstall(): Promise { if (process.platform !== 'darwin') return true - const result = spawnSync('codesign', ['-dv', '--verbose=2', macAppBundle()], { - encoding: 'utf8' - }) - const text = result.stdout + result.stderr - return text.includes('Authority=Developer ID Application') + try { + // codesign describes the signature on stderr, and fails on an unsigned bundle. + const { stdout, stderr } = await execFileAsync('codesign', ['-dv', '--verbose=2', macAppBundle()], { + encoding: 'utf8' + }) + return (stdout + stderr).includes('Authority=Developer ID Application') + } catch { + return false + } +} + +/** The signature can't change while the app runs, so it is read once. */ +function canInstallInPlace(): Promise { + inPlace ??= signedForInPlaceInstall() + return inPlace } /** The update as an Activity row: the one place it shows, sidebar open or not. */ function reportActivity(status: UpdateStatus): void { const base = { id: 'update', kind: 'update' as const, origin: 'app' as const } + const background = !userInitiated && autoUpdater.autoDownload + if (!shownInActivity(status.state, background)) { + clear(base.id) + return + } switch (status.state) { + case 'unavailable': case 'idle': + case 'checking': + case 'latest': clear(base.id) return case 'available': @@ -72,38 +111,45 @@ async function openReleases(): Promise { await shell.openExternal(RELEASES_URL) } -async function checkForUpdates(): Promise { - if (!updaterEnabled()) return +/** Looks for a newer release; with `byUser`, says so while it looks and when there's none. */ +export async function checkForUpdates(byUser: boolean): Promise { + if (!updaterEnabled() || !checkMayStart(current.state)) return + userInitiated = byUser + if (byUser) broadcast({ state: 'checking' }) try { await autoUpdater.checkForUpdates() } catch { - if (userInitiated) { - broadcast({ state: 'error', message: 'Could not check for updates.' }) - } + // The error event has logged it; this covers a failure that never reached it. + if (state() === 'checking') broadcast({ state: 'error', message: "Couldn't check for updates." }) } } export async function startUpdate(): Promise { if (!updaterEnabled()) return userInitiated = true - if (current.state === 'error' || !canInstallInPlace()) { - await openReleases() - return - } if (current.state === 'ready') { install() return } + // A download Lyra started on its own: from now on it shows its progress. + if (current.state === 'downloading') { + broadcast(current) + return + } + if (current.state === 'error' || !(await canInstallInPlace())) { + await openReleases() + return + } try { await autoUpdater.downloadUpdate() } catch { - broadcast({ state: 'error', message: 'Could not download the update.' }) + if (state() !== 'error') broadcast({ state: 'error', message: "Couldn't download the update." }) } } export async function installUpdate(): Promise { if (!updaterEnabled()) return - if (!canInstallInPlace() || current.state !== 'ready') { + if (!(await canInstallInPlace()) || current.state !== 'ready') { await openReleases() return } @@ -119,43 +165,79 @@ function install(): void { autoUpdater.quitAndInstall() } +/** Fetches an update already found, once updates are switched to automatic. */ +function downloadInBackground(): void { + autoUpdater.downloadUpdate().catch((error: unknown) => { + log('updater', 'background download failed', { error: errorMessage(error) }) + }) +} + +async function applyMode(mode: UpdateMode): Promise { + autoUpdater.autoDownload = autoDownloads(mode, await canInstallInPlace()) + if (!checksOnItsOwn(mode)) { + if (checkTimer) clearInterval(checkTimer) + checkTimer = null + return + } + if (checkTimer) return + checkTimer = setInterval(() => void checkForUpdates(false), CHECK_EVERY_MS) + checkTimer.unref() +} + +function onError(error: unknown): void { + log('updater', 'update failed', { state: current.state, error: errorMessage(error) }) + if (userInitiated) { + const message = current.state === 'downloading' ? "Couldn't download the update." : "Couldn't check for updates." + broadcast({ state: 'error', message }) + return + } + // Quietly back to where it was: the next check tries again, and it can still be installed. + if (current.state === 'downloading' && foundVersion) broadcast({ state: 'available', version: foundVersion }) +} + export function registerUpdater(options: { enabled: boolean; beforeInstall: () => void }): void { allowed = options.enabled beforeInstall = options.beforeInstall + ipcMain.handle('updater:check', () => checkForUpdates(true)) ipcMain.handle('updater:start', () => startUpdate()) ipcMain.handle('updater:install', () => installUpdate()) ipcMain.handle('updater:get', () => current) if (!updaterEnabled()) return + current = { state: 'idle' } autoUpdater.autoDownload = false autoUpdater.autoInstallOnAppQuit = true autoUpdater.allowPrerelease = false autoUpdater.on('update-available', (info) => { + foundVersion = info.version + log('updater', 'update available', { version: info.version, download: autoUpdater.autoDownload }) broadcast({ state: 'available', version: info.version }) }) autoUpdater.on('update-not-available', () => { - broadcast({ state: 'idle' }) + foundVersion = null + broadcast({ state: 'latest' }) }) autoUpdater.on('download-progress', (progress) => { broadcast({ state: 'downloading', percent: Math.round(progress.percent) }) }) autoUpdater.on('update-downloaded', (info) => { + log('updater', 'update downloaded', { version: info.version }) broadcast({ state: 'ready', version: info.version }) }) - autoUpdater.on('error', (error) => { - if (!userInitiated) return - broadcast({ - state: 'error', - message: error instanceof Error ? error.message : 'Update failed' + autoUpdater.on('error', onError) + + onSettingsChanged((next, prev) => { + if (next.updates === prev.updates) return + void applyMode(next.updates).then(() => { + // Switched to automatic with an update already found: fetch it now, not at the next check. + if (autoUpdater.autoDownload && current.state === 'available') downloadInBackground() }) }) - void checkForUpdates() - checkTimer = setInterval(() => { - userInitiated = false - void checkForUpdates() - }, CHECK_EVERY_MS) - checkTimer.unref() + const mode = getSettings().updates + void applyMode(mode).then(() => { + if (checksOnItsOwn(mode)) void checkForUpdates(false) + }) } diff --git a/apps/lyra/src/preload/index.ts b/apps/lyra/src/preload/index.ts index c086ef2..384a4ca 100644 --- a/apps/lyra/src/preload/index.ts +++ b/apps/lyra/src/preload/index.ts @@ -142,6 +142,7 @@ const api: VoicePagesApi = { ipcRenderer.removeListener('whisper:status', listener) } }, + checkForUpdates: () => ipcRenderer.invoke('updater:check'), startUpdate: () => ipcRenderer.invoke('updater:start'), installUpdate: () => ipcRenderer.invoke('updater:install'), onUpdateStatus: (callback) => { diff --git a/apps/lyra/src/renderer/src/components/Settings.tsx b/apps/lyra/src/renderer/src/components/Settings.tsx index 5bc162e..6e35872 100644 --- a/apps/lyra/src/renderer/src/components/Settings.tsx +++ b/apps/lyra/src/renderer/src/components/Settings.tsx @@ -41,6 +41,7 @@ import { PeopleSettings } from './People' import { PermissionRow } from './Permissions' import { CommitInput, Row, Section, type SectionProps, type Update } from './SettingsParts' import { tip } from './Tooltip' +import { UpdatesSection } from './Updates' import { UsageChart } from './UsageChart' import { VocabularyEditor } from './Vocabulary' import { Button } from './ui/button' @@ -62,6 +63,7 @@ const CHANGE_LABELS: Partial> = { micDeviceId: 'Changed the microphone', hotkey: 'Changed the session shortcut', launchAtLogin: 'Changed open at login', + updates: 'Changed how Lyra updates', captureSystemAudio: 'Changed computer audio capture', transcriptionLanguage: 'Changed the transcription language', notesEngine: 'Changed session summaries', @@ -1160,7 +1162,12 @@ export function SettingsDialog({ settings, update: rawUpdate, issues, onClose, f ) : null} {tab === 'performance' ? : null} - {tab === 'about' ? : null} + {tab === 'about' ? ( + <> + + + + ) : null} diff --git a/apps/lyra/src/renderer/src/components/Updates.tsx b/apps/lyra/src/renderer/src/components/Updates.tsx new file mode 100644 index 0000000..fb58a4b --- /dev/null +++ b/apps/lyra/src/renderer/src/components/Updates.tsx @@ -0,0 +1,105 @@ +import type { UpdateMode } from '../../../shared/settings' +import type { UpdateStatus } from '../../../shared/types' +import { useUpdateStatus } from '../hooks/useUpdateStatus' +import { ipcErrorMessage } from '../lib/ipcError' +import { notify } from '../lib/toast' +import { Select } from './Controls' +import { Row, Section, type SectionProps } from './SettingsParts' +import { Button } from './ui/button' + +const UPDATE_MODES: readonly { value: UpdateMode; label: string }[] = [ + { value: 'auto', label: 'Automatically' }, + { value: 'notify', label: 'Ask first' }, + { value: 'off', label: 'Only when I check' } +] + +function modeHint(mode: UpdateMode): string { + switch (mode) { + case 'auto': + return 'New versions download in the background and install the next time Lyra restarts.' + case 'notify': + return 'Lyra looks for new versions and asks before downloading one.' + case 'off': + return 'Lyra never looks for new versions on its own.' + } +} + +function statusText(status: UpdateStatus | null): string { + if (!status) return 'Reading the update status…' + switch (status.state) { + case 'unavailable': + return 'This build doesn’t update itself' + case 'idle': + return 'Not checked since Lyra started' + case 'checking': + return 'Checking for updates…' + case 'latest': + return 'Lyra is up to date' + case 'available': + return `Version ${status.version} is available` + case 'downloading': + return `Downloading the update · ${String(status.percent)}%` + case 'ready': + return `Version ${status.version} is ready` + case 'error': + return status.message + } +} + +type Action = { label: string; run: () => Promise } | null + +/** The one thing worth doing from where the update stands, if anything. */ +function action(status: UpdateStatus | null): Action { + if (!status) return null + switch (status.state) { + case 'unavailable': + case 'checking': + case 'downloading': + return null + case 'idle': + case 'latest': + return { label: 'Check now', run: () => window.api.checkForUpdates() } + case 'error': + return { label: 'Retry', run: () => window.api.checkForUpdates() } + case 'available': + return { label: 'Download', run: () => window.api.startUpdate() } + case 'ready': + return { label: 'Restart to update', run: () => window.api.installUpdate() } + } +} + +/** Settings → About → Updates: how Lyra keeps itself current, and where that stands now. */ +export function UpdatesSection({ settings, update }: SectionProps) { + const status = useUpdateStatus() + const next = action(status) + return ( +
+ +