Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
refactor(cli): regroup commands and add loading states
Kyle Mendell0f6591f7d316
diff --git a/cli/go.mod b/cli/go.modindex 23ee220d1..e9561ab54 100644--- a/cli/go.mod+++ b/cli/go.mod@@ -10,6 +10,8 @@ require (charm.land/fang/v2 v2.0.1charm.land/lipgloss/v2 v2.0.6charm.land/log/v2 v2.0.1+ github.com/charmbracelet/colorprofile v0.4.3+ github.com/charmbracelet/x/ansi v0.11.8github.com/charmbracelet/x/term v0.2.2github.com/getarcaneapp/arcane/types/v2 v2.14.0github.com/mattn/go-runewidth v0.0.30@@ -29,10 +31,8 @@ require (github.com/atotto/clipboard v0.1.4 // indirectgithub.com/beorn7/perks v1.0.1 // indirectgithub.com/cespare/xxhash/v2 v2.3.0 // indirect- github.com/charmbracelet/colorprofile v0.4.3 // indirectgithub.com/charmbracelet/harmonica v0.2.0 // indirectgithub.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886 // indirect- github.com/charmbracelet/x/ansi v0.11.8 // indirectgithub.com/charmbracelet/x/exp/charmtone v0.0.0-20260527151214-009e6338d40d // indirectgithub.com/charmbracelet/x/termios v0.1.1 // indirectgithub.com/charmbracelet/x/windows v0.2.2 // indirectdiff --git a/cli/internal/client/client.go b/cli/internal/client/client.goindex baf56439e..9201f8883 100644--- a/cli/internal/client/client.go+++ b/cli/internal/client/client.go@@ -44,6 +44,7 @@ import ("github.com/getarcaneapp/arcane/cli/v2/internal/config""github.com/getarcaneapp/arcane/cli/v2/internal/logger"+ "github.com/getarcaneapp/arcane/cli/v2/internal/output""github.com/getarcaneapp/arcane/cli/v2/internal/runstate""github.com/getarcaneapp/arcane/cli/v2/internal/types")@@ -242,6 +243,8 @@ type APIResponse[T any] struct {// as JSON (if provided), and includes authentication headers. The caller is// responsible for closing the response body.func (c *Client) Request(ctx context.Context, method, path string, body any, headers ...http.Header) (*http.Response, error) {+ loading := output.StartLoading(ctx)+ defer loading.Stop()fullURL, err := c.resolveURL(path)if err != nil {return nil, err@@ -293,6 +296,8 @@ func (c *Client) Request(ctx context.Context, method, path string, body any, hea// suitable for multipart form uploads and other non-JSON content types.// Custom headers can be provided to set Content-Type and other headers.func (c *Client) RequestRaw(ctx context.Context, method, path string, body io.Reader, headers map[string]string) (*http.Response, error) {+ loading := output.StartLoading(ctx)+ defer loading.Stop()fullURL, err := c.resolveURL(path)if err != nil {return nil, err@@ -575,6 +580,8 @@ func (c *Client) DeleteWithBody(ctx context.Context, path string, body any) (*ht// successful HTTP status. Unlike GetJSON/PostJSON it does not require the// standard API envelope or its Success flag.func (c *Client) DoJSON[T any](ctx context.Context, method, path string, body any, headers ...http.Header) (T, error) {+ loading := output.StartLoading(ctx)+ defer loading.Stop()var out Tresp, err := c.Request(ctx, method, path, body, headers...)if err != nil {@@ -596,6 +603,8 @@ func (c *Client) DoJSON[T any](ctx context.Context, method, path string, body an// GetJSON performs a GET and decodes the standard API envelope, enforcing// HTTP and API success.func (c *Client) GetJSON[T any](ctx context.Context, path string) (*APIResponse[T], error) {+ loading := output.StartLoading(ctx)+ defer loading.Stop()resp, err := c.Get(ctx, path)if err != nil {return nil, err@@ -607,6 +616,8 @@ func (c *Client) GetJSON[T any](ctx context.Context, path string) (*APIResponse[// PostJSON performs a POST with a JSON body and decodes the standard API// envelope, enforcing HTTP and API success.func (c *Client) PostJSON[T any](ctx context.Context, path string, body any) (*APIResponse[T], error) {+ loading := output.StartLoading(ctx)+ defer loading.Stop()resp, err := c.Post(ctx, path, body)if err != nil {return nil, err@@ -617,6 +628,8 @@ func (c *Client) PostJSON[T any](ctx context.Context, path string, body any) (*A// DoRaw performs a request and returns the response payload when status is 2xx.func (c *Client) DoRaw(ctx context.Context, method, path string, body any) ([]byte, error) {+ loading := output.StartLoading(ctx)+ defer loading.Stop()resp, err := c.Request(ctx, method, path, body)if err != nil {return nil, err@@ -638,6 +651,8 @@ func (c *Client) DoRaw(ctx context.Context, method, path string, body any) ([]by// PutJSON performs a PUT with a JSON body and decodes the standard API// envelope, enforcing HTTP and API success.func (c *Client) PutJSON[T any](ctx context.Context, path string, body any) (*APIResponse[T], error) {+ loading := output.StartLoading(ctx)+ defer loading.Stop()resp, err := c.Put(ctx, path, body)if err != nil {return nil, err@@ -649,6 +664,8 @@ func (c *Client) PutJSON[T any](ctx context.Context, path string, body any) (*AP// DeleteJSON performs a DELETE and decodes the standard API envelope,// enforcing HTTP and API success.func (c *Client) DeleteJSON[T any](ctx context.Context, path string) (*APIResponse[T], error) {+ loading := output.StartLoading(ctx)+ defer loading.Stop()resp, err := c.Delete(ctx, path)if err != nil {return nil, errdiff --git a/cli/internal/cmdutil/context.go b/cli/internal/cmdutil/context.goindex 714a082d7..e6d679f1a 100644--- a/cli/internal/cmdutil/context.go+++ b/cli/internal/cmdutil/context.go@@ -2,13 +2,11 @@ package cmdutilimport ("errors"- "fmt"- "io"- "strings""github.com/spf13/cobra""github.com/getarcaneapp/arcane/cli/v2/internal/client"+ "github.com/getarcaneapp/arcane/cli/v2/internal/output"runtimectx "github.com/getarcaneapp/arcane/cli/v2/internal/runtime")@@ -66,17 +64,5 @@ func Confirm(cmd *cobra.Command, prompt string) (bool, error) {return true, nil}- fmt.Printf("%s (y/N): ", strings.TrimSpace(prompt))- var response string- if _, err := fmt.Scanln(&response); err != nil && !errors.Is(err, io.EOF) {- // Keep EOF as a default "no" response, but surface other input failures.- return false, fmt.Errorf("failed to read confirmation input: %w", err)- }-- switch strings.ToLower(strings.TrimSpace(response)) {- case "y", "yes":- return true, nil- default:- return false, nil- }+ return output.Confirm(cmd.Context(), cmd.InOrStdin(), cmd.ErrOrStderr(), prompt)}diff --git a/cli/internal/cmdutil/response.go b/cli/internal/cmdutil/response.goindex aa6d3dfa4..fd68c882c 100644--- a/cli/internal/cmdutil/response.go+++ b/cli/internal/cmdutil/response.go@@ -9,6 +9,8 @@ import ("io""net/http""strings"++ "github.com/getarcaneapp/arcane/cli/v2/internal/output")const maxErrorBodyBytes = 4096@@ -76,12 +78,12 @@ func ReadJSONBody(resp *http.Response) ([]byte, error) {func PrintRawJSON(body []byte) error {value := jsontext.Value(bytes.Clone(body))if value.Indent(jsontext.WithIndent(" ")) == nil {- fmt.Println(value.String())- return nil+ _, err := fmt.Fprintln(output.Stdout(), value.String())+ return err}// Not valid JSON: echo the server's bytes verbatim rather than swallow them.- fmt.Println(string(body))- return nil+ _, err := fmt.Fprintln(output.Stdout(), string(body))+ return err}// PrintJSON prints indented JSON to stdout.@@ -90,6 +92,6 @@ func PrintJSON(v any) error {if err != nil {return fmt.Errorf("failed to marshal JSON: %w", err)}- fmt.Println(string(b))- return nil+ _, err = fmt.Fprintln(output.Stdout(), string(b))+ return err}diff --git a/cli/internal/cmdutil/run.go b/cli/internal/cmdutil/run.goindex 1dc3407a5..2e185c3e7 100644--- a/cli/internal/cmdutil/run.go+++ b/cli/internal/cmdutil/run.go@@ -35,6 +35,9 @@ type ListSpec[T any] struct {// RunList executes one standard list command as described by spec.func RunList[T any](cmd *cobra.Command, c *client.Client, spec ListSpec[T]) error {+ loading := output.StartTracker(cmd.Context(), cmd.ErrOrStderr(), !spec.JSON, "Loading "+spec.Resource)+ loading.NextStep()+ defer loading.Stop()path, err := ApplyPaginationParams(cmd, spec.Endpoint, spec.Params)if err != nil {return fmt.Errorf("failed to build pagination query: %w", err)@@ -63,6 +66,8 @@ func RunList[T any](cmd *cobra.Command, c *client.Client, spec ListSpec[T]) erroreturn fmt.Errorf("failed to parse response: %w", unmarshalErr)}+ loading.Finish("", nil)+ loading.Stop()rows := make([][]string, len(result.Data))for i, item := range result.Data {rows[i] = spec.Row(item)@@ -98,11 +103,16 @@ func RunPostAction[T any](cmd *cobra.Command, c *client.Client, spec PostActionSc.SetTimeout(spec.Timeout)}+ loading := output.StartTracker(cmd.Context(), cmd.ErrOrStderr(), !spec.JSON, cmd.Short)+ loading.NextStep()+ defer loading.Stop()result, err := c.PostJSON[T](cmd.Context(), spec.Path, spec.Body)if err != nil {return fmt.Errorf("%s: %w", spec.FailureMessage, err)}+ loading.Finish("", nil)+ loading.Stop()if spec.JSON {return PrintJSON(result.Data)}diff --git a/cli/internal/cmdutil/upload.go b/cli/internal/cmdutil/upload.goindex cd8f5a01c..98bad2e6f 100644--- a/cli/internal/cmdutil/upload.go+++ b/cli/internal/cmdutil/upload.go@@ -39,6 +39,9 @@ func UploadFileInChunks(ctx context.Context, c *client.Client, kind, filePath streturn "", fmt.Errorf("failed to stat file: %w", err)}+ loading := output.StartTracker(ctx, output.Stderr(), showProgress, "Creating upload session", "Uploading chunks")+ loading.NextStep()+ defer loading.Stop()created, err := c.PostJSON[uploadtypes.Session](ctx, types.UploadSessions(c.EnvID(), kind), uploadtypes.CreateSessionRequest{Filename: filepath.Base(filePath),Size: fileInfo.Size(),@@ -50,11 +53,9 @@ func UploadFileInChunks(ctx context.Context, c *client.Client, kind, filePath stlog.Debugf("Uploading %s as %d chunks of %d bytes (session %s)", filePath, session.TotalChunks, session.ChunkSize, session.ID)- var progressUI *output.Progress- if showProgress {- progressUI = output.StartProgress("Uploading", fileInfo.Size())- defer progressUI.Stop()- }+ loading.NextStep()+ loading.SetProgress("", "Uploading", 0, fileInfo.Size(), true)+ var uploaded int64deleteSession := func() {if resp, deleteErr := c.Delete(context.WithoutCancel(ctx), types.UploadSession(c.EnvID(), kind, session.ID)); deleteErr == nil {@@ -90,11 +91,11 @@ func UploadFileInChunks(ctx context.Context, c *client.Client, kind, filePath st}log.Debugf("Retrying chunk %d after error: %v", index, chunkErr)}- if progressUI != nil {- progressUI.Add(expected)- }+ uploaded += expected+ loading.SetProgress("", "Uploading", uploaded, fileInfo.Size(), true)}+ loading.Finish("", nil)return session.ID, nil}diff --git a/cli/internal/integrationtest/command_naming_test.go b/cli/internal/integrationtest/command_naming_test.goindex b5f9c0bf0..86afdb803 100644--- a/cli/internal/integrationtest/command_naming_test.go+++ b/cli/internal/integrationtest/command_naming_test.go@@ -5,19 +5,18 @@ import ("testing""github.com/spf13/cobra"+ "github.com/stretchr/testify/require"clipkg "github.com/getarcaneapp/arcane/cli/v2/pkg")-// Command names must never contain hyphens; multi-word actions are flags or-// nested subcommands instead. Hidden commands are exempt (back-compat-// spellings of renamed commands), as is self-update — the one allowed-// hyphenated name.+// Multi-word actions use flags or nested commands, except the explicit+// self-update, auto-update, and api-keys names. Hidden commands are exempt.func TestNoHyphenatedCommandNames(t *testing.T) {var walk func(cmd *cobra.Command, path string)walk = func(cmd *cobra.Command, path string) {for _, child := range cmd.Commands() {- if child.Hidden || child.Name() == "self-update" {+ if child.Hidden || child.Name() == "self-update" || child.Name() == "auto-update" || child.Name() == "api-keys" {continue}childPath := path + " " + child.Name()@@ -29,4 +28,34 @@ func TestNoHyphenatedCommandNames(t *testing.T) {}root := clipkg.RootCommand()walk(root, root.Name())+ for _, path := range [][]string{+ {"images", "vulnerabilities", "scan"},+ {"admin", "backups", "list"},+ {"volumes", "backups", "list"},+ {"jobs", "schedules", "get"},+ {"jobs", "schedules", "update"},+ {"jobs", "list"},+ {"jobs", "run"},+ {"containers", "auto-update"},+ {"auth", "api-keys", "list"},+ {"admin", "api-keys", "list"},+ } {+ cmd, remaining, err := root.Find(path)+ require.NoError(t, err)+ require.Empty(t, remaining, "command %s was not fully resolved", strings.Join(path, " "))+ require.Equal(t, root.Name()+" "+strings.Join(path, " "), cmd.CommandPath())+ }+ for _, path := range [][]string{+ {"backups"},+ {"vulnerabilities"},+ {"jobs", "get"},+ {"jobs", "update"},+ {"containers", "autoupdate"},+ {"auth", "keys"},+ {"admin", "keys"},+ } {+ cmd, remaining, err := root.Find(path)+ require.True(t, err != nil || len(remaining) > 0 || cmd.CommandPath() != root.Name()+" "+strings.Join(path, " "),+ "old command %s is still registered", strings.Join(path, " "))+ }}diff --git a/cli/internal/integrationtest/json_contract_test.go b/cli/internal/integrationtest/json_contract_test.goindex 719c0b165..85faccc85 100644--- a/cli/internal/integrationtest/json_contract_test.go+++ b/cli/internal/integrationtest/json_contract_test.go@@ -8,6 +8,8 @@ import ("testing""github.com/stretchr/testify/require"++ "github.com/getarcaneapp/arcane/cli/v2/internal/config")func TestContainersListJSONContract(t *testing.T) {@@ -32,12 +34,15 @@ func TestContainersListJSONContract(t *testing.T) {outBuf, errOut, err := executeCLIIntegrationCommandInternal(t,- []string{"--config", configPath, "containers", "list", "--json"},+ []string{"--config", configPath, "--log-level", "debug", "containers", "list", "--json"},)require.NoError(t, err,"execute: %v (%s)", err, errOut)+ require.Contains(t, errOut, "Sending request")+ require.NotContains(t, outBuf, "Sending request")+ require.NotContains(t, outBuf, "\x1b")var got map[string]any{unmarshalErr := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &got)@@ -53,3 +58,63 @@ func TestContainersListJSONContract(t *testing.T) {}}}++func TestVersionOutput(t *testing.T) {+ for _, tc := range []struct {+ name string+ status int+ body string+ json bool+ unavailable bool+ }{+ {name: "both versions", status: http.StatusOK, body: `{"currentVersion":"1.2.3","displayVersion":"v1.2.3","revision":"server-revision"}`},+ {name: "server JSON", status: http.StatusOK, body: `{"currentVersion":"1.2.3","displayVersion":"v1.2.3","revision":"server-revision"}`, json: true},+ {name: "unavailable text", status: http.StatusUnauthorized, body: `{"error":"unauthorized"}`, unavailable: true},+ {name: "unavailable JSON", status: http.StatusUnauthorized, body: `{"error":"unauthorized"}`, json: true, unavailable: true},+ {name: "invalid server response", status: http.StatusOK, body: `invalid JSON`, unavailable: true},+ } {+ t.Run(tc.name, func(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/app-version" {+ t.Errorf("unexpected version endpoint: %s", r.URL.Path)+ w.WriteHeader(http.StatusNotFound)+ return+ }+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(tc.status)+ _, _ = w.Write([]byte(tc.body))+ }))+ defer srv.Close()+ args := []string{"--config", writeCLIIntegrationConfigInternal(t, srv.URL), "--no-color", "version"}+ if tc.json {+ args = append(args, "--json")+ }+ out, diagnostics, err := executeCLIIntegrationCommandInternal(t, args)+ if tc.json && tc.unavailable {+ require.Error(t, err)+ require.Empty(t, out)+ return+ }+ require.NoError(t, err)+ if tc.json {+ var got map[string]any+ require.NoError(t, json.Unmarshal([]byte(out), &got))+ require.Equal(t, "v1.2.3", got["displayVersion"])+ require.Equal(t, "server-revision", got["revision"])+ require.NotContains(t, out, "Arcane CLI")+ return+ }+ require.Contains(t, out, "Arcane CLI")+ require.Contains(t, out, config.Version)+ require.Contains(t, out, config.Revision)+ require.Contains(t, out, "Arcane Server")+ if tc.unavailable {+ require.Contains(t, out, "Unavailable")+ require.Contains(t, diagnostics, "Could not get server version")+ } else {+ require.Contains(t, out, "v1.2.3")+ require.Contains(t, out, "server-revision")+ }+ })+ }+}diff --git a/cli/internal/logger/logger.go b/cli/internal/logger/logger.goindex cce6f42be..361b0cb07 100644--- a/cli/internal/logger/logger.go+++ b/cli/internal/logger/logger.go@@ -8,8 +8,8 @@//// Call Setup early in the application lifecycle://-// logger.Setup("debug", false) // debug level, text format-// logger.Setup("info", true) // info level, JSON format+// log.Setup(cmd.ErrOrStderr(), "debug", false) // debug level, text format+// log.Setup(cmd.ErrOrStderr(), "info", true) // info level, JSON format//// # Usage//@@ -20,16 +20,18 @@package loggerimport (- "os"+ "io"charmlog "charm.land/log/v2"++ "github.com/getarcaneapp/arcane/cli/v2/internal/output")// Setup configures the global logger with the specified level and format.// Valid log levels are: debug, info, warn, error, fatal.// If an invalid level is provided, it defaults to info.// When jsonFormat is true, logs are output as JSON for machine parsing.-func Setup(level string, jsonFormat bool) {+func Setup(w io.Writer, level string, jsonFormat bool) {lvl, err := charmlog.ParseLevel(level)if err != nil {lvl = charmlog.InfoLevel@@ -37,7 +39,7 @@ func Setup(level string, jsonFormat bool) {log := charmlog.Default()log.SetLevel(lvl)- log.SetOutput(os.Stdout)+ log.SetOutput(output.CoordinatedWriter(w))log.SetReportTimestamp(true)if jsonFormat {diff --git a/cli/internal/output/confirm.go b/cli/internal/output/confirm.gonew file mode 100644index 000000000..66d897c95--- /dev/null+++ b/cli/internal/output/confirm.go@@ -0,0 +1,95 @@+package output++import (+ "context"+ "errors"+ "fmt"+ "io"+ "strings"++ tea "charm.land/bubbletea/v2"+)++// Confirm uses a terminal selector, falling back to line input for scripts.+func Confirm(ctx context.Context, input io.Reader, out io.Writer, label string) (bool, error) {+ if err := ctx.Err(); err != nil {+ return false, err+ }+ defer SuspendProgress()()+ if !IsTerminal(input) || !IsTerminal(out) {+ if _, err := fmt.Fprintf(out, "%s (y/N): ", strings.TrimSpace(label)); err != nil {+ return false, err+ }+ var answer string+ if _, err := fmt.Fscanln(input, &answer); err != nil && !errors.Is(err, io.EOF) {+ return false, fmt.Errorf("failed to read confirmation input: %w", err)+ }+ if err := ctx.Err(); err != nil {+ return false, err+ }+ return strings.EqualFold(answer, "y") || strings.EqualFold(answer, "yes"), nil+ }+ model, err := tea.NewProgram(confirmModel{label: label, out: out}, tea.WithContext(ctx), tea.WithInput(input), tea.WithOutput(out)).Run()+ if ctx.Err() != nil {+ return false, ctx.Err()+ }+ if errors.Is(err, tea.ErrInterrupted) {+ return false, context.Canceled+ }+ if err != nil {+ return false, fmt.Errorf("confirmation prompt: %w", err)+ }+ result, ok := model.(confirmModel)+ if !ok {+ return false, errors.New("confirmation returned an unexpected result")+ }+ return result.confirmed, nil+}++type confirmModel struct {+ label string+ out io.Writer+ yes, confirmed, done bool+}++func (m confirmModel) Init() tea.Cmd { return nil }++func (m confirmModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {+ if m.done {+ return m, nil+ }+ if key, ok := msg.(tea.KeyPressMsg); ok {+ switch strings.ToLower(key.String()) {+ case "left", "right", "up", "down", "tab", "shift+tab":+ m.yes = !m.yes+ case "y":+ m.yes = true+ case "n":+ m.yes = false+ case "enter":+ m.done, m.confirmed = true, m.yes+ return m, tea.Quit+ case "esc", "q":+ m.done = true+ return m, tea.Quit+ case "ctrl+c":+ m.done = true+ return m, tea.Interrupt+ }+ }+ return m, nil+}++func (m confirmModel) View() tea.View {+ if m.done {+ return tea.NewView("")+ }+ no, yes := " No ", " Yes "+ if m.yes {+ yes = "[ Yes ]"+ } else {+ no = "[ No ]"+ }+ hint := renderForInternal(m.out, statusMutedStyle, "←/→ or tab: choose · enter: submit · esc: cancel")+ return tea.NewView("\n " + renderForInternal(m.out, headerStyle, m.label) + "\n\n " + no + " " + yes + "\n\n " + hint + "\n")+}diff --git a/cli/internal/output/output.go b/cli/internal/output/output.goindex ced1dc3c5..5dc6cf92f 100644--- a/cli/internal/output/output.go+++ b/cli/internal/output/output.go@@ -14,12 +14,11 @@ package outputimport ("fmt"- "os"+ "image/color""regexp""strings""charm.land/lipgloss/v2"- "charm.land/lipgloss/v2/compat""charm.land/lipgloss/v2/table""github.com/charmbracelet/x/term""github.com/mattn/go-runewidth"@@ -27,55 +26,37 @@ import ()var (- arcanePurple = compat.AdaptiveColor{- Light: lipgloss.Color("#6d28d9"),- Dark: lipgloss.Color("#a78bfa"),- }- textPrimary = compat.AdaptiveColor{- Light: lipgloss.Color("#1f2937"),- Dark: lipgloss.Color("#e5e7eb"),- }- textMuted = compat.AdaptiveColor{- Light: lipgloss.Color("#64748b"),- Dark: lipgloss.Color("#cbd5e1"),- }- statusOnline = compat.AdaptiveColor{- Light: lipgloss.Color("#15803d"),- Dark: lipgloss.Color("#4ade80"),- }- statusOffline = compat.AdaptiveColor{- Light: lipgloss.Color("#b91c1c"),- Dark: lipgloss.Color("#f87171"),- }- statusWarn = compat.AdaptiveColor{- Light: lipgloss.Color("#b45309"),- Dark: lipgloss.Color("#fbbf24"),- }+ arcanePurple, textPrimary, textMuted, statusOnline, statusOffline, statusWarn color.Color+ successStyle, warnStyle, infoStyle, headerStyle, keyStyle, valueStyle lipgloss.Style+ statusOnlineStyle, statusOfflineStyle, statusWarnStyle, statusMutedStyle, enabledStyle lipgloss.Style+ tableHeader, tableCell, tableOddRow, tableEvenRow, tableBorder, tablePlainCell, tablePlainHead lipgloss.Style)-var (+func init() { setThemeInternal(true) }++func setThemeInternal(dark bool) {+ c := lipgloss.LightDark(dark)+ arcanePurple = c(lipgloss.Color("#6d28d9"), lipgloss.Color("#a78bfa"))+ textPrimary = c(lipgloss.Color("#1f2937"), lipgloss.Color("#e5e7eb"))+ textMuted = c(lipgloss.Color("#64748b"), lipgloss.Color("#cbd5e1"))+ statusOnline = c(lipgloss.Color("#15803d"), lipgloss.Color("#4ade80"))+ statusOffline = c(lipgloss.Color("#b91c1c"), lipgloss.Color("#f87171"))+ statusWarn = c(lipgloss.Color("#b45309"), lipgloss.Color("#fbbf24"))successStyle = lipgloss.NewStyle().Foreground(statusOnline)- warnStyle = lipgloss.NewStyle().Foreground(statusWarn)- infoStyle = lipgloss.NewStyle().Foreground(arcanePurple)- headerStyle = lipgloss.NewStyle().Bold(true).Foreground(arcanePurple)- keyStyle = lipgloss.NewStyle().Bold(true).Foreground(textPrimary)- valueStyle = lipgloss.NewStyle().Foreground(arcanePurple)-- statusOnlineStyle = lipgloss.NewStyle().Foreground(statusOnline)- statusOfflineStyle = lipgloss.NewStyle().Foreground(statusOffline)- statusWarnStyle = lipgloss.NewStyle().Foreground(statusWarn)- statusMutedStyle = lipgloss.NewStyle().Foreground(textMuted)- enabledStyle = lipgloss.NewStyle().Foreground(arcanePurple)-- tablePurple = lipgloss.Color("99")- tableHeader = lipgloss.NewStyle().Foreground(tablePurple).Bold(true).Align(lipgloss.Center).Padding(0, 1)- tableCell = lipgloss.NewStyle().Padding(0, 1)- tableOddRow = tableCell.Foreground(textPrimary)- tableEvenRow = tableCell.Foreground(textPrimary)- tableBorder = lipgloss.NewStyle().Foreground(tablePurple)- tablePlainCell = lipgloss.NewStyle().Padding(0, 1)- tablePlainHead = lipgloss.NewStyle().Bold(true).Padding(0, 1)-)+ warnStyle = lipgloss.NewStyle().Foreground(statusWarn)+ infoStyle = lipgloss.NewStyle().Foreground(arcanePurple)+ headerStyle = infoStyle.Bold(true)+ keyStyle = lipgloss.NewStyle().Foreground(textMuted)+ valueStyle = lipgloss.NewStyle().Foreground(textPrimary)+ statusOnlineStyle, statusOfflineStyle, statusWarnStyle = successStyle, lipgloss.NewStyle().Foreground(statusOffline), warnStyle+ statusMutedStyle = keyStyle+ enabledStyle = infoStyle+ tableCell = lipgloss.NewStyle().Padding(0, 1)+ tableHeader = tableCell.Foreground(arcanePurple).Bold(true).Align(lipgloss.Left)+ tableOddRow, tableEvenRow = tableCell.Foreground(textPrimary), tableCell.Foreground(textPrimary)+ tableBorder = lipgloss.NewStyle().Foreground(arcanePurple)+ tablePlainCell, tablePlainHead = tableCell, tableCell+}var ansiRegexp = regexp.MustCompile("\x1b\\[[0-9;]*[a-zA-Z]")@@ -86,20 +67,12 @@ var tableWhitespaceReplacer = strings.NewReplacer("\r\n", " ", "\n", " ", "\r",var colorEnabled = true-func shouldColor() bool {- return colorEnabled && term.IsTerminal(os.Stdout.Fd())-}--func render(style lipgloss.Style, value string) string {- if !shouldColor() {- return value- }- return style.Render(value)+func shouldColorInternal() bool {+ return colorEnabledInternal() && IsTerminal(Stdout())}-// SetColorEnabled controls whether CLI output should render ANSI colors.-func SetColorEnabled(enabled bool) {- colorEnabled = enabled+func renderInternal(style lipgloss.Style, value string) string {+ return renderForInternal(Stdout(), style, value)}// Success prints a success message in green.@@ -109,7 +82,8 @@ func SetColorEnabled(enabled bool) {//nolint:goprintffuncname // printf-style output helper; *f rename across call sites tracked separatelyfunc Success(format string, a ...any) {msg := fmt.Sprintf(format, a...)- fmt.Printf("\n%s\n", render(successStyle, msg))+ defer SuspendProgress()()+ _, _ = fmt.Fprintf(Stdout(), "\n %s\n", renderInternal(successStyle, "✓ "+msg))}// Warning prints a warning message in yellow.@@ -119,44 +93,49 @@ func Success(format string, a ...any) {//nolint:goprintffuncname // printf-style output helper; *f rename across call sites tracked separatelyfunc Warning(format string, a ...any) {msg := fmt.Sprintf(format, a...)- fmt.Printf("\n%s\n", render(warnStyle, msg))+ defer SuspendProgress()()+ _, _ = fmt.Fprintf(Stderr(), "\n %s\n", renderForInternal(Stderr(), warnStyle, msg))}-// Info prints an info message in cyan.+// Info prints an info message in purple.// The message is prefixed with a newline for visual separation.// Format specifiers and arguments work like fmt.Printf.////nolint:goprintffuncname // printf-style output helper; *f rename across call sites tracked separatelyfunc Info(format string, a ...any) {msg := fmt.Sprintf(format, a...)- fmt.Printf("\n%s\n", render(infoStyle, msg))+ defer SuspendProgress()()+ _, _ = fmt.Fprintf(Stdout(), "\n %s\n", renderInternal(infoStyle, msg))}-// Header prints a header message in bold white.+// Header prints a purple section heading.// Use this to introduce sections of output. The message is prefixed// with a newline for visual separation.////nolint:goprintffuncname // printf-style output helper; *f rename across call sites tracked separatelyfunc Header(format string, a ...any) {msg := fmt.Sprintf(format, a...)- fmt.Printf("\n%s\n", render(headerStyle, msg))+ defer SuspendProgress()()+ _, _ = fmt.Fprintf(Stdout(), "\n %s\n", renderInternal(headerStyle, msg))}-// KeyValue prints a key-value pair with the key in bold and value in blue.+// KeyValue prints a key-value pair with the muted aligned labels and neutral values.// This is useful for displaying structured information like image details// or configuration values.func KeyValue(key string, value any) {keyText := keyvalueText := fmt.Sprint(value)- fmt.Printf("%s: %v\n", render(keyStyle, keyText), render(valueStyle, valueText))+ defer SuspendProgress()()+ _, _ = fmt.Fprintf(Stdout(), " %s %s\n", renderInternal(keyStyle, fmt.Sprintf("%-18s", keyText)), renderInternal(valueStyle, valueText))}// Showing prints a pagination summary in the form "Showing: shown/total label".func Showing(shown int, total int64, label string) {- fmt.Printf("\nShowing: %d/%d %s\n", shown, total, label)+ defer SuspendProgress()()+ _, _ = fmt.Fprintf(Stdout(), "\n Showing: %d/%d %s\n", shown, total, label)}-func hasAnsi(s string) bool {+func hasAnsiInternal(s string) bool {if s == "" {return false}@@ -166,17 +145,18 @@ func hasAnsi(s string) bool {// TintStatus applies semantic status coloring to a value.func TintStatus(value string) string {trimmed := strings.TrimSpace(value)- if trimmed == "" || hasAnsi(trimmed) || !shouldColor() {+ if trimmed == "" || hasAnsiInternal(trimmed) || !shouldColorInternal() {return value}lower := strings.ToLower(trimmed)switch {- case lower == "online" || lower == "running" || lower == "healthy" || lower == "active" || strings.HasPrefix(lower, "up"):+ case lower == "ok" || lower == "succeeded" || lower == "success" || lower == "online" || lower == "running" || lower == "healthy" || lower == "active" || strings.HasPrefix(lower, "up"):return statusOnlineStyle.Render(trimmed)- case lower == "offline" || lower == "stopped" || lower == "exited" || lower == "dead" || lower == "unhealthy" || lower == "failed" || strings.HasPrefix(lower, "down"):+ case lower == "fail" || lower == "error" || lower == "offline" || lower == "stopped" || lower == "exited" ||+ lower == "dead" || lower == "unhealthy" || lower == "failed" || strings.HasPrefix(lower, "down"):return statusOfflineStyle.Render(trimmed)- case lower == "paused" || lower == "restarting" || lower == "starting" || lower == "created" || lower == "degraded":+ case lower == "warn" || lower == "warning" || lower == "paused" || lower == "restarting" || lower == "starting" || lower == "created" || lower == "degraded":return statusWarnStyle.Render(trimmed)default:return statusMutedStyle.Render(trimmed)@@ -186,7 +166,7 @@ func TintStatus(value string) string {// TintEnabled applies tints for enabled/disabled values.func TintEnabled(value string) string {trimmed := strings.TrimSpace(value)- if trimmed == "" || hasAnsi(trimmed) || !shouldColor() {+ if trimmed == "" || hasAnsiInternal(trimmed) || !shouldColorInternal() {return value}lower := strings.ToLower(trimmed)@@ -203,7 +183,7 @@ func TintEnabled(value string) string {// TintYesNo applies tints for yes/no style values.func TintYesNo(value string) string {trimmed := strings.TrimSpace(value)- if trimmed == "" || hasAnsi(trimmed) || !shouldColor() {+ if trimmed == "" || hasAnsiInternal(trimmed) || !shouldColorInternal() {return value}lower := strings.ToLower(trimmed)@@ -220,7 +200,7 @@ func TintYesNo(value string) string {// TintInsecure applies warning tints for insecure values.func TintInsecure(value string) string {trimmed := strings.TrimSpace(value)- if trimmed == "" || hasAnsi(trimmed) || !shouldColor() {+ if trimmed == "" || hasAnsiInternal(trimmed) || !shouldColorInternal() {return value}lower := strings.ToLower(trimmed)@@ -237,7 +217,8 @@ func TintInsecure(value string) string {// Table prints a formatted table with headers and rows.// Rendering uses Lip Gloss table styles with zebra-striped rows.func Table(headers []string, rows [][]string) error {- if _, spacingErr := fmt.Println(); spacingErr != nil {+ defer SuspendProgress()()+ if _, spacingErr := fmt.Fprintln(Stdout()); spacingErr != nil {return fmt.Errorf("failed to print table: %w", spacingErr)}@@ -246,13 +227,13 @@ func Table(headers []string, rows [][]string) error {return nil}- rows = normalizeTableRows(rows, n)- rows = tintTableRows(headers, rows)- headers, rows = fitTableToTerminal(headers, rows)+ rows = normalizeTableRowsInternal(rows, n)+ rows = tintTableRowsInternal(headers, rows)+ headers, rows = fitTableToTerminalInternal(headers, rows)t := table.New().Border(lipgloss.NormalBorder()).Headers(headers...)- if shouldColor() {+ if shouldColorInternal() {t = t.BorderStyle(tableBorder).StyleFunc(func(row, col int) lipgloss.Style {switch {@@ -274,13 +255,13 @@ func Table(headers []string, rows [][]string) error {t = t.Rows(rows...)}- if _, tableErr := lipgloss.Println(t); tableErr != nil {+ if _, tableErr := fmt.Fprintln(Stdout(), t.String()); tableErr != nil {return fmt.Errorf("failed to print table: %w", tableErr)}return nil}-func fitTableToTerminal(headers []string, rows [][]string) ([]string, [][]string) {+func fitTableToTerminalInternal(headers []string, rows [][]string) ([]string, [][]string) {if len(headers) == 0 {return headers, rows}@@ -288,51 +269,52 @@ func fitTableToTerminal(headers []string, rows [][]string) ([]string, [][]stringcolumnCount := len(headers)displayHeaders := make([]string, columnCount)for i, header := range headers {- displayHeaders[i] = sanitizeTableCell(header)+ displayHeaders[i] = sanitizeTableCellInternal(header)}- displayRows := normalizeTableRows(rows, columnCount)+ displayRows := normalizeTableRowsInternal(rows, columnCount)for i, row := range displayRows {cleaned := make([]string, columnCount)for col := range columnCount {- cleaned[col] = sanitizeTableCell(row[col])+ cleaned[col] = sanitizeTableCellInternal(row[col])}displayRows[i] = cleaned}- if !term.IsTerminal(os.Stdout.Fd()) {+ fd, ok := Stdout().(interface{ Fd() uintptr })+ if !ok || !term.IsTerminal(fd.Fd()) {return displayHeaders, displayRows}- terminalWidth, _, err := term.GetSize(os.Stdout.Fd())+ terminalWidth, _, err := term.GetSize(fd.Fd())if err != nil || terminalWidth <= 0 {return displayHeaders, displayRows}columnWidths := make([]int, columnCount)for i, header := range displayHeaders {- columnWidths[i] = max(1, visibleWidth(header))+ columnWidths[i] = max(1, visibleWidthInternal(header))}for _, row := range displayRows {for col := range columnCount {- columnWidths[col] = max(columnWidths[col], visibleWidth(row[col]))+ columnWidths[col] = max(columnWidths[col], visibleWidthInternal(row[col]))}}- availableContentWidth := terminalWidth - tableNonContentWidth(columnCount)+ availableContentWidth := terminalWidth - tableNonContentWidthInternal(columnCount)if availableContentWidth <= 0 {return displayHeaders, displayRows}- fitWidths := fitColumnWidths(columnWidths, availableContentWidth)+ fitWidths := fitColumnWidthsInternal(columnWidths, availableContentWidth)for i, header := range displayHeaders {- displayHeaders[i] = truncateVisible(header, fitWidths[i])+ displayHeaders[i] = truncateVisibleInternal(header, fitWidths[i])}for i, row := range displayRows {for col := range columnCount {- row[col] = truncateVisible(row[col], fitWidths[col])+ row[col] = truncateVisibleInternal(row[col], fitWidths[col])}displayRows[i] = row}@@ -340,20 +322,20 @@ func fitTableToTerminal(headers []string, rows [][]string) ([]string, [][]stringreturn displayHeaders, displayRows}-func sanitizeTableCell(value string) string {+func sanitizeTableCellInternal(value string) string {cleaned := tableWhitespaceReplacer.Replace(value)return strings.TrimSpace(cleaned)}-func visibleWidth(value string) int {+func visibleWidthInternal(value string) int {return runewidth.StringWidth(ansiRegexp.ReplaceAllString(value, ""))}-func truncateVisible(value string, maxWidth int) string {+func truncateVisibleInternal(value string, maxWidth int) string {if maxWidth <= 0 {return ""}- if visibleWidth(value) <= maxWidth {+ if visibleWidthInternal(value) <= maxWidth {return value}@@ -374,7 +356,7 @@ func truncateVisible(value string, maxWidth int) string {return codes[0] + truncated + ansiReset}-func tableNonContentWidth(columnCount int) int {+func tableNonContentWidthInternal(columnCount int) int {const horizontalCellPadding = 2// For normal border style:@@ -383,7 +365,7 @@ func tableNonContentWidth(columnCount int) int {return (columnCount + 1) + (horizontalCellPadding * columnCount)}-func fitColumnWidths(widths []int, available int) []int {+func fitColumnWidthsInternal(widths []int, available int) []int {fitted := make([]int, len(widths))copy(fitted, widths)@@ -395,9 +377,9 @@ func fitColumnWidths(widths []int, available int) []int {available = len(fitted)}- current := sumInts(fitted)+ current := sumIntsInternal(fitted)for current > available {- idx := widestShrinkableColumn(fitted)+ idx := widestShrinkableColumnInternal(fitted)if idx < 0 {break}@@ -408,7 +390,7 @@ func fitColumnWidths(widths []int, available int) []int {return fitted}-func widestShrinkableColumn(widths []int) int {+func widestShrinkableColumnInternal(widths []int) int {idx := -1maxWidth := 1for i, width := range widths {@@ -420,7 +402,7 @@ func widestShrinkableColumn(widths []int) int {return idx}-func sumInts(values []int) int {+func sumIntsInternal(values []int) int {total := 0for _, value := range values {total += value@@ -428,7 +410,7 @@ func sumInts(values []int) int {return total}-func normalizeTableRows(rows [][]string, width int) [][]string {+func normalizeTableRowsInternal(rows [][]string, width int) [][]string {if width == 0 || len(rows) == 0 {return rows}@@ -443,11 +425,11 @@ func normalizeTableRows(rows [][]string, width int) [][]string {return normalized}-func tintTableRows(headers []string, rows [][]string) [][]string {+func tintTableRowsInternal(headers []string, rows [][]string) [][]string {if len(rows) == 0 {return rows}- if !shouldColor() {+ if !shouldColorInternal() {return rows}diff --git a/cli/internal/output/session.go b/cli/internal/output/session.gonew file mode 100644index 000000000..2db74f421--- /dev/null+++ b/cli/internal/output/session.go@@ -0,0 +1,125 @@+package output++import (+ "context"+ "fmt"+ "io"+ "os"+ "strconv"+ "strings"+ "sync"++ "charm.land/lipgloss/v2"+ "github.com/charmbracelet/colorprofile"+ "github.com/charmbracelet/x/term"+)++var (+ sessionMu sync.RWMutex+ resultWriter io.Writer+ diagnosticWriter io.Writer+ plainMode = true+ commandLabel = "Loading"+)++// Configure binds output to the current command's writers and output mode.+func Configure(stdout, stderr io.Writer, jsonMode, noColor bool, label string) {+ sessionMu.Lock()+ defer sessionMu.Unlock()+ resultWriter, diagnosticWriter = stdout, stderr+ plainMode = jsonMode+ colorEnabled = !noColor+ commandLabel = label+ setThemeInternal(detectDarkBackgroundInternal(stdout, noColor))+}++// Stdout returns the current command's result writer.+func Stdout() io.Writer {+ sessionMu.RLock()+ defer sessionMu.RUnlock()+ if resultWriter != nil {+ return resultWriter+ }+ return os.Stdout+}++// Stderr returns the current command's diagnostic writer.+func Stderr() io.Writer {+ sessionMu.RLock()+ defer sessionMu.RUnlock()+ if diagnosticWriter != nil {+ return diagnosticWriter+ }+ return os.Stderr+}++// IsTerminal checks the actual writer, including terminal capability.+func IsTerminal(value any) bool {+ if writer, ok := value.(*colorprofile.Writer); ok {+ value = writer.Forward+ }+ fd, ok := value.(interface{ Fd() uintptr })+ return ok && os.Getenv("TERM") != "dumb" && term.IsTerminal(fd.Fd())+}++func colorEnabledInternal() bool {+ sessionMu.RLock()+ defer sessionMu.RUnlock()+ _, noColor := os.LookupEnv("NO_COLOR")+ return colorEnabled && !noColor+}++func renderForInternal(w io.Writer, style lipgloss.Style, value string) string {+ if !colorEnabledInternal() || !IsTerminal(w) {+ return value+ }+ return style.Render(value)+}++// StartLoading tracks the current command while a request is in progress.+func StartLoading(ctx context.Context) *tracker {+ sessionMu.RLock()+ enabled, label := !plainMode, commandLabel+ sessionMu.RUnlock()+ trackersMu.Lock()+ enabled = enabled && len(activeTrackers) == 0+ trackersMu.Unlock()+ t := StartTracker(ctx, Stderr(), enabled, label)+ t.NextStep()+ return t+}++// CoordinatedWriter clears loading while another writer uses the terminal.+func CoordinatedWriter(w io.Writer) io.Writer { return coordinatedWriter{out: w} }++type coordinatedWriter struct{ out io.Writer }++func (w coordinatedWriter) Write(p []byte) (int, error) {+ defer SuspendProgress()()+ return w.out.Write(p)+}++// WriteError renders the command error once through Fang's error handler.+func WriteError(w io.Writer, err error) {+ defer SuspendProgress()()+ _, _ = fmt.Fprintf(w, "\n %s\n %s\n", renderForInternal(w, headerStyle.Foreground(statusOffline), "Error"), err.Error())+}++func detectDarkBackgroundInternal(out io.Writer, noColor bool) bool {+ if noColor || !IsTerminal(out) {+ return true+ }+ if _, disabled := os.LookupEnv("NO_COLOR"); disabled {+ return true+ }+ if value := os.Getenv("COLORFGBG"); value != "" {+ fields := strings.Split(value, ";")+ if background, err := strconv.Atoi(fields[len(fields)-1]); err == nil {+ return background != 7 && background != 15+ }+ }+ if file, ok := out.(term.File); ok && IsTerminal(os.Stdin) {+ return lipgloss.HasDarkBackground(os.Stdin, file)+ }+ return true+}diff --git a/cli/internal/output/transfer.go b/cli/internal/output/transfer.gonew file mode 100644index 000000000..4d5a337ca--- /dev/null+++ b/cli/internal/output/transfer.go@@ -0,0 +1,36 @@+package output++import (+ "context"+ "io"+)++// Copy copies a transfer while reporting bytes, or activity for unknown totals.+func Copy(ctx context.Context, dst io.Writer, src io.Reader, total int64, label string, enabled bool) (int64, error) {+ loading := StartTracker(ctx, Stderr(), enabled, label)+ loading.NextStep()+ defer loading.Stop()+ reader := &transferReader{ctx: ctx, source: src, loading: loading, total: total, label: label}+ loading.SetProgress("", label, 0, total, true)+ written, err := io.Copy(dst, reader)+ loading.Finish("", err)+ return written, err+}++type transferReader struct {+ ctx context.Context+ source io.Reader+ loading *tracker+ current, total int64+ label string+}++func (r *transferReader) Read(p []byte) (int, error) {+ if err := r.ctx.Err(); err != nil {+ return 0, err+ }+ n, err := r.source.Read(p)+ r.current += int64(n)+ r.loading.SetProgress("", r.label, r.current, r.total, true)+ return n, err+}diff --git a/cli/internal/output/tui.go b/cli/internal/output/tui.goindex eedb5286f..32c91bb01 100644--- a/cli/internal/output/tui.go+++ b/cli/internal/output/tui.go@@ -1,240 +1,270 @@package outputimport (+ "context""fmt"+ "io"+ "strings""sync"+ "time""charm.land/bubbles/v2/progress"- "charm.land/bubbles/v2/spinner"- tea "charm.land/bubbletea/v2"+ "github.com/charmbracelet/x/ansi"+ "github.com/charmbracelet/x/term""go.getarcane.app/sys/bytes")-type spinnerDoneMsg struct{}+var spinnerFrames = []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"}-type spinnerModel struct {- spinner spinner.Model- label string-}--func newSpinnerModel(label string) spinnerModel {- s := spinner.New()- s.Spinner = spinner.Dot- return spinnerModel{spinner: s, label: label}-}--func (m spinnerModel) Init() tea.Cmd {- return m.spinner.Tick-}+var (+ trackersMu sync.Mutex+ activeTrackers = make(map[*tracker]struct{})+ terminalMu sync.Mutex+)-func (m spinnerModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {- switch msg := msg.(type) {- case spinnerDoneMsg:- return m, tea.Quit- case tea.KeyPressMsg:- switch msg.String() {- case "q", "esc", "ctrl+c":- return m, tea.Quit- }- }+const (+ stepPending = iota+ stepRunning+ stepSucceeded+ stepFailed+)- var cmd tea.Cmd- m.spinner, cmd = m.spinner.Update(msg)- return m, cmd+type trackerStep struct {+ key, label string+ status int+ current, total int64+ bytes bool}-func (m spinnerModel) View() tea.View {- return tea.NewView(fmt.Sprintf("%s %s", m.spinner.View(), m.label))+type tracker struct {+ mu sync.Mutex+ out io.Writer+ live bool+ steps []trackerStep+ current, drawn, frame, paused int+ stopped bool+ stop, done chan struct{}+ once sync.Once+ resumeOuter func()}-// Spinner renders a Bubble Tea spinner inline.-type Spinner struct {- program *tea.Program- done chan struct{}+// StartTracker renders a checklist only for interactive text output.+func StartTracker(ctx context.Context, out io.Writer, enabled bool, labels ...string) *tracker {+ if out == nil {+ out = io.Discard+ }+ t := &tracker{out: out, live: enabled && IsTerminal(out) && IsTerminal(Stdout()), current: -1}+ for _, label := range labels {+ t.steps = append(t.steps, trackerStep{label: label, status: stepPending})+ }+ if !t.live || ctx.Err() != nil {+ t.live = false+ return t+ }+ t.stop, t.done = make(chan struct{}), make(chan struct{})+ t.resumeOuter = SuspendProgress()+ trackersMu.Lock()+ activeTrackers[t] = struct{}{}+ trackersMu.Unlock()+ go t.runInternal(ctx)+ return t}-// StartSpinner starts a spinner with the given label.-func StartSpinner(label string) *Spinner {- model := newSpinnerModel(label)- program := tea.NewProgram(model)- done := make(chan struct{})-- spin := &Spinner{program: program, done: done}- go func() {- _, _ = program.Run()- close(done)+func (t *tracker) runInternal(ctx context.Context) {+ defer close(t.done)+ defer func() {+ t.mu.Lock()+ defer t.mu.Unlock()+ t.stopped = true+ t.clearInternal()}()-- return spin-}--// Stop stops the spinner and moves to the next line.-func (s *Spinner) Stop() {- if s == nil || s.program == nil {- return+ ticker := time.NewTicker(100 * time.Millisecond)+ defer ticker.Stop()+ for {+ select {+ case <-ctx.Done():+ return+ case <-t.stop:+ return+ case <-ticker.C:+ t.mu.Lock()+ t.frame+++ if t.paused == 0 {+ t.drawInternal()+ }+ t.mu.Unlock()+ }}- s.program.Send(spinnerDoneMsg{})- <-s.done- fmt.Println()-}--type progressUpdateMsg struct {- current int64- total int64-}--type progressLabelMsg string--type progressDoneMsg struct{}--type progressModel struct {- progress progress.Model- label string- current int64- total int64}-func newProgressModel(label string, total int64) progressModel {- p := progress.New(progress.WithDefaultBlend(), progress.WithWidth(40))- return progressModel{progress: p, label: label, total: total}-}--func (m progressModel) Init() tea.Cmd {- return m.progress.Init()-}--func (m progressModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {- switch msg := msg.(type) {- case progressUpdateMsg:- m.current = msg.current- if msg.total > 0 {- m.total = msg.total- }- case progressLabelMsg:- m.label = string(msg)- case progressDoneMsg:- return m, tea.Quit- case tea.KeyPressMsg:- switch msg.String() {- case "q", "esc", "ctrl+c":- return m, tea.Quit- }- case tea.WindowSizeMsg:- if msg.Width > 10 {- m.progress.SetWidth(msg.Width - 10)- }+// NextStep completes the active step and starts the next pending step.+func (t *tracker) NextStep() {+ t.mu.Lock()+ defer t.mu.Unlock()+ if t.current >= 0 && t.current < len(t.steps) {+ t.steps[t.current].status = stepSucceeded+ }+ t.current+++ if t.current < len(t.steps) {+ t.steps[t.current].status = stepRunning}-- var cmd tea.Cmd- m.progress, cmd = m.progress.Update(msg)- return m, cmd}-func (m progressModel) View() tea.View {- percent := 0.0- if m.total > 0 {- percent = float64(m.current) / float64(m.total)- if percent < 0 {- percent = 0- } else if percent > 1 {- percent = 1+// SetProgress updates a distinct step, retaining interleaved layer totals.+func (t *tracker) SetProgress(key, label string, current, total int64, byteCount bool) {+ t.mu.Lock()+ defer t.mu.Unlock()+ index := -1+ if key == "" && t.current >= 0 && t.current < len(t.steps) {+ index = t.current+ } else {+ for i := range t.steps {+ if t.steps[i].key == key {+ index = i+ break+ }}}-- bar := m.progress.ViewAs(percent)- if m.total > 0 {- return tea.NewView(fmt.Sprintf("%s\n%s %s/%s", m.label, bar, bytes.Capacity(uint64(max(m.current, 0))), bytes.Capacity(uint64(max(m.total, 0)))))+ if index < 0 {+ t.steps = append(t.steps, trackerStep{key: key})+ index = len(t.steps) - 1}- return tea.NewView(fmt.Sprintf("%s\n%s", m.label, bar))-}--// Bytes renders a signed byte count in human-readable form. Negative values,-// which bytes.Capacity would otherwise wrap into the exabyte range, render as 0.-func Bytes(value int64) string {- return bytes.Capacity(uint64(max(value, 0))).String()-}--// UnsignedBytes renders an unsigned byte count in human-readable form.-func UnsignedBytes(value uint64) string {- return bytes.Capacity(value).String()+ step := &t.steps[index]+ step.label, step.current, step.total, step.bytes = label, max(current, 0), max(total, 0), byteCount+ step.status = stepRunning}-// Progress renders a Bubble Tea progress bar inline.-type Progress struct {- program *tea.Program- done chan struct{}-- mu sync.Mutex- current int64- total int64-}--// StartProgress starts a progress bar with the given label and total.-func StartProgress(label string, total int64) *Progress {- model := newProgressModel(label, total)- program := tea.NewProgram(model)- done := make(chan struct{})-- progressUI := &Progress{program: program, done: done, total: total}- go func() {- _, _ = program.Run()- close(done)- }()-- return progressUI+// Finish marks one tracked step complete or failed.+func (t *tracker) Finish(key string, err error) {+ t.mu.Lock()+ defer t.mu.Unlock()+ for i := range t.steps {+ if (key == "" && i == t.current) || (key != "" && t.steps[i].key == key) {+ t.steps[i].status = stepSucceeded+ if err != nil {+ t.steps[i].status = stepFailed+ }+ }+ }}-// SetLabel updates the progress label.-func (p *Progress) SetLabel(label string) {- if p == nil || p.program == nil {+// Stop clears loading and waits for the renderer. It is safe to repeat.+func (t *tracker) Stop() {+ if t == nil || !t.live {return}- p.program.Send(progressLabelMsg(label))+ t.once.Do(func() {+ close(t.stop)+ <-t.done+ trackersMu.Lock()+ delete(activeTrackers, t)+ trackersMu.Unlock()+ t.resumeOuter()+ })}-// SetTotal updates the total value.-func (p *Progress) SetTotal(total int64) {- if p == nil || p.program == nil {- return+// SuspendProgress pauses every active tracker until the returned function runs.+func SuspendProgress() func() {+ trackersMu.Lock()+ trackers := make([]*tracker, 0, len(activeTrackers))+ for t := range activeTrackers {+ trackers = append(trackers, t)+ }+ trackersMu.Unlock()+ for _, t := range trackers {+ t.mu.Lock()+ t.paused+++ t.clearInternal()+ t.mu.Unlock()+ }+ var once sync.Once+ return func() {+ once.Do(func() {+ for _, t := range trackers {+ t.mu.Lock()+ t.paused = max(t.paused-1, 0)+ t.mu.Unlock()+ }+ })}- p.mu.Lock()- p.total = total- current := p.current- p.mu.Unlock()- p.program.Send(progressUpdateMsg{current: current, total: total})}-// SetCurrent sets the current progress value.-func (p *Progress) SetCurrent(current int64) {- if p == nil || p.program == nil {+func (t *tracker) clearInternal() {+ if t.drawn == 0 {return}- p.mu.Lock()- p.current = current- total := p.total- p.mu.Unlock()- p.program.Send(progressUpdateMsg{current: current, total: total})+ terminalMu.Lock()+ defer terminalMu.Unlock()+ _, _ = io.WriteString(t.out, strings.Repeat("\x1b[A\r\x1b[2K", t.drawn))+ t.drawn = 0}-// Add increments progress by the given value.-func (p *Progress) Add(delta int64) {- if p == nil || p.program == nil {- return+func (t *tracker) drawInternal() {+ width := 80+ height := 24+ if fd, ok := t.out.(interface{ Fd() uintptr }); ok {+ if w, h, err := term.GetSize(fd.Fd()); err == nil {+ width, height = max(w, 1), max(h, 2)+ }+ }+ var frame strings.Builder+ if t.drawn > 0 {+ _, _ = fmt.Fprintf(&frame, "\x1b[%dA", t.drawn)+ }+ start := max(len(t.steps)-max(height-2, 1), 0)+ for _, step := range t.steps[start:] {+ frame.WriteString("\r\x1b[2K")+ frame.WriteString(ansi.Truncate(t.renderStepInternal(step, width), width, "…"))+ frame.WriteByte('\n')}- p.mu.Lock()- p.current += delta- current := p.current- total := p.total- p.mu.Unlock()- p.program.Send(progressUpdateMsg{current: current, total: total})+ // Erase rows left over after a terminal resize.+ count := len(t.steps) - start+ for i := count; i < t.drawn; i++ {+ frame.WriteString("\r\x1b[2K\n")+ }+ if t.drawn > count {+ _, _ = fmt.Fprintf(&frame, "\x1b[%dA", t.drawn-count)+ }+ t.drawn = count+ terminalMu.Lock()+ defer terminalMu.Unlock()+ _, _ = io.WriteString(t.out, frame.String())}-// Stop stops the progress bar and moves to the next line.-func (p *Progress) Stop() {- if p == nil || p.program == nil {- return+func (t *tracker) renderStepInternal(step trackerStep, width int) string {+ icon, style := "○", statusMutedStyle+ switch step.status {+ case stepRunning:+ icon, style = spinnerFrames[t.frame%len(spinnerFrames)], infoStyle+ if step.total > 0 {+ current := min(step.current, step.total)+ count := fmt.Sprintf("%d/%d", current, step.total)+ if step.bytes {+ count = Bytes(current) + "/" + Bytes(step.total)+ }+ barWidth := min(24, max(width-visibleWidthInternal(step.label)-len(count)-7, 1))+ bar := progress.New(progress.WithWidth(barWidth), progress.WithColors(arcanePurple))+ if !colorEnabledInternal() {+ bar.FullColor = nil+ bar.EmptyColor = nil+ bar.PercentageStyle = tablePlainCell.UnsetPadding()+ }+ line := fmt.Sprintf(" %s %s %s", renderForInternal(t.out, infoStyle, step.label), bar.ViewAs(float64(current)/float64(step.total)), count)+ if !colorEnabledInternal() {+ return ansi.Strip(line)+ }+ return line+ }+ case stepSucceeded:+ icon, style = "✓", successStyle+ case stepFailed:+ icon, style = "✗", warnStyle.Foreground(statusOffline)}- p.program.Send(progressDoneMsg{})- <-p.done- fmt.Println()+ return " " + renderForInternal(t.out, style, icon) + " " + renderForInternal(t.out, valueStyle, step.label)}++// Bytes renders a signed byte count in human-readable form.+func Bytes(value int64) string { return bytes.Capacity(uint64(max(value, 0))).String() }++// UnsignedBytes renders an unsigned byte count in human-readable form.+func UnsignedBytes(value uint64) string { return bytes.Capacity(value).String() }diff --git a/cli/internal/prompt/prompt.go b/cli/internal/prompt/prompt.goindex f07347b43..d2ad5773c 100644--- a/cli/internal/prompt/prompt.go+++ b/cli/internal/prompt/prompt.go@@ -8,6 +8,8 @@ import ("charm.land/bubbles/v2/list"tea "charm.land/bubbletea/v2""github.com/charmbracelet/x/term"++ "github.com/getarcaneapp/arcane/cli/v2/internal/output")// IsInteractive reports whether stdin is a terminal.@@ -24,6 +26,7 @@ func Select(label string, options []string) (int, error) {return -1, errors.New("interactive terminal required")}+ defer output.SuspendProgress()()items := make([]list.Item, len(options))for i, option := range options {items[i] = selectItem{index: i, title: option}diff --git a/cli/pkg/activities/cmd.go b/cli/pkg/activities/cmd.goindex d41ab93b0..08d07e0e3 100644--- a/cli/pkg/activities/cmd.go+++ b/cli/pkg/activities/cmd.go@@ -138,7 +138,7 @@ var getCmd = &cobra.Command{if len(result.Data.Messages) > 0 {output.Header("Messages")for _, msg := range result.Data.Messages {- fmt.Printf("%s [%s] %s\n", msg.CreatedAt.Format(time.RFC3339), msg.Level, msg.Message)+ _, _ = fmt.Fprintf(output.Stdout(), "%s [%s] %s\n", msg.CreatedAt.Format(time.RFC3339), msg.Level, msg.Message)}}return nil@@ -157,7 +157,7 @@ var cancelCmd = &cobra.Command{return err}if !confirmed {- fmt.Println("Cancelled")+ _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")return nil}}@@ -192,7 +192,7 @@ var clearCmd = &cobra.Command{return err}if !confirmed {- fmt.Println("Cancelled")+ _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")return nil}}diff --git a/cli/pkg/admin/apikeys/cmd.go b/cli/pkg/admin/apikeys/cmd.goindex b990d438d..b9304a95e 100644--- a/cli/pkg/admin/apikeys/cmd.go+++ b/cli/pkg/admin/apikeys/cmd.go@@ -77,8 +77,8 @@ func parsePermissionGrantsInternal(tokens []string) ([]apikey.PermissionGrant, e// ApiKeysCmd is the parent command for API key operationsvar ApiKeysCmd = &cobra.Command{- Use: "keys",- Aliases: []string{"api-keys", "apikey", "key"},+ Use: "api-keys",+ Aliases: []string{"apikey", "key"},Short: "Manage API keys",}@@ -189,7 +189,7 @@ var deleteCmd = &cobra.Command{return err}if !confirmed {- fmt.Println("Cancelled")+ _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")return nil}}diff --git a/cli/pkg/admin/cmd.go b/cli/pkg/admin/cmd.goindex c28384a1b..7700f2757 100644--- a/cli/pkg/admin/cmd.go+++ b/cli/pkg/admin/cmd.go@@ -10,6 +10,7 @@ import ("github.com/getarcaneapp/arcane/cli/v2/pkg/admin/oidcmappings""github.com/getarcaneapp/arcane/cli/v2/pkg/admin/roles""github.com/getarcaneapp/arcane/cli/v2/pkg/admin/users"+ "github.com/getarcaneapp/arcane/cli/v2/pkg/backups")// AdminCmd is the parent command for administrative operations.@@ -20,6 +21,7 @@ var AdminCmd = &cobra.Command{}func init() {+ AdminCmd.AddCommand(backups.BackupsCmd)AdminCmd.AddCommand(users.UsersCmd)AdminCmd.AddCommand(roles.RolesCmd)AdminCmd.AddCommand(oidcmappings.OidcMappingsCmd)diff --git a/cli/pkg/admin/events/cmd.go b/cli/pkg/admin/events/cmd.goindex 570f34d41..4e025d5f6 100644--- a/cli/pkg/admin/events/cmd.go+++ b/cli/pkg/admin/events/cmd.go@@ -91,7 +91,7 @@ var deleteCmd = &cobra.Command{return err}if !confirmed {- fmt.Println("Cancelled")+ _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")return nil}}diff --git a/cli/pkg/admin/federatedcredentials/cmd.go b/cli/pkg/admin/federatedcredentials/cmd.goindex 287d22892..2efdd1127 100644--- a/cli/pkg/admin/federatedcredentials/cmd.go+++ b/cli/pkg/admin/federatedcredentials/cmd.go@@ -260,7 +260,7 @@ var deleteCmd = &cobra.Command{return err}if !confirmed {- fmt.Println("Cancelled")+ _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")return nil}}diff --git a/cli/pkg/admin/notifications/cmd.go b/cli/pkg/admin/notifications/cmd.goindex ebe2eb1fc..ecd5ff055 100644--- a/cli/pkg/admin/notifications/cmd.go+++ b/cli/pkg/admin/notifications/cmd.go@@ -67,7 +67,7 @@ var settingsGetCmd = &cobra.Command{if tableErr := output.Table(headers, rows); tableErr != nil {return tableErr}- fmt.Printf("\nTotal: %d notification settings\n", len(result))+ _, _ = fmt.Fprintf(output.Stdout(), "\nTotal: %d notification settings\n", len(result))return nil},}@@ -84,7 +84,7 @@ var settingsDeleteCmd = &cobra.Command{return err}if !confirmed {- fmt.Println("Cancelled")+ _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")return nil}}diff --git a/cli/pkg/admin/oidcmappings/cmd.go b/cli/pkg/admin/oidcmappings/cmd.goindex ad8fdab37..49b0f815f 100644--- a/cli/pkg/admin/oidcmappings/cmd.go+++ b/cli/pkg/admin/oidcmappings/cmd.go@@ -180,7 +180,7 @@ var deleteCmd = &cobra.Command{return err}if !confirmed {- fmt.Println("Cancelled")+ _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")return nil}}diff --git a/cli/pkg/admin/roles/cmd.go b/cli/pkg/admin/roles/cmd.goindex 3358cf8eb..17fb03084 100644--- a/cli/pkg/admin/roles/cmd.go+++ b/cli/pkg/admin/roles/cmd.go@@ -229,7 +229,7 @@ var deleteCmd = &cobra.Command{return err}if !confirmed {- fmt.Println("Cancelled")+ _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")return nil}}diff --git a/cli/pkg/admin/users/cmd.go b/cli/pkg/admin/users/cmd.goindex 8b38286d8..d730c3de5 100644--- a/cli/pkg/admin/users/cmd.go+++ b/cli/pkg/admin/users/cmd.go@@ -138,13 +138,16 @@ var createCmd = &cobra.Command{}if userCreatePassword == "" {- fmt.Print("Password: ")+ resume := output.SuspendProgress()+ defer resume()+ _, _ = fmt.Fprint(cmd.ErrOrStderr(), "Password: ")bytePassword, readPasswordErr := term.ReadPassword(os.Stdin.Fd())+ resume()if readPasswordErr != nil {return fmt.Errorf("failed to read password: %w", readPasswordErr)}userCreatePassword = string(bytePassword)- fmt.Println()+ _, _ = fmt.Fprintln(output.Stdout())}req := user.CreateUser{@@ -272,7 +275,7 @@ var deleteCmd = &cobra.Command{return err}if !confirmed {- fmt.Println("Cancelled")+ _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")return nil}}diff --git a/cli/pkg/auth/apikeys.go b/cli/pkg/auth/apikeys.goindex 5b80481a5..26bee253e 100644--- a/cli/pkg/auth/apikeys.go+++ b/cli/pkg/auth/apikeys.go@@ -20,9 +20,9 @@ var (// apiKeysCmd is the parent command for the caller's own (personal) API keys.// Personal keys inherit the owner's role permissions; scoped keys with-// granular grants are managed via `arcane admin apikeys`.+// granular grants are managed via `arcane admin api-keys`.var apiKeysCmd = &cobra.Command{- Use: "keys",+ Use: "api-keys",Aliases: []string{"apikeys", "key"},Short: "Manage your own API keys",Long: "Manage the current user's personal API keys. Personal keys inherit the owner's role permissions. Creating and " +@@ -133,7 +133,7 @@ var apiKeysDeleteCmd = &cobra.Command{return err}if !confirmed {- fmt.Println("Cancelled")+ _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")return nil}}diff --git a/cli/pkg/auth/cmd.go b/cli/pkg/auth/cmd.goindex f2ac2b632..c645bf489 100644--- a/cli/pkg/auth/cmd.go+++ b/cli/pkg/auth/cmd.go@@ -239,23 +239,29 @@ var passwordCmd = &cobra.Command{newPassword, _ := cmd.Flags().GetString("new")if currentPassword == "" {- fmt.Print("Current password: ")+ resume := output.SuspendProgress()+ defer resume()+ _, _ = fmt.Fprint(cmd.ErrOrStderr(), "Current password: ")bytePassword, err := term.ReadPassword(os.Stdin.Fd())if err != nil {return fmt.Errorf("failed to read current password: %w", err)}currentPassword = string(bytePassword)- fmt.Println()+ _, _ = fmt.Fprintln(cmd.ErrOrStderr())+ resume()}if newPassword == "" {- fmt.Print("New password: ")+ resume := output.SuspendProgress()+ defer resume()+ _, _ = fmt.Fprint(cmd.ErrOrStderr(), "New password: ")bytePassword, err := term.ReadPassword(os.Stdin.Fd())if err != nil {return fmt.Errorf("failed to read new password: %w", err)}newPassword = string(bytePassword)- fmt.Println()+ _, _ = fmt.Fprintln(cmd.ErrOrStderr())+ resume()}c, err := cmdutil.ClientFromCommand(cmd)@@ -303,8 +309,10 @@ var refreshCmd = &cobra.Command{refreshToken = cfg.RefreshToken}if refreshToken == "" {- fmt.Print("Refresh token: ")- if _, scanlnErr := fmt.Scanln(&refreshToken); scanlnErr != nil {+ resume := output.SuspendProgress()+ defer resume()+ _, _ = fmt.Fprint(cmd.ErrOrStderr(), "Refresh token: ")+ if _, scanlnErr := fmt.Fscanln(cmd.InOrStdin(), &refreshToken); scanlnErr != nil {return fmt.Errorf("failed to read refresh token: %w", scanlnErr)}}diff --git a/cli/pkg/auth/federated.go b/cli/pkg/auth/federated.goindex 29b751058..d9120c41c 100644--- a/cli/pkg/auth/federated.go+++ b/cli/pkg/auth/federated.go@@ -105,8 +105,8 @@ GitHub Actions example:"persisted": persist,})case exportOutput:- fmt.Printf("export ARCANE_TOKEN=%s\n", shellQuoteInternal(tokenResp.AccessToken))- fmt.Printf("export ARCANE_TOKEN_EXPIRES_AT=%s\n", shellQuoteInternal(expiresAt.Format(time.RFC3339)))+ _, _ = fmt.Fprintf(output.Stdout(), "export ARCANE_TOKEN=%s\n", shellQuoteInternal(tokenResp.AccessToken))+ _, _ = fmt.Fprintf(output.Stdout(), "export ARCANE_TOKEN_EXPIRES_AT=%s\n", shellQuoteInternal(expiresAt.Format(time.RFC3339)))default:output.Success("Federated token exchange successful")output.KeyValue("Token source", tokenSource)diff --git a/cli/pkg/backups/cmd.go b/cli/pkg/backups/cmd.goindex 45b93a7f9..32161b177 100644--- a/cli/pkg/backups/cmd.go+++ b/cli/pkg/backups/cmd.go@@ -190,7 +190,7 @@ var deleteCmd = &cobra.Command{return err}if !confirmed {- fmt.Println("Cancelled")+ _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")return nil}}@@ -228,7 +228,7 @@ var restoreCmd = &cobra.Command{return err}if !confirmed {- fmt.Println("Cancelled")+ _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")return nil}}@@ -238,13 +238,16 @@ var restoreCmd = &cobra.Command{if !prompt.IsInteractive() {return errors.New("recovery key is required; pass --recovery-key")}- fmt.Print("Recovery key: ")+ resume := output.SuspendProgress()+ defer resume()+ _, _ = fmt.Fprint(cmd.ErrOrStderr(), "Recovery key: ")byteKey, err := term.ReadPassword(os.Stdin.Fd())+ resume()if err != nil {return fmt.Errorf("failed to read recovery key: %w", err)}key = string(byteKey)- fmt.Println()+ _, _ = fmt.Fprintln(output.Stdout())if key == "" {return errors.New("recovery key is required")}@@ -457,7 +460,7 @@ Alternatively, --file replaces all policies from a raw JSON payload.`,switch {case policiesUpdateID != "" && targetIndex == -1:- return fmt.Errorf("policy %q not found; run `arcane backups policies`", policiesUpdateID)+ return fmt.Errorf("policy %q not found; run `arcane admin backups policies`", policiesUpdateID)case policiesUpdateID == "" && len(req.Policies) > 1:return fmt.Errorf("%d backup policies exist; select one with --policy-id", len(req.Policies))case policiesUpdateID == "" && len(req.Policies) == 1:@@ -547,7 +550,7 @@ var recoveryKeyGenerateCmd = &cobra.Command{}output.Header("Generated Recovery Key")- fmt.Println(result.RecoveryKey)+ _, _ = fmt.Fprintln(output.Stdout(), result.RecoveryKey)output.Warning("Store this recovery key somewhere safe. Backups encrypted with it cannot be restored without it.")save := generateSave@@ -558,7 +561,7 @@ var recoveryKeyGenerateCmd = &cobra.Command{}}if !save {- fmt.Println("Run `arcane backups recovery set` to store it on the server later.")+ _, _ = fmt.Fprintln(output.Stdout(), "Run `arcane admin backups recovery set` to store it on the server later.")return nil}if storeRotatedRecoveryKeyErr := storeRecoveryKey(cmd, c, result.RecoveryKey); storeRotatedRecoveryKeyErr != nil {@@ -580,13 +583,16 @@ var recoveryKeySetCmd = &cobra.Command{if !prompt.IsInteractive() {return errors.New("recovery key is required; pass --recovery-key")}- fmt.Print("Recovery key: ")+ resume := output.SuspendProgress()+ defer resume()+ _, _ = fmt.Fprint(cmd.ErrOrStderr(), "Recovery key: ")byteKey, err := term.ReadPassword(os.Stdin.Fd())+ resume()if err != nil {return fmt.Errorf("failed to read recovery key: %w", err)}key = string(byteKey)- fmt.Println()+ _, _ = fmt.Fprintln(output.Stdout())}if key == "" {return errors.New("recovery key is required; use --recovery-key")diff --git a/cli/pkg/backups/resolve.go b/cli/pkg/backups/resolve.goindex 694ef031f..2df231731 100644--- a/cli/pkg/backups/resolve.go+++ b/cli/pkg/backups/resolve.go@@ -20,7 +20,7 @@ var s3DestinationRef = cmdutil.ResourceRef[backup.S3Destination, backup.S3DestinSingular: "S3 destination",Plural: "S3 destinations",IDHint: "the destination ID",- ListCmd: "arcane backups s3 list",+ ListCmd: "arcane admin backups s3 list",GetPath: func(_, identifier string) string { return types.BackupsS3Destination(identifier) },SearchCandidates: func(ctx context.Context, c *client.Client, identifier string) ([]backup.S3Destination, error) {destinations, err := c.DoJSON[[]backup.S3Destination](ctx, http.MethodGet, types.BackupsS3Options(), nil)diff --git a/cli/pkg/backups/s3.go b/cli/pkg/backups/s3.goindex 2bfcdcd33..85efba631 100644--- a/cli/pkg/backups/s3.go+++ b/cli/pkg/backups/s3.go@@ -230,7 +230,7 @@ var s3DeleteCmd = &cobra.Command{return confirmErr}if !confirmed {- fmt.Println("Cancelled")+ _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")return nil}}diff --git a/cli/pkg/config/cmd.go b/cli/pkg/config/cmd.goindex 6ee2495e5..4b0b33b95 100644--- a/cli/pkg/config/cmd.go+++ b/cli/pkg/config/cmd.go@@ -15,6 +15,7 @@ import ("github.com/spf13/cobra""github.com/getarcaneapp/arcane/cli/v2/internal/config"+ "github.com/getarcaneapp/arcane/cli/v2/internal/output""github.com/getarcaneapp/arcane/cli/v2/internal/types")@@ -45,18 +46,18 @@ var configShowCmd = &cobra.Command{}path, _ := config.ConfigPath()- fmt.Printf("Config file: %s\n\n", path)- fmt.Printf("Server URL: %s\n", cmp.Or(cfg.ServerURL, "(not set)"))- fmt.Printf("API Key: %s\n", maskAPIKey(cfg.APIKey))- fmt.Printf("JWT Token: %s\n", maskAPIKey(cfg.JWTToken))- fmt.Printf("Refresh Token: %s\n", maskAPIKey(cfg.RefreshToken))- fmt.Printf("Default Environment: %s\n", cmp.Or(cfg.DefaultEnvironment, "0 (local)"))- fmt.Printf("Federated Audience: %s\n", cmp.Or(cfg.FederatedAudience, "(not set)"))- fmt.Printf("Log Level: %s\n", cmp.Or(cfg.LogLevel, "info (default)"))- fmt.Printf("CLI Update Channel: %s\n", cmp.Or(cfg.CLIUpdateChannel, "(auto)"))- fmt.Printf("Pagination Default: %s\n", cmp.Or(intToString(cfg.Pagination.Default.Limit), "(not set)"))-- fmt.Println("\nPagination Resources:")+ output.Header("CLI configuration")+ output.KeyValue("Config file", path)+ output.KeyValue("Server URL", cmp.Or(cfg.ServerURL, "(not set)"))+ output.KeyValue("API key", maskAPIKey(cfg.APIKey))+ output.KeyValue("JWT token", maskAPIKey(cfg.JWTToken))+ output.KeyValue("Refresh token", maskAPIKey(cfg.RefreshToken))+ output.KeyValue("Environment", cmp.Or(cfg.DefaultEnvironment, "0 (local)"))+ output.KeyValue("Federated audience", cmp.Or(cfg.FederatedAudience, "(not set)"))+ output.KeyValue("Log level", cmp.Or(cfg.LogLevel, "info (default)"))+ output.KeyValue("Update channel", cmp.Or(cfg.CLIUpdateChannel, "(auto)"))+ output.KeyValue("Pagination limit", cmp.Or(intToString(cfg.Pagination.Default.Limit), "(not set)"))+ output.Header("Pagination resources")printed := 0for _, resource := range types.KnownPaginatedResources {limit := cfg.LimitFor(resource)@@ -67,7 +68,7 @@ var configShowCmd = &cobra.Command{} else if limit > 0 {label = fmt.Sprintf("%d (from global)", limit)}- fmt.Printf(" %-14s %s\n", resource+":", label)+ output.KeyValue(resource, label)printed++}if cfg.Pagination.Resources != nil {@@ -80,18 +81,18 @@ var configShowCmd = &cobra.Command{}sort.Strings(extras)for _, k := range extras {- fmt.Printf(" %-14s %d\n", k+":", cfg.Pagination.Resources[k].Limit)+ _, _ = fmt.Fprintf(output.Stdout(), " %-14s %d\n", k+":", cfg.Pagination.Resources[k].Limit)printed++}}if printed == 0 {- fmt.Println(" (none)")+ _, _ = fmt.Fprintln(output.Stdout(), " (none)")}if cfg.IsConfigured() {- fmt.Println("\n✓ Configuration is complete")+ _, _ = fmt.Fprintln(output.Stdout(), "\n✓ Configuration is complete")} else {- fmt.Println("\n✗ Configuration is incomplete. Run: arcane config set --help")+ _, _ = fmt.Fprintln(output.Stdout(), "\n✗ Configuration is incomplete. Run: arcane config set --help")}return nil@@ -147,7 +148,7 @@ Legacy flag syntax (flags shown below) is still supported:}path, _ := config.ConfigPath()- fmt.Printf("\nConfiguration saved to %s\n", path)+ _, _ = fmt.Fprintf(output.Stdout(), "\nConfiguration saved to %s\n", path)return nil},@@ -161,7 +162,7 @@ var configPathCmd = &cobra.Command{if err != nil {return err}- fmt.Println(path)+ _, _ = fmt.Fprintln(output.Stdout(), path)return nil},}@@ -179,7 +180,7 @@ var configTestCmd = &cobra.Command{return validateErr}- fmt.Printf("Testing connection to %s...\n", cfg.ServerURL)+ _, _ = fmt.Fprintf(output.Stdout(), "Testing connection to %s...\n", cfg.ServerURL)// Test connection directly without importing client to avoid circular importhttpClient := &http.Client{Timeout: 10 * time.Second}@@ -205,7 +206,7 @@ var configTestCmd = &cobra.Command{return fmt.Errorf("connection test failed with status %d: %s", resp.StatusCode, string(body))}- fmt.Println("✓ Connection successful!")+ _, _ = fmt.Fprintln(output.Stdout(), "✓ Connection successful!")return nil},}@@ -229,12 +230,12 @@ If the config file already exists, this command is a no-op and does not overwritreturn fmt.Errorf("failed to initialize config: %w", err)}if !created {- fmt.Printf("Config file already exists at %s (no changes made)\n", path)+ _, _ = fmt.Fprintf(output.Stdout(), "Config file already exists at %s (no changes made)\n", path)return nil}- fmt.Printf("Created default config at %s\n", path)- fmt.Println("Update values with `arcane config set <key> <value>` or run `arcane auth login`.")+ _, _ = fmt.Fprintf(output.Stdout(), "Created default config at %s\n", path)+ _, _ = fmt.Fprintln(output.Stdout(), "Update values with `arcane config set <key> <value>` or run `arcane auth login`.")return nil},}@@ -258,12 +259,12 @@ This removes the original config file from its previous path.`,return fmt.Errorf("failed to backup config: %w", err)}if !moved {- fmt.Printf("No config file found at %s (no changes made)\n", path)+ _, _ = fmt.Fprintf(output.Stdout(), "No config file found at %s (no changes made)\n", path)return nil}- fmt.Printf("Backed up config to %s\n", backupPath)- fmt.Printf("Removed original config at %s\n", path)+ _, _ = fmt.Fprintf(output.Stdout(), "Backed up config to %s\n", backupPath)+ _, _ = fmt.Fprintf(output.Stdout(), "Removed original config at %s\n", path)return nil},}@@ -321,7 +322,7 @@ func applyConfigSetFlags(cmd *cobra.Command, cfg *types.Config) (bool, error) {if setServerURL != "" {cfg.ServerURL = setServerURL- fmt.Printf("Set server_url = %s\n", setServerURL)+ _, _ = fmt.Fprintf(output.Stdout(), "Set server_url = %s\n", setServerURL)updated = true}@@ -330,7 +331,7 @@ func applyConfigSetFlags(cmd *cobra.Command, cfg *types.Config) (bool, error) {// If switching to API key auth, clear any existing JWT token.cfg.JWTToken = ""cfg.RefreshToken = ""- fmt.Printf("Set api_key = %s\n", maskAPIKey(setAPIKey))+ _, _ = fmt.Fprintf(output.Stdout(), "Set api_key = %s\n", maskAPIKey(setAPIKey))updated = true}@@ -339,25 +340,25 @@ func applyConfigSetFlags(cmd *cobra.Command, cfg *types.Config) (bool, error) {// If switching to JWT auth, clear any existing API key.cfg.APIKey = ""cfg.RefreshToken = ""- fmt.Printf("Set jwt_token = %s\n", maskAPIKey(setJWTToken))+ _, _ = fmt.Fprintf(output.Stdout(), "Set jwt_token = %s\n", maskAPIKey(setJWTToken))updated = true}if setEnvironment != "" {cfg.DefaultEnvironment = setEnvironment- fmt.Printf("Set default_environment = %s\n", setEnvironment)+ _, _ = fmt.Fprintf(output.Stdout(), "Set default_environment = %s\n", setEnvironment)updated = true}if setFederatedAudience != "" {cfg.FederatedAudience = setFederatedAudience- fmt.Printf("Set federated_audience = %s\n", setFederatedAudience)+ _, _ = fmt.Fprintf(output.Stdout(), "Set federated_audience = %s\n", setFederatedAudience)updated = true}if setLogLevel != "" {cfg.LogLevel = setLogLevel- fmt.Printf("Set log_level = %s\n", setLogLevel)+ _, _ = fmt.Fprintf(output.Stdout(), "Set log_level = %s\n", setLogLevel)updated = true}@@ -367,9 +368,9 @@ func applyConfigSetFlags(cmd *cobra.Command, cfg *types.Config) (bool, error) {}cfg.SetDefaultLimit(setDefaultLimit)if setDefaultLimit == 0 {- fmt.Println("Cleared pagination.default.limit")+ _, _ = fmt.Fprintln(output.Stdout(), "Cleared pagination.default.limit")} else {- fmt.Printf("Set pagination.default.limit = %d\n", setDefaultLimit)+ _, _ = fmt.Fprintf(output.Stdout(), "Set pagination.default.limit = %d\n", setDefaultLimit)}updated = true}@@ -384,9 +385,9 @@ func applyConfigSetFlags(cmd *cobra.Command, cfg *types.Config) (bool, error) {}cfg.SetResourceLimit(resource, limit)if limit == 0 {- fmt.Printf("Cleared pagination.resources.%s.limit\n", resource)+ _, _ = fmt.Fprintf(output.Stdout(), "Cleared pagination.resources.%s.limit\n", resource)} else {- fmt.Printf("Set pagination.resources.%s.limit = %d\n", resource, limit)+ _, _ = fmt.Fprintf(output.Stdout(), "Set pagination.resources.%s.limit = %d\n", resource, limit)}updated = true}@@ -418,33 +419,33 @@ func applyConfigSetArg(cfg *types.Config, key, value string) (bool, error) {switch normalized {case "server-url", "server", "serverurl", "server_url":cfg.ServerURL = value- fmt.Printf("Set server_url = %s\n", value)+ _, _ = fmt.Fprintf(output.Stdout(), "Set server_url = %s\n", value)return true, nilcase "api-key", "apikey", "api_key":cfg.APIKey = value// If switching to API key auth, clear any existing JWT token.cfg.JWTToken = ""cfg.RefreshToken = ""- fmt.Printf("Set api_key = %s\n", maskAPIKey(value))+ _, _ = fmt.Fprintf(output.Stdout(), "Set api_key = %s\n", maskAPIKey(value))return true, nilcase "jwt-token", "jwt", "jwt_token":cfg.JWTToken = value// If switching to JWT auth, clear any existing API key.cfg.APIKey = ""cfg.RefreshToken = ""- fmt.Printf("Set jwt_token = %s\n", maskAPIKey(value))+ _, _ = fmt.Fprintf(output.Stdout(), "Set jwt_token = %s\n", maskAPIKey(value))return true, nilcase "environment", "default-environment", "default_environment":cfg.DefaultEnvironment = value- fmt.Printf("Set default_environment = %s\n", value)+ _, _ = fmt.Fprintf(output.Stdout(), "Set default_environment = %s\n", value)return true, nilcase "federated-audience", "federated_audience", "audience":cfg.FederatedAudience = value- fmt.Printf("Set federated_audience = %s\n", value)+ _, _ = fmt.Fprintf(output.Stdout(), "Set federated_audience = %s\n", value)return true, nilcase "log-level", "loglevel", "log_level":cfg.LogLevel = value- fmt.Printf("Set log_level = %s\n", value)+ _, _ = fmt.Fprintf(output.Stdout(), "Set log_level = %s\n", value)return true, nilcase "cli-update-channel", "cli_update_channel", "cli-channel", "channel":channel := strings.ToLower(strings.TrimSpace(value))@@ -452,7 +453,7 @@ func applyConfigSetArg(cfg *types.Config, key, value string) (bool, error) {return false, fmt.Errorf("invalid cli update channel %q (expected stable or next)", value)}cfg.CLIUpdateChannel = channel- fmt.Printf("Set cli_update_channel = %s\n", channel)+ _, _ = fmt.Fprintf(output.Stdout(), "Set cli_update_channel = %s\n", channel)return true, nilcase "default-limit", "default_limit", "pagination.default.limit":limit, err := parseLimitValue(normalized, value)@@ -461,9 +462,9 @@ func applyConfigSetArg(cfg *types.Config, key, value string) (bool, error) {}cfg.SetDefaultLimit(limit)if limit == 0 {- fmt.Println("Cleared pagination.default.limit")+ _, _ = fmt.Fprintln(output.Stdout(), "Cleared pagination.default.limit")} else {- fmt.Printf("Set pagination.default.limit = %d\n", limit)+ _, _ = fmt.Fprintf(output.Stdout(), "Set pagination.default.limit = %d\n", limit)}return true, nilcase "resource-limit", "resource_limit":@@ -476,9 +477,9 @@ func applyConfigSetArg(cfg *types.Config, key, value string) (bool, error) {}cfg.SetResourceLimit(resource, limit)if limit == 0 {- fmt.Printf("Cleared pagination.resources.%s.limit\n", resource)+ _, _ = fmt.Fprintf(output.Stdout(), "Cleared pagination.resources.%s.limit\n", resource)} else {- fmt.Printf("Set pagination.resources.%s.limit = %d\n", resource, limit)+ _, _ = fmt.Fprintf(output.Stdout(), "Set pagination.resources.%s.limit = %d\n", resource, limit)}return true, nil}@@ -507,9 +508,9 @@ func applyResourceLimitByKey(cfg *types.Config, key, resourceValue, limitValue s}cfg.SetResourceLimit(resource, limit)if limit == 0 {- fmt.Printf("Cleared pagination.resources.%s.limit\n", resource)+ _, _ = fmt.Fprintf(output.Stdout(), "Cleared pagination.resources.%s.limit\n", resource)} else {- fmt.Printf("Set pagination.resources.%s.limit = %d\n", resource, limit)+ _, _ = fmt.Fprintf(output.Stdout(), "Set pagination.resources.%s.limit = %d\n", resource, limit)}return true, nil}diff --git a/cli/pkg/containers/actions.go b/cli/pkg/containers/actions.goindex 5e02351ea..82c71b4f5 100644--- a/cli/pkg/containers/actions.go+++ b/cli/pkg/containers/actions.go@@ -201,7 +201,7 @@ var containersEditCmd = &cobra.Command{}var containersAutoUpdateCmd = &cobra.Command{- Use: "autoupdate <container-id|name>",+ Use: "auto-update <container-id|name>",Short: "Enable or disable auto-update for a container",Args: cobra.ExactArgs(1),SilenceUsage: true,diff --git a/cli/pkg/containers/cmd.go b/cli/pkg/containers/cmd.goindex 910d86622..eaa016012 100644--- a/cli/pkg/containers/cmd.go+++ b/cli/pkg/containers/cmd.go@@ -363,7 +363,7 @@ var containersDeleteCmd = &cobra.Command{return confirmErr}if !confirmed {- fmt.Println("Cancelled")+ _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")return nil}}diff --git a/cli/pkg/environments/cmd.go b/cli/pkg/environments/cmd.goindex 24970ae27..8ab7abe88 100644--- a/cli/pkg/environments/cmd.go+++ b/cli/pkg/environments/cmd.go@@ -108,7 +108,7 @@ var deleteCmd = &cobra.Command{return err}if !confirmed {- fmt.Println("Cancelled")+ _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")return nil}}diff --git a/cli/pkg/generate/api_key.go b/cli/pkg/generate/api_key.goindex e20f89fed..0f70e5f2d 100644--- a/cli/pkg/generate/api_key.go+++ b/cli/pkg/generate/api_key.go@@ -4,6 +4,7 @@ import ("crypto/rand""encoding/hex""fmt"+ "io""github.com/spf13/cobra")@@ -19,7 +20,7 @@ var apiKeyCmd = &cobra.Command{Short: "Generate a static admin API key",Long: `Generate a static Arcane API key suitable for ADMIN_STATIC_API_KEY. This is just a local generation, nothing is stored to the database with these commands.`,RunE: func(cmd *cobra.Command, args []string) error {- return generateAPIKeyOutputInternal()+ return generateAPIKeyOutputInternal(cmd.OutOrStdout())},}@@ -36,12 +37,12 @@ func GenerateAPIKey() (string, error) {return apiKeyPrefix + hex.EncodeToString(keyBytes), nil}-func generateAPIKeyOutputInternal() error {+func generateAPIKeyOutputInternal(w io.Writer) error {apiKey, err := GenerateAPIKey()if err != nil {return err}- fmt.Println(apiKey)+ _, _ = fmt.Fprintln(w, apiKey)return nil}diff --git a/cli/pkg/generate/certs.go b/cli/pkg/generate/certs.goindex 97c3440a2..c9a5099a5 100644--- a/cli/pkg/generate/certs.go+++ b/cli/pkg/generate/certs.go@@ -11,6 +11,7 @@ import ("encoding/pem""errors""fmt"+ "io""math/big""net""net/url"@@ -43,7 +44,7 @@ var mtlsCmd = &cobra.Command{Short: "Generate Arcane edge mTLS assets",Long: `Generate an Arcane-managed edge mTLS CA and agent client certificate bundle using ML-DSA-87.`,RunE: func(cmd *cobra.Command, args []string) error {- return generateMTLSOutputInternal()+ return generateMTLSOutputInternal(cmd.OutOrStdout())},}@@ -52,7 +53,7 @@ var tlsCmd = &cobra.Command{Short: "Generate Arcane HTTPS TLS assets",Long: `Generate a self-signed Arcane HTTPS server certificate bundle using ECDSA P-384.`,RunE: func(cmd *cobra.Command, args []string) error {- return generateTLSOutputInternal()+ return generateTLSOutputInternal(cmd.OutOrStdout())},}@@ -71,7 +72,7 @@ func init() {tlsCmd.Flags().StringVar(&tlsKeyName, "key-name", "server.key", "private key file name to write under out-dir")}-func generateMTLSOutputInternal() error {+func generateMTLSOutputInternal(w io.Writer) error {outDir, err := filepath.Abs(strings.TrimSpace(mtlsOutDir))if err != nil {return fmt.Errorf("failed to resolve output directory: %w", err)@@ -82,21 +83,21 @@ func generateMTLSOutputInternal() error {return err}- fmt.Println("Generated Arcane edge mTLS assets (ML-DSA-87)")- fmt.Printf("CA cert: %s\n", paths.CACertPath)- fmt.Printf("CA key: %s\n", paths.CAKeyPath)- fmt.Printf("Agent cert: %s\n", paths.ClientCertPath)- fmt.Printf("Agent key: %s\n", paths.ClientKeyPath)- fmt.Println()- fmt.Println("Manager env")- fmt.Printf("EDGE_MTLS_MODE=required\nEDGE_MTLS_CA_FILE=%s\n", paths.CACertPath)- fmt.Println()- fmt.Println("Agent env")- fmt.Printf("EDGE_MTLS_MODE=required\nEDGE_MTLS_CA_FILE=%s\nEDGE_MTLS_CERT_FILE=%s\nEDGE_MTLS_KEY_FILE=%s\n", paths.CACertPath, paths.ClientCertPath, paths.ClientKeyPath)+ _, _ = fmt.Fprintln(w, "Generated Arcane edge mTLS assets (ML-DSA-87)")+ _, _ = fmt.Fprintf(w, "CA cert: %s\n", paths.CACertPath)+ _, _ = fmt.Fprintf(w, "CA key: %s\n", paths.CAKeyPath)+ _, _ = fmt.Fprintf(w, "Agent cert: %s\n", paths.ClientCertPath)+ _, _ = fmt.Fprintf(w, "Agent key: %s\n", paths.ClientKeyPath)+ _, _ = fmt.Fprintln(w)+ _, _ = fmt.Fprintln(w, "Manager env")+ _, _ = fmt.Fprintf(w, "EDGE_MTLS_MODE=required\nEDGE_MTLS_CA_FILE=%s\n", paths.CACertPath)+ _, _ = fmt.Fprintln(w)+ _, _ = fmt.Fprintln(w, "Agent env")+ _, _ = fmt.Fprintf(w, "EDGE_MTLS_MODE=required\nEDGE_MTLS_CA_FILE=%s\nEDGE_MTLS_CERT_FILE=%s\nEDGE_MTLS_KEY_FILE=%s\n", paths.CACertPath, paths.ClientCertPath, paths.ClientKeyPath)return nil}-func generateTLSOutputInternal() error {+func generateTLSOutputInternal(w io.Writer) error {outDir, err := filepath.Abs(strings.TrimSpace(tlsOutDir))if err != nil {return fmt.Errorf("failed to resolve output directory: %w", err)@@ -107,12 +108,12 @@ func generateTLSOutputInternal() error {return err}- fmt.Println("Generated Arcane TLS assets (ECDSA P-384)")- fmt.Printf("Server cert: %s\n", paths.CertPath)- fmt.Printf("Server key: %s\n", paths.KeyPath)- fmt.Println()- fmt.Println("Manager env")- fmt.Printf("TLS_ENABLED=true\nTLS_CERT_FILE=%s\nTLS_KEY_FILE=%s\n", paths.CertPath, paths.KeyPath)+ _, _ = fmt.Fprintln(w, "Generated Arcane TLS assets (ECDSA P-384)")+ _, _ = fmt.Fprintf(w, "Server cert: %s\n", paths.CertPath)+ _, _ = fmt.Fprintf(w, "Server key: %s\n", paths.KeyPath)+ _, _ = fmt.Fprintln(w)+ _, _ = fmt.Fprintln(w, "Manager env")+ _, _ = fmt.Fprintf(w, "TLS_ENABLED=true\nTLS_CERT_FILE=%s\nTLS_KEY_FILE=%s\n", paths.CertPath, paths.KeyPath)return nil}diff --git a/cli/pkg/generate/secret.go b/cli/pkg/generate/secret.goindex 271e58d52..1f88af55b 100644--- a/cli/pkg/generate/secret.go+++ b/cli/pkg/generate/secret.go@@ -5,6 +5,7 @@ import ("encoding/base64""encoding/hex""fmt"+ "io""github.com/spf13/cobra")@@ -19,7 +20,7 @@ var secretCmd = &cobra.Command{Short: "Generate cryptographic secrets",Long: `Generate a secure cryptographic secret for ENCRYPTION_KEY.`,RunE: func(cmd *cobra.Command, args []string) error {- return generateSecrets()+ return generateSecretsInternal(cmd.OutOrStdout())},}@@ -29,7 +30,7 @@ func init() {secretCmd.Flags().IntVarP(&secretLength, "length", "l", 32, "secret length in bytes (default: 32 for AES-256)")}-func generateSecrets() error {+func generateSecretsInternal(w io.Writer) error {encryptionKey := make([]byte, secretLength)if _, err := rand.Read(encryptionKey); err != nil {return fmt.Errorf("failed to generate encryption key: %w", err)@@ -37,15 +38,15 @@ func generateSecrets() error {switch secretFormat {case "base64":- printBase64Format(encryptionKey)+ printBase64FormatInternal(w, encryptionKey)case "hex":- printHexFormat(encryptionKey)+ printHexFormatInternal(w, encryptionKey)case "env":- printEnvFormat(encryptionKey)+ printEnvFormatInternal(w, encryptionKey)case "docker":- printDockerFormat(encryptionKey)+ printDockerFormatInternal(w, encryptionKey)case "all":- printAllFormats(encryptionKey)+ printAllFormatsInternal(w, encryptionKey)default:return fmt.Errorf("unknown format: %s (supported: base64, hex, env, docker, all)", secretFormat)}@@ -53,49 +54,49 @@ func generateSecrets() error {return nil}-func printBase64Format(encKey []byte) {- fmt.Println("BASE64")- fmt.Println("------")- fmt.Printf("ENCRYPTION_KEY=%s\n", base64.StdEncoding.EncodeToString(encKey))+func printBase64FormatInternal(w io.Writer, encKey []byte) {+ _, _ = fmt.Fprintln(w, "BASE64")+ _, _ = fmt.Fprintln(w, "------")+ _, _ = fmt.Fprintf(w, "ENCRYPTION_KEY=%s\n", base64.StdEncoding.EncodeToString(encKey))}-func printHexFormat(encKey []byte) {- fmt.Println("HEX")- fmt.Println("---")- fmt.Printf("ENCRYPTION_KEY=%s\n", hex.EncodeToString(encKey))+func printHexFormatInternal(w io.Writer, encKey []byte) {+ _, _ = fmt.Fprintln(w, "HEX")+ _, _ = fmt.Fprintln(w, "---")+ _, _ = fmt.Fprintf(w, "ENCRYPTION_KEY=%s\n", hex.EncodeToString(encKey))}-func printEnvFormat(encKey []byte) {- fmt.Println("ENV (.env) FORMAT")- fmt.Println("-------------------")- fmt.Printf("ENCRYPTION_KEY=%s\n", base64.StdEncoding.EncodeToString(encKey))+func printEnvFormatInternal(w io.Writer, encKey []byte) {+ _, _ = fmt.Fprintln(w, "ENV (.env) FORMAT")+ _, _ = fmt.Fprintln(w, "-------------------")+ _, _ = fmt.Fprintf(w, "ENCRYPTION_KEY=%s\n", base64.StdEncoding.EncodeToString(encKey))}-func printDockerFormat(encKey []byte) {- fmt.Println("DOCKER COMPOSE ENVIRONMENT")- fmt.Println("--------------------------")- fmt.Println("environment:")- fmt.Printf(" - ENCRYPTION_KEY=%s\n", base64.StdEncoding.EncodeToString(encKey))+func printDockerFormatInternal(w io.Writer, encKey []byte) {+ _, _ = fmt.Fprintln(w, "DOCKER COMPOSE ENVIRONMENT")+ _, _ = fmt.Fprintln(w, "--------------------------")+ _, _ = fmt.Fprintln(w, "environment:")+ _, _ = fmt.Fprintf(w, " - ENCRYPTION_KEY=%s\n", base64.StdEncoding.EncodeToString(encKey))}-func printAllFormats(encKey []byte) {- fmt.Println("Arcane cryptographic secrets")- fmt.Println("===========================")- fmt.Println()-- fmt.Println("ENV (.env) - recommended")- fmt.Println("------------------------")- fmt.Printf("ENCRYPTION_KEY=%s\n", base64.StdEncoding.EncodeToString(encKey))- fmt.Println()-- fmt.Println("Docker Compose (environment block)")- fmt.Println("-------------------------------")- fmt.Println("environment:")- fmt.Printf(" - ENCRYPTION_KEY=%s\n", base64.StdEncoding.EncodeToString(encKey))- fmt.Println()-- fmt.Println("HEX")- fmt.Println("---")- fmt.Printf("ENCRYPTION_KEY=%s\n", hex.EncodeToString(encKey))- fmt.Println()+func printAllFormatsInternal(w io.Writer, encKey []byte) {+ _, _ = fmt.Fprintln(w, "Arcane cryptographic secrets")+ _, _ = fmt.Fprintln(w, "===========================")+ _, _ = fmt.Fprintln(w)++ _, _ = fmt.Fprintln(w, "ENV (.env) - recommended")+ _, _ = fmt.Fprintln(w, "------------------------")+ _, _ = fmt.Fprintf(w, "ENCRYPTION_KEY=%s\n", base64.StdEncoding.EncodeToString(encKey))+ _, _ = fmt.Fprintln(w)++ _, _ = fmt.Fprintln(w, "Docker Compose (environment block)")+ _, _ = fmt.Fprintln(w, "-------------------------------")+ _, _ = fmt.Fprintln(w, "environment:")+ _, _ = fmt.Fprintf(w, " - ENCRYPTION_KEY=%s\n", base64.StdEncoding.EncodeToString(encKey))+ _, _ = fmt.Fprintln(w)++ _, _ = fmt.Fprintln(w, "HEX")+ _, _ = fmt.Fprintln(w, "---")+ _, _ = fmt.Fprintf(w, "ENCRYPTION_KEY=%s\n", hex.EncodeToString(encKey))+ _, _ = fmt.Fprintln(w)}diff --git a/cli/pkg/gitops/cmd.go b/cli/pkg/gitops/cmd.goindex fa5934299..8cce2cde2 100644--- a/cli/pkg/gitops/cmd.go+++ b/cli/pkg/gitops/cmd.go@@ -260,7 +260,7 @@ var deleteCmd = &cobra.Command{return confirmErr}if !confirmed {- fmt.Println("Cancelled")+ _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")return nil}}@@ -444,7 +444,7 @@ var importCmd = &cobra.Command{if len(result.Data.Errors) > 0 {output.Warning("Errors:")for _, e := range result.Data.Errors {- fmt.Printf(" - %s\n", e)+ _, _ = fmt.Fprintf(output.Stdout(), " - %s\n", e)}}return nildiff --git a/cli/pkg/images/cmd.go b/cli/pkg/images/cmd.goindex c37c00d94..ddcfa763c 100644--- a/cli/pkg/images/cmd.go+++ b/cli/pkg/images/cmd.go@@ -147,7 +147,7 @@ var imagesGetCmd = &cobra.Command{log.Debugf("Response body: %s", string(body))if jsonOutput {- fmt.Println(string(body))+ _, _ = fmt.Fprintln(output.Stdout(), string(body))return nil}@@ -186,7 +186,7 @@ var imagesGetCmd = &cobra.Command{if len(result.Data.Config.Env) > 0 {output.Header("Environment Variables")for _, env := range result.Data.Config.Env {- fmt.Println(env)+ _, _ = fmt.Fprintln(output.Stdout(), env)}}@@ -198,7 +198,7 @@ var imagesGetCmd = &cobra.Command{}sort.Strings(ports)for _, p := range ports {- fmt.Println(p)+ _, _ = fmt.Fprintln(output.Stdout(), p)}}@@ -258,7 +258,7 @@ var imagesRemoveCmd = &cobra.Command{log.Debugf("Response body: %s", string(body))if cmdutil.JSONOutputEnabled(cmd) {- fmt.Println(string(body))+ _, _ = fmt.Fprintln(output.Stdout(), string(body))return nil}@@ -325,8 +325,8 @@ var imagesPullCmd = &cobra.Command{output.Info("Pulling image: %s", imageName)decoder := jsontext.NewDecoder(resp.Body)- var progressUI *output.Progress- var currentID string+ loading := output.StartTracker(cmd.Context(), cmd.ErrOrStderr(), true)+ defer loading.Stop()for {var event struct {@@ -354,50 +354,30 @@ var imagesPullCmd = &cobra.Command{}if event.Error != "" {- if progressUI != nil {- progressUI.Stop()- }-- return fmt.Errorf("pull error: %s", event.Error)-+ pullErr := fmt.Errorf("pull error: %s", event.Error)+ loading.Finish(event.ID, pullErr)+ return pullErr}-- if event.Status == "Downloading" && event.ProgressDetail.Total > 0 {- if progressUI == nil {- progressUI = output.StartProgress("", event.ProgressDetail.Total)- }- if currentID != event.ID {- currentID = event.ID- progressUI.SetLabel("Downloading " + event.ID)- progressUI.SetTotal(event.ProgressDetail.Total)+ if event.ID != "" {+ label := event.Status + " " + event.ID+ loading.SetProgress(event.ID, label, event.ProgressDetail.Current, event.ProgressDetail.Total, true)+ if event.Status == "Download complete" || event.Status == "Pull complete" || event.Status == "Already exists" {+ loading.Finish(event.ID, nil)}- progressUI.SetCurrent(event.ProgressDetail.Current)- } else {- if progressUI != nil {- // Stop the progress bar when the current layer completes.- if event.ID == currentID && event.Status == "Download complete" {- progressUI.SetCurrent(event.ProgressDetail.Total)- progressUI.SetLabel("Download complete")- progressUI.Stop()- progressUI = nil- currentID = ""- }- }-- // Only print status if it's not a progress update for the current bar- if event.Status != "Downloading" {+ }+ if !output.IsTerminal(cmd.ErrOrStderr()) || !output.IsTerminal(cmd.OutOrStdout()) || event.ID == "" {+ if event.Status != "Downloading" && event.Status != "Extracting" {+ deferResume := output.SuspendProgress()if event.ID != "" {- fmt.Printf("%s: %s\n", event.ID, event.Status)+ _, _ = fmt.Fprintf(cmd.OutOrStdout(), "%s: %s\n", event.ID, event.Status)} else {- fmt.Printf("%s\n", event.Status)+ _, _ = fmt.Fprintln(cmd.OutOrStdout(), event.Status)}+ deferResume()}}}-- if progressUI != nil {- progressUI.Stop()- }+ loading.Stop()output.Success("Image pulled successfully")@@ -427,18 +407,10 @@ var imagesPruneCmd = &cobra.Command{}jsonOutput := cmdutil.JSONOutputEnabled(cmd)- var spinner *output.Spinner-- if !jsonOutput {- spinner = output.StartSpinner("Pruning images...")- }-+ loading := output.StartTracker(cmd.Context(), cmd.ErrOrStderr(), !jsonOutput, "Pruning images")+ loading.NextStep()+ defer loading.Stop()resp, err := c.Post(cmd.Context(), path, requestBody)-- if spinner != nil {- spinner.Stop()- }-if err != nil {return fmt.Errorf("failed to prune images: %w", err)}@@ -456,7 +428,7 @@ var imagesPruneCmd = &cobra.Command{log.Debugf("Response body: %s", string(body))if cmdutil.JSONOutputEnabled(cmd) {- fmt.Println(string(body))+ _, _ = fmt.Fprintln(output.Stdout(), string(body))return nil}@@ -507,7 +479,7 @@ var imagesCountsCmd = &cobra.Command{log.Debugf("Response body: %s", string(body))if cmdutil.JSONOutputEnabled(cmd) {- fmt.Println(string(body))+ _, _ = fmt.Fprintln(output.Stdout(), string(body))return nil}@@ -563,7 +535,7 @@ var imagesUploadCmd = &cobra.Command{log.Debugf("Response body: %s", string(respBody))if jsonOutput {- fmt.Println(string(respBody))+ _, _ = fmt.Fprintln(output.Stdout(), string(respBody))return nil}diff --git a/cli/pkg/images/extra.go b/cli/pkg/images/extra.goindex 4ccd13c53..8533a851e 100644--- a/cli/pkg/images/extra.go+++ b/cli/pkg/images/extra.go@@ -235,7 +235,7 @@ var imagesExportCmd = &cobra.Command{return fmt.Errorf("failed to create output file: %w", err)}- written, err := io.Copy(file, resp.Body)+ written, err := output.Copy(cmd.Context(), file, resp.Body, resp.ContentLength, "Exporting image", !cmdutil.JSONOutputEnabled(cmd))if closeErr := file.Close(); closeErr != nil && err == nil {err = closeErr}@@ -349,7 +349,7 @@ var imagesAttestationsCmd = &cobra.Command{for _, att := range result.Data.Attestations {rows = append(rows, []string{att.PredicateType, att.Platform, truncateCell(att.Digest, 19), output.Bytes(att.Size)})}- fmt.Println()+ _, _ = fmt.Fprintln(output.Stdout())if tableErr := output.Table(headers, rows); tableErr != nil {return tableErr}@@ -485,7 +485,7 @@ func streamBuildOutput(body io.Reader) error {}}}- fmt.Println(line)+ _, _ = fmt.Fprintln(output.Stdout(), line)}if err := scanner.Err(); err != nil {return fmt.Errorf("failed to read build stream: %w", err)@@ -608,7 +608,7 @@ var imagesBuildsGetCmd = &cobra.Command{if record.Output != nil && *record.Output != "" {output.Header("Output")- fmt.Println(*record.Output)+ _, _ = fmt.Fprintln(output.Stdout(), *record.Output)if record.OutputTruncated {output.Warning("Output was truncated")}diff --git a/cli/pkg/images/updates/cmd.go b/cli/pkg/images/updates/cmd.goindex 4b731a15c..0c5c03aa9 100644--- a/cli/pkg/images/updates/cmd.go+++ b/cli/pkg/images/updates/cmd.go@@ -116,7 +116,7 @@ var checkAllCmd = &cobra.Command{}}- fmt.Printf("\nTotal: %d images checked, %d updates available\n", len(result.Data), updatesAvailable)+ _, _ = fmt.Fprintf(output.Stdout(), "\nTotal: %d images checked, %d updates available\n", len(result.Data), updatesAvailable)return nil},}@@ -216,7 +216,7 @@ func printBatchResultsInternal(result imageupdate.BatchResponse) error {if tableErr := output.Table(headers, rows); tableErr != nil {return tableErr}- fmt.Printf("\nTotal: %d images checked, %d updates available\n", len(result), updatesAvailable)+ _, _ = fmt.Fprintf(output.Stdout(), "\nTotal: %d images checked, %d updates available\n", len(result), updatesAvailable)return nil}diff --git a/cli/pkg/jobs/cmd.go b/cli/pkg/jobs/cmd.goindex fdf08ea15..7fc452a85 100644--- a/cli/pkg/jobs/cmd.go+++ b/cli/pkg/jobs/cmd.go@@ -22,13 +22,18 @@ var (requestID string)-// JobsCmd is the parent command for job schedule operations.+// JobsCmd is the parent command for background jobs and their schedules.var JobsCmd = &cobra.Command{Use: "jobs",Aliases: []string{"job"},Short: "Manage background jobs",}+var schedulesCmd = &cobra.Command{+ Use: "schedules",+ Short: "Manage job schedule intervals",+}+var getCmd = &cobra.Command{Use: "get",Short: "Get configured job schedule intervals",@@ -144,7 +149,7 @@ var listCmd = &cobra.Command{if tableErr := output.Table(headers, rows); tableErr != nil {return tableErr}- fmt.Printf("\nTotal: %d jobs\n", len(result.Jobs))+ _, _ = fmt.Fprintf(output.Stdout(), "\nTotal: %d jobs\n", len(result.Jobs))return nil},}@@ -188,8 +193,9 @@ var runCmd = &cobra.Command{}func init() {- JobsCmd.AddCommand(getCmd)- JobsCmd.AddCommand(updateCmd)+ JobsCmd.AddCommand(schedulesCmd)+ schedulesCmd.AddCommand(getCmd)+ schedulesCmd.AddCommand(updateCmd)JobsCmd.AddCommand(listCmd)JobsCmd.AddCommand(runCmd)diff --git a/cli/pkg/networks/cmd.go b/cli/pkg/networks/cmd.goindex 7e0849d73..92b440c74 100644--- a/cli/pkg/networks/cmd.go+++ b/cli/pkg/networks/cmd.go@@ -181,7 +181,7 @@ var deleteCmd = &cobra.Command{return confirmErr}if !confirmed {- fmt.Println("Cancelled")+ _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")return nil}}@@ -238,7 +238,7 @@ var pruneCmd = &cobra.Command{return err}if !confirmed {- fmt.Println("Cancelled")+ _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")return nil}}diff --git a/cli/pkg/projects/actions.go b/cli/pkg/projects/actions.goindex 469b2a2cf..1ea24a44e 100644--- a/cli/pkg/projects/actions.go+++ b/cli/pkg/projects/actions.go@@ -3,7 +3,6 @@ package projectsimport ("errors""fmt"- "io""net/http""net/url""os"@@ -277,7 +276,7 @@ var workspaceCatCmd = &cobra.Command{if result.Data.Content == "" && result.Data.ReadOnlyReason != "" {return fmt.Errorf("file %s has no inline content (%s); use `arcane projects workspace download` instead", args[1], result.Data.ReadOnlyReason)}- fmt.Print(result.Data.Content)+ _, _ = fmt.Fprint(output.Stdout(), result.Data.Content)return nil},}@@ -317,7 +316,7 @@ var workspaceDownloadCmd = &cobra.Command{if err != nil {return fmt.Errorf("failed to create file %s: %w", outputFile, err)}- written, copyErr := io.Copy(file, resp.Body)+ written, copyErr := output.Copy(cmd.Context(), file, resp.Body, resp.ContentLength, "Downloading workspace file", !cmdutil.JSONOutputEnabled(cmd))closeErr := file.Close()if copyErr != nil {return fmt.Errorf("failed to write workspace file: %w", copyErr)diff --git a/cli/pkg/projects/cmd.go b/cli/pkg/projects/cmd.goindex ae0854f2d..2e4e0b6ab 100644--- a/cli/pkg/projects/cmd.go+++ b/cli/pkg/projects/cmd.go@@ -182,7 +182,7 @@ var destroyCmd = &cobra.Command{return confirmErr}if !confirmed {- fmt.Println("Cancelled")+ _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")return nil}}@@ -401,7 +401,7 @@ func printOperationStreamInternal(body io.Reader) error {return nil}if frame.Log != "" {- fmt.Println(frame.Log)+ _, _ = fmt.Fprintln(output.Stdout(), frame.Log)}}diff --git a/cli/pkg/registries/cmd.go b/cli/pkg/registries/cmd.goindex ae4f445f6..4465db448 100644--- a/cli/pkg/registries/cmd.go+++ b/cli/pkg/registries/cmd.go@@ -273,7 +273,7 @@ var deleteCmd = &cobra.Command{return err}if !confirmed {- fmt.Println("Cancelled")+ _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")return nil}}diff --git a/cli/pkg/repos/cmd.go b/cli/pkg/repos/cmd.goindex f6c2dae07..8e96a20b8 100644--- a/cli/pkg/repos/cmd.go+++ b/cli/pkg/repos/cmd.go@@ -339,7 +339,7 @@ var deleteCmd = &cobra.Command{return confirmErr}if !confirmed {- fmt.Println("Cancelled")+ _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")return nil}}@@ -424,7 +424,7 @@ var branchesCmd = &cobra.Command{if tableErr := output.Table(headers, rows); tableErr != nil {return tableErr}- fmt.Printf("\nTotal: %d branches\n", len(result.Data.Branches))+ _, _ = fmt.Fprintf(output.Stdout(), "\nTotal: %d branches\n", len(result.Data.Branches))return nil},}@@ -485,7 +485,7 @@ var filesCmd = &cobra.Command{if tableErr := output.Table(headers, rows); tableErr != nil {return tableErr}- fmt.Printf("\nTotal: %d entries\n", len(files))+ _, _ = fmt.Fprintf(output.Stdout(), "\nTotal: %d entries\n", len(files))return nil},}diff --git a/cli/pkg/root.go b/cli/pkg/root.goindex 5a82fbff5..01635f1a3 100644--- a/cli/pkg/root.go+++ b/cli/pkg/root.go@@ -22,7 +22,6 @@//// - admin: Administration & platform management// - auth: Authentication operations-// - backups: Manage Arcane system backups// - config: Manage CLI configuration// - containers: Manage containers// - images: Manage Docker images and updates@@ -36,7 +35,9 @@ import ("cmp""context""fmt"+ "io""os"+ "os/signal""runtime""strings""time"@@ -53,7 +54,6 @@ import ("github.com/getarcaneapp/arcane/cli/v2/pkg/activities""github.com/getarcaneapp/arcane/cli/v2/pkg/admin""github.com/getarcaneapp/arcane/cli/v2/pkg/auth"- "github.com/getarcaneapp/arcane/cli/v2/pkg/backups""github.com/getarcaneapp/arcane/cli/v2/pkg/completion"configClient "github.com/getarcaneapp/arcane/cli/v2/pkg/config""github.com/getarcaneapp/arcane/cli/v2/pkg/containers"@@ -126,13 +126,13 @@ var rootCmd = &cobra.Command{logLevel = cfg.LogLevel}- if noColorOutput {- output.SetColorEnabled(false)- } else {- output.SetColorEnabled(true)+ jsonMode := outputMode == string(runtimectx.OutputModeJSON)+ if flag := cmd.Flags().Lookup("json"); flag != nil {+ localJSON, _ := cmd.Flags().GetBool("json")+ jsonMode = jsonMode || localJSON}-- logger.Setup(logLevel, logJSONOutput)+ output.Configure(cmd.OutOrStdout(), cmd.ErrOrStderr(), jsonMode, noColorOutput, cmd.Short)+ logger.Setup(cmd.ErrOrStderr(), logLevel, logJSONOutput)app, err := runtimectx.New(runtimectx.Options{EnvOverride: envOverride,@@ -156,10 +156,10 @@ var rootCmd = &cobra.Command{},RunE: func(cmd *cobra.Command, args []string) error {if showVersion {- fmt.Printf("Arcane CLI version: %s\n", config.Version)- fmt.Printf("Git revision: %s\n", config.Revision)- fmt.Printf("Go version: %s\n", runtime.Version())- fmt.Printf("OS/Arch: %s/%s\n", runtime.GOOS, runtime.GOARCH)+ _, _ = fmt.Fprintf(output.Stdout(), "Arcane CLI version: %s\n", config.Version)+ _, _ = fmt.Fprintf(output.Stdout(), "Git revision: %s\n", config.Revision)+ _, _ = fmt.Fprintf(output.Stdout(), "Go version: %s\n", runtime.Version())+ _, _ = fmt.Fprintf(output.Stdout(), "OS/Arch: %s/%s\n", runtime.GOOS, runtime.GOARCH)return nil}return cmd.Help()@@ -168,15 +168,19 @@ var rootCmd = &cobra.Command{}func Execute() {+ ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt) //nolint:forbidigo // CLI process context.if err := fang.Execute(- context.Background(), //nolint:forbidigo // CLI entry point establishes the process context.+ ctx,rootCmd,fang.WithColorSchemeFunc(arcaneFangColorSchemeInternal),+ fang.WithErrorHandler(func(w io.Writer, _ fang.Styles, err error) { output.WriteError(w, err) }),fang.WithVersion(config.Version),fang.WithCommit(config.Revision),); err != nil {+ cancel()os.Exit(1)}+ cancel()}// RootCommand returns the configured root command.@@ -258,6 +262,7 @@ func init() {rootCmd.AddCommand(version.VersionCmd)rootCmd.AddCommand(auth.AuthCmd)rootCmd.AddCommand(containers.ContainersCmd)+ images.ImagesCmd.AddCommand(vulnerabilities.VulnerabilitiesCmd)rootCmd.AddCommand(images.ImagesCmd)rootCmd.AddCommand(volumes.VolumesCmd)rootCmd.AddCommand(networks.NetworksCmd)@@ -273,9 +278,7 @@ func init() {rootCmd.AddCommand(selfupdate.Cmd)rootCmd.AddCommand(admin.AdminCmd)rootCmd.AddCommand(gitops.GitopsCmd)- rootCmd.AddCommand(backups.BackupsCmd)rootCmd.AddCommand(variables.VariablesCmd)- rootCmd.AddCommand(vulnerabilities.VulnerabilitiesCmd)rootCmd.AddCommand(activities.ActivitiesCmd)rootCmd.AddCommand(webhooks.WebhooksCmd)diff --git a/cli/pkg/selfupdate/cmd.go b/cli/pkg/selfupdate/cmd.goindex fc68ed768..99ae3279e 100644--- a/cli/pkg/selfupdate/cmd.go+++ b/cli/pkg/selfupdate/cmd.go@@ -129,7 +129,9 @@ func setCLIUpdateChannelAndRunInternal(cmd *cobra.Command, channel string) errorif err := saveCLIUpdateChannelInternal(channel); err != nil {return err}- output.Success("Set CLI update channel to %s", channel)+ if !jsonOutput {+ output.Success("Set CLI update channel to %s", channel)+ }return runCLIUpdateInternal(cmd.Context(), channel)}@@ -138,11 +140,16 @@ func runCLIUpdateCommandInternal(cmd *cobra.Command, args []string) error {}func runCLIUpdateInternal(ctx context.Context, overrideChannel string) error {+ loading := output.StartTracker(ctx, output.Stderr(), !jsonOutput, "Resolving update")+ loading.NextStep()+ defer loading.Stop()plan, err := buildCLIUpdatePlanInternal(ctx, overrideChannel)if err != nil {return err}+ loading.Finish("", err)+ loading.Stop()if jsonOutput {return cmdutil.PrintJSON(plan)}@@ -439,16 +446,21 @@ func installCLIUpdateInternal(ctx context.Context, plan *cliUpdatePlan) error {}defer func() { _ = os.RemoveAll(tmpDir) }()+ loading := output.StartTracker(ctx, output.Stderr(), !jsonOutput, "Downloading artifact", "Verifying artifact", "Installing executable")+ loading.NextStep()+ defer loading.Stop()downloadPath := filepath.Join(tmpDir, plan.ArtifactName)if downloadFileErr := downloadFileInternal(ctx, plan.ArtifactURL, downloadPath); downloadFileErr != nil {return downloadFileErr}+ loading.NextStep()if gotSHA, sha256FileErr := sha256FileInternal(downloadPath); sha256FileErr != nil {return sha256FileErr} else if !strings.EqualFold(gotSHA, plan.ArtifactSHA) {return fmt.Errorf("downloaded artifact SHA mismatch: got %s, expected %s", gotSHA, plan.ArtifactSHA)}+ loading.NextStep()binaryPath := downloadPathif strings.HasSuffix(plan.ArtifactName, ".tar.gz") {extractedPath := filepath.Join(tmpDir, "arcane-cli")@@ -612,7 +624,7 @@ func downloadFileInternal(ctx context.Context, url, outputPath string) error {return fmt.Errorf("failed to create download file: %w", err)}limitedBody := &io.LimitedReader{R: resp.Body, N: maxCLIDownloadSize + 1}- written, err := io.Copy(out, limitedBody)+ written, err := output.Copy(ctx, out, limitedBody, resp.ContentLength, "Downloading artifact", !jsonOutput)if err != nil {_ = out.Close()return fmt.Errorf("failed to write download file: %w", err)@@ -632,7 +644,7 @@ func verboseCLIUpdateInternal(format string, args ...any) {if !cliUpdateVerbose {return}- fmt.Fprintf(os.Stderr, "self-update: "+format+"\n", args...)+ _, _ = fmt.Fprintf(output.CoordinatedWriter(output.Stderr()), "self-update: "+format+"\n", args...)}func sha256FileInternal(filePath string) (string, error) {diff --git a/cli/pkg/settings/cmd.go b/cli/pkg/settings/cmd.goindex 7f020e282..f37797456 100644--- a/cli/pkg/settings/cmd.go+++ b/cli/pkg/settings/cmd.go@@ -117,7 +117,7 @@ func runSettingsList(cmd *cobra.Command, cfg settingsListConfig) error {if tableErr := output.Table(headers, rows); tableErr != nil {return tableErr}- fmt.Printf("\nTotal: %d %s\n", len(result), cfg.totalLabel)+ _, _ = fmt.Fprintf(output.Stdout(), "\nTotal: %d %s\n", len(result), cfg.totalLabel)return nil}diff --git a/cli/pkg/system/cmd.go b/cli/pkg/system/cmd.goindex a8f039ef9..2f9ce1e1b 100644--- a/cli/pkg/system/cmd.go+++ b/cli/pkg/system/cmd.go@@ -177,15 +177,15 @@ var convertCmd = &cobra.Command{output.Header("Conversion Result")if result.ServiceName != "" {- fmt.Printf("Service: %s\n\n", result.ServiceName)+ _, _ = fmt.Fprintf(output.Stdout(), "Service: %s\n\n", result.ServiceName)}if result.DockerCompose != "" {- fmt.Println("Docker Compose:")- fmt.Println(result.DockerCompose)+ _, _ = fmt.Fprintln(output.Stdout(), "Docker Compose:")+ _, _ = fmt.Fprintln(output.Stdout(), result.DockerCompose)}if result.EnvVars != "" {- fmt.Println("Environment Variables:")- fmt.Println(result.EnvVars)+ _, _ = fmt.Fprintln(output.Stdout(), "Environment Variables:")+ _, _ = fmt.Fprintln(output.Stdout(), result.EnvVars)}return nil},@@ -217,7 +217,7 @@ var upgradeCmd = &cobra.Command{return err}if !confirmed {- fmt.Println("Cancelled")+ _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")return nil}}@@ -320,7 +320,7 @@ func printUpdateAllJobInternal(job environmentUpdateJob) error {resErr := cmp.Or(res.Error, "-")rows[i] = []string{name, res.Status, res.FromVersion, res.ToVersion, resErr}}- if _, spacingErr := fmt.Println(); spacingErr != nil {+ if _, spacingErr := fmt.Fprintln(output.Stdout()); spacingErr != nil {return fmt.Errorf("failed to print update status: %w", spacingErr)}return output.Table(headers, rows)@@ -357,7 +357,7 @@ func runUpgradeAllInternal(cmd *cobra.Command) error {return confirmErr}if !confirmed {- fmt.Println("Cancelled")+ _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")return nil}}diff --git a/cli/pkg/templates/cmd.go b/cli/pkg/templates/cmd.goindex 7207628c1..383be00c7 100644--- a/cli/pkg/templates/cmd.go+++ b/cli/pkg/templates/cmd.go@@ -174,11 +174,11 @@ var contentCmd = &cobra.Command{output.KeyValue("Description", result.Data.Template.Description)output.KeyValue("Services", strconv.Itoa(len(result.Data.Services)))output.KeyValue("Env Variables", strconv.Itoa(len(result.Data.EnvVariables)))- fmt.Println("\n--- Compose Content ---")- fmt.Println(result.Data.Content)+ _, _ = fmt.Fprintln(output.Stdout(), "\n--- Compose Content ---")+ _, _ = fmt.Fprintln(output.Stdout(), result.Data.Content)if result.Data.EnvContent != "" {- fmt.Println("\n--- Environment Content ---")- fmt.Println(result.Data.EnvContent)+ _, _ = fmt.Fprintln(output.Stdout(), "\n--- Environment Content ---")+ _, _ = fmt.Fprintln(output.Stdout(), result.Data.EnvContent)}return nil},@@ -222,7 +222,7 @@ var registriesCmd = &cobra.Command{if tableErr := output.Table(headers, rows); tableErr != nil {return tableErr}- fmt.Printf("\nTotal: %d registries\n", len(result.Data))+ _, _ = fmt.Fprintf(output.Stdout(), "\nTotal: %d registries\n", len(result.Data))return nil},}@@ -234,7 +234,7 @@ func runTemplateDeleteInternal(cmd *cobra.Command, label, path string) error {return err}if !confirmed {- fmt.Println("Cancelled")+ _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")return nil}}@@ -726,7 +726,7 @@ var downloadCmd = &cobra.Command{return nil}- fmt.Print(result.Data.Content)+ _, _ = fmt.Fprint(output.Stdout(), result.Data.Content)return nil},}diff --git a/cli/pkg/updater/cmd.go b/cli/pkg/updater/cmd.goindex 521c04171..0d1bf3567 100644--- a/cli/pkg/updater/cmd.go+++ b/cli/pkg/updater/cmd.go@@ -145,7 +145,7 @@ var historyCmd = &cobra.Command{if tableErr := output.Table(headers, rows); tableErr != nil {return tableErr}- fmt.Printf("\nTotal: %d history entries\n", len(result.Data))+ _, _ = fmt.Fprintf(output.Stdout(), "\nTotal: %d history entries\n", len(result.Data))return nil},}diff --git a/cli/pkg/variables/cmd.go b/cli/pkg/variables/cmd.goindex 4fe4856dc..b532587f7 100644--- a/cli/pkg/variables/cmd.go+++ b/cli/pkg/variables/cmd.go@@ -126,7 +126,7 @@ var listCmd = &cobra.Command{if tableErr := output.Table(headers, rows); tableErr != nil {return tableErr}- fmt.Printf("\nTotal: %d variables\n", len(result.Data))+ _, _ = fmt.Fprintf(output.Stdout(), "\nTotal: %d variables\n", len(result.Data))return nil},}@@ -212,7 +212,7 @@ var deleteCmd = &cobra.Command{return err}if !confirmed {- fmt.Println("Cancelled")+ _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")return nil}}diff --git a/cli/pkg/version/cmd.go b/cli/pkg/version/cmd.goindex 0a314bd6f..4214d542d 100644--- a/cli/pkg/version/cmd.go+++ b/cli/pkg/version/cmd.go@@ -1,50 +1,60 @@package versionimport (+ "cmp""fmt""net/http""github.com/getarcaneapp/arcane/types/v2/version""github.com/spf13/cobra"- "github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"+ "github.com/getarcaneapp/arcane/cli/v2/internal/config""github.com/getarcaneapp/arcane/cli/v2/internal/logger""github.com/getarcaneapp/arcane/cli/v2/internal/output"clitypes "github.com/getarcaneapp/arcane/cli/v2/internal/types")-// VersionCmd gets the server version+// VersionCmd displays CLI and server versions.var VersionCmd = &cobra.Command{Use: "version",- Short: "Get the Arcane server version",+ Short: "Show CLI and Arcane server versions",+ Args: cobra.NoArgs,SilenceUsage: true,RunE: func(cmd *cobra.Command, args []string) error {- logger.GetLogger().Debug("Fetching server version")-- c, err := client.NewFromConfig()- if err != nil {- return err+ jsonOutput := cmdutil.JSONOutputEnabled(cmd)+ if !jsonOutput {+ output.Header("Arcane CLI")+ output.KeyValue("Version", config.Version)+ output.KeyValue("Revision", config.Revision)}- // /api/version returns the trimmed version.Check payload, which carries- // neither displayVersion nor revision. /api/app-version returns the full- // version.Info, including the update-check fields printed below.- logger.GetLogger().Debug("Sending request", "endpoint", clitypes.AppVersionEndpoint)- result, err := c.DoJSON[version.Info](cmd.Context(), http.MethodGet, clitypes.AppVersionEndpoint, nil)+ c, err := cmdutil.ClientFromCommand(cmd)+ var result version.Info+ if err == nil {+ logger.GetLogger().Debug("Fetching server version", "endpoint", clitypes.AppVersionEndpoint)+ result, err = c.DoJSON[version.Info](cmd.Context(), http.MethodGet, clitypes.AppVersionEndpoint, nil)+ }if err != nil {- return fmt.Errorf("failed to get version: %w", err)+ if cmd.Context().Err() != nil {+ return cmd.Context().Err()+ }+ if jsonOutput {+ return fmt.Errorf("failed to get server version: %w", err)+ }+ output.Header("Arcane Server")+ output.KeyValue("Status", "Unavailable")+ output.Warning("Could not get server version: %s", err)+ return nil}- logger.GetLogger().Debug("Parsed version data", "result", result)-if cmdutil.JSONOutputEnabled(cmd) {return cmdutil.PrintJSON(result)}- output.Header("Arcane Environment Details: \n")+ output.Header("Arcane Server")- output.KeyValue("Version", result.DisplayVersion)+ output.KeyValue("Version", cmp.Or(result.DisplayVersion, result.CurrentVersion))if result.Revision != "" {output.KeyValue("Revision", result.Revision)}diff --git a/cli/pkg/volumes/backup.go b/cli/pkg/volumes/backup.goindex 98b93d2dd..fd3c9e58a 100644--- a/cli/pkg/volumes/backup.go+++ b/cli/pkg/volumes/backup.go@@ -2,6 +2,7 @@ package volumesimport ("cmp"+ "context""encoding/json/v2""errors""fmt"@@ -75,7 +76,7 @@ var renameCmd = &cobra.Command{return confirmErr}if !confirmed {- fmt.Println("Cancelled")+ _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")return nil}}@@ -245,7 +246,7 @@ func printBackupPolicies(volumeName string, collection volume.BackupPolicyCollecoutput.Header("Backup Policies: %s", volumeName)output.KeyValue("S3 Available", collection.S3Available)if len(collection.Policies) == 0 {- _, writeErr := fmt.Println("No backup policies configured")+ _, writeErr := fmt.Fprintln(output.Stdout(), "No backup policies configured")return writeErr}@@ -434,7 +435,7 @@ and restored instead (no backup ID).`,return confirmErr}if !confirmed {- fmt.Println("Cancelled")+ _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")return nil}}@@ -460,7 +461,7 @@ func runRestorePaths(cmd *cobra.Command, c *client.Client, volumeName, backupIDreturn err}if !confirmed {- fmt.Println("Cancelled")+ _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")return nil}}@@ -489,7 +490,7 @@ func runUploadRestore(cmd *cobra.Command, c *client.Client, volumeName string) ereturn err}if !confirmed {- fmt.Println("Cancelled")+ _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")return nil}}@@ -509,7 +510,7 @@ func runUploadRestore(cmd *cobra.Command, c *client.Client, volumeName string) e}if jsonOutput {- fmt.Println(string(respBody))+ _, _ = fmt.Fprintln(output.Stdout(), string(respBody))return nil}@@ -530,7 +531,7 @@ var backupsDeleteCmd = &cobra.Command{return err}if !confirmed {- fmt.Println("Cancelled")+ _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")return nil}}@@ -609,7 +610,7 @@ var backupsDownloadCmd = &cobra.Command{outputFile = downloadFilename(resp, args[0]+".tar.gz")}- if writeResponseToFileErr := writeResponseToFile(resp.Body, outputFile); writeResponseToFileErr != nil {+ if writeResponseToFileErr := writeResponseToFileInternal(cmd.Context(), resp.Body, resp.ContentLength, outputFile, !cmdutil.JSONOutputEnabled(cmd)); writeResponseToFileErr != nil {return writeResponseToFileErr}@@ -629,12 +630,12 @@ func downloadFilename(resp *http.Response, fallback string) string {return fallback}-func writeResponseToFile(body io.Reader, path string) error {+func writeResponseToFileInternal(ctx context.Context, body io.Reader, total int64, path string, showProgress bool) error {file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600)if err != nil {return fmt.Errorf("failed to create file %s: %w", path, err)}- if _, copyErr := io.Copy(file, body); copyErr != nil {+ if _, copyErr := output.Copy(ctx, file, body, total, "Downloading backup", showProgress); copyErr != nil {_ = file.Close()return fmt.Errorf("failed to write file %s: %w", path, copyErr)}@@ -665,7 +666,7 @@ var backupsFilesCmd = &cobra.Command{}for _, file := range result.Data {- fmt.Println(file)+ _, _ = fmt.Fprintln(output.Stdout(), file)}return nil},diff --git a/cli/pkg/volumes/cmd.go b/cli/pkg/volumes/cmd.goindex 1bc2982c4..ae82f21b9 100644--- a/cli/pkg/volumes/cmd.go+++ b/cli/pkg/volumes/cmd.go@@ -158,7 +158,7 @@ var deleteCmd = &cobra.Command{return confirmErr}if !confirmed {- fmt.Println("Cancelled")+ _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")return nil}}@@ -206,7 +206,7 @@ var pruneCmd = &cobra.Command{return err}if !confirmed {- fmt.Println("Cancelled")+ _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")return nil}}diff --git a/cli/pkg/volumes/workspace.go b/cli/pkg/volumes/workspace.goindex ef38ac5ad..92824c54e 100644--- a/cli/pkg/volumes/workspace.go+++ b/cli/pkg/volumes/workspace.go@@ -148,7 +148,7 @@ var workspaceCatCmd = &cobra.Command{return fmt.Errorf("file %s has no printable content (%s); use `arcane volumes workspace download` instead", args[1], result.Data.ReadOnlyReason)}- fmt.Print(result.Data.Content)+ _, _ = fmt.Fprint(output.Stdout(), result.Data.Content)return nil},}@@ -194,7 +194,7 @@ var workspaceDownloadCmd = &cobra.Command{outputFile = downloadFilename(resp, path.Base(args[1]))}- if writeResponseToFileErr := writeResponseToFile(resp.Body, outputFile); writeResponseToFileErr != nil {+ if writeResponseToFileErr := writeResponseToFileInternal(cmd.Context(), resp.Body, resp.ContentLength, outputFile, !cmdutil.JSONOutputEnabled(cmd)); writeResponseToFileErr != nil {return writeResponseToFileErr}@@ -236,7 +236,7 @@ var workspacePutCmd = &cobra.Command{return confirmErr}if !confirmed {- fmt.Println("Cancelled")+ _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")return nil}}diff --git a/cli/pkg/vulnerabilities/cmd.go b/cli/pkg/vulnerabilities/cmd.goindex f7951294d..1c04942bc 100644--- a/cli/pkg/vulnerabilities/cmd.go+++ b/cli/pkg/vulnerabilities/cmd.go@@ -1,7 +1,7 @@// Package vulnerabilities provides CLI commands for image vulnerability// scanning on Arcane servers.//-// This package implements the "arcane vulnerabilities" command group, which+// This package implements the "arcane images vulnerabilities" command group, which// includes subcommands for checking scanner status, viewing environment-wide// summaries, listing vulnerabilities, scanning images, and managing ignore// records.@@ -347,7 +347,7 @@ var unignoreCmd = &cobra.Command{return err}if !confirmed {- fmt.Println("Cancelled")+ _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")return nil}}diff --git a/cli/pkg/webhooks/cmd.go b/cli/pkg/webhooks/cmd.goindex 533046f92..b9658ed69 100644--- a/cli/pkg/webhooks/cmd.go+++ b/cli/pkg/webhooks/cmd.go@@ -172,7 +172,7 @@ var deleteCmd = &cobra.Command{return err}if !confirmed {- fmt.Println("Cancelled")+ _, _ = fmt.Fprintln(output.Stdout(), "Cancelled")return nil}}