Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

⚑️ perf(desktop): eliminate quick composer overlay open stall (#17295)

Innei0e2999111f09
diff --git a/.agents/skills/agent-testing/references/probe-mock-patterns.md b/.agents/skills/agent-testing/references/probe-mock-patterns.md
index 079d35fe698..8a0c85b362a 100644
--- a/.agents/skills/agent-testing/references/probe-mock-patterns.md
+++ b/.agents/skills/agent-testing/references/probe-mock-patterns.md
@@ -1557,3 +1557,37 @@ ingest-report <dir> --subject topic:<id> …` β€” and verify attachment in the D
- **Works**: mark the case `blocked` and cover the path with unit tests, or run the flow with a
real receivable mailbox (staging/prod smoke). Use the DB flip only to unblock downstream
fixtures, and assert it does NOT produce the event as a bonus authenticity check.
+
+### E36. Desktop main-process `logger.info` is invisible in dev without `DEBUG`
+
+- **Situation**: verifying desktop main-process behavior (e.g. perf probes in a manager/module) by
+ reading the dev log.
+- **Doesn't work**: expecting `createLogger(ns).info(...)` lines in `/tmp/electron-dev.log` from a
+ plain dev start β€” in dev (`app.isPackaged` false) `info` only goes through the `debug` package,
+ which is silent unless its namespace is enabled.
+- **Works**: start the instance with the namespace enabled, e.g.
+ `DEBUG="screenCapture:*" electron-dev.sh restart`, then grep the log. In packaged builds the same
+ lines land in electron-log's file instead.
+
+### E37. osascript keystrokes go to the frontmost app β€” never send Escape
+
+- **Situation**: driving a desktop flow with synthetic keys (global shortcut trigger is fine β€” it's
+ registered globally), then trying to dismiss a window with `key code 53` (Escape).
+- **Doesn't work**: the Escape lands on whatever app is frontmost β€” typically the terminal running
+ the agent session, which interprets it as an interrupt and kills the agent's own turn.
+- **Works**: close app surfaces in-band instead: eval the app's own close IPC via CDP on that
+ window's target (`window.electronAPI.invoke('...close')`), or click its close affordance. Reserve
+ synthetic keys for globally-registered shortcuts that don't depend on focus.
+
+### E38. Bimodal timings from a globalShortcut handler = idle-event-loop stall (and `setTimeout` probes mask it)
+
+- **Situation**: timing a flow triggered from an Electron `globalShortcut` callback; measurements
+ are wildly bimodal (sub-ms vs multi-second) and "fix" themselves when extra probes are added.
+- **Doesn't work**: attributing the multi-second gap to whatever awaited call sits at that milestone
+ (it may be a cached no-op), or keeping a `setTimeout(0)` diagnostic probe while re-measuring β€” a
+ pending timer wakes the loop and hides the stall entirely.
+- **Works**: bracket the suspect `await` with markers plus one `queueMicrotask` and one
+ `setTimeout(0)` marker ONCE to classify the stall, then remove them and re-measure. If the
+ continuation only runs when an external event arrives (a CDP poll, mouse move), the cause is the
+ native-callback context not draining microtasks on an idle loop β€” fix by deferring the handler
+ body via `setImmediate` at the registration site, then verify variance collapses.
diff --git a/apps/desktop/src/main/core/App.ts b/apps/desktop/src/main/core/App.ts
index 4a832bf29ea..f9f602413d6 100644
--- a/apps/desktop/src/main/core/App.ts
+++ b/apps/desktop/src/main/core/App.ts
@@ -379,6 +379,8 @@ export class App {
}
}
});
+ this.screenCaptureManager.prewarmPermissionCheck();
+
logger.info('Application ready state completed');
};
diff --git a/apps/desktop/src/main/core/ui/ShortcutManager.ts b/apps/desktop/src/main/core/ui/ShortcutManager.ts
index 22b1b6a1441..47a9d975e8d 100644
--- a/apps/desktop/src/main/core/ui/ShortcutManager.ts
+++ b/apps/desktop/src/main/core/ui/ShortcutManager.ts
@@ -10,12 +10,7 @@ const logger = createLogger('core:ShortcutManager');
export interface ShortcutUpdateResult {
errorType?:
- | 'INVALID_ID'
- | 'INVALID_FORMAT'
- | 'NO_MODIFIER'
- | 'CONFLICT'
- | 'SYSTEM_OCCUPIED'
- | 'UNKNOWN';
+ 'INVALID_ID' | 'INVALID_FORMAT' | 'NO_MODIFIER' | 'CONFLICT' | 'SYSTEM_OCCUPIED' | 'UNKNOWN';
success: boolean;
}
@@ -172,8 +167,12 @@ export class ShortcutManager {
this.unregisterShortcut(accelerator);
}
- // Register new shortcut
- const success = globalShortcut.register(accelerator, callback);
+ // globalShortcut callbacks fire synchronously from native code with no
+ // task wrapper, so microtasks queued by an async handler (any `await`
+ // continuation) are not drained until the event loop next wakes β€” on an
+ // idle app that can be seconds later. setImmediate re-enters the handler
+ // through a normal libuv task so continuations run right away.
+ const success = globalShortcut.register(accelerator, () => setImmediate(callback));
if (success) {
this.shortcuts.set(accelerator, callback);
diff --git a/apps/desktop/src/main/core/ui/__tests__/ShortcutManager.test.ts b/apps/desktop/src/main/core/ui/__tests__/ShortcutManager.test.ts
index ba2cc698b28..bb2f7e44821 100644
--- a/apps/desktop/src/main/core/ui/__tests__/ShortcutManager.test.ts
+++ b/apps/desktop/src/main/core/ui/__tests__/ShortcutManager.test.ts
@@ -266,10 +266,24 @@ describe('ShortcutManager', () => {
const result = shortcutManager.registerShortcut('Ctrl+T', callback);
expect(result).toBe(true);
- expect(globalShortcut.register).toHaveBeenCalledWith('Ctrl+T', callback);
+ expect(globalShortcut.register).toHaveBeenCalledWith('Ctrl+T', expect.any(Function));
expect(shortcutManager['shortcuts'].has('Ctrl+T')).toBe(true);
});
+ it('should defer the callback to a task so await continuations run immediately', async () => {
+ const callback = vi.fn();
+ vi.mocked(globalShortcut.register).mockReturnValue(true);
+
+ shortcutManager.registerShortcut('Ctrl+T', callback);
+
+ const registeredCallback = vi.mocked(globalShortcut.register).mock.calls[0][1];
+ registeredCallback();
+ expect(callback).not.toHaveBeenCalled();
+
+ await new Promise((resolve) => setImmediate(resolve));
+ expect(callback).toHaveBeenCalledTimes(1);
+ });
+
it('should unregister existing shortcut before registering new one', () => {
const callback1 = vi.fn();
const callback2 = vi.fn();
@@ -281,7 +295,7 @@ describe('ShortcutManager', () => {
shortcutManager.registerShortcut('Ctrl+T', callback2);
expect(globalShortcut.unregister).toHaveBeenCalledWith('Ctrl+T');
- expect(globalShortcut.register).toHaveBeenCalledWith('Ctrl+T', callback2);
+ expect(globalShortcut.register).toHaveBeenCalledWith('Ctrl+T', expect.any(Function));
});
it('should handle registration failure', () => {
diff --git a/apps/desktop/src/main/modules/screenCapture/ScreenCaptureManager.test.ts b/apps/desktop/src/main/modules/screenCapture/ScreenCaptureManager.test.ts
index bc52a5443c5..3b795c6eacf 100644
--- a/apps/desktop/src/main/modules/screenCapture/ScreenCaptureManager.test.ts
+++ b/apps/desktop/src/main/modules/screenCapture/ScreenCaptureManager.test.ts
@@ -151,6 +151,42 @@ describe('ScreenCaptureManager', () => {
expect(mockBrowserWindow.moveTop).toHaveBeenCalled();
});
+ describe('permission caching', () => {
+ it('queries screen capture status only once across sessions when granted', async () => {
+ const manager = new ScreenCaptureManager(createApp());
+
+ await manager.startSession();
+ manager.close();
+ await manager.startSession();
+
+ expect(mockGetScreenCaptureStatus).toHaveBeenCalledTimes(1);
+ });
+
+ it('skips the status query in startSession after prewarm', async () => {
+ const manager = new ScreenCaptureManager(createApp());
+
+ manager.prewarmPermissionCheck();
+ await new Promise((resolve) => setTimeout(resolve, 1));
+ expect(mockGetScreenCaptureStatus).toHaveBeenCalledTimes(1);
+
+ await manager.startSession();
+
+ expect(mockGetScreenCaptureStatus).toHaveBeenCalledTimes(1);
+ expect(mockBrowserWindow.show).toHaveBeenCalled();
+ });
+
+ it('re-queries status on each session while permission is not granted', async () => {
+ mockGetScreenCaptureStatus.mockReturnValue('denied');
+ mockDialogShowMessageBox.mockResolvedValue({ response: 1 });
+ const manager = new ScreenCaptureManager(createApp());
+
+ await manager.startSession();
+ await manager.startSession();
+
+ expect(mockGetScreenCaptureStatus).toHaveBeenCalledTimes(2);
+ });
+ });
+
it('blocks quick composer and prompts for permission when screen recording is unavailable', async () => {
mockGetScreenCaptureStatus.mockReturnValue('denied');
mockDialogShowMessageBox.mockResolvedValue({ response: 0 });
diff --git a/apps/desktop/src/main/modules/screenCapture/ScreenCaptureManager.ts b/apps/desktop/src/main/modules/screenCapture/ScreenCaptureManager.ts
index b41046d5d3e..34ea9ea85df 100644
--- a/apps/desktop/src/main/modules/screenCapture/ScreenCaptureManager.ts
+++ b/apps/desktop/src/main/modules/screenCapture/ScreenCaptureManager.ts
@@ -58,9 +58,26 @@ export class ScreenCaptureManager {
* session closes.
*/
private captureUploads = new Map<string, CaptureUploadEntry>();
+ /**
+ * macOS Screen Recording (TCC) status queries go through a native XPC call
+ * that can take seconds. A grant only takes effect after app relaunch, so a
+ * positive result is stable for the process lifetime and safe to cache.
+ */
+ private screenCaptureGranted = false;
constructor(private readonly app: App) {}
+ prewarmPermissionCheck(): void {
+ if (!isMac || this.screenCaptureGranted) return;
+ setTimeout(() => {
+ const start = Date.now();
+ this.screenCaptureGranted = getScreenCaptureStatus() === 'granted';
+ logger.info(
+ `Prewarmed screen capture permission: granted=${this.screenCaptureGranted} (${Date.now() - start}ms)`,
+ );
+ }, 0);
+ }
+
publishOverlaySnapshot(payload: OverlaySnapshotPayload): void {
this.snapshot = payload;
// If a session is already on screen, push the updated lists so the user
@@ -273,12 +290,13 @@ export class ScreenCaptureManager {
}
private async ensureScreenCaptureAccess(): Promise<boolean> {
- if (!isMac) {
+ if (!isMac || this.screenCaptureGranted) {
return true;
}
const status = getScreenCaptureStatus();
if (status === 'granted') {
+ this.screenCaptureGranted = true;
return true;
}