windowsCuaOperationIndicator.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. import { BrowserWindow, screen } from "electron";
  2. import type { BrowserWindowConstructorOptions, Display, Point, Rectangle } from "electron";
  3. import type { HostCuaOperationStateResponse, Locale } from "@zcode/shared";
  4. import {
  5. INDICATOR_CARD_TOP_OFFSET,
  6. INDICATOR_SHADOW_INSET,
  7. indicatorDataUrl,
  8. indicatorWindowSize,
  9. } from "./windowsCuaOperationIndicatorContent.js";
  10. const HIDE_ANIMATION_MS = 120;
  11. /**
  12. * 兜底隐藏时限。主导隐藏的是 turn 终态 / session 关闭 / runtime 不可用 / workspace 销毁
  13. * 这几条显式清除路径,这个计时器只在它们全部失约时收场,保证浮层不会无限期停留。
  14. *
  15. * 取 30s 而不是更短:CUA 事实现在按 cell 上报(每个 node_repl cell 一次),同一 turn 内
  16. * 后续 cell 会刷新计时器,但单个 cell 本身可以跑很久,10s 会让浮层在操作中途熄灭。
  17. */
  18. const AUTO_HIDE_MS = 30_000;
  19. const CREATE_RETRY_MS = 250;
  20. export interface WindowsCuaOperationIndicatorWindow {
  21. readonly webContents: Pick<BrowserWindow["webContents"], "executeJavaScript">;
  22. destroy(): void;
  23. hide(): void;
  24. isDestroyed(): boolean;
  25. loadURL(url: string): Promise<void>;
  26. moveTop(): void;
  27. on(event: "closed", listener: () => void): this;
  28. setAlwaysOnTop(flag: boolean, level?: Parameters<BrowserWindow["setAlwaysOnTop"]>[1]): void;
  29. setBounds(bounds: Rectangle): void;
  30. setContentProtection(enable: boolean): void;
  31. setIgnoreMouseEvents(ignore: boolean): void;
  32. showInactive(): void;
  33. }
  34. export interface WindowsCuaOperationIndicator {
  35. handleState(source: object, event: HostCuaOperationStateResponse): void;
  36. clearSource(source: object): void;
  37. ownsWindow(candidate: object): boolean;
  38. refreshContent(): void;
  39. dispose(): void;
  40. }
  41. interface IndicatorLogger {
  42. debug(...args: unknown[]): void;
  43. warn(...args: unknown[]): void;
  44. }
  45. interface WindowsCuaOperationIndicatorOptions {
  46. platform?: NodeJS.Platform;
  47. getLocale: () => Locale;
  48. logger: IndicatorLogger;
  49. createWindow?: (options: BrowserWindowConstructorOptions) => WindowsCuaOperationIndicatorWindow;
  50. getCursorScreenPoint?: () => Point;
  51. getDisplayNearestPoint?: (point: Point) => Pick<Display, "workArea">;
  52. schedule?: (callback: () => void, delayMs: number) => ReturnType<typeof setTimeout>;
  53. cancelSchedule?: (timer: ReturnType<typeof setTimeout>) => void;
  54. }
  55. export function createWindowsCuaOperationIndicator(
  56. options: WindowsCuaOperationIndicatorOptions,
  57. ): WindowsCuaOperationIndicator {
  58. const platform = options.platform ?? process.platform;
  59. const createWindow =
  60. options.createWindow ??
  61. ((windowOptions: BrowserWindowConstructorOptions) =>
  62. new BrowserWindow(windowOptions) as WindowsCuaOperationIndicatorWindow);
  63. const getCursorScreenPoint =
  64. options.getCursorScreenPoint ?? (() => screen.getCursorScreenPoint());
  65. const getDisplayNearestPoint =
  66. options.getDisplayNearestPoint ?? ((point: Point) => screen.getDisplayNearestPoint(point));
  67. const schedule = options.schedule ?? ((callback, delayMs) => setTimeout(callback, delayMs));
  68. const cancelSchedule = options.cancelSchedule ?? ((timer) => clearTimeout(timer));
  69. const activeTurnKeysBySource = new Map<object, Set<string>>();
  70. const ownedWindows = new WeakSet<object>();
  71. const failedWindows = new WeakSet<object>();
  72. let window: WindowsCuaOperationIndicatorWindow | null = null;
  73. let windowReady = false;
  74. let windowShown = false;
  75. let hideTimer: ReturnType<typeof setTimeout> | null = null;
  76. const autoHideTimersBySource = new Map<object, Map<string, ReturnType<typeof setTimeout>>>();
  77. let reconcileTimer: ReturnType<typeof setTimeout> | null = null;
  78. let setupRetryAvailable = false;
  79. let disposed = false;
  80. function hasActiveTurns(): boolean {
  81. for (const keys of activeTurnKeysBySource.values()) {
  82. if (keys.size > 0) return true;
  83. }
  84. return false;
  85. }
  86. function keyFor(event: HostCuaOperationStateResponse): string {
  87. const workspaceKey = event.workspaceIdentity?.trim() || event.workspacePath;
  88. return `${workspaceKey}\0${event.sessionId}\0${event.turnId}`;
  89. }
  90. function setDocumentState(nextState: "active" | "leaving"): void {
  91. if (!window || window.isDestroyed()) return;
  92. void window.webContents
  93. .executeJavaScript(`document.documentElement.dataset.state=${JSON.stringify(nextState)}`)
  94. .catch((error) =>
  95. options.logger.debug("[cua-operation-indicator] state update failed", error),
  96. );
  97. }
  98. function cancelPendingHide(): void {
  99. if (!hideTimer) return;
  100. cancelSchedule(hideTimer);
  101. hideTimer = null;
  102. }
  103. function cancelAutoHide(source: object, key: string): void {
  104. const timers = autoHideTimersBySource.get(source);
  105. const timer = timers?.get(key);
  106. if (!timer) return;
  107. cancelSchedule(timer);
  108. timers?.delete(key);
  109. if (timers?.size === 0) autoHideTimersBySource.delete(source);
  110. }
  111. function scheduleAutoHide(source: object, key: string): void {
  112. cancelAutoHide(source, key);
  113. const timers = autoHideTimersBySource.get(source) ?? new Map();
  114. autoHideTimersBySource.set(source, timers);
  115. let timer: ReturnType<typeof setTimeout>;
  116. timer = schedule(() => {
  117. const currentTimers = autoHideTimersBySource.get(source);
  118. if (currentTimers?.get(key) !== timer) return;
  119. currentTimers.delete(key);
  120. if (currentTimers.size === 0) autoHideTimersBySource.delete(source);
  121. const sourceKeys = activeTurnKeysBySource.get(source);
  122. if (!sourceKeys?.delete(key)) return;
  123. if (sourceKeys.size === 0) activeTurnKeysBySource.delete(source);
  124. // 安全计时器是 fail-hidden 边界:即使 runtime 没有补发 inactive,也不能让
  125. // 原生浮层无限期可见;后续 CUA tool-started 会重新建立该键并重新计时。
  126. if (!hasActiveTurns()) beginHide();
  127. }, AUTO_HIDE_MS);
  128. timers.set(key, timer);
  129. }
  130. function scheduleSetupRetry(): void {
  131. if (!setupRetryAvailable || !hasActiveTurns() || reconcileTimer) return;
  132. setupRetryAvailable = false;
  133. reconcileTimer = schedule(() => {
  134. reconcileTimer = null;
  135. ensureWindow();
  136. }, CREATE_RETRY_MS);
  137. }
  138. function discardFailedWindow(target: WindowsCuaOperationIndicatorWindow): void {
  139. failedWindows.add(target);
  140. if (window === target) {
  141. window = null;
  142. windowReady = false;
  143. windowShown = false;
  144. }
  145. try {
  146. if (!target.isDestroyed()) target.destroy();
  147. } catch (destroyError) {
  148. options.logger.debug(
  149. "[cua-operation-indicator] failed to discard partial window",
  150. destroyError,
  151. );
  152. }
  153. }
  154. function positionWindow(target: WindowsCuaOperationIndicatorWindow): void {
  155. const { width, height } = indicatorWindowSize(options.getLocale());
  156. const point = getCursorScreenPoint();
  157. const { workArea } = getDisplayNearestPoint(point);
  158. target.setBounds({
  159. width,
  160. height,
  161. x: Math.round(workArea.x + (workArea.width - width) / 2),
  162. y: Math.round(workArea.y + INDICATOR_CARD_TOP_OFFSET - INDICATOR_SHADOW_INSET.top),
  163. });
  164. }
  165. function handleLoadFailure(target: WindowsCuaOperationIndicatorWindow, error: unknown): void {
  166. options.logger.warn("[cua-operation-indicator] failed to load window content", error);
  167. if (disposed || target !== window) return;
  168. discardFailedWindow(target);
  169. scheduleSetupRetry();
  170. }
  171. function showWindowOnTop(target: WindowsCuaOperationIndicatorWindow): void {
  172. target.showInactive();
  173. // Windows 隐藏透明窗口后可能清除 WS_EX_TOPMOST;showInactive 只恢复可见性,
  174. // 不会恢复原生 Z-order,因此每次显示后都必须重新声明层级并移到该层级最前方。
  175. target.setAlwaysOnTop(true, "screen-saver");
  176. target.moveTop();
  177. }
  178. function loadContent(target: WindowsCuaOperationIndicatorWindow): void {
  179. try {
  180. positionWindow(target);
  181. void target
  182. .loadURL(indicatorDataUrl(options.getLocale()))
  183. .then(() => {
  184. if (disposed || target !== window || target.isDestroyed()) return;
  185. windowReady = true;
  186. setupRetryAvailable = false;
  187. if (!hasActiveTurns()) {
  188. // refreshContent 可能发生在窗口已经隐藏之后;HTML 默认是 active,必须在
  189. // 无活跃 turn 时显式恢复离场状态,避免后续错误 show() 暴露假提示。
  190. setDocumentState("leaving");
  191. return;
  192. }
  193. positionWindow(target);
  194. showWindowOnTop(target);
  195. windowShown = true;
  196. setDocumentState("active");
  197. })
  198. .catch((error) => handleLoadFailure(target, error));
  199. } catch (error) {
  200. handleLoadFailure(target, error);
  201. }
  202. }
  203. function ensureWindow(repositionExisting = false): void {
  204. if (disposed || platform !== "win32" || !hasActiveTurns()) return;
  205. cancelPendingHide();
  206. if (window && !window.isDestroyed()) {
  207. if (repositionExisting) positionWindow(window);
  208. setDocumentState("active");
  209. // 根因:退场只隐藏而不销毁窗口;后续 turn 复用时必须重新显示已加载的窗口。
  210. if (windowReady && !windowShown) {
  211. showWindowOnTop(window);
  212. windowShown = true;
  213. }
  214. if (windowReady) setupRetryAvailable = false;
  215. return;
  216. }
  217. let created: WindowsCuaOperationIndicatorWindow | null = null;
  218. try {
  219. const { width, height } = indicatorWindowSize(options.getLocale());
  220. created = createWindow({
  221. width,
  222. height,
  223. alwaysOnTop: true,
  224. focusable: false,
  225. frame: false,
  226. // 旧窗口只给 CSS shadow 留 1px 透明边,并叠加默认 DWM 矩形阴影,
  227. // 导致圆角阴影被裁成硬边和灰带;扩大透明画布后由 CSS 独占阴影。
  228. hasShadow: false,
  229. resizable: false,
  230. show: false,
  231. skipTaskbar: true,
  232. transparent: true,
  233. backgroundColor: "#00000000",
  234. autoHideMenuBar: true,
  235. fullscreenable: false,
  236. maximizable: false,
  237. minimizable: false,
  238. movable: false,
  239. webPreferences: {
  240. contextIsolation: true,
  241. devTools: false,
  242. nodeIntegration: false,
  243. sandbox: true,
  244. },
  245. });
  246. window = created;
  247. windowReady = false;
  248. windowShown = false;
  249. ownedWindows.add(created);
  250. created.setIgnoreMouseEvents(true);
  251. created.setContentProtection(true);
  252. created.on("closed", () => {
  253. const failedDuringSetup = failedWindows.delete(created as object);
  254. if (window === created) {
  255. window = null;
  256. windowReady = false;
  257. windowShown = false;
  258. }
  259. if (failedDuringSetup || disposed || !hasActiveTurns() || reconcileTimer) return;
  260. // 原因:系统意外关闭窗口时 Host 的 turn 仍然活跃,必须主动重建,不能等下一条状态。
  261. setupRetryAvailable = true;
  262. reconcileTimer = schedule(() => {
  263. reconcileTimer = null;
  264. ensureWindow();
  265. }, 0);
  266. });
  267. loadContent(created);
  268. } catch (error) {
  269. options.logger.warn("[cua-operation-indicator] failed to create secure window", error);
  270. if (created) discardFailedWindow(created);
  271. scheduleSetupRetry();
  272. }
  273. }
  274. function hideOrDestroy(target: WindowsCuaOperationIndicatorWindow): void {
  275. try {
  276. target.hide();
  277. windowShown = false;
  278. return;
  279. } catch (error) {
  280. // 关闭是这个浮层的安全底线:它在声称"ZCode 正在操作电脑",隐藏失败就等于向用户
  281. // 撒谎。hide() 抛错时降级为销毁窗口——下一个 CUA cell 会由 ensureWindow 重建。
  282. options.logger.warn("[cua-operation-indicator] hide failed, destroying window", error);
  283. }
  284. if (window === target) {
  285. window = null;
  286. windowReady = false;
  287. }
  288. windowShown = false;
  289. try {
  290. if (!target.isDestroyed()) target.destroy();
  291. } catch (destroyError) {
  292. options.logger.warn(
  293. "[cua-operation-indicator] destroy after failed hide failed",
  294. destroyError,
  295. );
  296. }
  297. }
  298. function beginHide(): void {
  299. setupRetryAvailable = false;
  300. if (!window || window.isDestroyed() || hideTimer) return;
  301. setDocumentState("leaving");
  302. const target = window;
  303. hideTimer = schedule(() => {
  304. hideTimer = null;
  305. if (!disposed && !hasActiveTurns() && target === window && !target.isDestroyed()) {
  306. hideOrDestroy(target);
  307. }
  308. }, HIDE_ANIMATION_MS);
  309. }
  310. function handleState(source: object, event: HostCuaOperationStateResponse): void {
  311. if (disposed || platform !== "win32") return;
  312. const key = keyFor(event);
  313. const sourceKeys = activeTurnKeysBySource.get(source);
  314. if (event.active) {
  315. if (sourceKeys?.has(key)) {
  316. cancelPendingHide();
  317. scheduleAutoHide(source, key);
  318. ensureWindow();
  319. return;
  320. }
  321. const wasActive = hasActiveTurns();
  322. if (!wasActive) setupRetryAvailable = true;
  323. const nextKeys = sourceKeys ?? new Set<string>();
  324. nextKeys.add(key);
  325. activeTurnKeysBySource.set(source, nextKeys);
  326. scheduleAutoHide(source, key);
  327. // 只有 aggregate 从空变为非空时按当前鼠标显示器重定位,避免并行 source 让窗口跳动。
  328. ensureWindow(!wasActive);
  329. return;
  330. }
  331. if (!sourceKeys?.delete(key)) return;
  332. cancelAutoHide(source, key);
  333. if (sourceKeys.size === 0) activeTurnKeysBySource.delete(source);
  334. if (!hasActiveTurns()) beginHide();
  335. }
  336. function clearSource(source: object): void {
  337. if (disposed || platform !== "win32" || !activeTurnKeysBySource.delete(source)) return;
  338. const timers = autoHideTimersBySource.get(source);
  339. for (const key of timers ? [...timers.keys()] : []) {
  340. cancelAutoHide(source, key);
  341. }
  342. if (!hasActiveTurns()) beginHide();
  343. }
  344. function refreshContent(): void {
  345. if (disposed || platform !== "win32" || !window || window.isDestroyed()) return;
  346. if (hasActiveTurns()) setupRetryAvailable = true;
  347. loadContent(window);
  348. }
  349. function ownsWindow(candidate: object): boolean {
  350. return ownedWindows.has(candidate);
  351. }
  352. function dispose(): void {
  353. if (disposed) return;
  354. disposed = true;
  355. setupRetryAvailable = false;
  356. activeTurnKeysBySource.clear();
  357. for (const [source, timers] of autoHideTimersBySource) {
  358. for (const timer of timers.values()) cancelSchedule(timer);
  359. autoHideTimersBySource.delete(source);
  360. }
  361. cancelPendingHide();
  362. if (reconcileTimer) {
  363. cancelSchedule(reconcileTimer);
  364. reconcileTimer = null;
  365. }
  366. const target = window;
  367. window = null;
  368. windowReady = false;
  369. windowShown = false;
  370. if (target && !target.isDestroyed()) target.destroy();
  371. }
  372. return { handleState, clearSource, ownsWindow, refreshContent, dispose };
  373. }