@memberjunction/ng-conversations 6.1.0-edge.4 → 6.1.0-edge.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.
Files changed (27) hide show
  1. package/dist/lib/components/conversation/conversation-chat-area.component.d.ts +2 -0
  2. package/dist/lib/components/conversation/conversation-chat-area.component.d.ts.map +1 -1
  3. package/dist/lib/components/conversation/conversation-chat-area.component.js +24 -0
  4. package/dist/lib/components/conversation/conversation-chat-area.component.js.map +1 -1
  5. package/dist/lib/components/message/message-input.component.d.ts +23 -0
  6. package/dist/lib/components/message/message-input.component.d.ts.map +1 -1
  7. package/dist/lib/components/message/message-input.component.js +144 -49
  8. package/dist/lib/components/message/message-input.component.js.map +1 -1
  9. package/dist/lib/components/message/message-item.component.d.ts +1 -0
  10. package/dist/lib/components/message/message-item.component.d.ts.map +1 -1
  11. package/dist/lib/components/message/message-item.component.js +52 -8
  12. package/dist/lib/components/message/message-item.component.js.map +1 -1
  13. package/dist/lib/components/realtime/remote-browser/remote-browser-channel.d.ts +65 -1
  14. package/dist/lib/components/realtime/remote-browser/remote-browser-channel.d.ts.map +1 -1
  15. package/dist/lib/components/realtime/remote-browser/remote-browser-channel.js +134 -41
  16. package/dist/lib/components/realtime/remote-browser/remote-browser-channel.js.map +1 -1
  17. package/dist/lib/components/workspace/conversation-workspace.component.d.ts.map +1 -1
  18. package/dist/lib/components/workspace/conversation-workspace.component.js +13 -3
  19. package/dist/lib/components/workspace/conversation-workspace.component.js.map +1 -1
  20. package/dist/lib/services/conversation-agent.service.d.ts.map +1 -1
  21. package/dist/lib/services/conversation-agent.service.js +7 -8
  22. package/dist/lib/services/conversation-agent.service.js.map +1 -1
  23. package/dist/lib/services/realtime-session.service.d.ts +188 -1
  24. package/dist/lib/services/realtime-session.service.d.ts.map +1 -1
  25. package/dist/lib/services/realtime-session.service.js +228 -25
  26. package/dist/lib/services/realtime-session.service.js.map +1 -1
  27. package/package.json +31 -31
@@ -47,7 +47,10 @@ LoadHuggingFaceRealtimeClient();
47
47
  * bakes the companion instructions + tool set into `SessionConfigJson`, which the client
48
48
  * driver applies verbatim.
49
49
  *
50
- * Lifecycle: {@link StartRealtimeSession} → live duplex → {@link EndRealtimeSession}.
50
+ * Lifecycle: {@link StartRealtimeSession} → live duplex → {@link EndRealtimeSession}. A start is
51
+ * two halves — MINT (the `StartRealtimeClientSession` mutation) and RUN (everything above) — and a
52
+ * host that must mint through its own server surface enters at the second half via
53
+ * {@link StartRealtimeSessionFromResult}; there is one implementation of the run half either way.
51
54
  */
52
55
  export class RealtimeSessionService {
53
56
  // ── Reactive UI state ──────────────────────────────────────────────────────
@@ -259,6 +262,19 @@ export class RealtimeSessionService {
259
262
  segmentIndex = 0;
260
263
  /** How often crash-recovery shards are flushed during a recording. */
261
264
  static SegmentFlushMs = 15000;
265
+ // ── Server-side liveness ───────────────────────────────────────────────────
266
+ /**
267
+ * Interval that tells the server this session is still in use, or `null` when no session is
268
+ * running. See {@link startLivenessPulse} for why the server cannot work this out itself.
269
+ */
270
+ livenessTimer = null;
271
+ /**
272
+ * How often the client asserts liveness. Comfortably under `SessionJanitor`'s
273
+ * `closeThresholdMinutes` (15 by default) so several pulses must be missed in a row before a
274
+ * live session is reaped, and well above `SessionManager`'s heartbeat write-coalescing window
275
+ * so the DB sees at most a trickle of writes per session.
276
+ */
277
+ static LivenessPulseMs = 60000;
262
278
  /**
263
279
  * Recording-relative ms offset at which the IN-FLIGHT (not-yet-finalized) turn's audio
264
280
  * actually BEGAN — captured the moment that turn's audio/text starts flowing (its first
@@ -269,6 +285,11 @@ export class RealtimeSessionService {
269
285
  * the post-gap turn at the pre-gap offset). See {@link markTurnAudioStart}.
270
286
  */
271
287
  currentTurnStartMs = null;
288
+ /**
289
+ * Wall-anchor of the SESSION clock (#3832): `performance.now()` at the moment the call went
290
+ * live, or `null` before any call has. Read only through {@link nowTurnOffsetMs}.
291
+ */
292
+ sessionClockStartMs = null;
272
293
  /**
273
294
  * Per-turn guard for {@link markTurnAudioStart}: `true` once the in-flight turn's audio-start
274
295
  * offset has been captured, so mid-turn interim deltas don't overwrite it. Reset to `false`
@@ -412,40 +433,96 @@ export class RealtimeSessionService {
412
433
  if (this.IsActive) {
413
434
  return; // a session is already running — ignore duplicate starts
414
435
  }
436
+ const consent = this.beginSessionStart({ agentName, recordingConsent, applicationId, appContext });
437
+ // Captured BEFORE startChannels so the mint carries exactly the snapshot the prologue
438
+ // resolved, whatever a channel plugin may push in the meantime.
439
+ const effectiveAppContext = this._appContext$.value;
440
+ let session;
441
+ try {
442
+ // Resolve + initialize the interactive-channel plugins FIRST: their client-executed
443
+ // tool sets must be declared to the realtime model at session mint.
444
+ const allClientTools = [...(clientTools ?? []), ...(await this.startChannels())];
445
+ session = await this.mintSession(targetAgentId, conversationId, lastSessionId, preferredModelId, allClientTools, coAgentId, configOverridesJson, consent, this.recordingStartedAtIso, mediaCollectionId, this.applicationId, effectiveAppContext);
446
+ }
447
+ catch (error) {
448
+ await this.failSessionStart(error);
449
+ return;
450
+ }
451
+ await this.runMintedSession(session, conversationId ?? null, consent);
452
+ }
453
+ /**
454
+ * Run a session the HOST has already minted itself — the second half of
455
+ * {@link StartRealtimeSession}, without the `StartRealtimeClientSession` mutation.
456
+ *
457
+ * For hosts that must mint through their own server surface because they attach per-session
458
+ * context the stock mutation cannot carry (e.g. an interview persona baked into the companion
459
+ * prompt). They call their own mutation, shape the reply into a
460
+ * {@link StartRealtimeClientSessionResult}, and hand it here: driver resolution, the ephemeral-token
461
+ * connect, tool/transcript relays, recording, connection state and teardown are all identical to
462
+ * the all-in-one path — there is exactly one implementation of the run half.
463
+ *
464
+ * NOTE: the interactive-channel plugins are NOT started on this path. Their tool sets must be
465
+ * declared to the model AT MINT, which happened on the host's side — so a host that wants channels
466
+ * owns that half too.
467
+ *
468
+ * @param result The minted session — the same ten fields the `StartRealtimeClientSession`
469
+ * mutation returns. `EphemeralToken` and `Provider` are what actually open the call.
470
+ * @param options Host-side inputs the result cannot carry; see {@link RealtimeSessionRunOptions}.
471
+ * Every field defaults exactly as its {@link StartRealtimeSession} counterpart does.
472
+ */
473
+ async StartRealtimeSessionFromResult(result, options) {
474
+ if (this.IsActive) {
475
+ return; // a session is already running — ignore duplicate starts
476
+ }
477
+ const effectiveOptions = options ?? {};
478
+ const consent = this.beginSessionStart(effectiveOptions);
479
+ await this.runMintedSession(result, effectiveOptions.conversationId ?? null, consent);
480
+ }
481
+ /**
482
+ * Start prologue shared by both entry points: bind the app layer, publish the agent name, reset
483
+ * per-session state, and flip the session live (which is ALSO what makes the `IsActive` guard
484
+ * suppress duplicate starts while the mint is still in flight — hence it runs before minting, not
485
+ * after). Returns the resolved recording consent, which the mint half reports to the server and
486
+ * the run half uses to decide whether to record.
487
+ */
488
+ beginSessionStart(options) {
415
489
  // App awareness (Move 1/3/4): the application the session runs in (sources the app config
416
490
  // cascade + RelevantAgents → allowed-agent union) and the live app-context snapshot injected
417
491
  // into the companion prompt at mint. Stored so the ClientContextChannel can stream subsequent
418
492
  // deltas. Absent ⇒ no app layer / no mint-time context (the pre-app behavior).
419
- this.applicationId = applicationId ?? null;
493
+ this.applicationId = options.applicationId ?? null;
420
494
  // Prefer the explicit param, but fall back to the snapshot the host has ALREADY pushed via
421
495
  // UpdateAppContext (explorer-app streams the live snapshot continuously). The overlay's
422
496
  // [appContext] binding can still read null at the instant the mic is clicked — without this
423
497
  // fallback, StartRealtimeSession(null) would clobber a perfectly good snapshot and mint the
424
498
  // companion prompt with no app context (no NavigableApps / no tool schemas → the co-agent guesses
425
499
  // parameter names and navigation fails). Never overwrite a good value with null.
426
- const effectiveAppContext = appContext ?? this._appContext$.value;
427
- this._appContext$.next(effectiveAppContext);
428
- if (agentName) {
429
- this._agentName$.next(agentName);
500
+ this._appContext$.next(options.appContext ?? this._appContext$.value);
501
+ if (options.agentName) {
502
+ this._agentName$.next(options.agentName);
430
503
  }
431
504
  this.resetState();
432
505
  this._active$.next(true);
433
506
  this._connectionState$.next('connecting');
434
507
  // Resolve recording consent for this session: explicit value wins, else the per-user
435
508
  // persisted preference. Computed before mint so it can be reported to the server.
436
- const consent = recordingConsent ?? this.readPersistedRecordingConsent();
509
+ const consent = options.recordingConsent ?? this.readPersistedRecordingConsent();
437
510
  this.recordingStartedAtIso = consent ? new Date().toISOString() : null;
511
+ return consent;
512
+ }
513
+ /**
514
+ * The RUN half of a session start, shared by both entry points: consume the minted result, open
515
+ * the provider connection, and go live. `inputConversationId` is the conversation the START asked
516
+ * for (null ⇒ "server, make me one") — the result alone can't distinguish the two.
517
+ */
518
+ async runMintedSession(session, inputConversationId, consent) {
438
519
  try {
439
- // Resolve + initialize the interactive-channel plugins FIRST: their client-executed
440
- // tool sets must be declared to the realtime model at session mint.
441
- const allClientTools = [...(clientTools ?? []), ...(await this.startChannels())];
442
- const session = await this.mintSession(targetAgentId, conversationId, lastSessionId, preferredModelId, allClientTools, coAgentId, configOverridesJson, consent, this.recordingStartedAtIso, mediaCollectionId, this.applicationId, effectiveAppContext);
443
520
  this.agentSessionId = session.AgentSessionId;
444
521
  // A null input conversationId means the SERVER created a fresh conversation for
445
522
  // this session — track it so the host can fold it into the cached list, select
446
523
  // it on close, and auto-name it (via the shared naming helper).
447
- this.createdConversationId = !conversationId && session.ConversationId ? session.ConversationId : null;
448
- this.sessionConversationId = session.ConversationId ?? conversationId ?? null;
524
+ this.createdConversationId = !inputConversationId && session.ConversationId ? session.ConversationId : null;
525
+ this.sessionConversationId = session.ConversationId ?? inputConversationId ?? null;
449
526
  this.firstUserTranscript = null;
450
527
  this.narrationTemplate = session.NarrationInstructionsTemplate ?? null;
451
528
  this._modelName$.next(session.ModelName ?? null);
@@ -462,6 +539,15 @@ export class RealtimeSessionService {
462
539
  // and never blocks the call. The remote stream may still be null here (the WebRTC
463
540
  // ontrack can land slightly after Connect resolves) — the recorder mixes the mic now
464
541
  // and the agent audio rides through whenever its track is already attached.
542
+ // The SESSION clock (#3832): anchored the moment the call goes live, whether or not a
543
+ // recording exists. When the recorder runs, per-turn timings use ITS clock (offsets into a
544
+ // seekable file); when it does not — every unconsented and every relay-captured session,
545
+ // which is 100% of turns measured across two databases — this is the fallback that stops
546
+ // `UtteranceStartMs`/`UtteranceEndMs` being categorically null. An offset into a session
547
+ // with no audio is not seekable, but it is orderable and displayable ("3:42 into the
548
+ // interview"), and it is stamped when the SPEECH happened rather than when the relay
549
+ // mutation landed — which no server-side backfill can ever recover.
550
+ this.sessionClockStartMs = performance.now();
465
551
  if (consent) {
466
552
  this.startRecording(client);
467
553
  }
@@ -476,13 +562,23 @@ export class RealtimeSessionService {
476
562
  sessionId: this.agentSessionId,
477
563
  channelNames: this._activeChannels$.value.map(c => c.ChannelName),
478
564
  });
565
+ // Same place, same reason: the session is connected and its id is known, which is exactly
566
+ // the window in which the server needs to be told it is alive.
567
+ this.startLivenessPulse();
479
568
  }
480
569
  catch (error) {
481
- console.error('[RealtimeSession] Failed to start session:', error);
482
- this._connectionState$.next('error');
483
- await this.teardown(false);
570
+ await this.failSessionStart(error);
484
571
  }
485
572
  }
573
+ /**
574
+ * The single failure path for a session start (mint half or run half): report it, latch the
575
+ * overlay into 'error', and unwind whatever the half-built session already opened.
576
+ */
577
+ async failSessionStart(error) {
578
+ console.error('[RealtimeSession] Failed to start session:', error);
579
+ this._connectionState$.next('error');
580
+ await this.teardown(false);
581
+ }
486
582
  /**
487
583
  * End the active session: stop the mic, tear down the provider connection, and close
488
584
  * the server-side agent session. Safe to call when no session is active.
@@ -556,6 +652,30 @@ export class RealtimeSessionService {
556
652
  }
557
653
  this.client.SendContextNote(trimmed);
558
654
  }
655
+ /**
656
+ * Asks the live model to SPEAK FIRST — before the human has said anything.
657
+ *
658
+ * Every other path into the model's voice reacts to something: the human spoke, or a channel
659
+ * reported input. A host that needs the agent to open the conversation (an interviewer greeting
660
+ * a candidate, a guide introducing a task) had no way to ask for that, so the session connected
661
+ * and both sides waited for the other. The instructions are what to say, in the host's words —
662
+ * the model still speaks in its own voice and persona.
663
+ *
664
+ * Returns whether the request was DELIVERED, which is the one way this deliberately differs from
665
+ * {@link SendContextNote} beside it. A context note that is dropped costs the model a little
666
+ * perception; an opening line that is dropped is a session that sits in silence, and the host
667
+ * needs to be able to tell the two apart. `false` means no session was live (or the instructions
668
+ * were empty) — usually a host that asked before the connection reached a speaking state, which
669
+ * it can then retry.
670
+ */
671
+ RequestSpokenOpening(instructions) {
672
+ const trimmed = instructions?.trim() ?? '';
673
+ if (trimmed.length === 0 || !this.client || !this.isSessionLive()) {
674
+ return false;
675
+ }
676
+ this.requestChannelSpokenResponse(trimmed);
677
+ return true;
678
+ }
559
679
  /**
560
680
  * The active client's current audio activity (per-direction RMS levels + spectrum
561
681
  * bins), or `null` when no session is live or the driver attached no audio meters.
@@ -596,6 +716,9 @@ export class RealtimeSessionService {
596
716
  // First turn's audio starts at ~0 (recording begins right as the call goes live). Seed it
597
717
  // here so the very first turn has a sane start even if its first interim is missed; later
598
718
  // turns re-stamp from where THEIR audio begins via markTurnAudioStart (handles tool gaps).
719
+ // Seeded even though the session clock may already have stamped a start: the clocks have
720
+ // different zeros, and a session-clock start carried into recorder-clock offsets would put
721
+ // turn one's cue wherever the clocks happen to differ.
599
722
  this.currentTurnStartMs = recorder.IsRecording ? 0 : null;
600
723
  this.turnAudioStartCaptured = false;
601
724
  if (this.recorder) {
@@ -623,6 +746,61 @@ export class RealtimeSessionService {
623
746
  this.segmentTimer = null;
624
747
  }
625
748
  }
749
+ /**
750
+ * Starts telling the server this session is still in use (#3533).
751
+ *
752
+ * **Why the server cannot work this out on its own.** In the client-direct topology the audio
753
+ * goes browser → provider over WebRTC. The server sees the mint, a few channel actions in the
754
+ * first seconds, and then nothing at all — so `SessionManager.RecordActivity` stops being
755
+ * reached while the conversation is still going. `LastActiveAt` freezes ~45 seconds in, and
756
+ * `SessionJanitor` — which cannot distinguish an active call from an abandoned one — force-closes
757
+ * it at `closeThresholdMinutes`, mid-sentence, taking the user's surfaces with it. A session
758
+ * whose channels are all client-side (whiteboard, media) goes quiet from the server's point of
759
+ * view almost immediately.
760
+ *
761
+ * The browser is the only participant that knows the call is alive, so it is the one that has to
762
+ * say so. Raising `closeThresholdMinutes` is not the fix — it just makes the janitor slower at
763
+ * its real job (reaping rows orphaned by a crash) without making liveness observable.
764
+ *
765
+ * The pulse is best-effort by design: a failed beat is logged and skipped, never surfaced to the
766
+ * user and never allowed to end the session. Losing one beat costs nothing because the threshold
767
+ * is many beats wide; turning a transient network blip into a visible error would be a worse
768
+ * failure than the one this fixes. Write amplification is bounded on the server side too, where
769
+ * `SessionManager.Heartbeat` coalesces persisted writes.
770
+ */
771
+ startLivenessPulse() {
772
+ this.stopLivenessPulse();
773
+ this.livenessTimer = setInterval(() => { void this.pulseLiveness(); }, RealtimeSessionService.LivenessPulseMs);
774
+ }
775
+ /** Stops the liveness pulse. Idempotent — safe on a session that never started one. */
776
+ stopLivenessPulse() {
777
+ if (this.livenessTimer) {
778
+ clearInterval(this.livenessTimer);
779
+ this.livenessTimer = null;
780
+ }
781
+ }
782
+ /**
783
+ * One liveness beat. Reads the session id at fire time rather than closing over it, so a beat
784
+ * that fires during teardown finds `null` and does nothing instead of resurrecting a closed row.
785
+ */
786
+ async pulseLiveness() {
787
+ const agentSessionId = this.agentSessionId;
788
+ if (!agentSessionId) {
789
+ return;
790
+ }
791
+ const mutation = `
792
+ mutation AgentSessionHeartbeat($agentSessionId: String!) {
793
+ AgentSessionHeartbeat(agentSessionId: $agentSessionId)
794
+ }
795
+ `;
796
+ try {
797
+ await this.gql().ExecuteGQL(mutation, { agentSessionId });
798
+ }
799
+ catch (error) {
800
+ // Best-effort: the next beat is 60s away and the janitor threshold is many beats wide.
801
+ console.warn('[RealtimeSession] Liveness pulse failed (session continues):', error);
802
+ }
803
+ }
626
804
  /**
627
805
  * Uploads the chunks captured since the last flush as one crash-recovery shard (durability only;
628
806
  * the canonical file is still the full upload at teardown). Best-effort — never disturbs the call.
@@ -1246,12 +1424,31 @@ export class RealtimeSessionService {
1246
1424
  * assistant answer, which always has interims.
1247
1425
  */
1248
1426
  markTurnAudioStart(kind) {
1249
- if (!this.recorder || this.turnAudioStartCaptured || kind === 'narration') {
1427
+ if (this.turnAudioStartCaptured || kind === 'narration') {
1428
+ return;
1429
+ }
1430
+ const offset = this.nowTurnOffsetMs();
1431
+ if (offset === null) {
1250
1432
  return;
1251
1433
  }
1252
- this.currentTurnStartMs = this.recorder.NowOffsetMs();
1434
+ this.currentTurnStartMs = offset;
1253
1435
  this.turnAudioStartCaptured = true;
1254
1436
  }
1437
+ /**
1438
+ * The current per-turn offset in ms — the RECORDER's clock when one runs (an offset into a
1439
+ * seekable file), else the SESSION clock (#3832: orderable and displayable, not seekable),
1440
+ * else `null` before any call is live. One function so the two stamp sites cannot disagree
1441
+ * about which clock a session is on.
1442
+ */
1443
+ nowTurnOffsetMs() {
1444
+ if (this.recorder) {
1445
+ return this.recorder.NowOffsetMs();
1446
+ }
1447
+ if (this.sessionClockStartMs !== null) {
1448
+ return Math.max(0, Math.round(performance.now() - this.sessionClockStartMs));
1449
+ }
1450
+ return null;
1451
+ }
1255
1452
  /**
1256
1453
  * Replaces the LAST caption of `role` in place (correction semantics); falls back to a
1257
1454
  * plain append when no such caption exists yet (e.g. the superseded turn predates this
@@ -1591,12 +1788,13 @@ export class RealtimeSessionService {
1591
1788
  if (!this.agentSessionId) {
1592
1789
  return;
1593
1790
  }
1594
- // Per-turn timing against the recording (when recording). `utteranceStartMs` is where this
1595
- // turn's audio actually began (captured by markTurnAudioStart on the first interim); the
1596
- // `?? 0` fallback covers a turn whose interim was missed / a final-only first turn.
1597
- const utteranceEndMs = this.recorder ? this.recorder.NowOffsetMs() : null;
1598
- const utteranceStartMs = this.recorder && !replacesPrevious ? (this.currentTurnStartMs ?? 0) : null;
1599
- if (this.recorder && !replacesPrevious) {
1791
+ // Per-turn timing against whichever clock the session is on (#3832): the recorder's when one
1792
+ // runs, else the session clock. `utteranceStartMs` is where this turn's audio actually began
1793
+ // (captured by markTurnAudioStart on the first interim); the `?? 0` fallback covers a turn
1794
+ // whose interim was missed / a final-only first turn.
1795
+ const utteranceEndMs = this.nowTurnOffsetMs();
1796
+ const utteranceStartMs = utteranceEndMs !== null && !replacesPrevious ? (this.currentTurnStartMs ?? 0) : null;
1797
+ if (utteranceEndMs !== null && !replacesPrevious) {
1600
1798
  // This turn is finalized — arm the NEXT turn to re-stamp its start from its own first
1601
1799
  // interim (handles a tool-call gap before the next turn). Stop inheriting this end as the
1602
1800
  // next start. `null` means "not yet captured"; relay falls back to `?? 0` if no interim fires.
@@ -1784,7 +1982,9 @@ export class RealtimeSessionService {
1784
1982
  routeScreencastFrame(frame) {
1785
1983
  for (const channel of this._activeChannels$.value) {
1786
1984
  if (channel.ChannelName === 'Remote Browser' && this.hasOnScreencastFrame(channel)) {
1787
- channel.OnScreencastFrame(frame.dataBase64);
1985
+ // The URL rides along so the channel can notice a page change nobody on this side caused —
1986
+ // under streaming the snapshot poll is stopped, and frames were pure pixels (#3496).
1987
+ channel.OnScreencastFrame(frame.dataBase64, frame.currentUrl ?? null);
1788
1988
  return;
1789
1989
  }
1790
1990
  }
@@ -1982,6 +2182,9 @@ export class RealtimeSessionService {
1982
2182
  * @param closeServerSession when true, calls `CloseAgentSession` on the server.
1983
2183
  */
1984
2184
  async teardown(closeServerSession) {
2185
+ // First: stop asserting liveness. A pulse racing the close would re-stamp LastActiveAt on a
2186
+ // session we are deliberately ending, leaving an Idle row the janitor then has to age out.
2187
+ this.stopLivenessPulse();
1985
2188
  this.teardownDelegationProgress();
1986
2189
  // Channels first: flush any unsaved channel state WHILE the live session id is still
1987
2190
  // set (the captured per-save id covers the race anyway), then dispose the plugins.