Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -179,9 +179,13 @@ jobs:
echo "::error::node-llama-cpp is missing from $RESOURCES/llama (scripts/prepare-llama.cjs)"
exit 1
fi
if [ "$RUNNER_OS" = macOS ] && [ ! -x "$RESOURCES/micwatch" ]; then
echo "::error::the micwatch helper is missing from $RESOURCES (scripts/build-mac-helpers.cjs)"
exit 1
if [ "$RUNNER_OS" = macOS ]; then
for helper in micwatch audiocapture; do
if [ ! -x "$RESOURCES/$helper" ]; then
echo "::error::the $helper helper is missing from $RESOURCES (scripts/build-mac-helpers.cjs)"
exit 1
fi
done
fi
if [ "$RUNNER_OS" = Linux ]; then xvfb-run -a "$APP" smoke; else "$APP" smoke; fi
# Both Mac builds write latest-mac.yml; the Intel one is renamed so the publish job can merge
Expand Down
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pnpm install
pnpm dev
```

On macOS, grant microphone access when prompted. The first **Record** click downloads the Whisper `large-v3-turbo` model (~575 MB) into the app data folder.
On macOS, grant microphone access when prompted. In development macOS asks on behalf of **Electron**, not your terminal (`pnpm dev` starts it through `build/helpers/devlaunch`, built with the other helpers; it needs Xcode's command line tools), so System Audio Recording is listed under Electron. The first **Record** click downloads the Whisper `large-v3-turbo` model (~575 MB) into the app data folder.

The website lives in `apps/website` (Next.js). Run it with `pnpm dev:web` and open http://localhost:3100.

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ Grant microphone access when prompted. Models download on first use:
for non-commercial use only (see [THIRD_PARTY.md](THIRD_PARTY.md))
- **Search model** (~146 MB), only if you turn on search by meaning

On macOS, capturing a call's audio needs Screen Recording permission.
On macOS, capturing a call's audio needs System Audio Recording permission; Lyra asks the first time.

## Privacy

Expand Down
2 changes: 2 additions & 0 deletions apps/lyra/electron-builder.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ mac:
extraResources:
- from: build/helpers/micwatch
to: micwatch
- from: build/helpers/audiocapture
to: audiocapture
entitlementsInherit: build/entitlements.mac.plist
extendInfo:
NSMicrophoneUsageDescription: Lyra records audio so it can transcribe your pages on this device.
Expand Down
56 changes: 56 additions & 0 deletions apps/lyra/native/mac/audiocapture.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// Reads or asks for macOS's System Audio Recording permission (TCC's kTCCServiceAudioCapture),
// which Chromium's Core Audio tap needs to record computer audio. Chromium only checks it and
// never asks, so without this the track ends at once and macOS never lists Lyra to allow.
//
// audiocapture status prints granted | denied | not-determined | unknown
// audiocapture request asks (a system prompt the first time), then prints granted | denied
//
// TCC has no public API for this service; this is the same private call macOS's own apps make.
// A missing symbol (an older macOS) prints "unknown". TCC answers for the app that launched the
// helper (Lyra, or the terminal running `pnpm dev`), so the prompt names that app.
//
// Build: swiftc -O native/mac/audiocapture.swift -o build/helpers/audiocapture

import Foundation

let service = "kTCCServiceAudioCapture" as CFString

typealias Preflight = @convention(c) (CFString, CFDictionary?) -> Int
typealias Request = @convention(c) (CFString, CFDictionary?, @escaping (Bool) -> Void) -> Void

let tcc = dlopen("/System/Library/PrivateFrameworks/TCC.framework/Versions/A/TCC", RTLD_NOW)

func symbol<T>(_ name: String, as _: T.Type) -> T? {
guard let tcc, let pointer = dlsym(tcc, name) else { return nil }
return unsafeBitCast(pointer, to: T.self)
}

func status() -> String {
guard let preflight = symbol("TCCAccessPreflight", as: Preflight.self) else { return "unknown" }
switch preflight(service, nil) {
case 0: return "granted"
case 1: return "denied"
case 2: return "not-determined"
default: return "unknown"
}
}

func request() -> String {
guard let ask = symbol("TCCAccessRequest", as: Request.self) else { return "unknown" }
let done = DispatchSemaphore(value: 0)
var granted = false
ask(service, nil) { answer in
granted = answer
done.signal()
}
done.wait()
return granted ? "granted" : "denied"
}

switch CommandLine.arguments.dropFirst().first {
case "status": print(status())
case "request": print(request())
default:
FileHandle.standardError.write("usage: audiocapture status|request\n".data(using: .utf8) ?? Data())
exit(2)
}
66 changes: 66 additions & 0 deletions apps/lyra/native/mac/devlaunch.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// Development only: starts Electron as its own "responsible" process, then waits for it.
//
// macOS asks for privacy permissions (TCC) on behalf of the app that launched a process, so
// under `pnpm dev` it asks for the terminal. Most terminals (Warp, Terminal, iTerm) don't declare
// NSAudioCaptureUsageDescription, and macOS then refuses System Audio Recording without asking.
// Disclaiming makes Electron.app, which declares it, the one asked. `pnpm dev`
// (scripts/dev.cjs) points electron-vite here through ELECTRON_EXEC_PATH and names the real
// Electron binary in DEVLAUNCH_TARGET; the packaged app never uses it.
//
// Usage: DEVLAUNCH_TARGET=<electron binary> devlaunch [args...]
// Build: clang -O2 native/mac/devlaunch.c -o build/helpers/devlaunch

#include <errno.h>
#include <signal.h>
#include <spawn.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>

extern char **environ;

// Private but stable since macOS 10.14; Chromium, LLDB and Xcode use it for the same reason.
int responsibility_spawnattrs_setdisclaim(posix_spawnattr_t *attrs, int disclaim);

static pid_t child = 0;

static void forward(int signal) {
if (child > 0) kill(child, signal);
}

int main(int argc, char **argv) {
const char *target = getenv("DEVLAUNCH_TARGET");
if (target == NULL || argc < 1) {
fprintf(stderr, "usage: DEVLAUNCH_TARGET=<electron binary> devlaunch [args...]\n");
return 2;
}
argv[0] = (char *)target;
posix_spawnattr_t attrs;
posix_spawnattr_init(&attrs);
responsibility_spawnattrs_setdisclaim(&attrs, 1);
int error = posix_spawn(&child, target, NULL, &attrs, argv, environ);
posix_spawnattr_destroy(&attrs);
if (error != 0) {
fprintf(stderr, "devlaunch: could not start %s (error %d)\n", target, error);
return 1;
}
// electron-vite stops and restarts Electron by signalling the process it spawned: this one.
signal(SIGTERM, forward);
signal(SIGINT, forward);
signal(SIGHUP, forward);
int status = 0;
while (waitpid(child, &status, 0) < 0) {
// Interrupted by a forwarded signal: keep waiting for Electron to exit. Anything else
// (ECHILD) would loop forever.
if (errno != EINTR) {
perror("devlaunch: waitpid");
return 1;
}
}
if (WIFSIGNALED(status)) {
signal(WTERMSIG(status), SIG_DFL);
raise(WTERMSIG(status));
}
return WIFEXITED(status) ? WEXITSTATUS(status) : 1;
}
2 changes: 1 addition & 1 deletion apps/lyra/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"license": "MIT",
"homepage": "https://github.com/osbytes/lyra",
"scripts": {
"dev": "electron-vite dev",
"dev": "node scripts/dev.cjs",
"start": "electron-vite preview",
"build": "pnpm check && electron-vite build",
"typecheck:node": "tsc --noEmit -p tsconfig.node.json --composite false",
Expand Down
30 changes: 24 additions & 6 deletions apps/lyra/scripts/build-mac-helpers.cjs
Original file line number Diff line number Diff line change
@@ -1,19 +1,37 @@
// Compiles the small native helpers Lyra ships on macOS (see native/mac).
// `--if-stale` (used by `pnpm dev`) builds only helpers older than their source, and warns
// instead of failing when a compiler is missing: the app runs without them, minus what they do.
const { execFileSync } = require('node:child_process')
const { mkdirSync } = require('node:fs')
const { existsSync, mkdirSync, statSync } = require('node:fs')
const { join } = require('node:path')

if (process.platform !== 'darwin') {
console.log('build-mac-helpers: not on macOS, skipping')
process.exit(0)
}

const ifStale = process.argv.includes('--if-stale')
const root = join(__dirname, '..')
const outDir = join(root, 'build', 'helpers')
mkdirSync(outDir, { recursive: true })

const out = join(outDir, 'micwatch')
execFileSync('swiftc', ['-O', join(root, 'native', 'mac', 'micwatch.swift'), '-o', out], {
stdio: 'inherit'
})
console.log(`build-mac-helpers: built ${out}`)
// devlaunch is for `pnpm dev` only (scripts/dev.cjs); electron-builder ships the other two.
const helpers = [
{ name: 'micwatch', file: 'micwatch.swift', compiler: 'swiftc', flags: ['-O'] },
{ name: 'audiocapture', file: 'audiocapture.swift', compiler: 'swiftc', flags: ['-O'] },
{ name: 'devlaunch', file: 'devlaunch.c', compiler: 'clang', flags: ['-O2', '-Wall'] }
]

for (const { name, file, compiler, flags } of helpers) {
const source = join(root, 'native', 'mac', file)
const out = join(outDir, name)
if (ifStale && existsSync(out) && statSync(out).mtimeMs >= statSync(source).mtimeMs) continue
try {
execFileSync(compiler, [...flags, source, '-o', out], { stdio: 'inherit' })
} catch (error) {
if (!ifStale) throw error
console.warn(`build-mac-helpers: could not build ${name} (${String(error)}); continuing without it`)
continue
}
console.log(`build-mac-helpers: built ${out}`)
}
31 changes: 31 additions & 0 deletions apps/lyra/scripts/dev.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// `pnpm dev`: electron-vite dev, after building the macOS helpers that are missing or stale.
// On macOS Electron starts through build/helpers/devlaunch, so macOS asks for privacy
// permissions (System Audio Recording) for Electron.app rather than the terminal running this,
// which usually can't be asked at all (see native/mac/devlaunch.c).
const { execFileSync, spawn } = require('node:child_process')
const { existsSync } = require('node:fs')
const { dirname, join } = require('node:path')

const root = join(__dirname, '..')
execFileSync(process.execPath, [join(__dirname, 'build-mac-helpers.cjs'), '--if-stale'], {
stdio: 'inherit'
})

const env = { ...process.env }
const devlaunch = join(root, 'build', 'helpers', 'devlaunch')
if (process.platform === 'darwin' && existsSync(devlaunch) && !env.ELECTRON_EXEC_PATH) {
// Requiring the electron package from Node gives the path to its binary.
env.DEVLAUNCH_TARGET = require('electron')
env.ELECTRON_EXEC_PATH = devlaunch
}

const cli = join(dirname(require.resolve('electron-vite/package.json')), 'bin', 'electron-vite.js')
const child = spawn(process.execPath, [cli, 'dev', ...process.argv.slice(2)], {
cwd: root,
env,
stdio: 'inherit'
})
for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => child.kill(signal))
child.on('exit', (code, signal) => {
process.exit(code ?? (signal ? 1 : 0))
})
26 changes: 26 additions & 0 deletions apps/lyra/src/main/audioCapturePermission.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { describe, expect, it } from 'vitest'
import { parseAudioCaptureReply, shouldRequestAudioCapture } from './audioCapturePermission'

describe('parseAudioCaptureReply', () => {
it('reads each state the helper prints', () => {
expect(parseAudioCaptureReply('granted\n')).toBe('granted')
expect(parseAudioCaptureReply('denied\n')).toBe('denied')
expect(parseAudioCaptureReply('not-determined\n')).toBe('not-determined')
expect(parseAudioCaptureReply('unknown')).toBe('unknown')
})

it('reads anything else as unknown', () => {
expect(parseAudioCaptureReply('')).toBe('unknown')
expect(parseAudioCaptureReply('restricted')).toBe('unknown')
expect(parseAudioCaptureReply('usage: audiocapture status|request')).toBe('unknown')
})
})

describe('shouldRequestAudioCapture', () => {
it('asks only when macOS has never asked', () => {
expect(shouldRequestAudioCapture('not-determined')).toBe(true)
expect(shouldRequestAudioCapture('granted')).toBe(false)
expect(shouldRequestAudioCapture('denied')).toBe(false)
expect(shouldRequestAudioCapture('unknown')).toBe(false)
})
})
19 changes: 19 additions & 0 deletions apps/lyra/src/main/audioCapturePermission.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { z } from 'zod'
import type { PermissionState } from '../shared/types'

/** One line from `native/mac/audiocapture.swift`. */
const HelperReply = z.enum(['granted', 'denied', 'not-determined', 'unknown'])

/** The helper's answer; anything it shouldn't print reads as unknown, which flags nothing. */
export function parseAudioCaptureReply(stdout: string): PermissionState {
const parsed = HelperReply.safeParse(stdout.trim())
return parsed.success ? parsed.data : 'unknown'
}

/**
* Whether to ask before capturing computer audio: only while macOS has never been asked.
* Asking again after a refusal shows nothing; the user changes it in System Settings.
*/
export function shouldRequestAudioCapture(state: PermissionState): boolean {
return state === 'not-determined'
}
17 changes: 14 additions & 3 deletions apps/lyra/src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
import { homedir, release } from 'node:os'
import { join } from 'node:path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import { systemAudioSource } from './systemAudioSource'
import { systemAudioSource, usesAudioTap } from './systemAudioSource'
import { installAppMenu } from './appMenu'
import { isAppPage, type AppPages } from './appOrigin'
import { checkConfig, config, ConfigError, configSummary } from './config'
Expand Down Expand Up @@ -94,7 +94,7 @@ import { getDiagnostics, noteWhisperUsed, revealFolder } from './diagnostics'
import { cancelModelDownload } from './models'
import { modelStatuses, onModelRetry, retryModel } from './modelStatus'
import { detectServers, listServerModels, testWriter } from './notesServers'
import { openPermissionSettings, permissionStatus } from './permissions'
import { ensureSystemAudioAsked, openPermissionSettings, permissionStatus } from './permissions'
import { installedPromptApps, openInPromptApp } from './promptApps'
import { PromptAppRequest } from '../shared/promptApps'
import { createTray } from './tray'
Expand Down Expand Up @@ -514,14 +514,25 @@ function registerPermissions(): void {
// Meetings ask for system audio via getDisplayMedia; answer with the loopback
// device and the primary screen (its video track is discarded), so no picker shows.
const audio = systemAudioSource(process.platform, release())
log('capture', 'system audio source', { audio })
const audioTap = usesAudioTap(process.platform, release())
log('capture', 'system audio source', { audio, audioTap })
session.defaultSession.setDisplayMediaRequestHandler((request, callback) => {
const main = getMainWindow()
const frame = request.frame
if (!main || frame?.top !== main.webContents.mainFrame || !isAppPage(frame.url, pages)) {
callback({})
return
}
if (audioTap) {
// macOS 14.2+ records computer audio through a Core Audio tap, which needs System Audio
// Recording; ask for it here, the first time, since Chromium only checks it. The video
// track is discarded, so it comes from Lyra's own window: a screen would need Screen
// Recording too, for nothing.
void ensureSystemAudioAsked().then(() => {
callback({ video: frame, audio: 'loopback' })
})
return
}
desktopCapturer.getSources({ types: ['screen'] }).then(
([screen]) => {
// Electron types `audio` as 'loopback' | 'loopbackWithMute', but hands any of Chromium's
Expand Down
2 changes: 1 addition & 1 deletion apps/lyra/src/main/ipcSchemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ export const ModelNameArg = z
export const ModelFeatureArg = z.enum(['semanticSearch', 'localNotes'])

/** `permissions:openSettings`. Main maps each to a fixed system settings page. */
export const PermissionKindArg = z.enum(['microphone', 'screen'])
export const PermissionKindArg = z.enum(['microphone', 'systemAudio'])

/** `diagnostics:reveal`. Main maps each to a fixed folder. */
export const RevealTargetArg = z.enum(['logs', 'models'])
4 changes: 2 additions & 2 deletions apps/lyra/src/main/permissionPanes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@ describe('permissionPane', () => {
expect(permissionPane('darwin', 'microphone')).toBe(
'x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone'
)
expect(permissionPane('darwin', 'screen')).toBe(
expect(permissionPane('darwin', 'systemAudio')).toBe(
'x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture'
)
})

it('has only the microphone page on Windows and nothing elsewhere', () => {
expect(permissionPane('win32', 'microphone')).toBe('ms-settings:privacy-microphone')
expect(permissionPane('win32', 'screen')).toBeNull()
expect(permissionPane('win32', 'systemAudio')).toBeNull()
expect(permissionPane('linux', 'microphone')).toBeNull()
})
})
5 changes: 3 additions & 2 deletions apps/lyra/src/main/permissionPanes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@ import type { PermissionKind } from '../shared/types'
const PANES: Partial<Record<NodeJS.Platform, Partial<Record<PermissionKind, string>>>> = {
darwin: {
microphone: 'x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone',
screen: 'x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture'
// Screen & System Audio Recording: Lyra is listed under "System Audio Recording Only".
systemAudio: 'x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture'
},
// Windows has no screen-capture permission; loopback audio needs none.
// Windows loopback audio needs no permission.
win32: { microphone: 'ms-settings:privacy-microphone' }
}

Expand Down
Loading
Loading