Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion internal/cli/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -734,7 +734,13 @@ func runInteractiveTUIWithSetup(stderr io.Writer, deps appDeps, permissionMode a
resolved.Provider = usable
resolved.ActiveProvider = usable.Name
} else {
resolved = config.ResolvedConfig{}
// Fresh-onboarding reset, but the user's notification preference is
// NOT config-to-redo: clearing it here would surface as an empty
// Options.Notify, and the TUI's unconfigured default (both/unfocused)
// would then resurrect alerts a user explicitly turned off while the
// setup wizard runs (maintainer review, PR #1001). Carry the stored
// block through; other wizard-visible state starts clean as before.
resolved = config.ResolvedConfig{Notify: resolved.Notify}
forceSetup = true
}
}
Expand Down
67 changes: 67 additions & 0 deletions internal/cli/app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,73 @@ func TestRunNoArgsFallsBackToUsableProviderWhenNoneMarkedActive(t *testing.T) {
}
}

// Maintainer regression (PR #1001): a stored explicit notify opt-out must
// survive the provider-recovery startup path. With a stale activeProvider and
// another usable saved provider, Resolve returns the partial config alongside
// ErrNoActiveProvider and the recovery branch forwards it — dropping the
// notify policy there would surface an empty Options.Notify, and the TUI's
// unconfigured default (both) would resurrect alerts the user explicitly
// turned off. The same recovery branch that clears the resolved config for
// the setup wizard carries the stored notify block through.
func TestRunNoArgsPreservesNotifyOptOutThroughProviderRecovery(t *testing.T) {
var stdout bytes.Buffer
var stderr bytes.Buffer
cwd := t.TempDir()
setCLIUserConfigRoot(t)
userConfigPath := filepath.Join(t.TempDir(), "zero", "config.json")
var launchedOptions tui.Options
launched := false

usable := config.ProviderProfile{
Name: "work",
ProviderKind: config.ProviderKindOpenAI,
BaseURL: config.OpenAIBaseURL,
APIKey: "sk-test",
Model: "gpt-test",
}

exitCode := runWithDeps([]string{}, &stdout, &stderr, appDeps{
getwd: func() (string, error) {
return cwd, nil
},
resolveConfig: func(workspaceRoot string, overrides config.Overrides) (config.ResolvedConfig, error) {
// Stale activeProvider + usable saved provider, and the user's
// config.json explicitly opts out of notifications. The fixed
// resolver carries the parsed notify block through the error path.
return config.ResolvedConfig{
Providers: []config.ProviderProfile{usable},
Notify: config.NotifyConfig{Mode: "off", FocusMode: "always"},
}, fmt.Errorf("%w: active provider %q not found", config.ErrNoActiveProvider, "ghost")
},
newProvider: func(profile config.ProviderProfile) (zeroruntime.Provider, error) {
return &cliFakeProvider{}, nil
},
userConfigPath: func() (string, error) {
return userConfigPath, nil
},
registerMCPTools: func(context.Context, *tools.Registry, config.MCPConfig, mcp.RegisterOptions) (mcpToolRuntime, error) {
return noopMCPRuntime{}, nil
},
runTUI: func(ctx context.Context, options tui.Options) int {
launched = true
launchedOptions = options
return 0
},
})

if exitCode != 0 {
t.Fatalf("exit code = %d, want 0, stderr=%q", exitCode, stderr.String())
}
if !launched {
t.Fatal("TUI was not launched")
}
// The explicit opt-out reaches the TUI intact — NOT the both/unfocused
// unconfigured default.
if launchedOptions.Notify.Mode != "off" || launchedOptions.Notify.FocusMode != "always" {
t.Fatalf("Options.Notify = %+v, want the stored off/always opt-out preserved through recovery", launchedOptions.Notify)
}
}

func TestRunNoArgsFailsWhenResolveErrorIsNotProviderRelated(t *testing.T) {
var stdout bytes.Buffer
var stderr bytes.Buffer
Expand Down
30 changes: 29 additions & 1 deletion internal/cli/command_center.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,30 @@ type modelSummary = zerocommands.ModelSnapshot
type providerCatalogSummary = zerocommands.ProviderCatalogSnapshot

func runConfig(args []string, stdout io.Writer, stderr io.Writer, deps appDeps) int {
// The first non-flag argument is a subcommand. With no positional argument
// (or only flag arguments), the read-only summary path runs — this keeps
// `zero config` and `zero config --json` working unchanged.
command := "summary"
rest := args
if len(args) > 0 && !strings.HasPrefix(args[0], "-") {
command = strings.ToLower(strings.TrimSpace(args[0]))
rest = args[1:]
}
switch command {
case "summary":
return runConfigSummary(rest, stdout, stderr, deps)
case "notify":
return runConfigNotify(rest, stdout, stderr, deps)
case "help":
if err := writeConfigHelp(stdout); err != nil {
return exitCrash
}
return exitSuccess
}
return writeExecUsageError(stderr, fmt.Sprintf("unknown config command %q", command))
}

func runConfigSummary(args []string, stdout io.Writer, stderr io.Writer, deps appDeps) int {
options, help, err := parseCommandCenterArgs(args, false, false)
if err != nil {
return writeExecUsageError(stderr, err.Error())
Expand Down Expand Up @@ -462,8 +486,12 @@ func formatProviderCatalogValue(value string, fallback string) string {
func writeConfigHelp(w io.Writer) error {
_, err := fmt.Fprint(w, `Usage:
zero config [flags]
zero config notify [flags]

Inspects resolved Go configuration without printing secrets.
Inspects resolved Go configuration without printing secrets. The notify
subcommand reads or updates the stored global notification preference,
which controls both the completion and needs-input alerts —
run "zero config notify --help" for details.

Flags:
--json Print JSON summary
Expand Down
6 changes: 5 additions & 1 deletion internal/cli/completions.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,11 @@ var completionRoot = completionNode{
},
{names: []string{"daemon"}, children: leafNodes("start", "stop", "status", "run", "attach", "serve-remote", "link")},
{names: []string{"setup"}},
{names: []string{"config"}},
{names: []string{"config"}, flags: []string{"-h", "--help", "--json"}, children: []completionNode{
{names: []string{"notify"}, flags: []string{
"-h", "--help", "--mode", "--focus", "--reset", "--json",
}},
}},
{names: []string{"models"}, children: []completionNode{{names: []string{"list", "ls"}}}},
{names: []string{"providers"}, children: []completionNode{
{names: []string{"current"}}, {names: []string{"list"}}, {names: []string{"catalog"}},
Expand Down
5 changes: 5 additions & 0 deletions internal/cli/completions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,11 @@ func TestCompletionTreeCoversAliasesNestingAndCommonFlags(t *testing.T) {
assertCandidates(t, byPath["completions"], "bash", "zsh", "fish", "powershell", "elvish")
assertCandidates(t, byPath["plugins"], "list", "add", "info", "remove", "rm")
assertCandidates(t, byPath["plugin"], "list", "add", "info", "remove", "rm")
// `config` gained the notify subcommand; the completion tree must expose
// it (and its flags) so shell completion cannot go stale for new CLI
// surfaces (maintainer review, PR #1001).
assertCandidates(t, byPath["config"], "notify", "--json", "--help")
assertCandidates(t, byPath["config notify"], "--mode", "--focus", "--reset", "--json", "--help")
}

func assertCandidates(t *testing.T, got []string, wants ...string) {
Expand Down
176 changes: 176 additions & 0 deletions internal/cli/config_notify.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
package cli

import (
"fmt"
"io"
"strings"

"github.com/Gitlawb/zero/internal/config"
)

// runConfigNotify implements `zero config notify`: with no flags it prints the
// stored mode/focusMode; --mode/--focus update them via the same
// config.SetNotify writer the TUI /notify command uses, so all surfaces stay
// in lockstep; --reset blanks both fields so the TUI's effective default
// applies again (an unconfigured headless run stays silent).
//
// The command manages a user preference, so it talks ONLY to the user's own
// config file (config.UserNotify / config.SetNotify) and never runs the full
// config resolution: resolving providers would fail with ErrNoActiveProvider
// for a brand-new user, locking them out of setting notifications before they
// have even configured a provider (CodeRabbit review, PR #1001). The display
// therefore reports the USER'S stored values — a project config that
// overrides notify for one repo is not shown here, by the same logic the
// maintainer applied to the write path.
func runConfigNotify(args []string, stdout io.Writer, stderr io.Writer, deps appDeps) int {
options, help, err := parseConfigNotifyArgs(args)
if err != nil {
return writeExecUsageError(stderr, err.Error())
}
if help {
if err := writeConfigNotifyHelp(stdout); err != nil {
return exitCrash
}
return exitSuccess
}

configPath, err := deps.userConfigPath()
if err != nil {
return writeAppError(stderr, err.Error(), exitCrash)
}

if options.mode != "" || options.focus != "" || options.reset {
// One serialized read-merge-write transaction: the lock covers
// reading the stored block, applying only the explicit fields, and
// replacing the file, so two concurrent partial updates (e.g.
// --mode off and --focus always from two terminals) cannot lose
// each other's change (maintainer review, PR #1001). Omitted
// fields preserve the values stored in the user's OWN file — blank
// stays blank; --reset is the only path that clears both fields.
_, err := config.UpdateNotify(configPath, func(current config.NotifyConfig) config.NotifyConfig {
if options.reset {
return config.NotifyConfig{}
}
if options.mode != "" {
current.Mode = options.mode
}
if options.focus != "" {
current.FocusMode = options.focus
}
return current
})
if err != nil {
return writeAppError(stderr, err.Error(), exitUsage)
}
}

// Report the stored values (blank renders as "(default)").
current, err := config.UserNotify(configPath)
if err != nil {
return writeAppError(stderr, err.Error(), exitUsage)
}
if options.json {
if err := writePrettyJSON(stdout, map[string]any{
"mode": current.Mode,
"focusMode": current.FocusMode,
}); err != nil {
return exitCrash
}
return exitSuccess
}
lines := []string{
"Notify",
"mode: " + displayCLIValue(current.Mode, "(default)"),
"focusMode: " + displayCLIValue(current.FocusMode, "(default)"),
}
if _, err := fmt.Fprintln(stdout, strings.Join(lines, "\n")); err != nil {
return exitCrash
}
return exitSuccess
}

type configNotifyOptions struct {
mode string
focus string
reset bool
json bool
}

func parseConfigNotifyArgs(args []string) (configNotifyOptions, bool, error) {
options := configNotifyOptions{}
for index := 0; index < len(args); index++ {
arg := args[index]
switch {
case arg == "-h" || arg == "--help" || arg == "help":
return options, true, nil
case arg == "--json":
options.json = true
case arg == "--reset":
options.reset = true
case arg == "--mode":
value, next, err := nextFlagValue(args, index, arg)
if err != nil {
return options, false, err
}
options.mode = value
index = next
case strings.HasPrefix(arg, "--mode="):
value, err := requiredInlineFlagValue(arg, "--mode")
if err != nil {
return options, false, err
}
options.mode = value
case arg == "--focus":
value, next, err := nextFlagValue(args, index, arg)
if err != nil {
return options, false, err
}
options.focus = value
index = next
case strings.HasPrefix(arg, "--focus="):
value, err := requiredInlineFlagValue(arg, "--focus")
if err != nil {
return options, false, err
}
options.focus = value
case strings.HasPrefix(arg, "-"):
return options, false, execUsageError{fmt.Sprintf("unknown flag %q", arg)}
default:
return options, false, execUsageError{fmt.Sprintf("unexpected argument %q", arg)}
}
}
return options, false, nil
}

func writeConfigNotifyHelp(w io.Writer) error {
_, err := fmt.Fprint(w, "Usage:\n"+
" zero config notify [flags]\n"+
"\n"+
"Print or update the stored global notification preference.\n"+
"\n"+
"The preference controls BOTH notification kinds: the turn-completion\n"+
"(\"Zero: ready\") alert and the needs-input alert. mode off silences both;\n"+
"the focus mode (unfocused, always, focused) applies to both.\n"+
"\n"+
"When run with no flag, prints the stored mode and focusMode; a field you\n"+
"never set shows as (default) — the TUI alerts with bell + notification,\n"+
"firing only when the terminal is unfocused, while an unconfigured\n"+
"headless run stays silent. Omitted flags preserve the values stored in\n"+
"YOUR config file; --reset clears both so the TUI's effective default\n"+
"applies again.\n"+
"\n"+
"Examples:\n"+
" zero config notify\n"+
" zero config notify --json\n"+
" zero config notify --mode both --focus unfocused\n"+
" zero config notify --mode off\n"+
" zero config notify --reset # clear the stored preference\n"+
"\n"+
"Flags:\n"+
" --mode <off|bell|notify|both> Notification mechanism (both kinds)\n"+
" --focus <unfocused|always|focused> When the alert fires\n"+
" --reset Clear the stored preference so the TUI effective default applies\n"+
" --json Machine-readable output\n"+
" -h, --help Show this help\n")
return err
}
Loading
Loading