feat(desktop): Chrome-style hold-to-quit (#5508)
This commit is contained in:
1 parent
178da6bc32
commit
b7dbbbaf6c
16 files changed
+539
-3
No files matched your search
@@ -5,6 +5,7 @@ export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||
export const PROBE_REMOTE_EDITORS_CHANNEL = "desktop:probe-remote-editors";
|
||||
export const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
||||
export const QUIT_SHORTCUT_CHANNEL = "desktop:quit-shortcut";
|
||||
export const GET_WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:get-window-fullscreen-state";
|
||||
export const WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:window-fullscreen-state";
|
||||
export const UPDATE_STATE_CHANNEL = "desktop:update-state";
|
||||
|
||||
@@ -10,8 +10,11 @@ import * as DesktopLifecycle from "../../app/DesktopLifecycle.ts";
|
||||
import * as DesktopShutdown from "../../app/DesktopShutdown.ts";
|
||||
import * as DesktopState from "../../app/DesktopState.ts";
|
||||
import * as ElectronApp from "../../electron/ElectronApp.ts";
|
||||
import * as ElectronDialog from "../../electron/ElectronDialog.ts";
|
||||
import * as ElectronTheme from "../../electron/ElectronTheme.ts";
|
||||
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
|
||||
import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopClientSettings from "../../settings/DesktopClientSettings.ts";
|
||||
import * as DesktopWindow from "../../window/DesktopWindow.ts";
|
||||
import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts";
|
||||
import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
|
||||
@@ -70,6 +73,15 @@ const unusedLifecycleRuntimeLayer = Layer.mergeAll(
|
||||
ElectronTheme.ElectronTheme,
|
||||
ElectronTheme.ElectronTheme.of({} as ElectronTheme.ElectronTheme["Service"]),
|
||||
),
|
||||
Layer.succeed(
|
||||
ElectronDialog.ElectronDialog,
|
||||
ElectronDialog.ElectronDialog.of({} as ElectronDialog.ElectronDialog["Service"]),
|
||||
),
|
||||
Layer.succeed(
|
||||
ElectronWindow.ElectronWindow,
|
||||
ElectronWindow.ElectronWindow.of({} as ElectronWindow.ElectronWindow["Service"]),
|
||||
),
|
||||
DesktopClientSettings.layerTest(),
|
||||
);
|
||||
|
||||
describe("WSL IPC", () => {
|
||||
|
||||
@@ -117,6 +117,17 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
ipcRenderer.removeListener(IpcChannels.MENU_ACTION_CHANNEL, wrappedListener);
|
||||
};
|
||||
},
|
||||
onQuitShortcut: (listener) => {
|
||||
const wrappedListener = (_event: Electron.IpcRendererEvent, state: unknown) => {
|
||||
if (state !== "down" && state !== "up") return;
|
||||
listener(state);
|
||||
};
|
||||
|
||||
ipcRenderer.on(IpcChannels.QUIT_SHORTCUT_CHANNEL, wrappedListener);
|
||||
return () => {
|
||||
ipcRenderer.removeListener(IpcChannels.QUIT_SHORTCUT_CHANNEL, wrappedListener);
|
||||
};
|
||||
},
|
||||
getWindowFullscreenState: () =>
|
||||
ipcRenderer.sendSync(IpcChannels.GET_WINDOW_FULLSCREEN_STATE_CHANNEL) === true,
|
||||
onWindowFullscreenStateChange: (listener) => {
|
||||
|
||||
@@ -13,6 +13,7 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopClientSettings from "./DesktopClientSettings.ts";
|
||||
|
||||
const clientSettings: ClientSettings = {
|
||||
confirmQuit: true,
|
||||
confirmThreadArchive: true,
|
||||
confirmThreadDelete: false,
|
||||
dismissedProviderUpdateNotificationKeys: [],
|
||||
|
||||
@@ -37,6 +37,8 @@ import * as DesktopConfig from "../app/DesktopConfig.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopState from "../app/DesktopState.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopClientSettings from "../settings/DesktopClientSettings.ts";
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronMenu from "../electron/ElectronMenu.ts";
|
||||
import * as ElectronShell from "../electron/ElectronShell.ts";
|
||||
import * as ElectronTheme from "../electron/ElectronTheme.ts";
|
||||
@@ -128,6 +130,14 @@ function makeFakeBrowserWindow() {
|
||||
};
|
||||
}
|
||||
|
||||
const desktopClientSettingsLayer = Layer.mock(DesktopClientSettings.DesktopClientSettings)({
|
||||
get: Effect.succeed(Option.none()),
|
||||
});
|
||||
|
||||
const electronAppLayer = Layer.mock(ElectronApp.ElectronApp)({
|
||||
quit: Effect.void,
|
||||
});
|
||||
|
||||
const desktopAssetsLayer = Layer.succeed(DesktopAssets.DesktopAssets, {
|
||||
iconPaths: Effect.succeed({
|
||||
ico: Option.none<string>(),
|
||||
@@ -253,8 +263,10 @@ function makeTestLayer(input: {
|
||||
desktopAssetsLayer,
|
||||
desktopEnvironmentLayer,
|
||||
desktopAppSettingsLayer,
|
||||
desktopClientSettingsLayer,
|
||||
desktopServerExposureLayer,
|
||||
DesktopState.layer,
|
||||
electronAppLayer,
|
||||
electronMenuLayer,
|
||||
Layer.succeed(ElectronShell.ElectronShell, {
|
||||
openExternal: (url) =>
|
||||
@@ -356,7 +368,9 @@ const makeSplashScenario = (createOutcomes: readonly (Electron.BrowserWindow | n
|
||||
desktopAssetsLayer,
|
||||
desktopEnvironmentLayer,
|
||||
DesktopAppSettings.layerTest(),
|
||||
desktopClientSettingsLayer,
|
||||
desktopServerExposureLayer,
|
||||
electronAppLayer,
|
||||
electronMenuLayer,
|
||||
Layer.succeed(ElectronShell.ElectronShell, {
|
||||
openExternal: () => Effect.succeed(true),
|
||||
|
||||
@@ -8,6 +8,8 @@ import * as Ref from "effect/Ref";
|
||||
|
||||
import * as Electron from "electron";
|
||||
|
||||
import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts";
|
||||
|
||||
import * as DesktopAssets from "../app/DesktopAssets.ts";
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import { makeComponentLogger } from "../app/DesktopObservability.ts";
|
||||
@@ -16,9 +18,16 @@ import { getDesktopUrl } from "../electron/ElectronProtocol.ts";
|
||||
import * as ElectronShell from "../electron/ElectronShell.ts";
|
||||
import * as ElectronTheme from "../electron/ElectronTheme.ts";
|
||||
import * as ElectronWindow from "../electron/ElectronWindow.ts";
|
||||
import { MENU_ACTION_CHANNEL, WINDOW_FULLSCREEN_STATE_CHANNEL } from "../ipc/channels.ts";
|
||||
import {
|
||||
MENU_ACTION_CHANNEL,
|
||||
QUIT_SHORTCUT_CHANNEL,
|
||||
WINDOW_FULLSCREEN_STATE_CHANNEL,
|
||||
} from "../ipc/channels.ts";
|
||||
import * as PreviewManager from "../preview/Manager.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopClientSettings from "../settings/DesktopClientSettings.ts";
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import { makeQuitHoldHandler } from "./QuitHold.ts";
|
||||
|
||||
const TITLEBAR_HEIGHT = 40;
|
||||
const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux
|
||||
@@ -51,6 +60,8 @@ type DesktopWindowRuntimeServices =
|
||||
| DesktopEnvironment.DesktopEnvironment
|
||||
| DesktopAssets.DesktopAssets
|
||||
| DesktopAppSettings.DesktopAppSettings
|
||||
| DesktopClientSettings.DesktopClientSettings
|
||||
| ElectronApp.ElectronApp
|
||||
| ElectronMenu.ElectronMenu
|
||||
| ElectronShell.ElectronShell
|
||||
| ElectronTheme.ElectronTheme
|
||||
@@ -261,6 +272,8 @@ export const make = Effect.gen(function* () {
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const previewManager = yield* PreviewManager.PreviewManager;
|
||||
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const clientSettings = yield* DesktopClientSettings.DesktopClientSettings;
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
// Window-side latch for the primary backend's readiness. Set by
|
||||
// handleBackendReady (driven by the pool's onReady callback), cleared
|
||||
// by handleBackendNotReady (driven by onShutdown). Only consumed by
|
||||
@@ -533,7 +546,32 @@ export const make = Effect.gen(function* () {
|
||||
// close-terminal shortcut can outlive the terminal that handled its first
|
||||
// press, so reject repeats before they reach the native window accelerator.
|
||||
// Deliberate presses still flow through the renderer or native menu.
|
||||
// Chrome-style hold-to-quit: intercept the quit accelerator before the
|
||||
// native menu sees it and only quit after the shortcut is held. The
|
||||
// renderer shows the "Hold to Quit" hint via QUIT_SHORTCUT_CHANNEL.
|
||||
const quitHoldHandler = makeQuitHoldHandler({
|
||||
platform: environment.platform,
|
||||
isEnabled: () =>
|
||||
runPromise(
|
||||
Effect.map(
|
||||
clientSettings.get,
|
||||
Option.match({
|
||||
onNone: () => DEFAULT_CLIENT_SETTINGS.confirmQuit,
|
||||
onSome: (settings) => settings.confirmQuit,
|
||||
}),
|
||||
),
|
||||
),
|
||||
notify: (state) => {
|
||||
if (!window.isDestroyed()) {
|
||||
window.webContents.send(QUIT_SHORTCUT_CHANNEL, state);
|
||||
}
|
||||
},
|
||||
quit: () => {
|
||||
void runPromise(electronApp.quit);
|
||||
},
|
||||
});
|
||||
window.webContents.on("before-input-event", (event, input) => {
|
||||
quitHoldHandler(event, input);
|
||||
if (input.type !== "keyDown" || !input.isAutoRepeat) return;
|
||||
const modifier = environment.platform === "darwin" ? input.meta : input.control;
|
||||
if (modifier && !input.alt && !input.shift && input.key.toLowerCase() === "w") {
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
makeQuitHoldHandler,
|
||||
QUIT_DOUBLE_TAP_MS,
|
||||
QUIT_HOLD_DURATION_MS,
|
||||
QUIT_HOLD_RELEASE_GRACE_MS,
|
||||
} from "./QuitHold.ts";
|
||||
import type { QuitHoldKeyInput, QuitHoldState } from "./QuitHold.ts";
|
||||
|
||||
function makeInput(overrides: Partial<QuitHoldKeyInput>): QuitHoldKeyInput {
|
||||
return {
|
||||
type: "keyDown",
|
||||
key: "q",
|
||||
meta: true,
|
||||
control: false,
|
||||
alt: false,
|
||||
shift: false,
|
||||
isAutoRepeat: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeHarness(options?: {
|
||||
enabled?: boolean;
|
||||
platform?: NodeJS.Platform;
|
||||
isEnabled?: () => Promise<boolean>;
|
||||
}) {
|
||||
const notifications: Array<QuitHoldState> = [];
|
||||
const quit = vi.fn();
|
||||
const handler = makeQuitHoldHandler({
|
||||
platform: options?.platform ?? "darwin",
|
||||
isEnabled: options?.isEnabled ?? (() => Promise.resolve(options?.enabled ?? true)),
|
||||
notify: (state) => notifications.push(state),
|
||||
quit,
|
||||
});
|
||||
const preventDefault = vi.fn();
|
||||
const send = async (input: QuitHoldKeyInput) => {
|
||||
handler({ preventDefault }, input);
|
||||
// Let the isEnabled promise settle.
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
};
|
||||
// Simulates the OS auto-repeating the held shortcut every `intervalMs`.
|
||||
const holdFor = async (
|
||||
durationMs: number,
|
||||
repeatOverrides: Partial<QuitHoldKeyInput> = {},
|
||||
intervalMs = 100,
|
||||
) => {
|
||||
for (let elapsed = 0; elapsed < durationMs; elapsed += intervalMs) {
|
||||
vi.advanceTimersByTime(intervalMs);
|
||||
await send(makeInput({ isAutoRepeat: true, ...repeatOverrides }));
|
||||
}
|
||||
};
|
||||
return { notifications, quit, preventDefault, send, holdFor };
|
||||
}
|
||||
|
||||
describe("makeQuitHoldHandler", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("shows the hint on a tap without quitting, even when the release is never seen", async () => {
|
||||
// macOS suppresses the letter's keyUp while Cmd is held, so a tap may
|
||||
// produce no keyUp at all. Quit must still not fire.
|
||||
const harness = makeHarness();
|
||||
await harness.send(makeInput({}));
|
||||
expect(harness.preventDefault).toHaveBeenCalledTimes(1);
|
||||
expect(harness.notifications).toEqual(["down"]);
|
||||
|
||||
vi.advanceTimersByTime(QUIT_HOLD_DURATION_MS + QUIT_HOLD_RELEASE_GRACE_MS);
|
||||
expect(harness.quit).not.toHaveBeenCalled();
|
||||
// The watchdog dismisses the hint once the press is clearly over.
|
||||
expect(harness.notifications).toEqual(["down", "up"]);
|
||||
});
|
||||
|
||||
it("quits once the shortcut auto-repeats past the hold duration", async () => {
|
||||
const harness = makeHarness();
|
||||
await harness.send(makeInput({}));
|
||||
await harness.holdFor(QUIT_HOLD_DURATION_MS - 200);
|
||||
expect(harness.quit).not.toHaveBeenCalled();
|
||||
await harness.holdFor(400);
|
||||
expect(harness.quit).toHaveBeenCalledTimes(1);
|
||||
// Exactly one hint cycle for the whole hold.
|
||||
expect(harness.notifications).toEqual(["down", "up"]);
|
||||
});
|
||||
|
||||
it("does not quit when the hold stops before the duration", async () => {
|
||||
const harness = makeHarness();
|
||||
await harness.send(makeInput({}));
|
||||
await harness.holdFor(500);
|
||||
await harness.send(makeInput({ type: "keyUp" }));
|
||||
expect(harness.notifications).toEqual(["down", "up"]);
|
||||
vi.advanceTimersByTime((QUIT_HOLD_DURATION_MS + QUIT_HOLD_RELEASE_GRACE_MS) * 2);
|
||||
expect(harness.quit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("cancels the hold when the modifier is released first", async () => {
|
||||
const harness = makeHarness();
|
||||
await harness.send(makeInput({}));
|
||||
await harness.send(makeInput({ type: "keyUp", key: "Meta", meta: false }));
|
||||
expect(harness.notifications).toEqual(["down", "up"]);
|
||||
vi.advanceTimersByTime((QUIT_HOLD_DURATION_MS + QUIT_HOLD_RELEASE_GRACE_MS) * 2);
|
||||
expect(harness.quit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("quits immediately on a single press when disabled", async () => {
|
||||
const harness = makeHarness({ enabled: false });
|
||||
await harness.send(makeInput({}));
|
||||
expect(harness.quit).toHaveBeenCalledTimes(1);
|
||||
// The hint is dismissed in case the quit gets cancelled downstream.
|
||||
expect(harness.notifications).toEqual(["down", "up"]);
|
||||
});
|
||||
|
||||
it("discards a stale isEnabled resolution from a superseded press", async () => {
|
||||
// Press #1's isEnabled is still pending when the user releases and
|
||||
// presses again; its late resolution must not act for press #2.
|
||||
const resolvers: Array<(enabled: boolean) => void> = [];
|
||||
const harness = makeHarness({
|
||||
isEnabled: () => new Promise((resolve) => resolvers.push(resolve)),
|
||||
});
|
||||
await harness.send(makeInput({}));
|
||||
await harness.send(makeInput({ type: "keyUp" }));
|
||||
// Outside the double-tap window, so the second press starts a new hold.
|
||||
vi.advanceTimersByTime(QUIT_DOUBLE_TAP_MS + 100);
|
||||
await harness.send(makeInput({}));
|
||||
expect(resolvers).toHaveLength(2);
|
||||
|
||||
// Press #1 resolves late with "disabled" — it must not quit press #2.
|
||||
resolvers[0]?.(false);
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
expect(harness.quit).not.toHaveBeenCalled();
|
||||
|
||||
// Press #2 resolves enabled and completes a full hold.
|
||||
resolvers[1]?.(true);
|
||||
await harness.holdFor(QUIT_HOLD_DURATION_MS + 200);
|
||||
expect(harness.quit).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("quits on a quick double tap, even when the first release was never seen", async () => {
|
||||
const harness = makeHarness();
|
||||
await harness.send(makeInput({}));
|
||||
vi.advanceTimersByTime(QUIT_DOUBLE_TAP_MS - 100);
|
||||
await harness.send(makeInput({}));
|
||||
expect(harness.quit).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("treats two slow taps as separate presses", async () => {
|
||||
const harness = makeHarness();
|
||||
await harness.send(makeInput({}));
|
||||
await harness.send(makeInput({ type: "keyUp" }));
|
||||
vi.advanceTimersByTime(QUIT_DOUBLE_TAP_MS + 100);
|
||||
await harness.send(makeInput({}));
|
||||
expect(harness.quit).not.toHaveBeenCalled();
|
||||
expect(harness.notifications).toEqual(["down", "up", "down"]);
|
||||
});
|
||||
|
||||
it("cancels the hold when another key interrupts it", async () => {
|
||||
const harness = makeHarness();
|
||||
await harness.send(makeInput({}));
|
||||
await harness.holdFor(500);
|
||||
// Shift pressed mid-hold breaks the gesture...
|
||||
await harness.send(makeInput({ shift: true }));
|
||||
expect(harness.notifications).toEqual(["down", "up"]);
|
||||
// ...so later repeats past the threshold must not quit.
|
||||
await harness.holdFor(QUIT_HOLD_DURATION_MS);
|
||||
expect(harness.quit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not count an interrupted press toward a double tap", async () => {
|
||||
const harness = makeHarness();
|
||||
await harness.send(makeInput({}));
|
||||
await harness.send(makeInput({ shift: true }));
|
||||
// A fresh press right after the interruption starts a new hold, not a
|
||||
// double-tap quit.
|
||||
await harness.send(makeInput({}));
|
||||
expect(harness.quit).not.toHaveBeenCalled();
|
||||
expect(harness.notifications).toEqual(["down", "up", "down"]);
|
||||
});
|
||||
|
||||
it("ignores other shortcuts", async () => {
|
||||
const harness = makeHarness();
|
||||
await harness.send(makeInput({ key: "w" }));
|
||||
await harness.send(makeInput({ shift: true }));
|
||||
await harness.send(makeInput({ meta: false }));
|
||||
expect(harness.preventDefault).not.toHaveBeenCalled();
|
||||
expect(harness.notifications).toEqual([]);
|
||||
});
|
||||
|
||||
it("uses control on non-mac platforms", async () => {
|
||||
const harness = makeHarness({ platform: "linux" });
|
||||
await harness.send(makeInput({ meta: false, control: true }));
|
||||
expect(harness.preventDefault).toHaveBeenCalledTimes(1);
|
||||
await harness.holdFor(QUIT_HOLD_DURATION_MS + 200, { meta: false, control: true });
|
||||
expect(harness.quit).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,148 @@
|
||||
// @effect-diagnostics globalDate:off globalTimers:off -- Synchronous before-input-event handler; key events must be timed and the watchdog scheduled outside any Effect runtime.
|
||||
|
||||
// Chrome-style hold-to-quit. The quit accelerator is intercepted in
|
||||
// before-input-event (which runs before the native menu accelerator), and the
|
||||
// app only quits once the shortcut has been held for QUIT_HOLD_DURATION_MS.
|
||||
// A quick tap just shows the renderer's "Hold to Quit" hint, and a second tap
|
||||
// within QUIT_DOUBLE_TAP_MS quits immediately. Quitting from the application
|
||||
// menu itself is untouched and quits immediately.
|
||||
export const QUIT_HOLD_DURATION_MS = 1200;
|
||||
// A second quick tap of the shortcut is the user insisting: quit immediately.
|
||||
export const QUIT_DOUBLE_TAP_MS = 500;
|
||||
// "Still held" is proven by auto-repeat keydowns, not by the absence of a
|
||||
// release: macOS suppresses a letter's keyUp while the command key is down, so
|
||||
// a tap's release can go completely unseen and a release-based timer would
|
||||
// quit anyway. The press is treated as released once no key event has arrived
|
||||
// for QUIT_HOLD_RELEASE_GRACE_MS past the hold duration. Keyboards with
|
||||
// auto-repeat disabled cannot hold-to-quit and fall back to the menu's Quit.
|
||||
export const QUIT_HOLD_RELEASE_GRACE_MS = 600;
|
||||
|
||||
export type QuitHoldState = "down" | "up";
|
||||
|
||||
export interface QuitHoldKeyInput {
|
||||
readonly type: string;
|
||||
readonly key: string;
|
||||
readonly meta: boolean;
|
||||
readonly control: boolean;
|
||||
readonly alt: boolean;
|
||||
readonly shift: boolean;
|
||||
readonly isAutoRepeat: boolean;
|
||||
}
|
||||
|
||||
export interface QuitHoldOptions {
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly isEnabled: () => Promise<boolean>;
|
||||
readonly notify: (state: QuitHoldState) => void;
|
||||
readonly quit: () => void;
|
||||
}
|
||||
|
||||
export function makeQuitHoldHandler(
|
||||
options: QuitHoldOptions,
|
||||
): (event: { preventDefault: () => void }, input: QuitHoldKeyInput) => void {
|
||||
const modifierKey = options.platform === "darwin" ? "meta" : "control";
|
||||
let watchdog: NodeJS.Timeout | undefined;
|
||||
let holding = false;
|
||||
// Set once isEnabled resolves true; auto-repeats may only quit when armed.
|
||||
let armed = false;
|
||||
let heldSince = 0;
|
||||
let lastPressAt = 0;
|
||||
// Incremented on every new press and every release/quit so a pending
|
||||
// isEnabled() resolution from a superseded press cannot arm (or quit for)
|
||||
// the current one.
|
||||
let generation = 0;
|
||||
|
||||
const clearWatchdog = () => {
|
||||
if (watchdog !== undefined) {
|
||||
clearTimeout(watchdog);
|
||||
watchdog = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
const release = () => {
|
||||
if (!holding) return;
|
||||
generation += 1;
|
||||
holding = false;
|
||||
armed = false;
|
||||
clearWatchdog();
|
||||
options.notify("up");
|
||||
};
|
||||
|
||||
// Dismisses the overlay first: if the quit is cancelled downstream the
|
||||
// renderer must not be left with a stuck "Hold to Quit" hint.
|
||||
const quitNow = () => {
|
||||
release();
|
||||
options.quit();
|
||||
};
|
||||
|
||||
return (event, input) => {
|
||||
const key = input.key.toLowerCase();
|
||||
if (input.type === "keyUp") {
|
||||
if (key === "q" || key === modifierKey) release();
|
||||
return;
|
||||
}
|
||||
if (input.type !== "keyDown") return;
|
||||
|
||||
const modifierDown = options.platform === "darwin" ? input.meta : input.control;
|
||||
if (!modifierDown || input.alt || input.shift || key !== "q") {
|
||||
// Any other key (or an extra modifier) pressed mid-hold breaks the
|
||||
// gesture; without this the hold timer keeps running through the
|
||||
// interruption and the next qualifying repeat would quit early. The
|
||||
// interrupted press also stops counting toward a double tap — but only
|
||||
// here, not in release(), which runs mid-restart on an unseen-release
|
||||
// re-press and must not wipe that press's own tap timestamp.
|
||||
if (holding && !input.isAutoRepeat) {
|
||||
lastPressAt = 0;
|
||||
release();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
|
||||
if (input.isAutoRepeat) {
|
||||
if (armed && Date.now() - heldSince >= QUIT_HOLD_DURATION_MS) {
|
||||
quitNow();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const previousPressAt = lastPressAt;
|
||||
lastPressAt = now;
|
||||
// A fresh keydown while "holding" means the key came back down after a
|
||||
// release macOS never delivered — so both branches below see real taps.
|
||||
if (previousPressAt !== 0 && now - previousPressAt <= QUIT_DOUBLE_TAP_MS) {
|
||||
quitNow();
|
||||
return;
|
||||
}
|
||||
if (holding) release();
|
||||
|
||||
generation += 1;
|
||||
const pressGeneration = generation;
|
||||
holding = true;
|
||||
heldSince = now;
|
||||
options.notify("down");
|
||||
void options.isEnabled().then(
|
||||
(enabled) => {
|
||||
if (generation !== pressGeneration) return;
|
||||
if (!enabled) {
|
||||
// Hold-to-quit disabled: a single press quits immediately.
|
||||
quitNow();
|
||||
return;
|
||||
}
|
||||
armed = true;
|
||||
// No auto-repeat by then means the key was released (possibly with a
|
||||
// suppressed keyUp) or repeat is disabled; either way, don't quit.
|
||||
watchdog = setTimeout(() => {
|
||||
watchdog = undefined;
|
||||
release();
|
||||
}, QUIT_HOLD_DURATION_MS + QUIT_HOLD_RELEASE_GRACE_MS);
|
||||
},
|
||||
// A failed settings read must never strand the quit request.
|
||||
() => {
|
||||
if (generation !== pressGeneration) return;
|
||||
quitNow();
|
||||
},
|
||||
);
|
||||
};
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { ElectronBrowserHost } from "./browser/ElectronBrowserHost";
|
||||
import { PreviewAutomationHosts } from "./components/preview/PreviewAutomationHosts";
|
||||
import { QuitHoldOverlay } from "./components/QuitHoldOverlay";
|
||||
import { AppAtomRegistryProvider } from "./rpc/atomRegistry";
|
||||
import type { AppRouter } from "./router";
|
||||
import { AppRoot } from "./AppRoot";
|
||||
@@ -16,9 +17,10 @@ describe("AppRoot", () => {
|
||||
const children = Children.toArray(
|
||||
(root as ReactElement<{ readonly children: ReactNode }>).props.children,
|
||||
);
|
||||
expect(children).toHaveLength(3);
|
||||
expect(children).toHaveLength(4);
|
||||
expect(isValidElement(children[0]) && children[0].type).toBe(RouterProvider);
|
||||
expect(isValidElement(children[1]) && children[1].type).toBe(PreviewAutomationHosts);
|
||||
expect(isValidElement(children[2]) && children[2].type).toBe(ElectronBrowserHost);
|
||||
expect(isValidElement(children[3]) && children[3].type).toBe(QuitHoldOverlay);
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import { RouterProvider } from "@tanstack/react-router";
|
||||
|
||||
import { ElectronBrowserHost } from "./browser/ElectronBrowserHost";
|
||||
import { PreviewAutomationHosts } from "./components/preview/PreviewAutomationHosts";
|
||||
import { QuitHoldOverlay } from "./components/QuitHoldOverlay";
|
||||
import { AppAtomRegistryProvider } from "./rpc/atomRegistry";
|
||||
import type { AppRouter } from "./router";
|
||||
|
||||
@@ -16,6 +17,7 @@ export function AppRoot({ router }: { readonly router: AppRouter }) {
|
||||
<RouterProvider router={router} />
|
||||
<PreviewAutomationHosts />
|
||||
<ElectronBrowserHost />
|
||||
<QuitHoldOverlay />
|
||||
</AppAtomRegistryProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import { isMacPlatform } from "../lib/utils";
|
||||
|
||||
// Matches the hold duration in apps/desktop/src/window/QuitHold.ts: the hint
|
||||
// from a quick tap lingers for as long as a full hold would have taken.
|
||||
const HIDE_AFTER_RELEASE_MS = 1200;
|
||||
|
||||
/**
|
||||
* Chrome-style "Hold ⌘Q to Quit" hint. The desktop main process intercepts
|
||||
* the quit accelerator and pushes press/release states; a quick tap shows
|
||||
* this pill while a full hold quits the app.
|
||||
*/
|
||||
export function QuitHoldOverlay() {
|
||||
const [visible, setVisible] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const subscribe = window.desktopBridge?.onQuitShortcut;
|
||||
if (!subscribe) return;
|
||||
let hideTimer: number | undefined;
|
||||
const unsubscribe = subscribe((state) => {
|
||||
window.clearTimeout(hideTimer);
|
||||
if (state === "down") {
|
||||
setVisible(true);
|
||||
return;
|
||||
}
|
||||
hideTimer = window.setTimeout(() => setVisible(false), HIDE_AFTER_RELEASE_MS);
|
||||
});
|
||||
return () => {
|
||||
window.clearTimeout(hideTimer);
|
||||
unsubscribe();
|
||||
};
|
||||
}, []);
|
||||
|
||||
if (!visible) return null;
|
||||
const shortcut = isMacPlatform(navigator.platform) ? "⌘Q" : "Ctrl+Q";
|
||||
return (
|
||||
<div
|
||||
role="status"
|
||||
className="pointer-events-none fixed inset-x-0 top-[22%] z-100 flex justify-center"
|
||||
>
|
||||
<div className="rounded-full bg-neutral-700/95 px-8 py-4 text-2xl font-bold text-white shadow-xl">
|
||||
Hold {shortcut} to Quit
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -526,11 +526,15 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
...(settings.confirmThreadDelete !== DEFAULT_UNIFIED_SETTINGS.confirmThreadDelete
|
||||
? ["Delete confirmation"]
|
||||
: []),
|
||||
...(settings.confirmQuit !== DEFAULT_UNIFIED_SETTINGS.confirmQuit
|
||||
? ["Quit confirmation"]
|
||||
: []),
|
||||
...(isTextGenerationModelDirty ? ["Text generation model"] : []),
|
||||
],
|
||||
[
|
||||
isTextGenerationModelDirty,
|
||||
isBackgroundActivityDirty,
|
||||
settings.confirmQuit,
|
||||
settings.confirmThreadArchive,
|
||||
settings.confirmThreadDelete,
|
||||
settings.addProjectBaseDirectory,
|
||||
@@ -644,6 +648,7 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
addProjectBaseDirectory: DEFAULT_UNIFIED_SETTINGS.addProjectBaseDirectory,
|
||||
confirmThreadArchive: DEFAULT_UNIFIED_SETTINGS.confirmThreadArchive,
|
||||
confirmThreadDelete: DEFAULT_UNIFIED_SETTINGS.confirmThreadDelete,
|
||||
confirmQuit: DEFAULT_UNIFIED_SETTINGS.confirmQuit,
|
||||
textGenerationModelSelection: DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection,
|
||||
fontFamilySans: DEFAULT_UNIFIED_SETTINGS.fontFamilySans,
|
||||
fontFamilyComposer: DEFAULT_UNIFIED_SETTINGS.fontFamilyComposer,
|
||||
@@ -2234,6 +2239,30 @@ export function GeneralSettingsPanel() {
|
||||
}
|
||||
/>
|
||||
|
||||
{isElectron ? (
|
||||
<SettingsRow
|
||||
{...searchableSetting("quit-confirmation")}
|
||||
description="Require holding the quit shortcut before the desktop app quits. A quick tap shows a hint instead."
|
||||
resetAction={
|
||||
settings.confirmQuit !== DEFAULT_UNIFIED_SETTINGS.confirmQuit ? (
|
||||
<SettingResetButton
|
||||
label="quit confirmation"
|
||||
onClick={() =>
|
||||
updateSettings({ confirmQuit: DEFAULT_UNIFIED_SETTINGS.confirmQuit })
|
||||
}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
control={
|
||||
<Switch
|
||||
checked={settings.confirmQuit}
|
||||
onCheckedChange={(checked) => updateSettings({ confirmQuit: Boolean(checked) })}
|
||||
aria-label="Hold to quit"
|
||||
/>
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<SettingsRow
|
||||
{...searchableSetting("text-generation-model")}
|
||||
description="Default model for generated text like thread titles and source control content. Source control settings can override it with a dedicated source control writer model."
|
||||
|
||||
@@ -60,6 +60,11 @@ describe("searchSettings", () => {
|
||||
expect(searchSettings(" ", ITEMS)).toEqual([]);
|
||||
});
|
||||
|
||||
it("hides desktop-only settings from browser search", () => {
|
||||
expect(SETTINGS_SEARCH_ITEMS.some((item) => item.id === "quit-confirmation")).toBe(true);
|
||||
expect(searchSettings("quit confirmation")).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps catalog result ids unique", () => {
|
||||
const ids = SETTINGS_SEARCH_ITEMS.map((item) => item.id);
|
||||
expect(new Set(ids).size).toBe(ids.length);
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { isElectron } from "~/env";
|
||||
|
||||
export type SettingsPath =
|
||||
| "/settings/general"
|
||||
| "/settings/appearance"
|
||||
@@ -12,6 +14,9 @@ export interface SettingsSearchItem {
|
||||
readonly title: string;
|
||||
readonly to: SettingsPath;
|
||||
readonly targetId?: string;
|
||||
// Its row only renders in the desktop app, so a browser result would land on
|
||||
// an anchor that isn't there.
|
||||
readonly desktopOnly?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -149,6 +154,12 @@ export const SETTINGS_SEARCH_ITEMS = [
|
||||
title: "Delete confirmation",
|
||||
to: "/settings/general",
|
||||
},
|
||||
{
|
||||
id: "quit-confirmation",
|
||||
title: "Hold to quit",
|
||||
to: "/settings/general",
|
||||
desktopOnly: true,
|
||||
},
|
||||
{
|
||||
id: "text-generation-model",
|
||||
title: "Text generation model",
|
||||
@@ -236,5 +247,9 @@ export function searchSettings(
|
||||
const normalizedQuery = normalizeSearchText(query);
|
||||
if (normalizedQuery.length === 0) return [];
|
||||
|
||||
return items.filter((item) => normalizeSearchText(item.title).includes(normalizedQuery));
|
||||
return items.filter(
|
||||
(item) =>
|
||||
(isElectron || item.desktopOnly !== true) &&
|
||||
normalizeSearchText(item.title).includes(normalizedQuery),
|
||||
);
|
||||
}
|
||||
@@ -1080,6 +1080,12 @@ export interface DesktopBridge {
|
||||
*/
|
||||
probeRemoteEditors?: () => Promise<readonly EditorId[]>;
|
||||
onMenuAction: (listener: (action: string) => void) => () => void;
|
||||
/**
|
||||
* Hold-to-quit hint pushes: "down" when the quit shortcut is first pressed,
|
||||
* "up" when it is released before the hold completes. Optional: older
|
||||
* desktop builds never emit it.
|
||||
*/
|
||||
onQuitShortcut?: (listener: (state: "down" | "up") => void) => () => void;
|
||||
getWindowFullscreenState: () => boolean;
|
||||
onWindowFullscreenStateChange: (listener: (fullscreen: boolean) => void) => () => void;
|
||||
getUpdateState: () => Promise<DesktopUpdateState>;
|
||||
|
||||
@@ -112,6 +112,9 @@ export const FontFamilyPreference = Schema.String.check(Schema.isMaxLength(200))
|
||||
export type FontFamilyPreference = typeof FontFamilyPreference.Type;
|
||||
|
||||
export const ClientSettingsSchema = Schema.Struct({
|
||||
// Desktop-only: require holding the quit shortcut (Cmd/Ctrl+Q) before the
|
||||
// app quits; a quick tap only shows a hint. Browser clients ignore it.
|
||||
confirmQuit: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
|
||||
confirmThreadArchive: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
|
||||
confirmThreadDelete: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
|
||||
dismissedProviderUpdateNotificationKeys: Schema.Array(TrimmedNonEmptyString).pipe(
|
||||
@@ -756,6 +759,7 @@ export const ServerSettingsPatch = Schema.Struct({
|
||||
export type ServerSettingsPatch = typeof ServerSettingsPatch.Type;
|
||||
|
||||
export const ClientSettingsPatch = Schema.Struct({
|
||||
confirmQuit: Schema.optionalKey(Schema.Boolean),
|
||||
confirmThreadArchive: Schema.optionalKey(Schema.Boolean),
|
||||
confirmThreadDelete: Schema.optionalKey(Schema.Boolean),
|
||||
diffIgnoreWhitespace: Schema.optionalKey(Schema.Boolean),
|
||||
|
||||
Reference in new issue
Block a user