Skip to content

The agent that grows with you

fix(webapp): follow a live window-kind change; Chromium app windows only

Tekniumaa881935db55
diff --git a/apps/desktop/src/lib/keybinds/actions.ts b/apps/desktop/src/lib/keybinds/actions.ts
index 45407927d7d..08bcd225025 100644
--- a/apps/desktop/src/lib/keybinds/actions.ts
+++ b/apps/desktop/src/lib/keybinds/actions.ts
@@ -10,6 +10,8 @@ import type { Contribution } from '@/contrib/types'
import { hostHas } from '@/lib/host-capabilities'
import { isMacPlatform } from '@/lib/platform'
+import { inChromiumAppWindow } from './app-window'
+
export type KeybindCategory = 'composer' | 'profiles' | 'session' | 'navigation' | 'view'
// A browser tab acts on some chords before the page sees the keydown: new
@@ -21,19 +23,11 @@ export type KeybindCategory = 'composer' | 'profiles' | 'session' | 'navigation'
// on macOS (Option types a character). Alt+Tab is the OS window switcher, so
// tab cycling takes ] and [. Native Desktop keeps the native chords.
//
-// A Chrome app window (Install / "Open as window", `--app=`) reserves none of
-// them: `BrowserCommandController::IsReservedCommandOrKey` returns false for
-// TYPE_APP windows, so the page gets Ctrl+N/T/W/Tab first there; such a
-// window matches one of the display modes below. Off macOS it keeps the
-// native Ctrl chords, the same ones Desktop ships. macOS keeps ⌃⌘ either way.
-const APP_WINDOW_DISPLAY_MODES = ['standalone', 'minimal-ui', 'window-controls-overlay'] as const
-
-function inBrowserAppWindow(): boolean {
- return (
- typeof window.matchMedia === 'function' &&
- APP_WINDOW_DISPLAY_MODES.some(mode => window.matchMedia(`(display-mode: ${mode})`).matches)
- )
-}
+// A Chromium app window (Install / "Open as window", `--app=`) reserves none
+// of them (see app-window.ts). Off macOS it keeps the native Ctrl chords, the
+// same ones Desktop ships; macOS keeps ⌃⌘ either way. The window kind can
+// change without a reload ("Open in Chrome"), so these rows resolve their
+// defaults on every read and the bindings store follows the change.
interface BrowserChords {
/** Omitted: the native default already reaches the page on macOS. */
@@ -41,24 +35,36 @@ interface BrowserChords {
other: string
}
-type HostDefaults = Pick<KeybindActionMeta, 'defaults' | 'editableTargetPolicy'>
-
-function hostDefaults(native: readonly string[], browser: BrowserChords): HostDefaults {
+// The host and platform are fixed for the page's life; only the window kind
+// moves, so a Windows/Linux browser row reads it on every access.
+function hostAction(
+ id: string,
+ category: KeybindCategory,
+ native: readonly string[],
+ browser: BrowserChords
+): KeybindActionMeta {
if (!hostHas('browserShortcutDefaults')) {
- return { defaults: native }
+ return { id, category, defaults: native }
}
if (isMacPlatform()) {
- return { defaults: browser.mac ? [browser.mac] : native }
+ return { id, category, defaults: browser.mac ? [browser.mac] : native }
}
- if (inBrowserAppWindow()) {
- return { defaults: native }
+ const tab = [browser.other]
+
+ return {
+ id,
+ category,
+ get defaults() {
+ return inChromiumAppWindow() ? native : tab
+ },
+ // Alt+letter has no Cmd/Ctrl, so it needs the editable-target opt-in to
+ // fire from the composer the way the native ⌘/Ctrl chord does.
+ get editableTargetPolicy() {
+ return inChromiumAppWindow() ? undefined : 'modified'
+ }
}
-
- // Alt+letter has no Cmd/Ctrl, so it needs the editable-target opt-in to
- // fire from the composer the way the native ⌘/Ctrl chord does.
- return { defaults: [browser.other], editableTargetPolicy: 'modified' }
}
// The self-referential opener — bound + dispatched like any action, but shown in
@@ -167,25 +173,13 @@ export const KEYBIND_ACTIONS: readonly KeybindActionMeta[] = [
// `shift+n` was dropped from the defaults (#76185): a bare shifted letter
// hijacked normal typing — pressing uppercase N outside an input (or via an
// IME) created a new session unexpectedly.
- { id: 'session.new', category: 'session', ...hostDefaults(['mod+n'], { mac: 'mod+ctrl+n', other: 'alt+n' }) },
- { id: 'session.newTab', category: 'session', ...hostDefaults(['mod+t'], { mac: 'mod+ctrl+t', other: 'alt+t' }) },
- {
- id: 'session.newWindow',
- category: 'session',
- ...hostDefaults(['mod+shift+n'], { mac: 'mod+ctrl+shift+n', other: 'alt+shift+n' })
- },
+ hostAction('session.new', 'session', ['mod+n'], { mac: 'mod+ctrl+n', other: 'alt+n' }),
+ hostAction('session.newTab', 'session', ['mod+t'], { mac: 'mod+ctrl+t', other: 'alt+t' }),
+ hostAction('session.newWindow', 'session', ['mod+shift+n'], { mac: 'mod+ctrl+shift+n', other: 'alt+shift+n' }),
// ⌃Tab / ⌃⇧Tab — the universal tab-cycle chord. Literally Control, not Cmd
// (macOS reserves Cmd+Tab for app switching); see `ctrl` in combo.ts.
- {
- id: 'session.next',
- category: 'session',
- ...hostDefaults(['ctrl+tab', 'ctrl+pagedown'], { mac: 'mod+ctrl+]', other: 'alt+]' })
- },
- {
- id: 'session.prev',
- category: 'session',
- ...hostDefaults(['ctrl+shift+tab', 'ctrl+pageup'], { mac: 'mod+ctrl+[', other: 'alt+[' })
- },
+ hostAction('session.next', 'session', ['ctrl+tab', 'ctrl+pagedown'], { mac: 'mod+ctrl+]', other: 'alt+]' }),
+ hostAction('session.prev', 'session', ['ctrl+shift+tab', 'ctrl+pageup'], { mac: 'mod+ctrl+[', other: 'alt+[' }),
...SESSION_SLOT_ACTIONS,
{ id: 'session.focusSearch', category: 'session', defaults: ['mod+shift+f'] },
{ id: 'session.togglePin', category: 'session', defaults: [] },
@@ -259,18 +253,14 @@ export const KEYBIND_ACTIONS: readonly KeybindActionMeta[] = [
// so these stay on `ctrl` — distinct on macOS, folding to Ctrl elsewhere.
{ id: 'view.nextTerminal', category: 'view', defaults: ['ctrl+shift+down'] },
{ id: 'view.prevTerminal', category: 'view', defaults: ['ctrl+shift+up'] },
- { id: 'view.closeTerminal', category: 'view', ...hostDefaults(['ctrl+shift+w'], { other: 'alt+shift+w' }) },
+ hostAction('view.closeTerminal', 'view', ['ctrl+shift+w'], { other: 'alt+shift+w' }),
// ⌘\ — the backslash reads like a mirror line flipping the layout.
{ id: 'view.flipPanes', category: 'view', defaults: ['mod+\\'] },
// ⌘W closes the focused zone's active tab — its own tab strip (preview) or
// the tree tab (session tiles, files, terminal). The uncloseable workspace
// is a no-op. ⌘⇧T reopens the last closed tab where it was.
- { id: 'view.closeTab', category: 'view', ...hostDefaults(['mod+w'], { mac: 'mod+ctrl+w', other: 'alt+w' }) },
- {
- id: 'view.reopenTab',
- category: 'view',
- ...hostDefaults(['mod+shift+t'], { mac: 'mod+ctrl+shift+t', other: 'alt+shift+t' })
- },
+ hostAction('view.closeTab', 'view', ['mod+w'], { mac: 'mod+ctrl+w', other: 'alt+w' }),
+ hostAction('view.reopenTab', 'view', ['mod+shift+t'], { mac: 'mod+ctrl+shift+t', other: 'alt+shift+t' }),
// ⌘F — open the find-in-page bar. `actionAllowedInInput` lets this action
// fire from inside a textarea / contenteditable (matches browser behavior
// so typing in the composer and pressing ⌘F focuses find, not 'f').
diff --git a/apps/desktop/src/lib/keybinds/app-window.ts b/apps/desktop/src/lib/keybinds/app-window.ts
new file mode 100644
index 00000000000..f7038bb996f
--- /dev/null
+++ b/apps/desktop/src/lib/keybinds/app-window.ts
@@ -0,0 +1,92 @@
+// Whether the Webapp runs in a Chromium app window (Install / "Open as
+// window", `--app=`), where the page gets Ctrl+N/T/W/Tab before the browser.
+//
+// Chromium only: `BrowserCommandController::IsReservedCommandOrKey` returns
+// false for TYPE_APP windows. Other engines' web-app windows (Firefox taskbar
+// tabs) can report `standalone` while the browser still acts on those chords.
+//
+// The window kind changes live: "Open in Chrome" moves an app window into a
+// tab without reloading the page, so callers follow `onBrowserWindowKindChange`.
+
+import { arraysEqual } from '@/lib/storage'
+
+const APP_WINDOW_QUERIES = ['standalone', 'minimal-ui', 'window-controls-overlay'].map(
+ mode => `(display-mode: ${mode})`
+)
+
+interface UserAgentBrands {
+ brands?: readonly { brand: string }[]
+}
+
+function isChromium(): boolean {
+ // userAgentData is secure-context only (absent on a plain-http LAN origin),
+ // and absent in Firefox and Safari; their UA strings carry no Chrome/ token.
+ const brands = (navigator as Navigator & { userAgentData?: UserAgentBrands }).userAgentData?.brands
+
+ return brands ? brands.some(entry => entry.brand === 'Chromium') : /Chrom(e|ium)\//.test(navigator.userAgent)
+}
+
+export function inChromiumAppWindow(): boolean {
+ return (
+ typeof window.matchMedia === 'function' &&
+ isChromium() &&
+ APP_WINDOW_QUERIES.some(query => window.matchMedia(query).matches)
+ )
+}
+
+/** Runs `listener` whenever the window's display mode changes. */
+export function onBrowserWindowKindChange(listener: () => void): () => void {
+ if (typeof window.matchMedia !== 'function') {
+ return () => undefined
+ }
+
+ const lists = APP_WINDOW_QUERIES.map(query => window.matchMedia(query))
+
+ for (const list of lists) {
+ list.addEventListener('change', listener)
+ }
+
+ return () => {
+ for (const list of lists) {
+ list.removeEventListener('change', listener)
+ }
+ }
+}
+
+type Bindings = Record<string, string[]>
+
+/** Moves every binding still on its old shipped default onto the new one; a
+ * user's own rebind (anything else, including a cleared binding) stays. */
+export function rebaseShippedDefaults(bindings: Bindings, previous: Bindings, next: Bindings): Bindings {
+ const out = { ...bindings }
+
+ for (const [id, combos] of Object.entries(next)) {
+ if (!arraysEqual(out[id] ?? [], previous[id] ?? []) || arraysEqual(out[id] ?? [], combos)) {
+ continue
+ }
+
+ out[id] = [...combos]
+ }
+
+ return out
+}
+
+/** Keeps `store`'s defaults on the current window kind. */
+export function followBrowserWindowKind(
+ store: { get(): Bindings; set(value: Bindings): void },
+ defaults: () => Bindings
+): () => void {
+ let shipped = defaults()
+
+ return onBrowserWindowKindChange(() => {
+ const next = defaults()
+ const current = store.get()
+ const rebased = rebaseShippedDefaults(current, shipped, next)
+
+ shipped = next
+
+ if (Object.keys(rebased).some(id => rebased[id] !== current[id])) {
+ store.set(rebased)
+ }
+ })
+}
diff --git a/apps/desktop/src/lib/keybinds/browser-app-window-defaults.test.ts b/apps/desktop/src/lib/keybinds/browser-app-window-defaults.test.ts
index b0a05ced6a1..d6250fb8eaf 100644
--- a/apps/desktop/src/lib/keybinds/browser-app-window-defaults.test.ts
+++ b/apps/desktop/src/lib/keybinds/browser-app-window-defaults.test.ts
@@ -16,12 +16,35 @@ const shortcuts = [
const setPlatform = (value: string) => Object.defineProperty(navigator, 'platform', { configurable: true, value })
-function stubDisplayMode(mode: string) {
- vi.stubGlobal('matchMedia', (query: string) => ({ matches: query === `(display-mode: ${mode})`, media: query }))
+const CHROME_UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36'
+const FIREFOX_UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:144.0) Gecko/20100101 Firefox/144.0'
+
+const setUserAgent = (value: string) => Object.defineProperty(navigator, 'userAgent', { configurable: true, value })
+
+// A display mode the test can flip live, the way "Open in Chrome" moves an
+// app window into a tab: every query list fires `change`.
+function stubDisplayMode(initial: string) {
+ let mode = initial
+ const listeners = new Set<() => void>()
+
+ vi.stubGlobal('matchMedia', (query: string) => ({
+ get matches() {
+ return query === `(display-mode: ${mode})`
+ },
+ media: query,
+ addEventListener: (_: string, listener: () => void) => listeners.add(listener),
+ removeEventListener: (_: string, listener: () => void) => listeners.delete(listener)
+ }))
+
+ return (next: string) => {
+ mode = next
+ listeners.forEach(listener => listener())
+ }
}
beforeEach(() => {
vi.resetModules()
+ setUserAgent(CHROME_UA)
localStorage.clear()
window.document.documentElement.dataset.hermesDesktopHost = 'browser'
})
@@ -29,6 +52,7 @@ beforeEach(() => {
afterEach(() => {
delete window.document.documentElement.dataset.hermesDesktopHost
setPlatform('')
+ Reflect.deleteProperty(navigator, 'userAgent')
vi.unstubAllGlobals()
localStorage.clear()
})
@@ -64,3 +88,34 @@ it.each([
expect(bindingsFor(shortcut.id)).toEqual([platform === 'MacIntel' ? shortcut.mac : shortcut.tab])
}
})
+
+it('follows a live display-mode change and leaves a user rebind alone', async () => {
+ setPlatform('Win32')
+ const moveTo = stubDisplayMode('standalone')
+ const { $bindings, bindingsFor, setBinding } = await import('@/store/keybinds')
+ const { keybindActionAllowedInEditableTarget } = await import('./actions')
+
+ setBinding('view.closeTab', ['mod+shift+q'])
+ moveTo('browser')
+
+ expect(bindingsFor('session.new')).toEqual(['alt+n'])
+ expect(bindingsFor('session.next')).toEqual(['alt+]'])
+ expect(keybindActionAllowedInEditableTarget('session.new', 'alt+n')).toBe(true)
+ expect(bindingsFor('view.closeTab')).toEqual(['mod+shift+q'])
+
+ moveTo('standalone')
+
+ expect(bindingsFor('session.new')).toEqual(['mod+n'])
+ expect($bindings.get()['view.closeTab']).toEqual(['mod+shift+q'])
+})
+
+it('a non-Chromium web-app window keeps the browser-tab defaults', async () => {
+ setPlatform('Win32')
+ setUserAgent(FIREFOX_UA)
+ stubDisplayMode('standalone')
+ const { bindingsFor } = await import('@/store/keybinds')
+
+ for (const shortcut of shortcuts) {
+ expect(bindingsFor(shortcut.id)).toEqual([shortcut.tab])
+ }
+})
diff --git a/apps/desktop/src/store/keybinds.ts b/apps/desktop/src/store/keybinds.ts
index 5a3812fd48a..b6112d29060 100644
--- a/apps/desktop/src/store/keybinds.ts
+++ b/apps/desktop/src/store/keybinds.ts
@@ -2,6 +2,7 @@ import { atom, computed } from 'nanostores'
import { $registryVersion } from '@/contrib/registry'
import { allKeybindActions, defaultBindings, keybindAction, type KeybindBindings } from '@/lib/keybinds/actions'
+import { followBrowserWindowKind } from '@/lib/keybinds/app-window'
import { canonicalizeCombo } from '@/lib/keybinds/combo'
import { persistStore } from '@/lib/persist-store'
import { arraysEqual, persistString, storedString, type WriteOptions } from '@/lib/storage'
@@ -87,6 +88,9 @@ export const $bindings = atom<KeybindBindings>(loadBindings())
persistStore($bindings, persistBindings, defaultBindings())
+// "Open in Chrome" turns an app window into a tab without a reload.
+followBrowserWindowKind($bindings, defaultBindings)
+
/** Live combos for an action: explicit binding → stored override → default. */
export function bindingsFor(id: string, bindings: KeybindBindings = $bindings.get()): string[] {
return bindings[id] ?? storedOverrides[id] ?? [...(keybindAction(id)?.defaults ?? [])]