* Fix typos in comments, docstrings and log messages
Correct 39 spelling mistakes across comments, docstrings and log/error
message strings throughout the package (e.g. "conection" -> "connection",
"Incomming" -> "Incoming", "Rasie" -> "Raise"). All changes are confined
to human-readable text; no identifiers, attributes or D-Bus contracts are
touched, so there is no behavior change. Found with codespell.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* Fix typos in tests and CI workflow
Correct spelling mistakes in test comments, docstrings and data, plus one
in the builder workflow, so the whole tree is clean for the codespell hook
added next. The assertion in test_network_manager.py is updated to match
the corrected "Unknown error while processing" log message in the source.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* Add codespell pre-commit hook
Wire up codespell so spelling mistakes in comments, docstrings and strings
are caught automatically. The vendored frontend panel is excluded, and
"hass" and "astroid" are added to the ignore list as known false positives
(the Home Assistant abbreviation and the pylint dependency package).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* Address review feedback
Improve grammar in several of the touched comments and docstrings: use the
plural "ignore conditions" for the list-returning property, add the missing
auxiliary verb and fix agreement in the timezone-filter comment, fix
"backups ... use" agreement, and reword "underlay" to "underlying" in the
arch module docstring.
Also drop the "*.json" skip from the codespell hook. It was carried over
from another project but is unnecessary here (all tracked JSON is clean),
and skipping it would needlessly leave translation and data JSON unchecked.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* Reword onboarding comment
"overflight" was a literal calque of the German "überflogen"; use the
idiomatic "skimmed through" instead.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* Run pytest in parallel with pytest-xdist
CI executes the full pytest suite serially, which currently takes
around 4-5 minutes. Most of that time is spent in fixture setup
(D-Bus session, mock services, CoreSys construction) rather than the
test bodies, but each test pays this setup cost on its own worker.
Add pytest-xdist and run with -n auto --dist=loadfile so tests are
distributed across CPU cores while keeping all tests of a file on the
same worker (preserves locality and keeps progress output readable).
GitHub Actions standard runners ship 4 vCPUs, so -n auto picks 4
workers in CI; locally on 8-core machines it picks 8. This matches
the pattern Home Assistant Core has been running for a long time
(--numprocesses auto --dist=loadfile in core's pytest-full job),
so the configuration is already battle-tested in a sibling project.
On an 8-core machine this cuts the local run from ~280s to ~88s
(~3.2x); on the 4-vCPU CI runner expect roughly a ~2x reduction.
The dbus-daemon and other session-scoped fixtures are spawned per
worker, so there is no shared state. pytest-cov already handles xdist
worker coverage merging via the standard .coverage.* files.
* Poll for resolution state in datadisk signal tests
test_multiple_datadisk_add_remove_signals and
test_disabled_datadisk_add_remove_signals fire UDisks2
InterfacesAdded/InterfacesRemoved signals through the real session
dbus-daemon and then assert that supervisor's signal handler chain
has updated coresys.resolution.issues. Each assertion was preceded
by ``await udisks2_service.ping()`` (only confirms signal delivery)
and ``await asyncio.sleep(0.2)`` to let the chained async tasks
finish.
The 0.2 s margin was effectively only 0.1 s of slack:
DataDisk._udisks2_interface_added itself does
``await asyncio.sleep(0.1)`` internally to wait for
UDisks2._interfaces_added (a sibling subscriber on the same signal)
to finish updating the block-device cache before the check runs.
Under xdist parallelism on a 4-vCPU CI runner that 100 ms cushion
evaporates, and the assertion races the handler.
Bumping the test sleep would just kick the can. Instead, replace
the four ``sleep+assert`` sites with a small polling helper
(tests.common.wait_for) that re-checks the predicate every 10 ms
up to a 5 s deadline. The wait completes the moment the resolution
state matches, so the test stays fast on idle and is robust under
load — and the assertion's failure mode becomes a clear "predicate
did not become true within 5 s" instead of a value mismatch.
The product-code sleep inside _udisks2_interface_added is still a
real smell (handler ordering shouldn't depend on a fixed sleep)
but is left for a separate fix; this commit is scoped to the test.
* Drop obsolete eager_start type ignore in CoreSys.create_task
The asyncio.AbstractEventLoop.create_task signature only gained the
eager_start keyword in the 3.14 typeshed. Now that Supervisor targets
3.14, the inline # type: ignore is redundant; mypy --warn-unused-ignores
flags it.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Drop redundant int | None casts in OS slot status parsing
SlotStatusDataType already declares size, installed.count, and
activated.count as NotRequired[int], so .get(...) returns int | None
directly. The cast(int | None, ...) wrappers were no-ops; mypy
--warn-redundant-casts flags them.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Drop unreachable scheduler else branch
_Task.interval is annotated float | time; the float|int isinstance
arm narrows to time on the else branch, making the prior elif and
the trailing _LOGGER.critical fallback dead code that mypy
--warn-unreachable flags. Collapse to a plain else for the time arm.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Initialize credentials before pull_image try block
If _get_credentials raises before assigning, the except DockerError
handler at line 380-382 references an unbound credentials local. Mypy
--enable-error-code=possibly-undefined flags this path. Initialize to
an empty dict beforehand so the unauthorized branch reads as "no
credentials known", matching the auth=credentials or None semantics on
the success path.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Use for/else to bind repository_file before .exists() check
If FILE_SUFFIX_CONFIGURATION is ever empty the loop body never runs
and repository_file is referenced unbound. Mypy
--enable-error-code=possibly-undefined flags it. The duplicate
.exists() check after the loop was also redundant: every loop body
either breaks on a hit or falls through to a final miss. Restructure
as for/else so the "no candidate matched" case is handled directly.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Make match statements exhaustive with explicit case _
mypy --enable-error-code=exhaustive-match flags match blocks that fall
through to a trailing return/raise without a wildcard arm. The
behaviour is unchanged; this just hoists the default into the match so
the compiler can verify all cases are handled and future enum
additions are caught.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Tighten mypy: warn-unreachable, redundant casts, unused ignores
Add a [tool.mypy] section so the existing
mypy --ignore-missing-imports supervisor invocation in CI now also
enforces:
warn_unreachable — flags dead code, e.g. else branches the
type system has already eliminated.
warn_redundant_casts — flags cast() calls whose target type
already matches the source.
warn_unused_ignores — flags # type: ignore comments that no
longer suppress anything (typeshed
updates make these accumulate silently).
exhaustive-match — flags match statements without a default
arm, so future enum additions surface
as type errors instead of silent
fallthroughs.
possibly-undefined — flags references to names whose binding
depends on a path that may not run
(e.g. for-loop variables when the
iterable is empty).
ignore_missing_imports moves into the config so future invocations
don't need the CLI flag, but the workflow command is left unchanged
to keep the cache key stable.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Disable import error codes instead of ignoring missing imports
Match the pattern used in Home Assistant Core's mypy config: use
disable_error_code = ["import-not-found", "import-untyped"] rather
than ignore_missing_imports. This drops the (now redundant)
--ignore-missing-imports flag from the CI invocation as well.
The semantics are equivalent for the five untyped third-party deps
(pyudev, log_rate_limit, pulsectl, cpe, atomicwrites), but expressed
as suppressing two specific error codes rather than disabling all
import resolution checks.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Use match/case for scheduler interval dispatch
Express the float-vs-time dispatch as a match statement rather than
isinstance chain. Mypy treats case int() | float() and case time() as
exhaustive over the float | time annotation, so the new
exhaustive-match check is satisfied without a wildcard arm — and any
future broadening of the type will surface here as a static error.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Hoist _get_credentials above pull_image try/finally
Per review feedback: _get_credentials only does dict reads against
internal config state and cannot raise DockerRegistryRateLimitExceeded
or aiodocker.DockerError, so it does not need to live inside the
try block. Lift it out, and place it before the bus listener
registration so a future raise site can't leak a stale listener
through the finally cycle.
This supersedes the earlier credentials: dict = {} initializer; the
local is now bound on every path that reaches the except handler.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Enumerate MountUsage members in container_where match
Replace the case _: catch-all with case MountUsage.BACKUP | None:.
The exhaustive-match check is designed to fire when the matched type
widens, so adding a new MountUsage member without deciding whether it
exposes a container path now produces a build error pointing at this
match. The wildcard form swallowed that question silently.
Behaviour unchanged: BACKUP and None still return None.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The CI workflow used a blanket `cancel-in-progress: true`, which makes
sense for PR runs (collapse to the latest commit) but means pushes to
`main` cancel each other when several PRs merge in quick succession.
There is no shared state between CI runs that would justify either
cancelling or serializing them — each run is independent — and we'd
rather see every commit on `main` get a full check.
Make the concurrency group unique per `run_id` for non-PR events so
pushes to `main` neither cancel nor queue, while PRs keep the existing
cancel-on-new-push behavior through the shared per-ref group.
CI and tox both passed ``--timeout=10`` explicitly, but a plain local
``pytest`` had no timeout — a hung asyncio task or stuck D-Bus signal
handler could stall a developer's run indefinitely while passing CI.
Move the timeout into ``[tool.pytest.ini_options]`` so it applies
everywhere (pytest auto-discovers ``pyproject.toml`` in the repo
root) and drop the now-redundant ``--timeout=10`` flags from
``ci.yaml`` and ``tox.ini``. The full suite already fits comfortably
under 10s per test, and ``@pytest.mark.timeout(N)`` remains
available for per-test overrides if a specific test ever needs more
headroom.
The builder workflow used a blanket `cancel-in-progress: true`, which is
fine for PR runs but harmful on `main`: when several PRs merge in quick
succession and one of them touches `requirements.txt`, the wheels
publish step from the in-flight run gets killed mid-upload. Subsequent
CI runs (and downstream consumers) then fail to install the wheels for
the latest requirements.
Scope `cancel-in-progress` to `pull_request` events so pushes to `main`
queue behind each other through the existing concurrency group, while
PRs still collapse to the latest commit as before.
* Use Unix socket for Supervisor to Core communication
Reintroduce Unix socket support for Supervisor-to-Core communication
(reverted in #6735) with the addition of a feature flag gate. The
feature is now controlled by the `core_unix_socket` feature flag and
disabled by default.
When enabled and Core version supports it, Supervisor communicates with
Core via a Unix socket at /run/os/core.sock instead of TCP. This
eliminates the need for access token authentication on the socket path,
as Core authenticates the peer by the socket connection itself.
Key changes:
- Add FeatureFlag.CORE_UNIX_SOCKET to gate the feature
- HomeAssistantAPI: transport-aware session/url/websocket management
- WSClient: separate connect() (Unix, no auth) and connect_with_auth()
(TCP) class methods with proper error handling
- APIProxy delegates websocket setup to api.connect_websocket()
- Container state tracking for Unix session lifecycle
- CI builder mounts /run/supervisor for integration tests
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Sort feature flags alphabetically
* Drop per-call max_msg_size from WSClient
Hardcode the WebSocket message size cap to 64 MB in WSClient and remove
the parameter from WSClient.connect, connect_with_auth, _ws_connect,
and HomeAssistantAPI.connect_websocket. This was only ever overridden
by APIProxy, so threading it through four layers was unnecessary.
max_msg_size is a cap, not a pre-allocation; aiohttp only grows buffers
to the size of actual incoming messages. Supervisor's own control
channel never approaches 64 MB, so unifying the limit has no runtime
cost.
Addresses review feedback on #6742.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Use Unix socket for Supervisor to Core communication
Switch internal Supervisor-to-Core HTTP and WebSocket communication
from TCP (port 8123) to a Unix domain socket.
The existing /run/supervisor directory on the host (already mounted
at /run/os inside the Supervisor container) is bind-mounted into the
Core container at /run/supervisor. Core receives the socket path via
the SUPERVISOR_CORE_API_SOCKET environment variable, creates the
socket there, and Supervisor connects to it via aiohttp.UnixConnector
at /run/os/core.sock.
Since the Unix socket is only reachable by processes on the same host,
requests arriving over it are implicitly trusted and authenticated as
the existing Supervisor system user. This removes the token round-trip
where Supervisor had to obtain and send Bearer tokens on every Core
API call. WebSocket connections are likewise authenticated implicitly,
skipping the auth_required/auth handshake.
Key design decisions:
- Version-gated by CORE_UNIX_SOCKET_MIN_VERSION so older Core
versions transparently continue using TCP with token auth
- LANDINGPAGE is explicitly excluded (not a CalVer version)
- Hard-fails with a clear error if the socket file is unexpectedly
missing when Unix socket communication is expected
- WSClient.connect() for Unix socket (no auth) and
WSClient.connect_with_auth() for TCP (token auth) separate the
two connection modes cleanly
- Token refresh always uses the TCP websession since it is inherently
a TCP/Bearer-auth operation
- Logs which transport (Unix socket vs TCP) is being used on first
request
Closes#6626
Related Core PR: home-assistant/core#163907
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Close WebSocket on handshake failure and validate auth_required
Ensure the underlying WebSocket connection is closed before raising
when the handshake produces an unexpected message. Also validate that
the first TCP message is auth_required before sending credentials.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Fix pylint protected-access warnings in tests
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Check running container env before using Unix socket
Split use_unix_socket into two properties to handle the Supervisor
upgrade transition where Core is still running with a container
started by the old Supervisor (without SUPERVISOR_CORE_API_SOCKET):
- supports_unix_socket: version check only, used when creating the
Core container to decide whether to set the env var
- use_unix_socket: version check + running container env check, used
for communication decisions
This ensures TCP fallback during the upgrade transition while still
hard-failing if the socket is missing after Supervisor configured
Core to use it.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Improve Core API communication logging and error handling
- Remove transport log from make_request that logged before Core
container was attached, causing misleading connection logs
- Log "Connected to Core via ..." once on first successful API response
in get_api_state, when the transport is actually known
- Remove explicit socket existence check from session property, let
aiohttp UnixConnector produce natural connection errors during
Core startup (same as TCP connection refused)
- Add validation in get_core_state matching get_config pattern
- Restore make_request docstring
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Guard Core API requests with container running check
Add is_running() check to make_request and connect_websocket so no
HTTP or WebSocket connection is attempted when the Core container is
not running. This avoids misleading connection attempts during
Supervisor startup before Core is ready.
Also make use_unix_socket raise if container metadata is not available
instead of silently falling back to TCP. This is a defensive check
since is_running() guards should prevent reaching this state.
Add attached property to DockerInterface to expose whether container
metadata has been loaded.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Reset Core API connection state on container stop
Listen for Core container STOPPED/FAILED events to reset the
connection state: clear the _core_connected flag so the transport
is logged again on next successful connection, and close any stale
Unix socket session.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Only mount /run/supervisor if we use it
* Fix pytest errors
* Remove redundant is_running check from ingress panel update
The is_running() guard in update_hass_panel is now redundant since
make_request checks is_running() internally. Also mock is_running
in the websession test fixture since tests using it need make_request
to proceed past the container running check.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Bind mount /run/supervisor to Supervisor /run/os
Home Assistant OS (as well as the Supervised run scripts) bind mount
/run/supervisor to /run/os in Supervisor. Since we reuse this location
for the communication socket between Supervisor and Core, we need to
also bind mount /run/supervisor to Supervisor /run/os in CI.
* Wrap WebSocket handshake errors in HomeAssistantAPIError
Unexpected exceptions during the WebSocket handshake (KeyError,
ValueError, TypeError from malformed messages) are now wrapped in
HomeAssistantAPIError inside WSClient.connect/connect_with_auth.
This means callers only need to catch HomeAssistantAPIError.
Remove the now-unnecessary except (RuntimeError, ValueError,
TypeError) from proxy _websocket_client and add a proper error
message to the APIError per review feedback.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Narrow WebSocket handshake exception handling
Replace broad `except Exception` with specific exception types that
can actually occur during the WebSocket handshake: KeyError (missing
dict keys), ValueError (bad JSON), TypeError (non-text WS message),
aiohttp.ClientError (connection errors), and TimeoutError. This
avoids silently wrapping programming errors into HomeAssistantAPIError.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Remove unused create_mountpoint from MountBindOptions
The field was added but never used. The /run/supervisor host path
is guaranteed to exist since HAOS creates it for the Supervisor
container mount, so auto-creating the mountpoint is unnecessary.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Clear stale access token before raising on final retry
Move token clear before the attempt check in connect_websocket so
the stale token is always discarded, even when raising on the final
attempt. Without this, the next call would reuse the cached bad token
via _ensure_access_token's fast path, wasting a round-trip.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* Add tests for Unix socket communication and Core API
Add tests for the new Unix socket communication path and improve
existing test coverage:
- Version-based supports_unix_socket and env-based use_unix_socket
- api_url/ws_url transport selection
- Connection lifecycle: connected log after restart, ignoring
unrelated container events
- get_api_state/check_api_state parameterized across versions,
responses, and error cases
- make_request is_running guard and TCP flow with real token fetch
- connect_websocket for both Unix and TCP (with token verification)
- WSClient.connect/connect_with_auth handshake success, errors,
cleanup on failure, and close with pending futures
Consolidate existing tests into parameterized form and drop synthetic
tests that covered very little.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Explicitly allow Python 3.14 syntax for except clauses with multiple
exceptions without parentheses. Despite calling out Python 3.14, AI
commonly suggests to change this syntax.
* Fix version/requirements parsing in setup.py, set version in Dockerfile
Remove the step patching const.py with detected version in CI and do
this during Dockerfile version from BUILD_VERSION argument instead.
Also, fix parsing of the version in `setup.py` - it wasn't working
because it was splitting the files on "/n" instead of newlines,
resulting in all Python packages installed having version string set to
`9999.9.9.dev9999` instead of the expected version.
(Note: setuptools are doing a version string normalization, so the
installed package has stripped leading zeroes and the second component
is `9` instead of the literal `09` used in default string in all places.
Fixing this is out of scope of this change as the ideal solution would
be to change the versioning schema but it should be noted.)
Lastly, clean up builder.yaml environment variables (crane is not used
anymore after #6679).
* Generate setuptools-compatible version for PR builds
For PR builds, we're using plain commit SHA as the version. This is
perfectly fine for Docker tags but it's not acceptable for Python
package version. By fixing the setup.py bug this error surfaced. Work it
around by setting the Package version to the string we used previously
suffixed by the commit SHA as build metadata (delimited by `+`).
When only the workflow changes, CI doesn't trigger rebuild when the PR
is merged to the `main` branch. Since it's a legitimate build trigger,
add it to the paths list.
The manifest step was failing because the image name wasn't set in the
env. Also we can standardize the workflow by using the shared matrix
prepare step.