Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 语音输入浮窗开在焦点所在的显示器上 (#845)

Dashc7ca9c7a45d4
diff --git a/apps/desktop/native/voice-input/macos-text-insertion-helper.swift b/apps/desktop/native/voice-input/macos-text-insertion-helper.swift
index e963d5081f..7fefe1fd79 100644
--- a/apps/desktop/native/voice-input/macos-text-insertion-helper.swift
+++ b/apps/desktop/native/voice-input/macos-text-insertion-helper.swift
@@ -34,6 +34,12 @@ struct Options {
var targetPid: pid_t?
var targetBundleId = ""
var targetName = ""
+ /// Only collect the focused window frame when the caller actually needs it.
+ /// On a single-display Mac the answer cannot change which display the overlay
+ /// opens on, and on an AX-slow target these extra requests each cost up to the
+ /// configured messaging timeout — that would delay the paste target capture for
+ /// nothing.
+ var withFocusedFrame = false
}
struct Snapshot {
@@ -140,6 +146,8 @@ func parseOptions() throws -> Options {
case "--target-name":
guard let value = iterator.next() else { throw HelperError.missingValue(arg) }
options.targetName = value
+ case "--with-focused-frame":
+ options.withFocusedFrame = true
default:
throw HelperError.invalidArgument("Unknown argument: \(arg)")
}
@@ -441,13 +449,55 @@ let AX_SELECTED_TEXT_MARKER_RANGE = "AXSelectedTextMarkerRange" as CFString
let AX_TEXT_MARKER_RANGE_FOR_UI_ELEMENT = "AXTextMarkerRangeForUIElement" as CFString
let AX_STRING_FOR_TEXT_MARKER_RANGE = "AXStringForTextMarkerRange" as CFString
-func captureTargetPayload() -> [String: Any] {
+func captureTargetPayload(withFocusedFrame: Bool) -> [String: Any] {
guard let app = NSWorkspace.shared.frontmostApplication else {
return [
"ok": false,
"error": "No frontmost application"
]
}
+ // Read the focused window frame FIRST, before any AX mutation below: it must
+ // describe the same frontmostApplication snapshot as the paste target, and it
+ // must not observe a layout perturbed by the AXEnhancedUserInterface flip.
+ // Deriving both from one helper run is what keeps "which display do we open
+ // on" and "which app do we paste into" from disagreeing — two separate helper
+ // processes would each read frontmostApplication at a slightly different
+ // moment.
+ // Two frames, streamed in cost order, each on its own line before the
+ // (potentially slow) context capture below:
+ //
+ // 1. CGWindowList — an in-process window-server query with no Accessibility
+ // grant and no per-request timeout. It always lands inside the caller's
+ // ~90 ms display-selection deadline, but z-order is only an approximation of
+ // focus: an app's unfocused always-on-top palette can sit in front of the
+ // focused document.
+ // 2. AX kAXFocusedWindow — authoritative about focus, but each request can burn
+ // a messaging timeout against an unresponsive target, so it may miss the
+ // deadline entirely.
+ //
+ // Emitting both lets the caller use the accurate answer whenever it arrives in
+ // time and still have a usable one when it does not. The final payload carries
+ // the best available frame so buffered callers keep working.
+ var bestFrame: (frame: [String: Any], source: String)? = nil
+ if withFocusedFrame {
+ if let listFrame = frontWindowFrameFromWindowList(pid: app.processIdentifier) {
+ bestFrame = (listFrame, "window-list")
+ emitLine([
+ "event": "focused-window-frame",
+ "frame": listFrame,
+ "frameSource": "window-list"
+ ])
+ }
+ if let axFrame = axFocusedWindowFrame(for: app) {
+ bestFrame = (axFrame, "ax")
+ emitLine([
+ "event": "focused-window-frame",
+ "frame": axFrame,
+ "frameSource": "ax"
+ ])
+ }
+ }
+ let focusedFrame = bestFrame
var context = captureFocusedElementContext(for: app)
var enhancedAxAttempted = false
var enhancedAxHelped = false
@@ -488,9 +538,106 @@ func captureTargetPayload() -> [String: Any] {
if let context = context {
payload["context"] = context
}
+ if let focusedFrame = focusedFrame {
+ payload["frame"] = focusedFrame.frame
+ payload["frameSource"] = focusedFrame.source
+ }
return payload
}
+// Reports the frontmost window's frame so the global voice overlay can open on
+// the display the user is actually working on.
+//
+// Coordinates are AX/CGWindow screen coordinates: origin at the top-left of the
+// primary display, y growing downwards, in points. That matches Electron's DIP
+// screen coordinate space on macOS, so main can feed the frame straight into
+// screen.getDisplayMatching().
+
+func axFocusedWindowFrame(for app: NSRunningApplication) -> [String: Any]? {
+ guard AXIsProcessTrusted() else { return nil }
+ let axApp = AXUIElementCreateApplication(app.processIdentifier)
+ AXUIElementSetMessagingTimeout(axApp, 0.2)
+ guard let windowValue = copyAttribute(axApp, kAXFocusedWindowAttribute as CFString),
+ CFGetTypeID(windowValue) == AXUIElementGetTypeID() else {
+ return nil
+ }
+ let window = windowValue as! AXUIElement
+ AXUIElementSetMessagingTimeout(window, 0.2)
+ guard let origin = axPointAttribute(window, kAXPositionAttribute as CFString),
+ let size = axSizeAttribute(window, kAXSizeAttribute as CFString) else {
+ return nil
+ }
+ return [
+ "x": Double(origin.x),
+ "y": Double(origin.y),
+ "width": Double(size.width),
+ "height": Double(size.height)
+ ]
+}
+
+func axPointAttribute(_ element: AXUIElement, _ attribute: CFString) -> CGPoint? {
+ guard let value = copyAttribute(element, attribute),
+ CFGetTypeID(value) == AXValueGetTypeID() else {
+ return nil
+ }
+ var point = CGPoint.zero
+ guard AXValueGetValue(value as! AXValue, .cgPoint, &point) else { return nil }
+ return point
+}
+
+func axSizeAttribute(_ element: AXUIElement, _ attribute: CFString) -> CGSize? {
+ guard let value = copyAttribute(element, attribute),
+ CFGetTypeID(value) == AXValueGetTypeID() else {
+ return nil
+ }
+ var size = CGSize.zero
+ guard AXValueGetValue(value as! AXValue, .cgSize, &size) else { return nil }
+ return size
+}
+
+func frontWindowFrameFromWindowList(pid: pid_t) -> [String: Any]? {
+ let options: CGWindowListOption = [.optionOnScreenOnly, .excludeDesktopElements]
+ guard let windows = CGWindowListCopyWindowInfo(options, kCGNullWindowID) as? [[String: Any]] else {
+ return nil
+ }
+ // This is the deadline-safe approximation only; AX kAXFocusedWindow is what
+ // actually knows where focus is, and the caller prefers it whenever it arrives
+ // in time (see captureTargetPayload).
+ //
+ // Within that role, prefer the frontmost layer-0 window: an app's document
+ // windows live on layer 0, while higher layers hold palettes, tooltips and
+ // always-on-top helpers that are commonly NOT focused. Only if the app exposes
+ // no layer-0 window at all do we fall back to its frontmost window on any layer
+ // (some apps are panel-only).
+ var fallbackAnyLayer: [String: Any]? = nil
+ for window in windows {
+ // 这些值是 NSNumber。不要写 `as? pid_t`:NSNumber 只桥接到 Int,条件转换到
+ // Int32 会一律失败,整条兜底就变成永远返回 nil。
+ guard let ownerPid = (window[kCGWindowOwnerPID as String] as? NSNumber)?.int32Value,
+ ownerPid == pid else { continue }
+ // 完全透明的窗口不是用户在看的东西(点击穿透层、隐藏的辅助窗口)。
+ if let alpha = (window[kCGWindowAlpha as String] as? NSNumber)?.doubleValue, alpha <= 0 {
+ continue
+ }
+ guard let boundsDict = window[kCGWindowBounds as String] as? [String: Any],
+ let rect = CGRect(dictionaryRepresentation: boundsDict as CFDictionary) else {
+ continue
+ }
+ // 退化尺寸同样跳过:1x1 之类的占位窗口没法用来判断用户在哪块屏。
+ if rect.width <= 1 || rect.height <= 1 { continue }
+ let frame: [String: Any] = [
+ "x": Double(rect.origin.x),
+ "y": Double(rect.origin.y),
+ "width": Double(rect.width),
+ "height": Double(rect.height)
+ ]
+ let layer = (window[kCGWindowLayer as String] as? NSNumber)?.intValue
+ if layer == 0 { return frame }
+ if fallbackAnyLayer == nil { fallbackAnyLayer = frame }
+ }
+ return fallbackAnyLayer
+}
+
// Extracts before/selected/after text around the cursor in the focused element.
// Used by the global voice overlay path to give the refiner the same kind of
// surrounding context that ChatInput already provides for in-app dictation —
@@ -1238,6 +1385,23 @@ func buildPasteResult(
]
}
+/**
+ Writes one JSON line and flushes it immediately.
+
+ stdout is a pipe here, so libc buffers it fully — without the explicit flush an
+ early "progress" line would not reach the parent until the process exits, which
+ would defeat the whole point of streaming it. The parent treats the LAST JSON
+ line as the command result and earlier lines as tagged progress events.
+ */
+func emitLine(_ payload: [String: Any]) {
+ guard let data = try? JSONSerialization.data(withJSONObject: payload, options: [.sortedKeys]),
+ let text = String(data: data, encoding: .utf8) else {
+ return
+ }
+ print(text)
+ fflush(stdout)
+}
+
func emit(_ payload: [String: Any]) {
do {
let data = try JSONSerialization.data(withJSONObject: payload, options: [.sortedKeys])
@@ -1269,7 +1433,7 @@ do {
let options = try parseOptions()
switch options.command {
case "capture-target":
- emit(captureTargetPayload())
+ emit(captureTargetPayload(withFocusedFrame: options.withFocusedFrame))
case "paste-verified":
emit(pasteVerifiedPayload(options: options))
default:
diff --git a/apps/desktop/src/main/voice-input/__tests__/globalShortcut.test.ts b/apps/desktop/src/main/voice-input/__tests__/globalShortcut.test.ts
index 01543b246b..3f62f43740 100644
--- a/apps/desktop/src/main/voice-input/__tests__/globalShortcut.test.ts
+++ b/apps/desktop/src/main/voice-input/__tests__/globalShortcut.test.ts
@@ -255,4 +255,43 @@ describe('voice input global shortcut registration', () => {
expect(shouldRestoreOverlayPasteTarget(undefined, 'darwin')).toBe(true);
expect(shouldRestoreOverlayPasteTarget(undefined, 'win32')).toBe(false);
});
+
+ // helper 会在最终结果之前先流式吐出前台窗口 frame(浮窗选屏只等这一行),所以
+ // 结果解析必须认最后一行,不能把第一行进度事件当成命令结果。
+ describe('parseMacTextInsertionHelperResult', () => {
+ it('多行输出时取最后一行作为结果', async () => {
+ const { parseMacTextInsertionHelperResult } = await import('../global.js');
+ const stdout = [
+ '{"event":"focused-window-frame","frame":{"x":0,"y":0,"width":800,"height":600},"frameSource":"ax"}',
+ '{"ok":true,"target":{"processName":"Chrome","bundleId":"com.google.Chrome","pid":42}}',
+ '',
+ ].join('\n');
+
+ const result = parseMacTextInsertionHelperResult(stdout);
+ expect(result.ok).toBe(true);
+ expect(result.event).toBeUndefined();
+ expect(result.target?.processName).toBe('Chrome');
+ });
+
+ it('单行输出保持原行为', async () => {
+ const { parseMacTextInsertionHelperResult } = await import('../global.js');
+ expect(parseMacTextInsertionHelperResult('{"ok":true,"outcome":"verified_success"}\n').ok)
+ .toBe(true);
+ });
+
+ it('空输出与非法 JSON 抛错(由调用方转成 PasteCommandError)', async () => {
+ const { parseMacTextInsertionHelperResult } = await import('../global.js');
+ expect(() => parseMacTextInsertionHelperResult(' \n\n')).toThrow();
+ expect(() => parseMacTextInsertionHelperResult('not json')).toThrow();
+ });
+ });
+
+ // 词典 toast 锚点按「请求到达顺序」绑定:renderer 收到证据会立刻发起 advisor 请求,
+ // 所以请求到达顺序 == 证据发布顺序,并发只发生在响应上。取走必须是 FIFO 且一次性。
+ describe('takeOverlayDictionaryToastAnchor', () => {
+ it('没有待取锚点时返回 null', async () => {
+ const { takeOverlayDictionaryToastAnchor } = await import('../global.js');
+ expect(takeOverlayDictionaryToastAnchor()).toBeNull();
+ });
+ });
});
diff --git a/apps/desktop/src/main/voice-input/__tests__/overlayPlacement.test.ts b/apps/desktop/src/main/voice-input/__tests__/overlayPlacement.test.ts
index ef065ad803..d95a84a7e0 100644
--- a/apps/desktop/src/main/voice-input/__tests__/overlayPlacement.test.ts
+++ b/apps/desktop/src/main/voice-input/__tests__/overlayPlacement.test.ts
@@ -2,10 +2,14 @@ import { describe, expect, it } from 'vitest';
import {
clampOverlayBoundsToWorkArea,
+ computeOverlayPositionRatio,
+ isBoundsCenterOnDisplay,
+ normalizeFocusedWindowFrame,
normalizeSavedOverlayPosition,
resolveDraggedOverlayBounds,
resolveOverlayInitialBounds,
type OverlayPlacementDisplay,
+ type SavedOverlayPosition,
} from '../overlayPlacement.js';
// 与 global.ts 保持一致的几何常量(避免 import 触发 electron 依赖)。
@@ -135,67 +139,295 @@ describe('resolveDraggedOverlayBounds', () => {
describe('resolveOverlayInitialBounds', () => {
const fallbackBounds = { x: 660, y: 800, width: WIDTH, height: HEIGHT };
- it('无保存位置时使用默认位置', () => {
- const result = resolveOverlayInitialBounds({
- savedPosition: null,
- displays: [primary],
+ function initial(
+ savedPosition: SavedOverlayPosition | null,
+ options?: {
+ displays?: OverlayPlacementDisplay[];
+ activeDisplay?: OverlayPlacementDisplay | null;
+ },
+ ) {
+ const displays = options?.displays ?? [primary];
+ return resolveOverlayInitialBounds({
+ savedPosition,
+ displays,
+ activeDisplay: options?.activeDisplay === undefined ? displays[0] ?? null : options.activeDisplay,
size: SIZE,
...geometry,
fallbackBounds,
});
- expect(result).toEqual(fallbackBounds);
+ }
+
+ /** 按 global.ts 落盘时的算法,为一个绝对坐标算出屏内相对比例。 */
+ function ratioOf(x: number, y: number, display: OverlayPlacementDisplay) {
+ return computeOverlayPositionRatio({ x, y, width: WIDTH, height: HEIGHT }, display.workArea);
+ }
+
+ it('无保存位置时使用默认位置', () => {
+ expect(initial(null)).toEqual(fallbackBounds);
});
it('保存位置有效时记忆优先', () => {
- const result = resolveOverlayInitialBounds({
- savedPosition: { x: 100, y: 200, displayId: 1, updatedAt: 1 },
- displays: [primary],
- size: SIZE,
- ...geometry,
- fallbackBounds,
- });
- expect(result).toEqual({ x: 100, y: 200, width: WIDTH, height: HEIGHT });
+ expect(initial({ x: 100, y: 200, displayId: 1, updatedAt: 1 }))
+ .toEqual({ x: 100, y: 200, width: WIDTH, height: HEIGHT });
});
it('保存位置所在屏幕已不存在时回退默认位置', () => {
- const result = resolveOverlayInitialBounds({
- savedPosition: { x: 3000, y: 500, displayId: 2, updatedAt: 1 }, // 中心在已拔掉的副屏
+ // 中心在已拔掉的副屏,displayId 也找不到对应屏。
+ expect(initial({ x: 3000, y: 500, displayId: 2, updatedAt: 1 })).toEqual(fallbackBounds);
+ });
+
+ it('displayId 记着但那块屏已拔掉时回退默认位置,即使旧坐标现在落进了另一块屏', () => {
+ // 记忆属于副屏(已拔掉),旧坐标现在落在主屏范围内。不能因此把记忆改判给
+ // 主屏并恢复那个陈旧坐标。
+ expect(initial({ x: 300, y: 500, displayId: secondary.id, updatedAt: 1 }, {
displays: [primary],
- size: SIZE,
- ...geometry,
- fallbackBounds,
- });
- expect(result).toEqual(fallbackBounds);
+ activeDisplay: primary,
+ })).toEqual(fallbackBounds);
});
- it('保存位置轻微越界时 clamp 回可见区域', () => {
- const result = resolveOverlayInitialBounds({
- savedPosition: { x: -200, y: 950, updatedAt: 1 }, // 中心仍在主屏内
+ it('同屏 workArea 未变时,带比例的记忆还原回原坐标(1px 取整误差内)', () => {
+ const saved = {
+ x: 400,
+ y: 700,
+ displayId: primary.id,
+ ...ratioOf(400, 700, primary),
+ updatedAt: 1,
+ };
+ const result = initial(saved, { displays: [primary], activeDisplay: primary });
+ expect(Math.abs(result.x - saved.x)).toBeLessThanOrEqual(1);
+ expect(Math.abs(result.y - saved.y)).toBeLessThanOrEqual(1);
+ });
+
+ it('同屏但分辨率变了时按比例走,不沿用旧的绝对坐标', () => {
+ // 在 1920 宽的屏上水平居中存下;该屏换成 2560 宽后仍应居中,而不是停在
+ // 旧坐标(那会变成偏左)。旧坐标中心仍落在新 workArea 内,所以这条正是
+ // 「坐标看起来还有效但其实已经不对」的场景。
+ const savedX = Math.round(primary.workArea.x + (primary.workArea.width - WIDTH) / 2);
+ const widerPrimary: OverlayPlacementDisplay = {
+ id: primary.id,
+ workArea: { x: primary.workArea.x, y: primary.workArea.y, width: 2560, height: 1055 },
+ };
+ const result = initial({
+ x: savedX,
+ y: 700,
+ displayId: primary.id,
+ ...ratioOf(savedX, 700, primary),
+ updatedAt: 1,
+ }, { displays: [widerPrimary], activeDisplay: widerPrimary });
+ const expectedX = Math.round(widerPrimary.workArea.x + (widerPrimary.workArea.width - WIDTH) / 2);
+ expect(Math.abs(result.x - expectedX)).toBeLessThanOrEqual(1);
+ });
+
+ it('旧快照没有比例、坐标又已不在归属屏内时回退默认位置', () => {
+ // 升级前存下的绝对坐标 + 之后的显示器重排:反推不出有意义的比例,夹到 0~1
+ // 只会得到一个贴边的假位置,不如回退默认。
+ expect(initial({ x: 3000, y: 500, displayId: primary.id, updatedAt: 1 }, {
displays: [primary],
- size: SIZE,
- ...geometry,
- fallbackBounds,
- });
+ activeDisplay: primary,
+ })).toEqual(fallbackBounds);
+ });
+
+ it('同样场景下带比例的快照仍能还原记忆(这正是持久化比例的意义)', () => {
+ const result = initial({
+ x: 3000,
+ y: 500,
+ displayId: primary.id,
+ ratioX: 0.5,
+ ratioY: 0.86,
+ updatedAt: 1,
+ }, { displays: [primary], activeDisplay: primary });
+ const expectedX = primary.workArea.x + primary.workArea.width * 0.5 - WIDTH / 2;
+ expect(Math.abs(result.x - expectedX)).toBeLessThanOrEqual(1);
+ expect(result).not.toEqual(fallbackBounds);
+ });
+
+ it('旧坐标落进另一块屏时,归属屏认 displayId 而不认坐标落点', () => {
+ // 记忆存的是主屏(displayId 1)+ 比例 (0.25, 0.5),但显示器重排后旧坐标
+ // 落进了副屏范围。归属屏必须仍是主屏,且按比例还原到焦点屏(主屏)。
+ const result = initial({
+ x: secondary.workArea.x + 400,
+ y: secondary.workArea.y + 400,
+ displayId: primary.id,
+ ratioX: 0.25,
+ ratioY: 0.5,
+ updatedAt: 1,
+ }, { displays: [primary, secondary], activeDisplay: primary });
+ const expectedX = primary.workArea.x + primary.workArea.width * 0.25 - WIDTH / 2;
+ const expectedY = primary.workArea.y + primary.workArea.height * 0.5 - HEIGHT / 2;
+ expect(Math.abs(result.x - expectedX)).toBeLessThanOrEqual(1);
+ expect(Math.abs(result.y - expectedY)).toBeLessThanOrEqual(1);
+ });
+
+ it('同屏但坐标已被重排作废时按保存的比例还原,而不是用失效坐标', () => {
+ // 主屏 workArea 已右移,旧坐标 (100, 200) 不再落在它内部。
+ const movedPrimary: OverlayPlacementDisplay = {
+ id: primary.id,
+ workArea: { x: 2560, y: 0, width: 1920, height: 1055 },
+ };
+ const result = initial({
+ x: 100,
+ y: 200,
+ displayId: primary.id,
+ ratioX: 0.5,
+ ratioY: 0.8,
+ updatedAt: 1,
+ }, { displays: [movedPrimary], activeDisplay: movedPrimary });
+ const expectedX = movedPrimary.workArea.x + movedPrimary.workArea.width * 0.5 - WIDTH / 2;
+ const expectedY = movedPrimary.workArea.y + movedPrimary.workArea.height * 0.8 - HEIGHT / 2;
+ expect(Math.abs(result.x - expectedX)).toBeLessThanOrEqual(1);
+ expect(Math.abs(result.y - expectedY)).toBeLessThanOrEqual(1);
+ });
+
+ it('跨屏时保存的比例优先于按坐标反推的比例', () => {
+ const result = initial({
+ // 坐标反推会得到 (0.25, 0.5),但快照里明确记着 (0.8, 0.3)。
+ x: Math.round(primary.workArea.x + primary.workArea.width * 0.25 - WIDTH / 2),
+ y: Math.round(primary.workArea.y + primary.workArea.height * 0.5 - HEIGHT / 2),
+ displayId: primary.id,
+ ratioX: 0.8,
+ ratioY: 0.3,
+ updatedAt: 1,
+ }, { displays: [primary, secondary], activeDisplay: secondary });
+ const expectedX = secondary.workArea.x + secondary.workArea.width * 0.8 - WIDTH / 2;
+ expect(Math.abs(result.x - expectedX)).toBeLessThanOrEqual(1);
+ });
+
+ it('保存位置轻微越界时 clamp 回可见区域', () => {
+ const result = initial({ x: -200, y: 950, updatedAt: 1 }); // 中心仍在主屏内
expect(result.x).toBe(primary.workArea.x + EDGE_PADDING - CONTENT_INSET);
expect(result.y).toBe(primary.workArea.y + primary.workArea.height - HEIGHT - (EDGE_PADDING - CONTENT_INSET));
});
it('非有限坐标回退默认位置', () => {
- const result = resolveOverlayInitialBounds({
- savedPosition: { x: Number.NaN, y: 200, updatedAt: 1 },
- displays: [primary],
- size: SIZE,
- ...geometry,
- fallbackBounds,
- });
- expect(result).toEqual(fallbackBounds);
+ expect(initial({ x: Number.NaN, y: 200, updatedAt: 1 })).toEqual(fallbackBounds);
+ });
+
+ it('焦点屏就是保存位置所在屏时原样恢复', () => {
+ const saved = { x: 1920 + 300, y: 900, displayId: 2, updatedAt: 1 };
+ expect(initial(saved, { displays: [primary, secondary], activeDisplay: secondary }))
+ .toEqual({ x: saved.x, y: saved.y, width: WIDTH, height: HEIGHT });
+ });
+
+ it('焦点屏是另一块屏时,把保存位置按比例迁移过去', () => {
+ // 主屏上卡片中心在 workArea 的 (25%, 50%) 处。
+ const centerRatioX = 0.25;
+ const centerRatioY = 0.5;
+ const saved = {
+ x: Math.round(primary.workArea.x + primary.workArea.width * centerRatioX - WIDTH / 2),
+ y: Math.round(primary.workArea.y + primary.workArea.height * centerRatioY - HEIGHT / 2),
+ displayId: primary.id,
+ updatedAt: 1,
+ };
+ const result = initial(saved, { displays: [primary, secondary], activeDisplay: secondary });
+ // 保存位置本身是整数像素,比例换算会带 1px 以内的取整误差。
+ const expectedX = secondary.workArea.x + secondary.workArea.width * centerRatioX - WIDTH / 2;
+ const expectedY = secondary.workArea.y + secondary.workArea.height * centerRatioY - HEIGHT / 2;
+ expect(Math.abs(result.x - expectedX)).toBeLessThanOrEqual(1);
+ expect(Math.abs(result.y - expectedY)).toBeLessThanOrEqual(1);
+ });
+
+ it('迁移保留水平居中:主屏居中的记忆在副屏也居中', () => {
+ const saved = {
+ x: Math.round(primary.workArea.x + (primary.workArea.width - WIDTH) / 2),
+ y: 800,
+ displayId: primary.id,
+ updatedAt: 1,
+ };
+ const result = initial(saved, { displays: [primary, secondary], activeDisplay: secondary });
+ expect(result.x).toBe(Math.round(secondary.workArea.x + (secondary.workArea.width - WIDTH) / 2));
+ });
+
+ it('迁移到更小的屏时 clamp 进可见区域', () => {
+ const small: OverlayPlacementDisplay = {
+ id: 3,
+ workArea: { x: -1280, y: 0, width: 1280, height: 800 },
+ };
+ // 副屏上贴着右下角的记忆,迁到小屏后仍需留出 edgePadding。
+ const saved = {
+ x: secondary.workArea.x + secondary.workArea.width - WIDTH - (EDGE_PADDING - CONTENT_INSET),
+ y: secondary.workArea.y + secondary.workArea.height - HEIGHT - (EDGE_PADDING - CONTENT_INSET),
+ displayId: secondary.id,
+ updatedAt: 1,
+ };
+ const result = initial(saved, { displays: [secondary, small], activeDisplay: small });
+ expect(result.x).toBeLessThanOrEqual(
+ small.workArea.x + small.workArea.width - WIDTH - (EDGE_PADDING - CONTENT_INSET),
+ );
+ expect(result.y).toBeLessThanOrEqual(
+ small.workArea.y + small.workArea.height - HEIGHT - (EDGE_PADDING - CONTENT_INSET),
+ );
+ expect(result.x).toBeGreaterThanOrEqual(small.workArea.x + EDGE_PADDING - CONTENT_INSET);
+ });
+
+ it('拿不到焦点屏时退回保存位置所在屏(防御分支)', () => {
+ const saved = { x: 1920 + 300, y: 900, displayId: 2, updatedAt: 1 };
+ expect(initial(saved, { displays: [primary, secondary], activeDisplay: null }))
+ .toEqual({ x: saved.x, y: saved.y, width: WIDTH, height: HEIGHT });
+ });
+});
+
+describe('computeOverlayPositionRatio', () => {
+ it('按卡片中心算屏内相对比例', () => {
+ const bounds = {
+ x: Math.round(primary.workArea.x + primary.workArea.width * 0.25 - WIDTH / 2),
+ y: Math.round(primary.workArea.y + primary.workArea.height * 0.75 - HEIGHT / 2),
+ width: WIDTH,
+ height: HEIGHT,
+ };
+ const ratio = computeOverlayPositionRatio(bounds, primary.workArea);
+ expect(ratio.ratioX).toBeCloseTo(0.25, 3);
+ expect(ratio.ratioY).toBeCloseTo(0.75, 3);
+ });
+
+ it('中心在 workArea 之外时把比例夹进 0~1', () => {
+ const ratio = computeOverlayPositionRatio(
+ { x: -9999, y: 99999, width: WIDTH, height: HEIGHT },
+ primary.workArea,
+ );
+ expect(ratio.ratioX).toBe(0);
+ expect(ratio.ratioY).toBe(1);
+ });
+});
+
+describe('isBoundsCenterOnDisplay', () => {
+ it('中心落在现存屏幕内时为 true', () => {
+ expect(isBoundsCenterOnDisplay({ x: 100, y: 200, width: WIDTH, height: HEIGHT }, [primary]))
+ .toBe(true);
+ });
+
+ it('对应屏幕已拔掉时为 false', () => {
+ expect(isBoundsCenterOnDisplay(
+ { x: secondary.workArea.x + 300, y: 500, width: WIDTH, height: HEIGHT },
+ [primary],
+ )).toBe(false);
+ });
+});
+
+describe('normalizeFocusedWindowFrame', () => {
+ it('接受合法 frame', () => {
+ expect(normalizeFocusedWindowFrame({ x: 10, y: 20, width: 800, height: 600 }))
+ .toEqual({ x: 10, y: 20, width: 800, height: 600 });
+ });
+
+ it('负坐标合法(副屏在主屏左侧时窗口 x 为负)', () => {
+ expect(normalizeFocusedWindowFrame({ x: -1200, y: -30, width: 640, height: 480 }))
+ .toEqual({ x: -1200, y: -30, width: 640, height: 480 });
+ });
+
+ it('缺字段 / 非法值 / 零尺寸返回 null', () => {
+ expect(normalizeFocusedWindowFrame(null)).toBeNull();
+ expect(normalizeFocusedWindowFrame('frame')).toBeNull();
+ expect(normalizeFocusedWindowFrame({ x: 0, y: 0, width: 800 })).toBeNull();
+ expect(normalizeFocusedWindowFrame({ x: 0, y: 0, width: 0, height: 600 })).toBeNull();
+ expect(normalizeFocusedWindowFrame({ x: 0, y: 0, width: 800, height: -600 })).toBeNull();
+ expect(normalizeFocusedWindowFrame({ x: Number.NaN, y: 0, width: 800, height: 600 })).toBeNull();
});
});
describe('normalizeSavedOverlayPosition', () => {
it('接受合法快照', () => {
- expect(normalizeSavedOverlayPosition({ x: 1, y: 2, displayId: 3, updatedAt: 4 }))
- .toEqual({ x: 1, y: 2, displayId: 3, updatedAt: 4 });
+ expect(normalizeSavedOverlayPosition({ x: 1, y: 2, displayId: 3, ratioX: 0.5, ratioY: 0.8, updatedAt: 4 }))
+ .toEqual({ x: 1, y: 2, displayId: 3, ratioX: 0.5, ratioY: 0.8, updatedAt: 4 });
});
it('缺字段 / 非法值返回 null', () => {
@@ -207,6 +439,18 @@ describe('normalizeSavedOverlayPosition', () => {
it('displayId / updatedAt 非法时降级而不丢整条记录', () => {
expect(normalizeSavedOverlayPosition({ x: 1, y: 2, displayId: 'nope' }))
- .toEqual({ x: 1, y: 2, displayId: undefined, updatedAt: 0 });
+ .toEqual({ x: 1, y: 2, displayId: undefined, ratioX: undefined, ratioY: undefined, updatedAt: 0 });
+ });
+
+ it('旧快照没有比例字段时保持 undefined(由坐标反推)', () => {
+ expect(normalizeSavedOverlayPosition({ x: 1, y: 2, displayId: 3, updatedAt: 4 }))
+ .toEqual({ x: 1, y: 2, displayId: 3, ratioX: undefined, ratioY: undefined, updatedAt: 4 });
+ });
+
+ it('比例超出 0~1 或非有限数时丢弃该字段', () => {
+ expect(normalizeSavedOverlayPosition({ x: 1, y: 2, ratioX: 1.5, ratioY: -0.2, updatedAt: 4 }))
+ .toEqual({ x: 1, y: 2, displayId: undefined, ratioX: undefined, ratioY: undefined, updatedAt: 4 });
+ expect(normalizeSavedOverlayPosition({ x: 1, y: 2, ratioX: Number.NaN, ratioY: 0.5, updatedAt: 4 }))
+ .toEqual({ x: 1, y: 2, displayId: undefined, ratioX: undefined, ratioY: 0.5, updatedAt: 4 });
});
});
diff --git a/apps/desktop/src/main/voice-input/global.ts b/apps/desktop/src/main/voice-input/global.ts
index c2bbfb87d0..aad9c84a3a 100644
--- a/apps/desktop/src/main/voice-input/global.ts
+++ b/apps/desktop/src/main/voice-input/global.ts
@@ -37,6 +37,9 @@ import {
type MacInputMonitoringPermissionSnapshot,
} from './MacModifierShortcutListener.js';
import {
+ computeOverlayPositionRatio,
+ isBoundsCenterOnDisplay,
+ normalizeFocusedWindowFrame,
resolveDraggedOverlayBounds,
resolveOverlayInitialBounds,
type OverlayPlacementDisplay,
@@ -151,6 +154,11 @@ type MacTextInsertionHelperResult = {
afterNumberOfCharacters?: number;
enhancedAxAttempted?: boolean;
enhancedAxHelped?: boolean;
+ /** 流式进度行的事件名;命令的最终结果行没有这个字段。 */
+ event?: string;
+ /** 前台窗口 frame(DIP 屏幕坐标),进度行与最终结果行都会带。 */
+ frame?: unknown;
+ frameSource?: string;
};
const OVERLAY_QUERY = 'view=voice-input-overlay';
@@ -167,6 +175,9 @@ const OVERLAY_EDGE_PADDING = 24;
// 拖动时卡片中心距 workArea 水平中线小于该值即吸附到水平居中(灵动岛式,
// 第一版只做 X 轴中线吸附,不做四边吸附)。
const OVERLAY_SNAP_THRESHOLD_X = 48;
+// 多屏下等待「前台窗口在哪块屏」的上限。超时就用鼠标所在屏,宁可判定退化
+// 也不让浮窗出现明显延迟;答案迟到时不再挪窗,避免可见的跨屏跳动。
+const OVERLAY_FOCUSED_DISPLAY_DEADLINE_MS = 90;
const DICTIONARY_TOAST_QUERY = 'view=voice-input-dictionary-toast';
const DICTIONARY_TOAST_CARD_WIDTH = 360;
const DICTIONARY_TOAST_CARD_ESTIMATED_HEIGHT = 68;
@@ -228,6 +239,31 @@ let dictionaryToastCloseTimer: NodeJS.Timeout | null = null;
// 坐标一律由 main 从 screen.getCursorScreenPoint() 读取(DIP 坐标系),
// 避免 renderer screenX/screenY 在 Windows 缩放下的坐标系不一致问题。
let overlayDragSession: { startBounds: Rectangle; startCursor: Point } | null = null;
+// 最近一次「浮窗真正呈现在哪」的 bounds。浮窗 hide 后会被停到屏幕外,实时
+// bounds 不能当锚点,全局浮窗路径的词典 toast 靠这份记录跟到同一块屏、同一位置。
+let lastPresentedOverlayBounds: Rectangle | null = null;
+// 从「发布证据」交棒给「显示 toast」的锚点队列,一次性消费。
+//
+// 快照是在粘贴开始前拍的(见 pasteTextToFocusedTarget):那才是产生这条听写的浮窗
+// 现场。之后的粘贴 await、延迟轮询、模型往返期间用户都可能开新会话,锚点必须跟着
+// 来源会话走,并在显示时用呈现代次复核,否则旧会话的 toast 会盖在新浮窗上。
+//
+// 为什么不需要给每条证据编 ID:锚点的身份就是它的呈现代次。代次变过的锚点对任何
+// 请求都无效(那正是「期间又开过浮窗」),所以取用时直接丢弃过期的、拿代次仍匹配
+// 的那个——见 takeOverlayDictionaryToastAnchor()。
+const pendingDictionaryToastAnchors: DictionaryToastAnchor[] = [];
+// 队列只用于「刚发布、还没出 toast」的证据。renderer 侧若因功能开关未发起 advisor,
+// 对应锚点不会被取走,所以设上限丢最旧,避免无界增长。
+const DICTIONARY_TOAST_ANCHOR_MAX_ENTRIES = 8;
+// 浮窗呈现代次。焦点屏查询是异步的,它的回调必须能认出「这次呈现还算不算数」:
+// 会话被取消(hide / 复位到 idle)或已经开始了新一次呈现时,迟到的回调不得再
+// 定位或显示窗口——浮窗是缓存复用的,hide 并不销毁它,只靠 isDestroyed() 判断
+// 会让已取消的浮窗重新出现。
+let overlayPresentationSeq = 0;
+// 多屏下浮窗会先等最多 90ms 的焦点屏答案再显示。这段窗口里呈现已经开始(麦克风
+// 在录)但窗口还不可见,所以「浮窗是否已打开」不能只看 isVisible():否则等待期
+// 内再按一次快捷键不会走提交分支,而是又开一次呈现,用户那一下就丢了。
+let overlayPresentationAwaitingShow = false;
type ExternalDictionaryLearningWatch = {
id: string;
@@ -240,6 +276,12 @@ type ExternalDictionaryLearningWatch = {
timers: NodeJS.Timeout[];
completed: boolean;
inspecting: boolean;
+ /**
+ * 这次听写的浮窗现场,建 watch 时(刚粘贴完、浮窗刚收起)就拍下来。
+ * watch 会延迟轮询几十秒,期间用户可能已经在另一块屏开了新一次浮窗,所以锚点
+ * 必须跟着 watch 走,不能等发布证据时再去读进程级的「最近一次浮窗位置」。
+ */
+ toastAnchor: DictionaryToastAnchor | null;
pendingEdit?: {
editedText: string;
detectedAt: number;
@@ -252,6 +294,21 @@ export type DictionaryToastEntryPayload = {
term: string;
};
+/** 一次浮窗听写的「现场」:浮窗当时的位置 + 当时的呈现代次。 */
+export type DictionaryToastAnchor = {
+ bounds: Rectangle;
+ presentationSeq: number;
+};
+
+type DictionaryToastPayload = {
+ entries: DictionaryToastEntryPayload[];
+ /**
+ * 非 null = 该 toast 来自全局浮窗听写,且已绑定产生它的那次浮窗现场,
+ * 显示时贴着那个位置出现(仍要过呈现代次与屏幕存在性复核)。
+ */
+ anchor: DictionaryToastAnchor | null;
+};
+
const EXTERNAL_DICTIONARY_LEARNING_POLL_DELAYS_MS = [2500, 6500, 14000];
// Base probes catch the common "edit shortly after paste" path. Once an edit is
// observed, mirror Typeless' strategy: keep watching and reset a single 15s
@@ -301,7 +358,17 @@ export function prewarmGlobalVoiceInputOverlay(): void {
}
export function isGlobalVoiceInputOverlayVisible(): boolean {
- return Boolean(overlayPresentationActive && getOverlayWindow()?.isVisible());
+ return isOverlayPresentationOpen(getOverlayWindow());
+}
+
+/**
+ * 一次浮窗呈现是否处于「已打开」状态:呈现生效,且窗口已可见或正等着显示。
+ * 快捷键的提交分支、Dock 激活让位判断都必须用这个,而不是裸 isVisible()。
+ */
+function isOverlayPresentationOpen(overlay: BrowserWindow | null): boolean {
+ if (!overlay || overlay.isDestroyed()) return false;
+ if (!overlayPresentationActive) return false;
+ return overlay.isVisible() || overlayPresentationAwaitingShow;
}
/**
@@ -568,10 +635,14 @@ export function registerGlobalVoiceInputIpc(): void {
// 走 positionOverlayWindow 的记忆优先路径。
const bounds = window.getBounds();
const display = screen.getDisplayMatching(bounds);
+ lastPresentedOverlayBounds = bounds;
voiceInputOverlayPositionStore.save({
x: bounds.x,
y: bounds.y,
displayId: display?.id,
+ // 同时存屏内相对比例:显示器重排后绝对坐标会失效,比例仍能还原用户
+ // 当时把浮窗放在这块屏的哪个位置。
+ ...(display ? computeOverlayPositionRatio(bounds, display.workArea) : {}),
updatedAt: Date.now(),
});
log.debug('global overlay drag position saved', { x: bounds.x, y: bounds.y });
@@ -582,9 +653,12 @@ export function registerGlobalVoiceInputIpc(): void {
if (window && event.sender === window.webContents) {
overlayDragSession = null;
voiceInputOverlayPositionStore.clear();
- const cursorPoint = screen.getCursorScreenPoint();
- const display = screen.getDisplayNearestPoint(cursorPoint);
- window.setBounds(computeOverlayBounds(display));
+ // 复位到「浮窗当前所在这块屏」的默认位置:双击复位时浮窗已经在用户眼前,
+ // 不该因为鼠标所在屏判定跑到另一块屏上去。
+ const display = screen.getDisplayMatching(window.getBounds());
+ const bounds = computeOverlayBounds(display);
+ lastPresentedOverlayBounds = bounds;
+ window.setBounds(bounds);
log.debug('global overlay position reset to default');
}
return { ok: true };
@@ -658,7 +732,8 @@ export function registerGlobalVoiceInputIpc(): void {
(_event, payload: unknown): { ok: true } | { ok: false; error: string } => {
const entries = normalizeDictionaryToastEntries(payload);
if (entries.length === 0) return { ok: false, error: 'Dictionary toast payload is incomplete.' };
- showDictionaryToastWindow({ entries });
+ // Renderer 侧(应用内听写)触发的 toast 与全局浮窗位置无关。
+ showDictionaryToastWindow({ entries, anchor: null });
return { ok: true };
},
);
@@ -837,13 +912,14 @@ function stableVoiceInputShortcutKey(shortcut: VoiceInputShortcut): string {
function handleGlobalVoiceInputShortcut(phase?: Extract<GlobalVoiceInputShortcutPhase, 'start'>): void {
const invokedAt = Date.now();
const overlay = getOverlayWindow();
- const overlayOpen = Boolean(overlay && overlayPresentationActive && overlay.isVisible());
+ const overlayOpen = isOverlayPresentationOpen(overlay);
log.debug('global shortcut invoked', {
overlayOpen,
overlayVisible: Boolean(overlay?.isVisible()),
+ overlayAwaitingShow: overlayPresentationAwaitingShow,
appFocused: Boolean(BrowserWindow.getFocusedWindow()),
});
- if (overlay && overlayPresentationActive && overlay.isVisible()) {
+ if (overlay && overlayOpen) {
if (phase === 'start') {
pendingModifierOverlaySuppressNextTap = false;
pendingModifierOverlaySuppressNextRelease = true;
@@ -891,7 +967,7 @@ function handleGlobalVoiceInputShortcutTap(): void {
}
if (sendShortcutToActiveInlineVoiceInput('tap')) return;
const overlay = getOverlayWindow();
- if (overlay && overlayPresentationActive && overlay.isVisible()) {
+ if (overlay && isOverlayPresentationOpen(overlay)) {
overlay.webContents.send('voice-input:global-overlay-command', { type: 'submit' });
return;
}
@@ -1119,6 +1195,9 @@ function destroyOverlayWindow(): void {
overlayWindow = null;
overlayLoaded = false;
overlayPresentationActive = false;
+ // 同 setOverlayIdlePresentationState:作废本次呈现,pending 的异步定位回调失效。
+ overlayPresentationSeq += 1;
+ overlayPresentationAwaitingShow = false;
pendingOverlayStart = null;
pendingModifierOverlaySubmit = false;
pendingModifierOverlaySuppressNextTap = false;
@@ -1136,6 +1215,9 @@ function destroyOverlayWindow(): void {
function setOverlayIdlePresentationState(window: BrowserWindow): void {
if (window.isDestroyed()) return;
overlayPresentationActive = false;
+ // 作废本次呈现:pending 的焦点屏回调据此放弃定位与显示。
+ overlayPresentationSeq += 1;
+ overlayPresentationAwaitingShow = false;
// `show: false` at BrowserWindow construction is not enough on macOS: a
// prewarmed native window can still be unhidden when the app is activated by
// a normal menu shortcut such as Cmd+,. Park the warm cache outside visible
@@ -1196,7 +1278,10 @@ function unregisterOverlayCancelShortcut(): void {
async function showOverlayWindow(shortcutInvokedAt = Date.now()): Promise<void> {
const existing = getOverlayWindow();
- if (existing?.isVisible()) {
+ // 第一个条件是原有行为(窗口已可见就提交);第二个补上「呈现已开始、正等着
+ // 显示」这段窗口,否则等待期内的第二次按键会再开一次呈现,renderer 收到重复
+ // start 会忽略,用户那一下等于丢了。
+ if (existing && (existing.isVisible() || isOverlayPresentationOpen(existing))) {
existing.webContents.send('voice-input:global-overlay-command', { type: 'submit' });
return;
}
@@ -1214,9 +1299,8 @@ async function showOverlayWindow(shortcutInvokedAt = Date.now()): Promise<void>
}
function createOverlayWindow(shortcutInvokedAt: number): BrowserWindow {
- const cursorPoint = screen.getCursorScreenPoint();
- const display = screen.getDisplayNearestPoint(cursorPoint);
- const bounds = computeOverlayBounds(display);
+ // 建窗时的 bounds 只是占位:真正的定位在 positionOverlayWindow 里按焦点屏做。
+ const bounds = computeOverlayBounds(getCursorDisplay());
// The global voice overlay behaves like an input-method candidate panel:
// visible above other apps, not part of normal app switching, and not allowed
// to take over the text field that will receive the paste.
@@ -1342,7 +1426,16 @@ function normalizeDictionaryToastEntries(payload: unknown): DictionaryToastEntry
.slice(0, DICTIONARY_TOAST_MAX_ENTRIES);
}
-function showDictionaryToastWindow(payload: { entries: DictionaryToastEntryPayload[] }): void {
+function showDictionaryToastWindow(payload: DictionaryToastPayload): void {
+ // 有浮窗正在呈现(用户正在录音)时不弹 toast。toast 是 alwaysOnTop 的,且它的默认
+ // 位置就是浮窗的默认位置——旧会话的建议迟到时退回默认位置,恰好会盖住正在录音的
+ // 新浮窗五秒。词条本身已经落库,这个提示不重要到值得挡住用户的操作界面。
+ if (isOverlayPresentationOpen(getOverlayWindow())) {
+ log.debug('dictionary toast suppressed: overlay presentation is open', {
+ entries: payload.entries.length,
+ });
+ return;
+ }
closeDictionaryToastWindow();
const window = createDictionaryToastWindow(payload);
dictionaryToastWindow = window;
@@ -1351,15 +1444,26 @@ function showDictionaryToastWindow(payload: { entries: DictionaryToastEntryPaylo
}, DICTIONARY_TOAST_DURATION_MS);
}
-export function showVoiceInputDictionaryToast(entries: DictionaryToastEntryPayload[]): void {
+/**
+ * `anchor` 只应由全局浮窗那条听写链路传(用 `takeOverlayDictionaryToastAnchor()`
+ * 在请求到达时取得)。应用内听写不传:它的 toast 不能借用浮窗位置,用户可能在另一
+ * 块屏的 Cindy 窗口里操作,甚至浮窗那块屏早已拔掉。
+ */
+export function showVoiceInputDictionaryToast(
+ entries: DictionaryToastEntryPayload[],
+ options?: { anchor?: DictionaryToastAnchor | null },
+): void {
if (entries.length === 0) return;
- showDictionaryToastWindow({ entries });
+ showDictionaryToastWindow({
+ entries,
+ anchor: options?.anchor ?? null,
+ });
}
-function createDictionaryToastWindow(payload: { entries: DictionaryToastEntryPayload[] }): BrowserWindow {
- const cursorPoint = screen.getCursorScreenPoint();
- const display = screen.getDisplayNearestPoint(cursorPoint);
- const bounds = computeDictionaryToastBounds(display);
+function createDictionaryToastWindow(payload: DictionaryToastPayload): BrowserWindow {
+ const bounds = computeDictionaryToastBounds(
+ resolveDictionaryToastAnchorBounds(payload.anchor),
+ );
const window = new BrowserWindow({
...bounds,
frame: false,
@@ -1429,14 +1533,56 @@ function createDictionaryToastWindow(payload: { entries: DictionaryToastEntryPay
function startLoadedOverlaySession(window: BrowserWindow, shortcutInvokedAt: number): void {
if (window.isDestroyed()) return;
- positionOverlayWindow(window);
- prepareOverlayForDisplay(window);
-
+ const presentationSeq = ++overlayPresentationSeq;
// Startup ordering is intentional:
- // 1. Capture the paste target before showing the overlay.
+ // 1. Capture the paste target before showing the overlay. 这一次调用同时带回
+ // 前台窗口 frame,焦点屏由它派生——和 target 同一次 frontmostApplication
+ // 读取,不会出现「浮窗开在 A 屏、粘贴却进了 B 屏的 App」。
// 2. Tell the renderer to start microphone capture as soon as it is ready.
// 3. Show the overlay on the next tick so UI display no longer gates mic start.
- const captureOverlayPromise = captureMacPasteTarget();
+ //
+ // frame 走流式:helper 读到就单独吐一行,不必等后面的 AX 上下文采集,所以 90ms 的
+ // 选屏截止时间才有意义。helper 会吐两条——先是便宜有界的 CGWindowList(z-order
+ // 近似,一定赶得上截止线),再是权威但可能超时的 AX kAXFocusedWindow。这里保留
+ // 「当前最好的一条」,AX 到了就立刻放行,没到就用已经到手的近似值。
+ //
+ // 要不要采集 frame 在 spawn 之前就定:单屏(或非 macOS)下答案改变不了落屏结果,
+ // 就不让 helper 去读——AX 慢的目标 App 里那几次读取会白白推迟粘贴目标采集。
+ let bestFocusedWindowFrame: Rectangle | null = null;
+ let hasAuthoritativeFrame = false;
+ let resolvePreferredFrame: () => void = () => {};
+ const preferredFrameArrived = new Promise<void>((resolve) => {
+ resolvePreferredFrame = resolve;
+ });
+ const wantsFocusedDisplay = shouldResolveFocusedDisplay();
+ const captureOverlayPromise = captureMacPasteTarget(
+ wantsFocusedDisplay
+ ? {
+ onFocusedWindowFrame: (frame, source) => {
+ if (!frame || hasAuthoritativeFrame) return;
+ bestFocusedWindowFrame = frame;
+ if (source !== 'ax') return;
+ // AX 是权威答案,到了就不再等,也不再被后续行覆盖。
+ hasAuthoritativeFrame = true;
+ resolvePreferredFrame();
+ },
+ }
+ : undefined,
+ );
+ // 兜底:helper 一条 frame 都没吐(AX 与 CGWindowList 都没结果)、走了 osascript
+ // 回退,或整个 capture 失败时,用最终结果收敛,别让选屏一直等到截止线。
+ void captureOverlayPromise
+ .then((captured) => {
+ if (!hasAuthoritativeFrame && captured?.frame) bestFocusedWindowFrame = captured.frame;
+ resolvePreferredFrame();
+ })
+ .catch(() => resolvePreferredFrame());
+ const focusedDisplayQuery = wantsFocusedDisplay
+ ? startFocusedDisplayQuery(preferredFrameArrived, () => bestFocusedWindowFrame)
+ : null;
+ positionOverlayWindow(window);
+ prepareOverlayForDisplay(window);
+
overlayPasteTarget = null;
overlayPasteContext = null;
overlayPasteTargetPromise = captureOverlayPromise.then((captured) => captured?.target ?? null);
@@ -1472,27 +1618,73 @@ function startLoadedOverlaySession(window: BrowserWindow, shortcutInvokedAt: num
if (pendingModifierOverlaySubmit) {
pendingModifierOverlaySubmit = false;
setImmediate(() => {
- if (!window.isDestroyed() && overlayPresentationActive) {
- window.webContents.send('voice-input:global-overlay-command', { type: 'submit' });
+ // 同 show():这条延迟提交也必须绑定呈现代次。窗口是跨会话复用的,
+ // overlayPresentationActive 是进程级状态,取消后紧接着重启会让它重新为
+ // true,届时旧会话的回调会把刚开始录音的新会话直接提交掉。
+ if (!isCurrentOverlayPresentation(window, presentationSeq)) {
+ log.debug('pending modifier submit dropped: presentation no longer current');
+ return;
}
+ window.webContents.send('voice-input:global-overlay-command', { type: 'submit' });
});
}
- setImmediate(() => {
- if (window.isDestroyed()) return;
+ const show = (): void => {
+ // 两条路径(单屏的 setImmediate、多屏的等待回调)都要过这道校验:显示总是
+ // 延后至少一个 tick,期间用户可能已经取消。取消只让缓存窗口进 idle、不销毁,
+ // 所以只查 isDestroyed() 会让已取消的浮窗重新出现。
+ if (!isCurrentOverlayPresentation(window, presentationSeq)) {
+ log.debug('global overlay show skipped: presentation no longer current');
+ return;
+ }
log.debug('global overlay ready to show', {
elapsedSinceShortcutMs: Date.now() - shortcutInvokedAt,
});
+ overlayPresentationAwaitingShow = false;
window.showInactive();
// showInactive preserves the user's focused app, but some Electron/macOS
// combinations can still perturb app-level presence. Restore immediately
// after showing without focusing the main app.
scheduleMainAppPresenceRestore('global-voice-overlay-shown');
+ };
+ if (!focusedDisplayQuery) {
+ setImmediate(show);
+ return;
+ }
+ // 多屏:先等一小会儿焦点屏答案,拿到就在显示前重新定位。窗口此刻还没可见,
+ // 所以重定位不会被看成跳动;超时则维持鼠标所在屏的定位直接显示。
+ // 这段等待期里呈现已经算「打开」(麦克风在录),见 overlayPresentationAwaitingShow。
+ overlayPresentationAwaitingShow = true;
+ void focusedDisplayQuery.then((focusedDisplay) => {
+ if (!isCurrentOverlayPresentation(window, presentationSeq)) {
+ // 等待期间用户取消了浮窗、或者已经开始了新一次呈现:这次的答案作废。
+ log.debug('focused display result dropped: overlay presentation no longer current');
+ return;
+ }
+ if (focusedDisplay) positionOverlayWindow(window, focusedDisplay);
+ show();
});
}
+/** 判断一次异步定位结果是否还属于「当前这次浮窗呈现」。 */
+function isCurrentOverlayPresentation(window: BrowserWindow, presentationSeq: number): boolean {
+ return overlayPresentationSeq === presentationSeq
+ && overlayPresentationActive
+ && overlayWindow === window
+ && !window.isDestroyed();
+}
+
function showPassiveOverlayWindow(window: BrowserWindow): void {
if (window.isDestroyed()) return;
- positionOverlayWindow(window);
+ // 被动呈现走的是「启动失败 / 粘贴失败后把浮窗重新亮出来」,属于同一次会话的延续,
+ // 必须留在它刚才所在的位置:这时重新按鼠标所在屏定位,会让错误提示从用户正在用的
+ // 那块屏跳到鼠标那块屏。浮窗 hide 后被停到屏幕外,所以用最近一次实际呈现的 bounds,
+ // 那块屏已经不存在时才退回默认定位。
+ const previousBounds = lastPresentedOverlayBounds;
+ if (previousBounds && isBoundsCenterOnDisplay(previousBounds, getOverlayPlacementDisplays())) {
+ window.setBounds(previousBounds);
+ } else {
+ positionOverlayWindow(window);
+ }
registerOverlayCancelShortcut();
window.setAlwaysOnTop(true, 'floating');
window.setVisibleOnAllWorkspaces(true, {
@@ -1504,19 +1696,91 @@ function showPassiveOverlayWindow(window: BrowserWindow): void {
scheduleMainAppPresenceRestore('global-voice-overlay-passive-shown');
}
-function positionOverlayWindow(window: BrowserWindow): void {
- const cursorPoint = screen.getCursorScreenPoint();
- const display = screen.getDisplayNearestPoint(cursorPoint);
- // 记忆优先:用户拖动过就用保存位置(clamp 进现存屏幕可见区域),保存
- // 位置所在屏幕已不存在或从未拖动过则回退鼠标所在屏幕的默认位置。
- window.setBounds(resolveOverlayInitialBounds({
+/**
+ * 把浮窗定位到焦点屏。`display` 省略时退回鼠标所在屏。
+ *
+ * 屏内位置沿用「记忆优先」:用户拖动过就用保存位置(clamp 进可见区域),
+ * 保存位置在别的屏上时按相对比例迁移过来,从未拖动过则用该屏默认位置。
+ */
+function positionOverlayWindow(window: BrowserWindow, display = getCursorDisplay()): void {
+ const displays = getOverlayPlacementDisplays();
+ const bounds = resolveOverlayInitialBounds({
savedPosition: voiceInputOverlayPositionStore.read(),
- displays: getOverlayPlacementDisplays(),
+ displays,
+ activeDisplay: displays.find((candidate) => candidate.id === display.id) ?? null,
size: { width: OVERLAY_WIDTH, height: OVERLAY_HEIGHT },
contentInset: OVERLAY_SHADOW_PADDING,
edgePadding: OVERLAY_EDGE_PADDING,
fallbackBounds: computeOverlayBounds(display),
- }));
+ });
+ lastPresentedOverlayBounds = bounds;
+ window.setBounds(bounds);
+}
+
+function getCursorDisplay(): Display {
+ return screen.getDisplayNearestPoint(screen.getCursorScreenPoint());
+}
+
+/**
+ * 是否值得去问「前台窗口在哪块屏」。false 时既不采集 frame 也不推迟显示,直接用
+ * 鼠标所在屏:
+ * - 只有一块屏时答案唯一;
+ * - 非 macOS 平台没有可用的低成本前台窗口查询(Electron 只能看自己的窗口),
+ * Windows 一律按鼠标所在屏判定。
+ */
+function shouldResolveFocusedDisplay(): boolean {
+ if (process.platform !== 'darwin') return false;
+ return screen.getAllDisplays().length > 1;
+}
+
+/**
+ * 把前台窗口 frame 换算成「焦点屏」,并给它加显示截止时间。
+ *
+ * `preferredFrameArrived` 在权威答案(AX kAXFocusedWindow)到达、或 capture 整体
+ * 收敛时兑现;截止线到了就用 `readBestFrame()` 当时已有的最好答案(通常是先到的
+ * CGWindowList 近似值),而不是干脆放弃——放弃就退回鼠标所在屏,恰恰是本功能要修的
+ * 那个错。两者都没有才返回 null。
+ *
+ * 注意鼠标所在屏和键盘焦点所在屏可以不同:鼠标停在 A 屏、正在 B 屏的编辑器里打字时,
+ * 粘贴目标在 B 屏,浮窗也应该开在 B 屏,所以这里优先认前台窗口。
+ */
+function startFocusedDisplayQuery(
+ preferredFrameArrived: Promise<void>,
+ readBestFrame: () => Rectangle | null,
+): Promise<Display | null> {
+ const startedAt = Date.now();
+ return new Promise((resolve) => {
+ let settled = false;
+ const settle = (timedOut: boolean): void => {
+ if (settled) return;
+ settled = true;
+ const frame = readBestFrame();
+ if (!frame) {
+ log.debug('focused display unresolved, falling back to cursor display', {
+ elapsedMs: Date.now() - startedAt,
+ timedOut,
+ });
+ resolve(null);
+ return;
+ }
+ // getDisplayMatching 按重叠面积选屏,跨屏摆放的窗口也能落到主要那块。
+ const display = screen.getDisplayMatching(frame);
+ log.debug('focused display resolved', {
+ elapsedMs: Date.now() - startedAt,
+ displayId: display?.id,
+ // true = 没等到 AX 权威答案,用的是先到的近似 frame。
+ timedOut,
+ });
+ resolve(display ?? null);
+ };
+ const timer = setTimeout(() => settle(true), OVERLAY_FOCUSED_DISPLAY_DEADLINE_MS);
+ void preferredFrameArrived
+ .catch(() => undefined)
+ .then(() => {
+ clearTimeout(timer);
+ settle(false);
+ });
+ });
}
function getOverlayPlacementDisplays(): OverlayPlacementDisplay[] {
@@ -1539,8 +1803,32 @@ function computeOverlayBounds(display: Display): Rectangle {
return { x, y, width: OVERLAY_WIDTH, height: OVERLAY_HEIGHT };
}
-function computeDictionaryToastBounds(display: Display): Rectangle {
- const overlayBounds = computeOverlayBounds(display);
+/**
+ * 全局浮窗听写的词典 toast 贴着「产生它的那次浮窗所在的位置」出现。浮窗 hide 后会
+ * 被停到屏幕外的 OVERLAY_IDLE_BOUNDS,实时 bounds 不能当锚点,所以用粘贴前拍下、
+ * 请求到达时按序绑定的快照(见 pendingDictionaryToastAnchors)。
+ *
+ * 三个条件都满足才用它,否则退回鼠标所在屏的默认位置:
+ * - 调用方是全局浮窗链路并带来了自己那次会话的锚点(应用内听写不传);
+ * - 呈现代次没变——变了说明期间又开过浮窗,这条 toast 会盖在新浮窗上;
+ * - 锚点中心仍落在某块现存屏幕上——否则外接屏拔掉后 toast 会整个落到屏幕外。
+ *
+ * 注意「退回默认位置」本身不足以避免遮挡:默认位置就是浮窗的默认位置。真正在录音
+ * 时的遮挡由 showDictionaryToastWindow() 的「有浮窗呈现就不弹」拦掉。
+ */
+function resolveDictionaryToastAnchorBounds(anchor: DictionaryToastAnchor | null): Rectangle {
+ if (!anchor) return computeOverlayBounds(getCursorDisplay());
+ if (anchor.presentationSeq === overlayPresentationSeq
+ && isBoundsCenterOnDisplay(anchor.bounds, getOverlayPlacementDisplays())) {
+ return anchor.bounds;
+ }
+ log.debug('dictionary toast anchor dropped', {
+ staleSession: anchor.presentationSeq !== overlayPresentationSeq,
+ });
+ return computeOverlayBounds(getCursorDisplay());
+}
+
+function computeDictionaryToastBounds(overlayBounds: Rectangle): Rectangle {
return {
x: Math.round(overlayBounds.x + (overlayBounds.width - DICTIONARY_TOAST_WIDTH) / 2),
y: Math.round(overlayBounds.y + (overlayBounds.height - DICTIONARY_TOAST_HEIGHT) / 2),
@@ -1550,6 +1838,10 @@ function computeDictionaryToastBounds(display: Display): Rectangle {
}
async function pasteTextToFocusedTarget(text: string, rawTranscriptText?: string): Promise<void> {
+ // 词典 toast 锚点必须在这里、任何 await 之前拍:renderer 已经把浮窗收起并让粘贴
+ // 在后台跑,用户完全可以在 pasteTextToMacTarget() 返回前开下一次会话。等到建 watch
+ // 时再读 lastPresentedOverlayBounds / 呈现代次,拿到的就是新会话的现场了。
+ const toastAnchor = captureOverlayToastAnchor();
const pasteTarget = await resolveOverlayPasteTarget();
log.debug(PASTE_DEBUG_TAG, 'paste start', {
chars: text.length,
@@ -1558,7 +1850,7 @@ async function pasteTextToFocusedTarget(text: string, rawTranscriptText?: string
});
if (process.platform === 'darwin') {
await pasteTextToMacTarget(text, pasteTarget);
- scheduleExternalDictionaryLearningWatch(text, rawTranscriptText, pasteTarget, overlayPasteContext);
+ scheduleExternalDictionaryLearningWatch(text, rawTranscriptText, pasteTarget, overlayPasteContext, toastAnchor);
return;
}
@@ -1774,22 +2066,58 @@ function scheduleClipboardRestore(snapshot: ClipboardSnapshot | null, expectedTe
type CapturedOverlayTarget = {
target: MacPasteTarget;
context: MacPasteContext | null;
+ /**
+ * 前台窗口 frame(DIP 屏幕坐标),来自与 target 同一次 helper 调用、同一次
+ * frontmostApplication 读取,所以「浮窗开在哪块屏」与「粘贴进哪个 App」不会
+ * 各自认到不同的前台 App。osascript 兜底路径拿不到 frame。
+ */
+ frame: Rectangle | null;
};
-async function captureMacPasteTarget(): Promise<CapturedOverlayTarget | null> {
+/**
+ * `onFocusedWindowFrame` 会在 helper 吐出前台窗口 frame 行时立刻回调——远早于整个
+ * capture 完成(AX 上下文采集在 Chromium 系编辑器里可能要几百毫秒)。浮窗选屏只等
+ * 这些行,所以不能等最终结果。
+ *
+ * helper 会吐两条:`window-list`(便宜有界的 z-order 近似)和 `ax`(权威的
+ * kAXFocusedWindow,可能超时)。`source` 原样透传,由调用方决定取舍。
+ */
+async function captureMacPasteTarget(
+ options?: { onFocusedWindowFrame?: (frame: Rectangle | null, source: string) => void },
+): Promise<CapturedOverlayTarget | null> {
if (process.platform !== 'darwin') return null;
+ const onFocusedWindowFrame = options?.onFocusedWindowFrame;
try {
- const helperResult = await runMacTextInsertionHelper(['--command', 'capture-target']);
+ // 只有真要用 frame 时才让 helper 去读它:AX 慢的目标 App 里 focusedWindow /
+ // position / size 三次请求各自可能吃满 200ms messaging timeout,而单屏下这个答案
+ // 根本改变不了落屏结果,白白推迟粘贴目标采集。
+ const args = ['--command', 'capture-target'];
+ if (onFocusedWindowFrame) args.push('--with-focused-frame');
+ const helperResult = await runMacTextInsertionHelper(args, {
+ onProgress: onFocusedWindowFrame
+ ? (event) => {
+ if (event.event !== 'focused-window-frame') return;
+ onFocusedWindowFrame(
+ normalizeFocusedWindowFrame(event.frame),
+ typeof event.frameSource === 'string' ? event.frameSource : 'unknown',
+ );
+ }
+ : undefined,
+ });
if (helperResult.ok && helperResult.target?.processName) {
+ const frame = normalizeFocusedWindowFrame(helperResult.frame);
log.debug(PASTE_DEBUG_TAG, 'capture target result (native)', {
target: describePasteTarget(helperResult.target),
context: summarizePasteContext(helperResult.context),
enhancedAxAttempted: Boolean(helperResult.enhancedAxAttempted),
enhancedAxHelped: Boolean(helperResult.enhancedAxHelped),
+ hasFocusedWindowFrame: Boolean(frame),
+ frameSource: helperResult.frameSource,
});
return {
target: helperResult.target,
context: helperResult.context ?? null,
+ frame,
};
}
} catch (error) {
@@ -1831,6 +2159,8 @@ async function captureMacPasteTarget(): Promise<CapturedOverlayTarget | null> {
return {
target: { processName, bundleId: bundleId ?? '', pid },
context: null,
+ // osascript 只报前台 App,不报窗口几何:焦点屏退回鼠标所在屏。
+ frame: null,
};
} catch (error) {
log.warn('capture paste target failed', { error: stringifyError(error) });
@@ -1843,6 +2173,7 @@ function scheduleExternalDictionaryLearningWatch(
rawTranscriptText: string | undefined,
target: MacPasteTarget | null,
context: MacPasteContext | null,
+ toastAnchor: DictionaryToastAnchor | null,
): void {
if (process.platform !== 'darwin') return;
cancelExternalDictionaryLearningWatch();
@@ -1875,6 +2206,7 @@ function scheduleExternalDictionaryLearningWatch(
timers: [],
completed: false,
inspecting: false,
+ toastAnchor,
};
externalDictionaryLearningWatch = watch;
EXTERNAL_DICTIONARY_LEARNING_POLL_DELAYS_MS.forEach((delayMs) => {
@@ -2134,7 +2466,7 @@ function finalizePendingExternalDictionaryLearningEdit(
selectedText: originalContext.selectedText,
selectionAfter: originalContext.selectionAfter,
},
- });
+ }, watch.toastAnchor);
log.debug('external dictionary learning pending evidence finalized', {
target: describePasteTarget(watch.target),
triggerReason,
@@ -2195,6 +2527,8 @@ async function captureMacPasteTargetForLearning(
return {
target: helperResult.target,
context: helperResult.context,
+ // 词典学习只关心文本上下文,不需要窗口几何(浮窗此时早已关掉)。
+ frame: null,
};
} catch (error) {
log.debug('external dictionary learning capture failed', {
@@ -2238,12 +2572,49 @@ function isSameMacPasteTarget(lhs: MacPasteTarget, rhs: MacPasteTarget): boolean
function publishExternalDictionaryLearningEvidence(
evidence: Pick<DictationDictionaryAdviceInput, 'source' | 'rawTranscriptText' | 'beforeText' | 'afterText' | 'context'>,
+ toastAnchor: DictionaryToastAnchor | null,
): void {
const window = getOverlayWindow();
if (!window || window.isDestroyed()) return;
+ // 锚点是粘贴开始前拍的(那才是这条证据对应的浮窗现场),这里排进队列,等这条
+ // 证据的建议请求到达 main 时按到达顺序取走。几何值不进 IPC payload:证据要经
+ // renderer 往返,renderer 传回的坐标属于不可信输入。
+ if (toastAnchor) {
+ pendingDictionaryToastAnchors.push(toastAnchor);
+ while (pendingDictionaryToastAnchors.length > DICTIONARY_TOAST_ANCHOR_MAX_ENTRIES) {
+ pendingDictionaryToastAnchors.shift();
+ }
+ }
window.webContents.send('voice-input:dictionary-learning-evidence', { evidence });
}
+/** 拍下「当前这次浮窗现场」,供之后给它的词典 toast 定位。 */
+function captureOverlayToastAnchor(): DictionaryToastAnchor | null {
+ if (!lastPresentedOverlayBounds) return null;
+ return { bounds: lastPresentedOverlayBounds, presentationSeq: overlayPresentationSeq };
+}
+
+/**
+ * 取走属于「当前这次浮窗呈现」的 toast 锚点,绑定给这一次词典建议请求。
+ *
+ * 身份靠呈现代次,不靠队列位置:代次已经变过的锚点无论给谁都过不了
+ * resolveDictionaryToastAnchorBounds() 的复核(那正是「期间又开过浮窗」的定义),
+ * 所以这里遇到就直接丢弃,继续找代次仍匹配的那个。这样两种情况都不会错位:
+ * - 旧会话的建议迟到(此时已开过新浮窗)→ 它的锚点已过期,取不到,走默认位置;
+ * - renderer 因功能开关没发起请求,锚点留在队列里 → 下次请求会把它当过期丢掉,
+ * 拿到自己那份,不会一直错位一格。
+ *
+ * 必须在请求刚到达、任何 await 之前调用(代次此刻才代表这次请求的来源会话)。
+ * 应用内听写不要调用它。
+ */
+export function takeOverlayDictionaryToastAnchor(): DictionaryToastAnchor | null {
+ while (pendingDictionaryToastAnchors.length > 0) {
+ const candidate = pendingDictionaryToastAnchors.shift();
+ if (candidate && candidate.presentationSeq === overlayPresentationSeq) return candidate;
+ }
+ return null;
+}
+
// Length-only summary for normal diagnostics. Full text debug is isolated in
// externalDictionaryLearningTextDebug() and gated to dev builds while the
// automatic dictionary learner is being tuned.
@@ -2326,17 +2697,29 @@ function macTextInsertionTargetArgs(pasteTarget: MacPasteTarget): string[] {
return args;
}
+/**
+ * helper 可以在最终结果之前先流式吐出若干「进度行」(每行一个 JSON,带 `event`
+ * 字段),最后一行才是命令结果。`onProgress` 会在进度行到达时同步回调;只有传了
+ * 它才走 spawn 逐行读取,其余调用保持原来的 execFile 缓冲路径。
+ */
async function runMacTextInsertionHelper(
args: string[],
- options?: { input?: string; timeoutMs?: number },
+ options?: {
+ input?: string;
+ timeoutMs?: number;
+ onProgress?: (event: MacTextInsertionHelperResult) => void;
+ },
): Promise<MacTextInsertionHelperResult> {
const helperPath = await resolveMacTextInsertionHelperPath();
- const stdout = await execFilePromise(helperPath, args, 'Could not run macOS text insertion helper.', {
- timeoutMs: options?.timeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS,
- input: options?.input,
- });
+ const timeoutMs = options?.timeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS;
+ const stdout = options?.onProgress
+ ? await spawnHelperWithProgressPromise(helperPath, args, timeoutMs, options.onProgress)
+ : await execFilePromise(helperPath, args, 'Could not run macOS text insertion helper.', {
+ timeoutMs,
+ input: options?.input,
+ });
try {
- return JSON.parse(stdout) as MacTextInsertionHelperResult;
+ return parseMacTextInsertionHelperResult(stdout);
} catch (error) {
// Don't include stdout in the error message: the helper may have printed
// partial JSON or debug output containing AX-captured surrounding text from
@@ -2349,6 +2732,98 @@ async function runMacTextInsertionHelper(
}
}
+/** 取 stdout 的最后一行 JSON 作为命令结果(前面的行是流式进度事件)。 */
+export function parseMacTextInsertionHelperResult(stdout: string): MacTextInsertionHelperResult {
+ const lines = stdout.split('\n').map((line) => line.trim()).filter(Boolean);
+ const lastLine = lines[lines.length - 1];
+ if (lastLine === undefined) throw new Error('Empty helper response');
+ return JSON.parse(lastLine) as MacTextInsertionHelperResult;
+}
+
+/**
+ * spawn helper 并逐行解析 stdout:非最后一行的 JSON 交给 onProgress,完整 stdout
+ * 仍然返回给调用方按最后一行取结果。只有需要「结果之前先拿到中间事件」的调用会
+ * 走这里(目前只有 capture-target 的前台窗口 frame)。
+ */
+function spawnHelperWithProgressPromise(
+ command: string,
+ args: string[],
+ timeoutMs: number,
+ onProgress: (event: MacTextInsertionHelperResult) => void,
+): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
+ let stdout = '';
+ let pending = '';
+ let stderr = '';
+ let settled = false;
+
+ const settle = (run: () => void): void => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ run();
+ };
+ const timer = setTimeout(() => {
+ settle(() => {
+ child.kill('SIGTERM');
+ reject(new PasteCommandError(
+ 'Could not run macOS text insertion helper.',
+ `Helper timed out after ${timeoutMs}ms.`,
+ ));
+ });
+ }, timeoutMs);
+
+ // setEncoding 必须在这里显式设:否则每个 Buffer 各自 toString(),一个跨 chunk
+ // 边界被切开的多字节 UTF-8 字符会两边各变成替换字符。AX 上下文里全是中文这类
+ // 非 ASCII 文本,而最终 JSON 仍能解析成功,损坏会静默流进 refine 与词典学习。
+ // 设了编码后由流内部的 StringDecoder 跨 chunk 保留半个字符。
+ child.stdout.setEncoding('utf8');
+ child.stderr.setEncoding('utf8');
+
+ // 每收到一个完整换行就尝试解析:带 event 字段的是进度事件,最后一行结果不在
+ // 这里派发(由调用方从完整 stdout 取)。解析失败的行直接忽略——stdout 可能
+ // 含用户输入框文本,不进日志。
+ child.stdout.on('data', (text: string) => {
+ stdout += text;
+ pending += text;
+ const lines = pending.split('\n');
+ pending = lines.pop() ?? '';
+ for (const line of lines) {
+ const trimmed = line.trim();
+ if (!trimmed) continue;
+ try {
+ const parsed = JSON.parse(trimmed) as MacTextInsertionHelperResult & { event?: string };
+ if (parsed.event) onProgress(parsed);
+ } catch {
+ // 半行 / 非 JSON 输出:忽略,最终结果仍按最后一行解析。
+ }
+ }
+ });
+ child.stderr.on('data', (text: string) => {
+ stderr += text;
+ });
+ child.on('error', (error) => {
+ settle(() => reject(new PasteCommandError(
+ 'Could not run macOS text insertion helper.',
+ error.message,
+ )));
+ });
+ child.on('close', (code) => {
+ settle(() => {
+ if (code === 0) {
+ resolve(stdout);
+ return;
+ }
+ reject(new PasteCommandError(
+ 'Could not run macOS text insertion helper.',
+ stderr.trim() || `Helper exited with code ${code}.`,
+ ));
+ });
+ });
+ });
+}
+
let macTextInsertionHelperPathPromise: Promise<string> | null = null;
function resolveMacTextInsertionHelperPath(): Promise<string> {
diff --git a/apps/desktop/src/main/voice-input/index.ts b/apps/desktop/src/main/voice-input/index.ts
index da968d566a..b865962e39 100644
--- a/apps/desktop/src/main/voice-input/index.ts
+++ b/apps/desktop/src/main/voice-input/index.ts
@@ -80,6 +80,7 @@ import {
refreshVoiceInputInputMonitoringPermissionSnapshot,
registerActiveInlineVoiceInputWebContents,
showVoiceInputDictionaryToast,
+ takeOverlayDictionaryToastAnchor,
unregisterActiveInlineVoiceInputWebContents,
} from './global.js';
import {
@@ -306,13 +307,30 @@ const DICTIONARY_LEARNING_TEXT_DEBUG = !app.isPackaged;
export async function adviseAndRecordVoiceInputDictionaryLearning(
payload: DictationDictionaryAdviceInput | undefined,
- options: { senderId?: number | string; sourceLabel?: string } = {},
+ options: {
+ senderId?: number | string;
+ sourceLabel?: string;
+ /**
+ * 该请求是否真的来自全局浮窗的 renderer。只有 main 依据 `event.sender` 反查得出
+ * 的结论才算,不能用 payload.source —— 那是 renderer 自报的,别的 renderer 拿
+ * 共享的 adviseDictionaryLearning 桥填个 'external_overlay' 就能消费掉浮窗锚点,
+ * 让真正的浮窗请求失去锚点、自己拿到浮窗的位置。
+ */
+ fromOverlaySender?: boolean;
+ } = {},
): Promise<DictionaryAdviceIpcResult> {
if (!payload?.beforeText || !payload.afterText) {
return { ok: true, actions: [], elapsedMs: 0 };
}
const sourceLabel = options.sourceLabel ?? payload.source ?? 'in_app';
+ // 锚点资格只认 main 侧由 event.sender 反查出的 fromOverlaySender,不认 payload.source
+ // 这个 renderer 自报字段。锚点必须在任何 await 之前取:此刻的呈现代次才代表这次请求
+ // 的来源会话,绑定后无论 advisor 何时返回都只认自己那份;等 advisor 返回后再取,
+ // 并发请求会互相抢。跳过分支同样取走,让过期锚点尽早出队。
+ const toastAnchor = options.fromOverlaySender === true
+ ? takeOverlayDictionaryToastAnchor()
+ : null;
const skipReason = getDictationDictionaryAdviceSkipReason(payload);
if (skipReason) {
log.debug('dictionary learning advice skipped', {
@@ -380,6 +398,10 @@ export async function adviseAndRecordVoiceInputDictionaryLearning(
entryId: entry.id,
term: entry.text,
})),
+ // 锚点在本函数入口、任何 await 之前就绑定好了(见 toastAnchor),这里只是
+ // 把它交给 toast:并发的 advisor 请求各认自己那次会话的现场,先返回的不会
+ // 消费掉别人的。应用内听写不带锚点,走默认位置。
+ { anchor: toastAnchor },
);
}
log.debug('dictionary learning advice', {
@@ -1884,7 +1906,12 @@ export function registerVoiceInputIpc(): void {
ipcMain.handle(
'voice-input:dictionary-learning:advise',
async (event, payload: DictationDictionaryAdviceInput | undefined): Promise<DictionaryAdviceIpcResult> => {
- return adviseAndRecordVoiceInputDictionaryLearning(payload, { senderId: event.sender.id });
+ return adviseAndRecordVoiceInputDictionaryLearning(payload, {
+ senderId: event.sender.id,
+ // 这个桥是所有 renderer 共享的:浮窗 toast 锚点的资格由真实 sender 决定,
+ // 不看 payload 里自报的 source。
+ fromOverlaySender: isGlobalVoiceInputOverlaySender(event.sender),
+ });
},
);
diff --git a/apps/desktop/src/main/voice-input/overlayPlacement.ts b/apps/desktop/src/main/voice-input/overlayPlacement.ts
index 9d2e057fbd..dddd5dc369 100644
--- a/apps/desktop/src/main/voice-input/overlayPlacement.ts
+++ b/apps/desktop/src/main/voice-input/overlayPlacement.ts
@@ -43,9 +43,26 @@ export type SavedOverlayPosition = {
x: number;
y: number;
displayId?: number;
+ /**
+ * 卡片中心在保存时那块屏 workArea 里的相对比例(0~1)。
+ *
+ * 绝对坐标一旦遇到显示器重新排布就会失效(同一块屏的 workArea 原点变了),
+ * 光靠 x/y 无法还原「用户当时把它放在这块屏的哪个位置」。比例与屏幕排布无关,
+ * 是跨屏迁移与重排后恢复的权威依据;x/y 只用于同屏且坐标仍然有效时的像素级
+ * 原样恢复。旧快照没有这两个字段,按 x/y 反推。
+ */
+ ratioX?: number;
+ ratioY?: number;
updatedAt: number;
};
+function normalizeRatio(value: unknown): number | undefined {
+ if (!Number.isFinite(value)) return undefined;
+ const ratio = value as number;
+ if (ratio < 0 || ratio > 1) return undefined;
+ return ratio;
+}
+
/** 校验持久化快照,字段缺失 / 非有限数一律视为无保存位置。 */
export function normalizeSavedOverlayPosition(value: unknown): SavedOverlayPosition | null {
if (!value || typeof value !== 'object') return null;
@@ -55,17 +72,37 @@ export function normalizeSavedOverlayPosition(value: unknown): SavedOverlayPosit
x: candidate.x as number,
y: candidate.y as number,
displayId: Number.isFinite(candidate.displayId) ? (candidate.displayId as number) : undefined,
+ ratioX: normalizeRatio(candidate.ratioX),
+ ratioY: normalizeRatio(candidate.ratioY),
updatedAt: Number.isFinite(candidate.updatedAt) ? (candidate.updatedAt as number) : 0,
};
}
+/** 落盘前算出屏内相对比例,让记忆不依赖屏幕排布。 */
+export function computeOverlayPositionRatio(
+ bounds: Rectangle,
+ workArea: Rectangle,
+): { ratioX: number; ratioY: number } {
+ const center = boundsCenter(bounds);
+ return {
+ ratioX: clampRatio(workArea.width > 0 ? (center.x - workArea.x) / workArea.width : 0.5),
+ ratioY: clampRatio(workArea.height > 0 ? (center.y - workArea.y) / workArea.height : 0.5),
+ };
+}
+
export type ResolveOverlayInitialBoundsInput = {
savedPosition: SavedOverlayPosition | null;
displays: OverlayPlacementDisplay[];
+ /**
+ * 用户焦点所在的屏(前台窗口所在屏优先,取不到时是鼠标所在屏)。
+ * 浮窗必须开在这块屏上,保存位置只决定「在这块屏的什么位置」。
+ * null = 调用方拿不到任何屏快照(防御分支)。
+ */
+ activeDisplay: OverlayPlacementDisplay | null;
size: { width: number; height: number };
contentInset: number;
edgePadding: number;
- /** 无保存位置或保存位置不可用时的默认 bounds(现有 computeOverlayBounds 结果)。 */
+ /** 无保存位置或保存位置不可用时的默认 bounds(焦点屏上的 computeOverlayBounds 结果)。 */
fallbackBounds: Rectangle;
};
@@ -112,6 +149,18 @@ function boundsCenter(bounds: Rectangle): Point {
};
}
+function clampRatio(value: number): number {
+ return Math.min(Math.max(value, 0), 1);
+}
+
+/** 卡片中心是否还落在某块现存屏幕的 workArea 里(判断缓存锚点是否仍然可见)。 */
+export function isBoundsCenterOnDisplay(
+ bounds: Rectangle,
+ displays: OverlayPlacementDisplay[],
+): boolean {
+ return findDisplayContainingPoint(displays, boundsCenter(bounds)) !== null;
+}
+
/**
* 把窗口 bounds clamp 进 workArea,保证「可见卡片」(窗口 rect 向内收
* contentInset)与 workArea 边缘至少保留 edgePadding。窗口本身的透明
@@ -184,14 +233,40 @@ export function resolveDraggedOverlayBounds({
return clamped;
}
+/** 把「屏内相对比例」还原成某块屏上的窗口 bounds。 */
+function boundsFromRatio(
+ ratio: { ratioX: number; ratioY: number },
+ workArea: Rectangle,
+ size: { width: number; height: number },
+): Rectangle {
+ return {
+ x: Math.round(workArea.x + workArea.width * ratio.ratioX - size.width / 2),
+ y: Math.round(workArea.y + workArea.height * ratio.ratioY - size.height / 2),
+ width: size.width,
+ height: size.height,
+ };
+}
+
/**
- * 打开浮窗时的初始位置:有有效保存位置则「记忆优先」,否则回退默认。
- * 保存位置的卡片中心不在任何现存 display 的 workArea 内(典型:外接屏
- * 已拔掉)时同样回退默认,避免浮窗打开在看不见的位置。
+ * 打开浮窗时的初始位置。
+ *
+ * 「浮窗开在焦点屏」是硬约束,位置记忆只在焦点屏内部生效:
+ * - 无保存位置 / 记忆所属屏已不存在(典型:外接屏已拔掉)→ 焦点屏默认位置。
+ * - 快照带屏内相对比例 → 一律按比例还原到焦点屏。workArea 没变时它还原出的就是
+ * 原坐标(±1px 取整),变了(分辨率 / 缩放 / 排布调整)则跟着新尺寸走,不会
+ * 把「原来居中」变成「偏左」。
+ * - 旧快照没有比例 → 坐标仍落在归属屏内时:同屏按绝对坐标原样恢复,跨屏按坐标
+ * 反推的比例迁移;坐标已经不在归属屏内(升级前的坐标 + 之后的显示器重排)则
+ * 无从还原原意,回退默认位置,不去夹出一个贴边的假位置。
+ *
+ * 记忆所属屏认 `displayId`:显示器重排后旧坐标可能正好落进另一块屏,那是坐标
+ * 失效而不是「用户当时放在那块屏」。`displayId` 记着但已不在 = 那块屏被拔掉,
+ * 直接回退默认位置;只有完全没有 `displayId` 的旧快照才从坐标反推归属屏。
*/
export function resolveOverlayInitialBounds({
savedPosition,
displays,
+ activeDisplay,
size,
contentInset,
edgePadding,
@@ -205,12 +280,56 @@ export function resolveOverlayInitialBounds({
width: size.width,
height: size.height,
};
- const display = findDisplayContainingPoint(displays, boundsCenter(saved));
- if (!display) return fallbackBounds;
+ const savedDisplay = savedPosition.displayId !== undefined
+ ? displays.find((display) => display.id === savedPosition.displayId) ?? null
+ : findDisplayContainingPoint(displays, boundsCenter(saved));
+ if (!savedDisplay) return fallbackBounds;
+ const targetDisplay = activeDisplay ?? savedDisplay;
+ const savedRatio = savedPosition.ratioX !== undefined && savedPosition.ratioY !== undefined
+ ? { ratioX: savedPosition.ratioX, ratioY: savedPosition.ratioY }
+ : null;
+ const savedCoordsUsable = rectContainsPoint(savedDisplay.workArea, boundsCenter(saved));
+ if (!savedRatio) {
+ // 旧快照没有比例,只能从绝对坐标反推。坐标已经不在归属屏内时(典型:升级前
+ // 存的坐标 + 之后显示器重排改了这块屏的 workArea 原点)反推不出有意义的比例
+ // ——夹到 0~1 会把「原本居中」恢复成贴边,不如老老实实回退默认位置。
+ if (!savedCoordsUsable) return fallbackBounds;
+ if (targetDisplay.id === savedDisplay.id) {
+ return clampOverlayBoundsToWorkArea({
+ bounds: saved,
+ workArea: targetDisplay.workArea,
+ contentInset,
+ edgePadding,
+ });
+ }
+ }
+ const bounds = boundsFromRatio(
+ savedRatio ?? computeOverlayPositionRatio(saved, savedDisplay.workArea),
+ targetDisplay.workArea,
+ size,
+ );
return clampOverlayBoundsToWorkArea({
- bounds: saved,
- workArea: display.workArea,
+ bounds,
+ workArea: targetDisplay.workArea,
contentInset,
edgePadding,
});
}
+
+/**
+ * 校验 macOS helper 返回的前台窗口 frame。宽高必须为正:AX 偶尔会给出
+ * 0 尺寸的占位窗口,那种 frame 不能用来判断焦点屏。
+ */
+export function normalizeFocusedWindowFrame(value: unknown): Rectangle | null {
+ if (!value || typeof value !== 'object') return null;
+ const candidate = value as Partial<Rectangle>;
+ if (!Number.isFinite(candidate.x) || !Number.isFinite(candidate.y)) return null;
+ if (!Number.isFinite(candidate.width) || !Number.isFinite(candidate.height)) return null;
+ if ((candidate.width as number) <= 0 || (candidate.height as number) <= 0) return null;
+ return {
+ x: candidate.x as number,
+ y: candidate.y as number,
+ width: candidate.width as number,
+ height: candidate.height as number,
+ };
+}
diff --git a/scripts/voice-input-benchmark.mjs b/scripts/voice-input-benchmark.mjs
index 2190f339f9..336107cbf4 100644
--- a/scripts/voice-input-benchmark.mjs
+++ b/scripts/voice-input-benchmark.mjs
@@ -1724,12 +1724,21 @@ function round(value) {
return value === undefined ? undefined : Math.round(value);
}
+// helper 可以在最终结果之前先流式吐出进度行(capture-target 会先单独吐一行前台
+// 窗口 frame,好让浮窗尽早选屏),所以结果一律取最后一行非空 JSON。
+function parseHelperResult(stdout) {
+ const lines = String(stdout).split('\n').map((line) => line.trim()).filter(Boolean);
+ const lastLine = lines[lines.length - 1];
+ if (lastLine === undefined) throw new Error('Empty helper response');
+ return JSON.parse(lastLine);
+}
+
async function pasteIntoFrontmostTarget(text) {
if (process.platform !== 'darwin') {
throw new Error('--paste is currently supported only on macOS');
}
const helper = await buildMacTextInsertionHelper();
- const capture = JSON.parse(await execFileStdout(helper, ['--command', 'capture-target']));
+ const capture = parseHelperResult(await execFileStdout(helper, ['--command', 'capture-target']));
if (!capture.ok || !capture.target) {
throw new Error(capture.error ?? 'Could not capture frontmost paste target');
}
@@ -1740,7 +1749,7 @@ async function pasteIntoFrontmostTarget(text) {
'--target-name', capture.target.processName ?? '',
];
const stdout = await spawnWithInput(helper, args, text, 5000);
- return JSON.parse(stdout);
+ return parseHelperResult(stdout);
}
async function buildMacTextInsertionHelper() {