@myrialabs/clopen 0.4.41 → 0.4.42
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/backend/chat/stream-manager.ts +8 -0
- package/backend/database/crypto/secret-columns.ts +5 -1
- package/backend/database/index.ts +18 -0
- package/backend/database/migrations/082_create_git_identities.test.ts +186 -0
- package/backend/database/migrations/082_create_git_identities.ts +122 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/git-identity-queries.ts +290 -0
- package/backend/database/queries/index.ts +2 -0
- package/backend/engine/adapters/claude/environment.ts +11 -1
- package/backend/engine/adapters/claude/stream.ts +1 -1
- package/backend/engine/adapters/codex/stream.ts +35 -3
- package/backend/engine/adapters/opencode/server.ts +26 -2
- package/backend/engine/adapters/opencode/stream.ts +4 -1
- package/backend/engine/adapters/qwen/stream.ts +3 -1
- package/backend/engine/types.ts +10 -0
- package/backend/git/git-executor.ts +28 -2
- package/backend/git/git-service.ts +59 -40
- package/backend/git/identity/cli.test.ts +58 -0
- package/backend/git/identity/cli.ts +201 -0
- package/backend/git/identity/credential-helper.test.ts +242 -0
- package/backend/git/identity/env.test.ts +214 -0
- package/backend/git/identity/env.ts +193 -0
- package/backend/git/identity/import-local.test.ts +199 -0
- package/backend/git/identity/import-local.ts +141 -0
- package/backend/git/identity/index.ts +78 -0
- package/backend/git/identity/keys.ts +183 -0
- package/backend/git/identity/resolve.ts +140 -0
- package/backend/git/identity/scope-config.test.ts +145 -0
- package/backend/git/identity/scope-config.ts +175 -0
- package/backend/git/identity/service.ts +297 -0
- package/backend/index.ts +16 -0
- package/backend/preview/browser/browser-console-manager.ts +214 -34
- package/backend/preview/browser/browser-pool.ts +526 -123
- package/backend/preview/browser/browser-preview-service.ts +192 -8
- package/backend/preview/browser/browser-tab-lifecycle.test.ts +240 -0
- package/backend/preview/browser/browser-tab-lifecycle.ts +495 -0
- package/backend/preview/browser/browser-tab-manager.ts +291 -65
- package/backend/preview/browser/capture-profile.ts +15 -1
- package/backend/preview/browser/types.ts +26 -1
- package/backend/terminal/ptykit.ts +24 -0
- package/backend/ws/git/branch.ts +17 -6
- package/backend/ws/git/commit.ts +6 -5
- package/backend/ws/git/conflict.ts +3 -2
- package/backend/ws/git/identity-context.ts +91 -0
- package/backend/ws/git/identity.ts +200 -0
- package/backend/ws/git/index.ts +3 -1
- package/backend/ws/git/remote.ts +57 -11
- package/backend/ws/preview/browser/data.ts +60 -0
- package/backend/ws/preview/browser/interact.ts +6 -0
- package/backend/ws/preview/browser/tab-info.ts +9 -1
- package/backend/ws/preview/browser/tab.ts +64 -8
- package/backend/ws/preview/index.ts +21 -0
- package/bin/clopen.ts +9 -0
- package/dist/assets/{index-CeNKKSDR.js → index-BynqyvF4.js} +1 -1
- package/dist/assets/{index-DW89566K.js → index-DLoJsmNQ.js} +1 -1
- package/dist/assets/{main-Cy5DXWPT.js → main-CUyZAmqt.js} +591 -584
- package/dist/assets/main-DVCW3cfr.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +2 -2
- package/shared/types/git-identity.ts +112 -0
- package/dist/assets/main-DJKj_4By.css +0 -1
|
@@ -12,6 +12,23 @@ import { scopeSlug } from '$shared/utils/workspace-scope';
|
|
|
12
12
|
|
|
13
13
|
// Tab cleanup configuration
|
|
14
14
|
const INACTIVE_TIMEOUT = 5 * 60 * 1000; // 5 minutes
|
|
15
|
+
/** How long a launch may stay in the bookkeeping before it is swept. */
|
|
16
|
+
const LAUNCH_TTL = 2 * 60 * 1000;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* A launch in flight.
|
|
20
|
+
*
|
|
21
|
+
* `waiters` is what lets a cancel cut a wait short rather than merely stop the
|
|
22
|
+
* next one: the Cloudflare pass sits on `waitForNavigation` for twenty seconds
|
|
23
|
+
* at a time, and a Stop that only set a flag would be honoured after the wait
|
|
24
|
+
* it was meant to end.
|
|
25
|
+
*/
|
|
26
|
+
interface LaunchRecord {
|
|
27
|
+
page: Page | null;
|
|
28
|
+
cancelled: boolean;
|
|
29
|
+
startedAt: number;
|
|
30
|
+
waiters: Array<() => void>;
|
|
31
|
+
}
|
|
15
32
|
const CLEANUP_INTERVAL = 60 * 1000; // Check every minute
|
|
16
33
|
|
|
17
34
|
/**
|
|
@@ -41,21 +58,40 @@ export type TabAilment = 'browser-gone' | 'session-gone' | 'page-gone';
|
|
|
41
58
|
*
|
|
42
59
|
* ARCHITECTURE:
|
|
43
60
|
* - Tabs are the primary unit (no separate "session" concept)
|
|
44
|
-
* - Each tab
|
|
45
|
-
* - 1 shared browser + isolated contexts = ~20 MB per tab
|
|
61
|
+
* - Each tab is a page, in a window of its own, in the workspace's profile
|
|
46
62
|
* - Active tab tracking for operations
|
|
47
63
|
* - Event-driven for frontend sync
|
|
48
64
|
* - **PROJECT ISOLATION**: Sessions are prefixed with projectId
|
|
49
65
|
*
|
|
50
66
|
* ISOLATION GUARANTEE:
|
|
51
|
-
*
|
|
52
|
-
*
|
|
53
|
-
*
|
|
54
|
-
*
|
|
55
|
-
*
|
|
56
|
-
*
|
|
57
|
-
|
|
67
|
+
* The boundary is the workspace, not the tab. Every tab of one workspace
|
|
68
|
+
* shares a Chrome profile — the same cookies, storage, cache and service
|
|
69
|
+
* workers — which is what makes two previews of one app behave like two tabs
|
|
70
|
+
* of one browser rather than two private windows, and what keeps a login
|
|
71
|
+
* across a restart. Between workspaces nothing is shared: the profile is
|
|
72
|
+
* keyed by the workspace scope, so no project can see another's data.
|
|
73
|
+
*/
|
|
74
|
+
/**
|
|
75
|
+
* Raised when a launch was stopped before its page loaded anything.
|
|
76
|
+
*
|
|
77
|
+
* Not an error the user needs to hear about — it is what they asked for — but
|
|
78
|
+
* it has to unwind the launch rather than return a tab, because a tab whose
|
|
79
|
+
* navigation never committed sits on `about:blank`, and `about:blank` is not a
|
|
80
|
+
* secure context: `VideoEncoder` does not exist there, so the preview pipeline
|
|
81
|
+
* could never produce a single frame for it. Handing one back left the panel
|
|
82
|
+
* waiting for a picture that was never coming.
|
|
58
83
|
*/
|
|
84
|
+
export class LaunchCancelledError extends Error {
|
|
85
|
+
constructor() {
|
|
86
|
+
super('Launch cancelled before the page loaded');
|
|
87
|
+
this.name = 'LaunchCancelledError';
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function createLaunchRecord(): LaunchRecord {
|
|
92
|
+
return { page: null, cancelled: false, startedAt: Date.now(), waiters: [] };
|
|
93
|
+
}
|
|
94
|
+
|
|
59
95
|
export class BrowserTabManager extends EventEmitter {
|
|
60
96
|
private tabs = new Map<string, BrowserTab>();
|
|
61
97
|
private activeTabId: string | null = null;
|
|
@@ -87,19 +123,37 @@ export class BrowserTabManager extends EventEmitter {
|
|
|
87
123
|
*/
|
|
88
124
|
private tabSetupHooks = new Map<string, (page: Page, tabId: string) => Promise<void>>();
|
|
89
125
|
|
|
126
|
+
/** Popup watchers, one per context the manager has seen. */
|
|
127
|
+
private contextWatchers = new Map<BrowserContext, (target: Target) => void>();
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* How many pages we are opening right now. Read by the popup watcher, which
|
|
131
|
+
* must not mistake one of them for a `window.open`.
|
|
132
|
+
*/
|
|
133
|
+
private adoptingPages = 0;
|
|
134
|
+
|
|
90
135
|
/**
|
|
91
|
-
*
|
|
92
|
-
*
|
|
93
|
-
*
|
|
94
|
-
*
|
|
136
|
+
* Launches in flight, by the id the client minted for them.
|
|
137
|
+
*
|
|
138
|
+
* A launch is the one part of a tab's life that has no tab yet: the page is
|
|
139
|
+
* created and navigated before the tab exists, so for the length of that
|
|
140
|
+
* navigation — up to a minute against a slow site, longer behind a
|
|
141
|
+
* Cloudflare challenge — there was nothing for Stop to address. The client
|
|
142
|
+
* names the launch instead, and this is where that name resolves to
|
|
143
|
+
* something that can be stopped.
|
|
144
|
+
*/
|
|
145
|
+
private launches = new Map<string, LaunchRecord>();
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* The listeners a tab holds on the shared browser, which outlives its page.
|
|
149
|
+
* A rebuild takes them off before fitting new ones, so a dead page's
|
|
150
|
+
* handlers cannot ask for a second recovery of a tab already being rebuilt.
|
|
95
151
|
*/
|
|
96
152
|
private tabListeners = new Map<
|
|
97
153
|
string,
|
|
98
154
|
{
|
|
99
155
|
browser: Browser;
|
|
100
156
|
onDisconnected: () => void;
|
|
101
|
-
context: BrowserContext;
|
|
102
|
-
onTargetCreated: (target: Target) => void;
|
|
103
157
|
}
|
|
104
158
|
>();
|
|
105
159
|
|
|
@@ -138,6 +192,8 @@ export class BrowserTabManager extends EventEmitter {
|
|
|
138
192
|
options?: {
|
|
139
193
|
setActive?: boolean;
|
|
140
194
|
preNavigationSetup?: (page: Page, tabId: string) => Promise<void>;
|
|
195
|
+
/** Client-minted name for this launch, so Stop can reach it. */
|
|
196
|
+
launchId?: string;
|
|
141
197
|
}
|
|
142
198
|
): Promise<BrowserTab> {
|
|
143
199
|
// The counter restarts per workspace, so the scope token is what stops a
|
|
@@ -148,21 +204,35 @@ export class BrowserTabManager extends EventEmitter {
|
|
|
148
204
|
debug.log('preview', `🟡🟡🟡 Creating new tab: ${tabId} for project: ${this.projectId} 🟡🟡🟡`);
|
|
149
205
|
debug.log('preview', `📁 Tab URL: ${finalUrl}, deviceSize: ${deviceSize}, rotation: ${rotation}`);
|
|
150
206
|
|
|
207
|
+
// Registered before the page exists, so a Stop that arrives while Chrome
|
|
208
|
+
// is still starting is remembered rather than dropped.
|
|
209
|
+
const launch = options?.launchId
|
|
210
|
+
? (this.launches.get(options.launchId) ?? createLaunchRecord())
|
|
211
|
+
: createLaunchRecord();
|
|
212
|
+
if (options?.launchId) {
|
|
213
|
+
this.pruneLaunches();
|
|
214
|
+
this.launches.set(options.launchId, launch);
|
|
215
|
+
}
|
|
216
|
+
|
|
151
217
|
let browser: Browser;
|
|
152
218
|
let context: BrowserContext;
|
|
153
219
|
let page: Page;
|
|
154
220
|
|
|
155
221
|
try {
|
|
156
|
-
//
|
|
157
|
-
//
|
|
222
|
+
// Project-scoped sessionId. The prefix is also the profile key, so
|
|
223
|
+
// isolation runs between workspaces while tabs inside one share a
|
|
224
|
+
// profile the way a browser's tabs do.
|
|
158
225
|
const sessionId = `${this.projectId}:${tabId}`;
|
|
159
226
|
|
|
160
|
-
//
|
|
161
|
-
//
|
|
162
|
-
|
|
163
|
-
|
|
227
|
+
// One profile per workspace, shared by its tabs: same cookies, same
|
|
228
|
+
// storage, one HTTP cache — what two tabs of a browser share, and
|
|
229
|
+
// kept on disk so it survives a restart. Isolation still holds
|
|
230
|
+
// where it matters, between workspaces.
|
|
231
|
+
const pooledSession = await this.adopt(() => browserPool.createSession(sessionId, this.projectId));
|
|
232
|
+
browser = pooledSession.browser;
|
|
164
233
|
context = pooledSession.context;
|
|
165
234
|
page = pooledSession.page;
|
|
235
|
+
launch.page = page;
|
|
166
236
|
|
|
167
237
|
debug.log('preview', `🔐 Session ID: ${sessionId} (project-scoped)`);
|
|
168
238
|
} catch (poolError) {
|
|
@@ -170,7 +240,7 @@ export class BrowserTabManager extends EventEmitter {
|
|
|
170
240
|
throw poolError;
|
|
171
241
|
}
|
|
172
242
|
|
|
173
|
-
debug.log('preview', `✅
|
|
243
|
+
debug.log('preview', `✅ Page ready for tab: ${tabId}`);
|
|
174
244
|
|
|
175
245
|
// Setup page (viewport, headers, etc.)
|
|
176
246
|
debug.log('preview', `⚙️ Setting up page...`);
|
|
@@ -186,9 +256,22 @@ export class BrowserTabManager extends EventEmitter {
|
|
|
186
256
|
|
|
187
257
|
// Navigate to URL (or about:blank)
|
|
188
258
|
debug.log('preview', `🌐 Navigating to: ${finalUrl}`);
|
|
189
|
-
const actualUrl = await this.navigateWithRetry(page, finalUrl);
|
|
259
|
+
const actualUrl = await this.navigateWithRetry(page, finalUrl, launch);
|
|
190
260
|
debug.log('preview', `✅ Navigation complete - final URL: ${actualUrl}`);
|
|
191
261
|
|
|
262
|
+
// Stopped with nothing to show for it. The page is discarded rather than
|
|
263
|
+
// handed over: it is parked on about:blank, which cannot be streamed,
|
|
264
|
+
// and a tab that can never paint is worse than no tab at all. A launch
|
|
265
|
+
// stopped *after* the document committed keeps its tab — that page is
|
|
266
|
+
// real, and leaving it is what Stop means in a browser.
|
|
267
|
+
if (launch.cancelled && actualUrl === 'about:blank' && finalUrl !== 'about:blank') {
|
|
268
|
+
debug.log('preview', `🛑 Launch for ${tabId} stopped before it loaded — discarding the page`);
|
|
269
|
+
this.detachTabListeners(tabId);
|
|
270
|
+
await browserPool.destroySession(this.getSessionId(tabId)).catch(() => {});
|
|
271
|
+
if (options?.launchId) this.launches.delete(options.launchId);
|
|
272
|
+
throw new LaunchCancelledError();
|
|
273
|
+
}
|
|
274
|
+
|
|
192
275
|
// Get title from URL
|
|
193
276
|
const title = this.getTitleFromUrl(actualUrl);
|
|
194
277
|
|
|
@@ -259,12 +342,18 @@ export class BrowserTabManager extends EventEmitter {
|
|
|
259
342
|
isActive: tab.isActive,
|
|
260
343
|
deviceSize: tab.deviceSize,
|
|
261
344
|
rotation: tab.rotation,
|
|
345
|
+
// Echoed so the client can tie this tab to the launch it started,
|
|
346
|
+
// rather than guessing from "some tab is launching" — which stopped
|
|
347
|
+
// being true the moment the user pressed Stop.
|
|
348
|
+
launchId: options?.launchId,
|
|
262
349
|
timestamp: Date.now()
|
|
263
350
|
};
|
|
264
351
|
|
|
265
352
|
debug.log('preview', `📤 Emitting preview:browser-tab-opened event:`, tabOpenedEvent);
|
|
266
353
|
this.emit('preview:browser-tab-opened', tabOpenedEvent);
|
|
267
354
|
|
|
355
|
+
if (options?.launchId) this.launches.delete(options.launchId);
|
|
356
|
+
|
|
268
357
|
debug.log('preview', `✅ Tab created: ${tabId} (active: ${tab.isActive})`);
|
|
269
358
|
|
|
270
359
|
// Log pool stats
|
|
@@ -274,6 +363,60 @@ export class BrowserTabManager extends EventEmitter {
|
|
|
274
363
|
return tab;
|
|
275
364
|
}
|
|
276
365
|
|
|
366
|
+
/**
|
|
367
|
+
* Stop a launch that has not produced a tab yet.
|
|
368
|
+
*
|
|
369
|
+
* Puppeteer offers no cancel for an in-flight `goto`, so the load is stopped
|
|
370
|
+
* where it actually runs: `Page.stopLoading` tells the renderer to give up,
|
|
371
|
+
* which settles the pending navigation in a moment instead of the minute a
|
|
372
|
+
* slow site (or a Cloudflare challenge) would otherwise take. The flag is
|
|
373
|
+
* what stops the retry loop from starting over behind it.
|
|
374
|
+
*
|
|
375
|
+
* The tab is still created, at whatever the page managed to load — which is
|
|
376
|
+
* what Stop does in a browser, and the alternative (discarding it) would
|
|
377
|
+
* take away the tab the user is looking at.
|
|
378
|
+
*
|
|
379
|
+
* A cancel for a launch that has not registered yet is recorded rather than
|
|
380
|
+
* dropped: the request and the Stop travel over the same socket moments
|
|
381
|
+
* apart, and losing that race would let the load the user just abandoned
|
|
382
|
+
* run to completion.
|
|
383
|
+
*/
|
|
384
|
+
async cancelLaunch(launchId: string): Promise<void> {
|
|
385
|
+
this.pruneLaunches();
|
|
386
|
+
|
|
387
|
+
const launch = this.launches.get(launchId) ?? createLaunchRecord();
|
|
388
|
+
this.launches.set(launchId, launch);
|
|
389
|
+
|
|
390
|
+
launch.cancelled = true;
|
|
391
|
+
for (const wake of launch.waiters.splice(0)) wake();
|
|
392
|
+
debug.log('preview', `🛑 Launch ${launchId} cancelled`);
|
|
393
|
+
|
|
394
|
+
const page = launch.page;
|
|
395
|
+
if (!page || page.isClosed()) return;
|
|
396
|
+
|
|
397
|
+
try {
|
|
398
|
+
const cdp = await page.createCDPSession();
|
|
399
|
+
await cdp.send('Page.stopLoading').catch(() => {});
|
|
400
|
+
await cdp.detach().catch(() => {});
|
|
401
|
+
} catch (error) {
|
|
402
|
+
debug.warn('preview', `⚠️ Could not stop the load for ${launchId}: ${error}`);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/**
|
|
407
|
+
* Drop launch bookkeeping left behind by one that threw.
|
|
408
|
+
*
|
|
409
|
+
* A launch that fails deletes nothing on its way out, and the entry is only
|
|
410
|
+
* ever a page reference plus two fields — so it is swept on the next launch
|
|
411
|
+
* rather than paid for with a timer.
|
|
412
|
+
*/
|
|
413
|
+
private pruneLaunches(): void {
|
|
414
|
+
const cutoff = Date.now() - LAUNCH_TTL;
|
|
415
|
+
for (const [id, launch] of this.launches) {
|
|
416
|
+
if (launch.startedAt < cutoff) this.launches.delete(id);
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
277
420
|
/**
|
|
278
421
|
* Navigate tab to a new URL
|
|
279
422
|
*/
|
|
@@ -367,7 +510,7 @@ export class BrowserTabManager extends EventEmitter {
|
|
|
367
510
|
// Wait a moment for streaming loop to detect the flags and stop
|
|
368
511
|
await new Promise(resolve => setTimeout(resolve, 500));
|
|
369
512
|
|
|
370
|
-
//
|
|
513
|
+
// Close the page. The workspace profile is deliberately left alone.
|
|
371
514
|
await this.cleanupContext(tab);
|
|
372
515
|
|
|
373
516
|
// Remove from map
|
|
@@ -760,10 +903,9 @@ export class BrowserTabManager extends EventEmitter {
|
|
|
760
903
|
|
|
761
904
|
// Keeps the context — and so the cookies and storage the tab has
|
|
762
905
|
// built up — whenever the context itself survived.
|
|
763
|
-
pooled = await browserPool.renewSessionPage(sessionId);
|
|
764
|
-
const browser = await browserPool.getBrowser();
|
|
906
|
+
pooled = await this.adopt(() => browserPool.renewSessionPage(sessionId, this.projectId));
|
|
765
907
|
|
|
766
|
-
tab.browser = browser;
|
|
908
|
+
tab.browser = pooled.browser;
|
|
767
909
|
tab.context = pooled.context;
|
|
768
910
|
tab.page = pooled.page;
|
|
769
911
|
tab.isStreaming = false;
|
|
@@ -782,7 +924,7 @@ export class BrowserTabManager extends EventEmitter {
|
|
|
782
924
|
await setupHook(pooled.page, tabId);
|
|
783
925
|
}
|
|
784
926
|
|
|
785
|
-
this.setupBrowserHandlers(tabId, browser, pooled.context, pooled.page);
|
|
927
|
+
this.setupBrowserHandlers(tabId, pooled.browser, pooled.context, pooled.page);
|
|
786
928
|
|
|
787
929
|
// `url` over `currentUrl`: the navigation tracker keeps the former
|
|
788
930
|
// current through redirects and SPA pushState, while the latter only
|
|
@@ -813,16 +955,23 @@ export class BrowserTabManager extends EventEmitter {
|
|
|
813
955
|
}
|
|
814
956
|
}
|
|
815
957
|
|
|
816
|
-
/** Take a tab's browser-
|
|
958
|
+
/** Take a tab's browser-level listeners back off. */
|
|
817
959
|
private detachTabListeners(tabId: string): void {
|
|
818
960
|
const entry = this.tabListeners.get(tabId);
|
|
819
961
|
if (!entry) return;
|
|
820
962
|
|
|
821
963
|
entry.browser.off('disconnected', entry.onDisconnected);
|
|
822
|
-
entry.context.off('targetcreated', entry.onTargetCreated);
|
|
823
964
|
this.tabListeners.delete(tabId);
|
|
824
965
|
}
|
|
825
966
|
|
|
967
|
+
/** Stop watching every context this manager attached a popup watcher to. */
|
|
968
|
+
private detachContextWatchers(): void {
|
|
969
|
+
for (const [context, handler] of this.contextWatchers) {
|
|
970
|
+
context.off('targetcreated', handler);
|
|
971
|
+
}
|
|
972
|
+
this.contextWatchers.clear();
|
|
973
|
+
}
|
|
974
|
+
|
|
826
975
|
/**
|
|
827
976
|
* Mark tab activity (prevent cleanup)
|
|
828
977
|
*/
|
|
@@ -987,22 +1136,37 @@ export class BrowserTabManager extends EventEmitter {
|
|
|
987
1136
|
/**
|
|
988
1137
|
* Navigate with retry, including Cloudflare auto-pass detection and CAPTCHA popup dismissal.
|
|
989
1138
|
*/
|
|
990
|
-
private async navigateWithRetry(page: Page, url: string): Promise<string> {
|
|
1139
|
+
private async navigateWithRetry(page: Page, url: string, launch?: LaunchRecord): Promise<string> {
|
|
991
1140
|
const cleanUrl = this.sanitizeNavigationUrl(url);
|
|
992
1141
|
let retries = 3;
|
|
993
1142
|
let actualUrl = '';
|
|
994
1143
|
|
|
995
1144
|
while (retries > 0) {
|
|
1145
|
+
// Checked before each attempt as well as after: a Stop pressed while
|
|
1146
|
+
// the previous attempt was failing must not be answered with another.
|
|
1147
|
+
if (launch?.cancelled) return page.url();
|
|
1148
|
+
|
|
996
1149
|
try {
|
|
997
1150
|
await page.goto(cleanUrl, {
|
|
998
1151
|
waitUntil: 'domcontentloaded',
|
|
999
1152
|
timeout: 30000
|
|
1000
1153
|
});
|
|
1001
|
-
|
|
1154
|
+
|
|
1155
|
+
// Both of the passes below wait on the page, for up to a minute
|
|
1156
|
+
// and a half between them. Neither is worth doing for a load the
|
|
1157
|
+
// user has already abandoned.
|
|
1158
|
+
if (launch?.cancelled) return page.url();
|
|
1159
|
+
|
|
1160
|
+
actualUrl = await this.waitForCloudflareIfPresent(page, launch);
|
|
1002
1161
|
// Dismiss any CAPTCHA failure popups from embedded Turnstile widgets
|
|
1003
1162
|
await this.dismissCaptchaPopupsIfPresent(page);
|
|
1004
1163
|
break;
|
|
1005
1164
|
} catch (error) {
|
|
1165
|
+
// `Page.stopLoading` makes the pending goto fail. That is the
|
|
1166
|
+
// cancel landing, not a navigation problem, so it is reported as
|
|
1167
|
+
// the page we stopped on rather than thrown.
|
|
1168
|
+
if (launch?.cancelled) return page.url();
|
|
1169
|
+
|
|
1006
1170
|
retries--;
|
|
1007
1171
|
debug.warn('preview', `⚠️ Navigation failed, ${retries} retries left:`, error);
|
|
1008
1172
|
if (retries === 0 || this.isNonRetryableError(error)) throw error;
|
|
@@ -1020,10 +1184,12 @@ export class BrowserTabManager extends EventEmitter {
|
|
|
1020
1184
|
* Loops up to MAX_CF_RETRIES times to handle infinite verify loops where
|
|
1021
1185
|
* Cloudflare keeps redirecting back to a new challenge after each pass.
|
|
1022
1186
|
*/
|
|
1023
|
-
private async waitForCloudflareIfPresent(page: Page): Promise<string> {
|
|
1187
|
+
private async waitForCloudflareIfPresent(page: Page, launch?: LaunchRecord): Promise<string> {
|
|
1024
1188
|
const MAX_CF_RETRIES = 5;
|
|
1025
1189
|
|
|
1026
1190
|
for (let attempt = 0; attempt < MAX_CF_RETRIES; attempt++) {
|
|
1191
|
+
if (launch?.cancelled) return page.url();
|
|
1192
|
+
|
|
1027
1193
|
let isChallenge = false;
|
|
1028
1194
|
|
|
1029
1195
|
try {
|
|
@@ -1056,10 +1222,26 @@ export class BrowserTabManager extends EventEmitter {
|
|
|
1056
1222
|
debug.log('preview', `🛡️ Cloudflare challenge detected (attempt ${attempt + 1}/${MAX_CF_RETRIES}), waiting for auto-pass...`);
|
|
1057
1223
|
|
|
1058
1224
|
try {
|
|
1059
|
-
|
|
1225
|
+
// Raced against the cancel, so Stop is answered now rather than
|
|
1226
|
+
// up to twenty seconds from now.
|
|
1227
|
+
const navigated = page.waitForNavigation({
|
|
1060
1228
|
waitUntil: 'domcontentloaded',
|
|
1061
1229
|
timeout: 20000
|
|
1062
1230
|
});
|
|
1231
|
+
|
|
1232
|
+
if (launch) {
|
|
1233
|
+
const cancelled = new Promise<'cancelled'>((resolve) =>
|
|
1234
|
+
launch.waiters.push(() => resolve('cancelled'))
|
|
1235
|
+
);
|
|
1236
|
+
const outcome = await Promise.race([navigated.then(() => 'navigated' as const), cancelled]);
|
|
1237
|
+
// The losing navigation still settles; unhandled, it would
|
|
1238
|
+
// surface as a rejection with nobody left to catch it.
|
|
1239
|
+
void navigated.catch(() => {});
|
|
1240
|
+
if (outcome === 'cancelled') return page.url();
|
|
1241
|
+
} else {
|
|
1242
|
+
await navigated;
|
|
1243
|
+
}
|
|
1244
|
+
|
|
1063
1245
|
debug.log('preview', `✅ Cloudflare navigation → ${page.url()}`);
|
|
1064
1246
|
} catch {
|
|
1065
1247
|
debug.warn('preview', `⚠️ Cloudflare auto-pass timed out on attempt ${attempt + 1}, proceeding`);
|
|
@@ -1204,40 +1386,83 @@ export class BrowserTabManager extends EventEmitter {
|
|
|
1204
1386
|
this.requestRecovery(tabId, 'page-gone');
|
|
1205
1387
|
});
|
|
1206
1388
|
|
|
1207
|
-
|
|
1389
|
+
this.detachTabListeners(tabId);
|
|
1390
|
+
browser.on('disconnected', onDisconnected);
|
|
1391
|
+
this.tabListeners.set(tabId, { browser, onDisconnected });
|
|
1392
|
+
|
|
1393
|
+
// Popups are watched once per context, not once per tab. With a context
|
|
1394
|
+
// per tab the two were the same thing; with a context shared by the
|
|
1395
|
+
// workspace, a per-tab watcher would see every *other* tab's page as a
|
|
1396
|
+
// popup and close it on sight.
|
|
1397
|
+
this.watchContext(context);
|
|
1398
|
+
}
|
|
1399
|
+
|
|
1400
|
+
/**
|
|
1401
|
+
* Watch a context for pages that appear without us opening them.
|
|
1402
|
+
*
|
|
1403
|
+
* Told apart by their opener: a page we create programmatically has none,
|
|
1404
|
+
* while a `window.open` popup is owned by the page that called it — which
|
|
1405
|
+
* is also how the popup gets attributed to the right tab. A popup opened
|
|
1406
|
+
* with `noopener` has neither, so it falls back to the tab on screen,
|
|
1407
|
+
* unless we happen to be opening a page ourselves at that moment.
|
|
1408
|
+
*/
|
|
1409
|
+
private watchContext(context: BrowserContext): void {
|
|
1410
|
+
if (this.contextWatchers.has(context)) return;
|
|
1411
|
+
|
|
1208
1412
|
const onTargetCreated = async (target: Target) => {
|
|
1209
|
-
if (target.type()
|
|
1210
|
-
const newPage = await target.page();
|
|
1211
|
-
if (newPage && newPage !== page) {
|
|
1212
|
-
const popupUrl = newPage.url();
|
|
1213
|
-
|
|
1214
|
-
// Emit event for frontend to handle
|
|
1215
|
-
this.emit('new-window', {
|
|
1216
|
-
tabId,
|
|
1217
|
-
url: popupUrl,
|
|
1218
|
-
timestamp: Date.now()
|
|
1219
|
-
});
|
|
1413
|
+
if (target.type() !== 'page') return;
|
|
1220
1414
|
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1415
|
+
const opener = target.opener();
|
|
1416
|
+
if (!opener && this.adoptingPages > 0) return;
|
|
1417
|
+
|
|
1418
|
+
const newPage = await target.page().catch(() => null);
|
|
1419
|
+
if (!newPage) return;
|
|
1420
|
+
|
|
1421
|
+
// Never a popup: it is a tab of ours that reached the context
|
|
1422
|
+
// before its bookkeeping did.
|
|
1423
|
+
for (const tab of this.tabs.values()) {
|
|
1424
|
+
if (tab.page === newPage) return;
|
|
1425
|
+
}
|
|
1426
|
+
|
|
1427
|
+
const openerTabId = opener
|
|
1428
|
+
? (Array.from(this.tabs.values()).find((tab) => tab.page.target() === opener)?.id ?? null)
|
|
1429
|
+
: null;
|
|
1430
|
+
|
|
1431
|
+
this.emit('new-window', {
|
|
1432
|
+
tabId: openerTabId ?? this.activeTabId ?? '',
|
|
1433
|
+
url: newPage.url(),
|
|
1434
|
+
timestamp: Date.now()
|
|
1435
|
+
});
|
|
1436
|
+
|
|
1437
|
+
try {
|
|
1438
|
+
await newPage.close();
|
|
1439
|
+
} catch (error) {
|
|
1440
|
+
debug.warn('preview', 'Failed to close popup:', error);
|
|
1228
1441
|
}
|
|
1229
1442
|
};
|
|
1230
1443
|
|
|
1231
|
-
// Registered together so a rebuild can lift both at once, before the
|
|
1232
|
-
// context is asked for the page that replaces this one.
|
|
1233
|
-
this.detachTabListeners(tabId);
|
|
1234
|
-
browser.on('disconnected', onDisconnected);
|
|
1235
1444
|
context.on('targetcreated', onTargetCreated);
|
|
1236
|
-
this.
|
|
1445
|
+
this.contextWatchers.set(context, onTargetCreated);
|
|
1446
|
+
}
|
|
1447
|
+
|
|
1448
|
+
/**
|
|
1449
|
+
* Run a page-opening call with the popup watcher told to expect it.
|
|
1450
|
+
*
|
|
1451
|
+
* `targetcreated` fires while the call is still in flight, before the tab
|
|
1452
|
+
* that owns the page exists — so without this the watcher would close the
|
|
1453
|
+
* very page it was waiting for.
|
|
1454
|
+
*/
|
|
1455
|
+
private async adopt<T>(open: () => Promise<T>): Promise<T> {
|
|
1456
|
+
this.adoptingPages += 1;
|
|
1457
|
+
try {
|
|
1458
|
+
return await open();
|
|
1459
|
+
} finally {
|
|
1460
|
+
this.adoptingPages -= 1;
|
|
1461
|
+
}
|
|
1237
1462
|
}
|
|
1238
1463
|
|
|
1239
1464
|
/**
|
|
1240
|
-
*
|
|
1465
|
+
* Close a tab's page, leaving the workspace profile untouched
|
|
1241
1466
|
*/
|
|
1242
1467
|
private async cleanupContext(tab: BrowserTab) {
|
|
1243
1468
|
try {
|
|
@@ -1442,6 +1667,7 @@ export class BrowserTabManager extends EventEmitter {
|
|
|
1442
1667
|
|
|
1443
1668
|
// Force clear tabs map
|
|
1444
1669
|
for (const tabId of this.tabs.keys()) this.detachTabListeners(tabId);
|
|
1670
|
+
this.detachContextWatchers();
|
|
1445
1671
|
this.tabs.clear();
|
|
1446
1672
|
this.activeTabId = null;
|
|
1447
1673
|
this.tabActivity.clear();
|
|
@@ -1450,12 +1676,12 @@ export class BrowserTabManager extends EventEmitter {
|
|
|
1450
1676
|
|
|
1451
1677
|
this.shuttingDown = wasShuttingDown;
|
|
1452
1678
|
|
|
1453
|
-
// Deliberately NOT browserPool.cleanup():
|
|
1454
|
-
//
|
|
1455
|
-
//
|
|
1456
|
-
//
|
|
1457
|
-
//
|
|
1458
|
-
// goes, and on process shutdown.
|
|
1679
|
+
// Deliberately NOT browserPool.cleanup(): that reaches every workspace's
|
|
1680
|
+
// Chrome, and calling it from one workspace's teardown — deleting a
|
|
1681
|
+
// worktree, an admin "clean up all" — took every other project's
|
|
1682
|
+
// preview tabs down with it. Our own sessions are already gone with the
|
|
1683
|
+
// tabs above; the pool closes this workspace's Chrome once its last
|
|
1684
|
+
// session goes, and every Chrome on process shutdown.
|
|
1459
1685
|
|
|
1460
1686
|
debug.log('preview', '✅ All tabs cleaned up');
|
|
1461
1687
|
}
|
|
@@ -37,6 +37,16 @@ export interface CaptureProfile {
|
|
|
37
37
|
maxFramerate: number;
|
|
38
38
|
/** Lower bound — below this, motion stops reading as motion. */
|
|
39
39
|
minFramerate: number;
|
|
40
|
+
/**
|
|
41
|
+
* How many preview pages this host may keep running at once.
|
|
42
|
+
*
|
|
43
|
+
* A frozen tab costs nothing, but an idle *running* one costs a full
|
|
44
|
+
* renderer — so the tier that decides how many pixels we may encode also
|
|
45
|
+
* decides how many pages may be awake behind them. Only idle tabs are ever
|
|
46
|
+
* reclaimed against this number (see `browser-tab-lifecycle.ts`); a watched
|
|
47
|
+
* or agent-held tab is never counted out of existence.
|
|
48
|
+
*/
|
|
49
|
+
maxAwakeTabs: number;
|
|
40
50
|
/** VP9 per-frame quantizer while the page is moving (higher = cheaper). */
|
|
41
51
|
motionQuantizer: number;
|
|
42
52
|
/** VP9 quantizer for the still-page refresh frame (lower = sharper). */
|
|
@@ -63,6 +73,7 @@ const PROFILES: Record<QualityTier, Omit<CaptureProfile, 'tier'>> = {
|
|
|
63
73
|
// smoothness — which is the difference the eye actually notices.
|
|
64
74
|
maxFramerate: 30,
|
|
65
75
|
minFramerate: 10,
|
|
76
|
+
maxAwakeTabs: 6,
|
|
66
77
|
motionQuantizer: 38,
|
|
67
78
|
topOffQuantizer: 10,
|
|
68
79
|
screenshotQuality: 80,
|
|
@@ -74,6 +85,7 @@ const PROFILES: Record<QualityTier, Omit<CaptureProfile, 'tier'>> = {
|
|
|
74
85
|
maxPixels: 1440 * 900,
|
|
75
86
|
maxFramerate: 20,
|
|
76
87
|
minFramerate: 8,
|
|
88
|
+
maxAwakeTabs: 4,
|
|
77
89
|
motionQuantizer: 42,
|
|
78
90
|
topOffQuantizer: 14,
|
|
79
91
|
screenshotQuality: 72,
|
|
@@ -85,6 +97,7 @@ const PROFILES: Record<QualityTier, Omit<CaptureProfile, 'tier'>> = {
|
|
|
85
97
|
maxPixels: 1280 * 720,
|
|
86
98
|
maxFramerate: 12,
|
|
87
99
|
minFramerate: 6,
|
|
100
|
+
maxAwakeTabs: 2,
|
|
88
101
|
motionQuantizer: 48,
|
|
89
102
|
topOffQuantizer: 20,
|
|
90
103
|
screenshotQuality: 65,
|
|
@@ -137,7 +150,8 @@ export function getHostCaptureProfile(): CaptureProfile {
|
|
|
137
150
|
'webcodecs',
|
|
138
151
|
`Capture profile: ${tier} (${os.cpus()?.length || '?'} cores, ` +
|
|
139
152
|
`${(os.totalmem() / 1024 ** 3).toFixed(1)} GB, ${os.platform()}) — ` +
|
|
140
|
-
`≤${(cachedProfile.maxPixels / 1e6).toFixed(2)}MP @ ${cachedProfile.maxFramerate}fps`
|
|
153
|
+
`≤${(cachedProfile.maxPixels / 1e6).toFixed(2)}MP @ ${cachedProfile.maxFramerate}fps, ` +
|
|
154
|
+
`≤${cachedProfile.maxAwakeTabs} tabs awake`
|
|
141
155
|
);
|
|
142
156
|
|
|
143
157
|
return cachedProfile;
|
|
@@ -74,7 +74,7 @@ export interface BrowserTab {
|
|
|
74
74
|
|
|
75
75
|
// Browser instances (from pool)
|
|
76
76
|
browser: Browser; // Shared browser reference
|
|
77
|
-
context: BrowserContext; //
|
|
77
|
+
context: BrowserContext; // Workspace context, shared with this tab's siblings
|
|
78
78
|
page: Page;
|
|
79
79
|
|
|
80
80
|
// Streaming
|
|
@@ -210,6 +210,31 @@ export interface BrowserTabInfo {
|
|
|
210
210
|
isActive: boolean;
|
|
211
211
|
canGoBack: boolean;
|
|
212
212
|
canGoForward: boolean;
|
|
213
|
+
/**
|
|
214
|
+
* Whether the page is frozen because nobody is watching it.
|
|
215
|
+
*
|
|
216
|
+
* Carried through recovery for the same reason as the favicon: a reload
|
|
217
|
+
* must not show a sleeping tab as a running one, or the strip claims work
|
|
218
|
+
* is happening in a page that is suspended.
|
|
219
|
+
*/
|
|
220
|
+
isSleeping?: boolean;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* One site the workspace's browser profile has data for.
|
|
225
|
+
*
|
|
226
|
+
* Reported per domain rather than per storage kind: "clear what this site
|
|
227
|
+
* knows about me" is the decision a user actually makes, and splitting it into
|
|
228
|
+
* cookies, local storage and cache would ask them to understand a distinction
|
|
229
|
+
* they did not make when signing in.
|
|
230
|
+
*/
|
|
231
|
+
export interface BrowserSiteData {
|
|
232
|
+
domain: string;
|
|
233
|
+
/** Best-known origin to clear storage for. */
|
|
234
|
+
origin: string;
|
|
235
|
+
cookies: number;
|
|
236
|
+
/** Whether a tab is on this site right now. */
|
|
237
|
+
open: boolean;
|
|
213
238
|
}
|
|
214
239
|
|
|
215
240
|
/** A point in page (emulated viewport) coordinates. */
|
|
@@ -15,6 +15,7 @@ import { PtyKitManager } from '@myrialabs/ptykit/core';
|
|
|
15
15
|
import { createPtyKitServer } from '@myrialabs/ptykit/server';
|
|
16
16
|
import { projectQueries } from '$backend/database/queries';
|
|
17
17
|
import { isScopeOfProject, makeScopeKey, scopeProjectId } from '$shared/utils/workspace-scope';
|
|
18
|
+
import { writeScopeConfig } from '$backend/git/identity';
|
|
18
19
|
|
|
19
20
|
/** Terminal-friendly env, matching the previous `createCleanPtyEnv` overrides. */
|
|
20
21
|
const TERMINAL_ENV = {
|
|
@@ -51,6 +52,29 @@ export const ptyKitServer = createPtyKitServer(ptyKitManager, {
|
|
|
51
52
|
const allowed = projectQueries.userHasProject(userId, scopeProjectId(ctx.namespace));
|
|
52
53
|
if (allowed) knownNamespaces.add(ctx.namespace);
|
|
53
54
|
return allowed;
|
|
55
|
+
},
|
|
56
|
+
/**
|
|
57
|
+
* The shell inherits the git identity of whoever opened it, for the project
|
|
58
|
+
* it belongs to. Without this a `git commit` typed into the terminal would
|
|
59
|
+
* use the machine's identity while the same commit from the Git panel used
|
|
60
|
+
* the chosen one — the same repository, two different authors.
|
|
61
|
+
*
|
|
62
|
+
* Pointed at a FILE rather than given the `GIT_CONFIG_*` block the other
|
|
63
|
+
* surfaces use. A shell lives for hours and its environment is fixed at
|
|
64
|
+
* spawn, so an inlined identity goes stale the moment the user switches
|
|
65
|
+
* accounts — silently, since the tab keeps working. Git re-reads a config
|
|
66
|
+
* file on every invocation, so the switch reaches tabs that are already open.
|
|
67
|
+
* See `backend/git/identity/scope-config.ts`.
|
|
68
|
+
*
|
|
69
|
+
* `GIT_CONFIG_GLOBAL` is only set when the file was actually written: it
|
|
70
|
+
* REPLACES `~/.gitconfig`, so aiming it at a missing path would take the
|
|
71
|
+
* user's own global config away from every git command in the terminal.
|
|
72
|
+
*/
|
|
73
|
+
env: async (ctx): Promise<Record<string, string>> => {
|
|
74
|
+
const userId = ctx.conn.data.userId;
|
|
75
|
+
if (typeof userId !== 'string' || !userId) return {};
|
|
76
|
+
const path = await writeScopeConfig(userId, scopeProjectId(ctx.namespace));
|
|
77
|
+
return path ? { GIT_CONFIG_GLOBAL: path } : {};
|
|
54
78
|
}
|
|
55
79
|
});
|
|
56
80
|
|