Repository navigation
Expand file tree
/
Copy pathtabs.go
More file actions
482 lines (447 loc) · 12.4 KB
/
Copy pathtabs.go
File metadata and controls
482 lines (447 loc) · 12.4 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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
package devbrowser
import (
"context"
"errors"
"fmt"
"net/url"
"webtyp.com/devbrowser/cdproto/inspector"
"webtyp.com/devbrowser/cdproto/page"
"webtyp.com/devbrowser/cdproto/runtime"
"webtyp.com/devbrowser/cdproto/target"
"webtyp.com/devbrowser/chromedp"
"webtyp.com/lang"
)
// browserTab is one tab of the browser: the main one (Ctx) or one OpenTab
// added. While a tab is NOT the active one, what it logs waits in its own
// buffers; the active tab's buffers are b.ConsoleLogs, b.NetworkLogs and
// b.JsErrors, which every MCP tool reads.
type browserTab struct {
ctx context.Context
cancel context.CancelFunc // nil for the main tab: Ctx owns the browser
url string // what OpenTab opened, to reopen it after RestartBrowser
// selectionInstalled: the selection gestures are wired on this tab (guarded by b.Mu)
selectionInstalled bool
console []string
network []NetworkLogEntry
errors []JSError
}
const (
tabActiveBinding = "webtypTabActive"
// tabActiveJS tells devbrowser when its tab comes to the front: switching
// tabs fires visibilitychange (to visible), clicking into the page fires
// focus — only the tab in front can receive focus.
tabActiveJS = `(() => {
const tell = () => {
if (typeof window.` + tabActiveBinding + ` === 'function') {
window.` + tabActiveBinding + `('');
}
};
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible') tell();
});
window.addEventListener('focus', tell);
if (document.visibilityState === 'visible') tell();
})()`
)
var errBrowserNotReady = errors.New("open tab: the browser is not open yet")
// OpenTab opens rawURL in a new tab of the browser that is already open, next
// to the main tab. The new tab gets its own console, network and error
// capture; MCP tools act on whichever tab the developer has in front
// (activeTab). It is reloaded together with the main one on every rebuild,
// and closes with the browser.
//
// b.OpenBrowser("6060", false)
// b.OpenTab("http://user2.localhost:6060/")
func (b *DevBrowser) OpenTab(rawURL string) error {
_, err := b.openTab(rawURL)
return err
}
func (b *DevBrowser) openTab(rawURL string) (*browserTab, error) {
b.Mu.Lock()
if !b.ready || b.Ctx == nil {
b.Mu.Unlock()
return nil, errBrowserNotReady
}
parent := b.rootCtx
if parent == nil {
parent = b.Ctx
}
b.Mu.Unlock()
ctx, cancel := chromedp.NewContext(parent) // a new target in the same browser
tab := &browserTab{ctx: ctx, cancel: cancel, url: rawURL}
if err := b.captureConsole(tab); err != nil {
cancel()
return nil, errors.New("open tab " + rawURL + ": " + err.Error())
}
b.captureNetwork(tab)
b.captureErrors(tab)
b.captureIntercept(tab)
b.installSelectionCaptureOn(tab)
b.watchTab(tab)
if err := b.applyDeviceEmulationOn(ctx); err != nil {
b.Logger(fmt.Sprintf("Failed to apply emulation to tab %s: %v", rawURL, err))
}
if err := chromedp.Run(ctx, chromedp.Navigate(rawURL)); err != nil {
b.forgetTab(tab)
cancel()
return nil, errors.New("open tab " + rawURL + ": " + err.Error())
}
b.Mu.Lock()
b.extraTabs = append(b.extraTabs, tab)
b.Mu.Unlock()
return tab, nil
}
// toolCtx is the context every MCP tool acts on: the tab the developer has
// in front, or the main tab when that one is gone.
func (b *DevBrowser) toolCtx() context.Context {
if t := b.toolTab(); t != nil {
return t.ctx
}
return b.Ctx
}
// toolTab is the tab the developer has in front, or the main tab; nil while
// the browser is closed.
func (b *DevBrowser) toolTab() *browserTab {
if t := b.active.Load(); t != nil && t.ctx != nil && t.ctx.Err() == nil {
return t
}
b.Mu.Lock()
defer b.Mu.Unlock()
return b.mainTabLocked()
}
// mainTabLocked is the tab of Ctx, whoever set Ctx (CreateBrowserContext, or
// a caller assigning the exported field). Call with b.Mu held.
func (b *DevBrowser) mainTabLocked() *browserTab {
if b.Ctx == nil {
return nil
}
if b.mainTab == nil || b.mainTab.ctx != b.Ctx {
b.mainTab = &browserTab{ctx: b.Ctx}
}
return b.mainTab
}
// CloseTabs closes every tab OpenTab added and keeps the main one, e.g. when
// the browser switches to another project whose users are other hosts.
func (b *DevBrowser) CloseTabs() {
b.Mu.Lock()
tabs := b.extraTabs
b.extraTabs = nil
main := b.mainTab
b.Mu.Unlock()
for _, t := range tabs {
t.cancel()
}
if main != nil {
b.activateTab(main)
}
}
// extraTabURLs lists what the extra tabs opened, in order.
func (b *DevBrowser) extraTabURLs() []string {
b.Mu.Lock()
defer b.Mu.Unlock()
urls := make([]string, len(b.extraTabs))
for i, t := range b.extraTabs {
urls[i] = t.url
}
return urls
}
// allTabCtxs is the main tab and every extra tab, for settings that apply to
// the whole browser (device emulation).
func (b *DevBrowser) allTabCtxs() []context.Context {
b.Mu.Lock()
defer b.Mu.Unlock()
var out []context.Context
if b.Ctx != nil {
out = append(out, b.Ctx)
}
for _, t := range b.extraTabs {
out = append(out, t.ctx)
}
return out
}
// watchTab makes tab report when it comes to the front (tabActiveJS) and
// when it goes away.
func (b *DevBrowser) watchTab(tab *browserTab) {
chromedp.ListenTarget(tab.ctx, func(ev any) {
switch e := ev.(type) {
case *runtime.EventBindingCalled:
if e.Name == tabActiveBinding {
go b.activateTab(tab) // never wait on a lock on chromedp's event loop
}
case *inspector.EventDetached:
go b.forgetTab(tab)
}
})
_ = chromedp.Run(tab.ctx,
runtime.Enable(),
page.Enable(),
runtime.AddBinding(tabActiveBinding),
chromedp.ActionFunc(func(c context.Context) error {
_, err := page.AddScriptToEvaluateOnNewDocument(tabActiveJS).Do(c)
return err
}),
)
}
// activateTab makes tab the one MCP tools read and act on: the buffers of
// the tab that was active go back into it, and tab's come out.
func (b *DevBrowser) activateTab(tab *browserTab) {
b.LogsMutex.Lock()
b.NetworkMutex.Lock()
b.ErrorsMutex.Lock()
old := b.active.Load()
if old != tab {
if old != nil {
old.console, old.network, old.errors = b.ConsoleLogs, b.NetworkLogs, b.JsErrors
}
b.ConsoleLogs, b.NetworkLogs, b.JsErrors = orEmpty(tab.console), orEmptyNet(tab.network), orEmptyErr(tab.errors)
tab.console, tab.network, tab.errors = nil, nil, nil
b.active.Store(tab)
}
b.ErrorsMutex.Unlock()
b.NetworkMutex.Unlock()
b.LogsMutex.Unlock()
}
// forgetTab drops a tab that closed; if it was the active one, the main tab
// takes over.
func (b *DevBrowser) forgetTab(tab *browserTab) {
b.Mu.Lock()
kept := b.extraTabs[:0]
for _, t := range b.extraTabs {
if t != tab {
kept = append(kept, t)
}
}
b.extraTabs = kept
main := b.mainTab
b.Mu.Unlock()
if b.active.Load() == tab && main != nil && main != tab {
b.activateTab(main)
}
}
// consoleOf, networkOf and errorsOf return the buffer tab writes to: the
// shared one while tab is active, its own otherwise. Call with the matching
// mutex held (LogsMutex, NetworkMutex, ErrorsMutex).
func (b *DevBrowser) consoleOf(tab *browserTab) *[]string {
if b.active.Load() == tab {
return &b.ConsoleLogs
}
return &tab.console
}
func (b *DevBrowser) networkOf(tab *browserTab) *[]NetworkLogEntry {
if b.active.Load() == tab {
return &b.NetworkLogs
}
return &tab.network
}
func (b *DevBrowser) errorsOf(tab *browserTab) *[]JSError {
if b.active.Load() == tab {
return &b.JsErrors
}
return &tab.errors
}
func orEmpty(v []string) []string {
if v == nil {
return []string{}
}
return v
}
func orEmptyNet(v []NetworkLogEntry) []NetworkLogEntry {
if v == nil {
return []NetworkLogEntry{}
}
return v
}
func orEmptyErr(v []JSError) []JSError {
if v == nil {
return []JSError{}
}
return v
}
// reloadExtraTabs reloads every tab OpenTab added; one the user closed by hand
// fails to reload and is forgotten.
func (b *DevBrowser) reloadExtraTabs() {
b.Mu.Lock()
tabs := append([]*browserTab(nil), b.extraTabs...)
b.Mu.Unlock()
for _, t := range tabs {
if err := chromedp.Run(t.ctx, chromedp.Reload()); err != nil {
t.cancel()
b.forgetTab(t)
}
}
}
// tabPort returns the TCP port of rawURL, or "" if absent/unparseable.
func tabPort(rawURL string) string {
u, err := url.Parse(rawURL)
if err != nil {
return ""
}
return u.Port()
}
// OpenPort ensures a tab for port is open in the browser and brings it to the
// front. When the browser is closed, it opens Chrome on port; when Chrome is
// already open with another project's tab, it opens a new tab (or focuses the
// existing one for port) without touching other projects' tabs.
func (b *DevBrowser) OpenPort(port string, https bool) error {
if port == "" {
return nil
}
scheme := "http"
if https {
scheme = "https"
}
rawURL := scheme + "://localhost:" + port + "/"
b.Mu.Lock()
open := b.IsOpenFlag && b.ready && b.Ctx != nil && b.Ctx.Err() == nil
var existing *browserTab
if open {
if b.mainTab != nil && tabPort(b.mainTab.url) == port {
existing = b.mainTab
} else {
for _, t := range b.extraTabs {
if tabPort(t.url) == port {
existing = t
break
}
}
}
}
b.Mu.Unlock()
if !open {
b.Mu.Lock()
b.LastPort = port
b.LastHttps = https
b.Mu.Unlock()
return b.Open(rawURL)
}
if existing != nil {
if err := chromedp.Run(existing.ctx, page.BringToFront()); err == nil {
b.activateTab(existing)
return nil
}
// Tab was closed manually by the user; forget it if extra and open a fresh one.
if existing.cancel != nil {
existing.cancel()
b.forgetTab(existing)
}
}
tab, err := b.openTab(rawURL)
if err != nil {
return err
}
_ = chromedp.Run(tab.ctx, page.BringToFront())
b.activateTab(tab)
return nil
}
// ReloadPort reloads only the tabs belonging to port (main and extra/autologin).
// Empty port falls back to Reload().
func (b *DevBrowser) ReloadPort(port string) error {
if port == "" {
return b.Reload()
}
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
}
main := b.mainTab
extras := append([]*browserTab(nil), b.extraTabs...)
b.Mu.Unlock()
var reloaded bool
if main != nil && tabPort(main.url) == port {
b.Logger("Reload")
reloaded = true
if err := chromedp.Run(main.ctx, chromedp.Reload()); err != nil {
return errors.New("Reload " + err.Error())
}
}
for _, t := range extras {
if tabPort(t.url) != port {
continue
}
if !reloaded {
b.Logger("Reload")
reloaded = true
}
if err := chromedp.Run(t.ctx, chromedp.Reload()); err != nil {
t.cancel()
b.forgetTab(t)
}
}
return nil
}
// ClosePort closes every tab belonging to port. If no other project tabs remain,
// it closes the browser window; if the main tab belonged to port while another
// project's tab is still open, that other tab is promoted to main and the old
// target is closed without closing Chrome.
func (b *DevBrowser) ClosePort(port string) error {
if port == "" {
return nil
}
b.Mu.Lock()
if !b.IsOpenFlag || b.Ctx == nil {
b.Mu.Unlock()
return nil
}
mainMatches := b.mainTab != nil && tabPort(b.mainTab.url) == port
var toClose, remaining []*browserTab
for _, t := range b.extraTabs {
if tabPort(t.url) == port {
toClose = append(toClose, t)
} else {
remaining = append(remaining, t)
}
}
if mainMatches && len(remaining) == 0 {
b.Mu.Unlock()
return b.CloseBrowser()
}
b.extraTabs = remaining
var oldMain, promoted *browserTab
var oldMainTargetID = ""
if mainMatches {
oldMain = b.mainTab
if c := chromedp.FromContext(oldMain.ctx); c != nil && c.Target != nil {
oldMainTargetID = string(c.Target.TargetID)
}
promoted = remaining[0]
b.extraTabs = remaining[1:]
b.mainTab = promoted
b.Ctx = promoted.ctx
b.LastURL = promoted.url
b.LastPort = tabPort(promoted.url)
}
active := b.active.Load()
fallback := b.mainTab
rootCtx := b.rootCtx
b.Mu.Unlock()
for _, t := range toClose {
if t.cancel != nil {
t.cancel()
}
}
if promoted != nil {
b.activateTab(promoted)
_ = chromedp.Run(promoted.ctx, page.BringToFront())
if oldMainTargetID != "" {
_ = chromedp.Run(promoted.ctx, target.CloseTarget(target.ID(oldMainTargetID)))
}
if oldMain != nil && oldMain.cancel != nil && oldMain.ctx != rootCtx {
oldMain.cancel()
}
return nil
}
// If the active tab was one of the closed extras, fall back to mainTab.
for _, t := range toClose {
if active == t && fallback != nil {
b.activateTab(fallback)
break
}
}
return nil
}