package cli import ( "bytes" "os" "strings" "testing" "time" "tangled.org/beardic.us/chatline/internal/api" "tangled.org/beardic.us/chatline/internal/events" "tangled.org/beardic.us/chatline/internal/output" "tangled.org/beardic.us/chatline/skills" ) func testApp(stdin string, env map[string]string) (*App, *bytes.Buffer, *bytes.Buffer) { var out, errb bytes.Buffer a := &App{ Stdin: strings.NewReader(stdin), Stdout: &out, Stderr: &errb, Env: func(k string) string { return env[k] }, StdinIsTTY: func() bool { return stdin == "" }, Now: time.Now, Build: BuildInfo{Version: "test", ChattoVersion: "v0.5.0"}, } return a, &out, &errb } func TestExitCodes(t *testing.T) { cases := []struct { args []string env map[string]string exit int want string }{ {[]string{"send", "--bogus"}, nil, output.ExitUsage, "error: bad_flag:"}, {[]string{"rooms", "extra"}, nil, output.ExitUsage, "error: bad_args:"}, {[]string{"--format", "yaml", "version"}, nil, output.ExitUsage, "bad_format"}, {[]string{"--config", "/nonexistent/c.json", "rooms"}, nil, output.ExitConfig, "error: config_error: no server URL"}, } for _, c := range cases { a, _, errb := testApp("", c.env) if got := a.Run(c.args); got != c.exit || !strings.Contains(errb.String(), c.want) { t.Errorf("%v: exit %d stderr %q; want %d %q", c.args, got, errb.String(), c.exit, c.want) } } } func TestInitRefusesNonTTYSecret(t *testing.T) { a, _, errb := testApp("piped", nil) got := a.Run([]string{"--config", t.TempDir() + "/c.json", "init", "--server", "https://x"}) if got != output.ExitConfig || !strings.Contains(errb.String(), "non_tty_secret_input") { t.Fatalf("exit %d %q", got, errb.String()) } } func TestVersionJSON(t *testing.T) { a, out, _ := testApp("", nil) if a.Run([]string{"--format", "json", "version"}) != 0 || !strings.Contains(out.String(), `"chatto_version":"v0.5.0"`) { t.Fatal(out.String()) } } func TestReadBody(t *testing.T) { a, _, _ := testApp("from stdin\n", nil) if b, err := a.readBody("", "", false); err != nil || b != "from stdin" { t.Fatalf("%q %v", b, err) } a, _, _ = testApp("", nil) // TTY, nothing given if _, err := a.readBody("", "", false); output.Classify(err).Code != "no_message" { t.Fatal(err) } if _, err := a.readBody("x", "f", false); output.Classify(err).Exit != output.ExitUsage { t.Fatal(err) } } func TestVersionWarning(t *testing.T) { for _, tt := range []struct { server string warning string }{ {"0.5.0-beta.9", "version_mismatch"}, {"0.5.0-beta.17", "version_mismatch"}, {"v0.5.0-beta.17", "version_mismatch"}, {"0.4.9", "version_mismatch"}, {"0.5.0-beta.29", "version_mismatch"}, {"0.5.0-rc.4", "version_mismatch"}, {"0.5.0-rc.5", "version_mismatch"}, {"0.5.0-rc.5+build.1", "version_mismatch"}, {"0.5.0", ""}, {"v0.5.0", ""}, {"0.5.0+build.1", ""}, {"0.5.1", ""}, {"0.6.0", ""}, {"1.0.0", ""}, {"", "version_check_failed"}, {"dev", "version_check_failed"}, {"0.5.0-beta.01", "version_check_failed"}, } { t.Run(tt.server, func(t *testing.T) { got := versionWarning(tt.server) if tt.warning == "" { if got != "" { t.Fatal(got) } } else if !strings.HasPrefix(got, tt.warning+":") || !strings.Contains(got, MinimumChattoVersion) { t.Fatalf("versionWarning(%q) = %q; want %s with minimum version", tt.server, got, tt.warning) } }) } } func TestFormatEvent(t *testing.T) { var b bytes.Buffer p := &output.Printer{W: &b} p.Line(formatEvent(&events.Event{Type: "mention", RoomID: "R1", RoomName: "ops", MessageID: "M1", SenderLogin: "beardicus", ThreadID: "T1", Body: "two\nlines"})...) if got := b.String(); got != "mention R1 ops M1 beardicus thread=T1 two\\nlines\n" { t.Fatalf("%q", got) } } func TestReplyMatcher(t *testing.T) { channel := &api.Room{ID: "R1", Kind: "channel", Threading: "enabled"} m := &replyMatcher{room: channel, posted: "Q", threadID: "Q", botID: "BOT", from: map[string]bool{}} if !m.matches(&events.Event{RoomID: "R1", MessageID: "A", ThreadID: "Q", SenderID: "U"}) { t.Error("thread reply not matched") } if m.matches(&events.Event{RoomID: "R1", MessageID: "A", SenderID: "U"}) { t.Error("root message matched for threaded question") } if m.matches(&events.Event{RoomID: "R1", MessageID: "A", ThreadID: "Q", SenderID: "BOT"}) { t.Error("bot's own message matched") } m.from = map[string]bool{"OWNER": true} if m.matches(&events.Event{RoomID: "R1", MessageID: "A", ThreadID: "Q", SenderID: "U"}) { t.Error("--from not enforced") } dm := &replyMatcher{room: &api.Room{ID: "D1", Kind: "dm"}, posted: "Q", botID: "BOT"} if !dm.matches(&events.Event{RoomID: "D1", MessageID: "A", SenderID: "U"}) { t.Error("dm reply not matched") } flat := &replyMatcher{room: &api.Room{ID: "R2", Kind: "channel", Threading: "disabled"}, posted: "Q", botID: "BOT"} if !flat.matches(&events.Event{RoomID: "R2", MessageID: "A", ReplyTo: "Q", SenderID: "U"}) { t.Error("quote reply not matched in flat room") } if flat.matches(&events.Event{RoomID: "R2", MessageID: "A", SenderID: "U"}) { t.Error("unrelated message matched in flat room without --from") } } func TestOldestReplyIgnoresRoot(t *testing.T) { msgs := []*api.Message{{ID: "ROOT"}, {ID: "R1"}} if m := oldestReply(msgs, "ROOT"); m == nil || m.ID != "R1" { t.Fatal(m) } if m := oldestReply([]*api.Message{{ID: "ROOT"}}, "ROOT"); m != nil { t.Fatal(m) } } func TestLogFileAppendsAndTees(t *testing.T) { path := t.TempDir() + "/chatline.log" os.WriteFile(path, []byte("earlier\n"), 0o600) a, _, errb := testApp("", map[string]string{"CHATLINE_LOG_FILE": path}) log, err := a.logger() if err != nil { t.Fatal(err) } log.Warn("realtime disconnected") b, _ := os.ReadFile(path) if !strings.HasPrefix(string(b), "earlier\n") || !strings.Contains(string(b), "realtime disconnected") { t.Fatalf("log file: %q", b) } if !strings.Contains(errb.String(), "realtime disconnected") { t.Fatalf("stderr: %q", errb.String()) } a, _, _ = testApp("", map[string]string{"CHATLINE_LOG_FILE": t.TempDir() + "/missing/dir.log"}) if _, err := a.logger(); output.Classify(err).Exit != output.ExitConfig { t.Fatalf("unopenable log file: %v", err) } } func TestMessageIDFlag(t *testing.T) { noConfig := map[string]string{"CHATLINE_CONFIG": "/nonexistent/c.json"} for _, c := range []struct { args []string exit int wantStderr string }{ {[]string{"permalink", "--room", "ops"}, output.ExitUsage, "error: bad_flag: --message-id is required"}, {[]string{"react", "--room", "ops", "--message-id", "E1", "--message", "E2", "--emoji", "eyes"}, output.ExitUsage, "use only one of --message-id and --message"}, // The old flag still works, with a warning; config is what fails next. {[]string{"permalink", "--room", "ops", "--message", "E1"}, output.ExitConfig, "warning: --message is deprecated here; use --message-id"}, {[]string{"react", "--room", "ops", "--message", "E1", "--message-id", "E1", "--emoji", "eyes"}, output.ExitConfig, "deprecated"}, {[]string{"react", "--room", "ops", "--message-id", "E1", "--emoji", "eyes"}, output.ExitConfig, "error: config_error"}, } { a, _, errb := testApp("", noConfig) if got := a.Run(c.args); got != c.exit || !strings.Contains(errb.String(), c.wantStderr) { t.Errorf("%q: exit %d, stderr %q", c.args, got, errb.String()) } } } func TestSkillPrintsEmbeddedSkill(t *testing.T) { a, out, _ := testApp("", nil) if a.Run([]string{"skill"}) != 0 || out.String() != skills.UsingChatto { t.Fatalf("skill printed %d bytes, want the embedded SKILL.md", out.Len()) } if !strings.HasPrefix(skills.UsingChatto, "---\nname: using-chatto\n") { t.Fatal("embedded skill has no using-chatto front matter") } } func TestBootstrapWithoutConfig(t *testing.T) { a, out, _ := testApp("", nil) if got := a.Run([]string{"--config", t.TempDir() + "/c.json", "bootstrap"}); got != 0 { t.Fatalf("exit %d, want 0 so the agent reads the output", got) } for _, want := range []string{"isn't set up yet", "chatline init --server", "----- BEGIN SKILL.md -----\n" + skills.UsingChatto, "----- END SKILL.md -----\n"} { if !strings.Contains(out.String(), want) { t.Errorf("bootstrap output lacks %q", want) } } } func TestFormatSearchHit(t *testing.T) { h := &api.SearchHit{RoomName: "ops", Message: &api.Message{ ID: "M1", RoomID: "R1", SenderID: "U1", SenderLogin: "dana", ThreadID: "T1", Body: "disk\nfull", CreatedAt: time.Date(2026, 10, 28, 4, 0, 0, 0, time.UTC), }} got := strings.Join(formatSearchHit(h, true), " ") if want := `2026-10-28T04:00:00Z R1 ops M1 dana thread=T1 disk\nfull`; strings.Join(strings.Fields(got), " ") != strings.Join(strings.Fields(want), " ") { t.Fatalf("got %q", got) } h.RoomName = "" if f := formatSearchHit(h, false); f[2] != "-" || f[4] != "U1" { t.Fatalf("unnamed room and unresolved sender: %q", f) } }