Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

feat(desktop): complete quit shortcut confirmation modes (#222)

Leo201466291f8c
diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts
index 541568f63..0aa3c3706 100644
--- a/apps/desktop/src/preload.ts
+++ b/apps/desktop/src/preload.ts
@@ -121,9 +121,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);
diff --git a/apps/desktop/src/settings/DesktopClientSettings.test.ts b/apps/desktop/src/settings/DesktopClientSettings.test.ts
index d8fba8cb7..28f7f78ff 100644
--- a/apps/desktop/src/settings/DesktopClientSettings.test.ts
+++ b/apps/desktop/src/settings/DesktopClientSettings.test.ts
@@ -20,7 +20,7 @@ const clientSettings: ClientSettings = {
browserDefaultZoomFactor: 1.25,
browserDefaultAppearance: "dark",
browserAutoShowFloatingPreview: false,
- confirmQuit: true,
+ confirmQuit: "hold",
confirmThreadArchive: true,
confirmThreadDelete: false,
dismissedProviderUpdateNotificationKeys: [],
@@ -186,7 +186,8 @@ describe("DesktopClientSettings", () => {
environment.clientSettingsPath,
`{
"settings": {
- "timestampFormat": "12-hour"
+ "timestampFormat": "12-hour",
+ "confirmQuit": false
}
}\n`,
);
@@ -195,6 +196,32 @@ describe("DesktopClientSettings", () => {
assert.isTrue(Option.isSome(persisted));
if (Option.isSome(persisted)) {
assert.equal(persisted.value.timestampFormat, "12-hour");
+ assert.equal(persisted.value.confirmQuit, "direct");
+ }
+ }),
+ ),
+ );
+
+ it.effect("migrates a wrapped boolean confirmQuit true to hold", () =>
+ withClientSettings(
+ Effect.gen(function* () {
+ const environment = yield* DesktopEnvironment.DesktopEnvironment;
+ const fileSystem = yield* FileSystem.FileSystem;
+ const settings = yield* DesktopClientSettings.DesktopClientSettings;
+ yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
+ yield* fileSystem.writeFileString(
+ environment.clientSettingsPath,
+ `{
+ "settings": {
+ "confirmQuit": true
+ }
+ }\n`,
+ );
+
+ const persisted = yield* settings.get;
+ assert.isTrue(Option.isSome(persisted));
+ if (Option.isSome(persisted)) {
+ assert.equal(persisted.value.confirmQuit, "hold");
}
}),
),
diff --git a/apps/desktop/src/window/DesktopWindow.test.ts b/apps/desktop/src/window/DesktopWindow.test.ts
index 39a93f460..c9e04eb91 100644
--- a/apps/desktop/src/window/DesktopWindow.test.ts
+++ b/apps/desktop/src/window/DesktopWindow.test.ts
@@ -105,6 +105,8 @@ function makeFakeBrowserWindow() {
restore: vi.fn(),
setBackgroundColor: vi.fn(),
setAutoHideCursor: vi.fn(),
+ setFullScreen: vi.fn(),
+ setOpacity: vi.fn(),
setTitle: vi.fn(),
setTitleBarOverlay: vi.fn(),
show: vi.fn(),
@@ -127,6 +129,8 @@ function makeFakeBrowserWindow() {
setZoomLevel: webContents.setZoomLevel,
setBackgroundThrottling: webContents.setBackgroundThrottling,
setAutoHideCursor: window.setAutoHideCursor,
+ setFullScreen: window.setFullScreen,
+ setOpacity: window.setOpacity,
webContentsListeners,
windowListeners,
};
@@ -394,6 +398,25 @@ const makeSplashScenario = (createOutcomes: readonly (Electron.BrowserWindow | n
});
describe("DesktopWindow", () => {
+ it("leaves fullscreen before concealing a pending quit", () => {
+ const fakeWindow = makeFakeBrowserWindow();
+
+ DesktopWindow.concealPendingQuitWindow(fakeWindow.window);
+ assert.deepEqual(fakeWindow.setOpacity.mock.calls, [[0]]);
+
+ fakeWindow.setOpacity.mockClear();
+ fakeWindow.isFullScreen.mockReturnValue(true);
+ DesktopWindow.concealPendingQuitWindow(fakeWindow.window);
+ assert.deepEqual(fakeWindow.setFullScreen.mock.calls, [[false]]);
+ assert.deepEqual(fakeWindow.setOpacity.mock.calls, [[0]]);
+
+ fakeWindow.setOpacity.mockClear();
+ fakeWindow.isFullScreen.mockReturnValue(false);
+ fakeWindow.isDestroyed.mockReturnValue(true);
+ DesktopWindow.concealPendingQuitWindow(fakeWindow.window);
+ assert.equal(fakeWindow.setOpacity.mock.calls.length, 0);
+ });
+
it("restores bounds only when the window fits within a connected display", () => {
const persistedBounds = { x: 2040, y: 80, width: 1320, height: 880 };
const displays = [
diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts
index 0097954da..8d7feb220 100644
--- a/apps/desktop/src/window/DesktopWindow.ts
+++ b/apps/desktop/src/window/DesktopWindow.ts
@@ -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
@@ -207,6 +207,21 @@ export function isRetryableDevelopmentRendererLoadFailure(input: {
);
}
+export function concealPendingQuitWindow(
+ window: Pick<
+ Electron.BrowserWindow,
+ "isDestroyed" | "isFullScreen" | "setFullScreen" | "setOpacity"
+ >,
+): void {
+ if (window.isDestroyed()) return;
+ if (window.isFullScreen()) {
+ window.setFullScreen(false);
+ }
+ // Electron implements window opacity on macOS and Windows. Linux keeps the
+ // release-gated quit behavior but cannot make the pending window disappear.
+ window.setOpacity(0);
+}
+
function getWindowTitleBarOptions(
shouldUseDarkColors: boolean,
platform: NodeJS.Platform,
@@ -551,12 +566,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,17 +580,20 @@ 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);
}
},
+ // Keep the transparent window focused until the physical shortcut is
+ // released so its remaining repeats cannot reach the next app.
+ concealWindow: () => concealPendingQuitWindow(window),
quit: () => {
void runPromise(electronApp.quit);
},
});
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") {
diff --git a/apps/desktop/src/window/QuitHold.test.ts b/apps/desktop/src/window/QuitHold.test.ts
index 75fed4b08..58f6fb5a4 100644
--- a/apps/desktop/src/window/QuitHold.test.ts
+++ b/apps/desktop/src/window/QuitHold.test.ts
@@ -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,24 @@ 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 concealWindow = vi.fn();
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),
+ concealWindow,
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();
};
@@ -52,10 +59,10 @@ function makeHarness(options?: {
await send(makeInput({ isAutoRepeat: true, ...repeatOverrides }));
}
};
- return { notifications, quit, preventDefault, send, holdFor };
+ return { notifications, concealWindow, quit, preventDefault, send, holdFor };
}
-describe("makeQuitHoldHandler", () => {
+describe("makeQuitShortcutHandler", () => {
beforeEach(() => {
vi.useFakeTimers();
});
@@ -69,24 +76,100 @@ 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 () => {
+ it("conceals a completed hold, then quits after release", async () => {
const harness = makeHarness();
await harness.send(makeInput({}));
await harness.holdFor(QUIT_HOLD_DURATION_MS + 200);
+ expect(harness.concealWindow).toHaveBeenCalledTimes(1);
expect(harness.quit).not.toHaveBeenCalled();
await harness.send(makeInput({ type: "keyUp", key: "Meta", meta: false }));
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("keeps a concealed hold committed when another key is pressed", async () => {
+ const harness = makeHarness();
+ await harness.send(makeInput({}));
+ await harness.holdFor(QUIT_HOLD_DURATION_MS);
+
+ await harness.send(makeInput({ key: "Shift", shift: true }));
+ expect(harness.concealWindow).toHaveBeenCalledTimes(1);
+ expect(harness.quit).not.toHaveBeenCalled();
+
+ vi.advanceTimersByTime(QUIT_HOLD_RELEASE_GRACE_MS);
+ expect(harness.quit).toHaveBeenCalledTimes(1);
+ });
+
+ it("keeps a concealed hold committed through a fresh Cmd+Q press", async () => {
+ const harness = makeHarness();
+ await harness.send(makeInput({}));
+ await harness.holdFor(QUIT_HOLD_DURATION_MS);
+
+ await harness.send(makeInput({}));
+ expect(harness.concealWindow).toHaveBeenCalledTimes(1);
+ expect(harness.quit).not.toHaveBeenCalled();
+
+ await harness.send(makeInput({ type: "keyUp" }));
+ expect(harness.quit).toHaveBeenCalledTimes(1);
+ });
+
+ it("quits when a completed hold goes quiet without release events", async () => {
+ const harness = makeHarness();
+ await harness.send(makeInput({}));
+ await harness.holdFor(QUIT_HOLD_DURATION_MS + QUIT_HOLD_RELEASE_GRACE_MS * 2);
+
+ // If neither keyUp reaches the handler, continued repeats must keep the
+ // app alive. Once they stop, the quiet period is the release signal.
+ expect(harness.quit).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(QUIT_HOLD_RELEASE_GRACE_MS);
+
+ expect(harness.quit).toHaveBeenCalledTimes(1);
+ expect(harness.notifications).toEqual([HOLD_DOWN, UP]);
+ });
+
+ it("waits for slow repeats to stop before quitting", async () => {
+ const harness = makeHarness();
+ await harness.send(makeInput({}));
+
+ vi.advanceTimersByTime(300);
+ await harness.send(makeInput({ isAutoRepeat: true }));
+ vi.advanceTimersByTime(900);
+ await harness.send(makeInput({ isAutoRepeat: true }));
+
+ vi.advanceTimersByTime(QUIT_HOLD_RELEASE_GRACE_MS);
+ expect(harness.quit).not.toHaveBeenCalled();
+
+ vi.advanceTimersByTime(300);
+ await harness.send(makeInput({ isAutoRepeat: true }));
+ vi.advanceTimersByTime(1_799);
+ expect(harness.quit).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+ expect(harness.quit).toHaveBeenCalledTimes(1);
+ });
+
+ it("uses the initial repeat delay when the first repeat completes the hold", async () => {
+ const harness = makeHarness();
+ await harness.send(makeInput({}));
+
+ vi.advanceTimersByTime(QUIT_HOLD_DURATION_MS + 100);
+ await harness.send(makeInput({ isAutoRepeat: true }));
+
+ vi.advanceTimersByTime(QUIT_HOLD_RELEASE_GRACE_MS);
+ expect(harness.quit).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1_999);
+ expect(harness.quit).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+ expect(harness.quit).toHaveBeenCalledTimes(1);
});
it("waits for Q release when Cmd is released first", async () => {
@@ -97,19 +180,30 @@ describe("makeQuitHoldHandler", () => {
harness.preventDefault.mockClear();
await harness.send(makeInput({ meta: false, isAutoRepeat: true }));
expect(harness.preventDefault).toHaveBeenCalledTimes(1);
- vi.advanceTimersByTime(QUIT_HOLD_RELEASE_GRACE_MS * 2);
expect(harness.quit).not.toHaveBeenCalled();
await harness.send(makeInput({ type: "keyUp", meta: false }));
expect(harness.quit).toHaveBeenCalledTimes(1);
});
+ it("still quits after Cmd-first release when the final Q key-up is omitted", async () => {
+ const harness = makeHarness();
+ await harness.send(makeInput({}));
+ await harness.holdFor(QUIT_HOLD_DURATION_MS + 200);
+ await harness.send(makeInput({ type: "keyUp", key: "Meta", meta: false }));
+ await harness.send(makeInput({ meta: false, isAutoRepeat: true }));
+ expect(harness.quit).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(QUIT_HOLD_RELEASE_GRACE_MS);
+ expect(harness.quit).toHaveBeenCalledTimes(1);
+ });
+
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"]);
+ expect(harness.notifications).toEqual([HOLD_DOWN, UP]);
vi.advanceTimersByTime((QUIT_HOLD_DURATION_MS + QUIT_HOLD_RELEASE_GRACE_MS) * 2);
+ expect(harness.concealWindow).not.toHaveBeenCalled();
expect(harness.quit).not.toHaveBeenCalled();
});
@@ -117,61 +211,220 @@ 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.concealWindow).not.toHaveBeenCalled();
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
+ it("honors direct mode when the key is released before its 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?.("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.each(["direct", "hold", "double-click"] as const)(
+ "quits on a quick second press without waiting for a pending %s mode read",
+ async (mode) => {
+ 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({}));
+
+ expect(harness.quit).toHaveBeenCalledTimes(1);
+ expect(harness.notifications).toEqual([]);
+
+ await harness.send(makeInput({ type: "keyUp" }));
+
+ resolvers[0]?.(mode);
+ 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<(enabled: boolean) => void> = [];
+ const resolvers: Array<(mode: QuitConfirmationMode) => void> = [];
const harness = makeHarness({
- isEnabled: () => new Promise((resolve) => resolvers.push(resolve)),
+ getMode: () => 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);
+ // 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 () => {
+ 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_PRESS_MS - 100);
+ await harness.send(makeInput({}));
+ expect(harness.concealWindow).not.toHaveBeenCalled();
+ expect(harness.quit).toHaveBeenCalledTimes(1);
+ expect(harness.notifications).toEqual([DOUBLE_CLICK_DOWN, UP]);
+ });
+
+ 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("quits on a quick second press in hold mode", async () => {
const harness = makeHarness();
await harness.send(makeInput({}));
- vi.advanceTimersByTime(QUIT_DOUBLE_TAP_MS - 100);
+ await harness.send(makeInput({ type: "keyUp" }));
+ vi.advanceTimersByTime(QUIT_DOUBLE_PRESS_MS - 100);
await harness.send(makeInput({}));
expect(harness.quit).toHaveBeenCalledTimes(1);
+ expect(harness.notifications).toEqual([HOLD_DOWN, UP]);
+ });
+
+ it("quits on a quick second press in hold mode when the first release is unseen", async () => {
+ const harness = makeHarness();
+ await harness.send(makeInput({}));
+ vi.advanceTimersByTime(QUIT_DOUBLE_PRESS_MS - 100);
+ await harness.send(makeInput({}));
+
+ expect(harness.concealWindow).not.toHaveBeenCalled();
+ expect(harness.quit).toHaveBeenCalledTimes(1);
+ expect(harness.notifications).toEqual([HOLD_DOWN, UP]);
});
- it("treats two slow taps as separate presses", async () => {
+ it("does not count auto-repeat as a second press", async () => {
+ const harness = makeHarness();
+ await harness.send(makeInput({}));
+ await harness.holdFor(QUIT_DOUBLE_PRESS_MS - 100);
+
+ expect(harness.quit).not.toHaveBeenCalled();
+ expect(harness.notifications).toEqual([HOLD_DOWN]);
+ });
+
+ it("does not count a released tap after another shortcut interrupts it", 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({ key: "c" }));
+ vi.advanceTimersByTime(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 +433,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 () => {
diff --git a/apps/desktop/src/window/QuitHold.ts b/apps/desktop/src/window/QuitHold.ts
index 885770acc..0507ee7e2 100644
--- a/apps/desktop/src/window/QuitHold.ts
+++ b/apps/desktop/src/window/QuitHold.ts
@@ -1,24 +1,23 @@
// @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
// anyway. Once held, quitting waits for Q keyUp or a quiet grace period after
-// modifier keyUp so repeats cannot reach the next app. Keyboards with
-// auto-repeat disabled fall back to the application menu Quit action.
+// repeats stop so they cannot reach the next app. Keyboards with
+// auto-repeat disabled must use a double press or the application menu Quit action.
+// Supporting holds without repeats requires a native physical key-state check.
export const QUIT_HOLD_RELEASE_GRACE_MS = 600;
-
-export type QuitHoldState = "down" | "up";
+// A slow repeat rate can exceed the fixed grace. Waiting for two observed
+// cadences keeps the timer behind the next repeat without slowing normal rates.
+const QUIT_HOLD_REPEAT_CADENCE_MULTIPLIER = 2;
export interface QuitHoldKeyInput {
readonly type: string;
@@ -30,27 +29,32 @@ 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 concealWindow: () => 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.
+ let lastRepeatAt = 0;
+ let repeatCadenceMs = 0;
+ // Incremented when a press is superseded or explicitly cancelled. A plain
+ // key release does not invalidate its pending mode read: a direct-mode
+ // press must still quit after that read settles.
let generation = 0;
const clearWatchdog = () => {
@@ -60,57 +64,85 @@ export function makeQuitHoldHandler(
}
};
- const release = () => {
- if (!holding) return;
- const shouldNotify = armed || quitOnRelease;
- generation += 1;
+ const release = (cancelPendingMode = true, keepDoublePressHint = false) => {
+ if (cancelPendingMode) generation += 1;
+ if (!holding && !notified) return;
+ const keepHint = keepDoublePressHint && mode === "double-click" && notified;
holding = false;
armed = false;
quitOnRelease = false;
+ lastRepeatAt = 0;
+ repeatCadenceMs = 0;
+ 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();
+ lastPressAt = 0;
options.quit();
};
+ const quitAfterQuietPeriod = () => {
+ clearWatchdog();
+ const quietPeriodMs = Math.max(
+ QUIT_HOLD_RELEASE_GRACE_MS,
+ repeatCadenceMs * QUIT_HOLD_REPEAT_CADENCE_MULTIPLIER,
+ );
+ watchdog = setTimeout(quitNow, quietPeriodMs);
+ };
+
return (event, input) => {
const key = input.key.toLowerCase();
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);
+ quitAfterQuietPeriod();
}
}
return;
}
if (input.type !== "keyDown") return;
- if (quitOnRelease && input.isAutoRepeat && key === "q") {
+ const modifierDown = options.platform === "darwin" ? input.meta : input.control;
+ if (input.isAutoRepeat && modifierDown && key === "q") {
+ const now = Date.now();
+ repeatCadenceMs = now - (lastRepeatAt === 0 ? heldSince : lastRepeatAt);
+ lastRepeatAt = now;
+ }
+ if (quitOnRelease) {
event.preventDefault();
- clearWatchdog();
+ if (key === "q") {
+ // Keep the quiet-period fallback even after the modifier is released.
+ // A later Q auto-repeat must not cancel it: macOS can omit the final
+ // Q key-up, and the concealed window would otherwise stay running.
+ quitAfterQuietPeriod();
+ }
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) {
+ // 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;
+
+ // Other keys cancel the hold and the first tap, even after release.
+ // Keep this separate from release(), which also runs when a fresh Q
+ // keydown follows a keyUp that macOS did not deliver.
+ if (!input.isAutoRepeat) {
lastPressAt = 0;
release();
}
@@ -120,10 +152,11 @@ 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();
+ options.concealWindow();
+ quitAfterQuietPeriod();
}
return;
}
@@ -131,28 +164,49 @@ 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) {
+ // A fresh keydown supersedes the current physical hold or the hint kept
+ // alive after a detected release.
+ if (holding || notified) release();
+
+ generation += 1;
+ // Every mode accepts two presses. Quit before reading settings so a slow
+ // read cannot delay the second press. Repeats never reach this branch.
+ if (previousPressAt !== 0 && now - previousPressAt <= QUIT_DOUBLE_PRESS_MS) {
quitNow();
return;
}
- if (holding) 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") {
+ 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(() => {
diff --git a/apps/web/src/components/QuitHoldOverlay.tsx b/apps/web/src/components/QuitHoldOverlay.tsx
index 1201b14f6..fa6f5005b 100644
--- a/apps/web/src/components/QuitHoldOverlay.tsx
+++ b/apps/web/src/components/QuitHoldOverlay.tsx
@@ -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,19 @@ 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} or press twice to quit`
+ : `Press ${shortcut} again to quit`;
return (
<div
role="status"
className="pointer-events-none fixed inset-0 z-100 flex items-center 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>
);
diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx
index 33f0be0d2..1b1e30bb7 100644
--- a/apps/web/src/components/settings/SettingsPanels.tsx
+++ b/apps/web/src/components/settings/SettingsPanels.tsx
@@ -31,6 +31,7 @@ import {
MIN_PROMPT_FONT_SIZE,
MIN_TERMINAL_FONT_SIZE,
ProductFeedbackEndpoint,
+ type QuitConfirmationMode,
} from "@t3tools/contracts/settings";
import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings";
import { createModelSelection } from "@t3tools/shared/model";
@@ -166,6 +167,12 @@ const BACKGROUND_ACTIVITY_PROFILE_LABELS: Record<BackgroundActivityProfile, stri
"battery-saver": "Battery saver",
};
+const QUIT_CONFIRMATION_MODE_LABELS: Record<QuitConfirmationMode, string> = {
+ hold: "Hold",
+ "double-click": "Double press",
+ direct: "Direct",
+};
+
type BackgroundActivityProfileOption = BackgroundActivityProfile | "advanced";
const BACKGROUND_ACTIVITY_PROFILE_OPTION_LABELS: Record<BackgroundActivityProfileOption, string> = {
@@ -424,9 +431,7 @@ export function useSettingsRestore(onRestored?: () => void) {
...(settings.addProjectBaseDirectory !== DEFAULT_UNIFIED_SETTINGS.addProjectBaseDirectory
? ["Add project base directory"]
: []),
- ...(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
@@ -2143,11 +2148,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="Hold mode also quits on 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 })
}
@@ -2155,11 +2160,29 @@ 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
+ size="sm"
+ 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}
diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts
index aae251af7..a28f20f5d 100644
--- a/apps/web/src/components/settings/settingsSearch.ts
+++ b/apps/web/src/components/settings/settingsSearch.ts
@@ -198,8 +198,9 @@ export const SETTINGS_SEARCH_ITEMS = [
},
{
id: "quit-confirmation",
- title: "Hold to quit",
+ title: "Quit shortcut",
to: "/settings/general",
+ keywords: ["confirmation", "desktop", "exit", "direct", "hold", "double click", "press twice"],
desktopOnly: true,
},
{
diff --git a/docs/user/keybindings.md b/docs/user/keybindings.md
index f3838cfb4..c3dc1c89a 100644
--- a/docs/user/keybindings.md
+++ b/docs/user/keybindings.md
@@ -77,6 +77,19 @@ Background submission from a new chat is the exception. `mod+enter` starts that
another new chat with the same workspace mode and base branch. **New worktree** remains selected, but
the new chat does not reuse the worktree created for the chat that just started.
+## Desktop quit shortcut
+
+Use `Cmd+Q` on macOS or `Ctrl+Q` on Windows and Linux. In the default **Hold** mode, hold the
+shortcut for 1.2 seconds or press it twice within 500 milliseconds. The second press quits
+immediately. You can keep Command or Control held between presses, or release both keys.
+
+Hold mode needs keyboard repeat. If holding does not quit, use two quick presses or choose
+**Quit** from the application menu.
+
+Change **Quit shortcut** in **Settings** → **General**. **Direct** quits on the first press.
+**Double press** requires two quick presses and does not accept a hold. The application menu's
+**Quit** action always quits immediately.
+
## `when` conditions
A `when` expression is evaluated against context keys describing the current UI state. The keys
diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts
index 264b71a1d..a046c8513 100644
--- a/packages/contracts/src/ipc.ts
+++ b/packages/contracts/src/ipc.ts
@@ -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;
@@ -1129,11 +1133,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>;
diff --git a/packages/contracts/src/settings.test.ts b/packages/contracts/src/settings.test.ts
index 71e46aff1..489bde1ac 100644
--- a/packages/contracts/src/settings.test.ts
+++ b/packages/contracts/src/settings.test.ts
@@ -197,6 +197,33 @@ describe("ClientSettings appearance contrast", () => {
});
});
+describe("ClientSettings quit confirmation", () => {
+ const encodeClientSettings = Schema.encodeSync(ClientSettingsSchema);
+
+ it("defaults to hold and accepts each confirmation mode", () => {
+ expect(decodeClientSettings({}).confirmQuit).toBe("hold");
+
+ for (const mode of ["direct", "hold", "double-click"] as const) {
+ expect(decodeClientSettings({ confirmQuit: mode }).confirmQuit).toBe(mode);
+ expect(decodeClientSettingsPatch({ confirmQuit: mode }).confirmQuit).toBe(mode);
+ expect(encodeClientSettings(decodeClientSettings({ confirmQuit: mode })).confirmQuit).toBe(
+ mode,
+ );
+ }
+ });
+
+ it("migrates persisted booleans to hold or direct", () => {
+ expect(decodeClientSettings({ confirmQuit: true }).confirmQuit).toBe("hold");
+ expect(decodeClientSettings({ confirmQuit: false }).confirmQuit).toBe("direct");
+ });
+
+ it("rejects unsupported confirmation modes", () => {
+ expect(() => decodeClientSettings({ confirmQuit: "maybe" })).toThrow();
+ expect(() => decodeClientSettingsPatch({ confirmQuit: "maybe" })).toThrow();
+ expect(() => decodeClientSettingsPatch({ confirmQuit: true })).toThrow();
+ });
+});
+
describe("ClientSettings environment identification", () => {
it("defaults to artwork and accepts each presentation mode", () => {
expect(decodeClientSettings({}).environmentIdentificationMode).toBe("artwork");
diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts
index 9f77353ec..d534835e7 100644
--- a/packages/contracts/src/settings.ts
+++ b/packages/contracts/src/settings.ts
@@ -136,6 +136,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.
@@ -191,9 +207,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))),
dismissedProviderUpdateNotificationKeys: Schema.Array(TrimmedNonEmptyString).pipe(
@@ -1093,7 +1111,7 @@ export const ClientSettingsPatch = Schema.Struct({
browserDefaultZoomFactor: Schema.optionalKey(PreviewZoomFactor),
browserDefaultAppearance: Schema.optionalKey(PreviewAppearancePreference),
browserAutoShowFloatingPreview: Schema.optionalKey(Schema.Boolean),
- confirmQuit: Schema.optionalKey(Schema.Boolean),
+ confirmQuit: Schema.optionalKey(QuitConfirmationMode),
confirmThreadArchive: Schema.optionalKey(Schema.Boolean),
confirmThreadDelete: Schema.optionalKey(Schema.Boolean),
diffIgnoreWhitespace: Schema.optionalKey(Schema.Boolean),