Skip to content

知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.

chore: dev builds sample the main thread when it is stuck for 2 s, to catch the talk-key freeze

wqugurue68cc3dc924c
diff --git a/Sources/Cicada/AppModel.swift b/Sources/Cicada/AppModel.swift
index 38d1ff5..8a59d97 100644
--- a/Sources/Cicada/AppModel.swift
+++ b/Sources/Cicada/AppModel.swift
@@ -1658,6 +1658,7 @@ final class AppModel: ObservableObject {
MainActor.assumeIsolated { self?.debugCommand(cmd) }
}
debugLog("debug control ready")
+ MainThreadWatchdog.shared.start()
}
private func debugCommand(_ cmd: String) {
@@ -2024,6 +2025,8 @@ final class AppModel: ObservableObject {
// talkDown / talkUp: the talk key held and let go, with the real microphone (audio tests).
case "talkDown": speak.pressBegan()
case "talkUp": speak.pressEnded()
+ // stall:<seconds> blocks the main thread, to check the watchdog samples it.
+ case "stall": Thread.sleep(forTimeInterval: Double(arg) ?? 3)
case "speakVP": speak.echoCancel = arg != "off"
case "voiceMicRun":
// voiceMicRun:<on|off> runs the echo-cancelling unit with nobody listening (what it does to the rest).
diff --git a/Sources/Cicada/Watchdog.swift b/Sources/Cicada/Watchdog.swift
new file mode 100644
index 0000000..bcb34b5
--- /dev/null
+++ b/Sources/Cicada/Watchdog.swift
@@ -0,0 +1,71 @@
+import Foundation
+
+/// Dev builds (and the debug mode): notices the main thread stuck and has `sample` record every
+/// thread's stack while it still is, so a freeze nobody can reproduce on demand (the talk key with
+/// the room mic open) leaves its frame behind. One sample per stall, written next to the log.
+final class MainThreadWatchdog: @unchecked Sendable {
+ static let shared = MainThreadWatchdog()
+
+ /// A main thread silent this long counts as stuck.
+ static let stuckAfter = 2.0
+
+ private let lock = NSLock()
+ private var lastPong = Date()
+ private var started = false
+ private var stalled = false
+ private var resumedAt: Date?
+
+ func start() {
+ let first = lock.withLock { () -> Bool in defer { started = true }; return !started }
+ guard first else { return }
+ let thread = Thread { [self] in run() }
+ thread.name = "com.wquguru.cicada.watchdog"
+ thread.qualityOfService = .userInteractive
+ thread.start()
+ debugLog("watchdog: watching the main thread (stuck after \(Self.stuckAfter) s)")
+ }
+
+ private func run() {
+ var stuckSince: Date?
+ while true {
+ Thread.sleep(forTimeInterval: 0.25)
+ // The first ping to run after a stall marks when the main thread came back: the sample
+ // itself takes seconds, so the time this loop next looks is too late.
+ DispatchQueue.main.async { [self] in
+ lock.withLock {
+ if resumedAt == nil, stalled { resumedAt = Date() }
+ lastPong = Date()
+ }
+ }
+ let silent = Date().timeIntervalSince(lock.withLock { lastPong })
+ if silent >= Self.stuckAfter, stuckSince == nil {
+ stuckSince = Date().addingTimeInterval(-silent)
+ lock.withLock { stalled = true; resumedAt = nil }
+ sample(silentFor: silent)
+ } else if let since = stuckSince, let back = lock.withLock({ resumedAt }) {
+ debugLog(String(format: "watchdog: main thread back after %.1f s", back.timeIntervalSince(since)))
+ stuckSince = nil
+ lock.withLock { stalled = false; resumedAt = nil }
+ }
+ }
+ }
+
+ /// `sample` blocks this thread for its duration, which is fine: there is one stall to record.
+ private func sample(silentFor silent: Double) {
+ let stamp = ISO8601DateFormatter().string(from: Date()).replacingOccurrences(of: ":", with: "")
+ let path = DevBuild.logPath.replacingOccurrences(of: ".log", with: "-hang-\(stamp).txt")
+ debugLog(String(format: "watchdog: main thread stuck %.1f s, sampling to %@", silent, path))
+ let p = Process()
+ p.executableURL = URL(fileURLWithPath: "/usr/bin/sample")
+ p.arguments = [String(ProcessInfo.processInfo.processIdentifier), "5", "-mayDie", "-file", path]
+ p.standardOutput = FileHandle.nullDevice
+ p.standardError = FileHandle.nullDevice
+ do {
+ try p.run()
+ p.waitUntilExit()
+ debugLog("watchdog: sample \(p.terminationStatus == 0 ? "written" : "failed (\(p.terminationStatus))")")
+ } catch {
+ debugLog("watchdog: sample failed to start: \(error)")
+ }
+ }
+}
diff --git a/tools/README.md b/tools/README.md
index 8b2b111..3ae2e6d 100644
--- a/tools/README.md
+++ b/tools/README.md
@@ -11,6 +11,7 @@
- 打开界面:`open`(主窗口)、`panel`(菜单栏面板)、`settings[:speak]`(设置,可指定栏目)
- 虚拟麦克风:`micTest` 试音(往虚拟麦克风播一句再听回来,结果写进日志),`micNext` 做清单里的下一步
- 会议软件的麦克风:`micUsers` 把每个读麦克风的进程和列表写进日志,`micGuide:<bundle id 或名字>` 打开怎么改,`micGuideRender:<bundle id>=<png>`
+ - 卡死:开发版(和调试模式)主线程超过 2 秒没反应时自动 `sample` 一次,存成日志旁边的 `/tmp/livesubs-dev-debug-hang-<时间>.txt`,日志 `watchdog: main thread stuck` / `back after … s`;`stall:<秒>` 故意卡住主线程来试它
- 快捷键:`talkKey:right` 或 `talkKey:<keyCode>:<Carbon 修饰键>` 换说话键(被拒的原因写进日志),`toggleKey:…` 同理,`shortcuts` 把当前状态写进日志
- 字幕条:`frame` 把位置写进日志,`place:x,y,宽,字号` 摆到指定位置
- 系统麦克风:`sysMic` 把状态、默认输入、要换回的麦克风和知了实际在录的麦克风写进日志,`sysMicSet:<设备名片段>` 假装别人改了系统麦克风,`sysMicRestore` 还原,`sysMicSwitch` 换成虚拟麦克风,`sysMicAuto:<on|off>`,`speakMic:<设备名片段>` 固定知了用的麦克风(留空 = 自动)。会改本机的系统麦克风:测完 `sysMicRestore` 或退出 App