| 1 | package cdp |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "strings" |
| 6 | "testing" |
| 7 | "time" |
| 8 | |
| 9 | "reasonix/internal/browser" |
| 10 | ) |
| 11 | |
| 12 | func TestLazyAttachesOnFirstUseOnly(t *testing.T) { |
| 13 | f := newFakeBrowser(t) |
| 14 | lazy := NewLazy(Options{Endpoint: f.srv.URL, ArtifactDir: t.TempDir(), NavigateTimeout: 5 * time.Second}) |
| 15 | t.Cleanup(lazy.Shutdown) |
| 16 | ctx := context.Background() |
| 17 | |
| 18 | if !lazy.Available(ctx) { |
| 19 | t.Fatal("a configured but unattached browser must stay visible") |
| 20 | } |
| 21 | if f.countCalls("Browser.setDownloadBehavior") != 0 { |
| 22 | t.Fatal("the browser was attached before any tool call") |
| 23 | } |
| 24 | if _, err := lazy.Tabs(ctx); err != nil { |
| 25 | t.Fatalf("tabs: %v", err) |
| 26 | } |
| 27 | if f.countCalls("Browser.setDownloadBehavior") != 1 { |
| 28 | t.Fatal("the first tool call did not attach the browser") |
| 29 | } |
| 30 | if _, err := lazy.Tabs(ctx); err != nil { |
| 31 | t.Fatalf("second tabs: %v", err) |
| 32 | } |
| 33 | if got := f.countCalls("Browser.setDownloadBehavior"); got != 1 { |
| 34 | t.Fatalf("attached %d times, want once", got) |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | func TestLazyReportsAStartFailureWithoutRetrying(t *testing.T) { |
| 39 | // A loopback port nothing listens on: the probe fails fast and for a |
| 40 | // reason the model can act on. |
| 41 | lazy := NewLazy(Options{Endpoint: "http://127.0.0.1:1", ArtifactDir: t.TempDir(), LaunchTimeout: 300 * time.Millisecond}) |
| 42 | t.Cleanup(lazy.Shutdown) |
| 43 | ctx := context.Background() |
| 44 | |
| 45 | _, first := lazy.Tabs(ctx) |
| 46 | if first == nil { |
| 47 | t.Fatal("an unreachable endpoint attached anyway") |
| 48 | } |
| 49 | if !strings.Contains(first.Error(), "DevTools") { |
| 50 | t.Fatalf("start failure = %v, want a DevTools endpoint diagnosis", first) |
| 51 | } |
| 52 | started := time.Now() |
| 53 | _, second := lazy.Open(ctx, browser.OpenRequest{OperationID: "op-1", URL: "https://example.test/"}) |
| 54 | if second == nil || second.Error() != first.Error() { |
| 55 | t.Fatalf("second call = %v, want the remembered start failure %v", second, first) |
| 56 | } |
| 57 | if elapsed := time.Since(started); elapsed > 200*time.Millisecond { |
| 58 | t.Fatalf("the second call waited %s, so it retried the launch", elapsed) |
| 59 | } |
| 60 | if lazy.Available(ctx) { |
| 61 | t.Fatal("a browser that cannot start still reports itself available") |
| 62 | } |
| 63 | } |
| 64 |