@myrialabs/clopen 0.4.41 → 0.4.43

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.
Files changed (72) hide show
  1. package/backend/chat/stream-manager.ts +8 -0
  2. package/backend/database/crypto/secret-columns.ts +5 -1
  3. package/backend/database/index.ts +18 -0
  4. package/backend/database/migrations/082_create_git_identities.test.ts +186 -0
  5. package/backend/database/migrations/082_create_git_identities.ts +122 -0
  6. package/backend/database/migrations/index.ts +7 -0
  7. package/backend/database/queries/git-identity-queries.ts +290 -0
  8. package/backend/database/queries/index.ts +2 -0
  9. package/backend/db-client/env/detect.ts +2 -1
  10. package/backend/engine/adapters/claude/environment.ts +11 -1
  11. package/backend/engine/adapters/claude/models.ts +147 -18
  12. package/backend/engine/adapters/claude/stream.ts +1 -1
  13. package/backend/engine/adapters/codex/models.ts +13 -9
  14. package/backend/engine/adapters/codex/stream.ts +35 -3
  15. package/backend/engine/adapters/opencode/server.ts +26 -2
  16. package/backend/engine/adapters/opencode/stream.ts +4 -1
  17. package/backend/engine/adapters/qwen/stream.ts +3 -1
  18. package/backend/engine/types.ts +10 -0
  19. package/backend/env-files/discovery.ts +2 -1
  20. package/backend/files/file-reading.ts +4 -3
  21. package/backend/files/path-browsing.ts +2 -1
  22. package/backend/git/git-executor.ts +28 -2
  23. package/backend/git/git-service.ts +61 -41
  24. package/backend/git/identity/cli.test.ts +58 -0
  25. package/backend/git/identity/cli.ts +201 -0
  26. package/backend/git/identity/credential-helper.test.ts +242 -0
  27. package/backend/git/identity/env.test.ts +214 -0
  28. package/backend/git/identity/env.ts +193 -0
  29. package/backend/git/identity/import-local.test.ts +199 -0
  30. package/backend/git/identity/import-local.ts +141 -0
  31. package/backend/git/identity/index.ts +78 -0
  32. package/backend/git/identity/keys.ts +183 -0
  33. package/backend/git/identity/resolve.ts +140 -0
  34. package/backend/git/identity/scope-config.test.ts +145 -0
  35. package/backend/git/identity/scope-config.ts +175 -0
  36. package/backend/git/identity/service.ts +297 -0
  37. package/backend/index.ts +16 -0
  38. package/backend/preview/browser/browser-console-manager.ts +214 -34
  39. package/backend/preview/browser/browser-pool.ts +526 -123
  40. package/backend/preview/browser/browser-preview-service.ts +192 -8
  41. package/backend/preview/browser/browser-tab-lifecycle.test.ts +240 -0
  42. package/backend/preview/browser/browser-tab-lifecycle.ts +495 -0
  43. package/backend/preview/browser/browser-tab-manager.ts +291 -65
  44. package/backend/preview/browser/capture-profile.ts +15 -1
  45. package/backend/preview/browser/types.ts +26 -1
  46. package/backend/snapshot/turn-changes.ts +3 -2
  47. package/backend/ssh/sftp.ts +2 -1
  48. package/backend/terminal/ptykit.ts +24 -0
  49. package/backend/worktrees/merge.ts +2 -1
  50. package/backend/ws/git/branch.ts +17 -6
  51. package/backend/ws/git/commit.ts +6 -5
  52. package/backend/ws/git/conflict.ts +3 -2
  53. package/backend/ws/git/identity-context.ts +91 -0
  54. package/backend/ws/git/identity.ts +200 -0
  55. package/backend/ws/git/index.ts +3 -1
  56. package/backend/ws/git/remote.ts +57 -11
  57. package/backend/ws/preview/browser/data.ts +60 -0
  58. package/backend/ws/preview/browser/interact.ts +6 -0
  59. package/backend/ws/preview/browser/tab-info.ts +9 -1
  60. package/backend/ws/preview/browser/tab.ts +64 -8
  61. package/backend/ws/preview/index.ts +21 -0
  62. package/bin/clopen.ts +9 -0
  63. package/dist/assets/{index-CeNKKSDR.js → index-B6u8cait.js} +1 -1
  64. package/dist/assets/{index-DW89566K.js → index-BeUKiRiY.js} +1 -1
  65. package/dist/assets/{main-Cy5DXWPT.js → main-CMRXlv2f.js} +604 -596
  66. package/dist/assets/main-DzCY0n-j.css +1 -0
  67. package/dist/index.html +2 -2
  68. package/package.json +2 -2
  69. package/shared/types/git-identity.ts +112 -0
  70. package/shared/utils/compare.test.ts +46 -0
  71. package/shared/utils/compare.ts +21 -0
  72. package/dist/assets/main-DJKj_4By.css +0 -1
@@ -0,0 +1,495 @@
1
+ /**
2
+ * Preview Tab Lifecycle
3
+ *
4
+ * Decides which preview pages are allowed to run. A tab nobody is watching is
5
+ * still a full Chromium renderer: rAF loops, timers, CSS animations, a dev
6
+ * server's HMR socket. Chrome would normally park such a page by itself, but
7
+ * every headless tab looks equally invisible to it — which is why the pool
8
+ * disables background throttling wholesale (see `browser-pool.ts`). That flag
9
+ * buys the streamed tab its full framerate and, until now, bought the other
10
+ * nine the same thing.
11
+ *
12
+ * So the decision is taken here instead, per tab and explicitly:
13
+ *
14
+ * - **active** — someone is watching it, an agent holds it, or it is still
15
+ * loading. The page runs at full speed, exactly as before.
16
+ * - **frozen** — nobody is watching. `Page.setWebLifecycleState: 'frozen'`
17
+ * suspends the page's task queues: no timers, no rAF, no script at all,
18
+ * while the DOM, the scroll position and the last painted frame stay exactly
19
+ * as they were. Waking is a single CDP round-trip, so switching back to a
20
+ * tab looks instant and shows what the page actually is — not a reload.
21
+ *
22
+ * Freezing rather than discarding is deliberate: a preview is something you
23
+ * come back to mid-flow (a form half filled in, a modal open, a scroll
24
+ * position), and a discarded page would have to be rebuilt from its URL and
25
+ * would lose all of that.
26
+ *
27
+ * Nothing here ever freezes a tab that has a viewer attached or that an agent
28
+ * is holding — including under the host budget, which only ever reclaims idle
29
+ * tabs. A frozen tab runs no JavaScript, so anything that evaluates in the
30
+ * page must call `ensureAwake()` first.
31
+ */
32
+
33
+ import { EventEmitter } from 'events';
34
+ import type { CDPSession, Page } from 'puppeteer';
35
+ import { debug } from '$shared/utils/logger';
36
+ import { getHostCaptureProfile } from './capture-profile';
37
+
38
+ export type TabLifecycleState = 'active' | 'frozen';
39
+
40
+ export interface TabLifecycleDeps {
41
+ /** The tab's current page, or null if it has none (closed, mid-rebuild). */
42
+ getPage(tabId: string): Page | null;
43
+ /**
44
+ * Tabs that must keep running even with no viewer: an agent is driving
45
+ * them, or they are still loading and freezing would strand them half
46
+ * rendered.
47
+ */
48
+ isPinned(tabId: string): boolean;
49
+ /**
50
+ * Grace before an unwatched tab is frozen. Defaults to FREEZE_AFTER_MS;
51
+ * overridden only where waiting eight real seconds is not an option.
52
+ */
53
+ freezeAfterMs?: number;
54
+ }
55
+
56
+ /**
57
+ * Grace between the last viewer leaving and the freeze.
58
+ *
59
+ * Long enough that flicking between two tabs never pays for a thaw, short
60
+ * enough that a tab left behind stops costing anything within a few seconds.
61
+ */
62
+ const FREEZE_AFTER_MS = 8_000;
63
+
64
+ /**
65
+ * Ceiling on a single lifecycle round-trip.
66
+ *
67
+ * DevTools commands are served on an inspector task runner that page freezing
68
+ * does not touch, so a thaw always has someone to answer it — but a renderer
69
+ * that is wedged for some other reason must not take the tab's queue down with
70
+ * it, because `ensureAwake()` is awaited on the path of every click.
71
+ */
72
+ const LIFECYCLE_TIMEOUT_MS = 5_000;
73
+
74
+ /**
75
+ * How many times a page may refuse to freeze before we stop asking.
76
+ *
77
+ * The tab keeps working; it just costs what it always did. Retrying for ever
78
+ * would turn one unfreezable page into a CDP call every few seconds for the
79
+ * rest of the session.
80
+ */
81
+ const MAX_FREEZE_FAILURES = 3;
82
+
83
+ function withTimeout<T>(work: Promise<T>, label: string): Promise<T> {
84
+ return new Promise<T>((resolve, reject) => {
85
+ const timer = setTimeout(() => reject(new Error(`${label} timed out`)), LIFECYCLE_TIMEOUT_MS);
86
+ timer.unref?.();
87
+ work.then(
88
+ (value) => {
89
+ clearTimeout(timer);
90
+ resolve(value);
91
+ },
92
+ (error) => {
93
+ clearTimeout(timer);
94
+ reject(error);
95
+ }
96
+ );
97
+ });
98
+ }
99
+
100
+ interface LifecycleEntry {
101
+ tabId: string;
102
+ /** What the page is doing right now. */
103
+ state: TabLifecycleState;
104
+ /** What it has been asked to do; applied asynchronously, newest wins. */
105
+ target: TabLifecycleState;
106
+ /** Viewers currently watching, on screen. A hidden viewer is not one. */
107
+ viewers: Set<string>;
108
+ /** Last moment this tab was watched, driven or touched. */
109
+ lastAwakeAt: number;
110
+ timer: ReturnType<typeof setTimeout> | null;
111
+ cdp: CDPSession | null;
112
+ /** The page the CDP session belongs to — a rebuild invalidates it. */
113
+ cdpPage: Page | null;
114
+ /** Whether this session needed `Page.enable` before it would take commands. */
115
+ pageEnabled: boolean;
116
+ /**
117
+ * Consecutive failed freezes on this page.
118
+ *
119
+ * A page that refuses to freeze — a build without the command, a renderer
120
+ * that will not answer — must not be asked again every few seconds for the
121
+ * rest of the session. Reset whenever the page is replaced or successfully
122
+ * woken, so the next page gets a clean chance.
123
+ */
124
+ freezeFailures: number;
125
+ /** Why the current target was chosen — reported once it actually lands. */
126
+ reason: string;
127
+ /** Transition queue, so two decisions can never interleave on one tab. */
128
+ work: Promise<unknown>;
129
+ }
130
+
131
+ export class BrowserTabLifecycle extends EventEmitter {
132
+ private entries = new Map<string, LifecycleEntry>();
133
+ private deps: TabLifecycleDeps;
134
+ private readonly freezeAfterMs: number;
135
+
136
+ constructor(deps: TabLifecycleDeps) {
137
+ super();
138
+ this.deps = deps;
139
+ this.freezeAfterMs = deps.freezeAfterMs ?? FREEZE_AFTER_MS;
140
+ }
141
+
142
+ /** Start managing a tab. New tabs begin awake — they are about to load. */
143
+ register(tabId: string): void {
144
+ if (this.entries.has(tabId)) return;
145
+
146
+ this.entries.set(tabId, {
147
+ tabId,
148
+ state: 'active',
149
+ target: 'active',
150
+ viewers: new Set(),
151
+ lastAwakeAt: Date.now(),
152
+ timer: null,
153
+ cdp: null,
154
+ cdpPage: null,
155
+ pageEnabled: false,
156
+ freezeFailures: 0,
157
+ reason: 'new tab',
158
+ work: Promise.resolve()
159
+ });
160
+
161
+ this.schedule(tabId);
162
+ }
163
+
164
+ /**
165
+ * The tab's page was replaced (crash recovery). The new page is awake by
166
+ * definition and the old CDP session is gone with the old target.
167
+ */
168
+ rebind(tabId: string): void {
169
+ const entry = this.entries.get(tabId);
170
+ if (!entry) return;
171
+
172
+ void this.dropSession(entry);
173
+ entry.state = 'active';
174
+ entry.target = 'active';
175
+ entry.freezeFailures = 0;
176
+ entry.lastAwakeAt = Date.now();
177
+ this.schedule(tabId);
178
+ }
179
+
180
+ /** Stop managing a tab and release its CDP session. */
181
+ dispose(tabId: string): void {
182
+ const entry = this.entries.get(tabId);
183
+ if (!entry) return;
184
+
185
+ this.clearTimer(entry);
186
+ void this.dropSession(entry);
187
+ this.entries.delete(tabId);
188
+ }
189
+
190
+ /** A viewer started watching this tab. */
191
+ attachViewer(tabId: string, viewerId: string): void {
192
+ const entry = this.entries.get(tabId);
193
+ if (!entry) return;
194
+
195
+ entry.viewers.add(viewerId);
196
+ entry.lastAwakeAt = Date.now();
197
+ this.schedule(tabId);
198
+ }
199
+
200
+ /** A viewer stopped watching — closed the panel, switched tab, went away. */
201
+ detachViewer(tabId: string, viewerId: string): void {
202
+ const entry = this.entries.get(tabId);
203
+ if (!entry) return;
204
+
205
+ entry.viewers.delete(viewerId);
206
+ this.schedule(tabId);
207
+ }
208
+
209
+ /**
210
+ * A viewer put the preview off screen (or brought it back).
211
+ *
212
+ * Treated as leaving and returning: capture is already suspended in that
213
+ * state, so there is nothing left for the page to be running for.
214
+ */
215
+ setViewerVisible(tabId: string, viewerId: string, visible: boolean): void {
216
+ if (visible) this.attachViewer(tabId, viewerId);
217
+ else this.detachViewer(tabId, viewerId);
218
+ }
219
+
220
+ /** Every viewer of this tab is gone at once (stream torn down). */
221
+ dropViewers(tabId: string): void {
222
+ const entry = this.entries.get(tabId);
223
+ if (!entry) return;
224
+
225
+ entry.viewers.clear();
226
+ this.schedule(tabId);
227
+ }
228
+
229
+ /**
230
+ * Something happened on this tab. Pushes the freeze back and, if it was
231
+ * already frozen, starts waking it — without waiting for the wake to land.
232
+ */
233
+ touch(tabId: string): void {
234
+ const entry = this.entries.get(tabId);
235
+ if (!entry) return;
236
+
237
+ entry.lastAwakeAt = Date.now();
238
+ if (entry.target === 'frozen') {
239
+ void this.ensureAwake(tabId);
240
+ return;
241
+ }
242
+ this.schedule(tabId);
243
+ }
244
+
245
+ /**
246
+ * Wake the tab and wait for it. Required before anything that runs script
247
+ * in the page — a frozen page would leave the evaluate hanging until it
248
+ * timed out.
249
+ */
250
+ async ensureAwake(tabId: string): Promise<void> {
251
+ const entry = this.entries.get(tabId);
252
+ if (!entry) return;
253
+
254
+ entry.lastAwakeAt = Date.now();
255
+
256
+ if (entry.target !== 'active') {
257
+ entry.target = 'active';
258
+ entry.reason = 'woken on demand';
259
+ this.queue(entry, () => this.applyTarget(entry));
260
+ }
261
+
262
+ this.schedule(tabId);
263
+ await entry.work.catch(() => {});
264
+ }
265
+
266
+ /** Whether anybody has this tab on screen right now. */
267
+ hasViewers(tabId: string): boolean {
268
+ return (this.entries.get(tabId)?.viewers.size ?? 0) > 0;
269
+ }
270
+
271
+ getState(tabId: string): TabLifecycleState {
272
+ return this.entries.get(tabId)?.state ?? 'active';
273
+ }
274
+
275
+ isFrozen(tabId: string): boolean {
276
+ return this.getState(tabId) === 'frozen';
277
+ }
278
+
279
+ /** Thaw everything and forget it. Used when the whole service goes away. */
280
+ async cleanup(): Promise<void> {
281
+ const entries = Array.from(this.entries.values());
282
+ this.entries.clear();
283
+
284
+ await Promise.all(
285
+ entries.map(async (entry) => {
286
+ this.clearTimer(entry);
287
+ await this.dropSession(entry);
288
+ })
289
+ );
290
+ }
291
+
292
+ // ── Internals ────────────────────────────────────────────────────────────
293
+
294
+ /**
295
+ * Decide when this tab should next change state.
296
+ *
297
+ * A tab with a viewer or an agent on it is woken immediately; anything else
298
+ * gets a countdown to the freeze, restarted on every call.
299
+ */
300
+ private schedule(tabId: string): void {
301
+ const entry = this.entries.get(tabId);
302
+ if (!entry) return;
303
+
304
+ this.clearTimer(entry);
305
+
306
+ if (this.mustStayAwake(entry)) {
307
+ if (entry.target !== 'active') {
308
+ entry.target = 'active';
309
+ entry.reason = 'in use again';
310
+ this.queue(entry, () => this.applyTarget(entry));
311
+ }
312
+ this.enforceBudget(tabId);
313
+ return;
314
+ }
315
+
316
+ if (entry.target === 'frozen') return;
317
+ if (entry.freezeFailures >= MAX_FREEZE_FAILURES) return;
318
+
319
+ entry.timer = setTimeout(() => {
320
+ entry.timer = null;
321
+ this.freeze(entry, 'idle');
322
+ }, this.freezeAfterMs);
323
+
324
+ // A sleeping preview must never be the reason the process stays up.
325
+ entry.timer.unref?.();
326
+ }
327
+
328
+ private mustStayAwake(entry: LifecycleEntry): boolean {
329
+ if (entry.viewers.size > 0) return true;
330
+ try {
331
+ return this.deps.isPinned(entry.tabId);
332
+ } catch {
333
+ return false;
334
+ }
335
+ }
336
+
337
+ private freeze(entry: LifecycleEntry, reason: string): void {
338
+ if (!this.entries.has(entry.tabId)) return;
339
+ if (this.mustStayAwake(entry)) {
340
+ this.schedule(entry.tabId);
341
+ return;
342
+ }
343
+ if (entry.target === 'frozen') return;
344
+
345
+ entry.target = 'frozen';
346
+ entry.reason = reason;
347
+ this.queue(entry, () => this.applyTarget(entry));
348
+ }
349
+
350
+ /**
351
+ * Keep the number of running pages within what this host can carry.
352
+ *
353
+ * Only idle tabs are ever reclaimed — a watched or agent-held tab is never
354
+ * a candidate, whatever the budget says, because freezing one would break
355
+ * something the user can see. The budget therefore bounds the transient
356
+ * pile-up (ten tabs restored at once, a batch opened by an agent) rather
357
+ * than fighting the user's actual attention.
358
+ */
359
+ private enforceBudget(exemptTabId?: string): void {
360
+ const budget = getHostCaptureProfile().maxAwakeTabs;
361
+
362
+ const awake = Array.from(this.entries.values()).filter((entry) => entry.target === 'active');
363
+ let over = awake.length - budget;
364
+ if (over <= 0) return;
365
+
366
+ const reclaimable = awake
367
+ .filter((entry) => entry.tabId !== exemptTabId && !this.mustStayAwake(entry))
368
+ .sort((a, b) => a.lastAwakeAt - b.lastAwakeAt);
369
+
370
+ for (const entry of reclaimable) {
371
+ if (over <= 0) break;
372
+ this.clearTimer(entry);
373
+ this.freeze(entry, `over budget (${awake.length}/${budget} awake)`);
374
+ over -= 1;
375
+ }
376
+ }
377
+
378
+ private clearTimer(entry: LifecycleEntry): void {
379
+ if (!entry.timer) return;
380
+ clearTimeout(entry.timer);
381
+ entry.timer = null;
382
+ }
383
+
384
+ private queue(entry: LifecycleEntry, step: () => Promise<void>): void {
385
+ entry.work = entry.work.then(step, step).catch(() => {});
386
+ }
387
+
388
+ /**
389
+ * Bring the page in line with `target`.
390
+ *
391
+ * Reads the target at the moment it runs rather than closing over it, so a
392
+ * wake queued behind a freeze settles on the newest decision instead of
393
+ * replaying a stale one.
394
+ */
395
+ private async applyTarget(entry: LifecycleEntry): Promise<void> {
396
+ if (!this.entries.has(entry.tabId)) return;
397
+ if (entry.state === entry.target) return;
398
+
399
+ const target = entry.target;
400
+ const page = this.deps.getPage(entry.tabId);
401
+
402
+ // No page to freeze or wake: a tab mid-rebuild is awake by definition
403
+ // once its new page arrives, and `rebind()` resets the state then.
404
+ if (!page || page.isClosed()) {
405
+ entry.state = 'active';
406
+ entry.target = 'active';
407
+ return;
408
+ }
409
+
410
+ if (entry.cdpPage && entry.cdpPage !== page) {
411
+ await this.dropSession(entry);
412
+ }
413
+
414
+ try {
415
+ const cdp = await this.sessionFor(entry, page);
416
+ await this.sendLifecycle(entry, cdp, target);
417
+ } catch (error) {
418
+ // Left in the state it was actually in — a tab we failed to freeze
419
+ // is still running, and claiming otherwise would hide it from the
420
+ // budget and show the user a sleeping badge on a page burning CPU.
421
+ debug.warn('preview', `⚠️ Lifecycle ${target} failed for ${entry.tabId}: ${error}`);
422
+ entry.target = entry.state;
423
+
424
+ if (target === 'frozen') {
425
+ entry.freezeFailures += 1;
426
+ if (entry.freezeFailures >= MAX_FREEZE_FAILURES) {
427
+ debug.warn('preview', `⚠️ Giving up on freezing ${entry.tabId}; it will keep running`);
428
+ } else {
429
+ // Try again on the usual countdown rather than never.
430
+ this.schedule(entry.tabId);
431
+ }
432
+ }
433
+ return;
434
+ }
435
+
436
+ entry.state = target;
437
+ if (target === 'active') {
438
+ entry.lastAwakeAt = Date.now();
439
+ entry.freezeFailures = 0;
440
+ }
441
+
442
+ // Logged here rather than where the decision is taken: a freeze the
443
+ // user cancelled by clicking back into the tab is queued and then
444
+ // dropped, and announcing it up front reported sleeps that never were.
445
+ debug.log(
446
+ 'preview',
447
+ `${target === 'frozen' ? '😴 Froze' : '☀️ Woke'} preview tab ${entry.tabId} (${entry.reason})`
448
+ );
449
+
450
+ this.emit('state', { tabId: entry.tabId, state: target });
451
+ }
452
+
453
+ private async sessionFor(entry: LifecycleEntry, page: Page): Promise<CDPSession> {
454
+ if (entry.cdp && entry.cdpPage === page) return entry.cdp;
455
+
456
+ const cdp = await page.createCDPSession();
457
+ entry.cdp = cdp;
458
+ entry.cdpPage = page;
459
+ entry.pageEnabled = false;
460
+ return cdp;
461
+ }
462
+
463
+ /**
464
+ * `Page.setWebLifecycleState` is refused by some builds until the Page
465
+ * domain is enabled on the session asking for it. Enabling it up front
466
+ * would subscribe every tab to page events we have no use for (and that
467
+ * another session already handles), so we only pay for it on the failure
468
+ * that asks for it.
469
+ */
470
+ private async sendLifecycle(
471
+ entry: LifecycleEntry,
472
+ cdp: CDPSession,
473
+ state: TabLifecycleState
474
+ ): Promise<void> {
475
+ try {
476
+ await withTimeout(cdp.send('Page.setWebLifecycleState', { state }), `lifecycle ${state}`);
477
+ return;
478
+ } catch (error) {
479
+ if (entry.pageEnabled) throw error;
480
+ }
481
+
482
+ await withTimeout(cdp.send('Page.enable'), 'Page.enable');
483
+ entry.pageEnabled = true;
484
+ await withTimeout(cdp.send('Page.setWebLifecycleState', { state }), `lifecycle ${state}`);
485
+ }
486
+
487
+ private async dropSession(entry: LifecycleEntry): Promise<void> {
488
+ const cdp = entry.cdp;
489
+ entry.cdp = null;
490
+ entry.cdpPage = null;
491
+ entry.pageEnabled = false;
492
+ if (!cdp) return;
493
+ await cdp.detach().catch(() => {});
494
+ }
495
+ }