Rate this page:

Control Worker Activities using Worker.js: Add an Agent UI to our Project

Let's get started on our agent UI. Assuming you've followed the conventions so far in this tutorial, the UI we create will be accessible using your web browser at:

http://localhost:8080/agent.cshtml?WorkerSid=WK01234012340123401234 (substitute your Alice's WorkerSid)

We pass the WorkerSid in the URL to avoid implementing complex user management in our demo. In reality, you are likely to store a user's WorkerSid in your database alongside other User attributes.

Now create a CSHTML file that will be rendered when the URL is requested:


  @using System;
  @using System.Collections.Generic;
  @using Twilio;
  @using Twilio.Http;
  @using Twilio.Jwt.Taskrouter;

     class PolicyUrlUtils
        const string taskRouterBaseUrl = "";
        const string taskRouterVersion = "v1";

        readonly string _workspaceSid;
        readonly string _workerSid;

        public PolicyUrlUtils(string workspaceSid, string workerSid)
            _workspaceSid = workspaceSid;
            _workerSid = workerSid;

        public string AllTasks => $"{Workspace}/Tasks/**";

        public string Worker => $"{Workspace}/Workers/{_workerSid}";

        public string AllReservations => $"{Worker}/Reservations/**";

        public string Workspace =>

        public string Activities => $"{Workspace}/Activities";


        // put your Twilio API credentials here
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken = "your_auth_token";
        const string workspaceSid = "WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string workerSid = "WKXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

        var updateActivityFilter = new Dictionary<string, Policy.FilterRequirement>
            { "ActivitySid", Policy.FilterRequirement.Required }

        var urls = new PolicyUrlUtils(workspaceSid, workerSid);

        var allowActivityUpdates = new Policy(urls.Worker,
                                              postFilter: updateActivityFilter);
        var allowTasksUpdate = new Policy(urls.AllTasks, HttpMethod.Post);
        var allowReservationUpdate = new Policy(urls.AllReservations, HttpMethod.Post);
        var allowWorkerFetches = new Policy(urls.Worker, HttpMethod.Get);
        var allowTasksFetches = new Policy(urls.AllTasks, HttpMethod.Get );
        var allowReservationFetches = new Policy(urls.AllReservations, HttpMethod.Get);
        var allowActivityFetches = new Policy(urls.Activities, HttpMethod.Get);

        var policies = new List<Policy>


        var capability = new TaskRouterCapability(
            policies: policies); 

        var workerToken = capability.ToJwt();
  <!DOCTYPE html>
      <title>Customer Care - Voice Agent Screen</title>
      <link rel="stylesheet" href="//"/>
    <script src="" integrity="sha384-5fq+0qjayReAreRyHy38VpD3Gr9R2OYIzonwIkoGI4M9dhfKW6RWeRnZjfwSrpN8" crossorigin="anonymous"></script>
      <script type="text/javascript">
          /* Subscribe to a subset of the available TaskRouter.js events for a worker */
          function registerTaskRouterCallbacks() {
              worker.on('ready', function(worker) {
                  logger("Successfully registered as: " + worker.friendlyName)
                  logger("Current activity is: " + worker.activityName);

              worker.on('activity.update', function(worker) {
                  logger("Worker activity changed to: " + worker.activityName);

              worker.on("reservation.created", function(reservation) {
                  logger("You have been reserved to handle a call!");
                  logger("Call from: " + reservation.task.attributes.from);
                  logger("Selected language: " + reservation.task.attributes.selected_language);

              worker.on("reservation.accepted", function(reservation) {
                  logger("Reservation " + reservation.sid + " accepted!");

              worker.on("reservation.rejected", function(reservation) {
                  logger("Reservation " + reservation.sid + " rejected!");

              worker.on("reservation.timeout", function(reservation) {
                  logger("Reservation " + reservation.sid + " timed out!");

              worker.on("reservation.canceled", function(reservation) {
                  logger("Reservation " + reservation.sid + " canceled!");

          /* Hook up the agent Activity buttons to TaskRouter.js */

          function bindAgentActivityButtons() {
              // Fetch the full list of available Activities from TaskRouter. Store each
              // ActivitySid against the matching Friendly Name
              var activitySids = {};
              worker.activities.fetch(function(error, activityList) {
                  var activities =;
                  var i = activities.length;
                  while (i--) {
                      activitySids[activities[i].friendlyName] = activities[i].sid;

              /* For each button of class 'change-activity' in our Agent UI, look up the
               ActivitySid corresponding to the Friendly Name in the button’s next-activity
               data attribute. Use Worker.js to transition the agent to that ActivitySid
               when the button is clicked.*/
              var elements = document.getElementsByClassName('change-activity');
              var i = elements.length;
              while (i--) {
                  elements[i].onclick = function() {
                      var nextActivity = this.dataset.nextActivity;
                      var nextActivitySid = activitySids[nextActivity];

          /* Update the UI to reflect a change in Activity */

          function agentActivityChanged(activity) {

          function hideAgentActivities() {
              var elements = document.getElementsByClassName('agent-activity');
              var i = elements.length;
              while (i--) {
                  elements[i].style.display = 'none';

          function showAgentActivity(activity) {
              activity = activity.toLowerCase();
              var elements = document.getElementsByClassName(('agent-activity ' + activity));
              elements.item(0).style.display = 'block';

          /* Other stuff */

          function logger(message) {
              var log = document.getElementById('log');
              log.value += "\n> " + message;
              log.scrollTop = log.scrollHeight;

          window.onload = function() {
              // Initialize TaskRouter.js on page load using window.workerToken -
              // a Twilio Capability token that was set from rendering the template with agents endpoint
              window.worker = new Twilio.TaskRouter.Worker("@workerToken");

  <div class="content">
      <section class="agent-activity offline">
          <p class="activity">Offline</p>
          <button class="change-activity" data-next-activity="Idle">Go Available</button>
      <section class="agent-activity idle">
          <p class="activity"><span>Available</span></p>
          <button class="change-activity" data-next-activity="Offline">Go Offline</button>
      <section class="agent-activity reserved">
          <p class="activity">Reserved</p>
      <section class="agent-activity busy">
          <p class="activity">Busy</p>
      <section class="agent-activity wrapup">
          <p class="activity">Wrap-Up</p>
          <button class="change-activity" data-next-activity="Idle">Go Available</button>
          <button class="change-activity" data-next-activity="Offline">Go Offline</button>
      <section class="log">
        <textarea id="log" readonly="true"></textarea>

You'll notice that we included two external files:

  • taskrouter.min.js is the primary TaskRouter.js JavaScript file that communicates with TaskRouter's infrastructure on our behalf. You can use this URL to include Worker.js in your production application, but first check the reference documentation to ensure that you include the latest version number.
  • agent.css is a simple CSS file created for the purpose of this Quickstart. It saves us having to type out some simple pre-defined styles.

And that's it! Compile your Java class and start your server.

Open http://localhost:8080/agent.cshtml?WorkerSid=WK01234012340123401234 in your browser and you should see the screen below. If you make the same phone call as we made in Part 3, you should see Alice's Activity transition on screen as she is reserved and assigned to handle the Task.

If you see "Initializing..." and no progress, make sure that you have included the correct WorkerSid in the "WorkerSid" request parameter of the URL.

For more details, refer to the TaskRouter JavaScript SDK documentation.

Completed Agent UI

  • This simple PoC has been tested in the latest version of popular browsers, including IE 11. *

Rate this page:

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd by visiting Twilio's Stack Overflow Collective or browsing the Twilio tag on Stack Overflow.


        Thank you for your feedback!

        Please select the reason(s) for your feedback. The additional information you provide helps us improve our documentation:

        Sending your feedback...
        🎉 Thank you for your feedback!
        Something went wrong. Please try again.

        Thanks for your feedback!

        Refer us and get $10 in 3 simple steps!

        Step 1

        Get link

        Get a free personal referral link here

        Step 2

        Give $10

        Your user signs up and upgrade using link

        Step 3

        Get $10

        1,250 free SMSes
        OR 1,000 free voice mins
        OR 12,000 chats
        OR more