diff --git a/internal/agentkit/agents/agents.go b/internal/agentkit/agents/agents.go index 5f74e59..b843508 100644 --- a/internal/agentkit/agents/agents.go +++ b/internal/agentkit/agents/agents.go @@ -2,6 +2,7 @@ package agents import ( "fmt" + "runtime" "strings" ) @@ -105,18 +106,30 @@ func (s Spec) EffortFlags(e string) []string { } // SplitCommand parses shell quoting without invoking a shell or expanding variables. +// On Windows a backslash is the path separator (C:\tools\agent.exe), so there it +// escapes only a double quote and is otherwise kept as typed. func SplitCommand(command string) ([]string, error) { + return splitCommand(command, runtime.GOOS == "windows") +} + +func splitCommand(command string, windows bool) ([]string, error) { var args []string var b strings.Builder var quote rune escaped, word := false, false - for _, r := range command { + runes := []rune(command) + for i, r := range runes { if escaped { b.WriteRune(r) escaped = false word = true continue } + if r == '\\' && windows && (i+1 == len(runes) || runes[i+1] != '"') { + b.WriteRune(r) + word = true + continue + } if r == '\\' && quote != '\'' { escaped = true word = true diff --git a/internal/agentkit/agents/agents_test.go b/internal/agentkit/agents/agents_test.go index 4f6a2ff..44e024e 100644 --- a/internal/agentkit/agents/agents_test.go +++ b/internal/agentkit/agents/agents_test.go @@ -61,3 +61,23 @@ func TestLoginArgv(t *testing.T) { } } } + +// A backslash escapes on Unix, but on Windows it is the path separator: a +// custom command's path keeps it, and only \" still escapes a quote. +func TestSplitCommandBackslashes(t *testing.T) { + for _, tc := range []struct { + in string + windows bool + want []string + }{ + {`a\ b "c d" 'e\f'`, false, []string{"a b", "c d", `e\f`}}, + {`C:\tools\agent.exe --x {prompt}`, true, []string{`C:\tools\agent.exe`, "--x", "{prompt}"}}, + {`"C:\Program Files\agent.exe" say \"hi\"`, true, []string{`C:\Program Files\agent.exe`, "say", `"hi"`}}, + {`C:\tools\`, true, []string{`C:\tools\`}}, + } { + got, err := splitCommand(tc.in, tc.windows) + if err != nil || !reflect.DeepEqual(got, tc.want) { + t.Errorf("%q (windows=%v) = %q %v, want %q", tc.in, tc.windows, got, err, tc.want) + } + } +} diff --git a/internal/agentkit/bridge/alerts_e2e_test.go b/internal/agentkit/bridge/alerts_e2e_test.go index bb9317c..a335854 100644 --- a/internal/agentkit/bridge/alerts_e2e_test.go +++ b/internal/agentkit/bridge/alerts_e2e_test.go @@ -2,8 +2,6 @@ package bridge import ( "net/http/httptest" - "os/exec" - "path/filepath" "reflect" "sync" "testing" @@ -19,12 +17,9 @@ import ( // MIA gets a clean error and stays quiet in the meeting; the owner gets one // desktop alert per kind of failure per meeting, not one per turn. func TestOneAlertPerKindPerMeeting(t *testing.T) { - if _, err := exec.LookPath("python3"); err != nil { - t.Skip("python3 is needed for the stub agent") - } const outOfCredits = "ERROR: Your workspace is out of credits. Ask your workspace owner to refill in order to continue." t.Setenv("STUB_FAIL_TEXT", outOfCredits) - stub, _ := filepath.Abs("testdata/stub_agent.py") + stub := stubAgent(t, "claude") dir := t.TempDir() var mu sync.Mutex var sent [][2]string @@ -39,8 +34,7 @@ func TestOneAlertPerKindPerMeeting(t *testing.T) { hs := httptest.NewServer(srv) t.Cleanup(func() { hs.Close(); srv.Close() }) - res := post(t, hs.URL+"/v1/session/start", token, map[string]any{"session_id": "bot1"}) - res.Body.Close() + startSession(t, hs.URL, token, map[string]any{"session_id": "bot1"}) turn := map[string]any{"session_id": "bot1", "messages": []map[string]string{{"speaker": "Nav", "text": "hi"}}} for i := 0; i < 2; i++ { _, last := readTurn(t, post(t, hs.URL+"/v1/turn", token, turn)) diff --git a/internal/agentkit/bridge/bridge.go b/internal/agentkit/bridge/bridge.go index fe33ef0..aad1816 100644 --- a/internal/agentkit/bridge/bridge.go +++ b/internal/agentkit/bridge/bridge.go @@ -83,7 +83,9 @@ func (s *Server) Start(ctx context.Context, id string, settings session.Settings if old != nil { old.Close() } - _ = newSession.Start(ctx) + if err := newSession.Start(ctx); err != nil { // the turn reports it to MIA; the terminal hears it now + s.Config.Log("[error] " + id + ": " + s.Config.Agent.Label + " did not start: " + redact.Secrets(clip(err.Error(), 200))) + } return newSession, false } @@ -333,6 +335,19 @@ func (s *Server) start(w http.ResponseWriter, r *http.Request, body map[string]a } login := s.loginPayload(true) if login["login"] == "expired" || login["login"] == "not_installed" { + // No session: MIA reads why from this reply. Say it here too, or the + // terminal shows nothing until a turn fails with "unknown session". + why := "needs sign-in" + if s.Config.Agent.Relogin != "" { + why += " (run: " + s.Config.Agent.Relogin + ")" + } + if login["login"] == "not_installed" { + why = "is not installed or cannot run" + } + if detail := parsers.Str(login["login_detail"]); detail != "" { + why += ": " + detail + } + s.Config.Log(fmt.Sprintf("[session] %s: not started: %s %s", id, s.Config.Agent.Label, why)) jsonReply(w, 200, merge(map[string]any{"agent": s.Config.Agent.Name, "warm": false}, login)) return } diff --git a/internal/agentkit/bridge/bridge_e2e_test.go b/internal/agentkit/bridge/bridge_e2e_test.go index 02fb958..1d57d2e 100644 --- a/internal/agentkit/bridge/bridge_e2e_test.go +++ b/internal/agentkit/bridge/bridge_e2e_test.go @@ -3,9 +3,9 @@ package bridge import ( "bufio" "encoding/json" + "io" "net/http" "net/http/httptest" - "os/exec" "path/filepath" "strings" "testing" @@ -14,16 +14,14 @@ import ( "github.com/meetstream-ai/cli/internal/agentkit/agents" "github.com/meetstream-ai/cli/internal/agentkit/config" "github.com/meetstream-ai/cli/internal/agentkit/pairing" + "github.com/meetstream-ai/cli/internal/testutil/fakecli" ) // End to end through the HTTP protocol (docs/protocol.md) with the kit's own // stub agent, which speaks Claude Code's stream-json and never calls a model. func newStubBridge(t *testing.T) (*httptest.Server, string) { t.Helper() - if _, err := exec.LookPath("python3"); err != nil { - t.Skip("python3 is needed for the stub agent") - } - stub, _ := filepath.Abs("testdata/stub_agent.py") + stub := stubAgent(t, "claude") dir := t.TempDir() spec := agents.All["claude"] srv := New(config.Config{Agent: spec, Binary: stub, Workdir: dir, RuntimeDir: dir, Owner: "Nav", Timeout: 20 * time.Second}) @@ -38,6 +36,26 @@ func newStubBridge(t *testing.T) (*httptest.Server, string) { return hs, token } +// stubAgent is the kit's stub agent as a program called name: Python runs the +// script, so no shebang or execute bit is needed (Windows has neither). +func stubAgent(t *testing.T, name string) string { + t.Helper() + return fakecli.Python(t, t.TempDir(), name, filepath.Join("testdata", "stub_agent.py")) +} + +// startSession starts a session and fails the test at once when the stub +// agent could not run, instead of at the turn with "unknown session". +func startSession(t *testing.T, url, token string, body map[string]any) { + t.Helper() + res := post(t, url+"/v1/session/start", token, body) + defer res.Body.Close() + var m map[string]any + _ = json.NewDecoder(res.Body).Decode(&m) + if res.StatusCode != 200 || m["login"] != "ok" { + t.Fatalf("session/start %d %v", res.StatusCode, m) + } +} + func post(t *testing.T, url, token string, body any) *http.Response { t.Helper() b, _ := json.Marshal(body) @@ -71,14 +89,17 @@ func TestBridgeTurnEndToEnd(t *testing.T) { var started map[string]any _ = json.NewDecoder(res.Body).Decode(&started) res.Body.Close() - if res.StatusCode != 200 || started["agent"] != "claude" { + // login "ok": the stub agent really ran (a CLI that cannot start is + // "not_installed", and then no session exists for the turn). + if res.StatusCode != 200 || started["agent"] != "claude" || started["login"] != "ok" { t.Fatalf("session/start %d %v", res.StatusCode, started) } res = post(t, hs.URL+"/v1/turn", token, map[string]any{"session_id": "bot_1", "messages": []map[string]string{{"speaker": "Nav", "text": "what is the answer?"}}}) defer res.Body.Close() if ct := res.Header.Get("Content-Type"); !strings.HasPrefix(ct, "application/x-ndjson") { - t.Fatalf("content-type %q", ct) + b, _ := io.ReadAll(res.Body) + t.Fatalf("content-type %q: %d %s", ct, res.StatusCode, b) } var text strings.Builder var done map[string]any @@ -145,8 +166,7 @@ func readTurn(t *testing.T, res *http.Response) (text string, last map[string]an func TestBridgeCancelThenNextTurn(t *testing.T) { t.Setenv("STUB_FIRST_S", "5") // the first answer token takes 5 s hs, token := newStubBridge(t) - res := post(t, hs.URL+"/v1/session/start", token, map[string]any{"session_id": "bot_2"}) - res.Body.Close() + startSession(t, hs.URL, token, map[string]any{"session_id": "bot_2"}) got := make(chan map[string]any, 1) go func() { @@ -156,7 +176,7 @@ func TestBridgeCancelThenNextTurn(t *testing.T) { }() time.Sleep(700 * time.Millisecond) start := time.Now() - res = post(t, hs.URL+"/v1/cancel", token, map[string]any{"session_id": "bot_2"}) + res := post(t, hs.URL+"/v1/cancel", token, map[string]any{"session_id": "bot_2"}) res.Body.Close() select { case last := <-got: diff --git a/internal/agentkit/bridge/start_fail_test.go b/internal/agentkit/bridge/start_fail_test.go new file mode 100644 index 0000000..1db324b --- /dev/null +++ b/internal/agentkit/bridge/start_fail_test.go @@ -0,0 +1,68 @@ +package bridge + +import ( + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/meetstream-ai/cli/internal/agentkit/agents" + "github.com/meetstream-ai/cli/internal/agentkit/config" +) + +// An agent CLI that cannot start fails the turn at once with that reason; it +// used to look like a slow agent until the turn timed out. +func TestOneShotAgentThatCannotStartFailsTheTurnAtOnce(t *testing.T) { + missing := filepath.Join(t.TempDir(), "no-such-agent") + spec, err := agents.Custom("'" + missing + "' {prompt}") + if err != nil { + t.Fatal(err) + } + dir := t.TempDir() + srv := New(config.Config{Agent: spec, Binary: missing, Workdir: dir, RuntimeDir: dir, Owner: "Nav", Timeout: 30 * time.Second}) + srv.SetInternalToken("tok") + hs := httptest.NewServer(srv) + t.Cleanup(func() { hs.Close(); srv.Close() }) + + res := post(t, hs.URL+"/v1/session/start", "tok", map[string]any{"session_id": "bot_x"}) // a custom CLI has no login check: "unknown" + res.Body.Close() + if res.StatusCode != 200 || srv.Session("bot_x") == nil { + t.Fatalf("session/start %d", res.StatusCode) + } + start := time.Now() + _, last := readTurn(t, post(t, hs.URL+"/v1/turn", "tok", map[string]any{"session_id": "bot_x", "messages": []map[string]string{{"speaker": "Nav", "text": "hi"}}})) + if last["type"] != "error" || !strings.Contains(last["message"].(string), "could not be started") { + t.Fatalf("last event %v", last) + } + if took := time.Since(start); took > 10*time.Second { + t.Fatalf("took %s: waited for the timeout", took) + } +} + +// A start refused because the CLI is missing leaves no session; the terminal +// says why at once instead of only "unknown session" at the next turn. +func TestRefusedStartIsLogged(t *testing.T) { + var mu sync.Mutex + var lines []string + dir := t.TempDir() + srv := New(config.Config{Agent: agents.All["claude"], Binary: filepath.Join(dir, "missing-claude"), Workdir: dir, RuntimeDir: dir, Owner: "Nav", + Log: func(l string) { mu.Lock(); lines = append(lines, l); mu.Unlock() }}) + srv.SetInternalToken("tok") + defer srv.Close() + r := httptest.NewRequest(http.MethodPost, "/v1/session/start", strings.NewReader(`{"session_id":"s1"}`)) + r.Header.Set("Authorization", "Bearer tok") + rec := httptest.NewRecorder() + srv.ServeHTTP(rec, r) + if rec.Code != 200 || !strings.Contains(rec.Body.String(), `"login":"not_installed"`) || srv.Session("s1") != nil { + t.Fatalf("%d %s", rec.Code, rec.Body) + } + mu.Lock() + got := strings.Join(lines, "\n") + mu.Unlock() + if !strings.Contains(got, "[session] s1: not started: Claude Code is not installed or cannot run") { + t.Fatalf("log:\n%s", got) + } +} diff --git a/internal/agentkit/checks/checks.go b/internal/agentkit/checks/checks.go index 84f4da5..2ba76db 100644 --- a/internal/agentkit/checks/checks.go +++ b/internal/agentkit/checks/checks.go @@ -197,13 +197,23 @@ func Binary(e Env, spec agents.Spec, override string) Check { } return Check{"agent", Fail, fmt.Sprintf("%s not found (%s)", spec.Label, shown), spec.InstallHint} case offPath: - dir := filepath.Dir(path) - return Check{"agent", Warn, fmt.Sprintf("%s: %s (its folder is not on your PATH)", spec.Label, path), - fmt.Sprintf(`Add it to your shell profile: export PATH="%s:$PATH"`, dir)} + lead, command := PathHint(filepath.Dir(path), e.windows()) + return Check{"agent", Warn, fmt.Sprintf("%s: %s (its folder is not on your PATH)", spec.Label, path), lead + " " + command} } return Check{"agent", OK, spec.Label + ": " + path, ""} } +// PathHint is how to put dir on PATH for good: an export line for the shell +// profile, or on Windows (no export, no profile) a PowerShell line that adds +// it to the user's Path. +func PathHint(dir string, windows bool) (lead, command string) { + if windows { + return "Add it to your PATH (in PowerShell, then open a new terminal):", + `[Environment]::SetEnvironmentVariable("Path", "` + dir + `;" + [Environment]::GetEnvironmentVariable("Path", "User"), "User")` + } + return "Add it to your shell profile:", `export PATH="` + dir + `:$PATH"` +} + // MuseApp: Muse's launcher without the app it downloads. ok is false for every // other agent (no check to show). func MuseApp(spec agents.Spec, binary string) (Check, bool) { @@ -256,7 +266,7 @@ func Home(e Env, home string) Check { func Port(e Env, port int) Check { ln, err := e.Listen("tcp4", fmt.Sprintf("127.0.0.1:%d", port)) if err != nil { - if errors.Is(err, syscall.EADDRINUSE) { + if addrInUse(err) { return Check{"port", Fail, fmt.Sprintf("port %d is used by another program (maybe a bridge already running)", port), fmt.Sprintf("Start the bridge with another --port, or free port %d.", port)} } @@ -266,6 +276,16 @@ func Port(e Env, port int) Check { return Check{"port", OK, fmt.Sprintf("127.0.0.1:%d is free", port), ""} } +// wsaeaddrinuse is Windows' "Only one usage of each socket address …" +// (WSAEADDRINUSE). syscall.EADDRINUSE there is Go's own number, which no +// Windows call returns. +const wsaeaddrinuse syscall.Errno = 10048 + +func addrInUse(err error) bool { + var errno syscall.Errno + return errors.Is(err, syscall.EADDRINUSE) || (runtime.GOOS == "windows" && errors.As(err, &errno) && errno == wsaeaddrinuse) +} + // Login turns the login package's status (State, Detail) into a check. // "unknown" (a CLI with no sign-in check) is a warning: the first turn will tell. func Login(spec agents.Spec, state, detail string) Check { diff --git a/internal/agentkit/checks/checks_pathext_test.go b/internal/agentkit/checks/checks_pathext_test.go index 19c3c70..a2f1f7c 100644 --- a/internal/agentkit/checks/checks_pathext_test.go +++ b/internal/agentkit/checks/checks_pathext_test.go @@ -3,6 +3,7 @@ package checks import ( "os" "path/filepath" + "strings" "testing" "github.com/meetstream-ai/cli/internal/agentkit/agents" @@ -38,6 +39,10 @@ func TestWindowsExecutablesByPathExt(t *testing.T) { if p, off := ResolveBinary(e, claude, ""); p != cmd || !off { t.Fatalf("install folder: %q %v", p, off) } + // No export or shell profile on Windows: a PowerShell line for the user's Path. + if c := Binary(e, claude, ""); !strings.Contains(c.Hint, `SetEnvironmentVariable("Path", "`+dir+`;"`) || strings.Contains(c.Hint, "export") { + t.Fatalf("hint %q", c.Hint) + } e.GOOS = "linux" // the same file without an execute bit is not a program there if p, _ := ResolveBinary(e, claude, cmd); p != "" { t.Fatal("unix needs the execute bit") diff --git a/internal/agentkit/checks/checks_test.go b/internal/agentkit/checks/checks_test.go index 1c2832f..f9639e0 100644 --- a/internal/agentkit/checks/checks_test.go +++ b/internal/agentkit/checks/checks_test.go @@ -5,22 +5,20 @@ import ( "os" "os/exec" "path/filepath" + "runtime" "strings" "testing" "github.com/meetstream-ai/cli/internal/agentkit/agents" "github.com/meetstream-ai/cli/internal/agentkit/meetingctx" "github.com/meetstream-ai/cli/internal/agentkit/warmcheck" + "github.com/meetstream-ai/cli/internal/testutil/fakecli" ) +// exe puts a program called name in dir (name.exe on Windows) and returns its path. func exe(t *testing.T, dir, name string) string { t.Helper() - _ = os.MkdirAll(dir, 0o755) - p := filepath.Join(dir, name) - if err := os.WriteFile(p, []byte("#!/bin/sh\n"), 0o755); err != nil { - t.Fatal(err) - } - return p + return fakecli.Program(t, dir, name) } // env with an empty PATH and the given install folders. @@ -49,7 +47,11 @@ func TestResolveBinaryFindsAnOffPathInstall(t *testing.T) { t.Fatalf("p=%q off=%v", p, off) } c := Binary(e, claude, "") - if c.Status != Warn || !strings.Contains(c.Hint, `export PATH="`+local+`:$PATH"`) { + wantHint := `export PATH="` + local + `:$PATH"` + if runtime.GOOS == "windows" { + wantHint = `[Environment]::SetEnvironmentVariable("Path", "` + local + `;"` + } + if c.Status != Warn || !strings.Contains(c.Hint, wantHint) { t.Fatalf("%+v", c) } e.LookPath = func(string) (string, error) { return "/usr/bin/claude", nil } diff --git a/internal/agentkit/drivers/process.go b/internal/agentkit/drivers/process.go index f7a4260..6edb84a 100644 --- a/internal/agentkit/drivers/process.go +++ b/internal/agentkit/drivers/process.go @@ -227,7 +227,10 @@ func RunOnce(ctx context.Context, c config.Config, prompt, access, model string, argv, input := OneShotArgs(c.Agent, c.Binary, prompt, access, model, c.Effort, c.IgnoreRules) p, spawnMS, err := spawn(argv, c.Workdir, Env(c, model, "")) if err != nil { + // "end" too: the turn waits for it, and without it a CLI that + // cannot start looked like a slow one until the turn timed out. emit(Event{Kind: "error", Text: err.Error()}) + emit(Event{Kind: "end"}) return 0 } defer p.close() diff --git a/internal/agentkit/estimates/estimates_test.go b/internal/agentkit/estimates/estimates_test.go index 2cc210c..b9e5efe 100644 --- a/internal/agentkit/estimates/estimates_test.go +++ b/internal/agentkit/estimates/estimates_test.go @@ -8,6 +8,7 @@ import ( "math" "os" "path/filepath" + "runtime" "strings" "sync" "testing" @@ -233,7 +234,8 @@ func TestCacheRoundTripAndDefaultKey(t *testing.T) { t.Fatal(err) } path := filepath.Join(kit, UsageFile) - if info, _ := os.Stat(path); info.Mode().Perm() != 0o600 { + // 0600 is a Unix mode; Windows reports 0666 for any writable file (its ACLs keep the profile private). + if info, _ := os.Stat(path); runtime.GOOS != "windows" && info.Mode().Perm() != 0o600 { t.Fatalf("mode %v", info.Mode().Perm()) } raw := readJSONf(t, path).(map[string]any)["claude:"].(map[string]any) @@ -246,7 +248,7 @@ func TestCacheRoundTripAndDefaultKey(t *testing.T) { } _ = os.Chmod(path, 0o644) _ = Save("hermes", "provider:model", m) - if info, _ := os.Stat(path); info.Mode().Perm() != 0o600 { + if info, _ := os.Stat(path); runtime.GOOS != "windows" && info.Mode().Perm() != 0o600 { t.Fatalf("mode after resave %v", info.Mode().Perm()) } if again := Load("claude")[""]; again.MeasuredAt != loaded.MeasuredAt { diff --git a/internal/agentkit/muse/muse.go b/internal/agentkit/muse/muse.go index 02f790f..3824a51 100644 --- a/internal/agentkit/muse/muse.go +++ b/internal/agentkit/muse/muse.go @@ -11,6 +11,7 @@ import ( "os/exec" "path/filepath" "regexp" + "runtime" "strings" ) @@ -47,8 +48,23 @@ func LauncherWithoutApp(agentName, binary string) bool { if !versionPattern.MatchString(version) { return true } - fi, err := os.Stat(filepath.Join(folder, "muse-bin-"+version)) - return err != nil || !fi.Mode().IsRegular() || fi.Mode().Perm()&0o111 == 0 + return !appPresent(filepath.Join(folder, "muse-bin-"+version)) +} + +// appPresent: the downloaded app is a regular file with an execute bit. Windows +// has no execute bits (Go reports none), so there the file itself, with or +// without .exe, is the app. +func appPresent(app string) bool { + if runtime.GOOS == "windows" { + for _, p := range []string{app, app + ".exe"} { + if fi, err := os.Stat(p); err == nil && fi.Mode().IsRegular() { + return true + } + } + return false + } + fi, err := os.Stat(app) + return err == nil && fi.Mode().IsRegular() && fi.Mode().Perm()&0o111 != 0 } // Command is a program to run without a shell: Argv plus extra environment diff --git a/internal/agentkit/muse/muse_test.go b/internal/agentkit/muse/muse_test.go index 999ba23..893ec9a 100644 --- a/internal/agentkit/muse/muse_test.go +++ b/internal/agentkit/muse/muse_test.go @@ -4,6 +4,7 @@ import ( "os" "path/filepath" "reflect" + "runtime" "strings" "testing" ) @@ -56,6 +57,9 @@ func TestTheAppBesideTheLauncherDecides(t *testing.T) { } func TestANonExecutableAppIsNotInstalled(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("execute bits are Unix-only: on Windows the app file itself is the app") + } l := launcher(t, t.TempDir()) download(t, l) _ = os.Chmod(filepath.Join(filepath.Dir(l), "muse-bin-"+version), 0o644) @@ -64,6 +68,22 @@ func TestANonExecutableAppIsNotInstalled(t *testing.T) { } } +// Windows: no execute bits, and the app may carry .exe. +func TestWindowsAppWithExeIsInstalled(t *testing.T) { + if runtime.GOOS != "windows" { + t.Skip("Windows file naming") + } + l := launcher(t, t.TempDir()) + dir := filepath.Dir(l) + _ = os.WriteFile(filepath.Join(dir, ".muse-version"), []byte(version), 0o644) + if err := os.WriteFile(filepath.Join(dir, "muse-bin-"+version+".exe"), []byte("MZ"), 0o644); err != nil { + t.Fatal(err) + } + if LauncherWithoutApp("muse", l) { + t.Fatal("muse-bin-.exe not counted as the app") + } +} + func TestASymlinkedLauncherIsFollowed(t *testing.T) { dir := t.TempDir() l := launcher(t, dir) diff --git a/internal/agentkit/relay/relay_e2e_test.go b/internal/agentkit/relay/relay_e2e_test.go index d134b64..f4e1d27 100644 --- a/internal/agentkit/relay/relay_e2e_test.go +++ b/internal/agentkit/relay/relay_e2e_test.go @@ -6,7 +6,6 @@ import ( "errors" "net/http" "net/http/httptest" - "os/exec" "path/filepath" "strings" "sync/atomic" @@ -19,6 +18,7 @@ import ( "github.com/meetstream-ai/cli/internal/agentkit/bridge" "github.com/meetstream-ai/cli/internal/agentkit/config" "github.com/meetstream-ai/cli/internal/agentkit/relay" + "github.com/meetstream-ai/cli/internal/testutil/fakecli" ) type frame = map[string]any @@ -36,6 +36,11 @@ func readFrame(t *testing.T, ctx context.Context, c *websocket.Conn) frame { return f } +func parsedBody(f frame) map[string]any { + b, _ := f["body"].(map[string]any) + return b +} + func writeFrame(t *testing.T, ctx context.Context, c *websocket.Conn, f frame) { t.Helper() f["v"] = 1 @@ -48,10 +53,7 @@ func writeFrame(t *testing.T, ctx context.Context, c *websocket.Conn, f frame) { // A fake relay drives the real bridge (with the kit's stub agent) through // the client, as MIA would through the real relay (PROTOCOL.md §2). func TestRelayEndToEnd(t *testing.T) { - if _, err := exec.LookPath("python3"); err != nil { - t.Skip("python3 is needed for the stub agent") - } - stub, _ := filepath.Abs("../bridge/testdata/stub_agent.py") + stub := fakecli.Python(t, t.TempDir(), "claude", filepath.Join("..", "bridge", "testdata", "stub_agent.py")) dir := t.TempDir() br := bridge.New(config.Config{Agent: agents.All["claude"], Binary: stub, Workdir: dir, RuntimeDir: dir, Owner: "Nav", Timeout: 20 * time.Second}) t.Cleanup(br.Close) @@ -90,7 +92,8 @@ func TestRelayEndToEnd(t *testing.T) { } // Session, then a streamed turn. writeFrame(t, ctx, c, frame{"t": "req", "s": 3, "method": "POST", "path": "/v1/session/start", "body": map[string]any{"session_id": "bot_r"}}) - if res := readFrame(t, ctx, c); res["status"] != 200.0 { + // login "ok": the stub agent ran, so the turn below has a session. + if res := readFrame(t, ctx, c); res["status"] != 200.0 || parsedBody(res)["login"] != "ok" { t.Errorf("session/start %v", res) } writeFrame(t, ctx, c, frame{"t": "req", "s": 4, "method": "POST", "path": "/v1/turn", diff --git a/internal/agentkit/warmcheck/warmcheck_test.go b/internal/agentkit/warmcheck/warmcheck_test.go index 4d27192..7ad5754 100644 --- a/internal/agentkit/warmcheck/warmcheck_test.go +++ b/internal/agentkit/warmcheck/warmcheck_test.go @@ -4,7 +4,6 @@ import ( "context" "errors" "os" - "os/exec" "path/filepath" "strings" "testing" @@ -13,6 +12,7 @@ import ( "github.com/meetstream-ai/cli/internal/agentkit/agents" "github.com/meetstream-ai/cli/internal/agentkit/bridge" "github.com/meetstream-ai/cli/internal/agentkit/config" + "github.com/meetstream-ai/cli/internal/testutil/fakecli" ) // The ACP driver starts the meeting-tools shim as ` agent mcp-stdio @@ -31,11 +31,8 @@ func TestMain(m *testing.M) { // stubConfig runs the kit's stub agent (no model, no network) as agent name. func stubConfig(t *testing.T, name string) config.Config { t.Helper() - if _, err := exec.LookPath("python3"); err != nil { - t.Skip("python3 is needed for the stub agent") - } - stub, _ := filepath.Abs("../bridge/testdata/stub_agent.py") dir := t.TempDir() + stub := fakecli.Python(t, dir, name, filepath.Join("..", "bridge", "testdata", "stub_agent.py")) return config.Config{Agent: agents.All[name], Binary: stub, Workdir: dir, RuntimeDir: dir, Owner: "Nav", Timeout: 30 * time.Second} } diff --git a/internal/cli/agent_cmd.go b/internal/cli/agent_cmd.go index f2c0d92..1272c70 100644 --- a/internal/cli/agent_cmd.go +++ b/internal/cli/agent_cmd.go @@ -121,10 +121,7 @@ func newAgentServeCmd(info BuildInfo) *cobra.Command { f.StringVar(&o.command, "command", "", "custom command; {prompt} is replaced, otherwise stdin") f.StringVar(&o.binary, "binary", "", "path to the agent CLI") f.StringVar(&o.workdir, "workdir", cwd, "folder the agent works in") - owner := os.Getenv("USER") - if owner == "" { - owner = "the user" - } + owner := setupOwner() f.StringVar(&o.owner, "owner", owner, "your name as MIA hears it") f.Float64Var(&o.timeout, "timeout", 60, "stop a turn after this many seconds with no output") f.StringVar(&o.model, "model", "", "agent model (MIA can override)") diff --git a/internal/cli/agent_setup_cmd.go b/internal/cli/agent_setup_cmd.go index c113f34..fd3c369 100644 --- a/internal/cli/agent_setup_cmd.go +++ b/internal/cli/agent_setup_cmd.go @@ -11,6 +11,7 @@ import ( "os/exec" "path/filepath" "regexp" + "runtime" "sort" "strings" @@ -74,8 +75,9 @@ func pathHint(c agentChoice) { return } dir := filepath.Dir(c.binary) - ui.Warn("`" + filepath.Base(c.binary) + "` is in " + ui.ShortPath(dir) + ", which is not on your PATH. Add it to your shell profile:") - ui.Command(`export PATH="` + dir + `:$PATH"`) + lead, command := checks.PathHint(dir, runtime.GOOS == "windows") + ui.Warn("`" + filepath.Base(c.binary) + "` is in " + ui.ShortPath(dir) + ", which is not on your PATH. " + lead) + ui.Command(command) } // ── picker ──────────────────────────────────────────────────────────────────── @@ -318,12 +320,21 @@ func museSay(kind, text string) { } func setupOwner() string { - if u := os.Getenv("USER"); u != "" { + if u := loginName(); u != "" { return u } return "the user" } +// loginName is this computer's user name: $USER, or on Windows (which sets +// no USER) %USERNAME%. +func loginName() string { + if u := os.Getenv("USER"); u != "" { + return u + } + return os.Getenv("USERNAME") +} + // stepModel is step 2: the model and effort. --model/--effort (or a run that // cannot ask) skip the menu; "" is the CLI's own default. func (w *setupWizard) stepModel() (bool, menuResult, error) { diff --git a/internal/cli/agent_setup_flow_test.go b/internal/cli/agent_setup_flow_test.go index 8407a16..6f55e53 100644 --- a/internal/cli/agent_setup_flow_test.go +++ b/internal/cli/agent_setup_flow_test.go @@ -27,6 +27,7 @@ import ( "github.com/meetstream-ai/cli/internal/agentkit/models" "github.com/meetstream-ai/cli/internal/agentkit/usage" "github.com/meetstream-ai/cli/internal/agentkit/warmcheck" + "github.com/meetstream-ai/cli/internal/testutil/fakecli" "github.com/meetstream-ai/cli/internal/ui" ) @@ -210,7 +211,7 @@ func TestEveryStepGoesBackWithoutCrashing(t *testing.T) { t.Fatalf("created %+v", created) } for _, want := range []string{"1/11", "2/11", "7/11", "11/11", "2 models from test", "Model: m1", "isn't available on this server yet", "meetstream calendar connect", - "Created ~/MeetStream Agent", "Meeting context: meeting only", "edit with: meetstream agent context edit", "Access: Meeting only", + filepath.FromSlash("Created ~/MeetStream Agent"), "Meeting context: meeting only", "edit with: meetstream agent context edit", "Access: Meeting only", "Woke Antigravity CLI", "First words", "Answered", "Antigravity CLI answered in 1.2 s: ready", "Warm mode (ACP) ready · meeting tools work (test tool called) (", "warm session per meeting"} { if !strings.Contains(out, want) { @@ -239,7 +240,8 @@ func withStderr(t *testing.T, f func()) string { } old := os.Stderr os.Stderr = file - defer func() { os.Stderr = old }() + // Closed even when f stops the test (t.Fatal): Windows cannot remove an open file. + defer func() { os.Stderr = old; _ = file.Close() }() f() _ = file.Close() b, _ := os.ReadFile(file.Name()) @@ -260,6 +262,7 @@ func keysFor(t *testing.T, script ...[]string) func(tea.Model) (tea.Model, error } func testWizard() *setupWizard { + g = globals{} // an earlier run's --json must not silence this wizard's output c := &cobra.Command{} c.SetContext(context.Background()) return &setupWizard{cmd: c} @@ -329,7 +332,7 @@ func TestAutoOnlyShortcutIsOnlyForAuto(t *testing.T) { // test_measure_live_is_not_offered_when_the_cli_cannot_report_usage, and the // cost columns of the rows. func TestModelMenuRows(t *testing.T) { - t.Setenv("HOME", t.TempDir()) + setHome(t, t.TempDir()) menu, _, _ := modelMenu(agents.All["copilot"], twoModels(), "", nil) v := menu.View() if strings.Contains(v, measureLabel) || !strings.Contains(v, "usage n/a") || !strings.Contains(v, "plan") { @@ -357,7 +360,7 @@ func estimatesUsage(in, out int64) usage.Usage { return usage.Usage{Input: in, O func TestMeasureLiveRunsTickedModels(t *testing.T) { out := captureUI(t) t.Setenv("MEETSTREAM_AGENT_KIT_HOME", t.TempDir()) - t.Setenv("HOME", t.TempDir()) + setHome(t, t.TempDir()) setupFakes(t, twoModels()) swap(t, &benchExec, fakeClaudeExec(nil)) swap(t, &runBenchLive, func(ctx context.Context, q *bench.Queue) ([]bench.Job, bool) { return q.Run(ctx), false }) @@ -431,23 +434,18 @@ func TestSetupNonInteractiveModelAndEffort(t *testing.T) { // export line, and its path is what serve uses. func TestDetectFindsAgentOffPath(t *testing.T) { home := t.TempDir() - t.Setenv("HOME", home) + setHome(t, home) swap(t, &systemInstallDirs, nil) t.Setenv("PATH", t.TempDir()) local := filepath.Join(home, ".local", "bin") - if err := os.MkdirAll(local, 0o755); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(local, "claude"), []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil { - t.Fatal(err) - } + installed := fakecli.Program(t, local, "claude") var claude agentChoice for _, c := range detectAgents() { if c.name == "claude" { claude = c } } - if !claude.installed || !claude.offPath || claude.binary != filepath.Join(local, "claude") { + if !claude.installed || !claude.offPath || claude.binary != installed { t.Fatalf("%+v", claude) } if v := (pickModel{items: []agentChoice{claude}}).View(); !strings.Contains(v, "not on PATH") { @@ -456,11 +454,11 @@ func TestDetectFindsAgentOffPath(t *testing.T) { out := captureUI(t) g = globals{} pathHint(claude) - if !strings.Contains(out.String(), `export PATH="`+local+`:$PATH"`) { + if !strings.Contains(out.String(), wantPathHint(local)) { t.Fatal(out.String()) } c, err := agentServeOptions{agent: "claude", workdir: t.TempDir(), maxAccess: "readonly", timeout: 60}.build() - if err != nil || c.Binary != filepath.Join(local, "claude") { + if err != nil || c.Binary != installed { t.Fatalf("%v %v", c.Binary, err) } } @@ -552,7 +550,7 @@ func TestSetupModelView(t *testing.T) { lipgloss.SetColorProfile(termenv.TrueColor) } home := t.TempDir() - t.Setenv("HOME", home) + setHome(t, home) t.Setenv("MEETSTREAM_AGENT_KIT_HOME", t.TempDir()) _ = os.WriteFile(filepath.Join(home, ".claude.json"), []byte(`{"oauthAccount":{}}`), 0o600) // signed in on a plan listed := models.Catalog{Models: []models.Choice{{ID: "sonnet"}, {ID: "opus"}, {ID: "haiku"}, {ID: "fable"}}, diff --git a/internal/cli/agent_setup_local.go b/internal/cli/agent_setup_local.go index 1eccc5b..04017ad 100644 --- a/internal/cli/agent_setup_local.go +++ b/internal/cli/agent_setup_local.go @@ -356,7 +356,7 @@ func (w *setupWizard) stepAccess() (bool, menuResult, error) { func (w *setupWizard) stepName() (bool, menuResult, error) { w.step("Your name") if w.owner == "" { - w.owner = os.Getenv("USER") + w.owner = loginName() } asked := false if w.interactive && !w.ownerFlag { diff --git a/internal/cli/agent_setup_local_test.go b/internal/cli/agent_setup_local_test.go index 6127eeb..3e8bc72 100644 --- a/internal/cli/agent_setup_local_test.go +++ b/internal/cli/agent_setup_local_test.go @@ -26,6 +26,7 @@ import ( "github.com/meetstream-ai/cli/internal/agentkit/meetingctx" "github.com/meetstream-ai/cli/internal/agentkit/relay" "github.com/meetstream-ai/cli/internal/agentkit/warmcheck" + "github.com/meetstream-ai/cli/internal/testutil/fakecli" ) // localWizard is a wizard on the local-agent path with spec chosen. @@ -589,14 +590,15 @@ func TestRelayUnsupportedServer(t *testing.T) { // A bridge with a stand-in agent (echo, one run per turn): a session, the // activation code claimed and released, and a turn print the kit's lines. func TestServeLogLinesFromBridge(t *testing.T) { - spec, err := agents.Custom("/bin/echo ready") + echo := fakecli.Echo(t, t.TempDir(), "echo") + spec, err := agents.Custom("'" + echo + "' ready") if err != nil { t.Fatal(err) } var mu sync.Mutex var lines, events []string code := "" - c := kitconfig.Config{Agent: spec, Binary: "/bin/echo", Workdir: t.TempDir(), RuntimeDir: t.TempDir(), + c := kitconfig.Config{Agent: spec, Binary: echo, Workdir: t.TempDir(), RuntimeDir: t.TempDir(), Log: func(l string) { mu.Lock(); lines = append(lines, l); mu.Unlock() }, Event: func(kind string, f map[string]any) { mu.Lock(); events = append(events, kind); mu.Unlock() }, Notify: func(title, text string) { code = regexp.MustCompile(`^\d{6}`).FindString(text) }, @@ -619,7 +621,7 @@ func TestServeLogLinesFromBridge(t *testing.T) { got := strings.Join(lines, "\n") mu.Unlock() for _, want := range []string{ - "[session] s1: started (/bin/echo, one run per turn, 1 meeting tools, access readonly", + "[session] s1: started (" + echo + ", one run per turn, 1 meeting tools, access readonly", "[activate] s1: activated for Nav", "[turn] Sam: Agent, are we on track?", "[done] first output ", diff --git a/internal/cli/agent_setup_wizard.go b/internal/cli/agent_setup_wizard.go index afbbd63..d9d72d1 100644 --- a/internal/cli/agent_setup_wizard.go +++ b/internal/cli/agent_setup_wizard.go @@ -15,6 +15,7 @@ import ( "github.com/charmbracelet/lipgloss" "github.com/meetstream-ai/cli/internal/agentkit/agents" + "github.com/meetstream-ai/cli/internal/agentkit/checks" "github.com/meetstream-ai/cli/internal/ui" ) @@ -389,15 +390,13 @@ func installDirs() []string { return append(dirs, systemInstallDirs...) } -// installedOffPath finds a CLI an installer put in a folder that is not on PATH. +// installedOffPath finds a CLI an installer put in a folder that is not on PATH +// (an execute bit, or on Windows a PATHEXT name such as claude.cmd). func installedOffPath(binary string) string { - for _, dir := range installDirs() { - p := filepath.Join(dir, binary) - if fi, err := os.Stat(p); err == nil && fi.Mode().IsRegular() && fi.Mode().Perm()&0o111 != 0 { - return p - } - } - return "" + e := agentEnv() + e.LookPath = func(string) (string, error) { return "", exec.ErrNotFound } // only the install folders + p, _ := checks.ResolveBinary(e, agents.Spec{Binary: binary}, "") + return p } // installer runs the offer; its fields are swapped in tests so nothing is installed. @@ -449,8 +448,9 @@ func (in installer) offer(spec agents.Spec) string { } dir := filepath.Dir(off) _ = os.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) - ui.Warn("`" + spec.Binary + "` is in " + ui.ShortPath(dir) + ", which is not on your PATH. Add it to your shell profile:") - ui.Command(`export PATH="` + dir + `:$PATH"`) + lead, command := checks.PathHint(dir, runtime.GOOS == "windows") + ui.Warn("`" + spec.Binary + "` is in " + ui.ShortPath(dir) + ", which is not on your PATH. " + lead) + ui.Command(command) found = off } ui.OK(spec.Label + " installed: " + ui.ShortPath(found)) diff --git a/internal/cli/agent_setup_wizard_test.go b/internal/cli/agent_setup_wizard_test.go index 0c965dc..d9cf983 100644 --- a/internal/cli/agent_setup_wizard_test.go +++ b/internal/cli/agent_setup_wizard_test.go @@ -5,12 +5,14 @@ import ( "errors" "os" "path/filepath" + "runtime" "strings" "testing" tea "github.com/charmbracelet/bubbletea" "github.com/meetstream-ai/cli/internal/agentkit/agents" + "github.com/meetstream-ai/cli/internal/testutil/fakecli" "github.com/meetstream-ai/cli/internal/ui" ) @@ -87,29 +89,45 @@ func TestSetupMissingAgentNonInteractiveHintsAndExits2(t *testing.T) { // installed on the test machine (~/.local/bin, Homebrew) is never found. func isolateAgentLookup(t *testing.T) { t.Helper() - if os.Getenv("HOME") == "" || !strings.HasPrefix(os.Getenv("HOME"), os.TempDir()) { - t.Setenv("HOME", t.TempDir()) + if home, _ := os.UserHomeDir(); home == "" || !strings.HasPrefix(home, os.TempDir()) { + setHome(t, t.TempDir()) } old := systemInstallDirs systemInstallDirs = nil t.Cleanup(func() { systemInstallDirs = old }) } -// fakeBin writes executable stubs into a fresh folder. +// setHome makes dir the user's home for this test: HOME, and USERPROFILE, +// which is what os.UserHomeDir reads on Windows. +func setHome(t *testing.T, dir string) { + t.Helper() + t.Setenv("HOME", dir) + t.Setenv("USERPROFILE", dir) +} + +// fakeBin writes stand-in programs (exit 0, no output) into a fresh folder: +// claude, or claude.exe on Windows, so PATH lookups find them everywhere. func fakeBin(t *testing.T, names ...string) string { t.Helper() dir := t.TempDir() for _, n := range names { - if err := os.WriteFile(filepath.Join(dir, n), []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil { - t.Fatal(err) - } + fakecli.Program(t, dir, n) } return dir } +// wantPathHint is the start of the line that puts dir on PATH: an export for +// the shell profile, or on Windows a PowerShell line for the user's Path. +func wantPathHint(dir string) string { + if runtime.GOOS == "windows" { + return `[Environment]::SetEnvironmentVariable("Path", "` + dir + `;"` + } + return `export PATH="` + dir + `:$PATH"` +} + func withInstallDirs(t *testing.T, home string) { t.Helper() - t.Setenv("HOME", home) + setHome(t, home) old := systemInstallDirs systemInstallDirs = nil t.Cleanup(func() { systemInstallDirs = old }) @@ -125,13 +143,11 @@ func TestInstallFindsMuseLauncherOffPath(t *testing.T) { var ran [][]string in := installer{in: strings.NewReader("y\nn\n"), run: func(stages [][]string) int { ran = append(ran, stages...) - dir := filepath.Join(home, ".local", "bin") - _ = os.MkdirAll(dir, 0o755) - _ = os.WriteFile(filepath.Join(dir, "muse"), []byte("#!/bin/sh\n"), 0o755) + fakecli.Program(t, filepath.Join(home, ".local", "bin"), "muse") return 0 }} got := in.offer(agents.All["muse"]) - want := filepath.Join(home, ".local", "bin", "muse") + want := filepath.Join(home, ".local", "bin", fakecli.Name("muse")) if got != want { t.Fatalf("got %q want %q\n%s", got, want, out) } @@ -139,7 +155,7 @@ func TestInstallFindsMuseLauncherOffPath(t *testing.T) { t.Fatalf("ran %v", ran) } s := out.String() - for _, w := range []string{"curl -fsSL https://dev.meta.ai/install.sh | bash", `export PATH="` + filepath.Dir(want) + `:$PATH"`, "not on your PATH", "Sign in and set it up now (muse)?"} { + for _, w := range []string{"curl -fsSL https://dev.meta.ai/install.sh | bash", wantPathHint(filepath.Dir(want)), "not on your PATH", "Sign in and set it up now (muse)?"} { if !strings.Contains(s, w) { t.Errorf("missing %q in\n%s", w, s) } diff --git a/internal/cli/cli_test.go b/internal/cli/cli_test.go index 35826d0..1c15da6 100644 --- a/internal/cli/cli_test.go +++ b/internal/cli/cli_test.go @@ -8,6 +8,7 @@ import ( "net/http" "net/http/httptest" "os" + "runtime" "strings" "testing" @@ -28,6 +29,11 @@ func run(t *testing.T, env map[string]string, args ...string) (string, int) { r, w, _ := os.Pipe() old := os.Stdout os.Stdout = w + // Read while the command runs: a pipe holds only so much (a few KB on + // Windows), and a writer with no reader blocks forever. + var buf bytes.Buffer + read := make(chan struct{}) + go func() { _, _ = io.Copy(&buf, r); close(read) }() root := NewRoot(BuildInfo{Version: "1.2.3", Commit: "abc", Date: "today"}) root.SetArgs(args) code := 0 @@ -39,8 +45,8 @@ func run(t *testing.T, env map[string]string, args ...string) (string, int) { } w.Close() os.Stdout = old - var buf bytes.Buffer - _, _ = io.Copy(&buf, r) + <-read + r.Close() return buf.String(), code } @@ -147,7 +153,8 @@ func TestLoginWithKeyFromStdinStoresMaskedKey(t *testing.T) { if !strings.Contains(string(b), "ms_piped_key_9876") { t.Fatal("key not stored") } - if fi, _ := os.Stat(dir + "/config.json"); fi.Mode().Perm() != 0o600 { + // 0600 is a Unix mode; Windows reports 0666 for any writable file (its ACLs keep the profile private). + if fi, _ := os.Stat(dir + "/config.json"); runtime.GOOS != "windows" && fi.Mode().Perm() != 0o600 { t.Fatalf("config mode %v", fi.Mode().Perm()) } } @@ -186,11 +193,7 @@ func TestAgentSetupDryRun(t *testing.T) { if err := os.WriteFile(home+"/credentials.json", []byte(`{"device_id":"dev_test1","refresh_token":"rt","auth_url":"http://a.invalid","relay_url":"wss://r.invalid/v1/connect"}`), 0o600); err != nil { t.Fatal(err) } - bin := t.TempDir() - if err := os.WriteFile(bin+"/claude", []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil { - t.Fatal(err) - } - t.Setenv("PATH", bin) + t.Setenv("PATH", fakeBin(t, "claude")) out, code := run(t, nil, "agent", "setup", "--agent", "claude", "--access", "confirm", "--dry-run", "--json", "--no-input") var m struct { DryRun bool `json:"dry_run"` diff --git a/internal/cli/home_test.go b/internal/cli/home_test.go index b966c48..11feb91 100644 --- a/internal/cli/home_test.go +++ b/internal/cli/home_test.go @@ -4,6 +4,7 @@ import ( "context" "os" "os/exec" + "os/signal" "path/filepath" "strings" "testing" @@ -237,6 +238,25 @@ func TestHomeExecFlowComesBack(t *testing.T) { } } +// TestHelperFakeBridge is not a test: run as a child with +// MEETSTREAM_TEST_FAKE_BRIDGE=, it is TestHomeAgentToggle's bridge. It +// leaves the marker, says it connected, and runs until stopped. +func TestHelperFakeBridge(t *testing.T) { + marker := os.Getenv("MEETSTREAM_TEST_FAKE_BRIDGE") + if marker == "" { + return + } + stop := make(chan os.Signal, 1) + signal.Notify(stop, os.Interrupt) // Ctrl-C, or Ctrl-Break on Windows: what the home app sends + _ = os.WriteFile(marker, nil, 0o644) + os.Stdout.WriteString("connected to MeetStream\n") + select { + case <-stop: + case <-time.After(30 * time.Second): + } + os.Exit(0) +} + func TestHomeAgentToggle(t *testing.T) { m := homeFor(t, nil) if err := (kitconfig.Setup{Agent: "claude", Workdir: t.TempDir(), Tunnel: "relay"}).Save(""); err != nil { @@ -244,8 +264,10 @@ func TestHomeAgentToggle(t *testing.T) { } marker := filepath.Join(t.TempDir(), "ran") old := homeAgentCommand - homeAgentCommand = func() *exec.Cmd { - return exec.Command("sh", "-c", "touch '"+marker+"'; echo connected to MeetStream; exec sleep 30") + homeAgentCommand = func() *exec.Cmd { // this test binary plays the bridge: no shell, so Windows runs it too + cmd := exec.Command(os.Args[0], "-test.run=^TestHelperFakeBridge$") + cmd.Env = append(os.Environ(), "MEETSTREAM_TEST_FAKE_BRIDGE="+marker) + return cmd } t.Cleanup(func() { homeAgentCommand = old }) m = moveTo(t, m, "Run my agent for meetings") diff --git a/internal/cli/m3b_test.go b/internal/cli/m3b_test.go index d303908..c681d6b 100644 --- a/internal/cli/m3b_test.go +++ b/internal/cli/m3b_test.go @@ -148,7 +148,7 @@ func TestM3BMiaApply(t *testing.T) { func TestM3BMCP(t *testing.T) { home := t.TempDir() - t.Setenv("HOME", home) + setHome(t, home) path := filepath.Join(home, ".cursor", "mcp.json") out, code := run(t, nil, "mcp", "add", "cursor", "--json") if code != 0 || !strings.Contains(out, hostedMCPURL) { @@ -298,7 +298,7 @@ func TestM3BCalendarConnect(t *testing.T) { func TestM3BCodexWrite(t *testing.T) { home := t.TempDir() - t.Setenv("HOME", home) + setHome(t, home) path := filepath.Join(home, ".codex", "config.toml") if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil { t.Fatal(err) diff --git a/internal/cli/review_fixes_test.go b/internal/cli/review_fixes_test.go index ad44608..9972bfb 100644 --- a/internal/cli/review_fixes_test.go +++ b/internal/cli/review_fixes_test.go @@ -22,6 +22,7 @@ import ( kitconfig "github.com/meetstream-ai/cli/internal/agentkit/config" agentlogin "github.com/meetstream-ai/cli/internal/agentkit/login" "github.com/meetstream-ai/cli/internal/api" + "github.com/meetstream-ai/cli/internal/testutil/fakecli" ) // Signed out at startup: the sign-in check notifies on serve's own goroutine @@ -60,14 +61,15 @@ func TestServeSignedOutNoticeBeforeHeader(t *testing.T) { // secrets hidden; the home app's background bridge logs only who spoke; and // agent errors are redacted too. func TestServeTurnLineRedactedAndHidden(t *testing.T) { - spec, err := agents.Custom("/bin/echo ready") + echo := fakecli.Echo(t, t.TempDir(), "echo") + spec, err := agents.Custom("'" + echo + "' ready") if err != nil { t.Fatal(err) } for _, hide := range []bool{false, true} { var mu sync.Mutex var lines []string - c := kitconfig.Config{Agent: spec, Binary: "/bin/echo", Workdir: t.TempDir(), RuntimeDir: t.TempDir(), HideTurnText: hide, + c := kitconfig.Config{Agent: spec, Binary: echo, Workdir: t.TempDir(), RuntimeDir: t.TempDir(), HideTurnText: hide, Log: func(l string) { mu.Lock(); lines = append(lines, l); mu.Unlock() }} srv := bridge.New(c) srv.SetInternalToken("tok") diff --git a/internal/testutil/fakecli/fakecli.go b/internal/testutil/fakecli/fakecli.go new file mode 100644 index 0000000..9455c29 --- /dev/null +++ b/internal/testutil/fakecli/fakecli.go @@ -0,0 +1,288 @@ +// Package fakecli makes stand-in agent CLIs for tests that run the same on +// macOS, Linux and Windows. Each fake is a copy of one tiny Go program (built +// once per test process, cached across runs) named like a real program on this +// OS (claude, or claude.exe on Windows). Beside it, .fakecli says what it +// does: nothing (exit 0), echo its arguments, or run another program, such as +// Python with a stub script, with its own arguments appended. No shell +// scripts, shebangs or execute bits are needed, so Windows runs them too. +package fakecli + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "sync" + "testing" +) + +// The environment and temp folder when the test binary started: tests change +// HOME, PATH and the like, and the build must keep using the real Go cache. +var ( + startEnv = os.Environ() + startTmp = os.TempDir() +) + +// Name is a program file name on this OS: name, or name.exe on Windows. +func Name(name string) string { + if runtime.GOOS == "windows" && filepath.Ext(name) == "" { + return name + ".exe" + } + return name +} + +// spec is the .fakecli file the program reads. +type spec struct { + Argv []string `json:"argv,omitempty"` // run this with the fake's own arguments appended + Echo bool `json:"echo,omitempty"` // print the arguments, like echo + Exit int `json:"exit,omitempty"` // exit code when Argv is empty +} + +// Program writes a program called name into dir that exits 0 and prints +// nothing (a stand-in that only has to be found, or to succeed). It returns +// the program's path. +func Program(t testing.TB, dir, name string) string { + t.Helper() + return write(t, dir, name, spec{}) +} + +// Echo writes a program called name into dir that prints its arguments joined +// by spaces and a newline, like /bin/echo. +func Echo(t testing.TB, dir, name string) string { + t.Helper() + return write(t, dir, name, spec{Echo: true}) +} + +// Run writes a program called name into dir that runs argv with its own +// arguments appended, passing stdin, stdout, stderr and the exit code through. +func Run(t testing.TB, dir, name string, argv ...string) string { + t.Helper() + if len(argv) == 0 { + t.Fatal("fakecli.Run: no program to run") + } + return write(t, dir, name, spec{Argv: argv}) +} + +// Python writes a program called name into dir that runs script with Python 3 +// (python3, python or py -3, whichever works here), never through a shebang. +// The test is skipped when this computer has no Python 3. +func Python(t testing.TB, dir, name, script string) string { + t.Helper() + py := Python3(t) + abs, err := filepath.Abs(script) + if err != nil { + t.Fatal(err) + } + // -u: unbuffered, as a streaming agent is; -X utf8: the same text on + // every OS (Windows pipes default to the ANSI code page). + return Run(t, dir, name, append(py, "-u", "-X", "utf8", abs)...) +} + +var ( + pyOnce sync.Once + pyArgv []string +) + +// Python3 is the command that runs Python 3 here (skips the test without one). +// A name on PATH is not enough: Windows' Store alias python3.exe exists but +// runs nothing, so each candidate must run a line of Python. +func Python3(t testing.TB) []string { + t.Helper() + pyOnce.Do(func() { + candidates := [][]string{{"python3"}, {"python"}} + if runtime.GOOS == "windows" { + candidates = append(candidates, []string{"py", "-3"}) + } + for _, c := range candidates { + p, err := exec.LookPath(c[0]) + if err != nil { + continue + } + argv := append([]string{p}, c[1:]...) + check := exec.Command(argv[0], append(argv[1:], "-c", "import sys; sys.exit(0 if sys.version_info >= (3, 8) else 1)")...) + if check.Run() == nil { + pyArgv = argv + return + } + } + }) + if pyArgv == nil { + t.Skip("Python 3 is needed for the stub agent") + } + return append([]string(nil), pyArgv...) +} + +func write(t testing.TB, dir, name string, s spec) string { + t.Helper() + src, err := program() + if err != nil { + t.Fatalf("fakecli: %v", err) + } + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + path := filepath.Join(dir, Name(name)) + if err := copyFile(src, path); err != nil { + t.Fatal(err) + } + b, _ := json.Marshal(s) + if err := os.WriteFile(specPath(path), b, 0o644); err != nil { + t.Fatal(err) + } + return path +} + +// specPath is .fakecli; the program finds it the same way. +func specPath(program string) string { + if strings.EqualFold(filepath.Ext(program), ".exe") { + program = program[:len(program)-4] + } + return program + ".fakecli" +} + +func copyFile(src, dst string) error { + _ = os.Remove(dst) + if os.Link(src, dst) == nil { + return nil + } + in, err := os.Open(src) + if err != nil { + return err + } + defer in.Close() + out, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o755) + if err != nil { + return err + } + if _, err := io.Copy(out, in); err != nil { + out.Close() + return err + } + return out.Close() +} + +var ( + buildOnce sync.Once + built string + buildErr error +) + +// program builds the fake program once per process, into a folder keyed by +// its source and Go version so later runs (and parallel packages) reuse it. +func program() (string, error) { + buildOnce.Do(func() { built, buildErr = build() }) + return built, buildErr +} + +func build() (string, error) { + sum := sha256.Sum256([]byte(source + runtime.Version() + runtime.GOOS + runtime.GOARCH)) + dir := filepath.Join(startTmp, "meetstream-fakecli-"+hex.EncodeToString(sum[:8])) + bin := filepath.Join(dir, Name("fakecli")) + if fi, err := os.Stat(bin); err == nil && fi.Mode().IsRegular() { + return bin, nil + } + work, err := os.MkdirTemp(startTmp, "meetstream-fakecli-build-") + if err != nil { + return "", err + } + defer os.RemoveAll(work) + srcDir, outDir := filepath.Join(work, "src"), filepath.Join(work, "out") + if err := os.MkdirAll(srcDir, 0o755); err != nil { + return "", err + } + if err := os.WriteFile(filepath.Join(srcDir, "go.mod"), []byte("module fakecli\n\ngo 1.21\n"), 0o644); err != nil { + return "", err + } + if err := os.WriteFile(filepath.Join(srcDir, "main.go"), []byte(source), 0o644); err != nil { + return "", err + } + goTool := filepath.Join(runtime.GOROOT(), "bin", Name("go")) + if _, err := os.Stat(goTool); err != nil { + goTool = "go" + } + cmd := exec.Command(goTool, "build", "-o", filepath.Join(outDir, Name("fakecli")), ".") + cmd.Dir = srcDir + cmd.Env = append(append([]string{}, startEnv...), "GOWORK=off", "GOFLAGS=", "CGO_ENABLED=0") + if out, err := cmd.CombinedOutput(); err != nil { + return "", fmt.Errorf("go build: %v\n%s", err, out) + } + // Another process may have built it meanwhile: theirs is as good. + if err := os.Rename(outDir, dir); err != nil { + if _, statErr := os.Stat(bin); statErr == nil { + return bin, nil + } + return "", errors.Join(err, fmt.Errorf("fakecli: cannot place the program in %s", dir)) + } + return bin, nil +} + +// source is the fake program. On Unix it replaces itself with the program it +// runs (exec), so signals and process groups reach that program as before; +// Windows has no exec, so it runs it as a child and passes the exit code on +// (a tree kill, taskkill /T, reaches both). +const source = `package main + +import ( + "encoding/json" + "errors" + "fmt" + "os" + "os/exec" + "os/signal" + "path/filepath" + "strings" + "syscall" +) + +type spec struct { + Argv []string ` + "`json:\"argv\"`" + ` + Echo bool ` + "`json:\"echo\"`" + ` + Exit int ` + "`json:\"exit\"`" + ` +} + +func main() { + self, err := os.Executable() + if err != nil { + fmt.Fprintln(os.Stderr, "fakecli:", err) + os.Exit(127) + } + if strings.EqualFold(filepath.Ext(self), ".exe") { + self = self[:len(self)-4] + } + var s spec + if b, err := os.ReadFile(self + ".fakecli"); err == nil { + if err := json.Unmarshal(b, &s); err != nil { + fmt.Fprintln(os.Stderr, "fakecli:", err) + os.Exit(127) + } + } + if s.Echo { + fmt.Println(strings.Join(os.Args[1:], " ")) + return + } + if len(s.Argv) == 0 { + os.Exit(s.Exit) + } + argv := append(append([]string{}, s.Argv...), os.Args[1:]...) + _ = syscall.Exec(argv[0], argv, os.Environ()) // returns only where exec is not supported (Windows) + cmd := exec.Command(argv[0], argv[1:]...) + cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr + signal.Ignore(os.Interrupt) // CTRL_BREAK reaches the child too (same process group) + err = cmd.Run() + var exit *exec.ExitError + if errors.As(err, &exit) { + os.Exit(exit.ExitCode()) + } + if err != nil { + fmt.Fprintln(os.Stderr, "fakecli:", err) + os.Exit(127) + } +} +` diff --git a/internal/testutil/fakecli/fakecli_test.go b/internal/testutil/fakecli/fakecli_test.go new file mode 100644 index 0000000..947764d --- /dev/null +++ b/internal/testutil/fakecli/fakecli_test.go @@ -0,0 +1,87 @@ +package fakecli + +import ( + "errors" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" +) + +func TestProgramIsFoundOnPathAndExitsZero(t *testing.T) { + dir := t.TempDir() + p := Program(t, dir, "claude") + if filepath.Base(p) != Name("claude") || (runtime.GOOS == "windows") != strings.HasSuffix(p, ".exe") { + t.Fatalf("path %q", p) + } + t.Setenv("PATH", dir) + found, err := exec.LookPath("claude") + if err != nil || found != p { + t.Fatalf("LookPath = %q %v", found, err) + } + out, err := exec.Command(found, "auth", "status").CombinedOutput() + if err != nil || len(out) != 0 { + t.Fatalf("out %q err %v", out, err) + } +} + +func TestEchoPrintsItsArguments(t *testing.T) { + out, err := exec.Command(Echo(t, t.TempDir(), "echo"), "ready", "now").Output() + if err != nil || string(out) != "ready now\n" { + t.Fatalf("out %q err %v", out, err) + } +} + +func TestRunPassesArgumentsStdinAndExitCode(t *testing.T) { + dir := t.TempDir() + // The fake runs another fake: an echo, then one that exits 3. + echo := Echo(t, dir, "inner") + outer := Run(t, dir, "outer", echo, "first") + out, err := exec.Command(outer, "second").Output() + if err != nil || string(out) != "first second\n" { + t.Fatalf("out %q err %v", out, err) + } + failing := write(t, dir, "failing", spec{Exit: 3}) + err = exec.Command(Run(t, dir, "wrapper", failing)).Run() + var exit *exec.ExitError + if !errors.As(err, &exit) || exit.ExitCode() != 3 { + t.Fatalf("exit %v", err) + } +} + +// The program is source text built at test time, so compiling the tests for +// Windows does not check it: build it for Windows here. +func TestProgramBuildsForWindows(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("every test here builds it on Windows") + } + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "go.mod"), []byte("module fakecli\n\ngo 1.21\n"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "main.go"), []byte(source), 0o644); err != nil { + t.Fatal(err) + } + cmd := exec.Command(filepath.Join(runtime.GOROOT(), "bin", "go"), "build", "-o", filepath.Join(dir, "fakecli.exe"), ".") + cmd.Dir = dir + cmd.Env = append(os.Environ(), "GOOS=windows", "GOARCH=amd64", "CGO_ENABLED=0", "GOWORK=off", "GOFLAGS=") + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("%v\n%s", err, out) + } +} + +func TestPythonRunsTheScriptWithoutAShebang(t *testing.T) { + dir := t.TempDir() + script := filepath.Join(dir, "stub.py") + if err := os.WriteFile(script, []byte("import sys\nprint(sys.stdin.read().strip() + ' ' + ' '.join(sys.argv[1:]))\n"), 0o644); err != nil { + t.Fatal(err) + } + cmd := exec.Command(Python(t, dir, "agent", script), "a", "b c") + cmd.Stdin = strings.NewReader("hello\n") + out, err := cmd.Output() + if err != nil || strings.TrimSpace(string(out)) != "hello a b c" { + t.Fatalf("out %q err %v", out, err) + } +}