package webui import ( "context" "io" "net/http" "strings" "golang.org/x/net/websocket" "google.golang.org/grpc/status" "github.com/samcharles93/archie-core/internal/domain/org" ) // SandboxView follows a running task attempt's sandbox output, read-only. A // finished or unknown attempt is refused with a gRPC status whose message // states why. The implementation belongs to a process that owns containers; // the dashboard consumes it over a contract and never links one. Nil answers // 503. type SandboxView interface { OpenRun(ctx context.Context, orgID string, taskID, attempt int64) (io.ReadCloser, error) } // handleTaskSandbox streams a running attempt's sandbox output to a WebSocket. // Reading it is the same authority as reading the task's log, decided before // this handler runs. Input from the browser is discarded: a view has no stdin. func (s *Server) handleTaskSandbox(w http.ResponseWriter, r *http.Request) { if s.SandboxView == nil { http.Error(w, "sandbox view not configured", http.StatusServiceUnavailable) return } if !strings.EqualFold(r.Header.Get("Upgrade"), "websocket") { http.Error(w, "websocket upgrade required", http.StatusUpgradeRequired) return } t, attempt, ok := s.taskAttemptTarget(w, r) if !ok { return } // The refusal rides the socket as text, not as an HTTP status: a browser // WebSocket cannot read a failed upgrade's body, and the operator's only // honest account of why there is no view is the daemon's stated reason. //nolint:contextcheck // websocket.Handler has no context parameter; the handler derives its context from ws.Request() websocket.Handler(func(ws *websocket.Conn) { defer func() { _ = ws.Close() }() ctx, cancel := context.WithCancel(ws.Request().Context()) defer cancel() go func() { _, _ = io.Copy(io.Discard, ws); cancel() }() view, err := s.SandboxView.OpenRun(ctx, string(org.OrgFromContext(ws.Request().Context())), t.ID, int64(attempt)) if err != nil { s.logf("open sandbox view", "err", err, "task", t.ID, "attempt", attempt) _, _ = io.WriteString(ws, sandboxRefusal(err)) return } defer func() { _ = view.Close() }() stopClose := context.AfterFunc(ctx, func() { _ = view.Close() }) defer stopClose() ws.PayloadType = websocket.BinaryFrame if _, err := io.Copy(ws, view); err != nil && ctx.Err() == nil { _ = websocket.Message.Send(ws, sandboxRefusal(err)) } }).ServeHTTP(w, r) } // sandboxRefusal is the reason shown to the operator. func sandboxRefusal(err error) string { if st, ok := status.FromError(err); ok && st.Message() != "" { return st.Message() } return "the sandbox view is unavailable" }