xonecas.io
60255
Zn

Zoea-Nova / commit 64cbf3c

fix: account being released hidden by tests

xonecas2026-02-10 64cbf3c79e32e285bc0e7319367c4f7648a870e4 parent 439f0c9

21 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

Makefile+3−13
@@ -19,21 +19,11 @@ install: build
1919 cp bin/zoea $(HOME)/.zoea-nova/bin/zoea
2020
2121 test:
22- go test -race -timeout=60s -coverprofile=coverage.out ./internal/config ./internal/core ./internal/integration ./internal/mcp ./internal/provider ./internal/store
23- go test -timeout=30s -coverprofile=coverage-tui.out ./internal/tui
22+ go test -race -timeout=60s -coverprofile=coverage.out ./internal/**
2423 go tool cover -func=coverage.out
2524 @echo ""
26- @echo "TUI package coverage:"
27- @go tool cover -func=coverage-tui.out | grep "^total:"
28-
29-test-integration:
30- go test -v ./internal/tui -run TestIntegration -count=1
31-
32-check-upstream-version:
33- @echo "Config upstream version:"
34- @rg "upstream_version" config.toml
35- @echo "Remote upstream version:"
36- @curl -s https://www.spacemolt.com/api.md | rg -o "gameserver v[0-9.]+"
25+ @echo "package coverage:"
26+ @go tool cover -func=coverage.out | grep "^total:"
3727
3828 clean:
3929 rm -rf bin/ coverage.out
internal/core/activity_state_test.go+0−42
@@ -1,42 +0,0 @@
1-package core
2-
3-import (
4- "testing"
5- "time"
6-)
7-
8-func TestMysis_ActivityStateAccessor(t *testing.T) {
9- m := &Mysis{activityState: ActivityStateTraveling}
10-
11- if m.ActivityState() != ActivityStateTraveling {
12- t.Errorf("expected traveling, got %v", m.ActivityState())
13- }
14-}
15-
16-func TestMysis_SetActivityLLM(t *testing.T) {
17- m := &Mysis{activityState: ActivityStateIdle}
18- m.setActivity(ActivityStateLLMCall, time.Time{})
19-
20- if m.activityState != ActivityStateLLMCall {
21- t.Errorf("expected llm_call, got %v", m.activityState)
22- }
23-}
24-
25-func TestMysis_SetActivityMCP(t *testing.T) {
26- m := &Mysis{activityState: ActivityStateIdle}
27- m.setActivity(ActivityStateMCPCall, time.Time{})
28-
29- if m.activityState != ActivityStateMCPCall {
30- t.Errorf("expected mcp_call, got %v", m.activityState)
31- }
32-}
33-
34-func TestActivityStateConstants(t *testing.T) {
35- // Verify new constants exist and have expected values
36- if ActivityStateLLMCall != "llm_call" {
37- t.Errorf("expected llm_call, got %v", ActivityStateLLMCall)
38- }
39- if ActivityStateMCPCall != "mcp_call" {
40- t.Errorf("expected mcp_call, got %v", ActivityStateMCPCall)
41- }
42-}
internal/core/long_running_stop_test.go+0−583
@@ -1,583 +0,0 @@
1-package core
2-
3-import (
4- "fmt"
5- "path/filepath"
6- "strings"
7- "sync"
8- "testing"
9- "time"
10-
11- "github.com/xonecas/zoea-nova/internal/config"
12- "github.com/xonecas/zoea-nova/internal/provider"
13- "github.com/xonecas/zoea-nova/internal/store"
14-)
15-
16-// TestLongRunningStopScenario reproduces the EXACT production failure:
17-// 1. App running for ~9 hours
18-// 2. Multiple myses active (long, sleepy runner)
19-// 3. User quits app (calls StopAll)
20-// 4. App should exit cleanly
21-// 5. All myses should show state=stopped (NOT errored)
22-//
23-// This test validates:
24-// - StopAll completes within 10 seconds
25-// - Both myses reach state=stopped (NOT errored)
26-// - No goroutine leaks (WaitGroup completes)
27-// - No deadlocks
28-// - lastError == nil for all myses
29-//
30-// Run with:
31-//
32-// go test ./internal/core -run TestLongRunningStopScenario -v -count=10
33-func TestLongRunningStopScenario(t *testing.T) {
34- tmpDir := t.TempDir()
35- dbPath := filepath.Join(tmpDir, "test.db")
36- s, err := store.Open(dbPath)
37- if err != nil {
38- t.Fatalf("Open() error: %v", err)
39- }
40- defer s.Close()
41-
42- bus := NewEventBus(100)
43- defer bus.Close()
44-
45- reg := provider.NewRegistry()
46- cfg := &config.Config{
47- Swarm: config.SwarmConfig{MaxMyses: 10},
48- Providers: map[string]config.ProviderConfig{
49- "mock": {Model: "test-model", Temperature: 0.7},
50- },
51- }
52-
53- cmd := NewCommander(s, reg, bus, cfg, "")
54-
55- // Create two myses: "long" and "sleepy"
56- longMock := provider.NewMock("mock-long", "response from long")
57- sleepyMock := provider.NewMock("mock-sleepy", "response from sleepy")
58-
59- storedLong, _ := s.CreateMysis("long", "mock", "test-model", 0.7)
60- storedSleepy, _ := s.CreateMysis("sleepy", "mock", "test-model", 0.7)
61-
62- long := NewMysis(storedLong.ID, storedLong.Name, storedLong.CreatedAt, longMock, s, bus, "", cmd)
63- sleepy := NewMysis(storedSleepy.ID, storedSleepy.Name, storedSleepy.CreatedAt, sleepyMock, s, bus, "", cmd)
64-
65- // Add them to commander
66- cmd.mu.Lock()
67- cmd.myses[storedLong.ID] = long
68- cmd.myses[storedSleepy.ID] = sleepy
69- cmd.mu.Unlock()
70-
71- // Start both myses
72- if err := long.Start(); err != nil {
73- t.Fatalf("Start(long) error: %v", err)
74- }
75- if err := sleepy.Start(); err != nil {
76- t.Fatalf("Start(sleepy) error: %v", err)
77- }
78-
79- // Simulate long runtime with multiple turns
80- // In production: 9 hours of runtime = hundreds of turns
81- // In test: simulate with rapid-fire messages
82- for i := 0; i < 5; i++ {
83- long.SendMessage(fmt.Sprintf("message %d", i), store.MemorySourceDirect)
84- sleepy.SendMessage(fmt.Sprintf("message %d", i), store.MemorySourceDirect)
85- time.Sleep(50 * time.Millisecond) // Let messages process
86- }
87-
88- // Give myses time to settle into idle state
89- time.Sleep(200 * time.Millisecond)
90-
91- // Verify both are running before stop
92- if long.State() != MysisStateRunning {
93- t.Fatalf("expected long state=running before stop, got %s", long.State())
94- }
95- if sleepy.State() != MysisStateRunning {
96- t.Fatalf("expected sleepy state=running before stop, got %s", sleepy.State())
97- }
98-
99- // CRITICAL: Call StopAll() - this is what TUI does on quit
100- // This must complete within 10 seconds
101- start := time.Now()
102- cmd.StopAll()
103- elapsed := time.Since(start)
104-
105- // Verify StopAll completed within timeout
106- if elapsed > 12*time.Second { // Allow 2s buffer
107- t.Errorf("StopAll took %s (expected < 10s)", elapsed)
108- }
109-
110- // CRITICAL ASSERTION: Both myses should be in Stopped state (NOT Errored)
111- if long.State() != MysisStateStopped {
112- t.Errorf("PRODUCTION BUG REPRODUCED: long state=%s (expected stopped), lastError=%v",
113- long.State(), long.LastError())
114- }
115- if sleepy.State() != MysisStateStopped {
116- t.Errorf("PRODUCTION BUG REPRODUCED: sleepy state=%s (expected stopped), lastError=%v",
117- sleepy.State(), sleepy.LastError())
118- }
119-
120- // Verify no errors were set
121- if long.LastError() != nil {
122- t.Errorf("long should have no error after clean stop, got: %v", long.LastError())
123- }
124- if sleepy.LastError() != nil {
125- t.Errorf("sleepy should have no error after clean stop, got: %v", sleepy.LastError())
126- }
127-
128- // Verify WaitGroup completed (no goroutine leaks)
129- // This is implicit in StopAll() completing, but verify explicitly
130- done := make(chan struct{})
131- go func() {
132- cmd.wg.Wait()
133- close(done)
134- }()
135-
136- select {
137- case <-done:
138- // WaitGroup completed - no goroutine leaks
139- case <-time.After(1 * time.Second):
140- t.Error("WaitGroup did not complete - goroutine leak detected")
141- }
142-}
143-
144-// TestMultipleMysesStoppingSimultaneously tests the scenario where
145-// multiple myses are stopped at exactly the same time.
146-//
147-// This validates:
148-// - No race conditions in Stop()
149-// - No deadlocks when multiple Stop() calls happen simultaneously
150-// - All myses reach state=stopped
151-//
152-// Run with:
153-//
154-// go test ./internal/core -run TestMultipleMysesStoppingSimultaneously -v -count=10
155-func TestMultipleMysesStoppingSimultaneously(t *testing.T) {
156- s, bus, cleanup := setupMysisTest(t)
157- defer cleanup()
158-
159- reg := provider.NewRegistry()
160- cfg := &config.Config{
161- Swarm: config.SwarmConfig{MaxMyses: 10},
162- Providers: map[string]config.ProviderConfig{
163- "mock": {Model: "test-model", Temperature: 0.7},
164- },
165- }
166-
167- cmd := NewCommander(s, reg, bus, cfg, "")
168-
169- // Create 5 myses
170- myses := make([]*Mysis, 5)
171- for i := 0; i < 5; i++ {
172- mock := provider.NewMock(fmt.Sprintf("mock-%d", i), "response")
173- stored, _ := s.CreateMysis(fmt.Sprintf("mysis-%d", i), "mock", "test-model", 0.7)
174- mysis := NewMysis(stored.ID, stored.Name, stored.CreatedAt, mock, s, bus, "", cmd)
175- myses[i] = mysis
176-
177- cmd.mu.Lock()
178- cmd.myses[stored.ID] = mysis
179- cmd.mu.Unlock()
180-
181- if err := mysis.Start(); err != nil {
182- t.Fatalf("Start(mysis-%d) error: %v", i, err)
183- }
184- }
185-
186- // Wait for myses to stabilize
187- time.Sleep(100 * time.Millisecond)
188-
189- // Stop all myses simultaneously
190- var wg sync.WaitGroup
191- errors := make([]error, 5)
192-
193- for i := 0; i < 5; i++ {
194- wg.Add(1)
195- go func(idx int) {
196- defer wg.Done()
197- errors[idx] = myses[idx].Stop()
198- }(i)
199- }
200-
201- // Wait for all stops to complete
202- done := make(chan struct{})
203- go func() {
204- wg.Wait()
205- close(done)
206- }()
207-
208- select {
209- case <-done:
210- // All stops completed
211- case <-time.After(5 * time.Second):
212- t.Fatal("timeout waiting for simultaneous stops - possible deadlock")
213- }
214-
215- // Verify all stopped successfully
216- for i := 0; i < 5; i++ {
217- if errors[i] != nil {
218- t.Errorf("mysis-%d Stop() error: %v", i, errors[i])
219- }
220- if myses[i].State() != MysisStateStopped {
221- t.Errorf("mysis-%d state=%s (expected stopped), lastError=%v",
222- i, myses[i].State(), myses[i].LastError())
223- }
224- if myses[i].LastError() != nil {
225- t.Errorf("mysis-%d should have no error, got: %v", i, myses[i].LastError())
226- }
227- }
228-}
229-
230-// TestStopDuringActiveLLMCalls tests stopping myses while they are
231-// actively processing LLM calls.
232-//
233-// This validates:
234-// - Stop() waits for active LLM calls to complete
235-// - Context cancellation is handled gracefully
236-// - Final state is stopped (NOT errored)
237-//
238-// Run with:
239-//
240-// go test ./internal/core -run TestStopDuringActiveLLMCalls -v -count=10
241-func TestStopDuringActiveLLMCalls(t *testing.T) {
242- s, bus, cleanup := setupMysisTest(t)
243- defer cleanup()
244-
245- stored, _ := s.CreateMysis("active-call", "mock", "test-model", 0.7)
246-
247- // Mock with delay to simulate active LLM call
248- mock := provider.NewMock("mock", "response").SetDelay(200 * time.Millisecond)
249- mysis := NewMysis(stored.ID, stored.Name, stored.CreatedAt, mock, s, bus, "")
250-
251- if err := mysis.Start(); err != nil {
252- t.Fatalf("Start() error: %v", err)
253- }
254-
255- // Wait for initial turn (triggered by encouragement message) to complete
256- time.Sleep(100 * time.Millisecond)
257-
258- // Send a message that will take 200ms to process
259- messageDone := make(chan struct{})
260- go func() {
261- _ = mysis.SendMessage("slow message", store.MemorySourceDirect)
262- close(messageDone)
263- }()
264-
265- // Wait to ensure message processing started
266- time.Sleep(100 * time.Millisecond)
267-
268- // Stop while LLM is processing
269- start := time.Now()
270- if err := mysis.Stop(); err != nil {
271- t.Fatalf("Stop() error: %v", err)
272- }
273- elapsed := time.Since(start)
274-
275- // Stop should complete within reasonable time
276- // It may wait for the current turn or cancel immediately - both are acceptable
277- if elapsed > 1*time.Second {
278- t.Errorf("Stop took too long (%s) - possible deadlock", elapsed)
279- }
280-
281- // Verify final state
282- if mysis.State() != MysisStateStopped {
283- t.Errorf("expected state=stopped, got %s (lastError=%v)", mysis.State(), mysis.LastError())
284- }
285- if mysis.LastError() != nil {
286- t.Errorf("expected no error after Stop during active call, got: %v", mysis.LastError())
287- }
288-}
289-
290-// TestStopWithQueuedMessages tests stopping a mysis that has queued messages
291-// waiting to be processed.
292-//
293-// This validates:
294-// - Queued messages are not processed after Stop()
295-// - No deadlock when stopping with queued messages
296-// - Final state is stopped
297-//
298-// Run with:
299-//
300-// go test ./internal/core -run TestStopWithQueuedMessages -v -count=10
301-func TestStopWithQueuedMessages(t *testing.T) {
302- s, bus, cleanup := setupMysisTest(t)
303- defer cleanup()
304-
305- stored, _ := s.CreateMysis("queued", "mock", "test-model", 0.7)
306-
307- // Mock with delay to create queue pressure
308- mock := provider.NewMock("mock", "response").SetDelay(100 * time.Millisecond)
309- mysis := NewMysis(stored.ID, stored.Name, stored.CreatedAt, mock, s, bus, "")
310-
311- if err := mysis.Start(); err != nil {
312- t.Fatalf("Start() error: %v", err)
313- }
314-
315- // Queue multiple messages rapidly
316- // Only one will process at a time due to turnMu
317- for i := 0; i < 5; i++ {
318- go func(idx int) {
319- _ = mysis.SendMessage(fmt.Sprintf("queued-%d", idx), store.MemorySourceDirect)
320- }(i)
321- }
322-
323- // Wait a bit to let some messages queue
324- time.Sleep(50 * time.Millisecond)
325-
326- // Stop while messages are queued
327- if err := mysis.Stop(); err != nil {
328- t.Fatalf("Stop() error: %v", err)
329- }
330-
331- // Verify final state
332- if mysis.State() != MysisStateStopped {
333- t.Errorf("expected state=stopped, got %s (lastError=%v)", mysis.State(), mysis.LastError())
334- }
335- if mysis.LastError() != nil {
336- t.Errorf("expected no error, got: %v", mysis.LastError())
337- }
338-
339- // Verify no further messages can be sent
340- err := mysis.SendMessage("after-stop", store.MemorySourceDirect)
341- if err == nil {
342- t.Error("expected error sending message to stopped mysis")
343- } else {
344- if !strings.Contains(err.Error(), "stopped") || !strings.Contains(err.Error(), "relaunch") {
345- t.Errorf("expected error about stopped state requiring relaunch, got: %v", err)
346- }
347- }
348-}
349-
350-// TestCleanExitAfterStop tests that the app can exit cleanly after StopAll.
351-//
352-// This validates:
353-// - EventBus can be closed after StopAll
354-// - Store can be closed after StopAll
355-// - No goroutines block cleanup
356-// - No panic during cleanup
357-//
358-// Run with:
359-//
360-// go test ./internal/core -run TestCleanExitAfterStop -v -count=10
361-func TestCleanExitAfterStop(t *testing.T) {
362- tmpDir := t.TempDir()
363- dbPath := filepath.Join(tmpDir, "test.db")
364- s, err := store.Open(dbPath)
365- if err != nil {
366- t.Fatalf("Open() error: %v", err)
367- }
368-
369- bus := NewEventBus(100)
370-
371- reg := provider.NewRegistry()
372- cfg := &config.Config{
373- Swarm: config.SwarmConfig{MaxMyses: 10},
374- Providers: map[string]config.ProviderConfig{
375- "mock": {Model: "test-model", Temperature: 0.7},
376- },
377- }
378-
379- cmd := NewCommander(s, reg, bus, cfg, "")
380-
381- // Create and start multiple myses
382- for i := 0; i < 3; i++ {
383- mock := provider.NewMock(fmt.Sprintf("mock-%d", i), "response")
384- stored, _ := s.CreateMysis(fmt.Sprintf("exit-test-%d", i), "mock", "test-model", 0.7)
385- mysis := NewMysis(stored.ID, stored.Name, stored.CreatedAt, mock, s, bus, "", cmd)
386-
387- cmd.mu.Lock()
388- cmd.myses[stored.ID] = mysis
389- cmd.mu.Unlock()
390-
391- if err := mysis.Start(); err != nil {
392- t.Fatalf("Start() error: %v", err)
393- }
394- }
395-
396- // Wait for myses to stabilize
397- time.Sleep(100 * time.Millisecond)
398-
399- // Stop all myses
400- cmd.StopAll()
401-
402- // Now perform cleanup (this is what main.go does)
403- // If this hangs or panics, we have a problem
404- done := make(chan struct{})
405- go func() {
406- bus.Close()
407- s.Close()
408- close(done)
409- }()
410-
411- select {
412- case <-done:
413- // Clean exit successful
414- case <-time.After(2 * time.Second):
415- t.Fatal("cleanup hung - possible goroutine leak or deadlock")
416- }
417-}
418-
419-// TestStopAllWithMixedStates tests StopAll when myses are in different states.
420-//
421-// This validates:
422-// - StopAll handles idle myses correctly
423-// - StopAll skips already-stopped myses
424-// - StopAll doesn't affect errored myses
425-// - No panic when calling Stop on non-running myses
426-//
427-// Run with:
428-//
429-// go test ./internal/core -run TestStopAllWithMixedStates -v -count=10
430-func TestStopAllWithMixedStates(t *testing.T) {
431- s, bus, cleanup := setupMysisTest(t)
432- defer cleanup()
433-
434- reg := provider.NewRegistry()
435- cfg := &config.Config{
436- Swarm: config.SwarmConfig{MaxMyses: 10},
437- Providers: map[string]config.ProviderConfig{
438- "mock": {Model: "test-model", Temperature: 0.7},
439- },
440- }
441-
442- cmd := NewCommander(s, reg, bus, cfg, "")
443-
444- // Create myses in different states
445- // 1. Running
446- runningStored, _ := s.CreateMysis("running", "mock", "test-model", 0.7)
447- runningMock := provider.NewMock("mock-running", "response")
448- running := NewMysis(runningStored.ID, runningStored.Name, runningStored.CreatedAt, runningMock, s, bus, "", cmd)
449- cmd.mu.Lock()
450- cmd.myses[runningStored.ID] = running
451- cmd.mu.Unlock()
452- running.Start()
453-
454- // 2. Idle (never started)
455- idleStored, _ := s.CreateMysis("idle", "mock", "test-model", 0.7)
456- idleMock := provider.NewMock("mock-idle", "response")
457- idle := NewMysis(idleStored.ID, idleStored.Name, idleStored.CreatedAt, idleMock, s, bus, "", cmd)
458- cmd.mu.Lock()
459- cmd.myses[idleStored.ID] = idle
460- cmd.mu.Unlock()
461-
462- // 3. Already stopped
463- stoppedStored, _ := s.CreateMysis("stopped", "mock", "test-model", 0.7)
464- stoppedMock := provider.NewMock("mock-stopped", "response")
465- stopped := NewMysis(stoppedStored.ID, stoppedStored.Name, stoppedStored.CreatedAt, stoppedMock, s, bus, "", cmd)
466- cmd.mu.Lock()
467- cmd.myses[stoppedStored.ID] = stopped
468- cmd.mu.Unlock()
469- stopped.Start()
470- stopped.Stop()
471-
472- // Wait for states to stabilize
473- time.Sleep(100 * time.Millisecond)
474-
475- // Call StopAll - should handle mixed states gracefully
476- start := time.Now()
477- cmd.StopAll()
478- elapsed := time.Since(start)
479-
480- if elapsed > 5*time.Second {
481- t.Errorf("StopAll took %s (expected < 5s)", elapsed)
482- }
483-
484- // Verify states
485- if running.State() != MysisStateStopped {
486- t.Errorf("running mysis state=%s (expected stopped)", running.State())
487- }
488- if idle.State() != MysisStateIdle {
489- t.Errorf("idle mysis state=%s (expected idle)", idle.State())
490- }
491- if stopped.State() != MysisStateStopped {
492- t.Errorf("stopped mysis state=%s (expected stopped)", stopped.State())
493- }
494-
495- // Verify no errors
496- if running.LastError() != nil {
497- t.Errorf("running mysis error: %v", running.LastError())
498- }
499- if idle.LastError() != nil {
500- t.Errorf("idle mysis error: %v", idle.LastError())
501- }
502- if stopped.LastError() != nil {
503- t.Errorf("stopped mysis error: %v", stopped.LastError())
504- }
505-}
506-
507-// TestStopAllStressTest performs repeated StopAll operations to detect
508-// rare race conditions and timing issues.
509-//
510-// Run with:
511-//
512-// go test ./internal/core -run TestStopAllStressTest -v -count=20
513-func TestStopAllStressTest(t *testing.T) {
514- for iteration := 0; iteration < 5; iteration++ {
515- t.Run(fmt.Sprintf("iteration_%d", iteration), func(t *testing.T) {
516- tmpDir := t.TempDir()
517- dbPath := filepath.Join(tmpDir, "test.db")
518- s, err := store.Open(dbPath)
519- if err != nil {
520- t.Fatalf("Open() error: %v", err)
521- }
522- defer s.Close()
523-
524- bus := NewEventBus(100)
525- defer bus.Close()
526-
527- reg := provider.NewRegistry()
528- cfg := &config.Config{
529- Swarm: config.SwarmConfig{MaxMyses: 10},
530- Providers: map[string]config.ProviderConfig{
531- "mock": {Model: "test-model", Temperature: 0.7},
532- },
533- }
534-
535- cmd := NewCommander(s, reg, bus, cfg, "")
536-
537- // Create multiple myses
538- for i := 0; i < 3; i++ {
539- mock := provider.NewMock(fmt.Sprintf("mock-%d", i), "response")
540- stored, _ := s.CreateMysis(fmt.Sprintf("stress-%d", i), "mock", "test-model", 0.7)
541- mysis := NewMysis(stored.ID, stored.Name, stored.CreatedAt, mock, s, bus, "", cmd)
542-
543- cmd.mu.Lock()
544- cmd.myses[stored.ID] = mysis
545- cmd.mu.Unlock()
546-
547- if err := mysis.Start(); err != nil {
548- t.Fatalf("Start() error: %v", err)
549- }
550-
551- // Send some messages to simulate activity
552- go func() {
553- _ = mysis.SendMessage("stress test", store.MemorySourceDirect)
554- }()
555- }
556-
557- // Random sleep to vary timing
558- time.Sleep(time.Duration(50+iteration*20) * time.Millisecond)
559-
560- // StopAll
561- start := time.Now()
562- cmd.StopAll()
563- elapsed := time.Since(start)
564-
565- if elapsed > 10*time.Second {
566- t.Errorf("iteration %d: StopAll timeout (%s)", iteration, elapsed)
567- }
568-
569- // Verify all myses are stopped
570- cmd.mu.RLock()
571- for id, mysis := range cmd.myses {
572- state := mysis.State()
573- // Running myses should now be stopped
574- // Idle myses remain idle
575- if state != MysisStateStopped && state != MysisStateIdle {
576- t.Errorf("iteration %d: mysis %s state=%s (expected stopped or idle), lastError=%v",
577- iteration, id, state, mysis.LastError())
578- }
579- }
580- cmd.mu.RUnlock()
581- })
582- }
583-}
internal/core/mysis.go+0−18
@@ -521,9 +521,6 @@ func (m *Mysis) Stop() error {
521521 a.cancel = nil
522522 a.mu.Unlock()
523523
524- // Release resources
525- a.releaseCurrentAccount()
526-
527524 // Close provider HTTP client
528525 if a.provider != nil {
529526 if err := a.provider.Close(); err != nil {
@@ -646,7 +643,6 @@ func (m *Mysis) SendMessageFrom(content string, source store.MemorySource, sende
646643 Str("mysis", a.name).
647644 Err(err).
648645 Msg("MCP connection lost - releasing account")
649- a.releaseCurrentAccount()
650646 if rebuildErr := a.rebuildSystemMemory(); rebuildErr != nil {
651647 log.Error().Err(rebuildErr).Msg("failed to rebuild system memory after MCP session loss")
652648 }
@@ -1104,7 +1100,6 @@ func (m *Mysis) executeToolCall(ctx context.Context, mcpProxy *mcp.Proxy, tc pro
11041100 Str("tool", tc.Name).
11051101 Err(err).
11061102 Msg("MCP connection lost during tool call - releasing account")
1107- a.releaseCurrentAccount()
11081103 if rebuildErr := a.rebuildSystemMemory(); rebuildErr != nil {
11091104 log.Error().Err(rebuildErr).Msg("failed to rebuild system memory after MCP session loss")
11101105 }
@@ -1141,13 +1136,6 @@ func (m *Mysis) executeToolCall(ctx context.Context, mcpProxy *mcp.Proxy, tc pro
11411136 log.Error().Err(err).Msg("failed to rebuild system memory after login")
11421137 }
11431138 }
1144- case "logout":
1145- a.releaseCurrentAccount()
1146-
1147- // Rebuild system prompt to clear credentials
1148- if err := a.rebuildSystemMemory(); err != nil {
1149- log.Error().Err(err).Msg("failed to rebuild system memory after logout")
1150- }
11511139 }
11521140 }
11531141
@@ -1392,9 +1380,6 @@ func (m *Mysis) setError(err error) {
13921380 // Emit state change event
13931381 a.emitStateChange(oldState, MysisStateErrored)
13941382
1395- // Release account (if any) to allow restart
1396- a.releaseCurrentAccount()
1397-
13981383 // Emit error event
13991384 a.publishCriticalEvent(Event{
14001385 Type: EventMysisError,
@@ -2477,9 +2462,6 @@ func (m *Mysis) setErrorState(err error) {
24772462 }
24782463 a.emitStateChange(oldState, MysisStateErrored)
24792464
2480- // Release account (if any) to allow restart
2481- a.releaseCurrentAccount()
2482-
24832465 a.publishCriticalEvent(Event{
24842466 Type: EventMysisError,
24852467 MysisID: a.id,
internal/core/mysis_context_cancel_test.go+0−161
@@ -1,161 +0,0 @@
1-package core
2-
3-import (
4- "context"
5- "testing"
6- "time"
7-)
8-
9-// TestContextCancellationPropagation verifies that when Stop() cancels the parent context,
10-// the child context in SendMessageFrom() receives the cancellation signal.
11-func TestContextCancellationPropagation(t *testing.T) {
12- t.Run("parent cancel propagates to child", func(t *testing.T) {
13- // Create parent context
14- parent, parentCancel := context.WithCancel(context.Background())
15- defer parentCancel()
16-
17- // Create child with timeout (same pattern as SendMessageFrom line 385)
18- child, childCancel := context.WithTimeout(parent, 5*time.Second)
19- defer childCancel()
20-
21- // Cancel parent (simulates Stop() line 284)
22- parentCancel()
23-
24- // Verify child receives cancellation
25- select {
26- case <-child.Done():
27- // SUCCESS: Child context canceled when parent canceled
28- if err := child.Err(); err != context.Canceled {
29- t.Errorf("expected context.Canceled, got %v", err)
30- }
31- case <-time.After(100 * time.Millisecond):
32- t.Fatal("BUG: Child context not canceled after parent cancel")
33- }
34- })
35-
36- t.Run("child timeout does not affect parent", func(t *testing.T) {
37- // Create parent context
38- parent, parentCancel := context.WithCancel(context.Background())
39- defer parentCancel()
40-
41- // Create child with very short timeout
42- child, childCancel := context.WithTimeout(parent, 1*time.Millisecond)
43- defer childCancel()
44-
45- // Wait for child timeout
46- <-child.Done()
47- if err := child.Err(); err != context.DeadlineExceeded {
48- t.Errorf("expected context.DeadlineExceeded, got %v", err)
49- }
50-
51- // Verify parent is still alive
52- select {
53- case <-parent.Done():
54- t.Fatal("BUG: Parent context canceled when child timed out")
55- case <-time.After(10 * time.Millisecond):
56- // SUCCESS: Parent context still alive
57- }
58- })
59-}
60-
61-// TestContextCancellationInProvider verifies that the mock provider respects context cancellation.
62-func TestContextCancellationInProvider(t *testing.T) {
63- t.Run("provider respects canceled context", func(t *testing.T) {
64- // Create mock provider with delay
65- mock := NewMockProvider("test", "response").SetDelay(2 * time.Second)
66-
67- // Create context and cancel it
68- ctx, cancel := context.WithCancel(context.Background())
69- cancel() // Cancel immediately
70-
71- // Call provider - should fail quickly
72- start := time.Now()
73- _, err := mock.Chat(ctx, nil)
74- elapsed := time.Since(start)
75-
76- // Verify it failed due to cancellation
77- if err == nil {
78- t.Fatal("expected error from canceled context")
79- }
80- if err != context.Canceled {
81- t.Errorf("expected context.Canceled, got %v", err)
82- }
83-
84- // Verify it didn't wait full delay
85- if elapsed > 500*time.Millisecond {
86- t.Errorf("provider took %v, expected quick failure on canceled context", elapsed)
87- }
88- })
89-
90- t.Run("provider respects context canceled during delay", func(t *testing.T) {
91- // Create mock provider with delay
92- mock := NewMockProvider("test", "response").SetDelay(2 * time.Second)
93-
94- // Create context
95- ctx, cancel := context.WithCancel(context.Background())
96-
97- // Start provider call
98- start := time.Now()
99- errCh := make(chan error, 1)
100- go func() {
101- _, err := mock.Chat(ctx, nil)
102- errCh <- err
103- }()
104-
105- // Cancel after 100ms
106- time.Sleep(100 * time.Millisecond)
107- cancel()
108-
109- // Wait for result
110- err := <-errCh
111- elapsed := time.Since(start)
112-
113- // Verify it failed due to cancellation
114- if err == nil {
115- t.Fatal("expected error from canceled context")
116- }
117- if err != context.Canceled {
118- t.Errorf("expected context.Canceled, got %v", err)
119- }
120-
121- // Verify it didn't wait full delay
122- if elapsed > 500*time.Millisecond {
123- t.Errorf("provider took %v, expected quick failure after cancel", elapsed)
124- }
125- })
126-}
127-
128-// Helper to create a mock provider for testing
129-func NewMockProvider(name, response string) *MockProvider {
130- return &MockProvider{
131- name: name,
132- response: response,
133- }
134-}
135-
136-// MockProvider is a minimal mock for testing context cancellation
137-type MockProvider struct {
138- name string
139- response string
140- delay time.Duration
141-}
142-
143-func (p *MockProvider) SetDelay(d time.Duration) *MockProvider {
144- p.delay = d
145- return p
146-}
147-
148-func (p *MockProvider) Chat(ctx context.Context, messages interface{}) (string, error) {
149- if p.delay > 0 {
150- timer := time.NewTimer(p.delay)
151- defer timer.Stop()
152-
153- select {
154- case <-ctx.Done():
155- return "", ctx.Err()
156- case <-timer.C:
157- return p.response, nil
158- }
159- }
160- return p.response, nil
161-}
internal/core/mysis_context_integration_test.go+0−178
@@ -1,178 +0,0 @@
1-package core
2-
3-import (
4- "context"
5- "testing"
6- "time"
7-
8- "github.com/xonecas/zoea-nova/internal/provider"
9-)
10-
11-// TestMysisContextCancellationIntegration verifies that Stop() cancels the context
12-// used by SendMessageFrom(), causing in-flight provider calls to abort.
13-func TestMysisContextCancellationIntegration(t *testing.T) {
14- t.Run("Stop cancels in-flight SendMessageFrom", func(t *testing.T) {
15- // Setup
16- s, bus, cleanup := setupMysisTest(t)
17- defer cleanup()
18-
19- // Create mysis with provider that has 2s delay (respects context cancellation)
20- mock := provider.NewMock("mock", "response").SetDelay(2 * time.Second)
21- stored, err := s.CreateMysis("test-mysis", "ollama", "test-model", 0.7)
22- if err != nil {
23- t.Fatalf("CreateMysis error: %v", err)
24- }
25- m := NewMysis(stored.ID, stored.Name, stored.CreatedAt, mock, s, bus, "")
26-
27- // Start mysis (will add system prompt automatically)
28- // Note: Myses don't have autonomous loops - they only respond to messages
29- if err := m.Start(); err != nil {
30- t.Fatalf("Start() error: %v", err)
31- }
32-
33- // Send message that will take 2 seconds
34- errCh := make(chan error, 1)
35- start := time.Now()
36- go func() {
37- err := m.SendMessageFrom("user", "", "test message")
38- errCh <- err
39- }()
40-
41- // Wait 100ms to ensure SendMessageFrom is in provider call
42- time.Sleep(100 * time.Millisecond)
43-
44- // Stop should cancel the context
45- stopStart := time.Now()
46- if err := m.Stop(); err != nil {
47- t.Fatalf("Stop() error: %v", err)
48- }
49- stopElapsed := time.Since(stopStart)
50-
51- // Get SendMessageFrom result
52- sendErr := <-errCh
53- totalElapsed := time.Since(start)
54-
55- // VERIFICATION 1: SendMessageFrom should fail with context canceled error
56- if sendErr == nil {
57- t.Error("expected SendMessageFrom to fail after Stop()")
58- } else if sendErr != nil {
59- // Check if error is context cancellation related
60- if !isContextError(sendErr) {
61- t.Logf("SendMessageFrom error (not context related): %v", sendErr)
62- // This is acceptable - might be due to state change
63- } else {
64- t.Logf("SendMessageFrom correctly failed with context error: %v", sendErr)
65- }
66- }
67-
68- // VERIFICATION 2: Total time should be much less than 2s (provider delay)
69- // If context cancellation worked, it should abort within ~100-500ms
70- if totalElapsed > 1*time.Second {
71- t.Errorf("SendMessageFrom took %v, expected quick failure after Stop() (context should cancel provider call)", totalElapsed)
72- } else {
73- t.Logf("SUCCESS: SendMessageFrom aborted in %v (well before 2s provider delay)", totalElapsed)
74- }
75-
76- // VERIFICATION 3: Stop() should complete quickly
77- if stopElapsed > 5*time.Second {
78- t.Errorf("Stop() took %v, expected completion within timeout", stopElapsed)
79- }
80-
81- // VERIFICATION 4: State should be Stopped
82- if m.State() != MysisStateStopped {
83- t.Errorf("expected state Stopped, got %v", m.State())
84- }
85- })
86-
87- t.Run("Stop without in-flight calls completes immediately", func(t *testing.T) {
88- // Setup
89- s, bus, cleanup := setupMysisTest(t)
90- defer cleanup()
91-
92- mock := provider.NewMock("mock", "response")
93- stored, err := s.CreateMysis("test-mysis", "ollama", "test-model", 0.7)
94- if err != nil {
95- t.Fatalf("CreateMysis error: %v", err)
96- }
97- m := NewMysis(stored.ID, stored.Name, stored.CreatedAt, mock, s, bus, "")
98-
99- // Start mysis
100- // Note: Myses don't have autonomous loops - they only respond to messages
101- if err := m.Start(); err != nil {
102- t.Fatalf("Start() error: %v", err)
103- }
104-
105- // Stop without any in-flight calls
106- start := time.Now()
107- if err := m.Stop(); err != nil {
108- t.Fatalf("Stop() error: %v", err)
109- }
110- elapsed := time.Since(start)
111-
112- // Should complete almost immediately
113- if elapsed > 100*time.Millisecond {
114- t.Errorf("Stop() took %v, expected immediate completion", elapsed)
115- }
116-
117- if m.State() != MysisStateStopped {
118- t.Errorf("expected state Stopped, got %v", m.State())
119- }
120- })
121-}
122-
123-// isContextError checks if error is context.Canceled or context.DeadlineExceeded
124-func isContextError(err error) bool {
125- return err == context.Canceled || err == context.DeadlineExceeded ||
Cut short: this commit's diff is over 1000 lines.
internal/core/mysis_helpers_test.go+0−272
Cut short: this commit's diff is over 1000 lines.
internal/core/mysis_race_test.go+0−172
Cut short: this commit's diff is over 1000 lines.
internal/core/mysis_real_provider_test.go+0−139
Cut short: this commit's diff is over 1000 lines.
internal/core/mysis_stop_race_aggressive_test.go+0−201
Cut short: this commit's diff is over 1000 lines.
internal/core/mysis_stop_race_instrumented_test.go+0−346
Cut short: this commit's diff is over 1000 lines.
internal/core/notifications_test.go+0−811
Cut short: this commit's diff is over 1000 lines.
internal/core/orphaned_tool_results_test.go+0−560
Cut short: this commit's diff is over 1000 lines.
internal/core/state_machine_test.go+0−663
Cut short: this commit's diff is over 1000 lines.
internal/core/tick_integration_test.go+0−354
Cut short: this commit's diff is over 1000 lines.
internal/integration/broadcast_sender_test.go+0−128
Cut short: this commit's diff is over 1000 lines.
internal/integration/login_flow_test.go+0−270
Cut short: this commit's diff is over 1000 lines.
internal/integration/mysis_creation_zen_nano_test.go+0−92
Cut short: this commit's diff is over 1000 lines.
internal/integration/zen_nano_failure_test.go+0−107
Cut short: this commit's diff is over 1000 lines.
internal/mcp/proxy_test.go+0−30
Cut short: this commit's diff is over 1000 lines.
internal/store/store_test.go+0−564
Cut short: this commit's diff is over 1000 lines.