Add Remote connection command and typed speech transport

This commit is contained in:
Storm Dragon committed 2026-11-04 13:14:24 -05:00
1 parent 0c74038c49
commit 703d44029c
20 files changed
+1053 -49

No files matched your search

+1
View File
@@ -6,3 +6,4 @@ __pycache__/
/wormhole/bin/
/battery-status/bin/
/remote/bin/
+1
View File
@@ -7,6 +7,7 @@ build:
go build -buildvcs=false -mod=readonly -o hello-world/bin/hello-world ./hello-world/src
go build -buildvcs=false -mod=readonly -o wormhole/bin/wormhole-tentacle ./wormhole/src
go build -buildvcs=false -mod=readonly -o battery-status/bin/battery-status ./battery-status/src
go build -buildvcs=false -mod=readonly -o remote/bin/remote ./remote/cmd/remote
check: build
go vet ./...
+6 -4
View File
@@ -4,8 +4,8 @@ A repository of experimental Tentacles for Cthulhu, maintained by Storm
Dragon. It contains [Hello World](hello-world/README.md), the development
[Wormhole tentacle](wormhole/README.md), and
[Battery Status](battery-status/README.md).
The [Remote implementation](remote/README.md) is in progress as a tested relay
library; it is not yet installable or able to control a desktop.
The [Remote implementation](remote/README.md) has a source-built relay-testing
command with reader-owned consent; it is not yet installable or able to control a desktop.
Repository material and these Tentacles are licensed under GPL-3.0-or-later; see
[LICENSE](LICENSE) and [CONTRIBUTING.md](CONTRIBUTING.md).
@@ -45,10 +45,12 @@ make check
```
The executables are `hello-world/bin/hello-world`,
`wormhole/bin/wormhole-tentacle`, and `battery-status/bin/battery-status`;
`wormhole/bin/wormhole-tentacle`, `battery-status/bin/battery-status`, and
the development command `remote/bin/remote`;
all are ignored by Git.
Checks validate the TOML metadata, registration and suggested bindings, and
invoke all three Tentacles through the actual Cthulhu host. They produce no speech
invoke the three catalog Tentacles through the actual Cthulhu host, plus private
Remote consent/relay and typed speech IPC tests. They produce no speech
or Braille and leave the running reader alone.
## Repository installation
+44 -8
View File
@@ -145,6 +145,33 @@ malicious same-user clients remain outside that guarantee. No connection command
is registered and no desktop service exists. Physical-source acceptance,
connection command integration and the existing live release gates remain open.
Eleventh implementation increment (2026-11-04): the source-built Remote command
now joins relay/role selection to reader-owned per-session consent and the
existing connection controls. A typed interaction request can ask for consent
only for its own process session; the continuation must match the SDK-delivered
action. All forms retain local-only XI2 capture. Core interaction completion
revokes its original epoch, and bounded child cleanup cancels pre-lease setup
on lock/handoff. Explicit persistent-pin Remember/Forget controls use the secure
store. The executable is included in source builds/checks, without a manifest,
catalog entry or release archive. See [the command contract and physical-input
test procedure](remote/command.md). Real-host/private-relay checks cover both
roles, denial, policy cancellation, certificate inspection, TLS join and
disconnect. The full Remote race suite, existing host/both-SDK conformance race
suites, focused application race checks, vet, reader build, repository `make check`,
and private Xorg input/internal-form harnesses passed. Native form-model coverage
also verifies Cancel works with empty relay fields. These use synthetic local-form submissions. Physical-keyboard
approval, audible masking and physical Braille acceptance remain pending.
No desktop services exist; Phase B/C and all live release gates remain open.
Twelfth implementation increment (2026-11-04): typed speech transport now has
Go/Python validation, lease-bound observed-output events and an explicit bounded
incoming reader mailbox. Revocation cancels accepted work and drains the queue;
overflow retires the lease. External conversion preserves whitespace, spelling,
language and utterance boundaries, splitting long UTF-8 text within encoded IPC
limits. See [the exact scope and checks](remote/speech.md). The speech worker
and coordinator are not connected; the source command remains relay-only.
Audible speech, real interoperability and the remaining release gates are open.
## 1. Intended result and recommended approach
Build a native Go Tentacle named **Remote**, with package ID `remote`, in this
@@ -654,8 +681,8 @@ share file lists, automatically paste text, or echo received text into diagnosti
permission, protocol and UI validators that need changes.
- [ ] Capture sanitized NVDA handshakes, output and gestures using a private test
relay and test documents. Record omitted fields, priorities and role routing.
- [ ] Write `remote/protocol.md` with supported message semantics, limits and
explicit unsupported features. Resolve provenance before importing material.
- [ ] Complete the existing `remote/protocol.md` contract with captured NVDA
evidence, supported semantics and limits. Resolve provenance before importing material.
- [ ] Review the lease, origin, threading, heartbeat and crash-cleanup designs.
Prototype Xorg consume/inject/provenance and virtual Braille rendering early:
these are the highest-risk dependencies, not finishing touches.
@@ -678,17 +705,22 @@ do not claim them from a design diagram.
- [ ] Integrate verified local consent and lock/handoff revocation with production
reader owners. Core consent, policy-bound managers and I38lock/XTerm revocation
are implemented; XI2 injected-approval rejection is privately tested. Physical
source acceptance and connection-command registration remain pending; see
source acceptance remains pending; source command integration now has private
real-host coverage. See
[the authorization increment](../cthulhu/docs/tentacle-remote-authorization.md).
- [x] Update registry/install/update grant persistence and access descriptions.
Existing Hello World, Wormhole and Battery Status actual-host checks passed.
- [ ] Add production first-use consent and per-session access controls.
- [x] Add reader-owned first-use consent and per-session access controls to the
source command. Physical-source approval acceptance remains pending.
- [x] Add transient secret-entry schema/editor support, reject persistent secret
preference controls, and test both SDKs and private Xorg form behavior. Live
audible speech/physical Braille acceptance remains pending with connection UI.
- [x] Document implemented public lifecycle operations, errors, ownership and
limits in the reader repository. Runtime Remote code stays external.
- [ ] Implement and document typed desktop services and their delivery-time checks.
Typed speech validation, lease-bound output events, an explicit reader-owned
incoming mailbox and both SDKs now have private coverage. The production speech
owner and delivery-time output policy remain pending; see [speech.md](remote/speech.md).
Exit: permission denials, timeout/overflow, stale epochs and process failures are
tested; existing Tentacles still install, register, run, disable and update.
@@ -703,10 +735,14 @@ tested; existing Tentacles still install, register, run, disable and update.
- [ ] Add the local CA/pin trust and Remember key UI workflows.
Library certificate-review and masked Remember/Forget handlers now integrate
with Connect, explicit saved-key loading and status/Disconnect. Verified local
input origin, endpoint/role selection, persistent-pin UI and production wiring
remain open. See [the connection workflow](remote/connection-ui.md).
input acceptance remains pending. Endpoint/role selection, persistent-pin UI
and production source-command wiring now exist, with private real-host
coverage. See [the source command](remote/command.md).
- [ ] Add core output observation and incoming remote presentation with origin
tracking, cancel order and lock/handoff revocation.
The [typed speech transport and relay conversion](remote/speech.md) prerequisite
now exists, preserving whitespace and UTF-8 across bounded IPC frames. The
source command remains relay-only until the worker/coordinator are connected.
- [ ] Demonstrate controlled Cthulhu speech to NVDA and NVDA speech to controlling
Cthulhu, then Cthulhu-to-Cthulhu. Verify read-all, spelling and ordinary stop.
@@ -745,8 +781,8 @@ features. A synthetic cell recorder cannot close physical Braille acceptance.
- [ ] Add catalog/manifest only once the required reader API exists. Record the
minimum supported reader/protocol and reject older hosts clearly.
- [ ] Extend `Makefile`, `tools/check.py`, `tools/package.py` and `.gitignore` for
Remote. The checker currently hard-codes three Tentacles and their grants;
the packager has special binary-name handling. Update both deliberately.
Remote. Source build/check/ignore support now exists; catalog/release packaging
remains unchanged and still needs explicit Remote support after readiness.
- [ ] Package Linux amd64/arm64 native executables, README, license and required
attribution; keep secret state and test certificates out of archives.
- [ ] Test extracted packages through the host and installer on the matching
+24 -13
View File
@@ -2,11 +2,16 @@
Remote will connect Cthulhu to an NVDA Remote protocol-v2 relay, as either a
controller or a controlled computer. The first implementation increment is a
tested Go relay library in `src/`. It is not yet a runnable or installable
Tentacle. There is no manifest, catalog entry, production connection UI or desktop access.
tested Go relay library in `src/`. A subsequent increment now provides a
source-built command with relay/role selection, reader-owned consent and connection
controls. It has no manifest, catalog entry or desktop access and is not installable.
See [the source command and physical-input checks](command.md).
Implemented:
- Typed speech conversion and matching reader IPC validators/mailbox, with
private Go/Python host coverage. This is transport only; production speech
delivery/export is still pending. See [speech.md](speech.md).
- Bounded newline JSON framing, duplicate-key and collection validation, and
typed speech, keyboard, membership, clipboard and Braille decoding.
- TLS with normal certificate/hostname validation or an already-approved,
@@ -28,7 +33,7 @@ Implemented:
A single library connection workflow now combines them with explicit saved-key
loading, Connect and status/Disconnect. Setup cancellation follows pending
approval lifetime; stale forms cannot disconnect a newer epoch. These have
private SDK-process coverage, but no production connection registration.
private SDK-process coverage and source-command registration.
The reader authorization prerequisite is described below. See [security-ui.md](security-ui.md) and
[connection-ui.md](connection-ui.md).
@@ -36,7 +41,7 @@ The adjacent reader now also supports secret entries in transient Tentacle forms
masked speech/Braille editing, copy/cut denial, explicit paste and cancellation
without returning values. Persistent preference pages reject secret entries.
This prerequisite is covered by both SDKs and a private Xorg form harness; it
does not yet provide Remote's production connection UI. Credential storage and
does not by itself provide Remote's connection UI. Credential storage and
the combined connection workflow are supplied by the library described above.
A subsequent [private Xorg feasibility increment](../../cthulhu/docs/testing/remote-input-feasibility.md)
@@ -60,10 +65,16 @@ and GTK tests cover this foundation. The library coordinator now consumes these
leases through the public Go SDK, with private synthetic-host/TLS coverage.
A subsequent [reader authorization increment](../../cthulhu/docs/tentacle-remote-authorization.md)
adds core consent, lock/handoff cancellation and local-only sensitive forms.
Injected approval is rejected in private XI2 tests; physical-keyboard approval and
connection-command registration remain unverified/unimplemented respectively.
Injected approval is rejected in private XI2 tests; physical-keyboard approval
remains unverified. The source command now requests core consent through typed
interaction requests. Core revokes the original epoch on interaction completion;
bounded cancellation also stops pre-lease inspection on lock/handoff.
There is no reader desktop service yet.
Explicit Trust and remember/Forget pin actions now manage endpoint-bound saved
certificate trust. `make build` builds `remote/bin/remote`; `make check` also
checks initial command-host output and real-host/private-relay integration.
This implements relay data handling, storage, connection lifecycle and library
forms. Parsing a key, speech fragment or
Braille gesture does not execute it. Network readiness is not consent. The
@@ -87,14 +98,14 @@ the desktop display or a clipboard. The coordinator also uses the actual Go SDK
over private pipes against a synthetic lifecycle host. A separate workflow test
process exercises actual SDK form/lease IPC, storage and private relay TLS together.
Fixtures are independently written examples
based on source review, **not captured NVDA sessions**. There is no live desktop
test to run for this increment.
based on source review, **not captured NVDA sessions**. The [source-command
procedure](command.md) describes pending physical-input acceptance checks;
private fixtures do not establish them.
Pending: actual NVDA/add-on/Orca interoperability, physical-source approval and
connection-command integration, reader desktop services, speech delivery/export, exclusive keyboard capture,
Pending: actual NVDA/add-on/Orca interoperability, physical-source approval,
reader desktop services, speech delivery/export, exclusive keyboard capture,
injection provenance and reader-death recovery, clipboard permission,
endpoint/role selection and production connection UI integration, persistent-pin
management, virtual Braille integration, physical displays and packaging. The
virtual Braille integration, audible masking, physical displays and packaging. The
full remote-control release must not be advertised until those gates pass.
## Relay trust
@@ -102,7 +113,7 @@ full remote-control release must not be advertised until those gates pass.
TLS protects the connection to the relay. NVDA Remote v2 is not end-to-end
encrypted: the relay can see the channel key and session contents. Relay origin
IDs do not authenticate human identities. Rejecting extra peers cannot undo data
the relay already sent to them. The future UI must explain these properties
the relay already sent to them. The reader's consent UI explains these properties
before issuing consent.
The code is an independent implementation licensed under GPL-3.0-or-later;
+30
View File
@@ -0,0 +1,30 @@
// Copyright (c) 2026 Storm Dragon
// SPDX-License-Identifier: GPL-3.0-or-later
package main
import (
"flag"
"os"
"path/filepath"
remote "git.stormux.org/storm/cthulhu-tentacles/remote/src"
)
func main() {
dataDirectory := flag.String("data-dir", "", "Private Remote settings directory (parent must exist)")
flag.Parse()
if flag.NArg() != 0 {
os.Exit(2)
}
if *dataDirectory == "" {
configDirectory, err := os.UserConfigDir()
if err != nil {
os.Exit(1)
}
*dataDirectory = filepath.Join(configDirectory, "cthulhu-remote")
}
if remote.Serve(os.Stdin, os.Stdout, *dataDirectory) != nil {
os.Exit(1)
}
}
+140
View File
@@ -0,0 +1,140 @@
# Remote source command and reader consent
The source-built Remote executable now registers a production command through
the public Go SDK. This increment joins relay/role selection, reader-owned
consent and the existing connection workflow. It is **relay testing only**:
there is no speech delivery, keyboard forwarding/injection, clipboard transfer
or Braille service. There is still no installable manifest or catalog entry.
Base revisions checked against maintained upstreams on 2026-11-04: reader
`testing` at `4cf3335`, Tentacles `master` at `0c74038`. No installed reader or
active desktop session is changed by building or running the private tests.
## Ownership and behavior
`remote/cmd/remote` calls `remote.Serve` with owned SDK streams and a private
settings directory. Its default is `$XDG_CONFIG_HOME/cthulhu-remote`, or
`~/.config/cthulhu-remote` when unset. `--data-dir` selects an absolute directory;
parents must already exist. Existing storage restrictions apply, including
rejection of symlinked ancestors and unsafe permissions. Startup loads only
ordinary relay/role/pin settings, with no networking or saved-key read.
The `remote` command uses **Cthulhu+Ctrl+Shift+R** in both layouts. It opens
relay host, port and controller/controlled role selection, initially on Cancel.
Save relay and role writes only ordinary settings and never connects. Changing
the endpoint drops the previous endpoint's pin. Review access returns a typed
`Interaction.remote` request to the host, not a lease or permission decision.
The host keeps its existing interaction slot and resolves the exact requesting
process session. Install grants limit the requested role/grants. The reader's
own local-only form starts on Cancel with every grant unchecked. This development
command requests only `remote-present` for controller or `output-observe` for
controlled; neither service is implemented yet. Keyboard, clipboard and Braille
permissions are not requested. A shortcut, child request or fabricated command
argument cannot approve access.
On explicit nonempty approval the reader issues `remote.action` through the SDK
event stream and gives the continuation a matching `Submission.remote`. The
command waits for that exact SDK event before claiming the connection workflow.
Cancel, denial, policy loss and missing events cannot advance to credentials.
The pending action expires after 30 seconds; long certificate/key reviews can
outlast it. In that case Connect fails and a fresh local access review is needed.
Every Remote form uses the reader's sensitive XI2 input capture, including relay
selection, secret editing, trust, saved keys and status. The coordinator owns
the only SDK event consumer and heartbeats the lease before/during networking.
All networking remains on its workers. The command never reconnects automatically.
When an interaction ends, core revokes only its original approved epoch, including
unused actions. Stale cleanup cannot revoke replacement consent. On cancellation
or an unfinished exit, a bounded cleanup invocation also retires child setup.
This is needed before `remote.open`, when no lease-revocation event exists.
Lock/handoff invalidates the interaction's original policy context; returning
does not revive it. Process EOF joins workflow/inspection/relay/event workers
before closing storage. Repeated shortcuts cannot replace a live workflow.
## Explicit saved trust
Certificate review additionally offers **Trust and remember this certificate
for this relay host and port**. It consumes that review once, saves the exact
observed digest using the existing private atomic store, and returns to explicit
Connect. Copy fingerprint and Trust once retain their previous meanings.
The credentials form can forget the current endpoint's pin and return to normal
CA/hostname validation. These actions neither open a lease nor join the relay.
Write errors are reported; a sync failure after rename can leave stored trust
changed, so a failed save is not described as a rollback.
## Private verification
From the Tentacles checkout:
```sh
make check GOPROXY=off
GOCACHE=/tmp/cthulhu-cache GOPROXY=off go test -race ./remote/... -count=1 -timeout=90s
go build -race -o /tmp/cthulhu-remote-next ./remote/cmd/remote
```
From the reader checkout, using that separately built executable:
```sh
GOCACHE=/tmp/cthulhu-go-cache GOPROXY=off CTHULHU_REMOTE_BINARY=/tmp/cthulhu-remote-next go test -race ./internal/app -run '^TestRemoteConnectionCommand' -count=1 -timeout=90s -v
```
`make check` builds the source command, checks its initial interaction through
the command host, and runs these real-process application integration cases.
They cover both roles, unchecked core consent, denial/empty approval, fresh
setup after lock/handoff cancellation, key-free inspection, explicit Trust once,
fresh TLS join and disconnect. A stalled-inspection case verifies cancellation
before a lease exists. Unit/race tests additionally cover invalid requests,
fabricated approval without an SDK event, endpoint trust isolation, explicit
Remember/Forget pin, failed writes and stale/removed pins. Native form-model
coverage verifies empty relay entries do not block Cancel. The complete Remote
race suite, existing host/both-SDK conformance race suites, focused application
race tests, vet, reader build and `make check` passed. Existing private Xorg
remote-input and internal-form harnesses also passed, retaining injected-approval
rejection, secret/ordinary forms, learn mode and XTerm handoff behavior.
Fixtures use private loopback relays and synthetic local
form submissions; they do not exercise physical keyboard input.
## Physical keyboard acceptance, still pending
Use a disposable Xorg desktop with the newly built matching reader and command.
Do not attach synthetic input to the active reader. A development launch list
may contain the following, with absolute paths substituted:
```json
[
{
"ID": "remote",
"Program": ["/absolute/cthulhu-tentacles/remote/bin/remote", "--data-dir", "/absolute/private-parent/remote-state"],
"Presentation": true,
"Interaction": true,
"SessionEvents": true,
"RemoteGrants": ["output-observe", "remote-present"]
}
]
```
Pass that file with `--tentacles /absolute/launch.json` and a disposable
`--config` when starting the matching reader in that test session. Building
Remote alone does not update the reader's consent-interaction support.
1. Use physical keys to open Remote, Tab/Shift+Tab through every control, select
each role and cancel. Review access must focus Cancel, with no prechecked
permissions. Approval with nothing checked must not reach credentials.
2. Approve the requested grant and verify masked typing/editing, denied copy/cut,
explicit paste and empty fields after cancelling/reopening. Confirm audible
output and physical Braille do not reveal the key.
3. Use a private relay. Inspect its certificate, verify/copy its fingerprint,
test Cancel, Trust once, explicit Remember/Forget pin, and Remember/Forget key.
Confirm none connects until Connect is chosen. Restart the test process and
check stored trust without automatic connection or automatic key loading.
4. Cancel while inspection or TLS join stalls; lock/unlock and trigger XTerm
handoff during consent, inspection and an established relay connection.
Confirm cancellation, no resume, no stale approval and a fresh usable command.
5. Recheck ordinary entries/menus, secret forms, learn mode, remapped shortcuts,
application key delivery and Hello World/Wormhole/Battery Status. These share
the changed host interaction path. Review the diff before any submission.
Physical-source acceptance, audible masking, physical Braille, desktop services,
actual NVDA/Orca interoperability and packaging remain separate open gates.
+15 -10
View File
@@ -1,9 +1,10 @@
# Remote connection workflow
The connection library now combines certificate review, saved-key actions and
the coordinator in one workflow. This remains **test-only wiring**: no production
command, manifest or reader consent issuer exists. Remote is not ready for live
desktop testing. The maintained Tentacles `master` matched `origin/master` at
The connection library combines certificate review, saved-key actions and
the coordinator in one workflow. The subsequent [source command](command.md)
now wires endpoint/role selection and reader-owned consent into it; physical
input acceptance is pending. No manifest or desktop service exists. The original
library increment's maintained Tentacles `master` matched `origin/master` at
`63e84e9` after fetch on 2026-11-03; existing uncommitted work was preserved.
No reader files or installed programs changed.
@@ -15,10 +16,10 @@ public SDK. It claims that action for one workflow and copies the reader's
role/grants and endpoint trust. Caller-modified role/grants are ignored. Opening
the workflow neither reads a saved key nor opens a network connection.
The production owner must supply endpoint/role selection, verify local input
origin and cancel the workflow context on closure, lock/handoff or retirement.
The source-command owner supplies endpoint/role selection. The reader owns
local-only input capture and cancels the interaction on lock/handoff or retirement.
The workflow does not manufacture consent from a command or `Submission`. Its
`remote-connection` continuation is registered only in a private test peer.
`remote-connection` continuation is now registered by the source command.
The owner must serialize the currently displayed form's submissions; this
library supplies no proof that a submission came from that form or a local key.
@@ -53,6 +54,9 @@ epoch: closing an old form cannot retire a newer approval or connection.
connecting, waiting, peer membership, cleanup and failure. Every status states
that desktop services are unavailable. **Disconnect and close**, Escape/form
cancellation or owner cancellation retires the workflow.
- **Trust and remember this certificate** saves its exact pin for this host/port
and returns to explicit Connect. **Forget this relay's pin** restores normal
certificate/hostname validation. Neither connects automatically.
Entries are always empty and masked. Responses and status omit channel keys and
server/RPC error text. Loaded keys are released on Connect, inspection, saved-key
@@ -82,9 +86,10 @@ synthetic values. They do not prove local input origin or accessible form
navigation. The focused race tests passed ten repetitions after correcting an
inspection/cleanup race; the complete race suite and `make check` also passed.
Before production registration, resolve reader-owned consent/input provenance,
endpoint/role selection, persistent-pin management and lock/handoff revocation.
Then test these actual forms with Tab/Shift+Tab, list navigation, masked editing,
Source registration, core consent, endpoint/role selection, persistent-pin
management and lock/handoff cleanup now have private integration coverage.
Physical-source input remains unverified. Test the actual forms with
Tab/Shift+Tab, list navigation, masked editing,
Copy, Cancel and failed storage, including cancellation during inspection/join.
Recheck ordinary Tentacle forms, CA and pin connections, certificate rotation,
Hello World, Wormhole and Battery Status. Reader desktop services, real NVDA/Orca
+12
View File
@@ -5,6 +5,18 @@ increment implements part of phases A and C. **Phase A is not complete**: actual
captured NVDA fixtures and complete Xorg/Braille feasibility evidence are missing.
It does not establish any of the release acceptance gates.
Current update: [the source command](command.md) now supplies endpoint/role
selection, core-consent interaction wiring, persistent-pin actions and private
real-host relay integration. Earlier increment descriptions below are historical;
connection registration is implemented, while physical-source approval and
desktop services remain pending.
The next increment adds [typed speech IPC and relay conversion](speech.md).
The reader has an explicit bounded speech mailbox and lease-bound output
events, exercised through both SDKs. No production output owner is connected;
the command remains relay-only. Policy-resolved observation, remote speech
delivery, coordinator wiring and live speech acceptance are still open.
## Confirmed reader boundaries
Source inspection began at reader revision
+4
View File
@@ -1,5 +1,9 @@
# Remote connection coordinator
Current integration: [the source command](command.md) now supplies reader-owned
consent and connection controls. The original library increment below predates
that wiring. There are still no desktop effects or installable Remote package.
Implemented as a source-library increment on 2026-11-03, based on Tentacles
`63e84e9` and the public Go SDK in reader `573d15d`. The Tentacles branch matched
`origin/master` after fetch. The reader revision was inspected locally; its
+6
View File
@@ -1,5 +1,11 @@
# Remote certificate review and saved-key form handlers
Current integration: the subsequent [source command](command.md) now registers
the combined continuation behind reader-owned local consent and sensitive input
capture. It adds explicit persistent-pin Remember/Forget. The original library
increment below remains its historical verification record; physical-source
acceptance and desktop services are still pending.
Implemented as a source-library increment on 2026-11-03, on Tentacles `master`
at `63e84e9` with the existing coordinator work preserved. The maintained remote
branch matched that revision when checked. This uses the adjacent reader's
+54
View File
@@ -0,0 +1,54 @@
# Typed speech transport and relay conversion
Remote now has a tested conversion boundary between NVDA protocol-v2 speech and
the matching experimental reader's typed speech IPC. This is a prerequisite for
speech integration. The source command still discards desktop payloads and does
not call `remote.present` or send reader output to the relay.
`src/speech_bridge.go` converts speech, cancel and pause messages. It preserves
text fragments and whitespace, resolved spelling/language state, end-utterance
boundaries and numeric priorities. Long text splits at UTF-8 boundaries into
frames within the reader's 6144-byte canonical JSON limit, including escaped
control characters. Each frame retains resolved character/language state.
Unknown NVDA speech commands remain counted by the existing decoder and are not
converted into reader effects. No peer-supplied path or backend command executes.
Outbound conversion emits NVDA command arrays, resets character/language state
when necessary, and leaves origin IDs to the relay. It validates every payload
through the same typed reader schema before serialization.
These helpers operate on data only. The future coordinator must check relay
membership before conversion, serialize presentation/heartbeat/close operation
sequences, recheck reader lease/epoch and peer readiness before each delivery or
send, and stop work on revocation. Split frames retain priority metadata; atomic
utterance admission and priority/cancel semantics still require reader-owner
integration. No audible pause/resume or priority fidelity is established here.
The matching reader adds a disabled-by-default incoming speech mailbox, typed
Go/Python validators and `remote.output` events. See
[its precise contract](../../cthulhu/docs/tentacle-remote-speech.md). These SDK
additions are prerequisites for building this increment; use the matching reader
source, not an older release. The existing connection command remains the only
production entry point and makes no speech-service claim.
Verification:
```sh
GOCACHE=/tmp/cthulhu-cache GOPROXY=off go test -race ./remote/src -count=1
make check GOPROXY=off
```
Conversion tests exercise spelling/language reset, cancel/pause, priorities,
unsupported commands, whitespace and long escaped multilingual text. Reader
tests send speech through real Go/Python SDK child processes and exercise stale
leases, replay, absent owners, origin restrictions and overflow cancellation.
The repository check also runs the reader's Remote speech host/SDK tests.
Existing greeting, Wormhole, Battery Status and connection/consent checks remain
regressions. These checks produce no audible speech and establish no physical
keyboard, Braille or real NVDA/Orca interoperability acceptance.
After the worker/coordinator integration, test ordinary reading, spelling,
read-all, key echo, stop speech and local status in both roles. Then test lock,
handoff, disconnect and peer loss for stale output and loops, using disposable
desktops before testing installed releases. Those workflows cannot be accepted
from this transport-only increment.
+238
View File
@@ -0,0 +1,238 @@
// Copyright (c) 2026 Storm Dragon
// SPDX-License-Identifier: GPL-3.0-or-later
package remote
import (
"context"
"encoding/json"
"io"
"strconv"
"sync"
"time"
sdk "git.stormux.org/storm/cthulhu/sdk/go/tentacle"
)
// Serve registers the relay-testing command with the public 1.1 SDK. It owns
// its coordinator, workers and private store until host EOF. No startup network
// connection, desktop effects, installed package or reusable consent is implied.
func Serve(input io.ReadCloser, output io.WriteCloser, dataDirectory string) error {
defer input.Close()
defer output.Close()
store, err := openSettingsStore(dataDirectory)
if err != nil {
return err
}
defer store.close()
selected, found, err := store.load()
if err != nil {
return err
}
if !found {
selected = settings{Version: 1, Role: "controller", Port: 6837}
}
client := sdk.NewSessionClient()
owner := &connectionCommand{coordinator: newCoordinator(context.Background(), client), store: store, selected: selected}
err = sdk.ServeSession(input, output, owner.commands(), nil, client)
owner.close()
return err
}
type connectionCommand struct {
mu sync.Mutex
coordinator *coordinator
store *settingsStore
selected settings
awaiting bool
workflow *connectionWorkflow
}
func (command *connectionCommand) commands() []sdk.Command {
entries := []struct {
id, title string
handler sdk.Handler
}{
{"remote", "Remote relay connection (desktop services unavailable)", 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},
}
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" {
value.Bindings = []sdk.Binding{{Layout: "desktop", Scope: "global", Key: "Cthulhu+Ctrl+Shift+R"}, {Layout: "laptop", Scope: "global", Key: "Cthulhu+Ctrl+Shift+R"}}
}
commands = append(commands, value)
}
return commands
}
func (command *connectionCommand) selection_form(notice string) sdk.Interaction {
roles := []sdk.ListItem{{ID: "controller", Label: "Control another computer"}, {ID: "controlled", Label: "Allow a helper to access this computer"}}
if command.selected.Role == "controlled" {
roles[0], roles[1] = roles[1], roles[0]
}
result := sdk.Interaction{Form: &sdk.Form{Title: "Remote relay and role. Relay testing only; desktop 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: "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"}
if notice != "" {
result.Presentation = security_message(notice).Presentation
}
return result
}
func (command *connectionCommand) open(ctx context.Context, _ json.RawMessage) (any, error) {
command.mu.Lock()
defer command.mu.Unlock()
if ctx.Err() != nil {
return nil, ctx.Err()
}
if command.workflow != nil {
select {
case <-command.workflow.done:
command.workflow = nil
default:
return command.workflow.form(), nil
}
}
if command.awaiting {
return security_message("A Remote access review is already pending."), nil
}
if err := command.refresh_pin(&command.selected); err != nil {
return security_message("Saved relay trust could not be read."), nil
}
return command.selection_form(""), nil
}
// Re-read stored trust for the selected endpoint, including removals or changes
// from previous workflows. A failed read cannot silently fall back to an old pin.
func (command *connectionCommand) refresh_pin(selected *settings) error {
stored, found, err := command.store.load()
if err != nil {
return err
}
selected.Pin = nil
if found && stored.Host == selected.Host && stored.Port == selected.Port {
selected.Pin = stored.Pin
}
return nil
}
func (command *connectionCommand) select_relay(ctx context.Context, raw json.RawMessage) (any, error) {
command.mu.Lock()
defer command.mu.Unlock()
var value sdk.Submission
if json.Unmarshal(raw, &value) != nil {
return nil, sdk.ErrProtocol
}
if ctx.Err() != nil || value.Cancelled || value.Activated == "cancel" {
return security_message("Remote setup cancelled."), nil
}
if command.awaiting || command.workflow != nil {
return security_message("A Remote connection workflow is already open."), nil
}
if value.Activated != "review-access" && value.Activated != "save-settings" {
return command.selection_form(""), nil
}
port, err := strconv.Atoi(value.Values["port"].Text)
selected := settings{Version: 1, Host: value.Values["host"].Text, Port: port, Role: value.Values["role"].Selected}
if _, validationErr := selected.endpoint(); err != nil || validationErr != nil {
return command.selection_form("Enter a valid relay host, port and connection role."), nil
}
if err := command.refresh_pin(&selected); err != nil {
return command.selection_form("Saved relay trust could not be read."), nil
}
command.selected = selected
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"
if selected.Role == "controlled" {
grant = "output-observe"
}
command.awaiting = true
return sdk.Interaction{Remote: &sdk.RemoteRequest{Role: selected.Role, Grants: []string{grant}}, Next: "remote-approved"}, nil
}
func (command *connectionCommand) approved(ctx context.Context, raw json.RawMessage) (any, error) {
command.mu.Lock()
defer command.mu.Unlock()
var value sdk.Submission
if json.Unmarshal(raw, &value) != nil {
return nil, sdk.ErrProtocol
}
if !command.awaiting || command.workflow != nil {
return security_message("Start a fresh Remote access review."), nil
}
command.awaiting = false
if value.Cancelled || value.Remote == nil || ctx.Err() != nil {
return security_message("Remote access was not approved."), nil
}
// The event consumer and command handlers run independently. Wait briefly
// for this exact SDK-delivered action; a command argument alone cannot mint
// approval. Role/grants from the event remain authoritative in the coordinator.
waitCtx, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
for {
select {
case action, open := <-command.coordinator.actions:
if !open {
return security_message("Reader approval is unavailable."), nil
}
if action.Action != value.Remote.Action || action.Epoch != value.Remote.Epoch {
continue
}
if action.Role != command.selected.Role {
return security_message("Remote role changed. Start a fresh access review."), nil
}
target, err := command.selected.endpoint()
if err != nil {
return nil, err
}
workflow, err := new_connection_workflow(command.coordinator.ctx, command.coordinator, action, target, command.store)
if err != nil {
return security_message("Remote approval ended. Start a fresh access review."), nil
}
command.workflow = workflow
return workflow.form(), nil
case <-waitCtx.Done():
return security_message("Remote approval ended. Start a fresh access review."), nil
}
}
}
func (command *connectionCommand) submit(ctx context.Context, raw json.RawMessage) (any, error) {
command.mu.Lock()
defer command.mu.Unlock()
var value sdk.Submission
if json.Unmarshal(raw, &value) != nil {
return nil, sdk.ErrProtocol
}
if command.workflow == nil {
return security_message("No Remote connection workflow is open."), nil
}
return command.workflow.submit(ctx, value)
}
func (command *connectionCommand) close() {
command.mu.Lock()
defer command.mu.Unlock()
if command.workflow != nil {
command.workflow.close()
<-command.workflow.done
}
barrier := command.coordinator.disconnect()
command.coordinator.close()
<-barrier
<-command.coordinator.done
}
+158
View File
@@ -0,0 +1,158 @@
// SPDX-License-Identifier: GPL-3.0-or-later
package remote
import (
"context"
"crypto/sha256"
"encoding/json"
"io"
"net"
"strings"
"testing"
"time"
sdk "git.stormux.org/storm/cthulhu/sdk/go/tentacle"
)
func TestRemoteCommandSelectsEndpointWithoutAccessOrNetworking(t *testing.T) {
c, client := fixtureCoordinator(t, nil)
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 {
t.Fatal("continuation has a shortcut")
}
}
for _, role := range []string{"controller", "controlled"} {
raw, _ := json.Marshal(sdk.Submission{Activated: "review-access", Values: map[string]sdk.Value{
"host": {Text: "relay.invalid"}, "port": {Text: "6837"}, "role": {Selected: role},
}})
value, err := command.select_relay(t.Context(), raw)
if err != nil {
t.Fatal(err)
}
result := value.(sdk.Interaction)
grant := "remote-present"
if role == "controlled" {
grant = "output-observe"
}
if result.Remote == nil || result.Remote.Role != role || len(result.Remote.Grants) != 1 || result.Remote.Grants[0] != grant {
t.Fatal("selection did not request core approval for its role")
}
// A fabricated command argument cannot replace an SDK action event.
limited, cancel := context.WithTimeout(t.Context(), 20*time.Millisecond)
fake, _ := json.Marshal(sdk.Submission{Remote: &sdk.SessionEvent{Kind: "remote.action", Epoch: 1, Action: strings.Repeat("a", 32)}})
value, err = command.approved(limited, fake)
cancel()
if err != nil || !value.(sdk.Interaction).Done || command.workflow != nil {
t.Fatal("fabricated approval opened connection controls")
}
}
select {
case call := <-client.calls:
t.Fatal("selection or forged approval opened a lease", call.method)
default:
}
}
func TestRemoteCommandRejectsInvalidSelectionAndDropsEndpointPin(t *testing.T) {
c, _ := fixtureCoordinator(t, nil)
store, _, saved := settingsFixture(t)
command := &connectionCommand{coordinator: c, store: store, selected: saved}
for _, host := range []string{"bad\nrelay", "bad\x00relay", ""} {
raw, _ := json.Marshal(sdk.Submission{Activated: "review-access", Values: map[string]sdk.Value{
"host": {Text: host}, "port": {Text: "6837"}, "role": {Selected: "controller"},
}})
value, err := command.select_relay(t.Context(), raw)
if err != nil || value.(sdk.Interaction).Remote != nil || command.awaiting {
t.Fatal("invalid endpoint reached approval")
}
}
raw, _ := json.Marshal(sdk.Submission{Activated: "save-settings", Values: map[string]sdk.Value{
"host": {Text: "other.invalid"}, "port": {Text: "6838"}, "role": {Selected: "controlled"},
}})
value, err := command.select_relay(t.Context(), raw)
if err != nil || value.(sdk.Interaction).Remote != nil {
t.Fatal("saving settings requested access")
}
loaded, found, err := store.load()
if err != nil || !found || loaded.Host != "other.invalid" || loaded.Pin != nil || loaded.Role != "controlled" {
t.Fatal("endpoint change retained old trust or did not save settings")
}
}
func TestRemoteCommandRefreshesRemovedPinsAndFailsClosedOnStorageError(t *testing.T) {
c, _ := fixtureCoordinator(t, nil)
store, _, saved := settingsFixture(t)
if err := store.save(saved); err != nil {
t.Fatal(err)
}
stale := saved
stale.Pin = &savedPin{Host: saved.Host, Port: saved.Port, SHA256: strings.Repeat("1", 64)}
command := &connectionCommand{coordinator: c, store: store, selected: stale}
value, err := command.open(t.Context(), nil)
if err != nil || value.(sdk.Interaction).Form == nil || command.selected.Pin != nil {
t.Fatal("reopening reused a removed certificate pin")
}
store.close()
for attempt := 0; attempt < 2; attempt++ {
value, err := command.open(t.Context(), nil)
if err != nil || !value.(sdk.Interaction).Done || value.(sdk.Interaction).Form != nil {
t.Fatal("a repeated command bypassed failed trust loading")
}
}
}
func TestConnectionWorkflowRememberPinAndForgetAreExplicit(t *testing.T) {
for _, failWrite := range []bool{false, true} {
t.Run(map[bool]string{false: "remember-and-forget", true: "failed-write"}[failWrite], func(t *testing.T) {
c, client := fixtureCoordinator(t, nil)
store, _, _ := settingsFixture(t)
certificate, _ := testCertificate(t, false)
inspected := make(chan struct{})
target := testRelay(t, certificate, func(connection net.Conn) {
data, _ := io.ReadAll(connection)
if len(data) != 0 {
t.Error("inspection disclosed application data")
}
close(inspected)
})
w := workflowFixture(t, c, approve(t, c, client, 1, "controller"), target, store)
workflowSubmit(t, w, "inspect-certificate", "")
awaitDone(t, w.probeDone)
awaitDone(t, inspected)
if failWrite {
store.close()
}
result := workflowSubmit(t, w, "remember-pin", "")
if result.Form == nil || result.Form.Title != "Connect Remote relay" {
t.Fatal("Remember did not return to explicit Connect")
}
if failWrite {
if w.target.pin != nil || !strings.Contains(result.Speech, "save failed") {
t.Fatal("failed storage silently approved the new certificate")
}
} else {
loaded, found, err := store.load()
if err != nil || !found || loaded.Pin == nil || loaded.Host != target.host || loaded.Port != target.port {
t.Fatal("pin was not bound to the selected endpoint")
}
restored, err := loaded.endpoint()
if err != nil || restored.pin == nil || restored.pin.sha256 != sha256.Sum256(certificate.Certificate[0]) {
t.Fatal("remembered pin changed across reload")
}
workflowSubmit(t, w, "forget-pin", "")
loaded, _, err = store.load()
if err != nil || loaded.Pin != nil || w.target.pin != nil {
t.Fatal("Forget retained the certificate exception")
}
}
select {
case call := <-client.calls:
t.Fatal("trust action opened a lease", call.method)
default:
}
})
}
}
+41 -4
View File
@@ -4,6 +4,7 @@ package remote
import (
"context"
"encoding/hex"
"errors"
"net"
"strconv"
@@ -13,8 +14,8 @@ import (
)
// connectionWorkflow joins the library forms and coordinator for one selected
// endpoint and reader action. It is NOT a local-origin authorizer. Production
// registration still requires reader-owned consent and trusted submissions.
// endpoint and reader action. It is not a local-origin authorizer: the source
// command relies on reader-owned consent and sensitive form submissions.
// The owner must cancel ctx on form closure, lock/handoff or process retirement.
type connectionWorkflow struct {
mu sync.Mutex
@@ -125,6 +126,9 @@ func (w *connectionWorkflow) form_locked() sdk.Interaction {
elements = append(elements,
sdk.Element{ID: "load-key", Label: "Use saved key", Kind: sdk.Button},
sdk.Element{ID: "saved-key-actions", Label: "Remember or forget a key", Kind: sdk.Button})
if w.target.pin != nil {
elements = append(elements, sdk.Element{ID: "forget-pin", Label: "Forget this relay's pin and use normal certificate validation", Kind: sdk.Button})
}
}
elements = append(elements, sdk.Element{ID: "cancel", Label: "Cancel", Kind: sdk.Button})
result.Form = &sdk.Form{Title: "Connect Remote relay", Elements: elements}
@@ -136,6 +140,9 @@ func (w *connectionWorkflow) form_locked() sdk.Interaction {
}}
case "certificate":
result = w.review.form()
if w.store != nil {
result.Form.Elements = append(result.Form.Elements, sdk.Element{ID: "remember-pin", Label: "Trust and remember this certificate for this relay host and port", Kind: sdk.Button})
}
case "saved-key":
result = w.keys.form()
case "status":
@@ -280,21 +287,51 @@ func (w *connectionWorkflow) submit(ctx context.Context, value sdk.Submission) (
} else {
w.keys, w.mode = keys, "saved-key"
}
case "forget-pin":
if w.store == nil {
break
}
selected, found, err := w.store.load()
if err == nil && found && selected.Host == w.target.host && selected.Port == w.target.port {
selected.Pin = nil
err = w.store.save(selected)
}
if err != nil {
w.notice = "The certificate pin update failed. Stored trust may have changed; review it before another connection."
} else {
w.target.pin = nil
w.notice = "Normal certificate and hostname validation will be used. No connection was started."
}
}
case "certificate":
remember := value.Activated == "remember-pin" && w.store != nil
if remember {
value.Activated = "trust-once"
}
approved, result, err := w.review.submit(ctx, value)
if err != nil || result.Done {
w.review, w.mode = nil, "credentials"
w.notice = result.Speech
if err != nil {
w.notice = "Certificate review ended without approval."
} else if approved.host != "" && remember {
selected := settings{Version: 1, Role: w.action.Role, Host: approved.host, Port: approved.port,
Pin: &savedPin{Host: approved.host, Port: approved.port, SHA256: hex.EncodeToString(approved.pin.sha256[:])}}
if w.store.save(selected) != nil {
w.notice = "The certificate pin save failed. Stored trust may have changed; review it before another connection."
} else {
w.target = approved
w.notice = "Certificate pin remembered for this relay host and port. Choose Connect relay to connect."
}
} else if approved.host != "" {
w.target = approved
w.notice = "Certificate approved for this attempt only. Enter a channel key and choose Connect relay."
}
} else {
result.Next = "remote-connection"
return result, nil
// Rebuild the nested form to retain the optional Remember pin action.
form := w.form_locked()
form.Clipboard = result.Clipboard
return form, nil
}
case "saved-key":
result, err := w.keys.submit(ctx, value)
+125
View File
@@ -0,0 +1,125 @@
// SPDX-License-Identifier: GPL-3.0-or-later
package remote
import (
"unicode/utf8"
sdk "git.stormux.org/storm/cthulhu/sdk/go/tentacle"
)
// reader_speech converts an already decoded relay payload. The caller must
// first check session.accept and then use a live lease for remote.present.
// Conversion alone neither authorizes nor queues a reader effect.
func reader_speech(message message) ([]sdk.RemoteSpeech, error) {
switch message.kind {
case "cancel":
return []sdk.RemoteSpeech{{Kind: "cancel"}}, nil
case "pause_speech":
paused, ok := message.payload.(bool)
if !ok {
return nil, errProtocol
}
return []sdk.RemoteSpeech{{Kind: "pause", Paused: &paused}}, nil
case "speak":
value, ok := message.payload.(speech)
if !ok || value.priority < 0 || value.priority > 2 {
return nil, errProtocol
}
var result []sdk.RemoteSpeech
current := sdk.RemoteSpeech{Kind: "speak", Priority: value.priority}
append_part := func(part sdk.RemoteSpeechPart) error {
candidate := current
candidate.Parts = append(current.Parts, part)
if !sdk.ValidRemoteSpeech(candidate) {
if len(current.Parts) == 0 {
return errLimit
}
result = append(result, current)
candidate.Parts = []sdk.RemoteSpeechPart{part}
if !sdk.ValidRemoteSpeech(candidate) {
return errProtocol
}
}
current = candidate
return nil
}
characters, language := false, ""
for _, part := range value.parts {
switch part.kind {
case "characters":
characters = part.characters
case "language":
language = part.text
case "end":
if err := append_part(sdk.RemoteSpeechPart{End: true}); err != nil {
return nil, err
}
case "text":
if !utf8.ValidString(part.text) {
return nil, errProtocol
}
text := part.text
for text != "" {
// Even a fragment made entirely of escaped control characters
// fits alone. Never cut a UTF-8 code point or trim whitespace.
size := min(len(text), 512)
for size < len(text) && !utf8.RuneStart(text[size]) {
size--
}
if err := append_part(sdk.RemoteSpeechPart{Text: text[:size], Characters: characters, Language: language}); err != nil {
return nil, err
}
text = text[size:]
}
default:
return nil, errProtocol
}
}
if len(current.Parts) != 0 {
result = append(result, current)
}
return result, nil
default:
return nil, errProtocol
}
}
// relay_speech serializes typed, policy-resolved output from the reader. The
// caller must check the event lease/epoch and relay membership at send time.
// No origin field is copied; only the relay assigns peer origins.
func relay_speech(value sdk.RemoteSpeech) ([]byte, error) {
if !sdk.ValidRemoteSpeech(value) {
return nil, errProtocol
}
switch value.Kind {
case "cancel":
return encodeMessage("cancel", map[string]any{})
case "pause":
return encodeMessage("pause_speech", map[string]any{"switch": *value.Paused})
case "speak":
sequence := []any{}
characters, language := false, ""
for _, part := range value.Parts {
if part.End {
sequence = append(sequence, []any{"EndUtteranceCommand", map[string]any{}})
continue
}
if characters != part.Characters {
characters = part.Characters
sequence = append(sequence, []any{"CharacterModeCommand", map[string]any{"state": characters}})
}
if language != part.Language {
language = part.Language
var lang any
if language != "" {
lang = language
}
sequence = append(sequence, []any{"LangChangeCommand", map[string]any{"lang": lang}})
}
sequence = append(sequence, part.Text)
}
return encodeMessage("speak", map[string]any{"sequence": sequence, "priority": value.Priority})
}
return nil, errProtocol
}
+115
View File
@@ -0,0 +1,115 @@
// SPDX-License-Identifier: GPL-3.0-or-later
package remote
import (
"bytes"
"encoding/json"
"reflect"
"strings"
"testing"
sdk "git.stormux.org/storm/cthulhu/sdk/go/tentacle"
)
func TestSpeechBridgeRoundTrip(t *testing.T) {
paused, resumed := true, false
cases := []sdk.RemoteSpeech{
{Kind: "cancel"},
{Kind: "pause", Paused: &paused},
{Kind: "pause", Paused: &resumed},
{Kind: "speak", Priority: 2, Parts: []sdk.RemoteSpeechPart{
{Text: " words\t世界 "},
{Text: "A", Characters: true, Language: "en_US"},
{Text: "B", Characters: true, Language: "en_US"},
{End: true},
{Text: " resets language and spelling "},
}},
}
for _, want := range cases {
frame, err := relay_speech(want)
if err != nil {
t.Fatal(err)
}
if bytes.Contains(frame, []byte(`"origin"`)) {
t.Fatal("forged relay origin")
}
message, err := decodeMessage(bytes.TrimSuffix(frame, []byte{'\n'}))
if err != nil {
t.Fatal(err)
}
got, err := reader_speech(message)
if err != nil || !reflect.DeepEqual(got, []sdk.RemoteSpeech{want}) {
t.Fatalf("round trip: %+v, %v; want %+v", got, err, want)
}
}
}
func TestSpeechBridgeSplitsEscapedUTF8WithoutLoss(t *testing.T) {
text := strings.Repeat(" \t<世界>\n\x00", 6000)
raw, err := encodeMessage("speak", map[string]any{"priority": 1, "sequence": []any{
[]any{"CharacterModeCommand", map[string]any{"state": true}},
[]any{"LangChangeCommand", map[string]any{"lang": "ja-JP"}},
text,
[]any{"EndUtteranceCommand", map[string]any{}},
}})
if err != nil {
t.Fatal(err)
}
message, err := decodeMessage(bytes.TrimSuffix(raw, []byte{'\n'}))
if err != nil {
t.Fatal(err)
}
frames, err := reader_speech(message)
if err != nil || len(frames) < 2 {
t.Fatal("did not split long speech", err)
}
var reconstructed strings.Builder
ends := 0
for index, frame := range frames {
if !sdk.ValidRemoteSpeech(frame) || frame.Priority != 1 {
t.Fatal("invalid split frame", index)
}
request, _ := json.Marshal(sdk.RemotePresentation{RemoteOperation: sdk.RemoteOperation{Lease: strings.Repeat("a", 32), Epoch: 1, Sequence: uint64(index + 1)}, Speech: frame})
if len(request) > 8192 {
t.Fatal("frame exceeds SDK call limit")
}
for _, part := range frame.Parts {
if part.End {
ends++
continue
}
if !part.Characters || part.Language != "ja-JP" {
t.Fatal("lost semantic state across split")
}
reconstructed.WriteString(part.Text)
}
}
if reconstructed.String() != text || ends != 1 {
t.Fatal("lost text/whitespace/utterance boundary")
}
}
func TestSpeechBridgeUnsupportedAndInvalidInput(t *testing.T) {
parsed, err := decodeMessage([]byte(`{"type":"speak","sequence":[" a ",["PitchCommand",{"offset":3}]," b "]}`))
if err != nil {
t.Fatal(err)
}
if parsed.payload.(speech).unsupported != 1 {
t.Fatal("lost unsupported command count")
}
frames, err := reader_speech(parsed)
if err != nil || len(frames) != 1 || len(frames[0].Parts) != 2 || frames[0].Parts[0].Text != " a " || frames[0].Parts[1].Text != " b " {
t.Fatal("flattened fragments", frames, err)
}
for _, value := range []message{
{kind: "key"}, {kind: "speak", payload: true}, {kind: "pause_speech", payload: "yes"},
} {
if _, err := reader_speech(value); err == nil {
t.Fatal("accepted invalid payload")
}
}
if _, err := relay_speech(sdk.RemoteSpeech{Kind: "wave"}); err == nil {
t.Fatal("accepted arbitrary output")
}
}
+3 -3
View File
@@ -13,10 +13,10 @@ import (
)
// certificateReview owns a single local review workflow. Its context must be
// the workflow lifetime, not a short command RPC. The future UI owner must cancel
// the workflow lifetime, not a short command RPC. The UI owner must cancel
// it on approval replacement, form closure, lock/handoff or process shutdown.
// A Submission is not proof of local input origin; these handlers must not be
// wired to production commands until the reader can establish that origin.
// A Submission is not proof of local input origin; the source command relies on
// the reader's local-only form capture rather than these library handlers.
type certificateReview struct {
mu sync.Mutex
lifetime context.Context
+7 -6
View File
@@ -1,7 +1,8 @@
# Remote settings and remembered credentials
The source library now includes Linux filesystem storage. It is not connected to
a command or connection UI yet. Opening, reading and writing this store performs
The source library includes Linux filesystem storage, now connected to the
[source command](command.md) through explicit settings, key and pin actions.
Opening, reading and writing this store performs
no network I/O and creates no session consent. Nothing auto-connects at startup.
`settings.toml` contains format version 1, plain-language role (`controller` or
@@ -9,7 +10,7 @@ no network I/O and creates no session consent. Nothing auto-connects at startup.
The pin repeats its host and port; a mismatch or invalid/zero digest is rejected.
Pin validation uses the same endpoint contract as the TLS transport. There is no
trust-on-first-use, changed-pin replacement, or certificate approval action in
this storage layer. A future local UI must obtain that decision explicitly.
this storage layer. The connection UI obtains that decision explicitly.
The schema contains no channel key, connection epoch, peer, lease, keyboard grant,
clipboard consent, reconnect switch or startup-connect switch. Unknown fields,
@@ -39,8 +40,8 @@ are rejected rather than changed automatically.
All files, including the cooperating-process lock, must be current-user regular
files with no group/other permissions and exactly one hard link. Symlinks, FIFOs,
devices and hard links are refused. File opens use nonblocking/no-follow flags so
an unexpected FIFO cannot hang the reader. Credential operations run on a future
session worker, not an input or native UI callback.
an unexpected FIFO cannot hang the reader. Credential operations run on the
external command worker, not an input or native UI callback.
Writers use an exclusive mode-0600 temporary file under the owned directory
descriptor, sync it, rename within the directory, and sync the directory. They
@@ -61,7 +62,7 @@ endpoint scoping, atomic inode replacement, permission modes, temporary-file
cleanup, explicit forgetting, host/port pin mismatch, unknown fields/versions,
malformed and oversized files, symlinked ancestors, file symlinks, hard links,
FIFOs, unsafe lock files, competing locks and secret-free errors. They do not
establish a completed Remember key UI or power-loss durability on every filesystem.
establish physical-input UI acceptance or power-loss durability on every filesystem.
```sh
GOCACHE=/tmp/cthulhu-cache GOPROXY=off go test -race ./remote/src -count=1 -timeout=60s
+29 -1
View File
@@ -8,6 +8,7 @@ import os
from pathlib import Path
import select
import subprocess
import tempfile
import tomllib
from urllib.parse import urlparse
@@ -153,6 +154,32 @@ def check_host(repoRoot, programPath, name):
}, "The actual host returned an unexpected greeting")
def check_remote(repoRoot):
programPath = repoRoot / "remote/bin/remote"
readerRoot = repoRoot.parent / "cthulhu"
environment = os.environ.copy()
environment["CTHULHU_REMOTE_BINARY"] = str(programPath)
with tempfile.TemporaryDirectory(prefix="cthulhu-remote-check-") as directory:
result = subprocess.run([
"go", "run", "./cmd/tentacle-host", "-presentation", "-interaction",
"-session-events", "-remote-grants", "output-observe,remote-present",
"-command", "remote", str(programPath), "--data-dir", str(Path(directory) / "state"),
], cwd=readerRoot, env=environment, capture_output=True, text=True,
timeout=60, check=True)
value = json.loads(result.stdout)
require(value.get("next") == "remote-select"
and "desktop services are unavailable" in value["form"]["title"],
"Remote did not disclose its relay-only scope")
subprocess.run([
"go", "test", "./internal/app", "-run", "^TestRemoteConnectionCommand",
"-count=1", "-timeout=90s",
], cwd=readerRoot, env=environment, timeout=120, check=True)
subprocess.run([
"go", "test", "./internal/tentacle", "./internal/tentaclewire",
"-run", "^TestRemoteSpeech", "-count=1", "-timeout=60s",
], cwd=readerRoot, env=environment, timeout=90, check=True)
def main():
repoRoot = Path(__file__).resolve().parents[1]
programPath = repoRoot / "hello-world/bin/hello-world"
@@ -162,7 +189,8 @@ def main():
programPath = repoRoot / name / "bin" / binary
check_registration(programPath, name)
check_host(repoRoot, programPath, name)
print("Repository metadata, shortcut/settings registration and actual-host greeting/menu/settings/battery checks passed.")
check_remote(repoRoot)
print("Repository metadata, existing Tentacle workflows and actual-host Remote consent/relay/speech IPC checks passed.")
if __name__ == "__main__":