Fastest and only macOS Dictation app with on-device STT and custom trained AI enhancement model. Windows, iOS testflight! Android, Linux waitlist open! A local Wispr Flow alternative. Follow https://x.com/fluidvoiceapp for more
feat(bench): log stop input timing and post-dispatch waits
altic-dev74a1ee8b7ce0
diff --git a/Sources/Fluid/ContentView.swift b/Sources/Fluid/ContentView.swiftindex 96d487f1..6f67664c 100644--- a/Sources/Fluid/ContentView.swift+++ b/Sources/Fluid/ContentView.swift@@ -2127,12 +2127,22 @@ struct ContentView: View {}private func resolveTypingTargetPID() -> (pid: pid_t?, shouldRestoreOriginalFocus: Bool) {+ let startedAt = ProcessInfo.processInfo.systemUptimeguard let context = NotchContentState.shared.recordingTargetContext else {+ self.appBench("focus_target_check totalMs=\((ProcessInfo.processInfo.systemUptime - startedAt) * 1000) missingContext=true")return (NotchContentState.shared.recordingTargetPID, true)}- let isStillFocused = context.pid == TypingService.currentFocusedPID() &&- (context.element == nil || TypingService.isCapturedFocusStillActive(context))- return (context.pid, !isStillFocused)+ let pidStartedAt = ProcessInfo.processInfo.systemUptime+ let focusedPID = TypingService.currentFocusedPID()+ let pidFinishedAt = ProcessInfo.processInfo.systemUptime+ let checksElement = context.pid == focusedPID && context.element != nil+ let elementIsFocused = !checksElement || TypingService.isCapturedFocusStillActive(context)+ let finishedAt = ProcessInfo.processInfo.systemUptime+ self.appBench(+ "focus_target_check totalMs=\((finishedAt - startedAt) * 1000) pidMs=\((pidFinishedAt - pidStartedAt) * 1000) " ++ "elementMs=\((finishedAt - pidFinishedAt) * 1000) elementChecked=\(checksElement)"+ )+ return (context.pid, !(context.pid == focusedPID && elementIsFocused))}// MARK: - Commented out app-specific prompts - using general processing only@@ -2567,7 +2577,7 @@ struct ContentView: View {private func processStoppedTranscription(route: DictationOutputRoute, pipelineID: String, toggleStopRequestedAt: TimeInterval?) async {let pipelineStartedAt = ProcessInfo.processInfo.systemUptimelet expectedOverlayLifecycleID = self.overlayLifecycleID- self.appBench("pipeline_begin id=\(pipelineID) route=\(route.rawValue)")+ self.appBench("pipeline_begin id=\(pipelineID) route=\(route.rawValue) toggleStopRequestedAt=\(toggleStopRequestedAt.map { String($0) } ?? "nil")")defer {self.appBench("pipeline_handler_return id=\(pipelineID) elapsedMs=\((ProcessInfo.processInfo.systemUptime - pipelineStartedAt) * 1000) deliveryMayBePending=true")}@@ -3577,17 +3587,12 @@ struct ContentView: View {return}- let typingTarget = self.resolveTypingTargetPID()- guard typingTarget.pid != nil else {+ // Paste Last is a new insertion at the current cursor, independent of+ // the previous recording's saved target. Never restore that older focus here.+ guard let targetPID = TypingService.currentFocusedPID(), targetPID != ProcessInfo.processInfo.processIdentifier else {DebugLogger.shared.info("Actions: Paste skipped - no external target field available", source: "ContentView")return}- if typingTarget.shouldRestoreOriginalFocus {- guard await self.restoreFocusToRecordingTarget() else {- self.showTextDeliveryFailure(.targetRestoreFailed, transcript: text)- return- }- }let appInfo = self.getCurrentAppInfo()let outputPlan = ASRService.makeDictationLiteralOutputPlan(for: text,@@ -3597,7 +3602,7 @@ struct ContentView: View {)let result = await self.asr.typeOutputPlanToActiveField(outputPlan,- preferredTargetPID: typingTarget.pid+ preferredTargetPID: targetPID)if case let .recoverableFailure(failure) = result {self.showTextDeliveryFailure(failure, transcript: text)diff --git a/Sources/Fluid/Services/ASRService.swift b/Sources/Fluid/Services/ASRService.swiftindex e7ddaf94..0dd2b570 100644--- a/Sources/Fluid/Services/ASRService.swift+++ b/Sources/Fluid/Services/ASRService.swift@@ -5534,6 +5534,20 @@ final class ASRService: ObservableObject {message: "asr_type_dispatched chars=\(text.count) preferredPID=\(preferredTargetPID.map { String($0) } ?? "nil") result=\(String(describing: result)) textReadyToDispatchMs=\(textReadyToDispatchMs)",source: "TypingBenchmark")+ if case .commandPosted = result {+ let scheduledAt = ProcessInfo.processInfo.systemUptime+ let pipelineID = DebugLogger.pipelineID+ // One queued timestamp per output. No polling, AX queries or delivery waits.+ DispatchQueue.main.async {+ DebugLogger.$pipelineID.withValue(pipelineID) {+ DebugLogger.shared.benchmark(+ "APP_BENCH",+ message: "dispatch_main_queue_probe scheduledAt=\(scheduledAt)",+ source: "AppBenchmark"+ )+ }+ }+ }return result}diff --git a/Sources/Fluid/Services/GlobalHotkeyManager.swift b/Sources/Fluid/Services/GlobalHotkeyManager.swiftindex 467887b8..da064651 100644--- a/Sources/Fluid/Services/GlobalHotkeyManager.swift+++ b/Sources/Fluid/Services/GlobalHotkeyManager.swift@@ -14,6 +14,22 @@ private nonisolated enum ActivePrimaryShortcutPress: Equatable {case mouse(Int)}+/// Input timing only: never changes shortcut routing or retains a keyboard event.+struct HotkeyInputTiming {+ let receivedAt: TimeInterval+ let eventTimestamp: UInt64+ let eventType: UInt32++ let receivedTimestamp: UInt64++ /// Quartz event timestamps and DispatchTime uptime are nanoseconds since boot.+ /// Keep this clock separate from the ProcessInfo timestamp used by the pipeline.+ var deliveryAgeMs: Double? {+ guard self.eventTimestamp > 0, self.receivedTimestamp >= self.eventTimestamp else { return nil }+ return Double(self.receivedTimestamp - self.eventTimestamp) / 1_000_000+ }+}+/// Snapshot of the modifier-only tracking state fed into `ModifierOnlyShortcutFlagsDecision`.struct ModifierOnlyShortcutTrackingState: Equatable {/// Currently-pressed modifier key codes (output of `synchronizedPressedModifierKeyCodes`).@@ -232,6 +248,10 @@ final class GlobalHotkeyManager: NSObject {private nonisolated(unsafe) var state = HotkeyState()private nonisolated(unsafe) var eventTap: CFMachPort?private nonisolated(unsafe) var runLoopSource: CFRunLoopSource?+ /// Keyboard tap events are serviced here, not on the main run loop, so main-thread+ /// work after a paste never holds the synthetic Cmd+V (or any keystroke) in our tap.+ private nonisolated(unsafe) var keyboardTapRunLoop: CFRunLoop?+ private nonisolated(unsafe) var keyboardTapThread: Thread?private nonisolated(unsafe) var mouseObserverTap: CFMachPort?private nonisolated(unsafe) var mouseObserverSource: CFRunLoopSource?private nonisolated(unsafe) var mouseShortcutTap: CFMachPort?@@ -262,6 +282,9 @@ final class GlobalHotkeyManager: NSObject {private var pasteLastTranscriptionCallback: (() -> Void)?private var hotkeyMode: HotkeyActivationMode = SettingsStore.shared.hotkeyModeprivate let automaticTapThresholdSeconds: TimeInterval = 0.4+ private var currentInputTiming: HotkeyInputTiming?+ private var modifierPressReceivedAt: TimeInterval?+ private var currentStopPressReceivedAt: TimeInterval?private struct ModifierOnlyShortcutBehavior {let shortcut: HotkeyShortcut@@ -983,6 +1006,15 @@ final class GlobalHotkeyManager: NSObject {}private func handleMouseShortcutEvent(type: CGEventType, event: CGEvent) -> Unmanaged<CGEvent>? {+ let previousInput = self.currentInputTiming+ self.currentInputTiming = HotkeyInputTiming(+ receivedAt: ProcessInfo.processInfo.systemUptime,+ eventTimestamp: event.timestamp,+ eventType: type.rawValue,+ receivedTimestamp: DispatchTime.now().uptimeNanoseconds+ )+ defer { self.currentInputTiming = previousInput }+if type == .tapDisabledByTimeout || type == .tapDisabledByUserInput {self.finishInterruptedMouseShortcutPress(reason: "mouse shortcut tap disabled")self.reenableMouseTap(self.mouseShortcutTap, label: "Mouse shortcut") {@@ -1144,6 +1176,15 @@ final class GlobalHotkeyManager: NSObject {}private func handleKeyEvent(proxy: CGEventTapProxy, type: CGEventType, event: CGEvent) -> Unmanaged<CGEvent>? {+ let previousInput = self.currentInputTiming+ self.currentInputTiming = HotkeyInputTiming(+ receivedAt: ProcessInfo.processInfo.systemUptime,+ eventTimestamp: event.timestamp,+ eventType: type.rawValue,+ receivedTimestamp: DispatchTime.now().uptimeNanoseconds+ )+ defer { self.currentInputTiming = previousInput }+if let tapRecoveryResult = self.handleTapDisableEvent(type: type, event: event) {return tapRecoveryResult}@@ -1756,6 +1797,8 @@ final class GlobalHotkeyManager: NSObject {return}+ let toggleStopRequestedAt = ProcessInfo.processInfo.systemUptime+ self.logStopInput(requestedAt: toggleStopRequestedAt, route: "deferred_release")let token = self.beginPendingReleaseStop(for: type)DebugLogger.shared.debug("\(label) release stop deferred until recording starts", source: "GlobalHotkeyManager")@@ -1777,7 +1820,7 @@ final class GlobalHotkeyManager: NSObject {DebugLogger.shared.info("\(label) deferred stop after recording start", source: "GlobalHotkeyManager")self.clearPendingReleaseStop(for: type, token: token)- await self.stopRecordingInternal()+ await self.stopRecordingInternal(toggleStopRequestedAt: toggleStopRequestedAt)return}@@ -1875,6 +1918,8 @@ final class GlobalHotkeyManager: NSObject {}func resetModifierOnlyShortcutTracking(reason: ModifierTrackingResetReason = .shortcutCapture) {+ self.modifierPressReceivedAt = nil+ self.currentStopPressReceivedAt = nillet shouldStopActiveHold = self.hotkeyMode != .toggle&& self.asrService.isRunning&& (self.isKeyPressed || self.isPromptModeKeyPressed || self.isCommandModeKeyPressed || self.isRewriteKeyPressed || self.isPromptAssignmentKeyPressed)@@ -2077,12 +2122,17 @@ final class GlobalHotkeyManager: NSObject {case .ignore:return falsecase .start:+ self.modifierPressReceivedAt = self.currentInputTiming?.receivedAtself.modifierOnlyKeyDown = trueself.modifierPressStartTime = Date()self.scheduleModifierOnlyStart(for: behavior)return truecase let .finish(wasCleanPress):+ let previousPress = self.currentStopPressReceivedAt+ self.currentStopPressReceivedAt = self.modifierPressReceivedAt+ self.modifierPressReceivedAt = nil+ defer { self.currentStopPressReceivedAt = previousPress }self.modifierOnlyKeyDown = falseself.modifierPressStartTime = nil@@ -2268,6 +2318,9 @@ final class GlobalHotkeyManager: NSObject {private func toggleRecording() {let toggleStopRequestedAt = ProcessInfo.processInfo.systemUptime+ if self.asrService.isRunningOrStarting {+ self.logStopInput(requestedAt: toggleStopRequestedAt, route: "toggle")+ }Task { @MainActor [weak self] inguard let self = self else { return }@@ -2305,11 +2358,27 @@ final class GlobalHotkeyManager: NSObject {}}+ private func logStopInput(requestedAt: TimeInterval, route: String) {+ var fields = "stop_request stopRequestedAt=\(requestedAt) route=\(route)"+ if let input = self.currentInputTiming {+ fields += " inputReceivedAt=\(input.receivedAt) eventType=\(input.eventType)"+ if let age = input.deliveryAgeMs {+ fields += " inputAgeMs=\(age)"+ }+ if let press = self.currentStopPressReceivedAt, press <= input.receivedAt {+ fields += " pressReceivedAt=\(press)"+ }+ }+ DebugLogger.shared.benchmark("HOTKEY_BENCH", message: fields, source: "HotkeyBenchmark")+ }+private func stopRecordingAfterToggle() {- self.stopRecordingIfNeeded(toggleStopRequestedAt: ProcessInfo.processInfo.systemUptime)+ self.stopRecordingIfNeeded()}private func stopRecordingIfNeeded(toggleStopRequestedAt: TimeInterval? = nil) {+ let toggleStopRequestedAt = toggleStopRequestedAt ?? ProcessInfo.processInfo.systemUptime+ self.logStopInput(requestedAt: toggleStopRequestedAt, route: "stop_if_needed")Task { @MainActor [weak self] inguard let self = self else { return }diff --git a/Sources/Fluid/Services/PasteDeliveryCoordinator.swift b/Sources/Fluid/Services/PasteDeliveryCoordinator.swiftindex 15ca8918..9142d618 100644--- a/Sources/Fluid/Services/PasteDeliveryCoordinator.swift+++ b/Sources/Fluid/Services/PasteDeliveryCoordinator.swift@@ -552,7 +552,9 @@ final class PasteDeliveryCoordinator {preserveTranscriptOnClipboard: Bool,onCommandPosted: ((TimeInterval) -> Void)? = nil) async -> TextDeliveryResult {+ let slotRequestedAt = ProcessInfo.processInfo.systemUptimeawait self.acquireDeliverySlot()+ let slotAcquiredAt = ProcessInfo.processInfo.systemUptimevar settlementOwnsSlot = falsedefer {if !settlementOwnsSlot { self.releaseDeliverySlot() }@@ -561,6 +563,7 @@ final class PasteDeliveryCoordinator {let startedAt = ProcessInfo.processInfo.systemUptimeself.generation &+= 1let generation = self.generation+ self.log("clipboard_slot_acquired generation=\(generation) waitMs=\((slotAcquiredAt - slotRequestedAt) * 1000)")let originalSnapshot = self.pasteboard.captureSnapshot()guard let originalSnapshot else {@@ -634,9 +637,11 @@ final class PasteDeliveryCoordinator {private func scheduleSettlement(sessionID: String, generation: UInt64) {let settlementDelayNanoseconds = self.settlementDelayNanoseconds+ let scheduledAt = ProcessInfo.processInfo.systemUptimelet task = Task { @MainActor [weak self] intry? await Task.sleep(nanoseconds: settlementDelayNanoseconds)guard !Task.isCancelled else { return }+ self?.log("settlement_begin generation=\(generation) elapsedMs=\((ProcessInfo.processInfo.systemUptime - scheduledAt) * 1000) scheduledDelayMs=\(settlementDelayNanoseconds / 1_000_000)")self?.settleIfCurrent(sessionID: sessionID, generation: generation)}self.lease?.settlementTask = task@@ -659,12 +664,13 @@ final class PasteDeliveryCoordinator {return}+ let restoreStartedAt = ProcessInfo.processInfo.systemUptimeif lease.shouldKeepTranscript {let didWrite = self.pasteboard.writeIntentionalText(lease.text)- self.log("intentional_copy_settled generation=\(generation) success=\(didWrite)")+ self.log("intentional_copy_settled generation=\(generation) success=\(didWrite) elapsedMs=\((ProcessInfo.processInfo.systemUptime - restoreStartedAt) * 1000)")} else {let didRestore = self.pasteboard.restoreTemporarySnapshot(lease.originalSnapshot, sessionID: sessionID, expectedText: lease.text)- self.log("restore_completed generation=\(generation) success=\(didRestore)")+ self.log("restore_completed generation=\(generation) success=\(didRestore) elapsedMs=\((ProcessInfo.processInfo.systemUptime - restoreStartedAt) * 1000)")}}diff --git a/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift b/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swiftindex 42283787..090d3276 100644--- a/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift+++ b/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift@@ -6,6 +6,25 @@ import Foundationimport XCTestfinal class HotkeyShortcutTests: XCTestCase {+ func testInputDeliveryTimingKeepsClocksSeparate() {+ let input = HotkeyInputTiming(+ receivedAt: 100, eventTimestamp: 5_000_000_000, eventType: 12, receivedTimestamp: 5_050_000_000+ )+ XCTAssertEqual(input.deliveryAgeMs, 50)+ XCTAssertEqual(input.receivedAt, 100)+ XCTAssertEqual(input.eventTimestamp, 5_000_000_000)+ XCTAssertEqual(input.eventType, 12)+ }++ func testInputDeliveryTimingRejectsMissingAndFutureEventTimestamps() {+ let missing = HotkeyInputTiming(receivedAt: 100, eventTimestamp: 0, eventType: 12, receivedTimestamp: 5_000_000_000)+ XCTAssertNil(missing.deliveryAgeMs)+ let future = HotkeyInputTiming(receivedAt: 100, eventTimestamp: 6_000_000_000, eventType: 12, receivedTimestamp: 5_000_000_000)+ XCTAssertNil(future.deliveryAgeMs)+ let immediate = HotkeyInputTiming(receivedAt: 100, eventTimestamp: 5_000_000_000, eventType: 12, receivedTimestamp: 5_000_000_000)+ XCTAssertEqual(immediate.deliveryAgeMs, 0)+ }+private let legacyHotkeyShortcutKey = "HotkeyShortcutKey"private let primaryDictationShortcutsKey = "PrimaryDictationShortcuts"private let pasteLastTranscriptionShortcutKey = "PasteLastTranscriptionHotkeyShortcut"diff --git a/scripts/dictation_log_summary.py b/scripts/dictation_log_summary.pyindex ae3ee2ae..a5ac552d 100644--- a/scripts/dictation_log_summary.py+++ b/scripts/dictation_log_summary.py@@ -1,7 +1,8 @@#!/usr/bin/env python3"""Read-only, standard-library summary of recent FluidVoice dictation timings.-Usage: python3 scripts/dictation_log_summary.py --last 5 [--details] [--json]+Usage: python3 scripts/dictation_log_summary.py --last 5 [--stages]+Use --markdown for Markdown export, --details for marker details, --json for data.Reads Fluid.log.1 then Fluid.log. Explicit paths are accepted with --log PATH.No recording, playback, app activation, or file writes are performed."""@@ -11,11 +12,13 @@ import jsonimport mathimport reimport statistics+import shutil+import textwrapfrom pathlib import PathMARKER = re.compile(- r"\b(APP_BENCH|ASR_BENCH|FI_SERVICE_BENCH|FI_BRIDGE_BENCH|LLM_BENCH|OVERLAY_BENCH|TYPING_BENCH|HISTORY_BENCH|PIPELINE_SUMMARY|DICTATION_SUMMARY)\b(.*)"+ r"\b(HOTKEY_BENCH|APP_BENCH|ASR_BENCH|FI_SERVICE_BENCH|FI_BRIDGE_BENCH|LLM_BENCH|OVERLAY_BENCH|TYPING_BENCH|HISTORY_BENCH|PIPELINE_SUMMARY|DICTATION_SUMMARY)\b(.*)")FIELD = re.compile(r"(?:^|\s)(\w+)=([^\s]+)")WALL = re.compile(r"^\[([\d:.]+)\]")@@ -30,8 +33,38 @@ def parse_logs(lines):App restarts reset correlation even when IDs/session numbers are reused."""runs, by_id, current, seen = [], {}, None, set()+ session_runs, stop_requests = [], []++ def stop_key(value):+ try:+ value = float(value)+ return value if math.isfinite(value) and value >= 0 else None+ except (TypeError, ValueError):+ return None++ def attach_stop_requests():+ # Hotkey events precede pipeline IDs. Only exact, unique stop-request+ # timestamps within this process session establish identity.+ targets, requests = {}, {}+ for run in session_runs:+ for event in run["events"]:+ if event["family"] == "APP_BENCH" and event["name"] == "pipeline_begin":+ key = stop_key(event["fields"].get("toggleStopRequestedAt"))+ if key is not None:+ targets.setdefault(key, []).append(run)+ for event in stop_requests:+ key = stop_key(event["fields"].get("stopRequestedAt"))+ if key is not None:+ requests.setdefault(key, []).append(event)+ for key, candidates in requests.items():+ matches = targets.get(key, [])+ if len(candidates) == 1 and len(matches) == 1:+ matches[0]["events"].append(candidates[0])+for line in lines:if line.startswith("[RUN]"):+ attach_stop_requests()+ session_runs, stop_requests = [], []current, by_id = None, {}seen.clear()continue@@ -61,16 +94,22 @@ def parse_logs(lines):event = {"family": family, "name": name, "t": timestamp,"pipeline_id": correlation,"fields": {k: v for k, v in fields.items() if k != "t"}}+ if family == "HOTKEY_BENCH":+ if name == "stop_request":+ stop_requests.append(event)+ continueif family == "APP_BENCH" and name == "begin_recording":wall = WALL.match(line)current = {"id": None, "time": wall.group(1) if wall else "?","events": [], "cancelled": False, "partial_start": False}runs.append(current)+ session_runs.append(current)if family == "APP_BENCH" and name == "pipeline_begin":if current is None or current["id"] is not None:current = {"id": None, "time": WALL.match(line).group(1) if WALL.match(line) else "?","events": [], "cancelled": False, "partial_start": True}runs.append(current)+ session_runs.append(current)current["id"] = fields.get("id")current["correlated"] = correlation is not Noneif current["id"]:@@ -98,6 +137,7 @@ def parse_logs(lines):target = by_id.get(fields["id"])if target is not None:target["events"].append(event)+ attach_stop_requests()return runs@@ -143,6 +183,7 @@ def summarize(run):"asr_stop_call": time(find("APP_BENCH", {"asr_stop_call"}, after)),"capture_stop_begin": time(find("ASR_BENCH", {"capture_stop_await_begin"}, after)),"capture_stop_return": time(find("ASR_BENCH", {"capture_stop_await_return"}, after)),+ "streaming_drain_end": time(find("ASR_BENCH", {"streaming_timer_stop end", "stop_streaming_wait"}, after)),"final_queue_ready": time(find("ASR_BENCH", {"final_queue_previous_finished"}, after)),"final_executor_begin": time(find("ASR_BENCH", {"final_executor_begin"}, after)),"final_executor_end": time(find("ASR_BENCH", {"final_executor_end"}, after)),@@ -206,6 +247,51 @@ def summarize(run):ai_call = find("APP_BENCH", {"ai_process_call"}, after)summary = find("PIPELINE_SUMMARY", {"summary"}, after)ready_summary = find_untimed("DICTATION_SUMMARY", {"summary"}, stop_event_index)+ typing_request = find_untimed("TYPING_BENCH", {"request"}, stop_event_index)+ clipboard_snapshot = find_untimed("TYPING_BENCH", {"clipboard_snapshot_complete"}, stop_event_index)+ clipboard_write = find_untimed("TYPING_BENCH", {"clipboard_write"}, stop_event_index)+ command_posted = find_untimed("TYPING_BENCH", {"command_posted"}, stop_event_index)+ delivery_failed = find_untimed("TYPING_BENCH", {"delivery_failed"}, stop_event_index)+ first_slot = find_untimed("TYPING_BENCH", {"clipboard_slot_acquired"}, stop_event_index)+ generation_source = command_posted or delivery_failed or first_slot+ command_generation = generation_source["fields"].get("generation") if generation_source else None+ focus_check = find_untimed("APP_BENCH", {"focus_target_check"}, stop_event_index)+ pipeline_begin = find("APP_BENCH", {"pipeline_begin"})+ toggle_requested_at = numeric_field(pipeline_begin, "toggleStopRequestedAt")++ def settlement_event(name, reason=None):+ # Multiple insertions can share a pipeline. Only pair the selected command+ # with its own generation, including callbacks after another recording starts.+ if command_generation is None:+ return None+ return next((event for event in events[stop_event_index:]+ if event["family"] == "TYPING_BENCH" and event["name"] == name+ and event["fields"].get("generation") == command_generation+ and (reason is None or event["fields"].get("reason") == reason)), None)++ clipboard_restore = settlement_event("restore_completed")+ clipboard_changed = settlement_event("settlement_skipped", "clipboard_changed")+ intentional_copy = settlement_event("intentional_copy_settled")+ clipboard_slot = settlement_event("clipboard_slot_acquired")+ settlement_begin = settlement_event("settlement_begin")+ phases.update({+ "clipboard_snapshot_complete": time(clipboard_snapshot),+ "clipboard_write": time(clipboard_write),+ "command_posted": time(command_posted),+ "clipboard_restore": time(clipboard_restore),+ "clipboard_change_skipped": time(clipboard_changed),+ "clipboard_slot_acquired": time(clipboard_slot),+ "clipboard_settlement_begin": time(settlement_begin),+ })+ clipboard_status = None+ if clipboard_restore:+ clipboard_status = {"true": "restored", "false": "restore_failed"}.get(+ clipboard_restore["fields"].get("success"))+ elif clipboard_changed:+ clipboard_status = "skipped_clipboard_changed"+ elif intentional_copy:+ clipboard_status = {"true": "transcript_kept", "false": "intentional_copy_failed"}.get(+ intentional_copy["fields"].get("success"))if run["cancelled"]:outcome = "cancelled"elif summary:@@ -247,6 +333,7 @@ def summarize(run):"overlay_after_paste_ms": tail,"callback_queue_ms": delta(phases["delivery_callback"], phases["paste_done"]),"capture_stop_ms": delta(phases["capture_stop_return"], phases["capture_stop_begin"]),+ "asr_stop_total_ms": delta(phases["asr_return"], phases["asr_stop_call"]),"final_executor_hop_ms": delta(phases["final_executor_begin"], phases["final_queue_ready"]),"final_executor_ms": delta(phases["final_executor_end"], phases["final_executor_begin"]),"asr_provider_ms": provider_final_ms,@@ -299,6 +386,22 @@ def summarize(run):"ai_to_ready_ms": delta(phases["text_ready"], phases["ai_return"]),"internal_stop_to_ready_ms": delta(phases["text_ready"], stop),"typing_queue_ms": delta(phases["typing_worker"], phases["typing_request"]),+ "ready_to_request_ms": delta(phases["typing_request"], phases["text_ready"]),+ "request_to_command_ms": delta(phases["command_posted"], phases["typing_request"]),+ "clipboard_snapshot_ms": numeric_field(clipboard_snapshot, "elapsedMs"),+ "clipboard_write_ms": numeric_field(clipboard_write, "elapsedMs"),+ "clipboard_command_total_ms": numeric_field(command_posted, "totalMs"),+ "command_to_restore_ms": delta(phases["clipboard_restore"], phases["command_posted"]),+ "command_to_clipboard_change_skip_ms": delta(phases["clipboard_change_skipped"], phases["command_posted"]),+ "toggle_callback_to_handler_ms": delta(time(pipeline_begin), toggle_requested_at),+ "focus_check_ms": numeric_field(focus_check, "totalMs"),+ "focus_pid_ms": numeric_field(focus_check, "pidMs"),+ "focus_element_ms": numeric_field(focus_check, "elementMs"),+ "clipboard_slot_wait_ms": numeric_field(clipboard_slot, "waitMs"),+ "clipboard_settlement_wait_ms": numeric_field(settlement_begin, "elapsedMs"),+ "clipboard_settlement_scheduled_ms": numeric_field(settlement_begin, "scheduledDelayMs"),+ "clipboard_restore_work_ms": numeric_field(clipboard_restore, "elapsedMs"),+ "clipboard_intentional_copy_work_ms": numeric_field(intentional_copy, "elapsedMs"),"ready_to_injection_ms": delta(phases["injection_return"], phases["text_ready"]),"ready_to_delivery_ms": delta(phases["delivery_callback"], phases["text_ready"]),"stop_to_delivery_ms": numeric_field(summary, "totalMs"),@@ -308,6 +411,12 @@ def summarize(run):"summary_ready_ms": numeric_field(ready_summary, "readyMs"),}context = {+ "insertion_mode": typing_request["fields"].get("mode") if typing_request else None,+ "clipboard_command_status": "command_posted" if command_posted else (+ delivery_failed["fields"].get("reason") if delivery_failed else None),+ "clipboard_settlement_status": clipboard_status,+ "clipboard_generation": command_generation,+ "focus_missing_context": focus_check["fields"].get("missingContext") if focus_check else None,"route": next((e["fields"].get("route") for e in eventsif e["family"] == "APP_BENCH" and e["name"] == "pipeline_begin"), None),"llm_attempt_count": sum(e["family"] == "LLM_BENCH" and e["name"] == "attempt_start" for e in events),@@ -325,6 +434,12 @@ def summarize(run):"correlation": "request_id" if run.get("correlated") else "legacy_proximity_uncertain","correctness": "not_checked_requires_expected_and_delivered_text","partial_start": run["partial_start"], "stop_uptime": stop,+ "stop_callback_uptime": toggle_requested_at,+ "phase_uptime": phases,+ "clipboard_uptime": {key: phases[key] for key in (+ "clipboard_snapshot_complete", "clipboard_write", "command_posted",+ "clipboard_restore", "clipboard_change_skipped", "clipboard_slot_acquired",+ "clipboard_settlement_begin")},"from_stop_ms": {key: delta(value, stop) for key, value in phases.items()},"metrics": metrics, "context": context, "events": events}@@ -363,6 +478,37 @@ def render(rows, details=False):"(negative = hidden first)."]lines += ["", "Cleanup is the last logged overlay-cleanup marker, not proof all background work has finished.","Unlabelled events are bounded by recording starts; rapid-overlap tails cannot be reliably attributed."]+ lines += ["", "## Clipboard delivery", "",+ "Durations in ms. Mode is the logged setting; command posted is dispatch, not visible insertion. "+ "Coordinator total starts after acquiring its slot; no queue time is inferred. "+ "For multiple clipboard commands, this table describes the first command and its matching settlement. "+ "— = unknown / not logged.", "",+ "| Time / ID | Mode | Ready→request | Request→command | Snapshot | Write | Coordinator total | Command→restore | Command→changed skip | Command status | Clipboard status |",+ "|---|---|---:|---:|---:|---:|---:|---:|---:|---|---|"]+ for row in rows:+ m, context = row["metrics"], row["context"]+ values = [m["ready_to_request_ms"], m["request_to_command_ms"],+ m["clipboard_snapshot_ms"], m["clipboard_write_ms"], m["clipboard_command_total_ms"],+ m["command_to_restore_ms"], m["command_to_clipboard_change_skip_ms"]]+ mode = (context["insertion_mode"] or "unknown").replace("|", "\\|")+ lines.append(f"| {row['time']} / {(row['id'] or '?')[:8]} | {mode} | "+ + " | ".join(map(fmt, values))+ + f" | {context['clipboard_command_status'] or 'unknown'} | "+ + f"{context['clipboard_settlement_status'] or 'unknown'} |")+ lines += ["", "## Measured focus and clipboard waits", "",+ "Times in ms. Toggle callback→handler starts at the app callback, not physical key-down. "+ "PID and element checks are parts of focus total; scheduled delay is part of actual timer wait. "+ "Timer wait and restoration work are separate from dispatch. Do not add nested columns or "+ "infer an unlogged wait from the remaining elapsed time.", "",+ "| Time / ID | Toggle callback→handler | Focus total | PID check | Element check | Clipboard queue | Timer scheduled | Timer actual | Restore work | Keep-transcript work |",+ "|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|"]+ for row in rows:+ m = row["metrics"]+ values = [m["toggle_callback_to_handler_ms"], m["focus_check_ms"], m["focus_pid_ms"],+ m["focus_element_ms"], m["clipboard_slot_wait_ms"],+ m["clipboard_settlement_scheduled_ms"], m["clipboard_settlement_wait_ms"],+ m["clipboard_restore_work_ms"], m["clipboard_intentional_copy_work_ms"]]+ lines.append(f"| {row['time']} / {(row['id'] or '?')[:8]} | " + " | ".join(map(fmt, values)) + " |")lines += ["", "## Internal model handoffs", "","These exclude focus restoration, paste injection, and overlay dismissal.", "","| Time / ID | Capture stop | ASR hop | ASR provider | ASR→AI | Refining→AI | AI process | AI→ready | Stop→ready |",@@ -436,12 +582,479 @@ def render(rows, details=False):return "\n".join(lines)+STAGES = [+ ("Recording start → first PCM (separate)", "metrics", "start_to_pcm_ms"),+ ("Toggle callback → stop handler", "metrics", "toggle_callback_to_handler_ms"),+ ("Stop handler → command dispatch", "from_stop_ms", "command_posted"),+ ("ASR stop call total", "metrics", "asr_stop_total_ms"),+ ("ASR provider (within ASR)", "metrics", "asr_provider_ms"),+ ("AI processing", "metrics", "ai_processing_ms"),+ ("Ready → insertion request", "metrics", "ready_to_request_ms"),+ ("Focus check total", "metrics", "focus_check_ms"),+ ("PID check (within focus)", "metrics", "focus_pid_ms"),+ ("Element check (within focus)", "metrics", "focus_element_ms"),+ ("Request → command dispatch", "metrics", "request_to_command_ms"),+ ("Clipboard slot wait", "metrics", "clipboard_slot_wait_ms"),+ ("Clipboard snapshot", "metrics", "clipboard_snapshot_ms"),+ ("Clipboard write", "metrics", "clipboard_write_ms"),+ ("Coordinator after slot acquired", "metrics", "clipboard_command_total_ms"),+ ("Overlay hide API duration", "metrics", "hide_duration_ms"),+ ("Restore timer scheduled (within actual wait)", "metrics", "clipboard_settlement_scheduled_ms"),+ ("Restore timer actual wait", "metrics", "clipboard_settlement_wait_ms"),+ ("Restore work", "metrics", "clipboard_restore_work_ms"),+ ("Keep-transcript work", "metrics", "clipboard_intentional_copy_work_ms"),+]+++def render_stages(rows):+ """One measured-stage overview; nested intervals are never added together."""+ def fmt(value):+ return "—" if value is None else f"{value:.1f}"++ lines = ["# Dictation stages", "",+ "Times in ms; — = not logged / unknown. Nested stages overlap and are not additive. "+ "Recording-start timing is separate from stop latency. Dispatch and overlay API completion "+ "do not prove visible insertion or rendered pixels.", "",+ "| Stage | " + " | ".join(f"{r['time']} / {(r['id'] or '?')[:8]}" for r in rows) + " |",+ "|---|" + "---:|" * len(rows)]+ lines.append("| Insertion mode | " + " | ".join(+ (r["context"]["insertion_mode"] or "—").replace("|", "\\|") for r in rows) + " |")+ for label, source, key in STAGES:+ lines.append(f"| {label} | " + " | ".join(fmt(r[source][key]) for r in rows) + " |")+ return "\n".join(lines)+++def render_terminal_stages(rows, width=None, stages=None, title="DICTATION TIMINGS", notes=None, precision=1):+ """Bounded-width tables for plain terminals, with no external packages."""+ width = max(40, width or shutil.get_terminal_size(fallback=(100, 24)).columns)+ label_width = min(40, width - 19)+ value_width = 12+ per_table = max(1, (width - label_width - 4) // (value_width + 3))+ lines = textwrap.wrap(title, width) + textwrap.wrap(+ "All durations in milliseconds (ms). — = not measured.", width) + [""]+ for index, row in enumerate(rows, 1):+ mode = row["context"]["insertion_mode"] or "unknown mode"+ lines.extend(textwrap.wrap(+ f"#{index} {row['time']} {(row['id'] or '?')[:8]} {mode}", width))+ for offset in range(0, len(rows), per_table):+ batch = rows[offset:offset + per_table]+ widths = [label_width] + [value_width] * len(batch)++ def border(left, middle, right):+ return left + middle.join("─" * (w + 2) for w in widths) + right++ def cells(values):+ wrapped = [textwrap.wrap(str(value), w) or [""]+ for value, w in zip(values, widths)]+ result = []+ for n in range(max(map(len, wrapped))):+ parts = []+ for col, (segments, w) in enumerate(zip(wrapped, widths)):+ value = segments[n] if n < len(segments) else ""+ parts.append(" " + (value.ljust(w) if col == 0 else value.rjust(w)) + " ")+ result.append("│" + "│".join(parts) + "│")+ return result++ lines += ["", border("┌", "┬", "┐")]+ lines += cells(["Stage (ms)"] + [f"#{offset + i + 1}" for i in range(len(batch))])+ lines.append(border("├", "┼", "┤"))+ for label, source, key in (STAGES if stages is None else stages):+ values = ["—" if r[source][key] is None else f"{r[source][key]:.{precision}f}" for r in batch]+ lines += cells([label] + values)+ lines.append(border("└", "┴", "┘"))+ for note in (notes if notes is not None else (+ "Nested stages overlap and are not additive. Recording-start timing is separate from stop latency.",+ "Dispatch measures sending the paste command, not when text becomes visible. Overlay timing measures the API call.",+ )):+ lines += [""] + textwrap.wrap(note, width)+ return "\n".join(lines)+++def attach_field_receipts(rows, lines):+ """Join a local test by target PID, stop window and full pasted character count.++ Ambiguous, timed-out, mismatched or incomplete tests never become successes.+ Receipt times use the same macOS systemUptime clock as the app, not log write time.+ """+ tests = {}+ for line in lines:+ try:+ event = json.loads(line)+ if not isinstance(event, dict):+ continue+ t = event.get("t")+ if isinstance(t, bool) or not isinstance(t, (int, float)) or not math.isfinite(t) or t < 0:+ continue+ tests.setdefault(event["run_id"], []).append(event)+ except (ValueError, KeyError, TypeError):+ continue # includes an incomplete final line during an active capture+ candidates = {}+ for run_id, events in tests.items():+ stops = [e for e in events if e.get("event") == "stop_pressed"]+ received = [e for e in events if e.get("event") == "field_received"]+ if len(stops) != 1 or len(received) != 1:+ continue+ if any(e.get("event") in ("timeout", "field_mismatch") for e in events):+ continue+ stop, receipt = stops[0], received[0]+ if not 0 <= receipt["t"] - stop["t"] <= 30:+ continue+ target_pid = stop.get("target_pid")+ if not isinstance(target_pid, int) or receipt.get("target_pid") != target_pid:+ continue+ matches = []+ for row in rows:+ callback = row["stop_callback_uptime"]+ request = next((e for e in row["events"] if e["family"] == "TYPING_BENCH"+ and e["name"] == "request"), None)+ if callback is None or not stop["t"] <= callback <= receipt["t"] or request is None:+ continue+ fields = request["fields"]+ if (row["correlation"] != "request_id" or row["outcome"] == "cancelled"+ or row["context"]["clipboard_command_status"] != "command_posted"+ or fields.get("preferredPID") != str(target_pid)+ or fields.get("chars") != str(receipt.get("chars"))):+ continue+ if request["t"] is None or not callback <= request["t"] <= receipt["t"]:+ continue+ matches.append(row)+ if len(matches) != 1:+ continue+ drawn = [e for e in events if e.get("event") == "field_drawn"+ and e.get("target_pid") == target_pid and e["t"] >= receipt["t"]]+ candidates.setdefault(matches[0]["id"], []).append({+ "run_id": run_id, "stop": stop["t"], "received": receipt["t"],+ "drawn": min((e["t"] for e in drawn), default=None),+ })+ for row in rows:+ matches = candidates.get(row["id"], [])+ if len(matches) == 1:+ row["field_receipt"] = matches[0]+++LATENCY_STAGES = [+ ("TOTAL: Stop → text in field", "latency", "total_ms"),+ ("Stop button → app receives stop", "latency", "input_ms"),+ ("App receives stop → ASR starts", "latency", "before_asr_ms"),+ ("Finish transcription", "latency", "asr_ms"),+ ("Transcription → AI starts", "latency", "before_ai_ms"),+ ("AI processing", "latency", "ai_ms"),+ ("AI ends → final text ready", "latency", "after_ai_ms"),+ ("Prepare target / request insertion", "latency", "prepare_ms"),+ ("Insertion request → paste sent", "latency", "insertion_ms"),+ ("Paste sent → text in field", "latency", "receiver_ms"),+ ("Other / unlogged stage time", "latency", "unattributed_ms"),+ ("SUBTOTAL: App stop → paste sent", "latency", "sent_ms"),+]+++def add_latency_breakdown(rows):+ def duration(start, end):+ if start is None or end is None or not all(math.isfinite(t) for t in (start, end)) or end < start:+ return None+ return (end - start) * 1000++ for row in rows:+ p = row["phase_uptime"]+ receipt = row.get("field_receipt", {})+ # Older logs have only a stop handler marker. Do not call that a button press.+ app_stop = row["stop_callback_uptime"]+ if app_stop is None:+ app_stop = row["stop_uptime"]+ origin = receipt.get("stop", app_stop)+ ai_end = p["ai_return"] if p["ai_return"] is not None else p["ai_failure"]+ intervals = [+ ("input_ms", receipt.get("stop"), app_stop),+ ("before_asr_ms", app_stop, p["asr_stop_call"]),+ ("asr_ms", p["asr_stop_call"], p["asr_return"]),+ ("before_ai_ms", p["asr_return"], p["ai_call"]),+ ("ai_ms", p["ai_call"], ai_end),+ ("after_ai_ms", ai_end, p["text_ready"]),+ ("prepare_ms", p["text_ready"], p["typing_request"]),+ ("insertion_ms", p["typing_request"], p["command_posted"]),+ ("receiver_ms", p["command_posted"], receipt.get("received")),+ ]+ end = receipt.get("received", p["command_posted"])+ m = {}+ previous_end = origin+ for key, start, finish in intervals:+ value = duration(start, finish)+ # Do not add overlapping or out-of-envelope markers into the critical path.+ if (value is not None and origin is not None and end is not None+ and origin <= start <= finish <= end+ and (previous_end is None or start >= previous_end)):+ m[key] = value+ previous_end = finish+ else:+ m[key] = None+ envelope = duration(origin, end)+ m["unattributed_ms"] = max(0, envelope - sum(v for v in m.values() if v is not None)) if envelope is not None else None+ m["total_ms"] = duration(receipt.get("stop"), receipt.get("received"))+ m["sent_ms"] = duration(app_stop, p["command_posted"])+ row["latency"] = {key: round(value, 1) if value is not None else None for key, value in m.items()}+++def render_terminal_latency(rows, width=None):+ add_latency_breakdown(rows)+ measured = sum(row["latency"]["total_ms"] is not None for row in rows)+ notes = [+ f"Verified local test-field receipts: {measured}/{len(rows)}. TOTAL is unknown without a receiving-field measurement.",+ "The individual stages partition the stop-to-field interval. Do not add TOTAL or SUBTOTAL again. "+ "Other/unlogged time includes gaps where stage markers are missing.",+ "The test verifies the full text is in the field. This is target-app receipt, not a physical display/pixel timestamp. "+ "The test button also includes the synthetic shortcut handoff to FluidVoice.",+ "Microphone startup, overlay cleanup and clipboard restoration are in --stages. "+ "They are not added to the stop-to-field total.",+ ]+ return render_terminal_stages(rows, width, LATENCY_STAGES, "STOP → TEXT IN FIELD", notes)+++DELIVERY_STAGES = [+ ("TOTAL: Text ready → paste sent", "delivery", "total_ms"),+ ("Prepare / restore target focus", "delivery", "prepare_ms"),+ ("Wait / enter clipboard slot", "delivery", "queue_ms"),+ ("Save previous clipboard", "delivery", "snapshot_ms"),+ ("Write dictated text to clipboard", "delivery", "write_ms"),+ ("Resolve paste key / send command", "delivery", "dispatch_ms"),+ ("Other / missing stage markers", "delivery", "unattributed_ms"),+]+++def add_delivery_breakdown(rows):+ for row in rows:+ p = row["phase_uptime"]+ start, end = p["text_ready"], p["command_posted"]+ intervals = [+ ("prepare_ms", start, p["typing_request"]),+ ("queue_ms", p["typing_request"], p["clipboard_slot_acquired"]),+ ("snapshot_ms", p["clipboard_slot_acquired"], p["clipboard_snapshot_complete"]),+ ("write_ms", p["clipboard_snapshot_complete"], p["clipboard_write"]),+ ("dispatch_ms", p["clipboard_write"], end),+ ]+ complete = (start is not None and end is not None and+ math.isfinite(start) and math.isfinite(end) and end >= start)+ total = (end - start) * 1000 if complete else None+ m, previous = {}, start+ for key, begin, finish in intervals:+ if (complete and begin is not None and finish is not None+ and start <= begin <= finish <= end and begin >= previous):+ m[key] = (finish - begin) * 1000+ previous = finish+ else:+ m[key] = None+ m["unattributed_ms"] = max(0, total - sum(v for v in m.values() if v is not None)) if complete else None+ m["total_ms"] = total+ row["delivery"] = {key: round(value, 2) if value is not None else None for key, value in m.items()}+++def render_terminal_delivery(rows, width=None):+ add_delivery_breakdown(rows)+ return render_terminal_stages(rows, width, DELIVERY_STAGES, "TEXT READY → PASTE COMMAND SENT", [+ "Starts after ASR/AI finish. Ends when FluidVoice sends the paste command.",+ "The stages partition that interval, including their handoffs. TOTAL is their summary, not another stage.",+ "Receiving-app rendering and later clipboard restoration are excluded. — = missing measurement.",+ ], precision=2)+++PIPELINE_STAGES = [+ ("TOTAL: Stop → text dispatch", "pipeline", "total_ms"),+ ("Stop request → handler begins", "pipeline", "stop_queue_ms"),+ ("Stop preparation / UI → ASR call", "pipeline", "stop_preparation_ms"),+ ("ASR work (unsplit older logs)", "pipeline", "asr_ms"),+ ("Enter ASR / begin stopping audio", "pipeline", "asr_setup_ms"),+ ("Stop audio capture", "pipeline", "capture_stop_ms"),+ ("Wait for active transcription chunk", "pipeline", "streaming_drain_ms"),+ ("Prepare final audio / ASR queue", "pipeline", "final_queue_ms"),+ ("Final transcription", "pipeline", "final_asr_ms"),+ ("Finalize ASR result / return", "pipeline", "asr_return_ms"),+ ("Transcription → AI handoff", "pipeline", "before_ai_ms"),+ ("AI processing (full call)", "pipeline", "ai_ms"),+ ("Finalize text after AI", "pipeline", "after_ai_ms"),+ ("Prepare / restore target focus", "pipeline", "prepare_ms"),+ ("Wait / enter clipboard slot", "pipeline", "queue_ms"),+ ("Save previous clipboard", "pipeline", "snapshot_ms"),+ ("Write dictated text to clipboard", "pipeline", "write_ms"),+ ("Resolve paste key / send command", "pipeline", "dispatch_ms"),+ ("Remaining output steps / waits", "pipeline", "remaining_output_ms"),+ ("Other / missing stage markers", "pipeline", "unattributed_ms"),+]+++def add_pipeline_breakdown(rows):+ """Partition the entire recorded stop-request to final dispatch interval."""+ for row in rows:+ p = row["phase_uptime"]+ start = row["stop_callback_uptime"]+ row["pipeline_start_basis"] = "stop_request"+ if start is None:+ start = row["stop_uptime"]+ row["pipeline_start_basis"] = "handler_only"+ commands = [e["t"] for e in row["events"] if e["family"] == "TYPING_BENCH"+ and e["name"] == "command_posted" and e["t"] is not None]+ end = max(commands) if commands else p["injection_return"]+ # Direct typing may only expose its final dispatch callback.+ if end is None:+ callback = next((e for e in row["events"] if e["family"] == "TYPING_BENCH"+ and e["name"] == "asr_type_dispatched"+ and e["fields"].get("result") == "commandPosted"), None)+ end = callback["t"] if callback else None+ if row["outcome"] == "cancelled" or any(+ e["family"] == "TYPING_BENCH" and (+ e["name"] == "delivery_failed" or+ e["fields"].get("result", "").startswith("recoverableFailure"))+ for e in row["events"]+ ):+ end = None+ ai_end = p["ai_return"] if p["ai_return"] is not None else p["ai_failure"]+ intervals = [+ ("stop_queue_ms", row["stop_callback_uptime"], row["stop_uptime"]),+ ("stop_preparation_ms", row["stop_uptime"], p["asr_stop_call"]),+ ("asr_ms", p["asr_stop_call"], p["asr_return"]),+ ("before_ai_ms", p["asr_return"], p["ai_call"]),+ ("ai_ms", p["ai_call"], ai_end),+ ("after_ai_ms", ai_end, p["text_ready"]),+ ("prepare_ms", p["text_ready"], p["typing_request"]),+ ("queue_ms", p["typing_request"], p["clipboard_slot_acquired"]),+ ("snapshot_ms", p["clipboard_slot_acquired"], p["clipboard_snapshot_complete"]),+ ("write_ms", p["clipboard_snapshot_complete"], p["clipboard_write"]),+ ("dispatch_ms", p["clipboard_write"], p["command_posted"]),+ ("remaining_output_ms", p["command_posted"], end),+ ]+ asr_points = [p["asr_stop_call"], p["capture_stop_begin"], p["capture_stop_return"],+ p["streaming_drain_end"], p["final_executor_begin"], p["final_executor_end"], p["asr_return"]]+ split_asr = (all(t is not None and math.isfinite(t) for t in asr_points)+ and all(a <= b for a,b in zip(asr_points, asr_points[1:])))+ asr_keys = ["asr_setup_ms", "capture_stop_ms", "streaming_drain_ms", "final_queue_ms", "final_asr_ms", "asr_return_ms"]+ if split_asr:+ intervals[2:3] = list(zip(asr_keys, asr_points, asr_points[1:]))+ complete = (start is not None and end is not None and+ math.isfinite(start) and math.isfinite(end) and end >= start)+ total = (end - start) * 1000 if complete else None+ m, previous = {}, start+ for key, begin, finish in intervals:+ # Partial runs still show stages that were measured; they never get a success total.+ if (start is not None and begin is not None and finish is not None+ and math.isfinite(begin) and math.isfinite(finish)+ and start <= begin <= finish and begin >= previous+ and (end is None or finish <= end)):+ m[key] = (finish - begin) * 1000+ previous = finish+ else:+ m[key] = None+ m["unattributed_ms"] = max(0, total - sum(v for v in m.values() if v is not None)) if complete else None+ m["total_ms"] = total+ for key in ["asr_ms"] + asr_keys:+ m.setdefault(key, None)+ row["pipeline"] = {key: round(value, 2) if value is not None else None for key, value in m.items()}+ row["dispatch_uptime"] = end if complete else None+++BOUNDARY_STAGES = [+ ("OS stop event → dispatch", "boundaries", "os_event_to_dispatch_ms"),+ ("OS input delivery delay", "boundaries", "input_delivery_ms"),+ ("Input callback → stop request", "boundaries", "input_to_request_ms"),+ ("Held-key time (press → release)", "boundaries", "held_key_ms"),+ ("Stop request → overlay hidden API", "boundaries", "stop_to_hidden_ms"),+ ("Stop request → handler returns", "boundaries", "stop_to_handler_return_ms"),+ ("Stop request → overlay cleanup", "boundaries", "stop_to_cleanup_ms"),+ ("Dispatch → overlay hidden API", "boundaries", "dispatch_to_hidden_ms"),+ ("Main queue wait after dispatch", "boundaries", "dispatch_main_queue_wait_ms"),+ ("Dispatch → text visibly entered", "boundaries", "dispatch_to_visible_ms"),+]++BOUNDARY_NOTES = [+ "Boundary diagnostics overlap: do not add these rows to each other or to the timeline TOTAL.",+ "OS stop event → dispatch includes OS delivery and input-callback time when all are logged. "+ "Held-key time precedes the release event; it is not processing time and is excluded from that total.",+ "Overlay milestones are API/cleanup completion, not proof of text visibility. The main-queue probe "+ "measures callback waiting after dispatch, not receiving-app delay. Missing input or visible-text markers stay —.",+]+++def add_boundary_diagnostics(rows):+ """Expose measured times outside dispatch boundaries, without claiming visibility."""+ def number(value):+ try:+ value = float(value)+ return value if math.isfinite(value) and value >= 0 else None+ except (TypeError, ValueError):+ return None++ def duration(start, end):+ start, end = number(start), number(end)+ return (end - start) * 1000 if start is not None and end is not None and end >= start else None++ for row in rows:+ m = {key: None for _, _, key in BOUNDARY_STAGES}+ stop = number(row["stop_callback_uptime"])+ dispatch = number(row.get("dispatch_uptime"))+ requests = [e for e in row["events"] if e["family"] == "HOTKEY_BENCH"+ and e["name"] == "stop_request"+ and stop is not None and number(e["fields"].get("stopRequestedAt")) == stop]+ if len(requests) == 1:+ fields = requests[0]["fields"]+ received = number(fields.get("inputReceivedAt"))+ m["input_to_request_ms"] = duration(received, stop)+ if m["input_to_request_ms"] is not None:+ m["input_delivery_ms"] = number(fields.get("inputAgeMs"))+ m["held_key_ms"] = duration(fields.get("pressReceivedAt"), received)+ if dispatch is not None and all(m[key] is not None for key in ("input_to_request_ms", "input_delivery_ms")):+ m["os_event_to_dispatch_ms"] = duration(stop, dispatch) + m["input_to_request_ms"] + m["input_delivery_ms"]+ row["input_context"] = {key: fields.get(key) for key in ("route", "eventType")}+ # Failed/cancelled output never produces a success endpoint. These+ # post-dispatch diagnostics also require a completed dispatch.+ if dispatch is not None:+ for phase, key in (("hidden", "stop_to_hidden_ms"),+ ("handler_return", "stop_to_handler_return_ms"),+ ("cleanup", "stop_to_cleanup_ms")):+ milestone = row["phase_uptime"][phase]+ if duration(dispatch, milestone) is not None:+ m[key] = duration(stop, milestone)+ m["dispatch_to_hidden_ms"] = duration(dispatch, row["phase_uptime"]["hidden"])+ probes = [e for e in row["events"] if e["family"] == "APP_BENCH"+ and e["name"] == "dispatch_main_queue_probe"+ and duration(dispatch, e["fields"].get("scheduledAt")) is not None+ and duration(e["fields"].get("scheduledAt"), e["t"]) is not None]+ if len(probes) == 1:+ m["dispatch_main_queue_wait_ms"] = duration(probes[0]["fields"]["scheduledAt"], probes[0]["t"])+ row["boundaries"] = {key: round(value, 2) if value is not None else None for key, value in m.items()}+++def render_terminal_pipeline(rows, width=None):+ add_pipeline_breakdown(rows)+ add_boundary_diagnostics(rows)+ notes = [+ "One column per dictation. Every stage is inside the TOTAL, including handoffs and waiting; "+ "rounding may differ by 0.01 ms. Unknown gaps remain in Other.",+ "Starts at the recorded stop-request callback; ends at text dispatch. "+ "Earlier input delivery and later UI work are shown separately below. Rendering/restoration are outside this interval.",+ ]+ legacy = [str(i) for i,r in enumerate(rows,1) if r["pipeline_start_basis"] == "handler_only"]+ failed = [str(i) for i,r in enumerate(rows,1) if r["pipeline"]["total_ms"] is None]+ if legacy:+ notes.append("Older/missing stop-request marker in #" + ", #".join(legacy) + ": timing starts at the handler only.")+ if failed:+ notes.append("No completed dispatch measured in #" + ", #".join(failed) + "; no successful total is claimed.")+ stages = [stage for stage in PIPELINE_STAGES if stage[2] != "asr_ms" or any(r["pipeline"]["asr_ms"] is not None for r in rows)]+ return render_terminal_stages(rows, width, stages, "FULL TIMELINE: STOP → TEXT DISPATCH", notes, precision=2) + "\n\n" + render_terminal_stages(+ rows, width, BOUNDARY_STAGES, "BOUNDARY DIAGNOSTICS (OVERLAPPING)", BOUNDARY_NOTES, precision=2)+++def main():parser = argparse.ArgumentParser(description=__doc__)parser.add_argument("--last", type=int, default=5, help="number of recent recordings (default: 5)")+ parser.add_argument("--all", action="store_true", help="include every recording retained in the input logs")parser.add_argument("--log", type=Path, action="append", help="explicit log; repeat oldest first")parser.add_argument("--details", action="store_true", help="include every benchmark marker from start through tail")- parser.add_argument("--json", action="store_true", help="machine-readable metrics and events")+ output = parser.add_mutually_exclusive_group()+ output.add_argument("--json", action="store_true", help="machine-readable metrics and events")+ output.add_argument("--stages", action="store_true", help="one measured-stage table with recordings as columns")+ output.add_argument("--latency", action="store_true", help="complete stop-to-dispatch timeline (default)")+ output.add_argument("--delivery", action="store_true", help="only the final-text-ready to paste-command-sent subsection")+ parser.add_argument("--target-log", type=Path, help="local test-field receipt JSONL")+ parser.add_argument("--test-runs", action="store_true", help="show only dictations with verified local test-field receipts")+ parser.add_argument("--markdown", action="store_true", help="export Markdown instead of the terminal table")args = parser.parse_args()if args.last < 1:parser.error("--last must be positive")@@ -454,10 +1067,47 @@ def main():lines = [line for path in paths for line in path.read_text(errors="replace").splitlines()]except OSError as error:parser.error(str(error))- rows = [summarize(run) for run in parse_logs(lines)[-args.last:]]+ rows = [summarize(run) for run in parse_logs(lines)]+ target_log = args.target_log or (base.with_name("DictationLatencyTarget.jsonl") if args.test_runs and not args.log else None)+ if target_log is not None and (args.target_log or target_log.exists()):+ try:+ attach_field_receipts(rows, target_log.read_text().splitlines())+ except OSError as error:+ parser.error(str(error))+ if args.test_runs:+ rows = [row for row in rows if row.get("field_receipt")]+ if not args.all:+ rows = rows[-args.last:]if not rows:- parser.error("no recording/pipeline start markers found")- print(json.dumps(rows, indent=2) if args.json else render(rows, args.details))+ parser.error("no verified test-field runs found" if args.test_runs else "no recording/pipeline start markers found")+ add_latency_breakdown(rows)+ add_delivery_breakdown(rows)+ add_pipeline_breakdown(rows)+ add_boundary_diagnostics(rows)+ if args.markdown and not args.stages and not args.details and not args.json:+ lines = ["# " + ("Text ready → paste command sent" if args.delivery else "Full timeline: Stop → text dispatch"), "", "All durations in ms. — = not measured.", "",+ "| Stage | " + " | ".join(f"{r['time']} / {r['id']}" for r in rows) + " |",+ "|---|" + "---:|" * len(rows)]+ for label, source, key in (DELIVERY_STAGES if args.delivery else PIPELINE_STAGES):+ lines.append("| " + label + " | " + " | ".join(+ "—" if r[source][key] is None else f"{r[source][key]:.2f}" for r in rows) + " |")+ lines += ["", "Ends at text dispatch. Start uses the stop-request callback (handler-only in older logs). Rendering and later restoration are excluded."]+ if not args.delivery:+ lines += ["", "## Boundary diagnostics (overlapping)", "",+ "| Measurement | " + " | ".join(f"{r['time']} / {r['id']}" for r in rows) + " |",+ "|---|" + "---:|" * len(rows)]+ for label, source, key in BOUNDARY_STAGES:+ lines.append("| " + label + " | " + " | ".join(+ "—" if r[source][key] is None else f"{r[source][key]:.2f}" for r in rows) + " |")+ for note in BOUNDARY_NOTES:+ lines += ["", note]+ print("\n".join(lines))+ return+ print(json.dumps(rows, indent=2) if args.json else (+ (render_stages(rows) if args.stages else render(rows, args.details))+ if args.markdown or args.details else (+ render_terminal_stages(rows) if args.stages else (+ render_terminal_delivery(rows) if args.delivery else render_terminal_pipeline(rows)))))if __name__ == "__main__":diff --git a/scripts/test_dictation_log_summary.py b/scripts/test_dictation_log_summary.pyindex 1dc88a94..859689c0 100644--- a/scripts/test_dictation_log_summary.py+++ b/scripts/test_dictation_log_summary.py@@ -1,8 +1,14 @@"""Regression fixtures; no app, microphone, or real log access."""+import contextlib+import io+import json+from pathlib import Path+import tempfileimport unittest+from unittest.mock import patch-from dictation_log_summary import parse_logs, render, summarize+from dictation_log_summary import main, parse_logs, render, render_stages, render_terminal_stages, summarize, attach_field_receipts, add_latency_breakdown, render_terminal_latency, render_terminal_delivery, add_delivery_breakdown, add_pipeline_breakdown, render_terminal_pipeline, add_boundary_diagnosticsdef row(family, t, event):@@ -252,6 +258,490 @@ class DictationLogSummaryTests(unittest.TestCase):self.assertIsNone(result["metrics"]["fi_request_ms"])+ def test_clipboard_timing_separates_request_command_and_restoration(self):+ result = self.parse(+ row("APP_BENCH", 1, "pipeline_begin id=A pipelineID=A"),+ "pipelineID=A APP_BENCH t=1.1 text_ready",+ "pipelineID=A TYPING_BENCH t=1.167 request mode=reliablePaste",+ "pipelineID=A TYPING_BENCH t=1.180 clipboard_snapshot_complete elapsedMs=2",+ "pipelineID=A TYPING_BENCH t=1.181 clipboard_write generation=5 elapsedMs=1",+ "pipelineID=A TYPING_BENCH t=1.182 command_posted generation=5 totalMs=4",+ "pipelineID=A TYPING_BENCH t=1.882 restore_completed generation=5 success=true",+ )[0]+ self.assertEqual(result["context"]["insertion_mode"], "reliablePaste")+ self.assertEqual(result["metrics"]["ready_to_request_ms"], 67)+ self.assertEqual(result["metrics"]["request_to_command_ms"], 15)+ self.assertEqual(result["metrics"]["clipboard_snapshot_ms"], 2)+ self.assertEqual(result["metrics"]["clipboard_write_ms"], 1)+ self.assertEqual(result["metrics"]["clipboard_command_total_ms"], 4)+ self.assertEqual(result["metrics"]["command_to_restore_ms"], 700)+ self.assertIsNone(result["metrics"]["typing_queue_ms"])+ self.assertEqual(result["clipboard_uptime"]["command_posted"], 1.182)+ self.assertEqual(result["context"]["clipboard_command_status"], "command_posted")+ self.assertEqual(result["context"]["clipboard_settlement_status"], "restored")+ self.assertIn("| reliablePaste | 67.0 | 15.0 | 2.0 | 1.0 | 4.0 | 700.0 |", render([result]))++ def test_absent_mode_or_command_is_unknown_and_direct_mode_is_preserved(self):+ results = self.parse(+ row("APP_BENCH", 1, "pipeline_begin id=A"),+ row("TYPING_BENCH", 1.1, "request"),+ row("APP_BENCH", 2, "pipeline_begin id=B"),+ row("TYPING_BENCH", 2.1, "request mode=standard"),+ row("TYPING_BENCH", 2.2, "complete totalMs=100"),+ )+ self.assertIsNone(results[0]["context"]["insertion_mode"])+ self.assertEqual(results[1]["context"]["insertion_mode"], "standard")+ for result in results:+ self.assertIsNone(result["metrics"]["request_to_command_ms"])+ self.assertIsNone(result["metrics"]["clipboard_command_total_ms"])+ self.assertIsNone(result["context"]["clipboard_settlement_status"])++ def test_late_clipboard_restore_uses_pipeline_and_command_generation(self):+ results = self.parse(+ row("APP_BENCH", 1, "pipeline_begin id=A pipelineID=A"),+ "pipelineID=A TYPING_BENCH t=1.1 request mode=reliablePaste",+ "pipelineID=A TYPING_BENCH t=1.2 command_posted generation=5 totalMs=1",+ row("APP_BENCH", 1.3, "begin_recording"),+ row("APP_BENCH", 1.4, "pipeline_begin id=B pipelineID=B"),+ "pipelineID=A TYPING_BENCH t=1.5 restore_completed generation=99 success=true",+ "pipelineID=A TYPING_BENCH t=1.9 restore_completed generation=5 success=false",+ )+ self.assertEqual(results[0]["metrics"]["command_to_restore_ms"], 700)+ self.assertEqual(results[0]["context"]["clipboard_settlement_status"], "restore_failed")+ self.assertEqual(results[0]["clipboard_uptime"]["clipboard_restore"], 1.9)+ self.assertIsNone(results[1]["metrics"]["command_to_restore_ms"])+ self.assertIsNone(results[1]["clipboard_uptime"]["clipboard_restore"])++ def test_clipboard_changed_skip_is_not_successful_restoration(self):+ result = self.parse(+ row("APP_BENCH", 1, "pipeline_begin id=A pipelineID=A"),+ "pipelineID=A TYPING_BENCH t=1.2 command_posted generation=3 totalMs=1",+ "pipelineID=A TYPING_BENCH t=1.9 settlement_skipped generation=3 reason=clipboard_changed",+ )[0]+ self.assertIsNone(result["metrics"]["command_to_restore_ms"])+ self.assertEqual(result["metrics"]["command_to_clipboard_change_skip_ms"], 700)+ self.assertEqual(result["context"]["clipboard_settlement_status"], "skipped_clipboard_changed")+ self.assertEqual(result["clipboard_uptime"]["clipboard_change_skipped"], 1.9)++ def test_untimed_clipboard_duration_does_not_invent_command_timestamp(self):+ result = self.parse(+ row("APP_BENCH", 1, "pipeline_begin id=A pipelineID=A"),+ "pipelineID=A TYPING_BENCH command_posted generation=3 totalMs=1",+ "pipelineID=A TYPING_BENCH t=1.9 restore_completed generation=3 success=true",+ )[0]+ self.assertEqual(result["metrics"]["clipboard_command_total_ms"], 1)+ self.assertIsNone(result["metrics"]["command_to_restore_ms"])+ self.assertIsNone(result["clipboard_uptime"]["command_posted"])++ def test_measured_focus_queue_and_timer_work_remain_separate(self):+ results = self.parse(+ row("APP_BENCH", 1.025, "pipeline_begin id=A pipelineID=A toggleStopRequestedAt=1.0"),+ "pipelineID=A APP_BENCH t=1.1 text_ready",+ "pipelineID=A APP_BENCH t=1.167 focus_target_check totalMs=67.0 pidMs=2.5 elementMs=64.0",+ "pipelineID=A TYPING_BENCH t=1.168 request mode=reliablePaste",+ "pipelineID=A TYPING_BENCH t=1.198 clipboard_slot_acquired generation=5 waitMs=30.0",+ "pipelineID=A TYPING_BENCH t=1.2 command_posted generation=5 totalMs=2",+ row("APP_BENCH", 1.3, "pipeline_begin id=B pipelineID=B toggleStopRequestedAt=nil"),+ "pipelineID=A TYPING_BENCH t=1.75 settlement_begin generation=99 elapsedMs=550 scheduledDelayMs=500",+ "pipelineID=A TYPING_BENCH t=1.8 settlement_begin generation=5 elapsedMs=599.5 scheduledDelayMs=500",+ "pipelineID=A TYPING_BENCH t=1.85 restore_completed generation=5 success=true elapsedMs=49.5",+ )+ metrics = results[0]["metrics"]+ self.assertEqual(metrics["toggle_callback_to_handler_ms"], 25)+ self.assertEqual(metrics["focus_check_ms"], 67)+ self.assertEqual(metrics["focus_pid_ms"], 2.5)+ self.assertEqual(metrics["focus_element_ms"], 64)+ self.assertEqual(metrics["clipboard_slot_wait_ms"], 30)+ self.assertEqual(metrics["request_to_command_ms"], 32)+ self.assertEqual(metrics["clipboard_command_total_ms"], 2)+ self.assertEqual(metrics["clipboard_settlement_scheduled_ms"], 500)+ self.assertEqual(metrics["clipboard_settlement_wait_ms"], 599.5)+ self.assertEqual(metrics["clipboard_restore_work_ms"], 49.5)+ self.assertEqual(metrics["command_to_restore_ms"], 650)+ self.assertIsNone(results[1]["metrics"]["clipboard_restore_work_ms"])+ self.assertIsNone(results[1]["metrics"]["toggle_callback_to_handler_ms"])+ self.assertIn("| 25.0 | 67.0 | 2.5 | 64.0 | 30.0 | 500.0 | 599.5 | 49.5 |", render(results))++ def test_missing_measured_subphases_are_not_inferred_from_totals(self):+ result = self.parse(+ row("APP_BENCH", 1, "pipeline_begin id=A pipelineID=A"),+ "pipelineID=A APP_BENCH t=1.1 focus_target_check totalMs=0.1 missingContext=true",+ "pipelineID=A TYPING_BENCH t=1.2 request mode=reliablePaste",+ "pipelineID=A TYPING_BENCH t=1.3 command_posted generation=5 totalMs=2",+ "pipelineID=A TYPING_BENCH t=1.9 restore_completed generation=5 success=true",+ )[0]+ self.assertEqual(result["metrics"]["focus_check_ms"], 0.1)+ self.assertEqual(result["context"]["focus_missing_context"], "true")+ for key in ("toggle_callback_to_handler_ms", "focus_pid_ms", "focus_element_ms",+ "clipboard_slot_wait_ms", "clipboard_settlement_wait_ms",+ "clipboard_settlement_scheduled_ms", "clipboard_restore_work_ms"):+ self.assertIsNone(result["metrics"][key], key)+ self.assertEqual(result["metrics"]["command_to_restore_ms"], 600)++ def test_intentional_copy_work_and_failed_delivery_queue_are_measured(self):+ results = self.parse(+ row("APP_BENCH", 1, "pipeline_begin id=A pipelineID=A"),+ "pipelineID=A TYPING_BENCH t=1.1 command_posted generation=5 totalMs=1",+ "pipelineID=A TYPING_BENCH t=1.7 settlement_begin generation=5 elapsedMs=600 scheduledDelayMs=500",+ "pipelineID=A TYPING_BENCH t=1.702 intentional_copy_settled generation=5 success=true elapsedMs=1.8",+ row("APP_BENCH", 2, "pipeline_begin id=B pipelineID=B"),+ "pipelineID=B TYPING_BENCH t=2.1 clipboard_slot_acquired generation=6 waitMs=9.5",+ "pipelineID=B TYPING_BENCH t=2.2 delivery_failed generation=6 reason=clipboard_snapshot_failed",+ )+ self.assertEqual(results[0]["metrics"]["clipboard_intentional_copy_work_ms"], 1.8)+ self.assertIsNone(results[0]["metrics"]["clipboard_restore_work_ms"])+ self.assertEqual(results[1]["metrics"]["clipboard_slot_wait_ms"], 9.5)+ self.assertIsNone(results[1]["metrics"]["clipboard_command_total_ms"])++ def test_stages_render_separates_recording_start_and_nested_stop_metrics(self):+ results = self.parse(+ row("APP_BENCH", 1, "begin_recording"),+ row("ASR_BENCH", 1.015, "first_audio"),+ row("APP_BENCH", 2, "pipeline_begin id=A pipelineID=A"),+ "pipelineID=A APP_BENCH t=2.01 asr_stop_call",+ "pipelineID=A APP_BENCH t=2.06 asr_stop_return",+ "pipelineID=A TYPING_BENCH t=2.2 command_posted generation=1 totalMs=1",+ row("APP_BENCH", 3, "pipeline_begin id=B pipelineID=B"),+ )+ text = render_stages(results)+ self.assertIn("| Recording start → first PCM (separate) | 15.0 | — |", text)+ self.assertIn("| Stop handler → command dispatch | 200.0 | — |", text)+ self.assertIn("| ASR stop call total | 50.0 | — |", text)+ self.assertIn("Nested stages overlap and are not additive", text)++ def test_stages_cli_uses_explicit_log_and_last(self):+ with tempfile.TemporaryDirectory() as directory:+ fixture = Path(directory) / "fixture.log"+ fixture.write_text("\n".join([+ row("APP_BENCH", 1, "pipeline_begin id=A pipelineID=A"),+ row("APP_BENCH", 2, "pipeline_begin id=B pipelineID=B"),+ "pipelineID=B TYPING_BENCH t=2.1 request mode=reliablePaste",+ ]))+ output = io.StringIO()+ with patch("sys.argv", ["dictation_log_summary.py", "--log", str(fixture), "--last", "1", "--stages"]):+ with contextlib.redirect_stdout(output):+ main()+ rendered = output.getvalue()+ self.assertIn("DICTATION TIMINGS", rendered)+ self.assertIn(" B reliablePaste", rendered)+ self.assertNotIn(" A ", rendered)+ self.assertIn("┌", rendered)+ self.assertIn("Stage (ms)", rendered)+ with patch("sys.argv", ["dictation_log_summary.py", "--log", str(fixture), "--last", "1", "--stages", "--markdown"]):+ with contextlib.redirect_stdout(io.StringIO()) as markdown:+ main()+ self.assertIn("# Dictation stages", markdown.getvalue())+ self.assertIn("| Insertion mode | reliablePaste |", markdown.getvalue())++ def test_terminal_tables_fit_width_and_preserve_every_recording(self):+ results = self.parse(*(row("APP_BENCH", i, f"pipeline_begin id=RUN{i} pipelineID=RUN{i}")+ for i in range(1, 7)))+ for width in (40, 60, 80, 120, 200):+ with self.subTest(width=width):+ output = render_terminal_stages(results, width=width)+ self.assertTrue(all(len(line) <= width for line in output.splitlines()))+ for index in range(1, 7):+ self.assertIn(f"#{index} ", output)+ self.assertIn(f"RUN{index}", output)+ self.assertEqual(output.count("┌"), output.count("└"))+ # Every row inside each bordered table must stay aligned.+ for table in output.split("┌")[1:]:+ body = table.split("└")[0].splitlines()+ self.assertTrue(all(len(line) == len(body[0]) + 1 for line in body[1:]))++ def test_terminal_preserves_zero_unknown_and_large_values(self):+ results = self.parse(row("APP_BENCH", 1, "pipeline_begin id=A pipelineID=A"))+ results[0]["metrics"]["clipboard_slot_wait_ms"] = 0+ results[0]["metrics"]["ai_processing_ms"] = 123456.7+ output = render_terminal_stages(results, width=80)+ self.assertRegex(output, r"Clipboard slot wait[^\n]+0\.0")+ self.assertRegex(output, r"AI processing[^\n]+123456\.7")+ self.assertRegex(output, r"Clipboard snapshot[^\n]+—")+ self.assertIn("Nested stages overlap", output)++ def latency_fixture(self, pipeline="A", pid=42):+ return self.parse(+ row("APP_BENCH", 1.02, f"pipeline_begin id={pipeline} pipelineID={pipeline} toggleStopRequestedAt=1.01"),+ f"pipelineID={pipeline} APP_BENCH t=1.03 asr_stop_call",+ f"pipelineID={pipeline} APP_BENCH t=1.13 asr_stop_return",+ f"pipelineID={pipeline} APP_BENCH t=1.14 ai_process_call",+ f"pipelineID={pipeline} APP_BENCH t=1.24 ai_process_return",+ f"pipelineID={pipeline} APP_BENCH t=1.25 text_ready",+ f"pipelineID={pipeline} TYPING_BENCH t=1.27 request chars=5 mode=reliablePaste preferredPID={pid}",+ f"pipelineID={pipeline} TYPING_BENCH t=1.28 command_posted generation=1 totalMs=10",+ )++ def receipt_fixture(self, **changes):+ events = [dict(event="stop_pressed", t=1.0, run_id="test", target_pid=42),+ dict(event="field_received", t=1.3, run_id="test", target_pid=42, chars=5)]+ events[1].update(changes)+ return [json.dumps(e) for e in events]++ def test_stop_to_field_partitions_all_time_and_excludes_background(self):+ rows = self.latency_fixture()+ attach_field_receipts(rows, self.receipt_fixture())+ add_latency_breakdown(rows)+ m = rows[0]["latency"]+ self.assertEqual(m["total_ms"], 300)+ self.assertEqual(m["sent_ms"], 270)+ self.assertEqual(m["input_ms"], 10)+ self.assertEqual(m["receiver_ms"], 20)+ self.assertEqual(m["unattributed_ms"], 0)+ self.assertEqual(sum(v for k, v in m.items() if k not in ("total_ms", "sent_ms") and v is not None), 300)+ output = render_terminal_latency(rows, width=80)+ table = output.split("┌", 1)[1].split("└", 1)[0]+ self.assertNotIn("PCM", table)+ self.assertNotIn("Restore", table)+ self.assertNotIn("Overlay", table)+ self.assertIn("300.0", table)++ def test_missing_receipt_never_claims_end_to_end(self):+ rows = self.latency_fixture()+ add_latency_breakdown(rows)+ self.assertIsNone(rows[0]["latency"]["total_ms"])+ self.assertIsNone(rows[0]["latency"]["receiver_ms"])+ self.assertEqual(rows[0]["latency"]["sent_ms"], 270)++ def test_reject_wrong_target_partial_text_and_stale_receipts(self):+ for changes in ({"target_pid": 9}, {"chars": 4}, {"t": 0.5}, {"t": 40},+ {"event": "field_mismatch"}, {"t": float("nan")}):+ with self.subTest(changes=changes):+ rows = self.latency_fixture()+ attach_field_receipts(rows, self.receipt_fixture(**changes))+ self.assertNotIn("field_receipt", rows[0])+ rows = self.latency_fixture()+ logs = self.receipt_fixture() + [json.dumps(dict(event="timeout", t=1.4, run_id="test", target_pid=42))]+ attach_field_receipts(rows, logs)+ self.assertNotIn("field_receipt", rows[0])++ def test_ambiguous_pipeline_or_duplicate_test_is_not_a_measurement(self):+ rows = self.latency_fixture() + self.latency_fixture(pipeline="B")+ attach_field_receipts(rows, self.receipt_fixture())+ self.assertTrue(all("field_receipt" not in r for r in rows))+ rows = self.latency_fixture()+ logs = self.receipt_fixture()+ attach_field_receipts(rows, logs + [line.replace('"test"', '"second"') for line in logs])+ self.assertNotIn("field_receipt", rows[0])++ def test_missing_ai_markers_count_as_unattributed_not_zero(self):+ rows = self.latency_fixture()+ rows[0]["phase_uptime"]["ai_call"] = None+ rows[0]["phase_uptime"]["ai_return"] = None+ attach_field_receipts(rows, self.receipt_fixture())+ add_latency_breakdown(rows)+ m = rows[0]["latency"]+ self.assertEqual(m["total_ms"], 300)+ self.assertEqual(m["unattributed_ms"], 120)+ self.assertIsNone(m["ai_ms"])++ def test_receipt_before_dispatch_log_does_not_make_negative_latency(self):+ rows = self.latency_fixture()+ attach_field_receipts(rows, self.receipt_fixture(t=1.275))+ add_latency_breakdown(rows)+ m = rows[0]["latency"]+ self.assertEqual(m["total_ms"], 275)+ self.assertIsNone(m["receiver_ms"])+ self.assertIsNone(m["insertion_ms"])+ self.assertEqual(m["unattributed_ms"], 5)+++ def test_delivery_only_partitions_ready_to_dispatch(self):+ rows = self.latency_fixture()+ p = rows[0]["phase_uptime"]+ p.update(clipboard_slot_acquired=1.271, clipboard_snapshot_complete=1.274, clipboard_write=1.278)+ add_delivery_breakdown(rows)+ m = rows[0]["delivery"]+ self.assertEqual(m, dict(prepare_ms=20, queue_ms=1, snapshot_ms=3, write_ms=4,+ dispatch_ms=2, unattributed_ms=0, total_ms=30))+ self.assertEqual(sum(v for k,v in m.items() if k != "total_ms"), m["total_ms"])+ output = render_terminal_delivery(rows, width=80)+ table = output.split("┌",1)[1].split("└",1)[0]+ self.assertIn("30.00", table)+ self.assertNotIn("AI", table)+ self.assertNotIn("PCM", table)+ self.assertNotIn("field confirmed", table)+ self.assertNotIn("Restore timer", table)++ def test_delivery_missing_markers_and_failed_dispatch_stay_honest(self):+ rows = self.latency_fixture()+ add_delivery_breakdown(rows)+ m = rows[0]["delivery"]+ self.assertEqual(m["total_ms"], 30)+ self.assertEqual(m["unattributed_ms"], 10)+ self.assertIsNone(m["snapshot_ms"])+ rows[0]["phase_uptime"]["command_posted"] = None+ add_delivery_breakdown(rows)+ self.assertIsNone(rows[0]["delivery"]["total_ms"])++ def test_full_timeline_counts_every_stage_once(self):+ rows = self.latency_fixture()+ p = rows[0]["phase_uptime"]+ p.update(clipboard_slot_acquired=1.271, clipboard_snapshot_complete=1.274, clipboard_write=1.278)+ # Neither a receiving-field timestamp nor later clipboard restoration changes this endpoint.+ rows[0]["field_receipt"] = dict(stop=1.0, received=1.9)+ p["clipboard_restore"] = 2.5+ add_pipeline_breakdown(rows)+ m = rows[0]["pipeline"]+ self.assertEqual(m["total_ms"], 270)+ self.assertEqual(m["stop_queue_ms"], 10)+ self.assertEqual(m["asr_ms"], 100)+ self.assertEqual(m["ai_ms"], 100)+ self.assertEqual(m["unattributed_ms"], 0)+ self.assertEqual(sum(v for k,v in m.items() if k != "total_ms" and v is not None), 270)++ def test_full_timeline_exposes_active_chunk_wait_without_double_counting_asr(self):+ rows = self.latency_fixture()+ rows[0]["phase_uptime"].update(capture_stop_begin=1.031, capture_stop_return=1.041,+ streaming_drain_end=1.09, final_executor_begin=1.10, final_executor_end=1.12)+ add_pipeline_breakdown(rows)+ m = rows[0]["pipeline"]+ self.assertIsNone(m["asr_ms"])+ self.assertEqual(m["capture_stop_ms"], 10)+ self.assertEqual(m["streaming_drain_ms"], 49)+ self.assertEqual(m["final_asr_ms"], 20)+ self.assertEqual(sum(v for k,v in m.items() if k != "total_ms" and v is not None), 270)+ self.assertIn("Wait for active transcription chunk", render_terminal_pipeline(rows, width=80))++ def test_full_timeline_multiple_output_steps_and_failure(self):+ rows = self.latency_fixture()+ rows[0]["events"].append(dict(family="TYPING_BENCH", name="command_posted", t=1.9, fields={}))+ add_pipeline_breakdown(rows)+ self.assertEqual(rows[0]["pipeline"]["total_ms"], 890)+ self.assertEqual(rows[0]["pipeline"]["remaining_output_ms"], 620)+ rows[0]["events"].append(dict(family="TYPING_BENCH", name="delivery_failed", t=1.91, fields={}))+ add_pipeline_breakdown(rows)+ self.assertIsNone(rows[0]["pipeline"]["total_ms"])+ self.assertEqual(rows[0]["pipeline"]["ai_ms"], 100)++ def test_default_cli_is_full_timeline_and_all_includes_each_recording(self):+ with tempfile.TemporaryDirectory() as directory:+ log = Path(directory) / "fixture.log"+ log.write_text("\n".join([row("APP_BENCH", 1, "pipeline_begin id=A pipelineID=A"),+ row("APP_BENCH", 2, "pipeline_begin id=B pipelineID=B")]))+ with patch("sys.argv", ["dictation_log_summary.py", "--log", str(log), "--last", "1", "--all"]):+ with contextlib.redirect_stdout(io.StringIO()) as output:+ main()+ text = output.getvalue()+ self.assertIn("FULL TIMELINE: STOP", text)+ self.assertIn(" A ", text)+ self.assertIn(" B ", text)+ self.assertNotIn("TOTAL: Text ready", text)++ def boundary_fixture(self, *extra):+ return self.parse(+ row("HOTKEY_BENCH", 1.01, "stop_request stopRequestedAt=1.01 inputReceivedAt=1.0 inputAgeMs=5 pressReceivedAt=0.9 route=toggle eventType=flagsChanged"),+ row("APP_BENCH", 1.02, "pipeline_begin id=A pipelineID=A toggleStopRequestedAt=1.01"),+ row("TYPING_BENCH", 1.28, "command_posted pipelineID=A"),+ row("OVERLAY_BENCH", 1.36, "manager finish_hide_complete pipelineID=A"),+ row("APP_BENCH", 1.37, "pipeline_handler_return pipelineID=A"),+ row("APP_BENCH", 1.38, "dispatch_main_queue_probe scheduledAt=1.281 pipelineID=A"),+ row("OVERLAY_BENCH", 1.47, "bottom_hide_immediate_cleanup_complete pipelineID=A"),+ *extra,+ )++ def test_input_and_post_dispatch_boundaries_do_not_inflate_pipeline_total(self):+ rows = self.boundary_fixture()+ add_pipeline_breakdown(rows)+ add_boundary_diagnostics(rows)+ self.assertEqual(rows[0]["pipeline"]["total_ms"], 270)+ self.assertEqual(rows[0]["boundaries"], dict(+ os_event_to_dispatch_ms=285, input_delivery_ms=5, input_to_request_ms=10,+ held_key_ms=100, stop_to_hidden_ms=350, stop_to_handler_return_ms=360,+ stop_to_cleanup_ms=460, dispatch_to_hidden_ms=80,+ dispatch_main_queue_wait_ms=99, dispatch_to_visible_ms=None))++ def test_hotkey_matching_is_exact_unique_and_reset_at_process_restart(self):+ prefix = row("HOTKEY_BENCH", 1.01, "stop_request stopRequestedAt=1.01 inputReceivedAt=1.0 inputAgeMs=5")+ pipeline = row("APP_BENCH", 1.02, "pipeline_begin id=A pipelineID=A toggleStopRequestedAt=1.01")+ for lines in ((prefix, pipeline.replace("At=1.01", "At=1.0101")),+ (prefix, "[RUN] new process", pipeline),+ (prefix, prefix.replace("inputAgeMs=5", "inputAgeMs=6"), pipeline),+ (prefix, pipeline, pipeline.replace("id=A", "id=B").replace("pipelineID=A", "pipelineID=B"))):+ with self.subTest(lines=lines):+ rows = self.parse(*lines)+ add_pipeline_breakdown(rows)+ add_boundary_diagnostics(rows)+ self.assertTrue(all(r["boundaries"]["input_to_request_ms"] is None for r in rows))+ # A delayed log line routes to A even after a newer B recording began.+ rows = self.parse(pipeline,+ pipeline.replace("id=A", "id=B").replace("pipelineID=A", "pipelineID=B").replace("At=1.01", "At=2.01"),+ prefix)+ add_pipeline_breakdown(rows)+ add_boundary_diagnostics(rows)+ self.assertEqual(rows[0]["boundaries"]["input_to_request_ms"], 10)+ self.assertIsNone(rows[1]["boundaries"]["input_to_request_ms"])++ def test_missing_invalid_or_future_input_does_not_create_total(self):+ for changes in ({"inputAgeMs": None}, {"inputAgeMs": "nan"},+ {"inputAgeMs": "-1"}, {"inputReceivedAt": "1.1"},+ {"inputReceivedAt": "inf"}, {"stopRequestedAt": "1.011"}):+ with self.subTest(changes=changes):+ rows = self.boundary_fixture()+ event = next(e for e in rows[0]["events"] if e["family"] == "HOTKEY_BENCH")+ event["fields"].update(changes)+ add_pipeline_breakdown(rows)+ add_boundary_diagnostics(rows)+ self.assertIsNone(rows[0]["boundaries"]["os_event_to_dispatch_ms"])+ rows = self.boundary_fixture()+ event = next(e for e in rows[0]["events"] if e["family"] == "HOTKEY_BENCH")+ event["fields"]["pressReceivedAt"] = "1.1"+ add_pipeline_breakdown(rows)+ add_boundary_diagnostics(rows)+ self.assertIsNone(rows[0]["boundaries"]["held_key_ms"])+ self.assertEqual(rows[0]["boundaries"]["os_event_to_dispatch_ms"], 285)++ def test_cancelled_and_failed_delivery_have_no_boundary_success_endpoint(self):+ for cancelled in (False, True):+ rows = self.boundary_fixture()+ if cancelled:+ rows[0]["outcome"] = "cancelled"+ else:+ rows[0]["events"].append(dict(family="TYPING_BENCH", name="delivery_failed", t=1.29, fields={}))+ add_pipeline_breakdown(rows)+ add_boundary_diagnostics(rows)+ self.assertIsNone(rows[0]["boundaries"]["os_event_to_dispatch_ms"])+ self.assertIsNone(rows[0]["boundaries"]["stop_to_cleanup_ms"])+ self.assertIsNone(rows[0]["boundaries"]["dispatch_main_queue_wait_ms"])+ self.assertEqual(rows[0]["boundaries"]["input_to_request_ms"], 10)++ def test_pre_dispatch_stale_and_ambiguous_probe_markers_stay_unknown(self):+ rows = self.boundary_fixture()+ rows[0]["phase_uptime"]["hidden"] = 1.1+ probe = next(e for e in rows[0]["events"] if e["name"] == "dispatch_main_queue_probe")+ probe["fields"]["scheduledAt"] = "1.27"+ add_pipeline_breakdown(rows)+ add_boundary_diagnostics(rows)+ self.assertIsNone(rows[0]["boundaries"]["dispatch_to_hidden_ms"])+ self.assertIsNone(rows[0]["boundaries"]["stop_to_hidden_ms"])+ self.assertIsNone(rows[0]["boundaries"]["dispatch_main_queue_wait_ms"])+ rows = self.boundary_fixture(row("APP_BENCH", 1.39, "dispatch_main_queue_probe scheduledAt=1.281 pipelineID=A"))+ add_pipeline_breakdown(rows)+ add_boundary_diagnostics(rows)+ self.assertIsNone(rows[0]["boundaries"]["dispatch_main_queue_wait_ms"])+ # Unlabelled or foreign IDs cannot contaminate a correlated run.+ rows = self.parse(row("APP_BENCH", 1.02, "pipeline_begin id=A pipelineID=A toggleStopRequestedAt=1.01"),+ row("TYPING_BENCH", 1.28, "command_posted pipelineID=A"),+ row("APP_BENCH", 1.38, "dispatch_main_queue_probe scheduledAt=1.281 pipelineID=OLD"),+ row("APP_BENCH", 1.39, "dispatch_main_queue_probe scheduledAt=1.281"))+ add_pipeline_breakdown(rows)+ add_boundary_diagnostics(rows)+ self.assertIsNone(rows[0]["boundaries"]["dispatch_main_queue_wait_ms"])++ def test_boundary_tables_fit_terminal_and_markdown_export_includes_notes(self):+ for width in (40, 60, 80, 120, 200):+ output = render_terminal_pipeline(self.boundary_fixture(), width=width)+ self.assertTrue(all(len(line) <= width for line in output.splitlines()))+ self.assertIn("BOUNDARY DIAGNOSTICS", output)+ with tempfile.TemporaryDirectory() as directory:+ log = Path(directory) / "fixture.log"+ log.write_text(row("APP_BENCH", 1.02, "pipeline_begin id=A pipelineID=A toggleStopRequestedAt=1.01"))+ with patch("sys.argv", ["dictation_log_summary.py", "--log", str(log), "--markdown"]):+ with contextlib.redirect_stdout(io.StringIO()) as output:+ main()+ self.assertIn("## Boundary diagnostics (overlapping)", output.getvalue())+ self.assertIn("do not add these rows", output.getvalue())+ self.assertIn("| Dispatch → text visibly entered | — |", output.getvalue())+if __name__ == "__main__":unittest.main()