| 9 | | "notRunning"; |
| 10 | |
| 11 | export function getWorkspaceActivityStatus( |
| 12 | workspace: Workspace, |
| 13 | ): WorkspaceActivityStatus { |
| 14 | const builtAt = dayjs(workspace.latest_build.created_at); |
| 15 | const usedAt = dayjs(workspace.last_used_at); |
| 16 | const now = dayjs(); |
| 17 | |
| 18 | if (workspace.latest_build.status !== "running") { |
| 19 | return "notRunning"; |
| 20 | } |
| 21 | |
| 22 | // This needs to compare to `usedAt` instead of `now`, because the "grace period" for |
| 23 | // marking a workspace as "Connected" is a lot longer. If you compared `builtAt` to `now`, |
| 24 | // you could end up switching from "Ready" to "Connected" without ever actually connecting. |
| 25 | const isBuiltRecently = builtAt.isAfter(usedAt.subtract(1, "second")); |
| 26 | // By default, agents report connection stats every 30 seconds, so 2 minutes should be |
| 27 | // plenty. Disconnection will be reflected relatively-quickly |
| 28 | const isUsedRecently = usedAt.isAfter(now.subtract(2, "minute")); |
| 29 | |
| 30 | // If the build is still "fresh", it'll be a while before the `last_used_at` gets bumped in |
| 31 | // a significant way by the agent, so just label it as ready instead of connected. |
| 32 | // Wait until `last_used_at` is after the time that the build finished, _and_ still |
| 33 | // make sure to check that it's recent, so that we don't show "Ready" indefinitely. |
| 34 | if (isUsedRecently && isBuiltRecently && workspace.health.healthy) { |
| 35 | return "ready"; |
| 36 | } |
| 37 | |
| 38 | if (isUsedRecently) { |
| 39 | return "connected"; |
| 40 | } |
| 41 | |
| 42 | // TODO: It'd be nice if we could differentiate between "connected but inactive" and |
| 43 | // "not connected", but that will require some relatively substantial backend work. |
| 44 | return "inactive"; |
| 45 | } |