Commit graph

132 commits

Author SHA1 Message Date
930885e21a
Add agent rename functionality
Implemented ability to rename agents through a new edit page following TDD:

Backend changes:
- Added update_agent_token/2 in Agents context for updating agent names
- Added update_changeset/2 in AgentToken schema that only allows name updates
- Security: Token field cannot be changed, only name field is allowed

LiveView implementation:
- Created AgentLive.Edit module with mount, validate, and save handlers
- Created edit.html.heex template with form for renaming agents
- Added route /orgs/:org_slug/agents/:id/edit
- Added Edit button to agent show page header
- Validates organization ownership using Repo.get_by!

Tests:
- Added comprehensive context tests for update_agent_token/2
- Added LiveView tests for edit page functionality
- Tests cover: loading, validation, save/redirect, auth, and org ownership

All 801 tests passing, no Credo warnings.
2026-01-17 15:48:47 -06:00
c35a502425
Change agent revoke to delete with full cleanup
Replace the revoke functionality with delete to properly clean up agent references.
When an agent is deleted:
- All direct device assignments are removed
- Agent is removed from site defaults
- Agent is removed from organization defaults
- Devices automatically fall back to site/org agents or cloud polling

This ensures no orphaned references and provides better clarity about
what happens to device monitoring when an agent is removed.

- Add delete_agent_token/1 function in Agents context
- Update LiveView to use delete_agent event instead of revoke_agent
- Update UI button from "Revoke" to "Delete" with clearer confirmation message
- Add comprehensive tests for delete functionality and fallback behavior
- All 792 tests passing, no Credo warnings
2026-01-17 15:40:09 -06:00
541ab7e7d6
more renames 2026-01-17 15:13:56 -06:00
b6f4946385
moduledocs 2026-01-17 15:08:49 -06:00
22f81acfa6
credo cleanup 2026-01-17 15:00:52 -06:00
a810e75fc4
rename equipment to device 2026-01-17 14:48:46 -06:00
c88f2bbf96
Make active alerts the default tab
Change the default filter from 'all' to 'active' on the alerts page.
This shows only active alerts by default, which is more useful for
monitoring current issues. Users can still click 'All Alerts' to see
the complete history.
2026-01-17 12:55:03 -06:00
44c71bca96
Make optional labels lighter on site form
Change (optional) text color from zinc-500/400 to zinc-400/500 for
better contrast and lighter appearance. Applied to:
- Parent Site field label
- Location field label
- Description field label
- Agent Configuration heading
- SNMP Configuration heading
2026-01-17 12:34:49 -06:00
9735e6e569
Improve optional field labels on site form
Add greyed out '(optional)' text to Parent Site, Location, and
Description field labels for better UX. The optional indicator uses
a lighter color (text-zinc-500/400) to distinguish it from the
required field label.
2026-01-17 12:33:23 -06:00
f9a18fa423
Fix clipboard copy and org settings navigation
- Replace phx:copy event with CopyToClipboard LiveView hook for more
  reliable clipboard functionality
- Add visual feedback (checkmark) when text is copied to clipboard
- Apply hook to both agent token and docker compose copy buttons
- Add readonly attribute to docker compose textarea
- Fix org settings page to stay on settings after save instead of
  redirecting to dashboard

The clipboard copy now works correctly by using a dedicated LiveView
hook that directly handles the click event and clipboard API, rather
than relying on custom event dispatching which was causing issues.
2026-01-17 12:18:49 -06:00
eff7d0b55a
Clarify agent assignment breakdown label
Change 'explicitly assigned' to 'equipment-level override' in organization
settings to better reflect that this counts equipment with custom agent
assignments, not equipment directly assigned to organizations (which doesn't
exist - equipment always belongs to sites).
2026-01-17 12:08:17 -06:00
dca90db137
allow override of agent and snmp community 2026-01-17 12:05:08 -06:00
7975581da2
Add Organization Settings link to org dropdown menu
- Add Organization Settings link in top-right org menu dropdown
- Position it between Switch Org and Admin Panel
- Add gear icon for visual clarity
- Rename 'Settings' to 'User Settings' with user icon for clarity
- Organization Settings link only shows when current_organization is set
2026-01-17 11:51:10 -06:00
60b97136c7
Add UI forms for hierarchical SNMP configuration
Adds forms to organization, site, and equipment pages to configure SNMP
community strings with hierarchical fallback.

Changes:
- Organization settings: Add SNMP version and community fields
- Site form: Add SNMP config section with inheritance notice
- Equipment form: Update SNMP fields to show inheritance source and effective values

The UI now shows:
- Where the SNMP config is coming from (equipment, site, organization, or default)
- What the effective values are when inheriting
- Visual indicators for overrides vs inheritance

All forms use the Equipment.get_snmp_config/1 function for consistent
hierarchical resolution.
2026-01-17 11:49:31 -06:00
79dabd840b
wording 2026-01-17 11:21:18 -06:00
ae16acf016
Add build timestamp to footer with shared time formatting helpers
- Add compile-time @build_timestamp to Application module
- Create ToweropsWeb.TimeHelpers module for shared time formatting
- Update footer to display 'Last deployed Xm ago · YYYY-MM-DD HH:MM:SS UTC'
- Refactor AgentLive.Helpers to delegate to shared TimeHelpers
- Consolidate duplicate time formatting logic into single module
- Timestamp updates automatically on each build/deploy
2026-01-17 11:10:50 -06:00
654fcb541c
Add footer with dynamic copyright year to all layouts
- Add footer component to app, authenticated, and admin layouts
- Update marketing layout footer to use dynamic year
- Use flexbox layout to push footer to bottom of viewport
- Footer displays 'Copyright © <year> Towerops'
- Year updates automatically using Date.utc_today().year
2026-01-17 11:05:39 -06:00
b53a53b199
Add comprehensive Dialyzer type specifications
- Add @type definitions to all schema modules:
  - User, UserCredential, Membership, Invitation
  - Organization, Site, AgentAssignment
  - InterfaceStat, SensorReading, Alert
- Fix all compilation warnings with stronger Elixir types:
  - Remove unused require Logger in log_filter.ex
  - Remove unused parse_float(nil) clause
  - Add pin operators (^) for variables in binary pattern matches
- Fix Dialyzer errors (25 → 0):
  - Remove unreachable pattern match clauses
  - Fix unmatched return values with _ = prefix
  - Update @spec for deliver_alert_notification/1
- Properly handle all Phoenix.PubSub.subscribe and Task.start return values
- Explicitly ignore if statement return values where needed

All files now pass mix compile --warnings-as-errors and mix dialyzer.
2026-01-17 10:52:02 -06:00
02c163986e
Fix 21 Dialyzer errors by adding schema types and fixing unmatched returns
Schema types added:
- AgentToken.t/0
- Equipment.t/0
- Device.t/0
- Interface.t/0
- Sensor.t/0

Fixed unmatched returns in AgentChannel:
- Agents.update_agent_token_heartbeat/3 (2 instances)
- process_snmp_result/2

Reduced Dialyzer errors from 48 to 27.
2026-01-17 10:40:47 -06:00
e1b9976219
Add Dialyzer typespecs to WebSocket agent code and Agents context
- Add @spec to AgentSocket callbacks (connect/3, id/1)
- Add @spec to AgentChannel callbacks (join/3, handle_info/2, handle_in/3)
- Add @spec to AgentChannel private function build_jobs_for_agent/1
- Add @spec to Agents.verify_agent_token/1
- Add @spec to Agents.update_agent_token_heartbeat/3
- Add @spec to Agents.list_agent_polling_targets/1

These specs provide strict type checking for the critical WebSocket
agent communication code implemented in this session.
2026-01-17 10:37:27 -06:00
305b22dc65
Fix organization_id access: use equipment.site.organization_id 2026-01-16 19:21:58 -06:00
6b7a3ba36e
Fix binary protobuf encoding for JSON serializer
- Use base64-encoded binary in JSON payload instead of {:binary, data} tuples
- V1.JSONSerializer cannot encode tuples, needs plain JSON objects
- Agent already sends/expects base64-encoded binary in 'binary' key
2026-01-16 18:36:24 -06:00
9b88a32f33
Move token authentication from URL to Phoenix channel join payload 2026-01-16 18:22:57 -06:00
538f582fec
Update agent setup instructions with Watchtower auto-updates
- Change default agent image to gmcintire/towerops-agent:main
- Add Watchtower service to docker-compose instructions
- Configure 15-minute update check interval for development
- Add DOCKER_API_VERSION=1.44 to prevent API compatibility errors
- Remove deprecated docker-compose version field
2026-01-16 17:38:30 -06:00
eb91798729
agent improvements and agent config 2026-01-16 17:26:51 -06:00
a7ed057976
neighbor improvements 2026-01-16 16:25:49 -06:00
dcd4588304
fix neighbors 2026-01-16 16:09:15 -06:00
3539e36f12
updates 2026-01-16 13:15:59 -06:00
6908661bd1
Fix mobile API organizations endpoint
Fixed bug where list_user_organizations was being called with user struct
instead of user_id, causing 400 Bad Request errors.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-15 16:54:28 -06:00
7068ab2466
Convert User Settings from controller to LiveView
- Create UserSettingsLive to replace UserSettingsController
- Convert email/password forms to LiveView with proper form handling
- Add mobile session management (toggle alerts, revoke devices)
- Add require_sudo_mode on_mount hook to UserAuth
- Create dedicated live_session for sudo mode routes in router
- Keep UserSettingsController for email confirmation via token only
- Add MobileSessions.get_session/1 function for test support
- Update tests to match LiveView behavior (password update redirects to login)
- Remove old controller tests for email/password updates (now in LiveView)
2026-01-15 16:29:50 -06:00
c7f02eac24
add api for mobile login 2026-01-15 15:36:14 -06:00
85abdedf8b
Update table borders to use lighter grey instead of black
Replace black ring border with lighter zinc-200/zinc-700 border on all
tables for better visual consistency across the application. Also update
tbody dividers to match the new border styling.
2026-01-15 13:32:09 -06:00
58433ec072
Enable Docker socket mount by default in agent setup
- Removed comment from Docker socket volume mount
- Auto-updates now work out of the box when users copy config
- Socket mount: /var/run/docker.sock:/var/run/docker.sock
2026-01-15 09:29:58 -06:00
b70ddfe166
timestamp improvement 2026-01-15 08:03:30 -06:00
723f064315
Add batch loading for sensor/interface stats to eliminate N+1 queries
Added two new functions to Snmp context:
- get_latest_sensor_readings_batch/1 - Loads latest readings for multiple sensors in one query
- get_latest_interface_stats_batch/1 - Loads latest stats for multiple interfaces in one query

Both use PostgreSQL DISTINCT ON to efficiently get only the latest record per ID.

Updated EquipmentLive.Show.load_snmp_data/1 to use batch functions:
- Equipment with 20 sensors: 20 queries → 1 query (20x reduction)
- Equipment with 10 interfaces: 10 queries → 1 query (10x reduction)
- Total improvement: 30 queries → 2 queries for typical equipment page load

This significantly improves page load performance for equipment with many sensors/interfaces.
2026-01-15 07:31:57 -06:00
96706b2cf8
Deduplicate agent status helper functions
Extracted 5 shared helper functions into ToweropsWeb.AgentLive.Helpers:
- agent_status/1 - Determines online/warning/offline/never status
- status_badge_class/1 - Returns Tailwind CSS classes for status badges
- status_dot_class/1 - Returns CSS classes for animated status dots
- format_last_seen/1 - Formats DateTime as human-readable time ago
- format_uptime/1 - Formats uptime seconds as days/hours/minutes

Removed duplicate code from:
- lib/towerops_web/live/agent_live/index.ex
- lib/towerops_web/live/agent_live/show.ex

Both modules now import the shared helpers, following DRY principle.
This reduces code duplication and makes status formatting consistent
across all agent-related pages.
2026-01-14 19:12:06 -06:00
4297556700
Implement all quick win improvements for agent UI and functionality
1. Fixed Docker Compose example to include socket mount
   - Added /var/run/docker.sock mount for auto-updates in agent modal

2. Show total equipment count with inheritance
   - Display both direct and inherited equipment counts in agents table
   - Shows breakdown: 'X total' with 'Y direct · Z inherited' details

3. Add visual status indicators with better CSS
   - Added animated pulsing dots for online agents
   - Color-coded status dots (green=online, yellow=warning, red=offline)
   - Improved status badge styling

4. Create agent detail page with metrics
   - New /agents/:id page showing comprehensive agent health
   - 4 metric cards: Status, Equipment count, Last seen, Agent info
   - Displays agent metadata (hostname, version, uptime)
   - Lists all polling targets with assignment source badges
   - Shows direct vs inherited equipment assignments
   - Clickable agent names in table link to detail page

5. Add health endpoint to Rust agent
   - Added /health HTTP endpoint on port 8080
   - Returns JSON with agent status, version, uptime, metrics pending
   - Uses lightweight tiny_http server
   - Non-blocking background thread
   - Ready for monitoring/health checks
2026-01-14 18:46:03 -06:00
ae521d2108
Fix protobuf body parsing causing 400 errors on agent heartbeat
Plug.Parsers was trying to parse protobuf bodies as JSON, failing with
400 errors before the request reached the controller.

Changes:
- Added custom BodyReader to endpoint that skips parsing for protobuf
- When Content-Type is application/x-protobuf, return empty body to parser
- Controller reads the raw body directly for protobuf requests
- Added error handling for protobuf decode failures in heartbeat endpoint

This fixes the 400 errors agents were seeing on heartbeat requests.
2026-01-14 18:35:20 -06:00
31b906b0fa
Fix agent IP detection to use real client IP from proxy headers
The agent's last_seen IP was showing the Docker container IP (10.244.x.x)
because conn.remote_ip returns the proxy/load balancer IP.

Changes:
- Added get_client_ip/1 helper that checks X-Forwarded-For first
- Falls back to X-Real-IP if X-Forwarded-For not present
- Falls back to conn.remote_ip as last resort
- Applied to both AgentAuth plug and AgentController heartbeat endpoint

Now correctly shows the actual external IP of the remote agent.
2026-01-14 17:04:59 -06:00
0ed82c47b9
Make agent heartbeat endpoint asynchronous for faster response
Changed heartbeat database update from synchronous to async using Task.start.
This reduces response time from ~20ms to <1ms by not waiting for the
database write to complete before sending the response.

The heartbeat is a fire-and-forget operation where the agent doesn't
need confirmation that the update succeeded.

In test environment, it remains synchronous to avoid DB ownership issues.
2026-01-14 17:01:57 -06:00
749efe4798
Fix agent API to accept protobuf content type
The :accepts plug in the agent_api pipeline was only allowing JSON,
which caused 406 errors when the agent sent protobuf requests.

Changes:
- Register application/x-protobuf MIME type in config
- Add protobuf to agent_api pipeline accepts list
- Agent can now successfully communicate using protobuf format
2026-01-14 16:58:11 -06:00
9a6369bd27
Fix agent API protobuf support and Mix.env runtime error
Fixed two critical issues preventing agent communication:

1. Fix Mix.env() runtime error in production
   - Replace Mix.env() with Application.get_env(:towerops, :env)
   - Add :env config to test.exs
   - Mix module not available in production releases

2. Add Protocol Buffers support to agent API endpoints
   - GET /api/v1/agent/config now accepts application/x-protobuf
   - POST /api/v1/agent/heartbeat now accepts application/x-protobuf
   - Added conversion functions for config/equipment/sensors/interfaces
   - Maintains JSON backward compatibility as fallback

All agent controller tests passing (14 tests, 0 failures)
2026-01-14 16:35:47 -06:00
8864b8d26d
Enhance agent assignment UI with clear inheritance indicators
- Add override warnings (amber) when site/equipment explicitly override defaults
- Show inherited agent names in organization and site forms
- Display equipment assignment breakdown in organization settings
- Make equipment boxes fully clickable on site page (remove View button)
- Add hover effects to equipment boxes for better UX
- Consistent icon usage across all assignment levels
2026-01-14 16:20:20 -06:00
8442d9e1fc
update liveview 2026-01-14 13:54:48 -06:00
fa591fde05
Revert manual data directory setup instructions from agent modal
The Docker agent now handles permissions automatically via the
entrypoint script, so users don't need to manually create the
data directory or run chown commands.

Reverted the UI back to the simple docker-compose example.
2026-01-14 09:36:59 -06:00
2aca9dc933
Add data directory setup instructions to agent modal
The Docker agent runs as non-root user (UID 1000) for security. When
mounting host directories, users must create the data directory with
proper permissions before starting the container.

Added clear instructions to:
1. Create the data directory: mkdir -p data
2. Set proper ownership: chown -R 1000:1000 data
3. Then use the Docker Compose configuration

This fixes the 'unable to open database file' error when starting
the agent.
2026-01-14 09:33:12 -06:00
569b5cb671
Make agent Docker image configurable and update success criteria
- Added agent_docker_image config option (defaults to towerops/agent:latest)
- Updated agent UI modal to use configurable image URL
- Can override in runtime.exs or environment config for production
- Updated AGENT_NEXT_STEPS.md success criteria with completion status
- 8/12 success criteria now complete
2026-01-14 09:16:48 -06:00
599fa2e69e
Integrate agent health statistics into agent UI
- Added Stats module to agent LiveView index
- Load organization-wide health statistics on mount
- Display agent health, equipment counts, and assignment breakdown
- Refresh stats after agent creation/revocation
- All 10 agent LiveView tests passing
2026-01-14 09:12:59 -06:00
a2d96f8e6e
Implement hierarchical agent assignment for SNMP polling
Add three-level agent assignment hierarchy (Equipment > Site > Organization)
allowing flexible agent deployment strategies. Agents now receive only equipment
assigned to them through direct assignment or inheritance from site/organization
defaults.

Key changes:
- Add agent_token_id to Sites table with migration
- Implement get_effective_agent_token/1 for hierarchical resolution
- Add list_agent_polling_targets/1 to return polling targets per agent
- Update API config endpoint to use hierarchical polling targets
- Add agent assignment UI to equipment, site, and organization forms
- Show agent source (direct/site/org/none) in equipment form
- Add equipment count column to agent list
- Update terminology from "poll from server" to "cloud polling"

Tests:
- Add 8 comprehensive tests for list_agent_polling_targets/1
- Add end-to-end test for hierarchical config endpoint
- All 775 tests passing
2026-01-14 08:38:50 -06:00
b8bd952681
agent token changes 2026-01-13 13:43:43 -06:00