diff --git a/remote.md b/remote.md index 452aa6d..6af83ca 100644 --- a/remote.md +++ b/remote.md @@ -882,6 +882,30 @@ The router has no production caller. Native capture, the escape's independence from a hung Tentacle, provenance, collisions, lock/AltGr policy and all live acceptance remain open; no release gate is complete. +Thirty-ninth implementation increment (2026-11-06): based on reader `26c3dbb` +and Tentacles `2379a4e`. Controlled-side keyboard injection is now reachable in +production. Local launch and managed startup attach the incoming-key mailbox for +sessions installed with `keyboard-inject`, using one input-helper Supervisor +retained for the reader lifetime. Delivery rechecks lease, grant, deadline, +lock, XTerm handoff and internal reader UI. `build-cthulhu.sh` and both Arch +packages build and install `cthulhu-input-helper`; a missing helper leaves +keyboard input unavailable without affecting startup. The source command offers +a session-only "let the helper control this keyboard" option and a key profile +(portable, or US punctuation) for the controlled role; with it, the reader's +consent covers `keyboard-inject` and the coordinator forwards converted relay +keys through `remote.key` in the shared operation sequence. Unconvertible keys +are ignored for both press and release; a full 256-key queue stops the +connection. See [the reader contract](../cthulhu/docs/tentacle-remote-keyboard.md#production-attachment-2026-11-06). + +Real SDK-process reader tests cover production delivery and lock-policy +retirement, handoff denial before launch, and no-grant/missing-helper cases. +Coordinator tests cover ordered key requests, ignored unsupported keys, missing +grant or profile, and queue overflow. The reader app/remoteinput/tentacle race +suites, build-script tests, the full Remote race suite and `make check` passed. +`shellcheck` is not installed here, so the edited build script was not linted. +No physical keyboard, desktop or NVDA peer was used. Physical collisions, +provenance, lock/AltGr policy and all live acceptance remain open. + ## 1. Intended result and recommended approach Build a native Go Tentacle named **Remote**, with package ID `remote`, in this @@ -1354,7 +1378,8 @@ controller or `slave` for controlled. Present plain-language role labels in UI. tests. Its [source-built helper](../cthulhu/docs/testing/remote-input-helper.md) now has fixed IPC and separate EOF/watchdog cleanup. Production supervision, actual reader crash acceptance, provenance and physical collision safety - remain absent; it is not attached to reader input or Remote. + remain absent. The helper is now attached to approved controlled sessions + and installed with the reader; provenance and collisions remain open. - [ ] Verify remote keys reach both ordinary applications and Cthulhu command handling exactly once. If physical/injected held-key collisions cannot be resolved safely, suspend input and report the limitation; do not clear all diff --git a/remote/README.md b/remote/README.md index 75d43b7..3a4d28e 100644 --- a/remote/README.md +++ b/remote/README.md @@ -41,6 +41,9 @@ Implemented: failed-write cleanup with sequence-checked acknowledgements. Capture, injection, AltGr and native layout/held-key ownership remain pending; these are library prerequisites, not keyboard control. See [keyboard.md](keyboard.md). +- Controlled-role keyboard control: an explicit session-only option requests + `keyboard-inject`; relay keys reach the reader's production input helper + through `remote.key`. Live acceptance is pending. - Typed reader `remote.key` IPC, Go/Python validation and a bounded incoming-key mailbox now have real-process SDK checks. The external bridge converts every supported canonical mapping to the public SDK representation. No production diff --git a/remote/command.md b/remote/command.md index b8bdb03..79cd5e5 100644 --- a/remote/command.md +++ b/remote/command.md @@ -273,3 +273,15 @@ reader and personal configuration untouched while preparing the test session. Physical-source acceptance, audible speech/masking, real-server priority, physical Braille, remaining desktop services, actual NVDA/Orca interoperability and packaging remain separate open gates. + +## Controlled keyboard live checks, pending + +Install the reader with `cthulhu-input-helper` beside it. On the controlled +computer choose **Allow a helper to access this computer**, check the keyboard +option and pick a key profile, then approve keyboard control in the reader's +dialog using the physical keyboard. From the controller, type into a harmless +text editor, use Shift+Tab, arrows and Control shortcuts, and confirm each key +arrives once. Hold Shift or Control on the controller and disconnect, lock the +controlled desktop, and trigger XTerm handoff; afterwards confirm no modifier +is stuck (for example with `xinput query-state` or by typing). Repeat without +the keyboard option and confirm keys are ignored. diff --git a/remote/keyboard.md b/remote/keyboard.md index df8dede..330b91f 100644 --- a/remote/keyboard.md +++ b/remote/keyboard.md @@ -5,8 +5,11 @@ keysym names and NVDA Remote `vk_code`/`extended` identities. The subsequent `src/keyboard_state.go` adds outgoing key-pair planning with bounded state and write acknowledgements. A further reader increment adds typed `remote.key` IPC and an explicitly attached mailbox, with the external conversion bridge in -`src/keyboard_bridge.go`. The source command still discards incoming keyboard -payloads and requests no keyboard grant. No production input owner is attached. +`src/keyboard_bridge.go`. When the controlled user enables keyboard control for +the session, the command requests `keyboard-inject` and the coordinator forwards +converted relay keys through `remote.key`; the reader attaches its production +input owner for that grant. Unconvertible keys are ignored for press and +release; a full 256-key queue stops the connection. ## Mapping contract diff --git a/remote/src/command.go b/remote/src/command.go index 5c88d28..5c253b7 100644 --- a/remote/src/command.go +++ b/remote/src/command.go @@ -46,6 +46,8 @@ type connectionCommand struct { selected settings awaiting bool workflow *connectionWorkflow + keyboard bool // Session-only; never persisted. + keyProfile string // "portable" or "us"; session-only. } func (command *connectionCommand) commands() []sdk.Command { @@ -53,7 +55,7 @@ func (command *connectionCommand) commands() []sdk.Command { id, title string handler sdk.Handler }{ - {"remote", "Remote relay connection (experimental speech)", command.open}, + {"remote", "Remote relay connection (experimental speech and keyboard)", command.open}, {"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}, @@ -74,11 +76,17 @@ func (command *connectionCommand) selection_form(notice string) sdk.Interaction if command.selected.Role == "controlled" { roles[0], roles[1] = roles[1], roles[0] } - result := sdk.Interaction{Form: &sdk.Form{Title: "Remote relay and role. Experimental speech; keyboard, clipboard and Braille services are unavailable.", Elements: []sdk.Element{ + profiles := []sdk.ListItem{{ID: "portable", Label: "Letters, digits and navigation only"}, {ID: "us", Label: "Also US layout punctuation"}} + if command.keyProfile == "us" { + profiles[0], profiles[1] = profiles[1], profiles[0] + } + result := sdk.Interaction{Form: &sdk.Form{Title: "Remote relay and role. Experimental speech and keyboard; clipboard and Braille services are unavailable.", Elements: []sdk.Element{ {ID: "cancel", Label: "Cancel", Kind: sdk.Button}, {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: "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"} @@ -150,18 +158,30 @@ func (command *connectionCommand) select_relay(ctx context.Context, raw json.Raw return command.selection_form("Saved relay trust could not be read."), nil } command.selected = selected + command.keyboard = value.Values["keyboard"].Checked + command.keyProfile = "portable" + if value.Values["key-profile"].Selected == "us" { + command.keyProfile = "us" + } if value.Activated == "save-settings" { if err := command.store.save(selected); err != nil { return command.selection_form("Relay settings could not be saved."), nil } return command.selection_form("Relay and role saved. No connection was started."), nil } - grant := "remote-present" + grants := []string{"remote-present"} + command.coordinator.set_keyboard("") if selected.Role == "controlled" { - grant = "output-observe" + 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) + } } command.awaiting = true - return sdk.Interaction{Remote: &sdk.RemoteRequest{Role: selected.Role, Grants: []string{grant}}, Next: "remote-approved"}, nil + return sdk.Interaction{Remote: &sdk.RemoteRequest{Role: selected.Role, Grants: grants}, Next: "remote-approved"}, nil } func (command *connectionCommand) approved(ctx context.Context, raw json.RawMessage) (any, error) { diff --git a/remote/src/coordinator.go b/remote/src/coordinator.go index ea53e13..a2e135a 100644 --- a/remote/src/coordinator.go +++ b/remote/src/coordinator.go @@ -57,7 +57,8 @@ type coordinator struct { setupClaimed bool active *connectionAttempt status connectionStatus - unavailable bool // Failed close cannot be followed by another connection. + unavailable bool // Failed close cannot be followed by another connection. + keyboard string // Agreed key profile for the next attempt; empty disables input. } func newCoordinator(ctx context.Context, client sessionClient) *coordinator { @@ -236,6 +237,14 @@ func (c *coordinator) disconnect_epoch(epoch uint64) <-chan struct{} { return done } +// set_keyboard selects the explicitly agreed key profile for later attempts. +// An active connection keeps the map it started with. +func (c *coordinator) set_keyboard(profile string) { + c.mu.Lock() + c.keyboard = profile + c.mu.Unlock() +} + // close ends the event owner too. Callers may wait on done and disconnect's // barrier before disposing the process session; neither path needs the relay. func (c *coordinator) close() { c.cancel() } @@ -338,6 +347,15 @@ func (c *coordinator) run(a *connectionAttempt, approval sdk.SessionEvent, e end c.mu.Unlock() stream = newSpeechStream(lease, approval) c.mu.Lock() + profile := c.keyboard + c.mu.Unlock() + if profile != "" { + if stream.mapping, err = newKeyboardMap(profile); err != nil { + failure = err + return + } + } + c.mu.Lock() a.speech = stream c.mu.Unlock() operationsDone = make(chan struct{}) @@ -380,6 +398,9 @@ func (c *coordinator) run(a *connectionAttempt, approval sdk.SessionEvent, e end } if accepted { handled, err := c.receive_speech(a, stream, m) + if err == nil && !handled { + handled, err = c.receive_key(a, stream, m) + } if err != nil { failure = err return diff --git a/remote/src/keyboard_receive_test.go b/remote/src/keyboard_receive_test.go new file mode 100644 index 0000000..e7dff1b --- /dev/null +++ b/remote/src/keyboard_receive_test.go @@ -0,0 +1,151 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +package remote + +import ( + "context" + "io" + "net" + "strconv" + "strings" + "testing" + "time" + + sdk "git.stormux.org/storm/cthulhu/sdk/go/tentacle" +) + +func approveGrants(t *testing.T, c *coordinator, f *fixtureClient, epoch uint64, role string, grants ...string) sdk.SessionEvent { + t.Helper() + f.events <- sdk.SessionEvent{Sequence: epoch, Kind: "remote.action", Action: strings.Repeat("a", 32), Epoch: epoch, Role: role, Grants: grants} + select { + case event := <-c.actions: + return event + case <-time.After(time.Second): + t.Fatal("missing action") + return sdk.SessionEvent{} + } +} + +// keyRelay joins one controller peer and writes the supplied key frames. +func keyRelay(t *testing.T, frames []string) endpoint { + t.Helper() + cert, roots := testCertificate(t, true) + e := testRelay(t, cert, func(conn net.Conn) { + if relayHandshake(t, conn, controlled) == nil { + return + } + _, _ = io.WriteString(conn, `{"type":"channel_joined","channel":"synthetic-fixture","clients":[{"id":7,"connection_type":"master"}]}`+"\n") + for _, frame := range frames { + _, _ = io.WriteString(conn, frame+"\n") + } + _, _ = io.Copy(io.Discard, conn) + }) + e.roots = roots + return e +} + +func keyFrame(vk int, pressed bool) string { + state := "false" + if pressed { + state = "true" + } + return `{"type":"key","origin":7,"vk_code":` + strconv.Itoa(vk) + `,"extended":false,"pressed":` + state + `}` +} + +func TestCoordinatorDeliversControlledKeysInSequence(t *testing.T) { + c, f := fixtureCoordinator(t, nil) + c.set_keyboard("portable") + action := approveGrants(t, c, f, 1, "controlled", "output-observe", "keyboard-inject") + // 0xBA is US OEM punctuation: unavailable under the portable profile and + // ignored for both press and release. + e := keyRelay(t, []string{keyFrame(0x41, true), keyFrame(0xBA, true), keyFrame(0xBA, false), keyFrame(0x41, false)}) + if err := c.connect(action, e, "synthetic-fixture"); err != nil { + t.Fatal(err) + } + nextCall(t, f, "remote.open") + var previous uint64 + for _, pressed := range []bool{true, false} { + var call readerCall + for { + call = <-f.calls + if call.method != "remote.heartbeat" { + break + } + previous = call.params.(sdk.RemoteOperation).Sequence + } + if call.method != "remote.key" { + t.Fatalf("got %s, want remote.key", call.method) + } + request := call.params.(sdk.RemoteKeyRequest) + if request.Key.Name != "a" || request.Key.Pressed != pressed || request.Epoch != 1 || request.Sequence <= previous || !sdk.ValidRemoteKeyRequest(request) { + t.Fatalf("bad key request %+v", request) + } + previous = request.Sequence + } + awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "ready" && s.ignored == 2 }) +} + +func TestCoordinatorIgnoresKeysWithoutGrantOrProfile(t *testing.T) { + for name, test := range map[string]struct { + profile string + grants []string + }{ + "no grant": {"portable", []string{"output-observe"}}, + "no profile": {"", []string{"output-observe", "keyboard-inject"}}, + } { + t.Run(name, func(t *testing.T) { + c, f := fixtureCoordinator(t, nil) + c.set_keyboard(test.profile) + action := approveGrants(t, c, f, 1, "controlled", test.grants...) + if err := c.connect(action, keyRelay(t, []string{keyFrame(0x41, true), keyFrame(0x41, false)}), "synthetic-fixture"); err != nil { + t.Fatal(err) + } + nextCall(t, f, "remote.open") + awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "ready" && s.ignored == 2 }) + for { + select { + case call := <-f.calls: + if call.method == "remote.key" { + t.Fatal("key delivered without keyboard consent and profile") + } + default: + return + } + } + }) + } +} + +func TestCoordinatorKeyQueueOverflowStopsConnection(t *testing.T) { + block := make(chan struct{}) + c, f := fixtureCoordinator(t, func(ctx context.Context, method string, params, result any) error { + switch method { + case "remote.open": + *result.(*sdk.RemoteLease) = sdk.RemoteLease{Lease: strings.Repeat("b", 32), Epoch: params.(sdk.RemoteOpen).Epoch} + case "remote.key": + select { + case <-block: + case <-ctx.Done(): + } + } + return nil + }) + t.Cleanup(func() { close(block) }) + go func() { + for range f.calls { + } + }() + c.set_keyboard("portable") + action := approveGrants(t, c, f, 1, "controlled", "keyboard-inject") + frames := make([]string, 0, maxKeyItems+4) + for index := 0; index < maxKeyItems+4; index++ { + frames = append(frames, keyFrame(0x41, index%2 == 0)) + } + if err := c.connect(action, keyRelay(t, frames), "synthetic-fixture"); err != nil { + t.Fatal(err) + } + status := awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "failed" }) + if status.err != errLimit { + t.Fatal("overflow did not stop the connection", status.err) + } +} diff --git a/remote/src/speech_stream.go b/remote/src/speech_stream.go index 23c1410..ad143a8 100644 --- a/remote/src/speech_stream.go +++ b/remote/src/speech_stream.go @@ -12,6 +12,10 @@ import ( const maxSpeechItems = 64 +// maxKeyItems matches the reader's 256-transition mailbox. A full queue stops +// the connection rather than dropping a release. +const maxKeyItems = 256 + type speechItem struct { speech sdk.RemoteSpeech bytes int @@ -32,11 +36,19 @@ type speechStream struct { items int bytes int 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. } 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)} + incoming: make(chan speechItem, maxSpeechItems), outgoing: make(chan []byte, maxSpeechItems), + keys: make(chan sdk.RemoteKey, maxKeyItems)} +} + +func (stream *speechStream) keyboard_enabled() bool { + return stream.mapping != nil && stream.role == "controlled" && slices.Contains(stream.grants, "keyboard-inject") } func (stream *speechStream) drain() { @@ -48,6 +60,8 @@ func (stream *speechStream) drain() { case frame := <-stream.outgoing: stream.items-- stream.bytes -= len(frame) + case <-stream.keys: + stream.keyItems-- default: return } @@ -128,6 +142,38 @@ func (c *coordinator) receive_speech(a *connectionAttempt, stream *speechStream, return true, nil } +// receive_key admits one controller transition for a controlled keyboard-inject +// lease. Membership/direction checks already ran in the relay reader. Keys the +// agreed map cannot represent are ignored consistently for both press and +// release, so no unmatched ownership is created; the reader's destination +// ledger owns release of every admitted key on revocation. +func (c *coordinator) receive_key(a *connectionAttempt, stream *speechStream, message message) (bool, error) { + if message.kind != "key" || !stream.keyboard_enabled() { + return false, nil + } + key, err := reader_key(stream.mapping, message) + if err != nil { + return false, nil + } + c.mu.Lock() + defer c.mu.Unlock() + if !c.speech_ready_locked(a, stream) { + return true, errLease + } + if stream.keyItems == maxKeyItems { + return true, errLimit + } + stream.keyItems++ + stream.keys <- key // Capacity reserved above, including in-flight work. + return true, nil +} + +func (c *coordinator) key_release(stream *speechStream) { + c.mu.Lock() + stream.keyItems-- + c.mu.Unlock() +} + func (c *coordinator) speech_release(stream *speechStream, bytes int) { c.mu.Lock() stream.items-- @@ -164,6 +210,18 @@ func (c *coordinator) speech_operations(a *connectionAttempt, stream *speechStre if !heartbeat() { return } + case key := <-stream.keys: + select { + case <-ticker.C: + if !heartbeat() { + c.key_release(stream) + return + } + default: + } + if !c.deliver_key(a, stream, key) { + return + } case item := <-stream.incoming: select { case <-ticker.C: @@ -200,6 +258,25 @@ func (c *coordinator) speech_operations(a *connectionAttempt, stream *speechStre } } +func (c *coordinator) deliver_key(a *connectionAttempt, stream *speechStream, key sdk.RemoteKey) bool { + defer c.key_release(stream) + c.mu.Lock() + ready := c.speech_ready_locked(a, stream) + c.mu.Unlock() + if !ready { + return false + } + stream.sequence++ + request := sdk.RemoteKeyRequest{RemoteOperation: sdk.RemoteOperation{Lease: stream.lease.Lease, Epoch: a.epoch, Sequence: stream.sequence}, Key: key} + if err := c.call("remote.key", request, nil); err != nil { + c.mu.Lock() + c.stop_locked(errLease) + c.mu.Unlock() + return false + } + return true +} + func (c *coordinator) speech_output(a *connectionAttempt, stream *speechStream, conn *relayConn) { for { select { diff --git a/tools/check.py b/tools/check.py index 0b51d5b..d817fec 100644 --- a/tools/check.py +++ b/tools/check.py @@ -168,8 +168,8 @@ def check_remote(repoRoot): timeout=60, check=True) value = json.loads(result.stdout) require(value.get("next") == "remote-select" - and "Experimental speech; keyboard, clipboard and Braille services are unavailable" in value["form"]["title"], - "Remote did not disclose its experimental speech scope") + and "Experimental speech and keyboard; clipboard and Braille services are unavailable" in value["form"]["title"], + "Remote did not disclose its experimental speech and keyboard scope") subprocess.run([ "go", "test", "./internal/app", "-run", "^(TestRemoteConnectionCommand|TestRemoteSpeech|TestRemoteDocument|TestRemoteReadAll|TestRemoteCurrentLine|TestRemoteNative|TestRemoteReview|TestRemoteFlatReview|TestRemoteWhereAmI|TestRemoteKeyboard)", "-count=1", "-timeout=90s",