| 1 | package control |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "sync/atomic" |
| 6 | "testing" |
| 7 | |
| 8 | "reasonix/internal/hook" |
| 9 | ) |
| 10 | |
| 11 | // TestCloseIsIdempotent guards the desktop tab-lifecycle contract: rebind, |
| 12 | // model switch, CloseTab, and shutdown can race to Close the same controller, |
| 13 | // so a duplicate Close must not re-fire SessionEnd hooks or re-run cleanup. |
| 14 | func TestCloseIsIdempotent(t *testing.T) { |
| 15 | var sessionEnds atomic.Int32 |
| 16 | hooks := hook.NewRunner([]hook.ResolvedHook{{ |
| 17 | HookConfig: hook.HookConfig{Command: "session-end"}, |
| 18 | Event: hook.SessionEnd, |
| 19 | Scope: hook.ScopeGlobal, |
| 20 | }}, t.TempDir(), func(context.Context, hook.SpawnInput) hook.SpawnResult { |
| 21 | sessionEnds.Add(1) |
| 22 | return hook.SpawnResult{ExitCode: 0} |
| 23 | }, nil) |
| 24 | c := New(Options{Runner: &fakeTurnRunner{}, Hooks: hooks}) |
| 25 | // A completed turn arms startedOnce so SessionEnd is eligible to fire. |
| 26 | if err := c.Run(context.Background(), "hi"); err != nil { |
| 27 | t.Fatal(err) |
| 28 | } |
| 29 | |
| 30 | done := make(chan struct{}) |
| 31 | go func() { |
| 32 | c.Close() |
| 33 | close(done) |
| 34 | }() |
| 35 | c.Close() |
| 36 | <-done |
| 37 | |
| 38 | if got := sessionEnds.Load(); got != 1 { |
| 39 | t.Fatalf("SessionEnd hooks fired %d times across concurrent Close calls, want 1", got) |
| 40 | } |
| 41 | } |
| 42 |