@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
|
@@ -2,11 +2,29 @@
|
|
|
2
2
|
* Browser Pool Module
|
|
3
3
|
*
|
|
4
4
|
* Uses puppeteer-extra with StealthPlugin for Cloudflare bypass.
|
|
5
|
-
*
|
|
6
|
-
* -
|
|
7
|
-
* - Isolated BrowserContext per session (separate cookies, storage, cache)
|
|
5
|
+
* - One Chrome per workspace, launched against a profile directory on disk
|
|
6
|
+
* - Every tab is a page in that profile's default context, in its own window
|
|
8
7
|
* - StealthPlugin applied at launch time (via puppeteer-extra hooks)
|
|
9
8
|
*
|
|
9
|
+
* **Why a profile per workspace rather than a context per tab.**
|
|
10
|
+
* A `BrowserContext` is always incognito: it cannot be written to disk, and it
|
|
11
|
+
* dies with the process. Tabs in one therefore could not stay signed in — not
|
|
12
|
+
* across a restart, and (when each tab had a context of its own) not even
|
|
13
|
+
* across each other. A profile directory is what a real browser uses, and it
|
|
14
|
+
* gives both: tabs of one workspace share cookies, storage and cache, and all
|
|
15
|
+
* of it survives Clopen being stopped. Workspaces still share nothing, because
|
|
16
|
+
* the profile is keyed by the workspace scope.
|
|
17
|
+
*
|
|
18
|
+
* **Why every page gets its own window.**
|
|
19
|
+
* Tabs in one window are mutually exclusive: Chrome marks all but the
|
|
20
|
+
* foreground one `document.visibilityState === 'hidden'`, and a hidden tab
|
|
21
|
+
* cannot be captured — `getDisplayMedia` rejects outright with
|
|
22
|
+
* `InvalidStateError`, and the fallback path composites against the window
|
|
23
|
+
* instead of the tab's emulated viewport, which reaches the viewer as a
|
|
24
|
+
* letterboxed preview. Creating each page with `newWindow: true` keeps every
|
|
25
|
+
* tab visible and capturable at its own device size while still sharing the
|
|
26
|
+
* profile.
|
|
27
|
+
*
|
|
10
28
|
* Why not puppeteer-cluster?
|
|
11
29
|
* - Cluster's CONCURRENCY_CONTEXT mode accesses the browser via the raw
|
|
12
30
|
* underlying reference, bypassing puppeteer-extra's page creation hooks.
|
|
@@ -15,12 +33,17 @@
|
|
|
15
33
|
* - Direct launch() ensures puppeteer-extra wraps ALL page creation correctly.
|
|
16
34
|
*/
|
|
17
35
|
|
|
18
|
-
import { existsSync } from 'fs';
|
|
19
|
-
import
|
|
36
|
+
import { existsSync, mkdirSync, rmSync, writeFileSync, readFileSync } from 'fs';
|
|
37
|
+
import { createHash } from 'crypto';
|
|
38
|
+
import { join } from 'path';
|
|
39
|
+
import type { Browser, BrowserContext, CDPSession, Page, Protocol } from 'puppeteer';
|
|
20
40
|
import { debug } from '$shared/utils/logger';
|
|
21
41
|
import puppeteer from 'puppeteer-extra';
|
|
22
42
|
import StealthPlugin from 'puppeteer-extra-plugin-stealth';
|
|
23
43
|
import { getChromeExecutablePath } from '$backend/engine/install-recipes';
|
|
44
|
+
import { getClopenDir } from '$backend/utils/paths';
|
|
45
|
+
import { scopeSlug } from '$shared/utils/workspace-scope';
|
|
46
|
+
import { open as openSealed, seal } from '$backend/database/crypto/envelope';
|
|
24
47
|
|
|
25
48
|
puppeteer.use(StealthPlugin());
|
|
26
49
|
|
|
@@ -32,10 +55,26 @@ export interface PoolConfig {
|
|
|
32
55
|
}
|
|
33
56
|
|
|
34
57
|
export interface PooledSession {
|
|
58
|
+
browser: Browser;
|
|
35
59
|
context: BrowserContext;
|
|
36
60
|
page: Page;
|
|
37
61
|
createdAt: number;
|
|
38
62
|
sessionId: string;
|
|
63
|
+
/** The workspace profile this session's page lives in. */
|
|
64
|
+
profileKey: string;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** One workspace's Chrome, and the sessions living in it. */
|
|
68
|
+
interface ProfileBrowser {
|
|
69
|
+
key: string;
|
|
70
|
+
browser: Browser;
|
|
71
|
+
/** Browser-level CDP session — window creation, cookies, storage. */
|
|
72
|
+
cdp: CDPSession;
|
|
73
|
+
sessions: Set<string>;
|
|
74
|
+
idleTimer: ReturnType<typeof setTimeout> | null;
|
|
75
|
+
cookieTimer: ReturnType<typeof setInterval> | null;
|
|
76
|
+
/** Serializes page creation, so two tabs cannot claim each other's window. */
|
|
77
|
+
openLock: Promise<unknown>;
|
|
39
78
|
}
|
|
40
79
|
|
|
41
80
|
const DEFAULT_CONFIG: PoolConfig = {
|
|
@@ -80,6 +119,12 @@ function buildChromeArgs(): string[] {
|
|
|
80
119
|
// A headless tab is never "visible" or "focused", and Chrome
|
|
81
120
|
// aggressively de-prioritises renderers in that state — timers get
|
|
82
121
|
// clamped and compositing stalls, which reads as a frozen preview.
|
|
122
|
+
//
|
|
123
|
+
// Kept browser-wide on purpose: Chrome cannot tell the tab we are
|
|
124
|
+
// streaming from the ones nobody is watching, because in headless they
|
|
125
|
+
// look identical to it. Which pages may run is decided explicitly
|
|
126
|
+
// instead, per tab, in `browser-tab-lifecycle.ts` — these flags only
|
|
127
|
+
// stop Chrome from second-guessing that decision.
|
|
83
128
|
'--disable-background-timer-throttling',
|
|
84
129
|
'--disable-backgrounding-occluded-windows',
|
|
85
130
|
'--disable-renderer-backgrounding',
|
|
@@ -130,61 +175,85 @@ function shouldDisableGpu(): boolean {
|
|
|
130
175
|
const CHROME_ARGS = buildChromeArgs();
|
|
131
176
|
|
|
132
177
|
/**
|
|
133
|
-
* How long
|
|
178
|
+
* How long a workspace's Chrome stays up with no sessions left.
|
|
134
179
|
*
|
|
135
180
|
* Long enough that closing a tab and opening another does not pay for a
|
|
136
|
-
* relaunch, short enough that a machine is not left running
|
|
137
|
-
* nobody is using.
|
|
138
|
-
* one goes the browser has no work left to do.
|
|
181
|
+
* relaunch, short enough that a machine is not left running headless Chromes
|
|
182
|
+
* nobody is using. Nothing is lost when it goes: the profile is on disk.
|
|
139
183
|
*/
|
|
140
184
|
const IDLE_BROWSER_CLOSE_MS = 60_000;
|
|
141
185
|
|
|
186
|
+
/** How often a live browser's session cookies are written to disk. */
|
|
187
|
+
const COOKIE_FLUSH_INTERVAL_MS = 60_000;
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Where a workspace's Chrome profile lives.
|
|
191
|
+
*
|
|
192
|
+
* Hashed rather than slugged alone: `scopeSlug` truncates, and two workspaces
|
|
193
|
+
* that collided would share a login.
|
|
194
|
+
*/
|
|
195
|
+
function profilesRoot(): string {
|
|
196
|
+
return join(getClopenDir(), 'preview', 'profiles');
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function profileDirName(profileKey: string): string {
|
|
200
|
+
const digest = createHash('sha256').update(profileKey).digest('hex').slice(0, 16);
|
|
201
|
+
return `${scopeSlug(profileKey) || 'ws'}-${digest}`;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function profileDir(profileKey: string): string {
|
|
205
|
+
return join(profilesRoot(), profileDirName(profileKey));
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Session cookies, kept beside the profile.
|
|
210
|
+
*
|
|
211
|
+
* Chrome drops these when it exits — that is what "session" means, and it is
|
|
212
|
+
* why a profile alone does not keep you signed into an app that issues one
|
|
213
|
+
* (which most dev servers do). Carrying them across a restart is the whole
|
|
214
|
+
* point of the persistent preview, so they are saved and put back by hand.
|
|
215
|
+
* Sealed, because a session cookie is a credential.
|
|
216
|
+
*/
|
|
217
|
+
function cookieFile(profileKey: string): string {
|
|
218
|
+
return join(profilesRoot(), `${profileDirName(profileKey)}.cookies`);
|
|
219
|
+
}
|
|
220
|
+
|
|
142
221
|
class BrowserPool {
|
|
143
|
-
private
|
|
222
|
+
private browsers = new Map<string, ProfileBrowser>();
|
|
144
223
|
private sessions = new Map<string, PooledSession>();
|
|
224
|
+
private launches = new Map<string, Promise<ProfileBrowser>>();
|
|
145
225
|
private config: PoolConfig;
|
|
146
|
-
private isLaunching = false;
|
|
147
|
-
private launchPromise: Promise<Browser> | null = null;
|
|
148
|
-
private idleCloseTimer: ReturnType<typeof setTimeout> | null = null;
|
|
149
226
|
|
|
150
227
|
constructor(config: Partial<PoolConfig> = {}) {
|
|
151
228
|
this.config = { ...DEFAULT_CONFIG, ...config };
|
|
152
229
|
}
|
|
153
230
|
|
|
154
231
|
/**
|
|
155
|
-
* Get or
|
|
156
|
-
* Uses puppeteer-extra directly (same as test-cf.ts) to ensure
|
|
157
|
-
* StealthPlugin hooks fire for every page created.
|
|
232
|
+
* Get or launch the Chrome that owns a workspace's profile.
|
|
158
233
|
*/
|
|
159
|
-
async
|
|
160
|
-
this.
|
|
161
|
-
|
|
162
|
-
if (this.browser?.connected) {
|
|
163
|
-
return this.browser;
|
|
164
|
-
}
|
|
234
|
+
async getBrowserFor(profileKey: string): Promise<Browser> {
|
|
235
|
+
return (await this.acquireBrowser(profileKey)).browser;
|
|
236
|
+
}
|
|
165
237
|
|
|
166
|
-
|
|
167
|
-
|
|
238
|
+
private async acquireBrowser(profileKey: string): Promise<ProfileBrowser> {
|
|
239
|
+
const existing = this.browsers.get(profileKey);
|
|
240
|
+
if (existing?.browser.connected) {
|
|
241
|
+
this.cancelIdleClose(existing);
|
|
242
|
+
return existing;
|
|
168
243
|
}
|
|
169
244
|
|
|
170
|
-
|
|
171
|
-
|
|
245
|
+
const inFlight = this.launches.get(profileKey);
|
|
246
|
+
if (inFlight) return inFlight;
|
|
172
247
|
|
|
173
|
-
|
|
174
|
-
this.
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
this.launchPromise = null;
|
|
179
|
-
}
|
|
248
|
+
const launch = this.launchProfile(profileKey).finally(() => {
|
|
249
|
+
this.launches.delete(profileKey);
|
|
250
|
+
});
|
|
251
|
+
this.launches.set(profileKey, launch);
|
|
252
|
+
return launch;
|
|
180
253
|
}
|
|
181
254
|
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
* This matches test-cf.ts which successfully bypasses Cloudflare.
|
|
185
|
-
*/
|
|
186
|
-
private async launchBrowser(): Promise<Browser> {
|
|
187
|
-
debug.log('preview', '🚀 Launching browser with puppeteer-extra + StealthPlugin...');
|
|
255
|
+
private async launchProfile(profileKey: string): Promise<ProfileBrowser> {
|
|
256
|
+
debug.log('preview', `🚀 Launching Chrome for workspace profile ${profileKey}...`);
|
|
188
257
|
|
|
189
258
|
// Use the clopen-managed Chrome for Testing under ~/.clopen/bin
|
|
190
259
|
// (macOS/Windows) or the system Google Chrome / chromium installed
|
|
@@ -193,92 +262,161 @@ class BrowserPool {
|
|
|
193
262
|
if (!executablePath) {
|
|
194
263
|
throw new Error('Chrome not installed. Go to Settings → Stack and click Install.');
|
|
195
264
|
}
|
|
265
|
+
|
|
266
|
+
const userDataDir = profileDir(profileKey);
|
|
267
|
+
mkdirSync(userDataDir, { recursive: true });
|
|
196
268
|
debug.log('preview', ` using Chrome at: ${executablePath}`);
|
|
269
|
+
debug.log('preview', ` profile: ${userDataDir}`);
|
|
197
270
|
|
|
198
|
-
const browser = await puppeteer.launch({
|
|
271
|
+
const browser = (await puppeteer.launch({
|
|
199
272
|
headless: true,
|
|
200
273
|
executablePath,
|
|
274
|
+
userDataDir,
|
|
201
275
|
args: CHROME_ARGS
|
|
202
|
-
}) as unknown as Browser;
|
|
203
|
-
|
|
204
|
-
|
|
276
|
+
})) as unknown as Browser;
|
|
277
|
+
|
|
278
|
+
const entry: ProfileBrowser = {
|
|
279
|
+
key: profileKey,
|
|
280
|
+
browser,
|
|
281
|
+
cdp: await browser.target().createCDPSession(),
|
|
282
|
+
sessions: new Set(),
|
|
283
|
+
idleTimer: null,
|
|
284
|
+
cookieTimer: null,
|
|
285
|
+
openLock: Promise.resolve()
|
|
286
|
+
};
|
|
205
287
|
|
|
206
|
-
// Handle browser disconnection
|
|
207
288
|
browser.on('disconnected', () => {
|
|
208
|
-
debug.warn('preview',
|
|
209
|
-
this.
|
|
210
|
-
// Close all sessions since browser is gone
|
|
211
|
-
this.sessions.clear();
|
|
289
|
+
debug.warn('preview', `⚠️ Chrome for ${profileKey} disconnected`);
|
|
290
|
+
this.forgetBrowser(entry);
|
|
212
291
|
});
|
|
213
292
|
|
|
214
|
-
|
|
293
|
+
// Chrome opens a page of its own at launch. Every tab we care about is
|
|
294
|
+
// created in a window of its own, so this one is only a spare renderer
|
|
295
|
+
// and a target the popup watcher would have to reason about.
|
|
296
|
+
for (const page of await browser.pages()) {
|
|
297
|
+
await page.close().catch(() => {});
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
this.browsers.set(profileKey, entry);
|
|
301
|
+
await this.restoreSessionCookies(entry);
|
|
302
|
+
|
|
303
|
+
entry.cookieTimer = setInterval(() => {
|
|
304
|
+
void this.saveSessionCookies(entry);
|
|
305
|
+
}, COOKIE_FLUSH_INTERVAL_MS);
|
|
306
|
+
// Flushing cookies is never a reason to hold the process open.
|
|
307
|
+
entry.cookieTimer.unref?.();
|
|
308
|
+
|
|
309
|
+
debug.log('preview', `✅ Chrome ready for ${profileKey}`);
|
|
310
|
+
return entry;
|
|
215
311
|
}
|
|
216
312
|
|
|
217
313
|
/**
|
|
218
|
-
* Create
|
|
219
|
-
*
|
|
314
|
+
* Create a session: one page, in its own window, in the workspace profile.
|
|
315
|
+
*
|
|
316
|
+
* `profileKey` is the workspace scope. Sessions under different keys share
|
|
317
|
+
* nothing; sessions under the same key share cookies, storage and cache,
|
|
318
|
+
* exactly as two tabs of one browser would.
|
|
220
319
|
*/
|
|
221
|
-
async createSession(sessionId: string): Promise<PooledSession> {
|
|
222
|
-
this.cancelIdleClose();
|
|
223
|
-
|
|
320
|
+
async createSession(sessionId: string, profileKey?: string): Promise<PooledSession> {
|
|
224
321
|
const existing = this.sessions.get(sessionId);
|
|
225
322
|
if (existing) {
|
|
226
323
|
debug.log('preview', `♻️ Reusing existing session: ${sessionId}`);
|
|
227
324
|
return existing;
|
|
228
325
|
}
|
|
229
326
|
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
const browser = await this.getBrowser();
|
|
327
|
+
const key = profileKey || sessionId;
|
|
328
|
+
debug.log('preview', `🔒 Creating session: ${sessionId} (profile: ${key})`);
|
|
233
329
|
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
const context = await browser.createBrowserContext();
|
|
237
|
-
const page = await context.newPage();
|
|
330
|
+
const entry = await this.acquireBrowser(key);
|
|
331
|
+
const page = await this.openWindowPage(entry);
|
|
238
332
|
|
|
239
333
|
const session: PooledSession = {
|
|
240
|
-
|
|
334
|
+
browser: entry.browser,
|
|
335
|
+
context: page.browserContext(),
|
|
241
336
|
page,
|
|
242
337
|
createdAt: Date.now(),
|
|
243
|
-
sessionId
|
|
338
|
+
sessionId,
|
|
339
|
+
profileKey: key
|
|
244
340
|
};
|
|
245
341
|
|
|
246
342
|
this.sessions.set(sessionId, session);
|
|
343
|
+
entry.sessions.add(sessionId);
|
|
344
|
+
this.cancelIdleClose(entry);
|
|
247
345
|
|
|
248
|
-
debug.log(
|
|
346
|
+
debug.log(
|
|
347
|
+
'preview',
|
|
348
|
+
`✅ Session created: ${sessionId} (total: ${this.sessions.size}, profiles: ${this.browsers.size})`
|
|
349
|
+
);
|
|
249
350
|
|
|
250
351
|
return session;
|
|
251
352
|
}
|
|
252
353
|
|
|
253
354
|
/**
|
|
254
|
-
*
|
|
355
|
+
* Open a page in a window of its own.
|
|
255
356
|
*
|
|
256
|
-
*
|
|
257
|
-
*
|
|
258
|
-
*
|
|
259
|
-
*
|
|
260
|
-
*
|
|
357
|
+
* `newWindow` is only reachable over CDP — `newPage()` always opens a tab
|
|
358
|
+
* in the existing window, where Chrome would mark it hidden and refuse to
|
|
359
|
+
* capture it. Serialized per browser: the new target is recognised by
|
|
360
|
+
* diffing the browser's target list, and two creations in flight at once
|
|
361
|
+
* could hand each other's page back.
|
|
261
362
|
*/
|
|
262
|
-
|
|
263
|
-
|
|
363
|
+
private openWindowPage(entry: ProfileBrowser): Promise<Page> {
|
|
364
|
+
const run = async (): Promise<Page> => {
|
|
365
|
+
const before = new Set(entry.browser.targets());
|
|
366
|
+
|
|
367
|
+
await entry.cdp.send('Target.createTarget', {
|
|
368
|
+
url: 'about:blank',
|
|
369
|
+
newWindow: true
|
|
370
|
+
} as Protocol.Target.CreateTargetRequest);
|
|
371
|
+
|
|
372
|
+
const target = await entry.browser.waitForTarget(
|
|
373
|
+
(candidate) => candidate.type() === 'page' && !before.has(candidate),
|
|
374
|
+
{ timeout: 30_000 }
|
|
375
|
+
);
|
|
376
|
+
|
|
377
|
+
const page = await target.page();
|
|
378
|
+
if (!page) throw new Error('Chrome opened a window with no page in it');
|
|
379
|
+
return page;
|
|
380
|
+
};
|
|
381
|
+
|
|
382
|
+
const queued = entry.openLock.then(run, run);
|
|
383
|
+
// Swallowed on the lock only: the caller still sees the rejection.
|
|
384
|
+
entry.openLock = queued.catch(() => {});
|
|
385
|
+
return queued;
|
|
386
|
+
}
|
|
264
387
|
|
|
388
|
+
/**
|
|
389
|
+
* Give a session a fresh page in the same profile.
|
|
390
|
+
*
|
|
391
|
+
* A crashed renderer takes the page but leaves the profile — and with it
|
|
392
|
+
* the cookies and storage the tab has built up — so only the page is
|
|
393
|
+
* replaced.
|
|
394
|
+
*/
|
|
395
|
+
async renewSessionPage(sessionId: string, profileKey?: string): Promise<PooledSession> {
|
|
265
396
|
const existing = this.sessions.get(sessionId);
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
397
|
+
const key = profileKey || existing?.profileKey || sessionId;
|
|
398
|
+
|
|
399
|
+
if (existing) {
|
|
400
|
+
const entry = this.browsers.get(key);
|
|
401
|
+
if (entry?.browser.connected) {
|
|
402
|
+
try {
|
|
403
|
+
const page = await this.openWindowPage(entry);
|
|
404
|
+
if (!existing.page.isClosed()) {
|
|
405
|
+
await existing.page.close().catch(() => {});
|
|
406
|
+
}
|
|
407
|
+
existing.page = page;
|
|
408
|
+
existing.browser = entry.browser;
|
|
409
|
+
existing.context = page.browserContext();
|
|
410
|
+
debug.log('preview', `♻️ Session ${sessionId}: new window in the surviving profile`);
|
|
411
|
+
return existing;
|
|
412
|
+
} catch (error) {
|
|
413
|
+
debug.warn('preview', `⚠️ Profile ${key} could not hand out a page: ${error}`);
|
|
271
414
|
}
|
|
272
|
-
existing.page = page;
|
|
273
|
-
debug.log('preview', `♻️ Session ${sessionId}: new page in the surviving context`);
|
|
274
|
-
return existing;
|
|
275
|
-
} catch (error) {
|
|
276
|
-
debug.warn('preview', `⚠️ Context for ${sessionId} could not hand out a page: ${error}`);
|
|
277
415
|
}
|
|
278
416
|
}
|
|
279
417
|
|
|
280
418
|
await this.destroySession(sessionId);
|
|
281
|
-
return this.createSession(sessionId);
|
|
419
|
+
return this.createSession(sessionId, key);
|
|
282
420
|
}
|
|
283
421
|
|
|
284
422
|
/**
|
|
@@ -312,50 +450,320 @@ class BrowserPool {
|
|
|
312
450
|
debug.warn('preview', `Error closing page: ${err.message}`);
|
|
313
451
|
});
|
|
314
452
|
}
|
|
315
|
-
|
|
316
|
-
await session.context.close().catch((err: Error) => {
|
|
317
|
-
debug.warn('preview', `Error closing context: ${err.message}`);
|
|
318
|
-
});
|
|
319
453
|
} catch (error) {
|
|
320
454
|
debug.warn('preview', `⚠️ Error destroying session: ${error}`);
|
|
321
455
|
}
|
|
322
456
|
|
|
323
457
|
this.sessions.delete(sessionId);
|
|
324
|
-
debug.log('preview', `✅ Session destroyed (remaining: ${this.sessions.size})`);
|
|
325
458
|
|
|
326
|
-
|
|
459
|
+
// The profile is deliberately untouched. Closing the last tab of a
|
|
460
|
+
// workspace used to take its cookies with it, so opening the same URL
|
|
461
|
+
// again asked for a fresh login — the browser equivalent of losing your
|
|
462
|
+
// session because you closed a tab.
|
|
463
|
+
const entry = this.browsers.get(session.profileKey);
|
|
464
|
+
if (entry) {
|
|
465
|
+
entry.sessions.delete(sessionId);
|
|
466
|
+
if (entry.sessions.size === 0) this.scheduleIdleClose(entry);
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
debug.log('preview', `✅ Session destroyed (remaining: ${this.sessions.size})`);
|
|
327
470
|
}
|
|
328
471
|
|
|
329
472
|
/**
|
|
330
|
-
* Close
|
|
473
|
+
* Close a workspace's Chrome once nothing has referenced it for a while.
|
|
331
474
|
*
|
|
332
|
-
*
|
|
333
|
-
*
|
|
475
|
+
* Safe in a way it never used to be: the profile outlives the process, so
|
|
476
|
+
* the only thing a relaunch costs is the launch itself.
|
|
334
477
|
*/
|
|
335
|
-
private scheduleIdleClose(): void {
|
|
336
|
-
this.cancelIdleClose();
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
this.browser = null;
|
|
345
|
-
debug.log('preview', '💤 No sessions left, closing the shared browser');
|
|
346
|
-
browser?.close().catch((error) => {
|
|
347
|
-
debug.warn('preview', `⚠️ Error closing idle browser: ${error}`);
|
|
348
|
-
});
|
|
478
|
+
private scheduleIdleClose(entry: ProfileBrowser): void {
|
|
479
|
+
this.cancelIdleClose(entry);
|
|
480
|
+
|
|
481
|
+
entry.idleTimer = setTimeout(() => {
|
|
482
|
+
entry.idleTimer = null;
|
|
483
|
+
if (entry.sessions.size > 0) return;
|
|
484
|
+
|
|
485
|
+
debug.log('preview', `💤 No sessions left for ${entry.key}, closing its Chrome`);
|
|
486
|
+
void this.closeBrowser(entry);
|
|
349
487
|
}, IDLE_BROWSER_CLOSE_MS);
|
|
350
488
|
|
|
351
489
|
// Nothing here should hold the process open on its own.
|
|
352
|
-
|
|
490
|
+
entry.idleTimer.unref?.();
|
|
353
491
|
}
|
|
354
492
|
|
|
355
|
-
private cancelIdleClose(): void {
|
|
356
|
-
if (!
|
|
357
|
-
clearTimeout(
|
|
358
|
-
|
|
493
|
+
private cancelIdleClose(entry: ProfileBrowser): void {
|
|
494
|
+
if (!entry.idleTimer) return;
|
|
495
|
+
clearTimeout(entry.idleTimer);
|
|
496
|
+
entry.idleTimer = null;
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
private forgetBrowser(entry: ProfileBrowser): void {
|
|
500
|
+
this.cancelIdleClose(entry);
|
|
501
|
+
if (entry.cookieTimer) {
|
|
502
|
+
clearInterval(entry.cookieTimer);
|
|
503
|
+
entry.cookieTimer = null;
|
|
504
|
+
}
|
|
505
|
+
for (const sessionId of entry.sessions) this.sessions.delete(sessionId);
|
|
506
|
+
entry.sessions.clear();
|
|
507
|
+
if (this.browsers.get(entry.key) === entry) this.browsers.delete(entry.key);
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
private async closeBrowser(entry: ProfileBrowser): Promise<void> {
|
|
511
|
+
await this.saveSessionCookies(entry);
|
|
512
|
+
this.forgetBrowser(entry);
|
|
513
|
+
|
|
514
|
+
try {
|
|
515
|
+
await entry.browser.close();
|
|
516
|
+
} catch (error) {
|
|
517
|
+
debug.warn('preview', `⚠️ Error closing Chrome for ${entry.key}: ${error}`);
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
// ── Session cookies ──────────────────────────────────────────────────────
|
|
522
|
+
|
|
523
|
+
private async saveSessionCookies(entry: ProfileBrowser): Promise<void> {
|
|
524
|
+
if (!entry.browser.connected) return;
|
|
525
|
+
|
|
526
|
+
try {
|
|
527
|
+
const { cookies } = (await entry.cdp.send(
|
|
528
|
+
'Storage.getCookies'
|
|
529
|
+
)) as Protocol.Storage.GetCookiesResponse;
|
|
530
|
+
|
|
531
|
+
// Only the ones Chrome is about to throw away. Persistent cookies
|
|
532
|
+
// are already in the profile, and writing them out again would let
|
|
533
|
+
// a stale copy overwrite a fresher one on the next launch.
|
|
534
|
+
const session = cookies.filter((cookie) => cookie.session);
|
|
535
|
+
|
|
536
|
+
mkdirSync(profilesRoot(), { recursive: true });
|
|
537
|
+
const payload = seal(JSON.stringify(session)) ?? '';
|
|
538
|
+
writeFileSync(cookieFile(entry.key), payload, { mode: 0o600 });
|
|
539
|
+
} catch (error) {
|
|
540
|
+
debug.warn('preview', `⚠️ Could not save session cookies for ${entry.key}: ${error}`);
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
private async restoreSessionCookies(entry: ProfileBrowser): Promise<void> {
|
|
545
|
+
const path = cookieFile(entry.key);
|
|
546
|
+
if (!existsSync(path)) return;
|
|
547
|
+
|
|
548
|
+
try {
|
|
549
|
+
const raw = openSealed(readFileSync(path, 'utf8'));
|
|
550
|
+
if (!raw) return;
|
|
551
|
+
|
|
552
|
+
const cookies = JSON.parse(raw) as Protocol.Network.CookieParam[];
|
|
553
|
+
if (!Array.isArray(cookies) || cookies.length === 0) return;
|
|
554
|
+
|
|
555
|
+
await entry.cdp.send('Storage.setCookies', { cookies });
|
|
556
|
+
debug.log('preview', `🍪 Restored ${cookies.length} session cookie(s) for ${entry.key}`);
|
|
557
|
+
} catch (error) {
|
|
558
|
+
debug.warn('preview', `⚠️ Could not restore session cookies for ${entry.key}: ${error}`);
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
// ── Browsing data ────────────────────────────────────────────────────────
|
|
563
|
+
|
|
564
|
+
/**
|
|
565
|
+
* Sites this workspace has data for, most cookies first.
|
|
566
|
+
*
|
|
567
|
+
* Derived from the cookie jar rather than a storage enumeration, which CDP
|
|
568
|
+
* does not offer: every login leaves a cookie, so this is the list a user
|
|
569
|
+
* would actually recognise. Origins currently open are folded in by the
|
|
570
|
+
* caller, which knows the tabs.
|
|
571
|
+
*/
|
|
572
|
+
async listBrowsingOrigins(
|
|
573
|
+
profileKey: string
|
|
574
|
+
): Promise<{ domain: string; cookies: number; secure: boolean }[]> {
|
|
575
|
+
// Launched if it is not up: the profile outlives its Chrome, so "no
|
|
576
|
+
// browser running" is not the same as "nothing stored" — and answering
|
|
577
|
+
// with an empty list would tell the user their logins were already gone.
|
|
578
|
+
const entry = await this.acquireBrowser(profileKey).catch(() => null);
|
|
579
|
+
if (!entry?.browser.connected) return [];
|
|
580
|
+
|
|
581
|
+
try {
|
|
582
|
+
const { cookies } = (await entry.cdp.send(
|
|
583
|
+
'Storage.getCookies'
|
|
584
|
+
)) as Protocol.Storage.GetCookiesResponse;
|
|
585
|
+
|
|
586
|
+
const byDomain = new Map<string, { cookies: number; secure: boolean }>();
|
|
587
|
+
for (const cookie of cookies) {
|
|
588
|
+
const domain = cookie.domain.replace(/^\./, '');
|
|
589
|
+
const entryFor = byDomain.get(domain) ?? { cookies: 0, secure: false };
|
|
590
|
+
entryFor.cookies += 1;
|
|
591
|
+
// A domain with no open tab has no origin of its own to report,
|
|
592
|
+
// and clearing needs one. A Secure cookie is the only evidence
|
|
593
|
+
// left that the site was https, so it decides the guess.
|
|
594
|
+
entryFor.secure ||= cookie.secure;
|
|
595
|
+
byDomain.set(domain, entryFor);
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
return Array.from(byDomain, ([domain, value]) => ({ domain, ...value })).sort(
|
|
599
|
+
(a, b) => b.cookies - a.cookies || a.domain.localeCompare(b.domain)
|
|
600
|
+
);
|
|
601
|
+
} catch (error) {
|
|
602
|
+
debug.warn('preview', `⚠️ Could not list browsing data for ${profileKey}: ${error}`);
|
|
603
|
+
return [];
|
|
604
|
+
} finally {
|
|
605
|
+
// Opened only to be read: let it go again on the usual timer.
|
|
606
|
+
if (entry.sessions.size === 0) this.scheduleIdleClose(entry);
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
/**
|
|
611
|
+
* A page CDP session in this profile, and whether we opened it ourselves.
|
|
612
|
+
*
|
|
613
|
+
* `Storage.clearDataForOrigin` is refused on a browser-level session with a
|
|
614
|
+
* bare "Internal error" — it needs a frame to resolve the storage partition
|
|
615
|
+
* against. Any page will do, including one on an unrelated origin, so an
|
|
616
|
+
* open tab is borrowed where there is one and a scratch window opened where
|
|
617
|
+
* there is not.
|
|
618
|
+
*/
|
|
619
|
+
private async pageSessionFor(entry: ProfileBrowser): Promise<{ cdp: CDPSession; scratch: Page | null }> {
|
|
620
|
+
for (const session of this.sessions.values()) {
|
|
621
|
+
if (session.profileKey !== entry.key) continue;
|
|
622
|
+
if (session.page.isClosed()) continue;
|
|
623
|
+
return { cdp: await session.page.createCDPSession(), scratch: null };
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
const scratch = await this.openWindowPage(entry);
|
|
627
|
+
return { cdp: await scratch.createCDPSession(), scratch };
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
/**
|
|
631
|
+
* Forget what a workspace's browser knows — one origin, or all of it.
|
|
632
|
+
*
|
|
633
|
+
* Done in place rather than by deleting the profile directory: the tabs
|
|
634
|
+
* stay open and keep their pages, exactly as clearing data in a real
|
|
635
|
+
* browser leaves the window you did it from standing.
|
|
636
|
+
*/
|
|
637
|
+
async clearBrowsingData(profileKey: string, origin?: string): Promise<boolean> {
|
|
638
|
+
if (!origin) return this.wipeProfile(profileKey);
|
|
639
|
+
|
|
640
|
+
const entry = await this.acquireBrowser(profileKey).catch(() => null);
|
|
641
|
+
if (!entry?.browser.connected) return false;
|
|
642
|
+
|
|
643
|
+
const { cdp, scratch } = await this.pageSessionFor(entry);
|
|
644
|
+
|
|
645
|
+
try {
|
|
646
|
+
await cdp.send('Storage.clearDataForOrigin', { origin, storageTypes: 'all' });
|
|
647
|
+
const cookies = await this.deleteCookiesForHost(entry, cdp, origin);
|
|
648
|
+
await this.dropSavedCookiesFor(entry, origin);
|
|
649
|
+
debug.log(
|
|
650
|
+
'preview',
|
|
651
|
+
`🧹 Cleared browsing data for ${origin} (${profileKey}), ${cookies} cookie(s)`
|
|
652
|
+
);
|
|
653
|
+
return true;
|
|
654
|
+
} catch (error) {
|
|
655
|
+
debug.warn('preview', `⚠️ Could not clear ${origin} for ${profileKey}: ${error}`);
|
|
656
|
+
return false;
|
|
657
|
+
} finally {
|
|
658
|
+
await cdp.detach().catch(() => {});
|
|
659
|
+
if (scratch) await scratch.close().catch(() => {});
|
|
660
|
+
if (entry.sessions.size === 0) this.scheduleIdleClose(entry);
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
/**
|
|
665
|
+
* Empty a workspace's profile completely.
|
|
666
|
+
*
|
|
667
|
+
* Done by closing Chrome and deleting the directory rather than by clearing
|
|
668
|
+
* origin by origin: the storage of a site whose tab was closed weeks ago
|
|
669
|
+
* cannot be enumerated over CDP, so per-origin clearing would leave exactly
|
|
670
|
+
* the data the user came here to remove. Open tabs lose their page and are
|
|
671
|
+
* rebuilt by the recovery path, which is what clearing everything means.
|
|
672
|
+
*/
|
|
673
|
+
private async wipeProfile(profileKey: string): Promise<boolean> {
|
|
674
|
+
const entry = this.browsers.get(profileKey);
|
|
675
|
+
|
|
676
|
+
if (entry) {
|
|
677
|
+
// Not closeBrowser(): that flushes the session cookies we are here
|
|
678
|
+
// to destroy, writing them straight back over the wipe.
|
|
679
|
+
this.forgetBrowser(entry);
|
|
680
|
+
await entry.browser.close().catch((error) => {
|
|
681
|
+
debug.warn('preview', `⚠️ Error closing Chrome for ${profileKey}: ${error}`);
|
|
682
|
+
});
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
try {
|
|
686
|
+
rmSync(profileDir(profileKey), { recursive: true, force: true });
|
|
687
|
+
rmSync(cookieFile(profileKey), { force: true });
|
|
688
|
+
debug.log('preview', `🧹 Wiped the browsing profile for ${profileKey}`);
|
|
689
|
+
return true;
|
|
690
|
+
} catch (error) {
|
|
691
|
+
debug.warn('preview', `⚠️ Could not wipe the profile for ${profileKey}: ${error}`);
|
|
692
|
+
return false;
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
/**
|
|
697
|
+
* Delete every cookie filed under a site's domain.
|
|
698
|
+
*
|
|
699
|
+
* `Storage.clearDataForOrigin` is not enough on its own: it takes out an
|
|
700
|
+
* origin's host-only cookies and leaves the domain-wide ones (`.site.com`)
|
|
701
|
+
* standing — which is most of a real login. The visible result was a site
|
|
702
|
+
* that was genuinely signed out while the panel still counted its cookies,
|
|
703
|
+
* because the jar the panel reads had barely changed.
|
|
704
|
+
*
|
|
705
|
+
* Matched on the domain with its leading dot stripped, which is exactly how
|
|
706
|
+
* the panel groups cookies into rows: what a row counts is what its Clear
|
|
707
|
+
* removes, and a cookie shown under another row is left for that row.
|
|
708
|
+
*/
|
|
709
|
+
private async deleteCookiesForHost(
|
|
710
|
+
entry: ProfileBrowser,
|
|
711
|
+
cdp: CDPSession,
|
|
712
|
+
origin: string
|
|
713
|
+
): Promise<number> {
|
|
714
|
+
let host: string;
|
|
715
|
+
try {
|
|
716
|
+
host = new URL(origin).hostname;
|
|
717
|
+
} catch {
|
|
718
|
+
return 0;
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
const { cookies } = (await entry.cdp.send(
|
|
722
|
+
'Storage.getCookies'
|
|
723
|
+
)) as Protocol.Storage.GetCookiesResponse;
|
|
724
|
+
|
|
725
|
+
const mine = cookies.filter((cookie) => cookie.domain.replace(/^\./, '') === host);
|
|
726
|
+
|
|
727
|
+
for (const cookie of mine) {
|
|
728
|
+
await cdp
|
|
729
|
+
.send('Network.deleteCookies', {
|
|
730
|
+
name: cookie.name,
|
|
731
|
+
domain: cookie.domain,
|
|
732
|
+
path: cookie.path
|
|
733
|
+
})
|
|
734
|
+
.catch(() => {});
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
return mine.length;
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
/** Drop one site's cookies from the saved session snapshot. */
|
|
741
|
+
private async dropSavedCookiesFor(entry: ProfileBrowser, origin: string): Promise<void> {
|
|
742
|
+
const path = cookieFile(entry.key);
|
|
743
|
+
if (!existsSync(path)) return;
|
|
744
|
+
|
|
745
|
+
let host: string;
|
|
746
|
+
try {
|
|
747
|
+
host = new URL(origin).hostname;
|
|
748
|
+
} catch {
|
|
749
|
+
return;
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
try {
|
|
753
|
+
const raw = openSealed(readFileSync(path, 'utf8'));
|
|
754
|
+
if (!raw) return;
|
|
755
|
+
|
|
756
|
+
// Same rule as the live jar, so a cleared site cannot be restored
|
|
757
|
+
// from the snapshot on the next launch.
|
|
758
|
+
const cookies = JSON.parse(raw) as Protocol.Network.CookieParam[];
|
|
759
|
+
const kept = cookies.filter(
|
|
760
|
+
(cookie) => (cookie.domain ?? '').replace(/^\./, '') !== host
|
|
761
|
+
);
|
|
762
|
+
|
|
763
|
+
writeFileSync(path, seal(JSON.stringify(kept)) ?? '', { mode: 0o600 });
|
|
764
|
+
} catch {
|
|
765
|
+
// A snapshot we cannot rewrite is one the next launch will overwrite.
|
|
766
|
+
}
|
|
359
767
|
}
|
|
360
768
|
|
|
361
769
|
/**
|
|
@@ -373,11 +781,13 @@ class BrowserPool {
|
|
|
373
781
|
*/
|
|
374
782
|
getStats() {
|
|
375
783
|
return {
|
|
376
|
-
browserConnected: this.browser
|
|
784
|
+
browserConnected: Array.from(this.browsers.values()).some((entry) => entry.browser.connected),
|
|
785
|
+
activeProfiles: this.browsers.size,
|
|
377
786
|
activeSessions: this.sessions.size,
|
|
378
787
|
maxConcurrency: this.config.maxConcurrency,
|
|
379
788
|
sessions: Array.from(this.sessions.entries()).map(([id, session]) => ({
|
|
380
789
|
sessionId: id,
|
|
790
|
+
profileKey: session.profileKey,
|
|
381
791
|
createdAt: session.createdAt,
|
|
382
792
|
ageMs: Date.now() - session.createdAt,
|
|
383
793
|
pageOpen: !session.page.isClosed()
|
|
@@ -390,19 +800,12 @@ class BrowserPool {
|
|
|
390
800
|
*/
|
|
391
801
|
async cleanup(): Promise<void> {
|
|
392
802
|
debug.log('preview', '🧹 Cleaning up browser pool...');
|
|
393
|
-
this.cancelIdleClose();
|
|
394
803
|
|
|
395
|
-
const
|
|
396
|
-
await Promise.all(
|
|
804
|
+
const entries = Array.from(this.browsers.values());
|
|
805
|
+
await Promise.all(entries.map((entry) => this.closeBrowser(entry)));
|
|
397
806
|
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
await this.browser.close();
|
|
401
|
-
} catch (error) {
|
|
402
|
-
debug.warn('preview', `⚠️ Error closing browser: ${error}`);
|
|
403
|
-
}
|
|
404
|
-
this.browser = null;
|
|
405
|
-
}
|
|
807
|
+
this.sessions.clear();
|
|
808
|
+
this.browsers.clear();
|
|
406
809
|
|
|
407
810
|
debug.log('preview', '✅ Browser pool cleaned up');
|
|
408
811
|
}
|