More capabilities for tentacles, for an upcoming one

This commit is contained in:
lilmike committed 2026-11-23 08:25:36 -08:00
1 parent ffc5107112
commit a34d7e70c8
53 files changed
+2744 -131

No files matched your search

+105
View File
@@ -0,0 +1,105 @@
// Copyright (c) 2026 Storm Dragon
// SPDX-License-Identifier: GPL-3.0-or-later
package tentacle
import (
"context"
"encoding/json"
sdk "git.stormux.org/storm/cthulhu/sdk/go/tentacle"
"os"
"os/exec"
"path/filepath"
"testing"
)
func TestApplicationSDKPeer(t *testing.T) {
mode := os.Getenv("CTHULHU_PRIVATE_APPLICATION_PEER")
if mode == "" {
return
}
automatic := mode != "scope"
command := sdk.Command{ID: "probe", Title: "Application probe", Application: "Example App", Automation: automatic, Presentation: automatic, Interaction: automatic,
Handle: func(context.Context, json.RawMessage) (any, error) {
if !automatic {
return "scoped", nil
}
return sdk.Interaction{Automation: &sdk.Automation{Actions: []sdk.AutomationAction{{Kind: "move", X: 5000, Y: 5000}}}, Done: true}, nil
}}
client := sdk.NewSessionClient()
if err := sdk.ServeSession(os.Stdin, os.Stdout, []sdk.Command{command}, nil, client); err != nil {
os.Exit(1)
}
os.Exit(0)
}
func TestApplicationSDKHostConformance(t *testing.T) {
for _, language := range []string{"go", "python"} {
for _, mode := range []string{"scope", "automation", "denied"} {
t.Run(language+"/"+mode, func(t *testing.T) {
t.Setenv("CTHULHU_PRIVATE_APPLICATION_PEER", mode)
executable, err := os.Executable()
if err != nil {
t.Fatal(err)
}
program := []string{executable, "-test.run=^TestApplicationSDKPeer$"}
if language == "python" {
python, err := exec.LookPath("python3")
if err != nil {
t.Skip(err)
}
source, err := filepath.Abs("testdata/sdk_application_peer.py")
if err != nil {
t.Fatal(err)
}
program = []string{python, "-B", source}
}
manager := testManager(t, DefaultLimits(), nil)
spec := Spec{ID: "probe", Program: program, SessionEvents: true, ApplicationBindings: true}
if mode != "scope" {
spec.Presentation = true
spec.Interaction = true
spec.Automation = mode == "automation"
}
session, err := manager.Start(t.Context(), spec)
if err != nil {
t.Fatal(err)
}
waitSignal(t, session.Ready())
state, failure := session.Status()
if mode == "denied" {
if state != Failed {
t.Fatalf("ungranted extension became %s", state)
}
return
}
if state != Ready || failure != nil {
t.Fatalf("%s: %v", state, failure)
}
if err := session.Activate(); err != nil {
t.Fatal(err)
}
pending, err := session.Invoke(t.Context(), "probe", nil)
if err != nil {
t.Fatal(err)
}
result := waitResult(t, pending)
if result.Err != nil {
t.Fatal(result.Err)
}
if mode == "scope" {
if string(result.Value) != `"scoped"` {
t.Fatal(string(result.Value))
}
return
}
var value sdk.Interaction
if err := json.Unmarshal(result.Value, &value); err != nil {
t.Fatal(err)
}
if value.Automation == nil || len(value.Automation.Actions) != 1 {
t.Fatal(string(result.Value))
}
})
}
}
}
+99
View File
@@ -0,0 +1,99 @@
package tentacle
import (
"encoding/json"
"path/filepath"
"testing"
)
func TestApplicationCommandRegistration(t *testing.T) {
var registration Registration
raw := `{"protocol":{"major":1,"minor":1},"session":"test","commands":[{"id":"click","title":"Click","application":"ck3","presentation":true,"interaction":true,"bindings":[{"layout":"desktop","scope":"global","key":"Ctrl+D"}]}]}`
if err := decodeStrict([]byte(raw), &registration); err != nil {
t.Fatal(err)
}
if err := validateRegistrationVersion(registration, "test", Version{Major: 1, Minor: 1}); err != nil {
t.Fatal(err)
}
data, _ := json.Marshal(registration)
if string(data) == "" {
t.Fatal("empty registration")
}
for _, app := range []string{"ck3\n", string([]byte{0xff})} {
registration.Commands[0].Application = app
if validateRegistrationVersion(registration, "test", Version{Major: 1, Minor: 1}) == nil {
t.Errorf("accepted application %q", app)
}
}
}
func TestApplicationBindingStatusesUseApplicationScope(t *testing.T) {
manager, err := NewManager(DefaultLimits(), nil)
if err != nil {
t.Fatal(err)
}
commands := []Command{{ID: "center", Application: "ck3", Bindings: []Binding{{Layout: "desktop", Scope: "global", Key: "Shift+1"}}}}
statuses := resolveBindings("ck3", commands, manager.occupiedBindings(), manager.occupiedBindings(true))
if len(statuses) != 1 || !statuses[0].Bound {
t.Fatalf("browser default blocked application: %+v", statuses)
}
}
func TestApplicationAndAutomationGrantsAreIndependent(t *testing.T) {
scoped := Command{ID: "scoped", Title: "Scoped", Application: "example"}
spec := Spec{ID: "test", Program: []string{"/bin/true"}, SessionEvents: true, ApplicationBindings: true}
if err := validateCommandAccess(scoped, spec); err != nil {
t.Fatal(err)
}
command := scoped
command.Automation = true
command.Presentation = true
command.Interaction = true
spec.Presentation = true
spec.Interaction = true
if validateCommandAccess(command, spec) == nil {
t.Fatal("interaction grant authorized automation")
}
spec.Automation = true
if err := validateCommandAccess(command, spec); err != nil {
t.Fatal(err)
}
spec.SessionEvents = false
if validateSpec(spec) == nil {
t.Fatal("extensions allowed without negotiation")
}
}
func TestApplicationAutomationRegistryRoundTrip(t *testing.T) {
registry := &Registry{Path: filepath.Join(t.TempDir(), "tentacles.toml")}
if _, err := registry.Load(); err != nil {
t.Fatal(err)
}
entry := Entry{ID: "extension", Program: []string{"/bin/true"}, SessionEvents: true, ApplicationBindings: true, Automation: true, Presentation: true, Interaction: true}
if err := registry.Save([]Entry{entry}); err != nil {
t.Fatal(err)
}
loaded, err := (&Registry{Path: registry.Path}).Load()
if err != nil || len(loaded) != 1 {
t.Fatal(loaded, err)
}
if !loaded[0].Spec().Automation || !loaded[0].Spec().ApplicationBindings {
t.Fatal("extension opt-ins lost on restart")
}
}
func TestApplicationDeclarationRequiresNegotiation(t *testing.T) {
command := Command{ID: "probe", Title: "Scoped", Application: "Example App"}
spec := Spec{ID: "probe", Program: []string{"/bin/true"}, SessionEvents: true}
if validateCommandAccess(command, spec) == nil {
t.Fatal("undeclared application API accepted")
}
spec.ApplicationBindings = true
if err := validateCommandAccess(command, spec); err != nil {
t.Fatal(err)
}
spec.SessionEvents = false
if validateSpec(spec) == nil {
t.Fatal("application API accepted in legacy protocol")
}
}
+14 -3
View File
@@ -46,9 +46,13 @@ func (session *Session) Bindings() []BindingStatus {
// Caller holds manager.mutex, but no session lock. Revoked sessions immediately
// stop reserving chords even while their processes are still shutting down.
func (manager *Manager) occupiedBindings() map[input.KeyboardLayout]input.CommandBindings {
func (manager *Manager) occupiedBindings(application ...bool) map[input.KeyboardLayout]input.CommandBindings {
occupied := make(map[input.KeyboardLayout]input.CommandBindings)
for layout, bindings := range manager.coreBindings {
core := manager.coreBindings
if len(application) > 0 && application[0] {
core = manager.coreApplicationBindings
}
for layout, bindings := range core {
occupied[layout] = make(input.CommandBindings)
for chord, command := range bindings {
occupied[layout][chord] = command
@@ -69,18 +73,25 @@ func (manager *Manager) occupiedBindings() map[input.KeyboardLayout]input.Comman
return occupied
}
func resolveBindings(identity string, commands []Command, occupied map[input.KeyboardLayout]input.CommandBindings) []BindingStatus {
func resolveBindings(identity string, commands []Command, occupied map[input.KeyboardLayout]input.CommandBindings, applicationOccupied ...map[input.KeyboardLayout]input.CommandBindings) []BindingStatus {
var result []BindingStatus
for _, command := range commands {
commandID := "tentacle/" + identity + "/" + command.ID
for _, binding := range command.Bindings {
chord, _ := input.ParseCommandChord(binding.Key)
bindings := occupied[bindingLayout(binding.Layout)]
if command.Application != "" && len(applicationOccupied) > 0 {
bindings = applicationOccupied[0][bindingLayout(binding.Layout)]
}
previous := bindings[chord]
result = append(result, BindingStatus{Command: commandID, Suggested: binding,
Bound: previous == "", Conflict: string(previous)})
if previous == "" {
bindings[chord] = input.Command(commandID)
occupied[bindingLayout(binding.Layout)][chord] = input.Command(commandID)
if len(applicationOccupied) > 0 {
applicationOccupied[0][bindingLayout(binding.Layout)][chord] = input.Command(commandID)
}
}
}
}
+1 -1
View File
@@ -260,7 +260,7 @@ func preparePackage(ctx context.Context, root string, repository Repository, loc
remoteGrants = append(remoteGrants, grant)
}
}
prepared.Entry = Entry{SessionEvents: packageManifest.Protocol.Minor == 1, RemoteGrants: remoteGrants, ID: PackageID(repository, localID), LocalID: localID, Name: manifest.Name, Version: manifest.Version,
prepared.Entry = Entry{ApplicationBindings: slices.Contains(packageManifest.APIs, "application-bindings"), Automation: slices.Contains(packageManifest.Capabilities, "automation"), SessionEvents: packageManifest.Protocol.Minor == 1, RemoteGrants: remoteGrants, ID: PackageID(repository, localID), LocalID: localID, Name: manifest.Name, Version: manifest.Version,
Program: program, Directory: final, Presentation: presentation, Interaction: interactive, ReaderSettings: readerSettings, Repository: repository.URL, RepositoryID: repository.ID,
RepositoryRevision: repository.Revision, PackageDirectory: final, PackageSHA256: release.SHA256}
if err := ValidateEntries([]Entry{prepared.Entry}); err != nil {
+38
View File
@@ -500,3 +500,41 @@ func TestSessionPackageGrantsPersistAndRejectMismatch(t *testing.T) {
})
}
}
func TestApplicationAutomationPackagePermission(t *testing.T) {
binary, err := os.ReadFile("/bin/true")
if err != nil {
t.Fatal(err)
}
for _, granted := range []bool{false, true} {
t.Run(fmt.Sprint(granted), func(t *testing.T) {
capabilities := []string{"presentation", "interaction"}
text := "'presentation','interaction'"
if granted {
capabilities = append(capabilities, "automation")
text += ",'automation'"
}
manifest := strings.Replace(packageManifest(), "minor=0", "minor=1", 1)
manifest = strings.Replace(manifest, "apis=['commands','presentation']", "apis=['commands','session-events','presentation','interaction','application-bindings','automation']", 1)
manifest = strings.Replace(manifest, "capabilities=['presentation']", "capabilities=["+text+"]", 1)
data := packageArchive(t, []archiveMember{{name: "tentacle.toml", data: []byte(manifest), mode: 0644}, {name: "bin/echo", data: binary, mode: 0755}})
repository, client := packageFixture(t, data)
repository.Tentacles[0].Capabilities = capabilities
prepared, err := preparePackage(t.Context(), t.TempDir(), repository, "echo", client)
if !granted {
if err == nil {
prepared.Discard()
t.Fatal("automation installed without grant")
}
return
}
if err != nil {
t.Fatal(err)
}
defer prepared.Discard()
if !prepared.Entry.Spec().Automation || !prepared.Entry.Spec().ApplicationBindings {
t.Fatal("package grants not propagated")
}
})
}
}
+31 -23
View File
@@ -37,14 +37,16 @@ func DefaultLimits() Limits {
// Spec is a validated launch description, independent of package metadata.
// Program[0] must be absolute; arguments are never interpreted by a shell.
type Spec struct {
SessionEvents bool // Opt in to protocol 1.1 lifecycle calls and events.
RemoteGrants []string // Install grants only; do not authorize desktop access.
ID string
Program []string
Directory string
Presentation bool // Explicit local grant for command speech/braille results.
ReaderSettings bool // Declarative preferences, quick settings and speech overrides.
Interaction bool // Internal forms and explicit focused-item/clipboard exchanges.
ApplicationBindings bool // Opt-in application-scoped command declarations.
Automation bool // Explicit local mouse/OCR automation grant.
SessionEvents bool // Opt in to protocol 1.1 lifecycle calls and events.
RemoteGrants []string // Install grants only; do not authorize desktop access.
ID string
Program []string
Directory string
Presentation bool // Explicit local grant for command speech/braille results.
ReaderSettings bool // Declarative preferences, quick settings and speech overrides.
Interaction bool // Internal forms and explicit focused-item/clipboard exchanges.
}
type Stats struct {
@@ -54,20 +56,21 @@ type Stats struct {
}
type Manager struct {
logger *slog.Logger // Copied into sessions under mutex.
mutex sync.Mutex
limits Limits
sessions map[string]*Session
starting chan struct{}
pending chan struct{}
closed bool
coreBindings map[input.KeyboardLayout]input.CommandBindings
containment *containment
supervisorProgram []string
cleanupError error
remoteMutex sync.Mutex
remoteOwner *Session
remotePolicy *RemotePolicy // immutable after the first child is started
logger *slog.Logger // Copied into sessions under mutex.
mutex sync.Mutex
limits Limits
sessions map[string]*Session
starting chan struct{}
pending chan struct{}
closed bool
coreBindings map[input.KeyboardLayout]input.CommandBindings
coreApplicationBindings map[input.KeyboardLayout]input.CommandBindings
containment *containment
supervisorProgram []string
cleanupError error
remoteMutex sync.Mutex
remoteOwner *Session
remotePolicy *RemotePolicy // immutable after the first child is started
}
// NewSupervisedManager launches a private lifetime helper for each Tentacle.
@@ -106,14 +109,16 @@ func NewManager(limits Limits, overrides []input.BindingOverride) (*Manager, err
return nil, err
}
coreBindings := make(map[input.KeyboardLayout]input.CommandBindings)
coreApplicationBindings := make(map[input.KeyboardLayout]input.CommandBindings)
for _, layout := range []input.KeyboardLayout{input.DesktopKeyboardLayout, input.LaptopKeyboardLayout} {
bindings, err := input.ResolveCommandBindings(layout, true, overrides)
if err != nil {
return nil, err
}
coreBindings[layout] = bindings
coreApplicationBindings[layout] = input.ApplicationOccupiedBindings(layout, overrides)
}
return &Manager{limits: limits, sessions: make(map[string]*Session), coreBindings: coreBindings,
return &Manager{limits: limits, sessions: make(map[string]*Session), coreBindings: coreBindings, coreApplicationBindings: coreApplicationBindings,
starting: make(chan struct{}, limits.Starting), pending: make(chan struct{}, limits.PendingTotal)}, nil
}
@@ -209,6 +214,9 @@ func (manager *Manager) Shutdown(ctx context.Context) error {
}
func validateSpec(spec Spec) error {
if (spec.ApplicationBindings || spec.Automation) && !spec.SessionEvents || spec.Automation && (!spec.ApplicationBindings || !spec.Interaction) {
return errors.New("invalid application extension grants")
}
if !tentaclewire.ValidRemoteGrants(spec.RemoteGrants) || len(spec.RemoteGrants) > 0 && !spec.SessionEvents {
return errors.New("invalid remote grants")
}
+20 -1
View File
@@ -15,6 +15,12 @@ func (spec Spec) apis(legacy []string) []string {
if spec.SessionEvents {
apis = append(apis, "session-events")
}
if spec.ApplicationBindings {
apis = append(apis, "application-bindings")
}
if spec.Automation {
apis = append(apis, "automation")
}
if len(spec.RemoteGrants) > 0 {
apis = append(apis, "remote-access")
}
@@ -25,5 +31,18 @@ func (spec Spec) capabilities(legacy []string) []string {
if !spec.SessionEvents {
return legacy
}
return append(append([]string{}, legacy[1:]...), spec.RemoteGrants...)
grants := append(append([]string{}, legacy[1:]...), spec.RemoteGrants...)
if spec.Automation {
grants = append(grants, "automation")
}
return grants
}
func validateCommandAccess(command Command, spec Spec) error {
if command.Application != "" && (!spec.SessionEvents || !spec.ApplicationBindings) ||
command.Automation && !spec.Automation || command.Reader && !spec.ReaderSettings ||
command.Presentation && !spec.Presentation || command.Interaction && (!command.Presentation || !spec.Interaction) {
return ErrProtocol
}
return nil
}
+1 -1
View File
@@ -245,7 +245,7 @@ func (session *Session) run() {
return
}
for _, command := range registration.Commands {
if command.Reader && !session.spec.ReaderSettings || command.Presentation && !session.spec.Presentation || command.Interaction && (!command.Presentation || !session.spec.Interaction) {
if validateCommandAccess(command, session.spec) != nil {
session.fail(ErrProtocol)
return
}
+9 -1
View File
@@ -38,6 +38,8 @@ type Version struct {
}
type Command struct {
Application string `json:"application,omitempty"`
Automation bool `json:"automation,omitempty"`
ID string `json:"id"`
Title string `json:"title"`
Description string `json:"description"`
@@ -156,16 +158,22 @@ func validateRegistrationVersion(registration Registration, session string, vers
seen := make(map[string]bool)
settings := false
for _, command := range registration.Commands {
if command.Reader && !command.Interaction || command.Settings && (!command.Interaction || settings) || command.Interaction && !command.Presentation || !validId(command.ID) || seen[command.ID] || strings.TrimSpace(command.Title) == "" ||
if command.Application != "" && !tentaclewire.ValidApplication(command.Application) || command.Automation && (command.Application == "" || !command.Interaction) || command.Reader && !command.Interaction || command.Settings && (!command.Interaction || settings) || command.Interaction && !command.Presentation || !validId(command.ID) || seen[command.ID] || strings.TrimSpace(command.Title) == "" ||
len(command.Title) > 256 || len(command.Description) > 1024 {
return ErrProtocol
}
if command.Application != "" && version.Minor < 1 {
return ErrProtocol
}
seen[command.ID] = true
settings = settings || command.Settings
if len(command.Bindings) > 4 {
return ErrLimit
}
for _, binding := range command.Bindings {
if command.Application != "" && binding.Scope != "global" {
return ErrProtocol
}
if err := validateBinding(binding); err != nil {
return err
}
+20 -18
View File
@@ -18,27 +18,29 @@ import (
// Entry records an explicitly added local program or a verified package.
// Discovery never adds entries. Enablement is desired state; failures retain it.
type Entry struct {
SessionEvents bool `toml:"session-events,omitempty"`
RemoteGrants []string `toml:"remote-grants,omitempty"`
ID string `toml:"id"`
Program []string `toml:"program"`
Directory string `toml:"directory,omitempty"`
Enabled bool `toml:"enabled"`
Presentation bool `toml:"presentation"`
ReaderSettings bool `toml:"reader-settings,omitempty"`
Interaction bool `toml:"interaction,omitempty"`
Repository string `toml:"repository,omitempty"`
RepositoryID string `toml:"repository-id,omitempty"`
LocalID string `toml:"local-id,omitempty"`
Name string `toml:"name,omitempty"`
Version string `toml:"package-version,omitempty"`
PackageDirectory string `toml:"package-directory,omitempty"`
PackageSHA256 string `toml:"package-sha256,omitempty"`
RepositoryRevision string `toml:"repository-revision,omitempty"`
ApplicationBindings bool `toml:"application-bindings,omitempty"`
Automation bool `toml:"automation,omitempty"`
SessionEvents bool `toml:"session-events,omitempty"`
RemoteGrants []string `toml:"remote-grants,omitempty"`
ID string `toml:"id"`
Program []string `toml:"program"`
Directory string `toml:"directory,omitempty"`
Enabled bool `toml:"enabled"`
Presentation bool `toml:"presentation"`
ReaderSettings bool `toml:"reader-settings,omitempty"`
Interaction bool `toml:"interaction,omitempty"`
Repository string `toml:"repository,omitempty"`
RepositoryID string `toml:"repository-id,omitempty"`
LocalID string `toml:"local-id,omitempty"`
Name string `toml:"name,omitempty"`
Version string `toml:"package-version,omitempty"`
PackageDirectory string `toml:"package-directory,omitempty"`
PackageSHA256 string `toml:"package-sha256,omitempty"`
RepositoryRevision string `toml:"repository-revision,omitempty"`
}
func (entry Entry) Spec() Spec {
return Spec{SessionEvents: entry.SessionEvents, RemoteGrants: append([]string(nil), entry.RemoteGrants...), ID: entry.ID, Program: append([]string(nil), entry.Program...), Directory: entry.Directory, Presentation: entry.Presentation, Interaction: entry.Interaction, ReaderSettings: entry.ReaderSettings}
return Spec{ApplicationBindings: entry.ApplicationBindings, Automation: entry.Automation, SessionEvents: entry.SessionEvents, RemoteGrants: append([]string(nil), entry.RemoteGrants...), ID: entry.ID, Program: append([]string(nil), entry.Program...), Directory: entry.Directory, Presentation: entry.Presentation, Interaction: entry.Interaction, ReaderSettings: entry.ReaderSettings}
}
type registryDocument struct {
+2 -1
View File
@@ -126,6 +126,7 @@ func (session *Session) Activate() error {
session.manager.mutex.Lock()
defer session.manager.mutex.Unlock()
occupied := session.manager.occupiedBindings()
applicationOccupied := session.manager.occupiedBindings(true)
session.mutex.Lock()
defer session.mutex.Unlock()
if session.state != Ready || session.ctx.Err() != nil {
@@ -136,7 +137,7 @@ func (session *Session) Activate() error {
}{session.identity}) {
return ErrBusy
}
session.bindings = resolveBindings(session.spec.ID, session.commands, occupied)
session.bindings = resolveBindings(session.spec.ID, session.commands, occupied, applicationOccupied)
session.state = Active
session.log("tentacle activated")
return nil
+19
View File
@@ -0,0 +1,19 @@
# Copyright (c) 2026 Storm Dragon
# SPDX-License-Identifier: GPL-3.0-or-later
"""Private application-extension conformance peer. Never injects input."""
import os
from pathlib import Path
import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "sdk" / "python"))
from cthulhu_tentacle import Command, serve
from cthulhu_tentacle.session import SessionClient
automatic = os.environ["CTHULHU_PRIVATE_APPLICATION_PEER"] != "scope"
def handle(_cancelled, _arguments):
if not automatic:
return "scoped"
return {"automation": {"actions": [{"kind": "move", "x": 5000, "y": 5000}]}, "done": True}
serve([Command("probe", "Application probe", "Application probe", handle,
application="Example App", automation=automatic,
presentation=automatic, interaction=automatic)], session_client=SessionClient())