@karlorz/codexhost-cli-linux-x64 0.22.0-1 → 0.22.0-5

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.
@@ -21209,6 +21209,7 @@ var RENDERER_VOICE_HOST_MAX_PAYLOAD_BYTES = 256 * 1024;
21209
21209
  var RENDERER_VOICE_HOST_SETTINGS_TIMEOUT_MS = 1e4;
21210
21210
  var RENDERER_VOICE_HOST_GATEWAY_TIMEOUT_MS = 2e3;
21211
21211
  var RENDERER_VOICE_HOST_REALTIME_TIMEOUT_MS = 3e4;
21212
+ var RENDERER_VOICE_HOST_PUBLISH_RETRY_MS = 1e3;
21212
21213
  var RENDERER_VOICE_HOST_METHODS = [
21213
21214
  VOICE_SETTINGS_METHOD,
21214
21215
  VOICE_GATEWAY_STATUS_METHOD,
@@ -21232,7 +21233,7 @@ function cleanupUnconfirmedError(error51) {
21232
21233
  if (error51 instanceof Error && error51.message === RENDERER_VOICE_HOST_CLEANUP_UNCONFIRMED && allowlistedStage(Reflect.get(error51, "stage")) === "cancel")
21233
21234
  return error51;
21234
21235
  }
21235
- function rendererVoiceHostCapabilitySource(owner, generation) {
21236
+ function rendererVoiceHostCapabilitySource(owner, generation, instanceId = "", installationOrder = 0, publisherId2 = "") {
21236
21237
  const guard = rendererVoiceHostDocumentGuardExpression();
21237
21238
  return `(() => {
21238
21239
  if (!${guard}) return true;
@@ -21244,6 +21245,9 @@ function rendererVoiceHostCapabilitySource(owner, generation) {
21244
21245
  const maxBytes = ${RENDERER_VOICE_HOST_MAX_PAYLOAD_BYTES};
21245
21246
  const ownerId = ${JSON.stringify(owner)};
21246
21247
  const generation = ${generation};
21248
+ const instance = ${JSON.stringify(instanceId)};
21249
+ const order = ${installationOrder};
21250
+ const publisher = ${JSON.stringify(publisherId2)};
21247
21251
  const settingsTimeout = ${RENDERER_VOICE_HOST_SETTINGS_TIMEOUT_MS};
21248
21252
  const gatewayTimeout = ${RENDERER_VOICE_HOST_GATEWAY_TIMEOUT_MS};
21249
21253
  const realtimeTimeout = ${RENDERER_VOICE_HOST_REALTIME_TIMEOUT_MS};
@@ -21261,6 +21265,8 @@ function rendererVoiceHostCapabilitySource(owner, generation) {
21261
21265
  }
21262
21266
  };
21263
21267
  const previous = globalThis[cap];
21268
+ // A publish that outlived its installation must leave a newer installation's state intact.
21269
+ if (previous && previous.publisher === publisher && typeof previous.order === "number" && previous.order > order) return true;
21264
21270
  if (previous && previous.generation !== generation) settleAll(${JSON.stringify(UNAVAILABLE)});
21265
21271
  globalThis[deliver] = (message) => {
21266
21272
  if (!message || typeof message !== "object" || typeof message.id !== "string") return;
@@ -21285,6 +21291,9 @@ function rendererVoiceHostCapabilitySource(owner, generation) {
21285
21291
  value: Object.freeze({
21286
21292
  owner: ownerId,
21287
21293
  generation,
21294
+ instance,
21295
+ order,
21296
+ publisher,
21288
21297
  request(method, params) {
21289
21298
  try {
21290
21299
  if (!${guard}) return unavailable();
@@ -21316,7 +21325,7 @@ function rendererVoiceHostCapabilitySource(owner, generation) {
21316
21325
  } catch (e) {}
21317
21326
  reject(new Error(${JSON.stringify(UNAVAILABLE)}));
21318
21327
  }, timeoutMs);
21319
- pending.set(id, { resolve, reject, timer, generation });
21328
+ pending.set(id, { resolve, reject, timer, generation, instance });
21320
21329
  try {
21321
21330
  globalThis[binding](payload);
21322
21331
  } catch {
@@ -21345,20 +21354,6 @@ function callIdFromCreateResult(result) {
21345
21354
  const callId = realtimeCallIdFromLocation(location);
21346
21355
  return isRealtimeCallId(callId) ? callId : void 0;
21347
21356
  }
21348
- async function cleanupAbandonedCreate(execution, params, result) {
21349
- let unconfirmed;
21350
- const note = (error51) => {
21351
- unconfirmed ??= cleanupUnconfirmedError(error51);
21352
- };
21353
- const requestId2 = typeof params.requestId === "string" ? params.requestId : void 0;
21354
- if (requestId2) {
21355
- await execution.request(REALTIME_CALL_METHOD, { operation: "cancel", requestId: requestId2 }).catch(note);
21356
- }
21357
- const callId = callIdFromCreateResult(result);
21358
- if (!callId) return unconfirmed;
21359
- await execution.request(REALTIME_CALL_METHOD, { operation: "hangup", callId }).catch(note);
21360
- return unconfirmed;
21361
- }
21362
21357
  function captureExecution(host) {
21363
21358
  return host.bindExecution?.() ?? {
21364
21359
  generation: host.generation,
@@ -21394,22 +21389,48 @@ async function deliver(renderer, executionContextId, message) {
21394
21389
  returnByValue: true
21395
21390
  }).catch(() => void 0);
21396
21391
  }
21397
- async function registerFutureScript(renderer, source, previousId) {
21398
- if (previousId) {
21399
- await renderer.command("Page.removeScriptToEvaluateOnNewDocument", { identifier: previousId }).catch(() => void 0);
21400
- }
21392
+ async function addFutureScript(renderer, source) {
21401
21393
  const added = await renderer.command("Page.addScriptToEvaluateOnNewDocument", { source });
21402
- return isRecord2(added) && typeof added.identifier === "string" ? added.identifier : void 0;
21394
+ if (!isRecord2(added) || typeof added.identifier !== "string")
21395
+ throw new Error("Voice Host future script registration failed");
21396
+ return added.identifier;
21403
21397
  }
21404
21398
  async function removeFutureScript(renderer, identifier) {
21405
21399
  if (!identifier) return;
21406
21400
  await renderer.command("Page.removeScriptToEvaluateOnNewDocument", { identifier }).catch(() => void 0);
21407
21401
  }
21402
+ function rendererVoiceHostCleanupSource(instanceId) {
21403
+ return `(() => {
21404
+ const instance = ${JSON.stringify(instanceId)};
21405
+ const pending = globalThis[${JSON.stringify(RENDERER_VOICE_HOST_PENDING_GLOBAL)}];
21406
+ if (pending && typeof pending.forEach === "function") {
21407
+ for (const [id, wait] of [...pending.entries()]) {
21408
+ if (!wait || wait.instance !== instance) continue;
21409
+ pending.delete(id);
21410
+ try { clearTimeout(wait.timer); } catch (e) {}
21411
+ try { wait.reject(new Error(${JSON.stringify(UNKNOWN_OUTCOME)})); } catch (e) {}
21412
+ }
21413
+ }
21414
+ const capability = globalThis[${JSON.stringify(RENDERER_VOICE_HOST_CAPABILITY_GLOBAL)}];
21415
+ if (capability && capability.instance === instance) {
21416
+ delete globalThis[${JSON.stringify(RENDERER_VOICE_HOST_CAPABILITY_GLOBAL)}];
21417
+ delete globalThis[${JSON.stringify(RENDERER_VOICE_HOST_DELIVER_GLOBAL)}];
21418
+ if (globalThis[${JSON.stringify(RENDERER_VOICE_HOST_PENDING_GLOBAL)}] === pending)
21419
+ delete globalThis[${JSON.stringify(RENDERER_VOICE_HOST_PENDING_GLOBAL)}];
21420
+ }
21421
+ return true;
21422
+ })()`;
21423
+ }
21424
+ var publisherId = crypto.randomUUID();
21425
+ var installationSequence = 0;
21408
21426
  async function installRendererVoiceHostBinding(renderer, host, options) {
21427
+ const instance = crypto.randomUUID();
21428
+ const installationOrder = installationSequence += 1;
21409
21429
  let disposed = false;
21430
+ let ready = false;
21410
21431
  let scriptId;
21432
+ let publishedGeneration;
21411
21433
  let publishing = Promise.resolve();
21412
- const inflight = /* @__PURE__ */ new Set();
21413
21434
  const works = /* @__PURE__ */ new Map();
21414
21435
  const abandonedIds = /* @__PURE__ */ new Set();
21415
21436
  const contexts = /* @__PURE__ */ new Map();
@@ -21432,20 +21453,47 @@ async function installRendererVoiceHostBinding(renderer, host, options) {
21432
21453
  stage: "cancel"
21433
21454
  });
21434
21455
  };
21435
- const abandonWork = (item) => {
21436
- if (item.abandoned) return;
21456
+ const reportCleanupUnconfirmed = (item, error51) => {
21457
+ const create = item.create;
21458
+ const unconfirmed = cleanupUnconfirmedError(error51);
21459
+ if (!create || !unconfirmed || create.cleanupReported) return;
21460
+ create.cleanupReported = true;
21461
+ void observeCleanupUnconfirmed(item.contextId, item.pageId, unconfirmed);
21462
+ };
21463
+ const requestCleanup = (item, params) => {
21464
+ try {
21465
+ void item.execution.request(REALTIME_CALL_METHOD, params).catch((error51) => reportCleanupUnconfirmed(item, error51));
21466
+ } catch (error51) {
21467
+ reportCleanupUnconfirmed(item, error51);
21468
+ }
21469
+ };
21470
+ const hangUpLateCreate = (item) => {
21471
+ const create = item.create;
21472
+ if (!create || create.hangupIssued) return;
21473
+ const callId = callIdFromCreateResult(create.result);
21474
+ if (!callId) return;
21475
+ create.hangupIssued = true;
21476
+ requestCleanup(item, { operation: "hangup", callId });
21477
+ };
21478
+ const retireWork = (item) => {
21437
21479
  item.abandoned = true;
21438
- if (!item.create) return;
21439
- void cleanupAbandonedCreate(
21440
- item.execution,
21441
- { requestId: item.create.requestId, operation: "create" },
21442
- item.create.result
21443
- ).then((unconfirmed) => observeCleanupUnconfirmed(item.contextId, item.pageId, unconfirmed));
21480
+ const create = item.create;
21481
+ if (!create) return;
21482
+ if (create.settled) {
21483
+ hangUpLateCreate(item);
21484
+ return;
21485
+ }
21486
+ if (create.cancelIssued) return;
21487
+ create.cancelIssued = true;
21488
+ requestCleanup(item, { operation: "cancel", requestId: create.requestId });
21489
+ };
21490
+ const retireInflight = () => {
21491
+ for (const item of works.values()) retireWork(item);
21444
21492
  };
21445
21493
  const abandonMatching = (contextId, uniqueId) => {
21446
21494
  for (const item of works.values()) {
21447
21495
  if (contextId !== void 0 && item.contextId === contextId || uniqueId !== void 0 && item.uniqueId === uniqueId)
21448
- abandonWork(item);
21496
+ retireWork(item);
21449
21497
  }
21450
21498
  };
21451
21499
  const forgetContext = (params) => {
@@ -21471,7 +21519,7 @@ async function installRendererVoiceHostBinding(renderer, host, options) {
21471
21519
  const unsubscribeDestroyed = renderer.on("Runtime.executionContextDestroyed", forgetContext);
21472
21520
  const unsubscribeCleared = renderer.on("Runtime.executionContextsCleared", () => {
21473
21521
  contexts.clear();
21474
- for (const item of works.values()) abandonWork(item);
21522
+ for (const item of works.values()) retireWork(item);
21475
21523
  });
21476
21524
  const contextIsVerified = async (executionContextId, uniqueId) => {
21477
21525
  const tracked = contexts.get(executionContextId);
@@ -21482,39 +21530,71 @@ async function installRendererVoiceHostBinding(renderer, host, options) {
21482
21530
  if (!document?.top) return false;
21483
21531
  return isEligibleVoiceHostUrl(document.href);
21484
21532
  };
21485
- const publishGeneration = async () => {
21486
- if (disposed) return;
21487
- const startedGeneration = host.generation;
21488
- const source = rendererVoiceHostCapabilitySource(host.owner, startedGeneration);
21489
- const addedId = await registerFutureScript(renderer, source, scriptId);
21490
- if (disposed || host.generation !== startedGeneration) {
21491
- await removeFutureScript(renderer, addedId);
21492
- return;
21493
- }
21494
- scriptId = addedId;
21495
- await renderer.evaluate(source);
21533
+ let publishRetry;
21534
+ const clearPublishRetry = () => {
21535
+ if (publishRetry === void 0) return;
21536
+ clearTimeout(publishRetry);
21537
+ publishRetry = void 0;
21496
21538
  };
21497
- const enqueuePublish = () => {
21498
- publishing = publishing.catch(() => void 0).then(() => publishGeneration()).catch(() => void 0);
21539
+ const schedulePublishRetry = () => {
21540
+ if (disposed || publishRetry !== void 0) return;
21541
+ publishRetry = setTimeout(() => {
21542
+ publishRetry = void 0;
21543
+ if (disposed) return;
21544
+ void enqueuePublish().catch(() => schedulePublishRetry());
21545
+ }, RENDERER_VOICE_HOST_PUBLISH_RETRY_MS);
21499
21546
  };
21500
- const cancelInflightCreates = () => {
21501
- for (const item of works.values()) {
21502
- if (!item.create || item.abandoned) continue;
21503
- void item.execution.request(REALTIME_CALL_METHOD, { operation: "cancel", requestId: item.create.requestId }).catch(
21504
- (error51) => observeCleanupUnconfirmed(item.contextId, item.pageId, cleanupUnconfirmedError(error51))
21547
+ const cleanupPageState = async () => {
21548
+ try {
21549
+ await renderer.evaluate(rendererVoiceHostCleanupSource(instance));
21550
+ } catch {
21551
+ }
21552
+ };
21553
+ const publishGeneration = async () => {
21554
+ for (let attempt = 0; !disposed && attempt < 3; attempt += 1) {
21555
+ const startedGeneration = host.generation;
21556
+ if (startedGeneration === publishedGeneration) return;
21557
+ const source = rendererVoiceHostCapabilitySource(
21558
+ host.owner,
21559
+ startedGeneration,
21560
+ instance,
21561
+ installationOrder,
21562
+ publisherId
21505
21563
  );
21564
+ const addedId = await addFutureScript(renderer, source);
21565
+ if (disposed || host.generation !== startedGeneration) {
21566
+ await removeFutureScript(renderer, addedId);
21567
+ continue;
21568
+ }
21569
+ const previousId = scriptId;
21570
+ scriptId = addedId;
21571
+ await removeFutureScript(renderer, previousId);
21572
+ if (disposed) return;
21573
+ await renderer.evaluate(source);
21574
+ if (disposed) {
21575
+ await cleanupPageState();
21576
+ return;
21577
+ }
21578
+ publishedGeneration = startedGeneration;
21579
+ if (host.generation === startedGeneration) return;
21506
21580
  }
21507
21581
  };
21508
- if (options?.enableRuntime !== false) await renderer.command("Runtime.enable");
21509
- await renderer.command("Page.enable");
21510
- await renderer.command("Runtime.addBinding", { name: RENDERER_VOICE_HOST_BINDING_NAME });
21511
- await publishGeneration();
21582
+ const enqueuePublish = () => {
21583
+ const next = publishing.catch(() => void 0).then(async () => {
21584
+ await publishGeneration();
21585
+ if (!disposed && host.generation !== publishedGeneration) schedulePublishRetry();
21586
+ else clearPublishRetry();
21587
+ });
21588
+ publishing = next.catch(() => void 0);
21589
+ return next;
21590
+ };
21512
21591
  const refresh = () => {
21513
21592
  if (disposed) return;
21514
- cancelInflightCreates();
21515
- enqueuePublish();
21593
+ retireInflight();
21594
+ if (!ready) return;
21595
+ void enqueuePublish().catch(() => schedulePublishRetry());
21516
21596
  };
21517
- const unsubscribeGeneration = host.onGenerationChange?.(refresh);
21597
+ let unsubscribeGeneration;
21518
21598
  const unsubscribe = renderer.on("Runtime.bindingCalled", (params) => {
21519
21599
  if (disposed || !isRecord2(params) || params.name !== RENDERER_VOICE_HOST_BINDING_NAME) return;
21520
21600
  if (typeof params.executionContextId !== "number" || typeof params.payload !== "string") return;
@@ -21522,7 +21602,7 @@ async function installRendererVoiceHostBinding(renderer, host, options) {
21522
21602
  const contextId = params.executionContextId;
21523
21603
  const payloadText = params.payload;
21524
21604
  const startedGeneration = host.generation;
21525
- const work = (async () => {
21605
+ void (async () => {
21526
21606
  let parsed;
21527
21607
  try {
21528
21608
  parsed = JSON.parse(payloadText);
@@ -21534,7 +21614,7 @@ async function installRendererVoiceHostBinding(renderer, host, options) {
21534
21614
  const requestId2 = parsed.id;
21535
21615
  if (parsed.abandon === true) {
21536
21616
  const existing = works.get(requestId2);
21537
- if (existing) abandonWork(existing);
21617
+ if (existing) retireWork(existing);
21538
21618
  else abandonedIds.add(requestId2);
21539
21619
  return;
21540
21620
  }
@@ -21555,22 +21635,21 @@ async function installRendererVoiceHostBinding(renderer, host, options) {
21555
21635
  generation: startedGeneration,
21556
21636
  execution,
21557
21637
  abandoned: abandonedIds.has(requestId2),
21558
- ...isCreateOperation(parsed.method, parsed.params) && typeof parsed.params.requestId === "string" ? { create: { requestId: parsed.params.requestId } } : {}
21638
+ ...isCreateOperation(parsed.method, parsed.params) && typeof parsed.params.requestId === "string" ? {
21639
+ create: {
21640
+ requestId: parsed.params.requestId,
21641
+ settled: false,
21642
+ cancelIssued: false,
21643
+ hangupIssued: false,
21644
+ cleanupReported: false
21645
+ }
21646
+ } : {}
21559
21647
  };
21560
21648
  works.set(requestId2, item);
21561
21649
  abandonedIds.delete(requestId2);
21562
21650
  try {
21563
21651
  if (item.abandoned) {
21564
- if (item.create)
21565
- await observeCleanupUnconfirmed(
21566
- contextId,
21567
- requestId2,
21568
- await cleanupAbandonedCreate(
21569
- item.execution,
21570
- { requestId: item.create.requestId, operation: "create" },
21571
- item.create.result
21572
- )
21573
- );
21652
+ retireWork(item);
21574
21653
  return;
21575
21654
  }
21576
21655
  const method = parsed.method;
@@ -21578,12 +21657,7 @@ async function installRendererVoiceHostBinding(renderer, host, options) {
21578
21657
  const verified = await contextIsVerified(contextId, uniqueId);
21579
21658
  const still = contexts.get(contextId);
21580
21659
  if (disposed || item.abandoned || host.generation !== startedGeneration || still?.uniqueId !== uniqueId) {
21581
- if (item.create)
21582
- await observeCleanupUnconfirmed(
21583
- contextId,
21584
- requestId2,
21585
- await cleanupAbandonedCreate(item.execution, requestParams, item.create.result)
21586
- );
21660
+ retireWork(item);
21587
21661
  return;
21588
21662
  }
21589
21663
  if (!verified) {
@@ -21597,21 +21671,21 @@ async function installRendererVoiceHostBinding(renderer, host, options) {
21597
21671
  }
21598
21672
  try {
21599
21673
  const result = await item.execution.request(method, requestParams);
21600
- if (item.create) item.create.result = result;
21674
+ if (item.create) {
21675
+ item.create.result = result;
21676
+ item.create.settled = true;
21677
+ }
21601
21678
  const after = contexts.get(contextId);
21602
21679
  if (disposed || item.abandoned || host.generation !== startedGeneration || after?.uniqueId !== uniqueId) {
21603
- if (item.create)
21604
- await observeCleanupUnconfirmed(
21605
- contextId,
21606
- requestId2,
21607
- await cleanupAbandonedCreate(item.execution, requestParams, result)
21608
- );
21680
+ retireWork(item);
21609
21681
  return;
21610
21682
  }
21611
21683
  await deliver(renderer, contextId, { id: requestId2, ok: true, result });
21612
21684
  } catch (error51) {
21685
+ if (item.create) item.create.settled = true;
21613
21686
  const unconfirmed = cleanupUnconfirmedError(error51);
21614
21687
  if (unconfirmed && !disposed) {
21688
+ if (item.create) item.create.cleanupReported = true;
21615
21689
  await deliver(renderer, contextId, {
21616
21690
  id: requestId2,
21617
21691
  ok: false,
@@ -21633,52 +21707,33 @@ async function installRendererVoiceHostBinding(renderer, host, options) {
21633
21707
  works.delete(requestId2);
21634
21708
  }
21635
21709
  })();
21636
- inflight.add(work);
21637
- void work.finally(() => inflight.delete(work));
21638
21710
  });
21639
- return () => {
21711
+ const dispose = () => {
21640
21712
  if (disposed) return;
21641
21713
  disposed = true;
21714
+ clearPublishRetry();
21642
21715
  unsubscribeGeneration?.();
21643
21716
  unsubscribe();
21644
21717
  unsubscribeCreated();
21645
21718
  unsubscribeDestroyed();
21646
21719
  unsubscribeCleared();
21647
- cancelInflightCreates();
21648
- const outstanding = [...inflight];
21649
- const leftover = [...works.values()];
21650
- void Promise.allSettled(outstanding).then(async () => {
21651
- for (const item of leftover)
21652
- if (item.create)
21653
- await observeCleanupUnconfirmed(
21654
- item.contextId,
21655
- item.pageId,
21656
- await cleanupAbandonedCreate(
21657
- item.execution,
21658
- { requestId: item.create.requestId, operation: "create" },
21659
- item.create.result
21660
- )
21661
- );
21662
- });
21720
+ retireInflight();
21663
21721
  void removeFutureScript(renderer, scriptId);
21664
21722
  void renderer.command("Runtime.removeBinding", { name: RENDERER_VOICE_HOST_BINDING_NAME }).catch(() => void 0);
21665
- void renderer.evaluate(
21666
- `(() => {
21667
- const pending = globalThis[${JSON.stringify(RENDERER_VOICE_HOST_PENDING_GLOBAL)}];
21668
- if (pending && typeof pending.forEach === "function") {
21669
- for (const [id, wait] of [...pending.entries()]) {
21670
- pending.delete(id);
21671
- try { clearTimeout(wait.timer); } catch (e) {}
21672
- try { wait.reject(new Error(${JSON.stringify(UNKNOWN_OUTCOME)})); } catch (e) {}
21673
- }
21674
- }
21675
- delete globalThis[${JSON.stringify(RENDERER_VOICE_HOST_CAPABILITY_GLOBAL)}];
21676
- delete globalThis[${JSON.stringify(RENDERER_VOICE_HOST_DELIVER_GLOBAL)}];
21677
- delete globalThis[${JSON.stringify(RENDERER_VOICE_HOST_PENDING_GLOBAL)}];
21678
- return true;
21679
- })()`
21680
- ).catch(() => void 0);
21723
+ void cleanupPageState();
21681
21724
  };
21725
+ try {
21726
+ unsubscribeGeneration = host.onGenerationChange?.(refresh);
21727
+ if (options?.enableRuntime !== false) await renderer.command("Runtime.enable");
21728
+ await renderer.command("Page.enable");
21729
+ await renderer.command("Runtime.addBinding", { name: RENDERER_VOICE_HOST_BINDING_NAME });
21730
+ ready = true;
21731
+ await enqueuePublish();
21732
+ } catch (error51) {
21733
+ dispose();
21734
+ throw error51;
21735
+ }
21736
+ return dispose;
21682
21737
  }
21683
21738
 
21684
21739
  // packages/desktop-control/src/renderer-cdp-control-session.ts
@@ -21695,6 +21750,33 @@ function discoveryTimeoutSignal(timeoutMs, signal) {
21695
21750
  function abortFailure(signal, fallback) {
21696
21751
  return signal.reason instanceof Error ? signal.reason : new Error(fallback);
21697
21752
  }
21753
+ function isRendererDocumentLoadEvent(params) {
21754
+ if (!isRecord3(params) || typeof params.name !== "string") return false;
21755
+ return params.name === "DOMContentLoaded" || params.name === "load" || params.name === "networkIdle";
21756
+ }
21757
+ async function waitForRendererDocumentLoad(renderer, run, signal, timeoutMessage) {
21758
+ await run(() => renderer.command("Page.enable"));
21759
+ let finished = false;
21760
+ const loaded = new Promise((resolve) => {
21761
+ const complete = () => {
21762
+ if (finished) return;
21763
+ finished = true;
21764
+ unsubscribeLoad();
21765
+ unsubscribeLifecycle();
21766
+ resolve();
21767
+ };
21768
+ const unsubscribeLoad = renderer.on("Page.loadEventFired", complete);
21769
+ const unsubscribeLifecycle = renderer.on("Page.lifecycleEvent", (params) => {
21770
+ if (isRendererDocumentLoadEvent(params)) complete();
21771
+ });
21772
+ });
21773
+ await run(() => renderer.command("Page.setLifecycleEventsEnabled", { enabled: true }));
21774
+ if (signal) await awaitWithSignal(loaded, signal, timeoutMessage);
21775
+ else await loaded;
21776
+ }
21777
+ function throwIfCdpAborted(signal, fallback) {
21778
+ if (signal.aborted) throw abortFailure(signal, fallback);
21779
+ }
21698
21780
  function awaitWithSignal(promise2, signal, timeoutMessage) {
21699
21781
  if (signal.aborted) return Promise.reject(abortFailure(signal, timeoutMessage));
21700
21782
  return new Promise((resolve, reject) => {
@@ -21808,6 +21890,40 @@ function unbindRendererVoiceHost(renderer, disposals) {
21808
21890
  disposals.get(renderer)?.();
21809
21891
  disposals.delete(renderer);
21810
21892
  }
21893
+ var VOICE_HOST_ATTACH_TIMEOUT_MS = 15e3;
21894
+ var VOICE_HOST_OVERLAY_RETRY_MS = 5e3;
21895
+ var VOICE_HOST_LIVENESS_INTERVAL_MS = 5e3;
21896
+ var VOICE_HOST_LIVENESS_TIMEOUT_MS = 3e3;
21897
+ async function bindVoiceHostOnNewConnection(target2, voiceHost, operations, timeoutMs, signal) {
21898
+ const timeout = AbortSignal.timeout(timeoutMs);
21899
+ const deadline = signal ? AbortSignal.any([timeout, signal]) : timeout;
21900
+ const timeoutMessage = "Voice Host attachment timed out";
21901
+ const client = await connectRendererTarget(target2, operations, deadline, timeoutMessage);
21902
+ const installing = installRendererVoiceHostBinding(client, voiceHost);
21903
+ try {
21904
+ const dispose = await awaitWithSignal(installing, deadline, timeoutMessage);
21905
+ return { targetId: target2.id, client, dispose, verifiedAt: Date.now() };
21906
+ } catch (error51) {
21907
+ client.close();
21908
+ throw error51;
21909
+ }
21910
+ }
21911
+ async function lateVoiceBindingIsLive(binding, signal) {
21912
+ if (Date.now() - binding.verifiedAt < VOICE_HOST_LIVENESS_INTERVAL_MS) return true;
21913
+ if (signal.aborted) return false;
21914
+ const deadline = AbortSignal.any([AbortSignal.timeout(VOICE_HOST_LIVENESS_TIMEOUT_MS), signal]);
21915
+ try {
21916
+ await awaitWithSignal(
21917
+ binding.client.evaluate("1", VOICE_HOST_LIVENESS_TIMEOUT_MS),
21918
+ deadline,
21919
+ "Voice Host binding liveness check timed out"
21920
+ );
21921
+ binding.verifiedAt = Date.now();
21922
+ return true;
21923
+ } catch {
21924
+ return false;
21925
+ }
21926
+ }
21811
21927
  async function evaluateSource(renderer, source) {
21812
21928
  const response = await renderer.command("Runtime.evaluate", {
21813
21929
  expression: source,
@@ -21989,6 +22105,7 @@ async function installOverlayHook(target2, overlayHookSource, overlayClients, op
21989
22105
  );
21990
22106
  await run(() => connected.command("Runtime.enable"));
21991
22107
  await run(() => connected.command("Page.enable"));
22108
+ throwIfCdpAborted(signal, timeoutMessage);
21992
22109
  overlayClients.set(target2.id, connected);
21993
22110
  } else if (voiceHost && voiceHostDisposals && !voiceHostDisposals.has(connected)) {
21994
22111
  await run(
@@ -22081,6 +22198,7 @@ async function installBrowserAnnotationStyles(target2, browserClients, operation
22081
22198
  source: BROWSER_ANNOTATION_STYLE_COMPAT_SOURCE
22082
22199
  })
22083
22200
  );
22201
+ throwIfCdpAborted(signal, timeoutMessage);
22084
22202
  browserClients.set(target2.id, connected);
22085
22203
  }
22086
22204
  const installed = await run(
@@ -22114,7 +22232,7 @@ async function installLocalThreadRenderer(target2, source, enabledAgents, operat
22114
22232
  renderer.close();
22115
22233
  }
22116
22234
  }
22117
- async function installAuxiliaryRenderers(endpoint, rendererSource, enabledAgents, overlayHookSource, overlayVoiceBootstrapSource, browserStyleClients, overlayClients, operations, signal, voiceHost, voiceHostDisposals) {
22235
+ async function installAuxiliaryRenderers(endpoint, rendererSource, enabledAgents, overlayHookSource, overlayVoiceBootstrapSource, browserStyleClients, overlayClients, operations, signal, voiceHost, voiceHostDisposals, lateVoiceBindings) {
22118
22236
  try {
22119
22237
  const targets = await awaitWithSignal(
22120
22238
  operations.listTargets(endpoint, signal),
@@ -22131,6 +22249,13 @@ async function installAuxiliaryRenderers(endpoint, rendererSource, enabledAgents
22131
22249
  }
22132
22250
  }
22133
22251
  }
22252
+ if (lateVoiceBindings)
22253
+ for (const [id, binding] of lateVoiceBindings) {
22254
+ if (liveTargets.has(id)) continue;
22255
+ binding.dispose();
22256
+ binding.client.close();
22257
+ lateVoiceBindings.delete(id);
22258
+ }
22134
22259
  await Promise.allSettled([
22135
22260
  ...targets.filter(isBrowserPage).map(
22136
22261
  (target2) => installBrowserAnnotationStyles(target2, browserStyleClients, operations, signal)
@@ -22154,20 +22279,36 @@ async function installAuxiliaryRenderers(endpoint, rendererSource, enabledAgents
22154
22279
  } catch {
22155
22280
  }
22156
22281
  }
22157
- async function installTarget(target2, rendererSource, enabledAgents, timeoutMs, pollIntervalMs, operations, voiceHost, voiceHostDisposals) {
22158
- const renderer = await operations.connect(target2.webSocketDebuggerUrl);
22282
+ async function installTarget(target2, rendererSource, enabledAgents, timeoutMs, pollIntervalMs, operations, voiceHost, voiceHostDisposals, signal, waitForDocumentLoad) {
22283
+ const timeoutMessage = "Primary Renderer installation timed out";
22284
+ const loadSignal = signal ?? (waitForDocumentLoad ? AbortSignal.timeout(timeoutMs) : void 0);
22285
+ const run = (operation) => loadSignal ? runWithCdpSignal(loadSignal, timeoutMessage, operation) : operation();
22286
+ const renderer = loadSignal ? await connectRendererTarget(target2, operations, loadSignal, timeoutMessage) : await operations.connect(target2.webSocketDebuggerUrl);
22159
22287
  let disposeModules;
22160
22288
  try {
22161
22289
  if (voiceHost && voiceHostDisposals)
22162
- await bindRendererVoiceHost(renderer, voiceHost, voiceHostDisposals, {
22163
- enableRuntime: false
22164
- });
22165
- disposeModules = await installRendererLoadedModules(renderer);
22166
- await renderer.command("Page.enable");
22167
- await renderer.command("Page.addScriptToEvaluateOnNewDocument", { source: rendererSource });
22168
- await evaluateSource(renderer, rendererSource);
22169
- const draftPrewarmPolicy = await operations.installDraftPrewarmPolicy(renderer);
22170
- const binding = await waitForBinding(renderer, enabledAgents, timeoutMs, pollIntervalMs);
22290
+ await run(
22291
+ () => bindRendererVoiceHost(renderer, voiceHost, voiceHostDisposals, {
22292
+ enableRuntime: false
22293
+ })
22294
+ );
22295
+ if (waitForDocumentLoad) {
22296
+ await waitForRendererDocumentLoad(renderer, run, loadSignal, timeoutMessage);
22297
+ }
22298
+ disposeModules = await run(() => installRendererLoadedModules(renderer));
22299
+ await run(() => renderer.command("Page.enable"));
22300
+ await run(
22301
+ () => renderer.command("Page.addScriptToEvaluateOnNewDocument", { source: rendererSource })
22302
+ );
22303
+ await run(() => evaluateSource(renderer, rendererSource));
22304
+ const draftPrewarmPolicy = await run(() => operations.installDraftPrewarmPolicy(renderer));
22305
+ const binding = await waitForBinding(
22306
+ renderer,
22307
+ enabledAgents,
22308
+ timeoutMs,
22309
+ pollIntervalMs,
22310
+ signal
22311
+ );
22171
22312
  return { renderer, snapshot: { target: target2, draftPrewarmPolicy, binding }, disposeModules };
22172
22313
  } catch (error51) {
22173
22314
  disposeModules?.();
@@ -22177,7 +22318,7 @@ async function installTarget(target2, rendererSource, enabledAgents, timeoutMs,
22177
22318
  }
22178
22319
  }
22179
22320
  var InstalledRendererCdpControlSession = class {
22180
- constructor(renderer, rendererCdpEndpoint2, rendererSource, overlayHookSource, overlayVoiceBootstrapSource, browserStyleClients, overlayClients, enabledAgents, timeoutMs, pollIntervalMs, operations, currentSnapshot, disposeModules, voiceHost, voiceHostDisposals) {
22321
+ constructor(renderer, rendererCdpEndpoint2, rendererSource, overlayHookSource, overlayVoiceBootstrapSource, browserStyleClients, overlayClients, enabledAgents, timeoutMs, pollIntervalMs, operations, currentSnapshot, disposeModules, voiceHost, voiceHostDisposals, waitForDocumentLoad) {
22181
22322
  this.renderer = renderer;
22182
22323
  this.rendererCdpEndpoint = rendererCdpEndpoint2;
22183
22324
  this.rendererSource = rendererSource;
@@ -22193,6 +22334,7 @@ var InstalledRendererCdpControlSession = class {
22193
22334
  this.disposeModules = disposeModules;
22194
22335
  this.voiceHost = voiceHost;
22195
22336
  this.voiceHostDisposals = voiceHostDisposals;
22337
+ this.waitForDocumentLoad = waitForDocumentLoad;
22196
22338
  }
22197
22339
  renderer;
22198
22340
  rendererCdpEndpoint;
@@ -22209,66 +22351,35 @@ var InstalledRendererCdpControlSession = class {
22209
22351
  disposeModules;
22210
22352
  voiceHost;
22211
22353
  voiceHostDisposals;
22354
+ waitForDocumentLoad;
22212
22355
  #closed = false;
22356
+ #lateVoiceHost;
22357
+ #lateVoicePrimaryId;
22358
+ #lateVoiceAttach;
22359
+ #lateVoiceBindings = /* @__PURE__ */ new Map();
22360
+ #overlayVoiceRetryAt = /* @__PURE__ */ new Map();
22361
+ // close() aborts this deadline, so discovery, connects, installs, and
22362
+ // liveness probes in flight stop instead of running to their own timeouts.
22363
+ #shutdown = new AbortController();
22213
22364
  get snapshot() {
22214
22365
  return this.currentSnapshot;
22215
22366
  }
22216
22367
  async ensureInstalled() {
22217
- if (this.#closed) throw new Error("Renderer CDP Control Session is closed");
22368
+ this.#assertOpen();
22218
22369
  const target2 = await waitForPrimaryTarget(
22219
22370
  this.rendererCdpEndpoint,
22220
22371
  this.operations,
22221
22372
  this.timeoutMs,
22222
22373
  this.pollIntervalMs,
22223
- this.currentSnapshot.target.id
22374
+ this.currentSnapshot.target.id,
22375
+ this.#shutdown.signal
22224
22376
  );
22377
+ this.#assertOpen();
22225
22378
  if (target2.id !== this.currentSnapshot.target.id) {
22226
- const replacement = await installTarget(
22227
- target2,
22228
- this.rendererSource,
22229
- this.enabledAgents,
22230
- this.timeoutMs,
22231
- this.pollIntervalMs,
22232
- this.operations,
22233
- this.voiceHost,
22234
- this.voiceHostDisposals
22235
- );
22236
- this.disposeModules();
22237
- unbindRendererVoiceHost(this.renderer, this.voiceHostDisposals);
22238
- this.renderer.close();
22239
- this.renderer = replacement.renderer;
22240
- this.disposeModules = replacement.disposeModules;
22241
- this.currentSnapshot = replacement.snapshot;
22379
+ this.#disposeLateVoiceBinding(this.currentSnapshot.target.id);
22380
+ await this.#replacePrimary(target2);
22242
22381
  } else {
22243
- try {
22244
- const existing = await readBinding(this.renderer);
22245
- if (existing === null) await evaluateSource(this.renderer, this.rendererSource);
22246
- const draftPrewarmPolicy = await this.operations.installDraftPrewarmPolicy(this.renderer);
22247
- const binding = await waitForBinding(
22248
- this.renderer,
22249
- this.enabledAgents,
22250
- this.timeoutMs,
22251
- this.pollIntervalMs
22252
- );
22253
- this.currentSnapshot = { target: target2, draftPrewarmPolicy, binding };
22254
- } catch {
22255
- const replacement = await installTarget(
22256
- target2,
22257
- this.rendererSource,
22258
- this.enabledAgents,
22259
- this.timeoutMs,
22260
- this.pollIntervalMs,
22261
- this.operations,
22262
- this.voiceHost,
22263
- this.voiceHostDisposals
22264
- );
22265
- this.disposeModules();
22266
- unbindRendererVoiceHost(this.renderer, this.voiceHostDisposals);
22267
- this.renderer.close();
22268
- this.renderer = replacement.renderer;
22269
- this.disposeModules = replacement.disposeModules;
22270
- this.currentSnapshot = replacement.snapshot;
22271
- }
22382
+ await this.#reconcilePrimary(target2);
22272
22383
  }
22273
22384
  await installAuxiliaryRenderers(
22274
22385
  this.rendererCdpEndpoint,
@@ -22279,14 +22390,178 @@ var InstalledRendererCdpControlSession = class {
22279
22390
  this.browserStyleClients,
22280
22391
  this.overlayClients,
22281
22392
  this.operations,
22282
- discoveryTimeoutSignal(this.timeoutMs),
22393
+ discoveryTimeoutSignal(this.timeoutMs, this.#shutdown.signal),
22283
22394
  this.voiceHost,
22284
- this.voiceHostDisposals
22395
+ this.voiceHostDisposals,
22396
+ this.#lateVoiceBindings
22285
22397
  );
22398
+ this.#assertOpen();
22286
22399
  return this.currentSnapshot;
22287
22400
  }
22288
- async activateDesktop() {
22401
+ async #reconcilePrimary(target2) {
22402
+ try {
22403
+ const existing = await this.#runWhileOpen(() => readBinding(this.renderer));
22404
+ if (existing === null)
22405
+ await this.#runWhileOpen(() => evaluateSource(this.renderer, this.rendererSource));
22406
+ const draftPrewarmPolicy = await this.#runWhileOpen(
22407
+ () => this.operations.installDraftPrewarmPolicy(this.renderer)
22408
+ );
22409
+ const binding = await waitForBinding(
22410
+ this.renderer,
22411
+ this.enabledAgents,
22412
+ this.timeoutMs,
22413
+ this.pollIntervalMs,
22414
+ this.#shutdown.signal
22415
+ );
22416
+ this.#assertOpen();
22417
+ this.currentSnapshot = { target: target2, draftPrewarmPolicy, binding };
22418
+ } catch {
22419
+ this.#assertOpen();
22420
+ this.#disposeLateVoiceBinding(this.currentSnapshot.target.id);
22421
+ await this.#replacePrimary(target2);
22422
+ }
22423
+ }
22424
+ async #replacePrimary(target2) {
22425
+ const replacement = await installTarget(
22426
+ target2,
22427
+ this.rendererSource,
22428
+ this.enabledAgents,
22429
+ this.timeoutMs,
22430
+ this.pollIntervalMs,
22431
+ this.operations,
22432
+ this.voiceHost,
22433
+ this.voiceHostDisposals,
22434
+ this.#shutdown.signal,
22435
+ this.waitForDocumentLoad
22436
+ );
22437
+ if (this.#closed) {
22438
+ replacement.disposeModules();
22439
+ unbindRendererVoiceHost(replacement.renderer, this.voiceHostDisposals);
22440
+ replacement.renderer.close();
22441
+ throw new Error("Renderer CDP Control Session is closed");
22442
+ }
22443
+ this.disposeModules();
22444
+ unbindRendererVoiceHost(this.renderer, this.voiceHostDisposals);
22445
+ this.renderer.close();
22446
+ this.renderer = replacement.renderer;
22447
+ this.disposeModules = replacement.disposeModules;
22448
+ this.currentSnapshot = replacement.snapshot;
22449
+ }
22450
+ #assertOpen() {
22289
22451
  if (this.#closed) throw new Error("Renderer CDP Control Session is closed");
22452
+ }
22453
+ #runWhileOpen(operation) {
22454
+ return runWithCdpSignal(
22455
+ this.#shutdown.signal,
22456
+ "Renderer CDP Control Session is closed",
22457
+ operation
22458
+ );
22459
+ }
22460
+ async attachVoiceHost(voiceHost) {
22461
+ this.#assertOpen();
22462
+ if (this.voiceHost) return;
22463
+ this.#lateVoiceAttach ??= this.#reconcileVoiceHost(voiceHost).finally(() => {
22464
+ this.#lateVoiceAttach = void 0;
22465
+ });
22466
+ return this.#lateVoiceAttach;
22467
+ }
22468
+ async #reconcileVoiceHost(voiceHost) {
22469
+ const timeoutMs = Math.min(this.timeoutMs, VOICE_HOST_ATTACH_TIMEOUT_MS);
22470
+ if (this.#lateVoiceHost !== void 0 && this.#lateVoiceHost !== voiceHost)
22471
+ this.#disposeLateVoiceBindings();
22472
+ const primaryTarget = this.currentSnapshot.target;
22473
+ if (this.#lateVoicePrimaryId !== void 0 && this.#lateVoicePrimaryId !== primaryTarget.id)
22474
+ this.#disposeLateVoiceBinding(this.#lateVoicePrimaryId);
22475
+ const existingPrimary = this.#lateVoiceBindings.get(primaryTarget.id);
22476
+ if (existingPrimary && !await lateVoiceBindingIsLive(existingPrimary, this.#shutdown.signal))
22477
+ this.#disposeLateVoiceBinding(primaryTarget.id);
22478
+ this.#assertOpen();
22479
+ if (!this.#lateVoiceBindings.has(primaryTarget.id)) {
22480
+ this.#disposeLateVoiceBinding(primaryTarget.id);
22481
+ const binding = await bindVoiceHostOnNewConnection(
22482
+ primaryTarget,
22483
+ voiceHost,
22484
+ this.operations,
22485
+ timeoutMs,
22486
+ this.#shutdown.signal
22487
+ );
22488
+ if (this.#closed) {
22489
+ binding.dispose();
22490
+ binding.client.close();
22491
+ throw new Error("Renderer CDP Control Session is closed");
22492
+ }
22493
+ this.#lateVoiceBindings.set(binding.targetId, binding);
22494
+ }
22495
+ this.#lateVoicePrimaryId = primaryTarget.id;
22496
+ this.#lateVoiceHost = voiceHost;
22497
+ await this.#reconcileOverlayVoiceHost(voiceHost, timeoutMs);
22498
+ this.#assertOpen();
22499
+ }
22500
+ async #reconcileOverlayVoiceHost(voiceHost, timeoutMs) {
22501
+ if (this.#closed || !this.overlayHookSource) return;
22502
+ const deadline = AbortSignal.any([AbortSignal.timeout(timeoutMs), this.#shutdown.signal]);
22503
+ let targets;
22504
+ try {
22505
+ targets = await awaitWithSignal(
22506
+ this.operations.listTargets(this.rendererCdpEndpoint, deadline),
22507
+ deadline,
22508
+ "Late overlay CDP target discovery timed out"
22509
+ );
22510
+ } catch {
22511
+ return;
22512
+ }
22513
+ const overlays = selectAvatarOverlayRendererTargets(targets);
22514
+ const live = new Set(overlays.map((target2) => target2.id));
22515
+ for (const id of [...this.#lateVoiceBindings.keys()])
22516
+ if (id !== this.#lateVoicePrimaryId && !live.has(id)) this.#disposeLateVoiceBinding(id);
22517
+ for (const id of [...this.#overlayVoiceRetryAt.keys()])
22518
+ if (!live.has(id)) this.#overlayVoiceRetryAt.delete(id);
22519
+ await Promise.allSettled(
22520
+ overlays.map(async (target2) => {
22521
+ if (this.#closed) return;
22522
+ const existing = this.#lateVoiceBindings.get(target2.id);
22523
+ if (existing) {
22524
+ if (await lateVoiceBindingIsLive(existing, this.#shutdown.signal)) return;
22525
+ if (this.#closed) return;
22526
+ this.#disposeLateVoiceBinding(target2.id);
22527
+ }
22528
+ if ((this.#overlayVoiceRetryAt.get(target2.id) ?? 0) > Date.now()) return;
22529
+ try {
22530
+ const binding = await bindVoiceHostOnNewConnection(
22531
+ target2,
22532
+ voiceHost,
22533
+ this.operations,
22534
+ timeoutMs,
22535
+ this.#shutdown.signal
22536
+ );
22537
+ if (this.#closed) {
22538
+ binding.dispose();
22539
+ binding.client.close();
22540
+ return;
22541
+ }
22542
+ this.#lateVoiceBindings.set(binding.targetId, binding);
22543
+ this.#overlayVoiceRetryAt.delete(binding.targetId);
22544
+ } catch {
22545
+ this.#overlayVoiceRetryAt.set(target2.id, Date.now() + VOICE_HOST_OVERLAY_RETRY_MS);
22546
+ }
22547
+ })
22548
+ );
22549
+ }
22550
+ #disposeLateVoiceBinding(targetId) {
22551
+ const binding = this.#lateVoiceBindings.get(targetId);
22552
+ if (!binding) return;
22553
+ binding.dispose();
22554
+ binding.client.close();
22555
+ this.#lateVoiceBindings.delete(targetId);
22556
+ if (this.#lateVoicePrimaryId === targetId) this.#lateVoicePrimaryId = void 0;
22557
+ this.#overlayVoiceRetryAt.delete(targetId);
22558
+ }
22559
+ #disposeLateVoiceBindings() {
22560
+ for (const targetId of [...this.#lateVoiceBindings.keys()])
22561
+ this.#disposeLateVoiceBinding(targetId);
22562
+ }
22563
+ async activateDesktop() {
22564
+ this.#assertOpen();
22290
22565
  await this.renderer.command("Page.bringToFront");
22291
22566
  return 1;
22292
22567
  }
@@ -22297,6 +22572,7 @@ var InstalledRendererCdpControlSession = class {
22297
22572
  close() {
22298
22573
  if (this.#closed) return;
22299
22574
  this.#closed = true;
22575
+ this.#shutdown.abort(new Error("Renderer CDP Control Session is closed"));
22300
22576
  this.disposeModules();
22301
22577
  unbindRendererVoiceHost(this.renderer, this.voiceHostDisposals);
22302
22578
  this.renderer.close();
@@ -22309,6 +22585,7 @@ var InstalledRendererCdpControlSession = class {
22309
22585
  this.overlayClients.clear();
22310
22586
  for (const dispose of this.voiceHostDisposals.values()) dispose();
22311
22587
  this.voiceHostDisposals.clear();
22588
+ this.#disposeLateVoiceBindings();
22312
22589
  }
22313
22590
  };
22314
22591
  var defaultOperations = {
@@ -22343,7 +22620,9 @@ async function createRendererCdpControlSession(options) {
22343
22620
  pollIntervalMs,
22344
22621
  operations,
22345
22622
  options.voiceHost,
22346
- voiceHostDisposals
22623
+ voiceHostDisposals,
22624
+ options.signal,
22625
+ options.waitForDocumentLoad
22347
22626
  );
22348
22627
  const browserStyleClients = /* @__PURE__ */ new Map();
22349
22628
  const overlayClients = /* @__PURE__ */ new Map();
@@ -22375,7 +22654,8 @@ async function createRendererCdpControlSession(options) {
22375
22654
  installed.snapshot,
22376
22655
  installed.disposeModules,
22377
22656
  options.voiceHost,
22378
- voiceHostDisposals
22657
+ voiceHostDisposals,
22658
+ options.waitForDocumentLoad === true
22379
22659
  );
22380
22660
  }
22381
22661
  function installRendererCdpControlSession(options) {
@@ -22385,10 +22665,15 @@ function installRendererCdpControlSession(options) {
22385
22665
  // packages/desktop-control/src/renderer-injection-skip.ts
22386
22666
  var SKIPPED_DESKTOP_VERSION_PREFIXES = ["26.1103.", "26.1106."];
22387
22667
  var HASHED_RENDERER_CANDIDATE_VERSION = "26.1106.51428";
22668
+ function hashedRendererWaitsForDocumentLoad(desktopVersion, platform = process.platform) {
22669
+ return platform === "win32" && desktopVersion?.trim() === HASHED_RENDERER_CANDIDATE_VERSION;
22670
+ }
22388
22671
  function rendererInjectionSkipReason(desktopVersion, platform = process.platform, options) {
22389
22672
  const version2 = desktopVersion?.trim();
22390
22673
  if (!version2) return null;
22391
- if (platform === "darwin" && version2 === HASHED_RENDERER_CANDIDATE_VERSION) return null;
22674
+ if (version2 === HASHED_RENDERER_CANDIDATE_VERSION && (platform === "darwin" || platform === "win32")) {
22675
+ return null;
22676
+ }
22392
22677
  if (SKIPPED_DESKTOP_VERSION_PREFIXES.some((prefix) => version2.startsWith(prefix))) {
22393
22678
  if (allowsIsolatedHashedInjection(version2, platform, options)) return null;
22394
22679
  return `Desktop ${version2} is skipped until hashed Renderer bindings are requalified`;
@@ -22777,6 +23062,8 @@ var TRANSIENT_INSTALL_RETRY_MS = 250;
22777
23062
  var RECOVERY_RETRY_INITIAL_MS = 3e4;
22778
23063
  var RECOVERY_RETRY_MAX_MS = 3e5;
22779
23064
  var REMOTE_CONNECTION_RECOVERY_INTERVAL_MS = 5e3;
23065
+ var VOICE_HOST_RETRY_INITIAL_MS = 1e3;
23066
+ var VOICE_HOST_RETRY_MAX_MS = 3e4;
22780
23067
  var SHUTDOWN_OPERATION_WAIT_MS = 3e3;
22781
23068
  async function settleWithin(promise2, milliseconds) {
22782
23069
  let timer;
@@ -22929,6 +23216,8 @@ async function runDesktopController(options, signal, dependencies = defaultDepen
22929
23216
  const now = dependencies.now ?? Date.now;
22930
23217
  let session;
22931
23218
  let voiceHost;
23219
+ let nextVoiceHostAt = 0;
23220
+ let voiceHostDelayMs = VOICE_HOST_RETRY_INITIAL_MS;
22932
23221
  let nextRecoveryAt = 0;
22933
23222
  let recoveryDelayMs = RECOVERY_RETRY_INITIAL_MS;
22934
23223
  const overlayDir = path6.dirname(options.rendererPath);
@@ -22989,11 +23278,16 @@ ${bootstrap}${overlayBundle}` : void 0;
22989
23278
  const overlayVoiceBootstrapSource = overlayHookSource && overlayBootstrapBundle.trim().length > 0 ? `${RENDERER_CSP_BOOTSTRAP}
22990
23279
  ${bootstrap}${overlayBootstrapBundle}` : void 0;
22991
23280
  startupTrace("installing Renderer Session");
23281
+ const waitForDocumentLoad = hashedRendererWaitsForDocumentLoad(desktopVersion);
22992
23282
  if (!voiceHost && options.hostDataDirectory && !skipReason) {
22993
- for (let attempt = 0; attempt < 8 && !voiceHost; attempt += 1) {
23283
+ for (let attempt = 0; attempt < 8 && !voiceHost && !signal.aborted; attempt += 1) {
22994
23284
  if (attempt > 0) await dependencies.sleep(250);
22995
23285
  voiceHost = await connectControllerVoiceHost(options.hostDataDirectory);
22996
23286
  }
23287
+ if (signal.aborted && voiceHost) {
23288
+ voiceHost.close();
23289
+ voiceHost = void 0;
23290
+ }
22997
23291
  }
22998
23292
  const installed = await installProductionSession(
22999
23293
  {
@@ -23005,13 +23299,59 @@ ${bootstrap}${rendererSource}`,
23005
23299
  ...voiceHost ? { voiceHost } : {},
23006
23300
  // External Agents are discovered from each target Host after installation.
23007
23301
  timeoutMs: PRODUCTION_INSTALL_TIMEOUT_MS,
23008
- signal
23302
+ signal,
23303
+ ...waitForDocumentLoad ? { waitForDocumentLoad } : {}
23009
23304
  },
23010
23305
  dependencies
23011
23306
  );
23012
23307
  startupTrace("Renderer Session installed");
23013
23308
  return installed;
23014
23309
  };
23310
+ const ensureVoiceHost = async (current) => {
23311
+ if (skipReason || !options.hostDataDirectory || signal.aborted) return;
23312
+ let connectedNow = false;
23313
+ if (!voiceHost) {
23314
+ if (now() < nextVoiceHostAt) return;
23315
+ const connected = await connectControllerVoiceHost(options.hostDataDirectory).catch(
23316
+ () => void 0
23317
+ );
23318
+ if (signal.aborted) {
23319
+ connected?.close();
23320
+ return;
23321
+ }
23322
+ if (!connected) {
23323
+ nextVoiceHostAt = now() + voiceHostDelayMs;
23324
+ voiceHostDelayMs = Math.min(voiceHostDelayMs * 2, VOICE_HOST_RETRY_MAX_MS);
23325
+ return;
23326
+ }
23327
+ voiceHost = connected;
23328
+ connectedNow = true;
23329
+ }
23330
+ const host = voiceHost;
23331
+ try {
23332
+ await current.attachVoiceHost(host);
23333
+ } catch (error51) {
23334
+ if (voiceHost === host) {
23335
+ host.close();
23336
+ voiceHost = void 0;
23337
+ }
23338
+ if (signal.aborted) return;
23339
+ nextVoiceHostAt = now() + voiceHostDelayMs;
23340
+ voiceHostDelayMs = Math.min(voiceHostDelayMs * 2, VOICE_HOST_RETRY_MAX_MS);
23341
+ startupTrace("Voice Host attachment deferred", error51);
23342
+ return;
23343
+ }
23344
+ if (signal.aborted || voiceHost !== host) {
23345
+ if (voiceHost === host) {
23346
+ host.close();
23347
+ voiceHost = void 0;
23348
+ }
23349
+ return;
23350
+ }
23351
+ nextVoiceHostAt = 0;
23352
+ voiceHostDelayMs = VOICE_HOST_RETRY_INITIAL_MS;
23353
+ if (connectedNow) startupTrace("Voice Host attached to the installed Renderer Session");
23354
+ };
23015
23355
  startupTrace("initialization started");
23016
23356
  let operation = Promise.resolve(void 0);
23017
23357
  const useSession = (callback) => {
@@ -23037,10 +23377,19 @@ ${bootstrap}${rendererSource}`,
23037
23377
  remoteRecovery = void 0;
23038
23378
  });
23039
23379
  };
23380
+ const releasedSessions = /* @__PURE__ */ new WeakSet();
23040
23381
  const resetSession = () => {
23041
- session?.close();
23382
+ if (session && !releasedSessions.has(session)) {
23383
+ releasedSessions.add(session);
23384
+ session.close();
23385
+ }
23042
23386
  session = void 0;
23043
23387
  };
23388
+ const releaseOwnedResources = () => {
23389
+ resetSession();
23390
+ voiceHost?.close();
23391
+ voiceHost = void 0;
23392
+ };
23044
23393
  const ensureSession = async () => {
23045
23394
  if (skipReason) throw new Error(skipReason);
23046
23395
  if (!session) session = await createSession();
@@ -23061,6 +23410,8 @@ ${bootstrap}${rendererSource}`,
23061
23410
  };
23062
23411
  let attachmentServer;
23063
23412
  try {
23413
+ signal.addEventListener("abort", releaseOwnedResources, { once: true });
23414
+ if (signal.aborted) releaseOwnedResources();
23064
23415
  startupTrace("starting attachment server");
23065
23416
  attachmentServer = await dependencies.startAttachmentServer({
23066
23417
  port: options.attachmentPort,
@@ -23100,6 +23451,10 @@ ${bootstrap}${rendererSource}`,
23100
23451
  if (session || skipReason) return;
23101
23452
  try {
23102
23453
  session = await createSession();
23454
+ if (signal.aborted) {
23455
+ resetSession();
23456
+ return;
23457
+ }
23103
23458
  recordRecoverySuccess();
23104
23459
  restoreRemoteConnections(session);
23105
23460
  } catch (error51) {
@@ -23114,17 +23469,19 @@ ${bootstrap}${rendererSource}`,
23114
23469
  await useSession(async () => {
23115
23470
  if (!session && now() < nextRecoveryAt) return;
23116
23471
  try {
23117
- restoreRemoteConnections(await recoverSession());
23472
+ const current = await recoverSession();
23473
+ restoreRemoteConnections(current);
23474
+ await ensureVoiceHost(current);
23118
23475
  } catch {
23119
23476
  }
23120
23477
  });
23121
23478
  }
23122
23479
  } finally {
23480
+ signal.removeEventListener("abort", releaseOwnedResources);
23123
23481
  await attachmentServer?.close();
23124
23482
  await settleWithin(operation, SHUTDOWN_OPERATION_WAIT_MS);
23125
- resetSession();
23126
- voiceHost?.close();
23127
- void operation.then(resetSession);
23483
+ releaseOwnedResources();
23484
+ void operation.then(releaseOwnedResources);
23128
23485
  }
23129
23486
  }
23130
23487