Skip to content

An open-source, faster Devin alternative

TypeScript

feat(logship): oc logs CLI, re-enable UI button, support stopped sandboxes (#243)

Mohamed Habib192efa388a13
diff --git a/cmd/oc/internal/client/client.go b/cmd/oc/internal/client/client.go
index 98461b97..fca6dc54 100644
--- a/cmd/oc/internal/client/client.go
+++ b/cmd/oc/internal/client/client.go
@@ -170,6 +170,17 @@ func (c *Client) Post(ctx context.Context, path string, body, result interface{}
return nil
}
+// GetStream performs a GET request and returns the raw response so the
+// caller can stream chunks (e.g. SSE log feeds). Caller closes resp.Body.
+func (c *Client) GetStream(ctx context.Context, path string) (*http.Response, error) {
+ req, err := http.NewRequestWithContext(ctx, "GET", c.baseURL+path, nil)
+ if err != nil {
+ return nil, err
+ }
+ req.Header.Set("Accept", "text/event-stream")
+ return c.do(req)
+}
+
// PostStream performs a POST request and returns the raw response so the
// caller can stream chunks (e.g. SSE / chat-completions). Caller is
// responsible for closing resp.Body.
diff --git a/cmd/oc/internal/commands/logs.go b/cmd/oc/internal/commands/logs.go
new file mode 100644
index 00000000..25bfdd15
--- /dev/null
+++ b/cmd/oc/internal/commands/logs.go
@@ -0,0 +1,181 @@
+package commands
+
+import (
+ "bufio"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/url"
+ "os"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/opensandbox/opensandbox/cmd/oc/internal/client"
+ "github.com/spf13/cobra"
+)
+
+var logsCmd = &cobra.Command{
+ Use: "logs <sandbox-id>",
+ Short: "Stream a sandbox's session logs (live tail by default)",
+ Long: `Stream logs from a sandbox session — /var/log/* and every exec'd
+command's stdout/stderr — shipped from inside the sandbox to Axiom and
+served back through the control plane.
+
+Default behaviour: tail. Prints the historical batch starting at
+the sandbox's createdAt, then polls forever for new lines until you
+hit Ctrl-C. Stopped/hibernated sandboxes flip to historical-only
+automatically (no new lines will arrive after stop) so --no-tail is
+not strictly needed for those.
+
+Examples:
+ oc logs sb-abc # live tail
+ oc logs sb-abc --no-tail # one historical batch, then exit
+ oc logs sb-abc --since 30m # last 30 minutes
+ oc logs sb-abc --grep error # server-side substring filter
+ oc logs sb-abc --source exec_stdout,exec_stderr
+ oc logs sb-abc --json # raw event JSON, one per line`,
+ Args: cobra.ExactArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ ctx := cmd.Context()
+ c := client.FromContext(ctx)
+ sandboxID := args[0]
+
+ noTail, _ := cmd.Flags().GetBool("no-tail")
+ since, _ := cmd.Flags().GetString("since")
+ until, _ := cmd.Flags().GetString("until")
+ grep, _ := cmd.Flags().GetString("grep")
+ sources, _ := cmd.Flags().GetStringSlice("source")
+ limit, _ := cmd.Flags().GetInt("limit")
+ jsonOut, _ := cmd.Flags().GetBool("json")
+
+ qs := url.Values{}
+ if noTail {
+ qs.Set("tail", "false")
+ }
+ if since != "" {
+ // Accept both Go duration (e.g. "30m", "2h") and RFC3339.
+ if d, err := time.ParseDuration(since); err == nil {
+ qs.Set("since", time.Now().UTC().Add(-d).Format(time.RFC3339))
+ } else if _, err := time.Parse(time.RFC3339, since); err == nil {
+ qs.Set("since", since)
+ } else {
+ return fmt.Errorf("--since must be a Go duration (e.g. 30m) or RFC3339 timestamp")
+ }
+ }
+ if until != "" {
+ if _, err := time.Parse(time.RFC3339, until); err != nil {
+ return fmt.Errorf("--until must be an RFC3339 timestamp")
+ }
+ qs.Set("until", until)
+ }
+ if grep != "" {
+ qs.Set("q", grep)
+ }
+ if len(sources) > 0 {
+ qs.Set("source", strings.Join(sources, ","))
+ }
+ if limit > 0 {
+ qs.Set("limit", strconv.Itoa(limit))
+ }
+
+ path := "/api/sandboxes/" + url.PathEscape(sandboxID) + "/logs"
+ if encoded := qs.Encode(); encoded != "" {
+ path += "?" + encoded
+ }
+
+ resp, err := c.GetStream(ctx, path)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != 200 {
+ buf, _ := io.ReadAll(resp.Body)
+ return fmt.Errorf("logs request failed (HTTP %d): %s", resp.StatusCode, strings.TrimSpace(string(buf)))
+ }
+
+ return streamSandboxLogs(resp.Body, os.Stdout, jsonOut)
+ },
+}
+
+// logEvent mirrors the on-the-wire shape from internal/api/sandbox_logs.go.
+// Unknown extra fields from server are tolerated by json.Unmarshal.
+type logEvent struct {
+ Time time.Time `json:"_time"`
+ Source string `json:"source"`
+ Line string `json:"line"`
+ Path string `json:"path,omitempty"`
+ ExecID string `json:"exec_id,omitempty"`
+ Command string `json:"command,omitempty"`
+ Argv []string `json:"argv,omitempty"`
+ ExitCode *int `json:"exit_code,omitempty"`
+}
+
+// streamSandboxLogs parses an SSE stream and writes each event to w.
+// Splits out from the cobra RunE so it's unit-testable.
+func streamSandboxLogs(r io.Reader, w io.Writer, jsonOut bool) error {
+ reader := bufio.NewReader(r)
+ for {
+ line, err := reader.ReadString('\n')
+ if line != "" {
+ line = strings.TrimRight(line, "\r\n")
+ // SSE comments start with ":" — keepalives, errors. Ignore.
+ if strings.HasPrefix(line, ":") {
+ if err == io.EOF {
+ return nil
+ }
+ continue
+ }
+ if strings.HasPrefix(line, "data:") {
+ payload := strings.TrimSpace(strings.TrimPrefix(line, "data:"))
+ if payload != "" {
+ if jsonOut {
+ fmt.Fprintln(w, payload)
+ } else {
+ var ev logEvent
+ if jerr := json.Unmarshal([]byte(payload), &ev); jerr == nil {
+ renderEvent(w, ev)
+ }
+ }
+ }
+ }
+ }
+ if err != nil {
+ if err == io.EOF {
+ return nil
+ }
+ return err
+ }
+ }
+}
+
+func renderEvent(w io.Writer, ev logEvent) {
+ ts := ev.Time.Local().Format("15:04:05.000")
+ color := sourceColor(ev.Source)
+ fmt.Fprintf(w, "%s %s%-12s\033[0m %s\n", ts, color, ev.Source, ev.Line)
+}
+
+func sourceColor(s string) string {
+ switch s {
+ case "var_log":
+ return "\033[36m" // cyan
+ case "exec_stdout":
+ return "\033[37m" // light gray
+ case "exec_stderr":
+ return "\033[31m" // red
+ case "agent":
+ return "\033[33m" // yellow
+ default:
+ return "\033[37m"
+ }
+}
+
+func init() {
+ logsCmd.Flags().Bool("no-tail", false, "exit after the historical batch instead of tailing")
+ logsCmd.Flags().String("since", "", "Go duration (e.g. 30m, 2h) or RFC3339 timestamp")
+ logsCmd.Flags().String("until", "", "RFC3339 timestamp; ignored when tailing")
+ logsCmd.Flags().String("grep", "", "server-side substring filter on the log line")
+ logsCmd.Flags().StringSlice("source", nil, "comma-separated filter: var_log, exec_stdout, exec_stderr, agent")
+ logsCmd.Flags().Int("limit", 0, "max historical rows (0 = server default of 1000)")
+ logsCmd.Flags().Bool("json", false, "emit raw event JSON instead of formatted lines")
+}
diff --git a/cmd/oc/internal/commands/logs_test.go b/cmd/oc/internal/commands/logs_test.go
new file mode 100644
index 00000000..75228529
--- /dev/null
+++ b/cmd/oc/internal/commands/logs_test.go
@@ -0,0 +1,73 @@
+package commands
+
+import (
+ "bytes"
+ "encoding/json"
+ "strings"
+ "testing"
+)
+
+func TestStreamSandboxLogs_FormattedMode(t *testing.T) {
+ sse := "" +
+ ": keepalive\n\n" +
+ "data: {\"_time\":\"2026-05-13T12:00:00Z\",\"source\":\"var_log\",\"line\":\"hello\"}\n\n" +
+ ": ping\n\n" +
+ "data: {\"_time\":\"2026-05-13T12:00:01Z\",\"source\":\"exec_stdout\",\"line\":\"world\"}\n\n"
+
+ var out bytes.Buffer
+ if err := streamSandboxLogs(strings.NewReader(sse), &out, false); err != nil {
+ t.Fatalf("stream: %v", err)
+ }
+ s := out.String()
+ for _, want := range []string{"hello", "world", "var_log", "exec_stdout"} {
+ if !strings.Contains(s, want) {
+ t.Errorf("formatted output missing %q:\n%s", want, s)
+ }
+ }
+}
+
+func TestStreamSandboxLogs_JSONMode(t *testing.T) {
+ payload := `{"_time":"2026-05-13T12:00:00Z","source":"var_log","line":"hello"}`
+ sse := "data: " + payload + "\n\n"
+
+ var out bytes.Buffer
+ if err := streamSandboxLogs(strings.NewReader(sse), &out, true); err != nil {
+ t.Fatalf("stream: %v", err)
+ }
+ // In JSON mode, the payload is printed verbatim. Verify it parses back
+ // to the same shape — protects against accidental wrapping/quoting.
+ got := strings.TrimSpace(out.String())
+ var rt map[string]any
+ if err := json.Unmarshal([]byte(got), &rt); err != nil {
+ t.Fatalf("output is not valid JSON: %v\n%s", err, got)
+ }
+ if rt["line"] != "hello" {
+ t.Errorf("round-tripped line = %v, want hello", rt["line"])
+ }
+}
+
+func TestStreamSandboxLogs_SkipsCommentsAndBlanks(t *testing.T) {
+ sse := ": just a keepalive\n\n: another\n\n\n\n"
+ var out bytes.Buffer
+ if err := streamSandboxLogs(strings.NewReader(sse), &out, false); err != nil {
+ t.Fatalf("stream: %v", err)
+ }
+ if out.Len() != 0 {
+ t.Errorf("expected no output for comment-only stream, got: %q", out.String())
+ }
+}
+
+func TestStreamSandboxLogs_TolerantOfMalformedPayload(t *testing.T) {
+ // A bad payload shouldn't kill the whole stream — subsequent good
+ // events should still render.
+ sse := "" +
+ "data: not-json\n\n" +
+ "data: {\"_time\":\"2026-05-13T12:00:00Z\",\"source\":\"var_log\",\"line\":\"after-bad\"}\n\n"
+ var out bytes.Buffer
+ if err := streamSandboxLogs(strings.NewReader(sse), &out, false); err != nil {
+ t.Fatalf("stream: %v", err)
+ }
+ if !strings.Contains(out.String(), "after-bad") {
+ t.Errorf("good event after malformed payload was dropped:\n%s", out.String())
+ }
+}
diff --git a/cmd/oc/internal/commands/root.go b/cmd/oc/internal/commands/root.go
index fe089839..4ad73120 100644
--- a/cmd/oc/internal/commands/root.go
+++ b/cmd/oc/internal/commands/root.go
@@ -71,6 +71,7 @@ func init() {
rootCmd.AddCommand(secretCmd)
rootCmd.AddCommand(configCmd)
rootCmd.AddCommand(agentCmd)
+ rootCmd.AddCommand(logsCmd)
// Top-level shortcuts
rootCmd.AddCommand(createShortcut)
diff --git a/internal/api/sandbox_logs.go b/internal/api/sandbox_logs.go
index 5b2c7bd7..53f0231c 100644
--- a/internal/api/sandbox_logs.go
+++ b/internal/api/sandbox_logs.go
@@ -127,6 +127,11 @@ func (s *Server) getSandboxLogs(c echo.Context) error {
if err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})
}
+ // Non-running sandboxes (stopped / error / hibernated): no new events
+ // will arrive post-stop, so tail mode is wasted polling. Cap the window
+ // at stoppedAt+grace too — the shipper finishes flushing within a few
+ // seconds of process exit; 30s covers ingest latency comfortably.
+ q = applySessionState(q, session.Status, session.StoppedAt)
// SSE headers + immediate flush so the browser knows the stream is open.
c.Response().Header().Set("Content-Type", "text/event-stream")
@@ -226,6 +231,27 @@ type logQuery struct {
tail bool
}
+// applySessionState narrows a parsed query based on the sandbox's
+// lifecycle. For stopped/error/hibernated sandboxes:
+// - tail is forced false (no new events will arrive)
+// - until is capped at stoppedAt + 30s grace (avoid polling into a void
+// of empty Axiom windows)
+//
+// Pure function (no DB dep) so the lifecycle behaviour is unit-testable.
+func applySessionState(q logQuery, status string, stoppedAt *time.Time) logQuery {
+ if status == "running" {
+ return q
+ }
+ q.tail = false
+ if stoppedAt != nil {
+ bound := stoppedAt.Add(30 * time.Second)
+ if q.until.IsZero() || q.until.After(bound) {
+ q.until = bound
+ }
+ }
+ return q
+}
+
func parseLogQuery(sandboxID string, sandboxStarted time.Time, qs url.Values) (logQuery, error) {
q := logQuery{
sandboxID: sandboxID,
diff --git a/internal/api/sandbox_logs_test.go b/internal/api/sandbox_logs_test.go
index e8329d21..31d8bfd7 100644
--- a/internal/api/sandbox_logs_test.go
+++ b/internal/api/sandbox_logs_test.go
@@ -213,3 +213,69 @@ func TestApplyClientFilters_TextAndSourceComposed(t *testing.T) {
t.Errorf("got %v, want only 'error in foo'", got)
}
}
+
+// TestApplySessionState_RunningPassthrough: a running sandbox keeps the
+// query exactly as parsed — no narrowing.
+func TestApplySessionState_RunningPassthrough(t *testing.T) {
+ q := logQuery{tail: true, until: time.Time{}}
+ got := applySessionState(q, "running", nil)
+ if !got.tail {
+ t.Errorf("running sandbox: tail = false, want true (caller-set default)")
+ }
+ if !got.until.IsZero() {
+ t.Errorf("running sandbox: until set to %v, want zero", got.until)
+ }
+}
+
+// TestApplySessionState_StoppedForcesHistorical: any non-running status
+// flips tail off. New events can't arrive once the sandbox is gone.
+func TestApplySessionState_StoppedForcesHistorical(t *testing.T) {
+ for _, status := range []string{"stopped", "error", "hibernated", "migrating"} {
+ t.Run(status, func(t *testing.T) {
+ q := logQuery{tail: true}
+ got := applySessionState(q, status, nil)
+ if got.tail {
+ t.Errorf("status=%s: tail = true, want false", status)
+ }
+ })
+ }
+}
+
+// TestApplySessionState_CapsUntilAtStoppedAtGrace: non-running sandboxes
+// with a stoppedAt timestamp get `until` bounded to stoppedAt + 30s. If
+// the caller already passed a tighter `until`, theirs wins.
+func TestApplySessionState_CapsUntilAtStoppedAtGrace(t *testing.T) {
+ stopped := time.Date(2026, 5, 13, 12, 0, 0, 0, time.UTC)
+ t.Run("unset until gets capped", func(t *testing.T) {
+ q := logQuery{tail: true}
+ got := applySessionState(q, "stopped", &stopped)
+ want := stopped.Add(30 * time.Second)
+ if !got.until.Equal(want) {
+ t.Errorf("until = %v, want %v", got.until, want)
+ }
+ })
+ t.Run("tighter until kept", func(t *testing.T) {
+ tighter := stopped.Add(-1 * time.Hour)
+ q := logQuery{tail: true, until: tighter}
+ got := applySessionState(q, "stopped", &stopped)
+ if !got.until.Equal(tighter) {
+ t.Errorf("until = %v, want caller-set %v", got.until, tighter)
+ }
+ })
+ t.Run("until in future gets clamped", func(t *testing.T) {
+ future := stopped.Add(1 * time.Hour)
+ q := logQuery{tail: true, until: future}
+ got := applySessionState(q, "stopped", &stopped)
+ want := stopped.Add(30 * time.Second)
+ if !got.until.Equal(want) {
+ t.Errorf("until = %v, want %v (capped at stoppedAt+30s)", got.until, want)
+ }
+ })
+ t.Run("no stoppedAt → no until set", func(t *testing.T) {
+ q := logQuery{tail: true}
+ got := applySessionState(q, "error", nil)
+ if !got.until.IsZero() {
+ t.Errorf("error+no-stoppedAt: until = %v, want zero", got.until)
+ }
+ })
+}
diff --git a/web/src/pages/SessionDetail.tsx b/web/src/pages/SessionDetail.tsx
index ea6bb094..60e02003 100644
--- a/web/src/pages/SessionDetail.tsx
+++ b/web/src/pages/SessionDetail.tsx
@@ -3,6 +3,7 @@ import { useParams, useNavigate } from 'react-router-dom'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { getSessionDetail, getSessionStats, rebootSession, powerCycleSession } from '../api/client'
import Terminal from '../components/Terminal'
+import LogsPanel from '../components/LogsPanel'
function StatusBadge({ status }: { status: string }) {
const cls =
@@ -62,6 +63,7 @@ export default function SessionDetail() {
const queryClient = useQueryClient()
const [copiedUrl, setCopiedUrl] = useState<string | null>(null)
const [showTerminal, setShowTerminal] = useState(false)
+ const [showLogs, setShowLogs] = useState(false)
const [showInternal, setShowInternal] = useState(false)
const [resetState, setResetState] = useState<'idle' | 'rebooting' | 'power-cycling'>('idle')
const [resetError, setResetError] = useState<string | null>(null)
@@ -177,6 +179,24 @@ export default function SessionDetail() {
{/* Actions */}
<div style={{ display: 'flex', gap: 8 }}>
+ {/* Logs is available regardless of sandbox status — Axiom
+ retains events past the sandbox's lifetime, so users can
+ fetch logs of stopped / hibernated / errored sandboxes. */}
+ <button
+ className={showLogs ? 'btn-primary' : 'btn-ghost'}
+ onClick={() => setShowLogs(!showLogs)}
+ title="Live logs from /var/log + every exec'd command"
+ >
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
+ <line x1="8" y1="6" x2="21" y2="6" />
+ <line x1="8" y1="12" x2="21" y2="12" />
+ <line x1="8" y1="18" x2="21" y2="18" />
+ <line x1="3" y1="6" x2="3.01" y2="6" />
+ <line x1="3" y1="12" x2="3.01" y2="12" />
+ <line x1="3" y1="18" x2="3.01" y2="18" />
+ </svg>
+ Logs
+ </button>
{session.status === 'running' && (
<>
<button
@@ -239,6 +259,13 @@ export default function SessionDetail() {
</div>
)}
+ {/* Logs — works for all sandbox states (Axiom retains past-lifetime). */}
+ {showLogs && (
+ <div className="glass-card animate-in" style={{ padding: 20, marginBottom: 16 }}>
+ <LogsPanel sandboxId={sandboxId!} onClose={() => setShowLogs(false)} />
+ </div>
+ )}
+
{/* Stats cards — only for running sandboxes */}
{session.status === 'running' && (
<div className="glass-card animate-in stagger-1" style={{ padding: 20, marginBottom: 16 }}>