@memberjunction/ng-conversations 6.2.0 → 6.3.0-edge.0

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 (49) hide show
  1. package/README.md +2 -2
  2. package/dist/lib/components/collection/artifact-create-modal.component.js +4 -4
  3. package/dist/lib/components/collection/artifact-create-modal.component.js.map +1 -1
  4. package/dist/lib/components/collection/collection-form-modal.component.js +3 -3
  5. package/dist/lib/components/collection/collection-form-modal.component.js.map +1 -1
  6. package/dist/lib/components/collection/collections-full-view.component.js +1 -1
  7. package/dist/lib/components/collection/collections-full-view.component.js.map +1 -1
  8. package/dist/lib/components/conversation/conversation-chat-area.component.d.ts +42 -3
  9. package/dist/lib/components/conversation/conversation-chat-area.component.d.ts.map +1 -1
  10. package/dist/lib/components/conversation/conversation-chat-area.component.js +145 -23
  11. package/dist/lib/components/conversation/conversation-chat-area.component.js.map +1 -1
  12. package/dist/lib/components/conversation/conversation-list.component.d.ts +35 -1
  13. package/dist/lib/components/conversation/conversation-list.component.d.ts.map +1 -1
  14. package/dist/lib/components/conversation/conversation-list.component.js +65 -6
  15. package/dist/lib/components/conversation/conversation-list.component.js.map +1 -1
  16. package/dist/lib/components/conversation/conversation-remote-browser-controller.d.ts +11 -3
  17. package/dist/lib/components/conversation/conversation-remote-browser-controller.d.ts.map +1 -1
  18. package/dist/lib/components/conversation/conversation-remote-browser-controller.js +40 -4
  19. package/dist/lib/components/conversation/conversation-remote-browser-controller.js.map +1 -1
  20. package/dist/lib/components/realtime/channels/client-context-channel.d.ts +20 -4
  21. package/dist/lib/components/realtime/channels/client-context-channel.d.ts.map +1 -1
  22. package/dist/lib/components/realtime/channels/client-context-channel.js +62 -8
  23. package/dist/lib/components/realtime/channels/client-context-channel.js.map +1 -1
  24. package/dist/lib/components/realtime/remote-browser/remote-browser-tools.d.ts.map +1 -1
  25. package/dist/lib/components/realtime/remote-browser/remote-browser-tools.js +2 -2
  26. package/dist/lib/components/realtime/remote-browser/remote-browser-tools.js.map +1 -1
  27. package/dist/lib/components/sidebar/conversation-sidebar.component.d.ts +28 -1
  28. package/dist/lib/components/sidebar/conversation-sidebar.component.d.ts.map +1 -1
  29. package/dist/lib/components/sidebar/conversation-sidebar.component.js +51 -6
  30. package/dist/lib/components/sidebar/conversation-sidebar.component.js.map +1 -1
  31. package/dist/lib/events/chat-events.d.ts +45 -0
  32. package/dist/lib/events/chat-events.d.ts.map +1 -1
  33. package/dist/lib/events/chat-events.js +64 -0
  34. package/dist/lib/events/chat-events.js.map +1 -1
  35. package/dist/lib/services/realtime-audio-recorder.d.ts +10 -8
  36. package/dist/lib/services/realtime-audio-recorder.d.ts.map +1 -1
  37. package/dist/lib/services/realtime-audio-recorder.js +28 -12
  38. package/dist/lib/services/realtime-audio-recorder.js.map +1 -1
  39. package/dist/lib/services/realtime-session.service.d.ts +10 -3
  40. package/dist/lib/services/realtime-session.service.d.ts.map +1 -1
  41. package/dist/lib/services/realtime-session.service.js +8 -3
  42. package/dist/lib/services/realtime-session.service.js.map +1 -1
  43. package/dist/lib/services/search.service.js +1 -1
  44. package/dist/lib/services/search.service.js.map +1 -1
  45. package/dist/lib/utils/agent-artifact-summary.d.ts +1 -1
  46. package/dist/lib/utils/agent-artifact-summary.d.ts.map +1 -1
  47. package/dist/lib/utils/agent-artifact-summary.js +1 -1
  48. package/dist/lib/utils/agent-artifact-summary.js.map +1 -1
  49. package/package.json +36 -36
@@ -1 +1 @@
1
- {"version":3,"file":"chat-events.js","sourceRoot":"","sources":["../../../src/lib/events/chat-events.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAMH;;;;GAIG;AACH,MAAM,OAAO,wBAAwB;IAC1B,MAAM,GAAY,KAAK,CAAC;IACxB,YAAY,CAAU;CAChC;AAED,uEAAuE;AACvE,uBAAuB;AACvB,uEAAuE;AAEvE;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,OAAO,wBAAyB,SAAQ,wBAAwB;IAgB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IAEZ;IACA;IAFpB,YACoB,SAAiB,EACjB,YAA+B;QAD/B,cAAS,GAAT,SAAS,CAAQ;QACjB,iBAAY,GAAZ,YAAY,CAAmB;IAChD,CAAC;CACP;AAED;;;GAGG;AACH,MAAM,OAAO,mCAAmC;IAExB;IACA;IACA;IAHpB,YACoB,SAAiB,EACjB,WAAmB,EACnB,KAAwB;QAFxB,cAAS,GAAT,SAAS,CAAQ;QACjB,gBAAW,GAAX,WAAW,CAAQ;QACnB,UAAK,GAAL,KAAK,CAAmB;IACzC,CAAC;CACP;AAED;;;GAGG;AACH,MAAM,OAAO,qBAAqB;IAEV;IACA;IAFpB,YACoB,SAAiB,EACjB,MAAwB;QADxB,cAAS,GAAT,SAAS,CAAQ;QACjB,WAAM,GAAN,MAAM,CAAkB;IACzC,CAAC;CACP","sourcesContent":["/**\n * @fileoverview Before/After cancelable event argument classes for the\n * conversations widget.\n *\n * Follows MJ's established Before/After cancelable event pattern (see\n * `packages/Angular/Generic/trees/src/lib/events/tree-events.ts` and\n * `packages/Angular/Generic/base-forms/src/lib/types/form-events.ts`).\n *\n * **Contract:** Action events come as `Before*` / `After*` pairs. The\n * `Before*` event carries an args object extending {@link CancellableChatEventArgs}\n * with a `Cancel: boolean` property the listener can flip. The component\n * checks `if (event.Cancel) return;` before proceeding and emits the\n * corresponding `After*` only on the non-canceled path. Informational\n * events (progress, shown-notifications, session lifecycle) stay as single\n * emitters without a Before-pair.\n *\n * @module @memberjunction/ng-conversations\n */\n\nimport type { ExecuteAgentResult } from '@memberjunction/ai-core-plus';\nimport type { SessionEndReason } from '@memberjunction/conversations-runtime';\nimport type { AgentTurnInfo, AgentTurnRoute } from '../models/agent-turn.model';\n\n/**\n * Base class for cancelable chat events. Listeners flip `Cancel = true` to\n * halt the default behavior; the matching `After*` event will NOT fire.\n * The optional `CancelReason` is a free-form string for telemetry / debug.\n */\nexport class CancellableChatEventArgs {\n public Cancel: boolean = false;\n public CancelReason?: string;\n}\n\n// ────────────────────────────────────────────────────────────────────\n// Agent-turn lifecycle\n// ────────────────────────────────────────────────────────────────────\n\n/**\n * Fired once per agent turn, BEFORE any reply row exists: the person's message is saved and the\n * chat area has picked the agent that will answer it, on whichever route chose it (a tagged\n * agent, the last agent that answered, a pinned or host default agent, or the conversation\n * manager). A message that starts no turn (see `AgentReplyMode`) fires nothing.\n *\n * A listener can:\n * - cancel the turn (`Cancel = true`). Nothing more is written: no placeholder, no reply row,\n * and `AfterAgentTurn` does not fire. `CancelReason` is logged, not shown.\n * - send the turn to a different agent by setting {@link RedirectAgentId}. The agent must be\n * one the chat allows (`AllowedAgentIDs`); otherwise the turn is refused with a notice.\n *\n * Listeners run synchronously: the chat area reads `Cancel` and `RedirectAgentId` as soon as\n * `emit()` returns.\n *\n * Earlier releases fired this event only on the conversation-manager route, after that route's\n * placeholder row was saved, so a cancel left the row behind marked \"Turn canceled\".\n */\nexport class BeforeAgentTurnEventArgs extends CancellableChatEventArgs {\n /** The agent the turn resolved to. Null only when the args were built without turn details. */\n public readonly AgentId: string | null;\n /** The agent's name, when known. */\n public readonly AgentName: string | null;\n /** How the agent was chosen. */\n public readonly Route: AgentTurnRoute | null;\n /** The person's saved message the turn answers. */\n public readonly UserMessageId: string | null;\n /**\n * Set to send the turn to a different agent instead. Null (the default) keeps\n * {@link AgentId}. The turn then runs with `Route` `'Redirect'`.\n */\n public RedirectAgentId: string | null = null;\n\n constructor(\n public readonly ConversationId: string,\n public readonly MessageText: string,\n public readonly ApplicationId: string | null = null,\n turn: AgentTurnInfo | null = null\n ) {\n super();\n this.AgentId = turn?.AgentId ?? null;\n this.AgentName = turn?.AgentName ?? null;\n this.Route = turn?.Route ?? null;\n this.UserMessageId = turn?.UserMessageId ?? null;\n }\n}\n\n/**\n * Fired AFTER a successful agent turn, on every route. Carries the agent run id and the\n * underlying `ExecuteAgentResult`. NOT fired when the corresponding `BeforeAgentTurnEventArgs`\n * was canceled, when the turn failed, or when a host `AgentTurnHandler` reported no `Result`.\n */\nexport class AfterAgentTurnEventArgs {\n constructor(\n public readonly ConversationId: string,\n public readonly AgentRunId: string,\n public readonly Result: ExecuteAgentResult\n ) {}\n}\n\n// ────────────────────────────────────────────────────────────────────\n// Tool invocations\n// ────────────────────────────────────────────────────────────────────\n\n/**\n * Fired BEFORE the agent invokes a registered client tool. Listeners can veto\n * the dispatch by setting `event.Cancel = true` — `AgentClientSession`\n * short-circuits, the tool handler does NOT run, `afterToolInvoked` does NOT\n * fire, and the server receives a failure response carrying the optional\n * `CancelReason`.\n *\n * @example Confirm before a destructive tool runs\n * ```typescript\n * onBeforeToolInvoked(event: BeforeToolInvokedEventArgs) {\n * if (event.ToolName === 'deleteRecord') {\n * if (!confirm('Agent wants to delete a record. Allow?')) {\n * event.Cancel = true;\n * event.CancelReason = 'User declined deletion';\n * }\n * }\n * }\n * ```\n */\nexport class BeforeToolInvokedEventArgs extends CancellableChatEventArgs {\n constructor(\n public readonly ToolName: string,\n public readonly Args: unknown\n ) {\n super();\n }\n}\n\n/**\n * Fired AFTER a tool invocation completes. Carries the tool name, the\n * arguments it was called with, and the result it produced. NOT fired when\n * the corresponding `BeforeToolInvokedEventArgs` was canceled — the contract\n * is enforced in `AgentClientSession.handleToolRequest`.\n */\nexport class AfterToolInvokedEventArgs {\n constructor(\n public readonly ToolName: string,\n public readonly Args: unknown,\n public readonly Result: unknown\n ) {}\n}\n\n// ────────────────────────────────────────────────────────────────────\n// Response forms\n// ────────────────────────────────────────────────────────────────────\n\n/**\n * Fired BEFORE a response form's submitted values are sent back to the\n * agent. Listeners can cancel (e.g., a validation pass that blocks\n * submission until certain fields are populated).\n */\nexport class BeforeResponseFormSubmittedEventArgs extends CancellableChatEventArgs {\n constructor(\n public readonly FormId: string,\n public readonly Values: Record<string, unknown>\n ) {\n super();\n }\n}\n\n/**\n * Fired AFTER a response form's submitted values have been sent. NOT fired\n * when the corresponding `BeforeResponseFormSubmittedEventArgs` was\n * canceled.\n */\nexport class AfterResponseFormSubmittedEventArgs {\n constructor(\n public readonly FormId: string,\n public readonly Values: Record<string, unknown>\n ) {}\n}\n\n// ────────────────────────────────────────────────────────────────────\n// Stopping an in-progress agent run\n// ────────────────────────────────────────────────────────────────────\n\n/**\n * Fired BEFORE an in-progress agent run is stopped, when the person clicks Stop on the reply\n * the run is writing. Listeners can cancel (`Cancel = true`): nothing is written, the control\n * stays available, and `AfterStopClicked` does not fire. `AgentRunId` is null when the run\n * row has not been seen by the chat yet (the first moment after the reply placeholder appears);\n * the stop is then resolved by the reply's detail id.\n *\n * Listeners run synchronously: the message item reads `Cancel` as soon as `emit()` returns.\n */\nexport class BeforeStopClickedEventArgs extends CancellableChatEventArgs {\n constructor(\n public readonly ConversationDetailId: string,\n public readonly AgentRunId: string | null\n ) {\n super();\n }\n}\n\n/**\n * Fired AFTER a stop was attempted. `Stopped` is whether the run's row was marked Cancelled;\n * false means the run had already finished or the write was refused. NOT fired when the\n * corresponding `BeforeStopClickedEventArgs` was canceled.\n */\nexport class AfterStopClickedEventArgs {\n constructor(\n public readonly ConversationDetailId: string,\n public readonly AgentRunId: string | null,\n public readonly Stopped: boolean\n ) {}\n}\n\n// ────────────────────────────────────────────────────────────────────\n// Session lifecycle (informational — no Before-pair)\n// ────────────────────────────────────────────────────────────────────\n//\n// These re-broadcast the `SessionLifecycleEvent` variants from\n// `@memberjunction/conversations-runtime`'s `SessionsObserver`. State/Reason\n// union types are intentionally narrowed to what's distinguishable client-side\n// today — see the `ISessionsAdapter` JSDoc in the runtime package for the full\n// rationale (no per-channel `opening`/`closing` observable, server-only\n// `Janitor`/`Shutdown` reasons that never reach the browser).\n\n/**\n * Informational event — fired when a realtime session has fully started\n * (server-issued `sessionId` is set AND the realtime client is connected).\n * Cancellation of voice/realtime activity lives at the Sessions layer\n * (PR #2787), not here.\n */\nexport class SessionStartedEventArgs {\n constructor(\n public readonly SessionId: string,\n public readonly ChannelKinds: readonly string[]\n ) {}\n}\n\n/**\n * Informational. A channel inside a session opened or closed. Narrowed to\n * `open | closed` — see {@link SessionStartedEventArgs} module comment.\n */\nexport class SessionChannelStateChangedEventArgs {\n constructor(\n public readonly SessionId: string,\n public readonly ChannelKind: string,\n public readonly State: 'open' | 'closed'\n ) {}\n}\n\n/**\n * Informational. A session ended client-side. `Reason` is the runtime's\n * `SessionEndReason` — see {@link SessionStartedEventArgs} module comment.\n */\nexport class SessionEndedEventArgs {\n constructor(\n public readonly SessionId: string,\n public readonly Reason: SessionEndReason\n ) {}\n}\n"]}
1
+ {"version":3,"file":"chat-events.js","sourceRoot":"","sources":["../../../src/lib/events/chat-events.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAOH;;;;GAIG;AACH,MAAM,OAAO,wBAAwB;IAC1B,MAAM,GAAY,KAAK,CAAC;IACxB,YAAY,CAAU;CAChC;AAED,uEAAuE;AACvE,uBAAuB;AACvB,uEAAuE;AAEvE;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,OAAO,wBAAyB,SAAQ,wBAAwB;IAgB9C;IACA;IACA;IAjBpB,+FAA+F;IAC/E,OAAO,CAAgB;IACvC,oCAAoC;IACpB,SAAS,CAAgB;IACzC,gCAAgC;IAChB,KAAK,CAAwB;IAC7C,mDAAmD;IACnC,aAAa,CAAgB;IAC7C;;;OAGG;IACI,eAAe,GAAkB,IAAI,CAAC;IAE7C,YACoB,cAAsB,EACtB,WAAmB,EACnB,gBAA+B,IAAI,EACnD,OAA6B,IAAI;QAEjC,KAAK,EAAE,CAAC;QALQ,mBAAc,GAAd,cAAc,CAAQ;QACtB,gBAAW,GAAX,WAAW,CAAQ;QACnB,kBAAa,GAAb,aAAa,CAAsB;QAInD,IAAI,CAAC,OAAO,GAAG,IAAI,EAAE,OAAO,IAAI,IAAI,CAAC;QACrC,IAAI,CAAC,SAAS,GAAG,IAAI,EAAE,SAAS,IAAI,IAAI,CAAC;QACzC,IAAI,CAAC,KAAK,GAAG,IAAI,EAAE,KAAK,IAAI,IAAI,CAAC;QACjC,IAAI,CAAC,aAAa,GAA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B,YAA4B,OAAwB;QAChD,KAAK,EAAE,CAAC;QADgB,YAAO,GAAP,OAAO,CAAiB;IAEpD,CAAC;CACJ;AAED;;;GAGG;AACH,MAAM,OAAO,wBAAwB;IACL;IAA5B,YAA4B,OAAwB;QAAxB,YAAO,GAAP,OAAO,CAAiB;IAAG,CAAC;CAC3D;AAED,uEAAuE;AACvE,yBAAyB;AACzB,uEAAuE;AAEvE;;;;;;;GAOG;AACH,MAAM,OAAO,gCAAiC,SAAQ,wBAAwB;IAEtD;IACA;IACA;IAHpB,YACoB,UAAkB,EAClB,aAAsB,EACtB,SAAkB;QAElC,KAAK,EAAE,CAAC;QAJQ,eAAU,GAAV,UAAU,CAAQ;QAClB,kBAAa,GAAb,aAAa,CAAS;QACtB,cAAS,GAAT,SAAS,CAAS;IAGtC,CAAC;CACJ;AAED;;;GAGG;AACH,MAAM,OAAO,+BAA+B;IAEpB;IACA;IACA;IAHpB,YACoB,UAAkB,EAClB,aAAsB,EACtB,SAAkB;QAFlB,eAAU,GAAV,UAAU,CAAQ;QAClB,kBAAa,GAAb,aAAa,CAAS;QACtB,cAAS,GAAT,SAAS,CAAS;IACnC,CAAC;CACP","sourcesContent":["/**\n * @fileoverview Before/After cancelable event argument classes for the\n * conversations widget.\n *\n * Follows MJ's established Before/After cancelable event pattern (see\n * `packages/Angular/Generic/trees/src/lib/events/tree-events.ts` and\n * `packages/Angular/Generic/base-forms/src/lib/types/form-events.ts`).\n *\n * **Contract:** Action events come as `Before*` / `After*` pairs. The\n * `Before*` event carries an args object extending {@link CancellableChatEventArgs}\n * with a `Cancel: boolean` property the listener can flip. The component\n * checks `if (event.Cancel) return;` before proceeding and emits the\n * corresponding `After*` only on the non-canceled path. Informational\n * events (progress, shown-notifications, session lifecycle) stay as single\n * emitters without a Before-pair.\n *\n * @module @memberjunction/ng-conversations\n */\n\nimport type { ExecuteAgentResult } from '@memberjunction/ai-core-plus';\nimport type { SessionEndReason } from '@memberjunction/conversations-runtime';\nimport type { MJProjectEntity } from '@memberjunction/core-entities';\nimport type { AgentTurnInfo, AgentTurnRoute } from '../models/agent-turn.model';\n\n/**\n * Base class for cancelable chat events. Listeners flip `Cancel = true` to\n * halt the default behavior; the matching `After*` event will NOT fire.\n * The optional `CancelReason` is a free-form string for telemetry / debug.\n */\nexport class CancellableChatEventArgs {\n public Cancel: boolean = false;\n public CancelReason?: string;\n}\n\n// ────────────────────────────────────────────────────────────────────\n// Agent-turn lifecycle\n// ────────────────────────────────────────────────────────────────────\n\n/**\n * Fired once per agent turn, BEFORE any reply row exists: the person's message is saved and the\n * chat area has picked the agent that will answer it, on whichever route chose it (a tagged\n * agent, the last agent that answered, a pinned or host default agent, or the conversation\n * manager). A message that starts no turn (see `AgentReplyMode`) fires nothing.\n *\n * A listener can:\n * - cancel the turn (`Cancel = true`). Nothing more is written: no placeholder, no reply row,\n * and `AfterAgentTurn` does not fire. `CancelReason` is logged, not shown.\n * - send the turn to a different agent by setting {@link RedirectAgentId}. The agent must be\n * one the chat allows (`AllowedAgentIDs`); otherwise the turn is refused with a notice.\n *\n * Listeners run synchronously: the chat area reads `Cancel` and `RedirectAgentId` as soon as\n * `emit()` returns.\n *\n * Earlier releases fired this event only on the conversation-manager route, after that route's\n * placeholder row was saved, so a cancel left the row behind marked \"Turn canceled\".\n */\nexport class BeforeAgentTurnEventArgs extends CancellableChatEventArgs {\n /** The agent the turn resolved to. Null only when the args were built without turn details. */\n public readonly AgentId: string | null;\n /** The agent's name, when known. */\n public readonly AgentName: string | null;\n /** How the agent was chosen. */\n public readonly Route: AgentTurnRoute | null;\n /** The person's saved message the turn answers. */\n public readonly UserMessageId: string | null;\n /**\n * Set to send the turn to a different agent instead. Null (the default) keeps\n * {@link AgentId}. The turn then runs with `Route` `'Redirect'`.\n */\n public RedirectAgentId: string | null = null;\n\n constructor(\n public readonly ConversationId: string,\n public readonly MessageText: string,\n public readonly ApplicationId: string | null = null,\n turn: AgentTurnInfo | null = null\n ) {\n super();\n this.AgentId = turn?.AgentId ?? null;\n this.AgentName = turn?.AgentName ?? null;\n this.Route = turn?.Route ?? null;\n this.UserMessageId = turn?.UserMessageId ?? null;\n }\n}\n\n/**\n * Fired AFTER a successful agent turn, on every route. Carries the agent run id and the\n * underlying `ExecuteAgentResult`. NOT fired when the corresponding `BeforeAgentTurnEventArgs`\n * was canceled, when the turn failed, or when a host `AgentTurnHandler` reported no `Result`.\n */\nexport class AfterAgentTurnEventArgs {\n constructor(\n public readonly ConversationId: string,\n public readonly AgentRunId: string,\n public readonly Result: ExecuteAgentResult\n ) {}\n}\n\n// ────────────────────────────────────────────────────────────────────\n// Tool invocations\n// ────────────────────────────────────────────────────────────────────\n\n/**\n * Fired BEFORE the agent invokes a registered client tool. Listeners can veto\n * the dispatch by setting `event.Cancel = true` — `AgentClientSession`\n * short-circuits, the tool handler does NOT run, `afterToolInvoked` does NOT\n * fire, and the server receives a failure response carrying the optional\n * `CancelReason`.\n *\n * @example Confirm before a destructive tool runs\n * ```typescript\n * onBeforeToolInvoked(event: BeforeToolInvokedEventArgs) {\n * if (event.ToolName === 'deleteRecord') {\n * if (!confirm('Agent wants to delete a record. Allow?')) {\n * event.Cancel = true;\n * event.CancelReason = 'User declined deletion';\n * }\n * }\n * }\n * ```\n */\nexport class BeforeToolInvokedEventArgs extends CancellableChatEventArgs {\n constructor(\n public readonly ToolName: string,\n public readonly Args: unknown\n ) {\n super();\n }\n}\n\n/**\n * Fired AFTER a tool invocation completes. Carries the tool name, the\n * arguments it was called with, and the result it produced. NOT fired when\n * the corresponding `BeforeToolInvokedEventArgs` was canceled — the contract\n * is enforced in `AgentClientSession.handleToolRequest`.\n */\nexport class AfterToolInvokedEventArgs {\n constructor(\n public readonly ToolName: string,\n public readonly Args: unknown,\n public readonly Result: unknown\n ) {}\n}\n\n// ────────────────────────────────────────────────────────────────────\n// Response forms\n// ────────────────────────────────────────────────────────────────────\n\n/**\n * Fired BEFORE a response form's submitted values are sent back to the\n * agent. Listeners can cancel (e.g., a validation pass that blocks\n * submission until certain fields are populated).\n */\nexport class BeforeResponseFormSubmittedEventArgs extends CancellableChatEventArgs {\n constructor(\n public readonly FormId: string,\n public readonly Values: Record<string, unknown>\n ) {\n super();\n }\n}\n\n/**\n * Fired AFTER a response form's submitted values have been sent. NOT fired\n * when the corresponding `BeforeResponseFormSubmittedEventArgs` was\n * canceled.\n */\nexport class AfterResponseFormSubmittedEventArgs {\n constructor(\n public readonly FormId: string,\n public readonly Values: Record<string, unknown>\n ) {}\n}\n\n// ────────────────────────────────────────────────────────────────────\n// Stopping an in-progress agent run\n// ────────────────────────────────────────────────────────────────────\n\n/**\n * Fired BEFORE an in-progress agent run is stopped, when the person clicks Stop on the reply\n * the run is writing. Listeners can cancel (`Cancel = true`): nothing is written, the control\n * stays available, and `AfterStopClicked` does not fire. `AgentRunId` is null when the run\n * row has not been seen by the chat yet (the first moment after the reply placeholder appears);\n * the stop is then resolved by the reply's detail id.\n *\n * Listeners run synchronously: the message item reads `Cancel` as soon as `emit()` returns.\n */\nexport class BeforeStopClickedEventArgs extends CancellableChatEventArgs {\n constructor(\n public readonly ConversationDetailId: string,\n public readonly AgentRunId: string | null\n ) {\n super();\n }\n}\n\n/**\n * Fired AFTER a stop was attempted. `Stopped` is whether the run's row was marked Cancelled;\n * false means the run had already finished or the write was refused. NOT fired when the\n * corresponding `BeforeStopClickedEventArgs` was canceled.\n */\nexport class AfterStopClickedEventArgs {\n constructor(\n public readonly ConversationDetailId: string,\n public readonly AgentRunId: string | null,\n public readonly Stopped: boolean\n ) {}\n}\n\n// ────────────────────────────────────────────────────────────────────\n// Session lifecycle (informational — no Before-pair)\n// ────────────────────────────────────────────────────────────────────\n//\n// These re-broadcast the `SessionLifecycleEvent` variants from\n// `@memberjunction/conversations-runtime`'s `SessionsObserver`. State/Reason\n// union types are intentionally narrowed to what's distinguishable client-side\n// today — see the `ISessionsAdapter` JSDoc in the runtime package for the full\n// rationale (no per-channel `opening`/`closing` observable, server-only\n// `Janitor`/`Shutdown` reasons that never reach the browser).\n\n/**\n * Informational event — fired when a realtime session has fully started\n * (server-issued `sessionId` is set AND the realtime client is connected).\n * Cancellation of voice/realtime activity lives at the Sessions layer\n * (PR #2787), not here.\n */\nexport class SessionStartedEventArgs {\n constructor(\n public readonly SessionId: string,\n public readonly ChannelKinds: readonly string[]\n ) {}\n}\n\n/**\n * Informational. A channel inside a session opened or closed. Narrowed to\n * `open | closed` — see {@link SessionStartedEventArgs} module comment.\n */\nexport class SessionChannelStateChangedEventArgs {\n constructor(\n public readonly SessionId: string,\n public readonly ChannelKind: string,\n public readonly State: 'open' | 'closed'\n ) {}\n}\n\n/**\n * Informational. A session ended client-side. `Reason` is the runtime's\n * `SessionEndReason` — see {@link SessionStartedEventArgs} module comment.\n */\nexport class SessionEndedEventArgs {\n constructor(\n public readonly SessionId: string,\n public readonly Reason: SessionEndReason\n ) {}\n}\n\n// ────────────────────────────────────────────────────────────────────\n// Folder / Project editing\n// ────────────────────────────────────────────────────────────────────\n\n/**\n * Fired BEFORE a folder's edit/rename modal is opened from the conversation list.\n * Listeners can cancel (`Cancel = true`) to open their own custom folder/project\n * editor instead of MJ's built-in `ProjectFormModalComponent`; `AfterFolderEdit`\n * then does not fire.\n *\n * Listeners run synchronously: `EditFolder()` reads `Cancel` as soon as `emit()` returns.\n */\nexport class BeforeFolderEditEventArgs extends CancellableChatEventArgs {\n constructor(public readonly Project: MJProjectEntity) {\n super();\n }\n}\n\n/**\n * Fired AFTER a folder's edits are saved through the built-in modal.\n * NOT fired when `BeforeFolderEditEventArgs` was canceled or the modal was dismissed without saving.\n */\nexport class AfterFolderEditEventArgs {\n constructor(public readonly Project: MJProjectEntity) {}\n}\n\n// ────────────────────────────────────────────────────────────────────\n// Artifact panel opening\n// ────────────────────────────────────────────────────────────────────\n\n/**\n * Fired BEFORE the chat area opens its built-in right-hand artifact viewer drawer.\n * Listeners can cancel (`Cancel = true`) to open the artifact in a host-managed\n * workspace drawer or surface instead; `ShowArtifactPanel` stays unchanged and\n * `AfterArtifactPanelOpen` does not fire.\n *\n * Listeners run synchronously: the chat area reads `Cancel` as soon as `emit()` returns.\n */\nexport class BeforeArtifactPanelOpenEventArgs extends CancellableChatEventArgs {\n constructor(\n public readonly ArtifactId: string,\n public readonly VersionNumber?: number,\n public readonly VersionId?: string\n ) {\n super();\n }\n}\n\n/**\n * Fired AFTER the chat area opens its built-in artifact viewer drawer.\n * NOT fired when `BeforeArtifactPanelOpenEventArgs` was canceled.\n */\nexport class AfterArtifactPanelOpenEventArgs {\n constructor(\n public readonly ArtifactId: string,\n public readonly VersionNumber?: number,\n public readonly VersionId?: string\n ) {}\n}\n\n"]}
@@ -49,7 +49,11 @@ export declare class RealtimeAudioRecorder implements IRealtimeSessionRecorder {
49
49
  /** Converts the context's rate to 48 kHz; `null` when the context already runs at 48 kHz. */
50
50
  private resampler;
51
51
  private recording;
52
- /** True once the agent's remote stream has been wired into the mix (prevents double-attach). */
52
+ /** The agent's remote stream currently wired into the mix (prevents duplicate attach of the same stream). */
53
+ private remoteStream;
54
+ /** The source node reading the agent's remote stream, replaced on mid-call WebRTC reconnect. */
55
+ private remoteSource;
56
+ /** True while a remote stream is wired into the active mix graph. */
53
57
  private remoteAttached;
54
58
  /** A remote stream handed to AttachRemoteStream before the audio graph was ready; wired at setup. */
55
59
  private pendingRemoteStream;
@@ -90,10 +94,9 @@ export declare class RealtimeAudioRecorder implements IRealtimeSessionRecorder {
90
94
  */
91
95
  Start(micStream: MediaStream, remoteStream: MediaStream | null): void;
92
96
  /**
93
- * Wires the agent's remote-audio stream into the live mix once it arrives. The WebRTC
94
- * `ontrack` that delivers the agent voice usually lands AFTER recording has already begun
95
- * (mic-only), so the session attaches it here when it lands. Idempotent, and safe to call
96
- * before the audio graph finishes its async setup (the stream is connected once ready).
97
+ * Wires the agent's remote-audio stream into the live mix once it arrives, or replaces the
98
+ * previous remote-audio stream when a WebRTC transport reconnects mid-call. Idempotent for the
99
+ * same `MediaStream` instance, and safe to call before the audio graph finishes its async setup.
97
100
  */
98
101
  AttachRemoteStream(stream: MediaStream): void;
99
102
  /**
@@ -135,10 +138,9 @@ export declare class RealtimeAudioRecorder implements IRealtimeSessionRecorder {
135
138
  */
136
139
  private createAudioContext;
137
140
  /**
138
- * Connects the agent stream, degrading to mic-only on failure. Unlike the mic (whose failure
139
- * rightly disables the recorder), the agent stream is best-effort: a browser may reject it
141
+ * Connects (or replaces) the agent stream, degrading to mic-only on failure. Unlike the mic (whose
142
+ * failure rightly disables the recorder), the agent stream is best-effort: a browser may reject it
140
143
  * (cross-sample-rate `NotSupportedError`) and that must not discard the user's recording.
141
- * Returns whether it was connected, so the caller only marks it attached on success.
142
144
  */
143
145
  private connectRemoteStream;
144
146
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"realtime-audio-recorder.d.ts","sourceRoot":"","sources":["../../../src/lib/services/realtime-audio-recorder.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,wBAAwB,EAAE,MAAM,kCAAkC,CAAC;AAE5E,OAAO,EAAE,kBAAkB,EAA2B,MAAM,iCAAiC,CAAC;AAE9F;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,qBAAa,qBAAsB,YAAW,wBAAwB;IA+DtD,OAAO,CAAC,QAAQ,CAAC,aAAa;IA9D1C,mGAAmG;IACnG,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,yBAAyB,CAAQ;IACzD;;;;OAIG;IACH,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,iBAAiB,CAA8B;IACvE,kGAAkG;IAClG,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,sBAAsB,CAY5C;IAEF,OAAO,CAAC,YAAY,CAA6B;IACjD,OAAO,CAAC,WAAW,CAAgD;IACnE,OAAO,CAAC,WAAW,CAAiC;IACpD,OAAO,CAAC,UAAU,CAAoC;IACtD,6FAA6F;IAC7F,OAAO,CAAC,SAAS,CAAgC;IACjD,OAAO,CAAC,SAAS,CAAS;IAE1B,gGAAgG;IAChG,OAAO,CAAC,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lC,sFAAsF;IACtF,OAAO,CAAC,yBAAyB;IAWjC,qFAAqF;IACrF,OAAO,CAAC,WAAW;IAInB;;;;;;;;OAQG;IACH,OAAO,CAAC,YAAY;IAwBpB,qHAAqH;IACrH,OAAO,CAAC,aAAa;IAUrB;;;OAGG;IACH,OAAO,CAAC,OAAO;IAKf,0GAA0G;IAC1G,OAAO,CAAC,YAAY;IA6BpB,OAAO,CAAC,cAAc;IAStB,OAAO,CAAC,YAAY;CAMvB"}
@@ -62,7 +62,11 @@ export class RealtimeAudioRecorder {
62
62
  /** Converts the context's rate to 48 kHz; `null` when the context already runs at 48 kHz. */
63
63
  resampler = null;
64
64
  recording = false;
65
- /** True once the agent's remote stream has been wired into the mix (prevents double-attach). */
65
+ /** The agent's remote stream currently wired into the mix (prevents duplicate attach of the same stream). */
66
+ remoteStream = null;
67
+ /** The source node reading the agent's remote stream, replaced on mid-call WebRTC reconnect. */
68
+ remoteSource = null;
69
+ /** True while a remote stream is wired into the active mix graph. */
66
70
  remoteAttached = false;
67
71
  /** A remote stream handed to AttachRemoteStream before the audio graph was ready; wired at setup. */
68
72
  pendingRemoteStream = null;
@@ -129,17 +133,16 @@ export class RealtimeAudioRecorder {
129
133
  });
130
134
  }
131
135
  /**
132
- * Wires the agent's remote-audio stream into the live mix once it arrives. The WebRTC
133
- * `ontrack` that delivers the agent voice usually lands AFTER recording has already begun
134
- * (mic-only), so the session attaches it here when it lands. Idempotent, and safe to call
135
- * before the audio graph finishes its async setup (the stream is connected once ready).
136
+ * Wires the agent's remote-audio stream into the live mix once it arrives, or replaces the
137
+ * previous remote-audio stream when a WebRTC transport reconnects mid-call. Idempotent for the
138
+ * same `MediaStream` instance, and safe to call before the audio graph finishes its async setup.
136
139
  */
137
140
  AttachRemoteStream(stream) {
138
- if (this.remoteAttached || stream.getAudioTracks().length === 0) {
141
+ if (this.remoteStream === stream || stream.getAudioTracks().length === 0) {
139
142
  return;
140
143
  }
141
144
  if (this.audioContext && this.captureNode()) {
142
- this.remoteAttached = this.connectRemoteStream(this.audioContext, stream);
145
+ this.connectRemoteStream(this.audioContext, stream);
143
146
  }
144
147
  else {
145
148
  // Audio-graph setup still in flight (awaiting resume / worklet load) — connect at setup.
@@ -284,7 +287,7 @@ export class RealtimeAudioRecorder {
284
287
  const remote = remoteStream ?? this.pendingRemoteStream;
285
288
  this.pendingRemoteStream = null;
286
289
  if (remote && remote.getAudioTracks().length > 0) {
287
- this.remoteAttached = this.connectRemoteStream(audioContext, remote);
290
+ this.connectRemoteStream(audioContext, remote);
288
291
  }
289
292
  return 'done';
290
293
  }
@@ -305,14 +308,22 @@ export class RealtimeAudioRecorder {
305
308
  return new AudioContext();
306
309
  }
307
310
  /**
308
- * Connects the agent stream, degrading to mic-only on failure. Unlike the mic (whose failure
309
- * rightly disables the recorder), the agent stream is best-effort: a browser may reject it
311
+ * Connects (or replaces) the agent stream, degrading to mic-only on failure. Unlike the mic (whose
312
+ * failure rightly disables the recorder), the agent stream is best-effort: a browser may reject it
310
313
  * (cross-sample-rate `NotSupportedError`) and that must not discard the user's recording.
311
- * Returns whether it was connected, so the caller only marks it attached on success.
312
314
  */
313
315
  connectRemoteStream(audioContext, stream) {
314
316
  try {
315
- this.connectStream(audioContext, stream);
317
+ const replacement = this.connectStream(audioContext, stream);
318
+ if (!replacement) {
319
+ return false;
320
+ }
321
+ if (this.remoteSource) {
322
+ this.disconnectNode(this.remoteSource);
323
+ }
324
+ this.remoteSource = replacement;
325
+ this.remoteStream = stream;
326
+ this.remoteAttached = true;
316
327
  return true;
317
328
  }
318
329
  catch (error) {
@@ -426,6 +437,11 @@ export class RealtimeAudioRecorder {
426
437
  /** Releases the audio graph + capture node. Idempotent; leaves the encoder and the sample count alone. */
427
438
  releaseGraph() {
428
439
  this.setupGeneration++;
440
+ if (this.remoteSource) {
441
+ this.disconnectNode(this.remoteSource);
442
+ this.remoteSource = null;
443
+ }
444
+ this.remoteStream = null;
429
445
  this.remoteAttached = false;
430
446
  this.pendingRemoteStream = null;
431
447
  this.micStream = null;
@@ -1 +1 @@
1
- {"version":3,"file":"realtime-audio-recorder.js","sourceRoot":"","sources":["../../../src/lib/services/realtime-audio-recorder.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AAErE,OAAO,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAC;AAC/D,OAAO,EAAsB,uBAAuB,EAAE,MAAM,iCAAiC,CAAC;AAE9F;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,MAAM,OAAO,qBAAqB;IA+DD;IA9D7B,mGAAmG;IAC3F,MAAM,CAAU,yBAAyB,GAAG,IAAI,CAAC;IACzD;;;;OAIG;IACK,MAAM,CAAU,iBAAiB,GAAG,EAAE,GAAG,qBAAqB,CAAC;IACvE,kGAAkG;IAC1F,MAAM,CAAU,sBAAsB,GAAG;;;;;;;;;;;;KAYhD,CAAC;IAEM,YAAY,GAAwB,IAAI,CAAC;IACzC,WAAW,GAA2C,IAAI,CAAC;IAC3D,WAAW,GAA4B,IAAI,CAAC;IAC5C,UAAU,GAA+B,IAAI,CAAC;IACtD,6FAA6F;IACrF,SAAS,GAA2B,IAAI,CAAC;IACzC,SAAS,GAAG,KAAK,CAAC;IAE1B,gGAAgG;IACxF,cAAc,GAAG,KAAK,CAAC;IAC/B,qGAAqG;IAC7F,mBAAmB,GAAuB,IAAI,CAAC;IACvD,0GAA0G;IAClG,SAAS,GAAuB,IAAI,CAAC;IAC7C,4EAA4E;IACpE,SAAS,GAAsC,IAAI,CAAC;IAE5D,uEAAuE;IAC/D,eAAe,GAAG,CAAC,CAAC;IAC5B,wGAAwG;IAChG,OAAO,GAA8B,IAAI,CAAC;IAClD,4GAA4G;IACpG,YAAY,GAA8C,IAAI,CAAC;IACvE,0FAA0F;IAClF,aAAa,GAAmB,EAAE,CAAC;IACnC,cAAc,GAAG,CAAC,CAAC;IACnB,qBAAqB,GAAG,KAAK,CAAC;IACtC,oEAAoE;IAC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D,IAAI,CAAC,UAAU,EAAE,CAAC;QACtB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,6FAA6F;YAC7F,OAAO,CAAC,KAAK,CAAC,0DAA0D,EAAE,KAAK,CAAC,CAAC;QACrF,CAAC;IACL,CAAC;IAEO,YAAY,CAAC,YAA0B;QAC3C,KAAK,YAAY,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;YAC/C,mFAAmF;YACnF,OAAO,CAAC,KAAK,CAAC,qDAAqD,EAAE,KAAK,CAAC,CAAC;QAChF,CAAC,CAAC,CAAC;IACP,CAAC","sourcesContent":["import { RECORDING_SAMPLE_RATE } from '@memberjunction/ai-core-plus';\nimport { IRealtimeSessionRecorder } from '@memberjunction/realtime-runtime';\nimport { LinearResampler } from './recording/linear-resampler';\nimport { IOpusPacketEncoder, SelectOpusPacketEncoder } from './recording/opus-packet-encoder';\n\n/**\n * Browser-side audio recorder for a CLIENT-DIRECT realtime voice session, implementing the\n * runtime's {@link IRealtimeSessionRecorder} contract directly.\n *\n * Mixes the user's microphone with the agent's remote-audio stream (every driver exposes one via\n * `GetRemoteMediaStream()`: WebRTC drivers publish their remote track, PCM drivers — Gemini,\n * ElevenLabs, AssemblyAI, xAI, HuggingFace — publish their playout engine's output) in a Web Audio\n * graph, captures the mix as mono Float32 frames through an {@link AudioWorkletNode} (preferred) or a\n * {@link ScriptProcessorNode} (fallback), and feeds them to ONE continuous Opus encoder for the whole\n * call. The runtime pulls the encoded packets with {@link TakeEncodedPackets}, cuts them into shards\n * and uploads them as the call goes, so nothing is held in memory until the end.\n *\n * Timing is the 48 kHz sample clock: the graph asks for a 48 kHz context, and when the browser\n * refuses (or reports another rate) every frame is resampled to 48 kHz before encoding. The\n * captured-sample count drives {@link NowOffsetMs} and is what {@link Stop} resolves.\n *\n * Robust by design — every step degrades gracefully:\n * - No `AudioContext` (server-side render / unsupported env) → the recorder disables itself\n * ({@link IsRecording} stays `false`, {@link Stop} resolves 0); the voice call proceeds.\n * - No `AudioWorkletNode` AND no `ScriptProcessorNode` → disables itself rather than throwing.\n * - A forced-48 kHz context that cannot take the microphone (Firefox rejects a source whose rate\n * differs from its context's) → rebuilt once at the device rate with resampling.\n * - No remote stream yet (e.g. the WebRTC track hasn't landed) → records mic only until it does.\n * - A remote stream that can't be connected (e.g. a cross-sample-rate `createMediaStreamSource`\n * rejection) → warns and records mic only; the mic recording is never lost to the agent stream.\n * - No usable encoder → logged, recording disabled for the call.\n *\n * Not an Angular service: it owns transient per-session media plumbing the runtime creates and\n * discards per call, so a plain class is the right shape (no DI, no singleton).\n */\nexport class RealtimeAudioRecorder implements IRealtimeSessionRecorder {\n /** PCM frame size for the ScriptProcessor fallback (worklet uses its native 128-frame quantum). */\n private static readonly scriptProcessorBufferSize = 4096;\n /**\n * Most 48 kHz audio held while the encoder is still being selected / loaded (10 s). Selection is\n * normally well under a second; past this the encoder is stuck, and later frames are dropped\n * (see {@link captureFrame} for why they are not counted either).\n */\n private static readonly maxPendingSamples = 10 * RECORDING_SAMPLE_RATE;\n /** Inline AudioWorklet processor: forwards each 128-frame mono input block to the main thread. */\n private static readonly workletProcessorSource = `\n class MJPcmCaptureProcessor extends AudioWorkletProcessor {\n process(inputs) {\n const input = inputs[0];\n if (input && input[0] && input[0].length > 0) {\n // Copy out of the reused worklet buffer before posting.\n this.port.postMessage(input[0].slice(0));\n }\n return true;\n }\n }\n registerProcessor('mj-pcm-capture', MJPcmCaptureProcessor);\n `;\n\n private audioContext: AudioContext | null = null;\n private destination: MediaStreamAudioDestinationNode | null = null;\n private workletNode: AudioWorkletNode | null = null;\n private scriptNode: ScriptProcessorNode | null = null;\n /** Converts the context's rate to 48 kHz; `null` when the context already runs at 48 kHz. */\n private resampler: LinearResampler | null = null;\n private recording = false;\n\n /** True once the agent's remote stream has been wired into the mix (prevents double-attach). */\n private remoteAttached = false;\n /** A remote stream handed to AttachRemoteStream before the audio graph was ready; wired at setup. */\n private pendingRemoteStream: MediaStream | null = null;\n /** The microphone to record: the latest stream given to Start or ReplaceMicrophone. Setup connects it. */\n private micStream: MediaStream | null = null;\n /** The source node reading the microphone, swapped by ReplaceMicrophone. */\n private micSource: MediaStreamAudioSourceNode | null = null;\n\n /** 48 kHz samples captured (post-resample) — the recording's clock. */\n private capturedSamples = 0;\n /** The call's encoder once selected; `null` while selecting, after a failure, or when not recording. */\n private encoder: IOpusPacketEncoder | null = null;\n /** Resolves to the encoder (or `null` on failure) — Stop awaits it so buffered audio still gets encoded. */\n private encoderReady: Promise<IOpusPacketEncoder | null> | null = null;\n /** 48 kHz frames captured before the encoder was ready, fed to it in order once it is. */\n private pendingFrames: Float32Array[] = [];\n private pendingSamples = 0;\n private pendingOverflowWarned = false;\n /** The first Stop's promise; later calls return it (idempotent). */\n private stopping: Promise<number> | null = null;\n\n /**\n * Bumped whenever the audio graph is released. The async graph setup snapshots it and, after each\n * await, gives up if it moved: a {@link Stop} that lands mid-setup can only release what setup has\n * already published, so setup must release the rest itself rather than build a live graph on a\n * stopped recorder.\n */\n private setupGeneration = 0;\n\n /** @param selectEncoder picks the call's Opus encoder; injectable for tests. */\n constructor(private readonly selectEncoder: () => Promise<IOpusPacketEncoder> = () => SelectOpusPacketEncoder()) {}\n\n /** True while a recorder is actively capturing. */\n public get IsRecording(): boolean {\n return this.recording;\n }\n\n /**\n * Begins recording a mix of `micStream` and (when present) `remoteStream`. Best-effort:\n * a missing `AudioContext` / no worklet+scriptprocessor support / any setup failure disables\n * the recorder (logged) so the live call is never blocked.\n *\n * @param micStream The user's microphone capture stream (required).\n * @param remoteStream The agent's remote-audio stream, or `null` for mic-only capture.\n */\n public Start(micStream: MediaStream, remoteStream: MediaStream | null): void {\n if (this.recording) {\n return;\n }\n if (typeof AudioContext === 'undefined') {\n console.warn('[RealtimeAudioRecorder] AudioContext unavailable — recording disabled for this session.');\n return;\n }\n // Mark recording SYNCHRONOUSLY so a caller that checks IsRecording immediately after Start()\n // (the runtime does) sees `true`, even though the audio graph and the encoder are set up\n // asynchronously below.\n this.recording = true;\n this.stopping = null;\n this.capturedSamples = 0;\n this.encoderReady = this.prepareEncoder();\n this.micStream = micStream;\n // Fire-and-forget the async setup (it must `await audioContext.resume()` + worklet load); any\n // failure disables the recorder rather than throwing into the session-start path.\n void this.startMixedRecording(micStream, remoteStream).catch((error) => {\n console.warn('[RealtimeAudioRecorder] Failed to start recording — disabling for this session:', error);\n this.disable();\n });\n }\n\n /**\n * Wires the agent's remote-audio stream into the live mix once it arrives. The WebRTC\n * `ontrack` that delivers the agent voice usually lands AFTER recording has already begun\n * (mic-only), so the session attaches it here when it lands. Idempotent, and safe to call\n * before the audio graph finishes its async setup (the stream is connected once ready).\n */\n public AttachRemoteStream(stream: MediaStream): void {\n if (this.remoteAttached || stream.getAudioTracks().length === 0) {\n return;\n }\n if (this.audioContext && this.captureNode()) {\n this.remoteAttached = this.connectRemoteStream(this.audioContext, stream);\n } else {\n // Audio-graph setup still in flight (awaiting resume / worklet load) — connect at setup.\n this.pendingRemoteStream = stream;\n }\n }\n\n /**\n * Records the microphone stream's current track from now on: call it after the track changes (a\n * device switch). A source node reads the track it was created with, so the recording would otherwise\n * carry silence from the old device. Safe before the audio graph is ready (setup connects the latest\n * stream, and Start replaces it); a stream without an audio track keeps the current one.\n */\n public ReplaceMicrophone(micStream: MediaStream): void {\n this.micStream = micStream;\n if (!this.audioContext || !this.captureNode()) {\n return;\n }\n const replacement = this.connectStream(this.audioContext, micStream);\n if (replacement) {\n this.micSource?.disconnect();\n this.micSource = replacement;\n }\n }\n\n /** Milliseconds of audio captured so far, on the 48 kHz sample clock (never wall clock). */\n public NowOffsetMs(): number {\n return (this.capturedSamples * 1000) / RECORDING_SAMPLE_RATE;\n }\n\n /** The Opus packets the encoder produced since the last call (also its final packets after {@link Stop}). */\n public TakeEncodedPackets(): Uint8Array[] {\n return this.encoder ? this.encoder.TakePackets() : [];\n }\n\n /**\n * Stops capture, waits for the encoder (encoding any audio buffered while it loaded), flushes and\n * closes it, and resolves the 48 kHz samples captured. The final packets stay available to\n * {@link TakeEncodedPackets}. Idempotent: every call resolves the same count; 0 when the recorder\n * never started.\n */\n public Stop(): Promise<number> {\n if (!this.stopping) {\n this.stopping = this.stopOnce();\n }\n return this.stopping;\n }\n\n private async stopOnce(): Promise<number> {\n this.recording = false;\n this.releaseGraph();\n const encoderReady = this.encoderReady;\n if (!encoderReady) {\n return this.capturedSamples;\n }\n const encoder = await encoderReady;\n if (encoder) {\n await encoder.Flush();\n encoder.Close();\n }\n return this.capturedSamples;\n }\n\n /**\n * Selects the encoder and feeds it what was captured meanwhile. A selection failure disables the\n * recorder: with no encoder nothing captured could ever reach the server.\n */\n private async prepareEncoder(): Promise<IOpusPacketEncoder | null> {\n let encoder: IOpusPacketEncoder;\n try {\n encoder = await this.selectEncoder();\n } catch (error) {\n console.warn('[RealtimeAudioRecorder] No Opus encoder available — recording disabled for this session:', error);\n this.disable();\n // Nothing captured can be encoded now, so report nothing recorded rather than a count with no audio.\n this.pendingFrames = [];\n this.pendingSamples = 0;\n this.capturedSamples = 0;\n return null;\n }\n this.encoder = encoder;\n for (const frame of this.pendingFrames) {\n encoder.Encode(frame);\n }\n this.pendingFrames = [];\n this.pendingSamples = 0;\n return encoder;\n }\n\n /** Builds the mix graph + capture node, retrying once at the device rate if 48 kHz cannot take the mic. */\n private async startMixedRecording(micStream: MediaStream, remoteStream: MediaStream | null): Promise<void> {\n const built = await this.buildGraph(micStream, remoteStream, true);\n if (built === 'mic-rejected') {\n await this.buildGraph(micStream, remoteStream, false);\n }\n }\n\n /**\n * Wires up the Web Audio mix graph + PCM capture node (worklet preferred) and starts capture.\n * Resolves `'mic-rejected'` when a forced-48 kHz context refused the microphone source (the graph\n * is released so the caller can rebuild at the device rate); otherwise `'done'`.\n */\n private async buildGraph(micStream: MediaStream, remoteStream: MediaStream | null, prefer48k: boolean): Promise<'done' | 'mic-rejected'> {\n const generation = this.setupGeneration;\n const audioContext = this.createAudioContext(prefer48k);\n const forced48k = prefer48k && audioContext.sampleRate === RECORDING_SAMPLE_RATE;\n // CRITICAL: browsers create an AudioContext in the `suspended` state under the autoplay policy.\n // Without resuming it, the mix graph never processes audio and we capture only silence. Starting\n // a voice call is a user gesture, so resume() succeeds here.\n if (audioContext.state === 'suspended') {\n await audioContext.resume();\n }\n if (generation !== this.setupGeneration) {\n // Stopped while resuming: the context was never published, so releaseGraph() could not close it.\n this.closeContext(audioContext);\n return 'done';\n }\n const destination = audioContext.createMediaStreamDestination();\n // Publish the context BEFORE wiring the remote so a concurrent AttachRemoteStream() (the agent\n // track can land during the awaits above) sees a ready graph to connect to.\n this.audioContext = audioContext;\n this.destination = destination;\n this.resampler = audioContext.sampleRate === RECORDING_SAMPLE_RATE ? null : new LinearResampler(audioContext.sampleRate, RECORDING_SAMPLE_RATE);\n\n // Build the PCM capture node: AudioWorklet preferred, ScriptProcessor fallback. Either way the\n // node both pulls audio from the mix AND drives the destination so the graph keeps processing.\n await this.createCaptureNode(audioContext, destination);\n if (generation !== this.setupGeneration) {\n return 'done'; // Stopped while the capture node loaded: releaseGraph() already closed the published context.\n }\n\n try {\n // The microphone may have been replaced while the graph was being built.\n this.micSource = this.connectStream(audioContext, this.micStream ?? micStream);\n } catch (error) {\n if (!forced48k) {\n throw error;\n }\n console.warn('[RealtimeAudioRecorder] The 48 kHz context rejected the microphone — rebuilding at the device rate with resampling:', error);\n // releaseGraph() forgets a stashed agent stream and a replaced microphone; the rebuild still has to connect both.\n const stashedRemote = this.pendingRemoteStream;\n const stashedMic = this.micStream;\n this.releaseGraph();\n this.pendingRemoteStream = stashedRemote;\n this.micStream = stashedMic;\n return 'mic-rejected';\n }\n // Connect the agent's stream if it was passed now, or if AttachRemoteStream() stashed one while\n // we were setting up. Either way, capture the agent voice — not just the mic.\n const remote = remoteStream ?? this.pendingRemoteStream;\n this.pendingRemoteStream = null;\n if (remote && remote.getAudioTracks().length > 0) {\n this.remoteAttached = this.connectRemoteStream(audioContext, remote);\n }\n return 'done';\n }\n\n /**\n * A 48 kHz context when asked for and the browser allows it, else the device-rate default. A\n * browser that silently picks another rate is fine too: the resampler is chosen from the rate the\n * context actually reports.\n */\n private createAudioContext(prefer48k: boolean): AudioContext {\n if (prefer48k) {\n try {\n return new AudioContext({ sampleRate: RECORDING_SAMPLE_RATE });\n } catch (error) {\n console.warn('[RealtimeAudioRecorder] 48 kHz AudioContext refused — capturing at the device rate with resampling:', error);\n }\n }\n return new AudioContext();\n }\n\n /**\n * Connects the agent stream, degrading to mic-only on failure. Unlike the mic (whose failure\n * rightly disables the recorder), the agent stream is best-effort: a browser may reject it\n * (cross-sample-rate `NotSupportedError`) and that must not discard the user's recording.\n * Returns whether it was connected, so the caller only marks it attached on success.\n */\n private connectRemoteStream(audioContext: AudioContext, stream: MediaStream): boolean {\n try {\n this.connectStream(audioContext, stream);\n return true;\n } catch (error) {\n console.warn('[RealtimeAudioRecorder] Could not mix the agent stream into the recording — continuing mic-only:', error);\n return false;\n }\n }\n\n /**\n * Creates the PCM capture node and inserts it into the graph: sources → captureNode → destination.\n * Prefers an {@link AudioWorkletNode} (off-main-thread, no deprecation); falls back to a\n * {@link ScriptProcessorNode} where worklets are unavailable. Throws when neither is supported\n * (caught by {@link Start}, which then disables the recorder).\n */\n private async createCaptureNode(audioContext: AudioContext, destination: MediaStreamAudioDestinationNode): Promise<void> {\n if (await this.tryCreateWorkletNode(audioContext, destination)) {\n return;\n }\n this.createScriptProcessorNode(audioContext, destination);\n }\n\n /** Attempts to build the AudioWorklet capture node; returns `false` (no throw) when unsupported. */\n private async tryCreateWorkletNode(audioContext: AudioContext, destination: MediaStreamAudioDestinationNode): Promise<boolean> {\n if (!audioContext.audioWorklet || typeof AudioWorkletNode === 'undefined' || typeof Blob === 'undefined') {\n return false;\n }\n try {\n const moduleUrl = URL.createObjectURL(\n new Blob([RealtimeAudioRecorder.workletProcessorSource], { type: 'application/javascript' }),\n );\n try {\n await audioContext.audioWorklet.addModule(moduleUrl);\n } finally {\n URL.revokeObjectURL(moduleUrl);\n }\n const node = new AudioWorkletNode(audioContext, 'mj-pcm-capture', { numberOfInputs: 1, numberOfOutputs: 1 });\n node.port.onmessage = (event: MessageEvent<Float32Array>) => this.captureFrame(event.data);\n node.connect(destination);\n this.workletNode = node;\n return true;\n } catch (error) {\n console.warn('[RealtimeAudioRecorder] AudioWorklet unavailable — falling back to ScriptProcessor:', error);\n return false;\n }\n }\n\n /** Builds the ScriptProcessor fallback capture node and inserts it into the graph. */\n private createScriptProcessorNode(audioContext: AudioContext, destination: MediaStreamAudioDestinationNode): void {\n if (typeof audioContext.createScriptProcessor !== 'function') {\n throw new Error('Neither AudioWorklet nor ScriptProcessor is supported');\n }\n const node = audioContext.createScriptProcessor(RealtimeAudioRecorder.scriptProcessorBufferSize, 1, 1);\n node.onaudioprocess = (event: AudioProcessingEvent) => this.captureFrame(event.inputBuffer.getChannelData(0));\n // ScriptProcessor only fires onaudioprocess while connected to the destination.\n node.connect(destination);\n this.scriptNode = node;\n }\n\n /** The active capture node (worklet or script processor), or `null` before setup. */\n private captureNode(): AudioNode | null {\n return this.workletNode ?? this.scriptNode;\n }\n\n /**\n * Absorbs one captured frame: resample to 48 kHz, count it, and hand it to the encoder (or buffer\n * it while the encoder loads).\n *\n * Past the pending-buffer cap a frame is dropped AND not counted. Keeping the count equal to the\n * audio actually handed to the encoder is what lets the runtime trust `packets × 960 ≥ captured`\n * when it trims the final shard; a few lost seconds at the start of a call whose encoder never\n * loaded is the smaller harm.\n */\n private captureFrame(frame: Float32Array): void {\n if (!this.recording || frame.length === 0) {\n return;\n }\n // Copy out of the engine's reused buffer (a resampler output is already a fresh array).\n const samples = this.resampler ? this.resampler.Process(frame) : frame.slice(0);\n if (samples.length === 0) {\n return;\n }\n if (this.encoder) {\n this.encoder.Encode(samples);\n } else if (this.pendingSamples + samples.length <= RealtimeAudioRecorder.maxPendingSamples) {\n this.pendingFrames.push(samples);\n this.pendingSamples += samples.length;\n } else {\n if (!this.pendingOverflowWarned) {\n this.pendingOverflowWarned = true;\n console.warn(`[RealtimeAudioRecorder] Opus encoder still not ready after ${RealtimeAudioRecorder.maxPendingSamples / RECORDING_SAMPLE_RATE} s of audio — dropping audio until it is.`);\n }\n return;\n }\n this.capturedSamples += samples.length;\n }\n\n /** Routes one stream's audio tracks into the capture node; returns the source, or null when track-less / no node. */\n private connectStream(audioContext: AudioContext, stream: MediaStream): MediaStreamAudioSourceNode | null {\n const node = this.captureNode();\n if (!node || stream.getAudioTracks().length === 0) {\n return null;\n }\n const source = audioContext.createMediaStreamSource(stream);\n source.connect(node);\n return source;\n }\n\n /**\n * Turns recording off after a setup failure and releases the graph. Audio already captured stays\n * queued for the encoder, so a graph failure mid-call still keeps what was recorded before it.\n */\n private disable(): void {\n this.recording = false;\n this.releaseGraph();\n }\n\n /** Releases the audio graph + capture node. Idempotent; leaves the encoder and the sample count alone. */\n private releaseGraph(): void {\n this.setupGeneration++;\n this.remoteAttached = false;\n this.pendingRemoteStream = null;\n this.micStream = null;\n this.micSource = null;\n if (this.workletNode) {\n this.workletNode.port.onmessage = null;\n this.disconnectNode(this.workletNode);\n this.workletNode = null;\n }\n if (this.scriptNode) {\n this.scriptNode.onaudioprocess = null;\n this.disconnectNode(this.scriptNode);\n this.scriptNode = null;\n }\n this.destination = null;\n this.resampler = null;\n if (this.audioContext) {\n this.closeContext(this.audioContext);\n this.audioContext = null;\n }\n }\n\n private disconnectNode(node: AudioNode): void {\n try {\n node.disconnect();\n } catch (error) {\n // Expected when the node was never connected or is already disconnected; nothing to release.\n console.debug('[RealtimeAudioRecorder] Capture node disconnect skipped:', error);\n }\n }\n\n private closeContext(audioContext: AudioContext): void {\n void audioContext.close().catch((error: unknown) => {\n // A context that is already closed rejects here; the graph is released either way.\n console.debug('[RealtimeAudioRecorder] AudioContext close skipped:', error);\n });\n }\n}\n"]}
1
+ {"version":3,"file":"realtime-audio-recorder.js","sourceRoot":"","sources":["../../../src/lib/services/realtime-audio-recorder.ts"],"names":[],"mappings":"AAAA,OAAO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C,UAAU,CAAC,cAAc,GAAG,IAAI,CAAC;YACtC,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;YACrC,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC;QAC3B,CAAC;QACD,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC;QACxB,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,IAAI,CAAC,YAAY,EAAE,CAAC;YACpB,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;YACrC,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC;QAC7B,CAAC;IACL,CAAC;IAEO,cAAc,CAAC,IAAe;QAClC,IAAI,CAAC;YACD,IAAI,CAAC,UAAU,EAAE,CAAC;QACtB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,6FAA6F;YAC7F,OAAO,CAAC,KAAK,CAAC,0DAA0D,EAAE,KAAK,CAAC,CAAC;QACrF,CAAC;IACL,CAAC;IAEO,YAAY,CAAC,YAA0B;QAC3C,KAAK,YAAY,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;YAC/C,mFAAmF;YACnF,OAAO,CAAC,KAAK,CAAC,qDAAqD,EAAE,KAAK,CAAC,CAAC;QAChF,CAAC,CAAC,CAAC;IACP,CAAC","sourcesContent":["import { RECORDING_SAMPLE_RATE } from '@memberjunction/ai-core-plus';\nimport { IRealtimeSessionRecorder } from '@memberjunction/realtime-runtime';\nimport { LinearResampler } from './recording/linear-resampler';\nimport { IOpusPacketEncoder, SelectOpusPacketEncoder } from './recording/opus-packet-encoder';\n\n/**\n * Browser-side audio recorder for a CLIENT-DIRECT realtime voice session, implementing the\n * runtime's {@link IRealtimeSessionRecorder} contract directly.\n *\n * Mixes the user's microphone with the agent's remote-audio stream (every driver exposes one via\n * `GetRemoteMediaStream()`: WebRTC drivers publish their remote track, PCM drivers — Gemini,\n * ElevenLabs, AssemblyAI, xAI, HuggingFace — publish their playout engine's output) in a Web Audio\n * graph, captures the mix as mono Float32 frames through an {@link AudioWorkletNode} (preferred) or a\n * {@link ScriptProcessorNode} (fallback), and feeds them to ONE continuous Opus encoder for the whole\n * call. The runtime pulls the encoded packets with {@link TakeEncodedPackets}, cuts them into shards\n * and uploads them as the call goes, so nothing is held in memory until the end.\n *\n * Timing is the 48 kHz sample clock: the graph asks for a 48 kHz context, and when the browser\n * refuses (or reports another rate) every frame is resampled to 48 kHz before encoding. The\n * captured-sample count drives {@link NowOffsetMs} and is what {@link Stop} resolves.\n *\n * Robust by design — every step degrades gracefully:\n * - No `AudioContext` (server-side render / unsupported env) → the recorder disables itself\n * ({@link IsRecording} stays `false`, {@link Stop} resolves 0); the voice call proceeds.\n * - No `AudioWorkletNode` AND no `ScriptProcessorNode` → disables itself rather than throwing.\n * - A forced-48 kHz context that cannot take the microphone (Firefox rejects a source whose rate\n * differs from its context's) → rebuilt once at the device rate with resampling.\n * - No remote stream yet (e.g. the WebRTC track hasn't landed) → records mic only until it does.\n * - A remote stream that can't be connected (e.g. a cross-sample-rate `createMediaStreamSource`\n * rejection) → warns and records mic only; the mic recording is never lost to the agent stream.\n * - No usable encoder → logged, recording disabled for the call.\n *\n * Not an Angular service: it owns transient per-session media plumbing the runtime creates and\n * discards per call, so a plain class is the right shape (no DI, no singleton).\n */\nexport class RealtimeAudioRecorder implements IRealtimeSessionRecorder {\n /** PCM frame size for the ScriptProcessor fallback (worklet uses its native 128-frame quantum). */\n private static readonly scriptProcessorBufferSize = 4096;\n /**\n * Most 48 kHz audio held while the encoder is still being selected / loaded (10 s). Selection is\n * normally well under a second; past this the encoder is stuck, and later frames are dropped\n * (see {@link captureFrame} for why they are not counted either).\n */\n private static readonly maxPendingSamples = 10 * RECORDING_SAMPLE_RATE;\n /** Inline AudioWorklet processor: forwards each 128-frame mono input block to the main thread. */\n private static readonly workletProcessorSource = `\n class MJPcmCaptureProcessor extends AudioWorkletProcessor {\n process(inputs) {\n const input = inputs[0];\n if (input && input[0] && input[0].length > 0) {\n // Copy out of the reused worklet buffer before posting.\n this.port.postMessage(input[0].slice(0));\n }\n return true;\n }\n }\n registerProcessor('mj-pcm-capture', MJPcmCaptureProcessor);\n `;\n\n private audioContext: AudioContext | null = null;\n private destination: MediaStreamAudioDestinationNode | null = null;\n private workletNode: AudioWorkletNode | null = null;\n private scriptNode: ScriptProcessorNode | null = null;\n /** Converts the context's rate to 48 kHz; `null` when the context already runs at 48 kHz. */\n private resampler: LinearResampler | null = null;\n private recording = false;\n\n /** The agent's remote stream currently wired into the mix (prevents duplicate attach of the same stream). */\n private remoteStream: MediaStream | null = null;\n /** The source node reading the agent's remote stream, replaced on mid-call WebRTC reconnect. */\n private remoteSource: MediaStreamAudioSourceNode | null = null;\n /** True while a remote stream is wired into the active mix graph. */\n private remoteAttached = false;\n /** A remote stream handed to AttachRemoteStream before the audio graph was ready; wired at setup. */\n private pendingRemoteStream: MediaStream | null = null;\n /** The microphone to record: the latest stream given to Start or ReplaceMicrophone. Setup connects it. */\n private micStream: MediaStream | null = null;\n /** The source node reading the microphone, swapped by ReplaceMicrophone. */\n private micSource: MediaStreamAudioSourceNode | null = null;\n\n /** 48 kHz samples captured (post-resample) — the recording's clock. */\n private capturedSamples = 0;\n /** The call's encoder once selected; `null` while selecting, after a failure, or when not recording. */\n private encoder: IOpusPacketEncoder | null = null;\n /** Resolves to the encoder (or `null` on failure) — Stop awaits it so buffered audio still gets encoded. */\n private encoderReady: Promise<IOpusPacketEncoder | null> | null = null;\n /** 48 kHz frames captured before the encoder was ready, fed to it in order once it is. */\n private pendingFrames: Float32Array[] = [];\n private pendingSamples = 0;\n private pendingOverflowWarned = false;\n /** The first Stop's promise; later calls return it (idempotent). */\n private stopping: Promise<number> | null = null;\n\n /**\n * Bumped whenever the audio graph is released. The async graph setup snapshots it and, after each\n * await, gives up if it moved: a {@link Stop} that lands mid-setup can only release what setup has\n * already published, so setup must release the rest itself rather than build a live graph on a\n * stopped recorder.\n */\n private setupGeneration = 0;\n\n /** @param selectEncoder picks the call's Opus encoder; injectable for tests. */\n constructor(private readonly selectEncoder: () => Promise<IOpusPacketEncoder> = () => SelectOpusPacketEncoder()) {}\n\n /** True while a recorder is actively capturing. */\n public get IsRecording(): boolean {\n return this.recording;\n }\n\n /**\n * Begins recording a mix of `micStream` and (when present) `remoteStream`. Best-effort:\n * a missing `AudioContext` / no worklet+scriptprocessor support / any setup failure disables\n * the recorder (logged) so the live call is never blocked.\n *\n * @param micStream The user's microphone capture stream (required).\n * @param remoteStream The agent's remote-audio stream, or `null` for mic-only capture.\n */\n public Start(micStream: MediaStream, remoteStream: MediaStream | null): void {\n if (this.recording) {\n return;\n }\n if (typeof AudioContext === 'undefined') {\n console.warn('[RealtimeAudioRecorder] AudioContext unavailable — recording disabled for this session.');\n return;\n }\n // Mark recording SYNCHRONOUSLY so a caller that checks IsRecording immediately after Start()\n // (the runtime does) sees `true`, even though the audio graph and the encoder are set up\n // asynchronously below.\n this.recording = true;\n this.stopping = null;\n this.capturedSamples = 0;\n this.encoderReady = this.prepareEncoder();\n this.micStream = micStream;\n // Fire-and-forget the async setup (it must `await audioContext.resume()` + worklet load); any\n // failure disables the recorder rather than throwing into the session-start path.\n void this.startMixedRecording(micStream, remoteStream).catch((error) => {\n console.warn('[RealtimeAudioRecorder] Failed to start recording — disabling for this session:', error);\n this.disable();\n });\n }\n\n /**\n * Wires the agent's remote-audio stream into the live mix once it arrives, or replaces the\n * previous remote-audio stream when a WebRTC transport reconnects mid-call. Idempotent for the\n * same `MediaStream` instance, and safe to call before the audio graph finishes its async setup.\n */\n public AttachRemoteStream(stream: MediaStream): void {\n if (this.remoteStream === stream || stream.getAudioTracks().length === 0) {\n return;\n }\n if (this.audioContext && this.captureNode()) {\n this.connectRemoteStream(this.audioContext, stream);\n } else {\n // Audio-graph setup still in flight (awaiting resume / worklet load) — connect at setup.\n this.pendingRemoteStream = stream;\n }\n }\n\n /**\n * Records the microphone stream's current track from now on: call it after the track changes (a\n * device switch). A source node reads the track it was created with, so the recording would otherwise\n * carry silence from the old device. Safe before the audio graph is ready (setup connects the latest\n * stream, and Start replaces it); a stream without an audio track keeps the current one.\n */\n public ReplaceMicrophone(micStream: MediaStream): void {\n this.micStream = micStream;\n if (!this.audioContext || !this.captureNode()) {\n return;\n }\n const replacement = this.connectStream(this.audioContext, micStream);\n if (replacement) {\n this.micSource?.disconnect();\n this.micSource = replacement;\n }\n }\n\n /** Milliseconds of audio captured so far, on the 48 kHz sample clock (never wall clock). */\n public NowOffsetMs(): number {\n return (this.capturedSamples * 1000) / RECORDING_SAMPLE_RATE;\n }\n\n /** The Opus packets the encoder produced since the last call (also its final packets after {@link Stop}). */\n public TakeEncodedPackets(): Uint8Array[] {\n return this.encoder ? this.encoder.TakePackets() : [];\n }\n\n /**\n * Stops capture, waits for the encoder (encoding any audio buffered while it loaded), flushes and\n * closes it, and resolves the 48 kHz samples captured. The final packets stay available to\n * {@link TakeEncodedPackets}. Idempotent: every call resolves the same count; 0 when the recorder\n * never started.\n */\n public Stop(): Promise<number> {\n if (!this.stopping) {\n this.stopping = this.stopOnce();\n }\n return this.stopping;\n }\n\n private async stopOnce(): Promise<number> {\n this.recording = false;\n this.releaseGraph();\n const encoderReady = this.encoderReady;\n if (!encoderReady) {\n return this.capturedSamples;\n }\n const encoder = await encoderReady;\n if (encoder) {\n await encoder.Flush();\n encoder.Close();\n }\n return this.capturedSamples;\n }\n\n /**\n * Selects the encoder and feeds it what was captured meanwhile. A selection failure disables the\n * recorder: with no encoder nothing captured could ever reach the server.\n */\n private async prepareEncoder(): Promise<IOpusPacketEncoder | null> {\n let encoder: IOpusPacketEncoder;\n try {\n encoder = await this.selectEncoder();\n } catch (error) {\n console.warn('[RealtimeAudioRecorder] No Opus encoder available — recording disabled for this session:', error);\n this.disable();\n // Nothing captured can be encoded now, so report nothing recorded rather than a count with no audio.\n this.pendingFrames = [];\n this.pendingSamples = 0;\n this.capturedSamples = 0;\n return null;\n }\n this.encoder = encoder;\n for (const frame of this.pendingFrames) {\n encoder.Encode(frame);\n }\n this.pendingFrames = [];\n this.pendingSamples = 0;\n return encoder;\n }\n\n /** Builds the mix graph + capture node, retrying once at the device rate if 48 kHz cannot take the mic. */\n private async startMixedRecording(micStream: MediaStream, remoteStream: MediaStream | null): Promise<void> {\n const built = await this.buildGraph(micStream, remoteStream, true);\n if (built === 'mic-rejected') {\n await this.buildGraph(micStream, remoteStream, false);\n }\n }\n\n /**\n * Wires up the Web Audio mix graph + PCM capture node (worklet preferred) and starts capture.\n * Resolves `'mic-rejected'` when a forced-48 kHz context refused the microphone source (the graph\n * is released so the caller can rebuild at the device rate); otherwise `'done'`.\n */\n private async buildGraph(micStream: MediaStream, remoteStream: MediaStream | null, prefer48k: boolean): Promise<'done' | 'mic-rejected'> {\n const generation = this.setupGeneration;\n const audioContext = this.createAudioContext(prefer48k);\n const forced48k = prefer48k && audioContext.sampleRate === RECORDING_SAMPLE_RATE;\n // CRITICAL: browsers create an AudioContext in the `suspended` state under the autoplay policy.\n // Without resuming it, the mix graph never processes audio and we capture only silence. Starting\n // a voice call is a user gesture, so resume() succeeds here.\n if (audioContext.state === 'suspended') {\n await audioContext.resume();\n }\n if (generation !== this.setupGeneration) {\n // Stopped while resuming: the context was never published, so releaseGraph() could not close it.\n this.closeContext(audioContext);\n return 'done';\n }\n const destination = audioContext.createMediaStreamDestination();\n // Publish the context BEFORE wiring the remote so a concurrent AttachRemoteStream() (the agent\n // track can land during the awaits above) sees a ready graph to connect to.\n this.audioContext = audioContext;\n this.destination = destination;\n this.resampler = audioContext.sampleRate === RECORDING_SAMPLE_RATE ? null : new LinearResampler(audioContext.sampleRate, RECORDING_SAMPLE_RATE);\n\n // Build the PCM capture node: AudioWorklet preferred, ScriptProcessor fallback. Either way the\n // node both pulls audio from the mix AND drives the destination so the graph keeps processing.\n await this.createCaptureNode(audioContext, destination);\n if (generation !== this.setupGeneration) {\n return 'done'; // Stopped while the capture node loaded: releaseGraph() already closed the published context.\n }\n\n try {\n // The microphone may have been replaced while the graph was being built.\n this.micSource = this.connectStream(audioContext, this.micStream ?? micStream);\n } catch (error) {\n if (!forced48k) {\n throw error;\n }\n console.warn('[RealtimeAudioRecorder] The 48 kHz context rejected the microphone — rebuilding at the device rate with resampling:', error);\n // releaseGraph() forgets a stashed agent stream and a replaced microphone; the rebuild still has to connect both.\n const stashedRemote = this.pendingRemoteStream;\n const stashedMic = this.micStream;\n this.releaseGraph();\n this.pendingRemoteStream = stashedRemote;\n this.micStream = stashedMic;\n return 'mic-rejected';\n }\n // Connect the agent's stream if it was passed now, or if AttachRemoteStream() stashed one while\n // we were setting up. Either way, capture the agent voice — not just the mic.\n const remote = remoteStream ?? this.pendingRemoteStream;\n this.pendingRemoteStream = null;\n if (remote && remote.getAudioTracks().length > 0) {\n this.connectRemoteStream(audioContext, remote);\n }\n return 'done';\n }\n\n /**\n * A 48 kHz context when asked for and the browser allows it, else the device-rate default. A\n * browser that silently picks another rate is fine too: the resampler is chosen from the rate the\n * context actually reports.\n */\n private createAudioContext(prefer48k: boolean): AudioContext {\n if (prefer48k) {\n try {\n return new AudioContext({ sampleRate: RECORDING_SAMPLE_RATE });\n } catch (error) {\n console.warn('[RealtimeAudioRecorder] 48 kHz AudioContext refused — capturing at the device rate with resampling:', error);\n }\n }\n return new AudioContext();\n }\n\n /**\n * Connects (or replaces) the agent stream, degrading to mic-only on failure. Unlike the mic (whose\n * failure rightly disables the recorder), the agent stream is best-effort: a browser may reject it\n * (cross-sample-rate `NotSupportedError`) and that must not discard the user's recording.\n */\n private connectRemoteStream(audioContext: AudioContext, stream: MediaStream): boolean {\n try {\n const replacement = this.connectStream(audioContext, stream);\n if (!replacement) {\n return false;\n }\n if (this.remoteSource) {\n this.disconnectNode(this.remoteSource);\n }\n this.remoteSource = replacement;\n this.remoteStream = stream;\n this.remoteAttached = true;\n return true;\n } catch (error) {\n console.warn('[RealtimeAudioRecorder] Could not mix the agent stream into the recording — continuing mic-only:', error);\n return false;\n }\n }\n\n /**\n * Creates the PCM capture node and inserts it into the graph: sources → captureNode → destination.\n * Prefers an {@link AudioWorkletNode} (off-main-thread, no deprecation); falls back to a\n * {@link ScriptProcessorNode} where worklets are unavailable. Throws when neither is supported\n * (caught by {@link Start}, which then disables the recorder).\n */\n private async createCaptureNode(audioContext: AudioContext, destination: MediaStreamAudioDestinationNode): Promise<void> {\n if (await this.tryCreateWorkletNode(audioContext, destination)) {\n return;\n }\n this.createScriptProcessorNode(audioContext, destination);\n }\n\n /** Attempts to build the AudioWorklet capture node; returns `false` (no throw) when unsupported. */\n private async tryCreateWorkletNode(audioContext: AudioContext, destination: MediaStreamAudioDestinationNode): Promise<boolean> {\n if (!audioContext.audioWorklet || typeof AudioWorkletNode === 'undefined' || typeof Blob === 'undefined') {\n return false;\n }\n try {\n const moduleUrl = URL.createObjectURL(\n new Blob([RealtimeAudioRecorder.workletProcessorSource], { type: 'application/javascript' }),\n );\n try {\n await audioContext.audioWorklet.addModule(moduleUrl);\n } finally {\n URL.revokeObjectURL(moduleUrl);\n }\n const node = new AudioWorkletNode(audioContext, 'mj-pcm-capture', { numberOfInputs: 1, numberOfOutputs: 1 });\n node.port.onmessage = (event: MessageEvent<Float32Array>) => this.captureFrame(event.data);\n node.connect(destination);\n this.workletNode = node;\n return true;\n } catch (error) {\n console.warn('[RealtimeAudioRecorder] AudioWorklet unavailable — falling back to ScriptProcessor:', error);\n return false;\n }\n }\n\n /** Builds the ScriptProcessor fallback capture node and inserts it into the graph. */\n private createScriptProcessorNode(audioContext: AudioContext, destination: MediaStreamAudioDestinationNode): void {\n if (typeof audioContext.createScriptProcessor !== 'function') {\n throw new Error('Neither AudioWorklet nor ScriptProcessor is supported');\n }\n const node = audioContext.createScriptProcessor(RealtimeAudioRecorder.scriptProcessorBufferSize, 1, 1);\n node.onaudioprocess = (event: AudioProcessingEvent) => this.captureFrame(event.inputBuffer.getChannelData(0));\n // ScriptProcessor only fires onaudioprocess while connected to the destination.\n node.connect(destination);\n this.scriptNode = node;\n }\n\n /** The active capture node (worklet or script processor), or `null` before setup. */\n private captureNode(): AudioNode | null {\n return this.workletNode ?? this.scriptNode;\n }\n\n /**\n * Absorbs one captured frame: resample to 48 kHz, count it, and hand it to the encoder (or buffer\n * it while the encoder loads).\n *\n * Past the pending-buffer cap a frame is dropped AND not counted. Keeping the count equal to the\n * audio actually handed to the encoder is what lets the runtime trust `packets × 960 ≥ captured`\n * when it trims the final shard; a few lost seconds at the start of a call whose encoder never\n * loaded is the smaller harm.\n */\n private captureFrame(frame: Float32Array): void {\n if (!this.recording || frame.length === 0) {\n return;\n }\n // Copy out of the engine's reused buffer (a resampler output is already a fresh array).\n const samples = this.resampler ? this.resampler.Process(frame) : frame.slice(0);\n if (samples.length === 0) {\n return;\n }\n if (this.encoder) {\n this.encoder.Encode(samples);\n } else if (this.pendingSamples + samples.length <= RealtimeAudioRecorder.maxPendingSamples) {\n this.pendingFrames.push(samples);\n this.pendingSamples += samples.length;\n } else {\n if (!this.pendingOverflowWarned) {\n this.pendingOverflowWarned = true;\n console.warn(`[RealtimeAudioRecorder] Opus encoder still not ready after ${RealtimeAudioRecorder.maxPendingSamples / RECORDING_SAMPLE_RATE} s of audio — dropping audio until it is.`);\n }\n return;\n }\n this.capturedSamples += samples.length;\n }\n\n /** Routes one stream's audio tracks into the capture node; returns the source, or null when track-less / no node. */\n private connectStream(audioContext: AudioContext, stream: MediaStream): MediaStreamAudioSourceNode | null {\n const node = this.captureNode();\n if (!node || stream.getAudioTracks().length === 0) {\n return null;\n }\n const source = audioContext.createMediaStreamSource(stream);\n source.connect(node);\n return source;\n }\n\n /**\n * Turns recording off after a setup failure and releases the graph. Audio already captured stays\n * queued for the encoder, so a graph failure mid-call still keeps what was recorded before it.\n */\n private disable(): void {\n this.recording = false;\n this.releaseGraph();\n }\n\n /** Releases the audio graph + capture node. Idempotent; leaves the encoder and the sample count alone. */\n private releaseGraph(): void {\n this.setupGeneration++;\n if (this.remoteSource) {\n this.disconnectNode(this.remoteSource);\n this.remoteSource = null;\n }\n this.remoteStream = null;\n this.remoteAttached = false;\n this.pendingRemoteStream = null;\n this.micStream = null;\n this.micSource = null;\n if (this.workletNode) {\n this.workletNode.port.onmessage = null;\n this.disconnectNode(this.workletNode);\n this.workletNode = null;\n }\n if (this.scriptNode) {\n this.scriptNode.onaudioprocess = null;\n this.disconnectNode(this.scriptNode);\n this.scriptNode = null;\n }\n this.destination = null;\n this.resampler = null;\n if (this.audioContext) {\n this.closeContext(this.audioContext);\n this.audioContext = null;\n }\n }\n\n private disconnectNode(node: AudioNode): void {\n try {\n node.disconnect();\n } catch (error) {\n // Expected when the node was never connected or is already disconnected; nothing to release.\n console.debug('[RealtimeAudioRecorder] Capture node disconnect skipped:', error);\n }\n }\n\n private closeContext(audioContext: AudioContext): void {\n void audioContext.close().catch((error: unknown) => {\n // A context that is already closed rejects here; the graph is released either way.\n console.debug('[RealtimeAudioRecorder] AudioContext close skipped:', error);\n });\n }\n}\n"]}
@@ -23,11 +23,16 @@ export declare class RealtimeSessionService extends RealtimeSessionRuntime {
23
23
  * Sends the recording terminal (tail shard + counts, as a keepalive request) when the page is
24
24
  * going away: on `pagehide`, and when the page becomes hidden — the last event a mobile browser
25
25
  * reliably fires before it may discard a backgrounded tab without any unload event. Both handlers
26
- * only call the runtime's synchronous {@link RealtimeSessionRuntime.SendRecordingTerminal}, which
27
- * does no IndexedDB work and no encoding: there is no time for either while a page is unloading.
26
+ * only call the runtime's synchronous {@link RealtimeSessionRuntime.SendRecordingTerminal} (`pagehide`
27
+ * through {@link RealtimeSessionRuntime.SendPageHideSignals}), which does no IndexedDB work and no
28
+ * encoding: there is no time for either while a page is unloading.
28
29
  * It does nothing when no call is recording, and repeating it is safe (a sent tail is sealed, so a
29
30
  * call that continues after the tab comes back sends its later shards at new indexes).
30
31
  *
32
+ * `pagehide` goes through {@link RealtimeSessionRuntime.SendPageHideSignals}, which also closes the
33
+ * server session with a `keepalive` request when the page is going away for good (not entering the
34
+ * back/forward cache); a hidden tab never closes it, the user may come back.
35
+ *
31
36
  * There is deliberately no `beforeunload` prompt any more: shards already on the server plus the
32
37
  * terminal make closing the tab safe, and a `beforeunload` listener blocks the back/forward cache.
33
38
  *
@@ -43,7 +48,9 @@ export declare class RealtimeSessionService extends RealtimeSessionRuntime {
43
48
  }
44
49
  /** The slice of `window` the terminal wiring needs; `window` itself satisfies it. */
45
50
  export interface PageHideEventTarget {
46
- addEventListener(type: 'pagehide', listener: () => void): void;
51
+ addEventListener(type: 'pagehide', listener: (event: {
52
+ readonly persisted: boolean;
53
+ }) => void): void;
47
54
  }
48
55
  /** The slice of `document` the terminal wiring needs; `document` itself satisfies it. */
49
56
  export interface VisibilityEventSource {
@@ -1 +1 @@
1
- {"version":3,"file":"realtime-session.service.d.ts","sourceRoot":"","sources":["../../../src/lib/services/realtime-session.service.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,sBAAsB,EAAE,MAAM,kCAAkC,CAAC;;AA8B1E;;;;;;;;;;;;;;;;GAgBG;AACH,qBACa,sBAAuB,SAAQ,sBAAsB;;IAQ9D;;;;;;;;;;;;;;;;;OAiBG;IACH,SAAS,CAAC,6BAA6B,CAAC,IAAI,EAAE,mBAAmB,EAAE,UAAU,EAAE,qBAAqB,GAAG,IAAI;yCA1BlG,sBAAsB;6CAAtB,sBAAsB;CAoClC;AAED,qFAAqF;AACrF,MAAM,WAAW,mBAAmB;IAEhC,gBAAgB,CAAC,IAAI,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,IAAI,GAAG,IAAI,CAAC;CAClE;AAED,yFAAyF;AACzF,MAAM,WAAW,qBAAqB;IAElC,QAAQ,CAAC,eAAe,EAAE,uBAAuB,CAAC;IAElD,gBAAgB,CAAC,IAAI,EAAE,kBAAkB,EAAE,QAAQ,EAAE,MAAM,IAAI,GAAG,IAAI,CAAC;CAC1E"}
1
+ {"version":3,"file":"realtime-session.service.d.ts","sourceRoot":"","sources":["../../../src/lib/services/realtime-session.service.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,sBAAsB,EAAE,MAAM,kCAAkC,CAAC;;AA8B1E;;;;;;;;;;;;;;;;GAgBG;AACH,qBACa,sBAAuB,SAAQ,sBAAsB;;IAQ9D;;;;;;;;;;;;;;;;;;;;;;OAsBG;IACH,SAAS,CAAC,6BAA6B,CAAC,IAAI,EAAE,mBAAmB,EAAE,UAAU,EAAE,qBAAqB,GAAG,IAAI;yCA/BlG,sBAAsB;6CAAtB,sBAAsB;CAyClC;AAED,qFAAqF;AACrF,MAAM,WAAW,mBAAmB;IAEhC,gBAAgB,CAAC,IAAI,EAAE,UAAU,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE;QAAE,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAA;KAAE,KAAK,IAAI,GAAG,IAAI,CAAC;CACxG;AAED,yFAAyF;AACzF,MAAM,WAAW,qBAAqB;IAElC,QAAQ,CAAC,eAAe,EAAE,uBAAuB,CAAC;IAElD,gBAAgB,CAAC,IAAI,EAAE,kBAAkB,EAAE,QAAQ,EAAE,MAAM,IAAI,GAAG,IAAI,CAAC;CAC1E"}
@@ -47,11 +47,16 @@ export class RealtimeSessionService extends RealtimeSessionRuntime {
47
47
  * Sends the recording terminal (tail shard + counts, as a keepalive request) when the page is
48
48
  * going away: on `pagehide`, and when the page becomes hidden — the last event a mobile browser
49
49
  * reliably fires before it may discard a backgrounded tab without any unload event. Both handlers
50
- * only call the runtime's synchronous {@link RealtimeSessionRuntime.SendRecordingTerminal}, which
51
- * does no IndexedDB work and no encoding: there is no time for either while a page is unloading.
50
+ * only call the runtime's synchronous {@link RealtimeSessionRuntime.SendRecordingTerminal} (`pagehide`
51
+ * through {@link RealtimeSessionRuntime.SendPageHideSignals}), which does no IndexedDB work and no
52
+ * encoding: there is no time for either while a page is unloading.
52
53
  * It does nothing when no call is recording, and repeating it is safe (a sent tail is sealed, so a
53
54
  * call that continues after the tab comes back sends its later shards at new indexes).
54
55
  *
56
+ * `pagehide` goes through {@link RealtimeSessionRuntime.SendPageHideSignals}, which also closes the
57
+ * server session with a `keepalive` request when the page is going away for good (not entering the
58
+ * back/forward cache); a hidden tab never closes it, the user may come back.
59
+ *
55
60
  * There is deliberately no `beforeunload` prompt any more: shards already on the server plus the
56
61
  * terminal make closing the tab safe, and a `beforeunload` listener blocks the back/forward cache.
57
62
  *
@@ -62,7 +67,7 @@ export class RealtimeSessionService extends RealtimeSessionRuntime {
62
67
  * @param visibility the visibility source (`document`)
63
68
  */
64
69
  WireRecordingTerminalTriggers(page, visibility) {
65
- page.addEventListener('pagehide', () => this.SendRecordingTerminal({ Final: true }));
70
+ page.addEventListener('pagehide', (event) => this.SendPageHideSignals({ Persisted: event.persisted }));
66
71
  visibility.addEventListener('visibilitychange', () => {
67
72
  if (visibility.visibilityState === 'hidden') {
68
73
  // Not final: the user may come back and the call go on, so the server only stamps the
@@ -1 +1 @@
1
- {"version":3,"file":"realtime-session.service.js","sourceRoot":"","sources":["../../../src/lib/services/realtime-session.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,sBAAsB,EAAE,MAAM,kCAAkC,CAAC;AAC1E,OAAO,EACH,4BAA4B,EAC5B,4BAA4B,EAC5B,wBAAwB,EACxB,wBAAwB,EACxB,6BAA6B,EAC7B,oBAAoB,EACpB,wBAAwB,EACxB,qBAAqB,GACxB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;;AAEzE,gGAAgG;AAChG,mGAAmG;AACnG,gDAAgD;AAChD,EAAE;AACF,+FAA+F;AAC/F,0FAA0F;AAC1F,+FAA+F;AAC/F,kBAAkB;AAClB,wBAAwB,EAAE,CAAC;AAC3B,oBAAoB,EAAE,CAAC;AACvB,wBAAwB,EAAE,CAAC;AAC3B,4BAA4B,EAAE,CAAC;AAC/B,4BAA4B,EAAE,CAAC;AAC/B,qBAAqB,EAAE,CAAC;AACxB,wBAAwB,EAAE,CAAC;AAC3B,6BAA6B,EAAE,CAAC;AAEhC;;;;;;;;;;;;;;;;GAgBG;AAEH,MAAM,OAAO,sBAAuB,SAAQ,sBAAsB;IAC9D;QACI,KAAK,CAAC,IAAI,wBAAwB,EAAE,CAAC,CAAC;QACtC,IAAI,OAAO,MAAM,KAAK,WAAW,IAAI,OAAO,QAAQ,KAAK,WAAW,EAAE,CAAC;YACnE,IAAI,CAAC,6BAA6B,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;QACzD,CAAC;IACL,CAAC;IAED;;;;;;;;;;;;;;;;;OAiBG;IACO,6BAA6B,CAAC,IAAyB,EAAE,UAAiC;QAChG,IAAI,CAAC,gBAAgB,CAAC,UAAU,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,qBAAqB,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;QACrF,UAAU,CAAC,gBAAgB,CAAC,kBAAkB,EAAE,GAAG,EAAE;YACjD,IAAI,UAAU,CAAC,eAAe,KAAK,QAAQ,EAAE,CAAC;gBAC1C,sFAAsF;gBACtF,sFAAsF;gBACtF,IAAI,CAAC,qBAAqB,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;YACjD,CAAC;QACL,CAAC,CAAC,CAAC;IACP,CAAC;gHAnCQ,sBAAsB;gEAAtB,sBAAsB,WAAtB,sBAAsB,mBADT,MAAM;;iFACnB,sBAAsB;cADlC,UAAU;eAAC,EAAE,UAAU,EAAE,MAAM,EAAE","sourcesContent":["import { Injectable } from '@angular/core';\nimport { RealtimeSessionRuntime } from '@memberjunction/realtime-runtime';\nimport {\n LoadAssemblyAIRealtimeClient,\n LoadElevenLabsRealtimeClient,\n LoadElevenRealtimeClient,\n LoadGeminiRealtimeClient,\n LoadHuggingFaceRealtimeClient,\n LoadOpenAILiveClient,\n LoadOpenAIRealtimeClient,\n LoadxAIRealtimeClient,\n} from '@memberjunction/ai-realtime-client';\nimport { BrowserRealtimeMediaHost } from './browser-realtime-media-host';\n\n// Tree-shaking prevention: client drivers are resolved dynamically through the ClassFactory (by\n// the server-reported Provider key), so these static calls are what keep their @RegisterClass side\n// effects from being eliminated by the bundler.\n//\n// NOTE: the interactive-channel plugins (resolved dynamically from the `MJ: AI Agent Channels`\n// registry by ClientPluginClass key) get the same treatment, but their Load calls live in\n// `conversations.module.ts` — plugins carry Angular surface COMPONENTS, and this service stays\n// component-free.\nLoadOpenAIRealtimeClient();\nLoadOpenAILiveClient();\nLoadGeminiRealtimeClient();\nLoadElevenLabsRealtimeClient();\nLoadAssemblyAIRealtimeClient();\nLoadxAIRealtimeClient();\nLoadElevenRealtimeClient();\nLoadHuggingFaceRealtimeClient();\n\n/**\n * Angular host for MemberJunction's realtime co-agent sessions.\n *\n * All orchestration — mint, driver resolution, transcripts, tool relay, delegation narration,\n * channel lifecycle, usage relay, teardown — lives in\n * {@link RealtimeSessionRuntime} (`@memberjunction/realtime-runtime`), which is framework-agnostic\n * and shared with every other host, including the React Native app. This class supplies the three\n * things that are genuinely Angular/browser: the `@Injectable` shell that lets components inject\n * it, the browser's media host, and the page-lifecycle wiring that sends the recording's terminal\n * request when the tab is hidden or unloaded (#5294).\n *\n * Consumers are unaffected by that split — the injectable token, class name, and public surface\n * are unchanged. Types that used to be declared in this file (`RealtimeCaption`,\n * `RealtimeConnectionState`, `RealtimeSessionRunOptions`, …) now come from\n * `@memberjunction/realtime-runtime`; import them from there directly, since MJ does not\n * re-export across package boundaries.\n */\n@Injectable({ providedIn: 'root' })\nexport class RealtimeSessionService extends RealtimeSessionRuntime {\n constructor() {\n super(new BrowserRealtimeMediaHost());\n if (typeof window !== 'undefined' && typeof document !== 'undefined') {\n this.WireRecordingTerminalTriggers(window, document);\n }\n }\n\n /**\n * Sends the recording terminal (tail shard + counts, as a keepalive request) when the page is\n * going away: on `pagehide`, and when the page becomes hidden — the last event a mobile browser\n * reliably fires before it may discard a backgrounded tab without any unload event. Both handlers\n * only call the runtime's synchronous {@link RealtimeSessionRuntime.SendRecordingTerminal}, which\n * does no IndexedDB work and no encoding: there is no time for either while a page is unloading.\n * It does nothing when no call is recording, and repeating it is safe (a sent tail is sealed, so a\n * call that continues after the tab comes back sends its later shards at new indexes).\n *\n * There is deliberately no `beforeunload` prompt any more: shards already on the server plus the\n * terminal make closing the tab safe, and a `beforeunload` listener blocks the back/forward cache.\n *\n * The service is a root singleton, so these listeners live exactly as long as the app and are\n * never removed.\n *\n * @param page the page-lifecycle event target (`window`)\n * @param visibility the visibility source (`document`)\n */\n protected WireRecordingTerminalTriggers(page: PageHideEventTarget, visibility: VisibilityEventSource): void {\n page.addEventListener('pagehide', () => this.SendRecordingTerminal({ Final: true }));\n visibility.addEventListener('visibilitychange', () => {\n if (visibility.visibilityState === 'hidden') {\n // Not final: the user may come back and the call go on, so the server only stamps the\n // counts and assembles after its grace period instead of rewriting the recording now.\n this.SendRecordingTerminal({ Final: false });\n }\n });\n }\n}\n\n/** The slice of `window` the terminal wiring needs; `window` itself satisfies it. */\nexport interface PageHideEventTarget {\n // case-violation-ok-legacy-back-compat: mirrors the DOM EventTarget API so `window` itself satisfies this interface\n addEventListener(type: 'pagehide', listener: () => void): void;\n}\n\n/** The slice of `document` the terminal wiring needs; `document` itself satisfies it. */\nexport interface VisibilityEventSource {\n // case-violation-ok-legacy-back-compat: mirrors the DOM Document API so `document` itself satisfies this interface\n readonly visibilityState: DocumentVisibilityState;\n // case-violation-ok-legacy-back-compat: mirrors the DOM EventTarget API so `document` itself satisfies this interface\n addEventListener(type: 'visibilitychange', listener: () => void): void;\n}\n"]}
1
+ {"version":3,"file":"realtime-session.service.js","sourceRoot":"","sources":["../../../src/lib/services/realtime-session.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,sBAAsB,EAAE,MAAM,kCAAkC,CAAC;AAC1E,OAAO,EACH,4BAA4B,EAC5B,4BAA4B,EAC5B,wBAAwB,EACxB,wB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,CAAC;YACjD,CAAC;QACL,CAAC,CAAC,CAAC;IACP,CAAC;gHAxCQ,sBAAsB;gEAAtB,sBAAsB,WAAtB,sBAAsB,mBADT,MAAM;;iFACnB,sBAAsB;cADlC,UAAU;eAAC,EAAE,UAAU,EAAE,MAAM,EAAE","sourcesContent":["import { Injectable } from '@angular/core';\nimport { RealtimeSessionRuntime } from '@memberjunction/realtime-runtime';\nimport {\n LoadAssemblyAIRealtimeClient,\n LoadElevenLabsRealtimeClient,\n LoadElevenRealtimeClient,\n LoadGeminiRealtimeClient,\n LoadHuggingFaceRealtimeClient,\n LoadOpenAILiveClient,\n LoadOpenAIRealtimeClient,\n LoadxAIRealtimeClient,\n} from '@memberjunction/ai-realtime-client';\nimport { BrowserRealtimeMediaHost } from './browser-realtime-media-host';\n\n// Tree-shaking prevention: client drivers are resolved dynamically through the ClassFactory (by\n// the server-reported Provider key), so these static calls are what keep their @RegisterClass side\n// effects from being eliminated by the bundler.\n//\n// NOTE: the interactive-channel plugins (resolved dynamically from the `MJ: AI Agent Channels`\n// registry by ClientPluginClass key) get the same treatment, but their Load calls live in\n// `conversations.module.ts` — plugins carry Angular surface COMPONENTS, and this service stays\n// component-free.\nLoadOpenAIRealtimeClient();\nLoadOpenAILiveClient();\nLoadGeminiRealtimeClient();\nLoadElevenLabsRealtimeClient();\nLoadAssemblyAIRealtimeClient();\nLoadxAIRealtimeClient();\nLoadElevenRealtimeClient();\nLoadHuggingFaceRealtimeClient();\n\n/**\n * Angular host for MemberJunction's realtime co-agent sessions.\n *\n * All orchestration — mint, driver resolution, transcripts, tool relay, delegation narration,\n * channel lifecycle, usage relay, teardown — lives in\n * {@link RealtimeSessionRuntime} (`@memberjunction/realtime-runtime`), which is framework-agnostic\n * and shared with every other host, including the React Native app. This class supplies the three\n * things that are genuinely Angular/browser: the `@Injectable` shell that lets components inject\n * it, the browser's media host, and the page-lifecycle wiring that sends the recording's terminal\n * request when the tab is hidden or unloaded (#5294).\n *\n * Consumers are unaffected by that split — the injectable token, class name, and public surface\n * are unchanged. Types that used to be declared in this file (`RealtimeCaption`,\n * `RealtimeConnectionState`, `RealtimeSessionRunOptions`, …) now come from\n * `@memberjunction/realtime-runtime`; import them from there directly, since MJ does not\n * re-export across package boundaries.\n */\n@Injectable({ providedIn: 'root' })\nexport class RealtimeSessionService extends RealtimeSessionRuntime {\n constructor() {\n super(new BrowserRealtimeMediaHost());\n if (typeof window !== 'undefined' && typeof document !== 'undefined') {\n this.WireRecordingTerminalTriggers(window, document);\n }\n }\n\n /**\n * Sends the recording terminal (tail shard + counts, as a keepalive request) when the page is\n * going away: on `pagehide`, and when the page becomes hidden — the last event a mobile browser\n * reliably fires before it may discard a backgrounded tab without any unload event. Both handlers\n * only call the runtime's synchronous {@link RealtimeSessionRuntime.SendRecordingTerminal} (`pagehide`\n * through {@link RealtimeSessionRuntime.SendPageHideSignals}), which does no IndexedDB work and no\n * encoding: there is no time for either while a page is unloading.\n * It does nothing when no call is recording, and repeating it is safe (a sent tail is sealed, so a\n * call that continues after the tab comes back sends its later shards at new indexes).\n *\n * `pagehide` goes through {@link RealtimeSessionRuntime.SendPageHideSignals}, which also closes the\n * server session with a `keepalive` request when the page is going away for good (not entering the\n * back/forward cache); a hidden tab never closes it, the user may come back.\n *\n * There is deliberately no `beforeunload` prompt any more: shards already on the server plus the\n * terminal make closing the tab safe, and a `beforeunload` listener blocks the back/forward cache.\n *\n * The service is a root singleton, so these listeners live exactly as long as the app and are\n * never removed.\n *\n * @param page the page-lifecycle event target (`window`)\n * @param visibility the visibility source (`document`)\n */\n protected WireRecordingTerminalTriggers(page: PageHideEventTarget, visibility: VisibilityEventSource): void {\n page.addEventListener('pagehide', (event) => this.SendPageHideSignals({ Persisted: event.persisted }));\n visibility.addEventListener('visibilitychange', () => {\n if (visibility.visibilityState === 'hidden') {\n // Not final: the user may come back and the call go on, so the server only stamps the\n // counts and assembles after its grace period instead of rewriting the recording now.\n this.SendRecordingTerminal({ Final: false });\n }\n });\n }\n}\n\n/** The slice of `window` the terminal wiring needs; `window` itself satisfies it. */\nexport interface PageHideEventTarget {\n // case-violation-ok-legacy-back-compat: mirrors the DOM EventTarget API so `window` itself satisfies this interface\n addEventListener(type: 'pagehide', listener: (event: { readonly persisted: boolean }) => void): void;\n}\n\n/** The slice of `document` the terminal wiring needs; `document` itself satisfies it. */\nexport interface VisibilityEventSource {\n // case-violation-ok-legacy-back-compat: mirrors the DOM Document API so `document` itself satisfies this interface\n readonly visibilityState: DocumentVisibilityState;\n // case-violation-ok-legacy-back-compat: mirrors the DOM EventTarget API so `document` itself satisfies this interface\n addEventListener(type: 'visibilitychange', listener: () => void): void;\n}\n"]}
@@ -280,7 +280,7 @@ export class SearchService {
280
280
  }, currentUser);
281
281
  if (collResult.Success && collResult.Results && collResult.Results.length > 0) {
282
282
  const collArtifact = collResult.Results[0];
283
- searchResults.push(this.mapArtifactToSearchResult(artifact, query, collArtifact.CollectionID, collArtifact.Collection));
283
+ searchResults.push(this.mapArtifactToSearchResult(artifact, query, collArtifact.CollectionID, collArtifact.Collection ?? undefined));
284
284
  }
285
285
  else {
286
286
  // No collection association