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(security): a keystroke aimed elsewhere can no longer answer a confirm dialog

enes1ccfeb97c441
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 01c63ed59..e400f48ea 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -194,6 +194,48 @@ const GRID = 24
/** How long a successful worktree notice stays on screen before fading itself out. */
const NOTICE_MS = 6000
+/** The confirm dialogs, named so their setters can be wrapped in a synchronous open-guard (see
+ * `confirmFlags`): ONE confirm at a time, decided at call time rather than at the next render. */
+interface ConfirmState {
+ message: string
+ onConfirm: () => void
+ /** Optional: runs when the user cancels/escapes (e.g. to reply 'denied' to an agent). */
+ onCancel?: () => void
+ confirmLabel?: string
+ cancelLabel?: string
+ danger?: boolean
+ /** Set when an AGENT asked for this dialog: it is answered by an explicit click, never by an
+ * Enter the user aimed at their terminal (see components/confirm-key). */
+ requestedBy?: string
+}
+interface RemoveState {
+ groupId: string
+ warning: string
+ /** nodeterm created this directory (`worktree.createdByApp`), so deleting it is ours to offer as
+ * the default. A worktree the user made outside the app defaults to Unbind, and deleting it from
+ * disk is an explicit opt-in (`deleteFromDisk`). */
+ canDelete: boolean
+ /** Named in the dialog, so the user approves the worktree they were shown — not whichever one
+ * the group happens to point at by the time they hit Enter. */
+ branch: string
+ path: string
+ /** Set when an AGENT asked (canvas-control `close-worktree --mode remove`); the dialog says so,
+ * exactly like the agent `write`/`close` confirms do — AND refuses to be confirmed by keyboard. */
+ requestedBy?: string
+}
+interface MergeState {
+ repoPath: string
+ branch: string
+ baseRef: string
+ /** Whether the dialog offers (and warns about) the push to origin — a repo with no `origin` must
+ * never be threatened with a publish that cannot happen. */
+ hasOrigin: boolean
+}
+interface PendingPeerState {
+ sas: string | null
+ id: string
+}
+
/**
* Worktrees are out of scope for SSH projects in v1, and being honestly absent beats being
* silently wrong: the default worktree path is computed from the LOCAL data dir while the git
@@ -392,16 +434,8 @@ export function Canvas() {
// Live SSH ControlMaster status per project id (drives the thin connection banner).
const [sshStatus, setSshStatus] = useState<Record<string, SshProjectStatus>>({})
// A client has finished the handshake and is awaiting this host's approval (carries the SAS).
- const [pendingPeer, setPendingPeer] = useState<{ sas: string | null; id: string } | null>(null)
- const [confirm, setConfirm] = useState<{
- message: string
- onConfirm: () => void
- /** Optional: runs when the user cancels/escapes (e.g. to reply 'denied' to an agent). */
- onCancel?: () => void
- confirmLabel?: string
- cancelLabel?: string
- danger?: boolean
- } | null>(null)
+ const [pendingPeer, setPendingPeerState] = useState<PendingPeerState | null>(null)
+ const [confirm, setConfirmState] = useState<ConfirmState | null>(null)
// Node to center once its project finishes loading (cross-project notification click).
const pendingFocusRef = useRef<string | null>(null)
const [consentOpen, setConsentOpen] = useState(false)
@@ -467,23 +501,12 @@ export function Canvas() {
return () => window.removeEventListener('nodeterm:toast', onToast)
}, [])
// Terminal node id awaiting confirmation to move into its group's worktree.
- const [moveTarget, setMoveTarget] = useState<string | null>(null)
+ const [moveTarget, setMoveTargetState] = useState<string | null>(null)
// Group awaiting confirmation to remove its worktree (drives the ask-first safety dialog).
// `canDelete` = nodeterm created this directory (`worktree.createdByApp`), so deleting it is
// ours to offer as the default. For a worktree the user made outside the app and merely bound,
// the default is Unbind and deleting from disk is an explicit opt-in (`deleteFromDisk`).
- const [removeTarget, setRemoveTarget] = useState<{
- groupId: string
- warning: string
- canDelete: boolean
- /** Named in the dialog, so the user approves the worktree they were shown — not whichever one
- * the group happens to point at by the time they hit Enter. */
- branch: string
- path: string
- /** Set when an AGENT asked (canvas-control `close-worktree --mode remove`); the dialog says so,
- * exactly like the agent `write`/`close` confirms do. */
- requestedBy?: string
- } | null>(null)
+ const [removeTarget, setRemoveTargetState] = useState<RemoveState | null>(null)
/**
* True from the instant a removal confirm is REQUESTED until its dialog closes. `removeTarget`
* alone cannot carry this: `requestRemoveWorktree` awaits `git.status` before opening, and two
@@ -496,12 +519,7 @@ export function Canvas() {
// Group awaiting confirmation to merge its worktree into the base branch. `hasOrigin` decides
// whether the dialog offers (and warns about) the push to origin — a repo with no `origin` must
// never be threatened with a publish that cannot happen.
- const [mergeTarget, setMergeTarget] = useState<{
- repoPath: string
- branch: string
- baseRef: string
- hasOrigin: boolean
- } | null>(null)
+ const [mergeTarget, setMergeTargetState] = useState<MergeState | null>(null)
const [mergePush, setMergePush] = useState(false)
const settings = useSettings((s) => s.settings)
const viewportRef = useRef<Viewport>({ x: 0, y: 0, zoom: 1 })
@@ -561,13 +579,42 @@ export function Canvas() {
* answers keys while it is topmost (see components/dialog-stack), but a destructive dialog the
* user cannot even SEE must not exist in the first place: every confirm state is in this guard.
*/
- const confirmOpenRef = useRef(false)
- confirmOpenRef.current = !!(confirm || removeTarget || moveTarget || mergeTarget || pendingPeer)
+ const confirmFlags = useRef({
+ confirm: false,
+ remove: false,
+ move: false,
+ merge: false,
+ peer: false
+ })
+ // Every confirm setter flips its flag AT CALL TIME. Assigning the mirror during RENDER (what this
+ // used to do) is a tick too late: two agent verbs arriving in separate IPC events before React
+ // commits both read the stale `false` and both open a dialog — the very stacking this guard
+ // exists to prevent.
+ const setConfirm = useCallback((v: ConfirmState | null) => {
+ confirmFlags.current.confirm = !!v
+ setConfirmState(v)
+ }, [])
+ const setRemoveTarget = useCallback((v: RemoveState | null) => {
+ confirmFlags.current.remove = !!v
+ setRemoveTargetState(v)
+ }, [])
+ const setMoveTarget = useCallback((v: string | null) => {
+ confirmFlags.current.move = !!v
+ setMoveTargetState(v)
+ }, [])
+ const setMergeTarget = useCallback((v: MergeState | null) => {
+ confirmFlags.current.merge = !!v
+ setMergeTargetState(v)
+ }, [])
+ const setPendingPeer = useCallback((v: PendingPeerState | null) => {
+ confirmFlags.current.peer = !!v
+ setPendingPeerState(v)
+ }, [])
/** Is any confirm open — or being opened (the async gap in `requestRemoveWorktree`)? */
- const confirmBusy = useCallback(
- () => confirmOpenRef.current || removePendingRef.current,
- []
- )
+ const confirmBusy = useCallback(() => {
+ const f = confirmFlags.current
+ return f.confirm || f.remove || f.move || f.merge || f.peer || removePendingRef.current
+ }, [])
const nodeTypes = useMemo(
() => ({
@@ -2815,7 +2862,11 @@ export function Canvas() {
break
}
case 'remove':
- void requestRemoveWorktree(groupId)
+ // A refusal (another confirm is already open) used to be discarded here, so Remove simply
+ // looked broken. Say it out loud instead.
+ void requestRemoveWorktree(groupId).then((res) => {
+ if (!res.ok && res.error) setNotice({ kind: 'error', text: res.error })
+ })
break
default:
break
@@ -4136,6 +4187,7 @@ export function Canvas() {
setConfirm({
message: `Agent "${srcTitle}" wants to send to ${args.node}:\n\n${args.text ?? ''}`,
confirmLabel: 'Send',
+ requestedBy: srcTitle,
onConfirm: async () => {
setConfirm(null)
try {
@@ -4167,6 +4219,7 @@ export function Canvas() {
// Destructive → confirm. Replies on confirm AND cancel.
setConfirm({
message: `Agent "${srcTitle}" wants to close node ${args.node}. Close it?`,
+ requestedBy: srcTitle,
confirmLabel: 'Close',
danger: true,
onConfirm: () => {
@@ -5331,6 +5384,9 @@ export function Canvas() {
confirmLabel={confirm.confirmLabel}
cancelLabel={confirm.cancelLabel}
danger={confirm.danger}
+ // The user did not open this one — an agent did. It appeared under their hands, so it is
+ // answered by a click, never by a keystroke aimed somewhere else (components/confirm-key).
+ enterConfirms={!confirm.requestedBy}
onConfirm={confirm.onConfirm}
onCancel={() => {
confirm.onCancel?.()
@@ -5456,6 +5512,9 @@ export function Canvas() {
})}
confirmLabel={deleteFromDisk ? 'Delete' : 'Unbind'}
danger={deleteFromDisk}
+ // An agent asked for this one: it appeared while the user was typing somewhere else, so
+ // no keystroke may confirm it — only a click on a button they had to look at.
+ enterConfirms={!removeTarget.requestedBy}
option={
// We created it → deletion is the point of the action, no opt-in to make. The user
// created it → deleting from disk is a deliberate extra choice, never the default.
diff --git a/src/renderer/components/ConfirmDialog.tsx b/src/renderer/components/ConfirmDialog.tsx
index 2b7a74163..161e933fa 100644
--- a/src/renderer/components/ConfirmDialog.tsx
+++ b/src/renderer/components/ConfirmDialog.tsx
@@ -1,5 +1,6 @@
import { useEffect, useRef } from 'react'
import { createPortal } from 'react-dom'
+import { confirmKeyAction } from './confirm-key'
import { isTopDialog, nextDialogId, popDialog, pushDialog } from './dialog-stack'
interface ConfirmDialogProps {
@@ -10,14 +11,22 @@ interface ConfirmDialogProps {
/** An explicit opt-in shown above the buttons (e.g. "Delete the worktree directory from disk
* too"). The caller owns the value, so it can also swap the confirm label / danger styling. */
option?: { label: string; checked: boolean; onChange: (checked: boolean) => void }
+ /**
+ * May Enter confirm this dialog? Default true — the user asked for it. Pass FALSE for a dialog
+ * the app raised on someone ELSE's behalf (an agent verb like `close-worktree`): the user never
+ * asked for it, it appeared under their hands, and it must be answered by an explicit click.
+ * Escape still cancels either way.
+ */
+ enterConfirms?: boolean
onConfirm: () => void
onCancel: () => void
}
/**
- * A small themed confirm dialog. Enter confirms, Esc cancels — but ONLY while this dialog is the
- * topmost one (see ./dialog-stack): the listener is on `window`, and a dialog painted underneath
- * another must never answer a key the user aimed at the one they can see.
+ * A small themed confirm dialog. Enter confirms and Esc cancels — but only under the conditions in
+ * ./confirm-key, which exist because this listener is on `window` and therefore sees every key the
+ * user aims at a terminal, a chat box or the command palette. Read that file before touching the
+ * key handling: a stray Enter used to be able to delete a worktree.
*/
export function ConfirmDialog({
message,
@@ -25,6 +34,7 @@ export function ConfirmDialog({
cancelLabel = 'Cancel',
danger = true,
option,
+ enterConfirms = true,
onConfirm,
onCancel
}: ConfirmDialogProps) {
@@ -32,6 +42,10 @@ export function ConfirmDialog({
const idRef = useRef<string>()
if (!idRef.current) idRef.current = nextDialogId()
const id = idRef.current
+ const boxRef = useRef<HTMLDivElement>(null)
+ // Set once, on the first render — not in an effect, so a key that arrives before the effect runs
+ // is still measured against the moment the dialog appeared.
+ const mountedAtRef = useRef(Date.now())
useEffect(() => {
pushDialog(id)
@@ -40,24 +54,30 @@ export function ConfirmDialog({
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
- // Not the dialog on top → this key is not ours. Do not preventDefault either: the topmost
- // dialog's own listener still has to see it.
- if (!isTopDialog(id)) return
- if (e.key === 'Escape') {
- e.preventDefault()
- onCancel()
- } else if (e.key === 'Enter') {
- e.preventDefault()
- onConfirm()
- }
+ const action = confirmKeyAction({
+ key: e.key,
+ repeat: e.repeat,
+ // Not the dialog on top → this key is not ours (the topmost dialog's own listener still has
+ // to see it, so we must not preventDefault it either).
+ top: isTopDialog(id),
+ // Aimed HERE, not at whatever had focus when we appeared. `boxRef` is the dialog box, so a
+ // key typed into a terminal underneath the overlay can never answer it.
+ inDialog: !!(e.target instanceof Node && boxRef.current?.contains(e.target)),
+ sinceMount: Date.now() - mountedAtRef.current,
+ enterConfirms
+ })
+ if (!action) return
+ e.preventDefault()
+ if (action === 'confirm') onConfirm()
+ else onCancel()
}
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
- }, [id, onConfirm, onCancel])
+ }, [id, enterConfirms, onConfirm, onCancel])
return createPortal(
<div className="confirm-overlay" onClick={onCancel}>
- <div className="confirm" onClick={(e) => e.stopPropagation()}>
+ <div className="confirm" ref={boxRef} onClick={(e) => e.stopPropagation()}>
<p className="confirm__msg">{message}</p>
{option && (
<label className="confirm__option">
@@ -70,12 +90,15 @@ export function ConfirmDialog({
</label>
)}
<div className="confirm__actions">
- <button className="confirm__btn" onClick={onCancel}>
+ {/* The DESTRUCTIVE button never takes focus: autoFocus on it is what turned a stray Enter
+ (or Space) into a deletion. On a danger dialog the safe button is the focused one; on a
+ harmless one the primary action may keep it. */}
+ <button className="confirm__btn" autoFocus={danger} onClick={onCancel}>
{cancelLabel}
</button>
<button
className={`confirm__btn${danger ? ' danger' : ' primary'}`}
- autoFocus
+ autoFocus={!danger}
onClick={onConfirm}
>
{confirmLabel}
diff --git a/src/renderer/components/InputDialog.tsx b/src/renderer/components/InputDialog.tsx
index e55e283a8..9d32d2f4a 100644
--- a/src/renderer/components/InputDialog.tsx
+++ b/src/renderer/components/InputDialog.tsx
@@ -1,5 +1,6 @@
import { useEffect, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
+import { useDialogStack } from './dialog-stack'
interface InputDialogProps {
message: string
@@ -27,6 +28,10 @@ export function InputDialog({
}: InputDialogProps) {
const [value, setValue] = useState(initialValue)
const inputRef = useRef<HTMLInputElement>(null)
+ // Registered in the modal stack so a ConfirmDialog underneath does not ALSO answer the Enter /
+ // Escape typed into this input (its own listener is on `window`). The keys here are handled on
+ // the input element itself, so nothing else is needed.
+ useDialogStack()
useEffect(() => {
inputRef.current?.focus()
diff --git a/src/renderer/components/NotifyConsentDialog.tsx b/src/renderer/components/NotifyConsentDialog.tsx
index bf395fc47..7629ebd5b 100644
--- a/src/renderer/components/NotifyConsentDialog.tsx
+++ b/src/renderer/components/NotifyConsentDialog.tsx
@@ -1,5 +1,6 @@
import { useEffect } from 'react'
import { createPortal } from 'react-dom'
+import { useDialogStack } from './dialog-stack'
interface Props {
onEnable: () => void
@@ -8,8 +9,12 @@ interface Props {
/** A polished one-time prompt asking to enable Claude completion notifications. */
export function NotifyConsentDialog({ onEnable, onDismiss }: Props) {
+ // Only the TOPMOST modal answers a key — this one and a ConfirmDialog can be on screen together,
+ // and both window listeners used to fire on one Enter (see ./dialog-stack).
+ const isTop = useDialogStack()
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
+ if (!isTop()) return
if (e.key === 'Escape') {
e.preventDefault()
onDismiss()
@@ -20,7 +25,7 @@ export function NotifyConsentDialog({ onEnable, onDismiss }: Props) {
}
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
- }, [onEnable, onDismiss])
+ }, [isTop, onEnable, onDismiss])
return createPortal(
<div className="consent-overlay" onClick={onDismiss}>
diff --git a/src/renderer/components/RemoteAccessDialog.tsx b/src/renderer/components/RemoteAccessDialog.tsx
index 1f106dd61..6ad37ef11 100644
--- a/src/renderer/components/RemoteAccessDialog.tsx
+++ b/src/renderer/components/RemoteAccessDialog.tsx
@@ -1,5 +1,6 @@
import { useEffect, useState } from 'react'
import { createPortal } from 'react-dom'
+import { useDialogStack } from './dialog-stack'
import { useEntitlement } from '../state/entitlement'
import { useRemoteHosting } from '../state/remoteHosting'
import { Button } from '@renderer/ui/Button'
@@ -26,8 +27,12 @@ export function RemoteAccessDialog({ onClose }: { onClose: () => void }): React.
const [clientSas, setClientSas] = useState<string | null>(null)
const [connectedId, setConnectedId] = useState<string | null>(null)
+ // Only the topmost modal answers a key (./dialog-stack) — the host approval ConfirmDialog opens
+ // on top of THIS dialog, and its Escape must not also close the one underneath.
+ const isTop = useDialogStack()
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
+ if (!isTop()) return
if (e.key === 'Escape') {
e.preventDefault()
onClose()
@@ -35,7 +40,7 @@ export function RemoteAccessDialog({ onClose }: { onClose: () => void }): React.
}
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
- }, [onClose])
+ }, [isTop, onClose])
const startHosting = async () => {
setError('')
diff --git a/src/renderer/components/SshProjectDialog.tsx b/src/renderer/components/SshProjectDialog.tsx
index 4a41c66ae..d26dceaab 100644
--- a/src/renderer/components/SshProjectDialog.tsx
+++ b/src/renderer/components/SshProjectDialog.tsx
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
+import { useDialogStack } from './dialog-stack'
import { useSshServers } from '../state/sshServers'
import { useEntitlement } from '../state/entitlement'
import { useUpgradeGate } from '../state/upgradeGate'
@@ -99,13 +100,16 @@ export function SshProjectDialog({ onCreate, onManage, onClose }: SshProjectDial
onClose()
}, [disconnectBrowse, onClose])
+ // Only the topmost modal answers a key (./dialog-stack).
+ const isTop = useDialogStack()
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
+ if (!isTop()) return
if (e.key === 'Escape') close()
}
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
- }, [close])
+ }, [isTop, close])
// Disconnect the browse master if the dialog unmounts without an explicit close.
useEffect(() => () => disconnectBrowse(), [disconnectBrowse])
diff --git a/src/renderer/components/WorktreeDialog.tsx b/src/renderer/components/WorktreeDialog.tsx
index a66f768a5..d1bfa9cac 100644
--- a/src/renderer/components/WorktreeDialog.tsx
+++ b/src/renderer/components/WorktreeDialog.tsx
@@ -1,5 +1,6 @@
import { useEffect, useState } from 'react'
import { createPortal } from 'react-dom'
+import { useDialogStack } from './dialog-stack'
import { isValidGitRef, type WorktreeCreateValue, type WorktreeEntry } from '@shared/worktree'
interface Props {
@@ -52,8 +53,12 @@ export function WorktreeDialog({
if (!baseEdited) setBaseRef(defaultBaseRef)
}, [defaultBaseRef, baseEdited])
+ // Only the topmost modal answers a key (./dialog-stack): this dialog and a ConfirmDialog can be
+ // open at the same time, and one Escape must not close both.
+ const isTop = useDialogStack()
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
+ if (!isTop()) return
if (e.key === 'Escape') {
e.preventDefault()
onCancel()
@@ -61,7 +66,7 @@ export function WorktreeDialog({
}
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
- }, [onCancel])
+ }, [isTop, onCancel])
// No writable base dir is known, so we refuse to *suggest* a path — an empty base would
// otherwise propose `/worktrees/…` at the filesystem root. The user can still type one. The hint
diff --git a/src/renderer/components/confirm-key.test.ts b/src/renderer/components/confirm-key.test.ts
new file mode 100644
index 000000000..e4394dc7a
--- /dev/null
+++ b/src/renderer/components/confirm-key.test.ts
@@ -0,0 +1,64 @@
+import { describe, it, expect } from 'vitest'
+import { confirmKeyAction, CONFIRM_ARM_MS, type ConfirmKeyContext } from './confirm-key'
+
+/** A key the user aimed at the dialog they are looking at, well after it appeared. */
+const aimedHere = (over: Partial<ConfirmKeyContext> = {}): ConfirmKeyContext => ({
+ key: 'Enter',
+ repeat: false,
+ top: true,
+ inDialog: true,
+ sinceMount: 5_000,
+ enterConfirms: true,
+ ...over
+})
+
+describe('confirmKeyAction', () => {
+ it('confirms an Enter the user aimed at the dialog they opened and can see', () => {
+ expect(confirmKeyAction(aimedHere())).toBe('confirm')
+ })
+
+ // THE EXPLOIT. The user is typing in a terminal (or a chat box / rename field / palette — none of
+ // them dialogs, so no stack guard is engaged); an agent's `close-worktree --mode remove` mounts
+ // the removal dialog under their hands. The keydown bubbles to `window` either way — the only
+ // thing that distinguishes it is WHERE IT WAS AIMED.
+ it('ignores an Enter aimed at a terminal, even when this is the only dialog on screen', () => {
+ expect(confirmKeyAction(aimedHere({ inDialog: false }))).toBeNull()
+ })
+
+ // …and a keystroke already in flight when the dialog appeared cannot be caught by it either,
+ // however the focus lands.
+ it('ignores keys during the arming window after mount', () => {
+ expect(confirmKeyAction(aimedHere({ sinceMount: 0 }))).toBeNull()
+ expect(confirmKeyAction(aimedHere({ sinceMount: CONFIRM_ARM_MS - 1 }))).toBeNull()
+ expect(confirmKeyAction(aimedHere({ sinceMount: CONFIRM_ARM_MS }))).toBe('confirm')
+ })
+
+ it('ignores a held-down key (auto-repeat is not an answer)', () => {
+ expect(confirmKeyAction(aimedHere({ repeat: true }))).toBeNull()
+ })
+
+ // A dialog the app raised on an AGENT's behalf is not answered by a keystroke at all: the user
+ // never asked for it, so they must look at it and click.
+ it('never confirms an agent-initiated dialog by keyboard, but still cancels it', () => {
+ expect(confirmKeyAction(aimedHere({ enterConfirms: false }))).toBeNull()
+ expect(confirmKeyAction(aimedHere({ enterConfirms: false, key: 'Escape' }))).toBe('cancel')
+ })
+
+ it('never acts for a dialog that is not on top (the user is answering the one above it)', () => {
+ expect(confirmKeyAction(aimedHere({ top: false }))).toBeNull()
+ expect(confirmKeyAction(aimedHere({ top: false, key: 'Escape' }))).toBeNull()
+ })
+
+ // Escape only ever cancels — the worst it can do is make the user ask again — so it is not gated
+ // on the target or the arming window.
+ it('cancels on Escape from anywhere, immediately', () => {
+ expect(confirmKeyAction(aimedHere({ key: 'Escape', inDialog: false, sinceMount: 0 }))).toBe(
+ 'cancel'
+ )
+ })
+
+ it('ignores every other key', () => {
+ expect(confirmKeyAction(aimedHere({ key: 'a' }))).toBeNull()
+ expect(confirmKeyAction(aimedHere({ key: ' ' }))).toBeNull()
+ })
+})
diff --git a/src/renderer/components/confirm-key.ts b/src/renderer/components/confirm-key.ts
new file mode 100644
index 000000000..c44d01bd7
--- /dev/null
+++ b/src/renderer/components/confirm-key.ts
@@ -0,0 +1,59 @@
+/**
+ * WHICH KEY MAY ANSWER A CONFIRM DIALOG — the primitive, pure and testable.
+ *
+ * The dialog listens on `window` (a portal, no focus trap), so every keystroke in the app reaches
+ * it — including the ones the user aimed at a terminal, a chat box, a rename field or the command
+ * palette. None of those are dialogs, so the one-at-a-time / dialog-stack guards are not even
+ * engaged for them. That was enough to destroy data:
+ *
+ * 1. the user is typing into a terminal;
+ * 2. an agent calls `close-worktree --mode remove` → the removal dialog mounts, with "delete from
+ * disk" pre-ticked for an app-created worktree, and `autoFocus` on the DELETE button silently
+ * steals focus off the terminal;
+ * 3. the user finishes their thought and presses Enter → the window listener fires → the worktree
+ * directory (uncommitted work included) and its branch are gone.
+ *
+ * So a keystroke must satisfy ALL of the following before it can CONFIRM:
+ * - `top` — this is the dialog the user can actually see (./dialog-stack);
+ * - `inDialog` — the key was aimed HERE (its target is inside this dialog's own DOM), not at
+ * the terminal that happened to have focus;
+ * - `!repeat` — a key the user is holding down is not an answer;
+ * - `armed` — the dialog has been on screen for CONFIRM_ARM_MS; a dialog that appears
+ * underneath an in-flight keystroke must not be able to catch it;
+ * - `enterConfirms`— the user OPENED this dialog. One the app raised on someone else's behalf (an
+ * agent verb) is answered by an explicit click, never by a stray Enter.
+ *
+ * ESCAPE is deliberately laxer: it only ever CANCELS, so the worst it can do is make the user ask
+ * again. It needs `top` and nothing else.
+ */
+
+/** How long a freshly mounted dialog ignores confirmations (ms). Long enough to cover a keystroke
+ * already on its way when the dialog appeared; short enough to be invisible to a real user. */
+export const CONFIRM_ARM_MS = 500
+
+export interface ConfirmKeyContext {
+ key: string
+ /** `KeyboardEvent.repeat` — the user is holding the key down. */
+ repeat: boolean
+ /** Is this dialog the topmost one (the one being painted for the user)? */
+ top: boolean
+ /** Was the event's target inside this dialog's own DOM subtree? */
+ inDialog: boolean
+ /** ms since this dialog mounted. */
+ sinceMount: number
+ /** May Enter confirm this dialog at all? False for a dialog the user did not open. */
+ enterConfirms: boolean
+}
+
+/** The action a keydown may take on this dialog — or `null` (the key is not ours; do not even
+ * preventDefault it, the terminal/input it was aimed at still has to see it). */
+export function confirmKeyAction(c: ConfirmKeyContext): 'confirm' | 'cancel' | null {
+ if (!c.top) return null
+ if (c.key === 'Escape') return 'cancel'
+ if (c.key !== 'Enter') return null
+ if (c.repeat) return null
+ if (!c.enterConfirms) return null
+ if (!c.inDialog) return null
+ if (c.sinceMount < CONFIRM_ARM_MS) return null
+ return 'confirm'
+}
diff --git a/src/renderer/components/dialog-stack.ts b/src/renderer/components/dialog-stack.ts
index 419f1c735..888119a26 100644
--- a/src/renderer/components/dialog-stack.ts
+++ b/src/renderer/components/dialog-stack.ts
@@ -1,3 +1,5 @@
+import { useCallback, useEffect, useRef } from 'react'
+
/**
* The open-modal stack — which dialog owns the keyboard.
*
@@ -50,3 +52,22 @@ export function openDialogCount(): number {
export function resetDialogStack(): void {
stack.length = 0
}
+
+/**
+ * Register a modal for the life of the component and get back "do I own the keyboard?".
+ *
+ * EVERY modal belongs in this stack, not just `ConfirmDialog` — `WorktreeDialog`,
+ * `NotifyConsentDialog`, `SshProjectDialog`, `RemoteAccessDialog` and `InputDialog`/`promptDialog`
+ * each listen for Enter/Escape too, and one of them coexisting with a confirm meant a single Enter
+ * or Escape was answered by both.
+ */
+export function useDialogStack(): () => boolean {
+ const idRef = useRef<string>()
+ if (!idRef.current) idRef.current = nextDialogId()
+ const id = idRef.current
+ useEffect(() => {
+ pushDialog(id)
+ return () => popDialog(id)
+ }, [id])
+ return useCallback(() => isTopDialog(id), [id])
+}