@@ -815,10 +815,13 @@ func (api *API) workspaceAgentListeningPorts(rw http.ResponseWriter, r *http.Req
815815// @Router /workspaceagents/{workspaceagent}/containers/watch [get]
816816func (api * API )watchWorkspaceAgentContainers (rw http.ResponseWriter ,r * http.Request ) {
817817var (
818- ctx = r .Context ()
819818workspaceAgent = httpmw .WorkspaceAgentParam (r )
819+ logger = api .Logger .Named ("agent_container_watcher" ).With (slog .F ("agent_id" ,workspaceAgent .ID ))
820820)
821821
822+ ctx ,cancelCtx := context .WithCancel (r .Context ())
823+ defer cancelCtx ()
824+
822825// If the agent is unreachable, the request will hang. Assume that if we
823826// don't get a response after 30s that the agent is unreachable.
824827dialCtx ,cancel := context .WithTimeout (ctx ,30 * time .Second )
@@ -857,8 +860,7 @@ func (api *API) watchWorkspaceAgentContainers(rw http.ResponseWriter, r *http.Re
857860}
858861defer release ()
859862
860- watcherLogger := api .Logger .Named ("agent_container_watcher" ).With (slog .F ("agent_id" ,workspaceAgent .ID ))
861- containersCh ,closer ,err := agentConn .WatchContainers (ctx ,watcherLogger )
863+ containersCh ,closer ,err := agentConn .WatchContainers (ctx ,logger )
862864if err != nil {
863865httpapi .Write (ctx ,rw ,http .StatusInternalServerError , codersdk.Response {
864866Message :"Internal error watching agent's containers." ,
@@ -881,11 +883,11 @@ func (api *API) watchWorkspaceAgentContainers(rw http.ResponseWriter, r *http.Re
881883// close frames.
882884_ = conn .CloseRead (context .Background ())
883885
886+ go httpapi .HeartbeatClose (ctx ,logger ,cancelCtx ,conn )
887+
884888ctx ,wsNetConn := codersdk .WebsocketNetConn (ctx ,conn ,websocket .MessageText )
885889defer wsNetConn .Close ()
886890
887- go httpapi .Heartbeat (ctx ,conn )
888-
889891encoder := json .NewEncoder (wsNetConn )
890892
891893for {