Skip to content

Modern Docker Management, Designed for Everyone

fix: dashboard env counts not displaying in a timley manner (#2901)

Kyle Mendell28a441461051
diff --git a/backend/api/api.go b/backend/api/api.go
index a134b27cc..9fe9934e4 100644
--- a/backend/api/api.go
+++ b/backend/api/api.go
@@ -310,5 +310,5 @@ func registerHandlersInternal(api huma.API, svc *di.Services, handlerAppCtx hand
handlers.RegisterGitOpsSyncs(api, svc.GitOpsSync)
handlers.RegisterWebhooks(api, svc.Webhook)
handlers.RegisterVulnerability(api, svc.Vulnerability, handlerAppCtx)
- handlers.RegisterDashboard(api, svc.Dashboard)
+ handlers.RegisterDashboard(api, svc.Dashboard, svc.Environment)
}
diff --git a/backend/api/handlers/activities.go b/backend/api/handlers/activities.go
index 7eb93494a..3c35f2210 100644
--- a/backend/api/handlers/activities.go
+++ b/backend/api/handlers/activities.go
@@ -5,18 +5,17 @@ import (
"encoding/json"
"errors"
"fmt"
- "log/slog"
"net/http"
"net/url"
"strconv"
"strings"
- "sync"
"time"
"github.com/danielgtaylor/huma/v2"
humamw "github.com/getarcaneapp/arcane/backend/v2/api/middleware"
"github.com/getarcaneapp/arcane/backend/v2/internal/services"
"github.com/getarcaneapp/arcane/backend/v2/pkg/authz"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/aggstream"
"github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"
"github.com/getarcaneapp/arcane/types/v2/activity"
@@ -335,55 +334,17 @@ func (h *ActivityHandler) StreamAllActivities(ctx context.Context, input *Stream
// environment and every enabled remote environment over a single response so
// the browser needs one connection regardless of environment count.
func (h *ActivityHandler) streamAllActivitiesInternal(ctx context.Context, limit int, encoder *json.Encoder, flush func()) {
- streamCtx, cancel := context.WithCancel(ctx)
-
- events := make(chan activity.StreamEvent, activityStreamEventBuffer)
- var wg sync.WaitGroup
- wg.Add(2)
- go func() {
- defer wg.Done()
- h.runLocalActivityStreamProducerInternal(streamCtx, limit, events)
- }()
- go func() {
- defer wg.Done()
- h.runRemoteActivityStreamPollersInternal(streamCtx, limit, events)
- }()
- defer wg.Wait()
- defer cancel()
-
- heartbeat := time.NewTicker(activityStreamHeartbeatInterval)
- defer heartbeat.Stop()
-
- for {
- select {
- case <-streamCtx.Done():
- return
- case event := <-events:
- if err := encoder.Encode(event); err != nil {
- return
- }
- flush()
- case <-heartbeat.C:
- if err := encoder.Encode(activity.StreamEvent{
- Type: "heartbeat",
- Timestamp: time.Now(),
- }); err != nil {
- return
- }
- flush()
- }
- }
-}
-
-// sendActivityStreamEventInternal forwards an event to the stream writer,
-// giving up when the stream is shutting down so producers can never block.
-func sendActivityStreamEventInternal(ctx context.Context, events chan<- activity.StreamEvent, event activity.StreamEvent) bool {
- select {
- case events <- event:
- return true
- case <-ctx.Done():
- return false
- }
+ aggstream.Run(ctx, encoder, flush, activityStreamEventBuffer, activityStreamHeartbeatInterval,
+ func() activity.StreamEvent {
+ return activity.StreamEvent{Type: "heartbeat", Timestamp: time.Now()}
+ },
+ func(ctx context.Context, events chan<- activity.StreamEvent) {
+ h.runLocalActivityStreamProducerInternal(ctx, limit, events)
+ },
+ func(ctx context.Context, events chan<- activity.StreamEvent) {
+ h.runRemoteActivityStreamPollersInternal(ctx, limit, events)
+ },
+ )
}
func (h *ActivityHandler) runLocalActivityStreamProducerInternal(ctx context.Context, limit int, events chan<- activity.StreamEvent) {
@@ -393,7 +354,7 @@ func (h *ActivityHandler) runLocalActivityStreamProducerInternal(ctx context.Con
})
if err != nil {
if ctx.Err() == nil {
- sendActivityStreamEventInternal(ctx, events, activity.StreamEvent{
+ aggstream.Send(ctx, events, activity.StreamEvent{
Type: "error",
EnvironmentID: "0",
Error: err.Error(),
@@ -403,7 +364,7 @@ func (h *ActivityHandler) runLocalActivityStreamProducerInternal(ctx context.Con
return false
}
h.applyActivitySourceLabelsInternal(ctx, "0", activities)
- return sendActivityStreamEventInternal(ctx, events, activity.StreamEvent{
+ return aggstream.Send(ctx, events, activity.StreamEvent{
Type: "snapshot",
EnvironmentID: "0",
Activities: activities,
@@ -429,7 +390,7 @@ func (h *ActivityHandler) runLocalActivityStreamProducerInternal(ctx context.Con
}
event.EnvironmentID = "0"
h.applyActivityStreamEventSourceLabelInternal(ctx, "0", &event)
- if !sendActivityStreamEventInternal(ctx, events, event) {
+ if !aggstream.Send(ctx, events, event) {
return
}
case <-ticker.C:
@@ -444,60 +405,10 @@ func (h *ActivityHandler) runLocalActivityStreamProducerInternal(ctx context.Con
// enabled remote environment, re-listing periodically so environments added
// or removed while the stream is open are picked up without a reconnect.
func (h *ActivityHandler) runRemoteActivityStreamPollersInternal(ctx context.Context, limit int, events chan<- activity.StreamEvent) {
- pollers := make(map[string]context.CancelFunc)
- var wg sync.WaitGroup
- defer wg.Wait()
- defer func() {
- for _, cancelPoll := range pollers {
- cancelPoll()
- }
- }()
-
- reconcile := func() {
- envs, err := h.environmentService.ListRemoteEnvironments(ctx)
- if err != nil {
- if ctx.Err() == nil {
- slog.WarnContext(ctx, "failed to list environments for activity stream", "error", err)
- }
- return
- }
-
- current := make(map[string]struct{}, len(envs))
- for _, env := range envs {
- current[env.ID] = struct{}{}
- if _, ok := pollers[env.ID]; ok {
- continue
- }
- pollCtx, cancelPoll := context.WithCancel(ctx) //nolint:gosec // cancel is retained in pollers and invoked on env removal or via the deferred cleanup.
- pollers[env.ID] = cancelPoll
- wg.Add(1)
- go func(environmentID string) {
- defer wg.Done()
- h.runRemoteActivityStreamPollerInternal(pollCtx, environmentID, limit, events)
- }(env.ID)
- }
-
- for id, cancelPoll := range pollers {
- if _, ok := current[id]; !ok {
- cancelPoll()
- delete(pollers, id)
- }
- }
- }
-
- reconcile()
-
- ticker := time.NewTicker(activityStreamEnvReconcileInterval)
- defer ticker.Stop()
-
- for {
- select {
- case <-ctx.Done():
- return
- case <-ticker.C:
- reconcile()
- }
- }
+ aggstream.ReconcileEnvironmentPollers(ctx, h.environmentService, activityStreamEnvReconcileInterval, "activity stream",
+ func(pollCtx context.Context, environmentID string) {
+ h.runRemoteActivityStreamPollerInternal(pollCtx, environmentID, limit, events)
+ })
}
func (h *ActivityHandler) runRemoteActivityStreamPollerInternal(ctx context.Context, environmentID string, limit int, events chan<- activity.StreamEvent) {
@@ -520,7 +431,7 @@ func (h *ActivityHandler) runRemoteActivityStreamPollerInternal(ctx context.Cont
// once per distinct message and keep polling.
if msg := err.Error(); msg != lastError {
lastError = msg
- sendActivityStreamEventInternal(ctx, events, activity.StreamEvent{
+ aggstream.Send(ctx, events, activity.StreamEvent{
Type: "error",
EnvironmentID: environmentID,
Error: msg,
@@ -530,7 +441,7 @@ func (h *ActivityHandler) runRemoteActivityStreamPollerInternal(ctx context.Cont
return
}
lastError = ""
- sendActivityStreamEventInternal(ctx, events, activity.StreamEvent{
+ aggstream.Send(ctx, events, activity.StreamEvent{
Type: "snapshot",
EnvironmentID: environmentID,
Activities: output.Body.Data,
diff --git a/backend/api/handlers/dashboard.go b/backend/api/handlers/dashboard.go
index 10f5eb954..02cdf992c 100644
--- a/backend/api/handlers/dashboard.go
+++ b/backend/api/handlers/dashboard.go
@@ -2,18 +2,29 @@ package handlers
import (
"context"
+ "encoding/json"
+ "errors"
"net/http"
+ "time"
"github.com/danielgtaylor/huma/v2"
humamw "github.com/getarcaneapp/arcane/backend/v2/api/middleware"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"
"github.com/getarcaneapp/arcane/backend/v2/internal/services"
"github.com/getarcaneapp/arcane/backend/v2/pkg/authz"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/aggstream"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/remenv"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"
"github.com/getarcaneapp/arcane/types/v2/base"
+ containertypes "github.com/getarcaneapp/arcane/types/v2/container"
dashboardtypes "github.com/getarcaneapp/arcane/types/v2/dashboard"
+ imagetypes "github.com/getarcaneapp/arcane/types/v2/image"
+ versiontypes "github.com/getarcaneapp/arcane/types/v2/version"
)
type DashboardHandler struct {
- dashboardService *services.DashboardService
+ dashboardService *services.DashboardService
+ environmentService *services.EnvironmentService
}
type GetDashboardInput struct {
@@ -25,8 +36,24 @@ type GetDashboardOutput struct {
Body base.ApiResponse[dashboardtypes.Snapshot]
}
-func RegisterDashboard(api huma.API, dashboardService *services.DashboardService) {
- h := &DashboardHandler{dashboardService: dashboardService}
+type StreamAllDashboardsInput struct {
+ DebugAllGood bool `query:"debugAllGood" default:"false" doc:"Debug mode: force an empty action item list"`
+}
+
+const (
+ dashboardStreamHeartbeatInterval = 15 * time.Second
+ dashboardStreamLocalPollInterval = 15 * time.Second
+ dashboardStreamRemotePollInterval = 15 * time.Second
+ dashboardStreamEnvReconcileInterval = 30 * time.Second
+ dashboardStreamRemotePollTimeout = 15 * time.Second
+ dashboardStreamEventBuffer = 64
+)
+
+func RegisterDashboard(api huma.API, dashboardService *services.DashboardService, environmentService *services.EnvironmentService) {
+ h := &DashboardHandler{
+ dashboardService: dashboardService,
+ environmentService: environmentService,
+ }
huma.Register(api, huma.Operation{
OperationID: "get-dashboard",
@@ -41,6 +68,20 @@ func RegisterDashboard(api huma.API, dashboardService *services.DashboardService
},
Middlewares: humamw.RequirePermission(api, authz.PermDashboardRead),
}, h.GetDashboard)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "stream-all-dashboards",
+ Method: http.MethodGet,
+ Path: "/dashboard/stream",
+ Summary: "Stream dashboard snapshots across all environments",
+ Description: "Stream dashboard snapshot updates for the local environment and all enabled remote environments as JSON lines",
+ Tags: []string{"Dashboard"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ Middlewares: humamw.RequirePermission(api, authz.PermDashboardRead),
+ }, h.StreamAllDashboards)
}
func (h *DashboardHandler) GetDashboard(ctx context.Context, input *GetDashboardInput) (*GetDashboardOutput, error) {
@@ -69,3 +110,277 @@ func (h *DashboardHandler) GetDashboard(ctx context.Context, input *GetDashboard
},
}, nil
}
+
+func (h *DashboardHandler) StreamAllDashboards(ctx context.Context, input *StreamAllDashboardsInput) (*huma.StreamResponse, error) {
+ if h.dashboardService == nil || h.environmentService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ return &huma.StreamResponse{
+ Body: func(humaCtx huma.Context) { //nolint:contextcheck // streaming work must use humaCtx.Context()
+ httpx.SetJSONStreamHeaders(humaCtx)
+
+ writer := humaCtx.BodyWriter()
+ encoder := json.NewEncoder(writer)
+ flush := func() {
+ if f, ok := writer.(http.Flusher); ok {
+ f.Flush()
+ }
+ }
+
+ h.streamAllDashboardsInternal(humaCtx.Context(), input.DebugAllGood, encoder, flush)
+ },
+ }, nil
+}
+
+// streamAllDashboardsInternal multiplexes dashboard snapshots for the local
+// environment and every enabled remote environment over a single response so
+// the browser needs one connection regardless of environment count.
+func (h *DashboardHandler) streamAllDashboardsInternal(ctx context.Context, debugAllGood bool, encoder *json.Encoder, flush func()) {
+ aggstream.Run(ctx, encoder, flush, dashboardStreamEventBuffer, dashboardStreamHeartbeatInterval,
+ func() dashboardtypes.StreamEvent {
+ return dashboardtypes.StreamEvent{Type: "heartbeat", Timestamp: time.Now()}
+ },
+ func(ctx context.Context, events chan<- dashboardtypes.StreamEvent) {
+ h.runLocalDashboardStreamProducerInternal(ctx, debugAllGood, events)
+ },
+ func(ctx context.Context, events chan<- dashboardtypes.StreamEvent) {
+ h.runRemoteDashboardStreamPollersInternal(ctx, debugAllGood, events)
+ },
+ )
+}
+
+// trimDashboardStreamSnapshotInternal drops the first-page container/image
+// tables: the all-environments dashboard only reads the aggregate counters,
+// and re-sending table rows for every environment on every poll would bloat
+// the stream.
+func trimDashboardStreamSnapshotInternal(snapshot *dashboardtypes.Snapshot) *dashboardtypes.Snapshot {
+ if snapshot == nil {
+ return nil
+ }
+ snapshot.Containers.Data = nil
+ snapshot.Images.Data = nil
+ return snapshot
+}
+
+func (h *DashboardHandler) runLocalDashboardStreamProducerInternal(ctx context.Context, debugAllGood bool, events chan<- dashboardtypes.StreamEvent) {
+ lastError := ""
+
+ poll := func() {
+ snapshot, err := h.dashboardService.GetSnapshot(ctx, services.DashboardActionItemsOptions{
+ DebugAllGood: debugAllGood,
+ })
+ if err == nil && snapshot == nil {
+ err = &common.DashboardSnapshotUnavailableError{}
+ }
+ if err != nil {
+ if ctx.Err() != nil {
+ return
+ }
+ // A failing snapshot must not end the stream; surface the error
+ // once per distinct message and keep polling.
+ if msg := err.Error(); msg != lastError {
+ lastError = msg
+ aggstream.Send(ctx, events, dashboardtypes.StreamEvent{
+ Type: "error",
+ EnvironmentID: "0",
+ Error: msg,
+ Timestamp: time.Now(),
+ })
+ }
+ return
+ }
+ lastError = ""
+ aggstream.Send(ctx, events, dashboardtypes.StreamEvent{
+ Type: "snapshot",
+ EnvironmentID: "0",
+ Snapshot: trimDashboardStreamSnapshotInternal(snapshot),
+ Timestamp: time.Now(),
+ })
+ }
+
+ poll()
+
+ ticker := time.NewTicker(dashboardStreamLocalPollInterval)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ poll()
+ }
+ }
+}
+
+// runRemoteDashboardStreamPollersInternal keeps one poller goroutine per
+// enabled remote environment, re-listing periodically so environments added
+// or removed while the stream is open are picked up without a reconnect.
+func (h *DashboardHandler) runRemoteDashboardStreamPollersInternal(ctx context.Context, debugAllGood bool, events chan<- dashboardtypes.StreamEvent) {
+ aggstream.ReconcileEnvironmentPollers(ctx, h.environmentService, dashboardStreamEnvReconcileInterval, "dashboard stream",
+ func(pollCtx context.Context, environmentID string) {
+ h.runRemoteDashboardStreamPollerInternal(pollCtx, environmentID, debugAllGood, events)
+ })
+}
+
+func (h *DashboardHandler) runRemoteDashboardStreamPollerInternal(ctx context.Context, environmentID string, debugAllGood bool, events chan<- dashboardtypes.StreamEvent) {
+ // Tell the client this environment is covered before the first poll
+ // completes so it can hold skeletons instead of assuming no data exists.
+ if !aggstream.Send(ctx, events, dashboardtypes.StreamEvent{
+ Type: "pending",
+ EnvironmentID: environmentID,
+ Timestamp: time.Now(),
+ }) {
+ return
+ }
+
+ lastError := ""
+
+ poll := func() {
+ pollCtx, cancelPoll := context.WithTimeout(ctx, dashboardStreamRemotePollTimeout)
+ defer cancelPoll()
+
+ snapshot, err := h.fetchRemoteDashboardSnapshotInternal(pollCtx, environmentID, debugAllGood)
+ if err != nil && isDashboardEndpointMissingInternal(err) {
+ // The agent runs a version without (or with an incompatible)
+ // aggregate dashboard endpoint; the underlying data is still
+ // there, so compose the snapshot from the granular endpoints.
+ snapshot, err = h.fetchLegacyDashboardSnapshotInternal(pollCtx, environmentID)
+ }
+ if err != nil {
+ if ctx.Err() != nil {
+ return
+ }
+ // A failing environment must not end the stream; surface the error
+ // once per distinct message and keep polling.
+ message, code := classifyDashboardStreamErrorInternal(err)
+ if message != lastError {
+ lastError = message
+ aggstream.Send(ctx, events, dashboardtypes.StreamEvent{
+ Type: "error",
+ EnvironmentID: environmentID,
+ Error: message,
+ ErrorCode: code,
+ Timestamp: time.Now(),
+ })
+ }
+ return
+ }
+ lastError = ""
+ aggstream.Send(ctx, events, dashboardtypes.StreamEvent{
+ Type: "snapshot",
+ EnvironmentID: environmentID,
+ Snapshot: trimDashboardStreamSnapshotInternal(snapshot),
+ Timestamp: time.Now(),
+ })
+ }
+
+ poll()
+
+ ticker := time.NewTicker(dashboardStreamRemotePollInterval)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ poll()
+ }
+ }
+}
+
+// fetchRemoteDashboardSnapshotInternal proxies the per-environment dashboard
+// endpoint directly through the environment service so the raw remenv error
+// survives for classification (proxyRemoteJSONInternal would translate it
+// into a huma error first).
+func (h *DashboardHandler) fetchRemoteDashboardSnapshotInternal(ctx context.Context, environmentID string, debugAllGood bool) (*dashboardtypes.Snapshot, error) {
+ path := "/api/environments/0/dashboard"
+ if debugAllGood {
+ path += "?debugAllGood=true"
+ }
+
+ var out base.ApiResponse[dashboardtypes.Snapshot]
+ if err := h.environmentService.ProxyJSONRequest(ctx, environmentID, http.MethodGet, path, nil, &out); err != nil {
+ return nil, err
+ }
+ if !out.Success {
+ return nil, &common.DashboardSnapshotUnavailableError{}
+ }
+ return &out.Data, nil
+}
+
+// fetchLegacyDashboardSnapshotInternal composes a dashboard snapshot from the
+// granular endpoints (container counts, image usage counts, app version) that
+// agents have exposed for far longer than the aggregate dashboard endpoint.
+// Each piece is fetched independently so a partially compatible agent still
+// yields partial data; only when every piece fails is an error returned.
+func (h *DashboardHandler) fetchLegacyDashboardSnapshotInternal(ctx context.Context, environmentID string) (*dashboardtypes.Snapshot, error) {
+ snapshot := &dashboardtypes.Snapshot{
+ ActionItems: dashboardtypes.ActionItems{Items: []dashboardtypes.ActionItem{}},
+ }
+ var errs []error
+ attempted := 0
+
+ attempted++
+ var containerCounts base.ApiResponse[containertypes.StatusCounts]
+ if err := h.environmentService.ProxyJSONRequest(ctx, environmentID, http.MethodGet, "/api/environments/0/containers/counts", nil, &containerCounts); err != nil {
+ errs = append(errs, err)
+ } else {
+ snapshot.Containers.Counts = containerCounts.Data
+ if stopped := containerCounts.Data.StoppedContainers; stopped > 0 {
+ snapshot.ActionItems.Items = append(snapshot.ActionItems.Items, dashboardtypes.ActionItem{
+ Kind: dashboardtypes.ActionItemKindStoppedContainers,
+ Count: stopped,
+ Severity: dashboardtypes.ActionItemSeverityWarning,
+ })
+ }
+ }
+
+ attempted++
+ var imageCounts base.ApiResponse[imagetypes.UsageCounts]
+ if err := h.environmentService.ProxyJSONRequest(ctx, environmentID, http.MethodGet, "/api/environments/0/images/counts", nil, &imageCounts); err != nil {
+ errs = append(errs, err)
+ } else {
+ snapshot.ImageUsageCounts = imageCounts.Data
+ }
+
+ attempted++
+ var versionInfo versiontypes.Info
+ if err := h.environmentService.ProxyJSONRequest(ctx, environmentID, http.MethodGet, "/api/app-version", nil, &versionInfo); err != nil {
+ errs = append(errs, err)
+ } else {
+ snapshot.VersionInfo = &versionInfo
+ }
+
+ if len(errs) == attempted {
+ return nil, errors.Join(errs...)
+ }
+ return snapshot, nil
+}
+
+// isDashboardEndpointMissingInternal reports whether the aggregate dashboard
+// endpoint is absent (404 on older agents) or speaks an incompatible payload
+// shape (decode failure) — the cases the legacy composition can recover from.
+func isDashboardEndpointMissingInternal(err error) bool {
+ if statusErr, ok := errors.AsType[*remenv.StatusError](err); ok && statusErr.StatusCode == http.StatusNotFound {
+ return true
+ }
+ _, ok := errors.AsType[*remenv.DecodeError](err)
+ return ok
+}
+
+// classifyDashboardStreamErrorInternal maps remote fetch failures to a
+// user-facing message and a stable error code. A 404 means the agent predates
+// the dashboard endpoint; a decode failure means its payload shape differs —
+// both indicate a version mismatch between manager and agent.
+func classifyDashboardStreamErrorInternal(err error) (string, string) {
+ if isDashboardEndpointMissingInternal(err) {
+ return (&common.AgentDashboardUnsupportedError{}).Error(), dashboardtypes.StreamErrorCodeAgentIncompatible
+ }
+ if transportErr, ok := errors.AsType[*remenv.TransportError](err); ok {
+ return transportErr.Error(), dashboardtypes.StreamErrorCodeUnreachable
+ }
+ return err.Error(), ""
+}
diff --git a/backend/api/handlers/dashboard_test.go b/backend/api/handlers/dashboard_test.go
index 2371e5a5c..e034b94e9 100644
--- a/backend/api/handlers/dashboard_test.go
+++ b/backend/api/handlers/dashboard_test.go
@@ -1,8 +1,10 @@
package handlers
import (
+ "bufio"
"context"
"encoding/json"
+ "io"
"net/http"
"net/http/httptest"
"strings"
@@ -132,3 +134,176 @@ func TestDashboardHandlerGetDashboardReturnsSnapshot(t *testing.T) {
{Kind: dashboardtypes.ActionItemKindExpiringKeys, Count: 1, Severity: dashboardtypes.ActionItemSeverityWarning},
}, snapshot.ActionItems.Items)
}
+
+// runDashboardStreamAllInternal drives streamAllDashboardsInternal through a
+// pipe and returns each decoded event to onEvent until it reports done or the
+// stream ends; remaining output is drained so a blocked encoder can finish.
+func runDashboardStreamAllInternal(t *testing.T, ctx context.Context, cancel context.CancelFunc, handler *DashboardHandler, onEvent func(dashboardtypes.StreamEvent) bool) {
+ t.Helper()
+
+ pr, pw := io.Pipe()
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ defer func() { _ = pw.Close() }()
+ handler.streamAllDashboardsInternal(ctx, false, json.NewEncoder(pw), func() {})
+ }()
+
+ scanner := bufio.NewScanner(pr)
+ for scanner.Scan() {
+ var event dashboardtypes.StreamEvent
+ require.NoError(t, json.Unmarshal(scanner.Bytes(), &event))
+ if onEvent(event) {
+ cancel()
+ break
+ }
+ }
+
+ go func() {
+ _, _ = io.Copy(io.Discard, pr)
+ }()
+ select {
+ case <-done:
+ case <-time.After(5 * time.Second):
+ t.Fatal("stream did not terminate after cancel")
+ }
+}
+
+func TestDashboardHandlerStreamAllEmitsRemoteSnapshotInternal(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ db := setupActivityHandlerTestDBInternal(t)
+ limitStreamTestDBToSingleConnInternal(t, db)
+ settingsService, err := services.NewSettingsService(ctx, db)
+ require.NoError(t, err)
+
+ token := "remote-token"
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ require.Equal(t, "/api/environments/0/dashboard", r.URL.Path)
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"success":true,"data":{
+ "containers":{"data":[{"id":"c1"}],"counts":{"runningContainers":2,"stoppedContainers":1,"totalContainers":3},"pagination":{"totalPages":1,"totalItems":1,"currentPage":1,"itemsPerPage":20}},
+ "images":{"data":[],"pagination":{"totalPages":1,"totalItems":0,"currentPage":1,"itemsPerPage":20}},
+ "imageUsageCounts":{"imagesInuse":4,"imagesUnused":1,"totalImages":5,"totalImageSize":0},
+ "actionItems":{"items":[]},
+ "settings":{}
+ }}`))
+ }))
+ defer server.Close()
+ createStreamTestRemoteEnvironmentInternal(t, db, server.URL, token)
+
+ handler := &DashboardHandler{
+ dashboardService: services.NewDashboardService(db, nil, nil, nil, nil, nil, nil, nil, nil),
+ environmentService: services.NewEnvironmentService(db, server.Client(), nil, nil, settingsService, nil),
+ }
+
+ var remoteSnapshot bool
+ runDashboardStreamAllInternal(t, ctx, cancel, handler, func(event dashboardtypes.StreamEvent) bool {
+ if event.Type == "snapshot" && event.EnvironmentID == "remote-1" && event.Snapshot != nil {
+ require.Equal(t, 2, event.Snapshot.Containers.Counts.RunningContainers)
+ require.Equal(t, 3, event.Snapshot.Containers.Counts.TotalContainers)
+ require.Equal(t, 5, event.Snapshot.ImageUsageCounts.Total)
+ require.Empty(t, event.Snapshot.Containers.Data, "first-page table rows must be trimmed from stream events")
+ remoteSnapshot = true
+ }
+ return remoteSnapshot
+ })
+
+ require.True(t, remoteSnapshot)
+}
+
+func TestDashboardHandlerStreamAllLegacyAgentComposesSnapshotFromGranularEndpointsInternal(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ db := setupActivityHandlerTestDBInternal(t)
+ limitStreamTestDBToSingleConnInternal(t, db)
+ settingsService, err := services.NewSettingsService(ctx, db)
+ require.NoError(t, err)
+
+ token := "remote-token"
+ // Older agents have no /dashboard route but do expose the granular
+ // counts/version endpoints the fallback composes a snapshot from.
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ switch r.URL.Path {
+ case "/api/environments/0/containers/counts":
+ _, _ = w.Write([]byte(`{"success":true,"data":{"runningContainers":4,"stoppedContainers":2,"totalContainers":6}}`))
+ case "/api/environments/0/images/counts":
+ _, _ = w.Write([]byte(`{"success":true,"data":{"imagesInuse":3,"imagesUnused":1,"totalImages":4,"totalImageSize":1024}}`))
+ case "/api/app-version":
+ _, _ = w.Write([]byte(`{"currentVersion":"1.9.0","displayVersion":"1.9.0","updateAvailable":true}`))
+ default:
+ w.WriteHeader(http.StatusNotFound)
+ _, _ = w.Write([]byte(`{"success":false,"error":"API endpoint not found: ` + r.URL.Path + `"}`))
+ }
+ }))
+ defer server.Close()
+ createStreamTestRemoteEnvironmentInternal(t, db, server.URL, token)
+
+ handler := &DashboardHandler{
+ dashboardService: services.NewDashboardService(db, nil, nil, nil, nil, nil, nil, nil, nil),
+ environmentService: services.NewEnvironmentService(db, server.Client(), nil, nil, settingsService, nil),
+ }
+
+ var composedSnapshot bool
+ runDashboardStreamAllInternal(t, ctx, cancel, handler, func(event dashboardtypes.StreamEvent) bool {
+ if event.Type == "snapshot" && event.EnvironmentID == "remote-1" && event.Snapshot != nil {
+ require.Equal(t, 4, event.Snapshot.Containers.Counts.RunningContainers)
+ require.Equal(t, 2, event.Snapshot.Containers.Counts.StoppedContainers)
+ require.Equal(t, 4, event.Snapshot.ImageUsageCounts.Total)
+ require.Len(t, event.Snapshot.ActionItems.Items, 1)
+ require.Equal(t, dashboardtypes.ActionItemKindStoppedContainers, event.Snapshot.ActionItems.Items[0].Kind)
+ require.NotNil(t, event.Snapshot.VersionInfo)
+ require.Equal(t, "1.9.0", event.Snapshot.VersionInfo.CurrentVersion)
+ composedSnapshot = true
+ }
+ return composedSnapshot
+ })
+
+ require.True(t, composedSnapshot)
+}
+
+func TestDashboardHandlerStreamAllLegacyAgent404EmitsIncompatibleErrorInternal(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+
+ db := setupActivityHandlerTestDBInternal(t)
+ limitStreamTestDBToSingleConnInternal(t, db)
+ settingsService, err := services.NewSettingsService(ctx, db)
+ require.NoError(t, err)
+
+ token := "remote-token"
+ // An agent so incompatible that even the granular fallback endpoints 404.
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusNotFound)
+ _, _ = w.Write([]byte(`{"success":false,"error":"API endpoint not found: ` + r.URL.Path + `"}`))
+ }))
+ defer server.Close()
+ createStreamTestRemoteEnvironmentInternal(t, db, server.URL, token)
+
+ handler := &DashboardHandler{
+ dashboardService: services.NewDashboardService(db, nil, nil, nil, nil, nil, nil, nil, nil),
+ environmentService: services.NewEnvironmentService(db, server.Client(), nil, nil, settingsService, nil),
+ }
+
+ var incompatibleError, localEvent bool
+ runDashboardStreamAllInternal(t, ctx, cancel, handler, func(event dashboardtypes.StreamEvent) bool {
+ if event.Type == "error" && event.EnvironmentID == "remote-1" {
+ require.Equal(t, dashboardtypes.StreamErrorCodeAgentIncompatible, event.ErrorCode)
+ require.NotEmpty(t, event.Error)
+ incompatibleError = true
+ }
+ // The local producer still emits (an error here — no docker in tests),
+ // proving one failing environment doesn't end the stream.
+ if event.EnvironmentID == "0" {
+ localEvent = true
+ }
+ return incompatibleError && localEvent
+ })
+
+ require.True(t, incompatibleError)
+ require.True(t, localEvent)
+}
diff --git a/backend/internal/common/errors.go b/backend/internal/common/errors.go
index 482e52d7b..9f03cbd76 100644
--- a/backend/internal/common/errors.go
+++ b/backend/internal/common/errors.go
@@ -1928,3 +1928,20 @@ func (e *NoGlobalAdminRemainsError) Error() string {
func IsNoGlobalAdminRemainsError(err error) bool {
return isErrorTypeInternal[*NoGlobalAdminRemainsError](err)
}
+
+// AgentDashboardUnsupportedError is emitted on the aggregated dashboard stream
+// when a remote agent does not expose the dashboard snapshot endpoint, which
+// typically means the agent runs an older Arcane version than the manager.
+type AgentDashboardUnsupportedError struct{}
+
+func (e *AgentDashboardUnsupportedError) Error() string {
+ return "Agent does not provide the dashboard endpoint — the agent is likely running an older Arcane version and should be upgraded"
+}
+
+// DashboardSnapshotUnavailableError is returned when a dashboard snapshot
+// request completes without producing a usable snapshot payload.
+type DashboardSnapshotUnavailableError struct{}
+
+func (e *DashboardSnapshotUnavailableError) Error() string {
+ return "dashboard snapshot not available"
+}
diff --git a/backend/internal/models/environment.go b/backend/internal/models/environment.go
index 76e28451d..8fb8ca1a6 100644
--- a/backend/internal/models/environment.go
+++ b/backend/internal/models/environment.go
@@ -12,6 +12,7 @@ type Environment struct {
IsEdge bool `json:"isEdge" gorm:"column:is_edge;default:false"`
Hidden bool `json:"hidden" gorm:"column:hidden;default:false"`
LastSeen *time.Time `json:"lastSeen" gorm:"column:last_seen"`
+ LastEdgeTransport *string `json:"lastEdgeTransport" gorm:"column:last_edge_transport"`
AccessToken *string `json:"-" gorm:"column:access_token"`
ApiKeyID *string `json:"-" gorm:"column:api_key_id"`
ParentEnvironmentID *string `json:"-" gorm:"column:parent_environment_id"`
diff --git a/backend/internal/services/environment_service.go b/backend/internal/services/environment_service.go
index d4dc2a503..31ce95e6e 100644
--- a/backend/internal/services/environment_service.go
+++ b/backend/internal/services/environment_service.go
@@ -766,13 +766,15 @@ func environmentTypeKeyInternal(env environment.Environment) string {
if !env.IsEdge {
return "http"
}
- if env.LastPollAt != nil {
- return "polling"
- }
- if env.Connected == nil || !*env.Connected || env.EdgeTransport == nil || strings.TrimSpace(*env.EdgeTransport) == "" {
- return "edge"
- }
- switch strings.ToLower(strings.TrimSpace(*env.EdgeTransport)) {
+ transport := ""
+ if env.Connected != nil && *env.Connected && env.EdgeTransport != nil {
+ transport = *env.EdgeTransport
+ } else if env.LastEdgeTransport != nil {
+ // Disconnected or poll-only agents classify by the transport they
+ // last used rather than collapsing into the generic edge bucket.
+ transport = *env.LastEdgeTransport
+ }
+ switch strings.ToLower(strings.TrimSpace(transport)) {
case edge.EdgeTransportWebSocket:
return "websocket"
case edge.EdgeTransportGRPC:
@@ -804,6 +806,20 @@ func (s *EnvironmentService) ListVisibleEnvironments(ctx context.Context) ([]env
return out, nil
}
+// ListRemoteEnvironmentIDs returns the IDs of enabled remote environments; it
+// satisfies aggstream.RemoteEnvironmentLister for aggregated stream handlers.
+func (s *EnvironmentService) ListRemoteEnvironmentIDs(ctx context.Context) ([]string, error) {
+ envs, err := s.ListRemoteEnvironments(ctx)
+ if err != nil {
+ return nil, err
+ }
+ ids := make([]string, 0, len(envs))
+ for _, env := range envs {
+ ids = append(ids, env.ID)
+ }
+ return ids, nil
+}
+
// ListRemoteEnvironments returns all non-local, enabled environments for syncing purposes.
func (s *EnvironmentService) ListRemoteEnvironments(ctx context.Context) ([]models.Environment, error) {
var envs []models.Environment
@@ -1086,6 +1102,11 @@ func (s *EnvironmentService) UpdateEnvironmentConnectionState(ctx context.Contex
if connected {
updates["status"] = string(models.EnvironmentStatusOnline)
updates["last_seen"] = &now
+ // Remember the tunnel transport so the UI can keep showing it after
+ // the tunnel drops or while the agent is poll-only.
+ if state, ok := edge.GetTunnelRuntimeState(id); ok && state.Transport != "" {
+ updates["last_edge_transport"] = state.Transport
+ }
} else {
updates["status"] = string(models.EnvironmentStatusOffline)
}
diff --git a/backend/internal/services/environment_service_test.go b/backend/internal/services/environment_service_test.go
index 6c6fceb4d..8ac88a991 100644
--- a/backend/internal/services/environment_service_test.go
+++ b/backend/internal/services/environment_service_test.go
@@ -797,6 +797,15 @@ func TestEnvironmentService_ListEnvironmentsPaginated_FiltersByRuntimeType(t *te
Enabled: true,
IsEdge: true,
},
+ {
+ BaseModel: models.BaseModel{ID: "env-last-ws", CreatedAt: now, UpdatedAt: &now},
+ Name: "LastWebsocket",
+ ApiUrl: "edge://last-ws",
+ Status: string(models.EnvironmentStatusOffline),
+ Enabled: true,
+ IsEdge: true,
+ LastEdgeTransport: new("websocket"),
+ },
}
require.NoError(t, db.WithContext(ctx).Create(&envs).Error)
@@ -824,11 +833,12 @@ func TestEnvironmentService_ListEnvironmentsPaginated_FiltersByRuntimeType(t *te
wantIDs []string
}{
{name: "http", typeFilter: "http", wantIDs: []string{"0"}},
- {name: "edge", typeFilter: "edge", wantIDs: []string{"env-edge"}},
+ // Poll-only edge environments (no tunnel transport) classify as plain edge.
+ {name: "edge", typeFilter: "edge", wantIDs: []string{"env-edge", "env-polling"}},
{name: "grpc", typeFilter: "grpc", wantIDs: []string{"env-grpc"}},
- {name: "websocket", typeFilter: "websocket", wantIDs: []string{"env-websocket"}},
- {name: "polling", typeFilter: "polling", wantIDs: []string{"env-polling"}},
- {name: "multiple", typeFilter: "http,polling", wantIDs: []string{"0", "env-polling"}},
+ // Disconnected agents classify by the transport they last used.
+ {name: "websocket", typeFilter: "websocket", wantIDs: []string{"env-websocket", "env-last-ws"}},
+ {name: "multiple", typeFilter: "http,grpc", wantIDs: []string{"0", "env-grpc"}},
}
for _, tt := range tests {
diff --git a/backend/pkg/libarcane/aggstream/aggstream.go b/backend/pkg/libarcane/aggstream/aggstream.go
new file mode 100644
index 000000000..f7b6b4fcd
--- /dev/null
+++ b/backend/pkg/libarcane/aggstream/aggstream.go
@@ -0,0 +1,145 @@
+// Package aggstream provides the plumbing for aggregated JSON-lines streams:
+// endpoints that multiplex per-environment events from the local environment
+// and every remote environment over a single HTTP response, so the browser
+// needs one connection regardless of environment count.
+package aggstream
+
+import (
+ "context"
+ "encoding/json"
+ "log/slog"
+ "sync"
+ "time"
+)
+
+// RemoteEnvironmentLister lists the remote environment IDs an aggregated
+// stream should cover; it decouples this package from the environment service.
+type RemoteEnvironmentLister interface {
+ ListRemoteEnvironmentIDs(ctx context.Context) ([]string, error)
+}
+
+// Run drives a JSON-lines aggregated stream: it fans in events from the given
+// producers over a single buffered channel and multiplexes them onto the
+// response together with periodic heartbeats. It returns when the request
+// context is canceled or the response writer fails.
+func Run[T any](
+ ctx context.Context,
+ encoder *json.Encoder,
+ flush func(),
+ buffer int,
+ heartbeatInterval time.Duration,
+ makeHeartbeat func() T,
+ producers ...func(ctx context.Context, events chan<- T),
+) {
+ streamCtx, cancel := context.WithCancel(ctx)
+
+ events := make(chan T, buffer)
+ var wg sync.WaitGroup
+ wg.Add(len(producers))
+ for _, producer := range producers {
+ go func(producer func(context.Context, chan<- T)) {
+ defer wg.Done()
+ producer(streamCtx, events)
+ }(producer)
+ }
+ defer wg.Wait()
+ defer cancel()
+
+ heartbeat := time.NewTicker(heartbeatInterval)
+ defer heartbeat.Stop()
+
+ for {
+ select {
+ case <-streamCtx.Done():
+ return
+ case event := <-events:
+ if err := encoder.Encode(event); err != nil {
+ return
+ }
+ flush()
+ case <-heartbeat.C:
+ if err := encoder.Encode(makeHeartbeat()); err != nil {
+ return
+ }
+ flush()
+ }
+ }
+}
+
+// Send forwards an event to the stream's event channel, giving up when the
+// stream is shutting down so producers can never block.
+func Send[T any](ctx context.Context, events chan<- T, event T) bool {
+ select {
+ case events <- event:
+ return true
+ case <-ctx.Done():
+ return false
+ }
+}
+
+// ReconcileEnvironmentPollers keeps one poller goroutine per enabled remote
+// environment, re-listing periodically so environments added or removed while
+// the stream is open are picked up without a reconnect. It returns when the
+// stream context is canceled, after every poller has exited.
+func ReconcileEnvironmentPollers(
+ ctx context.Context,
+ lister RemoteEnvironmentLister,
+ reconcileInterval time.Duration,
+ streamLabel string,
+ runPoller func(ctx context.Context, environmentID string),
+) {
+ pollers := make(map[string]context.CancelFunc)
+ var wg sync.WaitGroup
+ defer wg.Wait()
+ defer func() {
+ for _, cancelPoll := range pollers {
+ cancelPoll()
+ }
+ }()
+
+ reconcile := func() {
+ environmentIDs, err := lister.ListRemoteEnvironmentIDs(ctx)
+ if err != nil {
+ if ctx.Err() == nil {
+ slog.WarnContext(ctx, "failed to list environments for "+streamLabel, "error", err)
+ }
+ return
+ }
+
+ current := make(map[string]struct{}, len(environmentIDs))
+ for _, environmentID := range environmentIDs {
+ current[environmentID] = struct{}{}
+ if _, ok := pollers[environmentID]; ok {
+ continue
+ }
+ pollCtx, cancelPoll := context.WithCancel(ctx) //nolint:gosec // cancel is retained in pollers and invoked on env removal or via the deferred cleanup.
+ pollers[environmentID] = cancelPoll
+ wg.Add(1)
+ go func(environmentID string) {
+ defer wg.Done()
+ runPoller(pollCtx, environmentID)
+ }(environmentID)
+ }
+
+ for id, cancelPoll := range pollers {
+ if _, ok := current[id]; !ok {
+ cancelPoll()
+ delete(pollers, id)
+ }
+ }
+ }
+
+ reconcile()
+
+ ticker := time.NewTicker(reconcileInterval)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ reconcile()
+ }
+ }
+}
diff --git a/backend/resources/migrations/postgres/058_add_environment_last_edge_transport.sql b/backend/resources/migrations/postgres/058_add_environment_last_edge_transport.sql
new file mode 100644
index 000000000..953cf9d72
--- /dev/null
+++ b/backend/resources/migrations/postgres/058_add_environment_last_edge_transport.sql
@@ -0,0 +1,5 @@
+-- +goose Up
+ALTER TABLE environments ADD COLUMN IF NOT EXISTS last_edge_transport TEXT;
+
+-- +goose Down
+ALTER TABLE environments DROP COLUMN IF EXISTS last_edge_transport;
diff --git a/backend/resources/migrations/sqlite/058_add_environment_last_edge_transport.sql b/backend/resources/migrations/sqlite/058_add_environment_last_edge_transport.sql
new file mode 100644
index 000000000..b54ffb8e4
--- /dev/null
+++ b/backend/resources/migrations/sqlite/058_add_environment_last_edge_transport.sql
@@ -0,0 +1,5 @@
+-- +goose Up
+ALTER TABLE environments ADD COLUMN last_edge_transport TEXT;
+
+-- +goose Down
+ALTER TABLE environments DROP COLUMN last_edge_transport;
diff --git a/frontend/messages/en.json b/frontend/messages/en.json
index 9108c02ef..a0c75b450 100644
--- a/frontend/messages/en.json
+++ b/frontend/messages/en.json
@@ -478,6 +478,7 @@
"dashboard_all_environment_unavailable_title": "Environment unavailable",
"dashboard_all_environment_unavailable_description": "This environment is offline, pending, or otherwise unreachable right now.",
"dashboard_all_summary_unavailable": "Environment summary unavailable. {error}",
+ "dashboard_all_agent_incompatible": "Agent is running an older Arcane version and can't report dashboard data — upgrade the agent.",
"_comment_containers": "=== CONTAINERS ===",
"containers_title": "Containers",
"containers_subtitle": "View and Manage your Containers",
@@ -1314,7 +1315,6 @@
"environments_new_agent_mtls_assets_unavailable": "Manager mTLS assets are not available. Showing the standard edge agent config instead.",
"environments_download_edge_ca": "Download Edge CA",
"environments_download_edge_ca_failed": "Failed to download Edge CA",
- "environments_edge_polling_label": "Polling",
"environments_edge_control_plane_label": "Control Plane",
"environments_edge_polling_active": "Polling Active",
"environments_edge_polling_standby": "Polling Standby",
diff --git a/frontend/src/lib/components/dialogs/update-center-dialog.svelte b/frontend/src/lib/components/dialogs/update-center-dialog.svelte
index 776c74b64..fee3ec3dc 100644
--- a/frontend/src/lib/components/dialogs/update-center-dialog.svelte
+++ b/frontend/src/lib/components/dialogs/update-center-dialog.svelte
@@ -15,15 +15,18 @@
import DOMPurify from 'isomorphic-dompurify';
import { formatDistanceToNow } from 'date-fns';
+ // open/upgrading have no $bindable fallback: upstream binds can start out
+ // undefined, and binding undefined to a $bindable with a fallback throws
+ // props_invalid_value. Undefined reads as falsy.
let {
- open = $bindable(false),
+ open = $bindable(undefined),
versionInformation,
onConfirm,
environmentName,
environmentId,
canInstall = true,
debug = false,
- upgrading = $bindable(false)
+ upgrading = $bindable(undefined)
}: {
open?: boolean;
versionInformation?: AppVersionInformation;
diff --git a/frontend/src/lib/services/dashboard-service.ts b/frontend/src/lib/services/dashboard-service.ts
index fe38c5c69..5ea90d742 100644
--- a/frontend/src/lib/services/dashboard-service.ts
+++ b/frontend/src/lib/services/dashboard-service.ts
@@ -1,4 +1,4 @@
-import BaseAPIService from './api-service';
+import BaseAPIService, { handleUnauthorizedResponseInternal } from './api-service';
import type { DashboardSnapshot } from '$lib/types/shared';
interface GetDashboardOptions {
@@ -10,6 +10,37 @@ class DashboardService extends BaseAPIService {
const params = options?.debugAllGood ? { debugAllGood: 'true' } : undefined;
return this.handleResponse(this.api.get(`/environments/${environmentId}/dashboard`, { params }));
}
+
+ getDashboardStreamUrl(debugAllGood = false): string {
+ const baseUrl = this.api.defaults.baseURL.replace(/\/+$/, '');
+ const params = new URLSearchParams();
+ if (debugAllGood) {
+ params.set('debugAllGood', 'true');
+ }
+ const query = params.toString();
+ return `${baseUrl}/dashboard/stream${query ? `?${query}` : ''}`;
+ }
+
+ async openDashboardStream(signal: AbortSignal, debugAllGood = false, retry = false): Promise<Response> {
+ const response = await fetch(this.getDashboardStreamUrl(debugAllGood), {
+ credentials: 'include',
+ headers: { Accept: 'application/x-json-stream' },
+ signal
+ });
+ if (response.status === 401) {
+ const action = await handleUnauthorizedResponseInternal('/dashboard/stream', retry);
+ if (action === 'retry') {
+ return this.openDashboardStream(signal, debugAllGood, true);
+ }
+ if (action === 'redirect') {
+ return new Promise<Response>(() => {});
+ }
+ }
+ if (!response.ok) {
+ throw new Error(`Dashboard stream failed with status ${response.status}`);
+ }
+ return response;
+ }
}
export const dashboardService = new DashboardService();
diff --git a/frontend/src/lib/stores/dashboard.store.svelte.ts b/frontend/src/lib/stores/dashboard.store.svelte.ts
new file mode 100644
index 000000000..586e89317
--- /dev/null
+++ b/frontend/src/lib/stores/dashboard.store.svelte.ts
@@ -0,0 +1,412 @@
+import { browser } from '$app/env';
+import { dashboardService } from '$lib/services/dashboard-service';
+import { environmentStore, LOCAL_DOCKER_ENVIRONMENT_ID } from '$lib/stores/environment.store.svelte';
+import type { DashboardSnapshot, DashboardStreamErrorCode, DashboardStreamEvent } from '$lib/types/shared';
+import type { Environment } from '$lib/types/environment';
+
+const MAX_RECONNECT_DELAY = 15_000;
+const MAX_RECONNECT_ATTEMPTS = 20;
+
+type DashboardEnvironmentState = {
+ id: string;
+ name: string;
+ snapshot: DashboardSnapshot | null;
+ // hasLoaded flips on the first-ever snapshot and never back: later errors
+ // keep showing the last-known data instead of skeletons or zeros.
+ hasLoaded: boolean;
+ loading: boolean;
+ streamError: boolean;
+ errorMessage?: string;
+ errorCode?: DashboardStreamErrorCode;
+};
+
+function environmentNameInternal(environment: Pick<Environment, 'id' | 'name'> | null | undefined): string {
+ if (!environment) {
+ return 'Local';
+ }
+ return environment.name || environment.id;
+}
+
+function errorMessageInternal(error: unknown): string | undefined {
+ if (error instanceof Error && error.message.trim()) {
+ return error.message;
+ }
+ return undefined;
+}
+
+function createDashboardStore() {
+ let _environmentStates = $state<Record<string, DashboardEnvironmentState>>({});
+
+ let started = false;
+ let debugAllGood = false;
+ let unsubscribeEnvironment: (() => void) | null = null;
+ // A single aggregated stream carries every environment's snapshots; per-env
+ // pollers would multiply requests and break against agents on older versions
+ // without a per-environment error story.
+ let streamAbortController: AbortController | null = null;
+ let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
+ let reconnectAttempt = 0;
+ let streamGeneration = 0;
+ let _streamConnected = $state(false);
+ let _streamFailed = $state(false);
+
+ function createEnvironmentStateInternal(environment: Pick<Environment, 'id' | 'name'>): DashboardEnvironmentState {
+ return {
+ id: environment.id || LOCAL_DOCKER_ENVIRONMENT_ID,
+ name: environmentNameInternal(environment),
+ snapshot: null,
+ hasLoaded: false,
+ loading: true,
+ streamError: false
+ };
+ }
+
+ function environmentStateInternal(environmentId: string): DashboardEnvironmentState | undefined {
+ return _environmentStates[environmentId];
+ }
+
+ function updateEnvironmentStateInternal(
+ environmentId: string,
+ updater: (state: DashboardEnvironmentState) => DashboardEnvironmentState
+ ) {
+ const current =
+ _environmentStates[environmentId] ?? createEnvironmentStateInternal({ id: environmentId, name: environmentId });
+ _environmentStates = {
+ ..._environmentStates,
+ [environmentId]: updater(current)
+ };
+ }
+
+ function setEnvironmentErrorInternal(environmentId: string, error: unknown, errorCode?: DashboardStreamErrorCode) {
+ // Errors only flag the state; snapshot and hasLoaded are left untouched
+ // so the card keeps rendering the last-known values.
+ updateEnvironmentStateInternal(environmentId, (state) => ({
+ ...state,
+ loading: false,
+ streamError: true,
+ errorMessage: errorMessageInternal(error),
+ errorCode
+ }));
+ }
+
+ function clearEnvironmentErrorInternal(environmentId: string) {
+ updateEnvironmentStateInternal(environmentId, (state) => ({
+ ...state,
+ streamError: false,
+ errorMessage: undefined,
+ errorCode: undefined
+ }));
+ }
+
+ // A fresh stream re-emits error events for environments that are still
+ // failing, so stale per-environment errors are cleared on every (re)connect.
+ function clearAllEnvironmentErrorsInternal() {
+ for (const environmentId of Object.keys(_environmentStates)) {
+ if (environmentStateInternal(environmentId)?.streamError) {
+ clearEnvironmentErrorInternal(environmentId);
+ }
+ }
+ }
+
+ function nextGenerationInternal(): number {
+ streamGeneration += 1;
+ return streamGeneration;
+ }
+
+ function isCurrentGenerationInternal(generation: number): boolean {
+ return streamGeneration === generation;
+ }
+
+ function clearReconnectTimerInternal() {
+ if (reconnectTimer) {
+ clearTimeout(reconnectTimer);
+ reconnectTimer = null;
+ }
+ }
+
+ function abortStreamInternal() {
+ clearReconnectTimerInternal();
+ streamAbortController?.abort();
+ streamAbortController = null;
+ _streamConnected = false;
+ }
+
+ function removeEnvironmentInternal(environmentId: string) {
+ const nextStates = { ..._environmentStates };
+ delete nextStates[environmentId];
+ _environmentStates = nextStates;
+ }
+
+ function replaceEnvironmentSnapshotInternal(environmentId: string, snapshot: DashboardSnapshot) {
+ // Snapshots can still arrive (stream or in-flight REST) after the
+ // environment was removed locally; don't resurrect it.
+ if (!environmentStateInternal(environmentId)) {
+ return;
+ }
+ updateEnvironmentStateInternal(environmentId, (state) => ({
+ ...state,
+ snapshot,
+ hasLoaded: true,
+ loading: false,
+ streamError: false,
+ errorMessage: undefined,
+ errorCode: undefined
+ }));
+ }
+
+ function applyStreamEventInternal(environmentId: string, event: DashboardStreamEvent) {
+ // The aggregated stream can keep delivering events for an environment
+ // for a short while after it was removed locally; don't resurrect it.
+ if (event.type !== 'heartbeat' && !environmentStateInternal(environmentId)) {
+ return;
+ }
+ switch (event.type) {
+ case 'snapshot':
+ if (event.snapshot) {
+ replaceEnvironmentSnapshotInternal(environmentId, event.snapshot);
+ }
+ break;
+ case 'pending':
+ // The server confirms this environment is covered; the first
+ // snapshot or error for it will follow.
+ break;
+ case 'heartbeat':
+ _streamConnected = true;
+ break;
+ case 'error':
+ setEnvironmentErrorInternal(environmentId, new Error(event.error || 'Dashboard stream error'), event.errorCode);
+ break;
+ }
+ }
+
+ async function refreshEnvironmentInternal(environmentId: string, generation = streamGeneration) {
+ try {
+ const snapshot = await dashboardService.getDashboardForEnvironment(environmentId, { debugAllGood });
+ // The environment can be removed while the fetch is in-flight; don't resurrect it.
+ if (!isCurrentGenerationInternal(generation) || !environmentStateInternal(environmentId)) {
+ return;
+ }
+ replaceEnvironmentSnapshotInternal(environmentId, snapshot);
+ } catch (error) {
+ if (isCurrentGenerationInternal(generation) && environmentStateInternal(environmentId)) {
+ console.warn('Failed to refresh dashboard snapshot:', error);
+ setEnvironmentErrorInternal(environmentId, error);
+ }
+ }
+ }
+
+ async function refreshInternal() {
+ reconcileEnvironmentsInternal();
+ await Promise.all(Object.keys(_environmentStates).map((environmentId) => refreshEnvironmentInternal(environmentId)));
+ }
+
+ async function connectStreamInternal(generation: number) {
+ if (!browser || !isCurrentGenerationInternal(generation)) {
+ return;
+ }
+
+ const controller = new AbortController();
+ streamAbortController = controller;
+ try {
+ const response = await dashboardService.openDashboardStream(controller.signal, debugAllGood);
+ if (!isCurrentGenerationInternal(generation) || !response.body) {
+ if (streamAbortController === controller) {
+ streamAbortController = null;
+ }
+ return;
+ }
+
+ _streamConnected = true;
+ _streamFailed = false;
+ reconnectAttempt = 0;
+ clearAllEnvironmentErrorsInternal();
+ await readJSONLinesInternal(response.body, generation);
+ } catch (error) {
+ if (!controller.signal.aborted && isCurrentGenerationInternal(generation)) {
+ console.warn('Dashboard stream disconnected:', error);
+ }
+ } finally {
+ if (streamAbortController === controller) {
+ streamAbortController = null;
+ }
+ if (isCurrentGenerationInternal(generation)) {
+ _streamConnected = false;
+ if (!controller.signal.aborted) {
+ scheduleReconnectInternal(generation);
+ }
+ }
+ }
+ }
+
+ async function readJSONLinesInternal(stream: ReadableStream<Uint8Array>, generation: number) {
+ const reader = stream.getReader();
+ const decoder = new TextDecoder();
+ let buffer = '';
+
+ try {
+ while (isCurrentGenerationInternal(generation)) {
+ const { done, value } = await reader.read();
+ if (done) {
+ break;
+ }
+
+ buffer += decoder.decode(value, { stream: true });
+ const lines = buffer.split('\n');
+ buffer = lines.pop() ?? '';
+ for (const line of lines) {
+ handleStreamLineInternal(line);
+ }
+ }
+
+ buffer += decoder.decode();
+ if (buffer.trim()) {
+ handleStreamLineInternal(buffer);
+ }
+ } finally {
+ reader.releaseLock();
+ }
+ }
+
+ function handleStreamLineInternal(line: string) {
+ const trimmed = line.trim();
+ if (!trimmed) {
+ return;
+ }
+
+ try {
+ const event = JSON.parse(trimmed) as DashboardStreamEvent;
+ applyStreamEventInternal(event.environmentId || LOCAL_DOCKER_ENVIRONMENT_ID, event);
+ } catch (error) {
+ console.warn('Failed to parse dashboard stream line:', error);
+ }
+ }
+
+ function scheduleReconnectInternal(generation: number) {
+ if (!browser || !started || !isCurrentGenerationInternal(generation)) {
+ return;
+ }
+
+ if (reconnectAttempt >= MAX_RECONNECT_ATTEMPTS) {
+ _streamFailed = true;
+ return;
+ }
+
+ clearReconnectTimerInternal();
+ const delay = Math.min(1000 * 2 ** reconnectAttempt, MAX_RECONNECT_DELAY);
+ reconnectAttempt += 1;
+ reconnectTimer = setTimeout(() => {
+ void connectStreamInternal(generation);
+ }, delay);
+ }
+
+ function reconcileEnvironmentsInternal() {
+ if (!browser || !started) {
+ return;
+ }
+
+ // Track only enabled environments — they are the ones the aggregated
+ // stream serves; a disabled environment would never leave "loading".
+ const available = environmentStore.available.filter((environment) => environment.enabled);
+ const environments =
+ available.length > 0
+ ? available
+ : [
+ {
+ id: environmentStore.selected?.id ?? LOCAL_DOCKER_ENVIRONMENT_ID,
+ name: environmentStore.selected?.name ?? 'Local'
+ }
+ ];
+ const targetIds = new Set(environments.map((environment) => environment.id || LOCAL_DOCKER_ENVIRONMENT_ID));
+
+ for (const environmentId of Object.keys(_environmentStates)) {
+ if (!targetIds.has(environmentId)) {
+ removeEnvironmentInternal(environmentId);
+ }
+ }
+
+ for (const environment of environments) {
+ const environmentId = environment.id || LOCAL_DOCKER_ENVIRONMENT_ID;
+ const existing = environmentStateInternal(environmentId);
+ if (!existing) {
+ _environmentStates = {
+ ..._environmentStates,
+ [environmentId]: createEnvironmentStateInternal(environment)
+ };
+ // An already-open aggregated stream only picks new environments
+ // up on its server-side reconcile tick; fetch once so the first
+ // snapshot doesn't take up to that interval to appear.
+ if (streamAbortController) {
+ void refreshEnvironmentInternal(environmentId);
+ }
+ continue;
+ }
+
+ if (existing.name !== environmentNameInternal(environment)) {
+ updateEnvironmentStateInternal(environmentId, (state) => ({
+ ...state,
+ name: environmentNameInternal(environment)
+ }));
+ }
+ }
+ }
+
+ return {
+ get connected(): boolean {
+ return _streamConnected;
+ },
+ get streamFailed(): boolean {
+ return _streamFailed;
+ },
+ getEnvironmentState(environmentId: string): DashboardEnvironmentState | null {
+ return _environmentStates[environmentId] ?? null;
+ },
+ isSnapshotLoading(environmentId: string): boolean {
+ const state = _environmentStates[environmentId];
+ return Boolean(state && state.loading && !state.hasLoaded);
+ },
+ start: async (options?: { debugAllGood?: boolean }) => {
+ const nextDebugAllGood = options?.debugAllGood ?? false;
+ if (!browser) {
+ return;
+ }
+ if (started) {
+ if (nextDebugAllGood === debugAllGood) {
+ return;
+ }
+ // The flag is encoded in the stream URL; restart to apply it.
+ debugAllGood = nextDebugAllGood;
+ abortStreamInternal();
+ void connectStreamInternal(nextGenerationInternal());
+ return;
+ }
+
+ started = true;
+ debugAllGood = nextDebugAllGood;
+ await environmentStore.ready;
+ reconcileEnvironmentsInternal();
+ void connectStreamInternal(nextGenerationInternal());
+ unsubscribeEnvironment = environmentStore.subscribeSelected(() => {
+ reconcileEnvironmentsInternal();
+ });
+ },
+ stop: () => {
+ started = false;
+ unsubscribeEnvironment?.();
+ unsubscribeEnvironment = null;
+ nextGenerationInternal();
+ abortStreamInternal();
+ reconnectAttempt = 0;
+ _streamFailed = false;
+ },
+ refresh: () => refreshInternal(),
+ retryStream: () => {
+ _streamFailed = false;
+ reconnectAttempt = 0;
+ clearAllEnvironmentErrorsInternal();
+ abortStreamInternal();
+ void connectStreamInternal(nextGenerationInternal());
+ }
+ };
+}
+
+export const dashboardStore = createDashboardStore();
diff --git a/frontend/src/lib/types/environment.ts b/frontend/src/lib/types/environment.ts
index 63eb4085a..36669404a 100644
--- a/frontend/src/lib/types/environment.ts
+++ b/frontend/src/lib/types/environment.ts
@@ -18,6 +18,7 @@ export type Environment = {
enabled: boolean;
isEdge: boolean;
edgeTransport?: 'grpc' | 'websocket';
+ lastEdgeTransport?: 'grpc' | 'websocket';
edgeSecurityMode?: 'token' | 'mtls';
connected?: boolean;
connectedAt?: string;
diff --git a/frontend/src/lib/types/shared.ts b/frontend/src/lib/types/shared.ts
index b1d1d1301..c708783e2 100644
--- a/frontend/src/lib/types/shared.ts
+++ b/frontend/src/lib/types/shared.ts
@@ -197,6 +197,19 @@ export interface DashboardSnapshot {
versionInfo?: AppVersionInformation;
}
+export type DashboardStreamEventType = 'snapshot' | 'error' | 'pending' | 'heartbeat';
+
+export type DashboardStreamErrorCode = 'agent_incompatible' | 'unreachable' | '';
+
+export interface DashboardStreamEvent {
+ type: DashboardStreamEventType;
+ environmentId?: string;
+ snapshot?: DashboardSnapshot;
+ error?: string;
+ errorCode?: DashboardStreamErrorCode;
+ timestamp: string;
+}
+
export type EnvironmentDashboardSnapshotState = 'ready' | 'skipped' | 'error';
export interface DashboardEnvironmentOverview {
diff --git a/frontend/src/routes/(app)/dashboard/dashboard-all-environments-view.svelte b/frontend/src/routes/(app)/dashboard/dashboard-all-environments-view.svelte
index 481eb4809..32c18c749 100644
--- a/frontend/src/routes/(app)/dashboard/dashboard-all-environments-view.svelte
+++ b/frontend/src/routes/(app)/dashboard/dashboard-all-environments-view.svelte
@@ -2,7 +2,7 @@
import { goto, invalidateAll } from '$app/navigation';
import { resolve } from '$app/paths';
import { formatDistanceToNow } from 'date-fns';
- import { onDestroy, untrack } from 'svelte';
+ import { onDestroy, onMount, untrack } from 'svelte';
import { toast } from 'svelte-sonner';
import { type ActionButton } from '$lib/components/action-button-group/index.js';
import { cn } from '$lib/utils';
@@ -13,8 +13,8 @@
import { Skeleton } from '$lib/components/ui/skeleton';
import * as Card from '$lib/components/ui/card/index.js';
import { m } from '$lib/paraglide/messages';
- import { dashboardService } from '$lib/services/dashboard-service';
import { systemService } from '$lib/services/system-service';
+ import { dashboardStore } from '$lib/stores/dashboard.store.svelte';
import { environmentStore } from '$lib/stores/environment.store.svelte';
import { hasAnyPermission, hasPermission } from '$lib/utils/auth';
import type { SystemStats } from '$lib/types/shared';
@@ -80,17 +80,6 @@
let upgradeDialogOpenById = $state<Record<string, boolean>>({});
let upgradeDialogUpgradingById = $state<Record<string, boolean>>({});
- type EnvironmentSnapshotState = {
- snapshot: DashboardSnapshot | null;
- loading: boolean;
- hasLoaded: boolean;
- error: string | null;
- };
-
- const dashboardSnapshotPollInterval = 15000;
- let snapshotByEnvironmentId = $state<Record<string, EnvironmentSnapshotState>>({});
- let snapshotPollers: Record<string, ReturnType<typeof setInterval>> = {};
-
let dockerInfoOpen = $state(false);
let dockerInfoData = $state<DockerInfo | null>(null);
let dockerInfoPromise = $state<Promise<DockerInfo> | null>(null);
@@ -219,62 +208,6 @@
}
}
- async function fetchEnvironmentSnapshot(environment: Environment) {
- if (!snapshotByEnvironmentId[environment.id]) {
- return;
- }
-
- const result = await tryCatch(dashboardService.getDashboardForEnvironment(environment.id, { debugAllGood }));
- const state = snapshotByEnvironmentId[environment.id];
- if (!state) {
- return;
- }
-
- if (result.error) {
- state.error = extractApiErrorMessage(result.error);
- } else {
- state.snapshot = result.data;
- state.error = null;
- state.hasLoaded = true;
- }
- state.loading = false;
- }
-
- function ensureEnvironmentSnapshot(environment: Environment) {
- if (!shouldLoadEnvironment(environment)) {
- removeEnvironmentSnapshot(environment.id);
- return;
- }
-
- if (!snapshotByEnvironmentId[environment.id]) {
- snapshotByEnvironmentId[environment.id] = { snapshot: null, loading: true, hasLoaded: false, error: null };
- }
-
- if (snapshotPollers[environment.id]) {
- return;
- }
-
- void fetchEnvironmentSnapshot(environment);
- snapshotPollers[environment.id] = setInterval(() => {
- void fetchEnvironmentSnapshot(environment);
- }, dashboardSnapshotPollInterval);
- }
-
- function removeEnvironmentSnapshot(environmentId: string) {
- const poller = snapshotPollers[environmentId];
- if (poller) {
- clearInterval(poller);
- delete snapshotPollers[environmentId];
- }
- delete snapshotByEnvironmentId[environmentId];
- }
-
- function cleanupEnvironmentSnapshots() {
- for (const environmentId of Object.keys(snapshotPollers)) {
- removeEnvironmentSnapshot(environmentId);
- }
- }
-
async function loadDockerInfo(environment: Environment): Promise<DockerInfo> {
try {
const info = await systemService.getDockerInfoForEnvironment(environment.id);
@@ -330,6 +263,13 @@
const loadableEnvironmentCards = $derived(environmentCards.filter(({ environment }) => shouldLoadEnvironment(environment)));
const loadableEnvironmentIds = $derived.by(() => new Set(loadableEnvironmentCards.map(({ environment }) => environment.id)));
+ function resolveSnapshotErrorMessage(state: NonNullable<ReturnType<typeof dashboardStore.getEnvironmentState>>): string {
+ if (state.errorCode === 'agent_incompatible') {
+ return m.dashboard_all_agent_incompatible();
+ }
+ return state.errorMessage || m.common_unknown();
+ }
+
const boardState = $derived.by(() => {
void reloadVersion;
@@ -337,10 +277,12 @@
const items: DashboardEnvironmentOverview[] = [];
for (const { environment } of environmentCards) {
- const state = snapshotByEnvironmentId[environment.id];
+ const state = dashboardStore.getEnvironmentState(environment.id);
let item: DashboardEnvironmentOverview;
if (state?.snapshot) {
+ // Last-known data keeps rendering even while the environment is
+ // erroring; the error banner is shown alongside it.
const snapshot = state.snapshot;
item = {
environment,
@@ -349,13 +291,14 @@
actionItems: snapshot.actionItems,
settings: snapshot.settings,
versionInfo: snapshot.versionInfo,
- snapshotState: 'ready'
+ snapshotState: 'ready',
+ snapshotError: state.streamError ? resolveSnapshotErrorMessage(state) : undefined
};
- } else if (state?.error) {
+ } else if (state?.streamError) {
item = {
...createBaseEnvironmentOverview(environment),
snapshotState: 'error',
- snapshotError: state.error
+ snapshotError: resolveSnapshotErrorMessage(state)
};
} else {
item = createBaseEnvironmentOverview(environment);
@@ -372,8 +315,7 @@
});
function isEnvironmentSnapshotLoading(environmentId: string): boolean {
- const state = snapshotByEnvironmentId[environmentId];
- return Boolean(state && state.loading && !state.hasLoaded);
+ return dashboardStore.isSnapshotLoading(environmentId);
}
const boardSummaryLoading = $derived.by(() => {
@@ -383,7 +325,7 @@
continue;
}
hasReachable = true;
- if (snapshotByEnvironmentId[environment.id]?.hasLoaded) {
+ if (dashboardStore.getEnvironmentState(environment.id)?.hasLoaded) {
return false;
}
}
@@ -396,7 +338,6 @@
untrack(() => {
for (const environment of environmentsToLoad) {
ensureEnvironmentLiveStats(environment);
- ensureEnvironmentSnapshot(environment);
}
});
});
@@ -410,29 +351,23 @@
removeEnvironmentLiveStats(environmentId);
}
}
-
- for (const environmentId of Object.keys(snapshotByEnvironmentId)) {
- if (!reachableEnvironmentIds.has(environmentId)) {
- removeEnvironmentSnapshot(environmentId);
- }
- }
});
});
+ onMount(() => {
+ void dashboardStore.start({ debugAllGood });
+ });
+
onDestroy(() => {
cleanupEnvironmentLiveStats();
- cleanupEnvironmentSnapshots();
+ dashboardStore.stop();
});
async function refreshOverview() {
isRefreshing = true;
try {
await invalidateAll();
- await Promise.all(
- environmentCards
- .filter(({ environment }) => shouldLoadEnvironment(environment))
- .map(({ environment }) => fetchEnvironmentSnapshot(environment))
- );
+ await dashboardStore.refresh();
reloadVersion += 1;
} finally {
isRefreshing = false;
@@ -464,15 +399,14 @@
return { text: m.dashboard_all_transport_http(), variant: 'gray' };
}
- if (environment.lastPollAt) {
- return { text: m.environments_edge_polling_label(), variant: 'blue' };
- }
-
- if (!environment.connected || !environment.edgeTransport) {
+ // Prefer the live tunnel transport; fall back to the last one used so
+ // disconnected or poll-only agents still show what they connect with.
+ const transport = (environment.connected ? environment.edgeTransport : undefined) ?? environment.lastEdgeTransport;
+ if (!transport) {
return { text: m.dashboard_all_transport_edge(), variant: 'gray' };
}
- return environment.edgeTransport === 'websocket'
+ return transport === 'websocket'
? { text: m.dashboard_all_transport_websocket(), variant: 'purple' }
: { text: m.dashboard_all_transport_grpc(), variant: 'blue' };
}
@@ -1115,7 +1049,7 @@
{#if boardState}
{@const loadedItem = boardState.overviewById.get(environment.id) ?? baseItem}
- {#if loadedItem.snapshotState === 'error' && loadedItem.snapshotError}
+ {#if loadedItem.snapshotError}
<div
class="rounded-lg border border-red-500/20 bg-red-500/5 px-3 py-2 text-xs text-red-700 dark:text-red-300"
>
diff --git a/frontend/src/routes/(app)/dashboard/dashboard-environment-upgrade-action.svelte b/frontend/src/routes/(app)/dashboard/dashboard-environment-upgrade-action.svelte
index 504fcb3f1..962e6f552 100644
--- a/frontend/src/routes/(app)/dashboard/dashboard-environment-upgrade-action.svelte
+++ b/frontend/src/routes/(app)/dashboard/dashboard-environment-upgrade-action.svelte
@@ -12,6 +12,9 @@
import { extractApiErrorMessage } from '$lib/utils/api';
import { DownloadIcon } from '$lib/icons';
+ // open/upgrading have no $bindable fallback: they bind to per-environment
+ // record entries that start out undefined, and binding undefined to a
+ // $bindable with a fallback throws props_invalid_value. Undefined reads as falsy.
let {
environment,
versionInfo,
@@ -19,8 +22,8 @@
debug = false,
onRefreshRequested,
render = 'both',
- open = $bindable(false),
- upgrading = $bindable(false)
+ open = $bindable(undefined),
+ upgrading = $bindable(undefined)
}: {
environment: Environment;
versionInfo: AppVersionInformation;
diff --git a/frontend/src/routes/(app)/environments/[id]/components/DetailsTab.svelte b/frontend/src/routes/(app)/environments/[id]/components/DetailsTab.svelte
index 0e30d9dda..11af5cfca 100644
--- a/frontend/src/routes/(app)/environments/[id]/components/DetailsTab.svelte
+++ b/frontend/src/routes/(app)/environments/[id]/components/DetailsTab.svelte
@@ -28,15 +28,14 @@
return { text: 'HTTP', variant: 'gray' };
}
- if (environment.lastPollAt) {
- return { text: m.environments_edge_polling_label(), variant: 'blue' };
- }
-
- if (!environment.connected || !environment.edgeTransport) {
+ // Prefer the live tunnel transport; fall back to the last one used so
+ // disconnected or poll-only agents still show what they connect with.
+ const transport = (environment.connected ? environment.edgeTransport : undefined) ?? environment.lastEdgeTransport;
+ if (!transport) {
return { text: 'Edge', variant: 'gray' };
}
- if (environment.edgeTransport === 'websocket') {
+ if (transport === 'websocket') {
return { text: 'WebSocket', variant: 'purple' };
}
diff --git a/frontend/src/routes/(app)/environments/environment-table.svelte b/frontend/src/routes/(app)/environments/environment-table.svelte
index 26fd5c51e..4a28180be 100644
--- a/frontend/src/routes/(app)/environments/environment-table.svelte
+++ b/frontend/src/routes/(app)/environments/environment-table.svelte
@@ -49,15 +49,20 @@
{ value: 'http', label: m.environments_edge_http_label(), icon: EnvironmentsIcon },
{ value: 'edge', label: m.environments_edge_label(), icon: EnvironmentsIcon },
{ value: 'websocket', label: m.environments_edge_websocket_label(), icon: EnvironmentsIcon },
- { value: 'grpc', label: m.environments_edge_grpc_label(), icon: EnvironmentsIcon },
- { value: 'polling', label: m.environments_edge_polling_label(), icon: EnvironmentsIcon }
+ { value: 'grpc', label: m.environments_edge_grpc_label(), icon: EnvironmentsIcon }
];
+ function resolveEnvironmentTransport(item: Environment): 'grpc' | 'websocket' | undefined {
+ // Prefer the live tunnel transport; fall back to the last one used so
+ // disconnected or poll-only agents still show what they connect with.
+ return (item.connected ? item.edgeTransport : undefined) ?? item.lastEdgeTransport;
+ }
+
function getEnvironmentTypeLabel(item: Environment): string {
if (!item.isEdge) return m.environments_edge_http_label();
- if (item.lastPollAt) return m.environments_edge_polling_label();
- if (!item.connected || !item.edgeTransport) return m.environments_edge_label();
- if (item.edgeTransport === 'websocket') return m.environments_edge_websocket_label();
+ const transport = resolveEnvironmentTransport(item);
+ if (!transport) return m.environments_edge_label();
+ if (transport === 'websocket') return m.environments_edge_websocket_label();
return m.environments_edge_grpc_label();
}
@@ -311,15 +316,8 @@
{#snippet TypeCell({ value }: { value: unknown })}
{@const env = value as Environment}
{@const typeLabel = getEnvironmentTypeLabel(env)}
- {@const typeVariant = !env.isEdge
- ? 'gray'
- : env.lastPollAt
- ? 'blue'
- : !env.connected || !env.edgeTransport
- ? 'gray'
- : env.edgeTransport === 'websocket'
- ? 'purple'
- : 'blue'}
+ {@const transport = resolveEnvironmentTransport(env)}
+ {@const typeVariant = !env.isEdge || !transport ? 'gray' : transport === 'websocket' ? 'purple' : 'blue'}
<StatusBadge text={typeLabel} variant={typeVariant} />
{/snippet}
diff --git a/tests/spec/dashboard-system-stats.spec.ts b/tests/spec/dashboard-system-stats.spec.ts
index c37b3561e..99b3af6e6 100644
--- a/tests/spec/dashboard-system-stats.spec.ts
+++ b/tests/spec/dashboard-system-stats.spec.ts
@@ -145,7 +145,7 @@ test.describe('Dashboard system stats websocket', () => {
await page.waitForLoadState('load');
await expect(page.getByRole('heading', { name: 'Environment Board' })).toBeVisible();
- await expect.poll(() => requestPaths).toContain('/api/environments/0/dashboard');
+ await expect.poll(() => requestPaths).toContain('/api/dashboard/stream');
expect(
countMatchingRequests(requestPaths, /\/api\/environments\/[^/]+\/system\/docker\/info$/)
diff --git a/types/dashboard/dashboard.go b/types/dashboard/dashboard.go
index a8f900aa9..99328ad42 100644
--- a/types/dashboard/dashboard.go
+++ b/types/dashboard/dashboard.go
@@ -1,6 +1,8 @@
package dashboard
import (
+ "time"
+
"github.com/getarcaneapp/arcane/types/v2/base"
containertypes "github.com/getarcaneapp/arcane/types/v2/container"
imagetypes "github.com/getarcaneapp/arcane/types/v2/image"
@@ -120,3 +122,17 @@ type Snapshot struct {
// Required: false
VersionInfo *versiontypes.Info `json:"versionInfo,omitempty"`
}
+
+const (
+ StreamErrorCodeAgentIncompatible = "agent_incompatible"
+ StreamErrorCodeUnreachable = "unreachable"
+)
+
+type StreamEvent struct {
+ Type string `json:"type"`
+ EnvironmentID string `json:"environmentId,omitempty"`
+ Snapshot *Snapshot `json:"snapshot,omitempty"`
+ Error string `json:"error,omitempty"`
+ ErrorCode string `json:"errorCode,omitempty"`
+ Timestamp time.Time `json:"timestamp"`
+}
diff --git a/types/environment/environment.go b/types/environment/environment.go
index 3b403faaa..82601a19b 100644
--- a/types/environment/environment.go
+++ b/types/environment/environment.go
@@ -151,6 +151,13 @@ type Environment struct {
// Required: false
EdgeTransport *string `json:"edgeTransport,omitempty"`
+ // LastEdgeTransport is the most recently used tunnel transport, persisted
+ // so the transport stays known while the tunnel is down or the agent is
+ // poll-only. Values are "grpc" or "websocket".
+ //
+ // Required: false
+ LastEdgeTransport *string `json:"lastEdgeTransport,omitempty"`
+
// EdgeSecurityMode indicates how the current edge tunnel authenticated.
// Values include "token" and "mtls".
//