Skip to content

Improve SmartHomeMonitorWatcherTask: CancellationToken propagation, sync, and logging#60

Merged
thomasneuberger merged 2 commits into
Feature/SmartHomeMonitorWatcherfrom
copilot/sub-pr-59
Mar 22, 2026
Merged

Improve SmartHomeMonitorWatcherTask: CancellationToken propagation, sync, and logging#60
thomasneuberger merged 2 commits into
Feature/SmartHomeMonitorWatcherfrom
copilot/sub-pr-59

Conversation

Copilot AI commented Mar 22, 2026

Copy link
Copy Markdown
Contributor

Addresses review feedback on the SmartHomeMonitorWatcherTask PR: missing cancellation support, race conditions in EnsureMonitorIsRunning, unhandled Unknown state, and noisy logging.

Changes

  • ISmartHomeConnectorEnsureMonitorIsRunning now accepts a CancellationToken

  • HomeAssistantConnector.EnsureMonitorIsRunning

    • Propagates CancellationToken instead of CancellationToken.None
    • Treats MonitorState.Unknown like Idle — attempts StartMonitoringAsync rather than silently returning false
    • Wraps the read-and-start logic in _semaphore to prevent races with CreateMonitorAsync
  • SmartHomeMonitorWatcherTask.ExecuteAsync

    • Checks cancellationToken.ThrowIfCancellationRequested() before work
    • Passes cancellationToken through to the connector
    • Downgrades success log from InformationDebug; uses Warning on failure
public async Task ExecuteAsync(CancellationToken cancellationToken)
{
    cancellationToken.ThrowIfCancellationRequested();

    var isRunning = await smartHomeConnector.EnsureMonitorIsRunning(cancellationToken).ConfigureAwait(false);

    if (!isRunning)
        logger.LogWarning("Smart Home Monitor is not running and could not be started.");
    else
        logger.LogDebug("Smart Home Monitor is running.");
}

🔒 GitHub Advanced Security automatically protects Copilot coding agent pull requests. You can protect all pull requests by enabling Advanced Security for your repositories. Learn more about Advanced Security.

…, logging improvements

Co-authored-by: thomasneuberger <23504477+thomasneuberger@users.noreply.github.com>
Agent-Logs-Url: https://github.com/thomasneuberger/TgHomeBot/sessions/02041d09-0799-491d-ac3a-ccd36acdea63
Copilot AI changed the title [WIP] Add SmartHomeMonitorWatcherTask Improve SmartHomeMonitorWatcherTask: CancellationToken propagation, sync, and logging Mar 22, 2026
Copilot AI requested a review from thomasneuberger March 22, 2026 10:12
@thomasneuberger thomasneuberger marked this pull request as ready for review March 22, 2026 10:15
Copilot AI review requested due to automatic review settings March 22, 2026 10:15
@thomasneuberger thomasneuberger merged commit 0e08a63 into Feature/SmartHomeMonitorWatcher Mar 22, 2026
4 checks passed
@thomasneuberger thomasneuberger deleted the copilot/sub-pr-59 branch March 22, 2026 10:17

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR refines the Smart Home monitor “watchdog” flow by propagating cancellation tokens through the connector API, synchronizing monitor start checks to avoid races, and reducing log noise in the scheduled watcher task.

Changes:

  • Updated ISmartHomeConnector.EnsureMonitorIsRunning to accept a CancellationToken.
  • Improved HomeAssistantConnector.EnsureMonitorIsRunning to propagate cancellation, handle Unknown state like Idle, and synchronize access with a semaphore.
  • Updated SmartHomeMonitorWatcherTask to honor cancellation early, pass the token through, and adjust logging levels (success → Debug, failure → Warning).

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

File Description
TgHomeBot.SmartHome.HomeAssistant/HomeAssistantConnector.cs Adds token-aware, semaphore-synchronized monitor “ensure running” logic and treats Unknown as startable.
TgHomeBot.SmartHome.Contract/ISmartHomeConnector.cs Updates connector contract to include cancellation in EnsureMonitorIsRunning.
TgHomeBot.Scheduling/Tasks/SmartHomeMonitorWatcherTask.cs Propagates cancellation and adjusts logging to be less noisy on success.
Comments suppressed due to low confidence (1)

TgHomeBot.SmartHome.HomeAssistant/HomeAssistantConnector.cs:98

  • The broad catch (Exception) here will also catch OperationCanceledException from _semaphore.WaitAsync(cancellationToken) / StartMonitoringAsync(cancellationToken), log it as an error, and return false. That breaks cancellation propagation (e.g., scheduler shutdown) and can cause spurious warning/error logs. Handle OperationCanceledException separately (rethrow when cancellationToken.IsCancellationRequested) and only log/return false for non-cancellation failures.
        catch (Exception e)
        {
            logger.LogError(e, "Error ensuring Home Assistant monitor is running");
            return false;
        }

Comment on lines +74 to +82
await _semaphore.WaitAsync(cancellationToken);
try
{
switch (_smartHomeMonitor?.State)
{
case MonitorState.Idle:
case MonitorState.Unknown:
await _smartHomeMonitor!.StartMonitoringAsync(cancellationToken);
return true;

Copilot AI Mar 22, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

StartMonitoringAsync can perform network I/O and retry loops (potentially taking a long time). Because it is awaited while holding _semaphore, other callers that need the same semaphore (e.g., CreateMonitorAsync used by /check via GetMonitorStateRequestHandler) can be blocked for the entire connection/retry duration. Consider limiting the semaphore scope to just reading _smartHomeMonitor/State and deciding whether to start, then call StartMonitoringAsync outside the lock (it’s already idempotent when the WebSocket is open).

Copilot uses AI. Check for mistakes.
thomasneuberger added a commit that referenced this pull request Mar 22, 2026
* Add SmartHomeMonitorWatcherTask

* Improve SmartHomeMonitorWatcherTask: CancellationToken propagation, sync, and logging (#60)

* Initial plan

* Apply PR review feedback: CancellationToken, Unknown state, semaphore, logging improvements

Co-authored-by: thomasneuberger <23504477+thomasneuberger@users.noreply.github.com>
Agent-Logs-Url: https://github.com/thomasneuberger/TgHomeBot/sessions/02041d09-0799-491d-ac3a-ccd36acdea63

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: thomasneuberger <23504477+thomasneuberger@users.noreply.github.com>

---------

Co-authored-by: Copilot <198982749+Copilot@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants