feat(desktop): add configurable quit shortcut confirmation (#9076)
This commit is contained in:
1 parent
ef7014d851
commit
9d1879b142
11 files changed
+365
-132
No files matched your search
@@ -128,9 +128,19 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
};
|
||||
},
|
||||
onQuitShortcut: (listener) => {
|
||||
const wrappedListener = (_event: Electron.IpcRendererEvent, state: unknown) => {
|
||||
if (state !== "down" && state !== "up") return;
|
||||
listener(state);
|
||||
const wrappedListener = (_event: Electron.IpcRendererEvent, hint: unknown) => {
|
||||
if (typeof hint !== "object" || hint === null || !("state" in hint)) return;
|
||||
if (hint.state === "up") {
|
||||
listener({ state: "up" });
|
||||
return;
|
||||
}
|
||||
if (
|
||||
hint.state === "down" &&
|
||||
"mode" in hint &&
|
||||
(hint.mode === "hold" || hint.mode === "double-click")
|
||||
) {
|
||||
listener({ state: "down", mode: hint.mode });
|
||||
}
|
||||
};
|
||||
|
||||
ipcRenderer.on(IpcChannels.QUIT_SHORTCUT_CHANNEL, wrappedListener);
|
||||
|
||||
@@ -19,7 +19,7 @@ const clientSettings: ClientSettings = {
|
||||
browserDefaultAppearance: "dark",
|
||||
browserRecordingFrameRate: 60,
|
||||
browserAutoShowFloatingPreview: false,
|
||||
confirmQuit: true,
|
||||
confirmQuit: "double-click",
|
||||
confirmThreadArchive: true,
|
||||
confirmThreadDelete: false,
|
||||
confirmThreadUnpin: false,
|
||||
|
||||
@@ -27,7 +27,7 @@ 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";
|
||||
import { makeQuitShortcutHandler } from "./QuitHold.ts";
|
||||
|
||||
const TITLEBAR_HEIGHT = 40;
|
||||
const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux
|
||||
@@ -551,12 +551,11 @@ 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({
|
||||
// Intercept the quit accelerator before the native menu sees it and apply
|
||||
// the configured direct, hold, or double-press behavior.
|
||||
const quitShortcutHandler = makeQuitShortcutHandler({
|
||||
platform: environment.platform,
|
||||
isEnabled: () =>
|
||||
getMode: () =>
|
||||
runPromise(
|
||||
Effect.map(
|
||||
clientSettings.get,
|
||||
@@ -566,9 +565,9 @@ export const make = Effect.gen(function* () {
|
||||
}),
|
||||
),
|
||||
),
|
||||
notify: (state) => {
|
||||
notify: (hint) => {
|
||||
if (!window.isDestroyed()) {
|
||||
window.webContents.send(QUIT_SHORTCUT_CHANNEL, state);
|
||||
window.webContents.send(QUIT_SHORTCUT_CHANNEL, hint);
|
||||
}
|
||||
},
|
||||
quit: () => {
|
||||
@@ -576,7 +575,7 @@ export const make = Effect.gen(function* () {
|
||||
},
|
||||
});
|
||||
window.webContents.on("before-input-event", (event, input) => {
|
||||
quitHoldHandler(event, input);
|
||||
quitShortcutHandler(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") {
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
makeQuitHoldHandler,
|
||||
QUIT_DOUBLE_TAP_MS,
|
||||
makeQuitShortcutHandler,
|
||||
QUIT_DOUBLE_PRESS_MS,
|
||||
QUIT_HOLD_DURATION_MS,
|
||||
QUIT_HOLD_RELEASE_GRACE_MS,
|
||||
} from "./QuitHold.ts";
|
||||
import type { QuitHoldKeyInput, QuitHoldState } from "./QuitHold.ts";
|
||||
import type { QuitHoldKeyInput } from "./QuitHold.ts";
|
||||
import type { QuitConfirmationMode, QuitShortcutHintEvent } from "@t3tools/contracts";
|
||||
|
||||
const HOLD_DOWN = { state: "down", mode: "hold" } as const;
|
||||
const DOUBLE_CLICK_DOWN = { state: "down", mode: "double-click" } as const;
|
||||
const UP = { state: "up" } as const;
|
||||
|
||||
function makeInput(overrides: Partial<QuitHoldKeyInput>): QuitHoldKeyInput {
|
||||
return {
|
||||
@@ -22,22 +27,22 @@ function makeInput(overrides: Partial<QuitHoldKeyInput>): QuitHoldKeyInput {
|
||||
}
|
||||
|
||||
function makeHarness(options?: {
|
||||
enabled?: boolean;
|
||||
mode?: QuitConfirmationMode;
|
||||
platform?: NodeJS.Platform;
|
||||
isEnabled?: () => Promise<boolean>;
|
||||
getMode?: () => Promise<QuitConfirmationMode>;
|
||||
}) {
|
||||
const notifications: Array<QuitHoldState> = [];
|
||||
const notifications: Array<QuitShortcutHintEvent> = [];
|
||||
const quit = vi.fn();
|
||||
const handler = makeQuitHoldHandler({
|
||||
const handler = makeQuitShortcutHandler({
|
||||
platform: options?.platform ?? "darwin",
|
||||
isEnabled: options?.isEnabled ?? (() => Promise.resolve(options?.enabled ?? true)),
|
||||
notify: (state) => notifications.push(state),
|
||||
getMode: options?.getMode ?? (() => Promise.resolve(options?.mode ?? "hold")),
|
||||
notify: (event) => notifications.push(event),
|
||||
quit,
|
||||
});
|
||||
const preventDefault = vi.fn();
|
||||
const send = async (input: QuitHoldKeyInput) => {
|
||||
handler({ preventDefault }, input);
|
||||
// Let the isEnabled promise settle.
|
||||
// Let the getMode promise settle.
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
};
|
||||
@@ -55,7 +60,7 @@ function makeHarness(options?: {
|
||||
return { notifications, quit, preventDefault, send, holdFor };
|
||||
}
|
||||
|
||||
describe("makeQuitHoldHandler", () => {
|
||||
describe("makeQuitShortcutHandler", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
@@ -69,12 +74,12 @@ describe("makeQuitHoldHandler", () => {
|
||||
const harness = makeHarness();
|
||||
await harness.send(makeInput({}));
|
||||
expect(harness.preventDefault).toHaveBeenCalledTimes(1);
|
||||
expect(harness.notifications).toEqual(["down"]);
|
||||
expect(harness.notifications).toEqual([HOLD_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"]);
|
||||
expect(harness.notifications).toEqual([HOLD_DOWN, UP]);
|
||||
});
|
||||
|
||||
it("quits after a completed hold is released", async () => {
|
||||
@@ -86,7 +91,7 @@ describe("makeQuitHoldHandler", () => {
|
||||
expect(harness.quit).not.toHaveBeenCalled();
|
||||
vi.advanceTimersByTime(QUIT_HOLD_RELEASE_GRACE_MS);
|
||||
expect(harness.quit).toHaveBeenCalledTimes(1);
|
||||
expect(harness.notifications).toEqual(["down", "up"]);
|
||||
expect(harness.notifications).toEqual([HOLD_DOWN, UP]);
|
||||
});
|
||||
|
||||
it("waits for Q release when Cmd is released first", async () => {
|
||||
@@ -108,7 +113,7 @@ describe("makeQuitHoldHandler", () => {
|
||||
await harness.send(makeInput({}));
|
||||
await harness.holdFor(500);
|
||||
await harness.send(makeInput({ type: "keyUp" }));
|
||||
expect(harness.notifications).toEqual(["down", "up"]);
|
||||
expect(harness.notifications).toEqual([HOLD_DOWN, UP]);
|
||||
vi.advanceTimersByTime((QUIT_HOLD_DURATION_MS + QUIT_HOLD_RELEASE_GRACE_MS) * 2);
|
||||
expect(harness.quit).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -117,61 +122,179 @@ describe("makeQuitHoldHandler", () => {
|
||||
const harness = makeHarness();
|
||||
await harness.send(makeInput({}));
|
||||
await harness.send(makeInput({ type: "keyUp", key: "Meta", meta: false }));
|
||||
expect(harness.notifications).toEqual(["down", "up"]);
|
||||
expect(harness.notifications).toEqual([HOLD_DOWN, UP]);
|
||||
vi.advanceTimersByTime((QUIT_HOLD_DURATION_MS + QUIT_HOLD_RELEASE_GRACE_MS) * 2);
|
||||
expect(harness.quit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("quits without showing a hint when hold-to-quit is disabled", async () => {
|
||||
const harness = makeHarness({ enabled: false });
|
||||
it("quits without showing a hint in direct mode", async () => {
|
||||
const harness = makeHarness({ mode: "direct" });
|
||||
await harness.send(makeInput({}));
|
||||
expect(harness.quit).toHaveBeenCalledTimes(1);
|
||||
expect(harness.notifications).toEqual([]);
|
||||
});
|
||||
|
||||
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> = [];
|
||||
it("honors direct mode when the key is released before its mode read settles", async () => {
|
||||
let resolveMode: ((mode: QuitConfirmationMode) => void) | undefined;
|
||||
const harness = makeHarness({
|
||||
isEnabled: () => new Promise((resolve) => resolvers.push(resolve)),
|
||||
getMode: () =>
|
||||
new Promise((resolve) => {
|
||||
resolveMode = 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);
|
||||
|
||||
resolveMode?.("direct");
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(harness.quit).toHaveBeenCalledTimes(1);
|
||||
expect(harness.notifications).toEqual([]);
|
||||
});
|
||||
|
||||
it("does not arm hold mode after a released key's mode read settles", async () => {
|
||||
let resolveMode: ((mode: QuitConfirmationMode) => void) | undefined;
|
||||
const harness = makeHarness({
|
||||
getMode: () =>
|
||||
new Promise((resolve) => {
|
||||
resolveMode = resolve;
|
||||
}),
|
||||
});
|
||||
await harness.send(makeInput({}));
|
||||
await harness.send(makeInput({ type: "keyUp" }));
|
||||
|
||||
resolveMode?.("hold");
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(harness.quit).not.toHaveBeenCalled();
|
||||
expect(harness.notifications).toEqual([]);
|
||||
});
|
||||
|
||||
it("honors a quick double press when both key releases beat their mode reads", async () => {
|
||||
const resolvers: Array<(mode: QuitConfirmationMode) => void> = [];
|
||||
const harness = makeHarness({
|
||||
getMode: () => new Promise((resolve) => resolvers.push(resolve)),
|
||||
});
|
||||
await harness.send(makeInput({}));
|
||||
await harness.send(makeInput({ type: "keyUp" }));
|
||||
vi.advanceTimersByTime(QUIT_DOUBLE_PRESS_MS - 100);
|
||||
await harness.send(makeInput({}));
|
||||
await harness.send(makeInput({ type: "keyUp" }));
|
||||
|
||||
resolvers[1]?.("double-click");
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(harness.quit).toHaveBeenCalledTimes(1);
|
||||
expect(harness.notifications).toEqual([]);
|
||||
});
|
||||
|
||||
it("discards a stale mode resolution from a superseded press", async () => {
|
||||
// Press #1's mode is still pending when the user releases and
|
||||
// presses again; its late resolution must not act for press #2.
|
||||
const resolvers: Array<(mode: QuitConfirmationMode) => void> = [];
|
||||
const harness = makeHarness({
|
||||
getMode: () => new Promise((resolve) => resolvers.push(resolve)),
|
||||
});
|
||||
await harness.send(makeInput({}));
|
||||
await harness.send(makeInput({ type: "keyUp" }));
|
||||
// Outside the double-press window, so the second press starts a new hold.
|
||||
vi.advanceTimersByTime(QUIT_DOUBLE_PRESS_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);
|
||||
// Press #1 resolves late with "direct". It must not quit press #2.
|
||||
resolvers[0]?.("direct");
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
expect(harness.quit).not.toHaveBeenCalled();
|
||||
|
||||
// Press #2 resolves enabled and completes a full hold.
|
||||
resolvers[1]?.(true);
|
||||
// Press #2 resolves to hold and completes the gesture.
|
||||
resolvers[1]?.("hold");
|
||||
await harness.holdFor(QUIT_HOLD_DURATION_MS + 200);
|
||||
await harness.send(makeInput({ type: "keyUp" }));
|
||||
expect(harness.quit).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("quits on a quick double tap, even when the first release was never seen", async () => {
|
||||
const harness = makeHarness();
|
||||
it("quits on a quick double press in double-click mode when the first release is unseen", async () => {
|
||||
const harness = makeHarness({ mode: "double-click" });
|
||||
await harness.send(makeInput({}));
|
||||
vi.advanceTimersByTime(QUIT_DOUBLE_TAP_MS - 100);
|
||||
vi.advanceTimersByTime(QUIT_DOUBLE_PRESS_MS - 100);
|
||||
await harness.send(makeInput({}));
|
||||
expect(harness.quit).toHaveBeenCalledTimes(1);
|
||||
expect(harness.notifications).toEqual([DOUBLE_CLICK_DOWN, UP]);
|
||||
});
|
||||
|
||||
it("treats two slow taps as separate presses", async () => {
|
||||
it("keeps the double-press hint visible after key release until the window ends", async () => {
|
||||
const harness = makeHarness({ mode: "double-click" });
|
||||
await harness.send(makeInput({}));
|
||||
vi.advanceTimersByTime(100);
|
||||
await harness.send(makeInput({ type: "keyUp" }));
|
||||
expect(harness.notifications).toEqual([DOUBLE_CLICK_DOWN]);
|
||||
|
||||
vi.advanceTimersByTime(QUIT_DOUBLE_PRESS_MS - 101);
|
||||
expect(harness.notifications).toEqual([DOUBLE_CLICK_DOWN]);
|
||||
vi.advanceTimersByTime(1);
|
||||
expect(harness.notifications).toEqual([DOUBLE_CLICK_DOWN, UP]);
|
||||
});
|
||||
|
||||
it("accepts a second full shortcut after the modifier is released and pressed again", async () => {
|
||||
const harness = makeHarness({ mode: "double-click" });
|
||||
await harness.send(makeInput({}));
|
||||
await harness.send(makeInput({ type: "keyUp" }));
|
||||
await harness.send(makeInput({ type: "keyUp", key: "Meta", meta: false }));
|
||||
vi.advanceTimersByTime(100);
|
||||
|
||||
await harness.send(makeInput({ key: "Meta" }));
|
||||
await harness.send(makeInput({}));
|
||||
|
||||
expect(harness.quit).toHaveBeenCalledTimes(1);
|
||||
expect(harness.notifications).toEqual([DOUBLE_CLICK_DOWN, UP]);
|
||||
});
|
||||
|
||||
it("expires a delayed double-press hint from keydown rather than mode resolution", async () => {
|
||||
let resolveMode: ((mode: QuitConfirmationMode) => void) | undefined;
|
||||
const harness = makeHarness({
|
||||
getMode: () =>
|
||||
new Promise((resolve) => {
|
||||
resolveMode = resolve;
|
||||
}),
|
||||
});
|
||||
await harness.send(makeInput({}));
|
||||
vi.advanceTimersByTime(100);
|
||||
await harness.send(makeInput({ type: "keyUp" }));
|
||||
vi.advanceTimersByTime(100);
|
||||
resolveMode?.("double-click");
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
expect(harness.notifications).toEqual([DOUBLE_CLICK_DOWN]);
|
||||
|
||||
vi.advanceTimersByTime(QUIT_DOUBLE_PRESS_MS - 201);
|
||||
expect(harness.notifications).toEqual([DOUBLE_CLICK_DOWN]);
|
||||
vi.advanceTimersByTime(1);
|
||||
expect(harness.notifications).toEqual([DOUBLE_CLICK_DOWN, UP]);
|
||||
});
|
||||
|
||||
it("treats two slow presses as separate attempts in double-click mode", async () => {
|
||||
const harness = makeHarness({ mode: "double-click" });
|
||||
await harness.send(makeInput({}));
|
||||
await harness.send(makeInput({ type: "keyUp" }));
|
||||
vi.advanceTimersByTime(QUIT_DOUBLE_PRESS_MS + 100);
|
||||
await harness.send(makeInput({}));
|
||||
expect(harness.quit).not.toHaveBeenCalled();
|
||||
expect(harness.notifications).toEqual([DOUBLE_CLICK_DOWN, UP, DOUBLE_CLICK_DOWN]);
|
||||
});
|
||||
|
||||
it("does not treat two quick presses as a quit in hold mode", async () => {
|
||||
const harness = makeHarness();
|
||||
await harness.send(makeInput({}));
|
||||
await harness.send(makeInput({ type: "keyUp" }));
|
||||
vi.advanceTimersByTime(QUIT_DOUBLE_TAP_MS + 100);
|
||||
vi.advanceTimersByTime(QUIT_DOUBLE_PRESS_MS - 100);
|
||||
await harness.send(makeInput({}));
|
||||
expect(harness.quit).not.toHaveBeenCalled();
|
||||
expect(harness.notifications).toEqual(["down", "up", "down"]);
|
||||
expect(harness.notifications).toEqual([HOLD_DOWN, UP, HOLD_DOWN]);
|
||||
});
|
||||
|
||||
it("cancels the hold when another key interrupts it", async () => {
|
||||
@@ -180,21 +303,20 @@ describe("makeQuitHoldHandler", () => {
|
||||
await harness.holdFor(500);
|
||||
// Shift pressed mid-hold breaks the gesture...
|
||||
await harness.send(makeInput({ shift: true }));
|
||||
expect(harness.notifications).toEqual(["down", "up"]);
|
||||
expect(harness.notifications).toEqual([HOLD_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();
|
||||
it("does not count an interrupted press toward a double press", async () => {
|
||||
const harness = makeHarness({ mode: "double-click" });
|
||||
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.
|
||||
// A fresh press right after the interruption starts a new attempt.
|
||||
await harness.send(makeInput({}));
|
||||
expect(harness.quit).not.toHaveBeenCalled();
|
||||
expect(harness.notifications).toEqual(["down", "up", "down"]);
|
||||
expect(harness.notifications).toEqual([DOUBLE_CLICK_DOWN, UP, DOUBLE_CLICK_DOWN]);
|
||||
});
|
||||
|
||||
it("ignores other shortcuts", async () => {
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
// @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 after the shortcut has been held for QUIT_HOLD_DURATION_MS
|
||||
// and released.
|
||||
// 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.
|
||||
import type { QuitConfirmationMode, QuitShortcutHintEvent } from "@t3tools/contracts";
|
||||
|
||||
// The quit accelerator is intercepted in before-input-event, which runs
|
||||
// before the native menu accelerator. Quitting from the application menu is
|
||||
// untouched and always 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;
|
||||
export const QUIT_DOUBLE_PRESS_MS = 500;
|
||||
// "Still held" is proven by auto-repeat keydowns, not by the absence of a
|
||||
// release: macOS suppresses a letter keyUp while the command key is down, so a
|
||||
// tap release can go completely unseen and a release-based timer would quit
|
||||
@@ -18,8 +15,6 @@ export const QUIT_DOUBLE_TAP_MS = 500;
|
||||
// auto-repeat disabled fall back to the application menu Quit action.
|
||||
export const QUIT_HOLD_RELEASE_GRACE_MS = 600;
|
||||
|
||||
export type QuitHoldState = "down" | "up";
|
||||
|
||||
export interface QuitHoldKeyInput {
|
||||
readonly type: string;
|
||||
readonly key: string;
|
||||
@@ -30,27 +25,29 @@ export interface QuitHoldKeyInput {
|
||||
readonly isAutoRepeat: boolean;
|
||||
}
|
||||
|
||||
export interface QuitHoldOptions {
|
||||
export interface QuitShortcutOptions {
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly isEnabled: () => Promise<boolean>;
|
||||
readonly notify: (state: QuitHoldState) => void;
|
||||
readonly getMode: () => Promise<QuitConfirmationMode>;
|
||||
readonly notify: (event: QuitShortcutHintEvent) => void;
|
||||
readonly quit: () => void;
|
||||
}
|
||||
|
||||
export function makeQuitHoldHandler(
|
||||
options: QuitHoldOptions,
|
||||
export function makeQuitShortcutHandler(
|
||||
options: QuitShortcutOptions,
|
||||
): (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 complete the hold when armed.
|
||||
let mode: QuitConfirmationMode | undefined;
|
||||
let notified = false;
|
||||
// Set once getMode resolves to hold; auto-repeats may only complete the hold when armed.
|
||||
let armed = false;
|
||||
let quitOnRelease = 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.
|
||||
// Incremented when a press is superseded or explicitly cancelled. A plain
|
||||
// key release does not invalidate its pending mode read: direct mode and a
|
||||
// completed second press must still be honored after that read settles.
|
||||
let generation = 0;
|
||||
|
||||
const clearWatchdog = () => {
|
||||
@@ -60,19 +57,24 @@ export function makeQuitHoldHandler(
|
||||
}
|
||||
};
|
||||
|
||||
const release = () => {
|
||||
if (!holding) return;
|
||||
const shouldNotify = armed || quitOnRelease;
|
||||
generation += 1;
|
||||
const release = (cancelPendingMode = true, keepDoublePressHint = false) => {
|
||||
if (!holding && !notified) return;
|
||||
const keepHint = keepDoublePressHint && mode === "double-click" && notified;
|
||||
if (cancelPendingMode) generation += 1;
|
||||
holding = false;
|
||||
armed = false;
|
||||
quitOnRelease = false;
|
||||
if (keepHint) return;
|
||||
|
||||
mode = undefined;
|
||||
clearWatchdog();
|
||||
if (shouldNotify) options.notify("up");
|
||||
if (notified) {
|
||||
notified = false;
|
||||
options.notify({ state: "up" });
|
||||
}
|
||||
};
|
||||
|
||||
// Dismisses any overlay first: if the quit is cancelled downstream the
|
||||
// renderer must not be left with a stuck "Hold to Quit" hint.
|
||||
// Dismisses any overlay first so a cancelled quit cannot leave a stale hint.
|
||||
const quitNow = () => {
|
||||
release();
|
||||
options.quit();
|
||||
@@ -83,11 +85,11 @@ export function makeQuitHoldHandler(
|
||||
if (input.type === "keyUp") {
|
||||
if (key === "q") {
|
||||
const shouldQuit = quitOnRelease;
|
||||
release();
|
||||
release(false, true);
|
||||
if (shouldQuit) options.quit();
|
||||
} else if (key === modifierKey) {
|
||||
if (!quitOnRelease) {
|
||||
release();
|
||||
release(false, true);
|
||||
} else {
|
||||
watchdog = setTimeout(quitNow, QUIT_HOLD_RELEASE_GRACE_MS);
|
||||
}
|
||||
@@ -104,13 +106,17 @@ export function makeQuitHoldHandler(
|
||||
|
||||
const modifierDown = options.platform === "darwin" ? input.meta : input.control;
|
||||
if (!modifierDown || input.alt || input.shift || key !== "q") {
|
||||
// Re-pressing the platform modifier is the first half of a second full
|
||||
// quit shortcut, so it must not cancel an active double-press window.
|
||||
if (key === modifierKey && !input.alt && !input.shift) return;
|
||||
|
||||
// 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
|
||||
// interrupted press also stops counting toward a double press, 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) {
|
||||
if ((holding || notified) && !input.isAutoRepeat) {
|
||||
lastPressAt = 0;
|
||||
release();
|
||||
}
|
||||
@@ -120,7 +126,7 @@ export function makeQuitHoldHandler(
|
||||
event.preventDefault();
|
||||
|
||||
if (input.isAutoRepeat) {
|
||||
if (armed && Date.now() - heldSince >= QUIT_HOLD_DURATION_MS) {
|
||||
if (mode === "hold" && armed && Date.now() - heldSince >= QUIT_HOLD_DURATION_MS) {
|
||||
armed = false;
|
||||
quitOnRelease = true;
|
||||
clearWatchdog();
|
||||
@@ -131,28 +137,51 @@ export function makeQuitHoldHandler(
|
||||
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();
|
||||
// A fresh keydown supersedes the current physical hold or the hint kept
|
||||
// alive after a detected release.
|
||||
if (holding || notified) release();
|
||||
|
||||
generation += 1;
|
||||
const pressGeneration = generation;
|
||||
holding = true;
|
||||
heldSince = now;
|
||||
void options.isEnabled().then(
|
||||
(enabled) => {
|
||||
void options.getMode().then(
|
||||
(resolvedMode) => {
|
||||
if (generation !== pressGeneration) return;
|
||||
if (!enabled) {
|
||||
// Hold-to-quit disabled: a single press quits immediately.
|
||||
if (resolvedMode === "direct") {
|
||||
quitNow();
|
||||
return;
|
||||
}
|
||||
if (
|
||||
resolvedMode === "double-click" &&
|
||||
previousPressAt !== 0 &&
|
||||
now - previousPressAt <= QUIT_DOUBLE_PRESS_MS
|
||||
) {
|
||||
quitNow();
|
||||
return;
|
||||
}
|
||||
|
||||
if (resolvedMode === "double-click") {
|
||||
const remainingMs = QUIT_DOUBLE_PRESS_MS - (Date.now() - now);
|
||||
if (remainingMs <= 0) {
|
||||
release();
|
||||
return;
|
||||
}
|
||||
mode = resolvedMode;
|
||||
notified = true;
|
||||
options.notify({ state: "down", mode: resolvedMode });
|
||||
watchdog = setTimeout(release, remainingMs);
|
||||
return;
|
||||
}
|
||||
|
||||
// A hold cannot be armed after its physical press has ended.
|
||||
if (!holding) return;
|
||||
|
||||
mode = resolvedMode;
|
||||
notified = true;
|
||||
options.notify({ state: "down", mode: resolvedMode });
|
||||
|
||||
armed = true;
|
||||
options.notify("down");
|
||||
// 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(() => {
|
||||
|
||||
@@ -2,29 +2,34 @@ 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;
|
||||
// A released hold hint lingers for the original hold duration. Double-press
|
||||
// hints disappear as soon as their acceptance window closes.
|
||||
const HOLD_HINT_LINGER_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.
|
||||
* The desktop main process intercepts the quit accelerator and pushes
|
||||
* press/release states while it waits for a hold or second press.
|
||||
*/
|
||||
export function QuitHoldOverlay() {
|
||||
const [visible, setVisible] = useState(false);
|
||||
const [visibleMode, setVisibleMode] = useState<"hold" | "double-click" | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const subscribe = window.desktopBridge?.onQuitShortcut;
|
||||
if (!subscribe) return;
|
||||
let hideTimer: number | undefined;
|
||||
const unsubscribe = subscribe((state) => {
|
||||
let pressedMode: "hold" | "double-click" = "hold";
|
||||
const unsubscribe = subscribe((hint) => {
|
||||
window.clearTimeout(hideTimer);
|
||||
if (state === "down") {
|
||||
setVisible(true);
|
||||
if (hint.state === "down") {
|
||||
pressedMode = hint.mode;
|
||||
setVisibleMode(hint.mode);
|
||||
return;
|
||||
}
|
||||
hideTimer = window.setTimeout(() => setVisible(false), HIDE_AFTER_RELEASE_MS);
|
||||
if (pressedMode === "double-click") {
|
||||
setVisibleMode(null);
|
||||
return;
|
||||
}
|
||||
hideTimer = window.setTimeout(() => setVisibleMode(null), HOLD_HINT_LINGER_MS);
|
||||
});
|
||||
return () => {
|
||||
window.clearTimeout(hideTimer);
|
||||
@@ -32,15 +37,17 @@ export function QuitHoldOverlay() {
|
||||
};
|
||||
}, []);
|
||||
|
||||
if (!visible) return null;
|
||||
if (!visibleMode) return null;
|
||||
const shortcut = isMacPlatform(navigator.platform) ? "⌘Q" : "Ctrl+Q";
|
||||
const message =
|
||||
visibleMode === "hold" ? `Hold ${shortcut} to Quit` : `Press ${shortcut} again to Quit`;
|
||||
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
|
||||
{message}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -34,6 +34,7 @@ import {
|
||||
MIN_PROMPT_FONT_SIZE,
|
||||
MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS,
|
||||
MIN_TERMINAL_FONT_SIZE,
|
||||
type QuitConfirmationMode,
|
||||
} from "@t3tools/contracts/settings";
|
||||
import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings";
|
||||
import { createModelSelection } from "@t3tools/shared/model";
|
||||
@@ -163,6 +164,12 @@ const TIMESTAMP_FORMAT_LABELS = {
|
||||
"24-hour": "24-hour",
|
||||
} as const;
|
||||
|
||||
const QUIT_CONFIRMATION_MODE_LABELS: Record<QuitConfirmationMode, string> = {
|
||||
direct: "Direct",
|
||||
hold: "Hold",
|
||||
"double-click": "Double press",
|
||||
};
|
||||
|
||||
const BACKGROUND_ACTIVITY_PROFILE_LABELS: Record<BackgroundActivityProfile, string> = {
|
||||
balanced: "Balanced",
|
||||
performance: "Performance",
|
||||
@@ -542,9 +549,7 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
...(settings.confirmThreadDelete !== DEFAULT_UNIFIED_SETTINGS.confirmThreadDelete
|
||||
? ["Delete confirmation"]
|
||||
: []),
|
||||
...(settings.confirmQuit !== DEFAULT_UNIFIED_SETTINGS.confirmQuit
|
||||
? ["Quit confirmation"]
|
||||
: []),
|
||||
...(settings.confirmQuit !== DEFAULT_UNIFIED_SETTINGS.confirmQuit ? ["Quit shortcut"] : []),
|
||||
...(isTextGenerationModelDirty ? ["Text generation model"] : []),
|
||||
...getChangedBrowserSettingLabels(settings),
|
||||
...(settings.enableAgentBrowserAccess !== DEFAULT_UNIFIED_SETTINGS.enableAgentBrowserAccess
|
||||
@@ -2422,11 +2427,11 @@ 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."
|
||||
description="Choose whether the desktop app quits immediately, after a hold, or after two quick presses."
|
||||
resetAction={
|
||||
settings.confirmQuit !== DEFAULT_UNIFIED_SETTINGS.confirmQuit ? (
|
||||
<SettingResetButton
|
||||
label="quit confirmation"
|
||||
label="quit shortcut behavior"
|
||||
onClick={() =>
|
||||
updateSettings({ confirmQuit: DEFAULT_UNIFIED_SETTINGS.confirmQuit })
|
||||
}
|
||||
@@ -2434,11 +2439,25 @@ export function GeneralSettingsPanel() {
|
||||
) : null
|
||||
}
|
||||
control={
|
||||
<Switch
|
||||
checked={settings.confirmQuit}
|
||||
onCheckedChange={(checked) => updateSettings({ confirmQuit: Boolean(checked) })}
|
||||
aria-label="Hold to quit"
|
||||
/>
|
||||
<Select
|
||||
value={settings.confirmQuit}
|
||||
onValueChange={(value) => {
|
||||
if (value === "direct" || value === "hold" || value === "double-click") {
|
||||
updateSettings({ confirmQuit: value });
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-40" aria-label="Quit shortcut behavior">
|
||||
<SelectValue>{QUIT_CONFIRMATION_MODE_LABELS[settings.confirmQuit]}</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectPopup align="end" alignItemWithTrigger={false}>
|
||||
{Object.entries(QUIT_CONFIRMATION_MODE_LABELS).map(([value, label]) => (
|
||||
<SelectItem hideIndicator key={value} value={value}>
|
||||
{label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
@@ -238,9 +238,9 @@ export const SETTINGS_SEARCH_ITEMS = [
|
||||
},
|
||||
{
|
||||
id: "quit-confirmation",
|
||||
title: "Hold to quit",
|
||||
title: "Quit shortcut",
|
||||
to: "/settings/general",
|
||||
searchTerms: ["confirmation shortcut desktop app exit"],
|
||||
searchTerms: ["confirmation desktop app exit direct hold double click press twice"],
|
||||
desktopOnly: true,
|
||||
},
|
||||
{
|
||||
|
||||
@@ -91,7 +91,7 @@ import { EnvironmentId } from "./baseSchemas.ts";
|
||||
import { AuthAccessTokenResult, AuthSessionState, AuthWebSocketTicketResult } from "./auth.ts";
|
||||
import { AdvertisedEndpoint } from "./remoteAccess.ts";
|
||||
import { ExecutionEnvironmentDescriptor } from "./environment.ts";
|
||||
import type { ClientSettings } from "./settings.ts";
|
||||
import type { ClientSettings, QuitConfirmationMode } from "./settings.ts";
|
||||
import type { EditorId } from "./editor.ts";
|
||||
import type {
|
||||
SourceControlCloneRepositoryInput,
|
||||
@@ -116,6 +116,10 @@ export interface ContextMenuItem<T extends string = string> {
|
||||
children?: readonly ContextMenuItem<T>[];
|
||||
}
|
||||
|
||||
export type QuitShortcutHintEvent =
|
||||
| { readonly state: "down"; readonly mode: Exclude<QuitConfirmationMode, "direct"> }
|
||||
| { readonly state: "up" };
|
||||
|
||||
export interface ContextMenuItemSchemaType {
|
||||
readonly id: string;
|
||||
readonly label: string;
|
||||
@@ -1140,11 +1144,10 @@ 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.
|
||||
* Quit-confirmation hint pushes. Optional: older desktop builds never emit
|
||||
* them.
|
||||
*/
|
||||
onQuitShortcut?: (listener: (state: "down" | "up") => void) => () => void;
|
||||
onQuitShortcut?: (listener: (event: QuitShortcutHintEvent) => void) => () => void;
|
||||
getWindowFullscreenState: () => boolean;
|
||||
onWindowFullscreenStateChange: (listener: (fullscreen: boolean) => void) => () => void;
|
||||
getUpdateState: () => Promise<DesktopUpdateState>;
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
|
||||
const decodeClientSettings = Schema.decodeUnknownSync(ClientSettingsSchema);
|
||||
const decodeClientSettingsPatch = Schema.decodeUnknownSync(ClientSettingsPatch);
|
||||
const encodeClientSettings = Schema.encodeSync(ClientSettingsSchema);
|
||||
const decodeServerSettings = Schema.decodeUnknownSync(ServerSettings);
|
||||
const decodeServerSettingsPatch = Schema.decodeUnknownSync(ServerSettingsPatch);
|
||||
const encodeServerSettings = Schema.encodeSync(ServerSettings);
|
||||
@@ -66,6 +67,31 @@ describe("ClientSettings word wrap", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("ClientSettings quit confirmation", () => {
|
||||
it("defaults to hold", () => {
|
||||
expect(decodeClientSettings({}).confirmQuit).toBe("hold");
|
||||
});
|
||||
|
||||
it.each(["direct", "hold", "double-click"] as const)("accepts the %s mode", (mode) => {
|
||||
expect(decodeClientSettings({ confirmQuit: mode }).confirmQuit).toBe(mode);
|
||||
expect(decodeClientSettingsPatch({ confirmQuit: mode }).confirmQuit).toBe(mode);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[true, "hold"],
|
||||
[false, "direct"],
|
||||
] as const)("migrates the legacy %s value to %s", (legacyValue, mode) => {
|
||||
const settings = decodeClientSettings({ confirmQuit: legacyValue });
|
||||
|
||||
expect(settings.confirmQuit).toBe(mode);
|
||||
expect(encodeClientSettings(settings).confirmQuit).toBe(mode);
|
||||
});
|
||||
|
||||
it("rejects legacy booleans at the patch boundary", () => {
|
||||
expect(() => decodeClientSettingsPatch({ confirmQuit: true })).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("ClientSettings browser recording frame rate", () => {
|
||||
it("defaults to 30 fps", () => {
|
||||
expect(decodeClientSettings({}).browserRecordingFrameRate).toBe(30);
|
||||
|
||||
@@ -124,6 +124,22 @@ export const EnvironmentIdentificationMode = Schema.Literals(["artwork", "pill",
|
||||
export type EnvironmentIdentificationMode = typeof EnvironmentIdentificationMode.Type;
|
||||
export const DEFAULT_ENVIRONMENT_IDENTIFICATION_MODE: EnvironmentIdentificationMode = "artwork";
|
||||
|
||||
export const QuitConfirmationMode = Schema.Literals(["direct", "hold", "double-click"]);
|
||||
export type QuitConfirmationMode = typeof QuitConfirmationMode.Type;
|
||||
export const DEFAULT_QUIT_CONFIRMATION_MODE: QuitConfirmationMode = "hold";
|
||||
|
||||
const LegacyConfirmQuit = Schema.Boolean.pipe(
|
||||
Schema.decodeTo(
|
||||
QuitConfirmationMode,
|
||||
SchemaTransformation.transform({
|
||||
decode: (confirmQuit): QuitConfirmationMode => (confirmQuit ? "hold" : "direct"),
|
||||
encode: (mode) => mode === "hold",
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const QuitConfirmationModeSetting = Schema.Union([QuitConfirmationMode, LegacyConfirmQuit]);
|
||||
|
||||
/**
|
||||
* A user-chosen font family (a single name or a comma-separated list). Empty
|
||||
* means "use the app default"; clients compose their own fallback stacks.
|
||||
@@ -183,9 +199,11 @@ export const ClientSettingsSchema = Schema.Struct({
|
||||
browserAutoShowFloatingPreview: Schema.Boolean.pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed(DEFAULT_BROWSER_AUTO_SHOW_FLOATING_PREVIEW)),
|
||||
),
|
||||
// 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))),
|
||||
// Desktop-only. Boolean values from older settings files decode to their
|
||||
// equivalent mode and encode back as the canonical string value.
|
||||
confirmQuit: QuitConfirmationModeSetting.pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed(DEFAULT_QUIT_CONFIRMATION_MODE)),
|
||||
),
|
||||
confirmThreadArchive: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
|
||||
confirmThreadDelete: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
|
||||
confirmThreadUnpin: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
|
||||
@@ -938,7 +956,7 @@ export const ClientSettingsPatch = Schema.Struct({
|
||||
browserDefaultAppearance: Schema.optionalKey(PreviewAppearancePreference),
|
||||
browserRecordingFrameRate: Schema.optionalKey(BrowserRecordingFrameRate),
|
||||
browserAutoShowFloatingPreview: Schema.optionalKey(Schema.Boolean),
|
||||
confirmQuit: Schema.optionalKey(Schema.Boolean),
|
||||
confirmQuit: Schema.optionalKey(QuitConfirmationMode),
|
||||
confirmThreadArchive: Schema.optionalKey(Schema.Boolean),
|
||||
confirmThreadDelete: Schema.optionalKey(Schema.Boolean),
|
||||
confirmThreadUnpin: Schema.optionalKey(Schema.Boolean),
|
||||
|
||||
Reference in new issue
Block a user