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.

build: lsctl waits for each command's reply and can read and wait on the app's state

wqugurud3facab81ff5
diff --git a/.claude/skills/audio-test/scripts/room-round.sh b/.claude/skills/audio-test/scripts/room-round.sh
index dd41249..8b7e1d1 100755
--- a/.claude/skills/audio-test/scripts/room-round.sh
+++ b/.claude/skills/audio-test/scripts/room-round.sh
@@ -19,7 +19,7 @@ ctl=$repo/tools/lsctl
mkdir -p $WORK
[[ -x $WORK/audio ]] || swiftc -O $here/audio.swift -o $WORK/audio
[[ -f $WORK/table.wav ]] || python3 $here/clips.py $WORK >/dev/null
-[[ -x $ctl ]] || swiftc -O $repo/tools/lsctl.swift -o $ctl
+[[ $ctl -nt $repo/tools/lsctl.swift ]] || swiftc -O $repo/tools/lsctl.swift -o $ctl
$WORK/audio out "$OUT" >/dev/null
osascript -e "set volume output volume $vol"
diff --git a/.claude/skills/audio-test/scripts/speak-round.sh b/.claude/skills/audio-test/scripts/speak-round.sh
index dffd7ec..c6e482a 100755
--- a/.claude/skills/audio-test/scripts/speak-round.sh
+++ b/.claude/skills/audio-test/scripts/speak-round.sh
@@ -22,7 +22,7 @@ ctl=$repo/tools/lsctl
mkdir -p $WORK
[[ -x $WORK/audio ]] || swiftc -O $here/audio.swift -o $WORK/audio
[[ -f $WORK/me1.wav ]] || python3 $here/clips.py $WORK >/dev/null
-[[ -x $ctl ]] || swiftc -O $repo/tools/lsctl.swift -o $ctl
+[[ $ctl -nt $repo/tools/lsctl.swift ]] || swiftc -O $repo/tools/lsctl.swift -o $ctl
$WORK/audio out "$OUT" >/dev/null
osascript -e "set volume output volume $vol"
diff --git a/Sources/Cicada/AppModel.swift b/Sources/Cicada/AppModel.swift
index 0b8d7b7..b356c1d 100644
--- a/Sources/Cicada/AppModel.swift
+++ b/Sources/Cicada/AppModel.swift
@@ -30,7 +30,7 @@ final class AppModel: ObservableObject {
var roomEchoGate = true
/// The Mac's lines of late (wall clock), and room lines waiting to be told apart from their echo.
private var recentOnline: [EchoMatch.Heard] = []
- private var heldRoom: [(id: Int, seg: Segment, duration: Double, heard: EchoMatch.Heard)] = []
+ private(set) var heldRoom: [(id: Int, seg: Segment, duration: Double, heard: EchoMatch.Heard)] = []
/// What each engine shows as the line in progress, and when it last changed.
private var liveMain = (src: "", dst: "", at: Date.distantPast)
private var liveRoom = (src: "", dst: "", at: Date.distantPast)
@@ -1692,17 +1692,25 @@ final class AppModel: ObservableObject {
forName: Notification.Name(DevBuild.debugChannel), object: nil, queue: .main
) { [weak self] note in
let cmd = note.object as? String ?? ""
- MainActor.assumeIsolated { self?.debugCommand(cmd) }
+ let id = note.userInfo?["id"] as? String
+ MainActor.assumeIsolated { self?.runDebugCommand(cmd, id: id) }
}
debugLog("debug control ready")
MainThreadWatchdog.shared.start()
}
- private func debugCommand(_ cmd: String) {
+ func debugCommand(_ cmd: String) {
debugLog("debug command: \(cmd)")
let parts = cmd.split(separator: ":", maxSplits: 1).map(String.init)
let arg = parts.count > 1 ? parts[1] : ""
switch parts.first ?? "" {
+ case "ping":
+ let snapshot = debugSnapshot(["build"])
+ DebugRun.reply?.data = snapshot
+ case "state":
+ // Built first: a bad section fails the reply while the snapshot is made.
+ let snapshot = debugSnapshot(arg.split(separator: ",").map(String.init))
+ DebugRun.reply?.data = snapshot
// start:user is a click on 开始听; plain start is listening starting by itself.
case "start": start(byUser: arg == "user")
case "models":
@@ -1724,7 +1732,7 @@ final class AppModel: ObservableObject {
// share:<record id>[,full][,pw] shares a meeting as the sheet would (point a dev build at a
// local Worker with the shareServer default); unshare:<record id> turns it off.
let p = arg.split(separator: ",").map(String.init)
- guard let s = p.first.flatMap({ store.session($0) }) else { debugLog("share: no such record"); break }
+ guard let s = p.first.flatMap({ store.session($0) }) else { debugFail("share: no such record"); break }
var o = ShareClient.Options()
o.scope = p.contains("full") || s.notes?.isEmpty ?? true ? .full : .notes
o.password = p.contains("pw") ? SharePassword.make() : nil
@@ -1741,7 +1749,7 @@ final class AppModel: ObservableObject {
NotificationCenter.default.post(name: .debugShareSheet, object: arg.isEmpty ? nil : arg)
}
case "unshare":
- guard let r = ShareStore.read(arg) else { debugLog("share: \(arg) not shared"); break }
+ guard let r = ShareStore.read(arg) else { debugFail("share: \(arg) not shared"); break }
Task { debugLog("share: revoked \(await ShareClient.shared.revoke(r, sessionID: arg))") }
case "recordState": debugLog("record track: \(Recognition.recordTrack ? "on" : "off") settling=\(settling.count) tracked=\(refining.count)")
case "recognizer":
@@ -2251,7 +2259,7 @@ final class AppModel: ObservableObject {
let ok = writeExport(s, kind: kind, to: dir.appendingPathComponent("export.\(ext)"))
debugLog("export \(ext) ok=\(ok)")
}
- default: break
+ default: debugFail("unknown debug command: \(parts.first ?? "")", code: "unknown_command")
}
}
}
diff --git a/Sources/Cicada/DebugControl.swift b/Sources/Cicada/DebugControl.swift
new file mode 100644
index 0000000..a446ca3
--- /dev/null
+++ b/Sources/Cicada/DebugControl.swift
@@ -0,0 +1,144 @@
+import AppKit
+import Foundation
+
+/// The reply to one `tools/lsctl` command. lsctl waits for it by id instead of grepping the log, so an
+/// agent knows a command ran, failed or doesn't exist from the exit code alone. A command sent without
+/// an id (an older lsctl) gets no reply, as before.
+struct DebugReply {
+ var id: String
+ var ok = true
+ var error: (code: String, message: String)?
+ /// JSON-safe values only (`JSONSerialization`).
+ var data: Any?
+ /// What the command logged while it ran on the main thread; later lines (from Tasks) stay in the log.
+ var log: [String] = []
+
+ /// A distributed notification carries the reply, so it stays small: the newest lines win.
+ static let maxLogLines = 200
+ static let maxLogBytes = 48_000
+
+ func json() -> String {
+ var lines = Array(log.suffix(Self.maxLogLines))
+ while lines.reduce(0, { $0 + $1.utf8.count }) > Self.maxLogBytes, !lines.isEmpty { lines.removeFirst() }
+ var o: [String: Any] = ["id": id, "ok": ok, "log": lines]
+ if let error { o["error"] = ["code": error.code, "message": error.message] }
+ if let data, JSONSerialization.isValidJSONObject(["d": data]) { o["data"] = data }
+ guard let d = try? JSONSerialization.data(withJSONObject: o, options: [.sortedKeys]) else {
+ return #"{"id":"\#(id)","ok":false,"error":{"code":"encode","message":"reply not JSON"}}"#
+ }
+ return String(decoding: d, as: UTF8.self)
+ }
+}
+
+/// Lines logged on the main thread while a debug command runs (see `debugLog`).
+nonisolated(unsafe) var debugLogCapture: [String]?
+
+/// The command being run: cases mark a failure or hand back data through it.
+@MainActor enum DebugRun {
+ static var reply: DebugReply?
+}
+
+/// A debug command couldn't do what it was asked: logged, and the reply says so (lsctl exits 1).
+/// It writes `DebugRun.reply`, so never call it (or what calls it) from the right side of an
+/// assignment to `DebugRun.reply?.…`: overlapping access aborts. Build the value first.
+@MainActor func debugFail(_ message: String, code: String = "failed") {
+ debugLog(message)
+ DebugRun.reply?.ok = false
+ DebugRun.reply?.error = (code, message)
+}
+
+extension AppModel {
+ func runDebugCommand(_ cmd: String, id: String?) {
+ guard let id else { debugCommand(cmd); return }
+ DebugRun.reply = DebugReply(id: id)
+ debugLogCapture = []
+ debugCommand(cmd)
+ var reply = DebugRun.reply ?? DebugReply(id: id)
+ reply.log = debugLogCapture ?? []
+ debugLogCapture = nil
+ DebugRun.reply = nil
+ DistributedNotificationCenter.default().postNotificationName(
+ Notification.Name(DevBuild.debugChannel + ".reply"), object: reply.json(), userInfo: nil, deliverImmediately: true)
+ }
+
+ /// `state[:section,…]`: what the app is doing now, as JSON, for agents (`lsctl state`, `lsctl --wait`).
+ /// Read straight from the engines, never a copy. No keys or tokens, only whether there is one;
+ /// what was said only with the debug setting on, as in the log.
+ func debugSnapshot(_ only: [String]) -> [String: Any] {
+ let content = settings.debug
+ var all: [String: () -> Any] = [:]
+ all["build"] = { [
+ "version": Updates.current, "dev": DevBuild.isDev, "label": DevBuild.label ?? "",
+ "channel": DevBuild.channel ?? "", "pid": Int(ProcessInfo.processInfo.processIdentifier),
+ ] }
+ all["permissions"] = { [
+ "systemAudio": self.systemAudioOK, "systemAudioRefused": self.systemAudioRefused, "speech": self.speechOK,
+ "mic": String(describing: self.micStatus.rawValue), "talkNeedsPermission": self.talkNeedsPermission,
+ ] }
+ all["listen"] = { [
+ "running": self.listen.isRunning, "status": self.status, "source": self.settings.listenSource,
+ "sourceSelection": self.sourceSelection, "lang": self.listen.activeLang?.locale ?? "",
+ "target": self.settings.target, "recognizer": Recognition.name, "recordTrack": Recognition.recordTrack,
+ "identifyingLanguage": self.identifyingLanguage, "liveID": self.store.liveID ?? "",
+ "autoEnded": self.autoEnded, "endPending": self.ending.map { "\($0.reason)" } ?? "",
+ "cloud": [
+ "service": self.cloud.service ?? "", "offered": self.cloud.offered, "listening": self.cloud.listening,
+ ] as [String: Any],
+ "modelProblem": self.modelProblem.map { "\($0)" } ?? "",
+ "translation": [
+ "googleDown": self.translationHealth.googleDown, "googleOff": self.translationHealth.googleOff,
+ "sentencesUntranslated": self.translationHealth.sentencesUntranslated,
+ ],
+ ].merging(content ? ["liveSource": self.liveSource, "liveTranslation": self.liveTranslation] : [:]) { a, _ in a } }
+ all["room"] = { [
+ "running": self.roomListen.isRunning, "lang": self.roomListen.activeLang?.locale ?? "",
+ "echo": String(describing: self.roomListen.echoGate.echo), "echoCancelled": self.roomListen.hearsEchoCancelled,
+ "music": self.roomListen.echoGate.playingMusic(), "micSilent": self.roomMicSilent,
+ "micLost": self.roomMicLost ?? "", "micDenied": self.hybridMicDenied, "held": self.heldRoom.count,
+ "voicedSeconds": self.roomListen.router.stats().voicedTotal,
+ ] }
+ all["display"] = { [
+ "mode": self.settings.displayMode, "notesShown": self.notesShown,
+ "notesWindow": [
+ "visible": self.notesWindow.isVisible, "layout": "\(self.notesWindow.layout)",
+ "frame": self.notesWindow.frame.map { [$0.origin.x, $0.origin.y, $0.width, $0.height] } ?? [],
+ ] as [String: Any],
+ "overlay": ["shown": self.overlay.isShown, "expanded": self.overlay.expanded],
+ "keyWindow": NSApp.keyWindow?.title ?? "",
+ "onboardingStep": self.onboardingStep, "mainShow": self.mainShow ?? "",
+ ] }
+ all["notes"] = { [
+ "state": "\(self.notes.state)", "topics": self.notes.notes.topics.count,
+ "covered": self.notes.notes.covered, "glossary": self.notes.glossary.count, "fresh": self.notes.fresh.count,
+ ] }
+ all["speak"] = { [
+ "enabled": self.settings.speakEnabled, "phase": "\(self.speakPhase)", "mic": self.speak.micDeviceName,
+ "output": self.speak.outputDevice()?.name ?? "", "voiceMicInUse": self.voiceMic.inUse,
+ "test": ["shown": self.speakTestShown, "phase": "\(self.speakTester.phase)"] as [String: Any],
+ ] }
+ all["ai"] = { [
+ "keyState": "\(self.ling.keyState)", "hasKey": self.ling.hasKey,
+ "provider": self.settings.aiConfig.provider.id.rawValue, "model": self.settings.aiConfig.textModel,
+ "check": self.ling.aiCheck.summary,
+ ] }
+ all["import"] = { [
+ "current": self.importer.current?.id ?? "", "phase": "\(self.importer.phase)",
+ "queue": self.importer.queue.map(\.id),
+ ] }
+ all["update"] = { [
+ "current": Updates.current, "found": self.updates.update?.version ?? "",
+ "check": "\(self.updates.check)", "failure": self.updates.failure ?? "",
+ ] }
+ all["records"] = { [
+ "count": self.store.sessions.count, "latest": self.store.sessions.first?.id ?? "",
+ ] }
+ all["problem"] = { self.problem ?? "" }
+
+ var out: [String: Any] = ["schema": 1, "at": ISO8601DateFormatter().string(from: Date())]
+ let keys = only.isEmpty ? Array(all.keys) : only
+ for k in keys {
+ if let f = all[k] { out[k] = f() } else { debugFail("state: no section \(k) (have \(all.keys.sorted().joined(separator: ",")))", code: "bad_argument") }
+ }
+ return out
+ }
+}
diff --git a/Sources/Cicada/Settings.swift b/Sources/Cicada/Settings.swift
index 998bd92..359e45f 100644
--- a/Sources/Cicada/Settings.swift
+++ b/Sources/Cicada/Settings.swift
@@ -354,6 +354,7 @@ final class AppSettings: ObservableObject {
}
func debugLog(_ message: String) {
+ if Thread.isMainThread, debugLogCapture != nil { debugLogCapture?.append(message) }
let line = "\(Date()) \(message)\n"
let path = DevBuild.logPath
if let handle = FileHandle(forWritingAtPath: path) {
diff --git a/Tests/CicadaTests/DebugReplyTests.swift b/Tests/CicadaTests/DebugReplyTests.swift
new file mode 100644
index 0000000..c38a911
--- /dev/null
+++ b/Tests/CicadaTests/DebugReplyTests.swift
@@ -0,0 +1,47 @@
+import Foundation
+import Testing
+@testable import Cicada
+
+@Suite struct DebugReplyTests {
+ private func decode(_ r: DebugReply) -> [String: Any] {
+ (try? JSONSerialization.jsonObject(with: Data(r.json().utf8))) as? [String: Any] ?? [:]
+ }
+
+ @Test func successCarriesDataAndLog() {
+ var r = DebugReply(id: "a1")
+ r.data = ["listen": ["running": true]]
+ r.log = ["debug command: state"]
+ let o = decode(r)
+ #expect(o["id"] as? String == "a1")
+ #expect(o["ok"] as? Bool == true)
+ #expect(o["error"] == nil)
+ #expect(((o["data"] as? [String: Any])?["listen"] as? [String: Any])?["running"] as? Bool == true)
+ #expect(o["log"] as? [String] == ["debug command: state"])
+ }
+
+ @Test func failureHasACode() {
+ var r = DebugReply(id: "b2")
+ r.ok = false
+ r.error = ("unknown_command", "unknown debug command: x")
+ let o = decode(r)
+ #expect(o["ok"] as? Bool == false)
+ #expect((o["error"] as? [String: Any])?["code"] as? String == "unknown_command")
+ }
+
+ @Test func dataThatIsNotJSONIsDroppedNotFatal() {
+ var r = DebugReply(id: "c3")
+ r.data = ["when": Date()]
+ let o = decode(r)
+ #expect(o["id"] as? String == "c3")
+ #expect(o["data"] == nil)
+ }
+
+ @Test func longLogKeepsTheNewestLinesWithinTheLimit() {
+ var r = DebugReply(id: "d4")
+ r.log = (0..<1000).map { "line \($0) " + String(repeating: "x", count: 200) }
+ let log = decode(r)["log"] as? [String] ?? []
+ #expect(log.count <= DebugReply.maxLogLines)
+ #expect(log.reduce(0) { $0 + $1.utf8.count } <= DebugReply.maxLogBytes)
+ #expect(log.last?.hasPrefix("line 999 ") == true)
+ }
+}
diff --git a/tools/README.md b/tools/README.md
index 3ae2e6d..fcabcbb 100644
--- a/tools/README.md
+++ b/tools/README.md
@@ -6,6 +6,9 @@
编译:`swiftc -O lsctl.swift -o lsctl`(其他几个文件同理)。
- `lsctl <命令>`:通过分布式通知 `com.wquguru.cicada.debug` 遥控 App。
+ - 回复:每条命令带一个 id,App 在 `com.wquguru.cicada.debug.reply` 上回 JSON(`id`、`ok`、`error.code`、`data`、`log`),lsctl 等到它才退出。退出码:0 成功,1 命令失败,2 没有回复(App 没开、没开调试模式或是旧版),3 没有这个命令,64 用法错。标准输出只有 `data`(`lsctl state | jq` 可用),命令执行时写的日志行和错误在标准错误;`--json` 打印整个回复,`--timeout <秒>` 改等待时间(默认 3),`--no-reply` 像以前一样发完就走。命令里用 `Task` 晚些才写的日志不在回复里,仍看日志文件
+ - 状态:`state[:<分区>,…]` 把当前状态以 JSON 输出(`schema`、`at`,分区 `build` `permissions` `listen` `room` `display` `notes` `speak` `ai` `import` `update` `records` `problem`),直接从各引擎读;没有 key 和 token,原文只在调试模式下给。`ping` 只回 `build`
+ - 等待:`lsctl --wait '<路径> <==|!=|>|<|>=|<=> <值>'` 反复取 `state` 直到成立(默认最多 10 秒,超时退出 2 并写出当时的值),如 `lsctl start:user && lsctl --wait 'display.notesWindow.visible == true'`。布尔值只能用 `==` / `!=` 比 `true` / `false`
- 开关字幕:`start` / `stop`(`start:user` 当作用户点了开始听,纪要窗口立即出现;`start` 当作自动开始,等到有人说话)
- 麦克风:`mic:<on|off>` 等于点“打开麦克风”/“关闭麦克风”(没在听时打开会开始听;旧的 `listenSource:<system|room|both>` 也还能用),`hybridState` 把两边的状态写进日志,含 `echo=` 和测量值(扬声器传到麦克风没有)、`music=`、`micSilent=`;`roomEcho:on` / `roomGate:off` 下一场会议用系统回声消除 / 不在电脑放人声时关麦克风,单独试每道防线,日志 `hybrid: room line dropped as an echo` / `kept`、`room echo: speakers reach the mic` / `none`;`roomEchoSim:<on|off|real>` 假装测出(或没测出)回声;`roomMicSilent:<on|off>` 让麦克风从下次打开起只给 0(日志 `room mic: silent since it started`,再 `still silent`,纪要窗口出“麦克风没声音”);`voiceMicRun:<on|off>` 只开回声消除单元看它对别的声音有没有影响;念译文时 `room mic muted` / `open`;`micDeniedSim:<on|off>` 让麦克风当作被拒(纪要窗口顶部提示、字幕条橙色标签、菜单栏橙点,纪要窗口收起 10 秒后发一次通知,日志 `problem:` 和 `menu bar: badge=`)。实测回声、桌边的话和同声传译:`.claude/skills/audio-test`
- 打开界面:`open`(主窗口)、`panel`(菜单栏面板)、`settings[:speak]`(设置,可指定栏目)
diff --git a/tools/lsctl.swift b/tools/lsctl.swift
index d40367a..e5a12b1 100644
--- a/tools/lsctl.swift
+++ b/tools/lsctl.swift
@@ -1,6 +1,119 @@
import Foundation
-let cmd = CommandLine.arguments.dropFirst().joined(separator: " ")
+
+// lsctl [--json] [--timeout <s>] <command> send one debug command, wait for its reply
+// lsctl [--timeout <s>] --wait '<path> <op> <value>' poll `state` until it holds, e.g. 'display.notesWindow.visible == true'
+// lsctl --no-reply <command> fire and forget, as lsctl always did
+//
+// Exit: 0 done, 1 the command failed, 2 no reply (app not running, debug control off, old build),
+// 3 unknown command, 64 bad usage. stdout: `data` as JSON; stderr: the command's log lines and errors.
+
+var args = Array(CommandLine.arguments.dropFirst())
+var json = false, noReply = false, timeout: Double?, waitExpr: String?
+while let a = args.first, a.hasPrefix("--") {
+ args.removeFirst()
+ switch a {
+ case "--json": json = true
+ case "--no-reply": noReply = true
+ case "--timeout": timeout = Double(args.isEmpty ? "" : args.removeFirst())
+ case "--wait": waitExpr = args.isEmpty ? nil : args.removeFirst(); if waitExpr == nil { exit(64) }
+ default: FileHandle.standardError.write("lsctl: unknown option \(a)\n".data(using: .utf8)!); exit(64)
+ }
+}
+let cmd = args.joined(separator: " ")
+// One reply comes in well under a second; a condition may take a while (a model to load, a window).
+let limit = timeout ?? (waitExpr == nil ? 3 : 10)
+if cmd.isEmpty && waitExpr == nil { FileHandle.standardError.write("usage: lsctl [--json] [--timeout s] [--wait expr] <command>\n".data(using: .utf8)!); exit(64) }
+
// CICADA_DEBUG_CHANNEL picks one running copy (see DevBuild.debugChannel).
let channel = ProcessInfo.processInfo.environment["CICADA_DEBUG_CHANNEL"].map { $0.isEmpty ? "" : "." + $0 } ?? ""
-DistributedNotificationCenter.default().postNotificationName(Notification.Name("com.wquguru.cicada.debug" + channel), object: cmd, userInfo: nil, deliverImmediately: true)
-RunLoop.main.run(until: Date().addingTimeInterval(0.2))
+let name = "com.wquguru.cicada.debug" + channel
+let center = DistributedNotificationCenter.default()
+
+var replies: [String: [String: Any]] = [:]
+let observer = center.addObserver(forName: Notification.Name(name + ".reply"), object: nil, queue: nil) { note in
+ guard let s = note.object as? String, let d = s.data(using: .utf8),
+ let o = try? JSONSerialization.jsonObject(with: d) as? [String: Any], let id = o["id"] as? String else { return }
+ replies[id] = o
+}
+
+/// Sends one command and runs the run loop until its reply comes, or nil after `limit` seconds.
+func send(_ cmd: String, limit: Double) -> [String: Any]? {
+ let id = String(UUID().uuidString.prefix(8)).lowercased()
+ center.postNotificationName(Notification.Name(name), object: cmd, userInfo: ["id": id], deliverImmediately: true)
+ let end = Date().addingTimeInterval(limit)
+ while replies[id] == nil, Date() < end { RunLoop.main.run(until: Date().addingTimeInterval(0.02)) }
+ return replies.removeValue(forKey: id)
+}
+
+func jsonText(_ v: Any) -> String {
+ if let s = v as? String { return s }
+ guard JSONSerialization.isValidJSONObject(["v": v]),
+ let d = try? JSONSerialization.data(withJSONObject: v, options: [.prettyPrinted, .sortedKeys, .fragmentsAllowed]) else { return "\(v)" }
+ return String(decoding: d, as: UTF8.self)
+}
+
+func exitCode(_ r: [String: Any]) -> Int32 {
+ if r["ok"] as? Bool == true { return 0 }
+ return (r["error"] as? [String: Any])?["code"] as? String == "unknown_command" ? 3 : 1
+}
+
+/// `notes.state == idle`, `display.notesWindow.visible == true`, `room.voicedSeconds > 2`.
+func holds(_ expr: String, in state: [String: Any]) -> Bool {
+ let ops = ["==", "!=", ">=", "<=", ">", "<"]
+ guard let op = ops.first(where: { expr.contains($0) }) else { return false }
+ let sides = expr.components(separatedBy: op).map { $0.trimmingCharacters(in: .whitespaces) }
+ guard sides.count == 2 else { return false }
+ var v: Any? = state
+ for k in sides[0].split(separator: ".") { v = (v as? [String: Any])?[String(k)] }
+ guard let v else { return false }
+ let want = sides[1].trimmingCharacters(in: CharacterSet(charactersIn: "\"'"))
+ if let n = v as? NSNumber, CFGetTypeID(n) != CFBooleanGetTypeID(), let w = Double(want) {
+ let x = n.doubleValue
+ switch op { case "==": return x == w; case "!=": return x != w; case ">": return x > w
+ case "<": return x < w; case ">=": return x >= w; default: return x <= w }
+ }
+ let s = (v as? NSNumber).map { CFGetTypeID($0) == CFBooleanGetTypeID() ? ($0.boolValue ? "true" : "false") : $0.stringValue }
+ ?? (v as? String) ?? jsonText(v)
+ switch op { case "==": return s == want; case "!=": return s != want; default: return false }
+}
+
+if noReply {
+ center.postNotificationName(Notification.Name(name), object: cmd, userInfo: nil, deliverImmediately: true)
+ RunLoop.main.run(until: Date().addingTimeInterval(0.2))
+ exit(0)
+}
+
+if !cmd.isEmpty {
+ guard let r = send(cmd, limit: limit) else {
+ FileHandle.standardError.write("lsctl: no reply in \(limit) s (is the app running with debug control on? channel \(name))\n".data(using: .utf8)!)
+ exit(2)
+ }
+ if json { print(jsonText(r)) } else {
+ // stdout is only `data`, so `lsctl state | jq` works; what the command logged goes to stderr.
+ for l in r["log"] as? [String] ?? [] { FileHandle.standardError.write((l + "\n").data(using: .utf8)!) }
+ if let d = r["data"] { print(jsonText(d)) }
+ if let e = r["error"] as? [String: Any] { FileHandle.standardError.write("lsctl: \(e["code"] ?? "") \(e["message"] ?? "")\n".data(using: .utf8)!) }
+ }
+ if exitCode(r) != 0 || waitExpr == nil { exit(exitCode(r)) }
+}
+
+if let waitExpr {
+ // A wait is its own budget: --timeout is how long the condition may take, not one reply.
+ // The section is the path up to its first dot, space or operator (`problem == x` is top level).
+ let section = String(waitExpr.trimmingCharacters(in: .whitespaces).prefix { $0 != "." && $0 != " " && !"=!<>".contains($0) })
+ let end = Date().addingTimeInterval(limit)
+ var last: [String: Any]?
+ repeat {
+ if let r = send("state:\(section)", limit: min(2, max(0.1, end.timeIntervalSinceNow))) {
+ if r["ok"] as? Bool != true { FileHandle.standardError.write("lsctl: \(jsonText(r["error"] ?? ""))\n".data(using: .utf8)!); exit(64) }
+ last = r["data"] as? [String: Any]
+ if let last, holds(waitExpr, in: last) { exit(0) }
+ }
+ RunLoop.main.run(until: Date().addingTimeInterval(0.2))
+ } while Date() < end
+ var v: Any? = last
+ for k in waitExpr.split(whereSeparator: { " =!<>".contains($0) }).first?.split(separator: ".") ?? [] { v = (v as? [String: Any])?[String(k)] }
+ FileHandle.standardError.write("lsctl: still not \(waitExpr) after \(limit) s (now \(last == nil ? "no reply" : jsonText(v ?? "missing")))\n".data(using: .utf8)!)
+ exit(2)
+}
+_ = observer