Skip to content

joncrangle/teams-green

Repository files navigation

Teams-Green 🟢

Keep that Teams green.

Overview

Teams-Green runs in the background and periodically sends a key (F15) to keep your Teams status from going idle. It includes optional WebSocket support for real-time status monitoring and control.

Features

  • Background Service: Runs in a background process
  • Configurable Intervals: Set custom activity intervals (default: 180 seconds)
  • Advanced Timing Control: Fine-tune focus delays and key processing timing
  • Input Safety: Automatic detection and deferral when user is actively typing or using the mouse
  • Enhanced Activity Detection: Detects all user input including keyboard, mouse clicks, mouse movement, scroll wheel, and touch input
  • Enhanced Focus Validation: Multiple safety checks to prevent key leakage to wrong windows
  • WebSocket Server: Optional real-time monitoring and control via WebSocket API
  • Simple CLI: Easy start/stop/status/toggle commands
  • Debug Mode: Foreground execution with detailed logging
  • Process Management: Automatic PID tracking and cleanup

Installation

From Release

  1. Download the latest release from the releases page
  2. Extract the ZIP file to your desired location
  3. Run teams-green.exe from Command Prompt or PowerShell

Go Install

go install github.com/joncrangle/teams-green@latest

Build From Source

git clone https://github.com/joncrangle/teams-green
cd teams-green
just build

Usage

Basic Commands

# Start the service
teams-green start

# Stop the service
teams-green stop

# Check service status
teams-green status

# Toggle service on/off
teams-green toggle

Advanced Options

# Start with custom interval (seconds)
teams-green start --interval 120

# Start in debug mode (foreground)
teams-green start --debug

# Start with WebSocket server
teams-green start --websocket --port 8765

# Configure timing delays for reliability (milliseconds)
teams-green start --focus-delay 30 --key-process-delay 150

# Conservative timing to prevent pending notifications
teams-green start --focus-delay 25 --restore-delay 20 --key-process-delay 200

# Fast timing for performance (if Teams responds quickly)
teams-green start --focus-delay 10 --key-process-delay 75

# Enable logging to file with rotation
teams-green start --log-file logs/teams-green.log --log-rotate

# Use JSON logging format
teams-green start --log-format json --log-file logs/teams-green.log

# Combine options for troubleshooting
teams-green start --debug --focus-delay 50 --key-process-delay 150 --log-file debug.log

WebSocket API

When WebSocket is enabled, connect to ws://127.0.0.1:8765 to receive real-time events:

{
  "service": "teams-green",
  "status": "running",
  "pid": 1234,
  "message": "Service started",
  "timestamp": "2025-01-20T10:30:00Z",
  "type": "status"
}

Security & Connection Management

  • Localhost Only: WebSocket server only accepts connections from 127.0.0.1/localhost for security
  • Origin Validation: Validates Origin headers to prevent cross-site WebSocket hijacking
  • Connection Limits: Maximum 50 concurrent connections to prevent resource exhaustion
  • Automatic Cleanup: Disconnected clients are automatically removed from the registry

Connection Stability Features

  • Ping/Pong Support: Send {"type": "ping"} to test connection health - server responds with {"type": "pong"}
  • Read Timeouts: 30-second read timeout to detect inactive connections
  • Extended Timeouts: 30-second read/write timeouts with 5-minute idle timeout for stability
  • Graceful Error Handling: Timeout errors logged at debug level to reduce noise
  • Automatic Reconnection: Clients should implement reconnection logic for best results

Message Types

  • status - Service state changes and initial connection state
  • ping - Connection health check request from client
  • pong - Response to ping messages from server

Event Broadcasting

The WebSocket server automatically broadcasts events to all connected clients when:

  • Service starts or stops
  • Service state changes
  • Key activity is performed (when debug logging is enabled)

Events are broadcast using an efficient buffer pool system for optimal memory usage.

Configuration

The service accepts the following flags:

Flag Short Default Description
--debug -d false Run in foreground with debug logging
--interval -i 150 Activity interval in seconds (2.5 minutes)
--websocket -w false Enable WebSocket server
--port -p 8765 WebSocket server port
--focus-delay 150 Delay after setting focus before sending key (ms)
--restore-delay 100 Delay after restoring minimized window (ms)
--key-process-delay 150 Delay before restoring original focus (ms)
--input-threshold 2000 Consider input active if within this time (ms)
--activity-mode focus Activity mode: 'focus' (bring Teams forward) or 'global' (no focus change)
--log-format text Log format: text or json
--log-file `` Log file path (empty = no file logging)
--log-rotate false Enable log rotation
--max-log-size 10 Maximum log file size in MB
--max-log-age 30 Maximum log file age in days

Activity Modes

Teams-Green supports two activity modes:

  • focus (default): Attempts to locate and focus a Teams window before sending the F15 key. This provides targeted delivery but may cause a brief taskbar highlight or focus flash.
  • global: Sends the F15 key as a global input event without changing window focus. Use this if window flashing is distracting or focus cannot reliably be changed (e.g., strict system policies).

Fallback: In focus mode, if focus cannot be set after retries, the service will still attempt to send the key so Teams may register activity. Switch to global mode if you prefer to skip all focus operations.

Example:

teams-green start --activity-mode global --interval 120

Timing Configuration

The timing delays control how the service interacts with Teams windows:

  • --focus-delay: Time to wait after focusing a Teams window before sending the key. Increase if Teams needs more time to process focus changes.
  • --restore-delay: Time to wait after restoring a minimized Teams window. Increase if Windows is slow to restore windows.
  • --key-process-delay: Time to wait before restoring focus to the original window. Most important for preventing pending notifications - increase to 150-200ms if Teams shows pending items.

Development

Requirements

  • Go 1.25 or later
  • Windows OS (uses Win32 APIs)
  • Just (for task management)
# See Justfile recipes
just

Project Structure

teams-green/
├── cmd/                # CLI commands and root configuration
├── internal/
│   ├── config/         # Configuration and logging setup
│   ├── service/        # Core service logic and Windows integration
│   └── websocket/      # WebSocket server, client management, and event broadcasting
├── .golangci.yml       # Linting configuration
├── .goreleaser.yaml    # Release configuration
└── main.go             # Application entry point

How It Works

Teams-Green works by:

  1. Process Detection: Locates running Microsoft Teams processes
  2. Smart Activity Detection: Monitors all user input (keyboard, mouse clicks, mouse movement, scroll wheel, touch) and intelligently resets the activity timer when any interaction is detected
  3. Efficient Resource Usage: Uses Windows GetLastInputInfo API for comprehensive input detection with minimal system impact
  4. Window Targeting: Finds and focuses Teams windows with enhanced focus validation
  5. Smart Key Simulation: Sends F15 keys with configurable timing to prevent pending notifications
  6. Focus Protection: Multiple validation checks prevent keys from going to wrong windows
  7. Background Operation: Runs as a detached process with PID file management
  8. Status Monitoring: Tracks service state and provides real-time feedback

Key Safety Features

  • Comprehensive Input Detection: Automatically detects and defers Teams operations when user is actively providing any input (keyboard, mouse clicks, mouse movement, scroll wheel, touch)
  • Activity-Based Timer Reset: When any user input is detected, the Teams activity interval is reset, ensuring natural user behavior takes precedence
  • Efficient Monitoring: Single Windows API call (GetLastInputInfo) provides comprehensive input detection with minimal system impact
  • Configurable Sensitivity: Adjustable input threshold (default 500ms) to tune detection sensitivity
  • Enhanced Focus Validation: Double-checks window focus before and after key sending
  • Configurable Timing: Adjustable delays to work with different system performance levels
  • Post-Send Verification: Confirms focus state after key operations to detect interference

Troubleshooting

Service Won't Start

  • Check if Teams is running
  • Ensure no other instance is already running: teams-green status
  • Try running in debug mode: teams-green start --debug

Teams Still Goes Idle

  • Reduce the interval: teams-green start --interval 60
  • Check Windows focus policies and permissions
  • Ensure Teams has proper window focus

Teams Shows Pending Notifications After Key Send

  • Most Common Issue: Increase key processing delay: teams-green start --key-process-delay 150
  • Try conservative timing: teams-green start --focus-delay 30 --key-process-delay 200
  • Run in debug mode to monitor timing: teams-green start --debug --key-process-delay 150

Keys Going to Wrong Applications

  • The service includes multiple safety checks to prevent this
  • Enhanced input detection now monitors all input types: keyboard, mouse (clicks AND movement), scroll wheel, and touch
  • Activity detection automatically resets the interval timer when any user input is detected
  • Input threshold can be adjusted with --input-threshold flag (increase for more conservative detection)
  • Run with debug logging to see protection mechanisms in action

Performance Issues

  • Use faster timing for responsive systems: teams-green start --focus-delay 10 --key-process-delay 75
  • Increase delays for slower systems: teams-green start --focus-delay 50 --key-process-delay 200

Activity Detection Behavior

  • Mouse Activity: Any mouse movement, clicking, dragging, or scroll wheel usage will reset the Teams activity timer
  • Keyboard Activity: Any key press will reset the timer
  • Touch Input: Touch screen interactions will reset the timer (on supported devices)
  • Efficient Monitoring: Uses Windows GetLastInputInfo API - single system call detects all input types with millisecond precision
  • Configurable Threshold: Adjust sensitivity with --input-threshold flag (default 500ms means any input within last 500ms is considered "active")
  • Smart Timer Reset: When activity is detected, the full interval timer is reset (e.g., if interval is 180s, timer resets to 180s from current time)

WebSocket Connection Issues

  • Security Restrictions: WebSocket server only accepts localhost connections (127.0.0.1) with validated origins
  • Connection Limits: Maximum 50 concurrent connections - additional connections will be rejected
  • Frequent Disconnections: The WebSocket implementation includes keep-alive messages and extended timeouts to reduce disconnections
  • Timeout Errors: These are now logged at debug level - use --debug flag to see detailed connection information
  • Verify the port is not in use: netstat -an | findstr 8765
  • Try a different port: teams-green start --websocket --port 9000
  • Check Windows Firewall settings

Connection Health Monitoring

  • WebSocket connections support ping/pong for health checking
  • Clients can send {"type": "ping"} to test connection health
  • Server responds with {"type": "pong"} messages
  • Extended timeouts (30 seconds read/write, 5 minutes idle) improve stability
  • Automatic client cleanup removes disconnected connections

Fine-Tuning Timing

If Teams shows pending notifications:

# Start with conservative delays
teams-green start --key-process-delay 200

# Gradually reduce if working well
teams-green start --key-process-delay 150

If Teams doesn't register the activity:

# Increase focus delay to ensure Teams processes the focus change
teams-green start --focus-delay 50 --key-process-delay 150

For optimal performance:

# Test different combinations based on your system
teams-green start --debug --focus-delay 25 --key-process-delay 125

License

This project is licensed under the MIT License - see the LICENSE file for details.

Disclaimer

Use this tool at your own risk. The author is not responsible for any misuse or damage caused by this software. Always ensure compliance with your organization's IT policies.

About

Keep that Teams green

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors