27 changed files with 2960 additions and 95 deletions

No files matched your search

+3
View File
@@ -3,3 +3,6 @@ __pycache__/
*.pyc
/dist/
/wormhole/bin/
/battery-status/bin/
+1 -1
View File
@@ -9,7 +9,7 @@ directly from a Tentacle.
Before publishing catalog entries, validate metadata and source, review grants,
and test the actual command through the host. Run `make check` for this repository.
For reader changes, also run relevant existing Cthulhu-Go tests. Xorg regressions
For reader changes, also run relevant existing Cthulhu tests. Xorg regressions
block a contribution. Verify keyboard bindings, learn mode, remapping, ordinary
reading, speech interruption, speech modes, lock/handoff and connected Braille
where affected. Automated results alone cannot prove accessibility acceptance.
+4 -1
View File
@@ -1,13 +1,16 @@
GOCACHE ?= /tmp/cthulhu-go-cache
GOCACHE ?= /tmp/cthulhu-cache
export GOCACHE
.PHONY: build check package
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
check: build
go vet ./...
go test ./...
python3 -B tools/check.py
package:
+383 -17
View File
@@ -1,20 +1,38 @@
# Cthulhu Tentacles
A repository of experimental Tentacles for Cthulhu-Go, maintained by Storm
Dragon. It currently contains one Tentacle: [Hello World](hello-world/README.md).
Repository material and Hello World are licensed under GPL-3.0-or-later; see
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).
Repository material and these Tentacles are licensed under GPL-3.0-or-later; see
[LICENSE](LICENSE) and [CONTRIBUTING.md](CONTRIBUTING.md).
`repository.toml` identifies this source. `catalog.toml` explicitly lists its
Tentacles, each in a direct top-level folder with its own `tentacle.toml`.
The catalog lists verified native packages for Linux amd64 and arm64. Prepared
release artifacts live in `dist/`; they become downloadable only after publication.
The catalog lists native packages for Linux amd64 and arm64. Hello World 0.1.0 is
available from the [release page](https://git.stormux.org/storm/cthulhu-tentacles/releases/tag/hello-world-v0.1.0).
Wormhole 0.1.2 requires the matching reader with interactive Tentacle settings support.
Native packages are available from the
[Wormhole release page](https://git.stormux.org/storm/cthulhu-tentacles/releases/tag/wormhole-v0.1.2).
Battery Status 0.1.0 packages are available from the
[Battery Status release page](https://git.stormux.org/storm/cthulhu-tentacles/releases/tag/battery-status-v0.1.0).
It uses Cthulhu+Shift+B and requires the UPower system service.
Local build artifacts live in the ignored `dist/` directory.
The discovery source URL is
`https://git.stormux.org/storm/cthulhu-tentacles`.
Tentacles are independent of the Git hosting service. Discovery reads TOML files
from an HTTPS Git repository; installation downloads the HTTPS URLs explicitly
listed in its catalog. Packages can live in pretty much any git provider,
on an HTTPS web server, or in object storage with stable public HTTPS
links. The reader does not call a hosting service's release API. Keeping packages
in separate downloads avoids putting binaries into Git history.
To write your own, follow the [creation and release tutorial](#create-and-release-your-own-tentacle).
## Build and check
Keep the matching experimental `cthulhu-go` checkout beside this directory.
Keep the matching experimental `cthulhu` checkout beside this directory.
The `go.mod` local replacement uses its Go SDK, including the new
uninterruptible presentation option. Building requires Go 1.24 or newer;
checks also require Python 3.11 or newer and Make.
@@ -24,24 +42,32 @@ make build
make check
```
The executable is `hello-world/bin/hello-world`, which is ignored by Git.
The executables are `hello-world/bin/hello-world`,
`wormhole/bin/wormhole-tentacle`, and `battery-status/bin/battery-status`;
all are ignored by Git.
Checks validate the TOML metadata, registration and suggested bindings, and
invoke Hello World through the actual Cthulhu-Go host. They produce no speech
invoke all three Tentacles through the actual Cthulhu host. They produce no speech
or Braille and leave the running reader alone.
## Repository installation
With the updated reader, open global Cthulhu Preferences → Tentacles → Add
repository and enter the HTTPS Git URL above. Refresh an already added source.
Select Hello World and press Space to review its source/version and requested
speech/Braille access, then **Install and enable**. **Install** instead downloads
Select Hello World or Wormhole and press Space to review its source/version and
requested access, then **Install and enable**. Wormhole requests internal forms
and focused-item/clipboard access as well as speech/Braille. **Install** instead downloads
and saves the package disabled. The reader verifies the catalog's SHA-256 digest,
package identity and native architecture before saving a launch entry. Catalogs
without a published compatible release show a clear message and remain unchecked.
No source builds or install scripts run during this workflow. Resource limits
do not make untrusted same-user programs safe.
After installation, refresh status until Active and use Cthulhu+Alt+Shift+H.
Install and enable reports success after the Tentacle becomes Active. A failed
start returns an error and leaves the installed package disabled. Enable it again
to retry. Activation needs no administrator setup or particular init system;
configured cgroup resource limits are optional.
For Hello World, use Cthulhu+Alt+Shift+H after activation.
Disable retains the package; re-enabling and reader startup use installed files
without network access. Removing the source retains installed Tentacles. Removing
a managed Tentacle stops it and deletes its package files after shutdown.
@@ -65,12 +91,12 @@ module metadata, trim paths and omit VCS stamping. To build one architecture:
python3 -B tools/package.py --architecture amd64
```
Validate the actual host-architecture package through Cthulhu-Go's installer
Validate the actual host-architecture package through Cthulhu's installer
and command host, without changing the running reader:
```sh
cd ../cthulhu-go
CTHULHU_TENTACLE_RELEASE_ROOT=../cthulhu-tentacles GOCACHE=/tmp/cthulhu-go-cache go test ./internal/tentacle -run '^TestBuiltHelloWorldPackageThroughHost$' -count=1 -v
cd ../cthulhu
CTHULHU_TENTACLE_RELEASE_ROOT=../cthulhu-tentacles GOCACHE=/tmp/cthulhu-cache go test ./internal/tentacle -run '^TestBuiltHelloWorldPackageThroughHost$' -count=1 -v
```
Before publication, review both repositories' changes and contributing guides.
@@ -86,6 +112,346 @@ changed content; bump the version before preparing a later release.
The package command creates local artifacts only. It does not create commits,
releases, tags, uploads or pushes. Prepared catalog changes are not evidence that
the corresponding release is already available. Live shortcut, speech, Braille,
lock/handoff and interruption checks remain necessary after publication and an
explicit reader restart. For source-only local testing, the development launch
procedure remains in [Hello World](hello-world/README.md#local-launch).
lock/handoff and interruption checks remain necessary after installation. An
explicit restart is needed when changing the reader itself. For source-only local
testing, the development launch procedure remains in
[Hello World](hello-world/README.md#local-launch).
## Create and release your own Tentacle
This tutorial creates a native Go Tentacle named **Greeting**, then makes it
installable from a repository. The SDK and package format are experimental;
use a matching Cthulhu checkout. Currently the installer supports native Linux
executables, protocol 1.0, command registration and optional presentation access.
Python SDK development is separate from this native package workflow. Broader
APIs and automatic package updates are still pending.
### 1. Set up the source repository
You need Go 1.24 or newer, Git, Python 3.11 or newer for this repository's checks,
GNU tar and gzip. Keep your new repository beside `cthulhu`. From their parent
directory:
```sh
mkdir -p greeting-tentacles/greeting/src
cd greeting-tentacles
git init -b main
```
Create these files:
```text
greeting-tentacles/
repository.toml
catalog.toml
go.mod
.gitignore
greeting/
tentacle.toml
README.md
LICENSE
src/main.go
```
Use this `go.mod`:
```go
module example.org/greeting-tentacles
go 1.24.0
require git.stormux.org/storm/cthulhu v0.0.0
replace git.stormux.org/storm/cthulhu => ../cthulhu
```
The SDK import path names its source project; it does not constrain where you
host your own repository or downloads. Record the tested reader/SDK revision in
release notes, since this local replacement does not pin it. Add `/dist/` and
`/greeting/bin/` to `.gitignore`.
Give `greeting/README.md` a description, shortcut, requirements and test procedure.
Put the full license text in `greeting/LICENSE`; choose terms you have permission
to distribute. For an example derived from Hello World, preserve its notices and
GPL-3.0-or-later license. Include source corresponding to your executable.
Create `repository.toml`:
```toml
format-version = 1
id = "example.greeting-tentacles"
name = "Greeting Tentacles"
description = "A small example Tentacle repository."
```
Create the initial `catalog.toml`:
```toml
format-version = 1
[[tentacles]]
id = "greeting"
manifest = "greeting/tentacle.toml"
```
Manifests belong in direct top-level folders. Repository and Tentacle IDs start
with a lowercase letter and contain only lowercase letters, digits, dots and
hyphens, up to 128 characters. Keep IDs stable: the reader uses the source URL,
repository ID and Tentacle ID to identify an installation. A catalog can list
several Tentacles, each with its own manifest and releases. Entries without
releases can be discovered, but cannot yet be installed.
### 2. Describe the package and permissions
Create `greeting/tentacle.toml`, replacing the example source URL with your own
HTTPS Git URL before publication:
```toml
format-version = 1
id = "greeting"
name = "Greeting"
description = "Speak and braille a short greeting."
version = "0.1.0"
authors = ["Contributor"]
license = "GPL-3.0-or-later"
source = "https://example.org/projects/greeting-tentacles.git"
help = "README.md"
runtime = "native"
platforms = ["linux"]
entry-point = ["bin/greeting"]
apis = ["commands", "presentation"]
capabilities = ["presentation"]
[protocol]
major = 1
minor = 0
```
Paths refer to the archive's root, not the source repository's root. The entry
point is an executable followed by optional literal arguments, not a shell
command. Presentation access allows speech and Braille results through the
reader. A command-only package uses `apis = ["commands"]` and
`capabilities = []`, without requesting presentation in command registration.
Other package API or capability combinations are currently unsupported.
### 3. Implement a command
Create `greeting/src/main.go`:
```go
package main
import (
"context"
"encoding/json"
"os"
"git.stormux.org/storm/cthulhu/sdk/go/tentacle"
)
func say_greeting(ctx context.Context, _ json.RawMessage) (any, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
return tentacle.Presentation{
Speech: "Hello from Greeting!",
Braille: "Hello from Greeting!",
}, nil
}
func main() {
command := tentacle.Command{
ID: "greet", Title: "Greeting",
Description: "Speak and braille a greeting", Presentation: true,
Bindings: []tentacle.Binding{
{Layout: "desktop", Scope: "global", Key: "Cthulhu+Ctrl+Alt+F10"},
{Layout: "laptop", Scope: "global", Key: "Cthulhu+Ctrl+Alt+F10"},
},
Handle: say_greeting,
}
if tentacle.Serve(os.Stdin, os.Stdout, []tentacle.Command{command}) != nil {
os.Exit(1)
}
}
```
The SDK handles the JSON-RPC session and registration. Stdout belongs exclusively
to that protocol; send limited diagnostics to stderr. Respect the supplied
context when doing work, including network requests. The reader owns input,
speech, Braille, user settings and lifecycle safeguards. Use its public SDK
instead of reader internals or output backends. Core and user bindings take
precedence over suggested shortcuts; users can remap Tentacle commands.
Greeting uses ordinary interruptible presentation. Hello World demonstrates
`Uninterruptible: true`; use that deliberately, rather than for every message.
See its [output behavior](hello-world/README.md) for cancellation, the 30-second
protection bound and speech backend limitations.
### 4. Build and test before packaging
From `greeting-tentacles`:
```sh
gofmt -w greeting/src/main.go
mkdir -p greeting/bin
CGO_ENABLED=0 GOCACHE=/tmp/cthulhu-cache go build -buildvcs=false -mod=readonly -trimpath -o greeting/bin/greeting ./greeting/src
GOCACHE=/tmp/cthulhu-cache go test ./...
```
Invoke the compiled command through the development host. From `cthulhu`:
```sh
GOCACHE=/tmp/cthulhu-cache go run ./cmd/tentacle-host -presentation -command greet "$PWD/../greeting-tentacles/greeting/bin/greeting"
```
Expect JSON containing `speech` and `braille`, both `Hello from Greeting!`.
This runs the executable through the actual command host, but produces no speech
or Braille. The harness's default mode has no resource containment; use it only
with development code you trust. Protocol tests do not establish live behavior.
For a live test, follow [Hello World's development launch procedure](hello-world/README.md#local-launch),
substituting your absolute executable path and launch ID `greeting`, with
`Presentation: true` in the launch JSON. `--replace --tentacles` replaces the
current Go reader and selects the development list instead of the saved registry;
run it explicitly when ready. Rebuild the reader first if its implementation
changed. Production activation uses init-independent process supervision and
needs no administrator setup. Kernel resource limits are optional: configure a
delegated cgroup v2 parent with `--tentacle-cgroup-parent` or
`CTHULHU_TENTACLE_CGROUP_PARENT`. An invalid explicit parent fails startup.
Test the shortcut, learn mode, remapping, ordinary reading and web navigation on
Xorg. Verify speech modes, interruption, screen lock, terminal handoff, disable
and connected Braille where affected. See [CONTRIBUTING.md](CONTRIBUTING.md) for
review and regression requirements; contributors remain responsible for reviewing
and testing AI-assisted changes.
### 5. Create architecture-specific archives
The `make build`, `make check` and `tools/package.py` commands in **this**
repository build/check Hello World, Wormhole, and Battery Status. `tools/package.py --tentacle wormhole`
packages Wormhole; `--tentacle battery-status` packages Battery Status.
The default still packages Hello World. The checker pins the
current versions and expected Tentacles. Adapt those tools and checks when
extending this repository, or use
this standalone procedure for Greeting.
From `greeting-tentacles`, stage the root manifest, documentation and license:
```sh
mkdir -p dist/greeting-package/bin
cp greeting/tentacle.toml greeting/README.md greeting/LICENSE dist/greeting-package/
```
Run the following in Bash for version `0.1.0`. Change the version together with
the manifest on later releases. `set -euo pipefail` stops on build/archive failures.
```bash
set -euo pipefail
version=0.1.0
for architecture in amd64 arm64; do
CGO_ENABLED=0 GOOS=linux GOARCH="$architecture" GOCACHE=/tmp/cthulhu-cache \
go build -buildvcs=false -mod=readonly -trimpath -ldflags='-s -w' \
-o dist/greeting-package/bin/greeting ./greeting/src
tar --sort=name --mtime=@0 --owner=0 --group=0 --numeric-owner \
-C dist/greeting-package -cf - tentacle.toml README.md LICENSE bin \
| gzip -n > "dist/greeting-$version-linux-$architecture.tar.gz"
done
sha256sum "dist/greeting-$version-linux-amd64.tar.gz" \
"dist/greeting-$version-linux-arm64.tar.gz" \
| sed 's@ dist/@ @' > dist/SHA256SUMS
```
Each archive must have this layout, without an enclosing `greeting/` folder:
```text
tentacle.toml
README.md
LICENSE
bin/greeting
```
The executable must be a regular, executable Linux ELF file for the advertised
architecture. Static Go builds avoid undeclared shared-library dependencies.
The reader rejects unsafe paths, symbolic/hard links and special files. Current
limits are 32 MiB per compressed download, 64 MiB expanded file data and 1,024
archive entries. Installation runs no install scripts or source builds. Package
ID, name, version and capabilities must match the repository manifest.
Inspect each archive with `tar -tzf`; from `dist`, run `sha256sum -c SHA256SUMS`.
Run each extracted executable through the host on its matching architecture;
a cross-build alone is not an execution test. The staging executable above ends
with the last architecture built, so use the appropriate extracted archive for
your local test. Keep the exact archives for publication. Normalized tar/gzip
metadata supports repeatable packaging; compare hashes when rebuilding with the
same source and toolchain.
### 6. Publish downloads, then advertise them
Review the source diff and tests before committing. Push reviewed source to your
chosen Git host. For later versions, use a release branch while preparing assets
so the default branch's existing manifest and catalog remain consistent. Create
a release/tag such as `greeting-v0.1.0` targeting that source commit. If using a
separate download server, record that source revision alongside the files.
Upload both `.tar.gz` files and `SHA256SUMS`, and make the release public when the
assets are ready. Keep `dist/` and executables out of Git.
Use stable direct HTTPS download URLs. Release attachments are convenient but
optional; an ordinary HTTPS file server works too. URLs cannot embed credentials
or fragments, and redirects must remain HTTPS. The reader has no authenticated
private-download workflow; expiring signed URLs are unsuitable for a durable
catalog.
Download the published files again and check `sha256sum -c SHA256SUMS` against
those downloads. Check the archive manifest and executable. Only then append
these tables after Greeting's entry in `catalog.toml`:
```toml
[[tentacles.releases]]
platform = "linux"
architecture = "amd64"
url = "https://downloads.example.org/greeting/0.1.0/greeting-0.1.0-linux-amd64.tar.gz"
sha256 = "REPLACE_WITH_THE_AMD64_ARCHIVE_SHA256"
[[tentacles.releases]]
platform = "linux"
architecture = "arm64"
url = "https://downloads.example.org/greeting/0.1.0/greeting-0.1.0-linux-arm64.tar.gz"
sha256 = "REPLACE_WITH_THE_ARM64_ARCHIVE_SHA256"
```
Replace the URLs and placeholders with published URLs and their actual
64-character lowercase hexadecimal hashes. These tables belong to the preceding
`[[tentacles]]`; each platform/architecture pair may appear once. Keep the
manifest version equal to the version inside the packages. Include only
architectures you actually publish. For several Tentacles, preserve the existing
entries: this repository's generated `dist/catalog.toml` preserves catalog entries and prepares
release metadata for the selected Tentacles. Review it before publication.
Review and push the matching catalog and manifest together to the repository's
default branch, which discovery fetches. Never replace a release file with changed
content: increase the version, create new archives and URLs, then publish a new
catalog revision. Refresh updates available metadata, not installed packages.
To test a newer version with the current reader, remove that managed Tentacle
and install it again after refreshing the source.
### 7. Verify the published installation
Open global Preferences → Tentacles → Add repository in the matching reader and
enter your HTTPS Git URL, or refresh an existing source. Select Greeting and
press Space. Check source, version and presentation access in the first-use
dialog, then choose **Install and enable**. Confirm status becomes Active and
test Cthulhu+Ctrl+Alt+F10 and the live checks from step 4.
Also check **Install** without enabling, enable/disable, offline reader restart
and removal. Disabled packages retain their files; installed packages launch
offline. Removing a source retains installed packages; removing a managed
Tentacle stops it and deletes its package files. Keep ordinary reader commands,
keyboard navigation and speech/Braille preferences working.
For no compatible release, check architecture and refresh the source. For
download/checksum errors, verify the exact public URL and digest. For package
metadata errors, compare the archive manifest with the repository manifest. For
activation failures, check the reader log for protocol, executable or cgroup
errors. Resource limits constrain consumption; they do not sandbox access to
account files or network. Install publishers you trust and state any remaining
unverified live behavior in release notes.
+232
View File
@@ -0,0 +1,232 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for software and other kinds of works.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
“This License” refers to version 3 of the GNU General Public License.
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
A “covered work” means either the unmodified Program or a work based on the Program.
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <https://www.gnu.org/philosophy/why-not-lgpl.html>.
+64
View File
@@ -0,0 +1,64 @@
# Battery Status
Press **Cthulhu+Shift+B** in either keyboard layout to report battery status.
With one battery, hear and read a short message such as
“Laptop battery, discharging, 90 percent.” With several batteries, an internal
**Battery Menu** lists each device with its status and charge. Use Up and Down
to browse; Enter and Escape both close without additional output. The shortcut
is a suggestion and can be remapped in Cthulhu.
Battery Status reads the UPower service over the system D-Bus. It does not run
the `upower` command, require root, or change power settings. Install and enable
your distribution's UPower service if it is missing. An unavailable service
produces “Battery information unavailable.” A successful read with no batteries
produces “No batteries detected.” If some devices cannot be read, readable
results are accompanied by “Some battery information is unavailable.”
The kernel, drivers, and hardware determine which laptop, controller, headset,
mouse, UPS, and other batteries UPower can expose. Device model names may be
generic. Unknown charge is reported explicitly; unknown charging state is
omitted. Devices with only coarse levels use words such as “low” or “normal”
rather than an artificial percentage. Precise percentages are rounded to whole
numbers. System batteries appear first; duplicate names have numbered suffixes.
UPower's combined DisplayDevice and AC adapters are excluded.
Each invocation reads UPower's latest reported values, with a one-second read
limit to fit Cthulhu's two-second command deadline. An open menu is a snapshot:
close and invoke again to refresh. There are
no background notifications, time estimates, hardware-statistics views, or
sysfs fallbacks. UPower may itself cache values between device updates.
See the [UPower device API](https://upower.freedesktop.org/docs/Device.html).
## Build and verify
From the repository root, run `make check`. Build release artifacts with
`python3 -B tools/package.py --tentacle battery-status`. This prepares amd64 and
arm64 packages and a proposed catalog under `dist/`; it publishes nothing.
The source catalog intentionally advertises no release downloads yet.
For an actual-host diagnostic without speech or changes to the running reader,
run from the adjacent `cthulhu` checkout:
```sh
GOCACHE=/tmp/cthulhu-cache go run ./cmd/tentacle-host -presentation -interaction -command battery-status "$PWD/../cthulhu-tentacles/battery-status/bin/battery-status"
```
Use the development launch procedure in Hello World's README for live testing,
with launch ID `battery-status`, the matching executable, and both Presentation
and Interaction grants. Review and test before submission, as required by
CONTRIBUTING.md. Verify:
- The shortcut, learn-mode description, and remapping in both layouts.
- A single battery speaks and brailles its status without a menu.
- With another battery-bearing device connected, the Battery Menu opens,
Up/Down reads each row, and Enter and Escape dismiss it silently.
- Reopening reflects updated devices and charge; no combined duplicate appears.
- Speech preferences and interruption, connected Braille, screen lock/handoff,
disable/re-enable, and normal reading after closing the menu still work.
Automated tests use injected device sources for absent/unavailable services,
partial failures, and battery combinations, without altering the system service.
Cross-building arm64 does not establish execution on arm64; test that package
on matching hardware before publication.
Licensed GPL-3.0-or-later; see LICENSE.
+126
View File
@@ -0,0 +1,126 @@
// Copyright (c) 2026 Storm Dragon
// SPDX-License-Identifier: GPL-3.0-or-later
package main
import (
"fmt"
"math"
"sort"
"strings"
"unicode"
"git.stormux.org/storm/cthulhu/sdk/go/tentacle"
"github.com/godbus/dbus/v5"
)
type battery struct {
id, name, state, charge string
system bool
}
// UPower device kinds, indexed by their public D-Bus enum values.
var deviceNames = []string{
"Device", "AC adapter", "Battery", "UPS", "Monitor", "Mouse", "Keyboard",
"PDA", "Phone", "Media player", "Tablet", "Computer", "Game controller",
"Pen", "Touchpad", "Modem", "Network device", "Headset", "Speakers",
"Headphones", "Video device", "Audio device", "Remote control", "Printer",
"Scanner", "Camera", "Wearable", "Toy", "Bluetooth device",
}
func cleanName(name string) string {
name = strings.Map(func(r rune) rune {
if unicode.IsControl(r) {
return ' '
}
return r
}, strings.ToValidUTF8(name, ""))
name = strings.Join(strings.Fields(name), " ")
// Device-provided names must fit the host's form and output limits.
chars := []rune(name)
if len(chars) > 160 {
name = string(chars[:160])
}
return name
}
func decodeBattery(id string, properties map[string]dbus.Variant) (battery, bool) {
kind, _ := properties["Type"].Value().(uint32)
present, _ := properties["IsPresent"].Value().(bool)
if !present || kind == 1 || id == "/org/freedesktop/UPower/devices/DisplayDevice" {
return battery{}, false
}
powerSupply, _ := properties["PowerSupply"].Value().(bool)
model, _ := properties["Model"].Value().(string)
name := cleanName(model)
system := kind == 2 && powerSupply
if system {
name = "Laptop battery"
} else {
if name == "" {
name = "Device"
if int(kind) < len(deviceNames) {
name = deviceNames[kind]
}
}
if !strings.HasSuffix(strings.ToLower(name), "battery") {
name += " battery"
}
}
state, _ := properties["State"].Value().(uint32)
states := []string{"", "charging", "discharging", "empty", "fully charged", "pending charge", "pending discharge"}
stateText := ""
if int(state) < len(states) {
stateText = states[state]
}
charge := "charge unknown"
level, hasLevel := properties["BatteryLevel"].Value().(uint32)
if text, ok := map[uint32]string{3: "low", 4: "critical", 6: "normal", 7: "high", 8: "full"}[level]; ok {
charge = text
} else if !hasLevel || level == 1 {
percentage, ok := properties["Percentage"].Value().(float64)
if ok && !math.IsNaN(percentage) && !math.IsInf(percentage, 0) && percentage >= 0 && percentage <= 100 {
charge = fmt.Sprintf("%.0f percent", math.Round(percentage))
}
}
return battery{id: id, name: name, state: stateText, charge: charge, system: system}, true
}
func batteryItems(batteries []battery) []tentacle.ListItem {
// Own the slice so concurrent invocations cannot reorder shared source data.
batteries = append([]battery(nil), batteries...)
sort.Slice(batteries, func(i, j int) bool {
a, b := batteries[i], batteries[j]
if a.system != b.system {
return a.system
}
if strings.ToLower(a.name) != strings.ToLower(b.name) {
return strings.ToLower(a.name) < strings.ToLower(b.name)
}
return a.id < b.id
})
totals, counts := map[string]int{}, map[string]int{}
for _, b := range batteries {
totals[strings.ToLower(b.name)]++
}
items := make([]tentacle.ListItem, 0, len(batteries))
seen := map[string]bool{}
for _, b := range batteries {
if seen[b.id] {
continue
}
seen[b.id] = true
key := strings.ToLower(b.name)
counts[key]++
name := b.name
if totals[key] > 1 {
name += fmt.Sprintf(" %d", counts[key])
}
parts := []string{name}
if b.state != "" {
parts = append(parts, b.state)
}
parts = append(parts, b.charge)
items = append(items, tentacle.ListItem{ID: b.id, Label: strings.Join(parts, ", ")})
}
return items
}
+243
View File
@@ -0,0 +1,243 @@
// Copyright (c) 2026 Storm Dragon
// SPDX-License-Identifier: GPL-3.0-or-later
package main
import (
"context"
"encoding/json"
"errors"
"math"
"reflect"
"strings"
"testing"
"time"
"git.stormux.org/storm/cthulhu/sdk/go/tentacle"
"github.com/godbus/dbus/v5"
)
func properties(kind uint32, model string) map[string]dbus.Variant {
return map[string]dbus.Variant{
"Type": dbus.MakeVariant(kind), "IsPresent": dbus.MakeVariant(true),
"PowerSupply": dbus.MakeVariant(kind == 2), "Model": dbus.MakeVariant(model),
"State": dbus.MakeVariant(uint32(2)), "BatteryLevel": dbus.MakeVariant(uint32(1)),
"Percentage": dbus.MakeVariant(float64(90)),
}
}
func TestChargeReporting(t *testing.T) {
for _, test := range []struct {
name string
level any
percentage any
want string
}{
{"precise", uint32(1), 85.5, "86 percent"},
{"zero", uint32(1), float64(0), "0 percent"},
{"full", uint32(1), float64(100), "100 percent"},
{"older service", nil, float64(90), "90 percent"},
{"unknown level", uint32(0), float64(50), "charge unknown"},
{"low", uint32(3), float64(10), "low"},
{"critical", uint32(4), float64(5), "critical"},
{"normal", uint32(6), float64(55), "normal"},
{"high", uint32(7), float64(70), "high"},
{"coarse full", uint32(8), float64(100), "full"},
{"future level", uint32(99), float64(50), "charge unknown"},
{"missing", uint32(1), nil, "charge unknown"},
{"wrong type", uint32(1), "90", "charge unknown"},
{"negative", uint32(1), float64(-1), "charge unknown"},
{"over full", uint32(1), 100.1, "charge unknown"},
{"nan", uint32(1), math.NaN(), "charge unknown"},
{"infinity", uint32(1), math.Inf(1), "charge unknown"},
} {
t.Run(test.name, func(t *testing.T) {
p := properties(2, "Primary")
delete(p, "BatteryLevel")
delete(p, "Percentage")
if test.level != nil {
p["BatteryLevel"] = dbus.MakeVariant(test.level)
}
if test.percentage != nil {
p["Percentage"] = dbus.MakeVariant(test.percentage)
}
b, ok := decodeBattery("/battery", p)
if !ok || b.charge != test.want {
t.Fatalf("got %+v, included %v; want %s", b, ok, test.want)
}
})
}
}
func TestNamesStatesAndFiltering(t *testing.T) {
for _, test := range []struct {
kind uint32
model, want string
}{
{2, "Primary", "Laptop battery"}, {12, "Playstation 4 controller", "Playstation 4 controller battery"},
{12, "", "Game controller battery"}, {3, "", "UPS battery"}, {17, "", "Headset battery"},
{99, "", "Device battery"}, {5, "Mouse Battery", "Mouse Battery"}, {6, " A\nB\x00 ", "A B battery"},
} {
b, ok := decodeBattery("/device", properties(test.kind, test.model))
if !ok || b.name != test.want {
t.Fatalf("got %+v; want %s", b, test.want)
}
}
for state, want := range []string{"", "charging", "discharging", "empty", "fully charged", "pending charge", "pending discharge", ""} {
p := properties(2, "")
p["State"] = dbus.MakeVariant(uint32(state))
b, _ := decodeBattery("/battery", p)
if b.state != want {
t.Fatalf("state %d: got %s, want %s", state, b.state, want)
}
}
p := properties(2, "")
p["PowerSupply"] = dbus.MakeVariant(false)
b, _ := decodeBattery("/battery", p)
if b.name != "Battery" || b.system {
t.Fatalf("peripheral classified as laptop: %+v", b)
}
p["IsPresent"] = dbus.MakeVariant(false)
if _, ok := decodeBattery("/battery", p); ok {
t.Fatal("absent battery included")
}
if _, ok := decodeBattery("/adapter", properties(1, "")); ok {
t.Fatal("AC adapter included")
}
if _, ok := decodeBattery("/org/freedesktop/UPower/devices/DisplayDevice", properties(2, "")); ok {
t.Fatal("synthetic device included")
}
if name := cleanName(strings.Repeat("猫", 200)); len([]rune(name)) != 160 {
t.Fatal("long name not bounded")
}
}
func TestOrderingAndDuplicateNames(t *testing.T) {
batteries := []battery{
{id: "/z", name: "Mouse battery", charge: "low"},
{id: "/bat1", name: "Laptop battery", system: true, charge: "90 percent"},
{id: "/a", name: "Mouse battery", charge: "normal"},
{id: "/bat0", name: "Laptop battery", system: true, charge: "80 percent"},
}
want := []tentacle.ListItem{
{ID: "/bat0", Label: "Laptop battery 1, 80 percent"},
{ID: "/bat1", Label: "Laptop battery 2, 90 percent"},
{ID: "/a", Label: "Mouse battery 1, normal"},
{ID: "/z", Label: "Mouse battery 2, low"},
}
if got := batteryItems(batteries); !reflect.DeepEqual(got, want) {
t.Fatalf("got %+v", got)
}
if batteries[0].id != "/z" {
t.Fatal("modified source data")
}
}
type fakeDevices struct {
paths []dbus.ObjectPath
values map[dbus.ObjectPath]map[string]dbus.Variant
err error
reads int
}
func (f *fakeDevices) devices(ctx context.Context) ([]dbus.ObjectPath, error) { return f.paths, f.err }
func (f *fakeDevices) properties(ctx context.Context, p dbus.ObjectPath) (map[string]dbus.Variant, error) {
f.reads++
v, ok := f.values[p]
if !ok {
return nil, errors.New("disconnected")
}
return v, nil
}
func TestEnumeration(t *testing.T) {
f := &fakeDevices{paths: []dbus.ObjectPath{"/bat", "/bat", "/ac", "/absent", "/org/freedesktop/UPower/devices/DisplayDevice"}, values: map[dbus.ObjectPath]map[string]dbus.Variant{
"/bat": properties(2, ""), "/ac": properties(1, ""), "/absent": properties(2, ""),
}}
f.values["/absent"]["IsPresent"] = dbus.MakeVariant(false)
b, partial, err := readDevices(context.Background(), f)
if err != nil || partial || len(b) != 1 || f.reads != 3 {
t.Fatalf("got %+v, %v, %v; reads %d", b, partial, err, f.reads)
}
f.paths = append(f.paths, "/gone", "/malformed")
f.values["/malformed"] = map[string]dbus.Variant{}
b, partial, err = readDevices(context.Background(), f)
if err != nil || !partial || len(b) != 1 {
t.Fatalf("partial read: %+v, %v, %v", b, partial, err)
}
f.err = errors.New("service unavailable")
if _, _, err := readDevices(context.Background(), f); err == nil {
t.Fatal("lost service failure")
}
f.err = nil
ctx, cancel := context.WithCancel(context.Background())
cancel()
f.reads = 0
_, partial, _ = readDevices(ctx, f)
if !partial || f.reads != 0 {
t.Fatal("read after cancellation")
}
}
func TestInvocationAndCompletion(t *testing.T) {
laptop, _ := decodeBattery("/bat", properties(2, ""))
controller, _ := decodeBattery("/controller", properties(12, "Playstation 4 controller"))
for _, test := range []struct {
name string
batteries []battery
partial bool
err error
speech string
menu bool
}{
{name: "none", speech: "No batteries detected."},
{name: "single", batteries: []battery{laptop}, speech: "Laptop battery, discharging, 90 percent."},
{name: "multiple", batteries: []battery{controller, laptop}, menu: true},
{name: "service missing", err: errors.New("missing"), speech: "Battery information unavailable."},
{name: "all unreadable", partial: true, speech: "Battery information unavailable."},
{name: "partial single", batteries: []battery{laptop}, partial: true, speech: "Laptop battery, discharging, 90 percent. Some battery information is unavailable."},
{name: "partial menu", batteries: []battery{controller, laptop}, partial: true, menu: true, speech: "Some battery information is unavailable."},
} {
t.Run(test.name, func(t *testing.T) {
h := openBatteries(func(ctx context.Context) ([]battery, bool, error) {
deadline, ok := ctx.Deadline()
if !ok || time.Until(deadline) > readTimeout {
t.Fatal("missing read deadline")
}
return test.batteries, test.partial, test.err
})
value, err := h(context.Background(), nil)
if err != nil {
t.Fatal(err)
}
v := value.(tentacle.Interaction)
if v.Speech != test.speech || v.Braille != test.speech || (v.Form != nil) != test.menu {
t.Fatalf("got %+v", v)
}
if test.menu {
if v.Form.Title != "Battery Menu" || v.Next != "close-menu" || len(v.Form.Elements[0].Items) != 2 || v.Done {
t.Fatalf("bad menu: %+v", v)
}
} else if !v.Done {
t.Fatal("message did not complete")
}
})
}
for _, submission := range []string{`{"activated":"/bat"}`, `{"cancelled":true}`} {
value, err := closeMenu(context.Background(), json.RawMessage(submission))
if err != nil || value != (tentacle.Interaction{Done: true}) {
t.Fatalf("completion: %+v, %v", value, err)
}
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
called := false
h := openBatteries(func(context.Context) ([]battery, bool, error) { called = true; return nil, false, nil })
if _, err := h(ctx, nil); !errors.Is(err, context.Canceled) || called {
t.Fatal("ignored cancellation")
}
ctx, cancel = context.WithCancel(context.Background())
h = openBatteries(func(context.Context) ([]battery, bool, error) { cancel(); return []battery{laptop}, false, nil })
if _, err := h(ctx, nil); !errors.Is(err, context.Canceled) {
t.Fatal("presented after cancellation")
}
}
+111
View File
@@ -0,0 +1,111 @@
// Copyright (c) 2026 Storm Dragon
// SPDX-License-Identifier: GPL-3.0-or-later
package main
import (
"context"
"encoding/json"
"errors"
"os"
"os/exec"
"path/filepath"
"testing"
"time"
"git.stormux.org/storm/cthulhu/sdk/go/tentacle"
)
// Only the test executable accepts fixture arguments; production has no test mode.
func TestBatteryHostChild(t *testing.T) {
if len(os.Args) < 3 || os.Args[len(os.Args)-2] != "battery-host-child" {
return
}
fixture := os.Args[len(os.Args)-1]
source := func(ctx context.Context) ([]battery, bool, error) {
laptop, _ := decodeBattery("/bat", properties(2, ""))
controller, _ := decodeBattery("/controller", properties(12, "Playstation 4 controller"))
switch fixture {
case "none":
return nil, false, nil
case "single":
return []battery{laptop}, false, nil
case "multiple":
return []battery{controller, laptop}, false, nil
case "partial":
return []battery{controller, laptop}, true, nil
case "slow":
<-ctx.Done()
return nil, false, ctx.Err()
default:
return nil, false, errors.New("UPower unavailable")
}
}
if tentacle.Serve(os.Stdin, os.Stdout, commands(source)) != nil {
os.Exit(1)
}
os.Exit(0)
}
func TestBatteryThroughActualHost(t *testing.T) {
reader, err := filepath.Abs("../../../cthulhu")
if err != nil {
t.Fatal(err)
}
host := filepath.Join(t.TempDir(), "tentacle-host")
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
build := exec.CommandContext(ctx, "go", "build", "-buildvcs=false", "-mod=readonly", "-o", host, "./cmd/tentacle-host")
build.Dir = reader
if output, err := build.CombinedOutput(); err != nil {
t.Fatalf("build actual host: %v\n%s", err, output)
}
child, err := os.Executable()
if err != nil {
t.Fatal(err)
}
for _, fixture := range []string{"none", "single", "multiple", "partial", "missing", "slow", "close"} {
t.Run(fixture, func(t *testing.T) {
command := "battery-status"
if fixture == "close" {
command = "close-menu"
}
invoke := exec.CommandContext(ctx, host, "-presentation", "-interaction", "-command", command,
child, "-test.run=^TestBatteryHostChild$", "--", "battery-host-child", fixture)
output, err := invoke.CombinedOutput()
if err != nil {
t.Fatalf("actual host: %v\n%s", err, output)
}
var value tentacle.Interaction
if err := json.Unmarshal(output, &value); err != nil {
t.Fatalf("invalid output: %v\n%s", err, output)
}
switch fixture {
case "multiple", "partial":
if value.Form == nil || value.Form.Title != "Battery Menu" || value.Next != "close-menu" {
t.Fatalf("unexpected menu: %+v", value)
}
items := value.Form.Elements[0].Items
if len(items) != 2 || items[0].Label != "Laptop battery, discharging, 90 percent" || items[1].Label != "Playstation 4 controller battery, discharging, 90 percent" {
t.Fatalf("unexpected items: %+v", items)
}
if fixture == "partial" && value.Speech != "Some battery information is unavailable." {
t.Fatal("missing partial warning")
}
case "close":
if value != (tentacle.Interaction{Done: true}) {
t.Fatalf("completion was not silent: %+v", value)
}
default:
want := "Battery information unavailable."
if fixture == "none" {
want = "No batteries detected."
} else if fixture == "single" {
want = "Laptop battery, discharging, 90 percent."
}
if value.Form != nil || !value.Done || value.Speech != want || value.Braille != want {
t.Fatalf("unexpected announcement: %+v", value)
}
}
})
}
}
+86
View File
@@ -0,0 +1,86 @@
// Copyright (c) 2026 Storm Dragon
// SPDX-License-Identifier: GPL-3.0-or-later
package main
import (
"context"
"encoding/json"
"os"
"time"
"git.stormux.org/storm/cthulhu/sdk/go/tentacle"
)
type batterySource func(context.Context) ([]battery, bool, error)
// Leave room for presentation within the host's two-second RPC deadline.
const readTimeout = time.Second
func message(text string) tentacle.Interaction {
return tentacle.Interaction{Presentation: tentacle.Presentation{Speech: text, Braille: text}, Done: true}
}
func openBatteries(source batterySource) tentacle.Handler {
return func(ctx context.Context, _ json.RawMessage) (any, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
readCtx, cancel := context.WithTimeout(ctx, readTimeout)
defer cancel()
batteries, partial, err := source(readCtx)
if ctx.Err() != nil {
return nil, ctx.Err()
}
if err != nil || len(batteries) == 0 && partial {
return message("Battery information unavailable."), nil
}
if len(batteries) == 0 {
return message("No batteries detected."), nil
}
items := batteryItems(batteries)
warning := ""
if partial {
warning = "Some battery information is unavailable."
}
if len(items) == 1 {
text := items[0].Label + "."
if warning != "" {
text += " " + warning
}
return message(text), nil
}
return tentacle.Interaction{
Presentation: tentacle.Presentation{Speech: warning, Braille: warning},
Form: &tentacle.Form{Title: "Battery Menu", Elements: []tentacle.Element{
{ID: "batteries", Label: "Batteries", Kind: tentacle.List, Items: items},
}}, Next: "close-menu",
}, nil
}
}
func closeMenu(ctx context.Context, _ json.RawMessage) (any, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
// Both activation and cancellation complete without additional output.
return tentacle.Interaction{Done: true}, nil
}
func commands(source batterySource) []tentacle.Command {
return []tentacle.Command{
{ID: "battery-status", Title: "Battery Status", Description: "Report battery status or browse multiple batteries",
Presentation: true, Interaction: true, Handle: openBatteries(source),
Bindings: []tentacle.Binding{
{Layout: "desktop", Scope: "global", Key: "Cthulhu+Shift+B"},
{Layout: "laptop", Scope: "global", Key: "Cthulhu+Shift+B"},
}},
{ID: "close-menu", Title: "Close Battery Menu", Description: "Close the battery menu",
Presentation: true, Interaction: true, Handle: closeMenu},
}
}
func main() {
if tentacle.Serve(os.Stdin, os.Stdout, commands(readUPower)) != nil {
os.Exit(1)
}
}
+74
View File
@@ -0,0 +1,74 @@
// Copyright (c) 2026 Storm Dragon
// SPDX-License-Identifier: GPL-3.0-or-later
package main
import (
"context"
"github.com/godbus/dbus/v5"
)
const upower = "org.freedesktop.UPower"
type deviceSource interface {
devices(context.Context) ([]dbus.ObjectPath, error)
properties(context.Context, dbus.ObjectPath) (map[string]dbus.Variant, error)
}
type upowerSource struct{ conn *dbus.Conn }
func (s upowerSource) devices(ctx context.Context) ([]dbus.ObjectPath, error) {
var paths []dbus.ObjectPath
err := s.conn.Object(upower, "/org/freedesktop/UPower").CallWithContext(ctx, upower+".EnumerateDevices", 0).Store(&paths)
return paths, err
}
func (s upowerSource) properties(ctx context.Context, path dbus.ObjectPath) (map[string]dbus.Variant, error) {
var properties map[string]dbus.Variant
err := s.conn.Object(upower, path).CallWithContext(ctx, "org.freedesktop.DBus.Properties.GetAll", 0, upower+".Device").Store(&properties)
return properties, err
}
func readDevices(ctx context.Context, source deviceSource) ([]battery, bool, error) {
paths, err := source.devices(ctx)
if err != nil {
return nil, false, err
}
var batteries []battery
partial := false
seen := map[dbus.ObjectPath]bool{}
for _, path := range paths {
if err := ctx.Err(); err != nil {
return batteries, true, nil
}
if seen[path] || path == "/org/freedesktop/UPower/devices/DisplayDevice" {
continue
}
seen[path] = true
properties, err := source.properties(ctx, path)
if err != nil {
partial = true
continue
}
// These properties are needed to classify a device reliably.
_, kindOK := properties["Type"].Value().(uint32)
_, presentOK := properties["IsPresent"].Value().(bool)
if !kindOK || !presentOK {
partial = true
continue
}
if b, ok := decodeBattery(string(path), properties); ok {
batteries = append(batteries, b)
}
}
return batteries, partial, nil
}
func readUPower(ctx context.Context) ([]battery, bool, error) {
conn, err := dbus.ConnectSystemBus(dbus.WithContext(ctx))
if err != nil {
return nil, false, err
}
defer conn.Close()
return readDevices(ctx, upowerSource{conn})
}
+23
View File
@@ -0,0 +1,23 @@
format-version = 1
id = "battery-status"
name = "Battery Status"
description = "Report battery status or browse multiple batteries in an internal menu."
version = "0.1.0"
authors = ["Storm Dragon"]
license = "GPL-3.0-or-later"
source = "https://git.stormux.org/storm/cthulhu-tentacles"
help = "README.md"
runtime = "native"
platforms = ["linux"]
entry-point = ["bin/battery-status"]
apis = ["commands", "presentation", "interaction"]
capabilities = ["presentation", "interaction"]
[protocol]
major = 1
minor = 0
[requirements]
reader = "Cthulhu with interactive Tentacle support"
runtime = "UPower service on the system D-Bus; no upower CLI required"
build = "Go 1.24 or newer and the adjacent cthulhu source checkout"
+32
View File
@@ -15,3 +15,35 @@ platform = "linux"
architecture = "arm64"
url = "https://git.stormux.org/storm/cthulhu-tentacles/releases/download/hello-world-v0.1.0/hello-world-0.1.0-linux-arm64.tar.gz"
sha256 = "9ef956a04fb1fa98ac01b04fadc122f92b77d708440e0438a7451da62078a9d4"
[[tentacles]]
id = "wormhole"
manifest = "wormhole/tentacle.toml"
[[tentacles.releases]]
platform = "linux"
architecture = "amd64"
url = "https://git.stormux.org/storm/cthulhu-tentacles/releases/download/wormhole-v0.1.2/wormhole-0.1.2-linux-amd64.tar.gz"
sha256 = "537480f85effde8097afd2201dbd815c4093abc05da80feace5577bd777b2ed9"
[[tentacles.releases]]
platform = "linux"
architecture = "arm64"
url = "https://git.stormux.org/storm/cthulhu-tentacles/releases/download/wormhole-v0.1.2/wormhole-0.1.2-linux-arm64.tar.gz"
sha256 = "0c6254bd96dc9921884e81a58db3385cf0433073129e8ce64d86407992ce4134"
[[tentacles]]
id = "battery-status"
manifest = "battery-status/tentacle.toml"
[[tentacles.releases]]
platform = "linux"
architecture = "amd64"
url = "https://git.stormux.org/storm/cthulhu-tentacles/releases/download/battery-status-v0.1.0/battery-status-0.1.0-linux-amd64.tar.gz"
sha256 = "53939e7674c1f8ba4193a71a69c3e917b51439fa29884bebb7c622bdcef2c3d9"
[[tentacles.releases]]
platform = "linux"
architecture = "arm64"
url = "https://git.stormux.org/storm/cthulhu-tentacles/releases/download/battery-status-v0.1.0/battery-status-0.1.0-linux-arm64.tar.gz"
sha256 = "d75e40fd76280ecba228f3d3132d846f4e8f79a3e2bdd6dafd515c39a191cca0"
+4 -2
View File
@@ -2,8 +2,10 @@ module git.stormux.org/storm/cthulhu-tentacles
go 1.24.0
require git.stormux.org/storm/cthulhu-go v0.0.0
require git.stormux.org/storm/cthulhu v0.0.0
require github.com/godbus/dbus/v5 v5.1.0
// The experimental SDK is developed alongside this repository.
replace git.stormux.org/storm/cthulhu-go => ../cthulhu-go
replace git.stormux.org/storm/cthulhu => ../cthulhu
+2
View File
@@ -0,0 +1,2 @@
github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk=
github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
+7 -6
View File
@@ -30,12 +30,12 @@ status until Active before trying the shortcut.
## Local launch
Run `make build` from the repository root. Rebuild Cthulhu-Go with the matching
Run `make build` from the repository root. Rebuild Cthulhu with the matching
SDK/output implementation before a live test:
```sh
cd ../cthulhu-go
GOCACHE=/tmp/cthulhu-go-cache go build -o /tmp/cthulhu-with-hello-world ./cmd/cthulhu
cd ../cthulhu
GOCACHE=/tmp/cthulhu-cache go build -o /tmp/cthulhu-with-hello-world ./cmd/cthulhu
```
Create a development launch list with an absolute executable path. From this
@@ -60,9 +60,10 @@ When ready to test, launch the rebuilt reader explicitly:
```
That command replaces the running Go reader and selects the development launch
list instead of saved Tentacles. The reader automatically requests systemd user
cgroup delegation. A delegation failure leaves the Tentacle unavailable.
Resource limits do not make untrusted same-user programs safe.
list instead of saved Tentacles. The reader supervises each Tentacle directly;
no administrator setup or particular init system is required. Kernel CPU, memory
and task limits are optional and require an explicitly configured delegated
cgroup v2 parent. Tentacles run with your account's access; install trusted code.
## Live verification
+1 -1
View File
@@ -8,7 +8,7 @@ import (
"encoding/json"
"os"
"git.stormux.org/storm/cthulhu-go/sdk/go/tentacle"
"git.stormux.org/storm/cthulhu/sdk/go/tentacle"
)
func say_hello(ctx context.Context, _ json.RawMessage) (any, error) {
+2 -2
View File
@@ -18,6 +18,6 @@ major = 1
minor = 0
[requirements]
reader = "Cthulhu-Go with uninterruptible presentation support"
build = "Go 1.24 or newer and the adjacent cthulhu-go source checkout"
reader = "Cthulhu with uninterruptible presentation support"
build = "Go 1.24 or newer and the adjacent cthulhu source checkout"
+95 -41
View File
@@ -29,45 +29,50 @@ def check_metadata(repoRoot):
"Unsupported metadata format")
require(repository["id"] == "storm.cthulhu-tentacles" and repository["name"],
"Repository identity is missing")
require(len(catalog["tentacles"]) == 1 and catalog["tentacles"][0]["id"] == "hello-world"
and catalog["tentacles"][0]["manifest"] == "hello-world/tentacle.toml",
"Catalog must list exactly Hello World")
manifest = read_toml(repoRoot / catalog["tentacles"][0]["manifest"])
require(manifest["format-version"] == 1 and manifest["id"] == "hello-world"
and manifest["name"] and manifest["version"] == "0.1.0",
"Invalid Hello World metadata")
require(manifest["entry-point"] == ["bin/hello-world"]
and manifest["capabilities"] == ["presentation"], "Unexpected launch or grants")
require((repoRoot / "LICENSE").is_file() and (repoRoot / "hello-world/LICENSE").is_file(),
"Repository and Tentacle licenses are required")
seen = set()
for release in catalog["tentacles"][0].get("releases", []):
key = (release["platform"], release["architecture"])
require(key not in seen and key[0] == "linux" and key[1] in ("amd64", "arm64"),
"Invalid or duplicate release target")
seen.add(key)
parsed = urlparse(release["url"])
require(parsed.scheme == "https" and parsed.hostname and not parsed.username
and not parsed.fragment, "Release URL must be HTTPS without credentials")
digest = release["sha256"]
require(len(digest) == 64 and all(character in "0123456789abcdef" for character in digest),
"Invalid SHA-256 digest")
artifactPath = repoRoot / "dist" / parsed.path.rsplit("/", 1)[-1]
if artifactPath.exists():
require(hashlib.sha256(artifactPath.read_bytes()).hexdigest() == digest,
"Prepared package does not match its catalog digest")
require([item["id"] for item in catalog["tentacles"]] == ["hello-world", "wormhole", "battery-status"],
"Catalog must list Hello World, Wormhole, and Battery Status")
for item in catalog["tentacles"]:
name = item["id"]
require(item["manifest"] == f"{name}/tentacle.toml", "Manifest path must match ID")
manifest = read_toml(repoRoot / item["manifest"])
require(manifest["format-version"] == 1 and manifest["id"] == name
and manifest["name"] and manifest["version"] == ("0.1.2" if name == "wormhole" else "0.1.0"), "Invalid Tentacle metadata")
expectedGrants = ["presentation"] + (["interaction"] if name in ("wormhole", "battery-status") else [])
expectedProgram = "wormhole-tentacle" if name == "wormhole" else name
require(manifest["entry-point"] == [f"bin/{expectedProgram}"]
and manifest["capabilities"] == expectedGrants
and manifest["apis"] == ["commands"] + expectedGrants,
"Unexpected launch or grants")
require((repoRoot / "LICENSE").is_file() and (repoRoot / name / "LICENSE").is_file()
and (repoRoot / name / "README.md").is_file(), "License and help are required")
seen = set()
for release in item.get("releases", []):
key = (release["platform"], release["architecture"])
require(key not in seen and key[0] == "linux" and key[1] in ("amd64", "arm64"),
"Invalid or duplicate release target")
seen.add(key)
parsed = urlparse(release["url"])
require(parsed.scheme == "https" and parsed.hostname and not parsed.username
and not parsed.fragment, "Release URL must be HTTPS without credentials")
digest = release["sha256"]
require(len(digest) == 64 and all(character in "0123456789abcdef" for character in digest),
"Invalid SHA-256 digest")
artifactPath = repoRoot / "dist" / parsed.path.rsplit("/", 1)[-1]
if artifactPath.exists():
require(hashlib.sha256(artifactPath.read_bytes()).hexdigest() == digest,
"Prepared package does not match its catalog digest")
def check_registration(programPath):
def check_registration(programPath, name):
apis = ["commands", "presentation"] + (["interaction"] if name in ("wormhole", "battery-status") else [])
with subprocess.Popen([str(programPath)], stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE) as process:
try:
initialization = {
"jsonrpc": "2.0", "id": "1", "method": "initialize",
"params": {"protocol": {"major": 1, "minor": 0}, "session": "check",
"apis": ["commands", "presentation"],
"capabilities": ["commands", "presentation"]},
"apis": apis,
"capabilities": apis},
}
process.stdin.write((json.dumps(initialization) + "\n").encode())
process.stdin.flush()
@@ -76,11 +81,21 @@ def check_registration(programPath):
require(registration["id"] == "1" and registration["result"]["session"] == "check",
"Invalid registration response")
commands = registration["result"]["commands"]
require(len(commands) == 1 and commands[0]["id"] == "hello-world"
require(len(commands) == (9 if name == "wormhole" else 2 if name == "battery-status" else 1) and commands[0]["id"] == name
and commands[0]["presentation"] is True, "Unexpected commands or grant")
require(commands[0]["bindings"] == [
{"layout": layout, "scope": "global", "key": "Cthulhu+Alt+Shift+H"}
{"layout": layout, "scope": "global", "key": ("Cthulhu+Ctrl+Shift+W" if name == "wormhole" else "Cthulhu+Shift+B" if name == "battery-status" else "Cthulhu+Alt+Shift+H")}
for layout in ("desktop", "laptop")], "Wrong suggested shortcut")
if name == "battery-status":
require(commands[0].get("interaction") is True
and commands[1]["id"] == "close-menu"
and commands[1].get("interaction") is True
and not commands[1].get("bindings")
and not any(command.get("settings") for command in commands),
"Battery Status must have one bound entry point and an unbound continuation")
if name == "wormhole":
require([command["id"] for command in commands if command.get("settings")]
== ["settings"], "Wrong registered settings entry point")
process.stdin.close()
require(process.wait(timeout=5) == 0, "Tentacle did not stop cleanly on EOF")
finally:
@@ -89,14 +104,50 @@ def check_registration(programPath):
process.wait(timeout=5)
def check_host(repoRoot, programPath):
readerRoot = repoRoot.parent / "cthulhu-go"
def check_host(repoRoot, programPath, name):
readerRoot = repoRoot.parent / "cthulhu"
environment = os.environ.copy()
environment.setdefault("GOCACHE", "/tmp/cthulhu-go-cache")
environment.setdefault("GOCACHE", "/tmp/cthulhu-cache")
flags = ["-interaction"] if name in ("wormhole", "battery-status") else []
result = subprocess.run([
"go", "run", "./examples/tentacles/host", "-presentation",
"-command", "hello-world", str(programPath),
"go", "run", "./cmd/tentacle-host", "-presentation",
*flags, "-command", name, str(programPath),
], cwd=readerRoot, env=environment, capture_output=True, text=True, timeout=60, check=True)
if name == "battery-status":
value = json.loads(result.stdout)
form = value.get("form")
if form:
require(form.get("title") == "Battery Menu" and value.get("next") == "close-menu"
and len(form["elements"][0]["items"]) > 1,
"Host returned an unexpected Battery Menu")
else:
require(value.get("done") is True and value.get("speech")
and value.get("speech") == value.get("braille"),
"Host returned an unexpected battery announcement")
result = subprocess.run([
"go", "run", "./cmd/tentacle-host", "-presentation", "-interaction",
"-command", "close-menu", str(programPath),
], cwd=readerRoot, env=environment, capture_output=True, text=True,
timeout=60, check=True)
require(json.loads(result.stdout) == {"done": True},
"Battery menu completion must be silent")
return
if name == "wormhole":
value = json.loads(result.stdout)
require(value.get("form", {}).get("title") == "Wormhole menu"
or value == {"speech": "Magic wormhole is not installed",
"braille": "Magic wormhole is not installed", "uninterruptible": True},
"Host returned an unexpected Wormhole menu")
result = subprocess.run([
"go", "run", "./cmd/tentacle-host", "-presentation", "-interaction",
"-command", "settings", str(programPath),
], cwd=readerRoot, env=environment, capture_output=True, text=True,
timeout=60, check=True)
value = json.loads(result.stdout)
require(value.get("form", {}).get("title") == "Wormhole preferences"
and value.get("next") == "save-settings",
"Host returned an unexpected Wormhole settings form")
return
require(json.loads(result.stdout) == {
"speech": "Hello world!", "braille": "Hello world!", "uninterruptible": True,
}, "The actual host returned an unexpected greeting")
@@ -106,9 +157,12 @@ def main():
repoRoot = Path(__file__).resolve().parents[1]
programPath = repoRoot / "hello-world/bin/hello-world"
check_metadata(repoRoot)
check_registration(programPath)
check_host(repoRoot, programPath)
print("Repository metadata, shortcut registration and actual-host greeting passed.")
for name, binary in (("hello-world", "hello-world"), ("wormhole", "wormhole-tentacle"),
("battery-status", "battery-status")):
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.")
if __name__ == "__main__":
+46 -24
View File
@@ -1,6 +1,6 @@
# Copyright (c) 2026 Storm Dragon
# SPDX-License-Identifier: GPL-3.0-or-later
"""Build reproducible Hello World release artifacts and a catalog for review."""
"""Build reproducible Tentacle release artifacts and a catalog for review."""
import argparse
import gzip
@@ -12,26 +12,30 @@ from pathlib import Path
import subprocess
import tarfile
import tomllib
from urllib.parse import urlparse
def build_package(repoRoot, architecture, version):
def build_package(repoRoot, architecture, version, name):
sourceRoot = repoRoot / name
manifest = tomllib.loads((sourceRoot / "tentacle.toml").read_text())
binaryName = manifest["entry-point"][0]
distRoot = repoRoot / "dist"
distRoot.mkdir(exist_ok=True)
programPath = distRoot / f"hello-world-linux-{architecture}"
programPath = distRoot / f"{name}-linux-{architecture}"
environment = dict(os.environ, CGO_ENABLED="0", GOOS="linux", GOARCH=architecture)
environment.setdefault("GOCACHE", "/tmp/cthulhu-go-cache")
environment.setdefault("GOCACHE", "/tmp/cthulhu-cache")
subprocess.run(["go", "build", "-buildvcs=false", "-mod=readonly", "-trimpath",
"-ldflags=-s -w", "-o", str(programPath), "./hello-world/src"],
"-ldflags=-s -w", "-o", str(programPath), f"./{name}/src"],
cwd=repoRoot, env=environment, check=True)
artifactPath = distRoot / f"hello-world-{version}-linux-{architecture}.tar.gz"
artifactPath = distRoot / f"{name}-{version}-linux-{architecture}.tar.gz"
with artifactPath.open("wb") as output:
with gzip.GzipFile(filename="", mode="wb", fileobj=output, mtime=0) as compressed:
with tarfile.open(fileobj=compressed, mode="w", format=tarfile.USTAR_FORMAT) as archive:
for name, data, mode in [
("tentacle.toml", (repoRoot / "hello-world/tentacle.toml").read_bytes(), 0o644),
("README.md", (repoRoot / "hello-world/README.md").read_bytes(), 0o644),
("LICENSE", (repoRoot / "hello-world/LICENSE").read_bytes(), 0o644),
("bin/hello-world", programPath.read_bytes(), 0o755),
("tentacle.toml", (sourceRoot / "tentacle.toml").read_bytes(), 0o644),
("README.md", (sourceRoot / "README.md").read_bytes(), 0o644),
("LICENSE", (sourceRoot / "LICENSE").read_bytes(), 0o644),
(binaryName, programPath.read_bytes(), 0o755),
]:
member = tarfile.TarInfo(name)
member.size, member.mode, member.mtime = len(data), mode, 0
@@ -43,25 +47,43 @@ def build_package(repoRoot, architecture, version):
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--architecture", nargs="+", choices=["amd64", "arm64"], default=["amd64", "arm64"])
parser.add_argument("--tentacle", nargs="+", help="Catalog IDs to package (default: hello-world)")
parser.add_argument("--download-base", help="Immutable HTTPS directory containing the archives")
args = parser.parse_args()
if args.download_base:
parsed = urlparse(args.download_base)
if parsed.scheme != "https" or not parsed.hostname or parsed.username or parsed.fragment or parsed.query:
parser.error("Download base must be an HTTPS directory without credentials, query or fragment")
if len(set(args.architecture)) != len(args.architecture):
parser.error("Architectures must not be repeated")
repoRoot = Path(__file__).resolve().parents[1]
manifest = tomllib.loads((repoRoot / "hello-world/tentacle.toml").read_text())
version = manifest["version"]
if not version or any(character not in "0123456789abcdefghijklmnopqrstuvwxyz.-" for character in version):
raise ValueError("Version must be safe for release filenames")
lines = ["format-version = 1", "", "[[tentacles]]", 'id = "hello-world"',
'manifest = "hello-world/tentacle.toml"']
catalog = tomllib.loads((repoRoot / "catalog.toml").read_text())
names = [item["id"] for item in catalog["tentacles"]]
selected = args.tentacle or ["hello-world"]
if len(set(selected)) != len(selected) or any(name not in names for name in selected):
parser.error("Select distinct Tentacle IDs from catalog.toml")
lines = ["format-version = 1"]
checksums = []
for architecture in args.architecture:
artifactPath, digest = build_package(repoRoot, architecture, version)
releaseURL = f"https://git.stormux.org/storm/cthulhu-tentacles/releases/download/hello-world-v{version}/{artifactPath.name}"
lines += ["", "[[tentacles.releases]]", 'platform = "linux"',
f"architecture = {json.dumps(architecture)}", f"url = {json.dumps(releaseURL)}",
f"sha256 = {json.dumps(digest)}"]
checksums.append(f"{digest} {artifactPath.name}")
print(f"Prepared {artifactPath.name}: {digest}")
for item in catalog["tentacles"]:
name = item["id"]
lines += ["", "[[tentacles]]", f"id = {json.dumps(name)}",
f"manifest = {json.dumps(item['manifest'])}"]
releases = item.get("releases", [])
if name in selected:
manifest = tomllib.loads((repoRoot / item["manifest"]).read_text())
version = manifest["version"]
if not version or any(character not in "0123456789abcdefghijklmnopqrstuvwxyz.-" for character in version):
raise ValueError("Version must be safe for release filenames")
releases = []
for architecture in args.architecture:
artifactPath, digest = build_package(repoRoot, architecture, version, name)
releaseURL = (args.download_base.rstrip("/") + "/" + artifactPath.name) if args.download_base else f"https://git.stormux.org/storm/cthulhu-tentacles/releases/download/{name}-v{version}/{artifactPath.name}"
releases.append(dict(platform="linux", architecture=architecture, url=releaseURL, sha256=digest))
checksums.append(f"{digest} {artifactPath.name}")
print(f"Prepared {artifactPath.name}: {digest}")
for release in releases:
lines += ["", "[[tentacles.releases]]"]
lines += [f"{key} = {json.dumps(release[key])}" for key in ("platform", "architecture", "url", "sha256")]
(repoRoot / "dist/catalog.toml").write_text("\n".join(lines) + "\n")
(repoRoot / "dist/SHA256SUMS").write_text("\n".join(checksums) + "\n")
print("Prepared dist/catalog.toml and dist/SHA256SUMS for review. Nothing was published.")
+232
View File
@@ -0,0 +1,232 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for software and other kinds of works.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
“This License” refers to version 3 of the GNU General Public License.
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
A “covered work” means either the unmodified Program or a work based on the Program.
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <https://www.gnu.org/philosophy/why-not-lgpl.html>.
+159
View File
@@ -0,0 +1,159 @@
# Wormhole
An experimental Magic Wormhole Tentacle for Cthulhu. Suggested shortcut:
**Cthulhu+Ctrl+Shift+W**, on desktop and laptop layouts. It opens the reader's
internal **Wormhole menu**, preserving the underlying application's focus.
With a reader supporting Tentacle settings registration, global Preferences →
Tentacles → select Wormhole → Settings opens **Wormhole preferences** directly.
Save persists the two checkboxes and returns to reader preferences; Escape
discards the form's edits. This entry point works without the Wormhole CLI.
Use Wormhole 0.1.2 and rebuild the reader to obtain settings registration and the
Ctrl+Shift shortcut; the published 0.1.1 binary uses Alt+Shift and has no
registered settings entry point.
Install the `magic-wormhole` CLI using your distribution's package manager.
Clipboard operations require `xclip` on Xorg. Missing `wormhole` does not stop
reader startup: the shortcut speaks and brailles **Magic wormhole is not
installed**, with speech protected from ordinary interruption. Lock, shutdown,
disable and the reader's explicit stop policy still take precedence.
Use Up/Down and Enter in lists. Tab/Shift+Tab move through forms, Space toggles
checkboxes, and Escape closes the UI. Entries support editing, selection, Ctrl+C,
Ctrl+X and Ctrl+V. A transfer's Escape or Cancel transfer stops its process.
Changing native focus closes the UI and cancels the transfer. Only one transfer
runs at a time; keep the transfer UI open until it completes.
The menu offers:
- **Send focused item**: send one current text line, preserving spacing and
replacing line breaks with spaces. Password fields are excluded. A reliably
exposed local file URI/path is sent as one file or folder. File icons/list
items/table rows without a path are rejected; a filename never silently
becomes a text message. Flat review without an exact text range is unavailable.
- **Send from clipboard**: send text as a message, preserving its line breaks.
A local file URI from a file manager sends the file or folder. Exactly one
item is required; multiple files are rejected. Plain text that resembles a
path remains a text message. If the clipboard supplies PNG data, create a
private temporary `clipboard.png`, send it, and remove it after completion or
cancellation. A missing file path without any file data cannot be reconstructed.
- **Receive**: type/paste a code in the internal Wormhole code entry, then press
Enter. Files and folders are saved in `~/Downloads`, which is created if
needed. Existing destinations are refused rather than overwritten. Text is
read automatically when the transfer completes.
- **Preferences**: two independent checkboxes, both unchecked by default:
**Save received text messages to clipboard** and **Copy send code to clipboard**.
Checked means both speak and copy the respective text/code. Unchecked means
speak it and preserve the clipboard. Save persists both choices in
`$XDG_CONFIG_HOME/cthulhu-tentacles/wormhole.json` (normally `~/.config/...`).
Escape discards changes.
Transfer controls offer **Read transfer status**, **Copy code**, and **Cancel
transfer**. Generated codes are automatically spoken and shown on braille, and
copied only when the preference is enabled. Copy code performs an explicit copy
regardless of that preference. There is no per-packet progress chatter. Errors
report failure, not success, and do not copy partial received messages.
File managers such as Thunar, PCManFM, Caja and Nautilus do not have a common
AT-SPI method that guarantees the selected file's full URI. The portable path
is to select one file/folder, press Ctrl+C, open the menu and choose **Send from
clipboard**. Direct selected-file sending without that copy remains unavailable
when the application does not expose an exact path. No path is guessed from a
window title, status bar, or filename.
Text transfers currently have an 8 KiB input limit; received text has an 8,000
byte limit so its complete announcement fits the reader's bounded output.
Oversized data is rejected, not silently truncated. Clipboard PNG data has a
32 MiB limit. Clipboard support currently uses Xorg; on Wayland a missing
clipboard service reports an unavailable item. The Wormhole CLI manages the
network protocol, directory archive and transport; the tentacle never executes
received text or launches a shell for transfers. Consult the
[Magic Wormhole documentation](https://magic-wormhole.readthedocs.io/en/latest/welcome.html).
## Build and local launch
Keep this repository beside the matching `cthulhu` checkout:
```sh
make build
make check
```
The binary is `wormhole/bin/wormhole-tentacle`. The current reader must support
`interaction` grants; an older presentation-only host will reject it.
Use a local launch entry with both grants:
```json
[
{
"ID": "wormhole",
"Program": ["/home/angus/devel/cthulhu-tentacles/wormhole/bin/wormhole-tentacle"],
"Presentation": true,
"Interaction": true
}
]
```
Development launches use `--tentacles /absolute/launch.json` and the existing
contained launcher. Alternatively, add a local entry to the reader's version-1
`tentacles.toml` beside its settings file (normally
`~/.local/share/cthulhu/tentacles.toml`), preserving existing entries:
```toml
[[tentacles]]
id = "wormhole"
program = ["/home/angus/devel/cthulhu-tentacles/wormhole/bin/wormhole-tentacle"]
enabled = true
presentation = true
interaction = true
```
The normal installation path is global Preferences → Tentacles → Add repository
with `https://git.stormux.org/storm/cthulhu-tentacles`, followed by selecting
Wormhole and Install and enable. Version 0.1.2 downloads use the normal
[`wormhole-v0.1.2` release attachments](https://git.stormux.org/storm/cthulhu-tentacles/releases/tag/wormhole-v0.1.2). The manifest
requests presentation and interaction permissions. Local metadata above is an
optional development path.
Prepare amd64/arm64 archives with
`python3 -B tools/package.py --tentacle wormhole`. Generated `dist/catalog.toml`
preserves other catalog entries. Nothing is published by that command.
## Live verification
After configuring the local entry:
1. Quit Cthulhu with Cthulhu+Q. Press Ctrl+Escape, then Shift+G. These are
separate key presses. Shift+G rebuilds the reader and braille helper.
2. Focus an ordinary multiline text field. Open Cthulhu+Ctrl+Shift+W. Expect
“Wormhole menu. Send focused item” in speech and the menu option on braille.
Native application focus must stay on the original field. Send it to a
second Wormhole endpoint; the recipient must get exactly the current line.
3. Open Preferences. Tab and Shift+Tab across both checkboxes and Save; Space
toggles each. Enable Copy send code to clipboard and Save. Send text from
the clipboard; expect the generated code spoken and shown on braille.
The clipboard must contain that exact code. Cancel the transfer. Disable
the preference and repeat; the original clipboard text must remain.
4. In a file manager, copy exactly one file with Ctrl+C. Choose Send from
clipboard. Receive it at another endpoint and compare the contents.
Repeat with one folder, then multiple selected files: multiple items must
be refused. Sending a file icon without a usable path must give the copy
instruction and must not send its filename as text.
5. Receive a file with the code entry. Test typing, cursor movement and Ctrl+V.
After completion, expect “Wormhole transfer received in Downloads” and the
actual file in Downloads. Repeat with an existing filename: expect failure
and unchanged original contents. Test a folder too.
6. Receive text containing line breaks, quotes, backslashes and Unicode. With
Save received text messages to clipboard off, expect the complete message
spoken/shown and the previous clipboard preserved. Enable it and repeat:
expect the exact original text in the clipboard. Restart and verify both
checkbox choices persist.
7. Cancel a waiting transfer with Escape and with Cancel transfer. Ordinary
typing must return to the original application, with no remaining modal
key capture. Test focus change, reader quit, and tentacle disable during
a waiting transfer. Check ordinary actions, learn mode, reading, and braille
afterward.
Report the exact speech and braille, the focused control, the clipboard contents,
and any key that behaved differently. Unexpected results should be diagnosed
from `~/devel/cthulhu.log`. Automated and private Xorg checks do not establish
physical speech, keyboard or braille acceptance.
+201
View File
@@ -0,0 +1,201 @@
// Copyright (c) 2026 Storm Dragon
// SPDX-License-Identifier: GPL-3.0-or-later
package main
import (
"context"
"encoding/json"
"os"
"path/filepath"
"sync"
"git.stormux.org/storm/cthulhu/sdk/go/tentacle"
)
type preferences struct {
SaveReceivedText bool `json:"save_received_text"`
CopySendCode bool `json:"copy_send_code"`
}
type wormhole struct {
mutex sync.Mutex
preferences preferences
settingsPath string
downloads string
program string
job *transfer
workers sync.WaitGroup
}
func message(text string) tentacle.Interaction {
return tentacle.Interaction{Presentation: tentacle.Presentation{Speech: text, Braille: text}}
}
func menu() tentacle.Interaction {
return tentacle.Interaction{Form: &tentacle.Form{Title: "Wormhole menu", Elements: []tentacle.Element{{ID: "options", Label: "Options", Kind: tentacle.List, Items: []tentacle.ListItem{
{ID: "send-focus", Label: "Send focused item"}, {ID: "send-clipboard", Label: "Send from clipboard"}, {ID: "receive", Label: "Receive"}, {ID: "preferences", Label: "Preferences"},
}}}}, Next: "menu"}
}
func (w *wormhole) open(ctx context.Context, _ json.RawMessage) (any, error) {
w.mutex.Lock()
defer w.mutex.Unlock()
if ctx.Err() != nil {
return nil, ctx.Err()
}
if _, err := lookPath(w.program); err != nil {
result := message("Magic wormhole is not installed")
result.Uninterruptible = true
return result, nil
}
if w.job != nil {
return w.transferForm(), nil
}
return menu(), nil
}
func submission(raw json.RawMessage) (tentacle.Submission, error) {
var value tentacle.Submission
err := json.Unmarshal(raw, &value)
return value, err
}
func (w *wormhole) choose(ctx context.Context, raw json.RawMessage) (any, error) {
value, err := submission(raw)
if err != nil {
return nil, err
}
w.mutex.Lock()
defer w.mutex.Unlock()
if ctx.Err() != nil {
return nil, ctx.Err()
}
if value.Cancelled {
return tentacle.Interaction{Done: true}, nil
}
switch value.Activated {
case "send-focus":
return tentacle.Interaction{Source: "focus", Next: "send"}, nil
case "send-clipboard":
return tentacle.Interaction{Source: "clipboard", Next: "send"}, nil
case "receive":
return tentacle.Interaction{Form: &tentacle.Form{Title: "Receive with Wormhole", Elements: []tentacle.Element{
{ID: "code", Label: "Wormhole code", Kind: tentacle.Entry, Required: true, MaxLength: 256},
{ID: "receive", Label: "Receive", Kind: tentacle.Button},
}}, Next: "receive"}, nil
case "preferences":
return w.preferencesForm(), nil
}
return menu(), nil
}
func (w *wormhole) preferencesForm() tentacle.Interaction {
return tentacle.Interaction{Form: &tentacle.Form{Title: "Wormhole preferences", Elements: []tentacle.Element{
{ID: "save-text", Label: "Save received text messages to clipboard", Kind: tentacle.CheckBox, Checked: w.preferences.SaveReceivedText},
{ID: "copy-code", Label: "Copy send code to clipboard", Kind: tentacle.CheckBox, Checked: w.preferences.CopySendCode},
{ID: "save", Label: "Save", Kind: tentacle.Button},
}}, Next: "preferences"}
}
func (w *wormhole) openPreferences(ctx context.Context, _ json.RawMessage) (any, error) {
w.mutex.Lock()
defer w.mutex.Unlock()
if err := ctx.Err(); err != nil {
return nil, err
}
result := w.preferencesForm()
result.Next = "save-settings"
return result, nil
}
func (w *wormhole) saveSettings(ctx context.Context, raw json.RawMessage) (any, error) {
value, err := w.savePreferences(ctx, raw)
if err != nil {
return nil, err
}
result := value.(tentacle.Interaction)
result.Form, result.Next, result.Done = nil, "", true
return result, nil
}
func (w *wormhole) savePreferences(ctx context.Context, raw json.RawMessage) (any, error) {
value, err := submission(raw)
if err != nil {
return nil, err
}
w.mutex.Lock()
defer w.mutex.Unlock()
if value.Cancelled {
return tentacle.Interaction{Done: true}, nil
}
if ctx.Err() != nil {
return nil, ctx.Err()
}
next := preferences{SaveReceivedText: value.Values["save-text"].Checked, CopySendCode: value.Values["copy-code"].Checked}
if err := writePreferences(w.settingsPath, next); err != nil {
return message("Wormhole preferences could not be saved"), nil
}
w.preferences = next
result := menu()
result.Presentation = message("Wormhole preferences saved").Presentation
return result, nil
}
func writePreferences(path string, value preferences) error {
if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
return err
}
data, err := json.Marshal(value)
if err != nil {
return err
}
file, err := os.CreateTemp(filepath.Dir(path), ".wormhole-*.json")
if err != nil {
return err
}
defer os.Remove(file.Name())
defer file.Close()
if _, err = file.Write(data); err != nil {
return err
}
if err = file.Sync(); err != nil {
return err
}
if err = file.Close(); err != nil {
return err
}
return os.Rename(file.Name(), path)
}
func (w *wormhole) commands() []tentacle.Command {
var commands []tentacle.Command
for _, entry := range []struct {
id, title string
handler tentacle.Handler
}{
{"wormhole", "Wormhole menu", w.open}, {"menu", "Wormhole menu selection", w.choose},
{"send", "Send Wormhole item", w.send}, {"receive", "Receive Wormhole item", w.receive},
{"preferences", "Save Wormhole preferences", w.savePreferences}, {"control", "Wormhole transfer controls", w.control}, {"poll", "Wormhole transfer status", w.poll},
{"settings", "Wormhole preferences", w.openPreferences}, {"save-settings", "Save Wormhole settings", w.saveSettings},
} {
command := tentacle.Command{ID: entry.id, Title: entry.title, Description: entry.title, Presentation: true, Interaction: true, Handle: entry.handler}
if entry.id == "wormhole" {
command.Bindings = []tentacle.Binding{{Layout: "desktop", Scope: "global", Key: "Cthulhu+Ctrl+Shift+W"}, {Layout: "laptop", Scope: "global", Key: "Cthulhu+Ctrl+Shift+W"}}
}
command.Settings = entry.id == "settings"
commands = append(commands, command)
}
return commands
}
func main() {
config, err := os.UserConfigDir()
if err != nil {
os.Exit(1)
}
home, err := os.UserHomeDir()
if err != nil {
os.Exit(1)
}
w := &wormhole{program: "wormhole", settingsPath: filepath.Join(config, "cthulhu-tentacles", "wormhole.json"), downloads: filepath.Join(home, "Downloads")}
if data, err := os.ReadFile(w.settingsPath); err == nil {
if json.Unmarshal(data, &w.preferences) != nil {
os.Exit(1)
}
} else if !os.IsNotExist(err) {
os.Exit(1)
}
err = tentacle.Serve(os.Stdin, os.Stdout, w.commands())
w.workers.Wait()
if err != nil {
os.Exit(1)
}
}
+421
View File
@@ -0,0 +1,421 @@
// Copyright (c) 2026 Storm Dragon
// SPDX-License-Identifier: GPL-3.0-or-later
package main
import (
"bufio"
"context"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/url"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"unicode"
"unicode/utf8"
"git.stormux.org/storm/cthulhu/sdk/go/tentacle"
)
var lookPath = exec.LookPath
type transfer struct {
cancel context.CancelFunc
code string
reportedCode bool
received bool
done bool
cancelled bool
hasMessage bool
output string
diagnostic string // Bounded CLI detail retained in memory; never logged or spoken.
status string
copyCode bool
saveText bool
}
type boundedOutput struct {
mutex sync.Mutex
data []byte
overflow bool
}
func (output *boundedOutput) Write(data []byte) (int, error) {
output.mutex.Lock()
defer output.mutex.Unlock()
limit := 65536 - len(output.data)
if len(data) > limit {
output.overflow = true
}
output.data = append(output.data, data[:min(len(data), limit)]...)
return len(data), nil
}
func (output *boundedOutput) result() (string, bool) {
output.mutex.Lock()
defer output.mutex.Unlock()
return string(output.data), output.overflow
}
func localPath(raw string) (string, error) {
if strings.HasPrefix(raw, "file:") {
uri, err := url.Parse(raw)
if err != nil || uri.Host != "" && uri.Host != "localhost" || uri.RawQuery != "" || uri.Fragment != "" {
return "", errors.New("not a local file URI")
}
raw = uri.Path
}
if strings.HasPrefix(raw, "~/") {
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
raw = filepath.Join(home, raw[2:])
}
if !filepath.IsAbs(raw) {
return "", errors.New("not an absolute path")
}
info, err := os.Stat(raw)
if err != nil {
return "", err
}
if !info.IsDir() && !info.Mode().IsRegular() {
return "", errors.New("not a file or folder")
}
return filepath.Clean(raw), nil
}
func (w *wormhole) send(ctx context.Context, raw json.RawMessage) (any, error) {
value, err := submission(raw)
if err != nil {
return nil, err
}
w.mutex.Lock()
defer w.mutex.Unlock()
if ctx.Err() != nil {
return nil, ctx.Err()
}
if value.Error != "" || value.Item == nil {
return message("Cannot send this item. Copy one file or folder, then choose Send from clipboard"), nil
}
if w.job != nil {
return w.transferForm(), nil
}
args := []string{"send", "--hide-progress", "--no-qr"}
text := ""
if value.Item.Path != "" {
path, err := localPath(value.Item.Path)
if err != nil {
return message("The file or folder path is unavailable"), nil
}
args = append(args, "--", path)
} else {
text = value.Item.Text
if text == "" {
return message("There is no text to send"), nil
}
if !utf8.ValidString(text) || len(text) > 8192 {
return message("The text message is too large or invalid"), nil
}
args = append(args, "--text", "-")
}
if err = w.start(ctx, args, text, false); err != nil {
return message("Wormhole transfer could not start"), nil
}
return w.transferForm(), nil
}
func validCode(code string) bool {
if len(code) == 0 || len(code) > 256 {
return false
}
parts := strings.Split(code, "-")
if len(parts) < 2 {
return false
}
if _, err := strconv.ParseUint(parts[0], 10, 64); err != nil {
return false
}
for _, part := range parts[1:] {
if part == "" {
return false
}
for _, r := range part {
if !unicode.IsLetter(r) {
return false
}
}
}
return true
}
func (w *wormhole) receive(ctx context.Context, raw json.RawMessage) (any, error) {
value, err := submission(raw)
if err != nil {
return nil, err
}
w.mutex.Lock()
defer w.mutex.Unlock()
if value.Cancelled {
return tentacle.Interaction{Done: true}, nil
}
if ctx.Err() != nil {
return nil, ctx.Err()
}
if w.job != nil {
return w.transferForm(), nil
}
code := strings.TrimSpace(value.Values["code"].Text)
if !validCode(code) {
return message("Invalid Wormhole code"), nil
}
if err = os.MkdirAll(w.downloads, 0700); err != nil {
return message("Downloads could not be opened"), nil
}
if err = w.start(ctx, []string{"receive", "--accept-file", "--hide-progress", "--", code}, "", true); err != nil {
return message("Wormhole transfer could not start"), nil
}
return w.transferForm(), nil
}
func (w *wormhole) start(ctx context.Context, args []string, text string, received bool) error {
path, err := lookPath(w.program)
if err != nil {
return err
}
jobCtx, cancel := context.WithCancel(ctx)
command := exec.CommandContext(jobCtx, path, args...)
command.Env = append(os.Environ(), "PYTHONUNBUFFERED=1", "WORMHOLE_QR=0")
command.WaitDelay = time.Second
if received {
command.Dir = w.downloads
}
command.Stdin = strings.NewReader(text)
output := &boundedOutput{}
command.Stdout = output
stderr, err := command.StderrPipe()
if err != nil {
cancel()
return err
}
if err = command.Start(); err != nil {
cancel()
return err
}
job := &transfer{cancel: cancel, received: received, status: "Waiting for receiver", copyCode: w.preferences.CopySendCode, saveText: w.preferences.SaveReceivedText}
if received {
job.status = "Waiting for sender"
}
w.job = job
w.workers.Add(1)
go func() {
defer w.workers.Done()
defer cancel()
diagnostic := &boundedOutput{}
scanner := bufio.NewScanner(stderr)
scanner.Buffer(make([]byte, 1024), 8192)
for scanner.Scan() {
line := scanner.Text()
diagnostic.Write(append(scanner.Bytes(), '\n'))
if strings.HasPrefix(line, "Wormhole code is:") {
code := strings.TrimSpace(strings.TrimPrefix(line, "Wormhole code is:"))
if validCode(code) {
w.mutex.Lock()
job.code = code
w.mutex.Unlock()
}
}
}
if scanner.Err() != nil {
command.Process.Kill()
io.Copy(io.Discard, stderr)
}
err := command.Wait()
data, overflow := output.result()
w.mutex.Lock()
defer w.mutex.Unlock()
job.diagnostic, _ = diagnostic.result()
job.done = true
if job.cancelled || jobCtx.Err() != nil {
job.status = "Wormhole transfer cancelled"
return
}
if err != nil {
job.status = "Wormhole transfer failed. Check the code, connection, and whether the destination already exists"
return
}
if overflow {
job.status = "The received text message is too large to read or copy"
return
}
if received && data != "" {
decoded, err := decodeMessage(strings.TrimSuffix(data, "\n"))
if err != nil || len(decoded) > 8000 {
job.status = "The received text message is too large or invalid"
return
}
job.hasMessage = true
job.output = decoded
job.status = "Received text message"
} else if received {
job.status = "Wormhole transfer received in Downloads"
} else {
job.status = "Wormhole transfer complete"
}
}()
return nil
}
func (w *wormhole) transferForm() tentacle.Interaction {
title := "Wormhole transfer. " + w.job.status
return tentacle.Interaction{Form: &tentacle.Form{Title: title, Elements: []tentacle.Element{{ID: "controls", Label: "Transfer controls", Kind: tentacle.List, Items: []tentacle.ListItem{
{ID: "status", Label: "Read transfer status"}, {ID: "copy-code", Label: "Copy code"}, {ID: "cancel", Label: "Cancel transfer"},
}}}}, Next: "control", Poll: "poll"}
}
func (w *wormhole) poll(ctx context.Context, _ json.RawMessage) (any, error) {
w.mutex.Lock()
defer w.mutex.Unlock()
if ctx.Err() != nil {
return nil, ctx.Err()
}
if w.job == nil {
return tentacle.Interaction{Done: true}, nil
}
job := w.job
if job.code != "" && !job.reportedCode {
job.reportedCode = true
result := message("Wormhole code: " + job.code)
if job.copyCode {
code := job.code
result.Clipboard = &code
}
return result, nil
}
if job.done {
result := message(job.status)
if job.hasMessage {
result = message("Received text message: " + spokenText(job.output))
if job.output == "" {
result = message("Received empty text message")
}
if job.saveText {
result.Clipboard = &job.output
}
}
result.Done = true
w.job = nil
return result, nil
}
return tentacle.Interaction{}, nil
}
func (w *wormhole) control(ctx context.Context, raw json.RawMessage) (any, error) {
value, err := submission(raw)
if err != nil {
return nil, err
}
w.mutex.Lock()
defer w.mutex.Unlock()
if w.job == nil {
return message("No Wormhole transfer is running"), nil
}
if ctx.Err() != nil {
return nil, ctx.Err()
}
if value.Cancelled || value.Activated == "cancel" {
w.job.cancelled = true
w.job.cancel()
w.job = nil
result := message("Wormhole transfer cancelled")
result.Done = true
return result, nil
}
result := w.transferForm()
if value.Activated == "copy-code" {
if w.job.code == "" {
result.Presentation = message("The Wormhole code is not ready yet").Presentation
} else {
code := w.job.code
result.Clipboard = &code
result.Presentation = message("Wormhole code: " + w.job.code).Presentation
}
} else {
status := w.job.status
if w.job.code != "" {
status = fmt.Sprintf("Wormhole code: %s. %s", w.job.code, status)
}
result.Presentation = message(status).Presentation
}
return result, nil
}
func spokenText(text string) string {
return strings.Map(func(r rune) rune {
if unicode.IsControl(r) && r != '\n' && r != '\t' {
return ' '
}
return r
}, text)
}
// The reference CLI prints repr(message)[1:-1]. Decode that representation
// without evaluating Python or interpreting any received text as code.
func decodeMessage(text string) (string, error) {
var output strings.Builder
for index := 0; index < len(text); index++ {
if text[index] != '\\' {
output.WriteByte(text[index])
continue
}
index++
if index >= len(text) {
return "", errors.New("trailing escape")
}
switch text[index] {
case '\\', '\'', '"':
output.WriteByte(text[index])
case 'n':
output.WriteByte('\n')
case 'r':
output.WriteByte('\r')
case 't':
output.WriteByte('\t')
case 'a':
output.WriteByte(7)
case 'b':
output.WriteByte(8)
case 'f':
output.WriteByte(12)
case 'v':
output.WriteByte(11)
case 'x', 'u', 'U':
width := 2
if text[index] == 'u' {
width = 4
}
if text[index] == 'U' {
width = 8
}
if index+width >= len(text) {
return "", errors.New("short escape")
}
raw := text[index+1 : index+1+width]
if _, err := hex.DecodeString(raw); err != nil {
return "", err
}
number, err := strconv.ParseUint(raw, 16, 32)
if err != nil || !utf8.ValidRune(rune(number)) {
return "", errors.New("invalid character")
}
output.WriteRune(rune(number))
index += width
default:
output.WriteByte('\\')
output.WriteByte(text[index])
}
}
result := output.String()
if !utf8.ValidString(result) {
return "", errors.New("invalid UTF-8")
}
return result, nil
}
+121
View File
@@ -0,0 +1,121 @@
package main
import (
"context"
sdk "git.stormux.org/storm/cthulhu/sdk/go/tentacle"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
)
// Opt-in because it contacts Magic Wormhole's public rendezvous/transport relay.
// Only synthetic fixture data is sent; both endpoints and downloads are private
// test instances. It does not use the user's clipboard or active reader.
func TestRealWormholeTransfers(t *testing.T) {
if os.Getenv("CTHULHU_WORMHOLE_NETWORK_TEST") != "1" {
t.Skip("requires explicit real-relay check")
}
program, err := exec.LookPath("wormhole")
if err != nil {
t.Skip("Magic Wormhole not installed")
}
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
defer cancel()
sender := &wormhole{program: program, downloads: t.TempDir(), preferences: preferences{CopySendCode: true}}
receiver := &wormhole{program: program, downloads: t.TempDir(), preferences: preferences{SaveReceivedText: true}}
defer func() { cancel(); sender.workers.Wait(); receiver.workers.Wait() }()
exchange := func(item sdk.Item) sdk.Interaction {
t.Helper()
raw, err := sender.send(ctx, arguments(sdk.Submission{Item: &item}))
if err != nil || raw.(sdk.Interaction).Form == nil {
t.Fatal(raw, err)
}
sender.mutex.Lock()
job := sender.job
sender.mutex.Unlock()
code := ""
for code == "" {
raw, err = sender.poll(ctx, nil)
if err != nil {
t.Fatal("sender code", err)
}
result := raw.(sdk.Interaction)
if result.Clipboard != nil {
code = *result.Clipboard
}
if result.Done {
sender.mutex.Lock()
detail := job.diagnostic
sender.mutex.Unlock()
t.Fatal("sender failed before code", result.Speech, detail)
}
select {
case <-ctx.Done():
t.Fatal("relay did not produce a code", ctx.Err())
case <-time.After(20 * time.Millisecond):
}
}
raw, err = receiver.receive(ctx, arguments(sdk.Submission{Values: map[string]sdk.Value{"code": {Text: code}}}))
if err != nil || raw.(sdk.Interaction).Form == nil {
t.Fatal(raw, err)
}
var received sdk.Interaction
sendingDone := false
for !received.Done || !sendingDone {
if !received.Done {
raw, err = receiver.poll(ctx, nil)
if err != nil {
t.Fatal(err)
}
received = raw.(sdk.Interaction)
}
if !sendingDone {
raw, err = sender.poll(ctx, nil)
if err != nil {
t.Fatal(err)
}
result := raw.(sdk.Interaction)
sendingDone = result.Done
if sendingDone && result.Speech != "Wormhole transfer complete" {
t.Fatal("sender", result.Speech)
}
}
if received.Done && strings.Contains(received.Speech, "failed") {
t.Fatal("receiver", received.Speech)
}
select {
case <-ctx.Done():
t.Fatal("transfer timed out", ctx.Err())
case <-time.After(20 * time.Millisecond):
}
}
return received
}
text := "Synthetic Wormhole text\nSecond line: é猫 and \\n literal"
if result := exchange(sdk.Item{Text: text}); result.Clipboard == nil || *result.Clipboard != text {
t.Fatalf("text changed: %+v", result)
}
source := t.TempDir()
file := filepath.Join(source, "one file.txt")
if err = os.WriteFile(file, []byte("Synthetic file contents\n"), 0600); err != nil {
t.Fatal(err)
}
if result := exchange(sdk.Item{Path: file}); result.Clipboard != nil || result.Speech != "Wormhole transfer received in Downloads" {
t.Fatal(result)
}
data, err := os.ReadFile(filepath.Join(receiver.downloads, "one file.txt"))
if err != nil || string(data) != "Synthetic file contents\n" {
t.Fatal(string(data), err)
}
folder := filepath.Join(source, "one folder")
os.MkdirAll(folder, 0700)
os.WriteFile(filepath.Join(folder, "nested.txt"), []byte("Synthetic folder contents\n"), 0600)
exchange(sdk.Item{Path: folder})
data, err = os.ReadFile(filepath.Join(receiver.downloads, "one folder", "nested.txt"))
if err != nil || string(data) != "Synthetic folder contents\n" {
t.Fatal(string(data), err)
}
}
+264
View File
@@ -0,0 +1,264 @@
package main
import (
"context"
"encoding/json"
"git.stormux.org/storm/cthulhu/sdk/go/tentacle"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func arguments(value any) json.RawMessage { data, _ := json.Marshal(value); return data }
func testWormhole(t *testing.T, script string) *wormhole {
t.Helper()
directory := t.TempDir()
program := filepath.Join(directory, "fake-wormhole")
if err := os.WriteFile(program, []byte("#!/bin/sh\n"+script), 0700); err != nil {
t.Fatal(err)
}
w := &wormhole{program: program, downloads: filepath.Join(directory, "Downloads"), settingsPath: filepath.Join(directory, "config", "wormhole.json")}
t.Cleanup(func() {
w.mutex.Lock()
if w.job != nil {
w.job.cancel()
}
w.mutex.Unlock()
w.workers.Wait()
})
return w
}
func completed(t *testing.T, w *wormhole) tentacle.Interaction {
t.Helper()
deadline := time.Now().Add(3 * time.Second)
for time.Now().Before(deadline) {
raw, err := w.poll(context.Background(), nil)
if err != nil {
t.Fatal(err)
}
result := raw.(tentacle.Interaction)
if result.Done {
return result
}
time.Sleep(time.Millisecond)
}
t.Fatal("transfer did not complete")
return tentacle.Interaction{}
}
func TestMenuPreferencesAndMissingDependency(t *testing.T) {
w := testWormhole(t, "exit 0\n")
raw, err := w.open(context.Background(), nil)
if err != nil {
t.Fatal(err)
}
result := raw.(tentacle.Interaction)
if result.Form.Title != "Wormhole menu" || len(result.Form.Elements[0].Items) != 4 {
t.Fatal(result)
}
if w.preferences.SaveReceivedText || w.preferences.CopySendCode {
t.Fatal("preferences should default off")
}
prefs := tentacle.Submission{Activated: "save", Values: map[string]tentacle.Value{"save-text": {Checked: true}, "copy-code": {Checked: true}}}
if _, err = w.savePreferences(context.Background(), arguments(prefs)); err != nil {
t.Fatal(err)
}
data, err := os.ReadFile(w.settingsPath)
if err != nil {
t.Fatal(err)
}
var saved preferences
if json.Unmarshal(data, &saved) != nil || !saved.SaveReceivedText || !saved.CopySendCode {
t.Fatal(saved)
}
info, _ := os.Stat(w.settingsPath)
if info.Mode().Perm() != 0600 {
t.Fatal("settings are not private")
}
prefs.Cancelled = true
prefs.Values = nil
w.savePreferences(context.Background(), arguments(prefs))
if !w.preferences.CopySendCode {
t.Fatal("Cancel changed preferences")
}
w.program = filepath.Join(t.TempDir(), "missing")
raw, err = w.open(context.Background(), nil)
result = raw.(tentacle.Interaction)
if err != nil || result.Speech != "Magic wormhole is not installed" || !result.Uninterruptible {
t.Fatal(result, err)
}
}
func TestRegisteredSettingsAndDefaultShortcut(t *testing.T) {
w := testWormhole(t, "exit 0\n")
w.program = filepath.Join(t.TempDir(), "missing")
settings := 0
for _, command := range w.commands() {
if command.ID == "wormhole" {
if len(command.Bindings) != 2 {
t.Fatal(command.Bindings)
}
for index, layout := range []string{"desktop", "laptop"} {
binding := command.Bindings[index]
if binding.Layout != layout || binding.Scope != "global" || binding.Key != "Cthulhu+Ctrl+Shift+W" {
t.Fatal(binding)
}
}
}
if !command.Settings {
continue
}
settings++
value, err := command.Handle(context.Background(), nil)
if err != nil {
t.Fatal(err)
}
form := value.(tentacle.Interaction)
if !command.Interaction || !command.Presentation || form.Form.Title != "Wormhole preferences" || form.Next != "save-settings" {
t.Fatal(command, form)
}
}
if settings != 1 {
t.Fatalf("settings entry points: %d", settings)
}
value, err := w.saveSettings(context.Background(), arguments(tentacle.Submission{Activated: "save", Values: map[string]tentacle.Value{"copy-code": {Checked: true}}}))
if err != nil {
t.Fatal(err)
}
result := value.(tentacle.Interaction)
if !result.Done || result.Form != nil || result.Next != "" || !w.preferences.CopySendCode {
t.Fatal(result)
}
data, err := os.ReadFile(w.settingsPath)
var saved preferences
if err != nil || json.Unmarshal(data, &saved) != nil || !saved.CopySendCode {
t.Fatal("settings did not persist", err)
}
_, err = w.saveSettings(context.Background(), arguments(tentacle.Submission{Cancelled: true}))
if err != nil || !w.preferences.CopySendCode {
t.Fatal("Cancel changed saved settings", err)
}
}
func TestSendPreservesClipboardTextAndCodePreference(t *testing.T) {
for _, copyCode := range []bool{false, true} {
t.Run(map[bool]string{false: "read-only", true: "copy-code"}[copyCode], func(t *testing.T) {
directory := t.TempDir()
capture := filepath.Join(directory, "sent")
// Use env-free literal single quoting for a temporary path controlled by the test.
w := testWormhole(t, "[ \"$1\" = send ] || exit 8\n[ \"$4\" = --text ] || exit 9\ncat > '"+capture+"'\nprintf 'Wormhole code is: 7-alpha-beta\\n' >&2\nsleep 0.1\n")
w.preferences.CopySendCode = copyCode
text := "one\ntwo\\three é猫"
raw, err := w.send(context.Background(), arguments(tentacle.Submission{Item: &tentacle.Item{Text: text}}))
if err != nil || raw.(tentacle.Interaction).Poll != "poll" {
t.Fatal(raw, err)
}
deadline := time.Now().Add(2 * time.Second)
for {
raw, err = w.poll(context.Background(), nil)
if err != nil {
t.Fatal(err)
}
result := raw.(tentacle.Interaction)
if result.Speech != "" {
if result.Speech != "Wormhole code: 7-alpha-beta" || (result.Clipboard != nil) != copyCode {
t.Fatal(result)
}
break
}
if time.Now().After(deadline) {
t.Fatal("code not announced")
}
time.Sleep(time.Millisecond)
}
if got := completed(t, w).Speech; got != "Wormhole transfer complete" {
t.Fatal(got)
}
data, err := os.ReadFile(capture)
if err != nil || string(data) != text {
t.Fatalf("sent=%q %v", data, err)
}
})
}
}
func TestReceiveTextPreferenceAndExactDecode(t *testing.T) {
for _, saveText := range []bool{false, true} {
w := testWormhole(t, "[ \"$1\" = receive ] || exit 8\nprintf '%s\\n' 'one\\ntwo\\\\three é猫'\n")
w.preferences.SaveReceivedText = saveText
raw, err := w.receive(context.Background(), arguments(tentacle.Submission{Values: map[string]tentacle.Value{"code": {Text: "7-alpha-beta"}}}))
if err != nil || raw.(tentacle.Interaction).Form == nil {
t.Fatal(raw, err)
}
result := completed(t, w)
expected := "one\ntwo\\three é猫"
if result.Speech != "Received text message: "+expected || (result.Clipboard != nil) != saveText {
t.Fatal(result)
}
if result.Clipboard != nil && *result.Clipboard != expected {
t.Fatal("clipboard was not exact")
}
}
}
func TestReceiveFilesDownloadsFailureAndCancellation(t *testing.T) {
w := testWormhole(t, "pwd > received.txt\n")
raw := arguments(tentacle.Submission{Values: map[string]tentacle.Value{"code": {Text: "7-alpha-beta"}}})
w.receive(context.Background(), raw)
if result := completed(t, w); result.Speech != "Wormhole transfer received in Downloads" || result.Clipboard != nil {
t.Fatal(result)
}
data, err := os.ReadFile(filepath.Join(w.downloads, "received.txt"))
if err != nil || strings.TrimSpace(string(data)) != w.downloads {
t.Fatal(string(data), err)
}
failure := testWormhole(t, "exit 12\n")
failure.receive(context.Background(), raw)
if result := completed(t, failure); !strings.Contains(result.Speech, "failed") {
t.Fatal(result)
}
cancelled := testWormhole(t, "exec sleep 30\n")
cancelled.receive(context.Background(), raw)
result, err := cancelled.control(context.Background(), arguments(tentacle.Submission{Cancelled: true}))
if err != nil || result.(tentacle.Interaction).Speech != "Wormhole transfer cancelled" {
t.Fatal(result, err)
}
joined := make(chan struct{})
go func() { cancelled.workers.Wait(); close(joined) }()
select {
case <-joined:
case <-time.After(2 * time.Second):
t.Fatal("cancel left child running")
}
}
func TestMessageDecode(t *testing.T) {
cases := map[string]string{`line\nsecond`: "line\nsecond", `slash\\n`: `slash\n`, `it\'s`: "it's", `é\x00\u200b\U0001f600`: "é\x00\u200b😀"}
for input, expected := range cases {
got, err := decodeMessage(input)
if err != nil || got != expected {
t.Fatalf("%q => %q %v", input, got, err)
}
}
for _, input := range []string{`bad\`, `bad\x1`, `bad\uZZZZ`, `bad\Uffffffff`} {
if _, err := decodeMessage(input); err == nil {
t.Fatal("accepted", input)
}
}
}
func TestRejectUnavailableFilesAndInvalidCodes(t *testing.T) {
w := testWormhole(t, "exit 0\n")
for _, code := range []string{"", "--help", "a-alpha-beta", "7-alpha-", "7-alpha;touch-x"} {
result, err := w.receive(context.Background(), arguments(tentacle.Submission{Values: map[string]tentacle.Value{"code": {Text: code}}}))
if err != nil || result.(tentacle.Interaction).Speech != "Invalid Wormhole code" {
t.Fatal(result, err)
}
}
if _, err := localPath("file://remote/thing"); err == nil {
t.Fatal("accepted remote URI")
}
if _, err := localPath("relative"); err == nil {
t.Fatal("accepted guessed relative path")
}
raw, err := w.send(context.Background(), arguments(tentacle.Submission{Item: &tentacle.Item{Path: "/this/file/does/not/exist"}}))
if err != nil || raw.(tentacle.Interaction).Speech != "The file or folder path is unavailable" {
t.Fatal(raw, err)
}
}
+23
View File
@@ -0,0 +1,23 @@
format-version = 1
id = "wormhole"
name = "Wormhole"
description = "Send a focused line or clipboard item and receive files, folders, and text with Magic Wormhole."
version = "0.1.2"
authors = ["Storm Dragon"]
license = "GPL-3.0-or-later"
source = "https://git.stormux.org/storm/cthulhu-tentacles"
help = "README.md"
runtime = "native"
platforms = ["linux"]
entry-point = ["bin/wormhole-tentacle"]
apis = ["commands", "presentation", "interaction"]
capabilities = ["presentation", "interaction"]
[protocol]
major = 1
minor = 0
[requirements]
reader = "Cthulhu with interactive Tentacle settings support"
runtime = "Magic Wormhole CLI (wormhole); xclip for clipboard operations"
build = "Go 1.24 or newer and the adjacent cthulhu source checkout"