@@ -0,0 +1,448 @@
1+package tui
2+
3+import (
4+ "testing"
5+ "time"
6+
7+ tea "github.com/charmbracelet/bubbletea"
8+ "github.com/xonecas/zoea-nova/internal/config"
9+ "github.com/xonecas/zoea-nova/internal/core"
10+ "github.com/xonecas/zoea-nova/internal/provider"
11+ "github.com/xonecas/zoea-nova/internal/store"
12+ "golang.org/x/time/rate"
13+)
14+
15+// TestInputReset_DirectMessage verifies that the input box resets after sending a direct message.
16+func TestInputReset_DirectMessage(t *testing.T) {
17+ t.Run("non_empty_message_resets_input", func(t *testing.T) {
18+ m, cleanup := setupTestModel(t)
19+ defer cleanup()
20+
21+ // Create a mysis to message
22+ mysis, _ := m.commander.CreateMysis("test-mysis", "ollama")
23+ m.commander.StartMysis(mysis.ID())
24+ m.refreshMysisList()
25+ m.selectedIdx = 0
26+
27+ // Press 'm' to open message input
28+ newModel, _ := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'m'}})
29+ m = newModel.(Model)
30+
31+ // Verify input is active
32+ if !m.input.IsActive() {
33+ t.Fatal("input should be active after 'm' key")
34+ }
35+ if m.input.Mode() != InputModeMessage {
36+ t.Fatalf("input mode = %d, want InputModeMessage (%d)", m.input.Mode(), InputModeMessage)
37+ }
38+
39+ // Type a message
40+ m.input.textInput.SetValue("hello world")
41+
42+ // Verify input has value
43+ if m.input.Value() != "hello world" {
44+ t.Fatalf("input value = %q, want %q", m.input.Value(), "hello world")
45+ }
46+
47+ // Press Enter to send
48+ newModel, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter})
49+ m = newModel.(Model)
50+
51+ // Verify input is reset immediately (before async completion)
52+ if m.input.Value() != "" {
53+ t.Errorf("input value = %q, want empty string (input should reset immediately after Enter)", m.input.Value())
54+ }
55+ if m.input.Mode() != InputModeNone {
56+ t.Errorf("input mode = %d, want InputModeNone (%d)", m.input.Mode(), InputModeNone)
57+ }
58+ if m.input.IsActive() {
59+ t.Error("input should not be active after Enter (showing 'Sending...' indicator)")
60+ }
61+
62+ // With SendMessageAsync, m.sending is NOT set (message sent immediately)
63+ // Network indicator shows activity, but input is ready for next message
64+ if m.sending {
65+ t.Error("sending flag should be false (SendMessageAsync returns immediately)")
66+ }
67+
68+ // Verify async command was returned
69+ if cmd == nil {
70+ t.Fatal("cmd should not be nil (async send should be scheduled)")
71+ }
72+
73+ // Execute the async command to get the result
74+ result := cmd()
75+ if result == nil {
76+ t.Fatal("async command should return a result")
77+ }
78+
79+ // Process the result
80+ newModel, _ = m.Update(result)
81+ m = newModel.(Model)
82+
83+ // Verify input is still reset after async completion
84+ if m.input.Value() != "" {
85+ t.Errorf("input value = %q, want empty string (input should remain reset after async completion)", m.input.Value())
86+ }
87+
88+ // Verify sending state is cleared
89+ if m.sending {
90+ t.Error("sending flag should be false after async completion")
91+ }
92+ })
93+
94+ t.Run("empty_message_sends_and_shows_indicator", func(t *testing.T) {
95+ m, cleanup := setupTestModel(t)
96+ defer cleanup()
97+
98+ // Create a mysis to message
99+ mysis, _ := m.commander.CreateMysis("test-mysis", "ollama")
100+ m.commander.StartMysis(mysis.ID())
101+ m.refreshMysisList()
102+ m.selectedIdx = 0
103+
104+ // Press 'm' to open message input
105+ newModel, _ := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'m'}})
106+ m = newModel.(Model)
107+
108+ // Verify input is active
109+ if !m.input.IsActive() {
110+ t.Fatal("input should be active after 'm' key")
111+ }
112+
113+ // Press Enter without typing (empty message)
114+ // NOTE: Direct messages DO NOT validate for empty - this differs from broadcasts
115+ newModel, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter})
116+ m = newModel.(Model)
117+
118+ // Verify input is reset and showing "Sending..." indicator
119+ if m.input.Value() != "" {
120+ t.Errorf("input value = %q, want empty string", m.input.Value())
121+ }
122+ if m.input.Mode() != InputModeNone {
123+ t.Errorf("input mode = %d, want InputModeNone (%d)", m.input.Mode(), InputModeNone)
124+ }
125+ if m.input.IsActive() {
126+ t.Error("input should not be active (showing 'Sending...' indicator)")
127+ }
128+
129+ // Direct messages are sent even when empty (app.go:650-658, no empty check)
130+ if cmd == nil {
131+ t.Error("cmd should not be nil (direct messages are sent even when empty)")
132+ }
133+ // With SendMessageAsync, m.sending is NOT set
134+ if m.sending {
135+ t.Error("sending flag should be false (SendMessageAsync returns immediately)")
136+ }
137+ })
138+}
139+
140+// TestInputReset_Broadcast verifies that the input box resets after broadcasting.
141+func TestInputReset_Broadcast(t *testing.T) {
142+ t.Run("non_empty_broadcast_resets_input", func(t *testing.T) {
143+ m, cleanup := setupTestModel(t)
144+ defer cleanup()
145+
146+ // Create myses to broadcast to
147+ m.commander.CreateMysis("mysis-1", "ollama")
148+ m.commander.CreateMysis("mysis-2", "ollama")
149+ m.refreshMysisList()
150+
151+ // Press 'b' to open broadcast input
152+ newModel, _ := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'b'}})
153+ m = newModel.(Model)
154+
155+ // Verify input is active
156+ if !m.input.IsActive() {
157+ t.Fatal("input should be active after 'b' key")
158+ }
159+ if m.input.Mode() != InputModeBroadcast {
160+ t.Fatalf("input mode = %d, want InputModeBroadcast (%d)", m.input.Mode(), InputModeBroadcast)
161+ }
162+
163+ // Type a message
164+ m.input.textInput.SetValue("broadcast message")
165+
166+ // Press Enter to send
167+ newModel, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter})
168+ m = newModel.(Model)
169+
170+ // Verify input is reset immediately
171+ if m.input.Value() != "" {
172+ t.Errorf("input value = %q, want empty string (input should reset immediately after Enter)", m.input.Value())
173+ }
174+ if m.input.Mode() != InputModeNone {
175+ t.Errorf("input mode = %d, want InputModeNone (%d)", m.input.Mode(), InputModeNone)
176+ }
177+ if m.input.IsActive() {
178+ t.Error("input should not be active after Enter (showing 'Sending...' indicator)")
179+ }
180+
181+ // Verify sending state is set
182+ if !m.sending {
183+ t.Error("sending flag should be true after Enter")
184+ }
185+ if m.sendingMode != InputModeBroadcast {
186+ t.Errorf("sendingMode = %d, want InputModeBroadcast (%d)", m.sendingMode, InputModeBroadcast)
187+ }
188+
189+ // Verify async command was returned
190+ if cmd == nil {
191+ t.Fatal("cmd should not be nil (async broadcast should be scheduled)")
192+ }
193+ })
194+
195+ t.Run("empty_broadcast_resets_without_sending", func(t *testing.T) {
196+ m, cleanup := setupTestModel(t)
197+ defer cleanup()
198+
199+ // Press 'b' to open broadcast input
200+ newModel, _ := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'b'}})
201+ m = newModel.(Model)
202+
203+ // Press Enter without typing (empty broadcast)
204+ newModel, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter})
205+ m = newModel.(Model)
206+
207+ // Verify input is reset
208+ if m.input.Value() != "" {
209+ t.Errorf("input value = %q, want empty string", m.input.Value())
210+ }
211+ if m.input.Mode() != InputModeNone {
212+ t.Errorf("input mode = %d, want InputModeNone (%d)", m.input.Mode(), InputModeNone)
213+ }
214+ if m.input.IsActive() {
215+ t.Error("input should not be active after empty broadcast")
216+ }
217+
218+ // Empty broadcasts should NOT trigger sending (app.go:629-632)
219+ if cmd != nil {
220+ t.Error("cmd should be nil (empty broadcasts should not be sent)")
221+ }
222+ if m.sending {
223+ t.Error("sending flag should be false (empty broadcasts should not trigger sending)")
224+ }
225+ })
226+}
227+
228+// TestInputReset_Integration verifies input reset behavior in integration scenarios.
229+func TestInputReset_Integration(t *testing.T) {
230+ t.Run("send_multiple_messages_sequentially", func(t *testing.T) {
231+ m, cleanup := setupTestModel(t)
232+ defer cleanup()
233+
234+ // Create a mysis
235+ mysis, _ := m.commander.CreateMysis("test-mysis", "ollama")
236+ m.commander.StartMysis(mysis.ID())
237+ m.refreshMysisList()
238+ m.selectedIdx = 0
239+
240+ // Send first message
241+ newModel, _ := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'m'}})
242+ m = newModel.(Model)
243+ m.input.textInput.SetValue("message 1")
244+ newModel, cmd1 := m.Update(tea.KeyMsg{Type: tea.KeyEnter})
245+ m = newModel.(Model)
246+
247+ // Verify input is reset after first message
248+ if m.input.Value() != "" {
249+ t.Errorf("input value = %q after first message, want empty", m.input.Value())
250+ }
251+ if m.input.Mode() != InputModeNone {
252+ t.Errorf("input mode = %d after first message, want InputModeNone (%d)", m.input.Mode(), InputModeNone)
253+ }
254+ if m.input.IsActive() {
255+ t.Error("input should not be active after first message (showing 'Sending...' indicator)")
256+ }
257+
258+ // Complete first async send
259+ if cmd1 != nil {
260+ result1 := cmd1()
261+ newModel, _ = m.Update(result1)
262+ m = newModel.(Model)
263+ }
264+
265+ // Wait a bit for async completion
266+ time.Sleep(10 * time.Millisecond)
267+
268+ // Send second message
269+ newModel, _ = m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'m'}})
270+ m = newModel.(Model)
271+ m.input.textInput.SetValue("message 2")
272+ newModel, cmd2 := m.Update(tea.KeyMsg{Type: tea.KeyEnter})
273+ m = newModel.(Model)
274+
275+ // Verify input is reset after second message
276+ if m.input.Value() != "" {
277+ t.Errorf("input value = %q after second message, want empty", m.input.Value())
278+ }
279+ if m.input.Mode() != InputModeNone {
280+ t.Errorf("input mode = %d after second message, want InputModeNone (%d)", m.input.Mode(), InputModeNone)
281+ }
282+ if m.input.IsActive() {
283+ t.Error("input should not be active after second message (showing 'Sending...' indicator)")
284+ }
285+
286+ // Complete second async send
287+ if cmd2 != nil {
288+ result2 := cmd2()
289+ newModel, _ = m.Update(result2)
290+ m = newModel.(Model)
291+ }
292+
293+ // Verify final state
294+ if m.input.Value() != "" {
295+ t.Errorf("final input value = %q, want empty", m.input.Value())
296+ }
297+ if m.sending {
298+ t.Error("sending flag should be false after all messages sent")
299+ }
300+ })
301+}
302+
303+// setupTestModelWithSlowProvider creates a test model with a slow mock provider.
304+// The slow provider simulates a long LLM response time (5 seconds).
305+func setupTestModelWithSlowProvider(t *testing.T) (Model, func()) {
306+ t.Helper()
307+
308+ s, err := store.OpenMemory()
309+ if err != nil {
310+ t.Fatalf("OpenMemory() error: %v", err)
311+ }
312+
313+ bus := core.NewEventBus(100)
314+ eventCh := bus.Subscribe()
315+
316+ reg := provider.NewRegistry()
317+ limiter := rate.NewLimiter(rate.Limit(1000), 1000)
318+
319+ // Create a mock factory that returns a provider with a 5-second delay
320+ slowFactory := &slowMockFactory{
321+ name: "ollama",
322+ response: "mock response",
323+ limiter: limiter,
324+ delay: 5 * time.Second,
325+ }
326+ reg.RegisterFactory("ollama", slowFactory)
327+ reg.RegisterFactory("opencode_zen", provider.NewMockFactoryWithLimiter("opencode_zen", "mock response", limiter))
328+
329+ cfg := &config.Config{
330+ Swarm: config.SwarmConfig{
331+ MaxMyses: 16,
332+ DefaultProvider: "opencode_zen",
333+ DefaultModel: "gpt-5-nano",
334+ },
335+ Providers: map[string]config.ProviderConfig{
336+ "ollama": {Endpoint: "http://mock", Model: "mock-model", Temperature: 0.7, RateLimit: 1000, RateBurst: 1000},
337+ "opencode_zen": {Endpoint: "http://mock", Model: "gpt-5-nano", Temperature: 0.7, RateLimit: 1000, RateBurst: 1000},
338+ },
339+ }
340+
341+ commander := core.NewCommander(s, reg, bus, cfg)
342+
343+ model := New(commander, s, eventCh, false, cfg)
344+ model.width = 80
345+ model.height = 24
346+
347+ // Set fixed test time for deterministic timestamps
348+ fixedTime := testTime()
349+ model.testTime = &fixedTime
350+
351+ cleanup := func() {
352+ commander.StopAll()
353+ bus.Close()
354+ s.Close()
355+ }
356+
357+ return model, cleanup
358+}
359+
360+// slowMockFactory creates mock providers with a configurable delay.
361+type slowMockFactory struct {
362+ name string
363+ response string
364+ limiter *rate.Limiter
365+ delay time.Duration
366+}
367+
368+func (f *slowMockFactory) Name() string { return f.name }
369+
370+func (f *slowMockFactory) Create(model string, temperature float64) provider.Provider {
371+ p := provider.NewMock(f.name, f.response)
372+ p.WithLimiter(f.limiter)
373+ p.SetDelay(f.delay)
374+ return p
375+}
376+
377+// TestInputReset_SendingClearsImmediately verifies that m.sending is cleared
378+// immediately when Enter is pressed, not after the LLM finishes responding.
379+// This test demonstrates the bug where m.sending remains true until the async
380+// operation completes, preventing users from sending multiple messages quickly.
381+func TestInputReset_SendingClearsImmediately(t *testing.T) {
382+ m, cleanup := setupTestModelWithSlowProvider(t)
383+ defer cleanup()
384+
385+ // Create a mysis with the slow mock provider (5 second delay)
386+ mysis, _ := m.commander.CreateMysis("slow-mysis", "ollama")
387+ m.commander.StartMysis(mysis.ID())
388+ m.refreshMysisList()
389+ m.selectedIdx = 0
390+
391+ // Press 'm' to open message input
392+ newModel, _ := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'m'}})
393+ m = newModel.(Model)
394+
395+ // Type a message
396+ m.input.textInput.SetValue("test message")
397+
398+ // Press Enter to send
399+ startTime := time.Now()
400+ newModel, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter})
401+ m = newModel.(Model)
402+ elapsedAfterEnter := time.Since(startTime)
403+
404+ // BUG: m.sending should be FALSE immediately after Enter,
405+ // but currently it's TRUE until the async operation completes
406+ // (which takes 5 seconds due to the slow provider)
407+ if m.sending {
408+ t.Errorf("BUG DETECTED: m.sending = true after Enter (elapsed: %v), want false immediately", elapsedAfterEnter)
409+ t.Logf("This demonstrates the bug: m.sending should be cleared immediately after Enter, not after LLM completes")
410+ t.Logf("Expected behavior: User can press 'm' again immediately after sending")
411+ t.Logf("Actual behavior: User must wait %v for LLM to finish before m.sending clears", 5*time.Second)
412+ }
413+
414+ // Verify that the elapsed time is small (< 100ms), proving that
415+ // we're checking immediately after Enter, not after the 5-second delay
416+ if elapsedAfterEnter > 100*time.Millisecond {
417+ t.Fatalf("Test error: elapsed time %v is too large, expected < 100ms", elapsedAfterEnter)
418+ }
419+
420+ // Verify async command was returned (this is correct behavior)
421+ if cmd == nil {
422+ t.Fatal("cmd should not be nil (async send should be scheduled)")
423+ }
424+
425+ // Now execute the async command (with SendMessageAsync, this returns IMMEDIATELY)
426+ asyncStartTime := time.Now()
427+ result := cmd()
428+ asyncElapsed := time.Since(asyncStartTime)
429+
430+ // With SendMessageAsync, the command returns IMMEDIATELY (not after LLM completes)
431+ // This is the fix - the async operation should be fast (< 100ms)
432+ if asyncElapsed > 100*time.Millisecond {
433+ t.Errorf("async operation took %v, expected < 100ms (SendMessageAsync returns immediately)", asyncElapsed)
434+ }
435+
436+ // Process the async result
437+ newModel, _ = m.Update(result)
438+ m = newModel.(Model)
439+
440+ // m.sending should still be false (was never set with async approach)
441+ if m.sending {
442+ t.Error("m.sending should be false (never set with SendMessageAsync)")
443+ }
444+
445+ // The LLM processing happens in the background (via goroutine in SendMessageAsync)
446+ // The TUI doesn't wait for it, so the user can immediately send another message
447+ t.Log("SUCCESS: Input cleared immediately, LLM processing happens in background")
448+}