@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,297 @@
1
+ /**
2
+ * The git identity service — CRUD, key materialisation, and the DTO boundary.
3
+ *
4
+ * One rule governs this module: A SECRET NEVER LEAVES IT. `toDTO` reduces the
5
+ * private key, its passphrase, and the HTTPS token to booleans, so no code path
6
+ * above this file can accidentally serialise one to a browser. The public key
7
+ * is the deliberate exception — it is public, and the user needs to copy it.
8
+ *
9
+ * Key material on disk is kept in step with the row here rather than in the
10
+ * query layer: writing a file is not part of storing a row, and a failed write
11
+ * must not leave a saved identity whose key silently does not exist.
12
+ */
13
+
14
+ import { randomUUID } from 'node:crypto';
15
+ import {
16
+ gitIdentityQueries,
17
+ gitIdentityBindingQueries,
18
+ parseHosts,
19
+ type GitIdentityRow
20
+ } from '$backend/database/queries';
21
+ import { debug } from '$shared/utils/logger';
22
+ import type {
23
+ GeneratedSshKey,
24
+ GitIdentityDTO,
25
+ GitIdentityInput
26
+ } from '$shared/types/git-identity';
27
+ import { derivePublicKey, generateKeyPair, identityKeyPath, removeKeyFiles, writeKeyFile } from './keys';
28
+ import { syncLocalMachineIdentity } from './import-local';
29
+ import { refreshScopeConfigsForUser, writeScopeConfig } from './scope-config';
30
+
31
+ /** Strip a row down to what a client may see. */
32
+ export function toDTO(row: GitIdentityRow): GitIdentityDTO {
33
+ return {
34
+ id: row.id,
35
+ label: row.label,
36
+ name: row.name,
37
+ email: row.email,
38
+ authMethod: row.auth_method,
39
+ hosts: parseHosts(row.hosts),
40
+ sshPublicKey: row.ssh_public_key,
41
+ hasSshKey: !!row.ssh_private_key,
42
+ hasSshPassphrase: !!row.ssh_passphrase,
43
+ hasHttpsToken: !!row.https_token,
44
+ httpsUsername: row.https_username,
45
+ integrationAccountId: row.integration_account_id,
46
+ isDefault: row.is_default === 1,
47
+ source: row.source,
48
+ // Mirrored rows are not deletable: the machine's config still exists, so a
49
+ // delete would only be undone by the next list read.
50
+ canDelete: row.source !== 'local-machine',
51
+ createdAt: row.created_at,
52
+ updatedAt: row.updated_at
53
+ };
54
+ }
55
+
56
+ function assertValid(input: GitIdentityInput): void {
57
+ if (!input.label.trim()) throw new Error('An identity needs a label');
58
+ if (!input.name.trim()) throw new Error('An identity needs a name');
59
+ const email = input.email.trim();
60
+ // Deliberately loose. Git accepts anything without whitespace or angle
61
+ // brackets as an email, and rejecting an address a host does accept would be
62
+ // the more annoying failure.
63
+ if (!email || /[\s<>]/.test(email)) throw new Error('That email is not usable in a git commit');
64
+ }
65
+
66
+ /**
67
+ * Keep the key file in step with the row.
68
+ *
69
+ * Called after every write. Reads the stored (already unsealed) key rather than
70
+ * the input, so an edit that leaves the key untouched still guarantees the file
71
+ * exists — which matters after a restore onto a machine that has the database
72
+ * but not the key files.
73
+ */
74
+ async function syncKeyFile(row: GitIdentityRow): Promise<GitIdentityRow> {
75
+ if (row.auth_method !== 'ssh-key' || !row.ssh_private_key) {
76
+ await removeKeyFiles(row.id);
77
+ return row;
78
+ }
79
+
80
+ const { strictPermissions } = await writeKeyFile(row.id, row.ssh_private_key);
81
+ if (!strictPermissions) {
82
+ // Said once, loudly, rather than left for the user to decode out of an
83
+ // ssh error at push time.
84
+ debug.warn(
85
+ 'git',
86
+ `Key for identity ${row.id} could not be given strict permissions; ssh may refuse it`
87
+ );
88
+ }
89
+
90
+ // A user who pasted only a private key still gets something to copy into
91
+ // GitHub. Skipped for passphrased keys, which cannot be read unattended.
92
+ if (!row.ssh_public_key && !row.ssh_passphrase) {
93
+ const derived = await derivePublicKey(identityKeyPath(row.id));
94
+ if (derived) {
95
+ const updated = gitIdentityQueries.update(row.id, {
96
+ label: row.label,
97
+ name: row.name,
98
+ email: row.email,
99
+ authMethod: row.auth_method,
100
+ hosts: parseHosts(row.hosts),
101
+ sshPublicKey: derived,
102
+ httpsUsername: row.https_username,
103
+ integrationAccountId: row.integration_account_id
104
+ });
105
+ if (updated) return updated;
106
+ }
107
+ }
108
+
109
+ return row;
110
+ }
111
+
112
+ export const gitIdentityService = {
113
+ /**
114
+ * Every identity this user owns, mirroring the machine's git config first.
115
+ *
116
+ * Done on the read rather than at startup so it also covers a user who joins
117
+ * later, and because it is the moment the result is actually about to be
118
+ * shown. It is idempotent and only writes on the first call per user.
119
+ */
120
+ async list(userId: string): Promise<GitIdentityDTO[]> {
121
+ await syncLocalMachineIdentity(userId);
122
+ return gitIdentityQueries.listByUser(userId).map(toDTO);
123
+ },
124
+
125
+ get(userId: string, id: string): GitIdentityDTO | null {
126
+ const row = gitIdentityQueries.getById(id);
127
+ if (!row || row.owner_user_id !== userId) return null;
128
+ return toDTO(row);
129
+ },
130
+
131
+ async create(userId: string, input: GitIdentityInput): Promise<GitIdentityDTO> {
132
+ assertValid(input);
133
+ if (gitIdentityQueries.labelTaken(userId, input.label.trim())) {
134
+ throw new Error(`You already have an identity called "${input.label.trim()}"`);
135
+ }
136
+
137
+ const id = randomUUID();
138
+ let row = gitIdentityQueries.create(id, userId, {
139
+ label: input.label.trim(),
140
+ name: input.name.trim(),
141
+ email: input.email.trim(),
142
+ authMethod: input.authMethod,
143
+ hosts: input.hosts,
144
+ sshPrivateKey: input.sshPrivateKey ?? null,
145
+ sshPublicKey: input.sshPublicKey ?? null,
146
+ sshPassphrase: input.sshPassphrase ?? null,
147
+ httpsUsername: input.httpsUsername ?? null,
148
+ httpsToken: input.httpsToken ?? null,
149
+ integrationAccountId: input.integrationAccountId ?? null
150
+ });
151
+
152
+ row = await syncKeyFile(row);
153
+
154
+ // The first identity a user creates becomes their default — otherwise it
155
+ // would sit there doing nothing until they found the toggle, which reads
156
+ // as the feature being broken.
157
+ if (input.isDefault || gitIdentityQueries.listByUser(userId).length === 1) {
158
+ gitIdentityQueries.setDefault(userId, id);
159
+ row = gitIdentityQueries.getById(id)!;
160
+ }
161
+
162
+ // Terminals that are already open read their identity from a file, so it is
163
+ // rewritten here — otherwise the new account would only reach tabs opened
164
+ // after this point.
165
+ await refreshScopeConfigsForUser(userId);
166
+
167
+ debug.log('git', `Created git identity "${row.label}" for user ${userId}`);
168
+ return toDTO(row);
169
+ },
170
+
171
+ async update(userId: string, id: string, input: GitIdentityInput): Promise<GitIdentityDTO> {
172
+ assertValid(input);
173
+ const existing = gitIdentityQueries.getById(id);
174
+ if (!existing || existing.owner_user_id !== userId) throw new Error('Identity not found');
175
+ if (gitIdentityQueries.labelTaken(userId, input.label.trim(), id)) {
176
+ throw new Error(`You already have an identity called "${input.label.trim()}"`);
177
+ }
178
+
179
+ let row = gitIdentityQueries.update(id, {
180
+ label: input.label.trim(),
181
+ name: input.name.trim(),
182
+ email: input.email.trim(),
183
+ authMethod: input.authMethod,
184
+ hosts: input.hosts,
185
+ // `undefined` keeps the stored secret, `null` clears it — the
186
+ // distinction the query layer depends on.
187
+ sshPrivateKey: input.sshPrivateKey,
188
+ sshPublicKey: input.sshPublicKey ?? existing.ssh_public_key,
189
+ sshPassphrase: input.sshPassphrase,
190
+ httpsUsername: input.httpsUsername ?? null,
191
+ httpsToken: input.httpsToken,
192
+ integrationAccountId: input.integrationAccountId ?? null
193
+ // `source` is deliberately absent: the update statement does not touch
194
+ // that column, so an edited mirror stays a mirror — and stays
195
+ // undeletable, because the machine config it reflects is still there.
196
+ });
197
+ if (!row) throw new Error('Identity not found');
198
+
199
+ row = await syncKeyFile(row);
200
+
201
+ if (input.isDefault && row.is_default !== 1) {
202
+ gitIdentityQueries.setDefault(userId, id);
203
+ row = gitIdentityQueries.getById(id)!;
204
+ }
205
+
206
+ await refreshScopeConfigsForUser(userId);
207
+
208
+ debug.log('git', `Updated git identity "${row.label}"`);
209
+ return toDTO(row);
210
+ },
211
+
212
+ async remove(userId: string, id: string): Promise<void> {
213
+ const row = gitIdentityQueries.getById(id);
214
+ if (!row || row.owner_user_id !== userId) throw new Error('Identity not found');
215
+ if (row.source === 'local-machine') {
216
+ throw new Error(
217
+ "This account mirrors the machine's own git config, so it cannot be deleted. Edit it instead."
218
+ );
219
+ }
220
+
221
+ gitIdentityQueries.remove(id);
222
+ await removeKeyFiles(id);
223
+
224
+ // Deleting the default leaves the user with none, so the next one in the
225
+ // list takes over rather than every project silently losing its identity.
226
+ if (row.is_default === 1) {
227
+ const remaining = gitIdentityQueries.listByUser(userId);
228
+ if (remaining.length > 0) gitIdentityQueries.setDefault(userId, remaining[0]!.id);
229
+ }
230
+
231
+ await refreshScopeConfigsForUser(userId);
232
+
233
+ debug.log('git', `Removed git identity "${row.label}"`);
234
+ },
235
+
236
+ async setDefault(userId: string, id: string): Promise<GitIdentityDTO> {
237
+ const row = gitIdentityQueries.getById(id);
238
+ if (!row || row.owner_user_id !== userId) throw new Error('Identity not found');
239
+ gitIdentityQueries.setDefault(userId, id);
240
+ // Every project that inherits the default is affected, not just one.
241
+ await refreshScopeConfigsForUser(userId);
242
+ return toDTO(gitIdentityQueries.getById(id)!);
243
+ },
244
+
245
+ /**
246
+ * Generate a keypair for an identity and store the private half.
247
+ *
248
+ * Returns only the public key and its fingerprint; the private key goes
249
+ * straight into the sealed column and the 0600 file.
250
+ */
251
+ async generateKey(userId: string, id: string): Promise<GeneratedSshKey> {
252
+ const row = gitIdentityQueries.getById(id);
253
+ if (!row || row.owner_user_id !== userId) throw new Error('Identity not found');
254
+
255
+ const { privateKey, publicKey, fingerprint } = await generateKeyPair(
256
+ id,
257
+ `${row.email} (clopen)`
258
+ );
259
+
260
+ gitIdentityQueries.update(id, {
261
+ label: row.label,
262
+ name: row.name,
263
+ email: row.email,
264
+ authMethod: 'ssh-key',
265
+ hosts: parseHosts(row.hosts),
266
+ sshPrivateKey: privateKey,
267
+ sshPublicKey: publicKey,
268
+ // A generated key has no passphrase, so any stored one is now wrong.
269
+ sshPassphrase: null,
270
+ httpsUsername: row.https_username,
271
+ integrationAccountId: row.integration_account_id
272
+ });
273
+
274
+ await refreshScopeConfigsForUser(userId);
275
+
276
+ debug.log('git', `Generated SSH key for identity "${row.label}"`);
277
+ return { publicKey, fingerprint };
278
+ },
279
+
280
+ /** Bind a project to an identity, for this user. */
281
+ async bind(userId: string, projectId: string, identityId: string | null): Promise<void> {
282
+ if (identityId === null) {
283
+ gitIdentityBindingQueries.clear(projectId, userId);
284
+ } else {
285
+ const row = gitIdentityQueries.getById(identityId);
286
+ if (!row || row.owner_user_id !== userId) throw new Error('Identity not found');
287
+ gitIdentityBindingQueries.set(projectId, userId, identityId);
288
+ }
289
+ // Only this project's file can have changed, so only it is rewritten.
290
+ await writeScopeConfig(userId, projectId);
291
+ },
292
+
293
+ /** How many projects would lose their binding if this identity went away. */
294
+ bindingCount(identityId: string): number {
295
+ return gitIdentityBindingQueries.countForIdentity(identityId);
296
+ }
297
+ };
package/backend/index.ts CHANGED
@@ -16,6 +16,22 @@ if (typeof globalThis.Bun === 'undefined') {
16
16
  // MUST be first import — cleans process.env before any other module reads it.
17
17
  import { SERVER_ENV } from './utils/env';
18
18
 
19
+ // Git's credential/askpass helpers re-invoke Clopen through whatever entry point
20
+ // is running, which is `Bun.main` — and that is this file under `bun --watch
21
+ // backend/index.ts`, and `scripts/start.ts` (which imports this one) under `bun
22
+ // run start`. `bin/clopen.ts` has the same guard for a global install. All three
23
+ // need it: without one, git would spawn an entry that does not know the
24
+ // subcommand, and an HTTPS push would fail asking for a password nobody typed.
25
+ //
26
+ // Placed here, above every side-effecting import, so a helper invocation exits
27
+ // before anything opens a port or starts a watcher.
28
+ import { runGitHelper } from './git/identity/cli';
29
+
30
+ {
31
+ const helperExit = await runGitHelper(process.argv.slice(2));
32
+ if (helperExit !== null) process.exit(helperExit);
33
+ }
34
+
19
35
  import { Elysia } from 'elysia';
20
36
  import { corsMiddleware } from './middleware/cors';
21
37
  import { errorHandlerMiddleware } from './middleware/error-handler';
@@ -1,5 +1,5 @@
1
1
  import { EventEmitter } from 'events';
2
- import type { Page, ConsoleMessage as PuppeteerConsoleMessage, HTTPResponse } from 'puppeteer';
2
+ import type { JSHandle, Page, ConsoleMessage as PuppeteerConsoleMessage, HTTPResponse } from 'puppeteer';
3
3
  import type { BrowserConsoleMessage, BrowserConsoleValue, BrowserTab } from './types';
4
4
 
5
5
  import { debug } from '$shared/utils/logger';
@@ -8,6 +8,87 @@ import { debug } from '$shared/utils/logger';
8
8
  const MAX_LOGS = 1000;
9
9
  const TRIM_TO = 500;
10
10
 
11
+ /**
12
+ * Per-tab ceiling on page-originated console traffic.
13
+ *
14
+ * Every message costs a structured payload to each viewer in the project, and
15
+ * a dev build in a re-render loop can produce thousands a second. Past the
16
+ * ceiling the messages are counted rather than carried, and the count is
17
+ * reported — a panel that says "4,812 dropped" is honest, whereas one that
18
+ * silently keeps up is the one that makes the whole workspace stutter.
19
+ */
20
+ const RATE_WINDOW_MS = 1000;
21
+ const MAX_MESSAGES_PER_WINDOW = 60;
22
+
23
+ interface ConsoleBudget {
24
+ windowStart: number;
25
+ used: number;
26
+ dropped: number;
27
+ }
28
+
29
+ /** What the manager needs to know about the world outside it. */
30
+ export interface ConsoleManagerDeps {
31
+ /**
32
+ * Whether anyone is actually looking at this tab.
33
+ *
34
+ * Console capture used to be unconditional: every tab, watched or not,
35
+ * paid a CDP round-trip per logged argument and a broadcast per message,
36
+ * for a panel that in most cases was not even open. Unwatched tabs now
37
+ * keep a text-only history — enough to read back when the panel opens,
38
+ * with none of the per-message cost.
39
+ */
40
+ isWatched(sessionId: string): boolean;
41
+ }
42
+
43
+ function shorten(text: string, limit = 200): string {
44
+ return text.length > limit ? `${text.slice(0, limit)}…` : text;
45
+ }
46
+
47
+ /**
48
+ * Read an argument's value straight off the CDP payload Chrome already sent.
49
+ *
50
+ * Primitives — which is what the overwhelming majority of logs are made of —
51
+ * arrive complete with the console event, so evaluating in the page to learn
52
+ * what `"hello"` is costs a round-trip for something already in hand. Returns
53
+ * null for anything that genuinely needs the page to describe it.
54
+ */
55
+ function valueFromRemoteObject(handle: JSHandle): BrowserConsoleValue | null {
56
+ const remote = handle.remoteObject();
57
+
58
+ switch (remote.type) {
59
+ case 'string':
60
+ return { type: 'string', preview: shorten(String(remote.value), 1000) };
61
+ case 'number':
62
+ return { type: 'number', preview: remote.unserializableValue ?? String(remote.value) };
63
+ case 'boolean':
64
+ return { type: 'boolean', preview: String(remote.value) };
65
+ case 'undefined':
66
+ return { type: 'undefined', preview: 'undefined' };
67
+ case 'bigint':
68
+ return { type: 'bigint', preview: remote.unserializableValue ?? `${String(remote.value)}n` };
69
+ case 'symbol':
70
+ return { type: 'symbol', preview: remote.description ?? 'Symbol()' };
71
+ case 'function': {
72
+ // `description` is the function's source; its signature is the part
73
+ // before the body, which is what DevTools shows too.
74
+ const signature = (remote.description ?? '').split('{')[0].trim().replace(/^function\s*/, '');
75
+ return { type: 'function', preview: `ƒ ${shorten(signature || '()', 80)}` };
76
+ }
77
+ case 'object':
78
+ if (remote.subtype === 'null') return { type: 'null', preview: 'null' };
79
+ return null;
80
+ default:
81
+ return null;
82
+ }
83
+ }
84
+
85
+ /** The shape of an object, without asking the page to walk it. */
86
+ function outlineFromRemoteObject(handle: JSHandle): BrowserConsoleValue {
87
+ const remote = handle.remoteObject();
88
+ const label = remote.className || remote.subtype || 'Object';
89
+ return { type: 'object', preview: remote.description ? shorten(remote.description) : label };
90
+ }
91
+
11
92
  /**
12
93
  * Flatten a page value into something renderable.
13
94
  *
@@ -160,8 +241,87 @@ function normalizeConsoleType(type: string): BrowserConsoleMessage['type'] {
160
241
  }
161
242
 
162
243
  export class BrowserConsoleManager extends EventEmitter {
163
- constructor() {
244
+ private deps: ConsoleManagerDeps;
245
+ private budgets = new Map<string, ConsoleBudget>();
246
+
247
+ constructor(deps: ConsoleManagerDeps) {
164
248
  super();
249
+ this.deps = deps;
250
+ }
251
+
252
+ private isWatched(sessionId: string): boolean {
253
+ try {
254
+ return this.deps.isWatched(sessionId);
255
+ } catch {
256
+ return true;
257
+ }
258
+ }
259
+
260
+ /**
261
+ * Whether this tab may spend another message this second.
262
+ *
263
+ * Rolling the window is also where a burst gets reported, so the drop is
264
+ * visible in the panel at the point it happened rather than inferred from
265
+ * a gap in the log.
266
+ */
267
+ private admit(session: BrowserTab): boolean {
268
+ const now = Date.now();
269
+ let budget = this.budgets.get(session.id);
270
+
271
+ if (!budget || now - budget.windowStart >= RATE_WINDOW_MS) {
272
+ const dropped = budget?.dropped ?? 0;
273
+ budget = { windowStart: now, used: 0, dropped: 0 };
274
+ this.budgets.set(session.id, budget);
275
+
276
+ if (dropped > 0) {
277
+ budget.used += 1;
278
+ this.record(session, {
279
+ id: BrowserConsoleManager.makeId('console'),
280
+ type: 'warn',
281
+ text: `${dropped} more console message${dropped === 1 ? '' : 's'} dropped (rate limit)`,
282
+ timestamp: now
283
+ });
284
+ }
285
+ }
286
+
287
+ if (budget.used >= MAX_MESSAGES_PER_WINDOW) {
288
+ budget.dropped += 1;
289
+ return false;
290
+ }
291
+
292
+ budget.used += 1;
293
+ return true;
294
+ }
295
+
296
+ /**
297
+ * Turn a console call's arguments into renderable values.
298
+ *
299
+ * Primitives are read off the event itself. Objects need the page to walk
300
+ * them, which is a round-trip per argument — worth paying while someone is
301
+ * watching, and not worth paying at all for a tab in the background, which
302
+ * gets the outline Chrome already sent instead.
303
+ */
304
+ private async collectValues(
305
+ consoleMessage: PuppeteerConsoleMessage,
306
+ watched: boolean
307
+ ): Promise<BrowserConsoleValue[]> {
308
+ const args = consoleMessage.args();
309
+ if (args.length === 0) return [];
310
+
311
+ // Still one Promise.all: the arguments that do need the page are walked
312
+ // concurrently, as they always were. What changed is how few of them
313
+ // reach that path at all.
314
+ return Promise.all(
315
+ args.map((arg) => {
316
+ const cheap = valueFromRemoteObject(arg);
317
+ if (cheap) return cheap;
318
+ if (!watched) return outlineFromRemoteObject(arg);
319
+
320
+ return arg
321
+ .evaluate(serializeConsoleValue as never)
322
+ .catch(() => ({ type: 'object', preview: '[unserializable]' }) as BrowserConsoleValue);
323
+ })
324
+ );
165
325
  }
166
326
 
167
327
  /**
@@ -169,7 +329,12 @@ export class BrowserConsoleManager extends EventEmitter {
169
329
  * a counter the way DevTools does — a page logging inside a rAF loop would
170
330
  * otherwise flood the panel and evict everything useful.
171
331
  */
172
- private record(session: BrowserTab, message: BrowserConsoleMessage): void {
332
+ private record(session: BrowserTab, message: BrowserConsoleMessage, force = false): void {
333
+ // The buffer is always kept — it is what the panel reads back when it
334
+ // opens. Only the live broadcast is conditional: pushing a message to
335
+ // every viewer in the project for a tab none of them is looking at is
336
+ // work that ends in nothing being displayed.
337
+ const publish = force || this.isWatched(session.id);
173
338
  const previous = session.consoleLogs[session.consoleLogs.length - 1];
174
339
 
175
340
  if (
@@ -181,7 +346,7 @@ export class BrowserConsoleManager extends EventEmitter {
181
346
  ) {
182
347
  previous.count = (previous.count ?? 1) + 1;
183
348
  previous.timestamp = message.timestamp;
184
- this.emit('console-message', { sessionId: session.id, message: previous });
349
+ if (publish) this.emit('console-message', { sessionId: session.id, message: previous });
185
350
  return;
186
351
  }
187
352
 
@@ -190,7 +355,7 @@ export class BrowserConsoleManager extends EventEmitter {
190
355
  session.consoleLogs = session.consoleLogs.slice(-TRIM_TO);
191
356
  }
192
357
 
193
- this.emit('console-message', { sessionId: session.id, message });
358
+ if (publish) this.emit('console-message', { sessionId: session.id, message });
194
359
  }
195
360
 
196
361
  private static makeId(prefix: string): string {
@@ -207,6 +372,8 @@ export class BrowserConsoleManager extends EventEmitter {
207
372
  return;
208
373
  }
209
374
 
375
+ if (!this.admit(session)) return;
376
+
210
377
  try {
211
378
  const text = consoleMessage.text();
212
379
  const type = normalizeConsoleType(consoleMessage.type());
@@ -226,16 +393,7 @@ export class BrowserConsoleManager extends EventEmitter {
226
393
  // which make `jsonValue()` throw and used to be dropped entirely.
227
394
  let values: BrowserConsoleValue[] = [];
228
395
  try {
229
- const args = consoleMessage.args();
230
- if (args.length > 0) {
231
- values = await Promise.all(
232
- args.map((arg) =>
233
- arg
234
- .evaluate(serializeConsoleValue as never)
235
- .catch(() => ({ type: 'object', preview: '[unserializable]' }) as BrowserConsoleValue)
236
- )
237
- );
238
- }
396
+ values = await this.collectValues(consoleMessage, this.isWatched(session.id));
239
397
  } catch (error) {
240
398
  debug.warn('preview', 'Could not extract console message args:', error);
241
399
  }
@@ -265,6 +423,8 @@ export class BrowserConsoleManager extends EventEmitter {
265
423
  return;
266
424
  }
267
425
 
426
+ if (!this.admit(session)) return;
427
+
268
428
  try {
269
429
  const error = err as Error;
270
430
  this.record(session, {
@@ -283,6 +443,7 @@ export class BrowserConsoleManager extends EventEmitter {
283
443
  page.on('response', (response: HTTPResponse) => {
284
444
  if (!session.consoleEnabled) return;
285
445
  if (response.ok() || response.status() < 400) return;
446
+ if (!this.admit(session)) return;
286
447
 
287
448
  try {
288
449
  this.record(session, {
@@ -307,6 +468,7 @@ export class BrowserConsoleManager extends EventEmitter {
307
468
  // would otherwise be invisible in the panel.
308
469
  page.on('requestfailed', (request) => {
309
470
  if (!session.consoleEnabled) return;
471
+ if (!this.admit(session)) return;
310
472
 
311
473
  try {
312
474
  const failure = request.failure();
@@ -331,6 +493,7 @@ export class BrowserConsoleManager extends EventEmitter {
331
493
  if (!session) return false;
332
494
 
333
495
  session.consoleLogs = [];
496
+ this.budgets.delete(session.id);
334
497
 
335
498
  // Emit clear event
336
499
  this.emit('console-clear', {
@@ -341,6 +504,11 @@ export class BrowserConsoleManager extends EventEmitter {
341
504
  return true;
342
505
  }
343
506
 
507
+ /** Drop a closed tab's rate-limit bookkeeping. */
508
+ forgetSession(sessionId: string): void {
509
+ this.budgets.delete(sessionId);
510
+ }
511
+
344
512
  toggleConsoleLogging(session: BrowserTab, enabled: boolean): boolean {
345
513
  if (!session) return false;
346
514
 
@@ -359,12 +527,16 @@ export class BrowserConsoleManager extends EventEmitter {
359
527
  async executeConsoleCommand(session: BrowserTab, command: string): Promise<BrowserConsoleValue> {
360
528
  if (!session) throw new Error('Session not found');
361
529
 
362
- this.record(session, {
363
- id: BrowserConsoleManager.makeId('input'),
364
- type: 'input',
365
- text: command,
366
- timestamp: Date.now()
367
- });
530
+ this.record(
531
+ session,
532
+ {
533
+ id: BrowserConsoleManager.makeId('input'),
534
+ type: 'input',
535
+ text: command,
536
+ timestamp: Date.now()
537
+ },
538
+ true
539
+ );
368
540
 
369
541
  try {
370
542
  const outcome = await session.page.evaluate(
@@ -392,24 +564,32 @@ export class BrowserConsoleManager extends EventEmitter {
392
564
  serializeConsoleValue.toString()
393
565
  );
394
566
 
395
- this.record(session, {
396
- id: BrowserConsoleManager.makeId('result'),
397
- type: outcome.failed ? 'error' : 'result',
398
- text: outcome.value.preview,
399
- values: [outcome.value],
400
- timestamp: Date.now()
401
- });
567
+ this.record(
568
+ session,
569
+ {
570
+ id: BrowserConsoleManager.makeId('result'),
571
+ type: outcome.failed ? 'error' : 'result',
572
+ text: outcome.value.preview,
573
+ values: [outcome.value],
574
+ timestamp: Date.now()
575
+ },
576
+ true
577
+ );
402
578
 
403
579
  return outcome.value;
404
580
  } catch (error) {
405
581
  const message = error instanceof Error ? error.message : String(error);
406
582
 
407
- this.record(session, {
408
- id: BrowserConsoleManager.makeId('result'),
409
- type: 'error',
410
- text: message,
411
- timestamp: Date.now()
412
- });
583
+ this.record(
584
+ session,
585
+ {
586
+ id: BrowserConsoleManager.makeId('result'),
587
+ type: 'error',
588
+ text: message,
589
+ timestamp: Date.now()
590
+ },
591
+ true
592
+ );
413
593
 
414
594
  throw error;
415
595
  }