fix agents updates

This commit is contained in:
Graham McIntire 2026-02-10 08:08:34 -06:00
parent 144e04b998
commit 94405f0716
No known key found for this signature in database

View file

@ -364,19 +364,20 @@ defmodule ToweropsWeb.AgentLive.Index do
end
# Handle real-time agent status updates
# Only process events for this organization's agents, or cloud pollers if superuser
@impl true
def handle_info({:agent_connected, agent_token_id, _organization_id}, socket) do
{:noreply, update_single_agent(socket, agent_token_id)}
def handle_info({:agent_connected, agent_token_id, organization_id}, socket) do
{:noreply, maybe_update_agent(socket, agent_token_id, organization_id)}
end
@impl true
def handle_info({:agent_disconnected, agent_token_id, _organization_id}, socket) do
{:noreply, update_single_agent(socket, agent_token_id)}
def handle_info({:agent_disconnected, agent_token_id, organization_id}, socket) do
{:noreply, maybe_update_agent(socket, agent_token_id, organization_id)}
end
@impl true
def handle_info({:agent_heartbeat, agent_token_id, _organization_id}, socket) do
{:noreply, update_single_agent(socket, agent_token_id)}
def handle_info({:agent_heartbeat, agent_token_id, organization_id}, socket) do
{:noreply, maybe_update_agent(socket, agent_token_id, organization_id)}
end
@impl true
@ -410,19 +411,39 @@ defmodule ToweropsWeb.AgentLive.Index do
|> assign(:offline_agents, offline_agents)
end
defp update_single_agent(socket, agent_token_id) do
defp maybe_update_agent(socket, agent_token_id, organization_id) do
my_org_id = socket.assigns.current_scope.organization.id
agent_token = Agents.get_agent_token!(agent_token_id)
socket
|> stream_insert(:agent_tokens, agent_token)
|> maybe_update_stats()
cond do
agent_token.is_cloud_poller ->
# Cloud pollers only visible to superusers
if socket.assigns.is_superuser do
socket
|> stream_insert(:cloud_pollers, agent_token)
|> update_health_stats()
else
socket
end
organization_id == my_org_id ->
# Regular agent belonging to this organization
socket
|> stream_insert(:agent_tokens, agent_token)
|> update_health_stats()
true ->
# Agent from another organization, ignore
socket
end
rescue
Ecto.NoResultsError ->
# Agent was deleted, just update stats
maybe_update_stats(socket)
# Agent was deleted, just refresh stats
update_health_stats(socket)
end
defp maybe_update_stats(socket) do
defp update_health_stats(socket) do
organization = socket.assigns.current_scope.organization
agent_health_stats = Stats.get_organization_agent_health(organization.id)