Send captured controller keys to the relay with a focus command

The keyboard option now applies to the controller role, requesting
keyboard-capture. A new remote-focus command asks the reader to send
this keyboard; captured transitions are encoded with the epoch-bound
encoder and written to the relay. Keys outside the agreed profile are
ignored with their repeats and release. Status text names the granted
keyboard direction and the current focus.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Chase CichorzandClaude Opus 5.5 committed 2026-11-06 16:06:38 -05:00
1 parent bf27c84ebc
commit 2541ce58e4
12 files changed
+396 -19

No files matched your search

+31 -11
View File
@@ -59,12 +59,17 @@ func (command *connectionCommand) commands() []sdk.Command {
{"remote-select", "Choose Remote relay and role", command.select_relay},
{"remote-approved", "Continue after reader-owned Remote approval", command.approved},
{"remote-connection", "Remote connection controls", command.submit},
{"remote-focus", "Send this keyboard to the remote computer (F11 returns)", command.remote_focus},
}
var commands []sdk.Command
for _, entry := range entries {
value := sdk.Command{ID: entry.id, Title: entry.title, Description: entry.title, Presentation: true, Interaction: true, Handle: entry.handler}
if entry.id == "remote" {
switch entry.id {
case "remote":
value.Bindings = []sdk.Binding{{Layout: "desktop", Scope: "global", Key: "Cthulhu+Ctrl+Shift+R"}, {Layout: "laptop", Scope: "global", Key: "Cthulhu+Ctrl+Shift+R"}}
case "remote-focus":
value.Interaction = false
value.Bindings = []sdk.Binding{{Layout: "desktop", Scope: "global", Key: "Cthulhu+Ctrl+Shift+F"}, {Layout: "laptop", Scope: "global", Key: "Cthulhu+Ctrl+Shift+F"}}
}
commands = append(commands, value)
}
@@ -85,8 +90,8 @@ func (command *connectionCommand) selection_form(notice string) sdk.Interaction
{ID: "host", Label: "Relay host", Kind: sdk.Entry, Text: command.selected.Host, MaxLength: 253},
{ID: "port", Label: "Relay port", Kind: sdk.Entry, Text: strconv.Itoa(command.selected.Port), MaxLength: 5},
{ID: "role", Label: "Connection role", Kind: sdk.List, Items: roles},
{ID: "keyboard", Label: "When allowing access, also let the helper control this keyboard for this session", Kind: sdk.CheckBox, Checked: command.keyboard},
{ID: "key-profile", Label: "Keys the helper may send", Kind: sdk.List, Items: profiles},
{ID: "keyboard", Label: "Include keyboard control for this session: controlling sends this keyboard when remote focus is on; allowing access lets the helper type here", Kind: sdk.CheckBox, Checked: command.keyboard},
{ID: "key-profile", Label: "Keys that may be sent", Kind: sdk.List, Items: profiles},
{ID: "review-access", Label: "Review access for this session", Kind: sdk.Button},
{ID: "save-settings", Label: "Save relay and role without connecting", Kind: sdk.Button},
}}, Next: "remote-select"}
@@ -170,15 +175,16 @@ func (command *connectionCommand) select_relay(ctx context.Context, raw json.Raw
return command.selection_form("Relay and role saved. No connection was started."), nil
}
grants := []string{"remote-present"}
command.coordinator.set_keyboard("")
keyboardGrant := "keyboard-capture"
if selected.Role == "controlled" {
grants = []string{"output-observe"}
if command.keyboard {
// The reader's consent dialog discloses keyboard control separately;
// the profile limits which relay keys can be converted.
grants = append(grants, "keyboard-inject")
command.coordinator.set_keyboard(command.keyProfile)
}
grants, keyboardGrant = []string{"output-observe"}, "keyboard-inject"
}
command.coordinator.set_keyboard("")
if command.keyboard {
// The reader's consent dialog discloses keyboard control separately;
// the profile limits which keys can be converted in either direction.
grants = append(grants, keyboardGrant)
command.coordinator.set_keyboard(command.keyProfile)
}
command.awaiting = true
return sdk.Interaction{Remote: &sdk.RemoteRequest{Role: selected.Role, Grants: grants}, Next: "remote-approved"}, nil
@@ -256,3 +262,17 @@ func (command *connectionCommand) close() {
<-barrier
<-command.coordinator.done
}
// remote_focus asks the reader to send this keyboard to the remote computer.
// It only enters remote focus: F11 or any Remote shortcut returns it, handled
// by the reader without this process.
func (command *connectionCommand) remote_focus(ctx context.Context, _ json.RawMessage) (any, error) {
if ctx.Err() != nil {
return nil, ctx.Err()
}
if err := command.coordinator.request_focus(true); err != nil {
text := "Remote keyboard control needs a connected controller session with keyboard control approved."
return sdk.Presentation{Speech: text, Braille: text}, nil
}
return sdk.Presentation{Speech: "Requesting remote keyboard focus.", Braille: "Requesting remote keyboard focus."}, nil
}
+1 -1
View File
@@ -20,7 +20,7 @@ func TestRemoteCommandSelectsEndpointWithoutAccessOrNetworking(t *testing.T) {
store, _, saved := settingsFixture(t)
command := &connectionCommand{coordinator: c, store: store, selected: saved}
for _, entry := range command.commands() {
if entry.ID != "remote" && len(entry.Bindings) != 0 {
if entry.ID != "remote" && entry.ID != "remote-focus" && len(entry.Bindings) != 0 {
t.Fatal("continuation has a shortcut")
}
}
+23 -3
View File
@@ -7,6 +7,7 @@ import (
"encoding/hex"
"errors"
"net"
"slices"
"strconv"
"sync"
@@ -106,7 +107,7 @@ func (w *connectionWorkflow) form_locked() sdk.Interaction {
{ID: "endpoint", Label: "Relay: " + address},
{ID: "role", Label: "Approved role: " + w.action.Role},
{ID: "privacy", Label: "The relay can read the channel key and session contents. A channel key does not verify the other person's identity."},
{ID: "scope", Label: "Experimental speech; live verification is pending. Keyboard, clipboard and Braille services are unavailable."},
{ID: "scope", Label: session_scope_text(w.action)},
}}
switch w.mode {
case "credentials":
@@ -151,6 +152,14 @@ func (w *connectionWorkflow) form_locked() sdk.Interaction {
text := "This connection attempt has ended. Fresh local approval is required to connect again."
if status.epoch == w.action.Epoch {
text = connection_status_text(status)
if status.state == "ready" && slices.Contains(w.action.Grants, "keyboard-capture") {
switch status.focus {
case "remote":
text += " This keyboard controls the remote computer; F11 returns it."
default:
text += " This keyboard controls this computer. Use the Remote keyboard focus command to send it."
}
}
}
details.Items = append(details.Items, sdk.ListItem{ID: "status", Label: text})
result.Form = &sdk.Form{Title: "Remote relay status", Elements: []sdk.Element{details,
@@ -171,6 +180,17 @@ func (w *connectionWorkflow) form_locked() sdk.Interaction {
return result
}
// session_scope_text names what this approved session can actually do.
func session_scope_text(action sdk.SessionEvent) string {
text := "Experimental speech"
if slices.Contains(action.Grants, "keyboard-capture") {
text += " and keyboard control of the remote computer"
} else if slices.Contains(action.Grants, "keyboard-inject") {
text += " and keyboard control of this computer by the helper"
}
return text + "; live verification is pending. Clipboard and Braille services are unavailable."
}
func connection_status_text(status connectionStatus) string {
switch status.state {
case "opening":
@@ -178,9 +198,9 @@ func connection_status_text(status connectionStatus) string {
case "connecting":
return "Connecting and authenticating the relay."
case "waiting":
return "Connected to the relay; waiting for one opposite-role peer. Experimental speech; keyboard, clipboard and Braille services are unavailable."
return "Connected to the relay; waiting for one opposite-role peer."
case "ready":
return "One opposite-role peer has joined. Experimental speech; keyboard, clipboard and Braille services are unavailable."
return "One opposite-role peer has joined."
case "stopping":
return "Disconnecting and releasing the reader lease."
case "failed":
+1 -1
View File
@@ -155,7 +155,7 @@ func TestConnectionWorkflowConnectUsesLoadedKeyWithoutEcho(t *testing.T) {
awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "waiting" })
result = workflowSubmit(t, w, "refresh", "")
encoded, _ := json.Marshal(result)
if !strings.Contains(string(encoded), "waiting for one opposite-role peer") || !strings.Contains(string(encoded), "keyboard, clipboard and Braille services are unavailable") {
if !strings.Contains(string(encoded), "waiting for one opposite-role peer") || !strings.Contains(string(encoded), "Clipboard and Braille services are unavailable") || strings.Contains(string(encoded), "keyboard control") {
t.Fatal("status advertised desktop control or omitted waiting state")
}
if w.key != "" {
+14 -1
View File
@@ -28,7 +28,8 @@ type connectionStatus struct {
epoch uint64
peer int
ignored uint64
err error // Local constant errors only; never RPC/server diagnostic text.
focus string // Controller keyboard: "", "local" or "remote", as reported by core.
err error // Local constant errors only; never RPC/server diagnostic text.
}
type connectionAttempt struct {
@@ -113,6 +114,10 @@ func (c *coordinator) read_events() {
}
case "remote.output":
c.observe_locked(event)
case "remote.input":
c.capture_locked(event)
case "remote.focus":
c.focus_locked(event)
}
c.mu.Unlock()
}
@@ -378,6 +383,14 @@ func (c *coordinator) run(a *connectionAttempt, approval sdk.SessionEvent, e end
outputDone = make(chan struct{})
go func() {
defer close(outputDone)
if stream.capture_enabled() {
keysDone := make(chan struct{})
go func() {
defer close(keysDone)
c.key_output(a, stream, conn)
}()
defer func() { <-keysDone }()
}
c.speech_output(a, stream, conn)
}()
for a.ctx.Err() == nil {
+137
View File
@@ -0,0 +1,137 @@
// SPDX-License-Identifier: GPL-3.0-or-later
package remote
import (
"slices"
sdk "git.stormux.org/storm/cthulhu/sdk/go/tentacle"
)
// maxCapturedKeys bounds queued plus in-flight controller transitions. A full
// queue stops the connection rather than dropping a release.
const maxCapturedKeys = 256
func (stream *speechStream) capture_enabled() bool {
return stream.mapping != nil && stream.role == "controller" && slices.Contains(stream.grants, "keyboard-capture")
}
// capture_locked admits one transition from the reader's exclusive capture.
// Core supplies the origin; only events for this controller lease are taken.
// Pre-peer transitions are dropped: no down was sent for them.
func (c *coordinator) capture_locked(event sdk.SessionEvent) {
a := c.active
if a == nil || a.speech == nil || event.Input == nil {
return
}
stream := a.speech
if !stream.capture_enabled() || event.Lease != stream.lease.Lease || event.Epoch != stream.lease.Epoch || !c.speech_ready_locked(a, stream) {
return
}
if stream.capturedItems == maxCapturedKeys {
c.stop_locked(errLimit)
return
}
stream.capturedItems++
stream.captured <- *event.Input // Capacity reserved above.
}
func (c *coordinator) focus_locked(event sdk.SessionEvent) {
a := c.active
if a == nil || a.speech == nil || event.Lease != a.speech.lease.Lease || event.Epoch != a.speech.lease.Epoch {
return
}
c.status.focus = event.Focus
}
// request_focus asks the reader to enter or leave remote focus. The sequenced
// operation owner sends it; the reader reports the actual state as an event.
func (c *coordinator) request_focus(remote bool) error {
c.mu.Lock()
defer c.mu.Unlock()
a := c.active
if a == nil || a.speech == nil || !a.speech.capture_enabled() || !c.speech_ready_locked(a, a.speech) {
return errLease
}
select {
case a.speech.focusRequests <- remote:
return nil
default:
return errLimit
}
}
// key_output encodes captured transitions and writes them to the relay. The
// encoder retains each down's wire identity through repeats and release, so
// a layout change cannot strand a remote key. A press the agreed key profile
// cannot represent is ignored with its repeats and release. Releases are not
// written after the connection ends: the controlled side's reader releases
// every injected key when its own lease ends.
func (c *coordinator) key_output(a *connectionAttempt, stream *speechStream, conn *relayConn) {
encoder, err := newKeyboardEncoder(a.epoch)
if err != nil {
return
}
var ignored [256]bool
release := func() {
c.mu.Lock()
stream.capturedItems--
c.mu.Unlock()
}
stop := func(err error) {
c.mu.Lock()
c.stop_locked(err)
c.mu.Unlock()
}
for {
select {
case <-a.ctx.Done():
return
case key := <-stream.captured:
c.mu.Lock()
ready := c.speech_ready_locked(a, stream)
c.mu.Unlock()
if !ready {
release()
return
}
code := key.Code
if key.Pressed && !key.Repeat {
if _, err := stream.mapping.toWire(key.Name, true); err != nil {
ignored[code] = true
release()
continue
}
ignored[code] = false
} else if ignored[code] {
if !key.Pressed {
ignored[code] = false
}
release()
continue
}
plan, planned, err := encoder.apply(a.epoch, stream.mapping, keyboardEvent{code: code, name: key.Name, pressed: key.Pressed, repeat: key.Repeat})
release()
if err != nil {
stop(errKeyboard)
return
}
if !planned {
continue
}
frame, err := encodeMessage("key", plan.key)
if err != nil {
stop(errProtocol)
return
}
if err := conn.write(a.ctx, frame); err != nil {
stop(err)
return
}
if err := encoder.acknowledge(a.epoch, plan.sequence); err != nil {
stop(errKeyboard)
return
}
}
}
}
+107
View File
@@ -149,3 +149,110 @@ func TestCoordinatorKeyQueueOverflowStopsConnection(t *testing.T) {
t.Fatal("overflow did not stop the connection", status.err)
}
}
// controllerRelay joins one controlled peer and records the key frames it
// receives from this controller.
func controllerRelay(t *testing.T, received chan<- string) endpoint {
t.Helper()
cert, roots := testCertificate(t, true)
e := testRelay(t, cert, func(conn net.Conn) {
reader := relayHandshake(t, conn, controller)
if reader == nil {
return
}
_, _ = io.WriteString(conn, `{"type":"channel_joined","channel":"synthetic-fixture","clients":[{"id":7,"connection_type":"slave"}]}`+"\n")
for {
line, err := reader.ReadString('\n')
if err != nil {
return
}
if strings.Contains(line, `"type":"key"`) {
received <- strings.TrimSpace(line)
}
}
})
e.roots = roots
return e
}
func TestCoordinatorEncodesCapturedKeysAndRequestsFocus(t *testing.T) {
c, f := fixtureCoordinator(t, nil)
c.set_keyboard("portable")
action := approveGrants(t, c, f, 1, "controller", "remote-present", "keyboard-capture")
received := make(chan string, 16)
if err := c.connect(action, controllerRelay(t, received), "synthetic-fixture"); err != nil {
t.Fatal(err)
}
nextCall(t, f, "remote.open")
awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "ready" })
if err := c.request_focus(true); err != nil {
t.Fatal(err)
}
for {
call := <-f.calls
if call.method == "remote.heartbeat" {
continue
}
request, ok := call.params.(sdk.RemoteFocusRequest)
if call.method != "remote.focus" || !ok || !request.Remote || !sdk.ValidRemoteFocusRequest(request) {
t.Fatalf("bad focus call %s %+v", call.method, call.params)
}
break
}
lease := strings.Repeat("b", 32)
f.events <- sdk.SessionEvent{Sequence: 2, Kind: "remote.focus", Lease: lease, Epoch: 1, Focus: "remote", Reason: "requested"}
awaitStatus(t, c, func(s connectionStatus) bool { return s.focus == "remote" })
for index, key := range []sdk.RemoteCapturedKey{
{Code: 50, Name: "Shift_L", Pressed: true},
{Code: 59, Name: "comma", Pressed: true}, // Not in the portable profile: ignored.
{Code: 59, Pressed: true, Repeat: true},
{Code: 59},
{Code: 38, Name: "a", Pressed: true},
{Code: 38, Pressed: true, Repeat: true},
{Code: 38},
{Code: 50},
} {
f.events <- sdk.SessionEvent{Sequence: uint64(3 + index), Kind: "remote.input", Lease: lease, Epoch: 1, Input: &key}
}
want := []string{
`"vk_code":160`, `"vk_code":65`, `"vk_code":65`, `"vk_code":65`, `"vk_code":160`,
}
pressed := []string{"true", "true", "true", "false", "false"}
for index := range want {
select {
case frame := <-received:
if !strings.Contains(frame, want[index]) || !strings.Contains(frame, `"pressed":`+pressed[index]) {
t.Fatalf("frame %d = %s, want %s pressed %s", index, frame, want[index], pressed[index])
}
case <-time.After(4 * time.Second):
t.Fatalf("missing frame %d", index)
}
}
select {
case frame := <-received:
t.Fatal("unexpected frame", frame)
case <-time.After(100 * time.Millisecond):
}
}
func TestCoordinatorFocusRequiresCaptureGrant(t *testing.T) {
c, f := fixtureCoordinator(t, nil)
c.set_keyboard("portable")
action := approveGrants(t, c, f, 1, "controller", "remote-present")
received := make(chan string, 4)
if err := c.connect(action, controllerRelay(t, received), "synthetic-fixture"); err != nil {
t.Fatal(err)
}
nextCall(t, f, "remote.open")
awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "ready" })
if c.request_focus(true) == nil {
t.Fatal("focus requested without keyboard-capture")
}
key := sdk.RemoteCapturedKey{Code: 38, Name: "a", Pressed: true}
f.events <- sdk.SessionEvent{Sequence: 2, Kind: "remote.input", Lease: strings.Repeat("b", 32), Epoch: 1, Input: &key}
select {
case frame := <-received:
t.Fatal("key sent without keyboard-capture", frame)
case <-time.After(200 * time.Millisecond):
}
}
+25 -2
View File
@@ -38,13 +38,18 @@ type speechStream struct {
sequence uint64
keys chan sdk.RemoteKey // Controlled keyboard-inject only.
keyItems int // Queued plus in-flight; coordinator.mu.
mapping *keyboardMap // Immutable; nil without keyboard-inject.
mapping *keyboardMap // Immutable; nil without a keyboard grant.
// Controller keyboard-capture only.
captured chan sdk.RemoteCapturedKey
capturedItems int // Queued plus in-flight; coordinator.mu.
focusRequests chan bool // Sent by speech_operations in sequence.
}
func newSpeechStream(lease sdk.RemoteLease, approval sdk.SessionEvent) *speechStream {
return &speechStream{lease: lease, role: approval.Role, grants: slices.Clone(approval.Grants),
incoming: make(chan speechItem, maxSpeechItems), outgoing: make(chan []byte, maxSpeechItems),
keys: make(chan sdk.RemoteKey, maxKeyItems)}
keys: make(chan sdk.RemoteKey, maxKeyItems), captured: make(chan sdk.RemoteCapturedKey, maxCapturedKeys),
focusRequests: make(chan bool, 4)}
}
func (stream *speechStream) keyboard_enabled() bool {
@@ -62,6 +67,9 @@ func (stream *speechStream) drain() {
stream.bytes -= len(frame)
case <-stream.keys:
stream.keyItems--
case <-stream.captured:
stream.capturedItems--
case <-stream.focusRequests:
default:
return
}
@@ -210,6 +218,21 @@ func (c *coordinator) speech_operations(a *connectionAttempt, stream *speechStre
if !heartbeat() {
return
}
case remote := <-stream.focusRequests:
c.mu.Lock()
ready := c.speech_ready_locked(a, stream)
c.mu.Unlock()
if !ready {
return
}
stream.sequence++
request := sdk.RemoteFocusRequest{RemoteOperation: sdk.RemoteOperation{Lease: stream.lease.Lease, Epoch: a.epoch, Sequence: stream.sequence}, Remote: remote}
if c.call("remote.focus", request, nil) != nil {
c.mu.Lock()
c.stop_locked(errLease)
c.mu.Unlock()
return
}
case key := <-stream.keys:
select {
case <-ticker.C: