Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use app monitoring instead of polling to establish websocket connection #367

Merged
merged 2 commits into from
Jan 9, 2025

Conversation

neilenns
Copy link
Owner

@neilenns neilenns commented Jan 9, 2025

Fixes #366

Summary by CodeRabbit

Release Notes

  • New Features

    • Added support for monitoring specific applications on macOS and Windows
    • Introduced system wake-up event handling to restore TrackAudio connections
  • Improvements

    • Enhanced application launch and termination event tracking
    • Added state management for tracking application running status
  • Changes

    • Removed generic action added event emissions across various action handlers
    • Updated event registration and handler management in the plugin

@neilenns neilenns added the development Code cleanup and refactoring label Jan 9, 2025
@neilenns neilenns self-assigned this Jan 9, 2025
Copy link

coderabbitai bot commented Jan 9, 2025

Walkthrough

The pull request introduces significant changes to the TrackAudio Stream Deck plugin, focusing on application monitoring and event handling. The modifications include adding an "ApplicationsToMonitor" section to the manifest file, which specifies monitored applications for macOS and Windows. Additionally, it removes generic "actionAdded" event emissions across various action-related files and introduces new event handlers for application launch, termination, and system wake-up. These changes enhance the plugin's interaction with the Stream Deck system and the tracked applications.

Changes

File Change Summary
com.neil-enns.trackaudio.sdPlugin/manifest.json Added ApplicationsToMonitor section specifying monitored apps for macOS and Windows
src/events/action/* Removed actionAdded event emissions across multiple action-related files
src/events/streamDeck/applicationDidLaunch.ts Added new event handler for application launch
src/events/streamDeck/applicationDidTerminate.ts Added new event handler for application termination
src/events/streamDeck/systemDidWakeUp.ts Added new event handler for system wake-up
src/managers/action.ts Removed actionAdded event emission in add method
src/managers/trackAudio.ts Added properties to track if the application is running
src/plugin.ts Updated imports and event handler registrations

Assessment against linked issues

Objective Addressed Explanation
Use app monitoring instead of polling

Possibly related PRs

Suggested labels

enhancement

Poem

🐰 A rabbit's tale of code so bright,
Monitoring apps with Stream Deck might,
No more polling, events now flow,
Connections dance, performance aglow!
Hop, hop, hooray for plugin's new way! 🎉

Finishing Touches

  • 📝 Generate Docstrings (Beta)

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

github-actions bot commented Jan 9, 2025

Build for this pull request:
StreamDeck-TrackAudio.zip

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (3)
src/events/streamDeck/applicationDidTerminate.ts (1)

6-6: Fix logger service name

The logger service name should match the function name for consistency.

-const logger = mainLogger.child({ service: "handleOnApplicationDidTerminate" });
+const logger = mainLogger.child({ service: "applicationDidTerminate" });
src/plugin.ts (1)

67-69: Add comment explaining application monitoring strategy

Add a comment block to explain the application monitoring approach for better maintainability.

-// Register the event handlers
+// Monitor TrackAudio application lifecycle
+// These handlers connect/disconnect when the TrackAudio application launches/terminates,
+// replacing the previous polling mechanism for establishing websocket connections.
 streamDeck.system.onApplicationDidLaunch(handleOnApplicationDidLaunch);
 streamDeck.system.onApplicationDidTerminate(handleOnApplicationDidTerminate);
com.neil-enns.trackaudio.sdPlugin/manifest.json (1)

133-136: Document application monitoring in README

Consider adding documentation about the application monitoring feature in the project's README to help users understand how the plugin detects and connects to TrackAudio.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 98a75b2 and 67f9870.

📒 Files selected for processing (14)
  • com.neil-enns.trackaudio.sdPlugin/manifest.json (1 hunks)
  • src/events/action/actionAdded.ts (0 hunks)
  • src/events/action/removed.ts (0 hunks)
  • src/events/streamDeck/applicationDidLaunch.ts (1 hunks)
  • src/events/streamDeck/applicationDidTerminate.ts (1 hunks)
  • src/events/streamDeck/atisLetter/addAtisLetter.ts (0 hunks)
  • src/events/streamDeck/hotline/addHotline.ts (0 hunks)
  • src/events/streamDeck/mainVolume/addMainVolume.ts (0 hunks)
  • src/events/streamDeck/pushToTalk/addPushToTalk.ts (0 hunks)
  • src/events/streamDeck/stationStatus/addStation.ts (0 hunks)
  • src/events/streamDeck/stationVolume/addStationVolume.ts (0 hunks)
  • src/events/streamDeck/trackAudioStatus/addTrackAudioStatus.ts (0 hunks)
  • src/managers/action.ts (0 hunks)
  • src/plugin.ts (3 hunks)
💤 Files with no reviewable changes (10)
  • src/events/streamDeck/mainVolume/addMainVolume.ts
  • src/events/streamDeck/hotline/addHotline.ts
  • src/events/streamDeck/pushToTalk/addPushToTalk.ts
  • src/events/streamDeck/stationStatus/addStation.ts
  • src/events/streamDeck/atisLetter/addAtisLetter.ts
  • src/events/action/actionAdded.ts
  • src/events/streamDeck/trackAudioStatus/addTrackAudioStatus.ts
  • src/events/action/removed.ts
  • src/managers/action.ts
  • src/events/streamDeck/stationVolume/addStationVolume.ts
🔇 Additional comments (1)
src/events/streamDeck/applicationDidLaunch.ts (1)

7-10: Verify application name before connecting

The handler should verify that the launched application matches one of the monitored applications before attempting to connect.

 export const handleOnApplicationDidLaunch = (ev: ApplicationDidLaunchEvent) => {
   logger.info("Received applicationDidLaunch event", ev.application);
+  const monitoredApps = ["com.vatsim.trackaudio", "trackaudio.exe"];
+  if (!monitoredApps.includes(ev.application)) {
+    logger.debug("Ignoring non-monitored application launch", ev.application);
+    return;
+  }
   trackAudioManager.connect();
 };
✅ Verification successful

Application validation check is required

The review comment is accurate. The manifest.json confirms that only "com.vatsim.trackaudio" (Mac) and "trackaudio.exe" (Windows) should trigger a connection. The suggested implementation correctly validates against these applications.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Extract monitored applications from manifest.json
# to verify application name validation

jq -r '.ApplicationsToMonitor | (.mac[], .windows[])' com.neil-enns.trackaudio.sdPlugin/manifest.json

Length of output: 140

Comment on lines 7 to 10
export const handleOnApplicationDidLaunch = (ev: ApplicationDidLaunchEvent) => {
logger.info("Received applicationDidLaunch event", ev.application);
trackAudioManager.connect();
};
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for connect() call

The connection attempt should be wrapped in a try-catch block to handle potential connection failures gracefully.

 export const handleOnApplicationDidLaunch = (ev: ApplicationDidLaunchEvent) => {
   logger.info("Received applicationDidLaunch event", ev.application);
-  trackAudioManager.connect();
+  try {
+    trackAudioManager.connect();
+  } catch (error) {
+    logger.error("Failed to connect to TrackAudio", error);
+  }
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const handleOnApplicationDidLaunch = (ev: ApplicationDidLaunchEvent) => {
logger.info("Received applicationDidLaunch event", ev.application);
trackAudioManager.connect();
};
export const handleOnApplicationDidLaunch = (ev: ApplicationDidLaunchEvent) => {
logger.info("Received applicationDidLaunch event", ev.application);
try {
trackAudioManager.connect();
} catch (error) {
logger.error("Failed to connect to TrackAudio", error);
}
};

Comment on lines 8 to 14
export const handleOnApplicationDidTerminate = (
ev: ApplicationDidTerminateEvent
) => {
logger.info("Received applicationDidTerminate event", ev.application);
trackAudioManager.disconnect();
vatsimManager.stop();
};
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling and application validation

The handler should validate the application and handle potential errors from disconnect() and stop() calls.

 export const handleOnApplicationDidTerminate = (
   ev: ApplicationDidTerminateEvent
 ) => {
   logger.info("Received applicationDidTerminate event", ev.application);
+  const monitoredApps = ["com.vatsim.trackaudio", "trackaudio.exe"];
+  if (!monitoredApps.includes(ev.application)) {
+    logger.debug("Ignoring non-monitored application termination", ev.application);
+    return;
+  }
+  try {
     trackAudioManager.disconnect();
     vatsimManager.stop();
+  } catch (error) {
+    logger.error("Error during cleanup", error);
+  }
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const handleOnApplicationDidTerminate = (
ev: ApplicationDidTerminateEvent
) => {
logger.info("Received applicationDidTerminate event", ev.application);
trackAudioManager.disconnect();
vatsimManager.stop();
};
export const handleOnApplicationDidTerminate = (
ev: ApplicationDidTerminateEvent
) => {
logger.info("Received applicationDidTerminate event", ev.application);
const monitoredApps = ["com.vatsim.trackaudio", "trackaudio.exe"];
if (!monitoredApps.includes(ev.application)) {
logger.debug("Ignoring non-monitored application termination", ev.application);
return;
}
try {
trackAudioManager.disconnect();
vatsimManager.stop();
} catch (error) {
logger.error("Error during cleanup", error);
}
};

com.neil-enns.trackaudio.sdPlugin/manifest.json Outdated Show resolved Hide resolved
Copy link

github-actions bot commented Jan 9, 2025

Build for this pull request:
StreamDeck-TrackAudio.zip

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (3)
src/events/streamDeck/systemDidWakeUp.ts (1)

4-8: Add error handling for better reliability.

While the logging is good, consider adding try-catch blocks to handle potential errors during event processing.

 export const handleOnSystemDidWakeUp = () => {
   const logger = mainLogger.child({ service: "systemDidWakeUp" });

   logger.info("Received systemDidWakeUp event");
+
+  try {
+    // Connection logic here...
+  } catch (error) {
+    logger.error({ error }, "Failed to handle system wake up event");
+  }
 };
src/managers/trackAudio.ts (1)

51-66: Add validation in the isAppRunning setter.

While the getter and setter are well documented, the setter lacks validation which could lead to inconsistent state.

Consider adding validation:

  public set isAppRunning(newValue: boolean) {
+   if (typeof newValue !== 'boolean') {
+     throw new TypeError('isAppRunning must be a boolean value');
+   }
    this._isAppRunning = newValue;
  }
src/events/streamDeck/applicationDidTerminate.ts (1)

9-11: Use consistent logger service name.

The service name in the child logger differs from the applicationDidLaunch handler.

   const logger = mainLogger.child({
-    service: "handleOnApplicationDidTerminate",
+    service: "applicationDidTerminate",
   });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 67f9870 and c1f89d4.

📒 Files selected for processing (5)
  • src/events/streamDeck/applicationDidLaunch.ts (1 hunks)
  • src/events/streamDeck/applicationDidTerminate.ts (1 hunks)
  • src/events/streamDeck/systemDidWakeUp.ts (1 hunks)
  • src/managers/trackAudio.ts (2 hunks)
  • src/plugin.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/plugin.ts
🔇 Additional comments (5)
src/events/streamDeck/systemDidWakeUp.ts (2)

1-2: LGTM! Clean imports using proper path aliasing.


9-14: Enhance connection reliability with logging and verification.

While the basic reconnection logic is present, consider these improvements for better reliability and debugging:

   // This ensures reconnection to the TrackAudio manager if somehow the websocket
   // connection doesn't automatically start back up after a system wake.
   if (trackAudioManager.isAppRunning) {
+    logger.debug("Attempting to reconnect to TrackAudio manager");
     trackAudioManager.connect();
+    
+    // Consider adding connection verification
+    // Consider implementing a retry mechanism with backoff
   }

Let's verify if there's a retry mechanism or connection verification elsewhere in the codebase:

src/managers/trackAudio.ts (1)

32-32: LGTM! Property follows naming conventions.

The _isAppRunning private property aligns with the class's naming conventions and supports the transition to app monitoring.

src/events/streamDeck/applicationDidLaunch.ts (1)

5-11: ⚠️ Potential issue

Add application validation and error handling.

The handler needs to validate the application and handle potential connection errors.

Apply these improvements:

 export const handleOnApplicationDidLaunch = (ev: ApplicationDidLaunchEvent) => {
   const logger = mainLogger.child({ service: "applicationDidLaunch" });
 
   logger.info("Received applicationDidLaunch event", ev.application);
+  const monitoredApps = ["com.vatsim.trackaudio", "trackaudio.exe"];
+  if (!monitoredApps.includes(ev.application)) {
+    logger.debug("Ignoring non-monitored application launch", ev.application);
+    return;
+  }
+
   trackAudioManager.isAppRunning = true;
-  trackAudioManager.connect();
+  try {
+    trackAudioManager.connect();
+  } catch (error) {
+    logger.error("Failed to connect to TrackAudio", error);
+    trackAudioManager.isAppRunning = false;  // Reset state on connection failure
+  }
 };

Likely invalid or redundant comment.

src/events/streamDeck/applicationDidTerminate.ts (1)

6-17: ⚠️ Potential issue

Add application validation and error handling for cleanup.

The handler should validate the application and handle potential errors during cleanup.

Apply these improvements:

 export const handleOnApplicationDidTerminate = (
   ev: ApplicationDidTerminateEvent
 ) => {
   const logger = mainLogger.child({
-    service: "handleOnApplicationDidTerminate",
+    service: "applicationDidTerminate",
   });
 
   logger.info("Received applicationDidTerminate event", ev.application);
+  const monitoredApps = ["com.vatsim.trackaudio", "trackaudio.exe"];
+  if (!monitoredApps.includes(ev.application)) {
+    logger.debug("Ignoring non-monitored application termination", ev.application);
+    return;
+  }
+
   trackAudioManager.isAppRunning = false;
-  trackAudioManager.disconnect();
-  vatsimManager.stop();
+  try {
+    trackAudioManager.disconnect();
+    vatsimManager.stop();
+  } catch (error) {
+    logger.error("Error during cleanup", error);
+  }
 };

Likely invalid or redundant comment.

@neilenns neilenns merged commit b0755ee into main Jan 9, 2025
3 checks passed
@neilenns neilenns deleted the neilenns/issue366 branch January 9, 2025 23:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
development Code cleanup and refactoring
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Use app monitoring instead of polling to establish websocket connection
1 participant