dsh-browser-cdp 1.13.2 → 1.14.1

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.
@@ -3869,6 +3869,15 @@ var TargetSessions = class {
3869
3869
  await Promise.allSettled(current.map((session) => this.cdp.call("Target.detachFromTarget", { sessionId: session.sessionId })));
3870
3870
  }
3871
3871
  };
3872
+ /**
3873
+ * Multi-target CDP capture backend (#15).
3874
+ *
3875
+ * One screencast session PER watched target: several watch leases pointing at
3876
+ * different tabs each keep their own `Page.startScreencast` stream, and none of
3877
+ * them stops the others. Multiple leases on the SAME targetId are collapsed by
3878
+ * the manager into one entry here (derived set, no reference counting — D7).
3879
+ * `stopTarget` removes exactly one; `stop` clears everything.
3880
+ */
3872
3881
  var CdpCaptureBackend = class {
3873
3882
  cdp;
3874
3883
  sessions;
@@ -3879,11 +3888,16 @@ var CdpCaptureBackend = class {
3879
3888
  now;
3880
3889
  setTimer;
3881
3890
  clearTimer;
3882
- current;
3883
- pendingFrame;
3884
- sendTimer;
3885
- backstopTimer;
3891
+ /** targetId → live capture state. The multi-target replacement for `current`. */
3892
+ captures;
3893
+ /** targetId → newest undelivered frame (per-target pacing). */
3894
+ pendingFrames;
3895
+ /** targetId → throttle timer for that target's next flush. */
3896
+ sendTimers;
3897
+ /** targetId → timestamp of the last frame actually delivered. */
3886
3898
  lastSentAt;
3899
+ /** Single shared backstop timer: one tick screenshots every stale target. */
3900
+ backstopTimer;
3887
3901
  metrics;
3888
3902
  offFrame;
3889
3903
  offDestroyed;
@@ -3897,39 +3911,55 @@ var CdpCaptureBackend = class {
3897
3911
  this.now = now;
3898
3912
  this.setTimer = setTimer;
3899
3913
  this.clearTimer = clearTimer;
3900
- this.current = null;
3901
- this.pendingFrame = null;
3902
- this.sendTimer = null;
3914
+ this.captures = /* @__PURE__ */ new Map();
3915
+ this.pendingFrames = /* @__PURE__ */ new Map();
3916
+ this.sendTimers = /* @__PURE__ */ new Map();
3917
+ this.lastSentAt = /* @__PURE__ */ new Map();
3903
3918
  this.backstopTimer = null;
3904
- this.lastSentAt = 0;
3905
3919
  this.metrics = {
3906
3920
  sourceFrames: 0,
3907
3921
  sentFrames: 0,
3908
3922
  droppedFrames: 0,
3909
- ackErrors: 0
3923
+ ackErrors: 0,
3924
+ targets: 0
3910
3925
  };
3911
3926
  this.offFrame = cdp.on("Page.screencastFrame", (params, targetSessionId) => this.#onFrame(params, targetSessionId));
3912
3927
  this.offDestroyed = sessions.onDestroyed?.((targetId) => {
3913
- if (this.current?.targetId !== targetId) return;
3914
- this.stop("target-destroyed").then(() => this.onStatus({
3915
- backend: "cdp",
3916
- state: "failed",
3917
- targetId,
3918
- code: "capture-target-destroyed",
3919
- message: "The watched target was closed"
3920
- })).catch(() => {});
3928
+ if (!this.captures.has(targetId)) return;
3929
+ const remaining = this.captures.size - 1;
3930
+ this.stopTarget(targetId, "target-destroyed").then(() => {
3931
+ if (remaining > 0) return;
3932
+ this.onStatus({
3933
+ backend: "cdp",
3934
+ state: "failed",
3935
+ targetId,
3936
+ code: "capture-target-destroyed",
3937
+ message: "The watched target was closed"
3938
+ });
3939
+ }).catch(() => {});
3921
3940
  });
3922
3941
  }
3942
+ /** Reverse lookup: which watched target owns this flattened session id. */
3943
+ #captureBySession(targetSessionId) {
3944
+ if (!targetSessionId) return null;
3945
+ for (const capture of this.captures.values()) if (capture.sessionId === targetSessionId) return capture;
3946
+ return null;
3947
+ }
3948
+ /** All currently-watched target ids (manager derives the desired set from leases). */
3949
+ targetIds() {
3950
+ return [...this.captures.keys()];
3951
+ }
3923
3952
  async start({ targetId }) {
3924
- await this.stop("restart");
3953
+ if (this.captures.has(targetId)) return;
3925
3954
  const session = await this.sessions.ensure(targetId);
3926
3955
  const config = this.getConfig();
3927
- this.current = {
3956
+ this.captures.set(targetId, {
3928
3957
  targetId,
3929
3958
  sessionId: session.sessionId,
3930
3959
  lastFrameAt: 0,
3931
3960
  startedAt: this.now()
3932
- };
3961
+ });
3962
+ this.metrics.targets = this.captures.size;
3933
3963
  this.onStatus({
3934
3964
  backend: "cdp",
3935
3965
  state: "starting",
@@ -3950,7 +3980,8 @@ var CdpCaptureBackend = class {
3950
3980
  });
3951
3981
  this.#scheduleBackstop();
3952
3982
  } catch (error) {
3953
- this.current = null;
3983
+ this.captures.delete(targetId);
3984
+ this.metrics.targets = this.captures.size;
3954
3985
  this.onStatus({
3955
3986
  backend: "cdp",
3956
3987
  state: "failed",
@@ -3961,6 +3992,7 @@ var CdpCaptureBackend = class {
3961
3992
  throw error;
3962
3993
  }
3963
3994
  }
3995
+ /** Keep legacy single-target shape for callers that only know "switch". */
3964
3996
  async switchTarget({ targetId }) {
3965
3997
  this.onStatus({
3966
3998
  backend: "cdp",
@@ -3970,32 +4002,76 @@ var CdpCaptureBackend = class {
3970
4002
  await this.start({ targetId });
3971
4003
  }
3972
4004
  async updateConfig() {
3973
- if (this.current) await this.start({ targetId: this.current.targetId });
4005
+ for (const targetId of this.captures.keys()) {
4006
+ const capture = this.captures.get(targetId);
4007
+ await this.cdp.call("Page.stopScreencast", {}, capture.sessionId).catch(() => {});
4008
+ const config = this.getConfig();
4009
+ try {
4010
+ await this.cdp.call("Page.startScreencast", {
4011
+ format: this.imageFormat,
4012
+ ...this.imageFormat === "jpeg" ? { quality: config.cdpQuality } : {},
4013
+ maxWidth: config.cdpMaxWidth,
4014
+ everyNthFrame: 1
4015
+ }, capture.sessionId);
4016
+ } catch (error) {
4017
+ this.captures.delete(targetId);
4018
+ this.metrics.targets = this.captures.size;
4019
+ this.onStatus({
4020
+ backend: "cdp",
4021
+ state: "failed",
4022
+ targetId,
4023
+ code: "cdp-start-failed",
4024
+ message: error.message
4025
+ });
4026
+ }
4027
+ }
4028
+ }
4029
+ /** Stop exactly one target's screencast; the others keep streaming. */
4030
+ async stopTarget(targetId, reason = "stopped") {
4031
+ this.#clearSendTimer(targetId);
4032
+ this.pendingFrames.delete(targetId);
4033
+ const capture = this.captures.get(targetId);
4034
+ if (!capture) return;
4035
+ this.captures.delete(targetId);
4036
+ this.lastSentAt.delete(targetId);
4037
+ this.metrics.targets = this.captures.size;
4038
+ await this.cdp.call("Page.stopScreencast", {}, capture.sessionId).catch(() => {});
4039
+ this.onStatus({
4040
+ backend: "cdp",
4041
+ state: this.captures.size > 0 ? "streaming" : "idle",
4042
+ targetId: this.captures.size > 0 ? targetId : null,
4043
+ message: reason,
4044
+ metrics: this.metrics
4045
+ });
3974
4046
  }
3975
4047
  async stop(reason = "stopped") {
3976
- this.clearTimer(this.sendTimer);
3977
- this.clearTimer(this.backstopTimer);
3978
- this.sendTimer = null;
3979
- this.backstopTimer = null;
3980
- this.pendingFrame = null;
3981
- const current = this.current;
3982
- this.current = null;
3983
- if (current) {
3984
- await this.cdp.call("Page.stopScreencast", {}, current.sessionId).catch(() => {});
3985
- this.onStatus({
3986
- backend: "cdp",
3987
- state: "idle",
3988
- targetId: null,
3989
- message: reason,
3990
- metrics: this.metrics
3991
- });
3992
- }
4048
+ for (const targetId of [...this.captures.keys()]) {
4049
+ this.#clearSendTimer(targetId);
4050
+ const capture = this.captures.get(targetId);
4051
+ this.captures.delete(targetId);
4052
+ this.lastSentAt.delete(targetId);
4053
+ await this.cdp.call("Page.stopScreencast", {}, capture.sessionId).catch(() => {});
4054
+ }
4055
+ this.pendingFrames.clear();
4056
+ this.metrics.targets = 0;
4057
+ if (this.backstopTimer) {
4058
+ this.clearTimer(this.backstopTimer);
4059
+ this.backstopTimer = null;
4060
+ }
4061
+ if (this.lastSentAt.size === 0) this.onStatus({
4062
+ backend: "cdp",
4063
+ state: "idle",
4064
+ targetId: null,
4065
+ message: reason,
4066
+ metrics: this.metrics
4067
+ });
3993
4068
  }
3994
4069
  status() {
3995
4070
  return {
3996
4071
  backend: "cdp",
3997
- state: this.current ? "streaming" : "idle",
3998
- targetId: this.current?.targetId || null,
4072
+ state: this.captures.size > 0 ? "streaming" : "idle",
4073
+ targetId: this.captures.size > 0 ? [...this.captures.keys()][this.captures.size - 1] : null,
4074
+ targetIds: this.targetIds(),
3999
4075
  metrics: { ...this.metrics }
4000
4076
  };
4001
4077
  }
@@ -4004,10 +4080,21 @@ var CdpCaptureBackend = class {
4004
4080
  this.offFrame = null;
4005
4081
  this.offDestroyed?.();
4006
4082
  this.offDestroyed = null;
4083
+ if (this.backstopTimer) {
4084
+ this.clearTimer(this.backstopTimer);
4085
+ this.backstopTimer = null;
4086
+ }
4087
+ }
4088
+ #clearSendTimer(targetId) {
4089
+ const timer = this.sendTimers.get(targetId);
4090
+ if (timer) {
4091
+ this.clearTimer(timer);
4092
+ this.sendTimers.delete(targetId);
4093
+ }
4007
4094
  }
4008
4095
  async #onFrame(params, targetSessionId) {
4009
- const current = this.current;
4010
- if (!current || current.sessionId !== targetSessionId) return;
4096
+ const capture = this.#captureBySession(targetSessionId);
4097
+ if (!capture) return;
4011
4098
  this.metrics.sourceFrames += 1;
4012
4099
  if (params.sessionId === void 0 || params.sessionId === null) this.metrics.ackErrors += 1;
4013
4100
  else this.cdp.call("Page.screencastFrameAck", { sessionId: params.sessionId }, targetSessionId).catch((error) => {
@@ -4015,7 +4102,7 @@ var CdpCaptureBackend = class {
4015
4102
  this.onStatus({
4016
4103
  backend: "cdp",
4017
4104
  state: "streaming",
4018
- targetId: current.targetId,
4105
+ targetId: capture.targetId,
4019
4106
  code: "cdp-ack-failed",
4020
4107
  message: error.message,
4021
4108
  metrics: this.metrics
@@ -4023,42 +4110,45 @@ var CdpCaptureBackend = class {
4023
4110
  });
4024
4111
  if (!params.data) return;
4025
4112
  const metadata = params.metadata || {};
4026
- const session = this.sessions.get(current.targetId);
4113
+ const session = this.sessions.get(capture.targetId);
4027
4114
  if (session) {
4028
4115
  if (Number.isFinite(metadata.visibleViewportWidth)) session.viewportW = metadata.visibleViewportWidth;
4029
4116
  if (Number.isFinite(metadata.visibleViewportHeight)) session.viewportH = metadata.visibleViewportHeight;
4030
4117
  }
4031
- this.pendingFrame = {
4032
- targetId: current.targetId,
4118
+ this.pendingFrames.set(capture.targetId, {
4119
+ targetId: capture.targetId,
4033
4120
  data: params.data,
4034
4121
  vw: session?.viewportW || null,
4035
4122
  vh: session?.viewportH || null,
4036
4123
  ts: this.now()
4037
- };
4038
- current.lastFrameAt = this.now();
4124
+ });
4125
+ capture.lastFrameAt = this.now();
4039
4126
  const minGap = 1e3 / this.getConfig().cdpFps;
4040
- const delay = Math.max(0, minGap - (this.now() - (this.lastSentAt || 0)));
4041
- if (delay === 0) this.#flushLatest();
4042
- else if (!this.sendTimer) this.sendTimer = this.setTimer(() => this.#flushLatest(), delay);
4127
+ const last = this.lastSentAt.get(capture.targetId) || 0;
4128
+ const delay = Math.max(0, minGap - (this.now() - last));
4129
+ if (delay === 0) this.#flushLatest(capture.targetId);
4130
+ else if (!this.sendTimers.has(capture.targetId)) this.sendTimers.set(capture.targetId, this.setTimer(() => this.#flushLatest(capture.targetId), delay));
4043
4131
  if (delay > 0) this.metrics.droppedFrames += 1;
4044
4132
  }
4045
- #flushLatest() {
4046
- this.sendTimer = null;
4047
- const frame = this.pendingFrame;
4048
- this.pendingFrame = null;
4049
- if (!frame || !this.current || frame.targetId !== this.current.targetId) return;
4050
- this.lastSentAt = this.now();
4133
+ #flushLatest(targetId) {
4134
+ this.sendTimers.delete(targetId);
4135
+ const frame = this.pendingFrames.get(targetId);
4136
+ this.pendingFrames.delete(targetId);
4137
+ const capture = this.captures.get(targetId);
4138
+ if (!frame || !capture) return;
4139
+ this.lastSentAt.set(targetId, this.now());
4051
4140
  this.metrics.sentFrames += 1;
4052
4141
  this.onJpegFrame(frame);
4053
4142
  }
4143
+ /** One shared timer: every tick, screenshot each target whose frames stalled. */
4054
4144
  #scheduleBackstop() {
4055
- this.clearTimer(this.backstopTimer);
4145
+ if (this.backstopTimer) return;
4056
4146
  const interval = this.getConfig().cdpBackstopIntervalMs;
4057
4147
  this.backstopTimer = this.setTimer(async () => {
4058
- const current = this.current;
4059
- if (!current) return;
4060
- if (this.now() - current.lastFrameAt >= interval) try {
4061
- const session = await this.sessions.updateViewport(current.targetId);
4148
+ this.backstopTimer = null;
4149
+ const stale = [...this.captures.values()].filter((capture) => this.now() - capture.lastFrameAt >= interval);
4150
+ for (const capture of stale) try {
4151
+ const session = await this.sessions.updateViewport(capture.targetId);
4062
4152
  const scale = session.viewportW > this.getConfig().cdpMaxWidth ? this.getConfig().cdpMaxWidth / session.viewportW : 1;
4063
4153
  const result = await this.cdp.call("Page.captureScreenshot", {
4064
4154
  format: this.imageFormat,
@@ -4071,9 +4161,9 @@ var CdpCaptureBackend = class {
4071
4161
  height: session.viewportH,
4072
4162
  scale
4073
4163
  } } : {}
4074
- }, current.sessionId);
4164
+ }, capture.sessionId);
4075
4165
  if (result.data) this.onJpegFrame({
4076
- targetId: current.targetId,
4166
+ targetId: capture.targetId,
4077
4167
  data: result.data,
4078
4168
  vw: session.viewportW,
4079
4169
  vh: session.viewportH,
@@ -4081,7 +4171,7 @@ var CdpCaptureBackend = class {
4081
4171
  backstop: true
4082
4172
  });
4083
4173
  } catch {}
4084
- this.#scheduleBackstop();
4174
+ if (this.captures.size > 0) this.#scheduleBackstop();
4085
4175
  }, interval);
4086
4176
  }
4087
4177
  };
@@ -4138,6 +4228,16 @@ var CaptureManager = class {
4138
4228
  this.stopTimer = null;
4139
4229
  this.sweepTimer = this.setTimer(() => this.#sweep(), Math.min(5e3, this.leaseTtlMs));
4140
4230
  }
4231
+ /**
4232
+ * #15 D7 — derive the desired target set from the lease set. NO reference
4233
+ * counting: sweep-expired leases, in-place switchWatch retargets and
4234
+ * stop/start-on-same-target all collapse into "recompute the set", which
4235
+ * cannot leak (counting can: stale counts, orphaned old targets, flash on
4236
+ * transient zero).
4237
+ */
4238
+ #activeTargets() {
4239
+ return [...new Set([...this.leases.values()].map((lease) => lease.targetId))];
4240
+ }
4141
4241
  #resolvedBackend(requested) {
4142
4242
  const value = requested || this.getConfig().captureBackend;
4143
4243
  return value === "auto" ? "cdp" : value;
@@ -4147,20 +4247,14 @@ var CaptureManager = class {
4147
4247
  this.clearTimer(this.stopTimer);
4148
4248
  this.stopTimer = null;
4149
4249
  const requestedBackend = backend || this.getConfig().captureBackend;
4150
- const existing = this.leases.get(clientId);
4151
4250
  this.leases.set(clientId, {
4152
4251
  clientId,
4153
4252
  backend: requestedBackend,
4154
4253
  targetId,
4155
4254
  expiresAt: this.now() + this.leaseTtlMs
4156
4255
  });
4157
- if (existing && existing.backend === requestedBackend && existing.targetId === targetId) {
4158
- const resolved = this.#resolvedBackend(requestedBackend);
4159
- if (this.targetId !== targetId || this.backendName && this.backendName !== resolved) return this.status();
4160
- if (this.backend && this.backendName === resolved) return this.status();
4161
- }
4162
4256
  return this.#enqueue(async () => {
4163
- await this.#activate(this.#resolvedBackend(backend), targetId);
4257
+ await this.#ensureWatched(this.#resolvedBackend(requestedBackend), this.#activeTargets());
4164
4258
  return this.status();
4165
4259
  });
4166
4260
  }
@@ -4170,7 +4264,7 @@ var CaptureManager = class {
4170
4264
  lease.targetId = targetId;
4171
4265
  lease.expiresAt = this.now() + this.leaseTtlMs;
4172
4266
  return this.#enqueue(async () => {
4173
- await this.#activate(this.#resolvedBackend(lease.backend), targetId);
4267
+ await this.#ensureWatched(this.#resolvedBackend(lease.backend), this.#activeTargets());
4174
4268
  return this.status();
4175
4269
  });
4176
4270
  }
@@ -4180,13 +4274,20 @@ var CaptureManager = class {
4180
4274
  this.stopTimer = null;
4181
4275
  if (this.leases.size === 0) this.stop("no-watchers").catch(() => {});
4182
4276
  }, this.idleGraceMs);
4277
+ else if (this.leases.size > 0) {
4278
+ const desiredBackend = this.#resolvedBackend([...this.leases.values()].sort((a, b) => b.expiresAt - a.expiresAt)[0].backend);
4279
+ return this.#enqueue(async () => {
4280
+ await this.#ensureWatched(desiredBackend, this.#activeTargets());
4281
+ return this.status();
4282
+ });
4283
+ }
4183
4284
  return this.status();
4184
4285
  }
4185
4286
  async updateConfig() {
4186
4287
  const desired = this.#resolvedBackend();
4187
4288
  if (!this.backend) {
4188
4289
  const lease = [...this.leases.values()].sort((a, b) => b.expiresAt - a.expiresAt)[0];
4189
- if (lease) return this.#enqueue(() => this.#activate(this.#resolvedBackend(lease.backend), lease.targetId, true));
4290
+ if (lease) return this.#enqueue(() => this.#ensureWatched(this.#resolvedBackend(lease.backend), this.#activeTargets()));
4190
4291
  const fallbackReason = this.getConfig().ffmpegFallbackReason;
4191
4292
  this.#setStatus({
4192
4293
  backend: desired,
@@ -4197,7 +4298,7 @@ var CaptureManager = class {
4197
4298
  });
4198
4299
  return;
4199
4300
  }
4200
- return this.#enqueue(() => this.#activate(desired, this.targetId, true));
4301
+ return this.#enqueue(() => this.#ensureWatched(desired, this.#activeTargets()));
4201
4302
  }
4202
4303
  async browserDisconnected() {
4203
4304
  return this.#enqueue(async () => {
@@ -4212,99 +4313,144 @@ var CaptureManager = class {
4212
4313
  });
4213
4314
  }
4214
4315
  async browserConnected() {
4215
- const lease = [...this.leases.values()].sort((a, b) => b.expiresAt - a.expiresAt)[0];
4216
- if (lease) return this.#enqueue(() => this.#activate(this.#resolvedBackend(lease.backend), lease.targetId));
4316
+ if (this.leases.size > 0) return this.#enqueue(() => this.#ensureWatched(this.#resolvedBackend(), this.#activeTargets()));
4217
4317
  }
4218
- async #activate(backendName, targetId, force = false) {
4219
- if (!force && this.backend && this.backendName === backendName && this.targetId === targetId) return;
4318
+ /**
4319
+ * #15 — keep the backend watching EXACTLY the derived target set.
4320
+ * Whole-set diff (D7): one call may both add and remove; per-lease
4321
+ * start/stop would leak in that batch. Backend swap (global action) is the
4322
+ * only path that tears the whole backend down.
4323
+ */
4324
+ async #ensureWatched(backendName, targetIds) {
4220
4325
  if (!this.screencastSupported) {
4221
4326
  await this.#stopBackend("engine-unsupported");
4222
4327
  this.#setStatus({
4223
4328
  backend: backendName,
4224
4329
  state: "unsupported",
4225
- targetId,
4330
+ targetId: targetIds[0] ?? null,
4226
4331
  code: "engine-unsupported",
4227
4332
  message: "the attached engine cannot capture frames (no screencast, no window)",
4228
4333
  engineUnsupported: true
4229
4334
  });
4230
4335
  return;
4231
4336
  }
4232
- await this.#stopBackend("backend-change");
4233
- const factory = this.backendFactories[backendName];
4234
- if (!factory) {
4235
- const message = `${backendName} backend is unavailable`;
4236
- this.#setStatus({
4237
- backend: backendName,
4238
- state: "failed",
4239
- targetId,
4240
- code: "capture-backend-unavailable",
4241
- message
4242
- });
4243
- if (backendName === "ffmpeg" && this.backendFactories.cdp) {
4244
- await this.#activate("cdp", targetId, true);
4245
- if (this.backend && this.backendName === "cdp") this.#setStatus({
4246
- backend: "cdp",
4247
- code: "ffmpeg-fallback-cdp",
4248
- message: `FFmpeg unavailable; using CDP: ${message}`
4337
+ const effective = backendName === "ffmpeg" ? targetIds.slice(-1) : targetIds;
4338
+ if (backendName === "ffmpeg" && targetIds.length > 1) this.#setStatus({
4339
+ backend: backendName,
4340
+ singleStream: true,
4341
+ singleStreamReason: "FFmpeg captures one window stream; only the newest watched target is observed",
4342
+ targetId: effective[0] ?? null,
4343
+ targetIds: effective
4344
+ });
4345
+ if (this.backend && this.backendName !== backendName) await this.#stopBackend("backend-change");
4346
+ if (!this.backend) {
4347
+ const factory = this.backendFactories[backendName];
4348
+ if (!factory) {
4349
+ const message = `${backendName} backend is unavailable`;
4350
+ this.#setStatus({
4351
+ backend: backendName,
4352
+ state: "failed",
4353
+ targetId: effective[0] ?? null,
4354
+ code: "capture-backend-unavailable",
4355
+ message
4249
4356
  });
4357
+ if (backendName === "ffmpeg" && this.backendFactories.cdp) {
4358
+ await this.#ensureWatched("cdp", targetIds);
4359
+ if (this.backend && this.backendName === "cdp") this.#setStatus({
4360
+ backend: "cdp",
4361
+ code: "ffmpeg-fallback-cdp",
4362
+ message: `FFmpeg unavailable; using CDP: ${message}`
4363
+ });
4364
+ }
4365
+ return;
4250
4366
  }
4251
- return;
4252
- }
4253
- try {
4254
- this.backendName = backendName;
4255
- this.targetId = targetId;
4256
- this.generation += 1;
4257
- const generation = this.generation;
4258
- const fallbackReason = backendName === "cdp" ? this.getConfig().ffmpegFallbackReason : null;
4259
- this.#setStatus({
4260
- backend: backendName,
4261
- state: "starting",
4262
- targetId,
4263
- generation,
4264
- code: fallbackReason ? "ffmpeg-fallback-cdp" : null,
4265
- message: fallbackReason || null
4266
- });
4267
- let candidate;
4268
- candidate = factory({
4269
- generation,
4270
- onStatus: (status) => {
4271
- if (this.backend !== candidate || this.generation !== generation) return;
4272
- this.#setStatus({
4273
- ...status,
4274
- generation
4367
+ try {
4368
+ this.backendName = backendName;
4369
+ this.generation += 1;
4370
+ const generation = this.generation;
4371
+ const fallbackReason = backendName === "cdp" ? this.getConfig().ffmpegFallbackReason : null;
4372
+ this.#setStatus({
4373
+ backend: backendName,
4374
+ state: "starting",
4375
+ targetId: effective[0] ?? null,
4376
+ generation,
4377
+ code: fallbackReason ? "ffmpeg-fallback-cdp" : null,
4378
+ message: fallbackReason || null
4379
+ });
4380
+ let candidate;
4381
+ candidate = factory({
4382
+ generation,
4383
+ onStatus: (status) => {
4384
+ if (this.backend !== candidate || this.generation !== generation) return;
4385
+ this.#setStatus({
4386
+ ...status,
4387
+ generation
4388
+ });
4389
+ }
4390
+ });
4391
+ this.backend = candidate;
4392
+ for (const targetId of effective) await candidate.start({
4393
+ targetId,
4394
+ generation
4395
+ });
4396
+ } catch (error) {
4397
+ const e = error;
4398
+ const failed = this.backend;
4399
+ this.backend = null;
4400
+ if (failed) {
4401
+ await failed.stop?.("start-failed").catch(() => {});
4402
+ await Promise.resolve(failed.dispose?.()).catch(() => {});
4403
+ }
4404
+ this.#setStatus({
4405
+ backend: backendName,
4406
+ state: "failed",
4407
+ targetId: effective[0] ?? null,
4408
+ generation: this.generation,
4409
+ code: e.code,
4410
+ message: e.message
4411
+ });
4412
+ if (backendName === "ffmpeg" && this.backendFactories.cdp) {
4413
+ await this.#ensureWatched("cdp", targetIds);
4414
+ if (this.backend && this.backendName === "cdp") this.#setStatus({
4415
+ backend: "cdp",
4416
+ code: "ffmpeg-fallback-cdp",
4417
+ message: `FFmpeg unavailable; using CDP: ${e.message}`
4275
4418
  });
4276
4419
  }
4277
- });
4278
- this.backend = candidate;
4279
- await candidate.start({
4420
+ }
4421
+ return;
4422
+ }
4423
+ const live = new Set(this.backend.targetIds?.() ?? (this.targetId ? [this.targetId] : []));
4424
+ for (const targetId of effective) if (!live.has(targetId)) try {
4425
+ await this.backend.start({
4280
4426
  targetId,
4281
- generation
4427
+ generation: this.generation
4282
4428
  });
4283
4429
  } catch (error) {
4284
- const e = error;
4285
- const failed = this.backend;
4286
- this.backend = null;
4287
- if (failed) {
4288
- await failed.stop?.("start-failed").catch(() => {});
4289
- await Promise.resolve(failed.dispose?.()).catch(() => {});
4290
- }
4291
4430
  this.#setStatus({
4292
4431
  backend: backendName,
4293
4432
  state: "failed",
4294
4433
  targetId,
4295
- generation: this.generation,
4296
- code: e.code,
4297
- message: e.message
4434
+ code: error.code,
4435
+ message: error.message
4298
4436
  });
4299
- if (backendName === "ffmpeg" && this.backendFactories.cdp) {
4300
- await this.#activate("cdp", targetId, true);
4301
- if (this.backend && this.backendName === "cdp") this.#setStatus({
4302
- backend: "cdp",
4303
- code: "ffmpeg-fallback-cdp",
4304
- message: `FFmpeg unavailable; using CDP: ${e.message}`
4305
- });
4306
- }
4307
4437
  }
4438
+ if (this.backend.stopTarget) {
4439
+ for (const targetId of [...live]) if (!effective.includes(targetId)) await this.backend.stopTarget(targetId, "lease-set-changed");
4440
+ } else if (live.size > 0 && effective.length === 0) await this.#stopBackend("no-watchers");
4441
+ if (effective.length === 0) {
4442
+ await this.#stopBackend("no-watchers");
4443
+ return;
4444
+ }
4445
+ this.targetId = effective[effective.length - 1];
4446
+ this.#setStatus({
4447
+ targetId: this.targetId,
4448
+ targetIds: this.backend.targetIds?.() ?? effective
4449
+ });
4450
+ }
4451
+ async #activate(backendName, targetId, force = false) {
4452
+ if (!force && this.backend && this.backendName === backendName && this.targetId === targetId) return;
4453
+ await this.#ensureWatched(backendName, [targetId]);
4308
4454
  }
4309
4455
  async #stopBackend(reason = "stopped") {
4310
4456
  const backend = this.backend;
@@ -4319,6 +4465,7 @@ var CaptureManager = class {
4319
4465
  backend: this.#resolvedBackend(),
4320
4466
  state: "idle",
4321
4467
  targetId: null,
4468
+ targetIds: [],
4322
4469
  generation: this.generation,
4323
4470
  message: reason
4324
4471
  });
@@ -4332,9 +4479,11 @@ var CaptureManager = class {
4332
4479
  return run;
4333
4480
  }
4334
4481
  status() {
4482
+ const live = this.backend?.targetIds?.() ?? null;
4335
4483
  return {
4336
4484
  ...this.statusValue,
4337
- watchers: this.leases.size
4485
+ watchers: this.leases.size,
4486
+ ...live !== null ? { targetIds: live } : {}
4338
4487
  };
4339
4488
  }
4340
4489
  #setStatus(status) {
@@ -4348,6 +4497,10 @@ var CaptureManager = class {
4348
4497
  const now = this.now();
4349
4498
  for (const [clientId, lease] of this.leases) if (lease.expiresAt <= now) this.leases.delete(clientId);
4350
4499
  if (this.leases.size === 0 && this.backend) this.stop("lease-expired").catch(() => {});
4500
+ if (this.leases.size > 0 && this.backend) {
4501
+ const desiredBackend = this.#resolvedBackend([...this.leases.values()].sort((a, b) => b.expiresAt - a.expiresAt)[0].backend);
4502
+ this.#enqueue(() => this.#ensureWatched(desiredBackend, this.#activeTargets())).catch(() => {});
4503
+ }
4351
4504
  this.sweepTimer = this.setTimer(() => this.#sweep(), Math.min(5e3, this.leaseTtlMs));
4352
4505
  }
4353
4506
  async dispose() {
@@ -6551,7 +6704,9 @@ let currentStatus = {
6551
6704
  * the user made. Keeping them apart is what stops the panel highlight from
6552
6705
  * snapping back after a tab click (see src/runtime/focus.ts).
6553
6706
  */
6554
- let focusTargetId = null;
6707
+ let focusTargetGlobal = null;
6708
+ /** #15 — per-session focus slots: session id → target id it last drove. */
6709
+ const focusTargetBySession = /* @__PURE__ */ new Map();
6555
6710
  let videoInit = null;
6556
6711
  function normalizeConfig(input) {
6557
6712
  const next = { ...castConfig };
@@ -6816,15 +6971,22 @@ const proxyObserveCache = {
6816
6971
  * observation", never an error.
6817
6972
  * - the panel's own selection — belongs to the view focus, not here.
6818
6973
  *
6819
- * Order: explicit host focus (validated against the live list) → foreground
6820
- * observation (local port, else remote proxy) → none. `known` lets the caller
6821
- * pass the target list it already fetched, so a closed tab cannot keep the
6822
- * highlight.
6974
+ * Order: per-session focus (validated against the live list) → explicit host
6975
+ * focus → foreground observation (local port, else remote proxy) → none.
6976
+ * `known` lets the caller pass the target list it already fetched, so a closed
6977
+ * tab cannot keep the highlight.
6823
6978
  */
6824
- async function activeTargetInfo(known) {
6979
+ async function activeTargetInfo(known, sessionId) {
6825
6980
  const inKnown = (id) => known === void 0 || known.includes(id);
6826
- if (focusTargetId !== null && inKnown(focusTargetId)) return {
6827
- id: focusTargetId,
6981
+ if (sessionId) {
6982
+ const scoped = focusTargetBySession.get(sessionId);
6983
+ if (scoped !== void 0 && inKnown(scoped)) return {
6984
+ id: scoped,
6985
+ source: "focus-session"
6986
+ };
6987
+ }
6988
+ if (focusTargetGlobal !== null && inKnown(focusTargetGlobal)) return {
6989
+ id: focusTargetGlobal,
6828
6990
  source: "focus"
6829
6991
  };
6830
6992
  const target = await devtoolsBase(active);
@@ -6879,16 +7041,16 @@ async function activeTargetInfo(known) {
6879
7041
  };
6880
7042
  }
6881
7043
  /** String-only view of `activeTargetInfo` for the single-target routes. */
6882
- async function activeTargetId() {
6883
- return (await activeTargetInfo()).id;
7044
+ async function activeTargetId(sessionId) {
7045
+ return (await activeTargetInfo(void 0, sessionId)).id;
6884
7046
  }
6885
- async function snapshotSpaces() {
7047
+ async function snapshotSpaces(sessionId) {
6886
7048
  const browser = active;
6887
7049
  if (browser === null) return [];
6888
7050
  const targets = await listTargets();
6889
- const activeInfo = await activeTargetInfo(targets.map((target) => target.targetId));
7051
+ const activeInfo = await activeTargetInfo(targets.map((target) => target.targetId), sessionId);
6890
7052
  const activeId = activeInfo.id;
6891
- const capturingId = currentStatus.targetId;
7053
+ const capturingIds = new Set(currentStatus.targetIds ?? (currentStatus.targetId ? [currentStatus.targetId] : []));
6892
7054
  const spaces = [];
6893
7055
  for (const target of targets.slice(0, 30)) {
6894
7056
  const frame = frameCache.get(target.targetId);
@@ -6911,7 +7073,7 @@ async function snapshotSpaces() {
6911
7073
  title: target.title,
6912
7074
  active: target.targetId === activeId,
6913
7075
  activeSource: target.targetId === activeId ? activeInfo.source : "",
6914
- capturing: target.targetId === capturingId,
7076
+ capturing: capturingIds.has(target.targetId),
6915
7077
  lastActive: frame?.lastActive || 0,
6916
7078
  viewportW: frame?.viewportW || session?.viewportW,
6917
7079
  viewportH: frame?.viewportH || session?.viewportH,
@@ -7037,11 +7199,14 @@ async function main() {
7037
7199
  browserConnected: !!active,
7038
7200
  capture: manager.status()
7039
7201
  });
7040
- if (req.method === "GET" && url.pathname === "/api/spaces") return sendJson(res, 200, {
7041
- ok: true,
7042
- spaces: active ? await snapshotSpaces() : [],
7043
- capture: manager.status()
7044
- });
7202
+ if (req.method === "GET" && url.pathname === "/api/spaces") {
7203
+ const sid = typeof url.searchParams.get("sessionId") === "string" ? url.searchParams.get("sessionId").trim() : "";
7204
+ return sendJson(res, 200, {
7205
+ ok: true,
7206
+ spaces: active ? await snapshotSpaces(sid || void 0) : [],
7207
+ capture: manager.status()
7208
+ });
7209
+ }
7045
7210
  if (req.method === "GET" && url.pathname === "/api/watch/status") return sendJson(res, 200, {
7046
7211
  ok: true,
7047
7212
  ...manager.status()
@@ -7064,15 +7229,25 @@ async function main() {
7064
7229
  ok: false,
7065
7230
  error: "no live browser"
7066
7231
  });
7232
+ const body = await readJson(req);
7233
+ const status = await manager.startWatch(body);
7234
+ const sid = typeof body.sessionId === "string" ? body.sessionId.trim() : "";
7235
+ if (sid !== "" && typeof body.targetId === "string" && body.targetId !== "") focusTargetBySession.set(sid, body.targetId);
7067
7236
  return sendJson(res, 200, {
7068
7237
  ok: true,
7069
- ...await manager.startWatch(await readJson(req))
7238
+ ...status
7239
+ });
7240
+ }
7241
+ if (req.method === "POST" && url.pathname === "/api/watch/switch") {
7242
+ const body = await readJson(req);
7243
+ const status = await manager.switchWatch(body);
7244
+ const sid = typeof body.sessionId === "string" ? body.sessionId.trim() : "";
7245
+ if (sid !== "" && typeof body.targetId === "string" && body.targetId !== "") focusTargetBySession.set(sid, body.targetId);
7246
+ return sendJson(res, 200, {
7247
+ ok: true,
7248
+ ...status
7070
7249
  });
7071
7250
  }
7072
- if (req.method === "POST" && url.pathname === "/api/watch/switch") return sendJson(res, 200, {
7073
- ok: true,
7074
- ...await manager.switchWatch(await readJson(req))
7075
- });
7076
7251
  if (req.method === "POST" && url.pathname === "/api/watch/stop") return sendJson(res, 200, {
7077
7252
  ok: true,
7078
7253
  ...await manager.stopWatch(await readJson(req))
@@ -7234,8 +7409,11 @@ async function main() {
7234
7409
  });
7235
7410
  const body = await readJson(req);
7236
7411
  const targetId = typeof body?.targetId === "string" ? body.targetId.trim() : "";
7412
+ const sessionId = typeof body?.sessionId === "string" ? body.sessionId.trim() : "";
7237
7413
  if (targetId === "") {
7238
- focusTargetId = null;
7414
+ focusTargetGlobal = null;
7415
+ if (sessionId !== "") focusTargetBySession.delete(sessionId);
7416
+ else focusTargetBySession.clear();
7239
7417
  return sendJson(res, 200, {
7240
7418
  ok: true,
7241
7419
  cleared: true
@@ -7247,7 +7425,8 @@ async function main() {
7247
7425
  error: "that target is gone",
7248
7426
  targetId
7249
7427
  });
7250
- focusTargetId = targetId;
7428
+ if (sessionId !== "") focusTargetBySession.set(sessionId, targetId);
7429
+ else focusTargetGlobal = targetId;
7251
7430
  return sendJson(res, 200, {
7252
7431
  ok: true,
7253
7432
  targetId
@@ -7261,7 +7440,8 @@ async function main() {
7261
7440
  error: "targetId required"
7262
7441
  });
7263
7442
  await active.cdp.call("Target.closeTarget", { targetId });
7264
- if (focusTargetId === targetId) focusTargetId = null;
7443
+ if (focusTargetGlobal === targetId) focusTargetGlobal = null;
7444
+ for (const [sid, tid] of focusTargetBySession) if (tid === targetId) focusTargetBySession.delete(sid);
7265
7445
  return sendJson(res, 200, { ok: true });
7266
7446
  }
7267
7447
  if (req.method === "POST" && url.pathname === "/api/switch-tab") {
@@ -7273,7 +7453,7 @@ async function main() {
7273
7453
  });
7274
7454
  try {
7275
7455
  await active.cdp.call("Target.activateTarget", { targetId });
7276
- focusTargetId = targetId;
7456
+ focusTargetGlobal = targetId;
7277
7457
  return sendJson(res, 200, {
7278
7458
  ok: true,
7279
7459
  targetId