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
18 changes: 13 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ can do. Your own values are never touched.
{
"recordings_dir": "~/Recordings",
"meeting_detection": false,
"meeting_auto_record": false,
"mic_voice_processing": true,
"on_stop": "my-hook",
"transcription": { "enabled": true },
Expand All @@ -96,8 +97,8 @@ can do. Your own values are never touched.
```

Save it and yap picks it up. The hotkey, `tap_to_toggle`, the overlay,
`mute_output`, `newline_after_release` and `meeting_detection` all change on the
spot. A new `model` or `recordings_dir` wants a restart, and yap says so when it
`mute_output`, `newline_after_release`, `meeting_detection` and
`meeting_auto_record` all change on the spot. A new `model` or `recordings_dir` wants a restart, and yap says so when it
sees one.

`newline_after_release` hits Return once the text is in, which is what you want
Expand All @@ -112,7 +113,13 @@ free, tap again to finish. A press you actually hold still ends when you let go,
so both habits work and a hold never leaves the mic latched open.

`meeting_detection` offers to record when something else grabs the mic. Off by
default, and nothing is watching until you turn it on.
default, and nothing is watching until you turn it on. When the meeting app
exposes a window title, yap uses it in the prompt, recording folder and
transcript.

`meeting_auto_record` skips that prompt and starts recording immediately, with a
visible Stop action. It only has an effect when `meeting_detection` is on, and is
off by default.

`mic_voice_processing` cancels speaker echo on the mic track. On by default: a
call coming out of your speakers goes back into the mic. Without it, the other
Expand All @@ -124,8 +131,9 @@ argument.

`transcription` is automatic transcription of recordings, on by default.
Dictation ignores it, since the hotkey always transcribes. When one finishes
while the daemon is running, a banner drops under the menu bar with an Open
button that reveals the transcript in Finder. Turn it off to use yap as a plain
while the daemon is running, a banner drops under the menu bar with Open and
Name… buttons. Open reveals the transcript in Finder; Name… renames the folder
and updates its metadata and heading. Turn it off to use yap as a plain
recorder: `on_stop` then fires when the recording stops rather than after the
transcript. Nothing is lost either way. Turn it back on, restart, and yap works
through every session under `recordings_dir` that has no transcript yet, firing
Expand Down
8 changes: 8 additions & 0 deletions Sources/yap/Config.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import Foundation
/// "transcription": { "enabled": true },
/// "mic_voice_processing": true,
/// "meeting_detection": false,
/// "meeting_auto_record": false,
/// "on_stop": "my-hook",
/// "dictation": {
/// "model": "parakeet-tdt-ctc-110m",
Expand Down Expand Up @@ -60,6 +61,12 @@ enum Config {
load()?["meeting_detection"] as? Bool ?? false
}

/// Record detected meetings without asking. Only meaningful with meeting
/// detection enabled. Default off and read at each detection event.
static func meetingAutoRecord() -> Bool {
load()?["meeting_auto_record"] as? Bool ?? false
}

/// Apple voice processing (acoustic echo cancellation) on the mic, so
/// speaker playback doesn't bleed into the mic track and get transcribed
/// as "me". Default on: the mic track always pairs with a system track, so
Expand Down Expand Up @@ -164,6 +171,7 @@ enum Config {
"transcription": { "enabled": true },
"mic_voice_processing": true,
"meeting_detection": false,
"meeting_auto_record": false,
"dictation": {
"model": "parakeet-tdt-ctc-110m",
"hotkey": "fn",
Expand Down
32 changes: 14 additions & 18 deletions Sources/yap/Detection/MeetingDetector.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,9 @@ import Foundation
/// device read.
@MainActor
final class MeetingDetector {
/// Something took the mic. The argument is a display name ("Microsoft
/// Teams") when the capturing process belongs to an app, nil for the
/// daemons and XPC helpers that have no app to name.
var onMeetingStart: ((String?) -> Void)?
/// Something took the mic. The arguments are its capture pid and a display
/// name ("Microsoft Teams") when that pid belongs to an app.
var onMeetingStart: ((pid_t, String?) -> Void)?

/// The mic went quiet a moment ago (~2 s). The call could still come back
/// from a device switch, so this is only for things that are cheap to
Expand Down Expand Up @@ -114,6 +113,13 @@ final class MeetingDetector {
acceptedPID = observedPID ?? askedPID
}

/// The session bound to the accepted prompt has stopped. The preferred-pid
/// filter exists to keep clients woken by our own recording from prolonging
/// the call; with no recording live it only blinds the scan to other apps.
func releaseAcceptedMeeting() {
acceptedPID = nil
}

/// Ignore the microphone while yap is dictating.
///
/// Filtering our own pid is not enough, because the process on the mic
Expand Down Expand Up @@ -147,7 +153,8 @@ final class MeetingDetector {
// Suppressed rather than stopped, so an in-progress call keeps its
// end detection running underneath a dictation press.
guard !suppressed else { return }
let pid = capturePID?(acceptedPID) ?? currentCapturingPID(preferred: acceptedPID)
let pid = capturePID.map { $0(acceptedPID) }
?? currentCapturingPID(preferred: acceptedPID)
observedPID = pid
guard let pid else {
consecutiveActive = 0
Expand All @@ -174,7 +181,7 @@ final class MeetingDetector {
// about, and never for one the user turned down.
guard pid != askedPID, pid != declinedPID else { return }
askedPID = pid
onMeetingStart?(Self.appName(forPID: pid))
onMeetingStart?(pid, Self.appName(forPID: pid))
}

/// The capturing process to follow, excluding yap itself.
Expand Down Expand Up @@ -262,18 +269,7 @@ final class MeetingDetector {
/// the one a human would recognise. Daemons and XPC services have no `.app`
/// and get no name.
private static func appName(forPID pid: pid_t) -> String? {
var buffer = [UInt8](repeating: 0, count: 4 * Int(PATH_MAX))
let length = buffer.withUnsafeMutableBytes {
proc_pidpath(pid, $0.baseAddress, UInt32($0.count))
}
guard length > 0 else { return nil }

let components = (String(decoding: buffer[..<Int(length)], as: UTF8.self) as NSString)
.pathComponents
guard let end = components.firstIndex(where: { $0.hasSuffix(".app") }) else { return nil }
return FileManager.default.displayName(
atPath: NSString.path(withComponents: Array(components[...end]))
)
MeetingTitle.appBundlePath(forPID: pid).map(FileManager.default.displayName(atPath:))
}

// MARK: - Core Audio plumbing
Expand Down
127 changes: 127 additions & 0 deletions Sources/yap/Detection/MeetingTitle.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
import AppKit
import ApplicationServices
import Darwin

/// Best-effort meeting titles from the window-owning app behind a capture pid.
///
/// Cost contract: call only when prompting, accepting, or resuming after a
/// quiet gap — never from the detector poll loop or dictation path. Each call
/// makes a handful of AX round-trips bounded by a 0.25 second timeout.
@MainActor
enum MeetingTitle {
/// Path to the outermost app bundle holding the pid's executable.
static func appBundlePath(forPID pid: pid_t) -> String? {
var buffer = [UInt8](repeating: 0, count: 4 * Int(PATH_MAX))
let length = buffer.withUnsafeMutableBytes {
proc_pidpath(pid, $0.baseAddress, UInt32($0.count))
}
guard length > 0 else { return nil }

guard let path = String(bytes: buffer[..<Int(length)], encoding: .utf8) else {
return nil
}
let components = (path as NSString).pathComponents
guard let end = components.firstIndex(where: { $0.hasSuffix(".app") }) else { return nil }
return NSString.path(withComponents: Array(components[...end]))
}

/// Best-effort meeting name from the capturing app's windows.
static func capture(forCapturePID pid: pid_t) -> String? {
let appPath = appBundlePath(forPID: pid)
let app = application(forCapturePID: pid, appPath: appPath)

for attribute in [kAXFocusedWindowAttribute, kAXMainWindowAttribute] {
guard let window = element(attribute, from: app) else { continue }
if let title = title(of: window, appPath: appPath) { return title }
}
guard let windows = windows(of: app) else { return nil }
return windows.lazy.compactMap { title(of: $0, appPath: appPath) }.first
}

/// Whether the capturing app still shows a window carrying this title.
static func windowExists(_ title: String, forCapturePID pid: pid_t) -> Bool {
let appPath = appBundlePath(forPID: pid)
let app = application(forCapturePID: pid, appPath: appPath)
// Failure is not evidence that the meeting ended. Preserve today's
// single-session behavior rather than splitting a live recording.
guard let windows = windows(of: app) else { return true }
return windows.contains { self.title(of: $0, appPath: appPath) == title }
}

/// Folder-safe title, capped at 60 characters.
nonisolated static func sanitized(_ title: String) -> String {
let replaced = title.replacingOccurrences(of: "/", with: "-")
.replacingOccurrences(of: ":", with: "-")
let clean = String(
replaced.split(whereSeparator: \.isWhitespace).joined(separator: " ").prefix(60)
)
return clean.contains(where: { $0.isLetter || $0.isNumber }) ? clean : ""
}

private static func application(forCapturePID pid: pid_t, appPath: String?) -> AXUIElement {
let ownerPID = appPath.flatMap { path in
NSWorkspace.shared.runningApplications.first {
$0.bundleURL?.path == path
}?.processIdentifier
} ?? pid
let app = AXUIElementCreateApplication(ownerPID)
AXUIElementSetMessagingTimeout(app, 0.25)
return app
}

private static func element(_ attribute: String, from element: AXUIElement) -> AXUIElement? {
var value: CFTypeRef?
guard AXUIElementCopyAttributeValue(element, attribute as CFString, &value) == .success,
let value,
CFGetTypeID(value) == AXUIElementGetTypeID()
else { return nil }
return unsafeDowncast(value, to: AXUIElement.self)
}

private static func windows(of app: AXUIElement) -> [AXUIElement]? {
var value: CFTypeRef?
guard AXUIElementCopyAttributeValue(
app,
kAXWindowsAttribute as CFString,
&value
) == .success,
let value,
CFGetTypeID(value) == CFArrayGetTypeID()
else { return nil }
return value as? [AXUIElement]
}

private static func title(of window: AXUIElement, appPath: String?) -> String? {
var value: CFTypeRef?
guard AXUIElementCopyAttributeValue(
window,
kAXTitleAttribute as CFString,
&value
) == .success,
let value,
CFGetTypeID(value) == CFStringGetTypeID()
else { return nil }
guard let title = value as? String else { return nil }
return clean(title, appPath: appPath)
}

private static func clean(_ title: String, appPath: String?) -> String? {
var clean = title.trimmingCharacters(in: .whitespacesAndNewlines)
guard !clean.isEmpty else { return nil }
guard let appPath else { return clean }

let appName = FileManager.default.displayName(atPath: appPath)
for separator in [" | ", " - ", " — "] {
let suffix = separator + appName
if clean.hasSuffix(suffix) {
clean.removeLast(suffix.count)
clean = clean.trimmingCharacters(in: .whitespacesAndNewlines)
break
}
}
guard !clean.isEmpty, clean.caseInsensitiveCompare(appName) != .orderedSame else {
return nil
}
return clean
}
}
53 changes: 52 additions & 1 deletion Sources/yap/RecordingSession.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@ import Foundation
/// audio than on a mixdown of two people talking over each other, and two
/// tracks give free two-party diarization.
final class RecordingSession {
let dir: URL
private(set) var dir: URL
let startedAt = Date()
var title: String?

private let mic = MicRecorder()
private let system = SystemAudioRecorder()
Expand Down Expand Up @@ -127,5 +128,55 @@ final class RecordingSession {
) {
try? data.write(to: dir.appendingPathComponent("meta.json"))
}
if let title { dir = Self.applyTitle(title, to: dir) }
}

/// Stamp a human title onto a finished session and return its final URL.
static func applyTitle(_ title: String, to dir: URL) -> URL {
let trimmed = title.trimmingCharacters(in: .whitespacesAndNewlines)
let clean = MeetingTitle.sanitized(trimmed)
guard !clean.isEmpty else { return dir }

let metaURL = dir.appendingPathComponent("meta.json")
var previousTitle: String?
if let data = try? Data(contentsOf: metaURL),
var meta = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] {
previousTitle = meta["title"] as? String
meta["title"] = trimmed
if let updated = try? JSONSerialization.data(
withJSONObject: meta, options: [.prettyPrinted, .sortedKeys]
) {
try? updated.write(to: metaURL, options: .atomic)
}
}

var base = dir.lastPathComponent
if let previousTitle {
let suffix = "-" + MeetingTitle.sanitized(previousTitle)
if base.hasSuffix(suffix) { base.removeLast(suffix.count) }
}
let parent = dir.deletingLastPathComponent()
let newName = base + "-" + clean
var destination = parent.appendingPathComponent(newName, isDirectory: true)
var n = 2
while destination != dir && FileManager.default.fileExists(atPath: destination.path) {
destination = parent.appendingPathComponent("\(newName)-\(n)", isDirectory: true)
n += 1
}

let transcriptURL = dir.appendingPathComponent("transcript.md")
if var transcript = try? String(contentsOf: transcriptURL, encoding: .utf8),
let lineEnd = transcript.firstIndex(of: "\n"),
transcript.hasPrefix("# ") {
transcript.replaceSubrange(transcript.startIndex..<lineEnd, with: "# \(destination.lastPathComponent)")
try? transcript.write(to: transcriptURL, atomically: true, encoding: .utf8)
}
guard destination != dir else { return dir }
do {
try FileManager.default.moveItem(at: dir, to: destination)
return destination
} catch {
return dir
}
}
}
Loading
Loading