Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

feat: support held-modifier keyboard chords through the live input path

Boschd2f72d0dbd3b
diff --git a/dashboard/src/components/screencast/useScreencastInput.ts b/dashboard/src/components/screencast/useScreencastInput.ts
index 2ed75eff..ed23e73f 100644
--- a/dashboard/src/components/screencast/useScreencastInput.ts
+++ b/dashboard/src/components/screencast/useScreencastInput.ts
@@ -95,15 +95,24 @@ export function useScreencastInput({
return;
}
e.preventDefault();
+ // CDP modifier bitmask: Alt=1, Ctrl=2, Meta=4, Shift=8. Forwarded with
+ // `press` so keyboard chords (Ctrl+C, Cmd+A, Shift+Arrow) reach the page.
+ const modifiers =
+ (e.altKey ? 1 : 0) |
+ (e.ctrlKey ? 2 : 0) |
+ (e.metaKey ? 4 : 0) |
+ (e.shiftKey ? 8 : 0);
try {
if (e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey) {
+ // Printable character with no command modifier (Shift-for-caps is
+ // already reflected in e.key) → insert as text.
await api.sendAction({
kind: "keyboard-inserttext",
tabId,
text: e.key,
});
} else {
- await api.sendAction({ kind: "press", tabId, key: e.key });
+ await api.sendAction({ kind: "press", tabId, key: e.key, modifiers });
}
} catch (err) {
console.error("key input failed", err);
diff --git a/internal/bridge/action_request.go b/internal/bridge/action_request.go
index c9783212..5020e496 100644
--- a/internal/bridge/action_request.go
+++ b/internal/bridge/action_request.go
@@ -62,6 +62,10 @@ type ActionRequest struct {
FrameW float64 `json:"frameW,omitempty"`
FrameH float64 `json:"frameH,omitempty"`
+ // Modifiers is the CDP key-modifier bitmask (Alt=1, Ctrl=2, Meta=4, Shift=8)
+ // held during a press, enabling keyboard chords such as Ctrl+C or Shift+Arrow.
+ Modifiers int `json:"modifiers,omitempty"`
+
ScrollX int `json:"scrollX"`
ScrollY int `json:"scrollY"`
// DeltaX/DeltaY are explicit mouse-wheel deltas for low-level
diff --git a/internal/bridge/action_text.go b/internal/bridge/action_text.go
index 5cb14ef3..0798f533 100644
--- a/internal/bridge/action_text.go
+++ b/internal/bridge/action_text.go
@@ -65,7 +65,7 @@ func (b *Bridge) actionPress(ctx context.Context, req ActionRequest) (map[string
return nil, err
}
}
- return map[string]any{"pressed": req.Key}, DispatchNamedKey(ctx, req.Key)
+ return map[string]any{"pressed": req.Key}, DispatchNamedKey(ctx, req.Key, req.Modifiers)
}
func (b *Bridge) actionHumanizedType(ctx context.Context, req ActionRequest) (map[string]any, error) {
diff --git a/internal/bridge/cdp_keyboard.go b/internal/bridge/cdp_keyboard.go
index 7fa35b9d..e14e913b 100644
--- a/internal/bridge/cdp_keyboard.go
+++ b/internal/bridge/cdp_keyboard.go
@@ -14,18 +14,18 @@ var namedKeyDefs = map[string]struct {
virtualKey int64
insertText string
}{
- "Enter": {"Enter", 13, "\r"},
- "Return": {"Enter", 13, "\r"},
- "Tab": {"Tab", 9, "\t"},
- "Escape": {"Escape", 27, ""},
+ "Enter": {"Enter", 13, "\r"},
+ "Return": {"Enter", 13, "\r"},
+ "Tab": {"Tab", 9, "\t"},
+ "Escape": {"Escape", 27, ""},
// Modifier keys must dispatch keyDown/keyUp events, never text. Without these
// entries they fall through to chromedp.KeyEvent and the literal name ("Shift")
// is typed into the focused field (issue #588). insertText is empty so the
// browser receives a real modifier key event with no character.
- "Shift": {"ShiftLeft", 16, ""},
- "Control": {"ControlLeft", 17, ""},
- "Alt": {"AltLeft", 18, ""},
- "Meta": {"MetaLeft", 91, ""},
+ "Shift": {"ShiftLeft", 16, ""},
+ "Control": {"ControlLeft", 17, ""},
+ "Alt": {"AltLeft", 18, ""},
+ "Meta": {"MetaLeft", 91, ""},
"Backspace": {"Backspace", 8, ""},
"Delete": {"Delete", 46, ""},
"ArrowLeft": {"ArrowLeft", 37, ""},
@@ -51,10 +51,69 @@ var namedKeyDefs = map[string]struct {
"F12": {"F12", 123, ""},
}
-// Unrecognised keys fall back to chromedp.KeyEvent.
-func DispatchNamedKey(ctx context.Context, key string) error {
+// printableShortcutKey returns the CDP code and Windows virtual-key code for a
+// single printable ASCII key. It is used to dispatch keyboard shortcuts such as
+// Ctrl+C / Cmd+A where the key is not in namedKeyDefs but must still carry a real
+// code/virtualKey so the page recognises the chord. ok is false for anything we
+// cannot map (the caller then falls back to typing the key).
+func printableShortcutKey(key string) (code string, vk int64, ok bool) {
+ if len(key) != 1 {
+ return "", 0, false
+ }
+ c := key[0]
+ switch {
+ case c >= 'a' && c <= 'z':
+ u := c - ('a' - 'A')
+ return "Key" + string(rune(u)), int64(u), true
+ case c >= 'A' && c <= 'Z':
+ return "Key" + string(rune(c)), int64(c), true
+ case c >= '0' && c <= '9':
+ return "Digit" + string(rune(c)), int64(c), true
+ }
+ return "", 0, false
+}
+
+// editingCommand maps a Ctrl/Cmd shortcut to the editing command CDP applies via
+// the keyDown "commands" field. On macOS the built-in editor only performs these
+// actions (select-all, copy, …) when the command name is supplied; Linux/Windows
+// derive them from the key event directly, where the empty default is harmless.
+func editingCommand(key string, modifiers int) string {
+ const ctrl, meta, shift = 2, 4, 8
+ if modifiers&(ctrl|meta) == 0 {
+ return ""
+ }
+ switch key {
+ case "a", "A":
+ return "selectAll"
+ case "c", "C":
+ return "copy"
+ case "v", "V":
+ return "paste"
+ case "x", "X":
+ return "cut"
+ case "z", "Z":
+ if modifiers&shift != 0 {
+ return "redo"
+ }
+ return "undo"
+ case "y", "Y":
+ return "redo"
+ }
+ return ""
+}
+
+// DispatchNamedKey dispatches key with the given CDP modifier bitmask
+// (Alt=1, Ctrl=2, Meta=4, Shift=8). Unrecognised keys with no modifiers fall
+// back to chromedp.KeyEvent (types the key); with modifiers they are dispatched
+// as a shortcut so chords like Ctrl+C / Cmd+A reach the page.
+func DispatchNamedKey(ctx context.Context, key string, modifiers int) error {
def, ok := namedKeyDefs[key]
if !ok {
+ if modifiers != 0 {
+ if code, vk, mapped := printableShortcutKey(key); mapped {
+ return dispatchKeyChord(ctx, key, code, vk, "", modifiers, editingCommand(key, modifiers))
+ }
+ }
return chromedp.Run(ctx, chromedp.KeyEvent(key))
}
@@ -63,44 +122,55 @@ func DispatchNamedKey(ctx context.Context, key string) error {
w3cKey = "Enter"
}
- dispatchEvent := func(evType string) chromedp.ActionFunc {
- return chromedp.ActionFunc(func(ctx context.Context) error {
- return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchKeyEvent", map[string]any{
- "type": evType,
- "key": w3cKey,
- "code": def.code,
- "windowsVirtualKeyCode": def.virtualKey,
- "nativeVirtualKeyCode": def.virtualKey,
- }, nil)
- })
+ // A named key with modifiers is a shortcut (Shift+ArrowRight selects,
+ // Ctrl+Backspace deletes a word): suppress its default text so it isn't
+ // also inserted as a character.
+ text := def.insertText
+ if modifiers != 0 {
+ text = ""
}
+ return dispatchKeyChord(ctx, w3cKey, def.code, def.virtualKey, text, modifiers, "")
+}
- // "keyDown" + text field fires keypress and triggers default actions (form submit, tab advance).
- // "rawKeyDown" for non-character keys — no keypress needed.
- downType := "rawKeyDown"
- var downText string
- if def.insertText != "" {
- downType = "keyDown"
- downText = def.insertText
- }
- dispatchKeyDown := chromedp.ActionFunc(func(ctx context.Context) error {
- params := map[string]any{
- "type": downType,
- "key": w3cKey,
- "code": def.code,
- "windowsVirtualKeyCode": def.virtualKey,
- "nativeVirtualKeyCode": def.virtualKey,
+// dispatchKeyChord sends a keyDown+keyUp pair via CDP, applying the modifier
+// bitmask. When text is non-empty the keyDown uses type "keyDown" and carries the
+// text (fires keypress + default actions like form submit); otherwise it uses
+// "rawKeyDown" for non-character / shortcut keys.
+func dispatchKeyChord(ctx context.Context, key, code string, vk int64, text string, modifiers int, command string) error {
+ params := func(evType string, isKeyDown bool) map[string]any {
+ p := map[string]any{
+ "type": evType,
+ "key": key,
+ "code": code,
+ "windowsVirtualKeyCode": vk,
+ "nativeVirtualKeyCode": vk,
+ }
+ if modifiers != 0 {
+ p["modifiers"] = modifiers
}
- if downText != "" {
- params["text"] = downText
- params["unmodifiedText"] = downText
+ if isKeyDown && text != "" {
+ p["text"] = text
+ p["unmodifiedText"] = text
}
- return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchKeyEvent", params, nil)
- })
- actions := chromedp.Tasks{dispatchKeyDown}
- actions = append(actions, dispatchEvent("keyUp"))
+ // The editing command rides on the keyDown so macOS performs the action.
+ if isKeyDown && command != "" {
+ p["commands"] = []string{command}
+ }
+ return p
+ }
- return chromedp.Run(ctx, actions...)
+ downType := "rawKeyDown"
+ if text != "" {
+ downType = "keyDown"
+ }
+ return chromedp.Run(ctx,
+ chromedp.ActionFunc(func(c context.Context) error {
+ return chromedp.FromContext(c).Target.Execute(c, "Input.dispatchKeyEvent", params(downType, true), nil)
+ }),
+ chromedp.ActionFunc(func(c context.Context) error {
+ return chromedp.FromContext(c).Target.Execute(c, "Input.dispatchKeyEvent", params("keyUp", false), nil)
+ }),
+ )
}
func TypeByNodeID(ctx context.Context, nodeID int64, text string) error {
diff --git a/internal/bridge/cdp_keyboard_test.go b/internal/bridge/cdp_keyboard_test.go
index 09726587..edaf4207 100644
--- a/internal/bridge/cdp_keyboard_test.go
+++ b/internal/bridge/cdp_keyboard_test.go
@@ -79,6 +79,31 @@ func TestDispatchNamedKey_ModifiersNotTyped(t *testing.T) {
}
}
+// TestPrintableShortcutKey verifies the code/virtual-key mapping used to dispatch
+// keyboard chords (Ctrl+C, Cmd+A, …) on printable keys.
+func TestPrintableShortcutKey(t *testing.T) {
+ cases := []struct {
+ key string
+ wantCode string
+ wantVK int64
+ wantOK bool
+ }{
+ {"c", "KeyC", 67, true}, // Ctrl+C
+ {"a", "KeyA", 65, true}, // Cmd/Ctrl+A
+ {"C", "KeyC", 67, true}, // already-uppercase maps the same
+ {"5", "Digit5", 53, true},
+ {"Enter", "", 0, false}, // multi-char → not a printable shortcut key
+ {"-", "", 0, false}, // unmapped punctuation
+ }
+ for _, tc := range cases {
+ code, vk, ok := printableShortcutKey(tc.key)
+ if ok != tc.wantOK || code != tc.wantCode || vk != tc.wantVK {
+ t.Errorf("printableShortcutKey(%q) = (%q,%d,%v), want (%q,%d,%v)",
+ tc.key, code, vk, ok, tc.wantCode, tc.wantVK, tc.wantOK)
+ }
+ }
+}
+
// TestDispatchNamedKey_ReturnAlias verifies that "Return" is an alias for
// Enter and produces the same CDP parameters.
func TestDispatchNamedKey_ReturnAlias(t *testing.T) {
@@ -97,7 +122,7 @@ func TestDispatchNamedKey_FallbackOnCancelledCtx(t *testing.T) {
cancel()
// "a" is not in namedKeyDefs → falls back to chromedp.KeyEvent
- err := DispatchNamedKey(ctx, "a")
+ err := DispatchNamedKey(ctx, "a", 0)
if err == nil {
t.Error("expected error dispatching key on cancelled context")
}
@@ -109,7 +134,7 @@ func TestDispatchNamedKey_KnownKeyOnCancelledCtx(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
- err := DispatchNamedKey(ctx, "Enter")
+ err := DispatchNamedKey(ctx, "Enter", 0)
if err == nil {
t.Error("expected error dispatching Enter on cancelled context")
}
diff --git a/tests/e2e/scenarios/api/screencast-input-basic.sh b/tests/e2e/scenarios/api/screencast-input-basic.sh
index 80158faa..1ca95c86 100644
--- a/tests/e2e/scenarios/api/screencast-input-basic.sh
+++ b/tests/e2e/scenarios/api/screencast-input-basic.sh
@@ -50,6 +50,15 @@ sc_click_frame() {
pt_post /action "$body" >/dev/null
}
+# sc_press <key> <modifiers> — press a key with a CDP modifier bitmask
+# (Alt=1, Ctrl=2, Meta=4, Shift=8), as the dashboard sends keyboard chords.
+sc_press() {
+ local body
+ body=$(jq -nc --arg t "$SC_TAB_ID" --arg key "$1" --argjson mods "$2" \
+ '{kind:"press", tabId:$t, key:$key, modifiers:$mods}')
+ pt_post /action "$body" >/dev/null
+}
+
# ─────────────────────────────────────────────────────────────────
start_test "screencast click mapping: every target at every frame scale"
@@ -135,3 +144,33 @@ else
fi
end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "screencast keyboard chords (Ctrl+A, Shift+End) reach the page"
+
+sc_navigate "${FIXTURES_URL}/screencast-click-targets.html"
+# Put known text in the input and focus it with the caret mid-string.
+sc_eval 'var b=document.getElementById("inp"); b.value="hello world"; b.focus(); b.setSelectionRange(3,3); "ok"' >/dev/null
+
+# Ctrl+A (modifiers=2) → select the whole field.
+sc_press "a" 2
+SEL_START=$(sc_eval 'document.getElementById("inp").selectionStart')
+SEL_END=$(sc_eval 'document.getElementById("inp").selectionEnd')
+if [ "$SEL_START" = "0" ] && [ "$SEL_END" = "11" ]; then
+ pass_assert "Ctrl+A selected the whole field (0..11)"
+else
+ fail_assert "Ctrl+A selection was ${SEL_START}..${SEL_END}, want 0..11"
+fi
+
+# Shift+End (modifiers=8) from the start → extend selection to the end.
+sc_eval 'document.getElementById("inp").setSelectionRange(0,0); "ok"' >/dev/null
+sc_press "End" 8
+SEL_START=$(sc_eval 'document.getElementById("inp").selectionStart')
+SEL_END=$(sc_eval 'document.getElementById("inp").selectionEnd')
+if [ "$SEL_START" = "0" ] && [ "$SEL_END" = "11" ]; then
+ pass_assert "Shift+End extended the selection (0..11)"
+else
+ fail_assert "Shift+End selection was ${SEL_START}..${SEL_END}, want 0..11"
+fi
+
+end_test