Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
188 changes: 149 additions & 39 deletions cli/cmd/doctor.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ package cmd

import (
"fmt"
"net/url"
"os"
"path/filepath"
"strings"
"time"

"github.com/Aureliolo/synthorg/cli/internal/config"
"github.com/Aureliolo/synthorg/cli/internal/diagnostics"
"github.com/Aureliolo/synthorg/cli/internal/version"
"github.com/Aureliolo/synthorg/cli/internal/ui"
"github.com/spf13/cobra"
)

Expand All @@ -24,65 +24,175 @@ func init() {
rootCmd.AddCommand(doctorCmd)
}

func runDoctor(cmd *cobra.Command, args []string) error {
func runDoctor(cmd *cobra.Command, _ []string) error {
ctx := cmd.Context()
dir := resolveDataDir()
out := cmd.OutOrStdout()
out := ui.NewUI(cmd.OutOrStdout())

state, err := config.Load(dir)
if err != nil {
return fmt.Errorf("loading config: %w", err)
}

_, _ = fmt.Fprintln(out, "Collecting diagnostics...")
out.Step("Collecting diagnostics...")
report := diagnostics.Collect(ctx, state)
text := report.FormatText()

// Save to file.
// Save full plain-text report to file (for bug report attachment).
safeDir, err := safeStateDir(state)
if err != nil {
return err
}
filename := fmt.Sprintf("synthorg-diagnostic-%s.txt", time.Now().Format("20060102-150405"))
savePath := filepath.Join(safeDir, filename)
text := report.FormatText()
if err := os.WriteFile(savePath, []byte(text), 0o600); err != nil {
_, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Warning: could not save diagnostic file: %v\n", err)
out.Warn(fmt.Sprintf("Could not save diagnostic file: %v", err))
} else {
_, _ = fmt.Fprintf(out, "Saved to: %s\n\n", savePath)
out.Success(fmt.Sprintf("Saved to: %s", savePath))
}
_, _ = fmt.Fprintln(out.Writer())

_, _ = fmt.Fprintln(out, text)

// Generate GitHub issue URL (exclude logs — may contain secrets).
issueTitle := fmt.Sprintf("[CLI] Bug report — %s/%s, CLI %s", report.OS, report.Arch, report.CLIVersion)
issueBody := fmt.Sprintf(
"## Environment\n\nOS: %s/%s\nCLI: %s (%s)\nDocker: %s\nCompose: %s\nHealth: %s\n\n"+
"> Full diagnostics saved to: attach the file from `synthorg doctor` output\n\n"+
"## Steps to Reproduce\n\n1. \n\n## Expected Behavior\n\n\n## Actual Behavior\n\n",
report.OS, report.Arch, report.CLIVersion, report.CLICommit,
report.DockerVersion, report.ComposeVersion, report.HealthStatus,
)

// Truncate body if URL would exceed browser limits (~4000 chars).
encodedBody := url.QueryEscape(issueBody)
if len(encodedBody) > 3500 {
issueBody = fmt.Sprintf(
"## Environment\n\nOS: %s/%s\nCLI: %s\nDocker: %s\nHealth: %s\n\n"+
"> Attach the full diagnostics file from `synthorg doctor` output\n",
report.OS, report.Arch, report.CLIVersion,
report.DockerVersion, report.HealthStatus,
)
encodedBody = url.QueryEscape(issueBody)
}
// Render styled output to terminal.
renderDoctorEnvironment(out, report)
renderDoctorHealth(out, report)
renderDoctorContainers(out, report)
renderDoctorImages(out, report)
renderDoctorInfra(out, report)
renderDoctorConfig(out, state)
renderDoctorDisk(out, report)
renderDoctorErrors(out, report)

issueURL := fmt.Sprintf(
"%s/issues/new?title=%s&labels=type%%3Abug&body=%s",
version.RepoURL,
url.QueryEscape(issueTitle),
encodedBody,
)
_, _ = fmt.Fprintln(out.Writer())
out.Section("Links")
out.Link("Dashboard", fmt.Sprintf("http://localhost:%d", state.WebPort))
out.Link("API docs", fmt.Sprintf("http://localhost:%d/api", state.BackendPort))

_, _ = fmt.Fprintf(out, "File a bug report:\n %s\n", issueURL)
_, _ = fmt.Fprintln(out.Writer())
out.Hint("Run 'synthorg doctor report' to file a bug report")
out.Hint("Run 'synthorg logs' to view container logs")

return nil
}

func renderDoctorEnvironment(out *ui.UI, r diagnostics.Report) {
out.Section("Environment")
out.KeyValue("OS", fmt.Sprintf("%s/%s", r.OS, r.Arch))
out.KeyValue("CLI", fmt.Sprintf("%s (%s)", r.CLIVersion, r.CLICommit))
out.KeyValue("Docker", r.DockerVersion)
out.KeyValue("Compose", r.ComposeVersion)
_, _ = fmt.Fprintln(out.Writer())
}

func renderDoctorHealth(out *ui.UI, r diagnostics.Report) {
if r.HealthStatus == "" {
return
}
switch r.HealthStatus {
case "200":
out.Success(fmt.Sprintf("Backend healthy (HTTP %s)", r.HealthStatus))
case "unreachable":
out.Error("Backend unreachable")
default:
out.Error(fmt.Sprintf("Backend unhealthy (HTTP %s)", r.HealthStatus))
}
}

func renderDoctorContainers(out *ui.UI, r diagnostics.Report) {
if len(r.ContainerSummary) == 0 {
out.Warn("No containers detected")
return
}
_, _ = fmt.Fprintln(out.Writer())
out.Section("Containers")
for _, c := range r.ContainerSummary {
icon := healthIcon(c.State, c.Health)
health := c.Health
if health == "" {
health = c.State
}
switch {
case health == "healthy":
out.Success(fmt.Sprintf("%-24s %s", c.Name, health))
case health == "unhealthy", c.State == "exited":
out.Error(fmt.Sprintf("%-24s %s", c.Name, health))
default:
out.Warn(fmt.Sprintf("%-24s %s (%s)", c.Name, icon+" "+c.State, health))
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Outdated
}
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
}

func renderDoctorImages(out *ui.UI, r diagnostics.Report) {
if len(r.ImageStatus) == 0 {
return
}
_, _ = fmt.Fprintln(out.Writer())
out.Section("Images")
for _, img := range r.ImageStatus {
if strings.Contains(img, "available") {
out.Success(img)
} else {
out.Error(img)
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
}
}

func renderDoctorInfra(out *ui.UI, r diagnostics.Report) {
_, _ = fmt.Fprintln(out.Writer())
if r.ComposeFileExists {
valid := "not checked"
if r.ComposeFileValid != nil {
if *r.ComposeFileValid {
valid = "valid"
} else {
valid = "invalid"
}
}
if valid == "valid" {
out.Success(fmt.Sprintf("Compose file: exists, %s", valid))
} else {
out.Warn(fmt.Sprintf("Compose file: exists, %s", valid))
}
} else {
out.Error("Compose file: not found")
}
for _, conflict := range r.PortConflicts {
out.Error(fmt.Sprintf("Port conflict: %s", conflict))
}
}

func renderDoctorConfig(out *ui.UI, state config.State) {
_, _ = fmt.Fprintln(out.Writer())
out.Section("Config")
out.KeyValue("Data dir", state.DataDir)
out.KeyValue("Image tag", state.ImageTag)
out.KeyValue("Backend port", fmt.Sprintf("%d", state.BackendPort))
out.KeyValue("Web port", fmt.Sprintf("%d", state.WebPort))
out.KeyValue("Sandbox", fmt.Sprintf("%v", state.Sandbox))
out.KeyValue("Persistence", state.PersistenceBackend)
out.KeyValue("Memory", state.MemoryBackend)
out.KeyValue("Log level", state.LogLevel)
if state.JWTSecret != "" {
out.KeyValue("JWT secret", "****")
}
}

func renderDoctorDisk(out *ui.UI, r diagnostics.Report) {
if r.DiskInfo == "" {
return
}
_, _ = fmt.Fprintln(out.Writer())
out.Section("Disk")
// DiskInfo is a single line like "Total: 930.6 GiB Used: 596.8 GiB Free: 333.7 GiB (64% used)"
_, _ = fmt.Fprintf(out.Writer(), " %s\n", r.DiskInfo)
}

func renderDoctorErrors(out *ui.UI, r diagnostics.Report) {
if len(r.Errors) == 0 {
return
}
_, _ = fmt.Fprintln(out.Writer())
out.Section("Errors")
for _, e := range r.Errors {
out.Error(e)
}
}
133 changes: 133 additions & 0 deletions cli/cmd/doctor_report.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
package cmd

import (
"fmt"
"net/url"
"os"
"path/filepath"
"time"

"github.com/Aureliolo/synthorg/cli/internal/config"
"github.com/Aureliolo/synthorg/cli/internal/diagnostics"
"github.com/Aureliolo/synthorg/cli/internal/ui"
"github.com/Aureliolo/synthorg/cli/internal/version"
"github.com/spf13/cobra"
)

var doctorReportCmd = &cobra.Command{
Use: "report",
Short: "Generate a diagnostic archive and open a bug report",
Long: "Collects diagnostics, saves a report file, and opens a pre-filled GitHub issue URL in the browser.",
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Outdated
RunE: runDoctorReport,
}

func init() {
doctorCmd.AddCommand(doctorReportCmd)
}

func runDoctorReport(cmd *cobra.Command, _ []string) error {
ctx := cmd.Context()
dir := resolveDataDir()
out := ui.NewUI(cmd.OutOrStdout())

state, err := config.Load(dir)
if err != nil {
return fmt.Errorf("loading config: %w", err)
}

out.Step("Collecting diagnostics...")
report := diagnostics.Collect(ctx, state)

safeDir, err := safeStateDir(state)
if err != nil {
return err
}

// Save diagnostic report.
filename := fmt.Sprintf("synthorg-diagnostic-%s.txt",
time.Now().Format("20060102-150405"))
savePath := filepath.Join(safeDir, filename)
text := report.FormatText()
if err := os.WriteFile(savePath, []byte(text), 0o600); err != nil {
Comment thread Dismissed
return fmt.Errorf("saving diagnostic file: %w", err)
}
out.Success(fmt.Sprintf("Diagnostic file: %s", savePath))

// Build issue URL.
issueURL := buildBugReportURL(report, state)

_, _ = fmt.Fprintln(out.Writer())
out.Section("Bug Report")
out.Hint("1. Open the URL below in your browser")
out.Hint("2. Attach the diagnostic file to the issue")
_, _ = fmt.Fprintln(out.Writer())
_, _ = fmt.Fprintln(out.Writer(), issueURL)

return nil
}

func buildBugReportURL(report diagnostics.Report, state config.State) string {
title := fmt.Sprintf("[CLI] Bug report — %s/%s, CLI %s",
report.OS, report.Arch, report.CLIVersion)

// Build container summary lines.
var containers string
for _, c := range report.ContainerSummary {
health := c.Health
if health == "" {
health = c.State
}
containers += fmt.Sprintf("| %s | %s | %s |\n", c.Name, c.State, health)
}

body := fmt.Sprintf(
"## Environment\n\n"+
"| Field | Value |\n"+
"|-------|-------|\n"+
"| OS | %s/%s |\n"+
"| CLI | %s (%s) |\n"+
"| Docker | %s |\n"+
"| Compose | %s |\n"+
"| Health | %s |\n"+
"| Persistence | %s |\n"+
"| Memory | %s |\n"+
"| Image tag | %s |\n"+
"| Sandbox | %v |\n\n",
report.OS, report.Arch,
report.CLIVersion, report.CLICommit,
report.DockerVersion, report.ComposeVersion,
report.HealthStatus,
state.PersistenceBackend, state.MemoryBackend,
state.ImageTag, state.Sandbox,
)

if containers != "" {
body += "## Containers\n\n" +
"| Name | State | Health |\n" +
"|------|-------|--------|\n" +
containers + "\n"
}

body += "> Attach the diagnostic file from `synthorg doctor report`\n\n" +
"## Steps to Reproduce\n\n1. \n\n" +
"## Expected Behavior\n\n\n\n" +
"## Actual Behavior\n\n"

// Truncate body if URL would exceed browser limits (~8000 chars).
encodedBody := url.QueryEscape(body)
if len(encodedBody) > 6000 {
body = fmt.Sprintf(
"## Environment\n\nOS: %s/%s\nCLI: %s\nDocker: %s\nHealth: %s\n\n"+
"> Attach the diagnostic file from `synthorg doctor report`\n",
report.OS, report.Arch, report.CLIVersion,
report.DockerVersion, report.HealthStatus,
)
encodedBody = url.QueryEscape(body)
}

return fmt.Sprintf("%s/issues/new?title=%s&labels=type%%3Abug&body=%s",
version.RepoURL,
url.QueryEscape(title),
encodedBody,
)
}
Loading
Loading