Files
kandev/apps/backend/internal/gateway/websocket/client.go
T
João Salavisa c3d235b83b fix(auth): close per-user session isolation gaps (service, WS, orchestrator) (#1939)
* fix(auth): scope session-keyed reads and mutations to the workspace owner

Session-keyed service entry points did not apply per-user scoping, so
knowing another user's session or task ID was enough to reach it:

- GetTaskSession, ListTaskSessions, GetPrimarySession returned rows for
  any ID. These feed GET /task-sessions/:id and GET /tasks/:id/sessions,
  whose DTO carries session Metadata, the host worktree path, the branch,
  and container/executor IDs.
- DismissLastAgentError mutated any session.
- ApproveSession approved a workflow review step on any session, which
  advances the task's workflow — the highest-impact of the set.

Authorize via authorizeTaskID off the row already read, rather than
AuthorizeSessionAccess, which would re-read the session on what is a hot
path. Internal identity-less callers (pollers, event bus, office
schedulers, office agent JWTs) and the synthetic identity used while auth
is disabled stay unscoped, and unowned pre-auth rows stay visible.

Batch helpers that take ID lists are deliberately left alone: their
callers derive IDs from an already-authorized task list, so per-ID checks
would add N queries to list views for no gain. Recorded in AGENTS.md.

Also route httpApproveSession through handleNotFound so a denial answers
404 like every other session route instead of a 500 that would confirm
the session exists.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(auth): scope the session-keyed paths that bypass the task service

An adversarial sweep of the previous commit found session-keyed surfaces
reachable with a caller-supplied ID and no ownership check. They bypass
the task service, so scoping its methods did not cover them:

- POST /task-sessions/:id/{set-mode,set-model,set-config-option,
  authenticate} and .../processes/:processId/stop resolve their execution
  with a bare in-memory lookup, which skips the GetOrEnsure* chokepoint
  where the lifecycle per-user check runs. A non-owner could switch
  another user's model or mode, re-authenticate their agent, or kill
  their process. Guarded by a shared denySessionAccess helper.
- The orchestrator reads sessions through its own repo handle, so
  GetTaskSessionStatus and CheckSessionPR inherited nothing from the task
  service. CheckSessionPR also installs a PR watch as a side effect.
  Added a SetSessionAccessChecker hook mirroring the lifecycle manager's,
  wired to taskSvc.AuthorizeSessionAccess. The check runs before
  CheckSessionPR's unconfigured-GitHub early return so it applies
  regardless of setup, and denials reuse the "session not found" shape so
  they cannot be told apart from a missing session.
- GetMessage had no scoping while ListMessages beside it did, so a
  caller holding another user's (session_id, message_id) pair could read
  their shell output.

This does NOT close the whole surface. A second sweep found the
orchestrator's session-mutating WS actions (session.stop/delete/rename/
set_primary/set_plan_mode/reset_context/recover/launch/ensure,
agent.cancel, permission.respond) and agent.stdin / agent.resize also
unscoped — agent.stdin writes arbitrary input into another user's agent
process. Those touch live session lifecycle and need their own change;
recorded in AGENTS.md so the gap is not mistaken for covered.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(auth): scope every session-keyed WS action, plus a gateway backstop

Completes the sweep. Dispatched WS actions were left to authorize
themselves at the service layer, and a dozen never did — a caller with a
guessed session ID could stop, delete, rename, relaunch or reset another
user's live agent session, cancel their in-flight turn, answer their
permission prompts, or write arbitrary bytes into their agent process.

Two layers, deliberately both:

1. Gateway backstop. Client.authorizeAction checks any dispatched payload
   carrying task_id or session_id against the client's identity before
   dispatch. Per-method opt-in across ~74 actions in four packages had
   been missed repeatedly; this makes a newly added action scoped by
   default. Verified safe to apply generically: session_id means a task
   session everywhere, and user-shell/terminal actions key off task_id /
   task_environment_id, so nothing is misread.

2. Explicit guards, for defense in depth and for non-WS callers:
   - orchestrator: StopSession, DeleteSession, SetPrimarySession,
     RenameSession, ResetAgentContext, CancelAgent, RespondToPermission,
     SetSessionPlanModeByID, RecoverSession, LaunchSession, EnsureSession,
     CancelTransientRetry. Added SetTaskAccessChecker for the task-keyed
     ones. LaunchSession guards every intent at the single funnel;
     SessionID is empty on create, so the task check carries that case.
   - agent.stdin / agent.resize now call lifecycleMgr.CheckSessionAccess,
     the helper already documented for bare-lookup handlers.

Guards go first in each method, before any repo/executor use.
TestSessionKeyedEntryPointsGuardBeforeDependencies runs all twelve with
nil dependencies and fails on a panic if one is placed too late.

Denials are indistinguishable from a missing resource: WS returns
not-found, CancelTransientRetry reports "nothing cancelled", and
GetTaskSessionStatus reuses its "session not found" shape.

Unwired checkers stay permissive throughout, so identity-less internal
callers (schedulers, event bus, workflow engine) and pre-auth single-user
instances are unaffected — pinned per entry point.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(auth): scope environment-keyed user-shell actions

Third sweep finding, in surface the previous commit's own comment claimed
was covered. The user-shell actions key off task_environment_id and treat
task_id as optional, so a task_id-only backstop missed them:
user_shell.stop with an empty task_id and a foreign task_environment_id
fell through to the legacy runner path and tore down another user's
terminal PTY. That path never reaches
GetOrEnsureExecutionForEnvironment, where the environment check normally
runs, so neither layer caught it.

- Gateway backstop now also reads task_environment_id, gated by a new
  AuthPolicy.ActionEnvironment hook wired to
  taskSvc.AuthorizeEnvironmentAccess. This covers all three
  environment-keyed actions generically, not just the reported one.
- wsUserShellStop guards explicitly via a new
  lifecycleMgr.CheckEnvironmentAccess, mirroring CheckSessionAccess, so
  the fallback is safe independent of the gateway.

Corrected the comment that wrongly asserted task_environment_id was
already covered, and recorded in AGENTS.md both the exact field names the
backstop reads and why a permissive type on one of them would silently
opt out.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(auth): authorize both IDs on task+session entry points

Review finding (P1). Entry points taking both a task and a session ID
only checked the session, so a caller could satisfy that check with one
of their own sessions while pointing taskID at another user's task:

- CheckSessionPR then used the unchecked taskID for GetTaskPR,
  resolveTaskRepo, resolvePrimaryTaskRepositoryID and EnsurePRWatch —
  cross-workspace PR disclosure plus a PR-watch write.
- CancelTransientRetry handed it to handleRecoverableFailure, which
  writes against that task.

Both now use a new authorizeTaskSessionPair, which authorizes each ID and
additionally requires the pair to be consistent, so the two arguments
cannot describe different tasks. GetTaskSessionStatus already validated
the pair after loading the session and is unchanged.

The consistency half is skipped when the session cannot be loaded: both
IDs are authorized by then, so a mismatch is a caller bug rather than a
cross-user leak, and failing there would change behavior for
identity-less internal callers.

Recorded the rule in AGENTS.md — a two-ID entry point must never use
authorizeSession alone.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(auth): scope AttachWorkspaceSources

Found while rebasing onto main. POST /tasks/:id/workspace-sources and the
add_workspace_sources_kandev MCP tool landed on main during this PR's
review with no ownership check, so a caller could attach repositories and
folders to another user's task and have them materialized into that
task's workspace.

Same class as the rest of this PR, so fixed here rather than left for a
follow-up. The WS dispatch backstop added earlier already covered the
browser path (the payload carries task_id); this closes the HTTP route
and the MCP tool, which do not go through it.

ErrTaskNotFound already maps to 404 in workspaceSourceHTTPStatus, so the
denial surfaces correctly without touching the handler.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(auth): map denied shell-output reads to 404

Review finding. GetMessage became per-user scoped earlier in this PR, so
a denial now arrives as ErrTaskNotFound. httpGetShellOutput only mapped
sql.ErrNoRows to 404, sending everything else to the 500 branch — so a
foreign message answered 500 while a missing one answered 404, which is
an existence signal and inconsistent with the 404-everywhere rule the
other session routes follow.

Kept the sql.ErrNoRows branch explicit rather than replacing it outright:
isNotFound classifies typed sentinels and the "not found" substring, and
"sql: no rows in result set" matches neither, so routing that case
through handleNotFound alone regressed the missing-message response to
500 (caught by TestHTTPShellOutputSnapshot).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(auth): make the shell-output scoping test actually exercise the guard

Both reviewers caught that TestHTTPGetShellOutputDeniesForeignMessageWith404
was vacuous. httpGetShellOutput has a second 404 gate after the service
call — `if !ok || message.TaskSessionID != c.Param("id")` — and
ExtractShellExecOutput returns ok=false for nil metadata. The fixture had
none, so the route answered 404 through that gate whether or not scoping
denied the read.

Confirmed by mutation rather than inspection: with the authorization
removed from GetMessage the test still passed. With valid shell-output
metadata in the fixture it returns 200 and the victim's stdout, so the
test fails as intended; restoring the guard makes it pass again.

Also mutation-tested the sibling denial tests, since this is a defect
class rather than a one-off:
- TestHTTPGetTaskSessionDeniesForeignSessionWith404 — sound, returns 200
  with the session DTO when the guard is removed.
- TestProcessRoutesDenyForeignSession — catches removal, though via the
  documented nil-lifecycleMgr panic rather than a status assertion.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(auth): add an in-test witness to the shell-output scoping test

Review suggestion. The fixture fix made the test exercise the guard, but
nothing in the test proved the 404 came from authorization rather than the
route's post-service `!ok` gate — which is exactly how it went vacuous in
the first place. The evidence lived in a commit message describing a
manual mutation run, not in the test.

Now asserts both directions, matching the approve-route test: the
non-owner gets 404, and the owner does NOT. If the assertion ever stops
proving authorization, the owner case fails and says so.

Re-verified by mutation: removing the guard from GetMessage fails the test
with 200 and the victim's stdout; restoring it passes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-26 14:09:52 +01:00

640 lines
20 KiB
Go

package websocket
import (
"context"
"encoding/json"
"strings"
"sync"
"time"
"github.com/gorilla/websocket"
"github.com/kandev/kandev/internal/auth/authn"
"github.com/kandev/kandev/internal/common/logger"
"github.com/kandev/kandev/internal/user/store"
ws "github.com/kandev/kandev/pkg/websocket"
"go.uber.org/zap"
)
const (
// Time allowed to write a message to the peer
writeWait = 10 * time.Second
// Time allowed to read the next pong message from the peer
pongWait = 60 * time.Second
// Send pings to peer with this period (must be less than pongWait)
pingPeriod = (pongWait * 9) / 10
// Maximum message size allowed from peer
// Increased to support image attachments (base64 encoded images are ~33% larger)
maxMessageSize = 32 * 1024 * 1024 // 32MB
)
// Client represents a single WebSocket connection
type Client struct {
ID string
// identity is the authenticated caller behind this connection. Zero for
// anonymous connections (auth disabled and no synthetic identity set by
// the HTTP middleware — e.g. direct hub tests); synthetic in disabled
// mode; a real user when auth is enabled.
identity authn.Identity
conn *websocket.Conn
hub *Hub
send chan []byte
subscriptions map[string]bool // Task IDs this client is subscribed to
sessionSubscriptions map[string]bool // Session IDs this client is subscribed to
sessionFocus map[string]bool // Session IDs this client has focused (a strict subset of subscriptions, conceptually — see hub_session_mode.go)
userSubscriptions map[string]bool // User IDs this client is subscribed to
runSubscriptions map[string]bool // Office run IDs this client is subscribed to (for run.event.appended)
systemMetricsSubscribed bool
mu sync.RWMutex
closed bool
logger *logger.Logger
}
// NewClient creates a new WebSocket client
func NewClient(id string, identity authn.Identity, conn *websocket.Conn, hub *Hub, log *logger.Logger) *Client {
return &Client{
ID: id,
identity: identity,
conn: conn,
hub: hub,
send: make(chan []byte, 256),
subscriptions: make(map[string]bool),
sessionSubscriptions: make(map[string]bool),
sessionFocus: make(map[string]bool),
userSubscriptions: make(map[string]bool),
runSubscriptions: make(map[string]bool),
logger: log.WithFields(zap.String("client_id", id)),
}
}
// dispatchContext returns the hub's lifetime context carrying this client's
// identity, so dispatched RPC handlers (workspace.list, task CRUD, …) and
// subscription checks apply the same per-user scoping as HTTP requests.
func (c *Client) dispatchContext() context.Context {
ctx := c.hub.DispatchContext()
if c.identity.UserID != "" {
ctx = authn.WithIdentity(ctx, c.identity)
}
return ctx
}
// ReadPump pumps messages from the WebSocket connection to the hub.
//
// The ctx argument is retained for API stability but is not consulted by the
// pump itself — Gorilla's ReadMessage blocks on the conn only, so teardown
// happens via the conn close path (driven by client disconnect, server
// shutdown closing all conns, or pong timeout). Dispatched handlers use the
// hub's lifetime context instead; see handleMessage.
func (c *Client) ReadPump(_ context.Context) {
defer func() {
c.hub.Unregister(c)
if err := c.conn.Close(); err != nil {
c.logger.Debug("failed to close websocket connection", zap.Error(err))
}
}()
c.conn.SetReadLimit(maxMessageSize)
if err := c.conn.SetReadDeadline(time.Now().Add(pongWait)); err != nil {
c.logger.Debug("failed to set read deadline", zap.Error(err))
}
c.conn.SetPongHandler(func(string) error {
return c.conn.SetReadDeadline(time.Now().Add(pongWait))
})
for {
_, message, err := c.conn.ReadMessage()
if err != nil {
// CloseGoingAway (1001): Client navigating away
// CloseNoStatusReceived (1005): Client closed without status (normal browser close)
// CloseAbnormalClosure (1006): Abnormal close (network drop)
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseNoStatusReceived, websocket.CloseAbnormalClosure) {
c.logger.Error("WebSocket read error", zap.Error(err))
}
break
}
// Parse the message
var msg ws.Message
if err := json.Unmarshal(message, &msg); err != nil {
c.logger.Error("Failed to parse message", zap.Error(err))
c.sendError("", "", ws.ErrorCodeBadRequest, "Invalid message format", nil)
continue
}
// Process the message in a goroutine to avoid blocking the read pump
// This allows concurrent message handling so long-running handlers
// (like orchestrator.prompt) don't block other requests (like workspace.tree.get)
go c.handleMessage(&msg)
}
}
// handleMessage processes an incoming message.
//
// Intentionally does NOT take the connection context. Dispatched handlers run
// under the hub's lifetime context so a mid-flight client disconnect doesn't
// abort in-progress side effects (see the comment on Dispatch below).
func (c *Client) handleMessage(msg *ws.Message) {
c.logger.Debug("Received message",
zap.String("action", msg.Action),
zap.String("id", msg.ID))
if strings.HasPrefix(msg.Action, "mcp.") {
c.sendError(msg.ID, msg.Action, ws.ErrorCodeForbidden,
"MCP actions are not available over the raw WebSocket", nil)
return
}
// Handle subscription actions specially (they need access to the client)
switch msg.Action {
case ws.ActionTaskSubscribe:
c.handleSubscribe(msg)
return
case ws.ActionTaskUnsubscribe:
c.handleUnsubscribe(msg)
return
case ws.ActionSessionSubscribe:
c.handleSessionSubscribe(msg)
return
case ws.ActionSessionUnsubscribe:
c.handleSessionUnsubscribe(msg)
return
case ws.ActionSessionFocus:
c.handleSessionFocus(msg)
return
case ws.ActionSessionUnfocus:
c.handleSessionUnfocus(msg)
return
case ws.ActionUserSubscribe:
c.handleUserSubscribe(msg)
return
case ws.ActionUserUnsubscribe:
c.handleUserUnsubscribe(msg)
return
case ws.ActionRunSubscribe:
c.handleRunSubscribe(msg)
return
case ws.ActionRunUnsubscribe:
c.handleRunUnsubscribe(msg)
return
case ws.ActionSystemMetricsSubscribe:
c.handleSystemMetricsSubscribe(msg)
return
case ws.ActionSystemMetricsUnsubscribe:
c.handleSystemMetricsUnsubscribe(msg)
return
}
// Dispatch to handler using the hub's lifetime context, not the per-
// connection one. The connection ctx is cancelled when the client
// disconnects (page reload, nav, network drop). Using it here would
// SIGKILL any exec.CommandContext subprocesses the handler spawned
// (e.g. `gh pr`, `git`, agentctl HTTP requests) and abort
// side-effecting work like session.launch mid-flight. We can't deliver
// the response either way once the connection is gone, but the
// handler's work should run to completion so it doesn't leave partial
// state behind. The dispatch ctx still cancels on server shutdown.
dispatchCtx := c.dispatchContext()
// Per-user scoping backstop: refuse before the handler runs if the payload
// names a task or session this client may not touch. See dispatch_scope.go
// for why this lives here and not only in each handler.
if err := c.authorizeAction(dispatchCtx, msg.Payload); err != nil {
c.logger.Debug("denied out-of-scope action",
zap.String("action", msg.Action),
zap.String("user_id", c.identity.UserID),
zap.Error(err))
c.sendError(msg.ID, msg.Action, ws.ErrorCodeNotFound, "not found", nil)
return
}
response, err := c.hub.dispatcher.Dispatch(dispatchCtx, msg)
if err != nil {
c.logger.Error("Handler error",
zap.String("action", msg.Action),
zap.Error(err))
c.sendError(msg.ID, msg.Action, ws.ErrorCodeInternalError, err.Error(), nil)
return
}
if response != nil {
c.sendMessage(response)
}
}
// SubscribeRequest is the payload for task.subscribe
type SubscribeRequest struct {
TaskID string `json:"task_id"`
}
// handleSubscribe handles task.subscribe action
func (c *Client) handleSubscribe(msg *ws.Message) {
var req SubscribeRequest
if err := msg.ParsePayload(&req); err != nil {
c.sendError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil)
return
}
if req.TaskID == "" {
c.sendError(msg.ID, msg.Action, ws.ErrorCodeValidation, "task_id is required", nil)
return
}
// Per-user scoping: a client may only observe tasks in its own workspaces.
if check := c.hub.authPolicy.Subscriptions.Task; check != nil {
if err := check(c.dispatchContext(), req.TaskID); err != nil {
c.sendError(msg.ID, msg.Action, ws.ErrorCodeForbidden, "cannot subscribe to this task", nil)
return
}
}
c.hub.SubscribeToTask(c, req.TaskID)
// Send success response
resp, _ := ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{
"success": true,
"task_id": req.TaskID,
})
c.sendMessage(resp)
}
type UserSubscribeRequest struct {
UserID string `json:"user_id,omitempty"`
}
type SessionSubscribeRequest struct {
SessionID string `json:"session_id"`
}
// ownUserTopic resolves the user-topic this client may subscribe to: its own
// authenticated user, or the pre-auth default user for anonymous/synthetic
// connections (today's single-user behavior).
func (c *Client) ownUserTopic() string {
if c.identity.UserID != "" && !c.identity.Synthetic {
return c.identity.UserID
}
return store.DefaultUserID
}
func (c *Client) handleUserSubscribe(msg *ws.Message) {
var req UserSubscribeRequest
if err := msg.ParsePayload(&req); err != nil {
c.sendError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil)
return
}
userID := req.UserID
if userID == "" {
userID = c.ownUserTopic()
}
if userID != c.ownUserTopic() {
c.sendError(msg.ID, msg.Action, ws.ErrorCodeForbidden, "cannot subscribe to another user", nil)
return
}
c.hub.SubscribeToUser(c, userID)
resp, _ := ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{
"success": true,
"user_id": userID,
})
c.sendMessage(resp)
}
func (c *Client) handleSessionSubscribe(msg *ws.Message) {
var req SessionSubscribeRequest
if err := msg.ParsePayload(&req); err != nil {
c.sendError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil)
return
}
if req.SessionID == "" {
c.sendError(msg.ID, msg.Action, ws.ErrorCodeValidation, "session_id is required", nil)
return
}
if !c.maySubscribeSession(msg, req.SessionID) {
return
}
c.hub.SubscribeToSession(c, req.SessionID)
resp, _ := ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{
"success": true,
"session_id": req.SessionID,
})
c.sendMessage(resp)
// Send initial session data (e.g., git status) if available
c.sendSessionData(req.SessionID)
}
// maySubscribeSession applies the per-user session scoping check, emitting the
// forbidden error itself. Returns true when the subscription may proceed.
func (c *Client) maySubscribeSession(msg *ws.Message, sessionID string) bool {
check := c.hub.authPolicy.Subscriptions.Session
if check == nil {
return true
}
if err := check(c.dispatchContext(), sessionID); err != nil {
c.sendError(msg.ID, msg.Action, ws.ErrorCodeForbidden, "cannot subscribe to this session", nil)
return false
}
return true
}
func (c *Client) handleUserUnsubscribe(msg *ws.Message) {
var req UserSubscribeRequest
if err := msg.ParsePayload(&req); err != nil {
c.sendError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil)
return
}
userID := req.UserID
if userID == "" {
userID = c.ownUserTopic()
}
if userID != c.ownUserTopic() {
c.sendError(msg.ID, msg.Action, ws.ErrorCodeForbidden, "cannot unsubscribe from another user", nil)
return
}
c.hub.UnsubscribeFromUser(c, userID)
resp, _ := ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{
"success": true,
"user_id": userID,
})
c.sendMessage(resp)
}
// sendSessionData sends initial session data (e.g., git status) to the client
func (c *Client) sendSessionData(sessionID string) {
ctx := context.Background()
data, err := c.hub.GetSessionData(ctx, sessionID)
if err != nil {
c.logger.Error("Failed to get session data",
zap.String("session_id", sessionID),
zap.Error(err))
return
}
if len(data) == 0 {
return
}
c.logger.Debug("Sending session data",
zap.String("session_id", sessionID),
zap.Int("count", len(data)))
// Send each piece of session data as a notification
for _, msg := range data {
c.sendMessage(msg)
}
}
// handleUnsubscribe handles task.unsubscribe action
func (c *Client) handleUnsubscribe(msg *ws.Message) {
var req SubscribeRequest
if err := msg.ParsePayload(&req); err != nil {
c.sendError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil)
return
}
if req.TaskID == "" {
c.sendError(msg.ID, msg.Action, ws.ErrorCodeValidation, "task_id is required", nil)
return
}
c.hub.UnsubscribeFromTask(c, req.TaskID)
resp, _ := ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{
"success": true,
"task_id": req.TaskID,
})
c.sendMessage(resp)
}
// RunSubscribeRequest is the payload for run.subscribe / run.unsubscribe.
type RunSubscribeRequest struct {
RunID string `json:"run_id"`
}
// handleRunSubscribe handles run.subscribe action — registers this
// client on the per-run topic so it receives run.event.appended
// notifications. Clients fetch the snapshot via REST and only need
// the diff stream from this point forward; we deliberately replay no
// state on subscribe.
func (c *Client) handleRunSubscribe(msg *ws.Message) {
var req RunSubscribeRequest
if err := msg.ParsePayload(&req); err != nil {
c.sendError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil)
return
}
if req.RunID == "" {
c.sendError(msg.ID, msg.Action, ws.ErrorCodeValidation, "run_id is required", nil)
return
}
c.hub.SubscribeToRun(c, req.RunID)
resp, _ := ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{
"success": true,
"run_id": req.RunID,
})
c.sendMessage(resp)
}
// handleRunUnsubscribe handles run.unsubscribe action.
func (c *Client) handleRunUnsubscribe(msg *ws.Message) {
var req RunSubscribeRequest
if err := msg.ParsePayload(&req); err != nil {
c.sendError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil)
return
}
if req.RunID == "" {
c.sendError(msg.ID, msg.Action, ws.ErrorCodeValidation, "run_id is required", nil)
return
}
c.hub.UnsubscribeFromRun(c, req.RunID)
resp, _ := ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{
"success": true,
"run_id": req.RunID,
})
c.sendMessage(resp)
}
func (c *Client) handleSystemMetricsSubscribe(msg *ws.Message) {
c.hub.SubscribeToSystemMetrics(c)
resp, _ := ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{
"success": true,
})
c.sendMessage(resp)
}
func (c *Client) handleSystemMetricsUnsubscribe(msg *ws.Message) {
c.hub.UnsubscribeFromSystemMetrics(c)
resp, _ := ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{
"success": true,
})
c.sendMessage(resp)
}
// handleSessionUnsubscribe handles session.unsubscribe action
func (c *Client) handleSessionUnsubscribe(msg *ws.Message) {
var req SessionSubscribeRequest
if err := msg.ParsePayload(&req); err != nil {
c.sendError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil)
return
}
if req.SessionID == "" {
c.sendError(msg.ID, msg.Action, ws.ErrorCodeValidation, "session_id is required", nil)
return
}
c.hub.UnsubscribeFromSession(c, req.SessionID)
resp, _ := ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{
"success": true,
"session_id": req.SessionID,
})
c.sendMessage(resp)
}
// handleSessionFocus handles session.focus — marks the session as actively
// viewed by this client, lifting backend polling to fast mode for the workspace.
//
// Also pushes a fresh session data snapshot (git status, etc.) because the
// session.subscribe frame is often absorbed by the sidebar's bulk subscribe
// (ref-counted on the client) before the task-page hook can ask for it — so
// without this, switching tasks leaves the Changes panel showing stale/empty
// state until the next poll broadcast arrives.
func (c *Client) handleSessionFocus(msg *ws.Message) {
var req SessionSubscribeRequest
if err := msg.ParsePayload(&req); err != nil {
c.sendError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil)
return
}
if req.SessionID == "" {
c.sendError(msg.ID, msg.Action, ws.ErrorCodeValidation, "session_id is required", nil)
return
}
if !c.maySubscribeSession(msg, req.SessionID) {
return
}
c.hub.FocusSession(c, req.SessionID)
resp, _ := ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{
"success": true,
"session_id": req.SessionID,
})
c.sendMessage(resp)
c.sendSessionData(req.SessionID)
}
// handleSessionUnfocus handles session.unfocus — releases the focus mark for
// this client. The session falls back to slow mode (still subscribed) or
// paused (no subscribers), with a debounce to absorb tab churn.
func (c *Client) handleSessionUnfocus(msg *ws.Message) {
var req SessionSubscribeRequest
if err := msg.ParsePayload(&req); err != nil {
c.sendError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil)
return
}
if req.SessionID == "" {
c.sendError(msg.ID, msg.Action, ws.ErrorCodeValidation, "session_id is required", nil)
return
}
c.hub.UnfocusSession(c, req.SessionID)
resp, _ := ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{
"success": true,
"session_id": req.SessionID,
})
c.sendMessage(resp)
}
// sendMessage sends a message to the client
func (c *Client) sendMessage(msg *ws.Message) {
data, err := json.Marshal(msg)
if err != nil {
c.logger.Error("Failed to marshal message", zap.Error(err))
return
}
c.sendBytes(data)
}
func (c *Client) sendBytes(data []byte) bool {
c.mu.Lock()
defer c.mu.Unlock()
if c.closed {
return false
}
select {
case c.send <- data:
return true
default:
c.logger.Warn("Client send buffer full")
return false
}
}
// sendError sends an error message to the client
func (c *Client) sendError(id, action, code, message string, details map[string]interface{}) {
msg, err := ws.NewError(id, action, code, message, details)
if err != nil {
c.logger.Error("Failed to create error message", zap.Error(err))
return
}
c.sendMessage(msg)
}
func (c *Client) closeSend() {
c.mu.Lock()
defer c.mu.Unlock()
if c.closed {
return
}
c.closed = true
close(c.send)
}
// WritePump pumps messages from the hub to the WebSocket connection
func (c *Client) WritePump() {
ticker := time.NewTicker(pingPeriod)
defer func() {
ticker.Stop()
if err := c.conn.Close(); err != nil {
c.logger.Debug("failed to close websocket connection", zap.Error(err))
}
}()
for {
select {
case message, ok := <-c.send:
if err := c.conn.SetWriteDeadline(time.Now().Add(writeWait)); err != nil {
c.logger.Debug("failed to set write deadline", zap.Error(err))
}
if !ok {
// Hub closed the channel
if err := c.conn.WriteMessage(websocket.CloseMessage, []byte{}); err != nil {
c.logger.Debug("failed to write close message", zap.Error(err))
}
return
}
// Send each message in its own WebSocket frame
// (previously batched with newlines, but clients expect one JSON object per frame)
if err := c.conn.WriteMessage(websocket.TextMessage, message); err != nil {
c.logger.Debug("failed to write websocket message", zap.Error(err))
return
}
case <-ticker.C:
if err := c.conn.SetWriteDeadline(time.Now().Add(writeWait)); err != nil {
c.logger.Debug("failed to set write deadline", zap.Error(err))
}
if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
return
}
}
}
}