Files
kandev/apps/backend/internal/gateway/websocket/terminal_sessions.go
T
João Salavisa c534aac355 refactor(backend): split terminal_handler.go into pumps/sessions/messages (#1056)
* refactor(backend): split terminal_handler.go into pumps/sessions/messages

terminal_handler.go was 1,380 lines (1.7x the 800-line cap). Split it into
four sibling files in the same package, by responsibility:

- terminal_handler.go (525 lines): HTTP upgrade, route dispatch, top-level
  handler entries, shell-label resolution.
- terminal_pumps.go (725 lines): wsWriter, bridgeBinaryWebSockets,
  runTerminalBridge / runUserShellBridge and all input/resize/PTY-setup
  helpers. Extracts replayBufferedOutput from setupPtyAccessCommon to keep
  nestif under threshold.
- terminal_sessions.go (133 lines): execution-readiness helpers
  (ensurePassthroughExecutionReady, waitForRemoteExecutionReadyWithTimeout,
  remoteExecutionWithClientReady, shouldUseWorkspaceShell) and related
  timeout constants.
- terminal_messages.go (53 lines): protocol primitives (ResizePayload,
  isResizeCommand, resizeCommandByte, stripTerminalResponses), with a
  top-of-file doc comment describing the binary wire protocol.

Backed off the "typed TerminalMessage envelope" half of the task: the
current protocol is binary, not JSON-enveloped (terminal I/O is raw PTY
bytes; the only JSON is ResizePayload, sent as a binary frame prefixed by
0x01). Wrapping PTY bytes in a JSON envelope would require base64 and
break xterm.js AttachAddon for every client — the task brief explicitly
authorizes shipping just the file split when the format would change.

Adds terminal_messages_test.go pinning the wire format: exact JSON output
of ResizePayload, the 0x01-prefix detection, and a full resize-frame
round-trip. These fail loudly on any accidental change to the struct tags
or prefix byte.

Pure relocation otherwise: no signature changes, no behavior changes, no
frontend impact.

* refactor(backend): simplify detectInputSubmission with bytes.ContainsAny

Addresses Claude bot's PR review on #1056: replace the manual loop +
flag pattern with bytes.ContainsAny(data, "\n\r"). Behavior identical
(detect CR or LF anywhere in the input). Also drops the now-redundant
"Check for Enter key (CR or LF)" comment.

* ci: retrigger CI to re-test known-flaky session-resume spec

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
2026-05-29 00:31:27 +01:00

134 lines
3.6 KiB
Go

package websocket
import (
"context"
"errors"
"fmt"
"time"
"go.uber.org/zap"
"github.com/kandev/kandev/internal/agent/runtime/lifecycle"
)
const (
passthroughReadyTimeout = 30 * time.Second
remoteReadyProbeTimeout = 500 * time.Millisecond
pollInterval = 500 * time.Millisecond
)
func (h *TerminalHandler) shouldUseWorkspaceShell(ctx context.Context, sessionID string) bool {
// Delegates to lifecycle manager which checks both in-memory execution
// and database records for containerized/remote executors.
return h.lifecycleMgr.ShouldUseContainerShell(ctx, sessionID)
}
func (h *TerminalHandler) waitForRemoteExecutionReadyWithTimeout(
ctx context.Context,
sessionID string,
timeout time.Duration,
) (*lifecycle.AgentExecution, bool) {
deadline := time.Now().Add(timeout)
h.logger.Info("waiting for remote execution to become ready",
zap.String("session_id", sessionID),
zap.Duration("timeout", timeout))
for {
if execution, ok := h.remoteExecutionWithClientReady(ctx, sessionID, deadline); ok {
return execution, true
}
remaining := time.Until(deadline)
if remaining <= 0 {
h.logger.Warn("timed out waiting for remote execution readiness",
zap.String("session_id", sessionID),
zap.Duration("timeout", timeout))
return nil, false
}
wait := pollInterval
if remaining < wait {
wait = remaining
}
timer := time.NewTimer(wait)
select {
case <-ctx.Done():
timer.Stop()
return nil, false
case <-timer.C:
}
}
}
func (h *TerminalHandler) remoteExecutionWithClientReady(
ctx context.Context,
sessionID string,
deadline time.Time,
) (*lifecycle.AgentExecution, bool) {
execution, exists := h.lifecycleMgr.GetExecutionBySessionID(sessionID)
if !exists || execution.GetAgentCtlClient() == nil {
return nil, false
}
remaining := time.Until(deadline)
if remaining <= 0 {
return nil, false
}
probeTimeout := remoteReadyProbeTimeout
if remaining < probeTimeout {
probeTimeout = remaining
}
probeCtx, cancel := context.WithTimeout(ctx, probeTimeout)
defer cancel()
if err := execution.GetAgentCtlClient().Health(probeCtx); err != nil {
h.logger.Debug("remote execution agentctl client not ready",
zap.String("session_id", sessionID),
zap.String("execution_id", execution.ID),
zap.Error(err))
return nil, false
}
h.logger.Info("remote execution became ready",
zap.String("session_id", sessionID),
zap.String("execution_id", execution.ID))
return execution, true
}
func (h *TerminalHandler) ensurePassthroughExecutionReady(ctx context.Context, sessionID string) (*lifecycle.AgentExecution, error) {
execution, err := h.lifecycleMgr.EnsurePassthroughExecution(ctx, sessionID)
if err == nil {
return execution, nil
}
if !errors.Is(err, lifecycle.ErrSessionWorkspaceNotReady) {
return nil, err
}
h.logger.Info("waiting for passthrough workspace to become ready",
zap.String("session_id", sessionID),
zap.Duration("timeout", passthroughReadyTimeout))
timeoutCtx, cancel := context.WithTimeout(ctx, passthroughReadyTimeout)
defer cancel()
ticker := time.NewTicker(pollInterval)
defer ticker.Stop()
for {
select {
case <-timeoutCtx.Done():
return nil, fmt.Errorf("%w: timed out after %s", lifecycle.ErrSessionWorkspaceNotReady, passthroughReadyTimeout)
case <-ticker.C:
execution, err := h.lifecycleMgr.EnsurePassthroughExecution(timeoutCtx, sessionID)
if err == nil {
h.logger.Info("passthrough workspace became ready",
zap.String("session_id", sessionID),
zap.String("execution_id", execution.ID))
return execution, nil
}
if !errors.Is(err, lifecycle.ErrSessionWorkspaceNotReady) {
return nil, err
}
}
}
}