Private AI meeting notes that stay on your computer. No meeting bot. Free and open source for Mac, Windows and Linux. An alternative to Granola, Otter and Fireflies.
TypeScript ai-meeting-assistantai-notetakerelectrongranola-alternativelinuxllama-cpplocal-ailocal-firstmacosmcpmeeting-minutesmeeting-notesoffline-firstopen-sourceprivacyspeech-to-texttranscriptionwhisperwhisper-cppwindows
Mic detection on a Mac: one helper watches the mic for Yogurt's whole life and says when it changes, instead of a new one every few seconds, which after about an hour stopped the displays from waking (#143)
christianmat2ec710e16c88
diff --git a/app/native/yogurt-mac/main.swift b/app/native/yogurt-mac/main.swiftindex 3f56422b..cbc0c8ec 100644--- a/app/native/yogurt-mac/main.swift+++ b/app/native/yogurt-mac/main.swift@@ -5,6 +5,8 @@// yogurt-mac calendar-auth → asks once (the system's own prompt), then the status// yogurt-mac events FROM TO → meetings between two ISO dates (all-day and cancelled ones left out)// yogurt-mac mic-apps → [{"bundleId","name","pid"}] of processes using audio input right now+// yogurt-mac mic-watch → the same as mic-apps, one JSON line at start and on each change, until stdin closes:+// one Core Audio client for Yogurt's whole life instead of one per reading (#143)// yogurt-mac running-apps ID... → the supplied bundle IDs currently present in NSRunningApplication// yogurt-mac browser-title ID → {"title":string|null}: the front tab's name in Chrome, Arc, Edge, Brave or Safari (only if running)// yogurt-mac permissions → {"mic":"authorized"|"denied"|"restricted"|"notDetermined","systemAudio":0|1|2,"calendar":…,@@ -516,6 +518,49 @@ func watchCalls(every: Int, ids: [String], pids: [pid_t] = []) {}}+/// Listens for apps starting and stopping input instead of being asked again and again: each new helper was a new+/// Core Audio client with privacy checks in coreaudiod, and after about an hour of that powerd refused every power+/// assertion and the displays never woke (#143).+func watchMic() {+ // Yogurt closes stdin to stop the watch (and a crashed Yogurt closes it too)+ DispatchQueue.global().async { _ = FileHandle.standardInput.readDataToEndOfFile(); exit(0) }+ let sys = AudioObjectID(kAudioObjectSystemObject)+ var listAddr = address(kAudioHardwarePropertyProcessObjectList)+ var inputAddr = address(kAudioProcessPropertyIsRunningInput)+ var watched = Set<AudioObjectID>()+ var last: Data?+ var pending = false+ let parent = getppid()+ let emit = {+ guard let d = try? JSONSerialization.data(withJSONObject: audioApps(input: true), options: [.sortedKeys]), d != last else { return }+ last = d+ FileHandle.standardOutput.write(d); FileHandle.standardOutput.write("\n".data(using: .utf8)!)+ }+ // a call starting touches several processes at once: one line for the lot+ let changed: AudioObjectPropertyListenerBlock = { _, _ in+ if pending { return }+ pending = true+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { pending = false; emit() }+ }+ // the same block each time, so removing it finds it+ let follow = {+ let now = Set(audioProcesses())+ for gone in watched.subtracting(now) { AudioObjectRemovePropertyListenerBlock(gone, &inputAddr, .main, changed) }+ for new in now.subtracting(watched) { AudioObjectAddPropertyListenerBlock(new, &inputAddr, .main, changed) }+ watched = now+ }+ let listChanged: AudioObjectPropertyListenerBlock = { a, b in follow(); changed(a, b) }+ AudioObjectAddPropertyListenerBlock(sys, &listAddr, .main, listChanged)+ follow()+ emit()+ // in case a change was never told: read again now and then, and end if Yogurt is gone without closing stdin+ let safety = DispatchSource.makeTimerSource(queue: .main)+ safety.schedule(deadline: .now() + 30, repeating: 30)+ safety.setEventHandler { if getppid() != parent { exit(0) }; follow(); emit() }+ safety.resume()+ dispatchMain()+}+let args = Array(CommandLine.arguments.dropFirst())switch args.first {case "calendar-status":@@ -571,6 +616,8 @@ case "events":})case "mic-apps":out(audioApps(input: true))+case "mic-watch":+ watchMic()case "running-apps":out(args.dropFirst().filter(running))case "browser-title":@@ -605,5 +652,5 @@ case "call-watch":case "mic-devices":out(["devices": inputDevices()])default:- fail("usage: yogurt-mac calendar-status | calendar-auth | events FROM TO | mic-apps | running-apps ID... | browser-title ID | permissions | media-auth | mic-auth | audio-auth | media-pause | media-resume ID... | mic-devices | ax-auth | call-watch MS [--pid N]... ID...")+ fail("usage: yogurt-mac calendar-status | calendar-auth | events FROM TO | mic-apps | mic-watch | running-apps ID... | browser-title ID | permissions | media-auth | mic-auth | audio-auth | media-pause | media-resume ID... | mic-devices | ax-auth | call-watch MS [--pid N]... ID...")}diff --git a/app/src/main/detectSignals.ts b/app/src/main/detectSignals.tsindex d94dd11e..10e88c37 100644--- a/app/src/main/detectSignals.ts+++ b/app/src/main/detectSignals.ts@@ -8,10 +8,11 @@ const TITLE_TTL = 10_000export type Reading = { micApps: MicApp[]; events: CalEvent[]; runningApps?: string[] }/**- * Gathers the signals. The mic is asked each time (cheap); the calendar at most once a minute,+ * Gathers the signals. The mic comes from micApps (the Mac's long-lived mic watch, #143), else a helper each time;+ * the calendar at most once a minute,* since it only matters near a start time. Failed owner checks skip the observation.*/-export function createSignals(d: { helper: Helper; events: (from: number, to: number) => Promise<CalEvent[]>; eventsTtlMs?: number }) {+export function createSignals(d: { helper: Helper; micApps?: () => Promise<unknown>; events: (from: number, to: number) => Promise<CalEvent[]>; eventsTtlMs?: number }) {let cache: { at: number; events: CalEvent[] } | undefinedlet override: Reading | undefinedlet revision = 0@@ -24,7 +25,7 @@ export function createSignals(d: { helper: Helper; events: (from: number, to: nuif (override) return overridelet micApps: MicApp[] = []try {- const raw = await d.helper(['mic-apps'])+ const raw = d.micApps ? await d.micApps() : await d.helper(['mic-apps'])if (Array.isArray(raw)) micApps = raw.flatMap((r: Record<string, unknown>) => typeof r?.bundleId === 'string' ? [{bundleId: r.bundleId, name: typeof r.name === 'string' ? r.name : r.bundleId,// which process: two Zoom meetings are two processes, and names come only from the one on the mic (#98)diff --git a/app/src/main/index.ts b/app/src/main/index.tsindex c27f8a94..ddaccc61 100644--- a/app/src/main/index.ts+++ b/app/src/main/index.ts@@ -51,6 +51,7 @@ import { calendars, eventIds, matchesEvent, setCalendarSelection, setCalendarOwnimport { createCalendarLinks } from './calendarLink'import { getCalendar } from './calendarLink/get'import { createSignals } from './detectSignals'+import { createMicWatch, spawnMicWatch } from './micWatch'import { Watcher } from './watch'import { createPrompts } from './prompts'import { activeMeeting, bindMeetingApp, getMeeting, initMeetings, onMeetingBound, onMeetingChange, onMeetingStart, onMeetingStop, onMeetingStopSaved, createFolderNote, refreshEventSnapshots, linkEvent, unlinkEvent, prepareMeeting, startPreparedMeeting, resumeMeeting, pauseMeetingClock, renameMeeting, retryStopSave, setAttendees, startMeeting, stopMeeting, stopSavePending, withStopState } from './meeting'@@ -317,7 +318,12 @@ let indexerRef: { schedule(): Promise<unknown> } | undefined/** Notice calls, offer to take notes, stop when the call ends (or ask, with that setting off). Starts nothing without a click. */function startDetection() {if (isFake()) setHelper(fakeHelper)- const signals = createSignals({ helper: runHelper, events: readCalendar })+ // On a Mac one mic watch runs for Yogurt's whole life: a new helper per reading wore out coreaudiod and powerd (#143)+ const micWatch = process.platform === 'darwin' && !isFake()+ ? createMicWatch({ start: spawnMicWatch(helperPath), poll: () => runHelper(['mic-apps']), recording: () => !!activeMeeting() })+ : undefined+ app.on('will-quit', () => micWatch?.stop())+ const signals = createSignals({ helper: runHelper, micApps: micWatch?.read, events: readCalendar })refreshCalendarConsumers = () => signals.invalidateCalendar()let lastReading: { micApps: MicApp[]; runningApps?: string[] } | undefined// yogurt-system (Windows, Linux) reads no single process yet; the Mac helper doesdiff --git a/app/src/main/micWatch.ts b/app/src/main/micWatch.tsnew file mode 100644index 00000000..0ac1c25c--- /dev/null+++ b/app/src/main/micWatch.ts@@ -0,0 +1,111 @@+import { spawn } from 'node:child_process'+import { createInterface } from 'node:readline'++/** one running yogurt-mac mic-watch: its lines, its end, and how to end it */+export type MicWatchProc = { onLine(f: (line: string) => void): void; onExit(f: () => void): void; stop(): void }++/** waits before starting the watcher again, longer each time it ends soon after starting */+export const BACKOFF_MS = [1_000, 2_000, 4_000, 8_000, 16_000]+/** this many short runs in a row (an older helper without mic-watch, or one that can't run here): poll instead */+export const MAX_FAILURES = 5+/** a run this long was fine: the next end starts the waits over */+const LONG_RUN_MS = 60_000+/** without a watcher, how often a one-off mic-apps may run: each one is a new Core Audio client (#143) */+export const SLOW_POLL_MS = { idle: 20_000, recording: 5_000 }+/** a watcher just started prints at once; a read waits this long for it */+const FIRST_LINE_MS = 2_000++/**+ * Which apps are on the mic, from one long-lived yogurt-mac mic-watch that prints a line whenever it changes.+ * Starting a helper every few seconds made coreaudiod and powerd run out of room after about an hour, and the+ * displays never woke again (#143). A watcher that keeps ending is started again with growing waits, then given up on+ * for a slow poll.+ */+export function createMicWatch(d: { start: () => MicWatchProc; poll: () => Promise<unknown>; recording: () => boolean }) {+ let proc: MicWatchProc | undefined+ /** the watcher's latest line; undefined while none is running or it has not spoken yet */+ let value: unknown[] | undefined+ let failures = 0, stopped = false, polling = false+ let restart: NodeJS.Timeout | undefined+ let heard: (() => void)[] = []+ let polled: { at: number; value: unknown } | undefined+ let asking: Promise<unknown> | undefined++ const run = () => {+ if (stopped) return+ const startedAt = Date.now()+ const p = d.start()+ proc = p+ p.onLine((l) => {+ if (proc !== p) return+ let v: unknown+ try { v = JSON.parse(l) } catch { return }+ if (!Array.isArray(v)) return+ value = v+ for (const f of heard.splice(0)) f()+ })+ p.onExit(() => {+ if (proc !== p) return+ proc = undefined; value = undefined+ for (const f of heard.splice(0)) f()+ if (stopped) return+ failures = Date.now() - startedAt >= LONG_RUN_MS ? 0 : failures + 1+ if (failures >= MAX_FAILURES) {+ polling = true+ console.warn(`mic watch: ended ${failures} times in a row, asking every ${SLOW_POLL_MS.idle / 1000} s instead`)+ return+ }+ restart = setTimeout(run, BACKOFF_MS[Math.max(0, failures - 1)])+ })+ }++ const slowPoll = (): Promise<unknown> => {+ const every = d.recording() ? SLOW_POLL_MS.recording : SLOW_POLL_MS.idle+ if (polled && Date.now() - polled.at < every) return Promise.resolve(polled.value)+ asking ??= d.poll().catch(() => [])+ .then((v) => { polled = { at: Date.now(), value: v }; return v })+ .finally(() => { asking = undefined })+ return asking+ }++ run()+ return {+ async read(): Promise<unknown> {+ if (value) return value+ if (proc && !polling) {+ let timer: NodeJS.Timeout | undefined+ await new Promise<void>((r) => { heard.push(r); timer = setTimeout(r, FIRST_LINE_MS) })+ clearTimeout(timer)+ if (value) return value+ }+ return slowPoll()+ },+ /** quitting: the watcher ends, and no other starts */+ stop() {+ stopped = true+ clearTimeout(restart)+ proc?.stop()+ },+ }+}++/** yogurt-mac mic-watch: one JSON line (what mic-apps prints) at start and on each change, until its stdin closes */+export const spawnMicWatch = (binary: () => string) => (): MicWatchProc => {+ const child = spawn(binary(), ['mic-watch'], { stdio: ['pipe', 'pipe', 'ignore'] })+ const exits: (() => void)[] = []+ let ended = false+ const end = () => { if (ended) return; ended = true; for (const f of exits) f() }+ child.on('error', (e) => { console.warn('mic watch: could not run', e.message); end() })+ child.on('exit', end)+ // closing stdin of one already gone+ child.stdin.on('error', () => {})+ const lines = createInterface({ input: child.stdout })+ return {+ onLine: (f) => { lines.on('line', f) },+ onExit: (f) => { exits.push(f) },+ stop() {+ child.stdin.end()+ setTimeout(() => { if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL') }, 2000).unref()+ },+ }+}diff --git a/app/test/micWatch.test.ts b/app/test/micWatch.test.tsnew file mode 100644index 00000000..14843e9a--- /dev/null+++ b/app/test/micWatch.test.ts@@ -0,0 +1,162 @@+import { chmodSync, mkdtempSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { BACKOFF_MS, MAX_FAILURES, SLOW_POLL_MS, createMicWatch, spawnMicWatch, type MicWatchProc } from '../src/main/micWatch'+import { createSignals } from '../src/main/detectSignals'++const zoom = { bundleId: 'us.zoom.xos', name: 'zoom.us', pid: 2 }++/** stand-in helper processes: each start is one, lines and exits sent by hand */+function procs() {+ const all: { line(l: string): void; exit(): void; stopped: boolean }[] = []+ const start = (): MicWatchProc => {+ let onLine: (l: string) => void = () => {}, onExit: () => void = () => {}+ const p = { line: (l: string) => onLine(l), exit: () => onExit(), stopped: false }+ all.push(p)+ return { onLine: (f) => { onLine = f }, onExit: (f) => { onExit = f }, stop: () => { p.stopped = true } }+ }+ return { all, start, last: () => all[all.length - 1] }+}++function setup(o: { recording?: boolean } = {}) {+ const p = procs()+ const polls: number[] = []+ let recording = o.recording ?? false+ const w = createMicWatch({ start: p.start, poll: async () => { polls.push(Date.now()); return [zoom] }, recording: () => recording })+ return { w, p, polls, setRecording: (r: boolean) => { recording = r } }+}++describe('createMicWatch', () => {+ beforeEach(() => { vi.useFakeTimers({ now: 0 }) })+ afterEach(() => { vi.useRealTimers() })++ it('starts one watcher and returns its latest line, never asking again per read', async () => {+ const x = setup()+ x.p.last().line(JSON.stringify([zoom]))+ for (let i = 0; i < 100; i++) { expect(await x.w.read()).toEqual([zoom]); vi.advanceTimersByTime(3000) }+ x.p.last().line('[]')+ expect(await x.w.read()).toEqual([])+ expect(x.p.all).toHaveLength(1)+ expect(x.polls).toEqual([])+ })+ it('skips lines it cannot read and keeps the last good one', async () => {+ const x = setup()+ x.p.last().line(JSON.stringify([zoom]))+ x.p.last().line('[{"bundleId"')+ x.p.last().line('{"error":"x"}')+ expect(await x.w.read()).toEqual([zoom])+ })+ it('waits briefly for the first line after starting', async () => {+ const x = setup()+ const r = x.w.read()+ x.p.last().line(JSON.stringify([zoom]))+ expect(await r).toEqual([zoom])+ expect(x.polls).toEqual([])+ })+ it('restarts a watcher that ended, waiting longer each time it ends early', async () => {+ const x = setup()+ x.p.last().exit()+ vi.advanceTimersByTime(BACKOFF_MS[0] - 1)+ expect(x.p.all).toHaveLength(1)+ vi.advanceTimersByTime(1)+ expect(x.p.all).toHaveLength(2)+ x.p.last().line('[]')+ x.p.last().exit()+ vi.advanceTimersByTime(BACKOFF_MS[1] - 1)+ expect(x.p.all).toHaveLength(2)+ vi.advanceTimersByTime(1)+ expect(x.p.all).toHaveLength(3)+ })+ it('a watcher that ran a long while starts again at the shortest wait', async () => {+ const x = setup()+ for (let i = 0; i < 3; i++) { x.p.last().exit(); vi.advanceTimersByTime(60_000) }+ expect(x.p.all).toHaveLength(4)+ vi.advanceTimersByTime(10 * 60_000)+ x.p.last().exit()+ vi.advanceTimersByTime(BACKOFF_MS[0])+ expect(x.p.all).toHaveLength(5)+ })+ it('between watchers it asks once in a while, not every read', async () => {+ const x = setup()+ x.p.last().line(JSON.stringify([zoom]))+ x.p.last().exit()+ expect(await x.w.read()).toEqual([zoom])+ expect(x.polls).toHaveLength(1)+ await x.w.read()+ expect(x.polls).toHaveLength(1)+ })+ it('falls back to slow polling once the watcher keeps failing (an older helper)', async () => {+ const x = setup()+ for (let i = 0; i < MAX_FAILURES; i++) { x.p.last().exit(); vi.advanceTimersByTime(60_000) }+ expect(x.p.all).toHaveLength(MAX_FAILURES)+ vi.advanceTimersByTime(60 * 60_000)+ expect(x.p.all).toHaveLength(MAX_FAILURES)+ // reads every 3 s for a minute: a poll each SLOW_POLL_MS.idle+ for (let t = 0; t < 60_000; t += 3000) { expect(await x.w.read()).toEqual([zoom]); vi.advanceTimersByTime(3000) }+ expect(x.polls).toHaveLength(Math.ceil(60_000 / SLOW_POLL_MS.idle))+ })+ it('polls a little more often while recording, still far less than every tick', async () => {+ const x = setup({ recording: true })+ for (let i = 0; i < MAX_FAILURES; i++) { x.p.last().exit(); vi.advanceTimersByTime(60_000) }+ for (let t = 0; t < 60_000; t += 1500) { await x.w.read(); vi.advanceTimersByTime(1500) }+ expect(x.polls.length).toBeGreaterThan(1)+ expect(x.polls.length).toBeLessThanOrEqual(60_000 / SLOW_POLL_MS.recording)+ expect(SLOW_POLL_MS.recording).toBeGreaterThanOrEqual(5000)+ })+ it('a failed poll counts as nothing on the mic, and is not retried at once', async () => {+ const p = procs()+ let polls = 0+ const w = createMicWatch({ start: p.start, poll: async () => { polls++; throw new Error('no helper') }, recording: () => false })+ for (let i = 0; i < MAX_FAILURES; i++) { p.last().exit(); vi.advanceTimersByTime(60_000) }+ expect(await w.read()).toEqual([])+ expect(await w.read()).toEqual([])+ expect(polls).toBe(1)+ })+ it('stop ends the watcher and never starts another', async () => {+ const x = setup()+ x.w.stop()+ expect(x.p.last().stopped).toBe(true)+ x.p.last().exit()+ vi.advanceTimersByTime(10 * 60_000)+ expect(x.p.all).toHaveLength(1)+ })+ it('stop during a restart wait cancels the restart', async () => {+ const x = setup()+ x.p.last().exit()+ x.w.stop()+ vi.advanceTimersByTime(10 * 60_000)+ expect(x.p.all).toHaveLength(1)+ })+})++describe('createSignals with a mic watcher', () => {+ it('reads the mic from the watcher, never from a new helper', async () => {+ const calls: string[][] = []+ const s = createSignals({ helper: async (a) => { calls.push(a); return [] }, micApps: async () => [zoom], events: async () => [] })+ for (let i = 0; i < 10; i++) expect((await s.read(i * 3000)).micApps).toEqual([zoom])+ expect(calls.filter((c) => c[0] === 'mic-apps')).toEqual([])+ })+})++describe.skipIf(process.platform === 'win32')('spawnMicWatch', () => {+ it('hands on each line, and ends the helper when stopped (stdin closed)', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'micwatch-'))+ const bin = join(dir, 'helper')+ writeFileSync(bin, '#!/bin/sh\n[ "$1" = mic-watch ] || exit 2\necho \'[{"bundleId":"us.zoom.xos","name":"zoom.us","pid":2}]\'\ncat >/dev/null\n')+ chmodSync(bin, 0o755)+ const p = spawnMicWatch(() => bin)()+ const line = await new Promise<string>((r) => p.onLine(r))+ expect(JSON.parse(line)).toEqual([zoom])+ const ended = new Promise<void>((r) => p.onExit(r))+ p.stop()+ await ended+ })+ it('a helper that cannot start ends once', async () => {+ const p = spawnMicWatch(() => '/nonexistent/yogurt-mac')()+ let ends = 0+ await new Promise<void>((r) => p.onExit(() => { ends++; r() }))+ await new Promise((r) => setTimeout(r, 50))+ expect(ends).toBe(1)+ })+})