Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(md-view): ⌘/Ctrl+M in the Server Edition + one verdict for a multi-select toggle

review790da9e1740e
diff --git a/CLAUDE.md b/CLAUDE.md
index 5bb49e185..d570a2812 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -4189,10 +4189,25 @@ the Settings section and ShortcutsPanel start disagreeing about what a chord mea
dispatcher, whose main-intercepted command cases deliberately have no renderer handlers.
`terminalChordBubbles` must therefore refuse every `MAIN_INTERCEPTED_COMMAND_IDS` command; if
it returned true for `node.close`, xterm would withhold `^W` while the unclaimed event bubbled
- to Canvas. One predicate, two main-process consumers are pinned in `keydown-intercept.test.ts`
+ to Canvas. **`node.toggleMarkdown` is the one exception and BUBBLES**: in the Server Edition its
+ owner is a WINDOW keydown listener in the bridge (`bridge/markdown-toggle-key.ts`, below), which
+ xterm would otherwise starve by writing `\r` and cancelling the event. It changes nothing on the
+ desktop — under app-first main claims the chord above the page, under terminal-first the
+ resolver already refuses it, and main has no terminal-focus stand-down for it. One predicate, two main-process consumers are pinned in `keydown-intercept.test.ts`
(including a source-level wiring pin, since the menu leg lives against a real Menu in index.ts),
and `keybindingOverrides.test.ts` pins the renderer-to-xterm hand-off through
`terminalKeyAction`.
+ - **The Server Edition's ⌘/Ctrl+M is the bridge's own window listener**
+ (`renderer/bridge/markdown-toggle-key.ts`, wired as `onMarkdownToggle` in `bridge/stubs.ts`):
+ a browser has no `before-input-event`, so the stub used to be `noopUnsub` and the chord did
+ nothing there. It mirrors the intercept — effective `node.toggleMarkdown` bindings read per
+ keystroke, `policyStandsDown` (now in `shared/keybindings.ts`, re-exported by
+ `keydown-intercept.ts`, so both shells run ONE predicate) with focus read from the DOM via
+ `isTerminalTarget` — plus two refusals: auto-repeat is swallowed without re-toggling, and a
+ `defaultPrevented` event is left alone. Bubble phase for the recorder's sake, installed only
+ while subscribed. It cannot double-fire on desktop (only `buildStubApi` reaches it; the relay
+ tab takes `onMarkdownToggle` from the local preload). macOS Chrome reserves ⌘M for minimize,
+ so the default chord only reaches a Mac browser tab after a remap (docs/SERVER.md).
- **ShortcutsPanel is DERIVED from the registry, never a hand-written list.**
`buildShortcutSections` iterates `COMMAND_DEFINITIONS` — one section per `CommandGroup` in
registry source order, the label from `def.title`, and EVERY one of the command's EFFECTIVE
diff --git a/docs/SERVER.md b/docs/SERVER.md
index 5eee328cf..e7c6d56f0 100644
--- a/docs/SERVER.md
+++ b/docs/SERVER.md
@@ -407,6 +407,16 @@ The following affordances change shape in the browser (no native OS is reachable
Note also that **Ctrl+Shift+C** (advertised as copy on Linux/Windows) additionally opens
Chromium's element inspector and a page cannot suppress that; **Ctrl+Insert** is the
browser-safe copy chord.
+- **Markdown view toggle (⌘/Ctrl+M)** — works in the browser: with no main process to
+ intercept it, the bridge matches the user's `node.toggleMarkdown` binding with its own
+ window keydown listener (`src/renderer/bridge/markdown-toggle-key.ts`) and honors the
+ terminal-first policy like the desktop. **macOS Chrome reserves ⌘M for window
+ minimize** and never delivers it to the page, so on a Mac the default chord does
+ nothing — remap it in Settings → Keyboard Shortcuts, or use the node's right-click
+ "Markdown view". On Linux/Windows the default is Ctrl+M, which under the default
+ app-first policy is taken from a focused terminal exactly as on the desktop (a shell sees
+ Ctrl+M as Enter). Inside a focused Monaco editor Ctrl+M stays Monaco's own "toggle Tab
+ key moves focus" binding; hover the node with focus elsewhere to toggle its preview.
The **backpressure / flow-control** gap noted in the Phase 2 limitations is now
closed: a flooding PTY is automatically paused based on the WebSocket
diff --git a/src/main/keydown-intercept.ts b/src/main/keydown-intercept.ts
index 3cac5820c..249c55a9e 100644
--- a/src/main/keydown-intercept.ts
+++ b/src/main/keydown-intercept.ts
@@ -1,6 +1,7 @@
import { IPC } from '../shared/ipc'
import {
getEffectiveBindings,
+ policyStandsDown,
sanitizeKeybindingOverrides,
type TerminalShortcutPolicy
} from '../shared/keybindings'
@@ -199,30 +200,11 @@ export function navigationClearsRecording(details: {
return details.isMainFrame && !details.isSameDocument
}
-/**
- * PURE. Does the user's `terminalShortcutPolicy` mean this window must stop claiming chords right
- * now? The composition `index.ts` hands to `installKeydownIntercepts`' 5th parameter, exported so
- * it can be pressed instead of living untested inside a closure in a 5000-line file.
- *
- * **Both halves are refusals and both matter.** `app-first` is the shipped default, so it must be
- * false whatever the mirror reports — that is the byte-identical guarantee of this feature: a user
- * who never touched the setting sees exactly the pre-feature intercepts, even though their
- * renderer is reporting terminal focus all day. And `terminalFocused` is a MIRROR of the
- * renderer's `document.activeElement`, which is why `false` is its reset value everywhere: a page
- * that died mid-report, a window that never had one, a reload — all resolve to "intercepts on",
- * never to "intercepts off with nothing alive to turn them back on".
- *
- * Why the policy is read here rather than the intercepts simply being uninstalled under
- * `terminal-first`: the policy is a live setting and the focus changes per keystroke, so there is
- * nothing static to install against — and an app-first user's window must not be a different
- * window from a terminal-first user's.
- */
-export function policyStandsDown(
- policy: TerminalShortcutPolicy,
- terminalFocused: boolean
-): boolean {
- return policy === 'terminal-first' && terminalFocused
-}
+// `policyStandsDown` moved to `shared/keybindings.ts` (with its full rationale) so the Server
+// Edition's browser-side ⌘M listener (`renderer/bridge/markdown-toggle-key.ts`) applies the SAME
+// predicate — main is not importable from the renderer. Re-exported so this module stays the one
+// place `index.ts` and its tests import the intercept pieces from.
+export { policyStandsDown }
/**
* PURE. The CLOSE leg's extra stand-down, applied REGARDLESS of the policy (issue #383): off-mac,
diff --git a/src/renderer/bridge/markdown-toggle-key.test.ts b/src/renderer/bridge/markdown-toggle-key.test.ts
new file mode 100644
index 000000000..06675e799
--- /dev/null
+++ b/src/renderer/bridge/markdown-toggle-key.test.ts
@@ -0,0 +1,203 @@
+import { describe, it, expect, vi } from 'vitest'
+import {
+ markdownToggleKeyVerdict,
+ createMarkdownToggleSource,
+ type MarkdownToggleKeyEvent,
+ type MarkdownToggleSourceDeps
+} from './markdown-toggle-key'
+import type { ContextElement } from '../lib/keyContext'
+
+const ev = (p: Partial<MarkdownToggleKeyEvent> = {}): MarkdownToggleKeyEvent => ({
+ metaKey: false,
+ ctrlKey: true,
+ shiftKey: false,
+ altKey: false,
+ key: 'm',
+ repeat: false,
+ defaultPrevented: false,
+ ...p
+})
+const base = {
+ bindings: ['Cmd+M'] as readonly string[],
+ isMac: false,
+ policy: 'app-first' as const,
+ terminalFocused: false
+}
+
+describe('markdownToggleKeyVerdict', () => {
+ it('toggles on the effective binding (Cmd → Ctrl off-mac)', () => {
+ expect(markdownToggleKeyVerdict(ev(), base)).toBe('toggle')
+ })
+
+ it('matches exactly — extra modifiers are a different chord', () => {
+ expect(markdownToggleKeyVerdict(ev({ shiftKey: true }), base)).toBeNull()
+ expect(markdownToggleKeyVerdict(ev({ ctrlKey: false }), base)).toBeNull()
+ expect(markdownToggleKeyVerdict(ev({ key: 'n' }), base)).toBeNull()
+ })
+
+ it('follows a remap and reads [] (disabled) as never', () => {
+ expect(markdownToggleKeyVerdict(ev({ altKey: true }), { ...base, bindings: ['Cmd+Alt+M'] })).toBe(
+ 'toggle'
+ )
+ expect(markdownToggleKeyVerdict(ev(), { ...base, bindings: ['Cmd+Alt+M'] })).toBeNull()
+ expect(markdownToggleKeyVerdict(ev(), { ...base, bindings: [] })).toBeNull()
+ })
+
+ it('uses meta for Cmd on mac', () => {
+ const mac = { ...base, isMac: true }
+ expect(markdownToggleKeyVerdict(ev({ ctrlKey: false, metaKey: true }), mac)).toBe('toggle')
+ expect(markdownToggleKeyVerdict(ev(), mac)).toBeNull()
+ })
+
+ it('stands down under terminal-first while a terminal is focused — and ONLY then', () => {
+ expect(
+ markdownToggleKeyVerdict(ev(), { ...base, policy: 'terminal-first', terminalFocused: true })
+ ).toBeNull()
+ expect(
+ markdownToggleKeyVerdict(ev(), { ...base, policy: 'terminal-first', terminalFocused: false })
+ ).toBe('toggle')
+ // app-first keeps claiming a focused terminal's chord, exactly like the desktop intercept.
+ expect(markdownToggleKeyVerdict(ev(), { ...base, terminalFocused: true })).toBe('toggle')
+ })
+
+ it('a held chord is swallowed but never re-toggles', () => {
+ expect(markdownToggleKeyVerdict(ev({ repeat: true }), base)).toBe('swallow')
+ })
+
+ it('an event a child handler already claimed is left alone', () => {
+ expect(markdownToggleKeyVerdict(ev({ defaultPrevented: true }), base)).toBeNull()
+ })
+})
+
+/** A minimal EventTarget stand-in: records the one listener the source installs. */
+function fakeTarget() {
+ const listeners = new Set<(e: KeyboardEvent) => void>()
+ return {
+ listeners,
+ addEventListener: vi.fn((type: string, l: (e: KeyboardEvent) => void) => {
+ if (type === 'keydown') listeners.add(l)
+ }),
+ removeEventListener: vi.fn((type: string, l: (e: KeyboardEvent) => void) => {
+ if (type === 'keydown') listeners.delete(l)
+ }),
+ press(p: Partial<MarkdownToggleKeyEvent> = {}) {
+ const e = { ...ev(p), preventDefault: vi.fn() }
+ for (const l of [...listeners]) l(e as unknown as KeyboardEvent)
+ return e
+ }
+ }
+}
+
+function deps(
+ target: ReturnType<typeof fakeTarget>,
+ over: Partial<MarkdownToggleSourceDeps> = {}
+): MarkdownToggleSourceDeps {
+ return {
+ target,
+ bindings: () => ['Cmd+M'],
+ isMac: () => false,
+ policy: () => 'app-first',
+ activeElement: () => null,
+ ...over
+ }
+}
+
+describe('createMarkdownToggleSource', () => {
+ it('installs nothing until someone subscribes (buildStubApi has no side effect)', () => {
+ const t = fakeTarget()
+ createMarkdownToggleSource(deps(t))
+ expect(t.addEventListener).not.toHaveBeenCalled()
+ })
+
+ it('fans ONE window listener out to every subscriber, and preventDefaults the claim', () => {
+ const t = fakeTarget()
+ const on = createMarkdownToggleSource(deps(t))
+ const a = vi.fn()
+ const b = vi.fn()
+ on(a)
+ on(b)
+ expect(t.listeners.size).toBe(1)
+ const e = t.press()
+ expect(a).toHaveBeenCalledTimes(1)
+ expect(b).toHaveBeenCalledTimes(1)
+ expect(e.preventDefault).toHaveBeenCalled()
+ })
+
+ it('an unmatched key is neither prevented nor forwarded', () => {
+ const t = fakeTarget()
+ const on = createMarkdownToggleSource(deps(t))
+ const a = vi.fn()
+ on(a)
+ const e = t.press({ key: 'x' })
+ expect(a).not.toHaveBeenCalled()
+ expect(e.preventDefault).not.toHaveBeenCalled()
+ })
+
+ it('a repeat is prevented but not forwarded', () => {
+ const t = fakeTarget()
+ const on = createMarkdownToggleSource(deps(t))
+ const a = vi.fn()
+ on(a)
+ const e = t.press({ repeat: true })
+ expect(a).not.toHaveBeenCalled()
+ expect(e.preventDefault).toHaveBeenCalled()
+ })
+
+ it('reads terminal focus from the live DOM (xterm helper textarea) against the live policy', () => {
+ const t = fakeTarget()
+ let policy: 'app-first' | 'terminal-first' = 'terminal-first'
+ let focused: ContextElement | null = {
+ tagName: 'TEXTAREA',
+ classList: { contains: (c: string) => c === 'xterm-helper-textarea' }
+ }
+ const on = createMarkdownToggleSource(
+ deps(t, { policy: () => policy, activeElement: () => focused })
+ )
+ const a = vi.fn()
+ on(a)
+ const e = t.press()
+ expect(a).not.toHaveBeenCalled()
+ expect(e.preventDefault).not.toHaveBeenCalled() // the chord stays with the shell
+ focused = { tagName: 'DIV' }
+ t.press()
+ expect(a).toHaveBeenCalledTimes(1)
+ policy = 'app-first'
+ focused = {
+ tagName: 'TEXTAREA',
+ classList: { contains: (c: string) => c === 'xterm-helper-textarea' }
+ }
+ t.press()
+ expect(a).toHaveBeenCalledTimes(2)
+ })
+
+ it('reads bindings per keystroke, so a remap applies without resubscribing', () => {
+ const t = fakeTarget()
+ let bindings: readonly string[] = ['Cmd+M']
+ const on = createMarkdownToggleSource(deps(t, { bindings: () => bindings }))
+ const a = vi.fn()
+ on(a)
+ bindings = []
+ t.press()
+ expect(a).not.toHaveBeenCalled()
+ })
+
+ it('unsubscribe detaches that listener; the last one removes the window listener', () => {
+ const t = fakeTarget()
+ const on = createMarkdownToggleSource(deps(t))
+ const a = vi.fn()
+ const b = vi.fn()
+ const unA = on(a)
+ const unB = on(b)
+ unA()
+ unA() // idempotent
+ t.press()
+ expect(a).not.toHaveBeenCalled()
+ expect(b).toHaveBeenCalledTimes(1)
+ expect(t.listeners.size).toBe(1)
+ unB()
+ expect(t.listeners.size).toBe(0)
+ // Re-subscribing re-installs.
+ on(a)
+ expect(t.listeners.size).toBe(1)
+ })
+})
diff --git a/src/renderer/bridge/markdown-toggle-key.ts b/src/renderer/bridge/markdown-toggle-key.ts
new file mode 100644
index 000000000..44bf51918
--- /dev/null
+++ b/src/renderer/bridge/markdown-toggle-key.ts
@@ -0,0 +1,118 @@
+// The Server Edition's `onMarkdownToggle`: the browser half of the ⌘/Ctrl+M chord.
+//
+// On the DESKTOP the chord never reaches the page — `main/keydown-intercept.ts` claims it in
+// `before-input-event` (it is `{role:'minimize'}`'s accelerator otherwise) and forwards
+// `app:toggle-markdown` over IPC, which is what `window.nodeTerminal.onMarkdownToggle` subscribes
+// to there. A browser tab has no main process, so the stub used to be `noopUnsub` and the chord did
+// nothing at all in the Server Edition (the view was reachable only from the context menu). This is
+// the replacement: ONE window `keydown` listener, installed lazily on the first subscription, that
+// matches the user's effective `node.toggleMarkdown` bindings, `preventDefault`s a match and fans
+// out to every subscriber — the same contract the IPC event has, so TerminalNode / EditorNode /
+// Canvas's capture notice (and the kanban card modal) need no browser branch.
+//
+// **It cannot fire twice on desktop**: it is only reachable through `buildStubApi`, which the
+// desktop's own `window.nodeTerminal` (the preload) never uses. The relay tab also builds a stub
+// surface but takes `onMarkdownToggle` from the LOCAL preload (`...local`), and the lazy install
+// means merely building the stub registers nothing.
+//
+// Semantics mirror the desktop intercept, with three deliberate additions:
+// - **terminal-first** stands it down while a terminal has focus (`policyStandsDown`, the SAME
+// predicate main uses). Focus comes from the DOM exactly as the renderer's dispatcher decides
+// it (`isTerminalTarget` — xterm's helper textarea), not from a mirror: there is nothing to
+// mirror to in a browser, and the live answer is the only honest one.
+// - **auto-repeat is swallowed, never re-toggled**: a held chord would otherwise strobe the view.
+// Still `preventDefault`ed so the held key keeps being ours (the ⌘0 intercept's shape).
+// - An event a child handler already claimed (`defaultPrevented`) is left alone, the same first
+// rule `dispatchGlobalKeydown` applies.
+//
+// Bubble phase on purpose, like the window dispatcher: the Settings shortcut recorder's
+// `stopPropagation` on an armed capture is what keeps a chord being RECORDED from firing the
+// command it is being bound to, and a capture-phase listener would run before it. The price is
+// that a surface which consumes the key itself never lets it reach the window: xterm would (it
+// writes \r and cancels), which is why `terminalChordBubbles` lets this command bubble out of a
+// focused terminal; Monaco binds Ctrl+M to "toggle tab-key focus mode" off-mac and still does
+// inside a focused editor. Hover the node with focus elsewhere to toggle an editor from the key.
+//
+// **macOS Chrome reserves ⌘M for window minimize** — the browser takes it above the page, so the
+// default chord only reaches us on Linux/Windows (where it is Ctrl+M) or after a remap in
+// Settings → Keyboard Shortcuts. The context menu's "Markdown view" works everywhere.
+
+import { matchesShortcut, type ShortcutKeyEvent } from '../../shared/shortcut'
+import { policyStandsDown, type TerminalShortcutPolicy } from '../../shared/keybindings'
+import { isTerminalTarget, type ContextElement } from '../lib/keyContext'
+
+/** The keydown fields the decision reads (structural, so node-env tests need no DOM). */
+export interface MarkdownToggleKeyEvent extends ShortcutKeyEvent {
+ repeat: boolean
+ defaultPrevented: boolean
+}
+
+/** `toggle` = claim and forward; `swallow` = claim, forward nothing (a held chord); `null` = not
+ * ours — no `preventDefault`, the key goes on to the page. */
+export type MarkdownToggleKeyVerdict = 'toggle' | 'swallow' | null
+
+/** PURE. What this keydown means for the markdown toggle. */
+export function markdownToggleKeyVerdict(
+ e: MarkdownToggleKeyEvent,
+ ctx: {
+ bindings: readonly string[]
+ isMac: boolean
+ policy: TerminalShortcutPolicy
+ terminalFocused: boolean
+ }
+): MarkdownToggleKeyVerdict {
+ if (e.defaultPrevented) return null
+ if (policyStandsDown(ctx.policy, ctx.terminalFocused)) return null
+ // `[]` (the user disabled the command) matches nothing, which is the "do not claim" answer.
+ if (!ctx.bindings.some((s) => matchesShortcut(e, s, ctx.isMac))) return null
+ return e.repeat ? 'swallow' : 'toggle'
+}
+
+/** Minimal EventTarget shape (the real `window` in production, a fake in tests). */
+export interface KeydownTarget {
+ addEventListener(type: 'keydown', listener: (e: KeyboardEvent) => void): void
+ removeEventListener(type: 'keydown', listener: (e: KeyboardEvent) => void): void
+}
+
+/** Everything is a thunk and read PER KEYSTROKE: a remap or a policy change applies on the next
+ * key without resubscribing, exactly as the window dispatcher reads them. */
+export interface MarkdownToggleSourceDeps {
+ target: KeydownTarget
+ bindings: () => readonly string[]
+ isMac: () => boolean
+ policy: () => TerminalShortcutPolicy
+ activeElement: () => ContextElement | null
+}
+
+/** An `onMarkdownToggle`-shaped subscribe function backed by ONE shared window listener, which
+ * exists exactly while at least one subscriber does. */
+export function createMarkdownToggleSource(
+ deps: MarkdownToggleSourceDeps
+): (listener: () => void) => () => void {
+ const subscribers = new Set<() => void>()
+ const onKeydown = (e: KeyboardEvent): void => {
+ const verdict = markdownToggleKeyVerdict(e, {
+ bindings: deps.bindings(),
+ isMac: deps.isMac(),
+ policy: deps.policy(),
+ terminalFocused: isTerminalTarget(deps.activeElement())
+ })
+ if (verdict === null) return
+ e.preventDefault()
+ if (verdict === 'swallow') return
+ // Snapshot: a subscriber that unsubscribes (or mounts another) mid-fan-out must not skip or
+ // double-call a sibling.
+ for (const fn of [...subscribers]) fn()
+ }
+ return (listener) => {
+ // A wrapper per subscription so the same function subscribed twice is two subscriptions —
+ // the IPC-backed desktop version behaves that way too.
+ const entry = (): void => listener()
+ if (subscribers.size === 0) deps.target.addEventListener('keydown', onKeydown)
+ subscribers.add(entry)
+ return () => {
+ if (!subscribers.delete(entry)) return
+ if (subscribers.size === 0) deps.target.removeEventListener('keydown', onKeydown)
+ }
+ }
+}
diff --git a/src/renderer/bridge/stubs.dom.test.ts b/src/renderer/bridge/stubs.dom.test.ts
new file mode 100644
index 000000000..f243c648e
--- /dev/null
+++ b/src/renderer/bridge/stubs.dom.test.ts
@@ -0,0 +1,46 @@
+// @vitest-environment jsdom
+//
+// The Server Edition's ⌘M path end to end through the REAL stub surface: a keydown dispatched on
+// the browser `window` must reach an `onMarkdownToggle` subscriber, following the user's live
+// `node.toggleMarkdown` binding from the settings store. (jsdom reports a non-mac platform, so the
+// default `Cmd+M` resolves to Ctrl+M here.)
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { DEFAULT_SETTINGS } from '@shared/types'
+import { useSettings } from '../state/settings'
+import { buildStubApi } from './stubs'
+
+const press = (init: KeyboardEventInit) => {
+ const e = new KeyboardEvent('keydown', { bubbles: true, cancelable: true, ...init })
+ window.dispatchEvent(e)
+ return e
+}
+
+beforeEach(() => useSettings.setState({ settings: { ...DEFAULT_SETTINGS } }))
+
+describe('bridge onMarkdownToggle (browser)', () => {
+ it('fires on the default chord and claims it; stops after unsubscribe', () => {
+ const s = buildStubApi()
+ const cb = vi.fn()
+ const un = s.onMarkdownToggle(cb)
+ const e = press({ key: 'm', ctrlKey: true })
+ expect(cb).toHaveBeenCalledTimes(1)
+ expect(e.defaultPrevented).toBe(true)
+ un()
+ press({ key: 'm', ctrlKey: true })
+ expect(cb).toHaveBeenCalledTimes(1)
+ })
+
+ it('follows a remap from the settings store', () => {
+ useSettings.setState({
+ settings: { ...DEFAULT_SETTINGS, keybindings: { 'node.toggleMarkdown': ['Cmd+Alt+M'] } }
+ })
+ const s = buildStubApi()
+ const cb = vi.fn()
+ const un = s.onMarkdownToggle(cb)
+ press({ key: 'm', ctrlKey: true })
+ expect(cb).not.toHaveBeenCalled()
+ press({ key: 'm', ctrlKey: true, altKey: true })
+ expect(cb).toHaveBeenCalledTimes(1)
+ un()
+ })
+})
diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.ts
index bab26986d..17b0a755d 100644
--- a/src/renderer/bridge/stubs.ts
+++ b/src/renderer/bridge/stubs.ts
@@ -25,6 +25,10 @@ import {
type UpdatePolicy
} from '../../shared/types'
import { E_UNSUPPORTED } from '../../shared/rpc'
+import { isMacPlatform } from '../../shared/platform-utils'
+import { effectiveBindings, terminalShortcutPolicy } from '../lib/keybindingOverrides'
+import type { ContextElement } from '../lib/keyContext'
+import { createMarkdownToggleSource } from './markdown-toggle-key'
/** Reject with a coded error the RPC layer + renderer recognize (renderer degrades silently). */
export function unsupported(name: string): Promise<never> {
@@ -462,7 +466,8 @@ export function buildStubApi(): Omit<
// Deliberate no-op (not a gap): the recording bit exists to stand the DESKTOP's
// `before-input-event` intercepts down, and a browser tab has no application menu to steal
// ⌘W/⌘M/⌘0 back from — nothing intercepts here, so there is nothing to suspend. The
- // recorder's own preventDefault/stopPropagation is the whole path in this shell.
+ // recorder's own preventDefault/stopPropagation is the whole path in this shell; that also
+ // covers the ⌘M window listener below, which is bubble-phase and skips a prevented event.
setRecording: noop,
// Deliberate no-op for the same reason, one step further: the mirror exists so the DESKTOP's
// intercepts can stand down under `terminal-first`, and there are no intercepts here to
@@ -470,7 +475,20 @@ export function buildStubApi(): Omit<
// renderer's own dispatcher (`keyDispatchContextFor`), which reads focus directly.
setTerminalFocused: noop
},
- onMarkdownToggle: noopUnsub,
+ // REAL, not a stub: a browser tab has no main process to intercept ⌘/Ctrl+M, so the chord is
+ // matched by a window keydown listener here (bindings, terminal-first stand-down and focus all
+ // read live — see markdown-toggle-key.ts, including why macOS Chrome never delivers ⌘M).
+ // Node-env tests have no window: they get the inert unsubscribe the boot contract requires.
+ onMarkdownToggle:
+ typeof window === 'undefined'
+ ? noopUnsub
+ : createMarkdownToggleSource({
+ target: window,
+ bindings: () => effectiveBindings('node.toggleMarkdown'),
+ isMac: isMacPlatform,
+ policy: terminalShortcutPolicy,
+ activeElement: () => document.activeElement as unknown as ContextElement | null
+ }),
onCloseNode: noopUnsub,
// Deliberate no-op (not a gap): a browser tab has no application menu to steal ⌘0, so the
// renderer's own keydown handler is the whole path there.
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 9caa2580a..ab795b9e2 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -235,6 +235,7 @@ import {
type GlobalKeydownDeps
} from '../lib/globalKeybindings'
import { isTerminalTarget, type ContextElement } from '../lib/keyContext'
+import { nextMdMode } from '../lib/markdownModeToggle'
import { installTerminalFocusMirror } from '../lib/terminalFocusMirror'
import { nodeToRefocus } from '../lib/focusRestore'
import { openDialogCount } from '../components/dialog-stack'
@@ -5617,6 +5618,11 @@ export function Canvas() {
// TerminalNode and EditorNode each subscribe for themselves — so this listener exists ONLY to
// raise the same notice, and must stay side-effect-free: it consumes nothing, prevents nothing,
// and the nodes' own subscriptions are untouched by it.
+ // The same event arrives from the Server Edition's browser keydown listener
+ // (bridge/markdown-toggle-key.ts) instead of IPC, and the semantics carry over unchanged: that
+ // listener fires only when it CLAIMED the chord (it stands down under terminal-first exactly as
+ // main does, and xterm lets the chord bubble out to it), so a focused terminal here still means
+ // app-first took the key from it — and `noteTerminalCapture` is itself silent otherwise.
useEffect(() => {
return window.nodeTerminal.onMarkdownToggle(() => {
if (isTerminalTarget(document.activeElement as unknown as ContextElement | null)) {
@@ -6293,16 +6299,18 @@ export function Canvas() {
return () => setMoveIntoWorktreeHandler(null)
}, [requestMoveIntoWorktree])
+ // One verdict for the whole targeted set (`nextMdMode`): a mixed selection turns the view ON
+ // everywhere instead of inverting each node, which no number of clicks could ever unify.
const toggleMarkdown = useCallback(
(ids: string[]) => {
const set = new Set(ids)
- setNodes((ns) =>
- ns.map((n) =>
- set.has(n.id) && n.type === 'terminal'
- ? { ...n, data: { ...n.data, mdMode: !n.data.mdMode } }
- : n
+ setNodes((ns) => {
+ const next = nextMdMode(ns, ids)
+ if (next === null) return ns
+ return ns.map((n) =>
+ set.has(n.id) && n.type === 'terminal' ? { ...n, data: { ...n.data, mdMode: next } } : n
)
- )
+ })
},
[setNodes]
)
@@ -8294,7 +8302,10 @@ export function Canvas() {
'node.zoneUp': () => snapNodeToZone('top-half'),
'node.zoneDown': () => snapNodeToZone('bottom-half')
// node.close / node.toggleMarkdown: main-process intercepted on desktop; deliberately
- // no renderer handler (the browser owns ⌘W in the Server Edition — see bridge/stubs.ts).
+ // no renderer handler here. The browser owns ⌘W in the Server Edition (see
+ // bridge/stubs.ts); ⌘/Ctrl+M there is matched by the bridge's OWN window listener
+ // (bridge/markdown-toggle-key.ts), which feeds the same `onMarkdownToggle` subscribers the
+ // desktop IPC does — a handler here as well would toggle every hovered node twice.
// terminal.* / scm.commit / speech.dictation: owned by their local listeners.
},
gestures: {
diff --git a/src/renderer/lib/keybindingOverrides.test.ts b/src/renderer/lib/keybindingOverrides.test.ts
index b049812cb..7c33ca7ed 100644
--- a/src/renderer/lib/keybindingOverrides.test.ts
+++ b/src/renderer/lib/keybindingOverrides.test.ts
@@ -261,6 +261,31 @@ describe('terminalChordBubbles', () => {
expect(terminalKeyAction(event, false, false, bubbles)).toBe('pass')
})
+ it('bubbles the markdown toggle out of a focused terminal (its window listener owns it)', () => {
+ // The Server Edition's `onMarkdownToggle` is a window keydown listener; if xterm kept the
+ // chord it would write \r and cancel the event, and ⌘M would be dead in every focused
+ // terminal. On desktop main claims it above the page, so this never runs there under
+ // app-first, and under terminal-first the resolver refuses it (next case).
+ setKb({ 'node.toggleMarkdown': ['Ctrl+M'] })
+ const event = { ...bubbleEv({ ctrlKey: true, key: 'm' }), type: 'keydown', code: 'KeyM' }
+ const bubbles = terminalChordBubbles(event, false)
+ expect(bubbles).toBe(true)
+ expect(terminalKeyAction(event, false, false, bubbles)).toBe('bubble')
+ // Over the board too: the card modal's terminal is a markdown-toggle target as well.
+ expect(terminalChordBubbles(event, true)).toBe(true)
+ })
+
+ it('keeps the markdown toggle in xterm under terminal-first', () => {
+ useSettings.setState({
+ settings: {
+ ...DEFAULT_SETTINGS,
+ keybindings: { 'node.toggleMarkdown': ['Ctrl+M'] } as never,
+ terminalShortcutPolicy: 'terminal-first'
+ }
+ })
+ expect(terminalChordBubbles(bubbleEv({ ctrlKey: true, key: 'm' }), false)).toBe(false)
+ })
+
it('false for a chord nothing resolves', () => {
setKb(undefined)
expect(
diff --git a/src/renderer/lib/keybindingOverrides.ts b/src/renderer/lib/keybindingOverrides.ts
index d0769bfc9..fd36299e0 100644
--- a/src/renderer/lib/keybindingOverrides.ts
+++ b/src/renderer/lib/keybindingOverrides.ts
@@ -122,7 +122,17 @@ export function terminalShortcutPolicy(): TerminalShortcutPolicy {
* listeners own them and this helper must not reroute their chords. Main-intercepted commands
* are excluded too: the window dispatcher deliberately has no handlers for them. If the main
* process stands down (notably Ctrl+W in a focused Linux/Windows terminal), xterm must retain the
- * chord so the control byte reaches the pty. */
+ * chord so the control byte reaches the pty.
+ *
+ * **Except `node.toggleMarkdown`, which bubbles.** Its Server Edition owner is a WINDOW keydown
+ * listener (`bridge/markdown-toggle-key.ts` — a browser has no main process to intercept it), and
+ * xterm would turn Ctrl+M into a \r write and cancel the event, leaving ⌘M dead in exactly the
+ * terminal the user is looking at. On desktop this changes nothing: under app-first main claims
+ * the chord above the page so this never runs for it, under terminal-first the resolver above
+ * already refuses it (`null` — the byte stays with the shell), and the one other main stand-down
+ * (an armed shortcut recorder) has the recorder, not a terminal, focused. Unlike Ctrl+W there is
+ * no terminal-focus stand-down in main for it, so there is no desktop case where xterm must keep
+ * it. */
export function terminalChordBubbles(e: ShortcutKeyEvent, kanbanOpen: boolean): boolean {
const id = resolveCommandForKeyEvent(
e,
@@ -135,7 +145,8 @@ export function terminalChordBubbles(e: ShortcutKeyEvent, kanbanOpen: boolean):
activeKeybindingOverrides(),
isMacPlatform()
)
- if (id === null || MAIN_INTERCEPTED_COMMAND_IDS.includes(id)) return false
+ if (id === null) return false
+ if (id !== 'node.toggleMarkdown' && MAIN_INTERCEPTED_COMMAND_IDS.includes(id)) return false
return COMMANDS_BY_ID.get(id)?.scope !== 'terminal'
}
diff --git a/src/renderer/lib/markdownModeToggle.test.ts b/src/renderer/lib/markdownModeToggle.test.ts
new file mode 100644
index 000000000..4ab116157
--- /dev/null
+++ b/src/renderer/lib/markdownModeToggle.test.ts
@@ -0,0 +1,35 @@
+import { describe, it, expect } from 'vitest'
+import { nextMdMode } from './markdownModeToggle'
+
+const term = (id: string, mdMode?: boolean) => ({ id, type: 'terminal', data: { mdMode } })
+const other = (id: string) => ({ id, type: 'sticky', data: {} })
+
+describe('nextMdMode', () => {
+ it('turns the view ON for every target when ANY targeted terminal has it off', () => {
+ // The bug this replaces: a per-node flip inverted a mixed selection (on→off, off→on).
+ const nodes = [term('a', true), term('b', false), term('c')]
+ expect(nextMdMode(nodes, ['a', 'b', 'c'])).toBe(true)
+ })
+
+ it('turns it OFF for all only when every targeted terminal already has it on', () => {
+ const nodes = [term('a', true), term('b', true)]
+ expect(nextMdMode(nodes, ['a', 'b'])).toBe(false)
+ })
+
+ it('a single node still toggles (the non-selection case is unchanged)', () => {
+ expect(nextMdMode([term('a', false)], ['a'])).toBe(true)
+ expect(nextMdMode([term('a', true)], ['a'])).toBe(false)
+ expect(nextMdMode([term('a')], ['a'])).toBe(true)
+ })
+
+ it('ignores non-terminal and untargeted nodes when deciding', () => {
+ // An untargeted terminal that is off, and a targeted sticky, must not flip the verdict.
+ const nodes = [term('a', true), term('b', false), other('s')]
+ expect(nextMdMode(nodes, ['a', 's'])).toBe(false)
+ })
+
+ it('null when no targeted terminal exists (nothing to decide)', () => {
+ expect(nextMdMode([other('s'), term('a', false)], ['s'])).toBeNull()
+ expect(nextMdMode([], ['x'])).toBeNull()
+ })
+})
diff --git a/src/renderer/lib/markdownModeToggle.ts b/src/renderer/lib/markdownModeToggle.ts
new file mode 100644
index 000000000..fb35efa5e
--- /dev/null
+++ b/src/renderer/lib/markdownModeToggle.ts
@@ -0,0 +1,22 @@
+/**
+ * The context menu's "Markdown view" over a SELECTION: one verdict for every targeted terminal.
+ *
+ * It used to flip each node independently, so a mixed selection INVERTED — the nodes showing the
+ * view turned it off while the others turned it on — and no number of clicks could bring the
+ * selection into one state. The rule now is the usual multi-select toggle (Finder's, Figma's): if
+ * ANY targeted terminal has the view off, the action turns it ON for all of them; only when every
+ * one already has it on does it turn them all off. A single node still simply toggles.
+ *
+ * Only terminal nodes carry `mdMode` (an editor's preview is its own local state), so everything
+ * else — and every untargeted node — is ignored when deciding. `null` = no targeted terminal, i.e.
+ * nothing to change.
+ */
+export function nextMdMode(
+ nodes: readonly { id: string; type?: string; data: Readonly<Record<string, unknown>> }[],
+ ids: readonly string[]
+): boolean | null {
+ const set = new Set(ids)
+ const targets = nodes.filter((n) => set.has(n.id) && n.type === 'terminal')
+ if (!targets.length) return null
+ return targets.some((n) => !n.data.mdMode)
+}
diff --git a/src/shared/keybindings.ts b/src/shared/keybindings.ts
index ddcf9fe9d..e69aca274 100644
--- a/src/shared/keybindings.ts
+++ b/src/shared/keybindings.ts
@@ -523,6 +523,34 @@ export function normalizeTerminalShortcutPolicy(v: unknown): TerminalShortcutPol
return v === 'terminal-first' ? 'terminal-first' : 'app-first'
}
+/**
+ * PURE. Does the user's `terminalShortcutPolicy` mean this window must stop claiming chords right
+ * now? The composition `index.ts` hands to `installKeydownIntercepts`' 5th parameter, exported so
+ * it can be pressed instead of living untested inside a closure in a 5000-line file. It lives in
+ * `shared` because it has TWO consumers: the desktop intercept (`main/keydown-intercept.ts`, which
+ * re-exports it) and the Server Edition's browser-side ⌘M listener
+ * (`renderer/bridge/markdown-toggle-key.ts`, which feeds it focus read straight from the DOM).
+ *
+ * **Both halves are refusals and both matter.** `app-first` is the shipped default, so it must be
+ * false whatever the mirror reports — that is the byte-identical guarantee of this feature: a user
+ * who never touched the setting sees exactly the pre-feature intercepts, even though their
+ * renderer is reporting terminal focus all day. And `terminalFocused` is a MIRROR of the
+ * renderer's `document.activeElement`, which is why `false` is its reset value everywhere: a page
+ * that died mid-report, a window that never had one, a reload — all resolve to "intercepts on",
+ * never to "intercepts off with nothing alive to turn them back on".
+ *
+ * Why the policy is read here rather than the intercepts simply being uninstalled under
+ * `terminal-first`: the policy is a live setting and the focus changes per keystroke, so there is
+ * nothing static to install against — and an app-first user's window must not be a different
+ * window from a terminal-first user's.
+ */
+export function policyStandsDown(
+ policy: TerminalShortcutPolicy,
+ terminalFocused: boolean
+): boolean {
+ return policy === 'terminal-first' && terminalFocused
+}
+
/** `typing` and `terminal` are expected to be DISJOINT — xterm's hidden textarea is a terminal,
* not a typing surface, so a caller classifying focus must not report both. If one does anyway,
* `typing` wins (it is checked first) and every terminal-scope command becomes unreachable. */