Repository navigation
Expand file tree
/
Copy pathdevbrowser.go
More file actions
executable file
·461 lines (384 loc) · 12.5 KB
/
Copy pathdevbrowser.go
File metadata and controls
executable file
·461 lines (384 loc) · 12.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
package devbrowser
import (
"context"
"errors"
"sync"
"sync/atomic"
"time"
"webtyp.com/devbrowser/cdproto/cdp"
"webtyp.com/devbrowser/chromedp"
"webtyp.com/lang"
)
type Store interface {
Get(key string) (string, error)
Set(key, value string) error
}
type UserInterface interface {
RefreshUI()
ReturnFocus() error
}
type DevBrowser struct {
UI UserInterface
Width int // ej "800" default "1024"
Height int //ej: "600" default "768"
Position string //ej: "1930,0" (when you have second monitor) default: "0,0"
Headless bool // true para modo headless (sin UI), false muestra el navegador
AutoStart bool // true if browser should auto-open on startup
MonitorWidth int // Detected monitor availability width
MonitorHeight int // Detected monitor availability height
SizeConfigured bool // Track if size was loaded from storage
// TrustDevCertSPKI is the base64-encoded SHA-256 of a development certificate's
// SubjectPublicKeyInfo. When set, the launched browser trusts exactly that
// public key; verification stays on for every other origin.
//
// Obtain it from webtyp.com/server/httpd.LocalCertSPKI(). Empty = no pin.
TrustDevCertSPKI string
// ResolveTrustDevCertSPKI, when set, is called at each browser launch so a rotated
// local dev certificate is picked up without restarting the daemon.
ResolveTrustDevCertSPKI func() (string, error)
// DevToolsReserved is true when auto-open-devtools-for-tabs was launched
// for this session (context.go decides this once, at CreateBrowserContext
// time, based on the window width at launch). Later window growth does not
// retroactively open or close DevTools, so this flag is a session-long
// snapshot, not a live query — CDP exposes no way to read DevTools' actual
// panel bounds.
DevToolsReserved bool
ViewportMode string // Current emulation mode ("mobile", "tablet", "desktop", "off", "")
ViewportDevice string // Current emulation device name (e.g. "iphone15promax")
FirstCall bool // Internal flag to track if OpenBrowser was called for the first time
OpenedOnce bool // Internal flag to track if browser was actually opened at least once
LastPort string
LastHttps bool
LastURL string
SourceLocator SourceLocator
selections selectionHistory // guarded by Mu
lastPanelNodeID cdp.BackendNodeID // guarded by Mu; last DevTools panel node captured
prevPerf *perfSnapshot // guarded by Mu; previous browser_get_performance reading
captureMu sync.Mutex // serializes captureSelection
IsOpenFlag bool // Indica si el navegador está abierto
// ready is true only AFTER the initial open fully completed (browser
// allocated + navigated). IsOpenFlag is set optimistically before the async
// open finishes, so it is NOT a safe signal for issuing chromedp actions:
// running an action (e.g. Reload) on the context before the first allocation
// returns makes chromedp allocate a SECOND browser -> double window.
ready bool
// pendingReload remembers that a reload was requested while the browser
// was still opening. Discarding that request left the initial rendered content
// in an incomplete state until manual reload.
pendingReload bool
// guard reloads the page when the dev server cuts one of its resources (load_guard.go).
guard *loadGuard
DB Store // Key-value store para configuración y estado
// chromedp fields
rootCtx context.Context // browser-owning context from CreateBrowserContext; never overwritten on mainTab promotion
Ctx context.Context
Cancel context.CancelFunc
// AllocCancel cancels the exec allocator (the Chrome OS process). Must be
// called on close, otherwise cancelling only Ctx closes the tab/target but
// leaves the Chrome window alive -> orphan windows on restart (double window).
AllocCancel context.CancelFunc
// extraTabs are the tabs OpenTab added next to the main one (e.g. one per
// DEV_AUTOLOGIN user). MCP tools act only on Ctx; Reload refreshes them all.
extraTabs []*browserTab
mainTab *browserTab // the tab of Ctx; set by CreateBrowserContext
active atomic.Pointer[browserTab] // the tab the developer has in front (tabs.go)
ReadyChan chan bool
ErrChan chan error
ExitChan chan bool
Log func(message ...any) // For logging output (Loggable interface)
lastOpID string
// Console log capture
ConsoleLogs []string
LogsMutex sync.Mutex
// Network log capture
NetworkLogs []NetworkLogEntry
NetworkMutex sync.Mutex
// JS error capture
JsErrors []JSError
ErrorsMutex sync.Mutex
// Request interception
InterceptActive bool
interceptCtx context.Context // the tab interception runs on; guarded by InterceptMutex
InterceptedReqs []InterceptedRequest
InterceptMutex sync.Mutex
// Operation busy flag (atomic) to prevent race conditions and UI blocking
// 0 = idle, 1 = busy
Busy int32
TestMode bool // Skip opening browser in tests
// Cache configuration
CacheEnabled bool // Disabled by default for development
// Mu guards the browser state. Never call Logger, Log or UI while holding it: every TUI's logger and UI call
// back into the browser (GetLastOperationID, IsOpen) and the lock is not reentrant (tests/reentrant_callbacks_test.go).
Mu sync.Mutex
ProfileDir string // "" = throwaway profile
profileFallbackReason string
}
// Option configures the DevBrowser
type Option func(*DevBrowser)
// WithCache configures whether the browser cache is enabled
func WithCache(enabled bool) Option {
return func(b *DevBrowser) {
b.CacheEnabled = enabled
}
}
type JSError struct {
Message string
Source string // File/URL where error occurred
LineNumber int
ColumnNumber int
StackTrace string
Timestamp time.Time
}
type NetworkLogEntry struct {
URL string
Method string
Status int
Type string // xhr, fetch, document, script, image, etc.
Duration int64 // milliseconds
Failed bool
ErrorText string
}
/*
devbrowser.New creates a new DevBrowser instance.
type serverConfig interface {
GetServerPort() string
}
type userInterface interface {
RefreshUI()
ReturnFocus() error
}
example : New(userInterface, st, exitChan, WithCache(true))
*/
func New(ui UserInterface, st Store, exitChan chan bool, opts ...Option) *DevBrowser {
// Initialize clipboard for cross-platform support
// err := clipboard.Init()
// if err != nil {
// // Can't log yet, no logger injected
// }
browser := &DevBrowser{
UI: ui,
DB: st,
Width: 1024, // Default width
Height: 768, // Default height
Position: "0,0",
FirstCall: true,
ReadyChan: make(chan bool),
ErrChan: make(chan error),
ExitChan: exitChan,
CacheEnabled: false, // Default: Cache disabled for development
lastOpID: "browser-status",
}
// Apply options
for _, opt := range opts {
opt(browser)
}
// Load all configuration from store
browser.LoadConfig()
//id := atomic.AddInt32(&instanceCounter, 1)
// Logger not set yet, so we can't log this via b.Logger consistently
// But let's try just in case it's injected early or for future ref inspection
// We'll use fmt temporarily for this one-time struct init check if needed,
// but user dislikes fmt. Let's rely on AutoStart logs primarily.
// If we really need New log, we might need fmt. But user said no fmt.
// We'll skip logging in New for now unless critical, but we'll keep the counter.
// actually, let's just use fmt for the New call since it is before logger init usually
//fmt.Printf("DEBUG: DevBrowser New Instance #%d created\n", id)
return browser
}
func (h *DevBrowser) BrowserStartUrlChanged(fieldName string, oldValue, newValue string) error {
if !h.IsOpenFlag {
return nil
}
return h.RestartBrowser()
}
func (h *DevBrowser) RestartBrowser() error {
this := errors.New("RestartBrowser")
h.Mu.Lock()
port, https := h.LastPort, h.LastHttps
lastURL := h.LastURL
h.Mu.Unlock()
if lastURL == "" && port == "" {
return nil
}
tabs := h.extraTabURLs()
if err := h.CloseBrowser(); err != nil {
return errors.Join(this, err)
}
if lastURL != "" {
if err := h.Open(lastURL); err != nil {
return err
}
} else {
h.OpenBrowser(port, https)
}
// The extra tabs (one per DEV_AUTOLOGIN user) come back with the browser.
var errs []error
for _, u := range tabs {
if err := h.OpenTab(u); err != nil {
errs = append(errs, err)
}
}
if len(errs) > 0 {
return errors.Join(append([]error{this}, errs...)...)
}
return nil
}
func (b *DevBrowser) NavigateToURL(url string) error {
if b.Ctx == nil {
return errors.New("context not initialized")
}
if b.guard != nil {
b.guard.SetOrigin(url)
}
if err := chromedp.Run(b.Ctx, chromedp.Navigate(url)); err != nil {
return err
}
b.Mu.Lock()
b.LastURL = url
if mt := b.mainTabLocked(); mt != nil {
mt.url = url
}
b.Mu.Unlock()
return nil
}
func (b *DevBrowser) CurrentURL() (string, error) {
if b.Ctx == nil {
return "", errors.New("context not initialized")
}
var url string
if err := chromedp.Run(b.Ctx, chromedp.Location(&url)); err != nil {
return "", err
}
return url, nil
}
func (b *DevBrowser) Reload() error {
// Gate on `ready`, not IsOpenFlag: during startup the file watcher can fire
// a reload while the initial open is still allocating the browser. Running
// chromedp.Run on the not-yet-allocated context would spawn a SECOND Chrome
// (the about:blank "double window").
b.Mu.Lock()
ready := b.ready && b.Ctx != nil && b.IsOpenFlag
if !ready {
if b.IsOpenFlag {
b.pendingReload = true
}
b.Mu.Unlock()
b.Logger(lang.Translate("Reload", "pending:", "the", "browser", "is", "still", "opening").String())
return nil
}
b.Mu.Unlock()
b.Logger("Reload")
if err := chromedp.Run(b.Ctx, chromedp.Reload()); err != nil {
return errors.New("Reload " + err.Error())
}
b.reloadExtraTabs()
return nil
}
func (b *DevBrowser) SetLog(f func(message ...any)) {
b.Log = f
}
func (b *DevBrowser) GetLog() func(message ...any) {
return b.Log
}
// GetLastOperationID returns the stable TUI OperationID so BROWSER updates a
// single live line in place during hot-reload cycles.
func (b *DevBrowser) GetLastOperationID() string {
b.Mu.Lock()
id := b.lastOpID
b.Mu.Unlock()
if id == "" {
return "browser-status"
}
return id
}
// SetLastOperationID overrides the TUI OperationID for BROWSER logs.
func (b *DevBrowser) SetLastOperationID(id string) {
b.Mu.Lock()
b.lastOpID = id
b.Mu.Unlock()
}
func (b *DevBrowser) Logger(messages ...any) {
if b.Log != nil {
b.Log(messages...)
}
}
// SetHeadless configura si el navegador debe ejecutarse en modo headless (sin UI).
// Por defecto es false (muestra la ventana del navegador).
// Debe llamarse antes de OpenBrowser().
func (b *DevBrowser) SetHeadless(headless bool) {
b.Headless = headless
}
func (b *DevBrowser) SetTestMode(testMode bool) {
b.TestMode = testMode
}
func (b *DevBrowser) SetSourceLocator(l SourceLocator) {
b.Mu.Lock()
b.SourceLocator = l
b.Mu.Unlock()
}
// monitorBrowserClose monitors the browser context and updates state when browser is closed manually
func (b *DevBrowser) monitorBrowserClose() {
b.Mu.Lock()
ctx := b.rootCtx
if ctx == nil {
ctx = b.Ctx
}
b.Mu.Unlock()
if ctx == nil {
return
}
// Wait for context to be done (browser closed)
<-ctx.Done()
// Only handle if browser was marked as open (manual close by user). Report after releasing the lock: the
// logger and the UI call back into the browser.
b.Mu.Lock()
closedByUser := b.IsOpenFlag
if closedByUser {
b.IsOpenFlag = false
b.Ctx = nil
b.Cancel = nil
}
b.Mu.Unlock()
if closedByUser {
b.Logger("Browser closed by user")
if b.UI != nil {
b.UI.RefreshUI()
}
}
}
func (b *DevBrowser) IsOpen() bool {
return b.IsOpenFlag
}
func (b *DevBrowser) IsPendingReload() bool {
b.Mu.Lock()
defer b.Mu.Unlock()
return b.pendingReload
}
func (b *DevBrowser) IsReady() bool {
b.Mu.Lock()
defer b.Mu.Unlock()
return b.ready
}
func (b *DevBrowser) SetReadyForTest(ready bool) {
b.Mu.Lock()
defer b.Mu.Unlock()
b.ready = ready
}
func (b *DevBrowser) ProcessPendingReload() {
b.Mu.Lock()
pending := b.pendingReload
b.pendingReload = false
b.Mu.Unlock()
if pending {
b.Logger(lang.Translate("Applying", "the", "pending", "reload").String())
if err := b.Reload(); err != nil {
b.Logger(lang.Translate("Pending", "reload", "failed:", err).String())
}
}
}
func (b *DevBrowser) InitializeConsoleCapture() error {
return b.initializeConsoleCapture()
}
func (b *DevBrowser) InitializeInterceptCapture() {
b.initializeInterceptCapture()
}