diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c61011c..8ab98cd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,10 +2,11 @@ name: CI on: push: - branches: [main] + branches: ["**"] tags: ["v*"] pull_request: branches: [main] + workflow_dispatch: permissions: contents: read @@ -16,12 +17,42 @@ jobs: runs-on: macos-26 steps: - name: Check out repository - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Check formatting run: make lint + - name: Generate version + run: bash Scripts/generate-version.sh - name: Run tests run: swift test + build-cli-artifact: + name: Build downloadable CLI archive + if: github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && !startsWith(github.ref, 'refs/tags/')) + needs: test + runs-on: macos-26 + steps: + - name: Check out selected branch + uses: actions/checkout@v5 + - name: Build CLI archive + run: Scripts/package-cli.sh + - name: Test installed archive + shell: bash + run: | + prefix="$RUNNER_TEMP/nyathing-prefix" + config="$RUNNER_TEMP/nyathing-config" + mkdir -p "$prefix" "$config" + PREFIX="$prefix" bash out/nyathing-macos-arm64/install.sh + XDG_CONFIG_HOME="$config" "$prefix/bin/nyathing" list + test -x "$prefix/libexec/nyathing/nyathing" + test -d "$prefix/libexec/nyathing/Nyathing_Nyathing.bundle" + - name: Upload CLI archive + uses: actions/upload-artifact@v6 + with: + name: nyathing-macos-arm64 + path: out/nyathing-macos-arm64/* + if-no-files-found: error + retention-days: 14 + release: name: Build and publish tagged release if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') @@ -31,7 +62,7 @@ jobs: contents: write steps: - name: Check out repository - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: fetch-depth: 0 - name: Validate release tag and target branch @@ -49,16 +80,14 @@ jobs: exit 1 fi echo "value=${tag#v}" >> "$GITHUB_OUTPUT" - - name: Build installer package - env: - VERSION: ${{ steps.version.outputs.value }} - run: Scripts/build-pkg.sh + - name: Build CLI archive + run: Scripts/package-cli.sh - name: Publish GitHub Release - uses: softprops/action-gh-release@v2 + uses: softprops/action-gh-release@v3 with: tag_name: ${{ github.ref_name }} target_commitish: ${{ github.sha }} name: Nyathing ${{ steps.version.outputs.value }} generate_release_notes: true - files: out/Nyathing-${{ steps.version.outputs.value }}.pkg + files: out/nyathing-macos-arm64.tar.gz fail_on_unmatched_files: true diff --git a/.gitignore b/.gitignore index 2ac4997..5fe770c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ .agents/ .build/ +Sources/Nyathing/Version.swift .swiftpm/ out/ dist/ diff --git a/Makefile b/Makefile index cbeaa02..1654c1b 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ SHELL := /bin/bash .DEFAULT_GOAL := help -.PHONY: help format lint test package run install-app install-cli-link uninstall +.PHONY: help format lint test archive run install uninstall reinstall help: @printf '%s\n' \ @@ -9,11 +9,11 @@ help: ' format Format Swift files in Sources/ and Tests/' \ ' lint Check Swift formatting' \ ' test Run the Swift test suite' \ - ' package Build the macOS installer package' \ - ' run Run animations for five seconds (ANIMATIONS="a b" optional)' \ - ' install-app Build and install Nyathing.app in /Applications' \ - ' install-cli-link Create the /usr/local/bin/nyathing symlink' \ - ' uninstall Force-remove the app, CLI command, and user data' + ' archive Build a downloadable CLI archive' \ + ' run Run animations (DURATION=5 seconds; ANIMATIONS="a b" optional)' \ + ' install Build and install the CLI in $(PREFIX)/bin' \ + ' uninstall Remove the CLI and legacy app (keeps user data)' \ + ' reinstall Reinstall Nyathing using the selected PREFIX' format: @find Sources Tests -type f -name '*.swift' -print0 | xargs -0 swift format format --in-place @@ -24,18 +24,21 @@ lint: test: swift test -package: - Scripts/build-pkg.sh +archive: + bash Scripts/package-cli.sh -install-app: - bash Scripts/install-app.sh +PREFIX ?= /usr/local -install-cli-link: - bash Scripts/install-cli-link.sh +install: + PREFIX='$(PREFIX)' bash Scripts/install.sh uninstall: - bash Scripts/force-uninstall.sh + PREFIX='$(PREFIX)' bash Scripts/force-uninstall.sh + +reinstall: uninstall install + +DURATION ?= 5 run: swift build - ANIMATION='$(ANIMATION)' ANIMATIONS='$(ANIMATIONS)' python3 Scripts/run-test-animation.py + ANIMATION='$(ANIMATION)' ANIMATIONS='$(ANIMATIONS)' DURATION='$(DURATION)' python3 Scripts/run-test-animation.py diff --git a/README.md b/README.md index 1678537..45e8f5d 100644 --- a/README.md +++ b/README.md @@ -9,47 +9,95 @@ Nyathing brings background processes to life with playful animations in the macOS menu bar. Clients start an animation when work begins and stop it when the task is done. -## Install - -Download the installer package from the repository's **Releases** page. Open -the package and follow the Installer prompts to install `Nyathing.app` in -`/Applications`. The installer also creates the `/usr/local/bin/nyathing` -command symlink and requests administrator authorization to make these -system-wide changes. - -To remove the installed app and command, run in terminal: +## Contents + +- [↓ Install from archive](#-install-from-archive) +- [⚒︎ Build from source](#-build-from-source) +- [▤ Nyathing server](#-nyathing-server) + - [Launch at login](#launch-at-login) +- [⌘ Nyathing client](#-nyathing-client) + - [How to choose an animation](#how-to-choose-an-animation) + - [Describe a client](#describe-a-client) +- [>_ Nyathing CLI](#-nyathing-cli) +- [❯ Shell completion](#-shell-completion) +- [⚙︎ Configuration](#-configuration) +- [▦ Animation file format](#-animation-file-format) +- [⇄ Server communication protocol](#-server-communication-protocol) +- [✦ Examples](#-examples) + - [Minimal Python client example](#-minimal-python-client-example) + - [Coding-agent integrations](#-coding-agent-integrations) + - [Codex](#-codex) + - [Claude Code](#-claude-code) +- [⚡︎ Troubleshooting](#-troubleshooting) + +## ↓ Install from archive + +Download `nyathing-macos-arm64.tar.gz` from the latest GitHub Release, then +extract and install it: ```sh -nyathing uninstall +mkdir -p "$HOME/.local/share/nyathing-archive" +tar -xzf ~/Downloads/nyathing-macos-arm64.tar.gz \ + -C "$HOME/.local/share/nyathing-archive" +cd "$HOME/.local/share/nyathing-archive" +PREFIX="$HOME/.local" ./install.sh ``` -Uninstall requests administrator authorization. It asks -`Remove Nyathing configuration and user animations? [y/N]`; the default is no. -Answering no preserves configuration and animations while still removing the -app and CLI symlink. The app is closed as part of removal. - -If the built-in uninstall does not complete, run `make uninstall` from the -repository root. This force-removal fallback requires administrator -authorization and removes the app, CLI command, configuration, and logs. +This installs the command in `~/.local/bin` and the executable and resources +under `~/.local/libexec/nyathing`. Add `~/.local/bin` to your `PATH` if needed. +To uninstall, run `PREFIX="$HOME/.local" ./uninstall.sh` from the extracted +archive. User configuration and animations are kept in `~/.config/nyathing` (or +`$XDG_CONFIG_HOME/nyathing`). **👮🏻‍♂️ Note** -The app and package are **unsigned** and not notarized, so macOS may block the -app because it was downloaded from the internet. If macOS blocks it, try opening -the app once, then allow it in **System Settings → Privacy & Security**: +Nyathing is **unsigned** and not notarized, so macOS may block it because it +was downloaded from the internet. If macOS blocks Nyathing, try running it once +from Terminal, then allow it in **System Settings → Privacy & Security**: 1. Open **System Settings** and select **Privacy & Security**. 2. Scroll to the **Security** section. 3. Click **Open Anyway** next to the message about Nyathing being blocked, - then confirm when prompted. + then confirm when prompted. This option may only appear for app launches. + +The **Open Anyway** option may appear after you try to open the app; it may +not be available for a CLI binary. You may need to enter your password or +confirm with Touch ID. + +Alternatively, build and run Nyathing locally using the instructions in +[Build from source](#build-from-source); locally built binaries are not quarantined. -The **Open Anyway** option appears after you try to open the app. You may need -to enter your password or confirm with Touch ID. +## ⚒︎ Build from source + +Requires macOS 12+ and Swift 5.9 or later. From the repository root, install +the CLI in `/usr/local/bin` with: + +```sh +make install +``` + +The installer builds Nyathing and asks for administrator authorization to +install the command in `/usr/local/bin` and the executable and resources under +`/usr/local/libexec/nyathing`. To install under +your home directory instead, without administrator authorization, run: + +```sh +make install PREFIX="$HOME/.local" +``` + +This installs the command in `~/.local/bin`; add that directory to your `PATH` +if needed. To uninstall from that prefix, pass it again: + +```sh +make uninstall PREFIX="$HOME/.local" +``` -Alternatively, build and run `Nyathing` locally using the instructions in -[Build from source](#build-from-source); locally built apps are not quarantined. +Without a custom prefix, use `make uninstall` to remove the default installation +from `/usr/local/bin`. Uninstall keeps user configuration and animations. -## Nyathing server +## ▤ Nyathing server + +

nyathing-server

Nyathing exposes a local API over a Unix domain stream socket. The socket path is `$XDG_RUNTIME_DIR/nyathing.sock` when `XDG_RUNTIME_DIR` is set; otherwise it is @@ -59,45 +107,126 @@ current user, and the server checks the connecting process's user ID. Exchange UTF-8 JSON Lines: send one JSON object followed by a newline (`\n`); Nyathing returns one JSON object followed by a newline for each request. A connection can carry multiple request/response pairs, and multiple clients may -connect at the same time. Request lines are limited to 1 MiB. +connect at the same time. + +For convenience, Nyathing also implements the client side of the protocol. See +[Nyathing client](#nyathing-client) for details. + +For the complete message formats, field requirements, and response schemas, +see [Server communication protocol](#server-communication-protocol). + +### Launch at login + +In the **Edit Configuration** window, enable **Launch Nyathing at login** and +click **Accept**. Nyathing installs its own LaunchAgent in +`~/Library/LaunchAgents`; it will start automatically at your next login. No +manual `launchctl` commands are needed. + +Disable **Launch Nyathing at login** in **Edit Configuration** and click +**Accept** to remove the LaunchAgent. If you move +`Nyathing.app`, enable auto-start again and click **Accept** so the LaunchAgent +records the app's new location. -Commands: +## ⌘ Nyathing client -- Start an activity: `{"command":"start","animation":"nyan_54x36.png"}` - returns `{"ok":true,"activity_id":"…"}`. The animation is identified by - its filename. The `animation` field is optional; when omitted, Nyathing uses - the animation selected by `default_animation` in `config.toml`. If a - requested animation is unavailable or invalid, Nyathing uses the built-in - ghost animation. -- Refresh a running activity: `{"command":"keepalive","activity_id":"…"}` - returns `{"ok":true}` and resets its expiration timer. -- End an activity: `{"command":"stop","activity_id":"…"}` returns - `{"ok":true}` and does not count as a disconnect. +

nyathing-client

-Errors return `{"ok":false,"error":"…"}`. This includes malformed requests, -unknown commands, and unknown activity IDs. Send keepalives periodically; the -activity expires after `activity_timeout_seconds` without one. Expiration -increments the disconnected-client count and plays `explosion_36x36.png` when -available. Explicitly stopping an activity does not count as a disconnect. -Use **Reset Disconnected Count** in the menu to clear the count. +For convenience, Nyathing includes a client for communicating with the server +without having to implement the protocol yourself. -## Run terminal commands with Nyathing +Use `client` commands to control an activity without wrapping a process: + +```sh +nyathing client start +``` + +The server starts automatically if it is not already running. +On `start` Nyathing prints the activity ID. + +You can provide an ID with `--activity-id`. Starting an active or reserved ID +fails with an error: + +```sh +nyathing client start --activity-id "$(uuidgen)" +``` -Run a command with `nyathing` to display an animation while it runs. Nyathing -starts the activity, keeps it alive while the command runs, then stops it. +Send `keepalive` at least once per requested interval (5 seconds by default) to +keep animation, and use `stop` when done. + +```sh +nyathing client keepalive ACTIVITY_ID +nyathing client stop ACTIVITY_ID +``` + +Abandoned activities expire according to `max_wait_time` (see [Configuration](#-configuration)). +The command `start` also accepts `--keepalive-interval SECONDS` to override the +default for that activity. + +### How to choose an animation + +You can explicitly specify an animation on start: + +```sh +nyathing client start --animation nyan --description "Test" +``` + +`--animation` (or `-a`) selects an animation. A short name without the frame +size suffix or `.png` (for example, `nyan`) is looked up in Nyathing's user +animation directory. If multiple valid files share that name, Nyathing chooses +the frame with the largest pixel area. Any other value is treated as a path to +an animation file; relative paths are resolved from the current directory. +See [Animation file format](#-animation-file-format) for more details about file format. +Without `--animation`, a configured default animation is used. + +Set `--animation` to `random` to choose a random valid animation from the user +animations directory for that run. + +```sh + nyathing --animation random sleep 5 +``` + +If valid files named `random_x.png` exist, Nyathing plays the +largest matching animation. Otherwise, it chooses randomly from valid user +animations. If none are available, Nyathing uses its built-in ghost animation. + +Quote paths containing spaces as usual in your shell. Relative command paths +are resolved from the current working directory. + +### Describe a client + +Active animations appear in the menu with a shortened version of their +descriptions. Add a description when starting a client to make it easier to +identify the activity: + +```sh +nyathing client start --description "Running tests" +``` + +## >_ Nyathing CLI + +

nyathing-cli

+ +Nyathing provides a command-line utility for wrapping long-running terminal +commands in an animation. For example, show an animation while waiting five seconds, with or without a custom animation: ```sh nyathing sleep 5 - nyathing --animation nyan_54x36.png sleep 5 + nyathing --animation nyan sleep 5 ``` -`--animation` (or `-a`) selects an animation from Nyathing's user animation -directory. Without it, the CLI uses `nyathing_36x36.png`, regardless of the -configured server default. Quote paths containing spaces as usual in your shell. -Relative command paths are resolved from the current working directory. +The activity description is the command and its arguments (for example, +`sleep 5`). While the command runs, Nyathing sends a keepalive every 5 seconds +to keep the animation active. It stops when the command exits, or expires if +keepalives stop arriving. + +To get a list of valid installed animations by short name use: + +```sh + nyathing list +``` To view available options or check the installed version: @@ -106,15 +235,30 @@ To view available options or check the installed version: nyathing --version ``` -## Animation file format +## ❯ Shell completion + +Nyathing can generate completion scripts for Zsh and Bash. Add the appropriate +command to your shell configuration file to enable completion in new shells. + +For Zsh, add this to `~/.zshrc`: + +```sh + autoload -Uz compinit + compinit + eval "$(nyathing completion zsh)" +``` + +For Bash, add this to `~/.bashrc`: + +```sh + eval "$(nyathing completion bash)" +``` -Animation files are single horizontal PNG sprite sheets. Supported frame sizes -are 36x36 and 54x36 pixels; image height must equal the frame height and image -width must be a positive multiple of it. Name files with the frame size suffix, -for example `nyan_54x36.png`. The app validates assets on startup and reload; -invalid assets are ignored and logged. Playback runs at 10 frames per second. +The completion script offers Nyathing commands and options, including server +subcommands. It fetches available animations with `nyathing list` when +completing an animation argument, so the suggestions reflect installed files. -## Configuration +## ⚙︎ Configuration On first launch, Nyathing creates its configuration directory and adds these built-in animations: @@ -133,26 +277,182 @@ your files. The complete initial configuration is: ```toml -# Seconds between client keepalive messages; must be greater than zero. -keepalive_interval_seconds = 5 -# Seconds without a keepalive before an activity expires; must be greater than zero. -activity_timeout_seconds = 5 +# Maximum seconds to wait since the last client keepalive. +max_wait_time = 180 # Whether to launch Nyathing automatically when you log in. auto_start = false -# Animation filename used when a client omits the animation field. -default_animation = "nyathing_36x36.png" +# Animation name, PNG path, or "random" used when a client omits the animation field. +default_animation = "nyathing" ``` -Keep all four settings in your `config.toml`; Nyathing does not fill in omitted -settings. Set `auto_start` to `true` or `false`; both durations must be positive -numbers. Set `default_animation` to the filename of a valid animation in the -`animations/` directory. Requests with an explicit animation use it; missing or -unavailable requested animations fall back to the built-in ghost. -Use **Reload Configuration and Animations** in the menu after changing -configuration or animation files. Reload clears active client activities and -the disconnected-client count. +Keep all three settings in your `config.toml`; Nyathing does not fill in omitted +settings. Set `max_wait_time` to a positive number of seconds and `auto_start` +to `true` or `false`. Clients use a default keepalive interval of 5 seconds, +which they can override per activity. Activities expire after the smaller of +twice that interval and `max_wait_time`. Like `--animation`, `default_animation` +accepts a short name such as `nyathing`, a filename in `animations/`, a PNG path, +or `random` to select an animation per activity. Relative paths in `config.toml` +are resolved beside that file; CLI paths are relative to the working directory. +An explicit `-a` or `--animation` skips `default_animation` validation. +An invalid explicit selection fails instead of falling back. The configured +default is checked only when an activity starts without an animation. +Choose **Edit Configuration** from the menu to change these settings with +visual controls. **Choose PNG…** lets you select a file outside `animations/` +and saves its full path. **Accept** applies the new default animation and wait +limit to future activities without interrupting running ones. **Cancel** closes +the editor without applying changes. + +## ▦ Animation file format + +Animation files are horizontal PNG sprite sheets. The filename suffix declares +the dimensions of each frame, for example `nyan_64x48.png`. Each dimension must +be between 16 and 256 pixels, with an aspect ratio no greater than 3:1. The +image height must match the declared frame height, and its width must be a +positive multiple of the declared frame width. Sheets may contain at most 120 +frames and 4 million pixels total. Frames are scaled to fit the menu bar. The +app validates assets on startup and when settings are accepted; invalid assets +are ignored and logged. Playback runs at 10 frames per second. + +## ⇄ Server communication protocol + +The server communicates over a Unix domain `SOCK_STREAM` socket using UTF-8 +JSON Lines. Each message is a JSON object followed by `\n`; each request +receives exactly one response. A connection may carry multiple sequential +request/response pairs. A request line may be at most 1 MiB. The socket is +accessible only to the current user, whose identity is also checked when +connecting. + +### Request messages + +Every request has this common envelope: + +```json +{ + "command": "" +} +``` + +The `command` property is required and must be a string. The following command +messages are supported: + +| Command | Description | +| --- | --- | +| `start` | Starts an activity and returns its identifier. | +| `keepalive` | Refreshes an activity's expiration timer. | +| `stop` | Ends an activity without counting it as a disconnect. | + +#### `start` request + +| Field | Type | Required | Description | +| --- | --- | --- | --- | +| `command` | string | Yes | Must be `start`. | +| `animation` | string | No | Short name searched in the server's animation directory, or a path to a PNG sprite sheet. Defaults to the server's configured animation. Invalid explicit values return an error. | +| `description` | string | No | Description shown for the activity. If omitted or not a string, the server uses its default description. | +| `keepalive_interval_seconds` | number | No | Positive, finite interval in seconds at which the client promises to send keepalives. Defaults to 5 seconds. The activity expires after the smaller of twice this interval and the server's configured `max_wait_time`. | +| `activity_id` | string | No | Caller-provided activity ID. Must not match an active or reserved ID. If omitted, the server generates a UUID. | + +A short name without a frame-size suffix or `.png` is resolved in the server's +animation directory. Other values are treated as file paths; relative paths +are resolved from the server process's current working directory. `random` +selects a random valid animation, falling back to the built-in ghost if none +are available. + +Examples: + +```json +{"command":"start","animation":"nyan","keepalive_interval_seconds":5} +``` +or +```json +{"command":"start","animation":"nyan","description":"make test","keepalive_interval_seconds":5} +``` + +#### `keepalive` request + +| Field | Type | Required | Description | +| --- | --- | --- | --- | +| `command` | string | Yes | Must be `keepalive`. | +| `activity_id` | string | Yes | ID supplied to or returned by the corresponding `start` request. | + +Example: + +```json +{"command":"keepalive","activity_id":""} +``` + +Send keepalives periodically at the interval specified in the `start` request. +If the server does not receive one within the smaller of twice that interval +and `max_wait_time`, the activity expires and increments the +disconnected-client count. + +#### `stop` request + +| Field | Type | Required | Description | +| --- | --- | --- | --- | +| `command` | string | Yes | Must be `stop`. | +| `activity_id` | string (UUID) | Yes | Identifier returned by the corresponding `start` request. Stopping an activity does not count as a disconnect. | + +Example: + +```json +{"command":"stop","activity_id":""} +``` + +### Response messages + +A successful `start` response contains the activity identifier: + +```json +{"ok":true,"activity_id":""} +``` + +Successful `keepalive` and `stop` responses are: + +```json +{"ok":true} +``` -## Minimal Python client example +A failed request returns an error response: + +```json +{"ok":false,"error_code":"animation_cancelled","error":"Animation was cancelled."} +``` + +Use `error_code` to identify the failure in client code. The existing `error` +field is a human-readable message; angle brackets below mark variable text. +Connection and socket setup failures do not return a JSON response. + +| Code | Reason | Message template | +| --------------------------------- | ------------------------------------------------------------- | ------------------------------------------------------------------------------ | +| `invalid_request` | Malformed JSON, invalid request shape, or invalid arguments. | `Invalid JSON Lines request.` | +| `request_too_large` | The request line exceeds 1 MiB. | `Request line is too large.` | +| `unknown_command` | The command is not supported. | `Unknown command: .` | +| `invalid_keepalive_interval` | The keepalive interval is not a positive finite number. | `'keepalive_interval_seconds' must be a positive finite number of seconds.` | +| `activity_id_in_use` | The requested ID is active or reserved after cancellation. | `Activity ID "" is already in use.` | +| `unknown_activity` | The activity ID is not recognized. | `Unknown activity ID.` | +| `animation_cancelled` | A `keepalive` or `stop` targets a reserved, cancelled ID. | `Animation was cancelled.` | +| `invalid_default_animation` | The configured default animation could not be resolved. | `Cannot use the default animation: ` | +| `animation_unavailable` | The animation could not be resolved or loaded. | `Cannot load the animation: ` | +| `server_unavailable` | An in-flight request reaches the server during shutdown. | `The local API is unavailable.` | +| `internal_error` | An unexpected server error prevented completion. | `An internal server error occurred.` | + +During shutdown the socket may close before the server can send +`server_unavailable`; clients should also handle connection loss. + +An activity expires after the smaller of twice its keepalive interval and the +configured `max_wait_time`. Expiration increments the disconnected-client +count; an explicit `stop` does not. + +After **Cancel** in the app, the server reserves the ID for the `max_wait_time` +configured at the moment of cancellation. During that period, every `keepalive` +and `stop` for that ID returns `animation_cancelled`, and `start` with the same +ID returns `activity_id_in_use`. Requests do not extend the reservation. Once it +expires, `keepalive` and `stop` return `unknown_activity` until a successful +`start` reuses the ID. + +## ✦ Examples + +### 🐍 Minimal Python client example ```python import json @@ -170,70 +470,161 @@ with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client: stream.write(json.dumps(value).encode() + b"\n") stream.flush() return json.loads(stream.readline()) - activity = command({"command": "start", "animation": "nyan_54x36.png"})["activity_id"] + activity = command({ + "command": "start", + "animation": "nyan", + "keepalive_interval_seconds": 5, + })["activity_id"] command({"command": "keepalive", "activity_id": activity}) command({"command": "stop", "activity_id": activity}) ``` -## Launch at login +### 🤖 Coding-agent integrations + +Nyathing's CLI can be called directly from command hooks. The examples below +use `jq` to extract the activity ID from hook JSON on stdin; no helper script +is needed. Install `jq` and make sure it is on `PATH`. Replace `nyathing` with +its absolute path if the hook environment does not include it in `PATH`. + +#### Codex + +See the [Codex hooks documentation](https://developers.openai.com/codex/hooks). +Add these hooks to `~/.codex/hooks.json`: + +```json +{ + "hooks": { + "UserPromptSubmit": [{ + "hooks": [{ + "type": "command", + "command": "id=$(jq -r .turn_id) && nyathing client start --activity-id \"$id\" --keepalive-interval 90 >/dev/null" + }] + }], + "PostModelRequest": [{ + "hooks": [{ + "type": "command", + "command": "id=$(jq -r .turn_id) && nyathing client keepalive \"$id\"" + }] + }], + "PreToolUse": [{ + "hooks": [{ + "type": "command", + "command": "id=$(jq -r .turn_id) && nyathing client keepalive \"$id\"" + }] + }], + "PostToolUse": [{ + "hooks": [{ + "type": "command", + "command": "id=$(jq -r .turn_id) && nyathing client keepalive \"$id\"" + }] + }], + "Stop": [{ + "hooks": [{ + "type": "command", + "command": "id=$(jq -r .turn_id) && nyathing client stop \"$id\"" + }] + }], + "Interrupt": [{ + "hooks": [{ + "type": "command", + "command": "id=$(jq -r .turn_id) && nyathing client stop \"$id\"", + "timeout": 3 + }] + }] + } +} +``` + +`UserPromptSubmit` starts one activity per turn. Model responses and tool +calls refresh its keepalive; `Stop` and `Interrupt` stop it. The 90-second +keepalive interval gives the activity up to 180 seconds between refreshes, +subject to `max_wait_time`. A single long model request or tool call can still +outlast that timeout. Review and trust the hooks in Codex before using them. + +#### Claude Code + +See the [Claude Code hooks documentation](https://code.claude.com/docs/en/hooks). +Add these hooks to `~/.claude/settings.json`: + +```json +{ + "hooks": { + "UserPromptSubmit": [{ + "hooks": [{ + "type": "command", + "command": "id=$(jq -r .session_id) && (nyathing client keepalive \"$id\" 2>/dev/null || nyathing client start --activity-id \"$id\" --keepalive-interval 90 >/dev/null)" + }] + }], + "PreToolUse": [{ + "hooks": [{ + "type": "command", + "command": "id=$(jq -r .session_id) && nyathing client keepalive \"$id\"" + }] + }], + "PostToolUse": [{ + "hooks": [{ + "type": "command", + "command": "id=$(jq -r .session_id) && nyathing client keepalive \"$id\"" + }] + }], + "Stop": [{ + "hooks": [{ + "type": "command", + "command": "id=$(jq -r .session_id) && nyathing client stop \"$id\" || true" + }] + }], + "StopFailure": [{ + "hooks": [{ + "type": "command", + "command": "id=$(jq -r .session_id) && nyathing client stop \"$id\" || true" + }] + }], + "SessionEnd": [{ + "hooks": [{ + "type": "command", + "command": "id=$(jq -r .session_id) && nyathing client stop \"$id\" || true" + }] + }] + } +} +``` -Set `auto_start = true` in `config.toml`, then choose **Reload Configuration and -Animations** from Nyathing's menu. Nyathing installs its own LaunchAgent in -`~/Library/LaunchAgents`; it will start automatically at your next login. No -manual `launchctl` commands are needed. +Claude Code's `session_id` stays the same across turns, so the prompt hook +first refreshes an existing activity and starts it only if it is missing. +Tool hooks refresh keepalive; `Stop` and `StopFailure` stop the activity. +Claude Code does not run `Stop` when you interrupt a turn. In that case, the +activity expires after its keepalive timeout; submitting another prompt in +the same session refreshes it. `SessionEnd` provides final cleanup. For long +assistant output, add this hook to the `hooks` object to refresh keepalive +for each displayed message batch: + +```json +{ + "hooks": { + "MessageDisplay": [{ + "hooks": [{ + "type": "command", + "command": "id=$(jq -r .session_id) && nyathing client keepalive \"$id\"" + }] + }] + } +} +``` + +This can add command overhead while text streams. Claude Code does not expose +an equivalent of Codex's per-model-request event. -Set `auto_start = false` and reload to remove the LaunchAgent. If you move -`Nyathing.app`, enable auto-start again and reload so the LaunchAgent records -the app's new location. +Keepalives are sent at hook boundaries, not on a timer. Configure +`max_wait_time` high enough for the longest gap between hooks. See +[Configuration](#-configuration) for the server-side limit. -## Troubleshooting +## ⚡︎ Troubleshooting Startup and runtime diagnostics are written to `$XDG_STATE_HOME/nyathing/nyathing.log`, or `~/.local/state/nyathing/nyathing.log` when `XDG_STATE_HOME` is unset. Startup errors show an alert with an **Open Log** button. Configuration errors also -offer **Open Configuration**; animation errors offer **Open Animations Folder**. +offer **Open Configuration**. Invalid animation files are logged and ignored. If the socket path is already in use, quit the existing instance before -launching another. Invalid animation files are reported in the log; correct -them and reload. - -## Build from source - -Requires macOS 12+ and Swift 5.9 or later. Run the commands below from the -repository root. - -### Run the server - -Build and launch the menu-bar server: - -```sh -swift build -swift run nyathing --server -``` - -### Run the CLI - -The CLI runs a command while displaying an activity animation. For example: - -```sh -swift run nyathing sleep 5 -``` - -### Install from source - -Install the menu-bar app in `/Applications`: - -```sh -make install-app -``` - -To run Nyathing from a terminal, also create the CLI symlink in -`/usr/local/bin`: - -```sh -make install-cli-link -``` - -The CLI symlink requires the app to be installed first. Each command asks -before replacing an existing app or symlink and requires administrator -authorization to install its files. +launching another. After correcting animation files, click **Accept** in the +**Edit Configuration** window to reload them. diff --git a/Scripts/build-dmg.sh b/Scripts/build-dmg.sh deleted file mode 100755 index 8ce1407..0000000 --- a/Scripts/build-dmg.sh +++ /dev/null @@ -1,74 +0,0 @@ -#!/bin/bash -set -euo pipefail - -ROOT="$(cd "$(dirname "$0")/.." && pwd)" -cd "$ROOT" - -if [[ -z "${VERSION:-}" ]]; then - VERSION="$(git describe --tags --exact-match HEAD 2>/dev/null || true)" - VERSION="${VERSION#v}" -fi -if [[ ! "$VERSION" =~ ^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$ ]]; then - echo "Set VERSION to a SemVer value like 1.2.3, or build from a vX.Y.Z tag." >&2 - exit 1 -fi - -APP_NAME="Nyathing.app" -APP_DIR="$ROOT/.build/dmg/$APP_NAME" -CONTENTS="$APP_DIR/Contents" -RESOURCES="$CONTENTS/Resources" -STAGE="$ROOT/.build/dmg-staging" -DIST="$ROOT/dist" - -swift build -c release -rm -rf "$APP_DIR" "$STAGE" "$DIST" -mkdir -p "$CONTENTS/MacOS" "$RESOURCES" "$STAGE" "$DIST" -cp .build/release/nyathing "$CONTENTS/MacOS/nyathing" -cp -R .build/release/Nyathing_Nyathing.bundle "$RESOURCES/" -ICONSET="$ROOT/.build/dmg/Nyathing.iconset" -swift Scripts/make-app-icon.swift assets/nyathing.png "$ICONSET" -iconutil -c icns "$ICONSET" -o "$RESOURCES/Nyathing.icns" -cat > "$CONTENTS/Info.plist" < - - - - CFBundleDevelopmentRegion - en - CFBundleExecutable - nyathing - CFBundleIdentifier - com.nyathing.Nyathing - CFBundleIconFile - Nyathing - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - Nyathing - CFBundlePackageType - APPL - CFBundleShortVersionString - $VERSION - CFBundleVersion - $VERSION - LSMinimumSystemVersion - 12.0 - LSUIElement - - - -PLIST - -codesign --force --deep --sign - "$APP_DIR" -codesign --verify --deep --strict --verbose=2 "$APP_DIR" - -cp -R "$APP_DIR" "$STAGE/" -ln -s /Applications "$STAGE/Applications" -hdiutil create \ - -volname "Nyathing" \ - -srcfolder "$STAGE" \ - -ov \ - -format UDZO \ - "$DIST/nyathing-$VERSION.dmg" - -echo "Created $DIST/nyathing-$VERSION.dmg" diff --git a/Scripts/build-pkg.sh b/Scripts/build-pkg.sh deleted file mode 100755 index cc18ce6..0000000 --- a/Scripts/build-pkg.sh +++ /dev/null @@ -1,91 +0,0 @@ -#!/bin/bash -set -euo pipefail - -ROOT="$(cd "$(dirname "$0")/.." && pwd)" -cd "$ROOT" - -if [[ -z "${VERSION:-}" ]]; then - VERSION="$(git describe --tags --exact-match HEAD 2>/dev/null || true)" - VERSION="${VERSION#v}" -fi -if [[ ! "$VERSION" =~ ^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$ ]]; then - echo "Set VERSION to a SemVer value like 1.2.3, or build from a vX.Y.Z tag." >&2 - exit 1 -fi - -BUILD_DIR="$ROOT/.build/pkg" -APP_DIR="$BUILD_DIR/Nyathing.app" -CONTENTS="$APP_DIR/Contents" -RESOURCES="$CONTENTS/Resources" -PAYLOAD="$BUILD_DIR/payload" -PACKAGE_DIR="$BUILD_DIR/package-scripts" -COMPONENT_PLIST="$BUILD_DIR/components.plist" -OUTPUT_DIR="$ROOT/out" -OUTPUT="$OUTPUT_DIR/Nyathing-$VERSION.pkg" -COMPONENT_PACKAGE="$BUILD_DIR/Nyathing-component.pkg" -INSTALLER_RESOURCES="$BUILD_DIR/installer-resources" - -swift build -c release -rm -rf "$BUILD_DIR" "$OUTPUT" -mkdir -p "$CONTENTS/MacOS" "$RESOURCES" "$PAYLOAD/Applications" "$PACKAGE_DIR" \ - "$INSTALLER_RESOURCES" "$OUTPUT_DIR" -cp .build/release/nyathing "$CONTENTS/MacOS/nyathing" -cp -R .build/release/Nyathing_Nyathing.bundle "$RESOURCES/" -ICONSET="$BUILD_DIR/Nyathing.iconset" -swift Scripts/make-app-icon.swift assets/nyathing.png "$ICONSET" -iconutil -c icns "$ICONSET" -o "$RESOURCES/Nyathing.icns" -cat > "$CONTENTS/Info.plist" < - - - - CFBundleDevelopmentRegion - en - CFBundleExecutable - nyathing - CFBundleIdentifier - com.nyathing.Nyathing - CFBundleIconFile - Nyathing - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - Nyathing - CFBundlePackageType - APPL - CFBundleShortVersionString - $VERSION - CFBundleVersion - $VERSION - LSMinimumSystemVersion - 12.0 - LSUIElement - - - -PLIST - -cp -R "$APP_DIR" "$PAYLOAD/Applications/" -cp Scripts/pkg-preinstall "$PACKAGE_DIR/preinstall" -cp Scripts/pkg-postinstall "$PACKAGE_DIR/postinstall" -chmod 755 "$PACKAGE_DIR/preinstall" "$PACKAGE_DIR/postinstall" -pkgbuild --analyze --root "$PAYLOAD" "$COMPONENT_PLIST" -/usr/libexec/PlistBuddy -c 'Set :0:BundleIsRelocatable false' "$COMPONENT_PLIST" -pkgbuild \ - --root "$PAYLOAD" \ - --component-plist "$COMPONENT_PLIST" \ - --identifier com.nyathing.Nyathing.pkg \ - --version "$VERSION" \ - --install-location / \ - --scripts "$PACKAGE_DIR" \ - "$COMPONENT_PACKAGE" - -cp Scripts/installer-resources/welcome.html "$INSTALLER_RESOURCES/welcome.html" -sips -Z 56 assets/nyathing.png --out "$INSTALLER_RESOURCES/nyathing.png" >/dev/null -productbuild \ - --distribution Scripts/installer-resources/Distribution.xml \ - --resources "$INSTALLER_RESOURCES" \ - --package-path "$BUILD_DIR" \ - "$OUTPUT" - -echo "Created $OUTPUT" diff --git a/Scripts/force-uninstall.sh b/Scripts/force-uninstall.sh index c83cd9e..622cc73 100644 --- a/Scripts/force-uninstall.sh +++ b/Scripts/force-uninstall.sh @@ -1,15 +1,21 @@ #!/bin/bash set -euo pipefail -app_path="/Applications/Nyathing.app" -cli_path="/usr/local/bin/nyathing" +prefix="${PREFIX:-/usr/local}" +if [[ "$prefix" != /* || "$prefix" == / || "$prefix" == "$HOME" \ + || "/$prefix/" == */../* ]]; then + echo "Refusing unsafe PREFIX: $prefix" >&2 + exit 1 +fi +bin_dir="$prefix/bin" +cli_path="$bin_dir/nyathing" +libexec_dir="$prefix/libexec/nyathing" +legacy_app_path="/Applications/Nyathing.app" launch_agent="$HOME/Library/LaunchAgents/com.nyathing.Nyathing.plist" -config_dir="${XDG_CONFIG_HOME:-$HOME/.config}/nyathing" -state_dir="${XDG_STATE_HOME:-$HOME/.local/state}/nyathing" launchctl bootout "gui/$(id -u)" "$launch_agent" 2>/dev/null || true -# Stop Nyathing before removing its app bundle and executable. +# Stop Nyathing before removing its executable and resources. /usr/bin/pkill -TERM -x nyathing 2>/dev/null || true for _ in {1..5}; do if ! /usr/bin/pgrep -x nyathing >/dev/null 2>&1; then break; fi @@ -17,17 +23,33 @@ for _ in {1..5}; do done /usr/bin/pkill -KILL -x nyathing 2>/dev/null || true -sudo /bin/rm -rf -- \ - "$app_path" \ - "$cli_path" \ - "$launch_agent" \ - "$config_dir" \ - "$state_dir" +remove_path() { + local path="$1" parent="$(dirname "$1")" + case "$path" in + "$cli_path"|"$libexec_dir"|"$legacy_app_path"|"$launch_agent") ;; + *) echo "Refusing to remove unexpected path: $path" >&2; return 1 ;; + esac + [[ "$path" != / && -n "$path" ]] || { + echo "Refusing unsafe removal path: $path" >&2; return 1; + } + [[ -e "$path" || -L "$path" ]] || return 0 + while [[ ! -e "$parent" ]]; do parent="$(dirname "$parent")"; done + if [[ -w "$parent" ]]; then + /bin/rm -rf -- "$path" + else + sudo /bin/rm -rf -- "$path" + fi +} + +remove_path "$cli_path" +remove_path "$libexec_dir" +remove_path "$legacy_app_path" +remove_path "$launch_agent" -if [[ -e "$app_path" || -L "$app_path" || -e "$cli_path" || -L "$cli_path" \ - || -e "$launch_agent" || -e "$config_dir" || -e "$state_dir" ]]; then - echo "Nyathing uninstall failed: some app files or user data remain." >&2 +if [[ -e "$cli_path" || -L "$cli_path" || -e "$libexec_dir" \ + || -e "$legacy_app_path" || -e "$launch_agent" ]]; then + echo "Nyathing uninstall failed: some installed files remain." >&2 exit 1 fi -echo "Nyathing and its user data were removed." +echo "Nyathing was removed. User configuration and state were kept." diff --git a/Scripts/generate-version.sh b/Scripts/generate-version.sh new file mode 100644 index 0000000..d96a5a5 --- /dev/null +++ b/Scripts/generate-version.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail + +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +cd "$ROOT" + +tag="$(git describe --tags --exact-match HEAD 2>/dev/null || true)" +if [[ -n "$tag" ]]; then + version="${tag#v}" +else + version="$(git rev-parse --short HEAD)" +fi +output="$ROOT/Sources/Nyathing/Version.swift" +cat > "$output" < "$STAGED_APP/Contents/Info.plist" <<'PLIST' - - - - - CFBundleDevelopmentRegion - en - CFBundleExecutable - nyathing - CFBundleIdentifier - com.nyathing.Nyathing - CFBundleIconFile - Nyathing - CFBundleName - Nyathing - CFBundlePackageType - APPL - LSMinimumSystemVersion - 12.0 - LSUIElement - - - -PLIST - -sudo /bin/rm -rf -- "$APP_PATH" -sudo /usr/bin/ditto "$STAGED_APP" "$APP_PATH" -echo "Installed Nyathing.app in /Applications." diff --git a/Scripts/install-cli-link.sh b/Scripts/install-cli-link.sh deleted file mode 100644 index a67a202..0000000 --- a/Scripts/install-cli-link.sh +++ /dev/null @@ -1,25 +0,0 @@ -#!/bin/bash -set -euo pipefail - -APP_EXECUTABLE="/Applications/Nyathing.app/Contents/MacOS/nyathing" -CLI_PATH="/usr/local/bin/nyathing" - -if [[ ! -x "$APP_EXECUTABLE" ]]; then - echo "Install Nyathing.app in /Applications before creating the CLI link." >&2 - exit 1 -fi -if [[ -e "$CLI_PATH" || -L "$CLI_PATH" ]]; then - if [[ -d "$CLI_PATH" && ! -L "$CLI_PATH" ]]; then - echo "Cannot replace $CLI_PATH because it is a directory." >&2 - exit 1 - fi - read -r -p "Replace existing $CLI_PATH? [y/N] " answer - case "$answer" in - y|Y|yes|Yes|YES) sudo /bin/rm -f -- "$CLI_PATH" ;; - *) echo "Installation cancelled."; exit 0 ;; - esac -fi - -sudo /bin/mkdir -p /usr/local/bin -sudo /bin/ln -s "$APP_EXECUTABLE" "$CLI_PATH" -echo "Created CLI link at $CLI_PATH." diff --git a/Scripts/install.sh b/Scripts/install.sh new file mode 100644 index 0000000..b39b709 --- /dev/null +++ b/Scripts/install.sh @@ -0,0 +1,78 @@ +#!/bin/bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" +PREFIX="${PREFIX:-/usr/local}" +if [[ "$PREFIX" != /* || "$PREFIX" == / || "$PREFIX" == "$HOME" \ + || "/$PREFIX/" == */../* ]]; then + echo "Refusing unsafe PREFIX: $PREFIX" >&2 + exit 1 +fi +SOURCE_DIR="${1:-}" + +if [[ -z "$SOURCE_DIR" ]]; then + if [[ -f "$SCRIPT_DIR/nyathing" && -d "$SCRIPT_DIR/Nyathing_Nyathing.bundle" ]]; then + SOURCE_DIR="$SCRIPT_DIR" + else + cd "$ROOT" + bash Scripts/generate-version.sh + swift build -c release + SOURCE_DIR="$ROOT/.build/release" + fi + SOURCE_DIR="$(cd "$SOURCE_DIR" && pwd -P)" +fi +[[ -d "$SOURCE_DIR" && ! -L "$SOURCE_DIR" ]] || { + echo "Invalid install source directory: $SOURCE_DIR" >&2; exit 1; +} +SOURCE_DIR="$(cd "$SOURCE_DIR" && pwd -P)" +BIN_DIR="$PREFIX/bin" +LIBEXEC_DIR="$PREFIX/libexec/nyathing" + +permission_check="$PREFIX" +while [[ ! -e "$permission_check" ]]; do + permission_check="$(dirname "$permission_check")" +done +if [[ -w "$permission_check" ]]; then + needs_sudo=false +else + needs_sudo=true +fi + +run_install() { + if [[ "$needs_sudo" == true ]]; then + sudo "$@" + else + "$@" + fi +} + +run_install mkdir -p "$BIN_DIR" "$LIBEXEC_DIR" +run_install install -m 755 "$SOURCE_DIR/nyathing" "$LIBEXEC_DIR/nyathing" +bundle_path="$LIBEXEC_DIR/Nyathing_Nyathing.bundle" +if [[ -e "$bundle_path" || -L "$bundle_path" ]]; then + [[ ! -L "$bundle_path" && "$bundle_path" == "$PREFIX/libexec/nyathing/Nyathing_Nyathing.bundle" ]] || { + echo "Refusing to remove unexpected bundle path: $bundle_path" >&2; exit 1; + } + run_install rm -rf -- "$bundle_path" +fi +run_install ditto "$SOURCE_DIR/Nyathing_Nyathing.bundle" \ + "$LIBEXEC_DIR/Nyathing_Nyathing.bundle" + +wrapper="$BIN_DIR/nyathing" +wrapper_content='#!/bin/sh +SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)" +exec "$SCRIPT_DIR/../libexec/nyathing/nyathing" "$@" +' +wrapper_tmp_dir="$(mktemp -d "${TMPDIR:-/tmp}/nyathing-install.XXXXXX")" +wrapper_tmp="$wrapper_tmp_dir/wrapper" +cleanup() { + case "$wrapper_tmp_dir" in + "${TMPDIR:-/tmp}"/nyathing-install.*) rm -rf -- "$wrapper_tmp_dir" ;; + *) echo "Refusing to remove unexpected temporary path: $wrapper_tmp_dir" >&2; exit 1 ;; + esac +} +trap cleanup EXIT +printf '%s' "$wrapper_content" > "$wrapper_tmp" +run_install install -m 755 "$wrapper_tmp" "$wrapper" +echo "Installed nyathing in $BIN_DIR (resources in $LIBEXEC_DIR)." diff --git a/Scripts/installer-resources/Distribution.xml b/Scripts/installer-resources/Distribution.xml deleted file mode 100644 index db7066b..0000000 --- a/Scripts/installer-resources/Distribution.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - Nyathing - - - - - - - - - - Nyathing-component.pkg - diff --git a/Scripts/installer-resources/welcome.html b/Scripts/installer-resources/welcome.html deleted file mode 100644 index c963fee..0000000 --- a/Scripts/installer-resources/welcome.html +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - -

Install Nyathing

-

👻 Nyathing displays playful animations in the macOS menu bar while commands - run.

-

This installer installs Nyathing.app in - /Applications and creates a symlink at - /usr/local/bin/nyathing so you can launch Nyathing from - Terminal.

-

⚠️ You’ll be asked to enter your administrator password during - installation to authorize these changes.

-

Project page: https://github.com/dokwork/nyathing

- - diff --git a/Scripts/make-app-icon.swift b/Scripts/make-app-icon.swift deleted file mode 100644 index 57367f2..0000000 --- a/Scripts/make-app-icon.swift +++ /dev/null @@ -1,66 +0,0 @@ -import AppKit -import Foundation - -let inputURL = URL(fileURLWithPath: CommandLine.arguments[1]) -let outputURL = URL(fileURLWithPath: CommandLine.arguments[2], isDirectory: true) -guard let source = NSImage(contentsOf: inputURL), source.size.width > 0, source.size.height > 0 else { - fatalError("Unable to load app icon image at \(inputURL.path)") -} -try FileManager.default.createDirectory(at: outputURL, withIntermediateDirectories: true) - -let iconSizes: [(String, Int)] = [ - ("icon_16x16.png", 16), - ("icon_16x16@2x.png", 32), - ("icon_32x32.png", 32), - ("icon_32x32@2x.png", 64), - ("icon_128x128.png", 128), - ("icon_128x128@2x.png", 256), - ("icon_256x256.png", 256), - ("icon_256x256@2x.png", 512), - ("icon_512x512.png", 512), - ("icon_512x512@2x.png", 1024), -] - -for (filename, pixels) in iconSizes { - guard - let bitmap = NSBitmapImageRep( - bitmapDataPlanes: nil, - pixelsWide: pixels, - pixelsHigh: pixels, - bitsPerSample: 8, - samplesPerPixel: 4, - hasAlpha: true, - isPlanar: false, - colorSpaceName: .deviceRGB, - bytesPerRow: 0, - bitsPerPixel: 0 - ), - let context = NSGraphicsContext(bitmapImageRep: bitmap) - else { - fatalError("Unable to create \(pixels)x\(pixels) icon bitmap") - } - - NSGraphicsContext.saveGraphicsState() - NSGraphicsContext.current = context - context.imageInterpolation = .high - NSColor.clear.setFill() - NSRect(x: 0, y: 0, width: pixels, height: pixels).fill() - - let scale = min(CGFloat(pixels) / source.size.width, CGFloat(pixels) / source.size.height) - let width = source.size.width * scale - let height = source.size.height * scale - source.draw( - in: NSRect(x: (CGFloat(pixels) - width) / 2, y: (CGFloat(pixels) - height) / 2, - width: width, height: height), - from: .zero, - operation: .sourceOver, - fraction: 1 - ) - context.flushGraphics() - NSGraphicsContext.restoreGraphicsState() - - guard let data = bitmap.representation(using: .png, properties: [:]) else { - fatalError("Unable to encode \(pixels)x\(pixels) icon") - } - try data.write(to: outputURL.appendingPathComponent(filename)) -} diff --git a/Scripts/package-cli.sh b/Scripts/package-cli.sh new file mode 100755 index 0000000..8a44fb5 --- /dev/null +++ b/Scripts/package-cli.sh @@ -0,0 +1,49 @@ +#!/bin/bash +set -euo pipefail + +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +cd "$ROOT" + +if [[ "$(uname -m)" != "arm64" ]]; then + echo "The macOS arm64 archive must be built on an arm64 runner." >&2 + exit 1 +fi + +bash Scripts/generate-version.sh +swift build -c release +BUILD_DIR="$ROOT/.build" +OUT_DIR="$ROOT/out" +mkdir -p "$BUILD_DIR" "$OUT_DIR" +BUILD_DIR="$(cd "$BUILD_DIR" && pwd -P)" +OUT_DIR="$(cd "$OUT_DIR" && pwd -P)" +STAGING="$(mktemp -d "$BUILD_DIR/nyathing-cli.XXXXXX")" +OUTPUT_DIR="$OUT_DIR/nyathing-macos-arm64" +OUTPUT="$OUT_DIR/nyathing-macos-arm64.tar.gz" +cleanup() { + trap - EXIT + case "$STAGING" in + "$BUILD_DIR"/nyathing-cli.*) rm -rf -- "$STAGING" ;; + *) echo "Refusing to remove unexpected staging path: $STAGING" >&2; exit 1 ;; + esac +} +trap cleanup EXIT +cp .build/release/nyathing "$STAGING/nyathing" +cp -R .build/release/Nyathing_Nyathing.bundle "$STAGING/Nyathing_Nyathing.bundle" +cp Scripts/install.sh "$STAGING/install.sh" +cp Scripts/force-uninstall.sh "$STAGING/uninstall.sh" +chmod 755 "$STAGING/install.sh" "$STAGING/uninstall.sh" +if [[ -e "$OUTPUT_DIR" || -L "$OUTPUT_DIR" ]]; then + [[ ! -L "$OUTPUT_DIR" && "$OUTPUT_DIR" == "$OUT_DIR/nyathing-macos-arm64" ]] || { + echo "Refusing to replace unexpected output path: $OUTPUT_DIR" >&2; exit 1; + } + rm -rf -- "$OUTPUT_DIR" +fi +cp -R "$STAGING" "$OUTPUT_DIR" +if [[ -e "$OUTPUT" || -L "$OUTPUT" ]]; then + [[ ! -d "$OUTPUT" && "$OUTPUT" == "$OUT_DIR/nyathing-macos-arm64.tar.gz" ]] || { + echo "Refusing to replace unexpected archive path: $OUTPUT" >&2; exit 1; + } + rm -f -- "$OUTPUT" +fi +tar -czf "$OUTPUT" -C "$STAGING" . +echo "Created $OUTPUT" diff --git a/Scripts/pkg-postinstall b/Scripts/pkg-postinstall deleted file mode 100755 index 252fd7c..0000000 --- a/Scripts/pkg-postinstall +++ /dev/null @@ -1,5 +0,0 @@ -#!/bin/bash -set -euo pipefail - -mkdir -p /usr/local/bin -ln -s /Applications/Nyathing.app/Contents/MacOS/nyathing /usr/local/bin/nyathing diff --git a/Scripts/pkg-preinstall b/Scripts/pkg-preinstall deleted file mode 100755 index e14de4d..0000000 --- a/Scripts/pkg-preinstall +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/bash -set -euo pipefail - -CLI_PATH="/usr/local/bin/nyathing" -CLI_TARGET="/Applications/Nyathing.app/Contents/MacOS/nyathing" -if [[ -L "$CLI_PATH" ]]; then - if [[ "$(/usr/bin/readlink "$CLI_PATH")" == "$CLI_TARGET" ]]; then - /bin/rm -f -- "$CLI_PATH" - else - echo "Cannot install Nyathing: $CLI_PATH is an unrelated symlink." >&2 - exit 1 - fi -elif [[ -e "$CLI_PATH" ]]; then - echo "Cannot install Nyathing: $CLI_PATH already exists and is not a symlink." >&2 - exit 1 -fi diff --git a/Scripts/run-test-animation.py b/Scripts/run-test-animation.py index 19a111f..457e6a6 100644 --- a/Scripts/run-test-animation.py +++ b/Scripts/run-test-animation.py @@ -48,17 +48,13 @@ def configured_value(text, key, default): return match.group(2) if match else default -def configured_seconds(text, key, default): - match = re.search(rf"^\s*{re.escape(key)}\s*=\s*([0-9.]+)", text, re.M) - return float(match.group(1)) if match else default - app = None started_here = False activity_ids = [] try: if not api_is_ready(): - app = subprocess.Popen([".build/debug/nyathing"]) + app = subprocess.Popen([".build/debug/nyathing", "--nyathing-server"]) started_here = True startup_deadline = time.monotonic() + 30 while not api_is_ready(): @@ -71,21 +67,27 @@ def configured_seconds(text, key, default): time.sleep(0.2) settings = config_path.read_text(encoding="utf-8") if config_path.exists() else "" + interval = 5.0 + try: + duration = float(os.environ.get("DURATION", "5")) + except ValueError as error: + raise ValueError("DURATION must be a positive number of seconds") from error + if not 0 < duration < float("inf"): + raise ValueError("DURATION must be a positive finite number of seconds") + animations = os.environ.get("ANIMATIONS", "").replace(",", " ").split() if not animations: - animation = os.environ.get("ANIMATION") or configured_value( - settings, "default_animation", "nyathing_36x36.png" - ) - animations = [animation] + animations = [os.environ.get("ANIMATION")] for animation in animations: - activity_id = request({"command": "start", "animation": animation})["activity_id"] + payload = {"command": "start", "keepalive_interval_seconds": interval} + if animation is not None: + payload["animation"] = animation + activity_id = request(payload)["activity_id"] activity_ids.append(activity_id) - print(f"Started {animation} ({activity_id})") + print(f"Started {animation or 'default animation'} ({activity_id})") - interval = configured_seconds(settings, "keepalive_interval_seconds", 5.0) - timeout = configured_seconds(settings, "activity_timeout_seconds", 5.0) - keepalive_delay = min(interval, timeout) / 2 - run_deadline = time.monotonic() + 5 + keepalive_delay = interval + run_deadline = time.monotonic() + duration while time.monotonic() < run_deadline: time.sleep(min(keepalive_delay, run_deadline - time.monotonic())) for activity_id in activity_ids: diff --git a/Sources/Nyathing/ActivityLifecycle.swift b/Sources/Nyathing/ActivityLifecycle.swift index 988024a..7895d0d 100644 --- a/Sources/Nyathing/ActivityLifecycle.swift +++ b/Sources/Nyathing/ActivityLifecycle.swift @@ -1,15 +1,52 @@ import Foundation +/// Reserves cancelled protocol IDs until their monotonic deadlines. +struct CancelledActivityIDs { + private var deadlines: [String: DispatchTime] = [:] + + /// Records a cancellation and returns the deadline for scheduled cleanup. + mutating func reserve(_ id: String, for duration: TimeInterval, now: DispatchTime = .now()) + -> DispatchTime + { + let deadline = now + duration + deadlines[id] = deadline + return deadline + } + + /// Checks the reservation without consuming it or extending its lifetime. + func contains(_ id: String, now: DispatchTime = .now()) -> Bool { + guard let deadline = deadlines[id] else { return false } + return now < deadline + } + + /// Removes only the reservation associated with this cleanup callback. + mutating func remove(_ id: String, deadline: DispatchTime) { + guard deadlines[id] == deadline else { return } + deadlines.removeValue(forKey: id) + } +} + /// Tracks activity ownership, per-activity expiration generations, and disconnect accounting. struct ActivityLifecycle { + static let missingDescription = "No description provided" + private(set) var activities: [UUID: String] = [:] + private(set) var descriptions: [UUID: String] = [:] private(set) var expirationDeadlines: [UUID: UInt64] = [:] + private(set) var timedOutActivities: [ExpiredActivity] = [] private(set) var disconnectedCount = 0 + struct ExpiredActivity: Equatable, Identifiable { + let id: UUID + let animation: String + let description: String + } + @discardableResult - mutating func start(animation: String, deadline: UInt64) -> UUID { + mutating func start(animation: String, description: String? = nil, deadline: UInt64) -> UUID { let id = UUID() activities[id] = animation + descriptions[id] = description ?? Self.missingDescription expirationDeadlines[id] = deadline return id } @@ -23,18 +60,22 @@ struct ActivityLifecycle { @discardableResult mutating func stop(_ id: UUID) -> String? { expirationDeadlines.removeValue(forKey: id) + descriptions.removeValue(forKey: id) return activities.removeValue(forKey: id) } - /// Expires an activity only for its current deadline and increments the disconnect count once. + /// Expires an activity at its current deadline and returns its description for error reporting. @discardableResult - mutating func expire(_ id: UUID, deadline: UInt64) -> String? { + mutating func expire(_ id: UUID, deadline: UInt64) -> ExpiredActivity? { guard expirationDeadlines[id] == deadline, - let animation = activities.removeValue(forKey: id) + let animation = activities.removeValue(forKey: id), + let description = descriptions.removeValue(forKey: id) else { return nil } expirationDeadlines.removeValue(forKey: id) disconnectedCount += 1 - return animation + let expired = ExpiredActivity(id: id, animation: animation, description: description) + timedOutActivities.append(expired) + return expired } func animation(for id: UUID) -> String? { @@ -45,19 +86,28 @@ struct ActivityLifecycle { expirationDeadlines[id] } + func description(for id: UUID) -> String? { + descriptions[id] + } + func activityCount(for animation: String) -> Int { activities.values.reduce(into: 0) { count, value in if value == animation { count += 1 } } } - mutating func resetDisconnectedCount() { - disconnectedCount = 0 + mutating func acknowledgeTimeout(_ id: UUID) -> Bool { + guard let index = timedOutActivities.firstIndex(where: { $0.id == id }) else { return false } + timedOutActivities.remove(at: index) + disconnectedCount = max(0, disconnectedCount - 1) + return true } mutating func reset() { activities.removeAll() + descriptions.removeAll() expirationDeadlines.removeAll() + timedOutActivities.removeAll() disconnectedCount = 0 } } diff --git a/Sources/Nyathing/CLI.swift b/Sources/Nyathing/CLI.swift index 0ed2e83..dfa275f 100644 --- a/Sources/Nyathing/CLI.swift +++ b/Sources/Nyathing/CLI.swift @@ -34,36 +34,56 @@ private final class KeepaliveFailure { } struct CLIArguments { - let animation: String + let animation: String? let command: String let arguments: [String] - static let usage = """ - Nyathing displays playful animations in the macOS menu bar while commands run. + static var usage: String { + let version = + Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String + ?? AppVersion.current + return """ + Nyathing displays playful animations in the macOS menu bar while commands run. - Usage: - nyathing [--animation FILE | -a FILE] COMMAND [ARGUMENT ...] - nyathing uninstall - nyathing --help - nyathing --version + Version: + \(version) - Commands: - COMMAND [ARGUMENT ...] Run a command while showing an activity animation. - uninstall Remove the installed app and CLI command. + Usage: + nyathing [--animation NAME | -a NAME] COMMAND [ARGUMENT ...] + nyathing server start|stop|status + nyathing client start|keepalive|stop + nyathing list + nyathing completion zsh|bash + nyathing --help + nyathing --version - Options: - -a, --animation FILE Select an animation from the user animations folder. - --help Show this help. - --version Show the app version. + Commands: + COMMAND [ARGUMENT ...] Run a command while showing an activity animation. + server Manage the background server (start, stop, status). + client Start, refresh, or stop an activity. + list List available valid animations. + completion SHELL Print shell completion code for zsh or bash. - Examples: - nyathing sleep 5 - nyathing --animation nyan_54x36.png make test - """ + Options: + -a, --animation NAME Select a short animation name or path to a PNG. + --help Show this help. + --version Show the app version. + + Client usage: + nyathing client start [--animation NAME] [--description TEXT] + [--activity-id ID] [--keepalive-interval SECONDS] + nyathing client keepalive ACTIVITY_ID + nyathing client stop ACTIVITY_ID + + Examples: + nyathing sleep 5 + nyathing --animation nyan make test + """ + } static func parse(_ arguments: [String]) throws -> CLIArguments { var values = arguments - var animation = "nyathing_36x36.png" + var animation: String? if values.first == "--animation" || values.first == "-a" { guard values.count >= 3, !values[1].isEmpty else { throw CLIError.usage } animation = values[1] @@ -77,24 +97,31 @@ struct CLIArguments { enum CLIError: LocalizedError { case usage - case animationUnavailable(String) + case animationUnavailable(String, String) case server(String) case api(String) var errorDescription: String? { switch self { case .usage: return CLIArguments.usage - case .animationUnavailable(let filename): - return "Animation not found or invalid: \(filename)." + case .animationUnavailable(let filename, let reason): + return "Animation '\(filename)' \(reason)" case .server(let message), .api(let message): return message } } } enum NyathingCLI { + static let builtInGhostAnimation = "__built_in_ghost__" + static func run(_ arguments: [String]) -> Int32 { - if arguments == ["uninstall"] { - return NyathingUninstaller.run() + if arguments.count == 2, arguments[0] == "completion" { + guard let script = ShellCompletion.script(for: arguments[1]) else { + FileHandle.standardError.write(Data("Supported shells: zsh, bash\n".utf8)) + return 1 + } + print(script, terminator: "") + return 0 } if arguments.isEmpty || arguments == ["--help"] { print(CLIArguments.usage) @@ -103,10 +130,49 @@ enum NyathingCLI { if arguments == ["--version"] { print( Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String - ?? "Development build") + ?? AppVersion.current) return 0 } do { + if arguments.first == "client" { + return try executeClient(Array(arguments.dropFirst())) + } + if arguments.count == 2, arguments[0] == "server" { + let configurationDirectory = AppConfiguration.configurationDirectory + switch arguments[1] { + case "start": + try LaunchAgentSupport.startServer(in: configurationDirectory) + print("Nyathing server started in the background.") + return 0 + case "stop": + try LaunchAgentSupport.stopServer(in: configurationDirectory) + print("Nyathing server stopped.") + return 0 + case "status": + let running = LaunchAgentSupport.serverIsRunning() + print(running ? "Nyathing server is running." : "Nyathing server is not running.") + return running ? 0 : 1 + default: + throw CLIError.usage + } + } + if arguments == ["list"] { + let configurationDirectory = AppConfiguration.configurationDirectory + try AppConfiguration.prepareDirectory(configurationDirectory) + let directory = + configurationDirectory.appendingPathComponent("animations", isDirectory: true) + let names = SpriteAnimation.loadAll(in: directory).keys.compactMap { filename -> String? in + guard + let separator = filename.range( + of: #"_[0-9]+x[0-9]+\.png$"#, options: .regularExpression) + else { return nil } + return String(filename[.. Int32 { + guard let subcommand = arguments.first else { throw CLIError.usage } + switch subcommand { + case "start": + var animation: String? + var description: String? + var activityID: String? + var interval: Double? + var index = 1 + while index < arguments.count { + let option = arguments[index] + guard index + 1 < arguments.count else { throw CLIError.usage } + let value = arguments[index + 1] + guard !value.isEmpty else { throw CLIError.usage } + switch option { + case "--animation", "-a": + guard animation == nil else { throw CLIError.usage } + animation = value + case "--description": + guard description == nil else { throw CLIError.usage } + description = value + case "--activity-id": + guard activityID == nil else { throw CLIError.usage } + activityID = value + case "--keepalive-interval": + guard interval == nil, let parsed = Double(value), parsed.isFinite, parsed > 0 + else { throw CLIError.usage } + interval = parsed + default: + throw CLIError.usage + } + index += 2 + } + var request: [String: Any] = ["command": "start"] + if let animation { request["animation"] = try explicitAnimationForRequest(animation) } + if let description { request["description"] = description } + if let activityID { request["activity_id"] = activityID } + if let interval { request["keepalive_interval_seconds"] = NSNumber(value: interval) } + let client = try LocalAPIClient.connectOrStartServer() + guard let activityID = try client.command(request)["activity_id"] as? String else { + throw CLIError.api("The server returned an invalid activity response.") + } + print(activityID) + return 0 + case "keepalive", "stop": + guard arguments.count == 2, !arguments[1].isEmpty else { throw CLIError.usage } + let client = try LocalAPIClient.connectOrStartServer() + let response = try client.command([ + "command": subcommand, "activity_id": arguments[1], + ]) + guard response["ok"] as? Bool == true else { + throw CLIError.api(response["error"] as? String ?? "The server rejected the request.") + } + return 0 + default: + throw CLIError.usage + } + } + private static func execute(_ cli: CLIArguments) throws -> Int32 { let executable = try resolveExecutable(cli.command) - let configuration = try AppConfiguration.load() - let animationsDirectory = AppConfiguration.configurationDirectory - .appendingPathComponent("animations", isDirectory: true) - try validateAnimation(cli.animation, in: animationsDirectory) - let keepaliveInterval = keepaliveInterval(for: configuration) + let keepaliveInterval = LocalAPIServer.defaultKeepaliveInterval + var request: [String: Any] = [ + "command": "start", + "description": activityDescription(command: cli.command, arguments: cli.arguments), + ] + if let animation = cli.animation { + request["animation"] = try explicitAnimationForRequest(animation) + } let client = try LocalAPIClient.connectOrStartServer() - let activity = try client.command(["command": "start", "animation": cli.animation]) + let activity = try client.command(request) guard let activityID = activity["activity_id"] as? String else { throw CLIError.api("The server returned an invalid activity response.") } @@ -179,19 +307,119 @@ enum NyathingCLI { return child.terminationStatus } + private static func explicitAnimationForRequest(_ value: String) throws -> String { + if value == "random" { return value } + let directory = AppConfiguration.configurationDirectory + try AppConfiguration.prepareDirectory(directory) + return try resolveAnimation( + value, in: directory.appendingPathComponent("animations", isDirectory: true)) + } + static func validateAnimation(_ filename: String, in directory: URL) throws { - guard !filename.contains("/"), !filename.contains("\\"), - (try? SpriteAnimation.load(from: directory.appendingPathComponent(filename))) != nil + _ = try resolveAnimation(filename, in: directory) + } + + static func resolveAnimation( + _ name: String, in directory: URL, + relativeTo baseDirectory: URL = URL( + fileURLWithPath: FileManager.default.currentDirectoryPath, isDirectory: true) + ) throws -> String { + if name == "random" { + if let namedAnimation = try? resolveNamedAnimation(name, in: directory) { + return namedAnimation + } + let available = SpriteAnimation.loadAll(in: directory) + return available.keys.sorted().randomElement().map { + directory.appendingPathComponent($0).standardizedFileURL.path + } ?? builtInGhostAnimation + } + if isShortAnimationName(name) { + return try resolveNamedAnimation(name, in: directory) + } + if !name.contains("/"), !name.contains("\\") { + let installed = directory.appendingPathComponent(name).standardizedFileURL + if FileManager.default.fileExists(atPath: installed.path) { + return try resolveAnimation(installed.path, in: directory) + } + } + let path = URL( + fileURLWithPath: (name as NSString).expandingTildeInPath, relativeTo: baseDirectory + ).standardizedFileURL + do { + _ = try SpriteAnimation.load(from: path) + return path.path + } catch { + throw CLIError.animationUnavailable( + name, "could not load animation file: \(error.localizedDescription).") + } + } + + private static func isShortAnimationName(_ name: String) -> Bool { + !name.contains("/") && !name.contains("\\") + && URL(fileURLWithPath: name).pathExtension.isEmpty + && name.range(of: #"_[0-9]+x[0-9]+$"#, options: .regularExpression) == nil + } + + private static func resolveNamedAnimation(_ name: String, in directory: URL) throws -> String { + guard + let files = try? FileManager.default.contentsOfDirectory( + at: directory, includingPropertiesForKeys: nil) else { - throw CLIError.animationUnavailable(filename) + throw CLIError.animationUnavailable( + name, + "could not be checked because the animations directory is unavailable at \(directory.path)." + ) + } + + let pattern = + "^\(NSRegularExpression.escapedPattern(for: name))_([0-9]+)x([0-9]+)\\.png$" + guard + let regex = try? NSRegularExpression(pattern: pattern, options: [.caseInsensitive]) + else { + throw CLIError.animationUnavailable(name, "could not be resolved to a filename.") + } + let candidates = files.compactMap { file -> (url: URL, width: Int, height: Int)? in + let filename = file.lastPathComponent + guard + let match = regex.firstMatch( + in: filename, range: NSRange(filename.startIndex..., in: filename)), + let widthRange = Range(match.range(at: 1), in: filename), + let heightRange = Range(match.range(at: 2), in: filename), + let width = Int(filename[widthRange]), let height = Int(filename[heightRange]) + else { return nil } + return (file, width, height) + }.sorted { + let leftArea = Double($0.width) * Double($0.height) + let rightArea = Double($1.width) * Double($1.height) + if leftArea != rightArea { return leftArea > rightArea } + if $0.width != $1.width { return $0.width > $1.width } + return $0.url.lastPathComponent < $1.url.lastPathComponent + } + + var invalidAssetError: Error? + for candidate in candidates { + do { + _ = try SpriteAnimation.load(from: candidate.url) + return candidate.url.standardizedFileURL.path + } catch { + invalidAssetError = invalidAssetError ?? error + } } + if let invalidAssetError { + throw CLIError.animationUnavailable( + name, "has no valid matching animation: \(invalidAssetError.localizedDescription).") + } + throw CLIError.animationUnavailable( + name, + "was not found in \(directory.path). Use 'nyathing list' to see available animations." + ) } - static func keepaliveInterval(for configuration: AppConfiguration) -> TimeInterval { - min(configuration.keepaliveInterval, configuration.activityTimeout / 2) + static func activityDescription(command: String, arguments: [String]) -> String { + ([command] + arguments).joined(separator: " ") } - static func resolveExecutable(_ command: String) throws -> String { + static func resolveExecutable(_ command: String, searchPath: String? = nil) throws -> String { if command.contains("/") { let path = URL( fileURLWithPath: command, @@ -209,9 +437,11 @@ enum NyathingCLI { if FileManager.default.isExecutableFile(atPath: currentDirectoryPath) { return currentDirectoryPath } - let paths = ProcessInfo.processInfo.environment[ - "PATH", default: "/usr/bin:/bin:/usr/sbin:/sbin" - ].split(separator: ":") + let paths = + (searchPath + ?? ProcessInfo.processInfo.environment[ + "PATH", default: "/usr/bin:/bin:/usr/sbin:/sbin" + ]).split(separator: ":") for directory in paths { let path = URL(fileURLWithPath: String(directory)).appendingPathComponent(command).path if FileManager.default.isExecutableFile(atPath: path) { return path } @@ -222,6 +452,88 @@ enum NyathingCLI { } } +enum ShellCompletion { + static let supportedCommands = ["server", "client", "list", "completion"] + + static func script(for shell: String) -> String? { + let commands = supportedCommands.joined(separator: " ") + switch shell { + case "zsh": + return #""" + #compdef nyathing + + _nyathing() { + local -a commands animations + commands=(\#(commands)) + + case "${words[CURRENT-1]}" in + -a|--animation) + animations=(random ${(f)"$(nyathing list 2>/dev/null)"}) + compadd -- "${animations[@]}" + return + ;; + server) + compadd -- start stop status + return + ;; + client) + compadd -- start keepalive stop + return + ;; + completion) + compadd -- zsh bash + return + ;; + esac + + if (( CURRENT == 2 )); then + compadd -- "${commands[@]}" --animation -a --help --version + fi + } + + compdef _nyathing nyathing + """# + case "bash": + return #""" + _nyathing() { + local cur prev animations + COMPREPLY=() + cur="${COMP_WORDS[COMP_CWORD]}" + prev="${COMP_WORDS[COMP_CWORD-1]}" + + case "$prev" in + -a|--animation) + animations="$(nyathing list 2>/dev/null)" + COMPREPLY=( $(compgen -W "random $animations" -- "$cur") ) + return + ;; + server) + COMPREPLY=( $(compgen -W "start stop status" -- "$cur") ) + return + ;; + client) + COMPREPLY=( $(compgen -W "start keepalive stop" -- "$cur") ) + return + ;; + completion) + COMPREPLY=( $(compgen -W "zsh bash" -- "$cur") ) + return + ;; + esac + + if (( COMP_CWORD == 1 )); then + COMPREPLY=( $(compgen -W "\#(commands)" -- "$cur") ) + COMPREPLY+=( $(compgen -W "--animation -a --help --version" -- "$cur") ) + fi + } + complete -F _nyathing nyathing + """# + default: + return nil + } + } +} + private final class LocalAPIClient { private let descriptor: Int32 private let lock = NSLock() @@ -232,8 +544,9 @@ private final class LocalAPIClient { static func connectOrStartServer() throws -> LocalAPIClient { if let connected = try? connect() { return connected } let process = Process() - process.executableURL = URL(fileURLWithPath: CommandLine.arguments[0]).standardizedFileURL - process.arguments = ["--server"] + let executable = try NyathingCLI.resolveExecutable(CommandLine.arguments[0]) + process.executableURL = URL(fileURLWithPath: executable) + process.arguments = [LaunchAgentSupport.serverArgument] process.standardInput = FileHandle.nullDevice process.standardOutput = FileHandle.nullDevice process.standardError = FileHandle.nullDevice @@ -274,7 +587,7 @@ private final class LocalAPIClient { return LocalAPIClient(descriptor: fd) } - func command(_ request: [String: String]) throws -> [String: Any] { + func command(_ request: [String: Any]) throws -> [String: Any] { lock.lock() defer { lock.unlock() } var data = try JSONSerialization.data(withJSONObject: request) diff --git a/Sources/Nyathing/Configuration.swift b/Sources/Nyathing/Configuration.swift index e3fef04..d77c5e4 100644 --- a/Sources/Nyathing/Configuration.swift +++ b/Sources/Nyathing/Configuration.swift @@ -3,20 +3,40 @@ import Foundation import ImageIO struct AppConfiguration { - let keepaliveInterval: TimeInterval - let activityTimeout: TimeInterval + let maxWaitTime: TimeInterval let autoStart: Bool - let defaultAnimation: String + private let defaultAnimationValues: [String] + private let directory: URL + + var defaultAnimation: String { + get throws { + guard defaultAnimationValues.count == 1, + let rawAnimation = defaultAnimationValues.first, + let value = try? JSONDecoder().decode(String.self, from: Data(rawAnimation.utf8)), + !value.isEmpty + else { throw ConfigError.invalidValue("default_animation") } + return value + } + } + + var resolvedDefaultAnimation: String { + get throws { + let value = try defaultAnimation + do { + return try Self.resolveDefaultAnimation(value, in: directory) + } catch { + throw ConfigError.invalidDefaultAnimation(error.localizedDescription) + } + } + } static let template = """ - # Seconds between client keepalive messages; must be greater than zero. - keepalive_interval_seconds = 5 - # Seconds without a keepalive before an activity expires; must be greater than zero. - activity_timeout_seconds = 5 + # Maximum seconds to wait since the last client keepalive. + max_wait_time = 180 # Whether Nyathing should launch automatically when you log in. auto_start = false - # Animation filename used when a client omits the animation field. - default_animation = "nyathing_36x36.png" + # Animation name, PNG path, or "random" used when a client omits the animation field. + default_animation = "nyathing" """ static var configurationDirectory: URL { @@ -54,12 +74,7 @@ struct AppConfiguration { return String(line) } - static func load() throws -> AppConfiguration { - try load(in: configurationDirectory) - } - - /// Loads and validates configuration from a configuration directory. - static func load(in directory: URL) throws -> AppConfiguration { + static func prepareDirectory(_ directory: URL) throws { let configURL = directory.appendingPathComponent("config.toml") let animationsDirectory = directory.appendingPathComponent("animations", isDirectory: true) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) @@ -79,8 +94,16 @@ struct AppConfiguration { } } } + } + + static func load( + in directory: URL = configurationDirectory, validateDefaultAnimation: Bool = true + ) throws -> AppConfiguration { + try prepareDirectory(directory) + let configURL = directory.appendingPathComponent("config.toml") var text = try String(contentsOf: configURL, encoding: .utf8) var removedObsoleteSettings = false + var legacyMaxWaitTime: String? let obsoleteComments = [ "# Animate the app's icon instead of showing the static project logo.", "# Animate the app's main icon instead of showing the static logo.", @@ -95,6 +118,11 @@ struct AppConfiguration { let line = stripComment(from: rawLine).trimmingCharacters(in: .whitespaces) guard let equal = line.firstIndex(of: "=") else { return original } let key = line[.. Double { @@ -146,24 +182,21 @@ struct AppConfiguration { guard let rawAuto = values["auto_start"], rawAuto == "true" || rawAuto == "false" else { throw ConfigError.invalidValue("auto_start") } - guard let rawAnimation = values["default_animation"], - rawAnimation.count >= 2, rawAnimation.first == "\"", rawAnimation.last == "\"" - else { - throw ConfigError.invalidValue("default_animation") - } - let defaultAnimation = String(rawAnimation.dropFirst().dropLast()) - guard !defaultAnimation.contains("/"), !defaultAnimation.contains("\\"), - (try? SpriteAnimation.load( - from: animationsDirectory.appendingPathComponent( - defaultAnimation))) != nil - else { - throw ConfigError.invalidValue("default_animation") - } - return AppConfiguration( - keepaliveInterval: try number("keepalive_interval_seconds"), - activityTimeout: try number("activity_timeout_seconds"), + let configuration = AppConfiguration( + maxWaitTime: try number("max_wait_time"), autoStart: rawAuto == "true", - defaultAnimation: defaultAnimation) + defaultAnimationValues: defaultAnimationValues, + directory: directory) + if validateDefaultAnimation { _ = try configuration.resolvedDefaultAnimation } + return configuration + } + + static func resolveDefaultAnimation(_ value: String, in directory: URL) throws -> String { + // Keep random selection deferred until a client starts an activity. + if value == "random" { return value } + return try NyathingCLI.resolveAnimation( + value, in: directory.appendingPathComponent("animations", isDirectory: true), + relativeTo: directory) } } @@ -171,6 +204,7 @@ enum ConfigError: LocalizedError { case invalidLine(Int) case invalidKey(String, Int) case invalidValue(String) + case invalidDefaultAnimation(String) var errorDescription: String? { switch self { @@ -180,16 +214,18 @@ enum ConfigError: LocalizedError { case .invalidKey(let key, let line): return "Unknown or duplicate setting '\(key)' on line \(line). Use each supported setting once." + case .invalidDefaultAnimation(let reason): + return "Invalid 'default_animation': \(reason)" case .invalidValue(let key): switch key { - case "keepalive_interval_seconds", "activity_timeout_seconds": + case "max_wait_time": return "Missing or invalid '\(key)'. Add it to config.toml as a positive number of seconds." case "auto_start": return "Missing or invalid '\(key)'. Add it to config.toml with the value true or false." case "default_animation": return - "Missing or invalid 'default_animation'. Set it to the filename of a valid animation in the animations directory." + "Missing or invalid 'default_animation'. Set it to an animation name, PNG path, or 'random'." default: return "Missing or invalid setting: \(key). Check config.toml and correct its value." } @@ -202,40 +238,61 @@ struct SpriteAnimation { let frameSize: NSSize let frames: [NSImage] + static let minimumFrameDimension = 16 + static let maximumFrameDimension = 256 + static let maximumFrameAspectRatio = 3.0 + static let maximumFrameCount = 120 + static let maximumSpriteSheetPixels = 4_000_000 + static func load(from url: URL) throws -> SpriteAnimation { let filename = url.lastPathComponent - let pattern = #"^(.+)_((?:36x36)|(?:54x36))\.png$"# + let pattern = #"^(.+)_([0-9]+)x([0-9]+)\.png$"# guard let regex = try? NSRegularExpression(pattern: pattern, options: [.caseInsensitive]), let match = regex.firstMatch( in: filename, range: NSRange(filename.startIndex..., in: filename)), - let sizeRange = Range(match.range(at: 2), in: filename) + let widthRange = Range(match.range(at: 2), in: filename), + let heightRange = Range(match.range(at: 3), in: filename), + let frameWidth = Int(filename[widthRange]), + let frameHeight = Int(filename[heightRange]) else { throw AnimationError.invalidFilename(filename) } - let sizeName = filename[sizeRange].lowercased() - let size: NSSize = - sizeName == "36x36" ? NSSize(width: 36, height: 36) : NSSize(width: 54, height: 36) + let frameSize = NSSize(width: frameWidth, height: frameHeight) + let dimensionsAreInRange = + (Self.minimumFrameDimension...Self.maximumFrameDimension).contains(frameWidth) + && (Self.minimumFrameDimension...Self.maximumFrameDimension).contains(frameHeight) + let aspectRatio = Double(max(frameWidth, frameHeight)) / Double(min(frameWidth, frameHeight)) + guard dimensionsAreInRange, aspectRatio <= Self.maximumFrameAspectRatio else { + throw AnimationError.unsupportedFrameSize(filename, frameWidth, frameHeight) + } guard let source = CGImageSourceCreateWithURL(url as CFURL, nil), - let image = CGImageSourceCreateImageAtIndex(source, 0, nil) + let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any], + let width = (properties[kCGImagePropertyPixelWidth] as? NSNumber)?.intValue, + let height = (properties[kCGImagePropertyPixelHeight] as? NSNumber)?.intValue else { throw AnimationError.invalidPNG(filename) } - let width = image.width - let height = image.height - let frameWidth = Int(size.width) - let frameHeight = Int(size.height) guard height == frameHeight, width > 0, width % frameWidth == 0 else { throw AnimationError.invalidDimensions(filename, width, height) } - let sheet = NSImage(cgImage: image, size: NSSize(width: width, height: height)) + let frameCount = width / frameWidth + guard frameCount <= Self.maximumFrameCount else { + throw AnimationError.tooManyFrames(filename, frameCount, Self.maximumFrameCount) + } + guard width <= Self.maximumSpriteSheetPixels / height else { + throw AnimationError.spriteSheetTooLarge( + filename, width, height, Self.maximumSpriteSheetPixels) + } + guard let image = CGImageSourceCreateImageAtIndex(source, 0, nil) else { + throw AnimationError.invalidPNG(filename) + } var frames: [NSImage] = [] - for index in 0..<(width / frameWidth) { + for index in 0.. [String: SpriteAnimation] { @@ -270,13 +327,24 @@ enum AnimationResolution { enum AnimationError: LocalizedError { case invalidFilename(String) case invalidPNG(String) + case unsupportedFrameSize(String, Int, Int) case invalidDimensions(String, Int, Int) + case tooManyFrames(String, Int, Int) + case spriteSheetTooLarge(String, Int, Int, Int) var errorDescription: String? { switch self { case .invalidFilename(let name): return "Unrecognized animation filename: \(name)" case .invalidPNG(let name): return "Unable to decode PNG animation: \(name)" + case .unsupportedFrameSize(let name, let width, let height): + return + "Unsupported frame size for \(name): \(width)x\(height). Dimensions must be between 16 and 256 pixels with an aspect ratio no greater than 3:1." case .invalidDimensions(let name, let width, let height): return "Invalid sprite dimensions for \(name): \(width)x\(height)" + case .tooManyFrames(let name, let count, let maximum): + return "Too many frames in \(name): \(count); maximum is \(maximum)." + case .spriteSheetTooLarge(let name, let width, let height, let maximumPixels): + return + "Sprite sheet \(name) is too large (\(width)x\(height)); maximum is \(maximumPixels) pixels." } } } diff --git a/Sources/Nyathing/Diagnostics.swift b/Sources/Nyathing/Diagnostics.swift index 586aa65..020c7b5 100644 --- a/Sources/Nyathing/Diagnostics.swift +++ b/Sources/Nyathing/Diagnostics.swift @@ -75,12 +75,72 @@ enum NyathingLog { enum LaunchAgentSupport { static let label = "com.nyathing.Nyathing" + static let serverArgument = "--nyathing-server" + + private static var agentURL: URL { + FileManager.default.homeDirectoryForCurrentUser + .appendingPathComponent("Library/LaunchAgents", isDirectory: true) + .appendingPathComponent("\(label).plist") + } + + private static var serviceTarget: String { + "gui/\(getuid())/\(label)" + } + + static func startServer(in configurationDirectory: URL) throws { + try configure(enabled: true, in: configurationDirectory) + if launchctl(["print", serviceTarget]).status == 0 { + try runLaunchctl(["kickstart", serviceTarget]) + return + } + try runLaunchctl(["bootstrap", "gui/\(getuid())", agentURL.path]) + } + + static func stopServer(in configurationDirectory: URL) throws { + if launchctl(["print", serviceTarget]).status == 0 { + try runLaunchctl(["bootout", serviceTarget]) + } + try? FileManager.default.removeItem(at: agentURL) + } + + static func serverIsRunning() -> Bool { + let result = launchctl(["print", serviceTarget]) + guard result.status == 0 else { return false } + return result.output.components(separatedBy: .newlines).contains { line in + guard line.trimmingCharacters(in: .whitespaces).hasPrefix("pid = ") else { return false } + let value = line.trimmingCharacters(in: .whitespaces).dropFirst("pid = ".count) + return Int(value).map { $0 > 0 } ?? false + } + } + + private static func runLaunchctl(_ arguments: [String]) throws { + let result = launchctl(arguments) + guard result.status == 0 else { + let detail = result.output.trimmingCharacters(in: .whitespacesAndNewlines) + throw LaunchAgentError.launchctl(detail.isEmpty ? "launchctl failed." : detail) + } + } + + private static func launchctl(_ arguments: [String]) -> (status: Int32, output: String) { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/bin/launchctl") + process.arguments = arguments + let pipe = Pipe() + process.standardOutput = pipe + process.standardError = pipe + do { + try process.run() + let output = pipe.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + return (process.terminationStatus, String(data: output, encoding: .utf8) ?? "") + } catch { + return (1, error.localizedDescription) + } + } /// Installs or removes the user's login agent according to the auto-start setting. static func configure(enabled: Bool, in configurationDirectory: URL) throws { - let launchAgentsDirectory = FileManager.default.homeDirectoryForCurrentUser - .appendingPathComponent("Library/LaunchAgents", isDirectory: true) - let agentURL = launchAgentsDirectory.appendingPathComponent("\(label).plist") + let launchAgentsDirectory = agentURL.deletingLastPathComponent() let legacyURL = configurationDirectory.appendingPathComponent("\(label).plist") if enabled { @@ -89,7 +149,7 @@ enum LaunchAgentSupport { } let plist: [String: Any] = [ "Label": label, - "ProgramArguments": [executable], + "ProgramArguments": [executable, serverArgument], "RunAtLoad": true, ] let data = try PropertyListSerialization.data( @@ -110,7 +170,13 @@ enum LaunchAgentSupport { enum LaunchAgentError: LocalizedError { case executableUnavailable + case launchctl(String) var errorDescription: String? { - "Unable to determine Nyathing's executable path for the LaunchAgent plist." + switch self { + case .executableUnavailable: + return "Unable to determine Nyathing's executable path for the LaunchAgent plist." + case .launchctl(let message): + return "Unable to manage the Nyathing server: \(message)" + } } } diff --git a/Sources/Nyathing/LocalAPIServer.swift b/Sources/Nyathing/LocalAPIServer.swift index fe2df23..f40af59 100644 --- a/Sources/Nyathing/LocalAPIServer.swift +++ b/Sources/Nyathing/LocalAPIServer.swift @@ -3,8 +3,10 @@ import Foundation /// Serves the local JSON Lines API over a current-user Unix domain socket. final class LocalAPIServer { - private let defaultAnimation: String - private let onStart: (String) throws -> String + static let defaultKeepaliveInterval: TimeInterval = 5 + private var defaultAnimation: () throws -> String + private var maxWaitTime: TimeInterval + private let onStart: (String, String?, String?, TimeInterval, Bool, TimeInterval) throws -> String private let onKeepalive: (String) throws -> Void private let onStop: (String) throws -> Void private let socketPath: String @@ -15,18 +17,38 @@ final class LocalAPIServer { init( socketPath: String = LocalAPIServer.socketPath, - defaultAnimation: String = "nyathing_36x36.png", - onStart: @escaping (String) throws -> String, + defaultAnimation: @escaping () throws -> String = { "nyathing_36x36.png" }, + maxWaitTime: TimeInterval = 180, + onStart: + @escaping (String, String?, String?, TimeInterval, Bool, TimeInterval) throws -> String, onKeepalive: @escaping (String) throws -> Void, onStop: @escaping (String) throws -> Void ) { self.defaultAnimation = defaultAnimation + self.maxWaitTime = maxWaitTime self.onStart = onStart self.onKeepalive = onKeepalive self.onStop = onStop self.socketPath = socketPath } + /// Updates the settings for future starts without disconnecting existing clients. + func updateStartSettings( + defaultAnimation: @escaping () throws -> String, maxWaitTime: TimeInterval + ) { + lock.lock() + defer { lock.unlock() } + self.defaultAnimation = defaultAnimation + self.maxWaitTime = maxWaitTime + } + + private func startSettings() -> (defaultAnimation: () throws -> String, maxWaitTime: TimeInterval) + { + lock.lock() + defer { lock.unlock() } + return (defaultAnimation, maxWaitTime) + } + deinit { stop() } static var socketPath: String { @@ -190,13 +212,13 @@ final class LocalAPIServer { let line = Data(pending[.. 1_048_576 { - _ = writeResponse(["ok": false, "error": "Request line is too large."], to: client) + _ = writeResponse(errorResponse(.requestTooLarge), to: client) return } } @@ -204,19 +226,48 @@ final class LocalAPIServer { private func handle(_ line: Data) -> [String: Any] { guard isRunning else { - return ["ok": false, "error": LocalAPIError.unavailable.localizedDescription] + return errorResponse(.unavailable) } do { - guard let request = try JSONSerialization.jsonObject(with: line) as? [String: Any], + guard let request = (try? JSONSerialization.jsonObject(with: line)) as? [String: Any], let command = request["command"] as? String else { throw LocalAPIError.invalidRequest } switch command { case "start": - let animation = request["animation"] as? String ?? defaultAnimation - guard !animation.isEmpty else { throw LocalAPIError.invalidRequest } - return ["ok": true, "activity_id": try onStart(animation)] + let settings = startSettings() + let animation: String + if let explicit = request["animation"] { + guard let value = explicit as? String, !value.isEmpty else { + throw LocalAPIError.invalidRequest + } + animation = value + } else { + do { + animation = try settings.defaultAnimation() + } catch { + throw LocalAPIError.invalidDefaultAnimation(error.localizedDescription) + } + } + let requestedActivityID = request["activity_id"] as? String + if request["activity_id"] != nil && (requestedActivityID?.isEmpty ?? true) { + throw LocalAPIError.invalidRequest + } + let keepaliveIntervalWasProvided = request["keepalive_interval_seconds"] != nil + let keepaliveInterval: TimeInterval + if let rawKeepaliveInterval = request["keepalive_interval_seconds"] { + keepaliveInterval = try positiveSeconds(rawKeepaliveInterval) + } else { + keepaliveInterval = Self.defaultKeepaliveInterval + } + let activityTimeout = min(keepaliveInterval * 2, settings.maxWaitTime) + return [ + "ok": true, + "activity_id": try onStart( + animation, request["description"] as? String, requestedActivityID, keepaliveInterval, + keepaliveIntervalWasProvided, activityTimeout), + ] case "keepalive": guard let activityID = request["activity_id"] as? String, !activityID.isEmpty else { throw LocalAPIError.invalidRequest @@ -232,11 +283,25 @@ final class LocalAPIServer { default: throw LocalAPIError.unknownCommand(command) } + } catch let error as LocalAPIError { + return errorResponse(error) + } catch CLIError.animationUnavailable(let filename, let reason) { + return errorResponse(.animationUnavailable("Animation '\(filename)' \(reason)")) + } catch let error as AnimationError { + return errorResponse(.animationUnavailable(error.localizedDescription)) } catch { - return ["ok": false, "error": error.localizedDescription] + return errorResponse(.internalError) } } + private func errorResponse(_ error: LocalAPIError) -> [String: Any] { + let error = error.protocolCode == nil ? .internalError : error + return [ + "ok": false, "error_code": error.protocolCode ?? "internal_error", + "error": error.localizedDescription, + ] + } + @discardableResult private func writeResponse(_ response: [String: Any], to fd: Int32) -> Bool { guard var data = try? JSONSerialization.data(withJSONObject: response) else { return false } @@ -256,6 +321,14 @@ final class LocalAPIServer { } } + private func positiveSeconds(_ value: Any) throws -> TimeInterval { + guard let number = value as? NSNumber, number.doubleValue.isFinite, number.doubleValue > 0 + else { + throw LocalAPIError.invalidKeepaliveInterval + } + return number.doubleValue + } + private var isRunning: Bool { lock.lock() defer { lock.unlock() } @@ -290,18 +363,51 @@ final class LocalAPIServer { enum LocalAPIError: LocalizedError { case unavailable case invalidRequest + case invalidKeepaliveInterval case unknownCommand(String) case unknownActivity + case animationCancelled + case requestTooLarge + case invalidDefaultAnimation(String) + case animationUnavailable(String) + case internalError + case activityIDInUse(String) case socketPathTooLong case alreadyRunning(String) case unsafeSocketPath(String) + /// Stable wire identifier for request failures; transport setup errors have no code. + var protocolCode: String? { + switch self { + case .unavailable: return "server_unavailable" + case .invalidRequest: return "invalid_request" + case .invalidKeepaliveInterval: return "invalid_keepalive_interval" + case .unknownCommand: return "unknown_command" + case .unknownActivity: return "unknown_activity" + case .animationCancelled: return "animation_cancelled" + case .activityIDInUse: return "activity_id_in_use" + case .requestTooLarge: return "request_too_large" + case .invalidDefaultAnimation: return "invalid_default_animation" + case .animationUnavailable: return "animation_unavailable" + case .internalError: return "internal_error" + case .socketPathTooLong, .alreadyRunning, .unsafeSocketPath: return nil + } + } + var errorDescription: String? { switch self { case .unavailable: return "The local API is unavailable." case .invalidRequest: return "Invalid JSON Lines request." + case .invalidKeepaliveInterval: + return "'keepalive_interval_seconds' must be a positive finite number of seconds." case .unknownCommand(let command): return "Unknown command: \(command)." case .unknownActivity: return "Unknown activity ID." + case .animationCancelled: return "Animation was cancelled." + case .requestTooLarge: return "Request line is too large." + case .invalidDefaultAnimation(let reason): return "Cannot use the default animation: \(reason)" + case .animationUnavailable(let reason): return "Cannot load the animation: \(reason)" + case .internalError: return "An internal server error occurred." + case .activityIDInUse(let id): return "Activity ID \"\(id)\" is already in use." case .socketPathTooLong: return "The local API socket path is too long." case .alreadyRunning(let path): return "Another Nyathing instance is listening at \(path)." case .unsafeSocketPath(let path): diff --git a/Sources/Nyathing/Resources/explosion_36x36.png b/Sources/Nyathing/Resources/explosion_36x36.png deleted file mode 100644 index 88aa1b5..0000000 Binary files a/Sources/Nyathing/Resources/explosion_36x36.png and /dev/null differ diff --git a/Sources/Nyathing/Uninstall.swift b/Sources/Nyathing/Uninstall.swift deleted file mode 100644 index 8f282b2..0000000 --- a/Sources/Nyathing/Uninstall.swift +++ /dev/null @@ -1,113 +0,0 @@ -import Darwin -import Foundation - -/// Coordinates synchronous end-user removal of the app and CLI command. -enum NyathingUninstaller { - static let appPath = "/Applications/Nyathing.app" - static let symlinkPath = "/usr/local/bin/nyathing" - static let prompt = "Remove Nyathing configuration and user animations? [y/N]" - static func run() -> Int32 { - do { - let removeUserData = try confirmUserDataRemoval() - try requestAuthorization(removeUserData: removeUserData) - FileHandle.standardError.write(Data("Nyathing was successfully uninstalled.\n".utf8)) - return 0 - } catch { - FileHandle.standardError.write( - Data("nyathing: Uninstall failed: \(error.localizedDescription)\n".utf8)) - return 1 - } - } - - static func confirmUserDataRemoval() throws -> Bool { - FileHandle.standardOutput.write(Data((prompt + " ").utf8)) - guard let answer = readLine() else { return false } - return try parseConfirmation(answer) - } - - static func parseConfirmation(_ answer: String) throws -> Bool { - switch answer.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() { - case "", "n", "no": return false - case "y", "yes": return true - default: throw UninstallError.invalidConfirmation - } - } - - private static func requestAuthorization(removeUserData: Bool) throws { - let pid = getpid() - let executablePath = appPath + "/Contents/MacOS/nyathing" - let removalCommand = """ - attempts=0 - while :; do - pids=$(/usr/sbin/lsof -t \(shellQuote(executablePath)) 2>/dev/null) - lsof_status=$? - if [ "$lsof_status" -gt 1 ]; then exit 1; fi - other_pids= - for process_pid in $pids; do - if [ "$process_pid" != "\(pid)" ]; then other_pids="$other_pids $process_pid"; fi - done - if [ -z "$other_pids" ]; then break; fi - if [ "$attempts" -lt 1 ]; then signal=TERM; else signal=KILL; fi - for process_pid in $other_pids; do - /bin/kill -"$signal" "$process_pid" 2>/dev/null || true - done - attempts=$((attempts + 1)) - if [ "$attempts" -ge 10 ]; then exit 1; fi - /bin/sleep 1 - done - /bin/rm -f -- \(shellQuote(symlinkPath)) && /bin/rm -rf -- \(shellQuote(appPath)) && - [ ! -e \(shellQuote(symlinkPath)) ] && [ ! -L \(shellQuote(symlinkPath)) ] && - [ ! -e \(shellQuote(appPath)) ] && [ ! -L \(shellQuote(appPath)) ] - """ - var commands = [removalCommand] - if removeUserData { - let configuration = AppConfiguration.configurationDirectory.path - commands.append("/bin/rm -rf -- \(shellQuote(configuration + "/animations"))") - commands.append("/bin/rm -rf -- \(shellQuote(configuration))") - } - let shellCommand = commands.joined(separator: " && ") - let appleScript = - "do shell script \"\(appleScriptQuote(shellCommand))\" with administrator privileges" - let process = Process() - process.executableURL = URL(fileURLWithPath: "/usr/bin/osascript") - process.arguments = ["-e", appleScript] - let errorPipe = Pipe() - process.standardError = errorPipe - do { - try process.run() - } catch { - throw UninstallError.authorization(error.localizedDescription) - } - process.waitUntilExit() - guard process.terminationStatus == 0 else { - let details = String( - data: errorPipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8)? - .trimmingCharacters(in: .whitespacesAndNewlines) - throw UninstallError.authorization(details?.isEmpty == false ? details! : nil) - } - } - - private static func shellQuote(_ value: String) -> String { - "'" + value.replacingOccurrences(of: "'", with: "'\\''") + "'" - } - - private static func appleScriptQuote(_ value: String) -> String { - value.replacingOccurrences(of: "\\", with: "\\\\") - .replacingOccurrences(of: "\"", with: "\\\"") - } -} - -enum UninstallError: LocalizedError { - case invalidConfirmation - case authorization(String?) - - var errorDescription: String? { - switch self { - case .invalidConfirmation: - return "Please answer yes or no; user data has not been removed." - case .authorization(let details): - return details.map { "Administrator authorization failed: \($0)" } - ?? "Administrator authorization was canceled or failed." - } - } -} diff --git a/Sources/Nyathing/main.swift b/Sources/Nyathing/main.swift index 6c3f2e5..64c48da 100644 --- a/Sources/Nyathing/main.swift +++ b/Sources/Nyathing/main.swift @@ -1,8 +1,9 @@ import AppKit import Foundation +import UniformTypeIdentifiers let arguments = Array(CommandLine.arguments.dropFirst()) -if arguments == ["--server"] { +if arguments == [LaunchAgentSupport.serverArgument] { runNyathingApplication(serverMode: true) exit(EXIT_SUCCESS) } @@ -25,7 +26,38 @@ private func runNyathingApplication(serverMode: Bool) { application.run() } -final class AppDelegate: NSObject, NSApplicationDelegate { +private final class ActiveTaskMenuRow: NSView { + init( + description: String, time: String, icon: NSImage, width: CGFloat, font: NSFont, + timeWidth: CGFloat + ) { + super.init(frame: NSRect(x: 0, y: 0, width: width, height: 22)) + let imageView = NSImageView(image: icon) + imageView.frame = NSRect(x: 0, y: 3, width: 16, height: 16) + addSubview(imageView) + + let timeField = NSTextField(labelWithString: time) + timeField.font = font + timeField.alignment = .right + timeField.frame = NSRect(x: width - timeWidth - 8, y: 2, width: timeWidth + 4, height: 18) + addSubview(timeField) + + let descriptionField = NSTextField(labelWithString: description) + descriptionField.font = font + descriptionField.lineBreakMode = .byTruncatingTail + descriptionField.frame = NSRect( + x: 22, y: 2, width: max(0, width - 22 - timeWidth - 20), height: 18) + addSubview(descriptionField) + } + + required init?(coder: NSCoder) { nil } +} + +private final class ActiveActivitiesDocumentView: NSView { + override var isFlipped: Bool { true } +} + +final class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate { private let serverMode: Bool init(serverMode: Bool = false) { @@ -44,12 +76,27 @@ final class AppDelegate: NSObject, NSApplicationDelegate { }() private var activeAnimations: [String: ActiveAnimation] = [:] private var lifecycle = ActivityLifecycle() - private var activityTimeout: TimeInterval = 5 - private var defaultAnimation = "nyathing_36x36.png" + private var maxWaitTime: TimeInterval = 180 + private var activityTimeouts: [UUID: TimeInterval] = [:] + private var externalActivityIDs: [String: UUID] = [:] + private var activityKeepaliveIntervals: [UUID: TimeInterval] = [:] + private var activityKeepaliveIntervalSources: [UUID: String] = [:] + private var timedOutActivityDetails: [UUID: ActivityTimeoutDetails] = [:] + private var activityStartOrder: [UUID: UInt64] = [:] + private var activityStartUptime: [UUID: TimeInterval] = [:] + private var activeActivitiesOpenedAt: TimeInterval = 0 + private var nextActivityStartOrder: UInt64 = 0 private var apiServer: LocalAPIServer? private var apiGeneration = 0 - private var warningFrames: [NSImage] = [] - private var warningFrameIndex = 0 + private var errorsWindow: NSWindow? + private var errorsStackView: NSStackView? + private var activeActivitiesWindow: NSWindow? + private var activeActivitiesStackView: NSStackView? + private var cancelledActivityIDs = CancelledActivityIDs() + private var configurationWindow: NSWindow? + private var maxWaitTimeField: NSTextField? + private var autoStartCheckbox: NSButton? + private var defaultAnimationPicker: NSPopUpButton? func applicationDidFinishLaunching(_ notification: Notification) { let item = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength) @@ -58,7 +105,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { if serverMode { startDedicatedServer() } else { - reloadConfigurationAndAnimations() + reloadConfiguration() } animationTimer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { [weak self] _ in self?.advanceAnimations() @@ -67,36 +114,88 @@ final class AppDelegate: NSObject, NSApplicationDelegate { private func startDedicatedServer() { // Keep the AppKit event loop alive for API callbacks and animation updates. - reloadConfigurationAndAnimations() + reloadConfiguration() } func applicationWillTerminate(_ notification: Notification) { animationTimer?.invalidate() apiGeneration += 1 apiServer?.stop() - for active in activeAnimations.values { - NSStatusBar.system.removeStatusItem(active.statusItem) - } } private func configureMenu(for item: NSStatusItem) { let menu = NSMenu() - menu.addItem(withTitle: "About Nyathing", action: #selector(showAbout), keyEquivalent: "") - menu.addItem(.separator()) - menu.addItem( - withTitle: "Reset Disconnected Count", action: #selector(resetDisconnectedCount), - keyEquivalent: "") - menu.addItem( - withTitle: "Reload Configuration and Animations", action: #selector(reloadFromMenu), - keyEquivalent: "") + let activities = activeTaskMenuItems() + for menuItem in activities { menu.addItem(menuItem) } + if !activities.isEmpty { + menu.addItem( + withTitle: "View All Active Animations", action: #selector(viewActiveActivities(_:)), + keyEquivalent: "") + menu.addItem(.separator()) + } + if !lifecycle.timedOutActivities.isEmpty { + menu.addItem( + withTitle: "View Errors", action: #selector(viewErrors), keyEquivalent: "") + } menu.addItem( - withTitle: "Open Configuration", action: #selector(openConfiguration), keyEquivalent: "") + withTitle: "Edit Configuration", action: #selector(editConfiguration), keyEquivalent: "") + menu.addItem(.separator()) + menu.addItem(withTitle: "About", action: #selector(showAbout), keyEquivalent: "") menu.addItem(.separator()) - menu.addItem(withTitle: "Quit Nyathing", action: #selector(quit), keyEquivalent: "q") + menu.addItem(withTitle: "Quit", action: #selector(quit), keyEquivalent: "q") for menuItem in menu.items { menuItem.target = self } item.menu = menu } + private func activeTaskMenuItems() -> [NSMenuItem] { + let rows = activityStartOrder.keys.sorted { + activityStartOrder[$0, default: 0] > activityStartOrder[$1, default: 0] + } + let font = NSFont.menuFont(ofSize: 0) + let widestActionTitle = + [ + "View Errors", "Edit Configuration", "About", "Quit", + ].map { ($0 as NSString).size(withAttributes: [.font: font]).width }.max() ?? 0 + let iconColumnWidth: CGFloat = 16 + let horizontalMenuPadding: CGFloat = 16 + let availableWidth = max(0, widestActionTitle * 1.3 - iconColumnWidth - horizontalMenuPadding) + return rows.compactMap { id in + guard let animation = lifecycle.animation(for: id), + let active = activeAnimations[animation], !active.frames.isEmpty, + let description = lifecycle.description(for: id) + else { return nil } + let shortenedDescription = Self.truncatedMenuDescription( + description, font: font, width: availableWidth) + let item = NSMenuItem(title: shortenedDescription, action: nil, keyEquivalent: "") + let firstFrame = active.frames[0] + let menuIcon = (firstFrame.copy() as? NSImage) ?? firstFrame + menuIcon.size = NSSize(width: iconColumnWidth, height: iconColumnWidth) + item.image = menuIcon + item.isEnabled = false + return item + } + } + + private static func truncatedMenuDescription(_ text: String, font: NSFont, width: CGFloat) + -> String + { + let attributes: [NSAttributedString.Key: Any] = [.font: font] + guard (text as NSString).size(withAttributes: attributes).width > width else { return text } + let ellipsis = "…" + var result = text + while !result.isEmpty, + ((result + ellipsis) as NSString).size(withAttributes: attributes).width > width + { + result.removeLast() + } + return result.isEmpty ? ellipsis : result + ellipsis + } + + private func refreshStatusItemMenus() { + if let mainStatusItem { configureMenu(for: mainStatusItem) } + for active in activeAnimations.values { configureMenu(for: active.statusItem) } + } + @objc private func showAbout() { let repositoryURL = URL(string: "https://github.com/dokwork/nyathing")! let credits = NSMutableAttributedString( @@ -113,7 +212,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { Bundle.main.object( forInfoDictionaryKey: "CFBundleShortVersionString" ) as? String - let version = bundleVersion ?? "Development build" + let version = bundleVersion ?? AppVersion.current var options: [NSApplication.AboutPanelOptionKey: Any] = [ .applicationName: "Nyathing", .applicationVersion: version, @@ -131,36 +230,500 @@ final class AppDelegate: NSObject, NSApplicationDelegate { NSApp.terminate(nil) } - @objc private func resetDisconnectedCount() { - lifecycle.resetDisconnectedCount() - warningFrames = [] - warningFrameIndex = 0 + @objc private func viewActiveActivities(_ sender: NSMenuItem) { + if activeActivitiesWindow == nil { + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 480, height: 300), + styleMask: [.titled, .closable, .miniaturizable, .resizable], + backing: .buffered, defer: false) + window.title = "Active Animations" + window.isReleasedWhenClosed = false + let scrollView = NSScrollView() + scrollView.hasVerticalScroller = true + let stack = NSStackView() + stack.orientation = .vertical + stack.alignment = .leading + stack.spacing = 10 + stack.edgeInsets = NSEdgeInsets(top: 16, left: 20, bottom: 20, right: 20) + let document = ActiveActivitiesDocumentView() + document.translatesAutoresizingMaskIntoConstraints = false + stack.translatesAutoresizingMaskIntoConstraints = false + document.addSubview(stack) + scrollView.documentView = document + window.contentView = scrollView + NSLayoutConstraint.activate([ + document.widthAnchor.constraint(equalTo: scrollView.contentView.widthAnchor), + stack.leadingAnchor.constraint(equalTo: document.leadingAnchor), + stack.trailingAnchor.constraint(equalTo: document.trailingAnchor), + stack.topAnchor.constraint(equalTo: document.topAnchor), + stack.bottomAnchor.constraint(equalTo: document.bottomAnchor), + ]) + activeActivitiesWindow = window + activeActivitiesStackView = stack + } + activeActivitiesOpenedAt = ProcessInfo.processInfo.systemUptime + refreshActiveActivitiesWindow() + activeActivitiesWindow?.center() + activeActivitiesWindow?.makeKeyAndOrderFront(nil) + NSApp.activate(ignoringOtherApps: true) + } + + private func refreshActiveActivitiesWindow() { + guard let stack = activeActivitiesStackView else { return } + for view in Array(stack.arrangedSubviews) { + stack.removeArrangedSubview(view) + view.removeFromSuperview() + } + let ids = activityStartOrder.keys.sorted { + activityStartOrder[$0, default: 0] > activityStartOrder[$1, default: 0] + } + for id in ids { + guard let animation = lifecycle.animation(for: id), + let active = activeAnimations[animation], let description = lifecycle.description(for: id) + else { continue } + let row = NSStackView() + row.orientation = .horizontal + row.alignment = .centerY + row.spacing = 10 + if let frame = active.frames.first { + let icon = NSImageView(image: frame) + icon.imageScaling = .scaleProportionallyUpOrDown + row.addArrangedSubview(icon) + NSLayoutConstraint.activate([ + icon.widthAnchor.constraint(equalToConstant: 24), + icon.heightAnchor.constraint(equalToConstant: 24), + ]) + } + let idLabel = NSTextField(labelWithString: "ID: \(id.uuidString)") + idLabel.font = .monospacedSystemFont(ofSize: 11, weight: .regular) + idLabel.lineBreakMode = .byTruncatingTail + idLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + row.addArrangedSubview(idLabel) + let spacer = NSView() + spacer.setContentHuggingPriority(.defaultLow, for: .horizontal) + row.addArrangedSubview(spacer) + let cancel = NSButton( + title: "Cancel", target: self, action: #selector(cancelActiveActivity(_:))) + cancel.identifier = NSUserInterfaceItemIdentifier(id.uuidString) + row.addArrangedSubview(cancel) + + let block = NSStackView() + block.orientation = .vertical + block.alignment = .leading + block.spacing = 5 + block.addArrangedSubview(row) + row.widthAnchor.constraint(equalTo: block.widthAnchor).isActive = true + + let descriptionLabel = NSTextField(wrappingLabelWithString: "Description: \(description)") + descriptionLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + block.addArrangedSubview(descriptionLabel) + descriptionLabel.widthAnchor.constraint(equalTo: block.widthAnchor).isActive = true + + let startedAt = activityStartUptime[id] ?? activeActivitiesOpenedAt + let elapsed = Int(max(0, activeActivitiesOpenedAt - startedAt)) + let duration = String(format: "%ld:%02ld", elapsed / 60, elapsed % 60) + block.addArrangedSubview(NSTextField(labelWithString: "Time spent: \(duration)")) + stack.addArrangedSubview(block) + block.widthAnchor.constraint(equalTo: stack.widthAnchor, constant: -40).isActive = true + } + if stack.arrangedSubviews.isEmpty { + stack.addArrangedSubview(NSTextField(labelWithString: "No active animations")) + } + } + + @objc private func cancelActiveActivity(_ sender: NSButton) { + guard let id = UUID(uuidString: sender.identifier?.rawValue ?? ""), + let animation = lifecycle.animation(for: id) + else { return } + if let externalID = externalActivityIDs.first(where: { $0.value == id })?.key { + externalActivityIDs.removeValue(forKey: externalID) + let deadline = cancelledActivityIDs.reserve(externalID, for: maxWaitTime) + DispatchQueue.main.asyncAfter(deadline: deadline) { [weak self] in + self?.cancelledActivityIDs.remove(externalID, deadline: deadline) + } + } + _ = lifecycle.stop(id) + activityStartOrder.removeValue(forKey: id) + activityStartUptime.removeValue(forKey: id) + activityTimeouts.removeValue(forKey: id) + activityKeepaliveIntervals.removeValue(forKey: id) + activityKeepaliveIntervalSources.removeValue(forKey: id) + removeActivityFromStatusItem(id, animation: animation) + refreshStatusItemMenus() + refreshActiveActivitiesWindow() + } + + @objc private func viewErrors() { + if errorsWindow == nil { + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 480, height: 320), + styleMask: [.titled, .closable, .miniaturizable, .resizable], + backing: .buffered, defer: false) + window.title = "Timeout Errors" + window.isReleasedWhenClosed = false + + let scrollView = NSScrollView() + scrollView.hasVerticalScroller = true + scrollView.translatesAutoresizingMaskIntoConstraints = false + let stack = NSStackView() + stack.orientation = .vertical + stack.alignment = .leading + stack.spacing = 10 + stack.edgeInsets = NSEdgeInsets(top: 16, left: 20, bottom: 20, right: 20) + stack.setContentHuggingPriority(.required, for: .vertical) + stack.setContentCompressionResistancePriority(.required, for: .vertical) + stack.translatesAutoresizingMaskIntoConstraints = false + scrollView.documentView = stack + window.contentView = scrollView + NSLayoutConstraint.activate([ + stack.leadingAnchor.constraint(equalTo: scrollView.contentView.leadingAnchor), + stack.topAnchor.constraint(equalTo: scrollView.contentView.topAnchor), + stack.widthAnchor.constraint(equalTo: scrollView.contentView.widthAnchor), + stack.heightAnchor.constraint(greaterThanOrEqualTo: scrollView.contentView.heightAnchor), + ]) + errorsWindow = window + errorsStackView = stack + } + refreshErrorsWindow() + errorsWindow?.center() + errorsWindow?.makeKeyAndOrderFront(nil) + NSApp.activate(ignoringOtherApps: true) + } + + private func sectionLabel(_ text: String) -> NSTextField { + let label = NSTextField(labelWithString: text) + label.font = .systemFont(ofSize: 11, weight: .semibold) + label.textColor = .secondaryLabelColor + return label + } + + private static func seconds(_ value: TimeInterval) -> String { + "\(value.formatted()) seconds" + } + + @objc private func acknowledgeError(_ sender: NSButton) { + guard let id = UUID(uuidString: sender.identifier?.rawValue ?? ""), + lifecycle.acknowledgeTimeout(id) + else { return } + timedOutActivityDetails.removeValue(forKey: id) + updateMainStatusItemVisibility() updateMainStatusItem() + refreshStatusItemMenus() + refreshErrorsWindow() + if lifecycle.timedOutActivities.isEmpty { + errorsWindow?.close() + errorsWindow = nil + errorsStackView = nil + } } - @objc private func reloadFromMenu() { - reloadConfigurationAndAnimations() + private func refreshErrorsWindow() { + guard let stack = errorsStackView else { return } + for subview in Array(stack.arrangedSubviews) { + stack.removeArrangedSubview(subview) + subview.removeFromSuperview() + } + if lifecycle.timedOutActivities.isEmpty { + let emptyLabel = NSTextField(labelWithString: "No errors") + emptyLabel.lineBreakMode = .byWordWrapping + stack.addArrangedSubview(emptyLabel) + return + } + for (index, error) in lifecycle.timedOutActivities.enumerated() { + if index > 0 { + let separator = NSBox() + separator.boxType = .separator + stack.addArrangedSubview(separator) + separator.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true + } + let details = timedOutActivityDetails[error.id] + let block = NSStackView() + block.orientation = .vertical + block.alignment = .leading + block.spacing = 5 + block.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + block.addArrangedSubview(sectionLabel("Activity ID")) + let idLabel = NSTextField(labelWithString: error.id.uuidString) + idLabel.font = .monospacedSystemFont(ofSize: 12, weight: .medium) + block.addArrangedSubview(idLabel) + block.addArrangedSubview(sectionLabel("Client description")) + let descriptionLabel = NSTextField(wrappingLabelWithString: error.description) + descriptionLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + block.addArrangedSubview(descriptionLabel) + block.addArrangedSubview(sectionLabel("Reason")) + let reasonLabel = NSTextField( + wrappingLabelWithString: "No keepalive was received before the activity timed out.") + reasonLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + block.addArrangedSubview(reasonLabel) + if let details { + let intervalLabel = NSTextField( + wrappingLabelWithString: + "Keepalive interval: \(Self.seconds(details.keepaliveInterval)) " + + "(\(details.intervalSource)).") + intervalLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + block.addArrangedSubview(intervalLabel) + let waitExplanation = + details.timeout < details.keepaliveInterval * 2 + ? "capped by max_wait_time" + : "2 × keepalive interval" + let timeoutLabel = NSTextField( + wrappingLabelWithString: + "Expiration threshold: \(Self.seconds(details.timeout)) " + + "(\(waitExplanation); max_wait_time is " + + "\(Self.seconds(details.maxWaitTime))).") + timeoutLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + block.addArrangedSubview(timeoutLabel) + } + let buttonRow = NSStackView() + buttonRow.orientation = .horizontal + buttonRow.alignment = .centerY + buttonRow.distribution = .fill + let buttonSpacer = NSView() + buttonSpacer.setContentHuggingPriority(.defaultLow, for: .horizontal) + let acknowledgeButton = NSButton( + title: "Acknowledge", target: self, action: #selector(acknowledgeError(_:))) + acknowledgeButton.identifier = NSUserInterfaceItemIdentifier(error.id.uuidString) + buttonRow.addArrangedSubview(buttonSpacer) + buttonRow.addArrangedSubview(acknowledgeButton) + block.addArrangedSubview(buttonRow) + buttonRow.widthAnchor.constraint(equalTo: block.widthAnchor).isActive = true + stack.addArrangedSubview(block) + block.widthAnchor.constraint(equalTo: stack.widthAnchor, constant: -40).isActive = true + } } - @objc private func openConfiguration() { - let url = AppConfiguration.configurationDirectory.appendingPathComponent("config.toml") - guard NSWorkspace.shared.open(url) else { - NyathingLog.report( - NSError( - domain: "Nyathing", code: 1, - userInfo: [NSLocalizedDescriptionKey: "Unable to open configuration at \(url.path)"]), - context: "Unable to open configuration") + private static func shortAnimationName(_ filename: String) -> String? { + guard + let range = filename.range( + of: #"_[0-9]+x[0-9]+\.png$"#, options: .regularExpression) + else { return nil } + return String(filename[.. NSMenuItem { + let item = NSMenuItem(title: title, action: nil, keyEquivalent: "") + item.representedObject = title + let attributedTitle = NSMutableAttributedString(string: "\u{2002}\(title) ") + if let frame { + let image = (frame.copy() as? NSImage) ?? frame + image.size = NSSize(width: 18, height: 18) + let attachment = NSTextAttachment() + attachment.image = image + attachment.bounds = CGRect(x: 0, y: -4, width: 18, height: 18) + attributedTitle.append(NSAttributedString(attachment: attachment)) + } + item.attributedTitle = attributedTitle + return item + } + + @objc private func editConfiguration() { + if let configurationWindow { + configurationWindow.makeKeyAndOrderFront(nil) + NSApp.activate(ignoringOtherApps: true) + return + } + + let configuration: AppConfiguration + let configuredAnimation: String + do { + configuration = try AppConfiguration.load(validateDefaultAnimation: false) + configuredAnimation = try configuration.defaultAnimation + } catch { + showConfigurationEditorError(error.localizedDescription) + return + } + + let animationDirectory = AppConfiguration.configurationDirectory + .appendingPathComponent("animations", isDirectory: true) + var animationsByName: [String: SpriteAnimation] = [:] + for animation in SpriteAnimation.loadAll(in: animationDirectory).values { + guard let name = Self.shortAnimationName(animation.filename) else { continue } + if let current = animationsByName[name], + current.frameSize.width * current.frameSize.height + >= animation.frameSize.width * animation.frameSize.height + { + continue + } + animationsByName[name] = animation + } + let animationNames = ["random"] + animationsByName.keys.sorted() + + let maxWaitTimeField = NSTextField(string: String(configuration.maxWaitTime)) + maxWaitTimeField.placeholderString = "Seconds" + maxWaitTimeField.alignment = .right + maxWaitTimeField.widthAnchor.constraint(equalToConstant: 130).isActive = true + + let animationPicker = NSPopUpButton() + for name in animationNames { + animationPicker.menu?.addItem( + animationMenuItem(title: name, frame: animationsByName[name]?.frames.first)) + } + selectAnimation(configuredAnimation, in: animationPicker) + let browseButton = NSButton( + title: "Choose PNG…", target: self, action: #selector(chooseConfigurationAnimation)) + let animationControls = NSStackView(views: [animationPicker, browseButton]) + animationControls.spacing = 8 + animationPicker.widthAnchor.constraint(equalToConstant: 170).isActive = true + + let autoStart = NSButton( + checkboxWithTitle: "Launch Nyathing at login", target: self, action: nil) + autoStart.state = configuration.autoStart ? .on : .off + + func row(_ title: String, control: NSView) -> NSStackView { + let label = NSTextField(labelWithString: title) + label.widthAnchor.constraint(equalToConstant: 190).isActive = true + let row = NSStackView(views: [label, control]) + row.orientation = .horizontal + row.alignment = .centerY + row.spacing = 12 + return row + } + + let fields = NSStackView(views: [ + row("Maximum wait time (seconds)", control: maxWaitTimeField), + row("Default animation", control: animationControls), + autoStart, + ]) + fields.orientation = .vertical + fields.alignment = .leading + fields.spacing = 14 + fields.translatesAutoresizingMaskIntoConstraints = false + + let cancelButton = NSButton( + title: "Cancel", target: self, action: #selector(cancelConfigurationEdit)) + let acceptButton = NSButton( + title: "Accept", target: self, action: #selector(acceptConfigurationEdit)) + acceptButton.keyEquivalent = "\\r" + let buttons = NSStackView(views: [cancelButton, acceptButton]) + buttons.orientation = .horizontal + buttons.alignment = .centerY + buttons.spacing = 8 + buttons.translatesAutoresizingMaskIntoConstraints = false + + let content = NSView() + content.addSubview(fields) + content.addSubview(buttons) + NSLayoutConstraint.activate([ + fields.leadingAnchor.constraint(equalTo: content.leadingAnchor, constant: 20), + fields.trailingAnchor.constraint(lessThanOrEqualTo: content.trailingAnchor, constant: -20), + fields.topAnchor.constraint(equalTo: content.topAnchor, constant: 20), + buttons.trailingAnchor.constraint(equalTo: content.trailingAnchor, constant: -20), + buttons.bottomAnchor.constraint(equalTo: content.bottomAnchor, constant: -16), + fields.bottomAnchor.constraint(lessThanOrEqualTo: buttons.topAnchor, constant: -18), + ]) + + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 540, height: 230), + styleMask: [.titled, .closable], backing: .buffered, defer: false) + window.title = "Edit Configuration" + window.isReleasedWhenClosed = false + window.delegate = self + window.contentView = content + configurationWindow = window + self.maxWaitTimeField = maxWaitTimeField + autoStartCheckbox = autoStart + defaultAnimationPicker = animationPicker + window.center() + window.makeKeyAndOrderFront(nil) + NSApp.activate(ignoringOtherApps: true) + } + + private func selectAnimation(_ value: String, in picker: NSPopUpButton) { + if let item = picker.itemArray.first(where: { ($0.representedObject as? String) == value }) { + picker.select(item) return } + let title = URL(fileURLWithPath: value).lastPathComponent + let item = NSMenuItem(title: title, action: nil, keyEquivalent: "") + item.representedObject = value + item.toolTip = value + picker.menu?.addItem(item) + picker.select(item) } - private func reloadConfigurationAndAnimations() { - apiGeneration += 1 - apiServer?.stop() - apiServer = nil - clearRuntimeState() + @objc private func chooseConfigurationAnimation() { + guard let configurationWindow else { return } + let panel = NSOpenPanel() + panel.allowedContentTypes = [.png] + panel.beginSheetModal(for: configurationWindow) { [weak self] response in + guard response == .OK, let url = panel.url, let self, let picker = self.defaultAnimationPicker + else { return } + self.selectAnimation(url.path, in: picker) + } + } + + @objc private func cancelConfigurationEdit() { + configurationWindow?.close() + } + + @objc private func acceptConfigurationEdit() { + guard let maxWaitTimeField, + let autoStartCheckbox, + let defaultAnimationPicker, + let selectedAnimation = defaultAnimationPicker.selectedItem?.representedObject as? String + else { return } + + guard let maxWaitTime = Double(maxWaitTimeField.stringValue), + maxWaitTime.isFinite, maxWaitTime > 0 + else { + showConfigurationEditorError("Maximum wait time must be a positive finite number.") + return + } + + let animation: String + do { + _ = try AppConfiguration.resolveDefaultAnimation( + selectedAnimation, in: AppConfiguration.configurationDirectory) + let encoder = JSONEncoder() + encoder.outputFormatting = [.withoutEscapingSlashes] + animation = String(decoding: try encoder.encode(selectedAnimation), as: UTF8.self) + } catch { + showConfigurationEditorError(error.localizedDescription) + return + } + + let configurationText = """ + # Maximum seconds to wait since the last client keepalive. + max_wait_time = \(maxWaitTime) + # Whether Nyathing should launch automatically when you log in. + auto_start = \(autoStartCheckbox.state == .on ? "true" : "false") + # Animation name, PNG path, or "random" used when a client omits the animation field. + default_animation = \(animation) + """ + + let configurationURL = AppConfiguration.configurationDirectory + .appendingPathComponent("config.toml") + do { + try configurationText.write(to: configurationURL, atomically: true, encoding: .utf8) + } catch { + showConfigurationEditorError(error.localizedDescription) + return + } + + configurationWindow?.close() + reloadConfiguration() + } + + private func showConfigurationEditorError(_ message: String) { + let alert = NSAlert() + alert.alertStyle = .warning + alert.messageText = "Unable to Apply Configuration" + alert.informativeText = message + alert.addButton(withTitle: "OK") + alert.runModal() + } + + func windowWillClose(_ notification: Notification) { + guard (notification.object as? NSWindow) === configurationWindow else { return } + configurationWindow = nil + maxWaitTimeField = nil + autoStartCheckbox = nil + defaultAnimationPicker = nil + } + + private func reloadConfiguration() { do { - let configuration = try AppConfiguration.load() + let configuration = try AppConfiguration.load(validateDefaultAnimation: false) do { try LaunchAgentSupport.configure( enabled: configuration.autoStart, @@ -171,9 +734,14 @@ final class AppDelegate: NSObject, NSApplicationDelegate { } catch { NyathingLog.report(error, context: "Unable to configure login launch") } - activityTimeout = configuration.activityTimeout - defaultAnimation = configuration.defaultAnimation - try startAPIServer() + maxWaitTime = configuration.maxWaitTime + if let apiServer { + apiServer.updateStartSettings( + defaultAnimation: { try configuration.resolvedDefaultAnimation }, + maxWaitTime: maxWaitTime) + } else { + try startAPIServer(configuration: configuration) + } } catch { let configurationURL = AppConfiguration.configurationDirectory.appendingPathComponent( "config.toml") @@ -190,111 +758,164 @@ final class AppDelegate: NSObject, NSApplicationDelegate { updateMainStatusItem() } - private func startAPIServer() throws { + private func startAPIServer(configuration: AppConfiguration) throws { let generation = apiGeneration - apiServer = LocalAPIServer( - defaultAnimation: defaultAnimation, - onStart: { [weak self] filename in + let server = LocalAPIServer( + defaultAnimation: { try configuration.resolvedDefaultAnimation }, + maxWaitTime: maxWaitTime, + onStart: { + [weak self] filename, description, requestedID, interval, intervalWasProvided, timeout in try DispatchQueue.main.sync { guard let self, self.apiGeneration == generation else { throw LocalAPIError.unavailable } - return self.startActivity(animation: filename).uuidString + if let requestedID, + self.externalActivityIDs[requestedID] != nil + || self.cancelledActivityIDs.contains(requestedID) + { + throw LocalAPIError.activityIDInUse(requestedID) + } + let id = try self.startActivity( + animation: filename, description: description, activityTimeout: timeout, + keepaliveInterval: interval, intervalWasProvided: intervalWasProvided + ) + let externalID = requestedID ?? id.uuidString + self.externalActivityIDs[externalID] = id + return externalID } }, onKeepalive: { [weak self] activityID in try DispatchQueue.main.sync { - guard let self, self.apiGeneration == generation, - let id = UUID(uuidString: activityID), self.keepaliveActivity(id) - else { + guard let self, self.apiGeneration == generation else { throw LocalAPIError.unavailable } + let id = try self.activeActivityID(for: activityID) + guard self.keepaliveActivity(id) else { throw LocalAPIError.unknownActivity } } }, onStop: { [weak self] activityID in try DispatchQueue.main.sync { - guard let self, self.apiGeneration == generation, - let id = UUID(uuidString: activityID), self.lifecycle.animation(for: id) != nil - else { - throw LocalAPIError.unknownActivity - } + guard let self, self.apiGeneration == generation else { throw LocalAPIError.unavailable } + let id = try self.activeActivityID(for: activityID) self.stopActivity(id) + self.externalActivityIDs.removeValue(forKey: activityID) } } ) - try apiServer?.start() + try server.start() + apiServer = server } - private func clearRuntimeState() { - for active in activeAnimations.values { - NSStatusBar.system.removeStatusItem(active.statusItem) + private func activeActivityID(for externalID: String) throws -> UUID { + if cancelledActivityIDs.contains(externalID) { + throw LocalAPIError.animationCancelled } - activeAnimations.removeAll() - updateMainStatusItemVisibility() - lifecycle.reset() - warningFrames = [] - warningFrameIndex = 0 + guard let id = externalActivityIDs[externalID], lifecycle.animation(for: id) != nil else { + throw LocalAPIError.unknownActivity + } + return id } /// Begins an activity for a named animation, sharing its status item with matching activities. @discardableResult - func startActivity(animation filename: String) -> UUID { - let deadline = DispatchTime.now() + activityTimeout + func startActivity( + animation filename: String, description: String? = nil, + activityTimeout timeout: TimeInterval? = nil, + keepaliveInterval: TimeInterval = LocalAPIServer.defaultKeepaliveInterval, + intervalWasProvided: Bool = false + ) throws -> UUID { + let directory = AppConfiguration.configurationDirectory.appendingPathComponent( + "animations", isDirectory: true) + let resolvedFilename = try NyathingCLI.resolveAnimation(filename, in: directory) + let existingAnimation = activeAnimations[resolvedFilename] + let frames: [NSImage]? + if existingAnimation == nil { + let sourceFrames: [NSImage] + if resolvedFilename == NyathingCLI.builtInGhostAnimation { + sourceFrames = Self.builtInGhostFrames() + } else { + sourceFrames = try SpriteAnimation.load(from: URL(fileURLWithPath: resolvedFilename)).frames + } + frames = Self.scaledAnimationFrames(sourceFrames, height: 22) + } else { + frames = nil + } + + let timeout = timeout ?? min(LocalAPIServer.defaultKeepaliveInterval * 2, maxWaitTime) + let deadline = DispatchTime.now() + timeout let deadlineUptime = deadline.uptimeNanoseconds - let id = lifecycle.start(animation: filename, deadline: deadlineUptime) + let id = lifecycle.start( + animation: resolvedFilename, description: description, deadline: deadlineUptime) + activityStartOrder[id] = nextActivityStartOrder + activityStartUptime[id] = ProcessInfo.processInfo.systemUptime + nextActivityStartOrder &+= 1 + activityTimeouts[id] = timeout + activityKeepaliveIntervals[id] = keepaliveInterval + activityKeepaliveIntervalSources[id] = + intervalWasProvided ? "client-provided" : "built-in default" scheduleActivityExpiration(id, deadlineUptime: deadlineUptime) - if let active = activeAnimations[filename] { + if let active = existingAnimation { active.activityIDs.insert(id) updateActivityStatus(active) updateMainStatusItemVisibility() + updateMainStatusItem() + refreshStatusItemMenus() + refreshActiveActivitiesWindow() return id } - let directory = AppConfiguration.configurationDirectory.appendingPathComponent( - "animations", isDirectory: true) - let animations = SpriteAnimation.loadAll(in: directory) - let frames: [NSImage] - switch AnimationResolution.resolve(filename, available: animations) { - case .asset(let animation): frames = animation.frames - case .builtInGhost: frames = Self.builtInGhostFrames() - } + guard let frames else { preconditionFailure("New animations must have decoded frames.") } let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength) + configureMenu(for: statusItem) let active = ActiveAnimation( - filename: filename, statusItem: statusItem, frames: frames, activityIDs: [id]) - activeAnimations[filename] = active + filename: resolvedFilename, statusItem: statusItem, frames: frames, activityIDs: [id]) + activeAnimations[resolvedFilename] = active updateActivityStatus(active) updateMainStatusItemVisibility() + updateMainStatusItem() + refreshStatusItemMenus() + refreshActiveActivitiesWindow() return id } /// Ends an activity without counting it as a disconnect. func stopActivity(_ id: UUID) { guard let filename = lifecycle.stop(id) else { return } + activityTimeouts.removeValue(forKey: id) + activityKeepaliveIntervals.removeValue(forKey: id) + activityKeepaliveIntervalSources.removeValue(forKey: id) + activityStartOrder.removeValue(forKey: id) + activityStartUptime.removeValue(forKey: id) + refreshActiveActivitiesWindow() removeActivityFromStatusItem(id, animation: filename) + refreshStatusItemMenus() } private func removeActivityFromStatusItem(_ id: UUID, animation filename: String) { guard let active = activeAnimations[filename] else { return } active.activityIDs.remove(id) if active.activityIDs.isEmpty { - NSStatusBar.system.removeStatusItem(active.statusItem) activeAnimations.removeValue(forKey: filename) + NSStatusBar.system.removeStatusItem(active.statusItem) updateMainStatusItemVisibility() + updateMainStatusItem() } else { updateActivityStatus(active) } } - /// Displays the timeout effect after lifecycle accounting records an expired activity. + /// Refreshes the static error indicator after lifecycle accounting records a timeout. private func presentActivityTimeout() { - let directory = AppConfiguration.configurationDirectory.appendingPathComponent( - "animations", isDirectory: true) - if let explosion = SpriteAnimation.loadAll(in: directory)["explosion_36x36.png"] { - warningFrames = explosion.frames - warningFrameIndex = 0 - } else { - warningFrames = [] - NyathingLog.write("Explosion animation explosion_36x36.png is missing or invalid") - } + updateMainStatusItemVisibility() updateMainStatusItem() + refreshErrorsWindow() + } + + private static func scaledAnimationFrames(_ frames: [NSImage], height: CGFloat) -> [NSImage] { + frames.map { frame in + let scaled = (frame.copy() as? NSImage) ?? frame + let scale = height / frame.size.height + scaled.size = NSSize(width: frame.size.width * scale, height: height) + return scaled + } } private func updateActivityStatus(_ active: ActiveAnimation) { @@ -341,7 +962,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate { } private func keepaliveActivity(_ id: UUID) -> Bool { - let deadline = DispatchTime.now() + activityTimeout + let fallbackTimeout = min(LocalAPIServer.defaultKeepaliveInterval * 2, maxWaitTime) + let deadline = DispatchTime.now() + (activityTimeouts[id] ?? fallbackTimeout) let deadlineUptime = deadline.uptimeNanoseconds guard lifecycle.keepalive(id, deadline: deadlineUptime) else { return false } scheduleActivityExpiration(id, deadlineUptime: deadlineUptime) @@ -370,40 +992,47 @@ final class AppDelegate: NSObject, NSApplicationDelegate { } return } - guard let filename = lifecycle.expire(id, deadline: deadlineUptime) else { return } - removeActivityFromStatusItem(id, animation: filename) + guard let expired = lifecycle.expire(id, deadline: deadlineUptime) else { return } + let interval = + activityKeepaliveIntervals.removeValue(forKey: id) + ?? LocalAPIServer.defaultKeepaliveInterval + let intervalSource = + activityKeepaliveIntervalSources.removeValue(forKey: id) + ?? "built-in default" + let timeout = activityTimeouts.removeValue(forKey: id) ?? min(interval * 2, maxWaitTime) + externalActivityIDs = externalActivityIDs.filter { $0.value != id } + timedOutActivityDetails[id] = ActivityTimeoutDetails( + keepaliveInterval: interval, intervalSource: intervalSource, + timeout: timeout, maxWaitTime: maxWaitTime) + activityStartOrder.removeValue(forKey: id) + activityStartUptime.removeValue(forKey: id) + refreshActiveActivitiesWindow() + removeActivityFromStatusItem(id, animation: expired.animation) + refreshStatusItemMenus() presentActivityTimeout() } private func advanceAnimations() { for active in activeAnimations.values { + guard !active.frames.isEmpty else { continue } active.frameIndex = (active.frameIndex + 1) % active.frames.count updateActivityStatus(active) } - if !warningFrames.isEmpty { - warningFrameIndex += 1 - if warningFrameIndex >= warningFrames.count { - warningFrames = [] - warningFrameIndex = 0 - } - } updateMainStatusItem() } private func updateMainStatusItemVisibility() { - mainStatusItem?.isVisible = activeAnimations.isEmpty + mainStatusItem?.isVisible = activeAnimations.isEmpty || !lifecycle.timedOutActivities.isEmpty } private func updateMainStatusItem() { guard let button = mainStatusItem?.button else { return } - if lifecycle.disconnectedCount > 0 { - button.image = - warningFrames.isEmpty - ? NSImage( - systemSymbolName: "exclamationmark.triangle.fill", - accessibilityDescription: "Disconnected clients") - : warningFrames[warningFrameIndex] - button.title = "\(lifecycle.disconnectedCount)" + let outstandingErrorCount = lifecycle.timedOutActivities.count + if outstandingErrorCount > 0 { + button.image = NSImage( + systemSymbolName: "exclamationmark.triangle.fill", + accessibilityDescription: "Outstanding timeout errors") + button.title = "\(outstandingErrorCount)" } else { button.image = staticAppIcon @@ -413,7 +1042,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { } button.image?.isTemplate = false button.image?.accessibilityDescription = - lifecycle.disconnectedCount > 0 ? "Disconnected clients" : "Nyathing" + outstandingErrorCount > 0 ? "Outstanding timeout errors" : "Nyathing" } private static func builtInGhostFrames() -> [NSImage] { @@ -432,6 +1061,13 @@ final class AppDelegate: NSObject, NSApplicationDelegate { } } +private struct ActivityTimeoutDetails { + let keepaliveInterval: TimeInterval + let intervalSource: String + let timeout: TimeInterval + let maxWaitTime: TimeInterval +} + private final class ActiveAnimation { let filename: String let statusItem: NSStatusItem diff --git a/Tests/NyathingTests/ConfigurationAndAPITests.swift b/Tests/NyathingTests/ConfigurationAndAPITests.swift index 9d90f4f..78c4a32 100644 --- a/Tests/NyathingTests/ConfigurationAndAPITests.swift +++ b/Tests/NyathingTests/ConfigurationAndAPITests.swift @@ -1,3 +1,4 @@ +import AppKit import Darwin import Foundation import XCTest @@ -23,6 +24,11 @@ final class CLITests: XCTestCase { XCTAssertEqual(dashedCommand.arguments, ["--child-option"]) } + func testUsesConfiguredAnimationWhenNoAnimationIsSpecified() throws { + let parsed = try CLIArguments.parse(["sleep", "5"]) + XCTAssertNil(parsed.animation) + } + func testRejectsMissingCommandOrAnimationValue() { XCTAssertThrowsError(try CLIArguments.parse([])) XCTAssertThrowsError(try CLIArguments.parse(["-a", "animation.png"])) @@ -45,23 +51,112 @@ final class CLITests: XCTestCase { _ = try AppConfiguration.load(in: directory) let animationsDirectory = directory.appendingPathComponent("animations", isDirectory: true) - XCTAssertNoThrow(try NyathingCLI.validateAnimation("nyan_54x36.png", in: animationsDirectory)) + XCTAssertNoThrow(try NyathingCLI.validateAnimation("nyan", in: animationsDirectory)) XCTAssertThrowsError( - try NyathingCLI.validateAnimation("missing_36x36.png", in: animationsDirectory)) + try NyathingCLI.validateAnimation("missing", in: animationsDirectory)) + + let externalDirectory = directory.appendingPathComponent("external") + try FileManager.default.createDirectory( + at: externalDirectory, withIntermediateDirectories: true) + let externalAnimation = externalDirectory.appendingPathComponent("outside_54x36.png") + try FileManager.default.copyItem( + at: animationsDirectory.appendingPathComponent("nyan_54x36.png"), to: externalAnimation) + XCTAssertNoThrow( + try NyathingCLI.validateAnimation(externalAnimation.path, in: animationsDirectory)) XCTAssertThrowsError( - try NyathingCLI.validateAnimation("../nyan_54x36.png", in: animationsDirectory)) + try NyathingCLI.validateAnimation( + externalAnimation.lastPathComponent, in: animationsDirectory)) + } + + func testRandomAnimationSelectsFromAvailableAnimations() throws { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("NyathingRandom-\\(UUID().uuidString)", isDirectory: true) + defer { try? FileManager.default.removeItem(at: directory) } + _ = try AppConfiguration.load(in: directory) + let animationsDirectory = directory.appendingPathComponent("animations", isDirectory: true) + let listedAnimations = Set(SpriteAnimation.loadAll(in: animationsDirectory).keys) + + let selected = try NyathingCLI.resolveAnimation("random", in: animationsDirectory) + + XCTAssertFalse(listedAnimations.isEmpty) + XCTAssertTrue(listedAnimations.contains(URL(fileURLWithPath: selected).lastPathComponent)) + } + + func testNamedRandomAnimationTakesPrecedence() throws { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("NyathingRandom-\\(UUID().uuidString)", isDirectory: true) + defer { try? FileManager.default.removeItem(at: directory) } + _ = try AppConfiguration.load(in: directory) + let animationsDirectory = directory.appendingPathComponent("animations", isDirectory: true) + let randomAnimation = animationsDirectory.appendingPathComponent("random_36x36.png") + try FileManager.default.copyItem( + at: animationsDirectory.appendingPathComponent("nyathing_36x36.png"), to: randomAnimation) + + XCTAssertEqual( + try NyathingCLI.resolveAnimation("random", in: animationsDirectory), + randomAnimation.standardizedFileURL.path) + } + + func testRandomAnimationFallsBackToBuiltInGhostWhenPoolIsEmpty() throws { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("NyathingRandom-\\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + + let selected = try NyathingCLI.resolveAnimation("random", in: directory) + + XCTAssertEqual(selected, NyathingCLI.builtInGhostAnimation) + if case .builtInGhost = AnimationResolution.resolve(selected, available: [:]) { + XCTAssertTrue(true) + } else { + XCTFail("An empty random selection pool must resolve to the built-in ghost.") + } } - func testKeepaliveIntervalPrecedesConfiguredActivityTimeout() { - let configuration = AppConfiguration( - keepaliveInterval: 5, activityTimeout: 0.8, autoStart: false, - defaultAnimation: "nyathing_36x36.png") - XCTAssertEqual(NyathingCLI.keepaliveInterval(for: configuration), 0.4, accuracy: 0.0001) + func testActivityDescriptionJoinsChildCommandAndArguments() { + XCTAssertEqual( + NyathingCLI.activityDescription(command: "./run me", arguments: ["--flag", "a b"]), + "./run me --flag a b") + XCTAssertEqual(NyathingCLI.activityDescription(command: "sleep", arguments: []), "sleep") + } - let shorterConfiguredInterval = AppConfiguration( - keepaliveInterval: 0.2, activityTimeout: 3, autoStart: false, - defaultAnimation: "nyathing_36x36.png") - XCTAssertEqual(NyathingCLI.keepaliveInterval(for: shorterConfiguredInterval), 0.2) + func testZshCompletionTracksCLICommandsAndDynamicAnimations() throws { + let script = try XCTUnwrap(ShellCompletion.script(for: "zsh")) + + for command in documentedCLICommands { + XCTAssertTrue(script.contains(command)) + } + XCTAssertTrue(script.contains("nyathing list")) + XCTAssertTrue(script.contains("start stop status")) + XCTAssertTrue(script.contains("start keepalive stop")) + XCTAssertTrue(script.contains("compadd -- zsh bash")) + } + + func testBashCompletionTracksCLICommandsAndDynamicAnimations() throws { + let script = try XCTUnwrap(ShellCompletion.script(for: "bash")) + + for command in documentedCLICommands { + XCTAssertTrue(script.contains(command)) + } + XCTAssertTrue(script.contains("nyathing list")) + XCTAssertTrue(script.contains("start stop status")) + XCTAssertTrue(script.contains("start keepalive stop")) + XCTAssertTrue(script.contains("zsh bash")) + } + + func testCompletionRejectsUnsupportedShells() { + XCTAssertNil(ShellCompletion.script(for: "fish")) + } + + private var documentedCLICommands: [String] { + let commandsSection = + CLIArguments.usage + .components(separatedBy: "Commands:\n").last? + .components(separatedBy: "\n\nOptions:").first ?? "" + return commandsSection.split(separator: "\n").compactMap { line in + let command = line.split(whereSeparator: \.isWhitespace).first.map(String.init) + return command == "COMMAND" ? nil : command + } } func testHelpAndVersionAreOnlyAvailableAsOptions() throws { @@ -86,6 +181,21 @@ final class CLITests: XCTestCase { XCTAssertEqual(try NyathingCLI.resolveExecutable(name), executable.path) } + + func testResolvesBareArgv0ThroughPathForStartingServer() throws { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("NyathingPATH-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + + let executable = directory.appendingPathComponent("nyathing") + try Data("#!/bin/sh\\nexit 0\\n".utf8).write(to: executable) + XCTAssertEqual(chmod(executable.path, 0o755), 0) + + XCTAssertEqual( + try NyathingCLI.resolveExecutable("nyathing", searchPath: directory.path), + executable.path) + } } final class ConfigurationTests: XCTestCase { @@ -104,8 +214,8 @@ final class ConfigurationTests: XCTestCase { func testFirstLaunchSeedsConfigurationAndSampleAnimation() throws { let configuration = try AppConfiguration.load(in: temporaryDirectory) - XCTAssertEqual(configuration.keepaliveInterval, 5) - XCTAssertEqual(configuration.defaultAnimation, "nyathing_36x36.png") + XCTAssertEqual(configuration.maxWaitTime, 180) + XCTAssertEqual(try configuration.defaultAnimation, "nyathing") XCTAssertTrue( FileManager.default.fileExists( atPath: temporaryDirectory.appendingPathComponent("config.toml").path)) @@ -130,17 +240,101 @@ final class ConfigurationTests: XCTestCase { let matrix = try SpriteAnimation.load(from: matrixURL) XCTAssertEqual(matrix.frameSize, NSSize(width: 36, height: 36)) XCTAssertEqual(matrix.frames.count, 16) - let explosionURL = temporaryDirectory.appendingPathComponent("animations/explosion_36x36.png") - XCTAssertTrue(FileManager.default.fileExists(atPath: explosionURL.path)) - let explosion = try SpriteAnimation.load(from: explosionURL) - XCTAssertEqual(explosion.frameSize, NSSize(width: 36, height: 36)) - XCTAssertEqual(explosion.frames.count, 16) + } + + func testMigratesLegacyKeepaliveConfiguration() throws { + let legacy = AppConfiguration.template.replacingOccurrences( + of: "max_wait_time = 180", + with: "keepalive_interval_seconds = 7") + try writeConfiguration(legacy) + + let configuration = try AppConfiguration.load(in: temporaryDirectory) + + XCTAssertEqual(configuration.maxWaitTime, 180) + let saved = try String( + contentsOf: temporaryDirectory.appendingPathComponent("config.toml"), encoding: .utf8) + XCTAssertFalse(saved.contains("keepalive_interval_seconds")) + XCTAssertTrue(saved.contains("max_wait_time = 180")) + } + + func testRandomIsAcceptedAsDefaultAnimation() throws { + let configurationText = AppConfiguration.template.replacingOccurrences( + of: "default_animation = \"nyathing\"", + with: "default_animation = \"random\"") + try writeConfiguration(configurationText) + + let configuration = try AppConfiguration.load(in: temporaryDirectory) + + XCTAssertEqual(try configuration.defaultAnimation, "random") + XCTAssertEqual(try configuration.resolvedDefaultAnimation, "random") + } + + func testDefaultAnimationAcceptsShortNameAndPaths() throws { + let external = temporaryDirectory.appendingPathComponent("custom # sprite_36x36.png") + try writePNG(width: 36, height: 36, to: external) + let installed = temporaryDirectory.appendingPathComponent("animations/nyathing_36x36.png") + for (value, expected) in [ + ("nyathing", installed), + ("nyathing_36x36.png", installed), + (external.path, external), + ("./\(external.lastPathComponent)", external), + ] { + let configurationText = AppConfiguration.template.replacingOccurrences( + of: "default_animation = \"nyathing\"", + with: "default_animation = \"\(value)\"") + try writeConfiguration(configurationText) + let configuration = try AppConfiguration.load(in: temporaryDirectory) + XCTAssertEqual(try configuration.defaultAnimation, value) + XCTAssertEqual(try configuration.resolvedDefaultAnimation, expected.standardizedFileURL.path) + } + } + + func testLoadsAnimationWithFrameDimensionsFromFilename() throws { + let url = temporaryDirectory.appendingPathComponent("wide_64x48.png") + try writePNG(width: 128, height: 48, to: url) + + let animation = try SpriteAnimation.load(from: url) + + XCTAssertEqual(animation.frameSize, NSSize(width: 64, height: 48)) + XCTAssertEqual(animation.frames.count, 2) + } + + func testShortAnimationNameResolvesLargestValidFrame() throws { + _ = try AppConfiguration.load(in: temporaryDirectory) + let animationsDirectory = temporaryDirectory.appendingPathComponent("animations") + let largerAnimation = animationsDirectory.appendingPathComponent("nyathing_64x48.png") + try writePNG(width: 128, height: 48, to: largerAnimation) + + XCTAssertEqual( + try NyathingCLI.resolveAnimation("nyathing", in: animationsDirectory), + largerAnimation.standardizedFileURL.path) + XCTAssertEqual( + try NyathingCLI.resolveAnimation("nyathing", in: animationsDirectory), + try NyathingCLI.resolveAnimation(largerAnimation.path, in: animationsDirectory)) + } + + func testRejectsFrameDimensionsOutsideSupportedBounds() { + for filename in ["small_15x36.png", "large_257x36.png", "wide_256x16.png"] { + XCTAssertThrowsError( + try SpriteAnimation.load(from: URL(fileURLWithPath: "/tmp/\(filename)")), + filename) + } + } + + func testRejectsOversizedSpriteSheetsAndExcessiveFrameCounts() throws { + let oversized = temporaryDirectory.appendingPathComponent("large_256x256.png") + try writePNG(width: 256 * 62, height: 256, to: oversized) + XCTAssertThrowsError(try SpriteAnimation.load(from: oversized)) + + let tooManyFrames = temporaryDirectory.appendingPathComponent("many_16x16.png") + try writePNG(width: 16 * 121, height: 16, to: tooManyFrames) + XCTAssertThrowsError(try SpriteAnimation.load(from: tooManyFrames)) } func testRemovesObsoleteIconSettingAndKeepsDefaultAnimation() throws { let oldTemplate = AppConfiguration.template .replacingOccurrences( - of: "default_animation = \"nyathing_36x36.png\"", + of: "default_animation = \"nyathing\"", with: "default_animation = \"ghost_36x36.png\"" ) .replacingOccurrences( @@ -149,8 +343,7 @@ final class ConfigurationTests: XCTestCase { let configuration = try AppConfiguration.load(in: temporaryDirectory) - XCTAssertEqual(configuration.keepaliveInterval, 5) - XCTAssertEqual(configuration.activityTimeout, 5) + XCTAssertEqual(configuration.maxWaitTime, 180) XCTAssertFalse(configuration.autoStart) let savedConfig = try String( contentsOf: temporaryDirectory.appendingPathComponent("config.toml"), encoding: .utf8) @@ -177,15 +370,28 @@ final class ConfigurationTests: XCTestCase { func testRejectsMissingAndNonPositiveSettings() throws { try writeConfiguration( - "keepalive_interval_seconds = 5\nactivity_timeout_seconds = 5\nauto_start = false\n") + "max_wait_time = 0\nauto_start = false\n") XCTAssertThrowsError(try AppConfiguration.load(in: temporaryDirectory)) try writeConfiguration( AppConfiguration.template.replacingOccurrences( - of: "activity_timeout_seconds = 5", with: "activity_timeout_seconds = 0")) + of: "max_wait_time = 180", with: "max_wait_time = 0")) XCTAssertThrowsError(try AppConfiguration.load(in: temporaryDirectory)) } + private func writePNG(width: Int, height: Int, to url: URL) throws { + guard + let bitmap = NSBitmapImageRep( + bitmapDataPlanes: nil, pixelsWide: width, pixelsHigh: height, bitsPerSample: 8, + samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB, + bytesPerRow: 0, bitsPerPixel: 0), + let data = bitmap.representation(using: .png, properties: [:]) + else { + throw NSError(domain: "ConfigurationTests", code: 1) + } + try data.write(to: url) + } + private func writeConfiguration(_ contents: String) throws { try FileManager.default.createDirectory( at: temporaryDirectory.appendingPathComponent("animations"), @@ -203,6 +409,22 @@ final class ConfigurationTests: XCTestCase { } final class ActivityLifecycleTests: XCTestCase { + func testCancelledIDIsReservedUntilItsDeadlineWithoutConsumingIt() { + var cancelled = CancelledActivityIDs() + let start = DispatchTime(uptimeNanoseconds: 1_000_000_000) + let deadline = cancelled.reserve("test", for: 5, now: start) + XCTAssertEqual(deadline, start + .seconds(5)) + XCTAssertTrue(cancelled.contains("test", now: start + .seconds(1))) + XCTAssertTrue(cancelled.contains("test", now: start + .seconds(4))) + XCTAssertFalse(cancelled.contains("test", now: deadline)) + + let replacement = cancelled.reserve("test", for: 2, now: deadline) + cancelled.remove("test", deadline: deadline) + XCTAssertTrue(cancelled.contains("test", now: deadline)) + cancelled.remove("test", deadline: replacement) + XCTAssertFalse(cancelled.contains("test", now: deadline)) + } + func testAggregatesActivitiesAndDistinguishesExplicitStopFromTimeout() throws { var lifecycle = ActivityLifecycle() let first = lifecycle.start(animation: "same_36x36.png", deadline: 10) @@ -219,11 +441,59 @@ final class ActivityLifecycleTests: XCTestCase { XCTAssertNil( lifecycle.expire(second, deadline: 20), "An obsolete timeout must not expire a renewed activity.") - XCTAssertEqual(lifecycle.expire(second, deadline: 40), "same_36x36.png") + XCTAssertEqual( + lifecycle.expire(second, deadline: 40), + ActivityLifecycle.ExpiredActivity( + id: second, animation: "same_36x36.png", description: ActivityLifecycle.missingDescription)) XCTAssertEqual(lifecycle.disconnectedCount, 1) XCTAssertEqual(lifecycle.activityCount(for: "same_36x36.png"), 0) - XCTAssertEqual(lifecycle.expire(distinct, deadline: 30), "other_36x36.png") + XCTAssertEqual( + lifecycle.expire(distinct, deadline: 30), + ActivityLifecycle.ExpiredActivity( + id: distinct, animation: "other_36x36.png", + description: ActivityLifecycle.missingDescription)) XCTAssertEqual(lifecycle.disconnectedCount, 2) + XCTAssertEqual(lifecycle.timedOutActivities.count, 2) + } + + func testDescriptionsAreRetainedThroughTimeoutAndDefaultWhenAbsent() { + var lifecycle = ActivityLifecycle() + let described = lifecycle.start( + animation: "nyathing_36x36.png", description: "build test", deadline: 10) + let undescribed = lifecycle.start(animation: "nyathing_36x36.png", deadline: 20) + + XCTAssertEqual(lifecycle.description(for: described), "build test") + XCTAssertEqual(lifecycle.description(for: undescribed), ActivityLifecycle.missingDescription) + XCTAssertEqual( + lifecycle.expire(described, deadline: 10), + ActivityLifecycle.ExpiredActivity( + id: described, animation: "nyathing_36x36.png", description: "build test")) + XCTAssertEqual( + lifecycle.expire(undescribed, deadline: 20), + ActivityLifecycle.ExpiredActivity( + id: undescribed, animation: "nyathing_36x36.png", + description: ActivityLifecycle.missingDescription)) + XCTAssertEqual( + lifecycle.timedOutActivities.map(\.description), + [ + "build test", ActivityLifecycle.missingDescription, + ]) + } + + func testAcknowledgesTimeoutsIndividuallyEvenWhenDescriptionsMatch() { + var lifecycle = ActivityLifecycle() + let first = lifecycle.start(animation: "one", description: "same", deadline: 10) + let second = lifecycle.start(animation: "two", description: "same", deadline: 20) + _ = lifecycle.expire(first, deadline: 10) + _ = lifecycle.expire(second, deadline: 20) + + XCTAssertTrue(lifecycle.acknowledgeTimeout(first)) + XCTAssertEqual(lifecycle.timedOutActivities.map(\.id), [second]) + XCTAssertEqual(lifecycle.disconnectedCount, 1) + XCTAssertFalse(lifecycle.acknowledgeTimeout(first)) + XCTAssertTrue(lifecycle.acknowledgeTimeout(second)) + XCTAssertTrue(lifecycle.timedOutActivities.isEmpty) + XCTAssertEqual(lifecycle.disconnectedCount, 0) } func testResetClearsActivitiesDeadlinesAndDisconnectCount() throws { @@ -238,11 +508,93 @@ final class ActivityLifecycleTests: XCTestCase { XCTAssertEqual(lifecycle.disconnectedCount, 0) XCTAssertNil(lifecycle.animation(for: activeID)) XCTAssertNil(lifecycle.deadline(for: activeID)) + XCTAssertTrue(lifecycle.timedOutActivities.isEmpty) XCTAssertEqual(lifecycle.activityCount(for: "same_36x36.png"), 0) } } final class LocalAPIServerTests: XCTestCase { + func testExplicitAnimationDoesNotRequireValidConfiguredDefault() throws { + let directory = URL( + fileURLWithPath: "/tmp/nyathing-\(UUID().uuidString.prefix(8))", isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let text = AppConfiguration.template.replacingOccurrences( + of: "default_animation = \"nyathing\"", with: "default_animation = false") + try text.write( + to: directory.appendingPathComponent("config.toml"), atomically: true, encoding: .utf8) + let configuration = try AppConfiguration.load(in: directory, validateDefaultAnimation: false) + let animations = directory.appendingPathComponent("animations", isDirectory: true) + let socketPath = directory.appendingPathComponent("api.sock").path + let server = LocalAPIServer( + socketPath: socketPath, + defaultAnimation: { try configuration.resolvedDefaultAnimation }, + onStart: { animation, _, _, _, _, _ in + try NyathingCLI.resolveAnimation(animation, in: animations) + }, onKeepalive: { _ in }, onStop: { _ in }) + try server.start() + defer { server.stop() } + + let client = try UnixJSONClient(path: socketPath) + XCTAssertEqual( + try client.command(["command": "start", "animation": "nyathing"])["ok"] as? Bool, true) + let invalid = try client.command(["command": "start", "animation": "not-installed"]) + XCTAssertEqual(invalid["ok"] as? Bool, false) + XCTAssertEqual(invalid["error_code"] as? String, "animation_unavailable") + XCTAssertTrue((invalid["error"] as? String)?.contains("not-installed") == true) + let omitted = try client.command(["command": "start"]) + XCTAssertEqual(omitted["ok"] as? Bool, false) + XCTAssertEqual(omitted["error_code"] as? String, "invalid_default_animation") + XCTAssertTrue((omitted["error"] as? String)?.contains("default_animation") == true) + } + + func testRequestFailuresIncludeStableCodesAndReadableMessages() throws { + let directory = URL( + fileURLWithPath: "/tmp/nyathing-\(UUID().uuidString.prefix(8))", isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let socketPath = directory.appendingPathComponent("api.sock").path + let server = LocalAPIServer( + socketPath: socketPath, defaultAnimation: { "nyathing" }, + onStart: { _, _, _, _, _, _ in throw LocalAPIError.activityIDInUse("test") }, + onKeepalive: { _ in throw LocalAPIError.animationCancelled }, + onStop: { id in + if id == "test" { throw LocalAPIError.animationCancelled } + throw LocalAPIError.unknownActivity + }) + try server.start() + defer { server.stop() } + + let client = try UnixJSONClient(path: socketPath) + let malformed = try client.commandLine(Data("{".utf8)) + XCTAssertEqual(malformed["ok"] as? Bool, false) + XCTAssertEqual(malformed["error_code"] as? String, "invalid_request") + XCTAssertEqual(malformed["error"] as? String, "Invalid JSON Lines request.") + + let cases: [([String: Any], String, String)] = [ + (["command": "bogus"], "unknown_command", "Unknown command: bogus."), + ( + ["command": "start", "activity_id": "test"], "activity_id_in_use", + "Activity ID \"test\" is already in use." + ), + ( + ["command": "keepalive", "activity_id": "test"], "animation_cancelled", + "Animation was cancelled." + ), + ( + ["command": "stop", "activity_id": "test"], "animation_cancelled", + "Animation was cancelled." + ), + (["command": "stop", "activity_id": "missing"], "unknown_activity", "Unknown activity ID."), + ] + for (request, code, message) in cases { + let response = try client.command(request) + XCTAssertEqual(response["ok"] as? Bool, false) + XCTAssertEqual(response["error_code"] as? String, code) + XCTAssertEqual(response["error"] as? String, message) + } + } + func testMultipleCommandsOnConnectionAndConcurrentClients() throws { let directory = URL( fileURLWithPath: "/tmp/nyathing-\(UUID().uuidString.prefix(8))", isDirectory: true) @@ -251,15 +603,29 @@ final class LocalAPIServerTests: XCTestCase { let socketPath = directory.appendingPathComponent("api.sock").path let lock = NSLock() var startedAnimations: [String] = [] + var requestedActivityIDs: [String?] = [] + var startedDescriptions: [String?] = [] + var startedTimeouts: [Double] = [] + var startedIntervals: [Double] = [] + var startedIntervalsWereProvided: [Bool] = [] var stoppedIDs: [String] = [] let server = LocalAPIServer( socketPath: socketPath, - defaultAnimation: "nyan_54x36.png", - onStart: { animation in + defaultAnimation: { "nyan_54x36.png" }, + maxWaitTime: 30, + onStart: { animation, description, requestedID, interval, intervalWasProvided, timeout in lock.lock() defer { lock.unlock() } + if let requestedID, requestedActivityIDs.contains(requestedID) { + throw LocalAPIError.activityIDInUse(requestedID) + } startedAnimations.append(animation) - return "activity-\(startedAnimations.count)" + requestedActivityIDs.append(requestedID) + startedDescriptions.append(description) + startedIntervals.append(interval) + startedIntervalsWereProvided.append(intervalWasProvided) + startedTimeouts.append(timeout) + return requestedID ?? "activity-\(startedAnimations.count)" }, onKeepalive: { _ in }, onStop: { id in lock.lock() @@ -270,36 +636,82 @@ final class LocalAPIServerTests: XCTestCase { defer { server.stop() } let first = try UnixJSONClient(path: socketPath) + let defaultIntervalStart = try first.command(["command": "start"]) + XCTAssertEqual(defaultIntervalStart["activity_id"] as? String, "activity-1") + let nonPositiveInterval = try first.command([ + "command": "start", "keepalive_interval_seconds": 0, + ]) + XCTAssertEqual(nonPositiveInterval["ok"] as? Bool, false) + XCTAssertTrue( + (nonPositiveInterval["error"] as? String)?.contains("positive finite number") == true) + let largeInterval = try first.command([ + "command": "start", "keepalive_interval_seconds": 30, + ]) + XCTAssertEqual(largeInterval["activity_id"] as? String, "activity-2") + XCTAssertEqual(startedTimeouts[1], 30) + let firstStart = try first.command([ + "command": "start", "activity_id": "turn-123", "animation": "same_36x36.png", + "description": "first client", "keepalive_interval_seconds": 8, + ]) + XCTAssertEqual(firstStart["activity_id"] as? String, "turn-123") + let duplicateStart = try first.command([ + "command": "start", "activity_id": "turn-123", + ]) + XCTAssertEqual(duplicateStart["ok"] as? Bool, false) XCTAssertEqual( - try first.command(["command": "start", "animation": "same_36x36.png"])["activity_id"] - as? String, - "activity-1") + duplicateStart["error"] as? String, + "Activity ID \"turn-123\" is already in use.") + XCTAssertEqual(startedTimeouts[2], 16) XCTAssertEqual( - try first.command(["command": "keepalive", "activity_id": "activity-1"])["ok"] as? Bool, + try first.command(["command": "keepalive", "activity_id": "turn-123"])["ok"] as? Bool, true) XCTAssertEqual( - try first.command(["command": "stop", "activity_id": "activity-1"])["ok"] as? Bool, true) + try first.command(["command": "stop", "activity_id": "turn-123"])["ok"] as? Bool, true) let second = try UnixJSONClient(path: socketPath) + let secondStart = try second.command([ + "command": "start", "animation": "same_36x36.png", "keepalive_interval_seconds": 5, + ]) + XCTAssertEqual(secondStart["activity_id"] as? String, "activity-4") + XCTAssertEqual(startedTimeouts[3], 10) XCTAssertEqual( - try second.command(["command": "start", "animation": "same_36x36.png"])["activity_id"] + try second.command(["command": "start", "keepalive_interval_seconds": 1])["activity_id"] as? String, - "activity-2") - XCTAssertEqual( - try second.command(["command": "start"])["activity_id"] as? String, - "activity-3") + "activity-5") lock.lock() XCTAssertEqual( - startedAnimations, ["same_36x36.png", "same_36x36.png", "nyan_54x36.png"]) - XCTAssertEqual(stoppedIDs, ["activity-1"]) + startedAnimations, + ["nyan_54x36.png", "nyan_54x36.png", "same_36x36.png", "same_36x36.png", "nyan_54x36.png"]) + XCTAssertEqual(stoppedIDs, ["turn-123"]) + XCTAssertEqual(requestedActivityIDs, [nil, nil, "turn-123", nil, nil]) + XCTAssertEqual(startedDescriptions, [nil, nil, "first client", nil, nil]) + XCTAssertEqual(startedTimeouts, [10, 30, 16, 10, 2]) + XCTAssertEqual(startedIntervals, [5, 30, 8, 5, 1]) + XCTAssertEqual(startedIntervalsWereProvided, [false, true, true, true, true]) lock.unlock() + server.updateStartSettings(defaultAnimation: { "new_36x36.png" }, maxWaitTime: 4) + XCTAssertEqual( + try second.command(["command": "keepalive", "activity_id": "activity-4"])["ok"] as? Bool, + true) + XCTAssertEqual(try second.command(["command": "start"])["activity_id"] as? String, "activity-6") + lock.lock() + XCTAssertEqual(startedAnimations.last, "new_36x36.png") + XCTAssertEqual(startedTimeouts.last, 4) + lock.unlock() + XCTAssertEqual( + try second.command(["command": "stop", "activity_id": "activity-4"])["ok"] as? Bool, + true) + let responseLock = NSLock() var concurrentResults: [Bool] = [] DispatchQueue.concurrentPerform(iterations: 4) { _ in let result = (try? UnixJSONClient(path: socketPath) - .command(["command": "start", "animation": "other_36x36.png"])["ok"] as? Bool) ?? false + .command([ + "command": "start", "animation": "other_36x36.png", + "keepalive_interval_seconds": 5, + ])["ok"] as? Bool) ?? false responseLock.lock() concurrentResults.append(result) responseLock.unlock() @@ -340,8 +752,12 @@ private final class UnixJSONClient { deinit { Darwin.close(descriptor) } - func command(_ request: [String: String]) throws -> [String: Any] { - var data = try JSONSerialization.data(withJSONObject: request) + func command(_ request: [String: Any]) throws -> [String: Any] { + try commandLine(JSONSerialization.data(withJSONObject: request)) + } + + func commandLine(_ line: Data) throws -> [String: Any] { + var data = line data.append(0x0A) let written = data.withUnsafeBytes { Darwin.write(descriptor, $0.baseAddress!, $0.count) } guard written == data.count else { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno)) } diff --git a/assets/claude-code-icon.png b/assets/claude-code-icon.png new file mode 100644 index 0000000..baf83f5 Binary files /dev/null and b/assets/claude-code-icon.png differ diff --git a/assets/codex_icon.png b/assets/codex_icon.png new file mode 100644 index 0000000..bafba2e Binary files /dev/null and b/assets/codex_icon.png differ diff --git a/assets/nyathing-cli.png b/assets/nyathing-cli.png new file mode 100644 index 0000000..c769a16 Binary files /dev/null and b/assets/nyathing-cli.png differ diff --git a/assets/nyathing-client.png b/assets/nyathing-client.png new file mode 100644 index 0000000..b8d15f3 Binary files /dev/null and b/assets/nyathing-client.png differ diff --git a/assets/nyathing-server.png b/assets/nyathing-server.png new file mode 100644 index 0000000..40baa2c Binary files /dev/null and b/assets/nyathing-server.png differ