chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动

演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
wuzilongandCursor committed 2026-11-18 13:59:25 +08:00
1 parent 60158935f4
commit 6519682885
15831 files changed
+3063428

No files matched your search

@@ -0,0 +1,308 @@
package server
import (
"encoding/json"
"fmt"
"log"
"net/http"
"runtime/debug"
"strconv"
"strings"
"time"
"github.com/langgenius/dify/dify-agent-runtime/internal/jobmode"
)
// Handler creates the HTTP handler (mux) for the shellctl API.
func Handler(svc *Service, config *Config) http.Handler {
mux := http.NewServeMux()
auth := authMiddleware(config.AuthToken)
mux.HandleFunc("GET /healthz", handleHealthz)
mux.HandleFunc("POST /v1/jobs/run", auth(handleRunJob(svc)))
mux.HandleFunc("POST /v1/jobs/{job_id}/wait", auth(handleWaitJob(svc, config)))
mux.HandleFunc("GET /v1/jobs/{job_id}/log/tail", auth(handleTailJob(svc, config)))
mux.HandleFunc("GET /v1/jobs/{job_id}", auth(handleJobStatus(svc)))
mux.HandleFunc("GET /v1/jobs", auth(handleListJobs(svc, config)))
mux.HandleFunc("POST /v1/jobs/{job_id}/input", auth(handleInputJob(svc, config)))
mux.HandleFunc("POST /v1/jobs/{job_id}/terminate", auth(handleTerminateJob(svc, config)))
mux.HandleFunc("DELETE /v1/jobs/{job_id}", auth(handleDeleteJob(svc, config)))
{ // Snapshot handlers
snap := newSnapshotHandlers(config)
mux.HandleFunc("POST /v1/snapshot/save", auth(snap.handleSnapshotSave()))
mux.HandleFunc("POST /v1/snapshot/restore", auth(snap.handleSnapshotRestore()))
}
return requestLoggingMiddleware(recoveryMiddleware(mux))
}
func handleHealthz(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, HealthResponse{Status: HealthStatus})
}
func handleRunJob(svc *Service) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req RunJobRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, 400, "invalid_request", "Invalid JSON body")
return
}
if req.Script == "" {
writeError(w, 400, "invalid_request", "script is required")
return
}
mode, err := jobmode.Parse(string(req.Mode))
if err != nil {
writeError(w, 422, "validation_error", err.Error())
return
}
req.Mode = mode
// Validate env
if req.Env != nil {
for name, value := range req.Env {
if name == "" {
writeError(w, 422, "validation_error", "env names must be non-empty")
return
}
if strings.Contains(name, "=") {
writeError(w, 422, "validation_error", fmt.Sprintf("env name must not contain '=': %q", name))
return
}
if strings.Contains(name, "\x00") || strings.Contains(value, "\x00") {
writeError(w, 422, "validation_error", "env entries must not contain NUL")
return
}
}
}
result, err := svc.RunJob(&req)
if err != nil {
writeServerError(w, err)
return
}
writeJSON(w, http.StatusOK, result)
}
}
func handleWaitJob(svc *Service, config *Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
jobID := r.PathValue("job_id")
var req WaitJobRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, 400, "invalid_request", "Invalid JSON body")
return
}
if req.IdleFlushSeconds == 0 {
req.IdleFlushSeconds = DefaultIdleFlushSeconds
}
result, err := svc.WaitJob(jobID, &req)
if err != nil {
writeServerError(w, err)
return
}
writeJSON(w, http.StatusOK, result)
}
}
func handleTailJob(svc *Service, config *Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
jobID := r.PathValue("job_id")
outputLimit := config.DefaultOutputLimitBytes
if v := r.URL.Query().Get("output_limit"); v != "" {
if parsed, err := strconv.Atoi(v); err == nil && parsed > 0 {
outputLimit = parsed
}
}
if outputLimit > config.MaxOutputLimitBytes {
outputLimit = config.MaxOutputLimitBytes
}
result, err := svc.TailJob(jobID, outputLimit)
if err != nil {
writeServerError(w, err)
return
}
writeJSON(w, http.StatusOK, result)
}
}
func handleJobStatus(svc *Service) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
jobID := r.PathValue("job_id")
view, err := svc.GetJobStatus(jobID)
if err != nil {
writeServerError(w, err)
return
}
writeJSON(w, http.StatusOK, view)
}
}
func handleListJobs(svc *Service, config *Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var status *JobStatusName
if v := r.URL.Query().Get("status"); v != "" {
s := JobStatusName(v)
status = &s
}
limit := config.DefaultListLimit
if v := r.URL.Query().Get("limit"); v != "" {
if parsed, err := strconv.Atoi(v); err == nil && parsed > 0 {
limit = parsed
}
}
if limit > config.MaxListLimit {
limit = config.MaxListLimit
}
result, err := svc.ListJobs(status, limit)
if err != nil {
writeServerError(w, err)
return
}
writeJSON(w, http.StatusOK, result)
}
}
func handleInputJob(svc *Service, config *Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
jobID := r.PathValue("job_id")
var req InputJobRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, 400, "invalid_request", "Invalid JSON body")
return
}
if req.IdleFlushSeconds == 0 {
req.IdleFlushSeconds = DefaultIdleFlushSeconds
}
if req.Timeout == 0 {
req.Timeout = DefaultTimeoutSeconds
}
result, err := svc.SendInput(jobID, &req)
if err != nil {
writeServerError(w, err)
return
}
writeJSON(w, http.StatusOK, result)
}
}
func handleTerminateJob(svc *Service, config *Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
jobID := r.PathValue("job_id")
var req TerminateJobRequest
_ = json.NewDecoder(r.Body).Decode(&req)
graceSeconds := config.DefaultTerminateGraceSeconds
if req.GraceSeconds != nil {
graceSeconds = *req.GraceSeconds
}
view, err := svc.TerminateJob(jobID, graceSeconds)
if err != nil {
writeServerError(w, err)
return
}
writeJSON(w, http.StatusOK, view)
}
}
func handleDeleteJob(svc *Service, config *Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
jobID := r.PathValue("job_id")
force := r.URL.Query().Get("force") == "true"
graceSeconds := config.DefaultTerminateGraceSeconds
if v := r.URL.Query().Get("grace_seconds"); v != "" {
if parsed, err := strconv.ParseFloat(v, 64); err == nil {
graceSeconds = parsed
}
}
result, err := svc.DeleteJob(jobID, force, graceSeconds)
if err != nil {
writeServerError(w, err)
return
}
writeJSON(w, http.StatusOK, result)
}
}
// Middleware
// statusRecorder wraps ResponseWriter to capture the status code.
type statusRecorder struct {
http.ResponseWriter
statusCode int
}
func (sr *statusRecorder) WriteHeader(code int) {
sr.statusCode = code
sr.ResponseWriter.WriteHeader(code)
}
// Unwrap exposes the underlying writer so http.ResponseController works
// (flushes and per-request deadlines reach the real connection).
func (sr *statusRecorder) Unwrap() http.ResponseWriter { return sr.ResponseWriter }
func requestLoggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
rec := &statusRecorder{ResponseWriter: w, statusCode: 200}
next.ServeHTTP(rec, r)
log.Printf("%s %s -> %d (%s)", r.Method, r.URL.Path, rec.statusCode, time.Since(start).Round(time.Millisecond))
})
}
func recoveryMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if rec := recover(); rec != nil {
if rec == http.ErrAbortHandler {
// Deliberate connection abort (e.g. failed snapshot
// stream): let net/http tear the connection down.
panic(rec)
}
stack := debug.Stack()
log.Printf("PANIC %s %s: %v\n%s", r.Method, r.URL.Path, rec, stack)
writeError(w, 500, "internal_panic", fmt.Sprintf("internal server error: %v", rec))
}
}()
next.ServeHTTP(w, r)
})
}
func authMiddleware(token string) func(http.HandlerFunc) http.HandlerFunc {
return func(next http.HandlerFunc) http.HandlerFunc {
if token == "" {
return next // No auth configured
}
expected := "Bearer " + token
return func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != expected {
writeError(w, 401, "unauthorized", "Missing or invalid bearer token")
return
}
next(w, r)
}
}
}
// Response helpers
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}
func writeError(w http.ResponseWriter, status int, code, message string) {
writeJSON(w, status, ErrorResponse{Error: ErrorDetail{Code: code, Message: message}})
}
func writeServerError(w http.ResponseWriter, err error) {
if se, ok := err.(*ServerError); ok {
log.Printf("ERROR [%d] %s: %s", se.StatusCode, se.Code, se.Message)
writeError(w, se.StatusCode, se.Code, se.Message)
return
}
log.Printf("ERROR [500] internal_error: %v", err)
writeError(w, 500, "internal_error", err.Error())
}
@@ -0,0 +1,234 @@
package server
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
// We can't fully test the Service without tmux, but we can test the HTTP
// layer wiring, error handling, and JSON serialization.
func TestWriteJSON(t *testing.T) {
w := httptest.NewRecorder()
writeJSON(w, 200, HealthResponse{Status: "ok"})
if w.Code != 200 {
t.Errorf("expected 200, got %d", w.Code)
}
if w.Header().Get("Content-Type") != "application/json" {
t.Errorf("expected application/json, got %s", w.Header().Get("Content-Type"))
}
var result HealthResponse
if err := json.NewDecoder(w.Body).Decode(&result); err != nil {
t.Fatal(err)
}
if result.Status != "ok" {
t.Errorf("expected status=ok, got %s", result.Status)
}
}
func TestWriteError(t *testing.T) {
w := httptest.NewRecorder()
writeError(w, 400, "bad_request", "missing field")
if w.Code != 400 {
t.Errorf("expected 400, got %d", w.Code)
}
var result ErrorResponse
if err := json.NewDecoder(w.Body).Decode(&result); err != nil {
t.Fatal(err)
}
if result.Error.Code != "bad_request" {
t.Errorf("expected code=bad_request, got %s", result.Error.Code)
}
if result.Error.Message != "missing field" {
t.Errorf("expected message='missing field', got %s", result.Error.Message)
}
}
func TestWriteServerError(t *testing.T) {
w := httptest.NewRecorder()
err := NewServerError(404, "job_not_found", "Unknown job id")
writeServerError(w, err)
if w.Code != 404 {
t.Errorf("expected 404, got %d", w.Code)
}
var result ErrorResponse
if err := json.NewDecoder(w.Body).Decode(&result); err != nil {
t.Fatal(err)
}
if result.Error.Code != "job_not_found" {
t.Errorf("expected code=job_not_found, got %s", result.Error.Code)
}
}
func TestWriteServerErrorGeneric(t *testing.T) {
w := httptest.NewRecorder()
writeServerError(w, &json.SyntaxError{Offset: 5})
if w.Code != 500 {
t.Errorf("expected 500, got %d", w.Code)
}
var result ErrorResponse
if err := json.NewDecoder(w.Body).Decode(&result); err != nil {
t.Fatal(err)
}
if result.Error.Code != "internal_error" {
t.Errorf("expected code=internal_error, got %s", result.Error.Code)
}
}
func TestAuthMiddlewareNoToken(t *testing.T) {
// When no token configured, auth middleware should pass through
handler := authMiddleware("")(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
})
req := httptest.NewRequest("GET", "/v1/jobs", nil)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != 200 {
t.Errorf("expected 200 without auth, got %d", w.Code)
}
}
func TestAuthMiddlewareWithToken(t *testing.T) {
handler := authMiddleware("secret")(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
})
// Without auth header
req := httptest.NewRequest("GET", "/v1/jobs", nil)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != 401 {
t.Errorf("expected 401 without auth, got %d", w.Code)
}
// With correct auth header
req = httptest.NewRequest("GET", "/v1/jobs", nil)
req.Header.Set("Authorization", "Bearer secret")
w = httptest.NewRecorder()
handler(w, req)
if w.Code != 200 {
t.Errorf("expected 200 with correct auth, got %d", w.Code)
}
// With wrong auth header
req = httptest.NewRequest("GET", "/v1/jobs", nil)
req.Header.Set("Authorization", "Bearer wrong")
w = httptest.NewRecorder()
handler(w, req)
if w.Code != 401 {
t.Errorf("expected 401 with wrong auth, got %d", w.Code)
}
}
func TestHealthzHandler(t *testing.T) {
// Create a handler with a nil service (healthz doesn't use it)
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", handleHealthz)
req := httptest.NewRequest("GET", "/healthz", nil)
w := httptest.NewRecorder()
mux.ServeHTTP(w, req)
if w.Code != 200 {
t.Errorf("expected 200, got %d", w.Code)
}
body := w.Body.String()
if !strings.Contains(body, "ok") {
t.Errorf("expected body to contain 'ok', got %s", body)
}
}
func TestRunJobRejectsInvalidModeBeforeCallingService(t *testing.T) {
handler := handleRunJob(nil)
req := httptest.NewRequest("POST", "/v1/jobs/run", strings.NewReader(`{"script":"true","mode":"stdout"}`))
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusUnprocessableEntity {
t.Fatalf("expected 422, got %d", w.Code)
}
var result ErrorResponse
if err := json.NewDecoder(w.Body).Decode(&result); err != nil {
t.Fatal(err)
}
if result.Error.Code != "validation_error" {
t.Errorf("expected validation_error, got %q", result.Error.Code)
}
}
func TestServerErrorFormat(t *testing.T) {
err := NewServerError(422, "validation_error", "bad input")
expected := "[422] validation_error: bad input"
if err.Error() != expected {
t.Errorf("expected %q, got %q", expected, err.Error())
}
}
func TestIsNotFound(t *testing.T) {
if !isNotFound(ErrJobNotFound) {
t.Error("ErrJobNotFound should be detected as not found")
}
if isNotFound(NewServerError(500, "internal_error", "x")) {
t.Error("500 error should not be detected as not found")
}
}
func TestStatusRecorderUnwrap(t *testing.T) {
w := httptest.NewRecorder()
rec := &statusRecorder{ResponseWriter: w, statusCode: 200}
if rec.Unwrap() != w {
t.Fatal("Unwrap must return the wrapped ResponseWriter")
}
}
func TestRecoveryMiddlewareRepanicsAbortHandler(t *testing.T) {
srv := httptest.NewServer(requestLoggingMiddleware(recoveryMiddleware(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
_, _ = w.Write([]byte("partial"))
panic(http.ErrAbortHandler)
}))))
defer srv.Close()
resp, err := http.Get(srv.URL)
if err == nil {
_, readErr := io.ReadAll(resp.Body)
_ = resp.Body.Close()
if readErr == nil {
t.Fatal("expected aborted connection, got clean response")
}
}
}
func TestRecoveryMiddlewareStillCatchesOtherPanics(t *testing.T) {
srv := httptest.NewServer(recoveryMiddleware(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
panic("boom")
})))
defer srv.Close()
resp, err := http.Get(srv.URL)
if err != nil {
t.Fatal(err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != 500 {
t.Fatalf("expected 500, got %d", resp.StatusCode)
}
}
@@ -0,0 +1,157 @@
package server
import (
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
"time"
)
const (
DefaultListen = "127.0.0.1:8765"
DefaultTimeoutSeconds = 30.0
DefaultMaxWaitTimeoutSeconds = 600.0
DefaultIdleFlushSeconds = 0.5
DefaultTerminalCols = 200
DefaultTerminalRows = 50
DefaultOutputLimitBytes = 16 * 1024
MaxOutputLimitBytes = 512 * 1024
DefaultListLimit = 50
MaxListLimit = 200
DefaultTerminateGraceSeconds = 10.0
DefaultGCIntervalSeconds = 60.0
DefaultGCFinishedJobRetentionSeconds = 300.0
DefaultPollInterval = 5 * time.Millisecond
DefaultMaxPollInterval = 50 * time.Millisecond
DefaultPipeMonitorInterval = 1 * time.Second
DefaultPipeReadyTimeout = 10 * time.Second
DefaultSQLiteBusyTimeoutMs = 5000
DefaultAuthTokenEnv = "SHELLCTL_AUTH_TOKEN"
HealthStatus = "ok"
DefaultSnapshotTimeoutSeconds = 45.0
SnapshotTimeoutEnv = "SHELLCTL_SNAPSHOT_TIMEOUT"
)
// Config holds runtime configuration for the shellctl server.
type Config struct {
Listen string
AuthToken string
StateDir string
RuntimeDir string
GCInterval time.Duration
GCFinishedJobRetention time.Duration
DefaultTimeout time.Duration
MaxWaitTimeout time.Duration
IdleFlushDuration time.Duration
DefaultCwd string
DefaultTerminalCols int
DefaultTerminalRows int
DefaultListLimit int
MaxListLimit int
DefaultOutputLimitBytes int
MaxOutputLimitBytes int
DefaultTerminateGraceSeconds float64
PollInterval time.Duration
MaxPollInterval time.Duration
PipeMonitorInterval time.Duration
PipeReadyTimeout time.Duration
SQLiteBusyTimeoutMs int
SanitizePtyCommand []string
RunnerExitCommand []string
SnapshotTimeout time.Duration
}
// DefaultConfig returns a Config with sensible defaults.
func DefaultConfig() (*Config, error) {
homeDir, _ := os.UserHomeDir()
stateDir := defaultStateDir()
runtimeDir := filepath.Join(stateDir, "runtime")
snapshotTimeout, err := parseSnapshotTimeout(os.Getenv(SnapshotTimeoutEnv))
if err != nil {
return nil, err
}
cfg := &Config{
Listen: DefaultListen,
StateDir: stateDir,
RuntimeDir: runtimeDir,
GCInterval: time.Duration(DefaultGCIntervalSeconds * float64(time.Second)),
GCFinishedJobRetention: time.Duration(DefaultGCFinishedJobRetentionSeconds * float64(time.Second)),
DefaultTimeout: time.Duration(DefaultTimeoutSeconds * float64(time.Second)),
MaxWaitTimeout: time.Duration(DefaultMaxWaitTimeoutSeconds * float64(time.Second)),
IdleFlushDuration: time.Duration(DefaultIdleFlushSeconds * float64(time.Second)),
DefaultCwd: homeDir,
DefaultTerminalCols: DefaultTerminalCols,
DefaultTerminalRows: DefaultTerminalRows,
DefaultListLimit: DefaultListLimit,
MaxListLimit: MaxListLimit,
DefaultOutputLimitBytes: DefaultOutputLimitBytes,
MaxOutputLimitBytes: MaxOutputLimitBytes,
DefaultTerminateGraceSeconds: DefaultTerminateGraceSeconds,
PollInterval: DefaultPollInterval,
MaxPollInterval: DefaultMaxPollInterval,
PipeMonitorInterval: DefaultPipeMonitorInterval,
PipeReadyTimeout: DefaultPipeReadyTimeout,
SQLiteBusyTimeoutMs: DefaultSQLiteBusyTimeoutMs,
SanitizePtyCommand: []string{"shellctl-sanitize-pty"},
RunnerExitCommand: []string{"shellctl-runner-exit"},
SnapshotTimeout: snapshotTimeout,
}
// Auth token from environment if not set explicitly
if cfg.AuthToken == "" {
cfg.AuthToken = os.Getenv(DefaultAuthTokenEnv)
}
return cfg, nil
}
// JobsDir returns the path to the jobs artifact directory.
func (c *Config) JobsDir() string {
return filepath.Join(c.StateDir, "jobs")
}
// DBPath returns the path to the SQLite database.
func (c *Config) DBPath() string {
return filepath.Join(c.StateDir, "shellctl.db")
}
// TmuxSocket returns the path to the dedicated tmux socket.
func (c *Config) TmuxSocket() string {
return filepath.Join(c.RuntimeDir, "tmux.sock")
}
// RunnerPath returns the path to the installed runner script.
func (c *Config) RunnerPath() string {
return filepath.Join(c.RuntimeDir, "bin", "shellctl-runner")
}
func defaultStateDir() string {
if runtime.GOOS == "darwin" {
home, _ := os.UserHomeDir()
return filepath.Join(home, ".local", "share", "shellctl")
}
if xdg := os.Getenv("XDG_DATA_HOME"); xdg != "" {
return filepath.Join(xdg, "shellctl")
}
home, _ := os.UserHomeDir()
return filepath.Join(home, ".local", "share", "shellctl")
}
func parseSnapshotTimeout(raw string) (time.Duration, error) {
trimmed := strings.TrimSpace(raw)
if trimmed == "" {
return time.Duration(DefaultSnapshotTimeoutSeconds * float64(time.Second)), nil
}
timeout, err := time.ParseDuration(trimmed)
if err != nil {
return 0, fmt.Errorf("%s: %w", SnapshotTimeoutEnv, err)
}
if timeout <= 0 {
return 0, fmt.Errorf("%s: must be positive, got %q", SnapshotTimeoutEnv, trimmed)
}
return timeout, nil
}
@@ -0,0 +1,131 @@
package server
import (
"os"
"strings"
"testing"
"time"
)
func mustDefaultConfig(t *testing.T) *Config {
t.Helper()
cfg, err := DefaultConfig()
if err != nil {
t.Fatalf("DefaultConfig: %v", err)
}
return cfg
}
func TestDefaultConfig(t *testing.T) {
cfg := mustDefaultConfig(t)
if cfg.Listen != DefaultListen {
t.Errorf("expected Listen=%s, got %s", DefaultListen, cfg.Listen)
}
if cfg.DefaultTerminalCols != DefaultTerminalCols {
t.Errorf("expected cols=%d, got %d", DefaultTerminalCols, cfg.DefaultTerminalCols)
}
if cfg.DefaultTerminalRows != DefaultTerminalRows {
t.Errorf("expected rows=%d, got %d", DefaultTerminalRows, cfg.DefaultTerminalRows)
}
if cfg.SQLiteBusyTimeoutMs != DefaultSQLiteBusyTimeoutMs {
t.Errorf("expected busy_timeout=%d, got %d", DefaultSQLiteBusyTimeoutMs, cfg.SQLiteBusyTimeoutMs)
}
}
func TestConfigPaths(t *testing.T) {
cfg := mustDefaultConfig(t)
cfg.StateDir = "/tmp/shellctl-test"
cfg.RuntimeDir = "/tmp/shellctl-test/runtime"
if cfg.JobsDir() != "/tmp/shellctl-test/jobs" {
t.Errorf("unexpected JobsDir: %s", cfg.JobsDir())
}
if cfg.DBPath() != "/tmp/shellctl-test/shellctl.db" {
t.Errorf("unexpected DBPath: %s", cfg.DBPath())
}
if cfg.TmuxSocket() != "/tmp/shellctl-test/runtime/tmux.sock" {
t.Errorf("unexpected TmuxSocket: %s", cfg.TmuxSocket())
}
if cfg.RunnerPath() != "/tmp/shellctl-test/runtime/bin/shellctl-runner" {
t.Errorf("unexpected RunnerPath: %s", cfg.RunnerPath())
}
}
func TestConfigAuthTokenFromEnv(t *testing.T) {
t.Setenv("SHELLCTL_AUTH_TOKEN", "my-secret-token")
cfg := mustDefaultConfig(t)
if cfg.AuthToken != "my-secret-token" {
t.Errorf("expected auth token from env, got %q", cfg.AuthToken)
}
}
func TestConfigNoAuthToken(t *testing.T) {
t.Setenv("SHELLCTL_AUTH_TOKEN", "")
cfg := mustDefaultConfig(t)
if cfg.AuthToken != "" {
t.Errorf("expected empty auth token, got %q", cfg.AuthToken)
}
}
func TestDefaultConfigSnapshotFields(t *testing.T) {
cfg := mustDefaultConfig(t)
if cfg.SnapshotTimeout != 45*time.Second {
t.Errorf("SnapshotTimeout = %v, want 45s", cfg.SnapshotTimeout)
}
}
func TestSnapshotTimeoutDefaultsWhenEnvUnset(t *testing.T) {
t.Setenv(SnapshotTimeoutEnv, "")
_ = os.Unsetenv(SnapshotTimeoutEnv)
cfg := mustDefaultConfig(t)
if cfg.SnapshotTimeout != 45*time.Second {
t.Errorf("SnapshotTimeout = %v, want 45s", cfg.SnapshotTimeout)
}
}
func TestSnapshotTimeoutDefaultsWhenEnvEmpty(t *testing.T) {
t.Setenv(SnapshotTimeoutEnv, "")
cfg := mustDefaultConfig(t)
if cfg.SnapshotTimeout != 45*time.Second {
t.Errorf("SnapshotTimeout = %v, want 45s", cfg.SnapshotTimeout)
}
}
func TestSnapshotTimeoutFromEnv(t *testing.T) {
cases := []struct {
raw string
want time.Duration
}{
{"900s", 900 * time.Second},
{"15m", 15 * time.Minute},
{"15m30s", 15*time.Minute + 30*time.Second},
{" 15m ", 15 * time.Minute},
}
for _, tc := range cases {
t.Run(tc.raw, func(t *testing.T) {
t.Setenv(SnapshotTimeoutEnv, tc.raw)
cfg := mustDefaultConfig(t)
if cfg.SnapshotTimeout != tc.want {
t.Errorf("SnapshotTimeout = %v, want %v", cfg.SnapshotTimeout, tc.want)
}
})
}
}
func TestSnapshotTimeoutRejectsUnusableEnv(t *testing.T) {
for _, raw := range []string{"fifteen minutes", "600", "10 m", "0", "0s", "-1s", "-5m"} {
t.Run(raw, func(t *testing.T) {
t.Setenv(SnapshotTimeoutEnv, raw)
cfg, err := DefaultConfig()
if err == nil {
t.Fatalf("%q must fail startup, not run with a substituted timeout", raw)
}
if !strings.Contains(err.Error(), SnapshotTimeoutEnv) {
t.Errorf("error %q must name %s so the operator knows what to fix", err, SnapshotTimeoutEnv)
}
if cfg != nil {
t.Errorf("%q yielded a usable config; an unusable timeout must yield none", raw)
}
})
}
}
@@ -0,0 +1,453 @@
package server
import (
"database/sql"
"fmt"
"time"
"github.com/langgenius/dify/dify-agent-runtime/internal/jobmode"
_ "modernc.org/sqlite"
)
const latestSchemaVersion = 1
type schemaMigration func(*sql.Tx) error
var schemaMigrations = []schemaMigration{
migrateSchemaV1,
}
// JobStatusName represents the lifecycle states of a shellctl job.
type JobStatusName string
const (
StatusCreated JobStatusName = "created"
StatusStarting JobStatusName = "starting"
StatusRunning JobStatusName = "running"
StatusExited JobStatusName = "exited"
StatusTerminated JobStatusName = "terminated"
StatusFailed JobStatusName = "failed"
StatusLost JobStatusName = "lost"
)
// IsTerminal returns true if the status represents a final job state.
func (s JobStatusName) IsTerminal() bool {
switch s {
case StatusExited, StatusTerminated, StatusFailed, StatusLost:
return true
}
return false
}
// JobRow represents a row in the jobs SQLite table.
type JobRow struct {
JobID string
ScriptPath string
OutputPath string
Mode jobmode.Mode
Cwd string
TerminalCols int
TerminalRows int
Status JobStatusName
SessionName string
PaneTarget string
ExitCode *int
Reason *string
Message *string
CreatedAt string
StartedAt *string
EndedAt *string
UpdatedAt string
}
// DB wraps the SQLite database for shellctl job persistence.
type DB struct {
db *sql.DB
}
// OpenDB opens (or creates) the shellctl SQLite database.
func OpenDB(dbPath string, busyTimeoutMs int) (*DB, error) {
// synchronous=NORMAL is durable and crash-safe under WAL: it only fsyncs on
// checkpoint rather than on every commit, which removes the per-write fsync
// on the job-creation path. Worst case on power loss is losing the last few
// transactions of ephemeral job state, never DB corruption.
dsn := fmt.Sprintf(
"file:%s?_pragma=busy_timeout(%d)&_pragma=journal_mode(WAL)&_pragma=synchronous(NORMAL)",
dbPath, busyTimeoutMs,
)
db, err := sql.Open("sqlite", dsn)
if err != nil {
return nil, fmt.Errorf("open sqlite: %w", err)
}
db.SetMaxOpenConns(1)
db.SetConnMaxLifetime(0)
return &DB{db: db}, nil
}
// Close closes the database connection.
func (d *DB) Close() error {
return d.db.Close()
}
// InitSchema creates the v0 baseline and applies pending schema migrations.
func (d *DB) InitSchema() error {
var currentVersion int
if err := d.db.QueryRow("PRAGMA user_version").Scan(&currentVersion); err != nil {
return fmt.Errorf("read schema version: %w", err)
}
if currentVersion > latestSchemaVersion {
return fmt.Errorf(
"database schema version %d is newer than supported version %d",
currentVersion,
latestSchemaVersion,
)
}
if currentVersion == 0 {
if err := d.createSchemaV0(); err != nil {
return err
}
}
for currentVersion < latestSchemaVersion {
targetVersion := currentVersion + 1
if err := d.applySchemaMigration(targetVersion, schemaMigrations[targetVersion-1]); err != nil {
return err
}
currentVersion = targetVersion
}
return nil
}
// applySchemaMigration commits migration SQL and PRAGMA user_version together,
// rolling back the entire version if either operation fails.
func (d *DB) applySchemaMigration(targetVersion int, migration schemaMigration) error {
tx, err := d.db.Begin()
if err != nil {
return fmt.Errorf("begin schema migration v%d: %w", targetVersion, err)
}
if err := migration(tx); err != nil {
_ = tx.Rollback()
return fmt.Errorf("apply schema migration v%d: %w", targetVersion, err)
}
if _, err := tx.Exec(fmt.Sprintf("PRAGMA user_version = %d", targetVersion)); err != nil {
_ = tx.Rollback()
return fmt.Errorf("record schema migration v%d: %w", targetVersion, err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("commit schema migration v%d: %w", targetVersion, err)
}
return nil
}
func (d *DB) createSchemaV0() error {
tx, err := d.db.Begin()
if err != nil {
return fmt.Errorf("begin schema v0: %w", err)
}
if _, err := tx.Exec(`
CREATE TABLE IF NOT EXISTS jobs (
job_id TEXT PRIMARY KEY,
script_path TEXT NOT NULL,
output_path TEXT NOT NULL,
cwd TEXT NOT NULL,
terminal_cols INTEGER NOT NULL DEFAULT 200,
terminal_rows INTEGER NOT NULL DEFAULT 50,
status TEXT NOT NULL DEFAULT 'created',
session_name TEXT NOT NULL,
pane_target TEXT NOT NULL,
exit_code INTEGER,
reason TEXT,
message TEXT,
created_at TEXT NOT NULL,
started_at TEXT,
ended_at TEXT,
updated_at TEXT NOT NULL
)
`); err != nil {
_ = tx.Rollback()
return fmt.Errorf("create schema v0: %w", err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("commit schema v0: %w", err)
}
return nil
}
func migrateSchemaV1(tx *sql.Tx) error {
_, err := tx.Exec(`ALTER TABLE jobs ADD COLUMN mode TEXT NOT NULL DEFAULT 'pty'`)
return err
}
// InsertJob inserts a new job row. Returns false if the job_id already exists.
func (d *DB) InsertJob(row *JobRow) (bool, error) {
_, err := d.db.Exec(`
INSERT INTO jobs (job_id, script_path, output_path, mode, cwd, terminal_cols, terminal_rows,
status, session_name, pane_target, exit_code, reason, message,
created_at, started_at, ended_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
row.JobID, row.ScriptPath, row.OutputPath, string(row.Mode), row.Cwd,
row.TerminalCols, row.TerminalRows,
string(row.Status), row.SessionName, row.PaneTarget,
row.ExitCode, row.Reason, row.Message,
row.CreatedAt, row.StartedAt, row.EndedAt, row.UpdatedAt,
)
if err != nil {
// SQLite UNIQUE constraint violation
if isUniqueViolation(err) {
return false, nil
}
return false, err
}
return true, nil
}
// GetJob retrieves a single job row by ID.
func (d *DB) GetJob(jobID string) (*JobRow, error) {
row := d.db.QueryRow(`
SELECT job_id, script_path, output_path, mode, cwd, terminal_cols, terminal_rows,
status, session_name, pane_target, exit_code, reason, message,
created_at, started_at, ended_at, updated_at
FROM jobs WHERE job_id = ?`, jobID)
return scanJobRow(row)
}
// ListJobs returns all jobs ordered by created_at descending, optionally filtered by status.
func (d *DB) ListJobs(statuses []JobStatusName) ([]*JobRow, error) {
var rows *sql.Rows
var err error
if len(statuses) == 0 {
rows, err = d.db.Query(`SELECT job_id, script_path, output_path, mode, cwd,
terminal_cols, terminal_rows, status, session_name, pane_target,
exit_code, reason, message, created_at, started_at, ended_at, updated_at
FROM jobs ORDER BY created_at DESC`)
} else {
args := make([]any, len(statuses))
placeholders := ""
for i, s := range statuses {
args[i] = string(s)
if i > 0 {
placeholders += ","
}
placeholders += "?"
}
query := fmt.Sprintf(`SELECT job_id, script_path, output_path, mode, cwd,
terminal_cols, terminal_rows, status, session_name, pane_target,
exit_code, reason, message, created_at, started_at, ended_at, updated_at
FROM jobs WHERE status IN (%s) ORDER BY created_at DESC`, placeholders)
rows, err = d.db.Query(query, args...)
}
if err != nil {
return nil, err
}
defer func() { _ = rows.Close() }()
var result []*JobRow
for rows.Next() {
jr, err := scanJobRows(rows)
if err != nil {
return nil, err
}
result = append(result, jr)
}
return result, rows.Err()
}
// DeleteJob removes a job row by ID. Returns error if not found.
func (d *DB) DeleteJob(jobID string) error {
result, err := d.db.Exec("DELETE FROM jobs WHERE job_id = ?", jobID)
if err != nil {
return err
}
n, _ := result.RowsAffected()
if n == 0 {
return ErrJobNotFound
}
return nil
}
// TransitionStatus performs a conditional CAS update on a job row.
func (d *DB) TransitionStatus(jobID string, opts TransitionOpts) (*JobRow, error) {
now := FormatTimestamp(time.Now())
// Build WHERE clause
allowedList := make([]any, 0, len(opts.AllowedFrom)+len(opts.AllowOverrideFrom))
placeholders := ""
all := append(opts.AllowedFrom, opts.AllowOverrideFrom...)
for i, s := range all {
allowedList = append(allowedList, string(s))
if i > 0 {
placeholders += ","
}
placeholders += "?"
}
setClauses := `
status = ?,
updated_at = ?,
reason = ?,
message = ?`
args := []any{string(opts.Target), now, opts.Reason, opts.Message}
// started_at: set on first transition to starting/running
if opts.Target == StatusStarting || opts.Target == StatusRunning {
setClauses += `, started_at = CASE WHEN started_at IS NULL THEN ? ELSE started_at END`
args = append(args, now)
}
// ended_at + exit_code: set on terminal transitions
if opts.Target.IsTerminal() {
endedAt := opts.EndedAt
if endedAt == "" {
endedAt = now
}
setClauses += `, ended_at = CASE WHEN ended_at IS NULL THEN ? ELSE ended_at END`
args = append(args, endedAt)
// Set exit_code to 0 if not already set (normal exit without runner-exit callback)
setClauses += `, exit_code = CASE WHEN exit_code IS NULL THEN 0 ELSE exit_code END`
}
whereClause := fmt.Sprintf("job_id = ? AND status IN (%s)", placeholders)
args = append(args, jobID)
args = append(args, allowedList...)
if opts.RequireExitCodeNull {
whereClause += " AND exit_code IS NULL"
}
query := fmt.Sprintf("UPDATE jobs SET %s WHERE %s", setClauses, whereClause)
result, err := d.db.Exec(query, args...)
if err != nil {
return nil, fmt.Errorf("transition status: %w", err)
}
n, _ := result.RowsAffected()
_ = n // If 0 rows affected, we just return current state
return d.GetJob(jobID)
}
// RecordRunnerExit persists exit_code and ended_at for a drained job.
// The update is idempotent for terminal rows: once a job reaches a terminal
// state, this method returns nil without rewriting the row.
func (d *DB) RecordRunnerExit(jobID string, exitCode int, endedAt string) error {
// Check if job exists and is already terminal
var status string
err := d.db.QueryRow("SELECT status FROM jobs WHERE job_id = ?", jobID).Scan(&status)
if err == sql.ErrNoRows {
return ErrJobNotFound
}
if err != nil {
return err
}
if JobStatusName(status).IsTerminal() {
return nil
}
nonterminal := []any{"created", "starting", "running"}
result, err := d.db.Exec(`
UPDATE jobs
SET status = CASE WHEN status IN (?, ?, ?) THEN ? ELSE status END,
exit_code = CASE WHEN status IN (?, ?, ?) THEN ? ELSE exit_code END,
ended_at = CASE WHEN status IN (?, ?, ?) AND ended_at IS NULL THEN ? ELSE ended_at END,
updated_at = CASE WHEN status IN (?, ?, ?) THEN ? ELSE updated_at END,
reason = CASE WHEN status IN (?, ?, ?) THEN NULL ELSE reason END,
message = CASE WHEN status IN (?, ?, ?) THEN NULL ELSE message END
WHERE job_id = ? AND status IN (?, ?, ?)`,
nonterminal[0], nonterminal[1], nonterminal[2], string(StatusExited),
// exit_code
nonterminal[0], nonterminal[1], nonterminal[2], exitCode,
// ended_at
nonterminal[0], nonterminal[1], nonterminal[2], endedAt,
// updated_at
nonterminal[0], nonterminal[1], nonterminal[2], endedAt,
// reason
nonterminal[0], nonterminal[1], nonterminal[2],
// message
nonterminal[0], nonterminal[1], nonterminal[2],
// WHERE
jobID,
nonterminal[0], nonterminal[1], nonterminal[2],
)
if err != nil {
return err
}
n, _ := result.RowsAffected()
if n == 0 {
return ErrJobNotFound
}
return nil
}
// TransitionOpts holds parameters for a CAS state transition.
type TransitionOpts struct {
AllowedFrom []JobStatusName
AllowOverrideFrom []JobStatusName
Target JobStatusName
RequireExitCodeNull bool
Reason *string
Message *string
EndedAt string
}
func scanJobRow(row *sql.Row) (*JobRow, error) {
var jr JobRow
var mode, status string
err := row.Scan(
&jr.JobID, &jr.ScriptPath, &jr.OutputPath, &mode, &jr.Cwd,
&jr.TerminalCols, &jr.TerminalRows,
&status, &jr.SessionName, &jr.PaneTarget,
&jr.ExitCode, &jr.Reason, &jr.Message,
&jr.CreatedAt, &jr.StartedAt, &jr.EndedAt, &jr.UpdatedAt,
)
if err == sql.ErrNoRows {
return nil, ErrJobNotFound
}
if err != nil {
return nil, err
}
jr.Mode = jobmode.Mode(mode)
jr.Status = JobStatusName(status)
return &jr, nil
}
func scanJobRows(rows *sql.Rows) (*JobRow, error) {
var jr JobRow
var mode, status string
err := rows.Scan(
&jr.JobID, &jr.ScriptPath, &jr.OutputPath, &mode, &jr.Cwd,
&jr.TerminalCols, &jr.TerminalRows,
&status, &jr.SessionName, &jr.PaneTarget,
&jr.ExitCode, &jr.Reason, &jr.Message,
&jr.CreatedAt, &jr.StartedAt, &jr.EndedAt, &jr.UpdatedAt,
)
if err != nil {
return nil, err
}
jr.Mode = jobmode.Mode(mode)
jr.Status = JobStatusName(status)
return &jr, nil
}
func isUniqueViolation(err error) bool {
// modernc.org/sqlite returns error messages containing "UNIQUE constraint failed"
return err != nil && contains(err.Error(), "UNIQUE constraint failed")
}
func contains(s, substr string) bool {
return len(s) >= len(substr) && (s == substr || len(substr) == 0 ||
(len(s) > 0 && len(substr) > 0 && searchString(s, substr)))
}
func searchString(s, substr string) bool {
for i := 0; i <= len(s)-len(substr); i++ {
if s[i:i+len(substr)] == substr {
return true
}
}
return false
}
@@ -0,0 +1,432 @@
package server
import (
"database/sql"
"errors"
"os"
"path/filepath"
"testing"
"github.com/langgenius/dify/dify-agent-runtime/internal/jobmode"
)
func TestJobStatusIsTerminal(t *testing.T) {
terminal := []JobStatusName{StatusExited, StatusTerminated, StatusFailed, StatusLost}
for _, s := range terminal {
if !s.IsTerminal() {
t.Errorf("%s should be terminal", s)
}
}
nonTerminal := []JobStatusName{StatusCreated, StatusStarting, StatusRunning}
for _, s := range nonTerminal {
if s.IsTerminal() {
t.Errorf("%s should not be terminal", s)
}
}
}
func TestOpenDBAndInitSchema(t *testing.T) {
dir := t.TempDir()
dbPath := filepath.Join(dir, "shellctl.db")
db, err := OpenDB(dbPath, 5000)
if err != nil {
t.Fatalf("OpenDB: %v", err)
}
defer func() { _ = db.Close() }()
if err := db.InitSchema(); err != nil {
t.Fatalf("InitSchema: %v", err)
}
// Verify table exists by inserting and reading back
row := &JobRow{
JobID: "test-job-1",
ScriptPath: "jobs/test-job-1/script",
OutputPath: "jobs/test-job-1/output.log",
Mode: jobmode.PTY,
Cwd: "/tmp",
TerminalCols: 80,
TerminalRows: 24,
Status: StatusCreated,
SessionName: "shellctl-test-job-1",
PaneTarget: "shellctl-test-job-1:0.0",
CreatedAt: "2025-01-01T00:00:00Z",
UpdatedAt: "2025-01-01T00:00:00Z",
}
ok, err := db.InsertJob(row)
if err != nil {
t.Fatalf("InsertJob: %v", err)
}
if !ok {
t.Error("expected insert to succeed (ok=true)")
}
// Duplicate insert should return ok=false
ok, err = db.InsertJob(row)
if err != nil {
t.Fatalf("InsertJob duplicate: %v", err)
}
if ok {
t.Error("expected duplicate insert to return ok=false")
}
if got := schemaVersion(t, db); got != latestSchemaVersion {
t.Errorf("schema version = %d, want %d", got, latestSchemaVersion)
}
}
func TestInitSchemaMigratesV0JobsToPTY(t *testing.T) {
db := openTestDB(t, t.TempDir())
defer func() { _ = db.Close() }()
if err := db.createSchemaV0(); err != nil {
t.Fatalf("createSchemaV0: %v", err)
}
_, err := db.db.Exec(`
INSERT INTO jobs (
job_id, script_path, output_path, cwd, terminal_cols, terminal_rows,
status, session_name, pane_target, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
"legacy-job", "jobs/legacy-job/script", "jobs/legacy-job/output.log", "/tmp",
80, 24, "created", "shellctl-legacy-job", "shellctl-legacy-job:0.0",
"2025-01-01T00:00:00Z", "2025-01-01T00:00:00Z",
)
if err != nil {
t.Fatalf("insert legacy job: %v", err)
}
if err := db.InitSchema(); err != nil {
t.Fatalf("InitSchema: %v", err)
}
row, err := db.GetJob("legacy-job")
if err != nil {
t.Fatalf("GetJob: %v", err)
}
if row.Mode != jobmode.PTY {
t.Errorf("legacy job mode = %q, want %q", row.Mode, jobmode.PTY)
}
if got := schemaVersion(t, db); got != latestSchemaVersion {
t.Errorf("schema version = %d, want %d", got, latestSchemaVersion)
}
}
func TestInitSchemaAtLatestVersionIsIdempotent(t *testing.T) {
db := setupTestDB(t, t.TempDir())
defer func() { _ = db.Close() }()
if err := db.InitSchema(); err != nil {
t.Fatalf("second InitSchema: %v", err)
}
if got := schemaVersion(t, db); got != latestSchemaVersion {
t.Errorf("schema version = %d, want %d", got, latestSchemaVersion)
}
}
func TestInitSchemaRejectsNewerDatabaseWithoutDDL(t *testing.T) {
db := openTestDB(t, t.TempDir())
defer func() { _ = db.Close() }()
if _, err := db.db.Exec("PRAGMA user_version = 2"); err != nil {
t.Fatalf("set future schema version: %v", err)
}
if err := db.InitSchema(); err == nil {
t.Fatal("InitSchema unexpectedly accepted a newer schema")
}
var tableCount int
if err := db.db.QueryRow(`SELECT count(*) FROM sqlite_master WHERE type='table' AND name='jobs'`).Scan(&tableCount); err != nil {
t.Fatalf("query jobs table: %v", err)
}
if tableCount != 0 {
t.Errorf("jobs table count = %d, want 0", tableCount)
}
}
func TestApplySchemaMigrationFailureRollsBackDDLAndVersion(t *testing.T) {
db := openTestDB(t, t.TempDir())
defer func() { _ = db.Close() }()
if err := db.createSchemaV0(); err != nil {
t.Fatalf("createSchemaV0: %v", err)
}
sentinel := errors.New("sentinel migration failure")
err := db.applySchemaMigration(1, func(tx *sql.Tx) error {
if _, err := tx.Exec(`ALTER TABLE jobs ADD COLUMN rollback_probe TEXT`); err != nil {
return err
}
return sentinel
})
if !errors.Is(err, sentinel) {
t.Fatalf("migration error = %v, want sentinel failure", err)
}
var probeColumns int
if err := db.db.QueryRow(`SELECT count(*) FROM pragma_table_info('jobs') WHERE name = 'rollback_probe'`).Scan(&probeColumns); err != nil {
t.Fatalf("query rollback probe column: %v", err)
}
if probeColumns != 0 {
t.Errorf("rollback_probe column count = %d, want 0", probeColumns)
}
if got := schemaVersion(t, db); got != 0 {
t.Errorf("schema version = %d, want 0", got)
}
}
func TestGetJob(t *testing.T) {
dir := t.TempDir()
db := setupTestDB(t, dir)
defer func() { _ = db.Close() }()
insertTestJob(t, db, "job-get-1", StatusCreated)
row, err := db.GetJob("job-get-1")
if err != nil {
t.Fatalf("GetJob: %v", err)
}
if row.JobID != "job-get-1" {
t.Errorf("expected job_id=job-get-1, got %s", row.JobID)
}
if row.Status != StatusCreated {
t.Errorf("expected status=created, got %s", row.Status)
}
if row.TerminalCols != 80 {
t.Errorf("expected cols=80, got %d", row.TerminalCols)
}
if row.Mode != jobmode.PTY {
t.Errorf("expected mode=pty, got %s", row.Mode)
}
}
func TestGetJobNotFound(t *testing.T) {
dir := t.TempDir()
db := setupTestDB(t, dir)
defer func() { _ = db.Close() }()
_, err := db.GetJob("nonexistent")
if err != ErrJobNotFound {
t.Errorf("expected ErrJobNotFound, got %v", err)
}
}
func TestListJobs(t *testing.T) {
dir := t.TempDir()
db := setupTestDB(t, dir)
defer func() { _ = db.Close() }()
insertTestJob(t, db, "job-list-1", StatusRunning)
insertTestJob(t, db, "job-list-2", StatusExited)
insertTestJob(t, db, "job-list-3", StatusCreated)
// List all
rows, err := db.ListJobs(nil)
if err != nil {
t.Fatalf("ListJobs: %v", err)
}
if len(rows) != 3 {
t.Errorf("expected 3 jobs, got %d", len(rows))
}
// List by status
rows, err = db.ListJobs([]JobStatusName{StatusRunning})
if err != nil {
t.Fatalf("ListJobs filtered: %v", err)
}
if len(rows) != 1 {
t.Errorf("expected 1 running job, got %d", len(rows))
}
if rows[0].JobID != "job-list-1" {
t.Errorf("expected job-list-1, got %s", rows[0].JobID)
}
}
func TestDeleteJob(t *testing.T) {
dir := t.TempDir()
db := setupTestDB(t, dir)
defer func() { _ = db.Close() }()
insertTestJob(t, db, "job-del-1", StatusExited)
if err := db.DeleteJob("job-del-1"); err != nil {
t.Fatalf("DeleteJob: %v", err)
}
_, err := db.GetJob("job-del-1")
if err != ErrJobNotFound {
t.Errorf("expected ErrJobNotFound after delete, got %v", err)
}
}
func TestDeleteJobNotFound(t *testing.T) {
dir := t.TempDir()
db := setupTestDB(t, dir)
defer func() { _ = db.Close() }()
err := db.DeleteJob("nonexistent")
if err != ErrJobNotFound {
t.Errorf("expected ErrJobNotFound, got %v", err)
}
}
func TestTransitionStatus(t *testing.T) {
dir := t.TempDir()
db := setupTestDB(t, dir)
defer func() { _ = db.Close() }()
insertTestJob(t, db, "job-trans-1", StatusCreated)
// Transition created → starting
row, err := db.TransitionStatus("job-trans-1", TransitionOpts{
AllowedFrom: []JobStatusName{StatusCreated},
Target: StatusStarting,
})
if err != nil {
t.Fatalf("TransitionStatus: %v", err)
}
if row.Status != StatusStarting {
t.Errorf("expected starting, got %s", row.Status)
}
// Transition starting → running
row, err = db.TransitionStatus("job-trans-1", TransitionOpts{
AllowedFrom: []JobStatusName{StatusStarting},
Target: StatusRunning,
RequireExitCodeNull: true,
})
if err != nil {
t.Fatalf("TransitionStatus: %v", err)
}
if row.Status != StatusRunning {
t.Errorf("expected running, got %s", row.Status)
}
// Transition running → exited
exitCode := 0
row, err = db.TransitionStatus("job-trans-1", TransitionOpts{
AllowedFrom: []JobStatusName{StatusRunning},
Target: StatusExited,
})
if err != nil {
t.Fatalf("TransitionStatus: %v", err)
}
if row.Status != StatusExited {
t.Errorf("expected exited, got %s", row.Status)
}
if row.ExitCode == nil {
t.Error("expected exit_code to be set after exited transition")
} else if *row.ExitCode != exitCode {
t.Errorf("expected exit_code=0, got %d", *row.ExitCode)
}
if row.EndedAt == nil {
t.Error("expected ended_at to be set after terminal transition")
}
}
func TestRecordRunnerExit(t *testing.T) {
dir := t.TempDir()
db := setupTestDB(t, dir)
defer func() { _ = db.Close() }()
insertTestJob(t, db, "job-exit-1", StatusRunning)
if err := db.RecordRunnerExit("job-exit-1", 42, "2025-01-15T12:00:00Z"); err != nil {
t.Fatalf("RecordRunnerExit: %v", err)
}
row, _ := db.GetJob("job-exit-1")
if row.Status != StatusExited {
t.Errorf("expected exited, got %s", row.Status)
}
if row.ExitCode == nil || *row.ExitCode != 42 {
t.Errorf("expected exit_code=42, got %v", row.ExitCode)
}
}
func TestRecordRunnerExitIdempotent(t *testing.T) {
dir := t.TempDir()
db := setupTestDB(t, dir)
defer func() { _ = db.Close() }()
insertTestJob(t, db, "job-exit-2", StatusExited)
exitCode := 10
row := &JobRow{
JobID: "job-exit-2", ScriptPath: "x", OutputPath: "y", Cwd: "/tmp",
Mode: jobmode.PTY,
TerminalCols: 80, TerminalRows: 24, Status: StatusExited,
SessionName: "s", PaneTarget: "p", ExitCode: &exitCode,
CreatedAt: "2025-01-01T00:00:00Z", UpdatedAt: "2025-01-01T00:00:00Z",
EndedAt: strPtr("2025-01-01T00:01:00Z"),
}
_, _ = db.db.Exec(`UPDATE jobs SET exit_code=?, ended_at=? WHERE job_id=?`,
exitCode, "2025-01-01T00:01:00Z", "job-exit-2")
_ = row
// Should not overwrite existing terminal state
err := db.RecordRunnerExit("job-exit-2", 99, "2025-01-01T00:02:00Z")
if err != nil {
t.Fatalf("RecordRunnerExit on terminal: %v", err)
}
got, _ := db.GetJob("job-exit-2")
if got.ExitCode != nil && *got.ExitCode != 10 {
t.Errorf("expected exit_code=10 (preserved), got %d", *got.ExitCode)
}
}
// Helpers
func setupTestDB(t *testing.T, dir string) *DB {
t.Helper()
db := openTestDB(t, dir)
if err := db.InitSchema(); err != nil {
t.Fatalf("InitSchema: %v", err)
}
return db
}
func openTestDB(t *testing.T, dir string) *DB {
t.Helper()
dbPath := filepath.Join(dir, "shellctl.db")
db, err := OpenDB(dbPath, 5000)
if err != nil {
t.Fatalf("OpenDB: %v", err)
}
return db
}
func schemaVersion(t *testing.T, db *DB) int {
t.Helper()
var version int
if err := db.db.QueryRow("PRAGMA user_version").Scan(&version); err != nil {
t.Fatalf("read schema version: %v", err)
}
return version
}
func insertTestJob(t *testing.T, db *DB, jobID string, status JobStatusName) {
t.Helper()
row := &JobRow{
JobID: jobID,
ScriptPath: "jobs/" + jobID + "/script",
OutputPath: "jobs/" + jobID + "/output.log",
Mode: jobmode.PTY,
Cwd: "/tmp",
TerminalCols: 80,
TerminalRows: 24,
Status: status,
SessionName: "shellctl-" + jobID,
PaneTarget: "shellctl-" + jobID + ":0.0",
CreatedAt: "2025-01-01T00:00:00Z",
UpdatedAt: "2025-01-01T00:00:00Z",
}
ok, err := db.InsertJob(row)
if err != nil || !ok {
t.Fatalf("InsertJob(%s): err=%v ok=%v", jobID, err, ok)
}
}
func strPtr(s string) *string {
return &s
}
func TestMain(m *testing.M) {
os.Exit(m.Run())
}
@@ -0,0 +1,22 @@
package server
import "fmt"
// ServerError is a structured error with HTTP status code and machine-readable code.
type ServerError struct {
StatusCode int
Code string
Message string
}
func (e *ServerError) Error() string {
return fmt.Sprintf("[%d] %s: %s", e.StatusCode, e.Code, e.Message)
}
// Common sentinel errors.
var ErrJobNotFound = &ServerError{StatusCode: 404, Code: "job_not_found", Message: "Unknown job id"}
// NewServerError creates a new ServerError.
func NewServerError(statusCode int, code, message string) *ServerError {
return &ServerError{StatusCode: statusCode, Code: code, Message: message}
}
@@ -0,0 +1,167 @@
package server
import (
"fmt"
"os"
"unicode/utf8"
)
// OutputWindow represents a UTF-8-safe slice of output.log.
type OutputWindow struct {
Output string `json:"output"`
Offset int `json:"offset"`
Truncated bool `json:"truncated"`
}
// ReadOutputWindow reads a forward UTF-8-safe slice from an output file.
func ReadOutputWindow(path string, offset, limit int) (*OutputWindow, error) {
info, err := os.Stat(path)
if os.IsNotExist(err) {
if offset == 0 {
return &OutputWindow{Output: "", Offset: 0, Truncated: false}, nil
}
return nil, NewServerError(400, "invalid_offset", "offset exceeds current file size 0")
}
if err != nil {
return nil, err
}
size := int(info.Size())
if offset > size {
return nil, NewServerError(400, "invalid_offset",
fmt.Sprintf("offset %d exceeds current file size %d", offset, size))
}
if offset == size {
return &OutputWindow{Output: "", Offset: offset, Truncated: false}, nil
}
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer func() { _ = f.Close() }()
// Read up to limit+4 bytes to handle UTF-8 boundary
readSize := limit + 4
if offset+readSize > size {
readSize = size - offset
}
buf := make([]byte, readSize)
_, err = f.ReadAt(buf, int64(offset))
if err != nil {
return nil, err
}
// Advance past any UTF-8 continuation bytes at the start
startShift := advanceToUTF8Boundary(buf, 0)
data := buf[startShift:]
budget := limit - startShift
if budget < 0 {
budget = 0
}
// Find the longest valid UTF-8 prefix within budget
consumed := validUTF8PrefixLen(data, budget)
if consumed == 0 && len(data) > 0 {
// At least consume one complete rune
consumed = firstCompleteRuneLen(data)
}
outputBytes := data[:consumed]
newOffset := offset + startShift + consumed
truncated := newOffset < size
return &OutputWindow{
Output: string(outputBytes),
Offset: newOffset,
Truncated: truncated,
}, nil
}
// TailOutputWindow reads a UTF-8-safe tail snapshot from an output file.
func TailOutputWindow(path string, limit int) (*OutputWindow, error) {
info, err := os.Stat(path)
if os.IsNotExist(err) {
return &OutputWindow{Output: "", Offset: 0, Truncated: false}, nil
}
if err != nil {
return nil, err
}
size := int(info.Size())
if size == 0 {
return &OutputWindow{Output: "", Offset: 0, Truncated: false}, nil
}
start := size - limit
if start < 0 {
start = 0
}
paddedStart := start - 4
if paddedStart < 0 {
paddedStart = 0
}
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer func() { _ = f.Close() }()
readLen := size - paddedStart
buf := make([]byte, readLen)
_, err = f.ReadAt(buf, int64(paddedStart))
if err != nil {
return nil, err
}
relativeStart := advanceToUTF8Boundary(buf, start-paddedStart)
payload := buf[relativeStart:]
consumed := validUTF8PrefixLen(payload, len(payload))
outputBytes := payload[:consumed]
return &OutputWindow{
Output: string(outputBytes),
Offset: paddedStart + relativeStart + consumed,
Truncated: false,
}, nil
}
// advanceToUTF8Boundary skips continuation bytes (10xxxxxx) at position start.
func advanceToUTF8Boundary(data []byte, start int) int {
for start < len(data) && isUTF8Continuation(data[start]) {
start++
}
return start
}
// isUTF8Continuation returns true if byte is a UTF-8 continuation byte.
func isUTF8Continuation(b byte) bool {
return (b & 0xC0) == 0x80
}
// validUTF8PrefixLen returns the length of the longest valid UTF-8 prefix up to maxLen.
func validUTF8PrefixLen(data []byte, maxLen int) int {
if maxLen > len(data) {
maxLen = len(data)
}
end := maxLen
for end > 0 {
if utf8.Valid(data[:end]) {
return end
}
end--
}
return 0
}
// firstCompleteRuneLen returns the byte length of the first complete rune in data.
func firstCompleteRuneLen(data []byte) int {
for end := 1; end <= len(data) && end <= 4; end++ {
if utf8.Valid(data[:end]) {
return end
}
}
return 0
}
@@ -0,0 +1,275 @@
package server
import (
"os"
"path/filepath"
"testing"
)
func TestReadOutputWindowEmptyFile(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "output.log")
if err := os.WriteFile(path, []byte{}, 0644); err != nil {
t.Fatal(err)
}
w, err := ReadOutputWindow(path, 0, 1024)
if err != nil {
t.Fatalf("ReadOutputWindow: %v", err)
}
if w.Output != "" {
t.Errorf("expected empty output, got %q", w.Output)
}
if w.Offset != 0 {
t.Errorf("expected offset=0, got %d", w.Offset)
}
if w.Truncated {
t.Error("expected truncated=false")
}
}
func TestReadOutputWindowNonexistentFile(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "nonexistent.log")
w, err := ReadOutputWindow(path, 0, 1024)
if err != nil {
t.Fatalf("ReadOutputWindow: %v", err)
}
if w.Output != "" {
t.Errorf("expected empty output, got %q", w.Output)
}
}
func TestReadOutputWindowFullContent(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "output.log")
content := "hello\nworld\n"
if err := os.WriteFile(path, []byte(content), 0644); err != nil {
t.Fatal(err)
}
w, err := ReadOutputWindow(path, 0, 1024)
if err != nil {
t.Fatalf("ReadOutputWindow: %v", err)
}
if w.Output != content {
t.Errorf("expected %q, got %q", content, w.Output)
}
if w.Truncated {
t.Error("expected truncated=false")
}
}
func TestReadOutputWindowWithOffset(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "output.log")
content := "hello\nworld\n"
if err := os.WriteFile(path, []byte(content), 0644); err != nil {
t.Fatal(err)
}
w, err := ReadOutputWindow(path, 6, 1024)
if err != nil {
t.Fatalf("ReadOutputWindow: %v", err)
}
if w.Output != "world\n" {
t.Errorf("expected 'world\\n', got %q", w.Output)
}
if w.Offset != len(content) {
t.Errorf("expected offset=%d, got %d", len(content), w.Offset)
}
}
func TestReadOutputWindowTruncated(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "output.log")
content := "0123456789"
if err := os.WriteFile(path, []byte(content), 0644); err != nil {
t.Fatal(err)
}
// Read only 5 bytes
w, err := ReadOutputWindow(path, 0, 5)
if err != nil {
t.Fatalf("ReadOutputWindow: %v", err)
}
if w.Output != "01234" {
t.Errorf("expected '01234', got %q", w.Output)
}
if !w.Truncated {
t.Error("expected truncated=true")
}
if w.Offset != 5 {
t.Errorf("expected offset=5, got %d", w.Offset)
}
}
func TestReadOutputWindowOffsetExceedsSize(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "output.log")
if err := os.WriteFile(path, []byte("short"), 0644); err != nil {
t.Fatal(err)
}
_, err := ReadOutputWindow(path, 100, 1024)
if err == nil {
t.Error("expected error for offset > size")
}
}
func TestReadOutputWindowOffsetAtEnd(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "output.log")
content := "hello"
if err := os.WriteFile(path, []byte(content), 0644); err != nil {
t.Fatal(err)
}
w, err := ReadOutputWindow(path, len(content), 1024)
if err != nil {
t.Fatalf("ReadOutputWindow: %v", err)
}
if w.Output != "" {
t.Errorf("expected empty output at end, got %q", w.Output)
}
if w.Offset != len(content) {
t.Errorf("expected offset=%d, got %d", len(content), w.Offset)
}
}
func TestReadOutputWindowMultibyteUTF8(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "output.log")
content := "hello 世界\n"
if err := os.WriteFile(path, []byte(content), 0644); err != nil {
t.Fatal(err)
}
w, err := ReadOutputWindow(path, 0, 1024)
if err != nil {
t.Fatalf("ReadOutputWindow: %v", err)
}
if w.Output != content {
t.Errorf("expected %q, got %q", content, w.Output)
}
}
func TestReadOutputWindowMultibyteTruncated(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "output.log")
// "世" = 3 bytes (E4 B8 96), "界" = 3 bytes (E7 95 8C)
content := "世界"
if err := os.WriteFile(path, []byte(content), 0644); err != nil {
t.Fatal(err)
}
// Read only 4 bytes — should not split a multibyte char
w, err := ReadOutputWindow(path, 0, 4)
if err != nil {
t.Fatalf("ReadOutputWindow: %v", err)
}
// Should get "世" (3 bytes), not partial "界"
if w.Output != "世" {
t.Errorf("expected '世', got %q", w.Output)
}
if !w.Truncated {
t.Error("expected truncated=true")
}
}
func TestTailOutputWindow(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "output.log")
content := "line1\nline2\nline3\n"
if err := os.WriteFile(path, []byte(content), 0644); err != nil {
t.Fatal(err)
}
w, err := TailOutputWindow(path, 100)
if err != nil {
t.Fatalf("TailOutputWindow: %v", err)
}
if w.Output != content {
t.Errorf("expected %q, got %q", content, w.Output)
}
}
func TestTailOutputWindowLimited(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "output.log")
content := "0123456789"
if err := os.WriteFile(path, []byte(content), 0644); err != nil {
t.Fatal(err)
}
w, err := TailOutputWindow(path, 5)
if err != nil {
t.Fatalf("TailOutputWindow: %v", err)
}
if w.Output != "56789" {
t.Errorf("expected '56789', got %q", w.Output)
}
}
func TestTailOutputWindowNonexistent(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "nonexistent.log")
w, err := TailOutputWindow(path, 100)
if err != nil {
t.Fatalf("TailOutputWindow: %v", err)
}
if w.Output != "" {
t.Errorf("expected empty, got %q", w.Output)
}
}
func TestTailOutputWindowEmpty(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "empty.log")
if err := os.WriteFile(path, []byte{}, 0644); err != nil {
t.Fatal(err)
}
w, err := TailOutputWindow(path, 100)
if err != nil {
t.Fatalf("TailOutputWindow: %v", err)
}
if w.Output != "" {
t.Errorf("expected empty, got %q", w.Output)
}
}
func TestIsUTF8Continuation(t *testing.T) {
// ASCII bytes are not continuation bytes
if isUTF8Continuation('a') {
t.Error("'a' should not be a continuation byte")
}
// 0x80-0xBF are continuation bytes
if !isUTF8Continuation(0x80) {
t.Error("0x80 should be a continuation byte")
}
if !isUTF8Continuation(0xBF) {
t.Error("0xBF should be a continuation byte")
}
// 0xC0 is not a continuation byte (it's a lead byte)
if isUTF8Continuation(0xC0) {
t.Error("0xC0 should not be a continuation byte")
}
}
func TestAdvanceToUTF8Boundary(t *testing.T) {
// "世" = E4 B8 96, continuation bytes at index 1 and 2
data := []byte{0xE4, 0xB8, 0x96, 0x41} // 世 + A
// Start at 1, should advance to 3 (the 'A')
result := advanceToUTF8Boundary(data, 1)
if result != 3 {
t.Errorf("expected 3, got %d", result)
}
// Start at 0 (lead byte), should stay at 0
result = advanceToUTF8Boundary(data, 0)
if result != 0 {
t.Errorf("expected 0, got %d", result)
}
}
@@ -0,0 +1,35 @@
package server
import (
"crypto/rand"
"encoding/hex"
"fmt"
"time"
)
// GenerateJobID produces a short random hex job identifier.
func GenerateJobID() string {
b := make([]byte, 8)
_, _ = rand.Read(b)
return hex.EncodeToString(b)
}
// FormatTimestamp returns an ISO-8601 UTC timestamp string.
func FormatTimestamp(t time.Time) string {
return t.UTC().Truncate(time.Second).Format("2006-01-02T15:04:05Z")
}
// ParseTimestamp parses an ISO-8601 UTC timestamp.
func ParseTimestamp(s string) (time.Time, error) {
return time.Parse("2006-01-02T15:04:05Z", s)
}
// JobSessionName returns the tmux session name for a job.
func JobSessionName(jobID string) string {
return fmt.Sprintf("shellctl-%s", jobID)
}
// JobPaneTarget returns the tmux pane target for a job.
func JobPaneTarget(jobID string) string {
return fmt.Sprintf("%s:0.0", JobSessionName(jobID))
}
@@ -0,0 +1,71 @@
package server
import (
"testing"
"time"
)
func TestGenerateJobID(t *testing.T) {
id1 := GenerateJobID()
id2 := GenerateJobID()
if id1 == id2 {
t.Error("expected different job IDs")
}
if len(id1) != 16 {
t.Errorf("expected 16-char hex ID, got %d chars: %s", len(id1), id1)
}
}
func TestGenerateJobIDUniqueness(t *testing.T) {
seen := make(map[string]bool, 1000)
for i := 0; i < 1000; i++ {
id := GenerateJobID()
if seen[id] {
t.Fatalf("collision at iteration %d: %s", i, id)
}
seen[id] = true
}
}
func TestFormatTimestamp(t *testing.T) {
ts := time.Date(2025, 1, 15, 12, 30, 45, 0, time.UTC)
formatted := FormatTimestamp(ts)
expected := "2025-01-15T12:30:45Z"
if formatted != expected {
t.Errorf("expected %q, got %q", expected, formatted)
}
}
func TestParseTimestamp(t *testing.T) {
parsed, err := ParseTimestamp("2025-01-15T12:30:45Z")
if err != nil {
t.Fatalf("parse error: %v", err)
}
if parsed.Year() != 2025 || parsed.Month() != 1 || parsed.Day() != 15 {
t.Errorf("unexpected parsed time: %v", parsed)
}
if parsed.Hour() != 12 || parsed.Minute() != 30 || parsed.Second() != 45 {
t.Errorf("unexpected parsed time: %v", parsed)
}
}
func TestParseTimestampInvalid(t *testing.T) {
_, err := ParseTimestamp("not-a-timestamp")
if err == nil {
t.Error("expected error for invalid timestamp")
}
}
func TestJobSessionName(t *testing.T) {
name := JobSessionName("abc123")
if name != "shellctl-abc123" {
t.Errorf("expected 'shellctl-abc123', got %q", name)
}
}
func TestJobPaneTarget(t *testing.T) {
target := JobPaneTarget("abc123")
if target != "shellctl-abc123:0.0" {
t.Errorf("expected 'shellctl-abc123:0.0', got %q", target)
}
}
@@ -0,0 +1,6 @@
// Package server implements the shellctl HTTP API and job lifecycle service.
//
// This is the Go equivalent of shellctl/server/ in the Python implementation.
// It manages tmux-backed shell jobs with SQLite persistence and provides
// REST endpoints for run, wait, input, terminate, and delete operations.
package server
@@ -0,0 +1,913 @@
package server
import (
"context"
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/langgenius/dify/dify-agent-runtime/internal/jobmode"
)
// Service is the core job lifecycle manager backed by SQLite and tmux.
type Service struct {
config *Config
db *DB
tmux *TmuxController
startingJobs map[string]bool
mu sync.Mutex
cancelGC context.CancelFunc
cancelMon context.CancelFunc
}
// NewService creates a new shellctl service.
func NewService(config *Config) *Service {
return &Service{
config: config,
tmux: NewTmuxController(config),
startingJobs: make(map[string]bool),
}
}
// Initialize performs the full server startup (prepare + reconcile + gc).
func (s *Service) Initialize() error {
if err := s.PrepareRuntime(); err != nil {
return err
}
if err := s.Reconcile(); err != nil {
return err
}
return s.GCOnce()
}
// PrepareRuntime sets up directories, DB schema, runner script, and tmux server.
func (s *Service) PrepareRuntime() error {
if err := os.MkdirAll(s.config.StateDir, 0700); err != nil {
return err
}
if err := os.MkdirAll(s.config.RuntimeDir, 0700); err != nil {
return err
}
if err := os.MkdirAll(s.config.JobsDir(), 0700); err != nil {
return err
}
runnerDir := filepath.Dir(s.config.RunnerPath())
if err := os.MkdirAll(runnerDir, 0700); err != nil {
return err
}
db, err := OpenDB(s.config.DBPath(), s.config.SQLiteBusyTimeoutMs)
if err != nil {
return err
}
s.db = db
if err := s.db.InitSchema(); err != nil {
return err
}
s.installRunner()
return s.tmux.StartServer()
}
// Shutdown stops background goroutines and closes the database.
func (s *Service) Shutdown() {
if s.cancelGC != nil {
s.cancelGC()
}
if s.cancelMon != nil {
s.cancelMon()
}
if s.db != nil {
_ = s.db.Close()
}
}
// StartBackgroundGC starts the periodic GC goroutine.
func (s *Service) StartBackgroundGC() {
ctx, cancel := context.WithCancel(context.Background())
s.cancelGC = cancel
go func() {
ticker := time.NewTicker(s.config.GCInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
_ = s.GCOnce()
}
}
}()
}
// StartBackgroundPipeMonitor periodically reconciles mode-aware runtime state:
// PTY pane pipe/drain state, and stdio session state plus completion
// materialization from exit artifacts.
func (s *Service) StartBackgroundPipeMonitor() {
ctx, cancel := context.WithCancel(context.Background())
s.cancelMon = cancel
go func() {
ticker := time.NewTicker(s.config.PipeMonitorInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
s.CheckRunningJobsPipeHealth()
}
}
}()
}
// RunJob creates and starts a new tmux-backed job, then waits for initial output.
func (s *Service) RunJob(req *RunJobRequest) (*JobResult, error) {
log.Printf("RunJob: script=%d bytes, cwd=%v, env_keys=%d", len(req.Script), req.Cwd, len(req.Env))
cwd, err := s.resolveCwd(req.Cwd)
if err != nil {
log.Printf("RunJob: resolveCwd failed: %v", err)
return nil, err
}
cols := s.config.DefaultTerminalCols
rows := s.config.DefaultTerminalRows
if req.Terminal != nil {
cols = req.Terminal.Cols
rows = req.Terminal.Rows
}
timeout := s.config.DefaultTimeout
if req.Timeout > 0 {
timeout = time.Duration(req.Timeout * float64(time.Second))
}
outputLimit := s.config.DefaultOutputLimitBytes
if req.OutputLimit > 0 {
outputLimit = req.OutputLimit
}
idleFlush := s.config.IdleFlushDuration
if req.IdleFlushSeconds > 0 {
idleFlush = time.Duration(req.IdleFlushSeconds * float64(time.Second))
}
createdAt := FormatTimestamp(time.Now())
// Allocate job directory and insert DB row
jobID, jobDir, err := s.allocateJobDir()
if err != nil {
return nil, err
}
s.mu.Lock()
s.startingJobs[jobID] = true
s.mu.Unlock()
// Write script and env files
scriptPath := filepath.Join(jobDir, "script")
outputPath := filepath.Join(jobDir, "output.log")
envPath := filepath.Join(jobDir, ".job-env.json")
if err := os.WriteFile(scriptPath, []byte(req.Script), 0600); err != nil {
s.cleanupStarting(jobID, jobDir)
return nil, err
}
envJSON := "{}"
if req.Env != nil {
pairs := make([]string, 0, len(req.Env))
for k, v := range req.Env {
pairs = append(pairs, fmt.Sprintf("%q:%q", k, v))
}
envJSON = "{" + strings.Join(pairs, ",") + "}"
}
if err := os.WriteFile(envPath, []byte(envJSON), 0600); err != nil {
s.cleanupStarting(jobID, jobDir)
return nil, err
}
if err := os.WriteFile(outputPath, []byte{}, 0600); err != nil {
s.cleanupStarting(jobID, jobDir)
return nil, err
}
row := &JobRow{
JobID: jobID,
ScriptPath: fmt.Sprintf("jobs/%s/script", jobID),
OutputPath: fmt.Sprintf("jobs/%s/output.log", jobID),
Mode: req.Mode,
Cwd: cwd,
TerminalCols: cols,
TerminalRows: rows,
Status: StatusCreated,
SessionName: JobSessionName(jobID),
PaneTarget: JobPaneTarget(jobID),
CreatedAt: createdAt,
UpdatedAt: createdAt,
}
ok, err := s.db.InsertJob(row)
if err != nil {
s.cleanupStarting(jobID, jobDir)
return nil, err
}
if !ok {
s.cleanupStarting(jobID, jobDir)
return nil, NewServerError(500, "job_id_collision", "Failed to allocate a unique job id")
}
// Transition to starting
_, _ = s.db.TransitionStatus(jobID, TransitionOpts{
AllowedFrom: []JobStatusName{StatusCreated},
Target: StatusStarting,
})
// Start the mode-specific runtime: PTY manages pane piping and drain, while
// stdio tracks the session and materializes completion from exit artifacts.
log.Printf("RunJob [%s]: starting job, cwd=%s", jobID, cwd)
startErr := s.startJob(jobID, jobDir, cwd, cols, rows, req.Mode)
if startErr != nil {
log.Printf("RunJob [%s]: start failed: %v", jobID, startErr)
reason := "start_failed"
msg := startErr.Error()
_, _ = s.db.TransitionStatus(jobID, TransitionOpts{
AllowedFrom: []JobStatusName{StatusCreated, StatusStarting, StatusRunning},
Target: StatusFailed,
Reason: &reason,
Message: &msg,
})
s.tmux.CleanupSession(jobID)
} else {
log.Printf("RunJob [%s]: started successfully", jobID)
}
s.mu.Lock()
delete(s.startingJobs, jobID)
s.mu.Unlock()
// Wait for initial output
return s.WaitJob(jobID, &WaitJobRequest{
Offset: 0,
Timeout: timeout.Seconds(),
OutputLimit: outputLimit,
IdleFlushSeconds: idleFlush.Seconds(),
})
}
func (s *Service) startJob(jobID, jobDir, cwd string, cols, rows int, mode jobmode.Mode) error {
log.Printf("startJob [%s]: creating tmux session", jobID)
if err := s.tmux.CreateJobSession(jobID, jobDir, cwd, cols, rows, mode); err != nil {
log.Printf("startJob [%s]: tmux session failed: %v", jobID, err)
return err
}
pipeReadyPath := filepath.Join(jobDir, ".pipe-ready")
if mode == jobmode.PTY {
log.Printf("startJob [%s]: enabling output pipe", jobID)
if err := s.tmux.EnableOutputPipe(jobID, jobDir, pipeReadyPath); err != nil {
log.Printf("startJob [%s]: pipe-pane failed: %v", jobID, err)
return err
}
// Wait for pipe ready handshake
if err := s.waitForPipeReady(jobID, pipeReadyPath); err != nil {
log.Printf("startJob [%s]: pipe-ready timeout: %v", jobID, err)
return err
}
}
// Open start gate
log.Printf("startJob [%s]: opening start gate", jobID)
gateFile := filepath.Join(jobDir, "start-gate")
if err := os.WriteFile(gateFile, []byte{}, 0600); err != nil {
return err
}
// Transition to running
_, _ = s.db.TransitionStatus(jobID, TransitionOpts{
AllowedFrom: []JobStatusName{StatusStarting},
Target: StatusRunning,
RequireExitCodeNull: true,
})
if mode == jobmode.PTY {
_ = os.Remove(pipeReadyPath)
}
return nil
}
func (s *Service) waitForPipeReady(jobID, readyFile string) error {
deadline := time.Now().Add(s.config.PipeReadyTimeout)
for {
if _, err := os.Stat(readyFile); err == nil {
// Ready file exists, verify pipe is active
active, err := s.tmux.IsOutputPipeActive(jobID)
if err != nil {
return err
}
if active == nil {
return NewServerError(500, "pipe_failed",
"tmux pane disappeared after ready-file handshake")
}
if *active {
return nil
}
}
if time.Now().After(deadline) {
return NewServerError(500, "pipe_failed",
fmt.Sprintf("timed out waiting for pipe ready (%v)", s.config.PipeReadyTimeout))
}
time.Sleep(s.config.PollInterval)
}
}
// WaitJob blocks until output, completion, truncation, or timeout.
func (s *Service) WaitJob(jobID string, req *WaitJobRequest) (*JobResult, error) {
row, err := s.db.GetJob(jobID)
if err != nil {
return nil, err
}
outputPath := s.outputLogPath(row)
timeout := time.Duration(req.Timeout * float64(time.Second))
outputLimit := req.OutputLimit
if outputLimit <= 0 {
outputLimit = s.config.DefaultOutputLimitBytes
}
idleFlush := time.Duration(req.IdleFlushSeconds * float64(time.Second))
deadline := time.Now().Add(timeout)
lastSize := fileSize(outputPath)
sawOutput := lastSize > int64(req.Offset)
var lastGrowthAt *time.Time
if sawOutput {
now := time.Now()
lastGrowthAt = &now
}
// Poll with exponential backoff: start tight so short jobs return with low
// latency, then grow the interval up to MaxPollInterval so long/idle waits
// stop spawning a tmux liveness probe (fork) every few milliseconds.
pollInterval := s.config.PollInterval
for {
view, err := s.GetJobStatus(jobID)
if err != nil {
return nil, err
}
currentSize := fileSize(outputPath)
// Validate offset against current file size (mirror Python behavior).
if int64(req.Offset) > currentSize {
return nil, NewServerError(400, "invalid_offset",
fmt.Sprintf("offset %d exceeds current file size %d", req.Offset, currentSize))
}
// Only update lastGrowthAt when the file actually grows (not just
// when currentSize > offset). Without this, lastGrowthAt resets on
// every poll and idle-flush can never fire.
if currentSize > lastSize {
lastSize = currentSize
if currentSize > int64(req.Offset) {
sawOutput = true
now := time.Now()
lastGrowthAt = &now
}
}
if view.Done {
window, err := ReadOutputWindow(outputPath, req.Offset, outputLimit)
if err != nil {
return nil, err
}
return s.jobResultFromView(view, row, window), nil
}
if currentSize > int64(req.Offset) {
window, err := ReadOutputWindow(outputPath, req.Offset, outputLimit)
if err != nil {
return nil, err
}
if window.Truncated {
return s.jobResultFromView(view, row, window), nil
}
if sawOutput && lastGrowthAt != nil {
if time.Since(*lastGrowthAt) >= idleFlush {
return s.jobResultFromView(view, row, window), nil
}
}
}
if time.Now().After(deadline) {
var window *OutputWindow
if currentSize > int64(req.Offset) {
window, err = ReadOutputWindow(outputPath, req.Offset, outputLimit)
if err != nil {
return nil, err
}
} else {
window = &OutputWindow{Output: "", Offset: req.Offset, Truncated: false}
}
return s.jobResultFromView(view, row, window), nil
}
time.Sleep(pollInterval)
pollInterval = min(pollInterval*2, s.config.MaxPollInterval)
}
}
// TailJob returns the tail of a job's output.
func (s *Service) TailJob(jobID string, outputLimit int) (*JobResult, error) {
row, err := s.db.GetJob(jobID)
if err != nil {
return nil, err
}
view, err := s.GetJobStatus(jobID)
if err != nil {
return nil, err
}
window, err := TailOutputWindow(s.outputLogPath(row), outputLimit)
if err != nil {
return nil, err
}
return s.jobResultFromView(view, row, window), nil
}
// GetJobStatus materializes the current status from SQLite + live tmux state.
func (s *Service) GetJobStatus(jobID string) (*JobStatusView, error) {
row, err := s.db.GetJob(jobID)
if err != nil {
return nil, err
}
sessionExists, pipeActive, err := s.liveRuntimeState(row)
if err != nil {
return nil, err
}
return s.materializeStatusView(row, sessionExists, pipeActive)
}
// ListJobs returns recent jobs, optionally filtered by status.
func (s *Service) ListJobs(status *JobStatusName, limit int) (*ListJobsResponse, error) {
rows, err := s.db.ListJobs(nil)
if err != nil {
return nil, err
}
var items []JobInfo
for _, row := range rows {
view, err := s.GetJobStatus(row.JobID)
if err != nil {
if isNotFound(err) {
continue
}
return nil, err
}
if status != nil && view.Status != *status {
continue
}
items = append(items, JobInfo{
JobID: view.JobID,
Status: view.Status,
CreatedAt: view.CreatedAt,
StartedAt: view.StartedAt,
EndedAt: view.EndedAt,
})
if len(items) >= limit {
break
}
}
return &ListJobsResponse{Jobs: items}, nil
}
// SendInput sends input to a running job and waits.
func (s *Service) SendInput(jobID string, req *InputJobRequest) (*JobResult, error) {
view, err := s.GetJobStatus(jobID)
if err != nil {
return nil, err
}
if view.Done {
return nil, NewServerError(409, "job_not_running", fmt.Sprintf("Job %s is already terminal", jobID))
}
row, err := s.db.GetJob(jobID)
if err != nil {
return nil, err
}
if row.Mode == jobmode.Stdio {
return nil, NewServerError(409, "input_unsupported", "stdio jobs do not support input")
}
if err := s.tmux.SendInput(jobID, req.Text); err != nil {
// Check if job became terminal in the meantime
if se, ok := err.(*ServerError); ok && se.Code == "tmux_target_missing" {
view, _ = s.GetJobStatus(jobID)
if view != nil && view.Done {
return nil, NewServerError(409, "job_not_running", fmt.Sprintf("Job %s is already terminal", jobID))
}
}
return nil, err
}
return s.WaitJob(jobID, &WaitJobRequest{
Offset: req.Offset,
Timeout: req.Timeout,
OutputLimit: req.OutputLimit,
IdleFlushSeconds: req.IdleFlushSeconds,
})
}
// TerminateJob terminates a running job.
func (s *Service) TerminateJob(jobID string, graceSeconds float64) (*JobStatusView, error) {
view, err := s.GetJobStatus(jobID)
if err != nil {
return nil, err
}
if view.Done {
s.tmux.CleanupSession(jobID)
return view, nil
}
_, _ = s.db.TransitionStatus(jobID, TransitionOpts{
AllowedFrom: []JobStatusName{StatusCreated, StatusStarting, StatusRunning},
AllowOverrideFrom: []JobStatusName{StatusExited},
Target: StatusTerminated,
})
_ = s.tmux.SendInterrupt(jobID)
if graceSeconds > 0 {
time.Sleep(time.Duration(graceSeconds * float64(time.Second)))
}
s.tmux.CleanupSession(jobID)
return s.GetJobStatus(jobID)
}
// DeleteJob deletes a job and its artifacts.
func (s *Service) DeleteJob(jobID string, force bool, graceSeconds float64) (*DeleteJobResponse, error) {
view, err := s.GetJobStatus(jobID)
if err != nil {
return nil, err
}
if !view.Done {
if !force {
return nil, NewServerError(409, "job_running", fmt.Sprintf("Job %s is still running", jobID))
}
_, _ = s.TerminateJob(jobID, graceSeconds)
}
s.tmux.CleanupSession(jobID)
if err := s.db.DeleteJob(jobID); err != nil {
return nil, err
}
_ = os.RemoveAll(filepath.Join(s.config.JobsDir(), jobID))
return &DeleteJobResponse{JobID: jobID, Deleted: true}, nil
}
// Reconcile synchronizes SQLite rows with live tmux state.
func (s *Service) Reconcile() error {
rows, err := s.db.ListJobs(nil)
if err != nil {
return err
}
for _, row := range rows {
view, err := s.GetJobStatus(row.JobID)
if err != nil {
if isNotFound(err) {
continue
}
return err
}
if view.Done {
s.tmux.CleanupSession(row.JobID)
}
}
return nil
}
// GCOnce removes expired terminal jobs.
func (s *Service) GCOnce() error {
cutoff := time.Now().Add(-s.config.GCFinishedJobRetention)
rows, err := s.db.ListJobs(nil)
if err != nil {
return err
}
for _, row := range rows {
view, err := s.GetJobStatus(row.JobID)
if err != nil {
if isNotFound(err) {
continue
}
return err
}
if !view.Done || view.EndedAt == nil {
continue
}
endedAt, err := ParseTimestamp(*view.EndedAt)
if err != nil {
continue
}
if endedAt.After(cutoff) {
continue
}
s.tmux.CleanupSession(row.JobID)
_ = s.db.DeleteJob(row.JobID)
_ = os.RemoveAll(filepath.Join(s.config.JobsDir(), row.JobID))
}
return nil
}
// CheckRunningJobsPipeHealth reconciles PTY pane pipe/drain state and stdio
// session state, materializing completion from exit artifacts.
func (s *Service) CheckRunningJobsPipeHealth() {
rows, _ := s.db.ListJobs([]JobStatusName{StatusRunning})
for _, row := range rows {
_, _ = s.GetJobStatus(row.JobID)
}
}
func (s *Service) materializeStatusView(row *JobRow, sessionExists bool, pipeActive *bool) (*JobStatusView, error) {
jobID := row.JobID
status := row.Status
if status.IsTerminal() {
// Ensure ended_at is set
if row.EndedAt == nil {
now := FormatTimestamp(time.Now())
_, _ = s.db.TransitionStatus(jobID, TransitionOpts{
AllowedFrom: []JobStatusName{status},
Target: status,
EndedAt: now,
})
if r, err := s.db.GetJob(jobID); err == nil {
row = r
}
}
} else if row.ExitCode != nil {
// Already has exit code, transition to exited
if r, err := s.db.TransitionStatus(jobID, TransitionOpts{
AllowedFrom: []JobStatusName{StatusCreated, StatusStarting, StatusRunning},
Target: StatusExited,
}); err == nil {
row = r
}
} else if exit := s.completedExitMetadata(row); exit != nil {
// Recover from mode-specific completed exit artifacts.
_ = s.db.RecordRunnerExit(jobID, exit.exitCode, exit.endedAt)
if r, err := s.db.GetJob(jobID); err == nil {
row = r
}
} else if sessionExists {
if row.Mode == jobmode.PTY && pipeActive != nil && !*pipeActive {
s.mu.Lock()
isStarting := s.startingJobs[jobID]
s.mu.Unlock()
if !isStarting {
reason := "pipe_failed"
msg := "The tmux output pipe stopped while the job was still running."
if r, err := s.db.TransitionStatus(jobID, TransitionOpts{
AllowedFrom: []JobStatusName{StatusCreated, StatusStarting, StatusRunning},
Target: StatusFailed,
Reason: &reason,
Message: &msg,
}); err == nil {
row = r
}
}
} else if status == StatusCreated || status == StatusStarting {
s.mu.Lock()
isStarting := s.startingJobs[jobID]
s.mu.Unlock()
if !isStarting {
if r, err := s.db.TransitionStatus(jobID, TransitionOpts{
AllowedFrom: []JobStatusName{StatusCreated, StatusStarting},
Target: StatusRunning,
RequireExitCodeNull: true,
}); err == nil {
row = r
}
}
}
} else {
// No session
if s.normalExitCommitPending(row) {
// Wait for pipe drain finalizer
} else {
s.mu.Lock()
isStarting := s.startingJobs[jobID]
s.mu.Unlock()
if !isStarting || (status != StatusCreated && status != StatusStarting) {
reason := "tmux_session_missing"
msg := "The dedicated tmux session is no longer present."
if r, err := s.db.TransitionStatus(jobID, TransitionOpts{
AllowedFrom: []JobStatusName{StatusCreated, StatusStarting, StatusRunning},
Target: StatusLost,
Reason: &reason,
Message: &msg,
}); err == nil {
row = r
}
}
}
}
return s.statusViewFromRow(row), nil
}
func (s *Service) liveRuntimeState(row *JobRow) (bool, *bool, error) {
exists, err := s.tmux.SessionExists(row.SessionName)
if err != nil {
return false, nil, err
}
if !exists {
return false, nil, nil
}
if row.Mode == jobmode.Stdio {
return true, nil, nil
}
active, err := s.tmux.IsOutputPipeActive(row.JobID)
if err != nil {
return false, nil, err
}
if active == nil {
return false, nil, nil
}
return true, active, nil
}
type exitMetadata struct {
exitCode int
endedAt string
}
func (s *Service) completedExitMetadata(row *JobRow) *exitMetadata {
jobDir := filepath.Join(s.config.JobsDir(), row.JobID)
drainedPath := filepath.Join(jobDir, ".pipe-drained")
exitCodePath := filepath.Join(jobDir, "runner-exit-code")
endedAtPath := filepath.Join(jobDir, "runner-ended-at")
if row.Mode == jobmode.PTY && !fileExists(drainedPath) {
return nil
}
if !fileExists(exitCodePath) || !fileExists(endedAtPath) {
return nil
}
exitCodeRaw, err := os.ReadFile(exitCodePath)
if err != nil {
return nil
}
endedAtRaw, err := os.ReadFile(endedAtPath)
if err != nil {
return nil
}
exitCodeStr := strings.TrimSpace(string(exitCodeRaw))
endedAtStr := strings.TrimSpace(string(endedAtRaw))
if exitCodeStr == "" || endedAtStr == "" {
return nil
}
code, err := strconv.Atoi(exitCodeStr)
if err != nil {
return nil
}
return &exitMetadata{exitCode: code, endedAt: endedAtStr}
}
func (s *Service) normalExitCommitPending(row *JobRow) bool {
if row.Mode != jobmode.PTY {
return false
}
jobDir := filepath.Join(s.config.JobsDir(), row.JobID)
return fileExists(filepath.Join(jobDir, "runner-exit-code")) &&
fileExists(filepath.Join(jobDir, "runner-ended-at")) &&
!fileExists(filepath.Join(jobDir, ".pipe-drained")) &&
!fileExists(filepath.Join(jobDir, ".pipe-failed"))
}
func (s *Service) outputLogPath(row *JobRow) string {
return filepath.Join(s.config.StateDir, row.OutputPath)
}
func (s *Service) statusViewFromRow(row *JobRow) *JobStatusView {
outputPath := s.outputLogPath(row)
offset := int(fileSize(outputPath))
return &JobStatusView{
JobID: row.JobID,
Status: row.Status,
Done: row.Status.IsTerminal(),
ExitCode: row.ExitCode,
CreatedAt: row.CreatedAt,
StartedAt: row.StartedAt,
EndedAt: row.EndedAt,
Offset: offset,
}
}
func (s *Service) jobResultFromView(view *JobStatusView, row *JobRow, window *OutputWindow) *JobResult {
outputPath := s.outputLogPath(row)
absPath, _ := filepath.Abs(outputPath)
return &JobResult{
JobID: view.JobID,
Done: view.Done,
Status: view.Status,
ExitCode: view.ExitCode,
OutputPath: absPath,
Output: window.Output,
Offset: window.Offset,
Truncated: window.Truncated,
}
}
func (s *Service) resolveCwd(rawCwd *string) (string, error) {
var cwd string
if rawCwd != nil && *rawCwd != "" {
cwd = *rawCwd
} else {
cwd = s.config.DefaultCwd
}
info, err := os.Stat(cwd)
if err != nil || !info.IsDir() {
return "", NewServerError(400, "invalid_cwd", fmt.Sprintf("cwd is not a directory: %s", cwd))
}
abs, _ := filepath.Abs(cwd)
return abs, nil
}
func (s *Service) allocateJobDir() (string, string, error) {
for i := 0; i < 20; i++ {
jobID := GenerateJobID()
jobDir := filepath.Join(s.config.JobsDir(), jobID)
if err := os.Mkdir(jobDir, 0700); err == nil {
return jobID, jobDir, nil
}
}
return "", "", NewServerError(500, "job_id_collision", "Failed to allocate a unique job id")
}
func (s *Service) cleanupStarting(jobID, jobDir string) {
s.mu.Lock()
delete(s.startingJobs, jobID)
s.mu.Unlock()
_ = os.RemoveAll(jobDir)
}
func (s *Service) installRunner() {
// The runner is now a pre-built Go binary (shellctl-runner).
// Create a symlink at the expected RunnerPath so tmux can invoke it.
dst := s.config.RunnerPath()
_ = os.Remove(dst) // remove stale script/symlink
// Look for the binary next to the main shellctl binary first,
// then fall back to PATH lookup.
src := ""
selfExe, _ := os.Executable()
if selfExe != "" {
candidate := filepath.Join(filepath.Dir(selfExe), "shellctl-runner")
if _, err := os.Stat(candidate); err == nil {
src = candidate
}
}
if src == "" {
if p, err := exec.LookPath("shellctl-runner"); err == nil {
src = p
}
}
if src != "" {
// Prefer symlink; fall back to copy path reference.
if err := os.Symlink(src, dst); err != nil {
// If symlink fails (e.g., cross-device), write a tiny shell wrapper.
wrapper := fmt.Sprintf("#!/bin/sh\nexec %q \"$@\"\n", src)
_ = os.WriteFile(dst, []byte(wrapper), 0755)
}
}
}
// Helpers
func fileExists(path string) bool {
_, err := os.Stat(path)
return err == nil
}
func fileSize(path string) int64 {
info, err := os.Stat(path)
if err != nil {
return 0
}
return info.Size()
}
func isNotFound(err error) bool {
if se, ok := err.(*ServerError); ok {
return se.Code == "job_not_found"
}
return false
}
@@ -0,0 +1,111 @@
package server
import (
"os"
"path/filepath"
"testing"
"github.com/langgenius/dify/dify-agent-runtime/internal/jobmode"
)
func TestMaterializeStdioStatusDoesNotRequirePanePipe(t *testing.T) {
service, row := setupModeTestService(t, jobmode.Stdio, StatusRunning)
pipeInactive := false
view, err := service.materializeStatusView(row, true, &pipeInactive)
if err != nil {
t.Fatalf("materializeStatusView: %v", err)
}
if view.Status != StatusRunning {
t.Errorf("status = %q, want %q", view.Status, StatusRunning)
}
}
func TestMaterializeStdioStatusUsesExitArtifactsWithoutPipeDrainMarker(t *testing.T) {
service, row := setupModeTestService(t, jobmode.Stdio, StatusRunning)
jobDir := filepath.Join(service.config.JobsDir(), row.JobID)
if err := os.WriteFile(filepath.Join(jobDir, "runner-exit-code"), []byte("7\n"), 0600); err != nil {
t.Fatal(err)
}
const endedAt = "2026-08-04T10:00:00Z"
if err := os.WriteFile(filepath.Join(jobDir, "runner-ended-at"), []byte(endedAt+"\n"), 0600); err != nil {
t.Fatal(err)
}
view, err := service.materializeStatusView(row, false, nil)
if err != nil {
t.Fatalf("materializeStatusView: %v", err)
}
if view.Status != StatusExited || !view.Done {
t.Errorf("view = status %q done %v, want exited and done", view.Status, view.Done)
}
if view.ExitCode == nil || *view.ExitCode != 7 {
t.Errorf("exit code = %v, want 7", view.ExitCode)
}
if view.EndedAt == nil || *view.EndedAt != endedAt {
t.Errorf("ended_at = %v, want %s", view.EndedAt, endedAt)
}
}
func TestMaterializeStdioStatusMarksMissingSessionWithIncompleteArtifactsLost(t *testing.T) {
service, row := setupModeTestService(t, jobmode.Stdio, StatusRunning)
jobDir := filepath.Join(service.config.JobsDir(), row.JobID)
if err := os.WriteFile(filepath.Join(jobDir, "runner-exit-code"), []byte("0\n"), 0600); err != nil {
t.Fatal(err)
}
view, err := service.materializeStatusView(row, false, nil)
if err != nil {
t.Fatalf("materializeStatusView: %v", err)
}
if view.Status != StatusLost {
t.Errorf("status = %q, want %q", view.Status, StatusLost)
}
}
func setupModeTestService(t *testing.T, mode jobmode.Mode, status JobStatusName) (*Service, *JobRow) {
t.Helper()
stateDir := t.TempDir()
config := mustDefaultConfig(t)
config.StateDir = stateDir
config.RuntimeDir = filepath.Join(stateDir, "runtime")
if err := os.MkdirAll(config.JobsDir(), 0700); err != nil {
t.Fatal(err)
}
db := setupTestDB(t, stateDir)
t.Cleanup(func() { _ = db.Close() })
service := NewService(config)
service.db = db
const jobID = "mode-test-job"
jobDir := filepath.Join(config.JobsDir(), jobID)
if err := os.MkdirAll(jobDir, 0700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(jobDir, "output.log"), nil, 0600); err != nil {
t.Fatal(err)
}
row := &JobRow{
JobID: jobID,
ScriptPath: "jobs/mode-test-job/script",
OutputPath: "jobs/mode-test-job/output.log",
Mode: mode,
Cwd: "/tmp",
TerminalCols: 80,
TerminalRows: 24,
Status: status,
SessionName: JobSessionName(jobID),
PaneTarget: JobPaneTarget(jobID),
CreatedAt: "2026-08-04T09:00:00Z",
UpdatedAt: "2026-08-04T09:00:00Z",
}
inserted, err := db.InsertJob(row)
if err != nil || !inserted {
t.Fatalf("InsertJob: inserted=%v err=%v", inserted, err)
}
persisted, err := db.GetJob(jobID)
if err != nil {
t.Fatalf("GetJob: %v", err)
}
return service, persisted
}
@@ -0,0 +1,173 @@
package server
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"hash"
"io"
"log"
"net/http"
"os"
"strconv"
"sync"
"time"
"github.com/langgenius/dify/dify-agent-runtime/internal/snapshot"
)
const (
TrailerSnapshotStatus = "X-Snapshot-Status"
TrailerSnapshotSha256 = "X-Snapshot-Sha256"
TrailerSnapshotBytes = "X-Snapshot-Bytes"
SnapshotStatusOK = "ok"
maxSaveRequestBytes = 64 << 10
)
type SaveRequest struct {
Excludes []string `json:"excludes"`
}
func decodeSaveExcludes(body io.Reader) ([]string, error) {
var req SaveRequest
if err := json.NewDecoder(io.LimitReader(body, maxSaveRequestBytes)).Decode(&req); err != nil {
if errors.Is(err, io.EOF) {
return nil, nil
}
return nil, err
}
return req.Excludes, nil
}
// snapshotHandlers serves the native Home snapshot endpoints.
//
// SIZE CONTRACT: neither endpoint imposes a size limit. Consumers MUST bound
// the streams in their own logic.
type snapshotHandlers struct {
config *Config
gate sync.Mutex
}
func newSnapshotHandlers(config *Config) *snapshotHandlers {
return &snapshotHandlers{config: config}
}
// resolveHome fails loudly when $HOME is unset or not a directory — never
// degrade to a guessed or relative path.
func (h *snapshotHandlers) resolveHome() (string, error) {
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
info, err := os.Stat(home)
if err != nil {
return "", err
}
if !info.IsDir() {
return "", errors.New("home is not a directory")
}
return home, nil
}
func (h *snapshotHandlers) handleSnapshotSave() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
excludes, err := decodeSaveExcludes(r.Body)
if err != nil {
writeError(w, 400, "invalid_request", err.Error())
return
}
if !h.gate.TryLock() {
writeError(w, 409, "snapshot_busy", "another snapshot operation is in progress")
return
}
defer h.gate.Unlock()
home, err := h.resolveHome()
if err != nil {
writeError(w, 500, "home_unavailable", err.Error())
return
}
rc := http.NewResponseController(w)
if err := rc.SetWriteDeadline(time.Now().Add(h.config.SnapshotTimeout)); err != nil {
log.Printf("WARN snapshot save: set write deadline: %v", err)
}
ctx, cancel := context.WithTimeout(r.Context(), h.config.SnapshotTimeout)
defer cancel()
w.Header().Set("Trailer", TrailerSnapshotStatus+", "+TrailerSnapshotSha256+", "+TrailerSnapshotBytes)
w.Header().Set("Content-Type", "application/octet-stream")
hcw := &hashCountWriter{w: w, h: sha256.New()}
if err := snapshot.SaveHome(ctx, hcw, home, excludes); err != nil {
log.Printf("ERROR snapshot save: %v", err)
if hcw.n == 0 {
w.Header().Del("Trailer")
writeError(w, 500, "snapshot_failed", err.Error())
return
}
panic(http.ErrAbortHandler)
}
w.Header().Set(TrailerSnapshotStatus, SnapshotStatusOK)
w.Header().Set(TrailerSnapshotSha256, hex.EncodeToString(hcw.h.Sum(nil)))
w.Header().Set(TrailerSnapshotBytes, strconv.FormatInt(hcw.n, 10))
}
}
func (h *snapshotHandlers) handleSnapshotRestore() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !h.gate.TryLock() {
writeError(w, 409, "snapshot_busy", "another snapshot operation is in progress")
return
}
defer h.gate.Unlock()
home, err := h.resolveHome()
if err != nil {
writeError(w, 500, "home_unavailable", err.Error())
return
}
rc := http.NewResponseController(w)
if err := rc.SetReadDeadline(time.Now().Add(h.config.SnapshotTimeout)); err != nil {
log.Printf("WARN snapshot restore: set read deadline: %v", err)
}
ctx, cancel := context.WithTimeout(r.Context(), h.config.SnapshotTimeout)
defer cancel()
result, err := snapshot.RestoreHome(ctx, r.Body, home)
if err != nil {
log.Printf("ERROR snapshot restore: %v", err)
if errors.Is(err, snapshot.ErrMalformed) {
writeError(w, 400, "archive_malformed", err.Error())
return
}
writeError(w, 500, "restore_failed", err.Error())
return
}
writeJSON(w, http.StatusOK, RestoreResponse{
Entries: result.Entries,
BytesWritten: result.BytesWritten,
})
}
}
// hashCountWriter passes bytes through while hashing and counting them, so
// success trailers can carry the digest without buffering anything.
type hashCountWriter struct {
w io.Writer
h hash.Hash
n int64
}
func (hc *hashCountWriter) Write(p []byte) (int, error) {
n, err := hc.w.Write(p)
hc.n += int64(n)
_, _ = hc.h.Write(p[:n])
return n, err
}
@@ -0,0 +1,331 @@
package server
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"io"
"net"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strconv"
"testing"
"time"
"github.com/langgenius/dify/dify-agent-runtime/internal/snapshot"
)
func newSnapshotTestServer(t *testing.T, cfg *Config) *httptest.Server {
t.Helper()
srv := httptest.NewServer(Handler(nil, cfg)) // snapshot routes never touch the job Service
t.Cleanup(srv.Close)
return srv
}
func testConfig() *Config {
return &Config{SnapshotTimeout: 600 * time.Second}
}
func setHome(t *testing.T) string {
t.Helper()
home := t.TempDir()
t.Setenv("HOME", home)
return home
}
func TestSnapshotSaveSuccessWithTrailers(t *testing.T) {
home := setHome(t)
if err := os.WriteFile(filepath.Join(home, "data.txt"), []byte("hello"), 0o644); err != nil {
t.Fatal(err)
}
srv := newSnapshotTestServer(t, testConfig())
resp, err := http.Post(srv.URL+"/v1/snapshot/save", "", nil)
if err != nil {
t.Fatal(err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != 200 {
t.Fatalf("status = %d", resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("read stream: %v", err)
}
if resp.Trailer.Get(TrailerSnapshotStatus) != SnapshotStatusOK {
t.Fatalf("status trailer = %q", resp.Trailer.Get(TrailerSnapshotStatus))
}
sum := sha256.Sum256(body)
if got := resp.Trailer.Get(TrailerSnapshotSha256); got != hex.EncodeToString(sum[:]) {
t.Fatalf("sha trailer = %q, want %q", got, hex.EncodeToString(sum[:]))
}
if got := resp.Trailer.Get(TrailerSnapshotBytes); got != strconv.FormatInt(int64(len(body)), 10) {
t.Fatalf("bytes trailer = %q, want %d", got, len(body))
}
// The stream is a restorable archive.
dst := t.TempDir()
if _, err := snapshot.RestoreHome(context.Background(), bytes.NewReader(body), dst); err != nil {
t.Fatalf("returned stream not restorable: %v", err)
}
got, err := os.ReadFile(filepath.Join(dst, "data.txt"))
if err != nil || string(got) != "hello" {
t.Fatalf("restored content = %q err=%v", got, err)
}
}
// An empty Home is not a special case: it produces an ordinary archive with no
// entries, so every caller stores and restores it through the same path.
func TestSnapshotSaveEmptyHome(t *testing.T) {
setHome(t)
srv := newSnapshotTestServer(t, testConfig())
resp, err := http.Post(srv.URL+"/v1/snapshot/save", "", nil)
if err != nil {
t.Fatal(err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != 200 {
t.Fatalf("empty home: status = %d, want 200", resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("read stream: %v", err)
}
if resp.Trailer.Get(TrailerSnapshotStatus) != SnapshotStatusOK {
t.Fatalf("status trailer = %q", resp.Trailer.Get(TrailerSnapshotStatus))
}
if len(body) == 0 {
t.Fatal("empty home produced no bytes; callers cannot distinguish it from a dropped stream")
}
dst := t.TempDir()
res, err := snapshot.RestoreHome(context.Background(), bytes.NewReader(body), dst)
if err != nil {
t.Fatalf("empty-home archive not restorable: %v", err)
}
if res.Entries != 0 || res.BytesWritten != 0 {
t.Fatalf("restored %+v, want zero entries and bytes", res)
}
}
func TestSnapshotSaveAbortsOnMidStreamFailure(t *testing.T) {
if os.Geteuid() == 0 {
t.Skip("running as root: permission checks are bypassed")
}
home := setHome(t)
if err := os.WriteFile(filepath.Join(home, "ok.txt"), bytes.Repeat([]byte("x"), 64*1024), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(home, "zz-locked.txt"), []byte("secret"), 0o000); err != nil {
t.Fatal(err)
}
srv := newSnapshotTestServer(t, testConfig())
resp, err := http.Post(srv.URL+"/v1/snapshot/save", "", nil)
if err != nil {
return // aborted before headers: also a valid failure surface
}
defer func() { _ = resp.Body.Close() }()
_, readErr := io.ReadAll(resp.Body)
if readErr == nil && resp.Trailer.Get(TrailerSnapshotStatus) == SnapshotStatusOK {
t.Fatal("mid-stream failure must never produce a clean ok stream")
}
}
func TestSnapshotBusy(t *testing.T) {
setHome(t)
cfg := testConfig()
snap := newSnapshotHandlers(cfg)
if !snap.gate.TryLock() {
t.Fatal("fresh gate must lock")
}
defer snap.gate.Unlock()
req := httptest.NewRequest("POST", "/v1/snapshot/save", nil)
w := httptest.NewRecorder()
snap.handleSnapshotSave()(w, req)
if w.Code != 409 {
t.Fatalf("busy save: status = %d, want 409", w.Code)
}
var savePayload ErrorResponse
if err := json.NewDecoder(w.Body).Decode(&savePayload); err != nil {
t.Fatal(err)
}
if savePayload.Error.Code != "snapshot_busy" {
t.Fatalf("busy save: error code = %q, want snapshot_busy", savePayload.Error.Code)
}
req = httptest.NewRequest("POST", "/v1/snapshot/restore", nil)
w = httptest.NewRecorder()
snap.handleSnapshotRestore()(w, req)
if w.Code != 409 {
t.Fatalf("busy restore: status = %d, want 409", w.Code)
}
var restorePayload ErrorResponse
if err := json.NewDecoder(w.Body).Decode(&restorePayload); err != nil {
t.Fatal(err)
}
if restorePayload.Error.Code != "snapshot_busy" {
t.Fatalf("busy restore: error code = %q, want snapshot_busy", restorePayload.Error.Code)
}
}
// TestSnapshotWireContract pins the literal wire strings remote clients parse.
// If this test fails, the gateway protocol changed — that is a breaking change,
// not a refactor.
func TestSnapshotWireContract(t *testing.T) {
if TrailerSnapshotStatus != "X-Snapshot-Status" ||
TrailerSnapshotSha256 != "X-Snapshot-Sha256" ||
TrailerSnapshotBytes != "X-Snapshot-Bytes" ||
SnapshotStatusOK != "ok" {
t.Fatalf("snapshot trailer contract changed: %q %q %q %q",
TrailerSnapshotStatus, TrailerSnapshotSha256, TrailerSnapshotBytes, SnapshotStatusOK)
}
}
func TestSnapshotRestoreEndpoint(t *testing.T) {
srcHome := t.TempDir()
if err := os.WriteFile(filepath.Join(srcHome, "keep.txt"), []byte("v"), 0o644); err != nil {
t.Fatal(err)
}
var archive bytes.Buffer
if err := snapshot.SaveHome(context.Background(), &archive, srcHome, nil); err != nil {
t.Fatal(err)
}
home := setHome(t)
srv := newSnapshotTestServer(t, testConfig())
resp, err := http.Post(srv.URL+"/v1/snapshot/restore", "application/octet-stream", &archive)
if err != nil {
t.Fatal(err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != 200 {
t.Fatalf("status = %d", resp.StatusCode)
}
var result RestoreResponse
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
t.Fatal(err)
}
if result.Entries == 0 {
t.Error("entries not counted")
}
if got, err := os.ReadFile(filepath.Join(home, "keep.txt")); err != nil || string(got) != "v" {
t.Fatalf("restored file = %q err=%v", got, err)
}
}
func TestSnapshotRestoreMalformed(t *testing.T) {
setHome(t)
srv := newSnapshotTestServer(t, testConfig())
resp, err := http.Post(srv.URL+"/v1/snapshot/restore", "application/octet-stream", bytes.NewReader([]byte("garbage")))
if err != nil {
t.Fatal(err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != 400 {
t.Fatalf("status = %d, want 400", resp.StatusCode)
}
var payload ErrorResponse
if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil {
t.Fatal(err)
}
if payload.Error.Code != "archive_malformed" {
t.Fatalf("error code = %q", payload.Error.Code)
}
}
func TestSnapshotSaveHomeUnavailable(t *testing.T) {
t.Setenv("HOME", "") // os.UserHomeDir errors when $HOME is unset
srv := newSnapshotTestServer(t, testConfig())
resp, err := http.Post(srv.URL+"/v1/snapshot/save", "", nil)
if err != nil {
t.Fatal(err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != 500 {
t.Fatalf("status = %d, want 500", resp.StatusCode)
}
var payload ErrorResponse
if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil {
t.Fatal(err)
}
if payload.Error.Code != "home_unavailable" {
t.Fatalf("error code = %q, want home_unavailable", payload.Error.Code)
}
}
func TestSnapshotRoutesRequireAuth(t *testing.T) {
setHome(t)
cfg := testConfig()
cfg.AuthToken = "secret"
srv := newSnapshotTestServer(t, cfg)
resp, err := http.Post(srv.URL+"/v1/snapshot/save", "", nil)
if err != nil {
t.Fatal(err)
}
_ = resp.Body.Close()
if resp.StatusCode != 401 {
t.Fatalf("unauthenticated save: status = %d, want 401", resp.StatusCode)
}
resp, err = http.Post(srv.URL+"/v1/snapshot/restore", "", nil)
if err != nil {
t.Fatal(err)
}
_ = resp.Body.Close()
if resp.StatusCode != 401 {
t.Fatalf("unauthenticated restore: status = %d, want 401", resp.StatusCode)
}
}
// TestSnapshotRestoreStalledPeerReleasesGate proves that a peer which stops
// sending body bytes mid-stream cannot wedge the single-flight gate forever:
// the read deadline set via http.ResponseController must fire and unblock
// the handler even though the server's ReadTimeout is 0.
func TestSnapshotRestoreStalledPeerReleasesGate(t *testing.T) {
setHome(t)
cfg := testConfig()
cfg.SnapshotTimeout = 300 * time.Millisecond
srv := newSnapshotTestServer(t, cfg)
addr := srv.Listener.Addr().String()
conn, err := net.Dial("tcp", addr)
if err != nil {
t.Fatal(err)
}
defer func() { _ = conn.Close() }()
// A syntactically valid request head announcing a chunked body, followed
// by a partial chunk. The peer then goes silent without completing it.
head := "POST /v1/snapshot/restore HTTP/1.1\r\n" +
"Host: " + addr + "\r\n" +
"Transfer-Encoding: chunked\r\n" +
"Content-Type: application/octet-stream\r\n" +
"\r\n" +
"5\r\n" +
"ab"
if _, err := conn.Write([]byte(head)); err != nil {
t.Fatal(err)
}
// Comfortably past SnapshotTimeout: the stalled request's read deadline
// must have fired and released the gate by now.
time.Sleep(2 * time.Second)
resp, err := http.Post(srv.URL+"/v1/snapshot/restore", "application/octet-stream", bytes.NewReader([]byte("garbage")))
if err != nil {
t.Fatal(err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode == http.StatusConflict {
t.Fatal("gate still held after stalled peer's read deadline should have expired")
}
}
@@ -0,0 +1,298 @@
package server
import (
"bytes"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/langgenius/dify/dify-agent-runtime/internal/jobmode"
)
// TmuxController manages tmux sessions for shellctl jobs via a dedicated socket.
type TmuxController struct {
config *Config
}
// NewTmuxController creates a new tmux controller.
func NewTmuxController(config *Config) *TmuxController {
return &TmuxController{config: config}
}
// StartServer ensures the tmux server is running.
func (t *TmuxController) StartServer() error {
_, err := t.runTmux(
"start-server",
";",
"set-option", "-g", "exit-empty", "off",
)
return err
}
// ListSessions returns the set of active tmux session names.
func (t *TmuxController) ListSessions() (map[string]bool, error) {
result, err := t.runTmuxNoCheck("list-sessions", "-F", "#{session_name}")
if err != nil {
return nil, err
}
if result.exitCode != 0 {
stderr := strings.TrimSpace(result.stderr)
if isTmuxTargetMissing(stderr) {
return make(map[string]bool), nil
}
return nil, NewServerError(500, "tmux_error", stderr)
}
sessions := make(map[string]bool)
for _, line := range strings.Split(strings.TrimSpace(result.stdout), "\n") {
line = strings.TrimSpace(line)
if line != "" {
sessions[line] = true
}
}
return sessions, nil
}
// SessionExists checks if a tmux session exists by name.
func (t *TmuxController) SessionExists(sessionName string) (bool, error) {
sessions, err := t.ListSessions()
if err != nil {
return false, err
}
return sessions[sessionName], nil
}
// IsOutputPipeActive checks the #{pane_pipe} format variable for a job pane.
// Returns: true=active, false=inactive, error with nil bool if pane missing.
func (t *TmuxController) IsOutputPipeActive(jobID string) (*bool, error) {
result, err := t.runTmuxNoCheck(
"display-message", "-p", "-t", JobPaneTarget(jobID), "#{pane_pipe}",
)
if err != nil {
return nil, err
}
if result.exitCode != 0 {
stderr := strings.TrimSpace(result.stderr)
if isTmuxTargetMissing(stderr) {
return nil, nil // pane missing
}
return nil, NewServerError(500, "tmux_error", stderr)
}
active := strings.TrimSpace(result.stdout) == "1"
return &active, nil
}
// CreateJobSession creates a new tmux session for a job.
func (t *TmuxController) CreateJobSession(
jobID, jobDir, cwd string,
cols, rows int,
mode jobmode.Mode,
) error {
runnerCmd := shellJoin([]string{
t.config.RunnerPath(), jobDir, jobID, cwd, string(mode),
})
result, err := t.runTmuxNoCheck(
"-f", "/dev/null",
"new-session", "-d",
"-s", JobSessionName(jobID),
"-x", fmt.Sprintf("%d", cols),
"-y", fmt.Sprintf("%d", rows),
runnerCmd,
)
if err != nil {
return err
}
if result.exitCode != 0 {
return NewServerError(500, "tmux_new_session_failed",
strings.TrimSpace(result.stderr))
}
return nil
}
// EnableOutputPipe attaches the sanitize→output pipeline via tmux pipe-pane.
func (t *TmuxController) EnableOutputPipe(jobID, jobDir string, readyFile string) error {
pipeCmd := t.buildPipeCommand(jobID, jobDir, readyFile)
result, err := t.runTmuxNoCheck(
"pipe-pane", "-o", "-t", JobPaneTarget(jobID), pipeCmd,
)
if err != nil {
return err
}
if result.exitCode != 0 {
return NewServerError(500, "pipe_failed",
strings.TrimSpace(result.stderr))
}
return nil
}
// SendInput sends text to a job's tmux pane via load-buffer + paste-buffer.
func (t *TmuxController) SendInput(jobID, text string) error {
bufferName := fmt.Sprintf("shellctl-in-%s", jobID)
// Write input to a temp file
tmpFile, err := os.CreateTemp(t.config.RuntimeDir, fmt.Sprintf("shellctl-input-%s-", jobID))
if err != nil {
return err
}
tmpPath := tmpFile.Name()
defer func() { _ = os.Remove(tmpPath) }()
if _, err := tmpFile.WriteString(text); err != nil {
_ = tmpFile.Close()
return err
}
if err := tmpFile.Close(); err != nil {
return err
}
// Load buffer
result, err := t.runTmuxNoCheck("load-buffer", "-b", bufferName, tmpPath)
if err != nil {
return err
}
if result.exitCode != 0 {
stderr := strings.TrimSpace(result.stderr)
if isTmuxTargetMissing(stderr) {
return NewServerError(409, "tmux_target_missing", stderr)
}
return NewServerError(500, "tmux_input_failed", stderr)
}
// Paste buffer
result, err = t.runTmuxNoCheck(
"paste-buffer", "-t", JobPaneTarget(jobID), "-b", bufferName,
)
// Always clean up buffer
_, _ = t.runTmuxNoCheck("delete-buffer", "-b", bufferName)
if err != nil {
return err
}
if result.exitCode != 0 {
stderr := strings.TrimSpace(result.stderr)
if isTmuxTargetMissing(stderr) {
return NewServerError(409, "tmux_target_missing", stderr)
}
return NewServerError(500, "tmux_input_failed", stderr)
}
return nil
}
// SendInterrupt sends C-c to a job's pane.
func (t *TmuxController) SendInterrupt(jobID string) error {
_, _ = t.runTmuxNoCheck("send-keys", "-t", JobPaneTarget(jobID), "C-c")
return nil
}
// CleanupSession kills the tmux session for a job (best-effort).
func (t *TmuxController) CleanupSession(jobID string) {
_, _ = t.runTmuxNoCheck("kill-session", "-t", JobSessionName(jobID))
}
func (t *TmuxController) buildPipeCommand(jobID, jobDir, readyFile string) string {
sanitizeCmd := shellJoin(append(t.config.SanitizePtyCommand, "--ready-file", readyFile))
runnerExitCmd := shellJoin(append(t.config.RunnerExitCommand,
"--state-dir", t.config.StateDir,
"--job-id", jobID,
"--sqlite-busy-timeout-ms", fmt.Sprintf("%d", t.config.SQLiteBusyTimeoutMs),
))
outputPath := shellQuote(filepath.Join(jobDir, "output.log"))
drainedPath := shellQuote(filepath.Join(jobDir, ".pipe-drained"))
errorLogPath := shellQuote(filepath.Join(jobDir, "pipe-error.log"))
failedPath := shellQuote(filepath.Join(jobDir, ".pipe-failed"))
exitCodePath := shellQuote(filepath.Join(jobDir, "runner-exit-code"))
endedAtPath := shellQuote(filepath.Join(jobDir, "runner-ended-at"))
parts := []string{
fmt.Sprintf("%s >> %s 2> %s", sanitizeCmd, outputPath, errorLogPath),
"sanitize_status=$?",
"runner_exit_status=0",
fmt.Sprintf(
`if [ "$sanitize_status" -eq 0 ]; then : > %s; if [ -s %s ] && [ -s %s ]; then %s --exit-code "$(cat %s)" --ended-at "$(cat %s)" 2>> %s; runner_exit_status=$?; if [ "$runner_exit_status" -ne 0 ]; then printf 'runner-exit failed with status %%s\n' "$runner_exit_status" >> %s; fi; fi; else : > %s; fi`,
drainedPath, exitCodePath, endedAtPath, runnerExitCmd,
exitCodePath, endedAtPath, errorLogPath, errorLogPath, failedPath,
),
`if [ "$sanitize_status" -ne 0 ]; then exit "$sanitize_status"; fi`,
`exit "$sanitize_status"`,
}
return strings.Join(parts, " ; ")
}
type tmuxResult struct {
stdout string
stderr string
exitCode int
}
func (t *TmuxController) runTmux(args ...string) (string, error) {
result, err := t.runTmuxNoCheck(args...)
if err != nil {
return "", err
}
if result.exitCode != 0 {
stderr := strings.TrimSpace(result.stderr)
if stderr == "" {
stderr = "tmux command failed"
}
return "", NewServerError(500, "tmux_error", stderr)
}
return result.stdout, nil
}
func (t *TmuxController) runTmuxNoCheck(args ...string) (*tmuxResult, error) {
cmdArgs := append([]string{"-S", t.config.TmuxSocket()}, args...)
cmd := exec.Command("tmux", cmdArgs...)
// Clear TMUX env to avoid nesting
env := os.Environ()
filtered := env[:0]
for _, e := range env {
if !strings.HasPrefix(e, "TMUX=") {
filtered = append(filtered, e)
}
}
cmd.Env = filtered
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
exitCode := 0
if err != nil {
if exitErr, ok := err.(*exec.ExitError); ok {
exitCode = exitErr.ExitCode()
} else {
return nil, fmt.Errorf("exec tmux: %w", err)
}
}
return &tmuxResult{
stdout: stdout.String(),
stderr: stderr.String(),
exitCode: exitCode,
}, nil
}
func isTmuxTargetMissing(stderr string) bool {
lower := strings.ToLower(stderr)
return strings.Contains(lower, "can't find pane") ||
strings.Contains(lower, "can't find session") ||
strings.Contains(lower, "no server running") ||
strings.Contains(lower, "failed to connect") ||
strings.Contains(lower, "server exited unexpectedly")
}
func shellJoin(parts []string) string {
quoted := make([]string, len(parts))
for i, p := range parts {
quoted[i] = shellQuote(p)
}
return strings.Join(quoted, " ")
}
func shellQuote(s string) string {
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
}
@@ -0,0 +1,141 @@
package server
import (
"os/exec"
"strings"
"testing"
)
func newTestTmuxController(t *testing.T) *TmuxController {
t.Helper()
if _, err := exec.LookPath("tmux"); err != nil {
t.Skip("tmux is not installed")
}
config := mustDefaultConfig(t)
config.RuntimeDir = t.TempDir()
controller := NewTmuxController(config)
t.Cleanup(func() {
_, _ = controller.runTmuxNoCheck("kill-server")
})
return controller
}
func assertTmuxServerRunning(t *testing.T, controller *TmuxController) {
t.Helper()
exitEmpty, err := controller.runTmux("show-options", "-gv", "exit-empty")
if err != nil {
t.Fatalf("tmux server is not running: %v", err)
}
if got := strings.TrimSpace(exitEmpty); got != "off" {
t.Fatalf("exit-empty = %q, want %q", got, "off")
}
}
func TestStartServerKeepsTmuxServerRunningWithoutSessions(t *testing.T) {
controller := newTestTmuxController(t)
if err := controller.StartServer(); err != nil {
t.Fatalf("StartServer() error = %v", err)
}
assertTmuxServerRunning(t, controller)
sessions, err := controller.ListSessions()
if err != nil {
t.Fatalf("ListSessions() error = %v", err)
}
if len(sessions) != 0 {
t.Fatalf("ListSessions() = %v, want no sessions", sessions)
}
}
func TestTmuxServerRemainsRunningAfterLastSessionIsDeleted(t *testing.T) {
controller := newTestTmuxController(t)
if err := controller.StartServer(); err != nil {
t.Fatalf("StartServer() error = %v", err)
}
const jobID = "last-session"
sessionName := JobSessionName(jobID)
if _, err := controller.runTmux("new-session", "-d", "-s", sessionName); err != nil {
t.Fatalf("create tmux session: %v", err)
}
sessions, err := controller.ListSessions()
if err != nil {
t.Fatalf("ListSessions() before cleanup error = %v", err)
}
if !sessions[sessionName] {
t.Fatalf("ListSessions() = %v, want session %q", sessions, sessionName)
}
controller.CleanupSession(jobID)
assertTmuxServerRunning(t, controller)
sessions, err = controller.ListSessions()
if err != nil {
t.Fatalf("ListSessions() after cleanup error = %v", err)
}
if len(sessions) != 0 {
t.Fatalf("ListSessions() after cleanup = %v, want no sessions", sessions)
}
}
func TestShellQuote(t *testing.T) {
tests := []struct {
input string
expected string
}{
{"hello", "'hello'"},
{"", "''"},
{"a b c", "'a b c'"},
{"it's", "'it'\\''s'"},
{"/path/to/file", "'/path/to/file'"},
}
for _, tc := range tests {
got := shellQuote(tc.input)
if got != tc.expected {
t.Errorf("shellQuote(%q) = %q, want %q", tc.input, got, tc.expected)
}
}
}
func TestShellJoin(t *testing.T) {
got := shellJoin([]string{"echo", "hello world", "it's"})
expected := "'echo' 'hello world' 'it'\\''s'"
if got != expected {
t.Errorf("shellJoin = %q, want %q", got, expected)
}
}
func TestIsTmuxTargetMissing(t *testing.T) {
missingMsgs := []string{
"can't find pane: shellctl-abc",
"can't find session: shellctl-abc",
"no server running on /tmp/tmux.sock",
"failed to connect to server",
"server exited unexpectedly",
}
for _, msg := range missingMsgs {
if !isTmuxTargetMissing(msg) {
t.Errorf("expected %q to be detected as target missing", msg)
}
}
validMsgs := []string{
"some other error",
"permission denied",
"",
}
for _, msg := range validMsgs {
if isTmuxTargetMissing(msg) {
t.Errorf("expected %q to NOT be detected as target missing", msg)
}
}
}
@@ -0,0 +1,109 @@
package server
import "github.com/langgenius/dify/dify-agent-runtime/internal/jobmode"
// RunJobRequest is the HTTP request body for POST /v1/jobs/run.
type RunJobRequest struct {
Script string `json:"script"`
Cwd *string `json:"cwd,omitempty"`
Env map[string]string `json:"env,omitempty"`
Terminal *TerminalSize `json:"terminal,omitempty"`
Mode jobmode.Mode `json:"mode,omitempty"`
Timeout float64 `json:"timeout,omitempty"`
OutputLimit int `json:"output_limit,omitempty"`
IdleFlushSeconds float64 `json:"idle_flush_seconds,omitempty"`
}
// TerminalSize specifies the initial PTY geometry.
type TerminalSize struct {
Cols int `json:"cols"`
Rows int `json:"rows"`
}
// WaitJobRequest is the HTTP request body for POST /v1/jobs/{job_id}/wait.
type WaitJobRequest struct {
Timeout float64 `json:"timeout"`
Offset int `json:"offset"`
OutputLimit int `json:"output_limit,omitempty"`
IdleFlushSeconds float64 `json:"idle_flush_seconds,omitempty"`
}
// InputJobRequest is the HTTP request body for POST /v1/jobs/{job_id}/input.
type InputJobRequest struct {
Text string `json:"text"`
Timeout float64 `json:"timeout,omitempty"`
Offset int `json:"offset"`
OutputLimit int `json:"output_limit,omitempty"`
IdleFlushSeconds float64 `json:"idle_flush_seconds,omitempty"`
}
// TerminateJobRequest is the HTTP request body for POST /v1/jobs/{job_id}/terminate.
type TerminateJobRequest struct {
GraceSeconds *float64 `json:"grace_seconds,omitempty"`
}
// JobResult is the unified response for output-oriented job APIs.
type JobResult struct {
JobID string `json:"job_id"`
Done bool `json:"done"`
Status JobStatusName `json:"status"`
ExitCode *int `json:"exit_code"`
OutputPath string `json:"output_path"`
Output string `json:"output"`
Offset int `json:"offset"`
Truncated bool `json:"truncated"`
}
// JobStatusView is the materialized lifecycle view.
type JobStatusView struct {
JobID string `json:"job_id"`
Status JobStatusName `json:"status"`
Done bool `json:"done"`
ExitCode *int `json:"exit_code"`
CreatedAt string `json:"created_at"`
StartedAt *string `json:"started_at"`
EndedAt *string `json:"ended_at"`
Offset int `json:"offset"`
}
// JobInfo is a compact job listing record.
type JobInfo struct {
JobID string `json:"job_id"`
Status JobStatusName `json:"status"`
CreatedAt string `json:"created_at"`
StartedAt *string `json:"started_at,omitempty"`
EndedAt *string `json:"ended_at,omitempty"`
}
// ListJobsResponse is the response for GET /v1/jobs.
type ListJobsResponse struct {
Jobs []JobInfo `json:"jobs"`
}
// DeleteJobResponse is the response for DELETE /v1/jobs/{job_id}.
type DeleteJobResponse struct {
JobID string `json:"job_id"`
Deleted bool `json:"deleted"`
}
// HealthResponse is the health check response.
type HealthResponse struct {
Status string `json:"status"`
}
// ErrorDetail is the machine-readable API error payload.
type ErrorDetail struct {
Code string `json:"code"`
Message string `json:"message"`
}
// ErrorResponse is the error envelope.
type ErrorResponse struct {
Error ErrorDetail `json:"error"`
}
// RestoreResponse reports a completed Home restore.
type RestoreResponse struct {
Entries int `json:"entries"`
BytesWritten int64 `json:"bytes_written"`
}